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