596 lines
36 KiB
JavaScript
596 lines
36 KiB
JavaScript
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';
|
||
|
||
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('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&&{begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){},
|
||
activity:async()=>{},delta:async()=>{},end:async()=>{},...production.canvas};
|
||
const productionGoal=production&&{outputId:'detail',variantId:randomUUID(),deadline:production.deadline};
|
||
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('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('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('active thread goal'));
|
||
assert.ok(continuation);
|
||
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) {
|
||
goal={outputId:'detail',variantId:randomUUID()};
|
||
const goalScope='product/goal/'+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('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 {
|
||
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('a rejected native text edit can be corrected in the same production turn', async () => {
|
||
let 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, {
|
||
progress: () => ({state: {waitingOnOriginals: true}}),
|
||
canvas: {
|
||
nativeCatalog() {}, nativeReconcile() {},
|
||
requestWrite: async revision => ({allowed: true, revision}),
|
||
nativeCall: async () => ++edits === 1
|
||
? {completed: true, executed: false, error: '画布已修改,请先读取当前修订'}
|
||
: {completed: true, executed: true, revision: 2},
|
||
},
|
||
});
|
||
try {
|
||
assert.equal((await x.host.prompt('完成制作')).production.complete, true);
|
||
assert.equal(edits, 2);
|
||
assert.equal(x.host.nativeUnresolved, undefined);
|
||
} finally { await x.close(); }
|
||
});
|
||
|
||
test('production native queries follow the catalog without requesting a canvas write lease', async () => {
|
||
let read = 0;
|
||
const x = await setup((_, request) => {
|
||
const name = request === 1 ? 'native_call' : 'finish_production';
|
||
const args = request === 1
|
||
? {revision: 1, method: 'engine.execute', params: {command: 'document.inspect', params: {}}}
|
||
: {revision: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 () => { read++; return {completed: true, executed: true}; },
|
||
},
|
||
});
|
||
try {
|
||
assert.equal((await x.host.prompt('核对当前画布')).production.complete, true);
|
||
assert.equal(read, 1);
|
||
} finally { await x.close(); }
|
||
});
|
||
|
||
test('reading a fresh production goal never starts the strategy, image workers, or canvas writes', async () => {
|
||
const host = {
|
||
productionGoal: {outputId:'detail',variantId:'walnut'},
|
||
store:{dir:'fixture',get:async()=>null},
|
||
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 () => ({fields:[{layer:6,page:'intro'},{layer:9,page:'specs'}]}),
|
||
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.');
|
||
});
|