@eminent337/aery 0.67.68 → 0.74.1

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