@kabmo-labs/kabmo 0.24.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 (205) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +579 -510
  3. package/dist/client/static/js/index-bc9aa4mx.css +1 -0
  4. package/dist/client/static/js/{index-jcr5twtp.js → index-ga8cbpt4.js} +1072 -1174
  5. package/package.json +2 -4
  6. package/src/cli/lib/args.js +24 -1
  7. package/src/cli/lib/args.test.js +16 -0
  8. package/src/cli/lib/commands/session.js +233 -0
  9. package/src/cli/lib/commands/session.test.js +103 -0
  10. package/src/cli/main.js +1 -1
  11. package/src/client/components/common/ComposerPicker.tsx +3 -0
  12. package/src/client/components/common/code-surface/shiki.test.ts +82 -0
  13. package/src/client/components/common/code-surface/shiki.ts +28 -7
  14. package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +113 -0
  15. package/src/client/components/common/session-actions-menu/index.tsx +33 -2
  16. package/src/client/components/common/session-row/StatusSlot.tsx +4 -4
  17. package/src/client/components/common/session-row/index.tsx +27 -1
  18. package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
  19. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +25 -12
  20. package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +66 -0
  21. package/src/client/components/layout/session-sidebar/SessionItem.tsx +28 -3
  22. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +36 -5
  23. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +94 -0
  24. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
  25. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +120 -0
  26. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +47 -0
  27. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +28 -35
  28. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +18 -5
  29. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +21 -4
  30. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +27 -5
  31. package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
  32. package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
  33. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +135 -118
  34. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
  35. package/src/client/components/workspace/chat-timeline/MessageList.tsx +4 -0
  36. package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
  37. package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
  38. package/src/client/components/workspace/chat-timeline/index.tsx +3 -1
  39. package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
  40. package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
  41. package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
  42. package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
  43. package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
  44. package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
  45. package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
  46. package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
  47. package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
  48. package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
  49. package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
  50. package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
  51. package/src/client/data/settings/omp-schema.json +1 -1
  52. package/src/client/data/theme/terminal.test.ts +25 -0
  53. package/src/client/data/theme/terminal.ts +96 -79
  54. package/src/client/hooks/chat/composer/items.test.ts +12 -26
  55. package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
  56. package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
  57. package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
  58. package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
  59. package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
  60. package/src/client/hooks/chat/timeline/send-execute.test.ts +39 -0
  61. package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
  62. package/src/client/hooks/chat/timeline/send-steer.test.ts +3 -1
  63. package/src/client/hooks/chat/timeline/send.test-util.ts +7 -1
  64. package/src/client/hooks/chat/timeline/send.test.ts +3 -1
  65. package/src/client/hooks/chat/timeline/send.ts +51 -50
  66. package/src/client/hooks/chat/timeline/use-fork-session.ts +49 -0
  67. package/src/client/hooks/models/use-harness-update.test.ts +193 -0
  68. package/src/client/hooks/models/use-harness-update.ts +202 -0
  69. package/src/client/hooks/workspace/child-expansion.ts +33 -0
  70. package/src/client/hooks/workspace/terminal/index.ts +17 -3
  71. package/src/client/hooks/workspace/terminal/socket.ts +9 -4
  72. package/src/client/lib/session-tree.test.ts +50 -0
  73. package/src/client/lib/session-tree.ts +59 -0
  74. package/src/client/tailwind.css +17 -11
  75. package/src/server/index.ts +2 -0
  76. package/src/server/lib/auth/guard.ts +10 -0
  77. package/src/server/lib/btw/session-copy.server.ts +6 -44
  78. package/src/server/lib/btw/session-copy.test.ts +2 -1
  79. package/src/server/lib/db/schema.ts +4 -0
  80. package/src/server/lib/db/seed-terminal.test.ts +1 -1
  81. package/src/server/lib/db/seed.test.ts +1 -1
  82. package/src/server/lib/harness/acp/background-work.test.ts +262 -0
  83. package/src/server/lib/harness/acp/background-work.ts +320 -0
  84. package/src/server/lib/harness/acp/client.ts +2 -2
  85. package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
  86. package/src/server/lib/harness/acp/gateway-env.ts +70 -0
  87. package/src/server/lib/harness/acp/prompt.test.ts +20 -0
  88. package/src/server/lib/harness/acp/prompt.ts +19 -3
  89. package/src/server/lib/harness/acp/session-background.test.ts +129 -0
  90. package/src/server/lib/harness/acp/session-exit.ts +31 -0
  91. package/src/server/lib/harness/acp/session-handshake.test.ts +108 -0
  92. package/src/server/lib/harness/acp/session-handshake.ts +27 -1
  93. package/src/server/lib/harness/acp/session-listeners.ts +31 -0
  94. package/src/server/lib/harness/acp/session-requests.ts +47 -0
  95. package/src/server/lib/harness/acp/session-turns.ts +20 -5
  96. package/src/server/lib/harness/acp/session.test-util.ts +23 -1
  97. package/src/server/lib/harness/acp/session.ts +59 -59
  98. package/src/server/lib/harness/acp/turn.test.ts +81 -0
  99. package/src/server/lib/harness/acp/turn.ts +26 -9
  100. package/src/server/lib/harness/acp/verbs.ts +12 -2
  101. package/src/server/lib/harness/launch.ts +3 -1
  102. package/src/server/lib/harness/spawn.server.ts +15 -2
  103. package/src/server/lib/harness/update-job-store.test.ts +126 -0
  104. package/src/server/lib/harness/update-job-store.ts +109 -0
  105. package/src/server/lib/harness/update-job.server.ts +203 -0
  106. package/src/server/lib/harness/update-worker.test.ts +153 -0
  107. package/src/server/lib/harness/update-worker.ts +197 -0
  108. package/src/server/lib/lifecycle/paths.ts +23 -0
  109. package/src/server/lib/omp/rpc/manager.ts +5 -5
  110. package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
  111. package/src/server/lib/omp/rpc/session-registry.ts +14 -2
  112. package/src/server/lib/omp/rpc/terminal-settle.ts +53 -5
  113. package/src/server/lib/omp/session/delete-flow.server.ts +47 -0
  114. package/src/server/lib/omp/session/delete.server.ts +5 -0
  115. package/src/server/lib/omp/session/rewind-file.ts +39 -21
  116. package/src/server/lib/omp/session/sidebar-data.server.ts +6 -6
  117. package/src/server/lib/omp/session/transcript-copy.ts +123 -0
  118. package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
  119. package/src/server/lib/sessions/agent-token.server.ts +134 -0
  120. package/src/server/lib/sessions/answers.server.test.ts +33 -0
  121. package/src/server/lib/sessions/answers.server.ts +37 -0
  122. package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
  123. package/src/server/lib/sessions/dispatch.server.ts +128 -0
  124. package/src/server/lib/sessions/fork.server.test.ts +209 -0
  125. package/src/server/lib/sessions/fork.server.ts +304 -0
  126. package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
  127. package/src/server/lib/sessions/lifecycle.server.ts +71 -0
  128. package/src/server/lib/sessions/notify.server.test.ts +112 -0
  129. package/src/server/lib/sessions/notify.server.ts +212 -0
  130. package/src/server/lib/sessions/relation-types.ts +76 -0
  131. package/src/server/lib/sessions/relations.server.test.ts +207 -0
  132. package/src/server/lib/sessions/relations.server.ts +337 -0
  133. package/src/server/lib/sessions/resolve.server.ts +106 -0
  134. package/src/server/lib/sessions/schema.server.ts +82 -0
  135. package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
  136. package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
  137. package/src/server/lib/sessions/spawn.server.test.ts +196 -0
  138. package/src/server/lib/sessions/spawn.server.ts +310 -0
  139. package/src/server/lib/terminal/attach-replay.test.ts +2 -2
  140. package/src/server/lib/terminal/output.test.ts +2 -2
  141. package/src/server/lib/terminal/output.ts +1 -1
  142. package/src/server/lib/terminal/resize.test.ts +99 -0
  143. package/src/server/lib/terminal/runtime.server.ts +26 -6
  144. package/src/server/lib/terminal/send-result.test.ts +18 -1
  145. package/src/server/lib/terminal/send-result.ts +26 -2
  146. package/src/server/lib/terminal/session.server.ts +6 -6
  147. package/src/server/lib/usage/new-api.test.ts +92 -0
  148. package/src/server/lib/usage/new-api.ts +131 -0
  149. package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
  150. package/src/server/lib/usage/provider-key.ts +33 -0
  151. package/src/server/lib/usage/providers.server.ts +10 -3
  152. package/src/server/lib/usage/vendor-balance.server.ts +4 -53
  153. package/src/server/lib/usage/vendor-http.ts +41 -0
  154. package/src/server/lib/usage/window.ts +55 -0
  155. package/src/server/routes/agent/command.ts +14 -1
  156. package/src/server/routes/agent/harness-command.ts +6 -0
  157. package/src/server/routes/agent/new.ts +15 -0
  158. package/src/server/routes/harness/add-provider.test.ts +9 -1
  159. package/src/server/routes/harness/import-action.ts +4 -0
  160. package/src/server/routes/harness/import.test.ts +1 -1
  161. package/src/server/routes/harness/index.ts +5 -1
  162. package/src/server/routes/harness/update-status.ts +26 -0
  163. package/src/server/routes/harness/update.test.ts +119 -0
  164. package/src/server/routes/harness/update.ts +59 -147
  165. package/src/server/routes/sessions/answer.ts +24 -0
  166. package/src/server/routes/sessions/batch-delete.ts +11 -5
  167. package/src/server/routes/sessions/delete.ts +4 -2
  168. package/src/server/routes/sessions/fork.ts +74 -0
  169. package/src/server/routes/sessions/index.ts +14 -0
  170. package/src/server/routes/sessions/relations.ts +85 -0
  171. package/src/server/routes/sessions/session.ts +4 -0
  172. package/src/server/routes/sessions/spawn.ts +134 -0
  173. package/src/server/routes/terminal/ws.ts +3 -3
  174. package/src/shared/lib/chat/composer/client.ts +31 -2
  175. package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
  176. package/src/shared/lib/chat/composer/delegation.ts +206 -0
  177. package/src/shared/lib/chat/notice-text.ts +1 -1
  178. package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
  179. package/src/shared/lib/code/ansi.ts +1 -1
  180. package/src/shared/lib/fonts/nerd-symbols.css +4 -3
  181. package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
  182. package/src/shared/lib/harness/provider-facts.test.ts +27 -0
  183. package/src/shared/lib/harness/providers.ts +35 -1
  184. package/src/shared/lib/harness/update-job.ts +33 -0
  185. package/src/shared/lib/harness/update-plan.test.ts +21 -6
  186. package/src/shared/lib/harness/update-plan.ts +12 -4
  187. package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
  188. package/src/shared/lib/omp/session/wait-idle.ts +12 -2
  189. package/src/shared/lib/theme/catalog.test.ts +13 -9
  190. package/src/shared/lib/theme/color.test.ts +2 -2
  191. package/src/shared/lib/theme/color.ts +4 -4
  192. package/src/shared/lib/theme/theme.test.ts +1 -1
  193. package/src/shared/lib/workspace/terminal/input.test.ts +27 -0
  194. package/src/shared/lib/workspace/terminal/input.ts +33 -0
  195. package/src/shared/lib/workspace/terminal/keys.test.ts +1 -1
  196. package/src/shared/lib/workspace/terminal/keys.ts +7 -7
  197. package/src/shared/types/chat.ts +1 -1
  198. package/src/shared/types/harness-update.ts +65 -0
  199. package/src/shared/types/omp/agent.ts +19 -2
  200. package/src/shared/types/workspace.ts +4 -0
  201. package/src/test-support/fake-omp-fork.ts +16 -2
  202. package/src/test-support/harness-table.test-util.ts +15 -1
  203. package/dist/client/static/js/index-z3w7n85q.css +0 -1
  204. package/src/client/components/workspace/terminal-panel/webgl.test.ts +0 -75
  205. package/src/client/components/workspace/terminal-panel/webgl.ts +0 -108
@@ -0,0 +1,81 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { AcpTurns, type AcpTurnSeams } from '@/server/lib/harness/acp/turn';
3
+
4
+ type TurnEnd = Parameters<AcpTurnSeams['onTurnEnd']>[0];
5
+
6
+ function harness(overrides: Partial<AcpTurnSeams> = {}): {
7
+ turns: AcpTurns;
8
+ events: { type: string; errorMessage?: string }[];
9
+ ended: Promise<TurnEnd>;
10
+ } {
11
+ const events: { type: string; errorMessage?: string }[] = [];
12
+ const { promise: ended, resolve: resolveEnd } = Promise.withResolvers<TurnEnd>();
13
+ const turns = new AcpTurns({
14
+ emit: (event) => events.push(event as { type: string; errorMessage?: string }),
15
+ prompt: async () => ({}),
16
+ cancelAgent: () => {},
17
+ abandonPrompt: () => {},
18
+ resetMapper: () => {},
19
+ closeMessage: () => [],
20
+ openCalls: () => [],
21
+ onTurnEnd: (info) => resolveEnd(info),
22
+ ...overrides,
23
+ });
24
+ return { turns, events, ended };
25
+ }
26
+
27
+ describe('AcpTurns failure classification', () => {
28
+ test('a turn that ends without an answer is failed, not completed', async () => {
29
+ const { turns, events, ended } = harness();
30
+ turns.start('do the work', undefined);
31
+
32
+ const info = await ended;
33
+ expect(info.failed).toBe(true);
34
+ expect(info.failure).toContain('without sending an answer');
35
+ expect(events.some((event) => event.type === 'prompt_error')).toBe(true);
36
+ });
37
+
38
+ test('a rejected prompt keeps the agent error and is failed', async () => {
39
+ const { turns, events, ended } = harness({
40
+ prompt: async () => {
41
+ throw new Error('provider exploded');
42
+ },
43
+ });
44
+ turns.start('do the work', undefined);
45
+
46
+ const info = await ended;
47
+ expect(info.failed).toBe(true);
48
+ expect(info.failure).toBe('provider exploded');
49
+ expect(events.filter((event) => event.type === 'prompt_error')).toHaveLength(1);
50
+ });
51
+
52
+ test('an answered turn is not failed', async () => {
53
+ const { turns, ended } = harness({
54
+ closeMessage: () => [
55
+ {
56
+ type: 'message_end',
57
+ message: { role: 'assistant', content: [{ type: 'text', text: 'done' }] },
58
+ },
59
+ ] as never,
60
+ });
61
+ turns.start('do the work', undefined);
62
+
63
+ const info = await ended;
64
+ expect(info.failed).toBeUndefined();
65
+ expect(info.closedMessage).toBe(true);
66
+ });
67
+
68
+ test('a cancelled turn is interrupted, never failed', async () => {
69
+ const { turns, ended } = harness({ prompt: () => new Promise(() => {}) });
70
+ turns.start('do the work', undefined);
71
+ // The turn opens on the prompt chain's own microtask; cancel before that is
72
+ // the "nothing to cancel" path and would not emit a turn end.
73
+ await Promise.resolve();
74
+ await Promise.resolve();
75
+ turns.cancel();
76
+
77
+ const info = await ended;
78
+ expect(info.cancelled).toBe(true);
79
+ expect(info.failed).toBeUndefined();
80
+ });
81
+ });
@@ -21,6 +21,16 @@
21
21
  import type { AgentEvent } from '@/server/lib/omp/rpc/constants';
22
22
  import { turnEndFrame } from '@/server/lib/harness/acp/frames';
23
23
 
24
+ /** What a closed turn reports to its session and the parent notice. */
25
+ export interface AcpTurnEndInfo {
26
+ stopReason?: string;
27
+ closedMessage: boolean;
28
+ message?: unknown;
29
+ cancelled?: boolean;
30
+ failed?: boolean;
31
+ failure?: string | null;
32
+ }
33
+
24
34
  export interface AcpTurnSeams {
25
35
  /** Push one frame at the session's listeners. */
26
36
  emit: (event: AgentEvent) => void;
@@ -41,7 +51,7 @@ export interface AcpTurnSeams {
41
51
  * reason, the assistant message the mapper closed (the goal driver audits it),
42
52
  * and whether the turn was cancelled (a stop must not be audited).
43
53
  */
44
- onTurnEnd: (info: { stopReason?: string; closedMessage: boolean; message?: unknown; cancelled?: boolean }) => void;
54
+ onTurnEnd: (info: AcpTurnEndInfo) => void;
45
55
  }
46
56
 
47
57
  export class AcpTurns {
@@ -86,14 +96,12 @@ export class AcpTurns {
86
96
  (result) => this.settle(turnId, () => this.finish(result)),
87
97
  (error: unknown) =>
88
98
  this.settle(turnId, () => {
89
- this.seams.emit({
90
- type: 'prompt_error',
91
- errorMessage: error instanceof Error ? error.message : String(error),
92
- });
99
+ const message = error instanceof Error ? error.message : String(error);
100
+ this.seams.emit({ type: 'prompt_error', errorMessage: message });
93
101
  // The agent's own error is the reason. `finish` must not append its
94
102
  // generic "no answer" verdict on top of it — the second frame lands
95
103
  // last on the client and replaced the useful message.
96
- this.finish(undefined, true);
104
+ this.finish(undefined, true, message);
97
105
  }),
98
106
  )
99
107
  .finally(() => {
@@ -145,7 +153,7 @@ export class AcpTurns {
145
153
  * going to report an end for work it abandoned. `reported` says the caller
146
154
  * already emitted the failure reason, so only this module's generic silent
147
155
  * verdict is suppressed. */
148
- private finish(result: { stopReason?: string } | undefined, reported = false): void {
156
+ private finish(result: { stopReason?: string } | undefined, reported = false, failure?: string): void {
149
157
  const flushed = this.seams.closeMessage();
150
158
  for (const event of flushed) this.seams.emit(event);
151
159
  const closed = flushed.find((event) => event.type === 'message_end')?.message;
@@ -163,10 +171,18 @@ export class AcpTurns {
163
171
  // produces nothing, and a user's Stop is not a failure either.
164
172
  const answered = hasRenderableAnswer(closed) || abandoned.length > 0;
165
173
  const cancelled = result?.stopReason === 'cancelled';
166
- if (!answered && !cancelled && !reported && !this.promptText.trimStart().startsWith('/')) {
174
+ const slash = this.promptText.trimStart().startsWith('/');
175
+ // `reported` means the caller already emitted the agent's own error. It is
176
+ // still a failed turn, and the parent notice must say so rather than let a
177
+ // refused worker read as completed.
178
+ const failed = !cancelled && !slash && (reported || !answered);
179
+ const reason = failed
180
+ ? failure ?? 'The agent ended the turn without sending an answer'
181
+ : null;
182
+ if (!answered && !cancelled && !reported && !slash) {
167
183
  this.seams.emit({
168
184
  type: 'prompt_error',
169
- errorMessage: 'The agent ended the turn without sending an answer',
185
+ errorMessage: reason ?? 'The agent ended the turn without sending an answer',
170
186
  });
171
187
  }
172
188
  this.isPromptRunning = false;
@@ -177,6 +193,7 @@ export class AcpTurns {
177
193
  closedMessage: flushed.some((event) => event.type === 'message_end'),
178
194
  ...(closed ? { message: closed } : {}),
179
195
  ...(cancelled ? { cancelled: true } : {}),
196
+ ...(failed ? { failed: true, failure: reason } : {}),
180
197
  });
181
198
  }
182
199
  }
@@ -36,8 +36,18 @@ export async function resumeSession(invoke: AcpInvoke, sessionId: string, cwd: s
36
36
  return invoke('session/resume', { sessionId, cwd, mcpServers: [] }, timeoutMs);
37
37
  }
38
38
 
39
- export async function forkSession(invoke: AcpInvoke, sessionId: string, cwd: string, timeoutMs = 120_000): Promise<AcpSessionNewResult> {
40
- return invoke<AcpSessionNewResult>('session/fork', { sessionId, cwd, mcpServers: [] }, timeoutMs);
39
+ export async function forkSession(
40
+ invoke: AcpInvoke,
41
+ sessionId: string,
42
+ cwd: string,
43
+ timeoutMs = 120_000,
44
+ target?: Record<string, unknown>,
45
+ ): Promise<AcpSessionNewResult> {
46
+ return invoke<AcpSessionNewResult>(
47
+ 'session/fork',
48
+ { sessionId, cwd, mcpServers: [], ...(target ? { target } : {}) },
49
+ timeoutMs,
50
+ );
41
51
  }
42
52
 
43
53
  export async function listSessions(invoke: AcpInvoke, cwd?: string, timeoutMs = 60_000): Promise<AcpSessionInfo[]> {
@@ -22,6 +22,7 @@
22
22
  */
23
23
 
24
24
  import { AcpProcess } from '@/server/lib/harness/acp/client';
25
+ import { withGatewayCompatibility } from '@/server/lib/harness/acp/gateway-env';
25
26
  import { newSessionAfterActivation } from '@/server/lib/harness/acp/activation';
26
27
  import type { AcpConfigOption, AcpInitializeResult } from '@/server/lib/harness/acp/protocol';
27
28
  import { acpOptionValues } from '@/server/lib/harness/acp/protocol';
@@ -141,12 +142,13 @@ export async function probeHarness(
141
142
  let proc: AcpProcess | null = null;
142
143
  /** `agentInfo` from a handshake that succeeded before a later step failed. */
143
144
  let agent: AcpInitializeResult['agentInfo'] | undefined;
145
+ const env = withGatewayCompatibility(id, launch.env);
144
146
 
145
147
  try {
146
148
  const agentProcess = new AcpProcess({
147
149
  command: launch.command,
148
150
  cwd,
149
- ...(launch.env ? { env: launch.env } : {}),
151
+ ...(env ? { env } : {}),
150
152
  onStderr: (line) => {
151
153
  stderrTail = `${stderrTail}${line}\n`.slice(-2_000);
152
154
  },
@@ -37,6 +37,9 @@ export interface AcpSpawnRequest {
37
37
  /** On-disk transcript to resume; '' for a new chat. For ACP that is the
38
38
  * agent's own session id, not a path — Kabmo stores it in `harness_sessions`. */
39
39
  resumeAgentSessionId?: string;
40
+ /** Fork this agent session instead of starting a new one. Mutually exclusive
41
+ * with `resumeAgentSessionId`; the returned id is the child's own. */
42
+ forkAgentSessionId?: string;
40
43
  cwd: string;
41
44
  model?: SelectedModel | null;
42
45
  thinkingLevel?: string | null;
@@ -44,6 +47,8 @@ export interface AcpSpawnRequest {
44
47
  /** The composer's access pick, applied to the ACP session's own approval
45
48
  * gate (this transport has no `--approval-mode` spawn flag). */
46
49
  accessMode?: ApprovalMode | null;
50
+ /** Extra environment for this child only (the agent token and server URL). */
51
+ env?: Record<string, string>;
47
52
  }
48
53
 
49
54
  export class HarnessNotLaunchableError extends Error {
@@ -82,11 +87,12 @@ export async function startAcpSession(
82
87
  // Built here rather than behind a factory in the session module: this is the
83
88
  // only place a session is constructed, and the handshake it runs (load vs
84
89
  // new) is decided by the request this function already holds.
90
+ const childEnv = { ...(launch.env ?? {}), ...(request.env ?? {}) };
85
91
  const session = new AcpSession(
86
92
  {
87
93
  harness: request.harness,
88
94
  command: sessionLaunchCommand(request.harness, launch.command),
89
- ...(launch.env ? { env: launch.env } : {}),
95
+ ...(Object.keys(childEnv).length > 0 ? { env: childEnv } : {}),
90
96
  model: startingModel,
91
97
  thinkingLevel: request.thinkingLevel ?? configured.thinking ?? null,
92
98
  mode: request.mode ?? configured.mode ?? null,
@@ -96,7 +102,10 @@ export async function startAcpSession(
96
102
  );
97
103
  let realSessionId: string;
98
104
  try {
99
- ({ sessionId: realSessionId } = await session.start(request.resumeAgentSessionId || undefined));
105
+ ({ sessionId: realSessionId } = await session.start(
106
+ request.resumeAgentSessionId || undefined,
107
+ request.forkAgentSessionId,
108
+ ));
100
109
  } catch (error) {
101
110
  // A refused handshake (an agent that will not `session/load`, a launch line
102
111
  // that cannot run) must not leave the child it just spawned running with
@@ -105,6 +114,10 @@ export async function startAcpSession(
105
114
  await session.destroyAndWait().catch(() => {});
106
115
  throw error;
107
116
  }
117
+ if (!realSessionId) {
118
+ await session.destroyAndWait().catch(() => {});
119
+ throw new Error(`${request.harness} started a session without an id`);
120
+ }
108
121
 
109
122
  claimHarness(session, request.harness);
110
123
  registerAcpSession(session, request.sessionId);
@@ -0,0 +1,126 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The record a background harness update leaves on disk.
8
+ *
9
+ * The two questions these cases pin are the ones the dialog cannot answer for
10
+ * itself: is this run still going, and is a record that stopped moving a failure
11
+ * rather than something to poll forever.
12
+ */
13
+
14
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
15
+ import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
16
+ import { tmpdir } from 'node:os';
17
+ import { join } from 'node:path';
18
+ import {
19
+ jobInFlight,
20
+ pidAlive,
21
+ readUpdateJob,
22
+ settleDeadJob,
23
+ writeUpdateJob,
24
+ UPDATE_START_GRACE_MS,
25
+ } from '@/server/lib/harness/update-job-store';
26
+ import { getHarnessUpdateStatusPath } from '@/server/lib/lifecycle/paths';
27
+ import type { HarnessUpdateJob } from '@/shared/types/harness-update';
28
+
29
+ let dir = '';
30
+ let originalDataDir: string | undefined;
31
+
32
+ beforeEach(() => {
33
+ originalDataDir = Bun.env.KABMO_DATA_DIR;
34
+ dir = mkdtempSync(join(tmpdir(), 'kabmo-update-job-'));
35
+ Bun.env.KABMO_DATA_DIR = dir;
36
+ });
37
+
38
+ afterEach(() => {
39
+ if (originalDataDir === undefined) delete Bun.env.KABMO_DATA_DIR;
40
+ else Bun.env.KABMO_DATA_DIR = originalDataDir;
41
+ rmSync(dir, { recursive: true, force: true });
42
+ });
43
+
44
+ function job(overrides: Partial<HarnessUpdateJob> = {}): HarnessUpdateJob {
45
+ return {
46
+ harness: 'claude',
47
+ label: 'claude',
48
+ startedAt: Date.now(),
49
+ finishedAt: null,
50
+ pid: process.pid,
51
+ steps: [{ part: 'adapter', command: 'npm install -g x', argv: ['npm', 'install', '-g', 'x'], state: 'running', code: null }],
52
+ output: '',
53
+ ok: null,
54
+ message: null,
55
+ applied: false,
56
+ repointed: null,
57
+ ...overrides,
58
+ };
59
+ }
60
+
61
+ describe('the status record', () => {
62
+ test('round-trips, and leaves no temp file behind', async () => {
63
+ await writeUpdateJob(job({ output: 'installing' }));
64
+ const read = await readUpdateJob();
65
+ expect(read?.harness).toBe('claude');
66
+ expect(read?.output).toBe('installing');
67
+ // `tmp` + `rename`, so a reader never sees half a record and the temp name
68
+ // does not pile up.
69
+ const leftovers = readdirSync(join(dir, 'run')).filter((name) => name.endsWith('.tmp'));
70
+ expect(leftovers).toEqual([]);
71
+ });
72
+
73
+ test('an absent record is null, not a throw', async () => {
74
+ expect(await readUpdateJob()).toBeNull();
75
+ });
76
+
77
+ test('a foreign JSON file is not a job', async () => {
78
+ // A hand-written or half-written file must read as "nothing ran", not as a
79
+ // record whose missing fields crash the dialog.
80
+ writeFileSync(getHarnessUpdateStatusPath(), JSON.stringify({ hello: 'world' }));
81
+ expect(await readUpdateJob()).toBeNull();
82
+ });
83
+ });
84
+
85
+ describe('telling a live run from a dead one', () => {
86
+ test('a run with a live pid is in flight', () => {
87
+ expect(jobInFlight(job())).toBe(true);
88
+ });
89
+
90
+ test('a finished run is not in flight', () => {
91
+ expect(jobInFlight(job({ finishedAt: Date.now(), ok: true }))).toBe(false);
92
+ });
93
+
94
+ test('a run whose worker is gone is settled by the next read', async () => {
95
+ const dead = job({ pid: 99_999_999, startedAt: Date.now() - UPDATE_START_GRACE_MS * 2 });
96
+ await writeUpdateJob(dead);
97
+ const settled = await settleDeadJob(await readUpdateJob());
98
+ expect(settled?.finishedAt).not.toBeNull();
99
+ expect(settled?.ok).toBe(false);
100
+ expect(settled?.message).toContain('without reporting a result');
101
+ expect(settled?.steps[0].state).toBe('failed');
102
+ // Settled once, and the settle itself is on disk for the next reader.
103
+ expect((await readUpdateJob())?.finishedAt).not.toBeNull();
104
+ });
105
+
106
+ test('the start grace covers the pid handshake', async () => {
107
+ // The record is written before the worker has a pid; reading that as dead
108
+ // would report failure over a run that is about to start.
109
+ const starting = job({ pid: null, startedAt: Date.now() });
110
+ await writeUpdateJob(starting);
111
+ expect(await settleDeadJob(await readUpdateJob())).toEqual(starting);
112
+ expect(jobInFlight(starting)).toBe(true);
113
+ });
114
+
115
+ test('a finished run is left exactly as the worker wrote it', async () => {
116
+ const done = job({ pid: null, finishedAt: Date.now(), ok: true, message: 'claude updated (adapter)' });
117
+ await writeUpdateJob(done);
118
+ expect(await settleDeadJob(await readUpdateJob())).toEqual(done);
119
+ });
120
+
121
+ test('an impossible pid is not alive', () => {
122
+ expect(pidAlive(null)).toBe(false);
123
+ expect(pidAlive(0)).toBe(false);
124
+ expect(pidAlive(process.pid)).toBe(true);
125
+ });
126
+ });
@@ -0,0 +1,109 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The harness update record on disk: read it, write it atomically, and tell a
8
+ * live run from a dead one.
9
+ *
10
+ * Kept apart from `update-job.server.ts` because the DETACHED WORKER writes the
11
+ * same record (`update-worker.ts`) and must not import the server's database and
12
+ * config modules to do it. One writer, one file shape, two processes.
13
+ *
14
+ * **A run outlives the request that started it.** The POST answers in
15
+ * milliseconds while the install keeps going, so the state cannot live in a
16
+ * closure or a `Map`: a reloaded page, a second tab and a `bun --hot` reload all
17
+ * have to read the same answer. It is one JSON file, replaced atomically
18
+ * (`tmp` + `rename`), which is why a reader never sees half a record.
19
+ */
20
+
21
+ import fs from 'node:fs';
22
+ import { getHarnessUpdateStatusPath } from '@/server/lib/lifecycle/paths';
23
+ import { isHarnessUpdateJob } from '@/shared/lib/harness/update-job';
24
+ import type { HarnessUpdateJob } from '@/shared/types/harness-update';
25
+
26
+ /**
27
+ * How long a just-started job is trusted without a live pid.
28
+ *
29
+ * The server writes the record, then spawns the worker; for those first moments
30
+ * there is a `finishedAt: null` record and no worker pid yet. Reading that as "it
31
+ * died" would report a failure over a run that is about to start. Fifteen
32
+ * seconds is far longer than that handshake and far shorter than a human's
33
+ * patience for a stale row.
34
+ */
35
+ export const UPDATE_START_GRACE_MS = 15_000;
36
+
37
+ /** The current record, or null when none was ever written (or it is unreadable).
38
+ * `path` is the record the caller owns: the server uses the install's run
39
+ * directory, the detached worker uses the one its spec names. */
40
+ export async function readUpdateJob(path = getHarnessUpdateStatusPath()): Promise<HarnessUpdateJob | null> {
41
+ try {
42
+ const parsed = (await Bun.file(path).json()) as unknown;
43
+ return isHarnessUpdateJob(parsed) ? parsed : null;
44
+ } catch {
45
+ // Absent (never run) and corrupt (a half-written record from an old build)
46
+ // are the same answer: there is nothing to report.
47
+ return null;
48
+ }
49
+ }
50
+
51
+ /** Replace the record atomically. A reader sees the previous one or this one. */
52
+ export async function writeUpdateJob(job: HarnessUpdateJob, path = getHarnessUpdateStatusPath()): Promise<void> {
53
+ const target = path;
54
+ const temp = `${target}.${process.pid}.tmp`;
55
+ await Bun.write(temp, JSON.stringify(job, null, 2));
56
+ await fs.promises.rename(temp, target);
57
+ }
58
+
59
+ /** Is this pid a live process? `EPERM` means it exists and is not ours. */
60
+ export function pidAlive(pid: number | null): boolean {
61
+ if (!pid || !Number.isInteger(pid) || pid <= 0) return false;
62
+ try {
63
+ process.kill(pid, 0);
64
+ return true;
65
+ } catch (cause) {
66
+ return (cause as NodeJS.ErrnoException).code === 'EPERM';
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Is this run still going?
72
+ *
73
+ * A known-live pid settles it. Without one the record is trusted only inside the
74
+ * start grace window; after that an absent worker means the run died without
75
+ * writing a result, and the caller reports that instead of polling forever.
76
+ */
77
+ export function jobInFlight(job: HarnessUpdateJob | null, now = Date.now()): boolean {
78
+ if (!job || job.finishedAt !== null) return false;
79
+ if (pidAlive(job.pid)) return true;
80
+ return now - job.startedAt < UPDATE_START_GRACE_MS;
81
+ }
82
+
83
+ /**
84
+ * The record with a run that died without reporting turned into a failure.
85
+ *
86
+ * `finishedAt` is what every reader keys on, so settling here is what stops the
87
+ * dialog from spinning forever; the message says the install itself may have
88
+ * completed, because a killed reporter is not proof the commands failed.
89
+ */
90
+ export async function settleDeadJob(
91
+ job: HarnessUpdateJob | null,
92
+ path = getHarnessUpdateStatusPath(),
93
+ ): Promise<HarnessUpdateJob | null> {
94
+ // A record that already has a result is history, not a candidate: the worker
95
+ // wrote it, and rewriting it would turn a success into a "stopped without
96
+ // reporting" failure.
97
+ if (!job || job.finishedAt !== null || jobInFlight(job)) return job;
98
+ const settled: HarnessUpdateJob = {
99
+ ...job,
100
+ finishedAt: Date.now(),
101
+ pid: null,
102
+ ok: false,
103
+ applied: true,
104
+ message: `${job.label} update stopped without reporting a result — check its status before trying again`,
105
+ steps: job.steps.map((step) => (step.state === 'running' ? { ...step, state: 'failed' } : step)),
106
+ };
107
+ await writeUpdateJob(settled, path);
108
+ return settled;
109
+ }