@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
@@ -0,0 +1,202 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The detached process that actually installs a harness update.
8
+ *
9
+ * Why a process of its own, and not an `await` in the route:
10
+ *
11
+ * - **It outlives the request.** The POST answers while this runs, so closing
12
+ * the dialog, reloading the page or a `bun --hot` reload cannot interrupt an
13
+ * install halfway through writing a package tree.
14
+ * - **Nothing kills it for being slow.** The old path bounded the whole update
15
+ * at five minutes and killed the child; a large native package on a slow link
16
+ * then died MID-WRITE, which is exactly how an `npm` prefix ends up corrupt.
17
+ * The bound here is 30 minutes per step and only to stop a truly hung child.
18
+ * - **One install at a time.** `flock` on a lock file is held for the run and
19
+ * released by the kernel if this process dies, so a second server (or a
20
+ * second press after a reload) cannot run a competing `npm install -g` over
21
+ * the same prefix. A second harness's press is not refused any more — its
22
+ * record waits in the queue and this worker is spawned for it when the run
23
+ * ahead finishes.
24
+ *
25
+ * It writes the same record the server reads (`update-job-store.ts`), atomically,
26
+ * at every state change and throttled while output streams. It cannot apply the
27
+ * post-install side effects itself: those read the database, which the server
28
+ * owns — `update-queue.server.ts` does that on its next pass.
29
+ *
30
+ * Run as: `bun <this file> <spec.json>`.
31
+ */
32
+
33
+ import { flockAvailable, tryFlock, type FlockHandle } from '@/server/lib/lifecycle/flock';
34
+ import { OUTPUT_LIMIT } from '@/server/lib/updates/install-steps';
35
+ import { readUpdateJob, writeUpdateJob } from '@/server/lib/harness/update-job-store';
36
+ import type {
37
+ HarnessUpdateJob,
38
+ HarnessUpdateJobSpec,
39
+ HarnessUpdateJobStep,
40
+ } from '@/shared/types/harness-update';
41
+
42
+ /**
43
+ * Longest one step may run. Deliberately generous: `npm install -g` of a native
44
+ * package is a large download plus a postinstall, and killing it mid-flight is
45
+ * the corruption this whole module exists to avoid. A hung child is still
46
+ * bounded.
47
+ */
48
+ export const HARNESS_STEP_TIMEOUT_MS = 30 * 60_000;
49
+
50
+ /** How often streamed output is flushed to the record. */
51
+ const PROGRESS_FLUSH_MS = 400;
52
+
53
+ function tail(text: string): string {
54
+ return text.length > OUTPUT_LIMIT ? `…\n${text.slice(-OUTPUT_LIMIT)}` : text;
55
+ }
56
+
57
+ function freshJob(spec: HarnessUpdateJobSpec): HarnessUpdateJob {
58
+ return {
59
+ harness: spec.harness,
60
+ label: spec.label,
61
+ startedAt: Date.now(),
62
+ finishedAt: null,
63
+ // This process IS the worker: a record that said it was waiting has been
64
+ // taken over, so the stamp must not survive into the run.
65
+ queuedAt: null,
66
+ pid: process.pid,
67
+ steps: spec.steps.map((step): HarnessUpdateJobStep => ({ ...step, state: 'pending', code: null })),
68
+ output: '',
69
+ ok: null,
70
+ message: null,
71
+ applied: false,
72
+ repointed: null,
73
+ };
74
+ }
75
+
76
+ /** Copy a child stream into `job.output`, flushing as it arrives. */
77
+ async function pump(
78
+ stream: ReadableStream<Uint8Array>,
79
+ append: (chunk: string) => Promise<void>,
80
+ ): Promise<void> {
81
+ const reader = stream.getReader();
82
+ const decoder = new TextDecoder();
83
+ for (;;) {
84
+ const { done, value } = await reader.read();
85
+ if (done) break;
86
+ const chunk = decoder.decode(value, { stream: true });
87
+ if (chunk.length === 0) continue;
88
+ await append(chunk);
89
+ }
90
+ }
91
+
92
+ /** Run every planned step, stopping at the first failure. */
93
+ async function runSteps(spec: HarnessUpdateJobSpec, lock: FlockHandle | null): Promise<void> {
94
+ const existing = await readUpdateJob(spec.statusPath);
95
+ const job: HarnessUpdateJob = existing?.harness === spec.harness
96
+ ? { ...existing, pid: process.pid, finishedAt: null, queuedAt: null, ok: null, applied: false }
97
+ : freshJob(spec);
98
+ // The plan always comes from the spec: the record on disk may be from an
99
+ // earlier run of the same harness, and its steps must not be replayed.
100
+ job.steps = spec.steps.map((step): HarnessUpdateJobStep => ({ ...step, state: 'pending', code: null }));
101
+ job.output = '';
102
+ await writeUpdateJob(job, spec.statusPath);
103
+
104
+ let lastFlush = 0;
105
+ const flush = async (force: boolean): Promise<void> => {
106
+ const now = Date.now();
107
+ if (!force && now - lastFlush < PROGRESS_FLUSH_MS) return;
108
+ lastFlush = now;
109
+ await writeUpdateJob(job, spec.statusPath);
110
+ };
111
+
112
+ let ok = true;
113
+ for (let index = 0; index < job.steps.length; index += 1) {
114
+ const step = job.steps[index];
115
+ job.steps[index] = { ...step, state: 'running' };
116
+ await flush(true);
117
+
118
+ const proc = Bun.spawn({
119
+ cmd: step.argv,
120
+ stdin: 'ignore',
121
+ stdout: 'pipe',
122
+ stderr: 'pipe',
123
+ timeout: HARNESS_STEP_TIMEOUT_MS,
124
+ env: { ...Bun.env, PAGER: 'cat', FORCE_COLOR: '0' },
125
+ });
126
+ const append = async (chunk: string): Promise<void> => {
127
+ job.output = tail(job.output + chunk);
128
+ await flush(false);
129
+ };
130
+ // Appended as they arrive, so the record streams while npm prints; joining
131
+ // the captured text here as well printed every line twice.
132
+ await Promise.all([pump(proc.stdout, append), pump(proc.stderr, append)]);
133
+ const code = await proc.exited;
134
+
135
+ if (code !== 0) {
136
+ job.steps[index] = { ...job.steps[index], state: 'failed', code };
137
+ job.message = `${spec.label} update failed (exit ${code ?? 'killed'})`;
138
+ ok = false;
139
+ await flush(true);
140
+ break;
141
+ }
142
+ job.steps[index] = { ...job.steps[index], state: 'ok', code };
143
+ await flush(true);
144
+ }
145
+
146
+ job.finishedAt = Date.now();
147
+ job.pid = null;
148
+ job.ok = ok;
149
+ if (ok) {
150
+ const moved = job.steps.map((step) => step.part).join(' + ');
151
+ job.message = `${spec.label} updated (${moved})`;
152
+ }
153
+ await writeUpdateJob(job, spec.statusPath);
154
+ lock?.release();
155
+ }
156
+
157
+ async function main(): Promise<void> {
158
+ const specPath = process.argv[2];
159
+ if (!specPath) {
160
+ console.error('[kabmo] harness update worker: no spec path');
161
+ process.exit(2);
162
+ }
163
+ const spec = (await Bun.file(specPath).json()) as HarnessUpdateJobSpec;
164
+
165
+ // A host without flock (Windows, some NFS mounts) keeps the server-side
166
+ // in-flight check as its only guard; refusing every update there would break
167
+ // the feature on a platform that simply locks differently.
168
+ const lock = flockAvailable() ? tryFlock(spec.lockPath) : null;
169
+ if (flockAvailable() && !lock) {
170
+ const running = await readUpdateJob(spec.statusPath);
171
+ if (running && running.harness === spec.harness) {
172
+ await writeUpdateJob({
173
+ ...running,
174
+ finishedAt: Date.now(),
175
+ pid: null,
176
+ ok: false,
177
+ applied: true,
178
+ message: `${spec.label} update is already running in another process`,
179
+ }, spec.statusPath);
180
+ }
181
+ return;
182
+ }
183
+
184
+ try {
185
+ await runSteps(spec, lock);
186
+ } catch (cause) {
187
+ const running = await readUpdateJob(spec.statusPath);
188
+ const base = running ?? freshJob(spec);
189
+ await writeUpdateJob({
190
+ ...base,
191
+ finishedAt: Date.now(),
192
+ pid: null,
193
+ ok: false,
194
+ applied: true,
195
+ message: `${spec.label} update failed: ${cause instanceof Error ? cause.message : String(cause)}`,
196
+ }, spec.statusPath);
197
+ lock?.release();
198
+ process.exitCode = 1;
199
+ }
200
+ }
201
+
202
+ void main();
@@ -20,6 +20,7 @@
20
20
 
21
21
  import { getDb } from '@/server/db.server';
22
22
  import { startHarnessAutoProbe } from '@/server/lib/harness/auto-probe.server';
23
+ import { pumpUpdateQueue } from '@/server/lib/harness/update-queue.server';
23
24
  import { compactChatOverlayRows } from '@/server/lib/db/compact-chat-overlay';
24
25
  import { packageDir } from '@/server/lib/fs/package-root';
25
26
  import { isTrayEnabledByArgv } from '@/server/lib/lifecycle/argv-flags';
@@ -72,6 +73,14 @@ export async function runAfterListenTasks(target: AfterListenTarget): Promise<vo
72
73
  // listener is already serving tabs and chats. The pass is per PROCESS, so a
73
74
  // `bun --hot` reload does not start every agent again — see the module header.
74
75
  startHarnessAutoProbe();
76
+
77
+ // The harness-update queue. A run accepted before a restart (or one harness
78
+ // waiting behind an install) must not need a browser tab to move: this pass
79
+ // settles what died, applies a finished run's side effects, and starts the
80
+ // next waiting worker. Never awaited — it spawns a detached child.
81
+ void pumpUpdateQueue().catch((cause) => {
82
+ console.error('[harness-update] queue pump failed:', cause);
83
+ });
75
84
  }
76
85
 
77
86
  /**
@@ -110,3 +110,31 @@ export function getAuthPath(): string {
110
110
  export function getLockPath(port: number | string): string {
111
111
  return path.join(getRunDir(), `${port}.lock`);
112
112
  }
113
+
114
+ /**
115
+ * `<data>/run/harness-update.<id>.json` — the state of THAT harness's update:
116
+ * waiting in the queue, installing, or the last one that ran.
117
+ *
118
+ * On disk, not in memory, because the run outlives the request that started it:
119
+ * a reloaded page, a restarted server and a second tab all have to read the same
120
+ * answer, and a run killed by a reboot has to be distinguishable from one still
121
+ * installing. One file PER HARNESS, because two presses are two records: the
122
+ * second waits in its own record while the first installs, and each row keeps
123
+ * the log of its own last run instead of overwriting its neighbour's.
124
+ */
125
+ export function getHarnessUpdateStatusPath(harness: string): string {
126
+ return path.join(getRunDir(), `harness-update.${harness}.json`);
127
+ }
128
+
129
+ /** `<data>/run/harness-update.<id>.spec.json` — what that harness's worker was asked to run. */
130
+ export function getHarnessUpdateSpecPath(harness: string): string {
131
+ return path.join(getRunDir(), `harness-update.${harness}.spec.json`);
132
+ }
133
+
134
+ /** `<data>/run/harness-update.lock` — one harness install at a time, across processes.
135
+ * ONE lock for every harness, not one each: the installs share the global npm
136
+ * prefix, and two `npm install -g` over the same prefix is how a tree is
137
+ * corrupted. The queue above it is what lets a second press be accepted. */
138
+ export function getHarnessUpdateLockPath(): string {
139
+ return path.join(getRunDir(), 'harness-update.lock');
140
+ }
@@ -28,6 +28,7 @@ import { RunSettle, handleChildExit } from '@/server/lib/omp/rpc/run-settle.serv
28
28
  import { EventFanout } from '@/server/lib/omp/rpc/event-fanout';
29
29
  import { syncRunModel as syncRunModelFor } from '@/server/lib/omp/rpc/run-model';
30
30
  import { reloadChildPlugins } from '@/server/lib/omp/rpc/reload-plugins';
31
+ import { noteRefusedPrompt } from '@/server/lib/omp/rpc/terminal-settle';
31
32
  import { clearStreamStatus, type SessionRunModel } from '@/shared/lib/omp/session/stream-state.server';
32
33
  import { GET_STATE_TIMEOUT_MS, IDLE_REAP_MS, READY_TIMEOUT_MS, SUBAGENT_STALE_MS, type AgentEvent, type EventListener, type RpcSessionState } from '@/server/lib/omp/rpc/constants';
33
34
 
@@ -240,16 +241,15 @@ export class AgentSessionWrapper {
240
241
  private handleFrame(frame: RpcFrame): void {
241
242
  this.idle.reset();
242
243
  const event = frame as AgentEvent;
243
- // The state machine and its settle-time side effects live in frame-fold.ts;
244
- // this method owns only the wrapper's own bookkeeping around it.
244
+ // The fold owns the state machine; this method only bookkeeps around it.
245
245
  const { suppressForward } = foldSessionFrame(this, event);
246
+ // A refused prompt opens no turn; no agent_end will settle it.
247
+ noteRefusedPrompt(event, this.sessionId);
246
248
  // The run-settle clock reads every frame: it is what tells a quiet run from
247
249
  // one whose event stream stopped, and it is fed the retry waits omp
248
250
  // announces. See `run-settle.server.ts`.
249
251
  this.runSettle.noteFrame(event);
250
- // A frame settled the dispatch (agent_start cleared `awaitingAgentStart` and
251
- // set `streaming`; prompt_result cleared it too), so the watchdog has
252
- // nothing left to do.
252
+ // A frame settled the dispatch, so the watchdog has nothing left to do.
253
253
  this.agentStartWatchdog.settleIfDone();
254
254
  // `suppressForward` withholds only the FRAME — a failed prompt response
255
255
  // already emitted its own `prompt_error`, and Kabmo's own background
@@ -19,6 +19,7 @@ import { RpcProcess } from '@/server/lib/omp/rpc/process';
19
19
  import { buildSessionSpawnArgs } from '@/server/lib/omp/rpc/constants';
20
20
  import { AgentSessionWrapper } from '@/server/lib/omp/rpc/manager';
21
21
  import { recordSpawnProvenance } from '@/server/lib/omp/rpc/spawn-provenance';
22
+ import { mintAgentEnvironment, rememberAgentToken } from '@/server/lib/sessions/agent-token.server';
22
23
  import { DEFAULT_APPROVAL_MODE, type ApprovalMode } from '@/shared/lib/omp/config/access-mode';
23
24
 
24
25
  interface PrewarmedEntry {
@@ -50,6 +51,11 @@ export function prewarmRpcSession(cwd: string, approvalMode?: ApprovalMode, mode
50
51
  const existing = pool.get(cwd);
51
52
  if (existing) return;
52
53
  const mode = approvalMode ?? DEFAULT_APPROVAL_MODE;
54
+ // The prewarmed child is a session host with a real id, so it gets its own
55
+ // callback credential now; the claim path must not replace it, because the
56
+ // child's environment already carries this value.
57
+ const { token, env: agentEnv } = mintAgentEnvironment();
58
+ const env = { ...(modeEnv ?? {}), ...agentEnv };
53
59
  // A pending chat has no mode selection yet, so its prewarmed process is
54
60
  // spawned with none — the first send races it and any real selection kills
55
61
  // the entry (see `startNewRpcSession`).
@@ -57,18 +63,21 @@ export function prewarmRpcSession(cwd: string, approvalMode?: ApprovalMode, mode
57
63
  const proc = new RpcProcess({
58
64
  cwd,
59
65
  extraArgs: buildSessionSpawnArgs('', mode),
60
- env: modeEnv,
66
+ env,
61
67
  onExit: ({ stderrTail }) => holder.wrapper?.handleProcessExit(stderrTail),
62
68
  });
63
69
  const wrapper = new AgentSessionWrapper(proc, cwd);
64
- recordSpawnProvenance(wrapper, mode, modeEnv);
70
+ recordSpawnProvenance(wrapper, mode, env);
65
71
  holder.wrapper = wrapper;
66
72
  wrapper.start();
67
73
  const ready = wrapper
68
74
  .waitUntilReady()
69
- .then(() => {
75
+ .then(async () => {
70
76
  // A dead wrapper (idle-kill, crash, exit) must not be handed out.
71
77
  if (!wrapper.isAlive()) throw new Error('prewarmed process exited');
78
+ await rememberAgentToken(wrapper.sessionId, token).catch((cause: unknown) => {
79
+ console.error(`[sessions] could not record the agent token for ${wrapper.sessionId}:`, cause);
80
+ });
72
81
  return wrapper;
73
82
  })
74
83
  .catch((error) => {
@@ -302,7 +302,16 @@ export function handleChildExit(host: ChildExitHost, stderrTail: string): void {
302
302
  });
303
303
  if (host.streaming || host.promptRunning) {
304
304
  host.emit({ type: 'agent_end', isTerminal: true, messages: [] });
305
- if (host.sessionId) void markStreamStatus(host.sessionId, 'finish');
305
+ // The run's own process died mid-flight: that is a failure, not a normal
306
+ // finish, and the reason the notification shows is the one above.
307
+ if (host.sessionId) {
308
+ void markStreamStatus(
309
+ host.sessionId,
310
+ 'finish',
311
+ undefined,
312
+ `The omp process for this session exited unexpectedly${detail ? `: ${detail}` : '.'}`,
313
+ );
314
+ }
306
315
  }
307
316
  host.destroy();
308
317
  }
@@ -21,6 +21,7 @@ import { recordSpawnProvenance } from '@/server/lib/omp/rpc/spawn-provenance';
21
21
  import { registerSpawnedSession } from '@/server/lib/omp/rpc/session-registration';
22
22
  import { resolveSessionOwnership, SessionOwnedElsewhereError } from '@/server/lib/omp/session/ownership.server';
23
23
  import { claimPrewarmedSession } from '@/server/lib/omp/rpc/prewarm-pool';
24
+ import { mintAgentEnvironment, rememberAgentToken } from '@/server/lib/sessions/agent-token.server';
24
25
  import { isUnrestorableModelFailure, resolveResumableModel } from '@/server/lib/omp/session/resumable-model.server';
25
26
  import { DEFAULT_APPROVAL_MODE, type ApprovalMode } from '@/shared/lib/omp/config/access-mode';
26
27
  import type { SelectedModel } from '@/shared/types/models';
@@ -308,12 +309,23 @@ export async function startNewRpcSession(
308
309
  modeEnv?: Record<string, string>,
309
310
  ): Promise<{ session: AgentSessionWrapper; realSessionId: string }> {
310
311
  const mode = approvalMode ?? DEFAULT_APPROVAL_MODE;
311
- const wrapper = await claimPrewarmedSession(cwd, mode, modeEnv);
312
+ // Mint here, not at the route: the prewarmed entry and the cold spawn both
313
+ // get a callback credential, and no caller can forget it.
314
+ const { token, env: agentEnv } = mintAgentEnvironment();
315
+ const env = { ...(modeEnv ?? {}), ...agentEnv };
316
+ const wrapper = await claimPrewarmedSession(cwd, mode, env);
312
317
 
313
318
  if (!wrapper) {
314
- return startRpcSession(`__new__${Bun.randomUUIDv7()}`, '', cwd, undefined, mode, modeEnv);
319
+ const started = await startRpcSession(`__new__${Bun.randomUUIDv7()}`, '', cwd, undefined, mode, env);
320
+ await rememberAgentToken(started.realSessionId, token).catch((cause: unknown) => {
321
+ console.error(`[sessions] could not record the agent token for ${started.realSessionId}:`, cause);
322
+ });
323
+ return started;
315
324
  }
316
325
 
326
+ // A claimed prewarmed process recorded its own token before entering the
327
+ // pool; recording this call's token would invalidate the child's environment.
328
+
317
329
  const registry = getRegistry();
318
330
  const realSessionId = wrapper.sessionId;
319
331
  wrapper.onDestroy(() => {
@@ -14,11 +14,11 @@
14
14
  * the idle reaper. Used only for lifecycle decisions (idle reclaim, spawn-mode
15
15
  * reconcile), never for the UI's running set.
16
16
  *
17
- * Identity mirrors the UI fold (`SubagentList`): frames carry an id, a
18
- * lifecycle may also carry `index`, and progress frames may be id-less and are
19
- * then matched by index — hence the index→key alias, so one subagent is never
20
- * tracked under two keys (a leftover key would pin the session alive until it
21
- * goes stale).
17
+ * Identity mirrors the sidebar's roster fold (`hooks/chat/subagents/roster.ts`):
18
+ * frames carry an id, a lifecycle may also carry `index`, and progress frames
19
+ * may be id-less and are then matched by index — hence the index→key alias, so
20
+ * one subagent is never tracked under two keys (a leftover key would pin the
21
+ * session alive until it goes stale).
22
22
  */
23
23
 
24
24
  import { parseSubagentLifecycle, readSubagentProgressFrame } from '@/shared/lib/omp/subagent/parse';
@@ -34,7 +34,8 @@ import {
34
34
  import { scheduleQueueDelivery, type QueueDeliveryHost } from '@/server/lib/queue/delivery.server';
35
35
  import { requestWaitingSweep } from '@/server/lib/waiting/sweep-trigger';
36
36
  import { markStreamStatus, loadStreamStatuses } from '@/shared/lib/omp/session/stream-state.server';
37
- import { driveGoalAfterTurn } from '@/server/lib/omp/session/goal-driver.server';
37
+ import { driveGoalAfterTurn, lastAssistantText } from '@/server/lib/omp/session/goal-driver.server';
38
+ import { noteChildOutcome } from '@/server/lib/sessions/notify.server';
38
39
  import { emitRealtimeSignal } from '@/server/lib/realtime/signals.server';
39
40
  import { publishSidebarStructure } from '@/server/lib/realtime/topics.server';
40
41
 
@@ -74,6 +75,25 @@ function endedAborted(host: TerminalSettleHost, messages: unknown): boolean {
74
75
  );
75
76
  }
76
77
 
78
+ const FAILED_STOP_REASONS: Readonly<Record<string, true>> = { error: true, failed: true, failure: true };
79
+
80
+ /** The failure a terminal frame reports, or null for a normal stop.
81
+ *
82
+ * Conservative on purpose: only an assistant message's own `error` text or an
83
+ * explicit failure stop reason counts. A tool error is not a failed run. */
84
+ function endedFailure(messages: unknown): string | null {
85
+ if (!Array.isArray(messages)) return null;
86
+ for (const entry of messages) {
87
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
88
+ const record = entry as Record<string, unknown>;
89
+ const error = typeof record.error === 'string' ? record.error.trim() : '';
90
+ if (record.role === 'assistant' && error) return error;
91
+ const stop = typeof record.stopReason === 'string' ? record.stopReason : '';
92
+ if (FAILED_STOP_REASONS[stop] === true) return `The run ended with ${stop}`;
93
+ }
94
+ return null;
95
+ }
96
+
77
97
  /**
78
98
  * Write the terminal stream badge from the ending turn's own stopReason.
79
99
  *
@@ -86,19 +106,51 @@ async function markEndStatus(sessionId: string, host: TerminalSettleHost, messag
86
106
  if (!sessionId) return;
87
107
  const current = await loadStreamStatuses();
88
108
  if (current[sessionId] !== 'stream') return;
89
- await markStreamStatus(sessionId, endedAborted(host, messages) ? 'abort' : 'finish');
109
+ if (endedAborted(host, messages)) {
110
+ await markStreamStatus(sessionId, 'abort');
111
+ return;
112
+ }
113
+ await markStreamStatus(sessionId, 'finish', undefined, endedFailure(messages));
90
114
  }
91
115
 
92
116
  /**
93
- * Run the side effects a terminal run end owns.
117
+ * Report a refused `prompt` response as a failed child outcome.
94
118
  *
95
- * Callers clear the run's own flags (streaming, promptRunning, the
96
- * awaiting-start and continuation-grace clocks) — that is the fold's state
97
- * machine, and this function only performs the work the settle triggers.
119
+ * A refused prompt opens no turn, so no `agent_end` will ever settle it. The
120
+ * check lives here because this module already owns the outcome vocabulary.
98
121
  */
122
+ export function noteRefusedPrompt(
123
+ event: { type?: string; success?: unknown; command?: unknown; error?: unknown },
124
+ sessionId: string,
125
+ ): void {
126
+ if (event.type !== 'response' || event.success !== false || event.command !== 'prompt' || !sessionId) return;
127
+ void noteChildOutcome({
128
+ sessionId,
129
+ status: 'failed',
130
+ failure: typeof event.error === 'string' ? event.error : 'Prompt failed',
131
+ }).catch((error: unknown) => {
132
+ console.error('[sessions] could not record a refused prompt:', error);
133
+ });
134
+ }
135
+
136
+ /** Run the side effects a terminal run end owns. */
99
137
  export function settleTerminalRun(host: TerminalSettleHost, messages: unknown): void {
100
138
  const aborted = endedAborted(host, messages);
139
+ const failure = aborted ? null : endedFailure(messages);
101
140
  if (host.sessionId) void markEndStatus(host.sessionId, host, messages);
141
+ // Delegation is reported here, not from the route: this frame is the only
142
+ // moment that knows a run genuinely ended, and a synthetic `run-settle`
143
+ // reconcile must report the same outcome as a real `agent_end`.
144
+ if (host.sessionId) {
145
+ void noteChildOutcome({
146
+ sessionId: host.sessionId,
147
+ status: aborted ? 'interrupted' : failure ? 'failed' : 'completed',
148
+ output: aborted ? null : lastAssistantText(messages),
149
+ ...(failure ? { failure } : {}),
150
+ }).catch((error: unknown) => {
151
+ console.error('[sessions] could not record a child outcome:', error);
152
+ });
153
+ }
102
154
  if (!aborted) {
103
155
  void triggerAutoSessionTitle(host, 'settle');
104
156
  void driveGoalAfterTurn({ host, messages });
@@ -29,6 +29,7 @@
29
29
 
30
30
  import { getLiveSession } from '@/server/lib/omp/rpc/session-registry';
31
31
  import { purgeSessionData } from '@/server/lib/omp/session/delete.server';
32
+ import { dependentsDeepestFirst } from '@/server/lib/sessions/lifecycle.server';
32
33
  import { purgeBtwForSession } from '@/server/lib/btw/purge.server';
33
34
  import { isSinglePathSegment } from '@/server/lib/fs/path-segment';
34
35
  import { isMockMode } from '@/server/mock.server';
@@ -79,6 +80,7 @@ export async function removeSession(sessionId: string): Promise<SessionRemoval>
79
80
  error: 'This session is working. Stop the run before deleting it.',
80
81
  };
81
82
  }
83
+ if ('deleteAgentSession' in live && live.deleteAgentSession) await live.deleteAgentSession();
82
84
  await live.destroyAndWait();
83
85
  }
84
86
 
@@ -106,3 +108,49 @@ export async function removeSession(sessionId: string): Promise<SessionRemoval>
106
108
  };
107
109
  }
108
110
  }
111
+
112
+ export interface SessionTreeRemoval {
113
+ result: SessionRemoval;
114
+ /** Dependents removed before the root, deepest first. */
115
+ removedDependents: string[];
116
+ }
117
+
118
+ function busyRemoval(sessionId: string): SessionRemoval {
119
+ return {
120
+ ok: false,
121
+ status: 409,
122
+ code: 'session_busy',
123
+ error: `Session ${sessionId} is working. Stop the run before deleting the tree.`,
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Remove a session AND its dependents.
129
+ *
130
+ * Every dependent is prechecked for a busy child before anything is deleted: a
131
+ * partial cascade is worse than a refusal, because the user cannot tell which
132
+ * half of the tree disappeared. Deepest first, so a parent never loses the rows
133
+ * that name it before the children are gone.
134
+ */
135
+ export async function removeSessionTree(sessionId: string): Promise<SessionTreeRemoval> {
136
+ const rootLive = getLiveSession(sessionId);
137
+ if (rootLive?.isAlive() && rootLive.isBusy()) {
138
+ return { result: busyRemoval(sessionId), removedDependents: [] };
139
+ }
140
+
141
+ const dependents = await dependentsDeepestFirst(sessionId);
142
+ for (const id of dependents) {
143
+ const live = getLiveSession(id);
144
+ if (live?.isAlive() && live.isBusy()) {
145
+ return { result: busyRemoval(id), removedDependents: [] };
146
+ }
147
+ }
148
+
149
+ const removedDependents: string[] = [];
150
+ for (const id of dependents) {
151
+ const verdict = await removeSession(id);
152
+ if (!verdict.ok) return { result: verdict, removedDependents };
153
+ removedDependents.push(id);
154
+ }
155
+ return { result: await removeSession(sessionId), removedDependents };
156
+ }
@@ -41,6 +41,7 @@ import { emitRealtimeSignal } from '@/server/lib/realtime/signals.server';
41
41
  import { failWaitingOn } from '@/server/lib/waiting/store.server';
42
42
  import { siblingDirForSession } from '@/server/lib/omp/subagent/history/paths';
43
43
  import { isSinglePathSegment } from '@/server/lib/fs/path-segment';
44
+ import { deleteSessionRelations } from '@/server/lib/sessions/relations.server';
44
45
 
45
46
  export interface SessionPurgeResult {
46
47
  /** Something keyed to this id existed — a transcript, a mock session row, or
@@ -83,6 +84,10 @@ async function purgeKabmoRows(db: DbClient, sessionId: string): Promise<number>
83
84
  changes += result.changes ?? 0;
84
85
  }
85
86
  const mockRow = await db.run('DELETE FROM sessions WHERE id = ?', [sessionId]);
87
+ // The tree's own rows: this session's relation, incoming edges that would
88
+ // otherwise point at a dead id, and its pending notice/token rows. Cascading
89
+ // DELETE of dependents is a separate, deliberate path (M19).
90
+ await deleteSessionRelations(sessionId).catch(() => {});
86
91
  return changes + (mockRow.changes ?? 0);
87
92
  }
88
93
 
@@ -121,26 +121,15 @@ function resolveCutIndex(
121
121
  }
122
122
 
123
123
  /**
124
- * Build the truncated body: entries at/after the cut turn are dropped; header
125
- * records and everything before it survive. Returns null when the cut cannot be
126
- * resolved at all (an unknown id with no clock, or an id naming a non-turn).
124
+ * Build the body for a resolved cut index. Shared with the fork path, which
125
+ * resolves its own index (the start of the anchored turn) and must keep the
126
+ * same header-carrying rules as a rewind.
127
127
  */
128
- export function truncateSessionBody(body: string, cut: RewindCut): TruncatedSession | null {
129
- const records: Array<Record<string, unknown> | null> = body.split('\n').map((line) => {
130
- const trimmed = line.trim();
131
- if (!trimmed) return null;
132
- let parsed: unknown;
133
- try {
134
- parsed = JSON.parse(trimmed);
135
- } catch {
136
- return null;
137
- }
138
- return isRecord(parsed) ? parsed : null;
139
- });
140
-
141
- const cutIndex = resolveCutIndex(records, cut);
142
- if (cutIndex === undefined) return null;
143
-
128
+ export function buildTruncatedBody(
129
+ records: Array<Record<string, unknown> | null>,
130
+ cutIndex: number,
131
+ options: { requestedEntryId?: string; startedAt?: number } = {},
132
+ ): TruncatedSession {
144
133
  const kept = records.slice(0, cutIndex);
145
134
  const outLines = kept
146
135
  .filter((r): r is Record<string, unknown> => Boolean(r))
@@ -167,14 +156,43 @@ export function truncateSessionBody(body: string, cut: RewindCut): TruncatedSess
167
156
  // the boundary for stored rows is that same clock — not the next file turn's.
168
157
  // Using the file turn's clock kept every command row between the two alive,
169
158
  // so undoing one `/usage` left the next one standing after a reload.
170
- const resolvedByClock = cutRecord?.id !== cut.entryId;
159
+ const resolvedByClock =
160
+ options.requestedEntryId !== undefined && cutRecord?.id !== options.requestedEntryId;
171
161
  return {
172
162
  body: `${outLines.join('\n')}\n`,
173
- overlayCutClock: resolvedByClock ? cut.startedAt : (cutRecord ? recordClock(cutRecord) : undefined),
163
+ overlayCutClock: resolvedByClock
164
+ ? options.startedAt
165
+ : (cutRecord ? recordClock(cutRecord) : undefined),
174
166
  droppedEntryIds,
175
167
  };
176
168
  }
177
169
 
170
+ /**
171
+ * Build the truncated body: entries at/after the cut turn are dropped; header
172
+ * records and everything before it survive. Returns null when the cut cannot be
173
+ * resolved at all (an unknown id with no clock, or an id naming a non-turn).
174
+ */
175
+ export function truncateSessionBody(body: string, cut: RewindCut): TruncatedSession | null {
176
+ const records: Array<Record<string, unknown> | null> = body.split('\n').map((line) => {
177
+ const trimmed = line.trim();
178
+ if (!trimmed) return null;
179
+ let parsed: unknown;
180
+ try {
181
+ parsed = JSON.parse(trimmed);
182
+ } catch {
183
+ return null;
184
+ }
185
+ return isRecord(parsed) ? parsed : null;
186
+ });
187
+
188
+ const cutIndex = resolveCutIndex(records, cut);
189
+ if (cutIndex === undefined) return null;
190
+ return buildTruncatedBody(records, cutIndex, {
191
+ requestedEntryId: cut.entryId,
192
+ ...(cut.startedAt !== undefined ? { startedAt: cut.startedAt } : {}),
193
+ });
194
+ }
195
+
178
196
  /**
179
197
  * Drop the stored overlay rows the cut invalidated, and ONLY those.
180
198
  *