@draht/coding-agent 2026.7.30 → 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 (1229) hide show
  1. package/CHANGELOG.md +606 -0
  2. package/README.md +46 -2
  3. package/agents/debugger.md +12 -1
  4. package/agents/git-committer.md +1 -0
  5. package/agents/implementer.md +20 -0
  6. package/agents/investigator.md +75 -0
  7. package/agents/reviewer.md +7 -0
  8. package/agents/spec-reviewer.md +66 -0
  9. package/agents/verifier.md +4 -3
  10. package/bin/draht-tools.cjs +472 -41
  11. package/dist/agents/debugger.md +12 -1
  12. package/dist/agents/git-committer.md +1 -0
  13. package/dist/agents/implementer.md +20 -0
  14. package/dist/agents/investigator.md +75 -0
  15. package/dist/agents/reviewer.md +7 -0
  16. package/dist/agents/spec-reviewer.md +66 -0
  17. package/dist/agents/verifier.md +4 -3
  18. package/dist/bun/cli.d.ts +1 -1
  19. package/dist/bun/cli.d.ts.map +1 -1
  20. package/dist/bun/cli.js +6 -3
  21. package/dist/bun/cli.js.map +1 -1
  22. package/dist/bun/sandbox-env-setup.d.ts +2 -0
  23. package/dist/bun/sandbox-env-setup.d.ts.map +1 -0
  24. package/dist/bun/sandbox-env-setup.js +4 -0
  25. package/dist/bun/sandbox-env-setup.js.map +1 -0
  26. package/dist/bundle/chunks/anthropic-messages-GAKYXF65.js +6 -0
  27. package/dist/bundle/chunks/anthropic.js +75 -0
  28. package/dist/bundle/chunks/azure-openai-responses-ZIXMK6JO.js +2 -0
  29. package/dist/bundle/chunks/bedrock-converse-stream.js +79 -0
  30. package/dist/bundle/chunks/chunk-2E5VODES.js +2 -0
  31. package/dist/bundle/chunks/chunk-2FBJKY7F.js +2 -0
  32. package/dist/bundle/chunks/chunk-2N4I6WXC.js +2 -0
  33. package/dist/bundle/chunks/chunk-5VZWYVZB.js +82 -0
  34. package/dist/bundle/chunks/chunk-63BK6WK2.js +2 -0
  35. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +6 -0
  36. package/dist/bundle/chunks/chunk-6ZJKIMU7.js +2 -0
  37. package/dist/bundle/chunks/chunk-736QBNUZ.js +12 -0
  38. package/dist/bundle/chunks/chunk-BXSHCX3G.js +11 -0
  39. package/dist/bundle/chunks/chunk-CEJJ5XF2.js +170 -0
  40. package/dist/bundle/chunks/chunk-COF5JT7R.js +4 -0
  41. package/dist/bundle/chunks/chunk-D6TMD5Q2.js +44 -0
  42. package/dist/bundle/chunks/chunk-DPE4ALPU.js +146 -0
  43. package/dist/bundle/chunks/chunk-EBVYI75P.js +2 -0
  44. package/dist/bundle/chunks/chunk-GVXA72ZA.js +2 -0
  45. package/dist/bundle/chunks/chunk-H6FT43VC.js +137 -0
  46. package/dist/bundle/chunks/chunk-HJ72RANT.js +2 -0
  47. package/dist/bundle/chunks/chunk-HTJ3L72O.js +2 -0
  48. package/dist/bundle/chunks/chunk-HZ2UHMBT.js +2 -0
  49. package/dist/bundle/chunks/chunk-I5OKY6RH.js +11 -0
  50. package/dist/bundle/chunks/chunk-IWTUBX6V.js +4 -0
  51. package/dist/bundle/chunks/chunk-KPO5375S.js +2 -0
  52. package/dist/bundle/chunks/chunk-KVH4HR57.js +31 -0
  53. package/dist/bundle/chunks/chunk-LDAOC5RB.js +18 -0
  54. package/dist/bundle/chunks/chunk-ON6XU6AG.js +2 -0
  55. package/dist/bundle/chunks/chunk-QMN7OD6G.js +2 -0
  56. package/dist/bundle/chunks/chunk-RZKPFWMH.js +42 -0
  57. package/dist/bundle/chunks/chunk-SDRCE6OP.js +2 -0
  58. package/dist/bundle/chunks/chunk-SVNWI7EV.js +8 -0
  59. package/dist/bundle/chunks/chunk-TIA2T6EO.js +3 -0
  60. package/dist/bundle/chunks/chunk-VOFPZOUQ.js +1472 -0
  61. package/dist/bundle/chunks/chunk-XBUEMKIY.js +2 -0
  62. package/dist/bundle/chunks/chunk-XOGEYN4Q.js +2 -0
  63. package/dist/bundle/chunks/chunk-ZZD35WKM.js +2 -0
  64. package/dist/bundle/chunks/cli-SR5QBZH4.js +51 -0
  65. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-MJKOAE5S.js +2 -0
  66. package/dist/bundle/chunks/codemode-worker.js +315 -0
  67. package/dist/bundle/chunks/execute-VCYDHEYA.js +328 -0
  68. package/dist/bundle/chunks/github-copilot.js +2 -0
  69. package/dist/bundle/chunks/google-antigravity.js +75 -0
  70. package/dist/bundle/chunks/google-gemini-cli.js +75 -0
  71. package/dist/bundle/chunks/google-generative-ai-RPUPQ6PM.js +2 -0
  72. package/dist/bundle/chunks/google-vertex-EZES5QVQ.js +2 -0
  73. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +13 -0
  74. package/dist/bundle/chunks/image-resize-worker.js +2 -0
  75. package/dist/bundle/chunks/jiti-loader-RKXLMQV2.js +2 -0
  76. package/dist/bundle/chunks/kimi-coding.js +2 -0
  77. package/dist/bundle/chunks/lib-XOG5PI3Y.js +9 -0
  78. package/dist/bundle/chunks/llama-cpp-classify-EJ5XMSQL.js +22 -0
  79. package/dist/bundle/chunks/meta.js +2 -0
  80. package/dist/bundle/chunks/mistral-conversations-AOYGU43Y.js +5 -0
  81. package/dist/bundle/chunks/multipart-parser-AZP5BX2W.js +3 -0
  82. package/dist/bundle/chunks/node-C2JGH2OB.js +2 -0
  83. package/dist/bundle/chunks/node-LQ52KV6B.js +16 -0
  84. package/dist/bundle/chunks/openai-chatgpt.js +75 -0
  85. package/dist/bundle/chunks/openai-codex-responses-M2Y77JEQ.js +10 -0
  86. package/dist/bundle/chunks/openai-codex.js +75 -0
  87. package/dist/bundle/chunks/openai-completions-A4OKYOYV.js +7 -0
  88. package/dist/bundle/chunks/openai-responses-6IXV53T3.js +3 -0
  89. package/dist/bundle/chunks/opencode-go.js +2 -0
  90. package/dist/bundle/chunks/openrouter-images-LYV4NKFM.js +2 -0
  91. package/dist/bundle/chunks/openrouter.js +75 -0
  92. package/dist/bundle/chunks/pi-messages-KKMEUT3Z.js +8 -0
  93. package/dist/bundle/chunks/radius.js +75 -0
  94. package/dist/bundle/chunks/runtime-6YJPGSP7.js +2 -0
  95. package/dist/bundle/chunks/settings-manager-D2EG7WDO.js +2 -0
  96. package/dist/bundle/chunks/src-TIBHS42X.js +4 -0
  97. package/dist/bundle/chunks/typesafe-system-one-YBEEY5XU.js +2 -0
  98. package/dist/bundle/chunks/virtual-modules-CBOAFAFT.js +2 -0
  99. package/dist/bundle/chunks/xai.js +75 -0
  100. package/dist/bundle/cli-runtime.js +3 -0
  101. package/dist/bundle/cli.js +5 -0
  102. package/dist/bundle/index.js +2 -0
  103. package/dist/bundle/rpc-entry.js +3 -0
  104. package/dist/cli/args.d.ts +14 -0
  105. package/dist/cli/args.d.ts.map +1 -1
  106. package/dist/cli/args.js +140 -22
  107. package/dist/cli/args.js.map +1 -1
  108. package/dist/cli/attach-mode.d.ts +61 -0
  109. package/dist/cli/attach-mode.d.ts.map +1 -1
  110. package/dist/cli/attach-mode.js +243 -5
  111. package/dist/cli/attach-mode.js.map +1 -1
  112. package/dist/cli/auth-check.d.ts +19 -0
  113. package/dist/cli/auth-check.d.ts.map +1 -0
  114. package/dist/cli/auth-check.js +50 -0
  115. package/dist/cli/auth-check.js.map +1 -0
  116. package/dist/cli/auth-command.d.ts +24 -0
  117. package/dist/cli/auth-command.d.ts.map +1 -0
  118. package/dist/cli/auth-command.js +103 -0
  119. package/dist/cli/auth-command.js.map +1 -0
  120. package/dist/cli/config-selector.d.ts.map +1 -1
  121. package/dist/cli/config-selector.js +3 -2
  122. package/dist/cli/config-selector.js.map +1 -1
  123. package/dist/cli/credential-print.d.ts +6 -4
  124. package/dist/cli/credential-print.d.ts.map +1 -1
  125. package/dist/cli/credential-print.js +47 -34
  126. package/dist/cli/credential-print.js.map +1 -1
  127. package/dist/cli/file-processor.d.ts +1 -1
  128. package/dist/cli/file-processor.d.ts.map +1 -1
  129. package/dist/cli/file-processor.js +2 -1
  130. package/dist/cli/file-processor.js.map +1 -1
  131. package/dist/cli/list-models.d.ts +1 -1
  132. package/dist/cli/list-models.d.ts.map +1 -1
  133. package/dist/cli/list-models.js +2 -2
  134. package/dist/cli/list-models.js.map +1 -1
  135. package/dist/cli/session-picker.d.ts +1 -1
  136. package/dist/cli/session-picker.d.ts.map +1 -1
  137. package/dist/cli/session-picker.js.map +1 -1
  138. package/dist/cli/setup.d.ts +2 -0
  139. package/dist/cli/setup.d.ts.map +1 -0
  140. package/dist/cli/setup.js +12 -0
  141. package/dist/cli/setup.js.map +1 -0
  142. package/dist/cli/startup-ui.d.ts +2 -2
  143. package/dist/cli/startup-ui.d.ts.map +1 -1
  144. package/dist/cli/startup-ui.js +42 -33
  145. package/dist/cli/startup-ui.js.map +1 -1
  146. package/dist/cli.js +3 -12
  147. package/dist/cli.js.map +1 -1
  148. package/dist/config.d.ts +29 -4
  149. package/dist/config.d.ts.map +1 -1
  150. package/dist/config.js +73 -10
  151. package/dist/config.js.map +1 -1
  152. package/dist/core/agent-session-runtime.d.ts +17 -1
  153. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  154. package/dist/core/agent-session-runtime.js +98 -32
  155. package/dist/core/agent-session-runtime.js.map +1 -1
  156. package/dist/core/agent-session-services.d.ts +2 -1
  157. package/dist/core/agent-session-services.d.ts.map +1 -1
  158. package/dist/core/agent-session-services.js +15 -0
  159. package/dist/core/agent-session-services.js.map +1 -1
  160. package/dist/core/agent-session.d.ts +266 -49
  161. package/dist/core/agent-session.d.ts.map +1 -1
  162. package/dist/core/agent-session.js +1503 -597
  163. package/dist/core/agent-session.js.map +1 -1
  164. package/dist/core/auth-storage.d.ts +25 -9
  165. package/dist/core/auth-storage.d.ts.map +1 -1
  166. package/dist/core/auth-storage.js +245 -45
  167. package/dist/core/auth-storage.js.map +1 -1
  168. package/dist/core/bug-report-upload.d.ts +11 -0
  169. package/dist/core/bug-report-upload.d.ts.map +1 -0
  170. package/dist/core/bug-report-upload.js +20 -0
  171. package/dist/core/bug-report-upload.js.map +1 -0
  172. package/dist/core/bug-report.d.ts +176 -0
  173. package/dist/core/bug-report.d.ts.map +1 -0
  174. package/dist/core/bug-report.js +292 -0
  175. package/dist/core/bug-report.js.map +1 -0
  176. package/dist/core/builtins/checkpoints.d.ts +20 -0
  177. package/dist/core/builtins/checkpoints.d.ts.map +1 -0
  178. package/dist/core/builtins/checkpoints.js +161 -0
  179. package/dist/core/builtins/checkpoints.js.map +1 -0
  180. package/dist/core/builtins/duet.d.ts +26 -0
  181. package/dist/core/builtins/duet.d.ts.map +1 -0
  182. package/dist/core/builtins/duet.js +660 -0
  183. package/dist/core/builtins/duet.js.map +1 -0
  184. package/dist/core/builtins/index.d.ts.map +1 -1
  185. package/dist/core/builtins/index.js +7 -1
  186. package/dist/core/builtins/index.js.map +1 -1
  187. package/dist/core/builtins/subagent.d.ts +24 -4
  188. package/dist/core/builtins/subagent.d.ts.map +1 -1
  189. package/dist/core/builtins/subagent.js +278 -35
  190. package/dist/core/builtins/subagent.js.map +1 -1
  191. package/dist/core/cache-stats.d.ts.map +1 -1
  192. package/dist/core/cache-stats.js +12 -1
  193. package/dist/core/cache-stats.js.map +1 -1
  194. package/dist/core/cache-warmer.d.ts +103 -0
  195. package/dist/core/cache-warmer.d.ts.map +1 -0
  196. package/dist/core/cache-warmer.js +356 -0
  197. package/dist/core/cache-warmer.js.map +1 -0
  198. package/dist/core/checkpoints/checkpoint-cli.d.ts +17 -0
  199. package/dist/core/checkpoints/checkpoint-cli.d.ts.map +1 -0
  200. package/dist/core/checkpoints/checkpoint-cli.js +78 -0
  201. package/dist/core/checkpoints/checkpoint-cli.js.map +1 -0
  202. package/dist/core/checkpoints/checkpoint-manager.d.ts +298 -0
  203. package/dist/core/checkpoints/checkpoint-manager.d.ts.map +1 -0
  204. package/dist/core/checkpoints/checkpoint-manager.js +901 -0
  205. package/dist/core/checkpoints/checkpoint-manager.js.map +1 -0
  206. package/dist/core/checkpoints/rewind.d.ts +143 -0
  207. package/dist/core/checkpoints/rewind.d.ts.map +1 -0
  208. package/dist/core/checkpoints/rewind.js +247 -0
  209. package/dist/core/checkpoints/rewind.js.map +1 -0
  210. package/dist/core/compaction/branch-summarization.d.ts +1 -1
  211. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  212. package/dist/core/compaction/branch-summarization.js +11 -6
  213. package/dist/core/compaction/branch-summarization.js.map +1 -1
  214. package/dist/core/compaction/compaction.d.ts +14 -6
  215. package/dist/core/compaction/compaction.d.ts.map +1 -1
  216. package/dist/core/compaction/compaction.js +221 -122
  217. package/dist/core/compaction/compaction.js.map +1 -1
  218. package/dist/core/compaction/utils.d.ts +2 -1
  219. package/dist/core/compaction/utils.d.ts.map +1 -1
  220. package/dist/core/compaction/utils.js +25 -18
  221. package/dist/core/compaction/utils.js.map +1 -1
  222. package/dist/core/crash-log.d.ts +27 -0
  223. package/dist/core/crash-log.d.ts.map +1 -0
  224. package/dist/core/crash-log.js +140 -0
  225. package/dist/core/crash-log.js.map +1 -0
  226. package/dist/core/defaults.d.ts +1 -0
  227. package/dist/core/defaults.d.ts.map +1 -1
  228. package/dist/core/defaults.js +9 -0
  229. package/dist/core/defaults.js.map +1 -1
  230. package/dist/core/experimental.js +1 -1
  231. package/dist/core/experimental.js.map +1 -1
  232. package/dist/core/export-html/template.css +10 -0
  233. package/dist/core/export-html/template.js +72 -18
  234. package/dist/core/extensions/index.d.ts +2 -2
  235. package/dist/core/extensions/index.d.ts.map +1 -1
  236. package/dist/core/extensions/index.js +1 -1
  237. package/dist/core/extensions/index.js.map +1 -1
  238. package/dist/core/extensions/jiti-loader.d.ts +2 -0
  239. package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
  240. package/dist/core/extensions/jiti-loader.js +5 -0
  241. package/dist/core/extensions/jiti-loader.js.map +1 -0
  242. package/dist/core/extensions/loader.d.ts.map +1 -1
  243. package/dist/core/extensions/loader.js +298 -96
  244. package/dist/core/extensions/loader.js.map +1 -1
  245. package/dist/core/extensions/runner.d.ts +59 -9
  246. package/dist/core/extensions/runner.d.ts.map +1 -1
  247. package/dist/core/extensions/runner.js +410 -103
  248. package/dist/core/extensions/runner.js.map +1 -1
  249. package/dist/core/extensions/types.d.ts +701 -85
  250. package/dist/core/extensions/types.d.ts.map +1 -1
  251. package/dist/core/extensions/types.js +3 -0
  252. package/dist/core/extensions/types.js.map +1 -1
  253. package/dist/core/extensions/virtual-modules.d.ts +3 -0
  254. package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
  255. package/dist/core/extensions/virtual-modules.js +37 -0
  256. package/dist/core/extensions/virtual-modules.js.map +1 -0
  257. package/dist/core/extensions/wrapper.d.ts +2 -2
  258. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  259. package/dist/core/extensions/wrapper.js +3 -22
  260. package/dist/core/extensions/wrapper.js.map +1 -1
  261. package/dist/core/footer-data-provider.d.ts +1 -1
  262. package/dist/core/footer-data-provider.js +19 -18
  263. package/dist/core/footer-data-provider.js.map +1 -1
  264. package/dist/core/http-dispatcher.d.ts.map +1 -1
  265. package/dist/core/http-dispatcher.js +7 -0
  266. package/dist/core/http-dispatcher.js.map +1 -1
  267. package/dist/core/index.d.ts +2 -1
  268. package/dist/core/index.d.ts.map +1 -1
  269. package/dist/core/index.js.map +1 -1
  270. package/dist/core/keybindings.d.ts +88 -13
  271. package/dist/core/keybindings.d.ts.map +1 -1
  272. package/dist/core/keybindings.js +34 -7
  273. package/dist/core/keybindings.js.map +1 -1
  274. package/dist/core/mcp-servers.d.ts +119 -0
  275. package/dist/core/mcp-servers.d.ts.map +1 -0
  276. package/dist/core/mcp-servers.js +191 -0
  277. package/dist/core/mcp-servers.js.map +1 -0
  278. package/dist/core/messages.d.ts +1 -1
  279. package/dist/core/messages.d.ts.map +1 -1
  280. package/dist/core/messages.js +1 -0
  281. package/dist/core/messages.js.map +1 -1
  282. package/dist/core/model-config.d.ts +202 -20
  283. package/dist/core/model-config.d.ts.map +1 -1
  284. package/dist/core/model-config.js +53 -18
  285. package/dist/core/model-config.js.map +1 -1
  286. package/dist/core/model-registry.d.ts +21 -3
  287. package/dist/core/model-registry.d.ts.map +1 -1
  288. package/dist/core/model-registry.js +47 -10
  289. package/dist/core/model-registry.js.map +1 -1
  290. package/dist/core/model-resolver.d.ts +7 -5
  291. package/dist/core/model-resolver.d.ts.map +1 -1
  292. package/dist/core/model-resolver.js +62 -23
  293. package/dist/core/model-resolver.js.map +1 -1
  294. package/dist/core/model-runtime.d.ts +80 -15
  295. package/dist/core/model-runtime.d.ts.map +1 -1
  296. package/dist/core/model-runtime.js +466 -120
  297. package/dist/core/model-runtime.js.map +1 -1
  298. package/dist/core/models-store.d.ts +12 -7
  299. package/dist/core/models-store.d.ts.map +1 -1
  300. package/dist/core/models-store.js +87 -18
  301. package/dist/core/models-store.js.map +1 -1
  302. package/dist/core/multi-agent/fsm.js +8 -3
  303. package/dist/core/multi-agent/fsm.js.map +1 -1
  304. package/dist/core/multi-agent/mailbox.js +1 -3
  305. package/dist/core/multi-agent/mailbox.js.map +1 -1
  306. package/dist/core/multi-agent/permission-gate.d.ts +5 -2
  307. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  308. package/dist/core/multi-agent/permission-gate.js +601 -37
  309. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  310. package/dist/core/multi-agent/task-board.js +2 -4
  311. package/dist/core/multi-agent/task-board.js.map +1 -1
  312. package/dist/core/multi-agent/worktree.d.ts +2 -0
  313. package/dist/core/multi-agent/worktree.d.ts.map +1 -1
  314. package/dist/core/multi-agent/worktree.js +3 -5
  315. package/dist/core/multi-agent/worktree.js.map +1 -1
  316. package/dist/core/nested-tool-calls.d.ts +102 -0
  317. package/dist/core/nested-tool-calls.d.ts.map +1 -0
  318. package/dist/core/nested-tool-calls.js +178 -0
  319. package/dist/core/nested-tool-calls.js.map +1 -0
  320. package/dist/core/package-manager.d.ts +16 -0
  321. package/dist/core/package-manager.d.ts.map +1 -1
  322. package/dist/core/package-manager.js +162 -69
  323. package/dist/core/package-manager.js.map +1 -1
  324. package/dist/core/permission-relay/index.d.ts +19 -0
  325. package/dist/core/permission-relay/index.d.ts.map +1 -0
  326. package/dist/core/permission-relay/index.js +49 -0
  327. package/dist/core/permission-relay/index.js.map +1 -0
  328. package/dist/core/permission-relay/relay-ui-context.d.ts +39 -0
  329. package/dist/core/permission-relay/relay-ui-context.d.ts.map +1 -0
  330. package/dist/core/permission-relay/relay-ui-context.js +788 -0
  331. package/dist/core/permission-relay/relay-ui-context.js.map +1 -0
  332. package/dist/core/permission-relay/types.d.ts +222 -0
  333. package/dist/core/permission-relay/types.d.ts.map +1 -0
  334. package/dist/core/permission-relay/types.js +15 -0
  335. package/dist/core/permission-relay/types.js.map +1 -0
  336. package/dist/core/pi-manifest.d.ts +14 -0
  337. package/dist/core/pi-manifest.d.ts.map +1 -0
  338. package/dist/core/pi-manifest.js +36 -0
  339. package/dist/core/pi-manifest.js.map +1 -0
  340. package/dist/core/project-trust.js +2 -2
  341. package/dist/core/project-trust.js.map +1 -1
  342. package/dist/core/prompt-templates.d.ts +6 -1
  343. package/dist/core/prompt-templates.d.ts.map +1 -1
  344. package/dist/core/prompt-templates.js +63 -37
  345. package/dist/core/prompt-templates.js.map +1 -1
  346. package/dist/core/provider-attribution.js +5 -5
  347. package/dist/core/provider-attribution.js.map +1 -1
  348. package/dist/core/provider-composer.d.ts +44 -20
  349. package/dist/core/provider-composer.d.ts.map +1 -1
  350. package/dist/core/provider-composer.js +151 -51
  351. package/dist/core/provider-composer.js.map +1 -1
  352. package/dist/core/radius.d.ts +13 -0
  353. package/dist/core/radius.d.ts.map +1 -1
  354. package/dist/core/radius.js +19 -0
  355. package/dist/core/radius.js.map +1 -1
  356. package/dist/core/remote-catalog-provider.d.ts +10 -3
  357. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  358. package/dist/core/remote-catalog-provider.js +105 -81
  359. package/dist/core/remote-catalog-provider.js.map +1 -1
  360. package/dist/core/resource-loader.d.ts +28 -1
  361. package/dist/core/resource-loader.d.ts.map +1 -1
  362. package/dist/core/resource-loader.js +319 -65
  363. package/dist/core/resource-loader.js.map +1 -1
  364. package/dist/core/runtime-credentials.d.ts +5 -5
  365. package/dist/core/runtime-credentials.d.ts.map +1 -1
  366. package/dist/core/runtime-credentials.js +13 -9
  367. package/dist/core/runtime-credentials.js.map +1 -1
  368. package/dist/core/sandbox/bash-operations.d.ts +149 -0
  369. package/dist/core/sandbox/bash-operations.d.ts.map +1 -0
  370. package/dist/core/sandbox/bash-operations.js +163 -0
  371. package/dist/core/sandbox/bash-operations.js.map +1 -0
  372. package/dist/core/sandbox/env.d.ts +83 -0
  373. package/dist/core/sandbox/env.d.ts.map +1 -0
  374. package/dist/core/sandbox/env.js +123 -0
  375. package/dist/core/sandbox/env.js.map +1 -0
  376. package/dist/core/sandbox/executor.d.ts +104 -0
  377. package/dist/core/sandbox/executor.d.ts.map +1 -0
  378. package/dist/core/sandbox/executor.js +93 -0
  379. package/dist/core/sandbox/executor.js.map +1 -0
  380. package/dist/core/sandbox/index.d.ts +36 -0
  381. package/dist/core/sandbox/index.d.ts.map +1 -0
  382. package/dist/core/sandbox/index.js +36 -0
  383. package/dist/core/sandbox/index.js.map +1 -0
  384. package/dist/core/sandbox/linux.d.ts +121 -0
  385. package/dist/core/sandbox/linux.d.ts.map +1 -0
  386. package/dist/core/sandbox/linux.js +260 -0
  387. package/dist/core/sandbox/linux.js.map +1 -0
  388. package/dist/core/sandbox/policy.d.ts +142 -0
  389. package/dist/core/sandbox/policy.d.ts.map +1 -0
  390. package/dist/core/sandbox/policy.js +297 -0
  391. package/dist/core/sandbox/policy.js.map +1 -0
  392. package/dist/core/sandbox/real-path.d.ts +112 -0
  393. package/dist/core/sandbox/real-path.d.ts.map +1 -0
  394. package/dist/core/sandbox/real-path.js +158 -0
  395. package/dist/core/sandbox/real-path.js.map +1 -0
  396. package/dist/core/sandbox/seatbelt-profile.d.ts +95 -0
  397. package/dist/core/sandbox/seatbelt-profile.d.ts.map +1 -0
  398. package/dist/core/sandbox/seatbelt-profile.js +239 -0
  399. package/dist/core/sandbox/seatbelt-profile.js.map +1 -0
  400. package/dist/core/sandbox/seatbelt.d.ts +95 -0
  401. package/dist/core/sandbox/seatbelt.d.ts.map +1 -0
  402. package/dist/core/sandbox/seatbelt.js +154 -0
  403. package/dist/core/sandbox/seatbelt.js.map +1 -0
  404. package/dist/core/sandbox/self-test.d.ts +109 -0
  405. package/dist/core/sandbox/self-test.d.ts.map +1 -0
  406. package/dist/core/sandbox/self-test.js +369 -0
  407. package/dist/core/sandbox/self-test.js.map +1 -0
  408. package/dist/core/sandbox/spawn.d.ts +33 -0
  409. package/dist/core/sandbox/spawn.d.ts.map +1 -0
  410. package/dist/core/sandbox/spawn.js +87 -0
  411. package/dist/core/sandbox/spawn.js.map +1 -0
  412. package/dist/core/sdk.d.ts +7 -5
  413. package/dist/core/sdk.d.ts.map +1 -1
  414. package/dist/core/sdk.js +103 -53
  415. package/dist/core/sdk.js.map +1 -1
  416. package/dist/core/session-cwd.js +1 -0
  417. package/dist/core/session-cwd.js.map +1 -1
  418. package/dist/core/session-export.d.ts +8 -0
  419. package/dist/core/session-export.d.ts.map +1 -0
  420. package/dist/core/session-export.js +33 -0
  421. package/dist/core/session-export.js.map +1 -0
  422. package/dist/core/session-manager.d.ts +134 -15
  423. package/dist/core/session-manager.d.ts.map +1 -1
  424. package/dist/core/session-manager.js +366 -149
  425. package/dist/core/session-manager.js.map +1 -1
  426. package/dist/core/settings-diagnostics.d.ts +9 -0
  427. package/dist/core/settings-diagnostics.d.ts.map +1 -0
  428. package/dist/core/settings-diagnostics.js +21 -0
  429. package/dist/core/settings-diagnostics.js.map +1 -0
  430. package/dist/core/settings-manager.d.ts +105 -4
  431. package/dist/core/settings-manager.d.ts.map +1 -1
  432. package/dist/core/settings-manager.js +274 -40
  433. package/dist/core/settings-manager.js.map +1 -1
  434. package/dist/core/skills.d.ts +3 -1
  435. package/dist/core/skills.d.ts.map +1 -1
  436. package/dist/core/skills.js +70 -39
  437. package/dist/core/skills.js.map +1 -1
  438. package/dist/core/slash-commands.d.ts.map +1 -1
  439. package/dist/core/slash-commands.js +4 -1
  440. package/dist/core/slash-commands.js.map +1 -1
  441. package/dist/core/soak/soak-log.d.ts +298 -0
  442. package/dist/core/soak/soak-log.d.ts.map +1 -0
  443. package/dist/core/soak/soak-log.js +666 -0
  444. package/dist/core/soak/soak-log.js.map +1 -0
  445. package/dist/core/soak/soak-reader.d.ts +60 -0
  446. package/dist/core/soak/soak-reader.d.ts.map +1 -0
  447. package/dist/core/soak/soak-reader.js +106 -0
  448. package/dist/core/soak/soak-reader.js.map +1 -0
  449. package/dist/core/socket-server/discovery.d.ts +78 -1
  450. package/dist/core/socket-server/discovery.d.ts.map +1 -1
  451. package/dist/core/socket-server/discovery.js +356 -37
  452. package/dist/core/socket-server/discovery.js.map +1 -1
  453. package/dist/core/socket-server/index.d.ts +10 -4
  454. package/dist/core/socket-server/index.d.ts.map +1 -1
  455. package/dist/core/socket-server/index.js +6 -3
  456. package/dist/core/socket-server/index.js.map +1 -1
  457. package/dist/core/socket-server/permission-delivery.d.ts +125 -0
  458. package/dist/core/socket-server/permission-delivery.d.ts.map +1 -0
  459. package/dist/core/socket-server/permission-delivery.js +152 -0
  460. package/dist/core/socket-server/permission-delivery.js.map +1 -0
  461. package/dist/core/socket-server/permission-registry.d.ts +301 -0
  462. package/dist/core/socket-server/permission-registry.d.ts.map +1 -0
  463. package/dist/core/socket-server/permission-registry.js +410 -0
  464. package/dist/core/socket-server/permission-registry.js.map +1 -0
  465. package/dist/core/socket-server/permission-relay.d.ts +81 -0
  466. package/dist/core/socket-server/permission-relay.d.ts.map +1 -0
  467. package/dist/core/socket-server/permission-relay.js +528 -0
  468. package/dist/core/socket-server/permission-relay.js.map +1 -0
  469. package/dist/core/socket-server/safe-text.d.ts +83 -0
  470. package/dist/core/socket-server/safe-text.d.ts.map +1 -0
  471. package/dist/core/socket-server/safe-text.js +277 -0
  472. package/dist/core/socket-server/safe-text.js.map +1 -0
  473. package/dist/core/socket-server/session-integration.d.ts +65 -2
  474. package/dist/core/socket-server/session-integration.d.ts.map +1 -1
  475. package/dist/core/socket-server/session-integration.js +434 -32
  476. package/dist/core/socket-server/session-integration.js.map +1 -1
  477. package/dist/core/socket-server/socket-client.d.ts +21 -2
  478. package/dist/core/socket-server/socket-client.d.ts.map +1 -1
  479. package/dist/core/socket-server/socket-client.js +52 -1
  480. package/dist/core/socket-server/socket-client.js.map +1 -1
  481. package/dist/core/socket-server/socket-server.d.ts +152 -1
  482. package/dist/core/socket-server/socket-server.d.ts.map +1 -1
  483. package/dist/core/socket-server/socket-server.js +786 -26
  484. package/dist/core/socket-server/socket-server.js.map +1 -1
  485. package/dist/core/socket-server/types.d.ts +108 -3
  486. package/dist/core/socket-server/types.d.ts.map +1 -1
  487. package/dist/core/socket-server/types.js +13 -1
  488. package/dist/core/socket-server/types.js.map +1 -1
  489. package/dist/core/source-info.d.ts +8 -0
  490. package/dist/core/source-info.d.ts.map +1 -1
  491. package/dist/core/source-info.js +16 -0
  492. package/dist/core/source-info.js.map +1 -1
  493. package/dist/core/system-prompt.d.ts +49 -6
  494. package/dist/core/system-prompt.d.ts.map +1 -1
  495. package/dist/core/system-prompt.js +126 -90
  496. package/dist/core/system-prompt.js.map +1 -1
  497. package/dist/core/tools/bash.d.ts +32 -2
  498. package/dist/core/tools/bash.d.ts.map +1 -1
  499. package/dist/core/tools/bash.js +83 -141
  500. package/dist/core/tools/bash.js.map +1 -1
  501. package/dist/core/tools/edit-diff.d.ts +0 -5
  502. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  503. package/dist/core/tools/edit-diff.js +2 -5
  504. package/dist/core/tools/edit-diff.js.map +1 -1
  505. package/dist/core/tools/edit.d.ts +5 -12
  506. package/dist/core/tools/edit.d.ts.map +1 -1
  507. package/dist/core/tools/edit.js +36 -173
  508. package/dist/core/tools/edit.js.map +1 -1
  509. package/dist/core/tools/find.d.ts +7 -0
  510. package/dist/core/tools/find.d.ts.map +1 -1
  511. package/dist/core/tools/find.js +22 -76
  512. package/dist/core/tools/find.js.map +1 -1
  513. package/dist/core/tools/grep.d.ts +4 -0
  514. package/dist/core/tools/grep.d.ts.map +1 -1
  515. package/dist/core/tools/grep.js +10 -62
  516. package/dist/core/tools/grep.js.map +1 -1
  517. package/dist/core/tools/index.d.ts +4 -1
  518. package/dist/core/tools/index.d.ts.map +1 -1
  519. package/dist/core/tools/index.js +18 -1
  520. package/dist/core/tools/index.js.map +1 -1
  521. package/dist/core/tools/ls.d.ts +4 -0
  522. package/dist/core/tools/ls.d.ts.map +1 -1
  523. package/dist/core/tools/ls.js +9 -50
  524. package/dist/core/tools/ls.js.map +1 -1
  525. package/dist/core/tools/output-accumulator.d.ts +11 -0
  526. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  527. package/dist/core/tools/output-accumulator.js +54 -12
  528. package/dist/core/tools/output-accumulator.js.map +1 -1
  529. package/dist/core/tools/powershell.d.ts +16 -0
  530. package/dist/core/tools/powershell.d.ts.map +1 -0
  531. package/dist/core/tools/powershell.js +39 -0
  532. package/dist/core/tools/powershell.js.map +1 -0
  533. package/dist/core/tools/read.d.ts +8 -1
  534. package/dist/core/tools/read.d.ts.map +1 -1
  535. package/dist/core/tools/read.js +16 -123
  536. package/dist/core/tools/read.js.map +1 -1
  537. package/dist/core/tools/render-utils.d.ts +6 -0
  538. package/dist/core/tools/render-utils.d.ts.map +1 -1
  539. package/dist/core/tools/render-utils.js +26 -0
  540. package/dist/core/tools/render-utils.js.map +1 -1
  541. package/dist/core/tools/renderers/bash.d.ts +12 -0
  542. package/dist/core/tools/renderers/bash.d.ts.map +1 -0
  543. package/dist/core/tools/renderers/bash.js +117 -0
  544. package/dist/core/tools/renderers/bash.js.map +1 -0
  545. package/dist/core/tools/renderers/edit.d.ts +23 -0
  546. package/dist/core/tools/renderers/edit.d.ts.map +1 -0
  547. package/dist/core/tools/renderers/edit.js +167 -0
  548. package/dist/core/tools/renderers/edit.js.map +1 -0
  549. package/dist/core/tools/renderers/find.d.ts +10 -0
  550. package/dist/core/tools/renderers/find.d.ts.map +1 -0
  551. package/dist/core/tools/renderers/find.js +64 -0
  552. package/dist/core/tools/renderers/find.js.map +1 -0
  553. package/dist/core/tools/renderers/grep.d.ts +10 -0
  554. package/dist/core/tools/renderers/grep.d.ts.map +1 -0
  555. package/dist/core/tools/renderers/grep.js +69 -0
  556. package/dist/core/tools/renderers/grep.js.map +1 -0
  557. package/dist/core/tools/renderers/index.d.ts +28 -0
  558. package/dist/core/tools/renderers/index.d.ts.map +1 -0
  559. package/dist/core/tools/renderers/index.js +47 -0
  560. package/dist/core/tools/renderers/index.js.map +1 -0
  561. package/dist/core/tools/renderers/ls.d.ts +10 -0
  562. package/dist/core/tools/renderers/ls.d.ts.map +1 -0
  563. package/dist/core/tools/renderers/ls.js +58 -0
  564. package/dist/core/tools/renderers/ls.js.map +1 -0
  565. package/dist/core/tools/renderers/read.d.ts +11 -0
  566. package/dist/core/tools/renderers/read.d.ts.map +1 -0
  567. package/dist/core/tools/renderers/read.js +130 -0
  568. package/dist/core/tools/renderers/read.js.map +1 -0
  569. package/dist/core/tools/renderers/write.d.ts +10 -0
  570. package/dist/core/tools/renderers/write.d.ts.map +1 -0
  571. package/dist/core/tools/renderers/write.js +153 -0
  572. package/dist/core/tools/renderers/write.js.map +1 -0
  573. package/dist/core/tools/tool-definition-wrapper.d.ts +5 -3
  574. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  575. package/dist/core/tools/tool-definition-wrapper.js +3 -1
  576. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  577. package/dist/core/tools/truncate.d.ts +14 -0
  578. package/dist/core/tools/truncate.d.ts.map +1 -1
  579. package/dist/core/tools/truncate.js +29 -0
  580. package/dist/core/tools/truncate.js.map +1 -1
  581. package/dist/core/tools/write.d.ts +4 -0
  582. package/dist/core/tools/write.d.ts.map +1 -1
  583. package/dist/core/tools/write.js +12 -147
  584. package/dist/core/tools/write.js.map +1 -1
  585. package/dist/core/trust-manager.d.ts +6 -4
  586. package/dist/core/trust-manager.d.ts.map +1 -1
  587. package/dist/core/trust-manager.js +59 -22
  588. package/dist/core/trust-manager.js.map +1 -1
  589. package/dist/core/usage-totals.d.ts +3 -1
  590. package/dist/core/usage-totals.d.ts.map +1 -1
  591. package/dist/core/usage-totals.js +28 -1
  592. package/dist/core/usage-totals.js.map +1 -1
  593. package/dist/core/virtual-models.d.ts +117 -0
  594. package/dist/core/virtual-models.d.ts.map +1 -0
  595. package/dist/core/virtual-models.js +124 -0
  596. package/dist/core/virtual-models.js.map +1 -0
  597. package/dist/experimental/micro/api.d.ts +81 -0
  598. package/dist/experimental/micro/api.d.ts.map +1 -0
  599. package/dist/experimental/micro/api.js +2 -0
  600. package/dist/experimental/micro/api.js.map +1 -0
  601. package/dist/experimental/micro/main.d.ts +3 -0
  602. package/dist/experimental/micro/main.d.ts.map +1 -0
  603. package/dist/experimental/micro/main.js +21 -0
  604. package/dist/experimental/micro/main.js.map +1 -0
  605. package/dist/experimental/micro/models.d.ts +11 -0
  606. package/dist/experimental/micro/models.d.ts.map +1 -0
  607. package/dist/experimental/micro/models.js +95 -0
  608. package/dist/experimental/micro/models.js.map +1 -0
  609. package/dist/experimental/micro/runtime.d.ts +12 -0
  610. package/dist/experimental/micro/runtime.d.ts.map +1 -0
  611. package/dist/experimental/micro/runtime.js +465 -0
  612. package/dist/experimental/micro/runtime.js.map +1 -0
  613. package/dist/experimental/micro/sessions.d.ts +10 -0
  614. package/dist/experimental/micro/sessions.d.ts.map +1 -0
  615. package/dist/experimental/micro/sessions.js +41 -0
  616. package/dist/experimental/micro/sessions.js.map +1 -0
  617. package/dist/experimental/micro/tools.d.ts +10 -0
  618. package/dist/experimental/micro/tools.d.ts.map +1 -0
  619. package/dist/experimental/micro/tools.js +96 -0
  620. package/dist/experimental/micro/tools.js.map +1 -0
  621. package/dist/experimental/micro/tui.d.ts +3 -0
  622. package/dist/experimental/micro/tui.d.ts.map +1 -0
  623. package/dist/experimental/micro/tui.js +510 -0
  624. package/dist/experimental/micro/tui.js.map +1 -0
  625. package/dist/experimental/mini/main.d.ts +7 -0
  626. package/dist/experimental/mini/main.d.ts.map +1 -0
  627. package/dist/experimental/mini/main.js +21 -0
  628. package/dist/experimental/mini/main.js.map +1 -0
  629. package/dist/experimental/mini/server/entry.d.ts +3 -0
  630. package/dist/experimental/mini/server/entry.d.ts.map +1 -0
  631. package/dist/experimental/mini/server/entry.js +11 -0
  632. package/dist/experimental/mini/server/entry.js.map +1 -0
  633. package/dist/experimental/mini/server/run.d.ts +13 -0
  634. package/dist/experimental/mini/server/run.d.ts.map +1 -0
  635. package/dist/experimental/mini/server/run.js +150 -0
  636. package/dist/experimental/mini/server/run.js.map +1 -0
  637. package/dist/experimental/mini/shared/protocol.d.ts +127 -0
  638. package/dist/experimental/mini/shared/protocol.d.ts.map +1 -0
  639. package/dist/experimental/mini/shared/protocol.js +13 -0
  640. package/dist/experimental/mini/shared/protocol.js.map +1 -0
  641. package/dist/experimental/mini/shared/rpc.d.ts +49 -0
  642. package/dist/experimental/mini/shared/rpc.d.ts.map +1 -0
  643. package/dist/experimental/mini/shared/rpc.js +171 -0
  644. package/dist/experimental/mini/shared/rpc.js.map +1 -0
  645. package/dist/experimental/mini/shared/transport.d.ts +35 -0
  646. package/dist/experimental/mini/shared/transport.d.ts.map +1 -0
  647. package/dist/experimental/mini/shared/transport.js +94 -0
  648. package/dist/experimental/mini/shared/transport.js.map +1 -0
  649. package/dist/experimental/mini/tui/run.d.ts +9 -0
  650. package/dist/experimental/mini/tui/run.d.ts.map +1 -0
  651. package/dist/experimental/mini/tui/run.js +62 -0
  652. package/dist/experimental/mini/tui/run.js.map +1 -0
  653. package/dist/experimental/mini/tui/session.d.ts +26 -0
  654. package/dist/experimental/mini/tui/session.d.ts.map +1 -0
  655. package/dist/experimental/mini/tui/session.js +94 -0
  656. package/dist/experimental/mini/tui/session.js.map +1 -0
  657. package/dist/experimental/mini/tui/view.d.ts +10 -0
  658. package/dist/experimental/mini/tui/view.d.ts.map +1 -0
  659. package/dist/experimental/mini/tui/view.js +461 -0
  660. package/dist/experimental/mini/tui/view.js.map +1 -0
  661. package/dist/experimental/mini/worker/entry.d.ts +3 -0
  662. package/dist/experimental/mini/worker/entry.d.ts.map +1 -0
  663. package/dist/experimental/mini/worker/entry.js +10 -0
  664. package/dist/experimental/mini/worker/entry.js.map +1 -0
  665. package/dist/experimental/mini/worker/lane-service.d.ts +44 -0
  666. package/dist/experimental/mini/worker/lane-service.d.ts.map +1 -0
  667. package/dist/experimental/mini/worker/lane-service.js +97 -0
  668. package/dist/experimental/mini/worker/lane-service.js.map +1 -0
  669. package/dist/experimental/mini/worker/models-service.d.ts +19 -0
  670. package/dist/experimental/mini/worker/models-service.d.ts.map +1 -0
  671. package/dist/experimental/mini/worker/models-service.js +136 -0
  672. package/dist/experimental/mini/worker/models-service.js.map +1 -0
  673. package/dist/experimental/mini/worker/run.d.ts +14 -0
  674. package/dist/experimental/mini/worker/run.d.ts.map +1 -0
  675. package/dist/experimental/mini/worker/run.js +88 -0
  676. package/dist/experimental/mini/worker/run.js.map +1 -0
  677. package/dist/extensions/codemode/execute.d.ts +16 -0
  678. package/dist/extensions/codemode/execute.d.ts.map +1 -0
  679. package/dist/extensions/codemode/execute.js +429 -0
  680. package/dist/extensions/codemode/execute.js.map +1 -0
  681. package/dist/extensions/codemode/execute.lazy.d.ts +3 -0
  682. package/dist/extensions/codemode/execute.lazy.d.ts.map +1 -0
  683. package/dist/extensions/codemode/execute.lazy.js +3 -0
  684. package/dist/extensions/codemode/execute.lazy.js.map +1 -0
  685. package/dist/extensions/codemode/index.d.ts +21 -0
  686. package/dist/extensions/codemode/index.d.ts.map +1 -0
  687. package/dist/extensions/codemode/index.js +31 -0
  688. package/dist/extensions/codemode/index.js.map +1 -0
  689. package/dist/extensions/codemode/renderer.d.ts +12 -0
  690. package/dist/extensions/codemode/renderer.d.ts.map +1 -0
  691. package/dist/extensions/codemode/renderer.js +137 -0
  692. package/dist/extensions/codemode/renderer.js.map +1 -0
  693. package/dist/extensions/codemode/tool.d.ts +123 -0
  694. package/dist/extensions/codemode/tool.d.ts.map +1 -0
  695. package/dist/extensions/codemode/tool.js +315 -0
  696. package/dist/extensions/codemode/tool.js.map +1 -0
  697. package/dist/extensions/codemode/worker.d.ts +7 -0
  698. package/dist/extensions/codemode/worker.d.ts.map +1 -0
  699. package/dist/extensions/codemode/worker.js +7 -0
  700. package/dist/extensions/codemode/worker.js.map +1 -0
  701. package/dist/extensions/index.d.ts.map +1 -1
  702. package/dist/extensions/index.js +13 -1
  703. package/dist/extensions/index.js.map +1 -1
  704. package/dist/extensions/llama/client.d.ts +8 -0
  705. package/dist/extensions/llama/client.d.ts.map +1 -1
  706. package/dist/extensions/llama/client.js +13 -0
  707. package/dist/extensions/llama/client.js.map +1 -1
  708. package/dist/extensions/llama/huggingface.js +2 -0
  709. package/dist/extensions/llama/huggingface.js.map +1 -1
  710. package/dist/extensions/llama/index.d.ts.map +1 -1
  711. package/dist/extensions/llama/index.js +13 -2
  712. package/dist/extensions/llama/index.js.map +1 -1
  713. package/dist/extensions/llama/provider.d.ts +4 -2
  714. package/dist/extensions/llama/provider.d.ts.map +1 -1
  715. package/dist/extensions/llama/provider.js +121 -15
  716. package/dist/extensions/llama/provider.js.map +1 -1
  717. package/dist/extensions/llama/ui.js +28 -12
  718. package/dist/extensions/llama/ui.js.map +1 -1
  719. package/dist/extensions/mcp/cli.d.ts +21 -0
  720. package/dist/extensions/mcp/cli.d.ts.map +1 -0
  721. package/dist/extensions/mcp/cli.js +500 -0
  722. package/dist/extensions/mcp/cli.js.map +1 -0
  723. package/dist/extensions/mcp/cli.lazy.d.ts +3 -0
  724. package/dist/extensions/mcp/cli.lazy.d.ts.map +1 -0
  725. package/dist/extensions/mcp/cli.lazy.js +3 -0
  726. package/dist/extensions/mcp/cli.lazy.js.map +1 -0
  727. package/dist/extensions/mcp/config.d.ts +72 -0
  728. package/dist/extensions/mcp/config.d.ts.map +1 -0
  729. package/dist/extensions/mcp/config.js +158 -0
  730. package/dist/extensions/mcp/config.js.map +1 -0
  731. package/dist/extensions/mcp/index.d.ts +76 -0
  732. package/dist/extensions/mcp/index.d.ts.map +1 -0
  733. package/dist/extensions/mcp/index.js +1055 -0
  734. package/dist/extensions/mcp/index.js.map +1 -0
  735. package/dist/extensions/mcp/log.d.ts +16 -0
  736. package/dist/extensions/mcp/log.d.ts.map +1 -0
  737. package/dist/extensions/mcp/log.js +66 -0
  738. package/dist/extensions/mcp/log.js.map +1 -0
  739. package/dist/extensions/mcp/oauth.d.ts +96 -0
  740. package/dist/extensions/mcp/oauth.d.ts.map +1 -0
  741. package/dist/extensions/mcp/oauth.js +333 -0
  742. package/dist/extensions/mcp/oauth.js.map +1 -0
  743. package/dist/extensions/mcp/resources.d.ts +43 -0
  744. package/dist/extensions/mcp/resources.d.ts.map +1 -0
  745. package/dist/extensions/mcp/resources.js +262 -0
  746. package/dist/extensions/mcp/resources.js.map +1 -0
  747. package/dist/extensions/mcp/runtime.d.ts +98 -0
  748. package/dist/extensions/mcp/runtime.d.ts.map +1 -0
  749. package/dist/extensions/mcp/runtime.js +394 -0
  750. package/dist/extensions/mcp/runtime.js.map +1 -0
  751. package/dist/extensions/mcp/runtime.lazy.d.ts +3 -0
  752. package/dist/extensions/mcp/runtime.lazy.d.ts.map +1 -0
  753. package/dist/extensions/mcp/runtime.lazy.js +3 -0
  754. package/dist/extensions/mcp/runtime.lazy.js.map +1 -0
  755. package/dist/extensions/mcp/tools.d.ts +84 -0
  756. package/dist/extensions/mcp/tools.d.ts.map +1 -0
  757. package/dist/extensions/mcp/tools.js +251 -0
  758. package/dist/extensions/mcp/tools.js.map +1 -0
  759. package/dist/extensions/mcp/ui.d.ts +60 -0
  760. package/dist/extensions/mcp/ui.d.ts.map +1 -0
  761. package/dist/extensions/mcp/ui.js +174 -0
  762. package/dist/extensions/mcp/ui.js.map +1 -0
  763. package/dist/extensions/stub-provider/index.d.ts +9 -0
  764. package/dist/extensions/stub-provider/index.d.ts.map +1 -0
  765. package/dist/extensions/stub-provider/index.js +13 -0
  766. package/dist/extensions/stub-provider/index.js.map +1 -0
  767. package/dist/extensions/stub-provider/provider.d.ts +77 -0
  768. package/dist/extensions/stub-provider/provider.d.ts.map +1 -0
  769. package/dist/extensions/stub-provider/provider.js +194 -0
  770. package/dist/extensions/stub-provider/provider.js.map +1 -0
  771. package/dist/extensions/tool-search/index.d.ts +12 -0
  772. package/dist/extensions/tool-search/index.d.ts.map +1 -0
  773. package/dist/extensions/tool-search/index.js +15 -0
  774. package/dist/extensions/tool-search/index.js.map +1 -0
  775. package/dist/extensions/tool-search/tool.d.ts +73 -0
  776. package/dist/extensions/tool-search/tool.d.ts.map +1 -0
  777. package/dist/extensions/tool-search/tool.js +189 -0
  778. package/dist/extensions/tool-search/tool.js.map +1 -0
  779. package/dist/hooks/gsd/draht-quality-gate.js +3 -3
  780. package/dist/index.d.ts +20 -11
  781. package/dist/index.d.ts.map +1 -1
  782. package/dist/index.js +12 -6
  783. package/dist/index.js.map +1 -1
  784. package/dist/main.d.ts +4 -0
  785. package/dist/main.d.ts.map +1 -1
  786. package/dist/main.js +365 -96
  787. package/dist/main.js.map +1 -1
  788. package/dist/migrations.d.ts +1 -1
  789. package/dist/migrations.js +7 -6
  790. package/dist/migrations.js.map +1 -1
  791. package/dist/modes/index.d.ts +1 -0
  792. package/dist/modes/index.d.ts.map +1 -1
  793. package/dist/modes/index.js.map +1 -1
  794. package/dist/modes/interactive/bug-report.d.ts +19 -0
  795. package/dist/modes/interactive/bug-report.d.ts.map +1 -0
  796. package/dist/modes/interactive/bug-report.js +211 -0
  797. package/dist/modes/interactive/bug-report.js.map +1 -0
  798. package/dist/modes/interactive/chat-viewport.d.ts +20 -0
  799. package/dist/modes/interactive/chat-viewport.d.ts.map +1 -0
  800. package/dist/modes/interactive/chat-viewport.js +28 -0
  801. package/dist/modes/interactive/chat-viewport.js.map +1 -0
  802. package/dist/modes/interactive/components/armin.js +10 -6
  803. package/dist/modes/interactive/components/armin.js.map +1 -1
  804. package/dist/modes/interactive/components/assistant-message.d.ts +6 -2
  805. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  806. package/dist/modes/interactive/components/assistant-message.js +38 -15
  807. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  808. package/dist/modes/interactive/components/bash-execution.js +9 -4
  809. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  810. package/dist/modes/interactive/components/bordered-loader.js +3 -0
  811. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  812. package/dist/modes/interactive/components/branch-summary-message.d.ts +1 -1
  813. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  814. package/dist/modes/interactive/components/branch-summary-message.js +15 -6
  815. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  816. package/dist/modes/interactive/components/compaction-summary-message.d.ts +1 -1
  817. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  818. package/dist/modes/interactive/components/compaction-summary-message.js +15 -6
  819. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  820. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  821. package/dist/modes/interactive/components/config-selector.js +38 -10
  822. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  823. package/dist/modes/interactive/components/countdown-timer.js +5 -0
  824. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  825. package/dist/modes/interactive/components/custom-editor.d.ts +10 -1
  826. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  827. package/dist/modes/interactive/components/custom-editor.js +54 -2
  828. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  829. package/dist/modes/interactive/components/custom-entry.js +4 -1
  830. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  831. package/dist/modes/interactive/components/custom-message.js +7 -1
  832. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  833. package/dist/modes/interactive/components/daxnuts.js +8 -6
  834. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  835. package/dist/modes/interactive/components/dynamic-border.js +1 -0
  836. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  837. package/dist/modes/interactive/components/extension-editor.d.ts +4 -1
  838. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  839. package/dist/modes/interactive/components/extension-editor.js +14 -3
  840. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  841. package/dist/modes/interactive/components/extension-input.d.ts +2 -0
  842. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  843. package/dist/modes/interactive/components/extension-input.js +14 -2
  844. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  845. package/dist/modes/interactive/components/extension-selector.d.ts +50 -0
  846. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  847. package/dist/modes/interactive/components/extension-selector.js +218 -6
  848. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  849. package/dist/modes/interactive/components/first-time-setup.d.ts +4 -4
  850. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  851. package/dist/modes/interactive/components/first-time-setup.js +12 -4
  852. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  853. package/dist/modes/interactive/components/footer.d.ts +7 -0
  854. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  855. package/dist/modes/interactive/components/footer.js +51 -6
  856. package/dist/modes/interactive/components/footer.js.map +1 -1
  857. package/dist/modes/interactive/components/index.d.ts +1 -1
  858. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  859. package/dist/modes/interactive/components/index.js.map +1 -1
  860. package/dist/modes/interactive/components/login-dialog.js +9 -3
  861. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  862. package/dist/modes/interactive/components/markdown-transform.d.ts +3 -0
  863. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -0
  864. package/dist/modes/interactive/components/markdown-transform.js +19 -0
  865. package/dist/modes/interactive/components/markdown-transform.js.map +1 -0
  866. package/dist/modes/interactive/components/mermaid.d.ts +11 -0
  867. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -0
  868. package/dist/modes/interactive/components/mermaid.js +75 -0
  869. package/dist/modes/interactive/components/mermaid.js.map +1 -0
  870. package/dist/modes/interactive/components/model-selector.d.ts +10 -4
  871. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  872. package/dist/modes/interactive/components/model-selector.js +101 -40
  873. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  874. package/dist/modes/interactive/components/oauth-selector.js +11 -3
  875. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  876. package/dist/modes/interactive/components/scoped-models-selector.d.ts +4 -0
  877. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  878. package/dist/modes/interactive/components/scoped-models-selector.js +60 -32
  879. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  880. package/dist/modes/interactive/components/session-selector.d.ts +5 -5
  881. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  882. package/dist/modes/interactive/components/session-selector.js +138 -80
  883. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  884. package/dist/modes/interactive/components/settings-selector.d.ts +25 -4
  885. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  886. package/dist/modes/interactive/components/settings-selector.js +240 -67
  887. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  888. package/dist/modes/interactive/components/settings-submenu.d.ts +72 -0
  889. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -0
  890. package/dist/modes/interactive/components/settings-submenu.js +165 -0
  891. package/dist/modes/interactive/components/settings-submenu.js.map +1 -0
  892. package/dist/modes/interactive/components/show-images-selector.js +1 -0
  893. package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
  894. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  895. package/dist/modes/interactive/components/skill-invocation-message.js +14 -5
  896. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  897. package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
  898. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  899. package/dist/modes/interactive/components/status-indicator.js +12 -3
  900. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  901. package/dist/modes/interactive/components/theme-selector.js +2 -0
  902. package/dist/modes/interactive/components/theme-selector.js.map +1 -1
  903. package/dist/modes/interactive/components/themed-text.d.ts +17 -0
  904. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -0
  905. package/dist/modes/interactive/components/themed-text.js +29 -0
  906. package/dist/modes/interactive/components/themed-text.js.map +1 -0
  907. package/dist/modes/interactive/components/thinking-selector.d.ts +15 -3
  908. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  909. package/dist/modes/interactive/components/thinking-selector.js +76 -18
  910. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  911. package/dist/modes/interactive/components/tool-execution.d.ts +21 -4
  912. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  913. package/dist/modes/interactive/components/tool-execution.js +88 -53
  914. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  915. package/dist/modes/interactive/components/tree-selector.d.ts +20 -2
  916. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  917. package/dist/modes/interactive/components/tree-selector.js +65 -23
  918. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  919. package/dist/modes/interactive/components/trust-selector.js +8 -2
  920. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  921. package/dist/modes/interactive/components/user-message-selector.js +6 -3
  922. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  923. package/dist/modes/interactive/components/user-message.d.ts +3 -1
  924. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  925. package/dist/modes/interactive/components/user-message.js +12 -2
  926. package/dist/modes/interactive/components/user-message.js.map +1 -1
  927. package/dist/modes/interactive/components/visual-truncate.d.ts +27 -3
  928. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  929. package/dist/modes/interactive/components/visual-truncate.js +39 -6
  930. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  931. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  932. package/dist/modes/interactive/external-editor.js +2 -1
  933. package/dist/modes/interactive/external-editor.js.map +1 -1
  934. package/dist/modes/interactive/interactive-mode.d.ts +166 -8
  935. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  936. package/dist/modes/interactive/interactive-mode.js +1690 -599
  937. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  938. package/dist/modes/interactive/model-catalog-refresh.d.ts +7 -0
  939. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
  940. package/dist/modes/interactive/model-catalog-refresh.js +34 -0
  941. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -0
  942. package/dist/modes/interactive/session-share.d.ts +23 -0
  943. package/dist/modes/interactive/session-share.d.ts.map +1 -0
  944. package/dist/modes/interactive/session-share.js +130 -0
  945. package/dist/modes/interactive/session-share.js.map +1 -0
  946. package/dist/modes/interactive/theme/dark.json +54 -63
  947. package/dist/modes/interactive/theme/light.json +52 -60
  948. package/dist/modes/interactive/theme/system-theme.d.ts +54 -0
  949. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -0
  950. package/dist/modes/interactive/theme/system-theme.js +535 -0
  951. package/dist/modes/interactive/theme/system-theme.js.map +1 -0
  952. package/dist/modes/interactive/theme/theme-controller.d.ts +59 -7
  953. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  954. package/dist/modes/interactive/theme/theme-controller.js +164 -51
  955. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  956. package/dist/modes/interactive/theme/theme-json.d.ts +85 -0
  957. package/dist/modes/interactive/theme/theme-json.d.ts.map +1 -0
  958. package/dist/modes/interactive/theme/theme-json.js +132 -0
  959. package/dist/modes/interactive/theme/theme-json.js.map +1 -0
  960. package/dist/modes/interactive/theme/theme-schema.json +24 -3
  961. package/dist/modes/interactive/theme/theme.d.ts +80 -42
  962. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  963. package/dist/modes/interactive/theme/theme.js +274 -417
  964. package/dist/modes/interactive/theme/theme.js.map +1 -1
  965. package/dist/modes/interactive/tui-renderer.d.ts +22 -0
  966. package/dist/modes/interactive/tui-renderer.d.ts.map +1 -0
  967. package/dist/modes/interactive/tui-renderer.js +67 -0
  968. package/dist/modes/interactive/tui-renderer.js.map +1 -0
  969. package/dist/modes/json-event.d.ts +34 -0
  970. package/dist/modes/json-event.d.ts.map +1 -0
  971. package/dist/modes/json-event.js +29 -0
  972. package/dist/modes/json-event.js.map +1 -0
  973. package/dist/modes/print-mode.d.ts +1 -1
  974. package/dist/modes/print-mode.d.ts.map +1 -1
  975. package/dist/modes/print-mode.js +12 -2
  976. package/dist/modes/print-mode.js.map +1 -1
  977. package/dist/modes/rpc/rpc-client.d.ts +17 -9
  978. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  979. package/dist/modes/rpc/rpc-client.js +27 -15
  980. package/dist/modes/rpc/rpc-client.js.map +1 -1
  981. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  982. package/dist/modes/rpc/rpc-mode.js +179 -19
  983. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  984. package/dist/modes/rpc/rpc-types.d.ts +90 -2
  985. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  986. package/dist/modes/rpc/rpc-types.js.map +1 -1
  987. package/dist/package-manager-cli.d.ts +1 -0
  988. package/dist/package-manager-cli.d.ts.map +1 -1
  989. package/dist/package-manager-cli.js +217 -63
  990. package/dist/package-manager-cli.js.map +1 -1
  991. package/dist/prompts/commands/atomic-commit.md +1 -12
  992. package/dist/prompts/commands/brainstorm.md +12 -15
  993. package/dist/prompts/commands/create-verification-skill.md +108 -0
  994. package/dist/prompts/commands/discuss-phase.md +3 -14
  995. package/dist/prompts/commands/execute-phase.md +3 -11
  996. package/dist/prompts/commands/fix.md +41 -18
  997. package/dist/prompts/commands/grill.md +66 -0
  998. package/dist/prompts/commands/init-project.md +5 -15
  999. package/dist/prompts/commands/map-codebase.md +1 -13
  1000. package/dist/prompts/commands/new-project.md +5 -15
  1001. package/dist/prompts/commands/next-milestone.md +1 -13
  1002. package/dist/prompts/commands/orchestrate.md +1 -1
  1003. package/dist/prompts/commands/pause-work.md +1 -13
  1004. package/dist/prompts/commands/plan-phase.md +3 -11
  1005. package/dist/prompts/commands/progress.md +0 -13
  1006. package/dist/prompts/commands/quick.md +3 -11
  1007. package/dist/prompts/commands/resolve-conflicts.md +71 -0
  1008. package/dist/prompts/commands/resume-work.md +0 -13
  1009. package/dist/prompts/commands/review.md +6 -13
  1010. package/dist/prompts/commands/triage.md +159 -0
  1011. package/dist/prompts/commands/verify-work.md +5 -14
  1012. package/dist/prompts/commands/why.md +139 -0
  1013. package/dist/rpc-entry.js +1 -0
  1014. package/dist/rpc-entry.js.map +1 -1
  1015. package/dist/skills/atomic-reasoning/SKILL.md +115 -0
  1016. package/dist/skills/blast-radius/SKILL.md +56 -0
  1017. package/dist/skills/epistemics/SKILL.md +99 -0
  1018. package/dist/skills/explainers/SKILL.md +65 -0
  1019. package/dist/skills/hexagon-animation/SKILL.md +49 -0
  1020. package/dist/skills/hexagon-animation/generate.mjs +81 -0
  1021. package/dist/skills/hexagon-animation/template.html +361 -0
  1022. package/dist/skills/typescript-discipline/SKILL.md +50 -0
  1023. package/dist/skills/typescript-discipline/references/patterns.md +294 -0
  1024. package/dist/skills/unslop/SKILL.md +119 -0
  1025. package/dist/utils/abort.d.ts +5 -0
  1026. package/dist/utils/abort.d.ts.map +1 -0
  1027. package/dist/utils/abort.js +48 -0
  1028. package/dist/utils/abort.js.map +1 -0
  1029. package/dist/utils/canonical-path.d.ts +28 -0
  1030. package/dist/utils/canonical-path.d.ts.map +1 -0
  1031. package/dist/utils/canonical-path.js +90 -0
  1032. package/dist/utils/canonical-path.js.map +1 -0
  1033. package/dist/utils/changelog.js +1 -1
  1034. package/dist/utils/changelog.js.map +1 -1
  1035. package/dist/utils/child-process.d.ts +13 -2
  1036. package/dist/utils/child-process.d.ts.map +1 -1
  1037. package/dist/utils/child-process.js +26 -9
  1038. package/dist/utils/child-process.js.map +1 -1
  1039. package/dist/utils/clipboard-command.d.ts +7 -0
  1040. package/dist/utils/clipboard-command.d.ts.map +1 -0
  1041. package/dist/utils/clipboard-command.js +45 -0
  1042. package/dist/utils/clipboard-command.js.map +1 -0
  1043. package/dist/utils/clipboard-image.d.ts.map +1 -1
  1044. package/dist/utils/clipboard-image.js +60 -91
  1045. package/dist/utils/clipboard-image.js.map +1 -1
  1046. package/dist/utils/clipboard.d.ts +3 -1
  1047. package/dist/utils/clipboard.d.ts.map +1 -1
  1048. package/dist/utils/clipboard.js +123 -108
  1049. package/dist/utils/clipboard.js.map +1 -1
  1050. package/dist/utils/draht-user-agent.d.ts +2 -0
  1051. package/dist/utils/draht-user-agent.d.ts.map +1 -0
  1052. package/dist/utils/draht-user-agent.js +5 -0
  1053. package/dist/utils/draht-user-agent.js.map +1 -0
  1054. package/dist/utils/exif-orientation.d.ts +2 -1
  1055. package/dist/utils/exif-orientation.d.ts.map +1 -1
  1056. package/dist/utils/exif-orientation.js +2 -3
  1057. package/dist/utils/exif-orientation.js.map +1 -1
  1058. package/dist/utils/frontmatter.d.ts.map +1 -1
  1059. package/dist/utils/frontmatter.js +2 -1
  1060. package/dist/utils/frontmatter.js.map +1 -1
  1061. package/dist/utils/management-http.d.ts +25 -0
  1062. package/dist/utils/management-http.d.ts.map +1 -0
  1063. package/dist/utils/management-http.js +54 -0
  1064. package/dist/utils/management-http.js.map +1 -0
  1065. package/dist/utils/mime.js +1 -1
  1066. package/dist/utils/mime.js.map +1 -1
  1067. package/dist/utils/paths.d.ts +6 -10
  1068. package/dist/utils/paths.d.ts.map +1 -1
  1069. package/dist/utils/paths.js +23 -14
  1070. package/dist/utils/paths.js.map +1 -1
  1071. package/dist/utils/photon.d.ts +2 -1
  1072. package/dist/utils/photon.d.ts.map +1 -1
  1073. package/dist/utils/photon.js.map +1 -1
  1074. package/dist/utils/shell.d.ts +4 -3
  1075. package/dist/utils/shell.d.ts.map +1 -1
  1076. package/dist/utils/shell.js +26 -39
  1077. package/dist/utils/shell.js.map +1 -1
  1078. package/dist/utils/syntax-highlight.d.ts +1 -0
  1079. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  1080. package/dist/utils/syntax-highlight.js +62 -1
  1081. package/dist/utils/syntax-highlight.js.map +1 -1
  1082. package/dist/utils/text.d.ts +8 -0
  1083. package/dist/utils/text.d.ts.map +1 -0
  1084. package/dist/utils/text.js +9 -0
  1085. package/dist/utils/text.js.map +1 -0
  1086. package/dist/utils/tool-result-images.d.ts +21 -0
  1087. package/dist/utils/tool-result-images.d.ts.map +1 -0
  1088. package/dist/utils/tool-result-images.js +48 -0
  1089. package/dist/utils/tool-result-images.js.map +1 -0
  1090. package/dist/utils/tools-manager.d.ts +11 -1
  1091. package/dist/utils/tools-manager.d.ts.map +1 -1
  1092. package/dist/utils/tools-manager.js +56 -41
  1093. package/dist/utils/tools-manager.js.map +1 -1
  1094. package/dist/utils/version-check.d.ts +4 -1
  1095. package/dist/utils/version-check.d.ts.map +1 -1
  1096. package/dist/utils/version-check.js +30 -9
  1097. package/dist/utils/version-check.js.map +1 -1
  1098. package/dist/utils/wsl.d.ts +3 -0
  1099. package/dist/utils/wsl.d.ts.map +1 -0
  1100. package/dist/utils/wsl.js +15 -0
  1101. package/dist/utils/wsl.js.map +1 -0
  1102. package/dist/utils/zip.d.ts +7 -0
  1103. package/dist/utils/zip.d.ts.map +1 -0
  1104. package/dist/utils/zip.js +60 -0
  1105. package/dist/utils/zip.js.map +1 -0
  1106. package/docs/attachable-sessions.md +79 -0
  1107. package/docs/cli-integration.md +106 -0
  1108. package/docs/cli.md +374 -0
  1109. package/docs/compaction.md +107 -45
  1110. package/docs/configuration.md +47 -0
  1111. package/docs/containerization.md +100 -66
  1112. package/docs/custom-provider.md +109 -707
  1113. package/docs/docs.json +155 -95
  1114. package/docs/duet.md +42 -0
  1115. package/docs/environment-variables.md +30 -17
  1116. package/docs/extensions.md +169 -2811
  1117. package/docs/how-pi-works.md +53 -0
  1118. package/docs/images/interactive-mode.png +0 -0
  1119. package/docs/index.md +25 -69
  1120. package/docs/json.md +198 -57
  1121. package/docs/keybindings.md +89 -92
  1122. package/docs/llama-cpp.md +23 -8
  1123. package/docs/mcp.md +231 -0
  1124. package/docs/message-types.md +261 -0
  1125. package/docs/models.md +94 -478
  1126. package/docs/packages.md +68 -164
  1127. package/docs/prompt-templates.md +31 -68
  1128. package/docs/providers.md +118 -215
  1129. package/docs/quickstart.md +56 -109
  1130. package/docs/rpc-commands.md +860 -0
  1131. package/docs/rpc-extension-ui.md +200 -0
  1132. package/docs/rpc.md +186 -1494
  1133. package/docs/sdk.md +79 -1127
  1134. package/docs/security.md +77 -33
  1135. package/docs/session-format.md +98 -222
  1136. package/docs/sessions.md +36 -113
  1137. package/docs/settings.md +125 -251
  1138. package/docs/shell-aliases.md +85 -5
  1139. package/docs/skills.md +52 -188
  1140. package/docs/slash-commands.md +61 -0
  1141. package/docs/terminal-setup.md +132 -61
  1142. package/docs/termux.md +74 -84
  1143. package/docs/themes.md +91 -252
  1144. package/docs/tmux.md +31 -39
  1145. package/docs/tui.md +74 -891
  1146. package/docs/usage.md +54 -255
  1147. package/docs/virtual-models.md +114 -0
  1148. package/docs/windows.md +57 -7
  1149. package/examples/extensions/antigravity-image-gen.ts +9 -9
  1150. package/examples/extensions/bash-spawn-hook.ts +1 -1
  1151. package/examples/extensions/border-status-editor.ts +1 -1
  1152. package/examples/extensions/built-in-tool-renderer.ts +16 -40
  1153. package/examples/extensions/custom-compaction.ts +1 -16
  1154. package/examples/extensions/custom-provider-anthropic/index.ts +20 -13
  1155. package/examples/extensions/custom-provider-gitlab-duo/index.ts +4 -3
  1156. package/examples/extensions/custom-provider-gitlab-duo/test.ts +5 -5
  1157. package/examples/extensions/debug-provider.ts +90 -0
  1158. package/examples/extensions/doom-overlay/wad-finder.ts +7 -3
  1159. package/examples/extensions/dynamic-resources/dynamic.json +3 -1
  1160. package/examples/extensions/git-checkpoint.ts +2 -2
  1161. package/examples/extensions/handoff.ts +2 -11
  1162. package/examples/extensions/jev-router.ts +113 -0
  1163. package/examples/extensions/minimal-mode.ts +24 -96
  1164. package/examples/extensions/notify.ts +3 -1
  1165. package/examples/extensions/overlay-qa-tests.ts +3 -3
  1166. package/examples/extensions/prompt-customizer.ts +19 -67
  1167. package/examples/extensions/qna.ts +3 -7
  1168. package/examples/extensions/subagent/agents.ts +40 -9
  1169. package/examples/extensions/subagent/index.ts +27 -4
  1170. package/examples/extensions/summarize.ts +7 -18
  1171. package/examples/extensions/titlebar-spinner.ts +1 -1
  1172. package/examples/rpc-client.ts +35 -0
  1173. package/examples/rpc-extension-ui.ts +38 -9
  1174. package/examples/sdk/02-custom-model.ts +1 -2
  1175. package/examples/sdk/06-extensions.ts +1 -1
  1176. package/examples/sdk/09-api-keys-and-oauth.ts +1 -1
  1177. package/examples/sdk/12-full-control.ts +1 -1
  1178. package/examples/sdk/14-codemode-mcp.ts +61 -0
  1179. package/hooks/gsd/draht-quality-gate.js +3 -3
  1180. package/package.json +28 -32
  1181. package/prompts/commands/atomic-commit.md +1 -12
  1182. package/prompts/commands/brainstorm.md +12 -15
  1183. package/prompts/commands/create-verification-skill.md +108 -0
  1184. package/prompts/commands/discuss-phase.md +3 -14
  1185. package/prompts/commands/execute-phase.md +3 -11
  1186. package/prompts/commands/fix.md +41 -18
  1187. package/prompts/commands/grill.md +66 -0
  1188. package/prompts/commands/init-project.md +5 -15
  1189. package/prompts/commands/map-codebase.md +1 -13
  1190. package/prompts/commands/new-project.md +5 -15
  1191. package/prompts/commands/next-milestone.md +1 -13
  1192. package/prompts/commands/orchestrate.md +1 -1
  1193. package/prompts/commands/pause-work.md +1 -13
  1194. package/prompts/commands/plan-phase.md +3 -11
  1195. package/prompts/commands/progress.md +0 -13
  1196. package/prompts/commands/quick.md +3 -11
  1197. package/prompts/commands/resolve-conflicts.md +71 -0
  1198. package/prompts/commands/resume-work.md +0 -13
  1199. package/prompts/commands/review.md +6 -13
  1200. package/prompts/commands/triage.md +159 -0
  1201. package/prompts/commands/verify-work.md +5 -14
  1202. package/prompts/commands/why.md +139 -0
  1203. package/skills/atomic-reasoning/SKILL.md +115 -0
  1204. package/skills/blast-radius/SKILL.md +56 -0
  1205. package/skills/epistemics/SKILL.md +99 -0
  1206. package/skills/explainers/SKILL.md +65 -0
  1207. package/skills/hexagon-animation/SKILL.md +49 -0
  1208. package/skills/hexagon-animation/generate.mjs +81 -0
  1209. package/skills/hexagon-animation/template.html +361 -0
  1210. package/skills/typescript-discipline/SKILL.md +50 -0
  1211. package/skills/typescript-discipline/references/patterns.md +294 -0
  1212. package/skills/unslop/SKILL.md +119 -0
  1213. package/dist/prompts/agents/build.md +0 -86
  1214. package/dist/prompts/agents/plan.md +0 -79
  1215. package/dist/prompts/agents/verify.md +0 -69
  1216. package/dist/utils/clipboard-native.d.ts +0 -11
  1217. package/dist/utils/clipboard-native.d.ts.map +0 -1
  1218. package/dist/utils/clipboard-native.js +0 -20
  1219. package/dist/utils/clipboard-native.js.map +0 -1
  1220. package/dist/utils/pi-user-agent.d.ts +0 -2
  1221. package/dist/utils/pi-user-agent.d.ts.map +0 -1
  1222. package/dist/utils/pi-user-agent.js +0 -5
  1223. package/dist/utils/pi-user-agent.js.map +0 -1
  1224. package/docs/development.md +0 -71
  1225. package/docs/tree.md +0 -231
  1226. package/examples/extensions/kimi-deferred-tools.ts +0 -61
  1227. package/prompts/agents/build.md +0 -86
  1228. package/prompts/agents/plan.md +0 -79
  1229. package/prompts/agents/verify.md +0 -69
@@ -12,32 +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";
38
+ import { createRelayUIContext, noOpRelayBaseUIContext, } from "./permission-relay/index.js";
33
39
  import { expandPromptTemplate } from "./prompt-templates.js";
34
- import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
35
- import { createSyntheticSourceInfo } from "./source-info.js";
36
- 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";
37
45
  import { createLocalBashOperations } from "./tools/bash.js";
38
46
  import { createAllToolDefinitions } from "./tools/index.js";
39
47
  import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
40
- 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";
41
50
  /**
42
51
  * Parse a skill block from message text.
43
52
  * Returns null if the text doesn't contain a skill block.
@@ -71,107 +80,111 @@ function estimateMessagesTokens(messages) {
71
80
  // ============================================================================
72
81
  // Constants
73
82
  // ============================================================================
74
- /** Standard thinking levels */
75
- const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
83
+ /**
84
+ * Which SURFACE a dialog answered locally belongs to, per binding mode.
85
+ *
86
+ * Total over {@link ExtensionMode} on purpose — a `Record`, not a lookup with a fallback — because
87
+ * the fallback is what the defect was: the relay decorator hardcoded `tui`, so an answer typed into
88
+ * the RPC surface, and a SIGTERM that cancelled a pending dialog, were both recorded in the
89
+ * session's durable log as a human sitting at a terminal that does not exist.
90
+ *
91
+ * `json` and `print` bind no UI context at all (see `runPrintMode`), so the decorator wraps the
92
+ * barrel's no-op with `baseIsLive: false` and nothing is ever answered locally in them. `system` is
93
+ * therefore both unreachable and the truthful value: if such a mode somehow ended an ask, no person
94
+ * acted. It is deliberately not `tui`.
95
+ */
96
+ const LOCAL_SURFACE_BY_MODE = Object.freeze({
97
+ tui: "tui",
98
+ rpc: "rpc",
99
+ json: "system",
100
+ print: "system",
101
+ });
76
102
  // ============================================================================
77
103
  // AgentSession Class
78
104
  // ============================================================================
79
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;
80
187
  constructor(config) {
81
- this._eventListeners = [];
82
- this._isAgentRunActive = false;
83
- /** Tracks pending steering messages for UI display. Removed when delivered. */
84
- this._steeringMessages = [];
85
- /** Tracks pending follow-up messages for UI display. Removed when delivered. */
86
- this._followUpMessages = [];
87
- /** Messages queued to be included with the next user prompt as context ("asides"). */
88
- this._pendingNextTurnMessages = [];
89
- // Compaction state
90
- this._compactionAbortController = undefined;
91
- this._autoCompactionAbortController = undefined;
92
- this._overflowRecoveryAttempted = false;
93
- // Branch summarization state
94
- this._branchSummaryAbortController = undefined;
95
- // Retry state
96
- this._retryAbortController = undefined;
97
- this._retryAttempt = 0;
98
- // Bash execution state
99
- this._bashAbortControllers = new Set();
100
- this._pendingBashMessages = [];
101
- this._turnIndex = 0;
102
- this._baseToolDefinitions = new Map();
103
- this._extensionMode = "print";
104
- // Tool registry for extension getTools/setTools
105
- this._toolRegistry = new Map();
106
- this._toolDefinitions = new Map();
107
- this._toolPromptSnippets = new Map();
108
- this._toolPromptGuidelines = new Map();
109
- // Base system prompt (without extension appends) - used to apply fresh appends each turn
110
- this._baseSystemPrompt = "";
111
- // Track last assistant message for auto-compaction check
112
- this._lastAssistantMessage = undefined;
113
- /** Internal handler for agent events - shared by subscribe and reconnect */
114
- this._handleAgentEvent = async (event) => {
115
- // When a user message starts, check if it's from either queue and remove it BEFORE emitting
116
- // This ensures the UI sees the updated queue state
117
- if (event.type === "message_start" && event.message.role === "user") {
118
- this._overflowRecoveryAttempted = false;
119
- const messageText = contentText(event.message.content, "");
120
- if (messageText) {
121
- // Check steering queue first
122
- const steeringIndex = this._steeringMessages.indexOf(messageText);
123
- if (steeringIndex !== -1) {
124
- this._steeringMessages.splice(steeringIndex, 1);
125
- this._emitQueueUpdate();
126
- }
127
- else {
128
- // Check follow-up queue
129
- const followUpIndex = this._followUpMessages.indexOf(messageText);
130
- if (followUpIndex !== -1) {
131
- this._followUpMessages.splice(followUpIndex, 1);
132
- this._emitQueueUpdate();
133
- }
134
- }
135
- }
136
- }
137
- // Emit to extensions first
138
- await this._emitExtensionEvent(event);
139
- // Notify all listeners
140
- this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
141
- // Handle session persistence
142
- if (event.type === "message_end") {
143
- // Check if this is a custom message from extensions
144
- if (event.message.role === "custom") {
145
- // Persist as CustomMessageEntry
146
- this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
147
- }
148
- else if (event.message.role === "user" ||
149
- event.message.role === "assistant" ||
150
- event.message.role === "toolResult") {
151
- // Regular LLM message - persist as SessionMessageEntry
152
- this.sessionManager.appendMessage(event.message);
153
- }
154
- // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
155
- // Track assistant message for auto-compaction (checked on agent_end)
156
- if (event.message.role === "assistant") {
157
- this._lastAssistantMessage = event.message;
158
- const assistantMsg = event.message;
159
- if (assistantMsg.stopReason !== "error") {
160
- this._overflowRecoveryAttempted = false;
161
- }
162
- // Reset retry counter immediately on successful assistant response
163
- // This prevents accumulation across multiple LLM calls within a turn
164
- if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
165
- this._emit({
166
- type: "auto_retry_end",
167
- success: true,
168
- attempt: this._retryAttempt,
169
- });
170
- this._retryAttempt = 0;
171
- }
172
- }
173
- }
174
- };
175
188
  this.agent = config.agent;
176
189
  this.sessionManager = config.sessionManager;
177
190
  this.settingsManager = config.settingsManager;
@@ -180,8 +193,13 @@ export class AgentSession {
180
193
  this._customTools = config.customTools ?? [];
181
194
  this._cwd = config.cwd;
182
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
+ }
183
200
  this._extensionRunnerRef = config.extensionRunnerRef;
184
201
  this._initialActiveToolNames = config.initialActiveToolNames;
202
+ this._usesDefaultTools = config.usesDefaultTools ?? false;
185
203
  this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
186
204
  this._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;
187
205
  this._baseToolsOverride = config.baseToolsOverride;
@@ -191,18 +209,24 @@ export class AgentSession {
191
209
  this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
192
210
  this._installAgentToolHooks();
193
211
  this._installAgentNextTurnRefresh();
212
+ this._installAgentRequestProjection();
213
+ this._installAgentBoundaryHooks();
214
+ this._installHiddenDeclarationsProjection();
215
+ this._installAgentForcedPromptProjection();
194
216
  this._buildRuntime({
195
217
  activeToolNames: this._initialActiveToolNames,
196
218
  includeAllExtensionTools: true,
197
219
  });
220
+ if (this._initialActiveToolNames === undefined)
221
+ this._restoreToolsFromTranscript();
198
222
  }
199
223
  get modelRuntime() {
200
224
  return this._modelRuntime;
201
225
  }
202
- async _getRequiredRequestAuth(model) {
226
+ async _getRequiredRequestAuth(model, signal) {
203
227
  let result;
204
228
  try {
205
- result = await this._modelRuntime.getAuth(model);
229
+ result = await this._modelRuntime.getAuth(model, { signal });
206
230
  }
207
231
  catch (error) {
208
232
  const cause = error instanceof Error ? error.cause : undefined;
@@ -212,7 +236,9 @@ export class AgentSession {
212
236
  throw error;
213
237
  }
214
238
  if (result && (result.auth.apiKey || result.auth.headers)) {
239
+ const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
215
240
  return {
241
+ model: requestModel,
216
242
  apiKey: result.auth.apiKey,
217
243
  headers: withoutDeletedHeaders(result.auth.headers),
218
244
  env: result.env,
@@ -226,20 +252,71 @@ export class AgentSession {
226
252
  }
227
253
  throw new Error(formatNoApiKeyFoundMessage(model.provider));
228
254
  }
229
- 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 };
230
264
  if (this.agent.streamFunction === streamSimple) {
231
- return this._getRequiredRequestAuth(model);
265
+ return { ...(await this._getRequiredRequestAuth(model, signal)), thinkingLevel };
232
266
  }
233
267
  try {
234
- const result = await this._modelRuntime.getAuth(model);
235
- return result
236
- ? { apiKey: result.auth.apiKey, headers: withoutDeletedHeaders(result.auth.headers), env: result.env }
237
- : {};
268
+ const result = await this._modelRuntime.getAuth(model, { signal });
269
+ if (!result)
270
+ return { model, thinkingLevel };
271
+ const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
272
+ return {
273
+ model: requestModel,
274
+ apiKey: result.auth.apiKey,
275
+ headers: withoutDeletedHeaders(result.auth.headers),
276
+ env: result.env,
277
+ thinkingLevel,
278
+ };
238
279
  }
239
- catch {
240
- return {};
280
+ catch (error) {
281
+ if (signal?.aborted)
282
+ throw error;
283
+ return { model, thinkingLevel };
241
284
  }
242
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
+ }
243
320
  /**
244
321
  * Install tool hooks once on the Agent instance.
245
322
  *
@@ -249,50 +326,216 @@ export class AgentSession {
249
326
  * happens here instead of in wrappers.
250
327
  */
251
328
  _installAgentToolHooks() {
252
- this.agent.beforeToolCall = async ({ toolCall, args }) => {
253
- const runner = this._extensionRunner;
254
- if (!runner.hasHandlers("tool_call")) {
255
- return undefined;
256
- }
257
- try {
258
- return await runner.emitToolCall({
259
- type: "tool_call",
260
- toolName: toolCall.name,
261
- toolCallId: toolCall.id,
262
- input: args,
263
- });
264
- }
265
- catch (err) {
266
- if (err instanceof Error) {
267
- throw err;
268
- }
269
- throw new Error(`Extension failed, blocking execution: ${String(err)}`);
270
- }
271
- };
272
- this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
273
- const runner = this._extensionRunner;
274
- if (!runner.hasHandlers("tool_result")) {
275
- 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;
276
350
  }
277
- 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({
278
359
  type: "tool_result",
279
360
  toolName: toolCall.name,
280
361
  toolCallId: toolCall.id,
362
+ ...(parentToolCallId ? { parentToolCallId } : {}),
281
363
  input: args,
282
364
  content: result.content,
283
365
  details: result.details,
366
+ ...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent }),
284
367
  isError,
285
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,
286
478
  });
287
- if (!hookResult) {
288
- 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 });
289
484
  }
290
- return {
291
- content: hookResult.content,
292
- details: hookResult.details,
293
- isError: hookResult.isError ?? isError,
294
- usage: hookResult.usage,
295
- };
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;
296
539
  };
297
540
  }
298
541
  _installAgentNextTurnRefresh() {
@@ -301,15 +544,28 @@ export class AgentSession {
301
544
  ? async (_turn, signal) => await this.agent.prepareNextTurn?.(signal)
302
545
  : undefined);
303
546
  this.agent.prepareNextTurnWithContext = async (turn, signal) => {
304
- const previousSnapshot = await previousPrepareNextTurnWithContext?.(turn, signal);
305
- 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;
306
560
  return {
307
561
  ...previousSnapshot,
308
562
  context: {
309
- ...previousContext,
310
- systemPrompt: this._systemPromptOverride ?? this._baseSystemPrompt,
563
+ ...nextContext,
311
564
  tools: this.agent.state.tools.slice(),
312
565
  },
566
+ messages: updateMessage
567
+ ? [...(previousSnapshot?.messages ?? []), updateMessage]
568
+ : previousSnapshot?.messages,
313
569
  model: this.agent.state.model,
314
570
  thinkingLevel: this.agent.state.thinkingLevel,
315
571
  };
@@ -318,6 +574,84 @@ export class AgentSession {
318
574
  // =========================================================================
319
575
  // Event Subscription
320
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
+ }
321
655
  /** Emit an event to all listeners */
322
656
  _emit(event) {
323
657
  for (const l of this._eventListeners) {
@@ -331,6 +665,11 @@ export class AgentSession {
331
665
  followUp: [...this._followUpMessages],
332
666
  });
333
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
+ }
334
673
  _getIdleWaitPromise() {
335
674
  if (!this._idleWaitPromise) {
336
675
  this._idleWaitPromise = new Promise((resolve) => {
@@ -340,7 +679,7 @@ export class AgentSession {
340
679
  return this._idleWaitPromise;
341
680
  }
342
681
  _resolveIdleWaitIfIdle() {
343
- if (this._isAgentRunActive || !this._resolveIdleWait) {
682
+ if (!this.isIdle || !this._resolveIdleWait) {
344
683
  return;
345
684
  }
346
685
  const resolve = this._resolveIdleWait;
@@ -349,16 +688,120 @@ export class AgentSession {
349
688
  resolve();
350
689
  }
351
690
  async _emitAgentSettled() {
691
+ this._cacheWarmer?.onAgentSettled();
352
692
  this._isAgentRunActive = false;
693
+ this._isEmittingAgentSettled = true;
353
694
  try {
354
695
  await this._extensionRunner.emit({ type: "agent_settled" });
355
696
  this._emit({ type: "agent_settled" });
356
697
  }
357
698
  finally {
358
- this._resolveIdleWaitIfIdle();
699
+ this._isEmittingAgentSettled = false;
359
700
  }
360
- }
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
+ };
361
802
  _willRetryAfterAgentEnd(event) {
803
+ if (this._agentRunAbortRequested)
804
+ return false;
362
805
  const settings = this.settingsManager.getRetrySettings();
363
806
  if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
364
807
  return false;
@@ -371,6 +814,47 @@ export class AgentSession {
371
814
  }
372
815
  return false;
373
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
+ }
374
858
  /** Find the last assistant message in agent state (including aborted ones) */
375
859
  _findLastAssistantMessage() {
376
860
  const messages = this.agent.state.messages;
@@ -414,13 +898,9 @@ export class AgentSession {
414
898
  await this._extensionRunner.emit(extensionEvent);
415
899
  }
416
900
  else if (event.type === "turn_end") {
417
- const extensionEvent = {
418
- type: "turn_end",
419
- turnIndex: this._turnIndex,
420
- message: event.message,
421
- toolResults: event.toolResults,
422
- };
423
- 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
+ }
424
904
  this._turnIndex++;
425
905
  }
426
906
  else if (event.type === "message_start") {
@@ -502,26 +982,13 @@ export class AgentSession {
502
982
  }
503
983
  };
504
984
  }
505
- /**
506
- * Temporarily disconnect from agent events.
507
- * User listeners are preserved and will receive events again after resubscribe().
508
- * Used internally during operations that need to pause event processing.
509
- */
985
+ /** Disconnect from agent events during disposal. */
510
986
  _disconnectFromAgent() {
511
987
  if (this._unsubscribeAgent) {
512
988
  this._unsubscribeAgent();
513
989
  this._unsubscribeAgent = undefined;
514
990
  }
515
991
  }
516
- /**
517
- * Reconnect to agent events after _disconnectFromAgent().
518
- * Preserves all existing listeners.
519
- */
520
- _reconnectToAgent() {
521
- if (this._unsubscribeAgent)
522
- return; // Already connected
523
- this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
524
- }
525
992
  /**
526
993
  * Remove all listeners and disconnect from agent.
527
994
  * Call this when completely done with the session.
@@ -540,15 +1007,32 @@ export class AgentSession {
540
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().");
541
1008
  this._disconnectFromAgent();
542
1009
  this._eventListeners = [];
1010
+ if (this._cacheWarmer) {
1011
+ this._cacheWarmer.onWarmed = undefined;
1012
+ this._cacheWarmer.cancel();
1013
+ }
543
1014
  cleanupSessionResources(this.sessionId);
544
1015
  }
545
1016
  // =========================================================================
546
1017
  // Read-only State Access
547
1018
  // =========================================================================
1019
+ /** Refresh the public finalized transcript from the canonical session projection. */
1020
+ refreshContext() {
1021
+ this._refreshFinalizedContext();
1022
+ }
548
1023
  /** Full agent state */
549
1024
  get state() {
550
1025
  return this.agent.state;
551
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
+ }
552
1036
  /** Current model (may be undefined if not yet selected) */
553
1037
  get model() {
554
1038
  return this.agent.state.model;
@@ -557,29 +1041,41 @@ export class AgentSession {
557
1041
  get thinkingLevel() {
558
1042
  return this.agent.state.thinkingLevel;
559
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
+ }
560
1052
  /** Whether the session is currently processing an agent run or post-run continuation. */
561
1053
  get isStreaming() {
562
1054
  return this._isAgentRunActive;
563
1055
  }
564
- /** 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. */
565
1057
  get isIdle() {
566
- return !this._isAgentRunActive;
1058
+ return !this._isAgentRunActive && !this.isCompacting;
567
1059
  }
568
- /** Current effective system prompt (includes any per-turn extension modifications) */
1060
+ /** Current effective system prompt, including changes not yet sent to the model. */
569
1061
  get systemPrompt() {
570
- return this.agent.state.systemPrompt;
1062
+ return buildSystemPrompt(this._runSystemPromptOptions ?? this._baseSystemPromptOptions);
571
1063
  }
572
1064
  /** Current retry attempt (0 if not retrying) */
573
1065
  get retryAttempt() {
574
1066
  return this._retryAttempt;
575
1067
  }
576
1068
  /**
577
- * Get the names of currently active tools.
578
- * 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.
579
1071
  */
580
1072
  getActiveToolNames() {
581
1073
  return this.agent.state.tools.map((t) => t.name);
582
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
+ }
583
1079
  /**
584
1080
  * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
585
1081
  */
@@ -589,6 +1085,9 @@ export class AgentSession {
589
1085
  description: definition.description,
590
1086
  parameters: definition.parameters,
591
1087
  promptGuidelines: definition.promptGuidelines,
1088
+ exposure: this._getToolExposure(definition.name),
1089
+ ...(definition.namespace ? { namespace: definition.namespace } : {}),
1090
+ ...(definition.annotations ? { annotations: { ...definition.annotations } } : {}),
592
1091
  sourceInfo,
593
1092
  }));
594
1093
  }
@@ -597,24 +1096,79 @@ export class AgentSession {
597
1096
  }
598
1097
  /**
599
1098
  * Set active tools by name.
600
- * 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.
601
1100
  * Also rebuilds the system prompt to reflect the new tool set.
602
1101
  * Changes take effect on the next agent turn.
603
1102
  */
604
1103
  setActiveToolsByName(toolNames) {
605
- const tools = [];
606
- const validToolNames = [];
607
- 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) => {
608
1128
  const tool = this._toolRegistry.get(name);
609
- if (tool) {
610
- tools.push(tool);
611
- 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
+ }
612
1163
  }
1164
+ declared = tools.map((tool) => {
1165
+ const description = descriptions.get(tool.name);
1166
+ return description === undefined ? tool : { ...tool, description };
1167
+ });
613
1168
  }
614
- this.agent.state.tools = tools;
615
- // Rebuild base system prompt with new tool set
616
- this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
617
- this.agent.state.systemPrompt = this._systemPromptOverride ?? this._baseSystemPrompt;
1169
+ this._hiddenDeclarations = hidden;
1170
+ this.agent.state.tools = declared;
1171
+ return declared;
618
1172
  }
619
1173
  /** Whether compaction or branch summarization is currently running */
620
1174
  get isCompacting() {
@@ -683,23 +1237,18 @@ export class AgentSession {
683
1237
  _rebuildSystemPrompt(toolNames) {
684
1238
  const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
685
1239
  const toolSnippets = {};
686
- const promptGuidelines = [];
687
- for (const name of validToolNames) {
1240
+ for (const name of this._toolRegistry.keys()) {
688
1241
  const snippet = this._toolPromptSnippets.get(name);
689
- 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))
690
1244
  toolSnippets[name] = snippet;
691
- }
692
- const toolGuidelines = this._toolPromptGuidelines.get(name);
693
- if (toolGuidelines) {
694
- promptGuidelines.push(...toolGuidelines);
695
- }
696
1245
  }
697
1246
  const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
698
1247
  const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
699
- const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
1248
+ const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : "";
700
1249
  const loadedSkills = this._resourceLoader.getSkills().skills;
701
1250
  const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
702
- this._baseSystemPromptOptions = {
1251
+ this._baseSystemPromptOptions = normalizeBuildSystemPromptOptions({
703
1252
  cwd: this._cwd,
704
1253
  skills: loadedSkills,
705
1254
  contextFiles: loadedContextFiles,
@@ -707,51 +1256,217 @@ export class AgentSession {
707
1256
  appendSystemPrompt,
708
1257
  selectedTools: validToolNames,
709
1258
  toolSnippets,
710
- 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")];
711
1330
  };
712
- 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));
713
1342
  }
714
1343
  // =========================================================================
715
1344
  // Prompting
716
1345
  // =========================================================================
717
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();
718
1351
  this._isAgentRunActive = true;
719
1352
  try {
720
1353
  await this.agent.prompt(messages);
721
- 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;
722
1365
  await this.agent.continue();
723
1366
  }
724
1367
  }
725
1368
  finally {
726
- this._systemPromptOverride = undefined;
1369
+ if (this._agentRunAbortRequested)
1370
+ this._finishCancelledRetry();
1371
+ this._failedResponse = undefined;
1372
+ this._runSystemPromptOptions = undefined;
727
1373
  this._flushPendingBashMessages();
1374
+ this._flushPendingCustomMessages();
728
1375
  await this._emitAgentSettled();
729
1376
  }
730
1377
  }
731
1378
  async _handlePostAgentRun() {
732
- const msg = this._lastAssistantMessage;
1379
+ const message = this._lastAssistantMessage;
1380
+ const toolResults = this._lastAssistantToolResults;
733
1381
  this._lastAssistantMessage = undefined;
734
- if (!msg) {
1382
+ this._lastAssistantToolResults = [];
1383
+ if (this._agentRunAbortRequested) {
1384
+ this._finishCancelledRetry();
735
1385
  return false;
736
1386
  }
737
- if (this._isRetryableError(msg) && (await this._prepareRetry(msg))) {
738
- 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;
739
1398
  }
740
- if (msg.stopReason === "error" && this._retryAttempt > 0) {
1399
+ if (message.stopReason === "error" && this._retryAttempt > 0) {
741
1400
  this._emit({
742
1401
  type: "auto_retry_end",
743
1402
  success: false,
744
1403
  attempt: this._retryAttempt,
745
- finalError: msg.errorMessage,
1404
+ finalError: message.errorMessage,
746
1405
  });
747
1406
  this._retryAttempt = 0;
748
1407
  }
749
- if (await this._checkCompaction(msg)) {
750
- return true;
1408
+ if (await this._checkCompaction(message, true, toolResults)) {
1409
+ return !this._agentRunAbortRequested;
1410
+ }
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;
751
1437
  }
752
- // The agent loop drains both queues before emitting agent_end. Any messages
753
- // here were queued by agent_end extension handlers and need a continuation.
754
- return this.agent.hasQueuedMessages();
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 };
755
1470
  }
756
1471
  /**
757
1472
  * Send a prompt to the agent.
@@ -763,129 +1478,119 @@ export class AgentSession {
763
1478
  * @throws Error if no model selected or no API key available (when not streaming)
764
1479
  */
765
1480
  async prompt(text, options) {
1481
+ if (this._isEmittingAgentSettled) {
1482
+ this._deferredSettledActions.push(async () => await this.prompt(text, options));
1483
+ return;
1484
+ }
766
1485
  const expandPromptTemplates = options?.expandPromptTemplates ?? true;
767
1486
  const preflightResult = options?.preflightResult;
768
- let messages;
769
- try {
770
- // Handle extension commands first (execute immediately, even during streaming)
771
- // Extension commands manage their own LLM interaction via pi.sendMessage()
772
- if (expandPromptTemplates && text.startsWith("/")) {
773
- const handled = await this._tryExecuteExtensionCommand(text);
774
- if (handled) {
775
- // Extension command executed, no prompt to send
776
- preflightResult?.(true);
777
- return;
778
- }
779
- }
780
- // Emit input event for extension interception (before skill/template expansion)
781
- let currentText = text;
782
- let currentImages = options?.images;
783
- if (this._extensionRunner.hasHandlers("input")) {
784
- const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
785
- if (inputResult.action === "handled") {
786
- preflightResult?.(true);
787
- return;
788
- }
789
- if (inputResult.action === "transform") {
790
- currentText = inputResult.text;
791
- currentImages = inputResult.images ?? currentImages;
792
- }
793
- }
794
- // Expand skill commands (/skill:name args) and prompt templates (/template args)
795
- let expandedText = currentText;
796
- if (expandPromptTemplates) {
797
- expandedText = this._expandSkillCommand(expandedText);
798
- expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
799
- }
800
- // If streaming, queue via steer() or followUp() based on option
801
- if (this.isStreaming) {
802
- if (!options?.streamingBehavior) {
803
- throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
804
- }
805
- if (options.streamingBehavior === "followUp") {
806
- await this._queueFollowUp(expandedText, currentImages);
807
- }
808
- else {
809
- await this._queueSteer(expandedText, currentImages);
810
- }
811
- 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");
812
1494
  return;
813
1495
  }
814
- // Flush any pending bash messages before the new prompt
815
- this._flushPendingBashMessages();
816
- // Validate model
817
- if (!this.model) {
818
- throw new Error(formatNoModelSelectedMessage());
819
- }
820
- const hasConfiguredAuth = this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
821
- (await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
822
- if (!hasConfiguredAuth) {
823
- const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
824
- if (isOAuth) {
825
- throw new Error(`Authentication failed for "${this.model.provider}". ` +
826
- `Credentials may have expired or network is unavailable. ` +
827
- `Run '/login ${this.model.provider}' to re-authenticate.`);
828
- }
829
- throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
830
- }
831
- // Check if we need to compact before sending (catches aborted responses).
832
- // The user's new prompt is sent below, so do not call agent.continue() here.
833
- const lastAssistant = this._findLastAssistantMessage();
834
- if (lastAssistant) {
835
- await this._checkCompaction(lastAssistant, false);
836
- }
837
- // Build messages array (custom message if any, then user message)
838
- messages = [];
839
- // Add user message
840
- const userContent = [{ type: "text", text: expandedText }];
841
- if (currentImages) {
842
- userContent.push(...currentImages);
843
- }
844
- messages.push({
845
- role: "user",
846
- content: userContent,
847
- timestamp: Date.now(),
848
- });
849
- // Inject any pending "nextTurn" messages as context alongside the user message
850
- for (const msg of this._pendingNextTurnMessages) {
851
- messages.push(msg);
852
- }
853
- this._pendingNextTurnMessages = [];
854
- // Emit before_agent_start extension event
855
- const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt, this._baseSystemPromptOptions);
856
- // Add all custom messages from extensions
857
- if (result?.messages) {
858
- for (const msg of result.messages) {
859
- messages.push({
860
- role: "custom",
861
- customType: msg.customType,
862
- // Untyped extensions can pass null/missing content; normalize at ingestion.
863
- content: msg.content ?? [],
864
- display: msg.display,
865
- details: msg.details,
866
- timestamp: Date.now(),
867
- });
868
- }
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.");
869
1517
  }
870
- // Apply extension-modified system prompt, or reset to base
871
- if (result?.systemPrompt !== undefined) {
872
- this._systemPromptOverride = result.systemPrompt;
873
- this.agent.state.systemPrompt = result.systemPrompt;
1518
+ if (options.streamingBehavior === "followUp") {
1519
+ await this._queueFollowUp(expandedText, currentImages);
874
1520
  }
875
1521
  else {
876
- // Ensure we're using the base prompt (in case previous turn had modifications)
877
- this._systemPromptOverride = undefined;
878
- this.agent.state.systemPrompt = this._baseSystemPrompt;
1522
+ await this._queueSteer(expandedText, currentImages);
879
1523
  }
1524
+ preflightResult?.("queued");
1525
+ return;
880
1526
  }
881
- catch (error) {
882
- preflightResult?.(false);
883
- 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());
884
1533
  }
885
- if (!messages) {
886
- 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);
887
1576
  }
888
- 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");
889
1594
  await this._runAgentPrompt(messages);
890
1595
  }
891
1596
  /**
@@ -945,40 +1650,45 @@ export class AgentSession {
945
1650
  return text; // Return original on error
946
1651
  }
947
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
+ }
948
1670
  /**
949
1671
  * Queue a steering message while the agent is running.
950
1672
  * Delivered after the current assistant turn finishes executing its tool calls,
951
1673
  * before the next LLM call.
952
1674
  * Expands skill commands and prompt templates. Errors on extension commands.
953
1675
  * @param images Optional image attachments to include with the message
1676
+ * @param options Input source; defaults to interactive
954
1677
  * @throws Error if text is an extension command
955
1678
  */
956
- async steer(text, images) {
957
- // Check for extension commands (cannot be queued)
958
- if (text.startsWith("/")) {
959
- this._throwIfExtensionCommand(text);
960
- }
961
- // Expand skill commands and prompt templates
962
- let expandedText = this._expandSkillCommand(text);
963
- expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
964
- await this._queueSteer(expandedText, images);
1679
+ async steer(text, images, options) {
1680
+ return this._queueUserInput(text, images, "steer", options?.source ?? "interactive");
965
1681
  }
966
1682
  /**
967
1683
  * Queue a follow-up message to be processed after the agent finishes.
968
1684
  * Delivered only when agent has no more tool calls or steering messages.
969
1685
  * Expands skill commands and prompt templates. Errors on extension commands.
970
1686
  * @param images Optional image attachments to include with the message
1687
+ * @param options Input source; defaults to interactive
971
1688
  * @throws Error if text is an extension command
972
1689
  */
973
- async followUp(text, images) {
974
- // Check for extension commands (cannot be queued)
975
- if (text.startsWith("/")) {
976
- this._throwIfExtensionCommand(text);
977
- }
978
- // Expand skill commands and prompt templates
979
- let expandedText = this._expandSkillCommand(text);
980
- expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
981
- await this._queueFollowUp(expandedText, images);
1690
+ async followUp(text, images, options) {
1691
+ return this._queueUserInput(text, images, "followUp", options?.source ?? "interactive");
982
1692
  }
983
1693
  /**
984
1694
  * Internal: Queue a steering message (already expanded, no extension command check).
@@ -1006,11 +1716,7 @@ export class AgentSession {
1006
1716
  if (images) {
1007
1717
  content.push(...images);
1008
1718
  }
1009
- this.agent.followUp({
1010
- role: "user",
1011
- content,
1012
- timestamp: Date.now(),
1013
- });
1719
+ this.agent.followUp({ role: "user", content, timestamp: Date.now() });
1014
1720
  }
1015
1721
  /**
1016
1722
  * Throw an error if the text is an extension command.
@@ -1026,8 +1732,9 @@ export class AgentSession {
1026
1732
  /**
1027
1733
  * Send a custom message to the session. Creates a CustomMessageEntry.
1028
1734
  *
1029
- * Handles three cases:
1735
+ * Handles four cases:
1030
1736
  * - Streaming: queues message, processed when loop pulls from queue
1737
+ * - Streaming + triggerTurn false: appended to state/session once the current turn ends
1031
1738
  * - Not streaming + triggerTurn: appends to state/session, starts new turn
1032
1739
  * - Not streaming + no trigger: appends to state/session, no turn
1033
1740
  *
@@ -1048,7 +1755,7 @@ export class AgentSession {
1048
1755
  if (options?.deliverAs === "nextTurn") {
1049
1756
  this._pendingNextTurnMessages.push(appMessage);
1050
1757
  }
1051
- else if (this.isStreaming) {
1758
+ else if (this.isStreaming && options?.triggerTurn !== false) {
1052
1759
  if (options?.deliverAs === "followUp") {
1053
1760
  this.agent.followUp(appMessage);
1054
1761
  }
@@ -1057,13 +1764,40 @@ export class AgentSession {
1057
1764
  }
1058
1765
  }
1059
1766
  else if (options?.triggerTurn) {
1767
+ if (this._isEmittingAgentSettled) {
1768
+ this._deferredSettledActions.push(async () => await this._runAgentPrompt(appMessage));
1769
+ return;
1770
+ }
1060
1771
  await this._runAgentPrompt(appMessage);
1061
1772
  }
1773
+ else if (this.isStreaming) {
1774
+ // Appending now would put the message between an assistant tool call and its
1775
+ // result, which providers that validate message order reject on replay. Defer
1776
+ // to the end of the turn. Nothing is emitted yet: message events must not
1777
+ // describe messages the session tree does not contain.
1778
+ this._pendingCustomMessages.push(appMessage);
1779
+ }
1062
1780
  else {
1063
- this.agent.state.messages.push(appMessage);
1064
- this.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details);
1065
- this._emit({ type: "message_start", message: appMessage });
1066
- this._emit({ type: "message_end", message: appMessage });
1781
+ this._appendCustomMessage(appMessage);
1782
+ }
1783
+ }
1784
+ _appendCustomMessage(appMessage) {
1785
+ this.sessionManager.appendCustomMessageEntry(appMessage.customType, appMessage.content, appMessage.display, appMessage.details);
1786
+ this._refreshFinalizedContext();
1787
+ this._emit({ type: "message_start", message: appMessage });
1788
+ this._emit({ type: "message_end", message: appMessage });
1789
+ }
1790
+ /**
1791
+ * Append custom messages queued while the agent was running.
1792
+ * Called once the current turn's tool results are in agent state and session history.
1793
+ */
1794
+ _flushPendingCustomMessages() {
1795
+ if (this._pendingCustomMessages.length === 0)
1796
+ return;
1797
+ const pending = this._pendingCustomMessages;
1798
+ this._pendingCustomMessages = [];
1799
+ for (const appMessage of pending) {
1800
+ this._appendCustomMessage(appMessage);
1067
1801
  }
1068
1802
  }
1069
1803
  /**
@@ -1072,6 +1806,7 @@ export class AgentSession {
1072
1806
  *
1073
1807
  * @param content User message content (string or content array)
1074
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.
1075
1810
  */
1076
1811
  async sendUserMessage(content, options) {
1077
1812
  // Normalize content to text string + optional images
@@ -1095,9 +1830,8 @@ export class AgentSession {
1095
1830
  if (images.length === 0)
1096
1831
  images = undefined;
1097
1832
  }
1098
- // Use prompt() with expandPromptTemplates: false to skip command handling and template expansion
1099
1833
  await this.prompt(text, {
1100
- expandPromptTemplates: false,
1834
+ expandPromptTemplates: options?.expandPromptTemplates ?? false,
1101
1835
  streamingBehavior: options?.deliverAs,
1102
1836
  images,
1103
1837
  source: "extension",
@@ -1136,7 +1870,14 @@ export class AgentSession {
1136
1870
  * Abort current operation and wait for agent to become idle.
1137
1871
  */
1138
1872
  async abort() {
1873
+ if (this._isAgentRunActive) {
1874
+ this._agentRunAbortRequested = true;
1875
+ }
1139
1876
  this.abortRetry();
1877
+ this.abortCompaction();
1878
+ this.abortBranchSummary();
1879
+ if (this._isBeforeSettle)
1880
+ this._abortDuringBeforeSettle = true;
1140
1881
  this.agent.abort();
1141
1882
  await this.waitForIdle();
1142
1883
  }
@@ -1161,40 +1902,57 @@ export class AgentSession {
1161
1902
  }
1162
1903
  /**
1163
1904
  * Set model directly.
1164
- * Validates that auth is configured, saves to session and settings.
1905
+ * Validates that auth is configured and saves to the session transcript.
1906
+ * Persists to global defaults only when options.persist is true.
1165
1907
  * @throws Error if no auth is configured for the model
1166
1908
  */
1167
- async setModel(model) {
1909
+ async setModel(model, options = {}) {
1168
1910
  if (!(await this._modelRuntime.checkAuth(model.provider))) {
1169
1911
  throw new Error(`No API key for ${model.provider}/${model.id}`);
1170
1912
  }
1171
1913
  const previousModel = this.model;
1172
- const thinkingLevel = this._getThinkingLevelForModelSwitch();
1914
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(model);
1173
1915
  this.agent.state.model = model;
1174
1916
  this.sessionManager.appendModelChange(model.provider, model.id, model.contextWindow);
1175
- this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1176
- // Re-clamp thinking level for new model's capabilities
1917
+ if (options.persist) {
1918
+ this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1919
+ this._addPersistedDefaultToNonEmptyScope(model);
1920
+ }
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.
1177
1924
  this.setThinkingLevel(thinkingLevel);
1178
1925
  await this._emitModelSelect(model, previousModel, "set");
1179
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
+ }
1180
1941
  /**
1181
1942
  * Cycle to next/previous model.
1182
1943
  * Uses scoped models (from --models flag) if available, otherwise all available models.
1183
1944
  * @param direction - "forward" (default) or "backward"
1184
1945
  * @returns The new model info, or undefined if only one model available
1185
1946
  */
1186
- async cycleModel(direction = "forward") {
1947
+ async cycleModel(direction = "forward", options = {}) {
1187
1948
  if (this._scopedModels.length > 0) {
1188
- return this._cycleScopedModel(direction);
1949
+ return this._cycleScopedModel(direction, options);
1189
1950
  }
1190
- return this._cycleAvailableModel(direction);
1951
+ return this._cycleAvailableModel(direction, options);
1191
1952
  }
1192
- async _cycleScopedModel(direction) {
1193
- const checks = await Promise.all(this._scopedModels.map(async (scoped) => ({
1194
- scoped,
1195
- auth: await this._modelRuntime.checkAuth(scoped.model.provider),
1196
- })));
1197
- 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}`));
1198
1956
  if (scopedModels.length <= 1)
1199
1957
  return undefined;
1200
1958
  const currentModel = this.model;
@@ -1204,21 +1962,25 @@ export class AgentSession {
1204
1962
  const len = scopedModels.length;
1205
1963
  const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1206
1964
  const next = scopedModels[nextIndex];
1207
- const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
1965
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(next.model, next.thinkingLevel);
1208
1966
  // Apply model
1209
1967
  this.agent.state.model = next.model;
1210
1968
  this.sessionManager.appendModelChange(next.model.provider, next.model.id, next.model.contextWindow);
1211
- this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
1212
- // Apply thinking level.
1213
- // - Explicit scoped model thinking level overrides current session level
1214
- // - 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
1215
1976
  // setThinkingLevel clamps to model capabilities.
1977
+ // Model persistence does not implicitly rewrite the global thinking default.
1216
1978
  this.setThinkingLevel(thinkingLevel);
1217
1979
  await this._emitModelSelect(next.model, currentModel, "cycle");
1218
1980
  return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
1219
1981
  }
1220
- async _cycleAvailableModel(direction) {
1221
- const availableModels = await this._modelRuntime.getAvailable();
1982
+ async _cycleAvailableModel(direction, options) {
1983
+ const availableModels = this._modelRuntime.getAvailableSnapshot();
1222
1984
  if (availableModels.length <= 1)
1223
1985
  return undefined;
1224
1986
  const currentModel = this.model;
@@ -1228,11 +1990,15 @@ export class AgentSession {
1228
1990
  const len = availableModels.length;
1229
1991
  const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1230
1992
  const nextModel = availableModels[nextIndex];
1231
- const thinkingLevel = this._getThinkingLevelForModelSwitch();
1993
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(nextModel);
1232
1994
  this.agent.state.model = nextModel;
1233
1995
  this.sessionManager.appendModelChange(nextModel.provider, nextModel.id, nextModel.contextWindow);
1234
- this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
1235
- // 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.
1236
2002
  this.setThinkingLevel(thinkingLevel);
1237
2003
  await this._emitModelSelect(nextModel, currentModel, "cycle");
1238
2004
  return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
@@ -1287,20 +2053,21 @@ export class AgentSession {
1287
2053
  /**
1288
2054
  * Set thinking level.
1289
2055
  * Clamps to model capabilities based on available thinking levels.
1290
- * Saves to session and settings only if the level actually changes.
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.
1291
2058
  */
1292
- setThinkingLevel(level) {
2059
+ setThinkingLevel(level, options = {}) {
1293
2060
  const availableLevels = this.getAvailableThinkingLevels();
1294
2061
  const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
1295
2062
  // Only persist if actually changing
1296
2063
  const previousLevel = this.agent.state.thinkingLevel;
1297
2064
  const isChanging = effectiveLevel !== previousLevel;
1298
2065
  this.agent.state.thinkingLevel = effectiveLevel;
2066
+ if (options.persist) {
2067
+ this.settingsManager.setDefaultThinkingLevel(level);
2068
+ }
1299
2069
  if (isChanging) {
1300
2070
  this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1301
- if (this.supportsThinking() || effectiveLevel !== "off") {
1302
- this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
1303
- }
1304
2071
  this._emit({ type: "thinking_level_changed", level: effectiveLevel });
1305
2072
  void this._extensionRunner.emit({
1306
2073
  type: "thinking_level_select",
@@ -1313,14 +2080,14 @@ export class AgentSession {
1313
2080
  * Cycle to next thinking level.
1314
2081
  * @returns New level, or undefined if model doesn't support thinking
1315
2082
  */
1316
- cycleThinkingLevel() {
2083
+ cycleThinkingLevel(options = {}) {
1317
2084
  if (!this.supportsThinking())
1318
2085
  return undefined;
1319
2086
  const levels = this.getAvailableThinkingLevels();
1320
2087
  const currentIndex = levels.indexOf(this.thinkingLevel);
1321
2088
  const nextIndex = (currentIndex + 1) % levels.length;
1322
2089
  const nextLevel = levels[nextIndex];
1323
- this.setThinkingLevel(nextLevel);
2090
+ this.setThinkingLevel(nextLevel, options);
1324
2091
  return nextLevel;
1325
2092
  }
1326
2093
  /**
@@ -1329,7 +2096,7 @@ export class AgentSession {
1329
2096
  */
1330
2097
  getAvailableThinkingLevels() {
1331
2098
  if (!this.model)
1332
- return THINKING_LEVELS;
2099
+ return [...THINKING_LEVEL_OPTIONS];
1333
2100
  return getSupportedThinkingLevels(this.model);
1334
2101
  }
1335
2102
  /**
@@ -1338,14 +2105,18 @@ export class AgentSession {
1338
2105
  supportsThinking() {
1339
2106
  return !!this.model?.reasoning;
1340
2107
  }
1341
- _getThinkingLevelForModelSwitch(explicitLevel) {
2108
+ _getThinkingLevelForModelSwitch(targetModel, explicitLevel) {
1342
2109
  if (explicitLevel !== undefined) {
1343
2110
  return explicitLevel;
1344
2111
  }
1345
- if (!this.supportsThinking()) {
1346
- 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
+ }
1347
2118
  }
1348
- return this.thinkingLevel;
2119
+ return this.settingsManager.getDefaultThinkingLevel() ?? this.thinkingLevel ?? DEFAULT_THINKING_LEVEL;
1349
2120
  }
1350
2121
  _clampThinkingLevel(level, _availableLevels) {
1351
2122
  return this.model ? clampThinkingLevel(this.model, level) : "off";
@@ -1376,23 +2147,44 @@ export class AgentSession {
1376
2147
  // =========================================================================
1377
2148
  // Compaction
1378
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
+ }
1379
2160
  /**
1380
2161
  * Manually compact the session context.
1381
- * 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
+ *
1382
2173
  * @param customInstructions Optional instructions for the compaction summary
1383
2174
  */
1384
2175
  async compact(customInstructions) {
1385
- this._disconnectFromAgent();
1386
2176
  await this.abort();
1387
2177
  this._compactionAbortController = new AbortController();
1388
2178
  this._emit({ type: "compaction_start", reason: "manual" });
2179
+ let fromExtension = false;
2180
+ let cancelledByExtension = false;
1389
2181
  try {
1390
- if (!this.model) {
2182
+ const model = this.model;
2183
+ if (!model) {
1391
2184
  throw new Error(formatNoModelSelectedMessage());
1392
2185
  }
1393
- const { apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model);
2186
+ const settings = this.settingsManager.getCompactionSettings(model);
1394
2187
  const pathEntries = this.sessionManager.getBranch();
1395
- const settings = this.settingsManager.getCompactionSettings();
1396
2188
  const preparation = prepareCompaction(pathEntries, settings);
1397
2189
  if (!preparation) {
1398
2190
  // Check why we can't compact
@@ -1403,7 +2195,6 @@ export class AgentSession {
1403
2195
  throw new Error("Nothing to compact (session too small)");
1404
2196
  }
1405
2197
  let extensionCompaction;
1406
- let fromExtension = false;
1407
2198
  if (this._extensionRunner.hasHandlers("session_before_compact")) {
1408
2199
  const result = (await this._extensionRunner.emit({
1409
2200
  type: "session_before_compact",
@@ -1415,6 +2206,7 @@ export class AgentSession {
1415
2206
  signal: this._compactionAbortController.signal,
1416
2207
  }));
1417
2208
  if (result?.cancel) {
2209
+ cancelledByExtension = true;
1418
2210
  throw new Error("Compaction cancelled");
1419
2211
  }
1420
2212
  if (result?.compaction) {
@@ -1436,8 +2228,8 @@ export class AgentSession {
1436
2228
  details = extensionCompaction.details;
1437
2229
  }
1438
2230
  else {
1439
- // Generate compaction result
1440
- const result = await compact(preparation, this.model, 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");
1441
2233
  summary = result.summary;
1442
2234
  firstKeptEntryId = result.firstKeptEntryId;
1443
2235
  tokensBefore = result.tokensBefore;
@@ -1449,9 +2241,8 @@ export class AgentSession {
1449
2241
  }
1450
2242
  this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
1451
2243
  const newEntries = this.sessionManager.getEntries();
1452
- const sessionContext = this.sessionManager.buildSessionContext();
1453
- this.agent.state.messages = sessionContext.messages;
1454
- const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
2244
+ this._refreshFinalizedContext();
2245
+ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
1455
2246
  // Get the saved compaction entry for the extension event
1456
2247
  const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1457
2248
  if (this._extensionRunner && savedCompactionEntry) {
@@ -1471,6 +2262,8 @@ export class AgentSession {
1471
2262
  usage,
1472
2263
  details,
1473
2264
  };
2265
+ // compaction_end listeners may submit queued prompts, so expose idle state before notifying them.
2266
+ this._clearManualCompactionState();
1474
2267
  this._emit({
1475
2268
  type: "compaction_end",
1476
2269
  reason: "manual",
@@ -1482,20 +2275,28 @@ export class AgentSession {
1482
2275
  }
1483
2276
  catch (error) {
1484
2277
  const message = error instanceof Error ? error.message : String(error);
1485
- const aborted = message === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError");
2278
+ const aborted = this._compactionAbortController.signal.aborted || cancelledByExtension;
2279
+ const errorMessage = aborted ? undefined : `Compaction failed: ${message}`;
2280
+ this._clearManualCompactionState();
1486
2281
  this._emit({
1487
2282
  type: "compaction_end",
1488
2283
  reason: "manual",
1489
2284
  result: undefined,
1490
2285
  aborted,
1491
2286
  willRetry: false,
1492
- 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,
1493
2295
  });
1494
2296
  throw error;
1495
2297
  }
1496
2298
  finally {
1497
- this._compactionAbortController = undefined;
1498
- this._reconnectToAgent();
2299
+ this._clearManualCompactionState();
1499
2300
  }
1500
2301
  }
1501
2302
  /**
@@ -1512,29 +2313,41 @@ export class AgentSession {
1512
2313
  this._branchSummaryAbortController?.abort();
1513
2314
  }
1514
2315
  /**
1515
- * Check if compaction is needed and run it.
1516
- * 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.
1517
2326
  *
1518
- * Two cases:
1519
- * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
1520
- * 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.
1521
2331
  *
1522
2332
  * @param assistantMessage The assistant message to check
1523
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
1524
2335
  */
1525
- async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
1526
- const settings = this.settingsManager.getCompactionSettings();
2336
+ async _checkCompaction(assistantMessage, skipAbortedCheck = true, toolResults = []) {
2337
+ const settings = this.settingsManager.getCompactionSettings(this.model);
1527
2338
  if (!settings.enabled)
1528
2339
  return false;
1529
2340
  // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
1530
2341
  if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
1531
2342
  return false;
1532
- const contextWindow = this.model?.contextWindow ?? 0;
1533
2343
  // Skip overflow check if the message came from a different model.
1534
2344
  // This handles the case where user switched from a smaller-context model (e.g. opus)
1535
2345
  // to a larger-context model (e.g. codex) - the overflow error from the old model
1536
- // shouldn't trigger compaction for the new model.
1537
- 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;
1538
2351
  // Skip compaction checks if this assistant message is older than the latest
1539
2352
  // compaction boundary. This prevents a stale pre-compaction usage/error
1540
2353
  // from retriggering compaction on the first prompt after compaction.
@@ -1543,54 +2356,92 @@ export class AgentSession {
1543
2356
  if (assistantIsFromBeforeCompaction) {
1544
2357
  return false;
1545
2358
  }
1546
- // Case 1: Overflow - LLM returned context overflow error, or reported usage exceeded
1547
- // the configured window. A successful response over the configured window should compact
1548
- // but must not retry: the assistant answer already completed and agent.continue() cannot
1549
- // continue from an assistant message.
1550
- 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) {
1551
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.
1552
2387
  if (!willRetry) {
1553
2388
  return await this._runAutoCompaction("overflow", false);
1554
2389
  }
1555
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.";
1556
2394
  this._emit({
1557
2395
  type: "compaction_end",
1558
2396
  reason: "overflow",
1559
2397
  result: undefined,
1560
2398
  aborted: false,
1561
2399
  willRetry: false,
1562
- 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,
1563
2408
  });
1564
2409
  return false;
1565
2410
  }
2411
+ // Persistently omit the selected final attempt before post-run recovery compaction.
1566
2412
  this._overflowRecoveryAttempted = true;
1567
- // Remove the error message from agent state (it IS saved to session for history,
1568
- // but we don't want it in context for the retry)
1569
- const messages = this.agent.state.messages;
1570
- if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1571
- this.agent.state.messages = messages.slice(0, -1);
1572
- }
1573
- 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;
1574
2418
  }
1575
- // Case 2: Threshold - context is getting large
2419
+ // Case 3: threshold compaction without retry.
1576
2420
  // For error messages or all-zero usage messages, estimate from the last valid response.
1577
2421
  // This ensures sessions that hit persistent API errors (e.g. 529) or malformed zero-usage
1578
2422
  // responses can still compact and do not reset context accounting.
1579
2423
  let contextTokens;
2424
+ const projection = currentProjection;
2425
+ const hasContextEdits = projection.entries.some((entry) => entry.sourceEntry.type === "context_edit");
1580
2426
  const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
1581
- if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
2427
+ if (hasContextEdits) {
2428
+ contextTokens = estimateProjectedContextTokens(projection, branch).tokens;
2429
+ }
2430
+ else if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
1582
2431
  const messages = this.agent.state.messages;
1583
2432
  const estimate = estimateContextTokens(messages);
1584
- if (estimate.lastUsageIndex === null)
1585
- return false; // No usage data at all
1586
- // Verify the usage source is post-compaction. Kept pre-compaction messages
1587
- // have stale usage reflecting the old (larger) context and would falsely
1588
- // trigger compaction right after one just finished.
1589
- const usageMsg = messages[estimate.lastUsageIndex];
1590
- if (compactionEntry &&
1591
- usageMsg.role === "assistant" &&
1592
- usageMsg.timestamp <= new Date(compactionEntry.timestamp).getTime()) {
1593
- return false;
2433
+ // Without provider usage, estimate.tokens is the pure message-size estimate.
2434
+ // Only usage-backed estimates need the stale pre-compaction check.
2435
+ if (estimate.lastUsageIndex !== null) {
2436
+ // Verify the usage source is post-compaction. Kept pre-compaction messages
2437
+ // have stale usage reflecting the old (larger) context and would falsely
2438
+ // trigger compaction right after one just finished.
2439
+ const usageMsg = messages[estimate.lastUsageIndex];
2440
+ if (compactionEntry &&
2441
+ usageMsg.role === "assistant" &&
2442
+ usageMsg.timestamp <= new Date(compactionEntry.timestamp).getTime()) {
2443
+ return false;
2444
+ }
1594
2445
  }
1595
2446
  contextTokens = estimate.tokens;
1596
2447
  }
@@ -1603,34 +2454,37 @@ export class AgentSession {
1603
2454
  return false;
1604
2455
  }
1605
2456
  /**
1606
- * 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()`
1607
2465
  */
1608
2466
  async _runAutoCompaction(reason, willRetry) {
1609
- const settings = this.settingsManager.getCompactionSettings();
2467
+ const model = this.model;
2468
+ const settings = this.settingsManager.getCompactionSettings(model);
2469
+ let abortController;
1610
2470
  let started = false;
2471
+ let fromExtension = false;
2472
+ let cancelledByExtension = false;
1611
2473
  try {
1612
- if (!this.model) {
2474
+ if (!model) {
1613
2475
  return false;
1614
2476
  }
1615
- let apiKey;
1616
- let headers;
1617
- let env;
1618
- if (this.agent.streamFunction === streamSimple) {
1619
- ({ apiKey, headers, env } = await this._getRequiredRequestAuth(this.model));
1620
- }
1621
- else {
1622
- ({ apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model));
1623
- }
1624
2477
  const pathEntries = this.sessionManager.getBranch();
1625
2478
  const preparation = prepareCompaction(pathEntries, settings);
1626
2479
  if (!preparation) {
1627
2480
  return false;
1628
2481
  }
1629
- this._emit({ type: "compaction_start", reason });
1630
- this._autoCompactionAbortController = new AbortController();
2482
+ abortController = new AbortController();
2483
+ this._autoCompactionAbortController = abortController;
1631
2484
  started = true;
2485
+ this._emit({ type: "compaction_start", reason });
2486
+ abortController.signal.throwIfAborted();
1632
2487
  let extensionCompaction;
1633
- let fromExtension = false;
1634
2488
  if (this._extensionRunner.hasHandlers("session_before_compact")) {
1635
2489
  const extensionResult = (await this._extensionRunner.emit({
1636
2490
  type: "session_before_compact",
@@ -1639,23 +2493,18 @@ export class AgentSession {
1639
2493
  customInstructions: undefined,
1640
2494
  reason,
1641
2495
  willRetry,
1642
- signal: this._autoCompactionAbortController.signal,
2496
+ signal: abortController.signal,
1643
2497
  }));
1644
2498
  if (extensionResult?.cancel) {
1645
- this._emit({
1646
- type: "compaction_end",
1647
- reason,
1648
- result: undefined,
1649
- aborted: true,
1650
- willRetry: false,
1651
- });
1652
- return false;
2499
+ cancelledByExtension = true;
2500
+ throw new Error("Compaction cancelled");
1653
2501
  }
1654
2502
  if (extensionResult?.compaction) {
1655
2503
  extensionCompaction = extensionResult.compaction;
1656
2504
  fromExtension = true;
1657
2505
  }
1658
2506
  }
2507
+ abortController.signal.throwIfAborted();
1659
2508
  let summary;
1660
2509
  let firstKeptEntryId;
1661
2510
  let tokensBefore;
@@ -1670,29 +2519,19 @@ export class AgentSession {
1670
2519
  details = extensionCompaction.details;
1671
2520
  }
1672
2521
  else {
1673
- // Generate compaction result
1674
- const compactResult = await compact(preparation, this.model, 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);
1675
2524
  summary = compactResult.summary;
1676
2525
  firstKeptEntryId = compactResult.firstKeptEntryId;
1677
2526
  tokensBefore = compactResult.tokensBefore;
1678
2527
  usage = compactResult.usage;
1679
2528
  details = compactResult.details;
1680
2529
  }
1681
- if (this._autoCompactionAbortController.signal.aborted) {
1682
- this._emit({
1683
- type: "compaction_end",
1684
- reason,
1685
- result: undefined,
1686
- aborted: true,
1687
- willRetry: false,
1688
- });
1689
- return false;
1690
- }
2530
+ abortController.signal.throwIfAborted();
1691
2531
  this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
1692
2532
  const newEntries = this.sessionManager.getEntries();
1693
- const sessionContext = this.sessionManager.buildSessionContext();
1694
- this.agent.state.messages = sessionContext.messages;
1695
- const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
2533
+ this._refreshFinalizedContext();
2534
+ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
1696
2535
  // Get the saved compaction entry for the extension event
1697
2536
  const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1698
2537
  if (this._extensionRunner && savedCompactionEntry) {
@@ -1713,36 +2552,44 @@ export class AgentSession {
1713
2552
  details,
1714
2553
  };
1715
2554
  this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
1716
- if (willRetry) {
1717
- const messages = this.agent.state.messages;
1718
- const lastMsg = messages[messages.length - 1];
1719
- if (lastMsg?.role === "assistant" && lastMsg.stopReason === "error") {
1720
- this.agent.state.messages = messages.slice(0, -1);
1721
- }
2555
+ if (willRetry)
1722
2556
  return true;
1723
- }
1724
2557
  // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
1725
2558
  // Continue once so queued messages are delivered.
1726
2559
  return this.agent.hasQueuedMessages();
1727
2560
  }
1728
2561
  catch (error) {
1729
- 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;
1730
2564
  if (started) {
2565
+ const errorMessage = aborted
2566
+ ? undefined
2567
+ : reason === "overflow"
2568
+ ? `Context overflow recovery failed: ${message}`
2569
+ : `Auto-compaction failed: ${message}`;
1731
2570
  this._emit({
1732
2571
  type: "compaction_end",
1733
2572
  reason,
1734
2573
  result: undefined,
1735
- aborted: false,
2574
+ aborted,
1736
2575
  willRetry: false,
1737
- errorMessage: reason === "overflow"
1738
- ? `Context overflow recovery failed: ${errorMessage}`
1739
- : `Auto-compaction failed: ${errorMessage}`,
2576
+ errorMessage,
2577
+ });
2578
+ await this._emitSessionCompactFailed({
2579
+ reason,
2580
+ errorMessage,
2581
+ aborted,
2582
+ willRetry: false,
2583
+ fromExtension,
1740
2584
  });
1741
2585
  }
1742
2586
  return false;
1743
2587
  }
1744
2588
  finally {
1745
- this._autoCompactionAbortController = undefined;
2589
+ if (this._autoCompactionAbortController === abortController) {
2590
+ this._autoCompactionAbortController = undefined;
2591
+ }
2592
+ this._resolveIdleWaitIfIdle();
1746
2593
  }
1747
2594
  }
1748
2595
  /**
@@ -1755,6 +2602,17 @@ export class AgentSession {
1755
2602
  get autoCompactionEnabled() {
1756
2603
  return this.settingsManager.getCompactionEnabled();
1757
2604
  }
2605
+ /**
2606
+ * Install (or remove) the permission relay this session's dialogs are mirrored onto.
2607
+ *
2608
+ * Re-applies the extension bindings immediately: the constructor's own apply has already run
2609
+ * by the time any caller can hand a relay over, so without the re-apply the runner would keep
2610
+ * an undecorated context until the next reload.
2611
+ */
2612
+ setPermissionRelay(relay) {
2613
+ this._permissionRelay = relay;
2614
+ this._applyExtensionBindings(this._extensionRunner);
2615
+ }
1758
2616
  async bindExtensions(bindings) {
1759
2617
  if (bindings.uiContext !== undefined) {
1760
2618
  this._extensionUIContext = bindings.uiContext;
@@ -1776,6 +2634,7 @@ export class AgentSession {
1776
2634
  }
1777
2635
  this._applyExtensionBindings(this._extensionRunner);
1778
2636
  await this._extensionRunner.emit(this._sessionStartEvent);
2637
+ this._extensionRunner.reportUnhandledMcpServers();
1779
2638
  await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
1780
2639
  }
1781
2640
  async extendResourcesFromExtensions(reason) {
@@ -1792,13 +2651,12 @@ export class AgentSession {
1792
2651
  themePaths: this.buildExtensionResourcePaths(themePaths),
1793
2652
  };
1794
2653
  this._resourceLoader.extendResources(extensionPaths);
1795
- this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
1796
- this.agent.state.systemPrompt = this._baseSystemPrompt;
2654
+ this._rebuildSystemPrompt(this.getActiveToolNames());
1797
2655
  }
1798
2656
  buildExtensionResourcePaths(entries) {
1799
2657
  return entries.map((entry) => {
1800
2658
  const source = this.getExtensionSourceLabel(entry.extensionPath);
1801
- const baseDir = entry.extensionPath.startsWith("<") ? undefined : dirname(entry.extensionPath);
2659
+ const baseDir = isSyntheticPath(entry.extensionPath) ? undefined : dirname(entry.extensionPath);
1802
2660
  return {
1803
2661
  path: entry.path,
1804
2662
  metadata: {
@@ -1811,15 +2669,36 @@ export class AgentSession {
1811
2669
  });
1812
2670
  }
1813
2671
  getExtensionSourceLabel(extensionPath) {
1814
- if (extensionPath.startsWith("<")) {
2672
+ if (isSyntheticPath(extensionPath)) {
1815
2673
  return `extension:${extensionPath.replace(/[<>]/g, "")}`;
1816
2674
  }
1817
2675
  const base = basename(extensionPath);
1818
2676
  const name = base.replace(/\.(ts|js)$/, "");
1819
2677
  return `extension:${name}`;
1820
2678
  }
2679
+ /**
2680
+ * Wrap the mode's UI context so an attached remote surface can answer the same dialogs.
2681
+ *
2682
+ * Returns the base untouched when no relay is installed. When one is, the decorator is built
2683
+ * here and NOWHERE else: this is the only mode-agnostic seam every session passes through
2684
+ * (bindExtensions for interactive/rpc/print, _buildRuntime for the constructor and reload),
2685
+ * so a wrap installed anywhere else is silently overwritten when a mode binds its own context.
2686
+ */
2687
+ _wrapUIContext(base) {
2688
+ if (this._permissionRelay === undefined) {
2689
+ return base;
2690
+ }
2691
+ return createRelayUIContext(base ?? noOpRelayBaseUIContext, this._permissionRelay, base !== undefined,
2692
+ // The TRUTH about which surface a locally answered dialog came from, and the reason this
2693
+ // seam is the only place the decorator may be built: `_extensionMode` is set by
2694
+ // `bindExtensions` immediately before `_applyExtensionBindings` calls this, so the mode
2695
+ // and the context it wraps are always the same binding. A literal `tui` inside the
2696
+ // decorator recorded an answer typed into the RPC surface as a human at a terminal that
2697
+ // does not exist.
2698
+ LOCAL_SURFACE_BY_MODE[this._extensionMode]);
2699
+ }
1821
2700
  _applyExtensionBindings(runner) {
1822
- runner.setUIContext(this._extensionUIContext, this._extensionMode);
2701
+ runner.setUIContext(this._wrapUIContext(this._extensionUIContext), this._extensionMode);
1823
2702
  runner.bindCommandContext(this._extensionCommandContextActions);
1824
2703
  this._extensionErrorUnsubscriber?.();
1825
2704
  this._extensionErrorUnsubscriber = this._extensionErrorListener
@@ -1896,17 +2775,18 @@ export class AgentSession {
1896
2775
  },
1897
2776
  getActiveTools: () => this.getActiveToolNames(),
1898
2777
  getAllTools: () => this.getAllTools(),
2778
+ getSettings: () => this.settingsManager.getSettings(),
1899
2779
  setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
1900
2780
  refreshTools: () => this._refreshToolRegistry(),
1901
2781
  getCommands,
1902
- setModel: async (model) => {
2782
+ setModel: async (model, options) => {
1903
2783
  if (!this._modelRuntime.hasConfiguredAuth(model.provider))
1904
2784
  return false;
1905
- await this.setModel(model);
2785
+ await this.setModel(model, options);
1906
2786
  return true;
1907
2787
  },
1908
2788
  getThinkingLevel: () => this.thinkingLevel,
1909
- setThinkingLevel: (level) => this.setThinkingLevel(level),
2789
+ setThinkingLevel: (level, options) => this.setThinkingLevel(level, options),
1910
2790
  }, {
1911
2791
  getModel: () => this.model,
1912
2792
  getScopedModels: () => this._scopedModels,
@@ -1939,6 +2819,8 @@ export class AgentSession {
1939
2819
  },
1940
2820
  getSystemPrompt: () => this.systemPrompt,
1941
2821
  getSystemPromptOptions: () => this._baseSystemPromptOptions,
2822
+ executeTool: (callerId, name, args, options) => this._executeNestedToolCall(callerId, name, args, options),
2823
+ getCallableTools: () => this._getCallableTools(),
1942
2824
  }, {
1943
2825
  registerProvider: (name, config) => {
1944
2826
  this._modelRuntime.registerProvider(name, config);
@@ -1952,10 +2834,20 @@ export class AgentSession {
1952
2834
  this._modelRuntime.unregisterProvider(name);
1953
2835
  this._refreshCurrentModelFromRegistry();
1954
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
+ },
1955
2845
  });
1956
2846
  }
1957
2847
  _refreshToolRegistry(options) {
1958
- 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)));
1959
2851
  const previousActiveToolNames = this.getActiveToolNames();
1960
2852
  const allowedToolNames = this._allowedToolNames;
1961
2853
  const excludedToolNames = this._excludedToolNames;
@@ -1974,7 +2866,7 @@ export class AgentSession {
1974
2866
  name,
1975
2867
  {
1976
2868
  definition,
1977
- sourceInfo: createSyntheticSourceInfo(`<builtin:${name}>`, { source: "builtin" }),
2869
+ sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${name}`, { source: "builtin" }),
1978
2870
  },
1979
2871
  ]));
1980
2872
  for (const tool of allCustomTools) {
@@ -2002,7 +2894,9 @@ export class AgentSession {
2002
2894
  .filter((definition) => isAllowedTool(definition.name))
2003
2895
  .map((definition) => ({
2004
2896
  definition,
2005
- sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
2897
+ sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${definition.name}`, {
2898
+ source: "builtin",
2899
+ }),
2006
2900
  })), runner);
2007
2901
  const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
2008
2902
  for (const tool of wrappedExtensionTools) {
@@ -2012,25 +2906,36 @@ export class AgentSession {
2012
2906
  const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => isAllowedTool(name));
2013
2907
  if (allowedToolNames) {
2014
2908
  for (const toolName of this._toolRegistry.keys()) {
2015
- 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)) {
2016
2911
  nextActiveToolNames.push(toolName);
2017
2912
  }
2018
2913
  }
2019
2914
  }
2020
2915
  else if (options?.includeAllExtensionTools) {
2021
2916
  for (const tool of wrappedExtensionTools) {
2022
- nextActiveToolNames.push(tool.name);
2917
+ if (this._isActivatedOnRegistration(tool.name))
2918
+ nextActiveToolNames.push(tool.name);
2023
2919
  }
2024
2920
  }
2025
2921
  else if (!options?.activeToolNames) {
2026
2922
  for (const toolName of this._toolRegistry.keys()) {
2027
- if (!previousRegistryNames.has(toolName)) {
2923
+ if (!previousActivatedOnRegistration.has(toolName) && this._isActivatedOnRegistration(toolName)) {
2028
2924
  nextActiveToolNames.push(toolName);
2029
2925
  }
2030
2926
  }
2031
2927
  }
2032
2928
  this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
2033
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
+ }
2034
2939
  _buildRuntime(options) {
2035
2940
  const autoResizeImages = this.settingsManager.getImageAutoResize();
2036
2941
  const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
@@ -2067,14 +2972,22 @@ export class AgentSession {
2067
2972
  });
2068
2973
  }
2069
2974
  async reload(options) {
2070
- const previousFlagValues = this._extensionRunner.getFlagValues();
2071
- await emitSessionShutdownEvent(this._extensionRunner, { type: "session_shutdown", reason: "reload" });
2975
+ const oldRunner = this._extensionRunner;
2976
+ const previousFlagValues = oldRunner.getFlagValues();
2977
+ await emitSessionShutdownEvent(oldRunner, { type: "session_shutdown", reason: "reload" });
2978
+ oldRunner.invalidate();
2979
+ const previousDefaultTools = new Set(this._usesDefaultTools ? (this.settingsManager.getDefaultTools() ?? DEFAULT_TOOL_NAMES) : []);
2072
2980
  await this.settingsManager.reload();
2073
2981
  this.syncQueueModesFromSettings();
2074
2982
  resetApiProviders();
2075
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
+ : [];
2076
2989
  this._buildRuntime({
2077
- activeToolNames: this.getActiveToolNames(),
2990
+ activeToolNames: [...this.getActiveToolNames(), ...addedDefaultTools],
2078
2991
  flagValues: previousFlagValues,
2079
2992
  includeAllExtensionTools: true,
2080
2993
  });
@@ -2085,6 +2998,7 @@ export class AgentSession {
2085
2998
  if (hasBindings) {
2086
2999
  await options?.beforeSessionStart?.();
2087
3000
  await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
3001
+ this._extensionRunner.reportUnhandledMcpServers();
2088
3002
  await this.extendResourcesFromExtensions("reload");
2089
3003
  }
2090
3004
  }
@@ -2097,7 +3011,7 @@ export class AgentSession {
2097
3011
  */
2098
3012
  _isRetryableError(message) {
2099
3013
  // Context overflow is handled by compaction, not retry.
2100
- if (isContextOverflow(message, this.model?.contextWindow ?? 0))
3014
+ if (isContextOverflow(message, (this._modelForMessage(message) ?? this.model)?.contextWindow ?? 0))
2101
3015
  return false;
2102
3016
  return isRetryableAssistantError(message);
2103
3017
  }
@@ -2129,6 +3043,18 @@ export class AgentSession {
2129
3043
  },
2130
3044
  };
2131
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
+ }
2132
3058
  /**
2133
3059
  * Prepare a retryable error for continuation with exponential backoff.
2134
3060
  * @returns true if the caller should continue the agent, false otherwise
@@ -2144,7 +3070,7 @@ export class AgentSession {
2144
3070
  this._retryAttempt--;
2145
3071
  return false;
2146
3072
  }
2147
- const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
3073
+ const delayMs = retryDelayMs(settings, this._retryAttempt);
2148
3074
  this._emit({
2149
3075
  type: "auto_retry_start",
2150
3076
  attempt: this._retryAttempt,
@@ -2152,11 +3078,8 @@ export class AgentSession {
2152
3078
  delayMs,
2153
3079
  errorMessage: message.errorMessage || "Unknown error",
2154
3080
  });
2155
- // Remove error message from agent state (keep in session for history)
2156
- const messages = this.agent.state.messages;
2157
- if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
2158
- this.agent.state.messages = messages.slice(0, -1);
2159
- }
3081
+ // Keep the failed attempt in raw history while durably omitting it from model projection.
3082
+ this._omitRecoveryAttempt(message);
2160
3083
  // Wait with exponential backoff (abortable)
2161
3084
  this._retryAbortController = new AbortController();
2162
3085
  try {
@@ -2164,14 +3087,7 @@ export class AgentSession {
2164
3087
  }
2165
3088
  catch {
2166
3089
  // Aborted during sleep - emit end event so UI can clean up
2167
- const attempt = this._retryAttempt;
2168
- this._retryAttempt = 0;
2169
- this._emit({
2170
- type: "auto_retry_end",
2171
- success: false,
2172
- attempt,
2173
- finalError: "Retry cancelled",
2174
- });
3090
+ this._finishCancelledRetry();
2175
3091
  return false;
2176
3092
  }
2177
3093
  finally {
@@ -2255,10 +3171,8 @@ export class AgentSession {
2255
3171
  this._pendingBashMessages.push(bashMessage);
2256
3172
  }
2257
3173
  else {
2258
- // Add to agent state immediately
2259
- this.agent.state.messages.push(bashMessage);
2260
- // Save to session
2261
3174
  this.sessionManager.appendMessage(bashMessage);
3175
+ this._refreshFinalizedContext();
2262
3176
  }
2263
3177
  }
2264
3178
  /**
@@ -2285,12 +3199,10 @@ export class AgentSession {
2285
3199
  if (this._pendingBashMessages.length === 0)
2286
3200
  return;
2287
3201
  for (const bashMessage of this._pendingBashMessages) {
2288
- // Add to agent state
2289
- this.agent.state.messages.push(bashMessage);
2290
- // Save to session
2291
3202
  this.sessionManager.appendMessage(bashMessage);
2292
3203
  }
2293
3204
  this._pendingBashMessages = [];
3205
+ this._refreshFinalizedContext();
2294
3206
  }
2295
3207
  // =========================================================================
2296
3208
  // Session Management
@@ -2322,6 +3234,9 @@ export class AgentSession {
2322
3234
  if (this.isStreaming) {
2323
3235
  throw new Error("Wait for the current response to finish before navigating the session tree.");
2324
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
+ }
2325
3240
  const oldLeafId = this.sessionManager.getLeafId();
2326
3241
  // No-op if already at target
2327
3242
  if (targetId === oldLeafId) {
@@ -2386,15 +3301,11 @@ export class AgentSession {
2386
3301
  let summaryDetails;
2387
3302
  let summaryUsage;
2388
3303
  if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
2389
- const model = this.model;
2390
- const { apiKey, headers, env } = await this._getSummarizationRequestAuth(model);
3304
+ const signal = this._branchSummaryAbortController.signal;
2391
3305
  const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
2392
3306
  const result = await generateBranchSummary(entriesToSummarize, {
2393
- model,
2394
- apiKey,
2395
- headers,
2396
- env,
2397
- signal: this._branchSummaryAbortController.signal,
3307
+ ...(await this._getSummarizationRequestAuth(this.model, signal)),
3308
+ signal,
2398
3309
  customInstructions,
2399
3310
  replaceInstructions,
2400
3311
  reserveTokens: branchSummarySettings.reserveTokens,
@@ -2461,9 +3372,9 @@ export class AgentSession {
2461
3372
  if (label && !summaryText) {
2462
3373
  this.sessionManager.appendLabelChange(targetId, label);
2463
3374
  }
2464
- // Update agent state
2465
- const sessionContext = this.sessionManager.buildSessionContext();
2466
- this.agent.state.messages = sessionContext.messages;
3375
+ // Update finalized context from the canonical session projection.
3376
+ this._refreshFinalizedContext();
3377
+ this._restoreToolsFromTranscript();
2467
3378
  // Emit session_tree event
2468
3379
  await this._extensionRunner.emit({
2469
3380
  type: "session_tree",
@@ -2477,6 +3388,7 @@ export class AgentSession {
2477
3388
  }
2478
3389
  finally {
2479
3390
  this._branchSummaryAbortController = undefined;
3391
+ this._resolveIdleWaitIfIdle();
2480
3392
  }
2481
3393
  }
2482
3394
  /**
@@ -2510,7 +3422,10 @@ export class AgentSession {
2510
3422
  let toolCalls = 0;
2511
3423
  const usageTotals = createUsageTotals();
2512
3424
  for (const entry of this.sessionManager.getEntries()) {
2513
- 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) {
2514
3429
  addUsageToTotals(usageTotals, entry.usage);
2515
3430
  }
2516
3431
  if (entry.type !== "message")
@@ -2555,7 +3470,7 @@ export class AgentSession {
2555
3470
  };
2556
3471
  }
2557
3472
  getContextUsage() {
2558
- const model = this.model;
3473
+ const model = this._limitsModel();
2559
3474
  if (!model)
2560
3475
  return undefined;
2561
3476
  const contextWindow = model.contextWindow ?? 0;
@@ -2564,30 +3479,24 @@ export class AgentSession {
2564
3479
  // After compaction, the last assistant usage reflects pre-compaction context size.
2565
3480
  // We can only trust usage from an assistant that responded after the latest compaction.
2566
3481
  // If no such assistant exists, context token count is unknown until the next LLM response.
2567
- const branchEntries = this.sessionManager.getBranch();
2568
- const latestCompaction = getLatestCompactionEntry(branchEntries);
3482
+ const projection = this.sessionManager.buildSessionProjection();
3483
+ const branch = this.sessionManager.getBranch();
3484
+ const latestCompaction = getLatestCompactionEntry(branch);
2569
3485
  if (latestCompaction) {
2570
- // Check if there's a valid assistant usage after the compaction boundary
2571
- const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
2572
- let hasPostCompactionUsage = false;
2573
- for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
2574
- const entry = branchEntries[i];
2575
- if (entry.type === "message" && entry.message.role === "assistant") {
2576
- const assistant = entry.message;
2577
- if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
2578
- const contextTokens = calculateContextTokens(assistant.usage);
2579
- if (contextTokens > 0) {
2580
- hasPostCompactionUsage = true;
2581
- break;
2582
- }
2583
- }
2584
- }
2585
- }
2586
- 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)
2587
3497
  return { tokens: null, contextWindow, percent: null };
2588
- }
2589
3498
  }
2590
- const estimate = estimateContextTokens(this.messages);
3499
+ const estimate = estimateProjectedContextTokens(projection, branch);
2591
3500
  const percent = (estimate.tokens / contextWindow) * 100;
2592
3501
  return {
2593
3502
  tokens: estimate.tokens,
@@ -2598,11 +3507,11 @@ export class AgentSession {
2598
3507
  /**
2599
3508
  * Export session to HTML.
2600
3509
  * @param outputPath Optional output path (defaults to session directory)
3510
+ * @param options Optional export presentation settings
2601
3511
  * @returns Path to exported file
2602
3512
  */
2603
- async exportToHtml(outputPath) {
2604
- const configuredThemeName = this.settingsManager.getTheme();
2605
- 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);
2606
3515
  // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
2607
3516
  const toolRenderer = createToolHtmlRenderer({
2608
3517
  getToolDefinition: (name) => this.getToolDefinition(name),
@@ -2622,29 +3531,26 @@ export class AgentSession {
2622
3531
  * @returns The resolved output file path.
2623
3532
  */
2624
3533
  exportToJsonl(outputPath) {
2625
- const filePath = resolvePath(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`, process.cwd());
2626
- const dir = dirname(filePath);
2627
- if (!existsSync(dir)) {
2628
- mkdirSync(dir, { recursive: true });
2629
- }
2630
- const header = {
2631
- type: "session",
2632
- version: CURRENT_SESSION_VERSION,
2633
- id: this.sessionManager.getSessionId(),
2634
- timestamp: new Date().toISOString(),
2635
- cwd: this.sessionManager.getCwd(),
2636
- };
2637
- const branchEntries = this.sessionManager.getBranch();
2638
- const lines = [JSON.stringify(header)];
2639
- // Re-chain parentIds to form a linear sequence
2640
- let prevId = null;
2641
- for (const entry of branchEntries) {
2642
- const linear = { ...entry, parentId: prevId };
2643
- lines.push(JSON.stringify(linear));
2644
- prevId = entry.id;
2645
- }
2646
- writeFileSync(filePath, `${lines.join("\n")}\n`);
2647
- 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
+ });
2648
3554
  }
2649
3555
  // =========================================================================
2650
3556
  // Utilities