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