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

protocol.ts

608 lines20.2 KB

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;
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 onNotification?: (
53 notification: AcpIncomingNotification,
54 ) => Effect.Effect<void, AcpError.AcpError, never>;
55 readonly onExtRequest?: (
56 method: string,
57 params: unknown,
58 ) => Effect.Effect<unknown, AcpError.AcpError, never>;
59 readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
61​
62export interface AcpPatchedProtocol {
63 readonly clientProtocol: RpcClient.Protocol["Service"];
64 readonly serverProtocol: RpcServer.Protocol["Service"];
65 readonly incoming: Stream.Stream<AcpIncomingNotification>;
66 readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
67 readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
69​
70interface AcpPendingRequest {
71 readonly deferred: Deferred.Deferred<unknown, AcpError.AcpError>;
72 readonly method: string;
74​
75const decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);
76const decodeElicitationComplete = Schema.decodeUnknownEffect(
77 AcpSchema.ElicitationCompleteNotification,
78);
79const parserFactory = RpcSerialization.ndJsonRpc();
80const MAX_BUFFERED_RAW_NOTIFICATIONS = 32;
81// Outbound JSON-RPC notification: no `id`, so peers never treat it as a request.
82const encodeJsonRpcNotification = Schema.encodeUnknownExit(
83 Schema.fromJsonString(
84 Schema.Struct({
85 jsonrpc: Schema.Literal("2.0"),
86 method: Schema.String,
87 params: Schema.Unknown,
88 }),
89 ),
90);
91​
92export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
93 options: AcpPatchedProtocolOptions,
94): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {
95 const parser = parserFactory.makeUnsafe();
96 const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();
97 const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
98 const notificationQueue = yield* Queue.sliding<AcpIncomingNotification>(
99 MAX_BUFFERED_RAW_NOTIFICATIONS,
100 );
101 const disconnects = yield* Queue.unbounded<number>();
102 const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();
103 const nextRequestId = yield* Ref.make(1);
104 const terminationHandled = yield* Ref.make(false);
105 const extPending = yield* Ref.make(new Map<string, AcpPendingRequest>());
106​
107 const logProtocol = (event: AcpProtocolLogEvent) => {
108 if (event.direction === "incoming" && !options.logIncoming) {
109 return Effect.void;
110 }
111 if (event.direction === "outgoing" && !options.logOutgoing) {
112 return Effect.void;
113 }
114 return (
115 options.logger?.(event) ??
116 Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event }))
117 );
118 };
119​
120 const offerOutgoing = Effect.fn("offerOutgoing")(function* (
121 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
122 ) {
123 // RpcClient emits `@effect/rpc/Interrupt` when a pending request's fiber is interrupted.
124 // ACP has no such method; agents log it as an error and cannot act on it, so drop it.
125 if (message._tag === "Interrupt") {
126 return;
127 }
128 yield* logProtocol({
129 direction: "outgoing",
130 stage: "decoded",
131 payload: message,
132 });
133​
134 const method = message._tag === "Request" ? message.tag : undefined;
135 const encodedRequestId =
136 message._tag === "Request"
137 ? message.id
138 : "requestId" in message
139 ? message.requestId
140 : undefined;
141 const requestId = encodedRequestId === "" ? undefined : encodedRequestId;
142 const encoded = yield* Effect.try({
143 try: () => parser.encode(message),
144 catch: (cause) => AcpError.AcpProtocolParseError.fromEncodingError(method, requestId, cause),
145 });
146​
147 if (encoded) {
148 yield* logProtocol({
149 direction: "outgoing",
150 stage: "raw",
151 payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
152 });
153​
154 yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
155 }
156 });
157​
158 const resolveExtPending = (
159 requestId: AcpError.AcpRequestId,
160 onFound: (pendingRequest: AcpPendingRequest) => Effect.Effect<void>,
161 ) =>
162 Ref.modify(extPending, (pending) => {
163 const pendingKey = String(requestId);
164 const pendingRequest = pending.get(pendingKey);
165 if (!pendingRequest) {
166 return [Effect.void, pending] as const;
167 }
168 const next = new Map(pending);
169 next.delete(pendingKey);
170 return [onFound(pendingRequest), next] as const;
171 }).pipe(Effect.flatten);
172​
173 const removeExtPending = (requestId: AcpError.AcpRequestId) =>
174 Ref.update(extPending, (pending) => {
175 const pendingKey = String(requestId);
176 if (!pending.has(pendingKey)) {
177 return pending;
178 }
179 const next = new Map(pending);
180 next.delete(pendingKey);
181 return next;
182 });
183​
184 const completeExtPendingFailure = (requestId: AcpError.AcpRequestId, error: AcpError.AcpError) =>
185 resolveExtPending(requestId, ({ deferred }) => Deferred.fail(deferred, error));
186​
187 const completeExtPendingSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
188 resolveExtPending(requestId, ({ deferred }) => Deferred.succeed(deferred, value));
189​
190 const failAllExtPending = (error: AcpError.AcpError) =>
191 Ref.getAndSet(extPending, new Map()).pipe(
192 Effect.flatMap((pending) =>
193 Effect.forEach([...pending.values()], ({ deferred }) => Deferred.fail(deferred, error), {
194 discard: true,
195 }),
196 ),
197 );
198​
199 const dispatchNotification = (notification: AcpIncomingNotification) =>
200 Queue.offer(notificationQueue, notification).pipe(
201 Effect.andThen(
202 options.onNotification
203 ? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))
204 : Effect.void,
205 ),
206 Effect.asVoid,
207 );
208​
209 const emitClientProtocolError = (error: AcpError.AcpError) =>
210 Queue.offer(clientQueue, {
211 _tag: "ClientProtocolError",
212 error: new RpcClientError.RpcClientError({
213 reason: new RpcClientError.RpcClientDefect({
214 message: "ACP protocol terminated.",
215 cause: error,
216 }),
217 }),
218 }).pipe(Effect.asVoid);
219​
220 const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError | undefined>) =>
221 Ref.modify(terminationHandled, (handled) => {
222 if (handled) {
223 return [Effect.void, true] as const;
224 }
225 return [
226 Effect.gen(function* () {
227 yield* Queue.offer(disconnects, 0);
228 const error = yield* classify();
229 if (!error) {
230 return;
231 }
232 yield* failAllExtPending(error);
233 yield* emitClientProtocolError(error);
234 if (options.onTermination) {
235 yield* options.onTermination(error);
236 }
237 }),
238 true,
239 ] as const;
240 }).pipe(Effect.flatten);
241​
242 const respondWithSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
243 offerOutgoing({
244 _tag: "Exit",
245 requestId,
246 exit: {
247 _tag: "Success",
248 value,
249 },
250 });
251​
252 const respondWithError = (requestId: AcpError.AcpRequestId, error: AcpError.AcpRequestError) =>
253 offerOutgoing({
254 _tag: "Exit",
255 requestId,
256 exit: {
257 _tag: "Failure",
258 cause: [
259 {
260 _tag: "Fail",
261 error: error.toProtocolError(),
262 },
263 ],
264 },
265 });
266​
267 const handleExtRequest = (message: RpcMessage.RequestEncoded) => {
268 if (!options.onExtRequest) {
269 return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag));
270 }
271 return options.onExtRequest(message.tag, message.payload).pipe(
272 Effect.matchEffect({
273 onFailure: (error) =>
274 respondWithError(
275 message.id,
276 AcpError.AcpRequestError.fromExtensionHandlerError(error, message.tag),
277 ),
278 onSuccess: (value) => respondWithSuccess(message.id, value),
279 }),
280 );
281 };
282​
283 const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => {
284 if (message.id === "") {
285 if (message.tag === CLIENT_METHODS.session_update) {
286 return decodeSessionUpdate(message.payload).pipe(
287 Effect.map(
288 (params) =>
289 ({
290 _tag: "SessionUpdate",
291 method: CLIENT_METHODS.session_update,
292 params,
293 }) satisfies AcpIncomingNotification,
294 ),
295 Effect.mapError((cause) =>
296 AcpError.AcpProtocolParseError.fromSchemaError(
297 "decode-notification-payload",
298 CLIENT_METHODS.session_update,
299 cause,
300 ),
301 ),
302 Effect.flatMap(dispatchNotification),
303 );
304 }
305 if (message.tag === CLIENT_METHODS.session_elicitation_complete) {
306 return decodeElicitationComplete(message.payload).pipe(
307 Effect.map(
308 (params) =>
309 ({
310 _tag: "ElicitationComplete",
311 method: CLIENT_METHODS.session_elicitation_complete,
312 params,
313 }) satisfies AcpIncomingNotification,
314 ),
315 Effect.mapError((cause) =>
316 AcpError.AcpProtocolParseError.fromSchemaError(
317 "decode-notification-payload",
318 CLIENT_METHODS.session_elicitation_complete,
319 cause,
320 ),
321 ),
322 Effect.flatMap(dispatchNotification),
323 );
324 }
325 return dispatchNotification({
326 _tag: "ExtNotification",
327 method: message.tag,
328 params: message.payload,
329 });
330 }
331​
332 if (!options.serverRequestMethods.has(message.tag)) {
333 return handleExtRequest(message).pipe(
334 Effect.catchTags({
335 AcpProtocolParseError: (error) =>
336 Effect.logWarning(error).pipe(
337 Effect.annotateLogs({
338 method: message.tag,
339 requestId: message.id,
340 operation: error.operation,
341 }),
342 Effect.andThen(
343 respondWithError(
344 message.id,
345 AcpError.AcpRequestError.fromExtensionResponseEncodingError(
346 message.tag,
347 message.id,
348 error,
349 ),
350 ),
351 ),
352 ),
353 }),
354 Effect.asVoid,
355 );
356 }
357​
358 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
359 };
360​
361 const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
362 Ref.get(extPending).pipe(
363 Effect.flatMap((pending) => {
364 const pendingRequest = pending.get(String(message.requestId));
365 if (!pendingRequest) {
366 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
367 }
368 if (message.exit._tag === "Success") {
369 return completeExtPendingSuccess(message.requestId, message.exit.value);
370 }
371 const failure = message.exit.cause.find((entry) => entry._tag === "Fail");
372 if (failure && isProtocolError(failure.error)) {
373 return completeExtPendingFailure(
374 message.requestId,
375 AcpError.AcpRequestError.fromProtocolError(failure.error, {
376 method: pendingRequest.method,
377 requestId: message.requestId,
378 cause: message.exit.cause,
379 }),
380 );
381 }
382 return completeExtPendingFailure(
383 message.requestId,
384 AcpError.AcpRequestError.fromExtensionResponseFailure(
385 pendingRequest.method,
386 message.requestId,
387 message.exit.cause,
388 ),
389 );
390 }),
391 );
392​
393 const routeDecodedMessage = (
394 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
395 ): Effect.Effect<void, AcpError.AcpError> => {
396 switch (message._tag) {
397 case "Request":
398 return handleRequestEncoded(message);
399 case "Exit":
400 return handleExitEncoded(message);
401 case "Chunk":
402 return Ref.get(extPending).pipe(
403 Effect.flatMap((pending) => {
404 const pendingRequest = pending.get(String(message.requestId));
405 return pendingRequest
406 ? completeExtPendingFailure(
407 message.requestId,
408 AcpError.AcpRequestError.unsupportedStreamingResponse(
409 pendingRequest.method,
410 message.requestId,
411 ),
412 )
413 : Queue.offer(clientQueue, message).pipe(Effect.asVoid);
414 }),
415 );
416 case "Defect":
417 case "ClientProtocolError":
418 case "Pong":
419 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
420 case "Ack":
421 case "Interrupt":
422 case "Ping":
423 case "Eof":
424 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
425 }
426 };
427​
428 yield* options.stdio.stdin.pipe(
429 Stream.runForEach((data) =>
430 (options.logIncoming
431 ? logProtocol({
432 direction: "incoming",
433 stage: "raw",
434 payload: typeof data === "string" ? data : new TextDecoder().decode(data),
435 })
436 : Effect.void
437 ).pipe(
438 Effect.flatMap(() =>
439 Effect.try({
440 try: () =>
441 parser.decode(data) as ReadonlyArray<
442 RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded
443 >,
444 catch: (cause) =>
445 new AcpError.AcpProtocolParseError({
446 operation: "decode-wire-message",
447 cause,
448 }),
449 }),
450 ),
451 Effect.tap((messages) =>
452 logProtocol({
453 direction: "incoming",
454 stage: "decoded",
455 payload: messages,
456 }),
457 ),
458 Effect.tapErrorTag("AcpProtocolParseError", (error) =>
459 logProtocol({
460 direction: "incoming",
461 stage: "decode_failed",
462 payload: {
463 operation: error.operation,
464 ...(error.method === undefined ? {} : { method: error.method }),
465 ...(error.requestId === undefined ? {} : { requestId: error.requestId }),
466 ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
467 ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
468 ...(error.maximumPathDepth === undefined
469 ? {}
470 : { maximumPathDepth: error.maximumPathDepth }),
471 },
472 }),
473 ),
474 Effect.flatMap((messages) =>
475 Effect.forEach(messages, routeDecodedMessage, {
476 discard: true,
477 }),
478 ),
479 ),
480 ),
481 Effect.matchEffect({
482 onFailure: (error) => {
483 const normalized: AcpError.AcpError = isAcpError(error)
484 ? error
485 : new AcpError.AcpTransportError({
486 operation: "read-input-stream",
487 cause: error,
488 });
489 return handleTermination(() => Effect.succeed(normalized));
490 },
491 onSuccess: () =>
492 handleTermination(
493 () =>
494 options.terminationError ?? Effect.succeed(new AcpError.AcpInputStreamEndedError({})),
495 ),
496 }),
497 Effect.forkScoped,
498 );
499​
500 yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
501​
502 const clientProtocol = RpcClient.Protocol.of({
503 run: (_clientId, f) =>
504 Stream.fromQueue(clientQueue).pipe(
505 Stream.runForEach((message) => f(message)),
506 Effect.forever,
507 ),
508 send: (_clientId, request) =>
509 offerOutgoing(request).pipe(
510 Effect.mapError(
511 (error) =>
512 new RpcClientError.RpcClientError({
513 reason: new RpcClientError.RpcClientDefect({
514 message: "Failed to send ACP protocol message.",
515 cause: error,
516 }),
517 }),
518 ),
519 ),
520 supportsAck: true,
521 supportsTransferables: false,
522 });
523​
524 const serverProtocol = RpcServer.Protocol.of({
525 run: (f) =>
526 Stream.fromQueue(serverQueue).pipe(
527 Stream.runForEach((message) => f(0, message)),
528 Effect.forever,
529 ),
530 disconnects,
531 send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),
532 end: (_clientId) => Queue.end(outgoing),
533 clientIds: Effect.succeed(new Set([0])),
534 initialMessage: Effect.succeedNone,
535 supportsAck: true,
536 supportsTransferables: false,
537 supportsSpanPropagation: true,
538 });
539​
540 // JSON-RPC notifications carry no `id`. The generic Request encoder emits `id: ""` plus
541 // `headers`, which real agents (Grok CLI) parse as a malformed request and silently drop.
542 // That made `session/cancel` a no-op against Grok while the lenient mock agent accepted it.
543 const sendNotification = Effect.fn("sendNotification")(function* (
544 method: string,
545 payload: unknown,
546 ) {
547 yield* logProtocol({
548 direction: "outgoing",
549 stage: "decoded",
550 payload: { _tag: "Notification", tag: method, payload },
551 });
552 const exit = encodeJsonRpcNotification({ jsonrpc: "2.0", method, params: payload });
553 if (Exit.isFailure(exit)) {
554 return yield* AcpError.AcpProtocolParseError.fromEncodingError(
555 method,
556 undefined,
557 Cause.squash(exit.cause),
558 );
559 }
560 const encoded = `${exit.value}\n`;
561 yield* logProtocol({ direction: "outgoing", stage: "raw", payload: encoded });
562 yield* Queue.offer(outgoing, encoded);
563 });
564​
565 const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) {
566 const requestId = yield* Ref.modify(
567 nextRequestId,
568 (current) => [current, current + 1] as const,
569 );
570 const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();
571 yield* Ref.update(extPending, (pending) =>
572 new Map(pending).set(String(requestId), { deferred, method }),
573 );
574 yield* offerOutgoing({
575 _tag: "Request",
576 id: requestId,
577 tag: method,
578 payload,
579 headers: [],
580 }).pipe(Effect.tapError(() => removeExtPending(requestId)));
581 return yield* Deferred.await(deferred).pipe(
582 Effect.onInterrupt(() => removeExtPending(requestId)),
583 );
584 });
585​
586 return {
587 clientProtocol,
588 serverProtocol,
589 get incoming() {
590 return Stream.fromQueue(notificationQueue);
591 },
592 request: sendRequest,
593 notify: sendNotification,
594 } satisfies AcpPatchedProtocol;
595});
596​
597function isProtocolError(
598 value: unknown,
599): value is { code: number; message: string; data?: unknown } {
600 return (
601 typeof value === "object" &&
602 value !== null &&
603 "code" in value &&
604 typeof value.code === "number" &&
605 "message" in value &&
606 typeof value.message === "string"
607 );