@schlenkr/ragents 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (788) hide show
  1. package/LICENSE +166 -0
  2. package/README.md +88 -0
  3. package/apps/server/agent-home/settings.json +3 -0
  4. package/apps/server/package.json +29 -0
  5. package/apps/server/src/access-projection.ts +97 -0
  6. package/apps/server/src/access-service.ts +22 -0
  7. package/apps/server/src/access-session.ts +204 -0
  8. package/apps/server/src/api/contracts.ts +203 -0
  9. package/apps/server/src/api/core-methods.ts +163 -0
  10. package/apps/server/src/api/delivery.ts +40 -0
  11. package/apps/server/src/api/reference.ts +146 -0
  12. package/apps/server/src/api/rights.ts +26 -0
  13. package/apps/server/src/chat-attachments.ts +52 -0
  14. package/apps/server/src/chat-context.ts +6 -0
  15. package/apps/server/src/chat-events.ts +185 -0
  16. package/apps/server/src/chat-handler.ts +37 -0
  17. package/apps/server/src/config-definition.ts +80 -0
  18. package/apps/server/src/config-file.ts +324 -0
  19. package/apps/server/src/config.ts +46 -0
  20. package/apps/server/src/data-directory.ts +42 -0
  21. package/apps/server/src/external-access.ts +40 -0
  22. package/apps/server/src/help-files.ts +63 -0
  23. package/apps/server/src/host-resolution-hooks.mjs +31 -0
  24. package/apps/server/src/host-resolution.ts +3 -0
  25. package/apps/server/src/host-version.ts +74 -0
  26. package/apps/server/src/layout.ts +36 -0
  27. package/apps/server/src/main.ts +54 -0
  28. package/apps/server/src/plugin-support/actor-programs/capability-resolver.ts +107 -0
  29. package/apps/server/src/plugin-support/actor-programs/limits.ts +33 -0
  30. package/apps/server/src/plugin-support/actor-programs/operations.ts +19 -0
  31. package/apps/server/src/plugin-support/actor-programs/service.ts +16 -0
  32. package/apps/server/src/plugin-support/agent-tool.ts +60 -0
  33. package/apps/server/src/plugin-support/asset-path.ts +4 -0
  34. package/apps/server/src/plugin-support/await-with-signal.ts +18 -0
  35. package/apps/server/src/plugin-support/chat-display-contract.ts +7 -0
  36. package/apps/server/src/plugin-support/chat-display-policy.ts +55 -0
  37. package/apps/server/src/plugin-support/front-matter.ts +44 -0
  38. package/apps/server/src/plugin-support/http.ts +93 -0
  39. package/apps/server/src/plugin-support/language-server/contract.ts +18 -0
  40. package/apps/server/src/plugin-support/language-server/plugin.ts +32 -0
  41. package/apps/server/src/plugin-support/language-server/snapshot-method.ts +17 -0
  42. package/apps/server/src/plugin-support/language-server/tools.ts +73 -0
  43. package/apps/server/src/plugin-support/model-choice.ts +109 -0
  44. package/apps/server/src/plugin-support/model-upstreams.ts +12 -0
  45. package/apps/server/src/plugin-support/native-typescript-child.ts +78 -0
  46. package/apps/server/src/plugin-support/native-typescript-executor.ts +260 -0
  47. package/apps/server/src/plugin-support/plugin-config.ts +48 -0
  48. package/apps/server/src/plugin-support/plugin-folder.ts +81 -0
  49. package/apps/server/src/plugin-support/plugin-module.ts +14 -0
  50. package/apps/server/src/plugin-support/plugins-root.ts +41 -0
  51. package/apps/server/src/plugin-support/product-model-settings-contract.ts +24 -0
  52. package/apps/server/src/plugin-support/product-model-settings.ts +120 -0
  53. package/apps/server/src/plugin-support/product-start-options.ts +104 -0
  54. package/apps/server/src/plugin-support/prompt.ts +68 -0
  55. package/apps/server/src/plugin-support/provision.ts +85 -0
  56. package/apps/server/src/plugin-support/run-scripts.ts +88 -0
  57. package/apps/server/src/plugin-support/shell-platform.ts +21 -0
  58. package/apps/server/src/plugin-support/skills.ts +97 -0
  59. package/apps/server/src/plugin-support/start-entries-contract.ts +71 -0
  60. package/apps/server/src/plugin-support/start-options-contract.ts +65 -0
  61. package/apps/server/src/plugin-support/system-prompts.ts +138 -0
  62. package/apps/server/src/plugin-support/thinking-level.ts +8 -0
  63. package/apps/server/src/plugin-support/tool-availability.ts +20 -0
  64. package/apps/server/src/plugin-support/workspace-ownership.ts +36 -0
  65. package/apps/server/src/plugin-support/workspace-sandbox-host.ts +213 -0
  66. package/apps/server/src/plugin-support/workspace-tool-naming.ts +11 -0
  67. package/apps/server/src/plugin-support/zip.ts +69 -0
  68. package/apps/server/src/profile/compose.ts +69 -0
  69. package/apps/server/src/profile/plugin-discovery.ts +112 -0
  70. package/apps/server/src/profile/plugin-list.ts +19 -0
  71. package/apps/server/src/profile/provisioning.ts +81 -0
  72. package/apps/server/src/protocol.ts +106 -0
  73. package/apps/server/src/provider.ts +817 -0
  74. package/apps/server/src/ragents/actor-chat-history.ts +111 -0
  75. package/apps/server/src/ragents/chat-projection.ts +55 -0
  76. package/apps/server/src/ragents/chat-text-positions.ts +43 -0
  77. package/apps/server/src/ragents/coordinator.ts +5 -0
  78. package/apps/server/src/ragents/document-store.ts +12 -0
  79. package/apps/server/src/ragents/engine.ts +417 -0
  80. package/apps/server/src/ragents/global-chat.ts +40 -0
  81. package/apps/server/src/ragents/host-services.ts +26 -0
  82. package/apps/server/src/ragents/journal-chat-events.ts +52 -0
  83. package/apps/server/src/ragents/product-runtime.ts +31 -0
  84. package/apps/server/src/ragents/runtime-bridge.ts +7 -0
  85. package/apps/server/src/ragents/session.ts +859 -0
  86. package/apps/server/src/ragents/start-option-state.ts +37 -0
  87. package/apps/server/src/ragents/typescript-tools.ts +182 -0
  88. package/apps/server/src/ragents/workspace-runtime.ts +64 -0
  89. package/apps/server/src/rpc/dispatcher.ts +178 -0
  90. package/apps/server/src/rpc/http-transport.ts +178 -0
  91. package/apps/server/src/rpc/stdio-transport.ts +44 -0
  92. package/apps/server/src/run-preparation-contract.ts +20 -0
  93. package/apps/server/src/run-preparation-input.ts +16 -0
  94. package/apps/server/src/run-preparation.ts +147 -0
  95. package/apps/server/src/run-transfer.ts +264 -0
  96. package/apps/server/src/server.ts +312 -0
  97. package/apps/server/src/settings.ts +209 -0
  98. package/apps/server/src/startup.ts +13 -0
  99. package/apps/server/src/title-compactor.ts +131 -0
  100. package/apps/server/src/title-settings-contract.ts +9 -0
  101. package/apps/server/src/title-settings.ts +67 -0
  102. package/apps/web/package.json +41 -0
  103. package/apps/web/src/AccessContext.tsx +125 -0
  104. package/apps/web/src/App.tsx +315 -0
  105. package/apps/web/src/CanvasShortcuts.tsx +60 -0
  106. package/apps/web/src/DiffCode.tsx +89 -0
  107. package/apps/web/src/HelpDialog.tsx +87 -0
  108. package/apps/web/src/MaterialSettings.tsx +40 -0
  109. package/apps/web/src/Overview.tsx +201 -0
  110. package/apps/web/src/PluginActivation.ts +41 -0
  111. package/apps/web/src/PluginChat.tsx +552 -0
  112. package/apps/web/src/PluginRegistry.tsx +689 -0
  113. package/apps/web/src/RunPreparationChat.tsx +111 -0
  114. package/apps/web/src/RunStore.ts +86 -0
  115. package/apps/web/src/SessionList.tsx +148 -0
  116. package/apps/web/src/SettingsModal.tsx +949 -0
  117. package/apps/web/src/SourceCode.tsx +49 -0
  118. package/apps/web/src/StartOptions.tsx +231 -0
  119. package/apps/web/src/StartSurface.tsx +161 -0
  120. package/apps/web/src/StatusGroup.tsx +18 -0
  121. package/apps/web/src/ThemeSettings.tsx +46 -0
  122. package/apps/web/src/TitleModelSettings.tsx +100 -0
  123. package/apps/web/src/Toolbar.tsx +28 -0
  124. package/apps/web/src/WorkspacePanel.tsx +309 -0
  125. package/apps/web/src/access-session.ts +27 -0
  126. package/apps/web/src/access-token.ts +31 -0
  127. package/apps/web/src/api.ts +368 -0
  128. package/apps/web/src/chat/ChatInputToolbar.tsx +488 -0
  129. package/apps/web/src/chat/ChatMessages.tsx +666 -0
  130. package/apps/web/src/chat/ChatPanel.tsx +61 -0
  131. package/apps/web/src/chat/DetailModeSwitch.tsx +58 -0
  132. package/apps/web/src/chat/Markdown.tsx +104 -0
  133. package/apps/web/src/chat/QuestionCard.tsx +107 -0
  134. package/apps/web/src/chat/StepPopover.tsx +82 -0
  135. package/apps/web/src/chat/WorkingScenes.tsx +235 -0
  136. package/apps/web/src/chat/attachments.ts +53 -0
  137. package/apps/web/src/chat/chat-scroll.ts +41 -0
  138. package/apps/web/src/chat/chat-target.ts +21 -0
  139. package/apps/web/src/chat/requests.ts +23 -0
  140. package/apps/web/src/chat/texts.ts +61 -0
  141. package/apps/web/src/chat/types.ts +26 -0
  142. package/apps/web/src/chat/useAttachmentCapabilities.ts +35 -0
  143. package/apps/web/src/chat/useChat.ts +46 -0
  144. package/apps/web/src/chat/user-location.ts +22 -0
  145. package/apps/web/src/column/ColumnApp.tsx +158 -0
  146. package/apps/web/src/column/ColumnMenu.tsx +37 -0
  147. package/apps/web/src/column/ColumnRunHeader.tsx +43 -0
  148. package/apps/web/src/column/column-location.ts +30 -0
  149. package/apps/web/src/column/host-contract.ts +83 -0
  150. package/apps/web/src/column/host.ts +101 -0
  151. package/apps/web/src/column/use-session-list.ts +42 -0
  152. package/apps/web/src/column.tsx +43 -0
  153. package/apps/web/src/diff-view.css +38 -0
  154. package/apps/web/src/help-samples.ts +11 -0
  155. package/apps/web/src/highlighting.css +74 -0
  156. package/apps/web/src/highlighting.ts +262 -0
  157. package/apps/web/src/lib/format.ts +5 -0
  158. package/apps/web/src/lib/guards.ts +8 -0
  159. package/apps/web/src/lib/http.ts +9 -0
  160. package/apps/web/src/lib/labels.ts +11 -0
  161. package/apps/web/src/lib/local-storage-setting.ts +39 -0
  162. package/apps/web/src/main.tsx +30 -0
  163. package/apps/web/src/material-settings.ts +104 -0
  164. package/apps/web/src/model-settings-events.ts +1 -0
  165. package/apps/web/src/page-opener.tsx +14 -0
  166. package/apps/web/src/panel/LoginForm.tsx +31 -0
  167. package/apps/web/src/panel/OverviewPage.tsx +90 -0
  168. package/apps/web/src/panel/PanelPage.tsx +9 -0
  169. package/apps/web/src/panel/SettingsPage.tsx +102 -0
  170. package/apps/web/src/panel/contract.ts +101 -0
  171. package/apps/web/src/panel/target-state.ts +53 -0
  172. package/apps/web/src/panel.tsx +30 -0
  173. package/apps/web/src/plugin-bootstrap.ts +90 -0
  174. package/apps/web/src/plugin-discovery.ts +5 -0
  175. package/apps/web/src/rpc/client.ts +301 -0
  176. package/apps/web/src/rpc.ts +4 -0
  177. package/apps/web/src/run-overview.ts +34 -0
  178. package/apps/web/src/run-preparation.ts +16 -0
  179. package/apps/web/src/run-read-state.ts +33 -0
  180. package/apps/web/src/settings-contributions.ts +274 -0
  181. package/apps/web/src/theme.ts +135 -0
  182. package/apps/web/src/title-model-settings.ts +51 -0
  183. package/apps/web/src/toolLine.ts +67 -0
  184. package/apps/web/src/ui/ListDetail.tsx +149 -0
  185. package/apps/web/src/ui/SectionLabel.tsx +7 -0
  186. package/apps/web/src/ui/SvgEdge.tsx +39 -0
  187. package/apps/web/src/ui/alert.tsx +75 -0
  188. package/apps/web/src/ui/badge.tsx +51 -0
  189. package/apps/web/src/ui/button.tsx +57 -0
  190. package/apps/web/src/ui/card.tsx +102 -0
  191. package/apps/web/src/ui/checkbox.tsx +26 -0
  192. package/apps/web/src/ui/dialog.tsx +250 -0
  193. package/apps/web/src/ui/dropdown-menu.tsx +265 -0
  194. package/apps/web/src/ui/empty.tsx +103 -0
  195. package/apps/web/src/ui/field.tsx +236 -0
  196. package/apps/web/src/ui/frame.css +4 -0
  197. package/apps/web/src/ui/index.ts +43 -0
  198. package/apps/web/src/ui/input.tsx +19 -0
  199. package/apps/web/src/ui/label.tsx +17 -0
  200. package/apps/web/src/ui/modal-controller.ts +70 -0
  201. package/apps/web/src/ui/modal.tsx +62 -0
  202. package/apps/web/src/ui/popover.tsx +102 -0
  203. package/apps/web/src/ui/progress.tsx +80 -0
  204. package/apps/web/src/ui/radio-group.tsx +35 -0
  205. package/apps/web/src/ui/select.tsx +198 -0
  206. package/apps/web/src/ui/separator.tsx +22 -0
  207. package/apps/web/src/ui/skeleton.tsx +13 -0
  208. package/apps/web/src/ui/spinner.tsx +10 -0
  209. package/apps/web/src/ui/switch.tsx +29 -0
  210. package/apps/web/src/ui/table.tsx +113 -0
  211. package/apps/web/src/ui/tabs.tsx +79 -0
  212. package/apps/web/src/ui/tailwind.css +21 -0
  213. package/apps/web/src/ui/textarea.tsx +17 -0
  214. package/apps/web/src/ui/theme.css +300 -0
  215. package/apps/web/src/ui/toggle-group.tsx +87 -0
  216. package/apps/web/src/ui/toggle.tsx +42 -0
  217. package/apps/web/src/ui/tooltip.tsx +63 -0
  218. package/apps/web/src/ui/useFileInput.ts +50 -0
  219. package/apps/web/src/virtual-plugins.d.ts +3 -0
  220. package/apps/web/src/vite-env.d.ts +1 -0
  221. package/package.json +82 -0
  222. package/packages/agent/package.json +64 -0
  223. package/packages/agent/src/config.ts +161 -0
  224. package/packages/agent/src/core/agent-session-runtime.ts +548 -0
  225. package/packages/agent/src/core/agent-session-services.ts +224 -0
  226. package/packages/agent/src/core/agent-session.ts +3357 -0
  227. package/packages/agent/src/core/auth-guidance.ts +18 -0
  228. package/packages/agent/src/core/auth-storage.ts +271 -0
  229. package/packages/agent/src/core/bash-executor.ts +156 -0
  230. package/packages/agent/src/core/compaction/branch-summarization.ts +372 -0
  231. package/packages/agent/src/core/compaction/compaction.ts +875 -0
  232. package/packages/agent/src/core/compaction/index.ts +7 -0
  233. package/packages/agent/src/core/compaction/utils.ts +174 -0
  234. package/packages/agent/src/core/defaults.ts +3 -0
  235. package/packages/agent/src/core/diagnostics.ts +15 -0
  236. package/packages/agent/src/core/event-bus.ts +33 -0
  237. package/packages/agent/src/core/exec.ts +107 -0
  238. package/packages/agent/src/core/experimental.ts +3 -0
  239. package/packages/agent/src/core/extensions/index.ts +149 -0
  240. package/packages/agent/src/core/extensions/loader.ts +709 -0
  241. package/packages/agent/src/core/extensions/runner.ts +1132 -0
  242. package/packages/agent/src/core/extensions/types.ts +1460 -0
  243. package/packages/agent/src/core/extensions/wrapper.ts +45 -0
  244. package/packages/agent/src/core/footer-data-provider.ts +388 -0
  245. package/packages/agent/src/core/http-dispatcher.ts +106 -0
  246. package/packages/agent/src/core/index.ts +78 -0
  247. package/packages/agent/src/core/messages.ts +195 -0
  248. package/packages/agent/src/core/model-config.ts +287 -0
  249. package/packages/agent/src/core/model-registry.ts +126 -0
  250. package/packages/agent/src/core/model-resolver.ts +675 -0
  251. package/packages/agent/src/core/model-runtime.ts +517 -0
  252. package/packages/agent/src/core/output-guard.ts +108 -0
  253. package/packages/agent/src/core/package-manager.ts +2441 -0
  254. package/packages/agent/src/core/prompt-templates.ts +284 -0
  255. package/packages/agent/src/core/provider-composer.ts +549 -0
  256. package/packages/agent/src/core/resolve-config-value.ts +287 -0
  257. package/packages/agent/src/core/resource-loader.ts +946 -0
  258. package/packages/agent/src/core/runtime-credentials.ts +48 -0
  259. package/packages/agent/src/core/sdk.ts +358 -0
  260. package/packages/agent/src/core/session-cwd.ts +59 -0
  261. package/packages/agent/src/core/session-manager.ts +1623 -0
  262. package/packages/agent/src/core/settings-manager.ts +1212 -0
  263. package/packages/agent/src/core/skills.ts +487 -0
  264. package/packages/agent/src/core/slash-commands.ts +41 -0
  265. package/packages/agent/src/core/source-info.ts +40 -0
  266. package/packages/agent/src/core/system-prompt.ts +147 -0
  267. package/packages/agent/src/core/timings.ts +50 -0
  268. package/packages/agent/src/core/tools/bash.ts +314 -0
  269. package/packages/agent/src/core/tools/edit-diff.ts +704 -0
  270. package/packages/agent/src/core/tools/edit.ts +222 -0
  271. package/packages/agent/src/core/tools/file-mutation-queue.ts +61 -0
  272. package/packages/agent/src/core/tools/index.ts +130 -0
  273. package/packages/agent/src/core/tools/output-accumulator.ts +222 -0
  274. package/packages/agent/src/core/tools/path-utils.ts +118 -0
  275. package/packages/agent/src/core/tools/read.ts +195 -0
  276. package/packages/agent/src/core/tools/tool-definition-wrapper.ts +45 -0
  277. package/packages/agent/src/core/tools/truncate.ts +276 -0
  278. package/packages/agent/src/core/tools/write.ts +90 -0
  279. package/packages/agent/src/core/trust-manager.ts +244 -0
  280. package/packages/agent/src/index.ts +287 -0
  281. package/packages/agent/src/utils/ansi.ts +60 -0
  282. package/packages/agent/src/utils/child-process.ts +137 -0
  283. package/packages/agent/src/utils/exif-orientation.ts +183 -0
  284. package/packages/agent/src/utils/frontmatter.ts +39 -0
  285. package/packages/agent/src/utils/fs-watch.ts +30 -0
  286. package/packages/agent/src/utils/git.ts +226 -0
  287. package/packages/agent/src/utils/image-convert.ts +49 -0
  288. package/packages/agent/src/utils/image-process.ts +119 -0
  289. package/packages/agent/src/utils/image-resize-core.ts +164 -0
  290. package/packages/agent/src/utils/image-resize-worker.ts +42 -0
  291. package/packages/agent/src/utils/image-resize.ts +123 -0
  292. package/packages/agent/src/utils/json.ts +6 -0
  293. package/packages/agent/src/utils/mime.ts +116 -0
  294. package/packages/agent/src/utils/paths.ts +118 -0
  295. package/packages/agent/src/utils/photon.ts +139 -0
  296. package/packages/agent/src/utils/shell.ts +225 -0
  297. package/packages/agent/src/utils/sleep.ts +18 -0
  298. package/packages/agent/src/utils/tools-manager.ts +63 -0
  299. package/packages/agent-core/package.json +32 -0
  300. package/packages/agent-core/src/agent-loop.ts +877 -0
  301. package/packages/agent-core/src/agent.ts +598 -0
  302. package/packages/agent-core/src/index.ts +4 -0
  303. package/packages/agent-core/src/types.ts +455 -0
  304. package/packages/agent-core/src/uuid.ts +54 -0
  305. package/packages/ai/package.json +46 -0
  306. package/packages/ai/src/api/ai-sdk-messages.ts +102 -0
  307. package/packages/ai/src/api/ai-sdk-transport.ts +53 -0
  308. package/packages/ai/src/api/ai-sdk.lazy.ts +4 -0
  309. package/packages/ai/src/api/ai-sdk.ts +273 -0
  310. package/packages/ai/src/api/lazy.ts +75 -0
  311. package/packages/ai/src/api/openrouter-images.lazy.ts +10 -0
  312. package/packages/ai/src/api/openrouter-images.ts +98 -0
  313. package/packages/ai/src/api/simple-options.ts +77 -0
  314. package/packages/ai/src/api/transform-messages.ts +185 -0
  315. package/packages/ai/src/api-registry.ts +226 -0
  316. package/packages/ai/src/auth/context.ts +45 -0
  317. package/packages/ai/src/auth/credential-store.ts +51 -0
  318. package/packages/ai/src/auth/helpers.ts +47 -0
  319. package/packages/ai/src/auth/resolve.ts +139 -0
  320. package/packages/ai/src/auth/types.ts +220 -0
  321. package/packages/ai/src/compat/extension-oauth-types.ts +45 -0
  322. package/packages/ai/src/env-api-keys.ts +24 -0
  323. package/packages/ai/src/image-models.generated.ts +533 -0
  324. package/packages/ai/src/images-models.ts +274 -0
  325. package/packages/ai/src/index.ts +33 -0
  326. package/packages/ai/src/models-store.ts +38 -0
  327. package/packages/ai/src/models.generated.ts +6 -0
  328. package/packages/ai/src/models.ts +705 -0
  329. package/packages/ai/src/oauth.ts +10 -0
  330. package/packages/ai/src/providers/all.ts +64 -0
  331. package/packages/ai/src/providers/faux.ts +539 -0
  332. package/packages/ai/src/providers/openrouter-images.ts +14 -0
  333. package/packages/ai/src/providers/openrouter.models.ts +6050 -0
  334. package/packages/ai/src/providers/openrouter.ts +15 -0
  335. package/packages/ai/src/session-resources.ts +24 -0
  336. package/packages/ai/src/types.ts +692 -0
  337. package/packages/ai/src/utils/abort-signals.ts +41 -0
  338. package/packages/ai/src/utils/deferred-tools.ts +39 -0
  339. package/packages/ai/src/utils/diagnostics.ts +45 -0
  340. package/packages/ai/src/utils/error-body.ts +129 -0
  341. package/packages/ai/src/utils/estimate.ts +146 -0
  342. package/packages/ai/src/utils/event-stream.ts +88 -0
  343. package/packages/ai/src/utils/hash.ts +13 -0
  344. package/packages/ai/src/utils/headers.ts +18 -0
  345. package/packages/ai/src/utils/json-parse.ts +124 -0
  346. package/packages/ai/src/utils/node-http-proxy.ts +112 -0
  347. package/packages/ai/src/utils/overflow.ts +165 -0
  348. package/packages/ai/src/utils/provider-env.ts +52 -0
  349. package/packages/ai/src/utils/retry.ts +101 -0
  350. package/packages/ai/src/utils/sanitize-unicode.ts +25 -0
  351. package/packages/ai/src/utils/typebox-helpers.ts +24 -0
  352. package/packages/ai/src/utils/validation.ts +383 -0
  353. package/packages/ragents/package.json +31 -0
  354. package/packages/ragents/src/access.ts +54 -0
  355. package/packages/ragents/src/agents/actor-input.ts +191 -0
  356. package/packages/ragents/src/agents/catalog.ts +220 -0
  357. package/packages/ragents/src/agents/delivery.ts +187 -0
  358. package/packages/ragents/src/agents/live.ts +71 -0
  359. package/packages/ragents/src/agents/plugins.ts +130 -0
  360. package/packages/ragents/src/agents/scheduler.ts +1048 -0
  361. package/packages/ragents/src/agents/schemas.ts +64 -0
  362. package/packages/ragents/src/agents/tool-orientation.ts +12 -0
  363. package/packages/ragents/src/agents/tools.ts +709 -0
  364. package/packages/ragents/src/agents/toolset.ts +324 -0
  365. package/packages/ragents/src/agents/turn.ts +65 -0
  366. package/packages/ragents/src/agents/workspace-tools.ts +11 -0
  367. package/packages/ragents/src/agents/workspaces.ts +15 -0
  368. package/packages/ragents/src/domain/draft.ts +11 -0
  369. package/packages/ragents/src/domain/driver.ts +56 -0
  370. package/packages/ragents/src/domain/event-semantics.ts +668 -0
  371. package/packages/ragents/src/domain/event-validation.ts +620 -0
  372. package/packages/ragents/src/domain/events.ts +236 -0
  373. package/packages/ragents/src/domain/json-patch.ts +77 -0
  374. package/packages/ragents/src/domain/json.ts +86 -0
  375. package/packages/ragents/src/domain/model.ts +267 -0
  376. package/packages/ragents/src/domain/plugin-state.ts +33 -0
  377. package/packages/ragents/src/domain/portable-id.ts +9 -0
  378. package/packages/ragents/src/domain/projection.ts +506 -0
  379. package/packages/ragents/src/domain/schema-errors.ts +56 -0
  380. package/packages/ragents/src/domain/vocabulary.ts +37 -0
  381. package/packages/ragents/src/drivers/agent-runtime.ts +1503 -0
  382. package/packages/ragents/src/drivers/agent.ts +108 -0
  383. package/packages/ragents/src/drivers/attachments.ts +56 -0
  384. package/packages/ragents/src/drivers/skill-preload.ts +205 -0
  385. package/packages/ragents/src/drivers/types.ts +77 -0
  386. package/packages/ragents/src/http/contracts.ts +80 -0
  387. package/packages/ragents/src/http/methods.ts +150 -0
  388. package/packages/ragents/src/index.ts +161 -0
  389. package/packages/ragents/src/plugin-host.ts +1184 -0
  390. package/packages/ragents/src/plugin-types.ts +373 -0
  391. package/packages/ragents/src/rpc/contract.ts +76 -0
  392. package/packages/ragents/src/rpc/contribution.ts +67 -0
  393. package/packages/ragents/src/rpc/peer.ts +208 -0
  394. package/packages/ragents/src/rpc/protocol.ts +129 -0
  395. package/packages/ragents/src/runtime/artifacts.ts +95 -0
  396. package/packages/ragents/src/runtime/canonical-hash.ts +5 -0
  397. package/packages/ragents/src/runtime/canonical-json.ts +41 -0
  398. package/packages/ragents/src/runtime/command.ts +35 -0
  399. package/packages/ragents/src/runtime/decisions/actions.ts +77 -0
  400. package/packages/ragents/src/runtime/decisions/actors.ts +283 -0
  401. package/packages/ragents/src/runtime/decisions/artifacts.ts +28 -0
  402. package/packages/ragents/src/runtime/decisions/inputs.ts +79 -0
  403. package/packages/ragents/src/runtime/decisions/subscriptions.ts +135 -0
  404. package/packages/ragents/src/runtime/decisions/turns.ts +166 -0
  405. package/packages/ragents/src/runtime/domain-error.ts +10 -0
  406. package/packages/ragents/src/runtime/durable-fs.ts +13 -0
  407. package/packages/ragents/src/runtime/failures.ts +18 -0
  408. package/packages/ragents/src/runtime/guards.ts +196 -0
  409. package/packages/ragents/src/runtime/journal-storage.ts +228 -0
  410. package/packages/ragents/src/runtime/journal.ts +952 -0
  411. package/packages/ragents/src/runtime/orchestration.ts +711 -0
  412. package/packages/ragents/src/runtime/serial-queue.ts +13 -0
  413. package/packages/ragents/src/runtime/services.ts +15 -0
  414. package/packages/ragents/src/runtime/stop.ts +186 -0
  415. package/packages/ragents/src/script/driver.ts +18 -0
  416. package/packages/ragents/src/script/mediators.ts +386 -0
  417. package/packages/ragents/src/script/programs.ts +10 -0
  418. package/packages/ragents/src/script/std.ts +27 -0
  419. package/packages/ragents/src/script/types.ts +6 -0
  420. package/packages/ragents/src/typescript/async-compiler.ts +322 -0
  421. package/packages/ragents/src/typescript/build-contract.ts +14 -0
  422. package/packages/ragents/src/typescript/compiler-worker.ts +52 -0
  423. package/packages/ragents/src/typescript/compiler.ts +304 -0
  424. package/packages/ragents/src/typescript/index.ts +48 -0
  425. package/packages/ragents/src/typescript/native-executor.ts +40 -0
  426. package/packages/ragents/src/typescript/native-program.ts +5 -0
  427. package/packages/ragents/src/typescript/run-context.ts +199 -0
  428. package/packages/ragents/src/typescript/schema.ts +176 -0
  429. package/packages/ragents/src/typescript/snippet.ts +121 -0
  430. package/packages/workspace-executor/package.json +25 -0
  431. package/packages/workspace-executor/src/context.ts +123 -0
  432. package/packages/workspace-executor/src/executor.ts +134 -0
  433. package/packages/workspace-executor/src/git-config-environment.ts +10 -0
  434. package/packages/workspace-executor/src/index.ts +52 -0
  435. package/packages/workspace-executor/src/language-server/adapters/fsharp.ts +59 -0
  436. package/packages/workspace-executor/src/language-server/adapters/index.ts +7 -0
  437. package/packages/workspace-executor/src/language-server/adapters/roslyn.ts +54 -0
  438. package/packages/workspace-executor/src/language-server/adapters/typescript.ts +46 -0
  439. package/packages/workspace-executor/src/language-server/contract.ts +23 -0
  440. package/packages/workspace-executor/src/language-server/diagnostics.ts +62 -0
  441. package/packages/workspace-executor/src/language-server/host.ts +409 -0
  442. package/packages/workspace-executor/src/language-server/json-rpc.ts +103 -0
  443. package/packages/workspace-executor/src/language-server/roots.ts +29 -0
  444. package/packages/workspace-executor/src/language-server/session.ts +442 -0
  445. package/packages/workspace-executor/src/language-server/solution.ts +13 -0
  446. package/packages/workspace-executor/src/managed-process.ts +329 -0
  447. package/packages/workspace-executor/src/paths.ts +43 -0
  448. package/packages/workspace-executor/src/run-marker.ts +6 -0
  449. package/packages/workspace-executor/src/safe-environment.ts +47 -0
  450. package/packages/workspace-executor/src/sandbox-tools.ts +258 -0
  451. package/packages/workspace-executor/src/session-ident.ts +37 -0
  452. package/packages/workspace-executor/src/shell-platform.ts +11 -0
  453. package/packages/workspace-executor/src/tools.ts +28 -0
  454. package/plugins/package.json +8 -0
  455. package/plugins/ragents.activity/server/index.ts +9 -0
  456. package/plugins/ragents.activity/web/ActivityHeader.tsx +58 -0
  457. package/plugins/ragents.activity/web/activity.ts +144 -0
  458. package/plugins/ragents.activity/web/index.tsx +13 -0
  459. package/plugins/ragents.actor-programs/client-ui/DataTable.tsx +100 -0
  460. package/plugins/ragents.actor-programs/client-ui/FilePicker.tsx +65 -0
  461. package/plugins/ragents.actor-programs/client-ui/FlowDiagram.tsx +234 -0
  462. package/plugins/ragents.actor-programs/client-ui/FlowDiagramRenderer.tsx +85 -0
  463. package/plugins/ragents.actor-programs/client-ui/Form.tsx +126 -0
  464. package/plugins/ragents.actor-programs/client-ui/Layout.tsx +27 -0
  465. package/plugins/ragents.actor-programs/client-ui/MessageList.tsx +30 -0
  466. package/plugins/ragents.actor-programs/client-ui/Viewers.tsx +41 -0
  467. package/plugins/ragents.actor-programs/client-ui/WorkflowDiagram.tsx +14 -0
  468. package/plugins/ragents.actor-programs/client-ui/contracts.d.ts +84 -0
  469. package/plugins/ragents.actor-programs/client-ui/file-contracts.d.ts +19 -0
  470. package/plugins/ragents.actor-programs/client-ui/file-selection.ts +24 -0
  471. package/plugins/ragents.actor-programs/client-ui/flow-diagram-contracts.d.ts +27 -0
  472. package/plugins/ragents.actor-programs/client-ui/flow-diagram.css +23 -0
  473. package/plugins/ragents.actor-programs/client-ui/form-contracts.d.ts +38 -0
  474. package/plugins/ragents.actor-programs/client-ui/frame-layout.ts +4 -0
  475. package/plugins/ragents.actor-programs/client-ui/index.tsx +81 -0
  476. package/plugins/ragents.actor-programs/client-ui/layout-contracts.d.ts +33 -0
  477. package/plugins/ragents.actor-programs/client-ui/message-list-contracts.d.ts +33 -0
  478. package/plugins/ragents.actor-programs/client-ui/table-contracts.d.ts +35 -0
  479. package/plugins/ragents.actor-programs/client-ui/viewer-contracts.d.ts +37 -0
  480. package/plugins/ragents.actor-programs/client-ui/workflow-diagram-contracts.d.ts +10 -0
  481. package/plugins/ragents.actor-programs/contract.ts +180 -0
  482. package/plugins/ragents.actor-programs/parameter-types.ts +3 -0
  483. package/plugins/ragents.actor-programs/prompt.hbs +79 -0
  484. package/plugins/ragents.actor-programs/server/agent-tools.ts +31 -0
  485. package/plugins/ragents.actor-programs/server/app-project.ts +284 -0
  486. package/plugins/ragents.actor-programs/server/authoring-contracts.ts +10 -0
  487. package/plugins/ragents.actor-programs/server/client-compiler.ts +174 -0
  488. package/plugins/ragents.actor-programs/server/client-contracts.ts +187 -0
  489. package/plugins/ragents.actor-programs/server/client-runtime.ts +16 -0
  490. package/plugins/ragents.actor-programs/server/controls-template.ts +118 -0
  491. package/plugins/ragents.actor-programs/server/controls-tool.ts +48 -0
  492. package/plugins/ragents.actor-programs/server/index.ts +51 -0
  493. package/plugins/ragents.actor-programs/server/methods.ts +72 -0
  494. package/plugins/ragents.actor-programs/server/project-diagnostics.ts +138 -0
  495. package/plugins/ragents.actor-programs/server/prompts.ts +21 -0
  496. package/plugins/ragents.actor-programs/server/routes.ts +235 -0
  497. package/plugins/ragents.actor-programs/server/runtime-libraries.ts +4 -0
  498. package/plugins/ragents.actor-programs/server/runtime.ts +721 -0
  499. package/plugins/ragents.actor-programs/server/tailwind.ts +22 -0
  500. package/plugins/ragents.actor-programs/server/templates.ts +400 -0
  501. package/plugins/ragents.actor-programs/server/tool-contributor.ts +29 -0
  502. package/plugins/ragents.actor-programs/summary.hbs +17 -0
  503. package/plugins/ragents.actor-programs/web/ActorViewFrame.tsx +463 -0
  504. package/plugins/ragents.actor-programs/web/AppsPanel.tsx +436 -0
  505. package/plugins/ragents.actor-programs/web/EmbeddedApps.tsx +116 -0
  506. package/plugins/ragents.actor-programs/web/ExpandIcon.tsx +5 -0
  507. package/plugins/ragents.actor-programs/web/FullscreenHost.tsx +31 -0
  508. package/plugins/ragents.actor-programs/web/FunctionForm.tsx +102 -0
  509. package/plugins/ragents.actor-programs/web/ProgramSource.tsx +81 -0
  510. package/plugins/ragents.actor-programs/web/api.ts +353 -0
  511. package/plugins/ragents.actor-programs/web/bridge.ts +122 -0
  512. package/plugins/ragents.actor-programs/web/chat-state.ts +37 -0
  513. package/plugins/ragents.actor-programs/web/context.ts +30 -0
  514. package/plugins/ragents.actor-programs/web/function-call.ts +28 -0
  515. package/plugins/ragents.actor-programs/web/function-input.ts +40 -0
  516. package/plugins/ragents.actor-programs/web/index.tsx +96 -0
  517. package/plugins/ragents.actor-programs/web/invocations.ts +43 -0
  518. package/plugins/ragents.actor-programs/web/program-state.ts +68 -0
  519. package/plugins/ragents.actor-programs/web/state-revision.ts +16 -0
  520. package/plugins/ragents.actor-programs/workflow/index.ts +202 -0
  521. package/plugins/ragents.actor-programs/workflow/prompt-reader.ts +15 -0
  522. package/plugins/ragents.ask/ask.hbs +4 -0
  523. package/plugins/ragents.ask/contract.ts +17 -0
  524. package/plugins/ragents.ask/server/answer-method.ts +15 -0
  525. package/plugins/ragents.ask/server/ask-service.ts +152 -0
  526. package/plugins/ragents.ask/server/ask-tool.ts +39 -0
  527. package/plugins/ragents.ask/server/contract.ts +22 -0
  528. package/plugins/ragents.ask/server/index.ts +26 -0
  529. package/plugins/ragents.ask/server/tool-contributor.ts +11 -0
  530. package/plugins/ragents.ask/web/QuestionSection.tsx +47 -0
  531. package/plugins/ragents.ask/web/api.ts +6 -0
  532. package/plugins/ragents.ask/web/constants.ts +1 -0
  533. package/plugins/ragents.ask/web/index.tsx +50 -0
  534. package/plugins/ragents.browser/provision.ts +48 -0
  535. package/plugins/ragents.browser/server/browser.ts +393 -0
  536. package/plugins/ragents.browser/server/contract.ts +36 -0
  537. package/plugins/ragents.browser/server/index.ts +35 -0
  538. package/plugins/ragents.browser/server/tools.ts +197 -0
  539. package/plugins/ragents.browser/skills/browser-testing/SKILL.md +36 -0
  540. package/plugins/ragents.documents/contract.ts +33 -0
  541. package/plugins/ragents.documents/prompt.hbs +18 -0
  542. package/plugins/ragents.documents/server/config.ts +14 -0
  543. package/plugins/ragents.documents/server/document-write-tool.ts +45 -0
  544. package/plugins/ragents.documents/server/files-route.ts +137 -0
  545. package/plugins/ragents.documents/server/index.ts +38 -0
  546. package/plugins/ragents.documents/server/show-document-tool.ts +73 -0
  547. package/plugins/ragents.documents/server/store.ts +35 -0
  548. package/plugins/ragents.documents/server/tool-contributor.ts +16 -0
  549. package/plugins/ragents.documents/web/DocumentViewer.tsx +450 -0
  550. package/plugins/ragents.documents/web/api.ts +8 -0
  551. package/plugins/ragents.documents/web/index.tsx +279 -0
  552. package/plugins/ragents.lsp-fsharp/provision.ts +74 -0
  553. package/plugins/ragents.lsp-fsharp/server/index.ts +16 -0
  554. package/plugins/ragents.lsp-fsharp/web/index.tsx +7 -0
  555. package/plugins/ragents.lsp-roslyn/provision.ts +54 -0
  556. package/plugins/ragents.lsp-roslyn/server/index.ts +15 -0
  557. package/plugins/ragents.lsp-roslyn/web/api.ts +10 -0
  558. package/plugins/ragents.lsp-roslyn/web/index.tsx +7 -0
  559. package/plugins/ragents.lsp-roslyn/web/language-server-plugin.tsx +236 -0
  560. package/plugins/ragents.lsp-typescript/server/index.ts +7 -0
  561. package/plugins/ragents.lsp-typescript/web/index.tsx +7 -0
  562. package/plugins/ragents.model-relay/server/config.ts +37 -0
  563. package/plugins/ragents.model-relay/server/index.ts +31 -0
  564. package/plugins/ragents.model-relay/server/relay.ts +213 -0
  565. package/plugins/ragents.orchestration/canvas.hbs +50 -0
  566. package/plugins/ragents.orchestration/contract.ts +322 -0
  567. package/plugins/ragents.orchestration/orchestration.hbs +105 -0
  568. package/plugins/ragents.orchestration/server/canvas-tool.ts +248 -0
  569. package/plugins/ragents.orchestration/server/index.ts +64 -0
  570. package/plugins/ragents.orchestration/server/run-stop-tool.ts +30 -0
  571. package/plugins/ragents.orchestration/tiled-layout.ts +47 -0
  572. package/plugins/ragents.orchestration/web/ActorCanvasControls.tsx +159 -0
  573. package/plugins/ragents.orchestration/web/ActorChat.tsx +56 -0
  574. package/plugins/ragents.orchestration/web/ActorChatControls.tsx +64 -0
  575. package/plugins/ragents.orchestration/web/ActorChatPreview.tsx +36 -0
  576. package/plugins/ragents.orchestration/web/ActorNet.tsx +607 -0
  577. package/plugins/ragents.orchestration/web/ActorPopout.tsx +36 -0
  578. package/plugins/ragents.orchestration/web/ActorShortcut.tsx +76 -0
  579. package/plugins/ragents.orchestration/web/ActorTile.tsx +22 -0
  580. package/plugins/ragents.orchestration/web/CanvasStartup.tsx +14 -0
  581. package/plugins/ragents.orchestration/web/CanvasTiles.tsx +47 -0
  582. package/plugins/ragents.orchestration/web/CardSizeSettings.tsx +42 -0
  583. package/plugins/ragents.orchestration/web/Center.tsx +576 -0
  584. package/plugins/ragents.orchestration/web/DocumentsSection.tsx +37 -0
  585. package/plugins/ragents.orchestration/web/ExecutionsPanel.tsx +109 -0
  586. package/plugins/ragents.orchestration/web/FlowInspector.tsx +932 -0
  587. package/plugins/ragents.orchestration/web/JournalStatus.tsx +87 -0
  588. package/plugins/ragents.orchestration/web/MaterialBody.tsx +104 -0
  589. package/plugins/ragents.orchestration/web/ScriptActorCard.tsx +56 -0
  590. package/plugins/ragents.orchestration/web/StopRunButton.tsx +52 -0
  591. package/plugins/ragents.orchestration/web/TiledCanvas.tsx +281 -0
  592. package/plugins/ragents.orchestration/web/ZoomSettings.tsx +38 -0
  593. package/plugins/ragents.orchestration/web/actor-conversation.ts +64 -0
  594. package/plugins/ragents.orchestration/web/actor-header-settings.ts +41 -0
  595. package/plugins/ragents.orchestration/web/api.ts +33 -0
  596. package/plugins/ragents.orchestration/web/canvas-layout-storage.ts +39 -0
  597. package/plugins/ragents.orchestration/web/canvas-layout.ts +326 -0
  598. package/plugins/ragents.orchestration/web/canvas-scene.ts +311 -0
  599. package/plugins/ragents.orchestration/web/canvas-stage.ts +21 -0
  600. package/plugins/ragents.orchestration/web/canvas-startup.ts +36 -0
  601. package/plugins/ragents.orchestration/web/canvas-view-settings.ts +48 -0
  602. package/plugins/ragents.orchestration/web/card-size-settings.ts +36 -0
  603. package/plugins/ragents.orchestration/web/column/AddresseeControl.tsx +116 -0
  604. package/plugins/ragents.orchestration/web/column/ColumnSettings.tsx +50 -0
  605. package/plugins/ragents.orchestration/web/column/RunColumn.tsx +370 -0
  606. package/plugins/ragents.orchestration/web/column/column-actors.ts +38 -0
  607. package/plugins/ragents.orchestration/web/column/column-settings.ts +47 -0
  608. package/plugins/ragents.orchestration/web/column/column-state.ts +59 -0
  609. package/plugins/ragents.orchestration/web/column/sheet-status.ts +30 -0
  610. package/plugins/ragents.orchestration/web/constants.ts +10 -0
  611. package/plugins/ragents.orchestration/web/contract.ts +25 -0
  612. package/plugins/ragents.orchestration/web/executions.ts +124 -0
  613. package/plugins/ragents.orchestration/web/format.ts +4 -0
  614. package/plugins/ragents.orchestration/web/index.tsx +182 -0
  615. package/plugins/ragents.orchestration/web/keyboard-navigation.ts +55 -0
  616. package/plugins/ragents.orchestration/web/material-layout.ts +14 -0
  617. package/plugins/ragents.orchestration/web/run-view.ts +199 -0
  618. package/plugins/ragents.orchestration/web/tile-docking.ts +99 -0
  619. package/plugins/ragents.orchestration/web/tiled-view-settings.ts +76 -0
  620. package/plugins/ragents.orchestration/web/useCanvasMeasurements.ts +78 -0
  621. package/plugins/ragents.orchestration/web/zoom-settings.ts +28 -0
  622. package/plugins/ragents.overseer/contract.ts +165 -0
  623. package/plugins/ragents.overseer/server/api.ts +82 -0
  624. package/plugins/ragents.overseer/server/coordinator-prompt.ts +13 -0
  625. package/plugins/ragents.overseer/server/index.ts +71 -0
  626. package/plugins/ragents.overseer/server/orientation.ts +33 -0
  627. package/plugins/ragents.overseer/server/quick-answer.ts +54 -0
  628. package/plugins/ragents.overseer/server/reset-method.ts +5 -0
  629. package/plugins/ragents.overseer/server/run-directory.ts +49 -0
  630. package/plugins/ragents.overseer/server/settings-method.ts +8 -0
  631. package/plugins/ragents.overseer/server/settings.ts +83 -0
  632. package/plugins/ragents.overseer/server/user-location.ts +96 -0
  633. package/plugins/ragents.overseer/web/ModelSettings.tsx +70 -0
  634. package/plugins/ragents.overseer/web/chat-display.ts +10 -0
  635. package/plugins/ragents.overseer/web/index.tsx +208 -0
  636. package/plugins/ragents.overseer/web/model-settings.ts +61 -0
  637. package/plugins/ragents.overseer/web/quick-answers.ts +64 -0
  638. package/plugins/ragents.processes/contract.ts +61 -0
  639. package/plugins/ragents.processes/server/index.ts +36 -0
  640. package/plugins/ragents.processes/server/methods.ts +39 -0
  641. package/plugins/ragents.processes/server/observer.ts +179 -0
  642. package/plugins/ragents.processes/server/process-table.ts +395 -0
  643. package/plugins/ragents.processes/server/snapshot.ts +63 -0
  644. package/plugins/ragents.processes/server/terminator.ts +164 -0
  645. package/plugins/ragents.processes/web/ProcessHeader.tsx +157 -0
  646. package/plugins/ragents.processes/web/index.tsx +23 -0
  647. package/plugins/ragents.processes/web/processes.ts +75 -0
  648. package/plugins/ragents.product/model-settings-contract.ts +10 -0
  649. package/plugins/ragents.product/preamble.hbs +9 -0
  650. package/plugins/ragents.product/server/config.ts +73 -0
  651. package/plugins/ragents.product/server/index.ts +117 -0
  652. package/plugins/ragents.product/server/relay.ts +118 -0
  653. package/plugins/ragents.product/server/runtime.ts +30 -0
  654. package/plugins/ragents.product/web/ModelControl.tsx +81 -0
  655. package/plugins/ragents.product/web/ProductModelSettings.tsx +131 -0
  656. package/plugins/ragents.product/web/SystemPromptControl.tsx +136 -0
  657. package/plugins/ragents.product/web/index.tsx +29 -0
  658. package/plugins/ragents.product/web/model-settings.ts +39 -0
  659. package/plugins/ragents.product/web/start-options.tsx +12 -0
  660. package/plugins/ragents.profile-distribution/contract.ts +38 -0
  661. package/plugins/ragents.profile-distribution/server/archive.ts +159 -0
  662. package/plugins/ragents.profile-distribution/server/config.ts +27 -0
  663. package/plugins/ragents.profile-distribution/server/index.ts +93 -0
  664. package/plugins/ragents.profile-distribution/server/web.ts +48 -0
  665. package/plugins/ragents.reference/examples.ts +33 -0
  666. package/plugins/ragents.reference/run-scripts/balcony-wizard/RUN.md +27 -0
  667. package/plugins/ragents.reference/run-scripts/balcony-wizard/actors/balcony-app/package.json +10 -0
  668. package/plugins/ragents.reference/run-scripts/balcony-wizard/actors/balcony-app/src/client.tsx +80 -0
  669. package/plugins/ragents.reference/run-scripts/balcony-wizard/actors/balcony-app/src/conversation.ts +82 -0
  670. package/plugins/ragents.reference/run-scripts/balcony-wizard/actors/balcony-app/tests/conversation.test.ts +154 -0
  671. package/plugins/ragents.reference/run-scripts/balcony-wizard/package.json +9 -0
  672. package/plugins/ragents.reference/run-scripts/balcony-wizard/src/server.ts +32 -0
  673. package/plugins/ragents.reference/run-scripts/balcony-wizard/tests/program.test.ts +59 -0
  674. package/plugins/ragents.reference/run-scripts/conversation-circle/RUN.md +14 -0
  675. package/plugins/ragents.reference/run-scripts/conversation-circle/package.json +9 -0
  676. package/plugins/ragents.reference/run-scripts/conversation-circle/src/server.ts +87 -0
  677. package/plugins/ragents.reference/run-scripts/conversation-circle/tests/helpers.ts +26 -0
  678. package/plugins/ragents.reference/run-scripts/conversation-circle/tests/program.test.ts +32 -0
  679. package/plugins/ragents.reference/run-scripts/learning-afternoon/RUN.md +24 -0
  680. package/plugins/ragents.reference/run-scripts/learning-afternoon/package.json +10 -0
  681. package/plugins/ragents.reference/run-scripts/learning-afternoon/prompts/experiment.md +1 -0
  682. package/plugins/ragents.reference/run-scripts/learning-afternoon/prompts/helper.md +5 -0
  683. package/plugins/ragents.reference/run-scripts/learning-afternoon/prompts/quiz.md +1 -0
  684. package/plugins/ragents.reference/run-scripts/learning-afternoon/src/client.tsx +27 -0
  685. package/plugins/ragents.reference/run-scripts/learning-afternoon/src/server.ts +127 -0
  686. package/plugins/ragents.reference/run-scripts/learning-afternoon/src/state.ts +38 -0
  687. package/plugins/ragents.reference/run-scripts/learning-afternoon/src/view.tsx +42 -0
  688. package/plugins/ragents.reference/run-scripts/learning-afternoon/src/workflow.ts +38 -0
  689. package/plugins/ragents.reference/run-scripts/learning-afternoon/tests/program.test.ts +223 -0
  690. package/plugins/ragents.reference/run-scripts/moderated-round/RUN.md +12 -0
  691. package/plugins/ragents.reference/run-scripts/moderated-round/package.json +9 -0
  692. package/plugins/ragents.reference/run-scripts/moderated-round/src/server.ts +60 -0
  693. package/plugins/ragents.reference/run-scripts/moderated-round/tests/helpers.ts +26 -0
  694. package/plugins/ragents.reference/run-scripts/moderated-round/tests/program.test.ts +24 -0
  695. package/plugins/ragents.reference/run-scripts/shared-actor-list/RUN.md +18 -0
  696. package/plugins/ragents.reference/run-scripts/shared-actor-list/actors/shared-list/package.json +16 -0
  697. package/plugins/ragents.reference/run-scripts/shared-actor-list/actors/shared-list/src/client.tsx +39 -0
  698. package/plugins/ragents.reference/run-scripts/shared-actor-list/actors/shared-list/src/contract.ts +15 -0
  699. package/plugins/ragents.reference/run-scripts/shared-actor-list/actors/shared-list/src/server.ts +14 -0
  700. package/plugins/ragents.reference/run-scripts/shared-actor-list/actors/shared-list/tests/program.test.ts +13 -0
  701. package/plugins/ragents.reference/run-scripts/shared-actor-list/package.json +9 -0
  702. package/plugins/ragents.reference/run-scripts/shared-actor-list/src/server.ts +65 -0
  703. package/plugins/ragents.reference/run-scripts/shared-actor-list/tests/helpers.ts +26 -0
  704. package/plugins/ragents.reference/run-scripts/shared-actor-list/tests/program.test.ts +42 -0
  705. package/plugins/ragents.reference/run-scripts/word-game/RUN.md +25 -0
  706. package/plugins/ragents.reference/run-scripts/word-game/package.json +11 -0
  707. package/plugins/ragents.reference/run-scripts/word-game/src/client.tsx +27 -0
  708. package/plugins/ragents.reference/run-scripts/word-game/src/contract.ts +23 -0
  709. package/plugins/ragents.reference/run-scripts/word-game/src/server.ts +106 -0
  710. package/plugins/ragents.reference/run-scripts/word-game/src/state.ts +22 -0
  711. package/plugins/ragents.reference/run-scripts/word-game/src/view.tsx +54 -0
  712. package/plugins/ragents.reference/run-scripts/word-game/tests/program.test.ts +253 -0
  713. package/plugins/ragents.reference/server/index.ts +12 -0
  714. package/plugins/ragents.reference/skills/100-shared-actor-list/SKILL.md +12 -0
  715. package/plugins/ragents.reference/skills/110-all-card-slots/SKILL.md +12 -0
  716. package/plugins/ragents.reference/skills/120-canvas-conversation-circle/SKILL.md +12 -0
  717. package/plugins/ragents.reference/skills/130-canvas-pipeline-with-approval/SKILL.md +12 -0
  718. package/plugins/ragents.reference/skills/140-canvas-team-tree-and-topic-grid/SKILL.md +12 -0
  719. package/plugins/ragents.reference/skills/150-editorial-workbench/SKILL.md +12 -0
  720. package/plugins/ragents.reference/skills/160-learning-companion/SKILL.md +12 -0
  721. package/plugins/ragents.reference/skills/170-photo-collection/SKILL.md +12 -0
  722. package/plugins/ragents.reference/skills/180-decision-workbench/SKILL.md +12 -0
  723. package/plugins/ragents.reference/skills/190-review-queue/SKILL.md +12 -0
  724. package/plugins/ragents.reference/skills/20-circle-of-four/SKILL.md +12 -0
  725. package/plugins/ragents.reference/skills/200-typescript-diagnostics/SKILL.md +12 -0
  726. package/plugins/ragents.reference/skills/210-moderator-handover/SKILL.md +12 -0
  727. package/plugins/ragents.reference/skills/220-actor-approval-list/SKILL.md +12 -0
  728. package/plugins/ragents.reference/skills/230-shared-state-views/SKILL.md +12 -0
  729. package/plugins/ragents.reference/skills/240-live-result-list/SKILL.md +12 -0
  730. package/plugins/ragents.reference/skills/250-balcony-wizard/SKILL.md +12 -0
  731. package/plugins/ragents.reference/skills/30-llm-without-runtime-knowledge/SKILL.md +12 -0
  732. package/plugins/ragents.reference/skills/35-actor-input-fifo/SKILL.md +12 -0
  733. package/plugins/ragents.reference/skills/40-subscription-matrix/SKILL.md +12 -0
  734. package/plugins/ragents.reference/skills/50-subscription-removal/SKILL.md +12 -0
  735. package/plugins/ragents.reference/skills/60-stop-in-the-circle/SKILL.md +12 -0
  736. package/plugins/ragents.reference/skills/65-artifact-least-privilege/SKILL.md +12 -0
  737. package/plugins/ragents.reference/skills/70-headless-counter/SKILL.md +12 -0
  738. package/plugins/ragents.reference/skills/75-lsp-demo/SKILL.md +12 -0
  739. package/plugins/ragents.reference/skills/80-actor-text-analysis/SKILL.md +12 -0
  740. package/plugins/ragents.reference/skills/90-actor-notes/SKILL.md +12 -0
  741. package/plugins/ragents.reference/skills/95-hello-world/SKILL.md +12 -0
  742. package/plugins/ragents.reference/skills/decision-brief/SKILL.md +33 -0
  743. package/plugins/ragents.reference/skills/learning-sprint/SKILL.md +33 -0
  744. package/plugins/ragents.reference/walkthroughs.ts +219 -0
  745. package/plugins/ragents.reference/web/StartGuides.tsx +89 -0
  746. package/plugins/ragents.reference/web/index.tsx +10 -0
  747. package/plugins/ragents.todo/contract.ts +60 -0
  748. package/plugins/ragents.todo/server/index.ts +10 -0
  749. package/plugins/ragents.todo/server/todo-tool.ts +70 -0
  750. package/plugins/ragents.todo/server/tool-contributor.ts +9 -0
  751. package/plugins/ragents.todo/web/TodoSection.tsx +47 -0
  752. package/plugins/ragents.todo/web/index.ts +12 -0
  753. package/plugins/ragents.transcript/server/index.ts +20 -0
  754. package/plugins/ragents.transcript/server/transcript.ts +78 -0
  755. package/plugins/ragents.watch/contract.ts +48 -0
  756. package/plugins/ragents.watch/server/condition.ts +56 -0
  757. package/plugins/ragents.watch/server/contract.ts +4 -0
  758. package/plugins/ragents.watch/server/functions.ts +62 -0
  759. package/plugins/ragents.watch/server/index.ts +39 -0
  760. package/plugins/ragents.watch/server/observation.ts +69 -0
  761. package/plugins/ragents.watch/server/service.ts +294 -0
  762. package/plugins/ragents.workspace/client/transport.ts +13 -0
  763. package/plugins/ragents.workspace/client/workspace-client.ts +247 -0
  764. package/plugins/ragents.workspace/contract.ts +182 -0
  765. package/plugins/ragents.workspace/prompt.hbs +14 -0
  766. package/plugins/ragents.workspace/server/binding.ts +92 -0
  767. package/plugins/ragents.workspace/server/browse-route.ts +134 -0
  768. package/plugins/ragents.workspace/server/clients.ts +161 -0
  769. package/plugins/ragents.workspace/server/index.ts +91 -0
  770. package/plugins/ragents.workspace/server/runtime.ts +170 -0
  771. package/plugins/ragents.workspace/web/FileBrowser.tsx +271 -0
  772. package/plugins/ragents.workspace/web/WorkspaceBinding.tsx +216 -0
  773. package/plugins/ragents.workspace/web/api.ts +8 -0
  774. package/plugins/ragents.workspace/web/file-icons.tsx +94 -0
  775. package/plugins/ragents.workspace/web/index.tsx +37 -0
  776. package/ragents.config.core.ts +65 -0
  777. package/ragents.config.developer.ts +46 -0
  778. package/scripts/agent/agent-cli.ts +461 -0
  779. package/scripts/agent/journal.ts +125 -0
  780. package/scripts/package/build-package.ts +249 -0
  781. package/scripts/package/host-links.d.mts +1 -0
  782. package/scripts/package/host-links.mjs +39 -0
  783. package/scripts/package/publish-package.ts +129 -0
  784. package/scripts/package/ragents.mjs +59 -0
  785. package/scripts/provision/run-provision.ts +72 -0
  786. package/scripts/remote/connect.ts +265 -0
  787. package/scripts/remote/start.ts +91 -0
  788. package/scripts/workspace-client/run-workspace-client.ts +112 -0
@@ -0,0 +1,3357 @@
1
+ /**
2
+ * AgentSession - Core abstraction for agent lifecycle and session management.
3
+ *
4
+ * This class is shared between all run modes (interactive, print, rpc).
5
+ * It encapsulates:
6
+ * - Agent state access
7
+ * - Event subscription with automatic session persistence
8
+ * - Model and thinking level management
9
+ * - Compaction (manual and auto)
10
+ * - Bash execution
11
+ * - Session switching and branching
12
+ *
13
+ * Modes use this class and add their own I/O layer on top.
14
+ */
15
+
16
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
17
+ import { basename, dirname } from "node:path";
18
+ import type {
19
+ Agent,
20
+ AgentEvent,
21
+ AgentMessage,
22
+ AgentState,
23
+ AgentTool,
24
+ AgentToolCall,
25
+ AgentToolResult,
26
+ PrepareNextTurnContext,
27
+ ThinkingLevel,
28
+ } from "@aicontainer/agent-core";
29
+ import type {
30
+ AssistantMessage,
31
+ AuthResult,
32
+ ImageContent,
33
+ UserAttachment,
34
+ UserContent,
35
+ Message,
36
+ Model,
37
+ ProviderHeaders,
38
+ TextContent,
39
+ } from "@aicontainer/ai";
40
+ import {
41
+ clampThinkingLevel,
42
+ cleanupSessionResources,
43
+ getSupportedThinkingLevels,
44
+ isContextOverflow,
45
+ isRetryableAssistantError,
46
+ modelsAreEqual,
47
+ resetApiProviders,
48
+ streamSimple,
49
+ } from "@aicontainer/ai";
50
+ import { stripFrontmatter } from "../utils/frontmatter.ts";
51
+ import { resolvePath } from "../utils/paths.ts";
52
+ import { sleep } from "../utils/sleep.ts";
53
+ import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.ts";
54
+ import { type BashResult, executeBashWithOperations } from "./bash-executor.ts";
55
+ import {
56
+ type CompactionResult,
57
+ calculateContextTokens,
58
+ collectEntriesForBranchSummary,
59
+ compact,
60
+ estimateContextTokens,
61
+ estimateTokens,
62
+ generateBranchSummary,
63
+ prepareCompaction,
64
+ shouldCompact,
65
+ } from "./compaction/index.ts";
66
+ import { DEFAULT_THINKING_LEVEL } from "./defaults.ts";
67
+ import {
68
+ type ContextUsage,
69
+ type ExtensionCommandContextActions,
70
+ type ExtensionErrorListener,
71
+ type ExtensionMode,
72
+ ExtensionRunner,
73
+ type ExtensionUIContext,
74
+ type InputSource,
75
+ type MessageEndEvent,
76
+ type MessageStartEvent,
77
+ type MessageUpdateEvent,
78
+ type ReplacedSessionContext,
79
+ type SessionBeforeCompactResult,
80
+ type SessionBeforeTreeResult,
81
+ type SessionStartEvent,
82
+ type ShutdownHandler,
83
+ type ToolDefinition,
84
+ type ToolExecutionEndEvent,
85
+ type ToolExecutionStartEvent,
86
+ type ToolExecutionUpdateEvent,
87
+ type ToolInfo,
88
+ type TreePreparation,
89
+ type TurnEndEvent,
90
+ type TurnStartEvent,
91
+ wrapRegisteredTools,
92
+ } from "./extensions/index.ts";
93
+ import { beginSessionShutdownEvent } from "./extensions/runner.ts";
94
+ import type { BashExecutionMessage, CustomMessage } from "./messages.ts";
95
+ import { ModelRegistry } from "./model-registry.ts";
96
+ import type { ModelRuntime } from "./model-runtime.ts";
97
+ import { expandPromptTemplate, type PromptTemplate } from "./prompt-templates.ts";
98
+ import type { ResourceExtensionPaths, ResourceLoader } from "./resource-loader.ts";
99
+ import type { BranchSummaryEntry, CompactionEntry, SessionEntry, SessionManager } from "./session-manager.ts";
100
+ import { CURRENT_SESSION_VERSION, getLatestCompactionEntry, type SessionHeader } from "./session-manager.ts";
101
+ import type { SettingsManager } from "./settings-manager.ts";
102
+ import type { SlashCommandInfo } from "./slash-commands.ts";
103
+ import { createSyntheticSourceInfo, type SourceInfo } from "./source-info.ts";
104
+ import { type BuildSystemPromptOptions, buildSystemPrompt } from "./system-prompt.ts";
105
+ import { type BashOperations, createLocalBashOperations } from "./tools/bash.ts";
106
+ import { createAllToolDefinitions } from "./tools/index.ts";
107
+ import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.ts";
108
+
109
+ // ============================================================================
110
+ // Skill Block Parsing
111
+ // ============================================================================
112
+
113
+ /** Parsed skill block from a user message */
114
+ export interface ParsedSkillBlock {
115
+ name: string;
116
+ location: string;
117
+ content: string;
118
+ userMessage: string | undefined;
119
+ }
120
+
121
+ /**
122
+ * Parse a skill block from message text.
123
+ * Returns null if the text doesn't contain a skill block.
124
+ */
125
+ export function parseSkillBlock(text: string): ParsedSkillBlock | null {
126
+ const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
127
+ if (!match) return null;
128
+ return {
129
+ name: match[1],
130
+ location: match[2],
131
+ content: match[3],
132
+ userMessage: match[4]?.trim() || undefined,
133
+ };
134
+ }
135
+
136
+ /** Session-specific events that extend the core AgentEvent */
137
+ export type AgentSessionEvent =
138
+ | Exclude<AgentEvent, { type: "agent_end" }>
139
+ | {
140
+ type: "agent_end";
141
+ messages: AgentMessage[];
142
+ willRetry: boolean;
143
+ }
144
+ | { type: "agent_settled" }
145
+ | {
146
+ type: "queue_update";
147
+ steering: readonly string[];
148
+ followUp: readonly string[];
149
+ }
150
+ | { type: "compaction_start"; reason: "manual" | "threshold" | "overflow" }
151
+ | { type: "entry_appended"; entry: SessionEntry }
152
+ | { type: "session_info_changed"; name: string | undefined }
153
+ | { type: "thinking_level_changed"; level: ThinkingLevel }
154
+ | {
155
+ type: "compaction_end";
156
+ reason: "manual" | "threshold" | "overflow";
157
+ result: CompactionResult | undefined;
158
+ aborted: boolean;
159
+ willRetry: boolean;
160
+ errorMessage?: string;
161
+ }
162
+ | { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
163
+ | { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string };
164
+
165
+ /** Listener function for agent session events */
166
+ export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
167
+
168
+ // ============================================================================
169
+ // Types
170
+ // ============================================================================
171
+
172
+ function withoutDeletedHeaders(headers: ProviderHeaders | undefined): Record<string, string> | undefined {
173
+ return headers
174
+ ? Object.fromEntries(Object.entries(headers).filter((entry): entry is [string, string] => entry[1] !== null))
175
+ : undefined;
176
+ }
177
+
178
+ export interface AgentSessionConfig {
179
+ agent: Agent;
180
+ sessionManager: SessionManager;
181
+ settingsManager: SettingsManager;
182
+ cwd: string;
183
+ /** Models to cycle through with Ctrl+P (from --models flag) */
184
+ scopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
185
+ /** Resource loader for extensions, skills, prompts, themes, context files, and system prompt */
186
+ resourceLoader: ResourceLoader;
187
+ /** SDK custom tools registered outside extensions */
188
+ customTools?: ToolDefinition[];
189
+ /** Canonical model/auth runtime used by coding-agent internals. */
190
+ modelRuntime: ModelRuntime;
191
+ /** Initial active built-in tool names. Default: [read, bash, edit, write] */
192
+ initialActiveToolNames?: string[];
193
+ /** Optional allowlist of tool names. When provided, only these tool names are exposed. */
194
+ allowedToolNames?: string[];
195
+ /** Optional denylist of tool names. When provided, these tool names are not exposed. */
196
+ excludedToolNames?: string[];
197
+ /**
198
+ * Override base tools (useful for custom runtimes).
199
+ *
200
+ * These are synthesized into minimal ToolDefinitions internally so AgentSession can keep
201
+ * a definition-first registry even when callers provide plain AgentTool instances.
202
+ */
203
+ baseToolsOverride?: Record<string, AgentTool>;
204
+ /** Mutable ref used by Agent to access the current ExtensionRunner */
205
+ extensionRunnerRef?: { current?: ExtensionRunner };
206
+ /** Session start event metadata emitted when extensions bind to this runtime. */
207
+ sessionStartEvent?: SessionStartEvent;
208
+ }
209
+
210
+ export interface ExtensionBindings {
211
+ uiContext?: ExtensionUIContext;
212
+ mode?: ExtensionMode;
213
+ commandContextActions?: ExtensionCommandContextActions;
214
+ abortHandler?: () => void;
215
+ shutdownHandler?: ShutdownHandler;
216
+ onError?: ExtensionErrorListener;
217
+ }
218
+
219
+ /** Options for AgentSession.prompt() */
220
+ export interface PromptOptions {
221
+ /** Whether to expand file-based prompt templates (default: true) */
222
+ expandPromptTemplates?: boolean;
223
+ /** Image attachments */
224
+ images?: ImageContent[];
225
+ attachments?: UserAttachment[];
226
+ /** When streaming, how to queue the message: "steer" (interrupt) or "followUp" (wait). Required if streaming. */
227
+ streamingBehavior?: "steer" | "followUp";
228
+ /** Source of input for extension input event handlers. Defaults to "interactive". */
229
+ source?: InputSource;
230
+ /** Internal hook used by RPC mode to observe prompt preflight acceptance or rejection. */
231
+ preflightResult?: (success: boolean) => void;
232
+ }
233
+
234
+ /** Result from cycleModel() */
235
+ export interface ModelCycleResult {
236
+ model: Model<any>;
237
+ thinkingLevel: ThinkingLevel;
238
+ /** Whether cycling through scoped models (--models flag) or all available */
239
+ isScoped: boolean;
240
+ }
241
+
242
+ /** Session statistics for /session command */
243
+ export interface SessionStats {
244
+ sessionFile: string | undefined;
245
+ sessionId: string;
246
+ userMessages: number;
247
+ assistantMessages: number;
248
+ toolCalls: number;
249
+ toolResults: number;
250
+ totalMessages: number;
251
+ tokens: {
252
+ input: number;
253
+ output: number;
254
+ cacheRead: number;
255
+ cacheWrite: number;
256
+ total: number;
257
+ };
258
+ cost: number;
259
+ contextUsage?: ContextUsage;
260
+ }
261
+
262
+ interface ToolDefinitionEntry {
263
+ definition: ToolDefinition;
264
+ sourceInfo: SourceInfo;
265
+ }
266
+
267
+ function estimateMessagesTokens(messages: AgentMessage[]): number {
268
+ let tokens = 0;
269
+ for (const message of messages) {
270
+ tokens += estimateTokens(message);
271
+ }
272
+ return tokens;
273
+ }
274
+
275
+ // ============================================================================
276
+ // Constants
277
+ // ============================================================================
278
+
279
+ /** Standard thinking levels */
280
+ const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high"];
281
+
282
+ /** Cap for backgrounded tool results delivered as steering text. */
283
+ const BACKGROUND_RESULT_MAX_CHARS = 30_000;
284
+
285
+ // ============================================================================
286
+ // AgentSession Class
287
+ // ============================================================================
288
+
289
+ export class AgentSession {
290
+ readonly agent: Agent;
291
+ readonly sessionManager: SessionManager;
292
+ readonly settingsManager: SettingsManager;
293
+
294
+ private _scopedModels: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
295
+
296
+ // Event subscription state
297
+ private _unsubscribeAgent?: () => void;
298
+ private _eventListeners: AgentSessionEventListener[] = [];
299
+ private _isAgentRunActive = false;
300
+ private _disposed = false;
301
+ private _idleWaitPromise: Promise<void> | undefined;
302
+ private _resolveIdleWait: (() => void) | undefined;
303
+ private readonly _extensionSettlements = new Set<Promise<void>>();
304
+
305
+ /** Tracks pending steering messages for UI display. Removed when delivered. */
306
+ private _steeringMessages: string[] = [];
307
+ /** Tracks pending follow-up messages for UI display. Removed when delivered. */
308
+ private _followUpMessages: string[] = [];
309
+ /** Messages queued to be included with the next user prompt as context ("asides"). */
310
+ private _pendingNextTurnMessages: CustomMessage[] = [];
311
+
312
+ // Compaction state
313
+ private _compactionAbortController: AbortController | undefined = undefined;
314
+ private _autoCompactionAbortController: AbortController | undefined = undefined;
315
+ private _overflowRecoveryAttempted = false;
316
+
317
+ // Branch summarization state
318
+ private _branchSummaryAbortController: AbortController | undefined = undefined;
319
+
320
+ // Retry state
321
+ private _retryAbortController: AbortController | undefined = undefined;
322
+ private _retryAttempt = 0;
323
+
324
+ // Bash execution state
325
+ private _bashAbortController: AbortController | undefined = undefined;
326
+ private _pendingBashMessages: BashExecutionMessage[] = [];
327
+
328
+ // Extension system
329
+ private _extensionRunner!: ExtensionRunner;
330
+ private _turnIndex = 0;
331
+
332
+ private _resourceLoader: ResourceLoader;
333
+ private _customTools: ToolDefinition[];
334
+ private _baseToolDefinitions: Map<string, ToolDefinition> = new Map();
335
+ private _cwd: string;
336
+ private _extensionRunnerRef?: { current?: ExtensionRunner };
337
+ private _initialActiveToolNames?: string[];
338
+ private _allowedToolNames?: Set<string>;
339
+ private _excludedToolNames?: Set<string>;
340
+ private _baseToolsOverride?: Record<string, AgentTool>;
341
+ private _sessionStartEvent: SessionStartEvent;
342
+ private _extensionUIContext?: ExtensionUIContext;
343
+ private _extensionMode: ExtensionMode = "print";
344
+ private _extensionCommandContextActions?: ExtensionCommandContextActions;
345
+ private _extensionAbortHandler?: () => void;
346
+ private _extensionShutdownHandler?: ShutdownHandler;
347
+ private _extensionErrorListener?: ExtensionErrorListener;
348
+ private _extensionErrorUnsubscriber?: () => void;
349
+
350
+ private _modelRuntime: ModelRuntime;
351
+
352
+ // Tool registry for extension getTools/setTools
353
+ private _toolRegistry: Map<string, AgentTool> = new Map();
354
+ private _toolDefinitions: Map<string, ToolDefinitionEntry> = new Map();
355
+ private _toolPromptSnippets: Map<string, string> = new Map();
356
+ private _toolPromptGuidelines: Map<string, string[]> = new Map();
357
+
358
+ // Base system prompt (without extension appends) - used to apply fresh appends each turn
359
+ private _baseSystemPrompt = "";
360
+ private _baseSystemPromptOptions!: BuildSystemPromptOptions;
361
+ private _systemPromptOverride?: string;
362
+
363
+ constructor(config: AgentSessionConfig) {
364
+ this.agent = config.agent;
365
+ this.sessionManager = config.sessionManager;
366
+ this.settingsManager = config.settingsManager;
367
+ this._scopedModels = config.scopedModels ?? [];
368
+ this._resourceLoader = config.resourceLoader;
369
+ this._customTools = config.customTools ?? [];
370
+ this._cwd = config.cwd;
371
+ this._modelRuntime = config.modelRuntime;
372
+ this._extensionRunnerRef = config.extensionRunnerRef;
373
+ this._initialActiveToolNames = config.initialActiveToolNames;
374
+ this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
375
+ this._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;
376
+ this._baseToolsOverride = config.baseToolsOverride;
377
+ this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
378
+
379
+ // Always subscribe to agent events for internal handling
380
+ // (session persistence, extensions, auto-compaction, retry logic)
381
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
382
+ this._installAgentToolHooks();
383
+ this._installAgentNextTurnRefresh();
384
+ this.agent.onBackgroundToolResult = (toolCall, result, isError) =>
385
+ this._handleBackgroundToolResult(toolCall, result, isError);
386
+
387
+ this._buildRuntime({
388
+ activeToolNames: this._initialActiveToolNames,
389
+ includeAllExtensionTools: true,
390
+ });
391
+ }
392
+
393
+ get modelRuntime(): ModelRuntime {
394
+ return this._modelRuntime;
395
+ }
396
+
397
+ private async _getRequiredRequestAuth(model: Model<any>): Promise<{
398
+ apiKey: string;
399
+ headers?: Record<string, string>;
400
+ env?: Record<string, string>;
401
+ }> {
402
+ let result: AuthResult | undefined;
403
+ try {
404
+ result = await this._modelRuntime.getAuth(model);
405
+ } catch (error) {
406
+ const cause = error instanceof Error ? error.cause : undefined;
407
+ if (cause instanceof Error && cause.message === "authHeader requires a resolved API key") {
408
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
409
+ }
410
+ throw error;
411
+ }
412
+ if (result?.auth.apiKey) {
413
+ return {
414
+ apiKey: result.auth.apiKey,
415
+ headers: withoutDeletedHeaders(result.auth.headers),
416
+ env: result.env,
417
+ };
418
+ }
419
+
420
+ const isOAuth = this._modelRuntime.isUsingOAuth(model.provider);
421
+ if (isOAuth) {
422
+ throw new Error(
423
+ `Authentication failed for "${model.provider}". ` +
424
+ `Credentials may have expired or network is unavailable. ` +
425
+ `Run '/login ${model.provider}' to re-authenticate.`,
426
+ );
427
+ }
428
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
429
+ }
430
+
431
+ private async _getSummarizationRequestAuth(model: Model<any>): Promise<{
432
+ apiKey?: string;
433
+ headers?: Record<string, string>;
434
+ env?: Record<string, string>;
435
+ }> {
436
+ if (this.agent.streamFn === streamSimple) {
437
+ return this._getRequiredRequestAuth(model);
438
+ }
439
+
440
+ try {
441
+ const result = await this._modelRuntime.getAuth(model);
442
+ return result
443
+ ? { apiKey: result.auth.apiKey, headers: withoutDeletedHeaders(result.auth.headers), env: result.env }
444
+ : {};
445
+ } catch {
446
+ return {};
447
+ }
448
+ }
449
+
450
+ /**
451
+ * Install tool hooks once on the Agent instance.
452
+ *
453
+ * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the
454
+ * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt
455
+ * registered tool execution to the extension context. Tool call and tool result interception now
456
+ * happens here instead of in wrappers.
457
+ */
458
+ private _installAgentToolHooks(): void {
459
+ this.agent.beforeToolCall = async ({ toolCall, args }) => {
460
+ const runner = this._extensionRunner;
461
+ if (!runner.hasHandlers("tool_call")) {
462
+ return undefined;
463
+ }
464
+
465
+ try {
466
+ return await runner.emitToolCall({
467
+ type: "tool_call",
468
+ toolName: toolCall.name,
469
+ toolCallId: toolCall.id,
470
+ input: args as Record<string, unknown>,
471
+ });
472
+ } catch (err) {
473
+ if (err instanceof Error) {
474
+ throw err;
475
+ }
476
+ throw new Error(`Extension failed, blocking execution: ${String(err)}`);
477
+ }
478
+ };
479
+
480
+ this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
481
+ const runner = this._extensionRunner;
482
+ if (!runner.hasHandlers("tool_result")) {
483
+ return undefined;
484
+ }
485
+
486
+ const hookResult = await runner.emitToolResult({
487
+ type: "tool_result",
488
+ toolName: toolCall.name,
489
+ toolCallId: toolCall.id,
490
+ input: args as Record<string, unknown>,
491
+ content: result.content,
492
+ details: result.details,
493
+ isError,
494
+ });
495
+
496
+ if (!hookResult) {
497
+ return undefined;
498
+ }
499
+
500
+ return {
501
+ content: hookResult.content,
502
+ details: hookResult.details,
503
+ isError: hookResult.isError ?? isError,
504
+ };
505
+ };
506
+ }
507
+
508
+ private _installAgentNextTurnRefresh(): void {
509
+ const previousPrepareNextTurnWithContext =
510
+ this.agent.prepareNextTurnWithContext ??
511
+ (this.agent.prepareNextTurn
512
+ ? async (_turn: PrepareNextTurnContext, signal?: AbortSignal) => await this.agent.prepareNextTurn?.(signal)
513
+ : undefined);
514
+ this.agent.prepareNextTurnWithContext = async (turn, signal) => {
515
+ const previousSnapshot = await previousPrepareNextTurnWithContext?.(turn, signal);
516
+ const previousContext = previousSnapshot?.context ?? turn.context;
517
+
518
+ return {
519
+ ...previousSnapshot,
520
+ context: {
521
+ ...previousContext,
522
+ systemPrompt: this._systemPromptOverride ?? this._baseSystemPrompt,
523
+ tools: this.agent.state.tools.slice(),
524
+ },
525
+ model: this.agent.state.model,
526
+ thinkingLevel: this.agent.state.thinkingLevel,
527
+ };
528
+ };
529
+ }
530
+
531
+ // =========================================================================
532
+ // Event Subscription
533
+ // =========================================================================
534
+
535
+ /** Emit an event to all listeners */
536
+ private _emit(event: AgentSessionEvent): void {
537
+ for (const l of this._eventListeners) {
538
+ l(event);
539
+ }
540
+ }
541
+
542
+ private _emitQueueUpdate(): void {
543
+ this._emit({
544
+ type: "queue_update",
545
+ steering: [...this._steeringMessages],
546
+ followUp: [...this._followUpMessages],
547
+ });
548
+ }
549
+
550
+ private _getIdleWaitPromise(): Promise<void> {
551
+ if (!this._idleWaitPromise) {
552
+ this._idleWaitPromise = new Promise((resolve) => {
553
+ this._resolveIdleWait = resolve;
554
+ });
555
+ }
556
+ return this._idleWaitPromise;
557
+ }
558
+
559
+ private _resolveIdleWaitIfIdle(): void {
560
+ if (this._isAgentRunActive || !this._resolveIdleWait) {
561
+ return;
562
+ }
563
+ const resolve = this._resolveIdleWait;
564
+ this._idleWaitPromise = undefined;
565
+ this._resolveIdleWait = undefined;
566
+ resolve();
567
+ }
568
+
569
+ private async _emitAgentSettled(): Promise<void> {
570
+ this._isAgentRunActive = false;
571
+ try {
572
+ await this._extensionRunner.emit({ type: "agent_settled" });
573
+ this._emit({ type: "agent_settled" });
574
+ } finally {
575
+ this._resolveIdleWaitIfIdle();
576
+ }
577
+ }
578
+
579
+ // Track last assistant message for auto-compaction check
580
+ private _lastAssistantMessage: AssistantMessage | undefined = undefined;
581
+
582
+ /** Internal handler for agent events - shared by subscribe and reconnect */
583
+ private _handleAgentEvent = async (event: AgentEvent): Promise<void> => {
584
+ // When a user message starts, check if it's from either queue and remove it BEFORE emitting
585
+ // This ensures the UI sees the updated queue state
586
+ if (event.type === "message_start" && event.message.role === "user") {
587
+ this._overflowRecoveryAttempted = false;
588
+ const messageText = this._getUserMessageText(event.message);
589
+ if (messageText) {
590
+ // Check steering queue first
591
+ const steeringIndex = this._steeringMessages.indexOf(messageText);
592
+ if (steeringIndex !== -1) {
593
+ this._steeringMessages.splice(steeringIndex, 1);
594
+ this._emitQueueUpdate();
595
+ } else {
596
+ // Check follow-up queue
597
+ const followUpIndex = this._followUpMessages.indexOf(messageText);
598
+ if (followUpIndex !== -1) {
599
+ this._followUpMessages.splice(followUpIndex, 1);
600
+ this._emitQueueUpdate();
601
+ }
602
+ }
603
+ }
604
+ }
605
+
606
+ // Emit to extensions first
607
+ await this._emitExtensionEvent(event);
608
+
609
+ // Notify all listeners
610
+ this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
611
+
612
+ // Handle session persistence
613
+ if (event.type === "message_end") {
614
+ // Check if this is a custom message from extensions
615
+ if (event.message.role === "custom") {
616
+ // Persist as CustomMessageEntry
617
+ this.sessionManager.appendCustomMessageEntry(
618
+ event.message.customType,
619
+ event.message.content,
620
+ event.message.display,
621
+ event.message.details,
622
+ );
623
+ } else if (
624
+ event.message.role === "user" ||
625
+ event.message.role === "assistant" ||
626
+ event.message.role === "toolResult"
627
+ ) {
628
+ // Regular LLM message - persist as SessionMessageEntry
629
+ this.sessionManager.appendMessage(event.message);
630
+ }
631
+ // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
632
+
633
+ // Track assistant message for auto-compaction (checked on agent_end)
634
+ if (event.message.role === "assistant") {
635
+ this._lastAssistantMessage = event.message;
636
+
637
+ const assistantMsg = event.message as AssistantMessage;
638
+ if (assistantMsg.stopReason !== "error") {
639
+ this._overflowRecoveryAttempted = false;
640
+ }
641
+
642
+ // Reset retry counter immediately on successful assistant response
643
+ // This prevents accumulation across multiple LLM calls within a turn
644
+ if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
645
+ this._emit({
646
+ type: "auto_retry_end",
647
+ success: true,
648
+ attempt: this._retryAttempt,
649
+ });
650
+ this._retryAttempt = 0;
651
+ }
652
+ }
653
+ }
654
+ };
655
+
656
+ private _willRetryAfterAgentEnd(event: Extract<AgentEvent, { type: "agent_end" }>): boolean {
657
+ const settings = this.settingsManager.getRetrySettings();
658
+ if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
659
+ return false;
660
+ }
661
+
662
+ for (let i = event.messages.length - 1; i >= 0; i--) {
663
+ const message = event.messages[i];
664
+ if (message.role === "assistant") {
665
+ return this._isRetryableError(message as AssistantMessage);
666
+ }
667
+ }
668
+ return false;
669
+ }
670
+
671
+ /** Extract text content from a message */
672
+ private _getUserMessageText(message: Message): string {
673
+ if (message.role !== "user") return "";
674
+ const content = message.content;
675
+ if (typeof content === "string") return content;
676
+ const textBlocks = content.filter((c) => c.type === "text");
677
+ return textBlocks.map((c) => (c as TextContent).text).join("");
678
+ }
679
+
680
+ /** Find the last assistant message in agent state (including aborted ones) */
681
+ private _findLastAssistantMessage(): AssistantMessage | undefined {
682
+ const messages = this.agent.state.messages;
683
+ for (let i = messages.length - 1; i >= 0; i--) {
684
+ const msg = messages[i];
685
+ if (msg.role === "assistant") {
686
+ return msg as AssistantMessage;
687
+ }
688
+ }
689
+ return undefined;
690
+ }
691
+
692
+ private _replaceMessageInPlace(target: AgentMessage, replacement: AgentMessage): void {
693
+ // Agent-core stores the finalized message object in its state before emitting message_end.
694
+ // SessionManager persistence happens later in _handleAgentEvent() with event.message.
695
+ // Mutating this object in place keeps agent state, later turn/agent events, listeners,
696
+ // and the eventual SessionManager.appendMessage(event.message) persistence in sync.
697
+ if (target === replacement) {
698
+ return;
699
+ }
700
+
701
+ const targetRecord = target as unknown as Record<string, unknown>;
702
+ for (const key of Object.keys(targetRecord)) {
703
+ delete targetRecord[key];
704
+ }
705
+ Object.assign(targetRecord, replacement);
706
+ }
707
+
708
+ /** Emit extension events based on agent events */
709
+ private async _emitExtensionEvent(event: AgentEvent): Promise<void> {
710
+ if (event.type === "agent_start") {
711
+ this._turnIndex = 0;
712
+ await this._extensionRunner.emit({ type: "agent_start" });
713
+ } else if (event.type === "agent_end") {
714
+ await this._extensionRunner.emit({ type: "agent_end", messages: event.messages });
715
+ } else if (event.type === "turn_start") {
716
+ const extensionEvent: TurnStartEvent = {
717
+ type: "turn_start",
718
+ turnIndex: this._turnIndex,
719
+ timestamp: Date.now(),
720
+ };
721
+ await this._extensionRunner.emit(extensionEvent);
722
+ } else if (event.type === "turn_end") {
723
+ const extensionEvent: TurnEndEvent = {
724
+ type: "turn_end",
725
+ turnIndex: this._turnIndex,
726
+ message: event.message,
727
+ toolResults: event.toolResults,
728
+ };
729
+ await this._extensionRunner.emit(extensionEvent);
730
+ this._turnIndex++;
731
+ } else if (event.type === "message_start") {
732
+ const extensionEvent: MessageStartEvent = {
733
+ type: "message_start",
734
+ message: event.message,
735
+ };
736
+ await this._extensionRunner.emit(extensionEvent);
737
+ } else if (event.type === "message_update") {
738
+ const extensionEvent: MessageUpdateEvent = {
739
+ type: "message_update",
740
+ message: event.message,
741
+ assistantMessageEvent: event.assistantMessageEvent,
742
+ };
743
+ await this._extensionRunner.emit(extensionEvent);
744
+ } else if (event.type === "message_end") {
745
+ const extensionEvent: MessageEndEvent = {
746
+ type: "message_end",
747
+ message: event.message,
748
+ };
749
+ const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
750
+ if (replacement) {
751
+ // Untyped extension handlers can return messages with null/missing content;
752
+ // normalize so it never enters agent state or session history.
753
+ const normalized =
754
+ (replacement.role === "user" ||
755
+ replacement.role === "assistant" ||
756
+ replacement.role === "toolResult" ||
757
+ replacement.role === "custom") &&
758
+ replacement.content == null
759
+ ? ({ ...replacement, content: [] } as AgentMessage)
760
+ : replacement;
761
+ this._replaceMessageInPlace(event.message, normalized);
762
+ }
763
+ } else if (event.type === "tool_execution_start") {
764
+ const extensionEvent: ToolExecutionStartEvent = {
765
+ type: "tool_execution_start",
766
+ toolCallId: event.toolCallId,
767
+ toolName: event.toolName,
768
+ args: event.args,
769
+ };
770
+ await this._extensionRunner.emit(extensionEvent);
771
+ } else if (event.type === "tool_execution_update") {
772
+ const extensionEvent: ToolExecutionUpdateEvent = {
773
+ type: "tool_execution_update",
774
+ toolCallId: event.toolCallId,
775
+ toolName: event.toolName,
776
+ args: event.args,
777
+ partialResult: event.partialResult,
778
+ };
779
+ await this._extensionRunner.emit(extensionEvent);
780
+ } else if (event.type === "tool_execution_end") {
781
+ const extensionEvent: ToolExecutionEndEvent = {
782
+ type: "tool_execution_end",
783
+ toolCallId: event.toolCallId,
784
+ toolName: event.toolName,
785
+ result: event.result,
786
+ isError: event.isError,
787
+ };
788
+ await this._extensionRunner.emit(extensionEvent);
789
+ }
790
+ }
791
+
792
+ /**
793
+ * Subscribe to agent events.
794
+ * Session persistence is handled internally (saves messages on message_end).
795
+ * Multiple listeners can be added. Returns unsubscribe function for this listener.
796
+ */
797
+ subscribe(listener: AgentSessionEventListener): () => void {
798
+ this._eventListeners.push(listener);
799
+
800
+ // Return unsubscribe function for this specific listener
801
+ return () => {
802
+ const index = this._eventListeners.indexOf(listener);
803
+ if (index !== -1) {
804
+ this._eventListeners.splice(index, 1);
805
+ }
806
+ };
807
+ }
808
+
809
+ /**
810
+ * Temporarily disconnect from agent events.
811
+ * User listeners are preserved and will receive events again after resubscribe().
812
+ * Used internally during operations that need to pause event processing.
813
+ */
814
+ private _disconnectFromAgent(): void {
815
+ if (this._unsubscribeAgent) {
816
+ this._unsubscribeAgent();
817
+ this._unsubscribeAgent = undefined;
818
+ }
819
+ }
820
+
821
+ /**
822
+ * Reconnect to agent events after _disconnectFromAgent().
823
+ * Preserves all existing listeners.
824
+ */
825
+ private _reconnectToAgent(): void {
826
+ if (this._unsubscribeAgent) return; // Already connected
827
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
828
+ }
829
+
830
+ /**
831
+ * Remove all listeners and disconnect from agent.
832
+ * Call this when completely done with the session.
833
+ */
834
+ dispose(): void {
835
+ if (this._disposed) return;
836
+ this._disposed = true;
837
+
838
+ try {
839
+ this.abortRetry();
840
+ this.abortCompaction();
841
+ this.abortBranchSummary();
842
+ this.abortBash();
843
+ this.agent.abort();
844
+ } catch {
845
+ // Dispose must succeed even if an abort hook throws.
846
+ }
847
+
848
+ this._extensionRunner.invalidate(
849
+ "This extension ctx is stale after session replacement or reload. Do not use a captured extension or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().",
850
+ );
851
+ this._disconnectFromAgent();
852
+ this._eventListeners = [];
853
+ cleanupSessionResources(this.sessionId);
854
+ }
855
+
856
+ waitForSettlement(): Promise<void> {
857
+ const resourceSettlement = this._resourceLoader.waitForSettlement?.();
858
+ return Promise.allSettled([
859
+ ...this._extensionSettlements,
860
+ ...(resourceSettlement ? [resourceSettlement] : []),
861
+ ]).then(() => undefined);
862
+ }
863
+
864
+ private _trackExtensionSettlement(settlement: Promise<void>): void {
865
+ this._extensionSettlements.add(settlement);
866
+ void settlement.then(
867
+ () => this._extensionSettlements.delete(settlement),
868
+ () => this._extensionSettlements.delete(settlement),
869
+ );
870
+ }
871
+
872
+ // =========================================================================
873
+ // Read-only State Access
874
+ // =========================================================================
875
+
876
+ /** Full agent state */
877
+ get state(): AgentState {
878
+ return this.agent.state;
879
+ }
880
+
881
+ /** Current model (may be undefined if not yet selected) */
882
+ get model(): Model<any> | undefined {
883
+ return this.agent.state.model;
884
+ }
885
+
886
+ /** Current thinking level */
887
+ get thinkingLevel(): ThinkingLevel {
888
+ return this.agent.state.thinkingLevel;
889
+ }
890
+
891
+ /** Whether the session is currently processing an agent run or post-run continuation. */
892
+ get isStreaming(): boolean {
893
+ return this._isAgentRunActive;
894
+ }
895
+
896
+ /** Whether the session has no active agent run, retry, auto-compaction, or queued continuation. */
897
+ get isIdle(): boolean {
898
+ return !this._isAgentRunActive;
899
+ }
900
+
901
+ /** Current effective system prompt (includes any per-turn extension modifications) */
902
+ get systemPrompt(): string {
903
+ return this.agent.state.systemPrompt;
904
+ }
905
+
906
+ /** Replace the custom system prompt and rebuild the effective prompt for the next model call. */
907
+ setSystemPrompt(prompt: string): void {
908
+ this._resourceLoader.setSystemPrompt(prompt);
909
+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
910
+ this.agent.state.systemPrompt = this._systemPromptOverride ?? this._baseSystemPrompt;
911
+ }
912
+
913
+ /** Current retry attempt (0 if not retrying) */
914
+ get retryAttempt(): number {
915
+ return this._retryAttempt;
916
+ }
917
+
918
+ /**
919
+ * Get the names of currently active tools.
920
+ * Returns the names of tools currently set on the agent.
921
+ */
922
+ getActiveToolNames(): string[] {
923
+ return this.agent.state.tools.map((t) => t.name);
924
+ }
925
+
926
+ /**
927
+ * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
928
+ */
929
+ getAllTools(): ToolInfo[] {
930
+ return Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({
931
+ name: definition.name,
932
+ description: definition.description,
933
+ parameters: definition.parameters,
934
+ promptGuidelines: definition.promptGuidelines,
935
+ sourceInfo,
936
+ }));
937
+ }
938
+
939
+ getToolDefinition(name: string): ToolDefinition | undefined {
940
+ return this._toolDefinitions.get(name)?.definition;
941
+ }
942
+
943
+ /**
944
+ * Set active tools by name.
945
+ * Only tools in the registry can be enabled. Unknown tool names are ignored.
946
+ * Also rebuilds the system prompt to reflect the new tool set.
947
+ * Changes take effect on the next agent turn.
948
+ */
949
+ setActiveToolsByName(toolNames: string[]): void {
950
+ const tools: AgentTool[] = [];
951
+ const validToolNames: string[] = [];
952
+ for (const name of toolNames) {
953
+ const tool = this._toolRegistry.get(name);
954
+ if (tool) {
955
+ tools.push(tool);
956
+ validToolNames.push(name);
957
+ }
958
+ }
959
+ this.agent.state.tools = tools;
960
+
961
+ // Rebuild base system prompt with new tool set
962
+ this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
963
+ this.agent.state.systemPrompt = this._systemPromptOverride ?? this._baseSystemPrompt;
964
+ }
965
+
966
+ /** Whether compaction or branch summarization is currently running */
967
+ get isCompacting(): boolean {
968
+ return (
969
+ this._autoCompactionAbortController !== undefined ||
970
+ this._compactionAbortController !== undefined ||
971
+ this._branchSummaryAbortController !== undefined
972
+ );
973
+ }
974
+
975
+ /** All messages including custom types like BashExecutionMessage */
976
+ get messages(): AgentMessage[] {
977
+ return this.agent.state.messages;
978
+ }
979
+
980
+ /** Current steering mode */
981
+ get steeringMode(): "all" | "one-at-a-time" {
982
+ return this.agent.steeringMode;
983
+ }
984
+
985
+ /** Current follow-up mode */
986
+ get followUpMode(): "all" | "one-at-a-time" {
987
+ return this.agent.followUpMode;
988
+ }
989
+
990
+ /** Current session file path, or undefined if sessions are disabled */
991
+ get sessionFile(): string | undefined {
992
+ return this.sessionManager.getSessionFile();
993
+ }
994
+
995
+ /** Current session ID */
996
+ get sessionId(): string {
997
+ return this.sessionManager.getSessionId();
998
+ }
999
+
1000
+ /** Current session display name, if set */
1001
+ get sessionName(): string | undefined {
1002
+ return this.sessionManager.getSessionName();
1003
+ }
1004
+
1005
+ /** Scoped models for cycling (from --models flag) */
1006
+ get scopedModels(): ReadonlyArray<{ model: Model<any>; thinkingLevel?: ThinkingLevel }> {
1007
+ return this._scopedModels;
1008
+ }
1009
+
1010
+ /** Update scoped models for cycling */
1011
+ setScopedModels(scopedModels: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>): void {
1012
+ this._scopedModels = scopedModels;
1013
+ }
1014
+
1015
+ /** File-based prompt templates */
1016
+ get promptTemplates(): ReadonlyArray<PromptTemplate> {
1017
+ return this._resourceLoader.getPrompts().prompts;
1018
+ }
1019
+
1020
+ private _normalizePromptSnippet(text: string | undefined): string | undefined {
1021
+ if (!text) return undefined;
1022
+ const oneLine = text
1023
+ .replace(/[\r\n]+/g, " ")
1024
+ .replace(/\s+/g, " ")
1025
+ .trim();
1026
+ return oneLine.length > 0 ? oneLine : undefined;
1027
+ }
1028
+
1029
+ private _normalizePromptGuidelines(guidelines: string[] | undefined): string[] {
1030
+ if (!guidelines || guidelines.length === 0) {
1031
+ return [];
1032
+ }
1033
+
1034
+ const unique = new Set<string>();
1035
+ for (const guideline of guidelines) {
1036
+ const normalized = guideline.trim();
1037
+ if (normalized.length > 0) {
1038
+ unique.add(normalized);
1039
+ }
1040
+ }
1041
+ return Array.from(unique);
1042
+ }
1043
+
1044
+ private _rebuildSystemPrompt(toolNames: string[]): string {
1045
+ const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
1046
+ const toolSnippets: Record<string, string> = {};
1047
+ const promptGuidelines: string[] = [];
1048
+ for (const name of validToolNames) {
1049
+ const snippet = this._toolPromptSnippets.get(name);
1050
+ if (snippet) {
1051
+ toolSnippets[name] = snippet;
1052
+ }
1053
+
1054
+ const toolGuidelines = this._toolPromptGuidelines.get(name);
1055
+ if (toolGuidelines) {
1056
+ promptGuidelines.push(...toolGuidelines);
1057
+ }
1058
+ }
1059
+
1060
+ const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
1061
+ const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
1062
+ const appendSystemPrompt =
1063
+ loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
1064
+ const loadedSkills = this._resourceLoader.getSkills().skills;
1065
+ const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
1066
+
1067
+ this._baseSystemPromptOptions = {
1068
+ cwd: this._cwd,
1069
+ skills: loadedSkills,
1070
+ contextFiles: loadedContextFiles,
1071
+ customPrompt: loaderSystemPrompt,
1072
+ appendSystemPrompt,
1073
+ selectedTools: validToolNames,
1074
+ toolSnippets,
1075
+ promptGuidelines,
1076
+ };
1077
+ return buildSystemPrompt(this._baseSystemPromptOptions);
1078
+ }
1079
+
1080
+ // =========================================================================
1081
+ // Prompting
1082
+ // =========================================================================
1083
+
1084
+ private async _runAgentPrompt(messages: AgentMessage | AgentMessage[]): Promise<void> {
1085
+ this._isAgentRunActive = true;
1086
+ try {
1087
+ await this.agent.prompt(messages);
1088
+ while (await this._handlePostAgentRun()) {
1089
+ await this.agent.continue();
1090
+ }
1091
+ } finally {
1092
+ this._systemPromptOverride = undefined;
1093
+ this._flushPendingBashMessages();
1094
+ await this._emitAgentSettled();
1095
+ }
1096
+ }
1097
+
1098
+ private async _handlePostAgentRun(): Promise<boolean> {
1099
+ const msg = this._lastAssistantMessage;
1100
+ this._lastAssistantMessage = undefined;
1101
+ if (!msg) {
1102
+ return false;
1103
+ }
1104
+
1105
+ if (this._isRetryableError(msg) && (await this._prepareRetry(msg))) {
1106
+ return true;
1107
+ }
1108
+
1109
+ if (msg.stopReason === "error" && this._retryAttempt > 0) {
1110
+ this._emit({
1111
+ type: "auto_retry_end",
1112
+ success: false,
1113
+ attempt: this._retryAttempt,
1114
+ finalError: msg.errorMessage,
1115
+ });
1116
+ this._retryAttempt = 0;
1117
+ }
1118
+
1119
+ if (await this._checkCompaction(msg)) {
1120
+ return true;
1121
+ }
1122
+
1123
+ // The agent loop drains both queues before emitting agent_end. Any messages
1124
+ // here were queued by agent_end extension handlers and need a continuation.
1125
+ return this.agent.hasQueuedMessages();
1126
+ }
1127
+
1128
+ /**
1129
+ * Send a prompt to the agent.
1130
+ * - Handles extension commands (registered via agent.registerCommand) immediately, even during streaming
1131
+ * - Expands file-based prompt templates by default
1132
+ * - During streaming, queues via steer() or followUp() based on streamingBehavior option
1133
+ * - Validates model and API key before sending (when not streaming)
1134
+ * @throws Error if streaming and no streamingBehavior specified
1135
+ * @throws Error if no model selected or no API key available (when not streaming)
1136
+ */
1137
+ async prompt(text: string, options?: PromptOptions): Promise<void> {
1138
+ const expandPromptTemplates = options?.expandPromptTemplates ?? true;
1139
+ const preflightResult = options?.preflightResult;
1140
+ let messages: AgentMessage[] | undefined;
1141
+
1142
+ try {
1143
+ this._assertNotDisposed();
1144
+
1145
+ // Handle extension commands first (execute immediately, even during streaming)
1146
+ // Extension commands manage their own LLM interaction via agent.sendMessage()
1147
+ if (expandPromptTemplates && text.startsWith("/")) {
1148
+ const handled = await this._tryExecuteExtensionCommand(text);
1149
+ this._assertNotDisposed();
1150
+ if (handled) {
1151
+ // Extension command executed, no prompt to send
1152
+ preflightResult?.(true);
1153
+ return;
1154
+ }
1155
+ }
1156
+
1157
+ // Emit input event for extension interception (before skill/template expansion)
1158
+ let currentText = text;
1159
+ let currentImages = options?.images;
1160
+ let currentAttachments = options?.attachments;
1161
+ if (this._extensionRunner.hasHandlers("input")) {
1162
+ const inputResult = await this._extensionRunner.emitInput(
1163
+ currentText,
1164
+ currentImages,
1165
+ options?.source ?? "interactive",
1166
+ this.isStreaming ? options?.streamingBehavior : undefined,
1167
+ currentAttachments,
1168
+ );
1169
+ this._assertNotDisposed();
1170
+ if (inputResult.action === "handled") {
1171
+ preflightResult?.(true);
1172
+ return;
1173
+ }
1174
+ if (inputResult.action === "transform") {
1175
+ currentText = inputResult.text;
1176
+ currentImages = inputResult.images ?? currentImages;
1177
+ currentAttachments = inputResult.attachments ?? currentAttachments;
1178
+ }
1179
+ }
1180
+
1181
+ // Expand skill commands (/skill:name args) and prompt templates (/template args)
1182
+ let expandedText = currentText;
1183
+ if (expandPromptTemplates) {
1184
+ expandedText = this._expandSkillCommand(expandedText);
1185
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1186
+ }
1187
+
1188
+ // If streaming, queue via steer() or followUp() based on option
1189
+ if (this.isStreaming) {
1190
+ if (!options?.streamingBehavior) {
1191
+ throw new Error(
1192
+ "Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.",
1193
+ );
1194
+ }
1195
+ if (options.streamingBehavior === "followUp") {
1196
+ await this._queueFollowUp(expandedText, [...(currentImages ?? []), ...(currentAttachments ?? [])]);
1197
+ } else {
1198
+ await this._queueSteer(expandedText, [...(currentImages ?? []), ...(currentAttachments ?? [])]);
1199
+ }
1200
+ this._assertNotDisposed();
1201
+ preflightResult?.(true);
1202
+ return;
1203
+ }
1204
+
1205
+ // Flush any pending bash messages before the new prompt
1206
+ this._flushPendingBashMessages();
1207
+
1208
+ // Validate model
1209
+ if (!this.model) {
1210
+ throw new Error(formatNoModelSelectedMessage());
1211
+ }
1212
+
1213
+ const hasConfiguredAuth =
1214
+ this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
1215
+ (await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
1216
+ this._assertNotDisposed();
1217
+ if (!hasConfiguredAuth) {
1218
+ const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
1219
+ if (isOAuth) {
1220
+ throw new Error(
1221
+ `Authentication failed for "${this.model.provider}". ` +
1222
+ `Credentials may have expired or network is unavailable. ` +
1223
+ `Run '/login ${this.model.provider}' to re-authenticate.`,
1224
+ );
1225
+ }
1226
+ throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
1227
+ }
1228
+
1229
+ // Check if we need to compact before sending (catches aborted responses).
1230
+ // The user's new prompt is sent below, so do not call agent.continue() here.
1231
+ const lastAssistant = this._findLastAssistantMessage();
1232
+ if (lastAssistant) {
1233
+ await this._checkCompaction(lastAssistant, false);
1234
+ this._assertNotDisposed();
1235
+ }
1236
+
1237
+ // Build messages array (custom message if any, then user message)
1238
+ messages = [];
1239
+
1240
+ // Add user message
1241
+ const userContent: UserContent[] = [{ type: "text", text: expandedText }];
1242
+ if (currentImages) {
1243
+ userContent.push(...currentImages);
1244
+ }
1245
+ if (currentAttachments) userContent.push(...currentAttachments);
1246
+ messages.push({
1247
+ role: "user",
1248
+ content: userContent,
1249
+ timestamp: Date.now(),
1250
+ });
1251
+
1252
+ // Inject any pending "nextTurn" messages as context alongside the user message
1253
+ for (const msg of this._pendingNextTurnMessages) {
1254
+ messages.push(msg);
1255
+ }
1256
+ this._pendingNextTurnMessages = [];
1257
+
1258
+ // Emit before_agent_start extension event
1259
+ const result = await this._extensionRunner.emitBeforeAgentStart(
1260
+ expandedText,
1261
+ currentImages,
1262
+ this._baseSystemPrompt,
1263
+ this._baseSystemPromptOptions,
1264
+ currentAttachments,
1265
+ );
1266
+ this._assertNotDisposed();
1267
+ // Add all custom messages from extensions
1268
+ if (result?.messages) {
1269
+ for (const msg of result.messages) {
1270
+ messages.push({
1271
+ role: "custom",
1272
+ customType: msg.customType,
1273
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
1274
+ content: msg.content ?? [],
1275
+ display: msg.display,
1276
+ details: msg.details,
1277
+ timestamp: Date.now(),
1278
+ });
1279
+ }
1280
+ }
1281
+ // Apply extension-modified system prompt, or reset to base
1282
+ if (result?.systemPrompt !== undefined) {
1283
+ this._systemPromptOverride = result.systemPrompt;
1284
+ this.agent.state.systemPrompt = result.systemPrompt;
1285
+ } else {
1286
+ // Ensure we're using the base prompt (in case previous turn had modifications)
1287
+ this._systemPromptOverride = undefined;
1288
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
1289
+ }
1290
+ } catch (error) {
1291
+ preflightResult?.(false);
1292
+ throw error;
1293
+ }
1294
+
1295
+ if (!messages) {
1296
+ return;
1297
+ }
1298
+
1299
+ preflightResult?.(true);
1300
+ await this._runAgentPrompt(messages);
1301
+ }
1302
+
1303
+ private _assertNotDisposed(): void {
1304
+ if (this._disposed) {
1305
+ throw new Error("Agent session is disposed.");
1306
+ }
1307
+ }
1308
+
1309
+ /**
1310
+ * Try to execute an extension command. Returns true if command was found and executed.
1311
+ */
1312
+ private async _tryExecuteExtensionCommand(text: string): Promise<boolean> {
1313
+ // Parse command name and args
1314
+ const spaceIndex = text.indexOf(" ");
1315
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
1316
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
1317
+
1318
+ const command = this._extensionRunner.getCommand(commandName);
1319
+ if (!command) return false;
1320
+
1321
+ // Get command context from extension runner (includes session control methods)
1322
+ const ctx = this._extensionRunner.createCommandContext();
1323
+
1324
+ try {
1325
+ await command.handler(args, ctx);
1326
+ return true;
1327
+ } catch (err) {
1328
+ // Emit error via extension runner
1329
+ this._extensionRunner.emitError({
1330
+ extensionPath: `command:${commandName}`,
1331
+ event: "command",
1332
+ error: err instanceof Error ? err.message : String(err),
1333
+ });
1334
+ return true;
1335
+ }
1336
+ }
1337
+
1338
+ /**
1339
+ * Expand skill commands (/skill:name args) to their full content.
1340
+ * Returns the expanded text, or the original text if not a skill command or skill not found.
1341
+ * Emits errors via extension runner if file read fails.
1342
+ */
1343
+ private _expandSkillCommand(text: string): string {
1344
+ if (!text.startsWith("/skill:")) return text;
1345
+
1346
+ const spaceIndex = text.indexOf(" ");
1347
+ const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
1348
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
1349
+
1350
+ const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
1351
+ if (!skill) return text; // Unknown skill, pass through
1352
+
1353
+ try {
1354
+ const content = readFileSync(skill.filePath, "utf-8");
1355
+ const body = stripFrontmatter(content).trim();
1356
+ const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
1357
+ return args ? `${skillBlock}\n\n${args}` : skillBlock;
1358
+ } catch (err) {
1359
+ // Emit error like extension commands do
1360
+ this._extensionRunner.emitError({
1361
+ extensionPath: skill.filePath,
1362
+ event: "skill_expansion",
1363
+ error: err instanceof Error ? err.message : String(err),
1364
+ });
1365
+ return text; // Return original on error
1366
+ }
1367
+ }
1368
+
1369
+ /**
1370
+ * Queue a steering message while the agent is running.
1371
+ * Delivered after the current assistant turn finishes executing its tool calls,
1372
+ * before the next LLM call.
1373
+ * Expands skill commands and prompt templates. Errors on extension commands.
1374
+ * @param attachments Optional media attachments to include with the message
1375
+ * @throws Error if text is an extension command
1376
+ */
1377
+ async steer(text: string, attachments?: UserAttachment[]): Promise<void> {
1378
+ // Check for extension commands (cannot be queued)
1379
+ if (text.startsWith("/")) {
1380
+ this._throwIfExtensionCommand(text);
1381
+ }
1382
+
1383
+ // Expand skill commands and prompt templates
1384
+ let expandedText = this._expandSkillCommand(text);
1385
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1386
+
1387
+ await this._queueSteer(expandedText, attachments);
1388
+ }
1389
+
1390
+ /**
1391
+ * Queue a follow-up message to be processed after the agent finishes.
1392
+ * Delivered only when agent has no more tool calls or steering messages.
1393
+ * Expands skill commands and prompt templates. Errors on extension commands.
1394
+ * @param attachments Optional media attachments to include with the message
1395
+ * @throws Error if text is an extension command
1396
+ */
1397
+ async followUp(text: string, attachments?: UserAttachment[]): Promise<void> {
1398
+ // Check for extension commands (cannot be queued)
1399
+ if (text.startsWith("/")) {
1400
+ this._throwIfExtensionCommand(text);
1401
+ }
1402
+
1403
+ // Expand skill commands and prompt templates
1404
+ let expandedText = this._expandSkillCommand(text);
1405
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1406
+
1407
+ await this._queueFollowUp(expandedText, attachments);
1408
+ }
1409
+
1410
+ /**
1411
+ * Internal: Queue a steering message (already expanded, no extension command check).
1412
+ */
1413
+ private async _queueSteer(text: string, attachments?: UserAttachment[]): Promise<void> {
1414
+ this._steeringMessages.push(text);
1415
+ this._emitQueueUpdate();
1416
+ const content: UserContent[] = [{ type: "text", text }];
1417
+ if (attachments) {
1418
+ content.push(...attachments);
1419
+ }
1420
+ this.agent.steer({
1421
+ role: "user",
1422
+ content,
1423
+ timestamp: Date.now(),
1424
+ });
1425
+ }
1426
+
1427
+ /**
1428
+ * Internal: Queue a follow-up message (already expanded, no extension command check).
1429
+ */
1430
+ private async _queueFollowUp(text: string, attachments?: UserAttachment[]): Promise<void> {
1431
+ this._followUpMessages.push(text);
1432
+ this._emitQueueUpdate();
1433
+ const content: UserContent[] = [{ type: "text", text }];
1434
+ if (attachments) {
1435
+ content.push(...attachments);
1436
+ }
1437
+ this.agent.followUp({
1438
+ role: "user",
1439
+ content,
1440
+ timestamp: Date.now(),
1441
+ });
1442
+ }
1443
+
1444
+ /**
1445
+ * Deliver the real result of a backgrounded tool call as a queued steering message.
1446
+ * Steering reaches the model at the next loop boundary; when the agent is idle it is
1447
+ * injected at the start of the next run (an idle followUp would not trigger a run either
1448
+ * and drains later than steering, so steering is used in both cases).
1449
+ */
1450
+ private _handleBackgroundToolResult(toolCall: AgentToolCall, result: AgentToolResult<any>, isError: boolean): void {
1451
+ const text = (result.content ?? [])
1452
+ .filter((entry): entry is TextContent => entry.type === "text")
1453
+ .map((entry) => entry.text)
1454
+ .join("\n");
1455
+ const capped =
1456
+ text.length > BACKGROUND_RESULT_MAX_CHARS
1457
+ ? `${text.slice(0, BACKGROUND_RESULT_MAX_CHARS)}\n[...truncated]`
1458
+ : text;
1459
+ const status = isError ? ` status="error"` : "";
1460
+ const body = `<background-tool-result name="${toolCall.name}" callId="${toolCall.id}"${status}>\n${capped}\n</background-tool-result>`;
1461
+ void this._queueSteer(body);
1462
+ }
1463
+
1464
+ /**
1465
+ * Throw an error if the text is an extension command.
1466
+ */
1467
+ private _throwIfExtensionCommand(text: string): void {
1468
+ const spaceIndex = text.indexOf(" ");
1469
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
1470
+ const command = this._extensionRunner.getCommand(commandName);
1471
+
1472
+ if (command) {
1473
+ throw new Error(
1474
+ `Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`,
1475
+ );
1476
+ }
1477
+ }
1478
+
1479
+ /**
1480
+ * Send a custom message to the session. Creates a CustomMessageEntry.
1481
+ *
1482
+ * Handles three cases:
1483
+ * - Streaming: queues message, processed when loop pulls from queue
1484
+ * - Not streaming + triggerTurn: appends to state/session, starts new turn
1485
+ * - Not streaming + no trigger: appends to state/session, no turn
1486
+ *
1487
+ * @param message Custom message with customType, content, display, details
1488
+ * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
1489
+ * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
1490
+ */
1491
+ async sendCustomMessage<T = unknown>(
1492
+ message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">,
1493
+ options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" },
1494
+ ): Promise<void> {
1495
+ const appMessage = {
1496
+ role: "custom" as const,
1497
+ customType: message.customType,
1498
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
1499
+ content: message.content ?? [],
1500
+ display: message.display,
1501
+ details: message.details,
1502
+ timestamp: Date.now(),
1503
+ } satisfies CustomMessage<T>;
1504
+ if (options?.deliverAs === "nextTurn") {
1505
+ this._pendingNextTurnMessages.push(appMessage);
1506
+ } else if (this.isStreaming) {
1507
+ if (options?.deliverAs === "followUp") {
1508
+ this.agent.followUp(appMessage);
1509
+ } else {
1510
+ this.agent.steer(appMessage);
1511
+ }
1512
+ } else if (options?.triggerTurn) {
1513
+ await this._runAgentPrompt(appMessage);
1514
+ } else {
1515
+ this.agent.state.messages.push(appMessage);
1516
+ this.sessionManager.appendCustomMessageEntry(
1517
+ message.customType,
1518
+ message.content,
1519
+ message.display,
1520
+ message.details,
1521
+ );
1522
+ this._emit({ type: "message_start", message: appMessage });
1523
+ this._emit({ type: "message_end", message: appMessage });
1524
+ }
1525
+ }
1526
+
1527
+ /**
1528
+ * Send a user message to the agent. Always triggers a turn.
1529
+ * When the agent is streaming, use deliverAs to specify how to queue the message.
1530
+ *
1531
+ * @param content User message content (string or content array)
1532
+ * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
1533
+ */
1534
+ async sendUserMessage(
1535
+ content: string | UserContent[],
1536
+ options?: { deliverAs?: "steer" | "followUp" },
1537
+ ): Promise<void> {
1538
+ // Normalize content to text and media attachments.
1539
+ let text: string;
1540
+ let attachments: UserAttachment[] | undefined;
1541
+
1542
+ if (typeof content === "string") {
1543
+ text = content;
1544
+ } else {
1545
+ const textParts: string[] = [];
1546
+ attachments = [];
1547
+ for (const part of content) {
1548
+ if (part.type === "text") {
1549
+ textParts.push(part.text);
1550
+ } else {
1551
+ attachments.push(part);
1552
+ }
1553
+ }
1554
+ text = textParts.join("\n");
1555
+ if (attachments.length === 0) attachments = undefined;
1556
+ }
1557
+
1558
+ // Use prompt() with expandPromptTemplates: false to skip command handling and template expansion
1559
+ await this.prompt(text, {
1560
+ expandPromptTemplates: false,
1561
+ streamingBehavior: options?.deliverAs,
1562
+ attachments,
1563
+ source: "extension",
1564
+ });
1565
+ }
1566
+
1567
+ /**
1568
+ * Clear all queued messages and return them.
1569
+ * Useful for restoring to editor when user aborts.
1570
+ * @returns Object with steering and followUp arrays
1571
+ */
1572
+ clearQueue(): { steering: string[]; followUp: string[] } {
1573
+ const steering = [...this._steeringMessages];
1574
+ const followUp = [...this._followUpMessages];
1575
+ this._steeringMessages = [];
1576
+ this._followUpMessages = [];
1577
+ this.agent.clearAllQueues();
1578
+ this._emitQueueUpdate();
1579
+ return { steering, followUp };
1580
+ }
1581
+
1582
+ /** Number of pending messages (includes both steering and follow-up) */
1583
+ get pendingMessageCount(): number {
1584
+ return this._steeringMessages.length + this._followUpMessages.length;
1585
+ }
1586
+
1587
+ /** Get pending steering messages (read-only) */
1588
+ getSteeringMessages(): readonly string[] {
1589
+ return this._steeringMessages;
1590
+ }
1591
+
1592
+ /** Get pending follow-up messages (read-only) */
1593
+ getFollowUpMessages(): readonly string[] {
1594
+ return this._followUpMessages;
1595
+ }
1596
+
1597
+ get resourceLoader(): ResourceLoader {
1598
+ return this._resourceLoader;
1599
+ }
1600
+
1601
+ /**
1602
+ * Abort current operation and wait for agent to become idle.
1603
+ */
1604
+ async abort(): Promise<void> {
1605
+ this.abortRetry();
1606
+ this.agent.abort();
1607
+ await this.waitForIdle();
1608
+ }
1609
+
1610
+ async waitForIdle(): Promise<void> {
1611
+ if (this.isIdle) {
1612
+ return;
1613
+ }
1614
+ await this._getIdleWaitPromise();
1615
+ }
1616
+
1617
+ // =========================================================================
1618
+ // Model Management
1619
+ // =========================================================================
1620
+
1621
+ private async _emitModelSelect(
1622
+ nextModel: Model<any>,
1623
+ previousModel: Model<any> | undefined,
1624
+ source: "set" | "cycle" | "restore",
1625
+ ): Promise<void> {
1626
+ if (modelsAreEqual(previousModel, nextModel)) return;
1627
+ await this._extensionRunner.emit({
1628
+ type: "model_select",
1629
+ model: nextModel,
1630
+ previousModel,
1631
+ source,
1632
+ });
1633
+ }
1634
+
1635
+ /**
1636
+ * Set model directly.
1637
+ * Validates that auth is configured, saves to session and settings.
1638
+ * @throws Error if no auth is configured for the model
1639
+ */
1640
+ async setModel(model: Model<any>): Promise<void> {
1641
+ if (!(await this._modelRuntime.checkAuth(model.provider))) {
1642
+ throw new Error(`No API key for ${model.provider}/${model.id}`);
1643
+ }
1644
+
1645
+ const previousModel = this.model;
1646
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
1647
+ this.agent.state.model = model;
1648
+ this.sessionManager.appendModelChange(model.provider, model.id);
1649
+ this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1650
+
1651
+ // Re-clamp thinking level for new model's capabilities
1652
+ this.setThinkingLevel(thinkingLevel);
1653
+
1654
+ await this._emitModelSelect(model, previousModel, "set");
1655
+ }
1656
+
1657
+ /**
1658
+ * Cycle to next/previous model.
1659
+ * Uses scoped models (from --models flag) if available, otherwise all available models.
1660
+ * @param direction - "forward" (default) or "backward"
1661
+ * @returns The new model info, or undefined if only one model available
1662
+ */
1663
+ async cycleModel(direction: "forward" | "backward" = "forward"): Promise<ModelCycleResult | undefined> {
1664
+ if (this._scopedModels.length > 0) {
1665
+ return this._cycleScopedModel(direction);
1666
+ }
1667
+ return this._cycleAvailableModel(direction);
1668
+ }
1669
+
1670
+ private async _cycleScopedModel(direction: "forward" | "backward"): Promise<ModelCycleResult | undefined> {
1671
+ const checks = await Promise.all(
1672
+ this._scopedModels.map(async (scoped) => ({
1673
+ scoped,
1674
+ auth: await this._modelRuntime.checkAuth(scoped.model.provider),
1675
+ })),
1676
+ );
1677
+ const scopedModels = checks.filter(({ auth }) => auth !== undefined).map(({ scoped }) => scoped);
1678
+ if (scopedModels.length <= 1) return undefined;
1679
+
1680
+ const currentModel = this.model;
1681
+ let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
1682
+
1683
+ if (currentIndex === -1) currentIndex = 0;
1684
+ const len = scopedModels.length;
1685
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1686
+ const next = scopedModels[nextIndex];
1687
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
1688
+
1689
+ // Apply model
1690
+ this.agent.state.model = next.model;
1691
+ this.sessionManager.appendModelChange(next.model.provider, next.model.id);
1692
+ this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
1693
+
1694
+ // Apply thinking level.
1695
+ // - Explicit scoped model thinking level overrides current session level
1696
+ // - Undefined scoped model thinking level inherits the current session preference
1697
+ // setThinkingLevel clamps to model capabilities.
1698
+ this.setThinkingLevel(thinkingLevel);
1699
+
1700
+ await this._emitModelSelect(next.model, currentModel, "cycle");
1701
+
1702
+ return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
1703
+ }
1704
+
1705
+ private async _cycleAvailableModel(direction: "forward" | "backward"): Promise<ModelCycleResult | undefined> {
1706
+ const availableModels = await this._modelRuntime.getAvailable();
1707
+ if (availableModels.length <= 1) return undefined;
1708
+
1709
+ const currentModel = this.model;
1710
+ let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
1711
+
1712
+ if (currentIndex === -1) currentIndex = 0;
1713
+ const len = availableModels.length;
1714
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1715
+ const nextModel = availableModels[nextIndex];
1716
+
1717
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
1718
+ this.agent.state.model = nextModel;
1719
+ this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
1720
+ this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
1721
+
1722
+ // Re-clamp thinking level for new model's capabilities
1723
+ this.setThinkingLevel(thinkingLevel);
1724
+
1725
+ await this._emitModelSelect(nextModel, currentModel, "cycle");
1726
+
1727
+ return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
1728
+ }
1729
+
1730
+ // =========================================================================
1731
+ // Thinking Level Management
1732
+ // =========================================================================
1733
+
1734
+ /**
1735
+ * Set thinking level.
1736
+ * Clamps to model capabilities based on available thinking levels.
1737
+ * Saves to session and settings only if the level actually changes.
1738
+ */
1739
+ setThinkingLevel(level: ThinkingLevel): void {
1740
+ const availableLevels = this.getAvailableThinkingLevels();
1741
+ const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
1742
+
1743
+ // Only persist if actually changing
1744
+ const previousLevel = this.agent.state.thinkingLevel;
1745
+ const isChanging = effectiveLevel !== previousLevel;
1746
+
1747
+ this.agent.state.thinkingLevel = effectiveLevel;
1748
+
1749
+ if (isChanging) {
1750
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1751
+ if (this.supportsThinking() || effectiveLevel !== "off") {
1752
+ this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
1753
+ }
1754
+ this._emit({ type: "thinking_level_changed", level: effectiveLevel });
1755
+ void this._extensionRunner.emit({
1756
+ type: "thinking_level_select",
1757
+ level: effectiveLevel,
1758
+ previousLevel,
1759
+ });
1760
+ }
1761
+ }
1762
+
1763
+ /**
1764
+ * Cycle to next thinking level.
1765
+ * @returns New level, or undefined if model doesn't support thinking
1766
+ */
1767
+ cycleThinkingLevel(): ThinkingLevel | undefined {
1768
+ if (!this.supportsThinking()) return undefined;
1769
+
1770
+ const levels = this.getAvailableThinkingLevels();
1771
+ const currentIndex = levels.indexOf(this.thinkingLevel);
1772
+ const nextIndex = (currentIndex + 1) % levels.length;
1773
+ const nextLevel = levels[nextIndex];
1774
+
1775
+ this.setThinkingLevel(nextLevel);
1776
+ return nextLevel;
1777
+ }
1778
+
1779
+ /**
1780
+ * Get available thinking levels for current model.
1781
+ * The provider will clamp to what the specific model supports internally.
1782
+ */
1783
+ getAvailableThinkingLevels(): ThinkingLevel[] {
1784
+ if (!this.model) return THINKING_LEVELS;
1785
+ return getSupportedThinkingLevels(this.model) as ThinkingLevel[];
1786
+ }
1787
+
1788
+ /**
1789
+ * Check if current model supports thinking/reasoning.
1790
+ */
1791
+ supportsThinking(): boolean {
1792
+ return !!this.model?.reasoning;
1793
+ }
1794
+
1795
+ private _getThinkingLevelForModelSwitch(explicitLevel?: ThinkingLevel): ThinkingLevel {
1796
+ if (explicitLevel !== undefined) {
1797
+ return explicitLevel;
1798
+ }
1799
+ if (!this.supportsThinking()) {
1800
+ return this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
1801
+ }
1802
+ return this.thinkingLevel;
1803
+ }
1804
+
1805
+ private _clampThinkingLevel(level: ThinkingLevel, _availableLevels: ThinkingLevel[]): ThinkingLevel {
1806
+ return this.model ? (clampThinkingLevel(this.model, level) as ThinkingLevel) : "off";
1807
+ }
1808
+
1809
+ // =========================================================================
1810
+ // Queue Mode Management
1811
+ // =========================================================================
1812
+
1813
+ private syncQueueModesFromSettings(): void {
1814
+ this.agent.steeringMode = this.settingsManager.getSteeringMode();
1815
+ this.agent.followUpMode = this.settingsManager.getFollowUpMode();
1816
+ }
1817
+
1818
+ /**
1819
+ * Set steering message mode.
1820
+ * Saves to settings.
1821
+ */
1822
+ setSteeringMode(mode: "all" | "one-at-a-time"): void {
1823
+ this.agent.steeringMode = mode;
1824
+ this.settingsManager.setSteeringMode(mode);
1825
+ }
1826
+
1827
+ /**
1828
+ * Set follow-up message mode.
1829
+ * Saves to settings.
1830
+ */
1831
+ setFollowUpMode(mode: "all" | "one-at-a-time"): void {
1832
+ this.agent.followUpMode = mode;
1833
+ this.settingsManager.setFollowUpMode(mode);
1834
+ }
1835
+
1836
+ // =========================================================================
1837
+ // Compaction
1838
+ // =========================================================================
1839
+
1840
+ /**
1841
+ * Manually compact the session context.
1842
+ * Aborts current agent operation first.
1843
+ * @param customInstructions Optional instructions for the compaction summary
1844
+ */
1845
+ async compact(customInstructions?: string): Promise<CompactionResult> {
1846
+ this._disconnectFromAgent();
1847
+ await this.abort();
1848
+ this._compactionAbortController = new AbortController();
1849
+ this._emit({ type: "compaction_start", reason: "manual" });
1850
+
1851
+ try {
1852
+ if (!this.model) {
1853
+ throw new Error(formatNoModelSelectedMessage());
1854
+ }
1855
+
1856
+ const { apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model);
1857
+
1858
+ const pathEntries = this.sessionManager.getBranch();
1859
+ const settings = this.settingsManager.getCompactionSettings();
1860
+
1861
+ const preparation = prepareCompaction(pathEntries, settings);
1862
+ if (!preparation) {
1863
+ // Check why we can't compact
1864
+ const lastEntry = pathEntries[pathEntries.length - 1];
1865
+ if (lastEntry?.type === "compaction") {
1866
+ throw new Error("Already compacted");
1867
+ }
1868
+ throw new Error("Nothing to compact (session too small)");
1869
+ }
1870
+
1871
+ let extensionCompaction: CompactionResult | undefined;
1872
+ let fromExtension = false;
1873
+
1874
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1875
+ const result = (await this._extensionRunner.emit({
1876
+ type: "session_before_compact",
1877
+ preparation,
1878
+ branchEntries: pathEntries,
1879
+ customInstructions,
1880
+ reason: "manual",
1881
+ willRetry: false,
1882
+ signal: this._compactionAbortController.signal,
1883
+ })) as SessionBeforeCompactResult | undefined;
1884
+
1885
+ if (result?.cancel) {
1886
+ throw new Error("Compaction cancelled");
1887
+ }
1888
+
1889
+ if (result?.compaction) {
1890
+ extensionCompaction = result.compaction;
1891
+ fromExtension = true;
1892
+ }
1893
+ }
1894
+
1895
+ let summary: string;
1896
+ let firstKeptEntryId: string;
1897
+ let tokensBefore: number;
1898
+ let details: unknown;
1899
+
1900
+ if (extensionCompaction) {
1901
+ // Extension provided compaction content
1902
+ summary = extensionCompaction.summary;
1903
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1904
+ tokensBefore = extensionCompaction.tokensBefore;
1905
+ details = extensionCompaction.details;
1906
+ } else {
1907
+ // Generate compaction result
1908
+ const result = await compact(
1909
+ preparation,
1910
+ this.model,
1911
+ apiKey,
1912
+ headers,
1913
+ customInstructions,
1914
+ this._compactionAbortController.signal,
1915
+ this.thinkingLevel,
1916
+ this.agent.streamFn,
1917
+ env,
1918
+ );
1919
+ summary = result.summary;
1920
+ firstKeptEntryId = result.firstKeptEntryId;
1921
+ tokensBefore = result.tokensBefore;
1922
+ details = result.details;
1923
+ }
1924
+
1925
+ if (this._compactionAbortController.signal.aborted) {
1926
+ throw new Error("Compaction cancelled");
1927
+ }
1928
+
1929
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
1930
+ const newEntries = this.sessionManager.getEntries();
1931
+ const sessionContext = this.sessionManager.buildSessionContext();
1932
+ this.agent.state.messages = sessionContext.messages;
1933
+ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
1934
+
1935
+ // Get the saved compaction entry for the extension event
1936
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary) as
1937
+ | CompactionEntry
1938
+ | undefined;
1939
+
1940
+ if (this._extensionRunner && savedCompactionEntry) {
1941
+ await this._extensionRunner.emit({
1942
+ type: "session_compact",
1943
+ compactionEntry: savedCompactionEntry,
1944
+ fromExtension,
1945
+ reason: "manual",
1946
+ willRetry: false,
1947
+ });
1948
+ }
1949
+
1950
+ const compactionResult: CompactionResult = {
1951
+ summary,
1952
+ firstKeptEntryId,
1953
+ tokensBefore,
1954
+ estimatedTokensAfter,
1955
+ details,
1956
+ };
1957
+ this._emit({
1958
+ type: "compaction_end",
1959
+ reason: "manual",
1960
+ result: compactionResult,
1961
+ aborted: false,
1962
+ willRetry: false,
1963
+ });
1964
+ return compactionResult;
1965
+ } catch (error) {
1966
+ const message = error instanceof Error ? error.message : String(error);
1967
+ const aborted = message === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError");
1968
+ this._emit({
1969
+ type: "compaction_end",
1970
+ reason: "manual",
1971
+ result: undefined,
1972
+ aborted,
1973
+ willRetry: false,
1974
+ errorMessage: aborted ? undefined : `Compaction failed: ${message}`,
1975
+ });
1976
+ throw error;
1977
+ } finally {
1978
+ this._compactionAbortController = undefined;
1979
+ this._reconnectToAgent();
1980
+ }
1981
+ }
1982
+
1983
+ /**
1984
+ * Cancel in-progress compaction (manual or auto).
1985
+ */
1986
+ abortCompaction(): void {
1987
+ this._compactionAbortController?.abort();
1988
+ this._autoCompactionAbortController?.abort();
1989
+ }
1990
+
1991
+ /**
1992
+ * Cancel in-progress branch summarization.
1993
+ */
1994
+ abortBranchSummary(): void {
1995
+ this._branchSummaryAbortController?.abort();
1996
+ }
1997
+
1998
+ /**
1999
+ * Check if compaction is needed and run it.
2000
+ * Called after agent_end and before prompt submission.
2001
+ *
2002
+ * Two cases:
2003
+ * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
2004
+ * 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually)
2005
+ *
2006
+ * @param assistantMessage The assistant message to check
2007
+ * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
2008
+ */
2009
+ private async _checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<boolean> {
2010
+ const settings = this.settingsManager.getCompactionSettings();
2011
+ if (!settings.enabled) return false;
2012
+
2013
+ // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
2014
+ if (skipAbortedCheck && assistantMessage.stopReason === "aborted") return false;
2015
+
2016
+ const contextWindow = this.model?.contextWindow ?? 0;
2017
+
2018
+ // Skip overflow check if the message came from a different model.
2019
+ // This handles the case where user switched from a smaller-context model (e.g. opus)
2020
+ // to a larger-context model (e.g. codex) - the overflow error from the old model
2021
+ // shouldn't trigger compaction for the new model.
2022
+ const sameModel =
2023
+ this.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;
2024
+
2025
+ // Skip compaction checks if this assistant message is older than the latest
2026
+ // compaction boundary. This prevents a stale pre-compaction usage/error
2027
+ // from retriggering compaction on the first prompt after compaction.
2028
+ const compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());
2029
+ const assistantIsFromBeforeCompaction =
2030
+ compactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();
2031
+ if (assistantIsFromBeforeCompaction) {
2032
+ return false;
2033
+ }
2034
+
2035
+ // Case 1: Overflow - LLM returned context overflow error, or reported usage exceeded
2036
+ // the configured window. A successful response over the configured window should compact
2037
+ // but must not retry: the assistant answer already completed and agent.continue() cannot
2038
+ // continue from an assistant message.
2039
+ if (sameModel && isContextOverflow(assistantMessage, contextWindow)) {
2040
+ const willRetry = assistantMessage.stopReason !== "stop";
2041
+
2042
+ if (!willRetry) {
2043
+ return await this._runAutoCompaction("overflow", false);
2044
+ }
2045
+
2046
+ if (this._overflowRecoveryAttempted) {
2047
+ this._emit({
2048
+ type: "compaction_end",
2049
+ reason: "overflow",
2050
+ result: undefined,
2051
+ aborted: false,
2052
+ willRetry: false,
2053
+ errorMessage:
2054
+ "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
2055
+ });
2056
+ return false;
2057
+ }
2058
+
2059
+ this._overflowRecoveryAttempted = true;
2060
+ // Remove the error message from agent state (it IS saved to session for history,
2061
+ // but we don't want it in context for the retry)
2062
+ const messages = this.agent.state.messages;
2063
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
2064
+ this.agent.state.messages = messages.slice(0, -1);
2065
+ }
2066
+ return await this._runAutoCompaction("overflow", willRetry);
2067
+ }
2068
+
2069
+ // Case 2: Threshold - context is getting large
2070
+ // For error messages or all-zero usage messages, estimate from the last valid response.
2071
+ // This ensures sessions that hit persistent API errors (e.g. 529) or malformed zero-usage
2072
+ // responses can still compact and do not reset context accounting.
2073
+ let contextTokens: number;
2074
+ const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
2075
+ if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
2076
+ const messages = this.agent.state.messages;
2077
+ const estimate = estimateContextTokens(messages);
2078
+ if (estimate.lastUsageIndex === null) return false; // No usage data at all
2079
+ // Verify the usage source is post-compaction. Kept pre-compaction messages
2080
+ // have stale usage reflecting the old (larger) context and would falsely
2081
+ // trigger compaction right after one just finished.
2082
+ const usageMsg = messages[estimate.lastUsageIndex];
2083
+ if (
2084
+ compactionEntry &&
2085
+ usageMsg.role === "assistant" &&
2086
+ (usageMsg as AssistantMessage).timestamp <= new Date(compactionEntry.timestamp).getTime()
2087
+ ) {
2088
+ return false;
2089
+ }
2090
+ contextTokens = estimate.tokens;
2091
+ } else {
2092
+ contextTokens = directContextTokens;
2093
+ }
2094
+ if (shouldCompact(contextTokens, contextWindow, settings)) {
2095
+ return await this._runAutoCompaction("threshold", false);
2096
+ }
2097
+ return false;
2098
+ }
2099
+
2100
+ /**
2101
+ * Internal: Run auto-compaction with events.
2102
+ */
2103
+ private async _runAutoCompaction(reason: "overflow" | "threshold", willRetry: boolean): Promise<boolean> {
2104
+ const settings = this.settingsManager.getCompactionSettings();
2105
+ let started = false;
2106
+
2107
+ try {
2108
+ if (!this.model) {
2109
+ return false;
2110
+ }
2111
+
2112
+ let apiKey: string | undefined;
2113
+ let headers: Record<string, string> | undefined;
2114
+ let env: Record<string, string> | undefined;
2115
+ if (this.agent.streamFn === streamSimple) {
2116
+ const authResult = await this._modelRuntime.getAuth(this.model);
2117
+ if (!authResult?.auth.apiKey) return false;
2118
+ apiKey = authResult.auth.apiKey;
2119
+ headers = withoutDeletedHeaders(authResult.auth.headers);
2120
+ env = authResult.env;
2121
+ } else {
2122
+ ({ apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model));
2123
+ }
2124
+
2125
+ const pathEntries = this.sessionManager.getBranch();
2126
+
2127
+ const preparation = prepareCompaction(pathEntries, settings);
2128
+ if (!preparation) {
2129
+ return false;
2130
+ }
2131
+
2132
+ this._emit({ type: "compaction_start", reason });
2133
+ this._autoCompactionAbortController = new AbortController();
2134
+ started = true;
2135
+
2136
+ let extensionCompaction: CompactionResult | undefined;
2137
+ let fromExtension = false;
2138
+
2139
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
2140
+ const extensionResult = (await this._extensionRunner.emit({
2141
+ type: "session_before_compact",
2142
+ preparation,
2143
+ branchEntries: pathEntries,
2144
+ customInstructions: undefined,
2145
+ reason,
2146
+ willRetry,
2147
+ signal: this._autoCompactionAbortController.signal,
2148
+ })) as SessionBeforeCompactResult | undefined;
2149
+
2150
+ if (extensionResult?.cancel) {
2151
+ this._emit({
2152
+ type: "compaction_end",
2153
+ reason,
2154
+ result: undefined,
2155
+ aborted: true,
2156
+ willRetry: false,
2157
+ });
2158
+ return false;
2159
+ }
2160
+
2161
+ if (extensionResult?.compaction) {
2162
+ extensionCompaction = extensionResult.compaction;
2163
+ fromExtension = true;
2164
+ }
2165
+ }
2166
+
2167
+ let summary: string;
2168
+ let firstKeptEntryId: string;
2169
+ let tokensBefore: number;
2170
+ let details: unknown;
2171
+
2172
+ if (extensionCompaction) {
2173
+ // Extension provided compaction content
2174
+ summary = extensionCompaction.summary;
2175
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
2176
+ tokensBefore = extensionCompaction.tokensBefore;
2177
+ details = extensionCompaction.details;
2178
+ } else {
2179
+ // Generate compaction result
2180
+ const compactResult = await compact(
2181
+ preparation,
2182
+ this.model,
2183
+ apiKey,
2184
+ headers,
2185
+ undefined,
2186
+ this._autoCompactionAbortController.signal,
2187
+ this.thinkingLevel,
2188
+ this.agent.streamFn,
2189
+ env,
2190
+ );
2191
+ summary = compactResult.summary;
2192
+ firstKeptEntryId = compactResult.firstKeptEntryId;
2193
+ tokensBefore = compactResult.tokensBefore;
2194
+ details = compactResult.details;
2195
+ }
2196
+
2197
+ if (this._autoCompactionAbortController.signal.aborted) {
2198
+ this._emit({
2199
+ type: "compaction_end",
2200
+ reason,
2201
+ result: undefined,
2202
+ aborted: true,
2203
+ willRetry: false,
2204
+ });
2205
+ return false;
2206
+ }
2207
+
2208
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
2209
+ const newEntries = this.sessionManager.getEntries();
2210
+ const sessionContext = this.sessionManager.buildSessionContext();
2211
+ this.agent.state.messages = sessionContext.messages;
2212
+ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
2213
+
2214
+ // Get the saved compaction entry for the extension event
2215
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary) as
2216
+ | CompactionEntry
2217
+ | undefined;
2218
+
2219
+ if (this._extensionRunner && savedCompactionEntry) {
2220
+ await this._extensionRunner.emit({
2221
+ type: "session_compact",
2222
+ compactionEntry: savedCompactionEntry,
2223
+ fromExtension,
2224
+ reason,
2225
+ willRetry,
2226
+ });
2227
+ }
2228
+
2229
+ const result: CompactionResult = {
2230
+ summary,
2231
+ firstKeptEntryId,
2232
+ tokensBefore,
2233
+ estimatedTokensAfter,
2234
+ details,
2235
+ };
2236
+ this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
2237
+
2238
+ if (willRetry) {
2239
+ const messages = this.agent.state.messages;
2240
+ const lastMsg = messages[messages.length - 1];
2241
+ if (lastMsg?.role === "assistant" && (lastMsg as AssistantMessage).stopReason === "error") {
2242
+ this.agent.state.messages = messages.slice(0, -1);
2243
+ }
2244
+ return true;
2245
+ }
2246
+
2247
+ // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
2248
+ // Continue once so queued messages are delivered.
2249
+ return this.agent.hasQueuedMessages();
2250
+ } catch (error) {
2251
+ const errorMessage = error instanceof Error ? error.message : "compaction failed";
2252
+ if (started) {
2253
+ this._emit({
2254
+ type: "compaction_end",
2255
+ reason,
2256
+ result: undefined,
2257
+ aborted: false,
2258
+ willRetry: false,
2259
+ errorMessage:
2260
+ reason === "overflow"
2261
+ ? `Context overflow recovery failed: ${errorMessage}`
2262
+ : `Auto-compaction failed: ${errorMessage}`,
2263
+ });
2264
+ }
2265
+ return false;
2266
+ } finally {
2267
+ this._autoCompactionAbortController = undefined;
2268
+ }
2269
+ }
2270
+
2271
+ /**
2272
+ * Toggle auto-compaction setting.
2273
+ */
2274
+ setAutoCompactionEnabled(enabled: boolean): void {
2275
+ this.settingsManager.setCompactionEnabled(enabled);
2276
+ }
2277
+
2278
+ /** Whether auto-compaction is enabled */
2279
+ get autoCompactionEnabled(): boolean {
2280
+ return this.settingsManager.getCompactionEnabled();
2281
+ }
2282
+
2283
+ async bindExtensions(bindings: ExtensionBindings): Promise<void> {
2284
+ if (bindings.uiContext !== undefined) {
2285
+ this._extensionUIContext = bindings.uiContext;
2286
+ }
2287
+ if (bindings.mode !== undefined) {
2288
+ this._extensionMode = bindings.mode;
2289
+ }
2290
+ if (bindings.commandContextActions !== undefined) {
2291
+ this._extensionCommandContextActions = bindings.commandContextActions;
2292
+ }
2293
+ if (bindings.abortHandler !== undefined) {
2294
+ this._extensionAbortHandler = bindings.abortHandler;
2295
+ }
2296
+ if (bindings.shutdownHandler !== undefined) {
2297
+ this._extensionShutdownHandler = bindings.shutdownHandler;
2298
+ }
2299
+ if (bindings.onError !== undefined) {
2300
+ this._extensionErrorListener = bindings.onError;
2301
+ }
2302
+
2303
+ this._applyExtensionBindings(this._extensionRunner);
2304
+ await this._extensionRunner.emit(this._sessionStartEvent);
2305
+ await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
2306
+ }
2307
+
2308
+ private async extendResourcesFromExtensions(reason: "startup" | "reload"): Promise<void> {
2309
+ if (!this._extensionRunner.hasHandlers("resources_discover")) {
2310
+ return;
2311
+ }
2312
+
2313
+ const { skillPaths, promptPaths } = await this._extensionRunner.emitResourcesDiscover(
2314
+ this._cwd,
2315
+ reason,
2316
+ );
2317
+
2318
+ if (skillPaths.length === 0 && promptPaths.length === 0) {
2319
+ return;
2320
+ }
2321
+
2322
+ const extensionPaths: ResourceExtensionPaths = {
2323
+ skillPaths: this.buildExtensionResourcePaths(skillPaths),
2324
+ promptPaths: this.buildExtensionResourcePaths(promptPaths),
2325
+ };
2326
+
2327
+ this._resourceLoader.extendResources(extensionPaths);
2328
+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
2329
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
2330
+ }
2331
+
2332
+ private buildExtensionResourcePaths(entries: Array<{ path: string; extensionPath: string }>): Array<{
2333
+ path: string;
2334
+ metadata: { source: string; scope: "temporary"; origin: "top-level"; baseDir?: string };
2335
+ }> {
2336
+ return entries.map((entry) => {
2337
+ const source = this.getExtensionSourceLabel(entry.extensionPath);
2338
+ const baseDir = entry.extensionPath.startsWith("<") ? undefined : dirname(entry.extensionPath);
2339
+ return {
2340
+ path: entry.path,
2341
+ metadata: {
2342
+ source,
2343
+ scope: "temporary",
2344
+ origin: "top-level",
2345
+ baseDir,
2346
+ },
2347
+ };
2348
+ });
2349
+ }
2350
+
2351
+ private getExtensionSourceLabel(extensionPath: string): string {
2352
+ if (extensionPath.startsWith("<")) {
2353
+ return `extension:${extensionPath.replace(/[<>]/g, "")}`;
2354
+ }
2355
+ const base = basename(extensionPath);
2356
+ const name = base.replace(/\.(ts|js)$/, "");
2357
+ return `extension:${name}`;
2358
+ }
2359
+
2360
+ private _applyExtensionBindings(runner: ExtensionRunner): void {
2361
+ runner.setUIContext(this._extensionUIContext, this._extensionMode);
2362
+ runner.bindCommandContext(this._extensionCommandContextActions);
2363
+
2364
+ this._extensionErrorUnsubscriber?.();
2365
+ this._extensionErrorUnsubscriber = this._extensionErrorListener
2366
+ ? runner.onError(this._extensionErrorListener)
2367
+ : undefined;
2368
+ }
2369
+
2370
+ private _refreshCurrentModelFromRegistry(): void {
2371
+ const currentModel = this.model;
2372
+ if (!currentModel) {
2373
+ return;
2374
+ }
2375
+
2376
+ const refreshedModel = this._modelRuntime.getModel(currentModel.provider, currentModel.id);
2377
+ if (!refreshedModel || refreshedModel === currentModel) {
2378
+ return;
2379
+ }
2380
+
2381
+ this.agent.state.model = refreshedModel;
2382
+ }
2383
+
2384
+ private _bindExtensionCore(runner: ExtensionRunner): void {
2385
+ const getCommands = (): SlashCommandInfo[] => {
2386
+ const extensionCommands: SlashCommandInfo[] = runner.getRegisteredCommands().map((command) => ({
2387
+ name: command.invocationName,
2388
+ description: command.description,
2389
+ source: "extension",
2390
+ sourceInfo: command.sourceInfo,
2391
+ }));
2392
+
2393
+ const templates: SlashCommandInfo[] = this.promptTemplates.map((template) => ({
2394
+ name: template.name,
2395
+ description: template.description,
2396
+ source: "prompt",
2397
+ sourceInfo: template.sourceInfo,
2398
+ }));
2399
+
2400
+ const skills: SlashCommandInfo[] = this._resourceLoader.getSkills().skills.map((skill) => ({
2401
+ name: `skill:${skill.name}`,
2402
+ description: skill.description,
2403
+ source: "skill",
2404
+ sourceInfo: skill.sourceInfo,
2405
+ }));
2406
+
2407
+ return [...extensionCommands, ...templates, ...skills];
2408
+ };
2409
+
2410
+ runner.bindCore(
2411
+ {
2412
+ sendMessage: (message, options) => {
2413
+ this.sendCustomMessage(message, options).catch((err) => {
2414
+ runner.emitError({
2415
+ extensionPath: "<runtime>",
2416
+ event: "send_message",
2417
+ error: err instanceof Error ? err.message : String(err),
2418
+ });
2419
+ });
2420
+ },
2421
+ sendUserMessage: (content, options) => {
2422
+ this.sendUserMessage(content, options).catch((err) => {
2423
+ runner.emitError({
2424
+ extensionPath: "<runtime>",
2425
+ event: "send_user_message",
2426
+ error: err instanceof Error ? err.message : String(err),
2427
+ });
2428
+ });
2429
+ },
2430
+ appendEntry: (customType, data) => {
2431
+ const entryId = this.sessionManager.appendCustomEntry(customType, data);
2432
+ const entry = this.sessionManager.getEntry(entryId);
2433
+ if (entry) {
2434
+ this._emit({ type: "entry_appended", entry });
2435
+ }
2436
+ },
2437
+ setSessionName: (name) => {
2438
+ this.setSessionName(name);
2439
+ },
2440
+ getSessionName: () => {
2441
+ return this.sessionManager.getSessionName();
2442
+ },
2443
+ setLabel: (entryId, label) => {
2444
+ this.sessionManager.appendLabelChange(entryId, label);
2445
+ },
2446
+ getActiveTools: () => this.getActiveToolNames(),
2447
+ getAllTools: () => this.getAllTools(),
2448
+ setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
2449
+ refreshTools: () => this._refreshToolRegistry(),
2450
+ getCommands,
2451
+ setModel: async (model) => {
2452
+ if (!this._modelRuntime.hasConfiguredAuth(model.provider)) return false;
2453
+ await this.setModel(model);
2454
+ return true;
2455
+ },
2456
+ getThinkingLevel: () => this.thinkingLevel,
2457
+ setThinkingLevel: (level) => this.setThinkingLevel(level),
2458
+ },
2459
+ {
2460
+ getModel: () => this.model,
2461
+ isIdle: () => this.isIdle,
2462
+ isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
2463
+ getSignal: () => this.agent.signal,
2464
+ abort: () => {
2465
+ if (this._extensionAbortHandler) {
2466
+ this._extensionAbortHandler();
2467
+ return;
2468
+ }
2469
+ void this.abort();
2470
+ },
2471
+ hasPendingMessages: () => this.pendingMessageCount > 0,
2472
+ shutdown: () => {
2473
+ this._extensionShutdownHandler?.();
2474
+ },
2475
+ getContextUsage: () => this.getContextUsage(),
2476
+ compact: (options) => {
2477
+ void (async () => {
2478
+ try {
2479
+ const result = await this.compact(options?.customInstructions);
2480
+ options?.onComplete?.(result);
2481
+ } catch (error) {
2482
+ const err = error instanceof Error ? error : new Error(String(error));
2483
+ options?.onError?.(err);
2484
+ }
2485
+ })();
2486
+ },
2487
+ getSystemPrompt: () => this.systemPrompt,
2488
+ getSystemPromptOptions: () => this._baseSystemPromptOptions,
2489
+ },
2490
+ {
2491
+ registerProvider: (name, config) => {
2492
+ this._modelRuntime.registerProvider(name, config);
2493
+ this._refreshCurrentModelFromRegistry();
2494
+ },
2495
+ unregisterProvider: (name) => {
2496
+ this._modelRuntime.unregisterProvider(name);
2497
+ this._refreshCurrentModelFromRegistry();
2498
+ },
2499
+ },
2500
+ );
2501
+ }
2502
+
2503
+ private _refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void {
2504
+ const previousRegistryNames = new Set(this._toolRegistry.keys());
2505
+ const previousActiveToolNames = this.getActiveToolNames();
2506
+ const allowedToolNames = this._allowedToolNames;
2507
+ const excludedToolNames = this._excludedToolNames;
2508
+ const isAllowedTool = (name: string): boolean =>
2509
+ (!allowedToolNames || allowedToolNames.has(name)) && !excludedToolNames?.has(name);
2510
+
2511
+ const registeredTools = this._extensionRunner.getAllRegisteredTools();
2512
+ const allCustomTools = [
2513
+ ...registeredTools,
2514
+ ...this._customTools.map((definition) => ({
2515
+ definition,
2516
+ sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
2517
+ })),
2518
+ ].filter((tool) => isAllowedTool(tool.definition.name));
2519
+ const definitionRegistry = new Map<string, ToolDefinitionEntry>(
2520
+ Array.from(this._baseToolDefinitions.entries())
2521
+ .filter(([name]) => isAllowedTool(name))
2522
+ .map(([name, definition]) => [
2523
+ name,
2524
+ {
2525
+ definition,
2526
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${name}>`, { source: "builtin" }),
2527
+ },
2528
+ ]),
2529
+ );
2530
+ for (const tool of allCustomTools) {
2531
+ definitionRegistry.set(tool.definition.name, {
2532
+ definition: tool.definition,
2533
+ sourceInfo: tool.sourceInfo,
2534
+ });
2535
+ }
2536
+ this._toolDefinitions = definitionRegistry;
2537
+ this._toolPromptSnippets = new Map(
2538
+ Array.from(definitionRegistry.values())
2539
+ .map(({ definition }) => {
2540
+ const snippet = this._normalizePromptSnippet(definition.promptSnippet);
2541
+ return snippet ? ([definition.name, snippet] as const) : undefined;
2542
+ })
2543
+ .filter((entry): entry is readonly [string, string] => entry !== undefined),
2544
+ );
2545
+ this._toolPromptGuidelines = new Map(
2546
+ Array.from(definitionRegistry.values())
2547
+ .map(({ definition }) => {
2548
+ const guidelines = this._normalizePromptGuidelines(definition.promptGuidelines);
2549
+ return guidelines.length > 0 ? ([definition.name, guidelines] as const) : undefined;
2550
+ })
2551
+ .filter((entry): entry is readonly [string, string[]] => entry !== undefined),
2552
+ );
2553
+ const runner = this._extensionRunner;
2554
+ const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
2555
+ const wrappedBuiltInTools = wrapRegisteredTools(
2556
+ Array.from(this._baseToolDefinitions.values())
2557
+ .filter((definition) => isAllowedTool(definition.name))
2558
+ .map((definition) => ({
2559
+ definition,
2560
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
2561
+ })),
2562
+ runner,
2563
+ );
2564
+
2565
+ const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
2566
+ for (const tool of wrappedExtensionTools as AgentTool[]) {
2567
+ toolRegistry.set(tool.name, tool);
2568
+ }
2569
+ this._toolRegistry = toolRegistry;
2570
+
2571
+ const nextActiveToolNames = (
2572
+ options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]
2573
+ ).filter((name) => isAllowedTool(name));
2574
+
2575
+ if (allowedToolNames) {
2576
+ for (const toolName of this._toolRegistry.keys()) {
2577
+ if (allowedToolNames.has(toolName)) {
2578
+ nextActiveToolNames.push(toolName);
2579
+ }
2580
+ }
2581
+ } else if (options?.includeAllExtensionTools) {
2582
+ for (const tool of wrappedExtensionTools) {
2583
+ nextActiveToolNames.push(tool.name);
2584
+ }
2585
+ } else if (!options?.activeToolNames) {
2586
+ for (const toolName of this._toolRegistry.keys()) {
2587
+ if (!previousRegistryNames.has(toolName)) {
2588
+ nextActiveToolNames.push(toolName);
2589
+ }
2590
+ }
2591
+ }
2592
+
2593
+ this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
2594
+ }
2595
+
2596
+ private _buildRuntime(options: {
2597
+ activeToolNames?: string[];
2598
+ flagValues?: Map<string, boolean | string>;
2599
+ includeAllExtensionTools?: boolean;
2600
+ }): void {
2601
+ const autoResizeImages = this.settingsManager.getImageAutoResize();
2602
+ const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
2603
+ const shellPath = this.settingsManager.getShellPath();
2604
+ const baseToolDefinitions = this._baseToolsOverride
2605
+ ? Object.fromEntries(
2606
+ Object.entries(this._baseToolsOverride).map(([name, tool]) => [
2607
+ name,
2608
+ createToolDefinitionFromAgentTool(tool),
2609
+ ]),
2610
+ )
2611
+ : createAllToolDefinitions(this._cwd, {
2612
+ read: { autoResizeImages },
2613
+ bash: { commandPrefix: shellCommandPrefix, shellPath },
2614
+ });
2615
+
2616
+ this._baseToolDefinitions = new Map(
2617
+ Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool as ToolDefinition]),
2618
+ );
2619
+
2620
+ const extensionsResult = this._resourceLoader.getExtensions();
2621
+ if (options.flagValues) {
2622
+ for (const [name, value] of options.flagValues) {
2623
+ extensionsResult.runtime.flagValues.set(name, value);
2624
+ }
2625
+ }
2626
+
2627
+ this._extensionRunner = new ExtensionRunner(
2628
+ extensionsResult.extensions,
2629
+ extensionsResult.runtime,
2630
+ this._cwd,
2631
+ this.sessionManager,
2632
+ new ModelRegistry(this._modelRuntime),
2633
+ );
2634
+ if (this._extensionRunnerRef) {
2635
+ this._extensionRunnerRef.current = this._extensionRunner;
2636
+ }
2637
+ this._bindExtensionCore(this._extensionRunner);
2638
+ this._applyExtensionBindings(this._extensionRunner);
2639
+
2640
+ const defaultActiveToolNames = this._baseToolsOverride
2641
+ ? Object.keys(this._baseToolsOverride)
2642
+ : ["read", "bash", "edit", "write"];
2643
+ const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
2644
+ this._refreshToolRegistry({
2645
+ activeToolNames: baseActiveToolNames,
2646
+ includeAllExtensionTools: options.includeAllExtensionTools,
2647
+ });
2648
+ }
2649
+
2650
+ async reload(options?: {
2651
+ beforeSessionStart?: () => void | Promise<void>;
2652
+ signal?: AbortSignal;
2653
+ sessionShutdownTimeoutMs?: number;
2654
+ }): Promise<void> {
2655
+ const previousFlagValues = this._extensionRunner.getFlagValues();
2656
+ const previousRunner = this._extensionRunner;
2657
+ try {
2658
+ const shutdown = beginSessionShutdownEvent(
2659
+ previousRunner,
2660
+ { type: "session_shutdown", reason: "reload" },
2661
+ {
2662
+ ...(options?.signal ? { signal: options.signal } : {}),
2663
+ ...(options?.sessionShutdownTimeoutMs !== undefined
2664
+ ? { timeoutMs: options.sessionShutdownTimeoutMs }
2665
+ : {}),
2666
+ },
2667
+ );
2668
+ this._trackExtensionSettlement(shutdown.settled);
2669
+ await shutdown.bounded;
2670
+ } finally {
2671
+ previousRunner.invalidate();
2672
+ }
2673
+ options?.signal?.throwIfAborted();
2674
+ await this.settingsManager.reload();
2675
+ options?.signal?.throwIfAborted();
2676
+ this.syncQueueModesFromSettings();
2677
+ resetApiProviders();
2678
+ await this._resourceLoader.reload(options?.signal ? { signal: options.signal } : undefined);
2679
+ if (options?.signal?.aborted) {
2680
+ this._resourceLoader.getExtensions().runtime.invalidate("Extension creation was aborted.");
2681
+ options.signal.throwIfAborted();
2682
+ }
2683
+ this._buildRuntime({
2684
+ activeToolNames: this.getActiveToolNames(),
2685
+ flagValues: previousFlagValues,
2686
+ includeAllExtensionTools: true,
2687
+ });
2688
+
2689
+ const hasBindings =
2690
+ this._extensionUIContext ||
2691
+ this._extensionCommandContextActions ||
2692
+ this._extensionShutdownHandler ||
2693
+ this._extensionErrorListener;
2694
+ if (hasBindings) {
2695
+ await options?.beforeSessionStart?.();
2696
+ await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
2697
+ await this.extendResourcesFromExtensions("reload");
2698
+ }
2699
+ }
2700
+
2701
+ // =========================================================================
2702
+ // Auto-Retry
2703
+ // =========================================================================
2704
+
2705
+ /**
2706
+ * Check if an error is retryable (overloaded, rate limit, server errors).
2707
+ * Context overflow errors are NOT retryable (handled by compaction instead).
2708
+ */
2709
+ private _isRetryableError(message: AssistantMessage): boolean {
2710
+ // Context overflow is handled by compaction, not retry.
2711
+ if (isContextOverflow(message, this.model?.contextWindow ?? 0)) return false;
2712
+ return isRetryableAssistantError(message);
2713
+ }
2714
+
2715
+ /**
2716
+ * Prepare a retryable error for continuation with exponential backoff.
2717
+ * @returns true if the caller should continue the agent, false otherwise
2718
+ */
2719
+ private async _prepareRetry(message: AssistantMessage): Promise<boolean> {
2720
+ const settings = this.settingsManager.getRetrySettings();
2721
+ if (!settings.enabled) {
2722
+ return false;
2723
+ }
2724
+
2725
+ this._retryAttempt++;
2726
+
2727
+ if (this._retryAttempt > settings.maxRetries) {
2728
+ // Preserve the completed attempt count so post-run handling can emit the final failure.
2729
+ this._retryAttempt--;
2730
+ return false;
2731
+ }
2732
+
2733
+ const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
2734
+
2735
+ this._emit({
2736
+ type: "auto_retry_start",
2737
+ attempt: this._retryAttempt,
2738
+ maxAttempts: settings.maxRetries,
2739
+ delayMs,
2740
+ errorMessage: message.errorMessage || "Unknown error",
2741
+ });
2742
+
2743
+ // Remove error message from agent state (keep in session for history)
2744
+ const messages = this.agent.state.messages;
2745
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
2746
+ this.agent.state.messages = messages.slice(0, -1);
2747
+ }
2748
+
2749
+ // Wait with exponential backoff (abortable)
2750
+ this._retryAbortController = new AbortController();
2751
+ try {
2752
+ await sleep(delayMs, this._retryAbortController.signal);
2753
+ } catch {
2754
+ // Aborted during sleep - emit end event so UI can clean up
2755
+ const attempt = this._retryAttempt;
2756
+ this._retryAttempt = 0;
2757
+ this._emit({
2758
+ type: "auto_retry_end",
2759
+ success: false,
2760
+ attempt,
2761
+ finalError: "Retry cancelled",
2762
+ });
2763
+ return false;
2764
+ } finally {
2765
+ this._retryAbortController = undefined;
2766
+ }
2767
+
2768
+ return true;
2769
+ }
2770
+
2771
+ /**
2772
+ * Cancel in-progress retry.
2773
+ */
2774
+ abortRetry(): void {
2775
+ this._retryAbortController?.abort();
2776
+ }
2777
+
2778
+ /** Whether auto-retry is currently in progress */
2779
+ get isRetrying(): boolean {
2780
+ return this._retryAbortController !== undefined;
2781
+ }
2782
+
2783
+ /** Whether auto-retry is enabled */
2784
+ get autoRetryEnabled(): boolean {
2785
+ return this.settingsManager.getRetryEnabled();
2786
+ }
2787
+
2788
+ /**
2789
+ * Toggle auto-retry setting.
2790
+ */
2791
+ setAutoRetryEnabled(enabled: boolean): void {
2792
+ this.settingsManager.setRetryEnabled(enabled);
2793
+ }
2794
+
2795
+ // =========================================================================
2796
+ // Bash Execution
2797
+ // =========================================================================
2798
+
2799
+ /**
2800
+ * Execute a bash command.
2801
+ * Adds result to agent context and session.
2802
+ * @param command The bash command to execute
2803
+ * @param onChunk Optional streaming callback for output
2804
+ * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
2805
+ * @param options.operations Custom BashOperations for remote execution
2806
+ */
2807
+ async executeBash(
2808
+ command: string,
2809
+ onChunk?: (chunk: string) => void,
2810
+ options?: { excludeFromContext?: boolean; operations?: BashOperations },
2811
+ ): Promise<BashResult> {
2812
+ this._bashAbortController = new AbortController();
2813
+
2814
+ // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
2815
+ const prefix = this.settingsManager.getShellCommandPrefix();
2816
+ const shellPath = this.settingsManager.getShellPath();
2817
+ const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
2818
+
2819
+ try {
2820
+ const result = await executeBashWithOperations(
2821
+ resolvedCommand,
2822
+ this.sessionManager.getCwd(),
2823
+ options?.operations ?? createLocalBashOperations({ shellPath }),
2824
+ {
2825
+ onChunk,
2826
+ signal: this._bashAbortController.signal,
2827
+ },
2828
+ );
2829
+
2830
+ this.recordBashResult(command, result, options);
2831
+ return result;
2832
+ } finally {
2833
+ this._bashAbortController = undefined;
2834
+ }
2835
+ }
2836
+
2837
+ /**
2838
+ * Record a bash execution result in session history.
2839
+ * Used by executeBash and by extensions that handle bash execution themselves.
2840
+ */
2841
+ recordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {
2842
+ const bashMessage: BashExecutionMessage = {
2843
+ role: "bashExecution",
2844
+ command,
2845
+ output: result.output,
2846
+ exitCode: result.exitCode,
2847
+ cancelled: result.cancelled,
2848
+ truncated: result.truncated,
2849
+ fullOutputPath: result.fullOutputPath,
2850
+ timestamp: Date.now(),
2851
+ excludeFromContext: options?.excludeFromContext,
2852
+ };
2853
+
2854
+ // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
2855
+ if (this.isStreaming) {
2856
+ // Queue for later - will be flushed on agent_end
2857
+ this._pendingBashMessages.push(bashMessage);
2858
+ } else {
2859
+ // Add to agent state immediately
2860
+ this.agent.state.messages.push(bashMessage);
2861
+
2862
+ // Save to session
2863
+ this.sessionManager.appendMessage(bashMessage);
2864
+ }
2865
+ }
2866
+
2867
+ /**
2868
+ * Cancel running bash command.
2869
+ */
2870
+ abortBash(): void {
2871
+ this._bashAbortController?.abort();
2872
+ }
2873
+
2874
+ /** Whether a bash command is currently running */
2875
+ get isBashRunning(): boolean {
2876
+ return this._bashAbortController !== undefined;
2877
+ }
2878
+
2879
+ /** Whether there are pending bash messages waiting to be flushed */
2880
+ get hasPendingBashMessages(): boolean {
2881
+ return this._pendingBashMessages.length > 0;
2882
+ }
2883
+
2884
+ /**
2885
+ * Flush pending bash messages to agent state and session.
2886
+ * Called after agent turn completes to maintain proper message ordering.
2887
+ */
2888
+ private _flushPendingBashMessages(): void {
2889
+ if (this._pendingBashMessages.length === 0) return;
2890
+
2891
+ for (const bashMessage of this._pendingBashMessages) {
2892
+ // Add to agent state
2893
+ this.agent.state.messages.push(bashMessage);
2894
+
2895
+ // Save to session
2896
+ this.sessionManager.appendMessage(bashMessage);
2897
+ }
2898
+
2899
+ this._pendingBashMessages = [];
2900
+ }
2901
+
2902
+ // =========================================================================
2903
+ // Session Management
2904
+ // =========================================================================
2905
+
2906
+ /**
2907
+ * Set a display name for the current session.
2908
+ */
2909
+ setSessionName(name: string): void {
2910
+ this.sessionManager.appendSessionInfo(name);
2911
+ const event = { type: "session_info_changed", name: this.sessionManager.getSessionName() } as const;
2912
+ this._emit(event);
2913
+ void this._extensionRunner.emit(event);
2914
+ }
2915
+
2916
+ // =========================================================================
2917
+ // Tree Navigation
2918
+ // =========================================================================
2919
+
2920
+ /**
2921
+ * Navigate to a different node in the session tree.
2922
+ * Unlike fork() which creates a new session file, this stays in the same file.
2923
+ *
2924
+ * @param targetId The entry ID to navigate to
2925
+ * @param options.summarize Whether user wants to summarize abandoned branch
2926
+ * @param options.customInstructions Custom instructions for summarizer
2927
+ * @param options.replaceInstructions If true, customInstructions replaces the default prompt
2928
+ * @param options.label Label to attach to the branch summary entry
2929
+ * @returns Result with editorText (if user message) and cancelled status
2930
+ */
2931
+ async navigateTree(
2932
+ targetId: string,
2933
+ options: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},
2934
+ ): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {
2935
+ const oldLeafId = this.sessionManager.getLeafId();
2936
+
2937
+ // No-op if already at target
2938
+ if (targetId === oldLeafId) {
2939
+ return { cancelled: false };
2940
+ }
2941
+
2942
+ // Model required for summarization
2943
+ if (options.summarize && !this.model) {
2944
+ throw new Error("No model available for summarization");
2945
+ }
2946
+
2947
+ const targetEntry = this.sessionManager.getEntry(targetId);
2948
+ if (!targetEntry) {
2949
+ throw new Error(`Entry ${targetId} not found`);
2950
+ }
2951
+
2952
+ // Collect entries to summarize (from old leaf to common ancestor)
2953
+ const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(
2954
+ this.sessionManager,
2955
+ oldLeafId,
2956
+ targetId,
2957
+ );
2958
+
2959
+ // Prepare event data - mutable so extensions can override
2960
+ let customInstructions = options.customInstructions;
2961
+ let replaceInstructions = options.replaceInstructions;
2962
+ let label = options.label;
2963
+
2964
+ const preparation: TreePreparation = {
2965
+ targetId,
2966
+ oldLeafId,
2967
+ commonAncestorId,
2968
+ entriesToSummarize,
2969
+ userWantsSummary: options.summarize ?? false,
2970
+ customInstructions,
2971
+ replaceInstructions,
2972
+ label,
2973
+ };
2974
+
2975
+ // Set up abort controller for summarization
2976
+ this._branchSummaryAbortController = new AbortController();
2977
+
2978
+ try {
2979
+ let extensionSummary: { summary: string; details?: unknown } | undefined;
2980
+ let fromExtension = false;
2981
+
2982
+ // Emit session_before_tree event
2983
+ if (this._extensionRunner.hasHandlers("session_before_tree")) {
2984
+ const result = (await this._extensionRunner.emit({
2985
+ type: "session_before_tree",
2986
+ preparation,
2987
+ signal: this._branchSummaryAbortController.signal,
2988
+ })) as SessionBeforeTreeResult | undefined;
2989
+
2990
+ if (result?.cancel) {
2991
+ return { cancelled: true };
2992
+ }
2993
+
2994
+ if (result?.summary && options.summarize) {
2995
+ extensionSummary = result.summary;
2996
+ fromExtension = true;
2997
+ }
2998
+
2999
+ // Allow extensions to override instructions and label
3000
+ if (result?.customInstructions !== undefined) {
3001
+ customInstructions = result.customInstructions;
3002
+ }
3003
+ if (result?.replaceInstructions !== undefined) {
3004
+ replaceInstructions = result.replaceInstructions;
3005
+ }
3006
+ if (result?.label !== undefined) {
3007
+ label = result.label;
3008
+ }
3009
+ }
3010
+
3011
+ // Run default summarizer if needed
3012
+ let summaryText: string | undefined;
3013
+ let summaryDetails: unknown;
3014
+ if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
3015
+ const model = this.model!;
3016
+ const { apiKey, headers, env } = await this._getSummarizationRequestAuth(model);
3017
+ const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
3018
+ const result = await generateBranchSummary(entriesToSummarize, {
3019
+ model,
3020
+ apiKey,
3021
+ headers,
3022
+ env,
3023
+ signal: this._branchSummaryAbortController.signal,
3024
+ customInstructions,
3025
+ replaceInstructions,
3026
+ reserveTokens: branchSummarySettings.reserveTokens,
3027
+ streamFn: this.agent.streamFn,
3028
+ });
3029
+ if (result.aborted) {
3030
+ return { cancelled: true, aborted: true };
3031
+ }
3032
+ if (result.error) {
3033
+ throw new Error(result.error);
3034
+ }
3035
+ summaryText = result.summary;
3036
+ summaryDetails = {
3037
+ readFiles: result.readFiles || [],
3038
+ modifiedFiles: result.modifiedFiles || [],
3039
+ };
3040
+ } else if (extensionSummary) {
3041
+ summaryText = extensionSummary.summary;
3042
+ summaryDetails = extensionSummary.details;
3043
+ }
3044
+
3045
+ // Determine the new leaf position based on target type
3046
+ let newLeafId: string | null;
3047
+ let editorText: string | undefined;
3048
+
3049
+ if (targetEntry.type === "message" && targetEntry.message.role === "user") {
3050
+ // User message: leaf = parent (null if root), text goes to editor
3051
+ newLeafId = targetEntry.parentId;
3052
+ editorText = this._extractUserMessageText(targetEntry.message.content);
3053
+ } else if (targetEntry.type === "custom_message") {
3054
+ // Custom message: leaf = parent (null if root), text goes to editor
3055
+ newLeafId = targetEntry.parentId;
3056
+ editorText =
3057
+ typeof targetEntry.content === "string"
3058
+ ? targetEntry.content
3059
+ : targetEntry.content
3060
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
3061
+ .map((c) => c.text)
3062
+ .join("");
3063
+ } else {
3064
+ // Non-user message: leaf = selected node
3065
+ newLeafId = targetId;
3066
+ }
3067
+
3068
+ // Switch leaf (with or without summary)
3069
+ // Summary is attached at the navigation target position (newLeafId), not the old branch
3070
+ let summaryEntry: BranchSummaryEntry | undefined;
3071
+ if (summaryText) {
3072
+ // Create summary at target position (can be null for root)
3073
+ const summaryId = this.sessionManager.branchWithSummary(
3074
+ newLeafId,
3075
+ summaryText,
3076
+ summaryDetails,
3077
+ fromExtension,
3078
+ );
3079
+ summaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;
3080
+
3081
+ // Attach label to the summary entry
3082
+ if (label) {
3083
+ this.sessionManager.appendLabelChange(summaryId, label);
3084
+ }
3085
+ } else if (newLeafId === null) {
3086
+ // No summary, navigating to root - reset leaf
3087
+ this.sessionManager.resetLeaf();
3088
+ } else {
3089
+ // No summary, navigating to non-root
3090
+ this.sessionManager.branch(newLeafId);
3091
+ }
3092
+
3093
+ // Attach label to target entry when not summarizing (no summary entry to label)
3094
+ if (label && !summaryText) {
3095
+ this.sessionManager.appendLabelChange(targetId, label);
3096
+ }
3097
+
3098
+ // Update agent state
3099
+ const sessionContext = this.sessionManager.buildSessionContext();
3100
+ this.agent.state.messages = sessionContext.messages;
3101
+
3102
+ // Emit session_tree event
3103
+ await this._extensionRunner.emit({
3104
+ type: "session_tree",
3105
+ newLeafId: this.sessionManager.getLeafId(),
3106
+ oldLeafId,
3107
+ summaryEntry,
3108
+ fromExtension: summaryText ? fromExtension : undefined,
3109
+ });
3110
+
3111
+ // Emit to custom tools
3112
+
3113
+ return { editorText, cancelled: false, summaryEntry };
3114
+ } finally {
3115
+ this._branchSummaryAbortController = undefined;
3116
+ }
3117
+ }
3118
+
3119
+ /**
3120
+ * Get all user messages from session for fork selector.
3121
+ */
3122
+ getUserMessagesForForking(): Array<{ entryId: string; text: string }> {
3123
+ const entries = this.sessionManager.getEntries();
3124
+ const result: Array<{ entryId: string; text: string }> = [];
3125
+
3126
+ for (const entry of entries) {
3127
+ if (entry.type !== "message") continue;
3128
+ if (entry.message.role !== "user") continue;
3129
+
3130
+ const text = this._extractUserMessageText(entry.message.content);
3131
+ if (text) {
3132
+ result.push({ entryId: entry.id, text });
3133
+ }
3134
+ }
3135
+
3136
+ return result;
3137
+ }
3138
+
3139
+ private _extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {
3140
+ if (typeof content === "string") return content;
3141
+ if (Array.isArray(content)) {
3142
+ return content
3143
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
3144
+ .map((c) => c.text)
3145
+ .join("");
3146
+ }
3147
+ return "";
3148
+ }
3149
+
3150
+ /**
3151
+ * Get session statistics. Aggregates over ALL session entries (including
3152
+ * history that was compacted away), so token/cost totals reflect what was
3153
+ * actually billed across the session.
3154
+ */
3155
+ getSessionStats(): SessionStats {
3156
+ let userMessages = 0;
3157
+ let assistantMessages = 0;
3158
+ let toolResults = 0;
3159
+ let totalMessages = 0;
3160
+ let toolCalls = 0;
3161
+ let totalInput = 0;
3162
+ let totalOutput = 0;
3163
+ let totalCacheRead = 0;
3164
+ let totalCacheWrite = 0;
3165
+ let totalCost = 0;
3166
+
3167
+ for (const entry of this.sessionManager.getEntries()) {
3168
+ if (entry.type !== "message") continue;
3169
+ totalMessages++;
3170
+ const message = entry.message;
3171
+ if (message.role === "user") {
3172
+ userMessages++;
3173
+ } else if (message.role === "toolResult") {
3174
+ toolResults++;
3175
+ } else if (message.role === "assistant") {
3176
+ assistantMessages++;
3177
+ const assistantMsg = message as AssistantMessage;
3178
+ if (Array.isArray(assistantMsg.content)) {
3179
+ toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
3180
+ }
3181
+ const usage = assistantMsg.usage;
3182
+ totalInput += usage.input;
3183
+ totalOutput += usage.output;
3184
+ totalCacheRead += usage.cacheRead;
3185
+ totalCacheWrite += usage.cacheWrite;
3186
+ totalCost += usage.cost.total;
3187
+ }
3188
+ }
3189
+
3190
+ return {
3191
+ sessionFile: this.sessionFile,
3192
+ sessionId: this.sessionId,
3193
+ userMessages,
3194
+ assistantMessages,
3195
+ toolCalls,
3196
+ toolResults,
3197
+ totalMessages,
3198
+ tokens: {
3199
+ input: totalInput,
3200
+ output: totalOutput,
3201
+ cacheRead: totalCacheRead,
3202
+ cacheWrite: totalCacheWrite,
3203
+ total: totalInput + totalOutput + totalCacheRead + totalCacheWrite,
3204
+ },
3205
+ cost: totalCost,
3206
+ contextUsage: this.getContextUsage(),
3207
+ };
3208
+ }
3209
+
3210
+ getContextUsage(): ContextUsage | undefined {
3211
+ const model = this.model;
3212
+ if (!model) return undefined;
3213
+
3214
+ const contextWindow = model.contextWindow ?? 0;
3215
+ if (contextWindow <= 0) return undefined;
3216
+
3217
+ // After compaction, the last assistant usage reflects pre-compaction context size.
3218
+ // We can only trust usage from an assistant that responded after the latest compaction.
3219
+ // If no such assistant exists, context token count is unknown until the next LLM response.
3220
+ const branchEntries = this.sessionManager.getBranch();
3221
+ const latestCompaction = getLatestCompactionEntry(branchEntries);
3222
+
3223
+ if (latestCompaction) {
3224
+ // Check if there's a valid assistant usage after the compaction boundary
3225
+ const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
3226
+ let hasPostCompactionUsage = false;
3227
+ for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
3228
+ const entry = branchEntries[i];
3229
+ if (entry.type === "message" && entry.message.role === "assistant") {
3230
+ const assistant = entry.message;
3231
+ if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
3232
+ const contextTokens = calculateContextTokens(assistant.usage);
3233
+ if (contextTokens > 0) {
3234
+ hasPostCompactionUsage = true;
3235
+ break;
3236
+ }
3237
+ }
3238
+ }
3239
+ }
3240
+
3241
+ if (!hasPostCompactionUsage) {
3242
+ return { tokens: null, contextWindow, percent: null };
3243
+ }
3244
+ }
3245
+
3246
+ const estimate = estimateContextTokens(this.messages);
3247
+ const percent = (estimate.tokens / contextWindow) * 100;
3248
+
3249
+ return {
3250
+ tokens: estimate.tokens,
3251
+ contextWindow,
3252
+ percent,
3253
+ };
3254
+ }
3255
+
3256
+
3257
+
3258
+ /**
3259
+ * Export the current session branch to a JSONL file.
3260
+ * Writes the session header followed by all entries on the current branch path.
3261
+ * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
3262
+ * @returns The resolved output file path.
3263
+ */
3264
+ exportToJsonl(outputPath?: string): string {
3265
+ const filePath = resolvePath(
3266
+ outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`,
3267
+ process.cwd(),
3268
+ );
3269
+ const dir = dirname(filePath);
3270
+ if (!existsSync(dir)) {
3271
+ mkdirSync(dir, { recursive: true });
3272
+ }
3273
+
3274
+ const header: SessionHeader = {
3275
+ type: "session",
3276
+ version: CURRENT_SESSION_VERSION,
3277
+ id: this.sessionManager.getSessionId(),
3278
+ timestamp: new Date().toISOString(),
3279
+ cwd: this.sessionManager.getCwd(),
3280
+ };
3281
+
3282
+ const branchEntries = this.sessionManager.getBranch();
3283
+ const lines = [JSON.stringify(header)];
3284
+
3285
+ // Re-chain parentIds to form a linear sequence
3286
+ let prevId: string | null = null;
3287
+ for (const entry of branchEntries) {
3288
+ const linear = { ...entry, parentId: prevId };
3289
+ lines.push(JSON.stringify(linear));
3290
+ prevId = entry.id;
3291
+ }
3292
+
3293
+ writeFileSync(filePath, `${lines.join("\n")}\n`);
3294
+ return filePath;
3295
+ }
3296
+
3297
+ // =========================================================================
3298
+ // Utilities
3299
+ // =========================================================================
3300
+
3301
+ /**
3302
+ * Get text content of last assistant message.
3303
+ * Useful for /copy command.
3304
+ * @returns Text content, or undefined if no assistant message exists
3305
+ */
3306
+ getLastAssistantText(): string | undefined {
3307
+ const lastAssistant = this.messages
3308
+ .slice()
3309
+ .reverse()
3310
+ .find((m) => {
3311
+ if (m.role !== "assistant") return false;
3312
+ const msg = m as AssistantMessage;
3313
+ // Skip aborted messages with no content
3314
+ if (msg.stopReason === "aborted" && msg.content.length === 0) return false;
3315
+ return true;
3316
+ });
3317
+
3318
+ if (!lastAssistant) return undefined;
3319
+
3320
+ let text = "";
3321
+ for (const content of (lastAssistant as AssistantMessage).content) {
3322
+ if (content.type === "text") {
3323
+ text += content.text;
3324
+ }
3325
+ }
3326
+
3327
+ return text.trim() || undefined;
3328
+ }
3329
+
3330
+ // =========================================================================
3331
+ // Extension System
3332
+ // =========================================================================
3333
+
3334
+ createReplacedSessionContext(): ReplacedSessionContext {
3335
+ const context = Object.defineProperties(
3336
+ {},
3337
+ Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()),
3338
+ ) as ReplacedSessionContext;
3339
+ context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
3340
+ context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
3341
+ return context;
3342
+ }
3343
+
3344
+ /**
3345
+ * Check if extensions have handlers for a specific event type.
3346
+ */
3347
+ hasExtensionHandlers(eventType: string): boolean {
3348
+ return this._extensionRunner.hasHandlers(eventType);
3349
+ }
3350
+
3351
+ /**
3352
+ * Get the extension runner (for setting UI context and error handlers).
3353
+ */
3354
+ get extensionRunner(): ExtensionRunner {
3355
+ return this._extensionRunner;
3356
+ }
3357
+ }