The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,837 lines 67.6 KB
Raw
1 import * as Path from "effect/Path";
2 import * as Cause from "effect/Cause";
3 import * as Deferred from "effect/Deferred";
4 import * as Effect from "effect/Effect";
5 import * as Exit from "effect/Exit";
6 import * as Fiber from "effect/Fiber";
7 import * as Layer from "effect/Layer";
8 import * as Logger from "effect/Logger";
9 import * as Queue from "effect/Queue";
10 import * as Ref from "effect/Ref";
11 import * as Schema from "effect/Schema";
12 import * as Scope from "effect/Scope";
13 import * as Stream from "effect/Stream";
14 import * as TestClock from "effect/testing/TestClock";
15 import { ChildProcess, ChildProcessSpawner } from "effect/process";
16
17 import * as NodeServices from "@effect/platform-node/NodeServices";
18 import { it, assert } from "@effect/vitest";
19
20 import * as AcpClient from "./client.ts";
21 import * as AcpSchema from "./_generated/schema.gen.ts";
22 import * as AcpSchemaV1 from "./_generated/schema-v1.gen.ts";
23 import * as AcpError from "./errors.ts";
24 import type * as AcpCompat from "./compat.ts";
25 import type * as AcpProtocol from "./protocol.ts";
26 import {
27 encodeJsonl,
28 jsonRpcNotification,
29 jsonRpcRequest,
30 jsonRpcResponse,
31 } from "./_internal/shared.ts";
32 import { makeInMemoryStdio } from "./_internal/stdio.ts";
33
34 import antigravityInitialize from "../test/fixtures/antigravity-initialize.json" with { type: "json" };
35
36 const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
37 const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
38 const InitializeRequestV1 = jsonRpcRequest("initialize", AcpSchemaV1.InitializeRequest);
39 const InitializeResponseV1 = jsonRpcResponse(AcpSchemaV1.InitializeResponse);
40 const NewSessionRequestV1 = jsonRpcRequest("session/new", AcpSchemaV1.NewSessionRequest);
41 const PromptRequestV1 = jsonRpcRequest("session/prompt", AcpSchemaV1.PromptRequest);
42 const PromptResponseV1 = jsonRpcResponse(AcpSchemaV1.PromptResponse);
43 const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
44 const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
45 const PromptRequest = jsonRpcRequest("session/prompt", AcpSchema.PromptRequest);
46 const PromptResponse = jsonRpcResponse(AcpSchema.PromptResponse);
47 const SessionUpdateNotification = jsonRpcNotification("session/update", Schema.Unknown);
48 const PermissionRequest = jsonRpcRequest(
49 "session/request_permission",
50 AcpSchema.RequestPermissionRequest,
51 );
52 const ElicitationResponse = jsonRpcResponse(AcpSchema.CreateElicitationResponse);
53 const PermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
54 const ErrorResponse = Schema.Struct({ id: Schema.String, error: Schema.Unknown });
55 const DieResponse = Schema.Struct({
56 id: Schema.String,
57 error: Schema.Struct({
58 code: Schema.Literal(-32603),
59 message: Schema.Literal("Internal error"),
60 }),
61 });
62 const decodePromptRequestLine = Schema.decodeEffect(Schema.fromJsonString(PromptRequest));
63 const XAiPromptCompleteNotification = jsonRpcNotification(
64 "_x.ai/session/prompt_complete",
65 Schema.Struct({
66 sessionId: Schema.String,
67 promptId: Schema.String,
68 stopReason: Schema.String,
69 agentResult: Schema.NullOr(Schema.Unknown),
70 }),
71 );
72 const XAiQueueChangedNotification = jsonRpcNotification(
73 "_x.ai/queue/changed",
74 Schema.Struct({
75 sessionId: Schema.String,
76 entries: Schema.Array(Schema.Unknown),
77 }),
78 );
79 const XAiSessionsChangedNotification = jsonRpcNotification(
80 "_x.ai/sessions/changed",
81 Schema.Struct({
82 upserted: Schema.Array(Schema.Unknown),
83 removed: Schema.Array(Schema.Unknown),
84 }),
85 );
86 const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
87 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
88 );
89 const mockPeerArgs = (path: string) => [path];
90 const mockStartupNotice = "Mock ACP startup notice";
91 const stripMockStartupNotice = (stdout: ChildProcessSpawner.ChildProcessHandle["stdout"]) =>
92 stdout.pipe(
93 Stream.decodeText,
94 Stream.splitLines,
95 Stream.filter((line) => line !== mockStartupNotice),
96 Stream.map((line) => `${line}\n`),
97 Stream.encodeText,
98 );
99
100 function concatBytes(chunks: ReadonlyArray<Uint8Array>): Uint8Array {
101 const batch = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
102 let offset = 0;
103 for (const chunk of chunks) {
104 batch.set(chunk, offset);
105 offset += chunk.length;
106 }
107 return batch;
108 }
109
110 it.layer(NodeServices.layer)("effect-acp client", (it) => {
111 const makeHandle = (env?: Record<string, string>) =>
112 Effect.gen(function* () {
113 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
114 const path = yield* Path.Path;
115 const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
116 cwd: path.join(import.meta.dirname, ".."),
117 ...(env ? { env: { ...process.env, ...env } } : {}),
118 });
119 return yield* spawner.spawn(command);
120 });
121
122 it.effect("transforms fragmented stdout before parsing and preserves UTF-8", () =>
123 Effect.gen(function* () {
124 const handle = yield* makeHandle({ ACP_MOCK_STDOUT_PREFIX: `${mockStartupNotice}\n` });
125 yield* Effect.gen(function* () {
126 const acp = yield* AcpClient.AcpClient;
127 const initialized = yield* acp.agent.initialize({ protocolVersion: 1 });
128 assert.equal(initialized.protocolVersion, 2);
129
130 const echoed = yield* acp.raw.request("x/echo", { message: "café" });
131 assert.deepEqual(echoed, {
132 echoedMethod: "x/echo",
133 echoedParams: { message: "café" },
134 });
135 }).pipe(
136 Effect.provide(
137 AcpClient.layerChildProcess(handle, {
138 transformStdout: (stdout) =>
139 stdout.pipe(
140 Stream.flatMap((chunk) =>
141 Stream.fromIterable(Array.from(chunk, (byte) => Uint8Array.of(byte))),
142 ),
143 stripMockStartupNotice,
144 ),
145 }),
146 ),
147 );
148 }),
149 );
150
151 it.effect("preserves stdout transform errors without logging rejected input", () =>
152 Effect.gen(function* () {
153 const privateNotice = "Mock sign-in URL: https://example.test/login?token=mock-private-token";
154 const handle = yield* makeHandle({ ACP_MOCK_STDOUT_PREFIX: `${privateNotice}\n` });
155 const termination = yield* Deferred.make<AcpError.AcpError>();
156 const logs = yield* Ref.make<Array<unknown>>([]);
157 const expectedError = new AcpError.AcpTransportError({
158 operation: "read-input-stream",
159 detail: "Sign in to the mock agent.",
160 cause: undefined,
161 });
162 const error = yield* Effect.gen(function* () {
163 const acp = yield* AcpClient.AcpClient;
164 const failure = yield* acp.agent.initialize({ protocolVersion: 1 }).pipe(Effect.flip);
165 assert.strictEqual(yield* Deferred.await(termination), expectedError);
166 return failure;
167 }).pipe(
168 Effect.provide(
169 AcpClient.layerChildProcess(handle, {
170 logIncoming: true,
171 logger: (event) => Ref.update(logs, (current) => [...current, event]),
172 transformStdout: (stdout) =>
173 stdout.pipe(
174 Stream.decodeText,
175 Stream.splitLines,
176 Stream.mapEffect((line) =>
177 line === privateNotice ? Effect.fail(expectedError) : Effect.succeed(`${line}\n`),
178 ),
179 Stream.encodeText,
180 ),
181 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
182 }),
183 ),
184 );
185
186 assert.strictEqual(error, expectedError);
187 assert.isEmpty(yield* Ref.get(logs));
188 }),
189 );
190
191 it.effect("retains only transformed session updates in raw notifications and handlers", () =>
192 Effect.gen(function* () {
193 const { stdio, input } = yield* makeInMemoryStdio();
194 const delivered = yield* Deferred.make<import("./compat.ts").SessionNotification>();
195 const imageData = "A".repeat(1_048_576);
196 const normalized = {
197 sessionId: "session-1",
198 update: {
199 sessionUpdate: "agent_message_chunk",
200 content: { type: "text", text: "Image data omitted." },
201 },
202 } satisfies import("./compat.ts").SessionNotification;
203 let transformCalls = 0;
204 const acp = yield* AcpClient.make(stdio, {
205 transformSessionUpdate: (notification) => {
206 if (
207 notification.update.sessionUpdate !== "agent_message_chunk" ||
208 notification.update.content.type !== "image"
209 ) {
210 return notification;
211 }
212 assert.equal(notification.update.content.data, imageData);
213 transformCalls += 1;
214 return normalized;
215 },
216 });
217 yield* acp.handleSessionUpdate((notification) =>
218 Deferred.succeed(delivered, notification).pipe(Effect.asVoid),
219 );
220
221 yield* Queue.offer(
222 input,
223 yield* encodeJsonl(SessionUpdateNotification, {
224 jsonrpc: "2.0",
225 method: "session/update",
226 params: {
227 sessionId: "session-1",
228 update: {
229 sessionUpdate: "agent_message_chunk",
230 content: { type: "image", data: imageData, mimeType: "image/png" },
231 },
232 },
233 }),
234 );
235
236 assert.strictEqual(yield* Deferred.await(delivered), normalized);
237 const [retained] = yield* acp.raw.notifications.pipe(Stream.take(1), Stream.runCollect);
238 assert.deepEqual(retained, {
239 _tag: "SessionUpdate",
240 method: "session/update",
241 params: normalized,
242 });
243 assert.equal(transformCalls, 1);
244 }),
245 );
246
247 it.effect("keeps the JSON-RPC error of a failed v2 idle", () =>
248 Effect.gen(function* () {
249 const { stdio, input } = yield* makeInMemoryStdio();
250 const delivered = yield* Deferred.make<AcpCompat.SessionNotification>();
251 const acp = yield* AcpClient.make(stdio);
252 yield* acp.handleSessionUpdate((notification) =>
253 Deferred.succeed(delivered, notification).pipe(Effect.asVoid),
254 );
255 const error = { code: -32000, message: "Please sign in to Claude", data: { retry: false } };
256 const idle = {
257 sessionUpdate: "state_update",
258 state: "idle",
259 stopReason: "error",
260 error,
261 } as const;
262
263 yield* Queue.offer(
264 input,
265 yield* encodeJsonl(SessionUpdateNotification, {
266 jsonrpc: "2.0",
267 method: "session/update",
268 params: {
269 sessionId: "session-1",
270 update: idle,
271 },
272 }),
273 );
274
275 const { update } = yield* Deferred.await(delivered);
276 assert.deepEqual(
277 update.sessionUpdate === "state_update" && update.state === "idle" ? update : undefined,
278 idle,
279 );
280 }),
281 );
282
283 it.effect("reports idle child termination and rejects later requests and notifications", () =>
284 Effect.gen(function* () {
285 const handle = yield* makeHandle();
286 const termination = yield* Deferred.make<AcpError.AcpError>();
287 yield* Effect.gen(function* () {
288 const acp = yield* AcpClient.AcpClient;
289 yield* acp.agent.initialize({ protocolVersion: 1 });
290 yield* handle.kill();
291
292 const error = yield* Deferred.await(termination);
293 if (error._tag !== "AcpProcessExitedError") {
294 return assert.fail(`Expected a process exit, got ${error._tag}`);
295 }
296 assert.equal(error.pid, handle.pid);
297 assert.equal(error.code, yield* handle.exitCode);
298 const rawRequestError = yield* acp.raw.request("x/echo", {}).pipe(
299 Effect.match({
300 onFailure: (failure) => failure,
301 onSuccess: () => assert.fail("Expected the request to fail after process exit"),
302 }),
303 );
304 assert.strictEqual(rawRequestError, error);
305 assert.strictEqual(yield* acp.raw.notify("x/notify", {}).pipe(Effect.flip), error);
306 assert.strictEqual(
307 yield* acp.agent.cancel({ sessionId: "mock-session-1" }).pipe(Effect.flip),
308 error,
309 );
310
311 const requestError = yield* acp.agent
312 .createSession({ cwd: process.cwd(), mcpServers: [] })
313 .pipe(Effect.flip);
314 assert.strictEqual(requestError, error);
315 }).pipe(
316 Effect.provide(
317 AcpClient.layerChildProcess(handle, {
318 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
319 }),
320 ),
321 );
322 }),
323 );
324
325 it.effect("initializes, prompts, receives updates, and handles permission requests", () =>
326 Effect.gen(function* () {
327 const updates = yield* Ref.make<Array<unknown>>([]);
328 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
329 const typedRequests = yield* Ref.make<Array<unknown>>([]);
330 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
331 const requestContexts = yield* Ref.make<Array<AcpProtocol.AcpRequestContext>>([]);
332 const handle = yield* makeHandle();
333 const scope = yield* Scope.make();
334 const layerAcp = AcpClient.layerChildProcess(handle);
335 const context = yield* Layer.buildWithScope(layerAcp, scope);
336
337 const ext = yield* Effect.gen(function* () {
338 const acp = yield* AcpClient.AcpClient;
339
340 yield* acp.handleRequestPermission((_request, requestContext) =>
341 Ref.update(requestContexts, (current) => [...current, requestContext]).pipe(
342 Effect.as({
343 outcome: {
344 outcome: "selected",
345 optionId: "allow",
346 },
347 }),
348 ),
349 );
350 yield* acp.handleElicitation((_request, requestContext) =>
351 Ref.update(requestContexts, (current) => [...current, requestContext]).pipe(
352 Effect.as({
353 action: "accept",
354 content: {
355 approved: true,
356 },
357 }),
358 ),
359 );
360 yield* acp.handleSessionUpdate((notification) =>
361 Ref.update(updates, (current) => [...current, notification]),
362 );
363 yield* acp.handleElicitationComplete((notification) =>
364 Ref.update(elicitationCompletions, (current) => [...current, notification]),
365 );
366 yield* acp.handleExtRequest(
367 "x/typed_request",
368 Schema.Struct({ message: Schema.String }),
369 (payload, requestContext) =>
370 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
371 Effect.andThen(
372 Ref.update(requestContexts, (current) => [...current, requestContext]),
373 ),
374 Effect.as({
375 ok: true,
376 echoedMessage: payload.message,
377 }),
378 ),
379 );
380 yield* acp.handleExtNotification(
381 "x/typed_notification",
382 Schema.Struct({ count: Schema.Number }),
383 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
384 );
385
386 const init = yield* acp.agent.initialize({
387 protocolVersion: 1,
388 clientCapabilities: {
389 fs: { readTextFile: false, writeTextFile: false },
390 terminal: false,
391 elicitation: { form: {} },
392 },
393 clientInfo: {
394 name: "effect-acp-test",
395 version: "0.0.0",
396 },
397 });
398 assert.equal(init.protocolVersion, 2);
399
400 yield* acp.agent.authenticate({ methodId: "cursor_login" });
401
402 const session = yield* acp.agent.createSession({
403 cwd: process.cwd(),
404 mcpServers: [],
405 });
406 assert.equal(session.sessionId, "mock-session-1");
407 // ACP v2 removed session/set_mode; modes are config options there.
408 const setMode = yield* acp.agent
409 .setSessionMode({ sessionId: session.sessionId, modeId: "code" })
410 .pipe(Effect.flip);
411 assert.equal(setMode._tag === "AcpRequestError" ? setMode.code : undefined, -32601);
412
413 const prompt = yield* acp.agent.prompt({
414 sessionId: session.sessionId,
415 prompt: [{ type: "text", text: "hello" }],
416 });
417 assert.equal(prompt.stopReason, "end_turn");
418
419 const streamed = yield* Stream.runCollect(Stream.take(acp.raw.notifications, 2));
420 assert.equal(streamed.length, 2);
421 assert.equal(streamed[0]?._tag, "SessionUpdate");
422 assert.equal(streamed[1]?._tag, "ElicitationComplete");
423 assert.equal((yield* Ref.get(updates)).length, 2);
424 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
425 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
426 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
427 const observedRequestContexts = yield* Ref.get(requestContexts);
428 assert.deepEqual(
429 observedRequestContexts.map((requestContext) => requestContext.method),
430 ["session/request_permission", "elicitation/create", "x/typed_request"],
431 );
432 assert.equal(
433 new Set(observedRequestContexts.map((requestContext) => requestContext.requestId)).size,
434 observedRequestContexts.length,
435 );
436
437 return yield* acp.raw.request("x/echo", {
438 hello: "world",
439 });
440 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
441
442 assert.deepEqual(ext, {
443 echoedMethod: "x/echo",
444 echoedParams: {
445 hello: "world",
446 },
447 });
448 }),
449 );
450
451 it.effect(
452 "returns structured invalid params without exposing values from typed extension request payloads",
453 () =>
454 Effect.gen(function* () {
455 const handle = yield* makeHandle({ ACP_MOCK_BAD_TYPED_REQUEST: "1" });
456 const scope = yield* Scope.make();
457 const layerAcp = AcpClient.layerChildProcess(handle);
458 const context = yield* Layer.buildWithScope(layerAcp, scope);
459
460 const result = yield* Effect.gen(function* () {
461 const acp = yield* AcpClient.AcpClient;
462
463 yield* acp.handleRequestPermission(() =>
464 Effect.succeed({
465 outcome: {
466 outcome: "selected",
467 optionId: "allow",
468 },
469 }),
470 );
471 yield* acp.handleElicitation(() =>
472 Effect.succeed({
473 action: "accept",
474 content: {
475 approved: true,
476 },
477 }),
478 );
479 yield* acp.handleExtRequest(
480 "x/typed_request",
481 Schema.Struct({ message: Schema.String }),
482 () => Effect.succeed({ ok: true }),
483 );
484
485 yield* acp.agent.initialize({
486 protocolVersion: 1,
487 clientCapabilities: {
488 fs: { readTextFile: false, writeTextFile: false },
489 terminal: false,
490 elicitation: { form: {} },
491 },
492 clientInfo: {
493 name: "effect-acp-test",
494 version: "0.0.0",
495 },
496 });
497
498 yield* acp.agent.authenticate({ methodId: "cursor_login" });
499
500 const session = yield* acp.agent.createSession({
501 cwd: process.cwd(),
502 mcpServers: [],
503 });
504
505 return yield* Effect.exit(
506 acp.agent.prompt({
507 sessionId: session.sessionId,
508 prompt: [{ type: "text", text: "hello" }],
509 }),
510 );
511 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
512
513 if (result._tag !== "Failure") {
514 assert.fail("Expected prompt to fail for invalid typed extension payload");
515 }
516 const rendered = Cause.pretty(result.cause);
517 assert.include(rendered, "Invalid payload for ACP extension method 'x/typed_request'.");
518 assert.notInclude(rendered, "Expected string, got 123");
519 }),
520 );
521
522 it.effect("preserves ACP v2 structured diff semantics", () =>
523 Effect.gen(function* () {
524 const updates = yield* Ref.make<Array<AcpCompat.SessionNotification>>([]);
525 const handle = yield* makeHandle({ ACP_MOCK_V2_DIFF: "1" });
526 const scope = yield* Scope.make();
527 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
528
529 yield* Effect.gen(function* () {
530 const acp = yield* AcpClient.AcpClient;
531 yield* acp.handleRequestPermission(() =>
532 Effect.succeed({ outcome: { outcome: "selected", optionId: "allow" } }),
533 );
534 yield* acp.handleElicitation(() =>
535 Effect.succeed({ action: "accept", content: { approved: true } }),
536 );
537 yield* acp.handleExtRequest(
538 "x/typed_request",
539 Schema.Struct({ message: Schema.String }),
540 () => Effect.succeed({ ok: true }),
541 );
542 yield* acp.handleSessionUpdate((notification) =>
543 Ref.update(updates, (current) => [...current, notification]),
544 );
545
546 yield* acp.agent.initialize({
547 protocolVersion: 2,
548 clientCapabilities: { elicitation: { form: {} } },
549 });
550 yield* acp.agent.authenticate({ methodId: "cursor_login" });
551 const session = yield* acp.agent.createSession({ cwd: process.cwd(), mcpServers: [] });
552 yield* acp.agent.prompt({
553 sessionId: session.sessionId,
554 prompt: [{ type: "text", text: "show the diff" }],
555 });
556 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
557
558 const diffUpdate = (yield* Ref.get(updates)).find(
559 (notification) => notification.update.sessionUpdate === "tool_call_update",
560 );
561 assert.deepEqual(diffUpdate?.update, {
562 sessionUpdate: "tool_call_update",
563 toolCallId: "tool-diff",
564 content: [
565 {
566 type: "diff",
567 changes: [
568 {
569 operation: "move",
570 oldPath: "/workspace/old.ts",
571 path: "/workspace/new.ts",
572 fileType: "text",
573 mimeType: "text/typescript",
574 },
575 ],
576 patch: {
577 format: "git_patch",
578 text: "diff --git a/old.ts b/new.ts\nsimilarity index 100%\nrename from old.ts\nrename to new.ts\n",
579 },
580 },
581 ],
582 });
583 }),
584 );
585
586 it.effect("does not turn unsupported ACP v2 auth methods into agent login", () =>
587 Effect.gen(function* () {
588 const handle = yield* makeHandle({ ACP_MOCK_CUSTOM_AUTH: "1" });
589 const response = yield* Effect.gen(function* () {
590 const acp = yield* AcpClient.AcpClient;
591 return yield* acp.agent.initialize({ protocolVersion: 2 });
592 }).pipe(Effect.provide(AcpClient.layerChildProcess(handle)));
593 assert.deepEqual(response.authMethods, []);
594 }),
595 );
596
597 it.effect("preserves registry env-var authentication extensions", () =>
598 Effect.gen(function* () {
599 const handle = yield* makeHandle({ ACP_MOCK_ENV_VAR_AUTH: "1" });
600 const scope = yield* Scope.make();
601 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
602
603 const response = yield* Effect.gen(function* () {
604 const acp = yield* AcpClient.AcpClient;
605 return yield* acp.agent.initialize({ protocolVersion: 2 });
606 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
607
608 assert.deepEqual(response.authMethods, [
609 {
610 id: "api_key",
611 name: "API key",
612 type: "env_var",
613 vars: [{ name: "MOCK_API_KEY", label: "Mock API key" }],
614 link: "https://example.test/keys",
615 },
616 ]);
617 }),
618 );
619
620 it.effect("replays buffered notifications to handlers registered after they arrive", () =>
621 Effect.gen(function* () {
622 const updates = yield* Ref.make<Array<unknown>>([]);
623 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
624 const typedRequests = yield* Ref.make<Array<unknown>>([]);
625 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
626 const handle = yield* makeHandle();
627 const scope = yield* Scope.make();
628 const layerAcp = AcpClient.layerChildProcess(handle);
629 const context = yield* Layer.buildWithScope(layerAcp, scope);
630
631 yield* Effect.gen(function* () {
632 const acp = yield* AcpClient.AcpClient;
633
634 yield* acp.handleRequestPermission(() =>
635 Effect.succeed({
636 outcome: {
637 outcome: "selected",
638 optionId: "allow",
639 },
640 }),
641 );
642 yield* acp.handleElicitation(() =>
643 Effect.succeed({
644 action: "accept",
645 content: {
646 approved: true,
647 },
648 }),
649 );
650 yield* acp.handleExtRequest(
651 "x/typed_request",
652 Schema.Struct({ message: Schema.String }),
653 (payload) =>
654 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
655 Effect.as({
656 ok: true,
657 echoedMessage: payload.message,
658 }),
659 ),
660 );
661 yield* acp.handleExtNotification(
662 "x/typed_notification",
663 Schema.Struct({ count: Schema.Number }),
664 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
665 );
666
667 yield* acp.agent.initialize({
668 protocolVersion: 1,
669 clientCapabilities: {
670 fs: { readTextFile: false, writeTextFile: false },
671 terminal: false,
672 elicitation: { form: {} },
673 },
674 clientInfo: {
675 name: "effect-acp-test",
676 version: "0.0.0",
677 },
678 });
679 yield* acp.agent.authenticate({ methodId: "cursor_login" });
680
681 const session = yield* acp.agent.createSession({
682 cwd: process.cwd(),
683 mcpServers: [],
684 });
685 yield* acp.agent.prompt({
686 sessionId: session.sessionId,
687 prompt: [{ type: "text", text: "hello" }],
688 });
689
690 yield* acp.handleSessionUpdate((notification) =>
691 Ref.update(updates, (current) => [...current, notification]),
692 );
693 yield* acp.handleElicitationComplete((notification) =>
694 Ref.update(elicitationCompletions, (current) => [...current, notification]),
695 );
696
697 assert.equal((yield* Ref.get(updates)).length, 2);
698 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
699 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
700 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
701 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
702 }),
703 );
704
705 it.effect("keeps RPC ids within int32 and apart from extension ids", () =>
706 Effect.gen(function* () {
707 const { stdio, input, output } = yield* makeInMemoryStdio();
708 const scope = yield* Scope.make();
709 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
710
711 const initializeFiber = yield* acp.agent
712 .initialize({
713 protocolVersion: 1,
714 clientCapabilities: {
715 fs: { readTextFile: false, writeTextFile: false },
716 terminal: false,
717 },
718 clientInfo: {
719 name: "effect-acp-test",
720 version: "0.0.0",
721 },
722 })
723 .pipe(Effect.forkScoped);
724 const extFiber = yield* acp.raw.request("x/test", { hello: "world" }).pipe(Effect.forkScoped);
725
726 const firstOutbound = yield* Queue.take(output);
727 const secondOutbound = yield* Queue.take(output);
728
729 const decodedInitialize = Schema.decodeEffect(Schema.fromJsonString(InitializeRequest));
730 const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
731 const firstIsInitialize = yield* decodedInitialize(firstOutbound).pipe(Effect.isSuccess);
732
733 const initializeRequest = firstIsInitialize
734 ? yield* decodedInitialize(firstOutbound)
735 : yield* decodedInitialize(secondOutbound);
736 const extRequest = firstIsInitialize
737 ? yield* decodedExt(secondOutbound)
738 : yield* decodedExt(firstOutbound);
739
740 assert.notEqual(initializeRequest.id, extRequest.id);
741 // Keep locally generated ids compatible with SDKs that decode signed int32.
742 assert.typeOf(initializeRequest.id, "number");
743 assert.equal(initializeRequest.id, 2 ** 30);
744 assert.isAtMost(Number(initializeRequest.id), 2 ** 31 - 1);
745 assert.equal(extRequest.id, 1);
746
747 yield* Queue.offer(
748 input,
749 yield* encodeJsonl(InitializeResponse, {
750 jsonrpc: "2.0",
751 id: initializeRequest.id,
752 result: {
753 protocolVersion: 2,
754 capabilities: {},
755 info: {
756 name: "mock-agent",
757 version: "0.0.0",
758 },
759 },
760 }),
761 );
762 yield* Queue.offer(
763 input,
764 yield* encodeJsonl(ExtResponse, {
765 jsonrpc: "2.0",
766 id: extRequest.id,
767 result: { ok: true },
768 }),
769 );
770
771 yield* Fiber.join(initializeFiber);
772 assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
773
774 const sessionFiber = yield* acp.agent
775 .createSession({ cwd: "/tmp", mcpServers: [] })
776 .pipe(Effect.forkScoped);
777 const sessionRequest = yield* Schema.decodeEffect(
778 Schema.fromJsonString(jsonRpcRequest("session/new", AcpSchema.NewSessionRequest)),
779 )(yield* Queue.take(output));
780 assert.equal(sessionRequest.id, 2 ** 30 + 1);
781 yield* Queue.offer(
782 input,
783 yield* encodeJsonl(jsonRpcResponse(AcpSchema.NewSessionResponse), {
784 jsonrpc: "2.0",
785 id: sessionRequest.id,
786 result: { sessionId: "session-1" },
787 }),
788 );
789 assert.equal((yield* Fiber.join(sessionFiber)).sessionId, "session-1");
790 yield* Scope.close(scope, Exit.void);
791 }),
792 );
793
794 it.effect.each([1, 2])("keeps legacy wire behavior with version %s", (protocolVersion) =>
795 Effect.gen(function* () {
796 const { stdio, input, output } = yield* makeInMemoryStdio();
797 const scope = yield* Scope.make();
798 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
799 const updates = yield* Ref.make<Array<unknown>>([]);
800 yield* acp.handleSessionUpdate((notification) =>
801 Ref.update(updates, (current) => [...current, notification]),
802 );
803
804 const initializeFiber = yield* acp.agent
805 .initialize({
806 protocolVersion: 2,
807 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
808 clientCapabilities: { _meta: { "terminal-auth": true } },
809 })
810 .pipe(Effect.forkScoped);
811 const initializeRequest = yield* Queue.take(output).pipe(
812 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(InitializeRequestV1))),
813 );
814 assert.equal(initializeRequest.params.protocolVersion, 2);
815 assert.equal(initializeRequest.params.clientCapabilities?._meta?.["terminal-auth"], true);
816 yield* Queue.offer(
817 input,
818 yield* encodeJsonl(InitializeResponseV1, {
819 jsonrpc: "2.0",
820 id: initializeRequest.id,
821 result: {
822 ...antigravityInitialize,
823 protocolVersion,
824 },
825 }),
826 );
827 const initialized = yield* Fiber.join(initializeFiber);
828 assert.equal(initialized.protocolVersion, protocolVersion);
829 assert.equal(initialized.agentInfo?.name, "antigravity-acp");
830
831 const exchange = <A, E>(effect: Effect.Effect<A, E>, method: string) =>
832 Effect.gen(function* () {
833 const fiber = yield* effect.pipe(Effect.forkScoped);
834 const request = yield* Queue.take(output).pipe(
835 Effect.flatMap(
836 Schema.decodeEffect(Schema.fromJsonString(jsonRpcRequest(method, Schema.Unknown))),
837 ),
838 );
839 yield* Queue.offer(
840 input,
841 yield* encodeJsonl(jsonRpcResponse(Schema.Unknown), {
842 jsonrpc: "2.0",
843 id: request.id,
844 result: {},
845 }),
846 );
847 yield* Fiber.join(fiber);
848 return request.params;
849 });
850 assert.deepEqual(
851 yield* exchange(acp.agent.authenticate({ methodId: "oauth-personal" }), "authenticate"),
852 { methodId: "oauth-personal" },
853 );
854 const mcpServers = [{ name: "fixture", command: "fixture-only", args: [], env: [] }];
855
856 const sessionFiber = yield* acp.agent
857 .createSession({ cwd: process.cwd(), mcpServers })
858 .pipe(Effect.forkScoped);
859 const sessionRequest = yield* Queue.take(output).pipe(
860 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(NewSessionRequestV1))),
861 );
862 assert.deepEqual(sessionRequest.params.mcpServers, mcpServers);
863 yield* Queue.offer(
864 input,
865 yield* encodeJsonl(jsonRpcResponse(Schema.Unknown), {
866 jsonrpc: "2.0",
867 id: sessionRequest.id,
868 result: {
869 sessionId: "pi-session-1",
870 models: {
871 currentModelId: "native-model",
872 availableModels: [{ modelId: "native-model", name: "Native model" }],
873 },
874 },
875 }),
876 );
877 const session = yield* Fiber.join(sessionFiber);
878 assert.equal(session.sessionId, "pi-session-1");
879 assert.equal(session.models?.currentModelId, "native-model");
880 const resume = { sessionId: session.sessionId, cwd: process.cwd(), mcpServers };
881 assert.deepEqual(yield* exchange(acp.agent.resumeSession(resume), "session/resume"), resume);
882 assert.deepEqual(yield* exchange(acp.agent.loadSession(resume), "session/load"), resume);
883 const selectModel = yield* acp.agent
884 .setSessionModel({ sessionId: session.sessionId, modelId: "native-model" })
885 .pipe(Effect.forkScoped);
886 const selection = yield* Queue.take(output).pipe(
887 Effect.flatMap(
888 Schema.decodeEffect(
889 Schema.fromJsonString(
890 jsonRpcRequest(
891 "session/set_model",
892 Schema.Struct({ sessionId: Schema.String, modelId: Schema.String }),
893 ),
894 ),
895 ),
896 ),
897 );
898 assert.equal(selection.params.modelId, "native-model");
899 yield* Queue.offer(
900 input,
901 yield* encodeJsonl(jsonRpcResponse(Schema.Unknown), {
902 jsonrpc: "2.0",
903 id: selection.id,
904 result: {},
905 }),
906 );
907 yield* Fiber.join(selectModel);
908 const selectMode = yield* acp.agent
909 .setSessionMode({ sessionId: session.sessionId, modeId: "yolo" })
910 .pipe(Effect.forkScoped);
911 const modeSelection = yield* Queue.take(output).pipe(
912 Effect.flatMap(
913 Schema.decodeEffect(
914 Schema.fromJsonString(
915 jsonRpcRequest(
916 "session/set_mode",
917 Schema.Struct({ sessionId: Schema.String, modeId: Schema.String }),
918 ),
919 ),
920 ),
921 ),
922 );
923 assert.equal(modeSelection.params.modeId, "yolo");
924 yield* Queue.offer(
925 input,
926 yield* encodeJsonl(jsonRpcResponse(Schema.Unknown), {
927 jsonrpc: "2.0",
928 id: modeSelection.id,
929 result: {},
930 }),
931 );
932 yield* Fiber.join(selectMode);
933
934 yield* acp.handleElicitation(() =>
935 Effect.succeed({ action: "accept", content: { branch: "main" } }),
936 );
937 yield* Queue.offer(
938 input,
939 yield* encodeJsonl(jsonRpcRequest("session/elicitation", Schema.Unknown), {
940 jsonrpc: "2.0",
941 id: "legacy-question",
942 headers: [],
943 method: "session/elicitation",
944 params: {
945 sessionId: session.sessionId,
946 mode: "form",
947 message: "Choose a branch",
948 requestedSchema: { type: "object", properties: {} },
949 },
950 }),
951 );
952 const answer = yield* Queue.take(output).pipe(
953 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(jsonRpcResponse(Schema.Unknown)))),
954 );
955 assert.deepEqual(answer.result, {
956 action: { action: "accept", content: { branch: "main" } },
957 });
958 // Recorded Devin 2026-09-10 called the older underscore method.
959 yield* Queue.offer(
960 input,
961 yield* encodeJsonl(jsonRpcRequest("_session/elicitation", Schema.Unknown), {
962 jsonrpc: "2.0",
963 id: "devin-question",
964 headers: [],
965 method: "_session/elicitation",
966 params: {
967 sessionId: session.sessionId,
968 mode: "form",
969 message: "Proceed?",
970 requestedSchema: { type: "object", properties: {} },
971 },
972 }),
973 );
974 const devinAnswer = yield* Queue.take(output).pipe(
975 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(jsonRpcResponse(Schema.Unknown)))),
976 );
977 assert.deepEqual(devinAnswer.result, {
978 action: { action: "accept", content: { branch: "main" } },
979 });
980 const completed = yield* Deferred.make<void>();
981 yield* acp.handleElicitationComplete(() =>
982 Deferred.succeed(completed, undefined).pipe(Effect.asVoid),
983 );
984 yield* Queue.offer(
985 input,
986 yield* encodeJsonl(jsonRpcNotification("session/elicitation/complete", Schema.Unknown), {
987 jsonrpc: "2.0",
988 method: "session/elicitation/complete",
989 params: { elicitationId: "legacy-login" },
990 }),
991 );
992 yield* Deferred.await(completed);
993
994 const promptFiber = yield* acp.agent
995 .prompt({
996 sessionId: "pi-session-1",
997 prompt: [{ type: "text", text: "hello" }],
998 })
999 .pipe(Effect.forkScoped);
1000 const promptRequest = yield* Queue.take(output).pipe(
1001 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(PromptRequestV1))),
1002 );
1003 yield* Queue.offer(
1004 input,
1005 concatBytes([
1006 yield* encodeJsonl(
1007 jsonRpcNotification("session/update", AcpSchemaV1.SessionNotification),
1008 {
1009 jsonrpc: "2.0",
1010 method: "session/update",
1011 params: {
1012 sessionId: "pi-session-1",
1013 update: {
1014 sessionUpdate: "available_commands_update",
1015 availableCommands: [
1016 { name: "review", description: "Review changes", input: { hint: "scope" } },
1017 ],
1018 },
1019 },
1020 },
1021 ),
1022 yield* encodeJsonl(PromptResponseV1, {
1023 jsonrpc: "2.0",
1024 id: promptRequest.id,
1025 result: { stopReason: "end_turn" },
1026 }),
1027 ]),
1028 );
1029 assert.deepEqual(yield* Fiber.join(promptFiber), { stopReason: "end_turn" });
1030 const cancelledPrompt = yield* acp.agent
1031 .prompt({ sessionId: "pi-session-1", prompt: [{ type: "text", text: "retry" }] })
1032 .pipe(Effect.forkScoped);
1033 const cancelledRequest = yield* Queue.take(output).pipe(
1034 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(PromptRequestV1))),
1035 );
1036 yield* Queue.offer(
1037 input,
1038 yield* encodeJsonl(Schema.Unknown, {
1039 jsonrpc: "2.0",
1040 id: cancelledRequest.id,
1041 result: { stopReason: "cancelled", usage: {} },
1042 }),
1043 );
1044 assert.deepEqual(yield* Fiber.join(cancelledPrompt), { stopReason: "cancelled" });
1045 assert.deepEqual(yield* Ref.get(updates), [
1046 {
1047 sessionId: "pi-session-1",
1048 update: {
1049 sessionUpdate: "available_commands_update",
1050 availableCommands: [
1051 {
1052 name: "review",
1053 description: "Review changes",
1054 input: { type: "text", hint: "scope" },
1055 },
1056 ],
1057 },
1058 },
1059 ]);
1060 yield* exchange(acp.agent.logout({}), "logout");
1061 yield* Scope.close(scope, Exit.void);
1062 }),
1063 );
1064
1065 it.effect.each([
1066 { shape: "v1", deleteCapability: {} },
1067 { shape: "v2", deleteCapability: {} },
1068 { shape: "v2", deleteCapability: undefined },
1069 { shape: "v2", deleteCapability: null },
1070 ])(
1071 "gates session/delete for $shape with delete=$deleteCapability",
1072 ({ shape, deleteCapability }) =>
1073 Effect.gen(function* () {
1074 const { stdio, input, output } = yield* makeInMemoryStdio();
1075 const scope = yield* Scope.make();
1076 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1077 const deleteSession = acp.agent.deleteSession({ sessionId: "kiro-session-1" });
1078
1079 const initializeFiber = yield* acp.agent
1080 .initialize({
1081 protocolVersion: 1,
1082 clientCapabilities: {
1083 fs: { readTextFile: false, writeTextFile: false },
1084 terminal: false,
1085 },
1086 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
1087 })
1088 .pipe(Effect.forkScoped);
1089 const initializeRequest = yield* Queue.take(output).pipe(
1090 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(InitializeRequestV1))),
1091 );
1092 yield* Queue.offer(
1093 input,
1094 shape === "v1"
1095 ? yield* encodeJsonl(InitializeResponseV1, {
1096 jsonrpc: "2.0",
1097 id: initializeRequest.id,
1098 result: {
1099 protocolVersion: 1,
1100 agentInfo: { name: "kiro-acp", version: "0.0.0" },
1101 agentCapabilities: {
1102 sessionCapabilities: { list: {}, resume: {}, close: {}, delete: {} },
1103 },
1104 },
1105 })
1106 : yield* encodeJsonl(InitializeResponse, {
1107 jsonrpc: "2.0",
1108 id: initializeRequest.id,
1109 result: {
1110 protocolVersion: 2,
1111 info: { name: "v2-agent", version: "0.0.0" },
1112 capabilities: {
1113 session: deleteCapability === undefined ? {} : { delete: deleteCapability },
1114 },
1115 },
1116 }),
1117 );
1118 yield* Fiber.join(initializeFiber);
1119
1120 const deleteFailed = yield* Deferred.make<AcpError.AcpError>();
1121 const deleteFiber = yield* deleteSession.pipe(
1122 Effect.tapError((error) => Deferred.succeed(deleteFailed, error)),
1123 Effect.forkScoped,
1124 );
1125 const outcome = yield* Effect.raceFirst(
1126 Queue.take(output).pipe(Effect.map((line) => ({ line }))),
1127 Deferred.await(deleteFailed).pipe(Effect.map((error) => ({ error }))),
1128 );
1129 if ("error" in outcome) {
1130 if (deleteCapability != null) {
1131 return yield* outcome.error;
1132 }
1133 assert.equal(outcome.error._tag, "AcpRequestError");
1134 assert.equal(
1135 outcome.error._tag === "AcpRequestError" ? outcome.error.code : undefined,
1136 -32601,
1137 );
1138 yield* Scope.close(scope, Exit.void);
1139 return;
1140 }
1141 assert.exists(deleteCapability, "session/delete reached transport without its capability");
1142 const deleteRequest = yield* Schema.decodeEffect(
1143 Schema.fromJsonString(jsonRpcRequest("session/delete", AcpSchemaV1.DeleteSessionRequest)),
1144 )(outcome.line);
1145 assert.equal(deleteRequest.params.sessionId, "kiro-session-1");
1146 yield* Queue.offer(
1147 input,
1148 yield* encodeJsonl(jsonRpcResponse(Schema.Unknown), {
1149 jsonrpc: "2.0",
1150 id: deleteRequest.id,
1151 result: {},
1152 }),
1153 );
1154 assert.deepEqual(yield* Fiber.join(deleteFiber), {});
1155 yield* Scope.close(scope, Exit.void);
1156 }),
1157 );
1158
1159 it.effect("preserves exact ids for parallel requests with identical payloads", () =>
1160 Effect.gen(function* () {
1161 const { stdio, input, output } = yield* makeInMemoryStdio();
1162 const scope = yield* Scope.make();
1163 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1164 const contexts = yield* Ref.make<Array<AcpProtocol.AcpRequestContext>>([]);
1165 yield* acp.handleRequestPermission((_request, context) =>
1166 Ref.update(contexts, (current) => [...current, context]).pipe(
1167 Effect.as({ outcome: { outcome: "selected", optionId: "allow" } } as const),
1168 ),
1169 );
1170 const payload = {
1171 sessionId: "session-1",
1172 title: "Shared tool",
1173 subject: {
1174 type: "tool_call" as const,
1175 toolCall: { toolCallId: "shared-tool", title: "Shared tool" },
1176 },
1177 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" as const }],
1178 };
1179 yield* Queue.offer(
1180 input,
1181 concatBytes(
1182 yield* Effect.forEach(["permission-a", "permission-b"], (id) =>
1183 encodeJsonl(PermissionRequest, {
1184 jsonrpc: "2.0",
1185 id,
1186 method: "session/request_permission",
1187 params: payload,
1188 headers: [],
1189 }),
1190 ),
1191 ),
1192 );
1193
1194 const decodeResponse = Schema.decodeEffect(Schema.fromJsonString(PermissionResponse));
1195 const responses = yield* Effect.all([
1196 Queue.take(output).pipe(Effect.flatMap(decodeResponse)),
1197 Queue.take(output).pipe(Effect.flatMap(decodeResponse)),
1198 ]);
1199 assert.deepEqual(responses.map((response) => response.id).toSorted(), [
1200 "permission-a",
1201 "permission-b",
1202 ]);
1203 assert.deepEqual(
1204 (yield* Ref.get(contexts))
1205 .map(({ requestId, method }) => ({ requestId, method }))
1206 .toSorted((left, right) => left.requestId.localeCompare(right.requestId)),
1207 [
1208 { requestId: "permission-a", method: "session/request_permission" },
1209 { requestId: "permission-b", method: "session/request_permission" },
1210 ],
1211 );
1212 yield* Scope.close(scope, Exit.void);
1213 }),
1214 );
1215
1216 it.effect("answers each request whose handler dies, and keeps reading", () =>
1217 Effect.gen(function* () {
1218 const errorLogs = yield* Queue.unbounded<string>();
1219 const logger = Logger.make(({ logLevel, message }) => {
1220 if (logLevel === "Error") Queue.offerUnsafe(errorLogs, String([message].flat()[0]));
1221 });
1222 const { stdio, input, output } = yield* makeInMemoryStdio();
1223 const scope = yield* Scope.make();
1224 const acp = yield* AcpClient.make(stdio).pipe(
1225 Effect.provideService(Scope.Scope, scope),
1226 Effect.provide(Logger.layer([logger])),
1227 );
1228 const bug = () => Effect.die(new Error("handler bug"));
1229 yield* acp.handleRequestPermission(bug);
1230 yield* acp.handleExtRequest("x/dies", Schema.Unknown, bug);
1231 yield* acp.handleExtNotification("x/notification-dies", Schema.Unknown, bug);
1232 yield* acp.handleSessionUpdate(bug);
1233 const updates = yield* Queue.unbounded<string>();
1234 yield* acp.handleSessionUpdate((notification) =>
1235 Queue.offer(updates, notification.sessionId).pipe(Effect.asVoid),
1236 );
1237 yield* acp.handleExtRequest("x/test", Schema.Struct({ hello: Schema.String }), () =>
1238 Effect.succeed({ ok: true }),
1239 );
1240 const send = <E>(line: Effect.Effect<Uint8Array, E>) =>
1241 Effect.flatMap(line, (bytes) => Queue.offer(input, bytes));
1242 const decodeDie = Schema.decodeEffect(Schema.fromJsonString(DieResponse));
1243 const next = <A>(queue: Queue.Dequeue<A>) =>
1244 TestClock.withLive(Queue.take(queue).pipe(Effect.timeout("2 seconds")));
1245
1246 yield* send(
1247 encodeJsonl(PermissionRequest, {
1248 jsonrpc: "2.0",
1249 id: "permission-a",
1250 method: "session/request_permission",
1251 params: {
1252 sessionId: "session-1",
1253 title: "Tool",
1254 subject: {
1255 type: "tool_call" as const,
1256 toolCall: { toolCallId: "tool-1", title: "Tool" },
1257 },
1258 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" as const }],
1259 },
1260 headers: [],
1261 }),
1262 );
1263 assert.equal((yield* next(output).pipe(Effect.flatMap(decodeDie))).id, "permission-a");
1264
1265 yield* send(
1266 encodeJsonl(jsonRpcRequest("x/dies", Schema.Unknown), {
1267 jsonrpc: "2.0",
1268 id: "ext-a",
1269 method: "x/dies",
1270 params: {},
1271 headers: [],
1272 }),
1273 );
1274 const extDied = yield* next(output).pipe(
1275 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(ErrorResponse))),
1276 );
1277 assert.equal(extDied.id, "ext-a");
1278
1279 yield* send(
1280 encodeJsonl(jsonRpcNotification("x/notification-dies", Schema.Unknown), {
1281 jsonrpc: "2.0",
1282 method: "x/notification-dies",
1283 params: {},
1284 }),
1285 );
1286 yield* send(
1287 encodeJsonl(SessionUpdateNotification, {
1288 jsonrpc: "2.0",
1289 method: "session/update",
1290 params: {
1291 sessionId: "session-1",
1292 update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "hi" } },
1293 },
1294 }),
1295 );
1296
1297 assert.equal(yield* next(updates), "session-1");
1298
1299 yield* send(
1300 encodeJsonl(ExtRequest, {
1301 jsonrpc: "2.0",
1302 id: "ext-b",
1303 method: "x/test",
1304 params: { hello: "world" },
1305 headers: [],
1306 }),
1307 );
1308 const answered = yield* next(output).pipe(
1309 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(ExtResponse))),
1310 );
1311 assert.deepEqual([answered.id, answered.result], ["ext-b", { ok: true }]);
1312
1313 assert.deepEqual((yield* Queue.clear(errorLogs)).toSorted(), [
1314 "ACP extension request handler failed for 'x/dies'",
1315 "ACP notification handler failed",
1316 "ACP notification handler failed",
1317 "ACP request handler failed for 'session/request_permission'",
1318 ]);
1319 yield* Scope.close(scope, Exit.void);
1320 }),
1321 );
1322
1323 it.effect("hands titled multi-select elicitation fields to the handler", () =>
1324 Effect.gen(function* () {
1325 const { stdio, input, output } = yield* makeInMemoryStdio();
1326 const scope = yield* Scope.make();
1327 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1328 const received = yield* Deferred.make<AcpSchema.CreateElicitationRequest>();
1329 yield* acp.handleElicitation((request) =>
1330 Deferred.succeed(received, request).pipe(
1331 Effect.as({ action: "accept" as const, content: { areas: ["ui"] } }),
1332 ),
1333 );
1334 const requestedSchema = {
1335 type: "object",
1336 properties: {
1337 areas: {
1338 type: "array",
1339 title: "Areas",
1340 items: {
1341 anyOf: [
1342 { const: "api", title: "API", description: "Server routes" },
1343 { const: "ui", title: "Interface" },
1344 ],
1345 },
1346 },
1347 },
1348 required: ["areas"],
1349 };
1350
1351 yield* Queue.offer(
1352 input,
1353 yield* encodeJsonl(jsonRpcRequest("elicitation/create", Schema.Unknown), {
1354 jsonrpc: "2.0",
1355 id: "elicitation",
1356 method: "elicitation/create",
1357 params: {
1358 sessionId: "session-1",
1359 mode: "form",
1360 message: "Pick areas",
1361 requestedSchema,
1362 },
1363 headers: [],
1364 }),
1365 );
1366 const response = yield* Queue.take(output).pipe(
1367 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(ElicitationResponse))),
1368 );
1369 assert.deepEqual(response.result, { action: "accept", content: { areas: ["ui"] } });
1370 const request = yield* Deferred.await(received);
1371 assert.deepEqual("requestedSchema" in request && request.requestedSchema, requestedSchema);
1372 yield* Scope.close(scope, Exit.void);
1373 }),
1374 );
1375
1376 it.effect(
1377 "routes a standard prompt response after Grok extension notifications in the same batch",
1378 () =>
1379 Effect.gen(function* () {
1380 const { stdio, input, output } = yield* makeInMemoryStdio();
1381 const scope = yield* Scope.make();
1382 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1383
1384 const promptFiber = yield* acp.agent
1385 .prompt({
1386 sessionId: "grok-session-1",
1387 prompt: [{ type: "text", text: "run the ls command" }],
1388 })
1389 .pipe(Effect.forkScoped);
1390
1391 const outbound = yield* Queue.take(output);
1392 const decodedPrompt = yield* decodePromptRequestLine(outbound);
1393
1394 const responseBatch = concatBytes(
1395 yield* Effect.all([
1396 encodeJsonl(XAiQueueChangedNotification, {
1397 jsonrpc: "2.0",
1398 method: "_x.ai/queue/changed",
1399 params: { sessionId: "grok-session-1", entries: [] },
1400 }),
1401 encodeJsonl(XAiPromptCompleteNotification, {
1402 jsonrpc: "2.0",
1403 method: "_x.ai/session/prompt_complete",
1404 params: {
1405 sessionId: "grok-session-1",
1406 promptId: "prompt-1",
1407 stopReason: "end_turn",
1408 agentResult: null,
1409 },
1410 }),
1411 encodeJsonl(XAiSessionsChangedNotification, {
1412 jsonrpc: "2.0",
1413 method: "_x.ai/sessions/changed",
1414 params: {
1415 upserted: [
1416 {
1417 sessionId: "grok-session-1",
1418 title: null,
1419 cwd: process.cwd(),
1420 isWorktree: false,
1421 modelId: "grok-composer-2.5-fast",
1422 yolo: false,
1423 activity: "idle",
1424 resident: true,
1425 lastChangeUnixMs: 1_710_000_000_000,
1426 origin: { kind: "local" },
1427 },
1428 ],
1429 removed: [],
1430 },
1431 }),
1432 encodeJsonl(PromptResponse, {
1433 jsonrpc: "2.0",
1434 id: decodedPrompt.id,
1435 result: {},
1436 }),
1437 encodeJsonl(SessionUpdateNotification, {
1438 jsonrpc: "2.0",
1439 method: "session/update",
1440 params: {
1441 sessionId: "grok-session-1",
1442 update: {
1443 sessionUpdate: "state_update",
1444 state: "idle",
1445 stopReason: "end_turn",
1446 _meta: {
1447 sessionId: "grok-session-1",
1448 requestId: "prompt-1",
1449 promptId: "prompt-1",
1450 modelId: "grok-composer-2.5-fast",
1451 },
1452 },
1453 },
1454 }),
1455 ]),
1456 );
1457 yield* Queue.offer(input, responseBatch);
1458
1459 assert.deepEqual(yield* Fiber.join(promptFiber), {
1460 stopReason: "end_turn",
1461 _meta: {
1462 sessionId: "grok-session-1",
1463 requestId: "prompt-1",
1464 promptId: "prompt-1",
1465 modelId: "grok-composer-2.5-fast",
1466 },
1467 });
1468 yield* Scope.close(scope, Exit.void);
1469 }),
1470 );
1471
1472 it.effect("returns the ACP v2 idle error as the prompt result", () =>
1473 Effect.gen(function* () {
1474 const { stdio, input, output } = yield* makeInMemoryStdio();
1475 const acp = yield* AcpClient.make(stdio);
1476 const error = { code: -32000, message: "Missing Authentication header" };
1477 const prompt = yield* acp.agent
1478 .prompt({ sessionId: "idle-error", prompt: [{ type: "text", text: "Hello" }] })
1479 .pipe(Effect.forkScoped);
1480 const request = yield* decodePromptRequestLine(yield* Queue.take(output));
1481 yield* Queue.offer(
1482 input,
1483 concatBytes([
1484 yield* encodeJsonl(jsonRpcResponse(Schema.Unknown), {
1485 jsonrpc: "2.0",
1486 id: request.id,
1487 result: { messageId: `user-${request.id}` },
1488 }),
1489 yield* encodeJsonl(SessionUpdateNotification, {
1490 jsonrpc: "2.0",
1491 method: "session/update",
1492 params: {
1493 sessionId: "idle-error",
1494 update: { sessionUpdate: "state_update", state: "idle", stopReason: "error", error },
1495 },
1496 }),
1497 ]),
1498 );
1499 assert.deepEqual(yield* Fiber.join(prompt), { stopReason: "error", error });
1500 }),
1501 );
1502
1503 it.effect("routes MCP-over-ACP connect, message, notification, and disconnect callbacks", () =>
1504 Effect.gen(function* () {
1505 const handle = yield* makeHandle({ ACP_MOCK_MCP_OVER_ACP: "1" });
1506 const scope = yield* Scope.make();
1507 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
1508 const methods = yield* Ref.make<Array<string>>([]);
1509
1510 yield* Effect.gen(function* () {
1511 const acp = yield* AcpClient.AcpClient;
1512 yield* acp.handleRequestPermission(() =>
1513 Effect.succeed({ outcome: { outcome: "selected", optionId: "allow" } }),
1514 );
1515 yield* acp.handleElicitation(() => Effect.succeed({ action: "decline" }));
1516 yield* acp.handleExtRequest(
1517 "x/typed_request",
1518 Schema.Struct({ message: Schema.String }),
1519 () => Effect.succeed({ ok: true }),
1520 );
1521 yield* acp.handleExtNotification(
1522 "x/typed_notification",
1523 Schema.Struct({ count: Schema.Number }),
1524 () => Effect.void,
1525 );
1526 yield* acp.handleMcpConnect(() =>
1527 Ref.update(methods, (current) => [...current, "connect"]).pipe(
1528 Effect.as({ connectionId: "connection-1" }),
1529 ),
1530 );
1531 yield* acp.handleMcpMessage(() =>
1532 Ref.update(methods, (current) => [...current, "message"]).pipe(Effect.as({ tools: [] })),
1533 );
1534 yield* acp.handleMcpNotification(() =>
1535 Ref.update(methods, (current) => [...current, "notification"]),
1536 );
1537 yield* acp.handleMcpDisconnect(() =>
1538 Ref.update(methods, (current) => [...current, "disconnect"]).pipe(Effect.as({})),
1539 );
1540 yield* acp.agent.initialize({
1541 protocolVersion: 2,
1542 clientCapabilities: { elicitation: { form: {} } },
1543 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
1544 });
1545 const session = yield* acp.agent.createSession({ cwd: process.cwd(), mcpServers: [] });
1546 yield* acp.agent.prompt({
1547 sessionId: session.sessionId,
1548 prompt: [{ type: "text", text: "exercise MCP" }],
1549 });
1550 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
1551
1552 assert.deepEqual(yield* Ref.get(methods), [
1553 "connect",
1554 "message",
1555 "notification",
1556 "disconnect",
1557 ]);
1558 }),
1559 );
1560
1561 it.effect("preserves future content and session-update variants", () =>
1562 Effect.gen(function* () {
1563 const handle = yield* makeHandle({ ACP_MOCK_UNKNOWN_VARIANTS: "1" });
1564 const scope = yield* Scope.make();
1565 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
1566 const updates = yield* Ref.make<Array<AcpCompat.SessionNotification>>([]);
1567
1568 yield* Effect.gen(function* () {
1569 const acp = yield* AcpClient.AcpClient;
1570 yield* acp.handleRequestPermission(() =>
1571 Effect.succeed({ outcome: { outcome: "selected", optionId: "allow" } }),
1572 );
1573 yield* acp.handleElicitation(() => Effect.succeed({ action: "decline" }));
1574 yield* acp.handleExtRequest(
1575 "x/typed_request",
1576 Schema.Struct({ message: Schema.String }),
1577 () => Effect.succeed({ ok: true }),
1578 );
1579 yield* acp.handleExtNotification(
1580 "x/typed_notification",
1581 Schema.Struct({ count: Schema.Number }),
1582 () => Effect.void,
1583 );
1584 yield* acp.handleSessionUpdate((update) =>
1585 Ref.update(updates, (current) => [...current, update]),
1586 );
1587 yield* acp.agent.initialize({
1588 protocolVersion: 2,
1589 clientCapabilities: { elicitation: { form: {} } },
1590 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
1591 });
1592 const session = yield* acp.agent.createSession({ cwd: process.cwd(), mcpServers: [] });
1593 yield* acp.agent.prompt({
1594 sessionId: session.sessionId,
1595 prompt: [{ type: "text", text: "exercise future variants" }],
1596 });
1597 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
1598
1599 const received = yield* Ref.get(updates);
1600 assert.deepEqual(received[0]?.update, {
1601 sessionUpdate: "agent_message_chunk",
1602 messageId: "future-content",
1603 content: {
1604 type: "_t3_unknown",
1605 originalType: "chart",
1606 raw: { type: "chart", points: [] },
1607 },
1608 });
1609 assert.deepEqual(received[1]?.update, {
1610 sessionUpdate: "_t3_unknown",
1611 originalSessionUpdate: "timeline_update",
1612 raw: { sessionUpdate: "timeline_update", entries: [] },
1613 });
1614 }),
1615 );
1616
1617 it.effect("normalizes ACP v1 session notices and null tool names to v2 semantics", () =>
1618 Effect.gen(function* () {
1619 const { stdio, input, output } = yield* makeInMemoryStdio();
1620 const scope = yield* Scope.make();
1621 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1622 const initializeFiber = yield* acp.agent
1623 .initialize({ protocolVersion: 1, clientCapabilities: { session: { notices: {} } } })
1624 .pipe(Effect.forkScoped);
1625 const initializeRequest = yield* Queue.take(output).pipe(
1626 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(InitializeRequestV1))),
1627 );
1628 yield* Queue.offer(
1629 input,
1630 yield* encodeJsonl(InitializeResponseV1, {
1631 jsonrpc: "2.0",
1632 id: initializeRequest.id,
1633 result: { protocolVersion: 1 },
1634 }),
1635 );
1636 yield* Fiber.join(initializeFiber);
1637
1638 const notice = {
1639 sessionUpdate: "notice",
1640 severity: "warning",
1641 title: "MCP server unavailable",
1642 description: "Continuing without it.",
1643 } as const;
1644 const untitled = { sessionUpdate: "notice", severity: "info" } as const;
1645 const toolUpdate = {
1646 sessionUpdate: "tool_call_update",
1647 toolCallId: "c",
1648 status: "completed",
1649 };
1650 for (const update of [notice, untitled, { ...toolUpdate, name: null }]) {
1651 yield* Queue.offer(
1652 input,
1653 yield* encodeJsonl(SessionUpdateNotification, {
1654 jsonrpc: "2.0",
1655 method: "session/update",
1656 params: { sessionId: "session-1", update },
1657 }),
1658 );
1659 }
1660 const received = yield* acp.raw.notifications.pipe(Stream.take(3), Stream.runCollect);
1661 assert.deepEqual(
1662 Array.from(received, (event) =>
1663 event._tag === "SessionUpdate" ? event.params.update : undefined,
1664 ),
1665 [
1666 notice,
1667 { sessionUpdate: "_t3_unknown", originalSessionUpdate: "notice", raw: untitled },
1668 toolUpdate,
1669 ],
1670 );
1671 yield* Scope.close(scope, Exit.void);
1672 }),
1673 );
1674 });
1675
1676 const elicitationForm = {
1677 sessionId: "session-1",
1678 mode: "form" as const,
1679 message: "Continue?",
1680 requestedSchema: {
1681 type: "object" as const,
1682 properties: { choice: { type: "string" as const } },
1683 required: ["choice"],
1684 },
1685 };
1686 const decodeWireResponse = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
1687 const decodeWireError = Schema.decodeEffect(
1688 Schema.fromJsonString(Schema.Struct({ error: Schema.Struct({ code: Schema.Finite }) })),
1689 );
1690
1691 it.effect.each(["accept", "decline", "cancel"] as const)(
1692 "returns a flat %s action to the SDK and preserves the legacy response",
1693 (action) =>
1694 Effect.gen(function* () {
1695 for (const method of ["elicitation/create", "session/elicitation"]) {
1696 const { stdio, input, output } = yield* makeInMemoryStdio();
1697 const acp = yield* AcpClient.make(stdio);
1698 const answer = action === "accept" ? { action, content: { choice: "yes" } } : { action };
1699 const response = { ...answer, _meta: { trace: "fixture" } };
1700 yield* acp.handleElicitation((request) => {
1701 assert.deepEqual(request, elicitationForm);
1702 return Effect.succeed(response);
1703 });
1704 yield* Queue.offer(
1705 input,
1706 yield* encodeJsonl(jsonRpcRequest(method, AcpSchema.CreateElicitationRequest), {
1707 jsonrpc: "2.0",
1708 id: 71,
1709 headers: [],
1710 method,
1711 params: elicitationForm,
1712 }),
1713 );
1714 const received = yield* decodeWireResponse(yield* Queue.take(output));
1715 assert.deepEqual(received, {
1716 jsonrpc: "2.0",
1717 id: 71,
1718 result:
1719 method === "elicitation/create" ? response : { action: answer, _meta: response._meta },
1720 });
1721 }
1722 }),
1723 );
1724
1725 it.effect.each([1, 2] as const)(
1726 "rejects a URL elicitation the client did not advertise on wire v%s",
1727 (wireVersion) =>
1728 Effect.gen(function* () {
1729 const { stdio, input, output } = yield* makeInMemoryStdio();
1730 const acp = yield* AcpClient.make(stdio);
1731 const init = yield* acp.agent
1732 .initialize({ protocolVersion: 2, clientCapabilities: { elicitation: { form: {} } } })
1733 .pipe(Effect.forkChild);
1734 const initialize = yield* decodeWireResponse(yield* Queue.take(output));
1735 yield* Queue.offer(
1736 input,
1737 yield* encodeJsonl(jsonRpcResponse(Schema.Unknown), {
1738 jsonrpc: "2.0",
1739 id: (initialize as { id: number }).id,
1740 result:
1741 wireVersion === 2
1742 ? { protocolVersion: 2, info: { name: "fixture", version: "1" }, capabilities: {} }
1743 : { protocolVersion: 1, agentCapabilities: {} },
1744 }),
1745 );
1746 yield* Fiber.join(init);
1747 const calls = yield* Ref.make(0);
1748 yield* acp.handleElicitation(() =>
1749 Ref.update(calls, (n) => n + 1).pipe(Effect.as({ action: "accept" as const })),
1750 );
1751 yield* Queue.offer(
1752 input,
1753 yield* encodeJsonl(jsonRpcRequest("elicitation/create", Schema.Unknown), {
1754 jsonrpc: "2.0",
1755 id: 81,
1756 headers: [],
1757 method: "elicitation/create",
1758 params: {
1759 sessionId: "session-1",
1760 mode: "url",
1761 message: "Sign in",
1762 url: "https://example.test/auth",
1763 elicitationId: "auth-1",
1764 },
1765 }),
1766 );
1767 const response = yield* decodeWireError(yield* Queue.take(output));
1768 assert.equal(response.error.code, -32602);
1769 assert.equal(yield* Ref.get(calls), 0);
1770 }).pipe(Effect.scoped),
1771 );
1772
1773 it.effect.each(["elicitation/complete", "session/elicitation/complete"])(
1774 "delivers %s notifications to the completion handler",
1775 (method) =>
1776 Effect.gen(function* () {
1777 const { stdio, input } = yield* makeInMemoryStdio();
1778 const acp = yield* AcpClient.make(stdio);
1779 const received = yield* Deferred.make<AcpSchema.CompleteElicitationNotification>();
1780 yield* acp.handleElicitationComplete((notification) =>
1781 Deferred.succeed(received, notification).pipe(Effect.asVoid),
1782 );
1783 yield* Queue.offer(
1784 input,
1785 yield* encodeJsonl(jsonRpcNotification(method, AcpSchema.CompleteElicitationNotification), {
1786 jsonrpc: "2.0",
1787 method,
1788 params: { elicitationId: "elicitation-1" },
1789 }),
1790 );
1791 assert.deepEqual(yield* Deferred.await(received), { elicitationId: "elicitation-1" });
1792 }),
1793 );
1794
1795 it.effect("rejects malformed SDK elicitation without calling the question handler", () =>
1796 Effect.gen(function* () {
1797 const { stdio, input, output } = yield* makeInMemoryStdio();
1798 const acp = yield* AcpClient.make(stdio);
1799 let calls = 0;
1800 yield* acp.handleElicitation(() => {
1801 calls++;
1802 return Effect.succeed({ action: "cancel" as const });
1803 });
1804 yield* Queue.offer(
1805 input,
1806 yield* encodeJsonl(jsonRpcRequest("elicitation/create", Schema.Unknown), {
1807 jsonrpc: "2.0",
1808 id: 73,
1809 headers: [],
1810 method: "elicitation/create",
1811 params: { ...elicitationForm, message: 123 },
1812 }),
1813 );
1814 const response = yield* decodeWireError(yield* Queue.take(output));
1815 assert.equal(response.error.code, -32602);
1816 assert.equal(calls, 0);
1817 }),
1818 );
1819
1820 it.effect("returns method-not-found when SDK elicitation has no question handler", () =>
1821 Effect.gen(function* () {
1822 const { stdio, input, output } = yield* makeInMemoryStdio();
1823 yield* AcpClient.make(stdio);
1824 yield* Queue.offer(
1825 input,
1826 yield* encodeJsonl(jsonRpcRequest("elicitation/create", AcpSchema.CreateElicitationRequest), {
1827 jsonrpc: "2.0",
1828 id: 74,
1829 headers: [],
1830 method: "elicitation/create",
1831 params: elicitationForm,
1832 }),
1833 );
1834 const response = yield* decodeWireError(yield* Queue.take(output));
1835 assert.equal(response.error.code, -32601);
1836 }),
1837 );