Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

protocol.test.ts

1,233 lines43.2 KB

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