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