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