indusagi-coding-agent 0.1.59 → 0.1.61

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