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