@kabmo-labs/kabmo 0.27.0 → 0.28.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 (303) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +495 -467
  3. package/dist/client/static/js/index-81f7berm.css +1 -0
  4. package/dist/client/static/js/{index-e3qh2yps.js → index-xzvyrxya.js} +795 -795
  5. package/marketplace/plugins/command-runner/package.json +3 -17
  6. package/marketplace/plugins/command-runner/settings-schema.json +14 -0
  7. package/marketplace/plugins/git-forge/README.md +17 -7
  8. package/marketplace/plugins/git-forge/package.json +4 -30
  9. package/marketplace/plugins/git-forge/panel.css +16 -0
  10. package/marketplace/plugins/git-forge/settings-schema.json +27 -0
  11. package/marketplace/plugins/git-forge/src/panel/Badge.tsx +35 -22
  12. package/marketplace/plugins/git-forge/src/panel/Change.tsx +20 -24
  13. package/marketplace/plugins/git-forge/src/panel/CiBadge.tsx +16 -7
  14. package/marketplace/plugins/git-forge/src/panel/Credential.tsx +31 -26
  15. package/marketplace/plugins/git-forge/src/panel/Glyph.tsx +18 -2
  16. package/marketplace/plugins/git-forge/src/panel/Header.tsx +160 -96
  17. package/marketplace/plugins/git-forge/src/panel/ItemView.tsx +60 -44
  18. package/marketplace/plugins/git-forge/src/panel/List.tsx +150 -22
  19. package/marketplace/plugins/git-forge/src/panel/Row.tsx +11 -5
  20. package/marketplace/plugins/git-forge/src/panel/Sidebar.tsx +17 -15
  21. package/marketplace/plugins/git-forge/src/panel/Write.tsx +84 -61
  22. package/marketplace/plugins/git-forge/src/panel/format.test.ts +99 -0
  23. package/marketplace/plugins/git-forge/src/panel/format.ts +59 -16
  24. package/marketplace/plugins/git-forge/src/panel/index.test.tsx +109 -5
  25. package/marketplace/plugins/git-forge/src/panel/index.tsx +37 -4
  26. package/marketplace/plugins/git-forge/src/panel/use-forge.ts +17 -0
  27. package/marketplace/plugins/git-forge/src/panel/write.test.tsx +31 -0
  28. package/marketplace/plugins/session-info/package.json +2 -10
  29. package/marketplace/plugins/session-info/settings-schema.json +8 -0
  30. package/marketplace/plugins/stats/README.md +17 -5
  31. package/marketplace/plugins/stats/package.json +3 -23
  32. package/marketplace/plugins/stats/settings-schema.json +20 -0
  33. package/marketplace/plugins/stats/src/app.tsx +1 -1
  34. package/marketplace/plugins/stats/src/groups.test.ts +46 -1
  35. package/marketplace/plugins/stats/src/groups.ts +22 -11
  36. package/marketplace/plugins/stats/src/harness-leases.test.ts +84 -0
  37. package/marketplace/plugins/stats/src/harness-leases.ts +132 -0
  38. package/marketplace/plugins/stats/src/labels.test.ts +54 -1
  39. package/marketplace/plugins/stats/src/labels.ts +33 -7
  40. package/marketplace/plugins/stats/src/sampler.test.ts +61 -0
  41. package/marketplace/plugins/stats/src/sampler.ts +39 -5
  42. package/marketplace/plugins/stats/src/snapshot.ts +6 -0
  43. package/package.json +2 -2
  44. package/src/client/components/common/harness-glyph/index.tsx +18 -1
  45. package/src/client/components/common/session-actions-menu/index.test.tsx +106 -0
  46. package/src/client/components/common/session-actions-menu/index.tsx +43 -1
  47. package/src/client/components/common/session-row/TrailingSlot.tsx +9 -4
  48. package/src/client/components/common/session-row/index.tsx +4 -0
  49. package/src/client/components/common/session-row/session-row.test.tsx +6 -0
  50. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +2 -1
  51. package/src/client/components/layout/session-sidebar/SessionItem.tsx +9 -1
  52. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +2 -1
  53. package/src/client/components/layout/session-sidebar/scheduler-modal/ModelFields.tsx +202 -0
  54. package/src/client/components/layout/session-sidebar/scheduler-modal/TaskForm.tsx +80 -19
  55. package/src/client/components/layout/session-sidebar/scheduler-modal/TaskList.tsx +23 -3
  56. package/src/client/components/layout/session-sidebar/scheduler-modal/index.tsx +3 -0
  57. package/src/client/components/mobile/mobile-right-sidebar/EditorSurface.tsx +156 -0
  58. package/src/client/components/mobile/mobile-right-sidebar/FullEditor.tsx +41 -86
  59. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +2 -1
  60. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.test.ts +6 -0
  61. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +9 -1
  62. package/src/client/components/settings/Modal.tsx +6 -2
  63. package/src/client/components/settings/Sidebar.tsx +30 -3
  64. package/src/client/components/settings/categories/HarnessSettings.tsx +11 -7
  65. package/src/client/components/settings/categories/NotificationSettings.test.tsx +40 -15
  66. package/src/client/components/settings/categories/NotificationSettings.tsx +142 -64
  67. package/src/client/components/settings/categories/PanelPluginSettings.tsx +1 -1
  68. package/src/client/components/settings/categories/harness-settings/CustomHarnessForm.tsx +186 -0
  69. package/src/client/components/settings/categories/panel-plugins/InstalledList.tsx +11 -0
  70. package/src/client/components/settings/categories/panel-plugins/PluginCard.test.tsx +1 -0
  71. package/src/client/components/settings/categories/panel-plugins/PluginCard.tsx +15 -1
  72. package/src/client/components/settings/categories/panel-plugins/SettingsModal.test.tsx +165 -0
  73. package/src/client/components/settings/categories/panel-plugins/SettingsModal.tsx +260 -0
  74. package/src/client/components/workspace/chat-timeline/AiMessageFooter.fork.test.ts +24 -0
  75. package/src/client/components/workspace/chat-timeline/AiMessageFooter.tsx +8 -4
  76. package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +34 -0
  77. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +3 -2
  78. package/src/client/components/workspace/chat-timeline/MessageItem.fork.test.ts +80 -0
  79. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +9 -3
  80. package/src/client/components/workspace/chat-timeline/MessageList.tsx +3 -1
  81. package/src/client/components/workspace/chat-timeline/RunFooter.tsx +2 -1
  82. package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +2 -1
  83. package/src/client/components/workspace/chat-timeline/chat-input/ComposerRows.tsx +8 -0
  84. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.test.tsx +9 -0
  85. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.tsx +4 -1
  86. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.tsx +24 -0
  87. package/src/client/components/workspace/chat-timeline/chat-input/WaitingDependencyPicker.tsx +13 -20
  88. package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +2 -0
  89. package/src/client/components/workspace/chat-timeline/chat-input/props.ts +5 -5
  90. package/src/client/components/workspace/chat-timeline/index.tsx +11 -5
  91. package/src/client/components/workspace/chat-timeline/target-picker/DraftTargetRow.tsx +1 -9
  92. package/src/client/components/workspace/chat-timeline/target-picker/ParentSessionPicker.test.tsx +101 -0
  93. package/src/client/components/workspace/chat-timeline/target-picker/ParentSessionPicker.tsx +2 -2
  94. package/src/client/components/workspace/editor/FilePane.tsx +9 -4
  95. package/src/client/components/workspace/editor/Notices.tsx +2 -2
  96. package/src/client/components/workspace/editor/Pane.tsx +2 -2
  97. package/src/client/components/workspace/editor/Toolbar.tsx +16 -10
  98. package/src/client/components/workspace/editor/index.tsx +6 -10
  99. package/src/client/components/workspace/editor/toolbar-clusters.test.ts +4 -3
  100. package/src/client/components/workspace/editor/toolbar-clusters.tsx +23 -14
  101. package/src/client/components/workspace/terminal-panel/RealtimeTerminalView.tsx +9 -1
  102. package/src/client/components/workspace/terminal-panel/focus.test.ts +70 -0
  103. package/src/client/components/workspace/terminal-panel/focus.ts +46 -0
  104. package/src/client/components/workspace/terminal-panel/index.tsx +14 -1
  105. package/src/client/components/workspace/terminal-panel/mount.ts +17 -9
  106. package/src/client/components/workspace/terminal-panel/scroll-hold.test.ts +158 -0
  107. package/src/client/components/workspace/terminal-panel/scroll-hold.ts +136 -0
  108. package/src/client/hooks/chat/composer/use-draft.ts +45 -1
  109. package/src/client/hooks/chat/omp/pending-sessions.waiting.test.ts +11 -10
  110. package/src/client/hooks/chat/omp/pending-waiting.ts +15 -7
  111. package/src/client/hooks/chat/omp/prompt-send.test.ts +11 -0
  112. package/src/client/hooks/chat/omp/prompt-send.ts +3 -0
  113. package/src/client/hooks/chat/timeline/actions.ts +4 -4
  114. package/src/client/hooks/chat/timeline/composer-modes.ts +13 -2
  115. package/src/client/hooks/chat/timeline/fork-open.ts +52 -0
  116. package/src/client/hooks/chat/timeline/index.ts +5 -2
  117. package/src/client/hooks/chat/timeline/mode-availability.ts +7 -0
  118. package/src/client/hooks/chat/timeline/modes-contract.ts +6 -0
  119. package/src/client/hooks/chat/timeline/modes-hydrate.ts +93 -0
  120. package/src/client/hooks/chat/timeline/modes.ts +32 -52
  121. package/src/client/hooks/chat/timeline/new-chat-open.ts +7 -6
  122. package/src/client/hooks/chat/timeline/new-chat.ts +10 -1
  123. package/src/client/hooks/chat/timeline/pending-dispatch.ts +4 -0
  124. package/src/client/hooks/chat/timeline/pending-session-mode.test.ts +136 -0
  125. package/src/client/hooks/chat/timeline/pending-session-mode.ts +69 -0
  126. package/src/client/hooks/chat/timeline/pending-warmup.test.ts +147 -0
  127. package/src/client/hooks/chat/timeline/pending-warmup.ts +62 -0
  128. package/src/client/hooks/chat/timeline/run-identity.test.ts +12 -0
  129. package/src/client/hooks/chat/timeline/run-identity.ts +4 -1
  130. package/src/client/hooks/chat/timeline/send-props.ts +2 -0
  131. package/src/client/hooks/chat/timeline/send-steer.test.ts +1 -0
  132. package/src/client/hooks/chat/timeline/send.test-util.ts +1 -0
  133. package/src/client/hooks/chat/timeline/send.test.ts +1 -0
  134. package/src/client/hooks/chat/timeline/session-harness.ts +4 -0
  135. package/src/client/hooks/chat/timeline/use-fork-session.ts +9 -22
  136. package/src/client/hooks/chat/waiting/cancel.ts +13 -6
  137. package/src/client/hooks/chat/waiting/choice.ts +13 -16
  138. package/src/client/hooks/chat/waiting/composer-wait.ts +70 -0
  139. package/src/client/hooks/chat/waiting/dispatch.ts +48 -28
  140. package/src/client/hooks/chat/waiting/held.ts +37 -13
  141. package/src/client/hooks/chat/waiting/hold.test.ts +22 -0
  142. package/src/client/hooks/chat/waiting/hold.ts +20 -11
  143. package/src/client/hooks/chat/waiting/restore.test.ts +69 -0
  144. package/src/client/hooks/chat/waiting/restore.ts +34 -0
  145. package/src/client/hooks/chat/waiting/store.ts +9 -3
  146. package/src/client/hooks/editor/file-editor-types.ts +21 -12
  147. package/src/client/hooks/editor/save-file.test.ts +1 -1
  148. package/src/client/hooks/editor/save-file.ts +35 -8
  149. package/src/client/hooks/editor/target-key.ts +17 -0
  150. package/src/client/hooks/editor/use-disk-digest.test.ts +82 -0
  151. package/src/client/hooks/editor/use-disk-digest.ts +164 -0
  152. package/src/client/hooks/editor/use-disk-sync.ts +212 -0
  153. package/src/client/hooks/editor/use-file-cache.ts +113 -0
  154. package/src/client/hooks/editor/use-file-editor.test.ts +90 -0
  155. package/src/client/hooks/editor/use-file-editor.ts +90 -52
  156. package/src/client/hooks/editor/use-file-read.ts +24 -10
  157. package/src/client/hooks/editor/use-file-writes.ts +4 -4
  158. package/src/client/hooks/models/harness-catalog.ts +15 -0
  159. package/src/client/hooks/ui/notifications.ts +17 -8
  160. package/src/client/hooks/workspace/panel-registry.ts +1 -1
  161. package/src/client/hooks/workspace/scheduled-tasks.ts +26 -11
  162. package/src/client/lib/notifications/os.test.ts +1 -30
  163. package/src/client/lib/notifications/os.ts +0 -15
  164. package/src/client/lib/notifications/platform.test.ts +68 -0
  165. package/src/client/lib/notifications/platform.ts +36 -0
  166. package/src/server/index.ts +7 -0
  167. package/src/server/lib/harness/acp/client.ts +81 -87
  168. package/src/server/lib/harness/acp/prewarm.server.ts +237 -0
  169. package/src/server/lib/harness/acp/prewarm.test.ts +171 -0
  170. package/src/server/lib/harness/acp/prompt.test.ts +70 -1
  171. package/src/server/lib/harness/acp/prompt.ts +32 -1
  172. package/src/server/lib/harness/acp/protocol.ts +23 -0
  173. package/src/server/lib/harness/acp/session-handshake.test.ts +26 -0
  174. package/src/server/lib/harness/acp/session-handshake.ts +22 -20
  175. package/src/server/lib/harness/acp/session-options.ts +16 -0
  176. package/src/server/lib/harness/acp/session-process.ts +43 -0
  177. package/src/server/lib/harness/acp/session.ts +11 -12
  178. package/src/server/lib/harness/acp/stdio.ts +129 -0
  179. package/src/server/lib/harness/acp/verbs.test.ts +97 -0
  180. package/src/server/lib/harness/acp/verbs.ts +16 -6
  181. package/src/server/lib/harness/auto-probe.server.ts +4 -3
  182. package/src/server/lib/harness/capabilities.ts +8 -0
  183. package/src/server/lib/harness/config.server.ts +3 -2
  184. package/src/server/lib/harness/custom.server.ts +209 -0
  185. package/src/server/lib/harness/launch.ts +6 -1
  186. package/src/server/lib/harness/register.server.ts +8 -1
  187. package/src/server/lib/harness/schema.server.ts +21 -0
  188. package/src/server/lib/harness/session-lease.server.test.ts +99 -0
  189. package/src/server/lib/harness/session-lease.server.ts +193 -0
  190. package/src/server/lib/harness/session-store.server.test.ts +8 -8
  191. package/src/server/lib/harness/session-store.server.ts +25 -4
  192. package/src/server/lib/harness/session-title.server.ts +12 -2
  193. package/src/server/lib/harness/spawn.server.ts +123 -20
  194. package/src/server/lib/harness/update-queue.server.ts +3 -3
  195. package/src/server/lib/lifecycle/after-listen.ts +12 -1
  196. package/src/server/lib/lifecycle/paths.ts +19 -1
  197. package/src/server/lib/mcp/registry.server.ts +155 -0
  198. package/src/server/lib/mcp/registry.test.ts +169 -0
  199. package/src/server/lib/mcp/store.server.ts +38 -0
  200. package/src/server/lib/omp/rpc/frame-fold-contract.ts +59 -0
  201. package/src/server/lib/omp/rpc/frame-fold-frames.test.ts +64 -1
  202. package/src/server/lib/omp/rpc/frame-fold-host.test-util.ts +2 -1
  203. package/src/server/lib/omp/rpc/frame-fold.test.ts +2 -1
  204. package/src/server/lib/omp/rpc/frame-fold.ts +6 -45
  205. package/src/server/lib/omp/rpc/prewarm-pool.ts +19 -5
  206. package/src/server/lib/omp/rpc/run-model.test.ts +116 -0
  207. package/src/server/lib/omp/rpc/run-model.ts +4 -2
  208. package/src/server/lib/omp/session/sidebar-data.harness.test.ts +6 -3
  209. package/src/server/lib/omp/session/standby.server.ts +13 -2
  210. package/src/server/lib/panels/manifest.test.ts +47 -1
  211. package/src/server/lib/panels/manifest.ts +19 -0
  212. package/src/server/lib/panels/registry.server.ts +19 -2
  213. package/src/server/lib/panels/scan.server.ts +26 -2
  214. package/src/server/lib/panels/settings-schema.server.ts +72 -0
  215. package/src/server/lib/plugins/background.server.ts +21 -3
  216. package/src/server/lib/plugins/background.test.ts +13 -0
  217. package/src/server/lib/plugins/loader.server.ts +35 -51
  218. package/src/server/lib/plugins/mcp.server.ts +100 -0
  219. package/src/server/lib/plugins/mcp.test.ts +75 -0
  220. package/src/server/lib/plugins/schedule-runner.server.ts +153 -0
  221. package/src/server/lib/plugins/schedule-runner.test.ts +186 -0
  222. package/src/server/lib/plugins/schedule-store.server.ts +107 -0
  223. package/src/server/lib/plugins/schema.server.ts +8 -0
  224. package/src/server/lib/plugins/settings.server.ts +56 -19
  225. package/src/server/lib/plugins/shutdown.server.ts +58 -0
  226. package/src/server/lib/plugins/shutdown.test.ts +28 -3
  227. package/src/server/lib/realtime/topics/global.server.ts +5 -1
  228. package/src/server/lib/schedule/rows.server.ts +9 -0
  229. package/src/server/lib/schedule/runtime.server.test.ts +91 -0
  230. package/src/server/lib/schedule/runtime.server.ts +101 -23
  231. package/src/server/lib/schedule/schema.server.ts +15 -0
  232. package/src/server/lib/schedule/store.server.test.ts +34 -0
  233. package/src/server/lib/schedule/store.server.ts +33 -9
  234. package/src/server/lib/sessions/fork.server.test.ts +47 -0
  235. package/src/server/lib/sessions/fork.server.ts +17 -1
  236. package/src/server/lib/sessions/spawn.server.ts +2 -2
  237. package/src/server/lib/waiting/runtime.server.test.ts +48 -0
  238. package/src/server/lib/waiting/runtime.server.ts +22 -0
  239. package/src/server/lib/waiting/schema.server.ts +8 -0
  240. package/src/server/lib/waiting/store.server.test.ts +14 -0
  241. package/src/server/lib/waiting/store.server.ts +6 -2
  242. package/src/server/routes/agent/command-resume.test.ts +9 -4
  243. package/src/server/routes/agent/new-mode.test.ts +40 -0
  244. package/src/server/routes/agent/new.ts +31 -10
  245. package/src/server/routes/agent/prewarm.ts +48 -7
  246. package/src/server/routes/fs/action.ts +9 -1
  247. package/src/server/routes/fs/digest.test.ts +100 -0
  248. package/src/server/routes/fs/digest.ts +106 -0
  249. package/src/server/routes/fs/index.ts +2 -0
  250. package/src/server/routes/fs/read.ts +6 -1
  251. package/src/server/routes/harness/custom.test.ts +131 -0
  252. package/src/server/routes/harness/import-action.ts +2 -2
  253. package/src/server/routes/harness/root.ts +41 -8
  254. package/src/server/routes/harness/update.ts +2 -2
  255. package/src/server/routes/panels/bindings.ts +2 -0
  256. package/src/server/routes/panels/settings.test.ts +165 -0
  257. package/src/server/routes/panels/settings.ts +106 -0
  258. package/src/server/routes/schedule/body.ts +14 -0
  259. package/src/server/routes/schedule/index.ts +28 -4
  260. package/src/server/routes/settings/mcp.ts +9 -26
  261. package/src/server/routes/waiting/index.ts +21 -2
  262. package/src/server/routes/waiting/routes.test.ts +21 -0
  263. package/src/shared/lib/chat/composer/delegation.ts +3 -3
  264. package/src/shared/lib/chat/timeline/fork-anchor.test.ts +97 -0
  265. package/src/shared/lib/chat/timeline/fork-anchor.ts +47 -0
  266. package/src/shared/lib/fs/content-hash.ts +29 -0
  267. package/src/shared/lib/harness/catalog.ts +48 -6
  268. package/src/shared/lib/harness/fork.ts +60 -0
  269. package/src/shared/lib/harness/mcp-facts.test.ts +30 -0
  270. package/src/shared/lib/harness/mcp-facts.ts +65 -0
  271. package/src/shared/lib/harness/menu.test.ts +16 -1
  272. package/src/shared/lib/harness/menu.ts +2 -2
  273. package/src/shared/lib/harness/rewind.ts +6 -6
  274. package/src/shared/lib/harness/session-modes.ts +31 -0
  275. package/src/shared/lib/harness/transcript.test.ts +29 -0
  276. package/src/shared/lib/harness/transcript.ts +19 -0
  277. package/src/shared/lib/notifications/settings.test.ts +21 -0
  278. package/src/shared/lib/notifications/settings.ts +24 -0
  279. package/src/shared/lib/omp/session/prewarm.test.ts +28 -4
  280. package/src/shared/lib/omp/session/prewarm.ts +25 -6
  281. package/src/shared/lib/omp/session/stream-state.server.test.ts +25 -0
  282. package/src/shared/lib/omp/session/stream-state.server.ts +8 -4
  283. package/src/shared/lib/panels/capabilities.test.ts +1 -1
  284. package/src/shared/lib/panels/capabilities.ts +3 -0
  285. package/src/shared/lib/plugins/settings.ts +22 -0
  286. package/src/shared/lib/schedule/parse.test.ts +48 -0
  287. package/src/shared/lib/schedule/parse.ts +69 -45
  288. package/src/shared/lib/schedule/timezone.ts +128 -0
  289. package/src/shared/lib/settings/defaults.ts +2 -0
  290. package/src/shared/lib/workspace/refresh-cadence.test.ts +25 -1
  291. package/src/shared/lib/workspace/relative-time.ts +16 -0
  292. package/src/shared/types/harness.ts +7 -0
  293. package/src/shared/types/omp/agent.ts +6 -0
  294. package/src/shared/types/panels-registry.ts +3 -3
  295. package/src/shared/types/panels.ts +4 -2
  296. package/src/shared/types/schedule.ts +13 -0
  297. package/src/shared/types/settings/state.ts +12 -1
  298. package/src/shared/types/waiting.ts +9 -0
  299. package/src/test-support/file-editor.test-util.ts +70 -5
  300. package/dist/client/static/js/index-32rpkj6b.css +0 -1
  301. package/src/client/hooks/editor/use-external-change-notice.ts +0 -71
  302. package/src/client/hooks/editor/use-external-change.test.ts +0 -88
  303. package/src/client/hooks/editor/use-external-change.ts +0 -146
@@ -25,17 +25,15 @@
25
25
  * explicitly refused — never dropped.
26
26
  */
27
27
 
28
- import type { Subprocess } from 'bun';
29
- import { readLines } from '@/server/lib/omp/rpc/lines';
30
28
  import { PendingCalls } from '@/server/lib/harness/acp/calls';
31
- import { killProcessTree } from '@/server/lib/lifecycle/kill-tree';
32
- import { stripKabmoHostEnv, withToolchainPath } from '@kabmo-labs/kabmo-sdk';
29
+ import { AgentStdio } from '@/server/lib/harness/acp/stdio';
33
30
  import * as verbs from '@/server/lib/harness/acp/verbs';
34
31
  import { initializeAcpAgent } from '@/server/lib/harness/acp/client-initialize';
35
32
  import { ACP_ERROR } from '@/server/lib/harness/acp/protocol';
36
33
  import type {
37
34
  AcpId,
38
35
  AcpInitializeResult,
36
+ AcpMcpServer,
39
37
  AcpNotification,
40
38
  AcpProtocolVersion,
41
39
  AcpRequest,
@@ -72,15 +70,13 @@ export interface AcpClientOptions {
72
70
  }
73
71
 
74
72
  const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
75
- const STDERR_TAIL_LIMIT = 8_000;
76
73
 
77
74
  export class AcpProcess {
78
- private readonly child: Subprocess<'pipe', 'pipe', 'pipe'>;
75
+ private readonly stdio: AgentStdio;
79
76
  private readonly pending = new PendingCalls();
80
77
  private readonly options: AcpClientOptions;
81
78
  private nextId = 1;
82
79
  private exited = false;
83
- private stderrTail = '';
84
80
  private writeQueue: Promise<void> = Promise.resolve();
85
81
  /** The negotiated ACP major. 1 until `initialize` answers; every verb that
86
82
  * changed shape between versions reads it. */
@@ -88,49 +84,38 @@ export class AcpProcess {
88
84
  /** Set once `initialize` answers, so a request sent earlier fails loudly
89
85
  * instead of racing the handshake. */
90
86
  private initialized = false;
87
+ /** The one `initialize` this process ever runs. A prewarmed child is handed
88
+ * to a session that would otherwise handshake a second time; the cached
89
+ * answer is what makes adopting it free. */
90
+ private init: Promise<AcpInitializeResult> | null = null;
91
+ /** The frame sinks, re-bindable: a prewarmed process is created before the
92
+ * session that will own it exists, so its handlers are attached at claim. */
93
+ private sinks: Pick<AcpClientOptions, 'onNotification' | 'onClientRequest' | 'onExit' | 'onStderr'>;
91
94
 
92
95
  constructor(options: AcpClientOptions) {
93
96
  this.options = options;
94
- const [command, ...args] = options.command;
95
- if (!command) throw new Error('ACP launch command is empty');
96
- const childEnv = withToolchainPath(
97
- stripKabmoHostEnv({ ...Bun.env, ...options.env }, process.platform),
98
- process.platform,
99
- );
100
- try {
101
- this.child = Bun.spawn({
102
- cmd: [command, ...args],
97
+ this.sinks = options;
98
+ this.stdio = new AgentStdio(
99
+ {
100
+ command: options.command,
103
101
  cwd: options.cwd,
104
- env: childEnv,
105
- stdin: 'pipe',
106
- stdout: 'pipe',
107
- stderr: 'pipe',
108
- windowsHide: true,
109
- // Its own process group, exactly like the omp child: an ACP adapter
110
- // spawns ITS own agent binary (codex-acp runs codex, pi-acp runs pi),
111
- // so killing only the adapter leaves the real agent running.
112
- detached: process.platform !== 'win32',
113
- });
114
- } catch (error) {
115
- throw new Error(
116
- `Could not start ${command}: ${error instanceof Error ? error.message : String(error)}`,
117
- );
118
- }
119
-
120
- void readLines(this.child.stdout, (line) => this.handleLine(line));
121
- void readLines(this.child.stderr, (line) => {
122
- this.stderrTail = `${this.stderrTail}${line}\n`.slice(-STDERR_TAIL_LIMIT);
123
- this.options.onStderr?.(line);
124
- });
125
- void this.child.exited.then((code) => {
126
- this.exited = true;
127
- // The agent's own last words, when it left any: `exited (code 0)` is what
128
- // a shadowed/deprecated binary prints while it explains itself on stderr,
129
- // and without the tail the spawn failure names nothing actionable.
130
- const detail = this.stderrTail.trim().split('\n').slice(-3).join(' · ');
131
- this.rejectAll(new Error(`ACP agent exited (code ${code})${detail ? ` — ${detail}` : ''}`));
132
- this.options.onExit?.({ code, signal: null, stderrTail: this.stderrTail });
133
- });
102
+ ...(options.env ? { env: options.env } : {}),
103
+ },
104
+ {
105
+ onLine: (line) => this.handleLine(line),
106
+ onStderr: (line) => this.sinks.onStderr?.(line),
107
+ onExit: ({ code, stderrTail }) => {
108
+ this.exited = true;
109
+ // The agent's own last words, when it left any: `exited (code 0)` is
110
+ // what a shadowed/deprecated binary prints while it explains itself on
111
+ // stderr, and without the tail the spawn failure names nothing
112
+ // actionable.
113
+ const detail = stderrTail.trim().split('\n').slice(-3).join(' · ');
114
+ this.rejectAll(new Error(`ACP agent exited (code ${code})${detail ? ` — ${detail}` : ''}`));
115
+ this.sinks.onExit?.({ code, signal: null, stderrTail });
116
+ },
117
+ },
118
+ );
134
119
  }
135
120
 
136
121
  get isAlive(): boolean {
@@ -138,15 +123,35 @@ export class AcpProcess {
138
123
  }
139
124
 
140
125
  get pid(): number | undefined {
141
- return this.child.pid ?? undefined;
126
+ return this.stdio.pid;
142
127
  }
143
128
 
144
- /** `initialize`; the client advertises exactly what it can serve. */
145
- async initialize(capabilities?: Record<string, unknown>, timeoutMs = 60_000): Promise<AcpInitializeResult> {
146
- const result = await initializeAcpAgent(this.call, capabilities, timeoutMs);
147
- this.protocolVersion = result.protocolVersion === 2 ? 2 : 1;
148
- this.initialized = true;
149
- return result;
129
+ /**
130
+ * `initialize`; the client advertises exactly what it can serve.
131
+ *
132
+ * Idempotent: a prewarmed process has already answered, and the session that
133
+ * adopts it must not pay a second round trip (or, worse, send a second
134
+ * `initialize` the agent may refuse).
135
+ */
136
+ initialize(capabilities?: Record<string, unknown>, timeoutMs = 60_000): Promise<AcpInitializeResult> {
137
+ this.init ??= initializeAcpAgent(this.call, capabilities, timeoutMs).then((result) => {
138
+ this.protocolVersion = result.protocolVersion === 2 ? 2 : 1;
139
+ this.initialized = true;
140
+ return result;
141
+ });
142
+ return this.init;
143
+ }
144
+
145
+ /**
146
+ * Re-bind the frame sinks.
147
+ *
148
+ * A prewarmed process is spawned before the session that will own it exists,
149
+ * so its notifications and agent→client requests have nowhere to go until the
150
+ * claim. Attaching here is what makes the warm child indistinguishable from a
151
+ * cold one for the rest of its life.
152
+ */
153
+ attachSinks(sinks: Pick<AcpClientOptions, 'onNotification' | 'onClientRequest' | 'onExit' | 'onStderr'>): void {
154
+ this.sinks = sinks;
150
155
  }
151
156
 
152
157
  get hasInitialized(): boolean {
@@ -157,20 +162,27 @@ export class AcpProcess {
157
162
  // Thin delegates to `verbs.ts`: the transport owns framing, the verbs own the
158
163
  // wire shape. Callers keep using `proc.newSession(...)`.
159
164
 
160
- newSession(cwd: string, timeoutMs?: number) {
161
- return verbs.newSession(this.call, cwd, timeoutMs, this.protocolVersion);
165
+ newSession(cwd: string, timeoutMs?: number, mcpServers?: AcpMcpServer[]) {
166
+ return verbs.newSession(this.call, cwd, timeoutMs, this.protocolVersion, mcpServers);
162
167
  }
163
168
 
164
- loadSession(sessionId: string, cwd: string, timeoutMs?: number) {
165
- return verbs.loadSession(this.call, sessionId, cwd, timeoutMs);
169
+ loadSession(sessionId: string, cwd: string, timeoutMs?: number, mcpServers?: AcpMcpServer[]) {
170
+ return verbs.loadSession(this.call, sessionId, cwd, timeoutMs, mcpServers);
166
171
  }
167
172
 
168
- resumeSession(sessionId: string, cwd: string, timeoutMs?: number) {
169
- return verbs.resumeSession(this.call, sessionId, cwd, timeoutMs, this.protocolVersion);
173
+ resumeSession(sessionId: string, cwd: string, timeoutMs?: number, mcpServers?: AcpMcpServer[]) {
174
+ return verbs.resumeSession(this.call, sessionId, cwd, timeoutMs, this.protocolVersion, mcpServers);
170
175
  }
171
176
 
172
- forkSession(sessionId: string, cwd: string, timeoutMs?: number, target?: Record<string, unknown>) {
173
- return verbs.forkSession(this.call, sessionId, cwd, timeoutMs, target);
177
+ forkSession(
178
+ sessionId: string,
179
+ cwd: string,
180
+ timeoutMs?: number,
181
+ target?: Record<string, unknown>,
182
+ meta?: Record<string, unknown>,
183
+ mcpServers?: AcpMcpServer[],
184
+ ) {
185
+ return verbs.forkSession(this.call, sessionId, cwd, timeoutMs, target, meta, mcpServers);
174
186
  }
175
187
 
176
188
  listSessions(cwd?: string, timeoutMs?: number) {
@@ -239,23 +251,7 @@ export class AcpProcess {
239
251
  /** Graceful then forceful shutdown of the whole process group. */
240
252
  async dispose(gracePeriodMs = 5_000): Promise<void> {
241
253
  if (this.exited) return;
242
- const exited = this.child.exited.then(() => undefined);
243
- try {
244
- this.child.stdin.end();
245
- } catch {
246
- // Already closed.
247
- }
248
- const term = setTimeout(() => {
249
- if (!this.exited) killProcessTree(this.child.pid, false, 'SIGTERM');
250
- }, gracePeriodMs);
251
- const kill = setTimeout(() => {
252
- if (!this.exited) killProcessTree(this.child.pid, true, 'SIGKILL');
253
- }, gracePeriodMs * 2);
254
- term.unref?.();
255
- kill.unref?.();
256
- await exited;
257
- clearTimeout(term);
258
- clearTimeout(kill);
254
+ await this.stdio.dispose(gracePeriodMs);
259
255
  this.rejectAll(new Error('ACP agent disposed'));
260
256
  }
261
257
 
@@ -284,14 +280,12 @@ export class AcpProcess {
284
280
  private write(frame: AcpRequest | AcpNotification | AcpResponse): void {
285
281
  if (this.exited) return;
286
282
  const line = `${JSON.stringify(frame)}\n`;
283
+ // Serialized: two frames interleaved on one pipe would corrupt the stream,
284
+ // and a closed pipe is reported by `exited` rather than thrown into the
285
+ // queue (which would wedge every later frame).
287
286
  this.writeQueue = this.writeQueue.then(async () => {
288
- try {
289
- this.child.stdin.write(line);
290
- await this.child.stdin.flush();
291
- } catch {
292
- // A closed pipe is reported by `exited`; the writer must not throw into
293
- // the queue and wedge every later frame.
294
- }
287
+ this.stdio.write(line);
288
+ await this.stdio.flush();
295
289
  });
296
290
  }
297
291
 
@@ -315,7 +309,7 @@ export class AcpProcess {
315
309
  if (record.id !== undefined && record.id !== null) {
316
310
  void this.handleAgentRequest(record.id as AcpId, record.method, record.params);
317
311
  } else {
318
- this.options.onNotification(record.method, (record.params ?? {}) as Record<string, unknown>);
312
+ this.sinks.onNotification(record.method, (record.params ?? {}) as Record<string, unknown>);
319
313
  }
320
314
  return;
321
315
  }
@@ -327,7 +321,7 @@ export class AcpProcess {
327
321
  private async handleAgentRequest(id: AcpId, method: string, params: unknown): Promise<void> {
328
322
  const bag = (params ?? {}) as Record<string, unknown>;
329
323
  try {
330
- const handled = await this.options.onClientRequest?.(id, method, bag);
324
+ const handled = await this.sinks.onClientRequest?.(id, method, bag);
331
325
  if (handled?.answered) {
332
326
  this.respond(id, handled.result);
333
327
  return;
@@ -0,0 +1,237 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The ACP prewarm pool: one started *process*, spawned ahead of the first
8
+ * prompt so the send adopts it instead of paying the agent's boot.
9
+ *
10
+ * A cold ACP chat costs a process spawn and an `initialize` handshake before
11
+ * `session/new` can even be asked. Measured on `omp-acp`: ~1 ms spawn, ~100 ms
12
+ * `initialize`, ~80-120 ms `session/new`. The first two do not depend on what
13
+ * the user is about to type, so they happen while the prompt is written.
14
+ *
15
+ * **Only `initialize`. Deliberately.** Warming through `session/new` was tried
16
+ * and reverted: `omp-acp` writes its session JSONL at that moment, and Kabmo's
17
+ * sidebar scans that directory — so a warm child that nobody claimed appeared as
18
+ * an empty chat row (measured: the file lands before any prompt, and it outlives
19
+ * the child). A prewarm must be invisible, so it stops at the handshake that
20
+ * creates nothing.
21
+ *
22
+ * **Why this pool can be warmer than omp's.** omp's modes ride the spawn
23
+ * ENVIRONMENT (`KABMO_MODES`), read once at session start, so an entry whose
24
+ * selection differs has to be killed. ACP publishes model, thinking level and
25
+ * mode as config selectors and the approval tier as in-process state; the
26
+ * adopting session applies them after `session/new`, exactly as a cold spawn
27
+ * does. A prewarmed process therefore serves ANY pick.
28
+ *
29
+ * The pool is keyed by harness + cwd. One pending chat runs one agent, so a
30
+ * second pick in the same folder replaces the first candidate; an unclaimed
31
+ * entry is also disposed after `ACP_PREWARM_TTL_MS`.
32
+ */
33
+
34
+ import { mintAgentEnvironment } from '@/server/lib/sessions/agent-token.server';
35
+ import { loadHarnessConfig, resolveLaunch } from '@/server/lib/harness/config.server';
36
+ import { sessionLaunchCommand } from '@/server/lib/harness/launch';
37
+ import { AcpProcess } from '@/server/lib/harness/acp/client';
38
+ import { IDLE_REAP_MS } from '@/server/lib/omp/rpc/constants';
39
+ import { withGatewayCompatibility } from '@/server/lib/harness/acp/gateway-env';
40
+ import { noteHarnessLease, removeHarnessLease } from '@/server/lib/harness/session-lease.server';
41
+ import type { HarnessId } from '@/shared/lib/harness/catalog';
42
+
43
+ /** How long an unclaimed warm agent is kept. Long enough to write a prompt,
44
+ * short enough that a pick the user abandoned costs one process, not a day. */
45
+ export const ACP_PREWARM_TTL_MS = IDLE_REAP_MS;
46
+
47
+ /** A spawned, initialized agent waiting for the chat that will adopt it. */
48
+ export interface PrewarmedAcp {
49
+ process: AcpProcess;
50
+ /** The callback credential its environment carries; the claim records it
51
+ * against the session id `session/new` answers. */
52
+ token: string;
53
+ }
54
+
55
+ export interface PrewarmedAcpEntry {
56
+ harness: HarnessId;
57
+ cwd: string;
58
+ createdAt: number;
59
+ /** Set by the claim BEFORE it awaits readiness: two sends racing one entry
60
+ * must not both adopt it. */
61
+ claimed: boolean;
62
+ /** Resolves the warm process, or null when the spawn failed or the child died
63
+ * before it was claimed. Never rejects — an entry nobody claims must not
64
+ * surface as an unhandled rejection. */
65
+ ready: Promise<PrewarmedAcp | null>;
66
+ }
67
+
68
+ declare global {
69
+ // eslint-disable-next-line no-var
70
+ var __kabmoAcpPrewarmed: Map<string, PrewarmedAcpEntry> | undefined;
71
+ }
72
+
73
+ export function getPrewarmedAcp(): Map<string, PrewarmedAcpEntry> {
74
+ globalThis.__kabmoAcpPrewarmed ??= new Map();
75
+ return globalThis.__kabmoAcpPrewarmed;
76
+ }
77
+
78
+ /** One entry per harness AND cwd: two agents in one folder are two processes. */
79
+ export function acpPrewarmKey(harness: HarnessId, cwd: string): string {
80
+ return `${harness}\u0000${cwd}`;
81
+ }
82
+
83
+ /** The seam a test drives; the real opener spawns a process. */
84
+ export interface AcpPrewarmDeps {
85
+ open: (harness: HarnessId, cwd: string) => Promise<PrewarmedAcp>;
86
+ }
87
+
88
+ /** The launch line and env a prewarm — and the spawn that adopts it — use. */
89
+ async function openProcess(harness: HarnessId, cwd: string): Promise<PrewarmedAcp> {
90
+ const configured = await loadHarnessConfig(harness);
91
+ const launch = resolveLaunch(harness, configured);
92
+ const { token, env } = mintAgentEnvironment();
93
+ const merged = withGatewayCompatibility(harness, { ...(launch.env ?? {}), ...env });
94
+ const process = new AcpProcess({
95
+ command: sessionLaunchCommand(harness, launch.command),
96
+ cwd,
97
+ ...(merged ? { env: merged } : {}),
98
+ // Nobody owns this child yet. The adopting session re-binds these sinks; a
99
+ // frame that arrives in between is an unsolicited status update, which a
100
+ // session learns from `session/new` anyway.
101
+ onNotification: () => {},
102
+ onStderr: () => {},
103
+ });
104
+ // A prewarm is a real process the Stats panel must be able to name: without
105
+ // this lease it is a bare `npx` row inside Kabmo's own group. The claim
106
+ // overwrites the record with the session's id and title, keeping `startedAt`.
107
+ const pid = process.pid;
108
+ if (pid) noteHarnessLease({ pid, harness, cwd, state: 'prewarm' });
109
+ try {
110
+ await process.initialize();
111
+ } catch (error) {
112
+ if (pid) removeHarnessLease(pid);
113
+ throw error;
114
+ }
115
+ if (!process.isAlive) {
116
+ if (pid) removeHarnessLease(pid);
117
+ await process.dispose(1_000).catch(() => {});
118
+ throw new Error(`${harness} exited while warming`);
119
+ }
120
+ return { process, token };
121
+ }
122
+
123
+ const defaultDeps: AcpPrewarmDeps = { open: openProcess };
124
+
125
+ /** Drop an unclaimed entry and dispose its child. */
126
+ async function discard(key: string): Promise<void> {
127
+ const pool = getPrewarmedAcp();
128
+ const entry = pool.get(key);
129
+ if (!entry || entry.claimed) return;
130
+ entry.claimed = true;
131
+ pool.delete(key);
132
+ const warm = await entry.ready;
133
+ if (warm?.process.pid) removeHarnessLease(warm.process.pid);
134
+ await warm?.process.dispose(1_000).catch(() => {});
135
+ }
136
+
137
+ /**
138
+ * Drop the warm agents for `cwd` that belong to OTHER harnesses.
139
+ *
140
+ * One pending chat runs one agent, so the previous candidate is spent: keeping
141
+ * it would cost a process for a choice the operator already left.
142
+ */
143
+ async function discardOtherPrewarms(harness: HarnessId, cwd: string): Promise<void> {
144
+ const doomed = [...getPrewarmedAcp()]
145
+ .filter(([, entry]) => entry.cwd === cwd && entry.harness !== harness && !entry.claimed)
146
+ .map(([key]) => key);
147
+ await Promise.all(doomed.map((key) => discard(key)));
148
+ }
149
+
150
+ /**
151
+ * Spawn (at most one) idle agent for `harness` in `cwd` so the next new-chat
152
+ * send starts instantly. Fire-and-forget; a failed spawn just clears itself.
153
+ * Safe to call repeatedly — an existing live or in-flight entry wins.
154
+ */
155
+ export function prewarmAcpSession(
156
+ harness: HarnessId,
157
+ cwd: string,
158
+ deps: AcpPrewarmDeps = defaultDeps,
159
+ ): void {
160
+ const pool = getPrewarmedAcp();
161
+ const key = acpPrewarmKey(harness, cwd);
162
+ if (pool.has(key)) return;
163
+ // Fire-and-forget on purpose: the old entry's teardown must not delay this
164
+ // agent's boot, and `discard` marks it claimed before awaiting anything.
165
+ void discardOtherPrewarms(harness, cwd);
166
+
167
+ const entry: PrewarmedAcpEntry = {
168
+ harness,
169
+ cwd,
170
+ createdAt: Date.now(),
171
+ claimed: false,
172
+ ready: Promise.resolve(null),
173
+ };
174
+ entry.ready = deps.open(harness, cwd)
175
+ .then(async (warm) => {
176
+ // A child that died while warming must not be handed out.
177
+ if (warm.process.isAlive) return warm;
178
+ await warm.process.dispose(1_000).catch(() => {});
179
+ return null;
180
+ })
181
+ .catch((error: unknown) => {
182
+ console.error(`[harness] prewarm of ${harness} in ${cwd} failed:`, error);
183
+ return null;
184
+ })
185
+ .then((warm) => {
186
+ // A failed spawn leaves no entry: the next prewarm retries instead of
187
+ // finding a permanently empty slot.
188
+ if (!warm && pool.get(key) === entry) pool.delete(key);
189
+ return warm;
190
+ });
191
+ pool.set(key, entry);
192
+
193
+ const timer = setTimeout(() => {
194
+ void discard(key);
195
+ }, ACP_PREWARM_TTL_MS);
196
+ // A warm child must not keep the process alive on its own.
197
+ timer.unref?.();
198
+ }
199
+
200
+ /**
201
+ * Take the prewarmed agent for `harness`+`cwd`, or null when there is none to
202
+ * take. The claim is a synchronous check-and-set: two sends racing the same
203
+ * entry must not both adopt it.
204
+ */
205
+ export async function claimPrewarmedAcpSession(
206
+ harness: HarnessId,
207
+ cwd: string,
208
+ ): Promise<PrewarmedAcp | null> {
209
+ const pool = getPrewarmedAcp();
210
+ const key = acpPrewarmKey(harness, cwd);
211
+ const entry = pool.get(key);
212
+ if (!entry || entry.claimed) return null;
213
+ entry.claimed = true;
214
+ pool.delete(key);
215
+ const warm = await entry.ready;
216
+ if (warm?.process.isAlive) return warm;
217
+ if (warm?.process.pid) removeHarnessLease(warm.process.pid);
218
+ await warm?.process.dispose(1_000).catch(() => {});
219
+ return null;
220
+ }
221
+
222
+ /**
223
+ * Recycle every UNCLAIMED prewarmed agent.
224
+ *
225
+ * A warm child is a full agent process spawned from whatever binary was current
226
+ * when the user opened a pending chat. After an adapter update it is a stale
227
+ * build waiting to be adopted by the next send, so the recycle happens here
228
+ * rather than being left to the TTL. Safe because an unclaimed entry owns no
229
+ * session and no turn.
230
+ */
231
+ export async function restartPrewarmedAcpSessions(): Promise<number> {
232
+ const doomed = [...getPrewarmedAcp().entries()]
233
+ .filter(([, entry]) => !entry.claimed)
234
+ .map(([key]) => key);
235
+ await Promise.all(doomed.map((key) => discard(key)));
236
+ return doomed.length;
237
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The ACP prewarm pool's identity and claim rules.
8
+ *
9
+ * Three properties here are load-bearing and invisible at the call site. The
10
+ * claim is a synchronous check-and-set: two sends racing one warm agent would
11
+ * both adopt it and one would talk to a session the other owns. A failed spawn
12
+ * must leave NO entry, or every later prewarm for that harness+cwd silently does
13
+ * nothing and the user keeps paying the boot. And the pool warms a PROCESS, not
14
+ * a session: `session/new` is what makes some agents write a session record, and
15
+ * a warm child must stay invisible until a chat adopts it.
16
+ *
17
+ * No agent process is ever spawned: the opener is a fake handle. The real opener
18
+ * is exercised by the spawn path itself.
19
+ */
20
+
21
+ import { afterEach, describe, expect, test } from 'bun:test';
22
+ import {
23
+ acpPrewarmKey,
24
+ claimPrewarmedAcpSession,
25
+ getPrewarmedAcp,
26
+ prewarmAcpSession,
27
+ restartPrewarmedAcpSessions,
28
+ type AcpPrewarmDeps,
29
+ type PrewarmedAcp,
30
+ } from '@/server/lib/harness/acp/prewarm.server';
31
+ import type { AcpProcess } from '@/server/lib/harness/acp/client';
32
+
33
+ interface Fake {
34
+ warm: PrewarmedAcp;
35
+ /** Resolves when the fake is disposed, so a test waits on the event rather
36
+ * than on a guessed delay. */
37
+ torn: Promise<void>;
38
+ disposed: boolean;
39
+ }
40
+
41
+ function fakeProcess(alive = true): Fake {
42
+ const torn = Promise.withResolvers<void>();
43
+ const state = { alive };
44
+ // A test double for the transport: only the two members the pool reads.
45
+ const process = {
46
+ get isAlive() {
47
+ return state.alive;
48
+ },
49
+ dispose: async () => {
50
+ state.alive = false;
51
+ fake.disposed = true;
52
+ torn.resolve();
53
+ },
54
+ } as unknown as AcpProcess;
55
+ const fake: Fake = { warm: { process, token: 'kabmo_agent_test' }, torn: torn.promise, disposed: false };
56
+ return fake;
57
+ }
58
+
59
+ /** An opener that records every call and hands out one fake per call. */
60
+ function opener(outcome?: () => Promise<PrewarmedAcp>): { deps: AcpPrewarmDeps; opened: string[]; fakes: Fake[] } {
61
+ const opened: string[] = [];
62
+ const fakes: Fake[] = [];
63
+ return {
64
+ opened,
65
+ fakes,
66
+ deps: {
67
+ open: async (harness, cwd) => {
68
+ opened.push(`${harness}@${cwd}`);
69
+ if (outcome) return outcome();
70
+ const fake = fakeProcess();
71
+ fakes.push(fake);
72
+ return fake.warm;
73
+ },
74
+ },
75
+ };
76
+ }
77
+
78
+ afterEach(() => {
79
+ getPrewarmedAcp().clear();
80
+ });
81
+
82
+ describe('prewarmAcpSession', () => {
83
+ test('spawns once per harness AND cwd', () => {
84
+ const { deps, opened } = opener();
85
+ prewarmAcpSession('claude', '/work', deps);
86
+ prewarmAcpSession('claude', '/work', deps);
87
+ expect(opened).toEqual(['claude@/work']);
88
+ expect(getPrewarmedAcp().has(acpPrewarmKey('claude', '/work'))).toBe(true);
89
+
90
+ // Two agents in one folder are two processes, and so are one agent in two.
91
+ prewarmAcpSession('codex', '/other', deps);
92
+ prewarmAcpSession('claude', '/elsewhere', deps);
93
+ expect(opened).toEqual(['claude@/work', 'codex@/other', 'claude@/elsewhere']);
94
+ });
95
+
96
+ test('a different harness for the same cwd replaces the warm agent', async () => {
97
+ const { deps, opened, fakes } = opener();
98
+ prewarmAcpSession('claude', '/work', deps);
99
+ prewarmAcpSession('codex', '/work', deps);
100
+ // One pending chat runs one agent: keeping the previous candidate would cost
101
+ // a process for a choice the operator already left.
102
+ await fakes[0]!.torn;
103
+ expect(getPrewarmedAcp().has(acpPrewarmKey('claude', '/work'))).toBe(false);
104
+ expect(getPrewarmedAcp().has(acpPrewarmKey('codex', '/work'))).toBe(true);
105
+ expect(opened).toEqual(['claude@/work', 'codex@/work']);
106
+ expect(fakes[0]?.disposed).toBe(true);
107
+ });
108
+
109
+ test('a failed spawn leaves no entry, so the next prewarm retries', async () => {
110
+ let attempt = 0;
111
+ const { deps } = opener(async () => {
112
+ attempt += 1;
113
+ if (attempt === 1) throw new Error('agent exited');
114
+ return fakeProcess().warm;
115
+ });
116
+ prewarmAcpSession('claude', '/work', deps);
117
+ // The failure settles asynchronously; wait for the entry's own promise so
118
+ // the assertion reads the state after the catch, not during it.
119
+ await getPrewarmedAcp().get(acpPrewarmKey('claude', '/work'))?.ready;
120
+ expect(getPrewarmedAcp().has(acpPrewarmKey('claude', '/work'))).toBe(false);
121
+
122
+ prewarmAcpSession('claude', '/work', deps);
123
+ expect(await claimPrewarmedAcpSession('claude', '/work')).not.toBeNull();
124
+ });
125
+ });
126
+
127
+ describe('claimPrewarmedAcpSession', () => {
128
+ test('adopts an entry exactly once', async () => {
129
+ const { deps } = opener();
130
+ prewarmAcpSession('claude', '/work', deps);
131
+ const first = claimPrewarmedAcpSession('claude', '/work');
132
+ // The claim is synchronous: the entry is removed before readiness resolves,
133
+ // so a send racing this one cannot adopt the same child.
134
+ expect(getPrewarmedAcp().has(acpPrewarmKey('claude', '/work'))).toBe(false);
135
+ expect(await first).not.toBeNull();
136
+ expect(await claimPrewarmedAcpSession('claude', '/work')).toBeNull();
137
+ });
138
+
139
+ test('a harness the entry was not warmed for is not handed out', async () => {
140
+ const { deps } = opener();
141
+ prewarmAcpSession('claude', '/work', deps);
142
+ expect(await claimPrewarmedAcpSession('codex', '/work')).toBeNull();
143
+ expect(await claimPrewarmedAcpSession('claude', '/work')).not.toBeNull();
144
+ });
145
+
146
+ test('a child that died while warming is disposed, and the caller spawns cold', async () => {
147
+ const dead = fakeProcess(false);
148
+ const { deps } = opener(async () => dead.warm);
149
+ prewarmAcpSession('claude', '/work', deps);
150
+ // The pool disposes a child that is not alive when its boot settles.
151
+ await dead.torn;
152
+ expect(await claimPrewarmedAcpSession('claude', '/work')).toBeNull();
153
+ expect(dead.disposed).toBe(true);
154
+ });
155
+ });
156
+
157
+ describe('restartPrewarmedAcpSessions', () => {
158
+ test('disposes unclaimed entries and reports the count', async () => {
159
+ const { deps, fakes } = opener();
160
+ prewarmAcpSession('claude', '/a', deps);
161
+ prewarmAcpSession('codex', '/b', deps);
162
+ prewarmAcpSession('claude', '/c', deps);
163
+ await claimPrewarmedAcpSession('claude', '/c');
164
+
165
+ expect(await restartPrewarmedAcpSessions()).toBe(2);
166
+ expect(getPrewarmedAcp().size).toBe(0);
167
+ // The claimed child belongs to a chat now: recycling standby processes must
168
+ // not take it down.
169
+ expect(fakes.filter((fake) => fake.disposed)).toHaveLength(2);
170
+ });
171
+ });