@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,220 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * ACP v2 normalization.
8
+ *
9
+ * Kabmo's internal model is v1-shaped: the frame mapper, the turn machine, the
10
+ * permission queue and every panel read v1 field names. That is deliberate — a
11
+ * second mapper would double every rule — so v2 support is an ADAPTER at the
12
+ * process boundary: `initialize` results, session setup results, config option
13
+ * lists, permission requests and the few update variants that changed shape are
14
+ * translated here, and the rest of the app stays unaware of the version.
15
+ *
16
+ * The prompt lifecycle is the one thing an adapter cannot hide: v2's
17
+ * `session/prompt` response acknowledges insertion, not completion. That is
18
+ * handled by `AcpTurns.completion = 'state'`, not by pretending the response
19
+ * ended the turn.
20
+ */
21
+
22
+ import type {
23
+ AcpAgentCommand,
24
+ AcpConfigOption,
25
+ AcpInitializeResult,
26
+ AcpSessionNewResult,
27
+ } from '@/server/lib/harness/acp/protocol';
28
+
29
+ /** A parsed JSON object, or undefined when the value is not one. */
30
+ export function asRecord(value: unknown): Record<string, unknown> | undefined {
31
+ return value && typeof value === 'object' && !Array.isArray(value)
32
+ ? Object.fromEntries(Object.entries(value))
33
+ : undefined;
34
+ }
35
+
36
+ export function asString(value: unknown): string | undefined {
37
+ return typeof value === 'string' ? value : undefined;
38
+ }
39
+
40
+ /** A support marker is an object in v2; `{}` means supported. */
41
+ function advertised(value: unknown): boolean {
42
+ return value !== undefined && value !== null;
43
+ }
44
+
45
+ /** A v2 initialize result, in the v1 shape the rest of Kabmo reads. */
46
+ export function normalizeInitializeResult(raw: Record<string, unknown>): AcpInitializeResult {
47
+ const version = typeof raw.protocolVersion === 'number' ? raw.protocolVersion : 1;
48
+ if (version !== 2) return raw as unknown as AcpInitializeResult;
49
+
50
+ const capabilities = asRecord(raw.capabilities) ?? {};
51
+ const session = asRecord(capabilities.session);
52
+ const prompt = asRecord(session?.prompt);
53
+ const mcp = asRecord(session?.mcp);
54
+ const info = asRecord(raw.info);
55
+ const meta = {
56
+ ...(asRecord(capabilities._meta) ?? {}),
57
+ ...(asRecord(raw._meta) ?? {}),
58
+ };
59
+
60
+ // `capabilities.session` commits the agent to the whole baseline: list,
61
+ // resume and close have no individual markers in v2.
62
+ const sessionCapabilities: Record<string, unknown> = {};
63
+ if (session !== undefined) {
64
+ sessionCapabilities.list = {};
65
+ sessionCapabilities.resume = {};
66
+ sessionCapabilities.close = {};
67
+ if (advertised(session.delete)) sessionCapabilities.delete = {};
68
+ if (advertised(session.additionalDirectories)) sessionCapabilities.additionalDirectories = {};
69
+ if (advertised(session.fork)) sessionCapabilities.fork = {};
70
+ }
71
+
72
+ return {
73
+ protocolVersion: 2,
74
+ ...(info?.name !== undefined
75
+ ? {
76
+ agentInfo: {
77
+ name: asString(info.name),
78
+ ...(asString(info.title) ? { title: asString(info.title) } : {}),
79
+ ...(asString(info.version) ? { version: asString(info.version) } : {}),
80
+ },
81
+ }
82
+ : {}),
83
+ agentCapabilities: {
84
+ loadSession: false,
85
+ promptCapabilities: {
86
+ image: advertised(prompt?.image),
87
+ audio: advertised(prompt?.audio),
88
+ embeddedContext: advertised(prompt?.embeddedContext),
89
+ },
90
+ mcpCapabilities: { http: advertised(mcp?.http), sse: false },
91
+ sessionCapabilities,
92
+ },
93
+ authMethods: normalizeAuthMethods(raw.authMethods),
94
+ ...(Object.keys(meta).length > 0 ? { _meta: meta } : {}),
95
+ };
96
+ }
97
+
98
+ /** v2 auth descriptors use `methodId`; internal consumers use `id`. */
99
+ export function normalizeAuthMethods(value: unknown): AcpInitializeResult['authMethods'] {
100
+ if (!Array.isArray(value)) return [];
101
+ return value.flatMap((entry) => {
102
+ const method = asRecord(entry);
103
+ const id = asString(method?.methodId) ?? asString(method?.id);
104
+ if (!id) return [];
105
+ return [{
106
+ id,
107
+ name: asString(method?.name) ?? id,
108
+ ...(asString(method?.description) ? { description: asString(method?.description) } : {}),
109
+ ...(asString(method?.type) ? { type: asString(method?.type) } : {}),
110
+ }];
111
+ });
112
+ }
113
+
114
+ /** A v2 config option list, with `configId`/`groupId` renamed to v1 keys. */
115
+ export function normalizeConfigOptions(value: unknown): AcpConfigOption[] {
116
+ if (!Array.isArray(value)) return [];
117
+ return value.flatMap((entry) => {
118
+ const option = asRecord(entry);
119
+ const id = asString(option?.configId) ?? asString(option?.id);
120
+ if (!option || !id) return [];
121
+ return [{
122
+ ...option,
123
+ id,
124
+ ...(Array.isArray(option.options) ? { options: normalizeSelectEntries(option.options) } : {}),
125
+ } as AcpConfigOption];
126
+ });
127
+ }
128
+
129
+ function normalizeSelectEntries(value: readonly unknown[]): NonNullable<AcpConfigOption['options']> {
130
+ const out: NonNullable<AcpConfigOption['options']> = [];
131
+ for (const entry of value) {
132
+ const item = asRecord(entry);
133
+ if (!item) continue;
134
+ const groupId = asString(item.groupId) ?? asString(item.group);
135
+ if (groupId && Array.isArray(item.options)) {
136
+ out.push({
137
+ group: groupId,
138
+ ...(asString(item.name) ? { name: asString(item.name) } : {}),
139
+ options: item.options.flatMap((nested) => {
140
+ const select = asRecord(nested);
141
+ const choice = asString(select?.value);
142
+ return choice ? [{ value: choice, ...(asString(select?.name) ? { name: asString(select?.name) } : {}) }] : [];
143
+ }),
144
+ });
145
+ continue;
146
+ }
147
+ const choice = asString(item.value);
148
+ if (choice) {
149
+ out.push({
150
+ value: choice,
151
+ ...(asString(item.name) ? { name: asString(item.name) } : {}),
152
+ ...(asString(item.description) ? { description: asString(item.description) } : {}),
153
+ });
154
+ }
155
+ }
156
+ return out;
157
+ }
158
+
159
+ /** A v2 slash-command list, in the shape `parseAgentCommands` produces. */
160
+ export function normalizeCommands(value: unknown): AcpAgentCommand[] {
161
+ if (!Array.isArray(value)) return [];
162
+ return value.flatMap((entry) => {
163
+ const command = asRecord(entry);
164
+ const name = asString(command?.name);
165
+ if (!name) return [];
166
+ const input = asRecord(command?.input);
167
+ return [{
168
+ name,
169
+ ...(asString(command?.description) ? { description: asString(command?.description) } : {}),
170
+ ...(asString(input?.hint) ? { inputHint: asString(input?.hint) } : {}),
171
+ }];
172
+ });
173
+ }
174
+
175
+ /** A v2 `session/new|resume` result, normalized for the handshake. */
176
+ export function normalizeSessionResult(raw: Record<string, unknown>): AcpSessionNewResult {
177
+ return {
178
+ sessionId: asString(raw.sessionId) ?? '',
179
+ ...(Array.isArray(raw.configOptions) ? { configOptions: normalizeConfigOptions(raw.configOptions) } : {}),
180
+ ...(Array.isArray(raw.availableCommands) ? { availableCommands: normalizeCommands(raw.availableCommands) } : {}),
181
+ };
182
+ }
183
+
184
+ /**
185
+ * A v2 `session/request_permission`, in the shape the approval queue expects.
186
+ *
187
+ * v2 carries `title`, an optional `subject` (a tool call or a command) and the
188
+ * options. The queue keys on the tool call, so a command subject becomes an
189
+ * exec tool call and an absent subject becomes a titled generic one.
190
+ */
191
+ export function normalizePermissionParams(params: Record<string, unknown>): Record<string, unknown> {
192
+ const subject = asRecord(params.subject);
193
+ let toolCall: Record<string, unknown> | undefined;
194
+ if (subject?.type === 'tool_call') {
195
+ toolCall = asRecord(subject.toolCall);
196
+ } else if (subject?.type === 'command') {
197
+ toolCall = {
198
+ kind: 'execute',
199
+ rawInput: {
200
+ ...(asString(subject.command) ? { command: asString(subject.command) } : {}),
201
+ ...(asString(subject.cwd) ? { cwd: asString(subject.cwd) } : {}),
202
+ },
203
+ };
204
+ }
205
+ const title = asString(params.title) ?? 'Approve this action';
206
+ return {
207
+ ...params,
208
+ toolCall: {
209
+ ...(toolCall ?? {}),
210
+ title: asString(toolCall?.title) ?? title,
211
+ },
212
+ };
213
+ }
214
+
215
+ /** The entries a v2 `plan_update` replaces for its plan, or [] for an unknown type. */
216
+ export function planEntries(update: Record<string, unknown>): unknown[] {
217
+ const plan = asRecord(update.plan);
218
+ if (!plan || plan.type !== 'items' || !Array.isArray(plan.entries)) return [];
219
+ return plan.entries;
220
+ }
@@ -17,6 +17,7 @@
17
17
  */
18
18
 
19
19
  import type { AcpSessionInfo, AcpSessionNewResult } from '@/server/lib/harness/acp/protocol';
20
+ import { normalizeConfigOptions, normalizeSessionResult } from '@/server/lib/harness/acp/v2';
20
21
 
21
22
  /** One request/response round trip against an ACP agent. Implemented by
22
23
  * `AcpProcess.call`; a test supplies its own. */
@@ -24,16 +25,32 @@ export type AcpInvoke = <T>(method: string, params: unknown, timeoutMs: number)
24
25
  /** Fire-and-forget frame (notifications only). */
25
26
  export type AcpNotify = (method: string, params: unknown) => void;
26
27
 
27
- export async function newSession(invoke: AcpInvoke, cwd: string, timeoutMs = 120_000): Promise<AcpSessionNewResult> {
28
- return invoke<AcpSessionNewResult>('session/new', { cwd, mcpServers: [] }, timeoutMs);
28
+ /** The negotiated major, so a verb can shape its params and normalize its answer. */
29
+ export type AcpDialect = 1 | 2;
30
+
31
+ export async function newSession(
32
+ invoke: AcpInvoke,
33
+ cwd: string,
34
+ timeoutMs = 120_000,
35
+ dialect: AcpDialect = 1,
36
+ ): Promise<AcpSessionNewResult> {
37
+ const result = await invoke<Record<string, unknown>>('session/new', { cwd, mcpServers: [] }, timeoutMs);
38
+ return dialect === 2 ? normalizeSessionResult(result) : (result as unknown as AcpSessionNewResult);
29
39
  }
30
40
 
31
41
  export async function loadSession(invoke: AcpInvoke, sessionId: string, cwd: string, timeoutMs = 120_000): Promise<unknown> {
32
42
  return invoke('session/load', { sessionId, cwd, mcpServers: [] }, timeoutMs);
33
43
  }
34
44
 
35
- export async function resumeSession(invoke: AcpInvoke, sessionId: string, cwd: string, timeoutMs = 120_000): Promise<unknown> {
36
- return invoke('session/resume', { sessionId, cwd, mcpServers: [] }, timeoutMs);
45
+ export async function resumeSession(
46
+ invoke: AcpInvoke,
47
+ sessionId: string,
48
+ cwd: string,
49
+ timeoutMs = 120_000,
50
+ dialect: AcpDialect = 1,
51
+ ): Promise<unknown> {
52
+ const result = await invoke<Record<string, unknown>>('session/resume', { sessionId, cwd, mcpServers: [] }, timeoutMs);
53
+ return dialect === 2 ? normalizeSessionResult(result) : result;
37
54
  }
38
55
 
39
56
  export async function forkSession(
@@ -63,7 +80,7 @@ export async function prompt(
63
80
  sessionId: string,
64
81
  blocks: unknown[],
65
82
  timeoutMs = 0,
66
- ): Promise<{ stopReason?: string; usage?: unknown }> {
83
+ ): Promise<{ stopReason?: string; messageId?: string; usage?: unknown }> {
67
84
  return invoke('session/prompt', { sessionId, prompt: blocks }, timeoutMs);
68
85
  }
69
86
 
@@ -77,8 +94,15 @@ export async function setConfigOption(
77
94
  configId: string,
78
95
  value: string | boolean,
79
96
  timeoutMs = 30_000,
97
+ dialect: AcpDialect = 1,
80
98
  ): Promise<unknown> {
81
- return invoke('session/set_config_option', { sessionId, configId, value }, timeoutMs);
99
+ // v2 requires the value's shape: `id` for select options, `boolean` otherwise.
100
+ const params = dialect === 2
101
+ ? { sessionId, configId, type: typeof value === 'boolean' ? 'boolean' : 'id', value }
102
+ : { sessionId, configId, value };
103
+ const result = await invoke<Record<string, unknown>>('session/set_config_option', params, timeoutMs);
104
+ if (dialect !== 2) return result;
105
+ return { ...result, ...(Array.isArray(result.configOptions) ? { configOptions: normalizeConfigOptions(result.configOptions) } : {}) };
82
106
  }
83
107
 
84
108
  /** omp's steering extension (advertised as `_meta.steering.supported`). */
@@ -95,3 +119,19 @@ export async function steer(
95
119
  export async function closeSession(invoke: AcpInvoke, sessionId: string, timeoutMs = 30_000): Promise<unknown> {
96
120
  return invoke('session/close', { sessionId }, timeoutMs);
97
121
  }
122
+
123
+ /** The older Session Modes API; `configOptions` supersedes it but agents still
124
+ * publish one or the other. */
125
+ export async function setMode(
126
+ invoke: AcpInvoke,
127
+ sessionId: string,
128
+ modeId: string,
129
+ timeoutMs = 30_000,
130
+ ): Promise<unknown> {
131
+ return invoke('session/set_mode', { sessionId, modeId }, timeoutMs);
132
+ }
133
+
134
+ /** Remove one session from the agent's own history (`sessionCapabilities.delete`). */
135
+ export async function deleteSession(invoke: AcpInvoke, sessionId: string, timeoutMs = 30_000): Promise<unknown> {
136
+ return invoke('session/delete', { sessionId }, timeoutMs);
137
+ }
@@ -83,6 +83,31 @@ describe('capabilitiesFrom', () => {
83
83
  });
84
84
  });
85
85
 
86
+ test('a null session capability is ABSENT, not support', () => {
87
+ const caps = capabilitiesFrom(
88
+ { protocolVersion: 1, agentCapabilities: { sessionCapabilities: { resume: null, list: {}, close: null } } },
89
+ undefined,
90
+ { usage: false, plan: false },
91
+ );
92
+ expect(caps.resumeSession).toBe(false);
93
+ expect(caps.closeSession).toBe(false);
94
+ expect(caps.listSessions).toBe(true);
95
+ });
96
+
97
+ test('an agent with only the legacy modes API still publishes a mode ladder', () => {
98
+ const caps = capabilitiesFrom(
99
+ { protocolVersion: 1 },
100
+ undefined,
101
+ { usage: false, plan: false },
102
+ {
103
+ currentModeId: 'code',
104
+ availableModes: [{ id: 'code', name: 'Code' }, { id: 'plan', name: 'Plan' }],
105
+ },
106
+ );
107
+ expect(caps.configMode).toBe(2);
108
+ expect(caps.modeValues).toEqual(['code', 'plan']);
109
+ });
110
+
86
111
  test('usage and plan are OBSERVED, never assumed', () => {
87
112
  const caps = capabilitiesFrom(ompInit, ompConfig, { usage: false, plan: true });
88
113
  expect(caps.hasUsage).toBe(false);
@@ -24,7 +24,7 @@
24
24
  import { AcpProcess } from '@/server/lib/harness/acp/client';
25
25
  import { withGatewayCompatibility } from '@/server/lib/harness/acp/gateway-env';
26
26
  import { newSessionAfterActivation } from '@/server/lib/harness/acp/activation';
27
- import type { AcpConfigOption, AcpInitializeResult } from '@/server/lib/harness/acp/protocol';
27
+ import type { AcpConfigOption, AcpInitializeResult, AcpSessionModeState } from '@/server/lib/harness/acp/protocol';
28
28
  import { acpOptionValues } from '@/server/lib/harness/acp/protocol';
29
29
  import { UNPROBED_CAPABILITIES, type HarnessCapabilities, type HarnessProbe } from '@/server/lib/harness/capabilities';
30
30
  import { HARNESS_LAUNCH, type HarnessLaunch } from '@/server/lib/harness/launch-table';
@@ -59,12 +59,19 @@ export function capabilitiesFrom(
59
59
  init: AcpInitializeResult,
60
60
  configOptions: AcpConfigOption[] | undefined,
61
61
  observed: { usage: boolean; plan: boolean },
62
+ modes?: AcpSessionModeState | null,
62
63
  ): HarnessCapabilities {
63
64
  const caps = init.agentCapabilities ?? {};
64
65
  const sessionCaps = caps.sessionCapabilities ?? {};
65
66
  const model = configByCategory(configOptions ?? [], 'model');
66
67
  const thinking = configByCategory(configOptions ?? [], 'thought_level');
67
68
  const mode = configByCategory(configOptions ?? [], 'mode');
69
+ // Config options supersede the older Session Modes API, but an agent may
70
+ // publish only `modes`. A client that understands `configOptions` should
71
+ // ignore `modes` when a selector exists; otherwise the ladder is this list.
72
+ const modeValues = mode
73
+ ? acpOptionValues(mode)
74
+ : (modes?.availableModes ?? []).map((entry) => entry.id);
68
75
  // omp advertises steering at the RESULT root (`_meta.steering`), a sibling of
69
76
  // `agentCapabilities` — measured on 18.16.0. Reading it from inside
70
77
  // `agentCapabilities` found nothing, so the capability record said "no
@@ -73,18 +80,23 @@ export function capabilitiesFrom(
73
80
  const steeringSupported = Boolean(
74
81
  steering && typeof steering === 'object' && 'supported' in steering && steering.supported === true,
75
82
  );
83
+ // A session capability is advertised by PRESENCE, and `null` is the spec's
84
+ // other way of saying absent — `'key' in caps` would read `{resume: null}` as
85
+ // support and then call a method the agent does not implement.
86
+ const advertises = (key: string): boolean =>
87
+ sessionCaps[key] !== undefined && sessionCaps[key] !== null;
76
88
  return {
77
89
  ...UNPROBED_CAPABILITIES,
78
90
  configModel: model ? acpOptionValues(model).length : 0,
79
91
  configThinking: thinking ? acpOptionValues(thinking).length : 0,
80
- configMode: mode ? acpOptionValues(mode).length : 0,
81
- modeValues: mode ? acpOptionValues(mode) : [],
92
+ configMode: modeValues.length,
93
+ modeValues,
82
94
  loadSession: caps.loadSession === true,
83
- listSessions: 'list' in sessionCaps,
84
- forkSession: 'fork' in sessionCaps,
85
- deleteSession: 'delete' in sessionCaps,
86
- resumeSession: 'resume' in sessionCaps,
87
- closeSession: 'close' in sessionCaps,
95
+ listSessions: advertises('list'),
96
+ forkSession: advertises('fork'),
97
+ deleteSession: advertises('delete'),
98
+ resumeSession: advertises('resume'),
99
+ closeSession: advertises('close'),
88
100
  hasUsage: observed.usage,
89
101
  hasPlan: observed.plan,
90
102
  steerMode: steeringSupported ? 'steer' : null,
@@ -160,7 +172,7 @@ export async function probeHarness(
160
172
  if (!update || typeof update !== 'object') return;
161
173
  if (!('sessionUpdate' in update)) return;
162
174
  if (update.sessionUpdate === 'usage_update') observed.usage = true;
163
- if (update.sessionUpdate === 'plan') observed.plan = true;
175
+ if (update.sessionUpdate === 'plan' || update.sessionUpdate === 'plan_update') observed.plan = true;
164
176
  },
165
177
  });
166
178
  proc = agentProcess;
@@ -52,6 +52,9 @@ export interface HarnessSession extends HarnessEventSource, HarnessSessionState
52
52
  resolvePendingUiDialog(id: string): void;
53
53
  destroy(): void;
54
54
  destroyAndWait(): Promise<void>;
55
+ /** Delete the harness's own session record, when the agent advertises one
56
+ * (`sessionCapabilities.delete`). Best-effort: the local rows are the caller's. */
57
+ deleteAgentSession?(): Promise<void>;
55
58
  onDestroy(callback: () => void): void;
56
59
  }
57
60
 
@@ -23,6 +23,7 @@ import {
23
23
  writeUpdateJob,
24
24
  UPDATE_START_GRACE_MS,
25
25
  } from '@/server/lib/harness/update-job-store';
26
+ import { jobQueued, jobRunning } from '@/shared/lib/harness/update-job';
26
27
  import { getHarnessUpdateStatusPath } from '@/server/lib/lifecycle/paths';
27
28
  import type { HarnessUpdateJob } from '@/shared/types/harness-update';
28
29
 
@@ -41,12 +42,16 @@ afterEach(() => {
41
42
  rmSync(dir, { recursive: true, force: true });
42
43
  });
43
44
 
45
+ /** The one record this suite owns: claude's own file. */
46
+ const statusPath = (): string => getHarnessUpdateStatusPath('claude');
47
+
44
48
  function job(overrides: Partial<HarnessUpdateJob> = {}): HarnessUpdateJob {
45
49
  return {
46
50
  harness: 'claude',
47
51
  label: 'claude',
48
52
  startedAt: Date.now(),
49
53
  finishedAt: null,
54
+ queuedAt: null,
50
55
  pid: process.pid,
51
56
  steps: [{ part: 'adapter', command: 'npm install -g x', argv: ['npm', 'install', '-g', 'x'], state: 'running', code: null }],
52
57
  output: '',
@@ -60,8 +65,8 @@ function job(overrides: Partial<HarnessUpdateJob> = {}): HarnessUpdateJob {
60
65
 
61
66
  describe('the status record', () => {
62
67
  test('round-trips, and leaves no temp file behind', async () => {
63
- await writeUpdateJob(job({ output: 'installing' }));
64
- const read = await readUpdateJob();
68
+ await writeUpdateJob(job({ output: 'installing' }), statusPath());
69
+ const read = await readUpdateJob(statusPath());
65
70
  expect(read?.harness).toBe('claude');
66
71
  expect(read?.output).toBe('installing');
67
72
  // `tmp` + `rename`, so a reader never sees half a record and the temp name
@@ -71,14 +76,14 @@ describe('the status record', () => {
71
76
  });
72
77
 
73
78
  test('an absent record is null, not a throw', async () => {
74
- expect(await readUpdateJob()).toBeNull();
79
+ expect(await readUpdateJob(statusPath())).toBeNull();
75
80
  });
76
81
 
77
82
  test('a foreign JSON file is not a job', async () => {
78
83
  // A hand-written or half-written file must read as "nothing ran", not as a
79
84
  // record whose missing fields crash the dialog.
80
- writeFileSync(getHarnessUpdateStatusPath(), JSON.stringify({ hello: 'world' }));
81
- expect(await readUpdateJob()).toBeNull();
85
+ writeFileSync(statusPath(), JSON.stringify({ hello: 'world' }));
86
+ expect(await readUpdateJob(statusPath())).toBeNull();
82
87
  });
83
88
  });
84
89
 
@@ -93,29 +98,49 @@ describe('telling a live run from a dead one', () => {
93
98
 
94
99
  test('a run whose worker is gone is settled by the next read', async () => {
95
100
  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());
101
+ await writeUpdateJob(dead, statusPath());
102
+ const settled = await settleDeadJob(await readUpdateJob(statusPath()), statusPath());
98
103
  expect(settled?.finishedAt).not.toBeNull();
99
104
  expect(settled?.ok).toBe(false);
100
105
  expect(settled?.message).toContain('without reporting a result');
101
106
  expect(settled?.steps[0].state).toBe('failed');
102
107
  // Settled once, and the settle itself is on disk for the next reader.
103
- expect((await readUpdateJob())?.finishedAt).not.toBeNull();
108
+ expect((await readUpdateJob(statusPath()))?.finishedAt).not.toBeNull();
104
109
  });
105
110
 
106
111
  test('the start grace covers the pid handshake', async () => {
107
112
  // The record is written before the worker has a pid; reading that as dead
108
113
  // would report failure over a run that is about to start.
109
114
  const starting = job({ pid: null, startedAt: Date.now() });
110
- await writeUpdateJob(starting);
111
- expect(await settleDeadJob(await readUpdateJob())).toEqual(starting);
115
+ await writeUpdateJob(starting, statusPath());
116
+ expect(await settleDeadJob(await readUpdateJob(statusPath()), statusPath())).toEqual(starting);
112
117
  expect(jobInFlight(starting)).toBe(true);
113
118
  });
114
119
 
115
120
  test('a finished run is left exactly as the worker wrote it', async () => {
116
121
  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);
122
+ await writeUpdateJob(done, statusPath());
123
+ expect(await settleDeadJob(await readUpdateJob(statusPath()), statusPath())).toEqual(done);
124
+ });
125
+
126
+ test('a QUEUED record is neither in flight nor dead', async () => {
127
+ // Two presses are a queue: the second record exists with no pid on purpose,
128
+ // and reading that as a worker that died would fail a run that never started.
129
+ const waiting = job({ pid: null, queuedAt: Date.now() - UPDATE_START_GRACE_MS * 2 });
130
+ await writeUpdateJob(waiting, statusPath());
131
+ expect(jobQueued(waiting)).toBe(true);
132
+ expect(jobRunning(waiting)).toBe(false);
133
+ expect(jobInFlight(waiting)).toBe(false);
134
+ expect(await settleDeadJob(await readUpdateJob(statusPath()), statusPath())).toEqual(waiting);
135
+ });
136
+
137
+ test('a queued record starts reading as a RUN when its worker takes over', async () => {
138
+ const started = job({ pid: process.pid, queuedAt: Date.now() });
139
+ await writeUpdateJob(started, statusPath());
140
+ // The pid, not the stamp, is what makes it a run: the worker writes both.
141
+ expect(jobQueued(started)).toBe(false);
142
+ expect(jobRunning(started)).toBe(true);
143
+ expect(jobInFlight(started)).toBe(true);
119
144
  });
120
145
 
121
146
  test('an impossible pid is not alive', () => {
@@ -5,7 +5,7 @@
5
5
 
6
6
  /**
7
7
  * The harness update record on disk: read it, write it atomically, and tell a
8
- * live run from a dead one.
8
+ * live run from a queued one and from a dead one.
9
9
  *
10
10
  * Kept apart from `update-job.server.ts` because the DETACHED WORKER writes the
11
11
  * same record (`update-worker.ts`) and must not import the server's database and
@@ -14,13 +14,15 @@
14
14
  * **A run outlives the request that started it.** The POST answers in
15
15
  * milliseconds while the install keeps going, so the state cannot live in a
16
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.
17
+ * have to read the same answer. It is one JSON file PER HARNESS, replaced
18
+ * atomically (`tmp` + `rename`), which is why a reader never sees half a record.
19
+ *
20
+ * The path is always passed in: the server derives it from the harness id
21
+ * (`getHarnessUpdateStatusPath`), and the worker uses the one its spec names.
19
22
  */
20
23
 
21
24
  import fs from 'node:fs';
22
- import { getHarnessUpdateStatusPath } from '@/server/lib/lifecycle/paths';
23
- import { isHarnessUpdateJob } from '@/shared/lib/harness/update-job';
25
+ import { isHarnessUpdateJob, jobQueued } from '@/shared/lib/harness/update-job';
24
26
  import type { HarnessUpdateJob } from '@/shared/types/harness-update';
25
27
 
26
28
  /**
@@ -34,13 +36,14 @@ import type { HarnessUpdateJob } from '@/shared/types/harness-update';
34
36
  */
35
37
  export const UPDATE_START_GRACE_MS = 15_000;
36
38
 
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> {
39
+ /** The record at `path`, or null when none was ever written (or it is
40
+ * unreadable). `queuedAt` is normalized, because a record written before the
41
+ * queue existed has no such field. */
42
+ export async function readUpdateJob(path: string): Promise<HarnessUpdateJob | null> {
41
43
  try {
42
44
  const parsed = (await Bun.file(path).json()) as unknown;
43
- return isHarnessUpdateJob(parsed) ? parsed : null;
45
+ if (!isHarnessUpdateJob(parsed)) return null;
46
+ return { ...parsed, queuedAt: typeof parsed.queuedAt === 'number' ? parsed.queuedAt : null };
44
47
  } catch {
45
48
  // Absent (never run) and corrupt (a half-written record from an old build)
46
49
  // are the same answer: there is nothing to report.
@@ -49,7 +52,7 @@ export async function readUpdateJob(path = getHarnessUpdateStatusPath()): Promis
49
52
  }
50
53
 
51
54
  /** Replace the record atomically. A reader sees the previous one or this one. */
52
- export async function writeUpdateJob(job: HarnessUpdateJob, path = getHarnessUpdateStatusPath()): Promise<void> {
55
+ export async function writeUpdateJob(job: HarnessUpdateJob, path: string): Promise<void> {
53
56
  const target = path;
54
57
  const temp = `${target}.${process.pid}.tmp`;
55
58
  await Bun.write(temp, JSON.stringify(job, null, 2));
@@ -73,9 +76,10 @@ export function pidAlive(pid: number | null): boolean {
73
76
  * A known-live pid settles it. Without one the record is trusted only inside the
74
77
  * start grace window; after that an absent worker means the run died without
75
78
  * writing a result, and the caller reports that instead of polling forever.
79
+ * A QUEUED record is never in flight: it has no worker yet, by design.
76
80
  */
77
81
  export function jobInFlight(job: HarnessUpdateJob | null, now = Date.now()): boolean {
78
- if (!job || job.finishedAt !== null) return false;
82
+ if (!job || job.finishedAt !== null || jobQueued(job)) return false;
79
83
  if (pidAlive(job.pid)) return true;
80
84
  return now - job.startedAt < UPDATE_START_GRACE_MS;
81
85
  }
@@ -85,16 +89,18 @@ export function jobInFlight(job: HarnessUpdateJob | null, now = Date.now()): boo
85
89
  *
86
90
  * `finishedAt` is what every reader keys on, so settling here is what stops the
87
91
  * dialog from spinning forever; the message says the install itself may have
88
- * completed, because a killed reporter is not proof the commands failed.
92
+ * completed, because a killed reporter is not proof the commands failed. A
93
+ * queued record is left alone — nothing was ever spawned for it.
89
94
  */
90
95
  export async function settleDeadJob(
91
96
  job: HarnessUpdateJob | null,
92
- path = getHarnessUpdateStatusPath(),
97
+ path: string,
93
98
  ): Promise<HarnessUpdateJob | null> {
94
99
  // A record that already has a result is history, not a candidate: the worker
95
100
  // 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;
101
+ // reporting" failure. A queued record is a candidate for the QUEUE, not for
102
+ // this.
103
+ if (!job || job.finishedAt !== null || jobQueued(job) || jobInFlight(job)) return job;
98
104
  const settled: HarnessUpdateJob = {
99
105
  ...job,
100
106
  finishedAt: Date.now(),