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