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

protocol.ts

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