import {openXiaoyiSkills} from '../src/xiaoyi-release.mjs'; import {xiaoyiFixture} from './xiaoyi-fixture.mjs'; import { productionExportReceipt } from './production-store-fixture.mjs'; 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 { openAgent } from './fake-canvas.mjs'; import { WORKER_TURN_LIMIT } from '../src/worker-receipts.mjs'; import { auditResponse, InvalidToolReply } from '../src/response-audit.mjs'; import { cleanup } from './cleanup.mjs'; import { normalizeContext } from '@earendil-works/pi-ai/compat'; import { createAssistantMessageEventStream, openAICompletionsApi, openAIResponsesApi } from '@earendil-works/pi-ai/compat'; import { DEFAULT_COMPACTION_SETTINGS, SessionManager, SettingsManager, shouldCompact } 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 { createPhotoCraftExtensions } from '../src/photocraft-extension.mjs'; import { callProductionTool } from '../src/production-goal.mjs'; import { productionStore, stubProductionOperations } from './production-store-fixture.mjs'; import { validateToolArguments } from '@earendil-works/pi-ai'; import { canvasReadParameters, canvasReadQuery } from '../src/canvas-contract.mjs'; import { nativeCatalogParameters, nativeTools } from '../src/native-tools.mjs'; test('native_catalog structures exact help, reports misses and retains command leases', async () => { const queries = [], events = [], writes = []; const metadata = {documentId: 27, documentIndex: 2, revision: 8, parameterFormat: 'native documentation'}; const items = [ {id: 'layer.list', parameterDocs: '宿主读取说明', requiresRevisionLease: false, enabled: true}, {id: 'type.edit', parameterDocs: '宿主编辑说明', requiresRevisionLease: true, enabled: false, reason: '等待写入权限'}, {id: 'layer.setProps', parameterDocs: '宿主图层属性说明'}, {id: 'layer.layerStyle.stroke', parameterDocs: '宿主描边说明'}, {id: 'path.moveHandle', parameterDocs: '宿主控制柄说明'}, ]; const host = { store: {appendEvent: async event => events.push(event)}, canvas: { nativeCatalog: async query => { queries.push(query); return {...metadata, matchMode: query.id ? 'exact-id' : 'any-keyword', items: items.filter(item => item.id === query.id), nativeTiming: {totalMs: 1}}; }, nativeCall: async () => ({completed: true, executed: true, revision: 8}), requestWrite: async revision => { writes.push(revision); return {allowed: true, revision}; }, }, }; const [catalog, call] = nativeTools(host, (_name, _description, _parameters, execute) => ({execute})); const args = {id: ' layer.list ', ids: ['layer.list', 'type.edit', ' type.edit ', 'unknown.command', ' '], filter: 'ignored', offset: 2, limit: 1}; const tool = {name:'native_catalog',parameters:nativeCatalogParameters}; assert.deepEqual(validateToolArguments(tool,{name:tool.name,arguments:args}),args); for (const invalid of [{ids: []}, {ids: ['']}, {ids: Array.from({length: 13}, (_, i) => String(i))}, {ids: ['x'.repeat(161)]}]) { assert.throws(()=>validateToolArguments(tool,{name:tool.name,arguments:invalid})); } const batch=await catalog.execute(args); assert.deepEqual({...batch,items:batch.items.map(({parameterDocs,...item})=>({...item,parameterDocs:parameterDocs.nativeText}))}, { ...metadata, parameterFormat:'structured-help',matchMode: 'exact-ids', total: 2, items:items.slice(0,2), missingIds: ['unknown.command'], }); assert.deepEqual(batch.items[0].parameterDocs,{nativeText:'宿主读取说明'}); assert.equal(batch.items[1].parameterDocs.properties.box.unit,'px'); const expectedQueries = [{id: 'layer.list'}, {id: 'type.edit'}, {id: 'unknown.command'}]; assert.deepEqual(queries, expectedQueries); assert.equal(events.filter(event => event.type === 'native_catalog_timing' && event.totalMs === 1).length, 3); await call.execute({revision: 8, method: 'engine.execute', params: {command: 'layer.list'}}); assert.deepEqual(writes, []); await call.execute({revision: 8, method: 'engine.execute', params: {command: 'type.edit'}}); assert.deepEqual(writes, [8]); assert.deepEqual(queries, expectedQueries); const examples=await catalog.execute({ids:['layer.setProps','layer.layerStyle.stroke','path.moveHandle']}); const [props,stroke,handle]=examples.items.map(item=>item.parameterDocs); assert.equal(props.properties.opacity.unit,'fraction'); assert.equal(props.properties.opacity.maximum,1); assert.equal(stroke.properties.opacity.unit,'percent'); assert.equal(stroke.properties.opacity.maximum,100); assert.deepEqual(stroke.properties.position.enum,['inside','outside','center']); assert.deepEqual(handle.required,['subpath','knot','handle','to']); assert.deepEqual(await catalog.execute({id: ' layer.list '}), { ...metadata,parameterFormat:'structured-help',matchMode:'exact-id', items:[{...items[0],parameterDocs:{nativeText:items[0].parameterDocs}}], }); await catalog.execute({filter: 'layer', offset: 1, limit: 3}); assert.deepEqual(queries.slice(-2), [{id: 'layer.list'}, {filter: 'layer', offset: 1, limit: 3}]); }); 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:'{}'}),/本机拒绝该操作/); } 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(); await assert.rejects(round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}),{dispatchState:'not_dispatched'}); assert.equal(requests.length,1); assert.equal(requests[0].id,round.id); } 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); assert.throws(()=>broker.round({invocationHeaders:{Authorization:'Bearer test'}}),/路由选项头/); assert.throws(()=>broker.round({invocationHeaders:{'X-Relay-Route-Option':'not-a-uuid'}}),/路由选项头/); const unpinned=broker.round({invocationHeaders:{}}); await unpinned.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}); assert.deepEqual(requests[1].input.invocationHeaders,{}); }); 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('an exit signal during native broker startup prevents the original request from being sent', async () => { let admit, enter; const startup = new Promise(resolve => { admit = resolve; }); const entered = new Promise(resolve => { enter = resolve; }); const broker = new Native98kBroker({project:randomUUID()}); const abort = new AbortController(); const requests = []; broker.scope = 'fixture'; broker.open = async () => { enter(); await startup; broker.child = {stdin:{write:bytes => requests.push(bytes)},kill(){}}; }; const pending = broker.round().fetch('https://api.vip98k.com/v1/chat/completions', {method:'POST',body:'{}',signal:abort.signal}); await entered; abort.abort(Error('退出已停止接单')); admit(); await assert.rejects(pending, /退出已停止接单/); assert.deepEqual(requests, []); }); test('forcing the daemon model bridge closed also closes its goal and slot processes', async t => { const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-wire-')); t.after(() => cleanup(profile)); const killed = []; let serial = 0; const parent = new Native98kBroker({project:randomUUID(),profile,spawnProcess:() => { const pid = ++serial; const child = new EventEmitter(); child.stdin = new PassThrough(); child.stdout = new PassThrough(); child.stderr = new PassThrough(); child.kill = () => { killed.push(pid); child.stdout.end(); child.stderr.end(); child.emit('close',0); }; return child; }}); await parent.open(); await parent.forDetailSlot('goal').open(); await parent.forDetailSlot('cover').open(); await parent.close({force:true}); assert.deepEqual(killed.sort(), [1,2,3]); await assert.rejects(parent.forDetailSlot('late').open(), /模型桥已关闭/); }); 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'}}]); } }); const sse = (delta, finish) => `data: ${JSON.stringify({ id: 'wire', model: 'qa', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\ndata: [DONE]\n\n`; const outcomeUnknownMessage = 'The request was sent, but its final outcome could not be confirmed. Do not retry with a new idempotency key.'; const gatewayErrorFrame = (code = 'request_outcome_unknown') => 'data: '+JSON.stringify({error:{ code,message:outcomeUnknownMessage,type:'server_error', }})+'\n\n'; test('a lost local native ACK leaves no lock across turns and legacy receipts can still be reconciled', async t => { const dir=await fs.mkdtemp(path.join(os.tmpdir(),'pi-recovery-native-operation-')); t.after(()=>cleanup(dir)); const identity={scope:'a'.repeat(64),project:randomUUID()}; const store=await ProjectStore.open(dir,identity,{brandId:'qa',shopId:'A',categoryId:'desk',platform:'qa',version:'1',source:'qa',rules:[]}); const originalRun=randomUUID(), documentId=7, canvasIdentity={accountId:'account',origin:'https://example.invalid'}; const make=(name,_description,_schema,execute)=>({name,execute}); const method=(host,name)=>nativeTools(host,make).find(tool=>tool.name===name).execute; let clientOperationId, dispatches=0; const host={store,turnEpoch:1,canvas:{run:originalRun,documentId,identity:canvasIdentity, nativeCatalog:async()=>({items:[]}),requestWrite:async()=>({allowed:true,revision:4}), nativeCall:async input=>{ clientOperationId=input.clientOperationId; dispatches++; if(dispatches===1)throw new BridgeError('模拟首包丢失','transport_interrupted',{dispatched:true}); return {completed:true,executed:true,revision:4}; }, }}; await assert.rejects(method(host,'native_call')({revision:4,method:'engine.execute',params:{command:'layer.setProps'}}),/模拟首包丢失/); assert.equal(await store.get('native-unresolved-7.json',null),null); const priorOperationId=clientOperationId; await fs.writeFile(path.join(store.dir,'native-unresolved-7.json'),JSON.stringify({ kind:'native',clientOperationId:priorOperationId,run:originalRun,documentId, })); const reopened={store,turnEpoch:2,canvas:{...host.canvas,run:randomUUID(),nativeReconcile:async input=>{ assert.equal(input.clientOperationId,priorOperationId); assert.equal(input.run,originalRun); return {...input,source:'retained-native-receipt',state:'done',completed:true,executed:true,applied:true,applicationVerified:true}; }}}; const next=await method(reopened,'native_call')({revision:4,method:'engine.execute',params:{command:'layer.setProps'}}); assert.equal(next.completed,true); assert.equal((await method(reopened,'native_reconcile')()).results[0].status,'applied'); assert.equal(await store.get('native-unresolved-7.json',null),null); assert.equal(dispatches,2); }); 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 = [], routes = []; const broker = { info: async () => ({ accountScope: scope, model: recovery?.model ?? { id: 'qa', protocol: 'openai-chat' }, thinkingLevel: recovery?.thinkingLevel, candidates:recovery?.candidates,pending: [] }), round({retryOf,invocationHeaders}={}) { if(retryOf) retries.push(retryOf); const id=randomUUID(); return { id, fetch: async (url, init) => { routes.push({path:new URL(url).pathname,invocationHeaders}); const p = JSON.parse(init.body); requests.push(p); ids.push(id); const result=await reply(p,requests.length); return result instanceof Response ? result : new Response(result,{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()=>{},finishProduction:async input=>productionExportReceipt(input),...(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 openAgent({ store, broker, callBudget: production?.callBudget??3, canvas, productionGoal }); if(production&&productionGoal.outputId)stubProductionOperations(host,productionGoal,{ plan_production:args=>production.plan?.(args)??{pendingText:0}, finish_production:async()=>({text:'已核对导出。',production:{...productionGoal,complete:true,canvasRevision:1}}), }); host.streamRetryBaseMs=1; return { host, store, requests, ids, retries, routes, close: async () => { await host.dispose(); await cleanup(dir); } }; } const chatRoute={protocol:'openai-chat',path:'/v1/chat/completions',headers:{}}; const responsesRoute={protocol:'openai-responses',path:'/v1/responses',headers:{'X-Relay-Route-Option':randomUUID()}, maxTokens:3072,requiresOutputLimit:true,reasoning:false}; test('a routing preflight rejection of reasoning retries only the same Responses route',async t=>{ const route={...responsesRoute,reasoning:true,reasoningEfforts:['low']}; const event=(type,details)=>'event: '+type+'\ndata: '+JSON.stringify({type,...details})+'\n\n'; const item={type:'message',id:'msg_ready',role:'assistant',status:'completed', content:[{type:'output_text',text:'已读取画布。',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:'已读取画布。'}) +event('response.output_item.done',{output_index:0,item}) +event('response.completed',{response:{model:'qa',status:'completed',output:[item]}}); const x=await setup((_payload,n)=>n===1 ? Response.json({error:{code:'invalid_request', message:'The request parameter "reasoning" is not supported by the selected model.'}},{status:400}) : response, undefined,undefined,{model:{...route,id:'qa'},candidates:[route,chatRoute],thinkingLevel:'low'}); t.after(x.close); assert.equal((await x.host.prompt('看一下当前画布')).text,'已读取画布。'); assert.equal((await x.host.prompt('再看一下')).text,'已读取画布。'); assert.equal(x.requests[0].reasoning.effort,'low'); assert.equal(x.requests.length,3); assert.ok(x.requests.slice(1).every(request=>!Object.hasOwn(request,'reasoning'))); assert.ok(x.routes.every(request=>request.path===route.path && request.invocationHeaders['X-Relay-Route-Option']===route.headers['X-Relay-Route-Option'])); }); test('openai-chat with reasoning=true and thinking=off omits reasoning_effort instead of sending "off"',async t=>{ const route={...chatRoute,id:'deepseek-v4.1-flash-1017',reasoning:true,reasoningEfforts:['low','high','max']}; const x=await setup(()=>sse({content:'已关闭思考直接回复。'},'stop'), undefined,undefined,{model:route,candidates:[route],thinkingLevel:'off'}); t.after(x.close); assert.equal((await x.host.prompt('直接回答')).text,'已关闭思考直接回复。'); assert.equal(x.requests.length,1); assert.equal(Object.hasOwn(x.requests[0],'reasoning_effort'),false); }); test('openai-responses with reasoning=true and thinking=off never sends reasoning.effort="off"',async t=>{ const route={...responsesRoute,id:'gpt-5.4-mini',reasoning:true,reasoningEfforts:['low','high']}; const item={type:'message',id:'msg_off',role:'assistant',status:'completed', content:[{type:'output_text',text:'已关闭思考。',annotations:[]}]}; const event=(type,details)=>'event: '+type+'\ndata: '+JSON.stringify({type,...details})+'\n\n'; 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:'已关闭思考。'}) +event('response.output_item.done',{output_index:0,item}) +event('response.completed',{response:{model:'gpt-5.4-mini',status:'completed',output:[item]}}); const x=await setup(()=>response,undefined,undefined,{model:route,candidates:[route],thinkingLevel:'off'}); t.after(x.close); assert.equal((await x.host.prompt('直接回答')).text,'已关闭思考。'); assert.equal(x.requests.length,1); assert.notEqual(x.requests[0].reasoning?.effort,'off'); assert.equal(Object.hasOwn(x.requests[0],'reasoning'),false); }); test('openai-chat HTTP 422 on reasoning_effort strips reasoning and retries the same route immediately',async t=>{ const route={...chatRoute,id:'deepseek-v4.1-flash-1017',reasoning:true,reasoningEfforts:['low','high','max']}; const errorText="Failed to deserialize the JSON body into the target type: reasoning_effort: unknown variant 'high', expected one of 'none', 'minimal', 'low', 'medium', 'high'"; const x=await setup((_payload,n)=>n===1 ? new Response(errorText,{status:422,headers:{'content-type':'text/plain; charset=utf-8'}}) : sse({content:'降级重试成功。'},'stop'), undefined,undefined,{model:route,candidates:[route,responsesRoute],thinkingLevel:'high'}); t.after(x.close); assert.equal((await x.host.prompt('测试422降级')).text,'降级重试成功。'); assert.equal((await x.host.prompt('下一轮')).text,'降级重试成功。'); assert.equal(x.requests[0].reasoning_effort,'high'); assert.equal(x.requests.length,3); assert.ok(x.requests.slice(1).every(request=>!Object.hasOwn(request,'reasoning_effort') && !Object.hasOwn(request,'reasoning'))); assert.ok(x.routes.every(request=>request.path===route.path)); }); test('HTTP 503 before streaming retries the selected route and keeps it for the next turn',async t=>{ const selection={model:{id:'qa',protocol:'openai-chat'},candidates:[chatRoute,responsesRoute]}; const x=await setup((_payload,n)=> n===1 ? Response.json({error:{code:'service_unavailable',message:'Unavailable'}},{status:503}) : sse({content:'已读取当前画布。'},'stop'),undefined,undefined,selection); t.after(x.close); assert.equal((await x.host.prompt('查看当前进展')).text,'已读取当前画布。'); assert.equal(x.host.activeProtocol,'openai-chat'); await x.host.prompt('继续核对'); assert.deepEqual(x.routes,Array(3).fill({path:chatRoute.path,invocationHeaders:{}})); const events=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse); const failure=events.find(row=>row.type==='provider_error'); assert.equal(failure.httpStatus,503); assert.equal(failure.upstreamCode,'service_unavailable'); assert.equal(failure.reason,'Unavailable'); assert.equal(failure.willRetry,true); }); test('a failed SSE response retries on the same route and replaces partial visible prose',async t=>{ const updates=[]; const x=await setup((_payload,n)=>n===1 ? sse({content:'该段没有完成'},null).replace('data: [DONE]\n\n','')+gatewayErrorFrame() : sse({content:'已恢复对话。'},'stop'),undefined,undefined,{ model:{id:'qa',protocol:'openai-chat'},candidates:[chatRoute,responsesRoute], canvas:{delta:async text=>updates.push(text)}, }); t.after(x.close); assert.equal((await x.host.prompt('继续制作')).text,'已恢复对话。'); assert.equal(updates.at(-1),'已恢复对话。'); assert.deepEqual(x.routes,Array(2).fill({path:chatRoute.path,invocationHeaders:{}})); }); test('the terminal bridge outcome takes precedence over a complete-looking model stream',async t=>{ const tool={index:0,id:'unconfirmed-tool',type:'function',function:{name:'memory_set', arguments:JSON.stringify({key:'color',value:'胡桃色',evidence:'测试颜色是胡桃色'})}}; const x=await setup(()=>sse({tool_calls:[tool]},'tool_calls')); t.after(x.close); const bridge=x.host.broker; const round=bridge.round.bind(bridge); const originalRequestId=randomUUID(); bridge.round=(...args)=>{ const attempt=round(...args), outcome={}; return {...attempt,outcome,async settled(){ Object.assign(outcome,{dispatchState:'committed_error',originalRequestId,actualProtocol:'openai-chat'}); }}; }; await assert.rejects(x.host.prompt('测试颜色是胡桃色,请记住。'),{dispatchState:'committed_error',originalRequestId}); assert.equal(x.requests.length,1); assert.deepEqual((await x.store.context()).confirmedMemory,{}); }); test('HTTP 429 does not trigger cross-protocol failover',async t=>{ const x=await setup(()=>new Response('{"error":{"message":"Rate limit"}}', {status:429,headers:{'content-type':'application/json'}}),undefined,undefined,{ model:{id:'qa',protocol:'openai-chat'},candidates:[chatRoute,responsesRoute], }); t.after(x.close); x.host.session.settingsManager.getRetrySettings=()=>({enabled:false,maxRetries:0}); x.host.streamRetryBaseMs=1; await assert.rejects(x.host.prompt('核对当前画布'),/对话服务暂时连接不上/); assert.ok(x.routes.length>=1); assert.ok(x.routes.every(r=>r.path===chatRoute.path && Object.keys(r.invocationHeaders).length===0)); }); test('the native Google converter sends its published path and handles a streamed reply through the bridge', {timeout:30_000}, async t=>{ const frame={candidates:[{index:0,content:{role:'model',parts:[{text:'已核对画布'}]},finishReason:'STOP'}], usageMetadata:{promptTokenCount:8,candidatesTokenCount:5,totalTokenCount:13}}; const x=await setup(()=>`data: ${JSON.stringify(frame)}\n\n`,undefined,undefined,{ model:{id:'gemini-2.5-flash',protocol:'google-generative-ai',provider:'google',maxTokens:256,supportsImageInput:true}, }); t.after(x.close); const reply=await x.host.prompt('查看项目'); assert.equal(reply.text,'已核对画布'); assert.equal(x.routes[0].path,'/v1beta/models/gemini-2.5-flash:streamGenerateContent'); assert.ok(x.requests[0].contents.some(row=>row.parts.some(part=>part.text==='查看项目'))); assert.equal(x.requests.length,1); }); test('ordinary native calls wait for a background save and report the live revision on drift',async()=>{ const writes=[], calls=[]; let drift=false; const host={canvas:{ nativeCatalog:async({id})=>({items:[{id,requiresRevisionLease:true}]}), requestWrite:async revision=>{ writes.push(revision); if (drift) return {allowed:false,writeBlocked:false,retryWrite:true,revision:9,changedLayers:[6]}; if (writes.length===1) return {allowed:false,writeBlocked:false,retryWrite:true,revision}; return {allowed:true,revision}; }, nativeCall:async args=>{calls.push(args);return {completed:true,executed:true,revision:8};}, },store:{appendEvent:async()=>{}}}; const [,call]=nativeTools(host,(_name,_description,_parameters,execute)=>({execute})); const args={revision:7,method:'engine.execute',params:{command:'type.edit',params:{layer:6,text:'修改'}}}; assert.equal((await call.execute(args)).revision,8); assert.deepEqual(writes,[7,7]); drift=true; await assert.rejects(call.execute(args),error=> error.category==='revision_conflict' && error.currentRevision===9 && error.changedLayers[0]===6); assert.equal(calls.length,1); }); 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)return call('reconcile_image_slots',{}); if(n===4){ assert.match(JSON.stringify(payload.messages),new RegExp(instruction,'u')); const receipt=payload.messages.findLast(message=>message.role==='tool'); assert.deepEqual(JSON.parse(receipt.content),{scope:'project',results:[]}); return call('native_catalog',{id:'layer.setProps'}); } if(n===5){ assert.match(JSON.stringify(payload.messages),/production_canvas_pending/u); return call('open_production_output',outputs[1]); } if(n===6){ assert.match(JSON.stringify(payload.messages),/gallery.*revision/u); return call('native_catalog',{id:'layer.setProps'}); } if(n===7){ assert.match(JSON.stringify(payload.messages),/requiresRevisionLease/u); return call('finish_production',{revision:1}); } return sse({content:'已核对画册。'},'stop'); },undefined,{outputs,template,callBudget:8,canvas:{ imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId:'gallery',productVariantId:outputs[1].variantId, template:{contentHash:'fixture'},totalSlots:0,slots:[]}), 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); stubProductionOperations(x.host,args,{ finish_production:async({revision})=>({production:{...args,canvasRevision:revision,complete:true}})}); return {...args,revision:1,pendingOutputs:[outputs[0]]}; }, }}); try{ x.host.productEvidence={product:{name:'灯具',brandName:'测试品牌',categoryName:'灯具'}}; x.host.openProductionKnowledge=async templateId=>{ const entry = 'fixture/SKILL.md'; return openXiaoyiSkills(x.host.store,templateId,undefined,undefined,xiaoyiFixture(templateId,'3',entry,{ [entry]:'---\nname: fixture\ndescription: Fixture project order\n---\n'+instruction, })); }; 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,7); assert.ok(x.host.manager.getBranch().some(row=>row.customType==='production-goal'&&row.data.goal.status==='complete')); }finally{await x.close();} }); test('the model dispatcher retries an explicitly unavailable route once', async () => { const x = await setup((_p, n) => n === 1 ? new Response(JSON.stringify({error:{message:'Rate limit exceeded'}}),{status:503,headers:{'retry-after':'0'}}) : 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(); } }); for (const committed of [false,true]) test(`${committed?'A committed Responses error':'An HTTP 503 native inference receipt'} settles according to the dispatch outcome`, 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 item={id:'fc_ok',type:'function_call',call_id:'call_ok',name:'finish_production', arguments:JSON.stringify({revision:7,scope:"all"})}; 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=requests.length>1; const streaming=success||committed; emit({type:'headers',status:streaming?200:503,requestId:success?randomUUID():originalId, headers:{'content-type':streaming?'text/event-stream':'application/json'},bodyHash:'native-wire'}); const send=chunk=>emit({type:'chunk',data:Buffer.from(chunk).toString('base64')}); if(success)send(response); else if(committed){ const frame=gatewayErrorFrame(); const split=frame.indexOf('request_outcome_unknown')+8; send(event('response.created',{response:{id:'resp_lost',status:'in_progress'}})+frame.slice(0,split)); send(frame.slice(split)); } else send(JSON.stringify({error:{code:'service_unavailable',type:'server_error',message:'Service temporarily unavailable'}})); return success?{phase:'complete'}:committed ? {dispatchState:'outcome_unknown',originalRequestId:originalId,actualProtocol:'openai-responses'} : {dispatchState:'retryable_error',originalRequestId:originalId,actualProtocol:'openai-responses'}; }; const canvas={begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){},activity:async()=>{},delta:async()=>{},end:async()=>{},finishProduction:async input=>productionExportReceipt(input)}; const variantId=randomUUID(); const productionGoal={outputId:'detail',variantId,workspaceId:randomUUID(),requestedOutputs:[{outputId:'detail',variantId}], deadline:Math.floor(Date.now()/1000)+90}; host=await openAgent({store,broker,canvas,productionGoal,callBudget:4}); host.streamRetryBaseMs=1; const settings=host.session.settingsManager, retry=settings.getRetrySettings(); settings.getRetrySettings=()=>({...retry,baseDelayMs:1,maxDelayMs:1}); const retries=[]; host.session.subscribe(event=>{if(event.type==='auto_retry_start')retries.push(event);}); stubProductionOperations(host,productionGoal,{finish_production:async input=>{ operations.push(input); return {text:'已核对导出。',production:{...productionGoal,complete:true,canvasRevision:input.revision}}; }}); const resumed=await host.prompt('继续制作当前画布'); assert.equal(resumed.production.complete,true); assert.deepEqual(operations,[{revision:7,scope:'all'}]); assert.equal(requests.length,2); assert.notEqual(requests[0].id,requests[1].id); assert.deepEqual(finished,[]); assert.deepEqual(retries,[]); const journal=(await fs.readFile(path.join(store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse); assert.ok(journal.some(row=>row.type==='provider_finished'&&row.id===originalId&& row.dispatchState===(committed?'outcome_unknown':'retryable_error'))); }); test('the main agent and six workers retry simultaneous pre-header disconnects on their own routes', async t => { const firstWave=Promise.withResolvers(); const x=await setup(async(_payload,n)=>{ if(n===7)firstWave.resolve(); if(n<=7){ await firstWave.promise; throw new BridgeError('网关等待响应头超时','transport_interrupted',{code:'headers_timeout',dispatchState:'outcome_unknown'}); } return sse({content:'已恢复。'},'stop'); },undefined,undefined,{canvas:{}}); t.after(x.close); const [main]=await Promise.all([x.host.prompt('核对制作进度'), ...Array.from({length:6},(_,index)=>x.host.runDetailAgent('slot-'+index,'核对资料。','核对当前图位。',[],[]))]); assert.equal(main.text,'已恢复。'); assert.equal(new Set(x.ids).size,14); const events=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse); const failures=events.filter(row=>row.type==='provider_error'); assert.equal(failures.length,7); assert.equal(new Set(failures.map(row=>row.slotId)).size,7); assert.ok(failures.every(row=>row.upstreamCategory==='transport_interrupted'&& row.upstreamCode==='headers_timeout'&&row.willRetry)); }); test('aborting during inference backoff prevents a second request',async t=>{ const x=await setup(()=>Response.json({error:{code:'too_many_requests',message:'Slow down'}},{ status:429,headers:{'retry-after':'60'}, }),undefined,undefined,{canvas:{}}); t.after(x.close); const retrying=Promise.withResolvers(); const append=x.store.appendEvent.bind(x.store); x.store.appendEvent=async event=>{ await append(event); if(event.type==='provider_failover')retrying.resolve(); }; const stop=new AbortController(); const running=x.host.runDetailAgent('slot-a','核对资料。','核对图位。',[],[],'slot-a',undefined,stop.signal); await retrying.promise; stop.abort(Error('用户停止制作')); await assert.rejects(running,/用户停止制作/u); assert.equal(x.requests.length,1); }); test('a native production user turn runs tools and returns control when the model settles',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:()=>({outputId:'detail',variantId:'oak',pendingText:1,field:++plans===1?'标题':'规格'}), progress:()=>({state:{fields:[plans===1?'标题':'规格']}}), }); try { const result=await x.host.prompt('完成整套制作'); assert.equal(result.production.complete,false); assert.equal(plans,1); assert.equal(x.requests.length,2); assert.match(JSON.stringify(x.requests[0].messages.findLast(message=>message.role==='user')),/完成整套制作/); assert.doesNotMatch(JSON.stringify(x.requests),/\/goal /); } finally { await x.close(); } }); test('an interrupted inference stream executes only the confirmed tool call after retry', 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()=>({phase:'complete'}),{ 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('inference exhaustion after a confirmed write retains the edit and reports in Chinese', async t => { const write={index:0,id:'confirmed-memory',type:'function',function:{name:'memory_set', arguments:JSON.stringify({key:'color',value:'胡桃色',evidence:'产品是胡桃色'})}}; const x=await setup((_payload,n)=>n===1?sse({tool_calls:[write]},'tool_calls'):new Response(new ReadableStream({ start(controller) { controller.error(new TypeError('network error: mock stream disconnected')); }, }),{headers:{'content-type':'text/event-stream'}})); x.host.callBudget=10; t.after(()=>x.close()); const settings=x.host.session.settingsManager; const retry=settings.getRetrySettings(); settings.getRetrySettings=()=>({...retry,baseDelayMs:1,maxDelayMs:1}); await assert.rejects(x.host.prompt('产品是胡桃色,请记住并核对进度'),error=> error.dispatchState===undefined && /对话服务暂时连接不上.*已保留/u.test(error.message)); assert.equal(retry.enabled,false); assert.equal(x.requests.length,5); assert.equal((await x.store.context()).confirmedMemory.color.value,'胡桃色'); }); 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, undefined); 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 ? new Response('{}',{status:503}) : 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,128_000); 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('Pi reports malformed tool arguments and never executes a length-stopped write', async () => { for (const [args, finish] of [['{"key":"color","value":"红色","evidence":"测试颜色是红色"', 'tool_calls'], ['{"key":"color","value":"红色","evidence":"测试颜色是红色"}', 'length']]) { const x = await setup((payload, n) => { if (n===1) return sse({tool_calls:[{index:0,id:'partial',type:'function',function:{name:'memory_set',arguments:args}}]},finish); const toolResult=payload.messages.find(message=>message.role==='tool'&&message.tool_call_id==='partial'); assert.ok(toolResult); if(finish==='length')assert.match(JSON.stringify(toolResult),/output token limit/); return sse({content:'本轮未写入。'},'stop'); }); try { assert.equal((await x.host.prompt('测试颜色是红色')).text,'本轮未写入。'); assert.deepEqual((await x.store.context()).confirmedMemory, {}); assert.equal(x.requests.length,2); } 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); }); async function compactionFixture({ withCanvas, callBudget = 4, large = false, contextWindow = 64_000, historyInput = large ? 50_000 : 5_000, pendingStep, rateLimit = false, waitForAbort } = {}) { 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: historyInput, output: 500, cacheRead: 0, cacheWrite: 0, totalTokens: historyInput + 500, 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 requests = []; 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, contextWindowSource:'fixture', reasoning:true, reasoningEfforts:['low','high'] }, thinkingLevel:'high', pending: [] }, stream(model, context, options) { requests.push({model:model.id, systemPrompt:getCurrentSystemPrompt(context.messages), reasoning:options.reasoning}); 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 } } }; if (waitForAbort) { options.signal.addEventListener('abort', () => stream.end({...message, content:[], stopReason:'aborted'}), {once:true}); waitForAbort(); return stream; } 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('{"error":{"code":"service_unavailable","type":"server_error"}}', {status:503,headers:{'content-type':'application/json'}}); } 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 openAgent({ store, transport:broker?undefined:transport, broker, canvas, callBudget, productionGoal:goal }); return { host, requests, 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.deepEqual(x.host.session.settingsManager.getCompactionSettings(x.host.session.model), {enabled:true,reserveTokens:32_000,keepRecentTokens:12_000}); 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('stopping a production turn aborts an active context compaction', {timeout:3000}, async () => { const entered = Promise.withResolvers(); const x = await compactionFixture({waitForAbort:entered.resolve}); const stop = new AbortController(); try { x.host.productionSignal = stop.signal; const compacting = assert.rejects(x.host.compact()); await entered.promise; stop.abort(Error('production stopped')); await compacting; assert.equal(x.host.operationActive, false); assert.equal(x.host.contextUsage.phase, 'ready'); } finally { await x.close(); } }); test('a million-token session automatically compacts past the main budget and preserves production instructions',async()=>{ const x=await compactionFixture({large:true,contextWindow:1_000_000,historyInput:38_000}); try { const settings=x.host.session.settingsManager; assert.deepEqual(settings.getCompactionSettings(x.host.session.model),{enabled:true,reserveTokens:968_000,keepRecentTokens:12_000}); assert.equal(settings.getRetrySettings().enabled,false); assert.equal(settings.getRetrySettings().maxRetries,0); await x.host.prompt('继续'); assert.equal(x.calls,2); const compactionSettings=settings.getCompactionSettings(x.host.session.model); assert.equal(shouldCompact(38_500,1_000_000,DEFAULT_COMPACTION_SETTINGS),false); assert.equal(shouldCompact(32_000,1_000_000,compactionSettings),false); assert.equal(shouldCompact(32_001,1_000_000,compactionSettings),true); const summaries=x.requests.slice(0,-1); for (const {systemPrompt,reasoning} of summaries) { assert.equal(reasoning,'low'); for (const fact of [ '在途及已付费','出图请求号','候选号','各图位状态','各图位已采用的候选', '已做的决定及理由','未解决的问题','当前成品','当前屏','锁定的知识库版本','已写出的文件路径', 'userCanvasChanges','steer / followUp', ]) { assert.ok(systemPrompt.includes(fact),fact); } } assert.equal(x.requests.at(-1).reasoning,'high'); assert.ok(x.requests.every(request=>request.model==='qa')); 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 uses the same dispatcher for a safe pre-stream retry', 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 exact reference identities and instructions for acting on them', async()=>{ const x=await setup(()=>sse({content:'已核对。'},'stop')); try { const candidate={label:'椅背候选',source:'图片资源',kind:'candidate',nativeLayerId:1502,component:'layer', layerKind:'Smart Object',slotId:'M04-I01',fieldId:'hero',candidateId:'candidate-2',taskId:'task-2', outputId:'detail',productVariantId:'wood',documentId:7}; const mask={label:'像素蒙版',kind:'layer',nativeLayerId:1503,component:'pixelMask'}; await x.host.prompt('评估这张候选图和蒙版', {referenceContent:[candidate, mask]}); const wire=x.requests[0].messages; const text=wire.findLast(message=>message.role==='user').content; const quoted=JSON.parse((typeof text==='string' ? text : text.find(item=>item.type==='text').text).split('以下文字为引用内容):')[1]); assert.deepEqual(quoted, [candidate,{...mask,source:'发送时的画布图层'}]); const system=wire.find(message=>message.role==='system').content; for (const term of ['用户明确指代的对象','pixelMask','adopt_production_image','以该 candidateId 为父版本','保留模板原图定义']) { assert.match(system,new RegExp(term)); } } finally {await x.close();} }); test('a production goal carries candidate and slot references with their actual image into the request',async()=>{ const image='iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP43+AARwzEcQDiohvxgB7+wgAAAABJRU5ErkJggg=='; const slot={kind:'slot',label:'椅背图位',slotId:'back',outputId:'detail',productVariantId:'oak'}; const candidate={...slot,kind:'candidate',label:'椅背第二版',candidateId:'back-v2'}; const refinement={slotId:slot.slotId,reworkCandidateId:candidate.candidateId,prompt:'椅背居中,保留原商材。'}; const call=(name,args)=>sse({tool_calls:[{index:0,id:name,type:'function',function:{name,arguments:JSON.stringify(args)}}]},'tool_calls'); const x=await setup((_payload,n)=>n===1?call('prepare_image_request',refinement): n===2?call('finish_production',{revision:1}):sse({content:'已核对。'},'stop'),undefined,{deadline:1}); const received=[]; try { const {outputId,variantId}=x.host.productionGoal; const operations=await x.host.productionWork.get(JSON.stringify([outputId,variantId])); operations.prepare_image_request=async args=>{ received.push(args); return {requestId:'refinement-draft',reworkOf:args.reworkCandidateId}; }; await x.host.prompt('引用第二版,微调椅背构图。',{referenceContent:[slot,{...candidate,image,mimeType:'image/png'}]}); const reference=x.requests[0].messages.find(row=>Array.isArray(row.content)&& row.content.some(part=>part.type==='text'&&part.text.includes('椅背第二版'))); const request=reference.content.find(part=>part.type==='text').text; const quoted=JSON.parse(request.split('以下文字为引用内容):')[1]); assert.deepEqual(quoted,[ {...slot,source:'本轮引用'}, {...candidate,source:'候选图',image:1}, ]); assert.ok(reference.content.some(part=>part.type==='image_url'&&part.image_url.url===`data:image/png;base64,${image}`)); assert.deepEqual(received,[refinement]); } 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('main requests keep their original identity without saving a copy of the request body',async t=>{ const setting='XIAOYI_DUMP_RAW_PAYLOADS'; const previous=process.env[setting]; delete process.env[setting]; t.after(()=>{if(previous===undefined)delete process.env[setting];else process.env[setting]=previous;}); const image='iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP43+AARwzEcQDiohvxgB7+wgAAAABJRU5ErkJggg=='; const url=`data:image/png;base64,${image}`; const x=await setup(()=>sse({content:'已查看。'},'stop')); t.after(x.close); const readImageUrl=payload=>payload.messages.flatMap(row=>Array.isArray(row.content)?row.content:[]) .find(part=>part.type==='image_url')?.image_url.url; await x.host.prompt('检查附件',{referenceContent:[{label:'测试图',image,mimeType:'image/png'}]}); assert.equal(readImageUrl(x.requests.at(-1)),url); await assert.rejects(fs.access(path.join(x.store.dir,'payloads')), {code:'ENOENT'}); const journal=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8'); assert.equal(journal.includes(image),false); const events=journal.trim().split('\n').map(line=>JSON.parse(line)); const budget=events.find(event=>event.type==='context_budget'); assert.equal(budget.originalChars-budget.inputChars,image.length); const requests=events.filter(event=>event.type==='provider_started'); assert.deepEqual(requests.map(event=>event.id),x.ids); assert.ok(events.some(event=>event.type==='usage' && event.id===x.ids[0] && event.purpose==='conversation')); assert.ok(events.some(event=>event.type==='provider_finished' && event.id===x.ids[0])); process.env[setting]='1'; await x.host.prompt('继续核对'); await assert.rejects(fs.access(path.join(x.store.dir,'payloads')),{code:'ENOENT'}); }); test('a worker can change course after many identical calls without terminating',async t=>{ const calls=[], imageCounts=[]; const image={type:'image',mimeType:'image/png', data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=='}; const x=await setup((payload,round)=>{ imageCounts.push(payload.messages.reduce((count,{content})=>count+ (Array.isArray(content)?content.filter(part=>part.type==='image_url').length:0),0)); return sse({tool_calls:[{index:0,id:`worker-${round}`,type:'function',function:{name:'read_slot_images', arguments:JSON.stringify({item:round===10?'other':'same'})}}]},'tool_calls'); },undefined,undefined,{canvas:{}}); t.after(x.close); const tool={name:'read_slot_images',label:'Inspect item',description:'Inspect item',parameters:{type:'object',properties:{item:{type:'string'}},required:['item']}, async execute(_id,{item}){ calls.push(item); return {content:[{type:'text',text:item},image],details:{item},terminate:item==='other'}; }}; await x.host.runDetailAgent('slot-a','Inspect the item.','Read the fixture.',[tool],[],'product/slot/slot-a'); assert.deepEqual(calls,[...Array(9).fill('same'),'other']); assert.deepEqual(imageCounts,[0,...Array(9).fill(1)]); assert.equal(x.requests.length,10); }); test('worker tool events retain their output and variant after the working canvas changes',async t=>{ const x=await setup(()=>sse({tool_calls:[{index:0,id:'scope-worker',type:'function', function:{name:'prepare_image_request',arguments:'{}'}}]},'tool_calls'),undefined,undefined,{canvas:{}}); t.after(x.close); const detail={outputId:'detail',variantId:randomUUID()}; const main={outputId:'main_images',variantId:randomUUID()}; x.host.activityScope=main; x.store.executionScope=main; const recorded=Promise.withResolvers(); const append=x.store.appendEvent.bind(x.store); x.store.appendEvent=async event=>{ await append(event); if(event.type==='tool_execution_end')recorded.resolve(); }; const tool={name:'prepare_image_request',label:'准备生图',description:'准备生图',parameters:{type:'object',properties:{}}, async execute(){ x.host.activityScope={outputId:'sku_images',variantId:randomUUID()}; return {content:[{type:'text',text:'准备完成'}],terminate:true}; }}; await x.host.runDetailAgent('slot-a','Inspect.','Prepare.',[tool],[],'product/slot/slot-a',undefined,undefined,detail); await recorded.promise; const events=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line)); const worker=events.filter(event=>event.toolCallId==='scope-worker'); assert.equal(worker.length,2); assert.ok(worker.every(event=>event.outputId===detail.outputId && event.variantId===detail.variantId)); }); test('a retryable response at the worker limit does not trigger another Pi request',async t=>{ const x=await setup((_payload,round)=>{ if(round>=WORKER_TURN_LIMIT)return new Response('overloaded',{status:503}); return sse({tool_calls:[{index:0,id:`worker-${round}`,type:'function',function:{name:'submit', arguments:'{}'}}]},'tool_calls'); },undefined,undefined,{canvas:{}}); t.after(x.close); const tool={name:'submit',label:'Submit',description:'Submit',parameters:{type:'object',properties:{}}, execute(){throw Error('未找到受审编号,可用编号是 13');}}; await assert.rejects(x.host.runDetailAgent('screen-13','Inspect.','Review.',[tool],[]), error=>error.message.includes(`screen-13 在 ${WORKER_TURN_LIMIT} 轮内未提交有效结论`)&& error.message.includes('未找到受审编号,可用编号是 13')); assert.equal(x.requests.length,WORKER_TURN_LIMIT); }); test('Pi project tools share the same file boundary',async()=>{ const x=await setup(()=>sse({content:'已核对。'},'stop')); try { const exports=path.join(x.host.store.dir,'product-exports'); x.host.store.projectExportRoot=path.toNamespacedPath(exports); await fs.mkdir(exports); const image=path.join(exports,'sku.png'); await fs.writeFile(image,Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==','base64')); const metadata=path.join(exports,'manifest.json'); await fs.writeFile(metadata,'{}'); 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'}),/工作目录之外/); const exported=await tool('read').execute('5',{path:image}); assert.equal(exported.content.find(block=>block.type==='image')?.mimeType,'image/png'); await assert.rejects(tool('read').execute('6',{path:metadata}),/工作目录之外/); await assert.rejects(tool('write').execute('7',{path:image,content:'无'}),/工作目录之外/); 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); await assert.rejects(canvas.edit({command:'text'},rev,undefined,25),{category:'canvas_wait_timeout',dispatched:false,retryable:true}); apply=true; assert.equal((await canvas.edit({command:'text'},rev)).revision,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('private pipes carry a new canvas lease while one conversation waits for the original export receipt',async()=>{ const runs=new Set(); const variantId=randomUUID(); const detail={outputId:'detail',variantId}; const main={outputId:'main_images',variantId}; let binding, operationId; const canvas=new StdioCanvas(async(action,input)=>{ runs.add(input.run); if(action==='pi-begin')return {conversationActive:true}; if(action==='pi-production-open'){ assert.deepEqual(input.canvasBinding?.documentKey,binding?.documentKey); const previousSave=binding?{saved:true,revision:binding.revision,documentKey:binding.documentKey}:null; const documentKey={workspaceId:'workspace',outputId:input.outputId,variantId}; binding={outputId:input.outputId,variantId,documentKey,writeEpoch:(binding?.writeEpoch??0)+1, revision:7,previousSave,pendingOutputs:[detail,main]}; return {conversationActive:true,productionCanvas:binding}; } assert.deepEqual(input.canvasBinding,{documentKey:binding.documentKey,writeEpoch:binding.writeEpoch}); if(action==='pi-production-finish'){ operationId=input.operationId; assert.equal(input.canvasRevision,7); return {operationId,pending:true}; } assert.equal(action,'pi-production-finish-status'); assert.equal(input.operationId,operationId); return {operationId,canvasRevision:7,complete:true,files:[{path:'main.jpg'}],generationId:'verified-main', pendingOutputs:[detail]}; },13); await canvas.begin('制作两个成品'); const first=await canvas.openProductionOutput(detail); const second=await canvas.openProductionOutput(main); assert.equal(second.writeEpoch,first.writeEpoch+1); assert.deepEqual(second.previousSave,{saved:true,revision:7,documentKey:first.documentKey}); const receipt=await canvas.finishProduction({...main,complete:true,canvasRevision:7}); assert.equal(receipt.generationId,'verified-main'); assert.deepEqual(receipt.pendingOutputs,[detail]); await canvas.openProductionOutput(detail); assert.equal(runs.size,1); }); 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.deepEqual(validateToolArguments({name:'canvas_read',parameters:canvasReadParameters},{name:'canvas_read',arguments:query}),query); assert.deepEqual(canvasReadQuery(query),{mode:'summary',screenId:90,maxDepth:6,offset:0}); }); test('production exposes native controls and reads with other file tools deferred',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']){ assert.ok(names.includes(name),name); } for(const name of ['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')); assert.ok(x.host.session.getToolDefinition('write')); assert.equal((await x.host.prompt('核对制作工具')).production.complete,true); assert.equal(x.requests.length,1); } finally {await x.close();} }); test('a canvas script can join large JSON read pages without parsing a continuation notice', async t => { const file = 'large.json'; const code = ` const path = ${JSON.stringify(file)}; let page = await tools.read({path}); const parts = []; while (typeof page !== 'string') { parts.push(page.text); page = await tools.read({path, offset: page.nextOffset, limit: 100}); } parts.push(page); text(JSON.parse(parts.join('\\n')).length); `; const x = await setup((_, n) => n === 1 ? sse({tool_calls:[{index:0,id:'read-manifest',type:'function', function:{name:'codemode',arguments:JSON.stringify({code})}}]},'tool_calls') : sse({content:'已读取资料。'},'stop')); t.after(x.close); const source = JSON.stringify(Array.from({length:2250}, (_, i) => i), null, 2); await fs.writeFile(path.join(x.host.workingDirectory, file), source); await x.host.prompt('读取完整资料'); const result = x.host.manager.getBranch().find(({message}) => message?.toolCallId === 'read-manifest')?.message; assert.equal(result?.isError, false, result?.content.map(block => block.text).join('\n')); assert.match(result.content.map(block => block.text).join('\n'), /\b2250\b/u); }); test('read returns clean byte-limited pages and preserves actual file text', async t => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-')); t.after(() => cleanup(dir)); const {cwd,read} = await projectTools({store:{dir}}); const tool = read('main'); const file = 'page.txt'; const readText = async (text, range = {}) => { await fs.writeFile(path.join(cwd,file), text); return tool.execute('read',{path:file,...range}); }; const line = '字'.repeat(10000); const page = await readText(line+'\n'+line); assert.deepEqual(page.structuredContent,{type:'text_page',text:line,nextOffset:2}); assert.match(page.content[0].text,/Use offset=2 to continue/u); const longLine = await readText(line+line); assert.equal(longLine.structuredContent.type,'text_page'); assert.equal(longLine.structuredContent.text,''); assert.equal(longLine.structuredContent.nextOffset,undefined); assert.match(longLine.structuredContent.message,/第 1 行超过单次读取上限/u); const literalNotice = '原文\n\n[1 more lines in file. Use offset=4 to continue.]'; assert.equal((await readText(literalNotice,{limit:3})).structuredContent,literalNotice); }); 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':request===2?'tool_search':'finish_production'; const args=request===1?{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}: request===2?{query:'bash',limit:1}:{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_edit','canvas_template_image','canvas_preview','copywriting_options', 'copywriting_fields','workflow_navigate','workflow_execute','workflow_propose']) { assert.ok(!x.host.session.getActiveToolNames().includes(name),name); } for(const name of ['plan_production','canvas_read','workflow_read','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_copy_fields','review_image_slots','read_slot_images','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','transform_slot_image','finish_production']){ assert.equal(x.host.session.getToolDefinition(name).executionMode,'sequential',name); } assert.equal((await x.host.prompt('完成制作')).production.complete,true); const initialNames=x.requests[0].tools.map(tool=>tool.function.name); assert.ok(initialNames.includes('read')); assert.ok(x.requests[2].tools.some(tool=>tool.function.name==='bash')); for (const name of ['bash','edit','write','find','grep','ls','memory_set','memory_search','context_read']) { assert.ok(!initialNames.includes(name),name); } assert.equal(executed.length,1); const [{clientOperationId,...call}]=executed; assert.match(clientOperationId,/^[a-f\d-]{36}$/iu); assert.deepEqual(call,{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 syncs a single-layer presentation edit to the latest authorized revision before dispatch', async () => { const writes = [], dispatched = [], events = []; let dirty = 0; const host = { productionGoal:{}, productionWork:new Map([[JSON.stringify([undefined,undefined]),{markProgressDirty:()=>dirty++}]]), store:{appendEvent:async event=>events.push(event)}, canvas:{ nativeCatalog:async({id})=>({items:[{id,requiresRevisionLease:true}]}), requestWrite:async revision=>{ writes.push(revision); if(writes.length===1)return {revision:5,rebasedFrom:4,changedLayers:[],retryWrite:true,detailWriteWaiting:true}; if(revision===4)return {revision:6,rebasedFrom:4,changedLayers:[],allowed:true}; return {revision,allowed:true}; }, nativeCall:async args=>{ dispatched.push(args); return {completed:true,executed:true,revision:7}; }, }, }; const [,call]=nativeTools(host,(_name,_description,_schema,execute)=>({execute})); const args={revision:4,method:'engine.execute',params:{command:'layer.setProps',params:{layer:23,opacity:0.8}}}; assert.equal((await call.execute(args)).revision,7); assert.deepEqual(writes,[4,4]); assert.deepEqual(dispatched.map(({clientOperationId,...call})=>{assert.match(clientOperationId,/^[a-f\d-]{36}$/iu);return call;}),[{...args,revision:6}]); assert.equal(args.revision,4); assert.equal(dirty,1); assert.equal(events.at(-1).revision,7); }); test('production native writes stop on revoked permission, stale targets or a native rejection', async () => { const base={revision:4,method:'engine.execute',params:{command:'layer.setProps',params:{layer:23,visible:false}}}; for(const {args=base,reply,error,dispatch=false} of [ {reply:{revision:6,retryWrite:true,detailWriteWaiting:true,writeBlocked:true},error:{category:'write_revoked'}}, {reply:{revision:6,allowed:true,changedLayers:[12]},error:/当前图层已锁定/,dispatch:true}, {args:{...base,params:{command:'layer.setProps',params:{visible:false}}}, reply:{revision:6,retryWrite:true},error:{category:'revision_conflict'}}, {args:{...base,params:{command:'layer.setProps',params:{layers:[23,24],visible:false}}}, reply:{revision:6,retryWrite:true},error:{category:'revision_conflict'}}, {args:{...base,params:{command:'layer.setProps',params:{layer:23,locks:{all:false}}}}, reply:{revision:6,retryWrite:true},error:{category:'revision_conflict'}}, {args:{...base,params:{command:'edit.transform',params:{layer:23,dx:5}}}, reply:{revision:6,retryWrite:true},error:{category:'revision_conflict'}}, {reply:{revision:6,rebasedFrom:4,changedLayers:[23]},error:{category:'revision_conflict',currentRevision:6,changedLayers:[23]}}, {reply:{revision:6,rebasedFrom:4,changedLayers:[],allowed:true},error:/当前图层已锁定/,dispatch:true}, ]) { const writes=[],dispatched=[]; const host={productionGoal:{},store:{},canvas:{ nativeCatalog:async({id})=>({items:[{id,requiresRevisionLease:true}]}), requestWrite:async rev=>{ writes.push(rev); return writes.length===1?reply:{revision:rev,allowed:true}; }, nativeCall:async input=>{ dispatched.push(input); return {completed:true,executed:false,revision:6,error:'当前图层已锁定'}; }, }}; const [,call]=nativeTools(host,(_name,_description,_schema,execute)=>({execute})); await assert.rejects(call.execute(args),error); assert.deepEqual(writes,[4]); assert.deepEqual(dispatched.map(({clientOperationId,...call})=>{ assert.match(clientOperationId,/^[a-f\d-]{36}$/iu); return call; }),dispatch?[{...args,revision:6}]:[]); assert.equal(host.canvasOperations.original,undefined); } }); 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}), imageRequest: async stage => {assert.equal(stage,'pending');return [];}, 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.productionWork.get(JSON.stringify(['detail','walnut']))).active,0); }); test('production loads project prompt templates without discovering project skills', 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:'complete'}; }; const production = new AbortController(); const host = await openAgent({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 interrupted=0; broker.round=()=>({id:randomUUID(),fetch:async()=>{ interrupted++; throw Error('network error: synthetic disconnect'); },finish:async()=>{throw Error('network error: synthetic disconnect');}}); host.streamRetryBaseMs=1; await assert.rejects(host.runDetailAgent('slot-interrupted','Synthetic system','Inspect fixture.',[],[], 'product/review/slot-interrupted'),/对话服务暂时连接不上/u); assert.equal(interrupted,4); 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); }); import { getCurrentSystemPrompt } from '@earendil-works/pi-ai/utils/transcript'; test('conversation after delivery opens another output through the private canvas binding',async t=>{ const detail={outputId:'detail',variantId:'oak'}; const main={outputId:'main_images',variantId:'oak'}; const requestedOutputs=[detail,main]; const template={id:'desk',contentHash:'desk-template'}; const calls=[], visible=[]; const digest='1234567890'.repeat(6)+'1234'; let binding; const canvas=new StdioCanvas(async (action,input)=>{ if(action==='pi-begin'){ binding={...detail,documentKey:{workspaceId:'desk',...detail},writeEpoch:1}; return {run:input.run,conversationActive:true,productionCanvas:binding, context:{requestScope:{...detail,productionTemplate:template,requestedOutputs}}}; } if(action==='pi-production-open'){ assert.deepEqual(input.canvasBinding,{documentKey:binding.documentKey,writeEpoch:1}); assert.deepEqual({outputId:input.outputId,variantId:input.variantId},main); binding={...main,documentKey:{workspaceId:'desk',...main},writeEpoch:2,previousSave:{saved:true}}; calls.push(action); return {productionCanvas:binding,productionSwitch:{accepted:true}}; } if(action==='pi-state')return {conversationActive:true,revision:2}; if(action==='pi-workflow-read'){ assert.equal(input.canvasBinding.writeEpoch,binding.writeEpoch); return {available:true,canvasFirst:true,outputId:binding.outputId,productVariantId:binding.variantId, version:1,template,totalSlots:0,slots:[],productEvidence:{accountScope:x.store.identity.scope, project:x.store.identity.project,documentId:17,brief:{brandId:'qa',categoryId:'desk'}}}; } if(action==='pi-image-request')return []; if(action==='pi-delta'||action==='pi-end')visible.push(input.text); return {}; },17); const x=await setup((payload,round)=>{ const names=payload.tools.map(row=>row.function.name); assert.ok(names.includes('open_production_output')); assert.ok(!names.includes('finish_production')&&!names.includes('defer_production_output')); return round===1?sse({tool_calls:[{index:0,id:'follow-up-open',type:'function', function:{name:'open_production_output',arguments:JSON.stringify(main)}}]},'tool_calls') :sse({content:'已打开主图画布。\n| 复核 | '+digest+' |'},'stop'); }); t.after(x.close); x.host.canvas=canvas; x.host.productIdentity.documentId=17; x.host.manager.appendCustomEntry('production-goal',{goal:{id:'delivered',status:'complete'}}); const reply='已打开主图画布。\n- 复核,制作记录'; assert.equal((await x.host.prompt('主图改成侘寂风')).text,reply); assert.ok(visible.includes(reply)); assert.ok(visible.every(text=>!text||!text.includes('|')&&!text.includes(digest))); assert.deepEqual(calls,['pi-production-open']); assert.deepEqual(canvas.productionOutput,main); assert.equal(canvas.canvasBinding.writeEpoch,2); assert.equal(x.host.productionContext.outputId,main.outputId); }); test('native_reconcile clears a ghost workflow lock and preserves a saved paid original',async()=>{ const make=(name,_description,_schema,execute)=>({name,execute}); const identity={run:'old-run',documentId:23}; const ghost={...identity,kind:'workflow',operationId:'stale',slotId:'ghost',productVariantId:'oak'}; const paid={...identity,kind:'workflow',operationId:'paid',slotId:'hero', outputId:'main_images',productVariantId:'oak',candidateId:'paid-candidate'}; const host={store:{},canvas:{ imageRequest:async action=>{assert.equal(action,'pending');return [];}, workflowReconcile:async input=>{ assert.deepEqual(input,{...identity,operationId:input.operationId}); if(input.operationId==='stale')throw Error('原操作不存在或不属于当前项目'); return {...input,phase:'unknown',operationFound:false}; }, detailRecover:async (slotId,input,scope)=>{ assert.equal(slotId,'hero'); assert.deepEqual(input,{candidateId:'paid-candidate'}); assert.deepEqual(scope,{outputId:'main_images',variantId:'oak'}); return {id:'paid-candidate',status:'unknown',message:'远端仍在核查'}; }, }}; const {execute:reconcile}=nativeTools(host,make).find(tool=>tool.name==='native_reconcile'); await reconcile(); host.canvasOperations.retain(ghost); host.canvasOperations.retain(paid); const {results}=await reconcile(); assert.deepEqual(results.map(row=>row.status),['not_found','unknown']); assert.match(results[0].receipt.message,/可以发起新操作/u); assert.deepEqual(host.canvasOperations.pending,[paid]); });