@niwa-labs/harness-zcode 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 +21 -0
- package/README.md +8 -2
- package/package.json +20 -4
- package/scripts/gen-zcode.ts +384 -0
- package/src/config.ts +33 -0
- package/src/control.ts +1478 -0
- package/src/dispatch.ts +211 -0
- package/src/fixtures.ts +175 -0
- package/src/format.ts +153 -0
- package/src/index.ts +116 -0
- package/src/paths.ts +21 -0
- package/src/protocol/generated/zcode-protocol.ts +393 -0
- package/src/protocol/index.ts +230 -0
- package/src/reading.ts +506 -0
- package/src/reverse.ts +170 -0
- package/src/skills.ts +6 -0
- package/src/tools.ts +45 -0
- package/test/conformance.test.ts +29 -0
- package/test/control.test.ts +983 -0
- package/test/fixtures/zcode/captured-0.17.3.ndjson +23 -0
- package/test/fixtures/zcode/session-messages-0.17.3.json +241 -0
- package/test/live/control.test.ts +195 -0
- package/test/mode.test.ts +100 -0
- package/test/profile.test.ts +20 -0
- package/test/protocol.test.ts +437 -0
- package/test/reading.test.ts +332 -0
- package/tsconfig.json +8 -0
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,9 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @niwa-labs/harness-zcode
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The ZCode harness kind.
|
|
4
|
+
|
|
5
|
+
- Reading side: lists and reads sessions straight from the SQLite database ZCode writes, read-only.
|
|
6
|
+
- Control side: drives `zcode app-server --stdio` to start, resume, send, interrupt and ask, and answers the server's permission and question requests.
|
|
7
|
+
- `src/protocol/generated` holds the zod schemas of the app-server wire; `bun run gen` regenerates them from a ZCode checkout (`--zcode <path>`).
|
|
8
|
+
|
|
9
|
+
There is no insert side.
|
package/package.json
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niwa-labs/harness-zcode",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
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-zcode.ts"
|
|
11
|
+
},
|
|
12
|
+
"dependencies": {
|
|
13
|
+
"@niwa-labs/core": "0.0.0",
|
|
14
|
+
"@niwa-labs/harness": "0.0.0",
|
|
15
|
+
"@niwa-labs/sandbox": "0.0.0",
|
|
16
|
+
"zod": "^4.6.7"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@niwa-labs/testing": "0.0.0",
|
|
20
|
+
"json-schema-to-zod": "2.8.1"
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generates `src/protocol/generated/zcode-protocol.ts`: the zod schemas of the
|
|
3
|
+
* ZCode app-server wire, from ZCode's own zod protocol (`packages/shared/src/zcode-protocol`).
|
|
4
|
+
*
|
|
5
|
+
* bun scripts/gen-zcode.ts [--zcode <ZCode checkout>] (default: ~/projects/agents/ZCode)
|
|
6
|
+
*
|
|
7
|
+
* The route: ZCode's zod source is loaded as it is, `z.toJSONSchema` turns each wanted schema into
|
|
8
|
+
* JSON Schema, and the dev dependency `json-schema-to-zod` turns that into zod source. Two things
|
|
9
|
+
* are done to the JSON Schema on the way, both on purpose:
|
|
10
|
+
* - `additionalProperties: false` is dropped. ZCode's schemas are `.strict()` because its own
|
|
11
|
+
* host drops what it does not know; niwa must not lose a whole message when a newer ZCode adds a
|
|
12
|
+
* field. The unknown field is stripped, and the raw message is kept elsewhere.
|
|
13
|
+
* - `oneOf` (what a zod discriminated union becomes) is written `anyOf`: the converter would make `oneOf` an
|
|
14
|
+
* `unknown` checked by a refinement.
|
|
15
|
+
* - `{}` (ZCode's `z.unknown()`) becomes `z.unknown()`, not the `z.any()` the converter writes.
|
|
16
|
+
*
|
|
17
|
+
* ZCode's source needs its own workspace packages and a `zod`. A checkout has no `node_modules`
|
|
18
|
+
* and Bun would otherwise pick a `zod` from its cache or the home directory, so the sources are
|
|
19
|
+
* copied into a temporary directory whose `node_modules` points at this package's `zod`: the
|
|
20
|
+
* run is the same wherever it is made. Nothing is written to the checkout.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
24
|
+
import { homedir, tmpdir } from "node:os";
|
|
25
|
+
import { dirname, join, resolve } from "node:path";
|
|
26
|
+
import { spawnSync } from "node:child_process";
|
|
27
|
+
|
|
28
|
+
import { jsonSchemaToZod } from "json-schema-to-zod";
|
|
29
|
+
import { z } from "zod";
|
|
30
|
+
|
|
31
|
+
const ROOT = resolve(import.meta.dir, "..");
|
|
32
|
+
const OUT = join(ROOT, "src/protocol/generated/zcode-protocol.ts");
|
|
33
|
+
|
|
34
|
+
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
|
|
35
|
+
|
|
36
|
+
/** One schema of ZCode's, by the module it is exported from and its name there. */
|
|
37
|
+
interface Source {
|
|
38
|
+
readonly module: "protocol" | "legacy" | "validation" | "networkCapture";
|
|
39
|
+
readonly name: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const protocol = (name: string): Source => ({ module: "protocol", name });
|
|
43
|
+
|
|
44
|
+
/** A notification ZCode sends the client: the method, and the schema of its params. */
|
|
45
|
+
const NOTIFICATIONS: ReadonlyArray<{ readonly method: string; readonly id: string; readonly schema: Source }> = [
|
|
46
|
+
{ method: "session/event", id: "SessionEvent", schema: protocol("zcodeSessionEventSchema") },
|
|
47
|
+
{ method: "state.updated", id: "StateUpdated", schema: protocol("zcodeStateUpdatedNotificationSchema") },
|
|
48
|
+
{ method: "session/lifecycle/changed", id: "SessionLifecycleChanged", schema: protocol("sessionLifecycleSnapshotSchema") },
|
|
49
|
+
{ method: "startup/pluginsDegraded", id: "PluginsDegraded", schema: protocol("zcodePluginStartupDegradedSchema") },
|
|
50
|
+
{ method: "startup/storageState", id: "StorageState", schema: protocol("zcodeStorageStartupStateSchema") },
|
|
51
|
+
{
|
|
52
|
+
method: "interaction/providerRuntimeHeadersCancelled",
|
|
53
|
+
id: "ProviderRuntimeHeadersCancelled",
|
|
54
|
+
schema: protocol("zcodeProviderRuntimeHeadersCancelledSchema"),
|
|
55
|
+
},
|
|
56
|
+
{ method: "process/mcpTelemetry", id: "McpTelemetry", schema: protocol("zcodeMcpTelemetryEventSchema") },
|
|
57
|
+
{ method: "process/mcpResourceSamples", id: "McpResourceSamples", schema: protocol("zcodeMcpResourceSamplesSchema") },
|
|
58
|
+
{ method: "process/toolExecResource", id: "ToolExecResource", schema: protocol("zcodeToolExecResourceSchema") },
|
|
59
|
+
{ method: "plugins/operationProgress", id: "PluginOperationProgress", schema: protocol("zcodePluginOperationProgressNotificationSchema") },
|
|
60
|
+
{ method: "process/resourceSample", id: "ProcessResourceSample", schema: protocol("zcodeProcessResourceSampleSchema") },
|
|
61
|
+
{ method: "process/networkRequests", id: "NetworkRequests", schema: { module: "networkCapture", name: "networkCaptureBatchSchema" } },
|
|
62
|
+
{ method: "computer-use/operation-event", id: "ComputerUseOperationEvent", schema: protocol("zcodeComputerUseOperationEventSchema") },
|
|
63
|
+
];
|
|
64
|
+
|
|
65
|
+
/** A request ZCode makes of the client: the method, its params, and the answer it takes. */
|
|
66
|
+
const REQUESTS: ReadonlyArray<{ readonly method: string; readonly id: string; readonly params: Source; readonly result: Source }> = [
|
|
67
|
+
{
|
|
68
|
+
method: "session/requestRuntimePreferences",
|
|
69
|
+
id: "RuntimePreferences",
|
|
70
|
+
params: protocol("zcodeSessionRequestRuntimePreferencesParamsSchema"),
|
|
71
|
+
result: protocol("zcodeSessionRuntimePreferencesResultSchema"),
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
method: "interaction/requestPermission",
|
|
75
|
+
id: "Permission",
|
|
76
|
+
params: protocol("zcodePermissionRequestParamsSchema"),
|
|
77
|
+
result: { module: "legacy", name: "zcodePermissionResponseSchema" },
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
method: "interaction/requestUserInput",
|
|
81
|
+
id: "UserInput",
|
|
82
|
+
params: protocol("zcodeUserInputRequestParamsSchema"),
|
|
83
|
+
result: protocol("zcodeUserInputResponseSchema"),
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
method: "interaction/requestProviderRuntimeHeaders",
|
|
87
|
+
id: "ProviderRuntimeHeaders",
|
|
88
|
+
params: protocol("zcodeProviderRuntimeHeadersRequestParamsSchema"),
|
|
89
|
+
result: protocol("zcodeProviderRuntimeHeadersResponseSchema"),
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
method: "interaction/requestOfficialMcpAuthHeaders",
|
|
93
|
+
id: "OfficialMcpAuthHeaders",
|
|
94
|
+
params: protocol("zcodeOfficialMcpAuthHeadersRequestParamsSchema"),
|
|
95
|
+
result: protocol("zcodeOfficialMcpAuthHeadersResponseSchema"),
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
method: "interaction/requestCredentialCipher",
|
|
99
|
+
id: "CredentialCipher",
|
|
100
|
+
params: { module: "validation", name: "credentialCipherRequestSchema" },
|
|
101
|
+
result: { module: "validation", name: "credentialCipherReplySchema" },
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
method: "interaction/browserList",
|
|
105
|
+
id: "BrowserList",
|
|
106
|
+
params: protocol("zcodeBrowserListParamsSchema"),
|
|
107
|
+
result: protocol("zcodeBrowserListResultSchema"),
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
method: "interaction/browserExecute",
|
|
111
|
+
id: "BrowserExecute",
|
|
112
|
+
params: protocol("zcodeBrowserExecuteParamsSchema"),
|
|
113
|
+
result: protocol("zcodeBrowserExecuteResultSchema"),
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
method: "subagents/readRuntimeConfig",
|
|
117
|
+
id: "SubagentsRuntimeConfig",
|
|
118
|
+
params: protocol("zcodeSubagentsReadRuntimeConfigParamsSchema"),
|
|
119
|
+
result: protocol("subagentRuntimeConfigSchema"),
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
method: "bot/channel/reply",
|
|
123
|
+
id: "ChannelReply",
|
|
124
|
+
params: protocol("channelReplyRequestSchema"),
|
|
125
|
+
result: protocol("channelReplyResultSchema"),
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
method: "topic/resource/read",
|
|
129
|
+
id: "TopicResourceRead",
|
|
130
|
+
params: protocol("zcodeTopicResourceReadParamsSchema"),
|
|
131
|
+
result: protocol("zcodeTopicResourceReadResultSchema"),
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
method: "topic/resource/cancel",
|
|
135
|
+
id: "TopicResourceCancel",
|
|
136
|
+
params: protocol("zcodeTopicResourceCancelParamsSchema"),
|
|
137
|
+
result: protocol("zcodeTopicResourceCancelResultSchema"),
|
|
138
|
+
},
|
|
139
|
+
];
|
|
140
|
+
|
|
141
|
+
/** The app-control intents: one request each, `appControl/<intent>`, and `appControl/cancel`. */
|
|
142
|
+
const APP_CONTROL_INTENTS = [
|
|
143
|
+
"listProjects",
|
|
144
|
+
"listSessions",
|
|
145
|
+
"readSession",
|
|
146
|
+
"createSession",
|
|
147
|
+
"forkSession",
|
|
148
|
+
"sendToSession",
|
|
149
|
+
"waitSessions",
|
|
150
|
+
"interruptSession",
|
|
151
|
+
"renameSession",
|
|
152
|
+
"openSession",
|
|
153
|
+
"setSessionArchived",
|
|
154
|
+
"setSessionPinned",
|
|
155
|
+
] as const;
|
|
156
|
+
|
|
157
|
+
/** What niwa reads of the answers to its own calls: one message of a `session/messages` result. */
|
|
158
|
+
const CALLS: ReadonlyArray<{ readonly id: string; readonly schema: Source }> = [
|
|
159
|
+
{ id: "SessionMessage", schema: { module: "legacy", name: "zcodeMessageWithPartsSchema" } },
|
|
160
|
+
];
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Methods under `interaction/` that ZCode defines are all requests of the server to the client.
|
|
164
|
+
* One that is not in `REQUESTS` fails the generation: a snapshot with a new one is not silently left out.
|
|
165
|
+
*/
|
|
166
|
+
const REQUEST_FAMILY = /^interaction\/(request|browser)/;
|
|
167
|
+
|
|
168
|
+
function argument(name: string): string | undefined {
|
|
169
|
+
const at = process.argv.indexOf(name);
|
|
170
|
+
return at === -1 ? undefined : process.argv[at + 1];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const checkout = resolve((argument("--zcode") ?? join(homedir(), "projects/agents/ZCode")).replace(/^~/, homedir()));
|
|
174
|
+
|
|
175
|
+
function git(...args: string[]): string {
|
|
176
|
+
const run = spawnSync("git", ["-C", checkout, ...args], { encoding: "utf8" });
|
|
177
|
+
if (run.status !== 0) throw new Error(`git ${args.join(" ")} failed in ${checkout}: ${run.stderr}`);
|
|
178
|
+
return run.stdout.trim();
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function versionOf(path: string): string {
|
|
182
|
+
const manifest = JSON.parse(readFileSync(join(checkout, path), "utf8")) as { version?: string };
|
|
183
|
+
if (manifest.version === undefined) throw new Error(`${path} has no version`);
|
|
184
|
+
return manifest.version;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Copies the sources the protocol needs into a temporary directory that has its own `node_modules`. */
|
|
188
|
+
function stage(): string {
|
|
189
|
+
const dir = mkdtempSync(join(tmpdir(), "niwa-zcode-gen-"));
|
|
190
|
+
const packages = ["shared", "session-control", "model-option-map"];
|
|
191
|
+
for (const name of packages) {
|
|
192
|
+
mkdirSync(join(dir, "packages", name), { recursive: true });
|
|
193
|
+
cpSync(join(checkout, "packages", name, "package.json"), join(dir, "packages", name, "package.json"));
|
|
194
|
+
cpSync(join(checkout, "packages", name, "src"), join(dir, "packages", name, "src"), { recursive: true });
|
|
195
|
+
}
|
|
196
|
+
mkdirSync(join(dir, "node_modules/@zcode"), { recursive: true });
|
|
197
|
+
symlinkSync(dirname(realpathSync(Bun.resolveSync("zod/package.json", ROOT))), join(dir, "node_modules/zod"));
|
|
198
|
+
symlinkSync(join(dir, "packages/session-control"), join(dir, "node_modules/@zcode/session-control"));
|
|
199
|
+
symlinkSync(join(dir, "packages/model-option-map"), join(dir, "node_modules/@zcode/model-option-map"));
|
|
200
|
+
return dir;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Drops `additionalProperties: false`, and refuses what the converter cannot carry. */
|
|
204
|
+
function relax(node: Json, where: string): Json {
|
|
205
|
+
if (Array.isArray(node)) return node.map((item, index) => relax(item, `${where}[${index}]`));
|
|
206
|
+
if (typeof node !== "object" || node === null) return node;
|
|
207
|
+
const out: { [key: string]: Json } = {};
|
|
208
|
+
for (const [key, value] of Object.entries(node)) {
|
|
209
|
+
if (key === "$ref") throw new Error(`${where}: a $ref (a recursive schema) is not carried by the converter`);
|
|
210
|
+
if (key === "additionalProperties" && value === false) continue;
|
|
211
|
+
if (key === "$schema") continue;
|
|
212
|
+
// zod writes a discriminated union as `oneOf`, whose converter checks "exactly one" in a refinement
|
|
213
|
+
// and types the value `unknown`. The members of such a union exclude each other already, so `anyOf` says the same.
|
|
214
|
+
out[key === "oneOf" ? "anyOf" : key] = relax(value, `${where}.${key}`);
|
|
215
|
+
}
|
|
216
|
+
return out;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function toZod(schema: z.ZodType, where: string): string {
|
|
220
|
+
const json = z.toJSONSchema(schema, { io: "input", unrepresentable: "any", target: "draft-7" }) as Json;
|
|
221
|
+
const code = jsonSchemaToZod(relax(json, where) as never, { module: "none", zodVersion: 4 });
|
|
222
|
+
return code.replaceAll("z.any()", "z.unknown()");
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** A discriminated union of objects, as the discriminator and the members by its value. */
|
|
226
|
+
function membersOf(schema: z.ZodType): { discriminator: string; members: Array<{ value: string; schema: z.ZodType }> } | undefined {
|
|
227
|
+
const def = (schema as unknown as { _zod: { def: { type: string; discriminator?: string; options?: z.ZodType[] } } })._zod.def;
|
|
228
|
+
if (def.type !== "union" || def.discriminator === undefined || def.options === undefined) return undefined;
|
|
229
|
+
const discriminator = def.discriminator;
|
|
230
|
+
const members = def.options.map((option) => {
|
|
231
|
+
const shape = (option as unknown as { _zod: { def: { shape: Record<string, z.ZodType> } } })._zod.def.shape;
|
|
232
|
+
const literal = shape[discriminator] as unknown as { _zod: { def: { values: unknown[] } } } | undefined;
|
|
233
|
+
return { value: literal?._zod.def.values[0], schema: option };
|
|
234
|
+
});
|
|
235
|
+
// A union on a boolean (`ok`, `headersApplied`) stays one schema: its members have no name to take.
|
|
236
|
+
const named = members.flatMap((member) => (typeof member.value === "string" ? [{ value: member.value, schema: member.schema }] : []));
|
|
237
|
+
if (named.length !== members.length) return undefined;
|
|
238
|
+
return { discriminator, members: named };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const pascal = (value: string): string => value.replace(/(^|[^A-Za-z0-9]+)([A-Za-z0-9])/g, (_, __, letter: string) => letter.toUpperCase());
|
|
242
|
+
|
|
243
|
+
interface Output {
|
|
244
|
+
readonly lines: string[];
|
|
245
|
+
readonly names: Set<string>;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function declare(out: Output, name: string, code: string): void {
|
|
249
|
+
if (out.names.has(name)) throw new Error(`${name} is declared twice`);
|
|
250
|
+
out.names.add(name);
|
|
251
|
+
out.lines.push(`export const ${name}Schema = ${code};`, `export type ${name} = z.output<typeof ${name}Schema>;`, "");
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** A schema as a declaration; a union on a discriminator is a union of declared members, so each is a type of its own. */
|
|
255
|
+
function emit(out: Output, name: string, schema: z.ZodType): { discriminator: string; values: string[] } | undefined {
|
|
256
|
+
const union = membersOf(schema);
|
|
257
|
+
if (union === undefined) {
|
|
258
|
+
declare(out, name, toZod(schema, name));
|
|
259
|
+
return undefined;
|
|
260
|
+
}
|
|
261
|
+
const parts: string[] = [];
|
|
262
|
+
for (const member of union.members) {
|
|
263
|
+
const part = `${name}${pascal(member.value)}`;
|
|
264
|
+
declare(out, part, toZod(member.schema, part));
|
|
265
|
+
parts.push(`${part}Schema`);
|
|
266
|
+
}
|
|
267
|
+
declare(out, name, `z.discriminatedUnion(${JSON.stringify(union.discriminator)}, [${parts.join(", ")}])`);
|
|
268
|
+
return { discriminator: union.discriminator, values: union.members.map((member) => member.value) };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const dir = stage();
|
|
272
|
+
try {
|
|
273
|
+
const modules = {
|
|
274
|
+
protocol: (await import(join(dir, "packages/shared/src/zcode-protocol/index.ts"))) as Record<string, unknown>,
|
|
275
|
+
legacy: (await import(join(dir, "packages/shared/src/zcode-protocol-legacy-types.ts"))) as Record<string, unknown>,
|
|
276
|
+
validation: (await import(join(dir, "packages/shared/src/validation.ts"))) as Record<string, unknown>,
|
|
277
|
+
networkCapture: (await import(join(dir, "packages/shared/src/networkCapture.ts"))) as Record<string, unknown>,
|
|
278
|
+
};
|
|
279
|
+
const pick = (source: Source): z.ZodType => {
|
|
280
|
+
const found = modules[source.module][source.name];
|
|
281
|
+
if (!(found instanceof z.ZodType)) throw new Error(`${source.module} exports no schema ${source.name}`);
|
|
282
|
+
return found;
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
// The snapshot must hold every notification and every request-family method it names.
|
|
286
|
+
const methods = modules.protocol["zcodeProtocolMethods"] as Record<string, string>;
|
|
287
|
+
const notifications = modules.protocol["zcodeProtocolNotifications"] as Record<string, string>;
|
|
288
|
+
const knownRequests = new Set([...REQUESTS.map((request) => request.method), ...APP_CONTROL_INTENTS.map((intent) => `appControl/${intent}`)]);
|
|
289
|
+
for (const method of Object.values(methods)) {
|
|
290
|
+
if (REQUEST_FAMILY.test(method) && !knownRequests.has(method)) throw new Error(`the request ${method} is not in the generator's list`);
|
|
291
|
+
}
|
|
292
|
+
const knownNotifications = new Set(NOTIFICATIONS.map((notification) => notification.method));
|
|
293
|
+
for (const method of Object.values(notifications)) {
|
|
294
|
+
if (!knownNotifications.has(method)) throw new Error(`the notification ${method} is not in the generator's list`);
|
|
295
|
+
}
|
|
296
|
+
if (!knownNotifications.has(methods["sessionLifecycleChanged"] ?? "") || !knownNotifications.has(methods["computerUseOperationEvent"] ?? "")) {
|
|
297
|
+
throw new Error("a notification the method table names is not in the generator's list");
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const v4 = (await import(join(dir, "packages/shared/src/zcode-protocol-v4/transport.ts"))) as Record<string, unknown>;
|
|
301
|
+
const v4Notifications = Object.values(v4["V4_NOTIFICATIONS"] as Record<string, string>);
|
|
302
|
+
|
|
303
|
+
const out: Output = { lines: [], names: new Set() };
|
|
304
|
+
const unions: Record<string, { discriminator: string; values: string[] }> = {};
|
|
305
|
+
const notificationTable: string[] = [];
|
|
306
|
+
for (const notification of NOTIFICATIONS) {
|
|
307
|
+
const union = emit(out, `Notification${notification.id}`, pick(notification.schema));
|
|
308
|
+
if (union !== undefined) unions[`Notification${notification.id}`] = union;
|
|
309
|
+
notificationTable.push(` ${JSON.stringify(notification.method)}: Notification${notification.id}Schema,`);
|
|
310
|
+
}
|
|
311
|
+
const requestTable: string[] = [];
|
|
312
|
+
const answerTable: string[] = [];
|
|
313
|
+
const requests = [
|
|
314
|
+
...REQUESTS,
|
|
315
|
+
...APP_CONTROL_INTENTS.map((intent) => {
|
|
316
|
+
const contract = (modules.protocol["appControlProtocol"] as Record<string, { method: string; params: z.ZodType; result: z.ZodType }>)[intent];
|
|
317
|
+
if (contract === undefined) throw new Error(`appControlProtocol has no ${intent}`);
|
|
318
|
+
return { method: contract.method, id: `AppControl${pascal(intent)}`, params: contract.params, result: contract.result };
|
|
319
|
+
}),
|
|
320
|
+
{
|
|
321
|
+
method: modules.protocol["appControlCancelMethod"] as string,
|
|
322
|
+
id: "AppControlCancel",
|
|
323
|
+
params: pick(protocol("appControlCancelParamsSchema")),
|
|
324
|
+
result: pick(protocol("appControlCancelResultSchema")),
|
|
325
|
+
},
|
|
326
|
+
];
|
|
327
|
+
for (const request of requests) {
|
|
328
|
+
const params = request.params instanceof z.ZodType ? request.params : pick(request.params);
|
|
329
|
+
const result = request.result instanceof z.ZodType ? request.result : pick(request.result);
|
|
330
|
+
emit(out, `Request${request.id}Params`, params);
|
|
331
|
+
emit(out, `Request${request.id}Answer`, result);
|
|
332
|
+
requestTable.push(` ${JSON.stringify(request.method)}: Request${request.id}ParamsSchema,`);
|
|
333
|
+
answerTable.push(` ${JSON.stringify(request.method)}: Request${request.id}AnswerSchema,`);
|
|
334
|
+
}
|
|
335
|
+
for (const call of CALLS) emit(out, call.id, pick(call.schema));
|
|
336
|
+
|
|
337
|
+
const sessionEvent = unions["NotificationSessionEvent"];
|
|
338
|
+
if (sessionEvent === undefined) throw new Error("the session event is not a union on a discriminator");
|
|
339
|
+
|
|
340
|
+
const commit = git("rev-parse", "HEAD");
|
|
341
|
+
const subject = git("log", "-1", "--format=%s");
|
|
342
|
+
const header = [
|
|
343
|
+
"// GENERATED by scripts/gen-zcode.ts: do not edit. Regenerate with:",
|
|
344
|
+
"// bun scripts/gen-zcode.ts --zcode <ZCode checkout>",
|
|
345
|
+
"//",
|
|
346
|
+
`// Upstream: ZCode ${versionOf("package.json")} (apps/zcode-cli ${versionOf("apps/zcode-cli/package.json")}), commit ${commit} ("${subject}"),`,
|
|
347
|
+
"// packages/shared/src/zcode-protocol (zod, converted with z.toJSONSchema, then json-schema-to-zod).",
|
|
348
|
+
"// Objects are not strict (a field a newer ZCode adds is dropped, not a reason to lose the message);",
|
|
349
|
+
"// What ZCode leaves open (z.unknown()) stays unknown, never any. Refinements and transforms are not carried.",
|
|
350
|
+
"",
|
|
351
|
+
'import { z } from "zod";',
|
|
352
|
+
"",
|
|
353
|
+
];
|
|
354
|
+
const tables = [
|
|
355
|
+
"/** The notifications ZCode sends, by method: the schema of their params. */",
|
|
356
|
+
"export const NOTIFICATION_SCHEMAS = {",
|
|
357
|
+
...notificationTable,
|
|
358
|
+
"} as const;",
|
|
359
|
+
"",
|
|
360
|
+
"/** The requests ZCode makes of the client, by method: the schema of their params. */",
|
|
361
|
+
"export const REQUEST_SCHEMAS = {",
|
|
362
|
+
...requestTable,
|
|
363
|
+
"} as const;",
|
|
364
|
+
"",
|
|
365
|
+
"/** The requests ZCode makes of the client, by method: the schema of the answer it takes. */",
|
|
366
|
+
"export const ANSWER_SCHEMAS = {",
|
|
367
|
+
...answerTable,
|
|
368
|
+
"} as const;",
|
|
369
|
+
"",
|
|
370
|
+
"/** The types of the session event, by the discriminator the snapshot names. */",
|
|
371
|
+
`export const SESSION_EVENT_TYPES = ${JSON.stringify(sessionEvent.values)} as const;`,
|
|
372
|
+
"",
|
|
373
|
+
"/** The notifications of ZCode's v4 side channel (the conversation view of its own desktop). They have no meaning for a session driver. */",
|
|
374
|
+
`export const V4_NOTIFICATION_METHODS = ${JSON.stringify(v4Notifications)} as const;`,
|
|
375
|
+
"",
|
|
376
|
+
];
|
|
377
|
+
mkdirSync(dirname(OUT), { recursive: true });
|
|
378
|
+
writeFileSync(OUT, [...header, ...out.lines, ...tables].join("\n"));
|
|
379
|
+
console.log(`wrote ${OUT} (${out.names.size} schemas)`);
|
|
380
|
+
} finally {
|
|
381
|
+
rmSync(dir, { recursive: true, force: true });
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
if (!existsSync(OUT)) throw new Error("nothing was written");
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The user's config file of a ZCode installation, read the way ZCode reads it, for the one thing
|
|
3
|
+
* niwa needs from it: `permission.mode`, the mode a session gets when nothing else names one.
|
|
4
|
+
*
|
|
5
|
+
* Only this file counts. ZCode reads a project's `zcode.json` and `.zcode/config.json` through a
|
|
6
|
+
* schema that keeps the extension declarations (mcp, hooks, skills, commands, plugins) and strips
|
|
7
|
+
* the rest, `permission` among it; and its `ZCODE_*` environment names no mode. A file that is not
|
|
8
|
+
* a JSON object, or whose `permission.mode` is not one of ZCode's modes, is not loaded at all.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
12
|
+
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
|
|
15
|
+
import { configPathOf } from "./paths.ts";
|
|
16
|
+
|
|
17
|
+
/** The modes ZCode's config schema accepts for `permission.mode`. */
|
|
18
|
+
const ZCODE_MODES = ["plan", "build", "edit", "yolo", "guarded", "auto"] as const;
|
|
19
|
+
|
|
20
|
+
const ConfigFileSchema = z.looseObject({
|
|
21
|
+
permission: z.looseObject({ mode: z.enum(ZCODE_MODES).optional() }).optional(),
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
/** `permission.mode` of the config file under `home`; `undefined` when the file is absent, unreadable, invalid, or names none. */
|
|
25
|
+
export function configuredModeOf(home: string): string | undefined {
|
|
26
|
+
const path = configPathOf(home);
|
|
27
|
+
if (!existsSync(path)) return undefined;
|
|
28
|
+
try {
|
|
29
|
+
return ConfigFileSchema.parse(JSON.parse(readFileSync(path, "utf-8")) as unknown).permission?.mode;
|
|
30
|
+
} catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|