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

protocol.test.ts

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