使用制作 Key 读取已发布模板目录

This commit is contained in:
WuYongJie 2026-11-30 20:36:33 +08:00
parent fcfccb5c4f
commit 37e9761c07
6 changed files with 152 additions and 8 deletions

View File

@ -7,6 +7,8 @@ import { normalizeTemplateMapping } from './template-mapping.mjs';
import { digest } from './store.mjs';
import { EnterpriseContext } from './enterprise-context.mjs';
import {resourceRequest,resourceSnapshot} from './enterprise-resource-map.mjs';
import {nativeKnowledgeFetch} from './native-knowledge-http.mjs';
import origins from './enterprise-knowledge-origins.json' with {type:'json'};
async function waitForQuota(read, task) {
const networkRetryMs=task.retryPinnedRead?[2000,5000,12000]:[];
@ -336,7 +338,7 @@ export class EnterpriseTemplates {
export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
const {templateId,projectDir,cache} = input;
const skills = await openXiaoyiSkills({dir:projectDir,xiaoyiCache:cache,xiaoyiProgress:onProgress},templateId,signal,undefined,fetch);
const skills = await openXiaoyiSkills({dir:projectDir,xiaoyiCache:cache,xiaoyiProgress:onProgress},templateId,signal,undefined,fetch,input.knowledgeVersion,input.metadataOnly === true);
const {manifest,root} = skills.snapshot;
if (!manifest.bindings || !Object.keys(manifest.bindings).length) throw Error('小壹清单缺少组件绑定');
const files = new Map(manifest.files.map(file => [file.path,file]));
@ -378,6 +380,7 @@ export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
const original = pack.enterprise.components[component].originals[0];
Object.assign(pack.enterprise,{component,sourceKind:'xiaoyi-release',snapshotVersion:manifest.version,
originalSha256:original.sha256,canvas:original.canvas,
resourceSetId:templateId,componentId:component,
mappingPath:path.join(root,binding.mapping),inventoryPath:path.join(root,binding.inventory)});
pack.xiaoyi = skills.productionBinding;
packs[component] = pack;
@ -386,8 +389,83 @@ export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
}
const clients = new Map();
export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch,onProgress} = {}) {
let origin = origins[0];
if (process.env.PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE) {
origin = await fs.readFile(process.env.PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE, 'utf8')
.then(JSON.parse, error => {
if (error.code !== 'ENOENT') throw error;
return origins[0];
});
}
let response;
try {
response = await fetch(new URL('/api/xiaoyi/v1/templates', origin), {method:'GET',signal});
} catch (error) {
if (error.category === 'credential') throw Error('请先在小壹设置中填写并保存制作 Key', {cause:error});
throw error;
}
if (!response.ok) {
const messages = {401:'制作 Key 已失效或填写有误,请在小壹设置中更换',403:'制作 Key 无权读取模板目录,请联系知识库管理员'};
throw Object.assign(Error(messages[response.status] ?? '模板目录读取失败(HTTP ' + response.status + ')'),{status:response.status});
}
const data = await response.json();
if (!Array.isArray(data.items)) throw Error('小壹模板目录格式无效');
const rows = data.items;
const brandId = name => 'ekb:brand:' + name;
const categoryId = name => 'ekb:category:' + name;
if (input.action === 'choices' || input.action === 'brand') {
const brands = new Map();
for (const item of rows) {
if (!item.brand || !item.category) continue;
if (!brands.has(item.brand)) brands.set(item.brand,{id:brandId(item.brand),name:item.brand,ready:true,templateCount:0,categories:[],profile:{name:item.brand,tone:'',visualRules:{}}});
const brand = brands.get(item.brand);
let category = brand.categories.find(row => row.name === item.category);
if (!category) {
category = {id:categoryId(item.category),name:item.category,brandId:brand.id,ready:true,templateCount:0};
brand.categories.push(category);
}
brand.templateCount++;
category.templateCount++;
}
const selected = input.brandName || input.brandId?.replace(/^ekb:brand:/,'');
if (input.action === 'brand') {
const brand = brands.get(selected);
if (!brand) throw Error('当前制作模板目录没有所选品牌');
return {brand};
}
return {catalog:{kind:input.kind,items:input.kind === 'brands' ? [...brands.values()] : brands.get(selected)?.categories ?? []}};
}
const entries = rows.filter(item => item.brand === input.brandName && item.category === input.categoryName);
if (input.action === 'catalog') {
const query = input.query?.trim().toLocaleLowerCase() ?? '';
return {items:entries.filter(item => !query || (item.name + ' ' + item.templateId).toLocaleLowerCase().includes(query))
.map(item => ({id:item.templateId,key:item.templateId,name:item.name,brandId:input.brandId,categoryId:input.categoryId}))};
}
const item = entries.find(row => row.templateId === input.resourceSetId);
if (!item) throw Error('所选模板已不在当前发布目录,请重新选择');
const labels = {detail:'详情页',main_images:'主图',sku_images:'SKU'};
const components = item.components.map(part => ({
id:part.id,name:labels[part.id] ?? part.id,kind:part.id,status:'available',issues:[],previews:[]
}));
if (input.action === 'resource-set') return {items:components};
const component = components.find(part => part.id === input.componentId);
if (!component) throw Error('当前模板没有所选组件');
const projectDir = path.join(input.root,'catalog',digest([item.templateId,item.version]));
const {packs} = await xiaoyiPacks({
templateId:item.templateId,projectDir,cache:path.join(input.root,'blobs'),
name:item.name,brandId:input.brandId,categoryId:input.categoryId,
knowledgeVersion:item.knowledgeVersion,metadataOnly:true,
},{signal,fetch,onProgress});
if (!packs[component.id]) throw Error('制作包缺少所选组件,请联系知识库管理员');
return {items:[{...component,pack:packs[component.id]}]};
}
export async function templateRequest(input,options) {
if (input.action === 'xiaoyi-pack') return xiaoyiPacks(input,options);
if (['choices','brand','catalog','resource-set','resource-component'].includes(input.action)) {
return xiaoyiCatalog(input,options);
}
if (typeof input.root !== 'string' || !path.isAbsolute(input.root)) throw Error('模板缓存目录无效');
let client=clients.get(input.root);
if (!client) {client=new EnterpriseTemplates(input.root);clients.set(input.root,client);}

View File

@ -189,7 +189,7 @@ export async function acquireXiaoyiRelease(options) {
}
}
let confirmedAssetRelease = false;
for (const item of manifest.assets) {
for (const item of options.metadataOnly ? [] : manifest.assets) {
const file = fileAt(root, item.path);
if (await hasSize(file, item)) continue;
if (!/^[a-f0-9]{64}$/.test(item.sha256)) throw Error('小壹资产摘要无效');
@ -227,7 +227,7 @@ export async function acquireXiaoyiRelease(options) {
}
export async function openXiaoyiSkills(store, templateId, signal, finishedGoal, fetch = nativeKnowledgeFetch, pinnedKnowledgeVersion) {
export async function openXiaoyiSkills(store, templateId, signal, finishedGoal, fetch = nativeKnowledgeFetch, pinnedKnowledgeVersion, metadataOnly = false) {
const directory = path.join(store.dir, 'xiaoyi-release', digest(templateId).slice(0, 24));
await fs.mkdir(directory, {recursive:true});
const unlock = await lockfile.lock(directory);
@ -251,7 +251,7 @@ export async function openXiaoyiSkills(store, templateId, signal, finishedGoal,
});
}
const {manifest, root, productionProfiles} = await acquireXiaoyiRelease({
templateId, directory, cache:store.xiaoyiCache ?? path.join(path.dirname(store.dir), 'xiaoyi-blobs'), signal, pinnedKnowledgeVersion, onProgress:store.xiaoyiProgress,
templateId, directory, cache:store.xiaoyiCache ?? path.join(path.dirname(store.dir), 'xiaoyi-blobs'), signal, pinnedKnowledgeVersion, metadataOnly, onProgress:store.xiaoyiProgress,
fetch:(route, init) => fetch(new URL(route, origin), init),
});
const entry = fileAt(root, manifest.entrypoint);

View File

@ -1,4 +1,4 @@
import {xiaoyiPacks} from '../src/enterprise-templates.mjs';
import {xiaoyiPacks,templateRequest} from '../src/enterprise-templates.mjs';
import {createServer} from 'node:http';
import {once} from 'node:events';
import {xiaoyiFixture} from './xiaoyi-fixture.mjs';
@ -220,3 +220,46 @@ test('first production prepares the component from only manifest bindings and re
assert.deepEqual(pack.xiaoyi.productionProfiles.detail.pages,{D01:{}});
assert.ok(requests.every(([route])=>route.startsWith('/api/xiaoyi/v1/')));
});
test('production Key browses brands, categories, templates and component mappings without downloading originals', async t => {
const {options,requests} = await fixture(t,{withBindings:true});
const root = path.join(options.directory,'catalog-root');
const catalog = {items:[{templateId:'CHAIR',name:'Fixture chair',brand:'Fixture',category:'Chair',
version:'v1',knowledgeVersion:'CHAIR@v1',components:[{id:'detail'}]}]};
const fetch = async (url,init) => url.pathname === '/api/xiaoyi/v1/templates'
? Response.json(catalog) : options.fetch(url.pathname,init);
const common = {root,brandId:'ekb:brand:Fixture',brandName:'Fixture',
categoryId:'ekb:category:Chair',categoryName:'Chair'};
const brands = await templateRequest({...common,action:'choices',kind:'brands'},{fetch});
assert.equal(brands.catalog.items[0].name,'Fixture');
const categories = await templateRequest({...common,action:'choices',kind:'categories'},{fetch});
assert.equal(categories.catalog.items[0].name,'Chair');
const list = await templateRequest({...common,action:'catalog',query:'CHAIR'},{fetch});
assert.equal(list.items[0].id,'CHAIR');
const set = await templateRequest({...common,action:'resource-set',resourceSetId:'CHAIR'},{fetch});
assert.equal(set.items[0].id,'detail');
const part = await templateRequest({...common,action:'resource-component',resourceSetId:'CHAIR',componentId:'detail'},{fetch});
const pack = part.items[0].pack;
assert.equal(pack.enterprise.sourceKind,'xiaoyi-release');
assert.equal(pack.enterprise.resourceSetId,'CHAIR');
assert.equal(pack.enterprise.componentId,'detail');
assert.equal(pack.outputs[0].slots[0].fieldId,'D01-I01');
assert.equal(requests.some(([route])=>route.includes('/blobs/')),false);
assert.equal(requests.some(([route])=>route.endsWith('/bundle')),true);
const cachedProject = path.join(root,'catalog',createHash('sha256').update(JSON.stringify(['CHAIR','v1'])).digest('hex'));
const full = await xiaoyiPacks({templateId:'CHAIR',projectDir:cachedProject,cache:path.join(root,'blobs'),
name:'Fixture chair',brandId:common.brandId,categoryId:common.categoryId,knowledgeVersion:'CHAIR@v1'},{fetch});
const withoutKnowledge = value => {const copy = structuredClone(value); delete copy.xiaoyi; return copy;};
assert.deepEqual(withoutKnowledge(full.packs.detail),withoutKnowledge(pack));
assert.equal(requests.filter(([route])=>route.includes('/blobs/')).length,1);
});
test('production catalog reports rejected keys without falling through to generic MCP', async t => {
const {options} = await fixture(t);
await assert.rejects(templateRequest({root:options.directory,action:'choices',kind:'brands'},
{fetch:async url => {
assert.equal(url.pathname,'/api/xiaoyi/v1/templates');
return Response.json({code:'authentication_required'},{status:401});
}}),/制作 Key 已失效/);
});

View File

@ -4605,9 +4605,14 @@ impl Backend {
let project = self.locations.get(&doc).ok_or("项目身份尚未绑定")?;
let session = dir.join("agent").join(self.scope()).join(project).join("conversation-v1");
let template_id = input["template"]["id"].as_str().ok_or("企业模板编号缺失")?;
let result = self.enterprise_template_request(json!({"action":"xiaoyi-pack","templateId":template_id,
let mut request = json!({"action":"xiaoyi-pack","templateId":template_id,
"name":input["template"]["name"],"brandId":brand,"categoryId":category,
"projectDir":session,"cache":self.dir().join("xiaoyi-blobs")}))?;
"projectDir":session,"cache":self.dir().join("xiaoyi-blobs")});
if input["template"]["enterprise"]["sourceKind"] == "xiaoyi-release" {
let version = input["template"]["version"].as_str().ok_or("模板版本缺失")?;
request["knowledgeVersion"] = json!(format!("{template_id}@{version}"));
}
let result = self.enterprise_template_request(request)?;
let mut packs = result["packs"].as_object().cloned().ok_or("小壹清单没有可用组件")?;
for (component, pack) in &mut packs {
production_profile::add_image_fields(pack, component)?;

View File

@ -238,7 +238,7 @@ impl Route {
(Some("GET"), path)
if input["body"].is_null()
&& regex::Regex::new(
r"\A/api/xiaoyi/v1/(?:templates/[A-Za-z0-9][A-Za-z0-9_.-]*/(?:current|releases/[A-Za-z0-9][A-Za-z0-9_.-]*/(?:manifest|bundle))|blobs/[a-f0-9]{64})\z"
r"\A/api/xiaoyi/v1/(?:templates|templates/[A-Za-z0-9][A-Za-z0-9_.-]*/(?:current|releases/[A-Za-z0-9][A-Za-z0-9_.-]*/(?:manifest|bundle))|blobs/[a-f0-9]{64})\z"
).map_err(|_| INVALID)?.is_match(path) =>
{
if allows_xiaoyi_origin(origin) { Ok(Self::Xiaoyi) } else { Err(XIAOYI_ORIGIN_REQUIRED.into()) }
@ -556,6 +556,7 @@ mod tests {
for origin in origins {
for (method, path, body, route) in [
("GET", "/healthz", Value::Null, Route::Health),
("GET", "/api/xiaoyi/v1/templates", Value::Null, Route::Xiaoyi),
("GET", "/api/xiaoyi/v1/templates/SFY-CHAIR-001/current", Value::Null, Route::Xiaoyi),
("GET", "/api/xiaoyi/v1/templates/SFY-CHAIR-001/releases/2026-11-28.1/bundle", Value::Null, Route::Xiaoyi),
("POST", "/mcp", json!("{}"), Route::Mcp),

View File

@ -175,6 +175,23 @@ impl Backend {
}
pub(super) fn selected_template_pack(&self, selected: &Value, brand: &str, category: &str) -> R<Value> {
if !selected["enterprise"].is_object() { return self.template_pack(brand, category, false); }
if selected["enterprise"]["sourceKind"] == "xiaoyi-release" {
let id = selected["id"].as_str().ok_or("模板编号缺失")?;
let version = selected["version"].as_str().ok_or("模板版本缺失")?;
let component = selected["enterprise"]["component"].as_str().ok_or("模板组件缺失")?;
let root = self.dir().join("enterprise-templates");
let project_dir = root.join("catalog").join(hash(&json!([id, version]).to_string()));
let result = self.enterprise_template_request(json!({"action":"xiaoyi-pack","templateId":id,
"name":selected["name"],"brandId":brand,"categoryId":category,"projectDir":project_dir,
"cache":root.join("blobs"),"knowledgeVersion":format!("{id}@{version}")}))?;
let mut pack = result["packs"][component].clone();
pack["contentHash"] = json!(template_slots::pack_hash(&pack)?);
matching_pack(&pack, brand, category)?;
if pack["contentHash"] != selected["contentHash"] {
return Err("所选模板内容与固定版本不一致,请重新选择".into());
}
return Ok(pack);
}
let mut request = selected["enterprise"].clone();
request["action"] = json!("pack");
request["brandId"] = json!(brand);