@caupulican/pi-adaptative 0.81.21 → 0.81.22
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 +7 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +4 -4
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/model-router/intent-classifier.d.ts.map +1 -1
- package/dist/core/model-router/intent-classifier.js +1 -1
- package/dist/core/model-router/intent-classifier.js.map +1 -1
- package/dist/core/model-router/route-judge.d.ts.map +1 -1
- package/dist/core/model-router/route-judge.js +10 -6
- package/dist/core/model-router/route-judge.js.map +1 -1
- package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
- package/dist/core/model-router/tool-escalation.js +2 -1
- package/dist/core/model-router/tool-escalation.js.map +1 -1
- package/dist/core/model-router-controller.d.ts.map +1 -1
- package/dist/core/model-router-controller.js +27 -2
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +3 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +25 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- 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 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intent-classifier.d.ts","sourceRoot":"","sources":["../../../src/core/model-router/intent-classifier.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAE9D,MAAM,MAAM,iBAAiB,GAAG,UAAU,GAAG,QAAQ,CAAC;AAiCtD,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,CA0ItE;AAED,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,iBAAiB,CAG3E","sourcesContent":["import type { RouteDecision } from \"../autonomy/contracts.ts\";\n\nexport type ModelRouterIntent = \"research\" | \"modify\";\n\nconst EXPLICIT_MODIFY_REQUEST_RE =\n\t/^(?:can you|could you|please|pls|go ahead and|let'?s|i need you to|we need to|you should)\\s+.*\\b(add|apply|build|change|commit|create|delete|edit|fix|generate|implement|install|modify|patch|refactor|remove|rename|replace|run|test|update|write|publish|release|push|deploy|tag|reset|clean|rewrite)\\b/i;\n\nconst READ_ONLY_QUESTION_RE =\n\t/^(?:(?:can you|could you|please|pls|go ahead and|let'?s|i need you to|we need to|you should)\\s+)?(?:how|what|why|when|where|which|who|explain|summarize|compare|describe|list|show|search|find|view|read|locate)\\b/i;\n\nconst RELEASE_PUBLISH_RE = /\\b(publish|release|push|deploy|tag)\\b/i;\nconst SECURITY_AUTH_RE = /\\b(auth|token|credential|credentials|secret|api[-_]key)\\b/i;\nconst DESTRUCTIVE_RE = /\\b(delete|reset|rm\\s+-rf|clean)\\b/i;\n\nconst SELF_MOD_MUTATE_RE =\n\t/\\b(modify|change|write|update|edit|delete|add|remove)\\s+.*\\b(skills|prompts|settings|tools|behavior)\\b|self[-_]modification/i;\nconst ARCHITECTURE_MUTATE_RE = /\\b(rewrite|redesign|change|modify|rearchitect)\\s+.*\\b(architecture|architect)\\b/i;\n\n// Planning floor: plans steer all downstream work, so planning never routes cheap by default.\n// Only the route judge may downgrade a planning prompt back to cheap (explicit trivial verdict).\n// Core terms are always planning; design/architecture words count only with prospective phrasing,\n// so lookups like \"show me the architecture\" stay cheap.\nconst PLANNING_CORE_RE = /\\b(plan|planning|roadmap|strategy)\\b/i;\nconst PLANNING_DESIGN_WORD_RE = /\\b(design|architect\\w*|structure|approach)\\b/i;\nconst PLANNING_PROSPECTIVE_RE =\n\t/\\b(how (?:should|would|do we|can we)|what(?:'s| is) the best|propose|draft|come up with|figure out|decide (?:on|how))\\b/i;\n\nfunction isPlanningPrompt(text: string): boolean {\n\treturn PLANNING_CORE_RE.test(text) || (PLANNING_DESIGN_WORD_RE.test(text) && PLANNING_PROSPECTIVE_RE.test(text));\n}\n\nconst REFACTOR_RE = /\\b(refactor|refactoring)\\b/i;\nconst TEST_VALIDATION_RE = /\\b(test|testing|validation|lint|vitest|jest|run)\\b/i;\nconst IMPLEMENT_RE = /\\b(implement|fix|apply|change|update|create|write|generate|modify|edit|patch|add)\\b/i;\n\nexport function classifyModelRouterRoute(prompt: string): RouteDecision {\n\tconst text = prompt.trim();\n\n\tif (text.length === 0) {\n\t\treturn {\n\t\t\ttier: \"cheap\",\n\t\t\trisk: \"read-only\",\n\t\t\tconfidence: 0.1,\n\t\t\treasonCode: \"empty_prompt\",\n\t\t\treasons: [\"Empty or whitespace prompt\"],\n\t\t};\n\t}\n\n\t// 1. Explicit read-only questions/lookups dominate (unless prefixed by explicit mutation verb).\n\t// Planning-shaped questions are the exception: a plan steers expensive downstream work, so the\n\t// floor is medium even when phrased as a question.\n\tif (READ_ONLY_QUESTION_RE.test(text) && !EXPLICIT_MODIFY_REQUEST_RE.test(text)) {\n\t\tif (isPlanningPrompt(text)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"read-only\",\n\t\t\t\tconfidence: 0.75,\n\t\t\t\treasonCode: \"planning_min_medium\",\n\t\t\t\treasons: [\"Planning/design prompts never route cheap by default; a judge may deem them trivial\"],\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\ttier: \"cheap\",\n\t\t\trisk: \"read-only\",\n\t\t\tconfidence: 0.9,\n\t\t\treasonCode: \"read_only_question\",\n\t\t\treasons: [\"Prompt asks a question or requests an explanation, search, or lookup\"],\n\t\t};\n\t}\n\n\t// Helper function to match patterns and return appropriate decision\n\tfunction matchKeywords(input: string): RouteDecision | null {\n\t\t// A. High-risk / approval-required/expensive signals\n\t\tif (RELEASE_PUBLISH_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"release_or_publish\",\n\t\t\t\treasons: [\"Prompt mentions publishing, releasing, pushing, or deploying\"],\n\t\t\t};\n\t\t}\n\t\tif (SECURITY_AUTH_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"high-impact\",\n\t\t\t\tconfidence: 0.95,\n\t\t\t\treasonCode: \"security_or_auth\",\n\t\t\t\treasons: [\"Prompt mentions credentials, authentication, tokens, or secrets\"],\n\t\t\t};\n\t\t}\n\t\tif (DESTRUCTIVE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.85,\n\t\t\t\treasonCode: \"destructive_or_git_history\",\n\t\t\t\treasons: [\"Prompt mentions deleting, resetting, cleaning, or destructive operations\"],\n\t\t\t};\n\t\t}\n\t\tif (SELF_MOD_MUTATE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"settings_or_self_modification\",\n\t\t\t\treasons: [\"Prompt mentions modifying skills, prompts, settings, tools, or self-modification\"],\n\t\t\t};\n\t\t}\n\t\tif (ARCHITECTURE_MUTATE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"high-impact\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"architecture_or_ambiguous\",\n\t\t\t\treasons: [\"Prompt mentions core architecture or rewrite\"],\n\t\t\t};\n\t\t}\n\n\t\t// B. Explicit implementation/scoped-write signals route medium\n\t\tif (isPlanningPrompt(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"read-only\",\n\t\t\t\tconfidence: 0.75,\n\t\t\t\treasonCode: \"planning_min_medium\",\n\t\t\t\treasons: [\"Planning/design prompts never route cheap by default; a judge may deem them trivial\"],\n\t\t\t};\n\t\t}\n\t\tif (REFACTOR_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.8,\n\t\t\t\treasonCode: \"mechanical_refactor\",\n\t\t\t\treasons: [\"Prompt mentions refactoring code structure\"],\n\t\t\t};\n\t\t}\n\t\tif (TEST_VALIDATION_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.8,\n\t\t\t\treasonCode: \"test_or_validation\",\n\t\t\t\treasons: [\"Prompt mentions testing, validation, or linting\"],\n\t\t\t};\n\t\t}\n\t\tif (IMPLEMENT_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.85,\n\t\t\t\treasonCode: \"normal_implementation\",\n\t\t\t\treasons: [\"Prompt mentions implementing, updating, creating, or modifying code\"],\n\t\t\t};\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tconst match = matchKeywords(text);\n\tif (match) {\n\t\treturn match;\n\t}\n\n\t// 4. Default fallbacks\n\treturn {\n\t\ttier: \"cheap\",\n\t\trisk: \"read-only\",\n\t\tconfidence: 0.5,\n\t\treasonCode: \"default_read_only\",\n\t\treasons: [\"No explicit implementation, destructive, or release patterns detected\"],\n\t};\n}\n\nexport function classifyModelRouterIntent(prompt: string): ModelRouterIntent {\n\tconst decision = classifyModelRouterRoute(prompt);\n\treturn decision.tier === \"cheap\" ? \"research\" : \"modify\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"intent-classifier.d.ts","sourceRoot":"","sources":["../../../src/core/model-router/intent-classifier.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAE9D,MAAM,MAAM,iBAAiB,GAAG,UAAU,GAAG,QAAQ,CAAC;AAiCtD,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,CA0ItE;AAED,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,iBAAiB,CAG3E","sourcesContent":["import type { RouteDecision } from \"../autonomy/contracts.ts\";\n\nexport type ModelRouterIntent = \"research\" | \"modify\";\n\nconst EXPLICIT_MODIFY_REQUEST_RE =\n\t/^(?:can you|could you|please|pls|go ahead and|let'?s|i need you to|we need to|you should)\\s+.*\\b(add|apply|build|change|commit|create|delete|edit|fix|generate|implement|install|modify|patch|refactor|remove|rename|replace|run|test|update|write|publish|release|push|deploy|tag|reset|clean|rewrite)\\b/i;\n\nconst READ_ONLY_QUESTION_RE =\n\t/^(?:(?:can you|could you|please|pls|go ahead and|let'?s|i need you to|we need to|you should)\\s+)?(?:how|what|why|when|where|which|who|explain|summarize|compare|describe|list|show|search|find|view|read|locate)\\b/i;\n\nconst RELEASE_PUBLISH_RE = /\\b(publish|release|push|deploy|tag)\\b/i;\nconst SECURITY_AUTH_RE = /\\b(auth|token|credential|credentials|secret|api[-_]key)\\b/i;\nconst DESTRUCTIVE_RE = /\\b(delete|reset|rm\\s+-rf|clean)\\b/i;\n\nconst SELF_MOD_MUTATE_RE =\n\t/\\b(modify|change|write|update|edit|delete|add|remove)\\s+.*\\b(skills|prompts|settings|tools|behavior)\\b|self[-_]modification/i;\nconst ARCHITECTURE_MUTATE_RE = /\\b(rewrite|redesign|change|modify|rearchitect)\\s+.*\\b(architecture|architect)\\b/i;\n\n// Planning floor: plans steer all downstream work, so planning never routes cheap by default.\n// Only the route judge may downgrade a planning prompt back to cheap (explicit trivial verdict).\n// Core terms are always planning; design/architecture words count only with prospective phrasing,\n// so lookups like \"show me the architecture\" stay cheap.\nconst PLANNING_CORE_RE = /\\b(plan|planning|roadmap|strategy)\\b/i;\nconst PLANNING_DESIGN_WORD_RE = /\\b(design|architect\\w*|structure|approach)\\b/i;\nconst PLANNING_PROSPECTIVE_RE =\n\t/\\b(how (?:should|would|do we|can we)|what(?:'s| is) the (?:best|cleanest|right)|propose|draft|come up with|figure out|decide (?:on|how))\\b/i;\n\nfunction isPlanningPrompt(text: string): boolean {\n\treturn PLANNING_CORE_RE.test(text) || (PLANNING_DESIGN_WORD_RE.test(text) && PLANNING_PROSPECTIVE_RE.test(text));\n}\n\nconst REFACTOR_RE = /\\b(refactor|refactoring)\\b/i;\nconst TEST_VALIDATION_RE = /\\b(test|testing|validation|lint|vitest|jest|run)\\b/i;\nconst IMPLEMENT_RE = /\\b(implement|fix|apply|change|update|create|write|generate|modify|edit|patch|add)\\b/i;\n\nexport function classifyModelRouterRoute(prompt: string): RouteDecision {\n\tconst text = prompt.trim();\n\n\tif (text.length === 0) {\n\t\treturn {\n\t\t\ttier: \"cheap\",\n\t\t\trisk: \"read-only\",\n\t\t\tconfidence: 0.1,\n\t\t\treasonCode: \"empty_prompt\",\n\t\t\treasons: [\"Empty or whitespace prompt\"],\n\t\t};\n\t}\n\n\t// 1. Explicit read-only questions/lookups dominate (unless prefixed by explicit mutation verb).\n\t// Planning-shaped questions are the exception: a plan steers expensive downstream work, so the\n\t// floor is medium even when phrased as a question.\n\tif (READ_ONLY_QUESTION_RE.test(text) && !EXPLICIT_MODIFY_REQUEST_RE.test(text)) {\n\t\tif (isPlanningPrompt(text)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"read-only\",\n\t\t\t\tconfidence: 0.75,\n\t\t\t\treasonCode: \"planning_min_medium\",\n\t\t\t\treasons: [\"Planning/design prompts never route cheap by default; a judge may deem them trivial\"],\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\ttier: \"cheap\",\n\t\t\trisk: \"read-only\",\n\t\t\tconfidence: 0.9,\n\t\t\treasonCode: \"read_only_question\",\n\t\t\treasons: [\"Prompt asks a question or requests an explanation, search, or lookup\"],\n\t\t};\n\t}\n\n\t// Helper function to match patterns and return appropriate decision\n\tfunction matchKeywords(input: string): RouteDecision | null {\n\t\t// A. High-risk / approval-required/expensive signals\n\t\tif (RELEASE_PUBLISH_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"release_or_publish\",\n\t\t\t\treasons: [\"Prompt mentions publishing, releasing, pushing, or deploying\"],\n\t\t\t};\n\t\t}\n\t\tif (SECURITY_AUTH_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"high-impact\",\n\t\t\t\tconfidence: 0.95,\n\t\t\t\treasonCode: \"security_or_auth\",\n\t\t\t\treasons: [\"Prompt mentions credentials, authentication, tokens, or secrets\"],\n\t\t\t};\n\t\t}\n\t\tif (DESTRUCTIVE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.85,\n\t\t\t\treasonCode: \"destructive_or_git_history\",\n\t\t\t\treasons: [\"Prompt mentions deleting, resetting, cleaning, or destructive operations\"],\n\t\t\t};\n\t\t}\n\t\tif (SELF_MOD_MUTATE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"settings_or_self_modification\",\n\t\t\t\treasons: [\"Prompt mentions modifying skills, prompts, settings, tools, or self-modification\"],\n\t\t\t};\n\t\t}\n\t\tif (ARCHITECTURE_MUTATE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"high-impact\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"architecture_or_ambiguous\",\n\t\t\t\treasons: [\"Prompt mentions core architecture or rewrite\"],\n\t\t\t};\n\t\t}\n\n\t\t// B. Explicit implementation/scoped-write signals route medium\n\t\tif (isPlanningPrompt(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"read-only\",\n\t\t\t\tconfidence: 0.75,\n\t\t\t\treasonCode: \"planning_min_medium\",\n\t\t\t\treasons: [\"Planning/design prompts never route cheap by default; a judge may deem them trivial\"],\n\t\t\t};\n\t\t}\n\t\tif (REFACTOR_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.8,\n\t\t\t\treasonCode: \"mechanical_refactor\",\n\t\t\t\treasons: [\"Prompt mentions refactoring code structure\"],\n\t\t\t};\n\t\t}\n\t\tif (TEST_VALIDATION_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.8,\n\t\t\t\treasonCode: \"test_or_validation\",\n\t\t\t\treasons: [\"Prompt mentions testing, validation, or linting\"],\n\t\t\t};\n\t\t}\n\t\tif (IMPLEMENT_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.85,\n\t\t\t\treasonCode: \"normal_implementation\",\n\t\t\t\treasons: [\"Prompt mentions implementing, updating, creating, or modifying code\"],\n\t\t\t};\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tconst match = matchKeywords(text);\n\tif (match) {\n\t\treturn match;\n\t}\n\n\t// 4. Default fallbacks\n\treturn {\n\t\ttier: \"cheap\",\n\t\trisk: \"read-only\",\n\t\tconfidence: 0.5,\n\t\treasonCode: \"default_read_only\",\n\t\treasons: [\"No explicit implementation, destructive, or release patterns detected\"],\n\t};\n}\n\nexport function classifyModelRouterIntent(prompt: string): ModelRouterIntent {\n\tconst decision = classifyModelRouterRoute(prompt);\n\treturn decision.tier === \"cheap\" ? \"research\" : \"modify\";\n}\n"]}
|
|
@@ -11,7 +11,7 @@ const ARCHITECTURE_MUTATE_RE = /\b(rewrite|redesign|change|modify|rearchitect)\s
|
|
|
11
11
|
// so lookups like "show me the architecture" stay cheap.
|
|
12
12
|
const PLANNING_CORE_RE = /\b(plan|planning|roadmap|strategy)\b/i;
|
|
13
13
|
const PLANNING_DESIGN_WORD_RE = /\b(design|architect\w*|structure|approach)\b/i;
|
|
14
|
-
const PLANNING_PROSPECTIVE_RE = /\b(how (?:should|would|do we|can we)|what(?:'s| is) the best|propose|draft|come up with|figure out|decide (?:on|how))\b/i;
|
|
14
|
+
const PLANNING_PROSPECTIVE_RE = /\b(how (?:should|would|do we|can we)|what(?:'s| is) the (?:best|cleanest|right)|propose|draft|come up with|figure out|decide (?:on|how))\b/i;
|
|
15
15
|
function isPlanningPrompt(text) {
|
|
16
16
|
return PLANNING_CORE_RE.test(text) || (PLANNING_DESIGN_WORD_RE.test(text) && PLANNING_PROSPECTIVE_RE.test(text));
|
|
17
17
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intent-classifier.js","sourceRoot":"","sources":["../../../src/core/model-router/intent-classifier.ts"],"names":[],"mappings":"AAIA,MAAM,0BAA0B,GAC/B,4SAA4S,CAAC;AAE9S,MAAM,qBAAqB,GAC1B,qNAAqN,CAAC;AAEvN,MAAM,kBAAkB,GAAG,wCAAwC,CAAC;AACpE,MAAM,gBAAgB,GAAG,4DAA4D,CAAC;AACtF,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAE5D,MAAM,kBAAkB,GACvB,8HAA8H,CAAC;AAChI,MAAM,sBAAsB,GAAG,kFAAkF,CAAC;AAElH,8FAA8F;AAC9F,iGAAiG;AACjG,kGAAkG;AAClG,yDAAyD;AACzD,MAAM,gBAAgB,GAAG,uCAAuC,CAAC;AACjE,MAAM,uBAAuB,GAAG,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AW;QACjB,UAAU,EAAE,GAAG;QACf,UAAU,EAAE,mBAAmB;QAC/B,OAAO,EAAE,CAAC,uEAAuE,CAAC;KAClF,CAAC;AAAA,CACF;AAED,MAAM,UAAU,yBAAyB,CAAC,MAAc,EAAqB;IAC5E,MAAM,QAAQ,GAAG,wBAAwB,CAAC,MAAM,CAAC,CAAC;IAClD,OAAO,QAAQ,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;AAAA,CACzD","sourcesContent":["import type { RouteDecision } from \"../autonomy/contracts.ts\";\n\nexport type ModelRouterIntent = \"research\" | \"modify\";\n\nconst EXPLICIT_MODIFY_REQUEST_RE =\n\t/^(?:can you|could you|please|pls|go ahead and|let'?s|i need you to|we need to|you should)\\s+.*\\b(add|apply|build|change|commit|create|delete|edit|fix|generate|implement|install|modify|patch|refactor|remove|rename|replace|run|test|update|write|publish|release|push|deploy|tag|reset|clean|rewrite)\\b/i;\n\nconst READ_ONLY_QUESTION_RE =\n\t/^(?:(?:can you|could you|please|pls|go ahead and|let'?s|i need you to|we need to|you should)\\s+)?(?:how|what|why|when|where|which|who|explain|summarize|compare|describe|list|show|search|find|view|read|locate)\\b/i;\n\nconst RELEASE_PUBLISH_RE = /\\b(publish|release|push|deploy|tag)\\b/i;\nconst SECURITY_AUTH_RE = /\\b(auth|token|credential|credentials|secret|api[-_]key)\\b/i;\nconst DESTRUCTIVE_RE = /\\b(delete|reset|rm\\s+-rf|clean)\\b/i;\n\nconst SELF_MOD_MUTATE_RE =\n\t/\\b(modify|change|write|update|edit|delete|add|remove)\\s+.*\\b(skills|prompts|settings|tools|behavior)\\b|self[-_]modification/i;\nconst ARCHITECTURE_MUTATE_RE = /\\b(rewrite|redesign|change|modify|rearchitect)\\s+.*\\b(architecture|architect)\\b/i;\n\n// Planning floor: plans steer all downstream work, so planning never routes cheap by default.\n// Only the route judge may downgrade a planning prompt back to cheap (explicit trivial verdict).\n// Core terms are always planning; design/architecture words count only with prospective phrasing,\n// so lookups like \"show me the architecture\" stay cheap.\nconst PLANNING_CORE_RE = /\\b(plan|planning|roadmap|strategy)\\b/i;\nconst PLANNING_DESIGN_WORD_RE = /\\b(design|architect\\w*|structure|approach)\\b/i;\nconst PLANNING_PROSPECTIVE_RE =\n\t/\\b(how (?:should|would|do we|can we)|what(?:'s| is) the best|propose|draft|come up with|figure out|decide (?:on|how))\\b/i;\n\nfunction isPlanningPrompt(text: string): boolean {\n\treturn PLANNING_CORE_RE.test(text) || (PLANNING_DESIGN_WORD_RE.test(text) && PLANNING_PROSPECTIVE_RE.test(text));\n}\n\nconst REFACTOR_RE = /\\b(refactor|refactoring)\\b/i;\nconst TEST_VALIDATION_RE = /\\b(test|testing|validation|lint|vitest|jest|run)\\b/i;\nconst IMPLEMENT_RE = /\\b(implement|fix|apply|change|update|create|write|generate|modify|edit|patch|add)\\b/i;\n\nexport function classifyModelRouterRoute(prompt: string): RouteDecision {\n\tconst text = prompt.trim();\n\n\tif (text.length === 0) {\n\t\treturn {\n\t\t\ttier: \"cheap\",\n\t\t\trisk: \"read-only\",\n\t\t\tconfidence: 0.1,\n\t\t\treasonCode: \"empty_prompt\",\n\t\t\treasons: [\"Empty or whitespace prompt\"],\n\t\t};\n\t}\n\n\t// 1. Explicit read-only questions/lookups dominate (unless prefixed by explicit mutation verb).\n\t// Planning-shaped questions are the exception: a plan steers expensive downstream work, so the\n\t// floor is medium even when phrased as a question.\n\tif (READ_ONLY_QUESTION_RE.test(text) && !EXPLICIT_MODIFY_REQUEST_RE.test(text)) {\n\t\tif (isPlanningPrompt(text)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"read-only\",\n\t\t\t\tconfidence: 0.75,\n\t\t\t\treasonCode: \"planning_min_medium\",\n\t\t\t\treasons: [\"Planning/design prompts never route cheap by default; a judge may deem them trivial\"],\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\ttier: \"cheap\",\n\t\t\trisk: \"read-only\",\n\t\t\tconfidence: 0.9,\n\t\t\treasonCode: \"read_only_question\",\n\t\t\treasons: [\"Prompt asks a question or requests an explanation, search, or lookup\"],\n\t\t};\n\t}\n\n\t// Helper function to match patterns and return appropriate decision\n\tfunction matchKeywords(input: string): RouteDecision | null {\n\t\t// A. High-risk / approval-required/expensive signals\n\t\tif (RELEASE_PUBLISH_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"release_or_publish\",\n\t\t\t\treasons: [\"Prompt mentions publishing, releasing, pushing, or deploying\"],\n\t\t\t};\n\t\t}\n\t\tif (SECURITY_AUTH_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"high-impact\",\n\t\t\t\tconfidence: 0.95,\n\t\t\t\treasonCode: \"security_or_auth\",\n\t\t\t\treasons: [\"Prompt mentions credentials, authentication, tokens, or secrets\"],\n\t\t\t};\n\t\t}\n\t\tif (DESTRUCTIVE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.85,\n\t\t\t\treasonCode: \"destructive_or_git_history\",\n\t\t\t\treasons: [\"Prompt mentions deleting, resetting, cleaning, or destructive operations\"],\n\t\t\t};\n\t\t}\n\t\tif (SELF_MOD_MUTATE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"settings_or_self_modification\",\n\t\t\t\treasons: [\"Prompt mentions modifying skills, prompts, settings, tools, or self-modification\"],\n\t\t\t};\n\t\t}\n\t\tif (ARCHITECTURE_MUTATE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"high-impact\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"architecture_or_ambiguous\",\n\t\t\t\treasons: [\"Prompt mentions core architecture or rewrite\"],\n\t\t\t};\n\t\t}\n\n\t\t// B. Explicit implementation/scoped-write signals route medium\n\t\tif (isPlanningPrompt(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"read-only\",\n\t\t\t\tconfidence: 0.75,\n\t\t\t\treasonCode: \"planning_min_medium\",\n\t\t\t\treasons: [\"Planning/design prompts never route cheap by default; a judge may deem them trivial\"],\n\t\t\t};\n\t\t}\n\t\tif (REFACTOR_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.8,\n\t\t\t\treasonCode: \"mechanical_refactor\",\n\t\t\t\treasons: [\"Prompt mentions refactoring code structure\"],\n\t\t\t};\n\t\t}\n\t\tif (TEST_VALIDATION_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.8,\n\t\t\t\treasonCode: \"test_or_validation\",\n\t\t\t\treasons: [\"Prompt mentions testing, validation, or linting\"],\n\t\t\t};\n\t\t}\n\t\tif (IMPLEMENT_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.85,\n\t\t\t\treasonCode: \"normal_implementation\",\n\t\t\t\treasons: [\"Prompt mentions implementing, updating, creating, or modifying code\"],\n\t\t\t};\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tconst match = matchKeywords(text);\n\tif (match) {\n\t\treturn match;\n\t}\n\n\t// 4. Default fallbacks\n\treturn {\n\t\ttier: \"cheap\",\n\t\trisk: \"read-only\",\n\t\tconfidence: 0.5,\n\t\treasonCode: \"default_read_only\",\n\t\treasons: [\"No explicit implementation, destructive, or release patterns detected\"],\n\t};\n}\n\nexport function classifyModelRouterIntent(prompt: string): ModelRouterIntent {\n\tconst decision = classifyModelRouterRoute(prompt);\n\treturn decision.tier === \"cheap\" ? \"research\" : \"modify\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"intent-classifier.js","sourceRoot":"","sources":["../../../src/core/model-router/intent-classifier.ts"],"names":[],"mappings":"AAIA,MAAM,0BAA0B,GAC/B,4SAA4S,CAAC;AAE9S,MAAM,qBAAqB,GAC1B,qNAAqN,CAAC;AAEvN,MAAM,kBAAkB,GAAG,wCAAwC,CAAC;AACpE,MAAM,gBAAgB,GAAG,4DAA4D,CAAC;AACtF,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAE5D,MAAM,kBAAkB,GACvB,8HAA8H,CAAC;AAChI,MAAM,sBAAsB,GAAG,kFAAkF,CAAC;AAElH,8FAA8F;AAC9F,iGAAiG;AACjG,kGAAkG;AAClG,yDAAyD;AACzD,MAAM,gBAAgB,GAAG,uCAAuC,CAAC;AACjE,MAAM,uBAAuB,GAAG,+CAA+C,CAAC;AAChF,MAAM,uBAAuB,GAC5B,6IAA6I,CAAC;AAE/I,SAAS,gBAAgB,CAAC,IAAY,EAAW;IAChD,OAAO,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAAA,CACjH;AAED,MAAM,WAAW,GAAG,6BAA6B,CAAC;AAClD,MAAM,kBAAkB,GAAG,qDAAqD,CAAC;AACjF,MAAM,YAAY,GAAG,sFAAsF,CAAC;AAE5G,MAAM,UAAU,wBAAwB,CAAC,MAAc,EAAiB;IACvE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;IAE3B,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACvB,OAAO;YACN,IAAI,EAAE,OAAO;YACb,IAAI,EAAE,WAAW;YACjB,UAAU,E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;gBACN,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,cAAc;gBACpB,UAAU,EAAE,GAAG;gBACf,UAAU,EAAE,oBAAoB;gBAChC,OAAO,EAAE,CAAC,iDAAiD,CAAC;aAC5D,CAAC;QACH,CAAC;QACD,IAAI,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO;gBACN,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,cAAc;gBACpB,UAAU,EAAE,IAAI;gBAChB,UAAU,EAAE,uBAAuB;gBACnC,OAAO,EAAE,CAAC,qEAAqE,CAAC;aAChF,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAC;IAAA,CACZ;IAED,MAAM,KAAK,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC;IAClC,IAAI,KAAK,EAAE,CAAC;QACX,OAAO,KAAK,CAAC;IACd,CAAC;IAED,uBAAuB;IACvB,OAAO;QACN,IAAI,EAAE,OAAO;QACb,IAAI,EAAE,WAAW;QACjB,UAAU,EAAE,GAAG;QACf,UAAU,EAAE,mBAAmB;QAC/B,OAAO,EAAE,CAAC,uEAAuE,CAAC;KAClF,CAAC;AAAA,CACF;AAED,MAAM,UAAU,yBAAyB,CAAC,MAAc,EAAqB;IAC5E,MAAM,QAAQ,GAAG,wBAAwB,CAAC,MAAM,CAAC,CAAC;IAClD,OAAO,QAAQ,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;AAAA,CACzD","sourcesContent":["import type { RouteDecision } from \"../autonomy/contracts.ts\";\n\nexport type ModelRouterIntent = \"research\" | \"modify\";\n\nconst EXPLICIT_MODIFY_REQUEST_RE =\n\t/^(?:can you|could you|please|pls|go ahead and|let'?s|i need you to|we need to|you should)\\s+.*\\b(add|apply|build|change|commit|create|delete|edit|fix|generate|implement|install|modify|patch|refactor|remove|rename|replace|run|test|update|write|publish|release|push|deploy|tag|reset|clean|rewrite)\\b/i;\n\nconst READ_ONLY_QUESTION_RE =\n\t/^(?:(?:can you|could you|please|pls|go ahead and|let'?s|i need you to|we need to|you should)\\s+)?(?:how|what|why|when|where|which|who|explain|summarize|compare|describe|list|show|search|find|view|read|locate)\\b/i;\n\nconst RELEASE_PUBLISH_RE = /\\b(publish|release|push|deploy|tag)\\b/i;\nconst SECURITY_AUTH_RE = /\\b(auth|token|credential|credentials|secret|api[-_]key)\\b/i;\nconst DESTRUCTIVE_RE = /\\b(delete|reset|rm\\s+-rf|clean)\\b/i;\n\nconst SELF_MOD_MUTATE_RE =\n\t/\\b(modify|change|write|update|edit|delete|add|remove)\\s+.*\\b(skills|prompts|settings|tools|behavior)\\b|self[-_]modification/i;\nconst ARCHITECTURE_MUTATE_RE = /\\b(rewrite|redesign|change|modify|rearchitect)\\s+.*\\b(architecture|architect)\\b/i;\n\n// Planning floor: plans steer all downstream work, so planning never routes cheap by default.\n// Only the route judge may downgrade a planning prompt back to cheap (explicit trivial verdict).\n// Core terms are always planning; design/architecture words count only with prospective phrasing,\n// so lookups like \"show me the architecture\" stay cheap.\nconst PLANNING_CORE_RE = /\\b(plan|planning|roadmap|strategy)\\b/i;\nconst PLANNING_DESIGN_WORD_RE = /\\b(design|architect\\w*|structure|approach)\\b/i;\nconst PLANNING_PROSPECTIVE_RE =\n\t/\\b(how (?:should|would|do we|can we)|what(?:'s| is) the (?:best|cleanest|right)|propose|draft|come up with|figure out|decide (?:on|how))\\b/i;\n\nfunction isPlanningPrompt(text: string): boolean {\n\treturn PLANNING_CORE_RE.test(text) || (PLANNING_DESIGN_WORD_RE.test(text) && PLANNING_PROSPECTIVE_RE.test(text));\n}\n\nconst REFACTOR_RE = /\\b(refactor|refactoring)\\b/i;\nconst TEST_VALIDATION_RE = /\\b(test|testing|validation|lint|vitest|jest|run)\\b/i;\nconst IMPLEMENT_RE = /\\b(implement|fix|apply|change|update|create|write|generate|modify|edit|patch|add)\\b/i;\n\nexport function classifyModelRouterRoute(prompt: string): RouteDecision {\n\tconst text = prompt.trim();\n\n\tif (text.length === 0) {\n\t\treturn {\n\t\t\ttier: \"cheap\",\n\t\t\trisk: \"read-only\",\n\t\t\tconfidence: 0.1,\n\t\t\treasonCode: \"empty_prompt\",\n\t\t\treasons: [\"Empty or whitespace prompt\"],\n\t\t};\n\t}\n\n\t// 1. Explicit read-only questions/lookups dominate (unless prefixed by explicit mutation verb).\n\t// Planning-shaped questions are the exception: a plan steers expensive downstream work, so the\n\t// floor is medium even when phrased as a question.\n\tif (READ_ONLY_QUESTION_RE.test(text) && !EXPLICIT_MODIFY_REQUEST_RE.test(text)) {\n\t\tif (isPlanningPrompt(text)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"read-only\",\n\t\t\t\tconfidence: 0.75,\n\t\t\t\treasonCode: \"planning_min_medium\",\n\t\t\t\treasons: [\"Planning/design prompts never route cheap by default; a judge may deem them trivial\"],\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\ttier: \"cheap\",\n\t\t\trisk: \"read-only\",\n\t\t\tconfidence: 0.9,\n\t\t\treasonCode: \"read_only_question\",\n\t\t\treasons: [\"Prompt asks a question or requests an explanation, search, or lookup\"],\n\t\t};\n\t}\n\n\t// Helper function to match patterns and return appropriate decision\n\tfunction matchKeywords(input: string): RouteDecision | null {\n\t\t// A. High-risk / approval-required/expensive signals\n\t\tif (RELEASE_PUBLISH_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"release_or_publish\",\n\t\t\t\treasons: [\"Prompt mentions publishing, releasing, pushing, or deploying\"],\n\t\t\t};\n\t\t}\n\t\tif (SECURITY_AUTH_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"high-impact\",\n\t\t\t\tconfidence: 0.95,\n\t\t\t\treasonCode: \"security_or_auth\",\n\t\t\t\treasons: [\"Prompt mentions credentials, authentication, tokens, or secrets\"],\n\t\t\t};\n\t\t}\n\t\tif (DESTRUCTIVE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.85,\n\t\t\t\treasonCode: \"destructive_or_git_history\",\n\t\t\t\treasons: [\"Prompt mentions deleting, resetting, cleaning, or destructive operations\"],\n\t\t\t};\n\t\t}\n\t\tif (SELF_MOD_MUTATE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"approval-required\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"settings_or_self_modification\",\n\t\t\t\treasons: [\"Prompt mentions modifying skills, prompts, settings, tools, or self-modification\"],\n\t\t\t};\n\t\t}\n\t\tif (ARCHITECTURE_MUTATE_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"expensive\",\n\t\t\t\trisk: \"high-impact\",\n\t\t\t\tconfidence: 0.9,\n\t\t\t\treasonCode: \"architecture_or_ambiguous\",\n\t\t\t\treasons: [\"Prompt mentions core architecture or rewrite\"],\n\t\t\t};\n\t\t}\n\n\t\t// B. Explicit implementation/scoped-write signals route medium\n\t\tif (isPlanningPrompt(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"read-only\",\n\t\t\t\tconfidence: 0.75,\n\t\t\t\treasonCode: \"planning_min_medium\",\n\t\t\t\treasons: [\"Planning/design prompts never route cheap by default; a judge may deem them trivial\"],\n\t\t\t};\n\t\t}\n\t\tif (REFACTOR_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.8,\n\t\t\t\treasonCode: \"mechanical_refactor\",\n\t\t\t\treasons: [\"Prompt mentions refactoring code structure\"],\n\t\t\t};\n\t\t}\n\t\tif (TEST_VALIDATION_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.8,\n\t\t\t\treasonCode: \"test_or_validation\",\n\t\t\t\treasons: [\"Prompt mentions testing, validation, or linting\"],\n\t\t\t};\n\t\t}\n\t\tif (IMPLEMENT_RE.test(input)) {\n\t\t\treturn {\n\t\t\t\ttier: \"medium\",\n\t\t\t\trisk: \"scoped-write\",\n\t\t\t\tconfidence: 0.85,\n\t\t\t\treasonCode: \"normal_implementation\",\n\t\t\t\treasons: [\"Prompt mentions implementing, updating, creating, or modifying code\"],\n\t\t\t};\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tconst match = matchKeywords(text);\n\tif (match) {\n\t\treturn match;\n\t}\n\n\t// 4. Default fallbacks\n\treturn {\n\t\ttier: \"cheap\",\n\t\trisk: \"read-only\",\n\t\tconfidence: 0.5,\n\t\treasonCode: \"default_read_only\",\n\t\treasons: [\"No explicit implementation, destructive, or release patterns detected\"],\n\t};\n}\n\nexport function classifyModelRouterIntent(prompt: string): ModelRouterIntent {\n\tconst decision = classifyModelRouterRoute(prompt);\n\treturn decision.tier === \"cheap\" ? \"research\" : \"modify\";\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-judge.d.ts","sourceRoot":"","sources":["../../../src/core/model-router/route-judge.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAE9D;;;;;;;GAOG;AAEH,uGAAqG;AACrG,eAAO,MAAM,yBAAyB,QAS1B,CAAC;AAEb,eAAO,MAAM,6BAA6B,MAAM,CAAC;AACjD,eAAO,MAAM,6BAA6B,QAAS,CAAC;AAEpD,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,WAAW,CAAC;IACvC,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IAC5B,OAAO,EAAE,OAAO,CAAC;I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AED,uFAAuF;AACvF,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,GAAG,aAAa,CAczG;AAED,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,aAAa,CAAC;IACxB,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAC5B,qEAAqE;IACrE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,EAAE,MAAM,CAAC;CAChB;AAUD;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,aAAa,CAAC;IACxB,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,KAAK,OAAO,CAAC;QAChG,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,MAAM,CAAC;KACnB,CAAC,CAAC;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAsC/B","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { RouteDecision } from \"../autonomy/contracts.ts\";\n\n/**\n * Routing-only judge: a bounded, tool-less completion (default: the medium model) that decides the\n * final cheap/medium/expensive tier for a user prompt, refining the regex classifier's baseline.\n * Core rule: planning is never cheap unless the judge explicitly deems the task trivial. The judge\n * proposes; the existing pipeline (model resolution, auth, escalation, gates) still decides.\n * Failure is honest: unparseable/timeout/unavailable falls back to the baseline with a visible\n * reasonCode, never silently.\n */\n\n/** Static across calls — callers pass cacheRetention \"short\" so only the variable tail is billed. */\nexport const ROUTE_JUDGE_SYSTEM_PROMPT = [\n\t\"You are a routing judge for a coding agent. You only route; you never answer the task.\",\n\t\"Pick which model tier should handle the user prompt:\",\n\t'- \"cheap\": trivial, mechanical, read-only lookups only.',\n\t'- \"medium\": normal implementation, scoped edits, tests, and NON-trivial planning/design.',\n\t'- \"expensive\": architecture, ambiguity, security/auth, destructive or release operations, high-impact changes.',\n\t\"Planning, design, and strategy prompts are NEVER cheap unless the task is genuinely trivial.\",\n\t\"Respond with STRICT JSON only - no prose:\",\n\t'{\"tier\":\"cheap\"|\"medium\"|\"expensive\",\"risk\":\"read-only\"|\"scoped-write\"|\"high-impact\"|\"approval-required\",\"trivial\":true|false,\"reason\":\"<short reason>\"}',\n].join(\"\\n\");\n\nexport const ROUTE_JUDGE_MAX_OUTPUT_TOKENS = 128;\nexport const ROUTE_JUDGE_MAX_WALL_CLOCK_MS = 10_000;\n\nexport interface RouteJudgeVerdict {\n\ttier: \"cheap\" | \"medium\" | \"expensive\";\n\trisk: RouteDecision[\"risk\"];\n\ttrivial: boolean;\n\treason: string;\n}\n\nexport function buildRouteJudgeUserPrompt(args: { prompt: string; baseline: RouteDecision }): string {\n\treturn [\n\t\t`Baseline (regex) verdict: tier=${args.baseline.tier}, risk=${args.baseline.risk}, reason=${args.baseline.reasonCode}.`,\n\t\t\"User prompt:\",\n\t\targs.prompt.slice(0, 4000),\n\t].join(\"\\n\");\n}\n\nconst JUDGE_TIERS: readonly string[] = [\"cheap\", \"medium\", \"expensive\"];\nconst JUDGE_RISKS: readonly string[] = [\"read-only\", \"scoped-write\", \"high-impact\", \"approval-required\"];\n\nexport function parseRouteJudgeVerdict(text: string): RouteJudgeVerdict | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tconst start = trimmed.indexOf(\"{\");\n\tconst end = trimmed.lastIndexOf(\"}\");\n\tif (start >= 0 && end > start) candidates.push(trimmed.slice(start, end + 1));\n\n\tfor (const candidate of candidates) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(candidate);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\t// The judge may never select the learning tier or anything outside the three foreground tiers.\n\t\tif (typeof record.tier !== \"string\" || !JUDGE_TIERS.includes(record.tier)) continue;\n\t\tconst risk =\n\t\t\ttypeof record.risk === \"string\" && JUDGE_RISKS.includes(record.risk)\n\t\t\t\t? (record.risk as RouteDecision[\"risk\"])\n\t\t\t\t: undefined;\n\t\tif (!risk) continue;\n\t\treturn {\n\t\t\ttier: record.tier as RouteJudgeVerdict[\"tier\"],\n\t\t\trisk,\n\t\t\ttrivial: record.trivial === true,\n\t\t\treason: typeof record.reason === \"string\" ? record.reason.slice(0, 200) : \"\",\n\t\t};\n\t}\n\treturn undefined;\n}\n\n/** Merge a judge verdict into the baseline decision (pure; never returns learning). */\nexport function applyRouteJudgeVerdict(baseline: RouteDecision, verdict: RouteJudgeVerdict): RouteDecision {\n\t// Enforce the core rule in code, not just in the judge prompt: downgrading a non-cheap\n\t// baseline to cheap requires an EXPLICIT trivial verdict. An untrusted judge saying\n\t// {tier:\"cheap\", trivial:false} for an elevated prompt keeps the baseline tier.\n\tconst tier =\n\t\tverdict.tier === \"cheap\" && baseline.tier !== \"cheap\" && !verdict.trivial ? baseline.tier : verdict.tier;\n\treturn {\n\t\t...baseline,\n\t\ttier,\n\t\trisk: verdict.risk,\n\t\tconfidence: Math.max(baseline.confidence, 0.75),\n\t\treasonCode: `judge_${tier}${verdict.trivial ? \"_trivial\" : \"\"}`,\n\t\treasons: [...baseline.reasons, `Route judge: ${verdict.reason || \"no reason given\"}`],\n\t};\n}\n\nexport interface RouteJudgeRunResult {\n\tdecision: RouteDecision;\n\tverdict?: RouteJudgeVerdict;\n\t/** Set when the judge could not decide and the baseline was kept. */\n\tfallbackReason?: string;\n\tcostUsd: number;\n}\n\nfunction judgeFallbackDecision(baseline: RouteDecision, reason: string): RouteDecision {\n\treturn {\n\t\t...baseline,\n\t\treasonCode: \"judge_unavailable_fallback\",\n\t\treasons: [...baseline.reasons, reason],\n\t};\n}\n\n/**\n * Run the judge over a baseline decision. The completion executor is injected (production:\n * AgentSession.runIsolatedCompletion on the judge model). Never throws; every failure keeps the\n * baseline with a visible fallbackReason.\n */\nexport async function runRouteJudge(args: {\n\tprompt: string;\n\tbaseline: RouteDecision;\n\tcomplete: (input: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<{\n\t\ttext: string;\n\t\tcostUsd: number;\n\t\tstopReason: string;\n\t}>;\n\tsignal?: AbortSignal;\n\tmaxWallClockMs?: number;\n}): Promise<RouteJudgeRunResult> {\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: args.maxWallClockMs ?? ROUTE_JUDGE_MAX_WALL_CLOCK_MS,\n\t\tsignal: args.signal,\n\t\texecute: (signal) =>\n\t\t\targs.complete({\n\t\t\t\tsystemPrompt: ROUTE_JUDGE_SYSTEM_PROMPT,\n\t\t\t\tuserPrompt: buildRouteJudgeUserPrompt({ prompt: args.prompt, baseline: args.baseline }),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\n\tif (bounded.failure || !bounded.completion) {\n\t\treturn {\n\t\t\tdecision: judgeFallbackDecision(args.baseline, \"Route judge unavailable; baseline kept\"),\n\t\t\tfallbackReason: bounded.failure ? `judge_${bounded.failure.reasonCode}` : \"judge_unavailable_fallback\",\n\t\t\tcostUsd,\n\t\t};\n\t}\n\tif (bounded.completion.stopReason === \"error\" || bounded.completion.stopReason === \"aborted\") {\n\t\treturn {\n\t\t\tdecision: judgeFallbackDecision(args.baseline, \"Route judge errored; baseline kept\"),\n\t\t\tfallbackReason: \"judge_model_error\",\n\t\t\tcostUsd,\n\t\t};\n\t}\n\n\tconst verdict = parseRouteJudgeVerdict(bounded.completion.text);\n\tif (!verdict) {\n\t\treturn {\n\t\t\tdecision: judgeFallbackDecision(args.baseline, \"Route judge unparseable; baseline kept\"),\n\t\t\tfallbackReason: \"judge_unparseable_fallback\",\n\t\t\tcostUsd,\n\t\t};\n\t}\n\n\treturn { decision: applyRouteJudgeVerdict(args.baseline, verdict), verdict, costUsd };\n}\n"]}
|
|
@@ -82,6 +82,13 @@ export function applyRouteJudgeVerdict(baseline, verdict) {
|
|
|
82
82
|
reasons: [...baseline.reasons, `Route judge: ${verdict.reason || "no reason given"}`],
|
|
83
83
|
};
|
|
84
84
|
}
|
|
85
|
+
function judgeFallbackDecision(baseline, reason) {
|
|
86
|
+
return {
|
|
87
|
+
...baseline,
|
|
88
|
+
reasonCode: "judge_unavailable_fallback",
|
|
89
|
+
reasons: [...baseline.reasons, reason],
|
|
90
|
+
};
|
|
91
|
+
}
|
|
85
92
|
/**
|
|
86
93
|
* Run the judge over a baseline decision. The completion executor is injected (production:
|
|
87
94
|
* AgentSession.runIsolatedCompletion on the judge model). Never throws; every failure keeps the
|
|
@@ -100,17 +107,14 @@ export async function runRouteJudge(args) {
|
|
|
100
107
|
const costUsd = bounded.completion?.costUsd ?? 0;
|
|
101
108
|
if (bounded.failure || !bounded.completion) {
|
|
102
109
|
return {
|
|
103
|
-
decision:
|
|
104
|
-
...args.baseline,
|
|
105
|
-
reasons: [...args.baseline.reasons, "Route judge unavailable; baseline kept"],
|
|
106
|
-
},
|
|
110
|
+
decision: judgeFallbackDecision(args.baseline, "Route judge unavailable; baseline kept"),
|
|
107
111
|
fallbackReason: bounded.failure ? `judge_${bounded.failure.reasonCode}` : "judge_unavailable_fallback",
|
|
108
112
|
costUsd,
|
|
109
113
|
};
|
|
110
114
|
}
|
|
111
115
|
if (bounded.completion.stopReason === "error" || bounded.completion.stopReason === "aborted") {
|
|
112
116
|
return {
|
|
113
|
-
decision:
|
|
117
|
+
decision: judgeFallbackDecision(args.baseline, "Route judge errored; baseline kept"),
|
|
114
118
|
fallbackReason: "judge_model_error",
|
|
115
119
|
costUsd,
|
|
116
120
|
};
|
|
@@ -118,7 +122,7 @@ export async function runRouteJudge(args) {
|
|
|
118
122
|
const verdict = parseRouteJudgeVerdict(bounded.completion.text);
|
|
119
123
|
if (!verdict) {
|
|
120
124
|
return {
|
|
121
|
-
decision:
|
|
125
|
+
decision: judgeFallbackDecision(args.baseline, "Route judge unparseable; baseline kept"),
|
|
122
126
|
fallbackReason: "judge_unparseable_fallback",
|
|
123
127
|
costUsd,
|
|
124
128
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-judge.js","sourceRoot":"","sources":["../../../src/core/model-router/route-judge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAGzE;;;;;;;GAOG;AAEH,uGAAqG;AACrG,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,wFAAwF;IACxF,sDAAsD;IACtD,yDAAyD;IACzD,0FAA0F;IAC1F,gHAAgH;IAChH,8FAA8F;IAC9F,2CAA2C;IAC3C,0JAA0J;CAC1J,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEb,MAAM,CAAC,MAAM,6BAA6B,GAAG,GAAG,CAAC;AACjD,MAAM,CAAC,MAAM,6BAA6B,GAAG,MAAM,CAAC;AASpD,MAAM,UAAU,yBAAyB,CAAC,IAAiD,EAAU;IACpG,OAAO;QACN,kCAAkC,IAAI,CAAC,QAAQ,CAAC,IAAI,UAAU,IAAI,CAAC,QAAQ,CAAC,IAAI,YAAY,IAAI,CAAC,QAAQ,CAAC,UAAU,GAAG;QACvH,cAAc;QACd,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC;KAC1B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACb;AAED,MAAM,WAAW,GAAsB,CAAC,OAAO,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC;AACxE,MAAM,WAAW,GAAsB,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AAO,GAAG,sBAAsB,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAChE,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,OAAO;YACN,QAAQ,EAAE,EAAE,GAAG,IAAI,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,wCAAwC,CAAC,EAAE;YAC7G,cAAc,EAAE,4BAA4B;YAC5C,OAAO;SACP,CAAC;IACH,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,sBAAsB,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,CACtF","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { RouteDecision } from \"../autonomy/contracts.ts\";\n\n/**\n * Routing-only judge: a bounded, tool-less completion (default: the medium model) that decides the\n * final cheap/medium/expensive tier for a user prompt, refining the regex classifier's baseline.\n * Core rule: planning is never cheap unless the judge explicitly deems the task trivial. The judge\n * proposes; the existing pipeline (model resolution, auth, escalation, gates) still decides.\n * Failure is honest: unparseable/timeout/unavailable falls back to the baseline with a visible\n * reasonCode, never silently.\n */\n\n/** Static across calls — callers pass cacheRetention \"short\" so only the variable tail is billed. */\nexport const ROUTE_JUDGE_SYSTEM_PROMPT = [\n\t\"You are a routing judge for a coding agent. You only route; you never answer the task.\",\n\t\"Pick which model tier should handle the user prompt:\",\n\t'- \"cheap\": trivial, mechanical, read-only lookups only.',\n\t'- \"medium\": normal implementation, scoped edits, tests, and NON-trivial planning/design.',\n\t'- \"expensive\": architecture, ambiguity, security/auth, destructive or release operations, high-impact changes.',\n\t\"Planning, design, and strategy prompts are NEVER cheap unless the task is genuinely trivial.\",\n\t\"Respond with STRICT JSON only - no prose:\",\n\t'{\"tier\":\"cheap\"|\"medium\"|\"expensive\",\"risk\":\"read-only\"|\"scoped-write\"|\"high-impact\"|\"approval-required\",\"trivial\":true|false,\"reason\":\"<short reason>\"}',\n].join(\"\\n\");\n\nexport const ROUTE_JUDGE_MAX_OUTPUT_TOKENS = 128;\nexport const ROUTE_JUDGE_MAX_WALL_CLOCK_MS = 10_000;\n\nexport interface RouteJudgeVerdict {\n\ttier: \"cheap\" | \"medium\" | \"expensive\";\n\trisk: RouteDecision[\"risk\"];\n\ttrivial: boolean;\n\treason: string;\n}\n\nexport function buildRouteJudgeUserPrompt(args: { prompt: string; baseline: RouteDecision }): string {\n\treturn [\n\t\t`Baseline (regex) verdict: tier=${args.baseline.tier}, risk=${args.baseline.risk}, reason=${args.baseline.reasonCode}.`,\n\t\t\"User prompt:\",\n\t\targs.prompt.slice(0, 4000),\n\t].join(\"\\n\");\n}\n\nconst JUDGE_TIERS: readonly string[] = [\"cheap\", \"medium\", \"expensive\"];\nconst JUDGE_RISKS: readonly string[] = [\"read-only\", \"scoped-write\", \"high-impact\", \"approval-required\"];\n\nexport function parseRouteJudgeVerdict(text: string): RouteJudgeVerdict | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tconst start = trimmed.indexOf(\"{\");\n\tconst end = trimmed.lastIndexOf(\"}\");\n\tif (start >= 0 && end > start) candidates.push(trimmed.slice(start, end + 1));\n\n\tfor (const candidate of candidates) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(candidate);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\t// The judge may never select the learning tier or anything outside the three foreground tiers.\n\t\tif (typeof record.tier !== \"string\" || !JUDGE_TIERS.includes(record.tier)) continue;\n\t\tconst risk =\n\t\t\ttypeof record.risk === \"string\" && JUDGE_RISKS.includes(record.risk)\n\t\t\t\t? (record.risk as RouteDecision[\"risk\"])\n\t\t\t\t: undefined;\n\t\tif (!risk) continue;\n\t\treturn {\n\t\t\ttier: record.tier as RouteJudgeVerdict[\"tier\"],\n\t\t\trisk,\n\t\t\ttrivial: record.trivial === true,\n\t\t\treason: typeof record.reason === \"string\" ? record.reason.slice(0, 200) : \"\",\n\t\t};\n\t}\n\treturn undefined;\n}\n\n/** Merge a judge verdict into the baseline decision (pure; never returns learning). */\nexport function applyRouteJudgeVerdict(baseline: RouteDecision, verdict: RouteJudgeVerdict): RouteDecision {\n\t// Enforce the core rule in code, not just in the judge prompt: downgrading a non-cheap\n\t// baseline to cheap requires an EXPLICIT trivial verdict. An untrusted judge saying\n\t// {tier:\"cheap\", trivial:false} for an elevated prompt keeps the baseline tier.\n\tconst tier =\n\t\tverdict.tier === \"cheap\" && baseline.tier !== \"cheap\" && !verdict.trivial ? baseline.tier : verdict.tier;\n\treturn {\n\t\t...baseline,\n\t\ttier,\n\t\trisk: verdict.risk,\n\t\tconfidence: Math.max(baseline.confidence, 0.75),\n\t\treasonCode: `judge_${tier}${verdict.trivial ? \"_trivial\" : \"\"}`,\n\t\treasons: [...baseline.reasons, `Route judge: ${verdict.reason || \"no reason given\"}`],\n\t};\n}\n\nexport interface RouteJudgeRunResult {\n\tdecision: RouteDecision;\n\tverdict?: RouteJudgeVerdict;\n\t/** Set when the judge could not decide and the baseline was kept. */\n\tfallbackReason?: string;\n\tcostUsd: number;\n}\n\n/**\n * Run the judge over a baseline decision. The completion executor is injected (production:\n * AgentSession.runIsolatedCompletion on the judge model). Never throws; every failure keeps the\n * baseline with a visible fallbackReason.\n */\nexport async function runRouteJudge(args: {\n\tprompt: string;\n\tbaseline: RouteDecision;\n\tcomplete: (input: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<{\n\t\ttext: string;\n\t\tcostUsd: number;\n\t\tstopReason: string;\n\t}>;\n\tsignal?: AbortSignal;\n\tmaxWallClockMs?: number;\n}): Promise<RouteJudgeRunResult> {\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: args.maxWallClockMs ?? ROUTE_JUDGE_MAX_WALL_CLOCK_MS,\n\t\tsignal: args.signal,\n\t\texecute: (signal) =>\n\t\t\targs.complete({\n\t\t\t\tsystemPrompt: ROUTE_JUDGE_SYSTEM_PROMPT,\n\t\t\t\tuserPrompt: buildRouteJudgeUserPrompt({ prompt: args.prompt, baseline: args.baseline }),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\n\tif (bounded.failure || !bounded.completion) {\n\t\treturn {\n\t\t\tdecision: {\n\t\t\t\t...args.baseline,\n\t\t\t\treasons: [...args.baseline.reasons, \"Route judge unavailable; baseline kept\"],\n\t\t\t},\n\t\t\tfallbackReason: bounded.failure ? `judge_${bounded.failure.reasonCode}` : \"judge_unavailable_fallback\",\n\t\t\tcostUsd,\n\t\t};\n\t}\n\tif (bounded.completion.stopReason === \"error\" || bounded.completion.stopReason === \"aborted\") {\n\t\treturn {\n\t\t\tdecision: { ...args.baseline, reasons: [...args.baseline.reasons, \"Route judge errored; baseline kept\"] },\n\t\t\tfallbackReason: \"judge_model_error\",\n\t\t\tcostUsd,\n\t\t};\n\t}\n\n\tconst verdict = parseRouteJudgeVerdict(bounded.completion.text);\n\tif (!verdict) {\n\t\treturn {\n\t\t\tdecision: { ...args.baseline, reasons: [...args.baseline.reasons, \"Route judge unparseable; baseline kept\"] },\n\t\t\tfallbackReason: \"judge_unparseable_fallback\",\n\t\t\tcostUsd,\n\t\t};\n\t}\n\n\treturn { decision: applyRouteJudgeVerdict(args.baseline, verdict), verdict, costUsd };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"route-judge.js","sourceRoot":"","sources":["../../../src/core/model-router/route-judge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAGzE;;;;;;;GAOG;AAEH,uGAAqG;AACrG,MAAM,CAAC,MAA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CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvF,MAAM;SACN,CAAC;KACH,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,OAAO,CAAC,UAAU,EAAE,OAAO,IAAI,CAAC,CAAC;IAEjD,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;QAC5C,OAAO;YACN,QAAQ,EAAE,qBAAqB,CAAC,IAAI,CAAC,QAAQ,EAAE,wCAAwC,CAAC;YACxF,cAAc,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,4BAA4B;YACtG,OAAO;SACP,CAAC;IACH,CAAC;IACD,IAAI,OAAO,CAAC,UAAU,CAAC,UAAU,KAAK,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,UAAU,KAAK,SAAS,EAAE,CAAC;QAC9F,OAAO;YACN,QAAQ,EAAE,qBAAqB,CAAC,IAAI,CAAC,QAAQ,EAAE,oCAAoC,CAAC;YACpF,cAAc,EAAE,mBAAmB;YACnC,OAAO;SACP,CAAC;IACH,CAAC;IAED,MAAM,OAAO,GAAG,sBAAsB,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAChE,IAAI,CAAC,OAAO,EAAE,CAAC;QACd,OAAO;YACN,QAAQ,EAAE,qBAAqB,CAAC,IAAI,CAAC,QAAQ,EAAE,wCAAwC,CAAC;YACxF,cAAc,EAAE,4BAA4B;YAC5C,OAAO;SACP,CAAC;IACH,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,sBAAsB,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,CACtF","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { RouteDecision } from \"../autonomy/contracts.ts\";\n\n/**\n * Routing-only judge: a bounded, tool-less completion (default: the medium model) that decides the\n * final cheap/medium/expensive tier for a user prompt, refining the regex classifier's baseline.\n * Core rule: planning is never cheap unless the judge explicitly deems the task trivial. The judge\n * proposes; the existing pipeline (model resolution, auth, escalation, gates) still decides.\n * Failure is honest: unparseable/timeout/unavailable falls back to the baseline with a visible\n * reasonCode, never silently.\n */\n\n/** Static across calls — callers pass cacheRetention \"short\" so only the variable tail is billed. */\nexport const ROUTE_JUDGE_SYSTEM_PROMPT = [\n\t\"You are a routing judge for a coding agent. You only route; you never answer the task.\",\n\t\"Pick which model tier should handle the user prompt:\",\n\t'- \"cheap\": trivial, mechanical, read-only lookups only.',\n\t'- \"medium\": normal implementation, scoped edits, tests, and NON-trivial planning/design.',\n\t'- \"expensive\": architecture, ambiguity, security/auth, destructive or release operations, high-impact changes.',\n\t\"Planning, design, and strategy prompts are NEVER cheap unless the task is genuinely trivial.\",\n\t\"Respond with STRICT JSON only - no prose:\",\n\t'{\"tier\":\"cheap\"|\"medium\"|\"expensive\",\"risk\":\"read-only\"|\"scoped-write\"|\"high-impact\"|\"approval-required\",\"trivial\":true|false,\"reason\":\"<short reason>\"}',\n].join(\"\\n\");\n\nexport const ROUTE_JUDGE_MAX_OUTPUT_TOKENS = 128;\nexport const ROUTE_JUDGE_MAX_WALL_CLOCK_MS = 10_000;\n\nexport interface RouteJudgeVerdict {\n\ttier: \"cheap\" | \"medium\" | \"expensive\";\n\trisk: RouteDecision[\"risk\"];\n\ttrivial: boolean;\n\treason: string;\n}\n\nexport function buildRouteJudgeUserPrompt(args: { prompt: string; baseline: RouteDecision }): string {\n\treturn [\n\t\t`Baseline (regex) verdict: tier=${args.baseline.tier}, risk=${args.baseline.risk}, reason=${args.baseline.reasonCode}.`,\n\t\t\"User prompt:\",\n\t\targs.prompt.slice(0, 4000),\n\t].join(\"\\n\");\n}\n\nconst JUDGE_TIERS: readonly string[] = [\"cheap\", \"medium\", \"expensive\"];\nconst JUDGE_RISKS: readonly string[] = [\"read-only\", \"scoped-write\", \"high-impact\", \"approval-required\"];\n\nexport function parseRouteJudgeVerdict(text: string): RouteJudgeVerdict | undefined {\n\tconst trimmed = text.trim();\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tconst start = trimmed.indexOf(\"{\");\n\tconst end = trimmed.lastIndexOf(\"}\");\n\tif (start >= 0 && end > start) candidates.push(trimmed.slice(start, end + 1));\n\n\tfor (const candidate of candidates) {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(candidate);\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) continue;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\t// The judge may never select the learning tier or anything outside the three foreground tiers.\n\t\tif (typeof record.tier !== \"string\" || !JUDGE_TIERS.includes(record.tier)) continue;\n\t\tconst risk =\n\t\t\ttypeof record.risk === \"string\" && JUDGE_RISKS.includes(record.risk)\n\t\t\t\t? (record.risk as RouteDecision[\"risk\"])\n\t\t\t\t: undefined;\n\t\tif (!risk) continue;\n\t\treturn {\n\t\t\ttier: record.tier as RouteJudgeVerdict[\"tier\"],\n\t\t\trisk,\n\t\t\ttrivial: record.trivial === true,\n\t\t\treason: typeof record.reason === \"string\" ? record.reason.slice(0, 200) : \"\",\n\t\t};\n\t}\n\treturn undefined;\n}\n\n/** Merge a judge verdict into the baseline decision (pure; never returns learning). */\nexport function applyRouteJudgeVerdict(baseline: RouteDecision, verdict: RouteJudgeVerdict): RouteDecision {\n\t// Enforce the core rule in code, not just in the judge prompt: downgrading a non-cheap\n\t// baseline to cheap requires an EXPLICIT trivial verdict. An untrusted judge saying\n\t// {tier:\"cheap\", trivial:false} for an elevated prompt keeps the baseline tier.\n\tconst tier =\n\t\tverdict.tier === \"cheap\" && baseline.tier !== \"cheap\" && !verdict.trivial ? baseline.tier : verdict.tier;\n\treturn {\n\t\t...baseline,\n\t\ttier,\n\t\trisk: verdict.risk,\n\t\tconfidence: Math.max(baseline.confidence, 0.75),\n\t\treasonCode: `judge_${tier}${verdict.trivial ? \"_trivial\" : \"\"}`,\n\t\treasons: [...baseline.reasons, `Route judge: ${verdict.reason || \"no reason given\"}`],\n\t};\n}\n\nexport interface RouteJudgeRunResult {\n\tdecision: RouteDecision;\n\tverdict?: RouteJudgeVerdict;\n\t/** Set when the judge could not decide and the baseline was kept. */\n\tfallbackReason?: string;\n\tcostUsd: number;\n}\n\nfunction judgeFallbackDecision(baseline: RouteDecision, reason: string): RouteDecision {\n\treturn {\n\t\t...baseline,\n\t\treasonCode: \"judge_unavailable_fallback\",\n\t\treasons: [...baseline.reasons, reason],\n\t};\n}\n\n/**\n * Run the judge over a baseline decision. The completion executor is injected (production:\n * AgentSession.runIsolatedCompletion on the judge model). Never throws; every failure keeps the\n * baseline with a visible fallbackReason.\n */\nexport async function runRouteJudge(args: {\n\tprompt: string;\n\tbaseline: RouteDecision;\n\tcomplete: (input: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<{\n\t\ttext: string;\n\t\tcostUsd: number;\n\t\tstopReason: string;\n\t}>;\n\tsignal?: AbortSignal;\n\tmaxWallClockMs?: number;\n}): Promise<RouteJudgeRunResult> {\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: args.maxWallClockMs ?? ROUTE_JUDGE_MAX_WALL_CLOCK_MS,\n\t\tsignal: args.signal,\n\t\texecute: (signal) =>\n\t\t\targs.complete({\n\t\t\t\tsystemPrompt: ROUTE_JUDGE_SYSTEM_PROMPT,\n\t\t\t\tuserPrompt: buildRouteJudgeUserPrompt({ prompt: args.prompt, baseline: args.baseline }),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\n\tif (bounded.failure || !bounded.completion) {\n\t\treturn {\n\t\t\tdecision: judgeFallbackDecision(args.baseline, \"Route judge unavailable; baseline kept\"),\n\t\t\tfallbackReason: bounded.failure ? `judge_${bounded.failure.reasonCode}` : \"judge_unavailable_fallback\",\n\t\t\tcostUsd,\n\t\t};\n\t}\n\tif (bounded.completion.stopReason === \"error\" || bounded.completion.stopReason === \"aborted\") {\n\t\treturn {\n\t\t\tdecision: judgeFallbackDecision(args.baseline, \"Route judge errored; baseline kept\"),\n\t\t\tfallbackReason: \"judge_model_error\",\n\t\t\tcostUsd,\n\t\t};\n\t}\n\n\tconst verdict = parseRouteJudgeVerdict(bounded.completion.text);\n\tif (!verdict) {\n\t\treturn {\n\t\t\tdecision: judgeFallbackDecision(args.baseline, \"Route judge unparseable; baseline kept\"),\n\t\t\tfallbackReason: \"judge_unparseable_fallback\",\n\t\t\tcostUsd,\n\t\t};\n\t}\n\n\treturn { decision: applyRouteJudgeVerdict(args.baseline, verdict), verdict, costUsd };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-escalation.d.ts","sourceRoot":"","sources":["../../../src/core/model-router/tool-escalation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"tool-escalation.d.ts","sourceRoot":"","sources":["../../../src/core/model-router/tool-escalation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AA6F1D,wBAAgB,6BAA6B,CAAC,OAAO,EAAE;IACtD,IAAI,EAAE,SAAS,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,2EAA2E;IAC3E,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,OAAO,CAeV","sourcesContent":["import type { ModelTier } from \"../autonomy/contracts.ts\";\n\nconst READ_ONLY_TOOL_NAMES = new Set([\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"list\",\n\t\"search\",\n\t\"glob\",\n\t\"view_file\",\n\t\"list_dir\",\n\t\"grep_search\",\n\t\"search_web\",\n\t\"read_url_content\",\n\t\"read_browser_page\",\n]);\n\nconst SHELL_TOOL_NAMES = new Set([\"bash\", \"exec\", \"execute\", \"run\", \"run_command\", \"shell\"]);\n\nconst READ_ONLY_COMMANDS = new Set([\n\t\"awk\",\n\t\"cat\",\n\t\"date\",\n\t\"df\",\n\t\"du\",\n\t\"env\",\n\t\"git\",\n\t\"grep\",\n\t\"head\",\n\t\"jq\",\n\t\"ls\",\n\t\"node\",\n\t\"npm\",\n\t\"pnpm\",\n\t\"pwd\",\n\t\"rg\",\n\t\"sed\",\n\t\"tail\",\n\t\"test\",\n\t\"tsc\",\n\t\"wc\",\n\t\"which\",\n\t\"yarn\",\n]);\n\nconst READ_ONLY_GIT_SUBCOMMANDS = new Set([\"branch\", \"diff\", \"log\", \"rev-parse\", \"show\", \"status\", \"tag\"]);\nconst READ_ONLY_NPM_SUBCOMMANDS = new Set([\"info\", \"list\", \"ls\", \"outdated\", \"view\", \"whoami\"]);\nconst MUTATING_SHELL_TOKEN_RE =\n\t/(^|\\s)(>|>>|2>|&>|tee\\b|rm\\b|mv\\b|cp\\b|mkdir\\b|touch\\b|chmod\\b|chown\\b|install\\b|commit\\b|push\\b|publish\\b|deploy\\b|apply\\b|add\\b|checkout\\b|switch\\b|reset\\b|clean\\b|stash\\b|merge\\b|rebase\\b|npm\\s+(?:i|install|ci|update|publish|run)\\b|pnpm\\s+(?:i|install|update|publish|run)\\b|yarn\\s+(?:add|install|upgrade|publish|run)\\b)/i;\nconst UNSAFE_NESTED_SHELL_EXECUTION_RE = /(`|\\$\\(|\\bfind\\b[\\s\\S]*\\s-exec(?:dir)?\\b|\\bxargs\\b)/i;\nconst MUTATING_TOOL_NAME_RE =\n\t/(bash|exec|execute|run|shell|write|edit|patch|replace|delete|remove|move|rename|create|mkdir|touch|install|commit|push|publish|deploy|apply)/i;\n\nfunction getShellCommand(args: unknown): string | undefined {\n\tif (!args || typeof args !== \"object\") return undefined;\n\tconst record = args as Record<string, unknown>;\n\tconst command = record.command ?? record.cmd ?? record.shellCommand;\n\treturn typeof command === \"string\" ? command.trim() : undefined;\n}\n\nfunction commandName(segment: string): string | undefined {\n\tconst first = segment.trim().match(/^[A-Za-z0-9_./-]+/)?.[0];\n\tif (!first) return undefined;\n\tconst parts = first.split(\"/\");\n\treturn parts[parts.length - 1]?.toLowerCase();\n}\n\nfunction commandArg(segment: string, index: number): string | undefined {\n\treturn segment.trim().split(/\\s+/)[index]?.toLowerCase();\n}\n\nfunction isReadOnlyShellSegment(segment: string): boolean {\n\tconst name = commandName(segment);\n\tif (!name || !READ_ONLY_COMMANDS.has(name)) return false;\n\tif (name === \"git\") {\n\t\tconst subcommand = commandArg(segment, 1);\n\t\treturn Boolean(subcommand && READ_ONLY_GIT_SUBCOMMANDS.has(subcommand));\n\t}\n\tif (name === \"npm\" || name === \"pnpm\" || name === \"yarn\") {\n\t\tconst subcommand = commandArg(segment, 1);\n\t\treturn Boolean(subcommand && READ_ONLY_NPM_SUBCOMMANDS.has(subcommand));\n\t}\n\treturn true;\n}\n\nfunction isReadOnlyShellCommand(command: string): boolean {\n\tif (!command || MUTATING_SHELL_TOKEN_RE.test(command) || UNSAFE_NESTED_SHELL_EXECUTION_RE.test(command))\n\t\treturn false;\n\tconst segments = command.split(/\\s*(?:&&|\\|\\||[;|\\r\\n])\\s*/).map((segment) => segment.trim());\n\treturn segments.length > 0 && segments.every((segment) => segment.length > 0 && isReadOnlyShellSegment(segment));\n}\n\nexport function shouldEscalateModelRouterTool(options: {\n\ttier: ModelTier;\n\ttoolName: string;\n\targs?: unknown;\n\t/** The route's reasonCode; executor-lane turns carry \"executor_direct\". */\n\treasonCode?: string;\n}): boolean {\n\tif (options.tier !== \"cheap\") return false;\n\tconst toolName = options.toolName.trim().toLowerCase();\n\t// Executor-lane turns (G16) exist to run exactly one tool: run_toolkit_script, which enforces\n\t// its own safety (danger confirmation, structural exit-code contract). Escalating on it would\n\t// abort every executor turn at the moment it does its job. Any OTHER mutating tool still\n\t// escalates to the expensive model as usual.\n\tif (options.reasonCode === \"executor_direct\" && toolName === \"run_toolkit_script\") return false;\n\tif (!toolName) return true;\n\tif (READ_ONLY_TOOL_NAMES.has(toolName)) return false;\n\tif (SHELL_TOOL_NAMES.has(toolName)) {\n\t\tconst command = getShellCommand(options.args);\n\t\treturn command ? !isReadOnlyShellCommand(command) : true;\n\t}\n\treturn MUTATING_TOOL_NAME_RE.test(toolName) || !toolName.startsWith(\"read_\");\n}\n"]}
|
|
@@ -42,6 +42,7 @@ const READ_ONLY_COMMANDS = new Set([
|
|
|
42
42
|
const READ_ONLY_GIT_SUBCOMMANDS = new Set(["branch", "diff", "log", "rev-parse", "show", "status", "tag"]);
|
|
43
43
|
const READ_ONLY_NPM_SUBCOMMANDS = new Set(["info", "list", "ls", "outdated", "view", "whoami"]);
|
|
44
44
|
const MUTATING_SHELL_TOKEN_RE = /(^|\s)(>|>>|2>|&>|tee\b|rm\b|mv\b|cp\b|mkdir\b|touch\b|chmod\b|chown\b|install\b|commit\b|push\b|publish\b|deploy\b|apply\b|add\b|checkout\b|switch\b|reset\b|clean\b|stash\b|merge\b|rebase\b|npm\s+(?:i|install|ci|update|publish|run)\b|pnpm\s+(?:i|install|update|publish|run)\b|yarn\s+(?:add|install|upgrade|publish|run)\b)/i;
|
|
45
|
+
const UNSAFE_NESTED_SHELL_EXECUTION_RE = /(`|\$\(|\bfind\b[\s\S]*\s-exec(?:dir)?\b|\bxargs\b)/i;
|
|
45
46
|
const MUTATING_TOOL_NAME_RE = /(bash|exec|execute|run|shell|write|edit|patch|replace|delete|remove|move|rename|create|mkdir|touch|install|commit|push|publish|deploy|apply)/i;
|
|
46
47
|
function getShellCommand(args) {
|
|
47
48
|
if (!args || typeof args !== "object")
|
|
@@ -75,7 +76,7 @@ function isReadOnlyShellSegment(segment) {
|
|
|
75
76
|
return true;
|
|
76
77
|
}
|
|
77
78
|
function isReadOnlyShellCommand(command) {
|
|
78
|
-
if (!command || MUTATING_SHELL_TOKEN_RE.test(command))
|
|
79
|
+
if (!command || MUTATING_SHELL_TOKEN_RE.test(command) || UNSAFE_NESTED_SHELL_EXECUTION_RE.test(command))
|
|
79
80
|
return false;
|
|
80
81
|
const segments = command.split(/\s*(?:&&|\|\||[;|\r\n])\s*/).map((segment) => segment.trim());
|
|
81
82
|
return segments.length > 0 && segments.every((segment) => segment.length > 0 && isReadOnlyShellSegment(segment));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-escalation.js","sourceRoot":"","sources":["../../../src/core/model-router/tool-escalation.ts"],"names":[],"mappings":"AAEA,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC;IACpC,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,MAAM;IACN,QAAQ;IACR,MAAM;IACN,WAAW;IACX,UAAU;IACV,aAAa;IACb,YAAY;IACZ,kBAAkB;IAClB,mBAAmB;CACnB,CAAC,CAAC;AAEH,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,aAAa,EAAE,OAAO,CAAC,CAAC,CAAC;AAE7F,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC;IAClC,KAAK;IACL,KAAK;IACL,MAAM;IACN,IAAI;IACJ,IAAI;IACJ,KAAK;IACL,KAAK;IACL,MAAM;IACN,MAAM;IACN,IAAI;IACJ,IAAI;IACJ,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,IAAI;IACJ,KAAK;IACL,MAAM;IACN,MAAM;IACN,KAAK;IACL,IAAI;IACJ,OAAO;IACP,MAAM;CACN,CAAC,CAAC;AAEH,MAAM,yBAAyB,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE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\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"list\",\n\t\"search\",\n\t\"glob\",\n\t\"view_file\",\n\t\"list_dir\",\n\t\"grep_search\",\n\t\"search_web\",\n\t\"read_url_content\",\n\t\"read_browser_page\",\n]);\n\nconst SHELL_TOOL_NAMES = new Set([\"bash\", \"exec\", \"execute\", \"run\", \"run_command\", \"shell\"]);\n\nconst READ_ONLY_COMMANDS = new Set([\n\t\"awk\",\n\t\"cat\",\n\t\"date\",\n\t\"df\",\n\t\"du\",\n\t\"env\",\n\t\"git\",\n\t\"grep\",\n\t\"head\",\n\t\"jq\",\n\t\"ls\",\n\t\"node\",\n\t\"npm\",\n\t\"pnpm\",\n\t\"pwd\",\n\t\"rg\",\n\t\"sed\",\n\t\"tail\",\n\t\"test\",\n\t\"tsc\",\n\t\"wc\",\n\t\"which\",\n\t\"yarn\",\n]);\n\nconst READ_ONLY_GIT_SUBCOMMANDS = new Set([\"branch\", \"diff\", \"log\", \"rev-parse\", \"show\", \"status\", \"tag\"]);\nconst READ_ONLY_NPM_SUBCOMMANDS = new Set([\"info\", \"list\", \"ls\", \"outdated\", \"view\", \"whoami\"]);\nconst MUTATING_SHELL_TOKEN_RE =\n\t/(^|\\s)(>|>>|2>|&>|tee\\b|rm\\b|mv\\b|cp\\b|mkdir\\b|touch\\b|chmod\\b|chown\\b|install\\b|commit\\b|push\\b|publish\\b|deploy\\b|apply\\b|add\\b|checkout\\b|switch\\b|reset\\b|clean\\b|stash\\b|merge\\b|rebase\\b|npm\\s+(?:i|install|ci|update|publish|run)\\b|pnpm\\s+(?:i|install|update|publish|run)\\b|yarn\\s+(?:add|install|upgrade|publish|run)\\b)/i;\nconst UNSAFE_NESTED_SHELL_EXECUTION_RE = /(`|\\$\\(|\\bfind\\b[\\s\\S]*\\s-exec(?:dir)?\\b|\\bxargs\\b)/i;\nconst MUTATING_TOOL_NAME_RE =\n\t/(bash|exec|execute|run|shell|write|edit|patch|replace|delete|remove|move|rename|create|mkdir|touch|install|commit|push|publish|deploy|apply)/i;\n\nfunction getShellCommand(args: unknown): string | undefined {\n\tif (!args || typeof args !== \"object\") return undefined;\n\tconst record = args as Record<string, unknown>;\n\tconst command = record.command ?? record.cmd ?? record.shellCommand;\n\treturn typeof command === \"string\" ? command.trim() : undefined;\n}\n\nfunction commandName(segment: string): string | undefined {\n\tconst first = segment.trim().match(/^[A-Za-z0-9_./-]+/)?.[0];\n\tif (!first) return undefined;\n\tconst parts = first.split(\"/\");\n\treturn parts[parts.length - 1]?.toLowerCase();\n}\n\nfunction commandArg(segment: string, index: number): string | undefined {\n\treturn segment.trim().split(/\\s+/)[index]?.toLowerCase();\n}\n\nfunction isReadOnlyShellSegment(segment: string): boolean {\n\tconst name = commandName(segment);\n\tif (!name || !READ_ONLY_COMMANDS.has(name)) return false;\n\tif (name === \"git\") {\n\t\tconst subcommand = commandArg(segment, 1);\n\t\treturn Boolean(subcommand && READ_ONLY_GIT_SUBCOMMANDS.has(subcommand));\n\t}\n\tif (name === \"npm\" || name === \"pnpm\" || name === \"yarn\") {\n\t\tconst subcommand = commandArg(segment, 1);\n\t\treturn Boolean(subcommand && READ_ONLY_NPM_SUBCOMMANDS.has(subcommand));\n\t}\n\treturn true;\n}\n\nfunction isReadOnlyShellCommand(command: string): boolean {\n\tif (!command || MUTATING_SHELL_TOKEN_RE.test(command) || UNSAFE_NESTED_SHELL_EXECUTION_RE.test(command))\n\t\treturn false;\n\tconst segments = command.split(/\\s*(?:&&|\\|\\||[;|\\r\\n])\\s*/).map((segment) => segment.trim());\n\treturn segments.length > 0 && segments.every((segment) => segment.length > 0 && isReadOnlyShellSegment(segment));\n}\n\nexport function shouldEscalateModelRouterTool(options: {\n\ttier: ModelTier;\n\ttoolName: string;\n\targs?: unknown;\n\t/** The route's reasonCode; executor-lane turns carry \"executor_direct\". */\n\treasonCode?: string;\n}): boolean {\n\tif (options.tier !== \"cheap\") return false;\n\tconst toolName = options.toolName.trim().toLowerCase();\n\t// Executor-lane turns (G16) exist to run exactly one tool: run_toolkit_script, which enforces\n\t// its own safety (danger confirmation, structural exit-code contract). Escalating on it would\n\t// abort every executor turn at the moment it does its job. Any OTHER mutating tool still\n\t// escalates to the expensive model as usual.\n\tif (options.reasonCode === \"executor_direct\" && toolName === \"run_toolkit_script\") return false;\n\tif (!toolName) return true;\n\tif (READ_ONLY_TOOL_NAMES.has(toolName)) return false;\n\tif (SHELL_TOOL_NAMES.has(toolName)) {\n\t\tconst command = getShellCommand(options.args);\n\t\treturn command ? !isReadOnlyShellCommand(command) : true;\n\t}\n\treturn MUTATING_TOOL_NAME_RE.test(toolName) || !toolName.startsWith(\"read_\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-router-controller.d.ts","sourceRoot":"","sources":["../../src/core/model-router-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAiB,MAAM,2BAA2B,CAAC;AACpF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,GAAG,EAAW,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAEpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AACjH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAkC,KAAK,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AAG7G,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAkBzD,OAAO,EAIN,KAAK,yBAAyB,EAC9B,KAAK,yBAAyB,EAE9B,MAAM,0BAA0B,CAAC;AAGlC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAO7D,wGAAwG;AACxG,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,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CAAC,qBAAqB;IA6B7B,0GAA0G;IAC1G,OAAO,CAAC,2BAA2B;YAYrB,2BAA2B;IAkCzC,OAAO,CAAC,4BAA4B;IA6FpC,OAAO,CAAC,iCAAiC;IAUzC,0BAA0B,CAAC,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,WAAW,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CASzF;IAED;;;;;;;OAOG;IACG,sBAAsB,CAC3B,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,GAC/B,OAAO,CAAC;QAAE,QAAQ,EAAE,aAAa,CAAC;QAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;KAAE,GAAG,SAAS,CAAC,CAkFrE;IAGD,OAAO,CAAC,4BAA4B;IAKpC,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CA6BzD;IAEK,aAAa,CAClB,QAAQ,EAAE,YAAY,GAAG,YAAY,EAAE,EACvC,WAAW,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,EACnC,aAAa,EAAE,aAAa,GAAG,SAAS,EACxC,eAAe,UAAO,GACpB,OAAO,CAAC,IAAI,CAAC,CAoPf;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 stays host-side in\n * AgentSession._runAgentPrompt; this controller's parallel routed drive path ({@link runRoutedTurn})\n * owns only the route decision/escalation/tier bookkeeping and delegates every agent turn back through\n * {@link ModelRouterControllerDeps.runAgentPrompt}, so the drive-loop logic 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 escalation branch ({@link maybeEscalateToolCall}), the\n * message_end cheap-turn buffering ({@link captureSessionMessage}), the retry-event suppression\n * ({@link isRetryInFlight}), and the public getModelRouterStatus / autonomy-telemetry reads.\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\";\nimport type { AgentSessionEvent, IsolatedCompletionOptions, IsolatedCompletionResult } from \"./agent-session.ts\";\nimport type { RouteDecision } from \"./autonomy/contracts.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport { latestUserPromptText } from \"./context-pipeline.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 { shouldEscalateModelRouterTool } from \"./model-router/tool-escalation.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport {\n\tbuildReflexUserPrompt,\n\tparseReflexPlan,\n\tREFLEX_INTERPRETER_SYSTEM_PROMPT,\n} 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\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 B5 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 host-side drive loop (agent.prompt()/continue()); the routed drive 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. */\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}\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 host-side.\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 * 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.filter((m): m is AgentMessage => true));\n\t\t\tif (!request) return undefined;\n\t\t\tconst scripts = this.deps.getSettingsManager().getToolkitScripts();\n\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\tsystemPrompt: REFLEX_INTERPRETER_SYSTEM_PROMPT,\n\t\t\t\tmessages: [\n\t\t\t\t\t{\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: buildReflexUserPrompt(request, scripts) }],\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmodel,\n\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\tmaxTokens: 256,\n\t\t\t\tcacheRetention: \"short\",\n\t\t\t});\n\t\t\tif (completion.usage.cost.total > 0 || completion.usage.totalTokens > 0) {\n\t\t\t\tthis.deps.addSpawnedUsage(completion.usage, { label: \"executor-brain-warmup\" });\n\t\t\t}\n\t\t\tconst plan = parseReflexPlan(completion.text);\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// G16 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\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\treturn this.deps.isModelExhausted(resolved.model) ? undefined : 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\tconst judgePattern = settings.judgeModel ?? settings.mediumModel;\n\t\tif (!judgePattern) return baseline;\n\t\tconst judgeModel = this.deps.resolveLaneModel(judgePattern);\n\t\tif (!judgeModel) return baseline;\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 this.deps.runIsolatedCompletion({\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\tmodel: judgeModel,\n\t\t\t\t\t// Per-tier thinking (R1): 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});\n\t\t\t\tspentUsage = completion.usage;\n\t\t\t\treturn {\n\t\t\t\t\ttext: completion.text,\n\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t};\n\t\t\t},\n\t\t});\n\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"router-judge\" });\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// G4 swap bookkeeping (Bug G): 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\tif (!modelsAreEqual(this.deps.getModel(), routedModel)) {\n\t\t\tagent.state.model = routedModel;\n\t\t\t// Per-tier thinking (R1): 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\tconst routerThinkingSettings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\t\tconst configuredThinking = !routeDecision\n\t\t\t\t? undefined\n\t\t\t\t: routeDecision.reasonCode === \"executor_direct\"\n\t\t\t\t\t? routerThinkingSettings.executorThinking\n\t\t\t\t\t: routeDecision.tier === \"cheap\"\n\t\t\t\t\t\t? routerThinkingSettings.cheapThinking\n\t\t\t\t\t\t: routeDecision.tier === \"medium\"\n\t\t\t\t\t\t\t? routerThinkingSettings.mediumThinking\n\t\t\t\t\t\t\t: routeDecision.tier === \"expensive\"\n\t\t\t\t\t\t\t\t? routerThinkingSettings.expensiveThinking\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\tagent.state.thinkingLevel = clampThinkingLevel(\n\t\t\t\troutedModel,\n\t\t\t\tconfiguredThinking ?? previousThinkingLevel,\n\t\t\t) as ThinkingLevel;\n\t\t\t// G4: 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\tconst routedProfile = deriveModelCapabilityProfile({\n\t\t\t\tcontextWindow: routedModel.contextWindow,\n\t\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t\t});\n\t\t\tif (routedProfile.class !== \"full\") {\n\t\t\t\tconst allowed = new Set(\n\t\t\t\t\tfilterToolNamesForCapability(\n\t\t\t\t\t\tpreviousTurnTools.map((tool) => tool.name),\n\t\t\t\t\t\troutedProfile,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tswappedTools = previousTurnTools.filter((tool) => allowed.has(tool.name));\n\t\t\t\tagent.state.tools = swappedTools;\n\t\t\t\t// G4: the system prompt follows the ROUTED model's filtered surface too — otherwise the\n\t\t\t\t// cheap/local model is billed for (and told about) tool guidelines/snippets it can't call.\n\t\t\t\t// Per-turn only; restored in the finally. A live extension override of the prompt is left\n\t\t\t\t// alone (only shed when we're on the base prompt).\n\t\t\t\tif (agent.state.systemPrompt === this.deps.getBaseSystemPrompt()) {\n\t\t\t\t\tswappedSystemPrompt = this.deps.buildSystemPromptForToolNames(\n\t\t\t\t\t\tagent.state.tools.map((tool) => tool.name),\n\t\t\t\t\t);\n\t\t\t\t\tagent.state.systemPrompt = swappedSystemPrompt;\n\t\t\t\t}\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 (G16 refinement): 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\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 (Bug G): undo tools/systemPrompt only if each is STILL the exact\n\t\t\t\t// reference/string the G4 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// G3: 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.d.ts","sourceRoot":"","sources":["../../src/core/model-router-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAiB,MAAM,2BAA2B,CAAC;AACpF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,GAAG,EAAW,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAEpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AACjH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAkC,KAAK,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AAG7G,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAkBzD,OAAO,EAIN,KAAK,yBAAyB,EAC9B,KAAK,yBAAyB,EAE9B,MAAM,0BAA0B,CAAC;AAGlC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAO7D,wGAAwG;AACxG,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,MAAM,CAEhE;AA+BD,MAAM,WAAW,yBAAyB;IACzC;iFAC6E;IAC7E,QAAQ,IAAI,KAAK,CAAC;IAClB,4FAA4F;IAC5F,QAAQ,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC;IACnC,oFAAoF;IACpF,kBAAkB,IAAI,eAAe,CAAC;IACtC,4GAA4G;IAC5G,iBAAiB,IAAI,cAAc,CAAC;IACpC,uFAAuF;IACvF,gBAAgB,IAAI,a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;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,GAC/B,OAAO,CAAC;QAAE,QAAQ,EAAE,aAAa,CAAC;QAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;KAAE,GAAG,SAAS,CAAC,CA2FrE;IAGD,OAAO,CAAC,4BAA4B;IAKpC,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CA6BzD;IAEK,aAAa,CAClB,QAAQ,EAAE,YAAY,GAAG,YAAY,EAAE,EACvC,WAAW,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,SAAS,EACnC,aAAa,EAAE,aAAa,GAAG,SAAS,EACxC,eAAe,UAAO,GACpB,OAAO,CAAC,IAAI,CAAC,CAoPf;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 stays host-side in\n * AgentSession._runAgentPrompt; this controller's parallel routed drive path ({@link runRoutedTurn})\n * owns only the route decision/escalation/tier bookkeeping and delegates every agent turn back through\n * {@link ModelRouterControllerDeps.runAgentPrompt}, so the drive-loop logic 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 escalation branch ({@link maybeEscalateToolCall}), the\n * message_end cheap-turn buffering ({@link captureSessionMessage}), the retry-event suppression\n * ({@link isRetryInFlight}), and the public getModelRouterStatus / autonomy-telemetry reads.\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\";\nimport type { AgentSessionEvent, IsolatedCompletionOptions, IsolatedCompletionResult } from \"./agent-session.ts\";\nimport type { RouteDecision } from \"./autonomy/contracts.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport { latestUserPromptText } from \"./context-pipeline.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 { shouldEscalateModelRouterTool } from \"./model-router/tool-escalation.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport {\n\tbuildReflexUserPrompt,\n\tparseReflexPlan,\n\tREFLEX_INTERPRETER_SYSTEM_PROMPT,\n} 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 B5 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 host-side drive loop (agent.prompt()/continue()); the routed drive 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. */\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}\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 host-side.\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 * 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.filter((m): m is AgentMessage => true));\n\t\t\tif (!request) return undefined;\n\t\t\tconst scripts = this.deps.getSettingsManager().getToolkitScripts();\n\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\tsystemPrompt: REFLEX_INTERPRETER_SYSTEM_PROMPT,\n\t\t\t\tmessages: [\n\t\t\t\t\t{\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: buildReflexUserPrompt(request, scripts) }],\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmodel,\n\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\tmaxTokens: 256,\n\t\t\t\tcacheRetention: \"short\",\n\t\t\t});\n\t\t\tif (completion.usage.cost.total > 0 || completion.usage.totalTokens > 0) {\n\t\t\t\tthis.deps.addSpawnedUsage(completion.usage, { label: \"executor-brain-warmup\" });\n\t\t\t}\n\t\t\tconst plan = parseReflexPlan(completion.text);\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// G16 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\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\treturn this.deps.isModelExhausted(resolved.model) ? undefined : 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 this.deps.runIsolatedCompletion({\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\tmodel: judgeModel,\n\t\t\t\t\t// Per-tier thinking (R1): 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});\n\t\t\t\tspentUsage = completion.usage;\n\t\t\t\treturn {\n\t\t\t\t\ttext: completion.text,\n\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t};\n\t\t\t},\n\t\t});\n\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"router-judge\" });\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// G4 swap bookkeeping (Bug G): 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\tif (!modelsAreEqual(this.deps.getModel(), routedModel)) {\n\t\t\tagent.state.model = routedModel;\n\t\t\t// Per-tier thinking (R1): 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\tconst routerThinkingSettings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\t\tconst configuredThinking = !routeDecision\n\t\t\t\t? undefined\n\t\t\t\t: routeDecision.reasonCode === \"executor_direct\"\n\t\t\t\t\t? routerThinkingSettings.executorThinking\n\t\t\t\t\t: routeDecision.tier === \"cheap\"\n\t\t\t\t\t\t? routerThinkingSettings.cheapThinking\n\t\t\t\t\t\t: routeDecision.tier === \"medium\"\n\t\t\t\t\t\t\t? routerThinkingSettings.mediumThinking\n\t\t\t\t\t\t\t: routeDecision.tier === \"expensive\"\n\t\t\t\t\t\t\t\t? routerThinkingSettings.expensiveThinking\n\t\t\t\t\t\t\t\t: undefined;\n\t\t\tagent.state.thinkingLevel = clampThinkingLevel(\n\t\t\t\troutedModel,\n\t\t\t\tconfiguredThinking ?? previousThinkingLevel,\n\t\t\t) as ThinkingLevel;\n\t\t\t// G4: 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\tconst routedProfile = deriveModelCapabilityProfile({\n\t\t\t\tcontextWindow: routedModel.contextWindow,\n\t\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t\t});\n\t\t\tif (routedProfile.class !== \"full\") {\n\t\t\t\tconst allowed = new Set(\n\t\t\t\t\tfilterToolNamesForCapability(\n\t\t\t\t\t\tpreviousTurnTools.map((tool) => tool.name),\n\t\t\t\t\t\troutedProfile,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tswappedTools = previousTurnTools.filter((tool) => allowed.has(tool.name));\n\t\t\t\tagent.state.tools = swappedTools;\n\t\t\t\t// G4: the system prompt follows the ROUTED model's filtered surface too — otherwise the\n\t\t\t\t// cheap/local model is billed for (and told about) tool guidelines/snippets it can't call.\n\t\t\t\t// Per-turn only; restored in the finally. A live extension override of the prompt is left\n\t\t\t\t// alone (only shed when we're on the base prompt).\n\t\t\t\tif (agent.state.systemPrompt === this.deps.getBaseSystemPrompt()) {\n\t\t\t\t\tswappedSystemPrompt = this.deps.buildSystemPromptForToolNames(\n\t\t\t\t\t\tagent.state.tools.map((tool) => tool.name),\n\t\t\t\t\t);\n\t\t\t\t\tagent.state.systemPrompt = swappedSystemPrompt;\n\t\t\t\t}\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 (G16 refinement): 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\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 (Bug G): undo tools/systemPrompt only if each is STILL the exact\n\t\t\t\t// reference/string the G4 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// G3: 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"]}
|