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

113 lines
8.4 KiB
JavaScript

import { randomUUID } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { workflowResult } from './workflow-context.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;
const LOCAL_OPERATION_WAIT_MS = 120_000;
// 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 } = {}) {
if (host.canvasNotificationsDetached || host.canvasWritesStopped) throw Error('原项目已切换或原操作需核查,本轮不再派发');
if (host.nativeUnresolved) throw Error('原操作结果未知,先核查原请求;可使用 native_reconcile 只读核查,不会重发');
if (host.nativeToolActive) 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};
host.nativeToolOwner = owner;
host.nativeToolActive = true;
let dispatched = false, terminal = false;
const checkTurn = () => { if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧工作流操作不会继续或重发'); };
const operationId = randomUUID();
try {
signal?.throwIfAborted();
if (args.intent === 'adopt_candidate') {
if (typeof host.canvas.read !== 'function' || typeof host.canvas.requestWrite !== 'function') throw Error('画布写入许可不可用,未派发采纳');
const state = await host.canvas.read();
checkTurn();
if (state?.conversationActive === false || state?.writeBlocked || !Number.isSafeInteger(state?.revision) || state.revision < 0) throw Error('画布已变化或用户已接手,未派发采纳');
host.canvasWriteRequested = true;
const permission = await host.canvas.requestWrite(state.revision);
checkTurn();
if (!permission?.allowed) throw Error('用户已接手,本轮写入未获许可');
if (permission.revision !== state.revision) throw Error('画布已修改,写入许可已过期,未派发采纳');
signal?.throwIfAborted();
if (host.canvasNotificationsDetached || host.canvasWritesStopped) throw Error('原项目已切换或用户已接手,未派发采纳');
}
dispatched = true;
const saveDeadline = Date.now() + (timeoutMs ?? LOCAL_OPERATION_WAIT_MS);
let result = await host.canvas.workflowExecute({ ...args, operationId });
while (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 || state?.revision !== result.revision) throw Error('画布已变化或用户已接手,尚未派发操作');
if (state?.error) throw Error(state.error);
dispatched = true;
result = await host.canvas.workflowExecute({ ...args, operationId });
}
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}`;
host.canvasWritesStopped = true;
host.workflowStopReason = 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 Error(message);
}
if (result?.operationId !== operationId || result.phase !== 'submitted') throw Error('工作流操作提交状态无效,原操作需核查;不会重发');
await host.store.appendEvent({ type:'workflow_operation_submitted', run:host.canvas.run, operationId, intent:args.intent, slotId:args.slotId, productVariantId:args.productVariantId });
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 host.canvas.workflowPoll(operationId);
checkTurn();
if (result?.operationId !== operationId || !['submitted','complete','failed','unknown'].includes(result.phase)) throw Error('工作流操作回执无效,原操作需核查;不会重发');
}
terminal = result.phase === 'complete' || result.phase === 'failed';
if (keepFailedCandidate && args.intent === 'generate_candidate' && result.phase === 'failed'
&& 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:'failed',message}};
}
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) host.generatedCandidates?.set(candidateId, false);
if (args.intent === 'adopt_candidate' && host.generatedCandidates?.has(candidateId)) host.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 } : {}) });
let current;
try { current = await host.readWorkflow({ section:'slots', outputId:args.outputId }); }
catch { throw Error('原工作流操作已完成,但刷新状态失败;请核查,禁止重发'); }
return { operation, workflow: current };
} catch (error) {
if (dispatched && !terminal) host.nativeUnresolved = { kind:'workflow', operationId, run, documentId, identity, epoch };
if (host.turnEpoch === epoch && (dispatched || signal?.aborted || /接手|画布已修改|未获许可|项目已切换|结果未知|尚未确认|不会重发|连接中断|已取消/.test(error?.message || ''))) {
host.canvasWritesStopped = true;
if (dispatched) host.workflowStopReason = workflowResult({message:error?.message || '原操作未完成,请核查原请求;不会重发'}).message;
}
throw error;
} finally { if (host.nativeToolOwner === owner) { host.nativeToolActive = false; host.nativeToolOwner = null; } }
}