@draht/coding-agent 2026.5.12 → 2026.7.7

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 (652) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -4
  3. package/bin/draht-tools.cjs +3756 -1
  4. package/dist/bun/cli.d.ts.map +1 -1
  5. package/dist/bun/cli.js +4 -2
  6. package/dist/bun/cli.js.map +1 -1
  7. package/dist/bun/register-bedrock.d.ts.map +1 -1
  8. package/dist/bun/register-bedrock.js +1 -1
  9. package/dist/bun/register-bedrock.js.map +1 -1
  10. package/dist/bun/restore-sandbox-env.d.ts +17 -0
  11. package/dist/bun/restore-sandbox-env.d.ts.map +1 -0
  12. package/dist/bun/restore-sandbox-env.js +36 -0
  13. package/dist/bun/restore-sandbox-env.js.map +1 -0
  14. package/dist/cli/args.d.ts +9 -4
  15. package/dist/cli/args.d.ts.map +1 -1
  16. package/dist/cli/args.js +91 -38
  17. package/dist/cli/args.js.map +1 -1
  18. package/dist/cli/config-selector.d.ts +5 -3
  19. package/dist/cli/config-selector.d.ts.map +1 -1
  20. package/dist/cli/config-selector.js +1 -1
  21. package/dist/cli/config-selector.js.map +1 -1
  22. package/dist/cli/file-processor.d.ts.map +1 -1
  23. package/dist/cli/file-processor.js +13 -26
  24. package/dist/cli/file-processor.js.map +1 -1
  25. package/dist/cli/initial-message.d.ts +1 -1
  26. package/dist/cli/initial-message.d.ts.map +1 -1
  27. package/dist/cli/initial-message.js.map +1 -1
  28. package/dist/cli/list-models.d.ts +1 -1
  29. package/dist/cli/list-models.d.ts.map +1 -1
  30. package/dist/cli/list-models.js +7 -1
  31. package/dist/cli/list-models.js.map +1 -1
  32. package/dist/cli/project-trust.d.ts +10 -0
  33. package/dist/cli/project-trust.d.ts.map +1 -0
  34. package/dist/cli/project-trust.js +48 -0
  35. package/dist/cli/project-trust.js.map +1 -0
  36. package/dist/cli/session-picker.d.ts +3 -2
  37. package/dist/cli/session-picker.d.ts.map +1 -1
  38. package/dist/cli/session-picker.js +5 -4
  39. package/dist/cli/session-picker.js.map +1 -1
  40. package/dist/cli/startup-ui.d.ts +20 -0
  41. package/dist/cli/startup-ui.d.ts.map +1 -0
  42. package/dist/cli/startup-ui.js +184 -0
  43. package/dist/cli/startup-ui.js.map +1 -0
  44. package/dist/cli.d.ts.map +1 -1
  45. package/dist/cli.js +7 -4
  46. package/dist/cli.js.map +1 -1
  47. package/dist/config.d.ts +27 -13
  48. package/dist/config.d.ts.map +1 -1
  49. package/dist/config.js +284 -63
  50. package/dist/config.js.map +1 -1
  51. package/dist/core/agent-session-runtime.d.ts +45 -9
  52. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  53. package/dist/core/agent-session-runtime.js +100 -33
  54. package/dist/core/agent-session-runtime.js.map +1 -1
  55. package/dist/core/agent-session-services.d.ts +6 -4
  56. package/dist/core/agent-session-services.d.ts.map +1 -1
  57. package/dist/core/agent-session-services.js +7 -4
  58. package/dist/core/agent-session-services.js.map +1 -1
  59. package/dist/core/agent-session.d.ts +55 -33
  60. package/dist/core/agent-session.d.ts.map +1 -1
  61. package/dist/core/agent-session.js +560 -492
  62. package/dist/core/agent-session.js.map +1 -1
  63. package/dist/core/auth-guidance.d.ts +5 -0
  64. package/dist/core/auth-guidance.d.ts.map +1 -0
  65. package/dist/core/auth-guidance.js +21 -0
  66. package/dist/core/auth-guidance.js.map +1 -0
  67. package/dist/core/auth-storage.d.ts +21 -13
  68. package/dist/core/auth-storage.d.ts.map +1 -1
  69. package/dist/core/auth-storage.js +48 -28
  70. package/dist/core/auth-storage.js.map +1 -1
  71. package/dist/core/bash-executor.d.ts +1 -15
  72. package/dist/core/bash-executor.d.ts.map +1 -1
  73. package/dist/core/bash-executor.js +10 -24
  74. package/dist/core/bash-executor.js.map +1 -1
  75. package/dist/core/builtins/subagent.d.ts.map +1 -1
  76. package/dist/core/builtins/subagent.js +1 -2
  77. package/dist/core/builtins/subagent.js.map +1 -1
  78. package/dist/core/compaction/branch-summarization.d.ts +9 -5
  79. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  80. package/dist/core/compaction/branch-summarization.js +10 -4
  81. package/dist/core/compaction/branch-summarization.js.map +1 -1
  82. package/dist/core/compaction/compaction.d.ts +8 -7
  83. package/dist/core/compaction/compaction.d.ts.map +1 -1
  84. package/dist/core/compaction/compaction.js +56 -47
  85. package/dist/core/compaction/compaction.js.map +1 -1
  86. package/dist/core/compaction/index.d.ts +3 -3
  87. package/dist/core/compaction/index.d.ts.map +1 -1
  88. package/dist/core/compaction/index.js.map +1 -1
  89. package/dist/core/compaction/utils.d.ts +1 -1
  90. package/dist/core/compaction/utils.d.ts.map +1 -1
  91. package/dist/core/compaction/utils.js +1 -1
  92. package/dist/core/compaction/utils.js.map +1 -1
  93. package/dist/core/exec.d.ts.map +1 -1
  94. package/dist/core/exec.js.map +1 -1
  95. package/dist/core/experimental.d.ts +2 -0
  96. package/dist/core/experimental.d.ts.map +1 -0
  97. package/dist/core/experimental.js +4 -0
  98. package/dist/core/experimental.js.map +1 -0
  99. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  100. package/dist/core/export-html/ansi-to-html.js +1 -1
  101. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  102. package/dist/core/export-html/index.d.ts +1 -1
  103. package/dist/core/export-html/index.d.ts.map +1 -1
  104. package/dist/core/export-html/index.js +13 -11
  105. package/dist/core/export-html/index.js.map +1 -1
  106. package/dist/core/export-html/template.css +69 -4
  107. package/dist/core/export-html/template.js +231 -57
  108. package/dist/core/export-html/tool-renderer.d.ts +0 -6
  109. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  110. package/dist/core/export-html/tool-renderer.js +15 -2
  111. package/dist/core/export-html/tool-renderer.js.map +1 -1
  112. package/dist/core/export-html/vendor/marked.min.js +75 -3
  113. package/dist/core/extensions/index.d.ts +8 -8
  114. package/dist/core/extensions/index.d.ts.map +1 -1
  115. package/dist/core/extensions/index.js.map +1 -1
  116. package/dist/core/extensions/loader.d.ts +5 -6
  117. package/dist/core/extensions/loader.d.ts.map +1 -1
  118. package/dist/core/extensions/loader.js +98 -43
  119. package/dist/core/extensions/loader.js.map +1 -1
  120. package/dist/core/extensions/runner.d.ts +31 -12
  121. package/dist/core/extensions/runner.d.ts.map +1 -1
  122. package/dist/core/extensions/runner.js +248 -33
  123. package/dist/core/extensions/runner.js.map +1 -1
  124. package/dist/core/extensions/types.d.ts +191 -36
  125. package/dist/core/extensions/types.d.ts.map +1 -1
  126. package/dist/core/extensions/types.js.map +1 -1
  127. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  128. package/dist/core/extensions/wrapper.js +2 -2
  129. package/dist/core/extensions/wrapper.js.map +1 -1
  130. package/dist/core/footer-data-provider.d.ts +7 -1
  131. package/dist/core/footer-data-provider.d.ts.map +1 -1
  132. package/dist/core/footer-data-provider.js +78 -54
  133. package/dist/core/footer-data-provider.js.map +1 -1
  134. package/dist/core/http-dispatcher.d.ts +22 -0
  135. package/dist/core/http-dispatcher.d.ts.map +1 -0
  136. package/dist/core/http-dispatcher.js +91 -0
  137. package/dist/core/http-dispatcher.js.map +1 -0
  138. package/dist/core/index.d.ts +9 -8
  139. package/dist/core/index.d.ts.map +1 -1
  140. package/dist/core/index.js +2 -1
  141. package/dist/core/index.js.map +1 -1
  142. package/dist/core/keybindings.d.ts +67 -2
  143. package/dist/core/keybindings.d.ts.map +1 -1
  144. package/dist/core/keybindings.js +59 -7
  145. package/dist/core/keybindings.js.map +1 -1
  146. package/dist/core/model-registry.d.ts +24 -5
  147. package/dist/core/model-registry.d.ts.map +1 -1
  148. package/dist/core/model-registry.js +188 -51
  149. package/dist/core/model-registry.js.map +1 -1
  150. package/dist/core/model-resolver.d.ts +12 -1
  151. package/dist/core/model-resolver.d.ts.map +1 -1
  152. package/dist/core/model-resolver.js +84 -39
  153. package/dist/core/model-resolver.js.map +1 -1
  154. package/dist/core/output-guard.d.ts +1 -0
  155. package/dist/core/output-guard.d.ts.map +1 -1
  156. package/dist/core/output-guard.js +52 -22
  157. package/dist/core/output-guard.js.map +1 -1
  158. package/dist/core/package-manager.d.ts +22 -4
  159. package/dist/core/package-manager.d.ts.map +1 -1
  160. package/dist/core/package-manager.js +455 -157
  161. package/dist/core/package-manager.js.map +1 -1
  162. package/dist/core/project-trust.d.ts +15 -0
  163. package/dist/core/project-trust.d.ts.map +1 -0
  164. package/dist/core/project-trust.js +59 -0
  165. package/dist/core/project-trust.js.map +1 -0
  166. package/dist/core/prompt-templates.d.ts +13 -11
  167. package/dist/core/prompt-templates.d.ts.map +1 -1
  168. package/dist/core/prompt-templates.js +67 -76
  169. package/dist/core/prompt-templates.js.map +1 -1
  170. package/dist/core/provider-attribution.d.ts +4 -0
  171. package/dist/core/provider-attribution.d.ts.map +1 -0
  172. package/dist/core/provider-attribution.js +72 -0
  173. package/dist/core/provider-attribution.js.map +1 -0
  174. package/dist/core/provider-display-names.d.ts +2 -0
  175. package/dist/core/provider-display-names.d.ts.map +1 -0
  176. package/dist/core/provider-display-names.js +36 -0
  177. package/dist/core/provider-display-names.js.map +1 -0
  178. package/dist/core/resolve-config-value.d.ts +13 -6
  179. package/dist/core/resolve-config-value.d.ts.map +1 -1
  180. package/dist/core/resolve-config-value.js +143 -22
  181. package/dist/core/resolve-config-value.js.map +1 -1
  182. package/dist/core/resource-loader.d.ts +36 -15
  183. package/dist/core/resource-loader.d.ts.map +1 -1
  184. package/dist/core/resource-loader.js +178 -79
  185. package/dist/core/resource-loader.js.map +1 -1
  186. package/dist/core/sdk.d.ts +34 -18
  187. package/dist/core/sdk.d.ts.map +1 -1
  188. package/dist/core/sdk.js +47 -16
  189. package/dist/core/sdk.js.map +1 -1
  190. package/dist/core/session-manager.d.ts +32 -14
  191. package/dist/core/session-manager.d.ts.map +1 -1
  192. package/dist/core/session-manager.js +366 -209
  193. package/dist/core/session-manager.js.map +1 -1
  194. package/dist/core/settings-manager.d.ts +62 -6
  195. package/dist/core/settings-manager.d.ts.map +1 -1
  196. package/dist/core/settings-manager.js +230 -40
  197. package/dist/core/settings-manager.js.map +1 -1
  198. package/dist/core/skills.d.ts +10 -10
  199. package/dist/core/skills.d.ts.map +1 -1
  200. package/dist/core/skills.js +13 -35
  201. package/dist/core/skills.js.map +1 -1
  202. package/dist/core/slash-commands.d.ts +1 -1
  203. package/dist/core/slash-commands.d.ts.map +1 -1
  204. package/dist/core/slash-commands.js +7 -4
  205. package/dist/core/slash-commands.js.map +1 -1
  206. package/dist/core/source-info.d.ts +1 -1
  207. package/dist/core/source-info.d.ts.map +1 -1
  208. package/dist/core/source-info.js.map +1 -1
  209. package/dist/core/system-prompt.d.ts +4 -4
  210. package/dist/core/system-prompt.d.ts.map +1 -1
  211. package/dist/core/system-prompt.js +20 -16
  212. package/dist/core/system-prompt.js.map +1 -1
  213. package/dist/core/telemetry.d.ts +3 -0
  214. package/dist/core/telemetry.d.ts.map +1 -0
  215. package/dist/core/telemetry.js +9 -0
  216. package/dist/core/telemetry.js.map +1 -0
  217. package/dist/core/timings.d.ts +4 -2
  218. package/dist/core/timings.d.ts.map +1 -1
  219. package/dist/core/timings.js +24 -14
  220. package/dist/core/timings.js.map +1 -1
  221. package/dist/core/tools/bash.d.ts +11 -16
  222. package/dist/core/tools/bash.d.ts.map +1 -1
  223. package/dist/core/tools/bash.js +187 -178
  224. package/dist/core/tools/bash.js.map +1 -1
  225. package/dist/core/tools/edit-diff.d.ts +26 -5
  226. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  227. package/dist/core/tools/edit-diff.js +110 -23
  228. package/dist/core/tools/edit-diff.js.map +1 -1
  229. package/dist/core/tools/edit.d.ts +22 -24
  230. package/dist/core/tools/edit.d.ts.map +1 -1
  231. package/dist/core/tools/edit.js +201 -113
  232. package/dist/core/tools/edit.js.map +1 -1
  233. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  234. package/dist/core/tools/file-mutation-queue.js +27 -12
  235. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  236. package/dist/core/tools/find.d.ts +7 -18
  237. package/dist/core/tools/find.d.ts.map +1 -1
  238. package/dist/core/tools/find.js +148 -101
  239. package/dist/core/tools/find.js.map +1 -1
  240. package/dist/core/tools/grep.d.ts +11 -30
  241. package/dist/core/tools/grep.d.ts.map +1 -1
  242. package/dist/core/tools/grep.js +23 -12
  243. package/dist/core/tools/grep.js.map +1 -1
  244. package/dist/core/tools/index.d.ts +26 -101
  245. package/dist/core/tools/index.d.ts.map +1 -1
  246. package/dist/core/tools/index.js +78 -52
  247. package/dist/core/tools/index.js.map +1 -1
  248. package/dist/core/tools/ls.d.ts +6 -15
  249. package/dist/core/tools/ls.d.ts.map +1 -1
  250. package/dist/core/tools/ls.js +12 -17
  251. package/dist/core/tools/ls.js.map +1 -1
  252. package/dist/core/tools/output-accumulator.d.ts +52 -0
  253. package/dist/core/tools/output-accumulator.d.ts.map +1 -0
  254. package/dist/core/tools/output-accumulator.js +184 -0
  255. package/dist/core/tools/output-accumulator.js.map +1 -0
  256. package/dist/core/tools/path-utils.d.ts +2 -0
  257. package/dist/core/tools/path-utils.d.ts.map +1 -1
  258. package/dist/core/tools/path-utils.js +40 -22
  259. package/dist/core/tools/path-utils.js.map +1 -1
  260. package/dist/core/tools/read.d.ts +7 -18
  261. package/dist/core/tools/read.d.ts.map +1 -1
  262. package/dist/core/tools/read.js +103 -52
  263. package/dist/core/tools/read.js.map +1 -1
  264. package/dist/core/tools/render-utils.d.ts +5 -2
  265. package/dist/core/tools/render-utils.d.ts.map +1 -1
  266. package/dist/core/tools/render-utils.js +18 -2
  267. package/dist/core/tools/render-utils.js.map +1 -1
  268. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  269. package/dist/core/tools/tool-definition-wrapper.js +2 -0
  270. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  271. package/dist/core/tools/truncate.d.ts.map +1 -1
  272. package/dist/core/tools/truncate.js +12 -2
  273. package/dist/core/tools/truncate.js.map +1 -1
  274. package/dist/core/tools/write.d.ts +5 -14
  275. package/dist/core/tools/write.d.ts.map +1 -1
  276. package/dist/core/tools/write.js +27 -46
  277. package/dist/core/tools/write.js.map +1 -1
  278. package/dist/core/trust-manager.d.ts +36 -0
  279. package/dist/core/trust-manager.d.ts.map +1 -0
  280. package/dist/core/trust-manager.js +202 -0
  281. package/dist/core/trust-manager.js.map +1 -0
  282. package/dist/index.d.ts +33 -29
  283. package/dist/index.d.ts.map +1 -1
  284. package/dist/index.js +12 -9
  285. package/dist/index.js.map +1 -1
  286. package/dist/main.d.ts +5 -1
  287. package/dist/main.d.ts.map +1 -1
  288. package/dist/main.js +208 -93
  289. package/dist/main.js.map +1 -1
  290. package/dist/migrations.d.ts +2 -2
  291. package/dist/migrations.d.ts.map +1 -1
  292. package/dist/migrations.js +4 -4
  293. package/dist/migrations.js.map +1 -1
  294. package/dist/modes/index.d.ts +5 -5
  295. package/dist/modes/index.d.ts.map +1 -1
  296. package/dist/modes/index.js.map +1 -1
  297. package/dist/modes/interactive/assets/clankolas.png +0 -0
  298. package/dist/modes/interactive/components/assistant-message.d.ts +5 -1
  299. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  300. package/dist/modes/interactive/components/assistant-message.js +37 -15
  301. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  302. package/dist/modes/interactive/components/bash-execution.d.ts +1 -1
  303. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  304. package/dist/modes/interactive/components/bash-execution.js +3 -3
  305. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  306. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  307. package/dist/modes/interactive/components/bordered-loader.js +3 -0
  308. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  309. package/dist/modes/interactive/components/config-selector.d.ts +36 -5
  310. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  311. package/dist/modes/interactive/components/config-selector.js +318 -36
  312. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  313. package/dist/modes/interactive/components/countdown-timer.d.ts +2 -2
  314. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
  315. package/dist/modes/interactive/components/countdown-timer.js +2 -2
  316. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  317. package/dist/modes/interactive/components/custom-editor.d.ts +1 -1
  318. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  319. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  320. package/dist/modes/interactive/components/custom-entry.d.ts +19 -0
  321. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -0
  322. package/dist/modes/interactive/components/custom-entry.js +52 -0
  323. package/dist/modes/interactive/components/custom-entry.js.map +1 -0
  324. package/dist/modes/interactive/components/custom-message.d.ts +2 -2
  325. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  326. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  327. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  328. package/dist/modes/interactive/components/diff.js.map +1 -1
  329. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -1
  330. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -1
  331. package/dist/modes/interactive/components/extension-editor.d.ts +3 -1
  332. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  333. package/dist/modes/interactive/components/extension-editor.js +26 -9
  334. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  335. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  336. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  337. package/dist/modes/interactive/components/extension-selector.d.ts +2 -0
  338. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  339. package/dist/modes/interactive/components/extension-selector.js +8 -3
  340. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  341. package/dist/modes/interactive/components/first-time-setup.d.ts +25 -0
  342. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -0
  343. package/dist/modes/interactive/components/first-time-setup.js +103 -0
  344. package/dist/modes/interactive/components/first-time-setup.js.map +1 -0
  345. package/dist/modes/interactive/components/footer.d.ts +4 -3
  346. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  347. package/dist/modes/interactive/components/footer.js +27 -7
  348. package/dist/modes/interactive/components/footer.js.map +1 -1
  349. package/dist/modes/interactive/components/index.d.ts +33 -31
  350. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  351. package/dist/modes/interactive/components/index.js +2 -0
  352. package/dist/modes/interactive/components/index.js.map +1 -1
  353. package/dist/modes/interactive/components/keybinding-hints.d.ts +5 -0
  354. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  355. package/dist/modes/interactive/components/keybinding-hints.js +19 -5
  356. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  357. package/dist/modes/interactive/components/login-dialog.d.ts +12 -2
  358. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  359. package/dist/modes/interactive/components/login-dialog.js +45 -11
  360. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  361. package/dist/modes/interactive/components/model-selector.d.ts +2 -2
  362. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  363. package/dist/modes/interactive/components/model-selector.js +10 -6
  364. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  365. package/dist/modes/interactive/components/oauth-selector.d.ts +18 -6
  366. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  367. package/dist/modes/interactive/components/oauth-selector.js +93 -25
  368. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  369. package/dist/modes/interactive/components/scoped-models-selector.d.ts +5 -12
  370. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  371. package/dist/modes/interactive/components/scoped-models-selector.js +49 -31
  372. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  373. package/dist/modes/interactive/components/session-selector.d.ts +2 -2
  374. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  375. package/dist/modes/interactive/components/session-selector.js +33 -14
  376. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  377. package/dist/modes/interactive/components/settings-selector.d.ts +17 -0
  378. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  379. package/dist/modes/interactive/components/settings-selector.js +301 -20
  380. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  381. package/dist/modes/interactive/components/skill-invocation-message.d.ts +1 -1
  382. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  383. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  384. package/dist/modes/interactive/components/status-indicator.d.ts +28 -0
  385. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -0
  386. package/dist/modes/interactive/components/status-indicator.js +60 -0
  387. package/dist/modes/interactive/components/status-indicator.js.map +1 -0
  388. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  389. package/dist/modes/interactive/components/thinking-selector.js +1 -1
  390. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  391. package/dist/modes/interactive/components/tool-execution.d.ts +6 -1
  392. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  393. package/dist/modes/interactive/components/tool-execution.js +57 -14
  394. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  395. package/dist/modes/interactive/components/tree-selector.d.ts +1 -1
  396. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  397. package/dist/modes/interactive/components/tree-selector.js +137 -13
  398. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  399. package/dist/modes/interactive/components/trust-selector.d.ts +23 -0
  400. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -0
  401. package/dist/modes/interactive/components/trust-selector.js +91 -0
  402. package/dist/modes/interactive/components/trust-selector.js.map +1 -0
  403. package/dist/modes/interactive/components/user-message-selector.d.ts +2 -2
  404. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  405. package/dist/modes/interactive/components/user-message-selector.js +8 -7
  406. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  407. package/dist/modes/interactive/components/user-message.d.ts +6 -1
  408. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  409. package/dist/modes/interactive/components/user-message.js +22 -8
  410. package/dist/modes/interactive/components/user-message.js.map +1 -1
  411. package/dist/modes/interactive/interactive-mode.d.ts +76 -19
  412. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  413. package/dist/modes/interactive/interactive-mode.js +1294 -494
  414. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  415. package/dist/modes/interactive/model-search.d.ts +12 -0
  416. package/dist/modes/interactive/model-search.d.ts.map +1 -0
  417. package/dist/modes/interactive/model-search.js +15 -0
  418. package/dist/modes/interactive/model-search.js.map +1 -0
  419. package/dist/modes/interactive/theme/dark.json +5 -4
  420. package/dist/modes/interactive/theme/light.json +5 -4
  421. package/dist/modes/interactive/theme/theme-controller.d.ts +29 -0
  422. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -0
  423. package/dist/modes/interactive/theme/theme-controller.js +102 -0
  424. package/dist/modes/interactive/theme/theme-controller.js.map +1 -0
  425. package/dist/modes/interactive/theme/theme-schema.json +2 -1
  426. package/dist/modes/interactive/theme/theme.d.ts +41 -3
  427. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  428. package/dist/modes/interactive/theme/theme.js +183 -106
  429. package/dist/modes/interactive/theme/theme.js.map +1 -1
  430. package/dist/modes/print-mode.d.ts.map +1 -1
  431. package/dist/modes/print-mode.js +40 -20
  432. package/dist/modes/print-mode.js.map +1 -1
  433. package/dist/modes/rpc/rpc-client.d.ts +30 -5
  434. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  435. package/dist/modes/rpc/rpc-client.js +87 -8
  436. package/dist/modes/rpc/rpc-client.js.map +1 -1
  437. package/dist/modes/rpc/rpc-mode.d.ts +2 -2
  438. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  439. package/dist/modes/rpc/rpc-mode.js +113 -31
  440. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  441. package/dist/modes/rpc/rpc-types.d.ts +42 -4
  442. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  443. package/dist/modes/rpc/rpc-types.js.map +1 -1
  444. package/dist/package-manager-cli.d.ts +6 -2
  445. package/dist/package-manager-cli.d.ts.map +1 -1
  446. package/dist/package-manager-cli.js +504 -25
  447. package/dist/package-manager-cli.js.map +1 -1
  448. package/dist/prompts/commands/brainstorm.md +148 -0
  449. package/dist/prompts/commands/map-codebase.md +14 -0
  450. package/dist/rpc-entry.d.ts +3 -0
  451. package/dist/rpc-entry.d.ts.map +1 -0
  452. package/dist/rpc-entry.js +10 -0
  453. package/dist/rpc-entry.js.map +1 -0
  454. package/dist/utils/ansi.d.ts +2 -0
  455. package/dist/utils/ansi.d.ts.map +1 -0
  456. package/dist/utils/ansi.js +52 -0
  457. package/dist/utils/ansi.js.map +1 -0
  458. package/dist/utils/changelog.d.ts +2 -1
  459. package/dist/utils/changelog.d.ts.map +1 -1
  460. package/dist/utils/changelog.js +78 -0
  461. package/dist/utils/changelog.js.map +1 -1
  462. package/dist/utils/child-process.d.ts +12 -5
  463. package/dist/utils/child-process.d.ts.map +1 -1
  464. package/dist/utils/child-process.js +33 -5
  465. package/dist/utils/child-process.js.map +1 -1
  466. package/dist/utils/clipboard-image.d.ts.map +1 -1
  467. package/dist/utils/clipboard-image.js +2 -2
  468. package/dist/utils/clipboard-image.js.map +1 -1
  469. package/dist/utils/clipboard-native.d.ts +3 -1
  470. package/dist/utils/clipboard-native.d.ts.map +1 -1
  471. package/dist/utils/clipboard-native.js +14 -8
  472. package/dist/utils/clipboard-native.js.map +1 -1
  473. package/dist/utils/clipboard.d.ts.map +1 -1
  474. package/dist/utils/clipboard.js +84 -45
  475. package/dist/utils/clipboard.js.map +1 -1
  476. package/dist/utils/deprecation.d.ts +4 -0
  477. package/dist/utils/deprecation.d.ts.map +1 -0
  478. package/dist/utils/deprecation.js +13 -0
  479. package/dist/utils/deprecation.js.map +1 -0
  480. package/dist/utils/exif-orientation.d.ts +1 -1
  481. package/dist/utils/exif-orientation.d.ts.map +1 -1
  482. package/dist/utils/exif-orientation.js.map +1 -1
  483. package/dist/utils/fs-watch.d.ts +5 -0
  484. package/dist/utils/fs-watch.d.ts.map +1 -0
  485. package/dist/utils/fs-watch.js +25 -0
  486. package/dist/utils/fs-watch.js.map +1 -0
  487. package/dist/utils/git.d.ts.map +1 -1
  488. package/dist/utils/git.js +54 -22
  489. package/dist/utils/git.js.map +1 -1
  490. package/dist/utils/html.d.ts +7 -0
  491. package/dist/utils/html.d.ts.map +1 -0
  492. package/dist/utils/html.js +40 -0
  493. package/dist/utils/html.js.map +1 -0
  494. package/dist/utils/image-convert.d.ts +1 -0
  495. package/dist/utils/image-convert.d.ts.map +1 -1
  496. package/dist/utils/image-convert.js +21 -15
  497. package/dist/utils/image-convert.js.map +1 -1
  498. package/dist/utils/image-process.d.ts +18 -0
  499. package/dist/utils/image-process.d.ts.map +1 -0
  500. package/dist/utils/image-process.js +83 -0
  501. package/dist/utils/image-process.js.map +1 -0
  502. package/dist/utils/image-resize-core.d.ts +30 -0
  503. package/dist/utils/image-resize-core.d.ts.map +1 -0
  504. package/dist/utils/image-resize-core.js +124 -0
  505. package/dist/utils/image-resize-core.js.map +1 -0
  506. package/dist/utils/image-resize-worker.d.ts +2 -0
  507. package/dist/utils/image-resize-worker.d.ts.map +1 -0
  508. package/dist/utils/image-resize-worker.js +31 -0
  509. package/dist/utils/image-resize-worker.js.map +1 -0
  510. package/dist/utils/image-resize.d.ts +7 -27
  511. package/dist/utils/image-resize.d.ts.map +1 -1
  512. package/dist/utils/image-resize.js +75 -115
  513. package/dist/utils/image-resize.js.map +1 -1
  514. package/dist/utils/json.d.ts +3 -0
  515. package/dist/utils/json.d.ts.map +1 -0
  516. package/dist/utils/json.js +7 -0
  517. package/dist/utils/json.js.map +1 -0
  518. package/dist/utils/mime.d.ts +1 -0
  519. package/dist/utils/mime.d.ts.map +1 -1
  520. package/dist/utils/mime.js +100 -16
  521. package/dist/utils/mime.js.map +1 -1
  522. package/dist/utils/open-browser.d.ts +9 -0
  523. package/dist/utils/open-browser.d.ts.map +1 -0
  524. package/dist/utils/open-browser.js +22 -0
  525. package/dist/utils/open-browser.js.map +1 -0
  526. package/dist/utils/paths.d.ts +25 -1
  527. package/dist/utils/paths.d.ts.map +1 -1
  528. package/dist/utils/paths.js +75 -2
  529. package/dist/utils/paths.js.map +1 -1
  530. package/dist/utils/pi-user-agent.d.ts +2 -0
  531. package/dist/utils/pi-user-agent.d.ts.map +1 -0
  532. package/dist/utils/pi-user-agent.js +5 -0
  533. package/dist/utils/pi-user-agent.js.map +1 -0
  534. package/dist/utils/shell.d.ts +11 -6
  535. package/dist/utils/shell.d.ts.map +1 -1
  536. package/dist/utils/shell.js +42 -26
  537. package/dist/utils/shell.js.map +1 -1
  538. package/dist/utils/syntax-highlight.d.ts +12 -0
  539. package/dist/utils/syntax-highlight.d.ts.map +1 -0
  540. package/dist/utils/syntax-highlight.js +118 -0
  541. package/dist/utils/syntax-highlight.js.map +1 -0
  542. package/dist/utils/tools-manager.d.ts.map +1 -1
  543. package/dist/utils/tools-manager.js +86 -10
  544. package/dist/utils/tools-manager.js.map +1 -1
  545. package/dist/utils/version-check.d.ts +15 -0
  546. package/dist/utils/version-check.d.ts.map +1 -0
  547. package/dist/utils/version-check.js +59 -0
  548. package/dist/utils/version-check.js.map +1 -0
  549. package/dist/utils/windows-self-update.d.ts +3 -0
  550. package/dist/utils/windows-self-update.d.ts.map +1 -0
  551. package/dist/utils/windows-self-update.js +77 -0
  552. package/dist/utils/windows-self-update.js.map +1 -0
  553. package/docs/compaction.md +12 -12
  554. package/docs/containerization.md +111 -0
  555. package/docs/custom-provider.md +187 -47
  556. package/docs/development.md +5 -5
  557. package/docs/docs.json +156 -0
  558. package/docs/extensions.md +520 -79
  559. package/docs/index.md +82 -0
  560. package/docs/json.md +4 -4
  561. package/docs/keybindings.md +24 -2
  562. package/docs/models.md +119 -17
  563. package/docs/packages.md +19 -11
  564. package/docs/prompt-templates.md +30 -2
  565. package/docs/providers.md +85 -23
  566. package/docs/quickstart.md +165 -0
  567. package/docs/rpc.md +99 -10
  568. package/docs/sdk.md +118 -50
  569. package/docs/security.md +55 -0
  570. package/docs/{session.md → session-format.md} +29 -19
  571. package/docs/sessions.md +145 -0
  572. package/docs/settings.md +71 -11
  573. package/docs/skills.md +16 -17
  574. package/docs/terminal-setup.md +44 -2
  575. package/docs/termux.md +4 -4
  576. package/docs/themes.md +3 -3
  577. package/docs/tmux.md +4 -2
  578. package/docs/tui.md +44 -4
  579. package/docs/usage.md +305 -0
  580. package/examples/extensions/README.md +1 -0
  581. package/examples/extensions/border-status-editor.ts +145 -0
  582. package/examples/extensions/built-in-tool-renderer.ts +3 -0
  583. package/examples/extensions/custom-compaction.ts +2 -1
  584. package/examples/extensions/custom-header.ts +1 -1
  585. package/examples/extensions/custom-provider-anthropic/index.ts +2 -2
  586. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  587. package/examples/extensions/custom-provider-anthropic/package.json +2 -2
  588. package/examples/extensions/custom-provider-gitlab-duo/index.ts +63 -8
  589. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  590. package/examples/extensions/custom-provider-gitlab-duo/test.ts +2 -2
  591. package/examples/extensions/doom-overlay/doom-component.ts +2 -2
  592. package/examples/extensions/doom-overlay/index.ts +1 -1
  593. package/examples/extensions/dynamic-resources/dynamic.json +1 -1
  594. package/examples/extensions/dynamic-tools.ts +2 -2
  595. package/examples/extensions/entry-renderer.ts +41 -0
  596. package/examples/extensions/git-merge-and-resolve.ts +115 -0
  597. package/examples/extensions/github-issue-autocomplete.ts +185 -0
  598. package/examples/extensions/gondolin/index.ts +531 -0
  599. package/examples/extensions/gondolin/package-lock.json +185 -0
  600. package/examples/extensions/gondolin/package.json +19 -0
  601. package/examples/extensions/handoff.ts +52 -14
  602. package/examples/extensions/input-transform-streaming.ts +39 -0
  603. package/examples/extensions/interactive-shell.ts +1 -1
  604. package/examples/extensions/notify.ts +2 -9
  605. package/examples/extensions/overlay-qa-tests.ts +240 -138
  606. package/examples/extensions/overlay-test.ts +7 -4
  607. package/examples/extensions/plan-mode/index.ts +87 -37
  608. package/examples/extensions/plan-mode/utils.ts +1 -1
  609. package/examples/extensions/preset.ts +46 -7
  610. package/examples/extensions/project-trust.ts +64 -0
  611. package/examples/extensions/prompt-customizer.ts +97 -0
  612. package/examples/extensions/provider-payload.ts +8 -4
  613. package/examples/extensions/qna.ts +3 -3
  614. package/examples/extensions/question.ts +34 -20
  615. package/examples/extensions/questionnaire.ts +43 -30
  616. package/examples/extensions/reload-runtime.ts +1 -1
  617. package/examples/extensions/sandbox/index.ts +6 -6
  618. package/examples/extensions/sandbox/package-lock.json +5 -5
  619. package/examples/extensions/sandbox/package.json +2 -2
  620. package/examples/extensions/shutdown-command.ts +1 -1
  621. package/examples/extensions/snake.ts +1 -1
  622. package/examples/extensions/space-invaders.ts +1 -1
  623. package/examples/extensions/structured-output.ts +65 -0
  624. package/examples/extensions/subagent/agents.ts +2 -2
  625. package/examples/extensions/subagent/index.ts +58 -29
  626. package/examples/extensions/summarize.ts +3 -2
  627. package/examples/extensions/tic-tac-toe.ts +1008 -0
  628. package/examples/extensions/titlebar-spinner.ts +2 -2
  629. package/examples/extensions/todo.ts +2 -2
  630. package/examples/extensions/tool-override.ts +1 -1
  631. package/examples/extensions/tools.ts +5 -0
  632. package/examples/extensions/truncated-tool.ts +1 -1
  633. package/examples/extensions/with-deps/index.ts +1 -1
  634. package/examples/extensions/with-deps/package-lock.json +2 -2
  635. package/examples/extensions/with-deps/package.json +3 -3
  636. package/examples/extensions/working-indicator.ts +123 -0
  637. package/examples/extensions/working-message-test.ts +25 -0
  638. package/examples/sdk/01-minimal.ts +14 -10
  639. package/examples/sdk/02-custom-model.ts +13 -9
  640. package/examples/sdk/03-custom-prompt.ts +32 -17
  641. package/examples/sdk/04-skills.ts +5 -2
  642. package/examples/sdk/05-tools.ts +23 -31
  643. package/examples/sdk/06-extensions.ts +14 -8
  644. package/examples/sdk/07-context-files.ts +5 -3
  645. package/examples/sdk/08-prompt-templates.ts +5 -2
  646. package/examples/sdk/09-api-keys-and-oauth.ts +8 -4
  647. package/examples/sdk/10-settings.ts +8 -6
  648. package/examples/sdk/11-sessions.ts +4 -0
  649. package/examples/sdk/12-full-control.ts +15 -19
  650. package/package.json +22 -16
  651. package/prompts/commands/brainstorm.md +148 -0
  652. package/prompts/commands/map-codebase.md +14 -0
@@ -13,25 +13,27 @@
13
13
  * Modes use this class and add their own I/O layer on top.
14
14
  */
15
15
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
- import { basename, dirname, join, resolve } from "node:path";
17
- import { isContextOverflow, modelsAreEqual, resetApiProviders, supportsMax, supportsXhigh } from "@draht/ai";
18
- import { getDocsPath } from "../config.js";
19
- import { theme } from "../modes/interactive/theme/theme.js";
16
+ import { basename, dirname } from "node:path";
17
+ import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, isRetryableAssistantError, modelsAreEqual, resetApiProviders, streamSimple, } from "@draht/ai/compat";
18
+ import { getThemeByName, theme } from "../modes/interactive/theme/theme.js";
20
19
  import { stripFrontmatter } from "../utils/frontmatter.js";
20
+ import { resolvePath } from "../utils/paths.js";
21
21
  import { sleep } from "../utils/sleep.js";
22
+ import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
22
23
  import { executeBashWithOperations } from "./bash-executor.js";
23
- import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
24
+ import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
24
25
  import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
25
26
  import { exportSessionToHtml } from "./export-html/index.js";
26
27
  import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
27
28
  import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
29
+ import { emitSessionShutdownEvent } from "./extensions/runner.js";
28
30
  import { expandPromptTemplate } from "./prompt-templates.js";
29
31
  import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
30
32
  import { createSyntheticSourceInfo } from "./source-info.js";
31
33
  import { buildSystemPrompt } from "./system-prompt.js";
32
34
  import { createLocalBashOperations } from "./tools/bash.js";
33
35
  import { createAllToolDefinitions } from "./tools/index.js";
34
- import { createToolDefinitionFromAgentTool, wrapToolDefinition } from "./tools/tool-definition-wrapper.js";
36
+ import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
35
37
  /**
36
38
  * Parse a skill block from message text.
37
39
  * Returns null if the text doesn't contain a skill block.
@@ -47,15 +49,18 @@ export function parseSkillBlock(text) {
47
49
  userMessage: match[4]?.trim() || undefined,
48
50
  };
49
51
  }
52
+ function estimateMessagesTokens(messages) {
53
+ let tokens = 0;
54
+ for (const message of messages) {
55
+ tokens += estimateTokens(message);
56
+ }
57
+ return tokens;
58
+ }
50
59
  // ============================================================================
51
60
  // Constants
52
61
  // ============================================================================
53
62
  /** Standard thinking levels */
54
63
  const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
55
- /** Thinking levels including xhigh (for supported models) */
56
- const THINKING_LEVELS_WITH_XHIGH = ["off", "minimal", "low", "medium", "high", "xhigh"];
57
- /** Thinking levels including xhigh and max (Anthropic Opus only) */
58
- const THINKING_LEVELS_WITH_MAX = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
59
64
  // ============================================================================
60
65
  // AgentSession Class
61
66
  // ============================================================================
@@ -67,7 +72,6 @@ export class AgentSession {
67
72
  // Event subscription state
68
73
  _unsubscribeAgent;
69
74
  _eventListeners = [];
70
- _agentEventQueue = Promise.resolve();
71
75
  /** Tracks pending steering messages for UI display. Removed when delivered. */
72
76
  _steeringMessages = [];
73
77
  /** Tracks pending follow-up messages for UI display. Removed when delivered. */
@@ -83,13 +87,11 @@ export class AgentSession {
83
87
  // Retry state
84
88
  _retryAbortController = undefined;
85
89
  _retryAttempt = 0;
86
- _retryPromise = undefined;
87
- _retryResolve = undefined;
88
90
  // Bash execution state
89
91
  _bashAbortController = undefined;
90
92
  _pendingBashMessages = [];
91
93
  // Extension system
92
- _extensionRunner = undefined;
94
+ _extensionRunner;
93
95
  _turnIndex = 0;
94
96
  _resourceLoader;
95
97
  _customTools;
@@ -97,10 +99,14 @@ export class AgentSession {
97
99
  _cwd;
98
100
  _extensionRunnerRef;
99
101
  _initialActiveToolNames;
102
+ _allowedToolNames;
103
+ _excludedToolNames;
100
104
  _baseToolsOverride;
101
105
  _sessionStartEvent;
102
106
  _extensionUIContext;
107
+ _extensionMode = "print";
103
108
  _extensionCommandContextActions;
109
+ _extensionAbortHandler;
104
110
  _extensionShutdownHandler;
105
111
  _extensionErrorListener;
106
112
  _extensionErrorUnsubscriber;
@@ -113,6 +119,8 @@ export class AgentSession {
113
119
  _toolPromptGuidelines = new Map();
114
120
  // Base system prompt (without extension appends) - used to apply fresh appends each turn
115
121
  _baseSystemPrompt = "";
122
+ _baseSystemPromptOptions;
123
+ _systemPromptOverride;
116
124
  constructor(config) {
117
125
  this.agent = config.agent;
118
126
  this.sessionManager = config.sessionManager;
@@ -124,12 +132,15 @@ export class AgentSession {
124
132
  this._modelRegistry = config.modelRegistry;
125
133
  this._extensionRunnerRef = config.extensionRunnerRef;
126
134
  this._initialActiveToolNames = config.initialActiveToolNames;
135
+ this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
136
+ this._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;
127
137
  this._baseToolsOverride = config.baseToolsOverride;
128
138
  this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
129
139
  // Always subscribe to agent events for internal handling
130
140
  // (session persistence, extensions, auto-compaction, retry logic)
131
141
  this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
132
142
  this._installAgentToolHooks();
143
+ this._installAgentNextTurnRefresh();
133
144
  this._buildRuntime({
134
145
  activeToolNames: this._initialActiveToolNames,
135
146
  includeAllExtensionTools: true,
@@ -142,10 +153,13 @@ export class AgentSession {
142
153
  async _getRequiredRequestAuth(model) {
143
154
  const result = await this._modelRegistry.getApiKeyAndHeaders(model);
144
155
  if (!result.ok) {
156
+ if (result.error.startsWith("No API key found")) {
157
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
158
+ }
145
159
  throw new Error(result.error);
146
160
  }
147
161
  if (result.apiKey) {
148
- return { apiKey: result.apiKey, headers: result.headers };
162
+ return { apiKey: result.apiKey, headers: result.headers, env: result.env };
149
163
  }
150
164
  const isOAuth = this._modelRegistry.isUsingOAuth(model);
151
165
  if (isOAuth) {
@@ -153,8 +167,14 @@ export class AgentSession {
153
167
  `Credentials may have expired or network is unavailable. ` +
154
168
  `Run '/login ${model.provider}' to re-authenticate.`);
155
169
  }
156
- throw new Error(`No API key found for ${model.provider}.\n\n` +
157
- `Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`);
170
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
171
+ }
172
+ async _getCompactionRequestAuth(model) {
173
+ if (this.agent.streamFn === streamSimple) {
174
+ return this._getRequiredRequestAuth(model);
175
+ }
176
+ const result = await this._modelRegistry.getApiKeyAndHeaders(model);
177
+ return result.ok ? { apiKey: result.apiKey, headers: result.headers, env: result.env } : {};
158
178
  }
159
179
  /**
160
180
  * Install tool hooks once on the Agent instance.
@@ -167,10 +187,9 @@ export class AgentSession {
167
187
  _installAgentToolHooks() {
168
188
  this.agent.beforeToolCall = async ({ toolCall, args }) => {
169
189
  const runner = this._extensionRunner;
170
- if (!runner?.hasHandlers("tool_call")) {
190
+ if (!runner.hasHandlers("tool_call")) {
171
191
  return undefined;
172
192
  }
173
- await this._agentEventQueue;
174
193
  try {
175
194
  return await runner.emitToolCall({
176
195
  type: "tool_call",
@@ -188,7 +207,7 @@ export class AgentSession {
188
207
  };
189
208
  this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
190
209
  const runner = this._extensionRunner;
191
- if (!runner?.hasHandlers("tool_result")) {
210
+ if (!runner.hasHandlers("tool_result")) {
192
211
  return undefined;
193
212
  }
194
213
  const hookResult = await runner.emitToolResult({
@@ -197,15 +216,36 @@ export class AgentSession {
197
216
  toolCallId: toolCall.id,
198
217
  input: args,
199
218
  content: result.content,
200
- details: isError ? undefined : result.details,
219
+ details: result.details,
201
220
  isError,
202
221
  });
203
- if (!hookResult || isError) {
222
+ if (!hookResult) {
204
223
  return undefined;
205
224
  }
206
225
  return {
207
226
  content: hookResult.content,
208
227
  details: hookResult.details,
228
+ isError: hookResult.isError ?? isError,
229
+ };
230
+ };
231
+ }
232
+ _installAgentNextTurnRefresh() {
233
+ const previousPrepareNextTurnWithContext = this.agent.prepareNextTurnWithContext ??
234
+ (this.agent.prepareNextTurn
235
+ ? async (_turn, signal) => await this.agent.prepareNextTurn?.(signal)
236
+ : undefined);
237
+ this.agent.prepareNextTurnWithContext = async (turn, signal) => {
238
+ const previousSnapshot = await previousPrepareNextTurnWithContext?.(turn, signal);
239
+ const previousContext = previousSnapshot?.context ?? turn.context;
240
+ return {
241
+ ...previousSnapshot,
242
+ context: {
243
+ ...previousContext,
244
+ systemPrompt: this._systemPromptOverride ?? this._baseSystemPrompt,
245
+ tools: this.agent.state.tools.slice(),
246
+ },
247
+ model: this.agent.state.model,
248
+ thinkingLevel: this.agent.state.thinkingLevel,
209
249
  };
210
250
  };
211
251
  }
@@ -228,43 +268,7 @@ export class AgentSession {
228
268
  // Track last assistant message for auto-compaction check
229
269
  _lastAssistantMessage = undefined;
230
270
  /** Internal handler for agent events - shared by subscribe and reconnect */
231
- _handleAgentEvent = (event) => {
232
- // Create retry promise synchronously before queueing async processing.
233
- // Agent.emit() calls this handler synchronously, and prompt() calls waitForRetry()
234
- // as soon as agent.prompt() resolves. If _retryPromise is created only inside
235
- // _processAgentEvent, slow earlier queued events can delay agent_end processing
236
- // and waitForRetry() can miss the in-flight retry.
237
- this._createRetryPromiseForAgentEnd(event);
238
- this._agentEventQueue = this._agentEventQueue.then(() => this._processAgentEvent(event), () => this._processAgentEvent(event));
239
- // Keep queue alive if an event handler fails
240
- this._agentEventQueue.catch(() => { });
241
- };
242
- _createRetryPromiseForAgentEnd(event) {
243
- if (event.type !== "agent_end" || this._retryPromise) {
244
- return;
245
- }
246
- const settings = this.settingsManager.getRetrySettings();
247
- if (!settings.enabled) {
248
- return;
249
- }
250
- const lastAssistant = this._findLastAssistantInMessages(event.messages);
251
- if (!lastAssistant || !this._isRetryableError(lastAssistant)) {
252
- return;
253
- }
254
- this._retryPromise = new Promise((resolve) => {
255
- this._retryResolve = resolve;
256
- });
257
- }
258
- _findLastAssistantInMessages(messages) {
259
- for (let i = messages.length - 1; i >= 0; i--) {
260
- const message = messages[i];
261
- if (message.role === "assistant") {
262
- return message;
263
- }
264
- }
265
- return undefined;
266
- }
267
- async _processAgentEvent(event) {
271
+ _handleAgentEvent = async (event) => {
268
272
  // When a user message starts, check if it's from either queue and remove it BEFORE emitting
269
273
  // This ensures the UI sees the updated queue state
270
274
  if (event.type === "message_start" && event.message.role === "user") {
@@ -290,7 +294,7 @@ export class AgentSession {
290
294
  // Emit to extensions first
291
295
  await this._emitExtensionEvent(event);
292
296
  // Notify all listeners
293
- this._emit(event);
297
+ this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
294
298
  // Handle session persistence
295
299
  if (event.type === "message_end") {
296
300
  // Check if this is a custom message from extensions
@@ -324,27 +328,19 @@ export class AgentSession {
324
328
  }
325
329
  }
326
330
  }
327
- // Check auto-retry and auto-compaction after agent completes
328
- if (event.type === "agent_end" && this._lastAssistantMessage) {
329
- const msg = this._lastAssistantMessage;
330
- this._lastAssistantMessage = undefined;
331
- // Check for retryable errors first (overloaded, rate limit, server errors)
332
- if (this._isRetryableError(msg)) {
333
- const didRetry = await this._handleRetryableError(msg);
334
- if (didRetry)
335
- return; // Retry was initiated, don't proceed to compaction
336
- }
337
- this._resolveRetry();
338
- await this._checkCompaction(msg);
331
+ };
332
+ _willRetryAfterAgentEnd(event) {
333
+ const settings = this.settingsManager.getRetrySettings();
334
+ if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
335
+ return false;
339
336
  }
340
- }
341
- /** Resolve the pending retry promise */
342
- _resolveRetry() {
343
- if (this._retryResolve) {
344
- this._retryResolve();
345
- this._retryResolve = undefined;
346
- this._retryPromise = undefined;
337
+ for (let i = event.messages.length - 1; i >= 0; i--) {
338
+ const message = event.messages[i];
339
+ if (message.role === "assistant") {
340
+ return this._isRetryableError(message);
341
+ }
347
342
  }
343
+ return false;
348
344
  }
349
345
  /** Extract text content from a message */
350
346
  _getUserMessageText(message) {
@@ -367,10 +363,22 @@ export class AgentSession {
367
363
  }
368
364
  return undefined;
369
365
  }
366
+ _replaceMessageInPlace(target, replacement) {
367
+ // Agent-core stores the finalized message object in its state before emitting message_end.
368
+ // SessionManager persistence happens later in _handleAgentEvent() with event.message.
369
+ // Mutating this object in place keeps agent state, later turn/agent events, listeners,
370
+ // and the eventual SessionManager.appendMessage(event.message) persistence in sync.
371
+ if (target === replacement) {
372
+ return;
373
+ }
374
+ const targetRecord = target;
375
+ for (const key of Object.keys(targetRecord)) {
376
+ delete targetRecord[key];
377
+ }
378
+ Object.assign(targetRecord, replacement);
379
+ }
370
380
  /** Emit extension events based on agent events */
371
381
  async _emitExtensionEvent(event) {
372
- if (!this._extensionRunner)
373
- return;
374
382
  if (event.type === "agent_start") {
375
383
  this._turnIndex = 0;
376
384
  await this._extensionRunner.emit({ type: "agent_start" });
@@ -416,7 +424,19 @@ export class AgentSession {
416
424
  type: "message_end",
417
425
  message: event.message,
418
426
  };
419
- await this._extensionRunner.emit(extensionEvent);
427
+ const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
428
+ if (replacement) {
429
+ // Untyped extension handlers can return messages with null/missing content;
430
+ // normalize so it never enters agent state or session history.
431
+ const normalized = (replacement.role === "user" ||
432
+ replacement.role === "assistant" ||
433
+ replacement.role === "toolResult" ||
434
+ replacement.role === "custom") &&
435
+ replacement.content == null
436
+ ? { ...replacement, content: [] }
437
+ : replacement;
438
+ this._replaceMessageInPlace(event.message, normalized);
439
+ }
420
440
  }
421
441
  else if (event.type === "tool_execution_start") {
422
442
  const extensionEvent = {
@@ -488,8 +508,20 @@ export class AgentSession {
488
508
  * Call this when completely done with the session.
489
509
  */
490
510
  dispose() {
511
+ try {
512
+ this.abortRetry();
513
+ this.abortCompaction();
514
+ this.abortBranchSummary();
515
+ this.abortBash();
516
+ this.agent.abort();
517
+ }
518
+ catch {
519
+ // Dispose must succeed even if an abort hook throws.
520
+ }
521
+ 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().");
491
522
  this._disconnectFromAgent();
492
523
  this._eventListeners = [];
524
+ cleanupSessionResources(this.sessionId);
493
525
  }
494
526
  // =========================================================================
495
527
  // Read-only State Access
@@ -526,13 +558,14 @@ export class AgentSession {
526
558
  return this.agent.state.tools.map((t) => t.name);
527
559
  }
528
560
  /**
529
- * Get all configured tools with name, description, parameter schema, and source metadata.
561
+ * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
530
562
  */
531
563
  getAllTools() {
532
564
  return Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({
533
565
  name: definition.name,
534
566
  description: definition.description,
535
567
  parameters: definition.parameters,
568
+ promptGuidelines: definition.promptGuidelines,
536
569
  sourceInfo,
537
570
  }));
538
571
  }
@@ -558,7 +591,7 @@ export class AgentSession {
558
591
  this.agent.state.tools = tools;
559
592
  // Rebuild base system prompt with new tool set
560
593
  this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
561
- this.agent.state.systemPrompt = this._baseSystemPrompt;
594
+ this.agent.state.systemPrompt = this._systemPromptOverride ?? this._baseSystemPrompt;
562
595
  }
563
596
  /** Whether compaction or branch summarization is currently running */
564
597
  get isCompacting() {
@@ -643,7 +676,7 @@ export class AgentSession {
643
676
  const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
644
677
  const loadedSkills = this._resourceLoader.getSkills().skills;
645
678
  const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
646
- return buildSystemPrompt({
679
+ this._baseSystemPromptOptions = {
647
680
  cwd: this._cwd,
648
681
  skills: loadedSkills,
649
682
  contextFiles: loadedContextFiles,
@@ -652,11 +685,49 @@ export class AgentSession {
652
685
  selectedTools: validToolNames,
653
686
  toolSnippets,
654
687
  promptGuidelines,
655
- });
688
+ };
689
+ return buildSystemPrompt(this._baseSystemPromptOptions);
656
690
  }
657
691
  // =========================================================================
658
692
  // Prompting
659
693
  // =========================================================================
694
+ async _runAgentPrompt(messages) {
695
+ try {
696
+ await this.agent.prompt(messages);
697
+ while (await this._handlePostAgentRun()) {
698
+ await this.agent.continue();
699
+ }
700
+ }
701
+ finally {
702
+ this._systemPromptOverride = undefined;
703
+ this._flushPendingBashMessages();
704
+ }
705
+ }
706
+ async _handlePostAgentRun() {
707
+ const msg = this._lastAssistantMessage;
708
+ this._lastAssistantMessage = undefined;
709
+ if (!msg) {
710
+ return false;
711
+ }
712
+ if (this._isRetryableError(msg) && (await this._prepareRetry(msg))) {
713
+ return true;
714
+ }
715
+ if (msg.stopReason === "error" && this._retryAttempt > 0) {
716
+ this._emit({
717
+ type: "auto_retry_end",
718
+ success: false,
719
+ attempt: this._retryAttempt,
720
+ finalError: msg.errorMessage,
721
+ });
722
+ this._retryAttempt = 0;
723
+ }
724
+ if (await this._checkCompaction(msg)) {
725
+ return true;
726
+ }
727
+ // The agent loop drains both queues before emitting agent_end. Any messages
728
+ // here were queued by agent_end extension handlers and need a continuation.
729
+ return this.agent.hasQueuedMessages();
730
+ }
660
731
  /**
661
732
  * Send a prompt to the agent.
662
733
  * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
@@ -668,97 +739,101 @@ export class AgentSession {
668
739
  */
669
740
  async prompt(text, options) {
670
741
  const expandPromptTemplates = options?.expandPromptTemplates ?? true;
671
- // Handle extension commands first (execute immediately, even during streaming)
672
- // Extension commands manage their own LLM interaction via pi.sendMessage()
673
- if (expandPromptTemplates && text.startsWith("/")) {
674
- const handled = await this._tryExecuteExtensionCommand(text);
675
- if (handled) {
676
- // Extension command executed, no prompt to send
677
- return;
678
- }
679
- }
680
- // Emit input event for extension interception (before skill/template expansion)
681
- let currentText = text;
682
- let currentImages = options?.images;
683
- if (this._extensionRunner?.hasHandlers("input")) {
684
- const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive");
685
- if (inputResult.action === "handled") {
686
- return;
742
+ const preflightResult = options?.preflightResult;
743
+ let messages;
744
+ try {
745
+ // Handle extension commands first (execute immediately, even during streaming)
746
+ // Extension commands manage their own LLM interaction via pi.sendMessage()
747
+ if (expandPromptTemplates && text.startsWith("/")) {
748
+ const handled = await this._tryExecuteExtensionCommand(text);
749
+ if (handled) {
750
+ // Extension command executed, no prompt to send
751
+ preflightResult?.(true);
752
+ return;
753
+ }
687
754
  }
688
- if (inputResult.action === "transform") {
689
- currentText = inputResult.text;
690
- currentImages = inputResult.images ?? currentImages;
755
+ // Emit input event for extension interception (before skill/template expansion)
756
+ let currentText = text;
757
+ let currentImages = options?.images;
758
+ if (this._extensionRunner.hasHandlers("input")) {
759
+ const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
760
+ if (inputResult.action === "handled") {
761
+ preflightResult?.(true);
762
+ return;
763
+ }
764
+ if (inputResult.action === "transform") {
765
+ currentText = inputResult.text;
766
+ currentImages = inputResult.images ?? currentImages;
767
+ }
691
768
  }
692
- }
693
- // Expand skill commands (/skill:name args) and prompt templates (/template args)
694
- let expandedText = currentText;
695
- if (expandPromptTemplates) {
696
- expandedText = this._expandSkillCommand(expandedText);
697
- expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
698
- }
699
- // If streaming, queue via steer() or followUp() based on option
700
- if (this.isStreaming) {
701
- if (!options?.streamingBehavior) {
702
- throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
769
+ // Expand skill commands (/skill:name args) and prompt templates (/template args)
770
+ let expandedText = currentText;
771
+ if (expandPromptTemplates) {
772
+ expandedText = this._expandSkillCommand(expandedText);
773
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
703
774
  }
704
- if (options.streamingBehavior === "followUp") {
705
- await this._queueFollowUp(expandedText, currentImages);
775
+ // If streaming, queue via steer() or followUp() based on option
776
+ if (this.isStreaming) {
777
+ if (!options?.streamingBehavior) {
778
+ throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
779
+ }
780
+ if (options.streamingBehavior === "followUp") {
781
+ await this._queueFollowUp(expandedText, currentImages);
782
+ }
783
+ else {
784
+ await this._queueSteer(expandedText, currentImages);
785
+ }
786
+ preflightResult?.(true);
787
+ return;
706
788
  }
707
- else {
708
- await this._queueSteer(expandedText, currentImages);
789
+ // Flush any pending bash messages before the new prompt
790
+ this._flushPendingBashMessages();
791
+ // Validate model
792
+ if (!this.model) {
793
+ throw new Error(formatNoModelSelectedMessage());
794
+ }
795
+ if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
796
+ const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
797
+ if (isOAuth) {
798
+ throw new Error(`Authentication failed for "${this.model.provider}". ` +
799
+ `Credentials may have expired or network is unavailable. ` +
800
+ `Run '/login ${this.model.provider}' to re-authenticate.`);
801
+ }
802
+ throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
803
+ }
804
+ // Check if we need to compact before sending (catches aborted responses).
805
+ // The user's new prompt is sent below, so do not call agent.continue() here.
806
+ const lastAssistant = this._findLastAssistantMessage();
807
+ if (lastAssistant) {
808
+ await this._checkCompaction(lastAssistant, false);
809
+ }
810
+ // Build messages array (custom message if any, then user message)
811
+ messages = [];
812
+ // Add user message
813
+ const userContent = [{ type: "text", text: expandedText }];
814
+ if (currentImages) {
815
+ userContent.push(...currentImages);
816
+ }
817
+ messages.push({
818
+ role: "user",
819
+ content: userContent,
820
+ timestamp: Date.now(),
821
+ });
822
+ // Inject any pending "nextTurn" messages as context alongside the user message
823
+ for (const msg of this._pendingNextTurnMessages) {
824
+ messages.push(msg);
709
825
  }
710
- return;
711
- }
712
- // Flush any pending bash messages before the new prompt
713
- this._flushPendingBashMessages();
714
- // Validate model
715
- if (!this.model) {
716
- throw new Error("No model selected.\n\n" +
717
- `Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}\n\n` +
718
- "Then use /model to select a model.");
719
- }
720
- if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
721
- const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
722
- if (isOAuth) {
723
- throw new Error(`Authentication failed for "${this.model.provider}". ` +
724
- `Credentials may have expired or network is unavailable. ` +
725
- `Run '/login ${this.model.provider}' to re-authenticate.`);
726
- }
727
- throw new Error(`No API key found for ${this.model.provider}.\n\n` +
728
- `Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`);
729
- }
730
- // Check if we need to compact before sending (catches aborted responses)
731
- const lastAssistant = this._findLastAssistantMessage();
732
- if (lastAssistant) {
733
- await this._checkCompaction(lastAssistant, false);
734
- }
735
- // Build messages array (custom message if any, then user message)
736
- const messages = [];
737
- // Add user message
738
- const userContent = [{ type: "text", text: expandedText }];
739
- if (currentImages) {
740
- userContent.push(...currentImages);
741
- }
742
- messages.push({
743
- role: "user",
744
- content: userContent,
745
- timestamp: Date.now(),
746
- });
747
- // Inject any pending "nextTurn" messages as context alongside the user message
748
- for (const msg of this._pendingNextTurnMessages) {
749
- messages.push(msg);
750
- }
751
- this._pendingNextTurnMessages = [];
752
- // Emit before_agent_start extension event
753
- if (this._extensionRunner) {
754
- const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt);
826
+ this._pendingNextTurnMessages = [];
827
+ // Emit before_agent_start extension event
828
+ const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt, this._baseSystemPromptOptions);
755
829
  // Add all custom messages from extensions
756
830
  if (result?.messages) {
757
831
  for (const msg of result.messages) {
758
832
  messages.push({
759
833
  role: "custom",
760
834
  customType: msg.customType,
761
- content: msg.content,
835
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
836
+ content: msg.content ?? [],
762
837
  display: msg.display,
763
838
  details: msg.details,
764
839
  timestamp: Date.now(),
@@ -766,23 +841,30 @@ export class AgentSession {
766
841
  }
767
842
  }
768
843
  // Apply extension-modified system prompt, or reset to base
769
- if (result?.systemPrompt) {
844
+ if (result?.systemPrompt !== undefined) {
845
+ this._systemPromptOverride = result.systemPrompt;
770
846
  this.agent.state.systemPrompt = result.systemPrompt;
771
847
  }
772
848
  else {
773
849
  // Ensure we're using the base prompt (in case previous turn had modifications)
850
+ this._systemPromptOverride = undefined;
774
851
  this.agent.state.systemPrompt = this._baseSystemPrompt;
775
852
  }
776
853
  }
777
- await this.agent.prompt(messages);
778
- await this.waitForRetry();
854
+ catch (error) {
855
+ preflightResult?.(false);
856
+ throw error;
857
+ }
858
+ if (!messages) {
859
+ return;
860
+ }
861
+ preflightResult?.(true);
862
+ await this._runAgentPrompt(messages);
779
863
  }
780
864
  /**
781
865
  * Try to execute an extension command. Returns true if command was found and executed.
782
866
  */
783
867
  async _tryExecuteExtensionCommand(text) {
784
- if (!this._extensionRunner)
785
- return false;
786
868
  // Parse command name and args
787
869
  const spaceIndex = text.indexOf(" ");
788
870
  const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
@@ -828,7 +910,7 @@ export class AgentSession {
828
910
  }
829
911
  catch (err) {
830
912
  // Emit error like extension commands do
831
- this._extensionRunner?.emitError({
913
+ this._extensionRunner.emitError({
832
914
  extensionPath: skill.filePath,
833
915
  event: "skill_expansion",
834
916
  error: err instanceof Error ? err.message : String(err),
@@ -907,8 +989,6 @@ export class AgentSession {
907
989
  * Throw an error if the text is an extension command.
908
990
  */
909
991
  _throwIfExtensionCommand(text) {
910
- if (!this._extensionRunner)
911
- return;
912
992
  const spaceIndex = text.indexOf(" ");
913
993
  const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
914
994
  const command = this._extensionRunner.getCommand(commandName);
@@ -932,7 +1012,8 @@ export class AgentSession {
932
1012
  const appMessage = {
933
1013
  role: "custom",
934
1014
  customType: message.customType,
935
- content: message.content,
1015
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
1016
+ content: message.content ?? [],
936
1017
  display: message.display,
937
1018
  details: message.details,
938
1019
  timestamp: Date.now(),
@@ -949,7 +1030,7 @@ export class AgentSession {
949
1030
  }
950
1031
  }
951
1032
  else if (options?.triggerTurn) {
952
- await this.agent.prompt(appMessage);
1033
+ await this._runAgentPrompt(appMessage);
953
1034
  }
954
1035
  else {
955
1036
  this.agent.state.messages.push(appMessage);
@@ -1036,8 +1117,6 @@ export class AgentSession {
1036
1117
  // Model Management
1037
1118
  // =========================================================================
1038
1119
  async _emitModelSelect(nextModel, previousModel, source) {
1039
- if (!this._extensionRunner)
1040
- return;
1041
1120
  if (modelsAreEqual(previousModel, nextModel))
1042
1121
  return;
1043
1122
  await this._extensionRunner.emit({
@@ -1133,13 +1212,20 @@ export class AgentSession {
1133
1212
  const availableLevels = this.getAvailableThinkingLevels();
1134
1213
  const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
1135
1214
  // Only persist if actually changing
1136
- const isChanging = effectiveLevel !== this.agent.state.thinkingLevel;
1215
+ const previousLevel = this.agent.state.thinkingLevel;
1216
+ const isChanging = effectiveLevel !== previousLevel;
1137
1217
  this.agent.state.thinkingLevel = effectiveLevel;
1138
1218
  if (isChanging) {
1139
1219
  this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1140
1220
  if (this.supportsThinking() || effectiveLevel !== "off") {
1141
1221
  this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
1142
1222
  }
1223
+ this._emit({ type: "thinking_level_changed", level: effectiveLevel });
1224
+ void this._extensionRunner.emit({
1225
+ type: "thinking_level_select",
1226
+ level: effectiveLevel,
1227
+ previousLevel,
1228
+ });
1143
1229
  }
1144
1230
  }
1145
1231
  /**
@@ -1161,23 +1247,9 @@ export class AgentSession {
1161
1247
  * The provider will clamp to what the specific model supports internally.
1162
1248
  */
1163
1249
  getAvailableThinkingLevels() {
1164
- if (!this.supportsThinking())
1165
- return ["off"];
1166
- if (this.supportsMaxThinking())
1167
- return THINKING_LEVELS_WITH_MAX;
1168
- return this.supportsXhighThinking() ? THINKING_LEVELS_WITH_XHIGH : THINKING_LEVELS;
1169
- }
1170
- /**
1171
- * Check if current model supports xhigh thinking level.
1172
- */
1173
- supportsXhighThinking() {
1174
- return this.model ? supportsXhigh(this.model) : false;
1175
- }
1176
- /**
1177
- * Check if current model supports the `max` thinking level (Anthropic Opus 4.6/4.7 only).
1178
- */
1179
- supportsMaxThinking() {
1180
- return this.model ? supportsMax(this.model) : false;
1250
+ if (!this.model)
1251
+ return THINKING_LEVELS;
1252
+ return getSupportedThinkingLevels(this.model);
1181
1253
  }
1182
1254
  /**
1183
1255
  * Check if current model supports thinking/reasoning.
@@ -1194,28 +1266,16 @@ export class AgentSession {
1194
1266
  }
1195
1267
  return this.thinkingLevel;
1196
1268
  }
1197
- _clampThinkingLevel(level, availableLevels) {
1198
- const ordered = THINKING_LEVELS_WITH_MAX;
1199
- const available = new Set(availableLevels);
1200
- const requestedIndex = ordered.indexOf(level);
1201
- if (requestedIndex === -1) {
1202
- return availableLevels[0] ?? "off";
1203
- }
1204
- for (let i = requestedIndex; i < ordered.length; i++) {
1205
- const candidate = ordered[i];
1206
- if (available.has(candidate))
1207
- return candidate;
1208
- }
1209
- for (let i = requestedIndex - 1; i >= 0; i--) {
1210
- const candidate = ordered[i];
1211
- if (available.has(candidate))
1212
- return candidate;
1213
- }
1214
- return availableLevels[0] ?? "off";
1269
+ _clampThinkingLevel(level, _availableLevels) {
1270
+ return this.model ? clampThinkingLevel(this.model, level) : "off";
1215
1271
  }
1216
1272
  // =========================================================================
1217
1273
  // Queue Mode Management
1218
1274
  // =========================================================================
1275
+ syncQueueModesFromSettings() {
1276
+ this.agent.steeringMode = this.settingsManager.getSteeringMode();
1277
+ this.agent.followUpMode = this.settingsManager.getFollowUpMode();
1278
+ }
1219
1279
  /**
1220
1280
  * Set steering message mode.
1221
1281
  * Saves to settings.
@@ -1247,9 +1307,9 @@ export class AgentSession {
1247
1307
  this._emit({ type: "compaction_start", reason: "manual" });
1248
1308
  try {
1249
1309
  if (!this.model) {
1250
- throw new Error("No model selected");
1310
+ throw new Error(formatNoModelSelectedMessage());
1251
1311
  }
1252
- const { apiKey, headers } = await this._getRequiredRequestAuth(this.model);
1312
+ const { apiKey, headers, env } = await this._getCompactionRequestAuth(this.model);
1253
1313
  const pathEntries = this.sessionManager.getBranch();
1254
1314
  const settings = this.settingsManager.getCompactionSettings();
1255
1315
  const preparation = prepareCompaction(pathEntries, settings);
@@ -1263,12 +1323,14 @@ export class AgentSession {
1263
1323
  }
1264
1324
  let extensionCompaction;
1265
1325
  let fromExtension = false;
1266
- if (this._extensionRunner?.hasHandlers("session_before_compact")) {
1326
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1267
1327
  const result = (await this._extensionRunner.emit({
1268
1328
  type: "session_before_compact",
1269
1329
  preparation,
1270
1330
  branchEntries: pathEntries,
1271
1331
  customInstructions,
1332
+ reason: "manual",
1333
+ willRetry: false,
1272
1334
  signal: this._compactionAbortController.signal,
1273
1335
  }));
1274
1336
  if (result?.cancel) {
@@ -1292,7 +1354,7 @@ export class AgentSession {
1292
1354
  }
1293
1355
  else {
1294
1356
  // Generate compaction result
1295
- const result = await compact(preparation, this.model, apiKey, headers, customInstructions, this._compactionAbortController.signal);
1357
+ const result = await compact(preparation, this.model, apiKey, headers, customInstructions, this._compactionAbortController.signal, this.thinkingLevel, this.agent.streamFn, env);
1296
1358
  summary = result.summary;
1297
1359
  firstKeptEntryId = result.firstKeptEntryId;
1298
1360
  tokensBefore = result.tokensBefore;
@@ -1305,6 +1367,7 @@ export class AgentSession {
1305
1367
  const newEntries = this.sessionManager.getEntries();
1306
1368
  const sessionContext = this.sessionManager.buildSessionContext();
1307
1369
  this.agent.state.messages = sessionContext.messages;
1370
+ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
1308
1371
  // Get the saved compaction entry for the extension event
1309
1372
  const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1310
1373
  if (this._extensionRunner && savedCompactionEntry) {
@@ -1312,12 +1375,15 @@ export class AgentSession {
1312
1375
  type: "session_compact",
1313
1376
  compactionEntry: savedCompactionEntry,
1314
1377
  fromExtension,
1378
+ reason: "manual",
1379
+ willRetry: false,
1315
1380
  });
1316
1381
  }
1317
1382
  const compactionResult = {
1318
1383
  summary,
1319
1384
  firstKeptEntryId,
1320
1385
  tokensBefore,
1386
+ estimatedTokensAfter,
1321
1387
  details,
1322
1388
  };
1323
1389
  this._emit({
@@ -1374,10 +1440,10 @@ export class AgentSession {
1374
1440
  async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
1375
1441
  const settings = this.settingsManager.getCompactionSettings();
1376
1442
  if (!settings.enabled)
1377
- return;
1443
+ return false;
1378
1444
  // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
1379
1445
  if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
1380
- return;
1446
+ return false;
1381
1447
  const contextWindow = this.model?.contextWindow ?? 0;
1382
1448
  // Skip overflow check if the message came from a different model.
1383
1449
  // This handles the case where user switched from a smaller-context model (e.g. opus)
@@ -1390,10 +1456,17 @@ export class AgentSession {
1390
1456
  const compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());
1391
1457
  const assistantIsFromBeforeCompaction = compactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();
1392
1458
  if (assistantIsFromBeforeCompaction) {
1393
- return;
1459
+ return false;
1394
1460
  }
1395
- // Case 1: Overflow - LLM returned context overflow error
1461
+ // Case 1: Overflow - LLM returned context overflow error, or reported usage exceeded
1462
+ // the configured window. A successful response over the configured window should compact
1463
+ // but must not retry: the assistant answer already completed and agent.continue() cannot
1464
+ // continue from an assistant message.
1396
1465
  if (sameModel && isContextOverflow(assistantMessage, contextWindow)) {
1466
+ const willRetry = assistantMessage.stopReason !== "stop";
1467
+ if (!willRetry) {
1468
+ return await this._runAutoCompaction("overflow", false);
1469
+ }
1397
1470
  if (this._overflowRecoveryAttempted) {
1398
1471
  this._emit({
1399
1472
  type: "compaction_end",
@@ -1403,7 +1476,7 @@ export class AgentSession {
1403
1476
  willRetry: false,
1404
1477
  errorMessage: "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
1405
1478
  });
1406
- return;
1479
+ return false;
1407
1480
  }
1408
1481
  this._overflowRecoveryAttempted = true;
1409
1482
  // Remove the error message from agent state (it IS saved to session for history,
@@ -1412,18 +1485,19 @@ export class AgentSession {
1412
1485
  if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1413
1486
  this.agent.state.messages = messages.slice(0, -1);
1414
1487
  }
1415
- await this._runAutoCompaction("overflow", true);
1416
- return;
1488
+ return await this._runAutoCompaction("overflow", willRetry);
1417
1489
  }
1418
1490
  // Case 2: Threshold - context is getting large
1419
- // For error messages (no usage data), estimate from last successful response.
1420
- // This ensures sessions that hit persistent API errors (e.g. 529) can still compact.
1491
+ // For error messages or all-zero usage messages, estimate from the last valid response.
1492
+ // This ensures sessions that hit persistent API errors (e.g. 529) or malformed zero-usage
1493
+ // responses can still compact and do not reset context accounting.
1421
1494
  let contextTokens;
1422
- if (assistantMessage.stopReason === "error") {
1495
+ const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
1496
+ if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
1423
1497
  const messages = this.agent.state.messages;
1424
1498
  const estimate = estimateContextTokens(messages);
1425
1499
  if (estimate.lastUsageIndex === null)
1426
- return; // No usage data at all
1500
+ return false; // No usage data at all
1427
1501
  // Verify the usage source is post-compaction. Kept pre-compaction messages
1428
1502
  // have stale usage reflecting the old (larger) context and would falsely
1429
1503
  // trigger compaction right after one just finished.
@@ -1431,67 +1505,61 @@ export class AgentSession {
1431
1505
  if (compactionEntry &&
1432
1506
  usageMsg.role === "assistant" &&
1433
1507
  usageMsg.timestamp <= new Date(compactionEntry.timestamp).getTime()) {
1434
- return;
1508
+ return false;
1435
1509
  }
1436
1510
  contextTokens = estimate.tokens;
1437
1511
  }
1438
1512
  else {
1439
- contextTokens = calculateContextTokens(assistantMessage.usage);
1513
+ contextTokens = directContextTokens;
1440
1514
  }
1441
1515
  if (shouldCompact(contextTokens, contextWindow, settings)) {
1442
- await this._runAutoCompaction("threshold", false);
1516
+ return await this._runAutoCompaction("threshold", false);
1443
1517
  }
1518
+ return false;
1444
1519
  }
1445
1520
  /**
1446
1521
  * Internal: Run auto-compaction with events.
1447
1522
  */
1448
1523
  async _runAutoCompaction(reason, willRetry) {
1449
1524
  const settings = this.settingsManager.getCompactionSettings();
1450
- this._emit({ type: "compaction_start", reason });
1451
- this._autoCompactionAbortController = new AbortController();
1525
+ let started = false;
1452
1526
  try {
1453
1527
  if (!this.model) {
1454
- this._emit({
1455
- type: "compaction_end",
1456
- reason,
1457
- result: undefined,
1458
- aborted: false,
1459
- willRetry: false,
1460
- });
1461
- return;
1528
+ return false;
1462
1529
  }
1463
- const authResult = await this._modelRegistry.getApiKeyAndHeaders(this.model);
1464
- if (!authResult.ok || !authResult.apiKey) {
1465
- this._emit({
1466
- type: "compaction_end",
1467
- reason,
1468
- result: undefined,
1469
- aborted: false,
1470
- willRetry: false,
1471
- });
1472
- return;
1530
+ let apiKey;
1531
+ let headers;
1532
+ let env;
1533
+ if (this.agent.streamFn === streamSimple) {
1534
+ const authResult = await this._modelRegistry.getApiKeyAndHeaders(this.model);
1535
+ if (!authResult.ok || !authResult.apiKey) {
1536
+ return false;
1537
+ }
1538
+ apiKey = authResult.apiKey;
1539
+ headers = authResult.headers;
1540
+ env = authResult.env;
1541
+ }
1542
+ else {
1543
+ ({ apiKey, headers, env } = await this._getCompactionRequestAuth(this.model));
1473
1544
  }
1474
- const { apiKey, headers } = authResult;
1475
1545
  const pathEntries = this.sessionManager.getBranch();
1476
1546
  const preparation = prepareCompaction(pathEntries, settings);
1477
1547
  if (!preparation) {
1478
- this._emit({
1479
- type: "compaction_end",
1480
- reason,
1481
- result: undefined,
1482
- aborted: false,
1483
- willRetry: false,
1484
- });
1485
- return;
1548
+ return false;
1486
1549
  }
1550
+ this._emit({ type: "compaction_start", reason });
1551
+ this._autoCompactionAbortController = new AbortController();
1552
+ started = true;
1487
1553
  let extensionCompaction;
1488
1554
  let fromExtension = false;
1489
- if (this._extensionRunner?.hasHandlers("session_before_compact")) {
1555
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1490
1556
  const extensionResult = (await this._extensionRunner.emit({
1491
1557
  type: "session_before_compact",
1492
1558
  preparation,
1493
1559
  branchEntries: pathEntries,
1494
1560
  customInstructions: undefined,
1561
+ reason,
1562
+ willRetry,
1495
1563
  signal: this._autoCompactionAbortController.signal,
1496
1564
  }));
1497
1565
  if (extensionResult?.cancel) {
@@ -1502,7 +1570,7 @@ export class AgentSession {
1502
1570
  aborted: true,
1503
1571
  willRetry: false,
1504
1572
  });
1505
- return;
1573
+ return false;
1506
1574
  }
1507
1575
  if (extensionResult?.compaction) {
1508
1576
  extensionCompaction = extensionResult.compaction;
@@ -1522,7 +1590,7 @@ export class AgentSession {
1522
1590
  }
1523
1591
  else {
1524
1592
  // Generate compaction result
1525
- const compactResult = await compact(preparation, this.model, apiKey, headers, undefined, this._autoCompactionAbortController.signal);
1593
+ const compactResult = await compact(preparation, this.model, apiKey, headers, undefined, this._autoCompactionAbortController.signal, this.thinkingLevel, this.agent.streamFn, env);
1526
1594
  summary = compactResult.summary;
1527
1595
  firstKeptEntryId = compactResult.firstKeptEntryId;
1528
1596
  tokensBefore = compactResult.tokensBefore;
@@ -1536,12 +1604,13 @@ export class AgentSession {
1536
1604
  aborted: true,
1537
1605
  willRetry: false,
1538
1606
  });
1539
- return;
1607
+ return false;
1540
1608
  }
1541
1609
  this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
1542
1610
  const newEntries = this.sessionManager.getEntries();
1543
1611
  const sessionContext = this.sessionManager.buildSessionContext();
1544
1612
  this.agent.state.messages = sessionContext.messages;
1613
+ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
1545
1614
  // Get the saved compaction entry for the extension event
1546
1615
  const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1547
1616
  if (this._extensionRunner && savedCompactionEntry) {
@@ -1549,12 +1618,15 @@ export class AgentSession {
1549
1618
  type: "session_compact",
1550
1619
  compactionEntry: savedCompactionEntry,
1551
1620
  fromExtension,
1621
+ reason,
1622
+ willRetry,
1552
1623
  });
1553
1624
  }
1554
1625
  const result = {
1555
1626
  summary,
1556
1627
  firstKeptEntryId,
1557
1628
  tokensBefore,
1629
+ estimatedTokensAfter,
1558
1630
  details,
1559
1631
  };
1560
1632
  this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
@@ -1564,30 +1636,27 @@ export class AgentSession {
1564
1636
  if (lastMsg?.role === "assistant" && lastMsg.stopReason === "error") {
1565
1637
  this.agent.state.messages = messages.slice(0, -1);
1566
1638
  }
1567
- setTimeout(() => {
1568
- this.agent.continue().catch(() => { });
1569
- }, 100);
1570
- }
1571
- else if (this.agent.hasQueuedMessages()) {
1572
- // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
1573
- // Kick the loop so queued messages are actually delivered.
1574
- setTimeout(() => {
1575
- this.agent.continue().catch(() => { });
1576
- }, 100);
1639
+ return true;
1577
1640
  }
1641
+ // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
1642
+ // Continue once so queued messages are delivered.
1643
+ return this.agent.hasQueuedMessages();
1578
1644
  }
1579
1645
  catch (error) {
1580
1646
  const errorMessage = error instanceof Error ? error.message : "compaction failed";
1581
- this._emit({
1582
- type: "compaction_end",
1583
- reason,
1584
- result: undefined,
1585
- aborted: false,
1586
- willRetry: false,
1587
- errorMessage: reason === "overflow"
1588
- ? `Context overflow recovery failed: ${errorMessage}`
1589
- : `Auto-compaction failed: ${errorMessage}`,
1590
- });
1647
+ if (started) {
1648
+ this._emit({
1649
+ type: "compaction_end",
1650
+ reason,
1651
+ result: undefined,
1652
+ aborted: false,
1653
+ willRetry: false,
1654
+ errorMessage: reason === "overflow"
1655
+ ? `Context overflow recovery failed: ${errorMessage}`
1656
+ : `Auto-compaction failed: ${errorMessage}`,
1657
+ });
1658
+ }
1659
+ return false;
1591
1660
  }
1592
1661
  finally {
1593
1662
  this._autoCompactionAbortController = undefined;
@@ -1607,23 +1676,27 @@ export class AgentSession {
1607
1676
  if (bindings.uiContext !== undefined) {
1608
1677
  this._extensionUIContext = bindings.uiContext;
1609
1678
  }
1679
+ if (bindings.mode !== undefined) {
1680
+ this._extensionMode = bindings.mode;
1681
+ }
1610
1682
  if (bindings.commandContextActions !== undefined) {
1611
1683
  this._extensionCommandContextActions = bindings.commandContextActions;
1612
1684
  }
1685
+ if (bindings.abortHandler !== undefined) {
1686
+ this._extensionAbortHandler = bindings.abortHandler;
1687
+ }
1613
1688
  if (bindings.shutdownHandler !== undefined) {
1614
1689
  this._extensionShutdownHandler = bindings.shutdownHandler;
1615
1690
  }
1616
1691
  if (bindings.onError !== undefined) {
1617
1692
  this._extensionErrorListener = bindings.onError;
1618
1693
  }
1619
- if (this._extensionRunner) {
1620
- this._applyExtensionBindings(this._extensionRunner);
1621
- await this._extensionRunner.emit(this._sessionStartEvent);
1622
- await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
1623
- }
1694
+ this._applyExtensionBindings(this._extensionRunner);
1695
+ await this._extensionRunner.emit(this._sessionStartEvent);
1696
+ await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
1624
1697
  }
1625
1698
  async extendResourcesFromExtensions(reason) {
1626
- if (!this._extensionRunner?.hasHandlers("resources_discover")) {
1699
+ if (!this._extensionRunner.hasHandlers("resources_discover")) {
1627
1700
  return;
1628
1701
  }
1629
1702
  const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(this._cwd, reason);
@@ -1663,7 +1736,7 @@ export class AgentSession {
1663
1736
  return `extension:${name}`;
1664
1737
  }
1665
1738
  _applyExtensionBindings(runner) {
1666
- runner.setUIContext(this._extensionUIContext);
1739
+ runner.setUIContext(this._extensionUIContext, this._extensionMode);
1667
1740
  runner.bindCommandContext(this._extensionCommandContextActions);
1668
1741
  this._extensionErrorUnsubscriber?.();
1669
1742
  this._extensionErrorUnsubscriber = this._extensionErrorListener
@@ -1723,10 +1796,14 @@ export class AgentSession {
1723
1796
  });
1724
1797
  },
1725
1798
  appendEntry: (customType, data) => {
1726
- this.sessionManager.appendCustomEntry(customType, data);
1799
+ const entryId = this.sessionManager.appendCustomEntry(customType, data);
1800
+ const entry = this.sessionManager.getEntry(entryId);
1801
+ if (entry) {
1802
+ this._emit({ type: "entry_appended", entry });
1803
+ }
1727
1804
  },
1728
1805
  setSessionName: (name) => {
1729
- this.sessionManager.appendSessionInfo(name);
1806
+ this.setSessionName(name);
1730
1807
  },
1731
1808
  getSessionName: () => {
1732
1809
  return this.sessionManager.getSessionName();
@@ -1750,8 +1827,15 @@ export class AgentSession {
1750
1827
  }, {
1751
1828
  getModel: () => this.model,
1752
1829
  isIdle: () => !this.isStreaming,
1830
+ isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
1753
1831
  getSignal: () => this.agent.signal,
1754
- abort: () => this.abort(),
1832
+ abort: () => {
1833
+ if (this._extensionAbortHandler) {
1834
+ this._extensionAbortHandler();
1835
+ return;
1836
+ }
1837
+ void this.abort();
1838
+ },
1755
1839
  hasPendingMessages: () => this.pendingMessageCount > 0,
1756
1840
  shutdown: () => {
1757
1841
  this._extensionShutdownHandler?.();
@@ -1770,6 +1854,7 @@ export class AgentSession {
1770
1854
  })();
1771
1855
  },
1772
1856
  getSystemPrompt: () => this.systemPrompt,
1857
+ getSystemPromptOptions: () => this._baseSystemPromptOptions,
1773
1858
  }, {
1774
1859
  registerProvider: (name, config) => {
1775
1860
  this._modelRegistry.registerProvider(name, config);
@@ -1784,15 +1869,20 @@ export class AgentSession {
1784
1869
  _refreshToolRegistry(options) {
1785
1870
  const previousRegistryNames = new Set(this._toolRegistry.keys());
1786
1871
  const previousActiveToolNames = this.getActiveToolNames();
1787
- const registeredTools = this._extensionRunner?.getAllRegisteredTools() ?? [];
1872
+ const allowedToolNames = this._allowedToolNames;
1873
+ const excludedToolNames = this._excludedToolNames;
1874
+ const isAllowedTool = (name) => (!allowedToolNames || allowedToolNames.has(name)) && !excludedToolNames?.has(name);
1875
+ const registeredTools = this._extensionRunner.getAllRegisteredTools();
1788
1876
  const allCustomTools = [
1789
1877
  ...registeredTools,
1790
1878
  ...this._customTools.map((definition) => ({
1791
1879
  definition,
1792
1880
  sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
1793
1881
  })),
1794
- ];
1795
- const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries()).map(([name, definition]) => [
1882
+ ].filter((tool) => isAllowedTool(tool.definition.name));
1883
+ const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
1884
+ .filter(([name]) => isAllowedTool(name))
1885
+ .map(([name, definition]) => [
1796
1886
  name,
1797
1887
  {
1798
1888
  definition,
@@ -1818,21 +1908,28 @@ export class AgentSession {
1818
1908
  return guidelines.length > 0 ? [definition.name, guidelines] : undefined;
1819
1909
  })
1820
1910
  .filter((entry) => entry !== undefined));
1821
- const wrappedExtensionTools = this._extensionRunner
1822
- ? wrapRegisteredTools(allCustomTools, this._extensionRunner)
1823
- : [];
1824
- const toolRegistry = new Map(Array.from(this._baseToolDefinitions.values()).map((definition) => [
1825
- definition.name,
1826
- wrapToolDefinition(definition),
1827
- ]));
1911
+ const runner = this._extensionRunner;
1912
+ const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
1913
+ const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
1914
+ .filter((definition) => isAllowedTool(definition.name))
1915
+ .map((definition) => ({
1916
+ definition,
1917
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
1918
+ })), runner);
1919
+ const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
1828
1920
  for (const tool of wrappedExtensionTools) {
1829
1921
  toolRegistry.set(tool.name, tool);
1830
1922
  }
1831
1923
  this._toolRegistry = toolRegistry;
1832
- const nextActiveToolNames = options?.activeToolNames
1833
- ? [...options.activeToolNames]
1834
- : [...previousActiveToolNames];
1835
- if (options?.includeAllExtensionTools) {
1924
+ const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => isAllowedTool(name));
1925
+ if (allowedToolNames) {
1926
+ for (const toolName of this._toolRegistry.keys()) {
1927
+ if (allowedToolNames.has(toolName)) {
1928
+ nextActiveToolNames.push(toolName);
1929
+ }
1930
+ }
1931
+ }
1932
+ else if (options?.includeAllExtensionTools) {
1836
1933
  for (const tool of wrappedExtensionTools) {
1837
1934
  nextActiveToolNames.push(tool.name);
1838
1935
  }
@@ -1849,6 +1946,7 @@ export class AgentSession {
1849
1946
  _buildRuntime(options) {
1850
1947
  const autoResizeImages = this.settingsManager.getImageAutoResize();
1851
1948
  const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
1949
+ const shellPath = this.settingsManager.getShellPath();
1852
1950
  const baseToolDefinitions = this._baseToolsOverride
1853
1951
  ? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
1854
1952
  name,
@@ -1856,7 +1954,7 @@ export class AgentSession {
1856
1954
  ]))
1857
1955
  : createAllToolDefinitions(this._cwd, {
1858
1956
  read: { autoResizeImages },
1859
- bash: { commandPrefix: shellCommandPrefix },
1957
+ bash: { commandPrefix: shellCommandPrefix, shellPath },
1860
1958
  });
1861
1959
  this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
1862
1960
  const extensionsResult = this._resourceLoader.getExtensions();
@@ -1865,19 +1963,12 @@ export class AgentSession {
1865
1963
  extensionsResult.runtime.flagValues.set(name, value);
1866
1964
  }
1867
1965
  }
1868
- const hasExtensions = extensionsResult.extensions.length > 0;
1869
- const hasCustomTools = this._customTools.length > 0;
1870
- this._extensionRunner =
1871
- hasExtensions || hasCustomTools
1872
- ? new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry)
1873
- : undefined;
1966
+ this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry);
1874
1967
  if (this._extensionRunnerRef) {
1875
1968
  this._extensionRunnerRef.current = this._extensionRunner;
1876
1969
  }
1877
- if (this._extensionRunner) {
1878
- this._bindExtensionCore(this._extensionRunner);
1879
- this._applyExtensionBindings(this._extensionRunner);
1880
- }
1970
+ this._bindExtensionCore(this._extensionRunner);
1971
+ this._applyExtensionBindings(this._extensionRunner);
1881
1972
  const defaultActiveToolNames = this._baseToolsOverride
1882
1973
  ? Object.keys(this._baseToolsOverride)
1883
1974
  : ["read", "bash", "edit", "write"];
@@ -1887,10 +1978,11 @@ export class AgentSession {
1887
1978
  includeAllExtensionTools: options.includeAllExtensionTools,
1888
1979
  });
1889
1980
  }
1890
- async reload() {
1891
- const previousFlagValues = this._extensionRunner?.getFlagValues();
1892
- await this._extensionRunner?.emit({ type: "session_shutdown" });
1981
+ async reload(options) {
1982
+ const previousFlagValues = this._extensionRunner.getFlagValues();
1983
+ await emitSessionShutdownEvent(this._extensionRunner, { type: "session_shutdown", reason: "reload" });
1893
1984
  await this.settingsManager.reload();
1985
+ this.syncQueueModesFromSettings();
1894
1986
  resetApiProviders();
1895
1987
  await this._resourceLoader.reload();
1896
1988
  this._buildRuntime({
@@ -1902,7 +1994,8 @@ export class AgentSession {
1902
1994
  this._extensionCommandContextActions ||
1903
1995
  this._extensionShutdownHandler ||
1904
1996
  this._extensionErrorListener;
1905
- if (this._extensionRunner && hasBindings) {
1997
+ if (hasBindings) {
1998
+ await options?.beforeSessionStart?.();
1906
1999
  await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
1907
2000
  await this.extendResourcesFromExtensions("reload");
1908
2001
  }
@@ -1915,44 +2008,24 @@ export class AgentSession {
1915
2008
  * Context overflow errors are NOT retryable (handled by compaction instead).
1916
2009
  */
1917
2010
  _isRetryableError(message) {
1918
- if (message.stopReason !== "error" || !message.errorMessage)
2011
+ // Context overflow is handled by compaction, not retry.
2012
+ if (isContextOverflow(message, this.model?.contextWindow ?? 0))
1919
2013
  return false;
1920
- // Context overflow is handled by compaction, not retry
1921
- const contextWindow = this.model?.contextWindow ?? 0;
1922
- if (isContextOverflow(message, contextWindow))
1923
- return false;
1924
- const err = message.errorMessage;
1925
- // Match: overloaded_error, provider returned error, rate limit, 429, 500, 502, 503, 504, service unavailable, network/connection errors, fetch failed, request ended without sending chunks, terminated, retry delay exceeded, peer-closed/incomplete-chunked stream truncations
1926
- return /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?reset|peer closed|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|incomplete.?chunked.?read|chunked.?read|premature.?close|timed? out|timeout|terminated|retry delay/i.test(err);
2014
+ return isRetryableAssistantError(message);
1927
2015
  }
1928
2016
  /**
1929
- * Handle retryable errors with exponential backoff.
1930
- * @returns true if retry was initiated, false if max retries exceeded or disabled
2017
+ * Prepare a retryable error for continuation with exponential backoff.
2018
+ * @returns true if the caller should continue the agent, false otherwise
1931
2019
  */
1932
- async _handleRetryableError(message) {
2020
+ async _prepareRetry(message) {
1933
2021
  const settings = this.settingsManager.getRetrySettings();
1934
2022
  if (!settings.enabled) {
1935
- this._resolveRetry();
1936
2023
  return false;
1937
2024
  }
1938
- // Retry promise is created synchronously in _handleAgentEvent for agent_end.
1939
- // Keep a defensive fallback here in case a future refactor bypasses that path.
1940
- if (!this._retryPromise) {
1941
- this._retryPromise = new Promise((resolve) => {
1942
- this._retryResolve = resolve;
1943
- });
1944
- }
1945
2025
  this._retryAttempt++;
1946
2026
  if (this._retryAttempt > settings.maxRetries) {
1947
- // Max retries exceeded, emit final failure and reset
1948
- this._emit({
1949
- type: "auto_retry_end",
1950
- success: false,
1951
- attempt: this._retryAttempt - 1,
1952
- finalError: message.errorMessage,
1953
- });
1954
- this._retryAttempt = 0;
1955
- this._resolveRetry(); // Resolve so waitForRetry() completes
2027
+ // Preserve the completed attempt count so post-run handling can emit the final failure.
2028
+ this._retryAttempt--;
1956
2029
  return false;
1957
2030
  }
1958
2031
  const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
@@ -1977,23 +2050,17 @@ export class AgentSession {
1977
2050
  // Aborted during sleep - emit end event so UI can clean up
1978
2051
  const attempt = this._retryAttempt;
1979
2052
  this._retryAttempt = 0;
1980
- this._retryAbortController = undefined;
1981
2053
  this._emit({
1982
2054
  type: "auto_retry_end",
1983
2055
  success: false,
1984
2056
  attempt,
1985
2057
  finalError: "Retry cancelled",
1986
2058
  });
1987
- this._resolveRetry();
1988
2059
  return false;
1989
2060
  }
1990
- this._retryAbortController = undefined;
1991
- // Retry via continue() - use setTimeout to break out of event handler chain
1992
- setTimeout(() => {
1993
- this.agent.continue().catch(() => {
1994
- // Retry failed - will be caught by next agent_end
1995
- });
1996
- }, 0);
2061
+ finally {
2062
+ this._retryAbortController = undefined;
2063
+ }
1997
2064
  return true;
1998
2065
  }
1999
2066
  /**
@@ -2001,23 +2068,10 @@ export class AgentSession {
2001
2068
  */
2002
2069
  abortRetry() {
2003
2070
  this._retryAbortController?.abort();
2004
- // Note: _retryAttempt is reset in the catch block of _autoRetry
2005
- this._resolveRetry();
2006
- }
2007
- /**
2008
- * Wait for any in-progress retry to complete.
2009
- * Returns immediately if no retry is in progress.
2010
- */
2011
- async waitForRetry() {
2012
- if (!this._retryPromise) {
2013
- return;
2014
- }
2015
- await this._retryPromise;
2016
- await this.agent.waitForIdle();
2017
2071
  }
2018
2072
  /** Whether auto-retry is currently in progress */
2019
2073
  get isRetrying() {
2020
- return this._retryPromise !== undefined;
2074
+ return this._retryAbortController !== undefined;
2021
2075
  }
2022
2076
  /** Whether auto-retry is enabled */
2023
2077
  get autoRetryEnabled() {
@@ -2044,9 +2098,10 @@ export class AgentSession {
2044
2098
  this._bashAbortController = new AbortController();
2045
2099
  // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
2046
2100
  const prefix = this.settingsManager.getShellCommandPrefix();
2101
+ const shellPath = this.settingsManager.getShellPath();
2047
2102
  const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
2048
2103
  try {
2049
- const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations(), {
2104
+ const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
2050
2105
  onChunk,
2051
2106
  signal: this._bashAbortController.signal,
2052
2107
  });
@@ -2122,6 +2177,9 @@ export class AgentSession {
2122
2177
  */
2123
2178
  setSessionName(name) {
2124
2179
  this.sessionManager.appendSessionInfo(name);
2180
+ const event = { type: "session_info_changed", name: this.sessionManager.getSessionName() };
2181
+ this._emit(event);
2182
+ void this._extensionRunner.emit(event);
2125
2183
  }
2126
2184
  // =========================================================================
2127
2185
  // Tree Navigation
@@ -2169,118 +2227,119 @@ export class AgentSession {
2169
2227
  };
2170
2228
  // Set up abort controller for summarization
2171
2229
  this._branchSummaryAbortController = new AbortController();
2172
- let extensionSummary;
2173
- let fromExtension = false;
2174
- // Emit session_before_tree event
2175
- if (this._extensionRunner?.hasHandlers("session_before_tree")) {
2176
- const result = (await this._extensionRunner.emit({
2177
- type: "session_before_tree",
2178
- preparation,
2179
- signal: this._branchSummaryAbortController.signal,
2180
- }));
2181
- if (result?.cancel) {
2182
- return { cancelled: true };
2183
- }
2184
- if (result?.summary && options.summarize) {
2185
- extensionSummary = result.summary;
2186
- fromExtension = true;
2187
- }
2188
- // Allow extensions to override instructions and label
2189
- if (result?.customInstructions !== undefined) {
2190
- customInstructions = result.customInstructions;
2191
- }
2192
- if (result?.replaceInstructions !== undefined) {
2193
- replaceInstructions = result.replaceInstructions;
2194
- }
2195
- if (result?.label !== undefined) {
2196
- label = result.label;
2197
- }
2198
- }
2199
- // Run default summarizer if needed
2200
- let summaryText;
2201
- let summaryDetails;
2202
- if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
2203
- const model = this.model;
2204
- const { apiKey, headers } = await this._getRequiredRequestAuth(model);
2205
- const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
2206
- const result = await generateBranchSummary(entriesToSummarize, {
2207
- model,
2208
- apiKey,
2209
- headers,
2210
- signal: this._branchSummaryAbortController.signal,
2211
- customInstructions,
2212
- replaceInstructions,
2213
- reserveTokens: branchSummarySettings.reserveTokens,
2214
- });
2215
- this._branchSummaryAbortController = undefined;
2216
- if (result.aborted) {
2217
- return { cancelled: true, aborted: true };
2230
+ try {
2231
+ let extensionSummary;
2232
+ let fromExtension = false;
2233
+ // Emit session_before_tree event
2234
+ if (this._extensionRunner.hasHandlers("session_before_tree")) {
2235
+ const result = (await this._extensionRunner.emit({
2236
+ type: "session_before_tree",
2237
+ preparation,
2238
+ signal: this._branchSummaryAbortController.signal,
2239
+ }));
2240
+ if (result?.cancel) {
2241
+ return { cancelled: true };
2242
+ }
2243
+ if (result?.summary && options.summarize) {
2244
+ extensionSummary = result.summary;
2245
+ fromExtension = true;
2246
+ }
2247
+ // Allow extensions to override instructions and label
2248
+ if (result?.customInstructions !== undefined) {
2249
+ customInstructions = result.customInstructions;
2250
+ }
2251
+ if (result?.replaceInstructions !== undefined) {
2252
+ replaceInstructions = result.replaceInstructions;
2253
+ }
2254
+ if (result?.label !== undefined) {
2255
+ label = result.label;
2256
+ }
2218
2257
  }
2219
- if (result.error) {
2220
- throw new Error(result.error);
2258
+ // Run default summarizer if needed
2259
+ let summaryText;
2260
+ let summaryDetails;
2261
+ if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
2262
+ const model = this.model;
2263
+ const { apiKey, headers, env } = await this._getRequiredRequestAuth(model);
2264
+ const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
2265
+ const result = await generateBranchSummary(entriesToSummarize, {
2266
+ model,
2267
+ apiKey,
2268
+ headers,
2269
+ env,
2270
+ signal: this._branchSummaryAbortController.signal,
2271
+ customInstructions,
2272
+ replaceInstructions,
2273
+ reserveTokens: branchSummarySettings.reserveTokens,
2274
+ streamFn: this.agent.streamFn,
2275
+ });
2276
+ if (result.aborted) {
2277
+ return { cancelled: true, aborted: true };
2278
+ }
2279
+ if (result.error) {
2280
+ throw new Error(result.error);
2281
+ }
2282
+ summaryText = result.summary;
2283
+ summaryDetails = {
2284
+ readFiles: result.readFiles || [],
2285
+ modifiedFiles: result.modifiedFiles || [],
2286
+ };
2287
+ }
2288
+ else if (extensionSummary) {
2289
+ summaryText = extensionSummary.summary;
2290
+ summaryDetails = extensionSummary.details;
2291
+ }
2292
+ // Determine the new leaf position based on target type
2293
+ let newLeafId;
2294
+ let editorText;
2295
+ if (targetEntry.type === "message" && targetEntry.message.role === "user") {
2296
+ // User message: leaf = parent (null if root), text goes to editor
2297
+ newLeafId = targetEntry.parentId;
2298
+ editorText = this._extractUserMessageText(targetEntry.message.content);
2299
+ }
2300
+ else if (targetEntry.type === "custom_message") {
2301
+ // Custom message: leaf = parent (null if root), text goes to editor
2302
+ newLeafId = targetEntry.parentId;
2303
+ editorText =
2304
+ typeof targetEntry.content === "string"
2305
+ ? targetEntry.content
2306
+ : targetEntry.content
2307
+ .filter((c) => c.type === "text")
2308
+ .map((c) => c.text)
2309
+ .join("");
2221
2310
  }
2222
- summaryText = result.summary;
2223
- summaryDetails = {
2224
- readFiles: result.readFiles || [],
2225
- modifiedFiles: result.modifiedFiles || [],
2226
- };
2227
- }
2228
- else if (extensionSummary) {
2229
- summaryText = extensionSummary.summary;
2230
- summaryDetails = extensionSummary.details;
2231
- }
2232
- // Determine the new leaf position based on target type
2233
- let newLeafId;
2234
- let editorText;
2235
- if (targetEntry.type === "message" && targetEntry.message.role === "user") {
2236
- // User message: leaf = parent (null if root), text goes to editor
2237
- newLeafId = targetEntry.parentId;
2238
- editorText = this._extractUserMessageText(targetEntry.message.content);
2239
- }
2240
- else if (targetEntry.type === "custom_message") {
2241
- // Custom message: leaf = parent (null if root), text goes to editor
2242
- newLeafId = targetEntry.parentId;
2243
- editorText =
2244
- typeof targetEntry.content === "string"
2245
- ? targetEntry.content
2246
- : targetEntry.content
2247
- .filter((c) => c.type === "text")
2248
- .map((c) => c.text)
2249
- .join("");
2250
- }
2251
- else {
2252
- // Non-user message: leaf = selected node
2253
- newLeafId = targetId;
2254
- }
2255
- // Switch leaf (with or without summary)
2256
- // Summary is attached at the navigation target position (newLeafId), not the old branch
2257
- let summaryEntry;
2258
- if (summaryText) {
2259
- // Create summary at target position (can be null for root)
2260
- const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
2261
- summaryEntry = this.sessionManager.getEntry(summaryId);
2262
- // Attach label to the summary entry
2263
- if (label) {
2264
- this.sessionManager.appendLabelChange(summaryId, label);
2311
+ else {
2312
+ // Non-user message: leaf = selected node
2313
+ newLeafId = targetId;
2314
+ }
2315
+ // Switch leaf (with or without summary)
2316
+ // Summary is attached at the navigation target position (newLeafId), not the old branch
2317
+ let summaryEntry;
2318
+ if (summaryText) {
2319
+ // Create summary at target position (can be null for root)
2320
+ const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
2321
+ summaryEntry = this.sessionManager.getEntry(summaryId);
2322
+ // Attach label to the summary entry
2323
+ if (label) {
2324
+ this.sessionManager.appendLabelChange(summaryId, label);
2325
+ }
2265
2326
  }
2266
- }
2267
- else if (newLeafId === null) {
2268
- // No summary, navigating to root - reset leaf
2269
- this.sessionManager.resetLeaf();
2270
- }
2271
- else {
2272
- // No summary, navigating to non-root
2273
- this.sessionManager.branch(newLeafId);
2274
- }
2275
- // Attach label to target entry when not summarizing (no summary entry to label)
2276
- if (label && !summaryText) {
2277
- this.sessionManager.appendLabelChange(targetId, label);
2278
- }
2279
- // Update agent state
2280
- const sessionContext = this.sessionManager.buildSessionContext();
2281
- this.agent.state.messages = sessionContext.messages;
2282
- // Emit session_tree event
2283
- if (this._extensionRunner) {
2327
+ else if (newLeafId === null) {
2328
+ // No summary, navigating to root - reset leaf
2329
+ this.sessionManager.resetLeaf();
2330
+ }
2331
+ else {
2332
+ // No summary, navigating to non-root
2333
+ this.sessionManager.branch(newLeafId);
2334
+ }
2335
+ // Attach label to target entry when not summarizing (no summary entry to label)
2336
+ if (label && !summaryText) {
2337
+ this.sessionManager.appendLabelChange(targetId, label);
2338
+ }
2339
+ // Update agent state
2340
+ const sessionContext = this.sessionManager.buildSessionContext();
2341
+ this.agent.state.messages = sessionContext.messages;
2342
+ // Emit session_tree event
2284
2343
  await this._extensionRunner.emit({
2285
2344
  type: "session_tree",
2286
2345
  newLeafId: this.sessionManager.getLeafId(),
@@ -2288,10 +2347,12 @@ export class AgentSession {
2288
2347
  summaryEntry,
2289
2348
  fromExtension: summaryText ? fromExtension : undefined,
2290
2349
  });
2350
+ // Emit to custom tools
2351
+ return { editorText, cancelled: false, summaryEntry };
2352
+ }
2353
+ finally {
2354
+ this._branchSummaryAbortController = undefined;
2291
2355
  }
2292
- // Emit to custom tools
2293
- this._branchSummaryAbortController = undefined;
2294
- return { editorText, cancelled: false, summaryEntry };
2295
2356
  }
2296
2357
  /**
2297
2358
  * Get all user messages from session for fork selector.
@@ -2390,8 +2451,8 @@ export class AgentSession {
2390
2451
  const contextTokens = calculateContextTokens(assistant.usage);
2391
2452
  if (contextTokens > 0) {
2392
2453
  hasPostCompactionUsage = true;
2454
+ break;
2393
2455
  }
2394
- break;
2395
2456
  }
2396
2457
  }
2397
2458
  }
@@ -2413,7 +2474,8 @@ export class AgentSession {
2413
2474
  * @returns Path to exported file
2414
2475
  */
2415
2476
  async exportToHtml(outputPath) {
2416
- const themeName = this.settingsManager.getTheme();
2477
+ const configuredThemeName = this.settingsManager.getTheme();
2478
+ const themeName = configuredThemeName && getThemeByName(configuredThemeName) ? configuredThemeName : undefined;
2417
2479
  // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
2418
2480
  const toolRenderer = createToolHtmlRenderer({
2419
2481
  getToolDefinition: (name) => this.getToolDefinition(name),
@@ -2433,7 +2495,7 @@ export class AgentSession {
2433
2495
  * @returns The resolved output file path.
2434
2496
  */
2435
2497
  exportToJsonl(outputPath) {
2436
- const filePath = resolve(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`);
2498
+ const filePath = resolvePath(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`, process.cwd());
2437
2499
  const dir = dirname(filePath);
2438
2500
  if (!existsSync(dir)) {
2439
2501
  mkdirSync(dir, { recursive: true });
@@ -2491,11 +2553,17 @@ export class AgentSession {
2491
2553
  // =========================================================================
2492
2554
  // Extension System
2493
2555
  // =========================================================================
2556
+ createReplacedSessionContext() {
2557
+ const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));
2558
+ context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
2559
+ context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
2560
+ return context;
2561
+ }
2494
2562
  /**
2495
2563
  * Check if extensions have handlers for a specific event type.
2496
2564
  */
2497
2565
  hasExtensionHandlers(eventType) {
2498
- return this._extensionRunner?.hasHandlers(eventType) ?? false;
2566
+ return this._extensionRunner.hasHandlers(eventType);
2499
2567
  }
2500
2568
  /**
2501
2569
  * Get the extension runner (for setting UI context and error handlers).