@kabmo-labs/kabmo 0.23.0 → 0.25.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 +805 -736
  3. package/dist/client/static/js/index-bc9aa4mx.css +1 -0
  4. package/dist/client/static/js/{index-ph0q59rs.js → index-ga8cbpt4.js} +1071 -1171
  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/Modal.tsx +2 -6
  13. package/src/client/components/common/code-surface/shiki.test.ts +82 -0
  14. package/src/client/components/common/code-surface/shiki.ts +28 -7
  15. package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +113 -0
  16. package/src/client/components/common/session-actions-menu/index.tsx +33 -2
  17. package/src/client/components/common/session-row/StatusSlot.tsx +4 -4
  18. package/src/client/components/common/session-row/index.tsx +27 -1
  19. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +7 -1
  20. package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
  21. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +25 -12
  22. package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +66 -0
  23. package/src/client/components/layout/session-sidebar/SessionItem.tsx +28 -3
  24. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.test.tsx +20 -0
  25. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +59 -12
  26. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +94 -0
  27. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
  28. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +120 -0
  29. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +47 -0
  30. package/src/client/components/layout/session-sidebar/about-modal/index.test.tsx +122 -0
  31. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +55 -46
  32. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +18 -5
  33. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +21 -4
  34. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +27 -5
  35. package/src/client/components/settings/categories/harness-settings/EnvProviderForm.tsx +31 -0
  36. package/src/client/components/settings/categories/harness-settings/provider-panel.test.tsx +49 -0
  37. package/src/client/components/workspace/chat-timeline/ChatOverlays.tsx +5 -2
  38. package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
  39. package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
  40. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +135 -118
  41. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
  42. package/src/client/components/workspace/chat-timeline/MessageList.test.ts +14 -0
  43. package/src/client/components/workspace/chat-timeline/MessageList.tsx +4 -0
  44. package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
  45. package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +4 -3
  46. package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
  47. package/src/client/components/workspace/chat-timeline/index.tsx +5 -2
  48. package/src/client/components/workspace/chat-timeline/pending-harness.test.tsx +1 -1
  49. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/FrameControl.tsx +11 -20
  50. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/GroupedAsk.tsx +1 -1
  51. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/QuestionBlock.tsx +1 -1
  52. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/drafts.ts +1 -1
  53. package/src/client/components/workspace/chat-timeline/tool-renderers/ask-panel/index.tsx +2 -1
  54. package/src/client/components/workspace/file-explorer/index.test.ts +25 -0
  55. package/src/client/components/workspace/file-explorer/index.tsx +9 -3
  56. package/src/client/components/workspace/model-dropdown/harness-models.test.ts +17 -0
  57. package/src/client/components/workspace/model-dropdown/harness-models.ts +33 -18
  58. package/src/client/components/workspace/model-dropdown/index.tsx +3 -3
  59. package/src/client/components/workspace/model-dropdown/popover-metrics.ts +4 -1
  60. package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
  61. package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
  62. package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
  63. package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
  64. package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
  65. package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
  66. package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
  67. package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
  68. package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
  69. package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
  70. package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
  71. package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
  72. package/src/client/data/settings/omp-schema.json +5 -5
  73. package/src/client/data/theme/terminal.test.ts +25 -0
  74. package/src/client/data/theme/terminal.ts +96 -79
  75. package/src/client/hooks/chat/composer/items.test.ts +12 -26
  76. package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
  77. package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
  78. package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
  79. package/src/client/hooks/chat/timeline/actions.ts +2 -2
  80. package/src/client/hooks/chat/timeline/ask-frames.ts +5 -4
  81. package/src/client/hooks/chat/timeline/new-chat-open.test.ts +86 -0
  82. package/src/client/hooks/chat/timeline/new-chat-open.ts +23 -5
  83. package/src/client/hooks/chat/timeline/new-chat.test.ts +32 -4
  84. package/src/client/hooks/chat/timeline/new-chat.ts +18 -6
  85. package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
  86. package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
  87. package/src/client/hooks/chat/timeline/rewind-actions.test.ts +24 -1
  88. package/src/client/hooks/chat/timeline/rewind-actions.ts +15 -11
  89. package/src/client/hooks/chat/timeline/run-identity.test.ts +52 -0
  90. package/src/client/hooks/chat/timeline/run-identity.ts +23 -11
  91. package/src/client/hooks/chat/timeline/send-execute.test.ts +56 -0
  92. package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
  93. package/src/client/hooks/chat/timeline/send-props.ts +5 -3
  94. package/src/client/hooks/chat/timeline/send-steer.test.ts +4 -4
  95. package/src/client/hooks/chat/timeline/send.test-util.ts +8 -2
  96. package/src/client/hooks/chat/timeline/send.test.ts +4 -4
  97. package/src/client/hooks/chat/timeline/send.ts +59 -53
  98. package/src/client/hooks/chat/timeline/session-load.test-util.ts +6 -2
  99. package/src/client/hooks/chat/timeline/session-load.test.ts +31 -0
  100. package/src/client/hooks/chat/timeline/session-load.ts +6 -14
  101. package/src/client/hooks/chat/timeline/session-shapes.ts +32 -0
  102. package/src/client/hooks/chat/timeline/use-fork-session.ts +49 -0
  103. package/src/client/hooks/models/harness-catalog.ts +114 -0
  104. package/src/client/hooks/models/provider-writes.test.ts +81 -0
  105. package/src/client/hooks/models/provider-writes.ts +10 -3
  106. package/src/client/hooks/models/use-harness-update.test.ts +193 -0
  107. package/src/client/hooks/models/use-harness-update.ts +202 -0
  108. package/src/client/hooks/models/use-harnesses-controller.ts +57 -0
  109. package/src/client/hooks/models/use-harnesses-signal.test.ts +128 -0
  110. package/src/client/hooks/models/use-harnesses.test.ts +2 -1
  111. package/src/client/hooks/models/use-harnesses.ts +48 -114
  112. package/src/client/hooks/workspace/child-expansion.ts +33 -0
  113. package/src/client/hooks/workspace/terminal/index.ts +17 -3
  114. package/src/client/hooks/workspace/terminal/socket.ts +9 -4
  115. package/src/client/lib/session-tree.test.ts +50 -0
  116. package/src/client/lib/session-tree.ts +59 -0
  117. package/src/client/tailwind.css +26 -12
  118. package/src/server/index.ts +2 -0
  119. package/src/server/lib/auth/guard.ts +10 -0
  120. package/src/server/lib/btw/session-copy.server.ts +6 -44
  121. package/src/server/lib/btw/session-copy.test.ts +2 -1
  122. package/src/server/lib/db/schema.ts +4 -0
  123. package/src/server/lib/db/seed-terminal.test.ts +1 -1
  124. package/src/server/lib/db/seed.test.ts +1 -1
  125. package/src/server/lib/harness/acp/activation.test.ts +81 -0
  126. package/src/server/lib/harness/acp/activation.ts +72 -0
  127. package/src/server/lib/harness/acp/background-work.test.ts +262 -0
  128. package/src/server/lib/harness/acp/background-work.ts +320 -0
  129. package/src/server/lib/harness/acp/client.ts +2 -2
  130. package/src/server/lib/harness/acp/frames.test.ts +50 -1
  131. package/src/server/lib/harness/acp/frames.ts +17 -5
  132. package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
  133. package/src/server/lib/harness/acp/gateway-env.ts +70 -0
  134. package/src/server/lib/harness/acp/mapper.ts +6 -4
  135. package/src/server/lib/harness/acp/prompt.test.ts +20 -0
  136. package/src/server/lib/harness/acp/prompt.ts +19 -3
  137. package/src/server/lib/harness/acp/session-background.test.ts +129 -0
  138. package/src/server/lib/harness/acp/session-config.test.ts +73 -0
  139. package/src/server/lib/harness/acp/session-config.ts +87 -6
  140. package/src/server/lib/harness/acp/session-exit.ts +31 -0
  141. package/src/server/lib/harness/acp/session-handshake.test.ts +108 -0
  142. package/src/server/lib/harness/acp/session-handshake.ts +36 -3
  143. package/src/server/lib/harness/acp/session-idle.ts +51 -0
  144. package/src/server/lib/harness/acp/session-listeners.ts +31 -0
  145. package/src/server/lib/harness/acp/session-notifications.ts +19 -3
  146. package/src/server/lib/harness/acp/session-observers.test.ts +9 -0
  147. package/src/server/lib/harness/acp/session-options.ts +33 -0
  148. package/src/server/lib/harness/acp/session-reaper.test.ts +96 -0
  149. package/src/server/lib/harness/acp/session-requests.ts +47 -0
  150. package/src/server/lib/harness/acp/session-turns.ts +20 -5
  151. package/src/server/lib/harness/acp/session.test-util.ts +54 -3
  152. package/src/server/lib/harness/acp/session.test.ts +65 -3
  153. package/src/server/lib/harness/acp/session.ts +79 -79
  154. package/src/server/lib/harness/acp/turn.test.ts +81 -0
  155. package/src/server/lib/harness/acp/turn.ts +54 -13
  156. package/src/server/lib/harness/acp/verbs.ts +12 -2
  157. package/src/server/lib/harness/auto-probe.server.test.ts +121 -0
  158. package/src/server/lib/harness/auto-probe.server.ts +178 -0
  159. package/src/server/lib/harness/config.server.test.ts +1 -1
  160. package/src/server/lib/harness/config.server.ts +1 -1
  161. package/src/server/lib/harness/launch-table.ts +195 -0
  162. package/src/server/lib/harness/launch.test.ts +37 -0
  163. package/src/server/lib/harness/launch.ts +16 -116
  164. package/src/server/lib/harness/provider-entry.ts +32 -0
  165. package/src/server/lib/harness/provider-file.server.ts +3 -0
  166. package/src/server/lib/harness/provider-sources.server.test.ts +45 -0
  167. package/src/server/lib/harness/provider-sources.server.ts +26 -2
  168. package/src/server/lib/harness/provider-write.server.ts +21 -32
  169. package/src/server/lib/harness/provider-zcode.server.test.ts +270 -0
  170. package/src/server/lib/harness/provider-zcode.server.ts +324 -0
  171. package/src/server/lib/harness/spawn.server.ts +15 -2
  172. package/src/server/lib/harness/update-job-store.test.ts +126 -0
  173. package/src/server/lib/harness/update-job-store.ts +109 -0
  174. package/src/server/lib/harness/update-job.server.ts +203 -0
  175. package/src/server/lib/harness/update-state.server.ts +15 -20
  176. package/src/server/lib/harness/update-worker.test.ts +153 -0
  177. package/src/server/lib/harness/update-worker.ts +197 -0
  178. package/src/server/lib/lifecycle/after-listen.ts +7 -0
  179. package/src/server/lib/lifecycle/paths.ts +23 -0
  180. package/src/server/lib/models/registry-refresh.server.test.ts +87 -0
  181. package/src/server/lib/models/registry-refresh.server.ts +98 -0
  182. package/src/server/lib/omp/rpc/child-config.ts +5 -4
  183. package/src/server/lib/omp/rpc/constants.test.ts +2 -1
  184. package/src/server/lib/omp/rpc/forked-resume.test.ts +14 -3
  185. package/src/server/lib/omp/rpc/manager.ts +5 -5
  186. package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
  187. package/src/server/lib/omp/rpc/session-registry.ts +14 -2
  188. package/src/server/lib/omp/rpc/terminal-settle.ts +53 -5
  189. package/src/server/lib/omp/session/delete-flow.server.ts +62 -8
  190. package/src/server/lib/omp/session/delete.server.ts +17 -0
  191. package/src/server/lib/omp/session/rewind-file.ts +39 -21
  192. package/src/server/lib/omp/session/sidebar-data.server.ts +6 -6
  193. package/src/server/lib/omp/session/transcript-copy.ts +123 -0
  194. package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
  195. package/src/server/lib/sessions/agent-token.server.ts +134 -0
  196. package/src/server/lib/sessions/answers.server.test.ts +33 -0
  197. package/src/server/lib/sessions/answers.server.ts +37 -0
  198. package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
  199. package/src/server/lib/sessions/dispatch.server.ts +128 -0
  200. package/src/server/lib/sessions/fork.server.test.ts +209 -0
  201. package/src/server/lib/sessions/fork.server.ts +304 -0
  202. package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
  203. package/src/server/lib/sessions/lifecycle.server.ts +71 -0
  204. package/src/server/lib/sessions/notify.server.test.ts +112 -0
  205. package/src/server/lib/sessions/notify.server.ts +212 -0
  206. package/src/server/lib/sessions/relation-types.ts +76 -0
  207. package/src/server/lib/sessions/relations.server.test.ts +207 -0
  208. package/src/server/lib/sessions/relations.server.ts +337 -0
  209. package/src/server/lib/sessions/resolve.server.ts +106 -0
  210. package/src/server/lib/sessions/schema.server.ts +82 -0
  211. package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
  212. package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
  213. package/src/server/lib/sessions/spawn.server.test.ts +196 -0
  214. package/src/server/lib/sessions/spawn.server.ts +310 -0
  215. package/src/server/lib/terminal/attach-replay.test.ts +2 -2
  216. package/src/server/lib/terminal/output.test.ts +2 -2
  217. package/src/server/lib/terminal/output.ts +1 -1
  218. package/src/server/lib/terminal/resize.test.ts +99 -0
  219. package/src/server/lib/terminal/runtime.server.ts +26 -6
  220. package/src/server/lib/terminal/send-result.test.ts +18 -1
  221. package/src/server/lib/terminal/send-result.ts +26 -2
  222. package/src/server/lib/terminal/session.server.ts +6 -6
  223. package/src/server/lib/usage/new-api.test.ts +92 -0
  224. package/src/server/lib/usage/new-api.ts +131 -0
  225. package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
  226. package/src/server/lib/usage/provider-key.ts +33 -0
  227. package/src/server/lib/usage/providers.server.ts +10 -3
  228. package/src/server/lib/usage/vendor-balance.server.ts +4 -53
  229. package/src/server/lib/usage/vendor-http.ts +41 -0
  230. package/src/server/lib/usage/window.ts +55 -0
  231. package/src/server/routes/agent/command.ts +14 -1
  232. package/src/server/routes/agent/harness-command.ts +6 -0
  233. package/src/server/routes/agent/new.ts +15 -0
  234. package/src/server/routes/chat/rewind.test.ts +147 -0
  235. package/src/server/routes/chat/rewind.ts +29 -7
  236. package/src/server/routes/chat/session.test.ts +165 -10
  237. package/src/server/routes/chat/session.ts +60 -7
  238. package/src/server/routes/harness/add-provider.test.ts +9 -1
  239. package/src/server/routes/harness/import-action.ts +22 -4
  240. package/src/server/routes/harness/import.test.ts +1 -1
  241. package/src/server/routes/harness/index.ts +5 -1
  242. package/src/server/routes/harness/root.ts +8 -49
  243. package/src/server/routes/harness/toggle.test.ts +20 -0
  244. package/src/server/routes/harness/update-status.ts +26 -0
  245. package/src/server/routes/harness/update.test.ts +119 -0
  246. package/src/server/routes/harness/update.ts +67 -113
  247. package/src/server/routes/harness/versions.ts +5 -1
  248. package/src/server/routes/sessions/answer.ts +24 -0
  249. package/src/server/routes/sessions/batch-delete.ts +11 -5
  250. package/src/server/routes/sessions/delete-acp.test.ts +227 -0
  251. package/src/server/routes/sessions/delete.ts +4 -2
  252. package/src/server/routes/sessions/fork.ts +74 -0
  253. package/src/server/routes/sessions/index.ts +14 -0
  254. package/src/server/routes/sessions/relations.ts +85 -0
  255. package/src/server/routes/sessions/session.ts +4 -0
  256. package/src/server/routes/sessions/spawn.ts +134 -0
  257. package/src/server/routes/settings/model-override.ts +5 -2
  258. package/src/server/routes/settings/provider-entry.ts +2 -2
  259. package/src/server/routes/settings/provider-model.ts +2 -2
  260. package/src/server/routes/settings/provider-models.ts +2 -2
  261. package/src/server/routes/settings/provider-refresh.ts +6 -4
  262. package/src/server/routes/settings/providers.ts +3 -1
  263. package/src/server/routes/settings/settings-config-routes.test.ts +10 -2
  264. package/src/server/routes/terminal/ws.ts +3 -3
  265. package/src/shared/lib/chat/ask-form/fields.ts +76 -0
  266. package/src/shared/lib/chat/ask-form/index.ts +323 -0
  267. package/src/shared/lib/chat/ask-form/tokens.ts +199 -0
  268. package/src/shared/lib/chat/ask-form/types.ts +43 -0
  269. package/src/shared/lib/chat/ask-form.test.ts +137 -0
  270. package/src/shared/lib/chat/ask-questions.test.ts +65 -1
  271. package/src/shared/lib/chat/ask-questions.ts +51 -145
  272. package/src/shared/lib/chat/ask-results.ts +198 -0
  273. package/src/shared/lib/chat/composer/client.ts +31 -2
  274. package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
  275. package/src/shared/lib/chat/composer/delegation.ts +206 -0
  276. package/src/shared/lib/chat/notice-text.ts +1 -1
  277. package/src/shared/lib/chat/timeline/omp-callbacks.ts +13 -1
  278. package/src/shared/lib/chat/timeline/prompt-error.test.ts +146 -0
  279. package/src/shared/lib/chat/timeline/prompt-error.ts +88 -0
  280. package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
  281. package/src/shared/lib/code/ansi.ts +1 -1
  282. package/src/shared/lib/fonts/nerd-symbols.css +4 -3
  283. package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
  284. package/src/shared/lib/harness/catalog.test.ts +1 -1
  285. package/src/shared/lib/harness/config-fields.test.ts +4 -0
  286. package/src/shared/lib/harness/config-fields.ts +19 -4
  287. package/src/shared/lib/harness/dialects.test.ts +8 -0
  288. package/src/shared/lib/harness/dialects.ts +12 -0
  289. package/src/shared/lib/harness/provider-facts.test.ts +59 -8
  290. package/src/shared/lib/harness/provider-facts.ts +46 -11
  291. package/src/shared/lib/harness/providers.ts +44 -1
  292. package/src/shared/lib/harness/rewind.ts +24 -0
  293. package/src/shared/lib/harness/update-job.ts +33 -0
  294. package/src/shared/lib/harness/update-plan.test.ts +69 -4
  295. package/src/shared/lib/harness/update-plan.ts +57 -9
  296. package/src/shared/lib/harness/updates.test.ts +22 -0
  297. package/src/shared/lib/harness/updates.ts +24 -1
  298. package/src/shared/lib/models/client.ts +10 -1
  299. package/src/shared/lib/omp/dialog-methods.ts +4 -3
  300. package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
  301. package/src/shared/lib/omp/session/wait-idle.ts +12 -2
  302. package/src/shared/lib/theme/catalog.test.ts +13 -9
  303. package/src/shared/lib/theme/color.test.ts +2 -2
  304. package/src/shared/lib/theme/color.ts +4 -4
  305. package/src/shared/lib/theme/css.ts +2 -0
  306. package/src/shared/lib/theme/ink-scale.ts +21 -1
  307. package/src/shared/lib/theme/theme.test.ts +26 -10
  308. package/src/shared/lib/ui/safe-area.test.ts +28 -0
  309. package/src/shared/lib/ui/safe-area.ts +42 -0
  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 +65 -0
  316. package/src/shared/types/harness.ts +30 -4
  317. package/src/shared/types/omp/agent.ts +19 -2
  318. package/src/shared/types/workspace.ts +4 -0
  319. package/src/test-support/fake-omp-fork.ts +16 -2
  320. package/src/test-support/file-explorer-render.test-util.ts +37 -0
  321. package/src/test-support/file-explorer.test-util.ts +20 -18
  322. package/src/test-support/harness-table.test-util.ts +21 -4
  323. package/dist/client/static/js/index-jhmg4w91.css +0 -1
  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,87 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * A registry write is only visible to the readers that re-open the file, so the
8
+ * refresh has an ORDER: recycle the pooled omp children, forget the probes that
9
+ * measured the old file, re-probe when asked, and invalidate Kabmo's caches LAST
10
+ * — invalidating first would let the `models` topic resolve from the pre-write
11
+ * pool and cache that answer for another minute.
12
+ */
13
+
14
+ import { describe, expect, test } from 'bun:test';
15
+
16
+ import {
17
+ refreshModelRegistryAfterWrite,
18
+ type RegistryRefreshDeps,
19
+ } from '@/server/lib/models/registry-refresh.server';
20
+
21
+ /** Record every side effect in the order it happened. */
22
+ function recorder(sharing: string[] = ['omp-acp']) {
23
+ const steps: string[] = [];
24
+ const deps: RegistryRefreshDeps = {
25
+ restartUtilities: async () => { steps.push('restart'); },
26
+ registryPath: async () => '/home/me/.omp/models.yml',
27
+ sharing: (path) => {
28
+ steps.push(`sharing:${path}`);
29
+ return sharing as never;
30
+ },
31
+ forget: async (id) => { steps.push(`forget:${id}`); },
32
+ reprobe: async (ids, cwd) => { steps.push(`reprobe:${ids.join(',')}:${cwd}`); },
33
+ invalidate: () => { steps.push('invalidate'); },
34
+ };
35
+ return { steps, deps };
36
+ }
37
+
38
+ describe('refreshModelRegistryAfterWrite', () => {
39
+ test('recycles the pool, forgets the probes, and invalidates LAST', async () => {
40
+ const { steps, deps } = recorder();
41
+
42
+ const sharing = await refreshModelRegistryAfterWrite({}, deps);
43
+
44
+ expect(sharing).toEqual(['omp-acp'] as never);
45
+ expect(steps).toEqual([
46
+ 'restart',
47
+ 'sharing:/home/me/.omp/models.yml',
48
+ 'forget:omp-acp',
49
+ 'invalidate',
50
+ ]);
51
+ });
52
+
53
+ test('a re-probe runs on the shared harnesses, with the caller scope, before the caches drop', async () => {
54
+ const { steps, deps } = recorder(['omp-rpc', 'omp-acp']);
55
+
56
+ await refreshModelRegistryAfterWrite({ path: '/w/models.yml', reprobe: true, cwd: '/w' }, deps);
57
+
58
+ expect(steps).toEqual([
59
+ 'restart',
60
+ 'sharing:/w/models.yml',
61
+ 'forget:omp-rpc',
62
+ 'forget:omp-acp',
63
+ 'reprobe:omp-rpc,omp-acp:/w',
64
+ 'invalidate',
65
+ ]);
66
+ });
67
+
68
+ test('a write that cannot change a probe still recycles and invalidates', async () => {
69
+ const { steps, deps } = recorder();
70
+
71
+ const sharing = await refreshModelRegistryAfterWrite({ probes: false }, deps);
72
+
73
+ expect(sharing).toEqual([]);
74
+ expect(steps).toEqual(['restart', 'invalidate']);
75
+ });
76
+
77
+ test('the restart lands before any cache is dropped, even when it throws', async () => {
78
+ const { steps, deps } = recorder();
79
+ deps.restartUtilities = async () => {
80
+ steps.push('restart');
81
+ throw new Error('omp is missing');
82
+ };
83
+
84
+ await expect(refreshModelRegistryAfterWrite({}, deps)).rejects.toThrow('omp is missing');
85
+ expect(steps).toEqual(['restart']);
86
+ });
87
+ });
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Refresh every reader of a registry file AFTER a write to it.
8
+ *
9
+ * A `models.yml` write is invisible to the pooled `omp` utility child: the child
10
+ * loads the file when it is SPAWNED, and `get_available_models` only awaits an
11
+ * in-flight background refresh — it does not compare the file's mtime. So
12
+ * dropping Kabmo's cache alone left `/api/models` re-reading the OLD registry
13
+ * from that child, which is why adding a provider only showed up after omp was
14
+ * restarted. Recycling the pool makes the next read start from the current file.
15
+ *
16
+ * The harness probes have the same problem from the other side: an ACP transport
17
+ * reads the same file at spawn, so a probe recorded before the write describes a
18
+ * registry that no longer exists. Those records are dropped, and the launchable
19
+ * transports are re-probed when `reprobe` is set, so a picker that reads the
20
+ * cache sees the new provider without an extra "check status" round.
21
+ *
22
+ * The caches are dropped LAST: the `models` topic resolver reads through
23
+ * `loadModelsWithCache`, and publishing before the pool was recycled would cache
24
+ * the pre-write answer for another 60s.
25
+ */
26
+
27
+ import type { HarnessId } from '@/shared/lib/harness/catalog';
28
+ import { restartUtilityProcesses } from '@/server/lib/omp/rpc/utility';
29
+ import { getModelsConfigPath } from '@/server/lib/omp/config/models-config';
30
+ import { forgetProbe } from '@/server/lib/harness/probe-cache.server';
31
+ import { runAutoProbe } from '@/server/lib/harness/auto-probe.server';
32
+ import { harnessesSharingRegistry } from '@/server/lib/harness/provider-sources.server';
33
+ import { invalidateModelsCaches } from '@/shared/lib/models/server-cache';
34
+
35
+ export interface RegistryWriteRefreshOptions {
36
+ /**
37
+ * The registry file that was written. Defaults to the omp `models.yml` path,
38
+ * which is what every settings route writes.
39
+ */
40
+ path?: string;
41
+ /** Workspace scope for a re-probe; defaults to the server's cwd. */
42
+ cwd?: string;
43
+ /**
44
+ * Drop stored probes for the harnesses that read this file. Set false for a
45
+ * write that cannot change what an agent lists (a per-model override), where
46
+ * dropping the answer would only hide a still-valid model list.
47
+ */
48
+ probes?: boolean;
49
+ /** Re-probe the launchable harnesses after dropping their records. */
50
+ reprobe?: boolean;
51
+ }
52
+
53
+ /** The side effects the refresh drives, injected so a test can watch the ORDER. */
54
+ export interface RegistryRefreshDeps {
55
+ restartUtilities: () => Promise<unknown>;
56
+ registryPath: () => Promise<string>;
57
+ sharing: (path: string) => HarnessId[];
58
+ forget: (id: HarnessId) => Promise<void>;
59
+ reprobe: (ids: readonly HarnessId[], cwd: string) => Promise<unknown>;
60
+ invalidate: () => void;
61
+ }
62
+
63
+ const defaults: RegistryRefreshDeps = {
64
+ restartUtilities: restartUtilityProcesses,
65
+ registryPath: getModelsConfigPath,
66
+ sharing: harnessesSharingRegistry,
67
+ forget: forgetProbe,
68
+ reprobe: (ids, cwd) => runAutoProbe({ ids, cwd }),
69
+ invalidate: invalidateModelsCaches,
70
+ };
71
+
72
+ /**
73
+ * Recycle the pooled omp readers, forget the probes that measured the old file,
74
+ * and republish the model catalog once the fresh state is in place.
75
+ *
76
+ * Returns the harness ids that read the written file, so a caller can tell the
77
+ * browser which tabs need their own probe.
78
+ */
79
+ export async function refreshModelRegistryAfterWrite(
80
+ options: RegistryWriteRefreshOptions = {},
81
+ deps: RegistryRefreshDeps = defaults,
82
+ ): Promise<HarnessId[]> {
83
+ await deps.restartUtilities();
84
+
85
+ const sharing = options.probes === false
86
+ ? []
87
+ : deps.sharing(options.path ?? (await deps.registryPath()));
88
+
89
+ if (options.probes !== false) {
90
+ for (const id of sharing) await deps.forget(id);
91
+ if (options.reprobe) {
92
+ await deps.reprobe(sharing, options.cwd ?? process.cwd());
93
+ }
94
+ }
95
+
96
+ deps.invalidate();
97
+ return sharing;
98
+ }
@@ -39,10 +39,11 @@ export async function configureChild(proc: RpcProcess): Promise<void> {
39
39
  // Full accumulated `message_update` frames (see the module doc): the streaming
40
40
  // tool call's name/id live on the seed block, which delta mode drops.
41
41
  await proc.sendCommand({ type: 'set_event_filter', events: null, messageUpdates: 'full' }).catch(() => {});
42
- // Grouped `ask` dialogs: every question of one `ask` tool call in a SINGLE
42
+ // Grouped `ask` dialogs: every question of one ask in a SINGLE
43
43
  // `extension_ui_request` (`method:"ask"`, with `multi`/`recommended`), answered
44
- // by one `answers` response. Without this omp loops one `select` per question,
45
- // which is what the ask card's per-question bookkeeping exists to reassemble.
46
- // Verified on 18.8.3: two questions (one `multi`) arrived in one request.
44
+ // by one `answers` response. omp 18.18.3 no longer routes its OWN `ask` tool
45
+ // through this (the tool takes an HTML form now and the RPC host walks its
46
+ // fields one dialog at a time), but extensions and the ratchet still use the
47
+ // grouped dialog, and an older child still takes this path for the tool.
47
48
  await proc.sendCommand({ type: 'set_ask_dialog', enabled: true }).catch(() => {});
48
49
  }
@@ -119,7 +119,8 @@ describe('command classification sets', () => {
119
119
  test('image-bearing commands and answerable UI methods', () => {
120
120
  expect([...IMAGE_BEARING_COMMANDS].sort()).toEqual(['abort_and_prompt', 'follow_up', 'prompt', 'steer']);
121
121
  // `ask` is the grouped dialog `configureChild` opts into with
122
- // `set_ask_dialog`: omp parks the tool call on it exactly as it does on a
122
+ // `set_ask_dialog` (extensions and the ratchet; omp's own tool moved to an
123
+ // HTML form in 18.18.3): the agent parks on it exactly as it does on a
123
124
  // `select`, so a list without it leaves the frame unremembered and the
124
125
  // question unanswerable after a reload.
125
126
  expect(Object.keys(ANSWERABLE_UI_METHODS).sort()).toEqual(['ask', 'confirm', 'editor', 'input', 'select']);
@@ -32,6 +32,7 @@ import { describePosix } from '@/test-support/platform';
32
32
  import { invalidateOmpCliCache } from '@/server/lib/omp/core/cli';
33
33
  import { stopDiscoveryRootsWatch } from '@/server/lib/omp/config/roots-watch.server';
34
34
  import { getRpcSession, startRpcSession } from '@/server/lib/omp/rpc/session-registry';
35
+ import { isolateDb, releaseDb } from '@/test-support/isolated-db';
35
36
 
36
37
  /** One line per spawned child, written by the scripted omp. */
37
38
  interface ForkRecord {
@@ -53,12 +54,19 @@ const ENV_KEYS = [
53
54
  'FAKE_OMP_FORK_LOG',
54
55
  ] as const;
55
56
 
56
- beforeEach(() => {
57
+ beforeEach(async () => {
57
58
  root = mkdtempSync(join(tmpdir(), 'omp-fork-test-'));
58
59
  saved = Object.fromEntries(ENV_KEYS.map((key) => [key, Bun.env[key]]));
60
+ // The registry's spawn path persists `harness_sessions` rows. Assigning
61
+ // `KABMO_DB_PATH` here is NOT isolation: the handle is a process-wide
62
+ // singleton, so a sibling suite that already opened the developer's real
63
+ // `~/.kabmo/db.sqlite` makes the assignment inert and every spawn below
64
+ // writes a row there (measured: 141 `omp-fork-test-*` rows in a live
65
+ // install). `isolateDb` closes that handle before it points the path at a
66
+ // fresh temp file.
67
+ await isolateDb();
59
68
  Bun.env.KABMO_OMP_BIN = join(import.meta.dir, '../../../../test-support/fake-omp-fork.ts');
60
69
  Bun.env.PI_CODING_AGENT_DIR = join(root, 'agent');
61
- Bun.env.KABMO_DB_PATH = join(root, 'db.sqlite');
62
70
  Bun.env.SYNC_WORKSPACE = 'false';
63
71
  Bun.env.FAKE_OMP_FORK_ON_RESUME = '1';
64
72
  Bun.env.FAKE_OMP_FORK_LOG = join(root, 'forks.jsonl');
@@ -66,10 +74,13 @@ beforeEach(() => {
66
74
  delete globalThis.__ompStartLocks;
67
75
  });
68
76
 
69
- afterEach(() => {
77
+ afterEach(async () => {
70
78
  stopDiscoveryRootsWatch();
71
79
  delete globalThis.__ompSessions;
72
80
  delete globalThis.__ompStartLocks;
81
+ // Close and drop the temp handle BEFORE restoring `KABMO_DB_PATH`: leaving it
82
+ // in the process-wide slot sends the next suite's writes to this deleted file.
83
+ await releaseDb();
73
84
  for (const key of ENV_KEYS) {
74
85
  const value = saved[key];
75
86
  if (value === undefined) delete Bun.env[key];
@@ -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) => {
@@ -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(() => {
@@ -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
  *
@@ -90,15 +110,43 @@ async function markEndStatus(sessionId: string, host: TerminalSettleHost, messag
90
110
  }
91
111
 
92
112
  /**
93
- * Run the side effects a terminal run end owns.
113
+ * Report a refused `prompt` response as a failed child outcome.
94
114
  *
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.
115
+ * A refused prompt opens no turn, so no `agent_end` will ever settle it. The
116
+ * check lives here because this module already owns the outcome vocabulary.
98
117
  */
118
+ export function noteRefusedPrompt(
119
+ event: { type?: string; success?: unknown; command?: unknown; error?: unknown },
120
+ sessionId: string,
121
+ ): void {
122
+ if (event.type !== 'response' || event.success !== false || event.command !== 'prompt' || !sessionId) return;
123
+ void noteChildOutcome({
124
+ sessionId,
125
+ status: 'failed',
126
+ failure: typeof event.error === 'string' ? event.error : 'Prompt failed',
127
+ }).catch((error: unknown) => {
128
+ console.error('[sessions] could not record a refused prompt:', error);
129
+ });
130
+ }
131
+
132
+ /** Run the side effects a terminal run end owns. */
99
133
  export function settleTerminalRun(host: TerminalSettleHost, messages: unknown): void {
100
134
  const aborted = endedAborted(host, messages);
135
+ const failure = aborted ? null : endedFailure(messages);
101
136
  if (host.sessionId) void markEndStatus(host.sessionId, host, messages);
137
+ // Delegation is reported here, not from the route: this frame is the only
138
+ // moment that knows a run genuinely ended, and a synthetic `run-settle`
139
+ // reconcile must report the same outcome as a real `agent_end`.
140
+ if (host.sessionId) {
141
+ void noteChildOutcome({
142
+ sessionId: host.sessionId,
143
+ status: aborted ? 'interrupted' : failure ? 'failed' : 'completed',
144
+ output: aborted ? null : lastAssistantText(messages),
145
+ ...(failure ? { failure } : {}),
146
+ }).catch((error: unknown) => {
147
+ console.error('[sessions] could not record a child outcome:', error);
148
+ });
149
+ }
102
150
  if (!aborted) {
103
151
  void triggerAutoSessionTitle(host, 'settle');
104
152
  void driveGoalAfterTurn({ host, messages });
@@ -10,19 +10,26 @@
10
10
  * The ORDER is the contract and it is enforced here, not by the callers:
11
11
  * 1. refuse a pending `new-…` chat and an id that is not one path segment —
12
12
  * both name something other than the session they appear to;
13
- * 2. refuse a session whose omp child is mid-turn (a run, a live subagent, or
14
- * a dialog the agent is blocked on) — the delete would kill work the user
15
- * can still see, and omp would flush the file back on shutdown anyway;
16
- * 3. destroy the child and AWAIT its exit — omp writes session state on
17
- * shutdown and would otherwise recreate the transcript just removed;
13
+ * 2. refuse a session whose child is mid-turn (a run, a live subagent, or a
14
+ * dialog the agent is blocked on) — the delete would kill work the user can
15
+ * still see, and omp would flush the file back on shutdown anyway. ANY
16
+ * harness: an ACP chat is live in the same registry and is just as much in
17
+ * the middle of something;
18
+ * 3. destroy the child and AWAIT its exit;
18
19
  * 4. purge side questions, then the transcript, artifacts and Kabmo rows.
19
20
  *
21
+ * Step 2/3 read `getLiveSession`, not the omp-only view: an ACP session has no
22
+ * `AgentSessionWrapper`, so the old `getRpcSession` lookup answered "nothing is
23
+ * live" for every non-omp chat — the delete then removed its rows while the
24
+ * agent process kept the conversation aliased in the registry.
25
+ *
20
26
  * A batch that re-implemented any of this would drift from the single delete,
21
27
  * and the drift would be silent: the route answers per-id verdicts either way.
22
28
  */
23
29
 
24
- import { getRpcSession } from '@/server/lib/omp/rpc/session-registry';
30
+ import { getLiveSession } from '@/server/lib/omp/rpc/session-registry';
25
31
  import { purgeSessionData } from '@/server/lib/omp/session/delete.server';
32
+ import { dependentsDeepestFirst } from '@/server/lib/sessions/lifecycle.server';
26
33
  import { purgeBtwForSession } from '@/server/lib/btw/purge.server';
27
34
  import { isSinglePathSegment } from '@/server/lib/fs/path-segment';
28
35
  import { isMockMode } from '@/server/mock.server';
@@ -61,8 +68,9 @@ export async function removeSession(sessionId: string): Promise<SessionRemoval>
61
68
 
62
69
  try {
63
70
  // A live child is the only other writer of the transcript. Busy means a
64
- // turn, a live subagent, or a dialog omp is parked on.
65
- const live = getRpcSession(sessionId);
71
+ // turn, a live subagent, or a dialog the agent is parked on — omp's child
72
+ // and an ACP agent's alike.
73
+ const live = getLiveSession(sessionId);
66
74
  if (live?.isAlive()) {
67
75
  if (live.isBusy()) {
68
76
  return {
@@ -99,3 +107,49 @@ export async function removeSession(sessionId: string): Promise<SessionRemoval>
99
107
  };
100
108
  }
101
109
  }
110
+
111
+ export interface SessionTreeRemoval {
112
+ result: SessionRemoval;
113
+ /** Dependents removed before the root, deepest first. */
114
+ removedDependents: string[];
115
+ }
116
+
117
+ function busyRemoval(sessionId: string): SessionRemoval {
118
+ return {
119
+ ok: false,
120
+ status: 409,
121
+ code: 'session_busy',
122
+ error: `Session ${sessionId} is working. Stop the run before deleting the tree.`,
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Remove a session AND its dependents.
128
+ *
129
+ * Every dependent is prechecked for a busy child before anything is deleted: a
130
+ * partial cascade is worse than a refusal, because the user cannot tell which
131
+ * half of the tree disappeared. Deepest first, so a parent never loses the rows
132
+ * that name it before the children are gone.
133
+ */
134
+ export async function removeSessionTree(sessionId: string): Promise<SessionTreeRemoval> {
135
+ const rootLive = getLiveSession(sessionId);
136
+ if (rootLive?.isAlive() && rootLive.isBusy()) {
137
+ return { result: busyRemoval(sessionId), removedDependents: [] };
138
+ }
139
+
140
+ const dependents = await dependentsDeepestFirst(sessionId);
141
+ for (const id of dependents) {
142
+ const live = getLiveSession(id);
143
+ if (live?.isAlive() && live.isBusy()) {
144
+ return { result: busyRemoval(id), removedDependents: [] };
145
+ }
146
+ }
147
+
148
+ const removedDependents: string[] = [];
149
+ for (const id of dependents) {
150
+ const verdict = await removeSession(id);
151
+ if (!verdict.ok) return { result: verdict, removedDependents };
152
+ removedDependents.push(id);
153
+ }
154
+ return { result: await removeSession(sessionId), removedDependents };
155
+ }
@@ -18,6 +18,10 @@
18
18
  * - its sibling artifacts directory, which holds the subagent transcripts;
19
19
  * - the `archived_sessions`, `session_ui_state`, `session_stream_state`,
20
20
  * `queued_messages` and `chat_sessions` rows for that id;
21
+ * - the `harness_sessions`, `harness_goal_state` and `harness_usage_state`
22
+ * rows, which are the WHOLE record of a chat that ran on an ACP agent (its
23
+ * transcript is written by nobody Kabmo can read) and its resume id, goal
24
+ * and token usage besides;
21
25
  * - in mock mode the demo `sessions` row and its `files` tree.
22
26
  *
23
27
  * The caller owns the process: a live omp child MUST be destroyed before this
@@ -37,6 +41,7 @@ import { emitRealtimeSignal } from '@/server/lib/realtime/signals.server';
37
41
  import { failWaitingOn } from '@/server/lib/waiting/store.server';
38
42
  import { siblingDirForSession } from '@/server/lib/omp/subagent/history/paths';
39
43
  import { isSinglePathSegment } from '@/server/lib/fs/path-segment';
44
+ import { deleteSessionRelations } from '@/server/lib/sessions/relations.server';
40
45
 
41
46
  export interface SessionPurgeResult {
42
47
  /** Something keyed to this id existed — a transcript, a mock session row, or
@@ -62,6 +67,14 @@ const SESSION_ROW_DELETES: readonly (readonly [string, string])[] = [
62
67
  ['queued_messages', 'session_id'],
63
68
  ['chat_sessions', 'session_id'],
64
69
  ['files', 'session_id'],
70
+ // An ACP chat has no transcript for the scan to lose: `harness_sessions` IS
71
+ // its row, so leaving it behind both refused the delete as "not found" (nothing
72
+ // else matched) and, for `omp-acp` whose JSONL did exist, re-listed the chat
73
+ // from the record the moment the file was gone. The goal and usage rows are
74
+ // keyed to the same id and would otherwise outlive the chat they describe.
75
+ ['harness_sessions', 'session_id'],
76
+ ['harness_goal_state', 'session_id'],
77
+ ['harness_usage_state', 'session_id'],
65
78
  ];
66
79
 
67
80
  async function purgeKabmoRows(db: DbClient, sessionId: string): Promise<number> {
@@ -71,6 +84,10 @@ async function purgeKabmoRows(db: DbClient, sessionId: string): Promise<number>
71
84
  changes += result.changes ?? 0;
72
85
  }
73
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(() => {});
74
91
  return changes + (mockRow.changes ?? 0);
75
92
  }
76
93