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