@lenylvt/pi-coding-agent 0.64.0

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