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

client.ts

277 lines10.9 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Schema from "effect/Schema";
5import * as Scope from "effect/Scope";
6import * as Stdio from "effect/Stdio";
7import * as Stream from "effect/Stream";
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, 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>;
28 readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;
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"];
39​
40export class CodexAppServerClient extends Context.Service<
41 CodexAppServerClient,
42 {
43 readonly raw: CodexAppServerClientRaw;
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 notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();
105 let unknownRequestHandler:
106 | ((method: string, params: unknown) => Effect.Effect<unknown, CodexError.CodexAppServerError>)
107 | undefined;
108 let unknownNotificationHandler:
109 | ((method: string, params: unknown) => Effect.Effect<void, CodexError.CodexAppServerError>)
110 | undefined;
111​
112 const getServerRequestParamSchema = <M extends CodexRpc.ServerRequestMethod>(
113 method: M,
114 ):
115 | Schema.Codec<CodexRpc.ServerRequestParamsByMethod[M], CodexRpc.ServerRequestParamsByMethod[M]>
116 | undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never;
117​
118 const getServerRequestResponseSchema = <M extends CodexRpc.ServerRequestMethod>(
119 method: M,
120 ):
121 | Schema.Codec<
122 CodexRpc.ServerRequestResponsesByMethod[M],
123 CodexRpc.ServerRequestResponsesByMethod[M]
124 >
125 | undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never;
126​
127 const getClientRequestParamSchema = <M extends CodexRpc.ClientRequestMethod>(
128 method: M,
129 ):
130 | Schema.Codec<CodexRpc.ClientRequestParamsByMethod[M], CodexRpc.ClientRequestParamsByMethod[M]>
131 | undefined =>
132 method === "turn/start"
133 ? (V2TurnStartParamsWithCollaborationMode as never)
134 : (CodexRpc.CLIENT_REQUEST_PARAMS[method] as never);
135​
136 const getClientRequestResponseSchema = <M extends CodexRpc.ClientRequestMethod>(
137 method: M,
138 ):
139 | Schema.Codec<
140 CodexRpc.ClientRequestResponsesByMethod[M],
141 CodexRpc.ClientRequestResponsesByMethod[M]
142 >
143 | undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never;
144​
145 const getClientNotificationParamSchema = <M extends CodexRpc.ClientNotificationMethod>(
146 method: M,
147 ):
148 | Schema.Codec<
149 CodexRpc.ClientNotificationParamsByMethod[M],
150 CodexRpc.ClientNotificationParamsByMethod[M]
151 >
152 | undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never;
153​
154 const dispatchNotification = (
155 notification: CodexProtocol.CodexAppServerIncomingNotification,
156 ): Effect.Effect<void, never> => {
157 const schema =
158 notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS
159 ? CodexRpc.SERVER_NOTIFICATION_PARAMS[
160 notification.method as CodexRpc.ServerNotificationMethod
161 ]
162 : undefined;
163 const handlers = notificationHandlers.get(notification.method) ?? [];
164​
165 if (schema) {
166 return decodeNotificationPayload(notification.method, schema, notification.params).pipe(
167 Effect.flatMap((decoded) =>
168 Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),
169 ),
170 Effect.ignore,
171 );
172 }
173​
174 return unknownNotificationHandler
175 ? unknownNotificationHandler(notification.method, notification.params).pipe(Effect.ignore)
176 : Effect.void;
177 };
178​
179 const dispatchRequest = (
180 request: CodexProtocol.CodexAppServerIncomingRequest,
181 ): Effect.Effect<unknown, CodexError.CodexAppServerError> => {
182 if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {
183 const method = request.method as CodexRpc.ServerRequestMethod;
184 const payloadSchema = getServerRequestParamSchema(method);
185 const responseSchema = getServerRequestResponseSchema(method);
186 const handler = requestHandlers.get(method);
187​
188 return decodeOptionalPayload(method, payloadSchema, request.params).pipe(
189 Effect.flatMap((decoded) => runHandler(handler, decoded, method)),
190 Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),
191 );
192 }
193​
194 return unknownRequestHandler
195 ? unknownRequestHandler(request.method, request.params)
196 : Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));
197 };
198​
199 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
200 stdio,
201 ...(terminationError ? { terminationError } : {}),
202 ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
203 ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
204 ...(options.logger ? { logger: options.logger } : {}),
205 ...(options.onTermination ? { onTermination: options.onTermination } : {}),
206 onNotification: dispatchNotification,
207 onRequest: dispatchRequest,
208 });
209​
210 const request = <M extends CodexRpc.ClientRequestMethod>(
211 method: M,
212 payload: CodexRpc.ClientRequestParamsByMethod[M],
213 ): Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError> =>
214 encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(
215 Effect.flatMap((encoded) => transport.request(method, encoded)),
216 Effect.flatMap(
217 (
218 raw,
219 ): Effect.Effect<
220 CodexRpc.ClientRequestResponsesByMethod[M],
221 CodexError.CodexAppServerError
222 > => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),
223 ),
224 );
225​
226 const notify = <M extends CodexRpc.ClientNotificationMethod>(
227 method: M,
228 payload: CodexRpc.ClientNotificationParamsByMethod[M],
229 ) =>
230 encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe(
231 Effect.flatMap((encoded) => transport.notify(method, encoded)),
232 );
233​
234 return CodexAppServerClient.of({
235 raw: {
236 notifications: transport.incomingNotifications,
237 requests: transport.incomingRequests,
238 request: transport.request,
239 notify: transport.notify,
240 respond: transport.respond,
241 respondError: transport.respondError,
242 },
243 request,
244 notify,
245 handleServerRequest: (method, handler) =>
246 Effect.sync(() => {
247 requestHandlers.set(method, handler as ServerRequestHandler);
248 }),
249 handleServerNotification: (method, handler) =>
250 Effect.sync(() => {
251 const current = notificationHandlers.get(method) ?? [];
252 current.push(handler as ServerNotificationHandler);
253 notificationHandlers.set(method, current);
254 }),
255 handleUnknownServerRequest: (handler) =>
256 Effect.sync(() => {
257 unknownRequestHandler = handler;
258 }),
259 handleUnknownServerNotification: (handler) =>
260 Effect.sync(() => {
261 unknownNotificationHandler = handler;
262 }),
263 });
264});
265​
266export const layerChildProcess = (
267 handle: ChildProcessSpawner.ChildProcessHandle,
268 options: CodexAppServerClientOptions = {},
269): Layer.Layer<CodexAppServerClient> =>
270 Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options));
271​
272const makeChildProcessClient = Effect.fn(
273 "effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",
274)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {
275 yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);
276 return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
277});