@caupulican/pi-adaptative 0.81.37 → 0.81.39

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.
Files changed (451) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +1 -1
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +18 -1
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +131 -0
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +196 -0
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +308 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +22 -2
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +585 -24
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  13. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +749 -27
  14. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/__init__.py +43 -0
  15. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/fs.py +270 -0
  16. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/search.py +252 -0
  17. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/strings.py +399 -0
  18. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +575 -0
  19. package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +52 -0
  20. package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +49 -0
  21. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +734 -0
  22. package/dist/bundled-resources/runtimes/pi-shell-engine/expand.py +238 -0
  23. package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +132 -0
  24. package/dist/bundled-resources/runtimes/pi-shell-engine/nodes.py +116 -0
  25. package/dist/bundled-resources/runtimes/pi-shell-engine/parser.py +287 -0
  26. package/dist/bundled-resources/runtimes/pi-shell-engine/proc.py +137 -0
  27. package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +100 -0
  28. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +579 -0
  29. package/dist/bundled-resources/skills/tool-call-repair/SKILL.md +19 -9
  30. package/dist/bundled-resources/skills/tool-call-repair/references/failure-grammar.md +22 -5
  31. package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +5 -5
  32. package/dist/bundled-resources/skills/tool-call-repair/references/text-protocol-grammar.md +28 -7
  33. package/dist/cli/args.d.ts +3 -0
  34. package/dist/cli/args.d.ts.map +1 -1
  35. package/dist/cli/args.js +15 -0
  36. package/dist/cli/args.js.map +1 -1
  37. package/dist/core/agent-paths.d.ts +49 -0
  38. package/dist/core/agent-paths.d.ts.map +1 -0
  39. package/dist/core/agent-paths.js +107 -0
  40. package/dist/core/agent-paths.js.map +1 -0
  41. package/dist/core/agent-session-services.d.ts.map +1 -1
  42. package/dist/core/agent-session-services.js +3 -3
  43. package/dist/core/agent-session-services.js.map +1 -1
  44. package/dist/core/agent-session.d.ts +234 -17
  45. package/dist/core/agent-session.d.ts.map +1 -1
  46. package/dist/core/agent-session.js +484 -62
  47. package/dist/core/agent-session.js.map +1 -1
  48. package/dist/core/autonomy/contracts.d.ts +9 -0
  49. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  50. package/dist/core/autonomy/contracts.js.map +1 -1
  51. package/dist/core/autonomy/lane-tracker.d.ts +10 -1
  52. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  53. package/dist/core/autonomy/lane-tracker.js +5 -1
  54. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  55. package/dist/core/background-lane-controller.d.ts +122 -6
  56. package/dist/core/background-lane-controller.d.ts.map +1 -1
  57. package/dist/core/background-lane-controller.js +447 -90
  58. package/dist/core/background-lane-controller.js.map +1 -1
  59. package/dist/core/bash-execution-controller.d.ts +4 -0
  60. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  61. package/dist/core/bash-execution-controller.js +7 -1
  62. package/dist/core/bash-execution-controller.js.map +1 -1
  63. package/dist/core/compaction-support.d.ts +13 -3
  64. package/dist/core/compaction-support.d.ts.map +1 -1
  65. package/dist/core/compaction-support.js +43 -7
  66. package/dist/core/compaction-support.js.map +1 -1
  67. package/dist/core/context/context-audit.d.ts +33 -1
  68. package/dist/core/context/context-audit.d.ts.map +1 -1
  69. package/dist/core/context/context-audit.js +31 -5
  70. package/dist/core/context/context-audit.js.map +1 -1
  71. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  72. package/dist/core/context/sqlite-runtime-index.js +13 -7
  73. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  74. package/dist/core/context-gc.d.ts.map +1 -1
  75. package/dist/core/context-gc.js +16 -1
  76. package/dist/core/context-gc.js.map +1 -1
  77. package/dist/core/context-pipeline.d.ts +26 -4
  78. package/dist/core/context-pipeline.d.ts.map +1 -1
  79. package/dist/core/context-pipeline.js +137 -14
  80. package/dist/core/context-pipeline.js.map +1 -1
  81. package/dist/core/cost-guard.d.ts +19 -3
  82. package/dist/core/cost-guard.d.ts.map +1 -1
  83. package/dist/core/cost-guard.js +18 -3
  84. package/dist/core/cost-guard.js.map +1 -1
  85. package/dist/core/delegation/session-worker-result.d.ts +34 -4
  86. package/dist/core/delegation/session-worker-result.d.ts.map +1 -1
  87. package/dist/core/delegation/session-worker-result.js +64 -4
  88. package/dist/core/delegation/session-worker-result.js.map +1 -1
  89. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  90. package/dist/core/delegation/worker-actions.js +1 -1
  91. package/dist/core/delegation/worker-actions.js.map +1 -1
  92. package/dist/core/delegation/worker-result.d.ts +42 -1
  93. package/dist/core/delegation/worker-result.d.ts.map +1 -1
  94. package/dist/core/delegation/worker-result.js +68 -0
  95. package/dist/core/delegation/worker-result.js.map +1 -1
  96. package/dist/core/extensions/loader.d.ts.map +1 -1
  97. package/dist/core/extensions/loader.js +23 -7
  98. package/dist/core/extensions/loader.js.map +1 -1
  99. package/dist/core/extensions/runner.d.ts.map +1 -1
  100. package/dist/core/extensions/runner.js +1 -0
  101. package/dist/core/extensions/runner.js.map +1 -1
  102. package/dist/core/extensions/types.d.ts +51 -0
  103. package/dist/core/extensions/types.d.ts.map +1 -1
  104. package/dist/core/extensions/types.js.map +1 -1
  105. package/dist/core/goal-loop-controller.d.ts +17 -1
  106. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  107. package/dist/core/goal-loop-controller.js +79 -11
  108. package/dist/core/goal-loop-controller.js.map +1 -1
  109. package/dist/core/goals/goal-continuation-controller.d.ts +48 -2
  110. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  111. package/dist/core/goals/goal-continuation-controller.js +77 -0
  112. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  113. package/dist/core/goals/goal-continuation-defaults.d.ts +39 -0
  114. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  115. package/dist/core/goals/goal-continuation-defaults.js +42 -0
  116. package/dist/core/goals/goal-continuation-defaults.js.map +1 -1
  117. package/dist/core/goals/goal-continuation-prompt.d.ts +4 -0
  118. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  119. package/dist/core/goals/goal-continuation-prompt.js +51 -10
  120. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  121. package/dist/core/goals/goal-runtime-snapshot.d.ts +101 -2
  122. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  123. package/dist/core/goals/goal-runtime-snapshot.js +87 -4
  124. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  125. package/dist/core/goals/goal-state.d.ts +89 -1
  126. package/dist/core/goals/goal-state.d.ts.map +1 -1
  127. package/dist/core/goals/goal-state.js +71 -5
  128. package/dist/core/goals/goal-state.js.map +1 -1
  129. package/dist/core/goals/goal-tool-core.d.ts +56 -2
  130. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  131. package/dist/core/goals/goal-tool-core.js +111 -5
  132. package/dist/core/goals/goal-tool-core.js.map +1 -1
  133. package/dist/core/goals/session-goal-state.d.ts +11 -2
  134. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  135. package/dist/core/goals/session-goal-state.js +32 -17
  136. package/dist/core/goals/session-goal-state.js.map +1 -1
  137. package/dist/core/keybindings.d.ts +10 -0
  138. package/dist/core/keybindings.d.ts.map +1 -1
  139. package/dist/core/keybindings.js +10 -2
  140. package/dist/core/keybindings.js.map +1 -1
  141. package/dist/core/learning/observation-store.d.ts +12 -3
  142. package/dist/core/learning/observation-store.d.ts.map +1 -1
  143. package/dist/core/learning/observation-store.js +30 -15
  144. package/dist/core/learning/observation-store.js.map +1 -1
  145. package/dist/core/learning/skill-curator.d.ts +5 -1
  146. package/dist/core/learning/skill-curator.d.ts.map +1 -1
  147. package/dist/core/learning/skill-curator.js +21 -19
  148. package/dist/core/learning/skill-curator.js.map +1 -1
  149. package/dist/core/local-runtime-controller.d.ts +65 -3
  150. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  151. package/dist/core/local-runtime-controller.js +186 -26
  152. package/dist/core/local-runtime-controller.js.map +1 -1
  153. package/dist/core/memory/providers/file-store.d.ts +1 -1
  154. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  155. package/dist/core/memory/providers/file-store.js +6 -6
  156. package/dist/core/memory/providers/file-store.js.map +1 -1
  157. package/dist/core/model-capability.d.ts +34 -0
  158. package/dist/core/model-capability.d.ts.map +1 -1
  159. package/dist/core/model-capability.js +42 -1
  160. package/dist/core/model-capability.js.map +1 -1
  161. package/dist/core/model-router/tool-escalation.d.ts +15 -0
  162. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  163. package/dist/core/model-router/tool-escalation.js +23 -1
  164. package/dist/core/model-router/tool-escalation.js.map +1 -1
  165. package/dist/core/model-router-controller.d.ts +34 -7
  166. package/dist/core/model-router-controller.d.ts.map +1 -1
  167. package/dist/core/model-router-controller.js +95 -16
  168. package/dist/core/model-router-controller.js.map +1 -1
  169. package/dist/core/models/adaptation-store.d.ts +7 -0
  170. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  171. package/dist/core/models/adaptation-store.js +47 -11
  172. package/dist/core/models/adaptation-store.js.map +1 -1
  173. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  174. package/dist/core/models/default-model-suggestions.js +17 -0
  175. package/dist/core/models/default-model-suggestions.js.map +1 -1
  176. package/dist/core/models/fitness-store.d.ts +3 -0
  177. package/dist/core/models/fitness-store.d.ts.map +1 -1
  178. package/dist/core/models/fitness-store.js +11 -2
  179. package/dist/core/models/fitness-store.js.map +1 -1
  180. package/dist/core/models/llamacpp-runtime.d.ts +180 -0
  181. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -0
  182. package/dist/core/models/llamacpp-runtime.js +475 -0
  183. package/dist/core/models/llamacpp-runtime.js.map +1 -0
  184. package/dist/core/models/local-registration.d.ts +40 -0
  185. package/dist/core/models/local-registration.d.ts.map +1 -1
  186. package/dist/core/models/local-registration.js +94 -5
  187. package/dist/core/models/local-registration.js.map +1 -1
  188. package/dist/core/models/local-runtime.d.ts.map +1 -1
  189. package/dist/core/models/local-runtime.js +9 -7
  190. package/dist/core/models/local-runtime.js.map +1 -1
  191. package/dist/core/models/model-ref.d.ts +7 -0
  192. package/dist/core/models/model-ref.d.ts.map +1 -1
  193. package/dist/core/models/model-ref.js +26 -0
  194. package/dist/core/models/model-ref.js.map +1 -1
  195. package/dist/core/models/needle-runtime.d.ts +257 -0
  196. package/dist/core/models/needle-runtime.d.ts.map +1 -0
  197. package/dist/core/models/needle-runtime.js +519 -0
  198. package/dist/core/models/needle-runtime.js.map +1 -0
  199. package/dist/core/models/prism-llamacpp-lifecycle.d.ts +89 -0
  200. package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -0
  201. package/dist/core/models/prism-llamacpp-lifecycle.js +121 -0
  202. package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -0
  203. package/dist/core/package-manager.d.ts.map +1 -1
  204. package/dist/core/package-manager.js +11 -10
  205. package/dist/core/package-manager.js.map +1 -1
  206. package/dist/core/process-matrix/codes.d.ts +72 -0
  207. package/dist/core/process-matrix/codes.d.ts.map +1 -0
  208. package/dist/core/process-matrix/codes.js +15 -0
  209. package/dist/core/process-matrix/codes.js.map +1 -0
  210. package/dist/core/process-matrix/runtime.d.ts +63 -0
  211. package/dist/core/process-matrix/runtime.d.ts.map +1 -0
  212. package/dist/core/process-matrix/runtime.js +310 -0
  213. package/dist/core/process-matrix/runtime.js.map +1 -0
  214. package/dist/core/process-matrix/store.d.ts +22 -0
  215. package/dist/core/process-matrix/store.d.ts.map +1 -0
  216. package/dist/core/process-matrix/store.js +80 -0
  217. package/dist/core/process-matrix/store.js.map +1 -0
  218. package/dist/core/process-matrix/supervisor.d.ts +72 -0
  219. package/dist/core/process-matrix/supervisor.d.ts.map +1 -0
  220. package/dist/core/process-matrix/supervisor.js +130 -0
  221. package/dist/core/process-matrix/supervisor.js.map +1 -0
  222. package/dist/core/profile-registry.d.ts +7 -0
  223. package/dist/core/profile-registry.d.ts.map +1 -1
  224. package/dist/core/profile-registry.js +20 -0
  225. package/dist/core/profile-registry.js.map +1 -1
  226. package/dist/core/python-runtime.d.ts.map +1 -1
  227. package/dist/core/python-runtime.js +3 -3
  228. package/dist/core/python-runtime.js.map +1 -1
  229. package/dist/core/reflection-controller.d.ts +29 -5
  230. package/dist/core/reflection-controller.d.ts.map +1 -1
  231. package/dist/core/reflection-controller.js +215 -126
  232. package/dist/core/reflection-controller.js.map +1 -1
  233. package/dist/core/reload-blockers.d.ts +36 -0
  234. package/dist/core/reload-blockers.d.ts.map +1 -1
  235. package/dist/core/reload-blockers.js +44 -0
  236. package/dist/core/reload-blockers.js.map +1 -1
  237. package/dist/core/resource-loader.d.ts.map +1 -1
  238. package/dist/core/resource-loader.js +8 -7
  239. package/dist/core/resource-loader.js.map +1 -1
  240. package/dist/core/runtime-builder.d.ts +58 -5
  241. package/dist/core/runtime-builder.d.ts.map +1 -1
  242. package/dist/core/runtime-builder.js +209 -25
  243. package/dist/core/runtime-builder.js.map +1 -1
  244. package/dist/core/scout-controller.d.ts +6 -0
  245. package/dist/core/scout-controller.d.ts.map +1 -1
  246. package/dist/core/scout-controller.js +66 -52
  247. package/dist/core/scout-controller.js.map +1 -1
  248. package/dist/core/sdk.d.ts.map +1 -1
  249. package/dist/core/sdk.js +3 -3
  250. package/dist/core/sdk.js.map +1 -1
  251. package/dist/core/session-role.d.ts +31 -0
  252. package/dist/core/session-role.d.ts.map +1 -0
  253. package/dist/core/session-role.js +52 -0
  254. package/dist/core/session-role.js.map +1 -0
  255. package/dist/core/settings-manager.d.ts +42 -3
  256. package/dist/core/settings-manager.d.ts.map +1 -1
  257. package/dist/core/settings-manager.js +94 -60
  258. package/dist/core/settings-manager.js.map +1 -1
  259. package/dist/core/system-prompt-builder.d.ts +12 -0
  260. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  261. package/dist/core/system-prompt-builder.js +6 -0
  262. package/dist/core/system-prompt-builder.js.map +1 -1
  263. package/dist/core/system-prompt.d.ts +14 -1
  264. package/dist/core/system-prompt.d.ts.map +1 -1
  265. package/dist/core/system-prompt.js +20 -3
  266. package/dist/core/system-prompt.js.map +1 -1
  267. package/dist/core/tasks/session-task-state.d.ts +11 -2
  268. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  269. package/dist/core/tasks/session-task-state.js +27 -11
  270. package/dist/core/tasks/session-task-state.js.map +1 -1
  271. package/dist/core/tasks/task-contract-monitor.d.ts +45 -0
  272. package/dist/core/tasks/task-contract-monitor.d.ts.map +1 -0
  273. package/dist/core/tasks/task-contract-monitor.js +56 -0
  274. package/dist/core/tasks/task-contract-monitor.js.map +1 -0
  275. package/dist/core/tasks/task-state.d.ts +8 -0
  276. package/dist/core/tasks/task-state.d.ts.map +1 -1
  277. package/dist/core/tasks/task-state.js +28 -1
  278. package/dist/core/tasks/task-state.js.map +1 -1
  279. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  280. package/dist/core/tool-gate-controller.js +5 -0
  281. package/dist/core/tool-gate-controller.js.map +1 -1
  282. package/dist/core/tool-recovery-log-records.d.ts +7 -0
  283. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  284. package/dist/core/tool-recovery-log-records.js +14 -6
  285. package/dist/core/tool-recovery-log-records.js.map +1 -1
  286. package/dist/core/tool-selection/promotion.d.ts +54 -0
  287. package/dist/core/tool-selection/promotion.d.ts.map +1 -0
  288. package/dist/core/tool-selection/promotion.js +81 -0
  289. package/dist/core/tool-selection/promotion.js.map +1 -0
  290. package/dist/core/tool-selection/tool-performance-store.d.ts +37 -0
  291. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  292. package/dist/core/tool-selection/tool-performance-store.js +87 -3
  293. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  294. package/dist/core/tool-selection/tool-selection-controller.d.ts +45 -0
  295. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
  296. package/dist/core/tool-selection/tool-selection-controller.js +96 -0
  297. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
  298. package/dist/core/tools/bash.d.ts +18 -0
  299. package/dist/core/tools/bash.d.ts.map +1 -1
  300. package/dist/core/tools/bash.js +97 -18
  301. package/dist/core/tools/bash.js.map +1 -1
  302. package/dist/core/tools/delegate-status.d.ts +14 -0
  303. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  304. package/dist/core/tools/delegate-status.js +82 -7
  305. package/dist/core/tools/delegate-status.js.map +1 -1
  306. package/dist/core/tools/delegate.d.ts.map +1 -1
  307. package/dist/core/tools/delegate.js +25 -8
  308. package/dist/core/tools/delegate.js.map +1 -1
  309. package/dist/core/tools/find.d.ts.map +1 -1
  310. package/dist/core/tools/find.js +52 -44
  311. package/dist/core/tools/find.js.map +1 -1
  312. package/dist/core/tools/goal.d.ts +94 -3
  313. package/dist/core/tools/goal.d.ts.map +1 -1
  314. package/dist/core/tools/goal.js +165 -15
  315. package/dist/core/tools/goal.js.map +1 -1
  316. package/dist/core/tools/grep.d.ts.map +1 -1
  317. package/dist/core/tools/grep.js +5 -4
  318. package/dist/core/tools/grep.js.map +1 -1
  319. package/dist/core/tools/model-fitness.d.ts +7 -0
  320. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  321. package/dist/core/tools/model-fitness.js +2 -2
  322. package/dist/core/tools/model-fitness.js.map +1 -1
  323. package/dist/core/tools/render-utils.d.ts.map +1 -1
  324. package/dist/core/tools/render-utils.js +1 -1
  325. package/dist/core/tools/render-utils.js.map +1 -1
  326. package/dist/core/tools/shell-contract-router.d.ts +6 -1
  327. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  328. package/dist/core/tools/shell-contract-router.js +69 -13
  329. package/dist/core/tools/shell-contract-router.js.map +1 -1
  330. package/dist/core/tools/shell-session.d.ts +89 -0
  331. package/dist/core/tools/shell-session.d.ts.map +1 -0
  332. package/dist/core/tools/shell-session.js +432 -0
  333. package/dist/core/tools/shell-session.js.map +1 -0
  334. package/dist/core/tools/task-steps.d.ts +4 -0
  335. package/dist/core/tools/task-steps.d.ts.map +1 -1
  336. package/dist/core/tools/task-steps.js +63 -8
  337. package/dist/core/tools/task-steps.js.map +1 -1
  338. package/dist/core/tools/tmux-dispatch.d.ts +86 -0
  339. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -0
  340. package/dist/core/tools/tmux-dispatch.js +91 -0
  341. package/dist/core/tools/tmux-dispatch.js.map +1 -0
  342. package/dist/core/tools/windows-shell-engine.d.ts +42 -0
  343. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -0
  344. package/dist/core/tools/windows-shell-engine.js +153 -0
  345. package/dist/core/tools/windows-shell-engine.js.map +1 -0
  346. package/dist/core/tools/windows-shell-state.d.ts +40 -0
  347. package/dist/core/tools/windows-shell-state.d.ts.map +1 -0
  348. package/dist/core/tools/windows-shell-state.js +59 -0
  349. package/dist/core/tools/windows-shell-state.js.map +1 -0
  350. package/dist/core/tools/worktree-sync.d.ts +24 -0
  351. package/dist/core/tools/worktree-sync.d.ts.map +1 -0
  352. package/dist/core/tools/worktree-sync.js +338 -0
  353. package/dist/core/tools/worktree-sync.js.map +1 -0
  354. package/dist/core/trust-manager.d.ts +4 -1
  355. package/dist/core/trust-manager.d.ts.map +1 -1
  356. package/dist/core/trust-manager.js +20 -2
  357. package/dist/core/trust-manager.js.map +1 -1
  358. package/dist/core/util/atomic-file.d.ts +55 -0
  359. package/dist/core/util/atomic-file.d.ts.map +1 -0
  360. package/dist/core/util/atomic-file.js +255 -0
  361. package/dist/core/util/atomic-file.js.map +1 -0
  362. package/dist/core/util/minimatch-cache.d.ts +33 -0
  363. package/dist/core/util/minimatch-cache.d.ts.map +1 -0
  364. package/dist/core/util/minimatch-cache.js +0 -0
  365. package/dist/core/util/minimatch-cache.js.map +1 -0
  366. package/dist/core/worktree-sync/codes.d.ts +227 -0
  367. package/dist/core/worktree-sync/codes.d.ts.map +1 -0
  368. package/dist/core/worktree-sync/codes.js +14 -0
  369. package/dist/core/worktree-sync/codes.js.map +1 -0
  370. package/dist/core/worktree-sync/git-engine.d.ts +156 -0
  371. package/dist/core/worktree-sync/git-engine.d.ts.map +1 -0
  372. package/dist/core/worktree-sync/git-engine.js +1191 -0
  373. package/dist/core/worktree-sync/git-engine.js.map +1 -0
  374. package/dist/core/worktree-sync/lane-gate.d.ts +75 -0
  375. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -0
  376. package/dist/core/worktree-sync/lane-gate.js +360 -0
  377. package/dist/core/worktree-sync/lane-gate.js.map +1 -0
  378. package/dist/core/worktree-sync/runtime.d.ts +47 -0
  379. package/dist/core/worktree-sync/runtime.d.ts.map +1 -0
  380. package/dist/core/worktree-sync/runtime.js +96 -0
  381. package/dist/core/worktree-sync/runtime.js.map +1 -0
  382. package/dist/core/worktree-sync/store.d.ts +69 -0
  383. package/dist/core/worktree-sync/store.d.ts.map +1 -0
  384. package/dist/core/worktree-sync/store.js +247 -0
  385. package/dist/core/worktree-sync/store.js.map +1 -0
  386. package/dist/core/worktree-sync/watcher.d.ts +29 -0
  387. package/dist/core/worktree-sync/watcher.d.ts.map +1 -0
  388. package/dist/core/worktree-sync/watcher.js +93 -0
  389. package/dist/core/worktree-sync/watcher.js.map +1 -0
  390. package/dist/main.d.ts.map +1 -1
  391. package/dist/main.js +94 -0
  392. package/dist/main.js.map +1 -1
  393. package/dist/migrations.d.ts +9 -0
  394. package/dist/migrations.d.ts.map +1 -1
  395. package/dist/migrations.js +38 -0
  396. package/dist/migrations.js.map +1 -1
  397. package/dist/modes/interactive/auto-learn-controller.d.ts +16 -1
  398. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  399. package/dist/modes/interactive/auto-learn-controller.js +50 -8
  400. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  401. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  402. package/dist/modes/interactive/components/profile-resource-editor.js +23 -1
  403. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  404. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  405. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  406. package/dist/modes/interactive/interactive-mode.js +4 -0
  407. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  408. package/dist/modes/interactive/local-model-commands.d.ts +43 -0
  409. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  410. package/dist/modes/interactive/local-model-commands.js +290 -3
  411. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  412. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  413. package/dist/modes/interactive/session-flow-commands.js +24 -4
  414. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  415. package/dist/utils/fs-watch.d.ts +11 -0
  416. package/dist/utils/fs-watch.d.ts.map +1 -1
  417. package/dist/utils/fs-watch.js +20 -2
  418. package/dist/utils/fs-watch.js.map +1 -1
  419. package/dist/utils/highlight-js-languages.d.ts +4 -0
  420. package/dist/utils/highlight-js-languages.d.ts.map +1 -0
  421. package/dist/utils/highlight-js-languages.js +573 -0
  422. package/dist/utils/highlight-js-languages.js.map +1 -0
  423. package/dist/utils/shell.d.ts +7 -1
  424. package/dist/utils/shell.d.ts.map +1 -1
  425. package/dist/utils/shell.js +39 -9
  426. package/dist/utils/shell.js.map +1 -1
  427. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  428. package/dist/utils/syntax-highlight.js +53 -5
  429. package/dist/utils/syntax-highlight.js.map +1 -1
  430. package/dist/utils/tools-manager.d.ts.map +1 -1
  431. package/dist/utils/tools-manager.js +112 -1
  432. package/dist/utils/tools-manager.js.map +1 -1
  433. package/docs/development.md +2 -0
  434. package/docs/packages.md +1 -1
  435. package/docs/process-matrix.md +120 -0
  436. package/docs/settings.md +5 -2
  437. package/docs/tmux-agent-manager.md +85 -2
  438. package/docs/windows.md +52 -3
  439. package/docs/work-directory.md +29 -0
  440. package/docs/worktree-sync.md +250 -0
  441. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  442. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  443. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  444. package/examples/extensions/sandbox/package-lock.json +2 -2
  445. package/examples/extensions/sandbox/package.json +1 -1
  446. package/examples/extensions/with-deps/package-lock.json +2 -2
  447. package/examples/extensions/with-deps/package.json +1 -1
  448. package/npm-shrinkwrap.json +12 -12
  449. package/package.json +10 -4
  450. package/docs/integration-sweep-builder-blueprint-2026-07-09.md +0 -365
  451. package/docs/integration-sweep-resume-2026-07-09.md +0 -407
@@ -1 +1 @@
1
- {"version":3,"file":"model-router-controller.d.ts","sourceRoot":"","sources":["../../src/core/model-router-controller.ts"],"names":[],"mappings":"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","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\tconst routerThinkingSettings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst configuredThinking = !routeDecision\n\t\t\t? undefined\n\t\t\t: routeDecision.reasonCode === \"executor_direct\"\n\t\t\t\t? routerThinkingSettings.executorThinking\n\t\t\t\t: routeDecision.tier === \"cheap\"\n\t\t\t\t\t? routerThinkingSettings.cheapThinking\n\t\t\t\t\t: routeDecision.tier === \"medium\"\n\t\t\t\t\t\t? routerThinkingSettings.mediumThinking\n\t\t\t\t\t\t: routeDecision.tier === \"expensive\"\n\t\t\t\t\t\t\t? routerThinkingSettings.expensiveThinking\n\t\t\t\t\t\t\t: undefined;\n\t\tconst routedThinkingLevel = clampThinkingLevel(\n\t\t\troutedModel,\n\t\t\tconfiguredThinking ?? previousThinkingLevel,\n\t\t) as ThinkingLevel;\n\t\tconst modelChanged = !modelsAreEqual(this.deps.getModel(), routedModel);\n\t\tconst thinkingChanged = routedThinkingLevel !== previousThinkingLevel;\n\t\tif (modelChanged || thinkingChanged) {\n\t\t\tagent.state.model = routedModel;\n\t\t\t// Per-tier thinking (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\tagent.state.thinkingLevel = routedThinkingLevel;\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\tif (modelChanged) {\n\t\t\t\tconst routedProfile = deriveModelCapabilityProfile({\n\t\t\t\t\tcontextWindow: routedModel.contextWindow,\n\t\t\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t\t\t});\n\t\t\t\tif (routedProfile.class !== \"full\") {\n\t\t\t\t\tconst allowed = new Set(\n\t\t\t\t\t\tfilterToolNamesForCapability(\n\t\t\t\t\t\t\tpreviousTurnTools.map((tool) => tool.name),\n\t\t\t\t\t\t\troutedProfile,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tswappedTools = previousTurnTools.filter((tool) => allowed.has(tool.name));\n\t\t\t\t\tagent.state.tools = swappedTools;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// The routed prompt follows both the routed tool surface and its effective thinking mode.\n\t\t\t// This removes an Ultra policy during max/Luna routes, including same-model tier overrides.\n\t\t\t// Per-turn only; a live extension override is preserved rather than silently replaced.\n\t\t\tif (agent.state.systemPrompt === this.deps.getBaseSystemPrompt()) {\n\t\t\t\tswappedSystemPrompt = this.deps.buildSystemPromptForToolNames(agent.state.tools.map((tool) => tool.name));\n\t\t\t\tagent.state.systemPrompt = swappedSystemPrompt;\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tawait this.deps.runAgentPrompt(messages);\n\t\t\t// Speculative muscle-retry (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":"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","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 MUTATION escalation branch ({@link\n * maybeEscalateToolCall}), the tool-name-agnostic VALIDATION-FAILURE escalation branch for cloud\n * models ({@link requestValidationFailureEscalation} — de-conflated from the mutation gate; see the\n * capability-gate spine doctrine, which routes local/managed models to an evidence-gated\n * native→phone auto-probe on AgentSession instead), the message_end cheap-turn buffering ({@link\n * captureSessionMessage}), the retry-event suppression ({@link isRetryInFlight}), the public\n * getModelRouterStatus / autonomy-telemetry reads, and the tier resolution's consultation of the\n * persisted `/toolprobe` verdict for local/managed tier models ({@link\n * ModelRouterControllerDeps.getToolProbeVerdict}).\n */\n\nimport { createHash } from \"node:crypto\";\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 { isLocalOrManagedRouterModel, shouldEscalateModelRouterTool } from \"./model-router/tool-escalation.ts\";\nimport type { ModelToolProbeVerdict } from \"./models/adaptation-store.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport {\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\n/**\n * Deterministic `addSpawnedUsage` reportId: `kind` + session id + a content hash of `identity`\n * (the text driving the call — never `Date.now`/random). Same identity on a retry of the same\n * logical work unit yields the same id, so the ledger's `seenSubagentReportIds` dedupe catches a\n * duplicate report instead of double-counting spend.\n */\nfunction deriveSpawnedUsageReportId(kind: string, sessionId: string, identity: string): string {\n\tconst digest = createHash(\"sha256\").update(identity).digest(\"hex\").slice(0, 16);\n\treturn `${kind}:${sessionId}:${digest}`;\n}\n\nexport interface ModelRouterControllerDeps {\n\t/** Live agent — the controller reads/writes agent.state.{model,thinkingLevel,tools,systemPrompt,messages}\n\t * for the per-turn tier swap and aborts it on a mutating-tool escalation. */\n\tgetAgent(): Agent;\n\t/** Current session model, used to decide whether a routed turn actually swaps the model. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Router/executor/judge/thinking settings + capability mode (all opt-in gates). */\n\tgetSettingsManager(): SettingsManager;\n\t/** Session log: routed-turn message buffering/persistence, decision persistence, recent-decision status. */\n\tgetSessionManager(): SessionManager;\n\t/** Resolves configured route/judge/executor model patterns against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Session-scoped provider/model quota exhaustion guard. */\n\tisModelExhausted(model: Model<Api>): boolean;\n\t/** Status snapshot for exhausted models and the last failover notice. */\n\tgetFailoverStatus(): ModelRouterFailoverStatus;\n\t/** Root dir the host-keyed {@link FitnessStore} lives under (executor tool-call fitness gate). */\n\tgetAgentDir(): string;\n\t/** Aborts the judge's bounded completion when the session is disposed. */\n\tgetReflectionSignal(): AbortSignal;\n\t/** Base (extension-free) system prompt — the tier swap only sheds tools when the turn is on it. */\n\tgetBaseSystemPrompt(): string;\n\t/** The 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. `reportId` is REQUIRED: every\n\t * caller derives a stable id from the work unit's identity so a retry cannot double-count. */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts: { label?: string; sourceSessionId?: string; reportId: string },\n\t): string | undefined;\n\t/** Session event stream (executor-miss warning). */\n\temit(event: AgentSessionEvent): void;\n\t/** Autonomy telemetry stream (one route-decision event per user-facing routed turn). */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Resolves the judge model pattern via {@link BackgroundLaneController}. */\n\tresolveLaneModel(pattern: string): Model<Api> | undefined;\n\t/** Fitness-gated reflex-brain model via {@link ContextPipeline} (executor speculative refinement). */\n\tresolveCurationModelIfFit(): Model<Api> | undefined;\n\t/** Persisted `/toolprobe` verdict for this model (native / text-protocol / none), or undefined\n\t * when never probed. Tier-resolution's consultation reads this ONLY for local/managed models\n\t * ({@link isLocalOrManagedRouterModel}); cloud models never call it. */\n\tgetToolProbeVerdict(model: Model<Api>): ModelToolProbeVerdict | undefined;\n}\n\n/**\n * Owns the model-router turn routing extracted from {@link AgentSession}. See the module header for the\n * drive-path boundary that keeps the agent.prompt()/continue() loop 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 * Tool-name-agnostic validation-failure escalation gate, called from\n\t * AgentSession's onToolValidationEscalation handler for a CLOUD model only — see the\n\t * capability-gate-spine doctrine (local/managed models never reach this method; they trigger\n\t * the evidence-gated native→phone auto-probe instead). Unlike {@link maybeEscalateToolCall} (the\n\t * beforeToolCall MUTATION gate, still governed by `shouldEscalateModelRouterTool`/\n\t * READ_ONLY_TOOL_NAMES — a legitimate, unrelated mutation-blast-radius policy), \"the model\n\t * repeatedly cannot construct valid arguments for this tool\" is evidence about the MODEL's\n\t * capability, not about the tool's mutation status, so a read-only tool's repeated validation\n\t * failure now escalates a cheap routed turn exactly like a mutating tool's would — takes no\n\t * tool-name/args input at all (unlike maybeEscalateToolCall), because every repeated validation\n\t * failure escalates regardless of which tool or model triggered it. No-op outside an active\n\t * cheap-tier routed turn, same scoping as maybeEscalateToolCall.\n\t */\n\trequestValidationFailureEscalation(): void {\n\t\tif (this._activeModelRouterRoute?.tier !== \"cheap\") return;\n\t\tthis._modelRouterEscalationRequested = true;\n\t\tthis.deps.getAgent().abort();\n\t}\n\n\t/**\n\t * message_end hook: while a cheap routed turn is buffering, capture its messages into the session\n\t * buffer instead of persisting them (they are flushed on success or discarded on escalation).\n\t * Returns true when the message was buffered, so the host skips its own persistence.\n\t */\n\tcaptureSessionMessage(message: AgentMessage): boolean {\n\t\tconst modelRouterBuffer = this._modelRouterSessionBuffer;\n\t\tif (!modelRouterBuffer) return false;\n\t\tif (message.role === \"custom\") {\n\t\t\tbufferModelRouterSessionCustomMessage(modelRouterBuffer, message);\n\t\t\treturn true;\n\t\t}\n\t\tif (message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tbufferModelRouterSessionMessage(modelRouterBuffer, message as Message);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate _isModelAvailableAndAuthed(pattern: string): boolean {\n\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) return false;\n\t\treturn this.deps.getModelRegistry().hasConfiguredAuth(resolved.model);\n\t}\n\n\tprivate _evaluateModelFitness(surface: FitnessGatedSurface, model: Model<Api>): FitnessGateVerdict {\n\t\tconst fitness = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === formatModelRouterModel(model));\n\t\treturn evaluateSurfaceFitness(surface, fitness?.report);\n\t}\n\n\tprivate _formatFitnessFailure(verdict: Exclude<FitnessGateVerdict, { fit: true }>): string {\n\t\treturn verdict.reason === \"unprobed\" ? \"unprobed\" : `${verdict.lane} ${verdict.succeeded}/${verdict.total}`;\n\t}\n\n\tprivate _routerSurfaceForTier(tier: \"cheap\" | \"medium\" | \"expensive\"): FitnessGatedSurface {\n\t\treturn tier === \"cheap\" ? \"router_cheap\" : tier === \"medium\" ? \"router_medium\" : \"router_expensive\";\n\t}\n\n\tprivate _getRouterTierFitnessStatuses(): ModelRouterFitnessStatuses {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst statuses: ModelRouterFitnessStatuses = {};\n\t\tfor (const tier of [\"cheap\", \"medium\", \"expensive\"] as const) {\n\t\t\tconst pattern =\n\t\t\t\ttier === \"cheap\" ? settings.cheapModel : tier === \"medium\" ? settings.mediumModel : settings.expensiveModel;\n\t\t\tif (!pattern) continue;\n\t\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (!resolved.model || !this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) continue;\n\t\t\tconst verdict = this._evaluateModelFitness(this._routerSurfaceForTier(tier), resolved.model);\n\t\t\tstatuses[tier] = verdict.fit\n\t\t\t\t? { status: verdict.probed ? \"fit\" : \"unprobed\" }\n\t\t\t\t: verdict.reason === \"unprobed\"\n\t\t\t\t\t? { status: \"unprobed\" }\n\t\t\t\t\t: { status: \"unfit\", lane: verdict.lane, succeeded: verdict.succeeded, total: verdict.total };\n\t\t}\n\t\treturn statuses;\n\t}\n\n\tprivate _resolveExpensiveFallbackRoute(\n\t\tdecision: RouteDecision,\n\t\treasonCode: string,\n\t\treason: string,\n\t): { decision: RouteDecision; model: Model<Api> } | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst expensivePattern = settings.expensiveModel;\n\t\tif (!expensivePattern || !this._isModelAvailableAndAuthed(expensivePattern)) return undefined;\n\t\tconst resolvedExpensive = resolveCliModel({\n\t\t\tcliModel: expensivePattern,\n\t\t\tmodelRegistry: this.deps.getModelRegistry(),\n\t\t});\n\t\tif (!resolvedExpensive.model) return undefined;\n\t\tif (this.deps.isModelExhausted(resolvedExpensive.model)) {\n\t\t\tthis._lastModelRouterSkipReason = \"expensive model exhausted: quota\";\n\t\t\treturn undefined;\n\t\t}\n\t\tif (settings.fitnessGate) {\n\t\t\tconst verdict = this._evaluateModelFitness(\"router_expensive\", resolvedExpensive.model);\n\t\t\tif (!verdict.fit) {\n\t\t\t\tthis._lastModelRouterSkipReason = `expensive model unfit: ${this._formatFitnessFailure(verdict)} (fitness gate)`;\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\t\tdecision.fallbackFrom = \"medium\";\n\t\tdecision.tier = \"expensive\";\n\t\tdecision.reasonCode = reasonCode;\n\t\tdecision.reasons = [...decision.reasons, reason];\n\t\tdecision.model = formatModelRouterModel(resolvedExpensive.model);\n\t\tthis._lastModelRouterSkipReason = undefined;\n\t\treturn { decision, model: resolvedExpensive.model };\n\t}\n\n\tprivate _resolveExecutorRoute(\n\t\tprompt: string,\n\t\texecutorPattern: string | undefined,\n\t): { decision: RouteDecision; model: Model<Api> } | undefined {\n\t\tif (!executorPattern) return undefined;\n\t\ttry {\n\t\t\tconst verdict = classifyExecutorTurn(prompt, this.deps.getSettingsManager().getToolkitScripts());\n\t\t\tif (!verdict.execute) return undefined;\n\t\t\tconst resolved = resolveCliModel({ cliModel: executorPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (!resolved.model || !this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) return undefined;\n\t\t\t// Fitness gate: the executor must have PROVEN tool-calling on this host (same\n\t\t\t// canonical-ref discipline as the curation gate).\n\t\t\tif (!this._evaluateModelFitness(\"executor\", resolved.model).fit) return undefined;\n\t\t\tthis._lastModelRouterIntent = \"research\";\n\t\t\treturn {\n\t\t\t\tdecision: {\n\t\t\t\t\ttier: \"cheap\",\n\t\t\t\t\trisk: \"scoped-write\",\n\t\t\t\t\tconfidence: 1,\n\t\t\t\t\treasonCode: \"executor_direct\",\n\t\t\t\t\treasons: [`Executor lane: Level-0 direct hit on toolkit script \"${verdict.scriptName}\"`],\n\t\t\t\t},\n\t\t\t\tmodel: resolved.model,\n\t\t\t};\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/** True if a run_toolkit_script tool result since `fromIndex` actually EXECUTED (not error/ambiguous). */\n\tprivate _executorTurnExecutedScript(fromIndex: number): boolean {\n\t\tfor (const message of this.deps.getAgent().state.messages.slice(fromIndex)) {\n\t\t\tif ((message as { role?: string }).role !== \"toolResult\") continue;\n\t\t\tif ((message as { toolName?: string }).toolName !== \"run_toolkit_script\") continue;\n\t\t\tif ((message as { isError?: boolean }).isError === true) continue;\n\t\t\tconst outcome = (message as { details?: { outcome?: unknown } }).details?.outcome;\n\t\t\tif (outcome === \"executed\") return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Ask the reflex brain to refine the last user request into an explicit toolkit instruction. */\n\tprivate async _buildExecutorRefinedPrompt(messages: AgentMessage | AgentMessage[]): Promise<string | undefined> {\n\t\ttry {\n\t\t\tconst model = this.deps.resolveCurationModelIfFit();\n\t\t\tif (!model) return undefined;\n\t\t\tconst list = Array.isArray(messages) ? messages : [messages];\n\t\t\tconst request = latestUserPromptText(list.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\t// Stable per-lane synthetic affinity key for repeat executor-brain warmups.\n\t\t\t\tlaneKind: \"executor\",\n\t\t\t});\n\t\t\tif (completion.usage.cost.total > 0 || completion.usage.totalTokens > 0) {\n\t\t\t\t// `reportId` keyed on the request text driving THIS refinement — stable across a\n\t\t\t\t// retry of the same routed turn, distinct across genuinely different requests.\n\t\t\t\tconst reportId = deriveSpawnedUsageReportId(\n\t\t\t\t\t\"executor-brain\",\n\t\t\t\t\tthis.deps.getSessionManager().getSessionId(),\n\t\t\t\t\trequest,\n\t\t\t\t);\n\t\t\t\tthis.deps.addSpawnedUsage(completion.usage, { label: \"executor-brain-warmup\", reportId });\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// Executor lane: a Level-0 DIRECT toolkit hit on a command-shaped prompt routes the\n\t\t// whole turn to the configured local executor (tool-call-fitness-gated) instead of\n\t\t// spending the frontier model on a one-tool reflex. Ambiguity never routes here — it\n\t\t// stays with the big model and the reflex brain. Deterministic, so the judge is skipped.\n\t\tconst executorRoute = this._resolveExecutorRoute(prompt, settings.executorModel);\n\t\tif (executorRoute) return executorRoute;\n\n\t\tconst decision = classifyModelRouterRoute(prompt);\n\t\tthis._lastModelRouterIntent = decision.tier === \"cheap\" ? \"research\" : \"modify\";\n\n\t\t// Learning tier must not be selected for normal user prompts\n\t\tif (decision.tier === \"learning\") {\n\t\t\tthis._lastModelRouterSkipReason = \"learning tier not supported for user prompts\";\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst modelPattern =\n\t\t\tsettings[\n\t\t\t\tdecision.tier === \"cheap\" ? \"cheapModel\" : decision.tier === \"medium\" ? \"mediumModel\" : \"expensiveModel\"\n\t\t\t];\n\t\tconst label =\n\t\t\tdecision.tier === \"cheap\" ? \"cheap model\" : decision.tier === \"medium\" ? \"medium model\" : \"expensive model\";\n\n\t\tif (decision.tier === \"medium\" && (!modelPattern || !this._isModelAvailableAndAuthed(modelPattern))) {\n\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\tdecision,\n\t\t\t\t\"medium_unavailable_fallback_expensive\",\n\t\t\t\t\"Medium model is unavailable, falling back to expensive model\",\n\t\t\t);\n\t\t\tif (fallback) return fallback;\n\t\t\tthis._lastModelRouterSkipReason ??= \"medium model and expensive fallback are unavailable\";\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (!modelPattern) {\n\t\t\tthis._lastModelRouterSkipReason = `${label} unset`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst resolved = resolveCliModel({ cliModel: modelPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) {\n\t\t\tthis._lastModelRouterSkipReason = `${label} unresolved: ${modelPattern}`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst resolvedName = formatModelRouterModel(resolved.model);\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\tthis._lastModelRouterSkipReason = `${label} missing auth: ${resolvedName}`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (this.deps.isModelExhausted(resolved.model)) {\n\t\t\tif (decision.tier === \"medium\") {\n\t\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\t\tdecision,\n\t\t\t\t\t\"medium_exhausted_fallback_expensive\",\n\t\t\t\t\t\"Medium model exhausted: quota; falling back to expensive model\",\n\t\t\t\t);\n\t\t\t\tif (fallback) return fallback;\n\t\t\t}\n\t\t\tthis._lastModelRouterSkipReason = `${decision.tier} model exhausted: quota`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// For a LOCAL/MANAGED tier model (never cloud — isLocalOrManagedRouterModel), honor a\n\t\t// persisted \"no working tool-call path\" probe verdict. This is an ALWAYS-ON doctrine gate,\n\t\t// deliberately not behind the opt-in `fitnessGate` setting below (cloud fitness gating stays\n\t\t// opt-in; this local/managed check is unconditional, matching the auto-probe that writes\n\t\t// the verdict). \"native\"/\"text-protocol\"/unprobed all fall through unchanged: native wins\n\t\t// when it works, the phone lane engages downstream via _textProtocolFlag, and an unprobed\n\t\t// model routes native-first (the evidence loop, not a speculative pre-block).\n\t\tif (isLocalOrManagedRouterModel(resolved.model) && this.deps.getToolProbeVerdict(resolved.model) === \"none\") {\n\t\t\tif (decision.tier === \"medium\") {\n\t\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\t\tdecision,\n\t\t\t\t\t\"medium_no_tool_path_fallback_expensive\",\n\t\t\t\t\t\"Medium model has no working tool-call path (native and text-protocol probe both failed); falling back to expensive model\",\n\t\t\t\t);\n\t\t\t\tif (fallback) return fallback;\n\t\t\t}\n\t\t\tthis._lastModelRouterSkipReason = `${decision.tier} model has no working tool-call path (native and text-protocol probe both failed)`;\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (settings.fitnessGate) {\n\t\t\tconst verdict = this._evaluateModelFitness(this._routerSurfaceForTier(decision.tier), resolved.model);\n\t\t\tif (!verdict.fit) {\n\t\t\t\tif (decision.tier === \"medium\") {\n\t\t\t\t\tconst failure = this._formatFitnessFailure(verdict);\n\t\t\t\t\tconst fallback = this._resolveExpensiveFallbackRoute(\n\t\t\t\t\t\tdecision,\n\t\t\t\t\t\t\"medium_unfit_fallback_expensive\",\n\t\t\t\t\t\t`Medium model is unfit (${failure}); falling back to expensive model`,\n\t\t\t\t\t);\n\t\t\t\t\tif (fallback) return fallback;\n\t\t\t\t}\n\t\t\t\tthis._lastModelRouterSkipReason = `${decision.tier} model unfit: ${this._formatFitnessFailure(verdict)} (fitness gate)`;\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t}\n\n\t\tthis._lastModelRouterSkipReason = undefined;\n\t\tdecision.model = resolvedName;\n\t\treturn { decision, model: resolved.model };\n\t}\n\n\tprivate _resolveModelRouterModelForIntent(intent: ModelRouterIntent): Model<Api> | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst modelPattern = intent === \"research\" ? settings.cheapModel : settings.expensiveModel;\n\t\tif (!modelPattern) return undefined;\n\t\tconst resolved = resolveCliModel({ cliModel: modelPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) return undefined;\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) return undefined;\n\t\treturn this.deps.isModelExhausted(resolved.model) ? undefined : resolved.model;\n\t}\n\n\tresolveConfiguredTierModel(tier: \"cheap\" | \"medium\" | \"expensive\"): Model<Api> | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst pattern =\n\t\t\ttier === \"cheap\" ? settings.cheapModel : tier === \"medium\" ? settings.mediumModel : settings.expensiveModel;\n\t\tif (!pattern) return undefined;\n\t\tconst resolved = resolveCliModel({ cliModel: pattern, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model) return undefined;\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) return undefined;\n\t\tif (this.deps.isModelExhausted(resolved.model)) return undefined;\n\t\t// (Same doctrine as _resolveModelRouterTurnRoute above): never resolve a local/managed\n\t\t// model the probe has already graded as having no working tool-call path.\n\t\tif (isLocalOrManagedRouterModel(resolved.model) && this.deps.getToolProbeVerdict(resolved.model) === \"none\") {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn resolved.model;\n\t}\n\n\t/**\n\t * Router resolution with the routing judge (auto-on with the router): the regex classifier's\n\t * decision is the baseline; when a judge model resolves (judgeModel, else mediumModel), one\n\t * bounded, tool-less completion may move the tier between cheap/medium/expensive — never to\n\t * learning. Core rule encoded in the judge prompt: planning is never cheap unless genuinely\n\t * trivial. Every fallback stays visible in the decision reasons, and judge spend reports\n\t * through spawned-usage accounting.\n\t */\n\tasync resolveTurnRouteJudged(\n\t\tprompt: string,\n\t\toptions?: { skipJudge?: boolean },\n\t): Promise<{ decision: RouteDecision; model: Model<Api> } | undefined> {\n\t\tconst baseline = this._resolveModelRouterTurnRoute(prompt);\n\t\tif (!baseline) return undefined;\n\t\tif (options?.skipJudge) return baseline;\n\t\t// Deterministic executor routes need no judge (Level-0 already decided).\n\t\tif (baseline.decision.reasonCode === \"executor_direct\") return baseline;\n\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tif (!settings.judgeEnabled) return baseline;\n\t\tif (shouldSkipRouteJudgeForStaticDecision(baseline.decision)) return baseline;\n\t\tconst judgePattern = settings.judgeModel ?? settings.mediumModel;\n\t\tif (!judgePattern) return baseline;\n\t\tconst judgeModel = this.deps.resolveLaneModel(judgePattern);\n\t\tif (!judgeModel) {\n\t\t\treturn {\n\t\t\t\tdecision: withJudgeUnavailableFallback(\n\t\t\t\t\tbaseline.decision,\n\t\t\t\t\t`routing judge unavailable: ${judgePattern} did not resolve; baseline kept`,\n\t\t\t\t),\n\t\t\t\tmodel: baseline.model,\n\t\t\t};\n\t\t}\n\t\tif (settings.fitnessGate) {\n\t\t\tconst verdict = this._evaluateModelFitness(\"router_judge\", judgeModel);\n\t\t\tif (!verdict.fit) {\n\t\t\t\treturn {\n\t\t\t\t\tdecision: {\n\t\t\t\t\t\t...baseline.decision,\n\t\t\t\t\t\treasons: [\n\t\t\t\t\t\t\t...baseline.decision.reasons,\n\t\t\t\t\t\t\t`routing judge skipped: ${formatModelRouterModel(judgeModel)} unfit (${this._formatFitnessFailure(verdict)})`,\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t\tmodel: baseline.model,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tlet spentUsage: Usage | undefined;\n\t\tconst judged = await runRouteJudge({\n\t\t\tprompt,\n\t\t\tbaseline: baseline.decision,\n\t\t\tsignal: this.deps.getReflectionSignal(),\n\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\tconst completion = await 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: judgeThinking overrides the judge's own completion; unset\n\t\t\t\t\t// keeps today's \"off\" (the judge is a cheap classification call by default).\n\t\t\t\t\tthinkingLevel: settings.judgeThinking ?? \"off\",\n\t\t\t\t\tmaxTokens: ROUTE_JUDGE_MAX_OUTPUT_TOKENS,\n\t\t\t\t\tsignal,\n\t\t\t\t\t// The judge system prompt is static — the provider can cache the prefix.\n\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t// Stable per-lane synthetic affinity key so repeat judge calls hit the same\n\t\t\t\t\t// cache-warm backend.\n\t\t\t\t\tlaneKind: \"route-judge\",\n\t\t\t\t});\n\t\t\t\tspentUsage = completion.usage;\n\t\t\t\treturn {\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\t// `reportId` keyed on the routed prompt text — stable across a retry of the same\n\t\t\t// judged turn, distinct across genuinely different prompts.\n\t\t\tconst reportId = deriveSpawnedUsageReportId(\n\t\t\t\t\"route-judge\",\n\t\t\t\tthis.deps.getSessionManager().getSessionId(),\n\t\t\t\tprompt,\n\t\t\t);\n\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"router-judge\", reportId });\n\t\t}\n\n\t\tif (!judged.verdict || judged.decision.tier === baseline.decision.tier) {\n\t\t\t// Same tier (or judge fell back): keep the baseline model, carry the annotated decision.\n\t\t\treturn { decision: judged.decision, model: baseline.model };\n\t\t}\n\n\t\tconst judgedTier = judged.decision.tier;\n\t\tif (judgedTier !== \"cheap\" && judgedTier !== \"medium\" && judgedTier !== \"expensive\") {\n\t\t\treturn { decision: baseline.decision, model: baseline.model };\n\t\t}\n\t\tconst judgedModel = this.resolveConfiguredTierModel(judgedTier);\n\t\tif (!judgedModel) {\n\t\t\treturn {\n\t\t\t\tdecision: {\n\t\t\t\t\t...baseline.decision,\n\t\t\t\t\treasons: [\n\t\t\t\t\t\t...baseline.decision.reasons,\n\t\t\t\t\t\t`Route judge chose ${judgedTier} but no model resolves for that tier; baseline kept`,\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tmodel: baseline.model,\n\t\t\t};\n\t\t}\n\t\treturn { decision: { ...judged.decision, model: formatModelRouterModel(judgedModel) }, model: judgedModel };\n\t}\n\n\t// biome-ignore lint/correctness/noUnusedPrivateClassMembers: test seam\n\tprivate _resolveModelRouterTurnModel(prompt: string): Model<Api> | undefined {\n\t\tconst resolved = this._resolveModelRouterTurnRoute(prompt);\n\t\treturn resolved?.model;\n\t}\n\n\tgetStatus(formatLabel?: (label: string) => string): string {\n\t\tconst recentDecisions = getRecentModelRouterDecisions(this.deps.getSessionManager().getEntries());\n\t\tconst lastDecision = this._lastModelRouterDecision ?? recentDecisions.at(-1);\n\t\tconst historicalDecisions = this._lastModelRouterDecision ? recentDecisions : recentDecisions.slice(0, -1);\n\t\tconst settings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst lines = [\n\t\t\tformatModelRouterStatus(\n\t\t\t\tsettings,\n\t\t\t\tlastDecision,\n\t\t\t\tformatLabel,\n\t\t\t\thistoricalDecisions,\n\t\t\t\tthis._lastModelRouterSkipReason,\n\t\t\t\tthis._lastModelRouterIntent ?? lastDecision?.intent,\n\t\t\t\tsettings.fitnessGate ? this._getRouterTierFitnessStatuses() : undefined,\n\t\t\t\tthis.deps.getFailoverStatus(),\n\t\t\t),\n\t\t];\n\t\tconst diagnostics = collectModelRouterConfigDiagnostics(\n\t\t\tsettings,\n\t\t\tthis.deps.getModelRegistry(),\n\t\t\tthis.deps.getAgentDir(),\n\t\t);\n\t\tif (diagnostics.length > 0) {\n\t\t\tlines.push(formatLabel ? formatLabel(\"Config diagnostics:\") : \"Config diagnostics:\");\n\t\t\tfor (const diagnostic of diagnostics) {\n\t\t\t\tlines.push(`- ${diagnostic}`);\n\t\t\t}\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tasync runRoutedTurn(\n\t\tmessages: AgentMessage | AgentMessage[],\n\t\troutedModel: Model<Api> | undefined,\n\t\trouteDecision: RouteDecision | undefined,\n\t\tpersistDecision = true,\n\t): Promise<void> {\n\t\tif (!routedModel) {\n\t\t\tawait this.deps.runAgentPrompt(messages);\n\t\t\treturn;\n\t\t}\n\n\t\tconst agent = this.deps.getAgent();\n\t\tconst previousModel = agent.state.model;\n\t\tconst previousThinkingLevel = agent.state.thinkingLevel;\n\t\tconst previousTurnTools = agent.state.tools;\n\t\tconst previousSystemPrompt = agent.state.systemPrompt;\n\t\t// Swap bookkeeping: the exact references the swap below assigns, so the finally can\n\t\t// restore ONLY what IT put there — never assigned when no swap happens (e.g. a full-class\n\t\t// routed profile).\n\t\tlet swappedTools: typeof previousTurnTools | undefined;\n\t\tlet swappedSystemPrompt: typeof previousSystemPrompt | undefined;\n\t\tconst previousActiveModelRouterIntent = this._activeModelRouterIntent;\n\t\tconst previousActiveModelRouterRoute = this._activeModelRouterRoute;\n\t\tconst previousModelRouterSessionBuffer = this._modelRouterSessionBuffer;\n\t\tconst previousModelRouterEscalationRequested = this._modelRouterEscalationRequested;\n\t\tconst bufferRoutedTurn = routeDecision?.tier === \"cheap\";\n\t\tconst originalHistoryLength = agent.state.messages.length;\n\t\tlet retryModel: Model<Api> | undefined;\n\t\tlet completedDecision: ModelRouterDecisionStatus | undefined = routeDecision\n\t\t\t? {\n\t\t\t\t\troute: routeDecision,\n\t\t\t\t\troutedModel: formatModelRouterModel(routedModel),\n\t\t\t\t\toutcome: \"routed\",\n\t\t\t\t\tintent: routeDecision.tier === \"cheap\" ? \"research\" : \"modify\",\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tlet thrownError: unknown;\n\t\tif (routeDecision) {\n\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t}\n\t\tthis._activeModelRouterIntent = routeDecision\n\t\t\t? routeDecision.tier === \"cheap\"\n\t\t\t\t? \"research\"\n\t\t\t\t: \"modify\"\n\t\t\t: undefined;\n\t\tthis._activeModelRouterRoute = routeDecision;\n\t\tif (bufferRoutedTurn) {\n\t\t\tthis._modelRouterSessionBuffer = createModelRouterSessionBuffer();\n\t\t\tthis._modelRouterEscalationRequested = false;\n\t\t}\n\t\tconst routerThinkingSettings = this.deps.getSettingsManager().getModelRouterSettings();\n\t\tconst configuredThinking = !routeDecision\n\t\t\t? undefined\n\t\t\t: routeDecision.reasonCode === \"executor_direct\"\n\t\t\t\t? routerThinkingSettings.executorThinking\n\t\t\t\t: routeDecision.tier === \"cheap\"\n\t\t\t\t\t? routerThinkingSettings.cheapThinking\n\t\t\t\t\t: routeDecision.tier === \"medium\"\n\t\t\t\t\t\t? routerThinkingSettings.mediumThinking\n\t\t\t\t\t\t: routeDecision.tier === \"expensive\"\n\t\t\t\t\t\t\t? routerThinkingSettings.expensiveThinking\n\t\t\t\t\t\t\t: undefined;\n\t\tconst routedThinkingLevel = clampThinkingLevel(\n\t\t\troutedModel,\n\t\t\tconfiguredThinking ?? previousThinkingLevel,\n\t\t) as ThinkingLevel;\n\t\tconst modelChanged = !modelsAreEqual(this.deps.getModel(), routedModel);\n\t\tconst thinkingChanged = routedThinkingLevel !== previousThinkingLevel;\n\t\tif (modelChanged || thinkingChanged) {\n\t\t\tagent.state.model = routedModel;\n\t\t\t// Per-tier thinking: a configured tier/executor thinking level overrides the inherited\n\t\t\t// session thinking for THIS routed turn only; unset falls back to exactly today's\n\t\t\t// inherit-and-clamp behavior. Executor routes carry tier \"cheap\" too, so reasonCode is\n\t\t\t// checked first — otherwise an executor turn would silently pick up cheapThinking instead.\n\t\t\t// The judge's own completion has a separate knob (judgeThinking) applied at its call site.\n\t\t\tagent.state.thinkingLevel = routedThinkingLevel;\n\t\t\t// Capability tool-filtering follows the ROUTED model for the turn. Without this a\n\t\t\t// cheap/local routed model inherits the session model's full tool surface — schemas it\n\t\t\t// pays for on every request and may not be able to drive at all.\n\t\t\tif (modelChanged) {\n\t\t\t\tconst routedProfile = deriveModelCapabilityProfile({\n\t\t\t\t\tcontextWindow: routedModel.contextWindow,\n\t\t\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t\t\t});\n\t\t\t\tif (routedProfile.class !== \"full\") {\n\t\t\t\t\tconst allowed = new Set(\n\t\t\t\t\t\tfilterToolNamesForCapability(\n\t\t\t\t\t\t\tpreviousTurnTools.map((tool) => tool.name),\n\t\t\t\t\t\t\troutedProfile,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tswappedTools = previousTurnTools.filter((tool) => allowed.has(tool.name));\n\t\t\t\t\tagent.state.tools = swappedTools;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// The routed prompt follows both the routed tool surface and its effective thinking mode.\n\t\t\t// This removes an Ultra policy during max/Luna routes, including same-model tier overrides.\n\t\t\t// Per-turn only; a live extension override is preserved rather than silently replaced.\n\t\t\tif (agent.state.systemPrompt === this.deps.getBaseSystemPrompt()) {\n\t\t\t\tswappedSystemPrompt = this.deps.buildSystemPromptForToolNames(agent.state.tools.map((tool) => tool.name));\n\t\t\t\tagent.state.systemPrompt = swappedSystemPrompt;\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tawait this.deps.runAgentPrompt(messages);\n\t\t\t// Speculative muscle-retry: an executor-routed turn is a bet that the\n\t\t\t// small model can run the toolkit command directly. If it ends WITHOUT a successful\n\t\t\t// run_toolkit_script execution, retry ONCE on the same executor with the brain's\n\t\t\t// refined instruction injected — the brain warms while the muscle tries, so the retry\n\t\t\t// pays only when the muscle actually missed.\n\t\t\tif (\n\t\t\t\trouteDecision?.reasonCode === \"executor_direct\" &&\n\t\t\t\t!this._isModelRouterRetry &&\n\t\t\t\t!this._executorTurnExecutedScript(originalHistoryLength)\n\t\t\t) {\n\t\t\t\tconst refined = await this._buildExecutorRefinedPrompt(messages);\n\t\t\t\tif (refined) {\n\t\t\t\t\tagent.state.messages.splice(originalHistoryLength);\n\t\t\t\t\tif (bufferRoutedTurn) this._modelRouterSessionBuffer = createModelRouterSessionBuffer();\n\t\t\t\t\tawait this.deps.runAgentPrompt([\n\t\t\t\t\t\t{ role: \"user\", content: [{ type: \"text\", text: refined }], timestamp: Date.now() },\n\t\t\t\t\t]);\n\t\t\t\t\tcompletedDecision = {\n\t\t\t\t\t\troute: {\n\t\t\t\t\t\t\t...routeDecision,\n\t\t\t\t\t\t\treasonCode: \"executor_speculative_retry\",\n\t\t\t\t\t\t\treasons: [\n\t\t\t\t\t\t\t\t...routeDecision.reasons,\n\t\t\t\t\t\t\t\t\"Executor missed on first try; retried with brain-refined instruction\",\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\troutedModel: formatModelRouterModel(routedModel),\n\t\t\t\t\t\toutcome: \"routed\",\n\t\t\t\t\t\tintent: \"research\",\n\t\t\t\t\t};\n\t\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t\t} else {\n\t\t\t\t\t// The muscle missed AND the reflex brain could not refine the request into a toolkit\n\t\t\t\t\t// instruction (no fit brain model, or no confident plan). There is deliberately NO\n\t\t\t\t\t// frontier fallback here, so surface the miss instead of letting it stand silently —\n\t\t\t\t\t// otherwise the routed turn just ends with an unrun command and no explanation.\n\t\t\t\t\tthis.deps.emit({\n\t\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Executor lane: the toolkit command did not run and the reflex brain could not refine it into an explicit instruction; leaving the turn as-is (no automatic escalation).\",\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (bufferRoutedTurn && this._modelRouterEscalationRequested) {\n\t\t\t\tagent.state.messages.splice(originalHistoryLength);\n\t\t\t\tretryModel = this._resolveModelRouterModelForIntent(\"modify\") ?? previousModel;\n\t\t\t\tcompletedDecision = {\n\t\t\t\t\troute: routeDecision!,\n\t\t\t\t\troutedModel: formatModelRouterModel(routedModel),\n\t\t\t\t\toutcome: \"escalated\",\n\t\t\t\t\tretryModel: formatModelRouterModel(retryModel),\n\t\t\t\t\tintent: routeDecision!.tier === \"cheap\" ? \"research\" : \"modify\",\n\t\t\t\t};\n\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t} else if (bufferRoutedTurn && this._modelRouterSessionBuffer) {\n\t\t\t\tflushModelRouterSessionBuffer(\n\t\t\t\t\tthis._modelRouterSessionBuffer,\n\t\t\t\t\t(message) => {\n\t\t\t\t\t\tthis.deps.getSessionManager().appendMessage(message);\n\t\t\t\t\t},\n\t\t\t\t\t(customType, content, display, details) => {\n\t\t\t\t\t\tthis.deps.getSessionManager().appendCustomMessageEntry(customType, content, display, details);\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrownError = error;\n\t\t\t// Mirror the escalation splice above (~:812): a buffered cheap-tier turn never flushes its\n\t\t\t// live messages to the session on a genuine throw, so agent.state.messages must be rolled\n\t\t\t// back to the pre-turn length here too — otherwise the never-persisted buffered messages\n\t\t\t// permanently diverge from the persisted session (same shape as the W1.3 ghost-turn bug,\n\t\t\t// but on the error path instead of the success/escalation paths).\n\t\t\tif (bufferRoutedTurn) {\n\t\t\t\tagent.state.messages.splice(originalHistoryLength);\n\t\t\t}\n\t\t\tif (completedDecision) {\n\t\t\t\tcompletedDecision = { ...completedDecision, outcome: \"failed\" };\n\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t}\n\t\t} finally {\n\t\t\t// Restore the pre-route model ONLY if the routed model is still in place: a command\n\t\t\t// handler may have legitimately changed the session model mid-turn (setModel or a\n\t\t\t// provider re-registration), and clobbering that would silently undo the change.\n\t\t\tif (modelsAreEqual(agent.state.model, routedModel)) {\n\t\t\t\tagent.state.model = previousModel;\n\t\t\t\tagent.state.thinkingLevel = previousThinkingLevel;\n\t\t\t\t// Symmetric restore: undo tools/systemPrompt only if each is STILL the exact\n\t\t\t\t// reference/string the swap above assigned (never assigned at all when the routed\n\t\t\t\t// profile was full-class — then there is nothing to restore either). An extension calling\n\t\t\t\t// setActiveToolsByName mid-turn reassigns both to its own values without touching the\n\t\t\t\t// model — the model guard above still passes, but that live change is legitimate and must\n\t\t\t\t// survive rather than being silently reverted to the stale pre-turn snapshot.\n\t\t\t\tif (swappedTools !== undefined && agent.state.tools === swappedTools) {\n\t\t\t\t\tagent.state.tools = previousTurnTools;\n\t\t\t\t}\n\t\t\t\tif (swappedSystemPrompt !== undefined && agent.state.systemPrompt === swappedSystemPrompt) {\n\t\t\t\t\tagent.state.systemPrompt = previousSystemPrompt;\n\t\t\t\t}\n\t\t\t\t// The registry may have changed mid-turn (command-time registerProvider): re-resolve\n\t\t\t\t// the restored model so a provider override is not dropped with the routed model.\n\t\t\t\tthis.deps.refreshCurrentModelFromRegistry();\n\t\t\t}\n\t\t\tthis._activeModelRouterIntent = previousActiveModelRouterIntent;\n\t\t\tthis._activeModelRouterRoute = previousActiveModelRouterRoute;\n\t\t\tthis._modelRouterSessionBuffer = previousModelRouterSessionBuffer;\n\t\t\tthis._modelRouterEscalationRequested = previousModelRouterEscalationRequested;\n\t\t}\n\n\t\tif (retryModel && !thrownError) {\n\t\t\tconst previousIsModelRouterRetry = this._isModelRouterRetry;\n\t\t\ttry {\n\t\t\t\tthis._isModelRouterRetry = true;\n\t\t\t\tconst retryDecision: RouteDecision = {\n\t\t\t\t\ttier: \"expensive\",\n\t\t\t\t\trisk: \"high-impact\",\n\t\t\t\t\tconfidence: 1.0,\n\t\t\t\t\treasonCode: \"cheap_mutating_tool_escalation\",\n\t\t\t\t\treasons: [\"Cheap research turn attempted a mutating tool and escalated\"],\n\t\t\t\t\tfallbackFrom: \"cheap\",\n\t\t\t\t\tmodel: formatModelRouterModel(retryModel),\n\t\t\t\t};\n\t\t\t\tawait this.runRoutedTurn(messages, retryModel, retryDecision, false);\n\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t} catch (error) {\n\t\t\t\tthrownError = error;\n\t\t\t\tif (completedDecision) {\n\t\t\t\t\tcompletedDecision = { ...completedDecision, outcome: \"failed\" };\n\t\t\t\t\tthis._lastModelRouterDecision = completedDecision;\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis._isModelRouterRetry = previousIsModelRouterRetry;\n\t\t\t}\n\t\t}\n\n\t\tif (persistDecision && completedDecision) {\n\t\t\tpersistModelRouterDecision(this.deps.getSessionManager(), completedDecision);\n\t\t\t// One route event per user-facing routed turn (the escalation retry runs with\n\t\t\t// persistDecision=false, so it does not double-emit). Codes/numbers only — no prompt text.\n\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.routeDecision,\n\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\tpayload: {\n\t\t\t\t\ttier: completedDecision.route.tier,\n\t\t\t\t\trisk: completedDecision.route.risk,\n\t\t\t\t\treasonCode: completedDecision.route.reasonCode,\n\t\t\t\t\tconfidence: completedDecision.route.confidence,\n\t\t\t\t\toutcome: completedDecision.outcome,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tif (thrownError) {\n\t\t\tthrow thrownError;\n\t\t}\n\t}\n}\n"]}
@@ -20,10 +20,17 @@
20
20
  * owns only the route decision/escalation/tier bookkeeping and delegates every agent turn back through
21
21
  * {@link ModelRouterControllerDeps.runAgentPrompt}, so the drive-loop logic is never duplicated. The
22
22
  * host keeps a one-line delegation at each call-in: the routing prep + routed-turn entry in
23
- * _promptUnserialized, the beforeToolCall escalation branch ({@link maybeEscalateToolCall}), the
24
- * message_end cheap-turn buffering ({@link captureSessionMessage}), the retry-event suppression
25
- * ({@link isRetryInFlight}), and the public getModelRouterStatus / autonomy-telemetry reads.
23
+ * _promptUnserialized, the beforeToolCall MUTATION escalation branch ({@link
24
+ * maybeEscalateToolCall}), the tool-name-agnostic VALIDATION-FAILURE escalation branch for cloud
25
+ * models ({@link requestValidationFailureEscalation} de-conflated from the mutation gate; see the
26
+ * capability-gate spine doctrine, which routes local/managed models to an evidence-gated
27
+ * native→phone auto-probe on AgentSession instead), the message_end cheap-turn buffering ({@link
28
+ * captureSessionMessage}), the retry-event suppression ({@link isRetryInFlight}), the public
29
+ * getModelRouterStatus / autonomy-telemetry reads, and the tier resolution's consultation of the
30
+ * persisted `/toolprobe` verdict for local/managed tier models ({@link
31
+ * ModelRouterControllerDeps.getToolProbeVerdict}).
26
32
  */
33
+ import { createHash } from "node:crypto";
27
34
  import { clampThinkingLevel, modelsAreEqual } from "@caupulican/pi-ai";
28
35
  import { AUTONOMY_TELEMETRY_EVENT_TYPES } from "./autonomy/telemetry-events.js";
29
36
  import { latestUserPromptText } from "./context-pipeline.js";
@@ -36,7 +43,7 @@ import { classifyModelRouterRoute } from "./model-router/intent-classifier.js";
36
43
  import { ROUTE_JUDGE_MAX_OUTPUT_TOKENS, runRouteJudge } from "./model-router/route-judge.js";
37
44
  import { bufferModelRouterSessionCustomMessage, bufferModelRouterSessionMessage, createModelRouterSessionBuffer, flushModelRouterSessionBuffer, } from "./model-router/session-buffer.js";
38
45
  import { formatModelRouterStatus, getRecentModelRouterDecisions, MODEL_ROUTER_DECISION_CUSTOM_TYPE, } from "./model-router/status.js";
39
- import { shouldEscalateModelRouterTool } from "./model-router/tool-escalation.js";
46
+ import { isLocalOrManagedRouterModel, shouldEscalateModelRouterTool } from "./model-router/tool-escalation.js";
40
47
  import { FitnessStore } from "./models/fitness-store.js";
41
48
  import { buildReflexUserPrompt, parseReflexPlan, REFLEX_INTERPRETER_SYSTEM_PROMPT, } from "./toolkit/reflex-interpreter.js";
42
49
  /** Canonical `provider/id` label for a routed/resolved model, as it appears in decisions and status. */
@@ -65,6 +72,16 @@ function withJudgeUnavailableFallback(decision, reason) {
65
72
  function persistModelRouterDecision(sessionManager, decision) {
66
73
  sessionManager.appendCustomEntry(MODEL_ROUTER_DECISION_CUSTOM_TYPE, decision);
67
74
  }
75
+ /**
76
+ * Deterministic `addSpawnedUsage` reportId: `kind` + session id + a content hash of `identity`
77
+ * (the text driving the call — never `Date.now`/random). Same identity on a retry of the same
78
+ * logical work unit yields the same id, so the ledger's `seenSubagentReportIds` dedupe catches a
79
+ * duplicate report instead of double-counting spend.
80
+ */
81
+ function deriveSpawnedUsageReportId(kind, sessionId, identity) {
82
+ const digest = createHash("sha256").update(identity).digest("hex").slice(0, 16);
83
+ return `${kind}:${sessionId}:${digest}`;
84
+ }
68
85
  /**
69
86
  * Owns the model-router turn routing extracted from {@link AgentSession}. See the module header for the
70
87
  * drive-path boundary that keeps the agent.prompt()/continue() loop host-side.
@@ -113,6 +130,26 @@ export class ModelRouterController {
113
130
  }
114
131
  return undefined;
115
132
  }
133
+ /**
134
+ * Tool-name-agnostic validation-failure escalation gate, called from
135
+ * AgentSession's onToolValidationEscalation handler for a CLOUD model only — see the
136
+ * capability-gate-spine doctrine (local/managed models never reach this method; they trigger
137
+ * the evidence-gated native→phone auto-probe instead). Unlike {@link maybeEscalateToolCall} (the
138
+ * beforeToolCall MUTATION gate, still governed by `shouldEscalateModelRouterTool`/
139
+ * READ_ONLY_TOOL_NAMES — a legitimate, unrelated mutation-blast-radius policy), "the model
140
+ * repeatedly cannot construct valid arguments for this tool" is evidence about the MODEL's
141
+ * capability, not about the tool's mutation status, so a read-only tool's repeated validation
142
+ * failure now escalates a cheap routed turn exactly like a mutating tool's would — takes no
143
+ * tool-name/args input at all (unlike maybeEscalateToolCall), because every repeated validation
144
+ * failure escalates regardless of which tool or model triggered it. No-op outside an active
145
+ * cheap-tier routed turn, same scoping as maybeEscalateToolCall.
146
+ */
147
+ requestValidationFailureEscalation() {
148
+ if (this._activeModelRouterRoute?.tier !== "cheap")
149
+ return;
150
+ this._modelRouterEscalationRequested = true;
151
+ this.deps.getAgent().abort();
152
+ }
116
153
  /**
117
154
  * message_end hook: while a cheap routed turn is buffering, capture its messages into the session
118
155
  * buffer instead of persisting them (they are flushed on success or discarded on escalation).
@@ -268,9 +305,14 @@ export class ModelRouterController {
268
305
  thinkingLevel: "off",
269
306
  maxTokens: 256,
270
307
  cacheRetention: "short",
308
+ // Stable per-lane synthetic affinity key for repeat executor-brain warmups.
309
+ laneKind: "executor",
271
310
  });
272
311
  if (completion.usage.cost.total > 0 || completion.usage.totalTokens > 0) {
273
- this.deps.addSpawnedUsage(completion.usage, { label: "executor-brain-warmup" });
312
+ // `reportId` keyed on the request text driving THIS refinement — stable across a
313
+ // retry of the same routed turn, distinct across genuinely different requests.
314
+ const reportId = deriveSpawnedUsageReportId("executor-brain", this.deps.getSessionManager().getSessionId(), request);
315
+ this.deps.addSpawnedUsage(completion.usage, { label: "executor-brain-warmup", reportId });
274
316
  }
275
317
  const plan = parseReflexPlan(completion.text);
276
318
  if (!plan || plan.script === "none")
@@ -288,7 +330,7 @@ export class ModelRouterController {
288
330
  this._lastModelRouterSkipReason = "disabled";
289
331
  return undefined;
290
332
  }
291
- // G16 executor lane: a Level-0 DIRECT toolkit hit on a command-shaped prompt routes the
333
+ // Executor lane: a Level-0 DIRECT toolkit hit on a command-shaped prompt routes the
292
334
  // whole turn to the configured local executor (tool-call-fitness-gated) instead of
293
335
  // spending the frontier model on a one-tool reflex. Ambiguity never routes here — it
294
336
  // stays with the big model and the reflex brain. Deterministic, so the judge is skipped.
@@ -334,6 +376,22 @@ export class ModelRouterController {
334
376
  this._lastModelRouterSkipReason = `${decision.tier} model exhausted: quota`;
335
377
  return undefined;
336
378
  }
379
+ // For a LOCAL/MANAGED tier model (never cloud — isLocalOrManagedRouterModel), honor a
380
+ // persisted "no working tool-call path" probe verdict. This is an ALWAYS-ON doctrine gate,
381
+ // deliberately not behind the opt-in `fitnessGate` setting below (cloud fitness gating stays
382
+ // opt-in; this local/managed check is unconditional, matching the auto-probe that writes
383
+ // the verdict). "native"/"text-protocol"/unprobed all fall through unchanged: native wins
384
+ // when it works, the phone lane engages downstream via _textProtocolFlag, and an unprobed
385
+ // model routes native-first (the evidence loop, not a speculative pre-block).
386
+ if (isLocalOrManagedRouterModel(resolved.model) && this.deps.getToolProbeVerdict(resolved.model) === "none") {
387
+ if (decision.tier === "medium") {
388
+ const fallback = this._resolveExpensiveFallbackRoute(decision, "medium_no_tool_path_fallback_expensive", "Medium model has no working tool-call path (native and text-protocol probe both failed); falling back to expensive model");
389
+ if (fallback)
390
+ return fallback;
391
+ }
392
+ this._lastModelRouterSkipReason = `${decision.tier} model has no working tool-call path (native and text-protocol probe both failed)`;
393
+ return undefined;
394
+ }
337
395
  if (settings.fitnessGate) {
338
396
  const verdict = this._evaluateModelFitness(this._routerSurfaceForTier(decision.tier), resolved.model);
339
397
  if (!verdict.fit) {
@@ -373,7 +431,14 @@ export class ModelRouterController {
373
431
  return undefined;
374
432
  if (!this.deps.getModelRegistry().hasConfiguredAuth(resolved.model))
375
433
  return undefined;
376
- return this.deps.isModelExhausted(resolved.model) ? undefined : resolved.model;
434
+ if (this.deps.isModelExhausted(resolved.model))
435
+ return undefined;
436
+ // (Same doctrine as _resolveModelRouterTurnRoute above): never resolve a local/managed
437
+ // model the probe has already graded as having no working tool-call path.
438
+ if (isLocalOrManagedRouterModel(resolved.model) && this.deps.getToolProbeVerdict(resolved.model) === "none") {
439
+ return undefined;
440
+ }
441
+ return resolved.model;
377
442
  }
378
443
  /**
379
444
  * Router resolution with the routing judge (auto-on with the router): the regex classifier's
@@ -432,13 +497,16 @@ export class ModelRouterController {
432
497
  systemPrompt,
433
498
  messages: [{ role: "user", content: [{ type: "text", text: userPrompt }], timestamp: Date.now() }],
434
499
  model: judgeModel,
435
- // Per-tier thinking (R1): judgeThinking overrides the judge's own completion; unset
500
+ // Per-tier thinking: judgeThinking overrides the judge's own completion; unset
436
501
  // keeps today's "off" (the judge is a cheap classification call by default).
437
502
  thinkingLevel: settings.judgeThinking ?? "off",
438
503
  maxTokens: ROUTE_JUDGE_MAX_OUTPUT_TOKENS,
439
504
  signal,
440
505
  // The judge system prompt is static — the provider can cache the prefix.
441
506
  cacheRetention: "short",
507
+ // Stable per-lane synthetic affinity key so repeat judge calls hit the same
508
+ // cache-warm backend.
509
+ laneKind: "route-judge",
442
510
  });
443
511
  spentUsage = completion.usage;
444
512
  return {
@@ -449,7 +517,10 @@ export class ModelRouterController {
449
517
  },
450
518
  });
451
519
  if (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {
452
- this.deps.addSpawnedUsage(spentUsage, { label: "router-judge" });
520
+ // `reportId` keyed on the routed prompt text — stable across a retry of the same
521
+ // judged turn, distinct across genuinely different prompts.
522
+ const reportId = deriveSpawnedUsageReportId("route-judge", this.deps.getSessionManager().getSessionId(), prompt);
523
+ this.deps.addSpawnedUsage(spentUsage, { label: "router-judge", reportId });
453
524
  }
454
525
  if (!judged.verdict || judged.decision.tier === baseline.decision.tier) {
455
526
  // Same tier (or judge fell back): keep the baseline model, carry the annotated decision.
@@ -506,7 +577,7 @@ export class ModelRouterController {
506
577
  const previousThinkingLevel = agent.state.thinkingLevel;
507
578
  const previousTurnTools = agent.state.tools;
508
579
  const previousSystemPrompt = agent.state.systemPrompt;
509
- // G4 swap bookkeeping (Bug G): the exact references the swap below assigns, so the finally can
580
+ // Swap bookkeeping: the exact references the swap below assigns, so the finally can
510
581
  // restore ONLY what IT put there — never assigned when no swap happens (e.g. a full-class
511
582
  // routed profile).
512
583
  let swappedTools;
@@ -557,13 +628,13 @@ export class ModelRouterController {
557
628
  const thinkingChanged = routedThinkingLevel !== previousThinkingLevel;
558
629
  if (modelChanged || thinkingChanged) {
559
630
  agent.state.model = routedModel;
560
- // Per-tier thinking (R1): a configured tier/executor thinking level overrides the inherited
631
+ // Per-tier thinking: a configured tier/executor thinking level overrides the inherited
561
632
  // session thinking for THIS routed turn only; unset falls back to exactly today's
562
633
  // inherit-and-clamp behavior. Executor routes carry tier "cheap" too, so reasonCode is
563
634
  // checked first — otherwise an executor turn would silently pick up cheapThinking instead.
564
635
  // The judge's own completion has a separate knob (judgeThinking) applied at its call site.
565
636
  agent.state.thinkingLevel = routedThinkingLevel;
566
- // G4: capability tool-filtering follows the ROUTED model for the turn. Without this a
637
+ // Capability tool-filtering follows the ROUTED model for the turn. Without this a
567
638
  // cheap/local routed model inherits the session model's full tool surface — schemas it
568
639
  // pays for on every request and may not be able to drive at all.
569
640
  if (modelChanged) {
@@ -587,7 +658,7 @@ export class ModelRouterController {
587
658
  }
588
659
  try {
589
660
  await this.deps.runAgentPrompt(messages);
590
- // Speculative muscle-retry (G16 refinement): an executor-routed turn is a bet that the
661
+ // Speculative muscle-retry: an executor-routed turn is a bet that the
591
662
  // small model can run the toolkit command directly. If it ends WITHOUT a successful
592
663
  // run_toolkit_script execution, retry ONCE on the same executor with the brain's
593
664
  // refined instruction injected — the brain warms while the muscle tries, so the retry
@@ -651,6 +722,14 @@ export class ModelRouterController {
651
722
  }
652
723
  catch (error) {
653
724
  thrownError = error;
725
+ // Mirror the escalation splice above (~:812): a buffered cheap-tier turn never flushes its
726
+ // live messages to the session on a genuine throw, so agent.state.messages must be rolled
727
+ // back to the pre-turn length here too — otherwise the never-persisted buffered messages
728
+ // permanently diverge from the persisted session (same shape as the W1.3 ghost-turn bug,
729
+ // but on the error path instead of the success/escalation paths).
730
+ if (bufferRoutedTurn) {
731
+ agent.state.messages.splice(originalHistoryLength);
732
+ }
654
733
  if (completedDecision) {
655
734
  completedDecision = { ...completedDecision, outcome: "failed" };
656
735
  this._lastModelRouterDecision = completedDecision;
@@ -663,8 +742,8 @@ export class ModelRouterController {
663
742
  if (modelsAreEqual(agent.state.model, routedModel)) {
664
743
  agent.state.model = previousModel;
665
744
  agent.state.thinkingLevel = previousThinkingLevel;
666
- // Symmetric restore (Bug G): undo tools/systemPrompt only if each is STILL the exact
667
- // reference/string the G4 swap above assigned (never assigned at all when the routed
745
+ // Symmetric restore: undo tools/systemPrompt only if each is STILL the exact
746
+ // reference/string the swap above assigned (never assigned at all when the routed
668
747
  // profile was full-class — then there is nothing to restore either). An extension calling
669
748
  // setActiveToolsByName mid-turn reassigns both to its own values without touching the
670
749
  // model — the model guard above still passes, but that live change is legitimate and must
@@ -713,7 +792,7 @@ export class ModelRouterController {
713
792
  }
714
793
  if (persistDecision && completedDecision) {
715
794
  persistModelRouterDecision(this.deps.getSessionManager(), completedDecision);
716
- // G3: one route event per user-facing routed turn (the escalation retry runs with
795
+ // One route event per user-facing routed turn (the escalation retry runs with
717
796
  // persistDecision=false, so it does not double-emit). Codes/numbers only — no prompt text.
718
797
  this.deps.emitAutonomyTelemetry({
719
798
  type: AUTONOMY_TELEMETRY_EVENT_TYPES.routeDecision,