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.
package/lib/acp.js ADDED
@@ -0,0 +1,763 @@
1
+ 'use strict';
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).
5
+ //
6
+ // client ⇄ (ACP: JSON-RPC 2.0, one object per line) ⇄ this process
7
+ // ⇄ (ZCode Protocol, lib/appserver.js) ⇄ one engine per session
8
+ //
9
+ // Every ACP session is a zcode-agent session (kind "acp") in the store,
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
13
+ // session/new and kill the process, which must leave nothing behind.
14
+ //
15
+ // stdout carries protocol frames only. Diagnostics go to stderr, and every
16
+ // frame to $ZCODE_ACP_LOG when set.
17
+ const fs = require('node:fs');
18
+ const path = require('node:path');
19
+ const readline = require('node:readline');
20
+ const store = require('./store.js');
21
+ const { resolveRuntime, makeClient, ConfigError } = require('./bootstrap.js');
22
+ const { buildEngineHome, rootDir, liveDir, recordMcpHealth, ACP_AGENTS_MD } = require('./isolation.js');
23
+ const { openSession, runTurn, TurnError } = require('./appserver.js');
24
+ const { reservePort } = require('./ports.js');
25
+ const { workspaceRoot } = require('./workspace.js');
26
+ const { sessionCost } = require('./cost.js');
27
+ const { normalizeModel, normalizeEffort, supportedEfforts } = require('./models.js');
28
+ const map = require('./acp-map.js');
29
+
30
+ const PROTOCOL_VERSION = 1;
31
+ const ERR = {
32
+ parse: -32700,
33
+ invalidRequest: -32600,
34
+ methodNotFound: -32601,
35
+ invalidParams: -32602,
36
+ internal: -32603,
37
+ authRequired: -32000,
38
+ notFound: -32002,
39
+ };
40
+ const MAX_TIMER_MS = 2147483647;
41
+ // An ACP session's record between turns: not live (`wait` returns, `watch`
42
+ // shows it done, `cancel` has nothing to stop) though its client may prompt
43
+ // again; `running` only while a turn runs.
44
+ const IDLE = { state: 'finished', status: 'completed', phase: 'idle' };
45
+ const LIST_LIMIT = 256;
46
+
47
+ class AcpError extends Error {
48
+ constructor(code, message, data) {
49
+ super(message);
50
+ this.code = code;
51
+ this.data = data;
52
+ }
53
+ }
54
+
55
+ // --- JSON-RPC 2.0 peer over newline-delimited JSON --------------------------------
56
+
57
+ class Peer {
58
+ constructor({ input, output, log = null }) {
59
+ this.output = output;
60
+ this.log = log;
61
+ this.nextId = 1;
62
+ this.pending = new Map();
63
+ this.onRequest = async () => {
64
+ throw new AcpError(ERR.methodNotFound, 'method not found');
65
+ };
66
+ this.onNotification = () => {};
67
+ this.onClose = () => {};
68
+ const rl = readline.createInterface({ input });
69
+ rl.on('line', (line) => this.receive(line));
70
+ rl.on('close', () => this.onClose());
71
+ }
72
+
73
+ write(obj) {
74
+ const line = JSON.stringify(obj);
75
+ if (this.log) this.log('out', line);
76
+ this.output.write(line + '\n');
77
+ }
78
+
79
+ receive(line) {
80
+ if (!line.trim()) return;
81
+ if (this.log) this.log('in', line);
82
+ let msg;
83
+ try {
84
+ msg = JSON.parse(line);
85
+ } catch {
86
+ this.write({ jsonrpc: '2.0', id: null, error: { code: ERR.parse, message: 'parse error' } });
87
+ return;
88
+ }
89
+ if (!msg || typeof msg !== 'object') return;
90
+ if (typeof msg.method === 'string') {
91
+ if (msg.id === undefined || msg.id === null) {
92
+ try {
93
+ this.onNotification(msg.method, msg.params || {});
94
+ } catch {
95
+ /* notifications have no reply */
96
+ }
97
+ return;
98
+ }
99
+ // Dispatched synchronously: a handler runs up to its first await
100
+ // before the next line of the same chunk (session/prompt then
101
+ // session/cancel in one write must cancel that prompt).
102
+ let pending;
103
+ try {
104
+ pending = Promise.resolve(this.onRequest(msg.method, msg.params || {}));
105
+ } catch (err) {
106
+ pending = Promise.reject(err);
107
+ }
108
+ pending
109
+ .then(
110
+ (result) => this.write({ jsonrpc: '2.0', id: msg.id, result: result ?? null }),
111
+ (err) => this.write({
112
+ jsonrpc: '2.0',
113
+ id: msg.id,
114
+ error: {
115
+ code: err instanceof AcpError ? err.code : ERR.internal,
116
+ message: String((err && err.message) || err),
117
+ ...(err && err.data !== undefined ? { data: err.data } : {}),
118
+ },
119
+ })
120
+ );
121
+ return;
122
+ }
123
+ if (msg.id !== undefined && this.pending.has(msg.id)) {
124
+ const { resolve, reject } = this.pending.get(msg.id);
125
+ this.pending.delete(msg.id);
126
+ if (msg.error) reject(new AcpError(msg.error.code, msg.error.message || 'client error', msg.error.data));
127
+ else resolve(msg.result);
128
+ }
129
+ }
130
+
131
+ request(method, params) {
132
+ const id = this.nextId++;
133
+ return new Promise((resolve, reject) => {
134
+ this.pending.set(id, { resolve, reject });
135
+ this.write({ jsonrpc: '2.0', id, method, params });
136
+ });
137
+ }
138
+
139
+ notify(method, params) {
140
+ this.write({ jsonrpc: '2.0', method, params });
141
+ }
142
+
143
+ // Unblocks every request still waiting on the client (it went away).
144
+ failPending(message) {
145
+ for (const { reject } of this.pending.values()) reject(new AcpError(ERR.internal, message));
146
+ this.pending.clear();
147
+ }
148
+ }
149
+
150
+ // --- the agent ----------------------------------------------------------------------
151
+
152
+ class Agent {
153
+ // defaults: {model, effort, mode, mcpSpecs, hermetic, browser, skillsDirs,
154
+ // noSkills, inheritDesktop, timeoutMs}
155
+ constructor({ peer, defaults, env = process.env, version = '0.0.0' }) {
156
+ this.peer = peer;
157
+ this.defaults = defaults;
158
+ this.env = env;
159
+ this.version = version;
160
+ this.sessions = new Map();
161
+ this.clientCapabilities = {};
162
+ this.cachedRuntime = null;
163
+ peer.onRequest = (method, params) => this.handle(method, params);
164
+ peer.onNotification = (method, params) => {
165
+ if (method === 'session/cancel') this.cancel(params);
166
+ };
167
+ }
168
+
169
+ runtime() {
170
+ if (this.cachedRuntime) return this.cachedRuntime;
171
+ try {
172
+ this.cachedRuntime = resolveRuntime(this.env);
173
+ } catch (err) {
174
+ if (err instanceof ConfigError && err.exitCode === 3) {
175
+ throw new AcpError(ERR.authRequired, `Authentication required: ${err.message}`);
176
+ }
177
+ if (err instanceof ConfigError) throw new AcpError(ERR.internal, err.message);
178
+ throw err;
179
+ }
180
+ return this.cachedRuntime;
181
+ }
182
+
183
+ async handle(method, params) {
184
+ switch (method) {
185
+ case 'initialize':
186
+ return this.initialize(params);
187
+ case 'authenticate':
188
+ this.cachedRuntime = null;
189
+ this.runtime();
190
+ return {};
191
+ case 'session/new':
192
+ return this.newSession(params);
193
+ case 'session/load':
194
+ return this.loadSession(params);
195
+ case 'session/list':
196
+ return this.listSessions(params);
197
+ case 'session/prompt':
198
+ return this.prompt(params);
199
+ case 'session/set_mode':
200
+ return this.setConfig(this.session(params), 'mode', params.modeId).then(() => ({}));
201
+ case 'session/set_model':
202
+ return this.setConfig(this.session(params), 'model', params.modelId).then(() => ({}));
203
+ case 'session/set_config_option':
204
+ return this.setConfig(this.session(params), params.configId, params.value)
205
+ .then((s) => ({ configOptions: this.options(s) }));
206
+ case 'session/close':
207
+ await this.closeSession(this.session(params), { reason: 'closed' });
208
+ return {};
209
+ case 'session/cancel': // tolerated as a request too
210
+ this.cancel(params);
211
+ return {};
212
+ default:
213
+ throw new AcpError(ERR.methodNotFound, `method not found: ${method}`);
214
+ }
215
+ }
216
+
217
+ initialize(params) {
218
+ this.clientCapabilities = (params && params.clientCapabilities) || {};
219
+ return {
220
+ protocolVersion: PROTOCOL_VERSION,
221
+ agentCapabilities: {
222
+ loadSession: true,
223
+ promptCapabilities: { image: true, audio: false, embeddedContext: true },
224
+ mcpCapabilities: { http: true, sse: true },
225
+ sessionCapabilities: { list: {}, close: {} },
226
+ },
227
+ authMethods: [
228
+ {
229
+ id: 'zai-api-key',
230
+ name: 'Z.ai API key',
231
+ description: 'Sign in to the ZCode app, set ZAI_API_KEY, or pipe a key into `zcode-agent login`.',
232
+ },
233
+ ],
234
+ agentInfo: { name: 'zcode-agent', title: 'zcode-agent (GLM-5.3)', version: this.version },
235
+ };
236
+ }
237
+
238
+ session(params) {
239
+ const s = this.sessions.get(params && params.sessionId);
240
+ if (!s) throw new AcpError(ERR.notFound, `no open session "${params && params.sessionId}" (session/new or session/load first)`);
241
+ return s;
242
+ }
243
+
244
+ options(s) {
245
+ return map.configOptions(s, { env: this.env, builtinConfig: this.builtinConfig() });
246
+ }
247
+
248
+ builtinConfig() {
249
+ return this.cachedRuntime ? this.cachedRuntime.builtinConfig : undefined;
250
+ }
251
+
252
+ realCwd(cwd) {
253
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) throw new AcpError(ERR.invalidParams, 'cwd must be an absolute path');
254
+ try {
255
+ const real = fs.realpathSync(cwd);
256
+ if (!fs.statSync(real).isDirectory()) throw new Error('not a directory');
257
+ return real;
258
+ } catch {
259
+ throw new AcpError(ERR.invalidParams, `cwd "${cwd}" is not an existing directory`);
260
+ }
261
+ }
262
+
263
+ async newSession(params) {
264
+ const cwd = this.realCwd(params.cwd);
265
+ this.runtime(); // no key → auth_required now, not at the first prompt
266
+ let id = store.newId();
267
+ while (store.readSession(id, this.env) || this.sessions.has(id)) id = store.newId();
268
+ const s = this.makeSession({
269
+ id,
270
+ cwd,
271
+ mcpServers: params.mcpServers,
272
+ model: this.defaults.model,
273
+ effort: this.defaults.effort,
274
+ mode: this.defaults.mode,
275
+ persisted: false,
276
+ });
277
+ return { sessionId: id, modes: map.modeState(s.mode), configOptions: this.options(s) };
278
+ }
279
+
280
+ makeSession(fields) {
281
+ const s = {
282
+ ...fields,
283
+ client: null, // set as soon as the engine spawns, so close/exit can kill it
284
+ engine: null, // {sessionId, created} once the engine session is open
285
+ starting: null, // the in-flight engine start (one at a time)
286
+ running: null, // the in-flight prompt
287
+ closed: false,
288
+ busy: false,
289
+ abort: null,
290
+ releaseOwner: null,
291
+ releasePort: null,
292
+ sessionEnv: null,
293
+ contextUsed: null,
294
+ available: null,
295
+ images: 0,
296
+ activity: { toolCalls: 0, subagentsStarted: 0, modelRequests: 0, lastTool: null, lastToolAt: null, lastEventAt: null },
297
+ };
298
+ s.effort = map.effortFor(s.model, s.effort, { env: this.env, builtinConfig: this.builtinConfig() });
299
+ this.sessions.set(s.id, s);
300
+ return s;
301
+ }
302
+
303
+ async loadSession(params) {
304
+ const cwd = this.realCwd(params.cwd);
305
+ const id = params.sessionId;
306
+ let s = this.sessions.get(id);
307
+ const fresh = !s;
308
+ if (!s) {
309
+ const record = store.readSession(id, this.env);
310
+ if (!record || record.kind !== 'acp' || !record.engineSessionId) {
311
+ throw new AcpError(ERR.notFound, `no zcode-agent ACP session "${id}"`);
312
+ }
313
+ this.runtime();
314
+ s = this.makeSession({
315
+ id,
316
+ cwd: record.cwd && fs.existsSync(record.cwd) ? record.cwd : cwd,
317
+ mcpServers: params.mcpServers,
318
+ model: normalizeModel(record.model) || this.defaults.model,
319
+ effort: normalizeEffort(record.effort) || this.defaults.effort,
320
+ mode: map.MODE_IDS.includes(record.acp && record.acp.mode) ? record.acp.mode : this.defaults.mode,
321
+ title: record.label || null,
322
+ persisted: true,
323
+ });
324
+ if (record.activity) Object.assign(s.activity, record.activity);
325
+ } else {
326
+ s.mcpServers = params.mcpServers;
327
+ }
328
+ try {
329
+ await this.ensureEngine(s);
330
+ const history = await s.client.request('session/messages', { sessionId: s.engine.sessionId }, { timeoutMs: 30000 });
331
+ for (const update of map.historyUpdates(history && history.messages, { cwd: s.cwd })) this.send(s, update);
332
+ } catch (err) {
333
+ // Nothing of a failed load may outlive it: engine, port, owner lock
334
+ // (a retry would otherwise find its own lock and refuse).
335
+ if (fresh) await this.closeSession(s, { reason: 'load failed' });
336
+ throw err instanceof AcpError ? err : new AcpError(ERR.internal, this.scrub(err.message));
337
+ }
338
+ if (s.title) this.send(s, { sessionUpdate: 'session_info_update', title: s.title });
339
+ return { modes: map.modeState(s.mode), configOptions: this.options(s) };
340
+ }
341
+
342
+ listSessions(params) {
343
+ let cwd = null;
344
+ if (params && params.cwd) {
345
+ try {
346
+ cwd = fs.realpathSync(params.cwd);
347
+ } catch {
348
+ return { sessions: [] };
349
+ }
350
+ }
351
+ const sessions = store.listSessions(this.env)
352
+ .filter((r) => r.kind === 'acp' && r.engineSessionId && (!cwd || r.cwd === cwd))
353
+ .slice(0, LIST_LIMIT)
354
+ .map((r) => ({ sessionId: r.id, cwd: r.cwd, title: r.label || null, updatedAt: r.updatedAt }));
355
+ return { sessions };
356
+ }
357
+
358
+ // --- config ---------------------------------------------------------------------
359
+
360
+ async setConfig(s, configId, value) {
361
+ const opts = { env: this.env, builtinConfig: this.builtinConfig() };
362
+ if (configId === 'mode') {
363
+ if (!map.MODE_IDS.includes(value)) throw new AcpError(ERR.invalidParams, `unknown mode "${value}" (${map.MODE_IDS.join(', ')})`);
364
+ if (s.client && !s.client.dead && s.engine) {
365
+ await s.client.request('session/setMode', { sessionId: s.engine.sessionId, mode: value }, { timeoutMs: 15000 });
366
+ }
367
+ s.mode = value;
368
+ this.send(s, { sessionUpdate: 'current_mode_update', currentModeId: value });
369
+ } else if (configId === 'model') {
370
+ const model = normalizeModel(value);
371
+ if (!model) throw new AcpError(ERR.invalidParams, `unknown model "${value}" (GLM-5.3-Flash, GLM-5.3)`);
372
+ s.model = model;
373
+ s.effort = map.effortFor(model, s.effort, opts);
374
+ } else if (configId === 'effort') {
375
+ const effort = normalizeEffort(value);
376
+ const levels = supportedEfforts(s.model, opts);
377
+ if (!effort || !levels.includes(effort)) throw new AcpError(ERR.invalidParams, `effort "${value}" is not supported by ${s.model} (${levels.join(', ')})`);
378
+ s.effort = effort;
379
+ } else {
380
+ throw new AcpError(ERR.invalidParams, `unknown config option "${configId}" (mode, model, effort)`);
381
+ }
382
+ this.persist(s);
383
+ this.send(s, { sessionUpdate: 'config_option_update', configOptions: this.options(s) });
384
+ return s;
385
+ }
386
+
387
+ persist(s, patch = {}) {
388
+ if (!s.persisted) return;
389
+ try {
390
+ store.updateSession(s.id, { model: s.model, effort: s.effort, acp: { mode: s.mode }, ...patch }, this.env);
391
+ } catch {
392
+ /* the record is bookkeeping; never fail the protocol over it */
393
+ }
394
+ }
395
+
396
+ send(s, update) {
397
+ this.peer.notify('session/update', { sessionId: s.id, update });
398
+ }
399
+
400
+ scrub(text) {
401
+ return this.cachedRuntime ? this.cachedRuntime.scrub(text) : String(text);
402
+ }
403
+
404
+ // --- engine -----------------------------------------------------------------------
405
+
406
+ // One engine start per session at a time; concurrent callers share it.
407
+ ensureEngine(s) {
408
+ if (s.closed) return Promise.reject(new AcpError(ERR.notFound, `session "${s.id}" is closed`));
409
+ if (s.client && !s.client.dead && s.engine) return Promise.resolve();
410
+ if (!s.starting) s.starting = this.startEngine(s).finally(() => { s.starting = null; });
411
+ return s.starting;
412
+ }
413
+
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.
418
+ async startEngine(s) {
419
+ this.dropEngine(s); // a dead engine from an earlier turn
420
+ const runtime = this.runtime();
421
+ 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;
439
+ }
440
+ if (!s.releaseOwner) {
441
+ s.releaseOwner = store.claimSession(s.id, env);
442
+ if (!s.releaseOwner) throw new AcpError(ERR.internal, `session "${s.id}" is open in another zcode-agent process`);
443
+ }
444
+ const dir = store.sessionDir(s.id, env);
445
+ const record = store.readSession(s.id, env);
446
+ if (!s.sessionEnv) {
447
+ const reserved = await reservePort({ env, preferred: record.port });
448
+ if (!reserved) throw new AcpError(ERR.internal, 'no free port for ZCODE_PORT in 41000-48999');
449
+ s.releasePort = reserved.release;
450
+ const tmp = path.join(dir, 'tmp');
451
+ const out = path.join(tmp, 'out');
452
+ fs.mkdirSync(out, { recursive: true, mode: 0o700 });
453
+ 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);
455
+ }
456
+ const home = path.join(dir, 'home');
457
+ const built = buildEngineHome({
458
+ home,
459
+ root: rootDir(env),
460
+ key: runtime.key,
461
+ live: liveDir(env),
462
+ mcpSpecs: [...(this.defaults.mcpSpecs || []), map.mcpSpec(s.mcpServers)],
463
+ hermetic: !!this.defaults.hermetic || env.ZCODE_HERMETIC === '1',
464
+ browser: this.defaults.browser !== false,
465
+ skillsDirs: this.defaults.skillsDirs || [],
466
+ noSkills: !!this.defaults.noSkills,
467
+ inheritDesktop: !!this.defaults.inheritDesktop || env.ZCODE_INHERIT_DESKTOP === '1',
468
+ profile: 'general-purpose',
469
+ model: s.model,
470
+ instructions: ACP_AGENTS_MD,
471
+ });
472
+ for (let attempt = 1; ; attempt++) {
473
+ if (s.closed) throw new AcpError(ERR.notFound, `session "${s.id}" is closed`);
474
+ const client = makeClient(runtime, { home, cwd: s.cwd, sessionEnv: s.sessionEnv, interactions: this.interactions(s) });
475
+ client.start();
476
+ s.client = client; // tracked from spawn: close/exit kill it mid-start
477
+ try {
478
+ const opened = await openSession(client, {
479
+ workspacePath: s.cwd,
480
+ modelId: s.model,
481
+ effort: s.effort,
482
+ resumeSessionId: record.engineSessionId || null,
483
+ requiredMcp: built.mcp.added,
484
+ mode: s.mode,
485
+ onMcpStatuses: (statuses) => recordMcpHealth(rootDir(env), statuses, built.mcp.inherited),
486
+ });
487
+ if (s.closed) throw new AcpError(ERR.notFound, `session "${s.id}" is closed`);
488
+ s.engine = { sessionId: opened.sessionId, created: opened.created };
489
+ break;
490
+ } catch (err) {
491
+ client.kill();
492
+ if (s.client === client) s.client = null;
493
+ if (err instanceof AcpError) throw err;
494
+ const transient = /timeout|exited|failed to start|dead/.test(err.message);
495
+ if (attempt >= 2 || !transient || s.closed) throw new AcpError(ERR.internal, `engine failed to start: ${runtime.scrub(err.message).slice(0, 600)}`);
496
+ }
497
+ }
498
+ store.updateSession(s.id, {
499
+ engineSessionId: s.engine.sessionId,
500
+ enginePid: s.client.child.pid,
501
+ pid: process.pid,
502
+ ...IDLE,
503
+ outcome: null,
504
+ closedReason: null,
505
+ }, env);
506
+ }
507
+
508
+ // The engine's interactive requests, answered by the person in the client.
509
+ interactions(s) {
510
+ const ask = async (built) => {
511
+ let outcome = null;
512
+ try {
513
+ const res = await this.peer.request('session/request_permission', { sessionId: s.id, ...built.request });
514
+ outcome = res && res.outcome;
515
+ } catch {
516
+ outcome = null; // client error or gone: treated as cancelled
517
+ }
518
+ return built.reply(outcome);
519
+ };
520
+ return {
521
+ permission: (params) => ask(map.permissionRequest(params, { cwd: s.cwd })),
522
+ userInput: (params) => {
523
+ if (params.schema && params.schema.interaction === 'plan_approval') return ask(map.planApprovalRequest(params));
524
+ // AskUserQuestion and MCP elicitations: ACP v1 has no form UI, so the
525
+ // model asks in chat and the next prompt carries the answer.
526
+ return {
527
+ action: 'decline',
528
+ reason: 'This client has no question form. Ask the user in your reply instead and end your turn; their next message is the answer.',
529
+ };
530
+ },
531
+ };
532
+ }
533
+
534
+ // --- prompts ----------------------------------------------------------------------
535
+
536
+ prompt(params) {
537
+ const s = this.session(params);
538
+ if (s.busy) throw new AcpError(ERR.invalidRequest, `session "${s.id}" is already running a prompt`);
539
+ s.busy = true;
540
+ s.abort = new AbortController();
541
+ s.running = this.runPrompt(s, params).finally(() => { s.running = null; });
542
+ return s.running;
543
+ }
544
+
545
+ // Resolves true when `promise` settles first, false when the prompt is
546
+ // cancelled first (the start goes on; the next prompt reuses it).
547
+ untilCancelled(s, promise) {
548
+ const signal = s.abort.signal;
549
+ if (signal.aborted) return Promise.resolve(false);
550
+ promise.catch(() => {});
551
+ return Promise.race([
552
+ promise.then(() => true),
553
+ new Promise((resolve) => signal.addEventListener('abort', () => resolve(false), { once: true })),
554
+ ]);
555
+ }
556
+
557
+ async runPrompt(s, params) {
558
+ const env = this.env;
559
+ let mapper = null;
560
+ let phaseAt = 0;
561
+ const activity = s.activity;
562
+ try {
563
+ if (!(await this.untilCancelled(s, this.ensureEngine(s)))) return { stopReason: 'cancelled' };
564
+ const text = map.promptText(params.prompt, { saveImage: (block, i) => this.saveImage(s, block, i), model: s.model, env });
565
+ if (!text.trim()) return { stopReason: 'end_turn' };
566
+ const record = store.readSession(s.id, env) || {};
567
+ this.persist(s, { phase: 'working', turns: (record.turns || 0) + 1, pid: process.pid, state: 'running', status: null });
568
+ mapper = new map.TurnMapper({ engineSessionId: s.engine.sessionId, cwd: s.cwd });
569
+ mapper.mode = s.mode;
570
+ mapper.title = s.title || null;
571
+ mapper.prompt = text;
572
+ const timeoutMs = this.defaults.timeoutMs || MAX_TIMER_MS;
573
+ const turn = await runTurn(s.client, { sessionId: s.engine.sessionId }, {
574
+ modelId: s.model,
575
+ effort: s.effort,
576
+ prompt: text,
577
+ deadline: Date.now() + Math.min(timeoutMs, MAX_TIMER_MS),
578
+ signal: s.abort.signal,
579
+ onFrame: (frame) => {
580
+ for (const update of mapper.feed(frame)) {
581
+ this.send(s, update);
582
+ if (update.sessionUpdate === 'current_mode_update') {
583
+ s.mode = update.currentModeId;
584
+ this.persist(s);
585
+ this.send(s, { sessionUpdate: 'config_option_update', configOptions: this.options(s) });
586
+ } else if (update.sessionUpdate === 'session_info_update' && update.title) {
587
+ s.title = update.title;
588
+ this.persist(s, { label: update.title });
589
+ }
590
+ }
591
+ },
592
+ onEvent: (ev) => {
593
+ const now = new Date().toISOString();
594
+ activity.lastEventAt = now;
595
+ if (ev.type === 'model_request_started') activity.modelRequests++;
596
+ if (ev.type === 'tool' && ev.phase === 'started') {
597
+ activity.toolCalls++;
598
+ if (ev.name === 'Agent' || ev.name === 'Task') activity.subagentsStarted++;
599
+ activity.lastTool = ev.name;
600
+ activity.lastToolAt = now;
601
+ try {
602
+ store.appendEvent(s.id, { type: 'tool', phase: 'started', name: ev.name, id: ev.id }, env);
603
+ } catch {
604
+ /* best-effort */
605
+ }
606
+ }
607
+ if (Date.now() - phaseAt > 1000) {
608
+ phaseAt = Date.now();
609
+ this.recordActivity(s, activity);
610
+ }
611
+ },
612
+ });
613
+ for (const update of mapper.closeOpen('completed')) this.send(s, update);
614
+ this.addUsage(s, turn.usage);
615
+ return { stopReason: 'end_turn' };
616
+ } catch (err) {
617
+ if (mapper) for (const update of mapper.closeOpen('failed')) this.send(s, update);
618
+ if (s.abort.signal.aborted) return { stopReason: 'cancelled' };
619
+ if (err instanceof TurnError) {
620
+ if (err.turn) this.addUsage(s, err.turn.usage);
621
+ if (err.kind === 'cancelled') return { stopReason: 'cancelled' };
622
+ if (err.kind === 'engine_exit') this.dropEngine(s);
623
+ if (err.kind === 'result_type' && /max|limit/i.test(err.message)) return { stopReason: 'max_turn_requests' };
624
+ throw new AcpError(ERR.internal, this.scrub(err.message).slice(0, 1000));
625
+ }
626
+ throw err instanceof AcpError ? err : new AcpError(ERR.internal, this.scrub(err && err.message ? err.message : String(err)).slice(0, 1000));
627
+ } finally {
628
+ s.busy = false;
629
+ s.abort = null;
630
+ if (mapper && mapper.contextUsed !== null) s.contextUsed = mapper.contextUsed;
631
+ if (mapper && mapper.available) s.available = mapper.available;
632
+ if (!activity.lastEventAt) activity.lastEventAt = new Date().toISOString();
633
+ if (!s.closed) {
634
+ this.persist(s, { ...IDLE, activity: { ...activity } });
635
+ if (mapper) this.sendUsage(s);
636
+ }
637
+ }
638
+ }
639
+
640
+ // `zcode-agent watch` reads this: counts are for the whole session.
641
+ recordActivity(s, activity) {
642
+ if (!s.persisted) return;
643
+ try {
644
+ store.updateSession(s.id, { activity: { ...activity } }, this.env);
645
+ } catch {
646
+ /* best-effort */
647
+ }
648
+ }
649
+
650
+ addUsage(s, usage) {
651
+ if (!usage || !s.persisted) return;
652
+ try {
653
+ store.updateSession(s.id, (r) => {
654
+ const t = r.usageTotal || { inputTokens: 0, outputTokens: 0, modelRequests: 0 };
655
+ return {
656
+ usageTotal: {
657
+ inputTokens: (t.inputTokens || 0) + (usage.inputTokens || 0),
658
+ outputTokens: (t.outputTokens || 0) + (usage.outputTokens || 0),
659
+ modelRequests: (t.modelRequests || 0) + (usage.modelRequestCount || 0),
660
+ },
661
+ };
662
+ }, this.env);
663
+ } catch {
664
+ /* best-effort */
665
+ }
666
+ }
667
+
668
+ // Context use and the session's GLM cost so far (API list price, from the
669
+ // engine's own ledger, as `zcode-agent cost` reports it).
670
+ sendUsage(s) {
671
+ const size = map.contextWindow(s.model, { available: s.available, created: s.engine && s.engine.created });
672
+ const update = { sessionUpdate: 'usage_update', used: Math.max(0, Math.round(s.contextUsed || 0)), size };
673
+ try {
674
+ const cost = sessionCost(store.readSession(s.id, this.env), this.env);
675
+ if (cost && Number.isFinite(cost.usd)) update.cost = { amount: Number(cost.usd.toFixed(6)), currency: 'USD' };
676
+ } catch {
677
+ /* cost is informational */
678
+ }
679
+ this.send(s, update);
680
+ }
681
+
682
+ saveImage(s, block, index) {
683
+ const ext = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif', 'image/webp': 'webp' }[block.mimeType] || 'png';
684
+ const dir = path.join(s.sessionEnv.ZCODE_TMP, 'attachments');
685
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
686
+ const file = path.join(dir, `image-${Date.now()}-${++s.images}-${index}.${ext}`);
687
+ fs.writeFileSync(file, Buffer.from(block.data, 'base64'), { mode: 0o600 });
688
+ return file;
689
+ }
690
+
691
+ cancel(params) {
692
+ const s = this.sessions.get(params && params.sessionId);
693
+ if (s && s.abort) s.abort.abort();
694
+ }
695
+
696
+ dropEngine(s) {
697
+ if (s.client) s.client.kill();
698
+ s.client = null;
699
+ s.engine = null;
700
+ }
701
+
702
+ // Stops the running turn (or engine start), waits for it to unwind, then
703
+ // frees everything the session holds.
704
+ async closeSession(s, { reason = 'closed' } = {}) {
705
+ s.closed = true;
706
+ if (s.abort) s.abort.abort();
707
+ if (s.engine && s.client && !s.client.dead) await s.client.stopSession(s.engine.sessionId, { timeoutMs: 1500 });
708
+ if (!s.engine && s.client) this.dropEngine(s); // mid-start: the start fails fast
709
+ await Promise.allSettled([s.starting, s.running].filter(Boolean));
710
+ this.release(s, reason);
711
+ }
712
+
713
+ release(s, reason) {
714
+ s.closed = true;
715
+ this.dropEngine(s);
716
+ if (s.persisted) this.persist(s, { state: 'finished', phase: 'done', status: 'completed', closedReason: reason });
717
+ if (s.releasePort) s.releasePort();
718
+ if (s.releaseOwner) s.releaseOwner();
719
+ s.releasePort = null;
720
+ s.releaseOwner = null;
721
+ if (this.sessions.get(s.id) === s) this.sessions.delete(s.id);
722
+ }
723
+
724
+ // Process exit: synchronous, so it also runs from an 'exit' handler.
725
+ shutdownSync(reason) {
726
+ for (const s of [...this.sessions.values()]) {
727
+ if (s.abort) s.abort.abort();
728
+ this.release(s, reason);
729
+ }
730
+ }
731
+ }
732
+
733
+ // Runs the agent on this process's stdio until the client closes stdin.
734
+ function serve({ defaults, env = process.env, version, input = process.stdin, output = process.stdout } = {}) {
735
+ const logFile = env.ZCODE_ACP_LOG;
736
+ const log = logFile
737
+ ? (dir, line) => {
738
+ try {
739
+ fs.appendFileSync(logFile, `${new Date().toISOString()} ${dir} ${line}\n`, { mode: 0o600 });
740
+ } catch {
741
+ /* debug log only */
742
+ }
743
+ }
744
+ : null;
745
+ const peer = new Peer({ input, output, log });
746
+ const agent = new Agent({ peer, defaults, env, version });
747
+ let done = false;
748
+ const stop = (reason, code) => {
749
+ if (done) return;
750
+ done = true;
751
+ peer.failPending('client disconnected');
752
+ agent.shutdownSync(reason);
753
+ if (code !== null) process.exit(code);
754
+ };
755
+ peer.onClose = () => stop('client closed stdin', 0);
756
+ process.on('SIGTERM', () => stop('SIGTERM', 0));
757
+ process.on('SIGINT', () => stop('SIGINT', 0));
758
+ process.on('SIGHUP', () => stop('SIGHUP', 0));
759
+ process.on('exit', () => stop('exit', null));
760
+ return { peer, agent };
761
+ }
762
+
763
+ module.exports = { serve, Agent, Peer, AcpError, PROTOCOL_VERSION, ERR };