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 AcpError from "./errors.ts";
21import {
22 encodeJsonl,
23 jsonRpcNotification,
24 jsonRpcRequest,
25 jsonRpcResponse,
26} from "./_internal/shared.ts";
27import { makeInMemoryStdio } from "./_internal/stdio.ts";
28
29const InitializeRequest = jsonRpcRequest("initialize", AcpSchema.InitializeRequest);
30const InitializeResponse = jsonRpcResponse(AcpSchema.InitializeResponse);
31const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
32const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
33const PromptRequest = jsonRpcRequest("session/prompt", AcpSchema.PromptRequest);
34const PromptResponse = jsonRpcResponse(AcpSchema.PromptResponse);
35const SessionUpdateNotification = jsonRpcNotification(
36 "session/update",
37 AcpSchema.SessionNotification,
38);
39const decodePromptRequestLine = Schema.decodeEffect(Schema.fromJsonString(PromptRequest));
40const XAiPromptCompleteNotification = jsonRpcNotification(
41 "_x.ai/session/prompt_complete",
42 Schema.Struct({
43 sessionId: Schema.String,
44 promptId: Schema.String,
45 stopReason: Schema.String,
46 agentResult: Schema.NullOr(Schema.Unknown),
47 }),
48);
49const XAiQueueChangedNotification = jsonRpcNotification(
50 "_x.ai/queue/changed",
51 Schema.Struct({
52 sessionId: Schema.String,
53 entries: Schema.Array(Schema.Unknown),
54 }),
55);
56const XAiSessionsChangedNotification = jsonRpcNotification(
57 "_x.ai/sessions/changed",
58 Schema.Struct({
59 upserted: Schema.Array(Schema.Unknown),
60 removed: Schema.Array(Schema.Unknown),
61 }),
62);
63const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
64 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
65);
66const mockPeerArgs = (path: string) => [path];
67const mockStartupNotice = "Mock ACP startup notice";
68const stripMockStartupNotice = (stdout: ChildProcessSpawner.ChildProcessHandle["stdout"]) =>
69 stdout.pipe(
70 Stream.decodeText,
71 Stream.splitLines,
72 Stream.filter((line) => line !== mockStartupNotice),
73 Stream.map((line) => `${line}\n`),
74 Stream.encodeText,
75 );
76
77function concatBytes(chunks: ReadonlyArray<Uint8Array>): Uint8Array {
78 const batch = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
79 let offset = 0;
80 for (const chunk of chunks) {
81 batch.set(chunk, offset);
82 offset += chunk.length;
83 }
84 return batch;
85}
86
87it.layer(NodeServices.layer)("effect-acp client", (it) => {
88 const makeHandle = (env?: Record<string, string>) =>
89 Effect.gen(function* () {
90 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
91 const path = yield* Path.Path;
92 const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
93 cwd: path.join(import.meta.dirname, ".."),
94 ...(env ? { env: { ...process.env, ...env } } : {}),
95 });
96 return yield* spawner.spawn(command);
97 });
98
99 it.effect("transforms fragmented stdout before parsing and preserves UTF-8", () =>
100 Effect.gen(function* () {
101 const handle = yield* makeHandle({ ACP_MOCK_STDOUT_PREFIX: `${mockStartupNotice}\n` });
102 yield* Effect.gen(function* () {
103 const acp = yield* AcpClient.AcpClient;
104 const initialized = yield* acp.agent.initialize({ protocolVersion: 1 });
105 assert.equal(initialized.protocolVersion, 1);
106
107 const echoed = yield* acp.raw.request("x/echo", { message: "café" });
108 assert.deepEqual(echoed, {
109 echoedMethod: "x/echo",
110 echoedParams: { message: "café" },
111 });
112 }).pipe(
113 Effect.provide(
114 AcpClient.layerChildProcess(handle, {
115 transformStdout: (stdout) =>
116 stdout.pipe(
117 Stream.flatMap((chunk) =>
118 Stream.fromIterable(Array.from(chunk, (byte) => Uint8Array.of(byte))),
119 ),
120 stripMockStartupNotice,
121 ),
122 }),
123 ),
124 );
125 }),
126 );
127
128 it.effect("reports malformed JSON that remains after a stdout transform", () =>
129 Effect.gen(function* () {
130 const handle = yield* makeHandle({
131 ACP_MOCK_STDOUT_PREFIX: `${mockStartupNotice}\n`,
132 ACP_MOCK_MALFORMED_OUTPUT: "1",
133 });
134 const termination = yield* Deferred.make<AcpError.AcpError>();
135 const error = yield* Deferred.await(termination).pipe(
136 Effect.provide(
137 AcpClient.layerChildProcess(handle, {
138 transformStdout: stripMockStartupNotice,
139 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
140 }),
141 ),
142 );
143
144 if (error._tag !== "AcpProtocolParseError") {
145 return assert.fail(`Expected a parse error, got ${error._tag}`);
146 }
147 assert.equal(error.operation, "decode-wire-message");
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<AcpSchema.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 AcpSchema.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("reports idle child termination and rejects later requests and notifications", () =>
248 Effect.gen(function* () {
249 const handle = yield* makeHandle();
250 const termination = yield* Deferred.make<AcpError.AcpError>();
251 yield* Effect.gen(function* () {
252 const acp = yield* AcpClient.AcpClient;
253 yield* acp.agent.initialize({ protocolVersion: 1 });
254 yield* handle.kill();
255
256 const error = yield* Deferred.await(termination);
257 if (error._tag !== "AcpProcessExitedError") {
258 return assert.fail(`Expected a process exit, got ${error._tag}`);
259 }
260 assert.equal(error.pid, handle.pid);
261 assert.equal(error.code, yield* handle.exitCode);
262 const rawRequestError = yield* acp.raw.request("x/echo", {}).pipe(
263 Effect.match({
264 onFailure: (failure) => failure,
265 onSuccess: () => assert.fail("Expected the request to fail after process exit"),
266 }),
267 );
268 assert.strictEqual(rawRequestError, error);
269 assert.strictEqual(yield* acp.raw.notify("x/notify", {}).pipe(Effect.flip), error);
270 assert.strictEqual(
271 yield* acp.agent.cancel({ sessionId: "mock-session-1" }).pipe(Effect.flip),
272 error,
273 );
274
275 const requestError = yield* acp.agent
276 .createSession({ cwd: process.cwd(), mcpServers: [] })
277 .pipe(Effect.flip);
278 assert.strictEqual(requestError, error);
279 }).pipe(
280 Effect.provide(
281 AcpClient.layerChildProcess(handle, {
282 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
283 }),
284 ),
285 );
286 }),
287 );
288
289 it.effect("initializes, prompts, receives updates, and handles permission requests", () =>
290 Effect.gen(function* () {
291 const updates = yield* Ref.make<Array<unknown>>([]);
292 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
293 const typedRequests = yield* Ref.make<Array<unknown>>([]);
294 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
295 const handle = yield* makeHandle();
296 const scope = yield* Scope.make();
297 const acpLayer = AcpClient.layerChildProcess(handle);
298 const context = yield* Layer.buildWithScope(acpLayer, scope);
299
300 const ext = yield* Effect.gen(function* () {
301 const acp = yield* AcpClient.AcpClient;
302
303 yield* acp.handleRequestPermission(() =>
304 Effect.succeed({
305 outcome: {
306 outcome: "selected",
307 optionId: "allow",
308 },
309 }),
310 );
311 yield* acp.handleElicitation(() =>
312 Effect.succeed({
313 action: {
314 action: "accept",
315 content: {
316 approved: true,
317 },
318 },
319 }),
320 );
321 yield* acp.handleSessionUpdate((notification) =>
322 Ref.update(updates, (current) => [...current, notification]),
323 );
324 yield* acp.handleElicitationComplete((notification) =>
325 Ref.update(elicitationCompletions, (current) => [...current, notification]),
326 );
327 yield* acp.handleExtRequest(
328 "x/typed_request",
329 Schema.Struct({ message: Schema.String }),
330 (payload) =>
331 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
332 Effect.as({
333 ok: true,
334 echoedMessage: payload.message,
335 }),
336 ),
337 );
338 yield* acp.handleExtNotification(
339 "x/typed_notification",
340 Schema.Struct({ count: Schema.Number }),
341 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
342 );
343
344 const init = yield* acp.agent.initialize({
345 protocolVersion: 1,
346 clientCapabilities: {
347 fs: { readTextFile: false, writeTextFile: false },
348 terminal: false,
349 },
350 clientInfo: {
351 name: "effect-acp-test",
352 version: "0.0.0",
353 },
354 });
355 assert.equal(init.protocolVersion, 1);
356
357 yield* acp.agent.authenticate({ methodId: "cursor_login" });
358
359 const session = yield* acp.agent.createSession({
360 cwd: process.cwd(),
361 mcpServers: [],
362 });
363 assert.equal(session.sessionId, "mock-session-1");
364
365 const prompt = yield* acp.agent.prompt({
366 sessionId: session.sessionId,
367 prompt: [{ type: "text", text: "hello" }],
368 });
369 assert.equal(prompt.stopReason, "end_turn");
370
371 const streamed = yield* Stream.runCollect(Stream.take(acp.raw.notifications, 2));
372 assert.equal(streamed.length, 2);
373 assert.equal(streamed[0]?._tag, "SessionUpdate");
374 assert.equal(streamed[1]?._tag, "ElicitationComplete");
375 assert.equal((yield* Ref.get(updates)).length, 1);
376 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
377 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
378 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
379
380 return yield* acp.raw.request("x/echo", {
381 hello: "world",
382 });
383 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
384
385 assert.deepEqual(ext, {
386 echoedMethod: "x/echo",
387 echoedParams: {
388 hello: "world",
389 },
390 });
391 }),
392 );
393
394 it.effect(
395 "returns structured invalid params without exposing values from typed extension request payloads",
396 () =>
397 Effect.gen(function* () {
398 const handle = yield* makeHandle({ ACP_MOCK_BAD_TYPED_REQUEST: "1" });
399 const scope = yield* Scope.make();
400 const acpLayer = AcpClient.layerChildProcess(handle);
401 const context = yield* Layer.buildWithScope(acpLayer, scope);
402
403 const result = yield* Effect.gen(function* () {
404 const acp = yield* AcpClient.AcpClient;
405
406 yield* acp.handleRequestPermission(() =>
407 Effect.succeed({
408 outcome: {
409 outcome: "selected",
410 optionId: "allow",
411 },
412 }),
413 );
414 yield* acp.handleElicitation(() =>
415 Effect.succeed({
416 action: {
417 action: "accept",
418 content: {
419 approved: true,
420 },
421 },
422 }),
423 );
424 yield* acp.handleExtRequest(
425 "x/typed_request",
426 Schema.Struct({ message: Schema.String }),
427 () => Effect.succeed({ ok: true }),
428 );
429
430 yield* acp.agent.initialize({
431 protocolVersion: 1,
432 clientCapabilities: {
433 fs: { readTextFile: false, writeTextFile: false },
434 terminal: false,
435 },
436 clientInfo: {
437 name: "effect-acp-test",
438 version: "0.0.0",
439 },
440 });
441
442 yield* acp.agent.authenticate({ methodId: "cursor_login" });
443
444 const session = yield* acp.agent.createSession({
445 cwd: process.cwd(),
446 mcpServers: [],
447 });
448
449 return yield* Effect.exit(
450 acp.agent.prompt({
451 sessionId: session.sessionId,
452 prompt: [{ type: "text", text: "hello" }],
453 }),
454 );
455 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
456
457 if (result._tag !== "Failure") {
458 assert.fail("Expected prompt to fail for invalid typed extension payload");
459 }
460 const rendered = Cause.pretty(result.cause);
461 assert.include(rendered, "Invalid payload for ACP extension method 'x/typed_request'.");
462 assert.notInclude(rendered, "Expected string, got 123");
463 }),
464 );
465
466 it.effect("replays buffered notifications to handlers registered after they arrive", () =>
467 Effect.gen(function* () {
468 const updates = yield* Ref.make<Array<unknown>>([]);
469 const elicitationCompletions = yield* Ref.make<Array<unknown>>([]);
470 const typedRequests = yield* Ref.make<Array<unknown>>([]);
471 const typedNotifications = yield* Ref.make<Array<unknown>>([]);
472 const handle = yield* makeHandle();
473 const scope = yield* Scope.make();
474 const acpLayer = AcpClient.layerChildProcess(handle);
475 const context = yield* Layer.buildWithScope(acpLayer, scope);
476
477 yield* Effect.gen(function* () {
478 const acp = yield* AcpClient.AcpClient;
479
480 yield* acp.handleRequestPermission(() =>
481 Effect.succeed({
482 outcome: {
483 outcome: "selected",
484 optionId: "allow",
485 },
486 }),
487 );
488 yield* acp.handleElicitation(() =>
489 Effect.succeed({
490 action: {
491 action: "accept",
492 content: {
493 approved: true,
494 },
495 },
496 }),
497 );
498 yield* acp.handleExtRequest(
499 "x/typed_request",
500 Schema.Struct({ message: Schema.String }),
501 (payload) =>
502 Ref.update(typedRequests, (current) => [...current, payload]).pipe(
503 Effect.as({
504 ok: true,
505 echoedMessage: payload.message,
506 }),
507 ),
508 );
509 yield* acp.handleExtNotification(
510 "x/typed_notification",
511 Schema.Struct({ count: Schema.Number }),
512 (payload) => Ref.update(typedNotifications, (current) => [...current, payload]),
513 );
514
515 yield* acp.agent.initialize({
516 protocolVersion: 1,
517 clientCapabilities: {
518 fs: { readTextFile: false, writeTextFile: false },
519 terminal: false,
520 },
521 clientInfo: {
522 name: "effect-acp-test",
523 version: "0.0.0",
524 },
525 });
526 yield* acp.agent.authenticate({ methodId: "cursor_login" });
527
528 const session = yield* acp.agent.createSession({
529 cwd: process.cwd(),
530 mcpServers: [],
531 });
532 yield* acp.agent.prompt({
533 sessionId: session.sessionId,
534 prompt: [{ type: "text", text: "hello" }],
535 });
536
537 yield* acp.handleSessionUpdate((notification) =>
538 Ref.update(updates, (current) => [...current, notification]),
539 );
540 yield* acp.handleElicitationComplete((notification) =>
541 Ref.update(elicitationCompletions, (current) => [...current, notification]),
542 );
543
544 assert.equal((yield* Ref.get(updates)).length, 1);
545 assert.equal((yield* Ref.get(elicitationCompletions)).length, 1);
546 assert.deepEqual(yield* Ref.get(typedRequests), [{ message: "hello from typed request" }]);
547 assert.deepEqual(yield* Ref.get(typedNotifications), [{ count: 2 }]);
548 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
549 }),
550 );
551
552 it.effect("continues dispatching session updates after one handler fails", () =>
553 Effect.gen(function* () {
554 const successfulHandlers = yield* Ref.make(0);
555 const handle = yield* makeHandle();
556 const scope = yield* Scope.make();
557 const acpLayer = AcpClient.layerChildProcess(handle);
558 const context = yield* Layer.buildWithScope(acpLayer, scope);
559
560 yield* Effect.gen(function* () {
561 const acp = yield* AcpClient.AcpClient;
562
563 yield* acp.handleRequestPermission(() =>
564 Effect.succeed({
565 outcome: {
566 outcome: "selected",
567 optionId: "allow",
568 },
569 }),
570 );
571 yield* acp.handleElicitation(() =>
572 Effect.succeed({
573 action: {
574 action: "accept",
575 content: {
576 approved: true,
577 },
578 },
579 }),
580 );
581 yield* acp.handleExtRequest(
582 "x/typed_request",
583 Schema.Struct({ message: Schema.String }),
584 () => Effect.succeed({ ok: true }),
585 );
586 yield* acp.handleExtNotification(
587 "x/typed_notification",
588 Schema.Struct({ count: Schema.Number }),
589 () => Effect.void,
590 );
591 yield* acp.handleSessionUpdate(() =>
592 Effect.fail(AcpError.AcpRequestError.internalError("session update handler failed")),
593 );
594 yield* acp.handleSessionUpdate(() => Ref.update(successfulHandlers, (count) => count + 1));
595
596 yield* acp.agent.initialize({
597 protocolVersion: 1,
598 clientCapabilities: {
599 fs: { readTextFile: false, writeTextFile: false },
600 terminal: false,
601 },
602 clientInfo: {
603 name: "effect-acp-test",
604 version: "0.0.0",
605 },
606 });
607 yield* acp.agent.authenticate({ methodId: "cursor_login" });
608
609 const session = yield* acp.agent.createSession({
610 cwd: process.cwd(),
611 mcpServers: [],
612 });
613 yield* acp.agent.prompt({
614 sessionId: session.sessionId,
615 prompt: [{ type: "text", text: "hello" }],
616 });
617
618 assert.equal(yield* Ref.get(successfulHandlers), 1);
619 }).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
620 }),
621 );
622
623 it.effect("uses distinct ids for RPC calls and extension requests", () =>
624 Effect.gen(function* () {
625 const { stdio, input, output } = yield* makeInMemoryStdio();
626 const scope = yield* Scope.make();
627 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
628
629 const initializeFiber = yield* acp.agent
630 .initialize({
631 protocolVersion: 1,
632 clientCapabilities: {
633 fs: { readTextFile: false, writeTextFile: false },
634 terminal: false,
635 },
636 clientInfo: {
637 name: "effect-acp-test",
638 version: "0.0.0",
639 },
640 })
641 .pipe(Effect.forkScoped);
642 const extFiber = yield* acp.raw.request("x/test", { hello: "world" }).pipe(Effect.forkScoped);
643
644 const firstOutbound = yield* Queue.take(output);
645 const secondOutbound = yield* Queue.take(output);
646
647 const decodedInitialize = Schema.decodeEffect(Schema.fromJsonString(InitializeRequest));
648 const decodedExt = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
649 const firstIsInitialize = yield* decodedInitialize(firstOutbound).pipe(
650 Effect.match({
651 onFailure: () => false,
652 onSuccess: () => true,
653 }),
654 );
655
656 const initializeRequest = firstIsInitialize
657 ? yield* decodedInitialize(firstOutbound)
658 : yield* decodedInitialize(secondOutbound);
659 const extRequest = firstIsInitialize
660 ? yield* decodedExt(secondOutbound)
661 : yield* decodedExt(firstOutbound);
662
663 assert.notEqual(initializeRequest.id, extRequest.id);
664
665 yield* Queue.offer(
666 input,
667 yield* encodeJsonl(InitializeResponse, {
668 jsonrpc: "2.0",
669 id: initializeRequest.id,
670 result: {
671 protocolVersion: 1,
672 agentCapabilities: {},
673 agentInfo: {
674 name: "mock-agent",
675 version: "0.0.0",
676 },
677 },
678 }),
679 );
680 yield* Queue.offer(
681 input,
682 yield* encodeJsonl(ExtResponse, {
683 jsonrpc: "2.0",
684 id: extRequest.id,
685 result: { ok: true },
686 }),
687 );
688
689 yield* Fiber.join(initializeFiber);
690 assert.deepEqual(yield* Fiber.join(extFiber), { ok: true });
691 yield* Scope.close(scope, Exit.void);
692 }),
693 );
694
695 it.effect(
696 "routes a standard prompt response after Grok extension notifications in the same batch",
697 () =>
698 Effect.gen(function* () {
699 const { stdio, input, output } = yield* makeInMemoryStdio();
700 const scope = yield* Scope.make();
701 const acp = yield* AcpClient.make(stdio).pipe(Effect.provideService(Scope.Scope, scope));
702
703 const promptFiber = yield* acp.agent
704 .prompt({
705 sessionId: "grok-session-1",
706 prompt: [{ type: "text", text: "run the ls command" }],
707 })
708 .pipe(Effect.forkScoped);
709
710 const outbound = yield* Queue.take(output);
711 const decodedPrompt = yield* decodePromptRequestLine(outbound);
712
713 const responseBatch = concatBytes(
714 yield* Effect.all([
715 encodeJsonl(XAiQueueChangedNotification, {
716 jsonrpc: "2.0",
717 method: "_x.ai/queue/changed",
718 params: { sessionId: "grok-session-1", entries: [] },
719 }),
720 encodeJsonl(XAiPromptCompleteNotification, {
721 jsonrpc: "2.0",
722 method: "_x.ai/session/prompt_complete",
723 params: {
724 sessionId: "grok-session-1",
725 promptId: "prompt-1",
726 stopReason: "end_turn",
727 agentResult: null,
728 },
729 }),
730 encodeJsonl(XAiSessionsChangedNotification, {
731 jsonrpc: "2.0",
732 method: "_x.ai/sessions/changed",
733 params: {
734 upserted: [
735 {
736 sessionId: "grok-session-1",
737 title: null,
738 cwd: process.cwd(),
739 isWorktree: false,
740 modelId: "grok-composer-2.5-fast",
741 yolo: false,
742 activity: "idle",
743 resident: true,
744 lastChangeUnixMs: 1_710_000_000_000,
745 origin: { kind: "local" },
746 },
747 ],
748 removed: [],
749 },
750 }),
751 encodeJsonl(PromptResponse, {
752 jsonrpc: "2.0",
753 id: decodedPrompt.id,
754 result: {
755 stopReason: "end_turn",
756 _meta: {
757 sessionId: "grok-session-1",
758 requestId: "prompt-1",
759 promptId: "prompt-1",
760 modelId: "grok-composer-2.5-fast",
761 },
762 },
763 }),
764 ]),
765 );
766 yield* Queue.offer(input, responseBatch);
767
768 assert.deepEqual(yield* Fiber.join(promptFiber), {
769 stopReason: "end_turn",
770 _meta: {
771 sessionId: "grok-session-1",
772 requestId: "prompt-1",
773 promptId: "prompt-1",
774 modelId: "grok-composer-2.5-fast",
775 },
776 });
777 yield* Scope.close(scope, Exit.void);
778 }),
779 );
780});
781
782const elicitationForm = {
783 sessionId: "session-1",
784 mode: "form" as const,
785 message: "Continue?",
786 requestedSchema: {
787 type: "object" as const,
788 properties: { choice: { type: "string" as const } },
789 required: ["choice"],
790 },
791};
792const decodeWireResponse = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
793const decodeWireError = Schema.decodeEffect(
794 Schema.fromJsonString(Schema.Struct({ error: Schema.Struct({ code: Schema.Finite }) })),
795);
796
797it.effect.each(["accept", "decline", "cancel"] as const)(
798 "returns a flat %s action to the SDK and preserves the legacy response",
799 (action) =>
800 Effect.gen(function* () {
801 for (const method of ["elicitation/create", "session/elicitation"]) {
802 const { stdio, input, output } = yield* makeInMemoryStdio();
803 const acp = yield* AcpClient.make(stdio);
804 const answer = action === "accept" ? { action, content: { choice: "yes" } } : { action };
805 const response = { action: answer, _meta: { trace: "fixture" } };
806 yield* acp.handleElicitation((request) => {
807 assert.deepEqual(request, elicitationForm);
808 return Effect.succeed(response);
809 });
810 yield* Queue.offer(
811 input,
812 yield* encodeJsonl(jsonRpcRequest(method, AcpSchema.ElicitationRequest), {
813 jsonrpc: "2.0",
814 id: 71,
815 headers: [],
816 method,
817 params: elicitationForm,
818 }),
819 );
820 const received = yield* decodeWireResponse(yield* Queue.take(output));
821 assert.deepEqual(received, {
822 jsonrpc: "2.0",
823 id: 71,
824 result: method === "elicitation/create" ? { ...answer, _meta: response._meta } : response,
825 });
826 }
827 }).pipe(Effect.scoped),
828);
829
830it.effect("dispatches SDK URL elicitation to the same registered handler", () =>
831 Effect.gen(function* () {
832 const { stdio, input, output } = yield* makeInMemoryStdio();
833 const acp = yield* AcpClient.make(stdio);
834 const params = {
835 sessionId: "session-1",
836 mode: "url" as const,
837 message: "Sign in",
838 elicitationId: "elicitation-1",
839 url: "https://example.test/sign-in",
840 };
841 yield* acp.handleElicitation((request) => {
842 assert.deepEqual(request, params);
843 return Effect.succeed({ action: { action: "accept" as const } });
844 });
845 yield* Queue.offer(
846 input,
847 yield* encodeJsonl(jsonRpcRequest("elicitation/create", AcpSchema.ElicitationRequest), {
848 jsonrpc: "2.0",
849 id: 72,
850 headers: [],
851 method: "elicitation/create",
852 params,
853 }),
854 );
855 assert.deepEqual(yield* decodeWireResponse(yield* Queue.take(output)), {
856 jsonrpc: "2.0",
857 id: 72,
858 result: { action: "accept" },
859 });
860 }).pipe(Effect.scoped),
861);
862
863it.effect.each(["elicitation/complete", "session/elicitation/complete"])(
864 "delivers %s notifications to the completion handler",
865 (method) =>
866 Effect.gen(function* () {
867 const { stdio, input } = yield* makeInMemoryStdio();
868 const acp = yield* AcpClient.make(stdio);
869 const received = yield* Deferred.make<AcpSchema.ElicitationCompleteNotification>();
870 yield* acp.handleElicitationComplete((notification) =>
871 Deferred.succeed(received, notification).pipe(Effect.asVoid),
872 );
873 yield* Queue.offer(
874 input,
875 yield* encodeJsonl(jsonRpcNotification(method, AcpSchema.ElicitationCompleteNotification), {
876 jsonrpc: "2.0",
877 method,
878 params: { elicitationId: "elicitation-1" },
879 }),
880 );
881 assert.deepEqual(yield* Deferred.await(received), { elicitationId: "elicitation-1" });
882 }).pipe(Effect.scoped),
883);
884
885it.effect("rejects malformed SDK elicitation without calling the question handler", () =>
886 Effect.gen(function* () {
887 const { stdio, input, output } = yield* makeInMemoryStdio();
888 const acp = yield* AcpClient.make(stdio);
889 let calls = 0;
890 yield* acp.handleElicitation(() => {
891 calls++;
892 return Effect.succeed({ action: { action: "cancel" as const } });
893 });
894 yield* Queue.offer(
895 input,
896 yield* encodeJsonl(jsonRpcRequest("elicitation/create", Schema.Unknown), {
897 jsonrpc: "2.0",
898 id: 73,
899 headers: [],
900 method: "elicitation/create",
901 params: { ...elicitationForm, message: 123 },
902 }),
903 );
904 const response = yield* decodeWireError(yield* Queue.take(output));
905 assert.equal(response.error.code, -32602);
906 assert.equal(calls, 0);
907 }).pipe(Effect.scoped),
908);
909
910it.effect("returns method-not-found when SDK elicitation has no question handler", () =>
911 Effect.gen(function* () {
912 const { stdio, input, output } = yield* makeInMemoryStdio();
913 yield* AcpClient.make(stdio);
914 yield* Queue.offer(
915 input,
916 yield* encodeJsonl(jsonRpcRequest("elicitation/create", AcpSchema.ElicitationRequest), {
917 jsonrpc: "2.0",
918 id: 74,
919 headers: [],
920 method: "elicitation/create",
921 params: elicitationForm,
922 }),
923 );
924 const response = yield* decodeWireError(yield* Queue.take(output));
925 assert.equal(response.error.code, -32601);
926 }).pipe(Effect.scoped),
927);