gongxiangp2/apps/detail-agent-pi/src/workflow-execute.mjs

219 lines
13 KiB
JavaScript

import { randomUUID } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { workflowResult } from './workflow-context.mjs';
import { canvasOperations, missingCanvasOperation } from './canvas-operations.mjs';
import { BridgeError } from './bridge-error.mjs';
import { canvasReplyTimedOut } from './stdio-canvas.mjs';
// The native image worker can wait 10 minutes for the POST and 3 more for
// read-only recovery. Leave one minute for local preparation and final receipts.
const IMAGE_OPERATION_WAIT_MS = 14 * 60_000;
export const LOCAL_OPERATION_WAIT_MS = 120_000;
const receiptPhases = ['submitted','complete','failed','unknown','expired','candidate_limit_reached'];
async function acquireWrite(host, scope, signal, checkTurn, onWait) {
const state=await host.canvas.read();
checkTurn();
if(state?.conversationActive===false||state?.writeBlocked||!Number.isSafeInteger(state?.revision)||state.revision<0) {
throw new BridgeError('画布已变化或用户已停止,未派发采纳',state?.conversationActive===false?'scope_changed':'write_revoked');
}
if(state.detailWriteWaiting){
await onWait?.();
return null;
}
scope.writeRequested=true;
const receipt=await host.canvas.requestWrite(state.revision);
checkTurn();
if(receipt.writeBlocked)throw new BridgeError('本轮写入许可已撤销,未派发采纳',receipt.writeBlockReason ?? 'write_revoked');
if(receipt.retryWrite || receipt.writeBlockReason === 'waiting_save'){
await onWait?.();
return null;
}
if(receipt.writeBlockReason === 'revision_conflict') {
throw new BridgeError('准备期间画布有改动,本次未采纳,请确认图位后继续。','revision_conflict',
{retryable:true,currentRevision:receipt.revision,changedLayers:receipt.changedLayers});
}
if(!receipt.allowed)throw new BridgeError('本次写入未获许可,未派发采纳','write_revoked');
signal?.throwIfAborted();
if(host.canvasNotificationsDetached)throw Error('原项目已切换,未派发采纳');
return receipt;
}
export async function reconcileWorkflowReceipt(canvas, {run, documentId, operationId, adoption}) {
const identity={run,documentId,operationId};
const missing={...identity,phase:'not_found',message:'宿主确认原操作不存在'};
let receipt;
try { receipt=await canvas.workflowReconcile({...identity,...(adoption?{adoption}:null)}); }
catch(error) {
if(missingCanvasOperation(error))return missing;
throw error;
}
if(!receipt||Object.entries(identity).some(([key,value])=>receipt[key]!==value)){
throw Error('原画布操作的核查回执与提交身份不一致');
}
if(missingCanvasOperation(receipt))return missing;
if(!(receiptPhases.includes(receipt.phase)||adoption&&receipt.phase==='not_executed')){
throw Error('原画布操作的核查状态无效');
}
return receipt;
}
// One new operation, then only read its status. No transport or model retry.
export async function executeWorkflow(host, args, signal, { timeoutMs, pause = delay, keepFailedCandidate = false, detailBatch = false, onWriteWaiting, onAdoptionPrepared, onPrepared, onSubmitted,
scope=canvasOperations(host), generatedCandidates=host.generatedCandidates, readWorkflow=args=>host.readWorkflow(args) } = {}) {
if (host.canvasNotificationsDetached) throw Error('原项目已切换,本轮不再派发');
const held = scope.pending.find(op => op.kind === 'workflow' && op.slotId === args.slotId && op.productVariantId === args.productVariantId &&
(op.outputId===undefined||op.outputId===args.outputId));
if (held) throw Error(`图位 ${args.slotId} 的原请求 ${held.operationId} 结果未知,先用 native_reconcile 按原号核查;核查到完成、失败或过期后,才能为这个图位另发新请求。其他图位不受影响`);
if (scope.active) throw Error('已有原生操作正在执行,请依次等待');
const epoch = host.turnEpoch, run = host.canvas.run, documentId = host.canvas.documentId, owner = Symbol('workflow operation');
const identity = {scope:host.store.identity?.scope, project:host.store.identity?.project, accountId:host.canvas.identity?.accountId, origin:host.canvas.identity?.origin};
scope.active=owner;
let dispatched = false, terminal = false;
const checkTurn = () => { if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧工作流操作不会继续或重发'); };
const operationId = randomUUID();
const {slotId,productVariantId,outputId,intent}=args;
const original={kind:'workflow',operationId,run,documentId,identity,epoch,slotId,productVariantId,outputId,intent,
...(intent==='generate_candidate'&&!args.useProductReference?{candidateId:operationId}:null)};
const rejectUndispatched=async result=>{
if(result?.operationId!==operationId||!(result.phase==='not_dispatched'||result.dispatched===false))return;
dispatched=false;
terminal=true;
checkTurn();
const failure=result.error??result.failure;
const reason=failure?.reason??failure?.code??failure?.category??result.writeBlockReason??'not_dispatched';
const message=`本次操作未派发:${workflowResult({message:failure?.message??result.message??reason}).message}`;
await host.store.appendEvent({type:'workflow_operation_not_dispatched',run,documentId,operationId,baseRevision:result.baseRevision,
intent,slotId,productVariantId,code:failure?.code??reason,reason,message});
throw new BridgeError(message,reason,{retryable:reason==='revision_conflict',currentRevision:result.revision,
changedLayers:result.changedLayers});
};
try {
signal?.throwIfAborted();
const saveDeadline = Date.now() + (timeoutMs ?? LOCAL_OPERATION_WAIT_MS);
const adoption=args.intent==='adopt_candidate';
const requestWrite=async()=>{
while(!await acquireWrite(host,scope,signal,checkTurn,onWriteWaiting)){
signal?.throwIfAborted();
if(Date.now()>=saveDeadline)throw new BridgeError('画布仍在保存,已保留候选','waiting_save',{retryable:true});
await pause(150,undefined,{signal});
checkTurn();
}
};
if(adoption)await requestWrite();
let observedOriginal=false;
const reconcileOriginal=async()=>{
signal?.throwIfAborted();
checkTurn();
observedOriginal=true;
return reconcileWorkflowReceipt(host.canvas,{run,documentId,operationId});
};
const pollReceipt=async()=>{
if(observedOriginal)return reconcileOriginal();
try { return await host.canvas.workflowPoll(operationId); }
catch(error) {
if(!canvasReplyTimedOut(error))throw error;
return reconcileOriginal();
}
};
const submit=async()=>{
try { return await host.canvas.workflowExecute({...args,operationId}); }
catch(error) {
if(canvasReplyTimedOut(error))return reconcileOriginal();
if(error?.dispatched===false)dispatched=false;
throw error;
}
};
if(adoption&&onAdoptionPrepared){
await onAdoptionPrepared({run,documentId,operationId});
signal?.throwIfAborted();
checkTurn();
}
if(onPrepared){
await onPrepared({run,documentId,operationId});
signal?.throwIfAborted();
checkTurn();
}
dispatched = true;
let result=await submit();
while (!observedOriginal && result?.operationId === operationId && result.phase === 'waiting_save' && result.dispatched === false) {
dispatched = false;
checkTurn();
signal?.throwIfAborted();
if (Date.now() >= saveDeadline) throw Error('项目仍在保存,本次尚未开始处理');
await pause(100, undefined, { signal });
checkTurn();
signal?.throwIfAborted();
const state = await host.canvas.read();
checkTurn();
if (state?.conversationActive === false) throw new BridgeError('当前画布已切换,尚未派发操作','scope_changed');
if (state?.writeBlocked) throw new BridgeError('本轮写入许可已撤销,尚未派发操作','write_revoked');
if (!detailBatch && state?.error) throw Error(state.error);
if (!detailBatch && Number.isSafeInteger(result.revision) && state?.revision!==result.revision) {
throw new BridgeError('等待保存期间画布已变化,本次未派发','revision_conflict',{currentRevision:state?.revision});
}
if(adoption)await requestWrite();
dispatched = true;
result = await submit();
}
await rejectUndispatched(result);
checkTurn();
const phases=observedOriginal?receiptPhases:['submitted'];
if (result?.operationId !== operationId || !phases.includes(result.phase)) throw Error('工作流操作提交状态无效,原操作需核查;不会重发');
if(original.candidateId&&result.candidateId)original.candidateId=result.candidateId;
await onSubmitted?.(result);
if (result.phase !== 'unknown') {
await host.store.appendEvent({ type:'workflow_operation_submitted', run, operationId, intent:args.intent,
slotId:args.slotId, productVariantId:args.productVariantId, ...(observedOriginal ? { acknowledgment:'reconciled' } : {}) });
}
const deadline = Date.now() + (timeoutMs ?? (args.intent === 'generate_candidate' ? IMAGE_OPERATION_WAIT_MS : LOCAL_OPERATION_WAIT_MS));
while (result.phase === 'submitted' && Date.now() < deadline) {
signal?.throwIfAborted();
await pause(args.intent === 'generate_candidate' ? 500 : 200, undefined, { signal });
result = await pollReceipt();
await rejectUndispatched(result);
checkTurn();
if (result?.operationId !== operationId || !receiptPhases.includes(result.phase)) throw Error('工作流操作回执无效,原操作需核查;不会重发');
}
if(original.candidateId&&result.candidateId)original.candidateId=result.candidateId;
terminal = ['complete','failed','expired','candidate_limit_reached'].includes(result.phase);
if (result.phase === 'candidate_limit_reached') {
const {phase,reason,limitReached,candidateCount,candidatesRemaining,maxCandidatesPerSlot}=result;
return {operation:{phase,reason,limitReached,candidateCount,candidatesRemaining,maxCandidatesPerSlot}};
}
if (keepFailedCandidate && args.intent === 'generate_candidate' && ['failed','expired'].includes(result.phase)
&& typeof result.candidateId === 'string' && result.candidateId) {
const message = workflowResult(result).message || '这次生图已失败,请查看图位记录';
await host.store.appendEvent({type:'whole_detail_generation_failed',slotId:args.slotId,operationId,candidateId:result.candidateId,message});
return {operation:{candidateId:result.candidateId,phase:result.phase,message,
...(result.phase==='expired'?{requestId:result.requestId,retryable:false,resultExpiry:result.resultExpiry}:null),
...(result.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:result.retryAfterSeconds}:{})}};
}
if (detailBatch && args.intent==='generate_candidate' && !terminal) {
scope.retain(original);
return {operation:{phase:'unknown',operationId,candidateId:result.candidateId}};
}
if (result.phase === 'failed' && result.writeBlockReason) {
throw new BridgeError(workflowResult(result).message,result.writeBlockReason,{dispatched:true});
}
if (result.phase !== 'complete') throw Error(workflowResult(result).message || (result.phase === 'failed' ? '原工作流操作失败,请核查结果;不会重发' : '原工作流操作结果未知,请核查原请求;不会重发'));
const operation = workflowResult({
...result, intent: args.intent, outputId: args.outputId, slotId: args.slotId, productVariantId: args.productVariantId,
});
const candidateId = typeof result.candidateId === 'string' && result.candidateId.trim() ? result.candidateId : null;
const generated = args.intent === 'generate_candidate' && candidateId !== null;
if (generated) generatedCandidates?.set(candidateId, false);
if (args.intent === 'adopt_candidate' && generatedCandidates?.has(candidateId)) generatedCandidates.set(candidateId, true);
await host.store.appendEvent({ type:'workflow_operation_completed', run, operationId, intent:args.intent, slotId:args.slotId,
productVariantId:args.productVariantId, ...(generated ? { candidateId:result.candidateId } : {}) });
if(detailBatch)return {operation};
let current;
try { current = await readWorkflow({ section:'slots', outputId:args.outputId }); }
catch { throw Error('原工作流操作已完成,但刷新状态失败;请核查,禁止重发'); }
return { operation, workflow: current };
} catch (error) {
if (dispatched && !terminal) scope.retain(original);
throw error;
} finally { if (scope.active===owner) scope.active=null; }
}