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-map.js ADDED
@@ -0,0 +1,543 @@
1
+ 'use strict';
2
+ // Pure translation between the engine's app-server frames and ACP
3
+ // (Agent Client Protocol v1) `session/update` payloads, prompts and config
4
+ // options. No I/O: lib/acp.js owns the processes and the wire.
5
+ //
6
+ // Engine facts used here (live-probed against engine 0.16.9, 1.1):
7
+ // - model.streaming {kind:text_delta|reasoning_delta, delta}
8
+ // - model.streaming {kind:tool_input_start, toolCallId, toolName} then
9
+ // {kind:tool_call, toolCallId, toolName, input} once the input is complete
10
+ // - tool.updated {kind:scheduled|started|result|error|batch, toolCallId,
11
+ // toolName?, result?:{success, content}}
12
+ // - session.titleUpdated {title}; state.updated {patch:{mode:{current}}}
13
+ // - session/messages: [{info:{role, semantics:{kind, uiVisibility}},
14
+ // parts:[{type:text|reasoning|tool, …}]}]
15
+ const path = require('node:path');
16
+ const { supportedEfforts, supportsImage } = require('./models.js');
17
+
18
+ // Engine permission modes offered as the ACP session mode. `auto` is
19
+ // reserved-but-unimplemented in the engine and `guarded` behaves like yolo
20
+ // for permissions, so neither is offered.
21
+ const MODES = [
22
+ { id: 'build', name: 'Ask', description: 'Ask before edits and commands' },
23
+ { id: 'edit', name: 'Accept edits', description: 'Edit files without asking; ask before commands' },
24
+ { id: 'plan', name: 'Plan', description: 'Read-only: research and plan, then ask to start' },
25
+ { id: 'yolo', name: 'Full access', description: 'Run every tool without asking' },
26
+ ];
27
+ const MODE_IDS = MODES.map((m) => m.id);
28
+
29
+ const MODELS = [
30
+ { value: 'GLM-5.3-Flash', name: 'GLM-5.3-Flash', description: 'Fast and cheap; sees images' },
31
+ { value: 'GLM-5.3', name: 'GLM-5.3', description: 'Larger model; text only' },
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 };
36
+
37
+ const MAX_TOOL_TEXT = 8000;
38
+
39
+ function modeState(mode) {
40
+ return { currentModeId: mode, availableModes: MODES };
41
+ }
42
+
43
+ // The session's config options (ACP v1 SessionConfigOption, select type):
44
+ // mode, model, and the reasoning effort the current model accepts.
45
+ function configOptions({ mode, model, effort }, opts = {}) {
46
+ return [
47
+ {
48
+ id: 'mode',
49
+ name: 'Mode',
50
+ category: 'mode',
51
+ type: 'select',
52
+ currentValue: mode,
53
+ options: MODES.map(({ id, name, description }) => ({ value: id, name, description })),
54
+ },
55
+ {
56
+ id: 'model',
57
+ name: 'Model',
58
+ category: 'model',
59
+ type: 'select',
60
+ currentValue: model,
61
+ options: MODELS,
62
+ },
63
+ {
64
+ id: 'effort',
65
+ name: 'Effort',
66
+ category: 'thought_level',
67
+ type: 'select',
68
+ currentValue: effort,
69
+ options: supportedEfforts(model, opts).map((level) => ({ value: level, name: level })),
70
+ },
71
+ ];
72
+ }
73
+
74
+ // The effort to keep after a model switch: the same level when the new
75
+ // model accepts it, else its highest.
76
+ function effortFor(model, effort, opts = {}) {
77
+ const levels = supportedEfforts(model, opts);
78
+ return levels.includes(effort) ? effort : levels[levels.length - 1];
79
+ }
80
+
81
+ // --- prompts --------------------------------------------------------------------
82
+
83
+ // ACP prompt content blocks → the engine's prompt text. Images are written
84
+ // 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 } = {}) {
87
+ const parts = [];
88
+ let images = 0;
89
+ for (const block of Array.isArray(blocks) ? blocks : []) {
90
+ if (!block || typeof block !== 'object') continue;
91
+ if (block.type === 'text' && typeof block.text === 'string') {
92
+ parts.push(block.text);
93
+ } else if (block.type === 'resource_link') {
94
+ parts.push(`Referenced: ${uriToPath(block.uri) || block.name || ''}`.trim());
95
+ } else if (block.type === 'resource' && block.resource) {
96
+ const r = block.resource;
97
+ const where = uriToPath(r.uri) || r.uri || 'attachment';
98
+ if (typeof r.text === 'string') parts.push(`<file path="${where}">\n${r.text}\n</file>`);
99
+ else parts.push(`Referenced: ${where}`);
100
+ } else if (block.type === 'image' && typeof block.data === 'string' && saveImage) {
101
+ 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
+ : ' (open it with the Read tool)';
105
+ parts.push(`Attached image: ${file}${note}`);
106
+ }
107
+ }
108
+ return parts.join('\n\n');
109
+ }
110
+
111
+ function uriToPath(uri) {
112
+ if (typeof uri !== 'string') return null;
113
+ if (uri.startsWith('file://')) {
114
+ try {
115
+ return decodeURIComponent(new URL(uri).pathname);
116
+ } catch {
117
+ return uri.slice('file://'.length);
118
+ }
119
+ }
120
+ return null;
121
+ }
122
+
123
+ // ACP mcpServers → the engine's --mcp spec ({name: def}).
124
+ function mcpSpec(servers) {
125
+ const spec = {};
126
+ for (const s of Array.isArray(servers) ? servers : []) {
127
+ if (!s || !s.name) continue;
128
+ const pairs = (list) => Object.fromEntries((Array.isArray(list) ? list : []).filter((p) => p && p.name).map((p) => [p.name, String(p.value ?? '')]));
129
+ if (s.type === 'http' || s.type === 'sse') {
130
+ spec[s.name] = { type: s.type, url: s.url, headers: pairs(s.headers) };
131
+ } else if (s.command) {
132
+ spec[s.name] = { type: 'stdio', command: s.command, args: Array.isArray(s.args) ? s.args : [], env: pairs(s.env) };
133
+ }
134
+ }
135
+ return spec;
136
+ }
137
+
138
+ // --- tools ----------------------------------------------------------------------
139
+
140
+ const HIDDEN_TOOLS = new Set(['TodoWrite', 'TodoRead']); // shown as the plan instead
141
+
142
+ function rel(file, cwd) {
143
+ if (typeof file !== 'string' || !file) return '';
144
+ if (!cwd || !path.isAbsolute(file)) return file;
145
+ const r = path.relative(cwd, file);
146
+ return r && !r.startsWith('..') && !path.isAbsolute(r) ? r : file;
147
+ }
148
+
149
+ function clip(text, max = 80) {
150
+ const s = String(text ?? '').replace(/\s+/g, ' ').trim();
151
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
152
+ }
153
+
154
+ // {title, kind, locations?, content?} for one engine tool call.
155
+ function toolInfo(name, input, cwd) {
156
+ const i = input && typeof input === 'object' ? input : {};
157
+ const file = typeof i.file_path === 'string' ? i.file_path : typeof i.path === 'string' ? i.path : null;
158
+ const at = file ? [{ path: file, ...(Number.isInteger(i.offset) ? { line: i.offset } : {}) }] : undefined;
159
+ switch (name) {
160
+ case 'Read':
161
+ return { title: file ? `Read ${rel(file, cwd)}` : 'Read', kind: 'read', locations: at };
162
+ case 'Write':
163
+ return {
164
+ title: file ? `Write ${rel(file, cwd)}` : 'Write',
165
+ kind: 'edit',
166
+ locations: at,
167
+ content: file && typeof i.content === 'string' ? [{ type: 'diff', path: file, oldText: null, newText: i.content }] : undefined,
168
+ };
169
+ case 'Edit':
170
+ return {
171
+ title: file ? `Edit ${rel(file, cwd)}` : 'Edit',
172
+ kind: 'edit',
173
+ locations: at,
174
+ content: file && typeof i.new_string === 'string'
175
+ ? [{ type: 'diff', path: file, oldText: typeof i.old_string === 'string' ? i.old_string : null, newText: i.new_string }]
176
+ : undefined,
177
+ };
178
+ case 'MultiEdit':
179
+ return {
180
+ title: file ? `Edit ${rel(file, cwd)}` : 'Edit',
181
+ kind: 'edit',
182
+ locations: at,
183
+ content: file && Array.isArray(i.edits)
184
+ ? i.edits.filter((e) => e && typeof e.new_string === 'string')
185
+ .map((e) => ({ type: 'diff', path: file, oldText: typeof e.old_string === 'string' ? e.old_string : null, newText: e.new_string }))
186
+ : undefined,
187
+ };
188
+ case 'NotebookEdit':
189
+ return { title: `Edit ${rel(i.notebook_path || file, cwd)}`, kind: 'edit', locations: i.notebook_path ? [{ path: i.notebook_path }] : at };
190
+ case 'Bash':
191
+ return { title: i.command ? clip(i.command, 120) : (i.description || 'Run command'), kind: 'execute' };
192
+ case 'Grep':
193
+ return { title: `Search ${clip(i.pattern, 60)}${file ? ` in ${rel(file, cwd)}` : ''}`, kind: 'search', locations: at };
194
+ case 'Glob':
195
+ return { title: `Find ${clip(i.pattern, 60)}`, kind: 'search', locations: at };
196
+ case 'LS':
197
+ return { title: `List ${rel(file, cwd) || '.'}`, kind: 'search', locations: at };
198
+ case 'WebFetch':
199
+ return { title: i.url ? `Fetch ${clip(i.url, 100)}` : 'Fetch', kind: 'fetch' };
200
+ case 'WebSearch':
201
+ return { title: i.query ? `Search the web: ${clip(i.query, 80)}` : 'Search the web', kind: 'fetch' };
202
+ case 'Agent':
203
+ case 'Task':
204
+ return { title: `Subagent: ${clip(i.description || i.prompt || i.subagent_type || 'task', 80)}`, kind: 'think' };
205
+ case 'Skill':
206
+ return { title: `Skill ${i.skill || i.name || ''}`.trim(), kind: 'other' };
207
+ case 'EnterPlanMode':
208
+ case 'ExitPlanMode':
209
+ return { title: name === 'ExitPlanMode' ? 'Ready to code' : 'Plan first', kind: 'switch_mode' };
210
+ default: {
211
+ const m = /^mcp__(.+?)__(.+)$/.exec(String(name || ''));
212
+ return { title: m ? `${m[1]}: ${m[2]}` : String(name || 'tool'), kind: 'other' };
213
+ }
214
+ }
215
+ }
216
+
217
+ function truncate(text, max = MAX_TOOL_TEXT) {
218
+ const s = String(text ?? '');
219
+ return s.length > max ? `${s.slice(0, max)}\n… (${s.length - max} more characters)` : s;
220
+ }
221
+
222
+ // A tool result's text and rawOutput (Bash output as {stdout}, which ACP
223
+ // clients render as command output).
224
+ function toolOutput(name, text) {
225
+ const out = truncate(text);
226
+ return {
227
+ content: out ? [{ type: 'content', content: { type: 'text', text: out } }] : undefined,
228
+ rawOutput: name === 'Bash' ? { stdout: out } : { output: out },
229
+ };
230
+ }
231
+
232
+ // TodoWrite input → an ACP plan update, or null.
233
+ function planUpdate(input) {
234
+ const todos = input && Array.isArray(input.todos) ? input.todos : null;
235
+ if (!todos) return null;
236
+ const status = (s) => (s === 'in_progress' || s === 'completed' ? s : s === 'cancelled' ? 'completed' : 'pending');
237
+ const priority = (p) => (p === 'high' || p === 'low' ? p : 'medium');
238
+ return {
239
+ sessionUpdate: 'plan',
240
+ entries: todos.filter((t) => t && t.content).map((t) => ({ content: String(t.content), priority: priority(t.priority), status: status(t.status) })),
241
+ };
242
+ }
243
+
244
+ // The engine titles a session from its first input, verbatim. Clients
245
+ // that wrap the user's words in markup (T3 Code: <t3_code_instructions>…
246
+ // <user_request>…</user_request>) would get the markup as the title: use
247
+ // the user's request instead.
248
+ function cleanTitle(title, prompt) {
249
+ if (!/^\s*</.test(title)) return title;
250
+ const text = String(prompt || '');
251
+ const request = /<user_request>([\s\S]*?)<\/user_request>/.exec(text);
252
+ const words = (request ? request[1] : text.replace(/<([a-z_]+)>[\s\S]*?<\/\1>/g, ' ').replace(/<[^>]+>/g, ' '))
253
+ .split('\n').map((l) => l.trim()).find(Boolean);
254
+ return words ? clip(words, 60) : title;
255
+ }
256
+
257
+ function compact(obj) {
258
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
259
+ }
260
+
261
+ // Stateful per-session translator for live turns. feed(frame) returns the
262
+ // ACP updates the frame produces (possibly none).
263
+ class TurnMapper {
264
+ constructor({ engineSessionId, cwd }) {
265
+ this.engineSessionId = engineSessionId;
266
+ this.cwd = cwd;
267
+ this.tools = new Map(); // toolCallId → {name, announced, hidden, done}
268
+ this.contextUsed = null;
269
+ this.title = null;
270
+ this.mode = null;
271
+ this.available = null; // the engine's latest model list (state.updated)
272
+ this.prompt = ''; // this turn's prompt text (titles)
273
+ }
274
+
275
+ ownFrame(params) {
276
+ return !params.sessionId || !this.engineSessionId || params.sessionId === this.engineSessionId;
277
+ }
278
+
279
+ feed(frame) {
280
+ const out = [];
281
+ const params = (frame && frame.params) || {};
282
+ if (frame.method === 'state.updated') {
283
+ const available = params.patch && params.patch.model && params.patch.model.available;
284
+ if (Array.isArray(available)) this.available = available;
285
+ const mode = params.patch && params.patch.mode && params.patch.mode.current;
286
+ if (mode && MODE_IDS.includes(mode) && mode !== this.mode) {
287
+ this.mode = mode;
288
+ out.push({ sessionUpdate: 'current_mode_update', currentModeId: mode });
289
+ }
290
+ return out;
291
+ }
292
+ if (frame.method !== 'session/event' || !this.ownFrame(params)) return out;
293
+ const type = params.type;
294
+ const p = params.payload || {};
295
+ if (type === 'model.streaming') {
296
+ if (p.kind === 'text_delta' && p.delta) {
297
+ out.push({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: p.delta } });
298
+ } else if (p.kind === 'reasoning_delta' && p.delta) {
299
+ out.push({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: p.delta } });
300
+ } else if (p.kind === 'tool_input_start' && p.toolCallId) {
301
+ out.push(...this.announce(p.toolCallId, p.toolName, undefined));
302
+ } else if (p.kind === 'tool_call' && p.toolCallId) {
303
+ out.push(...this.announce(p.toolCallId, p.toolName, p.input));
304
+ }
305
+ } else if (type === 'tool.updated' && p.toolCallId) {
306
+ out.push(...this.toolUpdate(p));
307
+ } else if (type === 'permission.resolved' && p.toolCallId && p.decision === 'deny') {
308
+ // A denied tool never runs: no result event follows, only this.
309
+ const t = this.tools.get(p.toolCallId);
310
+ if (t && !t.hidden && !t.done) {
311
+ t.done = true;
312
+ out.push({ sessionUpdate: 'tool_call_update', toolCallId: p.toolCallId, status: 'failed', ...compact(toolOutput(t.name, p.reason ? `Denied: ${p.reason}` : 'Denied')) });
313
+ }
314
+ } else if (type === 'session.titleUpdated' && p.title) {
315
+ this.title = cleanTitle(String(p.title), this.prompt);
316
+ const at = Number.isFinite(params.timestamp) ? params.timestamp : Date.now();
317
+ out.push({ sessionUpdate: 'session_info_update', title: this.title, updatedAt: new Date(at).toISOString() });
318
+ } else if (type === 'session.updated' && p.type === 'model_request_completed' && p.usage
319
+ && (!p.modelRequestSessionType || p.modelRequestSessionType === 'main')) {
320
+ this.contextUsed = (p.usage.inputTokens || 0) + (p.usage.outputTokens || 0);
321
+ }
322
+ return out;
323
+ }
324
+
325
+ announce(id, name, input) {
326
+ let t = this.tools.get(id);
327
+ const toolName = name || (t && t.name) || 'tool';
328
+ if (!t) {
329
+ t = { name: toolName, announced: false, hidden: HIDDEN_TOOLS.has(toolName), done: false };
330
+ this.tools.set(id, t);
331
+ }
332
+ if (t.hidden) {
333
+ const plan = input !== undefined && toolName === 'TodoWrite' ? planUpdate(input) : null;
334
+ return plan ? [plan] : [];
335
+ }
336
+ const info = toolInfo(toolName, input, this.cwd);
337
+ const fields = compact({
338
+ title: info.title,
339
+ kind: info.kind,
340
+ locations: info.locations,
341
+ content: info.content,
342
+ rawInput: input,
343
+ });
344
+ if (!t.announced) {
345
+ t.announced = true;
346
+ return [{ sessionUpdate: 'tool_call', toolCallId: id, status: 'pending', ...fields }];
347
+ }
348
+ return input === undefined ? [] : [{ sessionUpdate: 'tool_call_update', toolCallId: id, ...fields }];
349
+ }
350
+
351
+ toolUpdate(p) {
352
+ const id = p.toolCallId;
353
+ let t = this.tools.get(id);
354
+ const out = [];
355
+ if (!t) {
356
+ if (!p.toolName) return out;
357
+ out.push(...this.announce(id, p.toolName, undefined));
358
+ t = this.tools.get(id);
359
+ }
360
+ if (t.hidden || t.done) return out;
361
+ if (p.kind === 'started') {
362
+ out.push({ sessionUpdate: 'tool_call_update', toolCallId: id, status: 'in_progress' });
363
+ } else if (p.kind === 'result') {
364
+ t.done = true;
365
+ const r = p.result || {};
366
+ 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))) });
368
+ } else if (p.kind === 'error') {
369
+ t.done = true;
370
+ const e = p.error || p.result || {};
371
+ const message = typeof e === 'string' ? e : e.message || e.content || JSON.stringify(e);
372
+ out.push({ sessionUpdate: 'tool_call_update', toolCallId: id, status: 'failed', ...compact(toolOutput(t.name, message)) });
373
+ }
374
+ return out;
375
+ }
376
+
377
+ // Updates that close every tool call still open (turn ended or cancelled).
378
+ closeOpen(status = 'failed') {
379
+ const out = [];
380
+ for (const [id, t] of this.tools) {
381
+ if (t.hidden || t.done || !t.announced) continue;
382
+ t.done = true;
383
+ out.push({ sessionUpdate: 'tool_call_update', toolCallId: id, status });
384
+ }
385
+ return out;
386
+ }
387
+ }
388
+
389
+ // --- history (session/load) -----------------------------------------------------
390
+
391
+ // session/messages → the ACP updates that replay the visible conversation.
392
+ function historyUpdates(messages, { cwd } = {}) {
393
+ const out = [];
394
+ let plan = null;
395
+ for (const m of Array.isArray(messages) ? messages : []) {
396
+ const info = (m && m.info) || {};
397
+ const sem = info.semantics || {};
398
+ if (sem.uiVisibility && sem.uiVisibility !== 'visible') continue;
399
+ const parts = Array.isArray(m.parts) ? m.parts : [];
400
+ if (info.role === 'user') {
401
+ if (sem.kind && sem.kind !== 'user_prompt') continue;
402
+ for (const part of parts) {
403
+ if (part && part.type === 'text' && part.text) out.push({ sessionUpdate: 'user_message_chunk', content: { type: 'text', text: part.text } });
404
+ }
405
+ continue;
406
+ }
407
+ if (info.role !== 'assistant' || (sem.kind && sem.kind !== 'assistant_response')) continue;
408
+ for (const part of parts) {
409
+ if (!part) continue;
410
+ if (part.type === 'text' && part.text) {
411
+ out.push({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: part.text } });
412
+ } else if (part.type === 'reasoning' && part.text) {
413
+ out.push({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: part.text } });
414
+ } else if (part.type === 'tool' && part.callID) {
415
+ const state = part.state || {};
416
+ if (HIDDEN_TOOLS.has(part.tool)) {
417
+ if (part.tool === 'TodoWrite') plan = planUpdate(state.input) || plan;
418
+ continue;
419
+ }
420
+ const info2 = toolInfo(part.tool, state.input, cwd);
421
+ const failed = state.status === 'error' || state.status === 'failed';
422
+ const output = typeof state.output === 'string' ? state.output : typeof state.error === 'string' ? state.error : '';
423
+ const result = toolOutput(part.tool, output);
424
+ out.push(compact({
425
+ sessionUpdate: 'tool_call',
426
+ toolCallId: part.callID,
427
+ title: info2.title,
428
+ kind: info2.kind,
429
+ status: failed ? 'failed' : 'completed',
430
+ locations: info2.locations,
431
+ content: [...(info2.content || []), ...(result.content || [])],
432
+ rawInput: state.input,
433
+ rawOutput: result.rawOutput,
434
+ }));
435
+ }
436
+ }
437
+ }
438
+ if (plan) out.push(plan);
439
+ return out;
440
+ }
441
+
442
+ // --- permissions ----------------------------------------------------------------
443
+
444
+ const OPTION_KINDS = { allow_once: 'allow_once', allow_always: 'allow_always', allow_session: 'allow_always', deny: 'reject_once', reject_once: 'reject_once', reject_always: 'reject_always' };
445
+
446
+ // The engine's interaction/requestPermission params → ACP
447
+ // session/request_permission params (minus sessionId) and a lookup from
448
+ // the client's chosen optionId to the engine's reply.
449
+ function permissionRequest(params, { cwd } = {}) {
450
+ const engineOptions = Array.isArray(params.options) ? params.options.filter((o) => o && o.optionId) : [];
451
+ const options = [];
452
+ const replies = new Map();
453
+ for (const o of engineOptions) {
454
+ // An option of unknown kind is never shown as an allow button.
455
+ const kind = OPTION_KINDS[o.kind] || (/^allow/.test(String(o.kind || '')) ? 'allow_once' : 'reject_once');
456
+ options.push({ optionId: o.optionId, name: o.name || o.optionId, kind });
457
+ replies.set(o.optionId, o.response || (kind.startsWith('reject') ? { decision: 'deny', reason: 'Denied by the user' } : { decision: 'allow', reason: 'Approved by the user' }));
458
+ }
459
+ // Every client can answer: the three basic kinds are always offered.
460
+ if (!options.some((o) => o.kind === 'allow_once')) {
461
+ options.unshift({ optionId: 'allow_once', name: 'Allow once', kind: 'allow_once' });
462
+ replies.set('allow_once', { decision: 'allow', reason: 'Approved once' });
463
+ }
464
+ if (!options.some((o) => o.kind === 'reject_once')) {
465
+ options.push({ optionId: 'deny', name: 'Deny', kind: 'reject_once' });
466
+ replies.set('deny', { decision: 'deny', reason: 'Denied by the user' });
467
+ }
468
+ const info = toolInfo(params.toolName, params.input, cwd);
469
+ const toolCall = compact({
470
+ toolCallId: params.toolCallId || params.requestId,
471
+ title: info.title,
472
+ kind: info.kind,
473
+ status: 'pending',
474
+ locations: info.locations,
475
+ content: info.content,
476
+ rawInput: params.input,
477
+ });
478
+ return {
479
+ request: { toolCall, options },
480
+ reply: (outcome) => {
481
+ if (outcome && outcome.outcome === 'selected' && replies.has(outcome.optionId)) return replies.get(outcome.optionId);
482
+ return { decision: 'deny', reason: 'The user cancelled this tool call. Stop and wait for their next message.' };
483
+ },
484
+ };
485
+ }
486
+
487
+ // The engine's ExitPlanMode approval (interaction/requestUserInput with
488
+ // schema.interaction "plan_approval") as an ACP permission request.
489
+ function planApprovalRequest(params) {
490
+ const plan = params.input && typeof params.input.plan === 'string' ? params.input.plan : '';
491
+ return {
492
+ request: {
493
+ toolCall: compact({
494
+ toolCallId: params.toolCallId || params.requestId,
495
+ title: 'Ready to code?',
496
+ kind: 'switch_mode',
497
+ status: 'pending',
498
+ content: plan ? [{ type: 'content', content: { type: 'text', text: plan } }] : undefined,
499
+ rawInput: params.input,
500
+ }),
501
+ options: [
502
+ { optionId: 'approve', name: 'Yes, start', kind: 'allow_once' },
503
+ { optionId: 'keep-planning', name: 'No, keep planning', kind: 'reject_once' },
504
+ ],
505
+ },
506
+ reply: (outcome) => (outcome && outcome.outcome === 'selected' && outcome.optionId === 'approve'
507
+ ? { action: 'accept', content: { answer: 'approve' } }
508
+ : { action: 'decline', reason: 'The user wants to keep planning.' }),
509
+ };
510
+ }
511
+
512
+ // The model's context window: the engine's latest state.updated model list,
513
+ // else the session projection when it is for this model, else the table.
514
+ // (live-probed 0.16.9: session/create's own settings list says 1M for
515
+ // GLM-5.3-Flash while its projection and later state updates say 200k.)
516
+ function contextWindow(model, { available = null, created = null } = {}) {
517
+ const hit = Array.isArray(available) && available.find((a) => a && a.ref && a.ref.modelId === model);
518
+ if (hit && hit.contextWindow) return hit.contextWindow;
519
+ const projection = created && created.projection;
520
+ const createdModel = created && created.session && created.session.model && created.session.model.modelId;
521
+ if (projection && projection.contextWindow && createdModel === model) return projection.contextWindow;
522
+ return CONTEXT_WINDOWS[model] || 200000;
523
+ }
524
+
525
+ module.exports = {
526
+ MODES,
527
+ MODE_IDS,
528
+ MODELS,
529
+ modeState,
530
+ configOptions,
531
+ effortFor,
532
+ promptText,
533
+ mcpSpec,
534
+ toolInfo,
535
+ planUpdate,
536
+ TurnMapper,
537
+ historyUpdates,
538
+ permissionRequest,
539
+ planApprovalRequest,
540
+ contextWindow,
541
+ uriToPath,
542
+ cleanTitle,
543
+ };