From 795f1ea3ab0a0f3802b21f0dd0f254bdbe573bde Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Wed, 25 Nov 2026 22:57:54 +0800 Subject: [PATCH] feat(xiaoyi): load pinned enterprise skills in Pi production --- apps/detail-agent-pi/src/agent.mjs | 96 +++++++++++++------ .../src/enterprise-context.mjs | 52 ++++++++-- .../src/enterprise-skill-resources.mjs | 83 ++++++++++++++++ apps/detail-agent-pi/src/production-goal.mjs | 15 +-- .../src/production-knowledge.mjs | 4 +- apps/detail-agent-pi/src/whole-detail.mjs | 42 ++++---- .../test/enterprise-context.test.mjs | 3 + apps/detail-agent-pi/test/pi.test.mjs | 88 ++++++++++++++++- docs/development/xiaoyi/implementation.md | 14 +++ 9 files changed, 331 insertions(+), 66 deletions(-) create mode 100644 apps/detail-agent-pi/src/enterprise-skill-resources.mjs diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index 0ddb35d0..7a7b049d 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -12,7 +12,7 @@ import { Type } from '@sinclair/typebox'; import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal, mayContinueProductionGoal, piGoalState, productionObjective } from './production-goal.mjs'; import { Agent, runToolCall } from '@earendil-works/pi-agent-core'; -import { createAgentSession, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent'; +import { createAgentSession, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent'; import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, normalizeContext, createAssistantMessageEventStream, parseStreamingJson } from '@earendil-works/pi-ai/compat'; import { atomic, digest } from './store.mjs'; import { jsonToolContext, decodeToolReply } from './json-tool-codec.mjs'; @@ -24,6 +24,7 @@ import { taskFor } from './rule-context.mjs'; import { productContext } from './project-context.mjs'; import { imageProgressQuestion, readImageProgress, workflowContext, workflowResult } from './workflow-context.mjs'; import { EnterpriseContext } from './enterprise-context.mjs'; +import { enterpriseSkillReadTool, openEnterpriseSkills } from './enterprise-skill-resources.mjs'; import { responseUsage } from './usage.mjs'; import { contextSnapshot, exceedsModelBudget, modelCapacity, contextTextLength } from './context-usage.mjs'; import { activityScope, activitySummary, toolActivity } from './activity-event.mjs'; @@ -61,6 +62,7 @@ references是用户提交时冻结的本轮引用;component为pixelMask或vect 不要声称尚未执行的修改已完成。工具失败要说明。未知模型请求只读查询,不要要求重试或重新生成。`; const PRODUCTION_SYSTEM = `你是由壹点详情页的制作 Agent 小壹。用户已授权整套制作,productionGoal 标明你当前负责的输出和款式。 +先用 read 加载已提供且适用于当前任务的企业 Skill。制作软件已选 PhotoCraft。按正文及引用,使用当前画布工具写入、回填、复核和交付。 根据已确认的产品事实、品牌和模板定好整页卖点、逐屏图文关系和统一调性。自主选择当前输出内的工具、顺序、并行任务和返工方案。逐屏初稿写入画布后,工具会派发该屏有策划依据的图位。其它图位和返工按实际问题交给子代理。局部等待时继续处理当前输出里能做的图位和文案。 根据具体退回原因修正有问题的部分。图像符合商品结构和图位要求、只有某句缺少画面依据时,依据文案修订回执改写对应格并复核原候选。逐屏复核实际画面、图文对应、裁切、可读性和标注。符合要求后提交当前输出,客户端根据实际导出回执与仍可推进的输出安排后续。 文案是给买家读的。标题说清这一屏的重点,短句说清买家能看到什么、怎么使用。拍摄说明、验图用语和部件清单只用于制作。逐屏连读标题和正文,改掉重复词、拼接的半句话及样稿里的卖点。 @@ -101,6 +103,7 @@ function toolsFor(host) { ...(host.productionGoal ? productionTools.map(([name, description, schema]) => make(name, description, schema, (args,signal)=>callProductionTool(host,name,args,signal), name==='read_output_screen'?result=>result:plain)) : []), + ...(host.productionGoal ? [enterpriseSkillReadTool(host.store, () => host.productionSkills, 'main')] : []), make('context_read', '按需读取当前项目规则。未指定topic返回当前任务必需规则;brand为品牌细节、template为模板模块、sources为来源。普通问答涉及企业知识库或模板规则时,先用此工具取依据。', Type.Object({ topic: Type.Optional(Type.Union([Type.Literal('brand'), Type.Literal('template'), Type.Literal('sources')])) }, { additionalProperties: false }), args => host.modelContext(args, {loadKnowledge:true})), make('memory_set', '持久记录用户明确确认的事实/决定;evidence必须是用户消息中的原话。', Type.Object({ key: string(64), value: string(1000), evidence: Type.String({ minLength: 4, maxLength: 1000 }) }), args => host.store.remember(args, host.session.messages)), make('memory_search', '查找本项目完整历史,包括压缩前的原始记录。', Type.Object({ query: Type.String({ minLength: 1, maxLength: 200 }) }), ({ query }) => host.store.search(query, host.manager)), @@ -422,8 +425,9 @@ export class DetailPiAgent { if (liveCanvas) injected.currentCanvasAuthority = { run: liveCanvas.run, conversationActive: liveCanvas.conversationActive, allowed: liveCanvas.allowed, writeBlocked: liveCanvas.writeBlocked, revision: liveCanvas.revision, documentId: liveCanvas.context?.id, appliesTo: 'current-user-turn', canvas: liveCanvas.context && { name: liveCanvas.context.name, width: liveCanvas.context.width, height: liveCanvas.context.height, totalLayers: liveCanvas.context.totalLayers, layersTruncated: liveCanvas.context.layersTruncated, subject: liveCanvas.context.subject, selected: liveCanvas.context.selected, references: frozenReferences(liveCanvas.context), liveSelected: liveCanvas.context.liveSelected, activeLayerId: liveCanvas.context.activeLayerId } }; + const knowledge=host.productionSkills?.knowledge??host.knowledgeContext; await store.appendEvent({ type: 'context_injected', bindingHash: store.hash, messageCount: context.messages.length, memoryHash: digest(injected.confirmedMemory), - constraints:injected.constraints,knowledgeSources:host.knowledgeContext?[...host.knowledgeContext.skills,...host.knowledgeContext.rules].map(({fileId,revision,kind})=>({fileId,revision,kind})):[] }); + constraints:injected.constraints,knowledgeSources:knowledge?[...knowledge.skills,...knowledge.rules].map(({fileId,revision,kind})=>({fileId,revision,kind})):[] }); const contextual = host.projectModelContext(context, injected); const encoded = protocolMode === 'structured-json' && !host.compacting; const wireContext = encoded ? jsonToolContext(contextual) : contextual; @@ -605,7 +609,8 @@ export class DetailPiAgent { }); const loader = { getExtensions: () => extensions, - getSkills: () => extensions.resourceLoader.getSkills(), getPrompts: () => ({ prompts: [], diagnostics: [] }), getThemes: () => ({ themes: [], diagnostics: [] }), + getSkills: () => host.productionSkills?.resource ?? extensions.resourceLoader.getSkills(), + getPrompts: () => ({ prompts: [], diagnostics: [] }), getThemes: () => ({ themes: [], diagnostics: [] }), getAgentsFiles: () => ({ agentsFiles: [] }), getSystemPrompt: () => productionGoal ? PRODUCTION_SYSTEM : SYSTEM, getSystemPromptSource: () => undefined, getAppendSystemPrompt: () => [], getAppendSystemPromptSources: () => [], extendResources() {}, async reload() {}, }; @@ -616,6 +621,10 @@ export class DetailPiAgent { settingsManager: SettingsManager.inMemory({ compaction: { enabled: false, keepRecentTokens: 2048, reserveTokens: 4096 }, retry: { enabled: false }, summarization: { enabled: false } }), sessionManager: host.manager, }); host.runDetailAgent = async (slotId, systemPrompt, prompt, tools, images, requestScope=slotId) => { + if (host.productionSkills) { + systemPrompt += formatSkillsForPrompt(host.productionSkills.resource.skills); + tools = [...tools,enterpriseSkillReadTool(store, () => host.productionSkills, 'worker', requestScope)]; + } const model = runtime.getModel('jiansun-native-98k', info.model.id); let scoped = broker?.forDetailSlot?.(requestScope); if (!model || !scoped && !transport?.stream) throw Error('详情页模型连接未就绪'); @@ -868,7 +877,8 @@ export class DetailPiAgent { const epoch = this.turnEpoch; if (this.canvasNotificationsDetached) throw Error('当前项目已切换,未读取其他项目工作流'); if (this.workflowBindingChanged) throw Error('品牌或品类已变化,请重新开始一轮对话以加载对应规则;未继续执行当前回合'); - const latest = workflowContext(await this.canvas.workflowRead(args), this.productIdentity); + const snapshot = await this.canvas.workflowRead(args); + const latest = workflowContext(snapshot, this.productIdentity); if (this.turnEpoch !== epoch) throw Error('原回合已结束,旧工作流读取不更新当前回合'); if (latest.workflow.available) { const identity = { brandId: latest.product.product.brandId, categoryId: latest.product.product.categoryId }; @@ -880,6 +890,7 @@ export class DetailPiAgent { } this.currentWorkflow = latest.workflow; this.productEvidence = latest.product; + if (this.productionGoal && args.section === 'overview') this.productionTemplate = snapshot.template; if (this.task && this.task !== 'chat' && !this.compacting && !this.wholeDetailActive) this.knowledgeContext = await this.readEnterpriseRules(); return latest.workflow; } @@ -894,6 +905,12 @@ export class DetailPiAgent { } async modelContext(options = {}, {loadKnowledge = false} = {}) { const value=await this.store.modelContext({task:this.task || 'chat',workflow:this.currentWorkflow,canvas:this.currentCanvas,...options}); + if (this.productionSkills && loadKnowledge) { + const {knowledge,documents}=this.productionSkills; + value.enterpriseKnowledge={execution:knowledge.execution,sources:[...documents.values()]}; + value.snapshot.rules=value.snapshot.rules.filter(rule=>/原稿画布|源模板约束/.test(rule)); + return value; + } const knowledge = this.knowledgeContext ?? (loadKnowledge ? await this.readEnterpriseRules() : null); if (knowledge) { value.enterpriseKnowledge=knowledge; @@ -1019,8 +1036,6 @@ export class DetailPiAgent { this.goalStageResult=null; this.goalPendingOriginal=undefined; this.nextGoalRetryOf=undefined; - this.goalProgressSnapshot=undefined; - this.goalStalledRounds=0; const originalGoal = this.goalRequestScope && latest.pending?.find(request => request.detailSlot === this.goalRequestScope); if (originalGoal) { const recovered = await this.recoverTurn(originalGoal.id, {executeReadOnly:false}); @@ -1105,6 +1120,14 @@ export class DetailPiAgent { } try { if (typeof this.canvas?.workflowRead === 'function') await this.readWorkflow({ section: 'overview' }); + if (this.productionGoal && this.productionTemplate?.enterprise) { + const template=this.productionTemplate; + const {brandName,categoryName}=this.productEvidence.product; + const selection={brandName,categoryName,templateId:template.id,releaseId:template.version, + resourceSetId:template.resourceSetId,outputId:this.productionGoal.outputId,runDeadline:this.productionGoal.deadline}; + this.productionSkills=await openEnterpriseSkills(this.store,selection,pins=>this.loadWholeDetailKnowledge(selection,undefined,false,pins)); + this.session.setActiveToolsByName([...new Set([...this.session.getActiveToolNames(),'read'])]); + } if (!goalContinuation) await this.store.recordUserEvidence(text); const running = this.productionGoal ? runPiProductionGoal(this, prompt, goalContinuation) @@ -1185,29 +1208,17 @@ export class DetailPiAgent { try { return await runWholeDetail(this,this.runDetailAgent,async plan=>{ if(!production&&!plan.template.enterprise)return null; - this.enterpriseContext??=new EnterpriseContext(this.store); const brief=plan.productEvidence?.brief; - return this.enterpriseContext.load({task:production?'production':'image',outputId,brandName:brief?.brandName,categoryName:brief?.categoryName, - templateId:plan.template.id,releaseId:plan.template.version,resourceSetId:plan.template.resourceSetId,turn:this.canvas.run}, - {deferVisual:!!drive,read:async read=>{ - for(;;){ - signal?.throwIfAborted(); - const state=await this.canvas.read(); - if(state.conversationActive===false||state.writeBlocked)throw Error('资料读取已取消,已完成图位保留'); - try{return await read();} - catch(error){ - if(error.status!==429||!(error.retryAfterSeconds>0))throw error; - const seconds=Math.ceil(error.retryAfterSeconds); - await this.canvas.delta('知识库访问限流,约 '+seconds+' 秒后继续',undefined,production?{heading:'等待知识库响应'}:undefined); - const until=Date.now()+seconds*1000; - while(Date.now(){ if(!await this.store.ownsRequest(id))return null; @@ -1229,6 +1240,35 @@ export class DetailPiAgent { } } + async loadWholeDetailKnowledge(selection, signal, deferVisual=false, pins) { + this.enterpriseContext??=new EnterpriseContext(this.store); + const requireCurrent = async () => { + signal?.throwIfAborted(); + if (this.productionGoal?.deadline * 1000 <= Date.now()) throw Error('整套制作已达到时限,保留当前结果'); + const state=await this.canvas.read(); + if (state.conversationActive===false||state.writeBlocked) throw Error('资料读取已取消,已完成图位保留'); + }; + return this.enterpriseContext.load({task:'production',...selection,turn:this.canvas.run}, { + deferVisual,signal,pins,read:async read=>{ + for(;;){ + await requireCurrent(); + try { return await read(); } + catch(error){ + if(error.status!==429||!(error.retryAfterSeconds>0))throw error; + const seconds=Math.ceil(error.retryAfterSeconds); + const notice=selection.task!=='image'?{heading:'等待知识库响应'}:undefined; + await this.canvas.delta('知识库访问限流,约 '+seconds+' 秒后继续',undefined,notice); + const until=Date.now()+seconds*1000; + while(Date.now() this.compactTurn()); } async compactTurn({ preserveBudget = false } = {}) { const pending = this.broker ? (await this.broker.info()).pending : []; diff --git a/apps/detail-agent-pi/src/enterprise-context.mjs b/apps/detail-agent-pi/src/enterprise-context.mjs index a0de07f4..dccb6b24 100644 --- a/apps/detail-agent-pi/src/enterprise-context.mjs +++ b/apps/detail-agent-pi/src/enterprise-context.mjs @@ -12,10 +12,10 @@ function links(document) { .map(([,label,target]) => ({label, target:path.posix.normalize(path.posix.dirname(document.path)+'/'+target)})); } -/** Task knowledge is read through the standard service, never installed or executed. */ +/** Resolve production resources through the authorized knowledge service. */ export class EnterpriseContext { constructor(store, client = new EnterpriseKnowledge({store})) { this.store=store; this.client=client; } - async load({task,brandName,categoryName,templateId,releaseId,resourceSetId,turn,outputId}, {signal, read = execute => execute(), deferVisual = false} = {}) { + async load({task,brandName,categoryName,templateId,releaseId,resourceSetId,turn,outputId}, {signal, read = execute => execute(), deferVisual = false, pins} = {}) { if (!tasks[task] && task!=='production') return null; const key=JSON.stringify([task,brandName,categoryName,templateId,releaseId,resourceSetId,turn,outputId,deferVisual]); if (this.key===key) return this.value; @@ -23,7 +23,14 @@ export class EnterpriseContext { const directory=navigation.navigation?.find(item=>item.name==='Skills')?.path; if (task==='production') { const identity={task,brandName,categoryName,templateId,releaseId,resourceSetId}; - const options={signal,read,deferVisual}; + const options={signal,read,deferVisual,pins}; + if (resourceSetId) { + const published=await this.declaredGuides(identity,options); + if (published) { + await this.addNativeSkill(directory,published,options); + return this.commit(key,published); + } + } const value=await this.imageContext(directory,identity,options); const marketing=await this.specificDocument(directory,directory+'/产品营销文案/SKILL.md','skill',options); value.skills.push(marketing); @@ -37,6 +44,7 @@ export class EnterpriseContext { if(outputId==='main_images') rules.push([general+'02-视觉与审稿/04-电商主图制作.md','output']); if(outputId==='sku_images') rules.push([general+'02-视觉与审稿/05-SKU内容与图片.md','output']); for(const [target,kind] of rules) value.rules.push(await this.specificDocument(directory,target,kind,options)); + await this.addNativeSkill(directory,value,options); return this.commit(key,value); } if (task === 'image') { @@ -94,7 +102,26 @@ export class EnterpriseContext { return this.commit(key,value); } - async declaredGuides(identity,{signal,read}) { + async addNativeSkill(directory, knowledge, options) { + const guide=knowledge.rules.find(rule=>rule.kind==='template-reference'); + if (!guide) return; + const text=guide.text??await guide.loadText(); + const entry=links({...guide,text}).find(link=>/PhotoCraft/i.test(link.label)&&link.target.endsWith('/SKILL.md')); + if (!entry) return; + let skill=knowledge.skills.find(skill=>skill.path===entry.target); + if (!skill) { + skill=await this.specificDocument(directory,entry.target,'skill',options); + knowledge.skills.push(skill); + } + const prefix=path.posix.dirname(entry.target)+'/references/'; + const references=new Set(links(skill).filter(({target})=>target.startsWith(prefix)).map(({target})=>target)); + for (const target of references) { + if (knowledge.rules.some(rule=>rule.path===target)) continue; + knowledge.rules.push(await this.specificDocument(directory,target,'native-reference',options)); + } + } + + async declaredGuides(identity,{signal,read,pins}) { const set=(await read(()=>this.client.call('get_resource_set',{resourceSetId:identity.resourceSetId},{signal}))).result; if(set.resourceSet.brand!==identity.brandName||set.resourceSet.category!==identity.categoryName) throw Error('创作规则不属于所选品牌或品类'); const component=set.components.find(c=>c.id==='visual_guides'); @@ -102,19 +129,26 @@ export class EnterpriseContext { if(component.status!=='available')throw Error('所选模板的生图及验图规则尚有缺项'); const skills=[],rules=[]; for (const asset of component.assets.filter(a=>a.role==='guide'&&a.required)) { - if(asset.status!=='available')throw Error('无法读取必需规则:'+asset.file.name); const {fileId,revision,path:source}=asset.file; const kind=asset.file.name==='SKILL.md'?'skill':asset.id; + const target=kind==='skill'?skills:rules; + const pinned=pins?.get(source); + if (pinned) { + target.push({...pinned,kind}); + continue; + } + if(asset.status!=='available')throw Error('无法读取必需规则:'+asset.file.name); const {result}=await this.client.readDocument(fileId,revision,{signal},read); - (kind==='skill'?skills:rules).push({fileId,revision,path:source,kind,pages:result.pages,text:result.text}); + target.push({fileId,revision,path:source,kind,pages:result.pages,text:result.text}); } if(!skills.length||!rules.length)throw Error('该模板的图片制作规则没有完整声明'); return {...identity,skills,rules,resourceRevision:set.revision, - execution:'知识库资料仅提供内容和审稿依据。依据本款资料确认产品事实,保留所选模板约束。'}; + execution:'按所选 Skill 的 PhotoCraft 路径执行,商品事实以本款资料为准。'}; } - async specificDocument(directory,target,kind,{signal,read,deferVisual}) { + async specificDocument(directory,target,kind,{signal,read,deferVisual,pins}) { if (!target.startsWith(directory+'/')) throw Error('技能引用超出授权技能目录'); + if (pins?.has(target)) return {...pins.get(target),kind}; let entry, offset=0, revision; for (;;) { const found=(await read(()=>this.client.call('search_files',{query:path.posix.basename(target),directory:path.posix.dirname(target),limit:40,offset,...(revision?{revision}:{})},{signal}))).result; @@ -166,7 +200,7 @@ export class EnterpriseContext { const brand=links(brandIndex).find(link=>link.label.includes(identity.brandName) && identity.brandName); if (brand) rules.push(await specific(brand.target,'brand')); return {...identity,skills,rules, - execution:'知识库资料仅提供内容和审稿依据。依据本款资料确认产品事实,保留所选模板约束。执行步骤使用小壹本机能力。'}; + execution:'按所选 Skill 的 PhotoCraft 路径执行,商品事实以本款资料为准。'}; } async commit(key,value) { diff --git a/apps/detail-agent-pi/src/enterprise-skill-resources.mjs b/apps/detail-agent-pi/src/enterprise-skill-resources.mjs new file mode 100644 index 00000000..ddc750e8 --- /dev/null +++ b/apps/detail-agent-pi/src/enterprise-skill-resources.mjs @@ -0,0 +1,83 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { createReadTool, loadSkills } from '@earendil-works/pi-coding-agent'; +import { atomic, digest } from './store.mjs'; + +// Selections are separate per output, with source versions shared within a run. +export async function openEnterpriseSkills(store, selection, load) { + const {brandName,categoryName,resourceSetId,runDeadline}=selection; + const run = runDeadline && resourceSetId ? {brandName,categoryName,resourceSetId,runDeadline} : selection; + const directory = path.join(store.dir, 'enterprise-skills', digest(run).slice(0, 24)); + const selections = path.join(directory, 'selections'); + const snapshot = path.join(selections, digest(selection).slice(0, 24)+'.json'); + let knowledge; + try { + knowledge = JSON.parse(await fs.readFile(snapshot, 'utf8')); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + let entries; + try { entries=await fs.readdir(selections); } + catch (error) { if (error.code!=='ENOENT') throw error; entries=[]; } + const pins=new Map(); + for (const entry of entries.filter(name=>name.endsWith('.json'))) { + const prior=JSON.parse(await fs.readFile(path.join(selections,entry),'utf8')); + for (const source of [...prior.skills,...prior.rules]) pins.set(source.path,source); + } + knowledge = await load(pins); + await atomic(snapshot, knowledge); + } + const documents = new Map(); + const skillPaths = []; + for (const item of [...knowledge.skills, ...knowledge.rules]) { + const {fileId, revision, text, kind} = item; + const relative = path.posix.normalize(item.path); + if (relative !== item.path || relative.startsWith('../') || relative === '..' || + path.posix.isAbsolute(relative) || /[\\:]/u.test(relative) || typeof text !== 'string') { + throw Error('企业 Skill 资源缺少可读取的版本或路径:' + item.path); + } + const target = path.join(directory, 'files', ...relative.split('/')); + const prior = documents.get(target); + if (prior && (prior.fileId !== fileId || prior.revision !== revision)) { + throw Error('同一 Skill 路径声明了多个版本:' + item.path); + } + if (prior) continue; + await fs.mkdir(path.dirname(target), {recursive:true}); + try { + await fs.writeFile(target, text, {encoding:'utf8', flag:'wx'}); + } catch (error) { + if (error.code !== 'EEXIST' || await fs.readFile(target, 'utf8') !== text) throw error; + } + documents.set(target, {fileId, revision, kind, path:item.path}); + if (kind === 'skill') skillPaths.push(target); + } + + const resource = loadSkills({cwd:store.dir, agentDir:store.dir, skillPaths, includeDefaults:false}); + const loadedPaths = new Set(resource.skills.map(skill => skill.filePath)); + const missing = skillPaths.filter(file => !loadedPaths.has(file)); + if (!skillPaths.length || missing.length) { + const names = missing.map(file => documents.get(file).path); + throw Error('Pi 无法载入本次制作的 Skill:' + (names.join('、') || '没有已发布的入口')); + } + await store.appendEvent({type:'enterprise_skill_resources_bound', outputId:selection.outputId, + ...((knowledge.resourceRevision) ? {resourceRevision:knowledge.resourceRevision} : null), + sources:[...documents.values()]}); + return {knowledge, resource, documents}; +} + +export function enterpriseSkillReadTool(store, getBinding, agent, requestScope) { + const source = file => { + const document = getBinding()?.documents.get(path.normalize(file)); + if (!document) throw Error('该路径未随本次制作的企业 Skill 加载,请读取所选 Skill 或已发布的引用。'); + return document; + }; + return createReadTool(store.dir, {operations:{ + access: async file => { source(file); }, + readFile: async file => { + const document = source(file); + const bytes = await fs.readFile(file); + await store.appendEvent({type:'enterprise_skill_resource_read', agent, requestScope, + fileId:document.fileId, revision:document.revision, kind:document.kind, path:document.path}); + return bytes; + }, + }}); +} diff --git a/apps/detail-agent-pi/src/production-goal.mjs b/apps/detail-agent-pi/src/production-goal.mjs index 69b96e8f..549fda9e 100644 --- a/apps/detail-agent-pi/src/production-goal.mjs +++ b/apps/detail-agent-pi/src/production-goal.mjs @@ -40,14 +40,9 @@ export async function mayContinueProductionGoal(host, event) { const last = event.messages.findLast(message => message.role === 'assistant'); if (host.compacting || host.canvasWritesStopped || host.canvasNotificationsDetached || host.goalStageResult || host.goalPendingOriginal || last?.stopReason !== 'stop') return false; - if (!host.productionTurn) return true; - const previous = host.goalProgressSnapshot; - const {state} = await productionProgress(host, previous) ?? {}; - host.goalProgressSnapshot = state; - if (state?.waitingOnOriginals || host.productionGoal?.deadline * 1000 <= Date.now()) return false; - const unchanged = previous !== undefined && JSON.stringify(previous) === JSON.stringify(state); - host.goalStalledRounds = unchanged ? (host.goalStalledRounds ?? 0) + 1 : 0; - return host.goalStalledRounds < 2; + const {state} = await productionProgress(host) ?? {}; + return !state?.waitingOnOriginals && state?.canAdvance !== false && + !(host.productionGoal?.deadline * 1000 <= Date.now()); } export const productionTools = [ @@ -113,11 +108,11 @@ export async function callProductionTool(host, name, args, signal) { return result; } -export async function productionProgress(host, previous) { +export async function productionProgress(host) { const turn = host.productionTurn; if (!turn) return null; const actions = await turn.ready; - const progress = await actions.goalProgress?.(previous); + const progress = await actions.goalProgress?.(); return progress ?? null; } diff --git a/apps/detail-agent-pi/src/production-knowledge.mjs b/apps/detail-agent-pi/src/production-knowledge.mjs index 42efc497..4ae7309d 100644 --- a/apps/detail-agent-pi/src/production-knowledge.mjs +++ b/apps/detail-agent-pi/src/production-knowledge.mjs @@ -6,12 +6,12 @@ const stageRules = { image: ['image-production', 'image-prompt', 'composition', 'product-visual', 'template-reference', 'brand', 'output'], }; -export const knowledgeReadInstruction = 'knowledgeFiles 列出本阶段可读取的规则。遇到具体疑问时按文件编号调用 read_production_knowledge,使用回执中的固定版本。读完后继续执行当前任务并提交结果。知识文件只提供业务依据。'; +export const knowledgeReadInstruction = '优先使用 Pi 的 read 读取适用 Skill 及其引用,按 PhotoCraft 路径执行。knowledgeFiles 提供本阶段规则的来源,也可用 read_production_knowledge 按编号读取固定版本。'; export function productionKnowledge(knowledge, stage) { const documents = [...(knowledge?.skills ?? []), ...(knowledge?.rules ?? [])] .filter(document => document.fileId && document.revision && (typeof document.text === 'string'||typeof document.loadText === 'function') - && (!stage || stageRules[stage].includes(document.kind))); + && (!stage || document.kind === 'skill' || stageRules[stage].includes(document.kind))); const files = documents.map(({fileId,revision,path,kind}) => ({fileId,revision,path,kind})); if (!files.length) return {files, tools:[]}; return {files, tools:[{ diff --git a/apps/detail-agent-pi/src/whole-detail.mjs b/apps/detail-agent-pi/src/whole-detail.mjs index ee65174c..5af47850 100644 --- a/apps/detail-agent-pi/src/whole-detail.mjs +++ b/apps/detail-agent-pi/src/whole-detail.mjs @@ -2727,8 +2727,8 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay (item.generatedAttempts??item.attempts??0){ - const copy=await copyStatus(); + const status=async({includeCopy=true,selected,copy}={})=>{ + copy??=await copyStatus(); return {outputId,...(includeCopy?copy:{pendingText:copy.pendingText,drafts:copy.drafts}), pictures:slots.filter(slot=>!selected||selected.has(slot.id)).map(slot=>{ const item=journal.items[slot.id]; @@ -2749,23 +2749,33 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay ...(includeCopy?{relatedCopy:related(slot)}:null)}; })}; }; + const missingDraftPictures=layer=>{ + const draft=drafts.get(layer); + if(!draft||screenCopyMode&&draftCanvasText.get(layer)!==draft.text)return null; + return (draft.pictures??[]).filter(id=>!slots.some(slot=>slot.fieldId===id&&pictureVerified(slot))); + }; const progressState=async()=>{ - const fields=await unstaged(); - const {pictures}=await status({includeCopy:false}); + const copy=await copyFields?.()??[]; + const fields=copy.filter(field=>!drafts.has(field.layer)); + const {pictures}=await status({includeCopy:false,copy:copyBatch(fields)}); const {revision}=await canvas.read(); - const waitingOnOriginals=!!(outlinePending || copyPending || pictures.some(picture=>picture.pendingOriginal)) - && !runningWorkers.size && !runningReviews.size - && !(fields.length && !outlinePending && !copyPending) - && !pictures.some(picture=>picture.interruptedWorker) - && !pictures.some(picture=>!picture.pendingOriginal && eligible(slots.find(slot=>slot.id===picture.id)) - && (picture.canRework || ['not_assigned','candidate','needs_review','ready_for_review','failed'].includes(picture.state))); + const imageWork=pictures.some(picture=>picture.interruptedWorker|| + (!picture.pendingOriginal && !journal.items[picture.id]?.pendingAdoption && + eligible(slots.find(slot=>slot.id===picture.id)) && + (picture.canRework || ['not_assigned','candidate','needs_review','ready_for_review','failed','placement'].includes(picture.state)))); + const copyWork=writeCopy&&!outlinePending&&!copyPending&& + (fields.length>0||pageCopyMode&©.some(field=>missingDraftPictures(field.layer)?.length===0)); + const deliveryCheck=!copy.length&&!blockedCopy.size&&!renderIssues.size&&pictures.every(picture=>picture.state==='applied'); + const canAdvance=Boolean(imageWork||copyWork||deliveryCheck); + const waitingOnOriginals=!canAdvance&&!runningWorkers.size&&!runningReviews.size&& + Boolean(outlinePending||copyPending||pictures.some(picture=>picture.pendingOriginal)); return {revision,fields:fields.map(({field,correction,review})=>({field,correction,review})), drafts:[...drafts.values()].map(({field,text})=>({field,text})), written:Object.values(journal.copyEvidence??{}).map(({field,text})=>({field,text})), pictures:pictures.map(({id,field,state,candidateId,reason,review,pendingOriginal,interruptedWorker,canRework,screenFeedback})=> ({id,field,state,candidateId,reason,review,pendingOriginal,interruptedWorker,canRework,screenFeedback})), screens:{reviewed:[...reviewed.keys()],read:[...reads.keys()],total:screenCount}, - outlineOriginal:outlinePending?.id,copyOriginal:copyPending?.id,waitingOnOriginals}; + outlineOriginal:outlinePending?.id,copyOriginal:copyPending?.id,waitingOnOriginals,canAdvance}; }; const storeScreenReviews=()=>writeJournal(async()=>{ journal.screenCount=screenCount; @@ -2812,13 +2822,14 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay async goalProgress(previous){ await checkHeldModels(null,signal); enqueueExistingReviews(null,signal); - const checkpoint=JSON.stringify(previous); + const checkpoint=previous===undefined?null:JSON.stringify(previous); for(;;){ signal?.throwIfAborted(); const activity=candidateProgress.promise; const state=await progressState(); if(verifiedProduction)pumpReviews(); - if(JSON.stringify(state)!==checkpoint||!runningWorkers.size&&!runningReviews.size)return {state}; + const ready=checkpoint===null?state.canAdvance:JSON.stringify(state)!==checkpoint; + if(ready||!runningWorkers.size&&!runningReviews.size)return {state}; await activity; } }, @@ -2859,9 +2870,8 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay const missingDrafts=[...available.values()].filter(field=>!drafts.has(field.layer)); const awaitingPictures=new Set(); const ready=new Set([...available.keys()].filter(layer=>{ - const draft=drafts.get(layer); - if(!draft||screenCopyMode&&draftCanvasText.get(layer)!==draft.text)return false; - const missing=(draft.pictures??[]).filter(id=>!slots.some(slot=>slot.fieldId===id&&pictureVerified(slot))); + const missing=missingDraftPictures(layer); + if(!missing)return false; for(const id of missing)awaitingPictures.add(id); return !missing.length; })); diff --git a/apps/detail-agent-pi/test/enterprise-context.test.mjs b/apps/detail-agent-pi/test/enterprise-context.test.mjs index 96c2882a..b4a9f6a3 100644 --- a/apps/detail-agent-pi/test/enterprise-context.test.mjs +++ b/apps/detail-agent-pi/test/enterprise-context.test.mjs @@ -33,6 +33,9 @@ test('selected resource guides are read completely with their own versions',asyn assert.equal(result.skills.length,2); assert.equal(result.rules[0].text,'第一页\n第二页'); assert.equal(result.rules[0].pages,2); + const production=await ctx.load({task:'production',brandName:'顾家',categoryName:'电脑桌',resourceSetId:'selected',outputId:'detail'}); + assert.deepEqual(production.skills,result.skills); + assert.deepEqual(calls.slice(2).map(([name])=>name),['list_libraries','get_resource_set']); }); test('visual guidance follows the declared PS reference selection across directories',async()=>{ diff --git a/apps/detail-agent-pi/test/pi.test.mjs b/apps/detail-agent-pi/test/pi.test.mjs index 51cc9aeb..0998c717 100644 --- a/apps/detail-agent-pi/test/pi.test.mjs +++ b/apps/detail-agent-pi/test/pi.test.mjs @@ -9,6 +9,8 @@ import { ProjectStore } from '../src/store.mjs'; import { evaluate, ToolLab } from '../src/tool-lab.mjs'; import { DetailPiAgent } from '../src/agent.mjs'; import { settleProductionGoal } from '../src/settle-production-goal.mjs'; +import { openEnterpriseSkills } from '../src/enterprise-skill-resources.mjs'; +import { mayContinueProductionGoal } from '../src/production-goal.mjs'; import { cleanup } from './cleanup.mjs'; const identity = () => ({ scope: 'a'.repeat(64), project: randomUUID() }); @@ -22,6 +24,90 @@ function stream(content) { } const info = scope => ({ accountScope: scope, model: { id: 'qa-model', protocol: 'openai-chat' }, pending: [] }); +test('Pi production and its worker read the same locked Skill and its relative reference', async t => { + const dir=await root(), id=identity(), documentId=23; + t.after(()=>cleanup(dir)); + const store=await ProjectStore.open(dir,id,binding('lights')); + const variantId=randomUUID(), runDeadline=Math.floor(Date.now()/1000)+300; + const selection={brandName:'试验品牌',categoryName:'灯具',templateId:'two-outputs',releaseId:'v4', + resourceSetId:'lighting',outputId:'detail',runDeadline}; + const knowledge={...selection,skills:[{fileId:'root',revision:'r4',kind:'skill',path:'Skills/lighting/SKILL.md', + text:'---\nname: lighting\ndescription: Use for lighting products.\n---\nUse the [fixture notes](references/finish.md).'}], + rules:[{fileId:'finish',revision:'r7',kind:'brand',path:'Skills/lighting/references/finish.md', + text:'PINNED_FINISH: keep satin highlights.'}]}; + const canvas={run:'skill-fixture',documentId,detailImages(){},begin:async()=>({run:'skill-fixture',conversationActive:true}), + read:async()=>({conversationActive:true}),delta:async()=>{},activity:async()=>{},reply:async()=>{},end:async()=>{}, + workflowRead:async()=>({available:true,version:1,canvasFirst:true,template:{id:'two-outputs',version:'v4',enterprise:true,resourceSetId:'lighting'}, + productEvidence:{accountScope:id.scope,project:id.project,documentId,brief:{brandName:'试验品牌',categoryName:'灯具'}}})}; + let main=0,worker=0,serial=0; + const reads=new Map(); + const transport={info:info(id.scope),stream(_model,context){ + const system=getCurrentSystemPrompt(context.messages); + assert.match(system,/lighting<\/name>/); + assert.doesNotMatch(system,/PINNED_FINISH|Use the \[fixture notes\]/); + const location=system.match(/lighting<\/name>[\s\S]*?([^<]*SKILL\.md)<\/location>/u)[1]; + const child=system.includes('worker-fixture'); + const steps=child?[ + ['read',{path:location}], + ['read',{path:path.join(path.dirname(location),'references','finish.md')}], + ]:[ + ['read',{path:location}], + ['plan_production',{}], + ['finish_production',{}], + ]; + for(const result of context.messages.filter(message=>message.role==='toolResult'&&message.toolName==='read')){ + assert.notEqual(result.isError,true,JSON.stringify(result.content)); + reads.set(result.toolCallId,result.content.map(item=>item.text).join('\n')); + } + const step=steps[child?worker++:main++]; + return step?stream([{type:'toolCall',name:step[0],id:'skill-'+(++serial),arguments:step[1]}]): + stream([{type:'text',text:'本轮结束。'}]); + }}; + const host=await DetailPiAgent.open({store,canvas,transport,documentId,productionGoal:{outputId:'detail',variantId,deadline:runDeadline}}); + let loads=0; + host.enterpriseContext={load:async()=>{loads++;return knowledge;}}; + host.executeWholeDetail=async (_output,_production,_pending,_signal,drive)=>drive({ + async plan_production(){ + await host.runDetailAgent('lighting-slot','worker-fixture','制作局部细节图',[]); + return {planned:true}; + }, + async finish_production(){ + return {status:{complete:true},stage:{text:'交付检查',production:{outputId:'detail',variantId,complete:true}}}; + }, + }); + try { + assert.equal((await host.prompt('制作详情页')).production.complete,true); + const context=await host.modelContext({}, {loadKnowledge:true}); + assert.deepEqual(context.enterpriseKnowledge.sources.map(row=>row.revision),['r4','r7']); + assert.equal(loads,1,'read-only context uses the original locked selection'); + assert.equal([...reads.values()].filter(body=>body.includes('fixture notes')).length,2); + assert.ok([...reads.values()].some(body=>body.includes('PINNED_FINISH'))); + const second=await openEnterpriseSkills(store,selection,()=>{throw Error('run must use the first locked version');}); + assert.equal(second.knowledge.rules[0].revision,'r7'); + const mainSelection={...selection,outputId:'main_images',releaseId:'main-v4'}; + const mainBinding=await openEnterpriseSkills(store,mainSelection,pins=>{ + assert.equal(pins.get(knowledge.skills[0].path).revision,'r4'); + return {...knowledge,...mainSelection,skills:[pins.get(knowledge.skills[0].path)]}; + }); + assert.equal(mainBinding.resource.skills[0].filePath,second.resource.skills[0].filePath); + const events=(await fs.readFile(path.join(store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line)); + assert.deepEqual(events.filter(e=>e.type==='enterprise_skill_resource_read').map(e=>[e.agent,e.fileId,e.revision]), + [['main','root','r4'],['worker','root','r4'],['worker','finish','r7']]); + } finally {await host.dispose();} +}); + +test('goal continuation waits for the original when no independent work is available', async () => { + let state={canAdvance:true,waitingOnOriginals:false}; + const actions={async goalProgress(){return {state};}}; + const host={productionTurn:{ready:Promise.resolve(actions)},productionGoal:{deadline:Date.now()/1000+60}}; + const event={messages:[{role:'assistant',stopReason:'stop'}]}; + for(let turn=0;turn<4;turn++)assert.equal(await mayContinueProductionGoal(host,event),true); + state={canAdvance:false,waitingOnOriginals:true}; + assert.equal(await mayContinueProductionGoal(host,event),false); + state={canAdvance:false,waitingOnOriginals:false}; + assert.equal(await mayContinueProductionGoal(host,event),false); +}); + test('production tools share one Pi transcript and only finish after the export handoff tool', async t => { const dir=await root(), id=identity(); t.after(()=>cleanup(dir)); @@ -76,7 +162,7 @@ test('production tools share one Pi transcript and only finish after the export const next=await makeHost('main_images'); try { const copy=layer=>['write_copy_fields',{items:[{layer,text:'商品文案',sources:['P01'],pictures:[]}]}]; - steps.push(['plan_production'],['plan_production'],null,copy(1),['finish_production'],copy(2),copy(3),['finish_production']); + steps.push(['plan_production'],['plan_production'],null,null,null,copy(1),['finish_production'],copy(2),copy(3),['finish_production']); const result=await next.prompt('制作主图',{goalContinuation:true}); assert.equal(result.production.outputId,'main_images'); assert.equal(result.production.canvasRevision,7); diff --git a/docs/development/xiaoyi/implementation.md b/docs/development/xiaoyi/implementation.md index 313a6430..f4d19d54 100644 --- a/docs/development/xiaoyi/implementation.md +++ b/docs/development/xiaoyi/implementation.md @@ -224,3 +224,17 @@ PhotoCraft 用正式文件独立导入了 5 张主图和 1 张 SKU,并按原 接续阶段 D 的 A20–A22,先将所选企业 Skill 和引用接入 Pi 的版本化资源加载,核对主、子代理读取记录,再处理项目目标和多余的固定轮次限制。 +## 第七批 · 阶段 D,企业 Skill 与目标续跑 + +一键制作根据画布绑定的品牌、品类、资源组和模板发布版本加载企业 Skill。Pi 用原生 Skill 发现和 `read` 读取正文及引用,保留资源原有的相对路径。主代理和本轮子代理共用同一份资源清单。选择、实际读取的角色、文件和版本写入项目事件。 + +| 触发条件 | 出口 | 验证 | +| --- | --- | --- | +| 开启企业模板制作或同轮切换输出,企业知识有新版 | 各输出保留自己的模板版本,同一轮同一资源组沿用已锁定的共享 Skill 与规则。重开读取本轮快照,新一轮可使用当前发布版本 | A20 通过两输出灯具夹具的锁定与重开测试。顾家电脑桌的详情、主图、SKU 三个正式组件绑定各自模板版本,共享 6 份同版本来源 | +| 主代理或子代理需要读取规则及相对引用 | 通过 Pi 原生 `read` 读取所选发布资源。已发布的视觉指南从资源组读取。正式电脑桌资源组没有视觉指南组件,沿用授权目录;模板参考中的 PhotoCraft 入口及其布局和运行环境说明均可读取 | A21 的正文和引用、A22 的主子代理读取通过。任务脚本执行绑定未验证。灯具夹具通过真实 Pi SDK 配合本地模型回执。电脑桌正式资源只读验证了 4 份 Skill、17/18/18 份输出资源及两种代理角色的读取事件 | +| Pi 本轮没有导出,仍有可做的文案、配图、审核或交付检查 | 目标依据当前工作继续。仅余本地在途作业时等待事件,原请求结果待核查时沿用原编号。没有可执行工作时交回本轮检查点或结算,原有制作期限仍生效 | A24 通过本地回归,覆盖连续三次只读回复后继续写入、有待核查图位时继续独立任务,以及原请求在等待中未重派。A23 的压缩与恢复留待下一切片 | + +验证以本批工作树为准。Node 回归 180 项通过。顾家电脑桌使用正式发布资源做只读验收,资源绑定及读取耗时依次为 2.547 秒、0.352 秒和 0.360 秒。证据位于 `D:/AI Code/gongxiangp2/output/xiaoyi-harness-implementation-20261125/batch-07/`,见 `phase-d-regression.log`、`desk-three-output-skills.log` 和 `desk-three-output-skill/events.jsonl`。 + +本批未执行 98K 模型调用、新原生客户端构建、Photoshop 外部兼容及实际三类导出。阶段 D 继续使用输出与花色作为执行单元。后续核验 Pi 原生压缩和作业恢复,再推进项目级主代理与实际需要的 Skill 执行绑定。 +