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

protocol.ts

1,003 lines34.9 KB

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