@kabmo-labs/kabmo 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +440 -436
  3. package/dist/client/static/js/{index-ga8cbpt4.js → index-95b3n20k.js} +945 -945
  4. package/dist/client/static/js/index-p2yw9ywf.css +1 -0
  5. package/package.json +1 -1
  6. package/src/client/components/common/session-actions-menu/index.tsx +38 -12
  7. package/src/client/components/common/session-branch/BranchGuides.tsx +93 -0
  8. package/src/client/components/common/session-branch/SubagentRow.tsx +77 -0
  9. package/src/client/components/common/session-branch/index.tsx +169 -0
  10. package/src/client/components/common/session-branch/session-branch.test.tsx +240 -0
  11. package/src/client/components/common/session-branch/style.ts +29 -0
  12. package/src/client/components/common/session-row/StatusSlot.tsx +15 -3
  13. package/src/client/components/common/session-row/index.tsx +24 -25
  14. package/src/client/components/common/session-row/session-row.test.tsx +11 -0
  15. package/src/client/components/common/session-state-provider/index.tsx +1 -1
  16. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +64 -68
  17. package/src/client/components/layout/session-sidebar/SessionItem.batch.test.ts +3 -3
  18. package/src/client/components/layout/session-sidebar/SessionItem.test.ts +25 -2
  19. package/src/client/components/layout/session-sidebar/SessionItem.tsx +33 -30
  20. package/src/client/components/layout/session-sidebar/about-modal/HarnessRow.tsx +261 -0
  21. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +35 -225
  22. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +36 -16
  23. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +11 -3
  24. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +13 -4
  25. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +28 -13
  26. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +59 -57
  27. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +57 -61
  28. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.test.ts +5 -0
  29. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +33 -30
  30. package/src/client/components/settings/Sidebar.tsx +1 -1
  31. package/src/client/components/settings/categories/NotificationSettings.test.tsx +92 -0
  32. package/src/client/components/settings/categories/NotificationSettings.tsx +112 -2
  33. package/src/client/components/settings/categories/harness-settings/HarnessCard.tsx +1 -1
  34. package/src/client/components/workspace/chat-timeline/AiMessageFooter.fork.test.ts +94 -0
  35. package/src/client/components/workspace/chat-timeline/AiMessageFooter.tsx +31 -5
  36. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +28 -39
  37. package/src/client/components/workspace/chat-timeline/MessageList.tsx +7 -5
  38. package/src/client/components/workspace/chat-timeline/PendingChatView.tsx +10 -0
  39. package/src/client/components/workspace/chat-timeline/RunFooter.tsx +12 -3
  40. package/src/client/components/workspace/chat-timeline/chat-input/AttachmentToolbar.tsx +2 -0
  41. package/src/client/components/workspace/chat-timeline/chat-input/ModeToggles.tsx +15 -1
  42. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.test.tsx +85 -0
  43. package/src/client/components/workspace/chat-timeline/chat-input/SessionModeDropdown.tsx +84 -0
  44. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.tsx +2 -0
  45. package/src/client/components/workspace/chat-timeline/chat-input/modes-props.ts +5 -0
  46. package/src/client/components/workspace/chat-timeline/index.tsx +10 -21
  47. package/src/client/components/workspace/chat-timeline/target-picker/DraftTargetRow.tsx +115 -0
  48. package/src/client/components/workspace/chat-timeline/target-picker/ParentSessionPicker.tsx +173 -0
  49. package/src/client/components/workspace/chat-timeline/target-picker/parent-session-options.test.ts +49 -0
  50. package/src/client/hooks/chat/composer/items.test.ts +19 -0
  51. package/src/client/hooks/chat/omp/folder-auto-expand.ts +1 -1
  52. package/src/client/hooks/chat/omp/pending-adoption.ts +51 -0
  53. package/src/client/hooks/chat/omp/pending-child.test.ts +73 -0
  54. package/src/client/hooks/chat/omp/pending-entry.ts +59 -0
  55. package/src/client/hooks/chat/omp/pending-rows.ts +6 -2
  56. package/src/client/hooks/chat/omp/pending-sessions.test.ts +1 -2
  57. package/src/client/hooks/chat/omp/pending-sessions.ts +45 -69
  58. package/src/client/hooks/chat/omp/pending-waiting.ts +1 -1
  59. package/src/client/hooks/chat/omp/run-switch.ts +1 -1
  60. package/src/client/hooks/chat/omp/session-list.tsx +4 -0
  61. package/src/client/hooks/chat/subagents/roster.ts +122 -0
  62. package/src/client/hooks/chat/timeline/child-spawn.test.ts +55 -0
  63. package/src/client/hooks/chat/timeline/child-spawn.ts +45 -0
  64. package/src/client/hooks/chat/timeline/fork-request.test.ts +54 -0
  65. package/src/client/hooks/chat/timeline/fork-request.ts +43 -0
  66. package/src/client/hooks/chat/timeline/mode-availability.test.ts +1 -1
  67. package/src/client/hooks/chat/timeline/mode-availability.ts +33 -0
  68. package/src/client/hooks/chat/timeline/mode-markers.ts +7 -1
  69. package/src/client/hooks/chat/timeline/mode-post.ts +15 -3
  70. package/src/client/hooks/chat/timeline/modes-contract.ts +9 -4
  71. package/src/client/hooks/chat/timeline/modes.test.ts +56 -18
  72. package/src/client/hooks/chat/timeline/modes.ts +42 -29
  73. package/src/client/hooks/chat/timeline/pending-branch.ts +205 -0
  74. package/src/client/hooks/chat/timeline/pending-dispatch.ts +253 -0
  75. package/src/client/hooks/chat/timeline/send.ts +17 -103
  76. package/src/client/hooks/chat/timeline/session-harness.ts +6 -0
  77. package/src/client/hooks/chat/timeline/stop-with-queue.ts +42 -0
  78. package/src/client/hooks/chat/timeline/use-fork-session.ts +40 -31
  79. package/src/client/hooks/models/use-harness-update.test.ts +137 -44
  80. package/src/client/hooks/models/use-harness-update.ts +133 -85
  81. package/src/client/hooks/ui/input-required-alert.ts +12 -5
  82. package/src/client/hooks/ui/notifications.ts +45 -0
  83. package/src/client/hooks/ui/run-outcome-alert.ts +48 -0
  84. package/src/client/hooks/workspace/expanded-sessions.ts +36 -7
  85. package/src/client/lib/native/open-session.ts +33 -0
  86. package/src/client/lib/notifications/os.test.ts +125 -0
  87. package/src/client/lib/notifications/os.ts +130 -0
  88. package/src/client/lib/plugins/sidebar-bridge.ts +2 -20
  89. package/src/client/lib/router/open-session.test.ts +75 -0
  90. package/src/client/lib/router/open-session.ts +34 -0
  91. package/src/client/lib/signals.ts +5 -1
  92. package/src/client/main.tsx +6 -0
  93. package/src/server/lib/db/schema.ts +1 -0
  94. package/src/server/lib/harness/acp/calls.ts +15 -1
  95. package/src/server/lib/harness/acp/client-capabilities.test.ts +55 -0
  96. package/src/server/lib/harness/acp/client-capabilities.ts +61 -0
  97. package/src/server/lib/harness/acp/client-fs.test.ts +135 -0
  98. package/src/server/lib/harness/acp/client-fs.ts +131 -0
  99. package/src/server/lib/harness/acp/client-initialize.test.ts +70 -0
  100. package/src/server/lib/harness/acp/client-initialize.ts +84 -0
  101. package/src/server/lib/harness/acp/client.ts +31 -21
  102. package/src/server/lib/harness/acp/commands.test.ts +5 -5
  103. package/src/server/lib/harness/acp/commands.ts +14 -2
  104. package/src/server/lib/harness/acp/frames-timing.test.ts +68 -0
  105. package/src/server/lib/harness/acp/frames-v2.test.ts +85 -0
  106. package/src/server/lib/harness/acp/frames.ts +71 -158
  107. package/src/server/lib/harness/acp/mapper.test.ts +40 -0
  108. package/src/server/lib/harness/acp/mapper.ts +12 -0
  109. package/src/server/lib/harness/acp/permissions.ts +6 -0
  110. package/src/server/lib/harness/acp/protocol.ts +41 -2
  111. package/src/server/lib/harness/acp/session-facts.ts +1 -1
  112. package/src/server/lib/harness/acp/session-handshake.test.ts +90 -1
  113. package/src/server/lib/harness/acp/session-handshake.ts +83 -6
  114. package/src/server/lib/harness/acp/session-idle.ts +7 -6
  115. package/src/server/lib/harness/acp/session-notifications.ts +41 -2
  116. package/src/server/lib/harness/acp/session-observers.test.ts +63 -0
  117. package/src/server/lib/harness/acp/session-permissions.test.ts +29 -0
  118. package/src/server/lib/harness/acp/session-permissions.ts +36 -0
  119. package/src/server/lib/harness/acp/session-requests.test.ts +92 -0
  120. package/src/server/lib/harness/acp/session-requests.ts +48 -6
  121. package/src/server/lib/harness/acp/session-turns.ts +8 -3
  122. package/src/server/lib/harness/acp/session-usage.ts +4 -0
  123. package/src/server/lib/harness/acp/session-web-state.ts +30 -2
  124. package/src/server/lib/harness/acp/session.test-util.ts +19 -1
  125. package/src/server/lib/harness/acp/session.ts +60 -60
  126. package/src/server/lib/harness/acp/tool-calls.ts +223 -0
  127. package/src/server/lib/harness/acp/turn.test.ts +102 -0
  128. package/src/server/lib/harness/acp/turn.ts +81 -6
  129. package/src/server/lib/harness/acp/v2.test.ts +144 -0
  130. package/src/server/lib/harness/acp/v2.ts +220 -0
  131. package/src/server/lib/harness/acp/verbs.ts +46 -6
  132. package/src/server/lib/harness/launch.test.ts +25 -0
  133. package/src/server/lib/harness/launch.ts +21 -9
  134. package/src/server/lib/harness/session.ts +3 -0
  135. package/src/server/lib/harness/update-job-store.test.ts +37 -12
  136. package/src/server/lib/harness/update-job-store.ts +22 -16
  137. package/src/server/lib/harness/update-job.server.ts +66 -175
  138. package/src/server/lib/harness/update-queue.server.ts +292 -0
  139. package/src/server/lib/harness/update-queue.test.ts +265 -0
  140. package/src/server/lib/harness/update-spawn.server.ts +96 -0
  141. package/src/server/lib/harness/update-worker.ts +8 -3
  142. package/src/server/lib/lifecycle/after-listen.ts +9 -0
  143. package/src/server/lib/lifecycle/paths.ts +14 -9
  144. package/src/server/lib/omp/rpc/run-settle.server.ts +10 -1
  145. package/src/server/lib/omp/rpc/subagent-liveness.ts +5 -5
  146. package/src/server/lib/omp/rpc/terminal-settle.ts +5 -1
  147. package/src/server/lib/omp/session/delete-flow.server.ts +1 -0
  148. package/src/server/lib/omp/session/sidebar-data.server.ts +10 -12
  149. package/src/server/lib/sessions/fork.server.test.ts +68 -0
  150. package/src/server/lib/sessions/fork.server.ts +31 -6
  151. package/src/server/lib/sessions/spawn.server.test.ts +41 -0
  152. package/src/server/lib/sessions/spawn.server.ts +27 -2
  153. package/src/server/routes/agent/harness-command.ts +6 -5
  154. package/src/server/routes/chat/stream.ts +7 -2
  155. package/src/server/routes/harness/update-status.ts +18 -12
  156. package/src/server/routes/harness/update.test.ts +53 -16
  157. package/src/server/routes/harness/update.ts +13 -8
  158. package/src/server/routes/sessions/body-readers.ts +43 -0
  159. package/src/server/routes/sessions/fork.ts +19 -4
  160. package/src/server/routes/sessions/routes.test.ts +1 -2
  161. package/src/server/routes/sessions/session.ts +19 -0
  162. package/src/server/routes/sessions/spawn.ts +16 -13
  163. package/src/shared/lib/chat/omp/agent-events.ts +11 -0
  164. package/src/shared/lib/chat/omp/session-modes-signal.test.ts +41 -0
  165. package/src/shared/lib/harness/mode-signal.ts +20 -0
  166. package/src/shared/lib/harness/session-modes.ts +24 -0
  167. package/src/shared/lib/harness/update-job.ts +53 -6
  168. package/src/shared/lib/icons/tint-hues.generated.ts +34 -34
  169. package/src/shared/lib/notifications/outcomes.test.ts +96 -0
  170. package/src/shared/lib/notifications/outcomes.ts +64 -0
  171. package/src/shared/lib/notifications/settings.test.ts +49 -0
  172. package/src/shared/lib/notifications/settings.ts +34 -0
  173. package/src/shared/lib/omp/session/default-title.ts +5 -4
  174. package/src/shared/lib/omp/session/prewarm-misc.test.ts +3 -2
  175. package/src/shared/lib/omp/session/schema-migrations.ts +4 -0
  176. package/src/shared/lib/omp/session/stream-state.server.test.ts +19 -0
  177. package/src/shared/lib/omp/session/stream-state.server.ts +24 -4
  178. package/src/shared/lib/settings/defaults.ts +3 -0
  179. package/src/shared/types/harness-update.ts +24 -0
  180. package/src/shared/types/realtime.ts +2 -0
  181. package/src/shared/types/settings/state.ts +10 -0
  182. package/src/shared/types/workspace.ts +4 -0
  183. package/src/test-support/harness-table.test-util.ts +25 -9
  184. package/dist/client/static/js/index-bc9aa4mx.css +0 -1
  185. package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +0 -113
  186. package/src/client/components/common/subagent-list/index.tsx +0 -165
  187. package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +0 -66
  188. package/src/client/hooks/workspace/child-expansion.ts +0 -33
@@ -0,0 +1,223 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The tool-call half of the ACP mapper: create on first sight, PATCH afterwards.
8
+ *
9
+ * Split out of `frames.ts` because the v1 and v2 lifecycles now share one
10
+ * accumulator and the file ceiling is real. The rules are the same in both
11
+ * versions:
12
+ *
13
+ * - a `tool_call_update` for an unknown id CREATES the call (v2 has no separate
14
+ * create notification; v1's `tool_call` is just the first update);
15
+ * - every field but `toolCallId` is a patch: omitted = unchanged, `null` =
16
+ * cleared, a value = replaced;
17
+ * - a completed/failed/cancelled update often carries no content, so the card's
18
+ * body must come from the accumulated state.
19
+ *
20
+ * The card itself is a block of the accumulated assistant message, so the host
21
+ * owns that array and the snapshot; this class never touches either directly.
22
+ */
23
+
24
+ import type { AgentEvent } from '@/server/lib/omp/rpc/constants';
25
+ import {
26
+ acpContentDetails,
27
+ acpContentText,
28
+ acpToolDetails,
29
+ acpToolOutput,
30
+ acpToolTarget,
31
+ isKnownToolName,
32
+ toolTypeFor,
33
+ } from '@/server/lib/harness/acp/mapper';
34
+ import type { AcpToolKind, AcpToolStatus } from '@/server/lib/harness/acp/protocol';
35
+
36
+ /** The message block a tool card renders from. */
37
+ export interface ToolCallBlock {
38
+ type: 'toolCall';
39
+ id: string;
40
+ name: string;
41
+ arguments?: Record<string, unknown>;
42
+ toolKind?: AcpToolKind;
43
+ toolType?: string;
44
+ }
45
+
46
+ interface OpenTool {
47
+ id: string;
48
+ name: string;
49
+ kind?: AcpToolKind;
50
+ title?: string;
51
+ status: AcpToolStatus;
52
+ rawOutput?: unknown;
53
+ /** `tool_call(Update).content` — where some agents put the diff/output. */
54
+ content?: unknown;
55
+ locations?: unknown;
56
+ startedAt: number;
57
+ }
58
+
59
+ export interface ToolCallHost {
60
+ pushBlock(block: ToolCallBlock): void;
61
+ snapshot(): Record<string, unknown>;
62
+ }
63
+
64
+ export class AcpToolCalls {
65
+ private readonly calls = new Map<string, OpenTool>();
66
+
67
+ constructor(private readonly host: ToolCallHost) {}
68
+
69
+ /** Forget per-turn state (an aborted run, a fresh load). */
70
+ reset(): void {
71
+ this.calls.clear();
72
+ }
73
+
74
+ /** Tool calls still running — the driver closes them if the agent exits. */
75
+ openCalls(): string[] {
76
+ return [...this.calls.values()]
77
+ .filter((call) => call.status === 'pending' || call.status === 'in_progress' || call.status === 'paused')
78
+ .map((call) => call.id);
79
+ }
80
+
81
+ /** First sight of an id: draw the card and register it while it runs. */
82
+ open(update: Record<string, unknown>): AgentEvent[] {
83
+ const toolCallId = typeof update.toolCallId === 'string' ? update.toolCallId : '';
84
+ if (!toolCallId) return [];
85
+ const name = typeof update.name === 'string' && update.name
86
+ ? update.name
87
+ : typeof update.title === 'string' && update.title
88
+ ? update.title
89
+ : 'tool';
90
+ const kind = typeof update.kind === 'string' ? (update.kind as AcpToolKind) : undefined;
91
+ const status = typeof update.status === 'string' ? (update.status as AcpToolStatus) : 'pending';
92
+ // A specific kind is authoritative. `other`/absent is only an explicit type
93
+ // when the name is one the renderers know; otherwise the shared parser's
94
+ // own inference from the name is better informed than a forced `read`.
95
+ const toolType = kind !== undefined && kind !== 'other'
96
+ ? toolTypeFor(kind, name)
97
+ : isKnownToolName(name) ? toolTypeFor(kind, name) : undefined;
98
+ const rawInput = update.rawInput;
99
+ const args = rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)
100
+ ? Object.fromEntries(Object.entries(rawInput))
101
+ : undefined;
102
+
103
+ this.host.pushBlock({
104
+ type: 'toolCall',
105
+ id: toolCallId,
106
+ name,
107
+ ...(args ? { arguments: args } : {}),
108
+ ...(kind ? { toolKind: kind } : {}),
109
+ ...(toolType ? { toolType } : {}),
110
+ });
111
+
112
+ const frames: AgentEvent[] = [
113
+ {
114
+ type: 'message_update',
115
+ message: this.host.snapshot(),
116
+ assistantMessageEvent: { type: 'toolcall_start' },
117
+ },
118
+ {
119
+ type: 'tool_execution_start',
120
+ toolCallId,
121
+ toolName: name,
122
+ ...(toolType ? { toolType } : {}),
123
+ ...(args ? { args } : {}),
124
+ ...(typeof update.title === 'string' ? { intent: update.title } : {}),
125
+ ...(acpToolTarget(update.locations, rawInput) ? { target: acpToolTarget(update.locations, rawInput) } : {}),
126
+ },
127
+ ];
128
+
129
+ if (isFinal(status)) {
130
+ frames.push(endFrame(update, toolCallId, name, status));
131
+ } else {
132
+ this.calls.set(toolCallId, {
133
+ id: toolCallId,
134
+ name,
135
+ kind,
136
+ title: typeof update.title === 'string' ? update.title : undefined,
137
+ status,
138
+ rawOutput: update.rawOutput,
139
+ content: update.content,
140
+ locations: update.locations,
141
+ startedAt: Date.now(),
142
+ });
143
+ }
144
+ return frames;
145
+ }
146
+
147
+ /** Patch an existing call; an unknown id is a create (v2's only shape). */
148
+ patch(update: Record<string, unknown>): AgentEvent[] {
149
+ const toolCallId = typeof update.toolCallId === 'string' ? update.toolCallId : '';
150
+ if (!toolCallId) return [];
151
+ const existing = this.calls.get(toolCallId);
152
+ if (!existing) return this.open(update);
153
+
154
+ if (update.rawOutput !== undefined) existing.rawOutput = update.rawOutput;
155
+ if (update.content !== undefined) existing.content = update.content;
156
+ if (update.locations !== undefined) existing.locations = update.locations;
157
+ if (typeof update.title === 'string') existing.title = update.title;
158
+ const status = typeof update.status === 'string' ? (update.status as AcpToolStatus) : existing.status;
159
+ existing.status = status;
160
+
161
+ const result = existing.rawOutput ?? (existing.content === undefined ? undefined : { content: existing.content });
162
+ const output = acpToolOutput(existing.rawOutput) || acpContentText(existing.content);
163
+ const details = acpToolDetails(existing.rawOutput) ?? acpContentDetails(existing.content);
164
+
165
+ if (isFinal(status)) {
166
+ this.calls.delete(toolCallId);
167
+ return [{
168
+ type: 'tool_execution_end',
169
+ toolCallId,
170
+ toolName: existing.name,
171
+ result,
172
+ isError: status !== 'completed',
173
+ details,
174
+ durationMs: Math.max(0, Date.now() - existing.startedAt),
175
+ output,
176
+ }];
177
+ }
178
+
179
+ return [{
180
+ type: 'tool_execution_update',
181
+ toolCallId,
182
+ toolName: existing.name,
183
+ partialResult: result,
184
+ // The ACP output shape may nest text (`{type:"content", content:{…}}`),
185
+ // which `toolResultText` does not walk. The flattened read travels with
186
+ // the raw result so the card is not blank while the call is running.
187
+ output,
188
+ }];
189
+ }
190
+
191
+ /** v2 `tool_call_content_chunk`: append one content item to an open call. */
192
+ appendContent(update: Record<string, unknown>): AgentEvent[] {
193
+ const toolCallId = typeof update.toolCallId === 'string' ? update.toolCallId : '';
194
+ const item = update.content;
195
+ if (!toolCallId || item === undefined || item === null) return [];
196
+ const existing = this.calls.get(toolCallId);
197
+ if (!existing) return this.open({ ...update, content: [item] });
198
+ const current = Array.isArray(existing.content) ? existing.content : [];
199
+ existing.content = [...current, item];
200
+ return [];
201
+ }
202
+ }
203
+
204
+ function isFinal(status: AcpToolStatus): boolean {
205
+ return status === 'completed' || status === 'failed' || status === 'cancelled';
206
+ }
207
+
208
+ function endFrame(
209
+ update: Record<string, unknown>,
210
+ toolCallId: string,
211
+ name: string,
212
+ status: AcpToolStatus,
213
+ ): AgentEvent {
214
+ return {
215
+ type: 'tool_execution_end',
216
+ toolCallId,
217
+ toolName: name,
218
+ result: update.rawOutput ?? (update.content === undefined ? undefined : { content: update.content }),
219
+ isError: status !== 'completed',
220
+ details: acpToolDetails(update.rawOutput) ?? acpContentDetails(update.content),
221
+ output: acpToolOutput(update.rawOutput) || acpContentText(update.content),
222
+ };
223
+ }
@@ -1,4 +1,5 @@
1
1
  import { describe, expect, test } from 'bun:test';
2
+ import { AcpRequestError } from '@/server/lib/harness/acp/calls';
2
3
  import { AcpTurns, type AcpTurnSeams } from '@/server/lib/harness/acp/turn';
3
4
 
4
5
  type TurnEnd = Parameters<AcpTurnSeams['onTurnEnd']>[0];
@@ -65,6 +66,20 @@ describe('AcpTurns failure classification', () => {
65
66
  expect(info.closedMessage).toBe(true);
66
67
  });
67
68
 
69
+ test('an ACP -32800 answer is a cancelled turn, not a prompt error', async () => {
70
+ const { turns, events, ended } = harness({
71
+ prompt: async () => {
72
+ throw new AcpRequestError('Request cancelled', -32800);
73
+ },
74
+ });
75
+ turns.start('do the work', undefined);
76
+
77
+ const info = await ended;
78
+ expect(info.cancelled).toBe(true);
79
+ expect(info.failed).toBeUndefined();
80
+ expect(events.some((event) => event.type === 'prompt_error')).toBe(false);
81
+ });
82
+
68
83
  test('a cancelled turn is interrupted, never failed', async () => {
69
84
  const { turns, ended } = harness({ prompt: () => new Promise(() => {}) });
70
85
  turns.start('do the work', undefined);
@@ -79,3 +94,90 @@ describe('AcpTurns failure classification', () => {
79
94
  expect(info.failed).toBeUndefined();
80
95
  });
81
96
  });
97
+
98
+ describe('AcpTurns v2 completion', () => {
99
+ test('acceptance does not end the turn; an idle state_update does', async () => {
100
+ const { turns, ended } = harness();
101
+ turns.completion = 'state';
102
+ turns.start('do the work', undefined);
103
+ await Promise.resolve();
104
+ await Promise.resolve();
105
+
106
+ let finished = false;
107
+ void ended.then(() => { finished = true; });
108
+ await Promise.resolve();
109
+ expect(finished).toBe(false);
110
+
111
+ turns.onStateUpdate({ state: 'idle', stopReason: 'end_turn' });
112
+ const info = await ended;
113
+ expect(info.stopReason).toBe('end_turn');
114
+ expect(info.cancelled).toBeUndefined();
115
+ });
116
+
117
+ test('idle without a stop reason is not a failure in v2', async () => {
118
+ const { turns, ended, events } = harness();
119
+ turns.completion = 'state';
120
+ turns.start('do the work', undefined);
121
+ await Promise.resolve();
122
+ await Promise.resolve();
123
+ turns.onStateUpdate({ state: 'idle' });
124
+
125
+ const info = await ended;
126
+ expect(info.failed).toBeUndefined();
127
+ expect(events.some((event) => event.type === 'prompt_error')).toBe(false);
128
+ });
129
+
130
+ test('an idle error carries the agent message as the failure', async () => {
131
+ const { turns, ended, events } = harness();
132
+ turns.completion = 'state';
133
+ turns.start('do the work', undefined);
134
+ await Promise.resolve();
135
+ await Promise.resolve();
136
+ turns.onStateUpdate({
137
+ state: 'idle',
138
+ stopReason: 'error',
139
+ error: { code: -32000, message: 'Authentication required' },
140
+ });
141
+
142
+ const info = await ended;
143
+ expect(info.failed).toBe(true);
144
+ expect(info.failure).toBe('Authentication required');
145
+ expect(events.some((event) => event.type === 'prompt_error')).toBe(true);
146
+ });
147
+
148
+ test('a cancelled v2 turn is not reopened by the cancelled run late states', async () => {
149
+ const { turns, ended } = harness();
150
+ turns.completion = 'state';
151
+ turns.start('do the work', undefined);
152
+ await Promise.resolve();
153
+ await Promise.resolve();
154
+ turns.cancel();
155
+ await ended;
156
+ turns.onStateUpdate({ state: 'running' });
157
+ expect(turns.isStreaming).toBe(false);
158
+ turns.onStateUpdate({ state: 'idle' });
159
+ expect(turns.isStreaming).toBe(false);
160
+ });
161
+
162
+ test('agent-initiated work opens a turn and idle closes it', async () => {
163
+ const { turns, ended, events } = harness();
164
+ turns.completion = 'state';
165
+ turns.onStateUpdate({ state: 'running' });
166
+ expect(turns.isStreaming).toBe(true);
167
+ expect(events.some((event) => event.type === 'agent_start')).toBe(true);
168
+ turns.onStateUpdate({ state: 'idle', stopReason: 'end_turn' });
169
+ await expect(ended).resolves.toMatchObject({ stopReason: 'end_turn' });
170
+ });
171
+
172
+ test('a running state does not close the turn', async () => {
173
+ const { turns, ended } = harness();
174
+ turns.completion = 'state';
175
+ turns.start('do the work', undefined);
176
+ await Promise.resolve();
177
+ await Promise.resolve();
178
+ turns.onStateUpdate({ state: 'running' });
179
+ turns.onStateUpdate({ state: 'requires_action' });
180
+ turns.onStateUpdate({ state: 'idle', stopReason: 'end_turn' });
181
+ await expect(ended).resolves.toMatchObject({ stopReason: 'end_turn' });
182
+ });
183
+ });
@@ -19,6 +19,7 @@
19
19
  */
20
20
 
21
21
  import type { AgentEvent } from '@/server/lib/omp/rpc/constants';
22
+ import { AcpRequestError } from '@/server/lib/harness/acp/calls';
22
23
  import { turnEndFrame } from '@/server/lib/harness/acp/frames';
23
24
 
24
25
  /** What a closed turn reports to its session and the parent notice. */
@@ -57,6 +58,12 @@ export interface AcpTurnSeams {
57
58
  export class AcpTurns {
58
59
  isStreaming = false;
59
60
  isPromptRunning = false;
61
+ /**
62
+ * How a turn ENDS. v1: the `session/prompt` response carries `stopReason`.
63
+ * v2: the response acknowledges insertion; an idle `state_update` ends the
64
+ * turn, so the prompt's resolution only clears the acceptance request.
65
+ */
66
+ completion: 'response' | 'state' = 'response';
60
67
  /** The turn whose frames are accepted, null when none is open. */
61
68
  private open: number | null = null;
62
69
  /** Identity of the last turn started; only ever grows, so a late reply can be
@@ -66,6 +73,8 @@ export class AcpTurns {
66
73
  private request: Promise<unknown> | null = null;
67
74
  /** The prompt text of the turn being opened, for the silent-turn verdict. */
68
75
  private promptText = '';
76
+ /** Set by a local cancel: non-idle states are the cancelled run, not new work. */
77
+ private awaitingCancellation = false;
69
78
 
70
79
  constructor(private readonly seams: AcpTurnSeams) {}
71
80
 
@@ -78,6 +87,7 @@ export class AcpTurns {
78
87
  this.seq += 1;
79
88
  const turnId = this.seq;
80
89
  this.promptText = message;
90
+ this.awaitingCancellation = false;
81
91
  this.isPromptRunning = true;
82
92
  this.isStreaming = true;
83
93
  this.seams.emit({ type: 'agent_start' });
@@ -93,9 +103,20 @@ export class AcpTurns {
93
103
  this.request = request;
94
104
  void request
95
105
  .then(
96
- (result) => this.settle(turnId, () => this.finish(result)),
106
+ (result) => {
107
+ // v2: acceptance is not completion. The idle `state_update` closes it.
108
+ if (this.completion === 'state') return;
109
+ this.settle(turnId, () => this.finish(result as { stopReason?: string } | undefined));
110
+ },
97
111
  (error: unknown) =>
98
112
  this.settle(turnId, () => {
113
+ // `-32800` is ACP's "Request cancelled": an agent that aborted the
114
+ // turn itself (context limit, internal timeout) answered with this
115
+ // instead of a stop reason. It is not a failure to show the user.
116
+ if (error instanceof AcpRequestError && error.code === -32800) {
117
+ this.finish({ stopReason: 'cancelled' });
118
+ return;
119
+ }
99
120
  const message = error instanceof Error ? error.message : String(error);
100
121
  this.seams.emit({ type: 'prompt_error', errorMessage: message });
101
122
  // The agent's own error is the reason. `finish` must not append its
@@ -121,6 +142,7 @@ export class AcpTurns {
121
142
  * turn is chained behind.
122
143
  */
123
144
  cancel(): void {
145
+ this.awaitingCancellation = true;
124
146
  if (this.open === null) {
125
147
  // Nothing dispatched yet, but a turn may be queued behind the previous
126
148
  // request: clear its flags too, or Stop leaves the session permanently
@@ -140,6 +162,59 @@ export class AcpTurns {
140
162
  return this.open !== null;
141
163
  }
142
164
 
165
+ /**
166
+ * v2's turn boundary: an idle `state_update` ends foreground work.
167
+ *
168
+ * `running`/`requires_action` do not open a turn: a prompt that is still being
169
+ * inserted is already open, and agent-initiated work without a prompt is not
170
+ * represented as a Kabmo turn yet. Repeats are idempotent because `settle`
171
+ * matches the turn id.
172
+ */
173
+ onStateUpdate(update: Record<string, unknown>): void {
174
+ if (this.completion !== 'state') return;
175
+ const state = typeof update.state === 'string' ? update.state : '';
176
+ if (state !== 'idle') {
177
+ // The cancelled run may still report running/requires_action before its
178
+ // idle; those are not a new foreground interval.
179
+ if (this.awaitingCancellation) return;
180
+ // v2 allows foreground work with no prompt (a goal, a follow-up on a
181
+ // background task). Open a turn so its frames are accepted and rendered.
182
+ if (this.open === null && !this.isPromptRunning && !this.isStreaming) this.beginAgentTurn();
183
+ return;
184
+ }
185
+ this.awaitingCancellation = false;
186
+ if (this.open === null) return;
187
+ const turnId = this.open;
188
+ this.settle(turnId, () => {
189
+ const error = update.error && typeof update.error === 'object'
190
+ ? (update.error as Record<string, unknown>)
191
+ : undefined;
192
+ const failure = typeof error?.message === 'string' ? error.message : undefined;
193
+ const stopReason = typeof update.stopReason === 'string' ? update.stopReason : undefined;
194
+ if (stopReason === 'error') {
195
+ this.seams.emit({
196
+ type: 'prompt_error',
197
+ errorMessage: failure ?? 'The agent ended the turn with an error',
198
+ });
199
+ this.finish({ stopReason: 'error' }, true, failure);
200
+ return;
201
+ }
202
+ this.finish(stopReason ? { stopReason } : undefined);
203
+ });
204
+ }
205
+
206
+ /** A v2 foreground interval that no `session/prompt` started. */
207
+ private beginAgentTurn(): void {
208
+ this.seq += 1;
209
+ this.open = this.seq;
210
+ this.promptText = '';
211
+ this.isPromptRunning = true;
212
+ this.isStreaming = true;
213
+ this.seams.resetMapper();
214
+ this.seams.emit({ type: 'agent_start' });
215
+ this.seams.emit({ type: 'turn_start' });
216
+ }
217
+
143
218
  /** Close a turn, unless it was cancelled first: a cancelled turn's late reply
144
219
  * must not close the one the user is now watching. */
145
220
  private settle(turnId: number, close: () => void): void {
@@ -172,14 +247,14 @@ export class AcpTurns {
172
247
  const answered = hasRenderableAnswer(closed) || abandoned.length > 0;
173
248
  const cancelled = result?.stopReason === 'cancelled';
174
249
  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);
250
+ // v2 says clients cannot infer failure from an idle without a stop reason;
251
+ // the "silent answer is a failure" rule is a v1 agent behaviour (pi-acp).
252
+ const failed = !cancelled && !slash
253
+ && (reported || (this.completion === 'response' && !answered));
179
254
  const reason = failed
180
255
  ? failure ?? 'The agent ended the turn without sending an answer'
181
256
  : null;
182
- if (!answered && !cancelled && !reported && !slash) {
257
+ if (failed && !reported && !slash) {
183
258
  this.seams.emit({
184
259
  type: 'prompt_error',
185
260
  errorMessage: reason ?? 'The agent ended the turn without sending an answer',
@@ -0,0 +1,144 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The v2 adapter.
8
+ *
9
+ * Every case pins a field the rest of Kabmo would otherwise read as v1:
10
+ * role-agnostic `info`/`capabilities`, object support markers, `configId`,
11
+ * permission `subject`, keyed plans, and the setup response's initial commands.
12
+ */
13
+
14
+ import { describe, expect, test } from 'bun:test';
15
+ import {
16
+ normalizeCommands,
17
+ normalizeConfigOptions,
18
+ normalizeInitializeResult,
19
+ normalizePermissionParams,
20
+ normalizeSessionResult,
21
+ planEntries,
22
+ } from '@/server/lib/harness/acp/v2';
23
+
24
+ const v2Init = {
25
+ protocolVersion: 2,
26
+ info: { name: 'agent', title: 'Agent', version: '2.0.0' },
27
+ capabilities: {
28
+ session: {
29
+ prompt: { image: {} },
30
+ mcp: { http: {} },
31
+ delete: {},
32
+ additionalDirectories: {},
33
+ },
34
+ _meta: { steering: { supported: true } },
35
+ },
36
+ authMethods: [{ methodId: 'login', type: 'agent', name: 'Login' }],
37
+ };
38
+
39
+ describe('normalizeInitializeResult', () => {
40
+ test('maps role-agnostic info and nested session capabilities to the v1 record', () => {
41
+ const init = normalizeInitializeResult(v2Init);
42
+ expect(init.protocolVersion).toBe(2);
43
+ expect(init.agentInfo).toEqual({ name: 'agent', title: 'Agent', version: '2.0.0' });
44
+ expect(init.agentCapabilities).toMatchObject({
45
+ loadSession: false,
46
+ promptCapabilities: { image: true, audio: false, embeddedContext: false },
47
+ mcpCapabilities: { http: true, sse: false },
48
+ sessionCapabilities: {
49
+ list: {},
50
+ resume: {},
51
+ close: {},
52
+ delete: {},
53
+ additionalDirectories: {},
54
+ },
55
+ });
56
+ expect(init.authMethods).toEqual([{ id: 'login', type: 'agent', name: 'Login' }]);
57
+ expect(init._meta).toMatchObject({ steering: { supported: true } });
58
+ });
59
+
60
+ test('an agent without capabilities.session claims no session methods', () => {
61
+ const init = normalizeInitializeResult({ protocolVersion: 2, info: { name: 'x', version: '1' }, capabilities: {} });
62
+ expect(init.agentCapabilities?.sessionCapabilities).toEqual({});
63
+ });
64
+
65
+ test('a v1 result is passed through untouched', () => {
66
+ const v1 = { protocolVersion: 1, agentCapabilities: { loadSession: true } };
67
+ expect(normalizeInitializeResult(v1)).toBe(v1 as never);
68
+ });
69
+ });
70
+
71
+ describe('normalizeConfigOptions', () => {
72
+ test('renames configId and groupId and keeps nested selects', () => {
73
+ const options = normalizeConfigOptions([
74
+ {
75
+ configId: 'model',
76
+ name: 'Model',
77
+ category: 'model',
78
+ type: 'select',
79
+ currentValue: 'a',
80
+ options: [{ groupId: 'recommended', name: 'Recommended', options: [{ value: 'a', name: 'A' }] }],
81
+ },
82
+ { configId: 'brave', name: 'Brave', type: 'boolean', currentValue: false },
83
+ ]);
84
+ expect(options[0]).toMatchObject({ id: 'model', currentValue: 'a' });
85
+ expect(options[0]?.options?.[0]).toMatchObject({ group: 'recommended' });
86
+ expect(options[1]).toMatchObject({ id: 'brave', type: 'boolean', currentValue: false });
87
+ });
88
+ });
89
+
90
+ describe('normalizeSessionResult', () => {
91
+ test('adopts initial config options and slash commands', () => {
92
+ const result = normalizeSessionResult({
93
+ sessionId: 's1',
94
+ configOptions: [{ configId: 'mode', category: 'mode', type: 'select', currentValue: 'ask' }],
95
+ availableCommands: [{ type: 'command', name: 'test', description: 'Run tests', input: { type: 'text', hint: 'args' } }],
96
+ });
97
+ expect(result.sessionId).toBe('s1');
98
+ expect(result.configOptions?.[0]).toMatchObject({ id: 'mode' });
99
+ expect(result.availableCommands).toEqual([{ name: 'test', description: 'Run tests', inputHint: 'args' }]);
100
+ });
101
+
102
+ test('normalizeCommands drops entries without a name', () => {
103
+ expect(normalizeCommands([{ name: 'x' }, { description: 'nameless' }, null])).toEqual([{ name: 'x' }]);
104
+ });
105
+ });
106
+
107
+ describe('normalizePermissionParams', () => {
108
+ test('a tool_call subject becomes the queue tool call, keeping the title', () => {
109
+ const params = normalizePermissionParams({
110
+ sessionId: 's1',
111
+ title: 'Approve file edit?',
112
+ subject: { type: 'tool_call', toolCall: { toolCallId: 'c1', kind: 'edit' } },
113
+ options: [{ optionId: 'allow', kind: 'allow_once' }],
114
+ });
115
+ expect(params.toolCall).toMatchObject({ toolCallId: 'c1', kind: 'edit', title: 'Approve file edit?' });
116
+ });
117
+
118
+ test('a command subject becomes an exec tool call with the command as rawInput', () => {
119
+ const params = normalizePermissionParams({
120
+ sessionId: 's1',
121
+ title: 'Run the tests?',
122
+ subject: { type: 'command', command: 'cargo test', cwd: '/repo' },
123
+ options: [],
124
+ });
125
+ expect(params.toolCall).toMatchObject({
126
+ title: 'Run the tests?',
127
+ kind: 'execute',
128
+ rawInput: { command: 'cargo test', cwd: '/repo' },
129
+ });
130
+ });
131
+
132
+ test('an absent subject still yields a titled prompt', () => {
133
+ const params = normalizePermissionParams({ sessionId: 's1', title: 'Proceed?', options: [] });
134
+ expect(params.toolCall).toMatchObject({ title: 'Proceed?' });
135
+ });
136
+ });
137
+
138
+ describe('planEntries', () => {
139
+ test('reads an items plan and replaces unknown types with an empty plan', () => {
140
+ expect(planEntries({ plan: { type: 'items', planId: 'p1', entries: [{ content: 'a' }] } })).toEqual([{ content: 'a' }]);
141
+ expect(planEntries({ plan: { type: '_future', planId: 'p2', entries: [{ content: 'a' }] } })).toEqual([]);
142
+ expect(planEntries({})).toEqual([]);
143
+ });
144
+ });