@leanandmean/coding-agent 0.74.1-scramjet.6

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