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