Open History to see the last commit
1#!/usr/bin/env node
2
3import { pipe } from "effect/Function";
4import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Logger from "effect/Logger";
11import * as Path from "effect/Path";
12import * as Schema from "effect/Schema";
13import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
14import { ChildProcess, ChildProcessSpawner } from "effect/process";
15
16const UPSTREAM_REF = "687a119f0fcaace47e1f1abcc77cec6c813fd6da";
17const USER_AGENT = "effect-codex-app-server-generator";
18const GITHUB_API_BASE =
19 "https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol";
20
21const GithubContentEntries = Schema.Array(
22 Schema.Struct({
23 name: Schema.String,
24 path: Schema.String,
25 download_url: Schema.NullOr(Schema.String),
26 type: Schema.String,
27 }),
28);
29type GithubContentEntry = (typeof GithubContentEntries.Type)[number];
30
31const JsonSchemaDocument = Schema.StructWithRest(
32 Schema.Struct({
33 definitions: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),
34 }),
35 [Schema.Record(Schema.String, Schema.Json)],
36);
37const decodeGithubContentEntries = Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries));
38const decodeJsonSchemaDocument = Schema.decodeEffect(Schema.fromJsonString(JsonSchemaDocument));
39
40interface GeneratedPaths {
41 readonly generatedDir: string;
42 readonly schemaOutputPath: string;
43 readonly metaOutputPath: string;
44 readonly namespacesOutputPath: string;
45}
46
47interface MethodEntry {
48 readonly method: string;
49 readonly paramsType?: string;
50}
51
52interface JsonSchemaFile {
53 readonly namespace?: string;
54 readonly exportName: string;
55 readonly fileName: string;
56 readonly downloadUrl: string;
57 readonly qualifiedName: string;
58}
59
60class GeneratorError extends Schema.TaggedError<GeneratorError>()("GeneratorError", {
61 detail: Schema.String,
62 cause: Schema.optional(Schema.Defect()),
63}) {
64 override get message() {
65 return this.detail;
66 }
67}
68
69const ManualSchemas: Record<string, Schema.Json> = {
70 GetAuthStatusParams: {
71 type: "object",
72 title: "GetAuthStatusParams",
73 properties: {
74 includeToken: {
75 anyOf: [{ type: "boolean" }, { type: "null" }],
76 },
77 refreshToken: {
78 anyOf: [{ type: "boolean" }, { type: "null" }],
79 },
80 },
81 },
82 GetConversationSummaryParams: {
83 title: "GetConversationSummaryParams",
84 oneOf: [
85 {
86 type: "object",
87 properties: {
88 rolloutPath: { type: "string" },
89 },
90 required: ["rolloutPath"],
91 },
92 {
93 type: "object",
94 properties: {
95 conversationId: { type: "string" },
96 },
97 required: ["conversationId"],
98 },
99 ],
100 },
101 GetConversationSummaryResponse: {
102 type: "object",
103 title: "GetConversationSummaryResponse",
104 properties: {
105 summary: {},
106 },
107 required: ["summary"],
108 },
109 GitDiffToRemoteParams: {
110 type: "object",
111 title: "GitDiffToRemoteParams",
112 properties: {
113 cwd: { type: "string" },
114 },
115 required: ["cwd"],
116 },
117 GitDiffToRemoteResponse: {
118 type: "object",
119 title: "GitDiffToRemoteResponse",
120 properties: {
121 sha: { type: "string" },
122 diff: { type: "string" },
123 },
124 required: ["sha", "diff"],
125 },
126 GetAuthStatusResponse: {
127 type: "object",
128 title: "GetAuthStatusResponse",
129 properties: {
130 authMethod: {
131 anyOf: [{}, { type: "null" }],
132 },
133 authToken: {
134 anyOf: [{ type: "string" }, { type: "null" }],
135 },
136 requiresOpenaiAuth: {
137 anyOf: [{ type: "boolean" }, { type: "null" }],
138 },
139 },
140 required: ["authMethod", "authToken", "requiresOpenaiAuth"],
141 },
142};
143
144// T3 Code only uses the plan for labels, so an unknown slug must not fail the whole
145// `account/read` decode and take the provider down with it.
146const DefinitionOverrides: Record<string, Schema.Json> = {
147 PlanType: { type: "string" },
148};
149
150const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
151 const path = yield* Path.Path;
152 const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
153 return {
154 generatedDir,
155 schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
156 metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
157 namespacesOutputPath: path.join(generatedDir, "namespaces.gen.ts"),
158 } satisfies GeneratedPaths;
159});
160
161const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
162 const fs = yield* FileSystem.FileSystem;
163 const { generatedDir } = yield* getGeneratedPaths();
164 yield* fs.makeDirectory(generatedDir, { recursive: true });
165});
166
167const fetchText = Effect.fn("fetchText")(function* (url: string) {
168 const token = process.env.GITHUB_TOKEN;
169 return yield* HttpClientRequest.get(url).pipe(
170 HttpClientRequest.setHeader("user-agent", USER_AGENT),
171 token && url.startsWith("https://api.github.com/")
172 ? HttpClientRequest.bearerToken(token)
173 : (request) => request,
174 HttpClient.execute,
175 Effect.flatMap(HttpClientResponse.filterStatusOk),
176 Effect.flatMap((okResponse) => okResponse.text),
177 Effect.mapError(
178 (cause) =>
179 new GeneratorError({
180 detail: `Failed to fetch ${url}`,
181 cause,
182 }),
183 ),
184 );
185});
186
187const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) {
188 const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`);
189 return yield* decodeGithubContentEntries(raw);
190});
191
192function collectSchemaEntries(
193 chunk: string,
194): ReadonlyArray<{ readonly name: string; readonly code: string }> {
195 const lines = chunk
196 .split("\n")
197 .map((line) => line.trim())
198 .filter((line) => line.length > 0 && !line.startsWith("//"));
199 const entries: Array<{ name: string; code: string }> = [];
200
201 for (let index = 0; index < lines.length; index += 1) {
202 const typeLine = lines[index];
203 if (!typeLine?.startsWith("export type ")) {
204 continue;
205 }
206
207 const constLine = lines[index + 1];
208 if (!constLine?.startsWith("export const ")) {
209 throw new Error(`Malformed generator output near: ${typeLine}`);
210 }
211
212 const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
213 if (!match?.[1]) {
214 throw new Error(`Could not extract schema name from: ${typeLine}`);
215 }
216
217 entries.push({
218 name: match[1],
219 code: `${typeLine}\n${constLine}`,
220 });
221 index += 1;
222 }
223
224 return entries;
225}
226
227function normalizeNullableTypes(value: Schema.Json): Schema.Json {
228 if (Array.isArray(value)) {
229 return value.map(normalizeNullableTypes);
230 }
231 if (value === null || typeof value !== "object") {
232 return value;
233 }
234
235 const normalizedEntries = Object.entries(value).map(([key, child]) => [
236 key,
237 normalizeNullableTypes(child),
238 ]);
239 const normalizedObject = Object.fromEntries(normalizedEntries) as Record<string, Schema.Json>;
240 const typeValue = normalizedObject.type;
241
242 if (!Array.isArray(typeValue)) {
243 return normalizedObject;
244 }
245
246 const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
247 if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
248 return normalizedObject;
249 }
250
251 const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
252 if (nonNullTypes.length !== 1) {
253 return normalizedObject;
254 }
255 const nonNullType = nonNullTypes[0]!;
256
257 const nextObject: Record<string, Schema.Json> = {};
258 for (const [key, child] of Object.entries(normalizedObject)) {
259 if (key !== "type") {
260 nextObject[key] = child;
261 }
262 }
263
264 return {
265 anyOf: [
266 {
267 ...nextObject,
268 type: nonNullType,
269 },
270 { type: "null" },
271 ],
272 };
273}
274
275function stripNullDefaults(value: Schema.Json): Schema.Json {
276 if (Array.isArray(value)) {
277 return value.map(stripNullDefaults);
278 }
279 if (value === null || typeof value !== "object") {
280 return value;
281 }
282
283 return Object.fromEntries(
284 Object.entries(value)
285 .filter(([key, child]) => !(key === "default" && child === null))
286 .map(([key, child]) => [key, stripNullDefaults(child)]),
287 ) as Schema.Json;
288}
289
290type JsonSchemaNode = { readonly [key: string]: Schema.Json };
291
292function isJsonSchemaNode(value: Schema.Json | undefined): value is JsonSchemaNode {
293 return value !== null && typeof value === "object" && !Array.isArray(value);
294}
295
296// Visit only schema positions so fields literally named properties stay untouched.
297// Close Codex structs that omit additionalProperties; Effect otherwise imports open records.
298// Fold shared fields into each object alternative because Effect cannot intersect them.
299function adaptSchemaForEffect(value: Schema.Json): Schema.Json {
300 if (!isJsonSchemaNode(value)) {
301 return value;
302 }
303 const node: Record<string, Schema.Json> = { ...value };
304 for (const key of ["items", "additionalProperties"]) {
305 const child = node[key];
306 if (isJsonSchemaNode(child)) node[key] = adaptSchemaForEffect(child);
307 }
308 for (const key of ["anyOf", "oneOf", "allOf"]) {
309 const child = node[key];
310 if (Array.isArray(child)) node[key] = child.map(adaptSchemaForEffect);
311 }
312 for (const key of ["properties", "definitions"]) {
313 const child = node[key];
314 if (isJsonSchemaNode(child)) {
315 node[key] = Object.fromEntries(
316 Object.entries(child).map(([name, schema]) => [name, adaptSchemaForEffect(schema)]),
317 );
318 }
319 }
320
321 const { properties } = node;
322 if (
323 isJsonSchemaNode(properties) &&
324 Object.keys(properties).length > 0 &&
325 !("additionalProperties" in node)
326 ) {
327 node.additionalProperties = false;
328 }
329
330 const alternativesKey = "anyOf" in node ? "anyOf" : "oneOf";
331 const alternatives = node[alternativesKey];
332 if (
333 !isJsonSchemaNode(properties) ||
334 !Array.isArray(alternatives) ||
335 !alternatives.every(
336 (alternative) => isJsonSchemaNode(alternative) && alternative.type === "object",
337 )
338 ) {
339 return node;
340 }
341 const {
342 properties: _shared,
343 required,
344 type: _type,
345 additionalProperties: _closed,
346 ...rest
347 } = node;
348 const sharedRequired = Array.isArray(required) ? required : [];
349 return {
350 ...rest,
351 [alternativesKey]: alternatives.map((alternative) => {
352 const branch = alternative as JsonSchemaNode;
353 const branchProperties = isJsonSchemaNode(branch.properties) ? branch.properties : {};
354 const branchRequired = Array.isArray(branch.required) ? branch.required : [];
355 return {
356 ...branch,
357 properties: { ...properties, ...branchProperties },
358 required: [...new Set([...sharedRequired, ...branchRequired])],
359 };
360 }),
361 };
362}
363
364function toPascalCaseMethod(method: string) {
365 return method
366 .split("/")
367 .flatMap((segment) => segment.split(/(?=[A-Z])/))
368 .flatMap((segment) => segment.split(/[-_]/))
369 .filter(Boolean)
370 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
371 .join("");
372}
373
374function parseRequestEntries(fileContents: string): ReadonlyArray<MethodEntry> {
375 const entryPattern = /\{\s*"method":\s*"([^"]+)",\s*id:\s*RequestId,\s*params(\??):\s*([^,}|]+)/g;
376 const entries: Array<MethodEntry> = [];
377 let match: RegExpExecArray | null;
378 while ((match = entryPattern.exec(fileContents)) !== null) {
379 entries.push({
380 method: match[1]!,
381 paramsType: `${match[2] ? "Nullable" : ""}${match[3]!.trim()}`,
382 });
383 }
384 return entries;
385}
386
387function parseNotificationEntries(fileContents: string): ReadonlyArray<MethodEntry> {
388 const entryPattern = /\{\s*"method":\s*"([^"]+)"(?:,\s*"params":\s*([^ }]+))?\s*\}/g;
389 const entries: Array<MethodEntry> = [];
390 let match: RegExpExecArray | null;
391 while ((match = entryPattern.exec(fileContents)) !== null) {
392 entries.push({
393 method: match[1]!,
394 ...(match[2] ? { paramsType: match[2].trim() } : {}),
395 });
396 }
397 return entries;
398}
399
400function resolveSchemaTypeName(
401 rawTypeName: string,
402 generatedSchemaNames: ReadonlySet<string>,
403): string {
404 if (rawTypeName === "undefined") {
405 return "undefined";
406 }
407
408 const candidates = [
409 rawTypeName,
410 `V2${rawTypeName}`,
411 `V1${rawTypeName}`,
412 `SerdeJson${rawTypeName}`,
413 ];
414 for (const candidate of candidates) {
415 if (generatedSchemaNames.has(candidate)) {
416 return candidate;
417 }
418 }
419
420 throw new Error(`Unable to resolve schema type name: ${rawTypeName}`);
421}
422
423function resolveResponseTypeName(
424 method: string,
425 paramsType: string | undefined,
426 generatedSchemaNames: ReadonlySet<string>,
427): string {
428 const overrides: Record<string, string> = {
429 "account/gatewayOAuth/cancel": "GatewayOAuthCancelResponse",
430 "account/gatewayOAuth/login": "GatewayOAuthLoginResponse",
431 "account/gatewayOAuth/read": "GatewayOAuthReadResponse",
432 "account/logout": "LogoutAccountResponse",
433 "account/rateLimits/read": "GetAccountRateLimitsResponse",
434 "account/usage/read": "GetAccountTokenUsageResponse",
435 "account/workspaceMessages/read": "GetWorkspaceMessagesResponse",
436 "config/batchWrite": "ConfigWriteResponse",
437 "config/mcpServer/reload": "McpServerRefreshResponse",
438 "config/value/write": "ConfigWriteResponse",
439 "configRequirements/read": "ConfigRequirementsReadResponse",
440 "externalAgentConfig/import/readHistories": "ExternalAgentConfigImportHistoriesReadResponse",
441 };
442
443 const override = overrides[method];
444 if (override) {
445 return resolveSchemaTypeName(override, generatedSchemaNames);
446 }
447
448 if (paramsType && paramsType !== "undefined") {
449 const fromParams = paramsType.replace(/Params$/, "Response");
450 try {
451 return resolveSchemaTypeName(fromParams, generatedSchemaNames);
452 } catch {}
453 }
454
455 return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames);
456}
457
458function renderMethodConstants(constantName: string, entries: ReadonlyArray<MethodEntry>) {
459 return [
460 `export const ${constantName} = {`,
461 ...entries.map(
462 (entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`,
463 ),
464 "} as const;",
465 "",
466 ].join("\n");
467}
468
469function renderTypeInterface(
470 interfaceName: string,
471 entries: ReadonlyArray<MethodEntry>,
472 typeName: (entry: MethodEntry) => string,
473) {
474 return [
475 `export interface ${interfaceName} {`,
476 ...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`),
477 "}",
478 "",
479 ].join("\n");
480}
481
482function renderSchemaMap(
483 constantName: string,
484 entries: ReadonlyArray<MethodEntry>,
485 typeName: (entry: MethodEntry) => string,
486) {
487 return [
488 `export const ${constantName} = {`,
489 ...entries.map((entry) => {
490 const schemaName = typeName(entry);
491 return ` ${JSON.stringify(entry.method)}: ${
492 schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`
493 },`;
494 }),
495 "} as const;",
496 "",
497 ].join("\n");
498}
499
500function renderSchemaTypeReference(schemaName: string) {
501 return schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`;
502}
503
504function exportNameForPath(filePath: string): string {
505 const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, "");
506 if (!relative.includes("/")) {
507 return relative;
508 }
509
510 const [namespace, name] = relative.split("/", 2) as [string, string];
511 const namespacePrefix = namespace
512 .split(/[^A-Za-z0-9]+/)
513 .filter(Boolean)
514 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
515 .join("");
516 return `${namespacePrefix}${name}`;
517}
518
519function buildJsonSchemaFiles(
520 entries: ReadonlyArray<GithubContentEntry>,
521): ReadonlyArray<JsonSchemaFile> {
522 return entries
523 .filter(
524 (entry) =>
525 entry.type === "file" &&
526 entry.name.endsWith(".json") &&
527 entry.download_url !== null &&
528 !entry.name.startsWith("codex_app_server_protocol."),
529 )
530 .map((entry) => {
531 const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, "");
532 const parts = relative.split("/");
533 if (parts.length > 1) {
534 return {
535 namespace: parts[0]!,
536 exportName: exportNameForPath(relative),
537 fileName: entry.name,
538 downloadUrl: entry.download_url!,
539 qualifiedName: relative.replace(/\.json$/, ""),
540 } satisfies JsonSchemaFile;
541 }
542 return {
543 exportName: exportNameForPath(relative),
544 fileName: entry.name,
545 downloadUrl: entry.download_url!,
546 qualifiedName: relative.replace(/\.json$/, ""),
547 } satisfies JsonSchemaFile;
548 });
549}
550
551function rewriteExternalRefs(
552 value: Schema.Json,
553 localDefinitionNames: ReadonlyMap<string, string>,
554 currentNamespace: string | undefined,
555 exportNameByQualifiedName: ReadonlyMap<string, string>,
556): Schema.Json {
557 if (Array.isArray(value)) {
558 return value.map((entry) =>
559 rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
560 );
561 }
562 if (value === null || typeof value !== "object") {
563 return value;
564 }
565
566 return Object.fromEntries(
567 Object.entries(value).map(([key, child]) => {
568 if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) {
569 const definitionName = child.slice("#/definitions/".length);
570 const localRewrite = localDefinitionNames.get(definitionName);
571 if (localRewrite) {
572 return [key, `#/components/schemas/${localRewrite}`];
573 }
574
575 const candidates = [
576 ...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []),
577 definitionName,
578 definitionName.replace(/^v[12]\//, ""),
579 definitionName.replace(/^serde_json\//, ""),
580 `v2/${definitionName}`,
581 `v1/${definitionName}`,
582 `serde_json/${definitionName}`,
583 ];
584
585 const rewritten = candidates
586 .map((candidate) => exportNameByQualifiedName.get(candidate))
587 .find((candidate) => candidate !== undefined);
588
589 if (!rewritten) {
590 throw new Error(`Missing rewritten definition for ref: ${child}`);
591 }
592
593 return [key, `#/components/schemas/${rewritten}`];
594 }
595
596 return [
597 key,
598 rewriteExternalRefs(
599 child,
600 localDefinitionNames,
601 currentNamespace,
602 exportNameByQualifiedName,
603 ),
604 ];
605 }),
606 ) as Schema.Json;
607}
608
609const generateFiles = Effect.fn("generateFiles")(function* () {
610 yield* ensureGeneratedDir();
611
612 const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([
613 fetchDirectoryEntries("schema/json"),
614 fetchDirectoryEntries("schema/json/v1"),
615 fetchDirectoryEntries("schema/json/v2"),
616 ]);
617
618 const jsonSchemaFiles = [
619 ...buildJsonSchemaFiles(rootJsonEntries),
620 ...buildJsonSchemaFiles(v1JsonEntries),
621 ...buildJsonSchemaFiles(v2JsonEntries),
622 ].toSorted((left, right) => left.exportName.localeCompare(right.exportName));
623
624 const exportNameByQualifiedName = new Map(
625 jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
626 );
627 const aggregateSchemas: Record<string, Schema.Json> = {};
628
629 for (const file of jsonSchemaFiles) {
630 const raw = yield* fetchText(file.downloadUrl);
631 const parsed = yield* decodeJsonSchemaDocument(raw);
632 const localDefinitionNames = new Map(
633 Object.keys(parsed.definitions ?? {}).map((definitionName) => [
634 definitionName,
635 `${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`,
636 ]),
637 );
638
639 for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
640 aggregateSchemas[localDefinitionNames.get(definitionName)!] = pipe(
641 rewriteExternalRefs(
642 DefinitionOverrides[definitionName] ?? definitionSchema,
643 localDefinitionNames,
644 file.namespace,
645 exportNameByQualifiedName,
646 ),
647 normalizeNullableTypes,
648 stripNullDefaults,
649 );
650 }
651
652 const topLevelSchema: Record<string, Schema.Json> = {};
653 for (const [key, value] of Object.entries(parsed)) {
654 if (key !== "definitions") {
655 topLevelSchema[key] = value;
656 }
657 }
658
659 aggregateSchemas[file.exportName] = pipe(
660 rewriteExternalRefs(
661 topLevelSchema,
662 localDefinitionNames,
663 file.namespace,
664 exportNameByQualifiedName,
665 ),
666 normalizeNullableTypes,
667 stripNullDefaults,
668 );
669 }
670
671 for (const [name, schema] of Object.entries(ManualSchemas)) {
672 if (!(name in aggregateSchemas)) {
673 aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema));
674 }
675 }
676
677 const generator = makeJsonSchemaGenerator();
678 for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>
679 left.localeCompare(right),
680 )) {
681 aggregateSchemas[name] = adaptSchemaForEffect(schema);
682 generator.addSchema(name, aggregateSchemas[name] as never);
683 }
684
685 const generatedEntries = new Map<string, string>();
686 const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim();
687 if (output.length > 0) {
688 for (const entry of collectSchemaEntries(output)) {
689 if (!generatedEntries.has(entry.name)) {
690 generatedEntries.set(entry.name, entry.code);
691 }
692 }
693 }
694
695 const generatedSchemaNames = new Set(generatedEntries.keys());
696 const clientRequestRaw = yield* fetchText(
697 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`,
698 );
699 const clientNotificationRaw = yield* fetchText(
700 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`,
701 );
702 const serverRequestRaw = yield* fetchText(
703 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`,
704 );
705 const serverNotificationRaw = yield* fetchText(
706 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`,
707 );
708
709 const clientRequestEntries = parseRequestEntries(clientRequestRaw);
710 const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw);
711 const serverRequestEntries = parseRequestEntries(serverRequestRaw);
712 const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw);
713
714 const prelude = [
715 "// This file is generated by the effect-codex-app-server package. Do not edit manually.",
716 `// Upstream protocol ref: ${UPSTREAM_REF}`,
717 "",
718 ];
719
720 const schemaOutput = [
721 ...prelude,
722 'import * as Schema from "effect/Schema";',
723 "",
724 [...generatedEntries.values()].join("\n\n"),
725 "",
726 ].join("\n");
727
728 const metaOutput = [
729 ...prelude,
730 'import * as CodexSchema from "./schema.gen.ts";',
731 "",
732 renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries),
733 renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries),
734 renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries),
735 renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries),
736 "export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;",
737 "export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;",
738 "export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;",
739 "export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;",
740 "",
741 renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) =>
742 renderSchemaTypeReference(
743 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
744 ),
745 ),
746 renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) =>
747 renderSchemaTypeReference(
748 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
749 ),
750 ),
751 renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) =>
752 renderSchemaTypeReference(
753 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
754 ),
755 ),
756 renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) =>
757 renderSchemaTypeReference(
758 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
759 ),
760 ),
761 renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) =>
762 renderSchemaTypeReference(
763 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
764 ),
765 ),
766 renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) =>
767 renderSchemaTypeReference(
768 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
769 ),
770 ),
771 renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) =>
772 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
773 ),
774 renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) =>
775 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
776 ),
777 renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) =>
778 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
779 ),
780 renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) =>
781 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
782 ),
783 renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) =>
784 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
785 ),
786 renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) =>
787 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
788 ),
789 ].join("\n");
790
791 const namespaceGroups = new Map<string, Array<JsonSchemaFile>>();
792 for (const file of jsonSchemaFiles) {
793 if (!file.namespace) {
794 continue;
795 }
796 const current = namespaceGroups.get(file.namespace) ?? [];
797 current.push(file);
798 namespaceGroups.set(file.namespace, current);
799 }
800
801 const namespacesOutput = [
802 ...prelude,
803 'import * as CodexSchema from "./schema.gen.ts";',
804 "",
805 ...[...namespaceGroups.entries()]
806 .toSorted(([left], [right]) => left.localeCompare(right))
807 .map(([namespace, files]) => {
808 const constantName = namespace.replace(/[^A-Za-z0-9]/g, "");
809 return [
810 `export const ${constantName} = {`,
811 ...files
812 .toSorted((left, right) => left.fileName.localeCompare(right.fileName))
813 .map(
814 (file) =>
815 ` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`,
816 ),
817 "} as const;",
818 "",
819 ].join("\n");
820 }),
821 ].join("\n");
822
823 const fs = yield* FileSystem.FileSystem;
824 const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } =
825 yield* getGeneratedPaths();
826 yield* fs.writeFileString(schemaOutputPath, schemaOutput);
827 yield* fs.writeFileString(metaOutputPath, metaOutput);
828 yield* fs.writeFileString(namespacesOutputPath, namespacesOutput);
829
830 yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
831
832 yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
833 Effect.flatMap((spawner) =>
834 spawner.spawn(ChildProcess.make("vp", ["fmt", generatedDir, "--write"])),
835 ),
836 Effect.flatMap((child) => child.exitCode),
837 Effect.tap((code) =>
838 code === 0
839 ? Effect.void
840 : Effect.fail(
841 new GeneratorError({
842 detail: `vp fmt failed with exit code ${code}`,
843 }),
844 ),
845 ),
846 );
847});
848
849generateFiles().pipe(
850 Effect.scoped,
851 Effect.provide(
852 Layer.mergeAll(
853 Logger.layer([Logger.consolePretty()]),
854 NodeServices.layer,
855 FetchHttpClient.layer,
856 ),
857 ),
858 NodeRuntime.runMain,
859);