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.
@@ -23,7 +23,8 @@ const USAGE = `usage:
23
23
  zcode-agent plan wait|status <name> [--timeout-ms n] [--json]
24
24
  one summary line: {type:"plan",name,status,sessions,briefs}
25
25
  zcode-agent plan resume <name> [message…] [--session <id>]
26
- resume failed/partial/blocked sessions, restart supervision
26
+ resume every session that ended without completing,
27
+ restart supervision
27
28
  zcode-agent login store a Z.ai API key piped on stdin (optional
28
29
  with ZAI_API_KEY or the ZCode app's key)
29
30
  zcode-agent doctor [--json] [--install-browser]
@@ -64,8 +65,8 @@ task contract (task only):
64
65
  zcode-agent resume <id> "<answers>" executes the task
65
66
  --unit "n: goal [owns a,b]" repeatable: one subagent per unit inside this
66
67
  session; owns must lie within --owns and be disjoint
67
- --visual <criterion> repeatable: after the work an independent image-capable
68
- verifier (GLM-5.3-Flash, fresh session) serves the app on
68
+ --visual <criterion> repeatable: after the work an independent verifier
69
+ (GLM-5.3-Flash, fresh session) serves the app on
69
70
  $ZCODE_PORT, screenshots it and judges each criterion
70
71
  --viewport <WxH> repeatable viewport for --visual (default 390x844, 1440x900)
71
72
  --serve <cmd> command that serves the app for --visual (honours $ZCODE_PORT)
@@ -83,6 +84,7 @@ plan (zcode-agent plan run <plan.json>):
83
84
  --preflight plan run: read-only preflight of every session ("<id>.pre"),
84
85
  prints the questions as one brief per session (exit 10 if any)
85
86
  --detach plan run/resume: supervise in a background process
87
+ --cwd <dir> plan check/run: workspace, when the plan file sets no cwd
86
88
  --id <name> plan name (default: the file's basename)
87
89
  --session <id> plan resume: only this session
88
90
 
@@ -98,8 +100,9 @@ acp (zcode-agent acp):
98
100
  --skills, --no-skills, --inherit-desktop
99
101
 
100
102
  execution:
101
- --model <id> glm-5.3 | glm-5.3-flash (+aliases). default: glm-5.3
102
- --effort <level> low | high | max for both models (zcode-agent doctor lists the
103
+ --model <id> glm-5.4 | glm-5.3 | glm-5.3-flash (+aliases: 5.4, 5.3, flash).
104
+ default: glm-5.4 (sees images; GLM-5.3 does not)
105
+ --effort <level> low | high | max for every model (zcode-agent doctor lists the
103
106
  engine's levels per model); an unsupported level exits 2
104
107
  before any spawn. default: high
105
108
  --timeout-ms <n> whole invocation incl. checks/repairs (default 600000;
@@ -107,8 +110,10 @@ execution:
107
110
  --profile <name> subagent profile (agent command; default general-purpose)
108
111
  --mcp <json|@f> add MCP servers (repeatable), on top of the desktop's
109
112
  --hermetic don't inherit the ZCode app's MCP servers and skills
110
- (inherited by default; OAuth-only remote servers never are)
111
- --no-browser drop the desktop's playwright MCP server (on by default)
113
+ (inherited by default; OAuth-only remote servers never are).
114
+ The Playwright browser server stays: see --no-browser
115
+ --no-browser drop the playwright MCP server (on by default, also with
116
+ --hermetic)
112
117
  --mcp-list print the effective MCP server set as JSON and exit
113
118
  --skills <dir> add skills (repeatable): one skill dir or a root of them
114
119
  --no-skills empty skill set
@@ -129,7 +134,7 @@ output:
129
134
  -p, --prompt <t> prompt text (alias for positional prompt)
130
135
  --session <id> run: continue a session (zcode-agent id or engine sess_ id)
131
136
  --install-browser doctor: install the default Playwright server's Chromium
132
- --version, --help
137
+ --version, -v --help, -h
133
138
 
134
139
  exit codes: 0 completed · 2 usage · 3 no key · 4 no engine · 5 failed ·
135
140
  6 agent: no subagent · 7 workspace conflict / session busy · 8 partial or
@@ -185,7 +190,7 @@ function parseArgv(argv) {
185
190
  effort: DEFAULT_EFFORT,
186
191
  cwd: process.cwd(),
187
192
  json: false,
188
- fresh: false,
193
+ fresh: false, // accepted and ignored: pre-0.4 callers pass it (every session has had its own HOME since)
189
194
  timeoutMs: undefined,
190
195
  profile: 'general-purpose',
191
196
  prompt: undefined,
@@ -252,9 +257,11 @@ function parseArgv(argv) {
252
257
  ['--thinking', ['thinking', true]], ['--no-thinking', ['thinking', false]], ['--stream', ['stream', true]],
253
258
  ['--full', ['full', true]], ['--any', ['any', true]], ['--all', ['all', true]], ['--app', ['app', true]], ['--install-browser', ['installBrowser', true]], ['--preflight', ['preflight', true]],
254
259
  ]);
255
- const numeric = (flag, value, { min = 1 } = {}) => {
260
+ const numeric = (flag, value, { min = 1, integer = false } = {}) => {
256
261
  const n = Number(value);
257
- if (!Number.isFinite(n) || n < min) fail(2, `${flag} must be a number >= ${min}, got "${value}".`);
262
+ if (!Number.isFinite(n) || n < min || (integer && !Number.isInteger(n))) {
263
+ fail(2, `${flag} must be ${integer ? 'an integer' : 'a number'} >= ${min}, got "${value}".`);
264
+ }
258
265
  return n;
259
266
  };
260
267
 
@@ -267,7 +274,7 @@ function parseArgv(argv) {
267
274
  out.given.add(key);
268
275
  if (key === 'timeoutMs' || key === 'checkTimeoutMs') out.flags[key] = numeric(arg, value);
269
276
  else if (key === 'stallMin') out.flags[key] = numeric(arg, value, { min: 0 });
270
- else if (key === 'maxRepairs') out.flags[key] = numeric(arg, value, { min: 0 });
277
+ else if (key === 'maxRepairs') out.flags[key] = numeric(arg, value, { min: 0, integer: true });
271
278
  else if (key === 'mcpSpecs') out.flags.mcpSpecs.push(parseMcpSpec(value));
272
279
  else if (key === 'skillsDirs') {
273
280
  if (!isDirectory(value)) fail(2, `--skills requires an existing directory, got "${value}".`);
@@ -291,7 +298,7 @@ function parseArgv(argv) {
291
298
  process.stdout.write((text || USAGE) + '\n');
292
299
  process.exit(0);
293
300
  }
294
- if (arg === '--version') {
301
+ if (arg === '--version' || arg === '-v' || arg === '-V') {
295
302
  process.stdout.write(require('../package.json').version + '\n');
296
303
  process.exit(0);
297
304
  }
@@ -303,6 +310,11 @@ function parseArgv(argv) {
303
310
  const hint = suggestFlag(arg, [...valueFlags.keys(), ...listFlags.keys(), ...boolFlags.keys()]);
304
311
  fail(2, `unknown flag ${arg} (${hint ? `did you mean ${hint}?` : 'see zcode-agent --help'})`);
305
312
  }
313
+ // A short flag we do not have (-x, -version) must not become a prompt
314
+ // and a paid turn. Prompt text that starts with a dash goes after `--`.
315
+ if (/^-[A-Za-z][\w-]*$/.test(arg)) {
316
+ fail(2, `unknown flag ${arg} (see zcode-agent --help; put prompt text that starts with "-" after --)`);
317
+ }
306
318
  if (out.prompts.length === 0 && out.command === 'run' && !out.commandSet && COMMANDS.has(arg)) {
307
319
  out.command = arg === 'list' ? 'status' : arg;
308
320
  out.commandSet = true;
@@ -312,7 +324,24 @@ function parseArgv(argv) {
312
324
  }
313
325
 
314
326
  const cmd = out.command;
315
- if (out.flags.prompt !== undefined) out.prompts.unshift(out.flags.prompt);
327
+ // A mistyped command must not become a prompt and a paid turn: one bare
328
+ // word next to a command name is refused. Distance 2 only from five
329
+ // letters, so the one-word prompt "test" (2 from "task") still runs.
330
+ if (!out.commandSet && out.prompts.length === 1 && out.flags.prompt === undefined && !/\s/.test(out.prompts[0])) {
331
+ const word = out.prompts[0];
332
+ const near = [...COMMANDS].filter((c) => !c.startsWith('__'))
333
+ .map((c) => [c, editDistance(word.toLowerCase(), c)])
334
+ .sort((a, b) => a[1] - b[1])[0];
335
+ if (near && near[1] <= (word.length >= 5 ? 2 : 1)) {
336
+ fail(2, `unknown command "${word}" (did you mean "${near[0]}"?). To send it as a prompt: zcode-agent run ${word}`);
337
+ }
338
+ }
339
+ // -p is the prompt of run/task/agent; elsewhere (resume <id> -p "…") it is
340
+ // the message and must not displace the id or the subcommand.
341
+ if (out.flags.prompt !== undefined) {
342
+ if (cmd === 'run' || cmd === 'task' || cmd === 'agent') out.prompts.unshift(out.flags.prompt);
343
+ else out.prompts.push(out.flags.prompt);
344
+ }
316
345
  if (cmd !== 'task') {
317
346
  for (const key of TASK_ONLY) {
318
347
  if (cmd === 'plan' && key === 'preflight') continue;
@@ -325,6 +354,10 @@ function parseArgv(argv) {
325
354
  for (const key of ['label', 'owns', 'touch', 'allowOverlap', 'model', 'effort', 'profile']) {
326
355
  if (out.given.has(key)) fail(2, `--${flagName(key)} is not valid with "zcode-agent plan"; set it in the plan file.`);
327
356
  }
357
+ // Plan sessions are started without these: refused rather than dropped.
358
+ for (const key of ['mcpSpecs', 'mcpInherit', 'hermetic', 'noBrowser', 'skillsDirs', 'noSkills', 'inheritDesktop', 'includeReasoning', 'stream']) {
359
+ if (out.given.has(key)) fail(2, `--${flagName(key)} is not valid with "zcode-agent plan" (plan sessions run with the default setup; ZCODE_HERMETIC=1 and ZCODE_INHERIT_DESKTOP=1 apply to them).`);
360
+ }
328
361
  }
329
362
  if (cmd === 'resume' || cmd === '__exec') {
330
363
  for (const key of START_ONLY) {
@@ -361,26 +394,27 @@ function parseArgv(argv) {
361
394
  return out;
362
395
  }
363
396
 
397
+ function editDistance(a, b) {
398
+ const row = Array.from({ length: b.length + 1 }, (_, j) => j);
399
+ for (let i = 1; i <= a.length; i++) {
400
+ let prev = row[0];
401
+ row[0] = i;
402
+ for (let j = 1; j <= b.length; j++) {
403
+ const tmp = row[j];
404
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
405
+ prev = tmp;
406
+ }
407
+ }
408
+ return row[b.length];
409
+ }
410
+
364
411
  // Closest known flag by edit distance (<= 2), or null.
365
412
  function suggestFlag(arg, known) {
366
- const dist = (a, b) => {
367
- const row = Array.from({ length: b.length + 1 }, (_, j) => j);
368
- for (let i = 1; i <= a.length; i++) {
369
- let prev = row[0];
370
- row[0] = i;
371
- for (let j = 1; j <= b.length; j++) {
372
- const tmp = row[j];
373
- row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
374
- prev = tmp;
375
- }
376
- }
377
- return row[b.length];
378
- };
379
413
  let best = null;
380
414
  let bestD = Infinity;
381
415
  for (const k of known) {
382
416
  if (!k.startsWith('--')) continue;
383
- const d = dist(arg, k);
417
+ const d = editDistance(arg, k);
384
418
  if (d < bestD) { best = k; bestD = d; }
385
419
  }
386
420
  return best && bestD <= 2 ? best : null;
package/lib/acp-map.js CHANGED
@@ -13,7 +13,7 @@
13
13
  // - session/messages: [{info:{role, semantics:{kind, uiVisibility}},
14
14
  // parts:[{type:text|reasoning|tool, …}]}]
15
15
  const path = require('node:path');
16
- const { supportedEfforts, supportsImage } = require('./models.js');
16
+ const { supportedEfforts, supportsImage, CONTEXT_WINDOWS, OFFICIAL_IDS } = require('./models.js');
17
17
 
18
18
  // Engine permission modes offered as the ACP session mode. `auto` is
19
19
  // reserved-but-unimplemented in the engine and `guarded` behaves like yolo
@@ -26,13 +26,14 @@ const MODES = [
26
26
  ];
27
27
  const MODE_IDS = MODES.map((m) => m.id);
28
28
 
29
- const MODELS = [
30
- { value: 'GLM-5.3', name: 'GLM-5.3', description: 'Default; larger model, text only' },
31
- { value: 'GLM-5.3-Flash', name: 'GLM-5.3-Flash', description: 'Fast and cheap; sees images' },
32
- ];
33
-
34
- // Context windows by model (engine session/create settings; fallback).
35
- const CONTEXT_WINDOWS = { 'GLM-5.3-Flash': 200000, 'GLM-5.3': 1000000 };
29
+ // The model picker, in models.js order (a model without a line here still
30
+ // appears, undescribed). No "default" label: --model decides that per agent.
31
+ const MODEL_NOTES = {
32
+ 'GLM-5.4': 'Strongest model, 1M context, sees images',
33
+ 'GLM-5.3': 'Previous flagship, 1M context, text only',
34
+ 'GLM-5.3-Flash': 'Fast and cheap, sees images',
35
+ };
36
+ const MODELS = OFFICIAL_IDS.map((id) => ({ value: id, name: id, ...(MODEL_NOTES[id] ? { description: MODEL_NOTES[id] } : {}) }));
36
37
 
37
38
  const MAX_TOOL_TEXT = 8000;
38
39
 
@@ -82,8 +83,8 @@ function effortFor(model, effort, opts = {}) {
82
83
 
83
84
  // ACP prompt content blocks → the engine's prompt text. Images are written
84
85
  // by `saveImage(block, index) → path` (the engine takes a string prompt;
85
- // GLM-5.3-Flash reads image files with its Read tool).
86
- function promptText(blocks, { saveImage = null, model = null, env } = {}) {
86
+ // an image-capable model reads image files with its Read tool).
87
+ function promptText(blocks, { saveImage = null, model = null, env, builtinConfig } = {}) {
87
88
  const parts = [];
88
89
  let images = 0;
89
90
  for (const block of Array.isArray(blocks) ? blocks : []) {
@@ -91,7 +92,8 @@ function promptText(blocks, { saveImage = null, model = null, env } = {}) {
91
92
  if (block.type === 'text' && typeof block.text === 'string') {
92
93
  parts.push(block.text);
93
94
  } else if (block.type === 'resource_link') {
94
- parts.push(`Referenced: ${uriToPath(block.uri) || block.name || ''}`.trim());
95
+ // A non-file link keeps its URI: the name alone loses where it points.
96
+ parts.push(`Referenced: ${uriToPath(block.uri) || block.uri || block.name || ''}`.trim());
95
97
  } else if (block.type === 'resource' && block.resource) {
96
98
  const r = block.resource;
97
99
  const where = uriToPath(r.uri) || r.uri || 'attachment';
@@ -99,8 +101,8 @@ function promptText(blocks, { saveImage = null, model = null, env } = {}) {
99
101
  else parts.push(`Referenced: ${where}`);
100
102
  } else if (block.type === 'image' && typeof block.data === 'string' && saveImage) {
101
103
  const file = saveImage(block, images++);
102
- const note = model && !supportsImage(model, { env })
103
- ? ` (${model} cannot see images; switch to GLM-5.3-Flash to have it looked at)`
104
+ const note = model && !supportsImage(model, { env, builtinConfig })
105
+ ? ` (${model} cannot see images; switch to ${OFFICIAL_IDS.filter((id) => supportsImage(id, { env, builtinConfig })).join(' or ')} to have it looked at)`
104
106
  : ' (open it with the Read tool)';
105
107
  parts.push(`Attached image: ${file}${note}`);
106
108
  }
@@ -264,7 +266,7 @@ class TurnMapper {
264
266
  constructor({ engineSessionId, cwd }) {
265
267
  this.engineSessionId = engineSessionId;
266
268
  this.cwd = cwd;
267
- this.tools = new Map(); // toolCallId → {name, announced, hidden, done}
269
+ this.tools = new Map(); // toolCallId → {name, announced, hidden, done, diff}
268
270
  this.contextUsed = null;
269
271
  this.title = null;
270
272
  this.mode = null;
@@ -334,6 +336,7 @@ class TurnMapper {
334
336
  return plan ? [plan] : [];
335
337
  }
336
338
  const info = toolInfo(toolName, input, this.cwd);
339
+ if (info.content) t.diff = info.content;
337
340
  const fields = compact({
338
341
  title: info.title,
339
342
  kind: info.kind,
@@ -364,7 +367,11 @@ class TurnMapper {
364
367
  t.done = true;
365
368
  const r = p.result || {};
366
369
  const failed = r.success === false;
367
- out.push({ sessionUpdate: 'tool_call_update', toolCallId: id, status: failed ? 'failed' : 'completed', ...compact(toolOutput(t.name, typeof r.content === 'string' ? r.content : r.content === undefined ? '' : JSON.stringify(r.content))) });
370
+ const result = toolOutput(t.name, typeof r.content === 'string' ? r.content : r.content === undefined ? '' : JSON.stringify(r.content));
371
+ // An update's `content` replaces the call's content: an edit that
372
+ // applied keeps its diff in front of the result text.
373
+ const content = [...(!failed && t.diff ? t.diff : []), ...(result.content || [])];
374
+ out.push({ sessionUpdate: 'tool_call_update', toolCallId: id, status: failed ? 'failed' : 'completed', ...compact({ content: content.length ? content : undefined, rawOutput: result.rawOutput }) });
368
375
  } else if (p.kind === 'error') {
369
376
  t.done = true;
370
377
  const e = p.error || p.result || {};
@@ -525,19 +532,16 @@ function contextWindow(model, { available = null, created = null } = {}) {
525
532
  module.exports = {
526
533
  MODES,
527
534
  MODE_IDS,
528
- MODELS,
529
535
  modeState,
530
536
  configOptions,
531
537
  effortFor,
532
538
  promptText,
533
539
  mcpSpec,
534
540
  toolInfo,
535
- planUpdate,
536
541
  TurnMapper,
537
542
  historyUpdates,
538
543
  permissionRequest,
539
544
  planApprovalRequest,
540
545
  contextWindow,
541
- uriToPath,
542
546
  cleanTitle,
543
547
  };
package/lib/acp.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
  // `zcode-agent acp`: an Agent Client Protocol (ACP v1) agent on stdio, so
3
- // T3 Code, Zed and other ACP clients drive GLM-5.3 through the ZCode engine
4
- // directly (DESIGN §20).
3
+ // T3 Code, Zed and other ACP clients drive GLM-5.4 (or GLM-5.3, GLM-5.3-Flash)
4
+ // through the ZCode engine directly (DESIGN §21).
5
5
  //
6
6
  // client ⇄ (ACP: JSON-RPC 2.0, one object per line) ⇄ this process
7
7
  // ⇄ (ZCode Protocol, lib/appserver.js) ⇄ one engine per session
@@ -29,7 +29,7 @@ const { openSession, runTurn, TurnError } = require('./appserver.js');
29
29
  const { reservePort } = require('./ports.js');
30
30
  const { workspaceRoot } = require('./workspace.js');
31
31
  const { sessionCost } = require('./cost.js');
32
- const { normalizeModel, normalizeEffort, supportedEfforts } = require('./models.js');
32
+ const { normalizeModel, normalizeEffort, supportedEfforts, OFFICIAL_IDS } = require('./models.js');
33
33
  const map = require('./acp-map.js');
34
34
 
35
35
  const PROTOCOL_VERSION = 1;
@@ -43,6 +43,7 @@ const ERR = {
43
43
  notFound: -32002,
44
44
  };
45
45
  const MAX_TIMER_MS = 2147483647;
46
+ const RESULT_STOP_REASONS = { cancelled: 'cancelled', error_max_turns: 'max_turn_requests', error_max_tool_calls: 'max_turn_requests' };
46
47
  // An ACP session's record between turns: not live (`wait` returns, `watch`
47
48
  // shows it done, `cancel` has nothing to stop) though its client may prompt
48
49
  // again; `running` only while a turn runs.
@@ -174,7 +175,6 @@ class Agent {
174
175
  this.env = env;
175
176
  this.version = version;
176
177
  this.sessions = new Map();
177
- this.clientCapabilities = {};
178
178
  this.cachedRuntime = null;
179
179
  peer.onRequest = (method, params) => this.handle(method, params);
180
180
  peer.onNotification = (method, params) => {
@@ -208,6 +208,8 @@ class Agent {
208
208
  return this.newSession(params);
209
209
  case 'session/load':
210
210
  return this.loadSession(params);
211
+ case 'session/resume': // load without the history replay
212
+ return this.loadSession(params, { replay: false });
211
213
  case 'session/list':
212
214
  return this.listSessions(params);
213
215
  case 'session/prompt':
@@ -219,9 +221,12 @@ class Agent {
219
221
  case 'session/set_config_option':
220
222
  return this.setConfig(this.session(params), params.configId, params.value)
221
223
  .then((s) => ({ configOptions: this.options(s) }));
222
- case 'session/close':
223
- await this.closeSession(this.session(params), { reason: 'closed' });
224
+ case 'session/close': {
225
+ // Closing a session that is not open succeeds (ACP): nothing to do.
226
+ const open = this.sessions.get(params && params.sessionId);
227
+ if (open) await this.closeSession(open, { reason: 'closed' });
224
228
  return {};
229
+ }
225
230
  case 'session/cancel': // tolerated as a request too
226
231
  this.cancel(params);
227
232
  return {};
@@ -230,15 +235,14 @@ class Agent {
230
235
  }
231
236
  }
232
237
 
233
- initialize(params) {
234
- this.clientCapabilities = (params && params.clientCapabilities) || {};
238
+ initialize() {
235
239
  return {
236
240
  protocolVersion: PROTOCOL_VERSION,
237
241
  agentCapabilities: {
238
242
  loadSession: true,
239
243
  promptCapabilities: { image: true, audio: false, embeddedContext: true },
240
244
  mcpCapabilities: { http: true, sse: true },
241
- sessionCapabilities: { list: {}, close: {} },
245
+ sessionCapabilities: { list: {}, close: {}, resume: {} },
242
246
  },
243
247
  authMethods: [
244
248
  {
@@ -247,7 +251,7 @@ class Agent {
247
251
  description: 'Sign in to the ZCode app, set ZAI_API_KEY, or pipe a key into `zcode-agent login`.',
248
252
  },
249
253
  ],
250
- agentInfo: { name: 'zcode-agent', title: 'zcode-agent (GLM-5.3)', version: this.version },
254
+ agentInfo: { name: 'zcode-agent', title: 'zcode-agent (GLM)', version: this.version },
251
255
  };
252
256
  }
253
257
 
@@ -339,7 +343,9 @@ class Agent {
339
343
  return s;
340
344
  }
341
345
 
342
- async loadSession(params) {
346
+ // session/load replays the conversation at the client; session/resume
347
+ // (replay: false) reopens it for a client that already shows it.
348
+ async loadSession(params, { replay = true } = {}) {
343
349
  const cwd = this.realCwd(params.cwd);
344
350
  const id = params.sessionId;
345
351
  let s = this.sessions.get(id);
@@ -366,8 +372,10 @@ class Agent {
366
372
  }
367
373
  try {
368
374
  await this.ensureEngine(s);
369
- const history = await s.client.request('session/messages', { sessionId: s.engine.sessionId }, { timeoutMs: 30000 });
370
- for (const update of map.historyUpdates(history && history.messages, { cwd: s.cwd })) this.send(s, update);
375
+ if (replay) {
376
+ const history = await s.client.request('session/messages', { sessionId: s.engine.sessionId }, { timeoutMs: 30000 });
377
+ for (const update of map.historyUpdates(history && history.messages, { cwd: s.cwd })) this.send(s, update);
378
+ }
371
379
  } catch (err) {
372
380
  // Nothing of a failed load may outlive it: engine, port, owner lock
373
381
  // (a retry would otherwise find its own lock and refuse).
@@ -400,6 +408,9 @@ class Agent {
400
408
  const opts = { env: this.env, builtinConfig: this.builtinConfig() };
401
409
  if (configId === 'mode') {
402
410
  if (!map.MODE_IDS.includes(value)) throw new AcpError(ERR.invalidParams, `unknown mode "${value}" (${map.MODE_IDS.join(', ')})`);
411
+ // An engine still starting was given the old mode: wait for it, or the
412
+ // change (yolo → build, build → plan) would never reach it.
413
+ if (s.starting) await s.starting.catch(() => {});
403
414
  if (s.client && !s.client.dead && s.engine) {
404
415
  await s.client.request('session/setMode', { sessionId: s.engine.sessionId, mode: value }, { timeoutMs: 15000 });
405
416
  }
@@ -407,7 +418,7 @@ class Agent {
407
418
  this.send(s, { sessionUpdate: 'current_mode_update', currentModeId: value });
408
419
  } else if (configId === 'model') {
409
420
  const model = normalizeModel(value);
410
- if (!model) throw new AcpError(ERR.invalidParams, `unknown model "${value}" (GLM-5.3, GLM-5.3-Flash)`);
421
+ if (!model) throw new AcpError(ERR.invalidParams, `unknown model "${value}" (${OFFICIAL_IDS.join(', ')})`);
411
422
  s.model = model;
412
423
  s.effort = map.effortFor(model, s.effort, opts);
413
424
  } else if (configId === 'effort') {
@@ -489,8 +500,9 @@ class Agent {
489
500
  mcpSpecs: [...(this.defaults.mcpSpecs || []), map.mcpSpec(s.mcpServers)],
490
501
  hermetic,
491
502
  // 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
503
+ // tool schemas ride along on every model request (measured in 1.3.0:
504
+ // 33.5k → 21.8k input tokens on the first request without the
505
+ // desktop's servers). Playwright and
494
506
  // the client's servers stay; --mcp-inherit / ZCODE_ACP_INHERIT_MCP=1
495
507
  // add the rest back.
496
508
  inheritMcp: !hermetic && (!!this.defaults.mcpInherit || env.ZCODE_ACP_INHERIT_MCP === '1'),
@@ -498,6 +510,7 @@ class Agent {
498
510
  skillsDirs: this.defaults.skillsDirs || [],
499
511
  noSkills: !!this.defaults.noSkills,
500
512
  inheritDesktop: !!this.defaults.inheritDesktop || env.ZCODE_INHERIT_DESKTOP === '1',
513
+ builtinConfig: runtime.builtinConfig,
501
514
  profile: 'general-purpose',
502
515
  model: s.model,
503
516
  instructions: ACP_AGENTS_MD,
@@ -515,7 +528,7 @@ class Agent {
515
528
  resumeSessionId: record.engineSessionId || s.startFacts.engineSessionId || null,
516
529
  requiredMcp: built.mcp.added,
517
530
  mode: s.mode,
518
- onMcpStatuses: (statuses) => recordMcpHealth(rootDir(env), statuses, built.mcp.inherited),
531
+ onMcpStatuses: (statuses) => recordMcpHealth(rootDir(env), statuses, built.mcp.inherited, { scrub: runtime.scrub }),
519
532
  });
520
533
  if (s.closed) throw new AcpError(ERR.notFound, `session "${s.id}" is closed`);
521
534
  s.engine = { sessionId: opened.sessionId, created: opened.created };
@@ -583,8 +596,8 @@ class Agent {
583
596
  permission: (params) => ask(map.permissionRequest(params, { cwd: s.cwd })),
584
597
  userInput: (params) => {
585
598
  if (params.schema && params.schema.interaction === 'plan_approval') return ask(map.planApprovalRequest(params));
586
- // AskUserQuestion and MCP elicitations: ACP v1 has no form UI, so the
587
- // model asks in chat and the next prompt carries the answer.
599
+ // AskUserQuestion and MCP elicitations: ACP elicitation is not used
600
+ // yet, so the model asks in chat and the next prompt carries the answer.
588
601
  return {
589
602
  action: 'decline',
590
603
  reason: 'This client has no question form. Ask the user in your reply instead and end your turn; their next message is the answer.',
@@ -621,24 +634,25 @@ class Agent {
621
634
  let mapper = null;
622
635
  let phaseAt = 0;
623
636
  const activity = s.activity;
637
+ const timeoutMs = Math.min(this.defaults.timeoutMs || MAX_TIMER_MS, MAX_TIMER_MS);
624
638
  try {
639
+ // Nothing to send: no engine start and no session record for it.
640
+ if (!map.promptText(params.prompt, { saveImage: () => 'image' }).trim()) return { stopReason: 'end_turn' };
625
641
  this.cancelPrewarm(s);
626
642
  if (!(await this.untilCancelled(s, this.ensureEngine(s)))) return { stopReason: 'cancelled' };
627
643
  this.commit(s);
628
- const text = map.promptText(params.prompt, { saveImage: (block, i) => this.saveImage(s, block, i), model: s.model, env });
629
- if (!text.trim()) return { stopReason: 'end_turn' };
644
+ const text = map.promptText(params.prompt, { saveImage: (block, i) => this.saveImage(s, block, i), model: s.model, env, builtinConfig: this.builtinConfig() });
630
645
  const record = store.readSession(s.id, env) || {};
631
646
  this.persist(s, { phase: 'working', turns: (record.turns || 0) + 1, pid: process.pid, state: 'running', status: null });
632
647
  mapper = new map.TurnMapper({ engineSessionId: s.engine.sessionId, cwd: s.cwd });
633
648
  mapper.mode = s.mode;
634
649
  mapper.title = s.title || null;
635
650
  mapper.prompt = text;
636
- const timeoutMs = this.defaults.timeoutMs || MAX_TIMER_MS;
637
651
  const turn = await runTurn(s.client, { sessionId: s.engine.sessionId }, {
638
652
  modelId: s.model,
639
653
  effort: s.effort,
640
654
  prompt: text,
641
- deadline: Date.now() + Math.min(timeoutMs, MAX_TIMER_MS),
655
+ deadline: Date.now() + timeoutMs,
642
656
  signal: s.abort.signal,
643
657
  onFrame: (frame) => {
644
658
  for (const update of mapper.feed(frame)) {
@@ -675,16 +689,26 @@ class Agent {
675
689
  },
676
690
  });
677
691
  for (const update of mapper.closeOpen('completed')) this.send(s, update);
678
- this.addUsage(s, turn.usage);
692
+ this.addUsage(s, turn.usage, turn.modelRequests);
679
693
  return { stopReason: 'end_turn' };
680
694
  } catch (err) {
681
695
  if (mapper) for (const update of mapper.closeOpen('failed')) this.send(s, update);
696
+ // What a stopped turn used is still billed: counted before any return.
697
+ if (err instanceof TurnError && err.turn) this.addUsage(s, err.turn.usage, err.turn.modelRequests);
682
698
  if (s.abort.signal.aborted) return { stopReason: 'cancelled' };
683
699
  if (err instanceof TurnError) {
684
- if (err.turn) this.addUsage(s, err.turn.usage);
685
700
  if (err.kind === 'cancelled') return { stopReason: 'cancelled' };
686
701
  if (err.kind === 'engine_exit') this.dropEngine(s);
687
- if (err.kind === 'result_type' && /max|limit/i.test(err.message)) return { stopReason: 'max_turn_requests' };
702
+ if (err.kind === 'timeout') {
703
+ // The agent's own --timeout-ms: the turn was stopped, which the
704
+ // user should read in the conversation, not as an error toast.
705
+ this.send(s, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `\n\nStopped: this prompt ran past the agent's time limit (--timeout-ms ${timeoutMs}). Send a message to continue.` } });
706
+ return { stopReason: 'cancelled' };
707
+ }
708
+ // Engine stops that ACP has a stop reason for; any other non-success
709
+ // result (error_max_budget, …) stays an error the user sees.
710
+ const stop = err.kind === 'result_type' && RESULT_STOP_REASONS[err.resultType];
711
+ if (stop) return { stopReason: stop };
688
712
  throw new AcpError(ERR.internal, this.scrub(err.message).slice(0, 1000));
689
713
  }
690
714
  throw err instanceof AcpError ? err : new AcpError(ERR.internal, this.scrub(err && err.message ? err.message : String(err)).slice(0, 1000));
@@ -711,8 +735,11 @@ class Agent {
711
735
  }
712
736
  }
713
737
 
714
- addUsage(s, usage) {
715
- if (!usage || !s.persisted) return;
738
+ // The engine's usage is {inputTokens, outputTokens}; requests are counted
739
+ // from the turn's model_request_started events.
740
+ addUsage(s, usage, requests = 0) {
741
+ if (!s.persisted || (!usage && !requests)) return;
742
+ usage = usage || {};
716
743
  try {
717
744
  store.updateSession(s.id, (r) => {
718
745
  const t = r.usageTotal || { inputTokens: 0, outputTokens: 0, modelRequests: 0 };
@@ -720,7 +747,7 @@ class Agent {
720
747
  usageTotal: {
721
748
  inputTokens: (t.inputTokens || 0) + (usage.inputTokens || 0),
722
749
  outputTokens: (t.outputTokens || 0) + (usage.outputTokens || 0),
723
- modelRequests: (t.modelRequests || 0) + (usage.modelRequestCount || 0),
750
+ modelRequests: (t.modelRequests || 0) + (requests || 0),
724
751
  },
725
752
  };
726
753
  }, this.env);
@@ -778,7 +805,10 @@ class Agent {
778
805
  s.closed = true;
779
806
  this.cancelPrewarm(s);
780
807
  this.dropEngine(s);
781
- if (s.persisted) this.persist(s, { state: 'finished', phase: 'done', status: 'completed', closedReason: reason });
808
+ // Only the process that owns the session writes its closing state: a
809
+ // load refused because another agent has it open must not mark that
810
+ // agent's running session finished.
811
+ if (s.persisted && s.releaseOwner) this.persist(s, { state: 'finished', phase: 'done', status: 'completed', closedReason: reason });
782
812
  if (s.releasePort) s.releasePort();
783
813
  if (s.releaseOwner) s.releaseOwner();
784
814
  s.releasePort = null;
@@ -828,7 +858,29 @@ function serve({ defaults, env = process.env, version, input = process.stdin, ou
828
858
  agent.shutdownSync(reason);
829
859
  if (code !== null) process.exit(code);
830
860
  };
831
- peer.onClose = () => stop('client closed stdin', 0);
861
+ // The client closed stdin: stop running prompts and let their replies (and
862
+ // anything already written) reach the pipe before exiting. Bounded, so a
863
+ // client that is gone can never leave the agent hanging.
864
+ peer.onClose = () => {
865
+ if (done) return;
866
+ peer.failPending('client disconnected');
867
+ const running = [];
868
+ for (const s of agent.sessions.values()) {
869
+ if (s.abort) s.abort.abort();
870
+ if (s.running) running.push(s.running);
871
+ }
872
+ const exit = () => process.exit(0);
873
+ setTimeout(exit, 3000).unref();
874
+ output.on('error', exit);
875
+ const finish = () => {
876
+ if (done) return;
877
+ done = true;
878
+ agent.shutdownSync('client closed stdin');
879
+ output.write('', exit);
880
+ };
881
+ if (!running.length) finish();
882
+ else Promise.race([Promise.allSettled(running), new Promise((r) => setTimeout(r, 2000))]).then(finish);
883
+ };
832
884
  process.on('SIGTERM', () => stop('SIGTERM', 0));
833
885
  process.on('SIGINT', () => stop('SIGINT', 0));
834
886
  process.on('SIGHUP', () => stop('SIGHUP', 0));
@@ -836,4 +888,4 @@ function serve({ defaults, env = process.env, version, input = process.stdin, ou
836
888
  return { peer, agent };
837
889
  }
838
890
 
839
- module.exports = { serve, Agent, Peer, AcpError, PROTOCOL_VERSION, ERR };
891
+ module.exports = { serve, Agent };