558 lines
35 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 { 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 } 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 { EnterpriseContext } from '../src/enterprise-context.mjs';
import { projectTools } from '../src/project-tools.mjs';
import { openEnterpriseSkills } from '../src/enterprise-skill-resources.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']}));
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,detailImages(){},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'+
'锁定资料入口:\nSkills/lighting/SKILL.md\n同名文件:\nSkills/lighting/references/finish.md';
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 documents=[];
host.enterpriseContext=new EnterpriseContext(store,{
call:async()=>assert.fail('a reference published with a version needs no catalogue search'),
readDocument:async(fileId,revision)=>{
documents.push([fileId,revision]);
return {result:{revision,text:'PINNED_FINISH: keep satin highlights.'}};
},
});
host.enterpriseContext.load=async()=>{loads++;return knowledge;};
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.deepEqual(context.enterpriseKnowledge.sources.map(row=>row.revision),['r4','r7']);
assert.equal(loads,1,'read-only context uses the original locked selection');
assert.equal([...reads.values()].filter(body=>body.includes('fixture notes')).length,1);
assert.equal([...reads.values()].filter(body=>body.includes('PINNED_FINISH')).length,2);
assert.deepEqual(documents,[['finish','r7']]);
const second=await openEnterpriseSkills(store,selection,()=>{throw Error('run must use the first locked version');});
assert.equal(second.files.find(file=>file.fileId==='finish').revision,'r7');
const mainSelection={...selection,outputId:'main_images',releaseId:'main-v4'};
const mainBinding=await openEnterpriseSkills(store,mainSelection,
()=>assert.fail('sibling output must use the existing lock'),
()=>assert.fail('sibling output must use the existing pin'));
assert.equal(mainBinding.resource.skills[0].filePath,second.resource.skills[0].filePath);
assert.equal(await mainBinding.resolveFile(path.join(path.dirname(mainBinding.resource.skills[0].filePath),'references','finish.md')),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.fileId,e.revision]),
[['main','root','r4'],['worker','finish','r7'],['main','finish','r7']]);
} finally {await host.dispose();}
});
test('native read reports an unavailable linked document and can read it once published', async t => {
const dir=await root(), id=identity();
t.after(()=>cleanup(dir));
const store=await ProjectStore.open(dir,id,binding('finish'));
const selection={outputId:'detail'};
const knowledge={skillDirectory:'Skills',skills:[{fileId:'root',revision:'r4',kind:'skill',path:'Skills/lights/SKILL.md',
text:'---\nname: lights\ndescription: Lamp production.\n---\n[Finish](references/missing.md)'}],
rules:[{fileId:'other',revision:'r1',kind:'rule',path:'Skills/other/missing.md',text:'Other locked rule.'}]};
const target='Skills/lights/references/missing.md';
let published=false, searchCalls=0, reads=0;
const client=new EnterpriseContext(store,{
async call(name,{directory,query}) {
assert.equal(name,'search_files');
assert.equal(directory,'Skills/lights/references');
assert.equal(query,'missing.md');
searchCalls++;
return {result:{entries:[
{id:'wrong',revision:'v1',path:'Skills/lights/unrelated/missing.md'},
...(published?[{id:'exact',revision:'r1',path:target}]:[]),
]}};
},
async readDocument(fileId,revision) {
assert.deepEqual([fileId,revision],['exact','r1']);
reads++;
return {result:{revision,text:'The exact published reference.'}};
},
});
const host={store,productionSkills:await openEnterpriseSkills(store,selection,async()=>knowledge,
(relative,lock)=>client.loadReference(relative,{...lock,read:execute=>execute()}))};
const {read}=await projectTools(host);
const skill=host.productionSkills.resource.skills[0].filePath;
const readMain=read('main'), readWorker=read('worker');
const file=path.join(path.dirname(skill),'references','missing.md');
await fs.writeFile(path.join(store.dir,'workspace','outside.md'),'Only the main agent can read this.');
const outside='.././../../workspace/outside.md';
await assert.rejects(readWorker.execute('outside',{path:outside}),{
message:`「${outside}」不在当前项目锁定的企业资料中。\n锁定资料入口:\nSkills/lights/SKILL.md`,
});
await assert.rejects(readWorker.execute('wrong-directory',{path:path.join(path.dirname(skill),'missing.md')}),{
message:'「Skills/lights/missing.md」不在当前项目锁定的企业资料中。\n锁定资料入口:\nSkills/lights/SKILL.md\n'+
'同名文件:\nSkills/other/missing.md\nSkills/lights/references/missing.md',
});
assert.equal((await readMain.execute('workspace',{path:'outside.md'})).content[0].text,'Only the main agent can read this.');
await assert.rejects(readMain.execute('absent',{path:file}),/Skills\/lights\/SKILL\.md.*Skills\/lights\/references\/missing\.md/u);
await assert.rejects(fs.access(file),{code:'ENOENT'});
await assert.rejects(readMain.execute('unrelated',{path:path.join(path.dirname(file),'unrelated.md')}),/本项目工作目录之外/u);
assert.equal(searchCalls,1);
assert.match((await readMain.execute('entry',{path:skill})).content[0].text,/Lamp production/u);
assert.match((await readWorker.execute('absolute-entry',{path:skill})).content[0].text,/Lamp production/u);
published=true;
for(const reply of await Promise.all([readMain.execute('present',{path:file}),readWorker.execute('same',{path:file})])){
assert.equal(reply.content[0].text,'The exact published reference.');
}
assert.deepEqual([searchCalls,reads],[2,1]);
});
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<=6,'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');
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');
});
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,/由你决定[^。]*顺序、并行和返工/);
assert.match(instructions,/命令行编修可用等价的画布命令完成/);
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,dispatchReady:[]});
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}],
['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){
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('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);
});