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

generate.ts

972 lines31.8 KB

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