Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as Deferred from "effect/Deferred";
4import * as Exit from "effect/Exit";
5import * as Queue from "effect/Queue";
6import * as Ref from "effect/Ref";
7import type * as PlatformError from "effect/PlatformError";
8import * as Schema from "effect/Schema";
9import * as Scope from "effect/Scope";
10import * as Stream from "effect/Stream";
11import * as Stdio from "effect/Stdio";
12import * as RpcClient from "effect/unstable/rpc/RpcClient";
13import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
14import * as RpcMessage from "effect/unstable/rpc/RpcMessage";
15import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
16import * as RpcServer from "effect/unstable/rpc/RpcServer";
17
18import * as AcpSchema from "./_generated/schema.gen.ts";
19import { CLIENT_METHODS } from "./_generated/meta.gen.ts";
20import * as AcpError from "./errors.ts";
21const isAcpError = Schema.is(AcpError.AcpError);
22
23export interface AcpProtocolLogEvent {
24 readonly direction: "incoming" | "outgoing";
25 readonly stage: "raw" | "decoded" | "decode_failed";
26 readonly payload: unknown;
27}
28
29export type AcpIncomingNotification =
30 | {
31 readonly _tag: "SessionUpdate";
32 readonly method: typeof CLIENT_METHODS.session_update;
33 readonly params: AcpSchema.SessionNotification;
34 }
35 | {
36 readonly _tag: "ElicitationComplete";
37 readonly method: typeof CLIENT_METHODS.session_elicitation_complete;
38 readonly params: AcpSchema.ElicitationCompleteNotification;
39 }
40 | {
41 readonly _tag: "ExtNotification";
42 readonly method: string;
43 readonly params: unknown;
44 };
45
46/** Standard I/O whose input can report provider-specific ACP failures. */
47export interface AcpStdio extends Omit<Stdio.Stdio, "stdin"> {
48 readonly stdin: Stream.Stream<Uint8Array, PlatformError.PlatformError | AcpError.AcpError>;
49}
50
51export interface AcpPatchedProtocolOptions {
52 readonly stdio: AcpStdio;
53 readonly terminationError?: Effect.Effect<AcpError.AcpError>;
54 readonly serverRequestMethods: ReadonlySet<string>;
55 readonly logIncoming?: boolean;
56 readonly logOutgoing?: boolean;
57 readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;
58 readonly onIncomingRequest?: (
59 requestId: string,
60 method: string,
61 payload: unknown,
62 ) => Effect.Effect<void, never>;
63 readonly transformSessionUpdate?: (
64 notification: AcpSchema.SessionNotification,
65 ) => AcpSchema.SessionNotification;
66 readonly onNotification?: (
67 notification: AcpIncomingNotification,
68 ) => Effect.Effect<void, AcpError.AcpError, never>;
69 readonly onExtRequest?: (
70 method: string,
71 params: unknown,
72 ) => Effect.Effect<unknown, AcpError.AcpError, never>;
73 readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
74 readonly onOutgoingResponseFailure?: (
75 requestId: string,
76 error: AcpError.AcpError,
77 ) => Effect.Effect<void, never>;
78 readonly onOutgoingResponse?: (requestId: string) => Effect.Effect<void, never>;
79 readonly testHooks?: {
80 readonly onOutgoingWriteAdmitted?: () => Effect.Effect<void>;
81 /** Invoked from the stdout writer exit path (after intentional/unexpected handling). */
82 readonly onOutgoingWriterExit?: (input: {
83 readonly intentionalEnd: boolean;
84 }) => Effect.Effect<void>;
85 };
86}
87
88export interface AcpPatchedProtocol {
89 readonly clientProtocol: RpcClient.Protocol["Service"];
90 readonly serverProtocol: RpcServer.Protocol["Service"];
91 readonly incoming: Stream.Stream<AcpIncomingNotification>;
92 readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
93 readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
94}
95
96interface AcpPendingRequest {
97 readonly deferred: Deferred.Deferred<unknown, AcpError.AcpError>;
98 readonly method: string;
99}
100
101interface AcpOutgoingWrite {
102 readonly acknowledgement?: Deferred.Deferred<void, AcpError.AcpError>;
103 readonly payload: string | Uint8Array;
104}
105
106interface AcpOutgoingWriterState {
107 readonly outstandingAcknowledgements: ReadonlySet<Deferred.Deferred<void, AcpError.AcpError>>;
108 readonly intentionalEnd: boolean;
109 readonly terminalError?: AcpError.AcpError;
110}
111
112const decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);
113const decodeElicitationComplete = Schema.decodeUnknownEffect(
114 AcpSchema.ElicitationCompleteNotification,
115);
116const parserFactory = RpcSerialization.ndJsonRpc();
117const MAX_BUFFERED_RAW_NOTIFICATIONS = 32;
118// Outbound JSON-RPC notification: no `id`, so peers never treat it as a request.
119const encodeJsonRpcNotification = Schema.encodeUnknownExit(
120 Schema.fromJsonString(
121 Schema.Struct({
122 jsonrpc: Schema.Literal("2.0"),
123 method: Schema.String,
124 params: Schema.Unknown,
125 }),
126 ),
127);
128
129const isEffectRpcRequestId = (requestId: AcpError.AcpRequestId): boolean =>
130 typeof requestId === "number" && Number.isSafeInteger(requestId);
131
132export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
133 options: AcpPatchedProtocolOptions,
134): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {
135 const parser = parserFactory.makeUnsafe();
136 const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();
137 const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
138 const notificationQueue = yield* Queue.sliding<AcpIncomingNotification>(
139 MAX_BUFFERED_RAW_NOTIFICATIONS,
140 );
141 const disconnects = yield* Queue.unbounded<number>();
142 const outgoing = yield* Queue.unbounded<AcpOutgoingWrite, AcpError.AcpError | Cause.Done<void>>();
143 const outgoingWriterState = yield* Ref.make<AcpOutgoingWriterState>({
144 intentionalEnd: false,
145 outstandingAcknowledgements: new Set(),
146 });
147 const nextRequestId = yield* Ref.make(1);
148 const terminationHandled = yield* Ref.make(false);
149 const terminationFailure = yield* Deferred.make<never, AcpError.AcpError>();
150 const extPending = yield* Ref.make(new Map<string, AcpPendingRequest>());
151
152 const ensureActive = Ref.get(terminationHandled).pipe(
153 Effect.flatMap((terminated) => (terminated ? Deferred.await(terminationFailure) : Effect.void)),
154 );
155
156 const logProtocol = (event: AcpProtocolLogEvent) => {
157 if (event.direction === "incoming" && !options.logIncoming) {
158 return Effect.void;
159 }
160 if (event.direction === "outgoing" && !options.logOutgoing) {
161 return Effect.void;
162 }
163 return (
164 options.logger?.(event) ??
165 Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event }))
166 );
167 };
168
169 const offerOutgoing = Effect.fn("offerOutgoing")(function* (
170 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
171 ) {
172 // RpcClient emits `@effect/rpc/Interrupt` when a pending request's fiber is interrupted.
173 // ACP has no such method; agents log it as an error and cannot act on it, so drop it.
174 if (message._tag === "Interrupt") {
175 return;
176 }
177 yield* ensureActive;
178 yield* logProtocol({
179 direction: "outgoing",
180 stage: "decoded",
181 payload: message,
182 });
183
184 const method = message._tag === "Request" ? message.tag : undefined;
185 const encodedRequestId =
186 message._tag === "Request"
187 ? message.id
188 : "requestId" in message
189 ? message.requestId
190 : undefined;
191 const requestId = encodedRequestId === "" ? undefined : encodedRequestId;
192 const encoded = yield* Effect.try({
193 try: () => parser.encode(message),
194 catch: (cause) => AcpError.AcpProtocolParseError.fromEncodingError(method, requestId, cause),
195 });
196
197 if (encoded) {
198 yield* logProtocol({
199 direction: "outgoing",
200 stage: "raw",
201 payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
202 });
203
204 yield* ensureActive;
205 const acknowledgement =
206 message._tag === "Exit" ? yield* Deferred.make<void, AcpError.AcpError>() : undefined;
207 const admissionError = yield* Ref.modify(outgoingWriterState, (state) => {
208 if (state.terminalError !== undefined) {
209 return [state.terminalError, state] as const;
210 }
211 if (acknowledgement === undefined) {
212 return [undefined, state] as const;
213 }
214 return [
215 undefined,
216 {
217 ...state,
218 outstandingAcknowledgements: new Set(state.outstandingAcknowledgements).add(
219 acknowledgement,
220 ),
221 },
222 ] as const;
223 });
224 if (admissionError !== undefined) {
225 return yield* admissionError;
226 }
227 if (options.testHooks?.onOutgoingWriteAdmitted !== undefined) {
228 yield* options.testHooks.onOutgoingWriteAdmitted();
229 }
230 yield* Queue.offer(outgoing, {
231 payload: encoded,
232 ...(acknowledgement === undefined ? {} : { acknowledgement }),
233 }).pipe(
234 Effect.mapError(
235 (cause) =>
236 new AcpError.AcpTransportError({
237 detail: "Failed to queue an outgoing ACP message",
238 cause,
239 }),
240 ),
241 Effect.filterOrFail(
242 (accepted) => accepted,
243 () =>
244 new AcpError.AcpTransportError({
245 detail: "The ACP output queue was closed before accepting a message",
246 cause: "Output queue closed",
247 }),
248 ),
249 Effect.tapError((error) =>
250 acknowledgement === undefined
251 ? Effect.void
252 : Ref.update(outgoingWriterState, (state) => {
253 const updated = new Set(state.outstandingAcknowledgements);
254 updated.delete(acknowledgement);
255 return { ...state, outstandingAcknowledgements: updated };
256 }).pipe(Effect.andThen(Deferred.fail(acknowledgement, error)), Effect.asVoid),
257 ),
258 );
259 if (acknowledgement !== undefined) {
260 yield* Deferred.await(acknowledgement);
261 }
262 if (message._tag === "Exit" && options.onOutgoingResponse !== undefined) {
263 yield* options.onOutgoingResponse(String(message.requestId));
264 }
265 }
266 });
267
268 const resolveExtPending = (
269 requestId: AcpError.AcpRequestId,
270 onFound: (pendingRequest: AcpPendingRequest) => Effect.Effect<void>,
271 ) =>
272 Ref.modify(extPending, (pending) => {
273 const pendingKey = String(requestId);
274 const pendingRequest = pending.get(pendingKey);
275 if (!pendingRequest) {
276 return [Effect.void, pending] as const;
277 }
278 const next = new Map(pending);
279 next.delete(pendingKey);
280 return [onFound(pendingRequest), next] as const;
281 }).pipe(Effect.flatten);
282
283 const removeExtPending = (requestId: AcpError.AcpRequestId) =>
284 Ref.update(extPending, (pending) => {
285 const pendingKey = String(requestId);
286 if (!pending.has(pendingKey)) {
287 return pending;
288 }
289 const next = new Map(pending);
290 next.delete(pendingKey);
291 return next;
292 });
293
294 const completeExtPendingFailure = (requestId: AcpError.AcpRequestId, error: AcpError.AcpError) =>
295 resolveExtPending(requestId, ({ deferred }) => Deferred.fail(deferred, error));
296
297 const completeExtPendingSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
298 resolveExtPending(requestId, ({ deferred }) => Deferred.succeed(deferred, value));
299
300 const failAllExtPending = (error: AcpError.AcpError) =>
301 Ref.getAndSet(extPending, new Map()).pipe(
302 Effect.flatMap((pending) =>
303 Effect.forEach([...pending.values()], ({ deferred }) => Deferred.fail(deferred, error), {
304 discard: true,
305 }),
306 ),
307 );
308
309 const dispatchNotification = (notification: AcpIncomingNotification) =>
310 Queue.offer(notificationQueue, notification).pipe(
311 Effect.andThen(
312 options.onNotification
313 ? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))
314 : Effect.void,
315 ),
316 Effect.asVoid,
317 );
318
319 const emitClientProtocolError = (error: AcpError.AcpError) =>
320 Queue.offer(clientQueue, {
321 _tag: "ClientProtocolError",
322 error: new RpcClientError.RpcClientError({
323 reason: new RpcClientError.RpcClientDefect({
324 message: "ACP protocol terminated.",
325 cause: error,
326 }),
327 }),
328 }).pipe(Effect.asVoid);
329
330 const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError>) =>
331 Ref.modify(terminationHandled, (handled) => {
332 if (handled) {
333 return [Effect.void, true] as const;
334 }
335 return [
336 Effect.gen(function* () {
337 yield* Queue.offer(disconnects, 0);
338 const error = yield* classify();
339 yield* Deferred.fail(terminationFailure, error);
340 yield* failAllExtPending(error);
341 yield* emitClientProtocolError(error);
342 if (options.onTermination) {
343 yield* options.onTermination(error);
344 }
345 }),
346 true,
347 ] as const;
348 }).pipe(Effect.flatten);
349
350 const respondWithSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
351 offerOutgoing({
352 _tag: "Exit",
353 requestId,
354 exit: {
355 _tag: "Success",
356 value,
357 },
358 });
359
360 const respondWithError = (requestId: AcpError.AcpRequestId, error: AcpError.AcpRequestError) =>
361 offerOutgoing({
362 _tag: "Exit",
363 requestId,
364 exit: {
365 _tag: "Failure",
366 cause: [
367 {
368 _tag: "Fail",
369 error: error.toProtocolError(),
370 },
371 ],
372 },
373 });
374
375 const handleExtRequest = (message: RpcMessage.RequestEncoded) => {
376 if (!options.onExtRequest) {
377 return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag));
378 }
379 return options.onExtRequest(message.tag, message.payload).pipe(
380 Effect.matchEffect({
381 onFailure: (error) =>
382 respondWithError(
383 message.id,
384 AcpError.AcpRequestError.fromExtensionHandlerError(error, message.tag),
385 ),
386 onSuccess: (value) => respondWithSuccess(message.id, value),
387 }),
388 );
389 };
390
391 const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => {
392 if (message.id === "") {
393 if (message.tag === CLIENT_METHODS.session_update) {
394 return decodeSessionUpdate(message.payload).pipe(
395 Effect.map(
396 (params) =>
397 ({
398 _tag: "SessionUpdate",
399 method: CLIENT_METHODS.session_update,
400 params: options.transformSessionUpdate?.(params) ?? params,
401 }) satisfies AcpIncomingNotification,
402 ),
403 Effect.mapError((cause) =>
404 AcpError.AcpProtocolParseError.fromSchemaError(
405 "decode-notification-payload",
406 CLIENT_METHODS.session_update,
407 cause,
408 ),
409 ),
410 Effect.flatMap(dispatchNotification),
411 );
412 }
413 if (message.tag === CLIENT_METHODS.session_elicitation_complete) {
414 return decodeElicitationComplete(message.payload).pipe(
415 Effect.map(
416 (params) =>
417 ({
418 _tag: "ElicitationComplete",
419 method: CLIENT_METHODS.session_elicitation_complete,
420 params,
421 }) satisfies AcpIncomingNotification,
422 ),
423 Effect.mapError((cause) =>
424 AcpError.AcpProtocolParseError.fromSchemaError(
425 "decode-notification-payload",
426 CLIENT_METHODS.session_elicitation_complete,
427 cause,
428 ),
429 ),
430 Effect.flatMap(dispatchNotification),
431 );
432 }
433 return dispatchNotification({
434 _tag: "ExtNotification",
435 method: message.tag,
436 params: message.payload,
437 });
438 }
439
440 const observeIncoming =
441 options.onIncomingRequest?.(String(message.id), message.tag, message.payload) ?? Effect.void;
442
443 if (!options.serverRequestMethods.has(message.tag)) {
444 return observeIncoming.pipe(Effect.andThen(handleExtRequest(message))).pipe(
445 Effect.catchTags({
446 AcpProtocolParseError: (error) =>
447 Effect.logWarning(error).pipe(
448 Effect.annotateLogs({
449 method: message.tag,
450 requestId: message.id,
451 operation: error.operation,
452 }),
453 Effect.andThen(
454 respondWithError(
455 message.id,
456 AcpError.AcpRequestError.fromExtensionResponseEncodingError(
457 message.tag,
458 message.id,
459 error,
460 ),
461 ),
462 ),
463 ),
464 }),
465 Effect.asVoid,
466 );
467 }
468
469 return observeIncoming.pipe(Effect.andThen(Queue.offer(serverQueue, message)), Effect.asVoid);
470 };
471
472 const forwardToRpcClient = (
473 message: RpcMessage.ResponseChunkEncoded | RpcMessage.ResponseExitEncoded,
474 ) =>
475 isEffectRpcRequestId(message.requestId)
476 ? Queue.offer(clientQueue, message).pipe(Effect.asVoid)
477 : Effect.void;
478
479 const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
480 Ref.get(extPending).pipe(
481 Effect.flatMap((pending) => {
482 const pendingRequest = pending.get(String(message.requestId));
483 if (!pendingRequest) {
484 return forwardToRpcClient(message);
485 }
486 if (message.exit._tag === "Success") {
487 return completeExtPendingSuccess(message.requestId, message.exit.value);
488 }
489 const failure = message.exit.cause.find((entry) => entry._tag === "Fail");
490 if (failure && isProtocolError(failure.error)) {
491 return completeExtPendingFailure(
492 message.requestId,
493 AcpError.AcpRequestError.fromProtocolError(failure.error, {
494 method: pendingRequest.method,
495 requestId: message.requestId,
496 cause: message.exit.cause,
497 }),
498 );
499 }
500 return completeExtPendingFailure(
501 message.requestId,
502 AcpError.AcpRequestError.fromExtensionResponseFailure(
503 pendingRequest.method,
504 message.requestId,
505 message.exit.cause,
506 ),
507 );
508 }),
509 );
510
511 const routeDecodedMessage = (
512 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
513 ): Effect.Effect<void, AcpError.AcpError> => {
514 switch (message._tag) {
515 case "Request":
516 return handleRequestEncoded(message);
517 case "Exit":
518 return handleExitEncoded(message);
519 case "Chunk":
520 return Ref.get(extPending).pipe(
521 Effect.flatMap((pending) => {
522 const pendingRequest = pending.get(String(message.requestId));
523 return pendingRequest
524 ? completeExtPendingFailure(
525 message.requestId,
526 AcpError.AcpRequestError.unsupportedStreamingResponse(
527 pendingRequest.method,
528 message.requestId,
529 ),
530 )
531 : forwardToRpcClient(message);
532 }),
533 );
534 case "Defect":
535 case "ClientProtocolError":
536 case "Pong":
537 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
538 case "Ack":
539 case "Interrupt":
540 case "Ping":
541 case "Eof":
542 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
543 }
544 };
545
546 yield* options.stdio.stdin.pipe(
547 Stream.runForEach((data) =>
548 (options.logIncoming
549 ? logProtocol({
550 direction: "incoming",
551 stage: "raw",
552 payload: typeof data === "string" ? data : new TextDecoder().decode(data),
553 })
554 : Effect.void
555 ).pipe(
556 Effect.flatMap(() =>
557 Effect.try({
558 try: () =>
559 parser.decode(data) as ReadonlyArray<
560 RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded
561 >,
562 catch: (cause) =>
563 new AcpError.AcpProtocolParseError({
564 operation: "decode-wire-message",
565 cause,
566 }),
567 }),
568 ),
569 Effect.tap((messages) =>
570 logProtocol({
571 direction: "incoming",
572 stage: "decoded",
573 payload: messages,
574 }),
575 ),
576 Effect.tapErrorTag("AcpProtocolParseError", (error) =>
577 logProtocol({
578 direction: "incoming",
579 stage: "decode_failed",
580 payload: {
581 operation: error.operation,
582 ...(error.method === undefined ? {} : { method: error.method }),
583 ...(error.requestId === undefined ? {} : { requestId: error.requestId }),
584 ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
585 ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
586 ...(error.maximumPathDepth === undefined
587 ? {}
588 : { maximumPathDepth: error.maximumPathDepth }),
589 },
590 }),
591 ),
592 Effect.flatMap((messages) =>
593 Effect.forEach(messages, routeDecodedMessage, {
594 discard: true,
595 }),
596 ),
597 ),
598 ),
599 Effect.matchEffect({
600 onFailure: (error) => {
601 const normalized: AcpError.AcpError = isAcpError(error)
602 ? error
603 : new AcpError.AcpTransportError({
604 operation: "read-input-stream",
605 cause: error,
606 });
607 return handleTermination(() => Effect.succeed(normalized));
608 },
609 onSuccess: () =>
610 handleTermination(
611 () =>
612 options.terminationError ?? Effect.succeed(new AcpError.AcpInputStreamEndedError({})),
613 ),
614 }),
615 Effect.forkScoped,
616 );
617
618 const failOutgoingWrites = (error: AcpError.AcpError) =>
619 Ref.modify(outgoingWriterState, (state) => {
620 const terminalError = state.terminalError ?? error;
621 return [
622 [terminalError, state.outstandingAcknowledgements] as const,
623 {
624 ...state,
625 terminalError,
626 outstandingAcknowledgements: new Set<Deferred.Deferred<void, AcpError.AcpError>>(),
627 },
628 ] as const;
629 }).pipe(
630 Effect.flatMap((acknowledgements) =>
631 Effect.forEach(
632 acknowledgements[1],
633 (acknowledgement) => Deferred.fail(acknowledgement, acknowledgements[0]),
634 { concurrency: "unbounded", discard: true },
635 ),
636 ),
637 Effect.andThen(Queue.fail(outgoing, error)),
638 Effect.asVoid,
639 );
640 const completeOutgoingWrites = () =>
641 Ref.modify(outgoingWriterState, (state) => {
642 return [
643 state.outstandingAcknowledgements,
644 {
645 ...state,
646 outstandingAcknowledgements: new Set<Deferred.Deferred<void, AcpError.AcpError>>(),
647 },
648 ] as const;
649 }).pipe(
650 Effect.flatMap((acknowledgements) =>
651 Effect.forEach(
652 acknowledgements,
653 (acknowledgement) => Deferred.succeed(acknowledgement, undefined),
654 { concurrency: "unbounded", discard: true },
655 ),
656 ),
657 Effect.asVoid,
658 );
659 const acknowledgeOutgoingWrite = (acknowledgement: Deferred.Deferred<void, AcpError.AcpError>) =>
660 Ref.update(outgoingWriterState, (state) => {
661 const updated = new Set(state.outstandingAcknowledgements);
662 updated.delete(acknowledgement);
663 return { ...state, outstandingAcknowledgements: updated };
664 }).pipe(Effect.andThen(Deferred.succeed(acknowledgement, undefined)), Effect.asVoid);
665 yield* Stream.fromQueue(outgoing).pipe(
666 Stream.flatMap((write) => {
667 const acknowledgement = write.acknowledgement;
668 const completion =
669 acknowledgement === undefined
670 ? Stream.empty
671 : Stream.fromEffect(acknowledgeOutgoingWrite(acknowledgement)).pipe(Stream.drain);
672 return Stream.make(write.payload).pipe(Stream.concat(completion));
673 }),
674 Stream.run(options.stdio.stdout()),
675 Effect.onExit((exit) =>
676 Exit.match(exit, {
677 onFailure: (cause) => {
678 const error = new AcpError.AcpTransportError({
679 detail: Cause.hasInterruptsOnly(cause)
680 ? "The ACP output writer was interrupted while closing"
681 : "Failed to write an outgoing ACP message",
682 cause,
683 });
684 return failOutgoingWrites(error).pipe(
685 Effect.andThen(
686 Cause.hasInterruptsOnly(cause)
687 ? Effect.void
688 : handleTermination(() => Effect.succeed(error)),
689 ),
690 );
691 },
692 onSuccess: () =>
693 Ref.get(outgoingWriterState).pipe(
694 Effect.flatMap((state) => {
695 // Intentional Queue.end (serverProtocol.end) completes the writer
696 // successfully. Do not invent a transport failure or client protocol
697 // error for a clean RPC shutdown.
698 const handled = state.intentionalEnd
699 ? completeOutgoingWrites()
700 : (() => {
701 const error = new AcpError.AcpTransportError({
702 detail: "ACP output writer ended before the protocol closed",
703 cause: "Output writer ended",
704 });
705 return failOutgoingWrites(error).pipe(
706 Effect.andThen(handleTermination(() => Effect.succeed(error))),
707 );
708 })();
709 return handled.pipe(
710 Effect.andThen(
711 options.testHooks?.onOutgoingWriterExit === undefined
712 ? Effect.void
713 : options.testHooks.onOutgoingWriterExit({
714 intentionalEnd: state.intentionalEnd,
715 }),
716 ),
717 );
718 }),
719 ),
720 }),
721 ),
722 Effect.forkScoped,
723 );
724
725 const clientProtocol = RpcClient.Protocol.of({
726 run: (_clientId, f) =>
727 Stream.fromQueue(clientQueue).pipe(
728 Stream.runForEach((message) => f(message)),
729 Effect.forever,
730 ),
731 send: (_clientId, request) =>
732 offerOutgoing(request).pipe(
733 Effect.mapError(
734 (error) =>
735 new RpcClientError.RpcClientError({
736 reason: new RpcClientError.RpcClientDefect({
737 message: "Failed to send ACP protocol message.",
738 cause: error,
739 }),
740 }),
741 ),
742 ),
743 supportsAck: true,
744 supportsTransferables: false,
745 });
746
747 const serverProtocol = RpcServer.Protocol.of({
748 run: (f) =>
749 Stream.fromQueue(serverQueue).pipe(
750 Stream.runForEach((message) => f(0, message)),
751 Effect.forever,
752 ),
753 disconnects,
754 send: (_clientId, response) =>
755 offerOutgoing(response).pipe(
756 Effect.tapError((error) =>
757 response._tag === "Exit" && options.onOutgoingResponseFailure !== undefined
758 ? options.onOutgoingResponseFailure(String(response.requestId), error)
759 : Effect.void,
760 ),
761 Effect.orDie,
762 ),
763 end: (_clientId) =>
764 Ref.update(outgoingWriterState, (state) => ({ ...state, intentionalEnd: true })).pipe(
765 Effect.andThen(Queue.end(outgoing)),
766 ),
767 clientIds: Effect.succeed(new Set([0])),
768 initialMessage: Effect.succeedNone,
769 supportsAck: true,
770 supportsTransferables: false,
771 supportsSpanPropagation: true,
772 });
773
774 // JSON-RPC notifications carry no `id`. The generic Request encoder emits `id: ""` plus
775 // `headers`, which real agents (Grok CLI) parse as a malformed request and silently drop.
776 // That made `session/cancel` a no-op against Grok while the lenient mock agent accepted it.
777 const sendNotification = Effect.fn("sendNotification")(function* (
778 method: string,
779 payload: unknown,
780 ) {
781 yield* ensureActive;
782 yield* logProtocol({
783 direction: "outgoing",
784 stage: "decoded",
785 payload: { _tag: "Notification", tag: method, payload },
786 });
787 const exit = encodeJsonRpcNotification({ jsonrpc: "2.0", method, params: payload });
788 if (Exit.isFailure(exit)) {
789 return yield* AcpError.AcpProtocolParseError.fromEncodingError(
790 method,
791 undefined,
792 Cause.squash(exit.cause),
793 );
794 }
795 const encoded = `${exit.value}\n`;
796 yield* logProtocol({ direction: "outgoing", stage: "raw", payload: encoded });
797 yield* ensureActive;
798 // FIFO queue admission preserves wire ordering against later requests
799 // (a session/prompt sent after session/cancel cannot overtake it).
800 yield* Queue.offer(outgoing, { payload: encoded }).pipe(
801 Effect.mapError(
802 (cause) =>
803 new AcpError.AcpTransportError({
804 detail: "Failed to queue an outgoing ACP notification",
805 cause,
806 }),
807 ),
808 Effect.filterOrFail(
809 (accepted) => accepted,
810 () =>
811 new AcpError.AcpTransportError({
812 detail: "The ACP output queue was closed before accepting a notification",
813 cause: "Output queue closed",
814 }),
815 ),
816 );
817 });
818
819 const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) {
820 yield* ensureActive;
821 const requestId = yield* Ref.modify(
822 nextRequestId,
823 (current) => [current, current + 1] as const,
824 );
825 const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();
826 yield* Ref.update(extPending, (pending) =>
827 new Map(pending).set(String(requestId), { deferred, method }),
828 );
829 yield* offerOutgoing({
830 _tag: "Request",
831 id: requestId,
832 tag: method,
833 payload,
834 headers: [],
835 }).pipe(Effect.tapError(() => removeExtPending(requestId)));
836 return yield* Deferred.await(deferred).pipe(
837 Effect.onInterrupt(() => removeExtPending(requestId)),
838 );
839 });
840
841 return {
842 clientProtocol,
843 serverProtocol,
844 get incoming() {
845 return Stream.fromQueue(notificationQueue);
846 },
847 request: sendRequest,
848 notify: sendNotification,
849 } satisfies AcpPatchedProtocol;
850});
851
852function isProtocolError(
853 value: unknown,
854): value is { code: number; message: string; data?: unknown } {
855 return (
856 typeof value === "object" &&
857 value !== null &&
858 "code" in value &&
859 typeof value.code === "number" &&
860 "message" in value &&
861 typeof value.message === "string"
862 );
863}