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,914 @@
1
+ 'use strict';
2
+ // One invocation, start to handback. Every command that talks to the
3
+ // engine (run, task, agent, resume, detached workers) goes through
4
+ // execute(), so lifecycle, isolation, cancellation and the result shape are
5
+ // identical across them.
6
+ //
7
+ // record → capacity → lease → engine HOME → snapshot → open session
8
+ // → turn → [task: handback, checks, bounded repair turns] → subagents
9
+ // → diff → status → result.json + final record
10
+ //
11
+ // Side-effect discipline: only the session-open phase is retried (it never
12
+ // touches the workspace). A prompt that reached the engine is never re-sent
13
+ // automatically; continuing is an explicit `zcode resume`, which tells the
14
+ // model the earlier work is already applied.
15
+ const fs = require('node:fs');
16
+ const path = require('node:path');
17
+ const store = require('./store.js');
18
+ const { resolveRuntime, makeClient } = require('./bootstrap.js');
19
+ const { buildEngineHome, rootDir, liveDir, recordMcpHealth } = require('./isolation.js');
20
+ const { openSession, runTurn, TurnError } = require('./appserver.js');
21
+ const { runChecks } = require('./checks.js');
22
+ const { reservePort } = require('./ports.js');
23
+ const {
24
+ workspaceRoot,
25
+ isOwned,
26
+ isZcodePath,
27
+ acquireLease,
28
+ liveLeases,
29
+ snapshot,
30
+ diffSnapshots,
31
+ ensureLocalExclude,
32
+ } = require('./workspace.js');
33
+ const {
34
+ buildTaskPrompt,
35
+ buildRepairPrompt,
36
+ buildResumePrompt,
37
+ HANDBACK_REQUEST,
38
+ parseHandback,
39
+ deriveStatus,
40
+ visualGaps,
41
+ } = require('./contract.js');
42
+ const { buildVerifierPrompt, parseVisualBlock, notVerified: notVerifiedEntries } = require('./verify.js');
43
+ const { visionModel, supportsImage } = require('./models.js');
44
+
45
+ // Runaway guard for verifier turns: characters one model request may stream
46
+ // (reasoning, text and tool arguments) without a tool call. A safety net, not
47
+ // a tuning knob: real verifier requests peak near 9k output tokens (~36k
48
+ // chars); the one runaway seen generated tool arguments to the engine's
49
+ // 128k-token cap over 20 min and ended with an empty call. Set far above any
50
+ // real request so it never cuts legitimate work. Never applied to the
51
+ // implementer, whose planning requests legitimately stream 100k+ chars.
52
+ // (The engine's RPC model options accept only reasoningLevel: no server cap.)
53
+ const VERIFIER_MAX_STREAM_CHARS = 200000;
54
+
55
+ const RESULT_SCHEMA = 'zcode.result/1';
56
+ const SUBAGENT_TOOLS = new Set(['Agent', 'Task']);
57
+
58
+ class ExecError extends Error {
59
+ constructor(message, { exitCode, kind }) {
60
+ super(message);
61
+ this.exitCode = exitCode;
62
+ this.kind = kind;
63
+ }
64
+ }
65
+
66
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
67
+
68
+ // Settings a session keeps across invocations (stored as invocation.json).
69
+ const SETTING_KEYS = [
70
+ 'kind', 'label', 'cwd', 'model', 'effort', 'timeoutMs', 'maxRepairs', 'checkTimeoutMs',
71
+ 'checks', 'preflight', 'owns', 'ownsDisplay', 'touch', 'touchDisplay', 'acceptanceDeclared', 'mcpSpecs', 'hermetic', 'noBrowser',
72
+ 'skillsDirs', 'noSkills', 'inheritDesktop', 'profile', 'includeReasoning', 'allowOverlap', 'stream',
73
+ ];
74
+
75
+ function settingsOf(inv) {
76
+ const out = {};
77
+ for (const k of SETTING_KEYS) if (inv[k] !== undefined) out[k] = inv[k];
78
+ return out;
79
+ }
80
+
81
+ function readSettings(id, env) {
82
+ try {
83
+ return JSON.parse(fs.readFileSync(path.join(store.sessionDir(id, env), 'invocation.json'), 'utf8'));
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ function writeSettings(id, inv, env) {
90
+ store.writeJsonAtomic(path.join(store.sessionDir(id, env), 'invocation.json'), settingsOf(inv));
91
+ }
92
+
93
+ // Joins session/subagents with the per-session agents dir
94
+ // (<home>/.zcode/cli/agents/<parent>/agent_<uuid>/{metadata.json,output.txt}).
95
+ // NOTE (live-pinned): status "success" means the subagent RETURNED, not that
96
+ // its work is correct — the parent's integration checks are the gate.
97
+ async function collectSubagents(client, { sessionId, home }) {
98
+ const result = await client.request('session/subagents', { sessionId }, { timeoutMs: 15000 });
99
+ const items = (result && result.ended && result.ended.items) || [];
100
+ const running = (result && result.running) || [];
101
+ const agentsDir = path.join(home, '.zcode', 'cli', 'agents', sessionId);
102
+ const readJson = (f) => {
103
+ try {
104
+ return JSON.parse(fs.readFileSync(f, 'utf8'));
105
+ } catch {
106
+ return null;
107
+ }
108
+ };
109
+ const subagents = items.map((item) => {
110
+ const dir = path.join(agentsDir, `agent_${String(item.agentId || '').replace(/^agent_/, '')}`);
111
+ const metadata = readJson(path.join(dir, 'metadata.json'));
112
+ let output = null;
113
+ try {
114
+ output = fs.readFileSync(path.join(dir, 'output.txt'), 'utf8');
115
+ } catch {
116
+ /* not flushed */
117
+ }
118
+ return {
119
+ agentId: item.agentId || (metadata && metadata.agentId) || null,
120
+ childSessionId: item.childSessionId || (metadata && metadata.childSessionId) || null,
121
+ profileId: (metadata && metadata.profileId) || item.subagentType || null,
122
+ title: item.title || (metadata && metadata.description) || null,
123
+ status: item.status || null,
124
+ summary: item.summary || null,
125
+ output,
126
+ startedAt: item.startedAt || null,
127
+ endedAt: item.endedAt || null,
128
+ durationMs: item.startedAt && item.endedAt ? item.endedAt - item.startedAt : null,
129
+ };
130
+ });
131
+ return { subagents, runningCount: running.length };
132
+ }
133
+
134
+ function sumUsage(turns) {
135
+ let input = null;
136
+ let output = null;
137
+ for (const t of turns) {
138
+ if (!t.usage) continue;
139
+ if (typeof t.usage.inputTokens === 'number') input = (input || 0) + t.usage.inputTokens;
140
+ if (typeof t.usage.outputTokens === 'number') output = (output || 0) + t.usage.outputTokens;
141
+ }
142
+ return input === null && output === null ? null : { inputTokens: input, outputTokens: output };
143
+ }
144
+
145
+ // Model requests and tokens over every turn of an invocation, failed ones
146
+ // included (their usage never arrived: `incomplete`). null = nothing ran.
147
+ function usageOf(turns, failedTurns) {
148
+ const all = [...turns, ...failedTurns];
149
+ if (!all.length) return null;
150
+ const base = sumUsage(turns) || { inputTokens: null, outputTokens: null };
151
+ const incomplete = all.some((t) => !t.usage);
152
+ return {
153
+ ...base,
154
+ modelRequests: all.reduce((n, t) => n + (t.modelRequests || 0), 0),
155
+ ...(incomplete ? { incomplete: true } : {}),
156
+ };
157
+ }
158
+
159
+ // Running totals across invocations (resumes) kept on the session record.
160
+ function addUsageTotal(prior, usage) {
161
+ const p = prior || {};
162
+ const u = usage || {};
163
+ return {
164
+ inputTokens: (p.inputTokens || 0) + (u.inputTokens || 0),
165
+ outputTokens: (p.outputTokens || 0) + (u.outputTokens || 0),
166
+ modelRequests: (p.modelRequests || 0) + (u.modelRequests || 0),
167
+ };
168
+ }
169
+
170
+ function exitCodeFor(result) {
171
+ switch (result.status) {
172
+ case 'completed':
173
+ return 0;
174
+ case 'unverified':
175
+ return 9;
176
+ case 'blocked':
177
+ return 10;
178
+ case 'partial':
179
+ return 8;
180
+ case 'cancelled':
181
+ return 130;
182
+ default: {
183
+ const kind = result.error && result.error.kind;
184
+ if (kind === 'timeout') return 124;
185
+ if (kind === 'no_subagent') return 6;
186
+ if (kind === 'checks_failed') return 8;
187
+ if (kind === 'conflict' || kind === 'busy') return 7;
188
+ return 5;
189
+ }
190
+ }
191
+ }
192
+
193
+ // Claims the id and writes the first record + settings (+ task.json).
194
+ // Used directly by detached starts so the id exists before the worker runs.
195
+ function prepareSession(inv, env = process.env) {
196
+ const record = store.createSession(inv.id, {
197
+ kind: inv.kind,
198
+ label: inv.label || null,
199
+ cwd: fs.realpathSync(inv.cwd),
200
+ workspaceRoot: workspaceRoot(inv.cwd),
201
+ owns: inv.ownsDisplay || [],
202
+ ownsRoot: inv.owns || [],
203
+ touch: inv.touchDisplay || [],
204
+ preflight: Boolean(inv.preflight),
205
+ checks: inv.checks || [],
206
+ model: inv.model,
207
+ effort: inv.effort,
208
+ engineSessionId: null,
209
+ }, env);
210
+ writeSettings(inv.id, inv, env);
211
+ if (inv.kind === 'task') {
212
+ store.writeJsonAtomic(path.join(store.sessionDir(inv.id, env), 'task.json'), inv.contract);
213
+ }
214
+ return record;
215
+ }
216
+
217
+ // inv: {kind, id, resume?:{message}, adopt?, cwd, model, effort, timeoutMs,
218
+ // prompt (run/agent), contract (task), checks, owns, ownsDisplay, …}
219
+ // opts: {onEvent, signal, env, runtime}
220
+ // Returns the result object; throws ConfigError / ExecError / store errors
221
+ // for invocations that never started.
222
+ async function execute(inv, opts = {}) {
223
+ const env = opts.env || process.env;
224
+ const emit = opts.onEvent || (() => {});
225
+ const signal = opts.signal || null;
226
+ const started = Date.now();
227
+ const deadline = started + inv.timeoutMs;
228
+ const runtime = opts.runtime || resolveRuntime(env);
229
+ const { scrub } = runtime;
230
+ const id = inv.id;
231
+ const dir = store.sessionDir(id, env);
232
+ const home = path.join(dir, 'home');
233
+ const root = workspaceRoot(inv.cwd);
234
+
235
+ // --- record ---------------------------------------------------------------
236
+ const resuming = Boolean(inv.resume);
237
+ if (!resuming && !inv.adopt) prepareSession(inv, env);
238
+ const record = store.readSession(id, env);
239
+ if (!record) throw new ExecError(`no session "${id}"`, { exitCode: 2, kind: 'not_found' });
240
+ const busy = () => new ExecError(
241
+ `session "${id}" is still running (pid ${store.readSession(id, env).pid}). Wait for it or cancel it first.`,
242
+ { exitCode: 7, kind: 'busy' }
243
+ );
244
+ if (resuming && !inv.adopt) {
245
+ const view = store.viewSession(record);
246
+ if (view.live && record.pid !== process.pid) throw busy();
247
+ }
248
+ // Atomic: exactly one live process drives this session.
249
+ const releaseOwner = store.claimSession(id, env);
250
+ if (!releaseOwner) throw busy();
251
+ let releaseSlot = null;
252
+ const releaseClaims = () => {
253
+ if (releaseSlot) releaseSlot();
254
+ releaseOwner();
255
+ };
256
+ // Resuming a preflight session proceeds to the real task: answers + the
257
+ // full protocol, checks and visual verification from here on.
258
+ const leavingPreflight = resuming && Boolean(inv.preflight);
259
+ if (leavingPreflight) inv.preflight = false;
260
+ const preflight = Boolean(inv.preflight);
261
+ if (resuming) writeSettings(id, inv, env);
262
+ if (leavingPreflight) store.updateSession(id, { preflight: false }, env);
263
+ const isFirstInvocation = !record.engineSessionId;
264
+ const update = (patch) => store.updateSession(id, patch, env);
265
+
266
+ // --- activity relay ---------------------------------------------------------
267
+ let lastWrite = 0;
268
+ let toolCalls = record.activity ? record.activity.toolCalls || 0 : 0;
269
+ let subagentsStarted = record.activity ? record.activity.subagentsStarted || 0 : 0;
270
+ let modelRequests = record.activity ? record.activity.modelRequests || 0 : 0;
271
+ let subagentsRunning = 0;
272
+ let lastTool = null;
273
+ let lastToolAt = null;
274
+ let lastEventAt = null;
275
+ // What the model is doing inside the current request (for `watch`): a long
276
+ // think streams events for many minutes and is not a stall.
277
+ let current = null; // {doing: 'thinking'|'writing', since, chars}
278
+ let requestAt = null;
279
+ const activity = () => ({
280
+ toolCalls, subagentsStarted, subagentsRunning, modelRequests, lastTool, lastToolAt,
281
+ lastEventAt: lastEventAt || new Date().toISOString(),
282
+ current,
283
+ });
284
+ const relay = (ev) => {
285
+ emit(ev);
286
+ const now = Date.now();
287
+ lastEventAt = new Date(now).toISOString(); // any engine event counts as life
288
+ if (ev.type === 'model_request_started') {
289
+ modelRequests++;
290
+ requestAt = new Date(now).toISOString();
291
+ current = null;
292
+ }
293
+ if (ev.type === 'stream' && (ev.kind === 'reasoning_delta' || ev.kind === 'text_delta')) {
294
+ const doing = ev.kind === 'reasoning_delta' ? 'thinking' : 'writing';
295
+ if (!current || current.doing !== doing) current = { doing, since: requestAt || new Date(now).toISOString(), chars: 0 };
296
+ current.chars += typeof ev.delta === 'string' ? ev.delta.length : 0;
297
+ }
298
+ if (ev.type === 'tool') {
299
+ current = null;
300
+ if (ev.phase === 'started') {
301
+ toolCalls++;
302
+ lastTool = ev.name;
303
+ lastToolAt = new Date(now).toISOString();
304
+ if (SUBAGENT_TOOLS.has(ev.name)) {
305
+ subagentsStarted++;
306
+ subagentsRunning++;
307
+ emit({ type: 'subagent', phase: 'started', toolCallId: ev.id });
308
+ }
309
+ } else if ((ev.phase === 'result' || ev.phase === 'error') && SUBAGENT_TOOLS.has(ev.name)) {
310
+ subagentsRunning = Math.max(0, subagentsRunning - 1);
311
+ emit({ type: 'subagent', phase: ev.phase === 'result' ? 'returned' : 'error', toolCallId: ev.id });
312
+ }
313
+ }
314
+ try {
315
+ if (!(ev.type === 'stream' || ev.type === 'model_request_started' || ev.type === 'state' || ev.type === 'turn')) {
316
+ store.appendEvent(id, ev, env);
317
+ }
318
+ if (now - lastWrite > 1000) {
319
+ lastWrite = now;
320
+ update({ activity: activity() });
321
+ }
322
+ } catch {
323
+ /* activity is best-effort; never fail the run over it */
324
+ }
325
+ };
326
+ const setPhase = (phase, detail = {}) => {
327
+ const ev = { type: 'phase', phase, ...detail };
328
+ emit(ev);
329
+ try {
330
+ store.appendEvent(id, ev, env);
331
+ lastEventAt = new Date().toISOString();
332
+ current = null; // a new phase (checks, verifying, repairing) is not the old stream
333
+ update({ phase, phaseDetail: Object.keys(detail).length ? detail : null, activity: activity() });
334
+ } catch {
335
+ /* best-effort */
336
+ }
337
+ };
338
+
339
+ emit({
340
+ type: 'session',
341
+ id,
342
+ kind: inv.kind,
343
+ label: inv.label || null,
344
+ resumed: resuming,
345
+ cwd: record.cwd,
346
+ owns: inv.ownsDisplay || [],
347
+ checks: inv.checks || [],
348
+ model: inv.model,
349
+ effort: inv.effort,
350
+ });
351
+
352
+ // --- capacity ---------------------------------------------------------------
353
+ const maxActive = Number(env.ZAI_CODE_MAX_ACTIVE) || 8;
354
+ update({ state: 'queued', phase: 'queued', pid: process.pid, status: null });
355
+ releaseSlot = store.claimSlot(maxActive, env);
356
+ if (!releaseSlot) {
357
+ setPhase('queued', { reason: `${maxActive} sessions already running (ZAI_CODE_MAX_ACTIVE)` });
358
+ while (!releaseSlot && !(signal && signal.aborted) && Date.now() < deadline) {
359
+ await sleep(1000);
360
+ releaseSlot = store.claimSlot(maxActive, env);
361
+ }
362
+ }
363
+
364
+ // --- lease ------------------------------------------------------------------
365
+ // A preflight is read-only: it reserves nothing and conflicts with nobody.
366
+ const lease = preflight
367
+ ? { ok: true, conflicts: [], others: [], release() {} }
368
+ : acquireLease({ id, root, owns: inv.owns || [], touch: inv.touch || [], allowOverlap: inv.allowOverlap, env });
369
+ if (!lease.ok) {
370
+ const names = lease.conflicts
371
+ .map((c) => `${c.id} (owns ${c.owns && c.owns.length ? c.owns.join(', ') : 'the whole workspace'})`)
372
+ .join('; ');
373
+ const message = lease.touch
374
+ ? `workspace conflict in ${root}: --touch ${(inv.touchDisplay || []).join(', ')} is owned by running session(s) ${names}. ` +
375
+ 'Wait for them, touch something else, or pass --allow-overlap.'
376
+ : `workspace conflict in ${root}: overlapping ownership with running session(s) ${names}. ` +
377
+ 'Declare disjoint --owns paths, use a separate worktree, wait for them, or pass --allow-overlap.';
378
+ if (inv.adopt) {
379
+ // A detached worker: the caller is polling this id, so leave a result.
380
+ store.writeResult(id, {
381
+ type: 'result', schema: RESULT_SCHEMA, ok: false, status: 'failed', id, kind: inv.kind,
382
+ error: { kind: 'conflict', message }, issues: [message],
383
+ }, env);
384
+ update({ state: 'finished', phase: 'done', status: 'failed', outcome: { status: 'failed', issues: [message] } });
385
+ } else if (!resuming) {
386
+ store.deleteSession(id, env); // the id stays free for a later retry
387
+ } else {
388
+ update({ state: 'finished', phase: 'done', status: record.status });
389
+ }
390
+ releaseClaims();
391
+ throw new ExecError(message, { exitCode: 7, kind: 'conflict' });
392
+ }
393
+
394
+ update({ state: 'running', phase: 'starting' });
395
+ ensureLocalExclude(record.cwd);
396
+
397
+ let client = null;
398
+ let session = null;
399
+ const turns = [];
400
+ const vturns = []; // independent verifier turns (never the implementer's)
401
+ const failedTurns = []; // turns that threw: only their partial facts survive
402
+ let checks = [];
403
+ let repairs = 0;
404
+ let parsed = { handback: null, report: '', error: 'missing' };
405
+ let error = null;
406
+ let userInput = null;
407
+ let subagents = null;
408
+ let subagentNote = null;
409
+ let built = null;
410
+ let before = null;
411
+ let releasePort = null;
412
+ let sessionEnv = null;
413
+ const visualDeclared = (inv.contract && inv.contract.visual) || [];
414
+ const concurrent = new Map(lease.others.map((o) => [o.id, o.owns || []]));
415
+ // Sessions that started after us (a parallel plan sibling a few ms later)
416
+ // are not in lease.others: re-read the live leases before attributing a
417
+ // change to us or to our verifier.
418
+ const refreshConcurrent = () => {
419
+ for (const other of liveLeases(root, env)) {
420
+ if (other.id !== id) concurrent.set(other.id, other.owns || []);
421
+ }
422
+ };
423
+ const checkTouched = new Set(); // files written by zcode's own check runs and the verifier
424
+ const verifierEdits = new Set();
425
+ let verifierModel = null;
426
+ let verifyRounds = 0;
427
+ let visualEntries = null; // the verifier's verdicts: authoritative `visual`
428
+ const invocationStart = new Date(started).toISOString();
429
+
430
+ try {
431
+ if (signal && signal.aborted) throw new TurnError('cancelled', { kind: 'cancelled' });
432
+ if (!releaseSlot) throw new TurnError('run exceeded --timeout-ms while queued', { kind: 'timeout' });
433
+
434
+ // Per-session environment for the executor AND the checks: a port no
435
+ // other live session holds, plus output and scratch dirs of its own.
436
+ const reserved = await reservePort({ env, preferred: record.port });
437
+ if (!reserved) throw new ExecError('no free port for ZCODE_PORT in 41000-48999', { exitCode: 5, kind: 'no_port' });
438
+ releasePort = reserved.release;
439
+ const outDir = path.join(record.cwd, '.zcode', 'out', id);
440
+ const tmpDir = path.join(dir, 'tmp');
441
+ fs.mkdirSync(outDir, { recursive: true });
442
+ fs.mkdirSync(tmpDir, { recursive: true, mode: 0o700 });
443
+ sessionEnv = {
444
+ ZCODE_SESSION_ID: id,
445
+ ZCODE_PORT: String(reserved.port),
446
+ ZCODE_OUT: outDir,
447
+ ZCODE_TMP: tmpDir,
448
+ };
449
+ update({ port: reserved.port, out: outDir, tmp: tmpDir });
450
+
451
+ built = buildEngineHome({
452
+ home,
453
+ root: rootDir(env),
454
+ key: runtime.key,
455
+ live: liveDir(env),
456
+ mcpSpecs: inv.mcpSpecs || [],
457
+ hermetic: !!inv.hermetic || env.ZCODE_HERMETIC === '1',
458
+ browser: !inv.noBrowser,
459
+ skillsDirs: inv.skillsDirs || [],
460
+ noSkills: inv.noSkills,
461
+ inheritDesktop: !!inv.inheritDesktop || env.ZCODE_INHERIT_DESKTOP === '1',
462
+ profile: inv.profile,
463
+ model: inv.model,
464
+ });
465
+ before = snapshot(root);
466
+ // Inherited servers that fail to connect: surfaced once in the feed and
467
+ // remembered, so the next sessions skip them for a while.
468
+ const reportedMcp = new Set();
469
+ const rememberMcp = (statuses) => {
470
+ recordMcpHealth(rootDir(env), statuses, built.mcp.inherited);
471
+ for (const name of Object.keys(built.mcp.inherited)) {
472
+ const entry = statuses[name];
473
+ if (!entry || entry.status !== 'failed' || reportedMcp.has(name)) continue;
474
+ reportedMcp.add(name);
475
+ relay({ type: 'mcp', name, status: 'failed', inherited: true, toolCount: null, error: entry.error ? scrub(String(typeof entry.error === 'string' ? entry.error : JSON.stringify(entry.error))).slice(0, 300) : null });
476
+ }
477
+ };
478
+
479
+ // Open the engine session; retry once on engine timeouts/exits (safe:
480
+ // nothing has been sent to the model yet).
481
+ setPhase('starting');
482
+ for (let attempt = 1; ; attempt++) {
483
+ client = makeClient(runtime, { home, cwd: record.cwd, sessionEnv });
484
+ client.start();
485
+ update({ enginePid: client.child.pid });
486
+ try {
487
+ session = await openSession(client, {
488
+ workspacePath: record.cwd,
489
+ modelId: inv.model,
490
+ effort: inv.effort,
491
+ resumeSessionId: record.engineSessionId || null,
492
+ requiredMcp: built.mcp.added,
493
+ onEvent: relay,
494
+ onMcpStatuses: rememberMcp,
495
+ });
496
+ break;
497
+ } catch (err) {
498
+ client.kill();
499
+ const transient = /timeout|exited|failed to start|dead/.test(err.message);
500
+ if (attempt >= 2 || !transient || (signal && signal.aborted) || Date.now() >= deadline) throw err;
501
+ relay({ type: 'retry', phase: 'open_session', reason: scrub(err.message).slice(0, 300) });
502
+ }
503
+ }
504
+ update({ engineSessionId: session.sessionId });
505
+
506
+ // First prompt for this invocation.
507
+ let prompt;
508
+ if (inv.kind === 'task') {
509
+ const taskPrompt = () => buildTaskPrompt(inv.contract, {
510
+ ownsDisplay: inv.ownsDisplay || [],
511
+ session: { id, port: sessionEnv.ZCODE_PORT, out: sessionEnv.ZCODE_OUT, tmp: sessionEnv.ZCODE_TMP },
512
+ preflight,
513
+ canSeeImages: supportsImage(inv.model, { env, builtinConfig: runtime.builtinConfig }),
514
+ });
515
+ prompt = leavingPreflight
516
+ ? `${taskPrompt()}\n\n## Answers to your preflight questions\nThe preflight is over: implement the task now (edits are allowed). The orchestrator's answers are binding:\n${(inv.resume.message || '').trim() || '(none: take the most conservative choice for anything open and list it in handback `decisions`)'}`
517
+ : isFirstInvocation
518
+ ? taskPrompt() +
519
+ (resuming && inv.resume.message ? `\n\n## Message from the orchestrator\n${inv.resume.message}` : '')
520
+ : buildResumePrompt(inv.resume ? inv.resume.message : '', {
521
+ kind: 'task',
522
+ // The port is the one thing that may have changed since the first prompt.
523
+ portChange: record.port && String(record.port) !== sessionEnv.ZCODE_PORT ? sessionEnv.ZCODE_PORT : null,
524
+ });
525
+ } else if (inv.kind === 'agent') {
526
+ prompt =
527
+ `You MUST use the Agent tool (profileId: "${inv.profile}") to accomplish the ` +
528
+ `task below — do not do the work yourself. When the subagent finishes, ` +
529
+ `report its agent id and result.\n\nTask: ${inv.resume ? inv.resume.message : inv.prompt}`;
530
+ } else {
531
+ prompt = inv.resume ? buildResumePrompt(inv.resume.message, { kind: 'run' }) : inv.prompt;
532
+ }
533
+
534
+ // One verifier round: a NEW engine session (own client: fresh context,
535
+ // separate from the implementer's) on the first image-capable model.
536
+ // Returns an entry per criterion; failures become met:null, never false.
537
+ const verifyVisual = async (round) => {
538
+ verifierModel = visionModel({ env, builtinConfig: runtime.builtinConfig });
539
+ verifyRounds = round;
540
+ setPhase('verifying', { round });
541
+ const vprompt = buildVerifierPrompt(inv.contract, {
542
+ session: { id, port: sessionEnv.ZCODE_PORT, out: sessionEnv.ZCODE_OUT, tmp: sessionEnv.ZCODE_TMP },
543
+ round,
544
+ });
545
+ const preSnap = before ? snapshot(root) : null;
546
+ let entries = null;
547
+ let why = 'verifier did not run';
548
+ for (let attempt = 1; attempt <= 2 && !entries; attempt++) {
549
+ if ((signal && signal.aborted) || Date.now() >= deadline) break;
550
+ let vclient = null;
551
+ let streamed = 0;
552
+ let runaway = false;
553
+ const maxStream = Number(env.ZCODE_VERIFIER_MAX_STREAM_CHARS) || VERIFIER_MAX_STREAM_CHARS;
554
+ const vrelay = (ev) => {
555
+ relay(ev);
556
+ if (ev.type === 'model_request_started' || ev.type === 'tool') streamed = 0;
557
+ else if (ev.type === 'stream' && typeof ev.delta === 'string') {
558
+ streamed += ev.delta.length;
559
+ if (streamed > maxStream && !runaway && vclient) {
560
+ runaway = true;
561
+ vclient.kill();
562
+ }
563
+ }
564
+ };
565
+ try {
566
+ vclient = makeClient(runtime, { home, cwd: record.cwd, sessionEnv });
567
+ vclient.start();
568
+ const vsession = await openSession(vclient, {
569
+ workspacePath: record.cwd,
570
+ modelId: verifierModel,
571
+ effort: 'high',
572
+ requiredMcp: built.mcp.added,
573
+ onEvent: vrelay,
574
+ onMcpStatuses: rememberMcp,
575
+ });
576
+ const vturn = await runTurn(vclient, vsession, {
577
+ modelId: verifierModel,
578
+ effort: 'high',
579
+ prompt: vprompt,
580
+ deadline,
581
+ signal,
582
+ onEvent: vrelay,
583
+ });
584
+ vturns.push(vturn);
585
+ if (runaway) throw new Error('runaway'); // whatever arrived after the kill does not count
586
+ const p = parseVisualBlock(vturn.response);
587
+ if (p.error) why = `the verifier gave no usable zcode-visual block (${p.error})`;
588
+ else entries = p.entries;
589
+ } catch (err) {
590
+ if (err && err.turn) failedTurns.push(err.turn);
591
+ if (err && (err.kind === 'timeout' || err.kind === 'cancelled')) throw err;
592
+ why = runaway
593
+ ? `a verifier request ran away (over ${maxStream} chars streamed without a tool call)`
594
+ : `verifier failed: ${scrub(err && err.message ? err.message : String(err)).slice(0, 200)}`;
595
+ } finally {
596
+ if (vclient) vclient.kill();
597
+ }
598
+ }
599
+ if (preSnap) {
600
+ refreshConcurrent();
601
+ const owned = (p) => [...concurrent.values()].some((o) => o.length && isOwned(p, o));
602
+ for (const f of diffSnapshots(preSnap, snapshot(root)) || []) {
603
+ if (isZcodePath(f.path) || owned(f.path)) continue;
604
+ verifierEdits.add(f.path);
605
+ checkTouched.add(f.path); // verifier edits are an issue, not a task scope violation
606
+ }
607
+ }
608
+ const got = entries || [];
609
+ const gaps = visualGaps(got, visualDeclared);
610
+ return [...got, ...notVerifiedEntries(gaps.missing, entries ? 'the verifier did not report it' : why)];
611
+ };
612
+
613
+ let askedForHandback = false;
614
+ let phase = 'executing';
615
+ for (;;) {
616
+ setPhase(phase, phase === 'repairing' ? { attempt: repairs, of: inv.maxRepairs } : {});
617
+ const turn = await runTurn(client, session, {
618
+ modelId: inv.model,
619
+ effort: inv.effort,
620
+ prompt,
621
+ deadline,
622
+ signal,
623
+ keepReasoning: inv.includeReasoning,
624
+ onEvent: relay,
625
+ });
626
+ turns.push(turn);
627
+ update({ turns: (record.turns || 0) + turns.length });
628
+ if (inv.kind !== 'task') break;
629
+
630
+ const next = parseHandback(turn.response);
631
+ // A handback-only follow-up keeps the substantive report from before.
632
+ parsed = { ...next, report: next.report || parsed.report };
633
+ if (parsed.error && !askedForHandback && Date.now() < deadline) {
634
+ askedForHandback = true;
635
+ prompt = HANDBACK_REQUEST;
636
+ phase = 'reporting';
637
+ continue;
638
+ }
639
+ if (preflight) break; // read-only: zcode-agent runs nothing
640
+ if (parsed.handback && parsed.handback.status === 'blocked') break;
641
+ if (!inv.checks.length && !visualDeclared.length) break;
642
+
643
+ if (inv.checks.length) {
644
+ setPhase('checking', { count: inv.checks.length });
645
+ const preChecks = before ? snapshot(root) : null;
646
+ checks = await runChecks(inv.checks, {
647
+ cwd: record.cwd,
648
+ env: { ...env, ...sessionEnv },
649
+ timeoutMs: Math.max(1000, Math.min(inv.checkTimeoutMs, deadline - Date.now())),
650
+ signal,
651
+ onEvent: relay,
652
+ });
653
+ if (preChecks) {
654
+ for (const f of diffSnapshots(preChecks, snapshot(root)) || []) checkTouched.add(f.path);
655
+ }
656
+ if (Date.now() >= deadline && checks.some((c) => c.timedOut)) {
657
+ throw new TurnError('run exceeded --timeout-ms during acceptance checks', { kind: 'timeout' });
658
+ }
659
+ }
660
+ const failures = checks.filter((c) => !c.ok);
661
+ // zcode, not the implementer, judges the visual criteria. Unmet ones
662
+ // share the repair budget with failing checks; a verifier that could
663
+ // not run (met:null) is reported, not repaired.
664
+ let visualUnmet = [];
665
+ if (visualDeclared.length && !failures.length && parsed.handback
666
+ && !(signal && signal.aborted) && Date.now() < deadline) {
667
+ visualEntries = await verifyVisual(verifyRounds + 1);
668
+ visualUnmet = visualEntries.filter((v) => v.met === false);
669
+ }
670
+ if ((!failures.length && !visualUnmet.length) || repairs >= inv.maxRepairs) break;
671
+ if ((signal && signal.aborted) || Date.now() >= deadline) break;
672
+ repairs++;
673
+ prompt = buildRepairPrompt(failures, { attempt: repairs, maxRepairs: inv.maxRepairs, visual: visualUnmet });
674
+ phase = 'repairing';
675
+ }
676
+
677
+ if (inv.kind === 'task' || inv.kind === 'agent') {
678
+ try {
679
+ const collected = await collectSubagents(client, { sessionId: session.sessionId, home });
680
+ subagents = collected.subagents;
681
+ if (collected.runningCount) subagentNote = `${collected.runningCount} subagent(s) still running at handback`;
682
+ } catch (err) {
683
+ subagentNote = `subagent report unavailable: ${scrub(err.message).slice(0, 200)}`;
684
+ if (inv.kind === 'agent') throw new TurnError(subagentNote, { kind: 'subagents_rpc' });
685
+ }
686
+ }
687
+ } catch (err) {
688
+ error = err;
689
+ if (err && err.turn) failedTurns.push(err.turn);
690
+ } finally {
691
+ if (client) client.kill();
692
+ if (releasePort) releasePort();
693
+ lease.release();
694
+ releaseClaims();
695
+ }
696
+
697
+ // --- assemble the handback --------------------------------------------------
698
+ const cancelled = Boolean(signal && signal.aborted) || (error && error.kind === 'cancelled');
699
+ if (error && error.kind === 'user_input') {
700
+ userInput = error.message.replace(/^headless run requested user input: /, '');
701
+ }
702
+ refreshConcurrent();
703
+ // Sessions in this workspace that were active at any point during this
704
+ // invocation, including ones that finished before us (their leases are
705
+ // gone): their changes are theirs, not scope violations of ours.
706
+ for (const other of store.listSessions(env)) {
707
+ if (other.id === id || other.workspaceRoot !== root || concurrent.has(other.id)) continue;
708
+ if (String(other.updatedAt) >= invocationStart && Array.isArray(other.ownsRoot)) {
709
+ concurrent.set(other.id, other.ownsRoot);
710
+ }
711
+ }
712
+ const after = before ? snapshot(root) : null;
713
+ const diff = before ? diffSnapshots(before, after) : null;
714
+ const owns = inv.owns || [];
715
+ const touch = inv.touch || [];
716
+ const files = (diff || [])
717
+ .filter((f) => !isZcodePath(f.path))
718
+ .map((f) => {
719
+ const owned = isOwned(f.path, owns);
720
+ // --touch: edits allowed but reported, never a scope violation.
721
+ const touchedByDesign = !owned && touch.length > 0 && isOwned(f.path, touch);
722
+ const by = owned || touchedByDesign
723
+ ? null
724
+ : [...concurrent.entries()].find(([, o]) => o.length && isOwned(f.path, o));
725
+ const fromChecks = !owned && !touchedByDesign && !by && checkTouched.has(f.path);
726
+ return {
727
+ ...f,
728
+ owned,
729
+ ...(touchedByDesign ? { touched: true } : {}),
730
+ ...(by ? { concurrentSession: by[0] } : {}),
731
+ ...(fromChecks ? { fromChecks: true } : {}),
732
+ };
733
+ });
734
+ const touched = files.filter((f) => f.touched).map((f) => f.path);
735
+ const scopeViolations = files
736
+ .filter((f) => !f.owned && !f.touched && !f.concurrentSession && !f.fromChecks)
737
+ .map((f) => f.path);
738
+
739
+ const handback = parsed.handback;
740
+ // Preflight is read-only: anything it changed (that no concurrent session
741
+ // owns) is a protocol breach.
742
+ const preflightWrote = preflight
743
+ ? files
744
+ .filter((f) => ![...concurrent.values()].some((o) => o.length && isOwned(f.path, o)))
745
+ .map((f) => f.path)
746
+ : [];
747
+ let { status, issues } = deriveStatus({
748
+ kind: inv.kind,
749
+ error: error && !cancelled && error.kind !== 'user_input' ? error : null,
750
+ cancelled,
751
+ userInput,
752
+ handback,
753
+ handbackError: parsed.error,
754
+ checks,
755
+ scopeViolations: preflight ? [] : scopeViolations,
756
+ preflight,
757
+ preflightWrote,
758
+ visualDeclared,
759
+ visual: visualEntries || [],
760
+ });
761
+
762
+ let errorOut = null;
763
+ if (status === 'failed') {
764
+ if (error && error.kind === 'timeout') {
765
+ // The work already on disk is kept; resuming continues from it.
766
+ const plan = /^plan:(\S+)/.exec(inv.label || record.label || '');
767
+ const cmd = plan ? `zcode-agent plan resume ${plan[1]} "continue"` : `zcode-agent resume ${id} "continue"`;
768
+ errorOut = {
769
+ kind: 'timeout',
770
+ message: `timed out after ${Math.round(inv.timeoutMs / 60000)} min; "${cmd}" picks up from the current files`,
771
+ };
772
+ } else if (error) errorOut = { kind: error.kind || 'error', message: scrub(error.message) };
773
+ else if (preflightWrote.length) errorOut = { kind: 'preflight_wrote', message: issues[0] };
774
+ else if (checks.some((c) => !c.ok)) errorOut = { kind: 'checks_failed', message: issues[0] };
775
+ } else if (status === 'cancelled') {
776
+ errorOut = { kind: 'cancelled', message: 'cancelled' };
777
+ }
778
+ if (inv.kind === 'agent' && status === 'completed') {
779
+ const ok = subagents && subagents.length >= 1 && subagents.every((s) => s.status === 'success');
780
+ if (!ok) {
781
+ status = 'failed';
782
+ const why = !subagents || subagents.length === 0
783
+ ? 'no subagent was dispatched'
784
+ : `subagent statuses: ${subagents.map((s) => s.status).join(', ')}`;
785
+ issues = [why];
786
+ errorOut = { kind: 'no_subagent', message: why };
787
+ }
788
+ }
789
+
790
+ const notVerified = [];
791
+ if (inv.kind === 'task' && preflight) {
792
+ notVerified.push('preflight: the questions come from reading only; nothing was built, run or checked');
793
+ } else if (inv.kind === 'task') {
794
+ if (!inv.checks.length) notVerified.push('no acceptance checks were declared; nothing was executed by zcode-agent to verify the work');
795
+ if (inv.acceptanceDeclared) notVerified.push('prose acceptance criteria are confirmed only by the executor\'s own report');
796
+ if (subagents && subagents.length) notVerified.push('subagent "success" means the subagent returned; only the integrated result is verified');
797
+ if (handback && handback.units.length) {
798
+ notVerified.push(`unit results are executor claims: ${handback.units.map((u) => `${u.name} ${u.status || '?'}`).join(', ')}; only the integrated result is verified`);
799
+ }
800
+ if (visualDeclared.length) {
801
+ const judged = visualEntries || [];
802
+ notVerified.push(visualEntries
803
+ ? `visual criteria judged by an independent ${verifierModel} verifier from its own screenshots (${judged.filter((v) => v.met === true).length} of ${judged.length} met)`
804
+ : 'visual criteria were not judged: the independent verifier did not run');
805
+ }
806
+ }
807
+ if (before && !diff) notVerified.push('changed files could not be tracked in this workspace');
808
+ if (subagentNote) issues.push(subagentNote);
809
+ if (verifierEdits.size) issues.push(`verifier edited files: ${[...verifierEdits].join(', ')}`);
810
+
811
+ const last = turns[turns.length - 1] || null;
812
+ const response = last ? last.response : '';
813
+ const questions = [...(handback ? handback.questions : [])];
814
+ if (userInput) questions.push(userInput);
815
+
816
+ const usage = usageOf([...turns, ...vturns], failedTurns);
817
+ const usageTotal = addUsageTotal(record.usageTotal, usage);
818
+ const result = {
819
+ type: 'result',
820
+ schema: RESULT_SCHEMA,
821
+ ok: status === 'completed',
822
+ status,
823
+ id,
824
+ kind: inv.kind,
825
+ label: inv.label || null,
826
+ summary: preflight && status === 'completed'
827
+ ? 'no open questions'
828
+ : handback && handback.summary ? handback.summary : '',
829
+ response: inv.kind === 'task' ? parsed.report : response,
830
+ issues,
831
+ questions,
832
+ unresolved: handback ? handback.unresolved : [],
833
+ notVerified,
834
+ changes: {
835
+ tracking: before ? (diff ? before.kind : 'unavailable') : 'not-started',
836
+ files,
837
+ },
838
+ scopeViolations,
839
+ touched,
840
+ ...(preflight ? { preflight: true } : {}),
841
+ decisions: handback ? handback.decisions : [],
842
+ visual: visualEntries || [],
843
+ executorVisual: handback ? handback.visual : [],
844
+ ...(visualDeclared.length ? { verifier: { model: verifierModel, rounds: verifyRounds } } : {}),
845
+ units: handback ? handback.units : [],
846
+ sessionEnv: sessionEnv
847
+ ? { port: Number(sessionEnv.ZCODE_PORT), out: sessionEnv.ZCODE_OUT, tmp: sessionEnv.ZCODE_TMP }
848
+ : null,
849
+ checks: checks.map((c) => ({
850
+ command: c.command,
851
+ ok: c.ok,
852
+ exitCode: c.exitCode,
853
+ timedOut: c.timedOut,
854
+ durationMs: c.durationMs,
855
+ output: scrub(c.output),
856
+ })),
857
+ checksPassed: checks.length ? checks.every((c) => c.ok) : null,
858
+ repairs,
859
+ handback,
860
+ subagents,
861
+ error: errorOut,
862
+ cwd: record.cwd,
863
+ workspaceRoot: root,
864
+ owns: inv.ownsDisplay || [],
865
+ sessionId: session ? session.sessionId : record.engineSessionId || null,
866
+ resumed: resuming || Boolean(session && session.resumed),
867
+ turns: turns.length,
868
+ model: (last && last.engineModel) || inv.model,
869
+ modelRequested: inv.model,
870
+ effort: (last && last.engineReasoningLevel) || inv.effort,
871
+ effortRequested: inv.effort,
872
+ mode: session ? session.mode : null,
873
+ usage,
874
+ usageTotal,
875
+ reasoningChars: turns.reduce((n, t) => n + t.reasoningChars, 0),
876
+ toolCalls: turns.some((t) => typeof t.toolCallCount === 'number')
877
+ ? turns.reduce((n, t) => n + (t.toolCallCount || 0), 0)
878
+ : null,
879
+ toolEvents: turns.reduce((n, t) => n + t.toolEvents, 0),
880
+ mcpServers: built ? Object.keys(built.mcp.servers) : [],
881
+ skillsInjected: built ? built.skillsInjected : [],
882
+ terminalStatus: last ? last.terminalStatus : null,
883
+ streamingEvents: turns.reduce((n, t) => n + t.streamingEvents, 0),
884
+ durationMs: Date.now() - started,
885
+ files: {
886
+ session: dir,
887
+ result: path.join(dir, 'result.json'),
888
+ events: path.join(dir, 'events.ndjson'),
889
+ },
890
+ };
891
+ if (inv.includeReasoning) result.reasoning = turns.map((t) => t.reasoningText).join('');
892
+
893
+ store.writeResult(id, result, env);
894
+ store.appendEvent(id, { type: 'result', status }, env);
895
+ update({
896
+ state: 'finished',
897
+ phase: 'done',
898
+ status,
899
+ usageTotal,
900
+ phaseDetail: null,
901
+ activity: activity(),
902
+ outcome: {
903
+ status,
904
+ summary: result.summary,
905
+ issues: issues.slice(0, 5),
906
+ checksPassed: result.checksPassed,
907
+ changedFiles: files.length,
908
+ durationMs: result.durationMs,
909
+ },
910
+ });
911
+ return result;
912
+ }
913
+
914
+ module.exports = { execute, prepareSession, exitCodeFor, ExecError, readSettings, RESULT_SCHEMA };