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