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

generate.ts

940 lines29.0 KB

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