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

protocol.ts

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