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

generate.ts

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