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