Open History to see the last commit
1import type * as AcpCompat from "./compat.ts";
2import * as Cause from "effect/Cause";
3import * as Effect from "effect/Effect";
4import * as Deferred from "effect/Deferred";
5import * as Exit from "effect/Exit";
6import * as Queue from "effect/Queue";
7import * as Ref from "effect/Ref";
8import type * as PlatformError from "effect/PlatformError";
9import * as Schema from "effect/Schema";
10import * as Scope from "effect/Scope";
11import * as Stream from "effect/Stream";
12import * as Stdio from "effect/Stdio";
13import * as RpcClient from "effect/rpc/RpcClient";
14import * as RpcClientError from "effect/rpc/RpcClientError";
15import * as RpcMessage from "effect/rpc/RpcMessage";
16import * as RpcSerialization from "effect/rpc/RpcSerialization";
17import * as RpcServer from "effect/rpc/RpcServer";
18
19import * as AcpSchema from "./schema.ts";
20import * as AcpSchemaV1 from "./_generated/schema-v1.gen.ts";
21import { CLIENT_METHODS } from "./_generated/meta.gen.ts";
22import * as AcpError from "./errors.ts";
23const isAcpError = Schema.is(AcpError.AcpError);
24
25export interface AcpProtocolLogEvent {
26 readonly direction: "incoming" | "outgoing";
27 readonly stage: "raw" | "decoded" | "decode_failed";
28 readonly payload: unknown;
29}
30
31/** Stable transport identity for an inbound ACP JSON-RPC request. */
32export interface AcpRequestContext {
33 readonly requestId: string;
34 readonly method: string;
35}
36
37/** Lossless string identity for JSON-RPC request IDs used by callback maps. */
38export function acpRequestIdentity(requestId: AcpError.AcpRequestId): string {
39 const prefix = "$t3:jsonrpc:";
40 if (typeof requestId === "number") return `${prefix}number:${requestId}`;
41 return requestId.startsWith(prefix) ? `${prefix}string:${requestId}` : requestId;
42}
43
44export type AcpRequestHandler<Request, Response> = (
45 request: Request,
46 context: AcpRequestContext,
47) => Effect.Effect<Response, AcpError.AcpError>;
48
49export type AcpIncomingNotification =
50 | {
51 readonly _tag: "SessionUpdate";
52 readonly method: typeof CLIENT_METHODS.session_update;
53 readonly params:
54 | AcpSchema.UpdateSessionNotification
55 | AcpSchemaV1.SessionNotification
56 | AcpCompat.SessionNotification;
57 }
58 | {
59 readonly _tag: "ElicitationComplete";
60 readonly method: typeof CLIENT_METHODS.elicitation_complete | "session/elicitation/complete";
61 readonly params: AcpSchema.CompleteElicitationNotification;
62 }
63 | {
64 readonly _tag: "ExtNotification";
65 readonly method: string;
66 readonly params: unknown;
67 };
68
69/** Standard I/O whose input can report provider-specific ACP failures. */
70export interface AcpStdio extends Omit<Stdio.Stdio, "stdin"> {
71 readonly stdin: Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpError.AcpError>;
72}
73
74export interface AcpPatchedProtocolOptions {
75 readonly stdio: AcpStdio;
76 readonly terminationError?: Effect.Effect<AcpError.AcpError>;
77 readonly serverRequestMethods: ReadonlySet<string>;
78 readonly logIncoming?: boolean;
79 readonly logOutgoing?: boolean;
80 readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;
81 readonly onIncomingRequest?: (
82 requestId: string,
83 method: string,
84 payload: unknown,
85 ) => Effect.Effect<void, never>;
86
87 readonly transformSessionUpdate?: (
88 notification: AcpSchema.UpdateSessionNotification | AcpSchemaV1.SessionNotification,
89 ) =>
90 | AcpSchema.UpdateSessionNotification
91 | AcpSchemaV1.SessionNotification
92 | AcpCompat.SessionNotification;
93 readonly onNotification?: (
94 notification: AcpIncomingNotification,
95 ) => Effect.Effect<void, AcpError.AcpError, never>;
96 readonly onExtRequest?: (
97 method: string,
98 params: unknown,
99 context: AcpRequestContext,
100 ) => Effect.Effect<unknown, AcpError.AcpError, never>;
101 readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
102 readonly onOutgoingResponseFailure?: (
103 requestId: string,
104 error: AcpError.AcpError,
105 ) => Effect.Effect<void, never>;
106 readonly onOutgoingResponse?: (requestId: string) => Effect.Effect<void, never>;
107 readonly testHooks?: {
108 readonly onOutgoingWriteAdmitted?: () => Effect.Effect<void>;
109 /** Invoked from the stdout writer exit path (after intentional/unexpected handling). */
110 readonly onOutgoingWriterExit?: (input: {
111 readonly intentionalEnd: boolean;
112 }) => Effect.Effect<void>;
113 };
114}
115
116export interface AcpPatchedProtocol {
117 readonly clientProtocol: RpcClient.Protocol["Service"];
118 readonly serverProtocol: RpcServer.Protocol["Service"];
119 readonly incoming: Stream.Stream<AcpIncomingNotification>;
120 readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
121 readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
122}
123
124interface AcpPendingRequest {
125 readonly deferred: Deferred.Deferred<unknown, AcpError.AcpError>;
126 readonly method: string;
127}
128
129interface AcpOutgoingWrite {
130 readonly acknowledgement?: Deferred.Deferred<void, AcpError.AcpError>;
131 readonly payload: string | Uint8Array;
132}
133
134interface AcpOutgoingWriterState {
135 readonly outstandingAcknowledgements: ReadonlySet<Deferred.Deferred<void, AcpError.AcpError>>;
136 readonly intentionalEnd: boolean;
137 readonly terminalError?: AcpError.AcpError;
138}
139
140const decodeSessionUpdate = Schema.decodeUnknownEffect(
141 Schema.Union([AcpSchema.UpdateSessionNotification, AcpSchemaV1.SessionNotification]),
142);
143const decodeElicitationComplete = Schema.decodeUnknownEffect(
144 AcpSchema.CompleteElicitationNotification,
145);
146const parserFactory = RpcSerialization.ndJsonRpc();
147// ndJsonRpc skips lines that are not JSON. A malformed agent line has to end the
148// session, so frames are split here and each one goes through the strict codec.
149const makeStrictNdJsonRpcParser = () => {
150 const codec = RpcSerialization.jsonRpc().makeUnsafe();
151 const decoder = new TextDecoder();
152 let buffer = "";
153 return {
154 decode: (bytes: Uint8Array | string): ReadonlyArray<unknown> => {
155 buffer += typeof bytes === "string" ? bytes : decoder.decode(bytes, { stream: true });
156 const lines = buffer.split("\n");
157 buffer = lines.pop() ?? "";
158 return lines.flatMap((line) => codec.decode(line));
159 },
160 encode: (response: Parameters<typeof codec.encode>[0]) => {
161 const encoded = codec.encode(response);
162 return encoded === undefined ? undefined : `${encoded}\n`;
163 },
164 };
165};
166const MAX_BUFFERED_RAW_NOTIFICATIONS = 32;
167// Outbound JSON-RPC notification: no `id`, so peers never treat it as a request.
168const encodeJsonRpcNotification = Schema.encodeUnknownExit(
169 Schema.fromJsonString(
170 Schema.Struct({
171 jsonrpc: Schema.Literal("2.0"),
172 method: Schema.String,
173 params: Schema.Unknown,
174 }),
175 ),
176);
177
178const isEffectRpcRequestId = (requestId: AcpError.AcpRequestId): boolean =>
179 typeof requestId === "number" && Number.isSafeInteger(requestId);
180
181/**
182 * Effect RPC's JSON-RPC codec treats a standard JSON-RPC error object as a
183 * defect unless it carries Effect's private `_tag: "Cause"` envelope. ACP
184 * agents correctly send the standard `{ code, message, data? }` shape, so
185 * restore it to the typed failure channel before handing it to RpcClient.
186 */
187function normalizeAcpJsonRpcError(
188 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
189): RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded {
190 if (message._tag !== "Exit" || message.exit._tag !== "Failure") return message;
191 const [failure] = message.exit.cause;
192 if (
193 message.exit.cause.length !== 1 ||
194 failure?._tag !== "Die" ||
195 !isProtocolError(failure.defect)
196 ) {
197 return message;
198 }
199 return {
200 ...message,
201 exit: {
202 _tag: "Failure",
203 cause: [{ _tag: "Fail", error: failure.defect }],
204 },
205 };
206}
207
208export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
209 options: AcpPatchedProtocolOptions,
210): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {
211 const parser = makeStrictNdJsonRpcParser();
212 const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();
213 const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
214 const notificationQueue = yield* Queue.sliding<AcpIncomingNotification>(
215 MAX_BUFFERED_RAW_NOTIFICATIONS,
216 );
217 const disconnects = yield* Queue.unbounded<number>();
218 const outgoing = yield* Queue.unbounded<AcpOutgoingWrite, AcpError.AcpError | Cause.Done<void>>();
219 const outgoingWriterState = yield* Ref.make<AcpOutgoingWriterState>({
220 intentionalEnd: false,
221 outstandingAcknowledgements: new Set(),
222 });
223 const nextRequestId = yield* Ref.make(1);
224 const terminationHandled = yield* Ref.make(false);
225 const terminationFailure = yield* Deferred.make<never, AcpError.AcpError>();
226 const extPending = yield* Ref.make(new Map<string, AcpPendingRequest>());
227
228 const ensureActive = Ref.get(terminationHandled).pipe(
229 Effect.flatMap((terminated) => (terminated ? Deferred.await(terminationFailure) : Effect.void)),
230 );
231
232 const logProtocol = (event: AcpProtocolLogEvent) => {
233 if (event.direction === "incoming" && !options.logIncoming) {
234 return Effect.void;
235 }
236 if (event.direction === "outgoing" && !options.logOutgoing) {
237 return Effect.void;
238 }
239 return (
240 options.logger?.(event) ??
241 Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event }))
242 );
243 };
244
245 const offerOutgoing = Effect.fn("offerOutgoing")(function* (
246 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
247 ) {
248 // RpcClient emits `@effect/rpc/Interrupt` when a pending request's fiber is interrupted.
249 // ACP has no such method; agents log it as an error and cannot act on it, so drop it.
250 if (message._tag === "Interrupt") {
251 return;
252 }
253 yield* ensureActive;
254 yield* logProtocol({
255 direction: "outgoing",
256 stage: "decoded",
257 payload: message,
258 });
259
260 const method = message._tag === "Request" ? message.tag : undefined;
261 const encodedRequestId =
262 message._tag === "Request"
263 ? message.id
264 : "requestId" in message
265 ? message.requestId
266 : undefined;
267 const requestId = encodedRequestId === "" ? undefined : encodedRequestId;
268 const encoded = yield* Effect.try({
269 try: () => parser.encode(message),
270 catch: (cause) => AcpError.AcpProtocolParseError.fromEncodingError(method, requestId, cause),
271 });
272
273 if (encoded) {
274 yield* logProtocol({
275 direction: "outgoing",
276 stage: "raw",
277 payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
278 });
279
280 yield* ensureActive;
281 const acknowledgement =
282 message._tag === "Exit" ? yield* Deferred.make<void, AcpError.AcpError>() : undefined;
283 const admissionError = yield* Ref.modify(outgoingWriterState, (state) => {
284 if (state.terminalError !== undefined) {
285 return [state.terminalError, state] as const;
286 }
287 if (acknowledgement === undefined) {
288 return [undefined, state] as const;
289 }
290 return [
291 undefined,
292 {
293 ...state,
294 outstandingAcknowledgements: new Set(state.outstandingAcknowledgements).add(
295 acknowledgement,
296 ),
297 },
298 ] as const;
299 });
300 if (admissionError !== undefined) {
301 return yield* admissionError;
302 }
303 if (options.testHooks?.onOutgoingWriteAdmitted !== undefined) {
304 yield* options.testHooks.onOutgoingWriteAdmitted();
305 }
306 yield* Queue.offer(outgoing, {
307 payload: encoded,
308 ...(acknowledgement === undefined ? {} : { acknowledgement }),
309 }).pipe(
310 Effect.mapError(
311 (cause) =>
312 new AcpError.AcpTransportError({
313 detail: "Failed to queue an outgoing ACP message",
314 cause,
315 }),
316 ),
317 Effect.filterOrFail(
318 (accepted) => accepted,
319 () =>
320 new AcpError.AcpTransportError({
321 detail: "The ACP output queue was closed before accepting a message",
322 cause: "Output queue closed",
323 }),
324 ),
325 Effect.tapError((error) =>
326 acknowledgement === undefined
327 ? Effect.void
328 : Ref.update(outgoingWriterState, (state) => {
329 const updated = new Set(state.outstandingAcknowledgements);
330 updated.delete(acknowledgement);
331 return { ...state, outstandingAcknowledgements: updated };
332 }).pipe(Effect.andThen(Deferred.fail(acknowledgement, error)), Effect.asVoid),
333 ),
334 );
335 if (acknowledgement !== undefined) {
336 yield* Deferred.await(acknowledgement);
337 }
338 if (message._tag === "Exit" && options.onOutgoingResponse !== undefined) {
339 yield* options.onOutgoingResponse(acpRequestIdentity(message.requestId));
340 }
341 }
342 });
343
344 const resolveExtPending = (
345 requestId: AcpError.AcpRequestId,
346 onFound: (pendingRequest: AcpPendingRequest) => Effect.Effect<void>,
347 ) =>
348 Ref.modify(extPending, (pending) => {
349 const pendingKey = acpRequestIdentity(requestId);
350 const pendingRequest = pending.get(pendingKey);
351 if (!pendingRequest) {
352 return [Effect.void, pending] as const;
353 }
354 const next = new Map(pending);
355 next.delete(pendingKey);
356 return [onFound(pendingRequest), next] as const;
357 }).pipe(Effect.flatten);
358
359 const removeExtPending = (requestId: AcpError.AcpRequestId) =>
360 Ref.update(extPending, (pending) => {
361 const pendingKey = acpRequestIdentity(requestId);
362 if (!pending.has(pendingKey)) {
363 return pending;
364 }
365 const next = new Map(pending);
366 next.delete(pendingKey);
367 return next;
368 });
369
370 const completeExtPendingFailure = (requestId: AcpError.AcpRequestId, error: AcpError.AcpError) =>
371 resolveExtPending(requestId, ({ deferred }) => Deferred.fail(deferred, error));
372
373 const completeExtPendingSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
374 resolveExtPending(requestId, ({ deferred }) => Deferred.succeed(deferred, value));
375
376 const failAllExtPending = (error: AcpError.AcpError) =>
377 Ref.getAndSet(extPending, new Map()).pipe(
378 Effect.flatMap((pending) =>
379 Effect.forEach([...pending.values()], ({ deferred }) => Deferred.fail(deferred, error), {
380 discard: true,
381 }),
382 ),
383 );
384
385 const dispatchNotification = (notification: AcpIncomingNotification) =>
386 Queue.offer(notificationQueue, notification).pipe(
387 Effect.andThen(
388 options.onNotification
389 ? options.onNotification(notification).pipe(Effect.ignore)
390 : Effect.void,
391 ),
392 Effect.asVoid,
393 );
394
395 const emitClientProtocolError = (error: AcpError.AcpError) =>
396 Queue.offer(clientQueue, {
397 _tag: "ClientProtocolError",
398 error: new RpcClientError.RpcClientError({
399 reason: new RpcClientError.RpcClientDefect({
400 message: "ACP protocol terminated.",
401 cause: error,
402 }),
403 }),
404 }).pipe(Effect.asVoid);
405
406 const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError>) =>
407 Ref.modify(terminationHandled, (handled) => {
408 if (handled) {
409 return [Effect.void, true] as const;
410 }
411 return [
412 Effect.gen(function* () {
413 yield* Queue.offer(disconnects, 0);
414 const error = yield* classify();
415 yield* Deferred.fail(terminationFailure, error);
416 yield* failAllExtPending(error);
417 yield* emitClientProtocolError(error);
418 if (options.onTermination) {
419 yield* options.onTermination(error);
420 }
421 }),
422 true,
423 ] as const;
424 }).pipe(Effect.flatten);
425
426 const respondWithSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
427 offerOutgoing({
428 _tag: "Exit",
429 requestId,
430 exit: {
431 _tag: "Success",
432 value,
433 },
434 });
435
436 const respondWithError = (requestId: AcpError.AcpRequestId, error: AcpError.AcpRequestError) =>
437 offerOutgoing({
438 _tag: "Exit",
439 requestId,
440 exit: {
441 _tag: "Failure",
442 cause: [
443 {
444 _tag: "Fail",
445 error: error.toProtocolError(),
446 },
447 ],
448 },
449 });
450
451 const handleExtRequest = (message: RpcMessage.RequestEncoded) => {
452 if (!options.onExtRequest) {
453 return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag));
454 }
455 return options
456 .onExtRequest(message.tag, message.payload, {
457 requestId: acpRequestIdentity(message.id),
458 method: message.tag,
459 })
460 .pipe(
461 Effect.matchEffect({
462 onFailure: (error) =>
463 respondWithError(
464 message.id,
465 AcpError.AcpRequestError.fromExtensionHandlerError(error, message.tag),
466 ),
467 onSuccess: (value) => respondWithSuccess(message.id, value),
468 }),
469 );
470 };
471
472 const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => {
473 if (message.id === "") {
474 if (message.tag === CLIENT_METHODS.session_update) {
475 return decodeSessionUpdate(message.payload).pipe(
476 Effect.map(
477 (params) =>
478 ({
479 _tag: "SessionUpdate",
480 method: CLIENT_METHODS.session_update,
481 params: options.transformSessionUpdate?.(params) ?? params,
482 }) satisfies AcpIncomingNotification,
483 ),
484 Effect.mapError((cause) =>
485 AcpError.AcpProtocolParseError.fromSchemaError(
486 "decode-notification-payload",
487 CLIENT_METHODS.session_update,
488 cause,
489 ),
490 ),
491 Effect.flatMap(dispatchNotification),
492 );
493 }
494 if (
495 message.tag === CLIENT_METHODS.elicitation_complete ||
496 message.tag === "session/elicitation/complete"
497 ) {
498 const method = message.tag;
499 return decodeElicitationComplete(message.payload).pipe(
500 Effect.map(
501 (params) =>
502 ({
503 _tag: "ElicitationComplete",
504 method,
505 params,
506 }) satisfies AcpIncomingNotification,
507 ),
508 Effect.mapError((cause) =>
509 AcpError.AcpProtocolParseError.fromSchemaError(
510 "decode-notification-payload",
511 method,
512 cause,
513 ),
514 ),
515 Effect.flatMap(dispatchNotification),
516 );
517 }
518 return dispatchNotification({
519 _tag: "ExtNotification",
520 method: message.tag,
521 params: message.payload,
522 });
523 }
524
525 const observeIncoming =
526 options.onIncomingRequest?.(acpRequestIdentity(message.id), message.tag, message.payload) ??
527 Effect.void;
528
529 if (!options.serverRequestMethods.has(message.tag)) {
530 return observeIncoming.pipe(
531 Effect.andThen(handleExtRequest(message)),
532 Effect.catchTags({
533 AcpProtocolParseError: (error) =>
534 Effect.logWarning(error).pipe(
535 Effect.annotateLogs({
536 method: message.tag,
537 requestId: message.id,
538 operation: error.operation,
539 }),
540 Effect.andThen(
541 respondWithError(
542 message.id,
543 AcpError.AcpRequestError.fromExtensionResponseEncodingError(
544 message.tag,
545 message.id,
546 error,
547 ),
548 ),
549 ),
550 ),
551 }),
552 Effect.asVoid,
553 );
554 }
555
556 return observeIncoming.pipe(Effect.andThen(Queue.offer(serverQueue, message)), Effect.asVoid);
557 };
558
559 const forwardToRpcClient = (
560 message: RpcMessage.ResponseChunkEncoded | RpcMessage.ResponseExitEncoded,
561 ) =>
562 isEffectRpcRequestId(message.requestId)
563 ? Queue.offer(clientQueue, message).pipe(Effect.asVoid)
564 : Effect.void;
565
566 const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
567 Ref.get(extPending).pipe(
568 Effect.flatMap((pending) => {
569 const pendingRequest = pending.get(acpRequestIdentity(message.requestId));
570 if (!pendingRequest) {
571 return forwardToRpcClient(message);
572 }
573 if (message.exit._tag === "Success") {
574 return completeExtPendingSuccess(message.requestId, message.exit.value);
575 }
576 const failure = message.exit.cause.find((entry) => entry._tag === "Fail");
577 if (failure && isProtocolError(failure.error)) {
578 return completeExtPendingFailure(
579 message.requestId,
580 AcpError.AcpRequestError.fromProtocolError(failure.error, {
581 method: pendingRequest.method,
582 requestId: message.requestId,
583 cause: message.exit.cause,
584 }),
585 );
586 }
587 return completeExtPendingFailure(
588 message.requestId,
589 AcpError.AcpRequestError.fromExtensionResponseFailure(
590 pendingRequest.method,
591 message.requestId,
592 message.exit.cause,
593 ),
594 );
595 }),
596 );
597
598 const routeDecodedMessage = (
599 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
600 ): Effect.Effect<void, AcpError.AcpError> => {
601 switch (message._tag) {
602 case "Request":
603 return handleRequestEncoded(message);
604 case "Exit":
605 return handleExitEncoded(message);
606 case "Chunk":
607 return Ref.get(extPending).pipe(
608 Effect.flatMap((pending) => {
609 const pendingRequest = pending.get(acpRequestIdentity(message.requestId));
610 return pendingRequest
611 ? completeExtPendingFailure(
612 message.requestId,
613 AcpError.AcpRequestError.unsupportedStreamingResponse(
614 pendingRequest.method,
615 message.requestId,
616 ),
617 )
618 : forwardToRpcClient(message);
619 }),
620 );
621 case "Defect":
622 case "ClientProtocolError":
623 case "Pong":
624 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
625 case "Ack":
626 case "Interrupt":
627 case "Ping":
628 case "Eof":
629 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
630 }
631 };
632
633 yield* options.stdio.stdin.pipe(
634 Stream.runForEach((data) =>
635 (options.logIncoming
636 ? logProtocol({
637 direction: "incoming",
638 stage: "raw",
639 payload: typeof data === "string" ? data : new TextDecoder().decode(data),
640 })
641 : Effect.void
642 ).pipe(
643 Effect.flatMap(() =>
644 Effect.try({
645 try: () =>
646 (
647 parser.decode(data) as ReadonlyArray<
648 RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded
649 >
650 ).map(normalizeAcpJsonRpcError),
651 catch: (cause) =>
652 new AcpError.AcpProtocolParseError({
653 operation: "decode-wire-message",
654 cause,
655 }),
656 }),
657 ),
658 Effect.tap((messages) =>
659 logProtocol({
660 direction: "incoming",
661 stage: "decoded",
662 payload: messages,
663 }),
664 ),
665 Effect.tapErrorTag("AcpProtocolParseError", (error) =>
666 logProtocol({
667 direction: "incoming",
668 stage: "decode_failed",
669 payload: {
670 operation: error.operation,
671 ...(error.method === undefined ? {} : { method: error.method }),
672 ...(error.requestId === undefined ? {} : { requestId: error.requestId }),
673 ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
674 ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
675 ...(error.maximumPathDepth === undefined
676 ? {}
677 : { maximumPathDepth: error.maximumPathDepth }),
678 },
679 }),
680 ),
681 Effect.flatMap((messages) =>
682 Effect.forEach(messages, routeDecodedMessage, {
683 discard: true,
684 }),
685 ),
686 ),
687 ),
688 Effect.matchEffect({
689 onFailure: (error) => {
690 const normalized: AcpError.AcpError = isAcpError(error)
691 ? error
692 : new AcpError.AcpTransportError({
693 operation: "read-input-stream",
694 cause: error,
695 });
696 return handleTermination(() => Effect.succeed(normalized));
697 },
698 onSuccess: () =>
699 handleTermination(
700 () =>
701 options.terminationError ?? Effect.succeed(new AcpError.AcpInputStreamEndedError({})),
702 ),
703 }),
704 Effect.forkScoped,
705 );
706
707 const failOutgoingWrites = (error: AcpError.AcpError) =>
708 Ref.modify(outgoingWriterState, (state) => {
709 const terminalError = state.terminalError ?? error;
710 return [
711 [terminalError, state.outstandingAcknowledgements] as const,
712 {
713 ...state,
714 terminalError,
715 outstandingAcknowledgements: new Set<Deferred.Deferred<void, AcpError.AcpError>>(),
716 },
717 ] as const;
718 }).pipe(
719 Effect.flatMap((acknowledgements) =>
720 Effect.forEach(
721 acknowledgements[1],
722 (acknowledgement) => Deferred.fail(acknowledgement, acknowledgements[0]),
723 { concurrency: "unbounded", discard: true },
724 ),
725 ),
726 Effect.andThen(Queue.fail(outgoing, error)),
727 Effect.asVoid,
728 );
729 const completeOutgoingWrites = () =>
730 Ref.modify(outgoingWriterState, (state) => {
731 return [
732 state.outstandingAcknowledgements,
733 {
734 ...state,
735 outstandingAcknowledgements: new Set<Deferred.Deferred<void, AcpError.AcpError>>(),
736 },
737 ] as const;
738 }).pipe(
739 Effect.flatMap((acknowledgements) =>
740 Effect.forEach(
741 acknowledgements,
742 (acknowledgement) => Deferred.succeed(acknowledgement, undefined),
743 { concurrency: "unbounded", discard: true },
744 ),
745 ),
746 Effect.asVoid,
747 );
748 const acknowledgeOutgoingWrite = (acknowledgement: Deferred.Deferred<void, AcpError.AcpError>) =>
749 Ref.update(outgoingWriterState, (state) => {
750 const updated = new Set(state.outstandingAcknowledgements);
751 updated.delete(acknowledgement);
752 return { ...state, outstandingAcknowledgements: updated };
753 }).pipe(Effect.andThen(Deferred.succeed(acknowledgement, undefined)), Effect.asVoid);
754 yield* Stream.fromQueue(outgoing).pipe(
755 Stream.flatMap((write) => {
756 const acknowledgement = write.acknowledgement;
757 const completion =
758 acknowledgement === undefined
759 ? Stream.empty
760 : Stream.fromEffect(acknowledgeOutgoingWrite(acknowledgement)).pipe(Stream.drain);
761 return Stream.make(write.payload).pipe(Stream.concat(completion));
762 }),
763 Stream.run(options.stdio.stdout()),
764 Effect.onExit((exit) =>
765 Exit.match(exit, {
766 onFailure: (cause) => {
767 const error = new AcpError.AcpTransportError({
768 detail: Cause.hasInterruptsOnly(cause)
769 ? "The ACP output writer was interrupted while closing"
770 : "Failed to write an outgoing ACP message",
771 cause,
772 });
773 return failOutgoingWrites(error).pipe(
774 Effect.andThen(
775 Cause.hasInterruptsOnly(cause)
776 ? Effect.void
777 : handleTermination(() => Effect.succeed(error)),
778 ),
779 );
780 },
781 onSuccess: () =>
782 Ref.get(outgoingWriterState).pipe(
783 Effect.flatMap((state) => {
784 // Intentional Queue.end (serverProtocol.end) completes the writer
785 // successfully. Do not invent a transport failure or client protocol
786 // error for a clean RPC shutdown.
787 const handled = state.intentionalEnd
788 ? completeOutgoingWrites()
789 : (() => {
790 const error = new AcpError.AcpTransportError({
791 detail: "ACP output writer ended before the protocol closed",
792 cause: "Output writer ended",
793 });
794 return failOutgoingWrites(error).pipe(
795 Effect.andThen(handleTermination(() => Effect.succeed(error))),
796 );
797 })();
798 return handled.pipe(
799 Effect.andThen(
800 options.testHooks?.onOutgoingWriterExit === undefined
801 ? Effect.void
802 : options.testHooks.onOutgoingWriterExit({
803 intentionalEnd: state.intentionalEnd,
804 }),
805 ),
806 );
807 }),
808 ),
809 }),
810 ),
811 Effect.forkScoped,
812 );
813
814 const clientProtocol = RpcClient.Protocol.of({
815 run: (_clientId, f) =>
816 Stream.fromQueue(clientQueue).pipe(
817 Stream.runForEach((message) => f(message)),
818 Effect.forever,
819 ),
820 send: (_clientId, request) =>
821 offerOutgoing(request).pipe(
822 Effect.mapError(
823 (error) =>
824 new RpcClientError.RpcClientError({
825 reason: new RpcClientError.RpcClientDefect({
826 message: "Failed to send ACP protocol message.",
827 cause: error,
828 }),
829 }),
830 ),
831 ),
832 supportsAck: true,
833 supportsTransferables: false,
834 codecFor: parserFactory.codecFor,
835 });
836
837 const serverProtocol = RpcServer.Protocol.of({
838 run: (f) =>
839 Stream.fromQueue(serverQueue).pipe(
840 Stream.runForEach((message) => f(0, message)),
841 Effect.forever,
842 ),
843 disconnects,
844 send: (_clientId, response) =>
845 offerOutgoing(response).pipe(
846 Effect.tapError((error) =>
847 response._tag === "Exit" && options.onOutgoingResponseFailure !== undefined
848 ? options.onOutgoingResponseFailure(acpRequestIdentity(response.requestId), error)
849 : Effect.void,
850 ),
851 Effect.orDie,
852 ),
853 end: (_clientId) =>
854 Ref.update(outgoingWriterState, (state) => ({ ...state, intentionalEnd: true })).pipe(
855 Effect.andThen(Queue.end(outgoing)),
856 ),
857 clientIds: Effect.succeed(new Set([0])),
858 initialMessage: Effect.succeedNone,
859 supportsAck: true,
860 supportsTransferables: false,
861 codecFor: parserFactory.codecFor,
862 supportsSpanPropagation: true,
863 supportsNotifications: true,
864 });
865
866 // JSON-RPC notifications carry no `id`. Encoding a Request without `isNotification`
867 // emits an `id`, which real agents (Grok CLI) parse as a malformed request and silently drop.
868 // That made `session/cancel` a no-op against Grok while the lenient mock agent accepted it.
869 const sendNotification = Effect.fn("sendNotification")(function* (
870 method: string,
871 payload: unknown,
872 ) {
873 yield* ensureActive;
874 yield* logProtocol({
875 direction: "outgoing",
876 stage: "decoded",
877 payload: { _tag: "Notification", tag: method, payload },
878 });
879 const exit = encodeJsonRpcNotification({ jsonrpc: "2.0", method, params: payload });
880 if (Exit.isFailure(exit)) {
881 return yield* AcpError.AcpProtocolParseError.fromEncodingError(
882 method,
883 undefined,
884 Cause.squash(exit.cause),
885 );
886 }
887 const encoded = `${exit.value}\n`;
888 yield* logProtocol({ direction: "outgoing", stage: "raw", payload: encoded });
889 yield* ensureActive;
890 // FIFO queue admission preserves wire ordering against later requests
891 // (a session/prompt sent after session/cancel cannot overtake it).
892 yield* Queue.offer(outgoing, { payload: encoded }).pipe(
893 Effect.mapError(
894 (cause) =>
895 new AcpError.AcpTransportError({
896 detail: "Failed to queue an outgoing ACP notification",
897 cause,
898 }),
899 ),
900 Effect.filterOrFail(
901 (accepted) => accepted,
902 () =>
903 new AcpError.AcpTransportError({
904 detail: "The ACP output queue was closed before accepting a notification",
905 cause: "Output queue closed",
906 }),
907 ),
908 );
909 });
910
911 const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) {
912 yield* ensureActive;
913 const requestId = yield* Ref.modify(
914 nextRequestId,
915 (current) => [current, current + 1] as const,
916 );
917 const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();
918 yield* Ref.update(extPending, (pending) =>
919 new Map(pending).set(acpRequestIdentity(requestId), { deferred, method }),
920 );
921 yield* offerOutgoing({
922 _tag: "Request",
923 id: requestId,
924 tag: method,
925 payload,
926 headers: [],
927 }).pipe(Effect.tapError(() => removeExtPending(requestId)));
928 return yield* Deferred.await(deferred).pipe(
929 Effect.onInterrupt(() => removeExtPending(requestId)),
930 );
931 });
932
933 return {
934 clientProtocol,
935 serverProtocol,
936 get incoming() {
937 return Stream.fromQueue(notificationQueue);
938 },
939 request: sendRequest,
940 notify: sendNotification,
941 } satisfies AcpPatchedProtocol;
942});
943
944const isProtocolError = Schema.is(AcpSchema.Error);