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

generate.ts

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