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