Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Schema from "effect/Schema";
6import * as Scope from "effect/Scope";
7import * as Stdio from "effect/Stdio";
8import * as Stream from "effect/Stream";
9import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
10
11import * as CodexRpc from "./_generated/meta.gen.ts";
12import * as CodexSchema from "./_generated/schema.gen.ts";
13import * as CodexError from "./errors.ts";
14import * as CodexProtocol from "./protocol.ts";
15import {
16 decodeNotificationPayload,
17 decodeOptionalPayload,
18 encodeOptionalPayload,
19 runHandler,
20} from "./_internal/shared.ts";
21import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
22
23export interface CodexAppServerClientOptions {
24 readonly logIncoming?: boolean;
25 readonly logOutgoing?: boolean;
26 readonly logger?: (
27 event: CodexProtocol.CodexAppServerProtocolLogEvent,
28 ) => Effect.Effect<void, never>;
29}
30
31interface CodexAppServerClientRaw {
32 readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol["incomingNotifications"];
33 readonly requests: CodexProtocol.CodexAppServerPatchedProtocol["incomingRequests"];
34 readonly request: CodexProtocol.CodexAppServerPatchedProtocol["request"];
35 readonly notify: CodexProtocol.CodexAppServerPatchedProtocol["notify"];
36 readonly respond: CodexProtocol.CodexAppServerPatchedProtocol["respond"];
37 readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol["respondError"];
38}
39
40export class CodexAppServerClient extends Context.Service<
41 CodexAppServerClient,
42 {
43 readonly raw: CodexAppServerClientRaw;
44 readonly awaitTermination: Effect.Effect<never, CodexError.CodexAppServerError>;
45 readonly request: <M extends CodexRpc.ClientRequestMethod>(
46 method: M,
47 payload: CodexRpc.ClientRequestParamsByMethod[M],
48 ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;
49 readonly notify: <M extends CodexRpc.ClientNotificationMethod>(
50 method: M,
51 payload: CodexRpc.ClientNotificationParamsByMethod[M],
52 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
53 readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(
54 method: M,
55 handler: (
56 payload: CodexRpc.ServerRequestParamsByMethod[M],
57 ) => Effect.Effect<
58 CodexRpc.ServerRequestResponsesByMethod[M],
59 CodexError.CodexAppServerError
60 >,
61 ) => Effect.Effect<void>;
62 readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(
63 method: M,
64 handler: (
65 payload: CodexRpc.ServerNotificationParamsByMethod[M],
66 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
67 ) => Effect.Effect<void>;
68 readonly handleUnknownServerRequest: (
69 handler: (
70 method: string,
71 params: unknown,
72 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>,
73 ) => Effect.Effect<void>;
74 readonly handleUnknownServerNotification: (
75 handler: (
76 method: string,
77 params: unknown,
78 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
79 ) => Effect.Effect<void>;
80 }
81>()("effect-codex-app-server/client/CodexAppServerClient") {}
82
83type ServerRequestHandler = (
84 payload: unknown,
85) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
86type ServerNotificationHandler = (
87 payload: unknown,
88) => Effect.Effect<void, CodexError.CodexAppServerError>;
89
90const V2TurnStartParamsWithCollaborationMode = CodexSchema.V2TurnStartParams.pipe(
91 Schema.fieldsAssign({
92 collaborationMode: Schema.optionalKey(CodexSchema.ClientRequest__CollaborationMode),
93 additionalContext: Schema.optionalKey(
94 Schema.Record(Schema.String, CodexSchema.V2TurnStartParams__AdditionalContextEntry),
95 ),
96 }),
97);
98
99export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make")(function* (
100 stdio: Stdio.Stdio,
101 options: CodexAppServerClientOptions = {},
102 terminationError?: Effect.Effect<CodexError.CodexAppServerError>,
103): Effect.fn.Return<CodexAppServerClient["Service"], never, Scope.Scope> {
104 const requestHandlers = new Map<string, ServerRequestHandler>();
105 const termination = yield* Deferred.make<never, CodexError.CodexAppServerError>();
106 const notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();
107 let unknownRequestHandler:
108 | ((method: string, params: unknown) => Effect.Effect<unknown, CodexError.CodexAppServerError>)
109 | undefined;
110 let unknownNotificationHandler:
111 | ((method: string, params: unknown) => Effect.Effect<void, CodexError.CodexAppServerError>)
112 | undefined;
113
114 const getServerRequestParamSchema = <M extends CodexRpc.ServerRequestMethod>(
115 method: M,
116 ):
117 | Schema.Codec<CodexRpc.ServerRequestParamsByMethod[M], CodexRpc.ServerRequestParamsByMethod[M]>
118 | undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never;
119
120 const getServerRequestResponseSchema = <M extends CodexRpc.ServerRequestMethod>(
121 method: M,
122 ):
123 | Schema.Codec<
124 CodexRpc.ServerRequestResponsesByMethod[M],
125 CodexRpc.ServerRequestResponsesByMethod[M]
126 >
127 | undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never;
128
129 const getClientRequestParamSchema = <M extends CodexRpc.ClientRequestMethod>(
130 method: M,
131 ):
132 | Schema.Codec<CodexRpc.ClientRequestParamsByMethod[M], CodexRpc.ClientRequestParamsByMethod[M]>
133 | undefined =>
134 method === "turn/start"
135 ? (V2TurnStartParamsWithCollaborationMode as never)
136 : (CodexRpc.CLIENT_REQUEST_PARAMS[method] as never);
137
138 const getClientRequestResponseSchema = <M extends CodexRpc.ClientRequestMethod>(
139 method: M,
140 ):
141 | Schema.Codec<
142 CodexRpc.ClientRequestResponsesByMethod[M],
143 CodexRpc.ClientRequestResponsesByMethod[M]
144 >
145 | undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never;
146
147 const getClientNotificationParamSchema = <M extends CodexRpc.ClientNotificationMethod>(
148 method: M,
149 ):
150 | Schema.Codec<
151 CodexRpc.ClientNotificationParamsByMethod[M],
152 CodexRpc.ClientNotificationParamsByMethod[M]
153 >
154 | undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never;
155
156 const dispatchNotification = (
157 notification: CodexProtocol.CodexAppServerIncomingNotification,
158 ): Effect.Effect<void, never> => {
159 const schema =
160 notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS
161 ? CodexRpc.SERVER_NOTIFICATION_PARAMS[
162 notification.method as CodexRpc.ServerNotificationMethod
163 ]
164 : undefined;
165 const handlers = notificationHandlers.get(notification.method) ?? [];
166
167 if (schema) {
168 return decodeNotificationPayload(notification.method, schema, notification.params).pipe(
169 Effect.flatMap((decoded) =>
170 Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),
171 ),
172 Effect.ignore,
173 );
174 }
175
176 return unknownNotificationHandler
177 ? unknownNotificationHandler(notification.method, notification.params).pipe(Effect.ignore)
178 : Effect.void;
179 };
180
181 const dispatchRequest = (
182 request: CodexProtocol.CodexAppServerIncomingRequest,
183 ): Effect.Effect<unknown, CodexError.CodexAppServerError> => {
184 if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {
185 const method = request.method as CodexRpc.ServerRequestMethod;
186 const payloadSchema = getServerRequestParamSchema(method);
187 const responseSchema = getServerRequestResponseSchema(method);
188 const handler = requestHandlers.get(method);
189
190 return decodeOptionalPayload(method, payloadSchema, request.params).pipe(
191 Effect.flatMap((decoded) => runHandler(handler, decoded, method)),
192 Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),
193 );
194 }
195
196 return unknownRequestHandler
197 ? unknownRequestHandler(request.method, request.params)
198 : Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));
199 };
200
201 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
202 stdio,
203 ...(terminationError ? { terminationError } : {}),
204 ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
205 ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
206 ...(options.logger ? { logger: options.logger } : {}),
207 onNotification: dispatchNotification,
208 onRequest: dispatchRequest,
209 onTermination: (error) => Deferred.fail(termination, error).pipe(Effect.asVoid),
210 });
211
212 const request = <M extends CodexRpc.ClientRequestMethod>(
213 method: M,
214 payload: CodexRpc.ClientRequestParamsByMethod[M],
215 ): Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError> =>
216 encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(
217 Effect.flatMap((encoded) => transport.request(method, encoded)),
218 Effect.flatMap(
219 (
220 raw,
221 ): Effect.Effect<
222 CodexRpc.ClientRequestResponsesByMethod[M],
223 CodexError.CodexAppServerError
224 > => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),
225 ),
226 );
227
228 const notify = <M extends CodexRpc.ClientNotificationMethod>(
229 method: M,
230 payload: CodexRpc.ClientNotificationParamsByMethod[M],
231 ) =>
232 encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe(
233 Effect.flatMap((encoded) => transport.notify(method, encoded)),
234 );
235
236 return CodexAppServerClient.of({
237 awaitTermination: Deferred.await(termination),
238 raw: {
239 notifications: transport.incomingNotifications,
240 requests: transport.incomingRequests,
241 request: transport.request,
242 notify: transport.notify,
243 respond: transport.respond,
244 respondError: transport.respondError,
245 },
246 request,
247 notify,
248 handleServerRequest: Effect.fn("CodexAppServerClient.handleServerRequest")(
249 function (method, handler) {
250 return Effect.sync(() => {
251 requestHandlers.set(method, handler as ServerRequestHandler);
252 });
253 },
254 ),
255 handleServerNotification: Effect.fn("CodexAppServerClient.handleServerNotification")(
256 function (method, handler) {
257 return Effect.sync(() => {
258 const current = notificationHandlers.get(method) ?? [];
259 current.push(handler as ServerNotificationHandler);
260 notificationHandlers.set(method, current);
261 });
262 },
263 ),
264 handleUnknownServerRequest: Effect.fn("CodexAppServerClient.handleUnknownServerRequest")(
265 function (handler) {
266 return Effect.sync(() => {
267 unknownRequestHandler = handler;
268 });
269 },
270 ),
271 handleUnknownServerNotification: Effect.fn(
272 "CodexAppServerClient.handleUnknownServerNotification",
273 )(function (handler) {
274 return Effect.sync(() => {
275 unknownNotificationHandler = handler;
276 });
277 }),
278 });
279});
280
281export const layerChildProcess = (
282 handle: ChildProcessSpawner.ChildProcessHandle,
283 options: CodexAppServerClientOptions = {},
284): Layer.Layer<CodexAppServerClient> =>
285 Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options));
286
287const makeChildProcessClient = Effect.fn(
288 "effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",
289)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {
290 yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);
291 return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
292});