zcode-agent 1.3.0 → 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 +83 -41
- 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/contract.js
CHANGED
|
@@ -37,10 +37,19 @@ const CONTRACT_KEYS = [
|
|
|
37
37
|
];
|
|
38
38
|
const LIMIT_KEYS = ['timeoutMs', 'maxRepairs', 'checkTimeoutMs'];
|
|
39
39
|
|
|
40
|
+
// A list of strings (one string is a list of one). An object entry is a
|
|
41
|
+
// contract mistake ("checks": [{"command": …}]), never the text "[object Object]".
|
|
40
42
|
const asList = (v) =>
|
|
41
43
|
v === undefined || v === null
|
|
42
44
|
? []
|
|
43
|
-
: (Array.isArray(v) ? v : [v])
|
|
45
|
+
: (Array.isArray(v) ? v : [v])
|
|
46
|
+
.map((x) => {
|
|
47
|
+
if (x !== null && typeof x === 'object') {
|
|
48
|
+
throw new ContractError(`contract list entries must be strings, got ${JSON.stringify(x).slice(0, 80)}`);
|
|
49
|
+
}
|
|
50
|
+
return String(x ?? '').trim();
|
|
51
|
+
})
|
|
52
|
+
.filter(Boolean);
|
|
44
53
|
|
|
45
54
|
const uniq = (items) => [...new Set(items)];
|
|
46
55
|
const VIEWPORT_RE = /^\d{2,5}x\d{2,5}$/;
|
|
@@ -105,6 +114,14 @@ function normalizeContract(base = {}, additions = {}) {
|
|
|
105
114
|
throw new ContractError(`contract limits.${k} must be a non-negative number`);
|
|
106
115
|
}
|
|
107
116
|
}
|
|
117
|
+
if (limits.maxRepairs !== undefined && !Number.isInteger(limits.maxRepairs)) {
|
|
118
|
+
throw new ContractError('contract limits.maxRepairs must be an integer');
|
|
119
|
+
}
|
|
120
|
+
// Below 1 ms is no timeout at all (0 would even be dropped for the
|
|
121
|
+
// default); the flags refuse it too.
|
|
122
|
+
for (const k of ['timeoutMs', 'checkTimeoutMs']) {
|
|
123
|
+
if (limits[k] !== undefined && limits[k] < 1) throw new ContractError(`contract limits.${k} must be at least 1`);
|
|
124
|
+
}
|
|
108
125
|
const viewports = uniq([...asList(base.viewports), ...asList(additions.viewports)]);
|
|
109
126
|
for (const v of viewports) {
|
|
110
127
|
if (!VIEWPORT_RE.test(v)) throw new ContractError(`viewport "${v}" must look like 390x844`);
|
|
@@ -274,7 +291,7 @@ function buildTaskPrompt(contract, { ownsDisplay = contract.owns, session = null
|
|
|
274
291
|
// `visual`: the verifier's unmet entries {criterion, viewport, seen, note, shot}.
|
|
275
292
|
function buildRepairPrompt(failures, { attempt, maxRepairs, visual = [] }) {
|
|
276
293
|
const blocks = failures.map((f) => {
|
|
277
|
-
const why = f.timedOut ? 'timed out' : `exit ${f.exitCode}`;
|
|
294
|
+
const why = f.timedOut ? 'timed out' : f.exitCode === null ? 'killed by a signal' : `exit ${f.exitCode}`;
|
|
278
295
|
return `### \`${f.command}\` (${why})\n\`\`\`\n${f.output.trim().slice(-3000) || '(no output)'}\n\`\`\``;
|
|
279
296
|
});
|
|
280
297
|
const head = failures.length
|
|
@@ -322,7 +339,11 @@ function buildResumePrompt(message, { kind, portChange = null }) {
|
|
|
322
339
|
|
|
323
340
|
// --- handback -------------------------------------------------------------------
|
|
324
341
|
|
|
325
|
-
|
|
342
|
+
// The block ends at a fence on its own line: a ``` inside a JSON string
|
|
343
|
+
// (a summary quoting code) is not the end. HANDBACK_LOOSE_RE accepts a
|
|
344
|
+
// closing fence glued to the JSON, tried only when no block ends properly.
|
|
345
|
+
const HANDBACK_RE = /```zcode-handback[^\n]*\n([\s\S]*?)\n[ \t]*```/g;
|
|
346
|
+
const HANDBACK_LOOSE_RE = /```zcode-handback[^\n]*\n([\s\S]*?)```/g;
|
|
326
347
|
const STATUS_ALIASES = new Map([
|
|
327
348
|
['done', 'done'],
|
|
328
349
|
['complete', 'done'],
|
|
@@ -382,7 +403,8 @@ function unmetVisual(entries, declared) {
|
|
|
382
403
|
// response text with the block removed.
|
|
383
404
|
function parseHandback(text) {
|
|
384
405
|
const source = String(text || '');
|
|
385
|
-
|
|
406
|
+
let matches = [...source.matchAll(HANDBACK_RE)];
|
|
407
|
+
if (matches.length === 0) matches = [...source.matchAll(HANDBACK_LOOSE_RE)];
|
|
386
408
|
if (matches.length === 0) return { handback: null, report: source.trim(), error: 'missing' };
|
|
387
409
|
const last = matches[matches.length - 1];
|
|
388
410
|
const report = (source.slice(0, last.index) + source.slice(last.index + last[0].length)).trim();
|
|
@@ -459,6 +481,10 @@ function deriveStatus({
|
|
|
459
481
|
if (handback.status === 'blocked' || handback.questions.length) {
|
|
460
482
|
return { status: 'blocked', issues: ['preflight found open questions (see questions)'] };
|
|
461
483
|
}
|
|
484
|
+
// "No open questions" is only what a "done" preflight says.
|
|
485
|
+
if (handback.status !== 'done') {
|
|
486
|
+
return { status: 'unverified', issues: [`the preflight reported "${handback.status || 'no status'}" without questions`] };
|
|
487
|
+
}
|
|
462
488
|
return { status: 'completed', issues };
|
|
463
489
|
}
|
|
464
490
|
if (handback && handback.status === 'blocked') {
|
|
@@ -514,11 +540,9 @@ function deriveStatus({
|
|
|
514
540
|
module.exports = {
|
|
515
541
|
ContractError,
|
|
516
542
|
sessionSection,
|
|
517
|
-
CONTRACT_KEYS,
|
|
518
543
|
DEFAULT_VIEWPORTS,
|
|
519
544
|
parseUnit,
|
|
520
545
|
questionText,
|
|
521
|
-
unmetVisual,
|
|
522
546
|
visualGaps,
|
|
523
547
|
normalizeContract,
|
|
524
548
|
buildTaskPrompt,
|
package/lib/cost.js
CHANGED
|
@@ -7,14 +7,17 @@
|
|
|
7
7
|
// without an engine DB fall back to the record's usageTotal (no cache split:
|
|
8
8
|
// marked `estimate`). Read-only; never blocks the engine (WAL readers).
|
|
9
9
|
const fs = require('node:fs');
|
|
10
|
-
const os = require('node:os');
|
|
11
10
|
const path = require('node:path');
|
|
12
|
-
const { spawnSync } = require('node:child_process');
|
|
13
11
|
const store = require('./store.js');
|
|
12
|
+
const { liveDir } = require('./isolation.js');
|
|
14
13
|
|
|
15
14
|
// USD per million tokens, Z.ai API list prices. ZCODE_PRICES (JSON, same
|
|
16
15
|
// shape, keyed by model id, case-insensitive) overrides or adds models.
|
|
16
|
+
// `provisional`: Z.ai has published no API price yet (GLM-5.4 shipped on the
|
|
17
|
+
// Coding Plan first, 2026-11-23); priced like GLM-5.1 to 5.3, which all list
|
|
18
|
+
// at the same rate, and marked as an estimate until the real price is in.
|
|
17
19
|
const LIST_PRICES = {
|
|
20
|
+
'GLM-5.4': { input: 1.4, cached: 0.26, output: 4.4, provisional: true },
|
|
18
21
|
'GLM-5.3-Flash': { input: 0.15, cached: 0.03, output: 0.5 },
|
|
19
22
|
'GLM-5.3': { input: 1.4, cached: 0.26, output: 4.4 },
|
|
20
23
|
};
|
|
@@ -26,7 +29,8 @@ function priceTable(env = process.env) {
|
|
|
26
29
|
try {
|
|
27
30
|
const extra = JSON.parse(env.ZCODE_PRICES);
|
|
28
31
|
for (const [k, v] of Object.entries(extra || {})) {
|
|
29
|
-
|
|
32
|
+
// A caller's own price is not provisional.
|
|
33
|
+
if (v && typeof v === 'object') table[k.toLowerCase()] = { ...table[k.toLowerCase()], provisional: false, ...v };
|
|
30
34
|
}
|
|
31
35
|
} catch {
|
|
32
36
|
/* ignored: list prices */
|
|
@@ -80,18 +84,7 @@ function query(file, sql, params = []) {
|
|
|
80
84
|
}
|
|
81
85
|
}
|
|
82
86
|
}
|
|
83
|
-
|
|
84
|
-
// The CLI has no bind parameters; callers only bind paths, quoted here.
|
|
85
|
-
let i = 0;
|
|
86
|
-
sql = sql.replace(/\?/g, () => `'${String(params[i++]).replace(/'/g, "''")}'`);
|
|
87
|
-
}
|
|
88
|
-
const r = spawnSync('sqlite3', ['-readonly', '-json', file, sql], { encoding: 'utf8', timeout: 15000 });
|
|
89
|
-
if (r.status !== 0) return null;
|
|
90
|
-
try {
|
|
91
|
-
return r.stdout.trim() ? JSON.parse(r.stdout) : [];
|
|
92
|
-
} catch {
|
|
93
|
-
return null;
|
|
94
|
-
}
|
|
87
|
+
return null;
|
|
95
88
|
}
|
|
96
89
|
|
|
97
90
|
const SUMS = `count(*) AS requests,
|
|
@@ -109,6 +102,7 @@ function engineDbOf(id, env = process.env) {
|
|
|
109
102
|
function fold(rows, env) {
|
|
110
103
|
const total = { requests: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, usd: 0, models: {} };
|
|
111
104
|
const unpriced = [];
|
|
105
|
+
const table = priceTable(env);
|
|
112
106
|
for (const r of rows) {
|
|
113
107
|
const counts = {
|
|
114
108
|
requests: Number(r.requests) || 0,
|
|
@@ -119,6 +113,8 @@ function fold(rows, env) {
|
|
|
119
113
|
};
|
|
120
114
|
const usd = priceOf(r.model, counts, env);
|
|
121
115
|
if (usd === null) unpriced.push(r.model);
|
|
116
|
+
const price = table[String(r.model || '').toLowerCase()];
|
|
117
|
+
if (price && price.provisional && counts.requests + counts.input + counts.output > 0) total.estimate = true;
|
|
122
118
|
total.models[r.model] = { ...counts, usd };
|
|
123
119
|
for (const k of ['requests', 'input', 'cached', 'cacheWrite', 'output']) total[k] += counts[k];
|
|
124
120
|
total.usd += usd || 0;
|
|
@@ -200,9 +196,10 @@ function dirSessions(dir, env = process.env) {
|
|
|
200
196
|
}
|
|
201
197
|
|
|
202
198
|
// The desktop app's own sessions (its DB, not zcode's) whose directory is
|
|
203
|
-
// `dir` or below it
|
|
199
|
+
// `dir` or below it, in the app directory every other command reads
|
|
200
|
+
// (ZAI_CODE_LIVE_DIR). ZCODE_APP_DB overrides the path (tests).
|
|
204
201
|
function appDb(env = process.env) {
|
|
205
|
-
return env.ZCODE_APP_DB || path.join(env
|
|
202
|
+
return env.ZCODE_APP_DB || path.join(liveDir(env), 'cli', 'db', 'db.sqlite');
|
|
206
203
|
}
|
|
207
204
|
|
|
208
205
|
function appSessions(dir, env = process.env) {
|
|
@@ -210,7 +207,9 @@ function appSessions(dir, env = process.env) {
|
|
|
210
207
|
// The app stores the directory as it was opened: match the given and the
|
|
211
208
|
// symlink-resolved spelling.
|
|
212
209
|
const forms = [...new Set([path.resolve(dir), real(dir)])].map((d) => d.replace(/\/+$/, '') || '/');
|
|
213
|
-
|
|
210
|
+
// LIKE wildcards in the directory name itself (my_app, 100%) are literal.
|
|
211
|
+
const like = (d) => `${d === '/' ? '' : d.replace(/[\\%_]/g, '\\$&')}/%`;
|
|
212
|
+
const where = forms.map(() => "(s.directory = ? OR s.directory LIKE ? ESCAPE '\\')").join(' OR ');
|
|
214
213
|
const rows = query(
|
|
215
214
|
file,
|
|
216
215
|
`SELECT s.id AS id, s.title AS title, s.directory AS cwd, m.model_id AS model, ${SUMS},
|
|
@@ -218,7 +217,7 @@ function appSessions(dir, env = process.env) {
|
|
|
218
217
|
FROM model_usage m JOIN session s ON s.id = m.session_id
|
|
219
218
|
WHERE ${where}
|
|
220
219
|
GROUP BY s.id, m.model_id`,
|
|
221
|
-
forms.flatMap((d) => [d,
|
|
220
|
+
forms.flatMap((d) => [d, like(d)])
|
|
222
221
|
);
|
|
223
222
|
if (!rows) return null;
|
|
224
223
|
const byId = new Map();
|
|
@@ -246,8 +245,10 @@ function sumCosts(costs) {
|
|
|
246
245
|
const t = { requests: 0, input: 0, cached: 0, cacheWrite: 0, output: 0, usd: 0 };
|
|
247
246
|
for (const c of costs) {
|
|
248
247
|
if (!c) continue;
|
|
249
|
-
for (const k of Object.keys(t)) t[k] += c[k] || 0;
|
|
248
|
+
for (const k of Object.keys(t)) if (k !== 'unpriced') t[k] += c[k] || 0;
|
|
250
249
|
if (c.estimate) t.estimate = true;
|
|
250
|
+
// Models with no known price add nothing to usd: carried so it shows.
|
|
251
|
+
if (c.unpriced && c.unpriced.length) t.unpriced = [...new Set([...(t.unpriced || []), ...c.unpriced])];
|
|
251
252
|
}
|
|
252
253
|
return t;
|
|
253
254
|
}
|
|
@@ -258,14 +259,12 @@ function formatUsd(usd) {
|
|
|
258
259
|
}
|
|
259
260
|
|
|
260
261
|
function formatTokens(n) {
|
|
261
|
-
if (n >=
|
|
262
|
+
if (n >= 999950) return `${(n / 1e6).toFixed(1)}M`; // 999,950 would print "1000.0k"
|
|
262
263
|
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
|
|
263
264
|
return String(n);
|
|
264
265
|
}
|
|
265
266
|
|
|
266
267
|
module.exports = {
|
|
267
|
-
LIST_PRICES,
|
|
268
|
-
priceTable,
|
|
269
268
|
priceOf,
|
|
270
269
|
sessionCost,
|
|
271
270
|
dirSessions,
|
package/lib/engine.js
CHANGED
|
@@ -22,7 +22,6 @@ function appBundleEngines(env = process.env) {
|
|
|
22
22
|
}
|
|
23
23
|
return ['/opt/ZCode/resources/glm/zcode.cjs', '/usr/lib/zcode/resources/glm/zcode.cjs', '/usr/share/zcode/resources/glm/zcode.cjs'];
|
|
24
24
|
}
|
|
25
|
-
const APP_BUNDLE_ENGINE = appBundleEngines()[0];
|
|
26
25
|
|
|
27
26
|
// The engine this package was tested with: the @zcode-agent/engine
|
|
28
27
|
// dependency (1.0), which mirrors the app's Resources layout
|
|
@@ -206,7 +205,5 @@ module.exports = {
|
|
|
206
205
|
engineVersion,
|
|
207
206
|
EngineNotFoundError,
|
|
208
207
|
BuiltinConfigNotFoundError,
|
|
209
|
-
APP_BUNDLE_ENGINE,
|
|
210
|
-
appBundleEngines,
|
|
211
208
|
packagedEngine,
|
|
212
209
|
};
|
package/lib/executor.js
CHANGED
|
@@ -66,8 +66,10 @@ class ExecError extends Error {
|
|
|
66
66
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
67
67
|
|
|
68
68
|
// Settings a session keeps across invocations (stored as invocation.json).
|
|
69
|
+
// `prompt` (run/agent): a session that never reached the engine (queue
|
|
70
|
+
// timeout, engine start failure) is resumed with what it was asked.
|
|
69
71
|
const SETTING_KEYS = [
|
|
70
|
-
'kind', 'label', 'cwd', 'model', 'effort', 'timeoutMs', 'maxRepairs', 'checkTimeoutMs',
|
|
72
|
+
'kind', 'label', 'prompt', 'cwd', 'model', 'effort', 'timeoutMs', 'maxRepairs', 'checkTimeoutMs',
|
|
71
73
|
'checks', 'preflight', 'owns', 'ownsDisplay', 'touch', 'touchDisplay', 'acceptanceDeclared', 'mcpSpecs', 'hermetic', 'noBrowser',
|
|
72
74
|
'skillsDirs', 'noSkills', 'inheritDesktop', 'profile', 'includeReasoning', 'allowOverlap', 'stream',
|
|
73
75
|
];
|
|
@@ -147,7 +149,8 @@ function sumUsage(turns) {
|
|
|
147
149
|
function usageOf(turns, failedTurns) {
|
|
148
150
|
const all = [...turns, ...failedTurns];
|
|
149
151
|
if (!all.length) return null;
|
|
150
|
-
|
|
152
|
+
// A failed turn that still reported usage (a non-success result) is billed too.
|
|
153
|
+
const base = sumUsage(all) || { inputTokens: null, outputTokens: null };
|
|
151
154
|
const incomplete = all.some((t) => !t.usage);
|
|
152
155
|
return {
|
|
153
156
|
...base,
|
|
@@ -181,6 +184,7 @@ function exitCodeFor(result) {
|
|
|
181
184
|
return 130;
|
|
182
185
|
default: {
|
|
183
186
|
const kind = result.error && result.error.kind;
|
|
187
|
+
if (Number.isInteger(result.error && result.error.exitCode)) return result.error.exitCode;
|
|
184
188
|
if (kind === 'timeout') return 124;
|
|
185
189
|
if (kind === 'no_subagent') return 6;
|
|
186
190
|
if (kind === 'checks_failed') return 8;
|
|
@@ -230,6 +234,10 @@ async function execute(inv, opts = {}) {
|
|
|
230
234
|
const id = inv.id;
|
|
231
235
|
const dir = store.sessionDir(id, env);
|
|
232
236
|
const home = path.join(dir, 'home');
|
|
237
|
+
// A resumed session's directory may be gone (a removed worktree).
|
|
238
|
+
if (!fs.existsSync(inv.cwd)) {
|
|
239
|
+
throw new ExecError(`the workspace of session "${id}" no longer exists: ${inv.cwd}`, { exitCode: 2, kind: 'not_found' });
|
|
240
|
+
}
|
|
233
241
|
const root = workspaceRoot(inv.cwd);
|
|
234
242
|
|
|
235
243
|
// --- record ---------------------------------------------------------------
|
|
@@ -255,11 +263,13 @@ async function execute(inv, opts = {}) {
|
|
|
255
263
|
};
|
|
256
264
|
// Resuming a preflight session proceeds to the real task: answers + the
|
|
257
265
|
// full protocol, checks and visual verification from here on.
|
|
266
|
+
// Stored only once the engine session is open: a resume that never starts
|
|
267
|
+
// (conflict, queue timeout, engine failure) must leave it a preflight, or
|
|
268
|
+
// the next resume would skip the task prompt.
|
|
258
269
|
const leavingPreflight = resuming && Boolean(inv.preflight);
|
|
270
|
+
if (resuming) writeSettings(id, inv, env);
|
|
259
271
|
if (leavingPreflight) inv.preflight = false;
|
|
260
272
|
const preflight = Boolean(inv.preflight);
|
|
261
|
-
if (resuming) writeSettings(id, inv, env);
|
|
262
|
-
if (leavingPreflight) store.updateSession(id, { preflight: false }, env);
|
|
263
273
|
const isFirstInvocation = !record.engineSessionId;
|
|
264
274
|
const update = (patch) => store.updateSession(id, patch, env);
|
|
265
275
|
|
|
@@ -468,13 +478,18 @@ async function execute(inv, opts = {}) {
|
|
|
468
478
|
inheritDesktop: !!inv.inheritDesktop || env.ZCODE_INHERIT_DESKTOP === '1',
|
|
469
479
|
profile: inv.profile,
|
|
470
480
|
model: inv.model,
|
|
481
|
+
builtinConfig: runtime.builtinConfig,
|
|
471
482
|
});
|
|
472
483
|
before = snapshot(root);
|
|
473
484
|
// Inherited servers that fail to connect: surfaced once in the feed and
|
|
474
485
|
// remembered, so the next sessions skip them for a while.
|
|
486
|
+
// Health is recorded once per invocation: the verifier engines start
|
|
487
|
+
// from the same HOME, and one dead server must count as one failure.
|
|
475
488
|
const reportedMcp = new Set();
|
|
489
|
+
let mcpRecorded = false;
|
|
476
490
|
const rememberMcp = (statuses) => {
|
|
477
|
-
recordMcpHealth(rootDir(env), statuses, built.mcp.inherited);
|
|
491
|
+
if (!mcpRecorded) recordMcpHealth(rootDir(env), statuses, built.mcp.inherited, { scrub });
|
|
492
|
+
mcpRecorded = true;
|
|
478
493
|
for (const name of Object.keys(built.mcp.inherited)) {
|
|
479
494
|
const entry = statuses[name];
|
|
480
495
|
if (!entry || entry.status !== 'failed' || reportedMcp.has(name)) continue;
|
|
@@ -490,6 +505,13 @@ async function execute(inv, opts = {}) {
|
|
|
490
505
|
client = makeClient(runtime, { home, cwd: record.cwd, sessionEnv });
|
|
491
506
|
client.start();
|
|
492
507
|
update({ enginePid: client.child.pid });
|
|
508
|
+
// openSession knows neither the deadline nor the abort signal: a
|
|
509
|
+
// cancel or --timeout-ms during engine start kills the engine, which
|
|
510
|
+
// rejects the pending request (runTurn handles both from here on).
|
|
511
|
+
const starting = client;
|
|
512
|
+
const stopStart = () => starting.kill();
|
|
513
|
+
const startTimer = setTimeout(stopStart, Math.max(0, deadline - Date.now()));
|
|
514
|
+
if (signal) signal.addEventListener('abort', stopStart, { once: true });
|
|
493
515
|
try {
|
|
494
516
|
session = await openSession(client, {
|
|
495
517
|
workspacePath: record.cwd,
|
|
@@ -503,12 +525,21 @@ async function execute(inv, opts = {}) {
|
|
|
503
525
|
break;
|
|
504
526
|
} catch (err) {
|
|
505
527
|
client.kill();
|
|
528
|
+
if (signal && signal.aborted) throw new TurnError('cancelled', { kind: 'cancelled' });
|
|
529
|
+
if (Date.now() >= deadline) throw new TurnError('run exceeded --timeout-ms while the engine was starting', { kind: 'timeout' });
|
|
506
530
|
const transient = /timeout|exited|failed to start|dead/.test(err.message);
|
|
507
|
-
if (attempt >= 2 || !transient
|
|
531
|
+
if (attempt >= 2 || !transient) throw err;
|
|
508
532
|
relay({ type: 'retry', phase: 'open_session', reason: scrub(err.message).slice(0, 300) });
|
|
533
|
+
} finally {
|
|
534
|
+
clearTimeout(startTimer);
|
|
535
|
+
if (signal) signal.removeEventListener('abort', stopStart);
|
|
509
536
|
}
|
|
510
537
|
}
|
|
511
538
|
update({ engineSessionId: session.sessionId });
|
|
539
|
+
if (leavingPreflight) {
|
|
540
|
+
writeSettings(id, inv, env);
|
|
541
|
+
update({ preflight: false });
|
|
542
|
+
}
|
|
512
543
|
|
|
513
544
|
// First prompt for this invocation.
|
|
514
545
|
let prompt;
|
|
@@ -529,18 +560,25 @@ async function execute(inv, opts = {}) {
|
|
|
529
560
|
// The port is the one thing that may have changed since the first prompt.
|
|
530
561
|
portChange: record.port && String(record.port) !== sessionEnv.ZCODE_PORT ? sessionEnv.ZCODE_PORT : null,
|
|
531
562
|
});
|
|
532
|
-
} else if (inv.kind === 'agent') {
|
|
533
|
-
prompt =
|
|
534
|
-
`You MUST use the Agent tool (profileId: "${inv.profile}") to accomplish the ` +
|
|
535
|
-
`task below — do not do the work yourself. When the subagent finishes, ` +
|
|
536
|
-
`report its agent id and result.\n\nTask: ${inv.resume ? inv.resume.message : inv.prompt}`;
|
|
537
563
|
} else {
|
|
538
|
-
|
|
564
|
+
// A resume of a session the engine never saw sends what it was first
|
|
565
|
+
// asked, then the message; a real resume sends the message alone.
|
|
566
|
+
const unsent = resuming && isFirstInvocation && inv.prompt
|
|
567
|
+
? inv.prompt + (inv.resume.message ? `\n\n## Message from the orchestrator\n${inv.resume.message}` : '')
|
|
568
|
+
: null;
|
|
569
|
+
if (inv.kind === 'agent') {
|
|
570
|
+
prompt =
|
|
571
|
+
`You MUST use the Agent tool (profileId: "${inv.profile}") to accomplish the ` +
|
|
572
|
+
`task below — do not do the work yourself. When the subagent finishes, ` +
|
|
573
|
+
`report its agent id and result.\n\nTask: ${unsent || (inv.resume ? inv.resume.message : inv.prompt)}`;
|
|
574
|
+
} else {
|
|
575
|
+
prompt = unsent || (inv.resume ? buildResumePrompt(inv.resume.message, { kind: 'run' }) : inv.prompt);
|
|
576
|
+
}
|
|
539
577
|
}
|
|
540
578
|
|
|
541
579
|
// The verifier's engine: a NEW engine session (own client: fresh context
|
|
542
|
-
// and its own browser, separate from the implementer's) on the
|
|
543
|
-
//
|
|
580
|
+
// and its own browser, separate from the implementer's) on the verifier
|
|
581
|
+
// model (models.js visionModel). Resolves {client, session}; kills it on failure.
|
|
544
582
|
const openVerifier = (model, onEvent) => {
|
|
545
583
|
const vclient = makeClient(runtime, { home, cwd: record.cwd, sessionEnv });
|
|
546
584
|
vclient.start();
|
|
@@ -681,7 +719,8 @@ async function execute(inv, opts = {}) {
|
|
|
681
719
|
checks = await runChecks(inv.checks, {
|
|
682
720
|
cwd: record.cwd,
|
|
683
721
|
env: { ...env, ...sessionEnv },
|
|
684
|
-
timeoutMs:
|
|
722
|
+
timeoutMs: inv.checkTimeoutMs,
|
|
723
|
+
deadline,
|
|
685
724
|
signal,
|
|
686
725
|
onEvent: relay,
|
|
687
726
|
});
|
|
@@ -696,15 +735,19 @@ async function execute(inv, opts = {}) {
|
|
|
696
735
|
// zcode, not the implementer, judges the visual criteria. Unmet ones
|
|
697
736
|
// share the repair budget with failing checks; a verifier that could
|
|
698
737
|
// not run (met:null) is reported, not repaired.
|
|
738
|
+
// Out of time with work still owed (the verifier, or a repair turn) is
|
|
739
|
+
// a timeout (exit 124, resumable), not "checks failed" or "partial".
|
|
740
|
+
const outOfTime = (what) => new TurnError(`run exceeded --timeout-ms before ${what}`, { kind: 'timeout' });
|
|
699
741
|
let visualUnmet = [];
|
|
700
|
-
if (visualDeclared.length && !failures.length && parsed.handback
|
|
701
|
-
|
|
742
|
+
if (visualDeclared.length && !failures.length && parsed.handback && !(signal && signal.aborted)) {
|
|
743
|
+
if (Date.now() >= deadline) throw outOfTime('the visual verifier');
|
|
702
744
|
visualEntries = await verifyVisual(verifyRounds + 1);
|
|
703
745
|
visualUnmet = visualEntries.filter((v) => v.met === false);
|
|
704
746
|
}
|
|
705
747
|
dropSpareVerifier(); // checks failed: no verifier this round
|
|
706
748
|
if ((!failures.length && !visualUnmet.length) || repairs >= inv.maxRepairs) break;
|
|
707
|
-
if (
|
|
749
|
+
if (signal && signal.aborted) break;
|
|
750
|
+
if (Date.now() >= deadline) throw outOfTime('the repair turn');
|
|
708
751
|
repairs++;
|
|
709
752
|
prompt = buildRepairPrompt(failures, { attempt: repairs, maxRepairs: inv.maxRepairs, visual: visualUnmet });
|
|
710
753
|
phase = 'repairing';
|
|
@@ -742,6 +785,9 @@ async function execute(inv, opts = {}) {
|
|
|
742
785
|
// gone): their changes are theirs, not scope violations of ours.
|
|
743
786
|
for (const other of store.listSessions(env)) {
|
|
744
787
|
if (other.id === id || other.workspaceRoot !== root || concurrent.has(other.id)) continue;
|
|
788
|
+
// Only a session that could have written: one refused before it started
|
|
789
|
+
// (no engine session) or a read-only preflight excuses nothing.
|
|
790
|
+
if (!other.engineSessionId || other.preflight) continue;
|
|
745
791
|
if (String(other.updatedAt) >= invocationStart && Array.isArray(other.ownsRoot)) {
|
|
746
792
|
concurrent.set(other.id, other.ownsRoot);
|
|
747
793
|
}
|
|
@@ -804,7 +850,8 @@ async function execute(inv, opts = {}) {
|
|
|
804
850
|
const cmd = plan ? `zcode-agent plan resume ${plan[1]} "continue"` : `zcode-agent resume ${id} "continue"`;
|
|
805
851
|
errorOut = {
|
|
806
852
|
kind: 'timeout',
|
|
807
|
-
|
|
853
|
+
// Under a minute in seconds: "0 min" read as if nothing had run.
|
|
854
|
+
message: `timed out after ${inv.timeoutMs < 60000 ? `${Math.max(1, Math.round(inv.timeoutMs / 1000))} s` : `${Math.round(inv.timeoutMs / 60000)} min`}; "${cmd}" picks up from the current files`,
|
|
808
855
|
};
|
|
809
856
|
} else if (error) errorOut = { kind: error.kind || 'error', message: scrub(error.message) };
|
|
810
857
|
else if (preflightWrote.length) errorOut = { kind: 'preflight_wrote', message: issues[0] };
|
|
@@ -844,6 +891,9 @@ async function execute(inv, opts = {}) {
|
|
|
844
891
|
if (before && !diff) notVerified.push('changed files could not be tracked in this workspace');
|
|
845
892
|
if (subagentNote) issues.push(subagentNote);
|
|
846
893
|
if (verifierEdits.size) issues.push(`verifier edited files: ${[...verifierEdits].join(', ')}`);
|
|
894
|
+
// deriveStatus copies raw engine/MCP error text into issues, which reach
|
|
895
|
+
// result.json, the session record and the brief: never the key.
|
|
896
|
+
issues = issues.map(scrub);
|
|
847
897
|
|
|
848
898
|
const last = turns[turns.length - 1] || null;
|
|
849
899
|
const response = last ? last.response : '';
|
|
@@ -948,4 +998,4 @@ async function execute(inv, opts = {}) {
|
|
|
948
998
|
return result;
|
|
949
999
|
}
|
|
950
1000
|
|
|
951
|
-
module.exports = { execute, prepareSession, exitCodeFor, ExecError, readSettings
|
|
1001
|
+
module.exports = { execute, prepareSession, exitCodeFor, ExecError, readSettings };
|
package/lib/help.js
CHANGED
|
@@ -8,17 +8,17 @@ const SESSION = ` --id <id> name the session (existing id is never re-ru
|
|
|
8
8
|
--cwd <dir> workspace (default: current dir)
|
|
9
9
|
--owns <path> repeatable: paths this session may change (default: whole workspace)
|
|
10
10
|
--allow-overlap start despite overlapping ownership`;
|
|
11
|
-
const EXEC = ` --model <id> glm-5.3 | glm-5.3-flash (default glm-5.
|
|
11
|
+
const EXEC = ` --model <id> glm-5.4 | glm-5.3 | glm-5.3-flash (default glm-5.4)
|
|
12
12
|
--effort <lvl> low | high | max (default high)
|
|
13
|
-
--mcp <json|@f> add MCP servers (repeatable) --
|
|
13
|
+
--mcp <json|@f> add MCP servers (repeatable) --hermetic --no-browser
|
|
14
14
|
--skills <dir> add skills (repeatable) --no-skills
|
|
15
|
-
--inherit-desktop give the executor the desktop's AGENTS.md,
|
|
15
|
+
--inherit-desktop give the executor the desktop's AGENTS.md, plugins and agent profiles
|
|
16
16
|
--json NDJSON events; last line is the compact brief (--full: whole record)
|
|
17
17
|
--quiet no progress feed; with --json only the result line`;
|
|
18
18
|
|
|
19
19
|
const HELP = {
|
|
20
20
|
task: `usage: zcode-agent task [options] <objective...>
|
|
21
|
-
Execute a task contract, verify it with zcode-
|
|
21
|
+
Execute a task contract, verify it with checks zcode-agent runs itself, hand back.
|
|
22
22
|
|
|
23
23
|
contract:
|
|
24
24
|
--task <file|-> JSON contract or markdown brief (- = stdin)
|
|
@@ -83,9 +83,10 @@ Exits 0 when every watched session has finished; Ctrl-C exits 0.`,
|
|
|
83
83
|
GLM cost of every zcode-agent session whose workspace is <dir> or below it (default:
|
|
84
84
|
the current directory), per session and in total, at Z.ai API list price
|
|
85
85
|
(USD per M tokens: GLM-5.3-Flash 0.15 input / 0.03 cached / 0.50 output;
|
|
86
|
-
GLM-5.3 1.40 / 0.26 / 4.40
|
|
87
|
-
|
|
88
|
-
|
|
86
|
+
GLM-5.3 1.40 / 0.26 / 4.40; GLM-5.4 provisionally the same as GLM-5.3 until
|
|
87
|
+
Z.ai lists it). Counts come from each session's engine DB: every request of
|
|
88
|
+
the implementer, its subagents and the visual verifier, across resumes.
|
|
89
|
+
~ marks an estimate (no cache split, or a provisional price).
|
|
89
90
|
--app also the desktop app's own sessions in that directory
|
|
90
91
|
--json {type:"cost", dir, total, sessions[, app]}
|
|
91
92
|
ZCODE_PRICES='{"GLM-5.3-Flash":{"input":0.15,"cached":0.03,"output":0.5}}' overrides.`,
|
|
@@ -109,24 +110,25 @@ plan file: {cwd?, decisions?, context?, files?, model?, effort?, limits?,
|
|
|
109
110
|
--detach supervise in a background process
|
|
110
111
|
--id <name> plan name (default: file basename)
|
|
111
112
|
--cwd <dir> workspace override
|
|
112
|
-
Exit: 0 completed, 10 blocked, 8 partial/failed, 124 timeout.`,
|
|
113
|
+
Exit: 0 completed, 10 blocked, 8 partial/failed, 124 timeout, 7 name taken.`,
|
|
113
114
|
login: `usage: printf %s "$ZAI_API_KEY" | zcode-agent login
|
|
114
115
|
Store a Z.ai API key (read from piped stdin, never echoed) in ~/.zcode-agent.
|
|
115
116
|
Not needed when ZAI_API_KEY is set or the ZCode app holds a key.`,
|
|
116
117
|
doctor: `usage: zcode-agent doctor [--json] [--install-browser]
|
|
117
|
-
Engine, key, inherited MCP servers and skills, and browser report
|
|
118
|
+
Engine, key, inherited MCP servers and skills, and browser report (with
|
|
119
|
+
--hermetic, --no-browser, --mcp, --skills: the setup such a run would get).
|
|
118
120
|
--install-browser installs the Chromium build the default Playwright server
|
|
119
121
|
drives (needed only without the ZCode app's own Playwright server).`,
|
|
120
122
|
skills: `usage: zcode-agent skills [install|uninstall] [claude|codex]
|
|
121
123
|
Install the orchestrator skills (default: show status).`,
|
|
122
124
|
acp: `usage: zcode-agent acp [options]
|
|
123
125
|
Serve the Agent Client Protocol (ACP v1) on stdio: T3 Code, Zed and any ACP
|
|
124
|
-
client run GLM-5.3 through it. Each ACP session is a zcode-agent session
|
|
126
|
+
client run GLM-5.4 (or GLM-5.3, GLM-5.3-Flash) through it. Each ACP session is a zcode-agent session
|
|
125
127
|
(status, watch, cost see it); clients switch mode, model and effort per session.
|
|
126
128
|
--mode <mode> default for new sessions: build (ask before edits and
|
|
127
129
|
commands) | edit (accept edits) | plan | yolo (full access)
|
|
128
130
|
default build (or $ZCODE_ACP_MODE)
|
|
129
|
-
--model <id> glm-5.3 | glm-5.3-flash (default glm-5.
|
|
131
|
+
--model <id> glm-5.4 | glm-5.3 | glm-5.3-flash (default glm-5.4)
|
|
130
132
|
--effort <lvl> low | high | max (default high)
|
|
131
133
|
--timeout-ms <n> per prompt (default: none)
|
|
132
134
|
--mcp <json|@f> add MCP servers (repeatable) --hermetic --no-browser
|