@niwa-labs/acp 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Niwa Labs contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # @niwa-labs/acp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Agent Client Protocol as niwa reads it: zod types generated from the schema of each supported SDK version, and the reading of a message against a snapshot, where a variant the snapshot does not know reads as a typed unknown instead of failing the session. It also holds the client side of a connection that the ACP harness kinds share: line framing, request ids, the calls in flight with their timeouts, and how far a failed call got.
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "@niwa-labs/acp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./src/index.ts"
8
+ },
9
+ "scripts": {
10
+ "gen": "bun scripts/gen-acp.ts"
11
+ },
12
+ "dependencies": {
13
+ "@niwa-labs/core": "0.0.0",
14
+ "@niwa-labs/harness": "0.0.0",
15
+ "zod": "^4.6.7"
16
+ },
17
+ "devDependencies": {
18
+ "json-schema-to-zod": "2.8.1"
19
+ }
20
+ }
@@ -0,0 +1,284 @@
1
+ /**
2
+ * Generates the zod types of one snapshot of the Agent Client Protocol from the JSON Schema the
3
+ * `@agentclientprotocol/sdk` package ships (`schema/schema.json`).
4
+ *
5
+ * bun scripts/gen-acp.ts <path to schema.json> <sdk version> <output .ts file>
6
+ *
7
+ * The snapshots in src/generated/ and the SDK versions their schemas come from:
8
+ * 0.14.1 — the version @zed-industries/claude-code-acp 0.16.2 pins
9
+ * 1.3.0 — the version the MiniMax Code fork pins; the upstream @minimax-ai/code 0.7.1 bundle serves
10
+ * the same method and update sets: `mcp/connect` without 1.6's `compaction_update`
11
+ *
12
+ * Every `$defs` entry becomes a zod schema and its output type of the same name. A variant that
13
+ * the schema writes as `allOf: [{ $ref }]` plus its own discriminator is flattened into one object,
14
+ * so each `oneOf` with a `discriminator` becomes a `z.discriminatedUnion`. A string definition whose
15
+ * name ends in `Id` becomes a branded string, and a schema that allows anything becomes `z.unknown()`.
16
+ *
17
+ * The schema marks each request, response and notification with its method (`x-method`) and the
18
+ * side that serves it (`x-side`). From those come the method-keyed unions of what the agent sends a
19
+ * client (`AgentToClientRequest`, `AgentToClientNotification`) and the method tables of both
20
+ * directions (`ClientToAgentMethods`, `AgentToClientMethods`), so a reply is typed by its method.
21
+ *
22
+ * A response says nothing of the method it answers, so the generic response unions (`AgentResponse`,
23
+ * `ClientResponse`) leave `result` open: a union of every result schema would take the first that
24
+ * fits, and most of them are all-optional objects that strip what they do not name. The schema of
25
+ * a result is chosen by the method of the request it answers, from `ClientToAgentResults` and
26
+ * `AgentToClientResults`.
27
+ */
28
+
29
+ import { readFileSync, writeFileSync } from "node:fs";
30
+ import { homedir } from "node:os";
31
+ import { jsonSchemaToZod, parseSchema } from "json-schema-to-zod";
32
+ import type { JsonSchema, JsonSchemaObject } from "json-schema-to-zod";
33
+
34
+ const [schemaPath, version, outPath] = process.argv.slice(2);
35
+ if (schemaPath === undefined || version === undefined || outPath === undefined) {
36
+ throw new Error("usage: bun scripts/gen-acp.ts <schema.json> <sdk version> <out.ts>");
37
+ }
38
+
39
+ const root = JSON.parse(readFileSync(schemaPath, "utf8")) as { $defs: Record<string, JsonSchemaObject> };
40
+ const defs = root.$defs;
41
+ const REF = "#/$defs/";
42
+ /** The schema's mark of a field whose unreadable value reads as absent. */
43
+ const TOLERANT = "x-deserialize-default-on-error";
44
+
45
+ function refName(schema: JsonSchema): string | undefined {
46
+ if (typeof schema !== "object") return undefined;
47
+ const ref = schema["$ref"];
48
+ return typeof ref === "string" && ref.startsWith(REF) ? ref.slice(REF.length) : undefined;
49
+ }
50
+
51
+ /** The one `$ref` of an `allOf` that holds nothing else, when it is that. */
52
+ function soleAllOfRef(schema: JsonSchemaObject): string | undefined {
53
+ const allOf = schema.allOf;
54
+ if (allOf === undefined || allOf.length !== 1) return undefined;
55
+ const [only] = allOf;
56
+ return only === undefined ? undefined : refName(only);
57
+ }
58
+
59
+ /** A plain object definition, whose properties a variant may take in. */
60
+ function plainObject(name: string): JsonSchemaObject | undefined {
61
+ const def = defs[name];
62
+ if (def === undefined || def.type !== "object" || def.properties === undefined) return undefined;
63
+ if (def.oneOf !== undefined || def.anyOf !== undefined || def.allOf !== undefined) return undefined;
64
+ return def;
65
+ }
66
+
67
+ /** The strings of a `oneOf` whose every member is one constant string: an enum, as the schema writes it. */
68
+ function constsOf(schema: JsonSchemaObject): string[] | undefined {
69
+ const members = schema.oneOf;
70
+ if (!Array.isArray(members) || members.length === 0) return undefined;
71
+ const literals = members.map((member) => (typeof member === "object" && typeof member.const === "string" ? member.const : undefined));
72
+ return literals.every((literal) => literal !== undefined) ? literals.filter((literal) => literal !== undefined) : undefined;
73
+ }
74
+
75
+ function simplify(schema: JsonSchema): JsonSchema {
76
+ if (typeof schema !== "object") return schema;
77
+ if (Array.isArray(schema)) return schema.map(simplify);
78
+ const out: JsonSchemaObject = {};
79
+ for (const [key, value] of Object.entries(schema)) {
80
+ if (key === "description" || key === "title" || key === "default" || key === "format") continue;
81
+ if ((key === "properties" || key === "patternProperties") && typeof value === "object" && value !== null) {
82
+ // A map of field names, whose keys are names, not annotations.
83
+ out[key] = Object.fromEntries(Object.entries(value).map(([field, sub]) => [field, simplify(sub as JsonSchema)]));
84
+ continue;
85
+ }
86
+ out[key] = typeof value === "object" && value !== null ? simplify(value as JsonSchema) : value;
87
+ }
88
+ const literals = constsOf(out);
89
+ if (literals !== undefined) return { type: "string", enum: literals };
90
+ const sole = soleAllOfRef(out);
91
+ if (sole !== undefined) {
92
+ const base = plainObject(sole);
93
+ if (out.properties !== undefined && base !== undefined) {
94
+ // A variant: the referenced object's fields plus its own discriminator.
95
+ const { allOf: _allOf, ...rest } = out;
96
+ const baseSimple = simplify(base) as JsonSchemaObject;
97
+ return {
98
+ ...rest,
99
+ type: "object",
100
+ properties: { ...baseSimple.properties, ...rest.properties },
101
+ required: [
102
+ ...((baseSimple.required as string[] | undefined) ?? []),
103
+ ...((rest.required as string[] | undefined) ?? []),
104
+ ],
105
+ };
106
+ }
107
+ if (out.properties === undefined && Object.keys(out).length === 1) return { $ref: REF + sole };
108
+ }
109
+ return spreadShared(out);
110
+ }
111
+
112
+ /**
113
+ * An object with fields of its own and a discriminated `oneOf` is a discriminated union whose
114
+ * every variant also has the shared fields.
115
+ */
116
+ function spreadShared(schema: JsonSchemaObject): JsonSchemaObject {
117
+ const { properties, required, oneOf, discriminator, type: _type, ...rest } = schema;
118
+ if (properties === undefined || !Array.isArray(oneOf) || discriminator === undefined) return schema;
119
+ const shared = (required as string[] | undefined) ?? [];
120
+ return {
121
+ ...rest,
122
+ discriminator,
123
+ oneOf: oneOf.map((variant) => {
124
+ if (typeof variant !== "object") throw new Error("a variant that is not an object");
125
+ return {
126
+ ...variant,
127
+ type: "object",
128
+ properties: { ...properties, ...variant.properties },
129
+ required: [...shared, ...((variant.required as string[] | undefined) ?? [])],
130
+ };
131
+ }),
132
+ };
133
+ }
134
+
135
+ /** The definitions a schema refers to. */
136
+ function refsOf(schema: JsonSchema, into: Set<string>): Set<string> {
137
+ if (typeof schema !== "object") return into;
138
+ const name = refName(schema);
139
+ if (name !== undefined) into.add(name);
140
+ for (const value of Object.values(schema)) {
141
+ if (typeof value === "object" && value !== null) refsOf(value as JsonSchema, into);
142
+ }
143
+ return into;
144
+ }
145
+
146
+ /** A generic response union: its successful member's `result` is left open, to be read by the method. */
147
+ function openResult(schema: JsonSchema): JsonSchema {
148
+ if (typeof schema !== "object" || !Array.isArray(schema.anyOf)) return schema;
149
+ return {
150
+ ...schema,
151
+ anyOf: schema.anyOf.map((member) => {
152
+ if (typeof member !== "object" || member.properties?.["result"] === undefined) return member;
153
+ return { ...member, properties: { ...member.properties, result: {} } };
154
+ }),
155
+ };
156
+ }
157
+
158
+ const simplified = new Map(
159
+ Object.entries(defs).map(([name, def]) => {
160
+ const simple = simplify(def);
161
+ return [name, name.endsWith("Response") ? openResult(simple) : simple];
162
+ }),
163
+ );
164
+
165
+ // Definitions in dependency order; a reference back into a cycle goes through `z.lazy`.
166
+ const order: string[] = [];
167
+ const state = new Map<string, "visiting" | "done">();
168
+ const lazy = new Set<string>();
169
+ function visit(name: string): void {
170
+ const seen = state.get(name);
171
+ if (seen === "done") return;
172
+ if (seen === "visiting") {
173
+ lazy.add(name);
174
+ return;
175
+ }
176
+ state.set(name, "visiting");
177
+ const schema = simplified.get(name);
178
+ if (schema === undefined) throw new Error(`no definition ${name}`);
179
+ for (const dep of [...refsOf(schema, new Set())].sort()) visit(dep);
180
+ state.set(name, "done");
181
+ order.push(name);
182
+ }
183
+ for (const name of [...simplified.keys()].sort()) visit(name);
184
+
185
+ function isBrandedId(name: string, schema: JsonSchema): boolean {
186
+ return name.endsWith("Id") && typeof schema === "object" && schema.type === "string";
187
+ }
188
+
189
+ function emit(name: string, schema: JsonSchema): string {
190
+ if (isBrandedId(name, schema)) return `z.string().brand<"Acp${name}">()`;
191
+ return jsonSchemaToZod(schema, {
192
+ zodVersion: 4,
193
+ withoutDescribes: true,
194
+ withoutDefaults: true,
195
+ parserOverride: (node, refs) => {
196
+ if (node[TOLERANT] === true) {
197
+ // The protocol reads a value of this field it cannot read as absent, never as a failure.
198
+ const { [TOLERANT]: _tolerant, ...strict } = node;
199
+ return `${parseSchema(strict, refs)}.optional().catch(undefined)`;
200
+ }
201
+ const ref = refName(node);
202
+ if (ref === undefined) return undefined;
203
+ return lazy.has(ref) ? `z.lazy((): z.ZodType<${ref}> => ${ref})` : ref;
204
+ },
205
+ });
206
+ }
207
+
208
+ const body = order
209
+ .map((name) => {
210
+ const schema = simplified.get(name);
211
+ if (schema === undefined) throw new Error(`no definition ${name}`);
212
+ return `export const ${name} = ${emit(name, schema).replaceAll("z.any()", "z.unknown()")};\nexport type ${name} = z.output<typeof ${name}>;`;
213
+ })
214
+ .join("\n\n");
215
+
216
+ interface Method {
217
+ readonly method: string;
218
+ readonly side: string;
219
+ readonly name: string;
220
+ }
221
+
222
+ const methods: Method[] = Object.entries(defs).flatMap(([name, def]) => {
223
+ const method = def["x-method"];
224
+ const side = def["x-side"];
225
+ return typeof method === "string" && typeof side === "string" ? [{ method, side, name }] : [];
226
+ });
227
+
228
+ /** The defs of one role (`Request`, `Response`, `Notification`) the given sides serve, by method. */
229
+ function byMethod(role: string, sides: readonly string[]): Method[] {
230
+ return methods
231
+ .filter((entry) => entry.name.endsWith(role) && sides.includes(entry.side))
232
+ .sort((a, b) => a.method.localeCompare(b.method));
233
+ }
234
+
235
+ function frameUnion(name: string, role: string, sides: readonly string[], id: boolean): string {
236
+ const variants = byMethod(role, sides).map(
237
+ (entry) =>
238
+ `z.object({ jsonrpc: z.literal("2.0").optional(), ${id ? "id: RequestId, " : ""}method: z.literal(${JSON.stringify(entry.method)}), params: ${entry.name} })`,
239
+ );
240
+ return `export const ${name} = z.discriminatedUnion("method", [\n ${variants.join(",\n ")},\n]);\nexport type ${name} = z.output<typeof ${name}>;`;
241
+ }
242
+
243
+ function methodTable(name: string, sides: readonly string[]): string {
244
+ const responses = new Map(byMethod("Response", sides).map((entry) => [entry.method, entry.name]));
245
+ const rows = byMethod("Request", sides).map((entry) => {
246
+ const result = responses.get(entry.method);
247
+ if (result === undefined) throw new Error(`no response for ${entry.method}`);
248
+ return ` ${JSON.stringify(entry.method)}: { readonly params: ${entry.name}; readonly result: ${result} };`;
249
+ });
250
+ return `export interface ${name} {\n${rows.join("\n")}\n}`;
251
+ }
252
+
253
+ /** The result schema of every request of the given sides, by method. */
254
+ function resultTable(name: string, sides: readonly string[]): string {
255
+ const rows = byMethod("Response", sides).map((entry) => ` ${JSON.stringify(entry.method)}: ${entry.name},`);
256
+ return `export const ${name} = {\n${rows.join("\n")}\n} as const;`;
257
+ }
258
+
259
+ const frames = [
260
+ "/** A request the agent sends the client, by method. */",
261
+ frameUnion("AgentToClientRequest", "Request", ["client", "both"], true),
262
+ "/** A notification the agent sends the client, by method. */",
263
+ frameUnion("AgentToClientNotification", "Notification", ["client", "both", "protocol"], false),
264
+ "/** The requests a client sends the agent: params and result, by method. */",
265
+ methodTable("ClientToAgentMethods", ["agent", "both"]),
266
+ "/** The requests the agent sends a client: params and result, by method. */",
267
+ methodTable("AgentToClientMethods", ["client", "both"]),
268
+ "/** The schema of the result of each request a client sends the agent, by method. */",
269
+ resultTable("ClientToAgentResults", ["agent", "both"]),
270
+ "/** The schema of the result of each request the agent sends a client, by method. */",
271
+ resultTable("AgentToClientResults", ["client", "both"]),
272
+ ].join("\n\n");
273
+
274
+ const header = `// GENERATED by scripts/gen-acp.ts — do not edit.
275
+ // Source: @agentclientprotocol/sdk ${version}, schema/schema.json
276
+ // Command: bun scripts/gen-acp.ts ${schemaPath.replace(homedir(), "~")} ${version} ${outPath}
277
+
278
+ import { z } from "zod";
279
+
280
+ /** The version of the @agentclientprotocol/sdk package whose schema this file was generated from. */
281
+ export const ACP_SDK_VERSION = ${JSON.stringify(version)};
282
+ `;
283
+
284
+ writeFileSync(outPath, `${header}\n${body}\n\n${frames}\n`);