@eminent337/aery 0.1.11 → 1.0.0

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