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