Open History to see the last commit
1import * as Path from "effect/Path";
2import * as Cause from "effect/Cause";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Fiber from "effect/Fiber";
7import * as Layer from "effect/Layer";
8import * as Queue from "effect/Queue";
9import * as Ref from "effect/Ref";
10import * as Schema from "effect/Schema";
11import * as Scope from "effect/Scope";
12import * as Stream from "effect/Stream";
13import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
14
15import * as NodeServices from "@effect/platform-node/NodeServices";
16import { it, assert } from "@effect/vitest";
17
18import * as AcpClient from "./client.ts";
19import * as AcpSchema from "./_generated/schema.gen.ts";
20import * as AcpSchemaV1 from "./_generated/schema-v1.gen.ts";
21import * as AcpError from "./errors.ts";
22import type * as AcpCompat from "./compat.ts";
23import type * as AcpProtocol from "./protocol.ts";
24import {
25 encodeJsonl,
26 jsonRpcNotification,
27 jsonRpcRequest,
28 jsonRpcResponse,
29} from "./_internal/shared.ts";
30import { makeInMemoryStdio } from "./_internal/stdio.ts";
31
32const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
33const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
34const InitializeRequestV1 = jsonRpcRequest("initialize", AcpSchemaV1.InitializeRequest);
35const InitializeResponseV1 = jsonRpcResponse(AcpSchemaV1.InitializeResponse);
36const NewSessionRequestV1 = jsonRpcRequest("session/new", AcpSchemaV1.NewSessionRequest);
37const PromptRequestV1 = jsonRpcRequest("session/prompt", AcpSchemaV1.PromptRequest);
38const PromptResponseV1 = jsonRpcResponse(AcpSchemaV1.PromptResponse);
39const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
40const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
41const PromptRequest = jsonRpcRequest("session/prompt", AcpSchema.PromptRequest);
42const PromptResponse = jsonRpcResponse(AcpSchema.PromptResponse);
43const SessionUpdateNotification = jsonRpcNotification("session/update", Schema.Unknown);
44const PermissionRequest = jsonRpcRequest(
45 "session/request_permission",
46 AcpSchema.RequestPermissionRequest,
47);
48const PermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
49const ElicitationRequest = jsonRpcRequest("elicitation/create", AcpSchema.CreateElicitationRequest);
50const ElicitationResponse = jsonRpcResponse(AcpSchema.CreateElicitationResponse);
51const decodePromptRequestLine = Schema.decodeEffect(Schema.fromJsonString(PromptRequest));
52const XAiPromptCompleteNotification = jsonRpcNotification(
53 "_x.ai/session/prompt_complete",
54 Schema.Struct({
55 sessionId: Schema.String,
56 promptId: Schema.String,
57 stopReason: Schema.String,
58 agentResult: Schema.NullOr(Schema.Unknown),
59 }),
60);
61const XAiQueueChangedNotification = jsonRpcNotification(
62 "_x.ai/queue/changed",
63 Schema.Struct({
64 sessionId: Schema.String,
65 entries: Schema.Array(Schema.Unknown),
66 }),
67);
68const XAiSessionsChangedNotification = jsonRpcNotification(
69 "_x.ai/sessions/changed",
70 Schema.Struct({
71 upserted: Schema.Array(Schema.Unknown),
72 removed: Schema.Array(Schema.Unknown),
73 }),
74);
75const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
76 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
77);
78const mockPeerArgs = (path: string) => [path];
79const mockStartupNotice = "Mock ACP startup notice";
80const stripMockStartupNotice = (stdout: ChildProcessSpawner.ChildProcessHandle["stdout"]) =>
81 stdout.pipe(
82 Stream.decodeText,
83 Stream.splitLines,
84 Stream.filter((line) => line !== mockStartupNotice),
85 Stream.map((line) => `${line}\n`),
86 Stream.encodeText,
87 );
88
89function concatBytes(chunks: ReadonlyArray<Uint8Array>): Uint8Array {
90 const batch = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
91 let offset = 0;
92 for (const chunk of chunks) {
93 batch.set(chunk, offset);
94 offset += chunk.length;
95 }
96 return batch;
97}
98
99it.layer(NodeServices.layer)("effect-acp client", (it) => {
100 const makeHandle = (env?: Record<string, string>) =>
101 Effect.gen(function* () {
102 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
103 const path = yield* Path.Path;
104 const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
105 cwd: path.join(import.meta.dirname, ".."),
106 ...(env ? { env: { ...process.env, ...env } } : {}),
107 });
108 return yield* spawner.spawn(command);
109 });
110
111 it.effect("transforms fragmented stdout before parsing and preserves UTF-8", () =>
112 Effect.gen(function* () {
113 const handle = yield* makeHandle({ ACP_MOCK_STDOUT_PREFIX: `${mockStartupNotice}\n` });
114 yield* Effect.gen(function* () {
115 const acp = yield* AcpClient.AcpClient;
116 const initialized = yield* acp.agent.initialize({ protocolVersion: 1 });
117 assert.equal(initialized.protocolVersion, 2);
118
119 const echoed = yield* acp.raw.request("x/echo", { message: "café" });
120 assert.deepEqual(echoed, {
121 echoedMethod: "x/echo",
122 echoedParams: { message: "café" },
123 });
124 }).pipe(
125 Effect.provide(
126 AcpClient.layerChildProcess(handle, {
127 transformStdout: (stdout) =>
128 stdout.pipe(
129 Stream.flatMap((chunk) =>
130 Stream.fromIterable(Array.from(chunk, (byte) => Uint8Array.of(byte))),
131 ),
132 stripMockStartupNotice,
133 ),
134 }),
135 ),
136 );
137 }),
138 );
139
140 it.effect("reports malformed JSON that remains after a stdout transform", () =>
141 Effect.gen(function* () {
142 const handle = yield* makeHandle({
143 ACP_MOCK_STDOUT_PREFIX: `${mockStartupNotice}\n`,
144 ACP_MOCK_MALFORMED_OUTPUT: "1",
145 });
146 const termination = yield* Deferred.make<AcpError.AcpError>();
147 const error = yield* Deferred.await(termination).pipe(
148 Effect.provide(
149 AcpClient.layerChildProcess(handle, {
150 transformStdout: stripMockStartupNotice,
151 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
152 }),
153 ),
154 );
155
156 if (error._tag !== "AcpProtocolParseError") {
157 return assert.fail(`Expected a parse error, got ${error._tag}`);
158 }
159 assert.equal(error.operation, "decode-wire-message");
160 }),
161 );
162
163 it.effect("preserves stdout transform errors without logging rejected input", () =>
164 Effect.gen(function* () {
165 const privateNotice = "Mock sign-in URL: https://example.test/login?token=mock-private-token";
166 const handle = yield* makeHandle({ ACP_MOCK_STDOUT_PREFIX: `${privateNotice}\n` });
167 const termination = yield* Deferred.make<AcpError.AcpError>();
168 const logs = yield* Ref.make<Array<unknown>>([]);
169 const expectedError = new AcpError.AcpTransportError({
170 operation: "read-input-stream",
171 detail: "Sign in to the mock agent.",
172 cause: undefined,
173 });
174 const error = yield* Effect.gen(function* () {
175 const acp = yield* AcpClient.AcpClient;
176 const failure = yield* acp.agent.initialize({ protocolVersion: 1 }).pipe(Effect.flip);
177 assert.strictEqual(yield* Deferred.await(termination), expectedError);
178 return failure;
179 }).pipe(
180 Effect.provide(
181 AcpClient.layerChildProcess(handle, {
182 logIncoming: true,
183 logger: (event) => Ref.update(logs, (current) => [...current, event]),
184 transformStdout: (stdout) =>
185 stdout.pipe(
186 Stream.decodeText,
187 Stream.splitLines,
188 Stream.mapEffect((line) =>
189 line === privateNotice ? Effect.fail(expectedError) : Effect.succeed(`${line}\n`),
190 ),
191 Stream.encodeText,
192 ),
193 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
194 }),
195 ),
196 );
197
198 assert.strictEqual(error, expectedError);
199 assert.isEmpty(yield* Ref.get(logs));
200 }),
201 );
202
203 it.effect("retains only transformed session updates in raw notifications and handlers", () =>
204 Effect.gen(function* () {
205 const { stdio, input } = yield* makeInMemoryStdio();
206 const delivered = yield* Deferred.make<import("./compat.ts").SessionNotification>();
207 const imageData = "A".repeat(1_048_576);
208 const normalized = {
209 sessionId: "session-1",
210 update: {
211 sessionUpdate: "agent_message_chunk",
212 content: { type: "text", text: "Image data omitted." },
213 },
214 } satisfies import("./compat.ts").SessionNotification;
215 let transformCalls = 0;
216 const acp = yield* AcpClient.make(stdio, {
217 transformSessionUpdate: (notification) => {
218 if (
219 notification.update.sessionUpdate !== "agent_message_chunk" ||
220 notification.update.content.type !== "image"
221 ) {
222 return notification;
223 }
224 assert.equal(notification.update.content.data, imageData);
225 transformCalls += 1;
226 return normalized;
227 },
228 });
229 yield* acp.handleSessionUpdate((notification) =>
230 Deferred.succeed(delivered, notification).pipe(Effect.asVoid),
231 );
232
233 yield* Queue.offer(
234 input,
235 yield* encodeJsonl(SessionUpdateNotification, {
236 jsonrpc: "2.0",
237 method: "session/update",
238 params: {
239 sessionId: "session-1",
240 update: {
241 sessionUpdate: "agent_message_chunk",
242 content: { type: "image", data: imageData, mimeType: "image/png" },
243 },
244 },
245 }),
246 );
247
248 assert.strictEqual(yield* Deferred.await(delivered), normalized);
249 const [retained] = yield* acp.raw.notifications.pipe(Stream.take(1), Stream.runCollect);
250 assert.deepEqual(retained, {
251 _tag: "SessionUpdate",
252 method: "session/update",
253 params: normalized,
254 });
255 assert.equal(transformCalls, 1);
256 }),
257 );
258
259 it.effect("reports idle child termination and rejects later requests and notifications", () =>
260 Effect.gen(function* () {
261 const handle = yield* makeHandle();
262 const termination = yield* Deferred.make<AcpError.AcpError>();
263 yield* Effect.gen(function* () {
264 const acp = yield* AcpClient.AcpClient;
265 yield* acp.agent.initialize({ protocolVersion: 1 });
266 yield* handle.kill();
267
268 const error = yield* Deferred.await(termination);
269 if (error._tag !== "AcpProcessExitedError") {
270 return assert.fail(`Expected a process exit, got ${error._tag}`);
271 }
272 assert.equal(error.pid, handle.pid);
273 assert.equal(error.code, yield* handle.exitCode);
274 const rawRequestError = yield* acp.raw.request("x/echo", {}).pipe(
275 Effect.match({
276 onFailure: (failure) => failure,
277 onSuccess: () => assert.fail("Expected the request to fail after process exit"),
278 }),
279 );
280 assert.strictEqual(rawRequestError, error);
281 assert.strictEqual(yield* acp.raw.notify("x/notify", {}).pipe(Effect.flip), error);
282 assert.strictEqual(
283 yield* acp.agent.cancel({ sessionId: "mock-session-1" }).pipe(Effect.flip),
284 error,
285 );
286
287 const requestError = yield* acp.agent
288 .createSession({ cwd: process.cwd(), mcpServers: [] })
289 .pipe(Effect.flip);
290 assert.strictEqual(requestError, error);
291 }).pipe(
292 Effect.provide(
293 AcpClient.layerChildProcess(handle, {
294 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
295 }),
296 ),
297 );
298 }),
299 );
300
301 it.effect("initializes, prompts, receives updates, and handles permission requests", () =>
302 Effect.gen(function* () {
303 const updates = yield* Ref.make<Array<unknown>>([]);
304 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
305 const typedRequests = yield* Ref.make<Array<unknown>>([]);
306 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
307 const requestContexts = yield* Ref.make<Array<AcpProtocol.AcpRequestContext>>([]);
308 const handle = yield* makeHandle();
309 const scope = yield* Scope.make();
310 const acpLayer = AcpClient.layerChildProcess(handle);
311 const context = yield* Layer.buildWithScope(acpLayer, scope);
312
313 const ext = yield* Effect.gen(function* () {
314 const acp = yield* AcpClient.AcpClient;
315
316 yield* acp.handleRequestPermission((_request, requestContext) =>
317 Ref.update(requestContexts, (current) => [...current, requestContext]).pipe(
318 Effect.as({
319 outcome: {
320 outcome: "selected",
321 optionId: "allow",
322 },
323 }),
324 ),
325 );
326 yield* acp.handleElicitation((_request, requestContext) =>
327 Ref.update(requestContexts, (current) => [...current, requestContext]).pipe(
328 Effect.as({
329 action: "accept",
330 content: {
331 approved: true,
332 },
333 }),
334 ),
335 );
336 yield* acp.handleSessionUpdate((notification) =>
337 Ref.update(updates, (current) => [...current, notification]),
338 );
339 yield* acp.handleElicitationComplete((notification) =>
340 Ref.update(elicitationCompletions, (current) => [...current, notification]),
341 );
342 yield* acp.handleExtRequest(
343 "x/typed_request",
344 Schema.Struct({ message: Schema.String }),
345 (payload, requestContext) =>
346 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
347 Effect.andThen(
348 Ref.update(requestContexts, (current) => [...current, requestContext]),
349 ),
350 Effect.as({
351 ok: true,
352 echoedMessage: payload.message,
353 }),
354 ),
355 );
356 yield* acp.handleExtNotification(
357 "x/typed_notification",
358 Schema.Struct({ count: Schema.Number }),
359 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
360 );
361
362 const init = yield* acp.agent.initialize({
363 protocolVersion: 1,
364 clientCapabilities: {
365 fs: { readTextFile: false, writeTextFile: false },
366 terminal: false,
367 },
368 clientInfo: {
369 name: "effect-acp-test",
370 version: "0.0.0",
371 },
372 });
373 assert.equal(init.protocolVersion, 2);
374
375 yield* acp.agent.authenticate({ methodId: "cursor_login" });
376
377 const session = yield* acp.agent.createSession({
378 cwd: process.cwd(),
379 mcpServers: [],
380 });
381 assert.equal(session.sessionId, "mock-session-1");
382
383 const prompt = yield* acp.agent.prompt({
384 sessionId: session.sessionId,
385 prompt: [{ type: "text", text: "hello" }],
386 });
387 assert.equal(prompt.stopReason, "end_turn");
388
389 const streamed = yield* Stream.runCollect(Stream.take(acp.raw.notifications, 2));
390 assert.equal(streamed.length, 2);
391 assert.equal(streamed[0]?._tag, "SessionUpdate");
392 assert.equal(streamed[1]?._tag, "ElicitationComplete");
393 assert.equal((yield* Ref.get(updates)).length, 2);
394 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
395 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
396 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
397 const observedRequestContexts = yield* Ref.get(requestContexts);
398 assert.deepEqual(
399 observedRequestContexts.map((requestContext) => requestContext.method),
400 ["session/request_permission", "elicitation/create", "x/typed_request"],
401 );
402 assert.equal(
403 new Set(observedRequestContexts.map((requestContext) => requestContext.requestId)).size,
404 observedRequestContexts.length,
405 );
406
407 return yield* acp.raw.request("x/echo", {
408 hello: "world",
409 });
410 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
411
412 assert.deepEqual(ext, {
413 echoedMethod: "x/echo",
414 echoedParams: {
415 hello: "world",
416 },
417 });
418 }),
419 );
420
421 it.effect(
422 "returns structured invalid params without exposing values from typed extension request payloads",
423 () =>
424 Effect.gen(function* () {
425 const handle = yield* makeHandle({ ACP_MOCK_BAD_TYPED_REQUEST: "1" });
426 const scope = yield* Scope.make();
427 const acpLayer = AcpClient.layerChildProcess(handle);
428 const context = yield* Layer.buildWithScope(acpLayer, scope);
429
430 const result = yield* Effect.gen(function* () {
431 const acp = yield* AcpClient.AcpClient;
432
433 yield* acp.handleRequestPermission(() =>
434 Effect.succeed({
435 outcome: {
436 outcome: "selected",
437 optionId: "allow",
438 },
439 }),
440 );
441 yield* acp.handleElicitation(() =>
442 Effect.succeed({
443 action: "accept",
444 content: {
445 approved: true,
446 },
447 }),
448 );
449 yield* acp.handleExtRequest(
450 "x/typed_request",
451 Schema.Struct({ message: Schema.String }),
452 () => Effect.succeed({ ok: true }),
453 );
454
455 yield* acp.agent.initialize({
456 protocolVersion: 1,
457 clientCapabilities: {
458 fs: { readTextFile: false, writeTextFile: false },
459 terminal: false,
460 },
461 clientInfo: {
462 name: "effect-acp-test",
463 version: "0.0.0",
464 },
465 });
466
467 yield* acp.agent.authenticate({ methodId: "cursor_login" });
468
469 const session = yield* acp.agent.createSession({
470 cwd: process.cwd(),
471 mcpServers: [],
472 });
473
474 return yield* Effect.exit(
475 acp.agent.prompt({
476 sessionId: session.sessionId,
477 prompt: [{ type: "text", text: "hello" }],
478 }),
479 );
480 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
481
482 if (result._tag !== "Failure") {
483 assert.fail("Expected prompt to fail for invalid typed extension payload");
484 }
485 const rendered = Cause.pretty(result.cause);
486 assert.include(rendered, "Invalid payload for ACP extension method 'x/typed_request'.");
487 assert.notInclude(rendered, "Expected string, got 123");
488 }),
489 );
490
491 it.effect("preserves ACP v2 structured diff semantics", () =>
492 Effect.gen(function* () {
493 const updates = yield* Ref.make<Array<AcpCompat.SessionNotification>>([]);
494 const handle = yield* makeHandle({ ACP_MOCK_V2_DIFF: "1" });
495 const scope = yield* Scope.make();
496 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
497
498 yield* Effect.gen(function* () {
499 const acp = yield* AcpClient.AcpClient;
500 yield* acp.handleRequestPermission(() =>
501 Effect.succeed({ outcome: { outcome: "selected", optionId: "allow" } }),
502 );
503 yield* acp.handleElicitation(() =>
504 Effect.succeed({ action: "accept", content: { approved: true } }),
505 );
506 yield* acp.handleExtRequest(
507 "x/typed_request",
508 Schema.Struct({ message: Schema.String }),
509 () => Effect.succeed({ ok: true }),
510 );
511 yield* acp.handleSessionUpdate((notification) =>
512 Ref.update(updates, (current) => [...current, notification]),
513 );
514
515 yield* acp.agent.initialize({ protocolVersion: 2 });
516 yield* acp.agent.authenticate({ methodId: "cursor_login" });
517 const session = yield* acp.agent.createSession({ cwd: process.cwd(), mcpServers: [] });
518 yield* acp.agent.prompt({
519 sessionId: session.sessionId,
520 prompt: [{ type: "text", text: "show the diff" }],
521 });
522 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
523
524 const diffUpdate = (yield* Ref.get(updates)).find(
525 (notification) => notification.update.sessionUpdate === "tool_call_update",
526 );
527 assert.deepEqual(diffUpdate?.update, {
528 sessionUpdate: "tool_call_update",
529 toolCallId: "tool-diff",
530 content: [
531 {
532 type: "diff",
533 changes: [
534 {
535 operation: "move",
536 oldPath: "/workspace/old.ts",
537 path: "/workspace/new.ts",
538 fileType: "text",
539 mimeType: "text/typescript",
540 },
541 ],
542 patch: {
543 format: "git_patch",
544 text: "diff --git a/old.ts b/new.ts\nsimilarity index 100%\nrename from old.ts\nrename to new.ts\n",
545 },
546 },
547 ],
548 });
549 }),
550 );
551
552 it.effect("preserves registry env-var authentication extensions", () =>
553 Effect.gen(function* () {
554 const handle = yield* makeHandle({ ACP_MOCK_ENV_VAR_AUTH: "1" });
555 const scope = yield* Scope.make();
556 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
557
558 const response = yield* Effect.gen(function* () {
559 const acp = yield* AcpClient.AcpClient;
560 return yield* acp.agent.initialize({ protocolVersion: 2 });
561 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
562
563 assert.deepEqual(response.authMethods, [
564 {
565 id: "api_key",
566 name: "API key",
567 type: "env_var",
568 vars: [{ name: "MOCK_API_KEY", label: "Mock API key" }],
569 link: "https://example.test/keys",
570 },
571 ]);
572 }),
573 );
574
575 it.effect("replays buffered notifications to handlers registered after they arrive", () =>
576 Effect.gen(function* () {
577 const updates = yield* Ref.make<Array<unknown>>([]);
578 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
579 const typedRequests = yield* Ref.make<Array<unknown>>([]);
580 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
581 const handle = yield* makeHandle();
582 const scope = yield* Scope.make();
583 const acpLayer = AcpClient.layerChildProcess(handle);
584 const context = yield* Layer.buildWithScope(acpLayer, scope);
585
586 yield* Effect.gen(function* () {
587 const acp = yield* AcpClient.AcpClient;
588
589 yield* acp.handleRequestPermission(() =>
590 Effect.succeed({
591 outcome: {
592 outcome: "selected",
593 optionId: "allow",
594 },
595 }),
596 );
597 yield* acp.handleElicitation(() =>
598 Effect.succeed({
599 action: "accept",
600 content: {
601 approved: true,
602 },
603 }),
604 );
605 yield* acp.handleExtRequest(
606 "x/typed_request",
607 Schema.Struct({ message: Schema.String }),
608 (payload) =>
609 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
610 Effect.as({
611 ok: true,
612 echoedMessage: payload.message,
613 }),
614 ),
615 );
616 yield* acp.handleExtNotification(
617 "x/typed_notification",
618 Schema.Struct({ count: Schema.Number }),
619 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
620 );
621
622 yield* acp.agent.initialize({
623 protocolVersion: 1,
624 clientCapabilities: {
625 fs: { readTextFile: false, writeTextFile: false },
626 terminal: false,
627 },
628 clientInfo: {
629 name: "effect-acp-test",
630 version: "0.0.0",
631 },
632 });
633 yield* acp.agent.authenticate({ methodId: "cursor_login" });
634
635 const session = yield* acp.agent.createSession({
636 cwd: process.cwd(),
637 mcpServers: [],
638 });
639 yield* acp.agent.prompt({
640 sessionId: session.sessionId,
641 prompt: [{ type: "text", text: "hello" }],
642 });
643
644 yield* acp.handleSessionUpdate((notification) =>
645 Ref.update(updates, (current) => [...current, notification]),
646 );
647 yield* acp.handleElicitationComplete((notification) =>
648 Ref.update(elicitationCompletions, (current) => [...current, notification]),
649 );
650
651 assert.equal((yield* Ref.get(updates)).length, 2);
652 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
653 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
654 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
655 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
656 }),
657 );
658
659 it.effect("continues dispatching session updates after one handler fails", () =>
660 Effect.gen(function* () {
661 const successfulHandlers = yield* Ref.make(0);
662 const handle = yield* makeHandle();
663 const scope = yield* Scope.make();
664 const acpLayer = AcpClient.layerChildProcess(handle);
665 const context = yield* Layer.buildWithScope(acpLayer, scope);
666
667 yield* Effect.gen(function* () {
668 const acp = yield* AcpClient.AcpClient;
669
670 yield* acp.handleRequestPermission(() =>
671 Effect.succeed({
672 outcome: {
673 outcome: "selected",
674 optionId: "allow",
675 },
676 }),
677 );
678 yield* acp.handleElicitation(() =>
679 Effect.succeed({
680 action: "accept",
681 content: {
682 approved: true,
683 },
684 }),
685 );
686 yield* acp.handleExtRequest(
687 "x/typed_request",
688 Schema.Struct({ message: Schema.String }),
689 () => Effect.succeed({ ok: true }),
690 );
691 yield* acp.handleExtNotification(
692 "x/typed_notification",
693 Schema.Struct({ count: Schema.Number }),
694 () => Effect.void,
695 );
696 yield* acp.handleSessionUpdate(() =>
697 Effect.fail(AcpError.AcpRequestError.internalError("session update handler failed")),
698 );
699 yield* acp.handleSessionUpdate(() => Ref.update(successfulHandlers, (count) => count + 1));
700
701 yield* acp.agent.initialize({
702 protocolVersion: 1,
703 clientCapabilities: {
704 fs: { readTextFile: false, writeTextFile: false },
705 terminal: false,
706 },
707 clientInfo: {
708 name: "effect-acp-test",
709 version: "0.0.0",
710 },
711 });
712 yield* acp.agent.authenticate({ methodId: "cursor_login" });
713
714 const session = yield* acp.agent.createSession({
715 cwd: process.cwd(),
716 mcpServers: [],
717 });
718 yield* acp.agent.prompt({
719 sessionId: session.sessionId,
720 prompt: [{ type: "text", text: "hello" }],
721 });
722
723 assert.equal(yield* Ref.get(successfulHandlers), 2);
724 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
725 }),
726 );
727
728 it.effect("uses distinct ids for RPC calls and extension requests", () =>
729 Effect.gen(function* () {
730 const { stdio, input, output } = yield* makeInMemoryStdio();
731 const scope = yield* Scope.make();
732 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
733
734 const initializeFiber = yield* acp.agent
735 .initialize({
736 protocolVersion: 1,
737 clientCapabilities: {
738 fs: { readTextFile: false, writeTextFile: false },
739 terminal: false,
740 },
741 clientInfo: {
742 name: "effect-acp-test",
743 version: "0.0.0",
744 },
745 })
746 .pipe(Effect.forkScoped);
747 const extFiber = yield* acp.raw.request("x/test", { hello: "world" }).pipe(Effect.forkScoped);
748
749 const firstOutbound = yield* Queue.take(output);
750 const secondOutbound = yield* Queue.take(output);
751
752 const decodedInitialize = Schema.decodeEffect(Schema.fromJsonString(InitializeRequest));
753 const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
754 const firstIsInitialize = yield* decodedInitialize(firstOutbound).pipe(
755 Effect.match({
756 onFailure: () => false,
757 onSuccess: () => true,
758 }),
759 );
760
761 const initializeRequest = firstIsInitialize
762 ? yield* decodedInitialize(firstOutbound)
763 : yield* decodedInitialize(secondOutbound);
764 const extRequest = firstIsInitialize
765 ? yield* decodedExt(secondOutbound)
766 : yield* decodedExt(firstOutbound);
767
768 assert.notEqual(initializeRequest.id, extRequest.id);
769
770 yield* Queue.offer(
771 input,
772 yield* encodeJsonl(InitializeResponse, {
773 jsonrpc: "2.0",
774 id: initializeRequest.id,
775 result: {
776 protocolVersion: 2,
777 capabilities: {},
778 info: {
779 name: "mock-agent",
780 version: "0.0.0",
781 },
782 },
783 }),
784 );
785 yield* Queue.offer(
786 input,
787 yield* encodeJsonl(ExtResponse, {
788 jsonrpc: "2.0",
789 id: extRequest.id,
790 result: { ok: true },
791 }),
792 );
793
794 yield* Fiber.join(initializeFiber);
795 assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
796 yield* Scope.close(scope, Exit.void);
797 }),
798 );
799
800 it.effect("classifies a legacy response by shape when its protocol version is 2", () =>
801 Effect.gen(function* () {
802 const { stdio, input, output } = yield* makeInMemoryStdio();
803 const scope = yield* Scope.make();
804 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
805 const initializeFiber = yield* acp.agent
806 .initialize({
807 protocolVersion: 2,
808 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
809 })
810 .pipe(Effect.forkScoped);
811 const decodeInitialize = Schema.decodeEffect(Schema.fromJsonString(InitializeRequestV1));
812 const initializeRequest = yield* decodeInitialize(yield* Queue.take(output));
813 yield* Queue.offer(
814 input,
815 yield* encodeJsonl(InitializeResponseV1, {
816 jsonrpc: "2.0",
817 id: initializeRequest.id,
818 result: {
819 protocolVersion: 2,
820 agentInfo: { name: "antigravity", version: "1.0.0" },
821 agentCapabilities: {},
822 },
823 }),
824 );
825
826 const initialized = yield* Fiber.join(initializeFiber);
827 assert.equal(initialized.protocolVersion, 2);
828 assert.equal(initialized.agentInfo?.name, "antigravity");
829 yield* Scope.close(scope, Exit.void);
830 }),
831 );
832
833 it.effect("negotiates ACP v1 and retains native model and elicitation compatibility", () =>
834 Effect.gen(function* () {
835 const { stdio, input, output } = yield* makeInMemoryStdio();
836 const scope = yield* Scope.make();
837 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
838 const updates = yield* Ref.make<Array<unknown>>([]);
839 yield* acp.handleSessionUpdate((notification) =>
840 Ref.update(updates, (current) => [...current, notification]),
841 );
842
843 const initializeFiber = yield* acp.agent
844 .initialize({
845 protocolVersion: 2,
846 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
847 clientCapabilities: { _meta: { "terminal-auth": true } },
848 })
849 .pipe(Effect.forkScoped);
850 const initializeRequest = yield* Queue.take(output).pipe(
851 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(InitializeRequestV1))),
852 );
853 assert.equal(initializeRequest.params.protocolVersion, 2);
854 assert.equal(initializeRequest.params.clientCapabilities?._meta?.["terminal-auth"], true);
855 yield* Queue.offer(
856 input,
857 yield* encodeJsonl(InitializeResponseV1, {
858 jsonrpc: "2.0",
859 id: initializeRequest.id,
860 result: {
861 protocolVersion: 1,
862 agentInfo: { name: "pi-acp", version: "0.0.33" },
863 agentCapabilities: { loadSession: true },
864 },
865 }),
866 );
867 const initialized = yield* Fiber.join(initializeFiber);
868 assert.equal(initialized.protocolVersion, 1);
869 assert.equal(initialized.agentInfo?.name, "pi-acp");
870
871 const sessionFiber = yield* acp.agent
872 .createSession({ cwd: process.cwd(), mcpServers: [] })
873 .pipe(Effect.forkScoped);
874 const sessionRequest = yield* Queue.take(output).pipe(
875 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(NewSessionRequestV1))),
876 );
877 yield* Queue.offer(
878 input,
879 yield* encodeJsonl(jsonRpcResponse(Schema.Unknown), {
880 jsonrpc: "2.0",
881 id: sessionRequest.id,
882 result: {
883 sessionId: "pi-session-1",
884 models: {
885 currentModelId: "native-model",
886 availableModels: [{ modelId: "native-model", name: "Native model" }],
887 },
888 },
889 }),
890 );
891 const session = yield* Fiber.join(sessionFiber);
892 assert.equal(session.sessionId, "pi-session-1");
893 assert.equal(session.models?.currentModelId, "native-model");
894 const selectModel = yield* acp.agent
895 .setSessionModel({ sessionId: session.sessionId, modelId: "native-model" })
896 .pipe(Effect.forkScoped);
897 const selection = yield* Queue.take(output).pipe(
898 Effect.flatMap(
899 Schema.decodeEffect(
900 Schema.fromJsonString(
901 jsonRpcRequest(
902 "session/set_model",
903 Schema.Struct({ sessionId: Schema.String, modelId: Schema.String }),
904 ),
905 ),
906 ),
907 ),
908 );
909 assert.equal(selection.params.modelId, "native-model");
910 yield* Queue.offer(
911 input,
912 yield* encodeJsonl(jsonRpcResponse(Schema.Unknown), {
913 jsonrpc: "2.0",
914 id: selection.id,
915 result: {},
916 }),
917 );
918 yield* Fiber.join(selectModel);
919
920 yield* acp.handleElicitation(() =>
921 Effect.succeed({ action: "accept", content: { branch: "main" } }),
922 );
923 yield* Queue.offer(
924 input,
925 yield* encodeJsonl(jsonRpcRequest("session/elicitation", Schema.Unknown), {
926 jsonrpc: "2.0",
927 id: "legacy-question",
928 headers: [],
929 method: "session/elicitation",
930 params: {
931 sessionId: session.sessionId,
932 mode: "form",
933 message: "Choose a branch",
934 requestedSchema: { type: "object", properties: {} },
935 },
936 }),
937 );
938 const answer = yield* Queue.take(output).pipe(
939 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(jsonRpcResponse(Schema.Unknown)))),
940 );
941 assert.deepEqual(answer.result, {
942 action: { action: "accept", content: { branch: "main" } },
943 });
944 // Recorded Devin 2026-09-10 called the older underscore method.
945 yield* Queue.offer(
946 input,
947 yield* encodeJsonl(jsonRpcRequest("_session/elicitation", Schema.Unknown), {
948 jsonrpc: "2.0",
949 id: "devin-question",
950 headers: [],
951 method: "_session/elicitation",
952 params: {
953 sessionId: session.sessionId,
954 mode: "form",
955 message: "Proceed?",
956 requestedSchema: { type: "object", properties: {} },
957 },
958 }),
959 );
960 const devinAnswer = yield* Queue.take(output).pipe(
961 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(jsonRpcResponse(Schema.Unknown)))),
962 );
963 assert.deepEqual(devinAnswer.result, {
964 action: { action: "accept", content: { branch: "main" } },
965 });
966 const completed = yield* Deferred.make<void>();
967 yield* acp.handleElicitationComplete(() =>
968 Deferred.succeed(completed, undefined).pipe(Effect.asVoid),
969 );
970 yield* Queue.offer(
971 input,
972 yield* encodeJsonl(jsonRpcNotification("session/elicitation/complete", Schema.Unknown), {
973 jsonrpc: "2.0",
974 method: "session/elicitation/complete",
975 params: { elicitationId: "legacy-login" },
976 }),
977 );
978 yield* Deferred.await(completed);
979
980 const promptFiber = yield* acp.agent
981 .prompt({
982 sessionId: "pi-session-1",
983 prompt: [{ type: "text", text: "hello" }],
984 })
985 .pipe(Effect.forkScoped);
986 const promptRequest = yield* Queue.take(output).pipe(
987 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(PromptRequestV1))),
988 );
989 yield* Queue.offer(
990 input,
991 concatBytes([
992 yield* encodeJsonl(
993 jsonRpcNotification("session/update", AcpSchemaV1.SessionNotification),
994 {
995 jsonrpc: "2.0",
996 method: "session/update",
997 params: {
998 sessionId: "pi-session-1",
999 update: {
1000 sessionUpdate: "available_commands_update",
1001 availableCommands: [
1002 { name: "review", description: "Review changes", input: { hint: "scope" } },
1003 ],
1004 },
1005 },
1006 },
1007 ),
1008 yield* encodeJsonl(PromptResponseV1, {
1009 jsonrpc: "2.0",
1010 id: promptRequest.id,
1011 result: { stopReason: "end_turn" },
1012 }),
1013 ]),
1014 );
1015 assert.deepEqual(yield* Fiber.join(promptFiber), { stopReason: "end_turn" });
1016 assert.deepEqual(yield* Ref.get(updates), [
1017 {
1018 sessionId: "pi-session-1",
1019 update: {
1020 sessionUpdate: "available_commands_update",
1021 availableCommands: [
1022 {
1023 name: "review",
1024 description: "Review changes",
1025 input: { type: "text", hint: "scope" },
1026 },
1027 ],
1028 },
1029 },
1030 ]);
1031 yield* Scope.close(scope, Exit.void);
1032 }),
1033 );
1034
1035 it.effect("preserves exact ids for parallel requests with identical payloads", () =>
1036 Effect.gen(function* () {
1037 const { stdio, input, output } = yield* makeInMemoryStdio();
1038 const scope = yield* Scope.make();
1039 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1040 const contexts = yield* Ref.make<Array<AcpProtocol.AcpRequestContext>>([]);
1041 yield* acp.handleRequestPermission((_request, context) =>
1042 Ref.update(contexts, (current) => [...current, context]).pipe(
1043 Effect.as({ outcome: { outcome: "selected", optionId: "allow" } } as const),
1044 ),
1045 );
1046 const payload = {
1047 sessionId: "session-1",
1048 title: "Shared tool",
1049 subject: {
1050 type: "tool_call" as const,
1051 toolCall: { toolCallId: "shared-tool", title: "Shared tool" },
1052 },
1053 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" as const }],
1054 };
1055 yield* Queue.offer(
1056 input,
1057 concatBytes(
1058 yield* Effect.all(
1059 ["permission-a", "permission-b"].map((id) =>
1060 encodeJsonl(PermissionRequest, {
1061 jsonrpc: "2.0",
1062 id,
1063 method: "session/request_permission",
1064 params: payload,
1065 headers: [],
1066 }),
1067 ),
1068 ),
1069 ),
1070 );
1071
1072 const decodeResponse = Schema.decodeEffect(Schema.fromJsonString(PermissionResponse));
1073 const responses = yield* Effect.all([
1074 Queue.take(output).pipe(Effect.flatMap(decodeResponse)),
1075 Queue.take(output).pipe(Effect.flatMap(decodeResponse)),
1076 ]);
1077 assert.deepEqual(responses.map((response) => response.id).toSorted(), [
1078 "permission-a",
1079 "permission-b",
1080 ]);
1081 assert.deepEqual(
1082 (yield* Ref.get(contexts))
1083 .map(({ requestId, method }) => ({ requestId, method }))
1084 .toSorted((left, right) => left.requestId.localeCompare(right.requestId)),
1085 [
1086 { requestId: "permission-a", method: "session/request_permission" },
1087 { requestId: "permission-b", method: "session/request_permission" },
1088 ],
1089 );
1090 yield* Scope.close(scope, Exit.void);
1091 }),
1092 );
1093
1094 it.effect("answers elicitation/create with the flat action shape", () =>
1095 Effect.gen(function* () {
1096 const { stdio, input, output } = yield* makeInMemoryStdio();
1097 const scope = yield* Scope.make();
1098 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1099 yield* acp.handleElicitation(() =>
1100 Effect.succeed({ action: "accept" as const, content: { approved: true } }),
1101 );
1102
1103 yield* Queue.offer(
1104 input,
1105 yield* encodeJsonl(ElicitationRequest, {
1106 jsonrpc: "2.0",
1107 id: "elicitation",
1108 method: "elicitation/create",
1109 params: {
1110 sessionId: "session-1",
1111 mode: "form" as const,
1112 message: "Approve this call?",
1113 requestedSchema: {
1114 type: "object" as const,
1115 properties: { approved: { type: "boolean" as const } },
1116 },
1117 },
1118 headers: [],
1119 }),
1120 );
1121 const response = yield* Queue.take(output).pipe(
1122 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(ElicitationResponse))),
1123 );
1124 assert.deepEqual(response.result, {
1125 action: "accept",
1126 content: { approved: true },
1127 });
1128 yield* Scope.close(scope, Exit.void);
1129 }),
1130 );
1131
1132 it.effect(
1133 "routes a standard prompt response after Grok extension notifications in the same batch",
1134 () =>
1135 Effect.gen(function* () {
1136 const { stdio, input, output } = yield* makeInMemoryStdio();
1137 const scope = yield* Scope.make();
1138 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1139
1140 const promptFiber = yield* acp.agent
1141 .prompt({
1142 sessionId: "grok-session-1",
1143 prompt: [{ type: "text", text: "run the ls command" }],
1144 })
1145 .pipe(Effect.forkScoped);
1146
1147 const outbound = yield* Queue.take(output);
1148 const decodedPrompt = yield* decodePromptRequestLine(outbound);
1149
1150 const responseBatch = concatBytes(
1151 yield* Effect.all([
1152 encodeJsonl(XAiQueueChangedNotification, {
1153 jsonrpc: "2.0",
1154 method: "_x.ai/queue/changed",
1155 params: { sessionId: "grok-session-1", entries: [] },
1156 }),
1157 encodeJsonl(XAiPromptCompleteNotification, {
1158 jsonrpc: "2.0",
1159 method: "_x.ai/session/prompt_complete",
1160 params: {
1161 sessionId: "grok-session-1",
1162 promptId: "prompt-1",
1163 stopReason: "end_turn",
1164 agentResult: null,
1165 },
1166 }),
1167 encodeJsonl(XAiSessionsChangedNotification, {
1168 jsonrpc: "2.0",
1169 method: "_x.ai/sessions/changed",
1170 params: {
1171 upserted: [
1172 {
1173 sessionId: "grok-session-1",
1174 title: null,
1175 cwd: process.cwd(),
1176 isWorktree: false,
1177 modelId: "grok-composer-2.5-fast",
1178 yolo: false,
1179 activity: "idle",
1180 resident: true,
1181 lastChangeUnixMs: 1_710_000_000_000,
1182 origin: { kind: "local" },
1183 },
1184 ],
1185 removed: [],
1186 },
1187 }),
1188 encodeJsonl(PromptResponse, {
1189 jsonrpc: "2.0",
1190 id: decodedPrompt.id,
1191 result: {},
1192 }),
1193 encodeJsonl(SessionUpdateNotification, {
1194 jsonrpc: "2.0",
1195 method: "session/update",
1196 params: {
1197 sessionId: "grok-session-1",
1198 update: {
1199 sessionUpdate: "state_update",
1200 state: "idle",
1201 stopReason: "end_turn",
1202 _meta: {
1203 sessionId: "grok-session-1",
1204 requestId: "prompt-1",
1205 promptId: "prompt-1",
1206 modelId: "grok-composer-2.5-fast",
1207 },
1208 },
1209 },
1210 }),
1211 ]),
1212 );
1213 yield* Queue.offer(input, responseBatch);
1214
1215 assert.deepEqual(yield* Fiber.join(promptFiber), {
1216 stopReason: "end_turn",
1217 _meta: {
1218 sessionId: "grok-session-1",
1219 requestId: "prompt-1",
1220 promptId: "prompt-1",
1221 modelId: "grok-composer-2.5-fast",
1222 },
1223 });
1224 yield* Scope.close(scope, Exit.void);
1225 }),
1226 );
1227
1228 it.effect("calls ACP v2 session deletion and provider-management methods", () =>
1229 Effect.gen(function* () {
1230 const handle = yield* makeHandle({ ACP_MOCK_V2_MANAGEMENT: "1" });
1231 const scope = yield* Scope.make();
1232 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
1233
1234 yield* Effect.gen(function* () {
1235 const acp = yield* AcpClient.AcpClient;
1236 const initialized = yield* acp.agent.initialize({
1237 protocolVersion: 2,
1238 clientCapabilities: {},
1239 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
1240 });
1241 assert.ok(initialized.agentCapabilities?.sessionCapabilities?.delete);
1242 assert.ok(initialized.agentCapabilities?.providers);
1243
1244 assert.deepEqual(yield* acp.agent.deleteSession({ sessionId: "mock-session-1" }), {});
1245 assert.deepEqual(yield* acp.agent.listProviders({}), {
1246 providers: [
1247 {
1248 providerId: "mock-provider",
1249 supported: ["openai"],
1250 required: false,
1251 current: null,
1252 },
1253 ],
1254 });
1255 assert.deepEqual(
1256 yield* acp.agent.setProvider({
1257 providerId: "mock-provider",
1258 apiType: "openai",
1259 baseUrl: "https://api.example.test/v1",
1260 headers: { Authorization: "Bearer secret" },
1261 }),
1262 {},
1263 );
1264 assert.deepEqual(yield* acp.agent.disableProvider({ providerId: "mock-provider" }), {});
1265 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
1266 }),
1267 );
1268
1269 it.effect("routes MCP-over-ACP connect, message, notification, and disconnect callbacks", () =>
1270 Effect.gen(function* () {
1271 const handle = yield* makeHandle({ ACP_MOCK_MCP_OVER_ACP: "1" });
1272 const scope = yield* Scope.make();
1273 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
1274 const methods = yield* Ref.make<Array<string>>([]);
1275
1276 yield* Effect.gen(function* () {
1277 const acp = yield* AcpClient.AcpClient;
1278 yield* acp.handleRequestPermission(() =>
1279 Effect.succeed({ outcome: { outcome: "selected", optionId: "allow" } }),
1280 );
1281 yield* acp.handleElicitation(() => Effect.succeed({ action: "decline" }));
1282 yield* acp.handleExtRequest(
1283 "x/typed_request",
1284 Schema.Struct({ message: Schema.String }),
1285 () => Effect.succeed({ ok: true }),
1286 );
1287 yield* acp.handleExtNotification(
1288 "x/typed_notification",
1289 Schema.Struct({ count: Schema.Number }),
1290 () => Effect.void,
1291 );
1292 yield* acp.handleMcpConnect(() =>
1293 Ref.update(methods, (current) => [...current, "connect"]).pipe(
1294 Effect.as({ connectionId: "connection-1" }),
1295 ),
1296 );
1297 yield* acp.handleMcpMessage(() =>
1298 Ref.update(methods, (current) => [...current, "message"]).pipe(Effect.as({ tools: [] })),
1299 );
1300 yield* acp.handleMcpNotification(() =>
1301 Ref.update(methods, (current) => [...current, "notification"]),
1302 );
1303 yield* acp.handleMcpDisconnect(() =>
1304 Ref.update(methods, (current) => [...current, "disconnect"]).pipe(Effect.as({})),
1305 );
1306 yield* acp.agent.initialize({
1307 protocolVersion: 2,
1308 clientCapabilities: {},
1309 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
1310 });
1311 const session = yield* acp.agent.createSession({ cwd: process.cwd(), mcpServers: [] });
1312 yield* acp.agent.prompt({
1313 sessionId: session.sessionId,
1314 prompt: [{ type: "text", text: "exercise MCP" }],
1315 });
1316 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
1317
1318 assert.deepEqual(yield* Ref.get(methods), [
1319 "connect",
1320 "message",
1321 "notification",
1322 "disconnect",
1323 ]);
1324 }),
1325 );
1326
1327 it.effect("preserves future content and session-update variants", () =>
1328 Effect.gen(function* () {
1329 const handle = yield* makeHandle({ ACP_MOCK_UNKNOWN_VARIANTS: "1" });
1330 const scope = yield* Scope.make();
1331 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
1332 const updates = yield* Ref.make<Array<AcpCompat.SessionNotification>>([]);
1333
1334 yield* Effect.gen(function* () {
1335 const acp = yield* AcpClient.AcpClient;
1336 yield* acp.handleRequestPermission(() =>
1337 Effect.succeed({ outcome: { outcome: "selected", optionId: "allow" } }),
1338 );
1339 yield* acp.handleElicitation(() => Effect.succeed({ action: "decline" }));
1340 yield* acp.handleExtRequest(
1341 "x/typed_request",
1342 Schema.Struct({ message: Schema.String }),
1343 () => Effect.succeed({ ok: true }),
1344 );
1345 yield* acp.handleExtNotification(
1346 "x/typed_notification",
1347 Schema.Struct({ count: Schema.Number }),
1348 () => Effect.void,
1349 );
1350 yield* acp.handleSessionUpdate((update) =>
1351 Ref.update(updates, (current) => [...current, update]),
1352 );
1353 yield* acp.agent.initialize({
1354 protocolVersion: 2,
1355 clientCapabilities: {},
1356 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
1357 });
1358 const session = yield* acp.agent.createSession({ cwd: process.cwd(), mcpServers: [] });
1359 yield* acp.agent.prompt({
1360 sessionId: session.sessionId,
1361 prompt: [{ type: "text", text: "exercise future variants" }],
1362 });
1363 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
1364
1365 const received = yield* Ref.get(updates);
1366 assert.deepEqual(received[0]?.update, {
1367 sessionUpdate: "agent_message_chunk",
1368 messageId: "future-content",
1369 content: {
1370 type: "_t3_unknown",
1371 originalType: "chart",
1372 raw: { type: "chart", points: [] },
1373 },
1374 });
1375 assert.deepEqual(received[1]?.update, {
1376 sessionUpdate: "_t3_unknown",
1377 originalSessionUpdate: "timeline_update",
1378 raw: { sessionUpdate: "timeline_update", entries: [] },
1379 });
1380 }),
1381 );
1382});