Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as FiberMap from "effect/FiberMap";
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 CodexRpc from "./_generated/meta.gen.ts";
15import * as CodexError from "./errors.ts";
16import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
17const isJsonRpcId = Schema.is(JsonRpcId);
18const isJsonRpcResponseEnvelope = Schema.is(JsonRpcResponseEnvelope);
19const isCodexAppServerError = Schema.is(CodexError.CodexAppServerError);
20const MAX_BUFFERED_RAW_MESSAGES = 32;
21// Bound JSONL lines before joining and parsing; the LF delimiter is excluded.
22const MAX_INCOMING_MESSAGE_BYTES = 128 * 1024 * 1024;
23const EXIT_STATUS_GRACE = "250 millis";
24
25export interface CodexAppServerProtocolLogEvent {
26 readonly direction: "incoming" | "outgoing";
27 readonly stage: "raw" | "decoded" | "decode_failed";
28 readonly payload: unknown;
29}
30
31export interface CodexAppServerIncomingNotification {
32 readonly method: string;
33 readonly params?: unknown;
34}
35
36export interface CodexAppServerIncomingRequest {
37 readonly id: string | number;
38 readonly method: string;
39 readonly params?: unknown;
40}
41
42export interface CodexAppServerPatchedProtocolOptions {
43 readonly stdio: Stdio.Stdio;
44 readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;
45 readonly logIncoming?: boolean;
46 readonly logOutgoing?: boolean;
47 // Test override; production uses MAX_INCOMING_MESSAGE_BYTES.
48 readonly maxIncomingMessageBytes?: number;
49 readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;
50 readonly onNotification?: (
51 notification: CodexAppServerIncomingNotification,
52 ) => Effect.Effect<void, never>;
53 readonly onRequest?: (
54 request: CodexAppServerIncomingRequest,
55 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
56 readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;
57}
58
59export interface CodexAppServerPatchedProtocol {
60 readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;
61 readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;
62 readonly request: (
63 method: string,
64 payload?: unknown,
65 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
66 readonly notify: (
67 method: string,
68 payload?: unknown,
69 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
70 readonly respond: (
71 requestId: string | number,
72 result: unknown,
73 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
74 readonly respondError: (
75 requestId: string | number,
76 error: CodexError.CodexAppServerRequestError,
77 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
78}
79
80interface CodexAppServerPendingRequest {
81 readonly deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>;
82 readonly method: string;
83}
84
85function isObject(value: unknown): value is Record<string, unknown> {
86 return typeof value === "object" && value !== null;
87}
88
89function isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest {
90 if (!isObject(value) || typeof value.method !== "string") {
91 return false;
92 }
93 return isJsonRpcId(value.id);
94}
95
96function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {
97 return isObject(value) && typeof value.method === "string" && !("id" in value);
98}
99
100function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {
101 return isJsonRpcResponseEnvelope(value);
102}
103
104const encodeJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
105const decodeJsonString = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
106
107const encodeWireMessage = (
108 message: Record<string, unknown>,
109): Effect.Effect<string, CodexError.CodexAppServerProtocolParseError> =>
110 encodeJsonString(message).pipe(
111 Effect.map((encoded) => `${encoded}\n`),
112 Effect.mapError((cause) => {
113 const method = typeof message.method === "string" ? message.method : undefined;
114 const requestId =
115 typeof message.id === "string" || typeof message.id === "number"
116 ? String(message.id)
117 : undefined;
118 return CodexError.CodexAppServerProtocolParseError.fromSchemaError(
119 "encode-wire-message",
120 cause,
121 {
122 ...(method === undefined ? {} : { method }),
123 ...(requestId === undefined ? {} : { requestId }),
124 },
125 );
126 }),
127 );
128
129const decodeWireMessage = (
130 line: string,
131): Effect.Effect<unknown, CodexError.CodexAppServerProtocolParseError> =>
132 decodeJsonString(line).pipe(
133 Effect.mapError((cause) =>
134 CodexError.CodexAppServerProtocolParseError.fromSchemaError("decode-wire-message", cause),
135 ),
136 );
137
138const normalizeIncomingError = (
139 error: unknown,
140 operation: CodexError.CodexAppServerTransportOperation,
141): CodexError.CodexAppServerError =>
142 isCodexAppServerError(error)
143 ? error
144 : new CodexError.CodexAppServerTransportError({
145 operation,
146 cause: error,
147 });
148
149const toProtocolMessage = (
150 requestId: string | number,
151 fields: {
152 readonly result?: unknown;
153 readonly error?: CodexError.CodexAppServerProtocolErrorShape;
154 },
155): { readonly [key: string]: unknown } => ({
156 id: requestId,
157 ...(fields.result !== undefined ? { result: fields.result } : {}),
158 ...(fields.error !== undefined ? { error: fields.error } : {}),
159});
160
161export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPatchedProtocol")(
162 function* (
163 options: CodexAppServerPatchedProtocolOptions,
164 ): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {
165 const protocolScope = yield* Scope.Scope;
166 const requestHandlerScope = yield* Scope.fork(protocolScope, "parallel");
167 const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();
168 const incomingNotifications =
169 yield* Queue.sliding<CodexAppServerIncomingNotification>(MAX_BUFFERED_RAW_MESSAGES);
170 const incomingRequests =
171 yield* Queue.sliding<CodexAppServerIncomingRequest>(MAX_BUFFERED_RAW_MESSAGES);
172 const pending = yield* Ref.make(new Map<string, CodexAppServerPendingRequest>());
173 const nextRequestId = yield* Ref.make(1);
174 const maxIncomingMessageBytes = options.maxIncomingMessageBytes ?? MAX_INCOMING_MESSAGE_BYTES;
175 const remainder: Array<string> = [];
176 let remainderBytes = 0;
177 const terminationHandled = yield* Ref.make(false);
178 const terminationFailure = yield* Ref.make(Option.none<CodexError.CodexAppServerError>());
179 const terminationSignal = yield* Deferred.make<void>();
180 const activeRequestHandlers = yield* Ref.make(0);
181 const requestHandlers = yield* FiberMap.make<string | number>().pipe(
182 Scope.provide(requestHandlerScope),
183 );
184
185 const logProtocol = (event: CodexAppServerProtocolLogEvent) => {
186 if (event.direction === "incoming" && !options.logIncoming) {
187 return Effect.void;
188 }
189 if (event.direction === "outgoing" && !options.logOutgoing) {
190 return Effect.void;
191 }
192 return (
193 options.logger?.(event) ??
194 Effect.logDebug("Codex App Server protocol event").pipe(Effect.annotateLogs({ event }))
195 );
196 };
197
198 const failAllPending = (error: CodexError.CodexAppServerError) =>
199 Ref.get(pending).pipe(
200 Effect.flatMap((current) =>
201 Effect.forEach([...current.values()], ({ deferred }) => Deferred.fail(deferred, error), {
202 discard: true,
203 }),
204 ),
205 Effect.andThen(Ref.set(pending, new Map())),
206 );
207
208 const handleTermination = (classify: () => Effect.Effect<CodexError.CodexAppServerError>) =>
209 Ref.modify(terminationHandled, (handled) => {
210 if (handled) {
211 return [Effect.void, true] as const;
212 }
213 return [
214 Effect.gen(function* () {
215 const error = yield* classify();
216 yield* Ref.set(terminationFailure, Option.some(error));
217 yield* failAllPending(error);
218 yield* Queue.end(outgoing);
219 yield* Deferred.succeed(terminationSignal, undefined);
220 yield* Scope.close(requestHandlerScope, Exit.void).pipe(
221 Effect.forkIn(protocolScope, { startImmediately: true }),
222 Effect.asVoid,
223 );
224 if (options.onTermination) {
225 yield* options.onTermination(error);
226 }
227 }),
228 true,
229 ] as const;
230 }).pipe(Effect.flatten);
231
232 const offerOutgoing =
233 /* Every protocol write reaches this helper; request spans cover the operation. */
234 Effect.fnUntraced(function* (message: Record<string, unknown>) {
235 const failure = yield* Ref.get(terminationFailure);
236 if (Option.isSome(failure)) return yield* failure.value;
237
238 yield* logProtocol({
239 direction: "outgoing",
240 stage: "decoded",
241 payload: message,
242 });
243 const encoded = yield* encodeWireMessage(message);
244 yield* logProtocol({
245 direction: "outgoing",
246 stage: "raw",
247 payload: encoded,
248 });
249 const accepted = yield* Queue.offer(outgoing, encoded);
250 if (!accepted) {
251 const closed = yield* Ref.get(terminationFailure);
252 return yield* Option.getOrElse(
253 closed,
254 () => new CodexError.CodexAppServerInputStreamEndedError({}),
255 );
256 }
257 });
258
259 const removePending = (requestId: string) =>
260 Ref.update(pending, (current) => {
261 if (!current.has(requestId)) {
262 return current;
263 }
264 const next = new Map(current);
265 next.delete(requestId);
266 return next;
267 });
268
269 const resolvePending = (
270 requestId: string,
271 handler: (pendingRequest: CodexAppServerPendingRequest) => Effect.Effect<void>,
272 ) =>
273 Ref.modify(pending, (current) => {
274 const pendingRequest = current.get(requestId);
275 if (!pendingRequest) {
276 return [Effect.void, current] as const;
277 }
278 const next = new Map(current);
279 next.delete(requestId);
280 return [handler(pendingRequest), next] as const;
281 }).pipe(Effect.flatten);
282
283 const respond = (requestId: string | number, result: unknown) =>
284 offerOutgoing(toProtocolMessage(requestId, { result }));
285
286 const respondError = (
287 requestId: string | number,
288 error: CodexError.CodexAppServerRequestError,
289 ) => offerOutgoing(toProtocolMessage(requestId, { error: error.toProtocolError() }));
290
291 const handleResponse = (response: typeof JsonRpcResponseEnvelope.Type) => {
292 const requestId = String(response.id);
293 const protocolError = response.error;
294 if (protocolError !== undefined) {
295 return resolvePending(requestId, ({ deferred, method }) =>
296 Deferred.fail(
297 deferred,
298 CodexError.CodexAppServerRequestError.fromProtocolError(
299 protocolError,
300 method,
301 requestId,
302 ),
303 ),
304 );
305 }
306 return resolvePending(requestId, ({ deferred }) =>
307 Deferred.succeed(deferred, response.result),
308 );
309 };
310
311 const handleRequest = (request: CodexAppServerIncomingRequest) =>
312 Queue.offer(incomingRequests, request).pipe(
313 Effect.flatMap(() => {
314 const handler = options.onRequest;
315 if (!handler) return Effect.void;
316
317 return Ref.modify(activeRequestHandlers, (count) =>
318 count >= MAX_BUFFERED_RAW_MESSAGES ? [false, count] : [true, count + 1],
319 ).pipe(
320 Effect.flatMap((accepted) => {
321 if (!accepted) {
322 return respondError(
323 request.id,
324 CodexError.CodexAppServerRequestError.overloaded(
325 "Too many Codex requests are already active.",
326 ),
327 );
328 }
329
330 return Effect.suspend(() => handler(request)).pipe(
331 // Adapter handlers end in Effect.orDie; Codex waits for an answer regardless.
332 Effect.catchDefect(() =>
333 Effect.logError("Codex request handler failed").pipe(
334 Effect.annotateLogs({
335 method:
336 request.method in CodexRpc.SERVER_REQUEST_PARAMS
337 ? request.method
338 : "unknown",
339 }),
340 Effect.andThen(
341 Effect.fail(CodexError.CodexAppServerRequestError.internalError()),
342 ),
343 ),
344 ),
345 Effect.matchEffect({
346 onFailure: (error) =>
347 respondError(
348 request.id,
349 CodexError.CodexAppServerRequestError.fromAppServerError(
350 error,
351 request.method,
352 ),
353 ),
354 onSuccess: (result) => respond(request.id, result),
355 }),
356 Effect.ensuring(
357 Ref.update(activeRequestHandlers, (count) => Math.max(0, count - 1)),
358 ),
359 Effect.catch((error) =>
360 handleTermination(() => Effect.succeed(error)).pipe(
361 Effect.forkIn(protocolScope),
362 Effect.asVoid,
363 ),
364 ),
365 FiberMap.run(requestHandlers, request.id),
366 Effect.asVoid,
367 );
368 }),
369 );
370 }),
371 Effect.asVoid,
372 );
373
374 // Codex settles requests itself when their turn ends; a handler still waiting would hold its slot.
375 const releaseResolvedRequest = (notification: CodexAppServerIncomingNotification) =>
376 notification.method === "serverRequest/resolved" &&
377 isObject(notification.params) &&
378 isJsonRpcId(notification.params.requestId)
379 ? FiberMap.remove(requestHandlers, notification.params.requestId)
380 : Effect.void;
381
382 const handleNotification = (notification: CodexAppServerIncomingNotification) =>
383 releaseResolvedRequest(notification).pipe(
384 Effect.andThen(Queue.offer(incomingNotifications, notification)),
385 Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void),
386 Effect.asVoid,
387 );
388
389 const routeMessage = Effect.fnUntraced(function* (message: unknown) {
390 if (Option.isSome(yield* Ref.get(terminationFailure))) return;
391 if (isIncomingRequest(message)) return yield* handleRequest(message);
392 if (isIncomingNotification(message)) return yield* handleNotification(message);
393 if (isIncomingResponse(message)) return yield* handleResponse(message);
394 return yield* CodexError.CodexAppServerProtocolParseError.fromUnroutableMessage(message);
395 });
396
397 const handleLine = (line: string): Effect.Effect<void, CodexError.CodexAppServerError> => {
398 if (line.trim().length === 0) {
399 return Effect.void;
400 }
401 return logProtocol({
402 direction: "incoming",
403 stage: "raw",
404 payload: line,
405 }).pipe(
406 Effect.flatMap(() => decodeWireMessage(line)),
407 Effect.tap((decoded) =>
408 logProtocol({
409 direction: "incoming",
410 stage: "decoded",
411 payload: decoded,
412 }),
413 ),
414 Effect.tapErrorTag("CodexAppServerProtocolParseError", (error) =>
415 logProtocol({
416 direction: "incoming",
417 stage: "decode_failed",
418 payload: {
419 operation: error.operation,
420 ...(error.method === undefined ? {} : { method: error.method }),
421 ...(error.requestId === undefined ? {} : { requestId: error.requestId }),
422 ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
423 ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
424 ...(error.maximumPathDepth === undefined
425 ? {}
426 : { maximumPathDepth: error.maximumPathDepth }),
427 },
428 }),
429 ),
430 Effect.flatMap(routeMessage),
431 );
432 };
433
434 yield* options.stdio.stdin.pipe(
435 Stream.interruptWhen(Deferred.await(terminationSignal)),
436 Stream.decodeText(),
437 Stream.runForEach(
438 Effect.fnUntraced(function* (chunk) {
439 let start = 0;
440 while (start < chunk.length) {
441 const newline = chunk.indexOf("\n", start);
442 const fragment = chunk.slice(start, newline === -1 ? chunk.length : newline);
443 // decodeText holds back split UTF-8 sequences, so fragment byte sums are exact.
444 remainderBytes += Buffer.byteLength(fragment, "utf8");
445 if (remainderBytes > maxIncomingMessageBytes) {
446 remainder.length = 0;
447 return yield* new CodexError.CodexAppServerTransportError({
448 operation: "read-input-stream",
449 cause: new Error(`Incoming message exceeded ${maxIncomingMessageBytes} bytes.`),
450 });
451 }
452 remainder.push(fragment);
453 if (newline === -1) break;
454 const line = remainder.join("").replace(/\r$/, "");
455 remainder.length = 0;
456 remainderBytes = 0;
457 yield* handleLine(line);
458 start = newline + 1;
459 }
460 }),
461 ),
462 Effect.matchEffect({
463 onFailure: (error) =>
464 handleTermination(() =>
465 Effect.succeed(normalizeIncomingError(error, "read-input-stream")),
466 ),
467 onSuccess: () =>
468 Effect.sync(() => {
469 const line = remainder.join("");
470 remainder.length = 0;
471 return line;
472 }).pipe(
473 Effect.flatMap(handleLine),
474 Effect.matchEffect({
475 onFailure: (error) => handleTermination(() => Effect.succeed(error)),
476 onSuccess: () =>
477 handleTermination(() => {
478 const ended = new CodexError.CodexAppServerInputStreamEndedError({});
479 // Node ends stdout before it reports the exit of a crashed process, so
480 // wait briefly for the exit status. stdout can also close while the
481 // process keeps running, so the wait must not hang pending requests.
482 return options.terminationError === undefined
483 ? Effect.succeed(ended)
484 : options.terminationError.pipe(
485 Effect.timeoutOrElse({
486 duration: EXIT_STATUS_GRACE,
487 orElse: () => Effect.succeed(ended),
488 }),
489 // A defect here would leave termination marked handled but unfinished.
490 Effect.catchDefect((cause) =>
491 Effect.succeed(
492 new CodexError.CodexAppServerTransportError({
493 operation: "read-input-stream",
494 cause,
495 }),
496 ),
497 ),
498 );
499 }),
500 }),
501 ),
502 }),
503 Effect.catchCause((cause) =>
504 handleTermination(() =>
505 Effect.succeed(
506 new CodexError.CodexAppServerTransportError({
507 operation: "read-input-stream",
508 cause: Cause.squash(cause),
509 }),
510 ),
511 ),
512 ),
513 Effect.forkScoped,
514 );
515
516 yield* Stream.fromQueue(outgoing).pipe(
517 Stream.run(options.stdio.stdout()),
518 Effect.catchCause((cause) =>
519 handleTermination(() =>
520 Effect.succeed(
521 new CodexError.CodexAppServerTransportError({
522 operation: "write-output-stream",
523 cause: Cause.squash(cause),
524 }),
525 ),
526 ),
527 ),
528 Effect.forkScoped,
529 );
530
531 const request = Effect.fn("CodexAppServerProtocol.request")(function* (
532 method: string,
533 payload?: unknown,
534 ) {
535 const requestId = yield* Ref.modify(
536 nextRequestId,
537 (current) => [current, current + 1] as const,
538 );
539 const attributes = {
540 "rpc.system": "jsonrpc",
541 "rpc.method": method,
542 "rpc.request_id": requestId,
543 };
544 yield* Effect.annotateCurrentSpan(attributes);
545 const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();
546 return yield* Effect.acquireUseRelease(
547 Ref.update(pending, (current) =>
548 new Map(current).set(String(requestId), { deferred, method }),
549 ),
550 () =>
551 Effect.gen(function* () {
552 yield* offerOutgoing({
553 id: requestId,
554 method,
555 ...(payload !== undefined ? { params: payload } : {}),
556 }).pipe(Effect.withSpan("CodexAppServerProtocol.request.enqueue", { attributes }));
557 // Includes queue/stdin delivery, Codex work and response routing, not just T3 CPU.
558 return yield* Deferred.await(deferred).pipe(
559 Effect.withSpan("CodexAppServerProtocol.request.awaitResponse", { attributes }),
560 );
561 }),
562 () => removePending(String(requestId)),
563 );
564 });
565
566 const notify = (method: string, payload?: unknown) =>
567 offerOutgoing({
568 method,
569 ...(payload !== undefined ? { params: payload } : {}),
570 });
571
572 return {
573 incomingNotifications: Stream.fromQueue(incomingNotifications),
574 incomingRequests: Stream.fromQueue(incomingRequests),
575 request,
576 notify,
577 respond,
578 respondError,
579 } satisfies CodexAppServerPatchedProtocol;
580 },
581);