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

protocol.ts

522 lines18.9 KB

1import * as Cause from "effect/Cause";
2import * as Deferred from "effect/Deferred";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
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 * as Scope from "effect/Scope";
10import * as Schema from "effect/Schema";
11import * as Stdio from "effect/Stdio";
12import * as Stream from "effect/Stream";
13​
14import * as CodexError from "./errors.ts";
15import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
16const isJsonRpcId = Schema.is(JsonRpcId);
17const isJsonRpcResponseEnvelope = Schema.is(JsonRpcResponseEnvelope);
18const isCodexAppServerError = Schema.is(CodexError.CodexAppServerError);
19const MAX_BUFFERED_RAW_MESSAGES = 32;
20​
21/**
22 * How long the reader may keep handling input after the process exits. The
23 * pipe can still hold output written before the exit. Past this, the exit ends
24 * the connection and any input not yet handled is dropped, so a reader that is
25 * stuck in a handler cannot hold the connection open forever.
26 */
27const PROCESS_EXIT_INPUT_GRACE = Duration.seconds(5);
28​
29export interface CodexAppServerProtocolLogEvent {
30 readonly direction: "incoming" | "outgoing";
31 readonly stage: "raw" | "decoded" | "decode_failed";
32 readonly payload: unknown;
34​
35export interface CodexAppServerIncomingNotification {
36 readonly method: string;
37 readonly params?: unknown;
39​
40export interface CodexAppServerIncomingRequest {
41 readonly id: string | number;
42 readonly method: string;
43 readonly params?: unknown;
45​
46export interface CodexAppServerPatchedProtocolOptions {
47 readonly stdio: Stdio.Stdio;
48 readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;
49 /**
50 * Completes when the peer process exits. The protocol then terminates even
51 * if a message handler never returns and the input never reaches its end.
52 */
53 readonly processExit?: Effect.Effect<CodexError.CodexAppServerError>;
54 readonly logIncoming?: boolean;
55 readonly logOutgoing?: boolean;
56 readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;
57 readonly onNotification?: (
58 notification: CodexAppServerIncomingNotification,
59 ) => Effect.Effect<void, never>;
60 readonly onRequest?: (
61 request: CodexAppServerIncomingRequest,
62 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
63 readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;
65​
66export interface CodexAppServerPatchedProtocol {
67 readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;
68 readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;
69 /** Completes with the error that ended the connection. */
70 readonly terminated: Effect.Effect<CodexError.CodexAppServerError>;
71 readonly request: (
72 method: string,
73 payload?: unknown,
74 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
75 readonly notify: (
76 method: string,
77 payload?: unknown,
78 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
79 readonly respond: (
80 requestId: string | number,
81 result: unknown,
82 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
83 readonly respondError: (
84 requestId: string | number,
85 error: CodexError.CodexAppServerRequestError,
86 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
88​
89interface CodexAppServerPendingRequest {
90 readonly deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>;
91 readonly method: string;
93​
94function isObject(value: unknown): value is Record<string, unknown> {
95 return typeof value === "object" && value !== null;
97​
98function isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest {
99 if (!isObject(value) || typeof value.method !== "string") {
100 return false;
101 }
102 return isJsonRpcId(value.id);
104​
105function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {
106 return isObject(value) && typeof value.method === "string" && !("id" in value);
108​
109function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {
110 return isJsonRpcResponseEnvelope(value);
112​
113const encodeJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
114const decodeJsonString = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
115​
116const encodeWireMessage = (
117 message: Record<string, unknown>,
118): Effect.Effect<string, CodexError.CodexAppServerProtocolParseError> =>
119 encodeJsonString(message).pipe(
120 Effect.map((encoded) => `${encoded}\n`),
121 Effect.mapError((cause) => {
122 const method = typeof message.method === "string" ? message.method : undefined;
123 const requestId =
124 typeof message.id === "string" || typeof message.id === "number"
125 ? String(message.id)
126 : undefined;
127 return CodexError.CodexAppServerProtocolParseError.fromSchemaError(
128 "encode-wire-message",
129 cause,
130 {
131 ...(method === undefined ? {} : { method }),
132 ...(requestId === undefined ? {} : { requestId }),
133 },
134 );
135 }),
136 );
137​
138const decodeWireMessage = (
139 line: string,
140): Effect.Effect<unknown, CodexError.CodexAppServerProtocolParseError> =>
141 decodeJsonString(line).pipe(
142 Effect.mapError((cause) =>
143 CodexError.CodexAppServerProtocolParseError.fromSchemaError("decode-wire-message", cause),
144 ),
145 );
146​
147const normalizeIncomingError = (
148 error: unknown,
149 operation: CodexError.CodexAppServerTransportOperation,
150): CodexError.CodexAppServerError =>
151 isCodexAppServerError(error)
152 ? error
153 : new CodexError.CodexAppServerTransportError({
154 operation,
155 cause: error,
156 });
157​
158const toProtocolMessage = (
159 requestId: string | number,
160 fields: {
161 readonly result?: unknown;
162 readonly error?: CodexError.CodexAppServerProtocolErrorShape;
163 },
164): { readonly [key: string]: unknown } => ({
165 id: requestId,
166 ...(fields.result !== undefined ? { result: fields.result } : {}),
167 ...(fields.error !== undefined ? { error: fields.error } : {}),
168});
169​
170export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPatchedProtocol")(
171 function* (
172 options: CodexAppServerPatchedProtocolOptions,
173 ): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {
174 const protocolScope = yield* Scope.Scope;
175 const requestHandlerScope = yield* Scope.fork(protocolScope, "parallel");
176 const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();
177 const incomingNotifications =
178 yield* Queue.sliding<CodexAppServerIncomingNotification>(MAX_BUFFERED_RAW_MESSAGES);
179 const incomingRequests =
180 yield* Queue.sliding<CodexAppServerIncomingRequest>(MAX_BUFFERED_RAW_MESSAGES);
181 const pending = yield* Ref.make(new Map<string, CodexAppServerPendingRequest>());
182 const nextRequestId = yield* Ref.make(1);
183 const remainder: Array<string> = [];
184 const terminationHandled = yield* Ref.make(false);
185 const terminationFailure = yield* Ref.make(Option.none<CodexError.CodexAppServerError>());
186 const terminationSignal = yield* Deferred.make<CodexError.CodexAppServerError>();
187 const activeRequestHandlers = yield* Ref.make(0);
188​
189 const logProtocol = (event: CodexAppServerProtocolLogEvent) => {
190 if (event.direction === "incoming" && !options.logIncoming) {
191 return Effect.void;
192 }
193 if (event.direction === "outgoing" && !options.logOutgoing) {
194 return Effect.void;
195 }
196 return (
197 options.logger?.(event) ??
198 Effect.logDebug("Codex App Server protocol event").pipe(Effect.annotateLogs({ event }))
199 );
200 };
201​
202 const failAllPending = (error: CodexError.CodexAppServerError) =>
203 Ref.get(pending).pipe(
204 Effect.flatMap((current) =>
205 Effect.forEach([...current.values()], ({ deferred }) => Deferred.fail(deferred, error), {
206 discard: true,
207 }),
208 ),
209 Effect.andThen(Ref.set(pending, new Map())),
210 );
211​
212 const handleTermination = (classify: () => Effect.Effect<CodexError.CodexAppServerError>) =>
213 Ref.modify(terminationHandled, (handled) => {
214 if (handled) {
215 return [Effect.void, true] as const;
216 }
217 return [
218 Effect.gen(function* () {
219 const error = yield* classify();
220 yield* Ref.set(terminationFailure, Option.some(error));
221 yield* failAllPending(error);
222 yield* Queue.end(outgoing);
223 yield* Deferred.succeed(terminationSignal, error);
224 yield* Scope.close(requestHandlerScope, Exit.void).pipe(
225 Effect.forkIn(protocolScope, { startImmediately: true }),
226 Effect.asVoid,
227 );
228 if (options.onTermination) {
229 yield* options.onTermination(error);
230 }
231 }),
232 true,
233 ] as const;
234 }).pipe(Effect.flatten);
235​
236 const offerOutgoing = (message: Record<string, unknown>) =>
237 Effect.gen(function* () {
238 const failure = yield* Ref.get(terminationFailure);
239 if (Option.isSome(failure)) return yield* failure.value;
240​
241 yield* logProtocol({
242 direction: "outgoing",
243 stage: "decoded",
244 payload: message,
245 });
246 const encoded = yield* encodeWireMessage(message);
247 yield* logProtocol({
248 direction: "outgoing",
249 stage: "raw",
250 payload: encoded,
251 });
252 const accepted = yield* Queue.offer(outgoing, encoded);
253 if (!accepted) {
254 const closed = yield* Ref.get(terminationFailure);
255 return yield* Option.getOrElse(
256 closed,
257 () => new CodexError.CodexAppServerInputStreamEndedError({}),
258 );
259 }
260 });
261​
262 const removePending = (requestId: string) =>
263 Ref.update(pending, (current) => {
264 if (!current.has(requestId)) {
265 return current;
266 }
267 const next = new Map(current);
268 next.delete(requestId);
269 return next;
270 });
271​
272 const resolvePending = (
273 requestId: string,
274 handler: (pendingRequest: CodexAppServerPendingRequest) => Effect.Effect<void>,
275 ) =>
276 Ref.modify(pending, (current) => {
277 const pendingRequest = current.get(requestId);
278 if (!pendingRequest) {
279 return [Effect.void, current] as const;
280 }
281 const next = new Map(current);
282 next.delete(requestId);
283 return [handler(pendingRequest), next] as const;
284 }).pipe(Effect.flatten);
285​
286 const respond = (requestId: string | number, result: unknown) =>
287 offerOutgoing(toProtocolMessage(requestId, { result }));
288​
289 const respondError = (
290 requestId: string | number,
291 error: CodexError.CodexAppServerRequestError,
292 ) => offerOutgoing(toProtocolMessage(requestId, { error: error.toProtocolError() }));
293​
294 const handleResponse = (response: typeof JsonRpcResponseEnvelope.Type) => {
295 const requestId = String(response.id);
296 const protocolError = response.error;
297 if (protocolError !== undefined) {
298 return resolvePending(requestId, ({ deferred, method }) =>
299 Deferred.fail(
300 deferred,
301 CodexError.CodexAppServerRequestError.fromProtocolError(
302 protocolError,
303 method,
304 requestId,
305 ),
306 ),
307 );
308 }
309 return resolvePending(requestId, ({ deferred }) =>
310 Deferred.succeed(deferred, response.result),
311 );
312 };
313​
314 const handleRequest = (request: CodexAppServerIncomingRequest) =>
315 Queue.offer(incomingRequests, request).pipe(
316 Effect.flatMap(() => {
317 const handler = options.onRequest;
318 if (!handler) return Effect.void;
319​
320 return Ref.modify(activeRequestHandlers, (count) =>
321 count >= MAX_BUFFERED_RAW_MESSAGES ? [false, count] : [true, count + 1],
322 ).pipe(
323 Effect.flatMap((accepted) => {
324 if (!accepted) {
325 return respondError(
326 request.id,
327 CodexError.CodexAppServerRequestError.overloaded(
328 "Too many Codex requests are already active.",
329 ),
330 );
331 }
332​
333 return handler(request).pipe(
334 Effect.matchEffect({
335 onFailure: (error) =>
336 respondError(
337 request.id,
338 CodexError.CodexAppServerRequestError.fromAppServerError(
339 error,
340 request.method,
341 ),
342 ),
343 onSuccess: (result) => respond(request.id, result),
344 }),
345 Effect.ensuring(
346 Ref.update(activeRequestHandlers, (count) => Math.max(0, count - 1)),
347 ),
348 Effect.catch((error) =>
349 handleTermination(() => Effect.succeed(error)).pipe(
350 Effect.forkIn(protocolScope),
351 Effect.asVoid,
352 ),
353 ),
354 Effect.forkIn(requestHandlerScope, { startImmediately: true }),
355 Effect.asVoid,
356 );
357 }),
358 );
359 }),
360 Effect.asVoid,
361 );
362​
363 const handleNotification = (notification: CodexAppServerIncomingNotification) =>
364 Queue.offer(incomingNotifications, notification).pipe(
365 Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void),
366 Effect.asVoid,
367 );
368​
369 const routeMessage = Effect.fnUntraced(function* (message: unknown) {
370 if (Option.isSome(yield* Ref.get(terminationFailure))) return;
371 if (isIncomingRequest(message)) return yield* handleRequest(message);
372 if (isIncomingNotification(message)) return yield* handleNotification(message);
373 if (isIncomingResponse(message)) return yield* handleResponse(message);
374 return yield* CodexError.CodexAppServerProtocolParseError.fromUnroutableMessage(message);
375 });
376​
377 const handleLine = (line: string): Effect.Effect<void, CodexError.CodexAppServerError> => {
378 if (line.trim().length === 0) {
379 return Effect.void;
380 }
381 return logProtocol({
382 direction: "incoming",
383 stage: "raw",
384 payload: line,
385 }).pipe(
386 Effect.flatMap(() => decodeWireMessage(line)),
387 Effect.tap((decoded) =>
388 logProtocol({
389 direction: "incoming",
390 stage: "decoded",
391 payload: decoded,
392 }),
393 ),
394 Effect.tapErrorTag("CodexAppServerProtocolParseError", (error) =>
395 logProtocol({
396 direction: "incoming",
397 stage: "decode_failed",
398 payload: {
399 operation: error.operation,
400 ...(error.method === undefined ? {} : { method: error.method }),
401 ...(error.requestId === undefined ? {} : { requestId: error.requestId }),
402 ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
403 ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
404 ...(error.maximumPathDepth === undefined
405 ? {}
406 : { maximumPathDepth: error.maximumPathDepth }),
407 },
408 }),
409 ),
410 Effect.flatMap(routeMessage),
411 );
412 };
413​
414 yield* options.stdio.stdin.pipe(
415 Stream.interruptWhen(Deferred.await(terminationSignal)),
416 Stream.decodeText(),
417 Stream.runForEach((chunk) =>
418 Effect.sync(() => {
419 const lines: Array<string> = [];
420 let start = 0;
421 for (
422 let newline = chunk.indexOf("\n");
423 newline !== -1;
424 newline = chunk.indexOf("\n", start)
425 ) {
426 remainder.push(chunk.slice(start, newline));
427 lines.push(remainder.join("").replace(/\r$/, ""));
428 remainder.length = 0;
429 start = newline + 1;
430 }
431 // Keep unfinished lines in fragments so each chunk is scanned only once.
432 if (start < chunk.length) {
433 remainder.push(chunk.slice(start));
434 }
435 return lines;
436 }).pipe(Effect.flatMap((lines) => Effect.forEach(lines, handleLine, { discard: true }))),
437 ),
438 Effect.matchEffect({
439 onFailure: (error) =>
440 handleTermination(() =>
441 Effect.succeed(normalizeIncomingError(error, "read-input-stream")),
442 ),
443 onSuccess: () =>
444 Effect.sync(() => {
445 const line = remainder.join("");
446 remainder.length = 0;
447 return line;
448 }).pipe(
449 Effect.flatMap(handleLine),
450 Effect.matchEffect({
451 onFailure: (error) => handleTermination(() => Effect.succeed(error)),
452 onSuccess: () =>
453 handleTermination(
454 () =>
455 options.terminationError ??
456 Effect.succeed(new CodexError.CodexAppServerInputStreamEndedError({})),
457 ),
458 }),
459 ),
460 }),
461 Effect.forkScoped,
462 );
463​
464 if (options.processExit !== undefined) {
465 yield* options.processExit.pipe(
466 Effect.tap(() => Effect.sleep(PROCESS_EXIT_INPUT_GRACE)),
467 Effect.flatMap((error) => handleTermination(() => Effect.succeed(error))),
468 Effect.forkScoped,
469 );
470 }
471​
472 yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
473​
474 // Closing the client fails the requests still waiting on a reply, which
475 // would otherwise wait forever.
476 yield* Effect.addFinalizer(() =>
477 Effect.gen(function* () {
478 const closed = new CodexError.CodexAppServerInputStreamEndedError({});
479 yield* Ref.update(terminationFailure, (current) =>
480 Option.isSome(current) ? current : Option.some(closed),
481 );
482 yield* failAllPending(closed);
483 }),
484 );
485​
486 const request = (method: string, payload?: unknown) =>
487 Effect.gen(function* () {
488 const requestId = yield* Ref.modify(
489 nextRequestId,
490 (current) => [current, current + 1] as const,
491 );
492 const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();
493 yield* Ref.update(pending, (current) =>
494 new Map(current).set(String(requestId), { deferred, method }),
495 );
496 yield* offerOutgoing({
497 id: requestId,
498 method,
499 ...(payload !== undefined ? { params: payload } : {}),
500 }).pipe(Effect.tapError(() => removePending(String(requestId))));
501 return yield* Deferred.await(deferred).pipe(
502 Effect.onInterrupt(() => removePending(String(requestId))),
503 );
504 });
505​
506 const notify = (method: string, payload?: unknown) =>
507 offerOutgoing({
508 method,
509 ...(payload !== undefined ? { params: payload } : {}),
510 });
511​
512 return {
513 incomingNotifications: Stream.fromQueue(incomingNotifications),
514 incomingRequests: Stream.fromQueue(incomingRequests),
515 terminated: Deferred.await(terminationSignal),
516 request,
517 notify,
518 respond,
519 respondError,
520 } satisfies CodexAppServerPatchedProtocol;
521 },
522);