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

protocol.test.ts

1,269 lines43.3 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 } 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 // The repeated bad update is dropped again but warned about once.
292 assert.lengthOf(
293 events.filter(({ stage }) => stage === "decode_failed"),
294 2,
295 );
296 assert.lengthOf(warnings, 1);
297 assert.deepInclude(warnings[0] as object, {
298 issueSummary: "update.used missing",
299 });
300 assert.notInclude(encodeUnknownJsonString({ decodeFailed, warnings }), secret);
301 }),
302 );
303​
304 it.effect("keeps invalid core notification values only in the schema cause", () =>
305 Effect.gen(function* () {
306 const secret = "acp-core-notification-secret-sentinel";
307 const cause = yield* Schema.decodeUnknownEffect(AcpSchema.SessionNotification)({
308 sessionId: { secret },
309 update: { sessionUpdate: "plan", entries: [] },
310 }).pipe(Effect.flip);
311 const parseError = AcpError.AcpProtocolParseError.fromSchemaError(
312 "decode-notification-payload",
313 "session/update",
314 cause,
315 );
316 const { cause: directCause, ...directDiagnostics } = parseError;
317 assert.equal(parseError.operation, "decode-notification-payload");
318 assert.equal(parseError.method, "session/update");
319 assert.isAbove(parseError.issueCount ?? 0, 0);
320 assert.include(parseError.issueKinds ?? [], "Pointer");
321 assert.isAbove(parseError.maximumPathDepth ?? 0, 0);
322 assert.equal(parseError.issueSummary, "sessionId wrong type");
323 assert.isTrue(Schema.isSchemaError(directCause));
324 assert.notInclude(parseError.message, secret);
325 assert.notInclude(encodeUnknownJsonString(directDiagnostics), secret);
326 }),
327 );
328​
329 it.effect("terminates when a callback on the reader dies", () =>
330 Effect.gen(function* () {
331 const { stdio, input } = yield* makeInMemoryStdio();
332 const termination = yield* Deferred.make<AcpError.AcpError>();
333 yield* AcpProtocol.makeAcpPatchedProtocol({
334 stdio,
335 serverRequestMethods: new Set(),
336 transformSessionUpdate: () => {
337 throw new Error("normalizer bug");
338 },
339 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
340 });
341​
342 yield* Queue.offer(
343 input,
344 encoder.encode(
345 `${encodeUnknownJsonString({
346 jsonrpc: "2.0",
347 method: "session/update",
348 params: {
349 sessionId: "session-1",
350 update: { sessionUpdate: "plan", entries: [] },
351 },
352 })}\n`,
353 ),
354 );
355​
356 // Pending requests are failed through termination instead of hanging.
357 const error = yield* TestClock.withLive(
358 Deferred.await(termination).pipe(Effect.timeout("2 seconds")),
359 );
360 assert.instanceOf(error, AcpError.AcpTransportError);
361 assert.equal((error as AcpError.AcpTransportError).operation, "read-input-stream");
362 }),
363 );
364​
365 it.effect("logs outgoing notifications when logOutgoing is enabled", () =>
366 Effect.gen(function* () {
367 const { stdio } = yield* makeInMemoryStdio();
368 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
369 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
370 stdio,
371 serverRequestMethods: new Set(),
372 logOutgoing: true,
373 logger: (event) =>
374 Effect.sync(() => {
375 events.push(event);
376 }),
377 });
378​
379 yield* transport.notify("session/cancel", { sessionId: "session-1" });
380​
381 // A notification must not carry `id` or `headers`. Grok CLI drops frames that do.
382 assert.deepEqual(events, [
383 {
384 direction: "outgoing",
385 stage: "decoded",
386 payload: {
387 _tag: "Notification",
388 tag: "session/cancel",
389 payload: {
390 sessionId: "session-1",
391 },
392 },
393 },
394 {
395 direction: "outgoing",
396 stage: "raw",
397 payload:
398 '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"}}\n',
399 },
400 ]);
401 }),
402 );
403​
404 it.effect("logs decode failures without copying the cause or wire payload", () =>
405 Effect.gen(function* () {
406 const secret = "acp-wire-secret-sentinel";
407 const { stdio, input } = yield* makeInMemoryStdio();
408 const events: Array<AcpProtocol.AcpProtocolLogEvent> = [];
409 const termination = yield* Deferred.make<AcpError.AcpError>();
410 yield* AcpProtocol.makeAcpPatchedProtocol({
411 stdio,
412 serverRequestMethods: new Set(),
413 logIncoming: true,
414 logger: (event) =>
415 Effect.sync(() => {
416 events.push(event);
417 }),
418 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
419 });
420​
421 yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
422 yield* Deferred.await(termination);
423​
424 const event = events.find(({ stage }) => stage === "decode_failed");
425 assert.deepEqual(event, {
426 direction: "incoming",
427 stage: "decode_failed",
428 payload: {
429 operation: "decode-wire-message",
430 },
431 });
432 assert.notInclude(encodeUnknownJsonString(event), secret);
433 }),
434 );
435​
436 it.effect("fails notification encoding through the declared ACP error channel", () =>
437 Effect.gen(function* () {
438 const { stdio } = yield* makeInMemoryStdio();
439 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
440 stdio,
441 serverRequestMethods: new Set(),
442 });
443​
444 // Notifications encode through Schema, so the cause is the schema failure rather
445 // than the raw TypeError JSON.stringify throws. The ACP error shape is what callers see.
446 const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
447 assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
448 assert.equal(bigintError.operation, "encode-message");
449 assert.equal(bigintError.method, "x/test");
450 assert.isDefined(bigintError.cause);
451 assert.equal(
452 bigintError.message,
453 "ACP protocol operation 'encode-message' failed for method 'x/test'.",
454 );
455​
456 const circular: Record<string, unknown> = {};
457 circular.self = circular;
458 const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
459 assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
460 assert.equal(circularError.operation, "encode-message");
461 assert.equal(circularError.method, "x/test");
462 assert.isDefined(circularError.cause);
463​
464 const requestError = yield* transport.request("x/request", 1n).pipe(
465 Effect.match({
466 onFailure: (error) => error,
467 onSuccess: () => assert.fail("Expected request encoding to fail"),
468 }),
469 );
470 assert.instanceOf(requestError, AcpError.AcpProtocolParseError);
471 assert.deepInclude(requestError, {
472 operation: "encode-message",
473 method: "x/request",
474 requestId: 1,
475 });
476 }),
477 );
478​
479 it.effect("supports generic extension requests over the patched transport", () =>
480 Effect.gen(function* () {
481 const { stdio, input, output } = yield* makeInMemoryStdio();
482 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
483 stdio,
484 serverRequestMethods: new Set(),
485 });
486​
487 const response = yield* transport
488 .request("x/test", { hello: "world" })
489 .pipe(Effect.forkScoped);
490 const outbound = yield* Queue.take(output);
491 assert.deepEqual(yield* decodeExtRequest(outbound), {
492 jsonrpc: "2.0",
493 id: 1,
494 method: "x/test",
495 params: {
496 hello: "world",
497 },
498 headers: [],
499 });
500​
501 yield* Queue.offer(
502 input,
503 yield* encodeJsonl(ExtResponse, {
504 jsonrpc: "2.0",
505 id: 1,
506 result: {
507 ok: true,
508 },
509 }),
510 );
511​
512 const resolved = yield* Fiber.join(response);
513 assert.deepEqual(resolved, { ok: true });
514 }),
515 );
516​
517 it.effect("does not correlate a string response id with a numeric extension request id", () =>
518 Effect.gen(function* () {
519 const { stdio, input, output } = yield* makeInMemoryStdio();
520 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
521 stdio,
522 serverRequestMethods: new Set(),
523 });
524​
525 const response = yield* transport
526 .request("x/test", { hello: "world" })
527 .pipe(Effect.forkScoped);
528 yield* Queue.take(output);
529 yield* Queue.offer(
530 input,
531 encoder.encode(
532 `${encodeUnknownJsonString({
533 jsonrpc: "2.0",
534 id: "1",
535 result: { ok: false },
536 })}\n`,
537 ),
538 );
539 yield* Effect.yieldNow;
540 assert.isUndefined(response.pollUnsafe());
541​
542 yield* Queue.offer(
543 input,
544 yield* encodeJsonl(ExtResponse, {
545 jsonrpc: "2.0",
546 id: 1,
547 result: { ok: true },
548 }),
549 );
550 assert.deepEqual(yield* Fiber.join(response), { ok: true });
551 }),
552 );
553​
554 it.effect("correlates extension response errors with the originating request", () =>
555 Effect.gen(function* () {
556 const { stdio, input, output } = yield* makeInMemoryStdio();
557 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
558 stdio,
559 serverRequestMethods: new Set(),
560 });
561​
562 const response = yield* transport
563 .request("x/private", { hello: "world" })
564 .pipe(Effect.forkScoped);
565 yield* Queue.take(output);
566 yield* Queue.offer(
567 input,
568 encoder.encode(
569 `${encodeUnknownJsonString({
570 jsonrpc: "2.0",
571 id: 1,
572 error: {
573 _tag: "Cause",
574 code: -32602,
575 message: "Invalid params",
576 data: [
577 {
578 _tag: "Fail",
579 error: {
580 code: -32602,
581 message: "Invalid params",
582 data: { field: "hello" },
583 },
584 },
585 ],
586 },
587 })}\n`,
588 ),
589 );
590​
591 const error = yield* Fiber.join(response).pipe(
592 Effect.match({
593 onFailure: (error) => error,
594 onSuccess: () => assert.fail("Expected extension request to fail"),
595 }),
596 );
597 assert.instanceOf(error, AcpError.AcpRequestError);
598 assert.deepInclude(error, {
599 code: -32602,
600 errorMessage: "Invalid params",
601 method: "x/private",
602 requestId: 1,
603 operation: "receive-response",
604 });
605 }),
606 );
607​
608 it.effect("answers an extension request whose handler also dies as an internal error", () =>
609 Effect.gen(function* () {
610 const { stdio, input, output } = yield* makeInMemoryStdio();
611 yield* AcpProtocol.makeAcpPatchedProtocol({
612 stdio,
613 serverRequestMethods: new Set(),
614 // The typed failure must not hide the defect from its cleanup.
615 onExtRequest: () =>
616 Effect.fail(AcpError.AcpRequestError.invalidParams("bad params")).pipe(
617 Effect.ensuring(Effect.die(new Error("cleanup bug"))),
618 ),
619 });
620​
621 yield* Queue.offer(
622 input,
623 yield* encodeJsonl(ExtRequest, {
624 jsonrpc: "2.0",
625 id: 9,
626 method: "x/test",
627 params: { hello: "world" },
628 headers: [],
629 }),
630 );
631​
632 const response = yield* Schema.decodeUnknownEffect(
633 Schema.fromJsonString(JsonRpcErrorResponse),
634 )(yield* Queue.take(output));
635 assert.equal(response.id, 9);
636 assert.equal(response.error.code, -32603);
637 }),
638 );
639​
640 it.effect("preserves numeric ids for inbound extension requests", () =>
641 Effect.gen(function* () {
642 const { stdio, input, output } = yield* makeInMemoryStdio();
643 yield* AcpProtocol.makeAcpPatchedProtocol({
644 stdio,
645 serverRequestMethods: new Set(),
646 onExtRequest: () => Effect.succeed({ ok: true }),
647 });
648​
649 yield* Queue.offer(
650 input,
651 yield* encodeJsonl(ExtRequest, {
652 jsonrpc: "2.0",
653 id: 7,
654 method: "x/test",
655 params: {
656 hello: "world",
657 },
658 headers: [],
659 }),
660 );
661​
662 const outbound = yield* Queue.take(output);
663 assert.deepEqual(yield* decodeExtResponse(outbound), {
664 jsonrpc: "2.0",
665 id: 7,
666 result: {
667 ok: true,
668 },
669 });
670 }),
671 );
672​
673 it.effect("keeps numeric and string extension request ids distinct in handler context", () =>
674 Effect.gen(function* () {
675 const { stdio, input } = yield* makeInMemoryStdio();
676 const contexts = yield* Queue.unbounded<string>();
677 yield* AcpProtocol.makeAcpPatchedProtocol({
678 stdio,
679 serverRequestMethods: new Set(),
680 onExtRequest: (_method, _params, context) =>
681 Queue.offer(contexts, context.requestId).pipe(Effect.as({ ok: true })),
682 });
683​
684 for (const id of [1, "1"] as const) {
685 yield* Queue.offer(
686 input,
687 yield* encodeJsonl(ExtRequest, {
688 jsonrpc: "2.0",
689 id,
690 method: "x/test",
691 params: { hello: "world" },
692 headers: [],
693 }),
694 );
695 }
696​
697 assert.deepEqual(yield* Queue.takeAll(contexts), ["$t3:jsonrpc:number:1", "1"]);
698 }),
699 );
700​
701 it.effect("preserves zero-valued ids for inbound core client requests", () =>
702 Effect.gen(function* () {
703 const { stdio, input, output } = yield* makeInMemoryStdio();
704 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
705 stdio,
706 serverRequestMethods: new Set(["session/request_permission"]),
707 });
708 const inboundRequest = yield* Deferred.make<unknown>();
709​
710 yield* transport.serverProtocol
711 .run((_clientId, message) => Deferred.succeed(inboundRequest, message).pipe(Effect.asVoid))
712 .pipe(Effect.forkScoped);
713​
714 yield* Queue.offer(
715 input,
716 yield* encodeJsonl(RequestPermissionRequest, {
717 jsonrpc: "2.0",
718 id: 0,
719 method: "session/request_permission",
720 params: {
721 sessionId: "session-1",
722 title: "Allow mock action",
723 subject: {
724 type: "tool_call",
725 toolCall: {
726 toolCallId: "tool-1",
727 title: "Allow mock action",
728 },
729 },
730 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
731 },
732 headers: [],
733 }),
734 );
735​
736 const message = yield* Deferred.await(inboundRequest);
737 assert.deepEqual(message, {
738 _tag: "Request",
739 id: 0,
740 tag: "session/request_permission",
741 payload: {
742 sessionId: "session-1",
743 title: "Allow mock action",
744 subject: {
745 type: "tool_call",
746 toolCall: {
747 toolCallId: "tool-1",
748 title: "Allow mock action",
749 },
750 },
751 options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
752 },
753 headers: [],
754 });
755​
756 yield* transport.serverProtocol.send(0, {
757 _tag: "Exit",
758 requestId: 0,
759 exit: {
760 _tag: "Success",
761 value: {
762 outcome: {
763 outcome: "selected",
764 optionId: "allow",
765 },
766 },
767 },
768 });
769​
770 const outbound = yield* Queue.take(output);
771 assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
772 jsonrpc: "2.0",
773 id: 0,
774 result: {
775 outcome: {
776 outcome: "selected",
777 optionId: "allow",
778 },
779 },
780 });
781 }),
782 );
783​
784 it.effect("acknowledges outgoing responses and reports encoding failures by request id", () =>
785 Effect.gen(function* () {
786 const { stdio } = yield* makeInMemoryStdio();
787 const acknowledged = yield* Deferred.make<string>();
788 const failed = yield* Deferred.make<readonly [string, AcpError.AcpError]>();
789 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
790 stdio,
791 serverRequestMethods: new Set(),
792 onOutgoingResponse: (requestId) =>
793 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
794 onOutgoingResponseFailure: (requestId, error) =>
795 Deferred.succeed(failed, [requestId, error]).pipe(Effect.asVoid),
796 });
797​
798 yield* transport.serverProtocol.send(0, {
799 _tag: "Exit",
800 requestId: "success-1",
801 exit: { _tag: "Success", value: { ok: true } },
802 });
803 assert.equal(yield* Deferred.await(acknowledged), "success-1");
804​
805 const circular: { self?: unknown } = {};
806 circular.self = circular;
807 yield* transport.serverProtocol
808 .send(0, {
809 _tag: "Exit",
810 requestId: "failure-1",
811 exit: { _tag: "Success", value: circular },
812 })
813 .pipe(Effect.exit);
814 const [requestId, error] = yield* Deferred.await(failed);
815 assert.equal(requestId, "failure-1");
816 assert.instanceOf(error, AcpError.AcpProtocolParseError);
817 }),
818 );
819​
820 it.effect("acknowledges a response only after the stdout write completes", () =>
821 Effect.gen(function* () {
822 const writeStarted = yield* Deferred.make<void>();
823 const releaseWrite = yield* Deferred.make<void>();
824 const acknowledged = yield* Deferred.make<string>();
825 const stdio = Stdio.make({
826 args: Effect.succeed([]),
827 stdin: Stream.never,
828 stdout: () =>
829 Sink.forEach(() =>
830 Deferred.succeed(writeStarted, undefined).pipe(
831 Effect.andThen(Deferred.await(releaseWrite)),
832 ),
833 ),
834 stderr: () => Sink.drain,
835 });
836 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
837 stdio,
838 serverRequestMethods: new Set(),
839 onOutgoingResponse: (requestId) =>
840 Deferred.succeed(acknowledged, requestId).pipe(Effect.asVoid),
841 });
842 const sendFiber = yield* transport.serverProtocol
843 .send(0, {
844 _tag: "Exit",
845 requestId: "held-write",
846 exit: { _tag: "Success", value: { ok: true } },
847 })
848 .pipe(Effect.forkScoped);
849​
850 yield* Deferred.await(writeStarted);
851 assert.isUndefined(sendFiber.pollUnsafe());
852 assert.isFalse(yield* Deferred.isDone(acknowledged));
853 yield* Deferred.succeed(releaseWrite, undefined);
854 yield* Fiber.join(sendFiber);
855 assert.equal(yield* Deferred.await(acknowledged), "held-write");
856 }),
857 );
858​
859 it.effect("fails current, queued, and future responses when the stdout writer fails", () =>
860 Effect.gen(function* () {
861 const writeStarted = yield* Deferred.make<void>();
862 const releaseFailure = yield* Deferred.make<void>();
863 const failures = yield* Queue.unbounded<string>();
864 const terminated = yield* Deferred.make<AcpError.AcpError>();
865 const stdio = Stdio.make({
866 args: Effect.succeed([]),
867 stdin: Stream.never,
868 stdout: () =>
869 Sink.forEach(() =>
870 Deferred.succeed(writeStarted, undefined).pipe(
871 Effect.andThen(Deferred.await(releaseFailure)),
872 Effect.andThen(Effect.die("stdout failed")),
873 ),
874 ),
875 stderr: () => Sink.drain,
876 });
877 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
878 stdio,
879 serverRequestMethods: new Set(),
880 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
881 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
882 });
883 const send = (requestId: string) =>
884 transport.serverProtocol
885 .send(0, {
886 _tag: "Exit",
887 requestId,
888 exit: { _tag: "Success", value: { ok: true } },
889 })
890 .pipe(Effect.exit);
891 const current = yield* send("current").pipe(Effect.forkScoped);
892 yield* Deferred.await(writeStarted);
893 const queued = yield* send("queued").pipe(Effect.forkScoped);
894 yield* Effect.yieldNow;
895 assert.isUndefined(current.pollUnsafe());
896 assert.isUndefined(queued.pollUnsafe());
897 yield* Deferred.succeed(releaseFailure, undefined);
898 assert.instanceOf(yield* Deferred.await(terminated), AcpError.AcpTransportError);
899 yield* Fiber.join(current);
900 yield* Fiber.join(queued);
901 yield* send("future");
902​
903 assert.deepEqual(
904 new Set(yield* Queue.takeN(failures, 3)),
905 new Set(["current", "queued", "future"]),
906 );
907 }),
908 );
909​
910 it.effect(
911 "atomically rejects an admitted response when the writer closes before queue offer",
912 () =>
913 Effect.gen(function* () {
914 const admitted = yield* Deferred.make<void>();
915 const releaseAdmission = yield* Deferred.make<void>();
916 const failures = yield* Queue.unbounded<string>();
917 const protocolScope = yield* Scope.make();
918 const stdio = Stdio.make({
919 args: Effect.succeed([]),
920 stdin: Stream.never,
921 stdout: () => Sink.drain,
922 stderr: () => Sink.drain,
923 });
924 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
925 stdio,
926 serverRequestMethods: new Set(),
927 onOutgoingResponseFailure: (requestId) => Queue.offer(failures, requestId),
928 testHooks: {
929 onOutgoingWriteAdmitted: () =>
930 Deferred.succeed(admitted, undefined).pipe(
931 Effect.andThen(Deferred.await(releaseAdmission)),
932 ),
933 },
934 }).pipe(Effect.provideService(Scope.Scope, protocolScope));
935 const send = (requestId: string) =>
936 transport.serverProtocol
937 .send(0, {
938 _tag: "Exit",
939 requestId,
940 exit: { _tag: "Success", value: { ok: true } },
941 })
942 .pipe(Effect.exit);
943 const admittedSend = yield* send("admitted").pipe(Effect.forkScoped);
944​
945 yield* Deferred.await(admitted);
946 yield* Scope.close(protocolScope, Exit.void);
947 yield* Deferred.succeed(releaseAdmission, undefined);
948 yield* Fiber.join(admittedSend);
949 yield* send("future");
950​
951 assert.deepEqual(yield* Queue.takeN(failures, 2), ["admitted", "future"]);
952 }),
953 );
954​
955 it.effect("drops agent-internal JSON-RPC responses with non-numeric request ids", () =>
956 Effect.gen(function* () {
957 const { stdio, input } = yield* makeInMemoryStdio();
958 const notifications =
959 yield* Deferred.make<ReadonlyArray<AcpProtocol.AcpIncomingNotification>>();
960 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
961 stdio,
962 serverRequestMethods: new Set(),
963 });
964​
965 yield* transport.incoming.pipe(
966 Stream.take(1),
967 Stream.runCollect,
968 Effect.flatMap((notificationChunk) => Deferred.succeed(notifications, notificationChunk)),
969 Effect.forkScoped,
970 );
971​
972 yield* Queue.offer(
973 input,
974 encoder.encode(
975 `${encodeUnknownJsonString({
976 jsonrpc: "2.0",
977 id: "skills-reload",
978 result: {
979 reloaded: true,
980 },
981 })}\n`,
982 ),
983 );
984 yield* Queue.offer(
985 input,
986 yield* encodeJsonl(SessionUpdateNotification, {
987 jsonrpc: "2.0",
988 method: "session/update",
989 params: {
990 sessionId: "session-1",
991 update: {
992 sessionUpdate: "plan",
993 entries: [
994 {
995 content: "Reload skills",
996 priority: "high",
997 status: "in_progress",
998 },
999 ],
1000 },
1001 },
1002 }),
1003 );
1004​
1005 const [update] = yield* Deferred.await(notifications);
1006 assert.equal(update?._tag, "SessionUpdate");
1007 }),
1008 );
1009​
1010 it.effect("cleans up interrupted extension requests before a late response arrives", () =>
1011 Effect.gen(function* () {
1012 const { stdio, input, output } = yield* makeInMemoryStdio();
1013 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1014 stdio,
1015 serverRequestMethods: new Set(),
1016 });
1017 const lateResponse = yield* Deferred.make<unknown>();
1018​
1019 yield* transport.clientProtocol
1020 .run(0, (message) => Deferred.succeed(lateResponse, message).pipe(Effect.asVoid))
1021 .pipe(Effect.forkScoped);
1022​
1023 const response = yield* transport
1024 .request("x/test", { hello: "world" })
1025 .pipe(Effect.forkScoped);
1026 const outbound = yield* Queue.take(output);
1027 assert.deepEqual(yield* decodeExtRequest(outbound), {
1028 jsonrpc: "2.0",
1029 id: 1,
1030 method: "x/test",
1031 params: {
1032 hello: "world",
1033 },
1034 headers: [],
1035 });
1036​
1037 yield* Fiber.interrupt(response);
1038 yield* Queue.offer(
1039 input,
1040 yield* encodeJsonl(ExtResponse, {
1041 jsonrpc: "2.0",
1042 id: 1,
1043 result: {
1044 ok: true,
1045 },
1046 }),
1047 );
1048​
1049 const message = yield* Deferred.await(lateResponse);
1050 assert.deepEqual(message, {
1051 _tag: "Exit",
1052 requestId: 1,
1053 exit: {
1054 _tag: "Success",
1055 value: {
1056 ok: true,
1057 },
1058 },
1059 });
1060 }),
1061 );
1062​
1063 it.effect("propagates the real child exit code when the input stream ends", () =>
1064 Effect.gen(function* () {
1065 const handle = yield* makeHandle({ ACP_MOCK_EXIT_IMMEDIATELY_CODE: "7" });
1066 const firstMessage = yield* Deferred.make<unknown>();
1067 const termination = yield* Deferred.make<AcpError.AcpError>();
1068 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1069 stdio: makeChildStdio(handle),
1070 terminationError: makeTerminationError(handle),
1071 serverRequestMethods: new Set(),
1072 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
1073 });
1074​
1075 yield* transport.clientProtocol
1076 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
1077 .pipe(Effect.forkScoped);
1078​
1079 const message = yield* Deferred.await(firstMessage);
1080 const exitError = yield* Deferred.await(termination);
1081 assert.instanceOf(exitError, AcpError.AcpProcessExitedError);
1082 assert.equal((exitError as AcpError.AcpProcessExitedError).code, 7);
1083 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
1084 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
1085 readonly _tag: string;
1086 readonly message: string;
1087 readonly cause: unknown;
1088 };
1089 assert.equal(defect._tag, "RpcClientDefect");
1090 assert.equal(defect.message, "ACP protocol terminated.");
1091 assert.instanceOf(defect.cause, AcpError.AcpProcessExitedError);
1092 assert.equal((defect.cause as AcpError.AcpProcessExitedError).code, 7);
1093 }),
1094 );
1095​
1096 it.effect("classifies an input stream ending without inventing a cause", () =>
1097 Effect.gen(function* () {
1098 const { stdio, input } = yield* makeInMemoryStdio();
1099 const termination = yield* Deferred.make<AcpError.AcpError>();
1100 yield* AcpProtocol.makeAcpPatchedProtocol({
1101 stdio,
1102 serverRequestMethods: new Set(),
1103 onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
1104 });
1105​
1106 yield* Queue.end(input);
1107​
1108 const error = yield* Deferred.await(termination);
1109 assert.instanceOf(error, AcpError.AcpInputStreamEndedError);
1110 assert.equal(error.message, "ACP input stream ended.");
1111 assert.equal("cause" in error, false);
1112 }),
1113 );
1114​
1115 it.effect("does not treat intentional serverProtocol.end as a transport failure", () =>
1116 Effect.gen(function* () {
1117 const { stdio, input } = yield* makeInMemoryStdio();
1118 const terminations = yield* Ref.make(0);
1119 const writerExit = yield* Deferred.make<{ readonly intentionalEnd: boolean }>();
1120 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1121 stdio,
1122 serverRequestMethods: new Set(),
1123 onTermination: () => Ref.update(terminations, (count) => count + 1),
1124 testHooks: {
1125 onOutgoingWriterExit: (detail) =>
1126 Deferred.succeed(writerExit, detail).pipe(Effect.asVoid),
1127 },
1128 });
1129​
1130 yield* transport.serverProtocol.end(0);
1131 const exitDetail = yield* Deferred.await(writerExit);
1132 assert.isTrue(exitDetail.intentionalEnd);
1133 assert.equal(yield* Ref.get(terminations), 0);
1134​
1135 // Tear down the forever input reader so the scoped test can finish.
1136 yield* Queue.end(input);
1137 }),
1138 );
1139​
1140 it.effect("does not emit a second process-exit error after a decode failure", () =>
1141 Effect.gen(function* () {
1142 const handle = yield* makeHandle({
1143 ACP_MOCK_MALFORMED_OUTPUT: "1",
1144 ACP_MOCK_MALFORMED_OUTPUT_EXIT_CODE: "23",
1145 });
1146 const terminationCalls = yield* Ref.make(0);
1147 const firstMessage = yield* Deferred.make<unknown>();
1148 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1149 stdio: makeChildStdio(handle),
1150 terminationError: makeTerminationError(handle),
1151 serverRequestMethods: new Set(),
1152 onTermination: () => Ref.update(terminationCalls, (count) => count + 1),
1153 });
1154​
1155 yield* transport.clientProtocol
1156 .run(0, (message) => Deferred.succeed(firstMessage, message).pipe(Effect.asVoid))
1157 .pipe(Effect.forkScoped);
1158​
1159 const message = yield* Deferred.await(firstMessage);
1160 assert.equal(yield* Ref.get(terminationCalls), 1);
1161 assert.equal((message as { readonly _tag?: string })._tag, "ClientProtocolError");
1162 const defect = (message as { readonly error: { readonly reason: unknown } }).error.reason as {
1163 readonly _tag: string;
1164 readonly message: string;
1165 readonly cause: unknown;
1166 };
1167 assert.equal(defect._tag, "RpcClientDefect");
1168 assert.equal(defect.message, "ACP protocol terminated.");
1169 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
1170 }),
1171 );
1172​
1173 it.effect("keeps client send failure messages independent from the cause", () =>
1174 Effect.gen(function* () {
1175 const { stdio } = yield* makeInMemoryStdio();
1176 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1177 stdio,
1178 serverRequestMethods: new Set(),
1179 });
1180​
1181 const failure = yield* transport.clientProtocol
1182 .send(0, {
1183 _tag: "Request",
1184 id: "request-1",
1185 tag: "x/test",
1186 payload: 1n,
1187 headers: [],
1188 })
1189 .pipe(Effect.flip);
1190 const defect = failure.reason as {
1191 readonly _tag: string;
1192 readonly message: string;
1193 readonly cause: unknown;
1194 };
1195​
1196 assert.equal(defect._tag, "RpcClientDefect");
1197 assert.equal(defect.message, "Failed to send ACP protocol message.");
1198 assert.instanceOf(defect.cause, AcpError.AcpProtocolParseError);
1199 }),
1200 );
1201​
1202 it.effect("fails pending extension requests with the propagated exit code", () =>
1203 Effect.gen(function* () {
1204 const { stdio, input, output } = yield* makeInMemoryStdio();
1205 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1206 stdio,
1207 terminationError: Effect.succeed(new AcpError.AcpProcessExitedError({ code: 0 })),
1208 serverRequestMethods: new Set(),
1209 });
1210​
1211 const response = yield* transport
1212 .request("x/test", { hello: "world" })
1213 .pipe(Effect.forkScoped);
1214 yield* Queue.take(output);
1215 yield* Queue.end(input);
1216​
1217 const error = yield* Fiber.join(response).pipe(
1218 Effect.match({
1219 onFailure: (error) => error,
1220 onSuccess: () => assert.fail("Expected request to fail after process exit"),
1221 }),
1222 );
1223 assert.instanceOf(error, AcpError.AcpProcessExitedError);
1224 assert.equal(error.code, 0);
1225 }),
1226 );
1227​
1228 it.effect.each(["request", "notification"] as const)(
1229 "rejects a %s if the connection ends while its logger is running",
1230 (operation) =>
1231 Effect.gen(function* () {
1232 const { stdio, input, output } = yield* makeInMemoryStdio();
1233 const writeStarted = yield* Deferred.make<void>();
1234 const releaseWrite = yield* Deferred.make<void>();
1235 const terminated = yield* Deferred.make<AcpError.AcpError>();
1236 const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
1237 stdio,
1238 serverRequestMethods: new Set(),
1239 logOutgoing: true,
1240 logger: (event) =>
1241 event.stage === "raw"
1242 ? Deferred.succeed(writeStarted, undefined).pipe(
1243 Effect.andThen(Deferred.await(releaseWrite)),
1245 : Effect.void,
1246 onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid),
1247 });
1248 const send = yield* (
1249 operation === "request"
1250 ? transport.request("x/test", { hello: "world" })
1251 : transport.notify("session/cancel", { sessionId: "session-1" })
1252 ).pipe(Effect.forkScoped);
1253​
1254 yield* Deferred.await(writeStarted);
1255 yield* Queue.end(input);
1256 const error = yield* Deferred.await(terminated);
1257 yield* Deferred.succeed(releaseWrite, undefined);
1258​
1259 const failure = yield* Fiber.join(send).pipe(
1260 Effect.match({
1261 onFailure: (failure) => failure,
1262 onSuccess: () => assert.fail("Expected the send to fail after termination"),
1263 }),
1264 );
1265 assert.strictEqual(failure, error);
1266 assert.equal(yield* Queue.size(output), 0);
1267 }),
1268 );
1269});