WuYongJie 51c644d7b5 合入精修开关、时间预算、每图位候选总数上限与整屏复核轮次(R5-Z70)
# Conflicts:
#	apps/detail-photocraft/apps/photocraft/src/jiansun_backend.rs
#	apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs
2026-11-30 15:50:28 +08:00

575 lines
36 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 { piGoalState, 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('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 = [0, 1].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], 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}}])
: 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.map(row => row.content), metadata.map((details, index) => [
{type: 'text', text: JSON.stringify(details)}, images[index],
]));
});
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 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 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()=>{},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 missing='当前小壹知识版本没有此路径:Skills/lighting/finish.md\n登记路径:\n'+reference.path;
const transport={info:info(id.scope),stream(_model,context){
const system=getCurrentSystemPrompt(context.messages);
assert.match(system,/<name>lighting<\/name>/);
assert.doesNotMatch(system,/PINNED_FINISH/);
const location=system.match(/<name>lighting<\/name>[\s\S]*?<location>([^<]*SKILL\.md)<\/location>/u)[1];
const child=system.includes('完成主代理委托的图位');
if(child){
assert.match(system,/Use the \[fixture notes\]/);
assert.equal(location,'Skills/lighting/SKILL.md');
assert.match(system,/调用 read 时填写相对于锁定资料根目录的路径。/u);
}else {
assert.doesNotMatch(system,/Use the \[fixture notes\]/);
assert.equal(path.isAbsolute(location),true);
}
const skillList=system.match(/<available_skills>[\s\S]*?<\/available_skills>/u)[0];
skillLists.set(child?'worker':'main',[...skillList.matchAll(/<name>([^<]+)<\/name>/gu)].map(match=>match[1]).sort());
const steps=child?[
['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.equal(body,missing);
}else 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,2);
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),[missing]);
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'],['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);
for (const agent of ['main','worker']) {
assert.equal((await read(agent).execute('present',{path:target})).content[0].text,'The exact published reference.');
for (const directory of ['', '.', 'Skills/lights']) {
const expected=directory==='Skills/lights'?[entry,target]:[entry,target,'小壹/production.json'];
assert.deepEqual((await read(agent).execute('directory',{path:directory})).details.files,expected.sort());
}
await assert.rejects(read(agent).execute('same-name',{path:'Skills/other/finish.md'}),
error=>error.message.endsWith(target));
await assert.rejects(read(agent).execute('same-parent',{path:'Skills/lights/references/missing.md'}),
error=>error.message.endsWith(target));
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}),
/这是本项目的候选编号.*list_project_images.*sourceCandidateId/);
}
});
test('Pi pauses after a continuation without tools and resumes on a new user request', {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,5,'tool activity allows the following continuation');
assert.equal(first.production.stageStatus,'paused');
assert.equal(first.production.outputId,detail.outputId);
assert.deepEqual(first.production.pause,{reason:blocker.reason,requiredAction:blocker.requiredAction});
assert.equal(piGoalState(host.manager).status,'paused');
const previousGoal = piGoalState(host.manager).id;
host.productionGoal.drafts=[];
const next=await host.prompt('已补资料,请继续');
assert.equal(calls,6);
assert.equal(next.production.stageStatus,'paused');
assert.deepEqual(next.production.pause,{reason:'已汇报进展'});
assert.equal(piGoalState(host.manager).status,'paused');
assert.equal(piGoalState(host.manager).id, previousGoal);
await host.prompt('从当前画布开始新一轮', {resetProductionGoal:true});
assert.ok(calls > 6);
assert.notEqual(piGoalState(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 查原生命令与参数/);
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,pendingOutputs:[],published:receipts};
}
assert.equal(input.outputId,stage);
assert.equal(input.canvasRevision,revision);
pending.delete(stage);
const receipt={...productionExportReceipt(input,pendingOutputs()),finalized:false,completed: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.deepEqual(entries.filter(e=>e.type==='custom_message'&&e.customType==='photocraft-goal-request').map(e=>JSON.parse(e.content).request),[userText]);
const completed=entries.findLast(e=>e.type==='custom'&&e.customType==='pi-goal');
assert.equal(completed.data.goal.status,'complete');
savedGoal=completed.data.goal.id;
await host.session.prompt('/goal pause');
assert.equal(piGoalState(host.manager).status,'paused');
}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.equal(chat.session.getToolDefinition('finish_production'),undefined);
assert.equal(chat.manager.getEntries().findLast(e=>e.type==='custom'&&e.customType==='pi-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,pendingOutputs:pendingOutputs(),published:[]};
pending.delete(stage);
return {...productionExportReceipt(input,pendingOutputs()),finalized:false,completed: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.match(premature.content.map(part=>part.text).join(''),/尚未经核验[^]*待交付:SKU 图。/u);
assert.equal(result.production.completed,true);
assert.equal(piGoalState(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.getEntryCount();
await host.dispose();
host = await openAgent({ store, transport });
assert.equal(host.session.messages.length, messages);
assert.equal(host.manager.getEntryCount(), entries);
await host.prompt('继续:颜色是什么?');
assert.equal(host.session.settingsManager.getRetryEnabled(), true);
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}));
const prefix=host.productionSkills.workerGuidePrefix;
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(prefix+role));
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('actual Pi SDK retries an overloaded inference with the default budget', 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;
} } });
assert.equal((await host.prompt('继续处理')).text,'已接续。');
assert.equal(calls, 2);
assert.ok(host.manager.getEntries().some(e => e.type === 'message' && e.message.role === 'user'));
await host.dispose(); await cleanup(dir);
});