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 const completed = yield* Deferred.make<void>();
945 yield* acp.handleElicitationComplete(() =>
946 Deferred.succeed(completed, undefined).pipe(Effect.asVoid),
947 );
948 yield* Queue.offer(
949 input,
950 yield* encodeJsonl(jsonRpcNotification("session/elicitation/complete", Schema.Unknown), {
951 jsonrpc: "2.0",
952 method: "session/elicitation/complete",
953 params: { elicitationId: "legacy-login" },
954 }),
955 );
956 yield* Deferred.await(completed);
957
958 const promptFiber = yield* acp.agent
959 .prompt({
960 sessionId: "pi-session-1",
961 prompt: [{ type: "text", text: "hello" }],
962 })
963 .pipe(Effect.forkScoped);
964 const promptRequest = yield* Queue.take(output).pipe(
965 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(PromptRequestV1))),
966 );
967 yield* Queue.offer(
968 input,
969 concatBytes([
970 yield* encodeJsonl(
971 jsonRpcNotification("session/update", AcpSchemaV1.SessionNotification),
972 {
973 jsonrpc: "2.0",
974 method: "session/update",
975 params: {
976 sessionId: "pi-session-1",
977 update: {
978 sessionUpdate: "available_commands_update",
979 availableCommands: [
980 { name: "review", description: "Review changes", input: { hint: "scope" } },
981 ],
982 },
983 },
984 },
985 ),
986 yield* encodeJsonl(PromptResponseV1, {
987 jsonrpc: "2.0",
988 id: promptRequest.id,
989 result: { stopReason: "end_turn" },
990 }),
991 ]),
992 );
993 assert.deepEqual(yield* Fiber.join(promptFiber), { stopReason: "end_turn" });
994 assert.deepEqual(yield* Ref.get(updates), [
995 {
996 sessionId: "pi-session-1",
997 update: {
998 sessionUpdate: "available_commands_update",
999 availableCommands: [
1000 {
1001 name: "review",
1002 description: "Review changes",
1003 input: { type: "text", hint: "scope" },
1004 },
1005 ],
1006 },
1007 },
1008 ]);
1009 yield* Scope.close(scope, Exit.void);
1010 }),
1011 );
1012
1013 it.effect("preserves exact ids for parallel requests with identical payloads", () =>
1014 Effect.gen(function* () {
1015 const { stdio, input, output } = yield* makeInMemoryStdio();
1016 const scope = yield* Scope.make();
1017 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1018 const contexts = yield* Ref.make<Array<AcpProtocol.AcpRequestContext>>([]);
1019 yield* acp.handleRequestPermission((_request, context) =>
1020 Ref.update(contexts, (current) => [...current, context]).pipe(
1021 Effect.as({ outcome: { outcome: "selected", optionId: "allow" } } as const),
1022 ),
1023 );
1024 const payload = {
1025 sessionId: "session-1",
1026 title: "Shared tool",
1027 subject: {
1028 type: "tool_call" as const,
1029 toolCall: { toolCallId: "shared-tool", title: "Shared tool" },
1030 },
1031 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" as const }],
1032 };
1033 yield* Queue.offer(
1034 input,
1035 concatBytes(
1036 yield* Effect.all(
1037 ["permission-a", "permission-b"].map((id) =>
1038 encodeJsonl(PermissionRequest, {
1039 jsonrpc: "2.0",
1040 id,
1041 method: "session/request_permission",
1042 params: payload,
1043 headers: [],
1044 }),
1045 ),
1046 ),
1047 ),
1048 );
1049
1050 const decodeResponse = Schema.decodeEffect(Schema.fromJsonString(PermissionResponse));
1051 const responses = yield* Effect.all([
1052 Queue.take(output).pipe(Effect.flatMap(decodeResponse)),
1053 Queue.take(output).pipe(Effect.flatMap(decodeResponse)),
1054 ]);
1055 assert.deepEqual(responses.map((response) => response.id).toSorted(), [
1056 "permission-a",
1057 "permission-b",
1058 ]);
1059 assert.deepEqual(
1060 (yield* Ref.get(contexts))
1061 .map(({ requestId, method }) => ({ requestId, method }))
1062 .toSorted((left, right) => left.requestId.localeCompare(right.requestId)),
1063 [
1064 { requestId: "permission-a", method: "session/request_permission" },
1065 { requestId: "permission-b", method: "session/request_permission" },
1066 ],
1067 );
1068 yield* Scope.close(scope, Exit.void);
1069 }),
1070 );
1071
1072 it.effect("answers elicitation/create with the flat action shape", () =>
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 yield* acp.handleElicitation(() =>
1078 Effect.succeed({ action: "accept" as const, content: { approved: true } }),
1079 );
1080
1081 yield* Queue.offer(
1082 input,
1083 yield* encodeJsonl(ElicitationRequest, {
1084 jsonrpc: "2.0",
1085 id: "elicitation",
1086 method: "elicitation/create",
1087 params: {
1088 sessionId: "session-1",
1089 mode: "form" as const,
1090 message: "Approve this call?",
1091 requestedSchema: {
1092 type: "object" as const,
1093 properties: { approved: { type: "boolean" as const } },
1094 },
1095 },
1096 headers: [],
1097 }),
1098 );
1099 const response = yield* Queue.take(output).pipe(
1100 Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(ElicitationResponse))),
1101 );
1102 assert.deepEqual(response.result, {
1103 action: "accept",
1104 content: { approved: true },
1105 });
1106 yield* Scope.close(scope, Exit.void);
1107 }),
1108 );
1109
1110 it.effect(
1111 "routes a standard prompt response after Grok extension notifications in the same batch",
1112 () =>
1113 Effect.gen(function* () {
1114 const { stdio, input, output } = yield* makeInMemoryStdio();
1115 const scope = yield* Scope.make();
1116 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
1117
1118 const promptFiber = yield* acp.agent
1119 .prompt({
1120 sessionId: "grok-session-1",
1121 prompt: [{ type: "text", text: "run the ls command" }],
1122 })
1123 .pipe(Effect.forkScoped);
1124
1125 const outbound = yield* Queue.take(output);
1126 const decodedPrompt = yield* decodePromptRequestLine(outbound);
1127
1128 const responseBatch = concatBytes(
1129 yield* Effect.all([
1130 encodeJsonl(XAiQueueChangedNotification, {
1131 jsonrpc: "2.0",
1132 method: "_x.ai/queue/changed",
1133 params: { sessionId: "grok-session-1", entries: [] },
1134 }),
1135 encodeJsonl(XAiPromptCompleteNotification, {
1136 jsonrpc: "2.0",
1137 method: "_x.ai/session/prompt_complete",
1138 params: {
1139 sessionId: "grok-session-1",
1140 promptId: "prompt-1",
1141 stopReason: "end_turn",
1142 agentResult: null,
1143 },
1144 }),
1145 encodeJsonl(XAiSessionsChangedNotification, {
1146 jsonrpc: "2.0",
1147 method: "_x.ai/sessions/changed",
1148 params: {
1149 upserted: [
1150 {
1151 sessionId: "grok-session-1",
1152 title: null,
1153 cwd: process.cwd(),
1154 isWorktree: false,
1155 modelId: "grok-composer-2.5-fast",
1156 yolo: false,
1157 activity: "idle",
1158 resident: true,
1159 lastChangeUnixMs: 1_710_000_000_000,
1160 origin: { kind: "local" },
1161 },
1162 ],
1163 removed: [],
1164 },
1165 }),
1166 encodeJsonl(PromptResponse, {
1167 jsonrpc: "2.0",
1168 id: decodedPrompt.id,
1169 result: {},
1170 }),
1171 encodeJsonl(SessionUpdateNotification, {
1172 jsonrpc: "2.0",
1173 method: "session/update",
1174 params: {
1175 sessionId: "grok-session-1",
1176 update: {
1177 sessionUpdate: "state_update",
1178 state: "idle",
1179 stopReason: "end_turn",
1180 _meta: {
1181 sessionId: "grok-session-1",
1182 requestId: "prompt-1",
1183 promptId: "prompt-1",
1184 modelId: "grok-composer-2.5-fast",
1185 },
1186 },
1187 },
1188 }),
1189 ]),
1190 );
1191 yield* Queue.offer(input, responseBatch);
1192
1193 assert.deepEqual(yield* Fiber.join(promptFiber), {
1194 stopReason: "end_turn",
1195 _meta: {
1196 sessionId: "grok-session-1",
1197 requestId: "prompt-1",
1198 promptId: "prompt-1",
1199 modelId: "grok-composer-2.5-fast",
1200 },
1201 });
1202 yield* Scope.close(scope, Exit.void);
1203 }),
1204 );
1205
1206 it.effect("calls ACP v2 session deletion and provider-management methods", () =>
1207 Effect.gen(function* () {
1208 const handle = yield* makeHandle({ ACP_MOCK_V2_MANAGEMENT: "1" });
1209 const scope = yield* Scope.make();
1210 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
1211
1212 yield* Effect.gen(function* () {
1213 const acp = yield* AcpClient.AcpClient;
1214 const initialized = yield* acp.agent.initialize({
1215 protocolVersion: 2,
1216 clientCapabilities: {},
1217 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
1218 });
1219 assert.ok(initialized.agentCapabilities?.sessionCapabilities?.delete);
1220 assert.ok(initialized.agentCapabilities?.providers);
1221
1222 assert.deepEqual(yield* acp.agent.deleteSession({ sessionId: "mock-session-1" }), {});
1223 assert.deepEqual(yield* acp.agent.listProviders({}), {
1224 providers: [
1225 {
1226 providerId: "mock-provider",
1227 supported: ["openai"],
1228 required: false,
1229 current: null,
1230 },
1231 ],
1232 });
1233 assert.deepEqual(
1234 yield* acp.agent.setProvider({
1235 providerId: "mock-provider",
1236 apiType: "openai",
1237 baseUrl: "https://api.example.test/v1",
1238 headers: { Authorization: "Bearer secret" },
1239 }),
1240 {},
1241 );
1242 assert.deepEqual(yield* acp.agent.disableProvider({ providerId: "mock-provider" }), {});
1243 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
1244 }),
1245 );
1246
1247 it.effect("routes MCP-over-ACP connect, message, notification, and disconnect callbacks", () =>
1248 Effect.gen(function* () {
1249 const handle = yield* makeHandle({ ACP_MOCK_MCP_OVER_ACP: "1" });
1250 const scope = yield* Scope.make();
1251 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
1252 const methods = yield* Ref.make<Array<string>>([]);
1253
1254 yield* Effect.gen(function* () {
1255 const acp = yield* AcpClient.AcpClient;
1256 yield* acp.handleRequestPermission(() =>
1257 Effect.succeed({ outcome: { outcome: "selected", optionId: "allow" } }),
1258 );
1259 yield* acp.handleElicitation(() => Effect.succeed({ action: "decline" }));
1260 yield* acp.handleExtRequest(
1261 "x/typed_request",
1262 Schema.Struct({ message: Schema.String }),
1263 () => Effect.succeed({ ok: true }),
1264 );
1265 yield* acp.handleExtNotification(
1266 "x/typed_notification",
1267 Schema.Struct({ count: Schema.Number }),
1268 () => Effect.void,
1269 );
1270 yield* acp.handleMcpConnect(() =>
1271 Ref.update(methods, (current) => [...current, "connect"]).pipe(
1272 Effect.as({ connectionId: "connection-1" }),
1273 ),
1274 );
1275 yield* acp.handleMcpMessage(() =>
1276 Ref.update(methods, (current) => [...current, "message"]).pipe(Effect.as({ tools: [] })),
1277 );
1278 yield* acp.handleMcpNotification(() =>
1279 Ref.update(methods, (current) => [...current, "notification"]),
1280 );
1281 yield* acp.handleMcpDisconnect(() =>
1282 Ref.update(methods, (current) => [...current, "disconnect"]).pipe(Effect.as({})),
1283 );
1284 yield* acp.agent.initialize({
1285 protocolVersion: 2,
1286 clientCapabilities: {},
1287 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
1288 });
1289 const session = yield* acp.agent.createSession({ cwd: process.cwd(), mcpServers: [] });
1290 yield* acp.agent.prompt({
1291 sessionId: session.sessionId,
1292 prompt: [{ type: "text", text: "exercise MCP" }],
1293 });
1294 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
1295
1296 assert.deepEqual(yield* Ref.get(methods), [
1297 "connect",
1298 "message",
1299 "notification",
1300 "disconnect",
1301 ]);
1302 }),
1303 );
1304
1305 it.effect("preserves future content and session-update variants", () =>
1306 Effect.gen(function* () {
1307 const handle = yield* makeHandle({ ACP_MOCK_UNKNOWN_VARIANTS: "1" });
1308 const scope = yield* Scope.make();
1309 const context = yield* Layer.buildWithScope(AcpClient.layerChildProcess(handle), scope);
1310 const updates = yield* Ref.make<Array<AcpCompat.SessionNotification>>([]);
1311
1312 yield* Effect.gen(function* () {
1313 const acp = yield* AcpClient.AcpClient;
1314 yield* acp.handleRequestPermission(() =>
1315 Effect.succeed({ outcome: { outcome: "selected", optionId: "allow" } }),
1316 );
1317 yield* acp.handleElicitation(() => Effect.succeed({ action: "decline" }));
1318 yield* acp.handleExtRequest(
1319 "x/typed_request",
1320 Schema.Struct({ message: Schema.String }),
1321 () => Effect.succeed({ ok: true }),
1322 );
1323 yield* acp.handleExtNotification(
1324 "x/typed_notification",
1325 Schema.Struct({ count: Schema.Number }),
1326 () => Effect.void,
1327 );
1328 yield* acp.handleSessionUpdate((update) =>
1329 Ref.update(updates, (current) => [...current, update]),
1330 );
1331 yield* acp.agent.initialize({
1332 protocolVersion: 2,
1333 clientCapabilities: {},
1334 clientInfo: { name: "effect-acp-test", version: "0.0.0" },
1335 });
1336 const session = yield* acp.agent.createSession({ cwd: process.cwd(), mcpServers: [] });
1337 yield* acp.agent.prompt({
1338 sessionId: session.sessionId,
1339 prompt: [{ type: "text", text: "exercise future variants" }],
1340 });
1341 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
1342
1343 const received = yield* Ref.get(updates);
1344 assert.deepEqual(received[0]?.update, {
1345 sessionUpdate: "agent_message_chunk",
1346 messageId: "future-content",
1347 content: {
1348 type: "_t3_unknown",
1349 originalType: "chart",
1350 raw: { type: "chart", points: [] },
1351 },
1352 });
1353 assert.deepEqual(received[1]?.update, {
1354 sessionUpdate: "_t3_unknown",
1355 originalSessionUpdate: "timeline_update",
1356 raw: { sessionUpdate: "timeline_update", entries: [] },
1357 });
1358 }),
1359 );
1360});