diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index 6c78f685..f1518990 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -1,6 +1,6 @@ import {setTimeout as delay} from 'node:timers/promises'; import { randomUUID } from 'node:crypto'; -import { confirmProductionResponse, confirmedProductionFailure, piRetryPolicy, productRequestScope, productionUsesAutomaticTools, ProductionOutputLimit, ProductionRequestFailed, ProductionRequestPending } from './production-recovery.mjs'; +import { recoverProductionResponse, confirmedProductionFailure, piRetryPolicy, productRequestScope, productionUsesAutomaticTools, ProductionOutputLimit, ProductionRequestFailed, ProductionRequestPending } from './production-recovery.mjs'; import { enterpriseTools } from './enterprise-knowledge.mjs'; import { executeWorkflow } from './workflow-execute.mjs'; import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, stripProductionToolText } from './stream-presentation.mjs'; @@ -100,7 +100,7 @@ function toolsFor(host) { const commands = nativeTools(host, make); const contextTools = [ 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_set', '持久记录用户明确确认的事实/决定;evidence必须是用户消息中的原话。', Type.Object({ key: string(64), value: string(1000), evidence: Type.String({ minLength: 4, maxLength: 1000 }) }), args => host.store.remember(args)), make('memory_search', '用 query 查本项目对话。只有拿到真实 toolCallId 时才填写它,可用 offset 分段读取该回执。回执无匹配时仍按 query 查询。', Type.Object({ query:Type.Optional(Type.String({maxLength:200})), toolCallId:Type.Optional(Type.String()), @@ -217,14 +217,15 @@ function toolsFor(host) { if (typeof host.canvas?.copyOptions === 'function') active.push({...make('copywriting_options', '把已生成的产品卖点逐条显示为可多选的候选。items中每条一个重点,只使用已确认资料;缺失依据放missing。展示不代表采纳或写入画布,等用户选择后再改写或预览。', Type.Object({items:Type.Array(Type.String({minLength:1,maxLength:160}),{minItems:1,maxItems:20}),missing:Type.Optional(Type.Array(Type.String({minLength:1,maxLength:160}),{maxItems:20}))},{additionalProperties:false}), async args => { const value = await host.canvas.copyOptions(args); if (!value?.optionsId || value.run !== host.canvas.run || value.documentId !== host.canvas.documentId) throw Error('卖点选项不属于当前会话'); - host.copyOptionsReceipt = value.optionsId; return {optionsId:value.optionsId,count:value.count,awaitingSelection:true,applied:false}; }),namespace:PHOTOCRAFT_NAMESPACE,exposure:'deferred'}); if(typeof host.canvas?.copyFields==='function')active.push({...make('copywriting_fields','按本轮引用的每个真实文字格分别提交候选文案。先canvas_read读取文字格、用途和字数行数限制;items中每个layer只能出现一次,覆盖全部引用文字格。宿主在提交前复核每格并绑定真实版本,无需填写revision。用户逐格预览和采纳,工具不会写入画布。',Type.Object({revision:Type.Optional(Type.Integer({minimum:0})),items:Type.Array(Type.Object({layer:Type.Integer({minimum:1}),text:Type.String({minLength:1,maxLength:3000})},{additionalProperties:false}),{minItems:2,maxItems:20})},{additionalProperties:false}),async (args,signal)=>{ if(args.items.length!==host.copyFieldsTargets.length||new Set(args.items.map(item=>item.layer)).size!==args.items.length||args.items.some(item=>!host.copyFieldsTargets.includes(item.layer)))throw Error('候选文案须与本轮引用文字格一一对应'); const reads=[];for(const layer of host.copyFieldsTargets)reads.push(await previewTarget(host,layer,signal)); const revision=reads[0].revision;if(reads.some(read=>read.revision!==revision))throw Error('读取期间画布已变化,请重新读取本次文字格'); - const value=await host.canvas.copyFields({...args,revision});if(!value?.optionsId||value.run!==host.canvas.run||value.documentId!==host.canvas.documentId||value.count!==args.items.length)throw Error('逐格文案回执不一致');host.copyFieldsReceipt=value.optionsId;return {...value,applied:false}; + const value=await host.canvas.copyFields({...args,revision}); + if(!value?.optionsId||value.run!==host.canvas.run||value.documentId!==host.canvas.documentId||value.count!==args.items.length)throw Error('逐格文案回执不一致'); + return {...value,applied:false}; }),namespace:PHOTOCRAFT_NAMESPACE,exposure:'deferred'}); if (typeof host.canvas?.preview === 'function') active.push({ ...make('canvas_preview', '在原生界面预览当前图层修改,等用户采纳才应用。宿主先读取真实目标并绑定当前版本,无需填写revision。type.edit替换文案须传params.text;超出模板文字格限制时由原生输入等待用户缩短或取消,不放宽模板。只传本命令支持的参数,其他命令可先查native_catalog。保留未要求改变的字体、字号、位置和其他图层。', previewParameters, async (args, signal, ctx) => { if (host.canvasNotificationsDetached || host.canvasOperations.writesBlocked) throw Error('原项目已切换或用户已接手,未生成预览'); @@ -544,25 +545,11 @@ export class DetailPiAgent { const files = await projectTools(host); const customTools = [...toolsFor(host),...files.tools]; host.workingDirectory=files.cwd; - const extensions = await createPhotoCraftExtensions(host, [], { + const {resourceLoader:loader} = await createPhotoCraftExtensions(host, [], { includeGoal: !!productionGoal, mayContinueGoal: event => mayContinueProductionGoal(host, event), + systemPrompt: productionGoal ? PRODUCTION_SYSTEM : SYSTEM, }); - host.localSkillFiles = new Set(extensions.resourceLoader.getSkills().skills.map(skill=>path.normalize(skill.filePath))); - const loader = { - getExtensions: () => extensions, - getSkills: () => { - const local=extensions.resourceLoader.getSkills(); - const enterprise=host.productionSkills?.resource; - if (!enterprise) return local; - const skills=new Map([...local.skills,...enterprise.skills].map(skill=>[skill.name,skill])); - return {skills:[...skills.values()],diagnostics:[...local.diagnostics,...enterprise.diagnostics]}; - }, - getPrompts: () => extensions.resourceLoader.getPrompts(), getThemes: () => ({ themes: [], diagnostics: [] }), - getAgentsFiles: () => ({ agentsFiles: [] }), - getSystemPrompt: () => productionGoal ? PRODUCTION_SYSTEM : SYSTEM, - getSystemPromptSource: () => undefined, - getAppendSystemPrompt: () => [], getAppendSystemPromptSources: () => [], extendResources() {}, async reload() {}, - }; + host.localSkillFiles = new Set(loader.getSkills().skills.map(skill=>path.normalize(skill.filePath))); const { session } = await createAgentSession({ cwd: files.cwd, agentDir: store.dir, modelRuntime: runtime, model: runtime.getModel('jiansun-native-98k', info.model.id), thinkingLevel: reasoning ? info.thinkingLevel ?? undefined : undefined, @@ -829,7 +816,9 @@ export class DetailPiAgent { // This only reads the session and publishes telemetry; it never prompts. await host.updateContextUsage(null, 'ready'); return host; - } catch (error) { await host.goalBroker?.close(); host.releaseLock(); host.releaseLock = null; throw error; } + } catch (error) { + try { await host.dispose(); } finally { throw error; } + } } async exclusive(operation) { if (this.disposed || this.operationActive) throw Error('此会话已有操作或已关闭,未发起新请求'); @@ -998,10 +987,15 @@ export class DetailPiAgent { runDeadline:production.deadline}; this.enterpriseContext??=new EnterpriseContext(this.store); this.productionSkills=await openEnterpriseSkills(this.store,selection, - pins=>this.loadWholeDetailKnowledge(selection,this.productionSignal,false,pins), + pins=>this.loadWholeDetailKnowledge(selection,this.productionSignal,pins), (target,lock)=>this.enterpriseContext.loadReference(target,{ ...lock,read:this.productionKnowledgeRead('production',lock.signal), })); + this.session.resourceLoader.extendResources({ + skillPaths: this.productionSkills.resource.skills.map(skill => ({ + path: skill.filePath, metadata: {source:'enterprise', scope:'project', origin:'top-level'}, + })), + }); this.session.setActiveToolsByName([...new Set([...this.session.getActiveToolNames(),'read'])]); } if (!goalContinuation) await this.store.recordUserEvidence(text); @@ -1069,7 +1063,7 @@ export class DetailPiAgent { }); } - async executeWholeDetail(outputId, production, pending, signal, drive, {planStrategy=true}={}) { + async executeWholeDetail(outputId, production, pending) { const heartbeat=setInterval(()=>{this.canvas.read().catch(()=>{});},2000); heartbeat.unref(); this.wholeDetailActive=true; @@ -1078,33 +1072,13 @@ export class DetailPiAgent { const [{runWholeDetail},{prepareProductStrategy}] = await Promise.all([ import('./legacy/whole-detail.mjs'), import('./legacy/product-strategy.mjs'), ]); - return await runWholeDetail(this,this.runDetailAgent,async plan=>{ + return await runWholeDetail(this,this.runDetailAgent,plan=>{ if(!production&&!plan.template.enterprise)return null; const brief=plan.productEvidence?.brief; - if (production && this.productionSkills) { - const lock=this.productionSkills.knowledge; - if (lock.templateId!==plan.template.id || lock.releaseId!==plan.template.version || - (lock.resourceSetId??null)!==(plan.template.resourceSetId??null)) { - throw Error('制作中的模板版本已变化,请在新模板上继续制作。'); - } - return lock; - } return this.loadWholeDetailKnowledge({task:production?'production':'image',outputId,brandName:brief?.brandName,categoryName:brief?.categoryName, - templateId:plan.template.id,releaseId:plan.template.version,resourceSetId:plan.template.resourceSetId,skillSources:plan.template.skillSources},signal,!!drive); - },{outputId,production,signal,drive, - readModelOriginal:drive&&this.broker?async (id,recheck=false)=>{ - if(!await this.store.ownsRequest(id))return null; - let receipt=await this.broker.read(id); - if(recheck&&['unknown','dispatched'].includes(receipt.phase)){ - await this.broker.recover(id).catch(()=>{}); - receipt=await this.broker.read(id); - } - if(['complete','rejected'].includes(receipt.phase))return {settled:true}; - const failure=confirmedProductionFailure(receipt,id); - if(failure)return {settled:true,...(!failure.retryable?{rejection:failure.message}:null)}; - return null; - }:undefined, - prepareStrategy:production && planStrategy ? (plan,slots,knowledge,runMainAgent)=>prepareProductStrategy(this,runMainAgent,plan,slots,knowledge) : undefined}); + templateId:plan.template.id,releaseId:plan.template.version,resourceSetId:plan.template.resourceSetId,skillSources:plan.template.skillSources}); + },{outputId,production, + prepareStrategy:production ? (plan,slots,knowledge,runMainAgent)=>prepareProductStrategy(this,runMainAgent,plan,slots,knowledge) : undefined}); } finally { this.wholeDetailActive=false; this.productionRequests=null; @@ -1112,10 +1086,10 @@ export class DetailPiAgent { } } - async loadWholeDetailKnowledge(selection, signal, deferVisual=false, pins) { + async loadWholeDetailKnowledge(selection, signal, pins) { this.enterpriseContext??=new EnterpriseContext(this.store); return this.enterpriseContext.load({task:'production',...selection,turn:this.canvas.run}, { - deferVisual,signal,pins,read:this.productionKnowledgeRead(selection.task,signal), + signal,pins,read:this.productionKnowledgeRead(selection.task,signal), }); } @@ -1156,9 +1130,23 @@ export class DetailPiAgent { async recover(id, options = {}) { return this.exclusive(() => this.recoverTurn(id, options)); } async recoverTurn(id, { executeReadOnly = false } = {}) { if (this.session.isStreaming) throw Error('先等待当前操作结束'); - if (!await this.store.ownsRequest(id)) throw Error('原请求不属于当前店铺/品类会话,未查询或恢复'); const purpose = await requestPurpose(this, id); - const internalCompaction = ['compaction','legacy-compaction'].includes(purpose.kind); + if (purpose === 'cancelled') { + const receipt = await recoverProductionResponse(this.broker, id, this.session.model, this.session.agent.state.tools); + const phase = ['failed','rejected'].includes(receipt.phase) ? 'failed' : receipt.phase === 'complete' ? 'complete' : 'unknown'; + return {phase,requestId:receipt.requestId,reposted:false,toolsExecuted:0,canvasWrites:0,consumption:'discarded_after_cancel'}; + } + if (['whole-detail-worker','product-goal','whole-detail-review'].includes(purpose)) { + const original=await recoverProductionResponse(this.broker,id,this.session.model,[]); + const {requestId}=original; + const phase=['failed','rejected'].includes(original.phase)?'failed':original.phase==='complete'?'complete':'unknown'; + if (phase==='unknown' && original.recoveryError) { + await this.store.appendEvent({type:'recovery_unknown',id,requestId,reason:original.recoveryError.message}); + } + return {phase,requestId,reposted:false,canvasWrites:0,...(phase==='complete'&&purpose==='whole-detail-review' + ?{restoredText:'已核查原验图结果,制作会从对应图位继续。'}:null)}; + } + const internalCompaction = ['compaction','legacy-compaction'].includes(purpose); let record = { id, ...await this.broker.read(id) }; if (record.phase === 'unknown' || record.phase === 'dispatched') { try { await this.broker.recover(id); } @@ -1168,22 +1156,6 @@ export class DetailPiAgent { } record = { id, ...await this.broker.read(id) }; } - if (purpose.kind === 'cancelled') { - const receipt=record.phase==='received' - ? await confirmProductionResponse(this.broker,record,this.session.model,this.session.agent.state.tools,this.protocolMode) - : record; - const phase=['failed','rejected'].includes(receipt.phase)?'failed':receipt.phase==='complete'?'complete':'unknown'; - return {phase,requestId:record.requestId,reposted:false,toolsExecuted:0,canvasWrites:0,consumption:'discarded_after_cancel'}; - } - if (['whole-detail-worker','product-goal','whole-detail-review'].includes(purpose.kind)) { - const {requestId}=record; - if (['failed','rejected'].includes(record.phase)) return {phase:'failed',requestId,reposted:false}; - if (!['complete','received'].includes(record.phase)) return {phase:'unknown',requestId,reposted:false}; - const original=await confirmProductionResponse(this.broker,record,this.session.model,[]); - const phase=['failed','rejected'].includes(original.phase)?'failed':original.phase==='complete'?'complete':'unknown'; - return {phase,requestId,reposted:false,canvasWrites:0,...(phase==='complete'&&purpose.kind==='whole-detail-review' - ?{restoredText:'已核查原验图结果,制作会从对应图位继续。'}:null)}; - } if (internalCompaction) { return {phase:['complete','received','failed','rejected'].includes(record.phase)?'complete':'unknown', requestId:record.requestId,reposted:false,internalCompaction:true,toolsExecuted:0,canvasWrites:0}; @@ -1237,8 +1209,11 @@ export class DetailPiAgent { this.disposed = true; if (this.nativeUI) this.nativeUI.active = false; if (this.heartbeat) clearInterval(this.heartbeat); - await this.session.abort(); this.session.dispose(); - await this.goalBroker?.close(); - this.releaseLock?.(); this.releaseLock = null; + try { + try { await this.session?.abort(); } finally { this.session?.dispose(); } + } finally { + try { await this.goalBroker?.close(); } + finally { this.releaseLock?.(); this.releaseLock = null; } + } } } diff --git a/apps/detail-agent-pi/src/desktop-host.mjs b/apps/detail-agent-pi/src/desktop-host.mjs index d3d44cbe..c215844d 100644 --- a/apps/detail-agent-pi/src/desktop-host.mjs +++ b/apps/detail-agent-pi/src/desktop-host.mjs @@ -202,8 +202,15 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o const settled=[]; const originals=config.productionOriginals ?? info.pending.map(request=>request.id); for(const id of new Set(originals)){ - const checked=await host.recover(id,{executeReadOnly:false}).catch(()=>({phase:'unknown'})); - settled.push({id,phase:checked.phase}); + signal?.throwIfAborted(); + try { + const checked=await host.recover(id,{executeReadOnly:false}); + settled.push({id,phase:checked.phase}); + } catch (error) { + signal?.throwIfAborted(); + await store.appendEvent({type:'production_original_check_failed',id,category:BridgeError.from(error).category}); + settled.push({id,phase:'unknown'}); + } } const remaining=settled.filter(request=>request.phase==='unknown').length; result={phase:remaining?'unknown':'complete',reposted:false,canvasWrites:0, diff --git a/apps/detail-agent-pi/src/enterprise-context.mjs b/apps/detail-agent-pi/src/enterprise-context.mjs index 8104e112..79419765 100644 --- a/apps/detail-agent-pi/src/enterprise-context.mjs +++ b/apps/detail-agent-pi/src/enterprise-context.mjs @@ -16,16 +16,16 @@ export function links(document) { /** 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,skillSources,turn,outputId}, {signal, read = execute => execute(), deferVisual = false, pins} = {}) { + async load({task,brandName,categoryName,templateId,releaseId,resourceSetId,skillSources,turn,outputId}, {signal, read = execute => execute(), pins} = {}) { signal?.throwIfAborted(); if (!tasks[task] && task!=='production') return null; - const key=JSON.stringify([task,brandName,categoryName,templateId,releaseId,resourceSetId,skillSources,turn,outputId,deferVisual]); + const key=JSON.stringify([task,brandName,categoryName,templateId,releaseId,resourceSetId,skillSources,turn,outputId]); if (this.key===key) return this.value; const navigation=(await read(()=>this.client.call('list_libraries',{},{signal}))).result; const directory=navigation.navigation?.find(item=>item.name==='Skills')?.path; if (task==='production' || task==='image') { const identity={task,brandName,categoryName,templateId,releaseId,resourceSetId}; - const options={signal,read,deferVisual,pins}; + const options={signal,read,pins}; const published = Array.isArray(skillSources) ? await this.loadGuides(identity,skillSources,releaseId,options) : resourceSetId ? await this.declaredGuides(identity,options) : null; @@ -79,8 +79,7 @@ export class EnterpriseContext { 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')); + const entry=links(guide).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) { @@ -150,7 +149,7 @@ export class EnterpriseContext { return {...source,kind:'native-reference',text:result.text}; } - async specificDocument(directory,target,kind,{signal,read,deferVisual,pins}) { + async specificDocument(directory,target,kind,{signal,read,pins}) { if (!target.startsWith(directory+'/')) throw Error('技能引用超出授权技能目录'); if (pins?.has(target)) return {...pins.get(target),kind}; let entry, offset=0, revision; @@ -165,14 +164,8 @@ export class EnterpriseContext { revision=found.revision; } if (!entry) throw Error('企业知识库缺少本次制作的资料:'+path.posix.basename(target)); - const document={fileId:entry.id,revision:entry.revision,path:target,kind}; - if(deferVisual&&['image-prompt','composition','product-visual','template-reference'].includes(kind)){ - let pending; - return {...document,loadText:()=>pending??=this.client.readDocument(entry.id,entry.revision,{signal},read) - .then(({result})=>result.text).catch(error=>{pending=undefined;throw error;})}; - } const {result}=await this.client.readDocument(entry.id,entry.revision,{signal},read); - return {...document,revision:result.revision,text:result.text}; + return {fileId:entry.id,revision:result.revision,path:target,kind,text:result.text}; } async commit(key,value) { diff --git a/apps/detail-agent-pi/src/enterprise-knowledge-cli.mjs b/apps/detail-agent-pi/src/enterprise-knowledge-cli.mjs index 05e90ff9..028453df 100644 --- a/apps/detail-agent-pi/src/enterprise-knowledge-cli.mjs +++ b/apps/detail-agent-pi/src/enterprise-knowledge-cli.mjs @@ -19,12 +19,11 @@ try { dir=await fs.mkdtemp(path.join(os.tmpdir(),'photocraft-ekb-check-')); const host={store:{dir,async appendEvent(){}}}; const tools=enterpriseTools(host,(n,description,parameters,fn)=>({name:n,label:n,description,parameters,async execute(_id,a){return {content:[{type:'text',text:JSON.stringify(await fn(a))}]};}})); - const extensions=await createPhotoCraftExtensions(host); - const loader={getExtensions:()=>extensions,getSkills:()=>({skills:[],diagnostics:[]}),getPrompts:()=>({prompts:[],diagnostics:[]}),getThemes:()=>({themes:[],diagnostics:[]}),getAgentsFiles:()=>({agentsFiles:[]}),getSystemPrompt:()=>'',getSystemPromptSource:()=>undefined,getAppendSystemPrompt:()=>[],getAppendSystemPromptSources:()=>[],extendResources(){},async reload(){}}; + const {resourceLoader}=await createPhotoCraftExtensions(host, [], {includeProjectResources:false}); const runtime=await ModelRuntime.create({authPath:path.join(dir,'auth.json'),modelsPath:null,refreshOnCreate:false,allowModelNetwork:false}); const cost={input:0,output:0,cacheRead:0,cacheWrite:0,total:0}; const model={id:'no-model',name:'No model',api:'openai-completions',provider:'local',baseUrl:'https://unused.invalid',reasoning:false,input:['text'],contextWindow:32768,maxTokens:512,cost}; - ({session}=await createAgentSession({cwd:dir,agentDir:dir,resourceLoader:loader,modelRuntime:runtime,model,customTools:tools,tools:photoCraftToolAllowlist(tools),sessionManager:SessionManager.inMemory(dir),thinkingLevel:'off',settingsManager:SettingsManager.inMemory({compaction:{enabled:false},retry:{enabled:false,maxRetries:0}})})); + ({session}=await createAgentSession({cwd:dir,agentDir:dir,resourceLoader,modelRuntime:runtime,model,customTools:tools,tools:photoCraftToolAllowlist(tools),sessionManager:SessionManager.inMemory(dir),thinkingLevel:'off',settingsManager:SettingsManager.inMemory({compaction:{enabled:false},retry:{enabled:false,maxRetries:0}})})); session.agent.streamFunction=()=>{throw Error('禁止调用模型');};activatePhotoCraftTools(session,tools); const call={type:'toolCall',id:randomUUID(),name:'codemode',arguments:{code:`text(await tools[${JSON.stringify('ekb_'+name)}](${JSON.stringify(args)}))`}}; const message={role:'assistant',api:model.api,provider:model.provider,model:model.id,content:[call],stopReason:'toolUse',usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost},timestamp:Date.now()}; diff --git a/apps/detail-agent-pi/src/enterprise-knowledge.mjs b/apps/detail-agent-pi/src/enterprise-knowledge.mjs index 16cb0720..f3c87977 100644 --- a/apps/detail-agent-pi/src/enterprise-knowledge.mjs +++ b/apps/detail-agent-pi/src/enterprise-knowledge.mjs @@ -94,7 +94,23 @@ async function request(origin,path,{body,key,session,protocol='2025-11-25',fetch try { response=await fetchImpl(origin+path,{method:body===undefined?'GET':'POST',redirect:'manual',signal:signal?AbortSignal.any([signal,AbortSignal.timeout(timeoutMs)]):AbortSignal.timeout(timeoutMs),headers:{Accept:'application/json, text/event-stream',...(body===undefined?{}:{'Content-Type':'application/json'}),...(key?{Authorization:`Bearer ${key}`} : {}),...(session?{'Mcp-Session-Id':session}:{}),'MCP-Protocol-Version':protocol},...(body===undefined?{}:{body:JSON.stringify(body)})}); } catch { signal?.throwIfAborted(); const error=Error('企业知识库网络不可达');error.network=true;throw error; } const reader=response.body?.getReader(); if (!reader) {if(!response.ok)throw failure(response.status);return {value:null,headers:response.headers};} - let size=0, chunks=[]; try { while(true){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>maxBytes){await reader.cancel();throw Error('企业知识库响应超过上限');}chunks.push(value);} } catch(error) { signal?.throwIfAborted();if(error.message==='企业知识库响应超过上限')throw error; const failure=Error('企业知识库网络不可达');failure.network=true;throw failure; } + let size=0; + const chunks=[]; + for (;;) { + const {done,value}=await reader.read().catch(() => { + signal?.throwIfAborted(); + const error=Error('企业知识库网络不可达'); + error.network=true; + throw error; + }); + if (done) break; + size+=value.byteLength; + if (size>maxBytes) { + await reader.cancel(); + throw Error('企业知识库响应超过上限'); + } + chunks.push(value); + } const raw=Buffer.concat(chunks.map(v=>Buffer.from(v))).toString('utf8'); if (!response.ok) { let value;try{value=JSON.parse(raw);}catch{} throw failure(response.status,value,response.headers.get('retry-after')); } return {value:raw.trim()?boundedJSON(raw,response.headers.get('content-type')||''):null,headers:response.headers}; diff --git a/apps/detail-agent-pi/src/photocraft-extension.mjs b/apps/detail-agent-pi/src/photocraft-extension.mjs index f018db73..f87a8e0d 100644 --- a/apps/detail-agent-pi/src/photocraft-extension.mjs +++ b/apps/detail-agent-pi/src/photocraft-extension.mjs @@ -28,19 +28,33 @@ export function nativeToolMetadata(name) { /** * Instantiate the official factories through the public SDK loader. */ -export async function createPhotoCraftExtensions(host, existing = [], { includeGoal = false, mayContinueGoal } = {}) { +export async function createPhotoCraftExtensions(host, existing = [], { + includeGoal = false, mayContinueGoal, systemPrompt = '', includeProjectResources = true, +} = {}) { const cwd = host?.workingDirectory ?? host?.store?.dir; if (typeof cwd !== 'string' || !cwd) throw new TypeError('PhotoCraft extension loading requires host.store.dir'); if (!Array.isArray(existing) || existing.some(extension => !(extension?.handlers instanceof Map) || !(extension?.tools instanceof Map))) { throw new TypeError('Existing PhotoCraft extensions must be compiled SDK Extension objects'); } + const enterpriseDirectory=path.join(host.store.dir,'enterprise-skills')+path.sep; const loader = new DefaultResourceLoader({ cwd, agentDir: host.store.dir, settingsManager: SettingsManager.inMemory({}), noExtensions: true, noThemes: true, noContextFiles: true, additionalExtensionPaths: includeGoal ? [path.join(goalPackage, '.pi', 'extensions', 'pi-goal', 'index.ts')] : [], additionalSkillPaths: includeGoal ? [path.join(goalPackage, 'skills'), productionSkills] : [], - systemPrompt: '', + noSkills: !includeProjectResources, noPromptTemplates: !includeProjectResources, + systemPromptOverride: () => systemPrompt, + appendSystemPrompt: [], + extensionsOverride: result => ({...result, extensions:[...existing, ...result.extensions]}), + skillsOverride: local => { + const enterprise = host.productionSkills?.resource; + if (!enterprise) return local; + // Pi keeps previously extended paths. Only the current enterprise binding is active. + const unpinned=local.skills.filter(skill => !path.normalize(skill.filePath).startsWith(enterpriseDirectory)); + const skills = new Map([...unpinned, ...enterprise.skills].map(skill => [skill.name, skill])); + return {skills:[...skills.values()], diagnostics:[...local.diagnostics, ...enterprise.diagnostics]}; + }, extensionFactories: [ // CodeMode has no Node/file/network globals. Disable its separate model // catalog API as model dispatch belongs to the host's durable broker. @@ -54,7 +68,7 @@ export async function createPhotoCraftExtensions(host, existing = [], { includeG throw new Error(`PhotoCraft SDK extensions failed to load: ${result.errors.map(error => `${error.path}: ${error.error}`).join('; ')}`); } if (includeGoal) { - const goal = result.extensions.find(extension => extension.commands.has('goal')); + const goal = result.extensions.findLast(extension => extension.commands.has('goal')); if (!goal) throw Error('客户端缺少 Pi 目标插件'); goal.handlers.set('context', [...goal.handlers.get('context') ?? [], event => ({ messages: event.messages.map(message => { @@ -71,7 +85,7 @@ export async function createPhotoCraftExtensions(host, existing = [], { includeG if (!mayContinueGoal || await mayContinueGoal(event)) return handler(event, ctx); })); } - return {...result, extensions: [...existing, ...result.extensions], resourceLoader: loader}; + return {...result, resourceLoader: loader}; } /** The SDK's tools option is also a registration allowlist, not just activation. */ diff --git a/apps/detail-agent-pi/src/production-recovery.mjs b/apps/detail-agent-pi/src/production-recovery.mjs index e0e555a3..829d1745 100644 --- a/apps/detail-agent-pi/src/production-recovery.mjs +++ b/apps/detail-agent-pi/src/production-recovery.mjs @@ -1,5 +1,4 @@ import { parseReceipt } from './receipt.mjs'; -import { setTimeout as delay } from 'node:timers/promises'; import { retryDelayMs } from '@earendil-works/pi-ai'; import { SettingsManager } from '@earendil-works/pi-coding-agent'; @@ -51,12 +50,6 @@ export function productionUsesAutomaticTools(model) { && /^claude-(?:opus-5-5|sonnet-5-5|fable-5-[12]|mythos-5-[12])(?:$|-)/u.test(model.id); } -export function isProductPending(request) { - return request?.modelRole==='detail'&&typeof request.detailSlot==='string'&&( - request.detailSlot==='production-strategy'|| - /^product\/(?:(?:strategy|strategy-audit|review|first-canvas|run)\/[a-f0-9-]{36}|(?:slot|compare)\/[a-f0-9]{64}|(?:goal|copy|copy-audit)\/[a-f0-9-]{36}\/[a-z][a-z0-9_-]*)$/i.test(request.detailSlot)); -} - // Model refusal is a terminal reply, but it authorizes no tools or canvas writes. async function closeProductRefusal(broker,record){ if(record.phase!=='received'||record.terminal!==true||typeof record.raw!=='string')return false; @@ -77,10 +70,10 @@ async function closeProductRefusal(broker,record){ return receipt.phase==='rejected'; } -export async function confirmProductionResponse(broker,record,model,tools,protocolMode='native-tools'){ +async function confirmProductionResponse(broker,record,model,tools){ const {id,requestId}=record; if(await closeProductRefusal(broker,record))return {phase:'rejected',requestId}; - const message=await parseReceipt(record,model,protocolMode,tools); + const message=await parseReceipt(record,model,'native-tools',tools); if(record.phase==='received'){ const receipt=await broker.confirm(id,record.bodyHash,message.stopReason!=='length',message.stopReason); if(receipt.phase!=='complete')return {phase:receipt.phase,requestId}; @@ -88,24 +81,23 @@ export async function confirmProductionResponse(broker,record,model,tools,protoc return message.stopReason==='length'?{phase:'rejected',requestId}:{phase:'complete',requestId,message}; } -export async function recoverProductionResponse(broker,id,model,tools,{signal,waitForResult=false,protocolMode='native-tools'}={}) { +export async function recoverProductionResponse(broker,id,model,tools) { let record=await broker.read(id); - for (const delayMs of (waitForResult?[0,2000,6000]:[0])) { - if (!['unknown','dispatched'].includes(record.phase)||signal?.aborted) break; - if (delayMs) { - const status=record.recovery?.status; - if (status===410||status===401||status===403) break; - await delay(delayMs,undefined,{signal}); + let recoveryError; + if (['unknown','dispatched'].includes(record.phase)) { + try { await broker.recover(id); } + catch (error) { + recoveryError=error; } - // A failed GET can still settle the native journal via the original idempotency key. - await broker.recover(id).catch(()=>{}); + // The native broker can settle the original journal even when the GET fails. record=await broker.read(id); } if (!['received','complete'].includes(record.phase)) { const confirmedFailure=record.phase==='failed'&&record.originalLookup?.verified===true&& record.originalLookup.status==='failed'&&record.originalLookup.requestId===record.requestId; return {phase:record.phase,requestId:record.requestId,failureCode:record.failureCode, + ...(recoveryError?{recoveryError}:null), ...(confirmedFailure?{confirmedFailure,httpStatus:record.failureHttpStatus??record.httpStatus}:null)}; } - return confirmProductionResponse(broker,{id,...record},model,tools,protocolMode); + return confirmProductionResponse(broker,{id,...record},model,tools); } diff --git a/apps/detail-agent-pi/src/request-purpose.mjs b/apps/detail-agent-pi/src/request-purpose.mjs index a75e8d27..9f262898 100644 --- a/apps/detail-agent-pi/src/request-purpose.mjs +++ b/apps/detail-agent-pi/src/request-purpose.mjs @@ -1,23 +1,20 @@ -import fs from 'node:fs/promises'; -import path from 'node:path'; - -export async function requestPurpose(host, id) { - const text = await fs.readFile(path.join(host.store.dir, 'events.jsonl'), 'utf8').catch(error => {if (error.code === 'ENOENT') return ''; throw error;}); - const events = text.split('\n').filter(Boolean).map(line => {try {return JSON.parse(line);} catch {return null;}}).filter(Boolean); - const index = events.findIndex(event => event.type === 'provider_prepared' && event.id === id && (!event.bindingHash || event.bindingHash === host.store.hash)); - if (index < 0) throw Error('原请求没有当前会话归属记录'); - const event = events[index]; - if (events.some(row=>row.id===id && row.consumption==='discarded_after_cancel')) return {kind:'cancelled',event}; - if (event.purpose === 'compaction') return {kind: 'compaction', event}; - if (['whole-detail-review','whole-detail-worker','product-goal'].includes(event.purpose)) return {kind:event.purpose,event}; - if (event.purpose === 'conversation') return {kind: 'conversation', event}; - // Legacy automatic summaries lack a durable cut-point contract. Recognize - // their purpose, but never guess a checkpoint from the returned prose. - let started = -1, finished = -1; - for (let i = 0; i < index; i++) { - if (events[i].type === 'automatic_compaction_started') started = i; - if (events[i].type === 'automatic_compaction_completed') finished = i; - } - if (started > finished) return {kind: 'legacy-compaction', event}; - return {kind: 'conversation', event}; -} +import fs from 'node:fs/promises'; +import path from 'node:path'; + +export async function requestPurpose(host, id) { + const text = await fs.readFile(path.join(host.store.dir, 'events.jsonl'), 'utf8').catch(error => {if (error.code === 'ENOENT') return ''; throw error;}); + const events = text.split('\n').filter(Boolean).map(line => { try { return JSON.parse(line); } catch { return null; } }); + let legacyCompacting = false; + for (const event of events) { + if (event?.type === 'automatic_compaction_started') legacyCompacting = true; + if (event?.type === 'automatic_compaction_completed') legacyCompacting = false; + if (event?.type !== 'provider_prepared' || event.id !== id || + (event.bindingHash && event.bindingHash !== host.store.hash)) continue; + if (events.some(row => row?.id === id && row.consumption === 'discarded_after_cancel')) return 'cancelled'; + const {purpose} = event; + if (['conversation','compaction','whole-detail-review','whole-detail-worker','product-goal'].includes(purpose)) return purpose; + // Old automatic summaries have no durable cut point. + return legacyCompacting ? 'legacy-compaction' : 'conversation'; + } + throw Error('原请求不属于当前店铺/品类会话,未查询或恢复'); +} diff --git a/apps/detail-agent-pi/src/response-audit.mjs b/apps/detail-agent-pi/src/response-audit.mjs index e9774d28..4d758953 100644 --- a/apps/detail-agent-pi/src/response-audit.mjs +++ b/apps/detail-agent-pi/src/response-audit.mjs @@ -1,22 +1,29 @@ export class InvalidToolReply extends Error {} +function toolArguments(input, serialized) { + let args=input; + if (serialized) { + try { args=JSON.parse(input); } + catch { throw new InvalidToolReply('模型工具参数未完整返回;未执行这一轮建议'); } + } + if (!args || typeof args !== 'object' || Array.isArray(args)) throw Error('模型工具参数必须为完整对象;未执行建议'); + return args; +} + /** Inspect only the original wire envelopes. Never repair JSON or interpret prose as code. */ export function auditResponse(raw, protocol) { const values = raw.split(/\r?\n/).filter(s => s.startsWith('data:')).flatMap(s => { - try { return [JSON.parse(s.slice(5).trim())]; } catch { return []; } + const data=s.slice(5).trim(); + if (!data || data==='[DONE]') return []; + try { return [JSON.parse(data)]; } + catch { throw new InvalidToolReply('模型流包含无效数据帧;未执行这一轮建议'); } }); if (protocol === 'openai-responses') { const terminal = values.findLast(v => ['response.completed', 'response.incomplete'].includes(v.type)); if (!terminal) throw Error('原响应缺少完成原因;未执行工具,保留原请求待核查'); const items = terminal.response.output; const functions = items.filter(item => item.type === 'function_call'); - const calls = functions.map(item => { - let args; - try { args = JSON.parse(item.arguments); } - catch { throw new InvalidToolReply('模型工具参数未完整返回;未执行这一轮建议'); } - if (!args || typeof args !== 'object' || Array.isArray(args)) throw Error('模型工具参数必须为完整对象;未执行建议'); - return { name: item.name, arguments: args }; - }); + const calls = functions.map(item => ({name:item.name, arguments:toolArguments(item.arguments, true)})); const text = items.filter(item => item.type === 'message') .flatMap(item => item.content ?? []).map(part => part.text ?? '').join(''); return { finishes: [terminal.type], textLength: text.length, literalEos: text.includes('<|eos|>'), calls }; @@ -46,10 +53,7 @@ export function auditResponse(raw, protocol) { } } if (!finishes.length) throw Error('原响应缺少完成原因;未执行工具,保留原请求待核查'); - for (const c of calls.values()) { - try { c.parsed = c.arguments ? JSON.parse(c.arguments) : protocol === 'anthropic-messages' ? c.input : JSON.parse(''); } - catch { throw new InvalidToolReply('模型工具参数未完整返回;未执行这一轮建议'); } - if (!c.parsed || typeof c.parsed !== 'object' || Array.isArray(c.parsed)) throw Error('模型工具参数必须为完整对象;未执行建议'); - } - return { finishes, textLength: text.length, literalEos: text.includes('<|eos|>'), calls: [...calls.values()].map(c => ({ name: c.name, arguments: c.parsed })) }; + const parsed = [...calls.values()].map(c => ({name:c.name, + arguments:c.arguments || protocol !== 'anthropic-messages' ? toolArguments(c.arguments, true) : toolArguments(c.input, false)})); + return { finishes, textLength: text.length, literalEos: text.includes('<|eos|>'), calls:parsed }; } diff --git a/apps/detail-agent-pi/src/store.mjs b/apps/detail-agent-pi/src/store.mjs index b79cb056..4cc954d1 100644 --- a/apps/detail-agent-pi/src/store.mjs +++ b/apps/detail-agent-pi/src/store.mjs @@ -104,10 +104,10 @@ export class ProjectStore { } async get(file, fallback) { const p = path.join(file==='memory.json'?this.memoryDir:this.dir, file); - if (!await exists(p)) return fallback; - return JSON.parse(await fs.readFile(p, 'utf8')); + try { return JSON.parse(await fs.readFile(p, 'utf8')); } + catch (error) { if (error.code === 'ENOENT') return fallback; throw error; } } - async remember({ key, value, evidence }, messages) { + async remember({ key, value, evidence }) { if (!/^[a-z][a-z0-9_]{0,63}$/i.test(key) || typeof value !== 'string' || value.length > 1000 || typeof evidence !== 'string' || evidence.length < 4 || evidence.length > 1000) throw Error('事实记录无效'); // Continuous discussion retains old shop history. It is not fresh consent // to promote that history into a different shop/category's current memory. @@ -141,12 +141,6 @@ export class ProjectStore { const record = executionEvent(event, {projectId:this.identity.project,...this.executionScope}, this.executionHealth ?? {}); await fs.appendFile(path.join(this.dir, 'events.jsonl'), JSON.stringify(redact(record)) + '\n', { mode: 0o600 }); } - async ownsRequest(id) { - let text; try { text = await fs.readFile(path.join(this.dir, 'events.jsonl'), 'utf8'); } catch { return false; } - return text.split('\n').some(line => { - try { const entry = JSON.parse(line); return entry.type === 'provider_prepared' && entry.id === id && (!entry.bindingHash || entry.bindingHash === this.hash); } catch { return false; } - }); - } readToolReceipt(manager, toolCallId, offset) { const entry = manager.getBranch().findLast(row => row.type === 'message' && row.message.role === 'toolResult' && row.message.toolCallId === toolCallId); diff --git a/apps/detail-agent-pi/src/workflow-execute.mjs b/apps/detail-agent-pi/src/workflow-execute.mjs index 36b5be3f..429f69c2 100644 --- a/apps/detail-agent-pi/src/workflow-execute.mjs +++ b/apps/detail-agent-pi/src/workflow-execute.mjs @@ -9,6 +9,7 @@ import { canvasReplyTimedOut } from './stdio-canvas.mjs'; // read-only recovery. Leave one minute for local preparation and final receipts. const IMAGE_OPERATION_WAIT_MS = 14 * 60_000; export const LOCAL_OPERATION_WAIT_MS = 120_000; +const receiptPhases = ['submitted','complete','failed','unknown','expired']; async function acquireWrite(host, scope, signal, checkTurn, wait, onWait) { const state=await host.canvas.read(); @@ -37,7 +38,7 @@ async function acquireWrite(host, scope, signal, checkTurn, wait, onWait) { export async function reconcileWorkflowReceipt(canvas, {run, documentId, operationId, adoption}) { const receipt=await canvas.workflowReconcile({run, documentId, operationId, ...(adoption?{adoption}:null)}); if(!receipt||receipt.run!==run||receipt.documentId!==documentId||receipt.operationId!==operationId|| - !(['submitted','complete','failed','unknown','expired'].includes(receipt.phase)||adoption&&receipt.phase==='not_executed')){ + !(receiptPhases.includes(receipt.phase)||adoption&&receipt.phase==='not_executed')){ throw Error('原画布操作的核查回执与提交身份不一致'); } return receipt; @@ -89,8 +90,9 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d const submit=async()=>{ try { return await host.canvas.workflowExecute({...args,operationId}); } catch(error) { - if(!canvasReplyTimedOut(error)||!canReconcile&&!detailBatch)throw error; + if(!canvasReplyTimedOut(error))throw error; if(canReconcile)return reconcileOriginal(); + if(!detailBatch)throw error; signal?.throwIfAborted(); checkTurn(); observedOriginal=true; @@ -145,7 +147,7 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d intent:args.intent,slotId:args.slotId,productVariantId:args.productVariantId,code:result.error.code,message}); throw new BridgeError(message,'local_precondition_failed'); } - const phases=observedOriginal?['submitted','complete','failed','unknown','expired']:['submitted']; + const phases=observedOriginal?receiptPhases:['submitted']; if (result?.operationId !== operationId || !phases.includes(result.phase)) throw Error('工作流操作提交状态无效,原操作需核查;不会重发'); await onSubmitted?.(result); if (result.phase !== 'unknown') { @@ -158,7 +160,7 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d await pause(args.intent === 'generate_candidate' ? 500 : 200, undefined, { signal }); result = await pollReceipt(); checkTurn(); - if (result?.operationId !== operationId || !['submitted','complete','failed','unknown','expired'].includes(result.phase)) throw Error('工作流操作回执无效,原操作需核查;不会重发'); + if (result?.operationId !== operationId || !receiptPhases.includes(result.phase)) throw Error('工作流操作回执无效,原操作需核查;不会重发'); } terminal = ['complete','failed','expired'].includes(result.phase); if (keepFailedCandidate && args.intent === 'generate_candidate' && ['failed','expired'].includes(result.phase) diff --git a/docs/development/xiaoyi/pi-native-and-defensive-audit.md b/docs/development/xiaoyi/pi-native-and-defensive-audit.md new file mode 100644 index 00000000..deb08a75 --- /dev/null +++ b/docs/development/xiaoyi/pi-native-and-defensive-audit.md @@ -0,0 +1,61 @@ +# 小壹 Pi 原生能力与防御性逻辑审计 + +基线为 `dcd0f13f`。该提交的 `package-lock.json` 将 `pi-coding-agent`、`pi-agent-core` 和 `pi-ai` 都锁定为 1.5.2。Git 记录显示 `f980f593` 将三者从 1.3.0 升到 1.5.2。本次对照锁定版本安装包中的 SDK 实现和类型声明。下表路径以 `apps/detail-agent-pi/src/` 为起点,行号按基线与本分支分别标注。 + +`2a337a42` 将会话和制作工具交回 Pi,`ad21604f` 让 Pi 调度制作操作,`0adb3874` 将旧整套编排隔离到 `legacy/`。此后 `d3291615` 引入原生桥结构化失败,`f8426fae` 将工程制作记录迁入 SQLite,`aa4c9868` 按原号处理到期生图。资源加载适配是当前最明确的重复实现。制作账本和画布回执已经形成独立契约,不能用会话历史代替。 + +| 可行范围 | 取舍 | +|---|---| +| 清理死代码 | 改动面小,仍保留生产和诊断各自对 `ResourceLoader` 的手写实现。 | +| 收归资源加载并清理重复分支 | 采用此方案。Pi 加载和发布资源,宿主保留资源的授权与版本绑定,原号恢复走现有账本。 | +| 将旧制作入口一并迁到 Pi 目标 | 涉及旧画布、项目记录和中断后的待处理操作,需要先完成 C 类下线条件。 | + +## A 类 · 已清理或收归 + +| 路径和位置 | 改前 | 改后 | +|---|---|---| +| `agent.mjs:531–554, 963–970` → `532–542, 953–963`;`photocraft-extension.mjs:31–74` → `31–88`;`enterprise-knowledge-cli.mjs:22–27` → `22–26` | 两个调用入口分别手写 `ResourceLoader` 及空的 `extendResources`、`reload`。 | 直接把 Pi `DefaultResourceLoader` 传给 `createAgentSession`。系统提示和注册策略使用原生 override,固定版本的企业 Skill 通过 `extendResources` 注册。同名保留当前企业发布版本,切换时从模型可见列表剔除上一绑定的企业 Skill。项目已有的原生 Skill 和提示模板继续由 Pi 加载。 | +| `agent.mjs:1034–1081` → `1028–1055`;`enterprise-context.mjs:19–28, 79–84, 153–175` → `19–28, 79–83, 152–169` | 旧入口始终只传三个参数,宿主仍为无人传入的 `drive`、`signal`、`planStrategy` 和预装生产 Skill 维护支路。企业资料层还包含无人启用的视觉资料延迟加载。 | 删除旧宿主入口的闲置参数及对应回退,发布资料照常按模板版本读取,原有且有测试覆盖的旧编排本体仍可运行。 | +| `agent.mjs:1120–1140` → `1092–1115`;`request-purpose.mjs:4–22` → `4–21`;`store.mjs:85–90, 122–128` → `85–90, 120–122` | 核查前两次读取和解析同一日志。存储读取先探测文件,任何访问错误都可被当成缺失。 | 一次扫描完成请求归属、用途和旧摘要识别。普通账本读取只对 `ENOENT` 采用缺省值,读取和解析错误继续上报。新子代理预派发事件明确携带规则域,见 `agent.mjs:606–611`。 | +| `production-recovery.mjs:54–59, 80–110` → `53–102`;`agent.mjs:1123–1142` → `1096–1114`;`desktop-host.mjs:145–156` → `145–163` | 生产原号核查有两个实现,另有无人启用的定时轮询和无调用方的请求分类器。批量核查将异常静默记为未知。 | 生产入口复用原号核查。一次 GET 后重读原账本,允许 GET 失败但原幂等账本已结清的结果生效。未知仍按原号保存。批量异常记录原本地 ID 和结构化类别,收到取消即停止继续查。 | +| `response-audit.mjs:1–55` → `1–59`;`enterprise-knowledge.mjs:95–100` → `95–116` | 流校验丢弃无法解析的数据帧,各协议重复验证工具参数。知识库用中文报错文本区分字节超限和网络失败。 | 工具参数复用同一完整对象校验,无效数据帧阻止执行。知识库仅将读取数据流的异常标为网络失败,字节限额就地处理;超限与断线有各自的处理路径。 | +| `workflow-execute.mjs:38–43, 75–99, 148–163` → `38–44, 76–101, 150–164` | 核查、失去 ACK 后的首次回执及轮询各自维护一套状态列表。 | 三个入口共用原操作状态定义。普通提交仍要求 `submitted`,采纳核查仍接受经原生确认的 `not_executed`。 | +| `agent.mjs:101, 215–226, 796–797, 1191–1198` → `101, 215–227, 783–786, 1165–1175` | 文案回执 ID 写到无人读取的宿主字段,记忆工具传入无人读取的会话消息。初始化或关闭时,清理中断可能跳过项目锁释放。 | 删除闲置回执字段和参数。文案工具仍返回已核实的 ID,记忆只引用当前规则域已冻结的用户原话。按顺序尝试释放会话、模型桥和项目锁,启动错误保持原样。 | + +## B 类 · 保留的工程边界 + +| 路径 | 保留理由 | +|---|---| +| `agent.mjs:525–542, 691–713, 899–905, 965–973, 1084–1090`、`context-usage.mjs:7–37`、`production-goal.mjs:40–79` | Pi 的 `SessionManager` 管会话树和档位,`AgentSession` 管工具循环、压缩及主循环重试,子代理使用 Pi `Agent` 与 `retryAssistantCall`,目标延续由随包的 `pi-goal` 管理。当前协议没有经桌面授权把新用户回合插入运行中的画布任务的入口。直接打开 SDK 的 `steer`/`followUp` 会绕过本轮冻结引用及写权边界。宿主只保存会话定位、项目级串行和来源口径。Pi 未给出窗口大小时,只能报告有效原使用量;切换模型或压缩后避免误用旧回执。 | +| `production-operations.mjs:265–415, 450–497, 654–685, 879–936`、`project-repository.mjs:186–196, 287–325`、`store.mjs:8–29` | 真实付费生图由原生作业与项目账本管理。先冻结请求和图位,再以原 ID 认领、派发、核查。未知、到期、已采用和明确失败分别结算。SQLite 事务、原子落盘及 Windows 上短暂文件占用的同次写入重试保护已付费请求和结果。图片作业沿用 Pi 的退避参数,授权条件仍来自原生回执。 | +| `workflow-execute.mjs:14–45, 103–145, 158–199`、`canvas-operations.mjs`、`native-tools.mjs:39–165`、`stdio-canvas.mjs:13–48, 95–104` | 原生宿主持有账户、文档、修订和写入代际。保存等待只允许重提交明确未派发的操作。提交确认丢失时核查原回合、文档和操作编号。用户接手、修订变化或切换后,旧任务没有重新获取写权的权限。 | +| `native-bridge.mjs:8–66, 148–202`、`agent.mjs:331–333, 424–466, 476–510`、`enterprise-knowledge.mjs:87–116`、`workflow-context.mjs:1–34` | 98k 凭据仍由 Rust 管理。Node 仅使用本地桥,限制模型地址和方法,持久层只记录请求正文和归属,模型可见工作流过滤私有资源。知识库凭据只在授权请求使用,资源绑定和脚本容器权限由项目边界提供。 | +| `receipt.mjs:6–50`、`response-audit.mjs:14–59`、`production-recovery.mjs:53–102`、`agent.mjs:1092–1163` | Pi 的协议解析服务于实时流,原响应完结与可供恢复由本地账本认定。工具调用必须有完整的原响应和参数。恢复只解析本地原字节或查询原号,变更建议保持待审。HTTP 410 仍可对应未知、或服务端成功但结果已过期,单独的 HTTP 状态不授权替换。 | +| `enterprise-skill-resources.mjs:9–143`、`project-tools.mjs:14–51`、`project-shell.mjs:23–115` | 资源发布身份、引用路径和脚本版本属于企业知识库约束。Pi SDK 提供资源和工具入口,脚本仍使用独立容器,以只读发布资源和限定项目目录执行。 | + +## C 类 · 下线前提 + +| 兼容项 | 活跃契约与清除条件 | +|---|---| +| `legacy/whole-detail.mjs:63–2599`,170,838 字节;同目录的 `page-copy.mjs`、`product-strategy.mjs`、`production-evidence.mjs` | Rust `jiansun.rs:2313–2340, 2380–2388` 仍把没有 `productionStages` 的旧模板送入 `wholeDetail`,由 `desktop-host.mjs:176–179` 转到旧入口。先让已支持的旧工程与模板可打开、继续单详情制作并导出。迁移或结清 `whole-detail.json` 和旧制作账本中的文案证据、候选审核、待采纳、待核查原号。对正在制作与重开项目分别验证读、写、取消、原号对账、导出和用户手改。Rust 停止发出旧入口,旧行为测试已有等价验收后,可删除旧编排和仅由该入口引用的模块。 | +| `legacy/whole-detail.mjs:100–119` 的中文审核理由 | 旧记录用自由文本区分配图不支持旧文案与结构/颜色等不合格。通用 `checks.evidence` 还涵盖其他证据失败。先在上游和持久层提供机器可识别的拒绝类型及对应文案引用,再让仍需重审的旧候选通过当前规则复核或迁移其状态。以「配图绑定改变,复验现有候选且无新生图」用例通过为删除条件。 | +| `native-bridge.mjs:82–91, 178–183` 的推理中断文案 | Rust `jiansun_pi.rs:631–669` 已为未派发的可重试准备错误提供 `dispatched:false/retryPreparation:true`,发送后连接/响应中断仍只有安全固定文案。先在原生桥提供明确的推理中断类别,覆盖有无响应头及打包二进制与 JS 的版本配对。只有两端经本地验证具备等价的 Pi 推理恢复行为后,才删除文案分支。付费生图继续走原号。 | +| `request-purpose.mjs:4–21`、`store.mjs:57–81`、`receipt.mjs:11–30` | 老请求可能缺用途标记,老会话可能还按规则目录分开,查询回来的原响应可能是 JSON。先确认活跃项目可以无损恢复会话树、旧域记忆和待核查原请求,并确认查询接口和保留账本已无 JSON 原响应。结构化 JSON 工具模式另有显式验证入口,移除前需更新其驱动和对应协议测试。 | + +## 逐文件核查索引 + +| 路径 | 核查入口 | +|---|---| +| `agent.mjs`, `photocraft-extension.mjs`, `desktop-host.mjs`, `desktop-daemon.mjs`, `production-goal.mjs`, `runtime-policy.mjs` | 会话及扩展生命周期、运行时版本、桌面配置及任务接力。 | +| `activity-event.mjs`, `context-usage.mjs`, `stream-presentation.mjs`, `usage.mjs`, `native-ui.mjs` | 活动和用量来源、流显示的非关键通知、原生用户输入。 | +| `bridge-error.mjs`, `canvas-contract.mjs`, `canvas-operations.mjs`, `native-bridge.mjs`, `native-control-client.mjs`, `native-tools.mjs`, `stdio-canvas.mjs`, `workflow-context.mjs`, `workflow-execute.mjs` | 原生协议、工作流状态、写许可、原操作核查和私有资源投影。 | +| `production-operations.mjs`, `production-repository.mjs`, `production-recovery.mjs`, `project-repository.mjs`, `store.mjs`, `request-purpose.mjs`, `response-audit.mjs`, `receipt.mjs`, `json-tool-codec.mjs` | 权威账本、请求身份及防重派发、原响应完整性。 | +| `enterprise-context.mjs`, `enterprise-knowledge.mjs`, `enterprise-knowledge-cli.mjs`, `enterprise-resource-map.mjs`, `enterprise-rules.mjs`, `enterprise-skill-resources.mjs`, `enterprise-templates.mjs`, `enterprise-tool-names.json`, `skills/product-image-sources/SKILL.md`, `production-knowledge.mjs`, `project-tools.mjs`, `project-shell.mjs`, `tool-lab.mjs` | 发布版本、资料和脚本读取、原生工具加载及脚本执行边界。 | +| `candidate-review.mjs`, `output-capabilities.mjs`, `product-copy-evidence.mjs`, `production-slots.mjs`, `project-context.mjs`, `rule-context.mjs`, `rules.mjs`, `template-mapping.mjs`, `legacy/page-copy.mjs`, `legacy/product-strategy.mjs`, `legacy/production-evidence.mjs`, `legacy/whole-detail.mjs` | 模板与产物能力、图文与候选证据、项目绑定及旧生产入口。 | + +## 本地验证 + +- Node 24.22.1。基线和本分支的 `npm --prefix apps/detail-agent-pi test` 均为 314/314 通过。 +- `npm --prefix apps/detail-agent-pi run test:skill-runtime` 为 5/5 通过,使用本机已有的 Linux Skill 容器镜像。 +- 三项离线验证分别确认企业 Skill 换绑、无效数据帧拒绝、GET 报错后按同一原请求账本结算。 +- `src/` 增加 146 行、删除 149 行,净减少 3 行。验证范围为本地 Node 与容器运行时,未调用付费模型或生图接口。