zcode-agent 1.2.0 → 1.3.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  <p align="center">
2
2
  <picture>
3
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/0xgeorgemathew/zcode-agent/main/docs/assets/hero-dark.svg">
4
- <img src="https://raw.githubusercontent.com/0xgeorgemathew/zcode-agent/main/docs/assets/hero-light.svg" width="960" alt="Your agent (Claude Code, Codex or any agent with a shell) writes the decisions and a task contract. zcode-agent runs parallel GLM-5.3 sessions that build, run their own checks and repair failures, and has a fresh GLM-5.3-Flash session judge screenshots. One handback line returns to your agent.">
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/0xgeorgemathew/zcode-agent/d5db74513374006362d70dd2fd380683c1c7cf2b/docs/assets/hero-dark.svg">
4
+ <img src="https://raw.githubusercontent.com/0xgeorgemathew/zcode-agent/d5db74513374006362d70dd2fd380683c1c7cf2b/docs/assets/hero-light.svg" width="960" alt="Your agent (Claude Code, Codex or any agent with a shell) writes the decisions and a task contract. zcode-agent runs parallel GLM-5.3 sessions that build, run their own checks and repair failures, and has a fresh GLM-5.3-Flash session judge screenshots. One handback line returns to your agent.">
5
5
  </picture>
6
6
  </p>
7
7
 
@@ -43,7 +43,7 @@ To skip `npx`, install it once with `npm install -g zcode-agent`. It needs Node
43
43
 
44
44
  zcode-agent is also an [ACP](https://agentclientprotocol.com) agent: `zcode-agent acp` lets you chat with GLM-5.3 directly in T3 Code, Zed or any other Agent Client Protocol client. See [Use it in T3 Code, Zed or any ACP client](#use-it-in-t3-code-zed-or-any-acp-client).
45
45
 
46
- **With the ZCode app installed, there is nothing to configure.** zcode-agent reads the app's Z.ai API key where it is stored (it never copies or prints it) and gives every session the app's MCP servers and skills. It leaves out remote MCP servers that sign in with OAuth, because a headless session can't complete the sign-in, and it skips a server that failed to connect for the next six hours. The app's plugins, agent profiles and your global `AGENTS.md` stay out unless you pass `--inherit-desktop`. `--hermetic` leaves out the app's MCP servers and skills as well.
46
+ **With the ZCode app installed, there is nothing to configure.** zcode-agent reads the app's Z.ai API key where it is stored (it never copies or prints it) and gives every session the app's MCP servers and skills. It leaves out remote MCP servers that sign in with OAuth, because a headless session can't complete the sign-in, and it skips a server that failed to connect for the next six hours (twice as long after each further failure, up to four days). The app's plugins, agent profiles and your global `AGENTS.md` stay out unless you pass `--inherit-desktop`. `--hermetic` leaves out the app's MCP servers and skills as well.
47
47
 
48
48
  **Without the app**, set an API key and install a browser for visual checks:
49
49
 
@@ -276,12 +276,12 @@ The counts come from each session's own engine database and include the executor
276
276
 
277
277
  <p align="center">
278
278
  <picture>
279
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/0xgeorgemathew/zcode-agent/main/docs/assets/acp-dark.svg">
280
- <img src="https://raw.githubusercontent.com/0xgeorgemathew/zcode-agent/main/docs/assets/acp-light.svg" width="960" alt="An ACP client such as T3 Code or Zed sends prompts and answers to zcode-agent over stdio. zcode-agent streams text, diffs and the plan back and asks before edits and commands. Mode, model and effort are pickers; the defaults are GLM-5.3, effort high and Ask mode.">
279
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/0xgeorgemathew/zcode-agent/d5db74513374006362d70dd2fd380683c1c7cf2b/docs/assets/acp-dark.svg">
280
+ <img src="https://raw.githubusercontent.com/0xgeorgemathew/zcode-agent/d5db74513374006362d70dd2fd380683c1c7cf2b/docs/assets/acp-light.svg" width="960" alt="An ACP client such as T3 Code or Zed sends prompts and answers to zcode-agent over stdio. zcode-agent streams text, diffs and the plan back and asks before edits and commands. Mode, model and effort are pickers; the defaults are GLM-5.3, effort high and Ask mode.">
281
281
  </picture>
282
282
  </p>
283
283
 
284
- `zcode-agent acp` speaks the [Agent Client Protocol](https://agentclientprotocol.com) (v1) on stdio, so an ACP client drives GLM-5.3 directly: you chat with it, approve its edits and commands, and watch its tool calls, diffs and plan as they happen. `zcode-agent-acp` is the same command for clients that take only an executable. Key, MCP servers and skills work the same way as for `task`.
284
+ `zcode-agent acp` speaks the [Agent Client Protocol](https://agentclientprotocol.com) (v1) on stdio, so an ACP client drives GLM-5.3 directly: you chat with it, approve its edits and commands, and watch its tool calls, diffs and plan as they happen. `zcode-agent-acp` is the same command for clients that take only an executable. Key and skills work the same way as for `task`. MCP servers differ: a session gets your client's servers and Playwright, but not the app's other servers, because every server's tool list is sent with every model request (the app's servers added about 12k input tokens per request in a measured setup). `--mcp-inherit` (or `ZCODE_ACP_INHERIT_MCP=1`) adds them back.
285
285
 
286
286
  **T3 Code** (a build with the ACP Registry provider): install zcode-agent globally, then add a provider in Settings → Providers. Choose **ACP Registry**, set **ACP source** to **Local command** and **Executable override** to `zcode-agent-acp`. To set it in `~/.t3/userdata/settings.json` instead:
287
287
 
@@ -323,7 +323,7 @@ What the client gets:
323
323
  - **Inputs.** Images (saved to the session's tmp dir; GLM-5.3 cannot read them, so the prompt says so and suggests GLM-5.3-Flash), embedded files and file links in prompts. Your client's MCP servers (stdio, HTTP, SSE) are added to the session.
324
324
  - **Cancel.** Stops the running turn and its tools.
325
325
 
326
- The engine starts at the first prompt, not at `session/new`, so client probes cost nothing and leave no session behind. Flags set the defaults for new sessions: `--mode`, `--model`, `--effort`, `--hermetic` (fastest start: none of the app's MCP servers to connect), `--no-browser`, `--mcp`, `--skills`, `--timeout-ms` (per prompt; default none). `ZCODE_ACP_MODE` sets the default mode for clients that take no arguments, and `ZCODE_ACP_LOG=<file>` logs every frame. Questions the model would ask through a form are asked in its reply instead, because ACP v1 has no form UI.
326
+ A new session's engine starts 1.5 s after `session/new`, while you type, so the first prompt reaches the model in well under a second instead of waiting ~3 s for the engine and its MCP servers. The session record is written only at the first prompt: a client that probes with `session/new` and exits right away starts nothing, and a session closed before its first prompt leaves nothing behind. `ZCODE_ACP_PREWARM_MS` sets the delay in milliseconds, or `off` to start the engine at the first prompt. Flags set the defaults for new sessions: `--mode`, `--model`, `--effort`, `--mcp-inherit`, `--hermetic` (also leaves out the app's skills), `--no-browser`, `--mcp`, `--skills`, `--timeout-ms` (per prompt; default none). `ZCODE_ACP_MODE` sets the default mode for clients that take no arguments, and `ZCODE_ACP_LOG=<file>` logs every frame. Questions the model would ask through a form are asked in its reply instead, because ACP v1 has no form UI.
327
327
 
328
328
  &nbsp;
329
329
 
@@ -443,7 +443,7 @@ The brief lists only failing checks (`checksPassed` counts the rest), unmet visu
443
443
 
444
444
  **The API key.** zcode-agent takes the key from `ZAI_API_KEY`, then from `zcode-agent login` (stored in `~/.zcode-agent/credentials.json`, mode 600), then from the ZCode app's own Z.ai API key, read where the app stores it. `ZCODE_NO_DESKTOP_KEY=1` turns the last one off. zcode-agent never reads the app's OAuth tokens, never prints or logs the key, and scrubs it from engine messages and check output. The only file it writes the key to is each session's own provider config, which the engine needs.
445
445
 
446
- **Isolation.** zcode-agent keeps its state in `~/.zcode-agent` and never writes to `~/.zcode`, which belongs to the ZCode app. On first run it moves a pre-1.0 `~/.zcode-cli` there and leaves a symlink. Each session's engine runs with `HOME` set to the session's own directory. On every run zcode-agent rewrites that directory's config: the provider with your key, the app's MCP servers (minus OAuth servers and those in `~/.zcode-agent/mcp-health.json` that failed in the last six hours), and the app's user skills, including symlinked ones. Every session gets zcode-agent's executor instructions as its `AGENTS.md`: headless rules, the session's port and output directories, and when to split work across subagents. The Playwright server runs with a fresh browser profile per engine, so the executor's and the verifier's browsers never share a lock or a cache. zcode-agent never touches the engine's database, so sessions stay resumable.
446
+ **Isolation.** zcode-agent keeps its state in `~/.zcode-agent` and never writes to `~/.zcode`, which belongs to the ZCode app. On first run it moves a pre-1.0 `~/.zcode-cli` there and leaves a symlink. Each session's engine runs with `HOME` set to the session's own directory. On every run zcode-agent rewrites that directory's config: the provider with your key, the app's MCP servers (minus OAuth servers and those in `~/.zcode-agent/mcp-health.json` that failed recently), and the app's user skills, including symlinked ones. The skills are copied once into a shared snapshot under `~/.zcode-agent/shared/skills/` and linked into each session; editing a skill makes a new snapshot, and snapshots unused for two weeks are deleted. The engine starts with Node's compile cache in `~/.zcode-agent/compile-cache` (`ZCODE_NO_COMPILE_CACHE=1` turns it off). Every session gets zcode-agent's executor instructions as its `AGENTS.md`: headless rules, the session's port and output directories, and when to split work across subagents. The Playwright server runs with a fresh browser profile per engine, so the executor's and the verifier's browsers never share a lock or a cache. zcode-agent never touches the engine's database, so sessions stay resumable.
447
447
 
448
448
  **The engine.** `@zcode-agent/engine` is the headless ZCode engine (`zcode.cjs`), built by `npm run build:engine` from the tag in `packages/engine/engine.json`, with the content plugins and bundled skills the app ships and upstream's `LICENSE`, `NOTICE.md` and third-party notices. `ZAI_CODE_ENGINE` points at another `zcode.cjs`. Without the package, zcode-agent uses the ZCode app's engine. `zcode-agent doctor` shows which engine runs and warns when its version differs from the tested one.
449
449
 
@@ -91,6 +91,9 @@ acp (zcode-agent acp):
91
91
  edits and commands) | edit (accept edits) | plan | yolo
92
92
  (full access). default: build; clients switch it per session
93
93
  --timeout-ms <n> per prompt (default: none)
94
+ --mcp-inherit also give sessions the ZCode app's MCP servers (default:
95
+ only the client's servers and Playwright; each server's
96
+ tools are sent with every model request)
94
97
  also: --model, --effort, --mcp, --hermetic, --no-browser,
95
98
  --skills, --no-skills, --inherit-desktop
96
99
 
@@ -207,7 +210,7 @@ function parseArgv(argv) {
207
210
  maxRepairs: undefined,
208
211
  checkTimeoutMs: undefined,
209
212
  mcpSpecs: [],
210
- mcpInherit: false, // accepted for pre-1.0 callers: inheriting is the default now
213
+ mcpInherit: false, // acp: add the desktop's MCP servers; elsewhere accepted for pre-1.0 callers (inheriting is the default there)
211
214
  hermetic: false,
212
215
  noBrowser: false,
213
216
  mcpList: false,
package/lib/acp.js CHANGED
@@ -8,9 +8,14 @@
8
8
  //
9
9
  // Every ACP session is a zcode-agent session (kind "acp") in the store,
10
10
  // with its own engine HOME, port and tmp dir, so `zcode-agent status`,
11
- // `watch` and `cost` see it. The record and the engine are created on the
12
- // first prompt (or session/load), never by session/new: clients probe with
11
+ // `watch` and `cost` see it. The record is created on the first prompt (or
12
+ // exists for session/load), never by session/new: clients probe with
13
13
  // session/new and kill the process, which must leave nothing behind.
14
+ // The engine, though, starts PREWARM_MS after session/new (engine start +
15
+ // MCP connect is ~3 s the first prompt would otherwise wait for) in a
16
+ // reserved session dir with no record; a session closed before its first
17
+ // prompt removes that dir, and a later agent reaps the dirs of agents that
18
+ // were killed. Probes that kill the agent within PREWARM_MS start nothing.
14
19
  //
15
20
  // stdout carries protocol frames only. Diagnostics go to stderr, and every
16
21
  // frame to $ZCODE_ACP_LOG when set.
@@ -43,6 +48,17 @@ const MAX_TIMER_MS = 2147483647;
43
48
  // again; `running` only while a turn runs.
44
49
  const IDLE = { state: 'finished', status: 'completed', phase: 'idle' };
45
50
  const LIST_LIMIT = 256;
51
+ const PREWARM_MS = 1500;
52
+
53
+ // ZCODE_ACP_PREWARM_MS: delay before a new session's engine starts (ms), or
54
+ // "off" to start it at the first prompt. null = off.
55
+ function prewarmDelay(env) {
56
+ const v = env.ZCODE_ACP_PREWARM_MS;
57
+ if (v === undefined || v === '') return PREWARM_MS;
58
+ if (v === 'off') return null;
59
+ const n = Number(v);
60
+ return Number.isFinite(n) && n >= 0 ? n : PREWARM_MS;
61
+ }
46
62
 
47
63
  class AcpError extends Error {
48
64
  constructor(code, message, data) {
@@ -150,7 +166,7 @@ class Peer {
150
166
  // --- the agent ----------------------------------------------------------------------
151
167
 
152
168
  class Agent {
153
- // defaults: {model, effort, mode, mcpSpecs, hermetic, browser, skillsDirs,
169
+ // defaults: {model, effort, mode, mcpSpecs, mcpInherit, hermetic, browser, skillsDirs,
154
170
  // noSkills, inheritDesktop, timeoutMs}
155
171
  constructor({ peer, defaults, env = process.env, version = '0.0.0' }) {
156
172
  this.peer = peer;
@@ -264,7 +280,7 @@ class Agent {
264
280
  const cwd = this.realCwd(params.cwd);
265
281
  this.runtime(); // no key → auth_required now, not at the first prompt
266
282
  let id = store.newId();
267
- while (store.readSession(id, this.env) || this.sessions.has(id)) id = store.newId();
283
+ while (fs.existsSync(store.sessionDir(id, this.env)) || this.sessions.has(id)) id = store.newId();
268
284
  const s = this.makeSession({
269
285
  id,
270
286
  cwd,
@@ -274,9 +290,29 @@ class Agent {
274
290
  mode: this.defaults.mode,
275
291
  persisted: false,
276
292
  });
293
+ this.schedulePrewarm(s);
277
294
  return { sessionId: id, modes: map.modeState(s.mode), configOptions: this.options(s) };
278
295
  }
279
296
 
297
+ schedulePrewarm(s) {
298
+ const delay = prewarmDelay(this.env);
299
+ if (delay === null) return;
300
+ s.prewarm = setTimeout(() => {
301
+ s.prewarm = null;
302
+ if (s.closed || s.busy) return;
303
+ this.ensureEngine(s).catch((err) => {
304
+ // The first prompt starts it again and reports what fails.
305
+ process.stderr.write(`zcode-agent: engine prewarm for ${s.id} failed: ${this.scrub(err && err.message ? err.message : err).slice(0, 300)}\n`);
306
+ });
307
+ }, delay);
308
+ s.prewarm.unref();
309
+ }
310
+
311
+ cancelPrewarm(s) {
312
+ if (s.prewarm) clearTimeout(s.prewarm);
313
+ s.prewarm = null;
314
+ }
315
+
280
316
  makeSession(fields) {
281
317
  const s = {
282
318
  ...fields,
@@ -290,6 +326,9 @@ class Agent {
290
326
  releaseOwner: null,
291
327
  releasePort: null,
292
328
  sessionEnv: null,
329
+ reserved: false, // the session dir is claimed but holds no record yet
330
+ prewarm: null,
331
+ startFacts: {}, // port/out/tmp/engine ids, written with the record
293
332
  contextUsed: null,
294
333
  available: null,
295
334
  images: 0,
@@ -411,38 +450,25 @@ class Agent {
411
450
  return s.starting;
412
451
  }
413
452
 
414
- // Creates the store record on first use, then starts (or restarts) the
415
- // session's engine and opens its engine session (create, or resume the
416
- // persisted one). Retried once on a transient start failure: nothing has
417
- // reached the model yet.
453
+ // Starts (or restarts) the session's engine and opens its engine session
454
+ // (create, or resume the persisted one). A session without a record yet
455
+ // runs in a reserved dir; commit() writes the record at the first prompt.
456
+ // Retried once on a transient start failure: nothing has reached the
457
+ // model yet.
418
458
  async startEngine(s) {
419
459
  this.dropEngine(s); // a dead engine from an earlier turn
420
460
  const runtime = this.runtime();
421
461
  const env = this.env;
422
- if (!s.persisted) {
423
- store.createSession(s.id, {
424
- kind: 'acp',
425
- label: s.title || null,
426
- cwd: s.cwd,
427
- workspaceRoot: workspaceRoot(s.cwd),
428
- owns: [],
429
- ownsRoot: [],
430
- touch: [],
431
- preflight: false,
432
- checks: [],
433
- model: s.model,
434
- effort: s.effort,
435
- engineSessionId: null,
436
- acp: { mode: s.mode },
437
- }, env);
438
- s.persisted = true;
462
+ if (!s.persisted && !s.reserved) {
463
+ store.reserveSessionDir(s.id, env, { mark: true });
464
+ s.reserved = true;
439
465
  }
440
466
  if (!s.releaseOwner) {
441
467
  s.releaseOwner = store.claimSession(s.id, env);
442
468
  if (!s.releaseOwner) throw new AcpError(ERR.internal, `session "${s.id}" is open in another zcode-agent process`);
443
469
  }
444
470
  const dir = store.sessionDir(s.id, env);
445
- const record = store.readSession(s.id, env);
471
+ const record = (s.persisted && store.readSession(s.id, env)) || {};
446
472
  if (!s.sessionEnv) {
447
473
  const reserved = await reservePort({ env, preferred: record.port });
448
474
  if (!reserved) throw new AcpError(ERR.internal, 'no free port for ZCODE_PORT in 41000-48999');
@@ -451,16 +477,23 @@ class Agent {
451
477
  const out = path.join(tmp, 'out');
452
478
  fs.mkdirSync(out, { recursive: true, mode: 0o700 });
453
479
  s.sessionEnv = { ZCODE_SESSION_ID: s.id, ZCODE_PORT: String(reserved.port), ZCODE_OUT: out, ZCODE_TMP: tmp };
454
- store.updateSession(s.id, { port: reserved.port, out, tmp }, env);
480
+ this.recordFacts(s, { port: reserved.port, out, tmp });
455
481
  }
456
482
  const home = path.join(dir, 'home');
483
+ const hermetic = !!this.defaults.hermetic || env.ZCODE_HERMETIC === '1';
457
484
  const built = buildEngineHome({
458
485
  home,
459
486
  root: rootDir(env),
460
487
  key: runtime.key,
461
488
  live: liveDir(env),
462
489
  mcpSpecs: [...(this.defaults.mcpSpecs || []), map.mcpSpec(s.mcpServers)],
463
- hermetic: !!this.defaults.hermetic || env.ZCODE_HERMETIC === '1',
490
+ hermetic,
491
+ // The client passes its own MCP servers, and each desktop server's
492
+ // tool schemas ride along on every model request (measured: the
493
+ // desktop's five cost ~16k input tokens per request). Playwright and
494
+ // the client's servers stay; --mcp-inherit / ZCODE_ACP_INHERIT_MCP=1
495
+ // add the rest back.
496
+ inheritMcp: !hermetic && (!!this.defaults.mcpInherit || env.ZCODE_ACP_INHERIT_MCP === '1'),
464
497
  browser: this.defaults.browser !== false,
465
498
  skillsDirs: this.defaults.skillsDirs || [],
466
499
  noSkills: !!this.defaults.noSkills,
@@ -479,7 +512,7 @@ class Agent {
479
512
  workspacePath: s.cwd,
480
513
  modelId: s.model,
481
514
  effort: s.effort,
482
- resumeSessionId: record.engineSessionId || null,
515
+ resumeSessionId: record.engineSessionId || s.startFacts.engineSessionId || null,
483
516
  requiredMcp: built.mcp.added,
484
517
  mode: s.mode,
485
518
  onMcpStatuses: (statuses) => recordMcpHealth(rootDir(env), statuses, built.mcp.inherited),
@@ -495,14 +528,43 @@ class Agent {
495
528
  if (attempt >= 2 || !transient || s.closed) throw new AcpError(ERR.internal, `engine failed to start: ${runtime.scrub(err.message).slice(0, 600)}`);
496
529
  }
497
530
  }
498
- store.updateSession(s.id, {
531
+ this.recordFacts(s, {
499
532
  engineSessionId: s.engine.sessionId,
500
533
  enginePid: s.client.child.pid,
501
534
  pid: process.pid,
502
535
  ...IDLE,
503
536
  outcome: null,
504
537
  closedReason: null,
505
- }, env);
538
+ });
539
+ }
540
+
541
+ // Facts about the running engine: into the record, or kept for commit().
542
+ recordFacts(s, facts) {
543
+ Object.assign(s.startFacts, facts);
544
+ if (s.persisted) store.updateSession(s.id, facts, this.env);
545
+ }
546
+
547
+ // Writes the record of a session that has none yet (its first prompt).
548
+ commit(s) {
549
+ if (s.persisted) return;
550
+ store.createSession(s.id, {
551
+ kind: 'acp',
552
+ label: s.title || null,
553
+ cwd: s.cwd,
554
+ workspaceRoot: workspaceRoot(s.cwd),
555
+ owns: [],
556
+ ownsRoot: [],
557
+ touch: [],
558
+ preflight: false,
559
+ checks: [],
560
+ model: s.model,
561
+ effort: s.effort,
562
+ engineSessionId: null,
563
+ acp: { mode: s.mode },
564
+ ...s.startFacts,
565
+ }, this.env, { adopt: s.reserved });
566
+ s.persisted = true;
567
+ s.reserved = false;
506
568
  }
507
569
 
508
570
  // The engine's interactive requests, answered by the person in the client.
@@ -560,7 +622,9 @@ class Agent {
560
622
  let phaseAt = 0;
561
623
  const activity = s.activity;
562
624
  try {
625
+ this.cancelPrewarm(s);
563
626
  if (!(await this.untilCancelled(s, this.ensureEngine(s)))) return { stopReason: 'cancelled' };
627
+ this.commit(s);
564
628
  const text = map.promptText(params.prompt, { saveImage: (block, i) => this.saveImage(s, block, i), model: s.model, env });
565
629
  if (!text.trim()) return { stopReason: 'end_turn' };
566
630
  const record = store.readSession(s.id, env) || {};
@@ -712,12 +776,22 @@ class Agent {
712
776
 
713
777
  release(s, reason) {
714
778
  s.closed = true;
779
+ this.cancelPrewarm(s);
715
780
  this.dropEngine(s);
716
781
  if (s.persisted) this.persist(s, { state: 'finished', phase: 'done', status: 'completed', closedReason: reason });
717
782
  if (s.releasePort) s.releasePort();
718
783
  if (s.releaseOwner) s.releaseOwner();
719
784
  s.releasePort = null;
720
785
  s.releaseOwner = null;
786
+ if (s.reserved) {
787
+ // Never prompted: the prewarmed engine's dir goes with it.
788
+ try {
789
+ store.dropReservedDir(s.id, this.env);
790
+ } catch {
791
+ /* reaped by the next agent */
792
+ }
793
+ s.reserved = false;
794
+ }
721
795
  if (this.sessions.get(s.id) === s) this.sessions.delete(s.id);
722
796
  }
723
797
 
@@ -744,6 +818,8 @@ function serve({ defaults, env = process.env, version, input = process.stdin, ou
744
818
  : null;
745
819
  const peer = new Peer({ input, output, log });
746
820
  const agent = new Agent({ peer, defaults, env, version });
821
+ // Dirs of prewarmed sessions whose agent was killed before a prompt.
822
+ setImmediate(() => store.reapReserved(env));
747
823
  let done = false;
748
824
  const stop = (reason, code) => {
749
825
  if (done) return;
package/lib/appserver.js CHANGED
@@ -19,6 +19,9 @@ const { spawn } = require('node:child_process');
19
19
  const readline = require('node:readline');
20
20
  const crypto = require('node:crypto');
21
21
  const fs = require('node:fs');
22
+ const path = require('node:path');
23
+
24
+ const ENGINE_BOOT = path.join(__dirname, 'engine-boot.js');
22
25
 
23
26
  const RUNTIME_PREFERENCES = {
24
27
  nativeSearchEnhancementsEnabled: false,
@@ -56,7 +59,10 @@ class AppServerClient {
56
59
  // Own process group, so kill() takes the engine's tool subprocesses and
57
60
  // stdio MCP servers with it (a runaway shell command must not keep
58
61
  // writing to the workspace after cancel/timeout).
59
- this.child = spawn(this.nodeBin, [this.enginePath, 'app-server', '--stdio'], {
62
+ // With ZCODE_COMPILE_CACHE set (engineEnv), lib/engine-boot.js starts
63
+ // the engine with V8's compile cache on.
64
+ const boot = this.env && this.env.ZCODE_COMPILE_CACHE ? [ENGINE_BOOT] : [];
65
+ this.child = spawn(this.nodeBin, [...boot, this.enginePath, 'app-server', '--stdio'], {
60
66
  env: this.env,
61
67
  cwd: this.cwd,
62
68
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -24,6 +24,7 @@ module.exports = function acpCommand(parsed) {
24
24
  effort: flags.effort,
25
25
  mode,
26
26
  mcpSpecs: flags.mcpSpecs,
27
+ mcpInherit: flags.mcpInherit,
27
28
  hermetic: flags.hermetic,
28
29
  browser: !flags.noBrowser,
29
30
  skillsDirs: flags.skillsDirs.map((d) => require('node:path').resolve(d)),
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+ // Engine launcher: `node engine-boot.js <zcode.cjs> app-server --stdio`.
3
+ // Turns on V8's on-disk compile cache for the 15 MB engine bundle, then runs
4
+ // the bundle exactly as if node had started it (argv[1] is the engine).
5
+ // Measured on 0.16.9: an engine start to session/create drops from
6
+ // ~750-900 ms to ~600 ms once the cache is warm.
7
+ //
8
+ // The cache dir arrives in ZCODE_COMPILE_CACHE and is removed from the env
9
+ // before the engine runs, so the commands the engine's tools spawn (the
10
+ // user's own node programs) never inherit it. NODE_COMPILE_CACHE would.
11
+ const mod = require('node:module');
12
+ const path = require('node:path');
13
+
14
+ const cacheDir = process.env.ZCODE_COMPILE_CACHE;
15
+ delete process.env.ZCODE_COMPILE_CACHE;
16
+ const engine = path.resolve(process.argv[2]);
17
+ process.argv.splice(1, 2, engine);
18
+
19
+ let caching = false;
20
+ if (cacheDir && typeof mod.enableCompileCache === 'function') {
21
+ try {
22
+ const res = mod.enableCompileCache(cacheDir);
23
+ caching = !res || res.status !== mod.constants?.compileCacheStatus?.FAILED;
24
+ } catch {
25
+ /* no cache: the engine just compiles from scratch */
26
+ }
27
+ }
28
+
29
+ require(engine);
30
+
31
+ // The engine never exits on its own: zcode-agent SIGKILLs its process group,
32
+ // and a killed process never writes its cache. Flush once startup compiled.
33
+ if (caching && typeof mod.flushCompileCache === 'function') {
34
+ setTimeout(() => {
35
+ try {
36
+ mod.flushCompileCache();
37
+ } catch {
38
+ /* best-effort */
39
+ }
40
+ }, 1000).unref();
41
+ }
package/lib/executor.js CHANGED
@@ -425,6 +425,13 @@ async function execute(inv, opts = {}) {
425
425
  let verifierModel = null;
426
426
  let verifyRounds = 0;
427
427
  let visualEntries = null; // the verifier's verdicts: authoritative `visual`
428
+ // A verifier engine started while the acceptance checks run (engine start
429
+ // + MCP connect took ~2.5 s per verifier round); killed if unused.
430
+ let spareVerifier = null;
431
+ const dropSpareVerifier = () => {
432
+ if (spareVerifier) spareVerifier.client.kill();
433
+ spareVerifier = null;
434
+ };
428
435
  const invocationStart = new Date(started).toISOString();
429
436
 
430
437
  try {
@@ -531,9 +538,29 @@ async function execute(inv, opts = {}) {
531
538
  prompt = inv.resume ? buildResumePrompt(inv.resume.message, { kind: 'run' }) : inv.prompt;
532
539
  }
533
540
 
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.
541
+ // The verifier's engine: a NEW engine session (own client: fresh context
542
+ // and its own browser, separate from the implementer's) on the first
543
+ // image-capable model. Resolves {client, session}; kills it on failure.
544
+ const openVerifier = (model, onEvent) => {
545
+ const vclient = makeClient(runtime, { home, cwd: record.cwd, sessionEnv });
546
+ vclient.start();
547
+ const opening = openSession(vclient, {
548
+ workspacePath: record.cwd,
549
+ modelId: model,
550
+ effort: 'high',
551
+ requiredMcp: built.mcp.added,
552
+ onEvent,
553
+ onMcpStatuses: rememberMcp,
554
+ }).then((vsession) => ({ client: vclient, session: vsession }), (err) => {
555
+ vclient.kill();
556
+ throw err;
557
+ });
558
+ opening.client = vclient;
559
+ opening.catch(() => {});
560
+ return opening;
561
+ };
562
+ // One verifier round. Returns an entry per criterion; failures become
563
+ // met:null, never false.
537
564
  const verifyVisual = async (round) => {
538
565
  verifierModel = visionModel({ env, builtinConfig: runtime.builtinConfig });
539
566
  verifyRounds = round;
@@ -563,16 +590,21 @@ async function execute(inv, opts = {}) {
563
590
  }
564
591
  };
565
592
  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
- });
593
+ const spare = attempt === 1 ? spareVerifier : null;
594
+ spareVerifier = null;
595
+ let opening = spare;
596
+ if (!opening) opening = openVerifier(verifierModel, vrelay);
597
+ vclient = opening.client;
598
+ let vsession;
599
+ try {
600
+ ({ session: vsession } = await opening);
601
+ } catch (err) {
602
+ if (!spare) throw err;
603
+ // The early start failed; one fresh start before giving up.
604
+ opening = openVerifier(verifierModel, vrelay);
605
+ vclient = opening.client;
606
+ ({ session: vsession } = await opening);
607
+ }
576
608
  const vturn = await runTurn(vclient, vsession, {
577
609
  modelId: verifierModel,
578
610
  effort: 'high',
@@ -640,6 +672,9 @@ async function execute(inv, opts = {}) {
640
672
  if (parsed.handback && parsed.handback.status === 'blocked') break;
641
673
  if (!inv.checks.length && !visualDeclared.length) break;
642
674
 
675
+ if (visualDeclared.length && parsed.handback && inv.checks.length && !spareVerifier) {
676
+ spareVerifier = openVerifier(visionModel({ env, builtinConfig: runtime.builtinConfig }), relay);
677
+ }
643
678
  if (inv.checks.length) {
644
679
  setPhase('checking', { count: inv.checks.length });
645
680
  const preChecks = before ? snapshot(root) : null;
@@ -667,6 +702,7 @@ async function execute(inv, opts = {}) {
667
702
  visualEntries = await verifyVisual(verifyRounds + 1);
668
703
  visualUnmet = visualEntries.filter((v) => v.met === false);
669
704
  }
705
+ dropSpareVerifier(); // checks failed: no verifier this round
670
706
  if ((!failures.length && !visualUnmet.length) || repairs >= inv.maxRepairs) break;
671
707
  if ((signal && signal.aborted) || Date.now() >= deadline) break;
672
708
  repairs++;
@@ -688,6 +724,7 @@ async function execute(inv, opts = {}) {
688
724
  error = err;
689
725
  if (err && err.turn) failedTurns.push(err.turn);
690
726
  } finally {
727
+ dropSpareVerifier();
691
728
  if (client) client.kill();
692
729
  if (releasePort) releasePort();
693
730
  lease.release();
package/lib/help.js CHANGED
@@ -130,8 +130,12 @@ client run GLM-5.3 through it. Each ACP session is a zcode-agent session
130
130
  --effort <lvl> low | high | max (default high)
131
131
  --timeout-ms <n> per prompt (default: none)
132
132
  --mcp <json|@f> add MCP servers (repeatable) --hermetic --no-browser
133
+ --mcp-inherit also the desktop's MCP servers (default: the client's
134
+ servers and Playwright only; or $ZCODE_ACP_INHERIT_MCP=1)
133
135
  --skills <dir> add skills (repeatable) --no-skills
134
136
  --inherit-desktop also the desktop's AGENTS.md, plugins and agent profiles
137
+ A new session's engine starts 1.5 s after session/new, so the first prompt
138
+ does not wait for it ($ZCODE_ACP_PREWARM_MS: delay in ms, or "off").
135
139
  T3 Code: an ACP Registry provider, source "Local command", executable
136
140
  zcode-agent-acp (see the README). $ZCODE_ACP_LOG=<file> logs every frame.`,
137
141
  };
package/lib/isolation.js CHANGED
@@ -223,7 +223,16 @@ function inheritableMcpServers(live = LIVE_ZCODE) {
223
223
  // (<root>/mcp-health.json), so one dead server costs one session its
224
224
  // connect timeout, not every session. Keyed by name + a hash of the
225
225
  // server's definition: editing the server in the app retries it at once.
226
+ // Each consecutive failure doubles the wait (6 h, 12 h, 1 d, 2 d, then 4 d):
227
+ // a server that never connects costs a 30 s connect every few days, not
228
+ // four times a day.
226
229
  const MCP_RETRY_AFTER_MS = 6 * 60 * 60 * 1000;
230
+ const MCP_RETRY_MAX_DOUBLINGS = 4;
231
+
232
+ function mcpRetryAfter(failures) {
233
+ const n = Math.min(Math.max(1, Number(failures) || 1), MCP_RETRY_MAX_DOUBLINGS + 1);
234
+ return MCP_RETRY_AFTER_MS * 2 ** (n - 1);
235
+ }
227
236
 
228
237
  function mcpSignature(def) {
229
238
  return crypto.createHash('sha256').update(JSON.stringify(def)).digest('hex').slice(0, 16);
@@ -242,7 +251,7 @@ function readMcpHealth(root) {
242
251
  function unhealthyMcp(servers, health, now = Date.now()) {
243
252
  return Object.keys(servers).filter((name) => {
244
253
  const h = health[name];
245
- return h && h.sig === mcpSignature(servers[name]) && now - h.failedAt < MCP_RETRY_AFTER_MS;
254
+ return h && h.sig === mcpSignature(servers[name]) && now - h.failedAt < mcpRetryAfter(h.failures);
246
255
  });
247
256
  }
248
257
 
@@ -258,9 +267,12 @@ function recordMcpHealth(root, statuses, inherited, now = Date.now()) {
258
267
  const state = statuses[name] && statuses[name].status;
259
268
  if (state === 'failed') {
260
269
  const error = statuses[name].error;
270
+ const sig = mcpSignature(def);
271
+ const prev = health[name] && health[name].sig === sig ? health[name] : null;
261
272
  health[name] = {
262
- sig: mcpSignature(def),
273
+ sig,
263
274
  failedAt: now,
275
+ failures: ((prev && prev.failures) || (prev ? 1 : 0)) + 1,
264
276
  error: error ? String(typeof error === 'string' ? error : JSON.stringify(error)).slice(0, 200) : null,
265
277
  };
266
278
  changed = true;
@@ -361,6 +373,98 @@ const EXECUTOR_AGENTS_MD = path.join(__dirname, '..', 'assets', 'executor-agents
361
373
  // `zcode-agent acp`: a person watches and approves in the client.
362
374
  const ACP_AGENTS_MD = path.join(__dirname, '..', 'assets', 'acp-agents.md');
363
375
 
376
+ // The desktop's user skills a session inherits: [{name, from}].
377
+ function desktopSkills(live) {
378
+ const liveSkills = path.join(live, 'skills');
379
+ return listDir(liveSkills)
380
+ .filter((e) => !HOST_ONLY_SKILLS.has(e.name) && fs.existsSync(path.join(liveSkills, e.name, 'SKILL.md')))
381
+ .map((e) => ({ name: e.name, from: path.join(liveSkills, e.name) }))
382
+ .sort((a, b) => a.name.localeCompare(b.name));
383
+ }
384
+
385
+ // Most desktop skills are symlinks into ~/.claude/skills or ~/.agents; the
386
+ // snapshot follows them and copies the targets (a session HOME must not
387
+ // point back into live directories, only into our own root). Keyed by every
388
+ // file's path, size and mtime (~20 ms for ~1,400 files), so editing a skill
389
+ // in place yields a new snapshot.
390
+ const SNAPSHOT_KEEP_MS = 14 * 24 * 60 * 60 * 1000;
391
+ const SKILL_WALK_DEPTH = 16;
392
+
393
+ function skillsSignature(entries) {
394
+ const hash = crypto.createHash('sha256');
395
+ const walk = (dir, rel, depth) => {
396
+ if (depth > SKILL_WALK_DEPTH) return;
397
+ for (const name of listDir(dir).map((e) => e.name).sort()) {
398
+ let st;
399
+ try {
400
+ st = fs.statSync(path.join(dir, name));
401
+ } catch {
402
+ continue; // dangling link
403
+ }
404
+ if (st.isDirectory()) walk(path.join(dir, name), `${rel}/${name}`, depth + 1);
405
+ else hash.update(`${rel}/${name}\0${st.size}\0${st.mtimeMs}\n`);
406
+ }
407
+ };
408
+ for (const { name, from } of entries) {
409
+ let real = from;
410
+ try {
411
+ real = fs.realpathSync(from);
412
+ } catch {
413
+ /* hashed by name */
414
+ }
415
+ hash.update(`skill\0${name}\0${real}\n`);
416
+ walk(from, name, 0);
417
+ }
418
+ return hash.digest('hex').slice(0, 16);
419
+ }
420
+
421
+ // <root>/shared/skills/<signature>, built once (into a temp dir, then
422
+ // renamed, so a concurrent builder never sees a half copy). Snapshots
423
+ // unused for two weeks are removed. Returns the dir, or null on failure.
424
+ function skillsSnapshot(entries, root) {
425
+ try {
426
+ const base = path.join(root, 'shared', 'skills');
427
+ const dir = path.join(base, skillsSignature(entries));
428
+ if (!fs.existsSync(dir)) {
429
+ fs.mkdirSync(base, { recursive: true, mode: 0o700 });
430
+ const tmp = path.join(base, `.tmp-${process.pid}-${crypto.randomBytes(3).toString('hex')}`);
431
+ try {
432
+ for (const { name, from } of entries) {
433
+ fs.cpSync(from, path.join(tmp, name), { recursive: true, dereference: true });
434
+ }
435
+ fs.mkdirSync(tmp, { recursive: true });
436
+ fs.renameSync(tmp, dir);
437
+ } catch (err) {
438
+ fs.rmSync(tmp, { recursive: true, force: true });
439
+ if (!fs.existsSync(dir)) throw err; // else a concurrent builder won
440
+ }
441
+ }
442
+ const now = new Date();
443
+ fs.utimesSync(dir, now, now);
444
+ for (const e of listDir(base)) {
445
+ const other = path.join(base, e.name);
446
+ if (other === dir) continue;
447
+ try {
448
+ if (now - fs.statSync(other).mtimeMs > SNAPSHOT_KEEP_MS) fs.rmSync(other, { recursive: true, force: true });
449
+ } catch {
450
+ /* pruning is housekeeping */
451
+ }
452
+ }
453
+ return dir;
454
+ } catch {
455
+ return null;
456
+ }
457
+ }
458
+
459
+ function linkDir(target, link) {
460
+ try {
461
+ fs.symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir');
462
+ return true;
463
+ } catch {
464
+ return false;
465
+ }
466
+ }
467
+
364
468
  // Rewrites the frontmatter `model:` of an agent profile when it names
365
469
  // GLM-5.3 / GLM-5.3-Flash (any prefix: "account:x/GLM-5.3",
366
470
  // "custom:account%3Ax:GLM-5.3") so its model part is `model`.
@@ -381,6 +485,9 @@ function buildEngineHome({
381
485
  live = LIVE_ZCODE,
382
486
  mcpSpecs = [],
383
487
  hermetic = false,
488
+ // The desktop's MCP servers; default: unless hermetic. `zcode-agent acp`
489
+ // passes false (the client brings its own servers), keeping skills.
490
+ inheritMcp = !hermetic,
384
491
  browser = true,
385
492
  skillsDirs = [],
386
493
  noSkills = false,
@@ -417,13 +524,13 @@ function buildEngineHome({
417
524
  zai.options.apiKey = key;
418
525
  }
419
526
  const health = readMcpHealth(root);
420
- const servers = effectiveMcpServers({ inherit: !hermetic, browser, mcpSpecs, live, health });
527
+ const servers = effectiveMcpServers({ inherit: inheritMcp, browser, mcpSpecs, live, health });
421
528
  const added = mcpSpecs.flatMap((spec) => Object.keys(spec));
422
- const inheritedNames = hermetic ? [] : Object.keys(inheritableMcpServers(live));
529
+ const inheritedNames = inheritMcp ? Object.keys(inheritableMcpServers(live)) : [];
423
530
  const inherited = Object.fromEntries(
424
531
  Object.entries(servers).filter(([name]) => inheritedNames.includes(name) && !added.includes(name))
425
532
  );
426
- const skippedUnhealthy = hermetic ? [] : unhealthyMcp(inheritableMcpServers(live), health).filter((n) => !servers[n]);
533
+ const skippedUnhealthy = !inheritMcp ? [] : unhealthyMcp(inheritableMcpServers(live), health).filter((n) => !servers[n]);
427
534
  cfg.mcp = { ...(cfg.mcp || {}), servers };
428
535
  // The desktop's plugins (browser-use, computer-use, …) inject skills and
429
536
  // tools meant for the app's own UI; the executor gets none unless
@@ -467,15 +574,15 @@ function buildEngineHome({
467
574
  fs.mkdirSync(skillsDir, { recursive: true });
468
575
  let skillsCopied = 0;
469
576
  if (!noSkills && !hermetic) {
470
- // Most desktop skills are symlinks into ~/.claude/skills or ~/.agents:
471
- // follow them, and copy the target (the session HOME must not point
472
- // back into live directories).
473
- const liveSkills = path.join(live, 'skills');
474
- for (const entry of listDir(liveSkills)) {
475
- if (HOST_ONLY_SKILLS.has(entry.name)) continue;
476
- const from = path.join(liveSkills, entry.name);
477
- if (!fs.existsSync(path.join(from, 'SKILL.md'))) continue;
478
- fs.cpSync(from, path.join(skillsDir, entry.name), { recursive: true, dereference: true });
577
+ const entries = desktopSkills(live);
578
+ // One shared snapshot per distinct desktop skill set, linked into each
579
+ // HOME: copying ~100 skills per invocation cost 200-400 ms and ~14 MB
580
+ // per session. Without a root (or links), copy as before.
581
+ const snapshot = root ? skillsSnapshot(entries, root) : null;
582
+ for (const { name, from } of entries) {
583
+ if (!snapshot || !linkDir(path.join(snapshot, name), path.join(skillsDir, name))) {
584
+ fs.cpSync(from, path.join(skillsDir, name), { recursive: true, dereference: true });
585
+ }
479
586
  skillsCopied++;
480
587
  }
481
588
  }
@@ -587,6 +694,11 @@ function engineEnv({ home, builtinProviderConfig, parentEnv = process.env, sessi
587
694
  }
588
695
  childEnv.HOME = home;
589
696
  childEnv.ZCODE_BUILTIN_PROVIDER_CONFIG_FILE = builtinProviderConfig;
697
+ // V8 compile cache for the engine bundle, shared by every session
698
+ // (lib/engine-boot.js consumes and removes it). ZCODE_NO_COMPILE_CACHE=1
699
+ // starts the engine directly.
700
+ if (parentEnv.ZCODE_NO_COMPILE_CACHE === '1') delete childEnv.ZCODE_COMPILE_CACHE;
701
+ else childEnv.ZCODE_COMPILE_CACHE = path.join(rootDir(parentEnv), 'compile-cache');
590
702
  for (const name of [
591
703
  'ZCODE_STORAGE_DIR',
592
704
  'ZCODE_DATA_BASE_DIR',
@@ -618,7 +730,9 @@ module.exports = {
618
730
  readMcpHealth,
619
731
  recordMcpHealth,
620
732
  unhealthyMcp,
733
+ mcpRetryAfter,
621
734
  mcpSignature,
735
+ skillsSnapshot,
622
736
  discoverSkillDirs,
623
737
  LIVE_ZCODE,
624
738
  LIVE_V2,
package/lib/store.js CHANGED
@@ -65,15 +65,15 @@ function readJson(file) {
65
65
 
66
66
  // Claims the id atomically (mkdir fails if it exists) and writes the first
67
67
  // record. Throws SessionExistsError on collision — an orchestrator retrying
68
- // a start with the same --id never runs the work twice.
69
- function createSession(id, fields, env = process.env) {
70
- fs.mkdirSync(sessionsDir(env), { recursive: true, mode: 0o700 });
71
- const dir = sessionDir(id, env);
72
- try {
73
- fs.mkdirSync(dir, { mode: 0o700 });
74
- } catch (err) {
75
- if (err.code === 'EEXIST') throw new SessionExistsError(id);
76
- throw err;
68
+ // a start with the same --id never runs the work twice. `adopt`: the dir was
69
+ // claimed earlier by reserveSessionDir (an ACP engine started ahead of the
70
+ // first prompt); it is taken over when it holds no record yet.
71
+ function createSession(id, fields, env = process.env, { adopt = false } = {}) {
72
+ const dir = adopt ? sessionDir(id, env) : reserveSessionDir(id, env);
73
+ if (adopt) {
74
+ if (fs.existsSync(path.join(dir, 'session.json'))) throw new SessionExistsError(id);
75
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
76
+ fs.rmSync(path.join(dir, RESERVED_MARK), { force: true });
77
77
  }
78
78
  const now = new Date().toISOString();
79
79
  const record = {
@@ -93,6 +93,50 @@ function createSession(id, fields, env = process.env) {
93
93
  return record;
94
94
  }
95
95
 
96
+ // A session dir without a record: invisible to status/list until
97
+ // createSession(…, {adopt: true}). RESERVED_MARK holds the reserving pid,
98
+ // so reapReserved can remove the dirs of processes that died before their
99
+ // first prompt (an ACP client SIGKILLing the agent).
100
+ const RESERVED_MARK = 'reserved.pid';
101
+
102
+ function reserveSessionDir(id, env = process.env, { mark = false } = {}) {
103
+ fs.mkdirSync(sessionsDir(env), { recursive: true, mode: 0o700 });
104
+ const dir = sessionDir(id, env);
105
+ try {
106
+ fs.mkdirSync(dir, { mode: 0o700 });
107
+ } catch (err) {
108
+ if (err.code === 'EEXIST') throw new SessionExistsError(id);
109
+ throw err;
110
+ }
111
+ if (mark) fs.writeFileSync(path.join(dir, RESERVED_MARK), String(process.pid), { mode: 0o600 });
112
+ return dir;
113
+ }
114
+
115
+ // Removes a reserved dir that never got a record (a no-op once adopted).
116
+ function dropReservedDir(id, env = process.env) {
117
+ const dir = sessionDir(id, env);
118
+ if (!validId(id) || !fs.existsSync(path.join(dir, RESERVED_MARK)) || fs.existsSync(path.join(dir, 'session.json'))) return;
119
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
120
+ }
121
+
122
+ // Reserved dirs whose process is gone. Never throws.
123
+ function reapReserved(env = process.env) {
124
+ let names = [];
125
+ try {
126
+ names = fs.readdirSync(sessionsDir(env));
127
+ } catch {
128
+ return;
129
+ }
130
+ for (const name of names) {
131
+ try {
132
+ const pid = Number(fs.readFileSync(path.join(sessionDir(name, env), RESERVED_MARK), 'utf8'));
133
+ if (!pidAlive(pid)) dropReservedDir(name, env);
134
+ } catch {
135
+ /* not reserved, or already gone */
136
+ }
137
+ }
138
+ }
139
+
96
140
  function readSession(id, env = process.env) {
97
141
  if (!validId(id)) return null;
98
142
  return readJson(path.join(sessionDir(id, env), 'session.json'));
@@ -315,6 +359,9 @@ module.exports = {
315
359
  validId,
316
360
  newId,
317
361
  createSession,
362
+ reserveSessionDir,
363
+ dropReservedDir,
364
+ reapReserved,
318
365
  readSession,
319
366
  updateSession,
320
367
  deleteSession,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zcode-agent",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Cheap, verified execution for Claude Code and Codex: your orchestrator decides, GLM-5.3 builds and tests, and a GLM-5.3-Flash verifier checks the screenshots in headless ZCode sessions (parallel sessions, subagents, dependency plans) and hands back a compact result. Also an ACP agent for T3 Code, Zed and any Agent Client Protocol client. Uses your ZCode app's key, MCP servers and skills, or runs standalone.",
5
5
  "license": "MIT",
6
6
  "bin": {