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 // Newer Codex releases add hook events (e.g. `preModelRequest`); a closed enum drops their notifications.
149 HookEventName: { type: "string" },
150 // Newer custom Codex binaries emit partial answers before additional tools or text.
151 MessagePhase: {
152 description:
153 'Classifies an assistant message as interim commentary or final answer text.\n\nProviders do not emit this consistently, so callers must treat `None` as "phase unknown" and keep compatibility behavior for legacy models.',
154 oneOf: [
155 {
156 type: "string",
157 enum: ["commentary"],
158 description:
159 "Mid-turn assistant text (for example preamble/progress narration).\n\nAdditional tool calls or assistant output may follow before turn completion.",
160 },
161 {
162 type: "string",
163 enum: ["partial_answer"],
164 description: "Stable answer text that may be followed by more assistant output or tools.",
165 },
166 {
167 type: "string",
168 enum: ["final_answer"],
169 description: "The assistant's terminal answer text for the current turn.",
170 },
171 ],
172 },
173};
174
175// Codex sends error codes this ref does not list yet (e.g. `modelNotFound`). A closed enum
176// fails the whole notification decode, which drops a failed `turn/completed` and leaves the turn running.
177const OpenStringEnumDefinitions = new Set(["CodexErrorInfo"]);
178
179function openStringEnum(schema: Schema.Json): Schema.Json {
180 if (!isJsonSchemaNode(schema) || !Array.isArray(schema.oneOf)) return schema;
181 return {
182 ...schema,
183 oneOf: schema.oneOf.map((variant: Schema.Json) =>
184 isJsonSchemaNode(variant) && variant.type === "string" && Array.isArray(variant.enum)
185 ? { type: "string" }
186 : variant,
187 ),
188 };
189}
190
191// Newer Codex identifies a generated image by `fileId` and omits the inline `result`.
192// Requiring `result` fails the whole notification decode and drops the finished image.
193function acceptImageFileIds(schema: Schema.Json): Schema.Json {
194 if (!isJsonSchemaNode(schema) || !Array.isArray(schema.oneOf)) return schema;
195 return {
196 ...schema,
197 oneOf: schema.oneOf.map((variant: Schema.Json) => {
198 if (
199 !isJsonSchemaNode(variant) ||
200 !isJsonSchemaNode(variant.properties) ||
201 !isJsonSchemaNode(variant.properties.type) ||
202 !Array.isArray(variant.properties.type.enum) ||
203 !variant.properties.type.enum.includes("imageGeneration") ||
204 !Array.isArray(variant.required)
205 ) {
206 return variant;
207 }
208 return {
209 ...variant,
210 properties: { ...variant.properties, fileId: { type: "string" } },
211 required: variant.required.filter((key: Schema.Json) => key !== "result"),
212 };
213 }),
214 };
215}
216
217const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
218 const path = yield* Path.Path;
219 const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
220 return {
221 generatedDir,
222 schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
223 metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
224 namespacesOutputPath: path.join(generatedDir, "namespaces.gen.ts"),
225 } satisfies GeneratedPaths;
226});
227
228const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
229 const fs = yield* FileSystem.FileSystem;
230 const { generatedDir } = yield* getGeneratedPaths();
231 yield* fs.makeDirectory(generatedDir, { recursive: true });
232});
233
234const githubToken = process.env.GITHUB_TOKEN;
235
236const fetchText = Effect.fn("fetchText")(function* (url: string) {
237 return yield* HttpClientRequest.get(url).pipe(
238 HttpClientRequest.setHeader("user-agent", USER_AGENT),
239 githubToken && url.startsWith("https://api.github.com/")
240 ? HttpClientRequest.bearerToken(githubToken)
241 : (request) => request,
242 HttpClient.execute,
243 Effect.flatMap(HttpClientResponse.filterStatusOk),
244 Effect.flatMap((okResponse) => okResponse.text),
245 Effect.mapError(
246 (cause) =>
247 new GeneratorError({
248 detail: `Failed to fetch ${url}`,
249 cause,
250 }),
251 ),
252 );
253});
254
255const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) {
256 const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`);
257 return yield* decodeGithubContentEntries(raw);
258});
259
260function collectSchemaEntries(
261 chunk: string,
262): ReadonlyArray<{ readonly name: string; readonly code: string }> {
263 const lines = chunk
264 .split("\n")
265 .map((line) => line.trim())
266 .filter((line) => line.length > 0 && !line.startsWith("//"));
267 const entries: Array<{ name: string; code: string }> = [];
268
269 for (let index = 0; index < lines.length; index += 1) {
270 const typeLine = lines[index];
271 if (!typeLine?.startsWith("export type ")) {
272 continue;
273 }
274
275 const constLine = lines[index + 1];
276 if (!constLine?.startsWith("export const ")) {
277 throw new Error(`Malformed generator output near: ${typeLine}`);
278 }
279
280 const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
281 if (!match?.[1]) {
282 throw new Error(`Could not extract schema name from: ${typeLine}`);
283 }
284
285 entries.push({
286 name: match[1],
287 code: `${typeLine}\n${constLine}`,
288 });
289 index += 1;
290 }
291
292 return entries;
293}
294
295function normalizeNullableTypes(value: Schema.Json): Schema.Json {
296 if (Array.isArray(value)) {
297 return value.map(normalizeNullableTypes);
298 }
299 if (value === null || typeof value !== "object") {
300 return value;
301 }
302
303 const normalizedEntries = Object.entries(value).map(([key, child]) => [
304 key,
305 normalizeNullableTypes(child),
306 ]);
307 const normalizedObject = Object.fromEntries(normalizedEntries) as Record<string, Schema.Json>;
308 const typeValue = normalizedObject.type;
309
310 if (!Array.isArray(typeValue)) {
311 return normalizedObject;
312 }
313
314 const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
315 if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
316 return normalizedObject;
317 }
318
319 const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
320 if (nonNullTypes.length !== 1) {
321 return normalizedObject;
322 }
323 const nonNullType = nonNullTypes[0]!;
324
325 const nextObject: Record<string, Schema.Json> = {};
326 for (const [key, child] of Object.entries(normalizedObject)) {
327 if (key !== "type") {
328 nextObject[key] = child;
329 }
330 }
331
332 return {
333 anyOf: [
334 {
335 ...nextObject,
336 type: nonNullType,
337 },
338 { type: "null" },
339 ],
340 };
341}
342
343function stripNullDefaults(value: Schema.Json): Schema.Json {
344 if (Array.isArray(value)) {
345 return value.map(stripNullDefaults);
346 }
347 if (value === null || typeof value !== "object") {
348 return value;
349 }
350
351 return Object.fromEntries(
352 Object.entries(value)
353 .filter(([key, child]) => !(key === "default" && child === null))
354 .map(([key, child]) => [key, stripNullDefaults(child)]),
355 ) as Schema.Json;
356}
357
358type JsonSchemaNode = { readonly [key: string]: Schema.Json };
359
360function isJsonSchemaNode(value: Schema.Json | undefined): value is JsonSchemaNode {
361 return value !== null && typeof value === "object" && !Array.isArray(value);
362}
363
364// Visit only schema positions so fields literally named properties stay untouched.
365// Close Codex structs that omit additionalProperties; Effect otherwise imports open records.
366// Fold shared fields into each object alternative because Effect cannot intersect them.
367function adaptSchemaForEffect(value: Schema.Json): Schema.Json {
368 if (!isJsonSchemaNode(value)) {
369 return value;
370 }
371 const node: Record<string, Schema.Json> = { ...value };
372 for (const key of ["items", "additionalProperties"]) {
373 const child = node[key];
374 if (isJsonSchemaNode(child)) node[key] = adaptSchemaForEffect(child);
375 }
376 for (const key of ["anyOf", "oneOf", "allOf"]) {
377 const child = node[key];
378 if (Array.isArray(child)) node[key] = child.map(adaptSchemaForEffect);
379 }
380 for (const key of ["properties", "definitions"]) {
381 const child = node[key];
382 if (isJsonSchemaNode(child)) {
383 node[key] = Object.fromEntries(
384 Object.entries(child).map(([name, schema]) => [name, adaptSchemaForEffect(schema)]),
385 );
386 }
387 }
388
389 const { properties } = node;
390 if (
391 isJsonSchemaNode(properties) &&
392 Object.keys(properties).length > 0 &&
393 !("additionalProperties" in node)
394 ) {
395 node.additionalProperties = false;
396 }
397
398 const alternativesKey = "anyOf" in node ? "anyOf" : "oneOf";
399 const alternatives = node[alternativesKey];
400 if (
401 !isJsonSchemaNode(properties) ||
402 !Array.isArray(alternatives) ||
403 !alternatives.every(
404 (alternative) => isJsonSchemaNode(alternative) && alternative.type === "object",
405 )
406 ) {
407 return node;
408 }
409 const {
410 properties: _shared,
411 required,
412 type: _type,
413 additionalProperties: _closed,
414 ...rest
415 } = node;
416 const sharedRequired = Array.isArray(required) ? required : [];
417 return {
418 ...rest,
419 [alternativesKey]: alternatives.map((alternative) => {
420 const branch = alternative as JsonSchemaNode;
421 const branchProperties = isJsonSchemaNode(branch.properties) ? branch.properties : {};
422 const branchRequired = Array.isArray(branch.required) ? branch.required : [];
423 return {
424 ...branch,
425 properties: { ...properties, ...branchProperties },
426 required: [...new Set([...sharedRequired, ...branchRequired])],
427 };
428 }),
429 };
430}
431
432function toPascalCaseMethod(method: string) {
433 return method
434 .split("/")
435 .flatMap((segment) => segment.split(/(?=[A-Z])/))
436 .flatMap((segment) => segment.split(/[-_]/))
437 .filter(Boolean)
438 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
439 .join("");
440}
441
442function parseRequestEntries(fileContents: string): ReadonlyArray<MethodEntry> {
443 const entryPattern = /\{\s*"method":\s*"([^"]+)",\s*id:\s*RequestId,\s*params(\??):\s*([^,}|]+)/g;
444 const entries: Array<MethodEntry> = [];
445 let match: RegExpExecArray | null;
446 while ((match = entryPattern.exec(fileContents)) !== null) {
447 entries.push({
448 method: match[1]!,
449 paramsType: `${match[2] ? "Nullable" : ""}${match[3]!.trim()}`,
450 });
451 }
452 return entries;
453}
454
455function parseNotificationEntries(fileContents: string): ReadonlyArray<MethodEntry> {
456 const entryPattern = /\{\s*"method":\s*"([^"]+)"(?:,\s*"params":\s*([^ }]+))?\s*\}/g;
457 const entries: Array<MethodEntry> = [];
458 let match: RegExpExecArray | null;
459 while ((match = entryPattern.exec(fileContents)) !== null) {
460 entries.push({
461 method: match[1]!,
462 ...(match[2] ? { paramsType: match[2].trim() } : {}),
463 });
464 }
465 return entries;
466}
467
468function resolveSchemaTypeName(
469 rawTypeName: string,
470 generatedSchemaNames: ReadonlySet<string>,
471): string {
472 if (rawTypeName === "undefined") {
473 return "undefined";
474 }
475
476 const candidates = [
477 rawTypeName,
478 `V2${rawTypeName}`,
479 `V1${rawTypeName}`,
480 `SerdeJson${rawTypeName}`,
481 ];
482 for (const candidate of candidates) {
483 if (generatedSchemaNames.has(candidate)) {
484 return candidate;
485 }
486 }
487
488 throw new Error(`Unable to resolve schema type name: ${rawTypeName}`);
489}
490
491function resolveResponseTypeName(
492 method: string,
493 paramsType: string | undefined,
494 generatedSchemaNames: ReadonlySet<string>,
495): string {
496 const overrides: Record<string, string> = {
497 "account/gatewayOAuth/cancel": "GatewayOAuthCancelResponse",
498 "account/gatewayOAuth/login": "GatewayOAuthLoginResponse",
499 "account/gatewayOAuth/read": "GatewayOAuthReadResponse",
500 "account/logout": "LogoutAccountResponse",
501 "account/rateLimits/read": "GetAccountRateLimitsResponse",
502 "account/usage/read": "GetAccountTokenUsageResponse",
503 "account/workspaceMessages/read": "GetWorkspaceMessagesResponse",
504 "config/batchWrite": "ConfigWriteResponse",
505 "config/mcpServer/reload": "McpServerRefreshResponse",
506 "config/value/write": "ConfigWriteResponse",
507 "configRequirements/read": "ConfigRequirementsReadResponse",
508 "externalAgentConfig/import/readHistories": "ExternalAgentConfigImportHistoriesReadResponse",
509 };
510
511 const override = overrides[method];
512 if (override) {
513 return resolveSchemaTypeName(override, generatedSchemaNames);
514 }
515
516 if (paramsType && paramsType !== "undefined") {
517 const fromParams = paramsType.replace(/Params$/, "Response");
518 try {
519 return resolveSchemaTypeName(fromParams, generatedSchemaNames);
520 } catch {}
521 }
522
523 return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames);
524}
525
526function renderMethodConstants(constantName: string, entries: ReadonlyArray<MethodEntry>) {
527 return [
528 `export const ${constantName} = {`,
529 ...entries.map(
530 (entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`,
531 ),
532 "} as const;",
533 "",
534 ].join("\n");
535}
536
537function renderTypeInterface(
538 interfaceName: string,
539 entries: ReadonlyArray<MethodEntry>,
540 typeName: (entry: MethodEntry) => string,
541) {
542 return [
543 `export interface ${interfaceName} {`,
544 ...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`),
545 "}",
546 "",
547 ].join("\n");
548}
549
550function renderSchemaMap(
551 constantName: string,
552 entries: ReadonlyArray<MethodEntry>,
553 typeName: (entry: MethodEntry) => string,
554) {
555 return [
556 `export const ${constantName} = {`,
557 ...entries.map((entry) => {
558 const schemaName = typeName(entry);
559 return ` ${JSON.stringify(entry.method)}: ${
560 schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`
561 },`;
562 }),
563 "} as const;",
564 "",
565 ].join("\n");
566}
567
568function renderSchemaTypeReference(schemaName: string) {
569 return schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`;
570}
571
572function exportNameForPath(filePath: string): string {
573 const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, "");
574 if (!relative.includes("/")) {
575 return relative;
576 }
577
578 const [namespace, name] = relative.split("/", 2) as [string, string];
579 const namespacePrefix = namespace
580 .split(/[^A-Za-z0-9]+/)
581 .filter(Boolean)
582 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
583 .join("");
584 return `${namespacePrefix}${name}`;
585}
586
587function buildJsonSchemaFiles(
588 entries: ReadonlyArray<GithubContentEntry>,
589): ReadonlyArray<JsonSchemaFile> {
590 return entries
591 .filter(
592 (entry) =>
593 entry.type === "file" &&
594 entry.name.endsWith(".json") &&
595 entry.download_url !== null &&
596 !entry.name.startsWith("codex_app_server_protocol."),
597 )
598 .map((entry) => {
599 const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, "");
600 const parts = relative.split("/");
601 if (parts.length > 1) {
602 return {
603 namespace: parts[0]!,
604 exportName: exportNameForPath(relative),
605 fileName: entry.name,
606 downloadUrl: entry.download_url!,
607 qualifiedName: relative.replace(/\.json$/, ""),
608 } satisfies JsonSchemaFile;
609 }
610 return {
611 exportName: exportNameForPath(relative),
612 fileName: entry.name,
613 downloadUrl: entry.download_url!,
614 qualifiedName: relative.replace(/\.json$/, ""),
615 } satisfies JsonSchemaFile;
616 });
617}
618
619function rewriteExternalRefs(
620 value: Schema.Json,
621 localDefinitionNames: ReadonlyMap<string, string>,
622 currentNamespace: string | undefined,
623 exportNameByQualifiedName: ReadonlyMap<string, string>,
624): Schema.Json {
625 if (Array.isArray(value)) {
626 return value.map((entry) =>
627 rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
628 );
629 }
630 if (value === null || typeof value !== "object") {
631 return value;
632 }
633
634 return Object.fromEntries(
635 Object.entries(value).map(([key, child]) => {
636 if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) {
637 const definitionName = child.slice("#/definitions/".length);
638 const localRewrite = localDefinitionNames.get(definitionName);
639 if (localRewrite) {
640 return [key, `#/components/schemas/${localRewrite}`];
641 }
642
643 const candidates = [
644 ...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []),
645 definitionName,
646 definitionName.replace(/^v[12]\//, ""),
647 definitionName.replace(/^serde_json\//, ""),
648 `v2/${definitionName}`,
649 `v1/${definitionName}`,
650 `serde_json/${definitionName}`,
651 ];
652
653 const rewritten = candidates
654 .map((candidate) => exportNameByQualifiedName.get(candidate))
655 .find((candidate) => candidate !== undefined);
656
657 if (!rewritten) {
658 throw new Error(`Missing rewritten definition for ref: ${child}`);
659 }
660
661 return [key, `#/components/schemas/${rewritten}`];
662 }
663
664 return [
665 key,
666 rewriteExternalRefs(
667 child,
668 localDefinitionNames,
669 currentNamespace,
670 exportNameByQualifiedName,
671 ),
672 ];
673 }),
674 ) as Schema.Json;
675}
676
677const generateFiles = Effect.fn("generateFiles")(function* () {
678 yield* ensureGeneratedDir();
679
680 const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([
681 fetchDirectoryEntries("schema/json"),
682 fetchDirectoryEntries("schema/json/v1"),
683 fetchDirectoryEntries("schema/json/v2"),
684 ]);
685
686 const jsonSchemaFiles = [
687 ...buildJsonSchemaFiles(rootJsonEntries),
688 ...buildJsonSchemaFiles(v1JsonEntries),
689 ...buildJsonSchemaFiles(v2JsonEntries),
690 ].toSorted((left, right) => left.exportName.localeCompare(right.exportName));
691
692 const exportNameByQualifiedName = new Map(
693 jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
694 );
695 const aggregateSchemas: Record<string, Schema.Json> = {};
696
697 for (const file of jsonSchemaFiles) {
698 const raw = yield* fetchText(file.downloadUrl);
699 const parsed = yield* decodeJsonSchemaDocument(raw);
700 const localDefinitionNames = new Map(
701 Object.keys(parsed.definitions ?? {}).map((definitionName) => [
702 definitionName,
703 `${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`,
704 ]),
705 );
706
707 for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
708 aggregateSchemas[localDefinitionNames.get(definitionName)!] = pipe(
709 rewriteExternalRefs(
710 DefinitionOverrides[definitionName] ??
711 (OpenStringEnumDefinitions.has(definitionName)
712 ? openStringEnum(definitionSchema)
713 : definitionName === "ThreadItem"
714 ? acceptImageFileIds(definitionSchema)
715 : definitionSchema),
716 localDefinitionNames,
717 file.namespace,
718 exportNameByQualifiedName,
719 ),
720 normalizeNullableTypes,
721 stripNullDefaults,
722 );
723 }
724
725 const topLevelSchema: Record<string, Schema.Json> = {};
726 for (const [key, value] of Object.entries(parsed)) {
727 if (key !== "definitions") {
728 topLevelSchema[key] = value;
729 }
730 }
731
732 aggregateSchemas[file.exportName] = pipe(
733 rewriteExternalRefs(
734 topLevelSchema,
735 localDefinitionNames,
736 file.namespace,
737 exportNameByQualifiedName,
738 ),
739 normalizeNullableTypes,
740 stripNullDefaults,
741 );
742 }
743
744 for (const [name, schema] of Object.entries(ManualSchemas)) {
745 if (!(name in aggregateSchemas)) {
746 aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema));
747 }
748 }
749
750 const generator = makeJsonSchemaGenerator();
751 for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>
752 left.localeCompare(right),
753 )) {
754 aggregateSchemas[name] = adaptSchemaForEffect(schema);
755 generator.addSchema(name, aggregateSchemas[name] as never);
756 }
757
758 const generatedEntries = new Map<string, string>();
759 const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim();
760 if (output.length > 0) {
761 for (const entry of collectSchemaEntries(output)) {
762 if (!generatedEntries.has(entry.name)) {
763 generatedEntries.set(entry.name, entry.code);
764 }
765 }
766 }
767
768 const generatedSchemaNames = new Set(generatedEntries.keys());
769 const clientRequestRaw = yield* fetchText(
770 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`,
771 );
772 const clientNotificationRaw = yield* fetchText(
773 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`,
774 );
775 const serverRequestRaw = yield* fetchText(
776 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`,
777 );
778 const serverNotificationRaw = yield* fetchText(
779 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`,
780 );
781
782 const clientRequestEntries = parseRequestEntries(clientRequestRaw);
783 const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw);
784 const serverRequestEntries = parseRequestEntries(serverRequestRaw);
785 const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw);
786
787 const prelude = [
788 "// This file is generated by the effect-codex-app-server package. Do not edit manually.",
789 `// Upstream protocol ref: ${UPSTREAM_REF}`,
790 "",
791 ];
792
793 const schemaOutput = [
794 ...prelude,
795 'import * as Schema from "effect/Schema";',
796 "",
797 [...generatedEntries.values()].join("\n\n"),
798 "",
799 ].join("\n");
800
801 const metaOutput = [
802 ...prelude,
803 'import * as CodexSchema from "./schema.gen.ts";',
804 "",
805 renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries),
806 renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries),
807 renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries),
808 renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries),
809 "export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;",
810 "export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;",
811 "export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;",
812 "export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;",
813 "",
814 renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) =>
815 renderSchemaTypeReference(
816 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
817 ),
818 ),
819 renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) =>
820 renderSchemaTypeReference(
821 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
822 ),
823 ),
824 renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) =>
825 renderSchemaTypeReference(
826 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
827 ),
828 ),
829 renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) =>
830 renderSchemaTypeReference(
831 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
832 ),
833 ),
834 renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) =>
835 renderSchemaTypeReference(
836 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
837 ),
838 ),
839 renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) =>
840 renderSchemaTypeReference(
841 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
842 ),
843 ),
844 renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) =>
845 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
846 ),
847 renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) =>
848 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
849 ),
850 renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) =>
851 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
852 ),
853 renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) =>
854 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
855 ),
856 renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) =>
857 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
858 ),
859 renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) =>
860 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
861 ),
862 ].join("\n");
863
864 const namespaceGroups = new Map<string, Array<JsonSchemaFile>>();
865 for (const file of jsonSchemaFiles) {
866 if (!file.namespace) {
867 continue;
868 }
869 const current = namespaceGroups.get(file.namespace) ?? [];
870 current.push(file);
871 namespaceGroups.set(file.namespace, current);
872 }
873
874 const namespacesOutput = [
875 ...prelude,
876 'import * as CodexSchema from "./schema.gen.ts";',
877 "",
878 ...[...namespaceGroups.entries()]
879 .toSorted(([left], [right]) => left.localeCompare(right))
880 .map(([namespace, files]) => {
881 const constantName = namespace.replace(/[^A-Za-z0-9]/g, "");
882 return [
883 `export const ${constantName} = {`,
884 ...files
885 .toSorted((left, right) => left.fileName.localeCompare(right.fileName))
886 .map(
887 (file) =>
888 ` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`,
889 ),
890 "} as const;",
891 "",
892 ].join("\n");
893 }),
894 ].join("\n");
895
896 const fs = yield* FileSystem.FileSystem;
897 const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } =
898 yield* getGeneratedPaths();
899 yield* fs.writeFileString(schemaOutputPath, schemaOutput);
900 yield* fs.writeFileString(metaOutputPath, metaOutput);
901 yield* fs.writeFileString(namespacesOutputPath, namespacesOutput);
902
903 yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
904
905 yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
906 Effect.flatMap((spawner) =>
907 spawner.spawn(ChildProcess.make("vp", ["fmt", generatedDir, "--write"])),
908 ),
909 Effect.flatMap((child) => child.exitCode),
910 Effect.tap((code) =>
911 code === 0
912 ? Effect.void
913 : Effect.fail(
914 new GeneratorError({
915 detail: `vp fmt failed with exit code ${code}`,
916 }),
917 ),
918 ),
919 );
920});
921
922generateFiles().pipe(
923 Effect.scoped,
924 Effect.provide(
925 Layer.mergeAll(
926 Logger.layer([Logger.consolePretty()]),
927 NodeServices.layer,
928 FetchHttpClient.layer,
929 ),
930 ),
931 NodeRuntime.runMain,
932);