zcode-agent 0.0.0-stage → 1.1.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,394 @@
1
+ 'use strict';
2
+ // lib/commands/exec.js — run | task | agent | resume | __exec (detached
3
+ // worker). Builds the invocation from argv, runs it (in-process, or in a
4
+ // detached worker with --detach), prints the result, exits with the
5
+ // status's exit code.
6
+ //
7
+ // Output contract:
8
+ // --json stdout = NDJSON events + exactly one final {"type":"result"}
9
+ // line (--quiet: only that line): the compact brief
10
+ // (zcode.brief/1, lib/brief.js), or the full record with --full.
11
+ // stderr = diagnostics only.
12
+ // plain stdout = the answer (run/agent) or the handback summary (task);
13
+ // stderr = the live feed (header, phases, tools, checks).
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ const { spawn } = require('node:child_process');
17
+ const store = require('../store.js');
18
+ const { execute, prepareSession, exitCodeFor, ExecError, readSettings } = require('../executor.js');
19
+ const { ConfigError } = require('../bootstrap.js');
20
+ const { ContractError } = require('../contract.js');
21
+ const { buildContract } = require('../taskspec.js');
22
+ const { workspaceRoot, normalizeOwns, OwnershipError } = require('../workspace.js');
23
+ const { buildBrief } = require('../brief.js');
24
+ const { makeReporter, formatResult, useColor } = require('../ui.js');
25
+ const { normalizeModel, normalizeEffort, effortProblem } = require('../models.js');
26
+
27
+ const BIN = path.join(__dirname, '..', '..', 'bin', 'zcode-agent.js');
28
+ const DEFAULT_TIMEOUT = { run: 600000, agent: 600000, task: 7200000 };
29
+
30
+ // Thrown (not exited) so builders can be reused by the plan supervisor; the
31
+ // command entry points below turn it into the one-line exit 2.
32
+ class UsageError extends Error {}
33
+
34
+ function usage(message) {
35
+ throw new UsageError(message);
36
+ }
37
+
38
+ function readStdin() {
39
+ try {
40
+ return fs.readFileSync(0, 'utf8');
41
+ } catch {
42
+ return '';
43
+ }
44
+ }
45
+
46
+ // --task <file|->: .json (or text starting with "{") is a contract object,
47
+ // anything else is a markdown brief that becomes the objective.
48
+ function loadTaskBase(spec) {
49
+ if (spec === undefined) return { base: {}, dir: null };
50
+ const text = spec === '-' ? readStdin() : (() => {
51
+ try {
52
+ return fs.readFileSync(spec, 'utf8');
53
+ } catch {
54
+ return usage(`--task file "${spec}" could not be read.`);
55
+ }
56
+ })();
57
+ const trimmed = text.trim();
58
+ // "@file" entries inside a contract resolve next to the contract file.
59
+ const dir = spec === '-' ? null : path.dirname(path.resolve(spec));
60
+ if (spec.endsWith('.json') || trimmed.startsWith('{')) {
61
+ try {
62
+ return { base: JSON.parse(trimmed), dir };
63
+ } catch (err) {
64
+ return usage(`--task JSON is invalid: ${err.message}`);
65
+ }
66
+ }
67
+ return { base: { objective: trimmed }, dir };
68
+ }
69
+
70
+ // `spec` ({base, dir}) replaces --task: the plan supervisor hands over an
71
+ // assembled contract instead of a file.
72
+ function buildInvocation(parsed, spec) {
73
+ const { command, flags, prompts } = parsed;
74
+ const kind = command;
75
+ let effortSource = '--effort';
76
+ const inv = {
77
+ kind,
78
+ id: flags.id || store.newId(),
79
+ label: flags.label || null,
80
+ cwd: path.resolve(flags.cwd),
81
+ model: flags.model,
82
+ effort: flags.effort,
83
+ timeoutMs: flags.timeoutMs ?? DEFAULT_TIMEOUT[kind],
84
+ maxRepairs: flags.maxRepairs ?? 2,
85
+ checkTimeoutMs: flags.checkTimeoutMs ?? 300000,
86
+ checks: [],
87
+ owns: [],
88
+ ownsDisplay: flags.owns,
89
+ acceptanceDeclared: false,
90
+ mcpSpecs: flags.mcpSpecs,
91
+ hermetic: flags.hermetic,
92
+ noBrowser: flags.noBrowser,
93
+ skillsDirs: flags.skillsDirs.map((d) => path.resolve(d)),
94
+ noSkills: flags.noSkills,
95
+ inheritDesktop: flags.inheritDesktop,
96
+ profile: flags.profile,
97
+ includeReasoning: flags.includeReasoning,
98
+ allowOverlap: flags.allowOverlap,
99
+ stream: kind !== 'task' || flags.stream,
100
+ };
101
+
102
+ if (kind === 'task') {
103
+ const objective = prompts.join(' ');
104
+ let { base, dir } = spec || loadTaskBase(flags.task);
105
+ if (!spec && !objective.trim() && flags.task === undefined && !process.stdin.isTTY) {
106
+ base = { objective: readStdin().trim() };
107
+ }
108
+ let contract;
109
+ try {
110
+ contract = buildContract({
111
+ base,
112
+ baseDir: dir || process.cwd(),
113
+ cwd: inv.cwd,
114
+ objective,
115
+ additions: {
116
+ acceptance: flags.accept,
117
+ checks: flags.check,
118
+ files: flags.file,
119
+ context: flags.context,
120
+ decisions: flags.decisions,
121
+ units: flags.units,
122
+ visual: flags.visual,
123
+ viewports: flags.viewports,
124
+ serve: flags.serve,
125
+ owns: flags.owns,
126
+ touch: flags.touch,
127
+ },
128
+ });
129
+ } catch (err) {
130
+ if (err instanceof ContractError) usage(err.message);
131
+ throw err;
132
+ }
133
+ // Contract-level model/effort/limits apply unless a flag overrides them.
134
+ if (contract.model && !parsed.given.has('model')) {
135
+ inv.model = normalizeModel(contract.model) || usage(`contract model "${contract.model}" is not supported.`);
136
+ }
137
+ if (contract.effort && !parsed.given.has('effort')) {
138
+ effortSource = 'contract effort';
139
+ inv.effort = normalizeEffort(contract.effort) || usage(`contract effort "${contract.effort}" is not valid.`);
140
+ }
141
+ const lim = contract.limits;
142
+ if (lim.timeoutMs && !parsed.given.has('timeoutMs')) inv.timeoutMs = lim.timeoutMs;
143
+ if (lim.maxRepairs !== undefined && !parsed.given.has('maxRepairs')) inv.maxRepairs = lim.maxRepairs;
144
+ if (lim.checkTimeoutMs && !parsed.given.has('checkTimeoutMs')) inv.checkTimeoutMs = lim.checkTimeoutMs;
145
+ inv.contract = contract;
146
+ inv.checks = contract.checks;
147
+ inv.ownsDisplay = contract.owns;
148
+ inv.touchDisplay = contract.touch;
149
+ inv.acceptanceDeclared = contract.acceptance.length > 0;
150
+ inv.preflight = Boolean(flags.preflight);
151
+ } else {
152
+ let prompt = prompts.join(' ');
153
+ if (!prompt && kind === 'run' && !process.stdin.isTTY) prompt = readStdin();
154
+ if (!prompt.trim()) usage(kind === 'agent' ? 'agent needs instructions.' : 'no prompt given (positional args or stdin).');
155
+ inv.prompt = prompt;
156
+ }
157
+
158
+ // The model/effort pair that will actually run, refused before any spawn.
159
+ const problem = effortProblem(inv.model, inv.effort, { source: effortSource });
160
+ if (problem) usage(problem);
161
+
162
+ try {
163
+ const root = workspaceRoot(inv.cwd);
164
+ inv.owns = normalizeOwns(inv.ownsDisplay, inv.cwd, root);
165
+ inv.touch = normalizeOwns(inv.touchDisplay || [], inv.cwd, root, '--touch');
166
+ } catch (err) {
167
+ if (err instanceof OwnershipError) usage(err.message);
168
+ throw err;
169
+ }
170
+ return inv;
171
+ }
172
+
173
+ // resume <id> [message] — or run --session <id> <prompt> (0.3 compat).
174
+ function buildResume(parsed, ref, message) {
175
+ const id = store.resolveSessionId(ref);
176
+ if (!id) usage(`no session "${ref}" (see "zcode-agent status").`);
177
+ const settings = readSettings(id);
178
+ if (!settings) usage(`session "${id}" has no stored settings; it cannot be resumed.`);
179
+ const { flags, given } = parsed;
180
+ if (settings.kind !== 'task' && !message.trim()) usage(`resume of a ${settings.kind} session needs a message.`);
181
+ const model = given.has('model') ? flags.model : settings.model;
182
+ const effort = given.has('effort') ? flags.effort : settings.effort;
183
+ const problem = effortProblem(model, effort);
184
+ if (problem) usage(problem);
185
+ return {
186
+ ...settings,
187
+ id,
188
+ resume: { message },
189
+ model: given.has('model') ? flags.model : settings.model,
190
+ effort: given.has('effort') ? flags.effort : settings.effort,
191
+ timeoutMs: given.has('timeoutMs') ? flags.timeoutMs : settings.timeoutMs,
192
+ maxRepairs: given.has('maxRepairs') ? flags.maxRepairs : settings.maxRepairs,
193
+ checkTimeoutMs: given.has('checkTimeoutMs') ? flags.checkTimeoutMs : settings.checkTimeoutMs,
194
+ includeReasoning: flags.includeReasoning,
195
+ stream: settings.kind !== 'task' || flags.stream,
196
+ contract: settings.kind === 'task' ? readTask(id) : undefined,
197
+ };
198
+ }
199
+
200
+ function readTask(id) {
201
+ try {
202
+ return JSON.parse(fs.readFileSync(path.join(store.sessionDir(id), 'task.json'), 'utf8'));
203
+ } catch {
204
+ return null;
205
+ }
206
+ }
207
+
208
+ // Claims the id, hands the invocation to a detached worker
209
+ // (`zcode __exec <id>`) and returns its handle. The worker writes its NDJSON
210
+ // to <session>/stdout.ndjson and diagnostics to stderr.log. Throws
211
+ // store.SessionExistsError for a taken id, ExecError (exit 7) when a resumed
212
+ // session is still running.
213
+ function startDetached(inv) {
214
+ if (inv.resume) {
215
+ const view = store.viewSession(store.readSession(inv.id));
216
+ if (view && view.live) {
217
+ throw new ExecError(`session "${inv.id}" is still running (pid ${view.pid}).`, { exitCode: 7, kind: 'busy' });
218
+ }
219
+ } else {
220
+ prepareSession(inv);
221
+ }
222
+ const dir = store.sessionDir(inv.id);
223
+ store.writeJsonAtomic(path.join(dir, 'pending.json'), inv);
224
+ // Mark it queued (owned by us) BEFORE the worker exists, so a concurrent
225
+ // `zcode wait` never mistakes a previous invocation's result for this one.
226
+ store.updateSession(inv.id, { state: 'queued', phase: 'queued', pid: process.pid, status: null });
227
+ const out = fs.openSync(path.join(dir, 'stdout.ndjson'), 'a', 0o600);
228
+ const err = fs.openSync(path.join(dir, 'stderr.log'), 'a', 0o600);
229
+ const child = spawn(process.execPath, [BIN, '__exec', inv.id], {
230
+ cwd: inv.cwd,
231
+ detached: true,
232
+ stdio: ['ignore', out, err],
233
+ env: process.env,
234
+ });
235
+ child.unref();
236
+ fs.closeSync(out);
237
+ fs.closeSync(err);
238
+ store.updateSession(inv.id, { state: 'queued', phase: 'queued', pid: child.pid, status: null });
239
+ return {
240
+ type: 'detached',
241
+ id: inv.id,
242
+ pid: child.pid,
243
+ kind: inv.kind,
244
+ status: 'queued',
245
+ files: { session: dir, stdout: path.join(dir, 'stdout.ndjson'), stderr: path.join(dir, 'stderr.log') },
246
+ };
247
+ }
248
+
249
+ // --detach: start in the background, print the handle, exit 0.
250
+ function detach(inv, flags) {
251
+ let handle;
252
+ try {
253
+ handle = startDetached(inv);
254
+ } catch (err) {
255
+ if (err instanceof store.SessionExistsError) usage(err.message);
256
+ if (err instanceof ExecError) {
257
+ process.stderr.write(`zcode-agent: ${err.message}\n`);
258
+ process.exit(err.exitCode);
259
+ }
260
+ throw err;
261
+ }
262
+ if (flags.json) process.stdout.write(JSON.stringify(handle) + '\n');
263
+ else {
264
+ process.stdout.write(`${inv.id}\n`);
265
+ if (!flags.quiet) {
266
+ process.stderr.write(`zcode-agent: started ${inv.id} in the background (pid ${handle.pid}). zcode-agent status ${inv.id} · zcode-agent wait ${inv.id}\n`);
267
+ }
268
+ }
269
+ process.exit(0);
270
+ }
271
+
272
+ async function exec(parsed) {
273
+ const { command, flags } = parsed;
274
+ let inv;
275
+ let worker = false;
276
+ if (command === '__exec') {
277
+ worker = true;
278
+ const id = parsed.prompts[0];
279
+ const file = path.join(store.sessionDir(id), 'pending.json');
280
+ try {
281
+ inv = JSON.parse(fs.readFileSync(file, 'utf8'));
282
+ fs.rmSync(file, { force: true });
283
+ } catch {
284
+ usage(`no pending invocation for "${id}".`);
285
+ }
286
+ inv.adopt = true;
287
+ } else if (command === 'resume') {
288
+ const [ref, ...rest] = parsed.prompts;
289
+ if (!ref) usage('resume needs a session id.');
290
+ // `zcode resume <id> -` reads the message from stdin (long answers).
291
+ const message = rest.length === 1 && rest[0] === '-' ? readStdin() : rest.join(' ');
292
+ inv = buildResume(parsed, ref, message);
293
+ } else if (command === 'run' && flags.session) {
294
+ inv = buildResume(parsed, flags.session, parsed.prompts.join(' ') || (!process.stdin.isTTY ? readStdin() : ''));
295
+ } else {
296
+ inv = buildInvocation(parsed);
297
+ }
298
+
299
+ if (flags.detach && !worker) return detach(inv, flags);
300
+
301
+ // Workers always emit NDJSON (to their stdout file) and never a TTY feed.
302
+ const json = worker || flags.json;
303
+ const quiet = flags.quiet && !worker;
304
+ const full = flags.full && !worker;
305
+ const kind = inv.kind;
306
+ const reporter = makeReporter({
307
+ quiet,
308
+ thinking: flags.thinking ?? kind !== 'task',
309
+ });
310
+ let streamedText = '';
311
+ const onEvent = json
312
+ ? (ev) => {
313
+ if (quiet) return;
314
+ if (ev.type === 'stream' && !inv.stream) return;
315
+ process.stdout.write(JSON.stringify(ev) + '\n');
316
+ }
317
+ : (ev) => {
318
+ if (ev.type === 'stream' && ev.kind === 'text_delta' && ev.delta && kind !== 'task') {
319
+ reporter.closeThinking();
320
+ streamedText += ev.delta;
321
+ process.stdout.write(ev.delta);
322
+ return;
323
+ }
324
+ reporter.onEvent(ev);
325
+ };
326
+
327
+ // SIGINT/SIGTERM (Ctrl-C, `zcode cancel`) abort cleanly: the engine is
328
+ // told to stop, checks are killed, the session is recorded "cancelled".
329
+ // A second signal exits immediately.
330
+ const controller = new AbortController();
331
+ let signals = 0;
332
+ const onSignal = () => {
333
+ signals++;
334
+ if (signals > 1) process.exit(130);
335
+ controller.abort();
336
+ };
337
+ process.on('SIGINT', onSignal);
338
+ process.on('SIGTERM', onSignal);
339
+
340
+ let result;
341
+ try {
342
+ result = await execute(inv, { onEvent, signal: controller.signal });
343
+ } catch (err) {
344
+ if (err instanceof ConfigError || err instanceof ExecError) {
345
+ const failed = {
346
+ type: 'result', ok: false, status: 'failed', id: inv.id, kind,
347
+ error: { kind: err.kind || 'config', message: err.message }, issues: [err.message],
348
+ };
349
+ if (json) process.stdout.write(JSON.stringify(full ? failed : buildBrief(failed)) + '\n');
350
+ // A detached worker's caller polls the store: record why it never ran
351
+ // (conflicts already record themselves).
352
+ if (worker && err.kind !== 'conflict' && store.readSession(inv.id)) {
353
+ store.writeResult(inv.id, failed);
354
+ store.updateSession(inv.id, { state: 'finished', phase: 'done', status: 'failed', outcome: { status: 'failed', issues: [err.message] } });
355
+ }
356
+ process.stderr.write(`zcode-agent: ${err.message}\n`);
357
+ process.exit(err.exitCode);
358
+ }
359
+ if (err instanceof store.SessionExistsError) usage(err.message);
360
+ throw err;
361
+ }
362
+
363
+ const code = exitCodeFor(result);
364
+ if (json) {
365
+ process.stdout.write(JSON.stringify(full ? result : buildBrief(result)) + '\n');
366
+ } else if (kind === 'task') {
367
+ reporter.closeThinking();
368
+ process.stdout.write(formatResult(result, { color: useColor(process.stdout) }));
369
+ } else {
370
+ reporter.closeThinking();
371
+ if (!streamedText.trim()) process.stdout.write(result.response || '');
372
+ process.stdout.write('\n');
373
+ reporter.footer(result);
374
+ if (result.status !== 'completed' || kind === 'agent') {
375
+ process.stderr.write(formatResult(result, { color: useColor(process.stderr) }));
376
+ }
377
+ }
378
+ process.exit(code);
379
+ }
380
+
381
+ module.exports = async function execCommand(parsed) {
382
+ try {
383
+ return await exec(parsed);
384
+ } catch (err) {
385
+ if (!(err instanceof UsageError)) throw err;
386
+ process.stderr.write(`zcode-agent: ${err.message}\n`);
387
+ process.exit(2);
388
+ }
389
+ };
390
+
391
+ module.exports.buildInvocation = buildInvocation;
392
+ module.exports.buildResume = buildResume;
393
+ module.exports.startDetached = startDetached;
394
+ module.exports.UsageError = UsageError;
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+ // lib/commands/login.js — read the API key from piped stdin and store it at
3
+ // <root>/credentials.json (mode 600, root mode 700) (DESIGN §5, §10).
4
+ // Never interactive (1.0): a terminal on stdin is refused instead of
5
+ // waiting for a paste. The key is never echoed. Output deliberately
6
+ // contains no key material.
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+ const { rootDir } = require('../key.js');
10
+
11
+ module.exports = async function login() {
12
+ if (process.stdin.isTTY) {
13
+ process.stderr.write(
14
+ 'zcode-agent login: pipe the key in, e.g. printf %s "$ZAI_API_KEY" | zcode-agent login\n' +
15
+ '(not needed with the ZCode app installed: its key is used automatically)\n'
16
+ );
17
+ process.exit(2);
18
+ }
19
+ let input = '';
20
+ await new Promise((resolve) => {
21
+ process.stdin.setEncoding('utf8');
22
+ process.stdin.on('data', (c) => (input += c));
23
+ process.stdin.on('end', resolve);
24
+ process.stdin.on('error', resolve);
25
+ });
26
+ const key = input.trim();
27
+ if (!key) {
28
+ process.stderr.write('zcode-agent login: no key received on stdin.\n');
29
+ process.exit(2);
30
+ }
31
+
32
+ const root = rootDir(process.env);
33
+ fs.mkdirSync(root, { recursive: true });
34
+ fs.chmodSync(root, 0o700);
35
+ const file = path.join(root, 'credentials.json');
36
+ fs.writeFileSync(file, JSON.stringify({ apiKey: key }, null, 2) + '\n', {
37
+ mode: 0o600,
38
+ });
39
+ fs.chmodSync(file, 0o600);
40
+ // No cache to invalidate: every invocation rewrites its session's
41
+ // provider config from the current key.
42
+ process.stdout.write(`zcode-agent login: key stored at ${file} (mode 600)\n`);
43
+ process.exit(0);
44
+ };
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+ // lib/commands/mcp-list.js — print the effective MCP server set for this
3
+ // invocation as one JSON line and exit 0. Never spawns the engine and needs
4
+ // no key; the value is exactly what a run with the same flags registers.
5
+ const { effectiveMcpServers } = require('../isolation.js');
6
+
7
+ module.exports = async function mcpList(parsed) {
8
+ const { flags } = parsed;
9
+ const servers = effectiveMcpServers({ inherit: !flags.hermetic && process.env.ZCODE_HERMETIC !== '1', browser: !flags.noBrowser, mcpSpecs: flags.mcpSpecs });
10
+ process.stdout.write(JSON.stringify({ type: 'mcp', servers }) + '\n');
11
+ process.exit(0);
12
+ };