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

client.ts

274 lines10.6 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/unstable/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>;
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 request: <M extends CodexRpc.ClientRequestMethod>(
44 method: M,
45 payload: CodexRpc.ClientRequestParamsByMethod[M],
46 ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;
47 readonly notify: <M extends CodexRpc.ClientNotificationMethod>(
48 method: M,
49 payload: CodexRpc.ClientNotificationParamsByMethod[M],
50 ) => Effect.Effect<void, CodexError.CodexAppServerError>;
51 readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(
52 method: M,
53 handler: (
54 payload: CodexRpc.ServerRequestParamsByMethod[M],
55 ) => Effect.Effect<
56 CodexRpc.ServerRequestResponsesByMethod[M],
57 CodexError.CodexAppServerError
58 >,
59 ) => Effect.Effect<void>;
60 readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(
61 method: M,
62 handler: (
63 payload: CodexRpc.ServerNotificationParamsByMethod[M],
64 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
65 ) => Effect.Effect<void>;
66 readonly handleUnknownServerRequest: (
67 handler: (
68 method: string,
69 params: unknown,
70 ) => Effect.Effect<unknown, CodexError.CodexAppServerError>,
71 ) => Effect.Effect<void>;
72 readonly handleUnknownServerNotification: (
73 handler: (
74 method: string,
75 params: unknown,
76 ) => Effect.Effect<void, CodexError.CodexAppServerError>,
77 ) => Effect.Effect<void>;
78 }
79>()("effect-codex-app-server/client/CodexAppServerClient") {}
80​
81type ServerRequestHandler = (
82 payload: unknown,
83) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
84type ServerNotificationHandler = (
85 payload: unknown,
86) => Effect.Effect<void, CodexError.CodexAppServerError>;
87​
88const V2TurnStartParamsWithCollaborationMode = CodexSchema.V2TurnStartParams.pipe(
89 Schema.fieldsAssign({
90 collaborationMode: Schema.optionalKey(CodexSchema.ClientRequest__CollaborationMode),
91 }),
92);
93​
94export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make")(function* (
95 stdio: Stdio.Stdio,
96 options: CodexAppServerClientOptions = {},
97 terminationError?: Effect.Effect<CodexError.CodexAppServerError>,
98): Effect.fn.Return<CodexAppServerClient["Service"], never, Scope.Scope> {
99 const requestHandlers = new Map<string, ServerRequestHandler>();
100 const notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();
101 let unknownRequestHandler:
102 | ((method: string, params: unknown) => Effect.Effect<unknown, CodexError.CodexAppServerError>)
103 | undefined;
104 let unknownNotificationHandler:
105 | ((method: string, params: unknown) => Effect.Effect<void, CodexError.CodexAppServerError>)
106 | undefined;
107​
108 const getServerRequestParamSchema = <M extends CodexRpc.ServerRequestMethod>(
109 method: M,
110 ):
111 | Schema.Codec<CodexRpc.ServerRequestParamsByMethod[M], CodexRpc.ServerRequestParamsByMethod[M]>
112 | undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never;
113​
114 const getServerRequestResponseSchema = <M extends CodexRpc.ServerRequestMethod>(
115 method: M,
116 ):
117 | Schema.Codec<
118 CodexRpc.ServerRequestResponsesByMethod[M],
119 CodexRpc.ServerRequestResponsesByMethod[M]
120 >
121 | undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never;
122​
123 const getClientRequestParamSchema = <M extends CodexRpc.ClientRequestMethod>(
124 method: M,
125 ):
126 | Schema.Codec<CodexRpc.ClientRequestParamsByMethod[M], CodexRpc.ClientRequestParamsByMethod[M]>
127 | undefined =>
128 method === "turn/start"
129 ? (V2TurnStartParamsWithCollaborationMode as never)
130 : (CodexRpc.CLIENT_REQUEST_PARAMS[method] as never);
131​
132 const getClientRequestResponseSchema = <M extends CodexRpc.ClientRequestMethod>(
133 method: M,
134 ):
135 | Schema.Codec<
136 CodexRpc.ClientRequestResponsesByMethod[M],
137 CodexRpc.ClientRequestResponsesByMethod[M]
138 >
139 | undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never;
140​
141 const getClientNotificationParamSchema = <M extends CodexRpc.ClientNotificationMethod>(
142 method: M,
143 ):
144 | Schema.Codec<
145 CodexRpc.ClientNotificationParamsByMethod[M],
146 CodexRpc.ClientNotificationParamsByMethod[M]
147 >
148 | undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never;
149​
150 const dispatchNotification = (
151 notification: CodexProtocol.CodexAppServerIncomingNotification,
152 ): Effect.Effect<void, never> => {
153 const schema =
154 notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS
155 ? CodexRpc.SERVER_NOTIFICATION_PARAMS[
156 notification.method as CodexRpc.ServerNotificationMethod
157 ]
158 : undefined;
159 const handlers = notificationHandlers.get(notification.method) ?? [];
160​
161 if (schema) {
162 return decodeNotificationPayload(notification.method, schema, notification.params).pipe(
163 Effect.flatMap((decoded) =>
164 Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),
165 ),
166 Effect.catch(() => Effect.void),
167 );
168 }
169​
170 return unknownNotificationHandler
171 ? unknownNotificationHandler(notification.method, notification.params).pipe(
172 Effect.catch(() => Effect.void),
173 )
174 : Effect.void;
175 };
176​
177 const dispatchRequest = (
178 request: CodexProtocol.CodexAppServerIncomingRequest,
179 ): Effect.Effect<unknown, CodexError.CodexAppServerError> => {
180 if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {
181 const method = request.method as CodexRpc.ServerRequestMethod;
182 const payloadSchema = getServerRequestParamSchema(method);
183 const responseSchema = getServerRequestResponseSchema(method);
184 const handler = requestHandlers.get(method);
185​
186 return decodeOptionalPayload(method, payloadSchema, request.params).pipe(
187 Effect.flatMap((decoded) => runHandler(handler, decoded, method)),
188 Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),
189 );
190 }
191​
192 return unknownRequestHandler
193 ? unknownRequestHandler(request.method, request.params)
194 : Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));
195 };
196​
197 const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
198 stdio,
199 ...(terminationError ? { terminationError } : {}),
200 ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
201 ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
202 ...(options.logger ? { logger: options.logger } : {}),
203 onNotification: dispatchNotification,
204 onRequest: dispatchRequest,
205 });
206​
207 const request = <M extends CodexRpc.ClientRequestMethod>(
208 method: M,
209 payload: CodexRpc.ClientRequestParamsByMethod[M],
210 ): Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError> =>
211 encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(
212 Effect.flatMap((encoded) => transport.request(method, encoded)),
213 Effect.flatMap(
214 (
215 raw,
216 ): Effect.Effect<
217 CodexRpc.ClientRequestResponsesByMethod[M],
218 CodexError.CodexAppServerError
219 > => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),
220 ),
221 );
222​
223 const notify = <M extends CodexRpc.ClientNotificationMethod>(
224 method: M,
225 payload: CodexRpc.ClientNotificationParamsByMethod[M],
226 ) =>
227 encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe(
228 Effect.flatMap((encoded) => transport.notify(method, encoded)),
229 );
230​
231 return CodexAppServerClient.of({
232 raw: {
233 notifications: transport.incomingNotifications,
234 requests: transport.incomingRequests,
235 request: transport.request,
236 notify: transport.notify,
237 respond: transport.respond,
238 respondError: transport.respondError,
239 },
240 request,
241 notify,
242 handleServerRequest: (method, handler) =>
243 Effect.sync(() => {
244 requestHandlers.set(method, handler as ServerRequestHandler);
245 }),
246 handleServerNotification: (method, handler) =>
247 Effect.sync(() => {
248 const current = notificationHandlers.get(method) ?? [];
249 current.push(handler as ServerNotificationHandler);
250 notificationHandlers.set(method, current);
251 }),
252 handleUnknownServerRequest: (handler) =>
253 Effect.sync(() => {
254 unknownRequestHandler = handler;
255 }),
256 handleUnknownServerNotification: (handler) =>
257 Effect.sync(() => {
258 unknownNotificationHandler = handler;
259 }),
260 });
261});
262​
263export const layerChildProcess = (
264 handle: ChildProcessSpawner.ChildProcessHandle,
265 options: CodexAppServerClientOptions = {},
266): Layer.Layer<CodexAppServerClient> =>
267 Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options));
268​
269const makeChildProcessClient = Effect.fn(
270 "effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",
271)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {
272 yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);
273 return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
274});