Open History to see the last commit
1import * as Path from "effect/Path";
2import * as AcpError from "./errors.ts";
3import * as Effect from "effect/Effect";
4import * as Deferred from "effect/Deferred";
5import * as Fiber from "effect/Fiber";
6import * as Exit from "effect/Exit";
7import * as Logger from "effect/Logger";
8import * as Queue from "effect/Queue";
9import * as References from "effect/References";
10import * as Schema from "effect/Schema";
11import * as Scope from "effect/Scope";
12import * as Sink from "effect/Sink";
13import * as Stdio from "effect/Stdio";
14import * as Stream from "effect/Stream";
15import * as Ref from "effect/Ref";
16import * as TestClock from "effect/testing/TestClock";
17import { ChildProcess, ChildProcessSpawner } from "effect/process";
18
19import { it, assert } from "@effect/vitest";
20import * as NodeServices from "@effect/platform-node/NodeServices";
21
22import * as AcpSchema from "./schema.ts";
23import * as AcpProtocol from "./protocol.ts";
24import {
25 encodeJsonl,
26 jsonRpcNotification,
27 jsonRpcRequest,
28 jsonRpcResponse,
29} from "./_internal/shared.ts";
30import { makeInMemoryStdio, makeTerminationError, makeChildStdio } from "./_internal/stdio.ts";
31
32const SessionCancelNotification = jsonRpcNotification(
33 "session/cancel",
34 AcpSchema.CancelNotification,
35);
36const SessionUpdateNotification = jsonRpcNotification(
37 "session/update",
38 AcpSchema.SessionNotification,
39);
40const ElicitationCompleteNotification = jsonRpcNotification(
41 "elicitation/complete",
42 AcpSchema.CompleteElicitationNotification,
43);
44const RequestPermissionRequest = jsonRpcRequest(
45 "session/request_permission",
46 AcpSchema.RequestPermissionRequest,
47);
48const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
49const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
50const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
51const decodeSessionCancelNotification = Schema.decodeEffect(
52 Schema.fromJsonString(SessionCancelNotification),
53);
54const decodeExtRequest = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
55const decodeExtResponse = Schema.decodeEffect(Schema.fromJsonString(ExtResponse));
56const decodeRequestPermissionResponse = Schema.decodeEffect(
57 Schema.fromJsonString(RequestPermissionResponse),
58);
59const decodeJsonRpcRequestId = Schema.decodeEffect(
60 Schema.fromJsonString(Schema.Struct({ id: Schema.Number })),
61);
62const JsonRpcErrorResponse = Schema.Struct({
63 jsonrpc: Schema.Literal("2.0"),
64 id: Schema.Number,
65 error: Schema.Struct({ code: Schema.Number, message: Schema.String }),
66});
67const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
68const encoder = new TextEncoder();
69const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
70 path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
71);
72const mockPeerArgs = (path: string) => [path];
73
74const makeHandle = (env?: Record<string, string>) =>
75 Effect.gen(function* () {
76 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
77 const path = yield* Path.Path;
78 const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
79 cwd: path.join(import.meta.dirname, ".."),
80 ...(env ? { env: { ...process.env, ...env } } : {}),
81 });
82 return yield* spawner.spawn(command);
83 });
84
85it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
86 it.effect(
87 "emits exact JSON-RPC notifications and decodes inbound session/update and elicitation completion",
88 () =>
89 Effect.gen(function* () {
90 const { stdio, input, output } = yield* makeInMemoryStdio();
91 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
92 stdio,
93 serverRequestMethods: new Set(),
94 });
95
96 const notifications =
97 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
98 yield* transport.incoming.pipe(
99 Stream.take(2),
100 Stream.runCollect,
101 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
102 Effect.forkScoped,
103 );
104
105 yield* transport.notify("session/cancel", { sessionId: "session-1" });
106 const outbound = yield* Queue.take(output);
107 assert.deepEqual(yield* decodeSessionCancelNotification(outbound), {
108 jsonrpc: "2.0",
109 method: "session/cancel",
110 params: {
111 sessionId: "session-1",
112 },
113 });
114
115 yield* Queue.offer(
116 input,
117 yield* encodeJsonl(SessionUpdateNotification, {
118 jsonrpc: "2.0",
119 method: "session/update",
120 params: {
121 sessionId: "session-1",
122 update: {
123 sessionUpdate: "plan",
124 entries: [
125 {
126 content: "Inspect repository",
127 priority: "high",
128 status: "in_progress",
129 },
130 ],
131 },
132 },
133 }),
134 );
135
136 yield* Queue.offer(
137 input,
138 yield* encodeJsonl(ElicitationCompleteNotification, {
139 jsonrpc: "2.0",
140 method: "elicitation/complete",
141 params: {
142 elicitationId: "elicitation-1",
143 },
144 }),
145 );
146
147 const [update, completion] = yield* Deferred.await(notifications);
148 assert.equal(update?._tag, "SessionUpdate");
149 assert.equal(completion?._tag, "ElicitationComplete");
150 }),
151 );
152
153 it.effect("keeps only recent raw notifications after their callbacks run", () =>
154 Effect.gen(function* () {
155 const { stdio, input } = yield* makeInMemoryStdio();
156 const handled = yield* Deferred.make<void>();
157 let handledCount = 0;
158 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
159 stdio,
160 serverRequestMethods: new Set(),
161 onNotification: () =>
162 Effect.sync(() => ++handledCount).pipe(
163 Effect.flatMap((count) =>
164 count === 64 ? Deferred.succeed(handled, undefined).pipe(Effect.asVoid) : Effect.void,
165 ),
166 ),
167 });
168
169 const messages = Array.from({ length: 64 }, (_, index) =>
170 encodeUnknownJsonString({
171 jsonrpc: "2.0",
172 method: "x/performance",
173 params: { index },
174 }),
175 );
176 yield* Queue.offer(input, encoder.encode(`${messages.join("\n")}\n`));
177 yield* Deferred.await(handled);
178
179 const retained = yield* transport.incoming.pipe(Stream.take(32), Stream.runCollect);
180
181 assert.equal(handledCount, 64);
182 assert.equal(retained.length, 32);
183 assert.deepEqual(retained[0]?.params, { index: 32 });
184 assert.deepEqual(retained[31]?.params, { index: 63 });
185 }),
186 );
187
188 it.effect("decodes standard JSON-RPC errors into typed ACP request failures", () =>
189 Effect.gen(function* () {
190 const { stdio, input, output } = yield* makeInMemoryStdio();
191 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
192 stdio,
193 serverRequestMethods: new Set(),
194 });
195
196 const request = yield* transport.request("x/auth", {}).pipe(Effect.forkScoped);
197 const outbound = yield* decodeJsonRpcRequestId(yield* Queue.take(output));
198 yield* Queue.offer(
199 input,
200 yield* encodeJsonl(JsonRpcErrorResponse, {
201 jsonrpc: "2.0",
202 id: outbound.id,
203 error: { code: -32000, message: "Authentication required" },
204 }),
205 );
206
207 const error = yield* Fiber.join(request).pipe(Effect.flip, Effect.orDie);
208 assert.instanceOf(error, AcpError.AcpRequestError);
209 assert.equal(error.code, -32000);
210 assert.equal(error.message, "Authentication required");
211 }),
212 );
213
214 // clanka once sent a usage_update without `used` and `size`. One bad update
215 // must not end a session whose later updates are fine.
216 it.effect("drops a session/update that fails to decode and keeps reading", () =>
217 Effect.gen(function* () {
218 const secret = "acp-core-notification-secret-sentinel";
219 const { stdio, input } = yield* makeInMemoryStdio();
220 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
221 const warnings: Array<unknown> = [];
222 let terminated = false;
223 let transformCalls = 0;
224 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
225 stdio,
226 serverRequestMethods: new Set(),
227 logIncoming: true,
228 logger: (event) =>
229 Effect.sync(() => {
230 events.push(event);
231 }),
232 transformSessionUpdate: (notification) => {
233 transformCalls += 1;
234 return notification;
235 },
236 onTermination: () =>
237 Effect.sync(() => {
238 terminated = true;
239 }),
240 }).pipe(
241 Effect.provide(
242 Logger.layer([
243 Logger.make(({ logLevel, fiber }) => {
244 if (logLevel === "Warn")
245 warnings.push(fiber.getRef(References.CurrentLogAnnotations));
246 }),
247 ]),
248 ),
249 );
250 const received = yield* Deferred.make<AcpProtocol.AcpIncomingNotification>();
251 yield* transport.incoming.pipe(
252 Stream.runForEach((notification) => Deferred.succeed(received, notification)),
253 Effect.forkScoped,
254 );
255
256 const send = (params: unknown) =>
257 Queue.offer(
258 input,
259 encoder.encode(
260 `${encodeUnknownJsonString({ jsonrpc: "2.0", method: "session/update", params })}\n`,
261 ),
262 );
263 const malformed = {
264 sessionId: "session-1",
265 update: { sessionUpdate: "usage_update", cost: { amount: 1, currency: secret } },
266 };
267 yield* send(malformed);
268 yield* send(malformed);
269 yield* send({
270 sessionId: "session-1",
271 update: { sessionUpdate: "usage_update", used: 10, size: 100 },
272 });
273
274 const notification = yield* TestClock.withLive(
275 Deferred.await(received).pipe(Effect.timeout("2 seconds")),
276 );
277 assert.equal(notification._tag, "SessionUpdate");
278 assert.deepEqual(notification.params, {
279 sessionId: "session-1",
280 update: { sessionUpdate: "usage_update", used: 10, size: 100 },
281 });
282 assert.isFalse(terminated);
283 assert.equal(transformCalls, 1);
284
285 const decodeFailed = events.find(({ stage }) => stage === "decode_failed");
286 assert.deepInclude(decodeFailed?.payload as object, {
287 operation: "decode-notification-payload",
288 method: "session/update",
289 issueSummary: "update.used missing",
290 });
291 assert.lengthOf(
292 events.filter(({ stage }) => stage === "decode_failed"),
293 2,
294 );
295 assert.lengthOf(warnings, 1);
296 assert.deepInclude(warnings[0] as object, {
297 issueSummary: "update.used missing",
298 });
299 assert.notInclude(encodeUnknownJsonString({ decodeFailed, warnings }), secret);
300 }),
301 );
302
303 it.effect("keeps invalid core notification values only in the schema cause", () =>
304 Effect.gen(function* () {
305 const secret = "acp-core-notification-secret-sentinel";
306 const cause = yield* Schema.decodeUnknownEffect(AcpSchema.SessionNotification)({
307 sessionId: { secret },
308 update: { sessionUpdate: "plan", entries: [] },
309 }).pipe(Effect.flip);
310 const parseError = AcpError.AcpProtocolParseError.fromSchemaError(
311 "decode-notification-payload",
312 "session/update",
313 cause,
314 );
315 const { cause: directCause, ...directDiagnostics } = parseError;
316 assert.equal(parseError.operation, "decode-notification-payload");
317 assert.equal(parseError.method, "session/update");
318 assert.isAbove(parseError.issueCount ?? 0, 0);
319 assert.include(parseError.issueKinds ?? [], "Pointer");
320 assert.isAbove(parseError.maximumPathDepth ?? 0, 0);
321 assert.equal(parseError.issueSummary, "sessionId wrong type");
322 assert.isTrue(Schema.isSchemaError(directCause));
323 assert.notInclude(parseError.message, secret);
324 assert.notInclude(encodeUnknownJsonString(directDiagnostics), secret);
325 }),
326 );
327
328 it.effect("terminates when a callback on the reader dies", () =>
329 Effect.gen(function* () {
330 const { stdio, input } = yield* makeInMemoryStdio();
331 const termination = yield* Deferred.make<AcpError.AcpError>();
332 yield* AcpProtocol.makeAcpPatchedProtocol({
333 stdio,
334 serverRequestMethods: new Set(),
335 transformSessionUpdate: () => {
336 throw new Error("normalizer bug");
337 },
338 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
339 });
340
341 yield* Queue.offer(
342 input,
343 encoder.encode(
344 `${encodeUnknownJsonString({
345 jsonrpc: "2.0",
346 method: "session/update",
347 params: {
348 sessionId: "session-1",
349 update: { sessionUpdate: "plan", entries: [] },
350 },
351 })}\n`,
352 ),
353 );
354
355 const error = yield* TestClock.withLive(
356 Deferred.await(termination).pipe(Effect.timeout("2 seconds")),
357 );
358 assert.instanceOf(error, AcpError.AcpTransportError);
359 assert.equal((error as AcpError.AcpTransportError).operation, "read-input-stream");
360 }),
361 );
362
363 it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
364 Effect.gen(function* () {
365 const { stdio } = yield* makeInMemoryStdio();
366 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
367 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
368 stdio,
369 serverRequestMethods: new Set(),
370 logOutgoing: true,
371 logger: (event) =>
372 Effect.sync(() => {
373 events.push(event);
374 }),
375 });
376
377 yield* transport.notify("session/cancel", { sessionId: "session-1" });
378
379 // A notification must not carry `id` or `headers`. Grok CLI drops frames that do.
380 assert.deepEqual(events, [
381 {
382 direction: "outgoing",
383 stage: "decoded",
384 payload: {
385 _tag: "Notification",
386 tag: "session/cancel",
387 payload: {
388 sessionId: "session-1",
389 },
390 },
391 },
392 {
393 direction: "outgoing",
394 stage: "raw",
395 payload:
396 '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"}}\n',
397 },
398 ]);
399 }),
400 );
401
402 it.effect("logs decode failures without copying the cause or wire payload", () =>
403 Effect.gen(function* () {
404 const secret = "acp-wire-secret-sentinel";
405 const { stdio, input } = yield* makeInMemoryStdio();
406 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
407 const termination = yield* Deferred.make<AcpError.AcpError>();
408 yield* AcpProtocol.makeAcpPatchedProtocol({
409 stdio,
410 serverRequestMethods: new Set(),
411 logIncoming: true,
412 logger: (event) =>
413 Effect.sync(() => {
414 events.push(event);
415 }),
416 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
417 });
418
419 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
420 yield* Deferred.await(termination);
421
422 const event = events.find(({ stage }) => stage === "decode_failed");
423 assert.deepEqual(event, {
424 direction: "incoming",
425 stage: "decode_failed",
426 payload: {
427 operation: "decode-wire-message",
428 },
429 });
430 assert.notInclude(encodeUnknownJsonString(event), secret);
431 }),
432 );
433
434 it.effect("fails notification encoding through the declared ACP error channel", () =>
435 Effect.gen(function* () {
436 const { stdio } = yield* makeInMemoryStdio();
437 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
438 stdio,
439 serverRequestMethods: new Set(),
440 });
441
442 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
443 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
444 assert.equal(bigintError.operation, "encode-message");
445 assert.equal(bigintError.method, "x/test");
446 assert.isDefined(bigintError.cause);
447 assert.equal(
448 bigintError.message,
449 "ACP protocol operation 'encode-message' failed for method 'x/test'.",
450 );
451
452 const circular: Record<string, unknown> = {};
453 circular.self = circular;
454 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
455 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
456 assert.equal(circularError.operation, "encode-message");
457 assert.equal(circularError.method, "x/test");
458 assert.isDefined(circularError.cause);
459
460 const requestError = yield* transport.request("x/request", 1n).pipe(
461 Effect.match({
462 onFailure: (error) => error,
463 onSuccess: () => assert.fail("Expected request encoding to fail"),
464 }),
465 );
466 assert.instanceOf(requestError, AcpError.AcpProtocolParseError);
467 assert.deepInclude(requestError, {
468 operation: "encode-message",
469 method: "x/request",
470 requestId: 1,
471 });
472 }),
473 );
474
475 it.effect("supports generic extension requests over the patched transport", () =>
476 Effect.gen(function* () {
477 const { stdio, input, output } = yield* makeInMemoryStdio();
478 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
479 stdio,
480 serverRequestMethods: new Set(),
481 });
482
483 const response = yield* transport
484 .request("x/test", { hello: "world" })
485 .pipe(Effect.forkScoped);
486 const outbound = yield* Queue.take(output);
487 assert.deepEqual(yield* decodeExtRequest(outbound), {
488 jsonrpc: "2.0",
489 id: 1,
490 method: "x/test",
491 params: {
492 hello: "world",
493 },
494 headers: [],
495 });
496
497 yield* Queue.offer(
498 input,
499 yield* encodeJsonl(ExtResponse, {
500 jsonrpc: "2.0",
501 id: 1,
502 result: {
503 ok: true,
504 },
505 }),
506 );
507
508 const resolved = yield* Fiber.join(response);
509 assert.deepEqual(resolved, { ok: true });
510 }),
511 );
512
513 it.effect("does not correlate a string response id with a numeric extension request id", () =>
514 Effect.gen(function* () {
515 const { stdio, input, output } = yield* makeInMemoryStdio();
516 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
517 stdio,
518 serverRequestMethods: new Set(),
519 });
520
521 const response = yield* transport
522 .request("x/test", { hello: "world" })
523 .pipe(Effect.forkScoped);
524 yield* Queue.take(output);
525 yield* Queue.offer(
526 input,
527 encoder.encode(
528 `${encodeUnknownJsonString({
529 jsonrpc: "2.0",
530 id: "1",
531 result: { ok: false },
532 })}\n`,
533 ),
534 );
535 yield* Effect.yieldNow;
536 assert.isUndefined(response.pollUnsafe());
537
538 yield* Queue.offer(
539 input,
540 yield* encodeJsonl(ExtResponse, {
541 jsonrpc: "2.0",
542 id: 1,
543 result: { ok: true },
544 }),
545 );
546 assert.deepEqual(yield* Fiber.join(response), { ok: true });
547 }),
548 );
549
550 it.effect("correlates extension response errors with the originating request", () =>
551 Effect.gen(function* () {
552 const { stdio, input, output } = yield* makeInMemoryStdio();
553 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
554 stdio,
555 serverRequestMethods: new Set(),
556 });
557
558 const response = yield* transport
559 .request("x/private", { hello: "world" })
560 .pipe(Effect.forkScoped);
561 yield* Queue.take(output);
562 yield* Queue.offer(
563 input,
564 encoder.encode(
565 `${encodeUnknownJsonString({
566 jsonrpc: "2.0",
567 id: 1,
568 error: {
569 _tag: "Cause",
570 code: -32602,
571 message: "Invalid params",
572 data: [
573 {
574 _tag: "Fail",
575 error: {
576 code: -32602,
577 message: "Invalid params",
578 data: { field: "hello" },
579 },
580 },
581 ],
582 },
583 })}\n`,
584 ),
585 );
586
587 const error = yield* Fiber.join(response).pipe(
588 Effect.match({
589 onFailure: (error) => error,
590 onSuccess: () => assert.fail("Expected extension request to fail"),
591 }),
592 );
593 assert.instanceOf(error, AcpError.AcpRequestError);
594 assert.deepInclude(error, {
595 code: -32602,
596 errorMessage: "Invalid params",
597 method: "x/private",
598 requestId: 1,
599 operation: "receive-response",
600 });
601 }),
602 );
603
604 it.effect("answers an extension request whose handler also dies as an internal error", () =>
605 Effect.gen(function* () {
606 const { stdio, input, output } = yield* makeInMemoryStdio();
607 yield* AcpProtocol.makeAcpPatchedProtocol({
608 stdio,
609 serverRequestMethods: new Set(),
610 onExtRequest: () =>
611 Effect.fail(AcpError.AcpRequestError.invalidParams("bad params")).pipe(
612 Effect.ensuring(Effect.die(new Error("cleanup bug"))),
613 ),
614 });
615
616 yield* Queue.offer(
617 input,
618 yield* encodeJsonl(ExtRequest, {
619 jsonrpc: "2.0",
620 id: 9,
621 method: "x/test",
622 params: { hello: "world" },
623 headers: [],
624 }),
625 );
626
627 const response = yield* Schema.decodeUnknownEffect(
628 Schema.fromJsonString(JsonRpcErrorResponse),
629 )(yield* Queue.take(output));
630 assert.equal(response.id, 9);
631 assert.equal(response.error.code, -32603);
632 }),
633 );
634
635 it.effect("preserves numeric ids for inbound extension requests", () =>
636 Effect.gen(function* () {
637 const { stdio, input, output } = yield* makeInMemoryStdio();
638 yield* AcpProtocol.makeAcpPatchedProtocol({
639 stdio,
640 serverRequestMethods: new Set(),
641 onExtRequest: () => Effect.succeed({ ok: true }),
642 });
643
644 yield* Queue.offer(
645 input,
646 yield* encodeJsonl(ExtRequest, {
647 jsonrpc: "2.0",
648 id: 7,
649 method: "x/test",
650 params: {
651 hello: "world",
652 },
653 headers: [],
654 }),
655 );
656
657 const outbound = yield* Queue.take(output);
658 assert.deepEqual(yield* decodeExtResponse(outbound), {
659 jsonrpc: "2.0",
660 id: 7,
661 result: {
662 ok: true,
663 },
664 });
665 }),
666 );
667
668 it.effect("keeps numeric and string extension request ids distinct in handler context", () =>
669 Effect.gen(function* () {
670 const { stdio, input } = yield* makeInMemoryStdio();
671 const contexts = yield* Queue.unbounded<string>();
672 yield* AcpProtocol.makeAcpPatchedProtocol({
673 stdio,
674 serverRequestMethods: new Set(),
675 onExtRequest: (_method, _params, context) =>
676 Queue.offer(contexts, context.requestId).pipe(Effect.as({ ok: true })),
677 });
678
679 for (const id of [1, "1"] as const) {
680 yield* Queue.offer(
681 input,
682 yield* encodeJsonl(ExtRequest, {
683 jsonrpc: "2.0",
684 id,
685 method: "x/test",
686 params: { hello: "world" },
687 headers: [],
688 }),
689 );
690 }
691
692 assert.deepEqual(yield* Queue.takeAll(contexts), ["$t3:jsonrpc:number:1", "1"]);
693 }),
694 );
695
696 it.effect("preserves zero-valued ids for inbound core client requests", () =>
697 Effect.gen(function* () {
698 const { stdio, input, output } = yield* makeInMemoryStdio();
699 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
700 stdio,
701 serverRequestMethods: new Set(["session/request_permission"]),
702 });
703 const inboundRequest = yield* Deferred.make<unknown>();
704
705 yield* transport.serverProtocol
706 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
707 .pipe(Effect.forkScoped);
708
709 yield* Queue.offer(
710 input,
711 yield* encodeJsonl(RequestPermissionRequest, {
712 jsonrpc: "2.0",
713 id: 0,
714 method: "session/request_permission",
715 params: {
716 sessionId: "session-1",
717 title: "Allow mock action",
718 subject: {
719 type: "tool_call",
720 toolCall: {
721 toolCallId: "tool-1",
722 title: "Allow mock action",
723 },
724 },
725 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
726 },
727 headers: [],
728 }),
729 );
730
731 const message = yield* Deferred.await(inboundRequest);
732 assert.deepEqual(message, {
733 _tag: "Request",
734 id: 0,
735 tag: "session/request_permission",
736 payload: {
737 sessionId: "session-1",
738 title: "Allow mock action",
739 subject: {
740 type: "tool_call",
741 toolCall: {
742 toolCallId: "tool-1",
743 title: "Allow mock action",
744 },
745 },
746 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
747 },
748 headers: [],
749 });
750
751 yield* transport.serverProtocol.send(0, {
752 _tag: "Exit",
753 requestId: 0,
754 exit: {
755 _tag: "Success",
756 value: {
757 outcome: {
758 outcome: "selected",
759 optionId: "allow",
760 },
761 },
762 },
763 });
764
765 const outbound = yield* Queue.take(output);
766 assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
767 jsonrpc: "2.0",
768 id: 0,
769 result: {
770 outcome: {
771 outcome: "selected",
772 optionId: "allow",
773 },
774 },
775 });
776 }),
777 );
778
779 it.effect("acknowledges outgoing responses and reports encoding failures by request id", () =>
780 Effect.gen(function* () {
781 const { stdio } = yield* makeInMemoryStdio();
782 const acknowledged = yield* Deferred.make<string>();
783 const failed = yield* Deferred.make<readonly [string, AcpError.AcpError]>();
784 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
785 stdio,
786 serverRequestMethods: new Set(),
787 onOutgoingResponse: (requestId) =>
788 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
789 onOutgoingResponseFailure: (requestId, error) =>
790 Deferred.succeed(failed, [requestId, error]).pipe(Effect.asVoid),
791 });
792
793 yield* transport.serverProtocol.send(0, {
794 _tag: "Exit",
795 requestId: "success-1",
796 exit: { _tag: "Success", value: { ok: true } },
797 });
798 assert.equal(yield* Deferred.await(acknowledged), "success-1");
799
800 const circular: { self?: unknown } = {};
801 circular.self = circular;
802 yield* transport.serverProtocol
803 .send(0, {
804 _tag: "Exit",
805 requestId: "failure-1",
806 exit: { _tag: "Success", value: circular },
807 })
808 .pipe(Effect.exit);
809 const [requestId, error] = yield* Deferred.await(failed);
810 assert.equal(requestId, "failure-1");
811 assert.instanceOf(error, AcpError.AcpProtocolParseError);
812 }),
813 );
814
815 it.effect("acknowledges a response only after the stdout write completes", () =>
816 Effect.gen(function* () {
817 const writeStarted = yield* Deferred.make<void>();
818 const releaseWrite = yield* Deferred.make<void>();
819 const acknowledged = yield* Deferred.make<string>();
820 const stdio = Stdio.make({
821 args: Effect.succeed([]),
822 stdin: Stream.never,
823 stdout: () =>
824 Sink.forEach(() =>
825 Deferred.succeed(writeStarted, undefined).pipe(
826 Effect.andThen(Deferred.await(releaseWrite)),
827 ),
828 ),
829 stderr: () => Sink.drain,
830 });
831 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
832 stdio,
833 serverRequestMethods: new Set(),
834 onOutgoingResponse: (requestId) =>
835 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
836 });
837 const sendFiber = yield* transport.serverProtocol
838 .send(0, {
839 _tag: "Exit",
840 requestId: "held-write",
841 exit: { _tag: "Success", value: { ok: true } },
842 })
843 .pipe(Effect.forkScoped);
844
845 yield* Deferred.await(writeStarted);
846 assert.isUndefined(sendFiber.pollUnsafe());
847 assert.isFalse(yield* Deferred.isDone(acknowledged));
848 yield* Deferred.succeed(releaseWrite, undefined);
849 yield* Fiber.join(sendFiber);
850 assert.equal(yield* Deferred.await(acknowledged), "held-write");
851 }),
852 );
853
854 it.effect("fails current, queued, and future responses when the stdout writer fails", () =>
855 Effect.gen(function* () {
856 const writeStarted = yield* Deferred.make<void>();
857 const releaseFailure = yield* Deferred.make<void>();
858 const failures = yield* Queue.unbounded<string>();
859 const terminated = yield* Deferred.make<AcpError.AcpError>();
860 const stdio = Stdio.make({
861 args: Effect.succeed([]),
862 stdin: Stream.never,
863 stdout: () =>
864 Sink.forEach(() =>
865 Deferred.succeed(writeStarted, undefined).pipe(
866 Effect.andThen(Deferred.await(releaseFailure)),
867 Effect.andThen(Effect.die("stdout failed")),
868 ),
869 ),
870 stderr: () => Sink.drain,
871 });
872 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
873 stdio,
874 serverRequestMethods: new Set(),
875 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
876 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
877 });
878 const send = (requestId: string) =>
879 transport.serverProtocol
880 .send(0, {
881 _tag: "Exit",
882 requestId,
883 exit: { _tag: "Success", value: { ok: true } },
884 })
885 .pipe(Effect.exit);
886 const current = yield* send("current").pipe(Effect.forkScoped);
887 yield* Deferred.await(writeStarted);
888 const queued = yield* send("queued").pipe(Effect.forkScoped);
889 yield* Effect.yieldNow;
890 assert.isUndefined(current.pollUnsafe());
891 assert.isUndefined(queued.pollUnsafe());
892 yield* Deferred.succeed(releaseFailure, undefined);
893 assert.instanceOf(yield* Deferred.await(terminated), AcpError.AcpTransportError);
894 yield* Fiber.join(current);
895 yield* Fiber.join(queued);
896 yield* send("future");
897
898 assert.deepEqual(
899 new Set(yield* Queue.takeN(failures, 3)),
900 new Set(["current", "queued", "future"]),
901 );
902 }),
903 );
904
905 it.effect(
906 "atomically rejects an admitted response when the writer closes before queue offer",
907 () =>
908 Effect.gen(function* () {
909 const admitted = yield* Deferred.make<void>();
910 const releaseAdmission = yield* Deferred.make<void>();
911 const failures = yield* Queue.unbounded<string>();
912 const protocolScope = yield* Scope.make();
913 const stdio = Stdio.make({
914 args: Effect.succeed([]),
915 stdin: Stream.never,
916 stdout: () => Sink.drain,
917 stderr: () => Sink.drain,
918 });
919 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
920 stdio,
921 serverRequestMethods: new Set(),
922 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
923 testHooks: {
924 onOutgoingWriteAdmitted: () =>
925 Deferred.succeed(admitted, undefined).pipe(
926 Effect.andThen(Deferred.await(releaseAdmission)),
927 ),
928 },
929 }).pipe(Effect.provideService(Scope.Scope, protocolScope));
930 const send = (requestId: string) =>
931 transport.serverProtocol
932 .send(0, {
933 _tag: "Exit",
934 requestId,
935 exit: { _tag: "Success", value: { ok: true } },
936 })
937 .pipe(Effect.exit);
938 const admittedSend = yield* send("admitted").pipe(Effect.forkScoped);
939
940 yield* Deferred.await(admitted);
941 yield* Scope.close(protocolScope, Exit.void);
942 yield* Deferred.succeed(releaseAdmission, undefined);
943 yield* Fiber.join(admittedSend);
944 yield* send("future");
945
946 assert.deepEqual(yield* Queue.takeN(failures, 2), ["admitted", "future"]);
947 }),
948 );
949
950 it.effect("drops agent-internal JSON-RPC responses with non-numeric request ids", () =>
951 Effect.gen(function* () {
952 const { stdio, input } = yield* makeInMemoryStdio();
953 const notifications =
954 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
955 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
956 stdio,
957 serverRequestMethods: new Set(),
958 });
959
960 yield* transport.incoming.pipe(
961 Stream.take(1),
962 Stream.runCollect,
963 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
964 Effect.forkScoped,
965 );
966
967 yield* Queue.offer(
968 input,
969 encoder.encode(
970 `${encodeUnknownJsonString({
971 jsonrpc: "2.0",
972 id: "skills-reload",
973 result: {
974 reloaded: true,
975 },
976 })}\n`,
977 ),
978 );
979 yield* Queue.offer(
980 input,
981 yield* encodeJsonl(SessionUpdateNotification, {
982 jsonrpc: "2.0",
983 method: "session/update",
984 params: {
985 sessionId: "session-1",
986 update: {
987 sessionUpdate: "plan",
988 entries: [
989 {
990 content: "Reload skills",
991 priority: "high",
992 status: "in_progress",
993 },
994 ],
995 },
996 },
997 }),
998 );
999
1000 const [update] = yield* Deferred.await(notifications);
1001 assert.equal(update?._tag, "SessionUpdate");
1002 }),
1003 );
1004
1005 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
1006 Effect.gen(function* () {
1007 const { stdio, input, output } = yield* makeInMemoryStdio();
1008 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1009 stdio,
1010 serverRequestMethods: new Set(),
1011 });
1012 const lateResponse = yield* Deferred.make<unknown>();
1013
1014 yield* transport.clientProtocol
1015 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
1016 .pipe(Effect.forkScoped);
1017
1018 const response = yield* transport
1019 .request("x/test", { hello: "world" })
1020 .pipe(Effect.forkScoped);
1021 const outbound = yield* Queue.take(output);
1022 assert.deepEqual(yield* decodeExtRequest(outbound), {
1023 jsonrpc: "2.0",
1024 id: 1,
1025 method: "x/test",
1026 params: {
1027 hello: "world",
1028 },
1029 headers: [],
1030 });
1031
1032 yield* Fiber.interrupt(response);
1033 yield* Queue.offer(
1034 input,
1035 yield* encodeJsonl(ExtResponse, {
1036 jsonrpc: "2.0",
1037 id: 1,
1038 result: {
1039 ok: true,
1040 },
1041 }),
1042 );
1043
1044 const message = yield* Deferred.await(lateResponse);
1045 assert.deepEqual(message, {
1046 _tag: "Exit",
1047 requestId: 1,
1048 exit: {
1049 _tag: "Success",
1050 value: {
1051 ok: true,
1052 },
1053 },
1054 });
1055 }),
1056 );
1057
1058 it.effect("propagates the real child exit code when the input stream ends", () =>
1059 Effect.gen(function* () {
1060 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
1061 const firstMessage = yield* Deferred.make<unknown>();
1062 const termination = yield* Deferred.make<AcpError.AcpError>();
1063 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1064 stdio: makeChildStdio(handle),
1065 terminationError: makeTerminationError(handle),
1066 serverRequestMethods: new Set(),
1067 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
1068 });
1069
1070 yield* transport.clientProtocol
1071 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
1072 .pipe(Effect.forkScoped);
1073
1074 const message = yield* Deferred.await(firstMessage);
1075 const exitError = yield* Deferred.await(termination);
1076 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
1077 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
1078 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
1079 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
1080 readonly _tag: string;
1081 readonly message: string;
1082 readonly cause: unknown;
1083 };
1084 assert.equal(defect._tag, "RpcClientDefect");
1085 assert.equal(defect.message, "ACP protocol terminated.");
1086 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
1087 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
1088 }),
1089 );
1090
1091 it.effect("classifies an input stream ending without inventing a cause", () =>
1092 Effect.gen(function* () {
1093 const { stdio, input } = yield* makeInMemoryStdio();
1094 const termination = yield* Deferred.make<AcpError.AcpError>();
1095 yield* AcpProtocol.makeAcpPatchedProtocol({
1096 stdio,
1097 serverRequestMethods: new Set(),
1098 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
1099 });
1100
1101 yield* Queue.end(input);
1102
1103 const error = yield* Deferred.await(termination);
1104 assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
1105 assert.equal(error.message, "ACP input stream ended.");
1106 assert.equal("cause" in error, false);
1107 }),
1108 );
1109
1110 it.effect("does not treat intentional serverProtocol.end as a transport failure", () =>
1111 Effect.gen(function* () {
1112 const { stdio, input } = yield* makeInMemoryStdio();
1113 const terminations = yield* Ref.make(0);
1114 const writerExit = yield* Deferred.make<{ readonly intentionalEnd: boolean }>();
1115 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1116 stdio,
1117 serverRequestMethods: new Set(),
1118 onTermination: () => Ref.update(terminations, (count) => count + 1),
1119 testHooks: {
1120 onOutgoingWriterExit: (detail) =>
1121 Deferred.succeed(writerExit, detail).pipe(Effect.asVoid),
1122 },
1123 });
1124
1125 yield* transport.serverProtocol.end(0);
1126 const exitDetail = yield* Deferred.await(writerExit);
1127 assert.isTrue(exitDetail.intentionalEnd);
1128 assert.equal(yield* Ref.get(terminations), 0);
1129
1130 yield* Queue.end(input);
1131 }),
1132 );
1133
1134 it.effect("does not emit a second process-exit error after a decode failure", () =>
1135 Effect.gen(function* () {
1136 const handle = yield* makeHandle({
1137 ACP_MOCK_MALFORMED_OUTPUT: "1",
1138 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
1139 });
1140 const terminationCalls = yield* Ref.make(0);
1141 const firstMessage = yield* Deferred.make<unknown>();
1142 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1143 stdio: makeChildStdio(handle),
1144 terminationError: makeTerminationError(handle),
1145 serverRequestMethods: new Set(),
1146 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
1147 });
1148
1149 yield* transport.clientProtocol
1150 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
1151 .pipe(Effect.forkScoped);
1152
1153 const message = yield* Deferred.await(firstMessage);
1154 assert.equal(yield* Ref.get(terminationCalls), 1);
1155 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
1156 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
1157 readonly _tag: string;
1158 readonly message: string;
1159 readonly cause: unknown;
1160 };
1161 assert.equal(defect._tag, "RpcClientDefect");
1162 assert.equal(defect.message, "ACP protocol terminated.");
1163 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
1164 }),
1165 );
1166
1167 it.effect("keeps client send failure messages independent from the cause", () =>
1168 Effect.gen(function* () {
1169 const { stdio } = yield* makeInMemoryStdio();
1170 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1171 stdio,
1172 serverRequestMethods: new Set(),
1173 });
1174
1175 const failure = yield* transport.clientProtocol
1176 .send(0, {
1177 _tag: "Request",
1178 id: "request-1",
1179 tag: "x/test",
1180 payload: 1n,
1181 headers: [],
1182 })
1183 .pipe(Effect.flip);
1184 const defect = failure.reason as {
1185 readonly _tag: string;
1186 readonly message: string;
1187 readonly cause: unknown;
1188 };
1189
1190 assert.equal(defect._tag, "RpcClientDefect");
1191 assert.equal(defect.message, "Failed to send ACP protocol message.");
1192 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
1193 }),
1194 );
1195
1196 it.effect("fails pending extension requests with the propagated exit code", () =>
1197 Effect.gen(function* () {
1198 const { stdio, input, output } = yield* makeInMemoryStdio();
1199 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1200 stdio,
1201 terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })),
1202 serverRequestMethods: new Set(),
1203 });
1204
1205 const response = yield* transport
1206 .request("x/test", { hello: "world" })
1207 .pipe(Effect.forkScoped);
1208 yield* Queue.take(output);
1209 yield* Queue.end(input);
1210
1211 const error = yield* Fiber.join(response).pipe(
1212 Effect.match({
1213 onFailure: (error) => error,
1214 onSuccess: () => assert.fail("Expected request to fail after process exit"),
1215 }),
1216 );
1217 assert.instanceOf(error, AcpError.AcpProcessExitedError);
1218 assert.equal(error.code, 0);
1219 }),
1220 );
1221
1222 it.effect.each(["request", "notification"] as const)(
1223 "rejects a %s if the connection ends while its logger is running",
1224 (operation) =>
1225 Effect.gen(function* () {
1226 const { stdio, input, output } = yield* makeInMemoryStdio();
1227 const writeStarted = yield* Deferred.make<void>();
1228 const releaseWrite = yield* Deferred.make<void>();
1229 const terminated = yield* Deferred.make<AcpError.AcpError>();
1230 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1231 stdio,
1232 serverRequestMethods: new Set(),
1233 logOutgoing: true,
1234 logger: (event) =>
1235 event.stage === "raw"
1236 ? Deferred.succeed(writeStarted, undefined).pipe(
1237 Effect.andThen(Deferred.await(releaseWrite)),
1238 )
1239 : Effect.void,
1240 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
1241 });
1242 const send = yield* (
1243 operation === "request"
1244 ? transport.request("x/test", { hello: "world" })
1245 : transport.notify("session/cancel", { sessionId: "session-1" })
1246 ).pipe(Effect.forkScoped);
1247
1248 yield* Deferred.await(writeStarted);
1249 yield* Queue.end(input);
1250 const error = yield* Deferred.await(terminated);
1251 yield* Deferred.succeed(releaseWrite, undefined);
1252
1253 const failure = yield* Fiber.join(send).pipe(
1254 Effect.match({
1255 onFailure: (failure) => failure,
1256 onSuccess: () => assert.fail("Expected the send to fail after termination"),
1257 }),
1258 );
1259 assert.strictEqual(failure, error);
1260 assert.equal(yield* Queue.size(output), 0);
1261 }),
1262 );
1263});