gongxiangp2/apps/detail-agent-pi/test/native-wire.test.mjs

992 lines
58 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 { BridgeError } from '../src/bridge-error.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 { EventEmitter } from 'node:events';
import { PassThrough } from 'node:stream';
import { ProjectStore } from '../src/store.mjs';
import { DetailPiAgent } from '../src/agent.mjs';
import { auditResponse, InvalidToolReply } from '../src/response-audit.mjs';
import { cleanup } from './cleanup.mjs';
import { decodeToolReply } from '../src/json-tool-codec.mjs';
import { normalizeContext } from '@earendil-works/pi-ai/compat';
import { createAssistantMessageEventStream, openAICompletionsApi, openAIResponsesApi } from '@earendil-works/pi-ai/compat';
import { SessionManager } from '@earendil-works/pi-coding-agent';
import { atomic } from '../src/store.mjs';
import { Native98kBroker } from '../src/native-bridge.mjs';
import { StdioCanvas } from '../src/stdio-canvas.mjs';
import { projectTools } from '../src/project-tools.mjs';
import { parseReceipt } from '../src/receipt.mjs';
import { createPhotoCraftExtensions } from '../src/photocraft-extension.mjs';
import { callProductionTool } from '../src/production-goal.mjs';
import { productionStore } from './production-store-fixture.mjs';
import { Value } from '@sinclair/typebox/value';
import { canvasReadParameters, canvasReadQuery } from '../src/canvas-contract.mjs';
test('native request validation can prove that no model was dispatched', async t => {
const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-wire-'));
t.after(() => cleanup(profile));
for (const rejectedBeforeDispatch of [true, false]) {
const child = new EventEmitter();
child.stdin = new PassThrough();
child.stdout = new PassThrough();
child.stderr = new PassThrough();
child.stdin.once('finish', () => {
child.stdout.end();
child.stderr.end();
child.emit('close',0);
});
child.stdin.on('data', buffer => {
assert.equal(JSON.parse(buffer.toString()).method,'request');
const response = {type:'error',error:'本机拒绝该操作',
...(rejectedBeforeDispatch ? {dispatched:false} : {})};
child.stdout.write(JSON.stringify(response)+'\n');
});
const broker = new Native98kBroker({project:randomUUID(),profile,spawnProcess:() => child});
broker.scope='fixture';
try {
const round=broker.round();
await assert.rejects(round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}),/本机拒绝该操作/);
assert.equal(broker.hasUnconfirmedRequest,!rejectedBeforeDispatch);
} finally { await broker.close(); }
}
});
test('the native bridge reports a retryable preflight to Pi without replaying it', async t => {
const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-wire-'));
t.after(() => cleanup(profile));
const child = new EventEmitter();
child.stdin = new PassThrough();
child.stdout = new PassThrough();
child.stderr = new PassThrough();
child.stdin.once('finish', () => {
child.stdout.end();
child.stderr.end();
child.emit('close', 0);
});
const requests=[];
child.stdin.on('data', buffer => {
requests.push(JSON.parse(buffer.toString()));
child.stdout.write(JSON.stringify({type:'error',error:'客户端准备模型请求失败,本次未发送',
dispatched:false,retryPreparation:true})+'\n');
});
const broker=new Native98kBroker({project:randomUUID(),profile,spawnProcess:()=>child});
broker.scope='fixture';
try {
const round=broker.round({inference:true});
await assert.rejects(round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}),/network error/);
assert.equal(requests.length,1);
assert.equal(requests[0].id,round.id);
assert.equal(requests[0].inference,true);
assert.equal(broker.hasUnconfirmedRequest,false);
} finally {await broker.close();}
});
test('the native bridge posts only to the endpoint bound to the selected route', async () => {
const route = randomUUID();
const broker = new Native98kBroker({project:randomUUID(),invocationHeaders:{'X-Relay-Route-Option':route}});
const requests = [];
broker.start = async (method, input, event) => {
requests.push({method, input});
event({type:'headers',status:200,headers:{'content-type':'text/event-stream'}});
return {phase:'received'};
};
const round = broker.round();
await round.fetch('https://api.vip98k.com/v1/responses', {method:'POST',body:'{}'});
assert.equal(requests[0].input.invocationPath,'/v1/responses');
assert.deepEqual(requests[0].input.invocationHeaders,{'X-Relay-Route-Option':route});
await assert.rejects(round.fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'}),/禁止自动重发/);
assert.equal(requests.length,1);
});
test('parallel production brokers inherit the native turn selection without revalidating it', async () => {
const project = randomUUID(), selectionId = randomUUID();
const route = {'X-Relay-Route-Option':randomUUID()};
const parent = new Native98kBroker({project,modelRole:'detail'});
parent.start = async method => {
assert.equal(method,'info');
return {accountScope:'fixture',selectionId,invocationHeaders:route};
};
await parent.info();
const received=[];
await Promise.all(['intro','design'].map(async slot => {
const worker=parent.forDetailSlot(slot);
assert.equal(worker.scope,'fixture');
worker.start=async(method,input,event)=>{
assert.equal(method,'request');
received.push({slot,input});
event({type:'headers',status:200,headers:{'content-type':'text/event-stream'}});
return {phase:'received'};
};
await worker.round({inference:true}).fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'});
}));
assert.equal(received.length,2);
assert.ok(received.every(row=>row.input.selectionId===selectionId));
assert.ok(received.every(row=>row.input.invocationHeaders['X-Relay-Route-Option']===route['X-Relay-Route-Option']));
parent.bind({project,scope:'fixture',modelRole:'detail'});
assert.equal(parent.forDetailSlot('new-turn').selectionId,undefined);
});
test('Pi sends an inline image and decodes a streamed function on both OpenAI APIs', async () => {
const pixel = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jNHsAAAAASUVORK5CYII=';
const tool = {name:'record_color',description:'Record the observed color',parameters:{type:'object',properties:{color:{type:'string'}},required:['color']}};
const args = '{"color":"green"}';
const call = {id:'fc_route',type:'function_call',status:'completed',call_id:'call_route',name:tool.name,arguments:args};
const event = (type, fields) => 'event: ' + type + '\ndata: ' + JSON.stringify({type,...fields}) + '\n\n';
const frame = value => 'data: ' + JSON.stringify(value) + '\n\n';
for (const responses of [false,true]) {
const api = responses ? 'openai-responses' : 'openai-completions';
const adapter = responses ? openAIResponsesApi() : openAICompletionsApi();
const model = {id:responses?'gpt-6.1-sol':'gemini-3.8-flash',api,provider:'jiansun-native-98k',input:['text','image'],
baseUrl:'https://api.vip98k.com/v1',name:api,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},
compat:{supportsStore:false,supportsReasoningEffort:false}};
const chunk = (delta,finish_reason=null) => frame({id:'synthetic',model:model.id,choices:[{index:0,delta,finish_reason}]});
const raw = responses
? event('response.output_item.added',{output_index:0,item:{...call,arguments:'',status:'in_progress'}}) +
event('response.function_call_arguments.delta',{output_index:0,delta:args}) +
event('response.output_item.done',{output_index:0,item:call}) +
event('response.completed',{response:{model:model.id,status:'completed',output:[call]}})
: chunk({tool_calls:[{index:0,id:'call_route',type:'function',function:{name:tool.name,arguments:'{"color":'}}]}) +
chunk({tool_calls:[{index:0,function:{arguments:'"green"}'}}]}) +
chunk({},'tool_calls')+'data: [DONE]\n\n';
let sent = 0;
const stream = adapter.streamSimple(model,normalizeContext({tools:[tool],messages:[
{role:'user',content:[{type:'text',text:'Read the image and call record_color'},{type:'image',mimeType:'image/png',data:pixel}],timestamp:0}
]}),{apiKey:'local-test',maxRetries:0,maxTokens:256,fetch:async (url,init)=>{
sent++;
assert.equal(new URL(url).pathname,responses?'/v1/responses':'/v1/chat/completions');
const payload=JSON.parse(init.body);
assert.equal(payload.stream,true);
const picture=(responses?payload.input:payload.messages).find(item=>item.role==='user').content[1];
assert.equal(responses?picture.image_url:picture.image_url.url,'data:image/png;base64,'+pixel);
assert.equal(responses?payload.tools[0].name:payload.tools[0].function.name,tool.name);
return new Response(raw,{headers:{'content-type':'text/event-stream'}});
}});
for await (const _event of stream) {}
const result=await stream.result();
assert.equal(sent,1);
assert.equal(result.stopReason,'toolUse',result.errorMessage);
assert.deepEqual(result.content.find(item=>item.type==='toolCall').arguments,{color:'green'});
assert.deepEqual(auditResponse(raw,responses?'openai-responses':'openai-chat').calls,[{name:tool.name,arguments:{color:'green'}}]);
}
});
test('a retained Responses function call is audited and decoded without a network fetch', async () => {
const model = {id:'route-model',api:'openai-responses',provider:'jiansun-native-98k',input:['text','image'],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}};
const response = {model:model.id,status:'completed',output:[
{id:'fc_route',type:'function_call',status:'completed',call_id:'call_route',name:'record_color',arguments:'{"color":"green"}'},
]};
const record = {phase:'received',terminal:true,model:{id:model.id,protocol:'openai-responses'},raw:Buffer.from(JSON.stringify(response)).toString('base64')};
const message = await parseReceipt(record,model,'native-tools',[]);
assert.equal(message.stopReason,'toolUse');
assert.deepEqual(message.content[0].arguments,{color:'green'});
response.output[0].arguments = '{"color":';
await assert.rejects(parseReceipt({...record,raw:Buffer.from(JSON.stringify(response)).toString('base64')},model,'native-tools',[]));
});
test('an explicit stream rate limit settles the attempt without confirm or replay', async () => {
const broker = new Native98kBroker({project:randomUUID()});
const calls = [];
broker.start = async (method, _input, event) => {
calls.push(method);
event({type:'headers',status:200,headers:{'content-type':'text/event-stream'}});
return {phase:'failed',failureCode:'rate_limit_exceeded'};
};
const round = broker.round();
await round.fetch('https://api.vip98k.com/v1/chat/completions', {method:'POST',body:'{}'});
assert.deepEqual(await round.finish(false,'error'),{phase:'failed',failureCode:'rate_limit_exceeded'});
assert.deepEqual(calls,['request']);
});
const sse = (delta, finish) => `data: ${JSON.stringify({ id: 'wire', model: 'qa', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\ndata: [DONE]\n\n`;
async function setup(reply, finish = async valid => { assert.equal(valid, true); return {phase:'complete'}; }, production, recovery = production) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-'));
const scope = 'f'.repeat(64), store = await ProjectStore.open(dir, { scope, project: randomUUID() }, { brandId: 'qa', shopId: 'A', categoryId: 'desk', platform: 'qa', version: '1', source: 'qa', rules: [] });
const requests = [];
const ids = [];
const retries = [];
const broker = { info: async () => ({ accountScope: scope, model: recovery?.model ?? { id: 'qa', protocol: 'openai-chat' }, thinkingLevel: recovery?.thinkingLevel, pending: [] }), round({retryOf}={}) {
if(retryOf) retries.push(retryOf);
const id=randomUUID();
return { id, fetch: async (_url, init) => {
const p = JSON.parse(init.body); requests.push(p); ids.push(id);
return new Response(reply(p, requests.length), { headers: { 'content-type': 'text/event-stream' } });
}, finish };
} };
const canvas=(production||recovery?.canvas)&&{begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){},
activity:async()=>{},delta:async()=>{},end:async()=>{},...(production??recovery).canvas};
const variantId=randomUUID();
const outputs=production?.outputs??[{outputId:'detail',variantId}];
const productionGoal=production&&{outputId:production.outputs?null:'detail',variantId:production.outputs?null:variantId,
workspaceId:randomUUID(),requestedOutputs:outputs,pendingOutputs:outputs,deadline:production.deadline,
template:production.template};
if(recovery)Object.assign(broker,{forDetailSlot:()=>broker,close:async()=>{},
status:async()=>({pending:[]}),isUnconfirmed:()=>Boolean(recovery.read),read:recovery.read,recover:recovery.recover});
const host = await DetailPiAgent.open({ store, broker, callBudget: production?.callBudget??3, canvas, productionGoal });
if(production)host.productionOperations=Promise.resolve({
plan_production:args=>production.plan?.(args)??{pendingText:0},
close:async()=>{},finish_production:async()=>({text:'已核对导出。',production:{...productionGoal,complete:true,canvasRevision:1}}),
});
return { host, store, requests, ids, retries, close: async () => { await host.dispose(); await cleanup(dir); } };
}
test('Pi loads the Skill and opens a project-selected output with the same session and tool declarations',async()=>{
const outputs=[{outputId:'detail',variantId:randomUUID()},{outputId:'gallery',variantId:randomUUID()}];
const template={id:'fixture',version:'3',enterprise:true,resourceSetId:'published'};
const instruction='先准备画册,再制作详情页。';
const bindings=[];
const catalogs=[];
const x=await setup((payload,n)=>{
const call=(name,args)=>sse({tool_calls:[{index:0,id:'binding-'+n,type:'function',
function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
assert.ok(payload.tools.some(row=>row.function?.name==='open_production_output'));
assert.ok(payload.tools.some(row=>row.function?.name==='finish_production'));
if(n>1){
assert.deepEqual(payload.tools,x.requests[0].tools);
assert.equal(payload.messages[0].content,x.requests[0].messages[0].content);
}
if(n===1){
assert.match(JSON.stringify(payload.messages),/requestedOutputs.*gallery/u);
return call('read',{path:x.host.productionSkills.resource.skills[0].filePath});
}
if(n===2)return call('plan_production',{});
if(n===3){
assert.match(JSON.stringify(payload.messages),new RegExp(instruction,'u'));
return call('native_catalog',{id:'layer.setProps'});
}
if(n===4){
assert.match(JSON.stringify(payload.messages),/production_canvas_pending/u);
return call('open_production_output',outputs[1]);
}
if(n===5){
assert.match(JSON.stringify(payload.messages),/gallery.*revision/u);
return call('native_catalog',{id:'layer.setProps'});
}
if(n===6){
assert.match(JSON.stringify(payload.messages),/requiresRevisionLease/u);
return call('finish_production',{revision:1});
}
return sse({content:'已核对画册。'},'stop');
},undefined,{outputs,template,callBudget:8,canvas:{
workflowRead(){assert.fail('selection should not require a mapped canvas');},
requestWrite(){assert.fail('selection should not ask for canvas write access');},
nativeCatalog:async({id})=>{
catalogs.push(id);
if(!bindings.length)throw new BridgeError('请先打开工作画布','production_canvas_pending',{retryable:true});
return {revision:1,items:[{id,requiresRevisionLease:true}]};
},
nativeCall(){assert.fail('catalog discovery should not dispatch an edit');},
openProductionOutput:async args=>{
bindings.push(args);
return {...args,revision:1,pendingOutputs:[outputs[0]]};
},
}});
try{
x.host.productEvidence={product:{name:'灯具',brandName:'测试品牌',categoryName:'灯具'}};
x.host.loadWholeDetailKnowledge=async selection=>{
assert.equal(selection.outputId,undefined);
assert.equal(selection.releaseId,'3');
return {skills:[{fileId:'entry',revision:'3',kind:'skill',path:'fixture/SKILL.md',
text:'---\nname: fixture\ndescription: Fixture project order\n---\n'+instruction}],rules:[]};
};
const response=await x.host.prompt('制作本轮所选输出');
assert.deepEqual(bindings,[outputs[1]]);
assert.deepEqual(catalogs,['layer.setProps','layer.setProps']);
assert.equal(response.production.outputId,'gallery');
assert.equal(response.production.complete,true);
assert.equal(x.requests.length,6);
assert.ok(x.host.manager.getBranch().some(row=>row.customType==='pi-goal'&&row.data.goal.status==='active'));
}finally{await x.close();}
});
test('ordinary chat resumes the same turn through Pi after a confirmed rate limit', async () => {
const x = await setup((_p, n) => n === 1
? 'data: {"error":{"code":"rate_limit_exceeded","type":"server_error"}}\n\n'
: sse({content:'可以继续处理。'}, 'stop'),
async valid => valid ? {phase:'complete'} : {phase:'failed',failureCode:'rate_limit_exceeded'});
try {
const next = await x.host.prompt('请先说明当前结果');
assert.equal(next.text, '可以继续处理。');
assert.equal(x.requests.length, 2);
assert.deepEqual(x.requests[0].messages,x.requests[1].messages);
assert.notEqual(x.ids[0],x.ids[1]);
} finally { await x.close(); }
});
test('an HTTP 503 native inference receipt reaches Pi retry in the same one-click goal', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-'));
let host;
t.after(async()=>{ await host?.dispose(); await cleanup(dir); });
const scope = 'b'.repeat(64), project=randomUUID();
const store = await ProjectStore.open(dir, {scope,project}, {brandId:'qa',shopId:'shop',categoryId:'qa',platform:'qa',version:'1',source:'qa',rules:[]});
const requests=[], finished=[], operations=[];
const originalId=randomUUID();
const broker = new Native98kBroker({project,profile:dir,modelRole:'detail'});
broker.scope=scope;
broker.info=async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-responses',supportsImageInput:true},pending:[]});
broker.status=async()=>({pending:[]});
broker.forDetailSlot=()=>broker;
const event=(type,details)=>'event: '+type+'\ndata: '+JSON.stringify({type,...details})+'\n\n';
const nextOutput={outputId:'sku_images',variantId:randomUUID()};
const item={id:'fc_ok',type:'function_call',call_id:'call_ok',name:'finish_production',
arguments:JSON.stringify({revision:7,nextOutput})};
const response=event('response.output_item.added',{output_index:0,item:{...item,arguments:''}})
+event('response.function_call_arguments.delta',{output_index:0,delta:item.arguments})
+event('response.output_item.done',{output_index:0,item})
+event('response.completed',{response:{model:'qa',status:'completed',output:[item]}});
broker.start=async(method,input,emit)=>{
if(method==='finish'){finished.push(input.id);return {phase:'complete'};}
assert.equal(method,'request');
requests.push(input);
const success=input.inference===true && requests.length>1;
emit({type:'headers',status:success?200:503,requestId:success?randomUUID():originalId,
headers:{'content-type':success?'text/event-stream':'application/json'},bodyHash:'native-wire'});
const error=JSON.stringify({error:{code:'service_unavailable',type:'server_error',message:'Service temporarily unavailable'}});
emit({type:'chunk',data:Buffer.from(success?response:error).toString('base64')});
return success?{phase:'received'}:{phase:'unknown',requestId:originalId};
};
const canvas={begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){},activity:async()=>{},delta:async()=>{},end:async()=>{}};
const variantId=randomUUID();
const productionGoal={outputId:'detail',variantId,workspaceId:randomUUID(),requestedOutputs:[{outputId:'detail',variantId}],
deadline:Math.floor(Date.now()/1000)+90};
host=await DetailPiAgent.open({store,broker,canvas,productionGoal,callBudget:4});
host.productionOperations=Promise.resolve({close:async()=>{},finish_production:async input=>{
operations.push(input);
return {text:'已核对导出。',production:{...productionGoal,complete:true,canvasRevision:input.revision,
nextOutput:input.nextOutput}};
}});
const resumed=await host.prompt('继续制作当前画布');
assert.equal(resumed.production.complete,true);
assert.deepEqual(operations,[{revision:7,nextOutput}]);
assert.deepEqual(resumed.production.nextOutput,nextOutput);
assert.deepEqual(finished,[requests[1].id]);
assert.notEqual(requests[0].id,requests[1].id);
assert.equal(requests[0].body,requests[1].body);
const guarded=broker.round();
await guarded.fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'});
await assert.rejects(guarded.finish(false,'error'),/结果未知;不会重发/u);
});
test('the one-click goal resumes on changed fields at the same count without naming the next tool',async()=>{
const plan=n=>sse({tool_calls:[{index:0,id:'plan-'+n,type:'function',function:{name:'plan_production',arguments:'{}'}}]},'tool_calls');
let plans=0;
const x=await setup((_,n)=>{
if(n===1||n===3)return plan(n);
if(n===5)return sse({tool_calls:[{index:0,id:'finish',type:'function',function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls');
return sse({content:'本次复核有进展。'},'stop');
},undefined,{
callBudget:6,plan:()=>({pendingText:1,field:++plans===1?'标题':'规格'}),
progress:()=>({state:{fields:[plans===1?'标题':'规格']}}),
});
try {
const result=await x.host.prompt('完成整套制作');
assert.equal(result.production.complete,true);
assert.equal(plans,2);
for(const request of [x.requests[2],x.requests[4]]){
const continuation=request.messages.findLast(message=>JSON.stringify(message).includes('继续当前制作目标'));
assert.ok(continuation);
assert.doesNotMatch(JSON.stringify(request.messages), /prompt-to-artifact checklist|PR state/u);
assert.doesNotMatch(JSON.stringify(continuation),/调用 (?:plan_production|write_copy_fields)/);
}
} finally { await x.close(); }
});
test('a managed inference interruption retries without executing its partial tool', async () => {
let plans=0;
const lookedUp=[];
const call={tool_calls:[{index:0,id:'plan',type:'function',
function:{name:'plan_production',arguments:'{}'}}]};
const x=await setup((_,n)=>n===1?sse(call,null).replace('data: [DONE]','')
:n===2?sse(call,'tool_calls'):sse({tool_calls:[{index:0,id:'finish',type:'function',
function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls'),
async valid=>valid?{phase:'complete'}:{phase:'unknown'},{
deadline:Math.floor(Date.now()/1000)+600,callBudget:4,
plan:()=>{plans++;return {pendingText:0};},
progress:()=>({state:{waitingOnOriginals:true}}),
},{
read:async()=>({phase:'unknown',recovery:{status:410}}),
recover:async id=>{lookedUp.push(id);},
});
try {
assert.equal((await x.host.prompt('开始整套制作')).production.complete,true);
assert.deepEqual(lookedUp,[]);
assert.deepEqual(x.retries,[]);
assert.equal(plans,1);
assert.equal(x.requests.length,3);
} finally {await x.close();}
});
test('actual native Pi wire sends function schemas, executes typed call and accepts a plain final reply', async () => {
const x = await setup((_p, n) => n === 1 ? sse({ tool_calls: [{ index: 0, id: 'call-memory', type: 'function', function: { name: 'memory_set', arguments: JSON.stringify({ key: 'color', value: '胡桃色', evidence: '测试颜色是胡桃色' }) } }] }, 'tool_calls') : sse({ content: '已记录胡桃色' }, 'stop'));
try {
const r = await x.host.prompt('测试颜色是胡桃色,请记住。', { requiredTool: 'memory_set' });
assert.equal(r.text, '已记录胡桃色');
assert.equal((await x.store.context()).confirmedMemory.color.value, '胡桃色');
assert.equal(x.requests.length, 2);
assert.deepEqual(x.requests[0].tool_choice, { type: 'function', function: { name: 'memory_set' } });
assert.equal(x.requests[0].parallel_tool_calls, false);
assert.ok(x.requests[0].tools.some(t => t.type === 'function' && t.function.name === 'memory_set'));
assert.ok(x.requests[1].messages.some(m => m.role === 'tool' && m.tool_call_id === 'call-memory'));
assert.equal(x.requests[0].response_format, undefined);
} finally { await x.close(); }
});
test('native Pi preserves a required named tool across a retry on a string-only Responses route', async () => {
const args = JSON.stringify({key:'color',value:'米色',evidence:'布面颜色是米色'});
const call = {type:'function_call',id:'fc_required',call_id:'call_required',status:'completed',name:'memory_set',arguments:args};
const text = {type:'message',id:'msg_required',role:'assistant',status:'completed',
content:[{type:'output_text',text:'已记录米色。',annotations:[]}]};
const event = (type, fields) => 'event: ' + type + '\ndata: ' + JSON.stringify({type,...fields}) + '\n\n';
const complete = item => event('response.completed',{response:{model:'qa',status:'completed',output:[item]}});
const fixture = {thinkingLevel:'low',model:{id:'qa',protocol:'openai-responses',supportsImageInput:true,requireSingleTool:true,
reasoning:true,reasoningEfforts:['low','medium','high'],requiresOutputLimit:false,maxTokens:128_000}};
const x = await setup((_payload, round) => round === 1
? event('response.created',{response:{id:'resp_lost',status:'in_progress'}})
: round === 2
? event('response.output_item.added',{output_index:0,item:{...call,arguments:'',status:'in_progress'}})
+ event('response.function_call_arguments.delta',{output_index:0,delta:args.slice(0,12)})
+ event('response.function_call_arguments.delta',{output_index:0,delta:args.slice(12)})
+ event('response.output_item.done',{output_index:0,item:call}) + complete(call)
: event('response.output_item.added',{output_index:0,item:{...text,content:[],status:'in_progress'}})
+ event('response.content_part.added',{output_index:0,content_index:0,part:{...text.content[0],text:''}})
+ event('response.output_text.delta',{output_index:0,content_index:0,delta:text.content[0].text})
+ event('response.output_item.done',{output_index:0,item:text}) + complete(text),
async valid => ({phase:valid?'complete':'unknown'}), undefined, fixture);
const reference = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAgACADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAYH/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AkgIpngAAAAAD/9k=';
try {
assert.equal(x.host.session.thinkingLevel,'low');
assert.equal((await x.host.prompt('/thinking high')).rounds,0);
assert.equal(x.host.session.thinkingLevel,'high');
await x.host.prompt('布面颜色是米色,请记住。', {requiredTool:'memory_set',referenceContent:[{label:'产品原图',image:reference}]});
assert.equal(x.requests[0].tool_choice,'required');
assert.equal(x.requests[0].reasoning.effort,'high');
assert.equal(x.requests[0].max_output_tokens,undefined);
assert.deepEqual(x.requests[0].tools.map(tool=>tool.name),['memory_set']);
assert.equal(x.requests[1].tool_choice,'required');
assert.deepEqual(x.requests[1].tools.map(tool=>tool.name),['memory_set']);
assert.notEqual(x.ids[0], x.ids[1]);
const parts = x.requests[0].input.flatMap(item=>Array.isArray(item.content)?item.content:[]);
assert.match(parts.find(part=>part.type==='input_image')?.image_url ?? '', /^data:image\/(?:jpeg|png);base64,/);
assert.equal((await x.store.context()).confirmedMemory.color.value,'米色');
assert.equal(x.requests[2].tool_choice,undefined);
} finally { await x.close(); }
});
test('native partial arguments and length-stopped valid prefixes never execute memory writes', async () => {
for (const [args, finish] of [['{"key":"color","value":"红色","evidence":"测试颜色是红色"', 'tool_calls'], ['{"key":"color","value":"红色","evidence":"测试颜色是红色"}', 'length']]) {
const x = await setup(() => sse({ tool_calls: [{ index: 0, id: 'partial', type: 'function', function: { name: 'memory_set', arguments: args } }] }, finish));
try {
await assert.rejects(x.host.prompt('测试颜色是红色'), /未完整|达到线路上限/);
assert.deepEqual((await x.store.context()).confirmedMemory, {});
assert.equal(x.requests.length, 1);
} finally { await x.close(); }
}
});
test('required tool returned as prose is a known protocol failure with one POST and no execution', async () => {
const x = await setup(() => sse({ content: 'invoke tool memory_set with color red' }, 'stop'));
try {
await assert.rejects(x.host.prompt('测试颜色是红色', { requiredTool: 'memory_set' }), /未返回要求的标准函数调用/);
assert.equal(x.requests.length, 1); assert.deepEqual((await x.store.context()).confirmedMemory, {});
} finally { await x.close(); }
});
test('a literal marker in a normal explanation is ordinary text, never a command or a repair trigger', async () => {
const x = await setup(() => sse({ content: '结束标记的示例是 <|eos|>。' }, 'stop'));
try { const r = await x.host.prompt('解释一个结束标记,不要调用工具'); assert.match(r.text, /结束标记/); assert.equal(x.requests.length, 1); }
finally { await x.close(); }
});
test('wire audit detects complete SSE with a literal early EOS instead of blaming the browser', () => {
const a = auditResponse(sse({ content: '{"reply":"未结束<|eos|>' }, 'stop'), 'openai-chat');
assert.equal(a.literalEos, true); assert.deepEqual(a.finishes, ['stop']);
});
test('a terminal marker without a completion reason remains unproven and cannot execute a tool', () => {
assert.throws(() => auditResponse(sse({ content: '只有前缀' }, null), 'openai-chat'), /缺少完成原因/);
const broken={tool_calls:[{index:0,function:{name:'review_candidate',arguments:'{"candidateId":'}}]};
assert.throws(() => auditResponse(sse(broken,null),'openai-chat'),error=>!(error instanceof InvalidToolReply)&&/缺少完成原因/.test(error.message));
assert.throws(() => auditResponse(sse(broken,'tool_calls'),'openai-chat'),InvalidToolReply);
});
test('JSON compatibility errors distinguish complete prose from a broken JSON envelope', () => {
const c = normalizeContext({ messages: [] });
assert.throws(() => decodeToolReply('产品编号与颜色核对正确。', c, 'id'), /文字而非约定的JSON/);
assert.throws(() => decodeToolReply('{"reply":"只返回一半<|eos|>', c, 'id'), /提前结束标记/);
assert.throws(() => decodeToolReply('{"reply":"未闭合', c, 'id'), /JSON指令未完整/);
});
async function compactionFixture({ withCanvas, callBudget = 4, large = false, pendingStep, rateLimit = false } = {}) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-')), scope = '9'.repeat(64);
const store = await ProjectStore.open(dir, { scope, project: randomUUID() }, { brandId: 'qa', shopId: 'qa', categoryId: 'qa', platform: 'qa', source: 'qa', version: '1', rules: [] });
const manager = SessionManager.create(store.dir, path.join(store.dir, 'sessions'));
for (let i = 0; i < (large ? 45 : 26); i++) {
manager.appendMessage({ role: 'user', content: `archive-marker-${i}: ` + 'x'.repeat(large ? 3000 : 1600), timestamp: Date.now() });
manager.appendMessage({ role: 'assistant', api: 'openai-completions', provider: 'jiansun-native-98k', model: 'qa', content: [{ type: 'text', text: 'Synthetic, not a live model reply. ' + 'y'.repeat(large ? 3000 : 1600) }], stopReason: 'stop', timestamp: Date.now(), usage: { input: large?50000:5000, output: 500, cacheRead: 0, cacheWrite: 0, totalTokens: large?50500:5500, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } });
}
await atomic(path.join(store.dir, 'session.json'), { file: manager.getSessionFile() });
let calls = 0, canvasCalls = 0;
const canvas = withCanvas ? { read() { canvasCalls++; throw Error('no canvas edit run during compaction'); }, delta() { canvasCalls++; throw Error('must not show internal summary'); } } : undefined;
const transport = { info: { accountScope: scope, model: { id: 'qa', protocol: 'openai-chat', contextWindow:64000, contextWindowSource:'fixture' }, pending: [] }, stream(model) {
calls++;
const stream = createAssistantMessageEventStream();
const message = { role: 'assistant', api: model.api, provider: model.provider, model: model.id, content: [{ type: 'text', text: 'Summary: original evidence remains archived.' }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 5000, output: 20, cacheRead: 0, cacheWrite: 0, totalTokens: 5020, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
queueMicrotask(() => { stream.push({ type: 'start', partial: message }); stream.push({ type: 'text_delta', contentIndex: 0, delta: message.content[0].text, partial: message }); stream.push({ type: 'done', reason: 'stop', message }); stream.end(message); });
return stream;
} };
let goal, broker;
if (pendingStep) {
const variantId=randomUUID();
goal={outputId:'detail',variantId,workspaceId:randomUUID(),requestedOutputs:[{outputId:'detail',variantId}]};
const goalScope='product/goal/'+variantId+'/detail';
transport.info.pending=[{id:randomUUID(),modelRole:'detail',phase:'unknown',
detailSlot:pendingStep==='goal'?goalScope:'product/review/'+randomUUID()}];
canvas.detailImages=()=>{};
broker = {
info:async()=>transport.info,
round(){throw Error('production summary must use its matching goal scope');},
forDetailSlot(value) {
assert.equal(value,goalScope);
return {round:()=>({
id:randomUUID(),
fetch:async(_url,{body})=>{
calls++;
assert.equal(JSON.parse(body).tools,undefined);
if (rateLimit && calls === 1) {
return new Response('data: {"error":{"code":"rate_limit_exceeded","type":"server_error"}}\n\n',
{headers:{'content-type':'text/event-stream'}});
}
return new Response(sse({content:'Summary: original evidence remains archived.'},'stop'),
{headers:{'content-type':'text/event-stream'}});
},
finish:async()=>rateLimit && calls === 1 ? {phase:'failed',failureCode:'rate_limit_exceeded'} : {phase:'complete'},
}),close:async()=>{}};
},
};
}
const host = await DetailPiAgent.open({ store, transport:broker?undefined:transport, broker, canvas, callBudget, productionGoal:goal });
return { host, get calls() { return calls; }, get canvasCalls() { return canvasCalls; }, close: async () => { await host.dispose(); await cleanup(dir); } };
}
test('compaction with a connected canvas does not call an inactive edit run or show the internal summary', async () => {
const x = await compactionFixture({ withCanvas: true });
try {
const result = await x.host.compact();
assert.match(result.summary, /original evidence/); assert.ok(x.calls > 0); assert.equal(x.canvasCalls, 0);
assert.ok(x.host.manager.getEntries().some(e => e.type === 'message' && e.message.role === 'user' && e.message.content.includes('archive-marker-0')));
} finally { await x.close(); }
});
test('the Pi defaults compact from the native session threshold',async()=>{
const x=await compactionFixture({large:true});
try {
const settings=x.host.session.settingsManager;
assert.deepEqual(settings.getCompactionSettings(x.host.session.model),{enabled:true,reserveTokens:16384,keepRecentTokens:20000});
assert.deepEqual(Object.fromEntries(Object.entries(settings.getRetrySettings()).filter(([k])=>['enabled','maxRetries','baseDelayMs'].includes(k))),
{enabled:true,maxRetries:3,baseDelayMs:2000});
await x.host.prompt('继续');
assert.equal(x.calls,3);
const checkpoints=x.host.manager.getEntries().filter(entry=>entry.type==='compaction');
assert.equal(checkpoints.length,1);
assert.ok(x.host.manager.getEntries().some(entry=>entry.message?.role==='user'&&entry.message.content.includes('archive-marker-0')));
} finally {await x.close();}
});
test('native compaction retries its own interrupted summary', async()=>{
const x=await compactionFixture({withCanvas:true,pendingStep:'review',rateLimit:true});
try {
assert.match((await x.host.compact()).summary,/original evidence/);
assert.equal(x.calls,2);
assert.equal(x.canvasCalls,0);
assert.equal(x.host.manager.getEntries().filter(entry=>entry.type==='compaction').length,1);
} finally {await x.close();}
});
test('the model receives prior images and original tool receipts through Pi', async()=>{
const x=await setup((payload,n)=>{
if(n===1) return sse({tool_calls:[{index:0,id:'context-1',type:'function',function:{name:'context_read',arguments:'{}'}}]},'tool_calls');
return sse({content:'继续核对。'},'stop');
});
try {
const image='iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP43+AARwzEcQDiohvxgB7+wgAAAABJRU5ErkJggg==';
await x.host.prompt('检查附件',{referenceContent:[{label:'测试图',image,mimeType:'image/png'}]});
await x.host.prompt('继续');
const tool=x.requests[1].messages.find(message=>message.tool_call_id==='context-1');
assert.ok(tool);
assert.ok(x.requests[2].messages.some(message=>message.tool_call_id==='context-1'&&message.content===tool.content));
assert.ok(x.requests[2].messages.some(message=>Array.isArray(message.content)&&message.content.some(x=>x.type==='image_url')),
JSON.stringify({model:x.host.session.model.input,session:x.host.session.messages.map(message=>[message.role,
Array.isArray(message.content)?message.content.map(x=>x.type):typeof message.content]),
wire:x.requests.map(payload=>payload.messages.map(message=>[message.role,
Array.isArray(message.content)?message.content.map(x=>x.type):typeof message.content]))}));
} finally {await x.close();}
});
test('Pi project tools share the same file boundary',async()=>{
const x=await setup(()=>sse({content:'已核对。'},'stop'));
try {
const {cwd,tools}=await projectTools(x.host);
const tool=name=>tools.find(row=>row.name===name);
await tool('write').execute('1',{path:'notes.md',content:'品牌说明'});
const result=await tool('read').execute('2',{path:'notes.md'});
assert.match(result.content[0].text,/品牌说明/);
assert.ok((await fs.readFile(path.join(cwd,'notes.md'),'utf8')).includes('品牌'));
await assert.rejects(tool('write').execute('3',{path:'../outside.txt',content:'无'}),/工作目录之外/);
await assert.rejects(tool('read').execute('4',{path:'../session.json'}),/工作目录之外/);
assert.ok(tool('bash'));
} finally {await x.close();}
});
test('a canvas can complete more than 20 edits and cancellation stops waiting',async()=>{
let rev=0, dispatched=0, apply=true;
const canvas=new StdioCanvas(async action=>{
if(action==='pi-edit'){dispatched++;if(apply)rev++;}
if(action==='pi-state')return {allowed:true,revision:rev,queued:!apply};
return {};
},1);
await canvas.begin('更新当前模板');
for(let index=0;index<21;index++)await canvas.edit({command:'text'},index);
apply=false;
const signal=AbortSignal.timeout(150);
await assert.rejects(canvas.edit({command:'text'},rev,signal),{name:'AbortError'});
assert.equal(dispatched,22);
});
test('first canvas save failure leaves the original run usable; a lost open ACK is observed without replay', async () => {
const target={outputId:'detail',variantId:'wood'};
const dispatched=[];
let attempts=0, binding;
const canvas=new StdioCanvas(async(action,input)=>{
if(action==='pi-begin')return {};
assert.equal(input.run,canvas.run);
assert.equal(input.documentId,1);
if(action==='pi-production-open'){
dispatched.push({outputId:input.outputId,variantId:input.variantId});
if(++attempts===1)return {openingProductionCanvas:true};
throw new BridgeError('画布未确认操作','transport_interrupted',{retryable:true,dispatched:true});
}
if(action==='pi-native-catalog'){
if(!binding)throw new BridgeError('请先打开工作画布','production_canvas_pending',{retryable:true});
return {revision:binding.revision};
}
assert.equal(action,'pi-state');
if(attempts===1)return {conversationActive:true,error:'当前草稿保存失败'};
binding={...target,revision:2,pendingOutputs:[]};
return {conversationActive:true,productionCanvas:binding};
},1);
await canvas.begin('制作详情页');
const first=canvas.openProductionOutput(target);
await Promise.all([
assert.rejects(first,{category:'production_canvas_open_failed',message:'当前草稿保存失败',retryable:true}),
assert.rejects(canvas.nativeCatalog(),{category:'production_canvas_pending',dispatched:false}),
]);
assert.deepEqual(await canvas.openProductionOutput(target),binding);
assert.deepEqual(await canvas.nativeCatalog(),{revision:2});
assert.deepEqual(dispatched,[target,target]);
});
test('canvas search keeps the screen and keyword when a layer argument is also present',()=>{
assert.deepEqual(canvasReadQuery({layer:999,screen:'第二屏',screenId:41,filter:'材质',maxDepth:0,mode:'layers',offset:0}),
{screenId:41,filter:'材质',mode:'layers',offset:0});
assert.deepEqual(canvasReadQuery({layer:41,screen:'',filter:' '}),{layer:41});
assert.deepEqual(canvasReadQuery({screen:'',filter:''}),{offset:0});
});
test('the Pi canvas contract forwards a deeper group summary with the requested scope',()=>{
const query={screenId:90,maxDepth:6};
assert.ok(Value.Check(canvasReadParameters,query));
assert.deepEqual(canvasReadQuery(query),{mode:'summary',screenId:90,maxDepth:6,offset:0});
});
test('production exposes direct native tools and Pi file tools',async()=>{
const x=await setup(payload=>{
const names=payload.tools.map(row=>row.function.name);
for(const name of ['native_catalog','native_call','native_reconcile','codemode','tool_search','read','write','edit','ls','find','grep','bash']){
assert.ok(names.includes(name),name);
}
return sse({tool_calls:[{index:0,id:'finish',type:'function',function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls');
},undefined,{progress:()=>({state:{waitingOnOriginals:true}}),
canvas:{nativeCatalog(){},nativeCall(){},nativeReconcile(){}}});
try {
assert.equal(x.host.session.agent.toolExecution,'parallel');
const names=x.host.session.getActiveToolNames();
assert.ok(names.includes('codemode'));
assert.ok(names.includes('tool_search'));
assert.ok(names.includes('read')&&names.includes('write'));
assert.equal((await x.host.prompt('核对制作工具')).production.complete,true);
assert.equal(x.requests.length,1);
} finally {await x.close();}
});
test('Pi runs independent production reads from the same model turn concurrently',async()=>{
let release;
const gate=new Promise(resolve=>{release=resolve;});
const started=[];
const read=async name=>{
started.push(name);
if(started.length===2)release();
await gate;
return {items:[]};
};
const x=await setup((_,round)=>{
const calls=round===1?['plan_production','native_catalog']:['finish_production'];
return sse({tool_calls:calls.map((name,index)=>({index,id:name,type:'function',
function:{name,arguments:round===1?'{}':'{"revision":1}'}}))},'tool_calls');
},undefined,{plan:()=>read('plan_production'),canvas:{
nativeCatalog:()=>read('native_catalog'),nativeCall(){},
}});
const result=x.host.prompt('读取制作计划和原生命令目录');
try{
await Promise.race([gate,new Promise((_,reject)=>{
const timer=setTimeout(()=>reject(Error('同批只读工具没有并发开始')),2000);
timer.unref();
})]);
assert.equal(started.length,2);
assert.equal((await result).production.complete,true);
}finally{
release();
try{await result;}finally{await x.close();}
}
});
test('production publishes direct native commands and no duplicate conversation tools',async()=>{
const executed=[];
const x=await setup((_,request)=>{
const name=request===1?'native_call':'finish_production';
const args=request===1?{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}:{revision:1};
return sse({tool_calls:[{index:0,id:'edit-'+request,type:'function',function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
},undefined,{
progress:()=>({state:{waitingOnOriginals:true}}),
canvas:{
nativeCatalog:async({id})=>({items:[{id,requiresRevisionLease:true}]}),
requestWrite:async revision=>({allowed:true,revision}),
nativeReconcile(){}, readTemplateImage(){}, preview(){}, copyOptions(){}, copyFields(){},
workflowRead:async()=>({available:false,version:1}), workflowNavigate(){}, workflowPropose(){}, workflowExecute(){}, workflowPoll(){},
edit:async()=>{assert.fail('production must use the original native command receipt');},
nativeCall:async args=>{executed.push(args);return {completed:true,executed:true,revision:2};},
},
});
try{
for(const name of ['canvas_read','canvas_edit','canvas_template_image','canvas_preview','copywriting_options',
'copywriting_fields','workflow_read','workflow_navigate','workflow_execute','workflow_propose']) {
assert.equal(x.host.session.getToolDefinition(name),undefined,name);
}
for(const name of ['plan_production','native_catalog','native_call','native_reconcile','read','bash','tool_search','codemode']){
assert.ok(x.host.session.getToolDefinition(name),name);
}
for(const name of ['read_image_request','freeze_image_request']){
assert.equal(x.host.session.getToolDefinition(name),undefined,name);
}
for(const name of ['plan_production','native_catalog','read_production_knowledge','read_copy_fields','read_slot_images','review_image_slots','read_output_screen']){
assert.notEqual(x.host.session.getToolDefinition(name).executionMode,'sequential',name);
}
for(const name of ['native_call','prepare_image_request','dispatch_image_request','finish_production']){
assert.equal(x.host.session.getToolDefinition(name).executionMode,'sequential',name);
}
assert.equal((await x.host.prompt('完成制作')).production.complete,true);
assert.deepEqual(executed,[{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}]);
const row=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='edit-1')?.message;
assert.equal(JSON.parse(row.content[0].text).executed,true);
}finally{await x.close();}
});
test('a temporary write wait and a rejected native edit can be corrected in the same production turn', async () => {
let leases = 0, edits = 0;
const x = await setup((_, request) => {
const name = request <= 2 ? 'native_call' : 'finish_production';
const args = request <= 2
? {revision: 1, method: 'engine.execute', params: {command: 'type.edit', params: {
layer: 2, text: request === 1 ? 'A title that cannot fit' : 'New', expectedText: 'Old',
}}}
: {revision:1};
return sse({tool_calls: [{index: 0, id: `tool-${request}`, type: 'function',
function: {name, arguments: JSON.stringify(args)}}]}, 'tool_calls');
}, undefined, {
callBudget: 4,
progress: () => ({state: {waitingOnOriginals: true}}),
canvas: {
nativeCatalog() {}, nativeReconcile() {},
requestWrite: async revision => ++leases === 1
? {allowed: false, revision, retryWrite: true, detailWriteWaiting: true}
: {allowed: true, revision},
nativeCall: async () => {
if (++edits === 1) throw new BridgeError('画布已修改,请先读取当前修订','revision_conflict',{dispatched:false});
return {completed:true,executed:true,revision:2};
},
},
});
try {
assert.equal((await x.host.prompt('完成制作')).production.complete, true);
assert.equal(leases, 3);
assert.equal(edits, 2);
const rejected = x.host.manager.getBranch().find(({message})=>message?.toolCallId==='tool-1')?.message;
assert.match(rejected.content[0].text,/画布已修改,请先读取当前修订/u);
assert.equal(x.requests.length, 3);
assert.equal(x.host.canvasOperations.original, undefined);
} finally { await x.close(); }
});
test('a new revision while a native write is waiting never dispatches the old command', async () => {
let reads=0;
const x=await setup((_,attempt)=>sse({tool_calls:[{index:0,id:'native-wait-'+attempt,type:'function',function:attempt===1
? {name:'native_call',arguments:JSON.stringify({revision:1,method:'engine.execute',
params:{command:'type.edit',params:{layer:2,text:'草稿'}}})}
: {name:'finish_production',arguments:'{"revision":2}'}}]},'tool_calls'),undefined,{
progress:()=>({}),
canvas:{
nativeCatalog:async({id})=>({items:[{id,requiresRevisionLease:true}]}),
requestWrite:async()=>({allowed:false,revision:++reads===1?1:2,retryWrite:true,detailWriteWaiting:true}),
nativeCall:async()=>assert.fail('stale native call must not dispatch'),
},
});
try {
assert.equal((await x.host.prompt('写入确认的修改')).production.complete,true);
assert.equal(reads,2);
const rejected=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='native-wait-1')?.message;
assert.match(rejected.content[0].text,/写入修订已变化/u);
assert.equal(x.host.canvasOperations.original,undefined);
} finally {await x.close();}
});
test('production native queries follow the catalog without requesting a canvas write lease', async () => {
const commands=[];
const calls=[
{name:'native_call',args:{revision:1,method:'engine.execute',params:{command:'document.inspect',params:{}}}},
{name:'native_call',args:{revision:1,method:'result.read',params:{resultId:3,pointer:'/layers',offset:0}}},
{name:'finish_production',args:{revision:1}},
];
const x = await setup((_, request) => {
const {name,args}=calls[request-1];
return sse({tool_calls: [{index: 0, id: `native-${request}`, type: 'function',
function: {name, arguments: JSON.stringify(args)}}]}, 'tool_calls');
}, undefined, {
progress: () => ({state: {waitingOnOriginals: true}}),
canvas: {
nativeCatalog: async ({id}) => ({items: [{id, requiresRevisionLease: false}]}),
requestWrite() { assert.fail('read-only operation requested a write lease'); },
nativeCall: async ({method,params}) => {
commands.push({method,params});
const result=method==='result.read'?{items:[{id:7}],nextOffset:null}:{resultRef:{resultId:3}};
return {completed:true,executed:true,result};
},
},
});
try {
assert.equal((await x.host.prompt('核对当前画布')).production.complete, true);
assert.deepEqual(commands,calls.slice(0,2).map(({args:{method,params}})=>({method,params})));
const read=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='native-2')?.message;
assert.deepEqual(JSON.parse(read.content[0].text).result.items,[{id:7}]);
} finally { await x.close(); }
});
test('ordinary discussion can still navigate the product views without writes', async () => {
const viewed=[];
const x=await setup((_,n)=>n===1?sse({tool_calls:[{index:0,id:'view-1',type:'function',
function:{name:'workflow_navigate',arguments:'{"stage":"canvas","outputId":"main_images"}'}}]},'tool_calls')
:sse({content:'已打开主图。'},'stop'),undefined,undefined,{
canvas:{
workflowNavigate:async args=>{
viewed.push(args);
return {navigated:true,executed:false,outputId:args.outputId,version:1};
},
requestWrite() {assert.fail('navigation requested a write');},
},
});
try {
assert.equal((await x.host.prompt('查看主图布局')).text,'已打开主图。');
const message=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='view-1')?.message;
assert.deepEqual(viewed,[{stage:'canvas',outputId:'main_images'}]);
assert.equal(JSON.parse(message.content[0].text).outputId,'main_images');
} finally {await x.close();}
});
test('reading a fresh production goal never starts the strategy, image workers, or canvas writes', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-production-read-'));
t.after(() => cleanup(dir));
const host = {
productionGoal: {outputId:'detail',variantId:'walnut'},
store:productionStore(dir),
runDetailAgent() {assert.fail('a read started production');},
canvas: {
workflowRead: async () => ({available:true,canvasFirst:true,outputId:'detail',productVariantId:'walnut',
template:{contentHash:'desk-version'},totalSlots:1,slots:[{id:'desk',fieldId:'cover',label:'主视觉',candidates:[]}]}),
detailCopyFields: async ({pageId}) => ({
fields:[{layer:6,page:'intro'},{layer:9,page:'specs'}].filter(field=>!pageId||field.page===pageId),
}),
read:async()=>({revision:3}),
detailRender: async () => ({page:0,revision:3,images:[]}),
},
};
assert.equal((await callProductionTool(host,'plan_production',{})).pictures.length,1);
assert.equal((await callProductionTool(host,'review_image_slots',{slotIds:['desk']})).pictures[0].id,'desk');
assert.deepEqual((await callProductionTool(host,'read_copy_fields',{pageId:'specs'})).fields,[{layer:9,page:'specs'}]);
assert.equal((await callProductionTool(host,'read_output_screen',{page:0})).details.revision,3);
assert.equal((await host.productionOperations).active,0);
});
test('production loads the project’s native skill and prompt template', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-project-resources-'));
t.after(() => cleanup(dir));
const cwd = path.join(dir, 'workspace');
const skillDir = path.join(cwd, '.pi', 'skills', 'desk-copy');
const promptDir = path.join(cwd, '.pi', 'prompts');
await fs.mkdir(skillDir, {recursive: true});
await fs.mkdir(promptDir, {recursive: true});
await fs.writeFile(path.join(skillDir, 'SKILL.md'),
'---\nname: desk-copy\ndescription: Write usable desk copy.\n---\nShow the available work surface.');
await fs.writeFile(path.join(promptDir, 'fixture-copy.md'),
'---\ndescription: Write a fixture headline.\n---\nDescribe the work surface.');
const {resourceLoader} = await createPhotoCraftExtensions({workingDirectory: cwd, store: {dir}}, [], {includeGoal: true});
assert.ok(resourceLoader.getSkills().skills.some(skill => skill.name === 'desk-copy'));
assert.equal(resourceLoader.getPrompts().prompts.find(prompt => prompt.name === 'fixture-copy')?.content,
'Describe the work surface.');
});
test('Pi serializes shared cache affinity for the same kind of production worker', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-worker-cache-'));
const scope = 'a'.repeat(64), project = randomUUID();
const store = await ProjectStore.open(root, {scope,project},
{brandId:'qa',shopId:'qa',categoryId:'qa',platform:'qa',version:'1',source:'fixture',rules:[]});
const bodies = [];
const broker = new Native98kBroker({project,profile:root});
broker.scope = scope;
broker.info = async () => ({accountScope:scope,model:{id:'qa',protocol:'openai-responses',supportsImageInput:true},pending:[]});
broker.status = async () => ({pending:[]});
broker.forDetailSlot = () => broker;
const event = (type,details) => 'event: '+type+'\ndata: '+JSON.stringify({type,...details})+'\n\n';
const item = {type:'message',id:'msg_test',role:'assistant',status:'completed',
content:[{type:'output_text',text:'Read complete.',annotations:[]}]};
const response = event('response.output_item.added',{output_index:0,item:{...item,content:[]}})
+event('response.output_text.delta',{output_index:0,content_index:0,delta:'Read complete.'})
+event('response.output_item.done',{output_index:0,item})
+event('response.completed',{response:{model:'qa',status:'completed',output:[item]}});
broker.start = async (method,input,emit) => {
if (method === 'finish') return {phase:'complete'};
assert.equal(method,'request');
bodies.push(typeof input.body === 'string' ? JSON.parse(input.body) : input.body);
emit({type:'headers',status:200,requestId:randomUUID(),headers:{'content-type':'text/event-stream'},bodyHash:'synthetic'});
emit({type:'chunk',data:Buffer.from(response).toString('base64')});
return {phase:'received'};
};
const production = new AbortController();
const host = await DetailPiAgent.open({store,broker,productionSignal:production.signal,
canvas:{read:async()=>({conversationActive:true})}});
t.after(async()=>{await host.dispose();await cleanup(root);});
for (const [slot,worker] of [['slot-a','review'],['slot-b','review'],['slot-c','worker']]) {
await host.runDetailAgent(slot,'Synthetic fixture system','Inspect the synthetic fixture.',[],[],'product/'+worker+'/'+slot);
}
assert.equal(bodies.length,3);
const session = host.manager.getSessionId();
assert.deepEqual(bodies.map(body=>body.prompt_cache_key),[session+':review',session+':review',session+':worker']);
const enter=Promise.withResolvers();
const round=broker.round.bind(broker);
let stoppedCalls=0;
broker.round=options=>({...round(options),fetch:(_address,{signal})=>{
stoppedCalls++;
enter.resolve();
return new Promise((_resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}));
}});
const worker=host.runDetailAgent('slot-d','Synthetic system','No further work after stop.',[],[],'product/review/slot-d');
const stopped=assert.rejects(worker,/制作已停止/u);
await enter.promise;
production.abort(Error('本轮制作已停止'));
await stopped;
assert.equal(stoppedCalls,1);
});