@prestyj/cli 5.32.2 → 5.34.0

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 (620) hide show
  1. package/README.md +16 -16
  2. package/assets/motion/skills/motion/SKILL.md +1 -1
  3. package/assets/skills/bulletproof/SKILL.md +72 -131
  4. package/assets/skills/bulletproof/references/agent-surface.md +22 -1
  5. package/assets/skills/bulletproof/references/audit-protocol.md +23 -6
  6. package/assets/skills/bulletproof/references/platform-playbooks.md +12 -0
  7. package/assets/skills/bulletproof/references/provenance.md +19 -2
  8. package/assets/skills/bulletproof/references/secure-defaults.md +13 -1
  9. package/assets/skills/bulletproof/references/supply-chain.md +8 -5
  10. package/assets/skills/bulletproof/references/threat-landscape.md +46 -57
  11. package/assets/skills/compliance-guard/SKILL.md +59 -212
  12. package/assets/skills/compliance-guard/references/artifacts.md +14 -1
  13. package/assets/skills/compliance-guard/references/eu-uk.md +17 -7
  14. package/assets/skills/compliance-guard/references/exposure-triage.md +16 -0
  15. package/assets/skills/compliance-guard/references/full-review.md +155 -0
  16. package/assets/skills/compliance-guard/references/lawsuit-vectors.md +14 -2
  17. package/assets/skills/compliance-guard/references/provenance.md +33 -2
  18. package/assets/skills/compliance-guard/references/sector-gates.md +15 -1
  19. package/assets/skills/compliance-guard/references/security-baseline.md +21 -34
  20. package/assets/skills/compliance-guard/references/trigger-map.md +15 -1
  21. package/assets/skills/compliance-guard/references/us.md +32 -8
  22. package/assets/skills/durable/SKILL.md +22 -29
  23. package/assets/skills/durable/references/agent-db-safety.md +2 -2
  24. package/assets/skills/durable/references/backups-and-runtime.md +6 -6
  25. package/assets/skills/durable/references/migrations-and-schema.md +5 -4
  26. package/assets/skills/lean/SKILL.md +36 -50
  27. package/assets/skills/lean/references/playbooks.md +9 -7
  28. package/dist/app-sidecar/app-settings.d.ts +5 -0
  29. package/dist/app-sidecar/app-settings.js +16 -0
  30. package/dist/app-sidecar/app-settings.js.map +1 -1
  31. package/dist/app-sidecar/auth-routes.js +45 -2
  32. package/dist/app-sidecar/auth-routes.js.map +1 -1
  33. package/dist/app-sidecar/autopilot-runner.d.ts +7 -0
  34. package/dist/app-sidecar/autopilot-runner.js +79 -19
  35. package/dist/app-sidecar/autopilot-runner.js.map +1 -1
  36. package/dist/app-sidecar/desktop-guidance.d.ts +1 -0
  37. package/dist/app-sidecar/desktop-guidance.js +27 -0
  38. package/dist/app-sidecar/desktop-guidance.js.map +1 -0
  39. package/dist/app-sidecar/history-routes.d.ts +6 -0
  40. package/dist/app-sidecar/history-routes.js +57 -2
  41. package/dist/app-sidecar/history-routes.js.map +1 -1
  42. package/dist/app-sidecar/history.d.ts +17 -0
  43. package/dist/app-sidecar/history.js.map +1 -1
  44. package/dist/app-sidecar/http.d.ts +1 -1
  45. package/dist/app-sidecar/http.js +2 -2
  46. package/dist/app-sidecar/http.js.map +1 -1
  47. package/dist/app-sidecar/integration-routes.js +4 -0
  48. package/dist/app-sidecar/integration-routes.js.map +1 -1
  49. package/dist/app-sidecar/live-preview/dev-url.d.ts +32 -0
  50. package/dist/app-sidecar/live-preview/dev-url.js +97 -0
  51. package/dist/app-sidecar/live-preview/dev-url.js.map +1 -0
  52. package/dist/app-sidecar/live-preview/frame-server.d.ts +31 -0
  53. package/dist/app-sidecar/live-preview/frame-server.js +193 -0
  54. package/dist/app-sidecar/live-preview/frame-server.js.map +1 -0
  55. package/dist/app-sidecar/live-preview/manager.d.ts +44 -0
  56. package/dist/app-sidecar/live-preview/manager.js +215 -0
  57. package/dist/app-sidecar/live-preview/manager.js.map +1 -0
  58. package/dist/app-sidecar/live-preview/proxy.d.ts +30 -0
  59. package/dist/app-sidecar/live-preview/proxy.js +235 -0
  60. package/dist/app-sidecar/live-preview/proxy.js.map +1 -0
  61. package/dist/app-sidecar/live-preview/routes.d.ts +4 -0
  62. package/dist/app-sidecar/live-preview/routes.js +52 -0
  63. package/dist/app-sidecar/live-preview/routes.js.map +1 -0
  64. package/dist/app-sidecar/live-preview/servers.d.ts +36 -0
  65. package/dist/app-sidecar/live-preview/servers.js +228 -0
  66. package/dist/app-sidecar/live-preview/servers.js.map +1 -0
  67. package/dist/app-sidecar/mcp-routes.js +9 -0
  68. package/dist/app-sidecar/mcp-routes.js.map +1 -1
  69. package/dist/app-sidecar/mcp-shell-command.d.ts +36 -0
  70. package/dist/app-sidecar/mcp-shell-command.js +302 -0
  71. package/dist/app-sidecar/mcp-shell-command.js.map +1 -0
  72. package/dist/app-sidecar/mcp-sync.d.ts +18 -0
  73. package/dist/app-sidecar/mcp-sync.js +38 -0
  74. package/dist/app-sidecar/mcp-sync.js.map +1 -0
  75. package/dist/app-sidecar/prompt-routes.js +58 -30
  76. package/dist/app-sidecar/prompt-routes.js.map +1 -1
  77. package/dist/app-sidecar/route-context.d.ts +13 -2
  78. package/dist/app-sidecar/run-control-routes.js +17 -3
  79. package/dist/app-sidecar/run-control-routes.js.map +1 -1
  80. package/dist/app-sidecar/session-routes.js +8 -0
  81. package/dist/app-sidecar/session-routes.js.map +1 -1
  82. package/dist/app-sidecar/shell-routes.d.ts +12 -0
  83. package/dist/app-sidecar/shell-routes.js +140 -0
  84. package/dist/app-sidecar/shell-routes.js.map +1 -0
  85. package/dist/app-sidecar/shell-runs.d.ts +103 -0
  86. package/dist/app-sidecar/shell-runs.js +268 -0
  87. package/dist/app-sidecar/shell-runs.js.map +1 -0
  88. package/dist/app-sidecar/shell-suggestions.d.ts +33 -0
  89. package/dist/app-sidecar/shell-suggestions.js +152 -0
  90. package/dist/app-sidecar/shell-suggestions.js.map +1 -0
  91. package/dist/app-sidecar/task-routes.js +1 -1
  92. package/dist/app-sidecar/task-routes.js.map +1 -1
  93. package/dist/app-sidecar/usage.js +26 -2
  94. package/dist/app-sidecar/usage.js.map +1 -1
  95. package/dist/app-sidecar/workspace-routes.js +35 -37
  96. package/dist/app-sidecar/workspace-routes.js.map +1 -1
  97. package/dist/app-sidecar-sessions.js +13 -3
  98. package/dist/app-sidecar-sessions.js.map +1 -1
  99. package/dist/app-sidecar.js +365 -96
  100. package/dist/app-sidecar.js.map +1 -1
  101. package/dist/chat-agents/index.d.ts +1 -1
  102. package/dist/chat-agents/index.js +1 -1
  103. package/dist/chat-agents/index.js.map +1 -1
  104. package/dist/chat-agents/shared.d.ts +4 -0
  105. package/dist/chat-agents/shared.js +8 -1
  106. package/dist/chat-agents/shared.js.map +1 -1
  107. package/dist/cli/mcp.js +19 -5
  108. package/dist/cli/mcp.js.map +1 -1
  109. package/dist/cli/shared.js +4 -0
  110. package/dist/cli/shared.js.map +1 -1
  111. package/dist/cli.js +41 -9
  112. package/dist/cli.js.map +1 -1
  113. package/dist/config.d.ts +22 -2
  114. package/dist/config.js +42 -97
  115. package/dist/config.js.map +1 -1
  116. package/dist/core/agent-session/mcp-tools.d.ts +17 -0
  117. package/dist/core/agent-session/mcp-tools.js +31 -0
  118. package/dist/core/agent-session/mcp-tools.js.map +1 -1
  119. package/dist/core/agent-session/verification-tracker.js +2 -10
  120. package/dist/core/agent-session/verification-tracker.js.map +1 -1
  121. package/dist/core/agent-session.d.ts +129 -11
  122. package/dist/core/agent-session.js +925 -171
  123. package/dist/core/agent-session.js.map +1 -1
  124. package/dist/core/agents.d.ts +0 -10
  125. package/dist/core/agents.js +5 -1
  126. package/dist/core/agents.js.map +1 -1
  127. package/dist/core/ask-user.d.ts +8 -0
  128. package/dist/core/ask-user.js +28 -6
  129. package/dist/core/ask-user.js.map +1 -1
  130. package/dist/core/autopilot-gate.js +2 -3
  131. package/dist/core/autopilot-gate.js.map +1 -1
  132. package/dist/core/bundled-agents.js +9 -29
  133. package/dist/core/bundled-agents.js.map +1 -1
  134. package/dist/core/cache-diagnostics.d.ts +4 -0
  135. package/dist/core/cache-diagnostics.js +4 -1
  136. package/dist/core/cache-diagnostics.js.map +1 -1
  137. package/dist/core/cache-expiry.d.ts +2 -0
  138. package/dist/core/cache-expiry.js +6 -0
  139. package/dist/core/cache-expiry.js.map +1 -1
  140. package/dist/core/checklist-items.d.ts +2 -10
  141. package/dist/core/checklist-items.js +14 -10
  142. package/dist/core/checklist-items.js.map +1 -1
  143. package/dist/core/checklist-prompt.d.ts +1 -1
  144. package/dist/core/checklist-prompt.js +1 -1
  145. package/dist/core/checkpoint-store.d.ts +17 -0
  146. package/dist/core/checkpoint-store.js +72 -0
  147. package/dist/core/checkpoint-store.js.map +1 -1
  148. package/dist/core/claude-code/complete.d.ts +35 -0
  149. package/dist/core/claude-code/complete.js +115 -0
  150. package/dist/core/claude-code/complete.js.map +1 -0
  151. package/dist/core/claude-code/events.d.ts +65 -0
  152. package/dist/core/claude-code/events.js +434 -0
  153. package/dist/core/claude-code/events.js.map +1 -0
  154. package/dist/core/claude-code/live-session.d.ts +92 -0
  155. package/dist/core/claude-code/live-session.js +519 -0
  156. package/dist/core/claude-code/live-session.js.map +1 -0
  157. package/dist/core/claude-code/loop.d.ts +9 -0
  158. package/dist/core/claude-code/loop.js +15 -0
  159. package/dist/core/claude-code/loop.js.map +1 -0
  160. package/dist/core/claude-code/session-sync.d.ts +28 -0
  161. package/dist/core/claude-code/session-sync.js +53 -0
  162. package/dist/core/claude-code/session-sync.js.map +1 -0
  163. package/dist/core/claude-code/tool-bridge.d.ts +49 -0
  164. package/dist/core/claude-code/tool-bridge.js +352 -0
  165. package/dist/core/claude-code/tool-bridge.js.map +1 -0
  166. package/dist/core/claude-code/transcripts.d.ts +29 -0
  167. package/dist/core/claude-code/transcripts.js +117 -0
  168. package/dist/core/claude-code/transcripts.js.map +1 -0
  169. package/dist/core/claude-code-version.d.ts +1 -1
  170. package/dist/core/claude-code-version.js +1 -1
  171. package/dist/core/claude-code-version.js.map +1 -1
  172. package/dist/core/code-retrieval.d.ts +1 -1
  173. package/dist/core/code-retrieval.js +2 -2
  174. package/dist/core/code-retrieval.js.map +1 -1
  175. package/dist/core/codex-request-shape.js +1 -1
  176. package/dist/core/compaction/compactor.d.ts +27 -1
  177. package/dist/core/compaction/compactor.js +143 -9
  178. package/dist/core/compaction/compactor.js.map +1 -1
  179. package/dist/core/compaction/plan-step-policy.d.ts +1 -1
  180. package/dist/core/compaction/plan-step-policy.js +1 -1
  181. package/dist/core/compaction/policy.d.ts +18 -0
  182. package/dist/core/compaction/policy.js +27 -7
  183. package/dist/core/compaction/policy.js.map +1 -1
  184. package/dist/core/compaction/tool-result-pruner.d.ts +20 -0
  185. package/dist/core/compaction/tool-result-pruner.js +25 -0
  186. package/dist/core/compaction/tool-result-pruner.js.map +1 -1
  187. package/dist/core/env-delta.d.ts +3 -3
  188. package/dist/core/env-delta.js +4 -5
  189. package/dist/core/env-delta.js.map +1 -1
  190. package/dist/core/extensions/plugin-bundles.d.ts +0 -9
  191. package/dist/core/extensions/plugin-bundles.js +0 -185
  192. package/dist/core/extensions/plugin-bundles.js.map +1 -1
  193. package/dist/core/goals-store.d.ts +9 -2
  194. package/dist/core/goals-store.js +111 -55
  195. package/dist/core/goals-store.js.map +1 -1
  196. package/dist/core/internal-diagnostics.d.ts +17 -0
  197. package/dist/core/internal-diagnostics.js +45 -0
  198. package/dist/core/internal-diagnostics.js.map +1 -1
  199. package/dist/core/language-detector.d.ts +2 -3
  200. package/dist/core/language-detector.js.map +1 -1
  201. package/dist/core/live-preview.d.ts +24 -0
  202. package/dist/core/live-preview.js +76 -0
  203. package/dist/core/live-preview.js.map +1 -0
  204. package/dist/core/local-endpoint-store.d.ts +4 -0
  205. package/dist/core/local-endpoint-store.js +31 -15
  206. package/dist/core/local-endpoint-store.js.map +1 -1
  207. package/dist/core/logger.d.ts +5 -0
  208. package/dist/core/logger.js +10 -2
  209. package/dist/core/logger.js.map +1 -1
  210. package/dist/core/lsp/edit-telemetry.js +3 -1
  211. package/dist/core/lsp/edit-telemetry.js.map +1 -1
  212. package/dist/core/lsp/manager.d.ts +15 -0
  213. package/dist/core/lsp/manager.js +31 -0
  214. package/dist/core/lsp/manager.js.map +1 -1
  215. package/dist/core/mcp/client.d.ts +9 -0
  216. package/dist/core/mcp/client.js +58 -5
  217. package/dist/core/mcp/client.js.map +1 -1
  218. package/dist/core/mcp/deferred-catalog.d.ts +1 -1
  219. package/dist/core/mcp/deferred-catalog.js +1 -1
  220. package/dist/core/mcp/oauth-provider.d.ts +7 -1
  221. package/dist/core/mcp/oauth-provider.js +11 -4
  222. package/dist/core/mcp/oauth-provider.js.map +1 -1
  223. package/dist/core/mcp/oauth-store.d.ts +6 -0
  224. package/dist/core/mcp/oauth-store.js +14 -0
  225. package/dist/core/mcp/oauth-store.js.map +1 -1
  226. package/dist/core/mcp/parse-add-command.d.ts +29 -3
  227. package/dist/core/mcp/parse-add-command.js +196 -26
  228. package/dist/core/mcp/parse-add-command.js.map +1 -1
  229. package/dist/core/mcp/store.d.ts +16 -0
  230. package/dist/core/mcp/store.js +28 -0
  231. package/dist/core/mcp/store.js.map +1 -1
  232. package/dist/core/mcp/types.d.ts +9 -0
  233. package/dist/core/nolan-ask-answer.d.ts +24 -0
  234. package/dist/core/nolan-ask-answer.js +96 -0
  235. package/dist/core/nolan-ask-answer.js.map +1 -0
  236. package/dist/core/nolan-context.d.ts +20 -0
  237. package/dist/core/nolan-context.js +55 -0
  238. package/dist/core/nolan-context.js.map +1 -1
  239. package/dist/core/nolan-prompt.js +6 -0
  240. package/dist/core/nolan-prompt.js.map +1 -1
  241. package/dist/core/opencode-catalog-store.d.ts +20 -0
  242. package/dist/core/opencode-catalog-store.js +82 -0
  243. package/dist/core/opencode-catalog-store.js.map +1 -0
  244. package/dist/core/openrouter-catalog-store.d.ts +24 -0
  245. package/dist/core/openrouter-catalog-store.js +140 -0
  246. package/dist/core/openrouter-catalog-store.js.map +1 -0
  247. package/dist/core/package-cooldown.d.ts +0 -2
  248. package/dist/core/package-cooldown.js +0 -4
  249. package/dist/core/package-cooldown.js.map +1 -1
  250. package/dist/core/plan-delta.d.ts +23 -0
  251. package/dist/core/plan-delta.js +36 -0
  252. package/dist/core/plan-delta.js.map +1 -0
  253. package/dist/core/process-gate.d.ts +17 -0
  254. package/dist/core/process-gate.js +24 -0
  255. package/dist/core/process-gate.js.map +1 -1
  256. package/dist/core/process-manager.d.ts +1 -1
  257. package/dist/core/process-manager.js +1 -1
  258. package/dist/core/project-discovery.js +2 -2
  259. package/dist/core/project-discovery.js.map +1 -1
  260. package/dist/core/project-files.js +1 -1
  261. package/dist/core/project-files.js.map +1 -1
  262. package/dist/core/prompt-commands.js +106 -107
  263. package/dist/core/prompt-commands.js.map +1 -1
  264. package/dist/core/radio-players.d.ts +28 -0
  265. package/dist/core/radio-players.js +133 -0
  266. package/dist/core/radio-players.js.map +1 -0
  267. package/dist/core/radio.js +20 -3
  268. package/dist/core/radio.js.map +1 -1
  269. package/dist/core/runtime-mode.d.ts +9 -8
  270. package/dist/core/runtime-mode.js +26 -0
  271. package/dist/core/runtime-mode.js.map +1 -1
  272. package/dist/core/session-history.d.ts +7 -0
  273. package/dist/core/session-history.js +48 -4
  274. package/dist/core/session-history.js.map +1 -1
  275. package/dist/core/session-manager.d.ts +10 -1
  276. package/dist/core/session-manager.js +48 -14
  277. package/dist/core/session-manager.js.map +1 -1
  278. package/dist/core/session-preview.js +2 -2
  279. package/dist/core/session-preview.js.map +1 -1
  280. package/dist/core/session-storage.d.ts +0 -2
  281. package/dist/core/session-storage.js +0 -2
  282. package/dist/core/session-storage.js.map +1 -1
  283. package/dist/core/session-summary-index.d.ts +18 -4
  284. package/dist/core/session-summary-index.js +28 -8
  285. package/dist/core/session-summary-index.js.map +1 -1
  286. package/dist/core/settings-manager.d.ts +9 -0
  287. package/dist/core/settings-manager.js +56 -8
  288. package/dist/core/settings-manager.js.map +1 -1
  289. package/dist/core/shell-path.d.ts +2 -0
  290. package/dist/core/shell-path.js +10 -1
  291. package/dist/core/shell-path.js.map +1 -1
  292. package/dist/core/shell.d.ts +4 -0
  293. package/dist/core/shell.js +15 -1
  294. package/dist/core/shell.js.map +1 -1
  295. package/dist/core/skills.d.ts +10 -0
  296. package/dist/core/skills.js +20 -5
  297. package/dist/core/skills.js.map +1 -1
  298. package/dist/core/steering.d.ts +4 -0
  299. package/dist/core/steering.js +8 -1
  300. package/dist/core/steering.js.map +1 -1
  301. package/dist/core/stream-diag-level.d.ts +3 -0
  302. package/dist/core/stream-diag-level.js +24 -0
  303. package/dist/core/stream-diag-level.js.map +1 -0
  304. package/dist/core/subagent-manager.d.ts +11 -0
  305. package/dist/core/subagent-manager.js +16 -4
  306. package/dist/core/subagent-manager.js.map +1 -1
  307. package/dist/core/subagent-policy.d.ts +6 -0
  308. package/dist/core/subagent-policy.js +22 -3
  309. package/dist/core/subagent-policy.js.map +1 -1
  310. package/dist/core/subagent-receipt.d.ts +3 -3
  311. package/dist/core/subagent-receipt.js +6 -9
  312. package/dist/core/subagent-receipt.js.map +1 -1
  313. package/dist/core/task-store.d.ts +0 -1
  314. package/dist/core/task-store.js +0 -3
  315. package/dist/core/task-store.js.map +1 -1
  316. package/dist/core/trophies/catalog-more.js +16 -36
  317. package/dist/core/trophies/catalog-more.js.map +1 -1
  318. package/dist/core/trophies/catalog.js +3 -3
  319. package/dist/core/trophies/catalog.js.map +1 -1
  320. package/dist/core/trophies/engine.js +0 -4
  321. package/dist/core/trophies/engine.js.map +1 -1
  322. package/dist/core/trophies/types.d.ts +1 -1
  323. package/dist/core/trophies/types.js +0 -2
  324. package/dist/core/trophies/types.js.map +1 -1
  325. package/dist/core/user-shell-context.d.ts +8 -0
  326. package/dist/core/user-shell-context.js +12 -0
  327. package/dist/core/user-shell-context.js.map +1 -0
  328. package/dist/core/verify-commands.d.ts +1 -1
  329. package/dist/goals-agent/goal-team.js +3 -4
  330. package/dist/goals-agent/goal-team.js.map +1 -1
  331. package/dist/goals-agent/goals-agent.d.ts +1 -1
  332. package/dist/goals-agent/goals-agent.js +4 -3
  333. package/dist/goals-agent/goals-agent.js.map +1 -1
  334. package/dist/modes/acp-mode.d.ts +2 -2
  335. package/dist/modes/acp-mode.js +4 -5
  336. package/dist/modes/acp-mode.js.map +1 -1
  337. package/dist/modes/agent-home-mode.js +5 -5
  338. package/dist/modes/agent-home-mode.js.map +1 -1
  339. package/dist/modes/json-mode.js +5 -0
  340. package/dist/modes/json-mode.js.map +1 -1
  341. package/dist/modes/serve-mode.js +5 -5
  342. package/dist/modes/serve-mode.js.map +1 -1
  343. package/dist/motion-agent/motion-agent.d.ts +12 -5
  344. package/dist/motion-agent/motion-agent.js +24 -9
  345. package/dist/motion-agent/motion-agent.js.map +1 -1
  346. package/dist/motion-agent/motion-review.d.ts +0 -75
  347. package/dist/motion-agent/motion-review.js +0 -189
  348. package/dist/motion-agent/motion-review.js.map +1 -1
  349. package/dist/subagent-entry.d.ts +1 -0
  350. package/dist/subagent-entry.js +50 -0
  351. package/dist/subagent-entry.js.map +1 -0
  352. package/dist/system-prompt.d.ts +11 -4
  353. package/dist/system-prompt.js +38 -22
  354. package/dist/system-prompt.js.map +1 -1
  355. package/dist/test-support/system-tools.d.ts +6 -0
  356. package/dist/test-support/system-tools.js +36 -0
  357. package/dist/test-support/system-tools.js.map +1 -0
  358. package/dist/tools/ask-user.js +5 -3
  359. package/dist/tools/ask-user.js.map +1 -1
  360. package/dist/tools/bash.d.ts +9 -2
  361. package/dist/tools/bash.js +382 -362
  362. package/dist/tools/bash.js.map +1 -1
  363. package/dist/tools/checklist.js +6 -11
  364. package/dist/tools/checklist.js.map +1 -1
  365. package/dist/tools/debug.js +6 -9
  366. package/dist/tools/debug.js.map +1 -1
  367. package/dist/tools/document-text.d.ts +6 -0
  368. package/dist/tools/document-text.js +154 -0
  369. package/dist/tools/document-text.js.map +1 -0
  370. package/dist/tools/enter-plan.js +4 -7
  371. package/dist/tools/enter-plan.js.map +1 -1
  372. package/dist/tools/find.d.ts +9 -0
  373. package/dist/tools/find.js +38 -1
  374. package/dist/tools/find.js.map +1 -1
  375. package/dist/tools/generate-image.d.ts +18 -0
  376. package/dist/tools/generate-image.js +208 -17
  377. package/dist/tools/generate-image.js.map +1 -1
  378. package/dist/tools/goals.d.ts +2 -2
  379. package/dist/tools/index.d.ts +5 -2
  380. package/dist/tools/index.js +5 -13
  381. package/dist/tools/index.js.map +1 -1
  382. package/dist/tools/live-preview.d.ts +21 -0
  383. package/dist/tools/live-preview.js +37 -0
  384. package/dist/tools/live-preview.js.map +1 -0
  385. package/dist/tools/operations.js +1 -1
  386. package/dist/tools/operations.js.map +1 -1
  387. package/dist/tools/overflow.d.ts +2 -0
  388. package/dist/tools/overflow.js +10 -0
  389. package/dist/tools/overflow.js.map +1 -1
  390. package/dist/tools/path-utils.d.ts +0 -15
  391. package/dist/tools/path-utils.js +0 -17
  392. package/dist/tools/path-utils.js.map +1 -1
  393. package/dist/tools/prompt-hints.d.ts +2 -0
  394. package/dist/tools/prompt-hints.js +16 -9
  395. package/dist/tools/prompt-hints.js.map +1 -1
  396. package/dist/tools/read.js +25 -10
  397. package/dist/tools/read.js.map +1 -1
  398. package/dist/tools/routine-output.d.ts +10 -1
  399. package/dist/tools/routine-output.js +79 -1
  400. package/dist/tools/routine-output.js.map +1 -1
  401. package/dist/tools/screenshot.js +6 -10
  402. package/dist/tools/screenshot.js.map +1 -1
  403. package/dist/tools/side-web-search.d.ts +35 -0
  404. package/dist/tools/side-web-search.js +147 -0
  405. package/dist/tools/side-web-search.js.map +1 -0
  406. package/dist/tools/skill.d.ts +2 -0
  407. package/dist/tools/skill.js +33 -6
  408. package/dist/tools/skill.js.map +1 -1
  409. package/dist/tools/steroids.d.ts +7 -6
  410. package/dist/tools/steroids.js +193 -87
  411. package/dist/tools/steroids.js.map +1 -1
  412. package/dist/tools/subagent-control.js +66 -10
  413. package/dist/tools/subagent-control.js.map +1 -1
  414. package/dist/tools/subagent-shared.d.ts +19 -2
  415. package/dist/tools/subagent-shared.js +35 -10
  416. package/dist/tools/subagent-shared.js.map +1 -1
  417. package/dist/tools/subagent.js +23 -7
  418. package/dist/tools/subagent.js.map +1 -1
  419. package/dist/tools/tool-search.js +7 -1
  420. package/dist/tools/tool-search.js.map +1 -1
  421. package/dist/tools/tool-tiers.d.ts +3 -2
  422. package/dist/tools/tool-tiers.js +7 -5
  423. package/dist/tools/tool-tiers.js.map +1 -1
  424. package/dist/tools/truncate.d.ts +0 -2
  425. package/dist/tools/truncate.js +4 -10
  426. package/dist/tools/truncate.js.map +1 -1
  427. package/dist/tools/web-fetch.d.ts +15 -1
  428. package/dist/tools/web-fetch.js +138 -21
  429. package/dist/tools/web-fetch.js.map +1 -1
  430. package/dist/tools/web-search.d.ts +3 -2
  431. package/dist/tools/web-search.js +25 -1
  432. package/dist/tools/web-search.js.map +1 -1
  433. package/dist/ui/App.js +37 -38
  434. package/dist/ui/App.js.map +1 -1
  435. package/dist/ui/app-items.d.ts +0 -2
  436. package/dist/ui/app-items.js +0 -2
  437. package/dist/ui/app-items.js.map +1 -1
  438. package/dist/ui/components/Footer.js +8 -5
  439. package/dist/ui/components/Footer.js.map +1 -1
  440. package/dist/ui/components/ModelSelector.js +2 -0
  441. package/dist/ui/components/ModelSelector.js.map +1 -1
  442. package/dist/ui/components/SkillsOverlay.js +2 -1
  443. package/dist/ui/components/SkillsOverlay.js.map +1 -1
  444. package/dist/ui/constants/figures.d.ts +0 -8
  445. package/dist/ui/constants/figures.js +0 -8
  446. package/dist/ui/constants/figures.js.map +1 -1
  447. package/dist/ui/hooks/useAgentLoop.d.ts +3 -0
  448. package/dist/ui/hooks/useAgentLoop.js +54 -4
  449. package/dist/ui/hooks/useAgentLoop.js.map +1 -1
  450. package/dist/ui/hooks/useContextCompaction.js +1 -0
  451. package/dist/ui/hooks/useContextCompaction.js.map +1 -1
  452. package/dist/ui/language-pack-update.d.ts +25 -0
  453. package/dist/ui/language-pack-update.js +19 -0
  454. package/dist/ui/language-pack-update.js.map +1 -0
  455. package/dist/ui/layout-decisions.d.ts +0 -5
  456. package/dist/ui/layout-decisions.js +1 -10
  457. package/dist/ui/layout-decisions.js.map +1 -1
  458. package/dist/ui/terminal-history-status-renderers.d.ts +0 -1
  459. package/dist/ui/terminal-history-status-renderers.js +0 -12
  460. package/dist/ui/terminal-history-status-renderers.js.map +1 -1
  461. package/dist/ui/terminal-history.js +3 -1
  462. package/dist/ui/terminal-history.js.map +1 -1
  463. package/dist/ui/transcript/presentation.d.ts +1 -2
  464. package/dist/ui/transcript/presentation.js +0 -4
  465. package/dist/ui/transcript/presentation.js.map +1 -1
  466. package/dist/utils/http-body.d.ts +5 -0
  467. package/dist/utils/http-body.js +5 -0
  468. package/dist/utils/http-body.js.map +1 -1
  469. package/dist/utils/image.d.ts +11 -4
  470. package/dist/utils/image.js +34 -11
  471. package/dist/utils/image.js.map +1 -1
  472. package/dist/utils/plan-steps.d.ts +1 -0
  473. package/dist/utils/plan-steps.js +10 -0
  474. package/dist/utils/plan-steps.js.map +1 -1
  475. package/dist/utils/prompt-enhancer.d.ts +3 -1
  476. package/dist/utils/prompt-enhancer.js +21 -16
  477. package/dist/utils/prompt-enhancer.js.map +1 -1
  478. package/dist/web.d.ts +5 -0
  479. package/dist/web.js +5 -0
  480. package/dist/web.js.map +1 -0
  481. package/package.json +27 -6
  482. package/assets/skills/clarify/SKILL.md +0 -39
  483. package/assets/skills/code-review/SKILL.md +0 -88
  484. package/assets/skills/code-review/references/agent-diffs.md +0 -27
  485. package/assets/skills/code-review/references/tests.md +0 -19
  486. package/assets/skills/evidence-led-ui/LICENSES.md +0 -80
  487. package/assets/skills/evidence-led-ui/SKILL.md +0 -100
  488. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/LICENSE +0 -21
  489. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/airbnb/DESIGN.md +0 -545
  490. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/airtable/DESIGN.md +0 -554
  491. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/apple/DESIGN.md +0 -562
  492. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/binance/DESIGN.md +0 -634
  493. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/bmw/DESIGN.md +0 -544
  494. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/bmw-m/DESIGN.md +0 -503
  495. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/bugatti/DESIGN.md +0 -454
  496. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/cal/DESIGN.md +0 -542
  497. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/claude/DESIGN.md +0 -589
  498. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/clay/DESIGN.md +0 -541
  499. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/clickhouse/DESIGN.md +0 -544
  500. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/cohere/DESIGN.md +0 -451
  501. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/coinbase/DESIGN.md +0 -570
  502. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/composio/DESIGN.md +0 -506
  503. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/cursor/DESIGN.md +0 -537
  504. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/dell-1996/DESIGN.md +0 -632
  505. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/elevenlabs/DESIGN.md +0 -504
  506. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/expo/DESIGN.md +0 -526
  507. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/ferrari/DESIGN.md +0 -531
  508. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/figma/DESIGN.md +0 -578
  509. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/framer/DESIGN.md +0 -544
  510. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/hashicorp/DESIGN.md +0 -575
  511. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/hp/DESIGN.md +0 -670
  512. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/ibm/DESIGN.md +0 -550
  513. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/intercom/DESIGN.md +0 -546
  514. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/kraken/DESIGN.md +0 -125
  515. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/lamborghini/DESIGN.md +0 -288
  516. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/linear.app/DESIGN.md +0 -548
  517. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/lovable/DESIGN.md +0 -298
  518. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/mastercard/DESIGN.md +0 -365
  519. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/meta/DESIGN.md +0 -683
  520. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/minimax/DESIGN.md +0 -746
  521. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/mintlify/DESIGN.md +0 -852
  522. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/miro/DESIGN.md +0 -825
  523. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/mistral.ai/DESIGN.md +0 -773
  524. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/mongodb/DESIGN.md +0 -767
  525. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/nike/DESIGN.md +0 -575
  526. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/nintendo-2001/DESIGN.md +0 -649
  527. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/notion/DESIGN.md +0 -821
  528. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/nvidia/DESIGN.md +0 -640
  529. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/ollama/DESIGN.md +0 -539
  530. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/opencode.ai/DESIGN.md +0 -521
  531. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/pinterest/DESIGN.md +0 -597
  532. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/playstation/DESIGN.md +0 -661
  533. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/posthog/DESIGN.md +0 -690
  534. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/raycast/DESIGN.md +0 -669
  535. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/renault/DESIGN.md +0 -589
  536. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/replicate/DESIGN.md +0 -616
  537. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/resend/DESIGN.md +0 -585
  538. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/revolut/DESIGN.md +0 -636
  539. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/runwayml/DESIGN.md +0 -244
  540. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/sanity/DESIGN.md +0 -357
  541. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/sentry/DESIGN.md +0 -551
  542. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/shopify/DESIGN.md +0 -516
  543. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/slack/DESIGN.md +0 -482
  544. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/spacex/DESIGN.md +0 -363
  545. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/spotify/DESIGN.md +0 -246
  546. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/starbucks/DESIGN.md +0 -580
  547. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/stripe/DESIGN.md +0 -487
  548. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/supabase/DESIGN.md +0 -462
  549. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/superhuman/DESIGN.md +0 -448
  550. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/tesla/DESIGN.md +0 -286
  551. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/theverge/DESIGN.md +0 -339
  552. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/together.ai/DESIGN.md +0 -633
  553. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/uber/DESIGN.md +0 -636
  554. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/vercel/DESIGN.md +0 -736
  555. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/vodafone/DESIGN.md +0 -538
  556. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/voltagent/DESIGN.md +0 -521
  557. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/warp/DESIGN.md +0 -526
  558. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/webflow/DESIGN.md +0 -588
  559. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/wired/DESIGN.md +0 -497
  560. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/wise/DESIGN.md +0 -544
  561. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/x.ai/DESIGN.md +0 -465
  562. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/zapier/DESIGN.md +0 -537
  563. package/assets/skills/evidence-led-ui/data/corpus-manifest.json +0 -768
  564. package/assets/skills/evidence-led-ui/data/observations.json +0 -47053
  565. package/assets/skills/evidence-led-ui/references/anti-defaults.md +0 -110
  566. package/assets/skills/evidence-led-ui/references/archetypes.md +0 -97
  567. package/assets/skills/evidence-led-ui/references/craft-rulings.md +0 -242
  568. package/assets/skills/evidence-led-ui/references/direction.md +0 -124
  569. package/assets/skills/evidence-led-ui/references/methodology.md +0 -72
  570. package/assets/skills/evidence-led-ui/references/observed-patterns.md +0 -68
  571. package/assets/skills/evidence-led-ui/references/production-contract.md +0 -148
  572. package/assets/skills/evidence-led-ui/references/provenance.md +0 -142
  573. package/assets/skills/evidence-led-ui/references/quality-rubric.md +0 -126
  574. package/assets/skills/evidence-led-ui/references/ui-libraries.md +0 -30
  575. package/assets/skills/refactoring/SKILL.md +0 -87
  576. package/assets/skills/refactoring/references/agent-pitfalls.md +0 -46
  577. package/assets/skills/refactoring/references/legacy.md +0 -70
  578. package/assets/skills/refactoring/references/smells.md +0 -71
  579. package/assets/skills/root-cause/SKILL.md +0 -46
  580. package/assets/skills/shared-language/SKILL.md +0 -32
  581. package/assets/skills/tdd/SKILL.md +0 -42
  582. package/dist/core/setup-history.d.ts +0 -6
  583. package/dist/core/setup-history.js +0 -55
  584. package/dist/core/setup-history.js.map +0 -1
  585. package/dist/core/style-packs/index.d.ts +0 -18
  586. package/dist/core/style-packs/index.js +0 -60
  587. package/dist/core/style-packs/index.js.map +0 -1
  588. package/dist/core/style-packs/packs.d.ts +0 -8
  589. package/dist/core/style-packs/packs.js +0 -188
  590. package/dist/core/style-packs/packs.js.map +0 -1
  591. package/dist/interactive.d.ts +0 -2
  592. package/dist/interactive.js +0 -257
  593. package/dist/interactive.js.map +0 -1
  594. package/dist/motion-agent/motion-review-coverage.d.ts +0 -12
  595. package/dist/motion-agent/motion-review-coverage.js +0 -33
  596. package/dist/motion-agent/motion-review-coverage.js.map +0 -1
  597. package/dist/motion-agent/motion-review-gate.d.ts +0 -48
  598. package/dist/motion-agent/motion-review-gate.js +0 -88
  599. package/dist/motion-agent/motion-review-gate.js.map +0 -1
  600. package/dist/motion-agent/motion-review-session.d.ts +0 -65
  601. package/dist/motion-agent/motion-review-session.js +0 -422
  602. package/dist/motion-agent/motion-review-session.js.map +0 -1
  603. package/dist/tools/code-nav.d.ts +0 -29
  604. package/dist/tools/code-nav.js +0 -299
  605. package/dist/tools/code-nav.js.map +0 -1
  606. package/dist/tools/code-skeleton.d.ts +0 -28
  607. package/dist/tools/code-skeleton.js +0 -115
  608. package/dist/tools/code-skeleton.js.map +0 -1
  609. package/dist/tools/search-code.d.ts +0 -10
  610. package/dist/tools/search-code.js +0 -90
  611. package/dist/tools/search-code.js.map +0 -1
  612. package/dist/ui/stores/index.d.ts +0 -2
  613. package/dist/ui/stores/index.js +0 -3
  614. package/dist/ui/stores/index.js.map +0 -1
  615. package/dist/utils/format.d.ts +0 -16
  616. package/dist/utils/format.js +0 -159
  617. package/dist/utils/format.js.map +0 -1
  618. package/dist/utils/shell.d.ts +0 -2
  619. package/dist/utils/shell.js +0 -8
  620. package/dist/utils/shell.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { agentLoop, isAbortError, isUsageLimitError, repairToolPairingAdjacent, } from "@prestyj/agent";
2
- import { ProviderError, resolveToolSchema, stream, } from "@prestyj/ai";
2
+ import { ProviderError, resolveToolSchema, stream, preconnectProvider, } from "@prestyj/ai";
3
3
  import { EventBus } from "./event-bus.js";
4
4
  import { flagUntrustedToolResult } from "./injection-detect.js";
5
5
  import { sameStamp, scanProjectLockfiles, stampProjectLockfiles, } from "./installed-threats.js";
@@ -13,23 +13,25 @@ import { loadWorkspaceCustomCommands } from "./custom-commands.js";
13
13
  import { expandPromptCommand } from "./prompt-command-expansion.js";
14
14
  import { SettingsManager } from "./settings-manager.js";
15
15
  import { AuthStorage, NotLoggedInError } from "./auth-storage.js";
16
- import { dualAuthProvider } from "@prestyj/core";
17
- import { getClaudeCliUserAgent, recordRequiredClaudeCodeVersion } from "./claude-code-version.js";
16
+ import { claudeCodeConfigDir, dualAuthProvider } from "@prestyj/core";
17
+ import { getClaudeCliUserAgent } from "./claude-code-version.js";
18
+ import { claudeCodeTranscriptExists, holdClaudeCodeTranscript, pruneClaudeCodeTranscriptsOnce, } from "./claude-code/transcripts.js";
19
+ import { runSideWebSearch, runSideWebSearchViaClaudeCode, SIDE_SEARCH_MODEL, } from "../tools/side-web-search.js";
18
20
  import { kimiCodingHeaders, isKimiCodingEndpoint } from "./oauth/kimi.js";
19
21
  import { isGrokCliEndpoint } from "./oauth/xai.js";
20
- import { SessionManager, } from "./session-manager.js";
22
+ import { SessionManager, processIsAlive, } from "./session-manager.js";
21
23
  import { ExtensionLoader } from "./extensions/loader.js";
22
24
  import { shouldCompact, compact, } from "./compaction/compactor.js";
23
25
  import { getHistoryMessageVisibility } from "./session-history.js";
24
26
  import { sourceFingerprint as computeSourceFingerprint } from "./session-compaction.js";
25
- import { getAuthStorageKeys, getContextWindow, getModel, MODELS } from "./model-registry.js";
27
+ import { getAuthStorageKeys, getContextWindow, getListedModels, getModel, } from "./model-registry.js";
26
28
  import { discoverSkillsWithBlocked } from "./skills.js";
27
29
  import { ensureAppDirs } from "../config.js";
28
30
  import { buildSubAgentSystemPrompt, buildSystemPrompt, } from "../system-prompt.js";
29
31
  import { createTools, createWebSearchTool, } from "../tools/index.js";
30
32
  import { partitionToolsByTier } from "../tools/tool-tiers.js";
31
33
  import { formatImpactForVerification } from "./test-impact.js";
32
- import { buildProcessCompletionFollowUp } from "./process-gate.js";
34
+ import { buildProcessCompletionFollowUp, mergeCompletionGateFollowUps } from "./process-gate.js";
33
35
  import { PLAN_SUBMISSION_NUDGE, shouldNudgePlanSubmission } from "./plan-submission-gate.js";
34
36
  import { buildSubAgentCompletionFollowUp, } from "./subagent-manager.js";
35
37
  import { applyAsyncSubagentPolicy } from "./subagent-policy.js";
@@ -42,7 +44,7 @@ import { createSessionStatsTool } from "../tools/session-stats.js";
42
44
  import { createDiagnoseCommand, isInternalDiagnosticsEnabled, SessionDiagnosticsRecorder, } from "./internal-diagnostics.js";
43
45
  import { log } from "./logger.js";
44
46
  import { CacheDiagnostics } from "./cache-diagnostics.js";
45
- import { assessCacheExpiry, resolveCacheTtl } from "./cache-expiry.js";
47
+ import { assessCacheExpiry, CLAUDE_CODE_CACHE_TTL, resolveCacheTtl, } from "./cache-expiry.js";
46
48
  import { setEstimatorModel, calibrateEstimatorFromUsage, estimateConversationTokens, } from "./compaction/token-estimator.js";
47
49
  import { calculateActiveContextTokens } from "./compaction/active-context.js";
48
50
  import { resolveCompactionPolicy } from "./compaction/policy.js";
@@ -50,14 +52,20 @@ import { decidePlanStepCompaction, DEFAULT_CACHE_WRITE_READ_RATIO, PLAN_STEP_KEE
50
52
  import { extractPlanSteps, findCompletedMarkers } from "../utils/plan-steps.js";
51
53
  import { readFileSync } from "node:fs";
52
54
  import { clampThinkingForPlanMode } from "./thinking-level.js";
53
- import { pruneStaleToolResults, shouldPruneToolResults } from "./compaction/tool-result-pruner.js";
55
+ import { pruneMinimumTokens, pruneStaleToolResults, shouldPruneToolResults, } from "./compaction/tool-result-pruner.js";
54
56
  import { discoverAgents } from "./agents.js";
55
57
  import { enhancePrompt } from "../utils/prompt-enhancer.js";
58
+ import { assistantText, renderTranscript } from "./claude-code/events.js";
59
+ import { ClaudeCodeLiveSession, systemPrompt } from "./claude-code/live-session.js";
60
+ import { CLAUDE_CODE_SEED_CHARS, CLAUDE_CODE_SESSION_KIND, claudeCodeResumeId, claudeCodeSessionEntryData, parseClaudeCodeSessionState, } from "./claude-code/session-sync.js";
61
+ import { claudeCodeComplete, resolveClaudeCodeProcess, } from "./claude-code/complete.js";
56
62
  import { detectLanguages, detectProjectStack } from "./language-detector.js";
57
63
  import { buildLoopBreakMessage } from "./loop-breaker.js";
58
64
  import { buildRegroundingMessage, requestTextForRegrounding } from "./regrounding.js";
59
65
  import { buildSemanticLoopJudgePrompt, buildSemanticLoopMessage, parseSemanticLoopVerdict, SEMANTIC_LOOP_JUDGE_TIMEOUT_MS, withJudgeTimeout, } from "./semantic-loop-check.js";
60
66
  import { buildEnvDeltaMessage, buildLanguageUpdateMessage } from "./env-delta.js";
67
+ import { buildUserShellContextText } from "./user-shell-context.js";
68
+ import { buildPlanStateMessage, samePlanState } from "./plan-delta.js";
61
69
  import { listProjectFiles } from "./project-files.js";
62
70
  import { wrapSteeringText, buildNotificationSteeringText, buildIdleWakeNotificationText, STEERING_PREFIX, } from "./steering.js";
63
71
  import { AgentNotificationQueue } from "./agent-notifications.js";
@@ -125,9 +133,46 @@ export class PaidModelConfirmationError extends Error {
125
133
  export { resolveSessionToolResultCharLimit, resolveSessionTurnToolResultCharLimit, } from "./agent-session/helpers.js";
126
134
  // ── Agent Session ──────────────────────────────────────────
127
135
  /** A prompt that asks for the live web (see AgentSession.attachWebSearchIfAsked). */
136
+ /** True when the transcript holds a native (server-side) `web_search` call. */
137
+ export function historyUsesNativeWebSearch(messages) {
138
+ for (const message of messages) {
139
+ if (message.role !== "assistant" || !Array.isArray(message.content))
140
+ continue;
141
+ for (const part of message.content) {
142
+ if (part.type === "server_tool_call" && part.name === "web_search")
143
+ return true;
144
+ if (part.type === "raw") {
145
+ const data = part.data;
146
+ if (data?.type === "server_tool_use" && data.name === "web_search")
147
+ return true;
148
+ }
149
+ }
150
+ }
151
+ return false;
152
+ }
128
153
  const WEB_INTENT = /\b(?:web|internet|online|google|googling|website|look (?:it |this |that )?up|(?:latest|newest|current) (?:version|release|news|docs?|documentation)|release notes|news)\b/i;
129
154
  /** Distinct security rows one run may add to the chat (and session file). */
130
155
  const MAX_SECURITY_ROWS_PER_RUN = 20;
156
+ /** How long dispose waits for a post-turn compaction before aborting it. */
157
+ export const DISPOSE_COMPACTION_WAIT_MS = 2_500;
158
+ /** Grace after aborting it, for the compaction to unwind. */
159
+ const DISPOSE_COMPACTION_ABORT_GRACE_MS = 500;
160
+ /** Resolves true if `promise` settles within `ms`, else false. Never rejects. */
161
+ async function settleWithin(promise, ms) {
162
+ let timer;
163
+ const timeout = new Promise((resolve) => {
164
+ timer = setTimeout(() => resolve(false), ms);
165
+ });
166
+ try {
167
+ return await Promise.race([
168
+ promise.then(() => true, () => true),
169
+ timeout,
170
+ ]);
171
+ }
172
+ finally {
173
+ clearTimeout(timer);
174
+ }
175
+ }
131
176
  /**
132
177
  * A chat row's target: first line, no control or bidi-override characters
133
178
  * (they could make a command look like another), at most 120 chars.
@@ -221,6 +266,8 @@ export class AgentSession {
221
266
  renderedEnvironment = {};
222
267
  /** Project files as of the first prompt build (undefined until then). */
223
268
  projectFiles;
269
+ /** `git ls-files` started at the top of initialize(), overlapping the rest of setup. */
270
+ projectFilesPending;
224
271
  /** Wall-clock start of the current run; scopes the background-process gate. */
225
272
  runStartedAt = 0;
226
273
  /** Gate injections spent this run, capped by MAX_PROCESS_GATE_INJECTIONS. */
@@ -245,6 +292,8 @@ export class AgentSession {
245
292
  compactionArmedForNextRun = false;
246
293
  /** In-flight post-turn (background) compaction, if any. */
247
294
  postTurnCompaction;
295
+ /** Aborts the in-flight post-turn compaction (dispose caps its wait). */
296
+ postTurnCompactionAbort;
248
297
  lastCompactionCompacted = false;
249
298
  compactionRetryAfter = 0;
250
299
  /**
@@ -282,6 +331,11 @@ export class AgentSession {
282
331
  // every turn boundary, so an index captured by the UI can point at a
283
332
  // different message (or past the end) by the time the cancel arrives.
284
333
  userQueue = [];
334
+ // Steering whose text the model already read in an ask_user result.
335
+ askAnswerSteering = new WeakSet();
336
+ // Taken into the run but not yet in the transcript. Claude Code takes queued
337
+ // messages at once but reads them at its next turn, so they still show as queued.
338
+ deliveringQueue = [];
285
339
  queueSeq = 0;
286
340
  /** Monotonic count of human-originated prompts; idle-wake budgets reset on it. */
287
341
  humanPromptSeq = 0;
@@ -313,6 +367,10 @@ export class AgentSession {
313
367
  * can discover and promote them; a promoted name drops out of this list.
314
368
  */
315
369
  deferredBuiltinToolNames = [];
370
+ /** Deferred built-ins in tier order, fixed at session start. Sent as the
371
+ * provider's on-demand catalog (see @prestyj/ai `deferredTools`) so promoting one
372
+ * loads it through the transcript and the cached tools block stays put. */
373
+ deferredToolCatalog = [];
316
374
  provider;
317
375
  model;
318
376
  cwd;
@@ -329,10 +387,18 @@ export class AgentSession {
329
387
  agentPrompt;
330
388
  /** Stable prompt prefix retained separately from the volatile uncached tail. */
331
389
  baseSystemPrompt = "";
390
+ /** Plan state rendered into the cached system prompt. */
391
+ promptPlanState = { planMode: false, approvedPlanPath: undefined };
392
+ /** Plan state the model has been told (prompt or appended notice). */
393
+ seenPlanState = { planMode: false, approvedPlanPath: undefined };
394
+ /** Plan notice waiting for the next request, with the state it describes. */
395
+ pendingPlanNotice = null;
396
+ /** Latest plan notice appended — re-announced if compaction drops it. */
397
+ lastPlanNotice = null;
332
398
  /**
333
- * Project languages whose style packs and verify commands are in the
334
- * standard prompt. Only ever grows within a session (same policy as the
335
- * terminal UI): a pack disappearing mid-task would rewrite the cached prefix
399
+ * Project languages whose verify commands are in the standard prompt.
400
+ * Only ever grows within a session (same policy as the terminal UI): a
401
+ * section disappearing mid-task would rewrite the cached prefix
336
402
  * for no benefit.
337
403
  */
338
404
  activeLanguages = new Set();
@@ -379,6 +445,10 @@ export class AgentSession {
379
445
  * dropped as out-of-range. Anchoring to the persisted prefix keeps resume
380
446
  * placement 1:1 with where the row appeared live.
381
447
  */
448
+ /** Commands the user ran themselves, held until their next message. */
449
+ pendingUserShell = [];
450
+ /** MCP servers the user added or removed mid-session, not yet told to the model. */
451
+ pendingMcpNotices = [];
382
452
  persistedTranscriptCount() {
383
453
  return this.messages.slice(0, this.lastPersistedIndex).filter((m) => m.role !== "system")
384
454
  .length;
@@ -434,6 +504,12 @@ export class AgentSession {
434
504
  // so it overlaps session setup and the user's typing instead.
435
505
  if (this.provider === "anthropic")
436
506
  void getClaudeCliUserAgent().catch(() => { });
507
+ // The prompt's file list is a `git ls-files` (~30 ms on a mid-size repo)
508
+ // that nothing before buildBasePrompt depends on: start it now so it runs
509
+ // alongside settings/auth/skills/tools instead of after them.
510
+ if (!this.customSystemPrompt && this.projectFiles === undefined) {
511
+ this.projectFilesPending = listProjectFiles(this.cwd);
512
+ }
437
513
  const paths = await ensureAppDirs();
438
514
  // Load settings & auth
439
515
  this.settingsManager = new SettingsManager(paths.settingsFile);
@@ -444,7 +520,7 @@ export class AgentSession {
444
520
  // Session manager. Agent-specific roots keep chat and coder histories isolated.
445
521
  this.sessionManager = new SessionManager(this.opts.sessionRootDir ?? paths.sessionsDir);
446
522
  const projectCustomization = this.opts.projectCustomization !== false;
447
- // A real project folder: not Motion (own skills), not GG Goals (goal notes
523
+ // A real project folder: not Motion (own skills), not EZ Goals (goal notes
448
524
  // folder, agentContext "none"), not chat (no project customization).
449
525
  this.projectSession =
450
526
  projectCustomization &&
@@ -462,6 +538,7 @@ export class AgentSession {
462
538
  }
463
539
  if (this.opts.skills) {
464
540
  this.skills = [...this.opts.skills];
541
+ this.blockedSkills = [...(this.opts.blockedSkills ?? [])];
465
542
  }
466
543
  else if (projectCustomization) {
467
544
  const discovery = await discoverSkillsWithBlocked({
@@ -503,6 +580,7 @@ export class AgentSession {
503
580
  additionalRoots: this.additionalRoots,
504
581
  }),
505
582
  getPackageCooldownDays: () => this.settingsManager.get("packageCooldownDays"),
583
+ getBashPath: () => this.settingsManager.get("bashPath"),
506
584
  getNetworkPolicy: () => ({
507
585
  mode: this.settingsManager.get("networkMode"),
508
586
  allow: this.settingsManager.get("networkAllow"),
@@ -521,6 +599,7 @@ export class AgentSession {
521
599
  allowUnixSockets: this.settingsManager.get("sandboxAllowUnixSockets"),
522
600
  }),
523
601
  getUseExternalGrep: () => this.settingsManager.get("grepUseRipgrep"),
602
+ sideWebSearch: (request) => this.runSideWebSearch(request),
524
603
  authStorage: this.authStorage,
525
604
  onFileMutated: (filePath) => {
526
605
  const relative = path.relative(this.cwd, filePath) || path.basename(filePath);
@@ -600,6 +679,7 @@ export class AgentSession {
600
679
  // sits inside the cached prefix stays byte-stable across turns.
601
680
  this.tools = core;
602
681
  this.deferredBuiltinToolNames = deferred.map((t) => t.name);
682
+ this.deferredToolCatalog = [...deferred];
603
683
  this.mcp.addDeferred(deferred);
604
684
  }
605
685
  }
@@ -679,6 +759,7 @@ export class AgentSession {
679
759
  message: error instanceof Error ? error.message : String(error),
680
760
  });
681
761
  });
762
+ void pruneClaudeCodeTranscriptsOnce(claudeCodeConfigDir());
682
763
  }
683
764
  // EZ Coder owns its command registry. Other agents start with an isolated
684
765
  // empty registry and can register their own commands in their own file.
@@ -734,6 +815,7 @@ export class AgentSession {
734
815
  await this.extensionLoader.loadAll(paths.extensionsDir, extContext);
735
816
  }
736
817
  this.eventBus.emit("session_start", { sessionId: this.sessionId });
818
+ this.preconnect();
737
819
  }
738
820
  /**
739
821
  * Whether a tool name is permitted for this session. With no `allowedTools`
@@ -803,7 +885,9 @@ export class AgentSession {
803
885
  // empty catalog and tool_search would answer "the catalog is empty" for
804
886
  // capabilities that genuinely exist — a wrong answer, not a slow one.
805
887
  await this.seedMcpCatalogFromCache(servers);
806
- const connected = await mcpManager.connectAll(servers);
888
+ const results = await mcpManager.connectAllDetailed(servers);
889
+ this.mcp.recordServers(servers, results);
890
+ const connected = results.flatMap((r) => r.tools);
807
891
  // Defense-in-depth: even from a whitelisted server, only push tools that
808
892
  // pass the allow-list (no-op when there's no allow-list).
809
893
  const mcpTools = this.opts.allowedTools
@@ -829,6 +913,80 @@ export class AgentSession {
829
913
  log("WARN", "mcp", `MCP initialization failed: ${err instanceof Error ? err.message : String(err)}`);
830
914
  }
831
915
  }
916
+ /**
917
+ * The user added, changed or removed one MCP server mid-session: connect,
918
+ * reconnect or drop just that server, without a restart. `config` is its
919
+ * current effective config, or undefined when it is gone (or not allowed).
920
+ *
921
+ * Append-only for the prompt cache: new tools go into the tool_search
922
+ * catalog (or are appended when deferral is off), and the model learns about
923
+ * the change from a hidden note with the next message, never from a
924
+ * re-rendered system prompt. Returns null when nothing changed here.
925
+ */
926
+ async applyMcpServerChange(name, config) {
927
+ const manager = this.mcp.manager;
928
+ if (!manager)
929
+ return null;
930
+ const whitelist = this.opts.allowedMcpServers;
931
+ if (this.opts.allowedTools && !whitelist?.includes(name))
932
+ return null;
933
+ const wanted = config && config.enabled !== false ? config : undefined;
934
+ const previous = this.mcp.serverState(name);
935
+ // Same config still connected: nothing to do. Same config that failed
936
+ // (e.g. before an OAuth sign-in) is retried.
937
+ if (wanted && previous?.ok && previous.config === JSON.stringify(wanted))
938
+ return null;
939
+ if (!wanted && !previous)
940
+ return null;
941
+ if (previous) {
942
+ await manager.disconnect(name);
943
+ this.mcp.removeServer(name);
944
+ }
945
+ if (!wanted) {
946
+ this.pendingMcpNotices.push(`- MCP server "${name}" was removed by the user. Its mcp__${name}__* tools no longer work; don't call them.`);
947
+ log("INFO", "mcp", `Removed MCP server "${name}" mid-session`);
948
+ return { name, removed: true, connected: false, toolCount: 0 };
949
+ }
950
+ const [result] = await manager.connectAllDetailed([wanted]);
951
+ const ok = result?.ok ?? false;
952
+ this.mcp.recordServers([wanted], result ? [result] : []);
953
+ const tools = (result?.tools ?? []).filter((t) => !this.opts.allowedTools || this.isToolAllowed(t.name));
954
+ this.addMcpTools(tools);
955
+ if (ok) {
956
+ const deferred = !this.opts.allowedTools && this.settingsManager.get("deferredMcpTools");
957
+ const names = tools.map((t) => t.name);
958
+ const shown = names.slice(0, 20).join(", ") + (names.length > 20 ? ", …" : "");
959
+ this.pendingMcpNotices.push(`- The user connected MCP server "${name}" with ${tools.length} tool${tools.length === 1 ? "" : "s"}` +
960
+ (names.length > 0 ? `: ${shown}.` : ".") +
961
+ (deferred
962
+ ? " Load them with tool_search (e.g. by capability or the server name) when they help."
963
+ : " They are in your tool list now."));
964
+ }
965
+ log("INFO", "mcp", `Applied MCP server "${name}" mid-session`, {
966
+ ok: String(ok),
967
+ tools: String(tools.length),
968
+ });
969
+ return {
970
+ name,
971
+ removed: false,
972
+ connected: ok,
973
+ toolCount: tools.length,
974
+ ...(result?.error ? { error: result.error } : {}),
975
+ ...(result?.requiresAuth ? { requiresAuth: true } : {}),
976
+ };
977
+ }
978
+ takeMcpNotice() {
979
+ if (this.pendingMcpNotices.length === 0)
980
+ return null;
981
+ const lines = this.pendingMcpNotices.splice(0);
982
+ return {
983
+ role: "user",
984
+ provenance: { source: "runtime", kind: "notification", visibility: "hidden" },
985
+ content: "MCP update. The user changed MCP servers during this session:\n" +
986
+ lines.join("\n") +
987
+ "\nTrust this over anything earlier that disagrees. Do not restate this note; just proceed.",
988
+ };
989
+ }
832
990
  /** Persist `cwd` as a trusted project for project-scope MCP. Called by the
833
991
  * sidecar's `/mcp/add` handler when a user adds a project-scope server via
834
992
  * the MCP modal — the explicit add is itself the trust signal. The next
@@ -865,7 +1023,7 @@ export class AgentSession {
865
1023
  * Whether provider-native web search rides along with this request.
866
1024
  *
867
1025
  * Anthropic's `web_search_20250305` server tool costs ~2.5k prefix tokens on
868
- * every request (count_tokens: 6,628 vs 4,098 for the GG prefix without it),
1026
+ * every request (count_tokens: 6,628 vs 4,098 for the EZ Coder prefix without it),
869
1027
  * yet web search is reached in ~6% of sessions — the reason the client tool
870
1028
  * is deferred everywhere else. So on a tiered Anthropic session it is only
871
1029
  * attached once the model has promoted `web_search` (tool_search or a direct
@@ -875,9 +1033,14 @@ export class AgentSession {
875
1033
  nativeWebSearchOn() {
876
1034
  if (this.provider !== "anthropic")
877
1035
  return true;
878
- if (!this.deferredBuiltinToolNames.includes("web_search"))
879
- return true;
880
- return this.tools.some((t) => t.name === "web_search");
1036
+ // Anthropic search runs inside the client web_search tool as a side
1037
+ // request (runSideWebSearch): its result pages cost 11–20k cache-write
1038
+ // tokens each in the main context. A restored, branched or compacted conversation can already hold native
1039
+ // `web_search` blocks from when the tool was attached. Anthropic rejects
1040
+ // any request whose history references a server tool that is not declared
1041
+ // (400 "`server_tool_use` block references `web_search`…"), so the history
1042
+ // itself keeps native search on.
1043
+ return historyUsesNativeWebSearch(this.messages);
881
1044
  }
882
1045
  /**
883
1046
  * A human prompt that plainly asks for the web gets native web search from
@@ -888,7 +1051,7 @@ export class AgentSession {
888
1051
  * one discovery turn, a false hit only the ~2.5k-token schema.
889
1052
  */
890
1053
  attachWebSearchIfAsked(content) {
891
- if (this.provider !== "anthropic" || this.nativeWebSearchOn())
1054
+ if (this.provider !== "anthropic" || this.tools.some((t) => t.name === "web_search"))
892
1055
  return;
893
1056
  const text = typeof content === "string"
894
1057
  ? content
@@ -900,6 +1063,277 @@ export class AgentSession {
900
1063
  if (WEB_INTENT.test(text))
901
1064
  this.promoteDeferredBuiltin("web_search");
902
1065
  }
1066
+ async runSideWebSearch(request) {
1067
+ if (this.provider !== "anthropic")
1068
+ return null;
1069
+ const claudeCode = await this.claudeCodeProcess();
1070
+ if (claudeCode)
1071
+ return await runSideWebSearchViaClaudeCode(request, claudeCode);
1072
+ const creds = await this.authStorage.resolveCredentials("anthropic", {
1073
+ storageKeys: getAuthStorageKeys("anthropic", SIDE_SEARCH_MODEL),
1074
+ });
1075
+ return await runSideWebSearch(request, {
1076
+ apiKey: creds.accessToken,
1077
+ baseUrl: this.baseUrl ?? creds.baseUrl,
1078
+ userAgent: await getClaudeCliUserAgent(),
1079
+ });
1080
+ }
1081
+ // No creds = Claude subscription route; compact() then summarizes through Claude Code.
1082
+ async maybeCompactPreRun(creds) {
1083
+ if (this.settingsManager.get("autoCompact") && Date.now() >= this.compactionRetryAfter) {
1084
+ // A post-turn compaction may still be running in the background. Let it
1085
+ // settle first: it usually already compacted this history, so the
1086
+ // decision below turns into a no-op instead of duplicate work.
1087
+ if (this.postTurnCompaction)
1088
+ await this.postTurnCompaction;
1089
+ const contextWindow = getContextWindow(this.model, {
1090
+ provider: this.provider,
1091
+ accountId: creds?.accountId,
1092
+ });
1093
+ const policy = resolveCompactionPolicy({
1094
+ provider: this.provider,
1095
+ model: this.model,
1096
+ contextWindow,
1097
+ threshold: this.settingsManager.get("compactThreshold"),
1098
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
1099
+ accountId: creds?.accountId,
1100
+ approvedPlanPath: this.approvedPlanPath,
1101
+ });
1102
+ let activeTokens;
1103
+ if (this.providerContext) {
1104
+ const anchorIndex = this.messages.lastIndexOf(this.providerContext.anchor);
1105
+ if (anchorIndex >= 0) {
1106
+ activeTokens = calculateActiveContextTokens(this.messages, {
1107
+ usage: this.providerContext.usage,
1108
+ pendingMessages: this.messages.slice(anchorIndex + 1),
1109
+ });
1110
+ }
1111
+ else {
1112
+ this.providerContext = null;
1113
+ }
1114
+ }
1115
+ log("INFO", "compaction", "Pre-run compaction decision", {
1116
+ provider: this.provider,
1117
+ model: this.model,
1118
+ transport: this.compactionTransport(creds),
1119
+ contextWindow: String(contextWindow),
1120
+ activeTokens: activeTokens === undefined ? "estimated" : String(activeTokens),
1121
+ triggerLimit: String(policy.targetTokens),
1122
+ });
1123
+ if (shouldCompact(this.messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens)) {
1124
+ try {
1125
+ await this.compact(creds, "automatic");
1126
+ if (this.lastCompactionCompacted) {
1127
+ // Re-grounding hook keys off this — the context was just summarized.
1128
+ this.compactionOccurred = true;
1129
+ this.compactionRetryAfter = 0;
1130
+ }
1131
+ else {
1132
+ this.compactionRetryAfter = Date.now() + 30_000;
1133
+ }
1134
+ }
1135
+ catch (error) {
1136
+ this.compactionRetryAfter = Date.now() + 30_000;
1137
+ if (isAbortError(error) || this.opts.signal?.aborted)
1138
+ throw error;
1139
+ log("WARN", "compaction", `Pre-run compaction failed; cooling down for 30s: ${error instanceof Error ? error.message : String(error)}`);
1140
+ }
1141
+ }
1142
+ }
1143
+ }
1144
+ compactionTransport(creds) {
1145
+ if (!creds)
1146
+ return "claude_code";
1147
+ return this.provider === "openai" && creds.accountId ? "codex_oauth" : "public_api";
1148
+ }
1149
+ /** One run on the Claude subscription route: Claude Code drives the loop with our prompt and tools. */
1150
+ async runClaudeCodeLoop(process, options) {
1151
+ let loopMessages = await this.prepareDynamicContext();
1152
+ let resume = claudeCodeResumeId(this.claudeCodeSession, loopMessages);
1153
+ // Claude Code fails a resume whose transcript is gone (retention pass, or
1154
+ // removed by hand); our history can seed a fresh session instead.
1155
+ if (resume &&
1156
+ !(await claudeCodeTranscriptExists(process.env.CLAUDE_CONFIG_DIR ?? claudeCodeConfigDir(), resume))) {
1157
+ log("INFO", "claude-code", "Transcript missing; seeding a fresh session from history");
1158
+ resume = undefined;
1159
+ }
1160
+ // A fresh Claude Code session gets our history as text; summarize it first
1161
+ // when it would not fit.
1162
+ if (!resume &&
1163
+ renderTranscript(loopMessages, Number.MAX_SAFE_INTEGER).length > CLAUDE_CODE_SEED_CHARS) {
1164
+ try {
1165
+ await this.compact(undefined, "automatic");
1166
+ }
1167
+ catch (error) {
1168
+ if (isAbortError(error) || this.opts.signal?.aborted)
1169
+ throw error;
1170
+ log("WARN", "compaction", "Summary before seeding Claude Code failed", {
1171
+ error: error instanceof Error ? error.message : String(error),
1172
+ });
1173
+ }
1174
+ loopMessages = await this.prepareDynamicContext();
1175
+ }
1176
+ let sessionId = resume;
1177
+ const title = this.sessionPreview?.trim().slice(0, 80);
1178
+ const thinking = this.planModeRef.current || options.capThinking
1179
+ ? clampThinkingForPlanMode(this.thinkingLevel)
1180
+ : this.thinkingLevel;
1181
+ const live = await this.claudeCodeLiveFor(process, loopMessages, resume, thinking, options);
1182
+ const generator = live.run(loopMessages, {
1183
+ provider: this.provider,
1184
+ model: this.model,
1185
+ tools: options.disableTools ? [] : this.tools,
1186
+ maxTurns: this.opts.maxTurns,
1187
+ thinking,
1188
+ signal: this.opts.signal,
1189
+ maxToolResultChars: resolveSessionToolResultCharLimit(this.model, this.provider, undefined),
1190
+ transformToolResult: flagUntrustedToolResult,
1191
+ ...(options.disableTools
1192
+ ? {}
1193
+ : { resolveTool: (name) => this.promoteDeferredBuiltin(name) }),
1194
+ getSteeringMessages: () => this.getHookSteeringMessages(),
1195
+ steeringAlreadyRead: (message) => this.askAnswerSteering.has(message),
1196
+ onSteeringAvailable: (listener) => {
1197
+ this.steeringListeners.add(listener);
1198
+ return () => this.steeringListeners.delete(listener);
1199
+ },
1200
+ getFollowUpMessages: () => this.getHookFollowUpMessages(),
1201
+ claudeCode: {
1202
+ ...process,
1203
+ maxSeedChars: CLAUDE_CODE_SEED_CHARS,
1204
+ ...(resume ? { resume } : {}),
1205
+ ...(title ? { title } : {}),
1206
+ onSessionId: (id) => {
1207
+ sessionId = id;
1208
+ },
1209
+ },
1210
+ });
1211
+ this.activeLoopMessages = loopMessages;
1212
+ try {
1213
+ for await (const event of generator) {
1214
+ await this.trackHookEvent(event);
1215
+ // Claude Code sends the requests, so the cache-diagnostics pass never
1216
+ // sees them; without a touch every idle chat read as an expired cache.
1217
+ if (event.type === "turn_end" && event.stopReason !== "error") {
1218
+ this.cacheDiagnostics.noteCacheTouch({
1219
+ at: Date.now(),
1220
+ provider: this.provider,
1221
+ model: this.model,
1222
+ policy: CLAUDE_CODE_CACHE_TTL,
1223
+ });
1224
+ }
1225
+ // Same line names as the public-API route, which logs them from the agent loop.
1226
+ if (event.type === "turn_end") {
1227
+ const cacheRead = event.usage.cacheRead ?? 0;
1228
+ const cacheWrite = event.usage.cacheWrite ?? 0;
1229
+ const promptTokens = event.usage.inputTokens + cacheRead + cacheWrite;
1230
+ log("INFO", "stream", "cache_health", {
1231
+ promptTokens,
1232
+ cacheRead,
1233
+ cacheWrite,
1234
+ ...(promptTokens > 0
1235
+ ? { ratio: Math.round((cacheRead / promptTokens) * 100) / 100 }
1236
+ : {}),
1237
+ ...(event.timing.ttftMs !== undefined ? { ttftMs: event.timing.ttftMs } : {}),
1238
+ providerDurationMs: event.timing.providerDurationMs,
1239
+ outputTokens: event.usage.outputTokens,
1240
+ provider: this.provider,
1241
+ model: this.model,
1242
+ transport: "claude_code",
1243
+ });
1244
+ }
1245
+ else if (event.type === "retry") {
1246
+ log("INFO", "stream", "retry", {
1247
+ reason: event.reason,
1248
+ attempt: event.attempt,
1249
+ maxAttempts: event.maxAttempts,
1250
+ delayMs: event.delayMs,
1251
+ transport: "claude_code",
1252
+ });
1253
+ }
1254
+ this.eventBus.forwardAgentEvent(event);
1255
+ }
1256
+ }
1257
+ finally {
1258
+ // The SDK counts maxTurns per process, so a capped session runs one process per run.
1259
+ if (live !== this.claudeCodeLive?.session)
1260
+ live.close("one-shot");
1261
+ this.activeLoopMessages = null;
1262
+ // A stopped run records unplaced messages without an event.
1263
+ this.settleDeliveredMessages(() => true);
1264
+ this.messages = loopMessages;
1265
+ for (let i = this.lastPersistedIndex; i < this.messages.length; i++) {
1266
+ await this.persistMessage(this.messages[i]);
1267
+ }
1268
+ this.lastPersistedIndex = this.messages.length;
1269
+ if (sessionId)
1270
+ await this.recordClaudeCodeSession(sessionId);
1271
+ }
1272
+ }
1273
+ /**
1274
+ * The Claude Code process for this run: the chat's live one when it holds
1275
+ * exactly our history with the same settings, else a new one (the old one is
1276
+ * closed first, so a chat never keeps two).
1277
+ */
1278
+ async claudeCodeLiveFor(process, messages, resume, thinking, options) {
1279
+ const hash = (value) => crypto.createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 16);
1280
+ const key = {
1281
+ executable: process.executable,
1282
+ cwd: process.cwd,
1283
+ model: this.model,
1284
+ system: hash(systemPrompt(messages, undefined)),
1285
+ thinking: thinking ? "on" : "off",
1286
+ tools: options.disableTools ? "off" : "on",
1287
+ };
1288
+ // Per variable, so a restart log names what moved (names only, never values).
1289
+ for (const [name, value] of Object.entries(process.env)) {
1290
+ // The SDK writes this into the daemon's env on its first query(); it sets it for the child anyway.
1291
+ if (name !== "CLAUDE_AGENT_SDK_VERSION")
1292
+ key[`env:${name}`] = hash(value);
1293
+ }
1294
+ const current = this.claudeCodeLive;
1295
+ const changed = current
1296
+ ? [...new Set([...Object.keys(key), ...Object.keys(current.key)])].filter((name) => current.key[name] !== key[name])
1297
+ : [];
1298
+ if (current &&
1299
+ changed.length === 0 &&
1300
+ current.session.alive &&
1301
+ !current.session.busy &&
1302
+ resume !== undefined &&
1303
+ resume === current.session.sessionId &&
1304
+ (await current.session.setEffort(thinking))) {
1305
+ return current.session;
1306
+ }
1307
+ this.closeClaudeCodeLive(changed.length > 0 ? `changed: ${changed.join(",")}` : "history or effort changed");
1308
+ const session = new ClaudeCodeLiveSession();
1309
+ if (!this.opts.maxTurns)
1310
+ this.claudeCodeLive = { session, key };
1311
+ return session;
1312
+ }
1313
+ closeClaudeCodeLive(reason) {
1314
+ this.claudeCodeLive?.session.close(reason);
1315
+ this.claudeCodeLive = null;
1316
+ }
1317
+ async recordClaudeCodeSession(sessionId) {
1318
+ const history = this.messages.filter((m) => m.role !== "system");
1319
+ const state = { sessionId, messageCount: history.length, anchor: history.at(-1) };
1320
+ this.claudeCodeSession = state;
1321
+ this.holdClaudeCodeTranscript();
1322
+ if (!this.sessionPath)
1323
+ return;
1324
+ await this.sessionManager.appendEntry(this.sessionPath, {
1325
+ type: "custom",
1326
+ kind: CLAUDE_CODE_SESSION_KIND,
1327
+ id: crypto.randomUUID(),
1328
+ parentId: null,
1329
+ timestamp: new Date().toISOString(),
1330
+ data: claudeCodeSessionEntryData(state),
1331
+ });
1332
+ }
1333
+ /** Claude Code settings when this session runs on a Claude subscription, else null. */
1334
+ claudeCodeProcess() {
1335
+ return resolveClaudeCodeProcess(this.authStorage, this.provider, this.cwd);
1336
+ }
903
1337
  /** Append a deferred built-in to the live tool list (append-only). */
904
1338
  promoteDeferredBuiltin(name) {
905
1339
  if (!this.deferredBuiltinToolNames.includes(name))
@@ -912,6 +1346,26 @@ export class AgentSession {
912
1346
  this.tools.push(tool);
913
1347
  return tool;
914
1348
  }
1349
+ // A restored conversation still calls the on-demand tools it used; Claude
1350
+ // Code refuses any name missing from the list this process gives it.
1351
+ reloadUsedTools(messages) {
1352
+ if (this.deferredBuiltinToolNames.length === 0)
1353
+ return;
1354
+ for (const message of messages) {
1355
+ if (message.role === "assistant" && Array.isArray(message.content)) {
1356
+ for (const part of message.content) {
1357
+ if (part.type === "tool_call")
1358
+ this.promoteDeferredBuiltin(part.name);
1359
+ }
1360
+ }
1361
+ else if (message.role === "tool") {
1362
+ for (const result of message.content) {
1363
+ for (const name of result.loadedTools ?? [])
1364
+ this.promoteDeferredBuiltin(name);
1365
+ }
1366
+ }
1367
+ }
1368
+ }
915
1369
  wrapToPromote(trigger, followUps, when = () => true) {
916
1370
  const index = this.tools.findIndex((t) => t.name === trigger);
917
1371
  const tool = index >= 0 ? this.tools[index] : undefined;
@@ -923,8 +1377,17 @@ export class AgentSession {
923
1377
  const result = await tool.execute(args, context);
924
1378
  if (when(args)) {
925
1379
  const missing = followUps.filter((name) => !this.tools.some((t) => t.name === name));
926
- if (missing.length > 0)
927
- this.tools.push(...this.mcp.promote(missing));
1380
+ const promoted = missing.length > 0 ? this.mcp.promote(missing) : [];
1381
+ if (promoted.length > 0) {
1382
+ this.tools.push(...promoted);
1383
+ // The trigger's result is where the follow-ups load (cache-safe
1384
+ // transports load them in the transcript, not the tools block).
1385
+ const structured = typeof result === "string" ? { content: result } : result;
1386
+ return {
1387
+ ...structured,
1388
+ loadedTools: [...(structured.loadedTools ?? []), ...promoted.map((t) => t.name)],
1389
+ };
1390
+ }
928
1391
  }
929
1392
  return result;
930
1393
  },
@@ -1001,6 +1464,8 @@ export class AgentSession {
1001
1464
  // Prompt templates remain human-originated: the user invoked the command.
1002
1465
  const userMessage = { role: "user", content: slash.fullPrompt, provenance };
1003
1466
  await this.announceNewLanguages();
1467
+ if (provenance.source === "human")
1468
+ await this.deliverUserShellContext();
1004
1469
  this.messages.push(userMessage);
1005
1470
  await this.persistMessage(userMessage);
1006
1471
  this.lastPersistedIndex = this.messages.length;
@@ -1018,6 +1483,8 @@ export class AgentSession {
1018
1483
  // Push user message
1019
1484
  const userMessage = { role: "user", content, provenance };
1020
1485
  await this.announceNewLanguages();
1486
+ if (provenance.source === "human")
1487
+ await this.deliverUserShellContext();
1021
1488
  this.messages.push(userMessage);
1022
1489
  await this.persistMessage(userMessage);
1023
1490
  this.lastPersistedIndex = this.messages.length;
@@ -1047,11 +1514,16 @@ export class AgentSession {
1047
1514
  provenance: { source: "human", kind: "prompt", visibility: "transcript" },
1048
1515
  };
1049
1516
  await this.announceNewLanguages();
1517
+ await this.deliverUserShellContext();
1050
1518
  this.messages.push(userMessage);
1051
1519
  await this.persistMessage(userMessage);
1052
1520
  this.lastPersistedIndex = this.messages.length;
1053
1521
  await this.runLoop();
1054
1522
  }
1523
+ /** A typed reply's attachments as blocks for the question it answers (ask_user). */
1524
+ askReplyAttachmentParts(attachments) {
1525
+ return this.buildAttachmentParts("", attachments);
1526
+ }
1055
1527
  /**
1056
1528
  * Build the native content blocks (text + image/video notes + file notes) for
1057
1529
  * a user message with attachments. Shared by {@link promptWithAttachments} and
@@ -1116,12 +1588,24 @@ export class AgentSession {
1116
1588
  else if (a.path) {
1117
1589
  fileNotes.push(`- ${a.name} (saved at ${a.path})`);
1118
1590
  }
1591
+ else {
1592
+ // Never drop a file silently: a file-only prompt would otherwise build no
1593
+ // parts and never run.
1594
+ parts.push({
1595
+ type: "text",
1596
+ text: `[User attached a file "${a.name}" but it could not be saved, so it can't be opened.]`,
1597
+ });
1598
+ }
1119
1599
  }
1120
1600
  const textParts = [];
1121
1601
  if (text.trim())
1122
1602
  textParts.push(text.trim());
1123
1603
  if (fileNotes.length > 0) {
1124
- textParts.push(`Attached files (inspect with your tools):\n${fileNotes.join("\n")}`);
1604
+ // Without this the model unzips/greps documents through bash instead.
1605
+ const docHint = attachments.some((a) => a.kind === "file" && a.path && /\.(pdf|epub)$/i.test(a.path))
1606
+ ? "\nThe read tool opens PDF and EPUB files as text."
1607
+ : "";
1608
+ textParts.push(`Attached files (inspect with your tools):\n${fileNotes.join("\n")}${docHint}`);
1125
1609
  }
1126
1610
  if (textParts.length > 0)
1127
1611
  parts.unshift({ type: "text", text: textParts.join("\n\n") });
@@ -1207,6 +1691,9 @@ export class AgentSession {
1207
1691
  // The assistant message for this turn is now in the array.
1208
1692
  await this.flushPendingMessages();
1209
1693
  break;
1694
+ case "steering_message":
1695
+ this.settleDeliveredMessages((m) => m.content === event.content);
1696
+ break;
1210
1697
  case "checkpoint":
1211
1698
  // Tool results for this step are in the array and their side effects
1212
1699
  // already hit the filesystem. Flushing here is what makes a crash lose
@@ -1216,6 +1703,14 @@ export class AgentSession {
1216
1703
  break;
1217
1704
  }
1218
1705
  }
1706
+ /** Drop delivered queued messages and announce the new queue depth. */
1707
+ settleDeliveredMessages(delivered) {
1708
+ const before = this.deliveringQueue.length;
1709
+ this.deliveringQueue = this.deliveringQueue.filter((m) => !delivered(m));
1710
+ if (this.deliveringQueue.length !== before) {
1711
+ this.eventBus.emit("queue_drained", { count: this.userQueue.length });
1712
+ }
1713
+ }
1219
1714
  /**
1220
1715
  * Count full-file `cat` output from the step that just finished as reads, so
1221
1716
  * an edit after `cat` does not cost a second read. Uses the step's results as
@@ -1288,6 +1783,12 @@ export class AgentSession {
1288
1783
  // never been told about. The note states the facts outright rather than
1289
1784
  // referring to a section such a prompt does not have.
1290
1785
  const environmentDelta = buildEnvDeltaMessage(this.renderedEnvironment, this.promptEnvironment());
1786
+ // Plan mode toggled / plan approved mid-run: appended, never re-rendered.
1787
+ const planNotice = this.takePlanNotice();
1788
+ if (planNotice) {
1789
+ log("INFO", "session", "Injecting plan state update instead of rebuilding the prompt");
1790
+ }
1791
+ const mcpNotice = this.takeMcpNotice();
1291
1792
  if (environmentDelta) {
1292
1793
  // The model has now been told; only a further change re-triggers this.
1293
1794
  this.renderedEnvironment = this.promptEnvironment();
@@ -1324,11 +1825,9 @@ export class AgentSession {
1324
1825
  // agent sees them mid-loop instead of after it stops.
1325
1826
  if (this.userQueue.length > 0) {
1326
1827
  const queued = this.userQueue.splice(0);
1327
- // The agent has now consumed these. Announce the new depth immediately so
1328
- // clients can drop the "queued" affordance at the turn boundary rather
1329
- // than holding it until the whole run ends — the message is already in
1330
- // the loop, and showing it as still-pending for minutes is a lie.
1331
- this.eventBus.emit("queue_drained", { count: this.userQueue.length });
1828
+ // `queue_drained` fires when each lands in the transcript (its
1829
+ // steering_message event), not here, so clients drop the "queued" look
1830
+ // when the agent reads it, not minutes later at run end.
1332
1831
  // Frame each queued item as concurrent steering — without this wrapper
1333
1832
  // the model treats a mid-run message as a fresh request that supersedes
1334
1833
  // the original task and silently drops it. ONE message per queued item
@@ -1351,15 +1850,27 @@ export class AgentSession {
1351
1850
  ];
1352
1851
  return { role: "user", content: parts, provenance };
1353
1852
  });
1853
+ steeringMessages.forEach((message, index) => {
1854
+ const { id, text, answeredAsk } = queued[index];
1855
+ if (answeredAsk)
1856
+ this.askAnswerSteering.add(message);
1857
+ this.deliveringQueue.push({ id, text, content: message.content });
1858
+ });
1859
+ const userShell = this.takeUserShellContext();
1354
1860
  return [
1355
1861
  ...(environmentDelta ? [environmentDelta] : []),
1862
+ ...(planNotice ? [planNotice] : []),
1863
+ ...(mcpNotice ? [mcpNotice] : []),
1864
+ ...(userShell ? [userShell] : []),
1356
1865
  ...steeringMessages,
1357
1866
  ...(notificationMessage ? [notificationMessage] : []),
1358
1867
  ];
1359
1868
  }
1360
- if (environmentDelta || notificationMessage) {
1869
+ if (environmentDelta || planNotice || mcpNotice || notificationMessage) {
1361
1870
  return [
1362
1871
  ...(environmentDelta ? [environmentDelta] : []),
1872
+ ...(planNotice ? [planNotice] : []),
1873
+ ...(mcpNotice ? [mcpNotice] : []),
1363
1874
  ...(notificationMessage ? [notificationMessage] : []),
1364
1875
  ];
1365
1876
  }
@@ -1453,6 +1964,23 @@ export class AgentSession {
1453
1964
  throw new Error("Active model has no confirmed image support");
1454
1965
  signal.throwIfAborted();
1455
1966
  try {
1967
+ const claudeCode = await this.claudeCodeProcess();
1968
+ if (claudeCode) {
1969
+ const response = await claudeCodeComplete({
1970
+ ...claudeCode,
1971
+ model,
1972
+ messages: [
1973
+ { role: "system", content: request.instruction },
1974
+ { role: "user", content: [{ type: "text", text: request.context }, ...request.images] },
1975
+ ],
1976
+ thinking,
1977
+ signal,
1978
+ });
1979
+ const text = assistantText(response.message.content);
1980
+ if (text.length > 32_768)
1981
+ throw new Error("Review response exceeded its limit");
1982
+ return { text, model, provider, thinking };
1983
+ }
1456
1984
  const creds = await this.authStorage.resolveCredentials(provider, {
1457
1985
  storageKeys: this.currentAuthStorageKeys(),
1458
1986
  });
@@ -1500,6 +2028,16 @@ export class AgentSession {
1500
2028
  * cheaper routing: judging a model's own failure patterns with a weaker
1501
2029
  * model swaps false negatives for false positives. */
1502
2030
  async callSemanticLoopJudge(prompt) {
2031
+ const claudeCode = await this.claudeCodeProcess();
2032
+ if (claudeCode) {
2033
+ const response = await withJudgeTimeout(claudeCodeComplete({
2034
+ ...claudeCode,
2035
+ model: this.model,
2036
+ messages: [{ role: "user", content: prompt }],
2037
+ signal: this.opts.signal,
2038
+ }), SEMANTIC_LOOP_JUDGE_TIMEOUT_MS);
2039
+ return assistantText(response.message.content);
2040
+ }
1503
2041
  const creds = await this.authStorage.resolveCredentials(this.provider, {
1504
2042
  storageKeys: this.currentAuthStorageKeys(),
1505
2043
  });
@@ -1610,19 +2148,26 @@ export class AgentSession {
1610
2148
  },
1611
2149
  ]
1612
2150
  : [];
1613
- const childCompletionFollowUp = buildSubAgentCompletionFollowUp(this.subAgentManager);
1614
- if (childCompletionFollowUp)
1615
- return [...diagnosticMessages, ...childCompletionFollowUp];
2151
+ const childCompletionFollowUp = buildSubAgentCompletionFollowUp(this.subAgentManager) ?? [];
1616
2152
  // Background processes started this run and never read block completion:
1617
2153
  // their progress/exit checkpoints only land on the steering path, which an
1618
- // agent about to stop never reaches.
1619
- const processFollowUp = buildProcessCompletionFollowUp(this.processManager?.list() ?? [], this.runStartedAt, this.processGateInjected);
1620
- if (processFollowUp) {
2154
+ // agent about to stop never reaches. Sent in the same follow-up as the
2155
+ // child-agent gate: one forced turn can collect both, where returning them
2156
+ // one per stop cost a separate model round-trip each.
2157
+ const processFollowUp = buildProcessCompletionFollowUp(this.processManager?.list() ?? [], this.runStartedAt, this.processGateInjected) ?? [];
2158
+ if (processFollowUp.length > 0) {
1621
2159
  this.processGateInjected += 1;
1622
2160
  log("INFO", "process-gate", "Injecting background-process completion gate", {
1623
2161
  injected: String(this.processGateInjected),
1624
2162
  });
1625
- return [...diagnosticMessages, ...processFollowUp];
2163
+ }
2164
+ // Child agents and background processes ride one forced turn together
2165
+ // (with any diagnostics). Diagnostics alone fall through, so the
2166
+ // verification gate below can join them in that same turn.
2167
+ if (childCompletionFollowUp.length > 0 || processFollowUp.length > 0) {
2168
+ const gateMessages = mergeCompletionGateFollowUps(diagnosticMessages, childCompletionFollowUp, processFollowUp);
2169
+ if (gateMessages)
2170
+ return gateMessages;
1626
2171
  }
1627
2172
  // A check whose exit status could not count (`npm test | tail; node -e …`)
1628
2173
  // is re-run on its own before the gate decides, so a passing run is not
@@ -1797,6 +2342,16 @@ export class AgentSession {
1797
2342
  .reverse()
1798
2343
  .find((m) => m.role === "user" && m.provenance?.kind !== "notification");
1799
2344
  this.resetHookState(requestTextForRegrounding(lastUser));
2345
+ // A Claude subscription only connects through Claude Code; compaction stays ours.
2346
+ const claudeCode = await this.claudeCodeProcess();
2347
+ if (claudeCode) {
2348
+ await this.maybeCompactPreRun();
2349
+ await this.runClaudeCodeLoop(claudeCode, options);
2350
+ this.maybeCompactPostTurn();
2351
+ return;
2352
+ }
2353
+ // Left the Claude subscription route (provider switch, sign-out).
2354
+ this.closeClaudeCodeLive("route changed");
1800
2355
  // Resolve OAuth credentials and run agent loop.
1801
2356
  // On 401, force-refresh the token and retry once — the provider may have
1802
2357
  // revoked the token server-side before the stored expiry (e.g. after a restart).
@@ -1812,72 +2367,9 @@ export class AgentSession {
1812
2367
  let lastResolvedAccessToken = creds.accessToken;
1813
2368
  // Auto-compact if needed. This must happen after credential resolution so
1814
2369
  // OpenAI OAuth/Codex sessions use the Codex product context window instead
1815
- // of the public API model window. Failed/no-op attempts cool down across
1816
- // prompts; provider overflow recovery still bypasses this path entirely.
1817
- if (this.settingsManager.get("autoCompact") && Date.now() >= this.compactionRetryAfter) {
1818
- // A post-turn compaction may still be running in the background. Let it
1819
- // settle first: it usually already compacted this history, so the
1820
- // decision below turns into a no-op instead of duplicate work.
1821
- if (this.postTurnCompaction)
1822
- await this.postTurnCompaction;
1823
- const contextWindow = getContextWindow(this.model, {
1824
- provider: this.provider,
1825
- accountId: creds.accountId,
1826
- });
1827
- const policy = resolveCompactionPolicy({
1828
- provider: this.provider,
1829
- model: this.model,
1830
- contextWindow,
1831
- threshold: this.settingsManager.get("compactThreshold"),
1832
- accountId: creds.accountId,
1833
- approvedPlanPath: this.approvedPlanPath,
1834
- });
1835
- let activeTokens;
1836
- if (this.providerContext) {
1837
- const anchorIndex = this.messages.lastIndexOf(this.providerContext.anchor);
1838
- if (anchorIndex >= 0) {
1839
- activeTokens = calculateActiveContextTokens(this.messages, {
1840
- usage: this.providerContext.usage,
1841
- pendingMessages: this.messages.slice(anchorIndex + 1),
1842
- });
1843
- }
1844
- else {
1845
- this.providerContext = null;
1846
- }
1847
- }
1848
- log("INFO", "compaction", "Pre-run compaction decision", {
1849
- provider: this.provider,
1850
- model: this.model,
1851
- transport: this.provider === "openai" && creds.accountId ? "codex_oauth" : "public_api",
1852
- contextWindow: String(contextWindow),
1853
- activeTokens: activeTokens === undefined ? "estimated" : String(activeTokens),
1854
- triggerLimit: String(policy.targetTokens),
1855
- });
1856
- if (shouldCompact(this.messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens)) {
1857
- try {
1858
- await this.compact(creds, "automatic");
1859
- if (this.lastCompactionCompacted) {
1860
- // Re-grounding hook keys off this — the context was just summarized.
1861
- this.compactionOccurred = true;
1862
- this.compactionRetryAfter = 0;
1863
- }
1864
- else {
1865
- this.compactionRetryAfter = Date.now() + 30_000;
1866
- }
1867
- }
1868
- catch (error) {
1869
- this.compactionRetryAfter = Date.now() + 30_000;
1870
- if (isAbortError(error) || this.opts.signal?.aborted)
1871
- throw error;
1872
- log("WARN", "compaction", `Pre-run compaction failed; cooling down for 30s: ${error instanceof Error ? error.message : String(error)}`);
1873
- }
1874
- }
1875
- }
1876
- // Reassigned when Anthropic rejects the turn for being below a model's
1877
- // minimum Claude Code version; the retry below rebuilds it from the floor
1878
- // that rejection taught us. The anthropic client cache is keyed on the UA,
1879
- // so the new value transparently yields a correctly-identified client.
1880
- let userAgent = this.provider === "anthropic" ? await getClaudeCliUserAgent() : undefined;
2370
+ // of the public API model window.
2371
+ await this.maybeCompactPreRun(creds);
2372
+ const userAgent = this.provider === "anthropic" ? await getClaudeCliUserAgent() : undefined;
1881
2373
  const loopMessages = await this.prepareDynamicContext();
1882
2374
  // Re-read every run so rule-file edits apply on the next turn; a few small files.
1883
2375
  const streamRules = await loadStreamRules(this.cwd);
@@ -1890,6 +2382,7 @@ export class AgentSession {
1890
2382
  provider: this.provider,
1891
2383
  model: this.model,
1892
2384
  tools: options.disableTools ? [] : this.tools,
2385
+ ...(options.disableTools ? {} : { deferredTools: this.deferredToolCatalog }),
1893
2386
  webSearch: options.disableTools ? false : () => this.nativeWebSearchOn(),
1894
2387
  maxTokens: this.requestMaxTokens(accountId),
1895
2388
  maxTurns: this.opts.maxTurns,
@@ -1902,6 +2395,7 @@ export class AgentSession {
1902
2395
  thinking: this.planModeRef.current || options.capThinking
1903
2396
  ? clampThinkingForPlanMode(this.thinkingLevel)
1904
2397
  : this.thinkingLevel,
2398
+ ...(modelInfo?.thinkingLevels ? { thinkingLevels: modelInfo.thinkingLevels } : {}),
1905
2399
  apiKey,
1906
2400
  // Per-turn credential resolution. A run can span many minutes; if any
1907
2401
  // process sharing auth.json refreshes this grant meanwhile, the token
@@ -1952,10 +2446,15 @@ export class AgentSession {
1952
2446
  promptCacheKey: this.getPromptCacheKey(),
1953
2447
  },
1954
2448
  });
1955
- log("INFO", "cache", "Prepared context", {
1956
- sessionId: this.sessionId || this.transportSessionId,
1957
- data: JSON.stringify(report),
1958
- });
2449
+ // "Context cache outcome" (persistTurnMetric) repeats this whole report
2450
+ // with usage attached, so only log the prepared report on its own when
2451
+ // it carries a cache-relevant change or risk worth seeing pre-response.
2452
+ if (report.changes.length > 0 || report.thinkingPrefixRiskBlocks > 0) {
2453
+ log("INFO", "cache", "Prepared context", {
2454
+ sessionId: this.sessionId || this.transportSessionId,
2455
+ data: JSON.stringify(report),
2456
+ });
2457
+ }
1959
2458
  if (report.thinkingPrefixRiskBlocks > 0) {
1960
2459
  log("WARN", "cache", "Possible signed-thinking prefix mismatch; not server verified", {
1961
2460
  sessionId: this.sessionId || this.transportSessionId,
@@ -2018,6 +2517,7 @@ export class AgentSession {
2018
2517
  model: this.model,
2019
2518
  contextWindow,
2020
2519
  threshold: this.settingsManager.get("compactThreshold"),
2520
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
2021
2521
  accountId,
2022
2522
  approvedPlanPath: this.approvedPlanPath,
2023
2523
  });
@@ -2044,7 +2544,10 @@ export class AgentSession {
2044
2544
  // anchors; drop the retained usage afterwards since it counted the
2045
2545
  // pruned content.
2046
2546
  if (shouldPruneToolResults(activeTokens, policy.targetTokens)) {
2047
- const pruneResult = pruneStaleToolResults(messages);
2547
+ const cacheCold = this.getCacheExpiryStatus()?.expired ?? false;
2548
+ const pruneResult = pruneStaleToolResults(messages, {
2549
+ minimumTokens: pruneMinimumTokens(activeTokens, cacheCold, policy.targetTokens),
2550
+ });
2048
2551
  if (pruneResult.pruned) {
2049
2552
  this.cacheDiagnostics.noteEdit("tool_prune", pruneResult.freedTokens);
2050
2553
  this.providerContext = null;
@@ -2067,6 +2570,8 @@ export class AgentSession {
2067
2570
  // An approved plan runs as ONE run, so step boundaries are only
2068
2571
  // visible here, between model steps — not after the run ends.
2069
2572
  const planStep = this.observePlanStepProgress(messages, contextWindow, activeTokens);
2573
+ // The decision line carries the outcome (compact=) next to its inputs.
2574
+ const overLimit = shouldCompact(messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens);
2070
2575
  log("INFO", "compaction", "In-flight compaction decision", {
2071
2576
  provider: this.provider,
2072
2577
  model: this.model,
@@ -2074,10 +2579,10 @@ export class AgentSession {
2074
2579
  contextWindow: String(contextWindow),
2075
2580
  activeTokens: String(activeTokens),
2076
2581
  triggerLimit: String(policy.targetTokens),
2582
+ compact: String(overLimit || Boolean(planStep?.compact)),
2077
2583
  ...(planStep ? { planStep: `${planStep.compact} (${planStep.reason})` } : {}),
2078
2584
  });
2079
- if (!shouldCompact(messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens) &&
2080
- !planStep?.compact)
2585
+ if (!overLimit && !planStep?.compact)
2081
2586
  return messages;
2082
2587
  }
2083
2588
  // compact() operates on this.messages, while an earlier transform may
@@ -2119,6 +2624,7 @@ export class AgentSession {
2119
2624
  }
2120
2625
  finally {
2121
2626
  this.activeLoopMessages = null;
2627
+ this.settleDeliveredMessages(() => true);
2122
2628
  // An in-flight compaction rebinds `this.messages` to the compacted array
2123
2629
  // while the loop keeps appending to `loopMessages`. Resync on every exit
2124
2630
  // — a failed or aborted run included — or the session silently drops
@@ -2136,8 +2642,9 @@ export class AgentSession {
2136
2642
  // fallback key, not the model's first preference).
2137
2643
  const badKey = (await this.authStorage.pickStorageKey(this.currentAuthStorageKeys())) ??
2138
2644
  this.currentAuthStorageKeys()[0];
2139
- log("WARN", "auth", `Got 401 for ${this.provider} (${badKey}) — API key is invalid or revoked`);
2140
- await this.authStorage.clearCredentials(badKey);
2645
+ const cleared = await this.authStorage.clearRejectedApiKey(badKey);
2646
+ log("WARN", "auth", `Got 401 for ${this.provider} (${badKey}) — ` +
2647
+ (cleared ? "API key is invalid or revoked" : "key rejected, kept on file"));
2141
2648
  return true;
2142
2649
  };
2143
2650
  try {
@@ -2198,17 +2705,22 @@ export class AgentSession {
2198
2705
  throw fallbackErr;
2199
2706
  }
2200
2707
  }
2201
- else if (this.provider === "anthropic" &&
2202
- err instanceof ProviderError &&
2203
- recordRequiredClaudeCodeVersion(err.message)) {
2204
- // Anthropic gates newly released models on a minimum Claude Code
2205
- // version and names it in the rejection. That message is more current
2206
- // than the npm registry can be at launch, so the floor it just taught
2207
- // us is authoritative: rebuild the spoofed User-Agent from it and retry
2208
- // this turn instead of making the user wait out a cache TTL.
2209
- userAgent = await getClaudeCliUserAgent();
2210
- log("INFO", "auth", `Retrying turn as ${userAgent}`);
2211
- await runAgentLoop(creds.accessToken, creds.accountId, creds.projectId);
2708
+ else if (err instanceof ProviderError &&
2709
+ err.statusCode === 401 &&
2710
+ !this.baseUrl &&
2711
+ (await this.authStorage.relocateRegionalApiKey(this.currentAuthStorageKeys()))) {
2712
+ // The key was valid all along, just sent to another region's cluster.
2713
+ creds = await this.authStorage.resolveCredentials(this.provider, {
2714
+ storageKeys: this.currentAuthStorageKeys(),
2715
+ });
2716
+ this.lastAccountId = creds.accountId;
2717
+ try {
2718
+ await runAgentLoop(creds.accessToken, creds.accountId, creds.projectId);
2719
+ }
2720
+ catch (retryErr) {
2721
+ await clearInvalidStaticApiKey(retryErr);
2722
+ throw retryErr;
2723
+ }
2212
2724
  }
2213
2725
  else if (err instanceof ProviderError && err.statusCode === 401) {
2214
2726
  // Static API-key providers (GLM, Moonshot API key, etc.) have no refresh
@@ -2283,6 +2795,8 @@ export class AgentSession {
2283
2795
  // booted on e.g. Kimi (256K) keeps sending that cap after switching to a
2284
2796
  // smaller model (Opus 128K), which the provider rejects.
2285
2797
  this.maxTokens = this.resolveMaxTokens(model);
2798
+ if (changed)
2799
+ this.preconnect();
2286
2800
  this.eventBus.emit("model_change", {
2287
2801
  provider: this.provider,
2288
2802
  model: this.model,
@@ -2320,25 +2834,15 @@ export class AgentSession {
2320
2834
  }
2321
2835
  // Update provider-specific tools when provider changes
2322
2836
  if (provider && provider !== prevProvider) {
2323
- // Add/remove client-side web_search tool based on provider.
2324
- // Anthropic has native server-side web search; all other providers need the client tool.
2837
+ // The client web_search tool serves every provider (on Anthropic it
2838
+ // runs the native search as a side request), so a switch only adds it
2839
+ // when an untiered session lacks it.
2325
2840
  const hasWebSearch = this.tools.some((t) => t.name === "web_search");
2326
- if (this.deferredBuiltinToolNames.includes("web_search")) {
2327
- // Tiered: the client tool lives in the catalog for every provider and,
2328
- // once promoted, is swapped for the native server tool by the Anthropic
2329
- // transport. Nothing to add or remove — doing so would either load the
2330
- // schema eagerly or take away a capability the model already has.
2331
- }
2332
- else if (this.provider === "anthropic" && hasWebSearch) {
2333
- // Switching TO anthropic — remove client-side web_search (server-side handles it)
2334
- this.tools = this.tools.filter((t) => t.name !== "web_search");
2335
- }
2336
- else if (this.provider !== "anthropic" && !hasWebSearch) {
2337
- // Switching FROM anthropic — add client-side web_search
2841
+ if (!this.deferredBuiltinToolNames.includes("web_search") && !hasWebSearch) {
2338
2842
  this.tools.push(createWebSearchTool(() => ({
2339
2843
  mode: this.settingsManager.get("networkMode"),
2340
2844
  allow: this.settingsManager.get("networkAllow"),
2341
- })));
2845
+ }), (request) => this.runSideWebSearch(request)));
2342
2846
  }
2343
2847
  // Reconnect MCP servers ONLY when GLM is involved on either side — GLM
2344
2848
  // is the only provider with a different server set (Z.AI tools), so a
@@ -2368,11 +2872,13 @@ export class AgentSession {
2368
2872
  const servers = await getAllMcpServers(this.provider, apiKey, this.cwd, {
2369
2873
  allowProjectScope: this.settingsManager.isProjectTrusted(this.cwd),
2370
2874
  });
2371
- const mcpTools = await mcpManager.connectAll(servers);
2875
+ const results = await mcpManager.connectAllDetailed(servers);
2876
+ const mcpTools = results.flatMap((r) => r.tools);
2372
2877
  // Drop stale MCP tools from both the live set and deferred catalog before
2373
2878
  // re-adding. Some tools may already have been promoted out of the catalog.
2374
2879
  this.tools = this.tools.filter((t) => !t.name.startsWith("mcp__"));
2375
2880
  this.mcp.clearMcpTools();
2881
+ this.mcp.recordServers(servers, results);
2376
2882
  this.addMcpTools(mcpTools);
2377
2883
  }
2378
2884
  catch (err) {
@@ -2592,7 +3098,7 @@ export class AgentSession {
2592
3098
  return;
2593
3099
  const contextWindow = getContextWindow(this.model, {
2594
3100
  provider: this.provider,
2595
- accountId: creds.accountId,
3101
+ accountId: creds?.accountId,
2596
3102
  });
2597
3103
  // One compaction per turn boundary: a pre-run, in-flight or overflow
2598
3104
  // compaction already shrank this run's history — re-probing right after
@@ -2607,7 +3113,8 @@ export class AgentSession {
2607
3113
  model: this.model,
2608
3114
  contextWindow,
2609
3115
  threshold: this.settingsManager.get("compactThreshold"),
2610
- accountId: creds.accountId,
3116
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
3117
+ accountId: creds?.accountId,
2611
3118
  approvedPlanPath: this.approvedPlanPath,
2612
3119
  });
2613
3120
  let activeTokens;
@@ -2628,14 +3135,16 @@ export class AgentSession {
2628
3135
  trigger: planStep?.compact ? `plan-step (${planStep.reason})` : "size",
2629
3136
  provider: this.provider,
2630
3137
  model: this.model,
2631
- transport: this.provider === "openai" && creds.accountId ? "codex_oauth" : "public_api",
3138
+ transport: this.compactionTransport(creds),
2632
3139
  contextWindow: String(contextWindow),
2633
3140
  activeTokens: activeTokens === undefined ? "estimated" : String(activeTokens),
2634
3141
  triggerLimit: String(policy.targetTokens),
2635
3142
  });
3143
+ const postTurnAbort = new AbortController();
3144
+ this.postTurnCompactionAbort = postTurnAbort;
2636
3145
  this.postTurnCompaction = (async () => {
2637
3146
  try {
2638
- await this.compact(creds, "automatic");
3147
+ await this.compact(creds, "automatic", undefined, postTurnAbort.signal);
2639
3148
  if (this.lastCompactionCompacted) {
2640
3149
  // Arm re-grounding for the next turn. resetHookState clears
2641
3150
  // compactionOccurred at run start, before the injection point, so
@@ -2655,17 +3164,40 @@ export class AgentSession {
2655
3164
  }
2656
3165
  finally {
2657
3166
  this.postTurnCompaction = undefined;
3167
+ if (this.postTurnCompactionAbort === postTurnAbort)
3168
+ this.postTurnCompactionAbort = undefined;
2658
3169
  }
2659
3170
  })();
2660
3171
  }
3172
+ // A caller's token was captured at run start; the loop may have rotated it since.
3173
+ async withLiveAccessToken(captured) {
3174
+ try {
3175
+ const live = await this.authStorage.resolveCredentials(this.provider, {
3176
+ storageKeys: this.currentAuthStorageKeys(),
3177
+ });
3178
+ return { ...captured, accessToken: live.accessToken };
3179
+ }
3180
+ catch {
3181
+ return captured;
3182
+ }
3183
+ }
2661
3184
  async compact(existingCredentials, mode = "manual",
2662
3185
  /** User-stated focus (`/compact <focus>`): what must survive verbatim. */
2663
- focus) {
3186
+ focus,
3187
+ /** Extra abort source (post-turn compaction, cancelled by dispose). */
3188
+ abortSignal) {
2664
3189
  this.lastCompactionCompacted = false;
2665
- const creds = existingCredentials ??
2666
- (await this.authStorage.resolveCredentials(this.provider, {
2667
- storageKeys: this.currentAuthStorageKeys(),
2668
- }));
3190
+ const compactionSignal = abortSignal && this.opts.signal
3191
+ ? AbortSignal.any([this.opts.signal, abortSignal])
3192
+ : (abortSignal ?? this.opts.signal);
3193
+ const claudeCode = existingCredentials ? null : await this.claudeCodeProcess();
3194
+ const creds = existingCredentials
3195
+ ? await this.withLiveAccessToken(existingCredentials)
3196
+ : claudeCode
3197
+ ? { accessToken: "" }
3198
+ : await this.authStorage.resolveCredentials(this.provider, {
3199
+ storageKeys: this.currentAuthStorageKeys(),
3200
+ });
2669
3201
  const contextWindow = getContextWindow(this.model, {
2670
3202
  provider: this.provider,
2671
3203
  accountId: creds.accountId,
@@ -2675,6 +3207,7 @@ export class AgentSession {
2675
3207
  model: this.model,
2676
3208
  contextWindow,
2677
3209
  threshold: this.settingsManager.get("compactThreshold"),
3210
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
2678
3211
  accountId: creds.accountId,
2679
3212
  approvedPlanPath: this.approvedPlanPath,
2680
3213
  });
@@ -2692,9 +3225,14 @@ export class AgentSession {
2692
3225
  baseUrl: this.baseUrl ?? creds.baseUrl,
2693
3226
  contextWindow,
2694
3227
  targetTokens: policy.targetTokens,
2695
- signal: this.opts.signal,
3228
+ signal: compactionSignal,
2696
3229
  approvedPlanPath: this.approvedPlanPath,
2697
3230
  focus,
3231
+ ...(claudeCode
3232
+ ? {
3233
+ complete: (req) => claudeCodeComplete({ ...claudeCode, ...req }),
3234
+ }
3235
+ : {}),
2698
3236
  });
2699
3237
  contextSelection = output.result.contextSelection;
2700
3238
  return output;
@@ -2713,7 +3251,7 @@ export class AgentSession {
2713
3251
  }
2714
3252
  else {
2715
3253
  const conversationId = this.conversationId;
2716
- await this.sessionManager.withCompactionLease(conversationId, this.opts.signal, async () => {
3254
+ await this.sessionManager.withCompactionLease(conversationId, compactionSignal, async () => {
2717
3255
  let sourceFingerprint = computeSourceFingerprint(this.messages);
2718
3256
  const canonicalPath = await this.sessionManager.resolveCanonicalSession(conversationId, this.cwd);
2719
3257
  if (canonicalPath && canonicalPath !== this.sessionPath) {
@@ -2819,6 +3357,7 @@ export class AgentSession {
2819
3357
  // into the fresh session (e.g. an accepted plan's build would inherit the
2820
3358
  // whole planning conversation and lose the approved-plan prompt).
2821
3359
  await this.settlePostTurnCompaction();
3360
+ this.closeClaudeCodeLive("new session");
2822
3361
  this.cacheDiagnostics.reset();
2823
3362
  // Approved-plan execution is a clean checkpoint of the same conversation;
2824
3363
  // explicit new sessions reset the conversation identity.
@@ -2866,6 +3405,7 @@ export class AgentSession {
2866
3405
  this.eventBus.emit("session_start", { sessionId: this.sessionId });
2867
3406
  }
2868
3407
  async loadSession(sessionPath) {
3408
+ this.closeClaudeCodeLive("session loaded");
2869
3409
  await this.loadExistingSession(sessionPath);
2870
3410
  this.cacheDiagnostics.reset();
2871
3411
  if (this.sessionId)
@@ -2919,6 +3459,10 @@ export class AgentSession {
2919
3459
  this.setSessionPath(loaded.path);
2920
3460
  return this.sessionManager.listBranches(loaded.entries);
2921
3461
  }
3462
+ /** The session's first user-authored prompt, or "" before there is one. */
3463
+ getSessionPreview() {
3464
+ return this.sessionPreview;
3465
+ }
2922
3466
  /** Skills the safety scan kept out of this session, for the app/CLI to show. */
2923
3467
  getBlockedSkills() {
2924
3468
  return this.blockedSkills;
@@ -3106,17 +3650,57 @@ export class AgentSession {
3106
3650
  /** Queue a user message (optionally with attachments) to be injected mid-run
3107
3651
  * as steering. Returns the new queue length. No-op semantics are the caller's
3108
3652
  * concern. */
3109
- queueMessage(text, attachments = []) {
3653
+ queueMessage(text, attachments = [], opts = {}) {
3110
3654
  this.queueSeq += 1;
3111
- this.userQueue.push({ id: `q${this.queueSeq}`, text, attachments });
3655
+ this.userQueue.push({
3656
+ id: `q${this.queueSeq}`,
3657
+ text,
3658
+ attachments,
3659
+ ...(opts.answeredAsk ? { answeredAsk: true } : {}),
3660
+ });
3112
3661
  // Instant interrupt: preempt running tools so the steer lands right away.
3113
3662
  for (const listener of [...this.steeringListeners])
3114
3663
  listener();
3115
3664
  return this.userQueue.length;
3116
3665
  }
3117
- /** Pending queued messages (id + text), oldest first, for client display. */
3666
+ /**
3667
+ * Hold the output of a command the user ran themselves (`!cmd` in the app)
3668
+ * so it reaches the agent with their next message: a prompt, or a message
3669
+ * queued as steering. Never on its own, and never mid-run without one.
3670
+ */
3671
+ addUserShellContext(runId, text) {
3672
+ if (text.trim())
3673
+ this.pendingUserShell.push({ runId, text });
3674
+ }
3675
+ /** Run ids of user commands still waiting for the next message. */
3676
+ getPendingUserShellRunIds() {
3677
+ return this.pendingUserShell.map((entry) => entry.runId);
3678
+ }
3679
+ takeUserShellContext() {
3680
+ if (this.pendingUserShell.length === 0)
3681
+ return null;
3682
+ const blocks = this.pendingUserShell.splice(0).map((entry) => entry.text);
3683
+ return {
3684
+ role: "user",
3685
+ content: buildUserShellContextText(blocks),
3686
+ provenance: { source: "runtime", kind: "notification", visibility: "hidden" },
3687
+ };
3688
+ }
3689
+ /** Persist pending user command output just ahead of the human message. */
3690
+ async deliverUserShellContext() {
3691
+ const message = this.takeUserShellContext();
3692
+ if (!message)
3693
+ return;
3694
+ this.messages.push(message);
3695
+ await this.persistMessage(message);
3696
+ }
3697
+ /** Pending queued messages (id + text), oldest first, for client display.
3698
+ * `delivering` ones are already with the agent and can no longer be cancelled. */
3118
3699
  listQueuedMessages() {
3119
- return this.userQueue.map((m) => ({ id: m.id, text: m.text }));
3700
+ return [
3701
+ ...this.deliveringQueue.map((m) => ({ id: m.id, text: m.text, delivering: true })),
3702
+ ...this.userQueue.map((m) => ({ id: m.id, text: m.text })),
3703
+ ];
3120
3704
  }
3121
3705
  /** Cancel one pending message by id. Returns true if it was still queued.
3122
3706
  * A false return is the normal race rather than an error: the message drained
@@ -3253,6 +3837,8 @@ export class AgentSession {
3253
3837
  */
3254
3838
  stopBackgroundProcesses() {
3255
3839
  this.processManager?.shutdownAll();
3840
+ // Synchronous, so app quit stops Claude Code even when later teardown hangs.
3841
+ this.closeClaudeCodeLive("shutdown");
3256
3842
  }
3257
3843
  /** Replace a host-owned system prompt in place without resetting conversation history. */
3258
3844
  setCustomSystemPrompt(systemPrompt, promptCacheKeyPrefix) {
@@ -3286,7 +3872,7 @@ export class AgentSession {
3286
3872
  // is about to be drafted); exiting keeps it (set explicitly via accept).
3287
3873
  if (active)
3288
3874
  this.approvedPlanPath = undefined;
3289
- await this.rebuildSystemPromptInPlace();
3875
+ await this.applyPlanStateChange();
3290
3876
  }
3291
3877
  /**
3292
3878
  * Bake an approved plan into the system prompt so the model is told to emit
@@ -3296,7 +3882,48 @@ export class AgentSession {
3296
3882
  */
3297
3883
  async setApprovedPlan(approvedPlanPath) {
3298
3884
  this.approvedPlanPath = approvedPlanPath;
3299
- await this.rebuildSystemPromptInPlace();
3885
+ await this.applyPlanStateChange();
3886
+ }
3887
+ /**
3888
+ * Before the conversation starts, render plan state into the prompt. After,
3889
+ * the prompt is a cached prefix: queue an appended notice instead, so the
3890
+ * cached bytes stay identical (a rebuild re-sent the whole history).
3891
+ */
3892
+ async applyPlanStateChange() {
3893
+ if (this.customSystemPrompt || this.agentPrompt !== undefined)
3894
+ return;
3895
+ if (!this.messages.some((message) => message.role !== "system")) {
3896
+ this.pendingPlanNotice = null;
3897
+ await this.rebuildSystemPromptInPlace();
3898
+ return;
3899
+ }
3900
+ const state = {
3901
+ planMode: this.planModeRef.current,
3902
+ approvedPlanPath: this.approvedPlanPath,
3903
+ };
3904
+ const message = await buildPlanStateMessage(this.seenPlanState, state, [
3905
+ ...this.tools.map((t) => t.name),
3906
+ ...this.deferredBuiltinToolNames,
3907
+ ]);
3908
+ this.pendingPlanNotice = message ? { message, state } : null;
3909
+ }
3910
+ /** The plan notice to append now, if any (pending, or a compacted-away one). */
3911
+ takePlanNotice() {
3912
+ if (this.pendingPlanNotice) {
3913
+ const { message, state } = this.pendingPlanNotice;
3914
+ this.pendingPlanNotice = null;
3915
+ this.seenPlanState = state;
3916
+ this.lastPlanNotice = message;
3917
+ return message;
3918
+ }
3919
+ if (this.lastPlanNotice &&
3920
+ !samePlanState(this.seenPlanState, this.promptPlanState) &&
3921
+ !this.messages.includes(this.lastPlanNotice)) {
3922
+ const again = { ...this.lastPlanNotice };
3923
+ this.lastPlanNotice = again;
3924
+ return again;
3925
+ }
3926
+ return null;
3300
3927
  }
3301
3928
  /** Extra workspace roots added with `/add-dir`, in the order added. */
3302
3929
  getAdditionalRoots() {
@@ -3406,10 +4033,15 @@ export class AgentSession {
3406
4033
  return this.customSystemPrompt;
3407
4034
  // Listed once: a rebuild (plan mode, /add-dir, compaction) must not churn the
3408
4035
  // prompt as the agent adds files.
3409
- if (this.projectFiles === undefined)
3410
- this.projectFiles = await listProjectFiles(this.cwd);
4036
+ if (this.projectFiles === undefined) {
4037
+ const pending = this.projectFilesPending;
4038
+ this.projectFilesPending = undefined;
4039
+ this.projectFiles = await (pending ?? listProjectFiles(this.cwd));
4040
+ }
3411
4041
  const toolNames = this.tools.map((tool) => tool.name);
3412
4042
  const deferredToolNames = this.deferredToolNamesForPrompt(toolNames);
4043
+ // A missing Claude Code binary fails the run itself with a clear message, not the prompt build.
4044
+ const deferredNeedSearch = deferredToolNames.length > 0 && (await this.claudeCodeProcess().then(Boolean, () => false));
3413
4045
  // Whatever is rendered now is what the model has been told.
3414
4046
  this.announcedLanguages = new Set(this.activeLanguages);
3415
4047
  if (this.agentPrompt !== undefined) {
@@ -3417,6 +4049,7 @@ export class AgentSession {
3417
4049
  cwd: this.cwd,
3418
4050
  toolNames,
3419
4051
  deferredToolNames,
4052
+ deferredNeedSearch,
3420
4053
  context: this.opts.agentContext,
3421
4054
  role: this.opts.agentRole,
3422
4055
  environment: this.recordRenderedEnvironment(),
@@ -3424,7 +4057,7 @@ export class AgentSession {
3424
4057
  ...(this.languagesApply() ? { activeLanguages: this.activeLanguages } : {}),
3425
4058
  });
3426
4059
  }
3427
- return buildSystemPrompt(this.cwd, this.skills, planMode, approvedPlanPath, toolNames, this.activeLanguages, this.provider, this.recordRenderedEnvironment(), deferredToolNames, this.contextLimits);
4060
+ return buildSystemPrompt(this.cwd, this.skills, planMode, approvedPlanPath, toolNames, this.activeLanguages, this.provider, this.recordRenderedEnvironment(), deferredToolNames, this.contextLimits, undefined, deferredNeedSearch);
3428
4061
  }
3429
4062
  /**
3430
4063
  * Bring the system prompt to the exact state the next provider request will
@@ -3445,7 +4078,7 @@ export class AgentSession {
3445
4078
  return this.messages.some((m) => m.role === "assistant");
3446
4079
  }
3447
4080
  /**
3448
- * Give the model style packs for languages that appeared after its prompt
4081
+ * Give the model verify commands for languages that appeared after its prompt
3449
4082
  * was cached (e.g. the previous task scaffolded a TypeScript project), as a
3450
4083
  * hidden message appended to the history rather than a prompt re-render that
3451
4084
  * would throw away the whole cache. Runs just before a new user message is
@@ -3453,6 +4086,19 @@ export class AgentSession {
3453
4086
  * update is saved in order with the rest of the conversation.
3454
4087
  */
3455
4088
  async announceNewLanguages() {
4089
+ const mcpNotice = this.takeMcpNotice();
4090
+ if (mcpNotice) {
4091
+ this.messages.push(mcpNotice);
4092
+ await this.persistMessage(mcpNotice);
4093
+ this.lastPersistedIndex = this.messages.length;
4094
+ }
4095
+ const planNotice = this.takePlanNotice();
4096
+ if (planNotice) {
4097
+ this.messages.push(planNotice);
4098
+ await this.persistMessage(planNotice);
4099
+ this.lastPersistedIndex = this.messages.length;
4100
+ log("INFO", "session", "Appended plan state update instead of rebuilding the prompt");
4101
+ }
3456
4102
  if (!this.hasReply())
3457
4103
  return; // the next request rebuilds the prompt instead
3458
4104
  this.refreshActiveLanguages();
@@ -3467,7 +4113,7 @@ export class AgentSession {
3467
4113
  this.messages.push(update);
3468
4114
  await this.persistMessage(update);
3469
4115
  this.lastPersistedIndex = this.messages.length;
3470
- log("INFO", "language", "Appended style packs for new languages", {
4116
+ log("INFO", "language", "Appended verify commands for new languages", {
3471
4117
  added: [...fresh].join(","),
3472
4118
  });
3473
4119
  }
@@ -3503,7 +4149,7 @@ export class AgentSession {
3503
4149
  return false;
3504
4150
  }
3505
4151
  if (grew) {
3506
- log("INFO", "language", "Style packs active", {
4152
+ log("INFO", "language", "Languages active", {
3507
4153
  active: [...this.activeLanguages].join(","),
3508
4154
  });
3509
4155
  }
@@ -3518,6 +4164,13 @@ export class AgentSession {
3518
4164
  return;
3519
4165
  const rebuilt = await this.buildBasePrompt(this.planModeRef.current, this.approvedPlanPath);
3520
4166
  this.baseSystemPrompt = rebuilt;
4167
+ this.promptPlanState = {
4168
+ planMode: this.planModeRef.current,
4169
+ approvedPlanPath: this.approvedPlanPath,
4170
+ };
4171
+ this.seenPlanState = this.promptPlanState;
4172
+ this.pendingPlanNotice = null;
4173
+ this.lastPlanNotice = null;
3521
4174
  const content = this.withSystemPromptTail(rebuilt);
3522
4175
  if (this.messages[0]?.role === "system") {
3523
4176
  this.messages[0] = { role: "system", content };
@@ -3740,6 +4393,7 @@ export class AgentSession {
3740
4393
  generation,
3741
4394
  startedAt: new Date().toISOString(),
3742
4395
  afterMessageCount: this.persistedTranscriptCount(),
4396
+ pid: process.pid,
3743
4397
  });
3744
4398
  }
3745
4399
  /** Close the run journal. Its absence is what marks a run as crashed. */
@@ -3766,9 +4420,12 @@ export class AgentSession {
3766
4420
  // if the user switches models while credential resolution is pending.
3767
4421
  const { provider, model, thinkingLevel, baseUrl } = this;
3768
4422
  const threshold = this.settingsManager.get("compactThreshold");
3769
- const creds = await this.authStorage.resolveCredentials(provider, {
3770
- storageKeys: this.currentAuthStorageKeys(),
3771
- });
4423
+ const claudeCode = await this.claudeCodeProcess();
4424
+ const creds = claudeCode
4425
+ ? { accessToken: "" }
4426
+ : await this.authStorage.resolveCredentials(provider, {
4427
+ storageKeys: this.currentAuthStorageKeys(),
4428
+ });
3772
4429
  const maxTokens = outputCapForRequest({
3773
4430
  provider,
3774
4431
  model,
@@ -3798,6 +4455,17 @@ export class AgentSession {
3798
4455
  baseUrl: baseUrl ?? creds.baseUrl,
3799
4456
  accountId: creds.accountId,
3800
4457
  signal: this.opts.signal,
4458
+ ...(claudeCode
4459
+ ? {
4460
+ complete: (messages) => claudeCodeComplete({
4461
+ ...claudeCode,
4462
+ model,
4463
+ messages,
4464
+ thinking: thinkingLevel,
4465
+ signal: this.opts.signal,
4466
+ }),
4467
+ }
4468
+ : {}),
3801
4469
  });
3802
4470
  }
3803
4471
  /** Current reasoning/thinking level, or undefined when thinking is off. */
@@ -3825,7 +4493,45 @@ export class AgentSession {
3825
4493
  runLoopDepth = 0;
3826
4494
  lastRealRequestAt = 0;
3827
4495
  lastPrewarmAt = 0;
4496
+ /** Last connection pre-open per provider origin (see {@link preconnect}). */
4497
+ preconnectedAt = new Map();
4498
+ /**
4499
+ * Fire-and-forget: open the TLS connection to the active provider before the
4500
+ * first request, through the shared keep-alive pool. Zero tokens — an
4501
+ * unauthenticated HEAD; skipped for local endpoints and throttled per origin.
4502
+ * Transient sessions (one-shot tools) and test runs never touch the network here.
4503
+ */
4504
+ preconnect() {
4505
+ const enabled = this.opts.preconnect ?? (this.opts.transient !== true && !process.env.VITEST);
4506
+ if (!enabled)
4507
+ return;
4508
+ const provider = this.provider;
4509
+ void this.authStorage
4510
+ .resolveCredentials(provider, { storageKeys: this.currentAuthStorageKeys() })
4511
+ .then((creds) => {
4512
+ if (provider !== this.provider)
4513
+ return;
4514
+ preconnectProvider({
4515
+ provider,
4516
+ baseUrl: this.baseUrl ?? creds.baseUrl,
4517
+ accountId: creds.accountId,
4518
+ warmedAt: this.preconnectedAt,
4519
+ });
4520
+ })
4521
+ .catch(() => { });
4522
+ }
3828
4523
  prewarmController = null;
4524
+ /** Claude Code session that has seen this history (Claude subscription route). */
4525
+ claudeCodeSession = null;
4526
+ releaseClaudeCodeTranscript;
4527
+ /** Keep the retention pass off the transcript this chat would resume. */
4528
+ holdClaudeCodeTranscript() {
4529
+ this.releaseClaudeCodeTranscript?.();
4530
+ const sessionId = this.claudeCodeSession?.sessionId;
4531
+ this.releaseClaudeCodeTranscript = sessionId ? holdClaudeCodeTranscript(sessionId) : undefined;
4532
+ }
4533
+ /** This chat's running Claude Code process, reused while `key` (its start settings) matches. */
4534
+ claudeCodeLive = null;
3829
4535
  /**
3830
4536
  * Best-effort Anthropic prompt-cache prewarm before the user's next turn
3831
4537
  * (desktop app calls this on the first keystroke after opening a chat or an
@@ -3834,6 +4540,11 @@ export class AgentSession {
3834
4540
  * first real reply is a cache read instead of a cold write.
3835
4541
  */
3836
4542
  async prewarm(signal) {
4543
+ // Claude Code keeps its own cache; there is no request prefix of ours to warm.
4544
+ if (await this.claudeCodeProcess().catch(() => null))
4545
+ return { ok: false, reason: "claude_code" };
4546
+ // Every provider: the user is typing, so the first request is seconds away.
4547
+ this.preconnect();
3837
4548
  if (this.provider !== "anthropic")
3838
4549
  return { ok: false, reason: "provider" };
3839
4550
  if (this.settingsManager?.get("cachePrewarm") === false) {
@@ -3892,11 +4603,13 @@ export class AgentSession {
3892
4603
  model: this.model,
3893
4604
  messages,
3894
4605
  tools: this.tools,
4606
+ deferredTools: this.deferredToolCatalog,
3895
4607
  webSearch: this.nativeWebSearchOn(),
3896
4608
  maxTokens: this.requestMaxTokens(creds.accountId),
3897
4609
  thinking: this.planModeRef.current
3898
4610
  ? clampThinkingForPlanMode(this.thinkingLevel)
3899
4611
  : this.thinkingLevel,
4612
+ ...(modelInfo?.thinkingLevels ? { thinkingLevels: modelInfo.thinkingLevels } : {}),
3900
4613
  apiKey: creds.accessToken,
3901
4614
  baseUrl: this.baseUrl ?? creds.baseUrl,
3902
4615
  accountId: creds.accountId,
@@ -3989,12 +4702,24 @@ export class AgentSession {
3989
4702
  // step leaves background commands running after the app has quit.
3990
4703
  this.stopBackgroundProcesses();
3991
4704
  this.installedWatchStop?.();
4705
+ this.releaseClaudeCodeTranscript?.();
4706
+ this.releaseClaudeCodeTranscript = undefined;
3992
4707
  // Quiesce any in-flight post-turn compaction BEFORE tearing down state:
3993
4708
  // the background compact() snapshots and replaces `this.messages`, so
3994
4709
  // letting it run past this point would checkpoint a near-empty history
3995
4710
  // and leak a junk session file after teardown.
3996
- if (this.postTurnCompaction)
3997
- await this.postTurnCompaction;
4711
+ // Capped: a hung summary call must not hold MCP/LSP/sub-agent teardown and
4712
+ // window close hostage. Past the cap it is aborted (compact() checks the
4713
+ // signal before replacing history), with a short grace to unwind.
4714
+ if (this.postTurnCompaction) {
4715
+ const pending = this.postTurnCompaction;
4716
+ const settledInTime = await settleWithin(pending, DISPOSE_COMPACTION_WAIT_MS);
4717
+ if (!settledInTime) {
4718
+ log("WARN", "compaction", "Post-turn compaction still running at dispose — aborting");
4719
+ this.postTurnCompactionAbort?.abort();
4720
+ await settleWithin(pending, DISPOSE_COMPACTION_ABORT_GRACE_MS);
4721
+ }
4722
+ }
3998
4723
  this.cacheDiagnostics.reset();
3999
4724
  this.diagnosticsRecorder?.finalize();
4000
4725
  this.managerAbortSignal?.removeEventListener("abort", this.managerAbortHandler);
@@ -4043,14 +4768,28 @@ export class AgentSession {
4043
4768
  : await this.sessionManager.load(sessionPath);
4044
4769
  // Use the leaf from the header to walk the correct branch
4045
4770
  const loadedMessages = this.sessionManager.getMessages(loaded.entries, loaded.header.leafId);
4046
- const savedCompletionReview = [...loaded.entries]
4047
- .reverse()
4048
- .find((entry) => entry.type === "custom" && entry.kind === COMPLETION_REVIEW_STATE_KIND);
4771
+ // One backward scan for both latest host checkpoints (no full copies).
4772
+ let savedCompletionReview;
4773
+ let savedVerification;
4774
+ let savedClaudeCode;
4775
+ for (let i = loaded.entries.length - 1; i >= 0; i--) {
4776
+ if (savedCompletionReview && savedVerification && savedClaudeCode)
4777
+ break;
4778
+ const entry = loaded.entries[i];
4779
+ if (entry?.type !== "custom")
4780
+ continue;
4781
+ if (!savedClaudeCode && entry.kind === CLAUDE_CODE_SESSION_KIND) {
4782
+ savedClaudeCode = entry;
4783
+ }
4784
+ else if (!savedCompletionReview && entry.kind === COMPLETION_REVIEW_STATE_KIND) {
4785
+ savedCompletionReview = entry;
4786
+ }
4787
+ else if (!savedVerification && entry.kind === VERIFICATION_STATE_KIND) {
4788
+ savedVerification = entry;
4789
+ }
4790
+ }
4049
4791
  this.opts.completionReview?.restore(savedCompletionReview?.type === "custom" ? savedCompletionReview.data : null);
4050
4792
  this.verificationTracker.clearBackground();
4051
- const savedVerification = [...loaded.entries]
4052
- .reverse()
4053
- .find((entry) => entry.type === "custom" && entry.kind === VERIFICATION_STATE_KIND);
4054
4793
  if (savedVerification?.type === "custom") {
4055
4794
  this.verificationGate.restore(savedVerification.data);
4056
4795
  }
@@ -4090,6 +4829,9 @@ export class AgentSession {
4090
4829
  // not fail when Anthropic's stricter many-image limit activates later.
4091
4830
  const systemMsg = this.messages[0]; // Already built
4092
4831
  this.messages = [systemMsg, ...loadedMessages];
4832
+ this.reloadUsedTools(loadedMessages);
4833
+ this.claudeCodeSession = parseClaudeCodeSessionState(savedClaudeCode?.type === "custom" ? savedClaudeCode.data : null, loadedMessages);
4834
+ this.holdClaudeCodeTranscript();
4093
4835
  // Reads recorded for the previous conversation don't carry over.
4094
4836
  this.clearReadTracker?.();
4095
4837
  const normalizedImageCount = await normalizeMessageImages(this.messages);
@@ -4129,6 +4871,7 @@ export class AgentSession {
4129
4871
  model: this.model,
4130
4872
  contextWindow,
4131
4873
  threshold: this.settingsManager.get("compactThreshold"),
4874
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
4132
4875
  accountId: creds?.accountId,
4133
4876
  approvedPlanPath: this.approvedPlanPath,
4134
4877
  });
@@ -4181,6 +4924,15 @@ export class AgentSession {
4181
4924
  */
4182
4925
  async recordInterruptedRuns(runs) {
4183
4926
  for (const run of runs) {
4927
+ // Another app has this chat open and is still running it: not a crash.
4928
+ if (run.pid !== undefined && run.pid !== process.pid && processIsAlive(run.pid)) {
4929
+ log("WARN", "session", "Unfinished run belongs to another live process; left open", {
4930
+ generation: String(run.generation),
4931
+ startedAt: run.startedAt,
4932
+ pid: String(run.pid),
4933
+ });
4934
+ continue;
4935
+ }
4184
4936
  log("WARN", "session", "Restored a session with an unfinished run", {
4185
4937
  generation: String(run.generation),
4186
4938
  startedAt: run.startedAt,
@@ -4235,7 +4987,9 @@ export class AgentSession {
4235
4987
  },
4236
4988
  getModelList: () => {
4237
4989
  const current = `Current: ${this.provider}:${this.model}\n\nAvailable models:\n`;
4238
- const list = MODELS.map((m) => ` ${m.provider}:${m.id} — ${m.name} (${m.costTier})`).join("\n");
4990
+ const list = getListedModels()
4991
+ .map((m) => ` ${m.provider}:${m.id} — ${m.name} (${m.costTier})`)
4992
+ .join("\n");
4239
4993
  return current + list;
4240
4994
  },
4241
4995
  quit: () => {