indusagi-coding-agent 0.1.40 → 0.1.42

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