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

generate.ts

942 lines29.2 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 ...Object.fromEntries(Object.entries(properties).filter(([key]) => key !== "type")),
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 type: itemType,
437 },
438 };
439 }
440 return Object.fromEntries(
441 Object.entries(value).map(([key, child]) => [key, addAsyncQuestionFields(child)]),
442 );
444​
445function toPascalCaseMethod(method: string) {
446 return method
447 .split("/")
448 .flatMap((segment) => segment.split(/(?=[A-Z])/))
449 .flatMap((segment) => segment.split(/[-_]/))
450 .filter(Boolean)
451 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
452 .join("");
454​
455function parseRequestEntries(fileContents: string): ReadonlyArray<MethodEntry> {
456 const entryPattern = /\{\s*"method":\s*"([^"]+)",\s*id:\s*RequestId,\s*params:\s*([^,}]+)/g;
457 const entries: Array<MethodEntry> = [];
458 let match: RegExpExecArray | null;
459 while ((match = entryPattern.exec(fileContents)) !== null) {
460 entries.push({
461 method: match[1]!,
462 paramsType: match[2]!.trim(),
463 });
464 }
465 return entries;
467​
468function parseNotificationEntries(fileContents: string): ReadonlyArray<MethodEntry> {
469 const entryPattern = /\{\s*"method":\s*"([^"]+)"(?:,\s*"params":\s*([^ }]+))?\s*\}/g;
470 const entries: Array<MethodEntry> = [];
471 let match: RegExpExecArray | null;
472 while ((match = entryPattern.exec(fileContents)) !== null) {
473 entries.push({
474 method: match[1]!,
475 ...(match[2] ? { paramsType: match[2].trim() } : {}),
476 });
477 }
478 return entries;
480​
481function resolveSchemaTypeName(
482 rawTypeName: string,
483 generatedSchemaNames: ReadonlySet<string>,
484): string {
485 if (rawTypeName === "undefined") {
486 return "undefined";
487 }
488​
489 const candidates = [
490 rawTypeName,
491 `V2${rawTypeName}`,
492 `V1${rawTypeName}`,
493 `SerdeJson${rawTypeName}`,
494 ];
495 for (const candidate of candidates) {
496 if (generatedSchemaNames.has(candidate)) {
497 return candidate;
498 }
499 }
500​
501 throw new Error(`Unable to resolve schema type name: ${rawTypeName}`);
503​
504function resolveResponseTypeName(
505 method: string,
506 paramsType: string | undefined,
507 generatedSchemaNames: ReadonlySet<string>,
508): string {
509 const overrides: Record<string, string> = {
510 "account/logout": "LogoutAccountResponse",
511 "account/rateLimits/read": "GetAccountRateLimitsResponse",
512 "account/usage/read": "GetAccountTokenUsageResponse",
513 "account/workspaceMessages/read": "GetWorkspaceMessagesResponse",
514 "config/batchWrite": "ConfigWriteResponse",
515 "config/mcpServer/reload": "McpServerRefreshResponse",
516 "config/value/write": "ConfigWriteResponse",
517 "configRequirements/read": "ConfigRequirementsReadResponse",
518 "externalAgentConfig/import/readHistories": "ExternalAgentConfigImportHistoriesReadResponse",
519 };
520​
521 const override = overrides[method];
522 if (override) {
523 return resolveSchemaTypeName(override, generatedSchemaNames);
524 }
525​
526 if (paramsType && paramsType !== "undefined") {
527 const fromParams = paramsType.replace(/Params$/, "Response");
528 try {
529 return resolveSchemaTypeName(fromParams, generatedSchemaNames);
530 } catch {
531 // Fall through to method-based lookup.
532 }
533 }
534​
535 return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames);
537​
538function renderMethodConstants(constantName: string, entries: ReadonlyArray<MethodEntry>) {
539 return [
540 `export const ${constantName} = {`,
541 ...entries.map(
542 (entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`,
543 ),
544 "} as const;",
545 "",
546 ].join("\n");
548​
549function renderTypeInterface(
550 interfaceName: string,
551 entries: ReadonlyArray<MethodEntry>,
552 typeName: (entry: MethodEntry) => string,
553) {
554 return [
555 `export interface ${interfaceName} {`,
556 ...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`),
557 "}",
558 "",
559 ].join("\n");
561​
562function renderSchemaMap(
563 constantName: string,
564 entries: ReadonlyArray<MethodEntry>,
565 typeName: (entry: MethodEntry) => string,
566) {
567 return [
568 `export const ${constantName} = {`,
569 ...entries.map((entry) => {
570 const schemaName = typeName(entry);
571 return ` ${JSON.stringify(entry.method)}: ${
572 schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`
573 },`;
574 }),
575 "} as const;",
576 "",
577 ].join("\n");
579​
580function renderSchemaTypeReference(schemaName: string) {
581 return schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`;
583​
584function exportNameForPath(filePath: string): string {
585 const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, "");
586 if (!relative.includes("/")) {
587 return relative;
588 }
589​
590 const [namespace, name] = relative.split("/", 2) as [string, string];
591 const namespacePrefix = namespace
592 .split(/[^A-Za-z0-9]+/)
593 .filter(Boolean)
594 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
595 .join("");
596 return `${namespacePrefix}${name}`;
598​
599function buildJsonSchemaFiles(
600 entries: ReadonlyArray<GithubContentEntry>,
601): ReadonlyArray<JsonSchemaFile> {
602 return entries
603 .filter(
604 (entry) =>
605 entry.type === "file" &&
606 entry.name.endsWith(".json") &&
607 entry.download_url !== null &&
608 !entry.name.startsWith("codex_app_server_protocol."),
609 )
610 .map((entry) => {
611 const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, "");
612 const parts = relative.split("/");
613 if (parts.length > 1) {
614 return {
615 namespace: parts[0]!,
616 exportName: exportNameForPath(relative),
617 fileName: entry.name,
618 downloadUrl: entry.download_url!,
619 qualifiedName: relative.replace(/\.json$/, ""),
620 } satisfies JsonSchemaFile;
621 }
622 return {
623 exportName: exportNameForPath(relative),
624 fileName: entry.name,
625 downloadUrl: entry.download_url!,
626 qualifiedName: relative.replace(/\.json$/, ""),
627 } satisfies JsonSchemaFile;
628 });
630​
631function rewriteExternalRefs(
632 value: Schema.Json,
633 localDefinitionNames: ReadonlyMap<string, string>,
634 currentNamespace: string | undefined,
635 exportNameByQualifiedName: ReadonlyMap<string, string>,
636): Schema.Json {
637 if (Array.isArray(value)) {
638 return value.map((entry) =>
639 rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
640 );
641 }
642 if (value === null || typeof value !== "object") {
643 return value;
644 }
645​
646 return Object.fromEntries(
647 Object.entries(value).map(([key, child]) => {
648 if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) {
649 const definitionName = child.slice("#/definitions/".length);
650 const localRewrite = localDefinitionNames.get(definitionName);
651 if (localRewrite) {
652 return [key, `#/definitions/${localRewrite}`];
653 }
654​
655 const candidates = [
656 ...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []),
657 definitionName,
658 definitionName.replace(/^v[12]\//, ""),
659 definitionName.replace(/^serde_json\//, ""),
660 `v2/${definitionName}`,
661 `v1/${definitionName}`,
662 `serde_json/${definitionName}`,
663 ];
664​
665 const rewritten = candidates
666 .map((candidate) => exportNameByQualifiedName.get(candidate))
667 .find((candidate) => candidate !== undefined);
668​
669 if (!rewritten) {
670 throw new Error(`Missing rewritten definition for ref: ${child}`);
671 }
672​
673 return [key, `#/definitions/${rewritten}`];
674 }
675​
676 return [
677 key,
678 rewriteExternalRefs(
679 child,
680 localDefinitionNames,
681 currentNamespace,
682 exportNameByQualifiedName,
683 ),
684 ];
685 }),
686 ) as Schema.Json;
688​
689const generateFiles = Effect.fn("generateFiles")(function* () {
690 yield* ensureGeneratedDir();
691​
692 const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([
693 fetchDirectoryEntries("schema/json"),
694 fetchDirectoryEntries("schema/json/v1"),
695 fetchDirectoryEntries("schema/json/v2"),
696 ]);
697​
698 const jsonSchemaFiles = [
699 ...buildJsonSchemaFiles(rootJsonEntries),
700 ...buildJsonSchemaFiles(v1JsonEntries),
701 ...buildJsonSchemaFiles(v2JsonEntries),
702 ].toSorted((left, right) => left.exportName.localeCompare(right.exportName));
703​
704 const exportNameByQualifiedName = new Map(
705 jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
706 );
707 const aggregateSchemas: Record<string, Schema.Json> = {};
708​
709 for (const file of jsonSchemaFiles) {
710 const raw = yield* fetchText(file.downloadUrl);
711 const parsed = yield* decodeJsonSchemaDocument(raw);
712 const localDefinitionNames = new Map(
713 Object.keys(parsed.definitions ?? {}).map((definitionName) => [
714 definitionName,
715 `${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`,
716 ]),
717 );
718​
719 for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
720 const compatibleDefinitionSchema =
721 Codex0150DefinitionSchemas[definitionName] ??
722 applyCodex0151DefinitionCompatibility(file.exportName, definitionName, definitionSchema);
723 aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults(
724 normalizeNullableTypes(
725 rewriteExternalRefs(
726 compatibleDefinitionSchema,
727 localDefinitionNames,
728 file.namespace,
729 exportNameByQualifiedName,
730 ),
731 ),
732 );
733 }
734​
735 const topLevelSchema: Record<string, Schema.Json> = {};
736 for (const [key, value] of Object.entries(parsed)) {
737 if (key !== "definitions") {
738 topLevelSchema[key] = value;
739 }
740 }
741​
742 aggregateSchemas[file.exportName] = stripNullDefaults(
743 normalizeNullableTypes(
744 rewriteExternalRefs(
745 topLevelSchema,
746 localDefinitionNames,
747 file.namespace,
748 exportNameByQualifiedName,
749 ),
750 ),
751 );
752 }
753​
754 for (const [name, schema] of Object.entries(ManualSchemas)) {
755 if (!(name in aggregateSchemas)) {
756 aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema));
757 }
758 }
759​
760 const generator = makeJsonSchemaGenerator();
761 for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>
762 left.localeCompare(right),
763 )) {
764 aggregateSchemas[name] = addAsyncQuestionFields(schema);
765 generator.addSchema(name, aggregateSchemas[name] as never);
766 }
767​
768 const generatedEntries = new Map<string, string>();
769 const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim();
770 if (output.length > 0) {
771 for (const entry of collectSchemaEntries(output)) {
772 if (!generatedEntries.has(entry.name)) {
773 generatedEntries.set(entry.name, entry.code);
774 }
775 }
776 }
777​
778 const generatedSchemaNames = new Set(generatedEntries.keys());
779 const clientRequestRaw = yield* fetchText(
780 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`,
781 );
782 const clientNotificationRaw = yield* fetchText(
783 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`,
784 );
785 const serverRequestRaw = yield* fetchText(
786 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`,
787 );
788 const serverNotificationRaw = yield* fetchText(
789 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`,
790 );
791​
792 const clientRequestEntries = parseRequestEntries(clientRequestRaw);
793 const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw);
794 const serverRequestEntries = parseRequestEntries(serverRequestRaw);
795 const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw);
796​
797 const prelude = [
798 "// This file is generated by the effect-codex-app-server package. Do not edit manually.",
799 `// Upstream protocol ref: ${UPSTREAM_REF}`,
800 "",
801 ];
802​
803 const schemaOutput = [
804 ...prelude,
805 'import * as Schema from "effect/Schema";',
806 "",
807 [...generatedEntries.values()].join("\n\n"),
808 "",
809 ].join("\n");
810​
811 const metaOutput = [
812 ...prelude,
813 'import * as CodexSchema from "./schema.gen.ts";',
814 "",
815 renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries),
816 renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries),
817 renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries),
818 renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries),
819 "export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;",
820 "export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;",
821 "export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;",
822 "export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;",
823 "",
824 renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) =>
825 renderSchemaTypeReference(
826 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
827 ),
828 ),
829 renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) =>
830 renderSchemaTypeReference(
831 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
832 ),
833 ),
834 renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) =>
835 renderSchemaTypeReference(
836 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
837 ),
838 ),
839 renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) =>
840 renderSchemaTypeReference(
841 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
842 ),
843 ),
844 renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) =>
845 renderSchemaTypeReference(
846 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
847 ),
848 ),
849 renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) =>
850 renderSchemaTypeReference(
851 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
852 ),
853 ),
854 renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) =>
855 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
856 ),
857 renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) =>
858 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
859 ),
860 renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) =>
861 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
862 ),
863 renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) =>
864 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
865 ),
866 renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) =>
867 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
868 ),
869 renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) =>
870 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
871 ),
872 ].join("\n");
873​
874 const namespaceGroups = new Map<string, Array<JsonSchemaFile>>();
875 for (const file of jsonSchemaFiles) {
876 if (!file.namespace) {
877 continue;
878 }
879 const current = namespaceGroups.get(file.namespace) ?? [];
880 current.push(file);
881 namespaceGroups.set(file.namespace, current);
882 }
883​
884 const namespacesOutput = [
885 ...prelude,
886 'import * as CodexSchema from "./schema.gen.ts";',
887 "",
888 ...[...namespaceGroups.entries()]
889 .toSorted(([left], [right]) => left.localeCompare(right))
890 .map(([namespace, files]) => {
891 const constantName = namespace.replace(/[^A-Za-z0-9]/g, "");
892 return [
893 `export const ${constantName} = {`,
894 ...files
895 .toSorted((left, right) => left.fileName.localeCompare(right.fileName))
896 .map(
897 (file) =>
898 ` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`,
899 ),
900 "} as const;",
901 "",
902 ].join("\n");
903 }),
904 ].join("\n");
905​
906 const fs = yield* FileSystem.FileSystem;
907 const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } =
908 yield* getGeneratedPaths();
909 yield* fs.writeFileString(schemaOutputPath, schemaOutput);
910 yield* fs.writeFileString(metaOutputPath, metaOutput);
911 yield* fs.writeFileString(namespacesOutputPath, namespacesOutput);
912​
913 yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
914​
915 yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
916 Effect.flatMap((spawner) =>
917 spawner.spawn(ChildProcess.make("vp", ["fmt", generatedDir, "--write"])),
918 ),
919 Effect.flatMap((child) => child.exitCode),
920 Effect.tap((code) =>
921 code === 0
922 ? Effect.void
923 : Effect.fail(
924 new GeneratorError({
925 detail: `vp fmt failed with exit code ${code}`,
926 }),
927 ),
928 ),
929 );
930});
931​
932generateFiles().pipe(
933 Effect.scoped,
934 Effect.provide(
935 Layer.mergeAll(
936 Logger.layer([Logger.consolePretty()]),
937 NodeServices.layer,
938 FetchHttpClient.layer,
939 ),
940 ),
941 NodeRuntime.runMain,
942);