import { createHash } from 'node:crypto'; import { isUsageLimitError } from '../llm/gatewayClient.js'; import type { AgentRuntimeContext, LoopEvent } from '../plugin-sdk.js'; import { GoalRuntime, GoalRuntimeError, type Goal, type GoalContractInput, type GoalExecutionContext, type GoalScope, type GoalSource, } from './index.js'; import { OUTCOME_TO_ATTEMPT, type WorkflowOutcome } from './statusMapping.js'; import type { ManagedExecutionBridge, ManagedExecutionContext, PreparedManagedCommand, } from '../managedExecution/types.js'; export interface GoalCommandOptions { cwd: string; runtimeContext?: AgentRuntimeContext; actorId?: string; acceptorHumanIds?: string[]; source?: GoalSource; runtime?: GoalRuntime; provenance?: import('../types.js').ConversationProvenance; } function scopeFor(options: GoalCommandOptions): GoalScope { const workspaceId = options.runtimeContext?.workspaceId ?? `path-${createHash('sha256').update(options.cwd).digest('hex').slice(0, 20)}`; return { workspaceId, sessionId: options.runtimeContext?.sessionId?.trim() || 'default', }; } function criteriaFrom(inputs: Record): string[] { if (Array.isArray(inputs.acceptanceCriteria)) { const values = inputs.acceptanceCriteria; if (!values.length || values.some((value) => typeof value !== 'string' || !value.trim())) { throw new Error('验收标准必须是非空字符串数组'); } return values; } const checks = String(inputs.checks ?? '') .split(',') .map((item) => item.trim()) .filter(Boolean); return checks.length > 0 ? checks : ['按照确认的目标与交付物完成,并提供可检查的验证证据']; } function render(goal: Goal, runtime: GoalRuntime): string { const contract = runtime.currentContract(goal); const latest = goal.attempts.at(-1); const lines = [ `Goal ${goal.goalId}`, `状态:${goal.status}`, `目标:${contract.objective}`, `契约:v${contract.version} (${contract.hash.slice(0, 12)})`, `执行:${goal.attempts.length} 次${latest ? `,最近 ${latest.status}` : ''}`, ]; if (goal.statusReason) lines.push(`原因:${goal.statusReason}`); if (goal.status === 'ready_for_acceptance') { lines.push('成果已通过 Agent 自检,等待指定人类验收;Agent 不会自行标记完成。'); } return `${lines.join('\n')}\n`; } function handled(goal: Goal, runtime: GoalRuntime, prefix?: string): PreparedManagedCommand { return { handled: true, inputs: {}, events: [ { type: 'text', delta: `${prefix ? `${prefix}\n` : ''}${render(goal, runtime)}` }, { type: 'turn_done' }, ], }; } function error(message: string): PreparedManagedCommand { return { handled: true, inputs: {}, events: [{ type: 'error', error: message }] }; } /** `/workflow goal` 的外层生命周期控制;返回 execute=false 时不会进入脚本。 */ export async function prepareGoalCommand( rawInputs: Record, options: GoalCommandOptions, ): Promise { const runtime = options.runtime ?? new GoalRuntime(); const scope = scopeFor(options); const groupMode = options.runtimeContext?.conversationMode === 'group'; const actorId = groupMode ? options.provenance?.senderId : options.actorId ?? 'local-human'; if (!actorId || (groupMode && !options.provenance?.groupId)) { return error('群任务缺少可信发送者与群来源,拒绝控制本机 Goal。'); } rawInputs = { ...rawInputs }; if (typeof rawInputs.contract_json === 'string') { try { const contract = JSON.parse(rawInputs.contract_json); if (!contract || typeof contract !== 'object' || Array.isArray(contract) || typeof contract.objective !== 'string' || !Array.isArray(contract.acceptanceCriteria) || contract.acceptanceCriteria.some((value: unknown) => typeof value !== 'string' || !value.trim()) || ['deliverables', 'sourceRefs'].some((field) => contract[field] !== undefined && (!Array.isArray(contract[field]) || contract[field].some((value: unknown) => typeof value !== 'string'))) || (contract.scope !== undefined && typeof contract.scope !== 'string') || (contract.tokenBudget != null && (!Number.isSafeInteger(contract.tokenBudget) || contract.tokenBudget <= 0))) { return error('任务合同格式无效'); } Object.assign(rawInputs, { objective: contract.objective, acceptanceCriteria: contract.acceptanceCriteria, deliverables: contract.deliverables, sourceRefs: contract.sourceRefs, scope: contract.scope }); if (contract.tokenBudget != null) rawInputs.token_budget = contract.tokenBudget; } catch { return error('任务合同 JSON 无效'); } } const action = String(rawInputs.action ?? '').trim(); const objective = String(rawInputs.objective ?? '').trim(); let current = await runtime.get(scope); const inferredSource: GoalSource | undefined = options.source ?? ( typeof rawInputs.group_id === 'string' && rawInputs.group_id.trim() && typeof rawInputs.task_id === 'string' && rawInputs.task_id.trim() ? { kind: 'group-task', groupId: rawInputs.group_id.trim(), taskId: rawInputs.task_id.trim(), ...(typeof rawInputs.agent_member_id === 'string' && rawInputs.agent_member_id.trim() ? { assigneeAgentId: rawInputs.agent_member_id.trim() } : {}), } : undefined ); try { if (groupMode && (inferredSource?.kind !== 'group-task' || inferredSource.groupId !== options.provenance?.groupId)) { return error('群操作必须携带与可信线路一致的 group_id 和 task_id。'); } if (current && inferredSource?.kind === 'group-task' && (current.source.kind !== 'group-task' || current.source.groupId !== inferredSource.groupId || current.source.taskId !== inferredSource.taskId) && (action !== 'start' || !['accepted', 'cancelled'].includes(current.status))) { return error('目标任务与当前 Session Goal 不匹配,未执行任何操作。'); } if (groupMode && action && action !== 'start' && action !== 'status' && (!actorId.startsWith('user:') || (current && actorId !== current.createdBy && !current.acceptorHumanIds.includes(actorId)))) { return error('只有任务发起人或指定人类验收人可以控制该任务。'); } if (action === 'status' || (!action && !objective)) { return current ? handled(current, runtime) : error('当前 Session 没有 Goal。用 /workflow goal <目标> 创建。'); } if (action === 'cancel') { if (!current) return error('当前 Session 没有可取消的 Goal。'); current = await runtime.transition(scope, current.goalId, current.revision, 'cancelled', { reason: String(rawInputs.reason ?? '用户取消'), actorId, }); return handled(current, runtime, 'Goal 已取消,历史与产物仍保留。'); } if (action === 'pause') { if (!current) return error('当前 Session 没有可暂停的 Goal。'); current = await runtime.transition(scope, current.goalId, current.revision, 'paused', { reason: String(rawInputs.reason ?? '用户暂停'), actorId, }); return handled(current, runtime, 'Goal 已暂停,现场已保留。'); } if (action === 'accept') { if (!current) return error('当前 Session 没有待验收 Goal。'); current = await runtime.transition(scope, current.goalId, current.revision, 'accepted', { actorId }); return handled(current, runtime, '人类验收已通过。'); } if (action === 'update') { if (!current) return error('当前 Session 没有可更新的 Goal。'); if (!objective) return error('update 必须提供新的 objective。'); const patch: GoalContractInput = { objective, confirmedBy: actorId, }; // 未提供 checks 时保留原验收标准;只有显式传入才替换。 if (Object.prototype.hasOwnProperty.call(rawInputs, 'checks') || Array.isArray(rawInputs.acceptanceCriteria)) { patch.acceptanceCriteria = criteriaFrom(rawInputs); } for (const field of ['deliverables', 'sourceRefs', 'scope'] as const) { if (rawInputs[field] !== undefined) Object.assign(patch, { [field]: rawInputs[field] }); } // 预算也是版本化契约的一部分。显式传 0/非法值表示清除预算;未传时 // 由 Runtime 的合并规则保留旧值,避免 update 误清空预算。 if (Object.prototype.hasOwnProperty.call(rawInputs, 'token_budget')) { const budget = Number(rawInputs.token_budget); patch.tokenBudget = Number.isFinite(budget) && budget > 0 ? budget : null; } current = await runtime.revise(scope, current.goalId, current.revision, patch); } else if (action === 'resume' || action === 'rework') { if (!current) return error('当前 Session 没有可继续的 Goal。'); current = await runtime.transition(scope, current.goalId, current.revision, 'active', { reason: action === 'rework' ? String(rawInputs.reason ?? '人类要求返工') : '用户继续执行', actorId, }); rawInputs.objective = runtime.currentContract(current).objective; } else if (action && action !== 'start') { return error(`未知 Goal action:${action}`); } else if (!current || current.status === 'accepted' || current.status === 'cancelled') { if (!objective) return error('创建 Goal 必须提供 objective。'); current = await runtime.create({ scope, contract: { objective, acceptanceCriteria: criteriaFrom(rawInputs), deliverables: rawInputs.deliverables as string[] | undefined, sourceRefs: rawInputs.sourceRefs as string[] | undefined, scope: rawInputs.scope as string | undefined, tokenBudget: Number(rawInputs.token_budget) > 0 ? Number(rawInputs.token_budget) : null, confirmedBy: actorId, }, source: inferredSource, createdBy: actorId, acceptorHumanIds: options.acceptorHumanIds ?? [actorId], }); } else { const existingObjective = runtime.currentContract(current).objective; if (existingObjective !== objective) { return error( `当前 Session 已有未完成 Goal「${existingObjective}」。` + '请用 --input action=update 显式修改,或先 action=cancel。', ); } if (current.status !== 'active') return handled(current, runtime); } // 除非这次调用显式传了新预算,否则沿用当前契约里已有的预算 —— // workflow.mjs 每次都无条件把 args.token_budget 写进新契约版本(预算挂在 // 版本化契约上是刻意设计,见脚本内注释),如果这里不兜底,任何一次「不带 // token_budget 重跑」(resume/rework/update,甚至只是同目标再跑一轮)都会把 // 预算悄悄写成 null(不限),「用尽后加预算续跑」的断点设计就形同虚设—— // 用户以为在续跑同一个受限任务,实际上预算闸已经被静默关掉了。 if ( !Object.prototype.hasOwnProperty.call(rawInputs, 'token_budget') && !(Number(rawInputs.token_budget) > 0) ) { const existingBudget = runtime.currentContract(current).tokenBudget; if (typeof existingBudget === 'number' && existingBudget > 0) { rawInputs.token_budget = existingBudget; } } const started = await runtime.startAttempt(scope, current.goalId, current.revision, 'goal'); current = started.goal; const execution = started.execution; // Resume/rework retains the same human contract, even without command inputs. if (current.source.kind === 'group-task') { rawInputs.contract_json = JSON.stringify(runtime.currentContract(current)); rawInputs.interactive = 'false'; } const managedExecution: ManagedExecutionContext = { executionId: execution.goalId, version: execution.contractVersion, runId: execution.attemptId, anchor: renderExecutionAnchor(execution), correlations: { ...(execution.groupId ? { groupId: execution.groupId } : {}), ...(execution.taskId ? { taskId: execution.taskId } : {}), }, }; const bridge: ManagedExecutionBridge = { updateContract: async (rawInput) => { const input = rawInput as GoalContractInput; const latest = await runtime.get(scope); if (!latest || latest.goalId !== execution.goalId) { throw new GoalRuntimeError('GOAL_NOT_FOUND', 'Goal 在执行期间已改变。'); } const updated = await runtime.materializeAttemptContract( scope, latest.goalId, latest.revision, execution.attemptId, // A workflow may derive checks, never rewrite a human-confirmed group contract. latest.source.kind === 'group-task' ? { ...runtime.currentContract(latest), confirmedBy: actorId } : { ...input, confirmedBy: actorId }, ); const contract = runtime.currentContract(updated); execution.contractVersion = contract.version; execution.contract = contract; return { version: contract.version, anchor: renderExecutionAnchor(execution), value: contract, }; }, /** * 资源记账。累计值落在 `goal.usage`(事件溯源 + 持久化)而不是进程内 —— * 断点续跑时账本重放**不会重新执行** agent/llm 调用,进程内计数会从 0 开始, * 于是「已经花掉的钱」凭空消失、预算闸永远不触发。 * * ⚠️ 上限取**最新契约**的 tokenBudget,而用量**累计不重置**: * 「把预算从 10 万改到 20 万」因此是自然的「加预算继续跑」, * 而不是偷偷把已花的清零。 */ recordUsage: async (input) => { const latest = await runtime.get(scope); if (!latest || latest.goalId !== execution.goalId) { throw new GoalRuntimeError('GOAL_NOT_FOUND', 'Goal 在执行期间已改变。'); } const updated = await runtime.recordUsage( scope, latest.goalId, latest.revision, { inputTokens: input.inputTokens, outputTokens: input.outputTokens }, ); return { inputTokens: updated.usage.inputTokens, outputTokens: updated.usage.outputTokens, limit: runtime.currentContract(updated).tokenBudget ?? null, }; }, finish: async (input) => { const latest = await runtime.get(scope); if (!latest || latest.goalId !== execution.goalId) { throw new GoalRuntimeError('GOAL_NOT_FOUND', 'Goal 在执行期间已改变。'); } const attempt = latest.attempts.find((item) => item.attemptId === execution.attemptId); if (!attempt || attempt.status !== 'running') return latest; // Runner 传来的 status 是它自己视角的通用默认值(异常路径恒 'failed')—— // 它不认识 'budget_limited' 这种具体工作流结局,也不该认识(三层解耦)。 // 这里按 statusMapping.ts::OUTCOME_TO_ATTEMPT 把工作流自己贴在 Error 上的 // outcome 精化成真实该记的 attempt 状态:budget_limited 是主动停在安全边界、 // 现场完好可续跑,要记 'stopped' 而不是 'failed'——记成 'failed' 会让 // finishAttempt 把 Goal 派生成 blocked,而 TRANSITIONS 里根本没有 // blocked → budget_limited 这条边,budget_limited 永远到不了(此前正是这样: // 状态在类型和 TRANSITIONS 里都声明了,却没有任何代码路径能真正推到它)。 const outcome = typeof input.outcome === 'string' ? (input.outcome as WorkflowOutcome) : undefined; const attemptStatus = outcome && Object.hasOwn(OUTCOME_TO_ATTEMPT, outcome) ? OUTCOME_TO_ATTEMPT[outcome] : input.status; const finished = await runtime.finishAttempt({ scope, expectedGoalId: latest.goalId, expectedRevision: latest.revision, attemptId: execution.attemptId, status: attemptStatus, artifacts: input.artifacts, evidence: input.evidence, blocker: input.blocker, }); // ── 用户设的 token 预算用尽 → budget_limited ──────────────────── // finishAttempt 把 'stopped' 统一派生成 Goal.paused(与用户主动 action=pause // 共用同一落点);这里识别出「这次 stopped 是因为预算」后再精化一步, // 避免「用户暂停」与「系统按预算停」被压成同一个状态、桌面端分不清、 // 用户也不知道该不该加预算再续。 if (outcome === 'budget_limited' && finished.status === 'paused') { return runtime.transition( scope, finished.goalId, finished.revision, 'budget_limited', { reason: input.blocker, actorId }, ); } // ── 服务端配额/授权不给了 → usage_limited ────────────────────── // 识别放在这里而不是具体工作流里:usage_limited 是 Goal 外层生命周期, // 工作流只报告通用失败信息;Goal 状态本来就归控制器管理。 // // ⚠️ 与 budget_limited 分工不同,别合并: // budget_limited = 用户自己设的额度用完 → 加预算即可继续; // usage_limited = 服务端配额/授权不给了 → 加预算没用,要去解决授权。 // attempt 失败会先把 Goal 推到 blocked;识别出配额类原因后再精化成 // usage_limited(TRANSITIONS 里显式允许这条精化边)。 if ( input.status === 'failed' && isUsageLimitError(input.blocker ?? '') && finished.status === 'blocked' ) { return runtime.transition( scope, finished.goalId, finished.revision, 'usage_limited', { reason: input.blocker, actorId }, ); } return finished; }, }; return { handled: false, events: [], inputs: rawInputs, execution: managedExecution, bridge, }; } catch (caught) { return error( caught instanceof GoalRuntimeError ? caught.message : `Goal Runtime 失败:${caught instanceof Error ? caught.message : String(caught)}`, ); } } function renderExecutionAnchor(execution: GoalExecutionContext): string { const contract = execution.contract; return [ `🎯 Goal ${execution.goalId} · 契约 v${contract.version}`, `目标:${contract.objective}`, contract.deliverables.length ? `交付物:\n${contract.deliverables.map((item) => `- ${item}`).join('\n')}` : '', contract.acceptanceCriteria.length ? `验收标准:\n${contract.acceptanceCriteria.map((item) => `- ${item}`).join('\n')}` : '', contract.scope ? `工作范围:${contract.scope}` : '', contract.sourceRefs.length ? `资料引用:${contract.sourceRefs.join('、')}` : '', '只有指定人类可以最终验收;Agent 只能提交可核查证据并进入待验收。', ].filter(Boolean).join('\n\n'); }