Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

client.ts

319 lines12.6 KB

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