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

generate.ts

289 lines9.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 { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
7import { Command, Flag } from "effect/unstable/cli";
8import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/unstable/http";
9import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
10​
11const CURRENT_SCHEMA_RELEASE = "v0.11.3";
12​
13interface GenerateCommandError {
14 readonly _tag: "GenerateCommandError";
15 readonly message: string;
17​
18interface GeneratedPaths {
19 readonly generatedDir: string;
20 readonly upstreamSchemaPath: string;
21 readonly upstreamMetaPath: string;
22 readonly schemaOutputPath: string;
23 readonly metaOutputPath: string;
25​
26const MetaJsonSchema = Schema.Struct({
27 agentMethods: Schema.Record(Schema.String, Schema.String),
28 clientMethods: Schema.Record(Schema.String, Schema.String),
29 version: Schema.Union([Schema.Number, Schema.String]),
30});
31​
32const UpstreamJsonSchemaSchema = Schema.Struct({
33 $defs: Schema.Record(Schema.String, Schema.Json),
34});
35​
36const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
37 const path = yield* Path.Path;
38 const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
39 return {
40 generatedDir,
41 upstreamSchemaPath: path.join(generatedDir, "upstream-schema.json"),
42 upstreamMetaPath: path.join(generatedDir, "upstream-meta.json"),
43 schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
44 metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
45 } satisfies GeneratedPaths;
46});
47​
48const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
49 const fs = yield* FileSystem.FileSystem;
50 const { generatedDir } = yield* getGeneratedPaths();
51​
52 yield* fs.makeDirectory(generatedDir, { recursive: true });
53});
54​
55const downloadFile = Effect.fn("downloadFile")(function* (url: string, outputPath: string) {
56 const fs = yield* FileSystem.FileSystem;
57 const path = yield* Path.Path;
58​
59 yield* fs.makeDirectory(path.dirname(outputPath), { recursive: true });
60​
61 const text = yield* HttpClient.get(url).pipe(
62 Effect.flatMap(HttpClientResponse.filterStatusOk),
63 Effect.flatMap((response) => response.text),
64 );
65​
66 yield* fs.writeFileString(outputPath, text);
67});
68​
69const downloadSchemas = Effect.fn("downloadSchemas")(function* (tag: string) {
70 const { upstreamMetaPath, upstreamSchemaPath } = yield* getGeneratedPaths();
71 const fs = yield* FileSystem.FileSystem;
72 const baseUrl = `https://github.com/agentclientprotocol/agent-client-protocol/releases/download/${tag}`;
73​
74 yield* downloadFile(`${baseUrl}/schema.unstable.json`, upstreamSchemaPath);
75 yield* downloadFile(`${baseUrl}/meta.unstable.json`, upstreamMetaPath);
76​
77 yield* Effect.addFinalizer(() =>
78 Effect.all([fs.remove(upstreamSchemaPath), fs.remove(upstreamMetaPath)]).pipe(
79 Effect.ignoreCause({ log: true }),
80 ),
81 );
82});
83​
84const readJsonFile = Effect.fn("readJsonFile")(function* <
85 S extends Schema.Top & { readonly DecodingServices: never },
86>(schema: S, filePath: string) {
87 const fs = yield* FileSystem.FileSystem;
88 const raw = yield* fs.readFileString(filePath);
89 return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(raw);
90});
91​
92const writeGeneratedFiles = Effect.fn("writeGeneratedFiles")(function* (
93 schemaOutput: string,
94 metaOutput: string,
95) {
96 const fs = yield* FileSystem.FileSystem;
97 const { metaOutputPath, schemaOutputPath } = yield* getGeneratedPaths();
98​
99 yield* fs.writeFileString(schemaOutputPath, schemaOutput);
100 yield* fs.writeFileString(metaOutputPath, metaOutput);
101});
102​
103function collectSchemaEntries(
104 chunk: string,
105): ReadonlyArray<{ readonly name: string; readonly code: string }> {
106 const lines = chunk
107 .split("\n")
108 .map((line) => line.trim())
109 .filter((line) => line.length > 0 && !line.startsWith("//"));
110 const entries: Array<{ name: string; code: string }> = [];
111​
112 for (let index = 0; index < lines.length; index += 1) {
113 const typeLine = lines[index];
114 if (!typeLine?.startsWith("export type ")) {
115 continue;
116 }
117​
118 const constLine = lines[index + 1];
119 if (!constLine?.startsWith("export const ")) {
120 throw new Error(`Malformed generator output near: ${typeLine}`);
121 }
122​
123 const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
124 if (!match?.[1]) {
125 throw new Error(`Could not extract schema name from: ${typeLine}`);
126 }
127​
128 entries.push({
129 name: match[1],
130 code: `${typeLine}\n${constLine}`,
131 });
132 index += 1;
133 }
134​
135 return entries;
137​
138function normalizeNullableTypes(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
139 if (Array.isArray(value)) {
140 return value.map(normalizeNullableTypes);
141 }
142 if (value === null || typeof value !== "object") {
143 return value;
144 }
145​
146 const normalizedEntries = Object.entries(value).map(([key, child]) => [
147 key,
148 normalizeNullableTypes(child),
149 ]);
150 const normalizedObject = Object.fromEntries(normalizedEntries) as Record<
151 string,
152 typeof Schema.Json.Type
153 >;
154 const typeValue = normalizedObject.type;
155​
156 if (!Array.isArray(typeValue)) {
157 return normalizedObject;
158 }
159​
160 const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
161 if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
162 return normalizedObject;
163 }
164​
165 const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
166 if (nonNullTypes.length !== 1) {
167 return normalizedObject;
168 }
169 const nonNullType = nonNullTypes[0]!;
170​
171 const nextObject: Record<string, typeof Schema.Json.Type> = {};
172 for (const [key, child] of Object.entries(normalizedObject)) {
173 if (key !== "type") {
174 nextObject[key] = child;
175 }
176 }
177​
178 return {
179 anyOf: [
180 {
181 ...nextObject,
182 type: nonNullType,
183 },
184 { type: "null" },
185 ],
186 };
188​
189const generateSchemas = Effect.fn("generateSchemas")(function* (skipDownload: boolean) {
190 const { upstreamMetaPath, upstreamSchemaPath } = yield* getGeneratedPaths();
191​
192 yield* ensureGeneratedDir();
193​
194 if (!skipDownload) {
195 yield* Effect.log(`Downloading ACP schema assets for ${CURRENT_SCHEMA_RELEASE}`);
196 yield* downloadSchemas(CURRENT_SCHEMA_RELEASE);
197 }
198​
199 const upstreamSchema = yield* readJsonFile(UpstreamJsonSchemaSchema, upstreamSchemaPath);
200 const upstreamMeta = yield* readJsonFile(MetaJsonSchema, upstreamMetaPath);
201 const normalizedDefinitions = Object.fromEntries(
202 Object.entries(upstreamSchema.$defs).map(([name, schema]) => [
203 name,
204 normalizeNullableTypes(schema),
205 ]),
206 );
207​
208 const sortedEntries = Object.entries(normalizedDefinitions).toSorted(([left], [right]) =>
209 left.localeCompare(right),
210 );
211 const generatedEntries = new Map<string, string>();
212 const generator = makeJsonSchemaGenerator();
213​
214 for (const [name, schema] of sortedEntries) {
215 generator.addSchema(name, schema as never);
216 }
217​
218 const output = generator.generate("openapi-3.1", normalizedDefinitions as never, false).trim();
219 if (output.length > 0) {
220 for (const entry of collectSchemaEntries(output)) {
221 if (!generatedEntries.has(entry.name)) {
222 generatedEntries.set(entry.name, entry.code);
223 }
224 }
225 }
226​
227 const prelude = [
228 `// This file is generated by the effect-acp package. Do not edit manually.`,
229 `// Current ACP schema release: ${CURRENT_SCHEMA_RELEASE}`,
230 "",
231 ];
232​
233 const schemaOutput = [
234 ...prelude,
235 'import * as Schema from "effect/Schema";',
236 "",
237 [...generatedEntries.values()].join("\n\n"),
238 "",
239 ].join("\n");
240​
241 const metaOutput = [
242 ...prelude,
243 `export const AGENT_METHODS = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.agentMethods))(upstreamMeta.agentMethods)} as const;`,
244 "",
245 `export const CLIENT_METHODS = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.clientMethods))(upstreamMeta.clientMethods)} as const;`,
246 "",
247 `export const PROTOCOL_VERSION = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.version))(upstreamMeta.version)} as const;`,
248 "",
249 ].join("\n");
250​
251 yield* writeGeneratedFiles(schemaOutput, metaOutput);
252 yield* Effect.log(
253 `Generated ${generatedEntries.size} ACP schemas from ${CURRENT_SCHEMA_RELEASE}`,
254 );
255​
256 const { generatedDir } = yield* getGeneratedPaths();
257 yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
258 Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
259 Effect.flatMap((child) => child.exitCode),
260 Effect.tap((code) =>
261 code === 0
262 ? Effect.void
263 : Effect.fail<GenerateCommandError>({
264 _tag: "GenerateCommandError",
265 message: `oxfmt failed with exit code ${code}`,
266 }),
267 ),
268 );
269});
270​
271const generateCommand = Command.make(
272 "generate",
273 {
274 skipDownload: Flag.boolean("skip-download").pipe(Flag.withDefault(false)),
275 },
276 ({ skipDownload }) => generateSchemas(skipDownload),
277).pipe(Command.withDescription("Generate Effect ACP schemas from the pinned ACP release assets."));
278​
279const runtimeLayer = Layer.mergeAll(
280 Logger.layer([Logger.consolePretty()]),
281 NodeServices.layer,
282 FetchHttpClient.layer,
283);
284​
285Command.run(generateCommand, { version: "0.0.0" }).pipe(
286 Effect.scoped,
287 Effect.provide(runtimeLayer),
288 NodeRuntime.runMain,
289);