import type { ToolCallContext } from '../types.js'; import { agentNeedsResolution, readAgentLedgerStrict, type AgentTaskRecord, } from '../tools/agent/agentTaskService.js'; /** Structural copy exposed on the turn_done event and the CLI JSON contract. */ export interface PendingRequiredTask { agent_id: string; attempt_id: string; state: AgentTaskRecord['status']; resolution?: string; description?: string; } export type DeliveryGate = | { kind: 'ready'; version: string } | { kind: 'pending'; version: string; tasks: AgentTaskRecord[] } | { kind: 'unknown'; reason: string }; /** Records inherit the delivery they were created under; legacy rows fall back to their request id. */ export function belongsToDelivery(record: AgentTaskRecord, deliveryId: string): boolean { return (record.deliveryId ?? record.parentMessageId) === deliveryId; } /** * The single permission check before publishing a final answer or a formal result. * * `pending` means required responsibility for this delivery is still open * (running, completed-but-unaccepted, blocked, failed, taken over but not * completed, or waived as an explicit gap). `unknown` means the ledger could * not be read reliably; a final answer must not be published on an assumption * that it was empty. * * The turn loop is the Session's serialization point: this is evaluated after * the model response settles and immediately before publishing, with no tool * execution in between. Version is exposed for diagnostics; cross-process * concurrent writers are not covered by a transaction here. */ export async function evaluateDeliveryGate( ctx: ToolCallContext, deliveryId: string, ): Promise { const snapshot = await readAgentLedgerStrict(ctx); if (snapshot.kind === 'unknown') return { kind: 'unknown', reason: snapshot.reason }; const tasks = snapshot.records.filter( (record) => belongsToDelivery(record, deliveryId) && agentNeedsResolution(record, snapshot.records), ); return tasks.length ? { kind: 'pending', version: snapshot.version, tasks } : { kind: 'ready', version: snapshot.version }; } export function pendingRequiredSummary(tasks: readonly AgentTaskRecord[]): PendingRequiredTask[] { return tasks.map((task) => ({ agent_id: task.id, attempt_id: task.attemptId ?? String(task.createdAt), state: task.status, ...(task.resolution?.action ? { resolution: task.resolution.action } : {}), ...(task.description ? { description: task.description } : {}), })); } /** * 逐个说明未收口任务「现在是什么状态、下一步该做什么」。 * 曾经只列 `id(status/action)`:用户看到的是笼统的「未收口」,分不清是还在跑、 * 做完了没验收、接管了没登记完成,还是被拒的验收证据(真实事故:测试已通过, * 但账本没收口,最终回答被替换后用户不知道缺哪一步)。 */ function describePendingTask(task: AgentTaskRecord): string { const action = task.resolution?.action; let next: string; if (action === 'takeover') next = '已接管、尚未登记完成:主 Agent 做完并核验后 AgentResolve complete(写任务附 writeReview)'; else if (task.status === 'running') next = '仍在运行:等待完成或 AgentWait'; else if (task.status === 'completed') next = '已完成、待验收:集成并核验后 AgentResolve accept(写任务附 writeReview,证据用检查类工具的调用 ID)'; else next = `状态 ${task.status}:续接、接管,或 waive 并说明缺口`; return `${task.id}(${next})`; } function describePendingTasks(tasks: readonly AgentTaskRecord[]): string { return tasks.map(describePendingTask).join(';'); } /** * Status text shown before the candidate body when the gate is closed. It says * what is still open and how to recover; it never claims the work is done. * * `candidateVisible` = the model's own text is still on screen (it streamed * live). When the runtime replaced the candidate with its status body there is * nothing "below" to qualify, so that sentence is left out. */ export function incompleteDeliveryWarning(gate: DeliveryGate, candidateVisible = true): string { const qualifier = candidateVisible ? '以下内容只是阶段性进展,不能视为最终结果;' : ''; if (gate.kind === 'pending') return `任务尚未全部完成:必要子任务未收口 ${gate.tasks.length} 个 —— ${describePendingTasks(gate.tasks)}。${qualifier}可等待运行、读取交接后接管,或明确报告缺口。`; if (gate.kind === 'unknown') return `无法确认子任务账本状态(${gate.reason}),因此本轮不能声称全部完成。${qualifier}请先恢复账本可读性。`; return ''; } /** * Body published in place of an unreleased candidate when the gate is closed. * It is generated by the runtime from the real ledger, so a model-written * "all done" report is never the thing the user sees as the answer. */ export function incompleteDeliveryBody(gate: DeliveryGate): string { if (gate.kind === 'pending') return `本轮未发布最终结论:还有 ${gate.tasks.length} 个必要子任务未收口 —— ${describePendingTasks(gate.tasks)}。完成核验、接管后完成或明确报告缺口,才能给出最终结果。`; if (gate.kind === 'unknown') return `本轮未发布最终结论:无法确认子任务账本状态(${gate.reason})。请先恢复账本可读性,不能假定工作已完成。`; return ''; } export function missingFormalDeliveryWarning(candidateVisible = true): string { return `交付尚未完成:用户明确要求提供可打开的文件成果,但本轮没有成功提交。${candidateVisible ? '以下内容只是过程说明,不是最终成果;' : ''}请提交成果或如实说明缺口。`; } /** * The request itself must open with a continuation cue. A word that merely * appears inside it ("continue;" in pasted code, "继续教育", a file called * resume.pdf) is not a request to resume an open goal. */ const CONTINUATION_CUE = /^\s*(?:(?:请|麻烦|帮我|我们|咱们|那就|那|好的?|可以|ok|please|let'?s|can you|could you)\s*[,,]?\s*){0,3}(?:继续(?!教育|教学)|接着|续上|(?:continue|resume)(?![\w.;(-])|carry on)/i; /** "不要继续旧审查" is not a continuation request. */ const NEGATED_CONTINUATION = /(?:不要|别|不用|无需|不必|停止|取消|不再)\s*(?:再|去|往下)?\s*(?:继续|接着|续上|接着做)|(?:don'?t|do not|no need to|stop)\s+(?:continue|resume|carry on)/i; export type DeliveryBindingSource = | 'host' | 'new' | 'inherited' | 'ambiguous' | 'unreadable'; export interface DeliveryBinding { deliveryId: string; source: DeliveryBindingSource; /** Distinct open delivery targets seen in the ledger (diagnostics / asking the user). */ candidates?: string[]; reason?: string; } /** * Bind a new user turn to an existing delivery target. * * Explicit beats inference: a host-provided target id always wins. A * continuation cue inherits only when the ledger has exactly one open target; * with several open targets the turn does not silently pick the most recently * updated one. An unreadable ledger is reported as such instead of degrading * into "no open work". */ export async function resolveDeliveryId( input: string, ctx: ToolCallContext, fallback: string, hostDeliveryId?: string, ): Promise { if (hostDeliveryId) return { deliveryId: hostDeliveryId, source: 'host' }; if (!CONTINUATION_CUE.test(input) || NEGATED_CONTINUATION.test(input)) return { deliveryId: fallback, source: 'new' }; const snapshot = await readAgentLedgerStrict(ctx); if (snapshot.kind === 'unknown') return { deliveryId: fallback, source: 'unreadable', reason: snapshot.reason }; const open = snapshot.records.filter((record) => agentNeedsResolution(record, snapshot.records), ); const targets = [ ...new Set( open .map((record) => record.deliveryId ?? record.parentMessageId) .filter((value): value is string => Boolean(value)), ), ]; if (targets.length === 0) return { deliveryId: fallback, source: 'new' }; if (targets.length > 1) return { deliveryId: fallback, source: 'ambiguous', candidates: targets }; return { deliveryId: targets[0]!, source: 'inherited' }; } /** Transient guidance when a continuation could not be bound deterministically. */ export function deliveryBindingNote(binding: DeliveryBinding): string { if (binding.source === 'ambiguous') return `[交付目标未绑定] 用户说要继续,但当前有 ${binding.candidates?.length ?? 0} 个未收口目标(${binding.candidates?.join('、') ?? ''})。不要擅自选择最近更新的一项;先问清用户指的是哪一个,或明确本轮是新问题。`; if (binding.source === 'unreadable') return `[交付目标未绑定] 用户要求继续,但子任务账本不可读(${binding.reason ?? '未知原因'})。不能假定旧目标已完成,也不能默默新建目标宣称完成;先恢复账本或在回答中说明无法确认状态。`; return ''; }