@prestyj/cli 5.32.1 → 5.33.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 (484) hide show
  1. package/assets/motion/skills/motion/SKILL.md +1 -1
  2. package/assets/skills/bulletproof/SKILL.md +72 -131
  3. package/assets/skills/bulletproof/references/agent-surface.md +22 -1
  4. package/assets/skills/bulletproof/references/audit-protocol.md +23 -6
  5. package/assets/skills/bulletproof/references/platform-playbooks.md +12 -0
  6. package/assets/skills/bulletproof/references/provenance.md +19 -2
  7. package/assets/skills/bulletproof/references/secure-defaults.md +13 -1
  8. package/assets/skills/bulletproof/references/supply-chain.md +8 -5
  9. package/assets/skills/bulletproof/references/threat-landscape.md +46 -57
  10. package/assets/skills/compliance-guard/SKILL.md +59 -212
  11. package/assets/skills/compliance-guard/references/artifacts.md +14 -1
  12. package/assets/skills/compliance-guard/references/eu-uk.md +17 -7
  13. package/assets/skills/compliance-guard/references/exposure-triage.md +16 -0
  14. package/assets/skills/compliance-guard/references/full-review.md +155 -0
  15. package/assets/skills/compliance-guard/references/lawsuit-vectors.md +14 -2
  16. package/assets/skills/compliance-guard/references/provenance.md +33 -2
  17. package/assets/skills/compliance-guard/references/sector-gates.md +15 -1
  18. package/assets/skills/compliance-guard/references/security-baseline.md +21 -34
  19. package/assets/skills/compliance-guard/references/trigger-map.md +15 -1
  20. package/assets/skills/compliance-guard/references/us.md +32 -8
  21. package/assets/skills/durable/SKILL.md +22 -29
  22. package/assets/skills/durable/references/agent-db-safety.md +2 -2
  23. package/assets/skills/durable/references/backups-and-runtime.md +6 -6
  24. package/assets/skills/durable/references/migrations-and-schema.md +5 -4
  25. package/assets/skills/lean/SKILL.md +36 -50
  26. package/assets/skills/lean/references/playbooks.md +9 -7
  27. package/dist/app-sidecar/app-settings.d.ts +5 -0
  28. package/dist/app-sidecar/app-settings.js +13 -0
  29. package/dist/app-sidecar/app-settings.js.map +1 -1
  30. package/dist/app-sidecar/auth-routes.js +45 -2
  31. package/dist/app-sidecar/auth-routes.js.map +1 -1
  32. package/dist/app-sidecar/desktop-guidance.d.ts +1 -0
  33. package/dist/app-sidecar/desktop-guidance.js +27 -0
  34. package/dist/app-sidecar/desktop-guidance.js.map +1 -0
  35. package/dist/app-sidecar/history-routes.d.ts +6 -0
  36. package/dist/app-sidecar/history-routes.js +57 -2
  37. package/dist/app-sidecar/history-routes.js.map +1 -1
  38. package/dist/app-sidecar/history.d.ts +17 -0
  39. package/dist/app-sidecar/history.js.map +1 -1
  40. package/dist/app-sidecar/http.d.ts +1 -1
  41. package/dist/app-sidecar/http.js +2 -2
  42. package/dist/app-sidecar/http.js.map +1 -1
  43. package/dist/app-sidecar/integration-routes.js +4 -0
  44. package/dist/app-sidecar/integration-routes.js.map +1 -1
  45. package/dist/app-sidecar/prompt-routes.js +28 -5
  46. package/dist/app-sidecar/prompt-routes.js.map +1 -1
  47. package/dist/app-sidecar/route-context.d.ts +10 -1
  48. package/dist/app-sidecar/run-control-routes.js +9 -2
  49. package/dist/app-sidecar/run-control-routes.js.map +1 -1
  50. package/dist/app-sidecar/session-routes.js +8 -0
  51. package/dist/app-sidecar/session-routes.js.map +1 -1
  52. package/dist/app-sidecar/shell-routes.d.ts +12 -0
  53. package/dist/app-sidecar/shell-routes.js +133 -0
  54. package/dist/app-sidecar/shell-routes.js.map +1 -0
  55. package/dist/app-sidecar/shell-runs.d.ts +103 -0
  56. package/dist/app-sidecar/shell-runs.js +268 -0
  57. package/dist/app-sidecar/shell-runs.js.map +1 -0
  58. package/dist/app-sidecar/shell-suggestions.d.ts +33 -0
  59. package/dist/app-sidecar/shell-suggestions.js +152 -0
  60. package/dist/app-sidecar/shell-suggestions.js.map +1 -0
  61. package/dist/app-sidecar/usage.js +26 -2
  62. package/dist/app-sidecar/usage.js.map +1 -1
  63. package/dist/app-sidecar-sessions.js +13 -3
  64. package/dist/app-sidecar-sessions.js.map +1 -1
  65. package/dist/app-sidecar.js +231 -60
  66. package/dist/app-sidecar.js.map +1 -1
  67. package/dist/chat-agents/index.d.ts +1 -1
  68. package/dist/chat-agents/index.js +1 -1
  69. package/dist/chat-agents/index.js.map +1 -1
  70. package/dist/chat-agents/shared.d.ts +4 -0
  71. package/dist/chat-agents/shared.js +8 -1
  72. package/dist/chat-agents/shared.js.map +1 -1
  73. package/dist/cli.js +28 -6
  74. package/dist/cli.js.map +1 -1
  75. package/dist/config.d.ts +22 -2
  76. package/dist/config.js +40 -97
  77. package/dist/config.js.map +1 -1
  78. package/dist/core/agent-session.d.ts +102 -11
  79. package/dist/core/agent-session.js +740 -164
  80. package/dist/core/agent-session.js.map +1 -1
  81. package/dist/core/ask-user.d.ts +6 -0
  82. package/dist/core/ask-user.js +20 -5
  83. package/dist/core/ask-user.js.map +1 -1
  84. package/dist/core/autopilot-gate.js +2 -3
  85. package/dist/core/autopilot-gate.js.map +1 -1
  86. package/dist/core/bundled-agents.js +9 -29
  87. package/dist/core/bundled-agents.js.map +1 -1
  88. package/dist/core/cache-diagnostics.d.ts +4 -0
  89. package/dist/core/cache-diagnostics.js +4 -1
  90. package/dist/core/cache-diagnostics.js.map +1 -1
  91. package/dist/core/cache-expiry.d.ts +2 -0
  92. package/dist/core/cache-expiry.js +6 -0
  93. package/dist/core/cache-expiry.js.map +1 -1
  94. package/dist/core/checklist-items.d.ts +0 -8
  95. package/dist/core/checklist-items.js +0 -8
  96. package/dist/core/checklist-items.js.map +1 -1
  97. package/dist/core/checkpoint-store.d.ts +17 -0
  98. package/dist/core/checkpoint-store.js +72 -0
  99. package/dist/core/checkpoint-store.js.map +1 -1
  100. package/dist/core/claude-code/complete.d.ts +33 -0
  101. package/dist/core/claude-code/complete.js +112 -0
  102. package/dist/core/claude-code/complete.js.map +1 -0
  103. package/dist/core/claude-code/events.d.ts +65 -0
  104. package/dist/core/claude-code/events.js +434 -0
  105. package/dist/core/claude-code/events.js.map +1 -0
  106. package/dist/core/claude-code/live-session.d.ts +92 -0
  107. package/dist/core/claude-code/live-session.js +519 -0
  108. package/dist/core/claude-code/live-session.js.map +1 -0
  109. package/dist/core/claude-code/loop.d.ts +9 -0
  110. package/dist/core/claude-code/loop.js +15 -0
  111. package/dist/core/claude-code/loop.js.map +1 -0
  112. package/dist/core/claude-code/session-sync.d.ts +28 -0
  113. package/dist/core/claude-code/session-sync.js +53 -0
  114. package/dist/core/claude-code/session-sync.js.map +1 -0
  115. package/dist/core/claude-code/tool-bridge.d.ts +49 -0
  116. package/dist/core/claude-code/tool-bridge.js +352 -0
  117. package/dist/core/claude-code/tool-bridge.js.map +1 -0
  118. package/dist/core/claude-code-version.d.ts +1 -1
  119. package/dist/core/claude-code-version.js +1 -1
  120. package/dist/core/claude-code-version.js.map +1 -1
  121. package/dist/core/code-retrieval.d.ts +1 -1
  122. package/dist/core/code-retrieval.js +2 -2
  123. package/dist/core/code-retrieval.js.map +1 -1
  124. package/dist/core/compaction/compactor.d.ts +25 -1
  125. package/dist/core/compaction/compactor.js +137 -7
  126. package/dist/core/compaction/compactor.js.map +1 -1
  127. package/dist/core/compaction/policy.d.ts +18 -0
  128. package/dist/core/compaction/policy.js +24 -5
  129. package/dist/core/compaction/policy.js.map +1 -1
  130. package/dist/core/compaction/tool-result-pruner.d.ts +10 -0
  131. package/dist/core/compaction/tool-result-pruner.js +14 -0
  132. package/dist/core/compaction/tool-result-pruner.js.map +1 -1
  133. package/dist/core/env-delta.d.ts +3 -3
  134. package/dist/core/env-delta.js +4 -5
  135. package/dist/core/env-delta.js.map +1 -1
  136. package/dist/core/goals-store.d.ts +9 -0
  137. package/dist/core/goals-store.js +111 -50
  138. package/dist/core/goals-store.js.map +1 -1
  139. package/dist/core/internal-diagnostics.d.ts +17 -0
  140. package/dist/core/internal-diagnostics.js +45 -0
  141. package/dist/core/internal-diagnostics.js.map +1 -1
  142. package/dist/core/language-detector.d.ts +2 -3
  143. package/dist/core/language-detector.js.map +1 -1
  144. package/dist/core/local-endpoint-store.d.ts +4 -0
  145. package/dist/core/local-endpoint-store.js +31 -15
  146. package/dist/core/local-endpoint-store.js.map +1 -1
  147. package/dist/core/logger.d.ts +5 -0
  148. package/dist/core/logger.js +10 -2
  149. package/dist/core/logger.js.map +1 -1
  150. package/dist/core/lsp/edit-telemetry.js +3 -1
  151. package/dist/core/lsp/edit-telemetry.js.map +1 -1
  152. package/dist/core/lsp/manager.d.ts +15 -0
  153. package/dist/core/lsp/manager.js +31 -0
  154. package/dist/core/lsp/manager.js.map +1 -1
  155. package/dist/core/mcp/deferred-catalog.d.ts +1 -1
  156. package/dist/core/mcp/deferred-catalog.js +1 -1
  157. package/dist/core/openrouter-catalog-store.d.ts +24 -0
  158. package/dist/core/openrouter-catalog-store.js +140 -0
  159. package/dist/core/openrouter-catalog-store.js.map +1 -0
  160. package/dist/core/plan-delta.d.ts +23 -0
  161. package/dist/core/plan-delta.js +36 -0
  162. package/dist/core/plan-delta.js.map +1 -0
  163. package/dist/core/process-gate.d.ts +17 -0
  164. package/dist/core/process-gate.js +24 -0
  165. package/dist/core/process-gate.js.map +1 -1
  166. package/dist/core/project-discovery.js +2 -2
  167. package/dist/core/project-discovery.js.map +1 -1
  168. package/dist/core/project-files.d.ts +15 -0
  169. package/dist/core/project-files.js +37 -0
  170. package/dist/core/project-files.js.map +1 -0
  171. package/dist/core/prompt-commands.js +41 -75
  172. package/dist/core/prompt-commands.js.map +1 -1
  173. package/dist/core/radio-players.d.ts +28 -0
  174. package/dist/core/radio-players.js +133 -0
  175. package/dist/core/radio-players.js.map +1 -0
  176. package/dist/core/radio.js +20 -3
  177. package/dist/core/radio.js.map +1 -1
  178. package/dist/core/runtime-mode.d.ts +9 -0
  179. package/dist/core/runtime-mode.js +26 -0
  180. package/dist/core/runtime-mode.js.map +1 -1
  181. package/dist/core/session-history.d.ts +7 -0
  182. package/dist/core/session-history.js +34 -2
  183. package/dist/core/session-history.js.map +1 -1
  184. package/dist/core/session-manager.d.ts +5 -1
  185. package/dist/core/session-manager.js +36 -7
  186. package/dist/core/session-manager.js.map +1 -1
  187. package/dist/core/session-preview.js +2 -2
  188. package/dist/core/session-preview.js.map +1 -1
  189. package/dist/core/session-summary-index.d.ts +18 -4
  190. package/dist/core/session-summary-index.js +28 -8
  191. package/dist/core/session-summary-index.js.map +1 -1
  192. package/dist/core/settings-manager.d.ts +7 -0
  193. package/dist/core/settings-manager.js +53 -7
  194. package/dist/core/settings-manager.js.map +1 -1
  195. package/dist/core/shell.d.ts +4 -0
  196. package/dist/core/shell.js +15 -1
  197. package/dist/core/shell.js.map +1 -1
  198. package/dist/core/skills.d.ts +8 -0
  199. package/dist/core/skills.js +15 -5
  200. package/dist/core/skills.js.map +1 -1
  201. package/dist/core/steering.d.ts +4 -0
  202. package/dist/core/steering.js +8 -1
  203. package/dist/core/steering.js.map +1 -1
  204. package/dist/core/stream-diag-level.d.ts +3 -0
  205. package/dist/core/stream-diag-level.js +24 -0
  206. package/dist/core/stream-diag-level.js.map +1 -0
  207. package/dist/core/subagent-manager.d.ts +11 -0
  208. package/dist/core/subagent-manager.js +16 -4
  209. package/dist/core/subagent-manager.js.map +1 -1
  210. package/dist/core/subagent-policy.d.ts +6 -0
  211. package/dist/core/subagent-policy.js +22 -3
  212. package/dist/core/subagent-policy.js.map +1 -1
  213. package/dist/core/subagent-receipt.d.ts +3 -3
  214. package/dist/core/subagent-receipt.js +6 -9
  215. package/dist/core/subagent-receipt.js.map +1 -1
  216. package/dist/core/threat-feed.js +10 -4
  217. package/dist/core/threat-feed.js.map +1 -1
  218. package/dist/core/trophies/catalog-more.js +16 -36
  219. package/dist/core/trophies/catalog-more.js.map +1 -1
  220. package/dist/core/trophies/engine.js +0 -4
  221. package/dist/core/trophies/engine.js.map +1 -1
  222. package/dist/core/trophies/types.d.ts +1 -1
  223. package/dist/core/trophies/types.js +0 -2
  224. package/dist/core/trophies/types.js.map +1 -1
  225. package/dist/core/user-shell-context.d.ts +8 -0
  226. package/dist/core/user-shell-context.js +12 -0
  227. package/dist/core/user-shell-context.js.map +1 -0
  228. package/dist/core/verify-commands.d.ts +1 -1
  229. package/dist/goals-agent/goal-team.js +3 -4
  230. package/dist/goals-agent/goal-team.js.map +1 -1
  231. package/dist/goals-agent/goals-agent.d.ts +1 -1
  232. package/dist/goals-agent/goals-agent.js +4 -3
  233. package/dist/goals-agent/goals-agent.js.map +1 -1
  234. package/dist/modes/acp-mode.d.ts +1 -1
  235. package/dist/modes/acp-mode.js +4 -5
  236. package/dist/modes/acp-mode.js.map +1 -1
  237. package/dist/modes/agent-home-mode.js +5 -5
  238. package/dist/modes/agent-home-mode.js.map +1 -1
  239. package/dist/modes/json-mode.js +5 -0
  240. package/dist/modes/json-mode.js.map +1 -1
  241. package/dist/modes/serve-mode.js +5 -5
  242. package/dist/modes/serve-mode.js.map +1 -1
  243. package/dist/motion-agent/motion-agent.d.ts +12 -5
  244. package/dist/motion-agent/motion-agent.js +24 -9
  245. package/dist/motion-agent/motion-agent.js.map +1 -1
  246. package/dist/subagent-entry.d.ts +1 -0
  247. package/dist/subagent-entry.js +50 -0
  248. package/dist/subagent-entry.js.map +1 -0
  249. package/dist/system-prompt.d.ts +13 -3
  250. package/dist/system-prompt.js +47 -21
  251. package/dist/system-prompt.js.map +1 -1
  252. package/dist/tools/ask-user.js +3 -2
  253. package/dist/tools/ask-user.js.map +1 -1
  254. package/dist/tools/bash.d.ts +7 -0
  255. package/dist/tools/bash.js +26 -8
  256. package/dist/tools/bash.js.map +1 -1
  257. package/dist/tools/checklist.js +6 -11
  258. package/dist/tools/checklist.js.map +1 -1
  259. package/dist/tools/debug.js +6 -9
  260. package/dist/tools/debug.js.map +1 -1
  261. package/dist/tools/document-text.d.ts +6 -0
  262. package/dist/tools/document-text.js +154 -0
  263. package/dist/tools/document-text.js.map +1 -0
  264. package/dist/tools/enter-plan.js +4 -7
  265. package/dist/tools/enter-plan.js.map +1 -1
  266. package/dist/tools/find.d.ts +9 -0
  267. package/dist/tools/find.js +38 -1
  268. package/dist/tools/find.js.map +1 -1
  269. package/dist/tools/generate-image.d.ts +18 -0
  270. package/dist/tools/generate-image.js +208 -17
  271. package/dist/tools/generate-image.js.map +1 -1
  272. package/dist/tools/goals.d.ts +2 -2
  273. package/dist/tools/index.d.ts +5 -2
  274. package/dist/tools/index.js +5 -13
  275. package/dist/tools/index.js.map +1 -1
  276. package/dist/tools/operations.js +1 -1
  277. package/dist/tools/operations.js.map +1 -1
  278. package/dist/tools/overflow.d.ts +2 -0
  279. package/dist/tools/overflow.js +10 -0
  280. package/dist/tools/overflow.js.map +1 -1
  281. package/dist/tools/prompt-hints.d.ts +10 -1
  282. package/dist/tools/prompt-hints.js +38 -11
  283. package/dist/tools/prompt-hints.js.map +1 -1
  284. package/dist/tools/read.js +25 -10
  285. package/dist/tools/read.js.map +1 -1
  286. package/dist/tools/routine-output.d.ts +39 -0
  287. package/dist/tools/routine-output.js +281 -0
  288. package/dist/tools/routine-output.js.map +1 -0
  289. package/dist/tools/screenshot.js +6 -10
  290. package/dist/tools/screenshot.js.map +1 -1
  291. package/dist/tools/side-web-search.d.ts +35 -0
  292. package/dist/tools/side-web-search.js +147 -0
  293. package/dist/tools/side-web-search.js.map +1 -0
  294. package/dist/tools/skill.d.ts +2 -0
  295. package/dist/tools/skill.js +33 -6
  296. package/dist/tools/skill.js.map +1 -1
  297. package/dist/tools/steroids.d.ts +7 -6
  298. package/dist/tools/steroids.js +193 -87
  299. package/dist/tools/steroids.js.map +1 -1
  300. package/dist/tools/subagent-control.js +66 -10
  301. package/dist/tools/subagent-control.js.map +1 -1
  302. package/dist/tools/subagent-shared.d.ts +19 -2
  303. package/dist/tools/subagent-shared.js +35 -10
  304. package/dist/tools/subagent-shared.js.map +1 -1
  305. package/dist/tools/subagent.js +23 -7
  306. package/dist/tools/subagent.js.map +1 -1
  307. package/dist/tools/tool-search.js +7 -1
  308. package/dist/tools/tool-search.js.map +1 -1
  309. package/dist/tools/tool-tiers.d.ts +3 -2
  310. package/dist/tools/tool-tiers.js +7 -5
  311. package/dist/tools/tool-tiers.js.map +1 -1
  312. package/dist/tools/truncate.js +4 -8
  313. package/dist/tools/truncate.js.map +1 -1
  314. package/dist/tools/web-fetch.d.ts +8 -0
  315. package/dist/tools/web-fetch.js +123 -17
  316. package/dist/tools/web-fetch.js.map +1 -1
  317. package/dist/tools/web-search.d.ts +3 -2
  318. package/dist/tools/web-search.js +25 -1
  319. package/dist/tools/web-search.js.map +1 -1
  320. package/dist/ui/App.js +37 -37
  321. package/dist/ui/App.js.map +1 -1
  322. package/dist/ui/components/Footer.js +4 -1
  323. package/dist/ui/components/Footer.js.map +1 -1
  324. package/dist/ui/components/SkillsOverlay.js +2 -1
  325. package/dist/ui/components/SkillsOverlay.js.map +1 -1
  326. package/dist/ui/hooks/useAgentLoop.d.ts +3 -0
  327. package/dist/ui/hooks/useAgentLoop.js +54 -4
  328. package/dist/ui/hooks/useAgentLoop.js.map +1 -1
  329. package/dist/ui/hooks/useContextCompaction.js +1 -0
  330. package/dist/ui/hooks/useContextCompaction.js.map +1 -1
  331. package/dist/ui/language-pack-update.d.ts +25 -0
  332. package/dist/ui/language-pack-update.js +19 -0
  333. package/dist/ui/language-pack-update.js.map +1 -0
  334. package/dist/ui/terminal-history.js +3 -1
  335. package/dist/ui/terminal-history.js.map +1 -1
  336. package/dist/utils/http-body.d.ts +5 -0
  337. package/dist/utils/http-body.js +5 -0
  338. package/dist/utils/http-body.js.map +1 -1
  339. package/dist/utils/image.d.ts +11 -0
  340. package/dist/utils/image.js +34 -1
  341. package/dist/utils/image.js.map +1 -1
  342. package/dist/utils/plan-steps.d.ts +1 -0
  343. package/dist/utils/plan-steps.js +10 -0
  344. package/dist/utils/plan-steps.js.map +1 -1
  345. package/dist/utils/prompt-enhancer.d.ts +3 -1
  346. package/dist/utils/prompt-enhancer.js +21 -16
  347. package/dist/utils/prompt-enhancer.js.map +1 -1
  348. package/package.json +23 -6
  349. package/assets/skills/clarify/SKILL.md +0 -39
  350. package/assets/skills/code-review/SKILL.md +0 -88
  351. package/assets/skills/code-review/references/agent-diffs.md +0 -27
  352. package/assets/skills/code-review/references/tests.md +0 -19
  353. package/assets/skills/evidence-led-ui/LICENSES.md +0 -80
  354. package/assets/skills/evidence-led-ui/SKILL.md +0 -100
  355. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/LICENSE +0 -21
  356. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/airbnb/DESIGN.md +0 -545
  357. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/airtable/DESIGN.md +0 -554
  358. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/apple/DESIGN.md +0 -562
  359. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/binance/DESIGN.md +0 -634
  360. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/bmw/DESIGN.md +0 -544
  361. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/bmw-m/DESIGN.md +0 -503
  362. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/bugatti/DESIGN.md +0 -454
  363. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/cal/DESIGN.md +0 -542
  364. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/claude/DESIGN.md +0 -589
  365. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/clay/DESIGN.md +0 -541
  366. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/clickhouse/DESIGN.md +0 -544
  367. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/cohere/DESIGN.md +0 -451
  368. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/coinbase/DESIGN.md +0 -570
  369. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/composio/DESIGN.md +0 -506
  370. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/cursor/DESIGN.md +0 -537
  371. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/dell-1996/DESIGN.md +0 -632
  372. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/elevenlabs/DESIGN.md +0 -504
  373. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/expo/DESIGN.md +0 -526
  374. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/ferrari/DESIGN.md +0 -531
  375. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/figma/DESIGN.md +0 -578
  376. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/framer/DESIGN.md +0 -544
  377. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/hashicorp/DESIGN.md +0 -575
  378. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/hp/DESIGN.md +0 -670
  379. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/ibm/DESIGN.md +0 -550
  380. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/intercom/DESIGN.md +0 -546
  381. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/kraken/DESIGN.md +0 -125
  382. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/lamborghini/DESIGN.md +0 -288
  383. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/linear.app/DESIGN.md +0 -548
  384. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/lovable/DESIGN.md +0 -298
  385. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/mastercard/DESIGN.md +0 -365
  386. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/meta/DESIGN.md +0 -683
  387. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/minimax/DESIGN.md +0 -746
  388. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/mintlify/DESIGN.md +0 -852
  389. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/miro/DESIGN.md +0 -825
  390. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/mistral.ai/DESIGN.md +0 -773
  391. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/mongodb/DESIGN.md +0 -767
  392. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/nike/DESIGN.md +0 -575
  393. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/nintendo-2001/DESIGN.md +0 -649
  394. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/notion/DESIGN.md +0 -821
  395. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/nvidia/DESIGN.md +0 -640
  396. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/ollama/DESIGN.md +0 -539
  397. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/opencode.ai/DESIGN.md +0 -521
  398. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/pinterest/DESIGN.md +0 -597
  399. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/playstation/DESIGN.md +0 -661
  400. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/posthog/DESIGN.md +0 -690
  401. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/raycast/DESIGN.md +0 -669
  402. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/renault/DESIGN.md +0 -589
  403. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/replicate/DESIGN.md +0 -616
  404. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/resend/DESIGN.md +0 -585
  405. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/revolut/DESIGN.md +0 -636
  406. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/runwayml/DESIGN.md +0 -244
  407. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/sanity/DESIGN.md +0 -357
  408. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/sentry/DESIGN.md +0 -551
  409. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/shopify/DESIGN.md +0 -516
  410. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/slack/DESIGN.md +0 -482
  411. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/spacex/DESIGN.md +0 -363
  412. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/spotify/DESIGN.md +0 -246
  413. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/starbucks/DESIGN.md +0 -580
  414. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/stripe/DESIGN.md +0 -487
  415. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/supabase/DESIGN.md +0 -462
  416. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/superhuman/DESIGN.md +0 -448
  417. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/tesla/DESIGN.md +0 -286
  418. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/theverge/DESIGN.md +0 -339
  419. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/together.ai/DESIGN.md +0 -633
  420. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/uber/DESIGN.md +0 -636
  421. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/vercel/DESIGN.md +0 -736
  422. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/vodafone/DESIGN.md +0 -538
  423. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/voltagent/DESIGN.md +0 -521
  424. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/warp/DESIGN.md +0 -526
  425. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/webflow/DESIGN.md +0 -588
  426. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/wired/DESIGN.md +0 -497
  427. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/wise/DESIGN.md +0 -544
  428. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/x.ai/DESIGN.md +0 -465
  429. package/assets/skills/evidence-led-ui/corpus/awesome-design-md/design-md/zapier/DESIGN.md +0 -537
  430. package/assets/skills/evidence-led-ui/data/corpus-manifest.json +0 -768
  431. package/assets/skills/evidence-led-ui/data/observations.json +0 -47053
  432. package/assets/skills/evidence-led-ui/references/anti-defaults.md +0 -110
  433. package/assets/skills/evidence-led-ui/references/archetypes.md +0 -97
  434. package/assets/skills/evidence-led-ui/references/craft-rulings.md +0 -242
  435. package/assets/skills/evidence-led-ui/references/direction.md +0 -124
  436. package/assets/skills/evidence-led-ui/references/methodology.md +0 -72
  437. package/assets/skills/evidence-led-ui/references/observed-patterns.md +0 -68
  438. package/assets/skills/evidence-led-ui/references/production-contract.md +0 -148
  439. package/assets/skills/evidence-led-ui/references/provenance.md +0 -142
  440. package/assets/skills/evidence-led-ui/references/quality-rubric.md +0 -126
  441. package/assets/skills/evidence-led-ui/references/ui-libraries.md +0 -30
  442. package/assets/skills/refactoring/SKILL.md +0 -87
  443. package/assets/skills/refactoring/references/agent-pitfalls.md +0 -46
  444. package/assets/skills/refactoring/references/legacy.md +0 -70
  445. package/assets/skills/refactoring/references/smells.md +0 -71
  446. package/assets/skills/root-cause/SKILL.md +0 -46
  447. package/assets/skills/shared-language/SKILL.md +0 -32
  448. package/assets/skills/tdd/SKILL.md +0 -42
  449. package/dist/core/setup-history.d.ts +0 -6
  450. package/dist/core/setup-history.js +0 -55
  451. package/dist/core/setup-history.js.map +0 -1
  452. package/dist/core/style-packs/index.d.ts +0 -18
  453. package/dist/core/style-packs/index.js +0 -60
  454. package/dist/core/style-packs/index.js.map +0 -1
  455. package/dist/core/style-packs/packs.d.ts +0 -8
  456. package/dist/core/style-packs/packs.js +0 -188
  457. package/dist/core/style-packs/packs.js.map +0 -1
  458. package/dist/interactive.d.ts +0 -2
  459. package/dist/interactive.js +0 -257
  460. package/dist/interactive.js.map +0 -1
  461. package/dist/motion-agent/motion-review-coverage.d.ts +0 -12
  462. package/dist/motion-agent/motion-review-coverage.js +0 -33
  463. package/dist/motion-agent/motion-review-coverage.js.map +0 -1
  464. package/dist/motion-agent/motion-review-session.d.ts +0 -65
  465. package/dist/motion-agent/motion-review-session.js +0 -422
  466. package/dist/motion-agent/motion-review-session.js.map +0 -1
  467. package/dist/tools/code-nav.d.ts +0 -29
  468. package/dist/tools/code-nav.js +0 -299
  469. package/dist/tools/code-nav.js.map +0 -1
  470. package/dist/tools/code-skeleton.d.ts +0 -28
  471. package/dist/tools/code-skeleton.js +0 -115
  472. package/dist/tools/code-skeleton.js.map +0 -1
  473. package/dist/tools/search-code.d.ts +0 -10
  474. package/dist/tools/search-code.js +0 -90
  475. package/dist/tools/search-code.js.map +0 -1
  476. package/dist/ui/stores/index.d.ts +0 -2
  477. package/dist/ui/stores/index.js +0 -3
  478. package/dist/ui/stores/index.js.map +0 -1
  479. package/dist/utils/format.d.ts +0 -16
  480. package/dist/utils/format.js +0 -159
  481. package/dist/utils/format.js.map +0 -1
  482. package/dist/utils/shell.d.ts +0 -2
  483. package/dist/utils/shell.js +0 -8
  484. 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";
@@ -14,7 +14,8 @@ 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
16
  import { dualAuthProvider } from "@prestyj/core";
17
- import { getClaudeCliUserAgent, recordRequiredClaudeCodeVersion } from "./claude-code-version.js";
17
+ import { getClaudeCliUserAgent } from "./claude-code-version.js";
18
+ import { runSideWebSearch, runSideWebSearchViaClaudeCode, SIDE_SEARCH_MODEL, } from "../tools/side-web-search.js";
18
19
  import { kimiCodingHeaders, isKimiCodingEndpoint } from "./oauth/kimi.js";
19
20
  import { isGrokCliEndpoint } from "./oauth/xai.js";
20
21
  import { SessionManager, } from "./session-manager.js";
@@ -22,14 +23,14 @@ import { ExtensionLoader } from "./extensions/loader.js";
22
23
  import { shouldCompact, compact, } from "./compaction/compactor.js";
23
24
  import { getHistoryMessageVisibility } from "./session-history.js";
24
25
  import { sourceFingerprint as computeSourceFingerprint } from "./session-compaction.js";
25
- import { getAuthStorageKeys, getContextWindow, getModel, MODELS } from "./model-registry.js";
26
+ import { getAuthStorageKeys, getContextWindow, getListedModels, getModel, } from "./model-registry.js";
26
27
  import { discoverSkillsWithBlocked } from "./skills.js";
27
28
  import { ensureAppDirs } from "../config.js";
28
29
  import { buildSubAgentSystemPrompt, buildSystemPrompt, } from "../system-prompt.js";
29
30
  import { createTools, createWebSearchTool, } from "../tools/index.js";
30
31
  import { partitionToolsByTier } from "../tools/tool-tiers.js";
31
32
  import { formatImpactForVerification } from "./test-impact.js";
32
- import { buildProcessCompletionFollowUp } from "./process-gate.js";
33
+ import { buildProcessCompletionFollowUp, mergeCompletionGateFollowUps } from "./process-gate.js";
33
34
  import { PLAN_SUBMISSION_NUDGE, shouldNudgePlanSubmission } from "./plan-submission-gate.js";
34
35
  import { buildSubAgentCompletionFollowUp, } from "./subagent-manager.js";
35
36
  import { applyAsyncSubagentPolicy } from "./subagent-policy.js";
@@ -42,7 +43,7 @@ import { createSessionStatsTool } from "../tools/session-stats.js";
42
43
  import { createDiagnoseCommand, isInternalDiagnosticsEnabled, SessionDiagnosticsRecorder, } from "./internal-diagnostics.js";
43
44
  import { log } from "./logger.js";
44
45
  import { CacheDiagnostics } from "./cache-diagnostics.js";
45
- import { assessCacheExpiry, resolveCacheTtl } from "./cache-expiry.js";
46
+ import { assessCacheExpiry, CLAUDE_CODE_CACHE_TTL, resolveCacheTtl, } from "./cache-expiry.js";
46
47
  import { setEstimatorModel, calibrateEstimatorFromUsage, estimateConversationTokens, } from "./compaction/token-estimator.js";
47
48
  import { calculateActiveContextTokens } from "./compaction/active-context.js";
48
49
  import { resolveCompactionPolicy } from "./compaction/policy.js";
@@ -50,14 +51,21 @@ import { decidePlanStepCompaction, DEFAULT_CACHE_WRITE_READ_RATIO, PLAN_STEP_KEE
50
51
  import { extractPlanSteps, findCompletedMarkers } from "../utils/plan-steps.js";
51
52
  import { readFileSync } from "node:fs";
52
53
  import { clampThinkingForPlanMode } from "./thinking-level.js";
53
- import { pruneStaleToolResults, shouldPruneToolResults } from "./compaction/tool-result-pruner.js";
54
+ import { pruneMinimumTokens, pruneStaleToolResults, shouldPruneToolResults, } from "./compaction/tool-result-pruner.js";
54
55
  import { discoverAgents } from "./agents.js";
55
56
  import { enhancePrompt } from "../utils/prompt-enhancer.js";
57
+ import { assistantText, renderTranscript } from "./claude-code/events.js";
58
+ import { ClaudeCodeLiveSession, systemPrompt } from "./claude-code/live-session.js";
59
+ import { CLAUDE_CODE_SEED_CHARS, CLAUDE_CODE_SESSION_KIND, claudeCodeResumeId, claudeCodeSessionEntryData, parseClaudeCodeSessionState, } from "./claude-code/session-sync.js";
60
+ import { claudeCodeComplete, resolveClaudeCodeProcess, } from "./claude-code/complete.js";
56
61
  import { detectLanguages, detectProjectStack } from "./language-detector.js";
57
62
  import { buildLoopBreakMessage } from "./loop-breaker.js";
58
63
  import { buildRegroundingMessage, requestTextForRegrounding } from "./regrounding.js";
59
64
  import { buildSemanticLoopJudgePrompt, buildSemanticLoopMessage, parseSemanticLoopVerdict, SEMANTIC_LOOP_JUDGE_TIMEOUT_MS, withJudgeTimeout, } from "./semantic-loop-check.js";
60
65
  import { buildEnvDeltaMessage, buildLanguageUpdateMessage } from "./env-delta.js";
66
+ import { buildUserShellContextText } from "./user-shell-context.js";
67
+ import { buildPlanStateMessage, samePlanState } from "./plan-delta.js";
68
+ import { listProjectFiles } from "./project-files.js";
61
69
  import { wrapSteeringText, buildNotificationSteeringText, buildIdleWakeNotificationText, STEERING_PREFIX, } from "./steering.js";
62
70
  import { AgentNotificationQueue } from "./agent-notifications.js";
63
71
  import { VerificationGate, VERIFICATION_STATE_KIND } from "./verification-gate.js";
@@ -124,9 +132,46 @@ export class PaidModelConfirmationError extends Error {
124
132
  export { resolveSessionToolResultCharLimit, resolveSessionTurnToolResultCharLimit, } from "./agent-session/helpers.js";
125
133
  // ── Agent Session ──────────────────────────────────────────
126
134
  /** A prompt that asks for the live web (see AgentSession.attachWebSearchIfAsked). */
135
+ /** True when the transcript holds a native (server-side) `web_search` call. */
136
+ export function historyUsesNativeWebSearch(messages) {
137
+ for (const message of messages) {
138
+ if (message.role !== "assistant" || !Array.isArray(message.content))
139
+ continue;
140
+ for (const part of message.content) {
141
+ if (part.type === "server_tool_call" && part.name === "web_search")
142
+ return true;
143
+ if (part.type === "raw") {
144
+ const data = part.data;
145
+ if (data?.type === "server_tool_use" && data.name === "web_search")
146
+ return true;
147
+ }
148
+ }
149
+ }
150
+ return false;
151
+ }
127
152
  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;
128
153
  /** Distinct security rows one run may add to the chat (and session file). */
129
154
  const MAX_SECURITY_ROWS_PER_RUN = 20;
155
+ /** How long dispose waits for a post-turn compaction before aborting it. */
156
+ export const DISPOSE_COMPACTION_WAIT_MS = 2_500;
157
+ /** Grace after aborting it, for the compaction to unwind. */
158
+ const DISPOSE_COMPACTION_ABORT_GRACE_MS = 500;
159
+ /** Resolves true if `promise` settles within `ms`, else false. Never rejects. */
160
+ async function settleWithin(promise, ms) {
161
+ let timer;
162
+ const timeout = new Promise((resolve) => {
163
+ timer = setTimeout(() => resolve(false), ms);
164
+ });
165
+ try {
166
+ return await Promise.race([
167
+ promise.then(() => true, () => true),
168
+ timeout,
169
+ ]);
170
+ }
171
+ finally {
172
+ clearTimeout(timer);
173
+ }
174
+ }
130
175
  /**
131
176
  * A chat row's target: first line, no control or bidi-override characters
132
177
  * (they could make a command look like another), at most 120 chars.
@@ -218,6 +263,10 @@ export class AgentSession {
218
263
  * delta; anything that changes WITHOUT one is caught by the hook below.
219
264
  */
220
265
  renderedEnvironment = {};
266
+ /** Project files as of the first prompt build (undefined until then). */
267
+ projectFiles;
268
+ /** `git ls-files` started at the top of initialize(), overlapping the rest of setup. */
269
+ projectFilesPending;
221
270
  /** Wall-clock start of the current run; scopes the background-process gate. */
222
271
  runStartedAt = 0;
223
272
  /** Gate injections spent this run, capped by MAX_PROCESS_GATE_INJECTIONS. */
@@ -242,6 +291,8 @@ export class AgentSession {
242
291
  compactionArmedForNextRun = false;
243
292
  /** In-flight post-turn (background) compaction, if any. */
244
293
  postTurnCompaction;
294
+ /** Aborts the in-flight post-turn compaction (dispose caps its wait). */
295
+ postTurnCompactionAbort;
245
296
  lastCompactionCompacted = false;
246
297
  compactionRetryAfter = 0;
247
298
  /**
@@ -279,6 +330,11 @@ export class AgentSession {
279
330
  // every turn boundary, so an index captured by the UI can point at a
280
331
  // different message (or past the end) by the time the cancel arrives.
281
332
  userQueue = [];
333
+ // Steering whose text the model already read in an ask_user result.
334
+ askAnswerSteering = new WeakSet();
335
+ // Taken into the run but not yet in the transcript. Claude Code takes queued
336
+ // messages at once but reads them at its next turn, so they still show as queued.
337
+ deliveringQueue = [];
282
338
  queueSeq = 0;
283
339
  /** Monotonic count of human-originated prompts; idle-wake budgets reset on it. */
284
340
  humanPromptSeq = 0;
@@ -310,6 +366,10 @@ export class AgentSession {
310
366
  * can discover and promote them; a promoted name drops out of this list.
311
367
  */
312
368
  deferredBuiltinToolNames = [];
369
+ /** Deferred built-ins in tier order, fixed at session start. Sent as the
370
+ * provider's on-demand catalog (see @prestyj/ai `deferredTools`) so promoting one
371
+ * loads it through the transcript and the cached tools block stays put. */
372
+ deferredToolCatalog = [];
313
373
  provider;
314
374
  model;
315
375
  cwd;
@@ -326,10 +386,18 @@ export class AgentSession {
326
386
  agentPrompt;
327
387
  /** Stable prompt prefix retained separately from the volatile uncached tail. */
328
388
  baseSystemPrompt = "";
389
+ /** Plan state rendered into the cached system prompt. */
390
+ promptPlanState = { planMode: false, approvedPlanPath: undefined };
391
+ /** Plan state the model has been told (prompt or appended notice). */
392
+ seenPlanState = { planMode: false, approvedPlanPath: undefined };
393
+ /** Plan notice waiting for the next request, with the state it describes. */
394
+ pendingPlanNotice = null;
395
+ /** Latest plan notice appended — re-announced if compaction drops it. */
396
+ lastPlanNotice = null;
329
397
  /**
330
- * Project languages whose style packs and verify commands are in the
331
- * standard prompt. Only ever grows within a session (same policy as the
332
- * terminal UI): a pack disappearing mid-task would rewrite the cached prefix
398
+ * Project languages whose verify commands are in the standard prompt.
399
+ * Only ever grows within a session (same policy as the terminal UI): a
400
+ * section disappearing mid-task would rewrite the cached prefix
333
401
  * for no benefit.
334
402
  */
335
403
  activeLanguages = new Set();
@@ -376,6 +444,8 @@ export class AgentSession {
376
444
  * dropped as out-of-range. Anchoring to the persisted prefix keeps resume
377
445
  * placement 1:1 with where the row appeared live.
378
446
  */
447
+ /** Commands the user ran themselves, held until their next message. */
448
+ pendingUserShell = [];
379
449
  persistedTranscriptCount() {
380
450
  return this.messages.slice(0, this.lastPersistedIndex).filter((m) => m.role !== "system")
381
451
  .length;
@@ -431,6 +501,12 @@ export class AgentSession {
431
501
  // so it overlaps session setup and the user's typing instead.
432
502
  if (this.provider === "anthropic")
433
503
  void getClaudeCliUserAgent().catch(() => { });
504
+ // The prompt's file list is a `git ls-files` (~30 ms on a mid-size repo)
505
+ // that nothing before buildBasePrompt depends on: start it now so it runs
506
+ // alongside settings/auth/skills/tools instead of after them.
507
+ if (!this.customSystemPrompt && this.projectFiles === undefined) {
508
+ this.projectFilesPending = listProjectFiles(this.cwd);
509
+ }
434
510
  const paths = await ensureAppDirs();
435
511
  // Load settings & auth
436
512
  this.settingsManager = new SettingsManager(paths.settingsFile);
@@ -441,7 +517,7 @@ export class AgentSession {
441
517
  // Session manager. Agent-specific roots keep chat and coder histories isolated.
442
518
  this.sessionManager = new SessionManager(this.opts.sessionRootDir ?? paths.sessionsDir);
443
519
  const projectCustomization = this.opts.projectCustomization !== false;
444
- // A real project folder: not Motion (own skills), not GG Goals (goal notes
520
+ // A real project folder: not Motion (own skills), not EZ Goals (goal notes
445
521
  // folder, agentContext "none"), not chat (no project customization).
446
522
  this.projectSession =
447
523
  projectCustomization &&
@@ -459,6 +535,7 @@ export class AgentSession {
459
535
  }
460
536
  if (this.opts.skills) {
461
537
  this.skills = [...this.opts.skills];
538
+ this.blockedSkills = [...(this.opts.blockedSkills ?? [])];
462
539
  }
463
540
  else if (projectCustomization) {
464
541
  const discovery = await discoverSkillsWithBlocked({
@@ -500,6 +577,7 @@ export class AgentSession {
500
577
  additionalRoots: this.additionalRoots,
501
578
  }),
502
579
  getPackageCooldownDays: () => this.settingsManager.get("packageCooldownDays"),
580
+ getBashPath: () => this.settingsManager.get("bashPath"),
503
581
  getNetworkPolicy: () => ({
504
582
  mode: this.settingsManager.get("networkMode"),
505
583
  allow: this.settingsManager.get("networkAllow"),
@@ -518,6 +596,7 @@ export class AgentSession {
518
596
  allowUnixSockets: this.settingsManager.get("sandboxAllowUnixSockets"),
519
597
  }),
520
598
  getUseExternalGrep: () => this.settingsManager.get("grepUseRipgrep"),
599
+ sideWebSearch: (request) => this.runSideWebSearch(request),
521
600
  authStorage: this.authStorage,
522
601
  onFileMutated: (filePath) => {
523
602
  const relative = path.relative(this.cwd, filePath) || path.basename(filePath);
@@ -597,6 +676,7 @@ export class AgentSession {
597
676
  // sits inside the cached prefix stays byte-stable across turns.
598
677
  this.tools = core;
599
678
  this.deferredBuiltinToolNames = deferred.map((t) => t.name);
679
+ this.deferredToolCatalog = [...deferred];
600
680
  this.mcp.addDeferred(deferred);
601
681
  }
602
682
  }
@@ -731,6 +811,7 @@ export class AgentSession {
731
811
  await this.extensionLoader.loadAll(paths.extensionsDir, extContext);
732
812
  }
733
813
  this.eventBus.emit("session_start", { sessionId: this.sessionId });
814
+ this.preconnect();
734
815
  }
735
816
  /**
736
817
  * Whether a tool name is permitted for this session. With no `allowedTools`
@@ -862,7 +943,7 @@ export class AgentSession {
862
943
  * Whether provider-native web search rides along with this request.
863
944
  *
864
945
  * Anthropic's `web_search_20250305` server tool costs ~2.5k prefix tokens on
865
- * every request (count_tokens: 6,628 vs 4,098 for the GG prefix without it),
946
+ * every request (count_tokens: 6,628 vs 4,098 for the EZ Coder prefix without it),
866
947
  * yet web search is reached in ~6% of sessions — the reason the client tool
867
948
  * is deferred everywhere else. So on a tiered Anthropic session it is only
868
949
  * attached once the model has promoted `web_search` (tool_search or a direct
@@ -872,9 +953,14 @@ export class AgentSession {
872
953
  nativeWebSearchOn() {
873
954
  if (this.provider !== "anthropic")
874
955
  return true;
875
- if (!this.deferredBuiltinToolNames.includes("web_search"))
876
- return true;
877
- return this.tools.some((t) => t.name === "web_search");
956
+ // Anthropic search runs inside the client web_search tool as a side
957
+ // request (runSideWebSearch): its result pages cost 11–20k cache-write
958
+ // tokens each in the main context. A restored, branched or compacted conversation can already hold native
959
+ // `web_search` blocks from when the tool was attached. Anthropic rejects
960
+ // any request whose history references a server tool that is not declared
961
+ // (400 "`server_tool_use` block references `web_search`…"), so the history
962
+ // itself keeps native search on.
963
+ return historyUsesNativeWebSearch(this.messages);
878
964
  }
879
965
  /**
880
966
  * A human prompt that plainly asks for the web gets native web search from
@@ -885,7 +971,7 @@ export class AgentSession {
885
971
  * one discovery turn, a false hit only the ~2.5k-token schema.
886
972
  */
887
973
  attachWebSearchIfAsked(content) {
888
- if (this.provider !== "anthropic" || this.nativeWebSearchOn())
974
+ if (this.provider !== "anthropic" || this.tools.some((t) => t.name === "web_search"))
889
975
  return;
890
976
  const text = typeof content === "string"
891
977
  ? content
@@ -897,6 +983,240 @@ export class AgentSession {
897
983
  if (WEB_INTENT.test(text))
898
984
  this.promoteDeferredBuiltin("web_search");
899
985
  }
986
+ async runSideWebSearch(request) {
987
+ if (this.provider !== "anthropic")
988
+ return null;
989
+ const claudeCode = await this.claudeCodeProcess();
990
+ if (claudeCode)
991
+ return await runSideWebSearchViaClaudeCode(request, claudeCode);
992
+ const creds = await this.authStorage.resolveCredentials("anthropic", {
993
+ storageKeys: getAuthStorageKeys("anthropic", SIDE_SEARCH_MODEL),
994
+ });
995
+ return await runSideWebSearch(request, {
996
+ apiKey: creds.accessToken,
997
+ baseUrl: this.baseUrl ?? creds.baseUrl,
998
+ userAgent: await getClaudeCliUserAgent(),
999
+ });
1000
+ }
1001
+ // No creds = Claude subscription route; compact() then summarizes through Claude Code.
1002
+ async maybeCompactPreRun(creds) {
1003
+ if (this.settingsManager.get("autoCompact") && Date.now() >= this.compactionRetryAfter) {
1004
+ // A post-turn compaction may still be running in the background. Let it
1005
+ // settle first: it usually already compacted this history, so the
1006
+ // decision below turns into a no-op instead of duplicate work.
1007
+ if (this.postTurnCompaction)
1008
+ await this.postTurnCompaction;
1009
+ const contextWindow = getContextWindow(this.model, {
1010
+ provider: this.provider,
1011
+ accountId: creds?.accountId,
1012
+ });
1013
+ const policy = resolveCompactionPolicy({
1014
+ provider: this.provider,
1015
+ model: this.model,
1016
+ contextWindow,
1017
+ threshold: this.settingsManager.get("compactThreshold"),
1018
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
1019
+ accountId: creds?.accountId,
1020
+ approvedPlanPath: this.approvedPlanPath,
1021
+ });
1022
+ let activeTokens;
1023
+ if (this.providerContext) {
1024
+ const anchorIndex = this.messages.lastIndexOf(this.providerContext.anchor);
1025
+ if (anchorIndex >= 0) {
1026
+ activeTokens = calculateActiveContextTokens(this.messages, {
1027
+ usage: this.providerContext.usage,
1028
+ pendingMessages: this.messages.slice(anchorIndex + 1),
1029
+ });
1030
+ }
1031
+ else {
1032
+ this.providerContext = null;
1033
+ }
1034
+ }
1035
+ log("INFO", "compaction", "Pre-run compaction decision", {
1036
+ provider: this.provider,
1037
+ model: this.model,
1038
+ transport: this.compactionTransport(creds),
1039
+ contextWindow: String(contextWindow),
1040
+ activeTokens: activeTokens === undefined ? "estimated" : String(activeTokens),
1041
+ triggerLimit: String(policy.targetTokens),
1042
+ });
1043
+ if (shouldCompact(this.messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens)) {
1044
+ try {
1045
+ await this.compact(creds, "automatic");
1046
+ if (this.lastCompactionCompacted) {
1047
+ // Re-grounding hook keys off this — the context was just summarized.
1048
+ this.compactionOccurred = true;
1049
+ this.compactionRetryAfter = 0;
1050
+ }
1051
+ else {
1052
+ this.compactionRetryAfter = Date.now() + 30_000;
1053
+ }
1054
+ }
1055
+ catch (error) {
1056
+ this.compactionRetryAfter = Date.now() + 30_000;
1057
+ if (isAbortError(error) || this.opts.signal?.aborted)
1058
+ throw error;
1059
+ log("WARN", "compaction", `Pre-run compaction failed; cooling down for 30s: ${error instanceof Error ? error.message : String(error)}`);
1060
+ }
1061
+ }
1062
+ }
1063
+ }
1064
+ compactionTransport(creds) {
1065
+ if (!creds)
1066
+ return "claude_code";
1067
+ return this.provider === "openai" && creds.accountId ? "codex_oauth" : "public_api";
1068
+ }
1069
+ /** One run on the Claude subscription route: Claude Code drives the loop with our prompt and tools. */
1070
+ async runClaudeCodeLoop(process, options) {
1071
+ let loopMessages = await this.prepareDynamicContext();
1072
+ const resume = claudeCodeResumeId(this.claudeCodeSession, loopMessages);
1073
+ // A fresh Claude Code session gets our history as text; summarize it first
1074
+ // when it would not fit.
1075
+ if (!resume &&
1076
+ renderTranscript(loopMessages, Number.MAX_SAFE_INTEGER).length > CLAUDE_CODE_SEED_CHARS) {
1077
+ try {
1078
+ await this.compact(undefined, "automatic");
1079
+ }
1080
+ catch (error) {
1081
+ if (isAbortError(error) || this.opts.signal?.aborted)
1082
+ throw error;
1083
+ log("WARN", "compaction", "Summary before seeding Claude Code failed", {
1084
+ error: error instanceof Error ? error.message : String(error),
1085
+ });
1086
+ }
1087
+ loopMessages = await this.prepareDynamicContext();
1088
+ }
1089
+ let sessionId = resume;
1090
+ const title = this.sessionPreview?.trim().slice(0, 80);
1091
+ const thinking = this.planModeRef.current || options.capThinking
1092
+ ? clampThinkingForPlanMode(this.thinkingLevel)
1093
+ : this.thinkingLevel;
1094
+ const live = await this.claudeCodeLiveFor(process, loopMessages, resume, thinking, options);
1095
+ const generator = live.run(loopMessages, {
1096
+ provider: this.provider,
1097
+ model: this.model,
1098
+ tools: options.disableTools ? [] : this.tools,
1099
+ maxTurns: this.opts.maxTurns,
1100
+ thinking,
1101
+ signal: this.opts.signal,
1102
+ maxToolResultChars: resolveSessionToolResultCharLimit(this.model, this.provider, undefined),
1103
+ transformToolResult: flagUntrustedToolResult,
1104
+ ...(options.disableTools
1105
+ ? {}
1106
+ : { resolveTool: (name) => this.promoteDeferredBuiltin(name) }),
1107
+ getSteeringMessages: () => this.getHookSteeringMessages(),
1108
+ steeringAlreadyRead: (message) => this.askAnswerSteering.has(message),
1109
+ onSteeringAvailable: (listener) => {
1110
+ this.steeringListeners.add(listener);
1111
+ return () => this.steeringListeners.delete(listener);
1112
+ },
1113
+ getFollowUpMessages: () => this.getHookFollowUpMessages(),
1114
+ claudeCode: {
1115
+ ...process,
1116
+ maxSeedChars: CLAUDE_CODE_SEED_CHARS,
1117
+ ...(resume ? { resume } : {}),
1118
+ ...(title ? { title } : {}),
1119
+ onSessionId: (id) => {
1120
+ sessionId = id;
1121
+ },
1122
+ },
1123
+ });
1124
+ this.activeLoopMessages = loopMessages;
1125
+ try {
1126
+ for await (const event of generator) {
1127
+ await this.trackHookEvent(event);
1128
+ // Claude Code sends the requests, so the cache-diagnostics pass never
1129
+ // sees them; without a touch every idle chat read as an expired cache.
1130
+ if (event.type === "turn_end" && event.stopReason !== "error") {
1131
+ this.cacheDiagnostics.noteCacheTouch({
1132
+ at: Date.now(),
1133
+ provider: this.provider,
1134
+ model: this.model,
1135
+ policy: CLAUDE_CODE_CACHE_TTL,
1136
+ });
1137
+ }
1138
+ this.eventBus.forwardAgentEvent(event);
1139
+ }
1140
+ }
1141
+ finally {
1142
+ // The SDK counts maxTurns per process, so a capped session runs one process per run.
1143
+ if (live !== this.claudeCodeLive?.session)
1144
+ live.close("one-shot");
1145
+ this.activeLoopMessages = null;
1146
+ // A stopped run records unplaced messages without an event.
1147
+ this.settleDeliveredMessages(() => true);
1148
+ this.messages = loopMessages;
1149
+ for (let i = this.lastPersistedIndex; i < this.messages.length; i++) {
1150
+ await this.persistMessage(this.messages[i]);
1151
+ }
1152
+ this.lastPersistedIndex = this.messages.length;
1153
+ if (sessionId)
1154
+ await this.recordClaudeCodeSession(sessionId);
1155
+ }
1156
+ }
1157
+ /**
1158
+ * The Claude Code process for this run: the chat's live one when it holds
1159
+ * exactly our history with the same settings, else a new one (the old one is
1160
+ * closed first, so a chat never keeps two).
1161
+ */
1162
+ async claudeCodeLiveFor(process, messages, resume, thinking, options) {
1163
+ const hash = (value) => crypto.createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 16);
1164
+ const key = {
1165
+ executable: process.executable,
1166
+ cwd: process.cwd,
1167
+ model: this.model,
1168
+ system: hash(systemPrompt(messages, undefined)),
1169
+ thinking: thinking ? "on" : "off",
1170
+ tools: options.disableTools ? "off" : "on",
1171
+ };
1172
+ // Per variable, so a restart log names what moved (names only, never values).
1173
+ for (const [name, value] of Object.entries(process.env)) {
1174
+ // The SDK writes this into the daemon's env on its first query(); it sets it for the child anyway.
1175
+ if (name !== "CLAUDE_AGENT_SDK_VERSION")
1176
+ key[`env:${name}`] = hash(value);
1177
+ }
1178
+ const current = this.claudeCodeLive;
1179
+ const changed = current
1180
+ ? [...new Set([...Object.keys(key), ...Object.keys(current.key)])].filter((name) => current.key[name] !== key[name])
1181
+ : [];
1182
+ if (current &&
1183
+ changed.length === 0 &&
1184
+ current.session.alive &&
1185
+ !current.session.busy &&
1186
+ resume !== undefined &&
1187
+ resume === current.session.sessionId &&
1188
+ (await current.session.setEffort(thinking))) {
1189
+ return current.session;
1190
+ }
1191
+ this.closeClaudeCodeLive(changed.length > 0 ? `changed: ${changed.join(",")}` : "history or effort changed");
1192
+ const session = new ClaudeCodeLiveSession();
1193
+ if (!this.opts.maxTurns)
1194
+ this.claudeCodeLive = { session, key };
1195
+ return session;
1196
+ }
1197
+ closeClaudeCodeLive(reason) {
1198
+ this.claudeCodeLive?.session.close(reason);
1199
+ this.claudeCodeLive = null;
1200
+ }
1201
+ async recordClaudeCodeSession(sessionId) {
1202
+ const history = this.messages.filter((m) => m.role !== "system");
1203
+ const state = { sessionId, messageCount: history.length, anchor: history.at(-1) };
1204
+ this.claudeCodeSession = state;
1205
+ if (!this.sessionPath)
1206
+ return;
1207
+ await this.sessionManager.appendEntry(this.sessionPath, {
1208
+ type: "custom",
1209
+ kind: CLAUDE_CODE_SESSION_KIND,
1210
+ id: crypto.randomUUID(),
1211
+ parentId: null,
1212
+ timestamp: new Date().toISOString(),
1213
+ data: claudeCodeSessionEntryData(state),
1214
+ });
1215
+ }
1216
+ /** Claude Code settings when this session runs on a Claude subscription, else null. */
1217
+ claudeCodeProcess() {
1218
+ return resolveClaudeCodeProcess(this.authStorage, this.provider, this.cwd);
1219
+ }
900
1220
  /** Append a deferred built-in to the live tool list (append-only). */
901
1221
  promoteDeferredBuiltin(name) {
902
1222
  if (!this.deferredBuiltinToolNames.includes(name))
@@ -920,8 +1240,17 @@ export class AgentSession {
920
1240
  const result = await tool.execute(args, context);
921
1241
  if (when(args)) {
922
1242
  const missing = followUps.filter((name) => !this.tools.some((t) => t.name === name));
923
- if (missing.length > 0)
924
- this.tools.push(...this.mcp.promote(missing));
1243
+ const promoted = missing.length > 0 ? this.mcp.promote(missing) : [];
1244
+ if (promoted.length > 0) {
1245
+ this.tools.push(...promoted);
1246
+ // The trigger's result is where the follow-ups load (cache-safe
1247
+ // transports load them in the transcript, not the tools block).
1248
+ const structured = typeof result === "string" ? { content: result } : result;
1249
+ return {
1250
+ ...structured,
1251
+ loadedTools: [...(structured.loadedTools ?? []), ...promoted.map((t) => t.name)],
1252
+ };
1253
+ }
925
1254
  }
926
1255
  return result;
927
1256
  },
@@ -998,6 +1327,8 @@ export class AgentSession {
998
1327
  // Prompt templates remain human-originated: the user invoked the command.
999
1328
  const userMessage = { role: "user", content: slash.fullPrompt, provenance };
1000
1329
  await this.announceNewLanguages();
1330
+ if (provenance.source === "human")
1331
+ await this.deliverUserShellContext();
1001
1332
  this.messages.push(userMessage);
1002
1333
  await this.persistMessage(userMessage);
1003
1334
  this.lastPersistedIndex = this.messages.length;
@@ -1015,6 +1346,8 @@ export class AgentSession {
1015
1346
  // Push user message
1016
1347
  const userMessage = { role: "user", content, provenance };
1017
1348
  await this.announceNewLanguages();
1349
+ if (provenance.source === "human")
1350
+ await this.deliverUserShellContext();
1018
1351
  this.messages.push(userMessage);
1019
1352
  await this.persistMessage(userMessage);
1020
1353
  this.lastPersistedIndex = this.messages.length;
@@ -1044,11 +1377,16 @@ export class AgentSession {
1044
1377
  provenance: { source: "human", kind: "prompt", visibility: "transcript" },
1045
1378
  };
1046
1379
  await this.announceNewLanguages();
1380
+ await this.deliverUserShellContext();
1047
1381
  this.messages.push(userMessage);
1048
1382
  await this.persistMessage(userMessage);
1049
1383
  this.lastPersistedIndex = this.messages.length;
1050
1384
  await this.runLoop();
1051
1385
  }
1386
+ /** A typed reply's attachments as blocks for the question it answers (ask_user). */
1387
+ askReplyAttachmentParts(attachments) {
1388
+ return this.buildAttachmentParts("", attachments);
1389
+ }
1052
1390
  /**
1053
1391
  * Build the native content blocks (text + image/video notes + file notes) for
1054
1392
  * a user message with attachments. Shared by {@link promptWithAttachments} and
@@ -1113,12 +1451,24 @@ export class AgentSession {
1113
1451
  else if (a.path) {
1114
1452
  fileNotes.push(`- ${a.name} (saved at ${a.path})`);
1115
1453
  }
1454
+ else {
1455
+ // Never drop a file silently: a file-only prompt would otherwise build no
1456
+ // parts and never run.
1457
+ parts.push({
1458
+ type: "text",
1459
+ text: `[User attached a file "${a.name}" but it could not be saved, so it can't be opened.]`,
1460
+ });
1461
+ }
1116
1462
  }
1117
1463
  const textParts = [];
1118
1464
  if (text.trim())
1119
1465
  textParts.push(text.trim());
1120
1466
  if (fileNotes.length > 0) {
1121
- textParts.push(`Attached files (inspect with your tools):\n${fileNotes.join("\n")}`);
1467
+ // Without this the model unzips/greps documents through bash instead.
1468
+ const docHint = attachments.some((a) => a.kind === "file" && a.path && /\.(pdf|epub)$/i.test(a.path))
1469
+ ? "\nThe read tool opens PDF and EPUB files as text."
1470
+ : "";
1471
+ textParts.push(`Attached files (inspect with your tools):\n${fileNotes.join("\n")}${docHint}`);
1122
1472
  }
1123
1473
  if (textParts.length > 0)
1124
1474
  parts.unshift({ type: "text", text: textParts.join("\n\n") });
@@ -1204,6 +1554,9 @@ export class AgentSession {
1204
1554
  // The assistant message for this turn is now in the array.
1205
1555
  await this.flushPendingMessages();
1206
1556
  break;
1557
+ case "steering_message":
1558
+ this.settleDeliveredMessages((m) => m.content === event.content);
1559
+ break;
1207
1560
  case "checkpoint":
1208
1561
  // Tool results for this step are in the array and their side effects
1209
1562
  // already hit the filesystem. Flushing here is what makes a crash lose
@@ -1213,6 +1566,14 @@ export class AgentSession {
1213
1566
  break;
1214
1567
  }
1215
1568
  }
1569
+ /** Drop delivered queued messages and announce the new queue depth. */
1570
+ settleDeliveredMessages(delivered) {
1571
+ const before = this.deliveringQueue.length;
1572
+ this.deliveringQueue = this.deliveringQueue.filter((m) => !delivered(m));
1573
+ if (this.deliveringQueue.length !== before) {
1574
+ this.eventBus.emit("queue_drained", { count: this.userQueue.length });
1575
+ }
1576
+ }
1216
1577
  /**
1217
1578
  * Count full-file `cat` output from the step that just finished as reads, so
1218
1579
  * an edit after `cat` does not cost a second read. Uses the step's results as
@@ -1285,6 +1646,11 @@ export class AgentSession {
1285
1646
  // never been told about. The note states the facts outright rather than
1286
1647
  // referring to a section such a prompt does not have.
1287
1648
  const environmentDelta = buildEnvDeltaMessage(this.renderedEnvironment, this.promptEnvironment());
1649
+ // Plan mode toggled / plan approved mid-run: appended, never re-rendered.
1650
+ const planNotice = this.takePlanNotice();
1651
+ if (planNotice) {
1652
+ log("INFO", "session", "Injecting plan state update instead of rebuilding the prompt");
1653
+ }
1288
1654
  if (environmentDelta) {
1289
1655
  // The model has now been told; only a further change re-triggers this.
1290
1656
  this.renderedEnvironment = this.promptEnvironment();
@@ -1321,11 +1687,9 @@ export class AgentSession {
1321
1687
  // agent sees them mid-loop instead of after it stops.
1322
1688
  if (this.userQueue.length > 0) {
1323
1689
  const queued = this.userQueue.splice(0);
1324
- // The agent has now consumed these. Announce the new depth immediately so
1325
- // clients can drop the "queued" affordance at the turn boundary rather
1326
- // than holding it until the whole run ends — the message is already in
1327
- // the loop, and showing it as still-pending for minutes is a lie.
1328
- this.eventBus.emit("queue_drained", { count: this.userQueue.length });
1690
+ // `queue_drained` fires when each lands in the transcript (its
1691
+ // steering_message event), not here, so clients drop the "queued" look
1692
+ // when the agent reads it, not minutes later at run end.
1329
1693
  // Frame each queued item as concurrent steering — without this wrapper
1330
1694
  // the model treats a mid-run message as a fresh request that supersedes
1331
1695
  // the original task and silently drops it. ONE message per queued item
@@ -1348,15 +1712,25 @@ export class AgentSession {
1348
1712
  ];
1349
1713
  return { role: "user", content: parts, provenance };
1350
1714
  });
1715
+ steeringMessages.forEach((message, index) => {
1716
+ const { id, text, answeredAsk } = queued[index];
1717
+ if (answeredAsk)
1718
+ this.askAnswerSteering.add(message);
1719
+ this.deliveringQueue.push({ id, text, content: message.content });
1720
+ });
1721
+ const userShell = this.takeUserShellContext();
1351
1722
  return [
1352
1723
  ...(environmentDelta ? [environmentDelta] : []),
1724
+ ...(planNotice ? [planNotice] : []),
1725
+ ...(userShell ? [userShell] : []),
1353
1726
  ...steeringMessages,
1354
1727
  ...(notificationMessage ? [notificationMessage] : []),
1355
1728
  ];
1356
1729
  }
1357
- if (environmentDelta || notificationMessage) {
1730
+ if (environmentDelta || planNotice || notificationMessage) {
1358
1731
  return [
1359
1732
  ...(environmentDelta ? [environmentDelta] : []),
1733
+ ...(planNotice ? [planNotice] : []),
1360
1734
  ...(notificationMessage ? [notificationMessage] : []),
1361
1735
  ];
1362
1736
  }
@@ -1450,6 +1824,23 @@ export class AgentSession {
1450
1824
  throw new Error("Active model has no confirmed image support");
1451
1825
  signal.throwIfAborted();
1452
1826
  try {
1827
+ const claudeCode = await this.claudeCodeProcess();
1828
+ if (claudeCode) {
1829
+ const response = await claudeCodeComplete({
1830
+ ...claudeCode,
1831
+ model,
1832
+ messages: [
1833
+ { role: "system", content: request.instruction },
1834
+ { role: "user", content: [{ type: "text", text: request.context }, ...request.images] },
1835
+ ],
1836
+ thinking,
1837
+ signal,
1838
+ });
1839
+ const text = assistantText(response.message.content);
1840
+ if (text.length > 32_768)
1841
+ throw new Error("Review response exceeded its limit");
1842
+ return { text, model, provider, thinking };
1843
+ }
1453
1844
  const creds = await this.authStorage.resolveCredentials(provider, {
1454
1845
  storageKeys: this.currentAuthStorageKeys(),
1455
1846
  });
@@ -1497,6 +1888,16 @@ export class AgentSession {
1497
1888
  * cheaper routing: judging a model's own failure patterns with a weaker
1498
1889
  * model swaps false negatives for false positives. */
1499
1890
  async callSemanticLoopJudge(prompt) {
1891
+ const claudeCode = await this.claudeCodeProcess();
1892
+ if (claudeCode) {
1893
+ const response = await withJudgeTimeout(claudeCodeComplete({
1894
+ ...claudeCode,
1895
+ model: this.model,
1896
+ messages: [{ role: "user", content: prompt }],
1897
+ signal: this.opts.signal,
1898
+ }), SEMANTIC_LOOP_JUDGE_TIMEOUT_MS);
1899
+ return assistantText(response.message.content);
1900
+ }
1500
1901
  const creds = await this.authStorage.resolveCredentials(this.provider, {
1501
1902
  storageKeys: this.currentAuthStorageKeys(),
1502
1903
  });
@@ -1607,19 +2008,26 @@ export class AgentSession {
1607
2008
  },
1608
2009
  ]
1609
2010
  : [];
1610
- const childCompletionFollowUp = buildSubAgentCompletionFollowUp(this.subAgentManager);
1611
- if (childCompletionFollowUp)
1612
- return [...diagnosticMessages, ...childCompletionFollowUp];
2011
+ const childCompletionFollowUp = buildSubAgentCompletionFollowUp(this.subAgentManager) ?? [];
1613
2012
  // Background processes started this run and never read block completion:
1614
2013
  // their progress/exit checkpoints only land on the steering path, which an
1615
- // agent about to stop never reaches.
1616
- const processFollowUp = buildProcessCompletionFollowUp(this.processManager?.list() ?? [], this.runStartedAt, this.processGateInjected);
1617
- if (processFollowUp) {
2014
+ // agent about to stop never reaches. Sent in the same follow-up as the
2015
+ // child-agent gate: one forced turn can collect both, where returning them
2016
+ // one per stop cost a separate model round-trip each.
2017
+ const processFollowUp = buildProcessCompletionFollowUp(this.processManager?.list() ?? [], this.runStartedAt, this.processGateInjected) ?? [];
2018
+ if (processFollowUp.length > 0) {
1618
2019
  this.processGateInjected += 1;
1619
2020
  log("INFO", "process-gate", "Injecting background-process completion gate", {
1620
2021
  injected: String(this.processGateInjected),
1621
2022
  });
1622
- return [...diagnosticMessages, ...processFollowUp];
2023
+ }
2024
+ // Child agents and background processes ride one forced turn together
2025
+ // (with any diagnostics). Diagnostics alone fall through, so the
2026
+ // verification gate below can join them in that same turn.
2027
+ if (childCompletionFollowUp.length > 0 || processFollowUp.length > 0) {
2028
+ const gateMessages = mergeCompletionGateFollowUps(diagnosticMessages, childCompletionFollowUp, processFollowUp);
2029
+ if (gateMessages)
2030
+ return gateMessages;
1623
2031
  }
1624
2032
  // A check whose exit status could not count (`npm test | tail; node -e …`)
1625
2033
  // is re-run on its own before the gate decides, so a passing run is not
@@ -1794,6 +2202,16 @@ export class AgentSession {
1794
2202
  .reverse()
1795
2203
  .find((m) => m.role === "user" && m.provenance?.kind !== "notification");
1796
2204
  this.resetHookState(requestTextForRegrounding(lastUser));
2205
+ // A Claude subscription only connects through Claude Code; compaction stays ours.
2206
+ const claudeCode = await this.claudeCodeProcess();
2207
+ if (claudeCode) {
2208
+ await this.maybeCompactPreRun();
2209
+ await this.runClaudeCodeLoop(claudeCode, options);
2210
+ this.maybeCompactPostTurn();
2211
+ return;
2212
+ }
2213
+ // Left the Claude subscription route (provider switch, sign-out).
2214
+ this.closeClaudeCodeLive("route changed");
1797
2215
  // Resolve OAuth credentials and run agent loop.
1798
2216
  // On 401, force-refresh the token and retry once — the provider may have
1799
2217
  // revoked the token server-side before the stored expiry (e.g. after a restart).
@@ -1809,72 +2227,9 @@ export class AgentSession {
1809
2227
  let lastResolvedAccessToken = creds.accessToken;
1810
2228
  // Auto-compact if needed. This must happen after credential resolution so
1811
2229
  // OpenAI OAuth/Codex sessions use the Codex product context window instead
1812
- // of the public API model window. Failed/no-op attempts cool down across
1813
- // prompts; provider overflow recovery still bypasses this path entirely.
1814
- if (this.settingsManager.get("autoCompact") && Date.now() >= this.compactionRetryAfter) {
1815
- // A post-turn compaction may still be running in the background. Let it
1816
- // settle first: it usually already compacted this history, so the
1817
- // decision below turns into a no-op instead of duplicate work.
1818
- if (this.postTurnCompaction)
1819
- await this.postTurnCompaction;
1820
- const contextWindow = getContextWindow(this.model, {
1821
- provider: this.provider,
1822
- accountId: creds.accountId,
1823
- });
1824
- const policy = resolveCompactionPolicy({
1825
- provider: this.provider,
1826
- model: this.model,
1827
- contextWindow,
1828
- threshold: this.settingsManager.get("compactThreshold"),
1829
- accountId: creds.accountId,
1830
- approvedPlanPath: this.approvedPlanPath,
1831
- });
1832
- let activeTokens;
1833
- if (this.providerContext) {
1834
- const anchorIndex = this.messages.lastIndexOf(this.providerContext.anchor);
1835
- if (anchorIndex >= 0) {
1836
- activeTokens = calculateActiveContextTokens(this.messages, {
1837
- usage: this.providerContext.usage,
1838
- pendingMessages: this.messages.slice(anchorIndex + 1),
1839
- });
1840
- }
1841
- else {
1842
- this.providerContext = null;
1843
- }
1844
- }
1845
- log("INFO", "compaction", "Pre-run compaction decision", {
1846
- provider: this.provider,
1847
- model: this.model,
1848
- transport: this.provider === "openai" && creds.accountId ? "codex_oauth" : "public_api",
1849
- contextWindow: String(contextWindow),
1850
- activeTokens: activeTokens === undefined ? "estimated" : String(activeTokens),
1851
- triggerLimit: String(policy.targetTokens),
1852
- });
1853
- if (shouldCompact(this.messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens)) {
1854
- try {
1855
- await this.compact(creds, "automatic");
1856
- if (this.lastCompactionCompacted) {
1857
- // Re-grounding hook keys off this — the context was just summarized.
1858
- this.compactionOccurred = true;
1859
- this.compactionRetryAfter = 0;
1860
- }
1861
- else {
1862
- this.compactionRetryAfter = Date.now() + 30_000;
1863
- }
1864
- }
1865
- catch (error) {
1866
- this.compactionRetryAfter = Date.now() + 30_000;
1867
- if (isAbortError(error) || this.opts.signal?.aborted)
1868
- throw error;
1869
- log("WARN", "compaction", `Pre-run compaction failed; cooling down for 30s: ${error instanceof Error ? error.message : String(error)}`);
1870
- }
1871
- }
1872
- }
1873
- // Reassigned when Anthropic rejects the turn for being below a model's
1874
- // minimum Claude Code version; the retry below rebuilds it from the floor
1875
- // that rejection taught us. The anthropic client cache is keyed on the UA,
1876
- // so the new value transparently yields a correctly-identified client.
1877
- let userAgent = this.provider === "anthropic" ? await getClaudeCliUserAgent() : undefined;
2230
+ // of the public API model window.
2231
+ await this.maybeCompactPreRun(creds);
2232
+ const userAgent = this.provider === "anthropic" ? await getClaudeCliUserAgent() : undefined;
1878
2233
  const loopMessages = await this.prepareDynamicContext();
1879
2234
  // Re-read every run so rule-file edits apply on the next turn; a few small files.
1880
2235
  const streamRules = await loadStreamRules(this.cwd);
@@ -1887,6 +2242,7 @@ export class AgentSession {
1887
2242
  provider: this.provider,
1888
2243
  model: this.model,
1889
2244
  tools: options.disableTools ? [] : this.tools,
2245
+ ...(options.disableTools ? {} : { deferredTools: this.deferredToolCatalog }),
1890
2246
  webSearch: options.disableTools ? false : () => this.nativeWebSearchOn(),
1891
2247
  maxTokens: this.requestMaxTokens(accountId),
1892
2248
  maxTurns: this.opts.maxTurns,
@@ -1899,6 +2255,7 @@ export class AgentSession {
1899
2255
  thinking: this.planModeRef.current || options.capThinking
1900
2256
  ? clampThinkingForPlanMode(this.thinkingLevel)
1901
2257
  : this.thinkingLevel,
2258
+ ...(modelInfo?.thinkingLevels ? { thinkingLevels: modelInfo.thinkingLevels } : {}),
1902
2259
  apiKey,
1903
2260
  // Per-turn credential resolution. A run can span many minutes; if any
1904
2261
  // process sharing auth.json refreshes this grant meanwhile, the token
@@ -1949,10 +2306,15 @@ export class AgentSession {
1949
2306
  promptCacheKey: this.getPromptCacheKey(),
1950
2307
  },
1951
2308
  });
1952
- log("INFO", "cache", "Prepared context", {
1953
- sessionId: this.sessionId || this.transportSessionId,
1954
- data: JSON.stringify(report),
1955
- });
2309
+ // "Context cache outcome" (persistTurnMetric) repeats this whole report
2310
+ // with usage attached, so only log the prepared report on its own when
2311
+ // it carries a cache-relevant change or risk worth seeing pre-response.
2312
+ if (report.changes.length > 0 || report.thinkingPrefixRiskBlocks > 0) {
2313
+ log("INFO", "cache", "Prepared context", {
2314
+ sessionId: this.sessionId || this.transportSessionId,
2315
+ data: JSON.stringify(report),
2316
+ });
2317
+ }
1956
2318
  if (report.thinkingPrefixRiskBlocks > 0) {
1957
2319
  log("WARN", "cache", "Possible signed-thinking prefix mismatch; not server verified", {
1958
2320
  sessionId: this.sessionId || this.transportSessionId,
@@ -2015,6 +2377,7 @@ export class AgentSession {
2015
2377
  model: this.model,
2016
2378
  contextWindow,
2017
2379
  threshold: this.settingsManager.get("compactThreshold"),
2380
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
2018
2381
  accountId,
2019
2382
  approvedPlanPath: this.approvedPlanPath,
2020
2383
  });
@@ -2041,7 +2404,10 @@ export class AgentSession {
2041
2404
  // anchors; drop the retained usage afterwards since it counted the
2042
2405
  // pruned content.
2043
2406
  if (shouldPruneToolResults(activeTokens, policy.targetTokens)) {
2044
- const pruneResult = pruneStaleToolResults(messages);
2407
+ const cacheCold = this.getCacheExpiryStatus()?.expired ?? false;
2408
+ const pruneResult = pruneStaleToolResults(messages, {
2409
+ minimumTokens: pruneMinimumTokens(activeTokens, cacheCold),
2410
+ });
2045
2411
  if (pruneResult.pruned) {
2046
2412
  this.cacheDiagnostics.noteEdit("tool_prune", pruneResult.freedTokens);
2047
2413
  this.providerContext = null;
@@ -2064,6 +2430,8 @@ export class AgentSession {
2064
2430
  // An approved plan runs as ONE run, so step boundaries are only
2065
2431
  // visible here, between model steps — not after the run ends.
2066
2432
  const planStep = this.observePlanStepProgress(messages, contextWindow, activeTokens);
2433
+ // The decision line carries the outcome (compact=) next to its inputs.
2434
+ const overLimit = shouldCompact(messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens);
2067
2435
  log("INFO", "compaction", "In-flight compaction decision", {
2068
2436
  provider: this.provider,
2069
2437
  model: this.model,
@@ -2071,10 +2439,10 @@ export class AgentSession {
2071
2439
  contextWindow: String(contextWindow),
2072
2440
  activeTokens: String(activeTokens),
2073
2441
  triggerLimit: String(policy.targetTokens),
2442
+ compact: String(overLimit || Boolean(planStep?.compact)),
2074
2443
  ...(planStep ? { planStep: `${planStep.compact} (${planStep.reason})` } : {}),
2075
2444
  });
2076
- if (!shouldCompact(messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens) &&
2077
- !planStep?.compact)
2445
+ if (!overLimit && !planStep?.compact)
2078
2446
  return messages;
2079
2447
  }
2080
2448
  // compact() operates on this.messages, while an earlier transform may
@@ -2116,6 +2484,7 @@ export class AgentSession {
2116
2484
  }
2117
2485
  finally {
2118
2486
  this.activeLoopMessages = null;
2487
+ this.settleDeliveredMessages(() => true);
2119
2488
  // An in-flight compaction rebinds `this.messages` to the compacted array
2120
2489
  // while the loop keeps appending to `loopMessages`. Resync on every exit
2121
2490
  // — a failed or aborted run included — or the session silently drops
@@ -2133,8 +2502,9 @@ export class AgentSession {
2133
2502
  // fallback key, not the model's first preference).
2134
2503
  const badKey = (await this.authStorage.pickStorageKey(this.currentAuthStorageKeys())) ??
2135
2504
  this.currentAuthStorageKeys()[0];
2136
- log("WARN", "auth", `Got 401 for ${this.provider} (${badKey}) — API key is invalid or revoked`);
2137
- await this.authStorage.clearCredentials(badKey);
2505
+ const cleared = await this.authStorage.clearRejectedApiKey(badKey);
2506
+ log("WARN", "auth", `Got 401 for ${this.provider} (${badKey}) — ` +
2507
+ (cleared ? "API key is invalid or revoked" : "key rejected, kept on file"));
2138
2508
  return true;
2139
2509
  };
2140
2510
  try {
@@ -2195,17 +2565,22 @@ export class AgentSession {
2195
2565
  throw fallbackErr;
2196
2566
  }
2197
2567
  }
2198
- else if (this.provider === "anthropic" &&
2199
- err instanceof ProviderError &&
2200
- recordRequiredClaudeCodeVersion(err.message)) {
2201
- // Anthropic gates newly released models on a minimum Claude Code
2202
- // version and names it in the rejection. That message is more current
2203
- // than the npm registry can be at launch, so the floor it just taught
2204
- // us is authoritative: rebuild the spoofed User-Agent from it and retry
2205
- // this turn instead of making the user wait out a cache TTL.
2206
- userAgent = await getClaudeCliUserAgent();
2207
- log("INFO", "auth", `Retrying turn as ${userAgent}`);
2208
- await runAgentLoop(creds.accessToken, creds.accountId, creds.projectId);
2568
+ else if (err instanceof ProviderError &&
2569
+ err.statusCode === 401 &&
2570
+ !this.baseUrl &&
2571
+ (await this.authStorage.relocateRegionalApiKey(this.currentAuthStorageKeys()))) {
2572
+ // The key was valid all along, just sent to another region's cluster.
2573
+ creds = await this.authStorage.resolveCredentials(this.provider, {
2574
+ storageKeys: this.currentAuthStorageKeys(),
2575
+ });
2576
+ this.lastAccountId = creds.accountId;
2577
+ try {
2578
+ await runAgentLoop(creds.accessToken, creds.accountId, creds.projectId);
2579
+ }
2580
+ catch (retryErr) {
2581
+ await clearInvalidStaticApiKey(retryErr);
2582
+ throw retryErr;
2583
+ }
2209
2584
  }
2210
2585
  else if (err instanceof ProviderError && err.statusCode === 401) {
2211
2586
  // Static API-key providers (GLM, Moonshot API key, etc.) have no refresh
@@ -2280,6 +2655,8 @@ export class AgentSession {
2280
2655
  // booted on e.g. Kimi (256K) keeps sending that cap after switching to a
2281
2656
  // smaller model (Opus 128K), which the provider rejects.
2282
2657
  this.maxTokens = this.resolveMaxTokens(model);
2658
+ if (changed)
2659
+ this.preconnect();
2283
2660
  this.eventBus.emit("model_change", {
2284
2661
  provider: this.provider,
2285
2662
  model: this.model,
@@ -2317,25 +2694,15 @@ export class AgentSession {
2317
2694
  }
2318
2695
  // Update provider-specific tools when provider changes
2319
2696
  if (provider && provider !== prevProvider) {
2320
- // Add/remove client-side web_search tool based on provider.
2321
- // Anthropic has native server-side web search; all other providers need the client tool.
2697
+ // The client web_search tool serves every provider (on Anthropic it
2698
+ // runs the native search as a side request), so a switch only adds it
2699
+ // when an untiered session lacks it.
2322
2700
  const hasWebSearch = this.tools.some((t) => t.name === "web_search");
2323
- if (this.deferredBuiltinToolNames.includes("web_search")) {
2324
- // Tiered: the client tool lives in the catalog for every provider and,
2325
- // once promoted, is swapped for the native server tool by the Anthropic
2326
- // transport. Nothing to add or remove — doing so would either load the
2327
- // schema eagerly or take away a capability the model already has.
2328
- }
2329
- else if (this.provider === "anthropic" && hasWebSearch) {
2330
- // Switching TO anthropic — remove client-side web_search (server-side handles it)
2331
- this.tools = this.tools.filter((t) => t.name !== "web_search");
2332
- }
2333
- else if (this.provider !== "anthropic" && !hasWebSearch) {
2334
- // Switching FROM anthropic — add client-side web_search
2701
+ if (!this.deferredBuiltinToolNames.includes("web_search") && !hasWebSearch) {
2335
2702
  this.tools.push(createWebSearchTool(() => ({
2336
2703
  mode: this.settingsManager.get("networkMode"),
2337
2704
  allow: this.settingsManager.get("networkAllow"),
2338
- })));
2705
+ }), (request) => this.runSideWebSearch(request)));
2339
2706
  }
2340
2707
  // Reconnect MCP servers ONLY when GLM is involved on either side — GLM
2341
2708
  // is the only provider with a different server set (Z.AI tools), so a
@@ -2589,7 +2956,7 @@ export class AgentSession {
2589
2956
  return;
2590
2957
  const contextWindow = getContextWindow(this.model, {
2591
2958
  provider: this.provider,
2592
- accountId: creds.accountId,
2959
+ accountId: creds?.accountId,
2593
2960
  });
2594
2961
  // One compaction per turn boundary: a pre-run, in-flight or overflow
2595
2962
  // compaction already shrank this run's history — re-probing right after
@@ -2604,7 +2971,8 @@ export class AgentSession {
2604
2971
  model: this.model,
2605
2972
  contextWindow,
2606
2973
  threshold: this.settingsManager.get("compactThreshold"),
2607
- accountId: creds.accountId,
2974
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
2975
+ accountId: creds?.accountId,
2608
2976
  approvedPlanPath: this.approvedPlanPath,
2609
2977
  });
2610
2978
  let activeTokens;
@@ -2625,14 +2993,16 @@ export class AgentSession {
2625
2993
  trigger: planStep?.compact ? `plan-step (${planStep.reason})` : "size",
2626
2994
  provider: this.provider,
2627
2995
  model: this.model,
2628
- transport: this.provider === "openai" && creds.accountId ? "codex_oauth" : "public_api",
2996
+ transport: this.compactionTransport(creds),
2629
2997
  contextWindow: String(contextWindow),
2630
2998
  activeTokens: activeTokens === undefined ? "estimated" : String(activeTokens),
2631
2999
  triggerLimit: String(policy.targetTokens),
2632
3000
  });
3001
+ const postTurnAbort = new AbortController();
3002
+ this.postTurnCompactionAbort = postTurnAbort;
2633
3003
  this.postTurnCompaction = (async () => {
2634
3004
  try {
2635
- await this.compact(creds, "automatic");
3005
+ await this.compact(creds, "automatic", undefined, postTurnAbort.signal);
2636
3006
  if (this.lastCompactionCompacted) {
2637
3007
  // Arm re-grounding for the next turn. resetHookState clears
2638
3008
  // compactionOccurred at run start, before the injection point, so
@@ -2652,17 +3022,27 @@ export class AgentSession {
2652
3022
  }
2653
3023
  finally {
2654
3024
  this.postTurnCompaction = undefined;
3025
+ if (this.postTurnCompactionAbort === postTurnAbort)
3026
+ this.postTurnCompactionAbort = undefined;
2655
3027
  }
2656
3028
  })();
2657
3029
  }
2658
3030
  async compact(existingCredentials, mode = "manual",
2659
3031
  /** User-stated focus (`/compact <focus>`): what must survive verbatim. */
2660
- focus) {
3032
+ focus,
3033
+ /** Extra abort source (post-turn compaction, cancelled by dispose). */
3034
+ abortSignal) {
2661
3035
  this.lastCompactionCompacted = false;
3036
+ const compactionSignal = abortSignal && this.opts.signal
3037
+ ? AbortSignal.any([this.opts.signal, abortSignal])
3038
+ : (abortSignal ?? this.opts.signal);
3039
+ const claudeCode = existingCredentials ? null : await this.claudeCodeProcess();
2662
3040
  const creds = existingCredentials ??
2663
- (await this.authStorage.resolveCredentials(this.provider, {
2664
- storageKeys: this.currentAuthStorageKeys(),
2665
- }));
3041
+ (claudeCode
3042
+ ? { accessToken: "" }
3043
+ : await this.authStorage.resolveCredentials(this.provider, {
3044
+ storageKeys: this.currentAuthStorageKeys(),
3045
+ }));
2666
3046
  const contextWindow = getContextWindow(this.model, {
2667
3047
  provider: this.provider,
2668
3048
  accountId: creds.accountId,
@@ -2672,6 +3052,7 @@ export class AgentSession {
2672
3052
  model: this.model,
2673
3053
  contextWindow,
2674
3054
  threshold: this.settingsManager.get("compactThreshold"),
3055
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
2675
3056
  accountId: creds.accountId,
2676
3057
  approvedPlanPath: this.approvedPlanPath,
2677
3058
  });
@@ -2689,9 +3070,14 @@ export class AgentSession {
2689
3070
  baseUrl: this.baseUrl ?? creds.baseUrl,
2690
3071
  contextWindow,
2691
3072
  targetTokens: policy.targetTokens,
2692
- signal: this.opts.signal,
3073
+ signal: compactionSignal,
2693
3074
  approvedPlanPath: this.approvedPlanPath,
2694
3075
  focus,
3076
+ ...(claudeCode
3077
+ ? {
3078
+ complete: (req) => claudeCodeComplete({ ...claudeCode, ...req }),
3079
+ }
3080
+ : {}),
2695
3081
  });
2696
3082
  contextSelection = output.result.contextSelection;
2697
3083
  return output;
@@ -2710,7 +3096,7 @@ export class AgentSession {
2710
3096
  }
2711
3097
  else {
2712
3098
  const conversationId = this.conversationId;
2713
- await this.sessionManager.withCompactionLease(conversationId, this.opts.signal, async () => {
3099
+ await this.sessionManager.withCompactionLease(conversationId, compactionSignal, async () => {
2714
3100
  let sourceFingerprint = computeSourceFingerprint(this.messages);
2715
3101
  const canonicalPath = await this.sessionManager.resolveCanonicalSession(conversationId, this.cwd);
2716
3102
  if (canonicalPath && canonicalPath !== this.sessionPath) {
@@ -2816,6 +3202,7 @@ export class AgentSession {
2816
3202
  // into the fresh session (e.g. an accepted plan's build would inherit the
2817
3203
  // whole planning conversation and lose the approved-plan prompt).
2818
3204
  await this.settlePostTurnCompaction();
3205
+ this.closeClaudeCodeLive("new session");
2819
3206
  this.cacheDiagnostics.reset();
2820
3207
  // Approved-plan execution is a clean checkpoint of the same conversation;
2821
3208
  // explicit new sessions reset the conversation identity.
@@ -2863,6 +3250,7 @@ export class AgentSession {
2863
3250
  this.eventBus.emit("session_start", { sessionId: this.sessionId });
2864
3251
  }
2865
3252
  async loadSession(sessionPath) {
3253
+ this.closeClaudeCodeLive("session loaded");
2866
3254
  await this.loadExistingSession(sessionPath);
2867
3255
  this.cacheDiagnostics.reset();
2868
3256
  if (this.sessionId)
@@ -2916,6 +3304,10 @@ export class AgentSession {
2916
3304
  this.setSessionPath(loaded.path);
2917
3305
  return this.sessionManager.listBranches(loaded.entries);
2918
3306
  }
3307
+ /** The session's first user-authored prompt, or "" before there is one. */
3308
+ getSessionPreview() {
3309
+ return this.sessionPreview;
3310
+ }
2919
3311
  /** Skills the safety scan kept out of this session, for the app/CLI to show. */
2920
3312
  getBlockedSkills() {
2921
3313
  return this.blockedSkills;
@@ -3103,17 +3495,57 @@ export class AgentSession {
3103
3495
  /** Queue a user message (optionally with attachments) to be injected mid-run
3104
3496
  * as steering. Returns the new queue length. No-op semantics are the caller's
3105
3497
  * concern. */
3106
- queueMessage(text, attachments = []) {
3498
+ queueMessage(text, attachments = [], opts = {}) {
3107
3499
  this.queueSeq += 1;
3108
- this.userQueue.push({ id: `q${this.queueSeq}`, text, attachments });
3500
+ this.userQueue.push({
3501
+ id: `q${this.queueSeq}`,
3502
+ text,
3503
+ attachments,
3504
+ ...(opts.answeredAsk ? { answeredAsk: true } : {}),
3505
+ });
3109
3506
  // Instant interrupt: preempt running tools so the steer lands right away.
3110
3507
  for (const listener of [...this.steeringListeners])
3111
3508
  listener();
3112
3509
  return this.userQueue.length;
3113
3510
  }
3114
- /** Pending queued messages (id + text), oldest first, for client display. */
3511
+ /**
3512
+ * Hold the output of a command the user ran themselves (`!cmd` in the app)
3513
+ * so it reaches the agent with their next message: a prompt, or a message
3514
+ * queued as steering. Never on its own, and never mid-run without one.
3515
+ */
3516
+ addUserShellContext(runId, text) {
3517
+ if (text.trim())
3518
+ this.pendingUserShell.push({ runId, text });
3519
+ }
3520
+ /** Run ids of user commands still waiting for the next message. */
3521
+ getPendingUserShellRunIds() {
3522
+ return this.pendingUserShell.map((entry) => entry.runId);
3523
+ }
3524
+ takeUserShellContext() {
3525
+ if (this.pendingUserShell.length === 0)
3526
+ return null;
3527
+ const blocks = this.pendingUserShell.splice(0).map((entry) => entry.text);
3528
+ return {
3529
+ role: "user",
3530
+ content: buildUserShellContextText(blocks),
3531
+ provenance: { source: "runtime", kind: "notification", visibility: "hidden" },
3532
+ };
3533
+ }
3534
+ /** Persist pending user command output just ahead of the human message. */
3535
+ async deliverUserShellContext() {
3536
+ const message = this.takeUserShellContext();
3537
+ if (!message)
3538
+ return;
3539
+ this.messages.push(message);
3540
+ await this.persistMessage(message);
3541
+ }
3542
+ /** Pending queued messages (id + text), oldest first, for client display.
3543
+ * `delivering` ones are already with the agent and can no longer be cancelled. */
3115
3544
  listQueuedMessages() {
3116
- return this.userQueue.map((m) => ({ id: m.id, text: m.text }));
3545
+ return [
3546
+ ...this.deliveringQueue.map((m) => ({ id: m.id, text: m.text, delivering: true })),
3547
+ ...this.userQueue.map((m) => ({ id: m.id, text: m.text })),
3548
+ ];
3117
3549
  }
3118
3550
  /** Cancel one pending message by id. Returns true if it was still queued.
3119
3551
  * A false return is the normal race rather than an error: the message drained
@@ -3250,6 +3682,8 @@ export class AgentSession {
3250
3682
  */
3251
3683
  stopBackgroundProcesses() {
3252
3684
  this.processManager?.shutdownAll();
3685
+ // Synchronous, so app quit stops Claude Code even when later teardown hangs.
3686
+ this.closeClaudeCodeLive("shutdown");
3253
3687
  }
3254
3688
  /** Replace a host-owned system prompt in place without resetting conversation history. */
3255
3689
  setCustomSystemPrompt(systemPrompt, promptCacheKeyPrefix) {
@@ -3283,7 +3717,7 @@ export class AgentSession {
3283
3717
  // is about to be drafted); exiting keeps it (set explicitly via accept).
3284
3718
  if (active)
3285
3719
  this.approvedPlanPath = undefined;
3286
- await this.rebuildSystemPromptInPlace();
3720
+ await this.applyPlanStateChange();
3287
3721
  }
3288
3722
  /**
3289
3723
  * Bake an approved plan into the system prompt so the model is told to emit
@@ -3293,7 +3727,48 @@ export class AgentSession {
3293
3727
  */
3294
3728
  async setApprovedPlan(approvedPlanPath) {
3295
3729
  this.approvedPlanPath = approvedPlanPath;
3296
- await this.rebuildSystemPromptInPlace();
3730
+ await this.applyPlanStateChange();
3731
+ }
3732
+ /**
3733
+ * Before the conversation starts, render plan state into the prompt. After,
3734
+ * the prompt is a cached prefix: queue an appended notice instead, so the
3735
+ * cached bytes stay identical (a rebuild re-sent the whole history).
3736
+ */
3737
+ async applyPlanStateChange() {
3738
+ if (this.customSystemPrompt || this.agentPrompt !== undefined)
3739
+ return;
3740
+ if (!this.messages.some((message) => message.role !== "system")) {
3741
+ this.pendingPlanNotice = null;
3742
+ await this.rebuildSystemPromptInPlace();
3743
+ return;
3744
+ }
3745
+ const state = {
3746
+ planMode: this.planModeRef.current,
3747
+ approvedPlanPath: this.approvedPlanPath,
3748
+ };
3749
+ const message = await buildPlanStateMessage(this.seenPlanState, state, [
3750
+ ...this.tools.map((t) => t.name),
3751
+ ...this.deferredBuiltinToolNames,
3752
+ ]);
3753
+ this.pendingPlanNotice = message ? { message, state } : null;
3754
+ }
3755
+ /** The plan notice to append now, if any (pending, or a compacted-away one). */
3756
+ takePlanNotice() {
3757
+ if (this.pendingPlanNotice) {
3758
+ const { message, state } = this.pendingPlanNotice;
3759
+ this.pendingPlanNotice = null;
3760
+ this.seenPlanState = state;
3761
+ this.lastPlanNotice = message;
3762
+ return message;
3763
+ }
3764
+ if (this.lastPlanNotice &&
3765
+ !samePlanState(this.seenPlanState, this.promptPlanState) &&
3766
+ !this.messages.includes(this.lastPlanNotice)) {
3767
+ const again = { ...this.lastPlanNotice };
3768
+ this.lastPlanNotice = again;
3769
+ return again;
3770
+ }
3771
+ return null;
3297
3772
  }
3298
3773
  /** Extra workspace roots added with `/add-dir`, in the order added. */
3299
3774
  getAdditionalRoots() {
@@ -3389,7 +3864,7 @@ export class AgentSession {
3389
3864
  const networkAllow = this.settingsManager.get("networkMode") === "allowlist"
3390
3865
  ? this.settingsManager.get("networkAllow")
3391
3866
  : [];
3392
- return { additionalRoots: this.additionalRoots, networkAllow };
3867
+ return { additionalRoots: this.additionalRoots, networkAllow, projectFiles: this.projectFiles };
3393
3868
  }
3394
3869
  /**
3395
3870
  * Build the stable system-prompt prefix for the current tool set and state.
@@ -3401,6 +3876,13 @@ export class AgentSession {
3401
3876
  async buildBasePrompt(planMode, approvedPlanPath) {
3402
3877
  if (this.customSystemPrompt)
3403
3878
  return this.customSystemPrompt;
3879
+ // Listed once: a rebuild (plan mode, /add-dir, compaction) must not churn the
3880
+ // prompt as the agent adds files.
3881
+ if (this.projectFiles === undefined) {
3882
+ const pending = this.projectFilesPending;
3883
+ this.projectFilesPending = undefined;
3884
+ this.projectFiles = await (pending ?? listProjectFiles(this.cwd));
3885
+ }
3404
3886
  const toolNames = this.tools.map((tool) => tool.name);
3405
3887
  const deferredToolNames = this.deferredToolNamesForPrompt(toolNames);
3406
3888
  // Whatever is rendered now is what the model has been told.
@@ -3438,7 +3920,7 @@ export class AgentSession {
3438
3920
  return this.messages.some((m) => m.role === "assistant");
3439
3921
  }
3440
3922
  /**
3441
- * Give the model style packs for languages that appeared after its prompt
3923
+ * Give the model verify commands for languages that appeared after its prompt
3442
3924
  * was cached (e.g. the previous task scaffolded a TypeScript project), as a
3443
3925
  * hidden message appended to the history rather than a prompt re-render that
3444
3926
  * would throw away the whole cache. Runs just before a new user message is
@@ -3446,6 +3928,13 @@ export class AgentSession {
3446
3928
  * update is saved in order with the rest of the conversation.
3447
3929
  */
3448
3930
  async announceNewLanguages() {
3931
+ const planNotice = this.takePlanNotice();
3932
+ if (planNotice) {
3933
+ this.messages.push(planNotice);
3934
+ await this.persistMessage(planNotice);
3935
+ this.lastPersistedIndex = this.messages.length;
3936
+ log("INFO", "session", "Appended plan state update instead of rebuilding the prompt");
3937
+ }
3449
3938
  if (!this.hasReply())
3450
3939
  return; // the next request rebuilds the prompt instead
3451
3940
  this.refreshActiveLanguages();
@@ -3460,7 +3949,7 @@ export class AgentSession {
3460
3949
  this.messages.push(update);
3461
3950
  await this.persistMessage(update);
3462
3951
  this.lastPersistedIndex = this.messages.length;
3463
- log("INFO", "language", "Appended style packs for new languages", {
3952
+ log("INFO", "language", "Appended verify commands for new languages", {
3464
3953
  added: [...fresh].join(","),
3465
3954
  });
3466
3955
  }
@@ -3496,7 +3985,7 @@ export class AgentSession {
3496
3985
  return false;
3497
3986
  }
3498
3987
  if (grew) {
3499
- log("INFO", "language", "Style packs active", {
3988
+ log("INFO", "language", "Languages active", {
3500
3989
  active: [...this.activeLanguages].join(","),
3501
3990
  });
3502
3991
  }
@@ -3511,6 +4000,13 @@ export class AgentSession {
3511
4000
  return;
3512
4001
  const rebuilt = await this.buildBasePrompt(this.planModeRef.current, this.approvedPlanPath);
3513
4002
  this.baseSystemPrompt = rebuilt;
4003
+ this.promptPlanState = {
4004
+ planMode: this.planModeRef.current,
4005
+ approvedPlanPath: this.approvedPlanPath,
4006
+ };
4007
+ this.seenPlanState = this.promptPlanState;
4008
+ this.pendingPlanNotice = null;
4009
+ this.lastPlanNotice = null;
3514
4010
  const content = this.withSystemPromptTail(rebuilt);
3515
4011
  if (this.messages[0]?.role === "system") {
3516
4012
  this.messages[0] = { role: "system", content };
@@ -3759,9 +4255,12 @@ export class AgentSession {
3759
4255
  // if the user switches models while credential resolution is pending.
3760
4256
  const { provider, model, thinkingLevel, baseUrl } = this;
3761
4257
  const threshold = this.settingsManager.get("compactThreshold");
3762
- const creds = await this.authStorage.resolveCredentials(provider, {
3763
- storageKeys: this.currentAuthStorageKeys(),
3764
- });
4258
+ const claudeCode = await this.claudeCodeProcess();
4259
+ const creds = claudeCode
4260
+ ? { accessToken: "" }
4261
+ : await this.authStorage.resolveCredentials(provider, {
4262
+ storageKeys: this.currentAuthStorageKeys(),
4263
+ });
3765
4264
  const maxTokens = outputCapForRequest({
3766
4265
  provider,
3767
4266
  model,
@@ -3791,6 +4290,17 @@ export class AgentSession {
3791
4290
  baseUrl: baseUrl ?? creds.baseUrl,
3792
4291
  accountId: creds.accountId,
3793
4292
  signal: this.opts.signal,
4293
+ ...(claudeCode
4294
+ ? {
4295
+ complete: (messages) => claudeCodeComplete({
4296
+ ...claudeCode,
4297
+ model,
4298
+ messages,
4299
+ thinking: thinkingLevel,
4300
+ signal: this.opts.signal,
4301
+ }),
4302
+ }
4303
+ : {}),
3794
4304
  });
3795
4305
  }
3796
4306
  /** Current reasoning/thinking level, or undefined when thinking is off. */
@@ -3818,7 +4328,38 @@ export class AgentSession {
3818
4328
  runLoopDepth = 0;
3819
4329
  lastRealRequestAt = 0;
3820
4330
  lastPrewarmAt = 0;
4331
+ /** Last connection pre-open per provider origin (see {@link preconnect}). */
4332
+ preconnectedAt = new Map();
4333
+ /**
4334
+ * Fire-and-forget: open the TLS connection to the active provider before the
4335
+ * first request, through the shared keep-alive pool. Zero tokens — an
4336
+ * unauthenticated HEAD; skipped for local endpoints and throttled per origin.
4337
+ * Transient sessions (one-shot tools) and test runs never touch the network here.
4338
+ */
4339
+ preconnect() {
4340
+ const enabled = this.opts.preconnect ?? (this.opts.transient !== true && !process.env.VITEST);
4341
+ if (!enabled)
4342
+ return;
4343
+ const provider = this.provider;
4344
+ void this.authStorage
4345
+ .resolveCredentials(provider, { storageKeys: this.currentAuthStorageKeys() })
4346
+ .then((creds) => {
4347
+ if (provider !== this.provider)
4348
+ return;
4349
+ preconnectProvider({
4350
+ provider,
4351
+ baseUrl: this.baseUrl ?? creds.baseUrl,
4352
+ accountId: creds.accountId,
4353
+ warmedAt: this.preconnectedAt,
4354
+ });
4355
+ })
4356
+ .catch(() => { });
4357
+ }
3821
4358
  prewarmController = null;
4359
+ /** Claude Code session that has seen this history (Claude subscription route). */
4360
+ claudeCodeSession = null;
4361
+ /** This chat's running Claude Code process, reused while `key` (its start settings) matches. */
4362
+ claudeCodeLive = null;
3822
4363
  /**
3823
4364
  * Best-effort Anthropic prompt-cache prewarm before the user's next turn
3824
4365
  * (desktop app calls this on the first keystroke after opening a chat or an
@@ -3827,6 +4368,11 @@ export class AgentSession {
3827
4368
  * first real reply is a cache read instead of a cold write.
3828
4369
  */
3829
4370
  async prewarm(signal) {
4371
+ // Claude Code keeps its own cache; there is no request prefix of ours to warm.
4372
+ if (await this.claudeCodeProcess().catch(() => null))
4373
+ return { ok: false, reason: "claude_code" };
4374
+ // Every provider: the user is typing, so the first request is seconds away.
4375
+ this.preconnect();
3830
4376
  if (this.provider !== "anthropic")
3831
4377
  return { ok: false, reason: "provider" };
3832
4378
  if (this.settingsManager?.get("cachePrewarm") === false) {
@@ -3885,11 +4431,13 @@ export class AgentSession {
3885
4431
  model: this.model,
3886
4432
  messages,
3887
4433
  tools: this.tools,
4434
+ deferredTools: this.deferredToolCatalog,
3888
4435
  webSearch: this.nativeWebSearchOn(),
3889
4436
  maxTokens: this.requestMaxTokens(creds.accountId),
3890
4437
  thinking: this.planModeRef.current
3891
4438
  ? clampThinkingForPlanMode(this.thinkingLevel)
3892
4439
  : this.thinkingLevel,
4440
+ ...(modelInfo?.thinkingLevels ? { thinkingLevels: modelInfo.thinkingLevels } : {}),
3893
4441
  apiKey: creds.accessToken,
3894
4442
  baseUrl: this.baseUrl ?? creds.baseUrl,
3895
4443
  accountId: creds.accountId,
@@ -3986,8 +4534,18 @@ export class AgentSession {
3986
4534
  // the background compact() snapshots and replaces `this.messages`, so
3987
4535
  // letting it run past this point would checkpoint a near-empty history
3988
4536
  // and leak a junk session file after teardown.
3989
- if (this.postTurnCompaction)
3990
- await this.postTurnCompaction;
4537
+ // Capped: a hung summary call must not hold MCP/LSP/sub-agent teardown and
4538
+ // window close hostage. Past the cap it is aborted (compact() checks the
4539
+ // signal before replacing history), with a short grace to unwind.
4540
+ if (this.postTurnCompaction) {
4541
+ const pending = this.postTurnCompaction;
4542
+ const settledInTime = await settleWithin(pending, DISPOSE_COMPACTION_WAIT_MS);
4543
+ if (!settledInTime) {
4544
+ log("WARN", "compaction", "Post-turn compaction still running at dispose — aborting");
4545
+ this.postTurnCompactionAbort?.abort();
4546
+ await settleWithin(pending, DISPOSE_COMPACTION_ABORT_GRACE_MS);
4547
+ }
4548
+ }
3991
4549
  this.cacheDiagnostics.reset();
3992
4550
  this.diagnosticsRecorder?.finalize();
3993
4551
  this.managerAbortSignal?.removeEventListener("abort", this.managerAbortHandler);
@@ -4036,14 +4594,28 @@ export class AgentSession {
4036
4594
  : await this.sessionManager.load(sessionPath);
4037
4595
  // Use the leaf from the header to walk the correct branch
4038
4596
  const loadedMessages = this.sessionManager.getMessages(loaded.entries, loaded.header.leafId);
4039
- const savedCompletionReview = [...loaded.entries]
4040
- .reverse()
4041
- .find((entry) => entry.type === "custom" && entry.kind === COMPLETION_REVIEW_STATE_KIND);
4597
+ // One backward scan for both latest host checkpoints (no full copies).
4598
+ let savedCompletionReview;
4599
+ let savedVerification;
4600
+ let savedClaudeCode;
4601
+ for (let i = loaded.entries.length - 1; i >= 0; i--) {
4602
+ if (savedCompletionReview && savedVerification && savedClaudeCode)
4603
+ break;
4604
+ const entry = loaded.entries[i];
4605
+ if (entry?.type !== "custom")
4606
+ continue;
4607
+ if (!savedClaudeCode && entry.kind === CLAUDE_CODE_SESSION_KIND) {
4608
+ savedClaudeCode = entry;
4609
+ }
4610
+ else if (!savedCompletionReview && entry.kind === COMPLETION_REVIEW_STATE_KIND) {
4611
+ savedCompletionReview = entry;
4612
+ }
4613
+ else if (!savedVerification && entry.kind === VERIFICATION_STATE_KIND) {
4614
+ savedVerification = entry;
4615
+ }
4616
+ }
4042
4617
  this.opts.completionReview?.restore(savedCompletionReview?.type === "custom" ? savedCompletionReview.data : null);
4043
4618
  this.verificationTracker.clearBackground();
4044
- const savedVerification = [...loaded.entries]
4045
- .reverse()
4046
- .find((entry) => entry.type === "custom" && entry.kind === VERIFICATION_STATE_KIND);
4047
4619
  if (savedVerification?.type === "custom") {
4048
4620
  this.verificationGate.restore(savedVerification.data);
4049
4621
  }
@@ -4083,6 +4655,7 @@ export class AgentSession {
4083
4655
  // not fail when Anthropic's stricter many-image limit activates later.
4084
4656
  const systemMsg = this.messages[0]; // Already built
4085
4657
  this.messages = [systemMsg, ...loadedMessages];
4658
+ this.claudeCodeSession = parseClaudeCodeSessionState(savedClaudeCode?.type === "custom" ? savedClaudeCode.data : null, loadedMessages);
4086
4659
  // Reads recorded for the previous conversation don't carry over.
4087
4660
  this.clearReadTracker?.();
4088
4661
  const normalizedImageCount = await normalizeMessageImages(this.messages);
@@ -4122,6 +4695,7 @@ export class AgentSession {
4122
4695
  model: this.model,
4123
4696
  contextWindow,
4124
4697
  threshold: this.settingsManager.get("compactThreshold"),
4698
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
4125
4699
  accountId: creds?.accountId,
4126
4700
  approvedPlanPath: this.approvedPlanPath,
4127
4701
  });
@@ -4228,7 +4802,9 @@ export class AgentSession {
4228
4802
  },
4229
4803
  getModelList: () => {
4230
4804
  const current = `Current: ${this.provider}:${this.model}\n\nAvailable models:\n`;
4231
- const list = MODELS.map((m) => ` ${m.provider}:${m.id} — ${m.name} (${m.costTier})`).join("\n");
4805
+ const list = getListedModels()
4806
+ .map((m) => ` ${m.provider}:${m.id} — ${m.name} (${m.costTier})`)
4807
+ .join("\n");
4232
4808
  return current + list;
4233
4809
  },
4234
4810
  quit: () => {