@kabmo-labs/kabmo 0.24.0 → 0.26.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 (325) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +585 -512
  3. package/dist/client/static/js/{index-jcr5twtp.js → index-95b3n20k.js} +1105 -1207
  4. package/dist/client/static/js/index-p2yw9ywf.css +1 -0
  5. package/package.json +2 -4
  6. package/src/cli/lib/args.js +24 -1
  7. package/src/cli/lib/args.test.js +16 -0
  8. package/src/cli/lib/commands/session.js +233 -0
  9. package/src/cli/lib/commands/session.test.js +103 -0
  10. package/src/cli/main.js +1 -1
  11. package/src/client/components/common/ComposerPicker.tsx +3 -0
  12. package/src/client/components/common/code-surface/shiki.test.ts +82 -0
  13. package/src/client/components/common/code-surface/shiki.ts +28 -7
  14. package/src/client/components/common/session-actions-menu/index.tsx +59 -2
  15. package/src/client/components/common/session-branch/BranchGuides.tsx +93 -0
  16. package/src/client/components/common/session-branch/SubagentRow.tsx +77 -0
  17. package/src/client/components/common/session-branch/index.tsx +169 -0
  18. package/src/client/components/common/session-branch/session-branch.test.tsx +240 -0
  19. package/src/client/components/common/session-branch/style.ts +29 -0
  20. package/src/client/components/common/session-row/StatusSlot.tsx +17 -5
  21. package/src/client/components/common/session-row/index.tsx +28 -3
  22. package/src/client/components/common/session-row/session-row.test.tsx +11 -0
  23. package/src/client/components/common/session-state-provider/index.tsx +1 -1
  24. package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
  25. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +70 -61
  26. package/src/client/components/layout/session-sidebar/SessionItem.batch.test.ts +3 -3
  27. package/src/client/components/layout/session-sidebar/SessionItem.test.ts +25 -2
  28. package/src/client/components/layout/session-sidebar/SessionItem.tsx +35 -7
  29. package/src/client/components/layout/session-sidebar/about-modal/HarnessRow.tsx +261 -0
  30. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +39 -198
  31. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +114 -0
  32. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
  33. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +128 -0
  34. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +56 -0
  35. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +44 -36
  36. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +62 -47
  37. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +63 -50
  38. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.test.ts +5 -0
  39. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +37 -12
  40. package/src/client/components/settings/Sidebar.tsx +1 -1
  41. package/src/client/components/settings/categories/NotificationSettings.test.tsx +92 -0
  42. package/src/client/components/settings/categories/NotificationSettings.tsx +112 -2
  43. package/src/client/components/settings/categories/harness-settings/HarnessCard.tsx +1 -1
  44. package/src/client/components/workspace/chat-timeline/AiMessageFooter.fork.test.ts +94 -0
  45. package/src/client/components/workspace/chat-timeline/AiMessageFooter.tsx +31 -5
  46. package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
  47. package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
  48. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +128 -122
  49. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
  50. package/src/client/components/workspace/chat-timeline/MessageList.tsx +11 -5
  51. package/src/client/components/workspace/chat-timeline/PendingChatView.tsx +10 -0
  52. package/src/client/components/workspace/chat-timeline/RunFooter.tsx +12 -3
  53. package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
  54. package/src/client/components/workspace/chat-timeline/chat-input/AttachmentToolbar.tsx +2 -0
  55. package/src/client/components/workspace/chat-timeline/chat-input/ModeToggles.tsx +15 -1
  56. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.test.tsx +85 -0
  57. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.tsx +84 -0
  58. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.tsx +2 -0
  59. package/src/client/components/workspace/chat-timeline/chat-input/modes-props.ts +5 -0
  60. package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
  61. package/src/client/components/workspace/chat-timeline/index.tsx +11 -20
  62. package/src/client/components/workspace/chat-timeline/target-picker/DraftTargetRow.tsx +115 -0
  63. package/src/client/components/workspace/chat-timeline/target-picker/ParentSessionPicker.tsx +173 -0
  64. package/src/client/components/workspace/chat-timeline/target-picker/parent-session-options.test.ts +49 -0
  65. package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
  66. package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
  67. package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
  68. package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
  69. package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
  70. package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
  71. package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
  72. package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
  73. package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
  74. package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
  75. package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
  76. package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
  77. package/src/client/data/settings/omp-schema.json +1 -1
  78. package/src/client/data/theme/terminal.test.ts +25 -0
  79. package/src/client/data/theme/terminal.ts +96 -79
  80. package/src/client/hooks/chat/composer/items.test.ts +31 -26
  81. package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
  82. package/src/client/hooks/chat/omp/folder-auto-expand.ts +1 -1
  83. package/src/client/hooks/chat/omp/pending-adoption.ts +51 -0
  84. package/src/client/hooks/chat/omp/pending-child.test.ts +73 -0
  85. package/src/client/hooks/chat/omp/pending-entry.ts +59 -0
  86. package/src/client/hooks/chat/omp/pending-rows.ts +6 -2
  87. package/src/client/hooks/chat/omp/pending-sessions.test.ts +1 -2
  88. package/src/client/hooks/chat/omp/pending-sessions.ts +45 -69
  89. package/src/client/hooks/chat/omp/pending-waiting.ts +1 -1
  90. package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
  91. package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
  92. package/src/client/hooks/chat/omp/run-switch.ts +1 -1
  93. package/src/client/hooks/chat/omp/session-list.tsx +4 -0
  94. package/src/client/hooks/chat/subagents/roster.ts +122 -0
  95. package/src/client/hooks/chat/timeline/child-spawn.test.ts +55 -0
  96. package/src/client/hooks/chat/timeline/child-spawn.ts +45 -0
  97. package/src/client/hooks/chat/timeline/fork-request.test.ts +54 -0
  98. package/src/client/hooks/chat/timeline/fork-request.ts +43 -0
  99. package/src/client/hooks/chat/timeline/mode-availability.test.ts +1 -1
  100. package/src/client/hooks/chat/timeline/mode-availability.ts +33 -0
  101. package/src/client/hooks/chat/timeline/mode-markers.ts +7 -1
  102. package/src/client/hooks/chat/timeline/mode-post.ts +15 -3
  103. package/src/client/hooks/chat/timeline/modes-contract.ts +9 -4
  104. package/src/client/hooks/chat/timeline/modes.test.ts +56 -18
  105. package/src/client/hooks/chat/timeline/modes.ts +42 -29
  106. package/src/client/hooks/chat/timeline/pending-branch.ts +205 -0
  107. package/src/client/hooks/chat/timeline/pending-dispatch.ts +253 -0
  108. package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
  109. package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
  110. package/src/client/hooks/chat/timeline/send-execute.test.ts +39 -0
  111. package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
  112. package/src/client/hooks/chat/timeline/send-steer.test.ts +3 -1
  113. package/src/client/hooks/chat/timeline/send.test-util.ts +7 -1
  114. package/src/client/hooks/chat/timeline/send.test.ts +3 -1
  115. package/src/client/hooks/chat/timeline/send.ts +48 -133
  116. package/src/client/hooks/chat/timeline/session-harness.ts +6 -0
  117. package/src/client/hooks/chat/timeline/stop-with-queue.ts +42 -0
  118. package/src/client/hooks/chat/timeline/use-fork-session.ts +58 -0
  119. package/src/client/hooks/models/use-harness-update.test.ts +286 -0
  120. package/src/client/hooks/models/use-harness-update.ts +250 -0
  121. package/src/client/hooks/ui/input-required-alert.ts +12 -5
  122. package/src/client/hooks/ui/notifications.ts +45 -0
  123. package/src/client/hooks/ui/run-outcome-alert.ts +48 -0
  124. package/src/client/hooks/workspace/expanded-sessions.ts +36 -7
  125. package/src/client/hooks/workspace/terminal/index.ts +17 -3
  126. package/src/client/hooks/workspace/terminal/socket.ts +9 -4
  127. package/src/client/lib/native/open-session.ts +33 -0
  128. package/src/client/lib/notifications/os.test.ts +125 -0
  129. package/src/client/lib/notifications/os.ts +130 -0
  130. package/src/client/lib/plugins/sidebar-bridge.ts +2 -20
  131. package/src/client/lib/router/open-session.test.ts +75 -0
  132. package/src/client/lib/router/open-session.ts +34 -0
  133. package/src/client/lib/session-tree.test.ts +50 -0
  134. package/src/client/lib/session-tree.ts +59 -0
  135. package/src/client/lib/signals.ts +5 -1
  136. package/src/client/main.tsx +6 -0
  137. package/src/client/tailwind.css +17 -11
  138. package/src/server/index.ts +2 -0
  139. package/src/server/lib/auth/guard.ts +10 -0
  140. package/src/server/lib/btw/session-copy.server.ts +6 -44
  141. package/src/server/lib/btw/session-copy.test.ts +2 -1
  142. package/src/server/lib/db/schema.ts +5 -0
  143. package/src/server/lib/db/seed-terminal.test.ts +1 -1
  144. package/src/server/lib/db/seed.test.ts +1 -1
  145. package/src/server/lib/harness/acp/background-work.test.ts +262 -0
  146. package/src/server/lib/harness/acp/background-work.ts +320 -0
  147. package/src/server/lib/harness/acp/calls.ts +15 -1
  148. package/src/server/lib/harness/acp/client-capabilities.test.ts +55 -0
  149. package/src/server/lib/harness/acp/client-capabilities.ts +61 -0
  150. package/src/server/lib/harness/acp/client-fs.test.ts +135 -0
  151. package/src/server/lib/harness/acp/client-fs.ts +131 -0
  152. package/src/server/lib/harness/acp/client-initialize.test.ts +70 -0
  153. package/src/server/lib/harness/acp/client-initialize.ts +84 -0
  154. package/src/server/lib/harness/acp/client.ts +33 -23
  155. package/src/server/lib/harness/acp/commands.test.ts +5 -5
  156. package/src/server/lib/harness/acp/commands.ts +14 -2
  157. package/src/server/lib/harness/acp/frames-timing.test.ts +68 -0
  158. package/src/server/lib/harness/acp/frames-v2.test.ts +85 -0
  159. package/src/server/lib/harness/acp/frames.ts +71 -158
  160. package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
  161. package/src/server/lib/harness/acp/gateway-env.ts +70 -0
  162. package/src/server/lib/harness/acp/mapper.test.ts +40 -0
  163. package/src/server/lib/harness/acp/mapper.ts +12 -0
  164. package/src/server/lib/harness/acp/permissions.ts +6 -0
  165. package/src/server/lib/harness/acp/prompt.test.ts +20 -0
  166. package/src/server/lib/harness/acp/prompt.ts +19 -3
  167. package/src/server/lib/harness/acp/protocol.ts +41 -2
  168. package/src/server/lib/harness/acp/session-background.test.ts +129 -0
  169. package/src/server/lib/harness/acp/session-exit.ts +31 -0
  170. package/src/server/lib/harness/acp/session-facts.ts +1 -1
  171. package/src/server/lib/harness/acp/session-handshake.test.ts +197 -0
  172. package/src/server/lib/harness/acp/session-handshake.ts +110 -7
  173. package/src/server/lib/harness/acp/session-idle.ts +7 -6
  174. package/src/server/lib/harness/acp/session-listeners.ts +31 -0
  175. package/src/server/lib/harness/acp/session-notifications.ts +41 -2
  176. package/src/server/lib/harness/acp/session-observers.test.ts +63 -0
  177. package/src/server/lib/harness/acp/session-permissions.test.ts +29 -0
  178. package/src/server/lib/harness/acp/session-permissions.ts +36 -0
  179. package/src/server/lib/harness/acp/session-requests.test.ts +92 -0
  180. package/src/server/lib/harness/acp/session-requests.ts +89 -0
  181. package/src/server/lib/harness/acp/session-turns.ts +28 -8
  182. package/src/server/lib/harness/acp/session-usage.ts +4 -0
  183. package/src/server/lib/harness/acp/session-web-state.ts +30 -2
  184. package/src/server/lib/harness/acp/session.test-util.ts +42 -2
  185. package/src/server/lib/harness/acp/session.ts +115 -115
  186. package/src/server/lib/harness/acp/tool-calls.ts +223 -0
  187. package/src/server/lib/harness/acp/turn.test.ts +183 -0
  188. package/src/server/lib/harness/acp/turn.ts +102 -10
  189. package/src/server/lib/harness/acp/v2.test.ts +144 -0
  190. package/src/server/lib/harness/acp/v2.ts +220 -0
  191. package/src/server/lib/harness/acp/verbs.ts +58 -8
  192. package/src/server/lib/harness/launch.test.ts +25 -0
  193. package/src/server/lib/harness/launch.ts +24 -10
  194. package/src/server/lib/harness/session.ts +3 -0
  195. package/src/server/lib/harness/spawn.server.ts +15 -2
  196. package/src/server/lib/harness/update-job-store.test.ts +151 -0
  197. package/src/server/lib/harness/update-job-store.ts +115 -0
  198. package/src/server/lib/harness/update-job.server.ts +94 -0
  199. package/src/server/lib/harness/update-queue.server.ts +292 -0
  200. package/src/server/lib/harness/update-queue.test.ts +265 -0
  201. package/src/server/lib/harness/update-spawn.server.ts +96 -0
  202. package/src/server/lib/harness/update-worker.test.ts +153 -0
  203. package/src/server/lib/harness/update-worker.ts +202 -0
  204. package/src/server/lib/lifecycle/after-listen.ts +9 -0
  205. package/src/server/lib/lifecycle/paths.ts +28 -0
  206. package/src/server/lib/omp/rpc/manager.ts +5 -5
  207. package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
  208. package/src/server/lib/omp/rpc/run-settle.server.ts +10 -1
  209. package/src/server/lib/omp/rpc/session-registry.ts +14 -2
  210. package/src/server/lib/omp/rpc/subagent-liveness.ts +5 -5
  211. package/src/server/lib/omp/rpc/terminal-settle.ts +58 -6
  212. package/src/server/lib/omp/session/delete-flow.server.ts +48 -0
  213. package/src/server/lib/omp/session/delete.server.ts +5 -0
  214. package/src/server/lib/omp/session/rewind-file.ts +39 -21
  215. package/src/server/lib/omp/session/sidebar-data.server.ts +16 -18
  216. package/src/server/lib/omp/session/transcript-copy.ts +123 -0
  217. package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
  218. package/src/server/lib/sessions/agent-token.server.ts +134 -0
  219. package/src/server/lib/sessions/answers.server.test.ts +33 -0
  220. package/src/server/lib/sessions/answers.server.ts +37 -0
  221. package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
  222. package/src/server/lib/sessions/dispatch.server.ts +128 -0
  223. package/src/server/lib/sessions/fork.server.test.ts +277 -0
  224. package/src/server/lib/sessions/fork.server.ts +329 -0
  225. package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
  226. package/src/server/lib/sessions/lifecycle.server.ts +71 -0
  227. package/src/server/lib/sessions/notify.server.test.ts +112 -0
  228. package/src/server/lib/sessions/notify.server.ts +212 -0
  229. package/src/server/lib/sessions/relation-types.ts +76 -0
  230. package/src/server/lib/sessions/relations.server.test.ts +207 -0
  231. package/src/server/lib/sessions/relations.server.ts +337 -0
  232. package/src/server/lib/sessions/resolve.server.ts +106 -0
  233. package/src/server/lib/sessions/schema.server.ts +82 -0
  234. package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
  235. package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
  236. package/src/server/lib/sessions/spawn.server.test.ts +237 -0
  237. package/src/server/lib/sessions/spawn.server.ts +335 -0
  238. package/src/server/lib/terminal/attach-replay.test.ts +2 -2
  239. package/src/server/lib/terminal/output.test.ts +2 -2
  240. package/src/server/lib/terminal/output.ts +1 -1
  241. package/src/server/lib/terminal/resize.test.ts +99 -0
  242. package/src/server/lib/terminal/runtime.server.ts +26 -6
  243. package/src/server/lib/terminal/send-result.test.ts +18 -1
  244. package/src/server/lib/terminal/send-result.ts +26 -2
  245. package/src/server/lib/terminal/session.server.ts +6 -6
  246. package/src/server/lib/usage/new-api.test.ts +92 -0
  247. package/src/server/lib/usage/new-api.ts +131 -0
  248. package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
  249. package/src/server/lib/usage/provider-key.ts +33 -0
  250. package/src/server/lib/usage/providers.server.ts +10 -3
  251. package/src/server/lib/usage/vendor-balance.server.ts +4 -53
  252. package/src/server/lib/usage/vendor-http.ts +41 -0
  253. package/src/server/lib/usage/window.ts +55 -0
  254. package/src/server/routes/agent/command.ts +14 -1
  255. package/src/server/routes/agent/harness-command.ts +12 -5
  256. package/src/server/routes/agent/new.ts +15 -0
  257. package/src/server/routes/chat/stream.ts +7 -2
  258. package/src/server/routes/harness/add-provider.test.ts +9 -1
  259. package/src/server/routes/harness/import-action.ts +4 -0
  260. package/src/server/routes/harness/import.test.ts +1 -1
  261. package/src/server/routes/harness/index.ts +5 -1
  262. package/src/server/routes/harness/update-status.ts +32 -0
  263. package/src/server/routes/harness/update.test.ts +156 -0
  264. package/src/server/routes/harness/update.ts +64 -147
  265. package/src/server/routes/sessions/answer.ts +24 -0
  266. package/src/server/routes/sessions/batch-delete.ts +11 -5
  267. package/src/server/routes/sessions/body-readers.ts +43 -0
  268. package/src/server/routes/sessions/delete.ts +4 -2
  269. package/src/server/routes/sessions/fork.ts +89 -0
  270. package/src/server/routes/sessions/index.ts +14 -0
  271. package/src/server/routes/sessions/relations.ts +85 -0
  272. package/src/server/routes/sessions/routes.test.ts +1 -2
  273. package/src/server/routes/sessions/session.ts +23 -0
  274. package/src/server/routes/sessions/spawn.ts +137 -0
  275. package/src/server/routes/terminal/ws.ts +3 -3
  276. package/src/shared/lib/chat/composer/client.ts +31 -2
  277. package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
  278. package/src/shared/lib/chat/composer/delegation.ts +206 -0
  279. package/src/shared/lib/chat/notice-text.ts +1 -1
  280. package/src/shared/lib/chat/omp/agent-events.ts +11 -0
  281. package/src/shared/lib/chat/omp/session-modes-signal.test.ts +41 -0
  282. package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
  283. package/src/shared/lib/code/ansi.ts +1 -1
  284. package/src/shared/lib/fonts/nerd-symbols.css +4 -3
  285. package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
  286. package/src/shared/lib/harness/mode-signal.ts +20 -0
  287. package/src/shared/lib/harness/provider-facts.test.ts +27 -0
  288. package/src/shared/lib/harness/providers.ts +35 -1
  289. package/src/shared/lib/harness/session-modes.ts +24 -0
  290. package/src/shared/lib/harness/update-job.ts +80 -0
  291. package/src/shared/lib/harness/update-plan.test.ts +21 -6
  292. package/src/shared/lib/harness/update-plan.ts +12 -4
  293. package/src/shared/lib/icons/tint-hues.generated.ts +34 -34
  294. package/src/shared/lib/notifications/outcomes.test.ts +96 -0
  295. package/src/shared/lib/notifications/outcomes.ts +64 -0
  296. package/src/shared/lib/notifications/settings.test.ts +49 -0
  297. package/src/shared/lib/notifications/settings.ts +34 -0
  298. package/src/shared/lib/omp/session/default-title.ts +5 -4
  299. package/src/shared/lib/omp/session/prewarm-misc.test.ts +3 -2
  300. package/src/shared/lib/omp/session/schema-migrations.ts +4 -0
  301. package/src/shared/lib/omp/session/stream-state.server.test.ts +19 -0
  302. package/src/shared/lib/omp/session/stream-state.server.ts +24 -4
  303. package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
  304. package/src/shared/lib/omp/session/wait-idle.ts +12 -2
  305. package/src/shared/lib/settings/defaults.ts +3 -0
  306. package/src/shared/lib/theme/catalog.test.ts +13 -9
  307. package/src/shared/lib/theme/color.test.ts +2 -2
  308. package/src/shared/lib/theme/color.ts +4 -4
  309. package/src/shared/lib/theme/theme.test.ts +1 -1
  310. package/src/shared/lib/workspace/terminal/input.test.ts +27 -0
  311. package/src/shared/lib/workspace/terminal/input.ts +33 -0
  312. package/src/shared/lib/workspace/terminal/keys.test.ts +1 -1
  313. package/src/shared/lib/workspace/terminal/keys.ts +7 -7
  314. package/src/shared/types/chat.ts +1 -1
  315. package/src/shared/types/harness-update.ts +89 -0
  316. package/src/shared/types/omp/agent.ts +19 -2
  317. package/src/shared/types/realtime.ts +2 -0
  318. package/src/shared/types/settings/state.ts +10 -0
  319. package/src/shared/types/workspace.ts +8 -0
  320. package/src/test-support/fake-omp-fork.ts +16 -2
  321. package/src/test-support/harness-table.test-util.ts +31 -1
  322. package/dist/client/static/js/index-z3w7n85q.css +0 -1
  323. package/src/client/components/common/subagent-list/index.tsx +0 -165
  324. package/src/client/components/workspace/terminal-panel/webgl.test.ts +0 -75
  325. package/src/client/components/workspace/terminal-panel/webgl.ts +0 -108
@@ -8,34 +8,43 @@
8
8
  * the `HarnessSession` contract every route already speaks.
9
9
  *
10
10
  * It owns the session's own state — the id, the config selectors, the resolved
11
- * model, the run flags the sidebar spinner and the queue's delivery gate read,
12
- * the agent's command list, and the approval queue a reloaded tab replays. The
13
- * RULES for each of those live beside it, one module per concern:
14
- * `session-handshake.ts` (initialize/new/load + the picks), `session-turns.ts`
15
- * (the ACK contract and turn-end bookkeeping), `session-config.ts` (adopting a
16
- * config answer, answering a parked dialog), `session-permissions.ts` (the
17
- * tier that answers before a dialog exists), `session-facts.ts` (the metadata an
18
- * agent publishes about itself between turns) and `session-web-state.ts`
19
- * (`get_state`, in the shape the omp transport reports it).
11
+ * model, the run flags the sidebar spinner and the queue delivery gate read, the
12
+ * agent's commands and the approval queue a reloaded tab replays. The RULES live
13
+ * beside it, one module per concern: `session-handshake.ts` (initialize/new/load
14
+ * + the picks), `session-turns.ts` (the ACK contract and turn-end bookkeeping),
15
+ * `session-config.ts` (config answers, parked dialogs), `session-permissions.ts`
16
+ * (the tier that answers before a dialog exists), `session-facts.ts` (what an
17
+ * agent publishes between turns) and `session-web-state.ts` (`get_state`).
20
18
  *
21
- * `send()` accepts the SAME command vocabulary the routes already send omp, so
19
+ * `send()` takes the SAME command vocabulary the routes already send omp, so
22
20
  * `routes/agent/command.ts` needs no second dispatch table.
23
21
  */
24
22
 
25
23
  import { AcpProcess } from '@/server/lib/harness/acp/client';
26
- import { AcpTurns } from '@/server/lib/harness/acp/turn';
24
+ import { AcpTurns, type AcpTurnEndInfo } from '@/server/lib/harness/acp/turn';
27
25
  import { AcpFrameMapper } from '@/server/lib/harness/acp/frames';
28
- import type { AcpConfigOption, AcpId } from '@/server/lib/harness/acp/protocol';
26
+ import type { AcpConfigOption, AcpId, AcpProtocolVersion, AcpSessionModeState } from '@/server/lib/harness/acp/protocol';
29
27
  import { promptBlocks } from '@/server/lib/harness/acp/prompt';
28
+ import { withGatewayCompatibility } from '@/server/lib/harness/acp/gateway-env';
30
29
  import { adoptConfigAnswer, publishConfigChange, settlePermissionDialog, stampMessageModel } from '@/server/lib/harness/acp/session-config';
31
30
  import { beginAcpTurn, settleAcpTurn } from '@/server/lib/harness/acp/session-turns';
32
31
  import { driveAcpGoalAfterTurn } from '@/server/lib/harness/acp/acp-goal-driver.server';
33
32
  import { handshakeAcpSession } from '@/server/lib/harness/acp/session-handshake';
34
33
  import { capabilitiesFrom } from '@/server/lib/harness/launch';
35
34
  import { PendingPermissions } from '@/server/lib/harness/acp/permissions';
35
+ import { cancelAllAcpPermissions } from '@/server/lib/harness/acp/session-permissions';
36
36
  import { handleSessionNotification } from '@/server/lib/harness/acp/session-notifications';
37
37
  import { AcpUsageMeter, type AcpContextUsage } from '@/server/lib/harness/acp/session-usage';
38
- import { answerPermissionRequest } from '@/server/lib/harness/acp/session-permissions';
38
+ import { handleAcpClientRequest, handleAcpCancelRequest, type AcpClientRequestAnswer } from '@/server/lib/harness/acp/session-requests';
39
+ import { acpExitFailureFrames } from '@/server/lib/harness/acp/session-exit';
40
+ import { SessionListeners } from '@/server/lib/harness/acp/session-listeners';
41
+ import {
42
+ AcpBackgroundProbe,
43
+ BACKGROUND_LOAD_TIMEOUT_MS,
44
+ assistantTextOf,
45
+ deliverBackgroundNotice,
46
+ spawnsBackgroundWork,
47
+ } from '@/server/lib/harness/acp/background-work';
39
48
  import { acpWebState } from '@/server/lib/harness/acp/session-web-state';
40
49
  import { acpIdleReaper } from '@/server/lib/harness/acp/session-idle';
41
50
  import { DEFAULT_APPROVAL_MODE, isApprovalMode, type ApprovalMode } from '@/shared/lib/omp/config/access-mode';
@@ -56,13 +65,9 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
56
65
  /** The turn in flight — the only one whose frames are accepted. */
57
66
  private readonly turns: AcpTurns;
58
67
  runModel: { provider: string; modelId: string } | null = null;
59
- /** The agent's own slash-command list, from `available_commands_update`; the
60
- * composer's `/` pool reads it for this session (omp's utility child answers
61
- * that question for the RPC transport). */
68
+ /** The agent's own slash-command list; the composer's `/` pool reads it. */
62
69
  agentCommands: { name: string; description?: string; inputHint?: string }[] = [];
63
- /** The agent's plan entries from `session/update plan`, as published. The
64
- * Todos panel renders them through the same payload omp's transcript
65
- * snapshot produces. */
70
+ /** The agent's plan entries, published for the Todos panel. */
66
71
  planEntries: unknown[] = [];
67
72
  /** Messages this session has moved: prompts sent plus assistant messages the
68
73
  * mapper closed. omp reports the same quantity from its transcript. */
@@ -73,47 +78,52 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
73
78
  assistantCount = 0;
74
79
  /** The last `usage_update` the agent reported, or null when it never did. */
75
80
  private readonly usage = new AcpUsageMeter();
76
-
77
- get contextUsage(): AcpContextUsage | null {
78
- return this.usage.contextUsage;
79
- }
80
-
81
- get totalCost(): number {
82
- return this.usage.totalCost;
83
- }
84
-
85
- get usageTokens(): number {
86
- return this.usage.usageTokens;
87
- }
81
+ get contextUsage(): AcpContextUsage | null { return this.usage.contextUsage; }
82
+ get totalCost(): number { return this.usage.totalCost; }
83
+ get usageTokens(): number { return this.usage.usageTokens; }
88
84
  /** The composer's approval tier. Answered in-process by {@link onClientRequest}. */
89
85
  accessMode: ApprovalMode = DEFAULT_APPROVAL_MODE;
90
86
  capabilities: HarnessCapabilities = capabilitiesFrom({ protocolVersion: 1 }, [], { usage: false, plan: false });
91
87
  configOptions: AcpConfigOption[] = [];
88
+ /** The older Session Modes API, adopted when the agent publishes one. */
89
+ modes: AcpSessionModeState | null = null;
90
+ /** Whether the agent advertised `promptCapabilities.image`. */
91
+ acceptsImages = false;
92
92
  private readonly proc: AcpProcess;
93
93
  /** The quiet-window reclaim; the rules live in `session-idle.ts`. */
94
94
  readonly idle: IdleReaper;
95
+ /** Watches for work that finishes after `end_turn`; see `background-work.ts`. */
96
+ private readonly background: AcpBackgroundProbe;
95
97
  private readonly mapper = new AcpFrameMapper();
96
- private readonly listeners = new Set<(event: AgentEvent) => void>();
97
- private readonly permissions = new PendingPermissions();
98
+ private readonly events = new SessionListeners();
99
+ readonly permissions = new PendingPermissions();
98
100
  private destroyHook: (() => void) | null = null;
99
101
  private destroyed = false;
100
- /** Set when Kabmo is the one ending the process, so the exit is not reported
101
- * as an agent failure. `force_reset` is the Stop button's escalation, and the
102
- * user must not get an "agent exited" error for a stop they asked for. */
102
+ /** Set when Kabmo ends the process, so a requested stop is not reported as a failure. */
103
103
  private closing = false;
104
104
 
105
105
  constructor(options: AcpSessionOptions, cwd: string) {
106
106
  this.harness = options.harness;
107
107
  this.cwd = cwd;
108
+ const env = withGatewayCompatibility(options.harness, options.env);
108
109
  this.proc = new AcpProcess({
109
110
  command: options.command,
110
111
  cwd,
111
- ...(options.env ? { env: options.env } : {}),
112
+ ...(env ? { env } : {}),
112
113
  onNotification: (method, params) => this.onNotification(method, params),
113
114
  onClientRequest: (id, method, params) => this.onClientRequest(id, method, params),
114
115
  onExit: (info) => this.onExit(info),
115
116
  });
116
117
  this.idle = acpIdleReaper(this, options.idleDestroyMs);
118
+ // ACP holds updates produced while idle until the next request, so a turn
119
+ // that spawned a subagent is followed by a `session/load` probe. The replay
120
+ // is swallowed by the probe; only the text past the answer already shown is
121
+ // emitted, as the agent's continuation.
122
+ this.background = new AcpBackgroundProbe({
123
+ load: () => this.proc.loadSession(this.sessionId, this.cwd, BACKGROUND_LOAD_TIMEOUT_MS),
124
+ resetIdle: () => this.idle.reset(),
125
+ emit: (text) => deliverBackgroundNotice(this, text),
126
+ });
117
127
  this.turns = new AcpTurns({
118
128
  emit: (event) => this.emit(event),
119
129
  prompt: (message, images) =>
@@ -139,54 +149,30 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
139
149
  private readonly requestedModel: { provider: string; modelId: string } | null;
140
150
  private readonly requestedThinking: string | null;
141
151
  private readonly requestedMode: string | null;
142
-
143
152
  /** `initialize` + `session/new|load|resume`, then the requested selections. */
144
- async start(sessionIdToLoad?: string): Promise<{ sessionId: string }> {
153
+ async start(sessionIdToLoad?: string, forkFromSessionId?: string): Promise<{ sessionId: string }> {
145
154
  await handshakeAcpSession(
146
155
  this,
147
156
  this.proc,
148
157
  { model: this.requestedModel, thinking: this.requestedThinking, mode: this.requestedMode },
149
158
  sessionIdToLoad,
159
+ forkFromSessionId,
150
160
  );
151
161
  // A slow handshake is not idleness: the window starts once it is usable.
152
162
  this.idle.reset(true);
153
163
  return { sessionId: this.sessionId };
154
164
  }
155
165
 
156
- isAlive(): boolean {
157
- return !this.destroyed && this.proc.isAlive;
158
- }
159
-
160
- get isStreaming(): boolean {
161
- return this.turns.isStreaming;
162
- }
163
-
164
- get isPromptRunning(): boolean {
165
- return this.turns.isPromptRunning;
166
- }
167
-
168
- isRunning(): boolean {
169
- return this.isAlive() && (this.turns.isPromptRunning || this.turns.isStreaming);
170
- }
171
-
172
- isBusy(): boolean {
173
- return this.isRunning() || this.permissions.size() > 0;
174
- }
175
-
176
- onEvent(listener: (event: AgentEvent) => void): () => void {
177
- this.listeners.add(listener);
178
- return () => this.listeners.delete(listener);
179
- }
180
-
181
- emit(event: AgentEvent): void {
182
- for (const listener of this.listeners) {
183
- try {
184
- listener(event);
185
- } catch {
186
- // One throwing subscriber must not starve the others.
187
- }
188
- }
189
- }
166
+ get protocol(): AcpProtocolVersion { return this.proc.protocolVersion === 2 ? 2 : 1; }
167
+ /** Set by the handshake as soon as `initialize` answers. */
168
+ onProtocol(version: AcpProtocolVersion): void { this.turns.completion = version === 2 ? 'state' : 'response'; }
169
+ isAlive(): boolean { return !this.destroyed && this.proc.isAlive; }
170
+ get isStreaming(): boolean { return this.turns.isStreaming; }
171
+ get isPromptRunning(): boolean { return this.turns.isPromptRunning; }
172
+ isRunning(): boolean { return this.isAlive() && (this.turns.isPromptRunning || this.turns.isStreaming); }
173
+ isBusy(): boolean { return this.isRunning() || this.permissions.size() > 0; }
174
+ onEvent(listener: (event: AgentEvent) => void): () => void { return this.events.add(listener); }
175
+ emit(event: AgentEvent): void { this.events.emit(event); }
190
176
 
191
177
  getPendingUiDialogs(): Record<string, unknown>[] {
192
178
  // Widened for the shared `HarnessSession` contract, which predates the
@@ -219,24 +205,32 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
219
205
  * spinner and a reattaching tab's "still running" answer read. A field so a
220
206
  * unit test can stub it: the default writes the same row omp's dispatch writes.
221
207
  */
222
- markStream: (status: 'stream' | 'finish' | 'abort') => void = (status) => {
208
+ markStream: (status: 'stream' | 'finish' | 'abort', failure?: string | null) => void = (status, failure) => {
223
209
  if (!this.sessionId) return;
224
- void markStreamStatus(this.sessionId, status, status === 'stream' ? this.runModel : undefined).catch(() => {});
210
+ void markStreamStatus(this.sessionId, status, status === 'stream' ? this.runModel : undefined, failure).catch(() => {});
225
211
  };
226
212
 
227
213
  /** Turn-end bookkeeping the panels read — see `session-turns.ts`. A cancelled
228
214
  * turn closes the marker as an `abort` badge, every other ending a `finish`.
229
215
  * The goal driver then audits the closed message and may open the next turn. */
230
- onTurnEnded(info: { stopReason?: string; closedMessage: boolean; message?: unknown; cancelled?: boolean }): void {
216
+ onTurnEnded(info: AcpTurnEndInfo): void {
231
217
  if (info.closedMessage) this.assistantCount += 1;
232
218
  this.usage.endTurn();
233
219
  settleAcpTurn(this, info);
220
+ // A subagent outlives the turn that spawned it: antigravity answers
221
+ // `end_turn` right after `invoke_subagent`, and its completion is held
222
+ // until the next request (upstream #1461). Probe the transcript instead.
223
+ if (!info.cancelled && info.failed !== true && spawnsBackgroundWork(info.message)) {
224
+ this.background.start(assistantTextOf(info.message));
225
+ }
234
226
  void driveAcpGoalAfterTurn(this, info.message, { cancelled: info.cancelled === true }).catch(() => {});
235
227
  }
236
228
 
237
- /** Dispatcher seam: stop the turn. The rules live in `AcpTurns.cancel`. */
229
+ /** Dispatcher seam: stop the turn and answer every parked approval. */
238
230
  cancelTurn(): void {
231
+ this.background.stop();
239
232
  this.turns.cancel();
233
+ cancelAllAcpPermissions(this.permissions, this.proc);
240
234
  }
241
235
 
242
236
  /** Dispatcher seam: adopt the composer's access pick. ACP answers approvals
@@ -248,12 +242,25 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
248
242
  /** Dispatcher seam: write one config selector and adopt the answer — see
249
243
  * `session-config.ts` for why the AGENT's resolved value is what is kept. */
250
244
  async setConfig(configId: string, value: string | boolean): Promise<unknown> {
245
+ // The synthesized selector `webState()` publishes for an agent that speaks
246
+ // only `modes`; there is no config option to write, so the mode verb is.
247
+ if (configId === 'mode' && typeof value === 'string' && !this.configOptions.some((option) => option.id === 'mode') && this.modes) {
248
+ return this.setMode(value);
249
+ }
251
250
  const result = await this.proc.setConfigOption(this.sessionId, configId, value);
252
251
  adoptConfigAnswer(this, result, { configId, value });
253
252
  publishConfigChange(this, configId);
254
253
  return result;
255
254
  }
256
255
 
256
+ /** `session/set_mode`: the pre-config-options way to move a mode. */
257
+ async setMode(modeId: string): Promise<unknown> {
258
+ const result = await this.proc.setMode(this.sessionId, modeId);
259
+ if (this.modes) this.modes = { ...this.modes, currentModeId: modeId };
260
+ this.emit({ type: 'mode_changed', modeId });
261
+ return result;
262
+ }
263
+
257
264
  /** Dispatcher seam: answer a pending approval dialog. Every exit answers the
258
265
  * agent — a silent return would hang it (see `session-config.ts`). */
259
266
  resolvePermission(dialogId: string, confirmed: boolean): unknown {
@@ -261,21 +268,7 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
261
268
  return null;
262
269
  }
263
270
 
264
- webState(): Record<string, unknown> {
265
- return acpWebState({
266
- sessionId: this.sessionId,
267
- isStreaming: this.isStreaming,
268
- isPromptRunning: this.isPromptRunning,
269
- messageCount: this.messageCount,
270
- promptCount: this.promptCount,
271
- assistantCount: this.assistantCount,
272
- contextUsage: this.contextUsage,
273
- totalCost: this.totalCost,
274
- runModel: this.runModel,
275
- configOptions: this.configOptions,
276
- harness: this.harness,
277
- });
278
- }
271
+ webState(): Record<string, unknown> { return acpWebState(this); }
279
272
 
280
273
  /** Run one turn. The promise IS the turn: ACP resolves `session/prompt` when
281
274
  * the agent is done, so the reply is awaited for its whole duration. The ACK,
@@ -283,6 +276,14 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
283
276
  * `session-turns.ts`.
284
277
  */
285
278
  startTurn(message: string, images: unknown): unknown {
279
+ // ACP's prompt capabilities are a MUST: an agent that did not advertise
280
+ // `image` has to be told, not sent blocks its dispatcher rejects.
281
+ if (!this.acceptsImages && Array.isArray(images) && images.length > 0) {
282
+ throw new Error(`This harness does not accept image attachments (${this.harness})`);
283
+ }
284
+ // A new prompt is the next request, so the agent flushes any held update
285
+ // itself; a probe would duplicate it.
286
+ this.background.stop();
286
287
  this.promptCount += 1;
287
288
  this.usage.beginTurn();
288
289
  return beginAcpTurn(this, this.turns, message, images);
@@ -291,57 +292,56 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
291
292
  private onNotification(method: string, params: Record<string, unknown>): void {
292
293
  // A long turn emits no commands but plenty of `session/update` frames.
293
294
  this.idle.reset();
295
+ // `$/cancel_request` names an agent→client request the agent no longer
296
+ // wants; the approval it parks is answered `cancelled`.
297
+ if (handleAcpCancelRequest(this, method, params)) return;
298
+ // A `session/load` replay repeats the whole chat; leave it to the probe.
299
+ if (this.background.consume(method, params)) return;
294
300
  handleSessionNotification(this, method, params);
295
301
  }
296
302
 
297
303
  absorbUsage(update: Record<string, unknown>): void { this.usage.absorb(update); }
298
304
  resetUsageTokens(): void { this.usage.reset(); }
299
305
  acceptingFrames(): boolean { return this.turns.acceptingFrames(); }
300
-
301
306
  mapUpdate(update: Record<string, unknown>): AgentEvent[] { return this.mapper.mapUpdate(update); }
302
-
307
+ onStateUpdate(update: Record<string, unknown>): void { this.turns.onStateUpdate(update); }
308
+ /** Answer an agent→client request with a result (cancellation uses it). */
309
+ respond(id: AcpId, result: unknown): void { this.proc.respond(id, result); }
303
310
  /** Agent→client requests: every branch answers or refuses — an unanswered call parks the turn. */
304
311
  private onClientRequest(
305
312
  id: AcpId,
306
313
  method: string,
307
314
  params: Record<string, unknown>,
308
- ): Promise<{ answered: true; result: unknown } | { answered: false; message: string } | { answered: false; deferred: true }> {
315
+ ): Promise<AcpClientRequestAnswer> {
309
316
  this.idle.reset();
310
- if (method === 'session/request_permission') {
311
- return answerPermissionRequest({
312
- sessionId: this.sessionId,
313
- accessMode: this.accessMode,
314
- permissions: this.permissions,
315
- emit: (event) => this.emit(event),
316
- }, id, params);
317
- }
318
- return Promise.resolve({ answered: false, message: `Kabmo does not implement ${method}` });
317
+ return handleAcpClientRequest(this, id, method, params);
319
318
  }
320
319
 
321
320
  private onExit(info: { code: number | null; stderrTail: string }): void {
322
321
  this.destroyed = true;
322
+ this.background.stop();
323
323
  this.idle.stop();
324
- if (this.closing) {
325
- this.destroyHook?.();
326
- return;
324
+ if (!this.closing) {
325
+ for (const event of acpExitFailureFrames(this.harness, info)) this.emit(event);
327
326
  }
328
- const detail = info.stderrTail.trim().split('\n').slice(-3).join(' · ');
329
- this.emit({
330
- type: 'prompt_error',
331
- errorMessage: detail || `The ${this.harness} agent exited (code ${info.code ?? 'signal'})`,
332
- });
333
- this.emit({ type: 'agent_end', isTerminal: true });
334
327
  this.destroyHook?.();
335
328
  }
336
329
 
337
- destroy(): void {
338
- void this.destroyAndWait();
330
+ destroy(): void { void this.destroyAndWait(); }
331
+
332
+ /** Remove this chat from the agent's own history, when it offers the method. */
333
+ async deleteAgentSession(): Promise<void> {
334
+ if (!this.sessionId || !this.capabilities.deleteSession) return;
335
+ await this.proc.deleteSession(this.sessionId, 10_000).catch((error: unknown) => {
336
+ console.error(`[harness] could not delete ${this.harness} session ${this.sessionId}:`, error);
337
+ });
339
338
  }
340
339
 
341
340
  async destroyAndWait(): Promise<void> {
342
341
  if (this.destroyed) return;
343
342
  this.destroyed = true;
344
343
  this.closing = true;
344
+ this.background.stop();
345
345
  this.idle.stop();
346
346
  this.permissions.clear();
347
347
  await this.proc.dispose().catch(() => {});
@@ -0,0 +1,223 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The tool-call half of the ACP mapper: create on first sight, PATCH afterwards.
8
+ *
9
+ * Split out of `frames.ts` because the v1 and v2 lifecycles now share one
10
+ * accumulator and the file ceiling is real. The rules are the same in both
11
+ * versions:
12
+ *
13
+ * - a `tool_call_update` for an unknown id CREATES the call (v2 has no separate
14
+ * create notification; v1's `tool_call` is just the first update);
15
+ * - every field but `toolCallId` is a patch: omitted = unchanged, `null` =
16
+ * cleared, a value = replaced;
17
+ * - a completed/failed/cancelled update often carries no content, so the card's
18
+ * body must come from the accumulated state.
19
+ *
20
+ * The card itself is a block of the accumulated assistant message, so the host
21
+ * owns that array and the snapshot; this class never touches either directly.
22
+ */
23
+
24
+ import type { AgentEvent } from '@/server/lib/omp/rpc/constants';
25
+ import {
26
+ acpContentDetails,
27
+ acpContentText,
28
+ acpToolDetails,
29
+ acpToolOutput,
30
+ acpToolTarget,
31
+ isKnownToolName,
32
+ toolTypeFor,
33
+ } from '@/server/lib/harness/acp/mapper';
34
+ import type { AcpToolKind, AcpToolStatus } from '@/server/lib/harness/acp/protocol';
35
+
36
+ /** The message block a tool card renders from. */
37
+ export interface ToolCallBlock {
38
+ type: 'toolCall';
39
+ id: string;
40
+ name: string;
41
+ arguments?: Record<string, unknown>;
42
+ toolKind?: AcpToolKind;
43
+ toolType?: string;
44
+ }
45
+
46
+ interface OpenTool {
47
+ id: string;
48
+ name: string;
49
+ kind?: AcpToolKind;
50
+ title?: string;
51
+ status: AcpToolStatus;
52
+ rawOutput?: unknown;
53
+ /** `tool_call(Update).content` — where some agents put the diff/output. */
54
+ content?: unknown;
55
+ locations?: unknown;
56
+ startedAt: number;
57
+ }
58
+
59
+ export interface ToolCallHost {
60
+ pushBlock(block: ToolCallBlock): void;
61
+ snapshot(): Record<string, unknown>;
62
+ }
63
+
64
+ export class AcpToolCalls {
65
+ private readonly calls = new Map<string, OpenTool>();
66
+
67
+ constructor(private readonly host: ToolCallHost) {}
68
+
69
+ /** Forget per-turn state (an aborted run, a fresh load). */
70
+ reset(): void {
71
+ this.calls.clear();
72
+ }
73
+
74
+ /** Tool calls still running — the driver closes them if the agent exits. */
75
+ openCalls(): string[] {
76
+ return [...this.calls.values()]
77
+ .filter((call) => call.status === 'pending' || call.status === 'in_progress' || call.status === 'paused')
78
+ .map((call) => call.id);
79
+ }
80
+
81
+ /** First sight of an id: draw the card and register it while it runs. */
82
+ open(update: Record<string, unknown>): AgentEvent[] {
83
+ const toolCallId = typeof update.toolCallId === 'string' ? update.toolCallId : '';
84
+ if (!toolCallId) return [];
85
+ const name = typeof update.name === 'string' && update.name
86
+ ? update.name
87
+ : typeof update.title === 'string' && update.title
88
+ ? update.title
89
+ : 'tool';
90
+ const kind = typeof update.kind === 'string' ? (update.kind as AcpToolKind) : undefined;
91
+ const status = typeof update.status === 'string' ? (update.status as AcpToolStatus) : 'pending';
92
+ // A specific kind is authoritative. `other`/absent is only an explicit type
93
+ // when the name is one the renderers know; otherwise the shared parser's
94
+ // own inference from the name is better informed than a forced `read`.
95
+ const toolType = kind !== undefined && kind !== 'other'
96
+ ? toolTypeFor(kind, name)
97
+ : isKnownToolName(name) ? toolTypeFor(kind, name) : undefined;
98
+ const rawInput = update.rawInput;
99
+ const args = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)
100
+ ? Object.fromEntries(Object.entries(rawInput))
101
+ : undefined;
102
+
103
+ this.host.pushBlock({
104
+ type: 'toolCall',
105
+ id: toolCallId,
106
+ name,
107
+ ...(args ? { arguments: args } : {}),
108
+ ...(kind ? { toolKind: kind } : {}),
109
+ ...(toolType ? { toolType } : {}),
110
+ });
111
+
112
+ const frames: AgentEvent[] = [
113
+ {
114
+ type: 'message_update',
115
+ message: this.host.snapshot(),
116
+ assistantMessageEvent: { type: 'toolcall_start' },
117
+ },
118
+ {
119
+ type: 'tool_execution_start',
120
+ toolCallId,
121
+ toolName: name,
122
+ ...(toolType ? { toolType } : {}),
123
+ ...(args ? { args } : {}),
124
+ ...(typeof update.title === 'string' ? { intent: update.title } : {}),
125
+ ...(acpToolTarget(update.locations, rawInput) ? { target: acpToolTarget(update.locations, rawInput) } : {}),
126
+ },
127
+ ];
128
+
129
+ if (isFinal(status)) {
130
+ frames.push(endFrame(update, toolCallId, name, status));
131
+ } else {
132
+ this.calls.set(toolCallId, {
133
+ id: toolCallId,
134
+ name,
135
+ kind,
136
+ title: typeof update.title === 'string' ? update.title : undefined,
137
+ status,
138
+ rawOutput: update.rawOutput,
139
+ content: update.content,
140
+ locations: update.locations,
141
+ startedAt: Date.now(),
142
+ });
143
+ }
144
+ return frames;
145
+ }
146
+
147
+ /** Patch an existing call; an unknown id is a create (v2's only shape). */
148
+ patch(update: Record<string, unknown>): AgentEvent[] {
149
+ const toolCallId = typeof update.toolCallId === 'string' ? update.toolCallId : '';
150
+ if (!toolCallId) return [];
151
+ const existing = this.calls.get(toolCallId);
152
+ if (!existing) return this.open(update);
153
+
154
+ if (update.rawOutput !== undefined) existing.rawOutput = update.rawOutput;
155
+ if (update.content !== undefined) existing.content = update.content;
156
+ if (update.locations !== undefined) existing.locations = update.locations;
157
+ if (typeof update.title === 'string') existing.title = update.title;
158
+ const status = typeof update.status === 'string' ? (update.status as AcpToolStatus) : existing.status;
159
+ existing.status = status;
160
+
161
+ const result = existing.rawOutput ?? (existing.content === undefined ? undefined : { content: existing.content });
162
+ const output = acpToolOutput(existing.rawOutput) || acpContentText(existing.content);
163
+ const details = acpToolDetails(existing.rawOutput) ?? acpContentDetails(existing.content);
164
+
165
+ if (isFinal(status)) {
166
+ this.calls.delete(toolCallId);
167
+ return [{
168
+ type: 'tool_execution_end',
169
+ toolCallId,
170
+ toolName: existing.name,
171
+ result,
172
+ isError: status !== 'completed',
173
+ details,
174
+ durationMs: Math.max(0, Date.now() - existing.startedAt),
175
+ output,
176
+ }];
177
+ }
178
+
179
+ return [{
180
+ type: 'tool_execution_update',
181
+ toolCallId,
182
+ toolName: existing.name,
183
+ partialResult: result,
184
+ // The ACP output shape may nest text (`{type:"content", content:{…}}`),
185
+ // which `toolResultText` does not walk. The flattened read travels with
186
+ // the raw result so the card is not blank while the call is running.
187
+ output,
188
+ }];
189
+ }
190
+
191
+ /** v2 `tool_call_content_chunk`: append one content item to an open call. */
192
+ appendContent(update: Record<string, unknown>): AgentEvent[] {
193
+ const toolCallId = typeof update.toolCallId === 'string' ? update.toolCallId : '';
194
+ const item = update.content;
195
+ if (!toolCallId || item === undefined || item === null) return [];
196
+ const existing = this.calls.get(toolCallId);
197
+ if (!existing) return this.open({ ...update, content: [item] });
198
+ const current = Array.isArray(existing.content) ? existing.content : [];
199
+ existing.content = [...current, item];
200
+ return [];
201
+ }
202
+ }
203
+
204
+ function isFinal(status: AcpToolStatus): boolean {
205
+ return status === 'completed' || status === 'failed' || status === 'cancelled';
206
+ }
207
+
208
+ function endFrame(
209
+ update: Record<string, unknown>,
210
+ toolCallId: string,
211
+ name: string,
212
+ status: AcpToolStatus,
213
+ ): AgentEvent {
214
+ return {
215
+ type: 'tool_execution_end',
216
+ toolCallId,
217
+ toolName: name,
218
+ result: update.rawOutput ?? (update.content === undefined ? undefined : { content: update.content }),
219
+ isError: status !== 'completed',
220
+ details: acpToolDetails(update.rawOutput) ?? acpContentDetails(update.content),
221
+ output: acpToolOutput(update.rawOutput) || acpContentText(update.content),
222
+ };
223
+ }