import {openXiaoyiSkills} from '../src/xiaoyi-release.mjs'; import {xiaoyiFixture} from './xiaoyi-fixture.mjs'; import { productionExportReceipt } from './production-store-fixture.mjs'; import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import { randomUUID } from 'node:crypto'; import { createAssistantMessageEventStream, getCurrentSystemPrompt, getCurrentTools } from '@earendil-works/pi-ai/compat'; import { ProjectStore } from '../src/store.mjs'; import { evaluate, ToolLab } from '../src/tool-lab.mjs'; import { openAgent } from './fake-canvas.mjs'; import { productionGoalState, recordProductionExport } from '../src/production-goal.mjs'; import { projectTools } from '../src/project-tools.mjs'; import { cleanup } from './cleanup.mjs'; const identity = () => ({ scope: 'a'.repeat(64), project: randomUUID() }); const binding = shop => ({ brandId: 'qa-brand', shopId: shop, categoryId: 'qa-desk', platform: 'qa-web', version: '1', source: 'explicit-local-qa-fixture', rules: [`仅使用${shop}的规则`] }); const root = () => fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-')); function stream(content) { const result = createAssistantMessageEventStream(); const message = { role: 'assistant', api: 'openai-completions', provider: 'jiansun-native-98k', model: 'qa-model', content, stopReason: content.some(c => c.type === 'toolCall') ? 'toolUse' : 'stop', timestamp: Date.now(), usage: { input: 10, output: 10, cacheRead: 0, cacheWrite: 0, totalTokens: 20, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } }; queueMicrotask(() => { result.push({ type: 'start', partial: message }); result.push({ type: 'done', reason: message.stopReason, message }); result.end(message); }); return result; } const info = scope => ({ accountScope: scope, model: { id: 'qa-model', protocol: 'openai-chat' }, pending: [] }); test('post-goal chat keeps the canvas production tools and reads the locked Skill without a goal command',async t=>{ const dir=await root(), id=identity(), documentId=23; t.after(()=>cleanup(dir)); const store=await ProjectStore.open(dir,id,binding('follow-up')); const entry='Skills/lighting/SKILL.md', knowledgeVersion='lamp@v4'; const template={id:'lamp',enterprise:true,knowledgeVersion,contentHash:'v4'}; const target={workspaceId:randomUUID(),outputId:'detail',variantId:randomUUID()}; const userCanvasChanges={revision:6,changedLayers:[19]}; let includeScope=true; const canvas={ async begin(){return includeScope?{context:{id:documentId,requestScope:{...target,productionTemplate:template,userCanvasChanges}}}:{};}, async workflowRead(){return {available:true,version:1,canvasFirst:true,workspaceId:target.workspaceId, outputId:target.outputId,productVariantId:target.variantId,template, productEvidence:{accountScope:id.scope,project:id.project,documentId,brief:{brandName:'灯具测试'}}};}, async detailHistory(){return [];}, }; const toolkit=['open_production_output','plan_production','write_copy_fields','read_slot_images','list_project_images', 'prepare_image_request','dispatch_image_request','delegate_image_slots','await_image_slots','check_image_slots', 'transform_slot_image','adopt_production_image','retire_production_image','read_output_screen','reconcile_image_slots']; let calls=0, host; const transport={info:info(id.scope),stream(_model,context){ const names=getCurrentTools(context.messages).map(tool=>tool.name); for(const tool of [...toolkit,'read']) assert.ok(names.includes(tool),tool); for(const tool of ['finish_production','defer_production_output','get_goal','update_goal']) { assert.ok(!names.includes(tool),tool); } const system=getCurrentSystemPrompt(context.messages); assert.match(system,/lighting<\/name>/); const messages=JSON.stringify(context.messages); assert.doesNotMatch(messages,/\/goal clear/u); const user=context.messages.findLast(message=>message.role==='user'); if(calls===0)assert.match(JSON.stringify(user),/changedLayers[^\d]+19/u); calls++; if(calls===1) return stream([{type:'toolCall',name:'read',id:'locked-read', arguments:{path:host.productionSkills.resource.skills[0].filePath}}]); if(calls===2){ assert.match(messages,/LOCKED_LAMP_FINISH/u); return stream([{type:'toolCall',name:'list_project_images',id:'image-list',arguments:{}}]); } return stream([{type:'text',text:'已核对当前项目。'}]); }}; host=await openAgent({store,canvas,transport,documentId}); const fetch=xiaoyiFixture('lamp','v4',entry,{[entry]:'---\nname: lighting\ndescription: Lamp finish.\n---\nLOCKED_LAMP_FINISH'}); await openXiaoyiSkills(store,'lamp',undefined,undefined,fetch); const locks=[]; host.openProductionKnowledge=(id,finished,pinned)=>{ locks.push([id,finished,pinned]); return openXiaoyiSkills(store,id,undefined,finished,fetch,pinned); }; try { host.manager.appendCustomEntry('pi-goal',{goal:{id:'prior-goal',status:'complete'}}); assert.equal((await host.prompt('继续查看这套成品',{resetProductionGoal:true})).rounds,3); assert.equal(productionGoalState(host.manager),null); includeScope=false; assert.equal((await host.prompt('再次查看')).rounds,1); assert.deepEqual(locks,[['lamp',undefined,knowledgeVersion],['lamp',undefined,knowledgeVersion]]); assert.equal(calls,4); } finally {await host.dispose();} }); test('historical screen images are pruned from model context and retained in the session file', async t => { const dir = await root(), id = identity(), variantId = randomUUID(), documentId = 23; const store = await ProjectStore.open(dir, id, binding('screens')); const images = ['b2xk', 'bmV3'].map(data => ({type: 'image', mimeType: 'image/png', data})); const metadata = [1, 2].map(page => ({page, revision: 3, screenStamp: `screen-${page}`, fields: ['title'], reviewRound: 0, issueHistory: []})); const canvas = { documentId, detailImages() {}, finishProduction:async input=>productionExportReceipt(input), begin: async () => ({}), read: async () => ({conversationActive: true, revision: 3}), delta: async () => {}, activity: async () => {}, end: async () => {}, imageRequest:async()=>[], workflowRead: async () => ({available: true, canvasFirst: true, version: 1, outputId: 'detail', productVariantId: variantId, template: {contentHash: 'fixture'}, totalSlots: 1, slots: [{id: 'cover', fieldId: 'cover', label: '主视觉', candidates: []}], productEvidence: {accountScope: id.scope, project: id.project, documentId, brief: {brandName: '试验品牌', categoryName: '灯具'}}}), detailRender: async ({page}) => ({...metadata[page],run:'screen-lease',writeEpoch:3,images:[images[page]]}), }; const contexts = []; const screenResults = messages => messages.filter(row => row.role === 'toolResult' && row.toolName === 'read_output_screen'); const transport = {info: info(id.scope), stream(_model, wireContext) { const page = contexts.length; contexts.push(screenResults(wireContext.messages)); return page < 2 ? stream([{type: 'toolCall', name: 'read_output_screen', id: `screen-${page}`, arguments: {page:page+1}}]) : stream([{type: 'toolCall', name: 'finish_production', id: 'finish', arguments: {revision: 3}}]); }}; const host = await openAgent({store, canvas, transport, documentId, callBudget: 3, productionGoal: {outputId: 'detail', variantId, workspaceId: randomUUID(), requestedOutputs: [{outputId: 'detail', variantId}]}}); t.after(async () => { try { await host.dispose(); } finally { await cleanup(dir); } }); assert.equal((await host.prompt('查看两屏')).production.complete, true); assert.deepEqual(contexts.map(rows => rows.length), [0, 1, 2]); assert.deepEqual(contexts[1][0].content, [{type: 'text', text: JSON.stringify(metadata[0])}, images[0]]); const [old, latest] = contexts[2]; assert.deepEqual(JSON.parse(old.content[0].text), metadata[0]); assert.equal(old.content.length, 2); assert.equal(old.content[1].type, 'text'); assert.match(old.content[1].text, /已释放 1 张.*重新调用 read_output_screen/); assert.deepEqual(latest.content, [{type: 'text', text: JSON.stringify(metadata[1])}, images[1]]); const sessionFile = host.manager.getSessionFile(); assert.equal(path.dirname(sessionFile), path.join(store.dir, 'sessions')); const entries = (await fs.readFile(sessionFile, 'utf8')).trim().split('\n').map(line => JSON.parse(line)); const recorded = screenResults(entries.filter(entry => entry.type === 'message').map(entry => entry.message)); assert.deepEqual(recorded.flatMap(({details})=>details.screens??[details]).map(({run,writeEpoch})=>({run,writeEpoch})), metadata.map(()=>({run:'screen-lease',writeEpoch:3}))); assert.deepEqual(recorded.map(row => row.content), metadata.map((details, index) => [ {type: 'text', text: JSON.stringify(details)}, images[index], ])); }); test('worker docPaths and unique basename recovery use the main agent’s locked Skill', 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 reference={fileId:'finish',revision:'r7',path:'Skills/lighting/references/finish.md'}; const knowledge={...selection,skillDirectory:'Skills',referenceSources:[reference],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:[]}; const activities=[]; const canvas={run:'skill-fixture',documentId,async detailImages(){return {images:[],referenceCount:0};},finishProduction:async input=>productionExportReceipt(input),begin:async()=>({run:'skill-fixture',conversationActive:true}), read:async()=>({conversationActive:true,revision:1}),delta:async()=>{},activity:async text=>activities.push(text),reply:async()=>{},end:async()=>{}, detailCopyFields:async()=>({fields:[]}), imageRequest:async()=>[], workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:'detail',productVariantId:variantId,totalSlots:1, slots:[{id:'lighting-slot',fieldId:'lamp',label:'灯罩近景'}], template:{id:'two-outputs',version:'v4',contentHash:'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 skillLists=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/); const location=system.match(/lighting<\/name>[\s\S]*?([^<]*SKILL\.md)<\/location>/u)[1]; const child=system.includes('完成主代理委托的图位'); if(child){ assert.doesNotMatch(system,/Use the \[fixture notes\]/); assert.equal(location,'Skills/lighting/SKILL.md'); assert.match(system,/调用 read 时填写相对于锁定资料根目录的路径。/u); assert.ok(system.includes(reference.path)); }else { assert.doesNotMatch(system,/Use the \[fixture notes\]/); assert.equal(path.isAbsolute(location),true); } const skillList=system.match(/[\s\S]*?<\/available_skills>/u)[0]; skillLists.set(child?'worker':'main',[...skillList.matchAll(/([^<]+)<\/name>/gu)].map(match=>match[1]).sort()); const steps=child?[ ['read',{path:'../../absent.md'}], ['read',{path:'../../../../../../../Skills/lighting/finish.md'}], ['read',{path:path.join(path.dirname(location),'references','finish.md')}], ]:[ ['read',{path:location}], ['delegate_image_slots',{jobs:[{slotId:'lighting-slot',goal:'查看灯具的饰面规则'}]}], ['await_image_slots',{}], ['read',{path:path.join(path.dirname(location),'references','finish.md')}], ['finish_production',{revision:1}], ]; for(const result of context.messages.filter(message=>message.role==='toolResult'&&message.toolName==='read')){ const body=result.content.map(item=>item.text).join('\n'); if(result.isError){ assert.equal(child,true); assert.match(body,/锁定资料中没有此路径.*absent.md/u); continue; } if(child&&result.toolCallId)assert.ok(result.details?.path===reference.path||body.includes('PINNED_FINISH')); reads.set(result.toolCallId,body); } 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 home=path.join(dir,'home'); for(const [base,name] of [ [path.join(home,'.agents','skills'),'personal-skill'], [path.join(store.dir,'skills'),'global-skill'], [path.join(store.dir,'workspace','.pi','skills'),'workspace-skill'], ]){ const skillDir=path.join(base,name); await fs.mkdir(skillDir,{recursive:true}); await fs.writeFile(path.join(skillDir,'SKILL.md'),`---\nname: ${name}\ndescription: An unbound test skill.\n---\nFixture only.`); } for(const key of ['HOME','USERPROFILE']){ const previous=process.env[key]; process.env[key]=home; t.after(()=>{ if(previous===undefined) delete process.env[key]; else process.env[key]=previous; }); } const host=await openAgent({store,canvas,transport,documentId,productionGoal:{outputId:'detail',variantId,workspaceId:randomUUID(),requestedOutputs:[{outputId:'detail',variantId}],skillRunDeadline:runDeadline}}); let loads=0; const entry = knowledge.skills[0]; const fetch = xiaoyiFixture(selection.templateId,'v4',entry.path,{ [entry.path]:entry.text,[reference.path]:'PINNED_FINISH: keep satin highlights.', }); host.openProductionKnowledge=(templateId)=>openXiaoyiSkills(store,templateId,undefined,undefined,(...args)=>{ loads++; return fetch(...args); }); try { assert.equal((await host.prompt('制作详情页')).production.complete,true); await t.test('production prompts only list bound and bundled skills',()=>{ assert.deepEqual(Object.fromEntries(skillLists),{ main:['lighting','product-image-sources'],worker:['lighting'], }); }); const context=await host.modelContext({}, {loadKnowledge:true}); assert.ok(context.enterpriseKnowledge.sources.every(row=>row.revision==='two-outputs@v4')); assert.equal(loads,3,'read-only context uses the original locked selection'); assert.equal([...reads.values()].filter(body=>body.includes('fixture notes')).length,1); assert.equal([...reads.values()].filter(body=>body.includes('PINNED_FINISH')).length,3); const second=await openXiaoyiSkills(store,selection.templateId,undefined,undefined, ()=>assert.fail('sibling output must use the existing lock')); assert.equal(await second.resolveFile(path.join(second.filesRoot,reference.path)),true); 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==='tool_execution_end'&&e.toolName==='read'&&e.isError).map(e=>e.error?.split('\n')[0]),['锁定资料中没有此路径:../../absent.md']); assert.ok(activities.every(text=>!text.includes('失败:读取资料')&&!text.includes('absent.md'))); assert.deepEqual(events.filter(e=>e.type==='enterprise_skill_resource_read').map(e=>[e.agent,e.path,e.revision]), [['main',entry.path,'two-outputs@v4'],['worker',reference.path,'two-outputs@v4'],['worker',reference.path,'two-outputs@v4'],['main',reference.path,'two-outputs@v4']]); } finally {await host.dispose();} }); test('a missing snapshot path stays missing until the next published round', async t => { const dir=await root(), id=identity(); t.after(()=>cleanup(dir)); const store=await ProjectStore.open(dir,id,binding('finish')); const entry='Skills/lights/SKILL.md', target='Skills/lights/references/finish.md'; const documents = {[entry]:'---\nname: lights\ndescription: Lamp production.\n---\n说明'}; const initial = xiaoyiFixture('light','v1',entry,documents); const next = xiaoyiFixture('light','v2',entry,{...documents,[target]:'The exact published reference.'}); const host={store,productionSkills:await openXiaoyiSkills(store,'light',undefined,undefined,initial)}; store.projectExportRoot=path.join(dir,'product-exports'); const {read}=await projectTools(host); await fs.writeFile(path.join(store.dir,'workspace','outside.md'),'Project note'); assert.equal((await read('main').execute('workspace',{path:'outside.md'})).content[0].text,'Project note'); await assert.rejects(read('worker').execute('outside',{path:'../../../workspace/outside.md'}),/锁定资料中没有此路径/); host.productionSkills=await openXiaoyiSkills(store,'light',undefined,undefined, ()=>assert.fail('lock must stay offline')); await assert.rejects(read('worker').execute('absent',{path:target}),/锁定资料中没有此路径/); host.productionSkills=await openXiaoyiSkills(store,'light',undefined,'finished',next); const absoluteTarget=path.join(host.productionSkills.filesRoot,target); for (const agent of ['main','worker']) { for (const file of [target,'./'+target,target.replaceAll('/','\\'),'/skills/'+target, absoluteTarget,'@'+absoluteTarget]) { assert.equal((await read(agent).execute('present',{path:file})).content[0].text,'The exact published reference.'); } for (const directory of ['', '.', '/skills', 'Skills/lights', '/skills/Skills/lights']) { const expected=directory.endsWith('/lights')?[entry,target]:[entry,target,'小壹/production.json']; assert.deepEqual((await read(agent).execute('directory',{path:directory})).details.files,expected.sort()); } const recovered=await read(agent).execute('wrong-directory',{path:'Skills/other/finish.md'}); assert.equal(recovered.details.path,target); assert.equal(recovered.content[0].text,'The exact published reference.'); for (const missing of ['/skills/Skills/lights/references/finsh.md', path.join(host.productionSkills.filesRoot,'Skills/lights/references/finsh.md')]) { await assert.rejects(read(agent).execute('missing',{path:missing}),error=>{ assert.match(error.message,/锁定资料中没有此路径/); assert.equal(error.message.split('\n')[2],target); return true; }); } const candidate=randomUUID(); await fs.writeFile(path.join(dir,'canvas-workspace.json'),JSON.stringify({candidates:[candidate]})); await assert.rejects(read(agent).execute('candidate',{path:candidate}), /这是本项目的候选编号.*按候选编号查询/); } }); test('locked knowledge read lists both paths when two documents share the requested basename',async t=>{ const dir=await root(), id=identity(); t.after(()=>cleanup(dir)); const store=await ProjectStore.open(dir,id,binding('ambiguous')); const entry='Skills/lights/SKILL.md'; const first='Skills/lights/finish.md', second='Skills/shared/finish.md'; const fetch=xiaoyiFixture('light','v1',entry,{ [entry]:'---\nname: lights\ndescription: Lamp production.\n---\n说明', [first]:'专用规则',[second]:'共用规则', }); const productionSkills=await openXiaoyiSkills(store,'light',undefined,undefined,fetch); const {read}=await projectTools({store,productionSkills}); await assert.rejects(read('worker').execute('ambiguous',{path:'../../finish.md'}),error=> error.message.includes('多个同名文件')&&error.message.includes(first)&&error.message.includes(second)); assert.equal((await read('worker').execute('exact',{path:first})).content[0].text,'专用规则'); }); test('a production turn settles normally and the next user message resumes the same goal', {timeout:10000}, async t=>{ const dir=await root(), id=identity(), documentId=13, variantId=randomUUID(); const store=await ProjectStore.open(dir,id,binding('pause')); const requestedOutputs=['sku_images','detail','main_images'].map(outputId=>({outputId,variantId})); const [sku,detail]=requestedOutputs; const blocker={kind:'missing_required_input',reason:'SKU 缺少花色',requiredAction:'请补充花色资料'}; let stage=sku.outputId, calls=0; const canvas={ run:'pause-fixture',documentId,detailImages(){}, begin:async()=>({conversationActive:true}),read:async()=>({conversationActive:true,revision:1}), delta:async()=>{},activity:async()=>{},end:async()=>{}, imageRequest:async()=>[], workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:stage, productVariantId:variantId,totalSlots:0,slots:[],template:{contentHash:stage}, productEvidence:{accountScope:id.scope,project:id.project,documentId,brief:{}}}), openProductionOutput:async target=>{stage=target.outputId;return target;}, finishProduction:async input=>({...input,pendingOutputs:requestedOutputs.slice(1),drafts:[input],finalized:false}), }; const transport={info:info(id.scope),stream(_model,context){ calls++; const tool=(name,args)=>stream([{type:'toolCall',id:'tool-'+calls,name,arguments:args}]); if(calls===1)return tool('defer_production_output',{blocker}); if(calls===2){ const defer=context.messages.find(message=>message.role==='toolResult'&&message.toolName==='defer_production_output'); assert.deepEqual(JSON.parse(defer.content[0].text).availableOutputs,requestedOutputs.slice(1)); } if(calls===3)return tool('open_production_output',detail); assert.ok(calls<=8,'a text-only continuation must stop further requests'); return stream([{type:'text',text:'已汇报进展'}]); }}; const host=await openAgent({store,canvas,transport,documentId,productionGoal:{ ...sku,workspaceId:randomUUID(),requestedOutputs,pendingOutputs:requestedOutputs, }}); t.after(async()=>{try{await host.dispose();}finally{await cleanup(dir);}}); const first=await host.prompt('制作三份成品'); assert.equal(calls,2); assert.equal(first.production.complete,false); assert.equal(productionGoalState(host.manager).status,'active'); const previousGoal = productionGoalState(host.manager).id; await host.prompt('已补资料,请继续'); assert.ok(calls>2); assert.equal(productionGoalState(host.manager).id, previousGoal); await host.prompt('从当前画布开始新一轮', {resetProductionGoal:true}); assert.notEqual(productionGoalState(host.manager).id, previousGoal); }); test('explicit tools share one Pi transcript and submit each real canvas revision', async t => { const dir=await root(), id=identity(); t.after(()=>cleanup(dir)); const store=await ProjectStore.open(dir,id,binding('goal-shop')); const variantId=randomUUID(), userText='制作详情、主图和 SKU'; const publicActivity=[],steps=[]; let stage,serial=0,revision=7,copyWrites=0; const fields=[{layer:1,field:'title',page:'screen',currentText:''}]; const canvas={ run:'goal-fixture',documentId:13,detailImages(){}, begin:async()=>({run:'goal-fixture',conversationActive:true,context:null}), read:async()=>({conversationActive:true,revision}),delta:async()=>{},end:async()=>{}, activity:async(_label,event)=>publicActivity.push(event), imageRequest:async()=>[], workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:stage, productVariantId:variantId,totalSlots:0,slots:[],template:{contentHash:stage}, productEvidence:{accountScope:id.scope,project:id.project,documentId:13,brief:{}}}), detailCopyFields:async()=>({fields:structuredClone(fields),revision}), commitDetailCopy:async(items,expected)=>{ assert.equal(expected,revision); assert.equal(items[0].expectedText,undefined); copyWrites++; revision++; fields[0].currentText=items[0].text; return {appliedLayers:[1]}; }, }; const transport={info:info(id.scope),stream(_model,context){ const instructions=getCurrentSystemPrompt(context.messages); assert.match(instructions,/锁定的企业 Skill、模板和补充规则/); assert.match(instructions,/native_catalog.*parameterDocs/); const write=context.messages.find(message=>message.role==='toolResult'&&message.toolName==='write_copy_fields'); if(write)assert.deepEqual(JSON.parse(write.content[0].text),{appliedLayers:[1],revision:8}); const call=steps.shift(); return call?stream([{type:'toolCall',name:call[0],id:'tool-'+(++serial),arguments:call[1]??{}}]): stream([{type:'text',text:'当前进展已记在项目里。'}]); }}; const workspaceId=randomUUID(); const requestedOutputs=['main_images','detail','sku_images'].map(outputId=>({outputId,variantId})); const pending=new Set(requestedOutputs.map(row=>row.outputId)); const pendingOutputs=()=>requestedOutputs.filter(row=>pending.has(row.outputId)); const bindings=[],receipts=[]; let starts=0, savedGoal; const begin=canvas.begin; canvas.begin=async()=>{starts++;return begin();}; canvas.openProductionOutput=async target=>{ const previousSave=stage?{revision,saved:true,outputId:stage}:null; stage=target.outputId; bindings.push(stage); return {...target,revision,previousSave,writeEpoch:bindings.length,pendingOutputs:pendingOutputs()}; }; canvas.finishProduction=async input=>{ if(input.scope==='all'){ assert.deepEqual([...pending],[]); return {finalized:true,completed:true,allOutputsCompleted:true,deliveryStatus:'completed',missingSlots:[],unreviewedScreens:[],pendingOutputs:[],published:receipts, productionDelivery:{path:'交付/成品',allOutputsCompleted:true}}; } assert.equal(input.outputId,stage); assert.equal(input.canvasRevision,revision); pending.delete(stage); const receipt=productionExportReceipt(input,pendingOutputs(),{finalize:false}); receipts.push(receipt); return receipt; }; const host=await openAgent({store,canvas,transport,documentId:13, productionGoal:{workspaceId,requestedOutputs,pendingOutputs:requestedOutputs,deadline:Date.now()/1000+60}}); try { steps.push( ['open_production_output',requestedOutputs[0]],['read_copy_fields'], ['write_copy_fields',{revision,items:[{layer:1,text:'木纹沿桌面延伸',sources:['P01'],pictures:[]}]}], ['finish_production',{revision:8}], ['open_production_output',requestedOutputs[1]],['finish_production',{revision:8}], ['open_production_output',requestedOutputs[2]],['finish_production',{revision:8}], ['open_production_output',requestedOutputs[1]],['finish_production',{scope:'all'}]); const result=await host.prompt(userText); assert.equal(result.production.completed,true); assert.equal(starts,1); assert.deepEqual(bindings,['main_images','detail','sku_images','detail']); assert.deepEqual(result.production.published.map(row=>row.files[0].path), ['main_images.jpg','detail.jpg','sku_images.jpg']); const entries=host.manager.getEntries(); assert.ok(entries.some(e=>e.message?.role==='user'&&JSON.stringify(e.message.content).includes(userText))); assert.ok(entries.some(e=>e.customType==='photocraft-goal-request'&&!Object.hasOwn(JSON.parse(e.content),'request'))); const completed=entries.findLast(e=>e.type==='custom'&&e.customType==='production-goal'); assert.equal(completed.data.goal.status,'complete'); savedGoal=completed.data.goal.id; }finally{await host.dispose();} assert.equal(copyWrites,1); assert.ok(publicActivity.every(row=>row.scope.documentId===canvas.documentId&&row.scope.run===canvas.run)); const copyActivities=publicActivity.filter(row=>row.toolName==='write_copy_fields'); assert.deepEqual(copyActivities.map(row=>row.status),['started','completed']); assert.equal(copyActivities[0].copyUpdates,undefined); assert.deepEqual(copyActivities[1].copyUpdates,{total:1,truncated:false,items:[{field:'screen',text:'木纹沿桌面延伸'}]}); assert.deepEqual(await recordProductionExport(store.dir,savedGoal),{recorded:true,goalId:savedGoal}); const chat=await openAgent({store,canvas,transport}); try{ assert.ok(!chat.session.getActiveToolNames().includes('finish_production')); assert.equal(chat.manager.getEntries().findLast(e=>e.type==='custom'&&e.customType==='production-goal').data.goal.status,'complete'); }finally{await chat.dispose();} }); test('a production goal completes only on the verified delivery receipt', {timeout:10000}, async t => { const dir=await root(), id=identity(), variantId=randomUUID(), documentId=13; const store=await ProjectStore.open(dir,id,binding('verified-goal')); const requestedOutputs=[{outputId:'detail',variantId,label:'详情页'},{outputId:'sku_images',variantId,label:'SKU 图'}]; const pending=new Set(requestedOutputs.map(row=>row.outputId)); const pendingOutputs=()=>requestedOutputs.filter(row=>pending.has(row.outputId)) .map(({outputId,variantId})=>({outputId,variantId})); const revision=8; let stage, serial=0, premature; const canvas={ run:'verified-goal',documentId,detailImages(){}, begin:async()=>({conversationActive:true}),read:async()=>({conversationActive:true,revision}), delta:async()=>{},activity:async()=>{},end:async()=>{},imageRequest:async()=>[], detailCopyFields:async()=>({fields:[],revision}), workflowRead:async()=>({available:true,version:1,canvasFirst:true,outputId:stage, productVariantId:variantId,totalSlots:0,slots:[],template:{contentHash:stage}, productEvidence:{accountScope:id.scope,project:id.project,documentId,brief:{}}}), openProductionOutput:async target=>{stage=target.outputId;return {...target,revision,pendingOutputs:pendingOutputs()};}, finishProduction:async input=>{ if(input.scope==='all')return {finalized:true,completed:pending.size===0,allOutputsCompleted:pending.size===0, deliveryStatus:pending.size===0?'completed':'partial_delivered',missingSlots:[],unreviewedScreens:[], pendingOutputs:pendingOutputs(),published:[],productionDelivery:{path:'交付/成品',allOutputsCompleted:pending.size===0}}; pending.delete(stage); return productionExportReceipt(input,pendingOutputs(),{finalize:false}); }, }; const steps=[ ['open_production_output',{outputId:'detail',variantId}],['finish_production',{revision}], ['tool_search',{query:'update_goal'}], ['update_goal',{status:'complete'}], ['open_production_output',{outputId:'sku_images',variantId}],['finish_production',{revision}], ['finish_production',{scope:'all'}], ]; const transport={info:info(id.scope),stream(_model,context){ const tools=getCurrentTools(context.messages); assert.ok(tools.some(tool=>tool.name==='finish_production')); assert.ok(!tools.some(tool=>tool.name==='update_goal')); assert.doesNotMatch(tools.find(tool=>tool.name==='codemode').description,/update_goal/u); assert.doesNotMatch(getCurrentSystemPrompt(context.messages),/update_goal/u); const search=context.messages.findLast(message=>message.role==='toolResult'&&message.toolName==='tool_search'); if(search) { assert.equal(search.isError,false); assert.doesNotMatch(search.content.map(part=>part.text).join(''),/update_goal/u); } premature??=context.messages.findLast(message=>message.role==='toolResult'&&message.toolName==='update_goal'); const call=steps.shift(); return call?stream([{type:'toolCall',name:call[0],id:'tool-'+(++serial),arguments:call[1]}]): stream([{type:'text',text:'已交付'}]); }}; const host=await openAgent({store,canvas,transport,documentId, productionGoal:{workspaceId:randomUUID(),requestedOutputs,pendingOutputs:requestedOutputs}}); t.after(async()=>{try{await host.dispose();}finally{await cleanup(dir);}}); const result=await host.prompt('制作详情和 SKU'); assert.equal(premature.isError,true); assert.doesNotMatch(premature.content.map(part=>part.text).join(''),/整套成品已核验完成/u); assert.equal(result.production.completed,true); assert.equal(productionGoalState(host.manager).status,'complete'); }); test('generated tools have no Node/FS/network and cannot run forever', async () => { assert.deepEqual(await evaluate('function main(){return [typeof process,typeof require,typeof fetch,typeof Deno]}', {}), ['undefined', 'undefined', 'undefined', 'undefined']); await assert.rejects(evaluate('function main(){while(true){}}', {}, 30), /隔离工具失败/); await assert.rejects(evaluate('function main(){return import("node:fs")}', {}), /工具必须返回|隔离工具失败/); assert.equal(await evaluate('function main(a){return a.x+1}', { x: 2 }), 3); }); test('only tested immutable tool versions execute; failed tests cannot replace', async () => { const dir = await root(), lab = new ToolLab(dir); const args = { name: 'add_one', description: 'QA', source: 'function main(i){return i+1}', tests: [{ input: 0, expected: 1 }, { input: -1, expected: 0 }, { input: 10, expected: 11 }] }; const saved = await lab.develop(args); assert.equal((await lab.run('add_one', 4)).result, 5); await assert.rejects(lab.develop({ ...args, source: 'function main(i){return i+2}' }), /测试1未通过/); assert.equal((await lab.run('add_one', 4)).version, saved.version); await assert.rejects(lab.run('../other', {}), /名称无效/); await cleanup(dir); }); test('snapshots, memories, sessions are isolated by account/shop/category/version', async () => { const dir = await root(), id = identity(); const a = await ProjectStore.open(dir, id, binding('A')); await a.recordUserEvidence('产品颜色是米白'); await a.remember({ key: 'color', value: '米白', evidence: '颜色是米白' }, [{ role: 'user', content: '产品颜色是米白' }]); await a.recordUserEvidence('产品改为胡桃色'); await a.remember({ key: 'color', value: '胡桃', evidence: '改为胡桃色' }, [{ role: 'user', content: '产品改为胡桃色' }]); assert.equal((await a.context()).confirmedMemory.color.previous, '米白'); await assert.rejects(a.remember({ key: 'certified', value: '已认证', evidence: '已认证测试' }, []), /用户已明确/); const b = await ProjectStore.open(dir, id, binding('B')); assert.notEqual(a.dir, b.dir); assert.deepEqual((await b.context()).confirmedMemory, {}); const restored = await ProjectStore.open(dir, id, binding('A')); assert.equal((await restored.context()).confirmedMemory.color.value, '胡桃'); const other = await ProjectStore.open(dir, { ...id, scope: 'b'.repeat(64) }, binding('A')); assert.deepEqual((await other.context()).confirmedMemory, {}); await cleanup(dir); }); test('actual Pi SDK executes memory tools, persists full transcript and reads project facts explicitly after restart', async () => { const dir = await root(), id = identity(), store = await ProjectStore.open(dir, id, binding('A')); let calls = 0; const transport = { info: info(id.scope), stream(model, ctx) { assert.doesNotMatch(getCurrentSystemPrompt(ctx.messages), /"shopId":"A"/); calls++; if (calls === 1) return stream([{ type: 'toolCall', id: 'qa-call-1', name: 'memory_set', arguments: { key: 'color', value: '胡桃色', evidence: '颜色是胡桃色' } }]); if (calls === 3) return stream([{ type:'toolCall', id:'qa-read-context', name:'context_read', arguments:{} }]); if (calls === 4) { const evidence=ctx.messages.find(message=>message.role==='toolResult'&&message.toolName==='context_read'); assert.match(evidence.content[0].text, /"shopId":"A"/); assert.match(evidence.content[0].text, /"color"/); } return stream([{ type: 'text', text: '已记录胡桃色' }]); } }; let host = await openAgent({ store, transport }); assert.deepEqual(host.session.getActiveToolNames().sort(), ['bash','canvas_edit','canvas_read','canvas_template_image','codemode','context_read','edit','find','grep','ls','memory_search','memory_set', 'native_call','native_catalog','native_reconcile','read','tool_search','workflow_execute','workflow_navigate','workflow_propose','workflow_read','write']); await host.prompt('这个测试产品颜色是胡桃色,请记住。'); const messages = host.session.messages.length, entries = host.manager.getEntries().filter(entry=>entry.type==='message'); await host.dispose(); host = await openAgent({ store, transport }); assert.equal(host.session.messages.length, messages); assert.equal(JSON.stringify(host.manager.getEntries().filter(entry=>entry.type==='message')),JSON.stringify(entries)); await host.prompt('继续:颜色是什么?'); assert.equal(host.session.settingsManager.getRetryEnabled(), false); await host.dispose(); await cleanup(dir); }); test('an unresolved inference does not block a new prompt or replay an old tool', async () => { const dir = await root(), id = identity(), store = await ProjectStore.open(dir, id, binding('A')); let calls = 0; const transport = { info: info(id.scope), stream() { calls++; return stream([{ type:'text',text:'x' }]); } }; const broker = { info: async () => ({ ...info(id.scope), pending: [{ id: 'original', phase: 'unknown' }] }) }; const host = await openAgent({ store, broker, transport }); assert.equal((await host.prompt('新一轮请求')).text,'x'); assert.equal(calls, 1); await host.dispose(); await cleanup(dir); }); test('references enter the actual Pi user message as image and quoted text parts', async () => { const dir = await root(), id = identity(), store = await ProjectStore.open(dir, id, binding('A')); const delivered = []; const host = await openAgent({ store, transport: { info: info(id.scope), stream(_model, context) { delivered.push(context.messages.findLast(message => message.role === 'user')); return stream([{ type: 'text', text: '收到引用' }]); } } }); try { const data = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//2wBDAQ4ODhMREyYVFSZPNS01T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0//wAARCAAIAAgDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAABAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCGAAoP/9k='; await host.prompt('图里有什么?', { referenceContent: [{ label: '主图', image: data }, { label: '标题', text: '朴然 Pro' }] }); assert.equal(delivered.length, 1); const { content } = delivered[0]; assert.deepEqual(content.find(part => part.type === 'image'), { type: 'image', mimeType: 'image/jpeg', data }); assert.match(content[0].text, /图里有什么/); assert.match(content[0].text, /朴然 Pro/); } finally { await host.dispose(); await cleanup(dir); } }); test('各类制作助手接收锁定入口索引,正文由工具按需读取', async t => { const dir=await root(), id=identity(), store=await ProjectStore.open(dir,id,binding('A')); t.after(()=>cleanup(dir)); const requests=[]; const host=await openAgent({store,transport:{info:info(id.scope),stream(_model,context){ requests.push({system:getCurrentSystemPrompt(context.messages),tools:getCurrentTools(context.messages)}); return stream([{type:'text',text:'已收到制作任务'}]); }}}); try { const entrypoint='SKILL.md', supplement='补充.md'; const entry='---\nname: guide\ndescription: Demo guide.\n---\n完整模板内容'; const extra='补充说明第一行\n补充说明末行'; host.productionSkills=await openXiaoyiSkills(store,'demo',undefined,undefined, xiaoyiFixture('demo','1',entrypoint,{[entrypoint]:entry,[supplement]:extra,'附录.md':'按需资料'},{supplement})); for(const [slot,role] of [['screen-1','整屏复核'],['slot-1','候选复核'],['slot-2','图位制作']]){ await host.runDetailAgent(slot,role,'当前任务',[],[]); const request=requests.at(-1); assert.ok(request.system.startsWith(role)); assert.ok(!request.system.includes(JSON.stringify(host.productionSkills.execution))); assert.ok(!request.system.includes(entry)); assert.ok(!request.system.includes(extra)); assert.ok(request.tools.some(tool=>tool.name==='read')); } assert.equal(requests.length,3); } finally { await host.dispose(); } }); test('an SDK transport error does not start a second retry loop', async () => { const dir = await root(), id = identity(), store = await ProjectStore.open(dir, id, binding('A')); let calls = 0; const host = await openAgent({ store, transport: { info: info(id.scope), stream(model) { calls++; if (calls>1) return stream([{type:'text',text:'已接续。'}]); const out = createAssistantMessageEventStream(); const error = { role: 'assistant', api: model.api, provider: model.provider, model: model.id, content: [], stopReason: 'error', errorMessage: 'HTTP 503 overload; original outcome unknown', timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } }; queueMicrotask(() => { out.push({ type: 'error', reason: 'error', error }); out.end(error); }); return out; } } }); await assert.rejects(host.prompt('继续处理'),/original outcome unknown/); assert.equal(calls, 1); assert.ok(host.manager.getEntries().some(e => e.type === 'message' && e.message.role === 'user')); await host.dispose(); await cleanup(dir); });