Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

protocol.ts

1,019 lines35.7 KB

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