@caupulican/pi-adaptative 0.93.2 → 0.93.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +6 -6
- package/dist/cli/args.js +1 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session-contracts.d.ts +2 -2
- package/dist/core/agent-session-contracts.d.ts.map +1 -1
- package/dist/core/agent-session-contracts.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +16 -11
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts +1 -0
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +4 -1
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/composite-tool-gate.d.ts +13 -0
- package/dist/core/autonomy/composite-tool-gate.d.ts.map +1 -0
- package/dist/core/autonomy/composite-tool-gate.js +44 -0
- package/dist/core/autonomy/composite-tool-gate.js.map +1 -0
- package/dist/core/autonomy/envelope-enforcement.d.ts +2 -0
- package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
- package/dist/core/autonomy/envelope-enforcement.js +48 -7
- package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
- package/dist/core/autonomy/gates.d.ts.map +1 -1
- package/dist/core/autonomy/gates.js +48 -76
- package/dist/core/autonomy/gates.js.map +1 -1
- package/dist/core/autonomy/path-scope.d.ts.map +1 -1
- package/dist/core/autonomy/path-scope.js +7 -7
- package/dist/core/autonomy/path-scope.js.map +1 -1
- package/dist/core/autonomy/subagent-prompt.d.ts +1 -1
- package/dist/core/autonomy/subagent-prompt.js.map +1 -1
- package/dist/core/background-tool-task-controller.d.ts +2 -0
- package/dist/core/background-tool-task-controller.d.ts.map +1 -1
- package/dist/core/background-tool-task-controller.js +13 -5
- package/dist/core/background-tool-task-controller.js.map +1 -1
- package/dist/core/compaction-controller.d.ts +3 -0
- package/dist/core/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +132 -97
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/cost-guard.js +1 -1
- package/dist/core/cost-guard.js.map +1 -1
- package/dist/core/delegation/session-root-mailbox.d.ts.map +1 -1
- package/dist/core/delegation/session-root-mailbox.js +14 -1
- package/dist/core/delegation/session-root-mailbox.js.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +6 -9
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.js +7 -5
- package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
- package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -1
- package/dist/core/delegation/worker-authority-resolver.js +3 -2
- package/dist/core/delegation/worker-authority-resolver.js.map +1 -1
- package/dist/core/delegation/worker-delegation-request.d.ts +5 -2
- package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-request.js +1 -1
- package/dist/core/delegation/worker-delegation-request.js.map +1 -1
- package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
- package/dist/core/delegation/worker-execution-policy.js +10 -8
- package/dist/core/delegation/worker-execution-policy.js.map +1 -1
- package/dist/core/foreground-recovery-controller.d.ts +2 -0
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
- package/dist/core/foreground-recovery-controller.js +18 -9
- package/dist/core/foreground-recovery-controller.js.map +1 -1
- package/dist/core/goal-loop-controller.d.ts.map +1 -1
- package/dist/core/goal-loop-controller.js +3 -5
- package/dist/core/goal-loop-controller.js.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js +6 -0
- package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
- package/dist/core/goals/goal-session-controller.js +1 -1
- package/dist/core/goals/goal-session-controller.js.map +1 -1
- package/dist/core/goals/goal-state.d.ts.map +1 -1
- package/dist/core/goals/goal-state.js +1 -0
- package/dist/core/goals/goal-state.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +2 -0
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +1 -1
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/model-router-controller.js +2 -2
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
- package/dist/core/orchestration/capability-gateway.js +32 -9
- package/dist/core/orchestration/capability-gateway.js.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.js +5 -5
- package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
- package/dist/core/orchestration/policy-compiler.d.ts.map +1 -1
- package/dist/core/orchestration/policy-compiler.js +7 -0
- package/dist/core/orchestration/policy-compiler.js.map +1 -1
- package/dist/core/orchestration/profile-registry.js +2 -2
- package/dist/core/orchestration/profile-registry.js.map +1 -1
- package/dist/core/orchestration/risk-budget.d.ts +0 -10
- package/dist/core/orchestration/risk-budget.d.ts.map +1 -1
- package/dist/core/orchestration/risk-budget.js +0 -14
- package/dist/core/orchestration/risk-budget.js.map +1 -1
- package/dist/core/pipelines/active-context.d.ts +16 -0
- package/dist/core/pipelines/active-context.d.ts.map +1 -0
- package/dist/core/pipelines/active-context.js +29 -0
- package/dist/core/pipelines/active-context.js.map +1 -0
- package/dist/core/pipelines/context.d.ts +1 -1
- package/dist/core/pipelines/context.d.ts.map +1 -1
- package/dist/core/pipelines/context.js +40 -31
- package/dist/core/pipelines/context.js.map +1 -1
- package/dist/core/pipelines/discover.d.ts +5 -1
- package/dist/core/pipelines/discover.d.ts.map +1 -1
- package/dist/core/pipelines/discover.js +91 -33
- package/dist/core/pipelines/discover.js.map +1 -1
- package/dist/core/pipelines/increment.d.ts +0 -2
- package/dist/core/pipelines/increment.d.ts.map +1 -1
- package/dist/core/pipelines/increment.js +35 -13
- package/dist/core/pipelines/increment.js.map +1 -1
- package/dist/core/pipelines/index.d.ts +4 -3
- package/dist/core/pipelines/index.d.ts.map +1 -1
- package/dist/core/pipelines/index.js +4 -3
- package/dist/core/pipelines/index.js.map +1 -1
- package/dist/core/pipelines/run-state.d.ts +8 -0
- package/dist/core/pipelines/run-state.d.ts.map +1 -1
- package/dist/core/pipelines/run-state.js +172 -38
- package/dist/core/pipelines/run-state.js.map +1 -1
- package/dist/core/pipelines/types.d.ts +2 -0
- package/dist/core/pipelines/types.d.ts.map +1 -1
- package/dist/core/pipelines/types.js +21 -4
- package/dist/core/pipelines/types.js.map +1 -1
- package/dist/core/provider-prompt-contracts.d.ts +1 -0
- package/dist/core/provider-prompt-contracts.d.ts.map +1 -1
- package/dist/core/provider-prompt-contracts.js +6 -5
- package/dist/core/provider-prompt-contracts.js.map +1 -1
- package/dist/core/reflection-controller.js +1 -1
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +2 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +46 -10
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/settings-manager.d.ts +5 -6
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +8 -13
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +2 -4
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +35 -11
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +6 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/task-projection.d.ts +2 -0
- package/dist/core/tasks/task-projection.d.ts.map +1 -1
- package/dist/core/tasks/task-projection.js +2 -0
- package/dist/core/tasks/task-projection.js.map +1 -1
- package/dist/core/tasks/task-state.d.ts +10 -0
- package/dist/core/tasks/task-state.d.ts.map +1 -1
- package/dist/core/tasks/task-state.js +43 -2
- package/dist/core/tasks/task-state.js.map +1 -1
- package/dist/core/tool-capability-policy.d.ts +13 -3
- package/dist/core/tool-capability-policy.d.ts.map +1 -1
- package/dist/core/tool-capability-policy.js +136 -28
- package/dist/core/tool-capability-policy.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +0 -16
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +21 -11
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +45 -7
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +5 -1
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +17 -1
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/orchestration-panel.d.ts.map +1 -1
- package/dist/core/tools/orchestration-panel.js +1 -0
- package/dist/core/tools/orchestration-panel.js.map +1 -1
- package/dist/core/tools/persistent-process-coordinator.d.ts.map +1 -1
- package/dist/core/tools/persistent-process-coordinator.js +12 -7
- package/dist/core/tools/persistent-process-coordinator.js.map +1 -1
- package/dist/core/tools/pipeline.d.ts +1 -0
- package/dist/core/tools/pipeline.d.ts.map +1 -1
- package/dist/core/tools/pipeline.js +95 -44
- package/dist/core/tools/pipeline.js.map +1 -1
- package/dist/core/tools/profile-writer.d.ts +0 -9
- package/dist/core/tools/profile-writer.d.ts.map +1 -1
- package/dist/core/tools/profile-writer.js +0 -3
- package/dist/core/tools/profile-writer.js.map +1 -1
- package/dist/core/tools/secret-store.d.ts.map +1 -1
- package/dist/core/tools/secret-store.js +2 -1
- package/dist/core/tools/secret-store.js.map +1 -1
- package/dist/core/tools/shell-session.d.ts.map +1 -1
- package/dist/core/tools/shell-session.js +6 -1
- package/dist/core/tools/shell-session.js.map +1 -1
- package/dist/core/tools/task-steps.d.ts +10 -0
- package/dist/core/tools/task-steps.d.ts.map +1 -1
- package/dist/core/tools/task-steps.js +70 -29
- package/dist/core/tools/task-steps.js.map +1 -1
- package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
- package/dist/core/tools/windows-shell-engine.js +6 -1
- package/dist/core/tools/windows-shell-engine.js.map +1 -1
- package/dist/core/util/bounded-file.d.ts +8 -0
- package/dist/core/util/bounded-file.d.ts.map +1 -1
- package/dist/core/util/bounded-file.js +81 -16
- package/dist/core/util/bounded-file.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +7 -16
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +2 -11
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
- package/dist/modes/interactive/local-model-commands.js +1 -10
- package/dist/modes/interactive/local-model-commands.js.map +1 -1
- package/dist/modes/interactive/thinking-level-descriptions.d.ts +4 -0
- package/dist/modes/interactive/thinking-level-descriptions.d.ts.map +1 -0
- package/dist/modes/interactive/thinking-level-descriptions.js +12 -0
- package/dist/modes/interactive/thinking-level-descriptions.js.map +1 -0
- package/docs/resources.md +1 -1
- package/docs/settings.md +7 -5
- package/docs/worker-profiles.md +3 -3
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 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;QACvC,MAAM,QAAQ,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/D,MAAM,CAAC,IAAI,CACV,2BAA2B,QAAQ,+CAA+C,WAAW,CAAC,EAAE,0DAA0D,CAC1J,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kCAAkC,CACjD,MAAkB,EAClB,KAAgB,EAChB,aAAqD;IAErD,IAAI,CAAC,aAAa,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAC5D,IAAI,MAAM,CAAC,MAAM,KAAK,qBAAqB,EAAE,CAAC;QAC7C,OAAO,mCAAmC,CAAC,KAAK,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,EAAE,aAAa,CAAC,CAAC;IACjG,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAClC,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY;aACrC,MAAM,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,MAAM,KAAK,WAAW,CAAC;aAC3D,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;QACvC,OAAO,mCAAmC,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { type BackgroundToolTaskRef, findBackgroundToolTask } from \"../background-tool-task-controller.ts\";\nimport { taskStepReferencesRequirement } from \"../tasks/task-projection.ts\";\nimport { getUnprovenGoalRequirementIds } from \"./goal-acceptance.ts\";\nimport { formatGoalRecord, projectGoalRecord } from \"./goal-record.ts\";\nimport {\n\tapplyGoalEvent,\n\tcreateGoalState,\n\ttype GoalEvent,\n\ttype GoalEvidenceKind,\n\ttype GoalState,\n\tisGoalExecutionActive,\n\tisGoalUnfinishedStatus,\n\tMAX_GOAL_OBJECTIVE_LENGTH,\n} from \"./goal-state.ts\";\n\nconst MAX_GOAL_ID_LENGTH = 128;\nconst MAX_GOAL_REQUIREMENTS = 256;\nconst MAX_GOAL_EVIDENCE = 512;\nconst MAX_GOAL_LEDGER_TEXT_LENGTH = 4_000;\nconst MAX_GOAL_URI_LENGTH = 4_096;\nconst MIN_AGENT_BLOCK_STALL_TURNS = 3;\n\n/**\n * Agent-facing goal ledger actions.\n *\n * This is the producer half of the goal continuation pipeline: the agent records\n * what it is trying to achieve and how far it has gotten, and those records become\n * the {@link GoalState} snapshots that the runtime continuation consumer reads.\n *\n * Each action maps onto either {@link createGoalState} or a single\n * {@link GoalEvent}, so the durable state model stays the single source of truth.\n */\nexport type GoalAction =\n\t| { action: \"start\"; goalId: string; userGoal: string; tokenBudget?: number }\n\t| { action: \"add_requirement\"; requirementId: string; text: string; dependencies?: readonly string[] }\n\t| { action: \"satisfy_requirement\"; requirementId: string; evidenceIds?: readonly string[] }\n\t| { action: \"block_requirement\"; requirementId: string; reason: string }\n\t| { action: \"reopen_requirement\"; requirementId: string }\n\t| {\n\t\t\taction: \"dispatch_worker\";\n\t\t\trequirementId: string;\n\t\t\tinstructions: string;\n\t\t\t/**\n\t\t\t * LaneId returned by the tool layer's dispatch side effect (calling the real worker/tmux\n\t\t\t * dispatch). Computed by the tool layer -- which has session/runtime access -- and merged\n\t\t\t * onto the action before it reaches this pure reducer, exactly like `add_evidence`'s\n\t\t\t * `verified` field. Undefined when the dispatch side effect is unwired/stubbed.\n\t\t\t */\n\t\t\tlaneId?: string;\n\t }\n\t| {\n\t\t\taction: \"add_evidence\";\n\t\t\tevidenceId: string;\n\t\t\tkind: GoalEvidenceKind;\n\t\t\tsummary: string;\n\t\t\turi?: string;\n\t\t\t/**\n\t\t\t * Whether `uri` was checked against session records/the filesystem. Computed by the\n\t\t\t * tool layer (which has session/filesystem access); `applyGoalAction` stays pure and\n\t\t\t * only carries this value through into the recorded {@link GoalEvidenceRef}.\n\t\t\t */\n\t\t\tverified?: boolean;\n\t }\n\t| { action: \"progress\" }\n\t| { action: \"no_progress\" }\n\t| { action: \"complete\" }\n\t| { action: \"increment\" }\n\t| { action: \"block_goal\"; reason: string };\n\nexport type GoalActionName = GoalAction[\"action\"];\n\nexport interface GoalActionSuccess {\n\tok: true;\n\tstate: GoalState;\n}\n\nexport interface GoalActionFailure {\n\tok: false;\n\terror: string;\n}\n\nexport type GoalActionResult = GoalActionSuccess | GoalActionFailure;\n\nexport interface ApplyGoalActionOptions {\n\t/**\n\t * Gate agent-facing 'complete' on every satisfied requirement being backed by\n\t * verified-ref evidence (kind 'tool'/'file' with `verified === true`) or kind 'user'\n\t * evidence. Defaults to `true` (on) when omitted — the conservative default. Manual\n\t * completion ({@link completeGoalManually}) is never subject to this gate.\n\t */\n\trequireVerifiedEvidenceForCompletion?: boolean;\n\t/**\n\t * Open (non-terminal) task_steps on this branch. Agent-facing complete refuses while any of\n\t * these still reference a requirement of the goal being closed.\n\t */\n\topenTaskSteps?: readonly OpenTaskStepRef[];\n\t/** Live background tool_task records used to re-check kind:\"tool\" evidence at complete time. */\n\tbackgroundToolTasks?: readonly BackgroundToolTaskRef[];\n\t/** Active ICM pipeline run; agent complete refuses while a joined or any active run remains. */\n\tactivePipeline?: { runId: string; pipelineName: string; goalId?: string; status: string };\n}\n\nfunction requirementExists(state: GoalState, requirementId: string): boolean {\n\treturn state.requirements.some((requirement) => requirement.id === requirementId);\n}\n\nfunction evidenceExists(state: GoalState, evidenceId: string): boolean {\n\treturn state.evidence.some((evidence) => evidence.id === evidenceId);\n}\n\n/**\n * Apply one agent-facing goal action to the current ledger state.\n *\n * Pure: takes the current state (or `undefined` when no goal exists yet) and the\n * action, and returns either the next state or a validation error. Performs no\n * I/O and never mutates its inputs.\n */\nexport function applyGoalAction(\n\tcurrent: GoalState | undefined,\n\taction: GoalAction,\n\tnow: string,\n\toptions?: ApplyGoalActionOptions,\n): GoalActionResult {\n\tif (action.action === \"start\") {\n\t\tconst goalId = action.goalId.trim();\n\t\tconst userGoal = action.userGoal.trim();\n\t\tif (!goalId) return { ok: false, error: \"start requires a non-empty goalId.\" };\n\t\tif (!userGoal) return { ok: false, error: \"start requires a non-empty userGoal.\" };\n\t\tif (goalId.length > MAX_GOAL_ID_LENGTH) {\n\t\t\treturn { ok: false, error: `start goalId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t}\n\t\tif (userGoal.length > MAX_GOAL_OBJECTIVE_LENGTH) {\n\t\t\treturn { ok: false, error: `start userGoal must be at most ${MAX_GOAL_OBJECTIVE_LENGTH} characters.` };\n\t\t}\n\t\tif (action.tokenBudget !== undefined && (!Number.isSafeInteger(action.tokenBudget) || action.tokenBudget <= 0)) {\n\t\t\treturn { ok: false, error: \"start tokenBudget must be a positive integer when provided.\" };\n\t\t}\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `An unfinished goal '${current.goalId}' already exists (${current.status}). Complete, clear, or explicitly replace it before starting '${goalId}'.`,\n\t\t\t};\n\t\t}\n\t\treturn { ok: true, state: createGoalState({ goalId, userGoal, tokenBudget: action.tokenBudget, now }) };\n\t}\n\n\tif (!current) {\n\t\treturn { ok: false, error: \"No active goal. Use action 'start' before recording goal updates.\" };\n\t}\n\n\tif (!isGoalExecutionActive(current.status)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Goal '${current.goalId}' is ${current.status}. Lifecycle changes are owner/system controlled; use the /goal controls.`,\n\t\t};\n\t}\n\n\tif (action.action === \"increment\") {\n\t\tconst firstOpen = current.requirements.find((requirement) => requirement.status === \"open\");\n\t\tif (firstOpen) {\n\t\t\tconst used = new Set(current.requirements.flatMap((requirement) => requirement.evidenceIds));\n\t\t\tconst unused = current.evidence.filter((evidence) => !used.has(evidence.id)).map((evidence) => evidence.id);\n\t\t\tif (unused.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot increment goal: open requirement '${firstOpen.id}' has no unused evidence. Record evidence, then increment.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn applyGoalAction(\n\t\t\t\tcurrent,\n\t\t\t\t{ action: \"satisfy_requirement\", requirementId: firstOpen.id, evidenceIds: unused },\n\t\t\t\tnow,\n\t\t\t\toptions,\n\t\t\t);\n\t\t}\n\t\treturn applyGoalAction(current, { action: \"complete\" }, now, options);\n\t}\n\n\tconst event = toGoalEvent(current, action, now, options);\n\tif (!event.ok) return event;\n\treturn { ok: true, state: applyGoalEvent(current, event.event) };\n}\n\ntype ToGoalEventResult = { ok: true; event: GoalEvent } | GoalActionFailure;\n\nfunction toGoalEvent(\n\tstate: GoalState,\n\taction: GoalAction,\n\tnow: string,\n\toptions: ApplyGoalActionOptions | undefined,\n): ToGoalEventResult {\n\tswitch (action.action) {\n\t\tcase \"add_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst text = action.text.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!text) return { ok: false, error: \"add_requirement requires non-empty text.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirementId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (text.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirement text must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.requirements.length >= MAX_GOAL_REQUIREMENTS) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_REQUIREMENTS} requirements.` };\n\t\t\t}\n\t\t\tif (requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' already exists.` };\n\t\t\t}\n\t\t\tif (action.dependencies) {\n\t\t\t\tfor (const depId of action.dependencies) {\n\t\t\t\t\tif (!requirementExists(state, depId) && depId !== id) {\n\t\t\t\t\t\treturn { ok: false, error: `Dependency requirementId '${depId}' does not exist.` };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"add_requirement\", id, text, dependencies: action.dependencies, now } };\n\t\t}\n\t\tcase \"satisfy_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"satisfy_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tconst evidenceIds = action.evidenceIds ?? [];\n\t\t\tfor (const evidenceId of evidenceIds) {\n\t\t\t\tif (!evidenceExists(state, evidenceId)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Unknown evidence '${evidenceId}'. Record it with action 'add_evidence' first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"satisfy_requirement\", id, evidenceIds: [...evidenceIds], now } };\n\t\t}\n\t\tcase \"block_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!id) return { ok: false, error: \"block_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!reason) return { ok: false, error: \"block_requirement requires a non-empty reason.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_requirement\", id, blockedReason: reason, now } };\n\t\t}\n\t\tcase \"reopen_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"reopen_requirement requires a non-empty requirementId.\" };\n\t\t\tconst requirement = state.requirements.find((candidate) => candidate.id === id);\n\t\t\tif (!requirement) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tif (requirement.status !== \"blocked\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Requirement '${id}' is ${requirement.status}; only blocked requirements can be reopened.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"reopen_requirement\", id, now } };\n\t\t}\n\t\tcase \"dispatch_worker\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst instructions = action.instructions.trim();\n\t\t\tif (!id) return { ok: false, error: \"dispatch_worker requires a non-empty requirementId.\" };\n\t\t\tif (!instructions) return { ok: false, error: \"dispatch_worker requires non-empty instructions.\" };\n\t\t\tconst requirement = state.requirements.find((r) => r.id === id);\n\t\t\tif (!requirement) return { ok: false, error: `Requirement '${id}' does not exist.` };\n\t\t\tif (requirement.status !== \"open\") {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' is not open (status: ${requirement.status}).` };\n\t\t\t}\n\t\t\tif (requirement.dependencies) {\n\t\t\t\tconst unsatisfied = requirement.dependencies.filter((depId) => {\n\t\t\t\t\tconst dep = state.requirements.find((r) => r.id === depId);\n\t\t\t\t\treturn !dep || dep.status !== \"satisfied\";\n\t\t\t\t});\n\t\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot dispatch worker: dependencies not satisfied [${unsatisfied.join(\", \")}].`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"dispatch_worker\", id, instructions, laneId: action.laneId, now } };\n\t\t}\n\t\tcase \"add_evidence\": {\n\t\t\tconst id = action.evidenceId.trim();\n\t\t\tconst summary = action.summary.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_evidence requires a non-empty evidenceId.\" };\n\t\t\tif (!summary) return { ok: false, error: \"add_evidence requires a non-empty summary.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidenceId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (summary.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence summary must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif ((action.uri?.trim().length ?? 0) > MAX_GOAL_URI_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence uri must be at most ${MAX_GOAL_URI_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.evidence.length >= MAX_GOAL_EVIDENCE) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_EVIDENCE} evidence entries.` };\n\t\t\t}\n\t\t\tif (evidenceExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Evidence '${id}' already exists.` };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: {\n\t\t\t\t\ttype: \"add_evidence\",\n\t\t\t\t\tid,\n\t\t\t\t\tkind: action.kind,\n\t\t\t\t\tsummary,\n\t\t\t\t\turi: action.uri?.trim() || undefined,\n\t\t\t\t\tverified: action.verified,\n\t\t\t\t\tnow,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tcase \"progress\":\n\t\t\treturn { ok: true, event: { type: \"progress\", now } };\n\t\tcase \"no_progress\":\n\t\t\treturn { ok: true, event: { type: \"no_progress\", now } };\n\t\tcase \"increment\":\n\t\t\treturn { ok: false, error: \"increment must be expanded by applyGoalAction.\" };\n\t\tcase \"complete\": {\n\t\t\tconst unsatisfied = state.requirements.filter((requirement) => requirement.status !== \"satisfied\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: ${unsatisfied.length} requirement(s) not satisfied (${unsatisfied\n\t\t\t\t\t\t.map((requirement) => requirement.id)\n\t\t\t\t\t\t.join(\", \")}).`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;\n\t\t\tconst linkedOpenSteps = findLinkedOpenTaskSteps(state, options?.openTaskSteps);\n\t\t\tif (linkedOpenSteps.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: open task_steps still reference this goal (${linkedOpenSteps.join(\", \")}). Update them via task_steps first.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pendingToolTasks = findNonterminalCitedToolTasks(state, options?.backgroundToolTasks);\n\t\t\tif (pendingToolTasks.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: cited tool_task(s) are not complete (${pendingToolTasks.join(\", \")}). Wait once via tool_task, then record the terminal result.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst activePipeline = options?.activePipeline;\n\t\t\tif (activePipeline && activePipeline.status === \"active\") {\n\t\t\t\tconst joined = !activePipeline.goalId || activePipeline.goalId === state.goalId;\n\t\t\t\tif (joined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot complete goal: pipeline '${activePipeline.pipelineName}' run '${activePipeline.runId}' is still active. Increment or abandon it first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst unprovenRequirementIds = getUnprovenGoalRequirementIds(state);\n\t\t\tif (requireVerifiedEvidence && unprovenRequirementIds.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: requirement(s) lack verified evidence (${unprovenRequirementIds.join(\", \")}). Record verified or user-confirmed evidence and cite it in satisfy_requirement.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: { type: \"complete_goal\", acceptanceOverride: !requireVerifiedEvidence, now },\n\t\t\t};\n\t\t}\n\t\tcase \"block_goal\": {\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!reason) return { ok: false, error: \"block_goal requires a non-empty reason.\" };\n\t\t\tif (state.stallTurns < MIN_AGENT_BLOCK_STALL_TURNS) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot block goal: the host has recorded ${state.stallTurns}/${MIN_AGENT_BLOCK_STALL_TURNS} consecutive no-progress goal turns. Keep the goal active until the same blocker has persisted for at least three consecutive goal turns.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_goal\", reason, now } };\n\t\t}\n\t\tdefault:\n\t\t\treturn { ok: false, error: \"Unknown goal action.\" };\n\t}\n}\n\n/**\n * Complete a goal on explicit user authority, even when requirements remain open or\n * blocked. Agent-facing `complete` stays evidence-gated; this path is reserved for\n * direct user lifecycle controls.\n */\nexport function completeGoalManually(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) {\n\t\treturn { ok: false, error: \"No goal exists to complete.\" };\n\t}\n\tif (current.status === \"completed\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is already completed.` };\n\t}\n\tif (current.status === \"cancelled\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is cancelled; start or override with a new goal.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"complete_goal_manually\", now }) };\n}\n\n/** Render a compact human-readable summary of the ledger after an action. */\nexport function summarizeGoalState(\n\tstate: GoalState,\n\toptions?: { action?: GoalAction; openTaskSteps?: readonly OpenTaskStepRef[] },\n): string {\n\tconst lines = [formatGoalRecord(projectGoalRecord(state))];\n\tif (state.requirements.length > 0) {\n\t\tconst openIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"open\")\n\t\t\t.slice(0, 20)\n\t\t\t.map((requirement) => requirement.id);\n\t\tlines.push(\n\t\t\t`Legacy ledger: ${state.requirements.length} requirements, ${state.evidence.length} evidence${openIds.length > 0 ? `; open: ${openIds.join(\", \")}` : \"\"}.`,\n\t\t);\n\t}\n\tif (options?.action) {\n\t\tlines.push(...buildGoalTaskCrossVisibilityNudges(options.action, state, options.openTaskSteps));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Read-only goal⇄task cross-visibility (bounded slice — no shared state machine).\n *\n * `goal-tool-core` never reads or mutates task state itself (it stays pure); callers that DO\n * have access to the branch-scoped open task steps (e.g. via `buildGoalRuntimeSnapshot`) may\n * pass them through here to surface a nudge in the tool response when an open task_steps step is\n * explicitly linked to, or conservatively appears to reference, a requirement the agent just\n * satisfied or completed. Task state is never written from goal code — this only reads an\n * already-resolved, caller-supplied summary.\n */\nexport interface OpenTaskStepRef {\n\tid: string;\n\tcontent: string;\n\trequirementIds?: readonly string[];\n\tevidence?: readonly string[];\n}\n\nfunction findLinkedOpenTaskSteps(state: GoalState, openTaskSteps: readonly OpenTaskStepRef[] | undefined): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\treturn openTaskSteps\n\t\t.filter((step) => state.requirements.some((requirement) => taskStepReferencesRequirement(step, requirement)))\n\t\t.map((step) => step.id);\n}\n\nfunction findNonterminalCitedToolTasks(\n\tstate: GoalState,\n\tbackgroundToolTasks: readonly BackgroundToolTaskRef[] | undefined,\n): string[] {\n\tif (!backgroundToolTasks || backgroundToolTasks.length === 0) return [];\n\tconst pending = new Set<string>();\n\tfor (const evidence of state.evidence) {\n\t\tif (evidence.kind !== \"tool\" || !evidence.uri) continue;\n\t\tconst task = findBackgroundToolTask(backgroundToolTasks, evidence.uri);\n\t\tif (task && task.status !== \"completed\") pending.add(task.taskId);\n\t}\n\treturn [...pending];\n}\n\n/**\n * Nudge lines for open task steps that reference any of `requirementIds` (deduped per\n * requirement, one line naming every referencing step). Empty when there is nothing to say.\n */\nexport function findRequirementCrossReferenceNudges(\n\tstate: GoalState,\n\trequirementIds: readonly string[],\n\topenTaskSteps: readonly OpenTaskStepRef[],\n): string[] {\n\tif (openTaskSteps.length === 0 || requirementIds.length === 0) return [];\n\tconst nudges: string[] = [];\n\tfor (const requirementId of requirementIds) {\n\t\tconst requirement = state.requirements.find((candidate) => candidate.id === requirementId);\n\t\tif (!requirement) continue;\n\t\tconst referencing = openTaskSteps.filter((step) => taskStepReferencesRequirement(step, requirement));\n\t\tif (referencing.length === 0) continue;\n\t\tconst stepList = referencing.map((step) => step.id).join(\", \");\n\t\tnudges.push(\n\t\t\t`Note: open task step(s) ${stepList} appear to reference satisfied requirement '${requirement.id}' -- consider updating them via task_steps once covered.`,\n\t\t);\n\t}\n\treturn nudges;\n}\n\n/**\n * After 'satisfy_requirement' or 'complete', nudge lines for linked open task steps. Returns `[]`\n * for every other action, or when\n * `openTaskSteps` was not supplied (the default -- backward compatible, no behavior change for\n * callers that do not pass task-step context).\n */\nexport function buildGoalTaskCrossVisibilityNudges(\n\taction: GoalAction,\n\tstate: GoalState,\n\topenTaskSteps: readonly OpenTaskStepRef[] | undefined,\n): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\tif (action.action === \"satisfy_requirement\") {\n\t\treturn findRequirementCrossReferenceNudges(state, [action.requirementId.trim()], openTaskSteps);\n\t}\n\tif (action.action === \"complete\") {\n\t\tconst satisfiedIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"satisfied\")\n\t\t\t.map((requirement) => requirement.id);\n\t\treturn findRequirementCrossReferenceNudges(state, satisfiedIds, openTaskSteps);\n\t}\n\treturn [];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"goal-tool-core.js","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAC3G,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AACrE,OAAO,EAAE,gB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;;;GAKG;AACH,MAAM,UAAU,kCAAkC,CACjD,MAAkB,EAClB,KAAgB,EAChB,aAAqD;IAErD,IAAI,CAAC,aAAa,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IAC5D,IAAI,MAAM,CAAC,MAAM,KAAK,qBAAqB,EAAE,CAAC;QAC7C,OAAO,mCAAmC,CAAC,KAAK,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC,EAAE,aAAa,CAAC,CAAC;IACjG,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;QAClC,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY;aACrC,MAAM,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,MAAM,KAAK,WAAW,CAAC;aAC3D,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;QACvC,OAAO,mCAAmC,CAAC,KAAK,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { type BackgroundToolTaskRef, findBackgroundToolTask } from \"../background-tool-task-controller.ts\";\nimport { taskStepReferencesRequirement } from \"../tasks/task-projection.ts\";\nimport { getUnprovenGoalRequirementIds } from \"./goal-acceptance.ts\";\nimport { formatGoalRecord, projectGoalRecord } from \"./goal-record.ts\";\nimport {\n\tapplyGoalEvent,\n\tcreateGoalState,\n\ttype GoalEvent,\n\ttype GoalEvidenceKind,\n\ttype GoalState,\n\tisGoalExecutionActive,\n\tisGoalUnfinishedStatus,\n\tMAX_GOAL_OBJECTIVE_LENGTH,\n} from \"./goal-state.ts\";\n\nconst MAX_GOAL_ID_LENGTH = 128;\nconst MAX_GOAL_REQUIREMENTS = 256;\nconst MAX_GOAL_EVIDENCE = 512;\nconst MAX_GOAL_LEDGER_TEXT_LENGTH = 4_000;\nconst MAX_GOAL_URI_LENGTH = 4_096;\nconst MIN_AGENT_BLOCK_STALL_TURNS = 3;\n\n/**\n * Agent-facing goal ledger actions.\n *\n * This is the producer half of the goal continuation pipeline: the agent records\n * what it is trying to achieve and how far it has gotten, and those records become\n * the {@link GoalState} snapshots that the runtime continuation consumer reads.\n *\n * Each action maps onto either {@link createGoalState} or a single\n * {@link GoalEvent}, so the durable state model stays the single source of truth.\n */\nexport type GoalAction =\n\t| { action: \"start\"; goalId: string; userGoal: string; tokenBudget?: number }\n\t| { action: \"add_requirement\"; requirementId: string; text: string; dependencies?: readonly string[] }\n\t| { action: \"satisfy_requirement\"; requirementId: string; evidenceIds?: readonly string[] }\n\t| { action: \"block_requirement\"; requirementId: string; reason: string }\n\t| { action: \"reopen_requirement\"; requirementId: string }\n\t| {\n\t\t\taction: \"dispatch_worker\";\n\t\t\trequirementId: string;\n\t\t\tinstructions: string;\n\t\t\t/**\n\t\t\t * LaneId returned by the tool layer's dispatch side effect (calling the real worker/tmux\n\t\t\t * dispatch). Computed by the tool layer -- which has session/runtime access -- and merged\n\t\t\t * onto the action before it reaches this pure reducer, exactly like `add_evidence`'s\n\t\t\t * `verified` field. Undefined when the dispatch side effect is unwired/stubbed.\n\t\t\t */\n\t\t\tlaneId?: string;\n\t }\n\t| {\n\t\t\taction: \"add_evidence\";\n\t\t\tevidenceId: string;\n\t\t\tkind: GoalEvidenceKind;\n\t\t\tsummary: string;\n\t\t\turi?: string;\n\t\t\t/**\n\t\t\t * Whether `uri` was checked against session records/the filesystem. Computed by the\n\t\t\t * tool layer (which has session/filesystem access); `applyGoalAction` stays pure and\n\t\t\t * only carries this value through into the recorded {@link GoalEvidenceRef}.\n\t\t\t */\n\t\t\tverified?: boolean;\n\t }\n\t| { action: \"progress\" }\n\t| { action: \"no_progress\" }\n\t| { action: \"complete\" }\n\t| { action: \"increment\" }\n\t| { action: \"block_goal\"; reason: string };\n\nexport type GoalActionName = GoalAction[\"action\"];\n\nexport interface GoalActionSuccess {\n\tok: true;\n\tstate: GoalState;\n}\n\nexport interface GoalActionFailure {\n\tok: false;\n\terror: string;\n}\n\nexport type GoalActionResult = GoalActionSuccess | GoalActionFailure;\n\nexport interface ApplyGoalActionOptions {\n\t/**\n\t * Gate agent-facing 'complete' on every satisfied requirement being backed by\n\t * verified-ref evidence (kind 'tool'/'file' with `verified === true`) or kind 'user'\n\t * evidence. Defaults to `true` (on) when omitted — the conservative default. Manual\n\t * completion ({@link completeGoalManually}) is never subject to this gate.\n\t */\n\trequireVerifiedEvidenceForCompletion?: boolean;\n\t/**\n\t * Open (non-terminal) task_steps on this branch. Agent-facing complete refuses while any of\n\t * these still reference a requirement of the goal being closed.\n\t */\n\topenTaskSteps?: readonly OpenTaskStepRef[];\n\t/** Live background tool_task records used to re-check kind:\"tool\" evidence at complete time. */\n\tbackgroundToolTasks?: readonly BackgroundToolTaskRef[];\n\t/** Active ICM pipeline run; agent complete refuses while a joined or any active run remains. */\n\tactivePipeline?: { runId: string; pipelineName: string; goalId?: string; status: string };\n}\n\nfunction requirementExists(state: GoalState, requirementId: string): boolean {\n\treturn state.requirements.some((requirement) => requirement.id === requirementId);\n}\n\nfunction evidenceExists(state: GoalState, evidenceId: string): boolean {\n\treturn state.evidence.some((evidence) => evidence.id === evidenceId);\n}\n\n/**\n * Apply one agent-facing goal action to the current ledger state.\n *\n * Pure: takes the current state (or `undefined` when no goal exists yet) and the\n * action, and returns either the next state or a validation error. Performs no\n * I/O and never mutates its inputs.\n */\nexport function applyGoalAction(\n\tcurrent: GoalState | undefined,\n\taction: GoalAction,\n\tnow: string,\n\toptions?: ApplyGoalActionOptions,\n): GoalActionResult {\n\tif (action.action === \"start\") {\n\t\tconst goalId = action.goalId.trim();\n\t\tconst userGoal = action.userGoal.trim();\n\t\tif (!goalId) return { ok: false, error: \"start requires a non-empty goalId.\" };\n\t\tif (!userGoal) return { ok: false, error: \"start requires a non-empty userGoal.\" };\n\t\tif (goalId.length > MAX_GOAL_ID_LENGTH) {\n\t\t\treturn { ok: false, error: `start goalId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t}\n\t\tif (userGoal.length > MAX_GOAL_OBJECTIVE_LENGTH) {\n\t\t\treturn { ok: false, error: `start userGoal must be at most ${MAX_GOAL_OBJECTIVE_LENGTH} characters.` };\n\t\t}\n\t\tif (action.tokenBudget !== undefined && (!Number.isSafeInteger(action.tokenBudget) || action.tokenBudget <= 0)) {\n\t\t\treturn { ok: false, error: \"start tokenBudget must be a positive integer when provided.\" };\n\t\t}\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `An unfinished goal '${current.goalId}' already exists (${current.status}). Complete, clear, or explicitly replace it before starting '${goalId}'.`,\n\t\t\t};\n\t\t}\n\t\treturn { ok: true, state: createGoalState({ goalId, userGoal, tokenBudget: action.tokenBudget, now }) };\n\t}\n\n\tif (!current) {\n\t\treturn { ok: false, error: \"No active goal. Use action 'start' before recording goal updates.\" };\n\t}\n\n\tif (!isGoalExecutionActive(current.status)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Goal '${current.goalId}' is ${current.status}. Lifecycle changes are owner/system controlled; use the /goal controls.`,\n\t\t};\n\t}\n\n\tif (action.action === \"increment\") {\n\t\tconst firstOpen = current.requirements.find((requirement) => requirement.status === \"open\");\n\t\tif (firstOpen) {\n\t\t\tconst used = new Set(current.requirements.flatMap((requirement) => requirement.evidenceIds));\n\t\t\tconst unused = current.evidence.filter((evidence) => !used.has(evidence.id)).map((evidence) => evidence.id);\n\t\t\tif (unused.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot increment goal: open requirement '${firstOpen.id}' has no unused evidence. Record evidence, then increment.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn applyGoalAction(\n\t\t\t\tcurrent,\n\t\t\t\t{ action: \"satisfy_requirement\", requirementId: firstOpen.id, evidenceIds: unused },\n\t\t\t\tnow,\n\t\t\t\toptions,\n\t\t\t);\n\t\t}\n\t\treturn applyGoalAction(current, { action: \"complete\" }, now, options);\n\t}\n\n\tconst event = toGoalEvent(current, action, now, options);\n\tif (!event.ok) return event;\n\treturn { ok: true, state: applyGoalEvent(current, event.event) };\n}\n\ntype ToGoalEventResult = { ok: true; event: GoalEvent } | GoalActionFailure;\n\nfunction toGoalEvent(\n\tstate: GoalState,\n\taction: GoalAction,\n\tnow: string,\n\toptions: ApplyGoalActionOptions | undefined,\n): ToGoalEventResult {\n\tswitch (action.action) {\n\t\tcase \"add_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst text = action.text.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!text) return { ok: false, error: \"add_requirement requires non-empty text.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirementId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (text.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `requirement text must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.requirements.length >= MAX_GOAL_REQUIREMENTS) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_REQUIREMENTS} requirements.` };\n\t\t\t}\n\t\t\tif (requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' already exists.` };\n\t\t\t}\n\t\t\tif (action.dependencies) {\n\t\t\t\tfor (const depId of action.dependencies) {\n\t\t\t\t\tif (!requirementExists(state, depId) && depId !== id) {\n\t\t\t\t\t\treturn { ok: false, error: `Dependency requirementId '${depId}' does not exist.` };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"add_requirement\", id, text, dependencies: action.dependencies, now } };\n\t\t}\n\t\tcase \"satisfy_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"satisfy_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tconst evidenceIds = action.evidenceIds ?? [];\n\t\t\tfor (const evidenceId of evidenceIds) {\n\t\t\t\tif (!evidenceExists(state, evidenceId)) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Unknown evidence '${evidenceId}'. Record it with action 'add_evidence' first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"satisfy_requirement\", id, evidenceIds: [...evidenceIds], now } };\n\t\t}\n\t\tcase \"block_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!id) return { ok: false, error: \"block_requirement requires a non-empty requirementId.\" };\n\t\t\tif (!reason) return { ok: false, error: \"block_requirement requires a non-empty reason.\" };\n\t\t\tif (!requirementExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_requirement\", id, blockedReason: reason, now } };\n\t\t}\n\t\tcase \"reopen_requirement\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tif (!id) return { ok: false, error: \"reopen_requirement requires a non-empty requirementId.\" };\n\t\t\tconst requirement = state.requirements.find((candidate) => candidate.id === id);\n\t\t\tif (!requirement) {\n\t\t\t\treturn { ok: false, error: `Unknown requirement '${id}'.` };\n\t\t\t}\n\t\t\tif (requirement.status !== \"blocked\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Requirement '${id}' is ${requirement.status}; only blocked requirements can be reopened.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"reopen_requirement\", id, now } };\n\t\t}\n\t\tcase \"dispatch_worker\": {\n\t\t\tconst id = action.requirementId.trim();\n\t\t\tconst instructions = action.instructions.trim();\n\t\t\tif (!id) return { ok: false, error: \"dispatch_worker requires a non-empty requirementId.\" };\n\t\t\tif (!instructions) return { ok: false, error: \"dispatch_worker requires non-empty instructions.\" };\n\t\t\tconst requirement = state.requirements.find((r) => r.id === id);\n\t\t\tif (!requirement) return { ok: false, error: `Requirement '${id}' does not exist.` };\n\t\t\tif (requirement.status !== \"open\") {\n\t\t\t\treturn { ok: false, error: `Requirement '${id}' is not open (status: ${requirement.status}).` };\n\t\t\t}\n\t\t\tif (requirement.dependencies) {\n\t\t\t\tconst unsatisfied = requirement.dependencies.filter((depId) => {\n\t\t\t\t\tconst dep = state.requirements.find((r) => r.id === depId);\n\t\t\t\t\treturn !dep || dep.status !== \"satisfied\";\n\t\t\t\t});\n\t\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot dispatch worker: dependencies not satisfied [${unsatisfied.join(\", \")}].`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"dispatch_worker\", id, instructions, laneId: action.laneId, now } };\n\t\t}\n\t\tcase \"add_evidence\": {\n\t\t\tconst id = action.evidenceId.trim();\n\t\t\tconst summary = action.summary.trim();\n\t\t\tif (!id) return { ok: false, error: \"add_evidence requires a non-empty evidenceId.\" };\n\t\t\tif (!summary) return { ok: false, error: \"add_evidence requires a non-empty summary.\" };\n\t\t\tif (id.length > MAX_GOAL_ID_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidenceId must be at most ${MAX_GOAL_ID_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (summary.length > MAX_GOAL_LEDGER_TEXT_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence summary must be at most ${MAX_GOAL_LEDGER_TEXT_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif ((action.uri?.trim().length ?? 0) > MAX_GOAL_URI_LENGTH) {\n\t\t\t\treturn { ok: false, error: `evidence uri must be at most ${MAX_GOAL_URI_LENGTH} characters.` };\n\t\t\t}\n\t\t\tif (state.evidence.length >= MAX_GOAL_EVIDENCE) {\n\t\t\t\treturn { ok: false, error: `Goal already has the maximum ${MAX_GOAL_EVIDENCE} evidence entries.` };\n\t\t\t}\n\t\t\tif (evidenceExists(state, id)) {\n\t\t\t\treturn { ok: false, error: `Evidence '${id}' already exists.` };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: {\n\t\t\t\t\ttype: \"add_evidence\",\n\t\t\t\t\tid,\n\t\t\t\t\tkind: action.kind,\n\t\t\t\t\tsummary,\n\t\t\t\t\turi: action.uri?.trim() || undefined,\n\t\t\t\t\tverified: action.verified,\n\t\t\t\t\tnow,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tcase \"progress\":\n\t\t\treturn { ok: true, event: { type: \"progress\", now } };\n\t\tcase \"no_progress\":\n\t\t\treturn { ok: true, event: { type: \"no_progress\", now } };\n\t\tcase \"increment\":\n\t\t\treturn { ok: false, error: \"increment must be expanded by applyGoalAction.\" };\n\t\tcase \"complete\": {\n\t\t\tconst unsatisfied = state.requirements.filter((requirement) => requirement.status !== \"satisfied\");\n\t\t\tif (unsatisfied.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: ${unsatisfied.length} requirement(s) not satisfied (${unsatisfied\n\t\t\t\t\t\t.map((requirement) => requirement.id)\n\t\t\t\t\t\t.join(\", \")}).`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;\n\t\t\tconst linkedOpenSteps = findLinkedOpenTaskSteps(state, options?.openTaskSteps);\n\t\t\tif (linkedOpenSteps.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: open task_steps still reference this goal (${linkedOpenSteps.join(\", \")}). Update them via task_steps first.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pendingToolTasks = findNonterminalCitedToolTasks(state, options?.backgroundToolTasks);\n\t\t\tif (pendingToolTasks.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: cited tool_task(s) are not complete (${pendingToolTasks.join(\", \")}). Wait once via tool_task, then record the terminal result.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst activePipeline = options?.activePipeline;\n\t\t\tif (activePipeline && activePipeline.status === \"active\") {\n\t\t\t\tconst joined = Boolean(activePipeline.goalId && activePipeline.goalId === state.goalId);\n\t\t\t\tif (joined) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `Cannot complete goal: pipeline '${activePipeline.pipelineName}' run '${activePipeline.runId}' is still active. Increment or abandon it first.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst unprovenRequirementIds = getUnprovenGoalRequirementIds(state);\n\t\t\tif (requireVerifiedEvidence && unprovenRequirementIds.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot complete goal: requirement(s) lack verified evidence (${unprovenRequirementIds.join(\", \")}). Record verified or user-confirmed evidence and cite it in satisfy_requirement.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tevent: { type: \"complete_goal\", acceptanceOverride: !requireVerifiedEvidence, now },\n\t\t\t};\n\t\t}\n\t\tcase \"block_goal\": {\n\t\t\tconst reason = action.reason.trim();\n\t\t\tif (!reason) return { ok: false, error: \"block_goal requires a non-empty reason.\" };\n\t\t\tif (state.stallTurns < MIN_AGENT_BLOCK_STALL_TURNS) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `Cannot block goal: the host has recorded ${state.stallTurns}/${MIN_AGENT_BLOCK_STALL_TURNS} consecutive no-progress goal turns. Keep the goal active until the same blocker has persisted for at least three consecutive goal turns.`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true, event: { type: \"block_goal\", reason, now } };\n\t\t}\n\t\tdefault:\n\t\t\treturn { ok: false, error: \"Unknown goal action.\" };\n\t}\n}\n\n/**\n * Complete a goal on explicit user authority, even when requirements remain open or\n * blocked. Agent-facing `complete` stays evidence-gated; this path is reserved for\n * direct user lifecycle controls.\n */\nexport function completeGoalManually(current: GoalState | undefined, now: string): GoalActionResult {\n\tif (!current) {\n\t\treturn { ok: false, error: \"No goal exists to complete.\" };\n\t}\n\tif (current.status === \"completed\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is already completed.` };\n\t}\n\tif (current.status === \"cancelled\") {\n\t\treturn { ok: false, error: `Goal '${current.goalId}' is cancelled; start or override with a new goal.` };\n\t}\n\treturn { ok: true, state: applyGoalEvent(current, { type: \"complete_goal_manually\", now }) };\n}\n\n/** Render a compact human-readable summary of the ledger after an action. */\nexport function summarizeGoalState(\n\tstate: GoalState,\n\toptions?: { action?: GoalAction; openTaskSteps?: readonly OpenTaskStepRef[] },\n): string {\n\tconst lines = [formatGoalRecord(projectGoalRecord(state))];\n\tif (state.requirements.length > 0) {\n\t\tconst openIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"open\")\n\t\t\t.slice(0, 20)\n\t\t\t.map((requirement) => requirement.id);\n\t\tlines.push(\n\t\t\t`Legacy ledger: ${state.requirements.length} requirements, ${state.evidence.length} evidence${openIds.length > 0 ? `; open: ${openIds.join(\", \")}` : \"\"}.`,\n\t\t);\n\t}\n\tif (options?.action) {\n\t\tlines.push(...buildGoalTaskCrossVisibilityNudges(options.action, state, options.openTaskSteps));\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/**\n * Read-only goal⇄task cross-visibility (bounded slice — no shared state machine).\n *\n * `goal-tool-core` never reads or mutates task state itself (it stays pure); callers that DO\n * have access to the branch-scoped open task steps (e.g. via `buildGoalRuntimeSnapshot`) may\n * pass them through here to surface a nudge in the tool response when an open task_steps step is\n * explicitly linked to, or conservatively appears to reference, a requirement the agent just\n * satisfied or completed. Task state is never written from goal code — this only reads an\n * already-resolved, caller-supplied summary.\n */\nexport interface OpenTaskStepRef {\n\tid: string;\n\tcontent: string;\n\trequirementIds?: readonly string[];\n\tevidence?: readonly string[];\n\tpipelineRunId?: string;\n\tpipelineStageId?: string;\n}\n\nfunction findLinkedOpenTaskSteps(state: GoalState, openTaskSteps: readonly OpenTaskStepRef[] | undefined): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\treturn openTaskSteps\n\t\t.filter((step) => state.requirements.some((requirement) => taskStepReferencesRequirement(step, requirement)))\n\t\t.map((step) => step.id);\n}\n\nfunction findNonterminalCitedToolTasks(\n\tstate: GoalState,\n\tbackgroundToolTasks: readonly BackgroundToolTaskRef[] | undefined,\n): string[] {\n\tif (!backgroundToolTasks || backgroundToolTasks.length === 0) return [];\n\tconst pending = new Set<string>();\n\tfor (const evidence of state.evidence) {\n\t\tif (evidence.kind !== \"tool\" || !evidence.uri) continue;\n\t\tconst task = findBackgroundToolTask(backgroundToolTasks, evidence.uri);\n\t\tif (task && task.status !== \"completed\") pending.add(task.taskId);\n\t}\n\treturn [...pending];\n}\n\n/**\n * Nudge lines for open task steps that reference any of `requirementIds` (deduped per\n * requirement, one line naming every referencing step). Empty when there is nothing to say.\n */\nexport function findRequirementCrossReferenceNudges(\n\tstate: GoalState,\n\trequirementIds: readonly string[],\n\topenTaskSteps: readonly OpenTaskStepRef[],\n): string[] {\n\tif (openTaskSteps.length === 0 || requirementIds.length === 0) return [];\n\tconst nudges: string[] = [];\n\tfor (const requirementId of requirementIds) {\n\t\tconst requirement = state.requirements.find((candidate) => candidate.id === requirementId);\n\t\tif (!requirement) continue;\n\t\tconst referencing = openTaskSteps.filter((step) => taskStepReferencesRequirement(step, requirement));\n\t\tif (referencing.length === 0) continue;\n\t\tconst stepList = referencing.map((step) => step.id).join(\", \");\n\t\tnudges.push(\n\t\t\t`Note: open task step(s) ${stepList} appear to reference satisfied requirement '${requirement.id}' -- consider updating them via task_steps once covered.`,\n\t\t);\n\t}\n\treturn nudges;\n}\n\n/**\n * After 'satisfy_requirement' or 'complete', nudge lines for linked open task steps. Returns `[]`\n * for every other action, or when\n * `openTaskSteps` was not supplied (the default -- backward compatible, no behavior change for\n * callers that do not pass task-step context).\n */\nexport function buildGoalTaskCrossVisibilityNudges(\n\taction: GoalAction,\n\tstate: GoalState,\n\topenTaskSteps: readonly OpenTaskStepRef[] | undefined,\n): string[] {\n\tif (!openTaskSteps || openTaskSteps.length === 0) return [];\n\tif (action.action === \"satisfy_requirement\") {\n\t\treturn findRequirementCrossReferenceNudges(state, [action.requirementId.trim()], openTaskSteps);\n\t}\n\tif (action.action === \"complete\") {\n\t\tconst satisfiedIds = state.requirements\n\t\t\t.filter((requirement) => requirement.status === \"satisfied\")\n\t\t\t.map((requirement) => requirement.id);\n\t\treturn findRequirementCrossReferenceNudges(state, satisfiedIds, openTaskSteps);\n\t}\n\treturn [];\n}\n"]}
|
|
@@ -617,8 +617,8 @@ export class ModelRouterController {
|
|
|
617
617
|
agent.state.tools = swappedTools;
|
|
618
618
|
}
|
|
619
619
|
}
|
|
620
|
-
// The routed prompt follows
|
|
621
|
-
//
|
|
620
|
+
// The routed prompt follows the routed tool surface and keeps provider-neutral delegation
|
|
621
|
+
// guidance whenever delegate remains active, including same-model thinking overrides.
|
|
622
622
|
// Per-turn only; a live extension override is preserved rather than silently replaced.
|
|
623
623
|
if (agent.state.systemPrompt === this.deps.getBaseSystemPrompt()) {
|
|
624
624
|
swappedSystemPrompt = this.deps.buildSystemPromptForToolNames(agent.state.tools.map((tool) => tool.name));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-router-controller.js","sourceRoot":"","sources":["../../src/core/model-router-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;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I,eAAe,IAAI,iBAAiB,EAAE,CAAC;YAC1C,0BAA0B,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,EAAE,iBAAiB,CAAC,CAAC;YAC7E,8EAA8E;YAC9E,2FAA2F;YAC3F,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAAC;gBAC/B,IAAI,EAAE,8BAA8B,CAAC,aAAa;gBAClD,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;gBACnC,OAAO,EAAE;oBACR,IAAI,EAAE,iBAAiB,CAAC,KAAK,CAAC,IAAI;oBAClC,IAAI,EAAE,iBAAiB,CAAC,KAAK,CAAC,IAAI;oBAClC,UAAU,EAAE,iBAAiB,CAAC,KAAK,CAAC,UAAU;oBAC9C,UAAU,EAAE,iBAAiB,CAAC,KAAK,CAAC,UAAU;oBAC9C,OAAO,EAAE,iBAAiB,CAAC,OAAO;iBAClC;aACD,CAAC,CAAC;QACJ,CAAC;QAED,IAAI,WAAW,EAAE,CAAC;YACjB,MAAM,WAAW,CAAC;QACnB,CAAC;IACF,CAAC;CACD","sourcesContent":["/**\n * Model-router turn routing: the session's per-turn model-selection subsystem — the regex/executor\n * route resolver, the optional bounded routing judge, the executor lane (Level-0 toolkit direct hit\n * + speculative brain-refined retry), the per-tier thinking/tool-surface swap around a routed turn,\n * the cheap-research-turn session buffer with mutating-tool escalation to an expensive retry, and\n * the router status/diagnostics report.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the transient per-turn\n * route state — the active intent/route, the cheap-turn session buffer, the escalation-requested and\n * retry-in-flight flags — and the sticky last-decision/last-skip-reason/last-intent used by the\n * status report. Everything else it needs — the live agent + its state, the current model, the\n * session/settings managers, the model registry, the agent dir, the reflection abort signal, the\n * base system prompt, the isolated-completion primitive, spawned-usage accounting, the event/telemetry\n * emitters, and the recently-extracted BackgroundLaneController (resolveLaneModel) / ContextPipeline\n * (resolveCurationModelIfFit) collaborators — is reached through narrow deps accessors rather than the\n * whole AgentSession.\n *\n * Drive-path boundary (deliberate): the actual agent.prompt()/continue() loop belongs to the\n * session-owned ForegroundRecoveryController; this controller's parallel routed drive path\n * ({@link runRoutedTurn}) owns only route decision/escalation/tier bookkeeping and delegates every\n * agent turn through {@link ModelRouterControllerDeps.runAgentPrompt}, so the drive loop is never duplicated. The\n * host keeps a one-line delegation at each call-in: the routing prep + routed-turn entry in\n * _promptUnserialized, the beforeToolCall MUTATION escalation branch ({@link\n * maybeEscalateToolCall}), the tool-name-agnostic VALIDATION-FAILURE escalation branch for cloud\n * models ({@link requestValidationFailureEscalation} — de-conflated from the mutation gate; see the\n * capability-gate spine doctrine, which routes local/managed models to an evidence-gated\n * native→phone auto-probe on AgentSession instead), the message_end cheap-turn buffering ({@link\n * captureSessionMessage}), the retry-event suppression ({@link isRetryInFlight}), the public\n * getModelRouterStatus / autonomy-telemetry reads, and the tier resolution's consultation of the\n * persisted `/toolprobe` verdict for local/managed tier models ({@link\n * ModelRouterControllerDeps.getToolProbeVerdict}).\n */\n\nimport type { Agent, AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, Message, Model, Usage } from \"@caupulican/pi-ai\";\nimport { clampThinkingLevel, modelsAreEqual } from \"@caupulican/pi-ai/models\";\nimport type {\n\tAgentSessionEvent,\n\tIsolatedCompletionOptions,\n\tIsolatedCompletionResult,\n} from \"./agent-session-contracts.ts\";\nimport type { RouteDecision } from \"./autonomy/contracts.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport { latestUserPromptText } from \"./context/message-text.ts\";\nimport { runIsolatedTextCompletion } from \"./isolated-text-completion.ts\";\nimport { deriveModelCapabilityProfile, filterToolNamesForCapability } from \"./model-capability.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { collectModelRouterConfigDiagnostics } from \"./model-router/config-diagnostics.ts\";\nimport { classifyExecutorTurn } from \"./model-router/executor-route.ts\";\nimport {\n\tevaluateSurfaceFitness,\n\ttype FitnessGatedSurface,\n\ttype FitnessGateVerdict,\n} from \"./model-router/fitness-gate.ts\";\nimport { classifyModelRouterRoute, type ModelRouterIntent } from \"./model-router/intent-classifier.ts\";\nimport { ROUTE_JUDGE_MAX_OUTPUT_TOKENS, runRouteJudge } from \"./model-router/route-judge.ts\";\nimport {\n\tbufferModelRouterSessionCustomMessage,\n\tbufferModelRouterSessionMessage,\n\tcreateModelRouterSessionBuffer,\n\tflushModelRouterSessionBuffer,\n\ttype ModelRouterSessionBuffer,\n} from \"./model-router/session-buffer.ts\";\nimport {\n\tformatModelRouterStatus,\n\tgetRecentModelRouterDecisions,\n\tMODEL_ROUTER_DECISION_CUSTOM_TYPE,\n\ttype ModelRouterDecisionStatus,\n\ttype ModelRouterFailoverStatus,\n\ttype ModelRouterFitnessStatuses,\n} from \"./model-router/status.ts\";\nimport { isLocalOrManagedRouterModel, shouldEscalateModelRouterTool } from \"./model-router/tool-escalation.ts\";\nimport type { ModelToolProbeVerdict } from \"./models/adaptation-store.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { reportSpawnedUsage } from \"./spawned-usage.ts\";\nimport { runReflexInterpreterCompletion } from \"./toolkit/reflex-interpreter.ts\";\n\n/** Canonical `provider/id` label for a routed/resolved model, as it appears in decisions and status. */\nexport function formatModelRouterModel(model: Model<Api>): string {\n\treturn `${model.provider}/${model.id}`;\n}\n\nconst ROUTE_JUDGE_STATIC_FAST_PATH_REASON_CODES = new Set([\n\t\"empty_prompt\",\n\t\"read_only_question\",\n\t\"release_or_publish\",\n\t\"security_or_auth\",\n\t\"destructive_or_git_history\",\n\t\"settings_or_self_modification\",\n\t\"architecture_or_ambiguous\",\n]);\n\nfunction shouldSkipRouteJudgeForStaticDecision(decision: RouteDecision): boolean {\n\treturn ROUTE_JUDGE_STATIC_FAST_PATH_REASON_CODES.has(decision.reasonCode);\n}\n\nfunction withJudgeUnavailableFallback(decision: RouteDecision, reason: string): RouteDecision {\n\treturn {\n\t\t...decision,\n\t\treasonCode: \"judge_unavailable_fallback\",\n\t\treasons: [...decision.reasons, reason],\n\t};\n}\n\nfunction persistModelRouterDecision(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\tdecision: ModelRouterDecisionStatus,\n): void {\n\tsessionManager.appendCustomEntry(MODEL_ROUTER_DECISION_CUSTOM_TYPE, decision);\n}\n\nexport interface ModelRouterControllerDeps {\n\t/** Live agent — the controller reads/writes agent.state.{model,thinkingLevel,tools,systemPrompt,messages}\n\t * for the per-turn tier swap and aborts it on a mutating-tool escalation. */\n\tgetAgent(): Agent;\n\t/** Current session model, used to decide whether a routed turn actually swaps the model. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Router/executor/judge/thinking settings + capability mode (all opt-in gates). */\n\tgetSettingsManager(): SettingsManager;\n\t/** Session log: routed-turn message buffering/persistence, decision persistence, recent-decision status. */\n\tgetSessionManager(): SessionManager;\n\t/** Resolves configured route/judge/executor model patterns against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Session-scoped provider/model quota exhaustion guard. */\n\tisModelExhausted(model: Model<Api>): boolean;\n\t/** Status snapshot for exhausted models and the last failover notice. */\n\tgetFailoverStatus(): ModelRouterFailoverStatus;\n\t/** Root dir the host-keyed {@link FitnessStore} lives under (executor tool-call fitness gate). */\n\tgetAgentDir(): string;\n\t/** Aborts the judge's bounded completion when the session is disposed. */\n\tgetReflectionSignal(): AbortSignal;\n\t/** Base (extension-free) system prompt — the tier swap only sheds tools when the turn is on it. */\n\tgetBaseSystemPrompt(): string;\n\t/** The session-owned foreground drive loop; the routed path delegates every turn here. */\n\trunAgentPrompt(messages: AgentMessage | AgentMessage[]): Promise<void>;\n\t/** Rebuilds the system prompt for a filtered tool surface (routed-model capability shedding). */\n\tbuildSystemPromptForToolNames(toolNames: string[]): string;\n\t/** Re-resolves the restored model against the registry after a routed turn (provider override safety). */\n\trefreshCurrentModelFromRegistry(): void;\n\t/** One-shot, tool-less LLM call — the routing judge and the executor reflex-brain warmup ride this. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\t/** Rolls judge/brain spend into spawned-usage accounting. `reportId` is REQUIRED: every\n\t * caller derives a stable id from the work unit's identity so a retry cannot double-count. */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts: { label?: string; sourceSessionId?: string; reportId: string },\n\t): string | undefined;\n\t/** Session event stream (executor-miss warning). */\n\temit(event: AgentSessionEvent): void;\n\t/** Autonomy telemetry stream (one route-decision event per user-facing routed turn). */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Resolves the judge model pattern via {@link BackgroundLaneController}. */\n\tresolveLaneModel(pattern: string): Model<Api> | undefined;\n\t/** Fitness-gated reflex-brain model via {@link ContextPipeline} (executor speculative refinement). */\n\tresolveCurationModelIfFit(): Model<Api> | undefined;\n\t/** Persisted `/toolprobe` verdict for this model (native / text-protocol / none), or undefined\n\t * when never probed. Tier-resolution's consultation reads this ONLY for local/managed models\n\t * ({@link isLocalOrManagedRouterModel}); cloud models never call it. */\n\tgetToolProbeVerdict(model: Model<Api>): ModelToolProbeVerdict | undefined;\n}\n\n/**\n * Owns the model-router turn routing extracted from {@link AgentSession}. See the module header for the\n * drive-path boundary that keeps the agent.prompt()/continue() loop in its foreground lifecycle owner.\n */\nexport class ModelRouterController {\n\t/** Active model-router intent for the current transient routed turn, if any. */\n\tprivate _activeModelRouterIntent?: ModelRouterIntent;\n\tprivate _activeModelRouterRoute?: RouteDecision;\n\tprivate _modelRouterSessionBuffer?: ModelRouterSessionBuffer;\n\tprivate _modelRouterEscalationRequested = false;\n\tprivate _isModelRouterRetry = false;\n\tprivate _lastModelRouterDecision?: ModelRouterDecisionStatus;\n\tprivate _lastModelRouterSkipReason?: string;\n\tprivate _lastModelRouterIntent?: ModelRouterIntent;\n\n\tprivate readonly deps: ModelRouterControllerDeps;\n\n\tconstructor(deps: ModelRouterControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** True while the escalation retry turn is running, so the host can suppress its duplicate prompt events. */\n\tisRetryInFlight(): boolean {\n\t\treturn this._isModelRouterRetry;\n\t}\n\n\t/** Latest completed route decision (sticky), for the autonomy telemetry snapshot. */\n\tgetLastDecision(): ModelRouterDecisionStatus | undefined {\n\t\treturn this._lastModelRouterDecision;\n\t}\n\n\t/**\n\t * beforeToolCall escalation gate: a cheap research turn that reaches for a mutating tool aborts the\n\t * turn and requests a retry on the expensive model. Returns the block result the host hook forwards,\n\t * or undefined when no escalation is required.\n\t */\n\tmaybeEscalateToolCall(toolName: string, args: unknown): { block: true; reason: string } | undefined {\n\t\tif (\n\t\t\tthis._activeModelRouterRoute &&\n\t\t\tshouldEscalateModelRouterTool({\n\t\t\t\ttier: this._activeModelRouterRoute.tier,\n\t\t\t\ttoolName,\n\t\t\t\targs,\n\t\t\t\treasonCode: this._activeModelRouterRoute.reasonCode,\n\t\t\t})\n\t\t) {\n\t\t\tthis._modelRouterEscalationRequested = true;\n\t\t\tthis.deps.getAgent().abort();\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason:\n\t\t\t\t\t\"Model router escalation required: a cheap research turn attempted a mutating tool. Retry the turn on the configured expensive model.\",\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Tool-name-agnostic validation-failure escalation gate, called from\n\t * AgentSession's onToolValidationEscalation handler for a CLOUD model only — see the\n\t * capability-gate-spine doctrine (local/managed models never reach this method; they trigger\n\t * the evidence-gated native→phone auto-probe instead). Unlike {@link maybeEscalateToolCall} (the\n\t * beforeToolCall MUTATION gate, still governed by `shouldEscalateModelRouterTool`/\n\t * READ_ONLY_TOOL_NAMES — a legitimate, unrelated mutation-blast-radius policy), \"the model\n\t * repeatedly cannot construct valid arguments for this tool\" is evidence about the MODEL's\n\t * capability, not about the tool's mutation status, so a read-only tool's repeated validation\n\t * failure now escalates a cheap routed turn exactly like a mutating tool's would — takes no\n\t * tool-name/args input at all (unlike maybeEscalateToolCall), because every repeated validation\n\t * failure escalates regardless of which tool or model triggered it. No-op outside an active\n\t * cheap-tier routed turn, same scoping as maybeEscalateToolCall.\n\t */\n\trequestValidationFailureEscalation(): void {\n\t\tif (this._activeModelRouterRoute?.tier !== \"cheap\") return;\n\t\tthis._modelRouterEscalationRequested = true;\n\t\tthis.deps.getAgent().abort();\n\t}\n\n\t/**\n\t * message_end hook: while a cheap routed turn is buffering, capture its messages into the session\n\t * buffer instead of persisting them (they are flushed on success or discarded on escalation).\n\t * Returns true when the message was buffered, so the host skips its own persistence.\n\t */\n\tcaptureSessionMessage(message: AgentMessage): boolean {\n\t\tconst modelRouterBuffer = this._modelRouterSessionBuffer;\n\t\tif (!modelRouterBuffer) return false;\n\t\tif (message.role === \"custom\") {\n\t\t\tbufferModelRouterSessionCustomMessage(modelRouterBuffer, message);\n\t\t\treturn true;\n\t\t}\n\t\tif (message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tbufferModelRouterSessionMessage(modelRouterBuffer, message as Message);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate _isModelAvailableAndAuthed(pattern: string): boolean {\n\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) return false;\n\t\treturn this.deps.getModelRegistry().hasConfiguredAuth(resolved.model);\n\t}\n\n\tprivate _evaluateModelFitness(surface: FitnessGatedSurface, model: Model<Api>): FitnessGateVerdict {\n\t\tconst fitness = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === formatModelRouterModel(model));\n\t\treturn evaluateSurfaceFitness(surface, fitness?.report);\n\t}\n\n\tprivate _formatFitnessFailure(verdict: Exclude<FitnessGateVerdict, { fit: true }>): string {\n\t\treturn verdict.reason === \"unprobed\" ? \"unprobed\" : `${verdict.lane} ${verdict.succeeded}/${verdict.total}`;\n\t}\n\n\tprivate _routerSurfaceForTier(tier: \"cheap\" | \"medium\" | \"expensive\"): FitnessGatedSurface {\n\t\treturn tier === \"cheap\" ? \"router_cheap\" : tier === \"medium\" ? \"router_medium\" : \"router_expensive\";\n\t}\n\n\tprivate _getRouterTierFitnessStatuses(): ModelRouterFitnessStatuses {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst statuses: ModelRouterFitnessStatuses = {};\n\t\tfor (const tier of [\"cheap\", \"medium\", \"expensive\"] as const) {\n\t\t\tconst pattern =\n\t\t\t\ttier === \"cheap\" ? settings.cheapModel : tier === \"medium\" ? settings.mediumModel : settings.expensiveModel;\n\t\t\tif (!pattern) continue;\n\t\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (!resolved.model || !this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) continue;\n\t\t\tconst verdict = this._evaluateModelFitness(this._routerSurfaceForTier(tier), resolved.model);\n\t\t\tstatuses[tier] = verdict.fit\n\t\t\t\t? { status: verdict.probed ? \"fit\" : \"unprobed\" }\n\t\t\t\t: verdict.reason === \"unprobed\"\n\t\t\t\t\t? { status: \"unprobed\" }\n\t\t\t\t\t: { status: \"unfit\", lane: verdict.lane, succeeded: verdict.succeeded, total: verdict.total };\n\t\t}\n\t\treturn statuses;\n\t}\n\n\tprivate _resolveExpensiveFallbackRoute(\n\t\tdecision: RouteDecision,\n\t\treasonCode: string,\n\t\treason: string,\n\t): { decision: RouteDecision; model: Model<Api> } | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst expensivePattern = settings.expensiveModel;\n\t\tif (!expensivePattern || !this._isModelAvailableAndAuthed(expensivePattern)) return undefined;\n\t\tconst resolvedExpensive = resolveCliModel({\n\t\t\tcliModel: expensivePattern,\n\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t});\n\t\tif (!resolvedExpensive.model) return undefined;\n\t\tif (this.deps.isModelExhausted(resolvedExpensive.model)) {\n\t\t\tthis._lastModelRouterSkipReason = \"expensive model exhausted: quota\";\n\t\t\treturn undefined;\n\t\t}\n\t\tif (settings.fitnessGate) {\n\t\t\tconst verdict = this._evaluateModelFitness(\"router_expensive\", resolvedExpensive.model);\n\t\t\tif (!verdict.fit) {\n\t\t\t\tthis._lastModelRouterSkipReason = `expensive model unfit: ${this._formatFitnessFailure(verdict)} (fitness gate)`;\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t\tdecision.fallbackFrom = \"medium\";\n\t\tdecision.tier = \"expensive\";\n\t\tdecision.reasonCode = reasonCode;\n\t\tdecision.reasons = [...decision.reasons, reason];\n\t\tdecision.model = formatModelRouterModel(resolvedExpensive.model);\n\t\tthis._lastModelRouterSkipReason = undefined;\n\t\treturn { decision, model: resolvedExpensive.model };\n\t}\n\n\tprivate _resolveExecutorRoute(\n\t\tprompt: string,\n\t\texecutorPattern: string | undefined,\n\t): { decision: RouteDecision; model: Model<Api> } | undefined {\n\t\tif (!executorPattern) return undefined;\n\t\ttry {\n\t\t\tconst verdict = classifyExecutorTurn(prompt, this.deps.getSettingsManager().getToolkitScripts());\n\t\t\tif (!verdict.execute) return undefined;\n\t\t\tconst resolved = resolveCliModel({ cliModel: executorPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (!resolved.model || !this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) return undefined;\n\t\t\t// Fitness gate: the executor must have PROVEN tool-calling on this host (same\n\t\t\t// canonical-ref discipline as the curation gate).\n\t\t\tif (!this._evaluateModelFitness(\"executor\", resolved.model).fit) return undefined;\n\t\t\tthis._lastModelRouterIntent = \"research\";\n\t\t\treturn {\n\t\t\t\tdecision: {\n\t\t\t\t\ttier: \"cheap\",\n\t\t\t\t\trisk: \"scoped-write\",\n\t\t\t\t\tconfidence: 1,\n\t\t\t\t\treasonCode: \"executor_direct\",\n\t\t\t\t\treasons: [`Executor lane: Level-0 direct hit on toolkit script \"${verdict.scriptName}\"`],\n\t\t\t\t},\n\t\t\t\tmodel: resolved.model,\n\t\t\t};\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/** True if a run_toolkit_script tool result since `fromIndex` actually EXECUTED (not error/ambiguous). */\n\tprivate _executorTurnExecutedScript(fromIndex: number): boolean {\n\t\tfor (const message of this.deps.getAgent().state.messages.slice(fromIndex)) {\n\t\t\tif ((message as { role?: string }).role !== \"toolResult\") continue;\n\t\t\tif ((message as { toolName?: string }).toolName !== \"run_toolkit_script\") continue;\n\t\t\tif ((message as { isError?: boolean }).isError === true) continue;\n\t\t\tconst outcome = (message as { details?: { outcome?: unknown } }).details?.outcome;\n\t\t\tif (outcome === \"executed\") return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Ask the reflex brain to refine the last user request into an explicit toolkit instruction. */\n\tprivate async _buildExecutorRefinedPrompt(messages: AgentMessage | AgentMessage[]): Promise<string | undefined> {\n\t\ttry {\n\t\t\tconst model = this.deps.resolveCurationModelIfFit();\n\t\t\tif (!model) return undefined;\n\t\t\tconst list = Array.isArray(messages) ? messages : [messages];\n\t\t\tconst request = latestUserPromptText(list);\n\t\t\tif (!request) return undefined;\n\t\t\tconst scripts = this.deps.getSettingsManager().getToolkitScripts();\n\t\t\tconst plan = await runReflexInterpreterCompletion({\n\t\t\t\trequest,\n\t\t\t\tscripts,\n\t\t\t\tmodel,\n\t\t\t\tlaneKind: \"executor\",\n\t\t\t\tusageKind: \"executor-brain\",\n\t\t\t\tusageLabel: \"executor-brain-warmup\",\n\t\t\t\tsessionId: this.deps.getSessionManager().getSessionId(),\n\t\t\t\tcompletionRunner: this.deps,\n\t\t\t\tusageReporter: this.deps,\n\t\t\t});\n\t\t\tif (!plan || plan.script === \"none\") return undefined;\n\t\t\tconst argHint = plan.args.length > 0 ? ` with args ${JSON.stringify(plan.args)}` : \"\";\n\t\t\treturn `Run the toolkit script \"${plan.script}\"${argHint} using run_toolkit_script, then report its result exactly.`;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate _resolveModelRouterTurnRoute(prompt: string): { decision: RouteDecision; model: Model<Api> } | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (!settings.enabled) {\n\t\t\tthis._lastModelRouterSkipReason = \"disabled\";\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Executor lane: a Level-0 DIRECT toolkit hit on a command-shaped prompt routes the\n\t\t// whole turn to the configured local executor (tool-call-fitness-gated) instead of\n\t\t// spending the frontier model on a one-tool reflex. Ambiguity never routes here — it\n\t\t// stays with the big model and the reflex brain. Deterministic, so the judge is skipped.\n\t\tconst executorRoute = this._resolveExecutorRoute(prompt, settings.executorModel);\n\t\tif (executorRoute) return executorRoute;\n\n\t\tconst decision = classifyModelRouterRoute(prompt);\n\t\tthis._lastModelRouterIntent = decision.tier === \"cheap\" ? \"research\" : \"modify\";\n\n\t\t// Learning tier must not be selected for normal user prompts\n\t\tif (decision.tier === \"learning\") {\n\t\t\tthis._lastModelRouterSkipReason = \"learning tier not supported for user prompts\";\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst modelPattern =\n\t\t\tsettings[\n\t\t\t\tdecision.tier === \"cheap\" ? \"cheapModel\" : decision.tier === \"medium\" ? \"mediumModel\" : \"expensiveModel\"\n\t\t\t];\n\t\tconst label =\n\t\t\tdecision.tier === \"cheap\" ? \"cheap model\" : decision.tier === \"medium\" ? \"medium model\" : \"expensive model\";\n\n\t\tif (decision.tier === \"medium\" && (!modelPattern || !this._isModelAvailableAndAuthed(modelPattern))) {\n\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\tdecision,\n\t\t\t\t\"medium_unavailable_fallback_expensive\",\n\t\t\t\t\"Medium model is unavailable, falling back to expensive model\",\n\t\t\t);\n\t\t\tif (fallback) return fallback;\n\t\t\tthis._lastModelRouterSkipReason ??= \"medium model and expensive fallback are unavailable\";\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (!modelPattern) {\n\t\t\tthis._lastModelRouterSkipReason = `${label} unset`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst resolved = resolveCliModel({ cliModel: modelPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) {\n\t\t\tthis._lastModelRouterSkipReason = `${label} unresolved: ${modelPattern}`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst resolvedName = formatModelRouterModel(resolved.model);\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\tthis._lastModelRouterSkipReason = `${label} missing auth: ${resolvedName}`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (this.deps.isModelExhausted(resolved.model)) {\n\t\t\tif (decision.tier === \"medium\") {\n\t\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\t\tdecision,\n\t\t\t\t\t\"medium_exhausted_fallback_expensive\",\n\t\t\t\t\t\"Medium model exhausted: quota; falling back to expensive model\",\n\t\t\t\t);\n\t\t\t\tif (fallback) return fallback;\n\t\t\t}\n\t\t\tthis._lastModelRouterSkipReason = `${decision.tier} model exhausted: quota`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// For a LOCAL/MANAGED tier model (never cloud — isLocalOrManagedRouterModel), honor a\n\t\t// persisted \"no working tool-call path\" probe verdict. This is an ALWAYS-ON doctrine gate,\n\t\t// deliberately not behind the opt-in `fitnessGate` setting below (cloud fitness gating stays\n\t\t// opt-in; this local/managed check is unconditional, matching the auto-probe that writes\n\t\t// the verdict). \"native\"/\"text-protocol\"/unprobed all fall through unchanged: native wins\n\t\t// when it works, the shared model-tool-protocol resolver engages the calibrated text dialect,\n\t\t// and an unprobed model routes native-first (the evidence loop, not a speculative pre-block).\n\t\tif (isLocalOrManagedRouterModel(resolved.model) && this.deps.getToolProbeVerdict(resolved.model) === \"none\") {\n\t\t\tif (decision.tier === \"medium\") {\n\t\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\t\tdecision,\n\t\t\t\t\t\"medium_no_tool_path_fallback_expensive\",\n\t\t\t\t\t\"Medium model has no working tool-call path (native and text-protocol probe both failed); falling back to expensive model\",\n\t\t\t\t);\n\t\t\t\tif (fallback) return fallback;\n\t\t\t}\n\t\t\tthis._lastModelRouterSkipReason = `${decision.tier} model has no working tool-call path (native and text-protocol probe both failed)`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (settings.fitnessGate) {\n\t\t\tconst verdict = this._evaluateModelFitness(this._routerSurfaceForTier(decision.tier), resolved.model);\n\t\t\tif (!verdict.fit) {\n\t\t\t\tif (decision.tier === \"medium\") {\n\t\t\t\t\tconst failure = this._formatFitnessFailure(verdict);\n\t\t\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\t\t\tdecision,\n\t\t\t\t\t\t\"medium_unfit_fallback_expensive\",\n\t\t\t\t\t\t`Medium model is unfit (${failure}); falling back to expensive model`,\n\t\t\t\t\t);\n\t\t\t\t\tif (fallback) return fallback;\n\t\t\t\t}\n\t\t\t\tthis._lastModelRouterSkipReason = `${decision.tier} model unfit: ${this._formatFitnessFailure(verdict)} (fitness gate)`;\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tthis._lastModelRouterSkipReason = undefined;\n\t\tdecision.model = resolvedName;\n\t\treturn { decision, model: resolved.model };\n\t}\n\n\tprivate _resolveModelRouterModelForIntent(intent: ModelRouterIntent): Model<Api> | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst modelPattern = intent === \"research\" ? settings.cheapModel : settings.expensiveModel;\n\t\tif (!modelPattern) return undefined;\n\t\tconst resolved = resolveCliModel({ cliModel: modelPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) return undefined;\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) return undefined;\n\t\treturn this.deps.isModelExhausted(resolved.model) ? undefined : resolved.model;\n\t}\n\n\tresolveConfiguredTierModel(tier: \"cheap\" | \"medium\" | \"expensive\"): Model<Api> | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst pattern =\n\t\t\ttier === \"cheap\" ? settings.cheapModel : tier === \"medium\" ? settings.mediumModel : settings.expensiveModel;\n\t\tif (!pattern) return undefined;\n\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) return undefined;\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) return undefined;\n\t\tif (this.deps.isModelExhausted(resolved.model)) return undefined;\n\t\t// (Same doctrine as _resolveModelRouterTurnRoute above): never resolve a local/managed\n\t\t// model the probe has already graded as having no working tool-call path.\n\t\tif (isLocalOrManagedRouterModel(resolved.model) && this.deps.getToolProbeVerdict(resolved.model) === \"none\") {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn resolved.model;\n\t}\n\n\t/**\n\t * Router resolution with the routing judge (auto-on with the router): the regex classifier's\n\t * decision is the baseline; when a judge model resolves (judgeModel, else mediumModel), one\n\t * bounded, tool-less completion may move the tier between cheap/medium/expensive — never to\n\t * learning. Core rule encoded in the judge prompt: planning is never cheap unless genuinely\n\t * trivial. Every fallback stays visible in the decision reasons, and judge spend reports\n\t * through spawned-usage accounting.\n\t */\n\tasync resolveTurnRouteJudged(\n\t\tprompt: string,\n\t\toptions?: { skipJudge?: boolean },\n\t): Promise<{ decision: RouteDecision; model: Model<Api> } | undefined> {\n\t\tconst baseline = this._resolveModelRouterTurnRoute(prompt);\n\t\tif (!baseline) return undefined;\n\t\tif (options?.skipJudge) return baseline;\n\t\t// Deterministic executor routes need no judge (Level-0 already decided).\n\t\tif (baseline.decision.reasonCode === \"executor_direct\") return baseline;\n\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (!settings.judgeEnabled) return baseline;\n\t\tif (shouldSkipRouteJudgeForStaticDecision(baseline.decision)) return baseline;\n\t\tconst judgePattern = settings.judgeModel ?? settings.mediumModel;\n\t\tif (!judgePattern) return baseline;\n\t\tconst judgeModel = this.deps.resolveLaneModel(judgePattern);\n\t\tif (!judgeModel) {\n\t\t\treturn {\n\t\t\t\tdecision: withJudgeUnavailableFallback(\n\t\t\t\t\tbaseline.decision,\n\t\t\t\t\t`routing judge unavailable: ${judgePattern} did not resolve; baseline kept`,\n\t\t\t\t),\n\t\t\t\tmodel: baseline.model,\n\t\t\t};\n\t\t}\n\t\tif (settings.fitnessGate) {\n\t\t\tconst verdict = this._evaluateModelFitness(\"router_judge\", judgeModel);\n\t\t\tif (!verdict.fit) {\n\t\t\t\treturn {\n\t\t\t\t\tdecision: {\n\t\t\t\t\t\t...baseline.decision,\n\t\t\t\t\t\treasons: [\n\t\t\t\t\t\t\t...baseline.decision.reasons,\n\t\t\t\t\t\t\t`routing judge skipped: ${formatModelRouterModel(judgeModel)} unfit (${this._formatFitnessFailure(verdict)})`,\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t\tmodel: baseline.model,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tlet spentUsage: Usage | undefined;\n\t\tconst judged = await runRouteJudge({\n\t\t\tprompt,\n\t\t\tbaseline: baseline.decision,\n\t\t\tsignal: this.deps.getReflectionSignal(),\n\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\tconst completion = await runIsolatedTextCompletion(this.deps, {\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tuserPrompt,\n\t\t\t\t\tmodel: judgeModel,\n\t\t\t\t\t// Per-tier thinking: judgeThinking overrides the judge's own completion; unset\n\t\t\t\t\t// keeps today's \"off\" (the judge is a cheap classification call by default).\n\t\t\t\t\tthinkingLevel: settings.judgeThinking ?? \"off\",\n\t\t\t\t\tmaxTokens: ROUTE_JUDGE_MAX_OUTPUT_TOKENS,\n\t\t\t\t\tsignal,\n\t\t\t\t\t// The judge system prompt is static — the provider can cache the prefix.\n\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t// Stable per-lane synthetic affinity key so repeat judge calls hit the same\n\t\t\t\t\t// cache-warm backend.\n\t\t\t\t\tlaneKind: \"route-judge\",\n\t\t\t\t});\n\t\t\t\tspentUsage = completion.usage;\n\t\t\t\treturn completion;\n\t\t\t},\n\t\t});\n\t\tif (spentUsage) {\n\t\t\treportSpawnedUsage(this.deps, spentUsage, {\n\t\t\t\tkind: \"route-judge\",\n\t\t\t\tlabel: \"router-judge\",\n\t\t\t\tsessionId: this.deps.getSessionManager().getSessionId(),\n\t\t\t\tidentity: prompt,\n\t\t\t});\n\t\t}\n\n\t\tif (!judged.verdict || judged.decision.tier === baseline.decision.tier) {\n\t\t\t// Same tier (or judge fell back): keep the baseline model, carry the annotated decision.\n\t\t\treturn { decision: judged.decision, model: baseline.model };\n\t\t}\n\n\t\tconst judgedTier = judged.decision.tier;\n\t\tif (judgedTier !== \"cheap\" && judgedTier !== \"medium\" && judgedTier !== \"expensive\") {\n\t\t\treturn { decision: baseline.decision, model: baseline.model };\n\t\t}\n\t\tconst judgedModel = this.resolveConfiguredTierModel(judgedTier);\n\t\tif (!judgedModel) {\n\t\t\treturn {\n\t\t\t\tdecision: {\n\t\t\t\t\t...baseline.decision,\n\t\t\t\t\treasons: [\n\t\t\t\t\t\t...baseline.decision.reasons,\n\t\t\t\t\t\t`Route judge chose ${judgedTier} but no model resolves for that tier; baseline kept`,\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tmodel: baseline.model,\n\t\t\t};\n\t\t}\n\t\treturn { decision: { ...judged.decision, model: formatModelRouterModel(judgedModel) }, model: judgedModel };\n\t}\n\n\t// biome-ignore lint/correctness/noUnusedPrivateClassMembers: test seam\n\tprivate _resolveModelRouterTurnModel(prompt: string): Model<Api> | undefined {\n\t\tconst resolved = this._resolveModelRouterTurnRoute(prompt);\n\t\treturn resolved?.model;\n\t}\n\n\tgetStatus(formatLabel?: (label: string) => string): string {\n\t\tconst recentDecisions = getRecentModelRouterDecisions(this.deps.getSessionManager().getEntries());\n\t\tconst lastDecision = this._lastModelRouterDecision ?? recentDecisions.at(-1);\n\t\tconst historicalDecisions = this._lastModelRouterDecision ? recentDecisions : recentDecisions.slice(0, -1);\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst lines = [\n\t\t\tformatModelRouterStatus(\n\t\t\t\tsettings,\n\t\t\t\tlastDecision,\n\t\t\t\tformatLabel,\n\t\t\t\thistoricalDecisions,\n\t\t\t\tthis._lastModelRouterSkipReason,\n\t\t\t\tthis._lastModelRouterIntent ?? lastDecision?.intent,\n\t\t\t\tsettings.fitnessGate ? this._getRouterTierFitnessStatuses() : undefined,\n\t\t\t\tthis.deps.getFailoverStatus(),\n\t\t\t),\n\t\t];\n\t\tconst diagnostics = collectModelRouterConfigDiagnostics(\n\t\t\tsettings,\n\t\t\tthis.deps.getModelRegistry(),\n\t\t\tthis.deps.getAgentDir(),\n\t\t);\n\t\tif (diagnostics.length > 0) {\n\t\t\tlines.push(formatLabel ? formatLabel(\"Config diagnostics:\") : \"Config diagnostics:\");\n\t\t\tfor (const diagnostic of diagnostics) {\n\t\t\t\tlines.push(`- ${diagnostic}`);\n\t\t\t}\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tasync runRoutedTurn(\n\t\tmessages: AgentMessage | AgentMessage[],\n\t\troutedModel: Model<Api> | undefined,\n\t\trouteDecision: RouteDecision | undefined,\n\t\tpersistDecision = true,\n\t): Promise<void> {\n\t\tif (!routedModel) {\n\t\t\tawait this.deps.runAgentPrompt(messages);\n\t\t\treturn;\n\t\t}\n\n\t\tconst agent = this.deps.getAgent();\n\t\tconst previousModel = agent.state.model;\n\t\tconst previousThinkingLevel = agent.state.thinkingLevel;\n\t\tconst previousTurnTools = agent.state.tools;\n\t\tconst previousSystemPrompt = agent.state.systemPrompt;\n\t\t// Swap bookkeeping: the exact references the swap below assigns, so the finally can\n\t\t// restore ONLY what IT put there — never assigned when no swap happens (e.g. a full-class\n\t\t// routed profile).\n\t\tlet swappedTools: typeof previousTurnTools | undefined;\n\t\tlet swappedSystemPrompt: typeof previousSystemPrompt | undefined;\n\t\tconst previousActiveModelRouterIntent = this._activeModelRouterIntent;\n\t\tconst previousActiveModelRouterRoute = this._activeModelRouterRoute;\n\t\tconst previousModelRouterSessionBuffer = this._modelRouterSessionBuffer;\n\t\tconst previousModelRouterEscalationRequested = this._modelRouterEscalationRequested;\n\t\tconst bufferRoutedTurn = routeDecision?.tier === \"cheap\";\n\t\tconst originalHistoryLength = agent.state.messages.length;\n\t\tlet retryModel: Model<Api> | undefined;\n\t\tlet completedDecision: ModelRouterDecisionStatus | undefined = routeDecision\n\t\t\t? {\n\t\t\t\t\troute: routeDecision,\n\t\t\t\t\troutedModel: formatModelRouterModel(routedModel),\n\t\t\t\t\toutcome: \"routed\",\n\t\t\t\t\tintent: routeDecision.tier === \"cheap\" ? \"research\" : \"modify\",\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tlet thrownError: unknown;\n\t\tif (routeDecision) {\n\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t}\n\t\tthis._activeModelRouterIntent = routeDecision\n\t\t\t? routeDecision.tier === \"cheap\"\n\t\t\t\t? \"research\"\n\t\t\t\t: \"modify\"\n\t\t\t: undefined;\n\t\tthis._activeModelRouterRoute = routeDecision;\n\t\tif (bufferRoutedTurn) {\n\t\t\tthis._modelRouterSessionBuffer = createModelRouterSessionBuffer();\n\t\t\tthis._modelRouterEscalationRequested = false;\n\t\t}\n\t\tconst routerThinkingSettings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst configuredThinking = !routeDecision\n\t\t\t? undefined\n\t\t\t: routeDecision.reasonCode === \"executor_direct\"\n\t\t\t\t? routerThinkingSettings.executorThinking\n\t\t\t\t: routeDecision.tier === \"cheap\"\n\t\t\t\t\t? routerThinkingSettings.cheapThinking\n\t\t\t\t\t: routeDecision.tier === \"medium\"\n\t\t\t\t\t\t? routerThinkingSettings.mediumThinking\n\t\t\t\t\t\t: routeDecision.tier === \"expensive\"\n\t\t\t\t\t\t\t? routerThinkingSettings.expensiveThinking\n\t\t\t\t\t\t\t: undefined;\n\t\tconst routedThinkingLevel = clampThinkingLevel(\n\t\t\troutedModel,\n\t\t\tconfiguredThinking ?? previousThinkingLevel,\n\t\t) as ThinkingLevel;\n\t\tconst modelChanged = !modelsAreEqual(this.deps.getModel(), routedModel);\n\t\tconst thinkingChanged = routedThinkingLevel !== previousThinkingLevel;\n\t\tif (modelChanged || thinkingChanged) {\n\t\t\tagent.state.model = routedModel;\n\t\t\t// Per-tier thinking: a configured tier/executor thinking level overrides the inherited\n\t\t\t// session thinking for THIS routed turn only; unset falls back to exactly today's\n\t\t\t// inherit-and-clamp behavior. Executor routes carry tier \"cheap\" too, so reasonCode is\n\t\t\t// checked first — otherwise an executor turn would silently pick up cheapThinking instead.\n\t\t\t// The judge's own completion has a separate knob (judgeThinking) applied at its call site.\n\t\t\tagent.state.thinkingLevel = routedThinkingLevel;\n\t\t\t// Capability tool-filtering follows the ROUTED model for the turn. Without this a\n\t\t\t// cheap/local routed model inherits the session model's full tool surface — schemas it\n\t\t\t// pays for on every request and may not be able to drive at all.\n\t\t\tif (modelChanged) {\n\t\t\t\tconst routedProfile = deriveModelCapabilityProfile({\n\t\t\t\t\tcontextWindow: routedModel.contextWindow,\n\t\t\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t\t\t});\n\t\t\t\tif (routedProfile.class !== \"full\") {\n\t\t\t\t\tconst allowed = new Set(\n\t\t\t\t\t\tfilterToolNamesForCapability(\n\t\t\t\t\t\t\tpreviousTurnTools.map((tool) => tool.name),\n\t\t\t\t\t\t\troutedProfile,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tswappedTools = previousTurnTools.filter((tool) => allowed.has(tool.name));\n\t\t\t\t\tagent.state.tools = swappedTools;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// The routed prompt follows both the routed tool surface and its effective thinking mode.\n\t\t\t// This removes an Ultra policy during max/Luna routes, including same-model tier overrides.\n\t\t\t// Per-turn only; a live extension override is preserved rather than silently replaced.\n\t\t\tif (agent.state.systemPrompt === this.deps.getBaseSystemPrompt()) {\n\t\t\t\tswappedSystemPrompt = this.deps.buildSystemPromptForToolNames(agent.state.tools.map((tool) => tool.name));\n\t\t\t\tagent.state.systemPrompt = swappedSystemPrompt;\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tawait this.deps.runAgentPrompt(messages);\n\t\t\t// Speculative muscle-retry: an executor-routed turn is a bet that the\n\t\t\t// small model can run the toolkit command directly. If it ends WITHOUT a successful\n\t\t\t// run_toolkit_script execution, retry ONCE on the same executor with the brain's\n\t\t\t// refined instruction injected — the brain warms while the muscle tries, so the retry\n\t\t\t// pays only when the muscle actually missed.\n\t\t\tif (\n\t\t\t\trouteDecision?.reasonCode === \"executor_direct\" &&\n\t\t\t\t!this._isModelRouterRetry &&\n\t\t\t\t!this._executorTurnExecutedScript(originalHistoryLength)\n\t\t\t) {\n\t\t\t\tconst refined = await this._buildExecutorRefinedPrompt(messages);\n\t\t\t\tif (refined) {\n\t\t\t\t\tagent.state.messages.splice(originalHistoryLength);\n\t\t\t\t\tif (bufferRoutedTurn) this._modelRouterSessionBuffer = createModelRouterSessionBuffer();\n\t\t\t\t\tawait this.deps.runAgentPrompt([\n\t\t\t\t\t\t{ role: \"user\", content: [{ type: \"text\", text: refined }], timestamp: Date.now() },\n\t\t\t\t\t]);\n\t\t\t\t\tcompletedDecision = {\n\t\t\t\t\t\troute: {\n\t\t\t\t\t\t\t...routeDecision,\n\t\t\t\t\t\t\treasonCode: \"executor_speculative_retry\",\n\t\t\t\t\t\t\treasons: [\n\t\t\t\t\t\t\t\t...routeDecision.reasons,\n\t\t\t\t\t\t\t\t\"Executor missed on first try; retried with brain-refined instruction\",\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\troutedModel: formatModelRouterModel(routedModel),\n\t\t\t\t\t\toutcome: \"routed\",\n\t\t\t\t\t\tintent: \"research\",\n\t\t\t\t\t};\n\t\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t\t} else {\n\t\t\t\t\t// The muscle missed AND the reflex brain could not refine the request into a toolkit\n\t\t\t\t\t// instruction (no fit brain model, or no confident plan). There is deliberately NO\n\t\t\t\t\t// frontier fallback here, so surface the miss instead of letting it stand silently —\n\t\t\t\t\t// otherwise the routed turn just ends with an unrun command and no explanation.\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Executor lane: the toolkit command did not run and the reflex brain could not refine it into an explicit instruction; leaving the turn as-is (no automatic escalation).\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (bufferRoutedTurn && this._modelRouterEscalationRequested) {\n\t\t\t\tagent.state.messages.splice(originalHistoryLength);\n\t\t\t\tretryModel = this._resolveModelRouterModelForIntent(\"modify\") ?? previousModel;\n\t\t\t\tcompletedDecision = {\n\t\t\t\t\troute: routeDecision!,\n\t\t\t\t\troutedModel: formatModelRouterModel(routedModel),\n\t\t\t\t\toutcome: \"escalated\",\n\t\t\t\t\tretryModel: formatModelRouterModel(retryModel),\n\t\t\t\t\tintent: routeDecision!.tier === \"cheap\" ? \"research\" : \"modify\",\n\t\t\t\t};\n\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t} else if (bufferRoutedTurn && this._modelRouterSessionBuffer) {\n\t\t\t\tflushModelRouterSessionBuffer(\n\t\t\t\t\tthis._modelRouterSessionBuffer,\n\t\t\t\t\t(message) => {\n\t\t\t\t\t\tthis.deps.getSessionManager().appendMessage(message);\n\t\t\t\t\t},\n\t\t\t\t\t(customType, content, display, details) => {\n\t\t\t\t\t\tthis.deps.getSessionManager().appendCustomMessageEntry(customType, content, display, details);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrownError = error;\n\t\t\t// Mirror the escalation splice above (~:812): a buffered cheap-tier turn never flushes its\n\t\t\t// live messages to the session on a genuine throw, so agent.state.messages must be rolled\n\t\t\t// back to the pre-turn length here too — otherwise the never-persisted buffered messages\n\t\t\t// permanently diverge from the persisted session (same shape as the W1.3 ghost-turn bug,\n\t\t\t// but on the error path instead of the success/escalation paths).\n\t\t\tif (bufferRoutedTurn) {\n\t\t\t\tagent.state.messages.splice(originalHistoryLength);\n\t\t\t}\n\t\t\tif (completedDecision) {\n\t\t\t\tcompletedDecision = { ...completedDecision, outcome: \"failed\" };\n\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t}\n\t\t} finally {\n\t\t\t// Restore the pre-route model ONLY if the routed model is still in place: a command\n\t\t\t// handler may have legitimately changed the session model mid-turn (setModel or a\n\t\t\t// provider re-registration), and clobbering that would silently undo the change.\n\t\t\tif (modelsAreEqual(agent.state.model, routedModel)) {\n\t\t\t\tagent.state.model = previousModel;\n\t\t\t\tagent.state.thinkingLevel = previousThinkingLevel;\n\t\t\t\t// Symmetric restore: undo tools/systemPrompt only if each is STILL the exact\n\t\t\t\t// reference/string the swap above assigned (never assigned at all when the routed\n\t\t\t\t// profile was full-class — then there is nothing to restore either). An extension calling\n\t\t\t\t// setActiveToolsByName mid-turn reassigns both to its own values without touching the\n\t\t\t\t// model — the model guard above still passes, but that live change is legitimate and must\n\t\t\t\t// survive rather than being silently reverted to the stale pre-turn snapshot.\n\t\t\t\tif (swappedTools !== undefined && agent.state.tools === swappedTools) {\n\t\t\t\t\tagent.state.tools = previousTurnTools;\n\t\t\t\t}\n\t\t\t\tif (swappedSystemPrompt !== undefined && agent.state.systemPrompt === swappedSystemPrompt) {\n\t\t\t\t\tagent.state.systemPrompt = previousSystemPrompt;\n\t\t\t\t}\n\t\t\t\t// The registry may have changed mid-turn (command-time registerProvider): re-resolve\n\t\t\t\t// the restored model so a provider override is not dropped with the routed model.\n\t\t\t\tthis.deps.refreshCurrentModelFromRegistry();\n\t\t\t}\n\t\t\tthis._activeModelRouterIntent = previousActiveModelRouterIntent;\n\t\t\tthis._activeModelRouterRoute = previousActiveModelRouterRoute;\n\t\t\tthis._modelRouterSessionBuffer = previousModelRouterSessionBuffer;\n\t\t\tthis._modelRouterEscalationRequested = previousModelRouterEscalationRequested;\n\t\t}\n\n\t\tif (retryModel && !thrownError) {\n\t\t\tconst previousIsModelRouterRetry = this._isModelRouterRetry;\n\t\t\ttry {\n\t\t\t\tthis._isModelRouterRetry = true;\n\t\t\t\tconst retryDecision: RouteDecision = {\n\t\t\t\t\ttier: \"expensive\",\n\t\t\t\t\trisk: \"high-impact\",\n\t\t\t\t\tconfidence: 1.0,\n\t\t\t\t\treasonCode: \"cheap_mutating_tool_escalation\",\n\t\t\t\t\treasons: [\"Cheap research turn attempted a mutating tool and escalated\"],\n\t\t\t\t\tfallbackFrom: \"cheap\",\n\t\t\t\t\tmodel: formatModelRouterModel(retryModel),\n\t\t\t\t};\n\t\t\t\tawait this.runRoutedTurn(messages, retryModel, retryDecision, false);\n\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t} catch (error) {\n\t\t\t\tthrownError = error;\n\t\t\t\tif (completedDecision) {\n\t\t\t\t\tcompletedDecision = { ...completedDecision, outcome: \"failed\" };\n\t\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis._isModelRouterRetry = previousIsModelRouterRetry;\n\t\t\t}\n\t\t}\n\n\t\tif (persistDecision && completedDecision) {\n\t\t\tpersistModelRouterDecision(this.deps.getSessionManager(), completedDecision);\n\t\t\t// One route event per user-facing routed turn (the escalation retry runs with\n\t\t\t// persistDecision=false, so it does not double-emit). Codes/numbers only — no prompt text.\n\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.routeDecision,\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tpayload: {\n\t\t\t\t\ttier: completedDecision.route.tier,\n\t\t\t\t\trisk: completedDecision.route.risk,\n\t\t\t\t\treasonCode: completedDecision.route.reasonCode,\n\t\t\t\t\tconfidence: completedDecision.route.confidence,\n\t\t\t\t\toutcome: completedDecision.outcome,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tif (thrownError) {\n\t\t\tthrow thrownError;\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model-router-controller.js","sourceRoot":"","sources":["../../src/core/model-router-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAKH,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAO9E,OAAO,EAAE,8BAA8B,EAA+B,MAAM,gCAAgC,CAAC;AAC7G,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,4BAA4B,EAAE,4BAA4B,EAAE,MAAM,uBAAuB,CAAC;AAEnG,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,mCAAmC,EAAE,MAAM,sCAAsC,CAAC;AAC3F,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EACN,sBAAsB,GAGtB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,wBAAwB,EAA0B,MAAM,qCAAqC,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC7F,OAAO,EACN,qCAAqC,EACrC,+BAA+B,EAC/B,8BAA8B,EAC9B,6BAA6B,GAE7B,MAAM,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MAAM,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,UAAU,EAAE,aAAa,EAAE,KAAK,CAAC,CAAC;gBACrE,IAAI,CAAC,wBAAwB,GAAG,iBAAiB,CAAC;YACnD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,WAAW,GAAG,KAAK,CAAC;gBACpB,IAAI,iBAAiB,EAAE,CAAC;oBACvB,iBAAiB,GAAG,EAAE,GAAG,iBAAiB,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;oBAChE,IAAI,CAAC,wBAAwB,GAAG,iBAAiB,CAAC;gBACnD,CAAC;YACF,CAAC;oBAAS,CAAC;gBACV,IAAI,CAAC,mBAAmB,GAAG,0BAA0B,CAAC;YACvD,CAAC;QACF,CAAC;QAED,IAAI,eAAe,IAAI,iBAAiB,EAAE,CAAC;YAC1C,0BAA0B,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,EAAE,iBAAiB,CAAC,CAAC;YAC7E,8EAA8E;YAC9E,2FAA2F;YAC3F,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAAC;gBAC/B,IAAI,EAAE,8BAA8B,CAAC,aAAa;gBAClD,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;gBACnC,OAAO,EAAE;oBACR,IAAI,EAAE,iBAAiB,CAAC,KAAK,CAAC,IAAI;oBAClC,IAAI,EAAE,iBAAiB,CAAC,KAAK,CAAC,IAAI;oBAClC,UAAU,EAAE,iBAAiB,CAAC,KAAK,CAAC,UAAU;oBAC9C,UAAU,EAAE,iBAAiB,CAAC,KAAK,CAAC,UAAU;oBAC9C,OAAO,EAAE,iBAAiB,CAAC,OAAO;iBAClC;aACD,CAAC,CAAC;QACJ,CAAC;QAED,IAAI,WAAW,EAAE,CAAC;YACjB,MAAM,WAAW,CAAC;QACnB,CAAC;IACF,CAAC;CACD","sourcesContent":["/**\n * Model-router turn routing: the session's per-turn model-selection subsystem — the regex/executor\n * route resolver, the optional bounded routing judge, the executor lane (Level-0 toolkit direct hit\n * + speculative brain-refined retry), the per-tier thinking/tool-surface swap around a routed turn,\n * the cheap-research-turn session buffer with mutating-tool escalation to an expensive retry, and\n * the router status/diagnostics report.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the transient per-turn\n * route state — the active intent/route, the cheap-turn session buffer, the escalation-requested and\n * retry-in-flight flags — and the sticky last-decision/last-skip-reason/last-intent used by the\n * status report. Everything else it needs — the live agent + its state, the current model, the\n * session/settings managers, the model registry, the agent dir, the reflection abort signal, the\n * base system prompt, the isolated-completion primitive, spawned-usage accounting, the event/telemetry\n * emitters, and the recently-extracted BackgroundLaneController (resolveLaneModel) / ContextPipeline\n * (resolveCurationModelIfFit) collaborators — is reached through narrow deps accessors rather than the\n * whole AgentSession.\n *\n * Drive-path boundary (deliberate): the actual agent.prompt()/continue() loop belongs to the\n * session-owned ForegroundRecoveryController; this controller's parallel routed drive path\n * ({@link runRoutedTurn}) owns only route decision/escalation/tier bookkeeping and delegates every\n * agent turn through {@link ModelRouterControllerDeps.runAgentPrompt}, so the drive loop is never duplicated. The\n * host keeps a one-line delegation at each call-in: the routing prep + routed-turn entry in\n * _promptUnserialized, the beforeToolCall MUTATION escalation branch ({@link\n * maybeEscalateToolCall}), the tool-name-agnostic VALIDATION-FAILURE escalation branch for cloud\n * models ({@link requestValidationFailureEscalation} — de-conflated from the mutation gate; see the\n * capability-gate spine doctrine, which routes local/managed models to an evidence-gated\n * native→phone auto-probe on AgentSession instead), the message_end cheap-turn buffering ({@link\n * captureSessionMessage}), the retry-event suppression ({@link isRetryInFlight}), the public\n * getModelRouterStatus / autonomy-telemetry reads, and the tier resolution's consultation of the\n * persisted `/toolprobe` verdict for local/managed tier models ({@link\n * ModelRouterControllerDeps.getToolProbeVerdict}).\n */\n\nimport type { Agent, AgentMessage, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, Message, Model, Usage } from \"@caupulican/pi-ai\";\nimport { clampThinkingLevel, modelsAreEqual } from \"@caupulican/pi-ai/models\";\nimport type {\n\tAgentSessionEvent,\n\tIsolatedCompletionOptions,\n\tIsolatedCompletionResult,\n} from \"./agent-session-contracts.ts\";\nimport type { RouteDecision } from \"./autonomy/contracts.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport { latestUserPromptText } from \"./context/message-text.ts\";\nimport { runIsolatedTextCompletion } from \"./isolated-text-completion.ts\";\nimport { deriveModelCapabilityProfile, filterToolNamesForCapability } from \"./model-capability.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { collectModelRouterConfigDiagnostics } from \"./model-router/config-diagnostics.ts\";\nimport { classifyExecutorTurn } from \"./model-router/executor-route.ts\";\nimport {\n\tevaluateSurfaceFitness,\n\ttype FitnessGatedSurface,\n\ttype FitnessGateVerdict,\n} from \"./model-router/fitness-gate.ts\";\nimport { classifyModelRouterRoute, type ModelRouterIntent } from \"./model-router/intent-classifier.ts\";\nimport { ROUTE_JUDGE_MAX_OUTPUT_TOKENS, runRouteJudge } from \"./model-router/route-judge.ts\";\nimport {\n\tbufferModelRouterSessionCustomMessage,\n\tbufferModelRouterSessionMessage,\n\tcreateModelRouterSessionBuffer,\n\tflushModelRouterSessionBuffer,\n\ttype ModelRouterSessionBuffer,\n} from \"./model-router/session-buffer.ts\";\nimport {\n\tformatModelRouterStatus,\n\tgetRecentModelRouterDecisions,\n\tMODEL_ROUTER_DECISION_CUSTOM_TYPE,\n\ttype ModelRouterDecisionStatus,\n\ttype ModelRouterFailoverStatus,\n\ttype ModelRouterFitnessStatuses,\n} from \"./model-router/status.ts\";\nimport { isLocalOrManagedRouterModel, shouldEscalateModelRouterTool } from \"./model-router/tool-escalation.ts\";\nimport type { ModelToolProbeVerdict } from \"./models/adaptation-store.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { reportSpawnedUsage } from \"./spawned-usage.ts\";\nimport { runReflexInterpreterCompletion } from \"./toolkit/reflex-interpreter.ts\";\n\n/** Canonical `provider/id` label for a routed/resolved model, as it appears in decisions and status. */\nexport function formatModelRouterModel(model: Model<Api>): string {\n\treturn `${model.provider}/${model.id}`;\n}\n\nconst ROUTE_JUDGE_STATIC_FAST_PATH_REASON_CODES = new Set([\n\t\"empty_prompt\",\n\t\"read_only_question\",\n\t\"release_or_publish\",\n\t\"security_or_auth\",\n\t\"destructive_or_git_history\",\n\t\"settings_or_self_modification\",\n\t\"architecture_or_ambiguous\",\n]);\n\nfunction shouldSkipRouteJudgeForStaticDecision(decision: RouteDecision): boolean {\n\treturn ROUTE_JUDGE_STATIC_FAST_PATH_REASON_CODES.has(decision.reasonCode);\n}\n\nfunction withJudgeUnavailableFallback(decision: RouteDecision, reason: string): RouteDecision {\n\treturn {\n\t\t...decision,\n\t\treasonCode: \"judge_unavailable_fallback\",\n\t\treasons: [...decision.reasons, reason],\n\t};\n}\n\nfunction persistModelRouterDecision(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\tdecision: ModelRouterDecisionStatus,\n): void {\n\tsessionManager.appendCustomEntry(MODEL_ROUTER_DECISION_CUSTOM_TYPE, decision);\n}\n\nexport interface ModelRouterControllerDeps {\n\t/** Live agent — the controller reads/writes agent.state.{model,thinkingLevel,tools,systemPrompt,messages}\n\t * for the per-turn tier swap and aborts it on a mutating-tool escalation. */\n\tgetAgent(): Agent;\n\t/** Current session model, used to decide whether a routed turn actually swaps the model. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Router/executor/judge/thinking settings + capability mode (all opt-in gates). */\n\tgetSettingsManager(): SettingsManager;\n\t/** Session log: routed-turn message buffering/persistence, decision persistence, recent-decision status. */\n\tgetSessionManager(): SessionManager;\n\t/** Resolves configured route/judge/executor model patterns against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Session-scoped provider/model quota exhaustion guard. */\n\tisModelExhausted(model: Model<Api>): boolean;\n\t/** Status snapshot for exhausted models and the last failover notice. */\n\tgetFailoverStatus(): ModelRouterFailoverStatus;\n\t/** Root dir the host-keyed {@link FitnessStore} lives under (executor tool-call fitness gate). */\n\tgetAgentDir(): string;\n\t/** Aborts the judge's bounded completion when the session is disposed. */\n\tgetReflectionSignal(): AbortSignal;\n\t/** Base (extension-free) system prompt — the tier swap only sheds tools when the turn is on it. */\n\tgetBaseSystemPrompt(): string;\n\t/** The session-owned foreground drive loop; the routed path delegates every turn here. */\n\trunAgentPrompt(messages: AgentMessage | AgentMessage[]): Promise<void>;\n\t/** Rebuilds the system prompt for a filtered tool surface (routed-model capability shedding). */\n\tbuildSystemPromptForToolNames(toolNames: string[]): string;\n\t/** Re-resolves the restored model against the registry after a routed turn (provider override safety). */\n\trefreshCurrentModelFromRegistry(): void;\n\t/** One-shot, tool-less LLM call — the routing judge and the executor reflex-brain warmup ride this. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\t/** Rolls judge/brain spend into spawned-usage accounting. `reportId` is REQUIRED: every\n\t * caller derives a stable id from the work unit's identity so a retry cannot double-count. */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts: { label?: string; sourceSessionId?: string; reportId: string },\n\t): string | undefined;\n\t/** Session event stream (executor-miss warning). */\n\temit(event: AgentSessionEvent): void;\n\t/** Autonomy telemetry stream (one route-decision event per user-facing routed turn). */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Resolves the judge model pattern via {@link BackgroundLaneController}. */\n\tresolveLaneModel(pattern: string): Model<Api> | undefined;\n\t/** Fitness-gated reflex-brain model via {@link ContextPipeline} (executor speculative refinement). */\n\tresolveCurationModelIfFit(): Model<Api> | undefined;\n\t/** Persisted `/toolprobe` verdict for this model (native / text-protocol / none), or undefined\n\t * when never probed. Tier-resolution's consultation reads this ONLY for local/managed models\n\t * ({@link isLocalOrManagedRouterModel}); cloud models never call it. */\n\tgetToolProbeVerdict(model: Model<Api>): ModelToolProbeVerdict | undefined;\n}\n\n/**\n * Owns the model-router turn routing extracted from {@link AgentSession}. See the module header for the\n * drive-path boundary that keeps the agent.prompt()/continue() loop in its foreground lifecycle owner.\n */\nexport class ModelRouterController {\n\t/** Active model-router intent for the current transient routed turn, if any. */\n\tprivate _activeModelRouterIntent?: ModelRouterIntent;\n\tprivate _activeModelRouterRoute?: RouteDecision;\n\tprivate _modelRouterSessionBuffer?: ModelRouterSessionBuffer;\n\tprivate _modelRouterEscalationRequested = false;\n\tprivate _isModelRouterRetry = false;\n\tprivate _lastModelRouterDecision?: ModelRouterDecisionStatus;\n\tprivate _lastModelRouterSkipReason?: string;\n\tprivate _lastModelRouterIntent?: ModelRouterIntent;\n\n\tprivate readonly deps: ModelRouterControllerDeps;\n\n\tconstructor(deps: ModelRouterControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** True while the escalation retry turn is running, so the host can suppress its duplicate prompt events. */\n\tisRetryInFlight(): boolean {\n\t\treturn this._isModelRouterRetry;\n\t}\n\n\t/** Latest completed route decision (sticky), for the autonomy telemetry snapshot. */\n\tgetLastDecision(): ModelRouterDecisionStatus | undefined {\n\t\treturn this._lastModelRouterDecision;\n\t}\n\n\t/**\n\t * beforeToolCall escalation gate: a cheap research turn that reaches for a mutating tool aborts the\n\t * turn and requests a retry on the expensive model. Returns the block result the host hook forwards,\n\t * or undefined when no escalation is required.\n\t */\n\tmaybeEscalateToolCall(toolName: string, args: unknown): { block: true; reason: string } | undefined {\n\t\tif (\n\t\t\tthis._activeModelRouterRoute &&\n\t\t\tshouldEscalateModelRouterTool({\n\t\t\t\ttier: this._activeModelRouterRoute.tier,\n\t\t\t\ttoolName,\n\t\t\t\targs,\n\t\t\t\treasonCode: this._activeModelRouterRoute.reasonCode,\n\t\t\t})\n\t\t) {\n\t\t\tthis._modelRouterEscalationRequested = true;\n\t\t\tthis.deps.getAgent().abort();\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason:\n\t\t\t\t\t\"Model router escalation required: a cheap research turn attempted a mutating tool. Retry the turn on the configured expensive model.\",\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Tool-name-agnostic validation-failure escalation gate, called from\n\t * AgentSession's onToolValidationEscalation handler for a CLOUD model only — see the\n\t * capability-gate-spine doctrine (local/managed models never reach this method; they trigger\n\t * the evidence-gated native→phone auto-probe instead). Unlike {@link maybeEscalateToolCall} (the\n\t * beforeToolCall MUTATION gate, still governed by `shouldEscalateModelRouterTool`/\n\t * READ_ONLY_TOOL_NAMES — a legitimate, unrelated mutation-blast-radius policy), \"the model\n\t * repeatedly cannot construct valid arguments for this tool\" is evidence about the MODEL's\n\t * capability, not about the tool's mutation status, so a read-only tool's repeated validation\n\t * failure now escalates a cheap routed turn exactly like a mutating tool's would — takes no\n\t * tool-name/args input at all (unlike maybeEscalateToolCall), because every repeated validation\n\t * failure escalates regardless of which tool or model triggered it. No-op outside an active\n\t * cheap-tier routed turn, same scoping as maybeEscalateToolCall.\n\t */\n\trequestValidationFailureEscalation(): void {\n\t\tif (this._activeModelRouterRoute?.tier !== \"cheap\") return;\n\t\tthis._modelRouterEscalationRequested = true;\n\t\tthis.deps.getAgent().abort();\n\t}\n\n\t/**\n\t * message_end hook: while a cheap routed turn is buffering, capture its messages into the session\n\t * buffer instead of persisting them (they are flushed on success or discarded on escalation).\n\t * Returns true when the message was buffered, so the host skips its own persistence.\n\t */\n\tcaptureSessionMessage(message: AgentMessage): boolean {\n\t\tconst modelRouterBuffer = this._modelRouterSessionBuffer;\n\t\tif (!modelRouterBuffer) return false;\n\t\tif (message.role === \"custom\") {\n\t\t\tbufferModelRouterSessionCustomMessage(modelRouterBuffer, message);\n\t\t\treturn true;\n\t\t}\n\t\tif (message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tbufferModelRouterSessionMessage(modelRouterBuffer, message as Message);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate _isModelAvailableAndAuthed(pattern: string): boolean {\n\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) return false;\n\t\treturn this.deps.getModelRegistry().hasConfiguredAuth(resolved.model);\n\t}\n\n\tprivate _evaluateModelFitness(surface: FitnessGatedSurface, model: Model<Api>): FitnessGateVerdict {\n\t\tconst fitness = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === formatModelRouterModel(model));\n\t\treturn evaluateSurfaceFitness(surface, fitness?.report);\n\t}\n\n\tprivate _formatFitnessFailure(verdict: Exclude<FitnessGateVerdict, { fit: true }>): string {\n\t\treturn verdict.reason === \"unprobed\" ? \"unprobed\" : `${verdict.lane} ${verdict.succeeded}/${verdict.total}`;\n\t}\n\n\tprivate _routerSurfaceForTier(tier: \"cheap\" | \"medium\" | \"expensive\"): FitnessGatedSurface {\n\t\treturn tier === \"cheap\" ? \"router_cheap\" : tier === \"medium\" ? \"router_medium\" : \"router_expensive\";\n\t}\n\n\tprivate _getRouterTierFitnessStatuses(): ModelRouterFitnessStatuses {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst statuses: ModelRouterFitnessStatuses = {};\n\t\tfor (const tier of [\"cheap\", \"medium\", \"expensive\"] as const) {\n\t\t\tconst pattern =\n\t\t\t\ttier === \"cheap\" ? settings.cheapModel : tier === \"medium\" ? settings.mediumModel : settings.expensiveModel;\n\t\t\tif (!pattern) continue;\n\t\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (!resolved.model || !this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) continue;\n\t\t\tconst verdict = this._evaluateModelFitness(this._routerSurfaceForTier(tier), resolved.model);\n\t\t\tstatuses[tier] = verdict.fit\n\t\t\t\t? { status: verdict.probed ? \"fit\" : \"unprobed\" }\n\t\t\t\t: verdict.reason === \"unprobed\"\n\t\t\t\t\t? { status: \"unprobed\" }\n\t\t\t\t\t: { status: \"unfit\", lane: verdict.lane, succeeded: verdict.succeeded, total: verdict.total };\n\t\t}\n\t\treturn statuses;\n\t}\n\n\tprivate _resolveExpensiveFallbackRoute(\n\t\tdecision: RouteDecision,\n\t\treasonCode: string,\n\t\treason: string,\n\t): { decision: RouteDecision; model: Model<Api> } | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst expensivePattern = settings.expensiveModel;\n\t\tif (!expensivePattern || !this._isModelAvailableAndAuthed(expensivePattern)) return undefined;\n\t\tconst resolvedExpensive = resolveCliModel({\n\t\t\tcliModel: expensivePattern,\n\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t});\n\t\tif (!resolvedExpensive.model) return undefined;\n\t\tif (this.deps.isModelExhausted(resolvedExpensive.model)) {\n\t\t\tthis._lastModelRouterSkipReason = \"expensive model exhausted: quota\";\n\t\t\treturn undefined;\n\t\t}\n\t\tif (settings.fitnessGate) {\n\t\t\tconst verdict = this._evaluateModelFitness(\"router_expensive\", resolvedExpensive.model);\n\t\t\tif (!verdict.fit) {\n\t\t\t\tthis._lastModelRouterSkipReason = `expensive model unfit: ${this._formatFitnessFailure(verdict)} (fitness gate)`;\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t\tdecision.fallbackFrom = \"medium\";\n\t\tdecision.tier = \"expensive\";\n\t\tdecision.reasonCode = reasonCode;\n\t\tdecision.reasons = [...decision.reasons, reason];\n\t\tdecision.model = formatModelRouterModel(resolvedExpensive.model);\n\t\tthis._lastModelRouterSkipReason = undefined;\n\t\treturn { decision, model: resolvedExpensive.model };\n\t}\n\n\tprivate _resolveExecutorRoute(\n\t\tprompt: string,\n\t\texecutorPattern: string | undefined,\n\t): { decision: RouteDecision; model: Model<Api> } | undefined {\n\t\tif (!executorPattern) return undefined;\n\t\ttry {\n\t\t\tconst verdict = classifyExecutorTurn(prompt, this.deps.getSettingsManager().getToolkitScripts());\n\t\t\tif (!verdict.execute) return undefined;\n\t\t\tconst resolved = resolveCliModel({ cliModel: executorPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (!resolved.model || !this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) return undefined;\n\t\t\t// Fitness gate: the executor must have PROVEN tool-calling on this host (same\n\t\t\t// canonical-ref discipline as the curation gate).\n\t\t\tif (!this._evaluateModelFitness(\"executor\", resolved.model).fit) return undefined;\n\t\t\tthis._lastModelRouterIntent = \"research\";\n\t\t\treturn {\n\t\t\t\tdecision: {\n\t\t\t\t\ttier: \"cheap\",\n\t\t\t\t\trisk: \"scoped-write\",\n\t\t\t\t\tconfidence: 1,\n\t\t\t\t\treasonCode: \"executor_direct\",\n\t\t\t\t\treasons: [`Executor lane: Level-0 direct hit on toolkit script \"${verdict.scriptName}\"`],\n\t\t\t\t},\n\t\t\t\tmodel: resolved.model,\n\t\t\t};\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/** True if a run_toolkit_script tool result since `fromIndex` actually EXECUTED (not error/ambiguous). */\n\tprivate _executorTurnExecutedScript(fromIndex: number): boolean {\n\t\tfor (const message of this.deps.getAgent().state.messages.slice(fromIndex)) {\n\t\t\tif ((message as { role?: string }).role !== \"toolResult\") continue;\n\t\t\tif ((message as { toolName?: string }).toolName !== \"run_toolkit_script\") continue;\n\t\t\tif ((message as { isError?: boolean }).isError === true) continue;\n\t\t\tconst outcome = (message as { details?: { outcome?: unknown } }).details?.outcome;\n\t\t\tif (outcome === \"executed\") return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Ask the reflex brain to refine the last user request into an explicit toolkit instruction. */\n\tprivate async _buildExecutorRefinedPrompt(messages: AgentMessage | AgentMessage[]): Promise<string | undefined> {\n\t\ttry {\n\t\t\tconst model = this.deps.resolveCurationModelIfFit();\n\t\t\tif (!model) return undefined;\n\t\t\tconst list = Array.isArray(messages) ? messages : [messages];\n\t\t\tconst request = latestUserPromptText(list);\n\t\t\tif (!request) return undefined;\n\t\t\tconst scripts = this.deps.getSettingsManager().getToolkitScripts();\n\t\t\tconst plan = await runReflexInterpreterCompletion({\n\t\t\t\trequest,\n\t\t\t\tscripts,\n\t\t\t\tmodel,\n\t\t\t\tlaneKind: \"executor\",\n\t\t\t\tusageKind: \"executor-brain\",\n\t\t\t\tusageLabel: \"executor-brain-warmup\",\n\t\t\t\tsessionId: this.deps.getSessionManager().getSessionId(),\n\t\t\t\tcompletionRunner: this.deps,\n\t\t\t\tusageReporter: this.deps,\n\t\t\t});\n\t\t\tif (!plan || plan.script === \"none\") return undefined;\n\t\t\tconst argHint = plan.args.length > 0 ? ` with args ${JSON.stringify(plan.args)}` : \"\";\n\t\t\treturn `Run the toolkit script \"${plan.script}\"${argHint} using run_toolkit_script, then report its result exactly.`;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate _resolveModelRouterTurnRoute(prompt: string): { decision: RouteDecision; model: Model<Api> } | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (!settings.enabled) {\n\t\t\tthis._lastModelRouterSkipReason = \"disabled\";\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Executor lane: a Level-0 DIRECT toolkit hit on a command-shaped prompt routes the\n\t\t// whole turn to the configured local executor (tool-call-fitness-gated) instead of\n\t\t// spending the frontier model on a one-tool reflex. Ambiguity never routes here — it\n\t\t// stays with the big model and the reflex brain. Deterministic, so the judge is skipped.\n\t\tconst executorRoute = this._resolveExecutorRoute(prompt, settings.executorModel);\n\t\tif (executorRoute) return executorRoute;\n\n\t\tconst decision = classifyModelRouterRoute(prompt);\n\t\tthis._lastModelRouterIntent = decision.tier === \"cheap\" ? \"research\" : \"modify\";\n\n\t\t// Learning tier must not be selected for normal user prompts\n\t\tif (decision.tier === \"learning\") {\n\t\t\tthis._lastModelRouterSkipReason = \"learning tier not supported for user prompts\";\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst modelPattern =\n\t\t\tsettings[\n\t\t\t\tdecision.tier === \"cheap\" ? \"cheapModel\" : decision.tier === \"medium\" ? \"mediumModel\" : \"expensiveModel\"\n\t\t\t];\n\t\tconst label =\n\t\t\tdecision.tier === \"cheap\" ? \"cheap model\" : decision.tier === \"medium\" ? \"medium model\" : \"expensive model\";\n\n\t\tif (decision.tier === \"medium\" && (!modelPattern || !this._isModelAvailableAndAuthed(modelPattern))) {\n\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\tdecision,\n\t\t\t\t\"medium_unavailable_fallback_expensive\",\n\t\t\t\t\"Medium model is unavailable, falling back to expensive model\",\n\t\t\t);\n\t\t\tif (fallback) return fallback;\n\t\t\tthis._lastModelRouterSkipReason ??= \"medium model and expensive fallback are unavailable\";\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (!modelPattern) {\n\t\t\tthis._lastModelRouterSkipReason = `${label} unset`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst resolved = resolveCliModel({ cliModel: modelPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) {\n\t\t\tthis._lastModelRouterSkipReason = `${label} unresolved: ${modelPattern}`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst resolvedName = formatModelRouterModel(resolved.model);\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\tthis._lastModelRouterSkipReason = `${label} missing auth: ${resolvedName}`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (this.deps.isModelExhausted(resolved.model)) {\n\t\t\tif (decision.tier === \"medium\") {\n\t\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\t\tdecision,\n\t\t\t\t\t\"medium_exhausted_fallback_expensive\",\n\t\t\t\t\t\"Medium model exhausted: quota; falling back to expensive model\",\n\t\t\t\t);\n\t\t\t\tif (fallback) return fallback;\n\t\t\t}\n\t\t\tthis._lastModelRouterSkipReason = `${decision.tier} model exhausted: quota`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// For a LOCAL/MANAGED tier model (never cloud — isLocalOrManagedRouterModel), honor a\n\t\t// persisted \"no working tool-call path\" probe verdict. This is an ALWAYS-ON doctrine gate,\n\t\t// deliberately not behind the opt-in `fitnessGate` setting below (cloud fitness gating stays\n\t\t// opt-in; this local/managed check is unconditional, matching the auto-probe that writes\n\t\t// the verdict). \"native\"/\"text-protocol\"/unprobed all fall through unchanged: native wins\n\t\t// when it works, the shared model-tool-protocol resolver engages the calibrated text dialect,\n\t\t// and an unprobed model routes native-first (the evidence loop, not a speculative pre-block).\n\t\tif (isLocalOrManagedRouterModel(resolved.model) && this.deps.getToolProbeVerdict(resolved.model) === \"none\") {\n\t\t\tif (decision.tier === \"medium\") {\n\t\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\t\tdecision,\n\t\t\t\t\t\"medium_no_tool_path_fallback_expensive\",\n\t\t\t\t\t\"Medium model has no working tool-call path (native and text-protocol probe both failed); falling back to expensive model\",\n\t\t\t\t);\n\t\t\t\tif (fallback) return fallback;\n\t\t\t}\n\t\t\tthis._lastModelRouterSkipReason = `${decision.tier} model has no working tool-call path (native and text-protocol probe both failed)`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (settings.fitnessGate) {\n\t\t\tconst verdict = this._evaluateModelFitness(this._routerSurfaceForTier(decision.tier), resolved.model);\n\t\t\tif (!verdict.fit) {\n\t\t\t\tif (decision.tier === \"medium\") {\n\t\t\t\t\tconst failure = this._formatFitnessFailure(verdict);\n\t\t\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\t\t\tdecision,\n\t\t\t\t\t\t\"medium_unfit_fallback_expensive\",\n\t\t\t\t\t\t`Medium model is unfit (${failure}); falling back to expensive model`,\n\t\t\t\t\t);\n\t\t\t\t\tif (fallback) return fallback;\n\t\t\t\t}\n\t\t\t\tthis._lastModelRouterSkipReason = `${decision.tier} model unfit: ${this._formatFitnessFailure(verdict)} (fitness gate)`;\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tthis._lastModelRouterSkipReason = undefined;\n\t\tdecision.model = resolvedName;\n\t\treturn { decision, model: resolved.model };\n\t}\n\n\tprivate _resolveModelRouterModelForIntent(intent: ModelRouterIntent): Model<Api> | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst modelPattern = intent === \"research\" ? settings.cheapModel : settings.expensiveModel;\n\t\tif (!modelPattern) return undefined;\n\t\tconst resolved = resolveCliModel({ cliModel: modelPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) return undefined;\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) return undefined;\n\t\treturn this.deps.isModelExhausted(resolved.model) ? undefined : resolved.model;\n\t}\n\n\tresolveConfiguredTierModel(tier: \"cheap\" | \"medium\" | \"expensive\"): Model<Api> | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst pattern =\n\t\t\ttier === \"cheap\" ? settings.cheapModel : tier === \"medium\" ? settings.mediumModel : settings.expensiveModel;\n\t\tif (!pattern) return undefined;\n\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) return undefined;\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) return undefined;\n\t\tif (this.deps.isModelExhausted(resolved.model)) return undefined;\n\t\t// (Same doctrine as _resolveModelRouterTurnRoute above): never resolve a local/managed\n\t\t// model the probe has already graded as having no working tool-call path.\n\t\tif (isLocalOrManagedRouterModel(resolved.model) && this.deps.getToolProbeVerdict(resolved.model) === \"none\") {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn resolved.model;\n\t}\n\n\t/**\n\t * Router resolution with the routing judge (auto-on with the router): the regex classifier's\n\t * decision is the baseline; when a judge model resolves (judgeModel, else mediumModel), one\n\t * bounded, tool-less completion may move the tier between cheap/medium/expensive — never to\n\t * learning. Core rule encoded in the judge prompt: planning is never cheap unless genuinely\n\t * trivial. Every fallback stays visible in the decision reasons, and judge spend reports\n\t * through spawned-usage accounting.\n\t */\n\tasync resolveTurnRouteJudged(\n\t\tprompt: string,\n\t\toptions?: { skipJudge?: boolean },\n\t): Promise<{ decision: RouteDecision; model: Model<Api> } | undefined> {\n\t\tconst baseline = this._resolveModelRouterTurnRoute(prompt);\n\t\tif (!baseline) return undefined;\n\t\tif (options?.skipJudge) return baseline;\n\t\t// Deterministic executor routes need no judge (Level-0 already decided).\n\t\tif (baseline.decision.reasonCode === \"executor_direct\") return baseline;\n\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (!settings.judgeEnabled) return baseline;\n\t\tif (shouldSkipRouteJudgeForStaticDecision(baseline.decision)) return baseline;\n\t\tconst judgePattern = settings.judgeModel ?? settings.mediumModel;\n\t\tif (!judgePattern) return baseline;\n\t\tconst judgeModel = this.deps.resolveLaneModel(judgePattern);\n\t\tif (!judgeModel) {\n\t\t\treturn {\n\t\t\t\tdecision: withJudgeUnavailableFallback(\n\t\t\t\t\tbaseline.decision,\n\t\t\t\t\t`routing judge unavailable: ${judgePattern} did not resolve; baseline kept`,\n\t\t\t\t),\n\t\t\t\tmodel: baseline.model,\n\t\t\t};\n\t\t}\n\t\tif (settings.fitnessGate) {\n\t\t\tconst verdict = this._evaluateModelFitness(\"router_judge\", judgeModel);\n\t\t\tif (!verdict.fit) {\n\t\t\t\treturn {\n\t\t\t\t\tdecision: {\n\t\t\t\t\t\t...baseline.decision,\n\t\t\t\t\t\treasons: [\n\t\t\t\t\t\t\t...baseline.decision.reasons,\n\t\t\t\t\t\t\t`routing judge skipped: ${formatModelRouterModel(judgeModel)} unfit (${this._formatFitnessFailure(verdict)})`,\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t\tmodel: baseline.model,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tlet spentUsage: Usage | undefined;\n\t\tconst judged = await runRouteJudge({\n\t\t\tprompt,\n\t\t\tbaseline: baseline.decision,\n\t\t\tsignal: this.deps.getReflectionSignal(),\n\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\tconst completion = await runIsolatedTextCompletion(this.deps, {\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tuserPrompt,\n\t\t\t\t\tmodel: judgeModel,\n\t\t\t\t\t// Per-tier thinking: judgeThinking overrides the judge's own completion; unset\n\t\t\t\t\t// keeps today's \"off\" (the judge is a cheap classification call by default).\n\t\t\t\t\tthinkingLevel: settings.judgeThinking ?? \"off\",\n\t\t\t\t\tmaxTokens: ROUTE_JUDGE_MAX_OUTPUT_TOKENS,\n\t\t\t\t\tsignal,\n\t\t\t\t\t// The judge system prompt is static — the provider can cache the prefix.\n\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t// Stable per-lane synthetic affinity key so repeat judge calls hit the same\n\t\t\t\t\t// cache-warm backend.\n\t\t\t\t\tlaneKind: \"route-judge\",\n\t\t\t\t});\n\t\t\t\tspentUsage = completion.usage;\n\t\t\t\treturn completion;\n\t\t\t},\n\t\t});\n\t\tif (spentUsage) {\n\t\t\treportSpawnedUsage(this.deps, spentUsage, {\n\t\t\t\tkind: \"route-judge\",\n\t\t\t\tlabel: \"router-judge\",\n\t\t\t\tsessionId: this.deps.getSessionManager().getSessionId(),\n\t\t\t\tidentity: prompt,\n\t\t\t});\n\t\t}\n\n\t\tif (!judged.verdict || judged.decision.tier === baseline.decision.tier) {\n\t\t\t// Same tier (or judge fell back): keep the baseline model, carry the annotated decision.\n\t\t\treturn { decision: judged.decision, model: baseline.model };\n\t\t}\n\n\t\tconst judgedTier = judged.decision.tier;\n\t\tif (judgedTier !== \"cheap\" && judgedTier !== \"medium\" && judgedTier !== \"expensive\") {\n\t\t\treturn { decision: baseline.decision, model: baseline.model };\n\t\t}\n\t\tconst judgedModel = this.resolveConfiguredTierModel(judgedTier);\n\t\tif (!judgedModel) {\n\t\t\treturn {\n\t\t\t\tdecision: {\n\t\t\t\t\t...baseline.decision,\n\t\t\t\t\treasons: [\n\t\t\t\t\t\t...baseline.decision.reasons,\n\t\t\t\t\t\t`Route judge chose ${judgedTier} but no model resolves for that tier; baseline kept`,\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tmodel: baseline.model,\n\t\t\t};\n\t\t}\n\t\treturn { decision: { ...judged.decision, model: formatModelRouterModel(judgedModel) }, model: judgedModel };\n\t}\n\n\t// biome-ignore lint/correctness/noUnusedPrivateClassMembers: test seam\n\tprivate _resolveModelRouterTurnModel(prompt: string): Model<Api> | undefined {\n\t\tconst resolved = this._resolveModelRouterTurnRoute(prompt);\n\t\treturn resolved?.model;\n\t}\n\n\tgetStatus(formatLabel?: (label: string) => string): string {\n\t\tconst recentDecisions = getRecentModelRouterDecisions(this.deps.getSessionManager().getEntries());\n\t\tconst lastDecision = this._lastModelRouterDecision ?? recentDecisions.at(-1);\n\t\tconst historicalDecisions = this._lastModelRouterDecision ? recentDecisions : recentDecisions.slice(0, -1);\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst lines = [\n\t\t\tformatModelRouterStatus(\n\t\t\t\tsettings,\n\t\t\t\tlastDecision,\n\t\t\t\tformatLabel,\n\t\t\t\thistoricalDecisions,\n\t\t\t\tthis._lastModelRouterSkipReason,\n\t\t\t\tthis._lastModelRouterIntent ?? lastDecision?.intent,\n\t\t\t\tsettings.fitnessGate ? this._getRouterTierFitnessStatuses() : undefined,\n\t\t\t\tthis.deps.getFailoverStatus(),\n\t\t\t),\n\t\t];\n\t\tconst diagnostics = collectModelRouterConfigDiagnostics(\n\t\t\tsettings,\n\t\t\tthis.deps.getModelRegistry(),\n\t\t\tthis.deps.getAgentDir(),\n\t\t);\n\t\tif (diagnostics.length > 0) {\n\t\t\tlines.push(formatLabel ? formatLabel(\"Config diagnostics:\") : \"Config diagnostics:\");\n\t\t\tfor (const diagnostic of diagnostics) {\n\t\t\t\tlines.push(`- ${diagnostic}`);\n\t\t\t}\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tasync runRoutedTurn(\n\t\tmessages: AgentMessage | AgentMessage[],\n\t\troutedModel: Model<Api> | undefined,\n\t\trouteDecision: RouteDecision | undefined,\n\t\tpersistDecision = true,\n\t): Promise<void> {\n\t\tif (!routedModel) {\n\t\t\tawait this.deps.runAgentPrompt(messages);\n\t\t\treturn;\n\t\t}\n\n\t\tconst agent = this.deps.getAgent();\n\t\tconst previousModel = agent.state.model;\n\t\tconst previousThinkingLevel = agent.state.thinkingLevel;\n\t\tconst previousTurnTools = agent.state.tools;\n\t\tconst previousSystemPrompt = agent.state.systemPrompt;\n\t\t// Swap bookkeeping: the exact references the swap below assigns, so the finally can\n\t\t// restore ONLY what IT put there — never assigned when no swap happens (e.g. a full-class\n\t\t// routed profile).\n\t\tlet swappedTools: typeof previousTurnTools | undefined;\n\t\tlet swappedSystemPrompt: typeof previousSystemPrompt | undefined;\n\t\tconst previousActiveModelRouterIntent = this._activeModelRouterIntent;\n\t\tconst previousActiveModelRouterRoute = this._activeModelRouterRoute;\n\t\tconst previousModelRouterSessionBuffer = this._modelRouterSessionBuffer;\n\t\tconst previousModelRouterEscalationRequested = this._modelRouterEscalationRequested;\n\t\tconst bufferRoutedTurn = routeDecision?.tier === \"cheap\";\n\t\tconst originalHistoryLength = agent.state.messages.length;\n\t\tlet retryModel: Model<Api> | undefined;\n\t\tlet completedDecision: ModelRouterDecisionStatus | undefined = routeDecision\n\t\t\t? {\n\t\t\t\t\troute: routeDecision,\n\t\t\t\t\troutedModel: formatModelRouterModel(routedModel),\n\t\t\t\t\toutcome: \"routed\",\n\t\t\t\t\tintent: routeDecision.tier === \"cheap\" ? \"research\" : \"modify\",\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tlet thrownError: unknown;\n\t\tif (routeDecision) {\n\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t}\n\t\tthis._activeModelRouterIntent = routeDecision\n\t\t\t? routeDecision.tier === \"cheap\"\n\t\t\t\t? \"research\"\n\t\t\t\t: \"modify\"\n\t\t\t: undefined;\n\t\tthis._activeModelRouterRoute = routeDecision;\n\t\tif (bufferRoutedTurn) {\n\t\t\tthis._modelRouterSessionBuffer = createModelRouterSessionBuffer();\n\t\t\tthis._modelRouterEscalationRequested = false;\n\t\t}\n\t\tconst routerThinkingSettings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst configuredThinking = !routeDecision\n\t\t\t? undefined\n\t\t\t: routeDecision.reasonCode === \"executor_direct\"\n\t\t\t\t? routerThinkingSettings.executorThinking\n\t\t\t\t: routeDecision.tier === \"cheap\"\n\t\t\t\t\t? routerThinkingSettings.cheapThinking\n\t\t\t\t\t: routeDecision.tier === \"medium\"\n\t\t\t\t\t\t? routerThinkingSettings.mediumThinking\n\t\t\t\t\t\t: routeDecision.tier === \"expensive\"\n\t\t\t\t\t\t\t? routerThinkingSettings.expensiveThinking\n\t\t\t\t\t\t\t: undefined;\n\t\tconst routedThinkingLevel = clampThinkingLevel(\n\t\t\troutedModel,\n\t\t\tconfiguredThinking ?? previousThinkingLevel,\n\t\t) as ThinkingLevel;\n\t\tconst modelChanged = !modelsAreEqual(this.deps.getModel(), routedModel);\n\t\tconst thinkingChanged = routedThinkingLevel !== previousThinkingLevel;\n\t\tif (modelChanged || thinkingChanged) {\n\t\t\tagent.state.model = routedModel;\n\t\t\t// Per-tier thinking: a configured tier/executor thinking level overrides the inherited\n\t\t\t// session thinking for THIS routed turn only; unset falls back to exactly today's\n\t\t\t// inherit-and-clamp behavior. Executor routes carry tier \"cheap\" too, so reasonCode is\n\t\t\t// checked first — otherwise an executor turn would silently pick up cheapThinking instead.\n\t\t\t// The judge's own completion has a separate knob (judgeThinking) applied at its call site.\n\t\t\tagent.state.thinkingLevel = routedThinkingLevel;\n\t\t\t// Capability tool-filtering follows the ROUTED model for the turn. Without this a\n\t\t\t// cheap/local routed model inherits the session model's full tool surface — schemas it\n\t\t\t// pays for on every request and may not be able to drive at all.\n\t\t\tif (modelChanged) {\n\t\t\t\tconst routedProfile = deriveModelCapabilityProfile({\n\t\t\t\t\tcontextWindow: routedModel.contextWindow,\n\t\t\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t\t\t});\n\t\t\t\tif (routedProfile.class !== \"full\") {\n\t\t\t\t\tconst allowed = new Set(\n\t\t\t\t\t\tfilterToolNamesForCapability(\n\t\t\t\t\t\t\tpreviousTurnTools.map((tool) => tool.name),\n\t\t\t\t\t\t\troutedProfile,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tswappedTools = previousTurnTools.filter((tool) => allowed.has(tool.name));\n\t\t\t\t\tagent.state.tools = swappedTools;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// The routed prompt follows the routed tool surface and keeps provider-neutral delegation\n\t\t\t// guidance whenever delegate remains active, including same-model thinking overrides.\n\t\t\t// Per-turn only; a live extension override is preserved rather than silently replaced.\n\t\t\tif (agent.state.systemPrompt === this.deps.getBaseSystemPrompt()) {\n\t\t\t\tswappedSystemPrompt = this.deps.buildSystemPromptForToolNames(agent.state.tools.map((tool) => tool.name));\n\t\t\t\tagent.state.systemPrompt = swappedSystemPrompt;\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tawait this.deps.runAgentPrompt(messages);\n\t\t\t// Speculative muscle-retry: an executor-routed turn is a bet that the\n\t\t\t// small model can run the toolkit command directly. If it ends WITHOUT a successful\n\t\t\t// run_toolkit_script execution, retry ONCE on the same executor with the brain's\n\t\t\t// refined instruction injected — the brain warms while the muscle tries, so the retry\n\t\t\t// pays only when the muscle actually missed.\n\t\t\tif (\n\t\t\t\trouteDecision?.reasonCode === \"executor_direct\" &&\n\t\t\t\t!this._isModelRouterRetry &&\n\t\t\t\t!this._executorTurnExecutedScript(originalHistoryLength)\n\t\t\t) {\n\t\t\t\tconst refined = await this._buildExecutorRefinedPrompt(messages);\n\t\t\t\tif (refined) {\n\t\t\t\t\tagent.state.messages.splice(originalHistoryLength);\n\t\t\t\t\tif (bufferRoutedTurn) this._modelRouterSessionBuffer = createModelRouterSessionBuffer();\n\t\t\t\t\tawait this.deps.runAgentPrompt([\n\t\t\t\t\t\t{ role: \"user\", content: [{ type: \"text\", text: refined }], timestamp: Date.now() },\n\t\t\t\t\t]);\n\t\t\t\t\tcompletedDecision = {\n\t\t\t\t\t\troute: {\n\t\t\t\t\t\t\t...routeDecision,\n\t\t\t\t\t\t\treasonCode: \"executor_speculative_retry\",\n\t\t\t\t\t\t\treasons: [\n\t\t\t\t\t\t\t\t...routeDecision.reasons,\n\t\t\t\t\t\t\t\t\"Executor missed on first try; retried with brain-refined instruction\",\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\troutedModel: formatModelRouterModel(routedModel),\n\t\t\t\t\t\toutcome: \"routed\",\n\t\t\t\t\t\tintent: \"research\",\n\t\t\t\t\t};\n\t\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t\t} else {\n\t\t\t\t\t// The muscle missed AND the reflex brain could not refine the request into a toolkit\n\t\t\t\t\t// instruction (no fit brain model, or no confident plan). There is deliberately NO\n\t\t\t\t\t// frontier fallback here, so surface the miss instead of letting it stand silently —\n\t\t\t\t\t// otherwise the routed turn just ends with an unrun command and no explanation.\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Executor lane: the toolkit command did not run and the reflex brain could not refine it into an explicit instruction; leaving the turn as-is (no automatic escalation).\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (bufferRoutedTurn && this._modelRouterEscalationRequested) {\n\t\t\t\tagent.state.messages.splice(originalHistoryLength);\n\t\t\t\tretryModel = this._resolveModelRouterModelForIntent(\"modify\") ?? previousModel;\n\t\t\t\tcompletedDecision = {\n\t\t\t\t\troute: routeDecision!,\n\t\t\t\t\troutedModel: formatModelRouterModel(routedModel),\n\t\t\t\t\toutcome: \"escalated\",\n\t\t\t\t\tretryModel: formatModelRouterModel(retryModel),\n\t\t\t\t\tintent: routeDecision!.tier === \"cheap\" ? \"research\" : \"modify\",\n\t\t\t\t};\n\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t} else if (bufferRoutedTurn && this._modelRouterSessionBuffer) {\n\t\t\t\tflushModelRouterSessionBuffer(\n\t\t\t\t\tthis._modelRouterSessionBuffer,\n\t\t\t\t\t(message) => {\n\t\t\t\t\t\tthis.deps.getSessionManager().appendMessage(message);\n\t\t\t\t\t},\n\t\t\t\t\t(customType, content, display, details) => {\n\t\t\t\t\t\tthis.deps.getSessionManager().appendCustomMessageEntry(customType, content, display, details);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrownError = error;\n\t\t\t// Mirror the escalation splice above (~:812): a buffered cheap-tier turn never flushes its\n\t\t\t// live messages to the session on a genuine throw, so agent.state.messages must be rolled\n\t\t\t// back to the pre-turn length here too — otherwise the never-persisted buffered messages\n\t\t\t// permanently diverge from the persisted session (same shape as the W1.3 ghost-turn bug,\n\t\t\t// but on the error path instead of the success/escalation paths).\n\t\t\tif (bufferRoutedTurn) {\n\t\t\t\tagent.state.messages.splice(originalHistoryLength);\n\t\t\t}\n\t\t\tif (completedDecision) {\n\t\t\t\tcompletedDecision = { ...completedDecision, outcome: \"failed\" };\n\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t}\n\t\t} finally {\n\t\t\t// Restore the pre-route model ONLY if the routed model is still in place: a command\n\t\t\t// handler may have legitimately changed the session model mid-turn (setModel or a\n\t\t\t// provider re-registration), and clobbering that would silently undo the change.\n\t\t\tif (modelsAreEqual(agent.state.model, routedModel)) {\n\t\t\t\tagent.state.model = previousModel;\n\t\t\t\tagent.state.thinkingLevel = previousThinkingLevel;\n\t\t\t\t// Symmetric restore: undo tools/systemPrompt only if each is STILL the exact\n\t\t\t\t// reference/string the swap above assigned (never assigned at all when the routed\n\t\t\t\t// profile was full-class — then there is nothing to restore either). An extension calling\n\t\t\t\t// setActiveToolsByName mid-turn reassigns both to its own values without touching the\n\t\t\t\t// model — the model guard above still passes, but that live change is legitimate and must\n\t\t\t\t// survive rather than being silently reverted to the stale pre-turn snapshot.\n\t\t\t\tif (swappedTools !== undefined && agent.state.tools === swappedTools) {\n\t\t\t\t\tagent.state.tools = previousTurnTools;\n\t\t\t\t}\n\t\t\t\tif (swappedSystemPrompt !== undefined && agent.state.systemPrompt === swappedSystemPrompt) {\n\t\t\t\t\tagent.state.systemPrompt = previousSystemPrompt;\n\t\t\t\t}\n\t\t\t\t// The registry may have changed mid-turn (command-time registerProvider): re-resolve\n\t\t\t\t// the restored model so a provider override is not dropped with the routed model.\n\t\t\t\tthis.deps.refreshCurrentModelFromRegistry();\n\t\t\t}\n\t\t\tthis._activeModelRouterIntent = previousActiveModelRouterIntent;\n\t\t\tthis._activeModelRouterRoute = previousActiveModelRouterRoute;\n\t\t\tthis._modelRouterSessionBuffer = previousModelRouterSessionBuffer;\n\t\t\tthis._modelRouterEscalationRequested = previousModelRouterEscalationRequested;\n\t\t}\n\n\t\tif (retryModel && !thrownError) {\n\t\t\tconst previousIsModelRouterRetry = this._isModelRouterRetry;\n\t\t\ttry {\n\t\t\t\tthis._isModelRouterRetry = true;\n\t\t\t\tconst retryDecision: RouteDecision = {\n\t\t\t\t\ttier: \"expensive\",\n\t\t\t\t\trisk: \"high-impact\",\n\t\t\t\t\tconfidence: 1.0,\n\t\t\t\t\treasonCode: \"cheap_mutating_tool_escalation\",\n\t\t\t\t\treasons: [\"Cheap research turn attempted a mutating tool and escalated\"],\n\t\t\t\t\tfallbackFrom: \"cheap\",\n\t\t\t\t\tmodel: formatModelRouterModel(retryModel),\n\t\t\t\t};\n\t\t\t\tawait this.runRoutedTurn(messages, retryModel, retryDecision, false);\n\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t} catch (error) {\n\t\t\t\tthrownError = error;\n\t\t\t\tif (completedDecision) {\n\t\t\t\t\tcompletedDecision = { ...completedDecision, outcome: \"failed\" };\n\t\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis._isModelRouterRetry = previousIsModelRouterRetry;\n\t\t\t}\n\t\t}\n\n\t\tif (persistDecision && completedDecision) {\n\t\t\tpersistModelRouterDecision(this.deps.getSessionManager(), completedDecision);\n\t\t\t// One route event per user-facing routed turn (the escalation retry runs with\n\t\t\t// persistDecision=false, so it does not double-emit). Codes/numbers only — no prompt text.\n\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.routeDecision,\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tpayload: {\n\t\t\t\t\ttier: completedDecision.route.tier,\n\t\t\t\t\trisk: completedDecision.route.risk,\n\t\t\t\t\treasonCode: completedDecision.route.reasonCode,\n\t\t\t\t\tconfidence: completedDecision.route.confidence,\n\t\t\t\t\toutcome: completedDecision.outcome,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tif (thrownError) {\n\t\t\tthrow thrownError;\n\t\t}\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capability-gateway.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/capability-gateway.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;
|
|
1
|
+
{"version":3,"file":"capability-gateway.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/capability-gateway.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAUlF,OAAO,KAAK,EAAE,oBAAoB,EAAE,cAAc,EAA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