@draht/coding-agent 2026.9.5-1 → 2026.10.4-2

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 (1012) hide show
  1. package/CHANGELOG.md +452 -0
  2. package/dist/bun/cli.d.ts +1 -1
  3. package/dist/bun/cli.d.ts.map +1 -1
  4. package/dist/bun/cli.js +6 -3
  5. package/dist/bun/cli.js.map +1 -1
  6. package/dist/bun/sandbox-env-setup.d.ts +2 -0
  7. package/dist/bun/sandbox-env-setup.d.ts.map +1 -0
  8. package/dist/bun/sandbox-env-setup.js +4 -0
  9. package/dist/bun/sandbox-env-setup.js.map +1 -0
  10. package/dist/bundle/chunks/anthropic-messages-GAKYXF65.js +6 -0
  11. package/dist/bundle/chunks/anthropic.js +75 -0
  12. package/dist/bundle/chunks/azure-openai-responses-ZIXMK6JO.js +2 -0
  13. package/dist/bundle/chunks/bedrock-converse-stream.js +79 -0
  14. package/dist/bundle/chunks/chunk-2E5VODES.js +2 -0
  15. package/dist/bundle/chunks/chunk-2FBJKY7F.js +2 -0
  16. package/dist/bundle/chunks/chunk-2N4I6WXC.js +2 -0
  17. package/dist/bundle/chunks/chunk-5VZWYVZB.js +82 -0
  18. package/dist/bundle/chunks/chunk-63BK6WK2.js +2 -0
  19. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +6 -0
  20. package/dist/bundle/chunks/chunk-6ZJKIMU7.js +2 -0
  21. package/dist/bundle/chunks/chunk-736QBNUZ.js +12 -0
  22. package/dist/bundle/chunks/chunk-BXSHCX3G.js +11 -0
  23. package/dist/bundle/chunks/chunk-CEJJ5XF2.js +170 -0
  24. package/dist/bundle/chunks/chunk-COF5JT7R.js +4 -0
  25. package/dist/bundle/chunks/chunk-D6TMD5Q2.js +44 -0
  26. package/dist/bundle/chunks/chunk-DPE4ALPU.js +146 -0
  27. package/dist/bundle/chunks/chunk-EBVYI75P.js +2 -0
  28. package/dist/bundle/chunks/chunk-GVXA72ZA.js +2 -0
  29. package/dist/bundle/chunks/chunk-H6FT43VC.js +137 -0
  30. package/dist/bundle/chunks/chunk-HJ72RANT.js +2 -0
  31. package/dist/bundle/chunks/chunk-HTJ3L72O.js +2 -0
  32. package/dist/bundle/chunks/chunk-HZ2UHMBT.js +2 -0
  33. package/dist/bundle/chunks/chunk-I5OKY6RH.js +11 -0
  34. package/dist/bundle/chunks/chunk-IWTUBX6V.js +4 -0
  35. package/dist/bundle/chunks/chunk-KPO5375S.js +2 -0
  36. package/dist/bundle/chunks/chunk-KVH4HR57.js +31 -0
  37. package/dist/bundle/chunks/chunk-LDAOC5RB.js +18 -0
  38. package/dist/bundle/chunks/chunk-ON6XU6AG.js +2 -0
  39. package/dist/bundle/chunks/chunk-QMN7OD6G.js +2 -0
  40. package/dist/bundle/chunks/chunk-RZKPFWMH.js +42 -0
  41. package/dist/bundle/chunks/chunk-SDRCE6OP.js +2 -0
  42. package/dist/bundle/chunks/chunk-SVNWI7EV.js +8 -0
  43. package/dist/bundle/chunks/chunk-TIA2T6EO.js +3 -0
  44. package/dist/bundle/chunks/chunk-VOFPZOUQ.js +1472 -0
  45. package/dist/bundle/chunks/chunk-XBUEMKIY.js +2 -0
  46. package/dist/bundle/chunks/chunk-XOGEYN4Q.js +2 -0
  47. package/dist/bundle/chunks/chunk-ZZD35WKM.js +2 -0
  48. package/dist/bundle/chunks/cli-SR5QBZH4.js +51 -0
  49. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-MJKOAE5S.js +2 -0
  50. package/dist/bundle/chunks/codemode-worker.js +315 -0
  51. package/dist/bundle/chunks/execute-VCYDHEYA.js +328 -0
  52. package/dist/bundle/chunks/github-copilot.js +2 -0
  53. package/dist/bundle/chunks/google-antigravity.js +75 -0
  54. package/dist/bundle/chunks/google-gemini-cli.js +75 -0
  55. package/dist/bundle/chunks/google-generative-ai-RPUPQ6PM.js +2 -0
  56. package/dist/bundle/chunks/google-vertex-EZES5QVQ.js +2 -0
  57. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +13 -0
  58. package/dist/bundle/chunks/image-resize-worker.js +2 -0
  59. package/dist/bundle/chunks/jiti-loader-RKXLMQV2.js +2 -0
  60. package/dist/bundle/chunks/kimi-coding.js +2 -0
  61. package/dist/bundle/chunks/lib-XOG5PI3Y.js +9 -0
  62. package/dist/bundle/chunks/llama-cpp-classify-EJ5XMSQL.js +22 -0
  63. package/dist/bundle/chunks/meta.js +2 -0
  64. package/dist/bundle/chunks/mistral-conversations-AOYGU43Y.js +5 -0
  65. package/dist/bundle/chunks/multipart-parser-AZP5BX2W.js +3 -0
  66. package/dist/bundle/chunks/node-C2JGH2OB.js +2 -0
  67. package/dist/bundle/chunks/node-LQ52KV6B.js +16 -0
  68. package/dist/bundle/chunks/openai-chatgpt.js +75 -0
  69. package/dist/bundle/chunks/openai-codex-responses-M2Y77JEQ.js +10 -0
  70. package/dist/bundle/chunks/openai-codex.js +75 -0
  71. package/dist/bundle/chunks/openai-completions-A4OKYOYV.js +7 -0
  72. package/dist/bundle/chunks/openai-responses-6IXV53T3.js +3 -0
  73. package/dist/bundle/chunks/opencode-go.js +2 -0
  74. package/dist/bundle/chunks/openrouter-images-LYV4NKFM.js +2 -0
  75. package/dist/bundle/chunks/openrouter.js +75 -0
  76. package/dist/bundle/chunks/pi-messages-KKMEUT3Z.js +8 -0
  77. package/dist/bundle/chunks/radius.js +75 -0
  78. package/dist/bundle/chunks/runtime-6YJPGSP7.js +2 -0
  79. package/dist/bundle/chunks/settings-manager-D2EG7WDO.js +2 -0
  80. package/dist/bundle/chunks/src-TIBHS42X.js +4 -0
  81. package/dist/bundle/chunks/typesafe-system-one-YBEEY5XU.js +2 -0
  82. package/dist/bundle/chunks/virtual-modules-CBOAFAFT.js +2 -0
  83. package/dist/bundle/chunks/xai.js +75 -0
  84. package/dist/bundle/cli-runtime.js +3 -0
  85. package/dist/bundle/cli.js +5 -0
  86. package/dist/bundle/index.js +2 -0
  87. package/dist/bundle/rpc-entry.js +3 -0
  88. package/dist/cli/args.d.ts +4 -0
  89. package/dist/cli/args.d.ts.map +1 -1
  90. package/dist/cli/args.js +72 -21
  91. package/dist/cli/args.js.map +1 -1
  92. package/dist/cli/auth-check.d.ts +19 -0
  93. package/dist/cli/auth-check.d.ts.map +1 -0
  94. package/dist/cli/auth-check.js +50 -0
  95. package/dist/cli/auth-check.js.map +1 -0
  96. package/dist/cli/auth-command.d.ts +24 -0
  97. package/dist/cli/auth-command.d.ts.map +1 -0
  98. package/dist/cli/auth-command.js +103 -0
  99. package/dist/cli/auth-command.js.map +1 -0
  100. package/dist/cli/config-selector.d.ts.map +1 -1
  101. package/dist/cli/config-selector.js +3 -2
  102. package/dist/cli/config-selector.js.map +1 -1
  103. package/dist/cli/credential-print.d.ts +5 -3
  104. package/dist/cli/credential-print.d.ts.map +1 -1
  105. package/dist/cli/credential-print.js +42 -30
  106. package/dist/cli/credential-print.js.map +1 -1
  107. package/dist/cli/file-processor.d.ts +1 -1
  108. package/dist/cli/file-processor.d.ts.map +1 -1
  109. package/dist/cli/file-processor.js +2 -1
  110. package/dist/cli/file-processor.js.map +1 -1
  111. package/dist/cli/list-models.d.ts +1 -1
  112. package/dist/cli/list-models.d.ts.map +1 -1
  113. package/dist/cli/list-models.js +2 -2
  114. package/dist/cli/list-models.js.map +1 -1
  115. package/dist/cli/session-picker.d.ts +1 -1
  116. package/dist/cli/session-picker.d.ts.map +1 -1
  117. package/dist/cli/session-picker.js.map +1 -1
  118. package/dist/cli/setup.d.ts +2 -0
  119. package/dist/cli/setup.d.ts.map +1 -0
  120. package/dist/cli/setup.js +12 -0
  121. package/dist/cli/setup.js.map +1 -0
  122. package/dist/cli/startup-ui.d.ts +2 -2
  123. package/dist/cli/startup-ui.d.ts.map +1 -1
  124. package/dist/cli/startup-ui.js +42 -33
  125. package/dist/cli/startup-ui.js.map +1 -1
  126. package/dist/cli.js +3 -12
  127. package/dist/cli.js.map +1 -1
  128. package/dist/config.d.ts +20 -4
  129. package/dist/config.d.ts.map +1 -1
  130. package/dist/config.js +42 -6
  131. package/dist/config.js.map +1 -1
  132. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  133. package/dist/core/agent-session-runtime.js +12 -3
  134. package/dist/core/agent-session-runtime.js.map +1 -1
  135. package/dist/core/agent-session-services.d.ts +1 -0
  136. package/dist/core/agent-session-services.d.ts.map +1 -1
  137. package/dist/core/agent-session-services.js +14 -0
  138. package/dist/core/agent-session-services.js.map +1 -1
  139. package/dist/core/agent-session.d.ts +237 -39
  140. package/dist/core/agent-session.d.ts.map +1 -1
  141. package/dist/core/agent-session.js +1386 -565
  142. package/dist/core/agent-session.js.map +1 -1
  143. package/dist/core/auth-storage.d.ts +20 -8
  144. package/dist/core/auth-storage.d.ts.map +1 -1
  145. package/dist/core/auth-storage.js +199 -56
  146. package/dist/core/auth-storage.js.map +1 -1
  147. package/dist/core/bug-report-upload.d.ts +11 -0
  148. package/dist/core/bug-report-upload.d.ts.map +1 -0
  149. package/dist/core/bug-report-upload.js +20 -0
  150. package/dist/core/bug-report-upload.js.map +1 -0
  151. package/dist/core/bug-report.d.ts +176 -0
  152. package/dist/core/bug-report.d.ts.map +1 -0
  153. package/dist/core/bug-report.js +292 -0
  154. package/dist/core/bug-report.js.map +1 -0
  155. package/dist/core/builtins/duet.js +2 -2
  156. package/dist/core/builtins/duet.js.map +1 -1
  157. package/dist/core/cache-stats.d.ts.map +1 -1
  158. package/dist/core/cache-stats.js +12 -1
  159. package/dist/core/cache-stats.js.map +1 -1
  160. package/dist/core/cache-warmer.d.ts +103 -0
  161. package/dist/core/cache-warmer.d.ts.map +1 -0
  162. package/dist/core/cache-warmer.js +356 -0
  163. package/dist/core/cache-warmer.js.map +1 -0
  164. package/dist/core/checkpoints/checkpoint-manager.d.ts +8 -4
  165. package/dist/core/checkpoints/checkpoint-manager.d.ts.map +1 -1
  166. package/dist/core/checkpoints/checkpoint-manager.js +46 -10
  167. package/dist/core/checkpoints/checkpoint-manager.js.map +1 -1
  168. package/dist/core/checkpoints/rewind.d.ts +4 -2
  169. package/dist/core/checkpoints/rewind.d.ts.map +1 -1
  170. package/dist/core/checkpoints/rewind.js +4 -3
  171. package/dist/core/checkpoints/rewind.js.map +1 -1
  172. package/dist/core/compaction/branch-summarization.js +2 -2
  173. package/dist/core/compaction/branch-summarization.js.map +1 -1
  174. package/dist/core/compaction/compaction.d.ts +9 -6
  175. package/dist/core/compaction/compaction.d.ts.map +1 -1
  176. package/dist/core/compaction/compaction.js +196 -118
  177. package/dist/core/compaction/compaction.js.map +1 -1
  178. package/dist/core/compaction/utils.d.ts +2 -1
  179. package/dist/core/compaction/utils.d.ts.map +1 -1
  180. package/dist/core/compaction/utils.js +25 -18
  181. package/dist/core/compaction/utils.js.map +1 -1
  182. package/dist/core/crash-log.d.ts +27 -0
  183. package/dist/core/crash-log.d.ts.map +1 -0
  184. package/dist/core/crash-log.js +140 -0
  185. package/dist/core/crash-log.js.map +1 -0
  186. package/dist/core/defaults.d.ts +1 -0
  187. package/dist/core/defaults.d.ts.map +1 -1
  188. package/dist/core/defaults.js +9 -0
  189. package/dist/core/defaults.js.map +1 -1
  190. package/dist/core/experimental.js +1 -1
  191. package/dist/core/experimental.js.map +1 -1
  192. package/dist/core/export-html/template.css +10 -0
  193. package/dist/core/export-html/template.js +72 -18
  194. package/dist/core/extensions/index.d.ts +2 -2
  195. package/dist/core/extensions/index.d.ts.map +1 -1
  196. package/dist/core/extensions/index.js +1 -1
  197. package/dist/core/extensions/index.js.map +1 -1
  198. package/dist/core/extensions/jiti-loader.d.ts +2 -0
  199. package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
  200. package/dist/core/extensions/jiti-loader.js +5 -0
  201. package/dist/core/extensions/jiti-loader.js.map +1 -0
  202. package/dist/core/extensions/loader.d.ts.map +1 -1
  203. package/dist/core/extensions/loader.js +228 -89
  204. package/dist/core/extensions/loader.js.map +1 -1
  205. package/dist/core/extensions/runner.d.ts +47 -8
  206. package/dist/core/extensions/runner.d.ts.map +1 -1
  207. package/dist/core/extensions/runner.js +376 -104
  208. package/dist/core/extensions/runner.js.map +1 -1
  209. package/dist/core/extensions/types.d.ts +521 -88
  210. package/dist/core/extensions/types.d.ts.map +1 -1
  211. package/dist/core/extensions/types.js +3 -0
  212. package/dist/core/extensions/types.js.map +1 -1
  213. package/dist/core/extensions/virtual-modules.d.ts +3 -0
  214. package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
  215. package/dist/core/extensions/virtual-modules.js +37 -0
  216. package/dist/core/extensions/virtual-modules.js.map +1 -0
  217. package/dist/core/extensions/wrapper.d.ts +2 -2
  218. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  219. package/dist/core/extensions/wrapper.js +3 -22
  220. package/dist/core/extensions/wrapper.js.map +1 -1
  221. package/dist/core/footer-data-provider.d.ts +1 -1
  222. package/dist/core/footer-data-provider.js +19 -18
  223. package/dist/core/footer-data-provider.js.map +1 -1
  224. package/dist/core/index.d.ts +2 -1
  225. package/dist/core/index.d.ts.map +1 -1
  226. package/dist/core/index.js.map +1 -1
  227. package/dist/core/keybindings.d.ts +83 -13
  228. package/dist/core/keybindings.d.ts.map +1 -1
  229. package/dist/core/keybindings.js +33 -7
  230. package/dist/core/keybindings.js.map +1 -1
  231. package/dist/core/mcp-servers.d.ts +119 -0
  232. package/dist/core/mcp-servers.d.ts.map +1 -0
  233. package/dist/core/mcp-servers.js +191 -0
  234. package/dist/core/mcp-servers.js.map +1 -0
  235. package/dist/core/messages.d.ts +1 -1
  236. package/dist/core/messages.d.ts.map +1 -1
  237. package/dist/core/messages.js +1 -0
  238. package/dist/core/messages.js.map +1 -1
  239. package/dist/core/model-config.d.ts +202 -20
  240. package/dist/core/model-config.d.ts.map +1 -1
  241. package/dist/core/model-config.js +53 -18
  242. package/dist/core/model-config.js.map +1 -1
  243. package/dist/core/model-registry.d.ts +19 -2
  244. package/dist/core/model-registry.d.ts.map +1 -1
  245. package/dist/core/model-registry.js +39 -2
  246. package/dist/core/model-registry.js.map +1 -1
  247. package/dist/core/model-resolver.d.ts +7 -5
  248. package/dist/core/model-resolver.d.ts.map +1 -1
  249. package/dist/core/model-resolver.js +29 -17
  250. package/dist/core/model-resolver.js.map +1 -1
  251. package/dist/core/model-runtime.d.ts +79 -20
  252. package/dist/core/model-runtime.d.ts.map +1 -1
  253. package/dist/core/model-runtime.js +460 -134
  254. package/dist/core/model-runtime.js.map +1 -1
  255. package/dist/core/models-store.d.ts +12 -7
  256. package/dist/core/models-store.d.ts.map +1 -1
  257. package/dist/core/models-store.js +87 -18
  258. package/dist/core/models-store.js.map +1 -1
  259. package/dist/core/multi-agent/fsm.js +8 -3
  260. package/dist/core/multi-agent/fsm.js.map +1 -1
  261. package/dist/core/multi-agent/mailbox.js +1 -3
  262. package/dist/core/multi-agent/mailbox.js.map +1 -1
  263. package/dist/core/multi-agent/permission-gate.d.ts +5 -2
  264. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  265. package/dist/core/multi-agent/permission-gate.js +597 -34
  266. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  267. package/dist/core/multi-agent/task-board.js +2 -4
  268. package/dist/core/multi-agent/task-board.js.map +1 -1
  269. package/dist/core/multi-agent/worktree.js +1 -3
  270. package/dist/core/multi-agent/worktree.js.map +1 -1
  271. package/dist/core/nested-tool-calls.d.ts +102 -0
  272. package/dist/core/nested-tool-calls.d.ts.map +1 -0
  273. package/dist/core/nested-tool-calls.js +178 -0
  274. package/dist/core/nested-tool-calls.js.map +1 -0
  275. package/dist/core/package-manager.d.ts +10 -0
  276. package/dist/core/package-manager.d.ts.map +1 -1
  277. package/dist/core/package-manager.js +149 -33
  278. package/dist/core/package-manager.js.map +1 -1
  279. package/dist/core/pi-manifest.d.ts.map +1 -1
  280. package/dist/core/pi-manifest.js +13 -12
  281. package/dist/core/pi-manifest.js.map +1 -1
  282. package/dist/core/prompt-templates.d.ts +6 -1
  283. package/dist/core/prompt-templates.d.ts.map +1 -1
  284. package/dist/core/prompt-templates.js +63 -37
  285. package/dist/core/prompt-templates.js.map +1 -1
  286. package/dist/core/provider-attribution.js +5 -5
  287. package/dist/core/provider-attribution.js.map +1 -1
  288. package/dist/core/provider-composer.d.ts +44 -20
  289. package/dist/core/provider-composer.d.ts.map +1 -1
  290. package/dist/core/provider-composer.js +151 -51
  291. package/dist/core/provider-composer.js.map +1 -1
  292. package/dist/core/radius.d.ts +13 -0
  293. package/dist/core/radius.d.ts.map +1 -1
  294. package/dist/core/radius.js +19 -0
  295. package/dist/core/radius.js.map +1 -1
  296. package/dist/core/remote-catalog-provider.d.ts +10 -3
  297. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  298. package/dist/core/remote-catalog-provider.js +105 -81
  299. package/dist/core/remote-catalog-provider.js.map +1 -1
  300. package/dist/core/resource-loader.d.ts +7 -1
  301. package/dist/core/resource-loader.d.ts.map +1 -1
  302. package/dist/core/resource-loader.js +219 -42
  303. package/dist/core/resource-loader.js.map +1 -1
  304. package/dist/core/runtime-credentials.d.ts +5 -5
  305. package/dist/core/runtime-credentials.d.ts.map +1 -1
  306. package/dist/core/runtime-credentials.js +13 -9
  307. package/dist/core/runtime-credentials.js.map +1 -1
  308. package/dist/core/sandbox/executor.js +1 -0
  309. package/dist/core/sandbox/executor.js.map +1 -1
  310. package/dist/core/sdk.d.ts +7 -5
  311. package/dist/core/sdk.d.ts.map +1 -1
  312. package/dist/core/sdk.js +100 -52
  313. package/dist/core/sdk.js.map +1 -1
  314. package/dist/core/session-cwd.js +1 -0
  315. package/dist/core/session-cwd.js.map +1 -1
  316. package/dist/core/session-export.d.ts +8 -0
  317. package/dist/core/session-export.d.ts.map +1 -0
  318. package/dist/core/session-export.js +33 -0
  319. package/dist/core/session-export.js.map +1 -0
  320. package/dist/core/session-manager.d.ts +75 -15
  321. package/dist/core/session-manager.d.ts.map +1 -1
  322. package/dist/core/session-manager.js +314 -144
  323. package/dist/core/session-manager.js.map +1 -1
  324. package/dist/core/settings-diagnostics.d.ts +9 -0
  325. package/dist/core/settings-diagnostics.d.ts.map +1 -0
  326. package/dist/core/settings-diagnostics.js +21 -0
  327. package/dist/core/settings-diagnostics.js.map +1 -0
  328. package/dist/core/settings-manager.d.ts +84 -4
  329. package/dist/core/settings-manager.d.ts.map +1 -1
  330. package/dist/core/settings-manager.js +239 -25
  331. package/dist/core/settings-manager.js.map +1 -1
  332. package/dist/core/skills.d.ts.map +1 -1
  333. package/dist/core/skills.js +51 -33
  334. package/dist/core/skills.js.map +1 -1
  335. package/dist/core/slash-commands.d.ts.map +1 -1
  336. package/dist/core/slash-commands.js +3 -1
  337. package/dist/core/slash-commands.js.map +1 -1
  338. package/dist/core/soak/soak-log.js +6 -0
  339. package/dist/core/soak/soak-log.js.map +1 -1
  340. package/dist/core/socket-server/socket-server.js +11 -0
  341. package/dist/core/socket-server/socket-server.js.map +1 -1
  342. package/dist/core/socket-server/types.d.ts +2 -1
  343. package/dist/core/socket-server/types.d.ts.map +1 -1
  344. package/dist/core/socket-server/types.js.map +1 -1
  345. package/dist/core/source-info.d.ts +8 -0
  346. package/dist/core/source-info.d.ts.map +1 -1
  347. package/dist/core/source-info.js +16 -0
  348. package/dist/core/source-info.js.map +1 -1
  349. package/dist/core/system-prompt.d.ts +49 -6
  350. package/dist/core/system-prompt.d.ts.map +1 -1
  351. package/dist/core/system-prompt.js +126 -89
  352. package/dist/core/system-prompt.js.map +1 -1
  353. package/dist/core/tools/bash.d.ts +32 -2
  354. package/dist/core/tools/bash.d.ts.map +1 -1
  355. package/dist/core/tools/bash.js +82 -143
  356. package/dist/core/tools/bash.js.map +1 -1
  357. package/dist/core/tools/edit-diff.d.ts +0 -5
  358. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  359. package/dist/core/tools/edit-diff.js +2 -5
  360. package/dist/core/tools/edit-diff.js.map +1 -1
  361. package/dist/core/tools/edit.d.ts +5 -12
  362. package/dist/core/tools/edit.d.ts.map +1 -1
  363. package/dist/core/tools/edit.js +19 -171
  364. package/dist/core/tools/edit.js.map +1 -1
  365. package/dist/core/tools/find.d.ts +4 -0
  366. package/dist/core/tools/find.d.ts.map +1 -1
  367. package/dist/core/tools/find.js +11 -58
  368. package/dist/core/tools/find.js.map +1 -1
  369. package/dist/core/tools/grep.d.ts +4 -0
  370. package/dist/core/tools/grep.d.ts.map +1 -1
  371. package/dist/core/tools/grep.js +10 -62
  372. package/dist/core/tools/grep.js.map +1 -1
  373. package/dist/core/tools/index.d.ts +4 -1
  374. package/dist/core/tools/index.d.ts.map +1 -1
  375. package/dist/core/tools/index.js +18 -1
  376. package/dist/core/tools/index.js.map +1 -1
  377. package/dist/core/tools/ls.d.ts +4 -0
  378. package/dist/core/tools/ls.d.ts.map +1 -1
  379. package/dist/core/tools/ls.js +9 -50
  380. package/dist/core/tools/ls.js.map +1 -1
  381. package/dist/core/tools/output-accumulator.d.ts +11 -0
  382. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  383. package/dist/core/tools/output-accumulator.js +54 -12
  384. package/dist/core/tools/output-accumulator.js.map +1 -1
  385. package/dist/core/tools/powershell.d.ts +16 -0
  386. package/dist/core/tools/powershell.d.ts.map +1 -0
  387. package/dist/core/tools/powershell.js +39 -0
  388. package/dist/core/tools/powershell.js.map +1 -0
  389. package/dist/core/tools/read.d.ts +8 -1
  390. package/dist/core/tools/read.d.ts.map +1 -1
  391. package/dist/core/tools/read.js +16 -123
  392. package/dist/core/tools/read.js.map +1 -1
  393. package/dist/core/tools/render-utils.d.ts +6 -0
  394. package/dist/core/tools/render-utils.d.ts.map +1 -1
  395. package/dist/core/tools/render-utils.js +26 -0
  396. package/dist/core/tools/render-utils.js.map +1 -1
  397. package/dist/core/tools/renderers/bash.d.ts +12 -0
  398. package/dist/core/tools/renderers/bash.d.ts.map +1 -0
  399. package/dist/core/tools/renderers/bash.js +117 -0
  400. package/dist/core/tools/renderers/bash.js.map +1 -0
  401. package/dist/core/tools/renderers/edit.d.ts +23 -0
  402. package/dist/core/tools/renderers/edit.d.ts.map +1 -0
  403. package/dist/core/tools/renderers/edit.js +167 -0
  404. package/dist/core/tools/renderers/edit.js.map +1 -0
  405. package/dist/core/tools/renderers/find.d.ts +10 -0
  406. package/dist/core/tools/renderers/find.d.ts.map +1 -0
  407. package/dist/core/tools/renderers/find.js +64 -0
  408. package/dist/core/tools/renderers/find.js.map +1 -0
  409. package/dist/core/tools/renderers/grep.d.ts +10 -0
  410. package/dist/core/tools/renderers/grep.d.ts.map +1 -0
  411. package/dist/core/tools/renderers/grep.js +69 -0
  412. package/dist/core/tools/renderers/grep.js.map +1 -0
  413. package/dist/core/tools/renderers/index.d.ts +28 -0
  414. package/dist/core/tools/renderers/index.d.ts.map +1 -0
  415. package/dist/core/tools/renderers/index.js +47 -0
  416. package/dist/core/tools/renderers/index.js.map +1 -0
  417. package/dist/core/tools/renderers/ls.d.ts +10 -0
  418. package/dist/core/tools/renderers/ls.d.ts.map +1 -0
  419. package/dist/core/tools/renderers/ls.js +58 -0
  420. package/dist/core/tools/renderers/ls.js.map +1 -0
  421. package/dist/core/tools/renderers/read.d.ts +11 -0
  422. package/dist/core/tools/renderers/read.d.ts.map +1 -0
  423. package/dist/core/tools/renderers/read.js +130 -0
  424. package/dist/core/tools/renderers/read.js.map +1 -0
  425. package/dist/core/tools/renderers/write.d.ts +10 -0
  426. package/dist/core/tools/renderers/write.d.ts.map +1 -0
  427. package/dist/core/tools/renderers/write.js +153 -0
  428. package/dist/core/tools/renderers/write.js.map +1 -0
  429. package/dist/core/tools/tool-definition-wrapper.d.ts +5 -3
  430. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  431. package/dist/core/tools/tool-definition-wrapper.js +3 -1
  432. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  433. package/dist/core/tools/truncate.d.ts +14 -0
  434. package/dist/core/tools/truncate.d.ts.map +1 -1
  435. package/dist/core/tools/truncate.js +29 -0
  436. package/dist/core/tools/truncate.js.map +1 -1
  437. package/dist/core/tools/write.d.ts +4 -0
  438. package/dist/core/tools/write.d.ts.map +1 -1
  439. package/dist/core/tools/write.js +12 -147
  440. package/dist/core/tools/write.js.map +1 -1
  441. package/dist/core/trust-manager.d.ts.map +1 -1
  442. package/dist/core/trust-manager.js +4 -1
  443. package/dist/core/trust-manager.js.map +1 -1
  444. package/dist/core/usage-totals.d.ts +3 -1
  445. package/dist/core/usage-totals.d.ts.map +1 -1
  446. package/dist/core/usage-totals.js +28 -1
  447. package/dist/core/usage-totals.js.map +1 -1
  448. package/dist/core/virtual-models.d.ts +117 -0
  449. package/dist/core/virtual-models.d.ts.map +1 -0
  450. package/dist/core/virtual-models.js +124 -0
  451. package/dist/core/virtual-models.js.map +1 -0
  452. package/dist/experimental/micro/api.d.ts +81 -0
  453. package/dist/experimental/micro/api.d.ts.map +1 -0
  454. package/dist/experimental/micro/api.js +2 -0
  455. package/dist/experimental/micro/api.js.map +1 -0
  456. package/dist/experimental/micro/main.d.ts +3 -0
  457. package/dist/experimental/micro/main.d.ts.map +1 -0
  458. package/dist/experimental/micro/main.js +21 -0
  459. package/dist/experimental/micro/main.js.map +1 -0
  460. package/dist/experimental/micro/models.d.ts +11 -0
  461. package/dist/experimental/micro/models.d.ts.map +1 -0
  462. package/dist/experimental/micro/models.js +95 -0
  463. package/dist/experimental/micro/models.js.map +1 -0
  464. package/dist/experimental/micro/runtime.d.ts +12 -0
  465. package/dist/experimental/micro/runtime.d.ts.map +1 -0
  466. package/dist/experimental/micro/runtime.js +465 -0
  467. package/dist/experimental/micro/runtime.js.map +1 -0
  468. package/dist/experimental/micro/sessions.d.ts +10 -0
  469. package/dist/experimental/micro/sessions.d.ts.map +1 -0
  470. package/dist/experimental/micro/sessions.js +41 -0
  471. package/dist/experimental/micro/sessions.js.map +1 -0
  472. package/dist/experimental/micro/tools.d.ts +10 -0
  473. package/dist/experimental/micro/tools.d.ts.map +1 -0
  474. package/dist/experimental/micro/tools.js +96 -0
  475. package/dist/experimental/micro/tools.js.map +1 -0
  476. package/dist/experimental/micro/tui.d.ts +3 -0
  477. package/dist/experimental/micro/tui.d.ts.map +1 -0
  478. package/dist/experimental/micro/tui.js +510 -0
  479. package/dist/experimental/micro/tui.js.map +1 -0
  480. package/dist/experimental/mini/main.d.ts +7 -0
  481. package/dist/experimental/mini/main.d.ts.map +1 -0
  482. package/dist/experimental/mini/main.js +21 -0
  483. package/dist/experimental/mini/main.js.map +1 -0
  484. package/dist/experimental/mini/server/entry.d.ts +3 -0
  485. package/dist/experimental/mini/server/entry.d.ts.map +1 -0
  486. package/dist/experimental/mini/server/entry.js +11 -0
  487. package/dist/experimental/mini/server/entry.js.map +1 -0
  488. package/dist/experimental/mini/server/run.d.ts +13 -0
  489. package/dist/experimental/mini/server/run.d.ts.map +1 -0
  490. package/dist/experimental/mini/server/run.js +150 -0
  491. package/dist/experimental/mini/server/run.js.map +1 -0
  492. package/dist/experimental/mini/shared/protocol.d.ts +127 -0
  493. package/dist/experimental/mini/shared/protocol.d.ts.map +1 -0
  494. package/dist/experimental/mini/shared/protocol.js +13 -0
  495. package/dist/experimental/mini/shared/protocol.js.map +1 -0
  496. package/dist/experimental/mini/shared/rpc.d.ts +49 -0
  497. package/dist/experimental/mini/shared/rpc.d.ts.map +1 -0
  498. package/dist/experimental/mini/shared/rpc.js +171 -0
  499. package/dist/experimental/mini/shared/rpc.js.map +1 -0
  500. package/dist/experimental/mini/shared/transport.d.ts +35 -0
  501. package/dist/experimental/mini/shared/transport.d.ts.map +1 -0
  502. package/dist/experimental/mini/shared/transport.js +94 -0
  503. package/dist/experimental/mini/shared/transport.js.map +1 -0
  504. package/dist/experimental/mini/tui/run.d.ts +9 -0
  505. package/dist/experimental/mini/tui/run.d.ts.map +1 -0
  506. package/dist/experimental/mini/tui/run.js +62 -0
  507. package/dist/experimental/mini/tui/run.js.map +1 -0
  508. package/dist/experimental/mini/tui/session.d.ts +26 -0
  509. package/dist/experimental/mini/tui/session.d.ts.map +1 -0
  510. package/dist/experimental/mini/tui/session.js +94 -0
  511. package/dist/experimental/mini/tui/session.js.map +1 -0
  512. package/dist/experimental/mini/tui/view.d.ts +10 -0
  513. package/dist/experimental/mini/tui/view.d.ts.map +1 -0
  514. package/dist/experimental/mini/tui/view.js +461 -0
  515. package/dist/experimental/mini/tui/view.js.map +1 -0
  516. package/dist/experimental/mini/worker/entry.d.ts +3 -0
  517. package/dist/experimental/mini/worker/entry.d.ts.map +1 -0
  518. package/dist/experimental/mini/worker/entry.js +10 -0
  519. package/dist/experimental/mini/worker/entry.js.map +1 -0
  520. package/dist/experimental/mini/worker/lane-service.d.ts +44 -0
  521. package/dist/experimental/mini/worker/lane-service.d.ts.map +1 -0
  522. package/dist/experimental/mini/worker/lane-service.js +97 -0
  523. package/dist/experimental/mini/worker/lane-service.js.map +1 -0
  524. package/dist/experimental/mini/worker/models-service.d.ts +19 -0
  525. package/dist/experimental/mini/worker/models-service.d.ts.map +1 -0
  526. package/dist/experimental/mini/worker/models-service.js +136 -0
  527. package/dist/experimental/mini/worker/models-service.js.map +1 -0
  528. package/dist/experimental/mini/worker/run.d.ts +14 -0
  529. package/dist/experimental/mini/worker/run.d.ts.map +1 -0
  530. package/dist/experimental/mini/worker/run.js +88 -0
  531. package/dist/experimental/mini/worker/run.js.map +1 -0
  532. package/dist/extensions/codemode/execute.d.ts +16 -0
  533. package/dist/extensions/codemode/execute.d.ts.map +1 -0
  534. package/dist/extensions/codemode/execute.js +429 -0
  535. package/dist/extensions/codemode/execute.js.map +1 -0
  536. package/dist/extensions/codemode/execute.lazy.d.ts +3 -0
  537. package/dist/extensions/codemode/execute.lazy.d.ts.map +1 -0
  538. package/dist/extensions/codemode/execute.lazy.js +3 -0
  539. package/dist/extensions/codemode/execute.lazy.js.map +1 -0
  540. package/dist/extensions/codemode/index.d.ts +21 -0
  541. package/dist/extensions/codemode/index.d.ts.map +1 -0
  542. package/dist/extensions/codemode/index.js +31 -0
  543. package/dist/extensions/codemode/index.js.map +1 -0
  544. package/dist/extensions/codemode/renderer.d.ts +12 -0
  545. package/dist/extensions/codemode/renderer.d.ts.map +1 -0
  546. package/dist/extensions/codemode/renderer.js +137 -0
  547. package/dist/extensions/codemode/renderer.js.map +1 -0
  548. package/dist/extensions/codemode/tool.d.ts +123 -0
  549. package/dist/extensions/codemode/tool.d.ts.map +1 -0
  550. package/dist/extensions/codemode/tool.js +315 -0
  551. package/dist/extensions/codemode/tool.js.map +1 -0
  552. package/dist/extensions/codemode/worker.d.ts +7 -0
  553. package/dist/extensions/codemode/worker.d.ts.map +1 -0
  554. package/dist/extensions/codemode/worker.js +7 -0
  555. package/dist/extensions/codemode/worker.js.map +1 -0
  556. package/dist/extensions/index.d.ts.map +1 -1
  557. package/dist/extensions/index.js +9 -1
  558. package/dist/extensions/index.js.map +1 -1
  559. package/dist/extensions/llama/client.d.ts +8 -0
  560. package/dist/extensions/llama/client.d.ts.map +1 -1
  561. package/dist/extensions/llama/client.js +13 -0
  562. package/dist/extensions/llama/client.js.map +1 -1
  563. package/dist/extensions/llama/huggingface.js +2 -0
  564. package/dist/extensions/llama/huggingface.js.map +1 -1
  565. package/dist/extensions/llama/index.d.ts.map +1 -1
  566. package/dist/extensions/llama/index.js +13 -2
  567. package/dist/extensions/llama/index.js.map +1 -1
  568. package/dist/extensions/llama/provider.d.ts +4 -2
  569. package/dist/extensions/llama/provider.d.ts.map +1 -1
  570. package/dist/extensions/llama/provider.js +119 -17
  571. package/dist/extensions/llama/provider.js.map +1 -1
  572. package/dist/extensions/llama/ui.js +28 -12
  573. package/dist/extensions/llama/ui.js.map +1 -1
  574. package/dist/extensions/mcp/cli.d.ts +21 -0
  575. package/dist/extensions/mcp/cli.d.ts.map +1 -0
  576. package/dist/extensions/mcp/cli.js +500 -0
  577. package/dist/extensions/mcp/cli.js.map +1 -0
  578. package/dist/extensions/mcp/cli.lazy.d.ts +3 -0
  579. package/dist/extensions/mcp/cli.lazy.d.ts.map +1 -0
  580. package/dist/extensions/mcp/cli.lazy.js +3 -0
  581. package/dist/extensions/mcp/cli.lazy.js.map +1 -0
  582. package/dist/extensions/mcp/config.d.ts +72 -0
  583. package/dist/extensions/mcp/config.d.ts.map +1 -0
  584. package/dist/extensions/mcp/config.js +158 -0
  585. package/dist/extensions/mcp/config.js.map +1 -0
  586. package/dist/extensions/mcp/index.d.ts +76 -0
  587. package/dist/extensions/mcp/index.d.ts.map +1 -0
  588. package/dist/extensions/mcp/index.js +1055 -0
  589. package/dist/extensions/mcp/index.js.map +1 -0
  590. package/dist/extensions/mcp/log.d.ts +16 -0
  591. package/dist/extensions/mcp/log.d.ts.map +1 -0
  592. package/dist/extensions/mcp/log.js +66 -0
  593. package/dist/extensions/mcp/log.js.map +1 -0
  594. package/dist/extensions/mcp/oauth.d.ts +96 -0
  595. package/dist/extensions/mcp/oauth.d.ts.map +1 -0
  596. package/dist/extensions/mcp/oauth.js +333 -0
  597. package/dist/extensions/mcp/oauth.js.map +1 -0
  598. package/dist/extensions/mcp/resources.d.ts +43 -0
  599. package/dist/extensions/mcp/resources.d.ts.map +1 -0
  600. package/dist/extensions/mcp/resources.js +262 -0
  601. package/dist/extensions/mcp/resources.js.map +1 -0
  602. package/dist/extensions/mcp/runtime.d.ts +98 -0
  603. package/dist/extensions/mcp/runtime.d.ts.map +1 -0
  604. package/dist/extensions/mcp/runtime.js +394 -0
  605. package/dist/extensions/mcp/runtime.js.map +1 -0
  606. package/dist/extensions/mcp/runtime.lazy.d.ts +3 -0
  607. package/dist/extensions/mcp/runtime.lazy.d.ts.map +1 -0
  608. package/dist/extensions/mcp/runtime.lazy.js +3 -0
  609. package/dist/extensions/mcp/runtime.lazy.js.map +1 -0
  610. package/dist/extensions/mcp/tools.d.ts +84 -0
  611. package/dist/extensions/mcp/tools.d.ts.map +1 -0
  612. package/dist/extensions/mcp/tools.js +251 -0
  613. package/dist/extensions/mcp/tools.js.map +1 -0
  614. package/dist/extensions/mcp/ui.d.ts +60 -0
  615. package/dist/extensions/mcp/ui.d.ts.map +1 -0
  616. package/dist/extensions/mcp/ui.js +174 -0
  617. package/dist/extensions/mcp/ui.js.map +1 -0
  618. package/dist/extensions/stub-provider/provider.d.ts +2 -2
  619. package/dist/extensions/stub-provider/provider.d.ts.map +1 -1
  620. package/dist/extensions/stub-provider/provider.js +2 -1
  621. package/dist/extensions/stub-provider/provider.js.map +1 -1
  622. package/dist/extensions/tool-search/index.d.ts +12 -0
  623. package/dist/extensions/tool-search/index.d.ts.map +1 -0
  624. package/dist/extensions/tool-search/index.js +15 -0
  625. package/dist/extensions/tool-search/index.js.map +1 -0
  626. package/dist/extensions/tool-search/tool.d.ts +73 -0
  627. package/dist/extensions/tool-search/tool.d.ts.map +1 -0
  628. package/dist/extensions/tool-search/tool.js +189 -0
  629. package/dist/extensions/tool-search/tool.js.map +1 -0
  630. package/dist/index.d.ts +20 -11
  631. package/dist/index.d.ts.map +1 -1
  632. package/dist/index.js +12 -6
  633. package/dist/index.js.map +1 -1
  634. package/dist/main.d.ts +4 -0
  635. package/dist/main.d.ts.map +1 -1
  636. package/dist/main.js +123 -51
  637. package/dist/main.js.map +1 -1
  638. package/dist/migrations.d.ts +1 -1
  639. package/dist/migrations.js +7 -6
  640. package/dist/migrations.js.map +1 -1
  641. package/dist/modes/index.d.ts +1 -0
  642. package/dist/modes/index.d.ts.map +1 -1
  643. package/dist/modes/index.js.map +1 -1
  644. package/dist/modes/interactive/bug-report.d.ts +19 -0
  645. package/dist/modes/interactive/bug-report.d.ts.map +1 -0
  646. package/dist/modes/interactive/bug-report.js +211 -0
  647. package/dist/modes/interactive/bug-report.js.map +1 -0
  648. package/dist/modes/interactive/chat-viewport.d.ts +20 -0
  649. package/dist/modes/interactive/chat-viewport.d.ts.map +1 -0
  650. package/dist/modes/interactive/chat-viewport.js +28 -0
  651. package/dist/modes/interactive/chat-viewport.js.map +1 -0
  652. package/dist/modes/interactive/components/armin.js +10 -6
  653. package/dist/modes/interactive/components/armin.js.map +1 -1
  654. package/dist/modes/interactive/components/assistant-message.d.ts +6 -2
  655. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  656. package/dist/modes/interactive/components/assistant-message.js +38 -15
  657. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  658. package/dist/modes/interactive/components/bash-execution.js +9 -4
  659. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  660. package/dist/modes/interactive/components/bordered-loader.js +3 -0
  661. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  662. package/dist/modes/interactive/components/branch-summary-message.d.ts +1 -1
  663. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  664. package/dist/modes/interactive/components/branch-summary-message.js +15 -6
  665. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  666. package/dist/modes/interactive/components/compaction-summary-message.d.ts +1 -1
  667. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  668. package/dist/modes/interactive/components/compaction-summary-message.js +15 -6
  669. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  670. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  671. package/dist/modes/interactive/components/config-selector.js +35 -8
  672. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  673. package/dist/modes/interactive/components/countdown-timer.js +5 -0
  674. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  675. package/dist/modes/interactive/components/custom-editor.d.ts +10 -1
  676. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  677. package/dist/modes/interactive/components/custom-editor.js +54 -2
  678. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  679. package/dist/modes/interactive/components/custom-entry.js +4 -1
  680. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  681. package/dist/modes/interactive/components/custom-message.js +7 -1
  682. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  683. package/dist/modes/interactive/components/daxnuts.js +8 -6
  684. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  685. package/dist/modes/interactive/components/dynamic-border.js +1 -0
  686. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  687. package/dist/modes/interactive/components/extension-editor.d.ts +4 -1
  688. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  689. package/dist/modes/interactive/components/extension-editor.js +14 -3
  690. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  691. package/dist/modes/interactive/components/extension-input.d.ts +2 -0
  692. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  693. package/dist/modes/interactive/components/extension-input.js +14 -2
  694. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  695. package/dist/modes/interactive/components/extension-selector.d.ts +1 -0
  696. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  697. package/dist/modes/interactive/components/extension-selector.js +16 -1
  698. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  699. package/dist/modes/interactive/components/first-time-setup.d.ts +4 -4
  700. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  701. package/dist/modes/interactive/components/first-time-setup.js +12 -4
  702. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  703. package/dist/modes/interactive/components/footer.d.ts +7 -0
  704. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  705. package/dist/modes/interactive/components/footer.js +51 -6
  706. package/dist/modes/interactive/components/footer.js.map +1 -1
  707. package/dist/modes/interactive/components/index.d.ts +1 -1
  708. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  709. package/dist/modes/interactive/components/index.js.map +1 -1
  710. package/dist/modes/interactive/components/login-dialog.js +9 -3
  711. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  712. package/dist/modes/interactive/components/markdown-transform.d.ts +3 -0
  713. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -0
  714. package/dist/modes/interactive/components/markdown-transform.js +19 -0
  715. package/dist/modes/interactive/components/markdown-transform.js.map +1 -0
  716. package/dist/modes/interactive/components/mermaid.d.ts +11 -0
  717. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -0
  718. package/dist/modes/interactive/components/mermaid.js +75 -0
  719. package/dist/modes/interactive/components/mermaid.js.map +1 -0
  720. package/dist/modes/interactive/components/model-selector.d.ts +10 -4
  721. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  722. package/dist/modes/interactive/components/model-selector.js +101 -40
  723. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  724. package/dist/modes/interactive/components/oauth-selector.js +11 -3
  725. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  726. package/dist/modes/interactive/components/scoped-models-selector.d.ts +4 -0
  727. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  728. package/dist/modes/interactive/components/scoped-models-selector.js +60 -32
  729. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  730. package/dist/modes/interactive/components/session-selector.d.ts +5 -5
  731. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  732. package/dist/modes/interactive/components/session-selector.js +128 -78
  733. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  734. package/dist/modes/interactive/components/settings-selector.d.ts +23 -4
  735. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  736. package/dist/modes/interactive/components/settings-selector.js +230 -67
  737. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  738. package/dist/modes/interactive/components/settings-submenu.d.ts +72 -0
  739. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -0
  740. package/dist/modes/interactive/components/settings-submenu.js +165 -0
  741. package/dist/modes/interactive/components/settings-submenu.js.map +1 -0
  742. package/dist/modes/interactive/components/show-images-selector.js +1 -0
  743. package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
  744. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  745. package/dist/modes/interactive/components/skill-invocation-message.js +14 -5
  746. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  747. package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
  748. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  749. package/dist/modes/interactive/components/status-indicator.js +12 -3
  750. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  751. package/dist/modes/interactive/components/theme-selector.js +2 -0
  752. package/dist/modes/interactive/components/theme-selector.js.map +1 -1
  753. package/dist/modes/interactive/components/themed-text.d.ts +17 -0
  754. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -0
  755. package/dist/modes/interactive/components/themed-text.js +29 -0
  756. package/dist/modes/interactive/components/themed-text.js.map +1 -0
  757. package/dist/modes/interactive/components/thinking-selector.d.ts +15 -3
  758. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  759. package/dist/modes/interactive/components/thinking-selector.js +76 -18
  760. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  761. package/dist/modes/interactive/components/tool-execution.d.ts +21 -4
  762. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  763. package/dist/modes/interactive/components/tool-execution.js +78 -52
  764. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  765. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  766. package/dist/modes/interactive/components/tree-selector.js +44 -18
  767. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  768. package/dist/modes/interactive/components/trust-selector.js +8 -2
  769. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  770. package/dist/modes/interactive/components/user-message-selector.js +6 -3
  771. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  772. package/dist/modes/interactive/components/user-message.d.ts +3 -1
  773. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  774. package/dist/modes/interactive/components/user-message.js +12 -2
  775. package/dist/modes/interactive/components/user-message.js.map +1 -1
  776. package/dist/modes/interactive/components/visual-truncate.d.ts +27 -3
  777. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  778. package/dist/modes/interactive/components/visual-truncate.js +39 -6
  779. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  780. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  781. package/dist/modes/interactive/external-editor.js +2 -1
  782. package/dist/modes/interactive/external-editor.js.map +1 -1
  783. package/dist/modes/interactive/interactive-mode.d.ts +69 -5
  784. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  785. package/dist/modes/interactive/interactive-mode.js +1314 -593
  786. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  787. package/dist/modes/interactive/model-catalog-refresh.d.ts +7 -0
  788. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
  789. package/dist/modes/interactive/model-catalog-refresh.js +34 -0
  790. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -0
  791. package/dist/modes/interactive/session-share.d.ts +23 -0
  792. package/dist/modes/interactive/session-share.d.ts.map +1 -0
  793. package/dist/modes/interactive/session-share.js +130 -0
  794. package/dist/modes/interactive/session-share.js.map +1 -0
  795. package/dist/modes/interactive/theme/dark.json +54 -63
  796. package/dist/modes/interactive/theme/light.json +52 -60
  797. package/dist/modes/interactive/theme/system-theme.d.ts +54 -0
  798. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -0
  799. package/dist/modes/interactive/theme/system-theme.js +535 -0
  800. package/dist/modes/interactive/theme/system-theme.js.map +1 -0
  801. package/dist/modes/interactive/theme/theme-controller.d.ts +59 -7
  802. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  803. package/dist/modes/interactive/theme/theme-controller.js +164 -51
  804. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  805. package/dist/modes/interactive/theme/theme-json.d.ts +85 -0
  806. package/dist/modes/interactive/theme/theme-json.d.ts.map +1 -0
  807. package/dist/modes/interactive/theme/theme-json.js +132 -0
  808. package/dist/modes/interactive/theme/theme-json.js.map +1 -0
  809. package/dist/modes/interactive/theme/theme-schema.json +24 -3
  810. package/dist/modes/interactive/theme/theme.d.ts +80 -42
  811. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  812. package/dist/modes/interactive/theme/theme.js +274 -417
  813. package/dist/modes/interactive/theme/theme.js.map +1 -1
  814. package/dist/modes/interactive/tui-renderer.d.ts +22 -0
  815. package/dist/modes/interactive/tui-renderer.d.ts.map +1 -0
  816. package/dist/modes/interactive/tui-renderer.js +67 -0
  817. package/dist/modes/interactive/tui-renderer.js.map +1 -0
  818. package/dist/modes/json-event.d.ts +34 -0
  819. package/dist/modes/json-event.d.ts.map +1 -0
  820. package/dist/modes/json-event.js +29 -0
  821. package/dist/modes/json-event.js.map +1 -0
  822. package/dist/modes/print-mode.d.ts +1 -1
  823. package/dist/modes/print-mode.d.ts.map +1 -1
  824. package/dist/modes/print-mode.js +12 -2
  825. package/dist/modes/print-mode.js.map +1 -1
  826. package/dist/modes/rpc/rpc-client.d.ts +17 -9
  827. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  828. package/dist/modes/rpc/rpc-client.js +27 -15
  829. package/dist/modes/rpc/rpc-client.js.map +1 -1
  830. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  831. package/dist/modes/rpc/rpc-mode.js +14 -12
  832. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  833. package/dist/modes/rpc/rpc-types.d.ts +22 -1
  834. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  835. package/dist/modes/rpc/rpc-types.js.map +1 -1
  836. package/dist/package-manager-cli.d.ts +1 -0
  837. package/dist/package-manager-cli.d.ts.map +1 -1
  838. package/dist/package-manager-cli.js +217 -63
  839. package/dist/package-manager-cli.js.map +1 -1
  840. package/dist/prompts/commands/plan-phase.md +1 -0
  841. package/dist/prompts/commands/review.md +2 -0
  842. package/dist/prompts/commands/verify-work.md +1 -0
  843. package/dist/prompts/commands/why.md +4 -0
  844. package/dist/rpc-entry.js +1 -0
  845. package/dist/rpc-entry.js.map +1 -1
  846. package/dist/skills/blast-radius/SKILL.md +1 -0
  847. package/dist/skills/explainers/SKILL.md +65 -0
  848. package/dist/skills/unslop/SKILL.md +19 -1
  849. package/dist/utils/abort.d.ts +5 -0
  850. package/dist/utils/abort.d.ts.map +1 -0
  851. package/dist/utils/abort.js +48 -0
  852. package/dist/utils/abort.js.map +1 -0
  853. package/dist/utils/changelog.js +1 -1
  854. package/dist/utils/changelog.js.map +1 -1
  855. package/dist/utils/child-process.d.ts +1 -1
  856. package/dist/utils/child-process.js +1 -1
  857. package/dist/utils/child-process.js.map +1 -1
  858. package/dist/utils/clipboard-command.d.ts +7 -0
  859. package/dist/utils/clipboard-command.d.ts.map +1 -0
  860. package/dist/utils/clipboard-command.js +45 -0
  861. package/dist/utils/clipboard-command.js.map +1 -0
  862. package/dist/utils/clipboard-image.d.ts.map +1 -1
  863. package/dist/utils/clipboard-image.js +60 -91
  864. package/dist/utils/clipboard-image.js.map +1 -1
  865. package/dist/utils/clipboard.d.ts +2 -0
  866. package/dist/utils/clipboard.d.ts.map +1 -1
  867. package/dist/utils/clipboard.js +116 -121
  868. package/dist/utils/clipboard.js.map +1 -1
  869. package/dist/utils/draht-user-agent.d.ts +2 -0
  870. package/dist/utils/draht-user-agent.d.ts.map +1 -0
  871. package/dist/utils/draht-user-agent.js +5 -0
  872. package/dist/utils/draht-user-agent.js.map +1 -0
  873. package/dist/utils/exif-orientation.d.ts +2 -1
  874. package/dist/utils/exif-orientation.d.ts.map +1 -1
  875. package/dist/utils/exif-orientation.js.map +1 -1
  876. package/dist/utils/frontmatter.d.ts.map +1 -1
  877. package/dist/utils/frontmatter.js +2 -1
  878. package/dist/utils/frontmatter.js.map +1 -1
  879. package/dist/utils/management-http.d.ts +25 -0
  880. package/dist/utils/management-http.d.ts.map +1 -0
  881. package/dist/utils/management-http.js +54 -0
  882. package/dist/utils/management-http.js.map +1 -0
  883. package/dist/utils/mime.js +1 -1
  884. package/dist/utils/mime.js.map +1 -1
  885. package/dist/utils/paths.d.ts +4 -3
  886. package/dist/utils/paths.d.ts.map +1 -1
  887. package/dist/utils/paths.js +15 -4
  888. package/dist/utils/paths.js.map +1 -1
  889. package/dist/utils/photon.d.ts +2 -1
  890. package/dist/utils/photon.d.ts.map +1 -1
  891. package/dist/utils/photon.js.map +1 -1
  892. package/dist/utils/shell.d.ts +4 -3
  893. package/dist/utils/shell.d.ts.map +1 -1
  894. package/dist/utils/shell.js +20 -35
  895. package/dist/utils/shell.js.map +1 -1
  896. package/dist/utils/syntax-highlight.d.ts +1 -0
  897. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  898. package/dist/utils/syntax-highlight.js +62 -1
  899. package/dist/utils/syntax-highlight.js.map +1 -1
  900. package/dist/utils/text.d.ts +8 -0
  901. package/dist/utils/text.d.ts.map +1 -0
  902. package/dist/utils/text.js +9 -0
  903. package/dist/utils/text.js.map +1 -0
  904. package/dist/utils/tool-result-images.d.ts +21 -0
  905. package/dist/utils/tool-result-images.d.ts.map +1 -0
  906. package/dist/utils/tool-result-images.js +48 -0
  907. package/dist/utils/tool-result-images.js.map +1 -0
  908. package/dist/utils/tools-manager.d.ts +11 -1
  909. package/dist/utils/tools-manager.d.ts.map +1 -1
  910. package/dist/utils/tools-manager.js +53 -36
  911. package/dist/utils/tools-manager.js.map +1 -1
  912. package/dist/utils/version-check.d.ts +4 -1
  913. package/dist/utils/version-check.d.ts.map +1 -1
  914. package/dist/utils/version-check.js +30 -9
  915. package/dist/utils/version-check.js.map +1 -1
  916. package/dist/utils/wsl.d.ts +3 -0
  917. package/dist/utils/wsl.d.ts.map +1 -0
  918. package/dist/utils/wsl.js +15 -0
  919. package/dist/utils/wsl.js.map +1 -0
  920. package/dist/utils/zip.d.ts +7 -0
  921. package/dist/utils/zip.d.ts.map +1 -0
  922. package/dist/utils/zip.js +60 -0
  923. package/dist/utils/zip.js.map +1 -0
  924. package/docs/cli-integration.md +106 -0
  925. package/docs/cli.md +374 -0
  926. package/docs/compaction.md +91 -29
  927. package/docs/configuration.md +47 -0
  928. package/docs/containerization.md +100 -66
  929. package/docs/custom-provider.md +109 -707
  930. package/docs/docs.json +155 -99
  931. package/docs/environment-variables.md +30 -17
  932. package/docs/extensions.md +169 -2811
  933. package/docs/how-pi-works.md +53 -0
  934. package/docs/images/interactive-mode.png +0 -0
  935. package/docs/index.md +25 -69
  936. package/docs/json.md +197 -56
  937. package/docs/keybindings.md +89 -93
  938. package/docs/llama-cpp.md +18 -3
  939. package/docs/mcp.md +231 -0
  940. package/docs/message-types.md +261 -0
  941. package/docs/models.md +94 -478
  942. package/docs/packages.md +67 -163
  943. package/docs/prompt-templates.md +31 -68
  944. package/docs/providers.md +118 -215
  945. package/docs/quickstart.md +55 -108
  946. package/docs/rpc-commands.md +860 -0
  947. package/docs/rpc-extension-ui.md +200 -0
  948. package/docs/rpc.md +139 -1518
  949. package/docs/sdk.md +79 -1127
  950. package/docs/security.md +76 -32
  951. package/docs/session-format.md +73 -219
  952. package/docs/sessions.md +36 -116
  953. package/docs/settings.md +124 -257
  954. package/docs/shell-aliases.md +85 -5
  955. package/docs/skills.md +52 -189
  956. package/docs/slash-commands.md +61 -0
  957. package/docs/terminal-setup.md +132 -61
  958. package/docs/termux.md +74 -84
  959. package/docs/themes.md +91 -252
  960. package/docs/tmux.md +31 -39
  961. package/docs/tui.md +74 -891
  962. package/docs/usage.md +54 -255
  963. package/docs/virtual-models.md +114 -0
  964. package/docs/windows.md +57 -7
  965. package/examples/extensions/antigravity-image-gen.ts +9 -9
  966. package/examples/extensions/bash-spawn-hook.ts +1 -1
  967. package/examples/extensions/border-status-editor.ts +1 -1
  968. package/examples/extensions/built-in-tool-renderer.ts +16 -40
  969. package/examples/extensions/custom-compaction.ts +1 -16
  970. package/examples/extensions/custom-provider-anthropic/index.ts +20 -13
  971. package/examples/extensions/custom-provider-gitlab-duo/index.ts +4 -3
  972. package/examples/extensions/custom-provider-gitlab-duo/test.ts +5 -5
  973. package/examples/extensions/debug-provider.ts +90 -0
  974. package/examples/extensions/doom-overlay/wad-finder.ts +7 -3
  975. package/examples/extensions/dynamic-resources/dynamic.json +3 -1
  976. package/examples/extensions/git-checkpoint.ts +2 -2
  977. package/examples/extensions/handoff.ts +2 -11
  978. package/examples/extensions/jev-router.ts +113 -0
  979. package/examples/extensions/minimal-mode.ts +24 -96
  980. package/examples/extensions/notify.ts +3 -1
  981. package/examples/extensions/prompt-customizer.ts +19 -67
  982. package/examples/extensions/qna.ts +3 -7
  983. package/examples/extensions/subagent/agents.ts +40 -9
  984. package/examples/extensions/subagent/index.ts +27 -4
  985. package/examples/extensions/summarize.ts +7 -18
  986. package/examples/extensions/titlebar-spinner.ts +1 -1
  987. package/examples/rpc-client.ts +35 -0
  988. package/examples/rpc-extension-ui.ts +38 -9
  989. package/examples/sdk/02-custom-model.ts +1 -2
  990. package/examples/sdk/06-extensions.ts +1 -1
  991. package/examples/sdk/09-api-keys-and-oauth.ts +1 -1
  992. package/examples/sdk/12-full-control.ts +1 -1
  993. package/examples/sdk/14-codemode-mcp.ts +61 -0
  994. package/package.json +25 -30
  995. package/prompts/commands/plan-phase.md +1 -0
  996. package/prompts/commands/review.md +2 -0
  997. package/prompts/commands/verify-work.md +1 -0
  998. package/prompts/commands/why.md +4 -0
  999. package/skills/blast-radius/SKILL.md +1 -0
  1000. package/skills/explainers/SKILL.md +65 -0
  1001. package/skills/unslop/SKILL.md +19 -1
  1002. package/dist/utils/clipboard-native.d.ts +0 -11
  1003. package/dist/utils/clipboard-native.d.ts.map +0 -1
  1004. package/dist/utils/clipboard-native.js +0 -20
  1005. package/dist/utils/clipboard-native.js.map +0 -1
  1006. package/dist/utils/pi-user-agent.d.ts +0 -2
  1007. package/dist/utils/pi-user-agent.d.ts.map +0 -1
  1008. package/dist/utils/pi-user-agent.js +0 -5
  1009. package/dist/utils/pi-user-agent.js.map +0 -1
  1010. package/docs/development.md +0 -71
  1011. package/docs/tree.md +0 -231
  1012. package/examples/extensions/kimi-deferred-tools.ts +0 -61
@@ -12,33 +12,41 @@
12
12
  *
13
13
  * Modes use this class and add their own I/O layer on top.
14
14
  */
15
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
15
+ import { readFileSync } from "node:fs";
16
16
  import { basename, dirname } from "node:path";
17
- import { contentText } from "@draht/ai";
18
- import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, isRetryableAssistantError, modelsAreEqual, resetApiProviders, streamSimple, } from "@draht/ai/compat";
17
+ import { runToolCall, } from "@draht/agent-core";
18
+ import { contentText, getCurrentSystemMessage, retryDelayMs } from "@draht/ai";
19
+ import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, isRecoverableLength, isRetryableAssistantError, modelsAreEqual, resetApiProviders, streamSimple, } from "@draht/ai/compat";
19
20
  import { getThemeByName, theme } from "../modes/interactive/theme/theme.js";
20
21
  import { stripFrontmatter } from "../utils/frontmatter.js";
21
- import { resolvePath } from "../utils/paths.js";
22
+ import { processImage } from "../utils/image-process.js";
22
23
  import { sleep } from "../utils/sleep.js";
24
+ import { normalizeToolResultImages } from "../utils/tool-result-images.js";
23
25
  import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
24
26
  import { executeBashWithOperations } from "./bash-executor.js";
25
- import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
27
+ import { generateBugReportSummary } from "./bug-report.js";
28
+ import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateProjectedContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
26
29
  import { applyContextWindow, getAvailableContextWindows } from "./context-windows.js";
27
- import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
30
+ import { DEFAULT_THINKING_LEVEL, THINKING_LEVEL_OPTIONS } from "./defaults.js";
28
31
  import { exportSessionToHtml } from "./export-html/index.js";
29
32
  import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
30
33
  import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
31
34
  import { emitSessionShutdownEvent } from "./extensions/runner.js";
35
+ import { convertToLlm } from "./messages.js";
32
36
  import { ModelRegistry } from "./model-registry.js";
37
+ import { NestedToolCallRunner } from "./nested-tool-calls.js";
33
38
  import { createRelayUIContext, noOpRelayBaseUIContext, } from "./permission-relay/index.js";
34
39
  import { expandPromptTemplate } from "./prompt-templates.js";
35
- import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
36
- import { createSyntheticSourceInfo } from "./source-info.js";
37
- import { buildSystemPrompt } from "./system-prompt.js";
40
+ import { exportSessionToJsonl } from "./session-export.js";
41
+ import { getLatestCompactionEntry, SessionManager, } from "./session-manager.js";
42
+ import { DEFAULT_TOOL_NAMES } from "./settings-manager.js";
43
+ import { BUILTIN_PATH_PREFIX, createSyntheticSourceInfo, isSyntheticPath } from "./source-info.js";
44
+ import { buildSystemPrompt, buildSystemPromptSections, diffSystemPromptSections, normalizeBuildSystemPromptOptions, } from "./system-prompt.js";
38
45
  import { createLocalBashOperations } from "./tools/bash.js";
39
46
  import { createAllToolDefinitions } from "./tools/index.js";
40
47
  import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
41
- import { addUsageToTotals, createUsageTotals } from "./usage-totals.js";
48
+ import { addUsageToTotals, combineUsage, createUsageTotals } from "./usage-totals.js";
49
+ import { findLatestResponse, getBranchSelection, getVirtualModelState, isVirtualModel, VIRTUAL_MODEL_STATE_ENTRY, } from "./virtual-models.js";
42
50
  /**
43
51
  * Parse a skill block from message text.
44
52
  * Returns null if the text doesn't contain a skill block.
@@ -72,8 +80,6 @@ function estimateMessagesTokens(messages) {
72
80
  // ============================================================================
73
81
  // Constants
74
82
  // ============================================================================
75
- /** Standard thinking levels */
76
- const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
77
83
  /**
78
84
  * Which SURFACE a dialog answered locally belongs to, per binding mode.
79
85
  *
@@ -97,111 +103,88 @@ const LOCAL_SURFACE_BY_MODE = Object.freeze({
97
103
  // AgentSession Class
98
104
  // ============================================================================
99
105
  export class AgentSession {
106
+ agent;
107
+ sessionManager;
108
+ settingsManager;
109
+ _scopedModels;
110
+ // Event subscription state
111
+ _unsubscribeAgent;
112
+ _eventListeners = [];
113
+ _isAgentRunActive = false;
114
+ _agentRunAbortRequested = false;
115
+ _idleWaitPromise;
116
+ _resolveIdleWait;
117
+ /** Tracks pending steering messages for UI display. Removed when delivered. */
118
+ _steeringMessages = [];
119
+ /** Tracks pending follow-up messages for UI display. Removed when delivered. */
120
+ _followUpMessages = [];
121
+ /** Messages queued to be included with the next user prompt as context ("asides"). */
122
+ _pendingNextTurnMessages = [];
123
+ /** Context-only custom messages queued during a run, flushed once the current turn's tool results are in. */
124
+ _pendingCustomMessages = [];
125
+ // Compaction state
126
+ _compactionAbortController = undefined;
127
+ _autoCompactionAbortController = undefined;
128
+ _overflowRecoveryAttempted = false;
129
+ // Branch summarization state
130
+ _branchSummaryAbortController = undefined;
131
+ // Retry state
132
+ _retryAbortController = undefined;
133
+ _retryAttempt = 0;
134
+ /**
135
+ * Failed response that the next request repeats, set by auto-retry and overflow recovery. The
136
+ * retry is routed with it as `failed`, since the context no longer contains it.
137
+ */
138
+ _failedResponse;
139
+ // Bash execution state
140
+ _bashAbortControllers = new Set();
141
+ _pendingBashMessages = [];
142
+ // Extension system
143
+ _extensionRunner;
144
+ _turnIndex = 0;
145
+ _entryIdsByMessage = new WeakMap();
146
+ _boundaryDispatchedMessages = new WeakSet();
147
+ _lastAssistantMessage;
148
+ _lastAssistantToolResults = [];
149
+ _lastActivityOutcome = "completed";
150
+ _isBeforeSettle = false;
151
+ _abortDuringBeforeSettle = false;
152
+ _isEmittingAgentSettled = false;
153
+ _deferredSettledActions = [];
154
+ _resourceLoader;
155
+ _customTools;
156
+ _baseToolDefinitions = new Map();
157
+ _cwd;
158
+ _extensionRunnerRef;
159
+ _initialActiveToolNames;
160
+ _usesDefaultTools;
161
+ _allowedToolNames;
162
+ _excludedToolNames;
163
+ _baseToolsOverride;
164
+ _sessionStartEvent;
165
+ _extensionUIContext;
166
+ _permissionRelay;
167
+ _extensionMode = "print";
168
+ _extensionCommandContextActions;
169
+ _extensionAbortHandler;
170
+ _extensionShutdownHandler;
171
+ _extensionErrorListener;
172
+ _extensionErrorUnsubscriber;
173
+ _modelRuntime;
174
+ _cacheWarmer;
175
+ // Tool registry for extension getTools/setTools
176
+ _toolRegistry = new Map();
177
+ /** Created on the first `ctx.executeTool()` call. */
178
+ _nestedToolCalls;
179
+ /** Declared tools whose declarations requests leave out, from `prepareLoadout` hooks. */
180
+ _hiddenDeclarations = new Set();
181
+ _toolDefinitions = new Map();
182
+ _toolPromptSnippets = new Map();
183
+ _toolPromptGuidelines = new Map();
184
+ _baseSystemPromptOptions;
185
+ /** Prompt options after before_agent_start mutations for the active run. */
186
+ _runSystemPromptOptions;
100
187
  constructor(config) {
101
- this._eventListeners = [];
102
- this._isAgentRunActive = false;
103
- /** Tracks pending steering messages for UI display. Removed when delivered. */
104
- this._steeringMessages = [];
105
- /** Tracks pending follow-up messages for UI display. Removed when delivered. */
106
- this._followUpMessages = [];
107
- /** Messages queued to be included with the next user prompt as context ("asides"). */
108
- this._pendingNextTurnMessages = [];
109
- /** Context-only custom messages queued during a run, flushed once the current turn's tool results are in. */
110
- this._pendingCustomMessages = [];
111
- // Compaction state
112
- this._compactionAbortController = undefined;
113
- this._autoCompactionAbortController = undefined;
114
- this._overflowRecoveryAttempted = false;
115
- // Branch summarization state
116
- this._branchSummaryAbortController = undefined;
117
- // Retry state
118
- this._retryAbortController = undefined;
119
- this._retryAttempt = 0;
120
- // Bash execution state
121
- this._bashAbortControllers = new Set();
122
- this._pendingBashMessages = [];
123
- this._turnIndex = 0;
124
- this._baseToolDefinitions = new Map();
125
- this._extensionMode = "print";
126
- // Tool registry for extension getTools/setTools
127
- this._toolRegistry = new Map();
128
- this._toolDefinitions = new Map();
129
- this._toolPromptSnippets = new Map();
130
- this._toolPromptGuidelines = new Map();
131
- // Base system prompt (without extension appends) - used to apply fresh appends each turn
132
- this._baseSystemPrompt = "";
133
- // Track last assistant message for auto-compaction check
134
- this._lastAssistantMessage = undefined;
135
- /** Internal handler for agent events - shared by subscribe and reconnect */
136
- this._handleAgentEvent = async (event) => {
137
- // When a user message starts, check if it's from either queue and remove it BEFORE emitting
138
- // This ensures the UI sees the updated queue state
139
- if (event.type === "message_start" && event.message.role === "user") {
140
- this._overflowRecoveryAttempted = false;
141
- const messageText = contentText(event.message.content, "");
142
- if (messageText) {
143
- // Check steering queue first
144
- const steeringIndex = this._steeringMessages.indexOf(messageText);
145
- if (steeringIndex !== -1) {
146
- this._steeringMessages.splice(steeringIndex, 1);
147
- this._emitQueueUpdate();
148
- }
149
- else {
150
- // Check follow-up queue
151
- const followUpIndex = this._followUpMessages.indexOf(messageText);
152
- if (followUpIndex !== -1) {
153
- this._followUpMessages.splice(followUpIndex, 1);
154
- this._emitQueueUpdate();
155
- }
156
- }
157
- }
158
- }
159
- // Emit to extensions first
160
- await this._emitExtensionEvent(event);
161
- // Notify all listeners
162
- this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
163
- // Handle session persistence
164
- if (event.type === "message_end") {
165
- // Check if this is a custom message from extensions
166
- if (event.message.role === "custom") {
167
- // Persist as CustomMessageEntry
168
- this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
169
- }
170
- else if (event.message.role === "user" ||
171
- event.message.role === "assistant" ||
172
- event.message.role === "toolResult") {
173
- // Regular LLM message - persist as SessionMessageEntry
174
- this.sessionManager.appendMessage(event.message);
175
- }
176
- // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
177
- // Track assistant message for auto-compaction (checked on agent_end)
178
- if (event.message.role === "assistant") {
179
- this._lastAssistantMessage = event.message;
180
- const assistantMsg = event.message;
181
- if (assistantMsg.stopReason !== "error") {
182
- this._overflowRecoveryAttempted = false;
183
- }
184
- // Reset retry counter immediately on successful assistant response
185
- // This prevents accumulation across multiple LLM calls within a turn
186
- if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
187
- this._emit({
188
- type: "auto_retry_end",
189
- success: true,
190
- attempt: this._retryAttempt,
191
- });
192
- this._retryAttempt = 0;
193
- }
194
- }
195
- }
196
- // A turn ends after its assistant message and every tool result has been appended,
197
- // so this is the first point in the run where a context-only custom message can be
198
- // inserted without landing between a tool call and its result. Flushing after the
199
- // extension and listener dispatch above also picks up messages that turn_end
200
- // handlers queued.
201
- if (event.type === "turn_end") {
202
- this._flushPendingCustomMessages();
203
- }
204
- };
205
188
  this.agent = config.agent;
206
189
  this.sessionManager = config.sessionManager;
207
190
  this.settingsManager = config.settingsManager;
@@ -210,8 +193,13 @@ export class AgentSession {
210
193
  this._customTools = config.customTools ?? [];
211
194
  this._cwd = config.cwd;
212
195
  this._modelRuntime = config.modelRuntime;
196
+ this._cacheWarmer = config.cacheWarmer;
197
+ if (this._cacheWarmer) {
198
+ this._cacheWarmer.onWarmed = (entry) => this._emit({ type: "entry_appended", entry });
199
+ }
213
200
  this._extensionRunnerRef = config.extensionRunnerRef;
214
201
  this._initialActiveToolNames = config.initialActiveToolNames;
202
+ this._usesDefaultTools = config.usesDefaultTools ?? false;
215
203
  this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
216
204
  this._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;
217
205
  this._baseToolsOverride = config.baseToolsOverride;
@@ -221,18 +209,24 @@ export class AgentSession {
221
209
  this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
222
210
  this._installAgentToolHooks();
223
211
  this._installAgentNextTurnRefresh();
212
+ this._installAgentRequestProjection();
213
+ this._installAgentBoundaryHooks();
214
+ this._installHiddenDeclarationsProjection();
215
+ this._installAgentForcedPromptProjection();
224
216
  this._buildRuntime({
225
217
  activeToolNames: this._initialActiveToolNames,
226
218
  includeAllExtensionTools: true,
227
219
  });
220
+ if (this._initialActiveToolNames === undefined)
221
+ this._restoreToolsFromTranscript();
228
222
  }
229
223
  get modelRuntime() {
230
224
  return this._modelRuntime;
231
225
  }
232
- async _getRequiredRequestAuth(model) {
226
+ async _getRequiredRequestAuth(model, signal) {
233
227
  let result;
234
228
  try {
235
- result = await this._modelRuntime.getAuth(model);
229
+ result = await this._modelRuntime.getAuth(model, { signal });
236
230
  }
237
231
  catch (error) {
238
232
  const cause = error instanceof Error ? error.cause : undefined;
@@ -258,26 +252,71 @@ export class AgentSession {
258
252
  }
259
253
  throw new Error(formatNoApiKeyFoundMessage(model.provider));
260
254
  }
261
- async _getSummarizationRequestAuth(model) {
255
+ async _getSummarizationRequestAuth(selectedModel, signal) {
256
+ // Route a virtual model first: summaries size their input and output from the model they get.
257
+ const { model, thinkingLevel } = isVirtualModel(selectedModel)
258
+ ? await this._modelRuntime.resolveModel(selectedModel, convertToLlm(this.messages), {
259
+ reason: "direct",
260
+ thinkingLevel: this.thinkingLevel,
261
+ signal,
262
+ })
263
+ : { model: selectedModel, thinkingLevel: this.thinkingLevel };
262
264
  if (this.agent.streamFunction === streamSimple) {
263
- return this._getRequiredRequestAuth(model);
265
+ return { ...(await this._getRequiredRequestAuth(model, signal)), thinkingLevel };
264
266
  }
265
267
  try {
266
- const result = await this._modelRuntime.getAuth(model);
268
+ const result = await this._modelRuntime.getAuth(model, { signal });
267
269
  if (!result)
268
- return { model };
270
+ return { model, thinkingLevel };
269
271
  const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
270
272
  return {
271
273
  model: requestModel,
272
274
  apiKey: result.auth.apiKey,
273
275
  headers: withoutDeletedHeaders(result.auth.headers),
274
276
  env: result.env,
277
+ thinkingLevel,
275
278
  };
276
279
  }
277
- catch {
278
- return { model };
280
+ catch (error) {
281
+ if (signal?.aborted)
282
+ throw error;
283
+ return { model, thinkingLevel };
279
284
  }
280
285
  }
286
+ /**
287
+ * The model whose limits apply to `message`, or undefined when the message came from another
288
+ * model. Under a virtual selection, that is the physical model that produced it.
289
+ */
290
+ _modelForMessage(message) {
291
+ const model = this.model;
292
+ if (model && isVirtualModel(model))
293
+ return this._modelRuntime.getPhysicalModel(message.provider, message.model);
294
+ return model?.provider === message.provider && model.id === message.model ? model : undefined;
295
+ }
296
+ /**
297
+ * Record the selection on the current branch when the branch implies another one, so a resume
298
+ * restores it. Tree navigation can leave the latest `model_change` on another branch; responses
299
+ * cannot record a virtual selection because they name physical models. Responses do record a
300
+ * physical selection unless the branch holds a virtual one; checking a physical selection against
301
+ * responses would record it on every prompt while `prepareRequest` redirects to another model.
302
+ */
303
+ _recordSelection() {
304
+ const model = this.model;
305
+ if (!model)
306
+ return;
307
+ const getModel = (provider, modelId) => this._modelRuntime.getModel(provider, modelId);
308
+ const recorded = getBranchSelection(this.sessionManager.getBranch(), getModel);
309
+ if (!recorded || (recorded.provider === model.provider && recorded.modelId === model.id))
310
+ return;
311
+ const recordedModel = getModel(recorded.provider, recorded.modelId);
312
+ if (!isVirtualModel(model) && !(recordedModel && isVirtualModel(recordedModel)))
313
+ return;
314
+ this.sessionManager.appendModelChange(model.provider, model.id);
315
+ }
316
+ /** The model whose limits apply to the conversation. */
317
+ _limitsModel() {
318
+ return this.routedModel?.model ?? this.model;
319
+ }
281
320
  /**
282
321
  * Install tool hooks once on the Agent instance.
283
322
  *
@@ -287,50 +326,216 @@ export class AgentSession {
287
326
  * happens here instead of in wrappers.
288
327
  */
289
328
  _installAgentToolHooks() {
290
- this.agent.beforeToolCall = async ({ toolCall, args }) => {
291
- const runner = this._extensionRunner;
292
- if (!runner.hasHandlers("tool_call")) {
293
- return undefined;
294
- }
295
- try {
296
- return await runner.emitToolCall({
297
- type: "tool_call",
298
- toolName: toolCall.name,
299
- toolCallId: toolCall.id,
300
- input: args,
301
- });
302
- }
303
- catch (err) {
304
- if (err instanceof Error) {
305
- throw err;
306
- }
307
- throw new Error(`Extension failed, blocking execution: ${String(err)}`);
308
- }
309
- };
310
- this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
311
- const runner = this._extensionRunner;
312
- if (!runner.hasHandlers("tool_result")) {
313
- return undefined;
329
+ this.agent.beforeToolCall = (context) => this._beforeToolCall(context);
330
+ this.agent.afterToolCall = (context) => this._afterToolCall(context);
331
+ }
332
+ /** `tool_call` handlers. `parentToolCallId` is set for calls another tool made. */
333
+ async _beforeToolCall({ toolCall, args }, parentToolCallId) {
334
+ const runner = this._extensionRunner;
335
+ if (!runner.hasHandlers("tool_call")) {
336
+ return undefined;
337
+ }
338
+ try {
339
+ return await runner.emitToolCall({
340
+ type: "tool_call",
341
+ toolName: toolCall.name,
342
+ toolCallId: toolCall.id,
343
+ ...(parentToolCallId ? { parentToolCallId } : {}),
344
+ input: args,
345
+ });
346
+ }
347
+ catch (err) {
348
+ if (err instanceof Error) {
349
+ throw err;
314
350
  }
315
- const hookResult = await runner.emitToolResult({
351
+ throw new Error(`Extension failed, blocking execution: ${String(err)}`);
352
+ }
353
+ }
354
+ /** `tool_result` handlers and image normalization. `parentToolCallId` is set for calls another tool made. */
355
+ async _afterToolCall({ toolCall, args, result, isError }, parentToolCallId) {
356
+ const runner = this._extensionRunner;
357
+ const hookResult = runner.hasHandlers("tool_result")
358
+ ? await runner.emitToolResult({
316
359
  type: "tool_result",
317
360
  toolName: toolCall.name,
318
361
  toolCallId: toolCall.id,
362
+ ...(parentToolCallId ? { parentToolCallId } : {}),
319
363
  input: args,
320
364
  content: result.content,
321
365
  details: result.details,
366
+ ...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent }),
322
367
  isError,
323
368
  usage: result.usage,
369
+ })
370
+ : undefined;
371
+ const content = hookResult?.content ?? result.content ?? [];
372
+ // Runs after the extension hook so images injected or replaced by extensions are normalized too.
373
+ const resizeOptions = this._limitsModel()?.inputLimits?.images?.resize;
374
+ const normalizedContent = await normalizeToolResultImages(content, {
375
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
376
+ ...(resizeOptions ? { resizeOptions } : {}),
377
+ });
378
+ if (!hookResult && normalizedContent === content) {
379
+ return undefined;
380
+ }
381
+ // The hook result already dropped structured content that replaced content no longer matches.
382
+ return {
383
+ content: normalizedContent,
384
+ details: hookResult?.details,
385
+ structuredContent: hookResult ? hookResult.structuredContent : result.structuredContent,
386
+ isError: hookResult?.isError ?? isError,
387
+ usage: hookResult?.usage,
388
+ };
389
+ }
390
+ /**
391
+ * Run a call that the tool call `parentToolCallId` made through `ctx.executeTool()`. It goes
392
+ * through the agent's tool pipeline with the session's hooks, against the callable tools.
393
+ */
394
+ async _executeNestedToolCall(parentToolCallId, name, args, options) {
395
+ this._nestedToolCalls ??= new NestedToolCallRunner({
396
+ getTools: () => this._getCallableTools(),
397
+ isSequential: () => this.agent.toolExecution === "sequential",
398
+ runToolCall: (toolCall, parentId, signal, onUpdate) => {
399
+ const assistantMessage = this._findLastAssistantMessage();
400
+ if (!assistantMessage) {
401
+ return Promise.resolve({
402
+ toolCall,
403
+ result: { content: [{ type: "text", text: "No assistant message issued this call" }], details: {} },
404
+ isError: true,
405
+ });
406
+ }
407
+ return runToolCall(toolCall, {
408
+ tools: this._getCallableTools(),
409
+ assistantMessage,
410
+ context: { messages: this.agent.state.messages, tools: this.agent.state.tools },
411
+ beforeToolCall: (context) => this._beforeToolCall(context, parentId),
412
+ afterToolCall: (context) => this._afterToolCall(context, parentId),
413
+ signal,
414
+ onUpdate,
415
+ });
416
+ },
417
+ emit: async (event) => {
418
+ await this._extensionRunner.emit(event);
419
+ this._emit(event);
420
+ },
421
+ });
422
+ return this._nestedToolCalls.execute(parentToolCallId, name, args, options);
423
+ }
424
+ /** Whether `projection`, the current session projection, exceeds the compaction threshold of `model`. */
425
+ _exceedsCompactionThreshold(model, projection) {
426
+ if (model.contextWindow <= 0)
427
+ return false;
428
+ return shouldCompact(estimateProjectedContextTokens(projection, this.sessionManager.getBranch()).tokens, model.contextWindow, this.settingsManager.getCompactionSettings(this.model));
429
+ }
430
+ async _compactBeforeNextAssistantResponse(context) {
431
+ const projection = this.sessionManager.buildSessionProjection();
432
+ // A virtual selection is checked in prepareRequest, against the model the request is routed to.
433
+ const model = this.model;
434
+ if (!model || isVirtualModel(model) || !this._exceedsCompactionThreshold(model, projection)) {
435
+ return { ...context, messages: projection.messages };
436
+ }
437
+ await this._runAutoCompaction("threshold", false);
438
+ return { ...context, messages: this.sessionManager.buildSessionProjection().messages };
439
+ }
440
+ _installAgentRequestProjection() {
441
+ const previousPrepareRequest = this.agent.prepareRequest;
442
+ this.agent.prepareRequest = async (request, signal) => {
443
+ const failed = this._failedResponse;
444
+ this._failedResponse = undefined;
445
+ const prepare = async () => {
446
+ const projection = this.sessionManager.buildSessionProjection();
447
+ const canonicalContext = {
448
+ ...request.context,
449
+ messages: projection.messages,
450
+ // Messages declare the provider-visible loadout; context.tools keeps executable implementations.
451
+ tools: this.agent.state.tools.slice(),
452
+ };
453
+ const previous = await previousPrepareRequest?.({
454
+ ...request,
455
+ context: canonicalContext,
456
+ model: this.agent.state.model,
457
+ thinkingLevel: this.agent.state.thinkingLevel,
458
+ }, signal);
459
+ return { previous, context: previous?.context ?? canonicalContext, projection };
460
+ };
461
+ let { previous, context, projection } = await prepare();
462
+ const model = previous?.model ?? this.agent.state.model;
463
+ const thinkingLevel = previous?.thinkingLevel ?? this.agent.state.thinkingLevel;
464
+ if (!isVirtualModel(model))
465
+ return { ...previous, context, model, thinkingLevel };
466
+ // The selection stays in agent state; only this request uses the routed model. A routing
467
+ // failure rejects, which ends the run with an error response. Only messages the user wrote
468
+ // start a turn; extension messages can follow them, e.g. from before_agent_start.
469
+ const lastResponse = context.messages.findLastIndex((message) => message.role === "assistant");
470
+ const userTurn = context.messages.slice(lastResponse + 1).some((message) => message.role === "user");
471
+ const state = getVirtualModelState(this.sessionManager.getBranch(), model.provider, model.id);
472
+ const route = await this._modelRuntime.resolveModel(model, convertToLlm(context.messages), {
473
+ reason: failed ? "retry" : userTurn ? "user" : "continuation",
474
+ thinkingLevel,
475
+ signal,
476
+ failed,
477
+ state,
324
478
  });
325
- if (!hookResult) {
326
- return undefined;
479
+ if (route.state !== undefined && route.state !== state) {
480
+ const data = { provider: model.provider, modelId: model.id, state: route.state };
481
+ const entry = this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(VIRTUAL_MODEL_STATE_ENTRY, data));
482
+ if (entry)
483
+ this._emit({ type: "entry_appended", entry });
327
484
  }
328
- return {
329
- content: hookResult.content,
330
- details: hookResult.details,
331
- isError: hookResult.isError ?? isError,
332
- usage: hookResult.usage,
333
- };
485
+ // The route stands: the router already decided this request. The state entry does not change
486
+ // the projection.
487
+ if (this._exceedsCompactionThreshold(route.model, projection)) {
488
+ await this._runAutoCompaction("threshold", false);
489
+ ({ previous, context } = await prepare());
490
+ }
491
+ return { ...previous, context, model: route.model, thinkingLevel: route.thinkingLevel };
492
+ };
493
+ }
494
+ async _dispatchTurnEndBoundary(message, toolResults) {
495
+ this._lastActivityOutcome =
496
+ message.stopReason === "aborted" ? "aborted" : message.stopReason === "error" ? "error" : "completed";
497
+ const messageEntryId = this._findPersistedMessageEntryId(message);
498
+ if (!this._extensionRunner.hasHandlers("turn_end"))
499
+ return false;
500
+ if (!messageEntryId) {
501
+ this._extensionRunner.emitError({
502
+ extensionPath: "<boundary>",
503
+ event: "turn_end",
504
+ error: "turn_end could not resolve the persisted assistant entry ID",
505
+ });
506
+ return false;
507
+ }
508
+ const toolResultEntryIds = toolResults.flatMap((result) => {
509
+ const entryId = this._findPersistedMessageEntryId(result);
510
+ return entryId ? [entryId] : [];
511
+ });
512
+ const boundary = await this._extensionRunner.emitBoundary({
513
+ type: "turn_end",
514
+ turnIndex: this._turnIndex,
515
+ message,
516
+ toolResults,
517
+ messageEntryId,
518
+ toolResultEntryIds,
519
+ outcome: this._lastActivityOutcome,
520
+ }, (entries) => this._buildBoundaryContext(entries, "turn_end"));
521
+ this._commitBoundaryDrafts(boundary.entries);
522
+ if (boundary.continue && !this._buildBoundaryContext([], "turn_end").canContinue) {
523
+ this._reportInvalidBoundaryContinuation("turn_end");
524
+ return false;
525
+ }
526
+ return boundary.continue;
527
+ }
528
+ _installAgentBoundaryHooks() {
529
+ const previousFinishTurn = this.agent.finishTurn;
530
+ this.agent.finishTurn = async (turn, signal) => {
531
+ this._boundaryDispatchedMessages.add(turn.message);
532
+ const extensionContinue = await this._dispatchTurnEndBoundary(turn.message, turn.toolResults);
533
+ const previousDecision = await previousFinishTurn?.(turn, signal);
534
+ if (previousDecision?.action === "end")
535
+ return previousDecision;
536
+ if (extensionContinue || previousDecision?.action === "continue")
537
+ return { action: "continue" };
538
+ return undefined;
334
539
  };
335
540
  }
336
541
  _installAgentNextTurnRefresh() {
@@ -339,15 +544,28 @@ export class AgentSession {
339
544
  ? async (_turn, signal) => await this.agent.prepareNextTurn?.(signal)
340
545
  : undefined);
341
546
  this.agent.prepareNextTurnWithContext = async (turn, signal) => {
342
- const previousSnapshot = await previousPrepareNextTurnWithContext?.(turn, signal);
343
- const previousContext = previousSnapshot?.context ?? turn.context;
547
+ const context = await this._compactBeforeNextAssistantResponse(turn.context);
548
+ const previousSnapshot = await previousPrepareNextTurnWithContext?.({ ...turn, context }, signal);
549
+ const nextContext = previousSnapshot?.context ?? context;
550
+ const runOptions = this._runSystemPromptOptions ?? this._baseSystemPromptOptions;
551
+ const options = normalizeBuildSystemPromptOptions({
552
+ ...runOptions,
553
+ selectedTools: this.getActiveToolNames(),
554
+ toolSnippets: { ...this._baseSystemPromptOptions.toolSnippets, ...runOptions.toolSnippets },
555
+ toolGuidelines: { ...this._baseSystemPromptOptions.toolGuidelines, ...runOptions.toolGuidelines },
556
+ });
557
+ const updateMessage = this._preparePromptAndToolLoadout(options, nextContext.messages);
558
+ // Keep session.systemPrompt and ctx.getSystemPrompt() in step with what the provider sees.
559
+ this._runSystemPromptOptions = options;
344
560
  return {
345
561
  ...previousSnapshot,
346
562
  context: {
347
- ...previousContext,
348
- systemPrompt: this._systemPromptOverride ?? this._baseSystemPrompt,
563
+ ...nextContext,
349
564
  tools: this.agent.state.tools.slice(),
350
565
  },
566
+ messages: updateMessage
567
+ ? [...(previousSnapshot?.messages ?? []), updateMessage]
568
+ : previousSnapshot?.messages,
351
569
  model: this.agent.state.model,
352
570
  thinkingLevel: this.agent.state.thinkingLevel,
353
571
  };
@@ -356,6 +574,84 @@ export class AgentSession {
356
574
  // =========================================================================
357
575
  // Event Subscription
358
576
  // =========================================================================
577
+ _refreshFinalizedContext() {
578
+ const projection = this.sessionManager.buildSessionProjection();
579
+ for (const entry of projection.entries) {
580
+ for (const message of entry.messages)
581
+ this._entryIdsByMessage.set(message, entry.sourceEntry.id);
582
+ }
583
+ this.agent.state.messages = projection.messages;
584
+ }
585
+ _applyBoundaryDrafts(manager, drafts) {
586
+ const appended = [];
587
+ for (const draft of drafts) {
588
+ let entryId;
589
+ switch (draft.type) {
590
+ case "custom":
591
+ entryId = manager.appendCustomEntry(draft.customType, draft.data);
592
+ break;
593
+ case "custom_message":
594
+ entryId = manager.appendCustomMessageEntry(draft.customType, draft.content, draft.display, draft.details);
595
+ break;
596
+ case "context_edit":
597
+ entryId = manager.appendContextEdit(draft.targetId, draft.replacement);
598
+ break;
599
+ case "compaction": {
600
+ const tokensBefore = estimateProjectedContextTokens(manager.buildSessionProjection(), manager.getBranch()).tokens;
601
+ entryId = manager.appendCompaction(draft.summary, draft.firstKeptEntryId, tokensBefore, draft.details, true, draft.usage);
602
+ break;
603
+ }
604
+ }
605
+ const entry = manager.getEntry(entryId);
606
+ if (entry)
607
+ appended.push(entry);
608
+ }
609
+ return appended;
610
+ }
611
+ _createBoundaryPreviewManager(drafts) {
612
+ const header = this.sessionManager.getHeader();
613
+ if (!header)
614
+ throw new Error("Session header is missing");
615
+ const manager = SessionManager.inMemory(this._cwd, undefined, [header, ...this.sessionManager.getBranch()]);
616
+ this._applyBoundaryDrafts(manager, drafts);
617
+ return manager;
618
+ }
619
+ _getPendingBoundaryMessages() {
620
+ return [...this.agent.peekQueuedMessages(), ...this._pendingCustomMessages];
621
+ }
622
+ _buildBoundaryContext(drafts, boundary) {
623
+ const projection = this._createBoundaryPreviewManager(drafts).buildSessionProjection();
624
+ const pendingMessages = this._getPendingBoundaryMessages();
625
+ const llmMessages = convertToLlm(projection.messages);
626
+ const finalRole = llmMessages[llmMessages.length - 1]?.role;
627
+ const hasNonSystemContext = llmMessages.some((message) => message.role !== "system");
628
+ const contextCanContinue = hasNonSystemContext && finalRole !== "assistant";
629
+ const pendingCustomContext = this._pendingCustomMessages.length > 0;
630
+ return {
631
+ contextEntries: projection.entries,
632
+ contextMessages: projection.messages,
633
+ llmMessages,
634
+ pendingMessages,
635
+ canContinue: contextCanContinue ||
636
+ pendingCustomContext ||
637
+ (boundary === "turn_end"
638
+ ? this.agent.hasQueuedMessages()
639
+ : finalRole === "assistant" && this.agent.hasQueuedMessages()),
640
+ };
641
+ }
642
+ _commitBoundaryDrafts(drafts) {
643
+ const appended = this._applyBoundaryDrafts(this.sessionManager, drafts);
644
+ this._refreshFinalizedContext();
645
+ for (const entry of appended)
646
+ this._emit({ type: "entry_appended", entry });
647
+ }
648
+ _reportInvalidBoundaryContinuation(event) {
649
+ this._extensionRunner.emitError({
650
+ extensionPath: "<boundary>",
651
+ event,
652
+ error: `${event} requested continuation without runnable model context`,
653
+ });
654
+ }
359
655
  /** Emit an event to all listeners */
360
656
  _emit(event) {
361
657
  for (const l of this._eventListeners) {
@@ -369,6 +665,11 @@ export class AgentSession {
369
665
  followUp: [...this._followUpMessages],
370
666
  });
371
667
  }
668
+ async _emitSessionCompactFailed(event) {
669
+ if (this._extensionRunner.hasHandlers("session_compact_failed")) {
670
+ await this._extensionRunner.emit({ type: "session_compact_failed", ...event });
671
+ }
672
+ }
372
673
  _getIdleWaitPromise() {
373
674
  if (!this._idleWaitPromise) {
374
675
  this._idleWaitPromise = new Promise((resolve) => {
@@ -378,7 +679,7 @@ export class AgentSession {
378
679
  return this._idleWaitPromise;
379
680
  }
380
681
  _resolveIdleWaitIfIdle() {
381
- if (this._isAgentRunActive || !this._resolveIdleWait) {
682
+ if (!this.isIdle || !this._resolveIdleWait) {
382
683
  return;
383
684
  }
384
685
  const resolve = this._resolveIdleWait;
@@ -387,16 +688,120 @@ export class AgentSession {
387
688
  resolve();
388
689
  }
389
690
  async _emitAgentSettled() {
691
+ this._cacheWarmer?.onAgentSettled();
390
692
  this._isAgentRunActive = false;
693
+ this._isEmittingAgentSettled = true;
391
694
  try {
392
695
  await this._extensionRunner.emit({ type: "agent_settled" });
393
696
  this._emit({ type: "agent_settled" });
394
697
  }
395
698
  finally {
396
- this._resolveIdleWaitIfIdle();
699
+ this._isEmittingAgentSettled = false;
397
700
  }
398
- }
701
+ const deferred = this._deferredSettledActions.splice(0);
702
+ if (deferred.length > 0) {
703
+ try {
704
+ for (const action of deferred)
705
+ await action();
706
+ }
707
+ finally {
708
+ this._resolveIdleWaitIfIdle();
709
+ }
710
+ return;
711
+ }
712
+ this._resolveIdleWaitIfIdle();
713
+ }
714
+ /** Internal handler for agent events - shared by subscribe and reconnect */
715
+ _handleAgentEvent = async (event) => {
716
+ // Record the calls a tool made through ctx.executeTool() and their usage on its result message.
717
+ if (this._nestedToolCalls) {
718
+ if (event.type === "message_start" && event.message.role === "toolResult") {
719
+ const message = event.message;
720
+ const summary = this._nestedToolCalls.takeRecord(message.toolCallId);
721
+ if (summary?.calls)
722
+ message.nestedCalls = summary.calls;
723
+ if (summary?.usage) {
724
+ message.usage = message.usage ? combineUsage(message.usage, summary.usage) : summary.usage;
725
+ }
726
+ }
727
+ else if (event.type === "agent_end") {
728
+ this._nestedToolCalls.clear();
729
+ }
730
+ }
731
+ // When a user message starts, check if it's from either queue and remove it BEFORE emitting
732
+ // This ensures the UI sees the updated queue state
733
+ if (event.type === "message_start" && event.message.role === "user") {
734
+ this._overflowRecoveryAttempted = false;
735
+ const messageText = contentText(event.message.content, "");
736
+ if (messageText) {
737
+ // Check steering queue first
738
+ const steeringIndex = this._steeringMessages.indexOf(messageText);
739
+ if (steeringIndex !== -1) {
740
+ this._steeringMessages.splice(steeringIndex, 1);
741
+ this._emitQueueUpdate();
742
+ }
743
+ else {
744
+ // Check follow-up queue
745
+ const followUpIndex = this._followUpMessages.indexOf(messageText);
746
+ if (followUpIndex !== -1) {
747
+ this._followUpMessages.splice(followUpIndex, 1);
748
+ this._emitQueueUpdate();
749
+ }
750
+ }
751
+ }
752
+ }
753
+ // Emit to extensions first, then notify public listeners.
754
+ await this._emitExtensionEvent(event);
755
+ this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
756
+ // Handle session persistence
757
+ if (event.type === "message_end") {
758
+ let entryId;
759
+ // Check if this is a custom message from extensions
760
+ if (event.message.role === "custom") {
761
+ // Persist as CustomMessageEntry
762
+ entryId = this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
763
+ }
764
+ else if (event.message.role === "system" ||
765
+ event.message.role === "user" ||
766
+ event.message.role === "assistant" ||
767
+ event.message.role === "toolResult") {
768
+ // Regular LLM message - persist as SessionMessageEntry
769
+ entryId = this.sessionManager.appendMessage(event.message);
770
+ }
771
+ if (entryId)
772
+ this._entryIdsByMessage.set(event.message, entryId);
773
+ // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
774
+ if (event.message.role === "assistant") {
775
+ const assistantMsg = event.message;
776
+ this._lastAssistantMessage = assistantMsg;
777
+ if (assistantMsg.stopReason !== "error" && assistantMsg.stopReason !== "length") {
778
+ this._overflowRecoveryAttempted = false;
779
+ }
780
+ // Reset retry counter immediately on successful assistant response
781
+ // This prevents accumulation across multiple LLM calls within a turn
782
+ if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
783
+ this._emit({
784
+ type: "auto_retry_end",
785
+ success: true,
786
+ attempt: this._retryAttempt,
787
+ });
788
+ this._retryAttempt = 0;
789
+ }
790
+ }
791
+ }
792
+ // A turn ends after its assistant message and every tool result has been appended,
793
+ // so this is the first point in the run where a context-only custom message can be
794
+ // inserted without landing between a tool call and its result. Flushing after the
795
+ // extension and listener dispatch above also picks up messages that turn_end
796
+ // handlers queued.
797
+ if (event.type === "turn_end") {
798
+ this._lastAssistantToolResults = event.toolResults;
799
+ this._flushPendingCustomMessages();
800
+ }
801
+ };
399
802
  _willRetryAfterAgentEnd(event) {
803
+ if (this._agentRunAbortRequested)
804
+ return false;
400
805
  const settings = this.settingsManager.getRetrySettings();
401
806
  if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
402
807
  return false;
@@ -409,6 +814,47 @@ export class AgentSession {
409
814
  }
410
815
  return false;
411
816
  }
817
+ _findPersistedMessageEntryId(message) {
818
+ const mapped = this._entryIdsByMessage.get(message);
819
+ if (mapped)
820
+ return mapped;
821
+ for (const entry of [...this.sessionManager.getBranch()].reverse()) {
822
+ if (entry.type === "message" && entry.message === message)
823
+ return entry.id;
824
+ }
825
+ const messageIndex = this.agent.state.messages.indexOf(message);
826
+ if (messageIndex < 0)
827
+ return undefined;
828
+ const projection = this.sessionManager.buildSessionProjection();
829
+ let projectedIndex = 0;
830
+ for (const entry of projection.entries) {
831
+ for (let i = 0; i < entry.messages.length; i++) {
832
+ if (projectedIndex === messageIndex) {
833
+ this._entryIdsByMessage.set(message, entry.sourceEntry.id);
834
+ return entry.sourceEntry.id;
835
+ }
836
+ projectedIndex++;
837
+ }
838
+ }
839
+ return undefined;
840
+ }
841
+ _omitRecoveryAttempt(message, toolResults = []) {
842
+ const targets = [message, ...toolResults];
843
+ const targetIds = targets.map((target) => this._findPersistedMessageEntryId(target));
844
+ const unresolvedProjectedTarget = targets.some((target, index) => targetIds[index] === undefined && this.agent.state.messages.includes(target));
845
+ if (unresolvedProjectedTarget) {
846
+ throw new Error("Cannot persist recovery omission because a projected message has no source entry");
847
+ }
848
+ for (const targetId of targetIds) {
849
+ if (!targetId)
850
+ continue;
851
+ const editId = this.sessionManager.appendContextEdit(targetId, null);
852
+ const entry = this.sessionManager.getEntry(editId);
853
+ if (entry)
854
+ this._emit({ type: "entry_appended", entry });
855
+ }
856
+ this._refreshFinalizedContext();
857
+ }
412
858
  /** Find the last assistant message in agent state (including aborted ones) */
413
859
  _findLastAssistantMessage() {
414
860
  const messages = this.agent.state.messages;
@@ -452,13 +898,9 @@ export class AgentSession {
452
898
  await this._extensionRunner.emit(extensionEvent);
453
899
  }
454
900
  else if (event.type === "turn_end") {
455
- const extensionEvent = {
456
- type: "turn_end",
457
- turnIndex: this._turnIndex,
458
- message: event.message,
459
- toolResults: event.toolResults,
460
- };
461
- await this._extensionRunner.emit(extensionEvent);
901
+ if (event.message.role === "assistant" && !this._boundaryDispatchedMessages.delete(event.message)) {
902
+ await this._dispatchTurnEndBoundary(event.message, event.toolResults);
903
+ }
462
904
  this._turnIndex++;
463
905
  }
464
906
  else if (event.type === "message_start") {
@@ -565,15 +1007,32 @@ export class AgentSession {
565
1007
  this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().");
566
1008
  this._disconnectFromAgent();
567
1009
  this._eventListeners = [];
1010
+ if (this._cacheWarmer) {
1011
+ this._cacheWarmer.onWarmed = undefined;
1012
+ this._cacheWarmer.cancel();
1013
+ }
568
1014
  cleanupSessionResources(this.sessionId);
569
1015
  }
570
1016
  // =========================================================================
571
1017
  // Read-only State Access
572
1018
  // =========================================================================
1019
+ /** Refresh the public finalized transcript from the canonical session projection. */
1020
+ refreshContext() {
1021
+ this._refreshFinalizedContext();
1022
+ }
573
1023
  /** Full agent state */
574
1024
  get state() {
575
1025
  return this.agent.state;
576
1026
  }
1027
+ /** Current cache-warming state and the policy inputs that produced it. */
1028
+ get cacheWarmingStatus() {
1029
+ return this._cacheWarmer?.status;
1030
+ }
1031
+ /** Persist the cache-warming mode and immediately reconcile active warming. */
1032
+ setCacheWarmingMode(mode) {
1033
+ this.settingsManager.setCacheWarmingMode(mode);
1034
+ this._cacheWarmer?.onModeChanged();
1035
+ }
577
1036
  /** Current model (may be undefined if not yet selected) */
578
1037
  get model() {
579
1038
  return this.agent.state.model;
@@ -582,29 +1041,41 @@ export class AgentSession {
582
1041
  get thinkingLevel() {
583
1042
  return this.agent.state.thinkingLevel;
584
1043
  }
1044
+ /** Under a virtual selection, the physical model and thinking level of the latest successful response. */
1045
+ get routedModel() {
1046
+ if (!this.model || !isVirtualModel(this.model))
1047
+ return undefined;
1048
+ const latest = findLatestResponse(this.agent.state.messages);
1049
+ const model = latest && this._modelRuntime.getPhysicalModel(latest.provider, latest.model);
1050
+ return model && { model, thinkingLevel: latest?.thinkingLevel };
1051
+ }
585
1052
  /** Whether the session is currently processing an agent run or post-run continuation. */
586
1053
  get isStreaming() {
587
1054
  return this._isAgentRunActive;
588
1055
  }
589
- /** Whether the session has no active agent run, retry, auto-compaction, or queued continuation. */
1056
+ /** Whether the session has no active agent run, compaction, branch summary, retry, or queued continuation. */
590
1057
  get isIdle() {
591
- return !this._isAgentRunActive;
1058
+ return !this._isAgentRunActive && !this.isCompacting;
592
1059
  }
593
- /** Current effective system prompt (includes any per-turn extension modifications) */
1060
+ /** Current effective system prompt, including changes not yet sent to the model. */
594
1061
  get systemPrompt() {
595
- return this.agent.state.systemPrompt;
1062
+ return buildSystemPrompt(this._runSystemPromptOptions ?? this._baseSystemPromptOptions);
596
1063
  }
597
1064
  /** Current retry attempt (0 if not retrying) */
598
1065
  get retryAttempt() {
599
1066
  return this._retryAttempt;
600
1067
  }
601
1068
  /**
602
- * Get the names of currently active tools.
603
- * Returns the names of tools currently set on the agent.
1069
+ * Get the names of currently active tools, which are the tools declared to the model.
1070
+ * Tools with `codemode` or `deferred` exposure are callable from other tools without being active.
604
1071
  */
605
1072
  getActiveToolNames() {
606
1073
  return this.agent.state.tools.map((t) => t.name);
607
1074
  }
1075
+ /** Get the names of the tools that tools can call through `ctx.executeTool()`. */
1076
+ getCallableToolNames() {
1077
+ return this._getCallableTools().map((t) => t.name);
1078
+ }
608
1079
  /**
609
1080
  * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
610
1081
  */
@@ -614,6 +1085,9 @@ export class AgentSession {
614
1085
  description: definition.description,
615
1086
  parameters: definition.parameters,
616
1087
  promptGuidelines: definition.promptGuidelines,
1088
+ exposure: this._getToolExposure(definition.name),
1089
+ ...(definition.namespace ? { namespace: definition.namespace } : {}),
1090
+ ...(definition.annotations ? { annotations: { ...definition.annotations } } : {}),
617
1091
  sourceInfo,
618
1092
  }));
619
1093
  }
@@ -622,24 +1096,79 @@ export class AgentSession {
622
1096
  }
623
1097
  /**
624
1098
  * Set active tools by name.
625
- * Only tools in the registry can be enabled. Unknown tool names are ignored.
1099
+ * Only tools in the registry can be enabled. Unknown and hidden tool names are ignored.
626
1100
  * Also rebuilds the system prompt to reflect the new tool set.
627
1101
  * Changes take effect on the next agent turn.
628
1102
  */
629
1103
  setActiveToolsByName(toolNames) {
630
- const tools = [];
631
- const validToolNames = [];
632
- for (const name of toolNames) {
1104
+ const tools = this._applyToolLoadout(toolNames);
1105
+ this._rebuildSystemPrompt(tools.map((tool) => tool.name));
1106
+ }
1107
+ _getToolExposure(name) {
1108
+ return this._toolDefinitions.get(name)?.definition.exposure ?? "direct";
1109
+ }
1110
+ /**
1111
+ * Tools callable through `ctx.executeTool()`: the active `direct` tools and every registered
1112
+ * `codemode` or `deferred` tool.
1113
+ */
1114
+ _getCallableTools(active = new Set(this.getActiveToolNames())) {
1115
+ return [...this._toolRegistry.values()].filter((tool) => {
1116
+ const exposure = this._getToolExposure(tool.name);
1117
+ return exposure === "codemode" || exposure === "deferred" || (exposure === "direct" && active.has(tool.name));
1118
+ });
1119
+ }
1120
+ /**
1121
+ * Set the agent's tools for the given active tool names and return them. The active tools are
1122
+ * the registered, non-hidden ones; they are declared to the model. Active tools with a
1123
+ * `prepareLoadout` hook can change the declared descriptions and hide declarations from
1124
+ * requests (see {@link _installHiddenDeclarationsProjection}).
1125
+ */
1126
+ _applyToolLoadout(toolNames) {
1127
+ const tools = [...new Set(toolNames)].flatMap((name) => {
633
1128
  const tool = this._toolRegistry.get(name);
634
- if (tool) {
635
- tools.push(tool);
636
- validToolNames.push(name);
1129
+ return tool && this._getToolExposure(name) !== "hidden" ? [tool] : [];
1130
+ });
1131
+ const hooks = tools.flatMap((tool) => {
1132
+ const entry = this._toolDefinitions.get(tool.name);
1133
+ return entry?.definition.prepareLoadout ? [entry] : [];
1134
+ });
1135
+ const hidden = new Set();
1136
+ let declared = tools;
1137
+ if (hooks.length > 0) {
1138
+ const loadout = {
1139
+ declared: tools,
1140
+ callable: this._getCallableTools(new Set(tools.map((tool) => tool.name))),
1141
+ registered: [...this._toolRegistry.values()],
1142
+ getExposure: (name) => this._getToolExposure(name),
1143
+ getNamespace: (name) => this._toolDefinitions.get(name)?.definition.namespace,
1144
+ };
1145
+ const descriptions = new Map();
1146
+ for (const { definition, sourceInfo } of hooks) {
1147
+ try {
1148
+ const changes = definition.prepareLoadout?.(loadout);
1149
+ for (const [name, description] of Object.entries(changes?.descriptions ?? {})) {
1150
+ descriptions.set(name, description);
1151
+ }
1152
+ for (const name of changes?.hiddenDeclarations ?? [])
1153
+ hidden.add(name);
1154
+ }
1155
+ catch (error) {
1156
+ this._extensionRunner.emitError({
1157
+ extensionPath: sourceInfo.path,
1158
+ event: "prepare_loadout",
1159
+ error: error instanceof Error ? error.message : String(error),
1160
+ stack: error instanceof Error ? error.stack : undefined,
1161
+ });
1162
+ }
637
1163
  }
1164
+ declared = tools.map((tool) => {
1165
+ const description = descriptions.get(tool.name);
1166
+ return description === undefined ? tool : { ...tool, description };
1167
+ });
638
1168
  }
639
- this.agent.state.tools = tools;
640
- // Rebuild base system prompt with new tool set
641
- this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
642
- this.agent.state.systemPrompt = this._systemPromptOverride ?? this._baseSystemPrompt;
1169
+ this._hiddenDeclarations = hidden;
1170
+ this.agent.state.tools = declared;
1171
+ return declared;
643
1172
  }
644
1173
  /** Whether compaction or branch summarization is currently running */
645
1174
  get isCompacting() {
@@ -708,23 +1237,18 @@ export class AgentSession {
708
1237
  _rebuildSystemPrompt(toolNames) {
709
1238
  const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
710
1239
  const toolSnippets = {};
711
- const promptGuidelines = [];
712
- for (const name of validToolNames) {
1240
+ for (const name of this._toolRegistry.keys()) {
713
1241
  const snippet = this._toolPromptSnippets.get(name);
714
- if (snippet) {
1242
+ // Tools without a snippet are not listed. Hidden tools are only callable through another tool.
1243
+ if (snippet && !this._hiddenDeclarations.has(name))
715
1244
  toolSnippets[name] = snippet;
716
- }
717
- const toolGuidelines = this._toolPromptGuidelines.get(name);
718
- if (toolGuidelines) {
719
- promptGuidelines.push(...toolGuidelines);
720
- }
721
1245
  }
722
1246
  const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
723
1247
  const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
724
- const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
1248
+ const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : "";
725
1249
  const loadedSkills = this._resourceLoader.getSkills().skills;
726
1250
  const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
727
- this._baseSystemPromptOptions = {
1251
+ this._baseSystemPromptOptions = normalizeBuildSystemPromptOptions({
728
1252
  cwd: this._cwd,
729
1253
  skills: loadedSkills,
730
1254
  contextFiles: loadedContextFiles,
@@ -732,52 +1256,217 @@ export class AgentSession {
732
1256
  appendSystemPrompt,
733
1257
  selectedTools: validToolNames,
734
1258
  toolSnippets,
735
- promptGuidelines,
1259
+ toolGuidelines: Object.fromEntries(this._toolPromptGuidelines),
1260
+ });
1261
+ }
1262
+ /**
1263
+ * Apply a prompt and tool loadout for the next request. Sets the executable tools and
1264
+ * returns a system message patching the prompt sections the model currently has (replayed
1265
+ * from `messages`), or undefined when the prompt is unchanged. Tool changes are declared by
1266
+ * the agent loop before the request.
1267
+ *
1268
+ * A forced prompt does not affect the transcript: the structured sections are still diffed
1269
+ * and persisted, and the forced text is projected onto the request by
1270
+ * {@link _installAgentForcedPromptProjection}.
1271
+ */
1272
+ _preparePromptAndToolLoadout(options, messages = this.agent.state.messages) {
1273
+ options.selectedTools = this._applyToolLoadout(options.selectedTools).map((tool) => tool.name);
1274
+ // The tool list must match the declarations the request carries, so hidden tools are not listed.
1275
+ options.toolSnippets = Object.fromEntries(Object.entries(options.toolSnippets).filter(([name]) => !this._hiddenDeclarations.has(name)));
1276
+ const sections = diffSystemPromptSections(getCurrentSystemMessage(messages)?.sections ?? {}, buildSystemPromptSections(options));
1277
+ return sections ? { role: "system", content: "", sections, timestamp: Date.now() } : undefined;
1278
+ }
1279
+ /**
1280
+ * Send a forced prompt as the provider's leading system prompt without recording it.
1281
+ *
1282
+ * A `before_agent_start` handler that returns `systemPrompt` needs that exact text at the
1283
+ * head of the request; a mid-conversation system message would leave the original prompt
1284
+ * in place. The forced text is a rendering of the current prompt, so the transcript keeps
1285
+ * its structured sections and the request is projected instead: the system messages
1286
+ * collapse into one head holding the forced text and the current tools. Runs after the
1287
+ * `context` extension handlers.
1288
+ */
1289
+ /**
1290
+ * Remove the declarations that `prepareLoadout` hooks hide from every request. The whole
1291
+ * transcript is filtered with the current set, so the projected declarations stay consistent
1292
+ * across requests and only change when the loadout does.
1293
+ */
1294
+ _installHiddenDeclarationsProjection() {
1295
+ const previousTransformContext = this.agent.transformContext;
1296
+ this.agent.transformContext = async (messages, signal) => {
1297
+ const transformed = previousTransformContext ? await previousTransformContext(messages, signal) : messages;
1298
+ const hidden = this._hiddenDeclarations;
1299
+ if (hidden.size === 0)
1300
+ return transformed;
1301
+ return transformed.map((message) => {
1302
+ if (message.role !== "system" || (!message.toolsAdded && !message.toolsRemoved))
1303
+ return message;
1304
+ const { toolsAdded, toolsRemoved, ...rest } = message;
1305
+ const added = toolsAdded?.filter((tool) => !hidden.has(tool.name)) ?? [];
1306
+ const removed = toolsRemoved?.filter((tool) => !hidden.has(tool.name)) ?? [];
1307
+ return {
1308
+ ...rest,
1309
+ ...(added.length > 0 ? { toolsAdded: added } : {}),
1310
+ ...(removed.length > 0 ? { toolsRemoved: removed } : {}),
1311
+ };
1312
+ });
1313
+ };
1314
+ }
1315
+ _installAgentForcedPromptProjection() {
1316
+ const previousTransformContext = this.agent.transformContext;
1317
+ this.agent.transformContext = async (messages, signal) => {
1318
+ const transformed = previousTransformContext ? await previousTransformContext(messages, signal) : messages;
1319
+ const forced = this._runSystemPromptOptions?.forceSystemPrompt;
1320
+ if (forced === undefined)
1321
+ return transformed;
1322
+ const current = getCurrentSystemMessage(transformed);
1323
+ const head = {
1324
+ role: "system",
1325
+ content: forced,
1326
+ ...(current?.toolsAdded ? { toolsAdded: current.toolsAdded } : {}),
1327
+ timestamp: current?.timestamp ?? Date.now(),
1328
+ };
1329
+ return [head, ...transformed.filter((message) => message.role !== "system")];
736
1330
  };
737
- return buildSystemPrompt(this._baseSystemPromptOptions);
1331
+ }
1332
+ /**
1333
+ * Restore the active tool loadout declared by the session transcript, if it declares one.
1334
+ * Tools reachable only from other tools are never declared, but they do not depend on the active
1335
+ * set, so the transcript's declarations are the whole loadout.
1336
+ */
1337
+ _restoreToolsFromTranscript() {
1338
+ const current = getCurrentSystemMessage(this.sessionManager.buildSessionContext().messages);
1339
+ if (!current)
1340
+ return;
1341
+ this.setActiveToolsByName((current.toolsAdded ?? []).map((tool) => tool.name));
738
1342
  }
739
1343
  // =========================================================================
740
1344
  // Prompting
741
1345
  // =========================================================================
742
1346
  async _runAgentPrompt(messages) {
1347
+ this._agentRunAbortRequested = false;
1348
+ // Compaction before the prompt may have scheduled a retry; the new prompt replaces it.
1349
+ this._failedResponse = undefined;
1350
+ this._recordSelection();
743
1351
  this._isAgentRunActive = true;
744
1352
  try {
745
1353
  await this.agent.prompt(messages);
746
- while (await this._handlePostAgentRun()) {
1354
+ while (!this._agentRunAbortRequested) {
1355
+ if (await this._handlePostAgentRun()) {
1356
+ if (this._agentRunAbortRequested)
1357
+ break;
1358
+ await this.agent.continue();
1359
+ continue;
1360
+ }
1361
+ if (this._agentRunAbortRequested || !(await this._runBeforeSettleBoundary()))
1362
+ break;
1363
+ if (this._agentRunAbortRequested)
1364
+ break;
747
1365
  await this.agent.continue();
748
1366
  }
749
1367
  }
750
1368
  finally {
751
- this._systemPromptOverride = undefined;
1369
+ if (this._agentRunAbortRequested)
1370
+ this._finishCancelledRetry();
1371
+ this._failedResponse = undefined;
1372
+ this._runSystemPromptOptions = undefined;
752
1373
  this._flushPendingBashMessages();
753
1374
  this._flushPendingCustomMessages();
754
1375
  await this._emitAgentSettled();
755
1376
  }
756
1377
  }
757
1378
  async _handlePostAgentRun() {
758
- const msg = this._lastAssistantMessage;
1379
+ const message = this._lastAssistantMessage;
1380
+ const toolResults = this._lastAssistantToolResults;
759
1381
  this._lastAssistantMessage = undefined;
760
- if (!msg) {
1382
+ this._lastAssistantToolResults = [];
1383
+ if (this._agentRunAbortRequested) {
1384
+ this._finishCancelledRetry();
761
1385
  return false;
762
1386
  }
763
- if (this._isRetryableError(msg) && (await this._prepareRetry(msg))) {
764
- return true;
1387
+ if (!message)
1388
+ return this.agent.hasQueuedMessages();
1389
+ if (this._isRetryableError(message) && (await this._prepareRetry(message))) {
1390
+ if (this._agentRunAbortRequested)
1391
+ this._finishCancelledRetry();
1392
+ this._failedResponse = message;
1393
+ return !this._agentRunAbortRequested;
1394
+ }
1395
+ if (this._agentRunAbortRequested) {
1396
+ this._finishCancelledRetry();
1397
+ return false;
765
1398
  }
766
- if (msg.stopReason === "error" && this._retryAttempt > 0) {
1399
+ if (message.stopReason === "error" && this._retryAttempt > 0) {
767
1400
  this._emit({
768
1401
  type: "auto_retry_end",
769
1402
  success: false,
770
1403
  attempt: this._retryAttempt,
771
- finalError: msg.errorMessage,
1404
+ finalError: message.errorMessage,
772
1405
  });
773
1406
  this._retryAttempt = 0;
774
1407
  }
775
- if (await this._checkCompaction(msg)) {
776
- return true;
1408
+ if (await this._checkCompaction(message, true, toolResults)) {
1409
+ return !this._agentRunAbortRequested;
777
1410
  }
778
- // The agent loop drains both queues before emitting agent_end. Any messages
779
- // here were queued by agent_end extension handlers and need a continuation.
780
- return this.agent.hasQueuedMessages();
1411
+ // The low-level loop drains both queues before agent_end. Messages queued by
1412
+ // agent_end handlers require a fresh run before pre-settlement handlers fire.
1413
+ return !this._agentRunAbortRequested && this.agent.hasQueuedMessages();
1414
+ }
1415
+ async _runBeforeSettleBoundary() {
1416
+ if (!this._extensionRunner.hasHandlers("agent_before_settle"))
1417
+ return this.agent.hasQueuedMessages();
1418
+ this._isBeforeSettle = true;
1419
+ this._abortDuringBeforeSettle = false;
1420
+ try {
1421
+ const result = await this._extensionRunner.emitBoundary({ type: "agent_before_settle", outcome: this._lastActivityOutcome }, (entries) => this._buildBoundaryContext(entries, "agent_before_settle"));
1422
+ this._commitBoundaryDrafts(result.entries);
1423
+ this._flushPendingCustomMessages();
1424
+ const finalContext = this._buildBoundaryContext([], "agent_before_settle");
1425
+ if (this._abortDuringBeforeSettle)
1426
+ return false;
1427
+ const shouldContinue = result.continue || this.agent.hasQueuedMessages();
1428
+ if (shouldContinue && !finalContext.canContinue) {
1429
+ if (result.continue)
1430
+ this._reportInvalidBoundaryContinuation("agent_before_settle");
1431
+ return false;
1432
+ }
1433
+ return shouldContinue;
1434
+ }
1435
+ finally {
1436
+ this._isBeforeSettle = false;
1437
+ }
1438
+ }
1439
+ async _runInputHandlers(text, images, source, streamingBehavior) {
1440
+ if (!this._extensionRunner.hasHandlers("input")) {
1441
+ return { text, images };
1442
+ }
1443
+ const inputResult = await this._extensionRunner.emitInput(text, images, source, streamingBehavior);
1444
+ if (inputResult.action === "handled") {
1445
+ return undefined;
1446
+ }
1447
+ if (inputResult.action === "transform") {
1448
+ return { text: inputResult.text, images: inputResult.images ?? images };
1449
+ }
1450
+ return { text, images };
1451
+ }
1452
+ async _normalizePromptImages(images) {
1453
+ if (!images)
1454
+ return { images: [], hints: [] };
1455
+ const normalizedImages = [];
1456
+ const hints = [];
1457
+ for (const image of images) {
1458
+ const processed = await processImage(Buffer.from(image.data, "base64"), image.mimeType, {
1459
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
1460
+ resizeOptions: this._limitsModel()?.inputLimits?.images?.resize,
1461
+ });
1462
+ if (!processed.ok) {
1463
+ hints.push(processed.message);
1464
+ continue;
1465
+ }
1466
+ normalizedImages.push({ type: "image", data: processed.data, mimeType: processed.mimeType });
1467
+ hints.push(...processed.hints);
1468
+ }
1469
+ return { images: normalizedImages, hints };
781
1470
  }
782
1471
  /**
783
1472
  * Send a prompt to the agent.
@@ -789,133 +1478,119 @@ export class AgentSession {
789
1478
  * @throws Error if no model selected or no API key available (when not streaming)
790
1479
  */
791
1480
  async prompt(text, options) {
1481
+ if (this._isEmittingAgentSettled) {
1482
+ this._deferredSettledActions.push(async () => await this.prompt(text, options));
1483
+ return;
1484
+ }
792
1485
  const expandPromptTemplates = options?.expandPromptTemplates ?? true;
793
1486
  const preflightResult = options?.preflightResult;
794
- let messages;
795
- try {
796
- // Handle extension commands first (execute immediately, even during streaming)
797
- // Extension commands manage their own LLM interaction via pi.sendMessage()
798
- if (expandPromptTemplates && text.startsWith("/")) {
799
- const handled = await this._tryExecuteExtensionCommand(text);
800
- if (handled) {
801
- // Extension command executed, no prompt to send
802
- preflightResult?.(true);
803
- return;
804
- }
805
- }
806
- if (this._compactionAbortController !== undefined) {
807
- throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");
808
- }
809
- // Emit input event for extension interception (before skill/template expansion)
810
- let currentText = text;
811
- let currentImages = options?.images;
812
- if (this._extensionRunner.hasHandlers("input")) {
813
- const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
814
- if (inputResult.action === "handled") {
815
- preflightResult?.(true);
816
- return;
817
- }
818
- if (inputResult.action === "transform") {
819
- currentText = inputResult.text;
820
- currentImages = inputResult.images ?? currentImages;
821
- }
822
- }
823
- // Expand skill commands (/skill:name args) and prompt templates (/template args)
824
- let expandedText = currentText;
825
- if (expandPromptTemplates) {
826
- expandedText = this._expandSkillCommand(expandedText);
827
- expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
828
- }
829
- // If streaming, queue via steer() or followUp() based on option
830
- if (this.isStreaming) {
831
- if (!options?.streamingBehavior) {
832
- throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
833
- }
834
- if (options.streamingBehavior === "followUp") {
835
- await this._queueFollowUp(expandedText, currentImages);
836
- }
837
- else {
838
- await this._queueSteer(expandedText, currentImages);
839
- }
840
- preflightResult?.(true);
1487
+ // Handle extension commands first (execute immediately, even during streaming)
1488
+ // Extension commands manage their own LLM interaction via pi.sendMessage()
1489
+ if (expandPromptTemplates && text.startsWith("/")) {
1490
+ const handled = await this._tryExecuteExtensionCommand(text);
1491
+ if (handled) {
1492
+ // Extension command executed, no prompt to send
1493
+ preflightResult?.("handled");
841
1494
  return;
842
1495
  }
843
- // Flush any pending bash and custom messages before the new prompt
844
- this._flushPendingBashMessages();
845
- this._flushPendingCustomMessages();
846
- // Validate model
847
- if (!this.model) {
848
- throw new Error(formatNoModelSelectedMessage());
849
- }
850
- const hasConfiguredAuth = this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
851
- (await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
852
- if (!hasConfiguredAuth) {
853
- const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
854
- if (isOAuth) {
855
- throw new Error(`Authentication failed for "${this.model.provider}". ` +
856
- `Credentials may have expired or network is unavailable. ` +
857
- `Run '/login ${this.model.provider}' to re-authenticate.`);
858
- }
859
- throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
860
- }
861
- // Check if we need to compact before sending (catches aborted responses).
862
- // The user's new prompt is sent below, so do not call agent.continue() here.
863
- const lastAssistant = this._findLastAssistantMessage();
864
- if (lastAssistant) {
865
- await this._checkCompaction(lastAssistant, false);
866
- }
867
- // Build messages array (custom message if any, then user message)
868
- messages = [];
869
- // Add user message
870
- const userContent = [{ type: "text", text: expandedText }];
871
- if (currentImages) {
872
- userContent.push(...currentImages);
873
- }
874
- messages.push({
875
- role: "user",
876
- content: userContent,
877
- timestamp: Date.now(),
878
- });
879
- // Inject any pending "nextTurn" messages as context alongside the user message
880
- for (const msg of this._pendingNextTurnMessages) {
881
- messages.push(msg);
882
- }
883
- this._pendingNextTurnMessages = [];
884
- // Emit before_agent_start extension event
885
- const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt, this._baseSystemPromptOptions);
886
- // Add all custom messages from extensions
887
- if (result?.messages) {
888
- for (const msg of result.messages) {
889
- messages.push({
890
- role: "custom",
891
- customType: msg.customType,
892
- // Untyped extensions can pass null/missing content; normalize at ingestion.
893
- content: msg.content ?? [],
894
- display: msg.display,
895
- details: msg.details,
896
- timestamp: Date.now(),
897
- });
898
- }
1496
+ }
1497
+ if (this._compactionAbortController !== undefined) {
1498
+ throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");
1499
+ }
1500
+ // Emit input event for extension interception (before skill/template expansion)
1501
+ const processedInput = await this._runInputHandlers(text, options?.images, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
1502
+ if (!processedInput) {
1503
+ preflightResult?.("handled");
1504
+ return;
1505
+ }
1506
+ const { text: currentText, images: currentImages } = processedInput;
1507
+ // Expand skill commands (/skill:name args) and prompt templates (/template args)
1508
+ let expandedText = currentText;
1509
+ if (expandPromptTemplates) {
1510
+ expandedText = this._expandSkillCommand(expandedText);
1511
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1512
+ }
1513
+ // If streaming, queue via steer() or followUp() based on option
1514
+ if (this.isStreaming) {
1515
+ if (!options?.streamingBehavior) {
1516
+ throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
899
1517
  }
900
- // Apply extension-modified system prompt, or reset to base
901
- if (result?.systemPrompt !== undefined) {
902
- this._systemPromptOverride = result.systemPrompt;
903
- this.agent.state.systemPrompt = result.systemPrompt;
1518
+ if (options.streamingBehavior === "followUp") {
1519
+ await this._queueFollowUp(expandedText, currentImages);
904
1520
  }
905
1521
  else {
906
- // Ensure we're using the base prompt (in case previous turn had modifications)
907
- this._systemPromptOverride = undefined;
908
- this.agent.state.systemPrompt = this._baseSystemPrompt;
1522
+ await this._queueSteer(expandedText, currentImages);
909
1523
  }
1524
+ preflightResult?.("queued");
1525
+ return;
910
1526
  }
911
- catch (error) {
912
- preflightResult?.(false);
913
- throw error;
1527
+ // Flush any pending bash and custom messages before the new prompt
1528
+ this._flushPendingBashMessages();
1529
+ this._flushPendingCustomMessages();
1530
+ // Validate model
1531
+ if (!this.model) {
1532
+ throw new Error(formatNoModelSelectedMessage());
914
1533
  }
915
- if (!messages) {
916
- return;
1534
+ const hasConfiguredAuth = this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
1535
+ (await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
1536
+ if (!hasConfiguredAuth) {
1537
+ const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
1538
+ if (isOAuth) {
1539
+ throw new Error(`Authentication failed for "${this.model.provider}". ` +
1540
+ `Credentials may have expired or network is unavailable. ` +
1541
+ `Run '/login ${this.model.provider}' to re-authenticate.`);
1542
+ }
1543
+ throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
1544
+ }
1545
+ // Check if we need to compact before sending (catches aborted responses).
1546
+ // The user's new prompt is sent below, so do not call agent.continue() here.
1547
+ const lastAssistant = this._findLastAssistantMessage();
1548
+ if (lastAssistant) {
1549
+ await this._checkCompaction(lastAssistant, false);
1550
+ }
1551
+ // Emit before_agent_start before normalizing images so extension-driven model
1552
+ // selection determines the resize profile used for the request and history.
1553
+ const selectedToolsBefore = this._baseSystemPromptOptions.selectedTools;
1554
+ const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPromptOptions);
1555
+ // Handlers may edit event.systemPromptOptions.selectedTools or call setActiveTools(),
1556
+ // which updates the live loadout instead. An explicit edit wins; otherwise the live
1557
+ // loadout is authoritative, so a setActiveTools() call is not undone here.
1558
+ const handlerEditedTools = result.systemPromptOptions.selectedTools.length !== selectedToolsBefore.length ||
1559
+ result.systemPromptOptions.selectedTools.some((name, index) => name !== selectedToolsBefore[index]);
1560
+ if (!handlerEditedTools)
1561
+ result.systemPromptOptions.selectedTools = this.getActiveToolNames();
1562
+ const normalized = await this._normalizePromptImages(currentImages);
1563
+ const userText = normalized.hints.length > 0 ? `${expandedText}\n\n${normalized.hints.join("\n")}` : expandedText;
1564
+ // Build messages only after hooks and image normalization have completed.
1565
+ const messages = [];
1566
+ const userContent = [{ type: "text", text: userText }];
1567
+ userContent.push(...normalized.images);
1568
+ messages.push({
1569
+ role: "user",
1570
+ content: userContent,
1571
+ timestamp: Date.now(),
1572
+ });
1573
+ // Inject any pending "nextTurn" messages as context alongside the user message
1574
+ for (const msg of this._pendingNextTurnMessages) {
1575
+ messages.push(msg);
917
1576
  }
918
- preflightResult?.(true);
1577
+ this._pendingNextTurnMessages = [];
1578
+ for (const msg of result.messages) {
1579
+ messages.push({
1580
+ role: "custom",
1581
+ customType: msg.customType,
1582
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
1583
+ content: msg.content ?? [],
1584
+ display: msg.display,
1585
+ details: msg.details,
1586
+ timestamp: Date.now(),
1587
+ });
1588
+ }
1589
+ const updateMessage = this._preparePromptAndToolLoadout(result.systemPromptOptions);
1590
+ this._runSystemPromptOptions = result.systemPromptOptions;
1591
+ if (updateMessage)
1592
+ messages.unshift(updateMessage);
1593
+ preflightResult?.("started");
919
1594
  await this._runAgentPrompt(messages);
920
1595
  }
921
1596
  /**
@@ -975,40 +1650,45 @@ export class AgentSession {
975
1650
  return text; // Return original on error
976
1651
  }
977
1652
  }
1653
+ async _queueUserInput(text, images, behavior, source) {
1654
+ if (text.startsWith("/")) {
1655
+ this._throwIfExtensionCommand(text);
1656
+ }
1657
+ const processedInput = await this._runInputHandlers(text, images, source, this.isStreaming ? behavior : undefined);
1658
+ if (!processedInput)
1659
+ return "handled";
1660
+ let expandedText = this._expandSkillCommand(processedInput.text);
1661
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1662
+ if (behavior === "steer") {
1663
+ await this._queueSteer(expandedText, processedInput.images);
1664
+ }
1665
+ else {
1666
+ await this._queueFollowUp(expandedText, processedInput.images);
1667
+ }
1668
+ return "queued";
1669
+ }
978
1670
  /**
979
1671
  * Queue a steering message while the agent is running.
980
1672
  * Delivered after the current assistant turn finishes executing its tool calls,
981
1673
  * before the next LLM call.
982
1674
  * Expands skill commands and prompt templates. Errors on extension commands.
983
1675
  * @param images Optional image attachments to include with the message
1676
+ * @param options Input source; defaults to interactive
984
1677
  * @throws Error if text is an extension command
985
1678
  */
986
- async steer(text, images) {
987
- // Check for extension commands (cannot be queued)
988
- if (text.startsWith("/")) {
989
- this._throwIfExtensionCommand(text);
990
- }
991
- // Expand skill commands and prompt templates
992
- let expandedText = this._expandSkillCommand(text);
993
- expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
994
- await this._queueSteer(expandedText, images);
1679
+ async steer(text, images, options) {
1680
+ return this._queueUserInput(text, images, "steer", options?.source ?? "interactive");
995
1681
  }
996
1682
  /**
997
1683
  * Queue a follow-up message to be processed after the agent finishes.
998
1684
  * Delivered only when agent has no more tool calls or steering messages.
999
1685
  * Expands skill commands and prompt templates. Errors on extension commands.
1000
1686
  * @param images Optional image attachments to include with the message
1687
+ * @param options Input source; defaults to interactive
1001
1688
  * @throws Error if text is an extension command
1002
1689
  */
1003
- async followUp(text, images) {
1004
- // Check for extension commands (cannot be queued)
1005
- if (text.startsWith("/")) {
1006
- this._throwIfExtensionCommand(text);
1007
- }
1008
- // Expand skill commands and prompt templates
1009
- let expandedText = this._expandSkillCommand(text);
1010
- expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1011
- await this._queueFollowUp(expandedText, images);
1690
+ async followUp(text, images, options) {
1691
+ return this._queueUserInput(text, images, "followUp", options?.source ?? "interactive");
1012
1692
  }
1013
1693
  /**
1014
1694
  * Internal: Queue a steering message (already expanded, no extension command check).
@@ -1036,11 +1716,7 @@ export class AgentSession {
1036
1716
  if (images) {
1037
1717
  content.push(...images);
1038
1718
  }
1039
- this.agent.followUp({
1040
- role: "user",
1041
- content,
1042
- timestamp: Date.now(),
1043
- });
1719
+ this.agent.followUp({ role: "user", content, timestamp: Date.now() });
1044
1720
  }
1045
1721
  /**
1046
1722
  * Throw an error if the text is an extension command.
@@ -1088,6 +1764,10 @@ export class AgentSession {
1088
1764
  }
1089
1765
  }
1090
1766
  else if (options?.triggerTurn) {
1767
+ if (this._isEmittingAgentSettled) {
1768
+ this._deferredSettledActions.push(async () => await this._runAgentPrompt(appMessage));
1769
+ return;
1770
+ }
1091
1771
  await this._runAgentPrompt(appMessage);
1092
1772
  }
1093
1773
  else if (this.isStreaming) {
@@ -1102,8 +1782,8 @@ export class AgentSession {
1102
1782
  }
1103
1783
  }
1104
1784
  _appendCustomMessage(appMessage) {
1105
- this.agent.state.messages.push(appMessage);
1106
1785
  this.sessionManager.appendCustomMessageEntry(appMessage.customType, appMessage.content, appMessage.display, appMessage.details);
1786
+ this._refreshFinalizedContext();
1107
1787
  this._emit({ type: "message_start", message: appMessage });
1108
1788
  this._emit({ type: "message_end", message: appMessage });
1109
1789
  }
@@ -1126,6 +1806,7 @@ export class AgentSession {
1126
1806
  *
1127
1807
  * @param content User message content (string or content array)
1128
1808
  * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
1809
+ * @param options.expandPromptTemplates Whether to dispatch extension commands and expand skill commands and prompt templates. Default: false.
1129
1810
  */
1130
1811
  async sendUserMessage(content, options) {
1131
1812
  // Normalize content to text string + optional images
@@ -1149,9 +1830,8 @@ export class AgentSession {
1149
1830
  if (images.length === 0)
1150
1831
  images = undefined;
1151
1832
  }
1152
- // Use prompt() with expandPromptTemplates: false to skip command handling and template expansion
1153
1833
  await this.prompt(text, {
1154
- expandPromptTemplates: false,
1834
+ expandPromptTemplates: options?.expandPromptTemplates ?? false,
1155
1835
  streamingBehavior: options?.deliverAs,
1156
1836
  images,
1157
1837
  source: "extension",
@@ -1190,7 +1870,14 @@ export class AgentSession {
1190
1870
  * Abort current operation and wait for agent to become idle.
1191
1871
  */
1192
1872
  async abort() {
1873
+ if (this._isAgentRunActive) {
1874
+ this._agentRunAbortRequested = true;
1875
+ }
1193
1876
  this.abortRetry();
1877
+ this.abortCompaction();
1878
+ this.abortBranchSummary();
1879
+ if (this._isBeforeSettle)
1880
+ this._abortDuringBeforeSettle = true;
1194
1881
  this.agent.abort();
1195
1882
  await this.waitForIdle();
1196
1883
  }
@@ -1215,7 +1902,8 @@ export class AgentSession {
1215
1902
  }
1216
1903
  /**
1217
1904
  * Set model directly.
1218
- * Validates that auth is configured and saves to the session. Updates settings unless `persistDefault` is false.
1905
+ * Validates that auth is configured and saves to the session transcript.
1906
+ * Persists to global defaults only when options.persist is true.
1219
1907
  * @throws Error if no auth is configured for the model
1220
1908
  */
1221
1909
  async setModel(model, options = {}) {
@@ -1223,34 +1911,48 @@ export class AgentSession {
1223
1911
  throw new Error(`No API key for ${model.provider}/${model.id}`);
1224
1912
  }
1225
1913
  const previousModel = this.model;
1226
- const thinkingLevel = this._getThinkingLevelForModelSwitch();
1914
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(model);
1227
1915
  this.agent.state.model = model;
1228
1916
  this.sessionManager.appendModelChange(model.provider, model.id, model.contextWindow);
1229
- if (options.persistDefault !== false) {
1917
+ if (options.persist) {
1230
1918
  this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1919
+ this._addPersistedDefaultToNonEmptyScope(model);
1231
1920
  }
1232
- // Re-clamp thinking level for new model's capabilities
1233
- this.setThinkingLevel(thinkingLevel, options);
1921
+ // Apply thinking level for the new model.
1922
+ // Per-model thinking level overrides take priority over the global default.
1923
+ // Model persistence does not implicitly rewrite the global thinking default.
1924
+ this.setThinkingLevel(thinkingLevel);
1234
1925
  await this._emitModelSelect(model, previousModel, "set");
1235
1926
  }
1927
+ _addPersistedDefaultToNonEmptyScope(model) {
1928
+ if (this._scopedModels.length === 0)
1929
+ return;
1930
+ if (this._scopedModels.some((scoped) => modelsAreEqual(scoped.model, model)))
1931
+ return;
1932
+ this._scopedModels = [...this._scopedModels, { model }];
1933
+ const enabledModels = this.settingsManager.getEnabledModels();
1934
+ if (!enabledModels?.length)
1935
+ return;
1936
+ const modelReference = `${model.provider}/${model.id}`;
1937
+ if (enabledModels.some((pattern) => pattern.toLowerCase() === modelReference.toLowerCase()))
1938
+ return;
1939
+ this.settingsManager.setEnabledModels([...enabledModels, modelReference]);
1940
+ }
1236
1941
  /**
1237
1942
  * Cycle to next/previous model.
1238
1943
  * Uses scoped models (from --models flag) if available, otherwise all available models.
1239
1944
  * @param direction - "forward" (default) or "backward"
1240
1945
  * @returns The new model info, or undefined if only one model available
1241
1946
  */
1242
- async cycleModel(direction = "forward") {
1947
+ async cycleModel(direction = "forward", options = {}) {
1243
1948
  if (this._scopedModels.length > 0) {
1244
- return this._cycleScopedModel(direction);
1949
+ return this._cycleScopedModel(direction, options);
1245
1950
  }
1246
- return this._cycleAvailableModel(direction);
1951
+ return this._cycleAvailableModel(direction, options);
1247
1952
  }
1248
- async _cycleScopedModel(direction) {
1249
- const checks = await Promise.all(this._scopedModels.map(async (scoped) => ({
1250
- scoped,
1251
- auth: await this._modelRuntime.checkAuth(scoped.model.provider),
1252
- })));
1253
- const scopedModels = checks.filter(({ auth }) => auth !== undefined).map(({ scoped }) => scoped);
1953
+ async _cycleScopedModel(direction, options) {
1954
+ const availableIds = new Set(this._modelRuntime.getAvailableSnapshot().map((model) => `${model.provider}\0${model.id}`));
1955
+ const scopedModels = this._scopedModels.filter((scoped) => availableIds.has(`${scoped.model.provider}\0${scoped.model.id}`));
1254
1956
  if (scopedModels.length <= 1)
1255
1957
  return undefined;
1256
1958
  const currentModel = this.model;
@@ -1260,21 +1962,25 @@ export class AgentSession {
1260
1962
  const len = scopedModels.length;
1261
1963
  const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1262
1964
  const next = scopedModels[nextIndex];
1263
- const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
1965
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(next.model, next.thinkingLevel);
1264
1966
  // Apply model
1265
1967
  this.agent.state.model = next.model;
1266
1968
  this.sessionManager.appendModelChange(next.model.provider, next.model.id, next.model.contextWindow);
1267
- this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
1268
- // Apply thinking level.
1269
- // - Explicit scoped model thinking level overrides current session level
1270
- // - Undefined scoped model thinking level inherits the current session preference
1969
+ if (options.persist) {
1970
+ this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
1971
+ this._addPersistedDefaultToNonEmptyScope(next.model);
1972
+ }
1973
+ // Apply thinking level for the new model.
1974
+ // - Explicit scoped model thinking level overrides defaults
1975
+ // - Per-model thinking level overrides take priority over the global default
1271
1976
  // setThinkingLevel clamps to model capabilities.
1977
+ // Model persistence does not implicitly rewrite the global thinking default.
1272
1978
  this.setThinkingLevel(thinkingLevel);
1273
1979
  await this._emitModelSelect(next.model, currentModel, "cycle");
1274
1980
  return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
1275
1981
  }
1276
- async _cycleAvailableModel(direction) {
1277
- const availableModels = await this._modelRuntime.getAvailable();
1982
+ async _cycleAvailableModel(direction, options) {
1983
+ const availableModels = this._modelRuntime.getAvailableSnapshot();
1278
1984
  if (availableModels.length <= 1)
1279
1985
  return undefined;
1280
1986
  const currentModel = this.model;
@@ -1284,11 +1990,15 @@ export class AgentSession {
1284
1990
  const len = availableModels.length;
1285
1991
  const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1286
1992
  const nextModel = availableModels[nextIndex];
1287
- const thinkingLevel = this._getThinkingLevelForModelSwitch();
1993
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(nextModel);
1288
1994
  this.agent.state.model = nextModel;
1289
1995
  this.sessionManager.appendModelChange(nextModel.provider, nextModel.id, nextModel.contextWindow);
1290
- this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
1291
- // Re-clamp thinking level for new model's capabilities
1996
+ if (options.persist) {
1997
+ this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
1998
+ this._addPersistedDefaultToNonEmptyScope(nextModel);
1999
+ }
2000
+ // Apply thinking level for the new model.
2001
+ // Model persistence does not implicitly rewrite the global thinking default.
1292
2002
  this.setThinkingLevel(thinkingLevel);
1293
2003
  await this._emitModelSelect(nextModel, currentModel, "cycle");
1294
2004
  return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
@@ -1343,7 +2053,8 @@ export class AgentSession {
1343
2053
  /**
1344
2054
  * Set thinking level.
1345
2055
  * Clamps to model capabilities based on available thinking levels.
1346
- * Saves changes to the session and updates settings unless `persistDefault` is false.
2056
+ * Saves the clamped level to the session transcript only if the level actually changes.
2057
+ * Persists the requested level to global defaults only when options.persist is true.
1347
2058
  */
1348
2059
  setThinkingLevel(level, options = {}) {
1349
2060
  const availableLevels = this.getAvailableThinkingLevels();
@@ -1352,11 +2063,11 @@ export class AgentSession {
1352
2063
  const previousLevel = this.agent.state.thinkingLevel;
1353
2064
  const isChanging = effectiveLevel !== previousLevel;
1354
2065
  this.agent.state.thinkingLevel = effectiveLevel;
2066
+ if (options.persist) {
2067
+ this.settingsManager.setDefaultThinkingLevel(level);
2068
+ }
1355
2069
  if (isChanging) {
1356
2070
  this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1357
- if (options.persistDefault !== false && (this.supportsThinking() || effectiveLevel !== "off")) {
1358
- this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
1359
- }
1360
2071
  this._emit({ type: "thinking_level_changed", level: effectiveLevel });
1361
2072
  void this._extensionRunner.emit({
1362
2073
  type: "thinking_level_select",
@@ -1369,14 +2080,14 @@ export class AgentSession {
1369
2080
  * Cycle to next thinking level.
1370
2081
  * @returns New level, or undefined if model doesn't support thinking
1371
2082
  */
1372
- cycleThinkingLevel() {
2083
+ cycleThinkingLevel(options = {}) {
1373
2084
  if (!this.supportsThinking())
1374
2085
  return undefined;
1375
2086
  const levels = this.getAvailableThinkingLevels();
1376
2087
  const currentIndex = levels.indexOf(this.thinkingLevel);
1377
2088
  const nextIndex = (currentIndex + 1) % levels.length;
1378
2089
  const nextLevel = levels[nextIndex];
1379
- this.setThinkingLevel(nextLevel);
2090
+ this.setThinkingLevel(nextLevel, options);
1380
2091
  return nextLevel;
1381
2092
  }
1382
2093
  /**
@@ -1385,7 +2096,7 @@ export class AgentSession {
1385
2096
  */
1386
2097
  getAvailableThinkingLevels() {
1387
2098
  if (!this.model)
1388
- return THINKING_LEVELS;
2099
+ return [...THINKING_LEVEL_OPTIONS];
1389
2100
  return getSupportedThinkingLevels(this.model);
1390
2101
  }
1391
2102
  /**
@@ -1394,14 +2105,18 @@ export class AgentSession {
1394
2105
  supportsThinking() {
1395
2106
  return !!this.model?.reasoning;
1396
2107
  }
1397
- _getThinkingLevelForModelSwitch(explicitLevel) {
2108
+ _getThinkingLevelForModelSwitch(targetModel, explicitLevel) {
1398
2109
  if (explicitLevel !== undefined) {
1399
2110
  return explicitLevel;
1400
2111
  }
1401
- if (!this.supportsThinking()) {
1402
- return this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
2112
+ // Per-model default takes priority when switching to a model that has one
2113
+ if (targetModel) {
2114
+ const perModel = this.settingsManager.getModelThinkingLevel(targetModel.provider, targetModel.id);
2115
+ if (perModel !== undefined) {
2116
+ return perModel;
2117
+ }
1403
2118
  }
1404
- return this.thinkingLevel;
2119
+ return this.settingsManager.getDefaultThinkingLevel() ?? this.thinkingLevel ?? DEFAULT_THINKING_LEVEL;
1405
2120
  }
1406
2121
  _clampThinkingLevel(level, _availableLevels) {
1407
2122
  return this.model ? clampThinkingLevel(this.model, level) : "off";
@@ -1432,22 +2147,44 @@ export class AgentSession {
1432
2147
  // =========================================================================
1433
2148
  // Compaction
1434
2149
  // =========================================================================
2150
+ /** Generate draht's built-in compaction summary for manual and automatic compaction. */
2151
+ async _runDefaultCompaction(preparation, model, customInstructions, signal, reason) {
2152
+ // Resolve the request only when draht summarizes itself: routing may call models or fail.
2153
+ const request = await this._getSummarizationRequestAuth(model, signal);
2154
+ return compact(preparation, request.model, request.apiKey, request.headers, customInstructions, signal, request.thinkingLevel, this.agent.streamFunction, request.env, this.settingsManager.getRetrySettings(), this._summarizationRetryCallbacks({ source: "compaction", reason }), undefined);
2155
+ }
2156
+ _clearManualCompactionState() {
2157
+ this._compactionAbortController = undefined;
2158
+ this._resolveIdleWaitIfIdle();
2159
+ }
1435
2160
  /**
1436
2161
  * Manually compact the session context.
1437
- * Aborts current agent operation first.
2162
+ *
2163
+ * This is the manual entry point used by `/compact`, RPC, and extensions. It is
2164
+ * separate from automatic threshold/overflow compaction, which enters through
2165
+ * `_checkCompaction()` and `_runAutoCompaction()`. After preparation and the
2166
+ * `session_before_compact` hook, both paths call the lower-level `compact()`
2167
+ * function imported from `./compaction/index.ts`, unless the hook cancels or
2168
+ * supplies a custom result.
2169
+ *
2170
+ * Aborts the current agent operation first. Manual compaction never retries or
2171
+ * continues the interrupted agent turn.
2172
+ *
1438
2173
  * @param customInstructions Optional instructions for the compaction summary
1439
2174
  */
1440
2175
  async compact(customInstructions) {
1441
2176
  await this.abort();
1442
2177
  this._compactionAbortController = new AbortController();
1443
2178
  this._emit({ type: "compaction_start", reason: "manual" });
2179
+ let fromExtension = false;
2180
+ let cancelledByExtension = false;
1444
2181
  try {
1445
- if (!this.model) {
2182
+ const model = this.model;
2183
+ if (!model) {
1446
2184
  throw new Error(formatNoModelSelectedMessage());
1447
2185
  }
1448
- const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model);
2186
+ const settings = this.settingsManager.getCompactionSettings(model);
1449
2187
  const pathEntries = this.sessionManager.getBranch();
1450
- const settings = this.settingsManager.getCompactionSettings();
1451
2188
  const preparation = prepareCompaction(pathEntries, settings);
1452
2189
  if (!preparation) {
1453
2190
  // Check why we can't compact
@@ -1458,7 +2195,6 @@ export class AgentSession {
1458
2195
  throw new Error("Nothing to compact (session too small)");
1459
2196
  }
1460
2197
  let extensionCompaction;
1461
- let fromExtension = false;
1462
2198
  if (this._extensionRunner.hasHandlers("session_before_compact")) {
1463
2199
  const result = (await this._extensionRunner.emit({
1464
2200
  type: "session_before_compact",
@@ -1470,6 +2206,7 @@ export class AgentSession {
1470
2206
  signal: this._compactionAbortController.signal,
1471
2207
  }));
1472
2208
  if (result?.cancel) {
2209
+ cancelledByExtension = true;
1473
2210
  throw new Error("Compaction cancelled");
1474
2211
  }
1475
2212
  if (result?.compaction) {
@@ -1491,8 +2228,8 @@ export class AgentSession {
1491
2228
  details = extensionCompaction.details;
1492
2229
  }
1493
2230
  else {
1494
- // Generate compaction result
1495
- const result = await compact(preparation, requestModel, apiKey, headers, customInstructions, this._compactionAbortController.signal, this.thinkingLevel, this.agent.streamFunction, env, this.settingsManager.getRetrySettings(), this._summarizationRetryCallbacks({ source: "compaction", reason: "manual" }));
2231
+ // Shared default summary generator, also used by automatic compaction.
2232
+ const result = await this._runDefaultCompaction(preparation, model, customInstructions, this._compactionAbortController.signal, "manual");
1496
2233
  summary = result.summary;
1497
2234
  firstKeptEntryId = result.firstKeptEntryId;
1498
2235
  tokensBefore = result.tokensBefore;
@@ -1504,9 +2241,8 @@ export class AgentSession {
1504
2241
  }
1505
2242
  this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
1506
2243
  const newEntries = this.sessionManager.getEntries();
1507
- const sessionContext = this.sessionManager.buildSessionContext();
1508
- this.agent.state.messages = sessionContext.messages;
1509
- const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
2244
+ this._refreshFinalizedContext();
2245
+ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
1510
2246
  // Get the saved compaction entry for the extension event
1511
2247
  const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1512
2248
  if (this._extensionRunner && savedCompactionEntry) {
@@ -1527,7 +2263,7 @@ export class AgentSession {
1527
2263
  details,
1528
2264
  };
1529
2265
  // compaction_end listeners may submit queued prompts, so expose idle state before notifying them.
1530
- this._compactionAbortController = undefined;
2266
+ this._clearManualCompactionState();
1531
2267
  this._emit({
1532
2268
  type: "compaction_end",
1533
2269
  reason: "manual",
@@ -1539,20 +2275,28 @@ export class AgentSession {
1539
2275
  }
1540
2276
  catch (error) {
1541
2277
  const message = error instanceof Error ? error.message : String(error);
1542
- const aborted = message === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError");
1543
- this._compactionAbortController = undefined;
2278
+ const aborted = this._compactionAbortController.signal.aborted || cancelledByExtension;
2279
+ const errorMessage = aborted ? undefined : `Compaction failed: ${message}`;
2280
+ this._clearManualCompactionState();
1544
2281
  this._emit({
1545
2282
  type: "compaction_end",
1546
2283
  reason: "manual",
1547
2284
  result: undefined,
1548
2285
  aborted,
1549
2286
  willRetry: false,
1550
- errorMessage: aborted ? undefined : `Compaction failed: ${message}`,
2287
+ errorMessage,
2288
+ });
2289
+ await this._emitSessionCompactFailed({
2290
+ reason: "manual",
2291
+ errorMessage,
2292
+ aborted,
2293
+ willRetry: false,
2294
+ fromExtension,
1551
2295
  });
1552
2296
  throw error;
1553
2297
  }
1554
2298
  finally {
1555
- this._compactionAbortController = undefined;
2299
+ this._clearManualCompactionState();
1556
2300
  }
1557
2301
  }
1558
2302
  /**
@@ -1569,29 +2313,41 @@ export class AgentSession {
1569
2313
  this._branchSummaryAbortController?.abort();
1570
2314
  }
1571
2315
  /**
1572
- * Check if compaction is needed and run it.
1573
- * Called after agent_end and before prompt submission.
2316
+ * Dispatch automatic compaction after `agent_end` or before prompt submission.
2317
+ * Manual compaction does not call this method; it enters through `compact()`.
2318
+ *
2319
+ * Automatic cases:
2320
+ * 1. Overflow with retry: a context-overflow error or recoverable length stop;
2321
+ * remove the failed assistant message, compact, and retry the turn once.
2322
+ * 2. Overflow without retry: a successful response exceeded the configured
2323
+ * context window; compact but preserve the completed response.
2324
+ * 3. Threshold without retry: valid or estimated context usage crossed the
2325
+ * configured threshold; compact without retrying the completed response.
1574
2326
  *
1575
- * Two cases:
1576
- * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
1577
- * 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually)
2327
+ * Each case calls `_runAutoCompaction()`. After preparation and the
2328
+ * `session_before_compact` hook, that method calls the lower-level `compact()`
2329
+ * function imported from `./compaction/index.ts`, unless the hook cancels or
2330
+ * supplies a custom result.
1578
2331
  *
1579
2332
  * @param assistantMessage The assistant message to check
1580
2333
  * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
2334
+ * @returns Whether the post-run loop should call `agent.continue()` for overflow recovery or queued messages
1581
2335
  */
1582
- async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
1583
- const settings = this.settingsManager.getCompactionSettings();
2336
+ async _checkCompaction(assistantMessage, skipAbortedCheck = true, toolResults = []) {
2337
+ const settings = this.settingsManager.getCompactionSettings(this.model);
1584
2338
  if (!settings.enabled)
1585
2339
  return false;
1586
2340
  // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
1587
2341
  if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
1588
2342
  return false;
1589
- const contextWindow = this.model?.contextWindow ?? 0;
1590
2343
  // Skip overflow check if the message came from a different model.
1591
2344
  // This handles the case where user switched from a smaller-context model (e.g. opus)
1592
2345
  // to a larger-context model (e.g. codex) - the overflow error from the old model
1593
- // shouldn't trigger compaction for the new model.
1594
- const sameModel = this.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;
2346
+ // shouldn't trigger compaction for the new model. Under a virtual selection, the
2347
+ // physical model that produced the message supplies the limits.
2348
+ const messageModel = this._modelForMessage(assistantMessage);
2349
+ const sameModel = messageModel !== undefined;
2350
+ const contextWindow = (messageModel ?? this.model)?.contextWindow ?? 0;
1595
2351
  // Skip compaction checks if this assistant message is older than the latest
1596
2352
  // compaction boundary. This prevents a stale pre-compaction usage/error
1597
2353
  // from retriggering compaction on the first prompt after compaction.
@@ -1600,42 +2356,78 @@ export class AgentSession {
1600
2356
  if (assistantIsFromBeforeCompaction) {
1601
2357
  return false;
1602
2358
  }
1603
- // Case 1: Overflow - LLM returned context overflow error, or reported usage exceeded
1604
- // the configured window. A successful response over the configured window should compact
1605
- // but must not retry: the assistant answer already completed and agent.continue() cannot
1606
- // continue from an assistant message.
1607
- if (sameModel && isContextOverflow(assistantMessage, contextWindow)) {
2359
+ // Automatic cases 1 and 2: context overflow.
2360
+ // A length stop is recoverable when output ended below the model's original desired limit,
2361
+ // independent of the configured context size or any context-clamped provider request limit.
2362
+ const currentProjection = this.sessionManager.buildSessionProjection();
2363
+ const assistantEntryId = this._findPersistedMessageEntryId(assistantMessage);
2364
+ const assistantIsProjected = assistantEntryId === undefined ||
2365
+ currentProjection.entries.some((entry) => entry.sourceEntry.id === assistantEntryId &&
2366
+ entry.messages.some((message) => message.role === "assistant"));
2367
+ const branch = this.sessionManager.getBranch();
2368
+ const assistantIndex = assistantEntryId ? branch.findIndex((entry) => entry.id === assistantEntryId) : -1;
2369
+ const entriesAfterAssistant = assistantIndex >= 0 ? branch.slice(assistantIndex + 1) : [];
2370
+ const hasPostAssistantContextEdit = entriesAfterAssistant.some((entry) => entry.type === "context_edit");
2371
+ const latestAssistantEdit = entriesAfterAssistant
2372
+ .filter((entry) => entry.type === "context_edit" && entry.targetId === assistantEntryId)
2373
+ .at(-1);
2374
+ const assistantRetainedForExplicitRecovery = assistantEntryId === undefined ||
2375
+ (!entriesAfterAssistant.some((entry) => entry.type === "compaction") &&
2376
+ latestAssistantEdit?.replacement !== null);
2377
+ const assistantUsageMatchesProjection = assistantIsProjected && !hasPostAssistantContextEdit;
2378
+ const explicitOverflow = assistantMessage.stopReason === "error" && isContextOverflow(assistantMessage);
2379
+ const contextOverflow = sameModel &&
2380
+ ((explicitOverflow && assistantRetainedForExplicitRecovery) ||
2381
+ (assistantUsageMatchesProjection && isContextOverflow(assistantMessage, contextWindow)));
2382
+ const recoverableLength = sameModel && assistantIsProjected && isRecoverableLength(assistantMessage, messageModel.maxTokens);
2383
+ if (contextOverflow || recoverableLength) {
1608
2384
  const willRetry = assistantMessage.stopReason !== "stop";
2385
+ // Case 2: the response completed successfully. Compact, but do not retry because
2386
+ // agent.continue() cannot continue from a completed assistant response.
1609
2387
  if (!willRetry) {
1610
2388
  return await this._runAutoCompaction("overflow", false);
1611
2389
  }
1612
2390
  if (this._overflowRecoveryAttempted) {
2391
+ const errorMessage = contextOverflow
2392
+ ? "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model."
2393
+ : "Truncated response recovery failed after one compact-and-retry attempt.";
1613
2394
  this._emit({
1614
2395
  type: "compaction_end",
1615
2396
  reason: "overflow",
1616
2397
  result: undefined,
1617
2398
  aborted: false,
1618
2399
  willRetry: false,
1619
- errorMessage: "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
2400
+ errorMessage,
2401
+ });
2402
+ await this._emitSessionCompactFailed({
2403
+ reason: "overflow",
2404
+ errorMessage,
2405
+ aborted: false,
2406
+ willRetry: false,
2407
+ fromExtension: false,
1620
2408
  });
1621
2409
  return false;
1622
2410
  }
2411
+ // Persistently omit the selected final attempt before post-run recovery compaction.
1623
2412
  this._overflowRecoveryAttempted = true;
1624
- // Remove the error message from agent state (it IS saved to session for history,
1625
- // but we don't want it in context for the retry)
1626
- const messages = this.agent.state.messages;
1627
- if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1628
- this.agent.state.messages = messages.slice(0, -1);
1629
- }
1630
- return await this._runAutoCompaction("overflow", willRetry);
2413
+ this._omitRecoveryAttempt(assistantMessage, toolResults);
2414
+ const retry = await this._runAutoCompaction("overflow", willRetry);
2415
+ if (retry)
2416
+ this._failedResponse = assistantMessage;
2417
+ return retry;
1631
2418
  }
1632
- // Case 2: Threshold - context is getting large
2419
+ // Case 3: threshold compaction without retry.
1633
2420
  // For error messages or all-zero usage messages, estimate from the last valid response.
1634
2421
  // This ensures sessions that hit persistent API errors (e.g. 529) or malformed zero-usage
1635
2422
  // responses can still compact and do not reset context accounting.
1636
2423
  let contextTokens;
2424
+ const projection = currentProjection;
2425
+ const hasContextEdits = projection.entries.some((entry) => entry.sourceEntry.type === "context_edit");
1637
2426
  const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
1638
- if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
2427
+ if (hasContextEdits) {
2428
+ contextTokens = estimateProjectedContextTokens(projection, branch).tokens;
2429
+ }
2430
+ else if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
1639
2431
  const messages = this.agent.state.messages;
1640
2432
  const estimate = estimateContextTokens(messages);
1641
2433
  // Without provider usage, estimate.tokens is the pure message-size estimate.
@@ -1662,26 +2454,37 @@ export class AgentSession {
1662
2454
  return false;
1663
2455
  }
1664
2456
  /**
1665
- * Internal: Run auto-compaction with events.
2457
+ * Execute threshold or overflow compaction. Manual compaction uses
2458
+ * `AgentSession.compact()` instead. Both paths call the lower-level `compact()`
2459
+ * function imported from `./compaction/index.ts` after preparation and extension
2460
+ * interception.
2461
+ *
2462
+ * @param reason Automatic trigger selected by `_checkCompaction()`
2463
+ * @param willRetry Whether to continue the interrupted turn after overflow compaction
2464
+ * @returns Whether the post-run loop should call `agent.continue()`
1666
2465
  */
1667
2466
  async _runAutoCompaction(reason, willRetry) {
1668
- const settings = this.settingsManager.getCompactionSettings();
2467
+ const model = this.model;
2468
+ const settings = this.settingsManager.getCompactionSettings(model);
2469
+ let abortController;
1669
2470
  let started = false;
2471
+ let fromExtension = false;
2472
+ let cancelledByExtension = false;
1670
2473
  try {
1671
- if (!this.model) {
2474
+ if (!model) {
1672
2475
  return false;
1673
2476
  }
1674
- const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model);
1675
2477
  const pathEntries = this.sessionManager.getBranch();
1676
2478
  const preparation = prepareCompaction(pathEntries, settings);
1677
2479
  if (!preparation) {
1678
2480
  return false;
1679
2481
  }
1680
- this._emit({ type: "compaction_start", reason });
1681
- this._autoCompactionAbortController = new AbortController();
2482
+ abortController = new AbortController();
2483
+ this._autoCompactionAbortController = abortController;
1682
2484
  started = true;
2485
+ this._emit({ type: "compaction_start", reason });
2486
+ abortController.signal.throwIfAborted();
1683
2487
  let extensionCompaction;
1684
- let fromExtension = false;
1685
2488
  if (this._extensionRunner.hasHandlers("session_before_compact")) {
1686
2489
  const extensionResult = (await this._extensionRunner.emit({
1687
2490
  type: "session_before_compact",
@@ -1690,23 +2493,18 @@ export class AgentSession {
1690
2493
  customInstructions: undefined,
1691
2494
  reason,
1692
2495
  willRetry,
1693
- signal: this._autoCompactionAbortController.signal,
2496
+ signal: abortController.signal,
1694
2497
  }));
1695
2498
  if (extensionResult?.cancel) {
1696
- this._emit({
1697
- type: "compaction_end",
1698
- reason,
1699
- result: undefined,
1700
- aborted: true,
1701
- willRetry: false,
1702
- });
1703
- return false;
2499
+ cancelledByExtension = true;
2500
+ throw new Error("Compaction cancelled");
1704
2501
  }
1705
2502
  if (extensionResult?.compaction) {
1706
2503
  extensionCompaction = extensionResult.compaction;
1707
2504
  fromExtension = true;
1708
2505
  }
1709
2506
  }
2507
+ abortController.signal.throwIfAborted();
1710
2508
  let summary;
1711
2509
  let firstKeptEntryId;
1712
2510
  let tokensBefore;
@@ -1721,29 +2519,19 @@ export class AgentSession {
1721
2519
  details = extensionCompaction.details;
1722
2520
  }
1723
2521
  else {
1724
- // Generate compaction result
1725
- const compactResult = await compact(preparation, requestModel, apiKey, headers, undefined, this._autoCompactionAbortController.signal, this.thinkingLevel, this.agent.streamFunction, env, this.settingsManager.getRetrySettings(), this._summarizationRetryCallbacks({ source: "compaction", reason }));
2522
+ // Shared default summary generator, also used by manual compaction.
2523
+ const compactResult = await this._runDefaultCompaction(preparation, model, undefined, abortController.signal, reason);
1726
2524
  summary = compactResult.summary;
1727
2525
  firstKeptEntryId = compactResult.firstKeptEntryId;
1728
2526
  tokensBefore = compactResult.tokensBefore;
1729
2527
  usage = compactResult.usage;
1730
2528
  details = compactResult.details;
1731
2529
  }
1732
- if (this._autoCompactionAbortController.signal.aborted) {
1733
- this._emit({
1734
- type: "compaction_end",
1735
- reason,
1736
- result: undefined,
1737
- aborted: true,
1738
- willRetry: false,
1739
- });
1740
- return false;
1741
- }
2530
+ abortController.signal.throwIfAborted();
1742
2531
  this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
1743
2532
  const newEntries = this.sessionManager.getEntries();
1744
- const sessionContext = this.sessionManager.buildSessionContext();
1745
- this.agent.state.messages = sessionContext.messages;
1746
- const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
2533
+ this._refreshFinalizedContext();
2534
+ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
1747
2535
  // Get the saved compaction entry for the extension event
1748
2536
  const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1749
2537
  if (this._extensionRunner && savedCompactionEntry) {
@@ -1764,36 +2552,44 @@ export class AgentSession {
1764
2552
  details,
1765
2553
  };
1766
2554
  this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
1767
- if (willRetry) {
1768
- const messages = this.agent.state.messages;
1769
- const lastMsg = messages[messages.length - 1];
1770
- if (lastMsg?.role === "assistant" && lastMsg.stopReason === "error") {
1771
- this.agent.state.messages = messages.slice(0, -1);
1772
- }
2555
+ if (willRetry)
1773
2556
  return true;
1774
- }
1775
2557
  // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
1776
2558
  // Continue once so queued messages are delivered.
1777
2559
  return this.agent.hasQueuedMessages();
1778
2560
  }
1779
2561
  catch (error) {
1780
- const errorMessage = error instanceof Error ? error.message : "compaction failed";
2562
+ const message = error instanceof Error ? error.message : "compaction failed";
2563
+ const aborted = abortController?.signal.aborted === true || cancelledByExtension;
1781
2564
  if (started) {
2565
+ const errorMessage = aborted
2566
+ ? undefined
2567
+ : reason === "overflow"
2568
+ ? `Context overflow recovery failed: ${message}`
2569
+ : `Auto-compaction failed: ${message}`;
1782
2570
  this._emit({
1783
2571
  type: "compaction_end",
1784
2572
  reason,
1785
2573
  result: undefined,
1786
- aborted: false,
2574
+ aborted,
2575
+ willRetry: false,
2576
+ errorMessage,
2577
+ });
2578
+ await this._emitSessionCompactFailed({
2579
+ reason,
2580
+ errorMessage,
2581
+ aborted,
1787
2582
  willRetry: false,
1788
- errorMessage: reason === "overflow"
1789
- ? `Context overflow recovery failed: ${errorMessage}`
1790
- : `Auto-compaction failed: ${errorMessage}`,
2583
+ fromExtension,
1791
2584
  });
1792
2585
  }
1793
2586
  return false;
1794
2587
  }
1795
2588
  finally {
1796
- this._autoCompactionAbortController = undefined;
2589
+ if (this._autoCompactionAbortController === abortController) {
2590
+ this._autoCompactionAbortController = undefined;
2591
+ }
2592
+ this._resolveIdleWaitIfIdle();
1797
2593
  }
1798
2594
  }
1799
2595
  /**
@@ -1838,6 +2634,7 @@ export class AgentSession {
1838
2634
  }
1839
2635
  this._applyExtensionBindings(this._extensionRunner);
1840
2636
  await this._extensionRunner.emit(this._sessionStartEvent);
2637
+ this._extensionRunner.reportUnhandledMcpServers();
1841
2638
  await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
1842
2639
  }
1843
2640
  async extendResourcesFromExtensions(reason) {
@@ -1854,13 +2651,12 @@ export class AgentSession {
1854
2651
  themePaths: this.buildExtensionResourcePaths(themePaths),
1855
2652
  };
1856
2653
  this._resourceLoader.extendResources(extensionPaths);
1857
- this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
1858
- this.agent.state.systemPrompt = this._baseSystemPrompt;
2654
+ this._rebuildSystemPrompt(this.getActiveToolNames());
1859
2655
  }
1860
2656
  buildExtensionResourcePaths(entries) {
1861
2657
  return entries.map((entry) => {
1862
2658
  const source = this.getExtensionSourceLabel(entry.extensionPath);
1863
- const baseDir = entry.extensionPath.startsWith("<") ? undefined : dirname(entry.extensionPath);
2659
+ const baseDir = isSyntheticPath(entry.extensionPath) ? undefined : dirname(entry.extensionPath);
1864
2660
  return {
1865
2661
  path: entry.path,
1866
2662
  metadata: {
@@ -1873,7 +2669,7 @@ export class AgentSession {
1873
2669
  });
1874
2670
  }
1875
2671
  getExtensionSourceLabel(extensionPath) {
1876
- if (extensionPath.startsWith("<")) {
2672
+ if (isSyntheticPath(extensionPath)) {
1877
2673
  return `extension:${extensionPath.replace(/[<>]/g, "")}`;
1878
2674
  }
1879
2675
  const base = basename(extensionPath);
@@ -1979,6 +2775,7 @@ export class AgentSession {
1979
2775
  },
1980
2776
  getActiveTools: () => this.getActiveToolNames(),
1981
2777
  getAllTools: () => this.getAllTools(),
2778
+ getSettings: () => this.settingsManager.getSettings(),
1982
2779
  setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
1983
2780
  refreshTools: () => this._refreshToolRegistry(),
1984
2781
  getCommands,
@@ -2022,6 +2819,8 @@ export class AgentSession {
2022
2819
  },
2023
2820
  getSystemPrompt: () => this.systemPrompt,
2024
2821
  getSystemPromptOptions: () => this._baseSystemPromptOptions,
2822
+ executeTool: (callerId, name, args, options) => this._executeNestedToolCall(callerId, name, args, options),
2823
+ getCallableTools: () => this._getCallableTools(),
2025
2824
  }, {
2026
2825
  registerProvider: (name, config) => {
2027
2826
  this._modelRuntime.registerProvider(name, config);
@@ -2035,10 +2834,20 @@ export class AgentSession {
2035
2834
  this._modelRuntime.unregisterProvider(name);
2036
2835
  this._refreshCurrentModelFromRegistry();
2037
2836
  },
2837
+ registerVirtualModel: (definition) => {
2838
+ this._modelRuntime.registerVirtualModel(definition);
2839
+ this._refreshCurrentModelFromRegistry();
2840
+ },
2841
+ unregisterVirtualModel: (provider, id) => {
2842
+ this._modelRuntime.unregisterVirtualModel(provider, id);
2843
+ this._refreshCurrentModelFromRegistry();
2844
+ },
2038
2845
  });
2039
2846
  }
2040
2847
  _refreshToolRegistry(options) {
2041
- const previousRegistryNames = new Set(this._toolRegistry.keys());
2848
+ // Tools that were already activated on registration. A tool whose exposure changes to
2849
+ // `direct` or `model-only` (for example from `hidden`) is activated like a new tool.
2850
+ const previousActivatedOnRegistration = new Set([...this._toolRegistry.keys()].filter((name) => this._isActivatedOnRegistration(name)));
2042
2851
  const previousActiveToolNames = this.getActiveToolNames();
2043
2852
  const allowedToolNames = this._allowedToolNames;
2044
2853
  const excludedToolNames = this._excludedToolNames;
@@ -2057,7 +2866,7 @@ export class AgentSession {
2057
2866
  name,
2058
2867
  {
2059
2868
  definition,
2060
- sourceInfo: createSyntheticSourceInfo(`<builtin:${name}>`, { source: "builtin" }),
2869
+ sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${name}`, { source: "builtin" }),
2061
2870
  },
2062
2871
  ]));
2063
2872
  for (const tool of allCustomTools) {
@@ -2085,7 +2894,9 @@ export class AgentSession {
2085
2894
  .filter((definition) => isAllowedTool(definition.name))
2086
2895
  .map((definition) => ({
2087
2896
  definition,
2088
- sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
2897
+ sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${definition.name}`, {
2898
+ source: "builtin",
2899
+ }),
2089
2900
  })), runner);
2090
2901
  const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
2091
2902
  for (const tool of wrappedExtensionTools) {
@@ -2095,25 +2906,36 @@ export class AgentSession {
2095
2906
  const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => isAllowedTool(name));
2096
2907
  if (allowedToolNames) {
2097
2908
  for (const toolName of this._toolRegistry.keys()) {
2098
- if (allowedToolNames.has(toolName)) {
2909
+ // Naming a tool activates it even when it is not active by default.
2910
+ if (allowedToolNames.has(toolName) && this._isDeclarable(toolName)) {
2099
2911
  nextActiveToolNames.push(toolName);
2100
2912
  }
2101
2913
  }
2102
2914
  }
2103
2915
  else if (options?.includeAllExtensionTools) {
2104
2916
  for (const tool of wrappedExtensionTools) {
2105
- nextActiveToolNames.push(tool.name);
2917
+ if (this._isActivatedOnRegistration(tool.name))
2918
+ nextActiveToolNames.push(tool.name);
2106
2919
  }
2107
2920
  }
2108
2921
  else if (!options?.activeToolNames) {
2109
2922
  for (const toolName of this._toolRegistry.keys()) {
2110
- if (!previousRegistryNames.has(toolName)) {
2923
+ if (!previousActivatedOnRegistration.has(toolName) && this._isActivatedOnRegistration(toolName)) {
2111
2924
  nextActiveToolNames.push(toolName);
2112
2925
  }
2113
2926
  }
2114
2927
  }
2115
2928
  this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
2116
2929
  }
2930
+ /** Whether activating the tool declares it to the model. */
2931
+ _isDeclarable(name) {
2932
+ const exposure = this._getToolExposure(name);
2933
+ return exposure === "direct" || exposure === "model-only";
2934
+ }
2935
+ /** Whether registering the tool activates it, which declares it to the model. */
2936
+ _isActivatedOnRegistration(name) {
2937
+ return this._isDeclarable(name) && this._toolDefinitions.get(name)?.definition.defaultActive !== false;
2938
+ }
2117
2939
  _buildRuntime(options) {
2118
2940
  const autoResizeImages = this.settingsManager.getImageAutoResize();
2119
2941
  const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
@@ -2154,12 +2976,18 @@ export class AgentSession {
2154
2976
  const previousFlagValues = oldRunner.getFlagValues();
2155
2977
  await emitSessionShutdownEvent(oldRunner, { type: "session_shutdown", reason: "reload" });
2156
2978
  oldRunner.invalidate();
2979
+ const previousDefaultTools = new Set(this._usesDefaultTools ? (this.settingsManager.getDefaultTools() ?? DEFAULT_TOOL_NAMES) : []);
2157
2980
  await this.settingsManager.reload();
2158
2981
  this.syncQueueModesFromSettings();
2159
2982
  resetApiProviders();
2160
2983
  await this._resourceLoader.reload();
2984
+ // Activate tools newly added to defaultTools. Removed ones stay active, and tools disabled
2985
+ // during the session stay disabled unless the setting newly adds them.
2986
+ const addedDefaultTools = this._usesDefaultTools
2987
+ ? (this.settingsManager.getDefaultTools() ?? DEFAULT_TOOL_NAMES).filter((name) => !previousDefaultTools.has(name))
2988
+ : [];
2161
2989
  this._buildRuntime({
2162
- activeToolNames: this.getActiveToolNames(),
2990
+ activeToolNames: [...this.getActiveToolNames(), ...addedDefaultTools],
2163
2991
  flagValues: previousFlagValues,
2164
2992
  includeAllExtensionTools: true,
2165
2993
  });
@@ -2170,6 +2998,7 @@ export class AgentSession {
2170
2998
  if (hasBindings) {
2171
2999
  await options?.beforeSessionStart?.();
2172
3000
  await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
3001
+ this._extensionRunner.reportUnhandledMcpServers();
2173
3002
  await this.extendResourcesFromExtensions("reload");
2174
3003
  }
2175
3004
  }
@@ -2182,7 +3011,7 @@ export class AgentSession {
2182
3011
  */
2183
3012
  _isRetryableError(message) {
2184
3013
  // Context overflow is handled by compaction, not retry.
2185
- if (isContextOverflow(message, this.model?.contextWindow ?? 0))
3014
+ if (isContextOverflow(message, (this._modelForMessage(message) ?? this.model)?.contextWindow ?? 0))
2186
3015
  return false;
2187
3016
  return isRetryableAssistantError(message);
2188
3017
  }
@@ -2214,6 +3043,18 @@ export class AgentSession {
2214
3043
  },
2215
3044
  };
2216
3045
  }
3046
+ _finishCancelledRetry() {
3047
+ if (this._retryAttempt === 0)
3048
+ return;
3049
+ const attempt = this._retryAttempt;
3050
+ this._retryAttempt = 0;
3051
+ this._emit({
3052
+ type: "auto_retry_end",
3053
+ success: false,
3054
+ attempt,
3055
+ finalError: "Retry cancelled",
3056
+ });
3057
+ }
2217
3058
  /**
2218
3059
  * Prepare a retryable error for continuation with exponential backoff.
2219
3060
  * @returns true if the caller should continue the agent, false otherwise
@@ -2229,7 +3070,7 @@ export class AgentSession {
2229
3070
  this._retryAttempt--;
2230
3071
  return false;
2231
3072
  }
2232
- const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
3073
+ const delayMs = retryDelayMs(settings, this._retryAttempt);
2233
3074
  this._emit({
2234
3075
  type: "auto_retry_start",
2235
3076
  attempt: this._retryAttempt,
@@ -2237,11 +3078,8 @@ export class AgentSession {
2237
3078
  delayMs,
2238
3079
  errorMessage: message.errorMessage || "Unknown error",
2239
3080
  });
2240
- // Remove error message from agent state (keep in session for history)
2241
- const messages = this.agent.state.messages;
2242
- if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
2243
- this.agent.state.messages = messages.slice(0, -1);
2244
- }
3081
+ // Keep the failed attempt in raw history while durably omitting it from model projection.
3082
+ this._omitRecoveryAttempt(message);
2245
3083
  // Wait with exponential backoff (abortable)
2246
3084
  this._retryAbortController = new AbortController();
2247
3085
  try {
@@ -2249,14 +3087,7 @@ export class AgentSession {
2249
3087
  }
2250
3088
  catch {
2251
3089
  // Aborted during sleep - emit end event so UI can clean up
2252
- const attempt = this._retryAttempt;
2253
- this._retryAttempt = 0;
2254
- this._emit({
2255
- type: "auto_retry_end",
2256
- success: false,
2257
- attempt,
2258
- finalError: "Retry cancelled",
2259
- });
3090
+ this._finishCancelledRetry();
2260
3091
  return false;
2261
3092
  }
2262
3093
  finally {
@@ -2340,10 +3171,8 @@ export class AgentSession {
2340
3171
  this._pendingBashMessages.push(bashMessage);
2341
3172
  }
2342
3173
  else {
2343
- // Add to agent state immediately
2344
- this.agent.state.messages.push(bashMessage);
2345
- // Save to session
2346
3174
  this.sessionManager.appendMessage(bashMessage);
3175
+ this._refreshFinalizedContext();
2347
3176
  }
2348
3177
  }
2349
3178
  /**
@@ -2370,12 +3199,10 @@ export class AgentSession {
2370
3199
  if (this._pendingBashMessages.length === 0)
2371
3200
  return;
2372
3201
  for (const bashMessage of this._pendingBashMessages) {
2373
- // Add to agent state
2374
- this.agent.state.messages.push(bashMessage);
2375
- // Save to session
2376
3202
  this.sessionManager.appendMessage(bashMessage);
2377
3203
  }
2378
3204
  this._pendingBashMessages = [];
3205
+ this._refreshFinalizedContext();
2379
3206
  }
2380
3207
  // =========================================================================
2381
3208
  // Session Management
@@ -2407,6 +3234,9 @@ export class AgentSession {
2407
3234
  if (this.isStreaming) {
2408
3235
  throw new Error("Wait for the current response to finish before navigating the session tree.");
2409
3236
  }
3237
+ if (this.isCompacting) {
3238
+ throw new Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");
3239
+ }
2410
3240
  const oldLeafId = this.sessionManager.getLeafId();
2411
3241
  // No-op if already at target
2412
3242
  if (targetId === oldLeafId) {
@@ -2471,15 +3301,11 @@ export class AgentSession {
2471
3301
  let summaryDetails;
2472
3302
  let summaryUsage;
2473
3303
  if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
2474
- const model = this.model;
2475
- const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(model);
3304
+ const signal = this._branchSummaryAbortController.signal;
2476
3305
  const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
2477
3306
  const result = await generateBranchSummary(entriesToSummarize, {
2478
- model: requestModel,
2479
- apiKey,
2480
- headers,
2481
- env,
2482
- signal: this._branchSummaryAbortController.signal,
3307
+ ...(await this._getSummarizationRequestAuth(this.model, signal)),
3308
+ signal,
2483
3309
  customInstructions,
2484
3310
  replaceInstructions,
2485
3311
  reserveTokens: branchSummarySettings.reserveTokens,
@@ -2546,9 +3372,9 @@ export class AgentSession {
2546
3372
  if (label && !summaryText) {
2547
3373
  this.sessionManager.appendLabelChange(targetId, label);
2548
3374
  }
2549
- // Update agent state
2550
- const sessionContext = this.sessionManager.buildSessionContext();
2551
- this.agent.state.messages = sessionContext.messages;
3375
+ // Update finalized context from the canonical session projection.
3376
+ this._refreshFinalizedContext();
3377
+ this._restoreToolsFromTranscript();
2552
3378
  // Emit session_tree event
2553
3379
  await this._extensionRunner.emit({
2554
3380
  type: "session_tree",
@@ -2562,6 +3388,7 @@ export class AgentSession {
2562
3388
  }
2563
3389
  finally {
2564
3390
  this._branchSummaryAbortController = undefined;
3391
+ this._resolveIdleWaitIfIdle();
2565
3392
  }
2566
3393
  }
2567
3394
  /**
@@ -2595,7 +3422,10 @@ export class AgentSession {
2595
3422
  let toolCalls = 0;
2596
3423
  const usageTotals = createUsageTotals();
2597
3424
  for (const entry of this.sessionManager.getEntries()) {
2598
- if ((entry.type === "branch_summary" || entry.type === "compaction") && entry.usage) {
3425
+ if (entry.type === "usage") {
3426
+ addUsageToTotals(usageTotals, entry.usage);
3427
+ }
3428
+ else if ((entry.type === "branch_summary" || entry.type === "compaction") && entry.usage) {
2599
3429
  addUsageToTotals(usageTotals, entry.usage);
2600
3430
  }
2601
3431
  if (entry.type !== "message")
@@ -2640,7 +3470,7 @@ export class AgentSession {
2640
3470
  };
2641
3471
  }
2642
3472
  getContextUsage() {
2643
- const model = this.model;
3473
+ const model = this._limitsModel();
2644
3474
  if (!model)
2645
3475
  return undefined;
2646
3476
  const contextWindow = model.contextWindow ?? 0;
@@ -2649,30 +3479,24 @@ export class AgentSession {
2649
3479
  // After compaction, the last assistant usage reflects pre-compaction context size.
2650
3480
  // We can only trust usage from an assistant that responded after the latest compaction.
2651
3481
  // If no such assistant exists, context token count is unknown until the next LLM response.
2652
- const branchEntries = this.sessionManager.getBranch();
2653
- const latestCompaction = getLatestCompactionEntry(branchEntries);
3482
+ const projection = this.sessionManager.buildSessionProjection();
3483
+ const branch = this.sessionManager.getBranch();
3484
+ const latestCompaction = getLatestCompactionEntry(branch);
2654
3485
  if (latestCompaction) {
2655
- // Check if there's a valid assistant usage after the compaction boundary
2656
- const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
2657
- let hasPostCompactionUsage = false;
2658
- for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
2659
- const entry = branchEntries[i];
2660
- if (entry.type === "message" && entry.message.role === "assistant") {
2661
- const assistant = entry.message;
2662
- if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
2663
- const contextTokens = calculateContextTokens(assistant.usage);
2664
- if (contextTokens > 0) {
2665
- hasPostCompactionUsage = true;
2666
- break;
2667
- }
2668
- }
2669
- }
2670
- }
2671
- if (!hasPostCompactionUsage) {
3486
+ const projectedAssistants = new Set(projection.entries.flatMap((entry) => entry.messages.some((message) => message.role === "assistant" &&
3487
+ message.stopReason !== "aborted" &&
3488
+ message.stopReason !== "error" &&
3489
+ calculateContextTokens(message.usage) > 0)
3490
+ ? [entry.sourceEntry.id]
3491
+ : []));
3492
+ const compactionIndex = branch.findIndex((entry) => entry.id === latestCompaction.id);
3493
+ const hasPostCompactionUsage = branch
3494
+ .slice(compactionIndex + 1)
3495
+ .some((entry) => projectedAssistants.has(entry.id));
3496
+ if (!hasPostCompactionUsage)
2672
3497
  return { tokens: null, contextWindow, percent: null };
2673
- }
2674
3498
  }
2675
- const estimate = estimateContextTokens(this.messages);
3499
+ const estimate = estimateProjectedContextTokens(projection, branch);
2676
3500
  const percent = (estimate.tokens / contextWindow) * 100;
2677
3501
  return {
2678
3502
  tokens: estimate.tokens,
@@ -2683,11 +3507,11 @@ export class AgentSession {
2683
3507
  /**
2684
3508
  * Export session to HTML.
2685
3509
  * @param outputPath Optional output path (defaults to session directory)
3510
+ * @param options Optional export presentation settings
2686
3511
  * @returns Path to exported file
2687
3512
  */
2688
- async exportToHtml(outputPath) {
2689
- const configuredThemeName = this.settingsManager.getTheme();
2690
- const themeName = configuredThemeName && getThemeByName(configuredThemeName) ? configuredThemeName : undefined;
3513
+ async exportToHtml(outputPath, options = {}) {
3514
+ const themeName = [options.themeName, this.settingsManager.getTheme()].find((candidate) => candidate !== undefined && getThemeByName(candidate) !== undefined);
2691
3515
  // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
2692
3516
  const toolRenderer = createToolHtmlRenderer({
2693
3517
  getToolDefinition: (name) => this.getToolDefinition(name),
@@ -2707,29 +3531,26 @@ export class AgentSession {
2707
3531
  * @returns The resolved output file path.
2708
3532
  */
2709
3533
  exportToJsonl(outputPath) {
2710
- const filePath = resolvePath(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`, process.cwd());
2711
- const dir = dirname(filePath);
2712
- if (!existsSync(dir)) {
2713
- mkdirSync(dir, { recursive: true });
2714
- }
2715
- const header = {
2716
- type: "session",
2717
- version: CURRENT_SESSION_VERSION,
2718
- id: this.sessionManager.getSessionId(),
2719
- timestamp: new Date().toISOString(),
2720
- cwd: this.sessionManager.getCwd(),
2721
- };
2722
- const branchEntries = this.sessionManager.getBranch();
2723
- const lines = [JSON.stringify(header)];
2724
- // Re-chain parentIds to form a linear sequence
2725
- let prevId = null;
2726
- for (const entry of branchEntries) {
2727
- const linear = { ...entry, parentId: prevId };
2728
- lines.push(JSON.stringify(linear));
2729
- prevId = entry.id;
2730
- }
2731
- writeFileSync(filePath, `${lines.join("\n")}\n`);
2732
- return filePath;
3534
+ return exportSessionToJsonl(this.sessionManager, outputPath);
3535
+ }
3536
+ /**
3537
+ * Ask the current model to describe what went wrong in this session for a bug report.
3538
+ * Used when the user declines to share the transcript itself.
3539
+ */
3540
+ async summarizeForBugReport(options) {
3541
+ const model = this.model;
3542
+ if (!model) {
3543
+ throw new Error("No model selected");
3544
+ }
3545
+ return generateBugReportSummary({
3546
+ ...(await this._getSummarizationRequestAuth(model, options.signal)),
3547
+ messages: this.messages,
3548
+ hint: options.hint,
3549
+ signal: options.signal,
3550
+ streamFn: this.agent.streamFunction,
3551
+ retry: this.settingsManager.getRetrySettings(),
3552
+ sessionId: this.sessionId,
3553
+ });
2733
3554
  }
2734
3555
  // =========================================================================
2735
3556
  // Utilities