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