@hoilab/ada-cli 0.84.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (972) hide show
  1. package/CHANGELOG.md +5498 -0
  2. package/README.md +716 -0
  3. package/dist/bun/cli.d.ts +3 -0
  4. package/dist/bun/cli.d.ts.map +1 -0
  5. package/dist/bun/cli.js +11 -0
  6. package/dist/bun/cli.js.map +1 -0
  7. package/dist/bun/register-bedrock.d.ts +2 -0
  8. package/dist/bun/register-bedrock.d.ts.map +1 -0
  9. package/dist/bun/register-bedrock.js +4 -0
  10. package/dist/bun/register-bedrock.js.map +1 -0
  11. package/dist/bun/restore-sandbox-env.d.ts +17 -0
  12. package/dist/bun/restore-sandbox-env.d.ts.map +1 -0
  13. package/dist/bun/restore-sandbox-env.js +36 -0
  14. package/dist/bun/restore-sandbox-env.js.map +1 -0
  15. package/dist/cli/args.d.ts +60 -0
  16. package/dist/cli/args.d.ts.map +1 -0
  17. package/dist/cli/args.js +419 -0
  18. package/dist/cli/args.js.map +1 -0
  19. package/dist/cli/auth-check.d.ts +19 -0
  20. package/dist/cli/auth-check.d.ts.map +1 -0
  21. package/dist/cli/auth-check.js +50 -0
  22. package/dist/cli/auth-check.js.map +1 -0
  23. package/dist/cli/auth-command.d.ts +24 -0
  24. package/dist/cli/auth-command.d.ts.map +1 -0
  25. package/dist/cli/auth-command.js +103 -0
  26. package/dist/cli/auth-command.js.map +1 -0
  27. package/dist/cli/config-selector.d.ts +16 -0
  28. package/dist/cli/config-selector.d.ts.map +1 -0
  29. package/dist/cli/config-selector.js +31 -0
  30. package/dist/cli/config-selector.js.map +1 -0
  31. package/dist/cli/credential-print.d.ts +13 -0
  32. package/dist/cli/credential-print.d.ts.map +1 -0
  33. package/dist/cli/credential-print.js +76 -0
  34. package/dist/cli/credential-print.js.map +1 -0
  35. package/dist/cli/experimental/auth.d.ts +16 -0
  36. package/dist/cli/experimental/auth.d.ts.map +1 -0
  37. package/dist/cli/experimental/auth.js +13 -0
  38. package/dist/cli/experimental/auth.js.map +1 -0
  39. package/dist/cli/experimental/cli.d.ts +6 -0
  40. package/dist/cli/experimental/cli.d.ts.map +1 -0
  41. package/dist/cli/experimental/cli.js +5 -0
  42. package/dist/cli/experimental/cli.js.map +1 -0
  43. package/dist/cli/experimental/command-options.d.ts +17 -0
  44. package/dist/cli/experimental/command-options.d.ts.map +1 -0
  45. package/dist/cli/experimental/command-options.js +35 -0
  46. package/dist/cli/experimental/command-options.js.map +1 -0
  47. package/dist/cli/experimental/command.d.ts +63 -0
  48. package/dist/cli/experimental/command.d.ts.map +1 -0
  49. package/dist/cli/experimental/command.js +130 -0
  50. package/dist/cli/experimental/command.js.map +1 -0
  51. package/dist/cli/experimental/commands/client.d.ts +13 -0
  52. package/dist/cli/experimental/commands/client.d.ts.map +1 -0
  53. package/dist/cli/experimental/commands/client.js +25 -0
  54. package/dist/cli/experimental/commands/client.js.map +1 -0
  55. package/dist/cli/experimental/commands/pi.d.ts +15 -0
  56. package/dist/cli/experimental/commands/pi.d.ts.map +1 -0
  57. package/dist/cli/experimental/commands/pi.js +28 -0
  58. package/dist/cli/experimental/commands/pi.js.map +1 -0
  59. package/dist/cli/experimental/commands/server.d.ts +13 -0
  60. package/dist/cli/experimental/commands/server.d.ts.map +1 -0
  61. package/dist/cli/experimental/commands/server.js +25 -0
  62. package/dist/cli/experimental/commands/server.js.map +1 -0
  63. package/dist/cli/experimental/transport-address.d.ts +10 -0
  64. package/dist/cli/experimental/transport-address.d.ts.map +1 -0
  65. package/dist/cli/experimental/transport-address.js +38 -0
  66. package/dist/cli/experimental/transport-address.js.map +1 -0
  67. package/dist/cli/file-processor.d.ts +15 -0
  68. package/dist/cli/file-processor.d.ts.map +1 -0
  69. package/dist/cli/file-processor.js +70 -0
  70. package/dist/cli/file-processor.js.map +1 -0
  71. package/dist/cli/initial-message.d.ts +18 -0
  72. package/dist/cli/initial-message.d.ts.map +1 -0
  73. package/dist/cli/initial-message.js +22 -0
  74. package/dist/cli/initial-message.js.map +1 -0
  75. package/dist/cli/list-models.d.ts +9 -0
  76. package/dist/cli/list-models.d.ts.map +1 -0
  77. package/dist/cli/list-models.js +98 -0
  78. package/dist/cli/list-models.js.map +1 -0
  79. package/dist/cli/project-trust.d.ts +10 -0
  80. package/dist/cli/project-trust.d.ts.map +1 -0
  81. package/dist/cli/project-trust.js +48 -0
  82. package/dist/cli/project-trust.js.map +1 -0
  83. package/dist/cli/session-picker.d.ts +10 -0
  84. package/dist/cli/session-picker.d.ts.map +1 -0
  85. package/dist/cli/session-picker.js +36 -0
  86. package/dist/cli/session-picker.js.map +1 -0
  87. package/dist/cli/startup-ui.d.ts +20 -0
  88. package/dist/cli/startup-ui.d.ts.map +1 -0
  89. package/dist/cli/startup-ui.js +184 -0
  90. package/dist/cli/startup-ui.js.map +1 -0
  91. package/dist/cli.d.ts +3 -0
  92. package/dist/cli.d.ts.map +1 -0
  93. package/dist/cli.js +19 -0
  94. package/dist/cli.js.map +1 -0
  95. package/dist/client/index.d.ts +3 -0
  96. package/dist/client/index.d.ts.map +1 -0
  97. package/dist/client/index.js +3 -0
  98. package/dist/client/index.js.map +1 -0
  99. package/dist/client/remote-session.d.ts +53 -0
  100. package/dist/client/remote-session.d.ts.map +1 -0
  101. package/dist/client/remote-session.js +340 -0
  102. package/dist/client/remote-session.js.map +1 -0
  103. package/dist/client/transcript.d.ts +12 -0
  104. package/dist/client/transcript.d.ts.map +1 -0
  105. package/dist/client/transcript.js +98 -0
  106. package/dist/client/transcript.js.map +1 -0
  107. package/dist/config.d.ts +96 -0
  108. package/dist/config.d.ts.map +1 -0
  109. package/dist/config.js +455 -0
  110. package/dist/config.js.map +1 -0
  111. package/dist/core/agent-session-runtime.d.ts +119 -0
  112. package/dist/core/agent-session-runtime.d.ts.map +1 -0
  113. package/dist/core/agent-session-runtime.js +309 -0
  114. package/dist/core/agent-session-runtime.js.map +1 -0
  115. package/dist/core/agent-session-services.d.ts +86 -0
  116. package/dist/core/agent-session-services.d.ts.map +1 -0
  117. package/dist/core/agent-session-services.js +134 -0
  118. package/dist/core/agent-session-services.js.map +1 -0
  119. package/dist/core/agent-session.d.ts +649 -0
  120. package/dist/core/agent-session.d.ts.map +1 -0
  121. package/dist/core/agent-session.js +2687 -0
  122. package/dist/core/agent-session.js.map +1 -0
  123. package/dist/core/auth-guidance.d.ts +5 -0
  124. package/dist/core/auth-guidance.d.ts.map +1 -0
  125. package/dist/core/auth-guidance.js +21 -0
  126. package/dist/core/auth-guidance.js.map +1 -0
  127. package/dist/core/auth-storage.d.ts +72 -0
  128. package/dist/core/auth-storage.d.ts.map +1 -0
  129. package/dist/core/auth-storage.js +427 -0
  130. package/dist/core/auth-storage.js.map +1 -0
  131. package/dist/core/bash-executor.d.ts +32 -0
  132. package/dist/core/bash-executor.d.ts.map +1 -0
  133. package/dist/core/bash-executor.js +111 -0
  134. package/dist/core/bash-executor.js.map +1 -0
  135. package/dist/core/cache-stats.d.ts +49 -0
  136. package/dist/core/cache-stats.d.ts.map +1 -0
  137. package/dist/core/cache-stats.js +101 -0
  138. package/dist/core/cache-stats.js.map +1 -0
  139. package/dist/core/compaction/branch-summarization.d.ts +98 -0
  140. package/dist/core/compaction/branch-summarization.d.ts.map +1 -0
  141. package/dist/core/compaction/branch-summarization.js +246 -0
  142. package/dist/core/compaction/branch-summarization.js.map +1 -0
  143. package/dist/core/compaction/compaction.d.ts +137 -0
  144. package/dist/core/compaction/compaction.d.ts.map +1 -0
  145. package/dist/core/compaction/compaction.js +645 -0
  146. package/dist/core/compaction/compaction.js.map +1 -0
  147. package/dist/core/compaction/index.d.ts +7 -0
  148. package/dist/core/compaction/index.d.ts.map +1 -0
  149. package/dist/core/compaction/index.js +7 -0
  150. package/dist/core/compaction/index.js.map +1 -0
  151. package/dist/core/compaction/utils.d.ts +38 -0
  152. package/dist/core/compaction/utils.d.ts.map +1 -0
  153. package/dist/core/compaction/utils.js +142 -0
  154. package/dist/core/compaction/utils.js.map +1 -0
  155. package/dist/core/defaults.d.ts +3 -0
  156. package/dist/core/defaults.d.ts.map +1 -0
  157. package/dist/core/defaults.js +2 -0
  158. package/dist/core/defaults.js.map +1 -0
  159. package/dist/core/diagnostics.d.ts +15 -0
  160. package/dist/core/diagnostics.d.ts.map +1 -0
  161. package/dist/core/diagnostics.js +2 -0
  162. package/dist/core/diagnostics.js.map +1 -0
  163. package/dist/core/event-bus.d.ts +9 -0
  164. package/dist/core/event-bus.d.ts.map +1 -0
  165. package/dist/core/event-bus.js +25 -0
  166. package/dist/core/event-bus.js.map +1 -0
  167. package/dist/core/exec.d.ts +29 -0
  168. package/dist/core/exec.d.ts.map +1 -0
  169. package/dist/core/exec.js +75 -0
  170. package/dist/core/exec.js.map +1 -0
  171. package/dist/core/experimental.d.ts +6 -0
  172. package/dist/core/experimental.d.ts.map +1 -0
  173. package/dist/core/experimental.js +8 -0
  174. package/dist/core/experimental.js.map +1 -0
  175. package/dist/core/export-html/ansi-to-html.d.ts +22 -0
  176. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
  177. package/dist/core/export-html/ansi-to-html.js +249 -0
  178. package/dist/core/export-html/ansi-to-html.js.map +1 -0
  179. package/dist/core/export-html/index.d.ts +37 -0
  180. package/dist/core/export-html/index.d.ts.map +1 -0
  181. package/dist/core/export-html/index.js +226 -0
  182. package/dist/core/export-html/index.js.map +1 -0
  183. package/dist/core/export-html/template.css +1066 -0
  184. package/dist/core/export-html/template.html +55 -0
  185. package/dist/core/export-html/template.js +1864 -0
  186. package/dist/core/export-html/tool-renderer.d.ts +34 -0
  187. package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
  188. package/dist/core/export-html/tool-renderer.js +108 -0
  189. package/dist/core/export-html/tool-renderer.js.map +1 -0
  190. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  191. package/dist/core/export-html/vendor/marked.min.js +78 -0
  192. package/dist/core/extensions/index.d.ts +12 -0
  193. package/dist/core/extensions/index.d.ts.map +1 -0
  194. package/dist/core/extensions/index.js +9 -0
  195. package/dist/core/extensions/index.js.map +1 -0
  196. package/dist/core/extensions/loader.d.ts +23 -0
  197. package/dist/core/extensions/loader.d.ts.map +1 -0
  198. package/dist/core/extensions/loader.js +581 -0
  199. package/dist/core/extensions/loader.js.map +1 -0
  200. package/dist/core/extensions/runner.d.ts +173 -0
  201. package/dist/core/extensions/runner.d.ts.map +1 -0
  202. package/dist/core/extensions/runner.js +967 -0
  203. package/dist/core/extensions/runner.js.map +1 -0
  204. package/dist/core/extensions/types.d.ts +1299 -0
  205. package/dist/core/extensions/types.d.ts.map +1 -0
  206. package/dist/core/extensions/types.js +45 -0
  207. package/dist/core/extensions/types.js.map +1 -0
  208. package/dist/core/extensions/wrapper.d.ts +20 -0
  209. package/dist/core/extensions/wrapper.d.ts.map +1 -0
  210. package/dist/core/extensions/wrapper.js +41 -0
  211. package/dist/core/extensions/wrapper.js.map +1 -0
  212. package/dist/core/footer-data-provider.d.ts +64 -0
  213. package/dist/core/footer-data-provider.d.ts.map +1 -0
  214. package/dist/core/footer-data-provider.js +338 -0
  215. package/dist/core/footer-data-provider.js.map +1 -0
  216. package/dist/core/http-dispatcher.d.ts +22 -0
  217. package/dist/core/http-dispatcher.d.ts.map +1 -0
  218. package/dist/core/http-dispatcher.js +96 -0
  219. package/dist/core/http-dispatcher.js.map +1 -0
  220. package/dist/core/index.d.ts +13 -0
  221. package/dist/core/index.d.ts.map +1 -0
  222. package/dist/core/index.js +13 -0
  223. package/dist/core/index.js.map +1 -0
  224. package/dist/core/keybindings.d.ts +422 -0
  225. package/dist/core/keybindings.d.ts.map +1 -0
  226. package/dist/core/keybindings.js +296 -0
  227. package/dist/core/keybindings.js.map +1 -0
  228. package/dist/core/messages.d.ts +77 -0
  229. package/dist/core/messages.d.ts.map +1 -0
  230. package/dist/core/messages.js +123 -0
  231. package/dist/core/messages.js.map +1 -0
  232. package/dist/core/model-config.d.ts +571 -0
  233. package/dist/core/model-config.d.ts.map +1 -0
  234. package/dist/core/model-config.js +254 -0
  235. package/dist/core/model-config.js.map +1 -0
  236. package/dist/core/model-registry.d.ts +45 -0
  237. package/dist/core/model-registry.d.ts.map +1 -0
  238. package/dist/core/model-registry.js +107 -0
  239. package/dist/core/model-registry.js.map +1 -0
  240. package/dist/core/model-resolver.d.ts +123 -0
  241. package/dist/core/model-resolver.d.ts.map +1 -0
  242. package/dist/core/model-resolver.js +583 -0
  243. package/dist/core/model-resolver.js.map +1 -0
  244. package/dist/core/model-runtime.d.ts +100 -0
  245. package/dist/core/model-runtime.d.ts.map +1 -0
  246. package/dist/core/model-runtime.js +599 -0
  247. package/dist/core/model-runtime.js.map +1 -0
  248. package/dist/core/models-store.d.ts +22 -0
  249. package/dist/core/models-store.d.ts.map +1 -0
  250. package/dist/core/models-store.js +114 -0
  251. package/dist/core/models-store.js.map +1 -0
  252. package/dist/core/output-guard.d.ts +7 -0
  253. package/dist/core/output-guard.d.ts.map +1 -0
  254. package/dist/core/output-guard.js +89 -0
  255. package/dist/core/output-guard.js.map +1 -0
  256. package/dist/core/package-manager.d.ts +213 -0
  257. package/dist/core/package-manager.d.ts.map +1 -0
  258. package/dist/core/package-manager.js +2169 -0
  259. package/dist/core/package-manager.js.map +1 -0
  260. package/dist/core/pi-manifest.d.ts +8 -0
  261. package/dist/core/pi-manifest.d.ts.map +1 -0
  262. package/dist/core/pi-manifest.js +25 -0
  263. package/dist/core/pi-manifest.js.map +1 -0
  264. package/dist/core/project-trust.d.ts +15 -0
  265. package/dist/core/project-trust.d.ts.map +1 -0
  266. package/dist/core/project-trust.js +59 -0
  267. package/dist/core/project-trust.js.map +1 -0
  268. package/dist/core/prompt-templates.d.ts +54 -0
  269. package/dist/core/prompt-templates.d.ts.map +1 -0
  270. package/dist/core/prompt-templates.js +236 -0
  271. package/dist/core/prompt-templates.js.map +1 -0
  272. package/dist/core/provider-attribution.d.ts +4 -0
  273. package/dist/core/provider-attribution.d.ts.map +1 -0
  274. package/dist/core/provider-attribution.js +72 -0
  275. package/dist/core/provider-attribution.js.map +1 -0
  276. package/dist/core/provider-composer.d.ts +58 -0
  277. package/dist/core/provider-composer.d.ts.map +1 -0
  278. package/dist/core/provider-composer.js +396 -0
  279. package/dist/core/provider-composer.js.map +1 -0
  280. package/dist/core/radius.d.ts +2 -0
  281. package/dist/core/radius.d.ts.map +1 -0
  282. package/dist/core/radius.js +2 -0
  283. package/dist/core/radius.js.map +1 -0
  284. package/dist/core/remote-catalog-provider.d.ts +5 -0
  285. package/dist/core/remote-catalog-provider.d.ts.map +1 -0
  286. package/dist/core/remote-catalog-provider.js +121 -0
  287. package/dist/core/remote-catalog-provider.js.map +1 -0
  288. package/dist/core/resolve-config-value.d.ts +30 -0
  289. package/dist/core/resolve-config-value.d.ts.map +1 -0
  290. package/dist/core/resolve-config-value.js +247 -0
  291. package/dist/core/resolve-config-value.js.map +1 -0
  292. package/dist/core/resource-loader.d.ts +221 -0
  293. package/dist/core/resource-loader.d.ts.map +1 -0
  294. package/dist/core/resource-loader.js +874 -0
  295. package/dist/core/resource-loader.js.map +1 -0
  296. package/dist/core/runtime-credentials.d.ts +15 -0
  297. package/dist/core/runtime-credentials.d.ts.map +1 -0
  298. package/dist/core/runtime-credentials.js +39 -0
  299. package/dist/core/runtime-credentials.js.map +1 -0
  300. package/dist/core/sdk.d.ts +108 -0
  301. package/dist/core/sdk.d.ts.map +1 -0
  302. package/dist/core/sdk.js +268 -0
  303. package/dist/core/sdk.js.map +1 -0
  304. package/dist/core/session-cwd.d.ts +19 -0
  305. package/dist/core/session-cwd.d.ts.map +1 -0
  306. package/dist/core/session-cwd.js +38 -0
  307. package/dist/core/session-cwd.js.map +1 -0
  308. package/dist/core/session-manager.d.ts +356 -0
  309. package/dist/core/session-manager.d.ts.map +1 -0
  310. package/dist/core/session-manager.js +1340 -0
  311. package/dist/core/session-manager.js.map +1 -0
  312. package/dist/core/settings-manager.d.ts +315 -0
  313. package/dist/core/settings-manager.d.ts.map +1 -0
  314. package/dist/core/settings-manager.js +938 -0
  315. package/dist/core/settings-manager.js.map +1 -0
  316. package/dist/core/skills.d.ts +60 -0
  317. package/dist/core/skills.d.ts.map +1 -0
  318. package/dist/core/skills.js +387 -0
  319. package/dist/core/skills.js.map +1 -0
  320. package/dist/core/slash-commands.d.ts +15 -0
  321. package/dist/core/slash-commands.d.ts.map +1 -0
  322. package/dist/core/slash-commands.js +26 -0
  323. package/dist/core/slash-commands.js.map +1 -0
  324. package/dist/core/source-info.d.ts +18 -0
  325. package/dist/core/source-info.d.ts.map +1 -0
  326. package/dist/core/source-info.js +19 -0
  327. package/dist/core/source-info.js.map +1 -0
  328. package/dist/core/system-prompt.d.ts +28 -0
  329. package/dist/core/system-prompt.d.ts.map +1 -0
  330. package/dist/core/system-prompt.js +110 -0
  331. package/dist/core/system-prompt.js.map +1 -0
  332. package/dist/core/telemetry.d.ts +3 -0
  333. package/dist/core/telemetry.d.ts.map +1 -0
  334. package/dist/core/telemetry.js +9 -0
  335. package/dist/core/telemetry.js.map +1 -0
  336. package/dist/core/timings.d.ts +10 -0
  337. package/dist/core/timings.d.ts.map +1 -0
  338. package/dist/core/timings.js +41 -0
  339. package/dist/core/timings.js.map +1 -0
  340. package/dist/core/tools/bash.d.ts +74 -0
  341. package/dist/core/tools/bash.d.ts.map +1 -0
  342. package/dist/core/tools/bash.js +394 -0
  343. package/dist/core/tools/bash.js.map +1 -0
  344. package/dist/core/tools/edit-diff.d.ts +106 -0
  345. package/dist/core/tools/edit-diff.d.ts.map +1 -0
  346. package/dist/core/tools/edit-diff.js +424 -0
  347. package/dist/core/tools/edit-diff.js.map +1 -0
  348. package/dist/core/tools/edit.d.ts +55 -0
  349. package/dist/core/tools/edit.d.ts.map +1 -0
  350. package/dist/core/tools/edit.js +290 -0
  351. package/dist/core/tools/edit.js.map +1 -0
  352. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  353. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -0
  354. package/dist/core/tools/file-mutation-queue.js +52 -0
  355. package/dist/core/tools/file-mutation-queue.js.map +1 -0
  356. package/dist/core/tools/find.d.ts +42 -0
  357. package/dist/core/tools/find.d.ts.map +1 -0
  358. package/dist/core/tools/find.js +302 -0
  359. package/dist/core/tools/find.js.map +1 -0
  360. package/dist/core/tools/grep.d.ts +41 -0
  361. package/dist/core/tools/grep.d.ts.map +1 -0
  362. package/dist/core/tools/grep.js +308 -0
  363. package/dist/core/tools/grep.js.map +1 -0
  364. package/dist/core/tools/index.d.ts +40 -0
  365. package/dist/core/tools/index.d.ts.map +1 -0
  366. package/dist/core/tools/index.js +112 -0
  367. package/dist/core/tools/index.js.map +1 -0
  368. package/dist/core/tools/ls.d.ts +41 -0
  369. package/dist/core/tools/ls.d.ts.map +1 -0
  370. package/dist/core/tools/ls.js +171 -0
  371. package/dist/core/tools/ls.js.map +1 -0
  372. package/dist/core/tools/output-accumulator.d.ts +52 -0
  373. package/dist/core/tools/output-accumulator.d.ts.map +1 -0
  374. package/dist/core/tools/output-accumulator.js +184 -0
  375. package/dist/core/tools/output-accumulator.js.map +1 -0
  376. package/dist/core/tools/path-utils.d.ts +10 -0
  377. package/dist/core/tools/path-utils.d.ts.map +1 -0
  378. package/dist/core/tools/path-utils.js +99 -0
  379. package/dist/core/tools/path-utils.js.map +1 -0
  380. package/dist/core/tools/read.d.ts +39 -0
  381. package/dist/core/tools/read.d.ts.map +1 -0
  382. package/dist/core/tools/read.js +282 -0
  383. package/dist/core/tools/read.js.map +1 -0
  384. package/dist/core/tools/render-utils.d.ts +24 -0
  385. package/dist/core/tools/render-utils.d.ts.map +1 -0
  386. package/dist/core/tools/render-utils.js +65 -0
  387. package/dist/core/tools/render-utils.js.map +1 -0
  388. package/dist/core/tools/tool-definition-wrapper.d.ts +14 -0
  389. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -0
  390. package/dist/core/tools/tool-definition-wrapper.js +36 -0
  391. package/dist/core/tools/tool-definition-wrapper.js.map +1 -0
  392. package/dist/core/tools/truncate.d.ts +70 -0
  393. package/dist/core/tools/truncate.d.ts.map +1 -0
  394. package/dist/core/tools/truncate.js +215 -0
  395. package/dist/core/tools/truncate.js.map +1 -0
  396. package/dist/core/tools/write.d.ts +30 -0
  397. package/dist/core/tools/write.d.ts.map +1 -0
  398. package/dist/core/tools/write.js +203 -0
  399. package/dist/core/tools/write.js.map +1 -0
  400. package/dist/core/trust-manager.d.ts +36 -0
  401. package/dist/core/trust-manager.d.ts.map +1 -0
  402. package/dist/core/trust-manager.js +202 -0
  403. package/dist/core/trust-manager.js.map +1 -0
  404. package/dist/core/usage-totals.d.ts +19 -0
  405. package/dist/core/usage-totals.d.ts.map +1 -0
  406. package/dist/core/usage-totals.js +52 -0
  407. package/dist/core/usage-totals.js.map +1 -0
  408. package/dist/extensions/index.d.ts +3 -0
  409. package/dist/extensions/index.d.ts.map +1 -0
  410. package/dist/extensions/index.js +3 -0
  411. package/dist/extensions/index.js.map +1 -0
  412. package/dist/extensions/llama/client.d.ts +61 -0
  413. package/dist/extensions/llama/client.d.ts.map +1 -0
  414. package/dist/extensions/llama/client.js +302 -0
  415. package/dist/extensions/llama/client.js.map +1 -0
  416. package/dist/extensions/llama/huggingface.d.ts +23 -0
  417. package/dist/extensions/llama/huggingface.d.ts.map +1 -0
  418. package/dist/extensions/llama/huggingface.js +141 -0
  419. package/dist/extensions/llama/huggingface.js.map +1 -0
  420. package/dist/extensions/llama/index.d.ts +3 -0
  421. package/dist/extensions/llama/index.d.ts.map +1 -0
  422. package/dist/extensions/llama/index.js +217 -0
  423. package/dist/extensions/llama/index.js.map +1 -0
  424. package/dist/extensions/llama/provider.d.ts +10 -0
  425. package/dist/extensions/llama/provider.d.ts.map +1 -0
  426. package/dist/extensions/llama/provider.js +121 -0
  427. package/dist/extensions/llama/provider.js.map +1 -0
  428. package/dist/extensions/llama/ui.d.ts +42 -0
  429. package/dist/extensions/llama/ui.d.ts.map +1 -0
  430. package/dist/extensions/llama/ui.js +416 -0
  431. package/dist/extensions/llama/ui.js.map +1 -0
  432. package/dist/index.d.ts +35 -0
  433. package/dist/index.d.ts.map +1 -0
  434. package/dist/index.js +47 -0
  435. package/dist/index.js.map +1 -0
  436. package/dist/main.d.ts +12 -0
  437. package/dist/main.d.ts.map +1 -0
  438. package/dist/main.js +796 -0
  439. package/dist/main.js.map +1 -0
  440. package/dist/migrations.d.ts +33 -0
  441. package/dist/migrations.d.ts.map +1 -0
  442. package/dist/migrations.js +281 -0
  443. package/dist/migrations.js.map +1 -0
  444. package/dist/modes/index.d.ts +10 -0
  445. package/dist/modes/index.d.ts.map +1 -0
  446. package/dist/modes/index.js +8 -0
  447. package/dist/modes/index.js.map +1 -0
  448. package/dist/modes/interactive/assets/clankolas.png +0 -0
  449. package/dist/modes/interactive/components/armin.d.ts +34 -0
  450. package/dist/modes/interactive/components/armin.d.ts.map +1 -0
  451. package/dist/modes/interactive/components/armin.js +333 -0
  452. package/dist/modes/interactive/components/armin.js.map +1 -0
  453. package/dist/modes/interactive/components/assistant-message.d.ts +25 -0
  454. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -0
  455. package/dist/modes/interactive/components/assistant-message.js +150 -0
  456. package/dist/modes/interactive/components/assistant-message.js.map +1 -0
  457. package/dist/modes/interactive/components/bash-execution.d.ts +34 -0
  458. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -0
  459. package/dist/modes/interactive/components/bash-execution.js +175 -0
  460. package/dist/modes/interactive/components/bash-execution.js.map +1 -0
  461. package/dist/modes/interactive/components/bordered-loader.d.ts +16 -0
  462. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -0
  463. package/dist/modes/interactive/components/bordered-loader.js +54 -0
  464. package/dist/modes/interactive/components/bordered-loader.js.map +1 -0
  465. package/dist/modes/interactive/components/branch-summary-message.d.ts +16 -0
  466. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -0
  467. package/dist/modes/interactive/components/branch-summary-message.js +44 -0
  468. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -0
  469. package/dist/modes/interactive/components/compaction-summary-message.d.ts +16 -0
  470. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -0
  471. package/dist/modes/interactive/components/compaction-summary-message.js +45 -0
  472. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -0
  473. package/dist/modes/interactive/components/config-selector.d.ts +102 -0
  474. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -0
  475. package/dist/modes/interactive/components/config-selector.js +761 -0
  476. package/dist/modes/interactive/components/config-selector.js.map +1 -0
  477. package/dist/modes/interactive/components/countdown-timer.d.ts +14 -0
  478. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -0
  479. package/dist/modes/interactive/components/countdown-timer.js +33 -0
  480. package/dist/modes/interactive/components/countdown-timer.js.map +1 -0
  481. package/dist/modes/interactive/components/custom-editor.d.ts +21 -0
  482. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -0
  483. package/dist/modes/interactive/components/custom-editor.js +77 -0
  484. package/dist/modes/interactive/components/custom-editor.js.map +1 -0
  485. package/dist/modes/interactive/components/custom-entry.d.ts +19 -0
  486. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -0
  487. package/dist/modes/interactive/components/custom-entry.js +52 -0
  488. package/dist/modes/interactive/components/custom-entry.js.map +1 -0
  489. package/dist/modes/interactive/components/custom-message.d.ts +22 -0
  490. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -0
  491. package/dist/modes/interactive/components/custom-message.js +87 -0
  492. package/dist/modes/interactive/components/custom-message.js.map +1 -0
  493. package/dist/modes/interactive/components/daxnuts.d.ts +23 -0
  494. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -0
  495. package/dist/modes/interactive/components/daxnuts.js +140 -0
  496. package/dist/modes/interactive/components/daxnuts.js.map +1 -0
  497. package/dist/modes/interactive/components/diff.d.ts +12 -0
  498. package/dist/modes/interactive/components/diff.d.ts.map +1 -0
  499. package/dist/modes/interactive/components/diff.js +133 -0
  500. package/dist/modes/interactive/components/diff.js.map +1 -0
  501. package/dist/modes/interactive/components/dynamic-border.d.ts +15 -0
  502. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -0
  503. package/dist/modes/interactive/components/dynamic-border.js +21 -0
  504. package/dist/modes/interactive/components/dynamic-border.js.map +1 -0
  505. package/dist/modes/interactive/components/earendil-announcement.d.ts +5 -0
  506. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -0
  507. package/dist/modes/interactive/components/earendil-announcement.js +40 -0
  508. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -0
  509. package/dist/modes/interactive/components/extension-editor.d.ts +21 -0
  510. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -0
  511. package/dist/modes/interactive/components/extension-editor.js +98 -0
  512. package/dist/modes/interactive/components/extension-editor.js.map +1 -0
  513. package/dist/modes/interactive/components/extension-input.d.ts +23 -0
  514. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -0
  515. package/dist/modes/interactive/components/extension-input.js +61 -0
  516. package/dist/modes/interactive/components/extension-input.js.map +1 -0
  517. package/dist/modes/interactive/components/extension-selector.d.ts +26 -0
  518. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -0
  519. package/dist/modes/interactive/components/extension-selector.js +83 -0
  520. package/dist/modes/interactive/components/extension-selector.js.map +1 -0
  521. package/dist/modes/interactive/components/first-time-setup.d.ts +25 -0
  522. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -0
  523. package/dist/modes/interactive/components/first-time-setup.js +103 -0
  524. package/dist/modes/interactive/components/first-time-setup.js.map +1 -0
  525. package/dist/modes/interactive/components/footer.d.ts +32 -0
  526. package/dist/modes/interactive/components/footer.d.ts.map +1 -0
  527. package/dist/modes/interactive/components/footer.js +222 -0
  528. package/dist/modes/interactive/components/footer.js.map +1 -0
  529. package/dist/modes/interactive/components/index.d.ts +34 -0
  530. package/dist/modes/interactive/components/index.d.ts.map +1 -0
  531. package/dist/modes/interactive/components/index.js +35 -0
  532. package/dist/modes/interactive/components/index.js.map +1 -0
  533. package/dist/modes/interactive/components/keybinding-hints.d.ts +13 -0
  534. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -0
  535. package/dist/modes/interactive/components/keybinding-hints.js +36 -0
  536. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -0
  537. package/dist/modes/interactive/components/login-dialog.d.ts +52 -0
  538. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -0
  539. package/dist/modes/interactive/components/login-dialog.js +188 -0
  540. package/dist/modes/interactive/components/login-dialog.js.map +1 -0
  541. package/dist/modes/interactive/components/markdown-transform.d.ts +3 -0
  542. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -0
  543. package/dist/modes/interactive/components/markdown-transform.js +19 -0
  544. package/dist/modes/interactive/components/markdown-transform.js.map +1 -0
  545. package/dist/modes/interactive/components/mermaid.d.ts +11 -0
  546. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -0
  547. package/dist/modes/interactive/components/mermaid.js +75 -0
  548. package/dist/modes/interactive/components/mermaid.js.map +1 -0
  549. package/dist/modes/interactive/components/model-selector.d.ts +54 -0
  550. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -0
  551. package/dist/modes/interactive/components/model-selector.js +326 -0
  552. package/dist/modes/interactive/components/model-selector.js.map +1 -0
  553. package/dist/modes/interactive/components/oauth-selector.d.ts +33 -0
  554. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -0
  555. package/dist/modes/interactive/components/oauth-selector.js +163 -0
  556. package/dist/modes/interactive/components/oauth-selector.js.map +1 -0
  557. package/dist/modes/interactive/components/scoped-models-selector.d.ts +46 -0
  558. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -0
  559. package/dist/modes/interactive/components/scoped-models-selector.js +328 -0
  560. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -0
  561. package/dist/modes/interactive/components/session-selector-search.d.ts +23 -0
  562. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -0
  563. package/dist/modes/interactive/components/session-selector-search.js +155 -0
  564. package/dist/modes/interactive/components/session-selector-search.js.map +1 -0
  565. package/dist/modes/interactive/components/session-selector.d.ts +95 -0
  566. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -0
  567. package/dist/modes/interactive/components/session-selector.js +867 -0
  568. package/dist/modes/interactive/components/session-selector.js.map +1 -0
  569. package/dist/modes/interactive/components/settings-selector.d.ts +85 -0
  570. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -0
  571. package/dist/modes/interactive/components/settings-selector.js +633 -0
  572. package/dist/modes/interactive/components/settings-selector.js.map +1 -0
  573. package/dist/modes/interactive/components/show-images-selector.d.ts +10 -0
  574. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -0
  575. package/dist/modes/interactive/components/show-images-selector.js +39 -0
  576. package/dist/modes/interactive/components/show-images-selector.js.map +1 -0
  577. package/dist/modes/interactive/components/skill-invocation-message.d.ts +17 -0
  578. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
  579. package/dist/modes/interactive/components/skill-invocation-message.js +47 -0
  580. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -0
  581. package/dist/modes/interactive/components/status-indicator.d.ts +28 -0
  582. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -0
  583. package/dist/modes/interactive/components/status-indicator.js +60 -0
  584. package/dist/modes/interactive/components/status-indicator.js.map +1 -0
  585. package/dist/modes/interactive/components/theme-selector.d.ts +11 -0
  586. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -0
  587. package/dist/modes/interactive/components/theme-selector.js +50 -0
  588. package/dist/modes/interactive/components/theme-selector.js.map +1 -0
  589. package/dist/modes/interactive/components/thinking-selector.d.ts +11 -0
  590. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -0
  591. package/dist/modes/interactive/components/thinking-selector.js +52 -0
  592. package/dist/modes/interactive/components/thinking-selector.js.map +1 -0
  593. package/dist/modes/interactive/components/tool-execution.d.ts +63 -0
  594. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -0
  595. package/dist/modes/interactive/components/tool-execution.js +326 -0
  596. package/dist/modes/interactive/components/tool-execution.js.map +1 -0
  597. package/dist/modes/interactive/components/tree-selector.d.ts +94 -0
  598. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -0
  599. package/dist/modes/interactive/components/tree-selector.js +1245 -0
  600. package/dist/modes/interactive/components/tree-selector.js.map +1 -0
  601. package/dist/modes/interactive/components/trust-selector.d.ts +23 -0
  602. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -0
  603. package/dist/modes/interactive/components/trust-selector.js +91 -0
  604. package/dist/modes/interactive/components/trust-selector.js.map +1 -0
  605. package/dist/modes/interactive/components/user-message-selector.d.ts +30 -0
  606. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -0
  607. package/dist/modes/interactive/components/user-message-selector.js +114 -0
  608. package/dist/modes/interactive/components/user-message-selector.js.map +1 -0
  609. package/dist/modes/interactive/components/user-message.d.ts +16 -0
  610. package/dist/modes/interactive/components/user-message.d.ts.map +1 -0
  611. package/dist/modes/interactive/components/user-message.js +49 -0
  612. package/dist/modes/interactive/components/user-message.js.map +1 -0
  613. package/dist/modes/interactive/components/visual-truncate.d.ts +24 -0
  614. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -0
  615. package/dist/modes/interactive/components/visual-truncate.js +33 -0
  616. package/dist/modes/interactive/components/visual-truncate.js.map +1 -0
  617. package/dist/modes/interactive/external-editor.d.ts +12 -0
  618. package/dist/modes/interactive/external-editor.d.ts.map +1 -0
  619. package/dist/modes/interactive/external-editor.js +37 -0
  620. package/dist/modes/interactive/external-editor.js.map +1 -0
  621. package/dist/modes/interactive/interactive-mode.d.ts +435 -0
  622. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -0
  623. package/dist/modes/interactive/interactive-mode.js +5438 -0
  624. package/dist/modes/interactive/interactive-mode.js.map +1 -0
  625. package/dist/modes/interactive/model-catalog-refresh.d.ts +7 -0
  626. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
  627. package/dist/modes/interactive/model-catalog-refresh.js +34 -0
  628. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -0
  629. package/dist/modes/interactive/model-search.d.ts +12 -0
  630. package/dist/modes/interactive/model-search.d.ts.map +1 -0
  631. package/dist/modes/interactive/model-search.js +15 -0
  632. package/dist/modes/interactive/model-search.js.map +1 -0
  633. package/dist/modes/interactive/theme/dark.json +90 -0
  634. package/dist/modes/interactive/theme/light.json +89 -0
  635. package/dist/modes/interactive/theme/theme-controller.d.ts +40 -0
  636. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -0
  637. package/dist/modes/interactive/theme/theme-controller.js +125 -0
  638. package/dist/modes/interactive/theme/theme-controller.js.map +1 -0
  639. package/dist/modes/interactive/theme/theme-schema.json +352 -0
  640. package/dist/modes/interactive/theme/theme.d.ts +122 -0
  641. package/dist/modes/interactive/theme/theme.d.ts.map +1 -0
  642. package/dist/modes/interactive/theme/theme.js +1091 -0
  643. package/dist/modes/interactive/theme/theme.js.map +1 -0
  644. package/dist/modes/json-event.d.ts +31 -0
  645. package/dist/modes/json-event.d.ts.map +1 -0
  646. package/dist/modes/json-event.js +15 -0
  647. package/dist/modes/json-event.js.map +1 -0
  648. package/dist/modes/print-mode.d.ts +28 -0
  649. package/dist/modes/print-mode.d.ts.map +1 -0
  650. package/dist/modes/print-mode.js +142 -0
  651. package/dist/modes/print-mode.js.map +1 -0
  652. package/dist/modes/rpc/jsonl.d.ts +17 -0
  653. package/dist/modes/rpc/jsonl.d.ts.map +1 -0
  654. package/dist/modes/rpc/jsonl.js +49 -0
  655. package/dist/modes/rpc/jsonl.js.map +1 -0
  656. package/dist/modes/rpc/rpc-client.d.ts +247 -0
  657. package/dist/modes/rpc/rpc-client.d.ts.map +1 -0
  658. package/dist/modes/rpc/rpc-client.js +488 -0
  659. package/dist/modes/rpc/rpc-client.js.map +1 -0
  660. package/dist/modes/rpc/rpc-mode.d.ts +20 -0
  661. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -0
  662. package/dist/modes/rpc/rpc-mode.js +654 -0
  663. package/dist/modes/rpc/rpc-mode.js.map +1 -0
  664. package/dist/modes/rpc/rpc-types.d.ts +457 -0
  665. package/dist/modes/rpc/rpc-types.d.ts.map +1 -0
  666. package/dist/modes/rpc/rpc-types.js +8 -0
  667. package/dist/modes/rpc/rpc-types.js.map +1 -0
  668. package/dist/package-manager-cli.d.ts +8 -0
  669. package/dist/package-manager-cli.d.ts.map +1 -0
  670. package/dist/package-manager-cli.js +777 -0
  671. package/dist/package-manager-cli.js.map +1 -0
  672. package/dist/rpc-entry.d.ts +3 -0
  673. package/dist/rpc-entry.d.ts.map +1 -0
  674. package/dist/rpc-entry.js +11 -0
  675. package/dist/rpc-entry.js.map +1 -0
  676. package/dist/server/create-harness.d.ts +26 -0
  677. package/dist/server/create-harness.d.ts.map +1 -0
  678. package/dist/server/create-harness.js +106 -0
  679. package/dist/server/create-harness.js.map +1 -0
  680. package/dist/utils/abort.d.ts +5 -0
  681. package/dist/utils/abort.d.ts.map +1 -0
  682. package/dist/utils/abort.js +48 -0
  683. package/dist/utils/abort.js.map +1 -0
  684. package/dist/utils/ansi.d.ts +2 -0
  685. package/dist/utils/ansi.d.ts.map +1 -0
  686. package/dist/utils/ansi.js +52 -0
  687. package/dist/utils/ansi.js.map +1 -0
  688. package/dist/utils/changelog.d.ts +22 -0
  689. package/dist/utils/changelog.d.ts.map +1 -0
  690. package/dist/utils/changelog.js +165 -0
  691. package/dist/utils/changelog.js.map +1 -0
  692. package/dist/utils/child-process.d.ts +18 -0
  693. package/dist/utils/child-process.d.ts.map +1 -0
  694. package/dist/utils/child-process.js +106 -0
  695. package/dist/utils/child-process.js.map +1 -0
  696. package/dist/utils/clipboard-image.d.ts +11 -0
  697. package/dist/utils/clipboard-image.d.ts.map +1 -0
  698. package/dist/utils/clipboard-image.js +245 -0
  699. package/dist/utils/clipboard-image.js.map +1 -0
  700. package/dist/utils/clipboard-native.d.ts +11 -0
  701. package/dist/utils/clipboard-native.d.ts.map +1 -0
  702. package/dist/utils/clipboard-native.js +20 -0
  703. package/dist/utils/clipboard-native.js.map +1 -0
  704. package/dist/utils/clipboard.d.ts +4 -0
  705. package/dist/utils/clipboard.d.ts.map +1 -0
  706. package/dist/utils/clipboard.js +161 -0
  707. package/dist/utils/clipboard.js.map +1 -0
  708. package/dist/utils/deprecation.d.ts +4 -0
  709. package/dist/utils/deprecation.d.ts.map +1 -0
  710. package/dist/utils/deprecation.js +13 -0
  711. package/dist/utils/deprecation.js.map +1 -0
  712. package/dist/utils/exif-orientation.d.ts +5 -0
  713. package/dist/utils/exif-orientation.d.ts.map +1 -0
  714. package/dist/utils/exif-orientation.js +158 -0
  715. package/dist/utils/exif-orientation.js.map +1 -0
  716. package/dist/utils/frontmatter.d.ts +8 -0
  717. package/dist/utils/frontmatter.d.ts.map +1 -0
  718. package/dist/utils/frontmatter.js +26 -0
  719. package/dist/utils/frontmatter.js.map +1 -0
  720. package/dist/utils/fs-watch.d.ts +5 -0
  721. package/dist/utils/fs-watch.d.ts.map +1 -0
  722. package/dist/utils/fs-watch.js +25 -0
  723. package/dist/utils/fs-watch.js.map +1 -0
  724. package/dist/utils/git.d.ts +26 -0
  725. package/dist/utils/git.d.ts.map +1 -0
  726. package/dist/utils/git.js +195 -0
  727. package/dist/utils/git.js.map +1 -0
  728. package/dist/utils/html.d.ts +7 -0
  729. package/dist/utils/html.d.ts.map +1 -0
  730. package/dist/utils/html.js +40 -0
  731. package/dist/utils/html.js.map +1 -0
  732. package/dist/utils/image-convert.d.ts +10 -0
  733. package/dist/utils/image-convert.d.ts.map +1 -0
  734. package/dist/utils/image-convert.js +45 -0
  735. package/dist/utils/image-convert.js.map +1 -0
  736. package/dist/utils/image-process.d.ts +18 -0
  737. package/dist/utils/image-process.d.ts.map +1 -0
  738. package/dist/utils/image-process.js +83 -0
  739. package/dist/utils/image-process.js.map +1 -0
  740. package/dist/utils/image-resize-core.d.ts +30 -0
  741. package/dist/utils/image-resize-core.d.ts.map +1 -0
  742. package/dist/utils/image-resize-core.js +124 -0
  743. package/dist/utils/image-resize-core.js.map +1 -0
  744. package/dist/utils/image-resize-worker.d.ts +2 -0
  745. package/dist/utils/image-resize-worker.d.ts.map +1 -0
  746. package/dist/utils/image-resize-worker.js +31 -0
  747. package/dist/utils/image-resize-worker.js.map +1 -0
  748. package/dist/utils/image-resize.d.ts +16 -0
  749. package/dist/utils/image-resize.d.ts.map +1 -0
  750. package/dist/utils/image-resize.js +97 -0
  751. package/dist/utils/image-resize.js.map +1 -0
  752. package/dist/utils/json.d.ts +3 -0
  753. package/dist/utils/json.d.ts.map +1 -0
  754. package/dist/utils/json.js +7 -0
  755. package/dist/utils/json.js.map +1 -0
  756. package/dist/utils/management-http.d.ts +23 -0
  757. package/dist/utils/management-http.d.ts.map +1 -0
  758. package/dist/utils/management-http.js +50 -0
  759. package/dist/utils/management-http.js.map +1 -0
  760. package/dist/utils/mime.d.ts +3 -0
  761. package/dist/utils/mime.d.ts.map +1 -0
  762. package/dist/utils/mime.js +110 -0
  763. package/dist/utils/mime.js.map +1 -0
  764. package/dist/utils/open-browser.d.ts +9 -0
  765. package/dist/utils/open-browser.d.ts.map +1 -0
  766. package/dist/utils/open-browser.js +22 -0
  767. package/dist/utils/open-browser.js.map +1 -0
  768. package/dist/utils/paths.d.ts +34 -0
  769. package/dist/utils/paths.d.ts.map +1 -0
  770. package/dist/utils/paths.js +114 -0
  771. package/dist/utils/paths.js.map +1 -0
  772. package/dist/utils/photon.d.ts +21 -0
  773. package/dist/utils/photon.d.ts.map +1 -0
  774. package/dist/utils/photon.js +121 -0
  775. package/dist/utils/photon.js.map +1 -0
  776. package/dist/utils/pi-user-agent.d.ts +2 -0
  777. package/dist/utils/pi-user-agent.d.ts.map +1 -0
  778. package/dist/utils/pi-user-agent.js +5 -0
  779. package/dist/utils/pi-user-agent.js.map +1 -0
  780. package/dist/utils/shell.d.ts +31 -0
  781. package/dist/utils/shell.d.ts.map +1 -0
  782. package/dist/utils/shell.js +202 -0
  783. package/dist/utils/shell.js.map +1 -0
  784. package/dist/utils/sleep.d.ts +5 -0
  785. package/dist/utils/sleep.d.ts.map +1 -0
  786. package/dist/utils/sleep.js +17 -0
  787. package/dist/utils/sleep.js.map +1 -0
  788. package/dist/utils/syntax-highlight.d.ts +12 -0
  789. package/dist/utils/syntax-highlight.d.ts.map +1 -0
  790. package/dist/utils/syntax-highlight.js +118 -0
  791. package/dist/utils/syntax-highlight.js.map +1 -0
  792. package/dist/utils/tool-result-images.d.ts +19 -0
  793. package/dist/utils/tool-result-images.d.ts.map +1 -0
  794. package/dist/utils/tool-result-images.js +45 -0
  795. package/dist/utils/tool-result-images.js.map +1 -0
  796. package/dist/utils/tools-manager.d.ts +12 -0
  797. package/dist/utils/tools-manager.d.ts.map +1 -0
  798. package/dist/utils/tools-manager.js +321 -0
  799. package/dist/utils/tools-manager.js.map +1 -0
  800. package/dist/utils/version-check.d.ts +19 -0
  801. package/dist/utils/version-check.d.ts.map +1 -0
  802. package/dist/utils/version-check.js +79 -0
  803. package/dist/utils/version-check.js.map +1 -0
  804. package/dist/utils/windows-self-update.d.ts +3 -0
  805. package/dist/utils/windows-self-update.d.ts.map +1 -0
  806. package/dist/utils/windows-self-update.js +77 -0
  807. package/dist/utils/windows-self-update.js.map +1 -0
  808. package/docs/compaction.md +401 -0
  809. package/docs/containerization.md +111 -0
  810. package/docs/custom-provider.md +774 -0
  811. package/docs/development.md +71 -0
  812. package/docs/docs.json +156 -0
  813. package/docs/environment-variables.md +94 -0
  814. package/docs/extensions.md +2992 -0
  815. package/docs/images/doom-extension.png +0 -0
  816. package/docs/images/exy.png +0 -0
  817. package/docs/images/interactive-mode.png +0 -0
  818. package/docs/images/tree-view.png +0 -0
  819. package/docs/index.md +84 -0
  820. package/docs/json.md +93 -0
  821. package/docs/keybindings.md +236 -0
  822. package/docs/llama-cpp.md +99 -0
  823. package/docs/models.md +565 -0
  824. package/docs/packages.md +228 -0
  825. package/docs/prompt-templates.md +96 -0
  826. package/docs/providers.md +317 -0
  827. package/docs/quickstart.md +167 -0
  828. package/docs/rpc.md +1589 -0
  829. package/docs/sdk.md +1214 -0
  830. package/docs/security.md +59 -0
  831. package/docs/session-format.md +438 -0
  832. package/docs/sessions.md +145 -0
  833. package/docs/settings.md +353 -0
  834. package/docs/shell-aliases.md +13 -0
  835. package/docs/skills.md +231 -0
  836. package/docs/terminal-setup.md +163 -0
  837. package/docs/termux.md +127 -0
  838. package/docs/themes.md +320 -0
  839. package/docs/tmux.md +63 -0
  840. package/docs/tui.md +942 -0
  841. package/docs/usage.md +306 -0
  842. package/docs/windows.md +17 -0
  843. package/examples/README.md +25 -0
  844. package/examples/extensions/README.md +213 -0
  845. package/examples/extensions/auto-commit-on-exit.ts +49 -0
  846. package/examples/extensions/bash-spawn-hook.ts +30 -0
  847. package/examples/extensions/bookmark.ts +50 -0
  848. package/examples/extensions/border-status-editor.ts +150 -0
  849. package/examples/extensions/built-in-tool-renderer.ts +249 -0
  850. package/examples/extensions/claude-rules.ts +86 -0
  851. package/examples/extensions/commands.ts +72 -0
  852. package/examples/extensions/confirm-destructive.ts +59 -0
  853. package/examples/extensions/custom-compaction.ts +117 -0
  854. package/examples/extensions/custom-footer.ts +64 -0
  855. package/examples/extensions/custom-header.ts +73 -0
  856. package/examples/extensions/custom-provider-anthropic/index.ts +611 -0
  857. package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  858. package/examples/extensions/custom-provider-anthropic/package.json +19 -0
  859. package/examples/extensions/custom-provider-gitlab-duo/index.ts +405 -0
  860. package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  861. package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -0
  862. package/examples/extensions/dirty-repo-guard.ts +56 -0
  863. package/examples/extensions/doom-overlay/README.md +46 -0
  864. package/examples/extensions/doom-overlay/doom/build/doom.js +21 -0
  865. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  866. package/examples/extensions/doom-overlay/doom/build.sh +152 -0
  867. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
  868. package/examples/extensions/doom-overlay/doom-component.ts +132 -0
  869. package/examples/extensions/doom-overlay/doom-engine.ts +173 -0
  870. package/examples/extensions/doom-overlay/doom-keys.ts +104 -0
  871. package/examples/extensions/doom-overlay/index.ts +74 -0
  872. package/examples/extensions/doom-overlay/wad-finder.ts +55 -0
  873. package/examples/extensions/dynamic-resources/SKILL.md +8 -0
  874. package/examples/extensions/dynamic-resources/dynamic.json +79 -0
  875. package/examples/extensions/dynamic-resources/dynamic.md +5 -0
  876. package/examples/extensions/dynamic-resources/index.ts +15 -0
  877. package/examples/extensions/dynamic-tools.ts +74 -0
  878. package/examples/extensions/entry-renderer.ts +41 -0
  879. package/examples/extensions/event-bus.ts +43 -0
  880. package/examples/extensions/file-trigger.ts +41 -0
  881. package/examples/extensions/git-checkpoint.ts +53 -0
  882. package/examples/extensions/git-merge-and-resolve.ts +115 -0
  883. package/examples/extensions/github-issue-autocomplete.ts +185 -0
  884. package/examples/extensions/gondolin/index.ts +531 -0
  885. package/examples/extensions/gondolin/package-lock.json +185 -0
  886. package/examples/extensions/gondolin/package.json +19 -0
  887. package/examples/extensions/handoff.ts +190 -0
  888. package/examples/extensions/hello.ts +26 -0
  889. package/examples/extensions/hidden-thinking-label.ts +53 -0
  890. package/examples/extensions/inline-bash.ts +94 -0
  891. package/examples/extensions/input-transform-streaming.ts +39 -0
  892. package/examples/extensions/input-transform.ts +43 -0
  893. package/examples/extensions/interactive-shell.ts +196 -0
  894. package/examples/extensions/kimi-deferred-tools.ts +61 -0
  895. package/examples/extensions/mac-system-theme.ts +47 -0
  896. package/examples/extensions/message-renderer.ts +59 -0
  897. package/examples/extensions/minimal-mode.ts +426 -0
  898. package/examples/extensions/modal-editor.ts +85 -0
  899. package/examples/extensions/model-status.ts +31 -0
  900. package/examples/extensions/notify.ts +55 -0
  901. package/examples/extensions/overlay-qa-tests.ts +1450 -0
  902. package/examples/extensions/overlay-test.ts +153 -0
  903. package/examples/extensions/permission-gate.ts +34 -0
  904. package/examples/extensions/pirate.ts +47 -0
  905. package/examples/extensions/plan-mode/README.md +66 -0
  906. package/examples/extensions/plan-mode/index.ts +390 -0
  907. package/examples/extensions/plan-mode/utils.ts +168 -0
  908. package/examples/extensions/preset.ts +436 -0
  909. package/examples/extensions/project-trust.ts +64 -0
  910. package/examples/extensions/prompt-customizer.ts +97 -0
  911. package/examples/extensions/protected-paths.ts +30 -0
  912. package/examples/extensions/provider-payload.ts +18 -0
  913. package/examples/extensions/qna.ts +118 -0
  914. package/examples/extensions/question.ts +286 -0
  915. package/examples/extensions/questionnaire.ts +448 -0
  916. package/examples/extensions/rainbow-editor.ts +88 -0
  917. package/examples/extensions/reload-runtime.ts +37 -0
  918. package/examples/extensions/rpc-demo.ts +118 -0
  919. package/examples/extensions/sandbox/index.ts +321 -0
  920. package/examples/extensions/sandbox/package-lock.json +92 -0
  921. package/examples/extensions/sandbox/package.json +19 -0
  922. package/examples/extensions/send-user-message.ts +97 -0
  923. package/examples/extensions/session-name.ts +27 -0
  924. package/examples/extensions/shutdown-command.ts +63 -0
  925. package/examples/extensions/snake.ts +343 -0
  926. package/examples/extensions/space-invaders.ts +560 -0
  927. package/examples/extensions/ssh.ts +220 -0
  928. package/examples/extensions/status-line.ts +32 -0
  929. package/examples/extensions/structured-output.ts +65 -0
  930. package/examples/extensions/subagent/README.md +177 -0
  931. package/examples/extensions/subagent/agents/planner.md +37 -0
  932. package/examples/extensions/subagent/agents/reviewer.md +35 -0
  933. package/examples/extensions/subagent/agents/scout.md +50 -0
  934. package/examples/extensions/subagent/agents/worker.md +24 -0
  935. package/examples/extensions/subagent/agents.ts +157 -0
  936. package/examples/extensions/subagent/index.ts +1033 -0
  937. package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  938. package/examples/extensions/subagent/prompts/implement.md +10 -0
  939. package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  940. package/examples/extensions/summarize.ts +199 -0
  941. package/examples/extensions/system-prompt-header.ts +17 -0
  942. package/examples/extensions/tic-tac-toe.ts +1008 -0
  943. package/examples/extensions/timed-confirm.ts +70 -0
  944. package/examples/extensions/titlebar-spinner.ts +58 -0
  945. package/examples/extensions/todo.ts +297 -0
  946. package/examples/extensions/tool-override.ts +144 -0
  947. package/examples/extensions/tools.ts +146 -0
  948. package/examples/extensions/trigger-compact.ts +50 -0
  949. package/examples/extensions/truncated-tool.ts +195 -0
  950. package/examples/extensions/widget-placement.ts +9 -0
  951. package/examples/extensions/with-deps/index.ts +32 -0
  952. package/examples/extensions/with-deps/package-lock.json +31 -0
  953. package/examples/extensions/with-deps/package.json +22 -0
  954. package/examples/extensions/working-indicator.ts +123 -0
  955. package/examples/extensions/working-message-test.ts +25 -0
  956. package/examples/rpc-extension-ui.ts +641 -0
  957. package/examples/sdk/01-minimal.ts +26 -0
  958. package/examples/sdk/02-custom-model.ts +49 -0
  959. package/examples/sdk/03-custom-prompt.ts +75 -0
  960. package/examples/sdk/04-skills.ts +55 -0
  961. package/examples/sdk/05-tools.ts +48 -0
  962. package/examples/sdk/06-extensions.ts +99 -0
  963. package/examples/sdk/07-context-files.ts +47 -0
  964. package/examples/sdk/08-prompt-templates.ts +51 -0
  965. package/examples/sdk/09-api-keys-and-oauth.ts +34 -0
  966. package/examples/sdk/10-settings.ts +53 -0
  967. package/examples/sdk/11-sessions.ts +52 -0
  968. package/examples/sdk/12-full-control.ts +74 -0
  969. package/examples/sdk/13-session-runtime.ts +67 -0
  970. package/examples/sdk/README.md +140 -0
  971. package/npm-shrinkwrap.json +1818 -0
  972. package/package.json +109 -0
@@ -0,0 +1,2687 @@
1
+ /**
2
+ * AgentSession - Core abstraction for agent lifecycle and session management.
3
+ *
4
+ * This class is shared between all run modes (interactive, print, rpc).
5
+ * It encapsulates:
6
+ * - Agent state access
7
+ * - Event subscription with automatic session persistence
8
+ * - Model and thinking level management
9
+ * - Compaction (manual and auto)
10
+ * - Bash execution
11
+ * - Session switching and branching
12
+ *
13
+ * Modes use this class and add their own I/O layer on top.
14
+ */
15
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { basename, dirname } from "node:path";
17
+ import { contentText } from "@earendil-works/pi-ai";
18
+ import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, isRecoverableLength, isRetryableAssistantError, modelsAreEqual, resetApiProviders, streamSimple, } from "@earendil-works/pi-ai/compat";
19
+ import { getThemeByName, theme } from "../modes/interactive/theme/theme.js";
20
+ import { stripFrontmatter } from "../utils/frontmatter.js";
21
+ import { resolvePath } from "../utils/paths.js";
22
+ import { sleep } from "../utils/sleep.js";
23
+ import { normalizeToolResultImages } from "../utils/tool-result-images.js";
24
+ import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
25
+ import { executeBashWithOperations } from "./bash-executor.js";
26
+ import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
27
+ import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
28
+ import { exportSessionToHtml } from "./export-html/index.js";
29
+ import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
30
+ import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
31
+ import { emitSessionShutdownEvent } from "./extensions/runner.js";
32
+ import { ModelRegistry } from "./model-registry.js";
33
+ import { expandPromptTemplate } from "./prompt-templates.js";
34
+ import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
35
+ import { createSyntheticSourceInfo } from "./source-info.js";
36
+ import { buildSystemPrompt } from "./system-prompt.js";
37
+ import { createLocalBashOperations } from "./tools/bash.js";
38
+ import { createAllToolDefinitions } from "./tools/index.js";
39
+ import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
40
+ import { addUsageToTotals, createUsageTotals } from "./usage-totals.js";
41
+ /**
42
+ * Parse a skill block from message text.
43
+ * Returns null if the text doesn't contain a skill block.
44
+ */
45
+ export function parseSkillBlock(text) {
46
+ const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
47
+ if (!match)
48
+ return null;
49
+ return {
50
+ name: match[1],
51
+ location: match[2],
52
+ content: match[3],
53
+ userMessage: match[4]?.trim() || undefined,
54
+ };
55
+ }
56
+ // ============================================================================
57
+ // Types
58
+ // ============================================================================
59
+ function withoutDeletedHeaders(headers) {
60
+ return headers
61
+ ? Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null))
62
+ : undefined;
63
+ }
64
+ function estimateMessagesTokens(messages) {
65
+ let tokens = 0;
66
+ for (const message of messages) {
67
+ tokens += estimateTokens(message);
68
+ }
69
+ return tokens;
70
+ }
71
+ // ============================================================================
72
+ // Constants
73
+ // ============================================================================
74
+ /** Standard thinking levels */
75
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
76
+ // ============================================================================
77
+ // AgentSession Class
78
+ // ============================================================================
79
+ export class AgentSession {
80
+ agent;
81
+ sessionManager;
82
+ settingsManager;
83
+ _scopedModels;
84
+ // Event subscription state
85
+ _unsubscribeAgent;
86
+ _eventListeners = [];
87
+ _isAgentRunActive = false;
88
+ _idleWaitPromise;
89
+ _resolveIdleWait;
90
+ /** Tracks pending steering messages for UI display. Removed when delivered. */
91
+ _steeringMessages = [];
92
+ /** Tracks pending follow-up messages for UI display. Removed when delivered. */
93
+ _followUpMessages = [];
94
+ /** Messages queued to be included with the next user prompt as context ("asides"). */
95
+ _pendingNextTurnMessages = [];
96
+ // Compaction state
97
+ _compactionAbortController = undefined;
98
+ _autoCompactionAbortController = undefined;
99
+ _overflowRecoveryAttempted = false;
100
+ // Branch summarization state
101
+ _branchSummaryAbortController = undefined;
102
+ // Retry state
103
+ _retryAbortController = undefined;
104
+ _retryAttempt = 0;
105
+ // Bash execution state
106
+ _bashAbortControllers = new Set();
107
+ _pendingBashMessages = [];
108
+ // Extension system
109
+ _extensionRunner;
110
+ _turnIndex = 0;
111
+ _resourceLoader;
112
+ _customTools;
113
+ _baseToolDefinitions = new Map();
114
+ _cwd;
115
+ _extensionRunnerRef;
116
+ _initialActiveToolNames;
117
+ _allowedToolNames;
118
+ _excludedToolNames;
119
+ _baseToolsOverride;
120
+ _sessionStartEvent;
121
+ _extensionUIContext;
122
+ _extensionMode = "print";
123
+ _extensionCommandContextActions;
124
+ _extensionAbortHandler;
125
+ _extensionShutdownHandler;
126
+ _extensionErrorListener;
127
+ _extensionErrorUnsubscriber;
128
+ _modelRuntime;
129
+ // Tool registry for extension getTools/setTools
130
+ _toolRegistry = new Map();
131
+ _toolDefinitions = new Map();
132
+ _toolPromptSnippets = new Map();
133
+ _toolPromptGuidelines = new Map();
134
+ // Base system prompt (without extension appends) - used to apply fresh appends each turn
135
+ _baseSystemPrompt = "";
136
+ _baseSystemPromptOptions;
137
+ _systemPromptOverride;
138
+ constructor(config) {
139
+ this.agent = config.agent;
140
+ this.sessionManager = config.sessionManager;
141
+ this.settingsManager = config.settingsManager;
142
+ this._scopedModels = config.scopedModels ?? [];
143
+ this._resourceLoader = config.resourceLoader;
144
+ this._customTools = config.customTools ?? [];
145
+ this._cwd = config.cwd;
146
+ this._modelRuntime = config.modelRuntime;
147
+ this._extensionRunnerRef = config.extensionRunnerRef;
148
+ this._initialActiveToolNames = config.initialActiveToolNames;
149
+ this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
150
+ this._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;
151
+ this._baseToolsOverride = config.baseToolsOverride;
152
+ this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
153
+ // Always subscribe to agent events for internal handling
154
+ // (session persistence, extensions, auto-compaction, retry logic)
155
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
156
+ this._installAgentToolHooks();
157
+ this._installAgentNextTurnRefresh();
158
+ this._buildRuntime({
159
+ activeToolNames: this._initialActiveToolNames,
160
+ includeAllExtensionTools: true,
161
+ });
162
+ }
163
+ get modelRuntime() {
164
+ return this._modelRuntime;
165
+ }
166
+ async _getRequiredRequestAuth(model) {
167
+ let result;
168
+ try {
169
+ result = await this._modelRuntime.getAuth(model);
170
+ }
171
+ catch (error) {
172
+ const cause = error instanceof Error ? error.cause : undefined;
173
+ if (cause instanceof Error && cause.message === "authHeader requires a resolved API key") {
174
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
175
+ }
176
+ throw error;
177
+ }
178
+ if (result && (result.auth.apiKey || result.auth.headers)) {
179
+ const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
180
+ return {
181
+ model: requestModel,
182
+ apiKey: result.auth.apiKey,
183
+ headers: withoutDeletedHeaders(result.auth.headers),
184
+ env: result.env,
185
+ };
186
+ }
187
+ const isOAuth = this._modelRuntime.isUsingOAuth(model.provider);
188
+ if (isOAuth) {
189
+ throw new Error(`Authentication failed for "${model.provider}". ` +
190
+ `Credentials may have expired or network is unavailable. ` +
191
+ `Run '/login ${model.provider}' to re-authenticate.`);
192
+ }
193
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
194
+ }
195
+ async _getSummarizationRequestAuth(model) {
196
+ if (this.agent.streamFunction === streamSimple) {
197
+ return this._getRequiredRequestAuth(model);
198
+ }
199
+ try {
200
+ const result = await this._modelRuntime.getAuth(model);
201
+ if (!result)
202
+ return { model };
203
+ const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
204
+ return {
205
+ model: requestModel,
206
+ apiKey: result.auth.apiKey,
207
+ headers: withoutDeletedHeaders(result.auth.headers),
208
+ env: result.env,
209
+ };
210
+ }
211
+ catch {
212
+ return { model };
213
+ }
214
+ }
215
+ /**
216
+ * Install tool hooks once on the Agent instance.
217
+ *
218
+ * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the
219
+ * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt
220
+ * registered tool execution to the extension context. Tool call and tool result interception now
221
+ * happens here instead of in wrappers.
222
+ */
223
+ _installAgentToolHooks() {
224
+ this.agent.beforeToolCall = async ({ toolCall, args }) => {
225
+ const runner = this._extensionRunner;
226
+ if (!runner.hasHandlers("tool_call")) {
227
+ return undefined;
228
+ }
229
+ try {
230
+ return await runner.emitToolCall({
231
+ type: "tool_call",
232
+ toolName: toolCall.name,
233
+ toolCallId: toolCall.id,
234
+ input: args,
235
+ });
236
+ }
237
+ catch (err) {
238
+ if (err instanceof Error) {
239
+ throw err;
240
+ }
241
+ throw new Error(`Extension failed, blocking execution: ${String(err)}`);
242
+ }
243
+ };
244
+ this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
245
+ const runner = this._extensionRunner;
246
+ const hookResult = runner.hasHandlers("tool_result")
247
+ ? await runner.emitToolResult({
248
+ type: "tool_result",
249
+ toolName: toolCall.name,
250
+ toolCallId: toolCall.id,
251
+ input: args,
252
+ content: result.content,
253
+ details: result.details,
254
+ isError,
255
+ usage: result.usage,
256
+ })
257
+ : undefined;
258
+ const content = hookResult?.content ?? result.content ?? [];
259
+ // Runs after the extension hook so images injected or replaced by extensions are normalized too.
260
+ const normalizedContent = await normalizeToolResultImages(content, {
261
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
262
+ });
263
+ if (!hookResult && normalizedContent === content) {
264
+ return undefined;
265
+ }
266
+ return {
267
+ content: normalizedContent,
268
+ details: hookResult?.details,
269
+ isError: hookResult?.isError ?? isError,
270
+ usage: hookResult?.usage,
271
+ };
272
+ };
273
+ }
274
+ _installAgentNextTurnRefresh() {
275
+ const previousPrepareNextTurnWithContext = this.agent.prepareNextTurnWithContext ??
276
+ (this.agent.prepareNextTurn
277
+ ? async (_turn, signal) => await this.agent.prepareNextTurn?.(signal)
278
+ : undefined);
279
+ this.agent.prepareNextTurnWithContext = async (turn, signal) => {
280
+ const previousSnapshot = await previousPrepareNextTurnWithContext?.(turn, signal);
281
+ const previousContext = previousSnapshot?.context ?? turn.context;
282
+ return {
283
+ ...previousSnapshot,
284
+ context: {
285
+ ...previousContext,
286
+ systemPrompt: this._systemPromptOverride ?? this._baseSystemPrompt,
287
+ tools: this.agent.state.tools.slice(),
288
+ },
289
+ model: this.agent.state.model,
290
+ thinkingLevel: this.agent.state.thinkingLevel,
291
+ };
292
+ };
293
+ }
294
+ // =========================================================================
295
+ // Event Subscription
296
+ // =========================================================================
297
+ /** Emit an event to all listeners */
298
+ _emit(event) {
299
+ for (const l of this._eventListeners) {
300
+ l(event);
301
+ }
302
+ }
303
+ _emitQueueUpdate() {
304
+ this._emit({
305
+ type: "queue_update",
306
+ steering: [...this._steeringMessages],
307
+ followUp: [...this._followUpMessages],
308
+ });
309
+ }
310
+ _getIdleWaitPromise() {
311
+ if (!this._idleWaitPromise) {
312
+ this._idleWaitPromise = new Promise((resolve) => {
313
+ this._resolveIdleWait = resolve;
314
+ });
315
+ }
316
+ return this._idleWaitPromise;
317
+ }
318
+ _resolveIdleWaitIfIdle() {
319
+ if (this._isAgentRunActive || !this._resolveIdleWait) {
320
+ return;
321
+ }
322
+ const resolve = this._resolveIdleWait;
323
+ this._idleWaitPromise = undefined;
324
+ this._resolveIdleWait = undefined;
325
+ resolve();
326
+ }
327
+ async _emitAgentSettled() {
328
+ this._isAgentRunActive = false;
329
+ try {
330
+ await this._extensionRunner.emit({ type: "agent_settled" });
331
+ this._emit({ type: "agent_settled" });
332
+ }
333
+ finally {
334
+ this._resolveIdleWaitIfIdle();
335
+ }
336
+ }
337
+ // Track last assistant message for auto-compaction check
338
+ _lastAssistantMessage = undefined;
339
+ /** Internal handler for agent events - shared by subscribe and reconnect */
340
+ _handleAgentEvent = async (event) => {
341
+ // When a user message starts, check if it's from either queue and remove it BEFORE emitting
342
+ // This ensures the UI sees the updated queue state
343
+ if (event.type === "message_start" && event.message.role === "user") {
344
+ this._overflowRecoveryAttempted = false;
345
+ const messageText = contentText(event.message.content, "");
346
+ if (messageText) {
347
+ // Check steering queue first
348
+ const steeringIndex = this._steeringMessages.indexOf(messageText);
349
+ if (steeringIndex !== -1) {
350
+ this._steeringMessages.splice(steeringIndex, 1);
351
+ this._emitQueueUpdate();
352
+ }
353
+ else {
354
+ // Check follow-up queue
355
+ const followUpIndex = this._followUpMessages.indexOf(messageText);
356
+ if (followUpIndex !== -1) {
357
+ this._followUpMessages.splice(followUpIndex, 1);
358
+ this._emitQueueUpdate();
359
+ }
360
+ }
361
+ }
362
+ }
363
+ // Emit to extensions first
364
+ await this._emitExtensionEvent(event);
365
+ // Notify all listeners
366
+ this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
367
+ // Handle session persistence
368
+ if (event.type === "message_end") {
369
+ // Check if this is a custom message from extensions
370
+ if (event.message.role === "custom") {
371
+ // Persist as CustomMessageEntry
372
+ this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
373
+ }
374
+ else if (event.message.role === "user" ||
375
+ event.message.role === "assistant" ||
376
+ event.message.role === "toolResult") {
377
+ // Regular LLM message - persist as SessionMessageEntry
378
+ this.sessionManager.appendMessage(event.message);
379
+ }
380
+ // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
381
+ // Track assistant message for auto-compaction (checked on agent_end)
382
+ if (event.message.role === "assistant") {
383
+ this._lastAssistantMessage = event.message;
384
+ const assistantMsg = event.message;
385
+ if (assistantMsg.stopReason !== "error" && assistantMsg.stopReason !== "length") {
386
+ this._overflowRecoveryAttempted = false;
387
+ }
388
+ // Reset retry counter immediately on successful assistant response
389
+ // This prevents accumulation across multiple LLM calls within a turn
390
+ if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
391
+ this._emit({
392
+ type: "auto_retry_end",
393
+ success: true,
394
+ attempt: this._retryAttempt,
395
+ });
396
+ this._retryAttempt = 0;
397
+ }
398
+ }
399
+ }
400
+ };
401
+ _willRetryAfterAgentEnd(event) {
402
+ const settings = this.settingsManager.getRetrySettings();
403
+ if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
404
+ return false;
405
+ }
406
+ for (let i = event.messages.length - 1; i >= 0; i--) {
407
+ const message = event.messages[i];
408
+ if (message.role === "assistant") {
409
+ return this._isRetryableError(message);
410
+ }
411
+ }
412
+ return false;
413
+ }
414
+ /** Find the last assistant message in agent state (including aborted ones) */
415
+ _findLastAssistantMessage() {
416
+ const messages = this.agent.state.messages;
417
+ for (let i = messages.length - 1; i >= 0; i--) {
418
+ const msg = messages[i];
419
+ if (msg.role === "assistant") {
420
+ return msg;
421
+ }
422
+ }
423
+ return undefined;
424
+ }
425
+ _replaceMessageInPlace(target, replacement) {
426
+ // Agent-core stores the finalized message object in its state before emitting message_end.
427
+ // SessionManager persistence happens later in _handleAgentEvent() with event.message.
428
+ // Mutating this object in place keeps agent state, later turn/agent events, listeners,
429
+ // and the eventual SessionManager.appendMessage(event.message) persistence in sync.
430
+ if (target === replacement) {
431
+ return;
432
+ }
433
+ const targetRecord = target;
434
+ for (const key of Object.keys(targetRecord)) {
435
+ delete targetRecord[key];
436
+ }
437
+ Object.assign(targetRecord, replacement);
438
+ }
439
+ /** Emit extension events based on agent events */
440
+ async _emitExtensionEvent(event) {
441
+ if (event.type === "agent_start") {
442
+ this._turnIndex = 0;
443
+ await this._extensionRunner.emit({ type: "agent_start" });
444
+ }
445
+ else if (event.type === "agent_end") {
446
+ await this._extensionRunner.emit({ type: "agent_end", messages: event.messages });
447
+ }
448
+ else if (event.type === "turn_start") {
449
+ const extensionEvent = {
450
+ type: "turn_start",
451
+ turnIndex: this._turnIndex,
452
+ timestamp: Date.now(),
453
+ };
454
+ await this._extensionRunner.emit(extensionEvent);
455
+ }
456
+ else if (event.type === "turn_end") {
457
+ const extensionEvent = {
458
+ type: "turn_end",
459
+ turnIndex: this._turnIndex,
460
+ message: event.message,
461
+ toolResults: event.toolResults,
462
+ };
463
+ await this._extensionRunner.emit(extensionEvent);
464
+ this._turnIndex++;
465
+ }
466
+ else if (event.type === "message_start") {
467
+ const extensionEvent = {
468
+ type: "message_start",
469
+ message: event.message,
470
+ };
471
+ await this._extensionRunner.emit(extensionEvent);
472
+ }
473
+ else if (event.type === "message_update") {
474
+ const extensionEvent = {
475
+ type: "message_update",
476
+ message: event.message,
477
+ assistantMessageEvent: event.assistantMessageEvent,
478
+ };
479
+ await this._extensionRunner.emit(extensionEvent);
480
+ }
481
+ else if (event.type === "message_end") {
482
+ const extensionEvent = {
483
+ type: "message_end",
484
+ message: event.message,
485
+ };
486
+ const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
487
+ if (replacement) {
488
+ // Untyped extension handlers can return messages with null/missing content;
489
+ // normalize so it never enters agent state or session history.
490
+ const normalized = (replacement.role === "user" ||
491
+ replacement.role === "assistant" ||
492
+ replacement.role === "toolResult" ||
493
+ replacement.role === "custom") &&
494
+ replacement.content == null
495
+ ? { ...replacement, content: [] }
496
+ : replacement;
497
+ this._replaceMessageInPlace(event.message, normalized);
498
+ }
499
+ }
500
+ else if (event.type === "tool_execution_start") {
501
+ const extensionEvent = {
502
+ type: "tool_execution_start",
503
+ toolCallId: event.toolCallId,
504
+ toolName: event.toolName,
505
+ args: event.args,
506
+ };
507
+ await this._extensionRunner.emit(extensionEvent);
508
+ }
509
+ else if (event.type === "tool_execution_update") {
510
+ const extensionEvent = {
511
+ type: "tool_execution_update",
512
+ toolCallId: event.toolCallId,
513
+ toolName: event.toolName,
514
+ args: event.args,
515
+ partialResult: event.partialResult,
516
+ };
517
+ await this._extensionRunner.emit(extensionEvent);
518
+ }
519
+ else if (event.type === "tool_execution_end") {
520
+ const extensionEvent = {
521
+ type: "tool_execution_end",
522
+ toolCallId: event.toolCallId,
523
+ toolName: event.toolName,
524
+ result: event.result,
525
+ isError: event.isError,
526
+ };
527
+ await this._extensionRunner.emit(extensionEvent);
528
+ }
529
+ }
530
+ /**
531
+ * Subscribe to agent events.
532
+ * Session persistence is handled internally (saves messages on message_end).
533
+ * Multiple listeners can be added. Returns unsubscribe function for this listener.
534
+ */
535
+ subscribe(listener) {
536
+ this._eventListeners.push(listener);
537
+ // Return unsubscribe function for this specific listener
538
+ return () => {
539
+ const index = this._eventListeners.indexOf(listener);
540
+ if (index !== -1) {
541
+ this._eventListeners.splice(index, 1);
542
+ }
543
+ };
544
+ }
545
+ /** Disconnect from agent events during disposal. */
546
+ _disconnectFromAgent() {
547
+ if (this._unsubscribeAgent) {
548
+ this._unsubscribeAgent();
549
+ this._unsubscribeAgent = undefined;
550
+ }
551
+ }
552
+ /**
553
+ * Remove all listeners and disconnect from agent.
554
+ * Call this when completely done with the session.
555
+ */
556
+ dispose() {
557
+ try {
558
+ this.abortRetry();
559
+ this.abortCompaction();
560
+ this.abortBranchSummary();
561
+ this.abortBash();
562
+ this.agent.abort();
563
+ }
564
+ catch {
565
+ // Dispose must succeed even if an abort hook throws.
566
+ }
567
+ 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().");
568
+ this._disconnectFromAgent();
569
+ this._eventListeners = [];
570
+ cleanupSessionResources(this.sessionId);
571
+ }
572
+ // =========================================================================
573
+ // Read-only State Access
574
+ // =========================================================================
575
+ /** Full agent state */
576
+ get state() {
577
+ return this.agent.state;
578
+ }
579
+ /** Current model (may be undefined if not yet selected) */
580
+ get model() {
581
+ return this.agent.state.model;
582
+ }
583
+ /** Current thinking level */
584
+ get thinkingLevel() {
585
+ return this.agent.state.thinkingLevel;
586
+ }
587
+ /** Whether the session is currently processing an agent run or post-run continuation. */
588
+ get isStreaming() {
589
+ return this._isAgentRunActive;
590
+ }
591
+ /** Whether the session has no active agent run, retry, auto-compaction, or queued continuation. */
592
+ get isIdle() {
593
+ return !this._isAgentRunActive;
594
+ }
595
+ /** Current effective system prompt (includes any per-turn extension modifications) */
596
+ get systemPrompt() {
597
+ return this.agent.state.systemPrompt;
598
+ }
599
+ /** Current retry attempt (0 if not retrying) */
600
+ get retryAttempt() {
601
+ return this._retryAttempt;
602
+ }
603
+ /**
604
+ * Get the names of currently active tools.
605
+ * Returns the names of tools currently set on the agent.
606
+ */
607
+ getActiveToolNames() {
608
+ return this.agent.state.tools.map((t) => t.name);
609
+ }
610
+ /**
611
+ * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
612
+ */
613
+ getAllTools() {
614
+ return Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({
615
+ name: definition.name,
616
+ description: definition.description,
617
+ parameters: definition.parameters,
618
+ promptGuidelines: definition.promptGuidelines,
619
+ sourceInfo,
620
+ }));
621
+ }
622
+ getToolDefinition(name) {
623
+ return this._toolDefinitions.get(name)?.definition;
624
+ }
625
+ /**
626
+ * Set active tools by name.
627
+ * Only tools in the registry can be enabled. Unknown tool names are ignored.
628
+ * Also rebuilds the system prompt to reflect the new tool set.
629
+ * Changes take effect on the next agent turn.
630
+ */
631
+ setActiveToolsByName(toolNames) {
632
+ const tools = [];
633
+ const validToolNames = [];
634
+ for (const name of toolNames) {
635
+ const tool = this._toolRegistry.get(name);
636
+ if (tool) {
637
+ tools.push(tool);
638
+ validToolNames.push(name);
639
+ }
640
+ }
641
+ this.agent.state.tools = tools;
642
+ // Rebuild base system prompt with new tool set
643
+ this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
644
+ this.agent.state.systemPrompt = this._systemPromptOverride ?? this._baseSystemPrompt;
645
+ }
646
+ /** Whether compaction or branch summarization is currently running */
647
+ get isCompacting() {
648
+ return (this._autoCompactionAbortController !== undefined ||
649
+ this._compactionAbortController !== undefined ||
650
+ this._branchSummaryAbortController !== undefined);
651
+ }
652
+ /** All messages including custom types like BashExecutionMessage */
653
+ get messages() {
654
+ return this.agent.state.messages;
655
+ }
656
+ /** Current steering mode */
657
+ get steeringMode() {
658
+ return this.agent.steeringMode;
659
+ }
660
+ /** Current follow-up mode */
661
+ get followUpMode() {
662
+ return this.agent.followUpMode;
663
+ }
664
+ /** Current session file path, or undefined if sessions are disabled */
665
+ get sessionFile() {
666
+ return this.sessionManager.getSessionFile();
667
+ }
668
+ /** Current session ID */
669
+ get sessionId() {
670
+ return this.sessionManager.getSessionId();
671
+ }
672
+ /** Current session display name, if set */
673
+ get sessionName() {
674
+ return this.sessionManager.getSessionName();
675
+ }
676
+ /** Scoped models for cycling (from --models flag) */
677
+ get scopedModels() {
678
+ return this._scopedModels;
679
+ }
680
+ /** Update scoped models for cycling */
681
+ setScopedModels(scopedModels) {
682
+ this._scopedModels = scopedModels;
683
+ }
684
+ /** File-based prompt templates */
685
+ get promptTemplates() {
686
+ return this._resourceLoader.getPrompts().prompts;
687
+ }
688
+ _normalizePromptSnippet(text) {
689
+ if (!text)
690
+ return undefined;
691
+ const oneLine = text
692
+ .replace(/[\r\n]+/g, " ")
693
+ .replace(/\s+/g, " ")
694
+ .trim();
695
+ return oneLine.length > 0 ? oneLine : undefined;
696
+ }
697
+ _normalizePromptGuidelines(guidelines) {
698
+ if (!guidelines || guidelines.length === 0) {
699
+ return [];
700
+ }
701
+ const unique = new Set();
702
+ for (const guideline of guidelines) {
703
+ const normalized = guideline.trim();
704
+ if (normalized.length > 0) {
705
+ unique.add(normalized);
706
+ }
707
+ }
708
+ return Array.from(unique);
709
+ }
710
+ _rebuildSystemPrompt(toolNames) {
711
+ const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
712
+ const toolSnippets = {};
713
+ const promptGuidelines = [];
714
+ for (const name of validToolNames) {
715
+ const snippet = this._toolPromptSnippets.get(name);
716
+ if (snippet) {
717
+ toolSnippets[name] = snippet;
718
+ }
719
+ const toolGuidelines = this._toolPromptGuidelines.get(name);
720
+ if (toolGuidelines) {
721
+ promptGuidelines.push(...toolGuidelines);
722
+ }
723
+ }
724
+ const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
725
+ const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
726
+ const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
727
+ const loadedSkills = this._resourceLoader.getSkills().skills;
728
+ const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
729
+ this._baseSystemPromptOptions = {
730
+ cwd: this._cwd,
731
+ skills: loadedSkills,
732
+ contextFiles: loadedContextFiles,
733
+ customPrompt: loaderSystemPrompt,
734
+ appendSystemPrompt,
735
+ selectedTools: validToolNames,
736
+ toolSnippets,
737
+ promptGuidelines,
738
+ };
739
+ return buildSystemPrompt(this._baseSystemPromptOptions);
740
+ }
741
+ // =========================================================================
742
+ // Prompting
743
+ // =========================================================================
744
+ async _runAgentPrompt(messages) {
745
+ this._isAgentRunActive = true;
746
+ try {
747
+ await this.agent.prompt(messages);
748
+ while (await this._handlePostAgentRun()) {
749
+ await this.agent.continue();
750
+ }
751
+ }
752
+ finally {
753
+ this._systemPromptOverride = undefined;
754
+ this._flushPendingBashMessages();
755
+ await this._emitAgentSettled();
756
+ }
757
+ }
758
+ async _handlePostAgentRun() {
759
+ const msg = this._lastAssistantMessage;
760
+ this._lastAssistantMessage = undefined;
761
+ if (!msg) {
762
+ return false;
763
+ }
764
+ if (this._isRetryableError(msg) && (await this._prepareRetry(msg))) {
765
+ return true;
766
+ }
767
+ if (msg.stopReason === "error" && this._retryAttempt > 0) {
768
+ this._emit({
769
+ type: "auto_retry_end",
770
+ success: false,
771
+ attempt: this._retryAttempt,
772
+ finalError: msg.errorMessage,
773
+ });
774
+ this._retryAttempt = 0;
775
+ }
776
+ if (await this._checkCompaction(msg)) {
777
+ return true;
778
+ }
779
+ // The agent loop drains both queues before emitting agent_end. Any messages
780
+ // here were queued by agent_end extension handlers and need a continuation.
781
+ return this.agent.hasQueuedMessages();
782
+ }
783
+ /**
784
+ * Send a prompt to the agent.
785
+ * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
786
+ * - Expands file-based prompt templates by default
787
+ * - During streaming, queues via steer() or followUp() based on streamingBehavior option
788
+ * - Validates model and API key before sending (when not streaming)
789
+ * @throws Error if streaming and no streamingBehavior specified
790
+ * @throws Error if no model selected or no API key available (when not streaming)
791
+ */
792
+ async prompt(text, options) {
793
+ const expandPromptTemplates = options?.expandPromptTemplates ?? true;
794
+ const preflightResult = options?.preflightResult;
795
+ let messages;
796
+ try {
797
+ // Handle extension commands first (execute immediately, even during streaming)
798
+ // Extension commands manage their own LLM interaction via pi.sendMessage()
799
+ if (expandPromptTemplates && text.startsWith("/")) {
800
+ const handled = await this._tryExecuteExtensionCommand(text);
801
+ if (handled) {
802
+ // Extension command executed, no prompt to send
803
+ preflightResult?.(true);
804
+ return;
805
+ }
806
+ }
807
+ if (this._compactionAbortController !== undefined) {
808
+ throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");
809
+ }
810
+ // Emit input event for extension interception (before skill/template expansion)
811
+ let currentText = text;
812
+ let currentImages = options?.images;
813
+ if (this._extensionRunner.hasHandlers("input")) {
814
+ const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
815
+ if (inputResult.action === "handled") {
816
+ preflightResult?.(true);
817
+ return;
818
+ }
819
+ if (inputResult.action === "transform") {
820
+ currentText = inputResult.text;
821
+ currentImages = inputResult.images ?? currentImages;
822
+ }
823
+ }
824
+ // Expand skill commands (/skill:name args) and prompt templates (/template args)
825
+ let expandedText = currentText;
826
+ if (expandPromptTemplates) {
827
+ expandedText = this._expandSkillCommand(expandedText);
828
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
829
+ }
830
+ // If streaming, queue via steer() or followUp() based on option
831
+ if (this.isStreaming) {
832
+ if (!options?.streamingBehavior) {
833
+ throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
834
+ }
835
+ if (options.streamingBehavior === "followUp") {
836
+ await this._queueFollowUp(expandedText, currentImages);
837
+ }
838
+ else {
839
+ await this._queueSteer(expandedText, currentImages);
840
+ }
841
+ preflightResult?.(true);
842
+ return;
843
+ }
844
+ // Flush any pending bash messages before the new prompt
845
+ this._flushPendingBashMessages();
846
+ // Validate model
847
+ if (!this.model) {
848
+ throw new Error(formatNoModelSelectedMessage());
849
+ }
850
+ const hasConfiguredAuth = this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
851
+ (await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
852
+ if (!hasConfiguredAuth) {
853
+ const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
854
+ if (isOAuth) {
855
+ throw new Error(`Authentication failed for "${this.model.provider}". ` +
856
+ `Credentials may have expired or network is unavailable. ` +
857
+ `Run '/login ${this.model.provider}' to re-authenticate.`);
858
+ }
859
+ throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
860
+ }
861
+ // Check if we need to compact before sending (catches aborted responses).
862
+ // The user's new prompt is sent below, so do not call agent.continue() here.
863
+ const lastAssistant = this._findLastAssistantMessage();
864
+ if (lastAssistant) {
865
+ await this._checkCompaction(lastAssistant, false);
866
+ }
867
+ // Build messages array (custom message if any, then user message)
868
+ messages = [];
869
+ // Add user message
870
+ const userContent = [{ type: "text", text: expandedText }];
871
+ if (currentImages) {
872
+ userContent.push(...currentImages);
873
+ }
874
+ messages.push({
875
+ role: "user",
876
+ content: userContent,
877
+ timestamp: Date.now(),
878
+ });
879
+ // Inject any pending "nextTurn" messages as context alongside the user message
880
+ for (const msg of this._pendingNextTurnMessages) {
881
+ messages.push(msg);
882
+ }
883
+ this._pendingNextTurnMessages = [];
884
+ // Emit before_agent_start extension event
885
+ const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt, this._baseSystemPromptOptions);
886
+ // Add all custom messages from extensions
887
+ if (result?.messages) {
888
+ for (const msg of result.messages) {
889
+ messages.push({
890
+ role: "custom",
891
+ customType: msg.customType,
892
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
893
+ content: msg.content ?? [],
894
+ display: msg.display,
895
+ details: msg.details,
896
+ timestamp: Date.now(),
897
+ });
898
+ }
899
+ }
900
+ // Apply extension-modified system prompt, or reset to base
901
+ if (result?.systemPrompt !== undefined) {
902
+ this._systemPromptOverride = result.systemPrompt;
903
+ this.agent.state.systemPrompt = result.systemPrompt;
904
+ }
905
+ else {
906
+ // Ensure we're using the base prompt (in case previous turn had modifications)
907
+ this._systemPromptOverride = undefined;
908
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
909
+ }
910
+ }
911
+ catch (error) {
912
+ preflightResult?.(false);
913
+ throw error;
914
+ }
915
+ if (!messages) {
916
+ return;
917
+ }
918
+ preflightResult?.(true);
919
+ await this._runAgentPrompt(messages);
920
+ }
921
+ /**
922
+ * Try to execute an extension command. Returns true if command was found and executed.
923
+ */
924
+ async _tryExecuteExtensionCommand(text) {
925
+ // Parse command name and args
926
+ const spaceIndex = text.indexOf(" ");
927
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
928
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
929
+ const command = this._extensionRunner.getCommand(commandName);
930
+ if (!command)
931
+ return false;
932
+ // Get command context from extension runner (includes session control methods)
933
+ const ctx = this._extensionRunner.createCommandContext();
934
+ try {
935
+ await command.handler(args, ctx);
936
+ return true;
937
+ }
938
+ catch (err) {
939
+ // Emit error via extension runner
940
+ this._extensionRunner.emitError({
941
+ extensionPath: `command:${commandName}`,
942
+ event: "command",
943
+ error: err instanceof Error ? err.message : String(err),
944
+ });
945
+ return true;
946
+ }
947
+ }
948
+ /**
949
+ * Expand skill commands (/skill:name args) to their full content.
950
+ * Returns the expanded text, or the original text if not a skill command or skill not found.
951
+ * Emits errors via extension runner if file read fails.
952
+ */
953
+ _expandSkillCommand(text) {
954
+ if (!text.startsWith("/skill:"))
955
+ return text;
956
+ const spaceIndex = text.indexOf(" ");
957
+ const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
958
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
959
+ const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
960
+ if (!skill)
961
+ return text; // Unknown skill, pass through
962
+ try {
963
+ const content = readFileSync(skill.filePath, "utf-8");
964
+ const body = stripFrontmatter(content).trim();
965
+ const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
966
+ return args ? `${skillBlock}\n\n${args}` : skillBlock;
967
+ }
968
+ catch (err) {
969
+ // Emit error like extension commands do
970
+ this._extensionRunner.emitError({
971
+ extensionPath: skill.filePath,
972
+ event: "skill_expansion",
973
+ error: err instanceof Error ? err.message : String(err),
974
+ });
975
+ return text; // Return original on error
976
+ }
977
+ }
978
+ /**
979
+ * Queue a steering message while the agent is running.
980
+ * Delivered after the current assistant turn finishes executing its tool calls,
981
+ * before the next LLM call.
982
+ * Expands skill commands and prompt templates. Errors on extension commands.
983
+ * @param images Optional image attachments to include with the message
984
+ * @throws Error if text is an extension command
985
+ */
986
+ async steer(text, images) {
987
+ // Check for extension commands (cannot be queued)
988
+ if (text.startsWith("/")) {
989
+ this._throwIfExtensionCommand(text);
990
+ }
991
+ // Expand skill commands and prompt templates
992
+ let expandedText = this._expandSkillCommand(text);
993
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
994
+ await this._queueSteer(expandedText, images);
995
+ }
996
+ /**
997
+ * Queue a follow-up message to be processed after the agent finishes.
998
+ * Delivered only when agent has no more tool calls or steering messages.
999
+ * Expands skill commands and prompt templates. Errors on extension commands.
1000
+ * @param images Optional image attachments to include with the message
1001
+ * @throws Error if text is an extension command
1002
+ */
1003
+ async followUp(text, images) {
1004
+ // Check for extension commands (cannot be queued)
1005
+ if (text.startsWith("/")) {
1006
+ this._throwIfExtensionCommand(text);
1007
+ }
1008
+ // Expand skill commands and prompt templates
1009
+ let expandedText = this._expandSkillCommand(text);
1010
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1011
+ await this._queueFollowUp(expandedText, images);
1012
+ }
1013
+ /**
1014
+ * Internal: Queue a steering message (already expanded, no extension command check).
1015
+ */
1016
+ async _queueSteer(text, images) {
1017
+ this._steeringMessages.push(text);
1018
+ this._emitQueueUpdate();
1019
+ const content = [{ type: "text", text }];
1020
+ if (images) {
1021
+ content.push(...images);
1022
+ }
1023
+ this.agent.steer({
1024
+ role: "user",
1025
+ content,
1026
+ timestamp: Date.now(),
1027
+ });
1028
+ }
1029
+ /**
1030
+ * Internal: Queue a follow-up message (already expanded, no extension command check).
1031
+ */
1032
+ async _queueFollowUp(text, images) {
1033
+ this._followUpMessages.push(text);
1034
+ this._emitQueueUpdate();
1035
+ const content = [{ type: "text", text }];
1036
+ if (images) {
1037
+ content.push(...images);
1038
+ }
1039
+ this.agent.followUp({
1040
+ role: "user",
1041
+ content,
1042
+ timestamp: Date.now(),
1043
+ });
1044
+ }
1045
+ /**
1046
+ * Throw an error if the text is an extension command.
1047
+ */
1048
+ _throwIfExtensionCommand(text) {
1049
+ const spaceIndex = text.indexOf(" ");
1050
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
1051
+ const command = this._extensionRunner.getCommand(commandName);
1052
+ if (command) {
1053
+ throw new Error(`Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`);
1054
+ }
1055
+ }
1056
+ /**
1057
+ * Send a custom message to the session. Creates a CustomMessageEntry.
1058
+ *
1059
+ * Handles three cases:
1060
+ * - Streaming: queues message, processed when loop pulls from queue
1061
+ * - Not streaming + triggerTurn: appends to state/session, starts new turn
1062
+ * - Not streaming + no trigger: appends to state/session, no turn
1063
+ *
1064
+ * @param message Custom message with customType, content, display, details
1065
+ * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
1066
+ * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
1067
+ */
1068
+ async sendCustomMessage(message, options) {
1069
+ const appMessage = {
1070
+ role: "custom",
1071
+ customType: message.customType,
1072
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
1073
+ content: message.content ?? [],
1074
+ display: message.display,
1075
+ details: message.details,
1076
+ timestamp: Date.now(),
1077
+ };
1078
+ if (options?.deliverAs === "nextTurn") {
1079
+ this._pendingNextTurnMessages.push(appMessage);
1080
+ }
1081
+ else if (this.isStreaming && options?.triggerTurn !== false) {
1082
+ if (options?.deliverAs === "followUp") {
1083
+ this.agent.followUp(appMessage);
1084
+ }
1085
+ else {
1086
+ this.agent.steer(appMessage);
1087
+ }
1088
+ }
1089
+ else if (options?.triggerTurn) {
1090
+ await this._runAgentPrompt(appMessage);
1091
+ }
1092
+ else {
1093
+ this.agent.state.messages.push(appMessage);
1094
+ this.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details);
1095
+ this._emit({ type: "message_start", message: appMessage });
1096
+ this._emit({ type: "message_end", message: appMessage });
1097
+ }
1098
+ }
1099
+ /**
1100
+ * Send a user message to the agent. Always triggers a turn.
1101
+ * When the agent is streaming, use deliverAs to specify how to queue the message.
1102
+ *
1103
+ * @param content User message content (string or content array)
1104
+ * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
1105
+ * @param options.expandPromptTemplates Whether to dispatch extension commands and expand skill commands and prompt templates. Default: false.
1106
+ */
1107
+ async sendUserMessage(content, options) {
1108
+ // Normalize content to text string + optional images
1109
+ let text;
1110
+ let images;
1111
+ if (typeof content === "string") {
1112
+ text = content;
1113
+ }
1114
+ else {
1115
+ const textParts = [];
1116
+ images = [];
1117
+ for (const part of content) {
1118
+ if (part.type === "text") {
1119
+ textParts.push(part.text);
1120
+ }
1121
+ else {
1122
+ images.push(part);
1123
+ }
1124
+ }
1125
+ text = textParts.join("\n");
1126
+ if (images.length === 0)
1127
+ images = undefined;
1128
+ }
1129
+ await this.prompt(text, {
1130
+ expandPromptTemplates: options?.expandPromptTemplates ?? false,
1131
+ streamingBehavior: options?.deliverAs,
1132
+ images,
1133
+ source: "extension",
1134
+ });
1135
+ }
1136
+ /**
1137
+ * Clear all queued messages and return them.
1138
+ * Useful for restoring to editor when user aborts.
1139
+ * @returns Object with steering and followUp arrays
1140
+ */
1141
+ clearQueue() {
1142
+ const steering = [...this._steeringMessages];
1143
+ const followUp = [...this._followUpMessages];
1144
+ this._steeringMessages = [];
1145
+ this._followUpMessages = [];
1146
+ this.agent.clearAllQueues();
1147
+ this._emitQueueUpdate();
1148
+ return { steering, followUp };
1149
+ }
1150
+ /** Number of pending messages (includes both steering and follow-up) */
1151
+ get pendingMessageCount() {
1152
+ return this._steeringMessages.length + this._followUpMessages.length;
1153
+ }
1154
+ /** Get pending steering messages (read-only) */
1155
+ getSteeringMessages() {
1156
+ return this._steeringMessages;
1157
+ }
1158
+ /** Get pending follow-up messages (read-only) */
1159
+ getFollowUpMessages() {
1160
+ return this._followUpMessages;
1161
+ }
1162
+ get resourceLoader() {
1163
+ return this._resourceLoader;
1164
+ }
1165
+ /**
1166
+ * Abort current operation and wait for agent to become idle.
1167
+ */
1168
+ async abort() {
1169
+ this.abortRetry();
1170
+ this.agent.abort();
1171
+ await this.waitForIdle();
1172
+ }
1173
+ async waitForIdle() {
1174
+ if (this.isIdle) {
1175
+ return;
1176
+ }
1177
+ await this._getIdleWaitPromise();
1178
+ }
1179
+ // =========================================================================
1180
+ // Model Management
1181
+ // =========================================================================
1182
+ async _emitModelSelect(nextModel, previousModel, source) {
1183
+ if (modelsAreEqual(previousModel, nextModel))
1184
+ return;
1185
+ await this._extensionRunner.emit({
1186
+ type: "model_select",
1187
+ model: nextModel,
1188
+ previousModel,
1189
+ source,
1190
+ });
1191
+ }
1192
+ /**
1193
+ * Set model directly.
1194
+ * Validates that auth is configured, saves to session and settings.
1195
+ * @throws Error if no auth is configured for the model
1196
+ */
1197
+ async setModel(model) {
1198
+ if (!(await this._modelRuntime.checkAuth(model.provider))) {
1199
+ throw new Error(`No API key for ${model.provider}/${model.id}`);
1200
+ }
1201
+ const previousModel = this.model;
1202
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
1203
+ this.agent.state.model = model;
1204
+ this.sessionManager.appendModelChange(model.provider, model.id);
1205
+ this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1206
+ // Re-clamp thinking level for new model's capabilities
1207
+ this.setThinkingLevel(thinkingLevel);
1208
+ await this._emitModelSelect(model, previousModel, "set");
1209
+ }
1210
+ /**
1211
+ * Cycle to next/previous model.
1212
+ * Uses scoped models (from --models flag) if available, otherwise all available models.
1213
+ * @param direction - "forward" (default) or "backward"
1214
+ * @returns The new model info, or undefined if only one model available
1215
+ */
1216
+ async cycleModel(direction = "forward") {
1217
+ if (this._scopedModels.length > 0) {
1218
+ return this._cycleScopedModel(direction);
1219
+ }
1220
+ return this._cycleAvailableModel(direction);
1221
+ }
1222
+ async _cycleScopedModel(direction) {
1223
+ const availableIds = new Set(this._modelRuntime.getAvailableSnapshot().map((model) => `${model.provider}\0${model.id}`));
1224
+ const scopedModels = this._scopedModels.filter((scoped) => availableIds.has(`${scoped.model.provider}\0${scoped.model.id}`));
1225
+ if (scopedModels.length <= 1)
1226
+ return undefined;
1227
+ const currentModel = this.model;
1228
+ let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
1229
+ if (currentIndex === -1)
1230
+ currentIndex = 0;
1231
+ const len = scopedModels.length;
1232
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1233
+ const next = scopedModels[nextIndex];
1234
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
1235
+ // Apply model
1236
+ this.agent.state.model = next.model;
1237
+ this.sessionManager.appendModelChange(next.model.provider, next.model.id);
1238
+ this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
1239
+ // Apply thinking level.
1240
+ // - Explicit scoped model thinking level overrides current session level
1241
+ // - Undefined scoped model thinking level inherits the current session preference
1242
+ // setThinkingLevel clamps to model capabilities.
1243
+ this.setThinkingLevel(thinkingLevel);
1244
+ await this._emitModelSelect(next.model, currentModel, "cycle");
1245
+ return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
1246
+ }
1247
+ async _cycleAvailableModel(direction) {
1248
+ const availableModels = this._modelRuntime.getAvailableSnapshot();
1249
+ if (availableModels.length <= 1)
1250
+ return undefined;
1251
+ const currentModel = this.model;
1252
+ let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
1253
+ if (currentIndex === -1)
1254
+ currentIndex = 0;
1255
+ const len = availableModels.length;
1256
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1257
+ const nextModel = availableModels[nextIndex];
1258
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
1259
+ this.agent.state.model = nextModel;
1260
+ this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
1261
+ this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
1262
+ // Re-clamp thinking level for new model's capabilities
1263
+ this.setThinkingLevel(thinkingLevel);
1264
+ await this._emitModelSelect(nextModel, currentModel, "cycle");
1265
+ return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
1266
+ }
1267
+ // =========================================================================
1268
+ // Thinking Level Management
1269
+ // =========================================================================
1270
+ /**
1271
+ * Set thinking level.
1272
+ * Clamps to model capabilities based on available thinking levels.
1273
+ * Saves to session and settings only if the level actually changes.
1274
+ */
1275
+ setThinkingLevel(level) {
1276
+ const availableLevels = this.getAvailableThinkingLevels();
1277
+ const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
1278
+ // Only persist if actually changing
1279
+ const previousLevel = this.agent.state.thinkingLevel;
1280
+ const isChanging = effectiveLevel !== previousLevel;
1281
+ this.agent.state.thinkingLevel = effectiveLevel;
1282
+ if (isChanging) {
1283
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1284
+ if (this.supportsThinking() || effectiveLevel !== "off") {
1285
+ this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
1286
+ }
1287
+ this._emit({ type: "thinking_level_changed", level: effectiveLevel });
1288
+ void this._extensionRunner.emit({
1289
+ type: "thinking_level_select",
1290
+ level: effectiveLevel,
1291
+ previousLevel,
1292
+ });
1293
+ }
1294
+ }
1295
+ /**
1296
+ * Cycle to next thinking level.
1297
+ * @returns New level, or undefined if model doesn't support thinking
1298
+ */
1299
+ cycleThinkingLevel() {
1300
+ if (!this.supportsThinking())
1301
+ return undefined;
1302
+ const levels = this.getAvailableThinkingLevels();
1303
+ const currentIndex = levels.indexOf(this.thinkingLevel);
1304
+ const nextIndex = (currentIndex + 1) % levels.length;
1305
+ const nextLevel = levels[nextIndex];
1306
+ this.setThinkingLevel(nextLevel);
1307
+ return nextLevel;
1308
+ }
1309
+ /**
1310
+ * Get available thinking levels for current model.
1311
+ * The provider will clamp to what the specific model supports internally.
1312
+ */
1313
+ getAvailableThinkingLevels() {
1314
+ if (!this.model)
1315
+ return THINKING_LEVELS;
1316
+ return getSupportedThinkingLevels(this.model);
1317
+ }
1318
+ /**
1319
+ * Check if current model supports thinking/reasoning.
1320
+ */
1321
+ supportsThinking() {
1322
+ return !!this.model?.reasoning;
1323
+ }
1324
+ _getThinkingLevelForModelSwitch(explicitLevel) {
1325
+ if (explicitLevel !== undefined) {
1326
+ return explicitLevel;
1327
+ }
1328
+ if (!this.supportsThinking()) {
1329
+ return this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
1330
+ }
1331
+ return this.thinkingLevel;
1332
+ }
1333
+ _clampThinkingLevel(level, _availableLevels) {
1334
+ return this.model ? clampThinkingLevel(this.model, level) : "off";
1335
+ }
1336
+ // =========================================================================
1337
+ // Queue Mode Management
1338
+ // =========================================================================
1339
+ syncQueueModesFromSettings() {
1340
+ this.agent.steeringMode = this.settingsManager.getSteeringMode();
1341
+ this.agent.followUpMode = this.settingsManager.getFollowUpMode();
1342
+ }
1343
+ /**
1344
+ * Set steering message mode.
1345
+ * Saves to settings.
1346
+ */
1347
+ setSteeringMode(mode) {
1348
+ this.agent.steeringMode = mode;
1349
+ this.settingsManager.setSteeringMode(mode);
1350
+ }
1351
+ /**
1352
+ * Set follow-up message mode.
1353
+ * Saves to settings.
1354
+ */
1355
+ setFollowUpMode(mode) {
1356
+ this.agent.followUpMode = mode;
1357
+ this.settingsManager.setFollowUpMode(mode);
1358
+ }
1359
+ // =========================================================================
1360
+ // Compaction
1361
+ // =========================================================================
1362
+ /**
1363
+ * Manually compact the session context.
1364
+ * Aborts current agent operation first.
1365
+ * @param customInstructions Optional instructions for the compaction summary
1366
+ */
1367
+ async compact(customInstructions) {
1368
+ await this.abort();
1369
+ this._compactionAbortController = new AbortController();
1370
+ this._emit({ type: "compaction_start", reason: "manual" });
1371
+ try {
1372
+ if (!this.model) {
1373
+ throw new Error(formatNoModelSelectedMessage());
1374
+ }
1375
+ const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model);
1376
+ const pathEntries = this.sessionManager.getBranch();
1377
+ const settings = this.settingsManager.getCompactionSettings();
1378
+ const preparation = prepareCompaction(pathEntries, settings);
1379
+ if (!preparation) {
1380
+ // Check why we can't compact
1381
+ const lastEntry = pathEntries[pathEntries.length - 1];
1382
+ if (lastEntry?.type === "compaction") {
1383
+ throw new Error("Already compacted");
1384
+ }
1385
+ throw new Error("Nothing to compact (session too small)");
1386
+ }
1387
+ let extensionCompaction;
1388
+ let fromExtension = false;
1389
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1390
+ const result = (await this._extensionRunner.emit({
1391
+ type: "session_before_compact",
1392
+ preparation,
1393
+ branchEntries: pathEntries,
1394
+ customInstructions,
1395
+ reason: "manual",
1396
+ willRetry: false,
1397
+ signal: this._compactionAbortController.signal,
1398
+ }));
1399
+ if (result?.cancel) {
1400
+ throw new Error("Compaction cancelled");
1401
+ }
1402
+ if (result?.compaction) {
1403
+ extensionCompaction = result.compaction;
1404
+ fromExtension = true;
1405
+ }
1406
+ }
1407
+ let summary;
1408
+ let firstKeptEntryId;
1409
+ let tokensBefore;
1410
+ let usage;
1411
+ let details;
1412
+ if (extensionCompaction) {
1413
+ // Extension provided compaction content
1414
+ summary = extensionCompaction.summary;
1415
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1416
+ tokensBefore = extensionCompaction.tokensBefore;
1417
+ usage = extensionCompaction.usage;
1418
+ details = extensionCompaction.details;
1419
+ }
1420
+ else {
1421
+ // Generate compaction result
1422
+ const result = await compact(preparation, requestModel, apiKey, headers, customInstructions, this._compactionAbortController.signal, this.thinkingLevel, this.agent.streamFunction, env, this.settingsManager.getRetrySettings(), this._summarizationRetryCallbacks({ source: "compaction", reason: "manual" }));
1423
+ summary = result.summary;
1424
+ firstKeptEntryId = result.firstKeptEntryId;
1425
+ tokensBefore = result.tokensBefore;
1426
+ usage = result.usage;
1427
+ details = result.details;
1428
+ }
1429
+ if (this._compactionAbortController.signal.aborted) {
1430
+ throw new Error("Compaction cancelled");
1431
+ }
1432
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
1433
+ const newEntries = this.sessionManager.getEntries();
1434
+ const sessionContext = this.sessionManager.buildSessionContext();
1435
+ this.agent.state.messages = sessionContext.messages;
1436
+ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
1437
+ // Get the saved compaction entry for the extension event
1438
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1439
+ if (this._extensionRunner && savedCompactionEntry) {
1440
+ await this._extensionRunner.emit({
1441
+ type: "session_compact",
1442
+ compactionEntry: savedCompactionEntry,
1443
+ fromExtension,
1444
+ reason: "manual",
1445
+ willRetry: false,
1446
+ });
1447
+ }
1448
+ const compactionResult = {
1449
+ summary,
1450
+ firstKeptEntryId,
1451
+ tokensBefore,
1452
+ estimatedTokensAfter,
1453
+ usage,
1454
+ details,
1455
+ };
1456
+ // compaction_end listeners may submit queued prompts, so expose idle state before notifying them.
1457
+ this._compactionAbortController = undefined;
1458
+ this._emit({
1459
+ type: "compaction_end",
1460
+ reason: "manual",
1461
+ result: compactionResult,
1462
+ aborted: false,
1463
+ willRetry: false,
1464
+ });
1465
+ return compactionResult;
1466
+ }
1467
+ catch (error) {
1468
+ const message = error instanceof Error ? error.message : String(error);
1469
+ const aborted = message === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError");
1470
+ this._compactionAbortController = undefined;
1471
+ this._emit({
1472
+ type: "compaction_end",
1473
+ reason: "manual",
1474
+ result: undefined,
1475
+ aborted,
1476
+ willRetry: false,
1477
+ errorMessage: aborted ? undefined : `Compaction failed: ${message}`,
1478
+ });
1479
+ throw error;
1480
+ }
1481
+ finally {
1482
+ this._compactionAbortController = undefined;
1483
+ }
1484
+ }
1485
+ /**
1486
+ * Cancel in-progress compaction (manual or auto).
1487
+ */
1488
+ abortCompaction() {
1489
+ this._compactionAbortController?.abort();
1490
+ this._autoCompactionAbortController?.abort();
1491
+ }
1492
+ /**
1493
+ * Cancel in-progress branch summarization.
1494
+ */
1495
+ abortBranchSummary() {
1496
+ this._branchSummaryAbortController?.abort();
1497
+ }
1498
+ /**
1499
+ * Check if compaction is needed and run it.
1500
+ * Called after agent_end and before prompt submission.
1501
+ *
1502
+ * Two cases:
1503
+ * 1. Recoverable failure: LLM returned context overflow or stopped below its desired output limit;
1504
+ * remove the assistant message, compact, and auto-retry once
1505
+ * 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually)
1506
+ *
1507
+ * @param assistantMessage The assistant message to check
1508
+ * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
1509
+ */
1510
+ async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
1511
+ const settings = this.settingsManager.getCompactionSettings();
1512
+ if (!settings.enabled)
1513
+ return false;
1514
+ // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
1515
+ if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
1516
+ return false;
1517
+ const contextWindow = this.model?.contextWindow ?? 0;
1518
+ // Skip overflow check if the message came from a different model.
1519
+ // This handles the case where user switched from a smaller-context model (e.g. opus)
1520
+ // to a larger-context model (e.g. codex) - the overflow error from the old model
1521
+ // shouldn't trigger compaction for the new model.
1522
+ const sameModel = this.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;
1523
+ // Skip compaction checks if this assistant message is older than the latest
1524
+ // compaction boundary. This prevents a stale pre-compaction usage/error
1525
+ // from retriggering compaction on the first prompt after compaction.
1526
+ const compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());
1527
+ const assistantIsFromBeforeCompaction = compactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();
1528
+ if (assistantIsFromBeforeCompaction) {
1529
+ return false;
1530
+ }
1531
+ // Case 1: Recoverable failure. Explicit/silent context overflow still uses context metadata.
1532
+ // A length stop is recoverable when output ended below the model's original desired limit,
1533
+ // independent of the configured context size or any context-clamped provider request limit.
1534
+ // A successful response over the configured window should compact but must not retry: the
1535
+ // assistant answer already completed and agent.continue() cannot continue from an assistant.
1536
+ const recoverableLength = sameModel && isRecoverableLength(assistantMessage, this.model?.maxTokens ?? 0);
1537
+ if (sameModel && (isContextOverflow(assistantMessage, contextWindow) || recoverableLength)) {
1538
+ const willRetry = assistantMessage.stopReason !== "stop";
1539
+ if (!willRetry) {
1540
+ return await this._runAutoCompaction("overflow", false);
1541
+ }
1542
+ if (this._overflowRecoveryAttempted) {
1543
+ this._emit({
1544
+ type: "compaction_end",
1545
+ reason: "overflow",
1546
+ result: undefined,
1547
+ aborted: false,
1548
+ willRetry: false,
1549
+ errorMessage: "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
1550
+ });
1551
+ return false;
1552
+ }
1553
+ this._overflowRecoveryAttempted = true;
1554
+ // Remove the failed or truncated message from agent state. It remains in session history,
1555
+ // but must not be included in the compact-and-retry context.
1556
+ const messages = this.agent.state.messages;
1557
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1558
+ this.agent.state.messages = messages.slice(0, -1);
1559
+ }
1560
+ return await this._runAutoCompaction("overflow", willRetry);
1561
+ }
1562
+ // Case 2: Threshold - context is getting large
1563
+ // For error messages or all-zero usage messages, estimate from the last valid response.
1564
+ // This ensures sessions that hit persistent API errors (e.g. 529) or malformed zero-usage
1565
+ // responses can still compact and do not reset context accounting.
1566
+ let contextTokens;
1567
+ const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
1568
+ if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
1569
+ const messages = this.agent.state.messages;
1570
+ const estimate = estimateContextTokens(messages);
1571
+ if (estimate.lastUsageIndex === null)
1572
+ return false; // No usage data at all
1573
+ // Verify the usage source is post-compaction. Kept pre-compaction messages
1574
+ // have stale usage reflecting the old (larger) context and would falsely
1575
+ // trigger compaction right after one just finished.
1576
+ const usageMsg = messages[estimate.lastUsageIndex];
1577
+ if (compactionEntry &&
1578
+ usageMsg.role === "assistant" &&
1579
+ usageMsg.timestamp <= new Date(compactionEntry.timestamp).getTime()) {
1580
+ return false;
1581
+ }
1582
+ contextTokens = estimate.tokens;
1583
+ }
1584
+ else {
1585
+ contextTokens = directContextTokens;
1586
+ }
1587
+ if (shouldCompact(contextTokens, contextWindow, settings)) {
1588
+ return await this._runAutoCompaction("threshold", false);
1589
+ }
1590
+ return false;
1591
+ }
1592
+ /**
1593
+ * Internal: Run auto-compaction with events.
1594
+ */
1595
+ async _runAutoCompaction(reason, willRetry) {
1596
+ const settings = this.settingsManager.getCompactionSettings();
1597
+ let started = false;
1598
+ try {
1599
+ if (!this.model) {
1600
+ return false;
1601
+ }
1602
+ const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model);
1603
+ const pathEntries = this.sessionManager.getBranch();
1604
+ const preparation = prepareCompaction(pathEntries, settings);
1605
+ if (!preparation) {
1606
+ return false;
1607
+ }
1608
+ this._emit({ type: "compaction_start", reason });
1609
+ this._autoCompactionAbortController = new AbortController();
1610
+ started = true;
1611
+ let extensionCompaction;
1612
+ let fromExtension = false;
1613
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1614
+ const extensionResult = (await this._extensionRunner.emit({
1615
+ type: "session_before_compact",
1616
+ preparation,
1617
+ branchEntries: pathEntries,
1618
+ customInstructions: undefined,
1619
+ reason,
1620
+ willRetry,
1621
+ signal: this._autoCompactionAbortController.signal,
1622
+ }));
1623
+ if (extensionResult?.cancel) {
1624
+ this._emit({
1625
+ type: "compaction_end",
1626
+ reason,
1627
+ result: undefined,
1628
+ aborted: true,
1629
+ willRetry: false,
1630
+ });
1631
+ return false;
1632
+ }
1633
+ if (extensionResult?.compaction) {
1634
+ extensionCompaction = extensionResult.compaction;
1635
+ fromExtension = true;
1636
+ }
1637
+ }
1638
+ let summary;
1639
+ let firstKeptEntryId;
1640
+ let tokensBefore;
1641
+ let usage;
1642
+ let details;
1643
+ if (extensionCompaction) {
1644
+ // Extension provided compaction content
1645
+ summary = extensionCompaction.summary;
1646
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1647
+ tokensBefore = extensionCompaction.tokensBefore;
1648
+ usage = extensionCompaction.usage;
1649
+ details = extensionCompaction.details;
1650
+ }
1651
+ else {
1652
+ // Generate compaction result
1653
+ const compactResult = await compact(preparation, requestModel, apiKey, headers, undefined, this._autoCompactionAbortController.signal, this.thinkingLevel, this.agent.streamFunction, env, this.settingsManager.getRetrySettings(), this._summarizationRetryCallbacks({ source: "compaction", reason }));
1654
+ summary = compactResult.summary;
1655
+ firstKeptEntryId = compactResult.firstKeptEntryId;
1656
+ tokensBefore = compactResult.tokensBefore;
1657
+ usage = compactResult.usage;
1658
+ details = compactResult.details;
1659
+ }
1660
+ if (this._autoCompactionAbortController.signal.aborted) {
1661
+ this._emit({
1662
+ type: "compaction_end",
1663
+ reason,
1664
+ result: undefined,
1665
+ aborted: true,
1666
+ willRetry: false,
1667
+ });
1668
+ return false;
1669
+ }
1670
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
1671
+ const newEntries = this.sessionManager.getEntries();
1672
+ const sessionContext = this.sessionManager.buildSessionContext();
1673
+ this.agent.state.messages = sessionContext.messages;
1674
+ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
1675
+ // Get the saved compaction entry for the extension event
1676
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1677
+ if (this._extensionRunner && savedCompactionEntry) {
1678
+ await this._extensionRunner.emit({
1679
+ type: "session_compact",
1680
+ compactionEntry: savedCompactionEntry,
1681
+ fromExtension,
1682
+ reason,
1683
+ willRetry,
1684
+ });
1685
+ }
1686
+ const result = {
1687
+ summary,
1688
+ firstKeptEntryId,
1689
+ tokensBefore,
1690
+ estimatedTokensAfter,
1691
+ usage,
1692
+ details,
1693
+ };
1694
+ this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
1695
+ if (willRetry) {
1696
+ const messages = this.agent.state.messages;
1697
+ const lastMsg = messages[messages.length - 1];
1698
+ // The overflow response was persisted on message_end before _checkCompaction() removed it
1699
+ // from agent state. Rebuilding state from the new compaction can restore that kept entry,
1700
+ // leaving an assistant as the final message. agent.continue() rejects that state, so remove
1701
+ // the retriable error or truncated-length response again before continuing the interrupted turn.
1702
+ if (lastMsg?.role === "assistant" && (lastMsg.stopReason === "error" || lastMsg.stopReason === "length")) {
1703
+ this.agent.state.messages = messages.slice(0, -1);
1704
+ }
1705
+ return true;
1706
+ }
1707
+ // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
1708
+ // Continue once so queued messages are delivered.
1709
+ return this.agent.hasQueuedMessages();
1710
+ }
1711
+ catch (error) {
1712
+ const errorMessage = error instanceof Error ? error.message : "compaction failed";
1713
+ if (started) {
1714
+ this._emit({
1715
+ type: "compaction_end",
1716
+ reason,
1717
+ result: undefined,
1718
+ aborted: false,
1719
+ willRetry: false,
1720
+ errorMessage: reason === "overflow"
1721
+ ? `Context overflow recovery failed: ${errorMessage}`
1722
+ : `Auto-compaction failed: ${errorMessage}`,
1723
+ });
1724
+ }
1725
+ return false;
1726
+ }
1727
+ finally {
1728
+ this._autoCompactionAbortController = undefined;
1729
+ }
1730
+ }
1731
+ /**
1732
+ * Toggle auto-compaction setting.
1733
+ */
1734
+ setAutoCompactionEnabled(enabled) {
1735
+ this.settingsManager.setCompactionEnabled(enabled);
1736
+ }
1737
+ /** Whether auto-compaction is enabled */
1738
+ get autoCompactionEnabled() {
1739
+ return this.settingsManager.getCompactionEnabled();
1740
+ }
1741
+ async bindExtensions(bindings) {
1742
+ if (bindings.uiContext !== undefined) {
1743
+ this._extensionUIContext = bindings.uiContext;
1744
+ }
1745
+ if (bindings.mode !== undefined) {
1746
+ this._extensionMode = bindings.mode;
1747
+ }
1748
+ if (bindings.commandContextActions !== undefined) {
1749
+ this._extensionCommandContextActions = bindings.commandContextActions;
1750
+ }
1751
+ if (bindings.abortHandler !== undefined) {
1752
+ this._extensionAbortHandler = bindings.abortHandler;
1753
+ }
1754
+ if (bindings.shutdownHandler !== undefined) {
1755
+ this._extensionShutdownHandler = bindings.shutdownHandler;
1756
+ }
1757
+ if (bindings.onError !== undefined) {
1758
+ this._extensionErrorListener = bindings.onError;
1759
+ }
1760
+ this._applyExtensionBindings(this._extensionRunner);
1761
+ await this._extensionRunner.emit(this._sessionStartEvent);
1762
+ await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
1763
+ }
1764
+ async extendResourcesFromExtensions(reason) {
1765
+ if (!this._extensionRunner.hasHandlers("resources_discover")) {
1766
+ return;
1767
+ }
1768
+ const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(this._cwd, reason);
1769
+ if (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {
1770
+ return;
1771
+ }
1772
+ const extensionPaths = {
1773
+ skillPaths: this.buildExtensionResourcePaths(skillPaths),
1774
+ promptPaths: this.buildExtensionResourcePaths(promptPaths),
1775
+ themePaths: this.buildExtensionResourcePaths(themePaths),
1776
+ };
1777
+ this._resourceLoader.extendResources(extensionPaths);
1778
+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
1779
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
1780
+ }
1781
+ buildExtensionResourcePaths(entries) {
1782
+ return entries.map((entry) => {
1783
+ const source = this.getExtensionSourceLabel(entry.extensionPath);
1784
+ const baseDir = entry.extensionPath.startsWith("<") ? undefined : dirname(entry.extensionPath);
1785
+ return {
1786
+ path: entry.path,
1787
+ metadata: {
1788
+ source,
1789
+ scope: "temporary",
1790
+ origin: "top-level",
1791
+ baseDir,
1792
+ },
1793
+ };
1794
+ });
1795
+ }
1796
+ getExtensionSourceLabel(extensionPath) {
1797
+ if (extensionPath.startsWith("<")) {
1798
+ return `extension:${extensionPath.replace(/[<>]/g, "")}`;
1799
+ }
1800
+ const base = basename(extensionPath);
1801
+ const name = base.replace(/\.(ts|js)$/, "");
1802
+ return `extension:${name}`;
1803
+ }
1804
+ _applyExtensionBindings(runner) {
1805
+ runner.setUIContext(this._extensionUIContext, this._extensionMode);
1806
+ runner.bindCommandContext(this._extensionCommandContextActions);
1807
+ this._extensionErrorUnsubscriber?.();
1808
+ this._extensionErrorUnsubscriber = this._extensionErrorListener
1809
+ ? runner.onError(this._extensionErrorListener)
1810
+ : undefined;
1811
+ }
1812
+ _refreshCurrentModelFromRegistry() {
1813
+ const currentModel = this.model;
1814
+ if (!currentModel) {
1815
+ return;
1816
+ }
1817
+ const refreshedModel = this._modelRuntime.getModel(currentModel.provider, currentModel.id);
1818
+ if (!refreshedModel || refreshedModel === currentModel) {
1819
+ return;
1820
+ }
1821
+ this.agent.state.model = refreshedModel;
1822
+ }
1823
+ _bindExtensionCore(runner) {
1824
+ const getCommands = () => {
1825
+ const extensionCommands = runner.getRegisteredCommands().map((command) => ({
1826
+ name: command.invocationName,
1827
+ description: command.description,
1828
+ source: "extension",
1829
+ sourceInfo: command.sourceInfo,
1830
+ }));
1831
+ const templates = this.promptTemplates.map((template) => ({
1832
+ name: template.name,
1833
+ description: template.description,
1834
+ source: "prompt",
1835
+ sourceInfo: template.sourceInfo,
1836
+ }));
1837
+ const skills = this._resourceLoader.getSkills().skills.map((skill) => ({
1838
+ name: `skill:${skill.name}`,
1839
+ description: skill.description,
1840
+ source: "skill",
1841
+ sourceInfo: skill.sourceInfo,
1842
+ }));
1843
+ return [...extensionCommands, ...templates, ...skills];
1844
+ };
1845
+ runner.bindCore({
1846
+ sendMessage: (message, options) => {
1847
+ this.sendCustomMessage(message, options).catch((err) => {
1848
+ runner.emitError({
1849
+ extensionPath: "<runtime>",
1850
+ event: "send_message",
1851
+ error: err instanceof Error ? err.message : String(err),
1852
+ });
1853
+ });
1854
+ },
1855
+ sendUserMessage: (content, options) => {
1856
+ this.sendUserMessage(content, options).catch((err) => {
1857
+ runner.emitError({
1858
+ extensionPath: "<runtime>",
1859
+ event: "send_user_message",
1860
+ error: err instanceof Error ? err.message : String(err),
1861
+ });
1862
+ });
1863
+ },
1864
+ appendEntry: (customType, data) => {
1865
+ const entryId = this.sessionManager.appendCustomEntry(customType, data);
1866
+ const entry = this.sessionManager.getEntry(entryId);
1867
+ if (entry) {
1868
+ this._emit({ type: "entry_appended", entry });
1869
+ }
1870
+ },
1871
+ setSessionName: (name) => {
1872
+ this.setSessionName(name);
1873
+ },
1874
+ getSessionName: () => {
1875
+ return this.sessionManager.getSessionName();
1876
+ },
1877
+ setLabel: (entryId, label) => {
1878
+ this.sessionManager.appendLabelChange(entryId, label);
1879
+ },
1880
+ getActiveTools: () => this.getActiveToolNames(),
1881
+ getAllTools: () => this.getAllTools(),
1882
+ setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
1883
+ refreshTools: () => this._refreshToolRegistry(),
1884
+ getCommands,
1885
+ setModel: async (model) => {
1886
+ if (!this._modelRuntime.hasConfiguredAuth(model.provider))
1887
+ return false;
1888
+ await this.setModel(model);
1889
+ return true;
1890
+ },
1891
+ getThinkingLevel: () => this.thinkingLevel,
1892
+ setThinkingLevel: (level) => this.setThinkingLevel(level),
1893
+ }, {
1894
+ getModel: () => this.model,
1895
+ getScopedModels: () => this._scopedModels,
1896
+ isIdle: () => this.isIdle,
1897
+ isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
1898
+ getSignal: () => this.agent.signal,
1899
+ abort: () => {
1900
+ if (this._extensionAbortHandler) {
1901
+ this._extensionAbortHandler();
1902
+ return;
1903
+ }
1904
+ void this.abort();
1905
+ },
1906
+ hasPendingMessages: () => this.pendingMessageCount > 0,
1907
+ shutdown: () => {
1908
+ this._extensionShutdownHandler?.();
1909
+ },
1910
+ getContextUsage: () => this.getContextUsage(),
1911
+ compact: (options) => {
1912
+ void (async () => {
1913
+ try {
1914
+ const result = await this.compact(options?.customInstructions);
1915
+ options?.onComplete?.(result);
1916
+ }
1917
+ catch (error) {
1918
+ const err = error instanceof Error ? error : new Error(String(error));
1919
+ options?.onError?.(err);
1920
+ }
1921
+ })();
1922
+ },
1923
+ getSystemPrompt: () => this.systemPrompt,
1924
+ getSystemPromptOptions: () => this._baseSystemPromptOptions,
1925
+ }, {
1926
+ registerProvider: (name, config) => {
1927
+ this._modelRuntime.registerProvider(name, config);
1928
+ this._refreshCurrentModelFromRegistry();
1929
+ },
1930
+ registerNativeProvider: (provider) => {
1931
+ this._modelRuntime.registerNativeProvider(provider);
1932
+ this._refreshCurrentModelFromRegistry();
1933
+ },
1934
+ unregisterProvider: (name) => {
1935
+ this._modelRuntime.unregisterProvider(name);
1936
+ this._refreshCurrentModelFromRegistry();
1937
+ },
1938
+ });
1939
+ }
1940
+ _refreshToolRegistry(options) {
1941
+ const previousRegistryNames = new Set(this._toolRegistry.keys());
1942
+ const previousActiveToolNames = this.getActiveToolNames();
1943
+ const allowedToolNames = this._allowedToolNames;
1944
+ const excludedToolNames = this._excludedToolNames;
1945
+ const isAllowedTool = (name) => (!allowedToolNames || allowedToolNames.has(name)) && !excludedToolNames?.has(name);
1946
+ const registeredTools = this._extensionRunner.getAllRegisteredTools();
1947
+ const allCustomTools = [
1948
+ ...registeredTools,
1949
+ ...this._customTools.map((definition) => ({
1950
+ definition,
1951
+ sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
1952
+ })),
1953
+ ].filter((tool) => isAllowedTool(tool.definition.name));
1954
+ const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
1955
+ .filter(([name]) => isAllowedTool(name))
1956
+ .map(([name, definition]) => [
1957
+ name,
1958
+ {
1959
+ definition,
1960
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${name}>`, { source: "builtin" }),
1961
+ },
1962
+ ]));
1963
+ for (const tool of allCustomTools) {
1964
+ definitionRegistry.set(tool.definition.name, {
1965
+ definition: tool.definition,
1966
+ sourceInfo: tool.sourceInfo,
1967
+ });
1968
+ }
1969
+ this._toolDefinitions = definitionRegistry;
1970
+ this._toolPromptSnippets = new Map(Array.from(definitionRegistry.values())
1971
+ .map(({ definition }) => {
1972
+ const snippet = this._normalizePromptSnippet(definition.promptSnippet);
1973
+ return snippet ? [definition.name, snippet] : undefined;
1974
+ })
1975
+ .filter((entry) => entry !== undefined));
1976
+ this._toolPromptGuidelines = new Map(Array.from(definitionRegistry.values())
1977
+ .map(({ definition }) => {
1978
+ const guidelines = this._normalizePromptGuidelines(definition.promptGuidelines);
1979
+ return guidelines.length > 0 ? [definition.name, guidelines] : undefined;
1980
+ })
1981
+ .filter((entry) => entry !== undefined));
1982
+ const runner = this._extensionRunner;
1983
+ const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
1984
+ const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
1985
+ .filter((definition) => isAllowedTool(definition.name))
1986
+ .map((definition) => ({
1987
+ definition,
1988
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
1989
+ })), runner);
1990
+ const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
1991
+ for (const tool of wrappedExtensionTools) {
1992
+ toolRegistry.set(tool.name, tool);
1993
+ }
1994
+ this._toolRegistry = toolRegistry;
1995
+ const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => isAllowedTool(name));
1996
+ if (allowedToolNames) {
1997
+ for (const toolName of this._toolRegistry.keys()) {
1998
+ if (allowedToolNames.has(toolName)) {
1999
+ nextActiveToolNames.push(toolName);
2000
+ }
2001
+ }
2002
+ }
2003
+ else if (options?.includeAllExtensionTools) {
2004
+ for (const tool of wrappedExtensionTools) {
2005
+ nextActiveToolNames.push(tool.name);
2006
+ }
2007
+ }
2008
+ else if (!options?.activeToolNames) {
2009
+ for (const toolName of this._toolRegistry.keys()) {
2010
+ if (!previousRegistryNames.has(toolName)) {
2011
+ nextActiveToolNames.push(toolName);
2012
+ }
2013
+ }
2014
+ }
2015
+ this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
2016
+ }
2017
+ _buildRuntime(options) {
2018
+ const autoResizeImages = this.settingsManager.getImageAutoResize();
2019
+ const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
2020
+ const shellPath = this.settingsManager.getShellPath();
2021
+ const baseToolDefinitions = this._baseToolsOverride
2022
+ ? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
2023
+ name,
2024
+ createToolDefinitionFromAgentTool(tool),
2025
+ ]))
2026
+ : createAllToolDefinitions(this._cwd, {
2027
+ read: { autoResizeImages },
2028
+ bash: { commandPrefix: shellCommandPrefix, shellPath },
2029
+ });
2030
+ this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
2031
+ const extensionsResult = this._resourceLoader.getExtensions();
2032
+ if (options.flagValues) {
2033
+ for (const [name, value] of options.flagValues) {
2034
+ extensionsResult.runtime.flagValues.set(name, value);
2035
+ }
2036
+ }
2037
+ this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, new ModelRegistry(this._modelRuntime));
2038
+ if (this._extensionRunnerRef) {
2039
+ this._extensionRunnerRef.current = this._extensionRunner;
2040
+ }
2041
+ this._bindExtensionCore(this._extensionRunner);
2042
+ this._applyExtensionBindings(this._extensionRunner);
2043
+ const defaultActiveToolNames = this._baseToolsOverride
2044
+ ? Object.keys(this._baseToolsOverride)
2045
+ : ["read", "bash", "edit", "write"];
2046
+ const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
2047
+ this._refreshToolRegistry({
2048
+ activeToolNames: baseActiveToolNames,
2049
+ includeAllExtensionTools: options.includeAllExtensionTools,
2050
+ });
2051
+ }
2052
+ async reload(options) {
2053
+ const oldRunner = this._extensionRunner;
2054
+ const previousFlagValues = oldRunner.getFlagValues();
2055
+ await emitSessionShutdownEvent(oldRunner, { type: "session_shutdown", reason: "reload" });
2056
+ oldRunner.invalidate();
2057
+ await this.settingsManager.reload();
2058
+ this.syncQueueModesFromSettings();
2059
+ resetApiProviders();
2060
+ await this._resourceLoader.reload();
2061
+ this._buildRuntime({
2062
+ activeToolNames: this.getActiveToolNames(),
2063
+ flagValues: previousFlagValues,
2064
+ includeAllExtensionTools: true,
2065
+ });
2066
+ const hasBindings = this._extensionUIContext ||
2067
+ this._extensionCommandContextActions ||
2068
+ this._extensionShutdownHandler ||
2069
+ this._extensionErrorListener;
2070
+ if (hasBindings) {
2071
+ await options?.beforeSessionStart?.();
2072
+ await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
2073
+ await this.extendResourcesFromExtensions("reload");
2074
+ }
2075
+ }
2076
+ // =========================================================================
2077
+ // Auto-Retry
2078
+ // =========================================================================
2079
+ /**
2080
+ * Check if an error is retryable (overloaded, rate limit, server errors).
2081
+ * Context overflow errors are NOT retryable (handled by compaction instead).
2082
+ */
2083
+ _isRetryableError(message) {
2084
+ // Context overflow is handled by compaction, not retry.
2085
+ if (isContextOverflow(message, this.model?.contextWindow ?? 0))
2086
+ return false;
2087
+ return isRetryableAssistantError(message);
2088
+ }
2089
+ /**
2090
+ * Retry policy + callbacks shared by compaction and branch-summary summarization calls.
2091
+ * Uses the same `settings.retry` budget/backoff as agent-turn retries so a single transient
2092
+ * stream drop no longer fails the whole operation. `source` carries the context
2093
+ * the TUI needs to render the retry and recreate the underlying indicator.
2094
+ */
2095
+ _summarizationRetryCallbacks(source) {
2096
+ return {
2097
+ onRetryScheduled: (attempt, maxAttempts, delayMs, errorMessage) => {
2098
+ this._emit({
2099
+ type: "summarization_retry_scheduled",
2100
+ attempt,
2101
+ maxAttempts,
2102
+ delayMs,
2103
+ errorMessage,
2104
+ });
2105
+ },
2106
+ onRetryAttemptStart: () => {
2107
+ this._emit({
2108
+ type: "summarization_retry_attempt_start",
2109
+ ...source,
2110
+ });
2111
+ },
2112
+ onRetryFinished: () => {
2113
+ this._emit({ type: "summarization_retry_finished" });
2114
+ },
2115
+ };
2116
+ }
2117
+ /**
2118
+ * Prepare a retryable error for continuation with exponential backoff.
2119
+ * @returns true if the caller should continue the agent, false otherwise
2120
+ */
2121
+ async _prepareRetry(message) {
2122
+ const settings = this.settingsManager.getRetrySettings();
2123
+ if (!settings.enabled) {
2124
+ return false;
2125
+ }
2126
+ this._retryAttempt++;
2127
+ if (this._retryAttempt > settings.maxRetries) {
2128
+ // Preserve the completed attempt count so post-run handling can emit the final failure.
2129
+ this._retryAttempt--;
2130
+ return false;
2131
+ }
2132
+ const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
2133
+ this._emit({
2134
+ type: "auto_retry_start",
2135
+ attempt: this._retryAttempt,
2136
+ maxAttempts: settings.maxRetries,
2137
+ delayMs,
2138
+ errorMessage: message.errorMessage || "Unknown error",
2139
+ });
2140
+ // Remove error message from agent state (keep in session for history)
2141
+ const messages = this.agent.state.messages;
2142
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
2143
+ this.agent.state.messages = messages.slice(0, -1);
2144
+ }
2145
+ // Wait with exponential backoff (abortable)
2146
+ this._retryAbortController = new AbortController();
2147
+ try {
2148
+ await sleep(delayMs, this._retryAbortController.signal);
2149
+ }
2150
+ catch {
2151
+ // Aborted during sleep - emit end event so UI can clean up
2152
+ const attempt = this._retryAttempt;
2153
+ this._retryAttempt = 0;
2154
+ this._emit({
2155
+ type: "auto_retry_end",
2156
+ success: false,
2157
+ attempt,
2158
+ finalError: "Retry cancelled",
2159
+ });
2160
+ return false;
2161
+ }
2162
+ finally {
2163
+ this._retryAbortController = undefined;
2164
+ }
2165
+ return true;
2166
+ }
2167
+ /**
2168
+ * Cancel in-progress retry.
2169
+ */
2170
+ abortRetry() {
2171
+ this._retryAbortController?.abort();
2172
+ }
2173
+ /** Whether auto-retry is currently in progress */
2174
+ get isRetrying() {
2175
+ return this._retryAbortController !== undefined;
2176
+ }
2177
+ /** Whether auto-retry is enabled */
2178
+ get autoRetryEnabled() {
2179
+ return this.settingsManager.getRetryEnabled();
2180
+ }
2181
+ /**
2182
+ * Toggle auto-retry setting.
2183
+ */
2184
+ setAutoRetryEnabled(enabled) {
2185
+ this.settingsManager.setRetryEnabled(enabled);
2186
+ }
2187
+ // =========================================================================
2188
+ // Bash Execution
2189
+ // =========================================================================
2190
+ /**
2191
+ * Execute a bash command.
2192
+ * Adds result to agent context and session.
2193
+ * @param command The bash command to execute
2194
+ * @param onChunk Optional streaming callback for output
2195
+ * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
2196
+ * @param options.id Optional identifier included in bash execution update events
2197
+ * @param options.operations Custom BashOperations for remote execution
2198
+ */
2199
+ async executeBash(command, onChunk, options) {
2200
+ const abortController = new AbortController();
2201
+ this._bashAbortControllers.add(abortController);
2202
+ // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
2203
+ const prefix = this.settingsManager.getShellCommandPrefix();
2204
+ const shellPath = this.settingsManager.getShellPath();
2205
+ const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
2206
+ try {
2207
+ const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
2208
+ onChunk: (delta) => {
2209
+ onChunk?.(delta);
2210
+ this._emit({ type: "bash_execution_update", id: options?.id, delta });
2211
+ },
2212
+ signal: abortController.signal,
2213
+ });
2214
+ this.recordBashResult(command, result, options);
2215
+ return result;
2216
+ }
2217
+ finally {
2218
+ this._bashAbortControllers.delete(abortController);
2219
+ }
2220
+ }
2221
+ /**
2222
+ * Record a bash execution result in session history.
2223
+ * Used by executeBash and by extensions that handle bash execution themselves.
2224
+ */
2225
+ recordBashResult(command, result, options) {
2226
+ const bashMessage = {
2227
+ role: "bashExecution",
2228
+ command,
2229
+ output: result.output,
2230
+ exitCode: result.exitCode,
2231
+ cancelled: result.cancelled,
2232
+ truncated: result.truncated,
2233
+ fullOutputPath: result.fullOutputPath,
2234
+ timestamp: Date.now(),
2235
+ excludeFromContext: options?.excludeFromContext,
2236
+ };
2237
+ // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
2238
+ if (this.isStreaming) {
2239
+ // Queue for later - will be flushed on agent_end
2240
+ this._pendingBashMessages.push(bashMessage);
2241
+ }
2242
+ else {
2243
+ // Add to agent state immediately
2244
+ this.agent.state.messages.push(bashMessage);
2245
+ // Save to session
2246
+ this.sessionManager.appendMessage(bashMessage);
2247
+ }
2248
+ }
2249
+ /**
2250
+ * Cancel running bash command.
2251
+ */
2252
+ abortBash() {
2253
+ for (const abortController of [...this._bashAbortControllers]) {
2254
+ abortController.abort();
2255
+ }
2256
+ }
2257
+ /** Whether a bash command is currently running */
2258
+ get isBashRunning() {
2259
+ return this._bashAbortControllers.size > 0;
2260
+ }
2261
+ /** Whether there are pending bash messages waiting to be flushed */
2262
+ get hasPendingBashMessages() {
2263
+ return this._pendingBashMessages.length > 0;
2264
+ }
2265
+ /**
2266
+ * Flush pending bash messages to agent state and session.
2267
+ * Called after agent turn completes to maintain proper message ordering.
2268
+ */
2269
+ _flushPendingBashMessages() {
2270
+ if (this._pendingBashMessages.length === 0)
2271
+ return;
2272
+ for (const bashMessage of this._pendingBashMessages) {
2273
+ // Add to agent state
2274
+ this.agent.state.messages.push(bashMessage);
2275
+ // Save to session
2276
+ this.sessionManager.appendMessage(bashMessage);
2277
+ }
2278
+ this._pendingBashMessages = [];
2279
+ }
2280
+ // =========================================================================
2281
+ // Session Management
2282
+ // =========================================================================
2283
+ /**
2284
+ * Set a display name for the current session.
2285
+ */
2286
+ setSessionName(name) {
2287
+ this.sessionManager.appendSessionInfo(name);
2288
+ const event = { type: "session_info_changed", name: this.sessionManager.getSessionName() };
2289
+ this._emit(event);
2290
+ void this._extensionRunner.emit(event);
2291
+ }
2292
+ // =========================================================================
2293
+ // Tree Navigation
2294
+ // =========================================================================
2295
+ /**
2296
+ * Navigate to a different node in the session tree.
2297
+ * Unlike fork() which creates a new session file, this stays in the same file.
2298
+ *
2299
+ * @param targetId The entry ID to navigate to
2300
+ * @param options.summarize Whether user wants to summarize abandoned branch
2301
+ * @param options.customInstructions Custom instructions for summarizer
2302
+ * @param options.replaceInstructions If true, customInstructions replaces the default prompt
2303
+ * @param options.label Label to attach to the branch summary entry
2304
+ * @returns Result with editorText (if user message) and cancelled status
2305
+ */
2306
+ async navigateTree(targetId, options = {}) {
2307
+ if (this.isStreaming) {
2308
+ throw new Error("Wait for the current response to finish before navigating the session tree.");
2309
+ }
2310
+ const oldLeafId = this.sessionManager.getLeafId();
2311
+ // No-op if already at target
2312
+ if (targetId === oldLeafId) {
2313
+ return { cancelled: false };
2314
+ }
2315
+ // Model required for summarization
2316
+ if (options.summarize && !this.model) {
2317
+ throw new Error("No model available for summarization");
2318
+ }
2319
+ const targetEntry = this.sessionManager.getEntry(targetId);
2320
+ if (!targetEntry) {
2321
+ throw new Error(`Entry ${targetId} not found`);
2322
+ }
2323
+ // Collect entries to summarize (from old leaf to common ancestor)
2324
+ const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(this.sessionManager, oldLeafId, targetId);
2325
+ // Prepare event data - mutable so extensions can override
2326
+ let customInstructions = options.customInstructions;
2327
+ let replaceInstructions = options.replaceInstructions;
2328
+ let label = options.label;
2329
+ const preparation = {
2330
+ targetId,
2331
+ oldLeafId,
2332
+ commonAncestorId,
2333
+ entriesToSummarize,
2334
+ userWantsSummary: options.summarize ?? false,
2335
+ customInstructions,
2336
+ replaceInstructions,
2337
+ label,
2338
+ };
2339
+ // Set up abort controller for summarization
2340
+ this._branchSummaryAbortController = new AbortController();
2341
+ try {
2342
+ let extensionSummary;
2343
+ let fromExtension = false;
2344
+ // Emit session_before_tree event
2345
+ if (this._extensionRunner.hasHandlers("session_before_tree")) {
2346
+ const result = (await this._extensionRunner.emit({
2347
+ type: "session_before_tree",
2348
+ preparation,
2349
+ signal: this._branchSummaryAbortController.signal,
2350
+ }));
2351
+ if (result?.cancel) {
2352
+ return { cancelled: true };
2353
+ }
2354
+ if (result?.summary && options.summarize) {
2355
+ extensionSummary = result.summary;
2356
+ fromExtension = true;
2357
+ }
2358
+ // Allow extensions to override instructions and label
2359
+ if (result?.customInstructions !== undefined) {
2360
+ customInstructions = result.customInstructions;
2361
+ }
2362
+ if (result?.replaceInstructions !== undefined) {
2363
+ replaceInstructions = result.replaceInstructions;
2364
+ }
2365
+ if (result?.label !== undefined) {
2366
+ label = result.label;
2367
+ }
2368
+ }
2369
+ // Run default summarizer if needed
2370
+ let summaryText;
2371
+ let summaryDetails;
2372
+ let summaryUsage;
2373
+ if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
2374
+ const model = this.model;
2375
+ const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(model);
2376
+ const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
2377
+ const result = await generateBranchSummary(entriesToSummarize, {
2378
+ model: requestModel,
2379
+ apiKey,
2380
+ headers,
2381
+ env,
2382
+ signal: this._branchSummaryAbortController.signal,
2383
+ customInstructions,
2384
+ replaceInstructions,
2385
+ reserveTokens: branchSummarySettings.reserveTokens,
2386
+ streamFn: this.agent.streamFunction,
2387
+ retry: this.settingsManager.getRetrySettings(),
2388
+ callbacks: this._summarizationRetryCallbacks({ source: "branchSummary" }),
2389
+ });
2390
+ if (result.aborted) {
2391
+ return { cancelled: true, aborted: true };
2392
+ }
2393
+ if (result.error) {
2394
+ throw new Error(result.error);
2395
+ }
2396
+ summaryText = result.summary;
2397
+ summaryUsage = result.usage;
2398
+ summaryDetails = {
2399
+ readFiles: result.readFiles || [],
2400
+ modifiedFiles: result.modifiedFiles || [],
2401
+ };
2402
+ }
2403
+ else if (extensionSummary) {
2404
+ summaryText = extensionSummary.summary;
2405
+ summaryDetails = extensionSummary.details;
2406
+ summaryUsage = extensionSummary.usage;
2407
+ }
2408
+ // Determine the new leaf position based on target type
2409
+ let newLeafId;
2410
+ let editorText;
2411
+ if (targetEntry.type === "message" && targetEntry.message.role === "user") {
2412
+ // User message: leaf = parent (null if root), text goes to editor
2413
+ newLeafId = targetEntry.parentId;
2414
+ editorText = contentText(targetEntry.message.content, "");
2415
+ }
2416
+ else if (targetEntry.type === "custom_message") {
2417
+ // Custom message: leaf = parent (null if root), text goes to editor
2418
+ newLeafId = targetEntry.parentId;
2419
+ editorText = contentText(targetEntry.content, "");
2420
+ }
2421
+ else {
2422
+ // Non-user message: leaf = selected node
2423
+ newLeafId = targetId;
2424
+ }
2425
+ // Switch leaf (with or without summary)
2426
+ // Summary is attached at the navigation target position (newLeafId), not the old branch
2427
+ let summaryEntry;
2428
+ if (summaryText) {
2429
+ // Create summary at target position (can be null for root)
2430
+ const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension, summaryUsage);
2431
+ summaryEntry = this.sessionManager.getEntry(summaryId);
2432
+ // Attach label to the summary entry
2433
+ if (label) {
2434
+ this.sessionManager.appendLabelChange(summaryId, label);
2435
+ }
2436
+ }
2437
+ else if (newLeafId === null) {
2438
+ // No summary, navigating to root - reset leaf
2439
+ this.sessionManager.resetLeaf();
2440
+ }
2441
+ else {
2442
+ // No summary, navigating to non-root
2443
+ this.sessionManager.branch(newLeafId);
2444
+ }
2445
+ // Attach label to target entry when not summarizing (no summary entry to label)
2446
+ if (label && !summaryText) {
2447
+ this.sessionManager.appendLabelChange(targetId, label);
2448
+ }
2449
+ // Update agent state
2450
+ const sessionContext = this.sessionManager.buildSessionContext();
2451
+ this.agent.state.messages = sessionContext.messages;
2452
+ // Emit session_tree event
2453
+ await this._extensionRunner.emit({
2454
+ type: "session_tree",
2455
+ newLeafId: this.sessionManager.getLeafId(),
2456
+ oldLeafId,
2457
+ summaryEntry,
2458
+ fromExtension: summaryText ? fromExtension : undefined,
2459
+ });
2460
+ // Emit to custom tools
2461
+ return { editorText, cancelled: false, summaryEntry };
2462
+ }
2463
+ finally {
2464
+ this._branchSummaryAbortController = undefined;
2465
+ }
2466
+ }
2467
+ /**
2468
+ * Get all user messages from session for fork selector.
2469
+ */
2470
+ getUserMessagesForForking() {
2471
+ const entries = this.sessionManager.getEntries();
2472
+ const result = [];
2473
+ for (const entry of entries) {
2474
+ if (entry.type !== "message")
2475
+ continue;
2476
+ if (entry.message.role !== "user")
2477
+ continue;
2478
+ const text = contentText(entry.message.content, "");
2479
+ if (text) {
2480
+ result.push({ entryId: entry.id, text });
2481
+ }
2482
+ }
2483
+ return result;
2484
+ }
2485
+ /**
2486
+ * Get session statistics. Aggregates over ALL session entries (including
2487
+ * history that was compacted away), so token/cost totals reflect what was
2488
+ * actually billed across the session.
2489
+ */
2490
+ getSessionStats() {
2491
+ let userMessages = 0;
2492
+ let assistantMessages = 0;
2493
+ let toolResults = 0;
2494
+ let totalMessages = 0;
2495
+ let toolCalls = 0;
2496
+ const usageTotals = createUsageTotals();
2497
+ for (const entry of this.sessionManager.getEntries()) {
2498
+ if ((entry.type === "branch_summary" || entry.type === "compaction") && entry.usage) {
2499
+ addUsageToTotals(usageTotals, entry.usage);
2500
+ }
2501
+ if (entry.type !== "message")
2502
+ continue;
2503
+ totalMessages++;
2504
+ const message = entry.message;
2505
+ if (message.role === "user") {
2506
+ userMessages++;
2507
+ }
2508
+ else if (message.role === "toolResult") {
2509
+ toolResults++;
2510
+ if (message.usage) {
2511
+ addUsageToTotals(usageTotals, message.usage);
2512
+ }
2513
+ }
2514
+ else if (message.role === "assistant") {
2515
+ assistantMessages++;
2516
+ const assistantMsg = message;
2517
+ if (Array.isArray(assistantMsg.content)) {
2518
+ toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
2519
+ }
2520
+ addUsageToTotals(usageTotals, assistantMsg.usage);
2521
+ }
2522
+ }
2523
+ return {
2524
+ sessionFile: this.sessionFile,
2525
+ sessionId: this.sessionId,
2526
+ userMessages,
2527
+ assistantMessages,
2528
+ toolCalls,
2529
+ toolResults,
2530
+ totalMessages,
2531
+ tokens: {
2532
+ input: usageTotals.input,
2533
+ output: usageTotals.output,
2534
+ cacheRead: usageTotals.cacheRead,
2535
+ cacheWrite: usageTotals.cacheWrite,
2536
+ total: usageTotals.input + usageTotals.output + usageTotals.cacheRead + usageTotals.cacheWrite,
2537
+ },
2538
+ cost: usageTotals.cost,
2539
+ contextUsage: this.getContextUsage(),
2540
+ };
2541
+ }
2542
+ getContextUsage() {
2543
+ const model = this.model;
2544
+ if (!model)
2545
+ return undefined;
2546
+ const contextWindow = model.contextWindow ?? 0;
2547
+ if (contextWindow <= 0)
2548
+ return undefined;
2549
+ // After compaction, the last assistant usage reflects pre-compaction context size.
2550
+ // We can only trust usage from an assistant that responded after the latest compaction.
2551
+ // If no such assistant exists, context token count is unknown until the next LLM response.
2552
+ const branchEntries = this.sessionManager.getBranch();
2553
+ const latestCompaction = getLatestCompactionEntry(branchEntries);
2554
+ if (latestCompaction) {
2555
+ // Check if there's a valid assistant usage after the compaction boundary
2556
+ const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
2557
+ let hasPostCompactionUsage = false;
2558
+ for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
2559
+ const entry = branchEntries[i];
2560
+ if (entry.type === "message" && entry.message.role === "assistant") {
2561
+ const assistant = entry.message;
2562
+ if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
2563
+ const contextTokens = calculateContextTokens(assistant.usage);
2564
+ if (contextTokens > 0) {
2565
+ hasPostCompactionUsage = true;
2566
+ break;
2567
+ }
2568
+ }
2569
+ }
2570
+ }
2571
+ if (!hasPostCompactionUsage) {
2572
+ return { tokens: null, contextWindow, percent: null };
2573
+ }
2574
+ }
2575
+ const estimate = estimateContextTokens(this.messages);
2576
+ const percent = (estimate.tokens / contextWindow) * 100;
2577
+ return {
2578
+ tokens: estimate.tokens,
2579
+ contextWindow,
2580
+ percent,
2581
+ };
2582
+ }
2583
+ /**
2584
+ * Export session to HTML.
2585
+ * @param outputPath Optional output path (defaults to session directory)
2586
+ * @param options Optional export presentation settings
2587
+ * @returns Path to exported file
2588
+ */
2589
+ async exportToHtml(outputPath, options = {}) {
2590
+ const themeName = [options.themeName, this.settingsManager.getTheme()].find((candidate) => candidate !== undefined && getThemeByName(candidate) !== undefined);
2591
+ // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
2592
+ const toolRenderer = createToolHtmlRenderer({
2593
+ getToolDefinition: (name) => this.getToolDefinition(name),
2594
+ theme,
2595
+ cwd: this.sessionManager.getCwd(),
2596
+ });
2597
+ return await exportSessionToHtml(this.sessionManager, this.state, {
2598
+ outputPath,
2599
+ themeName,
2600
+ toolRenderer,
2601
+ });
2602
+ }
2603
+ /**
2604
+ * Export the current session branch to a JSONL file.
2605
+ * Writes the session header followed by all entries on the current branch path.
2606
+ * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
2607
+ * @returns The resolved output file path.
2608
+ */
2609
+ exportToJsonl(outputPath) {
2610
+ const filePath = resolvePath(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`, process.cwd());
2611
+ const dir = dirname(filePath);
2612
+ if (!existsSync(dir)) {
2613
+ mkdirSync(dir, { recursive: true });
2614
+ }
2615
+ const header = {
2616
+ type: "session",
2617
+ version: CURRENT_SESSION_VERSION,
2618
+ id: this.sessionManager.getSessionId(),
2619
+ timestamp: new Date().toISOString(),
2620
+ cwd: this.sessionManager.getCwd(),
2621
+ };
2622
+ const branchEntries = this.sessionManager.getBranch();
2623
+ const lines = [JSON.stringify(header)];
2624
+ // Re-chain parentIds to form a linear sequence
2625
+ let prevId = null;
2626
+ for (const entry of branchEntries) {
2627
+ const linear = { ...entry, parentId: prevId };
2628
+ lines.push(JSON.stringify(linear));
2629
+ prevId = entry.id;
2630
+ }
2631
+ writeFileSync(filePath, `${lines.join("\n")}\n`);
2632
+ return filePath;
2633
+ }
2634
+ // =========================================================================
2635
+ // Utilities
2636
+ // =========================================================================
2637
+ /**
2638
+ * Get text content of last assistant message.
2639
+ * Useful for /copy command.
2640
+ * @returns Text content, or undefined if no assistant message exists
2641
+ */
2642
+ getLastAssistantText() {
2643
+ const lastAssistant = this.messages
2644
+ .slice()
2645
+ .reverse()
2646
+ .find((m) => {
2647
+ if (m.role !== "assistant")
2648
+ return false;
2649
+ const msg = m;
2650
+ // Skip aborted messages with no content
2651
+ if (msg.stopReason === "aborted" && msg.content.length === 0)
2652
+ return false;
2653
+ return true;
2654
+ });
2655
+ if (!lastAssistant)
2656
+ return undefined;
2657
+ let text = "";
2658
+ for (const content of lastAssistant.content) {
2659
+ if (content.type === "text") {
2660
+ text += content.text;
2661
+ }
2662
+ }
2663
+ return text.trim() || undefined;
2664
+ }
2665
+ // =========================================================================
2666
+ // Extension System
2667
+ // =========================================================================
2668
+ createReplacedSessionContext() {
2669
+ const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));
2670
+ context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
2671
+ context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
2672
+ return context;
2673
+ }
2674
+ /**
2675
+ * Check if extensions have handlers for a specific event type.
2676
+ */
2677
+ hasExtensionHandlers(eventType) {
2678
+ return this._extensionRunner.hasHandlers(eventType);
2679
+ }
2680
+ /**
2681
+ * Get the extension runner (for setting UI context and error handlers).
2682
+ */
2683
+ get extensionRunner() {
2684
+ return this._extensionRunner;
2685
+ }
2686
+ }
2687
+ //# sourceMappingURL=agent-session.js.map