zcode-agent 1.3.1 → 1.4.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/README.md +135 -90
- package/bin/zcode-agent.js +62 -28
- package/lib/acp-map.js +22 -18
- package/lib/acp.js +84 -32
- package/lib/appserver.js +26 -17
- package/lib/bootstrap.js +1 -1
- package/lib/brief.js +2 -2
- package/lib/checks.js +23 -5
- package/lib/commands/acp.js +8 -0
- package/lib/commands/cost.js +9 -4
- package/lib/commands/doctor.js +18 -5
- package/lib/commands/exec.js +29 -9
- package/lib/commands/mcp-list.js +49 -4
- package/lib/commands/plan.js +22 -3
- package/lib/commands/sessions.js +27 -6
- package/lib/contract.js +30 -6
- package/lib/cost.js +22 -23
- package/lib/engine.js +0 -3
- package/lib/executor.js +70 -20
- package/lib/help.js +13 -11
- package/lib/isolation.js +73 -29
- package/lib/key.js +1 -5
- package/lib/models.js +93 -22
- package/lib/plan.js +14 -6
- package/lib/ports.js +1 -1
- package/lib/procs.js +35 -0
- package/lib/store.js +0 -1
- package/lib/taskspec.js +1 -1
- package/lib/ui.js +8 -3
- package/lib/verify.js +7 -3
- package/lib/workspace.js +34 -7
- package/package.json +4 -2
- package/skills/claude-code/zcode-agent/SKILL.md +13 -12
- package/skills/codex/zcode-agent/SKILL.md +13 -12
package/lib/appserver.js
CHANGED
|
@@ -21,6 +21,8 @@ const crypto = require('node:crypto');
|
|
|
21
21
|
const fs = require('node:fs');
|
|
22
22
|
const path = require('node:path');
|
|
23
23
|
|
|
24
|
+
const { track } = require('./procs.js');
|
|
25
|
+
|
|
24
26
|
const ENGINE_BOOT = path.join(__dirname, 'engine-boot.js');
|
|
25
27
|
|
|
26
28
|
const RUNTIME_PREFERENCES = {
|
|
@@ -68,6 +70,10 @@ class AppServerClient {
|
|
|
68
70
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
69
71
|
detached: true,
|
|
70
72
|
});
|
|
73
|
+
// Killed at process exit if nothing killed it before (lib/procs.js).
|
|
74
|
+
const untrack = track(this.child.pid);
|
|
75
|
+
this.child.on('exit', untrack);
|
|
76
|
+
this.child.on('error', untrack);
|
|
71
77
|
this.child.stderr.on('data', (d) => {
|
|
72
78
|
this.engineStderr += d;
|
|
73
79
|
if (this.engineStderr.length > 20000) {
|
|
@@ -182,7 +188,6 @@ class AppServerClient {
|
|
|
182
188
|
// proven non-fatal with -32601 — gets method-not-found and the run
|
|
183
189
|
// continues.
|
|
184
190
|
replyError(-32601, `zcode-agent: no policy for server request ${method}`);
|
|
185
|
-
if (this.onServerRequest) this.onServerRequest(frame);
|
|
186
191
|
}
|
|
187
192
|
|
|
188
193
|
request(method, params, { timeoutMs = 30000 } = {}) {
|
|
@@ -259,16 +264,23 @@ function workspaceKeyFor(workspacePath) {
|
|
|
259
264
|
// the last status map (the caller remembers inherited servers that failed).
|
|
260
265
|
async function waitForMcp(client, { workspacePath, required, timeoutMs = 20000, onEvent = () => {}, onStatuses = () => {} }) {
|
|
261
266
|
const ws = { workspace: { workspacePath, workspaceKey: workspaceKeyFor(workspacePath) } };
|
|
267
|
+
// An engine that died here must fail the open (the caller retries with a
|
|
268
|
+
// fresh one), not pass for a session that then polls a dead client.
|
|
269
|
+
const alive = () => {
|
|
270
|
+
if (client.dead) throw new Error('engine app-server exited during MCP connect');
|
|
271
|
+
};
|
|
262
272
|
try {
|
|
263
273
|
await client.request('mcp/list', { ...ws, mode: 'connect' }, { timeoutMs: 45000 });
|
|
264
274
|
} catch {
|
|
265
275
|
/* best-effort trigger; the status checks below still report */
|
|
266
276
|
}
|
|
277
|
+
alive();
|
|
267
278
|
const status = async () => {
|
|
268
279
|
try {
|
|
269
280
|
const res = await client.request('mcp/list', { ...ws, mode: 'status' }, { timeoutMs: 5000 });
|
|
270
281
|
return (res && res.statuses) || {};
|
|
271
282
|
} catch {
|
|
283
|
+
alive();
|
|
272
284
|
return null; // transient — retry
|
|
273
285
|
}
|
|
274
286
|
};
|
|
@@ -295,7 +307,7 @@ async function waitForMcp(client, { workspacePath, required, timeoutMs = 20000,
|
|
|
295
307
|
status: state,
|
|
296
308
|
toolCount: (entry && entry.toolCount) ?? null,
|
|
297
309
|
failureKind: (entry && entry.failureKind) ?? null,
|
|
298
|
-
error: (entry && entry.error) ? String(typeof entry.error === 'string' ? entry.error : JSON.stringify(entry.error)).slice(0, 300) : null,
|
|
310
|
+
error: (entry && entry.error) ? client.scrub(String(typeof entry.error === 'string' ? entry.error : JSON.stringify(entry.error))).slice(0, 300) : null,
|
|
299
311
|
});
|
|
300
312
|
}
|
|
301
313
|
}
|
|
@@ -375,7 +387,7 @@ async function openSession(client, {
|
|
|
375
387
|
|
|
376
388
|
// Sends one prompt into an open session and waits for its terminal event.
|
|
377
389
|
// Resolves the turn facts; rejects with TurnError (kind: timeout |
|
|
378
|
-
// cancelled | user_input | terminal_failed | result_type |
|
|
390
|
+
// cancelled | user_input | terminal_failed | result_type | engine_exit).
|
|
379
391
|
// On timeout or abort the engine is told to stop the active prompt
|
|
380
392
|
// (session/stop) before we give up on it, so no tool keeps running behind
|
|
381
393
|
// our back while the caller tears the engine down.
|
|
@@ -394,7 +406,6 @@ async function runTurn(client, session, {
|
|
|
394
406
|
response: '',
|
|
395
407
|
usage: null,
|
|
396
408
|
engineModel: null,
|
|
397
|
-
engineProvider: null,
|
|
398
409
|
engineReasoningLevel: null,
|
|
399
410
|
terminalStatus: null,
|
|
400
411
|
streamingEvents: 0,
|
|
@@ -403,7 +414,6 @@ async function runTurn(client, session, {
|
|
|
403
414
|
toolCallCount: null,
|
|
404
415
|
toolEvents: 0,
|
|
405
416
|
modelRequests: 0,
|
|
406
|
-
userInput: null,
|
|
407
417
|
durationMs: 0,
|
|
408
418
|
};
|
|
409
419
|
|
|
@@ -421,7 +431,6 @@ async function runTurn(client, session, {
|
|
|
421
431
|
const question = client.scrub(
|
|
422
432
|
String(params.message || params.prompt || params.question || JSON.stringify(params)).slice(0, 800)
|
|
423
433
|
);
|
|
424
|
-
turn.userInput = question;
|
|
425
434
|
fail(new TurnError(`headless run requested user input: ${question}`, { kind: 'user_input' }));
|
|
426
435
|
};
|
|
427
436
|
|
|
@@ -464,7 +473,6 @@ async function runTurn(client, session, {
|
|
|
464
473
|
onEvent({ type: 'turn', phase: 'started', turnId: params.turnId });
|
|
465
474
|
} else if (type === 'session.updated' && payload && payload.type === 'model_request_started') {
|
|
466
475
|
turn.modelRequests++;
|
|
467
|
-
turn.engineProvider = payload.providerId ?? turn.engineProvider;
|
|
468
476
|
turn.engineModel = payload.modelId ?? turn.engineModel;
|
|
469
477
|
turn.engineReasoningLevel = payload.modelCall?.reasoning?.requestedLevel ?? turn.engineReasoningLevel;
|
|
470
478
|
onEvent({
|
|
@@ -490,11 +498,11 @@ async function runTurn(client, session, {
|
|
|
490
498
|
const prevOnExit = client.onExit;
|
|
491
499
|
client.onExit = (err) => fail(new TurnError(client.scrub(err.message), { kind: 'engine_exit' }));
|
|
492
500
|
|
|
493
|
-
const
|
|
494
|
-
const
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
);
|
|
501
|
+
const timedOut = () => fail(new TurnError('run exceeded --timeout-ms', { kind: 'timeout' }));
|
|
502
|
+
const remaining = deadline - Date.now();
|
|
503
|
+
// No time left (engine start used it up): the prompt is never sent.
|
|
504
|
+
if (remaining <= 0) timedOut();
|
|
505
|
+
const timer = setTimeout(timedOut, Math.max(0, remaining));
|
|
498
506
|
const onAbort = () => fail(new TurnError('cancelled', { kind: 'cancelled' }));
|
|
499
507
|
if (signal) {
|
|
500
508
|
if (signal.aborted) onAbort();
|
|
@@ -526,10 +534,14 @@ async function runTurn(client, session, {
|
|
|
526
534
|
failed.turn = turn;
|
|
527
535
|
throw failed;
|
|
528
536
|
}
|
|
537
|
+
turn.durationMs = Date.now() - started;
|
|
529
538
|
if (completed.resultType && completed.resultType !== 'success') {
|
|
530
|
-
|
|
539
|
+
const err = new TurnError(`turn completed with resultType "${completed.resultType}"`, { kind: 'result_type' });
|
|
540
|
+
// The turn's usage and request count still happened and are billed.
|
|
541
|
+
err.turn = turn;
|
|
542
|
+
err.resultType = completed.resultType;
|
|
543
|
+
throw err;
|
|
531
544
|
}
|
|
532
|
-
turn.durationMs = Date.now() - started;
|
|
533
545
|
return turn;
|
|
534
546
|
} finally {
|
|
535
547
|
clearTimeout(timer);
|
|
@@ -545,8 +557,5 @@ module.exports = {
|
|
|
545
557
|
openSession,
|
|
546
558
|
runTurn,
|
|
547
559
|
TurnError,
|
|
548
|
-
workspaceKeyFor,
|
|
549
|
-
waitForMcp,
|
|
550
|
-
RUNTIME_PREFERENCES,
|
|
551
560
|
allowOnce,
|
|
552
561
|
};
|
package/lib/bootstrap.js
CHANGED
package/lib/brief.js
CHANGED
|
@@ -18,8 +18,8 @@ function clip(text, max) {
|
|
|
18
18
|
const empty = (v) =>
|
|
19
19
|
v === undefined || v === null || v === '' || (Array.isArray(v) && v.length === 0);
|
|
20
20
|
|
|
21
|
+
// A failing check (passing ones are only counted).
|
|
21
22
|
function briefCheck(c) {
|
|
22
|
-
if (c.ok) return { command: c.command, ok: true };
|
|
23
23
|
const out = { command: c.command, ok: false, exitCode: c.exitCode ?? null };
|
|
24
24
|
if (c.timedOut) out.timedOut = true;
|
|
25
25
|
out.tail = String(c.output || '').slice(-TAIL_MAX);
|
|
@@ -106,4 +106,4 @@ function buildBrief(result) {
|
|
|
106
106
|
return out;
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
-
module.exports = { buildBrief
|
|
109
|
+
module.exports = { buildBrief };
|
package/lib/checks.js
CHANGED
|
@@ -3,11 +3,15 @@
|
|
|
3
3
|
// ITSELF after the model's turn — the model's own claims are never the
|
|
4
4
|
// verification evidence. Each check runs in its own process group (so a
|
|
5
5
|
// timeout or cancel kills the whole tree), with a per-check timeout and a
|
|
6
|
-
// bounded output tail.
|
|
6
|
+
// bounded output tail. A check is over when its shell exits: whatever it left
|
|
7
|
+
// running in the background (`npm run preview & …; curl …`) is killed with it
|
|
8
|
+
// and cannot hold the check open until the timeout. CI=1 is set when unset so test runners do not enter
|
|
7
9
|
// watch/interactive mode.
|
|
8
10
|
const { spawn } = require('node:child_process');
|
|
11
|
+
const { track } = require('./procs.js');
|
|
9
12
|
|
|
10
13
|
const OUTPUT_TAIL = 4000;
|
|
14
|
+
const EXIT_GRACE_MS = 250;
|
|
11
15
|
|
|
12
16
|
function killGroup(child) {
|
|
13
17
|
try {
|
|
@@ -44,6 +48,7 @@ function runCheck(command, { cwd, timeoutMs = 300000, signal, env = process.env
|
|
|
44
48
|
resolve({ command, ok: false, exitCode: null, timedOut: false, durationMs: 0, output: String(err.message) });
|
|
45
49
|
return;
|
|
46
50
|
}
|
|
51
|
+
const untrack = track(child.pid);
|
|
47
52
|
child.stdout.setEncoding('utf8');
|
|
48
53
|
child.stderr.setEncoding('utf8');
|
|
49
54
|
child.stdout.on('data', keep);
|
|
@@ -60,9 +65,14 @@ function runCheck(command, { cwd, timeoutMs = 300000, signal, env = process.env
|
|
|
60
65
|
if (signal.aborted) onAbort();
|
|
61
66
|
else signal.addEventListener('abort', onAbort, { once: true });
|
|
62
67
|
}
|
|
68
|
+
let done = false;
|
|
63
69
|
const finish = (exitCode, errText) => {
|
|
70
|
+
if (done) return;
|
|
71
|
+
done = true;
|
|
64
72
|
clearTimeout(timer);
|
|
65
73
|
if (signal) signal.removeEventListener('abort', onAbort);
|
|
74
|
+
killGroup(child); // background children of the check end with it
|
|
75
|
+
untrack();
|
|
66
76
|
const tail = (output + (errText ? `\n${errText}` : '')).slice(-OUTPUT_TAIL);
|
|
67
77
|
resolve({
|
|
68
78
|
command,
|
|
@@ -74,19 +84,27 @@ function runCheck(command, { cwd, timeoutMs = 300000, signal, env = process.env
|
|
|
74
84
|
output: tail,
|
|
75
85
|
});
|
|
76
86
|
};
|
|
87
|
+
const ended = (code, sig) => finish(code, code === null && sig && !timedOut && !cancelled ? `killed by ${sig}` : undefined);
|
|
77
88
|
child.on('error', (err) => finish(null, err.message));
|
|
78
|
-
|
|
89
|
+
// `close` waits for every holder of the output pipes, which a background
|
|
90
|
+
// child keeps open: finish on the shell's exit, after a moment for
|
|
91
|
+
// buffered output.
|
|
92
|
+
child.on('exit', (code, sig) => setTimeout(() => ended(code, sig), EXIT_GRACE_MS));
|
|
93
|
+
child.on('close', ended);
|
|
79
94
|
});
|
|
80
95
|
}
|
|
81
96
|
|
|
82
97
|
// Runs every check in order (later checks still run when an earlier one
|
|
83
98
|
// fails, so the handback carries complete evidence); stops on cancel.
|
|
84
|
-
|
|
99
|
+
// `deadline` (epoch ms) bounds each check by the time the run has left, so
|
|
100
|
+
// several checks cannot each overrun --timeout-ms by a full check timeout.
|
|
101
|
+
async function runChecks(commands, { cwd, timeoutMs, deadline, signal, env, onEvent = () => {} } = {}) {
|
|
85
102
|
const results = [];
|
|
86
103
|
for (const command of commands) {
|
|
87
104
|
if (signal && signal.aborted) break;
|
|
88
105
|
onEvent({ type: 'check', phase: 'started', command });
|
|
89
|
-
const
|
|
106
|
+
const limit = deadline ? Math.max(1000, Math.min(timeoutMs, deadline - Date.now())) : timeoutMs;
|
|
107
|
+
const r = await runCheck(command, { cwd, timeoutMs: limit, signal, env });
|
|
90
108
|
results.push(r);
|
|
91
109
|
onEvent({
|
|
92
110
|
type: 'check',
|
|
@@ -101,4 +119,4 @@ async function runChecks(commands, { cwd, timeoutMs, signal, env, onEvent = () =
|
|
|
101
119
|
return results;
|
|
102
120
|
}
|
|
103
121
|
|
|
104
|
-
module.exports = { runCheck, runChecks
|
|
122
|
+
module.exports = { runCheck, runChecks };
|
package/lib/commands/acp.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
// session through ACP config options.
|
|
6
6
|
const { serve } = require('../acp.js');
|
|
7
7
|
const { MODE_IDS } = require('../acp-map.js');
|
|
8
|
+
const { effortProblem } = require('../models.js');
|
|
8
9
|
|
|
9
10
|
module.exports = function acpCommand(parsed) {
|
|
10
11
|
const { flags, given } = parsed;
|
|
@@ -17,6 +18,13 @@ module.exports = function acpCommand(parsed) {
|
|
|
17
18
|
process.stderr.write(`zcode-agent: unknown mode "${mode}". --mode accepts ${MODE_IDS.join(' | ')}.\n`);
|
|
18
19
|
process.exit(2);
|
|
19
20
|
}
|
|
21
|
+
// As for every other command: an effort the model does not accept is a
|
|
22
|
+
// usage error, not silently replaced by the model's highest level.
|
|
23
|
+
const problem = effortProblem(flags.model, flags.effort);
|
|
24
|
+
if (problem) {
|
|
25
|
+
process.stderr.write(`zcode-agent: ${problem}\n`);
|
|
26
|
+
process.exit(2);
|
|
27
|
+
}
|
|
20
28
|
serve({
|
|
21
29
|
version: require('../../package.json').version,
|
|
22
30
|
defaults: {
|
package/lib/commands/cost.js
CHANGED
|
@@ -21,20 +21,24 @@ function table(entries, title) {
|
|
|
21
21
|
c ? cost.formatTokens(c.input) : '-',
|
|
22
22
|
c ? cost.formatTokens(c.cached) : '-',
|
|
23
23
|
c ? cost.formatTokens(c.output) : '-',
|
|
24
|
-
c ?
|
|
24
|
+
c ? money(c) : '-',
|
|
25
25
|
];
|
|
26
26
|
});
|
|
27
27
|
const widths = head.map((h, i) => Math.max(String(h).length, ...rows.map((r) => String(r[i]).length)));
|
|
28
28
|
return [row(head, widths), ...rows.map((r) => row(r, widths))].join('\n');
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
// `$1.23`, `~` for an estimate, `+?` when usage of a model with no known
|
|
32
|
+
// price is not in the amount.
|
|
33
|
+
const money = (c) => `${cost.formatUsd(c.usd)}${c.estimate ? '~' : ''}${c.unpriced && c.unpriced.length ? '+?' : ''}`;
|
|
34
|
+
|
|
31
35
|
module.exports = async function costCommand(parsed) {
|
|
32
36
|
const { flags, prompts } = parsed;
|
|
33
37
|
if (prompts.length > 1) {
|
|
34
38
|
process.stderr.write('zcode-agent: cost takes at most one directory.\n');
|
|
35
39
|
process.exit(2);
|
|
36
40
|
}
|
|
37
|
-
const dir = path.resolve(prompts[0] || flags.cwd
|
|
41
|
+
const dir = path.resolve(prompts[0] || flags.cwd);
|
|
38
42
|
const sessions = cost.dirSessions(dir);
|
|
39
43
|
const app = flags.app ? cost.appSessions(dir) : null;
|
|
40
44
|
const zTotal = cost.sumCosts(sessions.map((s) => s.cost));
|
|
@@ -60,8 +64,9 @@ module.exports = async function costCommand(parsed) {
|
|
|
60
64
|
'',
|
|
61
65
|
`total ${n} session${n === 1 ? '' : 's'} ${total.requests} requests ` +
|
|
62
66
|
`${cost.formatTokens(total.input)} input (${cost.formatTokens(total.cached)} cached) ` +
|
|
63
|
-
`${cost.formatTokens(total.output)} output ${
|
|
64
|
-
`Z.ai API list price${total.estimate ? '; ~ = no cache split,
|
|
67
|
+
`${cost.formatTokens(total.output)} output ${money(total)}`,
|
|
68
|
+
`Z.ai API list price${total.estimate ? '; ~ = estimate (no cache split, or a provisional price)' : ''}` +
|
|
69
|
+
`${total.unpriced ? `; +? = not counted, no price for ${total.unpriced.join(', ')}` : ''}; ZCODE_PRICES overrides`
|
|
65
70
|
);
|
|
66
71
|
process.stdout.write(lines.join('\n') + '\n');
|
|
67
72
|
};
|
package/lib/commands/doctor.js
CHANGED
|
@@ -80,12 +80,20 @@ module.exports = async function doctor(parsed) {
|
|
|
80
80
|
const { enginePath, builtinConfig, nodeBin } = runtime;
|
|
81
81
|
const root = rootDir(process.env);
|
|
82
82
|
const live = liveDir(process.env);
|
|
83
|
+
const hermetic = Boolean(flags.hermetic) || process.env.ZCODE_HERMETIC === '1';
|
|
83
84
|
const built = buildEngineHome({
|
|
84
85
|
home: path.join(root, 'doctor', 'home'),
|
|
85
86
|
root,
|
|
86
87
|
key: runtime.key,
|
|
87
88
|
live,
|
|
88
|
-
|
|
89
|
+
// The setup a run with the same flags would get.
|
|
90
|
+
hermetic,
|
|
91
|
+
browser: !flags.noBrowser,
|
|
92
|
+
mcpSpecs: flags.mcpSpecs,
|
|
93
|
+
skillsDirs: flags.skillsDirs,
|
|
94
|
+
noSkills: flags.noSkills,
|
|
95
|
+
inheritDesktop: flags.inheritDesktop || process.env.ZCODE_INHERIT_DESKTOP === '1',
|
|
96
|
+
builtinConfig,
|
|
89
97
|
});
|
|
90
98
|
const version = engineVersion(nodeBin, enginePath, engineEnv({ home: built.home, builtinProviderConfig: builtinConfig }));
|
|
91
99
|
const tested = testedEngineVersion();
|
|
@@ -109,6 +117,10 @@ module.exports = async function doctor(parsed) {
|
|
|
109
117
|
if (tested && version && version !== tested) warnings.push(`engine ${version} differs from the tested ${tested}`);
|
|
110
118
|
if (defaultBrowser && !chromium) warnings.push('no Playwright Chromium found for the default browser server: run zcode-agent doctor --install-browser');
|
|
111
119
|
if (browserInstalled === false) warnings.push('browser install failed (see the output above)');
|
|
120
|
+
if (built.skillsSkipped.length) warnings.push(`skills that could not be copied and are left out: ${built.skillsSkipped.join(', ')}`);
|
|
121
|
+
// Left out of the inherited set, by cause.
|
|
122
|
+
const skippedUnhealthy = built.mcp.skippedUnhealthy;
|
|
123
|
+
const skippedOAuth = hermetic ? [] : liveSet.filter((n) => !servers.includes(n) && !skippedUnhealthy.includes(n));
|
|
112
124
|
|
|
113
125
|
const report = {
|
|
114
126
|
ok: nodeOk(nodeVersion) && browserInstalled !== false,
|
|
@@ -134,9 +146,10 @@ module.exports = async function doctor(parsed) {
|
|
|
134
146
|
home: built.home,
|
|
135
147
|
sessionsDir: store.sessionsDir(process.env),
|
|
136
148
|
mode: built.mode,
|
|
137
|
-
hermetic
|
|
149
|
+
hermetic,
|
|
138
150
|
mcpServers: servers,
|
|
139
|
-
mcpSkippedOAuth:
|
|
151
|
+
mcpSkippedOAuth: skippedOAuth,
|
|
152
|
+
mcpSkippedUnhealthy: skippedUnhealthy,
|
|
140
153
|
skillsInherited: built.skillsCopied,
|
|
141
154
|
},
|
|
142
155
|
browser: {
|
|
@@ -166,8 +179,8 @@ module.exports = async function doctor(parsed) {
|
|
|
166
179
|
` api key from ${KEY_SOURCES[runtime.keySource] || runtime.keySource} (never printed)`,
|
|
167
180
|
` models ${Object.entries(report.models).map(([id, l]) => `${id} (effort ${l.join('|')}, ${report.vision[id] ? 'images' : 'no images'})`).join(', ')}`,
|
|
168
181
|
report.desktop.found ? ` ZCode app settings ${live}` : ' ZCode app not found: standalone mode',
|
|
169
|
-
` mcp servers ${servers.length ? servers.join(', ') : 'none'}${iso.mcpSkippedOAuth.length ? ` (skipped, OAuth: ${iso.mcpSkippedOAuth.join(', ')})` : ''}`,
|
|
170
|
-
` skills inherited ${iso.skillsInherited}${iso.hermetic ? ' (
|
|
182
|
+
` mcp servers ${servers.length ? servers.join(', ') : 'none'}${iso.mcpSkippedOAuth.length ? ` (skipped, OAuth: ${iso.mcpSkippedOAuth.join(', ')})` : ''}${skippedUnhealthy.length ? ` (skipped, failed recently: ${skippedUnhealthy.join(', ')})` : ''}`,
|
|
183
|
+
` skills inherited ${iso.skillsInherited}${iso.hermetic ? ' (hermetic)' : ''}`,
|
|
171
184
|
` browser ${report.browser.server}; Playwright Chromium ${chromium ? 'found' : 'missing'}`,
|
|
172
185
|
` state ${root} (one engine HOME per session)`,
|
|
173
186
|
` sessions ${report.sessions.total} (${report.sessions.running} running, ${report.sessions.interrupted} interrupted)`,
|
package/lib/commands/exec.js
CHANGED
|
@@ -67,6 +67,16 @@ function loadTaskBase(spec) {
|
|
|
67
67
|
return { base: { objective: trimmed }, dir };
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
+
// Node fires a timer set beyond 2^31-1 ms at once, so a larger --timeout-ms
|
|
71
|
+
// (or contract limit) would time the run out immediately.
|
|
72
|
+
const MAX_TIMER_MS = 2147483647;
|
|
73
|
+
function clampTimers(inv) {
|
|
74
|
+
for (const k of ['timeoutMs', 'checkTimeoutMs']) {
|
|
75
|
+
if (typeof inv[k] === 'number' && inv[k] > MAX_TIMER_MS) inv[k] = MAX_TIMER_MS;
|
|
76
|
+
}
|
|
77
|
+
return inv;
|
|
78
|
+
}
|
|
79
|
+
|
|
70
80
|
// `spec` ({base, dir}) replaces --task: the plan supervisor hands over an
|
|
71
81
|
// assembled contract instead of a file.
|
|
72
82
|
function buildInvocation(parsed, spec) {
|
|
@@ -167,7 +177,7 @@ function buildInvocation(parsed, spec) {
|
|
|
167
177
|
if (err instanceof OwnershipError) usage(err.message);
|
|
168
178
|
throw err;
|
|
169
179
|
}
|
|
170
|
-
return inv;
|
|
180
|
+
return clampTimers(inv);
|
|
171
181
|
}
|
|
172
182
|
|
|
173
183
|
// resume <id> [message] — or run --session <id> <prompt> (0.3 compat).
|
|
@@ -182,19 +192,19 @@ function buildResume(parsed, ref, message) {
|
|
|
182
192
|
const effort = given.has('effort') ? flags.effort : settings.effort;
|
|
183
193
|
const problem = effortProblem(model, effort);
|
|
184
194
|
if (problem) usage(problem);
|
|
185
|
-
return {
|
|
195
|
+
return clampTimers({
|
|
186
196
|
...settings,
|
|
187
197
|
id,
|
|
188
198
|
resume: { message },
|
|
189
|
-
model
|
|
190
|
-
effort
|
|
199
|
+
model,
|
|
200
|
+
effort,
|
|
191
201
|
timeoutMs: given.has('timeoutMs') ? flags.timeoutMs : settings.timeoutMs,
|
|
192
202
|
maxRepairs: given.has('maxRepairs') ? flags.maxRepairs : settings.maxRepairs,
|
|
193
203
|
checkTimeoutMs: given.has('checkTimeoutMs') ? flags.checkTimeoutMs : settings.checkTimeoutMs,
|
|
194
204
|
includeReasoning: flags.includeReasoning,
|
|
195
205
|
stream: settings.kind !== 'task' || flags.stream,
|
|
196
206
|
contract: settings.kind === 'task' ? readTask(id) : undefined,
|
|
197
|
-
};
|
|
207
|
+
});
|
|
198
208
|
}
|
|
199
209
|
|
|
200
210
|
function readTask(id) {
|
|
@@ -212,6 +222,11 @@ function readTask(id) {
|
|
|
212
222
|
// session is still running.
|
|
213
223
|
function startDetached(inv) {
|
|
214
224
|
if (inv.resume) {
|
|
225
|
+
// The worker starts in the session's directory: without it the spawn
|
|
226
|
+
// fails silently and the session would read "interrupted".
|
|
227
|
+
if (!fs.existsSync(inv.cwd)) {
|
|
228
|
+
throw new ExecError(`the workspace of session "${inv.id}" no longer exists: ${inv.cwd}`, { exitCode: 2, kind: 'not_found' });
|
|
229
|
+
}
|
|
215
230
|
const view = store.viewSession(store.readSession(inv.id));
|
|
216
231
|
if (view && view.live) {
|
|
217
232
|
throw new ExecError(`session "${inv.id}" is still running (pid ${view.pid}).`, { exitCode: 7, kind: 'busy' });
|
|
@@ -324,7 +339,7 @@ async function exec(parsed) {
|
|
|
324
339
|
reporter.onEvent(ev);
|
|
325
340
|
};
|
|
326
341
|
|
|
327
|
-
// SIGINT/SIGTERM (Ctrl-C, `zcode cancel
|
|
342
|
+
// SIGINT/SIGTERM/SIGHUP (Ctrl-C, `zcode-agent cancel`, a closed terminal) abort cleanly: the engine is
|
|
328
343
|
// told to stop, checks are killed, the session is recorded "cancelled".
|
|
329
344
|
// A second signal exits immediately.
|
|
330
345
|
const controller = new AbortController();
|
|
@@ -336,6 +351,8 @@ async function exec(parsed) {
|
|
|
336
351
|
};
|
|
337
352
|
process.on('SIGINT', onSignal);
|
|
338
353
|
process.on('SIGTERM', onSignal);
|
|
354
|
+
// A closed terminal must stop the engine too, not leave it running tools.
|
|
355
|
+
process.on('SIGHUP', onSignal);
|
|
339
356
|
|
|
340
357
|
let result;
|
|
341
358
|
try {
|
|
@@ -344,12 +361,15 @@ async function exec(parsed) {
|
|
|
344
361
|
if (err instanceof ConfigError || err instanceof ExecError) {
|
|
345
362
|
const failed = {
|
|
346
363
|
type: 'result', ok: false, status: 'failed', id: inv.id, kind,
|
|
347
|
-
|
|
364
|
+
// exitCode: `wait` on a detached run that never started exits as the
|
|
365
|
+
// run itself would have (3 no key, 2 not found), not 5.
|
|
366
|
+
error: { kind: err.kind || 'config', message: err.message, exitCode: err.exitCode }, issues: [err.message],
|
|
348
367
|
};
|
|
349
368
|
if (json) process.stdout.write(JSON.stringify(full ? failed : buildBrief(failed)) + '\n');
|
|
350
369
|
// A detached worker's caller polls the store: record why it never ran
|
|
351
|
-
// (conflicts already record themselves
|
|
352
|
-
|
|
370
|
+
// (conflicts already record themselves; busy means another process is
|
|
371
|
+
// driving the session and owns its record).
|
|
372
|
+
if (worker && err.kind !== 'conflict' && err.kind !== 'busy' && store.readSession(inv.id)) {
|
|
353
373
|
store.writeResult(inv.id, failed);
|
|
354
374
|
store.updateSession(inv.id, { state: 'finished', phase: 'done', status: 'failed', outcome: { status: 'failed', issues: [err.message] } });
|
|
355
375
|
}
|
package/lib/commands/mcp-list.js
CHANGED
|
@@ -1,12 +1,57 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
// lib/commands/mcp-list.js — print the effective MCP server set for this
|
|
3
3
|
// invocation as one JSON line and exit 0. Never spawns the engine and needs
|
|
4
|
-
// no key; the
|
|
5
|
-
|
|
4
|
+
// no key; the set is exactly what a run with the same flags registers, with
|
|
5
|
+
// credentials redacted (headers, env and URLs commonly hold tokens, and
|
|
6
|
+
// Z.ai's own MCP servers hold the Z.ai key).
|
|
7
|
+
const { effectiveMcpServers, liveDir, rootDir, readMcpHealth } = require('../isolation.js');
|
|
8
|
+
|
|
9
|
+
const SECRET_HEADER = /authorization|api[-_]?key|token|secret|cookie/i;
|
|
10
|
+
const SECRET_ENV = /key|token|secret|password|auth/i;
|
|
11
|
+
const SECRET_PARAMS = new Set(['key', 'api_key', 'apikey', 'token', 'access_token', 'secret']);
|
|
12
|
+
|
|
13
|
+
function redactUrl(url) {
|
|
14
|
+
try {
|
|
15
|
+
const u = new URL(url);
|
|
16
|
+
u.username = '';
|
|
17
|
+
u.password = '';
|
|
18
|
+
for (const name of [...u.searchParams.keys()]) {
|
|
19
|
+
if (SECRET_PARAMS.has(name.toLowerCase())) u.searchParams.set(name, '***');
|
|
20
|
+
}
|
|
21
|
+
return u.toString();
|
|
22
|
+
} catch {
|
|
23
|
+
return url;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function redact(def) {
|
|
28
|
+
const out = { ...def };
|
|
29
|
+
const mask = (obj, re) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, re.test(k) ? '***' : v]));
|
|
30
|
+
if (out.headers && typeof out.headers === 'object') out.headers = mask(out.headers, SECRET_HEADER);
|
|
31
|
+
if (out.env && typeof out.env === 'object') out.env = mask(out.env, SECRET_ENV);
|
|
32
|
+
if (typeof out.url === 'string') out.url = redactUrl(out.url);
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
6
35
|
|
|
7
36
|
module.exports = async function mcpList(parsed) {
|
|
8
37
|
const { flags } = parsed;
|
|
9
|
-
|
|
10
|
-
|
|
38
|
+
// The same app dir and MCP health a run reads, so servers a run would skip
|
|
39
|
+
// (recently failed) are not listed.
|
|
40
|
+
const servers = effectiveMcpServers({
|
|
41
|
+
inherit: !flags.hermetic && process.env.ZCODE_HERMETIC !== '1',
|
|
42
|
+
browser: !flags.noBrowser,
|
|
43
|
+
mcpSpecs: flags.mcpSpecs,
|
|
44
|
+
live: liveDir(process.env),
|
|
45
|
+
health: readMcpHealth(rootDir(process.env)),
|
|
46
|
+
});
|
|
47
|
+
let line = JSON.stringify({ type: 'mcp', servers: Object.fromEntries(Object.entries(servers).map(([n, d]) => [n, redact(d)])) });
|
|
48
|
+
// Best effort: the key itself, wherever a definition carries it (args).
|
|
49
|
+
try {
|
|
50
|
+
const { key } = require('../key.js').resolveKeyInfo(process.env);
|
|
51
|
+
if (key) line = line.split(key).join('***');
|
|
52
|
+
} catch {
|
|
53
|
+
/* no key configured: nothing to remove */
|
|
54
|
+
}
|
|
55
|
+
process.stdout.write(line + '\n');
|
|
11
56
|
process.exit(0);
|
|
12
57
|
};
|
package/lib/commands/plan.js
CHANGED
|
@@ -122,9 +122,20 @@ async function superviseAndReport(name, flags, given) {
|
|
|
122
122
|
|
|
123
123
|
async function waitFor(name, flags, given) {
|
|
124
124
|
const deadline = given.has('timeoutMs') ? Date.now() + flags.timeoutMs : Infinity;
|
|
125
|
+
let { r } = open(name);
|
|
125
126
|
for (;;) {
|
|
126
|
-
const
|
|
127
|
-
if (
|
|
127
|
+
const state = store.readPlanState(name);
|
|
128
|
+
if (!state) die(2, `no plan "${name}" (zcode-agent plan run <file> starts one).`);
|
|
129
|
+
// Polled twice a second: statuses only (briefs are built once, at the
|
|
130
|
+
// end), and a plan file caught mid-save keeps the last good read.
|
|
131
|
+
try {
|
|
132
|
+
r = plans.resolvePlan(state.file, state.cwd);
|
|
133
|
+
} catch (err) {
|
|
134
|
+
if (!(err instanceof plans.PlanError)) throw err;
|
|
135
|
+
}
|
|
136
|
+
if (plans.planReport(name, r, state, { briefs: false }).status !== 'running') {
|
|
137
|
+
return finish(plans.planReport(name, r, state), flags);
|
|
138
|
+
}
|
|
128
139
|
if (Date.now() >= deadline) {
|
|
129
140
|
brief(name, flags, 'running');
|
|
130
141
|
process.exit(124);
|
|
@@ -259,10 +270,18 @@ async function resume(parsed, name, words) {
|
|
|
259
270
|
return finish(plans.planReport(name, r, state), flags);
|
|
260
271
|
}
|
|
261
272
|
const message = text || 'Continue: fix the remaining issues.';
|
|
273
|
+
// One session refusing (still running, a workspace conflict) must not
|
|
274
|
+
// strand the ones already resumed without a supervisor.
|
|
275
|
+
const refused = [];
|
|
262
276
|
for (const id of targets) {
|
|
263
277
|
const refusal = plans.resumeSession(id, message);
|
|
264
|
-
if (refusal)
|
|
278
|
+
if (refusal) {
|
|
279
|
+
refused.push(id);
|
|
280
|
+
process.stderr.write(`zcode-agent: ${id}: ${refusal}\n`);
|
|
281
|
+
}
|
|
265
282
|
}
|
|
283
|
+
const waiting = [...statuses.values()].some((x) => x.status === 'pending' || x.status === 'skipped');
|
|
284
|
+
if (targets.length && refused.length === targets.length && !waiting) process.exit(7);
|
|
266
285
|
// Launch failures recorded earlier are retried by the supervisor.
|
|
267
286
|
if (state.launchErrors && Object.keys(state.launchErrors).length) {
|
|
268
287
|
store.updatePlanState(name, { launchErrors: {} });
|
package/lib/commands/sessions.js
CHANGED
|
@@ -24,6 +24,19 @@ function resolveOrExit(ref, json) {
|
|
|
24
24
|
function finalResult(view) {
|
|
25
25
|
const result = store.readResult(view.id);
|
|
26
26
|
if (view.state === 'finished' && result) return result;
|
|
27
|
+
// An ACP session writes no handback: between prompts (and once closed) its
|
|
28
|
+
// record says finished/completed, and it continues in the ACP client, not
|
|
29
|
+
// with `resume`.
|
|
30
|
+
if (view.kind === 'acp' && view.state === 'finished') {
|
|
31
|
+
return { type: 'result', ok: true, status: 'completed', id: view.id, kind: 'acp', issues: [], durationMs: 0 };
|
|
32
|
+
}
|
|
33
|
+
if (view.kind === 'acp') {
|
|
34
|
+
return {
|
|
35
|
+
type: 'result', ok: false, status: 'failed', id: view.id, kind: 'acp',
|
|
36
|
+
error: { kind: 'interrupted', message: 'the ACP agent running this session exited mid-prompt; reopen the session in the ACP client' },
|
|
37
|
+
issues: ['interrupted before completion'], durationMs: 0,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
27
40
|
return {
|
|
28
41
|
type: 'result',
|
|
29
42
|
ok: false,
|
|
@@ -52,7 +65,7 @@ async function status(parsed) {
|
|
|
52
65
|
if (prompts.length === 0) {
|
|
53
66
|
const everything = store.listSessions();
|
|
54
67
|
if (flags.json) {
|
|
55
|
-
process.stdout.write(JSON.stringify({ type: 'sessions', sessions: everything.slice(0, 50).map(summaryOf) }) + '\n');
|
|
68
|
+
process.stdout.write(JSON.stringify({ type: 'sessions', sessions: (flags.all ? everything : everything.slice(0, 50)).map(summaryOf) }) + '\n');
|
|
56
69
|
} else if (everything.length === 0) {
|
|
57
70
|
process.stdout.write('no sessions\n');
|
|
58
71
|
} else {
|
|
@@ -238,7 +251,7 @@ async function cancel(parsed) {
|
|
|
238
251
|
// <age> ago[ thinking|writing <age> <n> chars] req <n> sub <running>
|
|
239
252
|
// $cost` (+ STALLED? when running and silent). `usd`: the session's cost so
|
|
240
253
|
// far (lib/cost.js), null if unknown.
|
|
241
|
-
function watchLine(view, { stallMin, now = Date.now(), usd = null }) {
|
|
254
|
+
function watchLine(view, { stallMin, now = Date.now(), usd = null, estimate = false }) {
|
|
242
255
|
const done = isDone(view);
|
|
243
256
|
const state = view.state === 'finished' ? view.status || 'finished' : view.state;
|
|
244
257
|
const a = view.activity || {};
|
|
@@ -254,7 +267,7 @@ function watchLine(view, { stallMin, now = Date.now(), usd = null }) {
|
|
|
254
267
|
? ` ${cur.doing} ${formatElapsed(now - Date.parse(cur.since))}${cur.chars ? ` ${cost.formatTokens(cur.chars)} chars` : ''}`
|
|
255
268
|
: '';
|
|
256
269
|
const stalled = idle && idle.stalled ? ' STALLED?' : '';
|
|
257
|
-
const money = usd === null || usd === undefined ? '' : ` ${cost.formatUsd(usd)}`;
|
|
270
|
+
const money = usd === null || usd === undefined ? '' : ` ${cost.formatUsd(usd)}${estimate ? '~' : ''}`;
|
|
258
271
|
const text = `${view.id} ${state}${phase} ${elapsed} ${last}${doing} req ${a.modelRequests || 0} sub ${a.subagentsRunning || 0}${money}${stalled}`;
|
|
259
272
|
// The change signature leaves out the clocks (elapsed, ages, char counts).
|
|
260
273
|
const sig = [view.id, state, phase, a.lastTool, cur ? cur.doing : '', a.modelRequests || 0, a.subagentsRunning || 0, money, Boolean(stalled)].join('|');
|
|
@@ -279,7 +292,13 @@ async function watch(parsed) {
|
|
|
279
292
|
process.stderr.write(`zcode-agent: no plan "${flags.plan}" (zcode-agent plan run <file> starts one).\n`);
|
|
280
293
|
process.exit(2);
|
|
281
294
|
}
|
|
282
|
-
|
|
295
|
+
try {
|
|
296
|
+
planCtx = { plans, state, r: plans.resolvePlan(state.file, state.cwd) };
|
|
297
|
+
} catch (err) {
|
|
298
|
+
if (!(err instanceof plans.PlanError)) throw err;
|
|
299
|
+
process.stderr.write(`zcode-agent: ${err.message}\n`);
|
|
300
|
+
process.exit(2);
|
|
301
|
+
}
|
|
283
302
|
}
|
|
284
303
|
const ids = prompts.map((p) => resolveOrExit(p, false));
|
|
285
304
|
const pick = () => {
|
|
@@ -301,9 +320,11 @@ async function watch(parsed) {
|
|
|
301
320
|
process.exit(0);
|
|
302
321
|
}
|
|
303
322
|
const costs = views.map((v) => cost.sessionCost(v));
|
|
304
|
-
const lines = views.map((v, i) => watchLine(v, { stallMin, usd: costs[i] ? costs[i].usd : null }));
|
|
323
|
+
const lines = views.map((v, i) => watchLine(v, { stallMin, usd: costs[i] ? costs[i].usd : null, estimate: Boolean(costs[i] && costs[i].estimate) }));
|
|
305
324
|
const known = costs.filter(Boolean);
|
|
306
|
-
const
|
|
325
|
+
const sum = cost.sumCosts(known);
|
|
326
|
+
// ~ as in `zcode-agent cost`: an estimate (no cache split, or a provisional price).
|
|
327
|
+
const total = lines.length > 1 && known.length ? `total ${cost.formatUsd(sum.usd)}${sum.estimate ? '~' : ''} (${known.length} session${known.length === 1 ? '' : 's'}, Z.ai list price${sum.estimate ? '; ~ = estimate' : ''})` : null;
|
|
307
328
|
if (tty) {
|
|
308
329
|
const shown = total ? [...lines.map((l) => l.text), total] : lines.map((l) => l.text);
|
|
309
330
|
process.stdout.write(`${drawn ? `\x1b[${drawn}F\x1b[J` : ''}${shown.join('\n')}${shown.length ? '\n' : ''}`);
|