@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,31 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * What a session emits when its agent process exits without Kabmo asking.
8
+ *
9
+ * The exit is a failure the operator must see, but only when the session was
10
+ * still wanted; a process Kabmo is tearing down reports through the destroy
11
+ * hook instead of a `prompt_error` for a stop the user asked for.
12
+ */
13
+
14
+ import type { AgentEvent } from '@/server/lib/omp/rpc/constants';
15
+ import type { HarnessId } from '@/shared/lib/harness/catalog';
16
+
17
+ export interface AcpExitInfo {
18
+ code: number | null;
19
+ stderrTail: string;
20
+ }
21
+
22
+ export function acpExitFailureFrames(harness: HarnessId, info: AcpExitInfo): AgentEvent[] {
23
+ const detail = info.stderrTail.trim().split('\n').slice(-3).join(' · ');
24
+ return [
25
+ {
26
+ type: 'prompt_error',
27
+ errorMessage: detail || `The ${harness} agent exited (code ${info.code ?? 'signal'})`,
28
+ },
29
+ { type: 'agent_end', isTerminal: true },
30
+ ];
31
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The three handshake shapes: new, load, fork.
8
+ *
9
+ * The fork branch is the one that must never fall back: a harness that cannot
10
+ * fork has to refuse, not open an empty session under the fork's name.
11
+ */
12
+
13
+ import { describe, expect, test } from 'bun:test';
14
+ import { handshakeAcpSession, type AcpHandshakeTarget } from '@/server/lib/harness/acp/session-handshake';
15
+ import type { AcpConfigOption } from '@/server/lib/harness/acp/protocol';
16
+
17
+ function target(): AcpHandshakeTarget {
18
+ return {
19
+ cwd: '/tmp/project',
20
+ harness: 'claude',
21
+ sessionId: '',
22
+ configOptions: [] as AcpConfigOption[],
23
+ runModel: null,
24
+ capabilities: {
25
+ configModel: 0,
26
+ configThinking: 0,
27
+ configMode: 0,
28
+ modeValues: [],
29
+ loadSession: false,
30
+ listSessions: false,
31
+ forkSession: false,
32
+ deleteSession: false,
33
+ resumeSession: false,
34
+ closeSession: false,
35
+ hasUsage: false,
36
+ hasPlan: false,
37
+ steerMode: null,
38
+ },
39
+ async setConfig() {
40
+ return {};
41
+ },
42
+ };
43
+ }
44
+
45
+ function processDouble(overrides: Record<string, unknown> = {}) {
46
+ const calls: string[] = [];
47
+ return {
48
+ calls,
49
+ async initialize() {
50
+ return { protocolVersion: 1, agentCapabilities: {} };
51
+ },
52
+ async loadSession() {
53
+ calls.push('load');
54
+ },
55
+ async newSession() {
56
+ calls.push('new');
57
+ return { sessionId: 'new-id' };
58
+ },
59
+ ...overrides,
60
+ };
61
+ }
62
+
63
+ describe('handshakeAcpSession', () => {
64
+ test('new starts a new agent session', async () => {
65
+ const proc = processDouble();
66
+ await handshakeAcpSession(target(), proc, { model: null, thinking: null, mode: null });
67
+ expect(proc.calls).toEqual(['new']);
68
+ });
69
+
70
+ test('load restores and then starts the replacement session', async () => {
71
+ const proc = processDouble();
72
+ await handshakeAcpSession(target(), proc, { model: null, thinking: null, mode: null }, 'agent-1');
73
+ expect(proc.calls).toEqual(['load', 'new']);
74
+ });
75
+
76
+ test('fork asks the agent for session/fork and uses the returned id', async () => {
77
+ const proc = processDouble({
78
+ async forkSession(sessionId: string) {
79
+ proc.calls.push(`fork:${sessionId}`);
80
+ return { sessionId: 'forked-id' };
81
+ },
82
+ });
83
+ const session = target();
84
+ await handshakeAcpSession(
85
+ session,
86
+ proc,
87
+ { model: null, thinking: null, mode: null },
88
+ undefined,
89
+ 'agent-1',
90
+ );
91
+ expect(proc.calls).toEqual(['fork:agent-1']);
92
+ expect(session.sessionId).toBe('forked-id');
93
+ });
94
+
95
+ test('a process with no fork verb refuses instead of creating an empty session', async () => {
96
+ const proc = processDouble();
97
+ await expect(
98
+ handshakeAcpSession(
99
+ target(),
100
+ proc,
101
+ { model: null, thinking: null, mode: null },
102
+ undefined,
103
+ 'agent-1',
104
+ ),
105
+ ).rejects.toThrow('cannot fork');
106
+ expect(proc.calls).toEqual([]);
107
+ });
108
+ });
@@ -40,6 +40,13 @@ export interface AcpHandshakeProcess {
40
40
  initialize(params: Record<string, unknown>, timeoutMs?: number): Promise<AcpInitializeResult>;
41
41
  loadSession(sessionId: string, cwd: string, timeoutMs?: number): Promise<unknown>;
42
42
  newSession(cwd: string, timeoutMs?: number): Promise<AcpSessionNewResult>;
43
+ /** `session/fork`; absent on a process double used by older tests. */
44
+ forkSession?(
45
+ sessionId: string,
46
+ cwd: string,
47
+ timeoutMs?: number,
48
+ target?: Record<string, unknown>,
49
+ ): Promise<AcpSessionNewResult>;
43
50
  }
44
51
 
45
52
  /** The session fields a handshake seeds. */
@@ -65,6 +72,7 @@ export async function handshakeAcpSession(
65
72
  proc: AcpHandshakeProcess,
66
73
  wanted: AcpHandshakeSelections,
67
74
  sessionIdToLoad?: string,
75
+ forkFromSessionId?: string,
68
76
  ): Promise<void> {
69
77
  const init = await proc.initialize({}, 60_000);
70
78
  /** opencode's plugin activation gate: the first `session/new`s refuse with
@@ -74,7 +82,25 @@ export async function handshakeAcpSession(
74
82
  ...(timeoutMs !== undefined ? { perAttemptMs: timeoutMs } : {}),
75
83
  });
76
84
  let session: AcpSessionNewResult;
77
- if (sessionIdToLoad) {
85
+ if (forkFromSessionId) {
86
+ // A fork is a NEW agent session that inherits the source's context; the
87
+ // returned id is the child's own. Refusing here is deliberate: silently
88
+ // falling back to `session/new` would start an empty chat under a fork's
89
+ // name, which is the substitution this feature exists to prevent.
90
+ if (!proc.forkSession) {
91
+ throw new Error(`${target.harness} cannot fork a session`);
92
+ }
93
+ session = await proc.forkSession(
94
+ forkFromSessionId,
95
+ target.cwd,
96
+ 120_000,
97
+ // zcode's fork is checkpoint-scoped; its schema defaults `target` but
98
+ // the ACP call needs it stated or the runtime answers "sessionId is
99
+ // required" for a request it cannot place. Other harnesses reject an
100
+ // unknown `target`, so it is sent only where it is understood.
101
+ target.harness === 'zcode' ? { kind: 'latestCheckpoint' } : undefined,
102
+ );
103
+ } else if (sessionIdToLoad) {
78
104
  await proc.loadSession(sessionIdToLoad, target.cwd, 120_000);
79
105
  const reloaded = await newSession(target.cwd).catch(() => null);
80
106
  session = reloaded ?? { sessionId: sessionIdToLoad };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The session's subscriber set, split out of `AcpSession` because it is a
8
+ * transport-neutral detail: every adapter emits frames to the same listeners,
9
+ * and one throwing subscriber must not starve the others.
10
+ */
11
+
12
+ import type { AgentEvent } from '@/server/lib/omp/rpc/constants';
13
+
14
+ export class SessionListeners {
15
+ private readonly listeners = new Set<(event: AgentEvent) => void>();
16
+
17
+ add(listener: (event: AgentEvent) => void): () => void {
18
+ this.listeners.add(listener);
19
+ return () => this.listeners.delete(listener);
20
+ }
21
+
22
+ emit(event: AgentEvent): void {
23
+ for (const listener of this.listeners) {
24
+ try {
25
+ listener(event);
26
+ } catch {
27
+ // One throwing subscriber must not starve the others.
28
+ }
29
+ }
30
+ }
31
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Agent→client requests for an ACP session.
8
+ *
9
+ * Every branch answers or refuses — an unanswered call parks the turn — and the
10
+ * approval branch is the same code the in-process tier uses, so a dialog and an
11
+ * auto-answer cannot disagree.
12
+ */
13
+
14
+ import { answerPermissionRequest } from '@/server/lib/harness/acp/session-permissions';
15
+ import type { AcpId } from '@/server/lib/harness/acp/protocol';
16
+ import type { PendingPermissions } from '@/server/lib/harness/acp/permissions';
17
+ import type { AgentEvent } from '@/server/lib/omp/rpc/constants';
18
+ import type { ApprovalMode } from '@/shared/lib/omp/config/access-mode';
19
+
20
+ export interface AcpClientRequestHost {
21
+ sessionId: string;
22
+ accessMode: ApprovalMode;
23
+ permissions: PendingPermissions;
24
+ emit: (event: AgentEvent) => void;
25
+ }
26
+
27
+ export type AcpClientRequestAnswer =
28
+ | { answered: true; result: unknown }
29
+ | { answered: false; message: string }
30
+ | { answered: false; deferred: true };
31
+
32
+ export function handleAcpClientRequest(
33
+ host: AcpClientRequestHost,
34
+ id: AcpId,
35
+ method: string,
36
+ params: Record<string, unknown>,
37
+ ): Promise<AcpClientRequestAnswer> {
38
+ if (method === 'session/request_permission') {
39
+ return answerPermissionRequest({
40
+ sessionId: host.sessionId,
41
+ accessMode: host.accessMode,
42
+ permissions: host.permissions,
43
+ emit: (event) => host.emit(event),
44
+ }, id, params);
45
+ }
46
+ return Promise.resolve({ answered: false, message: `Kabmo does not implement ${method}` });
47
+ }
@@ -37,7 +37,10 @@
37
37
  import { scheduleQueueDelivery } from '@/server/lib/queue/delivery.server';
38
38
  import { emitRealtimeSignal } from '@/server/lib/realtime/signals.server';
39
39
  import { saveAcpUsage } from '@/server/lib/harness/acp/acp-telemetry.server';
40
- import type { AcpTurns } from '@/server/lib/harness/acp/turn';
40
+ import { lastAssistantText } from '@/server/lib/omp/session/goal-driver.server';
41
+ import { noteChildOutcome } from '@/server/lib/sessions/notify.server';
42
+ import { saveSessionAnswer } from '@/server/lib/sessions/answers.server';
43
+ import type { AcpTurns, AcpTurnEndInfo } from '@/server/lib/harness/acp/turn';
41
44
 
42
45
  /** What a turn reads and moves on the session. */
43
46
  export interface AcpTurnTarget {
@@ -70,10 +73,7 @@ export function beginAcpTurn(
70
73
  }
71
74
 
72
75
  /** Turn-end bookkeeping: the closed message, the badge, then the queue. */
73
- export function settleAcpTurn(
74
- target: AcpTurnTarget,
75
- info: { stopReason?: string; closedMessage: boolean },
76
- ): void {
76
+ export function settleAcpTurn(target: AcpTurnTarget, info: AcpTurnEndInfo): void {
77
77
  if (info.closedMessage) target.messageCount += 1;
78
78
  // ACP has no transcript to re-read, so the last usage snapshot is what lets
79
79
  // the Context ring answer after a reload or a restart.
@@ -91,5 +91,20 @@ export function settleAcpTurn(
91
91
  // Todo/plan/telemetry panels read their own topics; without this signal an
92
92
  // ACP turn's usage and titles never republished (the RPC settle path does it).
93
93
  emitRealtimeSignal('session-data-dirty', target.sessionId);
94
+ const finalText = lastAssistantText([info.message]);
95
+ if (finalText) void saveSessionAnswer(target.sessionId, finalText).catch(() => {});
96
+ const status = info.cancelled === true
97
+ ? 'interrupted'
98
+ : info.failed === true
99
+ ? 'failed'
100
+ : 'completed';
101
+ void noteChildOutcome({
102
+ sessionId: target.sessionId,
103
+ status,
104
+ output: finalText,
105
+ ...(status === 'failed' ? { failure: info.failure ?? 'The agent ended the turn without an answer' } : {}),
106
+ }).catch((error: unknown) => {
107
+ console.error('[sessions] could not record an ACP child outcome:', error);
108
+ });
94
109
  scheduleQueueDelivery(target);
95
110
  }
@@ -22,6 +22,7 @@ import { AcpSession } from '@/server/lib/harness/acp/session';
22
22
  import { AcpUsageMeter } from '@/server/lib/harness/acp/session-usage';
23
23
  import { AcpFrameMapper } from '@/server/lib/harness/acp/frames';
24
24
  import { AcpTurns } from '@/server/lib/harness/acp/turn';
25
+ import { SessionListeners } from '@/server/lib/harness/acp/session-listeners';
25
26
  import { PendingPermissions } from '@/server/lib/harness/acp/permissions';
26
27
  import { stampMessageModel } from '@/server/lib/harness/acp/session-config';
27
28
  import type { AgentEvent } from '@/server/lib/omp/rpc/constants';
@@ -50,6 +51,15 @@ export interface MountedSession {
50
51
  idleResets: () => number;
51
52
  /** Whether a destroy stopped the reclaim clock. */
52
53
  idleStopped: () => boolean;
54
+ /** Swap the background probe the session drives with one a case controls. */
55
+ setBackground: (probe: BackgroundProbeStub) => void;
56
+ }
57
+
58
+ /** The slice of `AcpBackgroundProbe` a session calls. */
59
+ export interface BackgroundProbeStub {
60
+ start: (baseline: string) => void;
61
+ stop: () => void;
62
+ consume: (method: string, params: Record<string, unknown>) => boolean;
53
63
  }
54
64
 
55
65
  /** One in-flight `session/prompt` the stub can settle. */
@@ -114,6 +124,13 @@ export function mountSession(): MountedSession {
114
124
  },
115
125
  });
116
126
  const marks: string[] = [];
127
+ const eventSink = new SessionListeners();
128
+ eventSink.add((event) => events.push(event));
129
+ let background: BackgroundProbeStub = {
130
+ start: () => {},
131
+ stop: () => {},
132
+ consume: () => false,
133
+ };
117
134
  Object.assign(session as unknown as Record<string, unknown>, {
118
135
  markStream: (status: string) => {
119
136
  marks.push(status);
@@ -134,10 +151,11 @@ export function mountSession(): MountedSession {
134
151
  assistantCount: 0,
135
152
  usage: new AcpUsageMeter(),
136
153
  runModel: null,
137
- listeners: new Set<(event: AgentEvent) => void>([(event) => events.push(event)]),
154
+ events: eventSink,
138
155
  proc,
139
156
  idle,
140
157
  destroyed: false,
158
+ background,
141
159
  });
142
160
  return {
143
161
  session,
@@ -147,6 +165,10 @@ export function mountSession(): MountedSession {
147
165
  streamMarks: () => marks,
148
166
  idleResets: () => idleResets,
149
167
  idleStopped: () => idleStopped,
168
+ setBackground: (probe) => {
169
+ background = probe;
170
+ Object.assign(session as unknown as Record<string, unknown>, { background: probe });
171
+ },
150
172
  };
151
173
  }
152
174
 
@@ -8,25 +8,24 @@
8
8
  * the `HarnessSession` contract every route already speaks.
9
9
  *
10
10
  * It owns the session's own state — the id, the config selectors, the resolved
11
- * model, the run flags the sidebar spinner and the queue's delivery gate read,
12
- * the agent's command list, and the approval queue a reloaded tab replays. The
13
- * RULES for each of those live beside it, one module per concern:
14
- * `session-handshake.ts` (initialize/new/load + the picks), `session-turns.ts`
15
- * (the ACK contract and turn-end bookkeeping), `session-config.ts` (adopting a
16
- * config answer, answering a parked dialog), `session-permissions.ts` (the
17
- * tier that answers before a dialog exists), `session-facts.ts` (the metadata an
18
- * agent publishes about itself between turns) and `session-web-state.ts`
19
- * (`get_state`, in the shape the omp transport reports it).
11
+ * model, the run flags the sidebar spinner and the queue delivery gate read, the
12
+ * agent's commands and the approval queue a reloaded tab replays. The RULES live
13
+ * beside it, one module per concern: `session-handshake.ts` (initialize/new/load
14
+ * + the picks), `session-turns.ts` (the ACK contract and turn-end bookkeeping),
15
+ * `session-config.ts` (config answers, parked dialogs), `session-permissions.ts`
16
+ * (the tier that answers before a dialog exists), `session-facts.ts` (what an
17
+ * agent publishes between turns) and `session-web-state.ts` (`get_state`).
20
18
  *
21
- * `send()` accepts the SAME command vocabulary the routes already send omp, so
19
+ * `send()` takes the SAME command vocabulary the routes already send omp, so
22
20
  * `routes/agent/command.ts` needs no second dispatch table.
23
21
  */
24
22
 
25
23
  import { AcpProcess } from '@/server/lib/harness/acp/client';
26
- import { AcpTurns } from '@/server/lib/harness/acp/turn';
24
+ import { AcpTurns, type AcpTurnEndInfo } from '@/server/lib/harness/acp/turn';
27
25
  import { AcpFrameMapper } from '@/server/lib/harness/acp/frames';
28
26
  import type { AcpConfigOption, AcpId } from '@/server/lib/harness/acp/protocol';
29
27
  import { promptBlocks } from '@/server/lib/harness/acp/prompt';
28
+ import { withGatewayCompatibility } from '@/server/lib/harness/acp/gateway-env';
30
29
  import { adoptConfigAnswer, publishConfigChange, settlePermissionDialog, stampMessageModel } from '@/server/lib/harness/acp/session-config';
31
30
  import { beginAcpTurn, settleAcpTurn } from '@/server/lib/harness/acp/session-turns';
32
31
  import { driveAcpGoalAfterTurn } from '@/server/lib/harness/acp/acp-goal-driver.server';
@@ -35,7 +34,16 @@ import { capabilitiesFrom } from '@/server/lib/harness/launch';
35
34
  import { PendingPermissions } from '@/server/lib/harness/acp/permissions';
36
35
  import { handleSessionNotification } from '@/server/lib/harness/acp/session-notifications';
37
36
  import { AcpUsageMeter, type AcpContextUsage } from '@/server/lib/harness/acp/session-usage';
38
- import { answerPermissionRequest } from '@/server/lib/harness/acp/session-permissions';
37
+ import { handleAcpClientRequest, type AcpClientRequestAnswer } from '@/server/lib/harness/acp/session-requests';
38
+ import { acpExitFailureFrames } from '@/server/lib/harness/acp/session-exit';
39
+ import { SessionListeners } from '@/server/lib/harness/acp/session-listeners';
40
+ import {
41
+ AcpBackgroundProbe,
42
+ BACKGROUND_LOAD_TIMEOUT_MS,
43
+ assistantTextOf,
44
+ deliverBackgroundNotice,
45
+ spawnsBackgroundWork,
46
+ } from '@/server/lib/harness/acp/background-work';
39
47
  import { acpWebState } from '@/server/lib/harness/acp/session-web-state';
40
48
  import { acpIdleReaper } from '@/server/lib/harness/acp/session-idle';
41
49
  import { DEFAULT_APPROVAL_MODE, isApprovalMode, type ApprovalMode } from '@/shared/lib/omp/config/access-mode';
@@ -92,9 +100,11 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
92
100
  private readonly proc: AcpProcess;
93
101
  /** The quiet-window reclaim; the rules live in `session-idle.ts`. */
94
102
  readonly idle: IdleReaper;
103
+ /** Watches for work that finishes after `end_turn`; see `background-work.ts`. */
104
+ private readonly background: AcpBackgroundProbe;
95
105
  private readonly mapper = new AcpFrameMapper();
96
- private readonly listeners = new Set<(event: AgentEvent) => void>();
97
- private readonly permissions = new PendingPermissions();
106
+ private readonly events = new SessionListeners();
107
+ readonly permissions = new PendingPermissions();
98
108
  private destroyHook: (() => void) | null = null;
99
109
  private destroyed = false;
100
110
  /** Set when Kabmo is the one ending the process, so the exit is not reported
@@ -105,15 +115,25 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
105
115
  constructor(options: AcpSessionOptions, cwd: string) {
106
116
  this.harness = options.harness;
107
117
  this.cwd = cwd;
118
+ const env = withGatewayCompatibility(options.harness, options.env);
108
119
  this.proc = new AcpProcess({
109
120
  command: options.command,
110
121
  cwd,
111
- ...(options.env ? { env: options.env } : {}),
122
+ ...(env ? { env } : {}),
112
123
  onNotification: (method, params) => this.onNotification(method, params),
113
124
  onClientRequest: (id, method, params) => this.onClientRequest(id, method, params),
114
125
  onExit: (info) => this.onExit(info),
115
126
  });
116
127
  this.idle = acpIdleReaper(this, options.idleDestroyMs);
128
+ // ACP holds updates produced while idle until the next request, so a turn
129
+ // that spawned a subagent is followed by a `session/load` probe. The replay
130
+ // is swallowed by the probe; only the text past the answer already shown is
131
+ // emitted, as the agent's continuation.
132
+ this.background = new AcpBackgroundProbe({
133
+ load: () => this.proc.loadSession(this.sessionId, this.cwd, BACKGROUND_LOAD_TIMEOUT_MS),
134
+ resetIdle: () => this.idle.reset(),
135
+ emit: (text) => deliverBackgroundNotice(this, text),
136
+ });
117
137
  this.turns = new AcpTurns({
118
138
  emit: (event) => this.emit(event),
119
139
  prompt: (message, images) =>
@@ -139,14 +159,14 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
139
159
  private readonly requestedModel: { provider: string; modelId: string } | null;
140
160
  private readonly requestedThinking: string | null;
141
161
  private readonly requestedMode: string | null;
142
-
143
162
  /** `initialize` + `session/new|load|resume`, then the requested selections. */
144
- async start(sessionIdToLoad?: string): Promise<{ sessionId: string }> {
163
+ async start(sessionIdToLoad?: string, forkFromSessionId?: string): Promise<{ sessionId: string }> {
145
164
  await handshakeAcpSession(
146
165
  this,
147
166
  this.proc,
148
167
  { model: this.requestedModel, thinking: this.requestedThinking, mode: this.requestedMode },
149
168
  sessionIdToLoad,
169
+ forkFromSessionId,
150
170
  );
151
171
  // A slow handshake is not idleness: the window starts once it is usable.
152
172
  this.idle.reset(true);
@@ -174,18 +194,11 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
174
194
  }
175
195
 
176
196
  onEvent(listener: (event: AgentEvent) => void): () => void {
177
- this.listeners.add(listener);
178
- return () => this.listeners.delete(listener);
197
+ return this.events.add(listener);
179
198
  }
180
199
 
181
200
  emit(event: AgentEvent): void {
182
- for (const listener of this.listeners) {
183
- try {
184
- listener(event);
185
- } catch {
186
- // One throwing subscriber must not starve the others.
187
- }
188
- }
201
+ this.events.emit(event);
189
202
  }
190
203
 
191
204
  getPendingUiDialogs(): Record<string, unknown>[] {
@@ -227,15 +240,22 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
227
240
  /** Turn-end bookkeeping the panels read — see `session-turns.ts`. A cancelled
228
241
  * turn closes the marker as an `abort` badge, every other ending a `finish`.
229
242
  * The goal driver then audits the closed message and may open the next turn. */
230
- onTurnEnded(info: { stopReason?: string; closedMessage: boolean; message?: unknown; cancelled?: boolean }): void {
243
+ onTurnEnded(info: AcpTurnEndInfo): void {
231
244
  if (info.closedMessage) this.assistantCount += 1;
232
245
  this.usage.endTurn();
233
246
  settleAcpTurn(this, info);
247
+ // A subagent outlives the turn that spawned it: antigravity answers
248
+ // `end_turn` right after `invoke_subagent`, and its completion is held
249
+ // until the next request (upstream #1461). Probe the transcript instead.
250
+ if (!info.cancelled && info.failed !== true && spawnsBackgroundWork(info.message)) {
251
+ this.background.start(assistantTextOf(info.message));
252
+ }
234
253
  void driveAcpGoalAfterTurn(this, info.message, { cancelled: info.cancelled === true }).catch(() => {});
235
254
  }
236
255
 
237
256
  /** Dispatcher seam: stop the turn. The rules live in `AcpTurns.cancel`. */
238
257
  cancelTurn(): void {
258
+ this.background.stop();
239
259
  this.turns.cancel();
240
260
  }
241
261
 
@@ -262,19 +282,7 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
262
282
  }
263
283
 
264
284
  webState(): Record<string, unknown> {
265
- return acpWebState({
266
- sessionId: this.sessionId,
267
- isStreaming: this.isStreaming,
268
- isPromptRunning: this.isPromptRunning,
269
- messageCount: this.messageCount,
270
- promptCount: this.promptCount,
271
- assistantCount: this.assistantCount,
272
- contextUsage: this.contextUsage,
273
- totalCost: this.totalCost,
274
- runModel: this.runModel,
275
- configOptions: this.configOptions,
276
- harness: this.harness,
277
- });
285
+ return acpWebState(this);
278
286
  }
279
287
 
280
288
  /** Run one turn. The promise IS the turn: ACP resolves `session/prompt` when
@@ -283,6 +291,9 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
283
291
  * `session-turns.ts`.
284
292
  */
285
293
  startTurn(message: string, images: unknown): unknown {
294
+ // A new prompt is the next request, so the agent flushes any held update
295
+ // itself; a probe would duplicate it.
296
+ this.background.stop();
286
297
  this.promptCount += 1;
287
298
  this.usage.beginTurn();
288
299
  return beginAcpTurn(this, this.turns, message, images);
@@ -291,6 +302,8 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
291
302
  private onNotification(method: string, params: Record<string, unknown>): void {
292
303
  // A long turn emits no commands but plenty of `session/update` frames.
293
304
  this.idle.reset();
305
+ // A `session/load` replay repeats the whole chat; leave it to the probe.
306
+ if (this.background.consume(method, params)) return;
294
307
  handleSessionNotification(this, method, params);
295
308
  }
296
309
 
@@ -305,32 +318,18 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
305
318
  id: AcpId,
306
319
  method: string,
307
320
  params: Record<string, unknown>,
308
- ): Promise<{ answered: true; result: unknown } | { answered: false; message: string } | { answered: false; deferred: true }> {
321
+ ): Promise<AcpClientRequestAnswer> {
309
322
  this.idle.reset();
310
- if (method === 'session/request_permission') {
311
- return answerPermissionRequest({
312
- sessionId: this.sessionId,
313
- accessMode: this.accessMode,
314
- permissions: this.permissions,
315
- emit: (event) => this.emit(event),
316
- }, id, params);
317
- }
318
- return Promise.resolve({ answered: false, message: `Kabmo does not implement ${method}` });
323
+ return handleAcpClientRequest(this, id, method, params);
319
324
  }
320
325
 
321
326
  private onExit(info: { code: number | null; stderrTail: string }): void {
322
327
  this.destroyed = true;
328
+ this.background.stop();
323
329
  this.idle.stop();
324
- if (this.closing) {
325
- this.destroyHook?.();
326
- return;
330
+ if (!this.closing) {
331
+ for (const event of acpExitFailureFrames(this.harness, info)) this.emit(event);
327
332
  }
328
- const detail = info.stderrTail.trim().split('\n').slice(-3).join(' · ');
329
- this.emit({
330
- type: 'prompt_error',
331
- errorMessage: detail || `The ${this.harness} agent exited (code ${info.code ?? 'signal'})`,
332
- });
333
- this.emit({ type: 'agent_end', isTerminal: true });
334
333
  this.destroyHook?.();
335
334
  }
336
335
 
@@ -342,6 +341,7 @@ export class AcpSession implements HarnessSession, AcpCommandHost {
342
341
  if (this.destroyed) return;
343
342
  this.destroyed = true;
344
343
  this.closing = true;
344
+ this.background.stop();
345
345
  this.idle.stop();
346
346
  this.permissions.clear();
347
347
  await this.proc.dispose().catch(() => {});