合入小壹模型请求结果未知时按原生重试续上(R5-T)

This commit is contained in:
WuYongJie 2026-11-28 18:47:26 +08:00
commit ec374e3c11
2 changed files with 91 additions and 8 deletions

View File

@ -32,6 +32,32 @@ import { NativeExtensionUI } from './native-ui.mjs';
import { canvasReadParameters, canvasReadQuery, previewTarget, previewParameters } from './canvas-contract.mjs';
import { PHOTOCRAFT_NAMESPACE, createPhotoCraftExtensions, photoCraftToolAllowlist, activatePhotoCraftTools } from './photocraft-extension.mjs';
// 98k sends a single data line for terminal errors after the HTTP status is committed.
// Observe the structured code before the provider parser drops it from errorMessage.
function observeUnknownOutcome(response, onUnknownOutcome) {
if (!response.headers.get('content-type')?.startsWith('text/event-stream') || !response.body) return response;
const code = 'request_outcome_unknown';
const decoder = new TextDecoder();
let pending = '';
const body = response.body.pipeThrough(new TransformStream({
transform(chunk, controller) {
const lines = (pending + decoder.decode(chunk, {stream:true})).split('\n');
pending = lines.pop();
for (const line of lines) {
if (!line.startsWith('data: ') || !line.includes(`"${code}"`)) continue;
let payload;
try { payload = JSON.parse(line.slice(6)); } catch { continue; }
const error = payload?.error;
if (error?.code === code || (payload?.type === 'error' && error?.type === code)) {
onUnknownOutcome(`503 ${code}: ${error.message}`);
}
}
controller.enqueue(chunk);
},
}));
return new Response(body, {status:response.status,statusText:response.statusText,headers:response.headers});
}
const PRODUCT_VOICE = "对用户回复、状态汇报和错误说明始终使用「小壹」「画布」「工作台」「制作助手」等产品术语。不得向用户暴露底层技术或开源底座名称;工具及参考资料中的内部名称仅用于执行。";
const SYSTEM = `你是由壹点详情页的本地协作助手“小壹”。使用中文,能够与用户连贯讨论、回答问题、解释原因、提出并比较方案。可以直接自然语言回答;不需要工具时不要调用工具,不把每次对话都当作执行任务。
@ -383,7 +409,7 @@ export class DetailPiAgent {
const retry = {enabled:true,maxRetries:3};
// The main agent carries the run, so its waits of 3–60 s ride out a gateway outage of about
// 2.5 minutes (R5 run 8 lost a whole run to a 502 burst longer than the default 14 s window).
// Gateway errors are not billed and the count is bounded. Workers fail fast and are re-delegated.
// Workers use a shorter retry window so failed work can be re-delegated.
const mainRetry = {enabled:true,maxRetries:6,baseDelayMs:3000};
const workers = new Map();
// Worker sessions are in memory, so the event log is the only place a failed tool's reason survives.
@ -438,6 +464,7 @@ export class DetailPiAgent {
round = (worker ? worker.broker : host.goalBroker ?? broker).round();
const requiredTool = !worker && !host.compacting ? host.requiredTool : null;
let requestBytes, promptCacheKeyPresent, sentAt, headersAt, firstTextAt;
let unknownOutcomeError;
const stream = apiImpl.streamSimple(model, wireContext, { ...options,
...(worker ? {sessionId:worker.cacheKey} : null),maxRetries:0,
apiKey: 'native-broker-only', fetch: async (...args) => {
@ -447,7 +474,7 @@ export class DetailPiAgent {
host.productionSignal?.throwIfAborted();
const response=await round.fetch(...args);
headersAt=Date.now();
return response;
return observeUnknownOutcome(response, message => { unknownOutcomeError = message; });
},
onPayload: async payload => {
applyOutputContract(payload);
@ -494,6 +521,7 @@ export class DetailPiAgent {
...(options.signal?.aborted||host.productionSignal?.aborted?{consumption:'discarded_after_cancel'}:{})});
if (broker?.authority?.error) throw broker.authority.error;
if (['error','aborted'].includes(stopReason)) {
if (stopReason==='error' && unknownOutcomeError) result.errorMessage=unknownOutcomeError;
result.errorMessage=redactText(result.errorMessage??'');
output.push(finalEvent);
output.end(result);

View File

@ -16,7 +16,7 @@ import { cleanup } from './cleanup.mjs';
import { decodeToolReply } from '../src/json-tool-codec.mjs';
import { normalizeContext } from '@earendil-works/pi-ai/compat';
import { createAssistantMessageEventStream, openAICompletionsApi, openAIResponsesApi } from '@earendil-works/pi-ai/compat';
import { SessionManager } from '@earendil-works/pi-coding-agent';
import { SessionManager, SettingsManager } 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';
@ -284,6 +284,11 @@ test('a retained Responses function call is audited and decoded without a networ
});
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 outcomeUnknownError = `503 request_outcome_unknown: ${outcomeUnknownMessage}`;
const gatewayErrorFrame = (code = 'request_outcome_unknown') => 'data: '+JSON.stringify({error:{
code,message:outcomeUnknownMessage,type:'server_error',
}})+'\n\n';
async function setup(reply, finish = async valid => { assert.equal(valid, true); return {phase:'complete'}; }, production, recovery = production) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-'));
const scope = 'f'.repeat(64), store = await ProjectStore.open(dir, { scope, project: randomUUID() }, { brandId: 'qa', shopId: 'A', categoryId: 'desk', platform: 'qa', version: '1', source: 'qa', rules: [] });
@ -405,7 +410,7 @@ test('ordinary chat resumes the same turn through Pi after a rate limit', async
} finally { await x.close(); }
});
test('an HTTP 503 native inference receipt reaches Pi retry in the same one-click goal', async t => {
for (const committed of [false,true]) test(`${committed?'A committed Responses error':'An HTTP 503 native inference receipt'} reaches Pi retry in the same one-click goal`, async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-'));
let host;
t.after(async()=>{ await host?.dispose(); await cleanup(dir); });
@ -430,10 +435,17 @@ test('an HTTP 503 native inference receipt reaches Pi retry in the same one-clic
assert.equal(method,'request');
requests.push(input);
const success=requests.length>1;
emit({type:'headers',status:success?200:503,requestId:success?randomUUID():originalId,
headers:{'content-type':success?'text/event-stream':'application/json'},bodyHash:'native-wire'});
const error=JSON.stringify({error:{code:'service_unavailable',type:'server_error',message:'Service temporarily unavailable'}});
emit({type:'chunk',data:Buffer.from(success?response:error).toString('base64')});
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'}:{phase:'unknown',requestId:originalId};
};
const canvas={begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){},activity:async()=>{},delta:async()=>{},end:async()=>{},finishProduction:async input=>productionExportReceipt(input)};
@ -441,6 +453,10 @@ test('an HTTP 503 native inference receipt reaches Pi retry in the same one-clic
const productionGoal={outputId:'detail',variantId,workspaceId:randomUUID(),requestedOutputs:[{outputId:'detail',variantId}],
deadline:Math.floor(Date.now()/1000)+90};
host=await DetailPiAgent.open({store,broker,canvas,productionGoal,callBudget:4});
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}};
@ -450,10 +466,49 @@ test('an HTTP 503 native inference receipt reaches Pi retry in the same one-clic
assert.deepEqual(operations,[{revision:7,scope:"all"}]);
assert.equal(resumed.production.finalized,true);
assert.deepEqual(finished,[]);
assert.equal(retries.length,1);
if(committed)assert.equal(retries[0].errorMessage,outcomeUnknownError);
const journal=await fs.readFile(path.join(store.dir,'events.jsonl'),'utf8');
assert.ok(journal.split('\n').filter(Boolean).map(line=>JSON.parse(line))
.some(row=>row.type==='pi_retry'&&row.attempt===1&&row.maxAttempts===6));
assert.notEqual(requests[0].id,requests[1].id);
assert.equal(requests[0].body,requests[1].body);
});
test('a committed Anthropic error preserves the gateway code and status for Pi', async t => {
const frame='event: error\ndata: '+JSON.stringify({type:'error',error:{
type:'request_outcome_unknown',message:outcomeUnknownMessage,
}})+'\n\n';
const x=await setup(()=>frame,undefined,undefined,{model:{id:'qa',protocol:'anthropic-messages'}});
t.after(x.close);
const settings=x.host.session.settingsManager, retry=settings.getRetrySettings();
settings.getRetrySettings=()=>({...retry,baseDelayMs:1,maxDelayMs:1});
x.host.callBudget=10;
await assert.rejects(x.host.prompt('核对制作进度'),{message:outcomeUnknownError});
assert.equal(x.requests.length,7);
});
test('a committed unknown outcome follows the main and worker retry limits by code', async t => {
const getRetrySettings=SettingsManager.prototype.getRetrySettings;
t.mock.method(SettingsManager.prototype,'getRetrySettings',function(){
return {...getRetrySettings.call(this),baseDelayMs:1,maxDelayMs:1};
});
let code='request_outcome_unknown';
const x=await setup(()=>': keep-alive\n\n'+gatewayErrorFrame(code),undefined,undefined,{
model:{id:'qa',protocol:'openai-responses'},
});
t.after(x.close);
x.host.callBudget=12;
await assert.rejects(x.host.prompt('核对制作进度'),{message:outcomeUnknownError});
assert.equal(x.requests.length,7);
await assert.rejects(x.host.runDetailAgent('slot-a','核对资料。','核对当前图位。',[],[]),{message:outcomeUnknownError});
assert.equal(x.requests.length,11);
assert.equal(new Set(x.ids).size,11);
code='other_error';
await assert.rejects(x.host.prompt('再次核对制作进度'),{message:outcomeUnknownMessage});
assert.equal(x.requests.length,12);
});
test('the one-click goal resumes on changed fields at the same count without naming the next tool',async()=>{
const plan=n=>sse({tool_calls:[{index:0,id:'plan-'+n,type:'function',function:{name:'plan_production',arguments:'{}'}}]},'tool_calls');
let plans=0;