zcode-agent 0.0.0-stage → 1.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.
@@ -0,0 +1,418 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // zcode — CLI entry: argv parsing + command dispatch. Parsing rejects bad
4
+ // input (exit 2) before any engine spawn or session record exists.
5
+ const { normalizeModel, unknownModelMessage, normalizeEffort, EFFORT_LEVELS, DEFAULT_MODEL } = require('../lib/models.js');
6
+
7
+ const USAGE = `usage:
8
+ zcode-agent task [options] <objective…> execute a task contract, verify it, hand back
9
+ zcode-agent [run] [options] <prompt…> one-shot turn (prompt via stdin when piped)
10
+ zcode-agent agent [options] <instructions…> turn that MUST dispatch a subagent
11
+ zcode-agent resume <id> [message…] continue a session (answer, follow-up, retry)
12
+ zcode-agent status [<id>] [--all] [--json] one session in detail, or the 15 most recent (--all: every session)
13
+ zcode-agent wait <id…> [--any] [--json] block until sessions finish; print handbacks
14
+ zcode-agent watch [<id…> | --plan <name>] [--stall-min n]
15
+ live one-line-per-session view with cost (no model tokens); exits when all finish
16
+ zcode-agent cost [<dir>] [--app] [--json] GLM cost of the zcode-agent sessions in a directory (default: current dir) at
17
+ API list price; --app adds the desktop app's sessions there
18
+ zcode-agent result <id> [--full] [--json] print a finished session's handback (brief by default)
19
+ zcode-agent cancel <id> [--json] stop a running session
20
+ zcode-agent plan check <file> validate a plan file (ids, after, cycles, owns, effort)
21
+ zcode-agent plan run <file> [--preflight] [--detach] [--timeout-ms n] [--id name] [--json]
22
+ run a DAG of task sessions (see "plan" below)
23
+ zcode-agent plan wait|status <name> [--timeout-ms n] [--json]
24
+ one summary line: {type:"plan",name,status,sessions,briefs}
25
+ zcode-agent plan resume <name> [message…] [--session <id>]
26
+ resume failed/partial/blocked sessions, restart supervision
27
+ zcode-agent login store a Z.ai API key piped on stdin (optional
28
+ with ZAI_API_KEY or the ZCode app's key)
29
+ zcode-agent doctor [--json] [--install-browser]
30
+ engine, key, inherited setup and browser report
31
+ zcode-agent skills [install|uninstall] [claude|codex]
32
+ install the orchestrator skills (default: status)
33
+
34
+ session:
35
+ --id <id> name the session (letters, digits, . _ -); default zc-<random>.
36
+ An existing id is never re-run: use resume.
37
+ --label <text> free-form label shown in status
38
+ --detach start in the background, print the id, exit 0
39
+ --cwd <dir> workspace (default: current dir)
40
+ --owns <path|glob> repeatable: paths this session may change (relative to
41
+ --cwd). Default: the whole workspace. Overlapping
42
+ ownership with a running session is refused (exit 7)
43
+ --allow-overlap start despite overlapping ownership
44
+
45
+ task contract (task only):
46
+ --task <file|-> JSON contract or markdown brief (- = stdin)
47
+ --accept <text> repeatable acceptance criterion
48
+ --check <command> repeatable shell check zcode-agent runs after the work
49
+ --touch <path|glob> repeatable: minimal edits allowed outside --owns; reported
50
+ as "touched", not a scope violation. Refused (exit 7) if a
51
+ running session owns a matching path; reserves nothing
52
+ --file <path> repeatable relevant file to read first (a file also given
53
+ as --context @file is inlined once, not listed twice)
54
+ --context <text|@f> repeatable extra context (references, background)
55
+ --decision <text> repeatable binding decision the orchestrator made (the
56
+ executor implements it exactly and must not guess others)
57
+ --decisions <@f|text> binding decisions from a file (same list as --decision)
58
+ --preflight read-only turn: the executor lists the open questions it
59
+ would otherwise guess (blocked + questions, or completed
60
+ "no open questions"); no edits, no checks. Then
61
+ zcode-agent resume <id> "<answers>" executes the task
62
+ --unit "n: goal [owns a,b]" repeatable: one subagent per unit inside this
63
+ session; owns must lie within --owns and be disjoint
64
+ --visual <criterion> repeatable: after the work an independent image-capable
65
+ verifier (GLM-5.3-Flash, fresh session) serves the app on
66
+ $ZCODE_PORT, screenshots it and judges each criterion
67
+ --viewport <WxH> repeatable viewport for --visual (default 390x844, 1440x900)
68
+ --serve <cmd> command that serves the app for --visual (honours $ZCODE_PORT)
69
+ --max-repairs <n> repair turns after failing checks (default 2)
70
+ --check-timeout-ms <n> per-check timeout (default 300000)
71
+
72
+ plan (zcode-agent plan run <plan.json>):
73
+ plan.json {cwd?, decisions?, context?, files?, model?, effort?, limits?,
74
+ sessions:[{id, after?:[ids], label?, ...task contract keys}]}; the
75
+ top-level decisions/context/files are prepended to every
76
+ session. A session starts when everything it is "after" has
77
+ completed; sessions that can run together must own disjoint
78
+ paths. A session ending non-completed marks its downstream
79
+ "skipped"; the others continue
80
+ --preflight plan run: read-only preflight of every session ("<id>.pre"),
81
+ prints the questions as one brief per session (exit 10 if any)
82
+ --detach plan run/resume: supervise in a background process
83
+ --id <name> plan name (default: the file's basename)
84
+ --session <id> plan resume: only this session
85
+
86
+ execution:
87
+ --model <id> glm-5.3 | glm-5.3-flash (+aliases). default: glm-5.3-flash
88
+ --effort <level> low | high | max for both models (zcode-agent doctor lists the
89
+ engine's levels per model); an unsupported level exits 2
90
+ before any spawn. default: max
91
+ --timeout-ms <n> whole invocation incl. checks/repairs (default 600000;
92
+ task default 7200000 = 2 h)
93
+ --profile <name> subagent profile (agent command; default general-purpose)
94
+ --mcp <json|@f> add MCP servers (repeatable), on top of the desktop's
95
+ --hermetic don't inherit the ZCode app's MCP servers and skills
96
+ (inherited by default; OAuth-only remote servers never are)
97
+ --no-browser drop the desktop's playwright MCP server (on by default)
98
+ --mcp-list print the effective MCP server set as JSON and exit
99
+ --skills <dir> add skills (repeatable): one skill dir or a root of them
100
+ --no-skills empty skill set
101
+ --inherit-desktop also give the executor the desktop's AGENTS.md, plugins
102
+ and agent profiles (off by default)
103
+
104
+ output:
105
+ --json NDJSON events on stdout; final line is the compact brief
106
+ {"type":"result","schema":"zcode.brief/1",…}
107
+ --full with --json (and result/wait): the full record instead
108
+ (schema zcode.result/1; result.json on disk is always full)
109
+ --any wait: return as soon as the FIRST id finishes
110
+ --quiet no progress: no stderr feed; with --json only the result line;
111
+ usage errors are always a single line
112
+ --thinking / --no-thinking mirror reasoning to stderr (run: on, task: off)
113
+ --stream task --json: include text/reasoning deltas in the events
114
+ --include-reasoning full reasoning text in the result
115
+ -p, --prompt <t> prompt text (alias for positional prompt)
116
+ --session <id> run: continue a session (zcode-agent id or engine sess_ id)
117
+ --install-browser doctor: install the default Playwright server's Chromium
118
+ --version, --help
119
+
120
+ exit codes: 0 completed · 2 usage · 3 no key · 4 no engine · 5 failed ·
121
+ 6 agent: no subagent · 7 workspace conflict / session busy · 8 partial or
122
+ checks failing · 9 unverified · 10 blocked · 124 timeout · 130 cancelled`;
123
+
124
+ function fail(code, message) {
125
+ process.stderr.write(`zcode-agent: ${message}\n`);
126
+ process.exit(code);
127
+ }
128
+
129
+ function readFileOrFail(file, flag) {
130
+ try {
131
+ return require('node:fs').readFileSync(file, 'utf8');
132
+ } catch {
133
+ return fail(2, `${flag} file "${file}" could not be read.`);
134
+ }
135
+ }
136
+
137
+ // --mcp accepts inline JSON or @file mapping server names to definitions.
138
+ function parseMcpSpec(value) {
139
+ const text = value.startsWith('@') ? readFileOrFail(value.slice(1), '--mcp') : value;
140
+ let parsed;
141
+ try {
142
+ parsed = JSON.parse(text);
143
+ } catch (err) {
144
+ fail(2, `--mcp spec must be valid JSON mapping server names to definitions: ${err.message}`);
145
+ }
146
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
147
+ fail(2, `--mcp spec must be valid JSON mapping server names to definitions, got ${Array.isArray(parsed) ? 'an array' : `a ${typeof parsed}`}.`);
148
+ }
149
+ for (const [name, def] of Object.entries(parsed)) {
150
+ if (!def || typeof def !== 'object' || Array.isArray(def)) {
151
+ fail(2, `--mcp server "${name}" must be an object (e.g. {"type":"stdio","command":...,"args":[...]}).`);
152
+ }
153
+ }
154
+ return parsed;
155
+ }
156
+
157
+ const COMMANDS = new Set(['run', 'task', 'agent', 'resume', 'status', 'list', 'wait', 'watch', 'cost', 'cancel', 'login', 'doctor', 'skills', 'result', 'plan', '__plan', '__exec']);
158
+ const TASK_ONLY = new Set(['task', 'accept', 'check', 'file', 'context', 'touch', 'maxRepairs', 'checkTimeoutMs', 'decisions', 'units', 'visual', 'viewports', 'serve', 'preflight']);
159
+ const FULL_COMMANDS = new Set(['run', 'task', 'agent', 'resume', 'wait', 'result', '__exec']);
160
+ const START_ONLY = new Set(['id', 'label', 'owns', 'touch', 'preflight', 'allowOverlap', 'mcpSpecs', 'mcpInherit', 'hermetic', 'noBrowser', 'skillsDirs', 'noSkills', 'inheritDesktop', 'profile', 'cwd']);
161
+
162
+ function parseArgv(argv) {
163
+ const out = {
164
+ command: 'run',
165
+ prompts: [],
166
+ given: new Set(),
167
+ flags: {
168
+ model: DEFAULT_MODEL,
169
+ effort: 'max',
170
+ cwd: process.cwd(),
171
+ json: false,
172
+ fresh: false,
173
+ timeoutMs: undefined,
174
+ profile: 'general-purpose',
175
+ prompt: undefined,
176
+ session: undefined,
177
+ id: undefined,
178
+ label: undefined,
179
+ detach: false,
180
+ task: undefined,
181
+ accept: [],
182
+ check: [],
183
+ file: [],
184
+ context: [],
185
+ owns: [],
186
+ touch: [],
187
+ decisions: [],
188
+ units: [],
189
+ visual: [],
190
+ viewports: [],
191
+ serve: undefined,
192
+ preflight: false,
193
+ allowOverlap: false,
194
+ maxRepairs: undefined,
195
+ checkTimeoutMs: undefined,
196
+ mcpSpecs: [],
197
+ mcpInherit: false, // accepted for pre-1.0 callers: inheriting is the default now
198
+ hermetic: false,
199
+ noBrowser: false,
200
+ mcpList: false,
201
+ skillsDirs: [],
202
+ noSkills: false,
203
+ inheritDesktop: false,
204
+ includeReasoning: false,
205
+ quiet: false,
206
+ thinking: undefined,
207
+ stream: false,
208
+ plan: undefined,
209
+ stallMin: undefined,
210
+ full: false,
211
+ any: false,
212
+ all: false,
213
+ app: false,
214
+ installBrowser: false,
215
+ },
216
+ };
217
+ const valueFlags = new Map([
218
+ ['--model', 'model'], ['--effort', 'effort'], ['--cwd', 'cwd'], ['--profile', 'profile'],
219
+ ['--timeout-ms', 'timeoutMs'], ['-p', 'prompt'], ['--prompt', 'prompt'], ['--session', 'session'],
220
+ ['--id', 'id'], ['--label', 'label'], ['--task', 'task'], ['--max-repairs', 'maxRepairs'],
221
+ ['--check-timeout-ms', 'checkTimeoutMs'], ['--serve', 'serve'], ['--plan', 'plan'], ['--stall-min', 'stallMin'],
222
+ ]);
223
+ const listFlags = new Map([
224
+ ['--mcp', 'mcpSpecs'], ['--skills', 'skillsDirs'], ['--accept', 'accept'], ['--check', 'check'],
225
+ ['--file', 'file'], ['--context', 'context'], ['--owns', 'owns'], ['--touch', 'touch'],
226
+ ['--decision', 'decisions'], ['--decisions', 'decisions'], ['--unit', 'units'], ['--visual', 'visual'],
227
+ ['--viewport', 'viewports'],
228
+ ]);
229
+ const boolFlags = new Map([
230
+ ['--json', ['json', true]], ['--fresh', ['fresh', true]], ['--mcp-inherit', ['mcpInherit', true]], ['--hermetic', ['hermetic', true]],
231
+ ['--mcp-list', ['mcpList', true]], ['--no-skills', ['noSkills', true]], ['--inherit-desktop', ['inheritDesktop', true]], ['--no-browser', ['noBrowser', true]],
232
+ ['--include-reasoning', ['includeReasoning', true]], ['--quiet', ['quiet', true]],
233
+ ['--detach', ['detach', true]], ['--allow-overlap', ['allowOverlap', true]],
234
+ ['--thinking', ['thinking', true]], ['--no-thinking', ['thinking', false]], ['--stream', ['stream', true]],
235
+ ['--full', ['full', true]], ['--any', ['any', true]], ['--all', ['all', true]], ['--app', ['app', true]], ['--install-browser', ['installBrowser', true]], ['--preflight', ['preflight', true]],
236
+ ]);
237
+ const numeric = (flag, value, { min = 1 } = {}) => {
238
+ const n = Number(value);
239
+ if (!Number.isFinite(n) || n < min) fail(2, `${flag} must be a number >= ${min}, got "${value}".`);
240
+ return n;
241
+ };
242
+
243
+ for (let i = 0; i < argv.length; i++) {
244
+ const arg = argv[i];
245
+ if (valueFlags.has(arg) || listFlags.has(arg)) {
246
+ const key = valueFlags.get(arg) || listFlags.get(arg);
247
+ const value = argv[++i];
248
+ if (value === undefined) fail(2, `option ${arg} requires a value.`);
249
+ out.given.add(key);
250
+ if (key === 'timeoutMs' || key === 'checkTimeoutMs') out.flags[key] = numeric(arg, value);
251
+ else if (key === 'stallMin') out.flags[key] = numeric(arg, value, { min: 0 });
252
+ else if (key === 'maxRepairs') out.flags[key] = numeric(arg, value, { min: 0 });
253
+ else if (key === 'mcpSpecs') out.flags.mcpSpecs.push(parseMcpSpec(value));
254
+ else if (key === 'skillsDirs') {
255
+ if (!isDirectory(value)) fail(2, `--skills requires an existing directory, got "${value}".`);
256
+ out.flags.skillsDirs.push(value);
257
+ } else if (listFlags.has(arg)) out.flags[key].push(value);
258
+ else if (!value.trim()) fail(2, `${arg} requires a non-empty value.`);
259
+ else out.flags[key] = value.trim();
260
+ continue;
261
+ }
262
+ if (boolFlags.has(arg)) {
263
+ const [key, v] = boolFlags.get(arg);
264
+ out.given.add(key);
265
+ out.flags[key] = v;
266
+ continue;
267
+ }
268
+ if (arg === '--help' || arg === '-h') {
269
+ // Scan the rest of argv for the command: `zcode --help task` works too.
270
+ let command = out.commandSet ? out.command : null;
271
+ if (!command) for (const a of argv) if (COMMANDS.has(a) && !a.startsWith('__')) { command = a === 'list' ? 'status' : a; break; }
272
+ const text = command && require('../lib/help.js').commandHelp(command);
273
+ process.stdout.write((text || USAGE) + '\n');
274
+ process.exit(0);
275
+ }
276
+ if (arg === '--version') {
277
+ process.stdout.write(require('../package.json').version + '\n');
278
+ process.exit(0);
279
+ }
280
+ if (arg === '--') {
281
+ out.prompts.push(...argv.slice(i + 1));
282
+ break;
283
+ }
284
+ if (arg.startsWith('--') && arg.length > 2) {
285
+ const hint = suggestFlag(arg, [...valueFlags.keys(), ...listFlags.keys(), ...boolFlags.keys()]);
286
+ fail(2, `unknown flag ${arg} (${hint ? `did you mean ${hint}?` : 'see zcode-agent --help'})`);
287
+ }
288
+ if (out.prompts.length === 0 && out.command === 'run' && !out.commandSet && COMMANDS.has(arg)) {
289
+ out.command = arg === 'list' ? 'status' : arg;
290
+ out.commandSet = true;
291
+ continue;
292
+ }
293
+ out.prompts.push(arg);
294
+ }
295
+
296
+ const cmd = out.command;
297
+ if (out.flags.prompt !== undefined) out.prompts.unshift(out.flags.prompt);
298
+ if (cmd !== 'task') {
299
+ for (const key of TASK_ONLY) {
300
+ if (cmd === 'plan' && key === 'preflight') continue;
301
+ if (out.given.has(key) && !(cmd === 'resume' && (key === 'maxRepairs' || key === 'checkTimeoutMs'))) {
302
+ fail(2, `--${flagName(key)} is only valid with "zcode-agent task".`);
303
+ }
304
+ }
305
+ }
306
+ if (cmd === 'plan' || cmd === '__plan') {
307
+ for (const key of ['label', 'owns', 'touch', 'allowOverlap', 'model', 'effort', 'profile']) {
308
+ if (out.given.has(key)) fail(2, `--${flagName(key)} is not valid with "zcode-agent plan"; set it in the plan file.`);
309
+ }
310
+ }
311
+ if (cmd === 'resume' || cmd === '__exec') {
312
+ for (const key of START_ONLY) {
313
+ if (out.given.has(key)) fail(2, `--${flagName(key)} cannot change on resume; it is fixed when the session starts.`);
314
+ }
315
+ }
316
+ if (out.given.has('all') && cmd !== 'status') fail(2, '--all is only valid with "zcode-agent status".');
317
+ for (const k of ['plan', 'stallMin']) {
318
+ if (out.given.has(k) && cmd !== 'watch') fail(2, `--${flagName(k)} is only valid with "zcode-agent watch".`);
319
+ }
320
+ if (out.given.has('app') && cmd !== 'cost') fail(2, '--app is only valid with "zcode-agent cost".');
321
+ if (out.given.has('installBrowser') && cmd !== 'doctor') fail(2, '--install-browser is only valid with "zcode-agent doctor".');
322
+ if (out.given.has('any') && cmd !== 'wait') fail(2, '--any is only valid with "zcode-agent wait".');
323
+ if (out.given.has('full') && !FULL_COMMANDS.has(cmd)) fail(2, `--full is not valid with "zcode-agent ${cmd}".`);
324
+ if (out.given.has('session') && cmd !== 'run' && cmd !== 'plan') fail(2, '--session is only valid with "zcode-agent run"; use "zcode-agent resume <id>".');
325
+ if (out.given.has('id') && !require('../lib/store.js').validId(out.flags.id)) {
326
+ fail(2, `--id "${out.flags.id}" must be 1-64 chars of letters, digits, ".", "_" or "-", starting with a letter or digit.`);
327
+ }
328
+ if (!isDirectory(out.flags.cwd)) fail(2, `--cwd must be an existing directory, got "${out.flags.cwd}".`);
329
+
330
+ const model = normalizeModel(out.flags.model);
331
+ if (!model) fail(2, unknownModelMessage(out.flags.model));
332
+ out.flags.model = model;
333
+ const effort = normalizeEffort(out.flags.effort);
334
+ if (!effort) fail(2, `unknown effort "${out.flags.effort}". --effort accepts ${EFFORT_LEVELS.join(' | ')}.`);
335
+ out.flags.effort = effort;
336
+ return out;
337
+ }
338
+
339
+ // Closest known flag by edit distance (<= 2), or null.
340
+ function suggestFlag(arg, known) {
341
+ const dist = (a, b) => {
342
+ const row = Array.from({ length: b.length + 1 }, (_, j) => j);
343
+ for (let i = 1; i <= a.length; i++) {
344
+ let prev = row[0];
345
+ row[0] = i;
346
+ for (let j = 1; j <= b.length; j++) {
347
+ const tmp = row[j];
348
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
349
+ prev = tmp;
350
+ }
351
+ }
352
+ return row[b.length];
353
+ };
354
+ let best = null;
355
+ let bestD = Infinity;
356
+ for (const k of known) {
357
+ if (!k.startsWith('--')) continue;
358
+ const d = dist(arg, k);
359
+ if (d < bestD) { best = k; bestD = d; }
360
+ }
361
+ return best && bestD <= 2 ? best : null;
362
+ }
363
+
364
+ function flagName(key) {
365
+ return key.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`).replace(/^mcp-specs$/, 'mcp').replace(/^skills-dirs$/, 'skills')
366
+ .replace(/^(unit|viewport)s$/, '$1');
367
+ }
368
+
369
+ function isDirectory(p) {
370
+ try {
371
+ return require('node:fs').statSync(p).isDirectory();
372
+ } catch {
373
+ return false;
374
+ }
375
+ }
376
+
377
+ async function main() {
378
+ const parsed = parseArgv(process.argv.slice(2));
379
+ if (parsed.flags.mcpList) return require('../lib/commands/mcp-list.js')(parsed);
380
+ switch (parsed.command) {
381
+ case 'run':
382
+ case 'task':
383
+ case 'agent':
384
+ case 'resume':
385
+ case '__exec':
386
+ return require('../lib/commands/exec.js')(parsed);
387
+ case 'plan':
388
+ case '__plan':
389
+ return require('../lib/commands/plan.js')(parsed);
390
+ case 'status':
391
+ case 'wait':
392
+ case 'watch':
393
+ case 'result':
394
+ case 'cancel':
395
+ return require('../lib/commands/sessions.js')(parsed);
396
+ case 'cost':
397
+ return require('../lib/commands/cost.js')(parsed);
398
+ case 'login':
399
+ return require('../lib/commands/login.js')(parsed);
400
+ case 'doctor':
401
+ return require('../lib/commands/doctor.js')(parsed);
402
+ case 'skills':
403
+ return require('../lib/commands/skills.js')(parsed);
404
+ default:
405
+ return fail(2, `unknown command "${parsed.command}" (see zcode-agent --help).`);
406
+ }
407
+ }
408
+
409
+ // Exported before main() runs: the plan supervisor reuses parseArgv.
410
+ module.exports = { parseArgv, USAGE };
411
+
412
+ if (require.main === module) {
413
+ main().catch((err) => {
414
+ process.stderr.write(`zcode-agent: internal error: ${err && err.stack ? err.stack : err}\n`);
415
+ process.exit(1);
416
+ });
417
+ }
418
+