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

202 lines
12 KiB
JavaScript

import { randomUUID } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { workflowResult } from './workflow-context.mjs';
import { canvasOperations } from './canvas-operations.mjs';
import { BridgeError, stoppedCanvas } 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'];
async function acquireWrite(host, scope, signal, checkTurn, wait, 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(wait && state.detailWriteWaiting){
await onWait?.();
return null;
}
scope.writeRequested=true;
const receipt=await host.canvas.requestWrite(state.revision);
checkTurn();
if(wait && receipt?.retryWrite){
await onWait?.();
return null;
}
if(!receipt?.allowed)throw new BridgeError('用户已接手,本轮写入未获许可','write_revoked');
if(receipt.revision!==state.revision)throw new BridgeError('画布已修改,写入许可已过期,未派发采纳','revision_conflict');
signal?.throwIfAborted();
if(host.canvasNotificationsDetached||scope.writesBlocked)throw Error('原项目已切换或用户已接手,未派发采纳');
return receipt;
}
export async function reconcileWorkflowReceipt(canvas, {run, documentId, operationId, adoption}) {
const receipt=await canvas.workflowReconcile({run, documentId, operationId, ...(adoption?{adoption}:null)});
if(!receipt||receipt.run!==run||receipt.documentId!==documentId||receipt.operationId!==operationId||
!(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 || scope.writesBlocked) throw Error('原项目已切换或原操作需核查,本轮不再派发');
if (scope.original) throw Error('原操作结果未知,先核查原请求;可使用 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();
try {
signal?.throwIfAborted();
const saveDeadline = Date.now() + (timeoutMs ?? LOCAL_OPERATION_WAIT_MS);
const adoption=args.intent==='adopt_candidate';
const requestWrite=async()=>{
if(typeof host.canvas.read!=='function'||typeof host.canvas.requestWrite!=='function')throw Error('画布写入许可不可用,未派发采纳');
while(!await acquireWrite(host,scope,signal,checkTurn,detailBatch,onWriteWaiting)){
signal?.throwIfAborted();
if(Date.now()>=saveDeadline)throw Error('当前编辑尚未落定,已保留候选');
await pause(150,undefined,{signal});
checkTurn();
}
};
if(adoption)await requestWrite();
let observedOriginal=false;
const canReconcile = typeof host.canvas.workflowReconcile === 'function'
&& Number.isSafeInteger(documentId) && typeof run === 'string' && run;
const reconcileOriginal=async()=>{
signal?.throwIfAborted();
checkTurn();
observedOriginal=true;
return reconcileWorkflowReceipt(host.canvas,{run,documentId,operationId});
};
const pollReceipt=async()=>{
if(observedOriginal && canReconcile)return reconcileOriginal();
try { return await host.canvas.workflowPoll(operationId); }
catch(error) {
if(!canvasReplyTimedOut(error)||!canReconcile)throw error;
return reconcileOriginal();
}
};
const submit=async()=>{
try { return await host.canvas.workflowExecute({...args,operationId}); }
catch(error) {
if(!canvasReplyTimedOut(error))throw error;
if(canReconcile)return reconcileOriginal();
if(!detailBatch)throw error;
signal?.throwIfAborted();
checkTurn();
observedOriginal=true;
return pollReceipt();
}
};
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 || state?.writeBlocked || (!detailBatch && state?.revision !== result.revision)) throw new BridgeError('画布已变化或用户已接手,尚未派发操作','write_revoked');
if (!detailBatch && state?.error) throw Error(state.error);
if(detailBatch && adoption)await requestWrite();
dispatched = true;
result = await submit();
}
const notDispatched = result?.phase === 'not_dispatched' && result.accepted === false && result.dispatched === false
&& result.operationId === operationId && typeof run === 'string' && run && result.run === run
&& Number.isSafeInteger(documentId) && documentId > 0 && result.documentId === documentId
&& Number.isSafeInteger(result.baseRevision) && result.baseRevision >= 0
&& ['accountId','origin','project'].every(key => typeof identity[key] === 'string' && identity[key])
&& result.accountId === identity.accountId && result.origin === identity.origin
&& result.projectLocalId === `${identity.origin}|${identity.accountId}|${identity.project}`
&& result.error?.code === 'local_precondition_failed' && typeof result.error.message === 'string' && result.error.message.trim();
if (notDispatched) { dispatched = false; terminal = true; }
checkTurn();
if (notDispatched) {
const message = `本次操作未派发:${workflowResult({message:result.error.message}).message}`;
if(!detailBatch){
scope.writesBlocked = true;
scope.stopReason = message;
}
await host.store.appendEvent({type:'workflow_operation_not_dispatched',run,documentId,operationId,baseRevision:result.baseRevision,
intent:args.intent,slotId:args.slotId,productVariantId:args.productVariantId,code:result.error.code,message});
throw new BridgeError(message,'local_precondition_failed');
}
const phases=observedOriginal?receiptPhases:['submitted'];
if (result?.operationId !== operationId || !phases.includes(result.phase)) throw Error('工作流操作提交状态无效,原操作需核查;不会重发');
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();
checkTurn();
if (result?.operationId !== operationId || !receiptPhases.includes(result.phase)) throw Error('工作流操作回执无效,原操作需核查;不会重发');
}
terminal = ['complete','failed','expired'].includes(result.phase);
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({kind:'workflow',operationId,run,documentId,identity,epoch});
return {operation:{phase:'unknown',operationId,candidateId:result.candidateId}};
}
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({kind:'workflow',operationId,run,documentId,identity,epoch});
if (host.turnEpoch === epoch && (dispatched || signal?.aborted || stoppedCanvas(error))) {
scope.writesBlocked = true;
if (dispatched) scope.stopReason = workflowResult({message:error?.message || '原操作未完成,请核查原请求;不会重发'}).message;
}
throw error;
} finally { if (scope.active===owner) scope.active=null; }
}