@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
@@ -18,6 +18,18 @@
18
18
 
19
19
  import type { AcpId, AcpResponse } from '@/server/lib/harness/acp/protocol';
20
20
 
21
+ /** A JSON-RPC error answer, with the code the spec defines for it. */
22
+ export class AcpRequestError extends Error {
23
+ constructor(
24
+ message: string,
25
+ readonly code: number,
26
+ readonly data?: unknown,
27
+ ) {
28
+ super(message);
29
+ this.name = 'AcpRequestError';
30
+ }
31
+ }
32
+
21
33
  export interface Pending {
22
34
  resolve: (value: unknown) => void;
23
35
  reject: (error: Error) => void;
@@ -60,8 +72,10 @@ export class PendingCalls {
60
72
  this.map.delete(response.id);
61
73
  clearTimeout(entry.timer);
62
74
  if (response.error) {
63
- entry.reject(new Error(
75
+ entry.reject(new AcpRequestError(
64
76
  `${response.error.message}${response.error.data ? `: ${JSON.stringify(response.error.data)}` : ''}`,
77
+ response.error.code,
78
+ response.error.data,
65
79
  ));
66
80
  return true;
67
81
  }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The client's `initialize` advertisement and version negotiation.
8
+ *
9
+ * Both are promises made to the agent: the capability object says which
10
+ * agent→client calls this client will answer, and the answer to an unsupported
11
+ * protocol major has to be a refusal rather than a v2 frame parsed as v1.
12
+ */
13
+
14
+ import { describe, expect, test } from 'bun:test';
15
+ import {
16
+ ACP_PROTOCOL_VERSION,
17
+ KABMO_CLIENT_CAPABILITIES,
18
+ assertProtocolVersion,
19
+ } from '@/server/lib/harness/acp/client-capabilities';
20
+
21
+ describe('client capabilities', () => {
22
+ test('advertises the fs methods the client actually implements', () => {
23
+ expect(KABMO_CLIENT_CAPABILITIES.fs).toEqual({ readTextFile: true, writeTextFile: true });
24
+ });
25
+
26
+ test('advertises notices, which the frame mapper already renders', () => {
27
+ expect(KABMO_CLIENT_CAPABILITIES.session.notices).toEqual({});
28
+ });
29
+
30
+ test('does not advertise surfaces with no bridge', () => {
31
+ const advertised = KABMO_CLIENT_CAPABILITIES as Record<string, unknown>;
32
+ expect(advertised.terminal).toBeUndefined();
33
+ expect(advertised.elicitation).toBeUndefined();
34
+ });
35
+ });
36
+
37
+ describe('protocol version negotiation', () => {
38
+ test('sends v2 as its latest version', () => {
39
+ expect(ACP_PROTOCOL_VERSION).toBe(2);
40
+ });
41
+
42
+ test('accepts both majors it implements', () => {
43
+ expect(() => assertProtocolVersion({ protocolVersion: 1 })).not.toThrow();
44
+ expect(() => assertProtocolVersion({ protocolVersion: 2 })).not.toThrow();
45
+ });
46
+
47
+ test('refuses a major it cannot speak, naming the agent and both versions', () => {
48
+ expect(() => assertProtocolVersion({ protocolVersion: 3, agentInfo: { title: 'Acme' } }))
49
+ .toThrow('Acme speaks ACP v3; Kabmo supports v1 and v2');
50
+ });
51
+
52
+ test('refuses an answer that reports no version at all', () => {
53
+ expect(() => assertProtocolVersion({})).toThrow('speaks ACP vundefined');
54
+ });
55
+ });
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * What Kabmo advertises as a **v1** ACP client at `initialize`.
8
+ *
9
+ * v2 removed the client fs and terminal execution APIs, so a v2 connection
10
+ * advertises `capabilities: {}` instead; the hybrid request in
11
+ * `client-initialize.ts` carries both field sets so a v1 peer still sees this
12
+ * object while a v2 peer ignores it as an unknown field.
13
+ *
14
+ * Every entry here is a promise the client answers itself, so the list is
15
+ * narrower than the protocol: an advertised capability the client cannot serve
16
+ * makes the agent park a turn on a call nobody answers (the failure mode
17
+ * `session-requests.ts` exists to prevent).
18
+ *
19
+ * - **fs** — `client-fs.ts` implements both methods against the session's
20
+ * workspace, so an agent that reads or writes through the client reaches the
21
+ * same files the user's editor is looking at.
22
+ * - **session.notices** — `AcpFrameMapper` already renders `notice` updates as
23
+ * notices; without the advertisement a spec-compliant agent had to model them
24
+ * as conversation text instead.
25
+ *
26
+ * Deliberately absent, each for a measured reason:
27
+ *
28
+ * - `terminal` — this client has no bridge that surfaces an ACP terminal's
29
+ * output in the timeline, and advertising it would route an agent's shell
30
+ * work through a terminal the user cannot see.
31
+ * - `elicitation` — no form/URL dialog exists yet; advertising it would make
32
+ * the agent block on an `elicitation/create` nobody draws.
33
+ * - `auth.terminal` — Kabmo does not reproduce the agent's launch line in an
34
+ * interactive terminal for login.
35
+ * - `session.configOptions.boolean` — the selector UI is select-only.
36
+ * - `session.compaction` — compaction updates have no renderer.
37
+ */
38
+ export const KABMO_CLIENT_CAPABILITIES = {
39
+ fs: { readTextFile: true, writeTextFile: true },
40
+ session: { notices: {} },
41
+ } as const;
42
+
43
+ /** The latest protocol major this client sends; it also speaks v1. */
44
+ export const ACP_PROTOCOL_VERSION = 2;
45
+
46
+ /** Every major this client implements. */
47
+ export const ACP_SUPPORTED_VERSIONS = [1, 2] as const;
48
+
49
+ /**
50
+ * Refuse an `initialize` answer this client cannot speak.
51
+ *
52
+ * Kabmo implements v1 and v2 side by side; a v1-only agent answers 1 and a v2
53
+ * agent answers 2. Anything else is a connection this client cannot parse.
54
+ */
55
+ export function assertProtocolVersion(result: { protocolVersion?: unknown; agentInfo?: { name?: string; title?: string } }): void {
56
+ if (result.protocolVersion === 1 || result.protocolVersion === 2) return;
57
+ const agent = result.agentInfo?.title ?? result.agentInfo?.name ?? 'The agent';
58
+ throw new Error(
59
+ `${agent} speaks ACP v${String(result.protocolVersion)}; Kabmo supports v1 and v2`,
60
+ );
61
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The ACP client's file surface.
8
+ *
9
+ * The cases that matter are the REFUSALS: an agent asking for a path outside the
10
+ * session's workspace must get `-32602`, not a read of the host's filesystem.
11
+ * The line window is pinned because ACP numbers lines from 1.
12
+ */
13
+
14
+ import { afterEach, describe, expect, test } from 'bun:test';
15
+ import { mkdtemp, rm, symlink } from 'node:fs/promises';
16
+ import { tmpdir } from 'node:os';
17
+ import { join } from 'node:path';
18
+ import { handleAcpFsRequest, isAcpFsMethod, type AcpFsHost } from '@/server/lib/harness/acp/client-fs';
19
+ import { testPosix } from '@/test-support/platform';
20
+ import { ACP_ERROR } from '@/server/lib/harness/acp/protocol';
21
+
22
+ const scratch: string[] = [];
23
+
24
+ async function workspace(): Promise<AcpFsHost> {
25
+ const cwd = await mkdtemp(join(tmpdir(), 'kabmo-acp-fs-'));
26
+ scratch.push(cwd);
27
+ return { cwd, sessionId: 's1' };
28
+ }
29
+
30
+ afterEach(async () => {
31
+ await Promise.all(scratch.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
32
+ });
33
+
34
+ describe('fs capability methods', () => {
35
+ test('recognises exactly the two methods it serves', () => {
36
+ expect(isAcpFsMethod('fs/read_text_file')).toBe(true);
37
+ expect(isAcpFsMethod('fs/write_text_file')).toBe(true);
38
+ expect(isAcpFsMethod('terminal/create')).toBe(false);
39
+ });
40
+ });
41
+
42
+ describe('fs/read_text_file', () => {
43
+ test('answers the whole file when no window is given', async () => {
44
+ const host = await workspace();
45
+ await Bun.write(join(host.cwd, 'a.txt'), 'one\ntwo\n');
46
+ const answer = await handleAcpFsRequest(host, 'fs/read_text_file', { sessionId: 's1', path: join(host.cwd, 'a.txt') });
47
+ expect(answer).toEqual({ answered: true, result: { content: 'one\ntwo\n' } });
48
+ });
49
+
50
+ test('a line window is 1-based and counts limit lines', async () => {
51
+ const host = await workspace();
52
+ const file = join(host.cwd, 'a.txt');
53
+ await Bun.write(file, 'one\ntwo\nthree\nfour');
54
+ const second = await handleAcpFsRequest(host, 'fs/read_text_file', { sessionId: 's1', path: file, line: 2, limit: 2 });
55
+ expect(second).toEqual({ answered: true, result: { content: 'two\nthree' } });
56
+ const tail = await handleAcpFsRequest(host, 'fs/read_text_file', { sessionId: 's1', path: file, line: 3 });
57
+ expect(tail).toEqual({ answered: true, result: { content: 'three\nfour' } });
58
+ const past = await handleAcpFsRequest(host, 'fs/read_text_file', { sessionId: 's1', path: file, line: 99 });
59
+ expect(past).toEqual({ answered: true, result: { content: '' } });
60
+ });
61
+
62
+ test('a missing file is -32002, the resource-not-found code', async () => {
63
+ const host = await workspace();
64
+ const answer = await handleAcpFsRequest(host, 'fs/read_text_file', { sessionId: 's1', path: join(host.cwd, 'nope.txt') });
65
+ expect(answer).toMatchObject({ answered: false, code: ACP_ERROR.notFound });
66
+ });
67
+
68
+ test('a relative path is refused as invalid params', async () => {
69
+ const host = await workspace();
70
+ const answer = await handleAcpFsRequest(host, 'fs/read_text_file', { sessionId: 's1', path: 'a.txt' });
71
+ expect(answer).toMatchObject({ answered: false, code: ACP_ERROR.invalidParams });
72
+ });
73
+
74
+ test('a path outside the workspace is refused even when it exists', async () => {
75
+ const host = await workspace();
76
+ const answer = await handleAcpFsRequest(host, 'fs/read_text_file', { sessionId: 's1', path: '/etc/hosts' });
77
+ expect(answer).toMatchObject({ answered: false, code: ACP_ERROR.invalidParams });
78
+ });
79
+
80
+ // POSIX only: the fixture links to `/etc/hosts`, which does not exist on
81
+ // Windows, and creating a symlink there needs a privilege a default runner
82
+ // does not have. Measured on the Windows gate: the link was never made, so the
83
+ // handler answered `-32002 File not found` instead of the refusal under test —
84
+ // a failure about the fixture, not about the guard. The case ABOVE still runs
85
+ // there: an absolute path outside the workspace is refused before any read.
86
+ testPosix('a symlink out of the workspace is refused', async () => {
87
+ const host = await workspace();
88
+ const link = join(host.cwd, 'escape.txt');
89
+ await symlink('/etc/hosts', link);
90
+ const answer = await handleAcpFsRequest(host, 'fs/read_text_file', { sessionId: 's1', path: link });
91
+ expect(answer).toMatchObject({ answered: false, code: ACP_ERROR.invalidParams });
92
+ });
93
+
94
+ test('a window of 0 is invalid params, not an empty answer', async () => {
95
+ const host = await workspace();
96
+ const file = join(host.cwd, 'a.txt');
97
+ await Bun.write(file, 'one');
98
+ const answer = await handleAcpFsRequest(host, 'fs/read_text_file', { sessionId: 's1', path: file, line: 0 });
99
+ expect(answer).toMatchObject({ answered: false, code: ACP_ERROR.invalidParams });
100
+ });
101
+
102
+ test('a request naming another session is refused', async () => {
103
+ const host = await workspace();
104
+ const file = join(host.cwd, 'a.txt');
105
+ await Bun.write(file, 'one');
106
+ const answer = await handleAcpFsRequest(host, 'fs/read_text_file', { sessionId: 'other', path: file });
107
+ expect(answer).toMatchObject({ answered: false, code: ACP_ERROR.invalidParams });
108
+ });
109
+ });
110
+
111
+ describe('fs/write_text_file', () => {
112
+ test('creates the file and its parent directories', async () => {
113
+ const host = await workspace();
114
+ const target = join(host.cwd, 'nested', 'dir', 'a.txt');
115
+ const answer = await handleAcpFsRequest(host, 'fs/write_text_file', { sessionId: 's1', path: target, content: 'hello' });
116
+ expect(answer).toEqual({ answered: true, result: {} });
117
+ expect(await Bun.file(target).text()).toBe('hello');
118
+ });
119
+
120
+ test('a path outside the workspace is refused and nothing is written', async () => {
121
+ const host = await workspace();
122
+ const target = join(host.cwd, '..', 'escaped.txt');
123
+ const answer = await handleAcpFsRequest(host, 'fs/write_text_file', { sessionId: 's1', path: target, content: 'x' });
124
+ expect(answer).toMatchObject({ answered: false, code: ACP_ERROR.invalidParams });
125
+ });
126
+
127
+ test('missing content is invalid params', async () => {
128
+ const host = await workspace();
129
+ const answer = await handleAcpFsRequest(host, 'fs/write_text_file', {
130
+ sessionId: 's1',
131
+ path: join(host.cwd, 'a.txt'),
132
+ });
133
+ expect(answer).toMatchObject({ answered: false, code: ACP_ERROR.invalidParams });
134
+ });
135
+ });
@@ -0,0 +1,131 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The ACP client's file surface: `fs/read_text_file` / `fs/write_text_file`.
8
+ *
9
+ * These are calls the AGENT makes on the CLIENT (see `file-system.md`), so the
10
+ * client performs the operation itself and is responsible for its own checks —
11
+ * a permission request does not replace them. Three rules here are the whole
12
+ * point of the module:
13
+ *
14
+ * - **Workspace containment.** Every path is canonicalized against the
15
+ * session's cwd with `pathHolds`, which resolves symlinks and the nearest
16
+ * existing ancestor. A path that merely LOOKS inside (`../`, a symlink to
17
+ * `/etc`) is refused with `-32602`, never read.
18
+ * - **Line numbers are 1-based.** `line`/`limit` select a window of lines, and
19
+ * an out-of-range window is an empty string, not an error.
20
+ * - **A write creates.** ACP says the client MUST create the file if it does
21
+ * not exist, which includes its parent directories.
22
+ *
23
+ * Capability advertisement lives in `client-capabilities.ts`; this module only
24
+ * serves what that object promises.
25
+ */
26
+
27
+ import path from 'node:path';
28
+ import { pathHolds } from '@/server/lib/fs/canonical';
29
+ import { ACP_ERROR } from '@/server/lib/harness/acp/protocol';
30
+
31
+ /** The slice of a session an fs call reads. */
32
+ export interface AcpFsHost {
33
+ readonly cwd: string;
34
+ readonly sessionId: string;
35
+ }
36
+
37
+ /** Structurally the `answered: false` branch of the client-request answer. */
38
+ export type AcpFsAnswer =
39
+ | { answered: true; result: unknown }
40
+ | { answered: false; message: string; code: number };
41
+
42
+ export function isAcpFsMethod(method: string): boolean {
43
+ return method === 'fs/read_text_file' || method === 'fs/write_text_file';
44
+ }
45
+
46
+ export async function handleAcpFsRequest(
47
+ host: AcpFsHost,
48
+ method: string,
49
+ params: Record<string, unknown>,
50
+ ): Promise<AcpFsAnswer> {
51
+ const requestedSession = params.sessionId;
52
+ // One process serves one session on this transport, so any other id names
53
+ // something this client cannot address. Silently serving it would let a
54
+ // second session reach a workspace it was never given.
55
+ if (typeof requestedSession === 'string' && requestedSession !== host.sessionId) {
56
+ return refuse(ACP_ERROR.invalidParams, `Unknown session: ${requestedSession}`);
57
+ }
58
+ const target = params.path;
59
+ if (typeof target !== 'string' || target.length === 0) {
60
+ return refuse(ACP_ERROR.invalidParams, 'path is required');
61
+ }
62
+ if (!path.isAbsolute(target)) {
63
+ return refuse(ACP_ERROR.invalidParams, `Path must be absolute: ${target}`);
64
+ }
65
+ if (!(await pathHolds(host.cwd, target))) {
66
+ return refuse(ACP_ERROR.invalidParams, `Path is outside this session's workspace: ${target}`);
67
+ }
68
+
69
+ return method === 'fs/read_text_file' ? read(target, params) : write(target, params);
70
+ }
71
+
72
+ async function read(target: string, params: Record<string, unknown>): Promise<AcpFsAnswer> {
73
+ const line = optionalPositive(params.line);
74
+ if (line === false) return refuse(ACP_ERROR.invalidParams, 'line must be a positive integer');
75
+ const limit = optionalPositive(params.limit);
76
+ if (limit === false) return refuse(ACP_ERROR.invalidParams, 'limit must be a positive integer');
77
+
78
+ let text: string;
79
+ try {
80
+ text = await Bun.file(target).text();
81
+ } catch (error) {
82
+ return fileError(target, error);
83
+ }
84
+ if (line === undefined && limit === undefined) return { answered: true, result: { content: text } };
85
+
86
+ /**
87
+ * Splitting on '\n' keeps a trailing newline as a final empty element, so
88
+ * `line: 1, limit: 1` on "a\nb\n" answers "a" — not "a\n". The window is
89
+ * inclusive of `line` and counts `limit` lines, exactly as the spec words it.
90
+ */
91
+ const lines = text.split('\n');
92
+ const start = (line ?? 1) - 1;
93
+ const end = limit === undefined ? undefined : start + limit;
94
+ return { answered: true, result: { content: lines.slice(start, end).join('\n') } };
95
+ }
96
+
97
+ async function write(target: string, params: Record<string, unknown>): Promise<AcpFsAnswer> {
98
+ const content = params.content;
99
+ if (typeof content !== 'string') {
100
+ return refuse(ACP_ERROR.invalidParams, 'content is required');
101
+ }
102
+ try {
103
+ // `Bun.write` creates missing parent directories, which is the "MUST create
104
+ // the file if it doesn't exist" half of the method.
105
+ await Bun.write(target, content);
106
+ return { answered: true, result: {} };
107
+ } catch (error) {
108
+ return fileError(target, error);
109
+ }
110
+ }
111
+
112
+ /** The optional positive integer a window parameter must be, or false. */
113
+ function optionalPositive(value: unknown): number | undefined | false {
114
+ if (value === undefined || value === null) return undefined;
115
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) return false;
116
+ return value;
117
+ }
118
+
119
+ function refuse(code: number, message: string): AcpFsAnswer {
120
+ return { answered: false, message, code };
121
+ }
122
+
123
+ /** Map a filesystem failure onto the spec's codes. */
124
+ function fileError(target: string, error: unknown): AcpFsAnswer {
125
+ const code = (error as { code?: unknown } | null)?.code;
126
+ if (code === 'ENOENT') return refuse(ACP_ERROR.notFound, `File not found: ${target}`);
127
+ if (code === 'EISDIR' || code === 'ENOTDIR' || code === 'EINVAL') {
128
+ return refuse(ACP_ERROR.invalidParams, `Not a text file: ${target}`);
129
+ }
130
+ return refuse(ACP_ERROR.internal, error instanceof Error ? error.message : String(error));
131
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Version negotiation at `initialize`.
8
+ *
9
+ * The client sends v2 as its latest version and carries the v1 field names in
10
+ * the same request, so a v1 peer answers 1 without losing the client's
11
+ * capabilities. A strict v1 peer that REJECTS version 2 gets one clean v1
12
+ * retry; a dead process or timeout is not retried.
13
+ */
14
+
15
+ import { describe, expect, test } from 'bun:test';
16
+ import { initializeAcpAgent, type AcpInitializeInvoke } from '@/server/lib/harness/acp/client-initialize';
17
+ import { AcpRequestError } from '@/server/lib/harness/acp/calls';
18
+
19
+ /**
20
+ * A one-method invoke. The cast is the seam's own shape: `AcpInitializeInvoke`
21
+ * is generic over the caller's requested result, and these doubles answer the
22
+ * only method under test.
23
+ */
24
+ function invokeAnswering(answer: (params: Record<string, unknown>) => Promise<unknown>): AcpInitializeInvoke {
25
+ return ((_method: string, params: unknown) => answer(params as Record<string, unknown>)) as AcpInitializeInvoke;
26
+ }
27
+
28
+ describe('initializeAcpAgent', () => {
29
+ test('sends v2 plus the v1 field names and normalizes a v2 answer', async () => {
30
+ const sent: Record<string, unknown>[] = [];
31
+ const result = await initializeAcpAgent(invokeAnswering(async (params) => {
32
+ sent.push(params);
33
+ return {
34
+ protocolVersion: 2,
35
+ info: { name: 'agent', version: '2.0' },
36
+ capabilities: { session: { prompt: { image: {} } } },
37
+ };
38
+ }));
39
+ expect(sent[0]).toMatchObject({
40
+ protocolVersion: 2,
41
+ capabilities: {},
42
+ info: { name: 'kabmo', version: '0.1' },
43
+ clientCapabilities: { fs: { readTextFile: true, writeTextFile: true } },
44
+ });
45
+ expect(result.protocolVersion).toBe(2);
46
+ expect(result.agentCapabilities?.promptCapabilities?.image).toBe(true);
47
+ });
48
+
49
+ test('retries a rejected v2 initialize as a clean v1 request', async () => {
50
+ const versions: unknown[] = [];
51
+ const result = await initializeAcpAgent(invokeAnswering(async (params) => {
52
+ const version = params.protocolVersion;
53
+ versions.push(version);
54
+ if (version === 2) throw new AcpRequestError('Unsupported protocol version', -32022);
55
+ return { protocolVersion: 1, agentCapabilities: { loadSession: true } };
56
+ }));
57
+ expect(versions).toEqual([2, 1]);
58
+ expect(result.protocolVersion).toBe(1);
59
+ expect(result.agentCapabilities?.loadSession).toBe(true);
60
+ });
61
+
62
+ test('does not retry a transport failure', async () => {
63
+ let calls = 0;
64
+ await expect(initializeAcpAgent(invokeAnswering(async () => {
65
+ calls += 1;
66
+ throw new Error('ACP agent exited');
67
+ }))).rejects.toThrow('ACP agent exited');
68
+ expect(calls).toBe(1);
69
+ });
70
+ });
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The client half of `initialize`, kept out of `client.ts` because the transport
8
+ * file has a line ceiling and this is pure protocol.
9
+ *
10
+ * ## Speaking both majors
11
+ *
12
+ * The client sends v2 as its latest version, but the request also carries the v1
13
+ * field names (`clientCapabilities`/`clientInfo`). Migration §Version
14
+ * negotiation says a v1 agent reads a v2 request without those fields and loses
15
+ * the client's file-system support; carrying both means a v1 agent answers 1 and
16
+ * still sees the capabilities it understands, while a v2 agent ignores the v1
17
+ * names as unknown fields.
18
+ *
19
+ * A strict v1 agent may reject version 2 instead of answering 1. The connection
20
+ * is still uninitialized after a failed `initialize`, so one clean v1 retry is
21
+ * allowed and is what keeps such an agent working.
22
+ *
23
+ * The result is normalized into the v1-shaped record the rest of Kabmo reads
24
+ * (`normalizeInitializeResult`); the negotiated major is kept on it.
25
+ */
26
+
27
+ import {
28
+ ACP_PROTOCOL_VERSION,
29
+ KABMO_CLIENT_CAPABILITIES,
30
+ assertProtocolVersion,
31
+ } from '@/server/lib/harness/acp/client-capabilities';
32
+ import { AcpRequestError } from '@/server/lib/harness/acp/calls';
33
+ import { asRecord, normalizeInitializeResult } from '@/server/lib/harness/acp/v2';
34
+ import type { AcpInitializeResult } from '@/server/lib/harness/acp/protocol';
35
+
36
+ /** One request/response round trip; `AcpProcess.call` is one. */
37
+ export type AcpInitializeInvoke = <T>(method: string, params: unknown, timeoutMs: number) => Promise<T>;
38
+
39
+ const CLIENT_INFO = { name: 'kabmo', title: 'Kabmo', version: '0.1' };
40
+
41
+ /** v1 capabilities for a v1 peer; v2 removed fs/terminal and Kabmo advertises neither. */
42
+ function v1Request(capabilities: Record<string, unknown>): Record<string, unknown> {
43
+ return {
44
+ protocolVersion: 1,
45
+ clientCapabilities: capabilities,
46
+ clientInfo: CLIENT_INFO,
47
+ };
48
+ }
49
+
50
+ /** v2 request plus the v1 field names, for a peer that selects v1 instead. */
51
+ function hybridRequest(capabilities: Record<string, unknown>): Record<string, unknown> {
52
+ return {
53
+ protocolVersion: ACP_PROTOCOL_VERSION,
54
+ capabilities: {},
55
+ info: CLIENT_INFO,
56
+ clientCapabilities: capabilities,
57
+ clientInfo: CLIENT_INFO,
58
+ };
59
+ }
60
+
61
+ export async function initializeAcpAgent(
62
+ request: AcpInitializeInvoke,
63
+ capabilities: Record<string, unknown> = KABMO_CLIENT_CAPABILITIES,
64
+ timeoutMs = 60_000,
65
+ ): Promise<AcpInitializeResult> {
66
+ let raw: Record<string, unknown>;
67
+ try {
68
+ raw = asRecord(await request<unknown>('initialize', hybridRequest(capabilities), timeoutMs)) ?? {};
69
+ } catch (first) {
70
+ // Only an ANSWERED initialize is retried: a dead process or a timeout has
71
+ // nothing to renegotiate. The connection is still uninitialized after a
72
+ // failed `initialize`, so a v1 retry is allowed by both specs.
73
+ if (!(first instanceof AcpRequestError)) throw first;
74
+ try {
75
+ raw = asRecord(await request<unknown>('initialize', v1Request(capabilities), timeoutMs)) ?? {};
76
+ } catch (retry) {
77
+ const b = retry instanceof Error ? retry.message : String(retry);
78
+ throw new Error(`initialize failed (v2 attempt: ${first.message}; v1 attempt: ${b})`);
79
+ }
80
+ }
81
+ const result = normalizeInitializeResult(raw);
82
+ assertProtocolVersion(result);
83
+ return result;
84
+ }