@mistriwork/acp 0.0.0-stage → 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.
package/dist/client.js ADDED
@@ -0,0 +1,680 @@
1
+ /**
2
+ * First-class Agent Client Protocol (ACP) v1 client / host runtime.
3
+ *
4
+ * Manages an ACP-compliant coding agent subprocess (or in-memory stream pair)
5
+ * over NDJSON JSON-RPC 2.0, delegates client-side `fs/*` and `terminal/*`
6
+ * callbacks to Mistri's `SandboxAdapter`, routes `session/request_permission`
7
+ * through Mistri's `PermissionBroker`, and folds `session/update` notifications
8
+ * into Mistri's normalized `AgentEvent` stream.
9
+ */
10
+ import { randomUUID } from 'node:crypto';
11
+ import { createJsonRpcPeer, JSON_RPC_ERRORS, JsonRpcError } from '@mistriwork/engine/server/jsonrpc.js';
12
+ import { isPermissionAllowed, } from '@mistriwork/mistri/agents';
13
+ import { killProcessTree, spawnManagedSubprocess } from './env.js';
14
+ import { ACP_PROTOCOL_VERSION, } from './types.js';
15
+ const DEFAULT_CLIENT_INFO = Object.freeze({ name: 'mistri-acp', version: '1.3.0', title: 'Mistri ACP Host' });
16
+ const DEFAULT_PRINCIPAL = Object.freeze({ accountId: 'system', roles: [] });
17
+ const DEFAULT_CONTROL_TIMEOUT_MS = 30_000;
18
+ function shellQuote(arg) {
19
+ if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(arg))
20
+ return arg;
21
+ return `'${arg.replace(/'/g, `'\\''`)}'`;
22
+ }
23
+ function validateFsPath(raw) {
24
+ const path = typeof raw === 'string' ? raw : '';
25
+ if (!path.trim() || path.includes('\0')) {
26
+ throw new JsonRpcError(JSON_RPC_ERRORS.INVALID_PARAMS, 'Invalid file path.');
27
+ }
28
+ return path;
29
+ }
30
+ function truncateUtf8Tail(text, maxBytes) {
31
+ const buf = Buffer.from(text, 'utf8');
32
+ if (buf.length <= maxBytes)
33
+ return { text, truncated: false };
34
+ return { text: buf.subarray(buf.length - maxBytes).toString('utf8'), truncated: true };
35
+ }
36
+ function mapAcpKindToPermissionKind(kind) {
37
+ switch (kind) {
38
+ case 'read':
39
+ case 'search':
40
+ return 'read';
41
+ case 'edit':
42
+ case 'move':
43
+ return 'edit';
44
+ case 'delete':
45
+ return 'delete';
46
+ case 'execute':
47
+ return 'execute';
48
+ case 'fetch':
49
+ return 'fetch';
50
+ default:
51
+ return 'tool';
52
+ }
53
+ }
54
+ function pickPermissionOption(options, outcome) {
55
+ const exact = options.find((o) => o.kind === outcome);
56
+ if (exact)
57
+ return exact;
58
+ if (outcome === 'allow_always')
59
+ return options.find((o) => o.kind === 'allow_once');
60
+ if (outcome === 'allow_once')
61
+ return options.find((o) => o.kind === 'allow_always');
62
+ if (outcome === 'reject_always')
63
+ return options.find((o) => o.kind === 'reject_once');
64
+ if (outcome === 'reject_once')
65
+ return options.find((o) => o.kind === 'reject_always');
66
+ return undefined;
67
+ }
68
+ function extractDiffs(content) {
69
+ if (!Array.isArray(content))
70
+ return [];
71
+ const diffs = [];
72
+ for (const item of content) {
73
+ if (!item || typeof item !== 'object' || Array.isArray(item))
74
+ continue;
75
+ const part = item;
76
+ if (part.type === 'diff' && typeof part.path === 'string' && typeof part.newText === 'string') {
77
+ diffs.push({
78
+ path: part.path,
79
+ ...(typeof part.oldText === 'string' ? { oldText: part.oldText } : {}),
80
+ newText: part.newText,
81
+ });
82
+ }
83
+ }
84
+ return diffs;
85
+ }
86
+ function extractTextChunk(update) {
87
+ const content = update.content;
88
+ if (content && typeof content === 'object' && !Array.isArray(content)) {
89
+ const text = content.text;
90
+ if (typeof text === 'string')
91
+ return text;
92
+ }
93
+ if (typeof update.text === 'string')
94
+ return update.text;
95
+ return '';
96
+ }
97
+ function parseConfigOptions(raw) {
98
+ if (!Array.isArray(raw))
99
+ return [];
100
+ const out = [];
101
+ for (const item of raw) {
102
+ if (!item || typeof item !== 'object' || Array.isArray(item))
103
+ continue;
104
+ const c = item;
105
+ if (typeof c.id !== 'string' || typeof c.name !== 'string')
106
+ continue;
107
+ const opts = Array.isArray(c.options)
108
+ ? c.options
109
+ .filter((o) => Boolean(o && typeof o === 'object' && typeof o.value === 'string'))
110
+ .map((o) => ({
111
+ value: o.value,
112
+ name: typeof o.name === 'string' ? o.name : o.value,
113
+ ...(typeof o.description === 'string' ? { description: o.description } : {}),
114
+ }))
115
+ : [];
116
+ out.push({
117
+ id: c.id,
118
+ name: c.name,
119
+ ...(typeof c.description === 'string' ? { description: c.description } : {}),
120
+ ...(typeof c.category === 'string' ? { category: c.category } : {}),
121
+ currentValue: typeof c.currentValue === 'string' ? c.currentValue : '',
122
+ options: opts,
123
+ });
124
+ }
125
+ return out;
126
+ }
127
+ /**
128
+ * Create an ACP v1 client connected to either a spawned coding-agent subprocess
129
+ * or an in-memory stream pair.
130
+ */
131
+ export function createAcpClient(options) {
132
+ if (!options.command && !options.streams) {
133
+ throw new Error('createAcpClient requires either `command` or `streams`.');
134
+ }
135
+ const child = options.command
136
+ ? spawnManagedSubprocess({
137
+ command: options.command,
138
+ args: options.args,
139
+ cwd: options.cwd,
140
+ extraEnv: options.extraEnv,
141
+ passThroughEnv: options.passThroughEnv,
142
+ })
143
+ : undefined;
144
+ if (child?.stderr && options.onStderr) {
145
+ child.stderr.setEncoding('utf8');
146
+ child.stderr.on('data', (chunk) => options.onStderr(chunk));
147
+ }
148
+ const input = options.streams ? options.streams.input : child.stdout;
149
+ const output = options.streams ? options.streams.output : child.stdin;
150
+ const principal = options.principal ?? DEFAULT_PRINCIPAL;
151
+ const controlTimeoutMs = options.controlTimeoutMs ?? DEFAULT_CONTROL_TIMEOUT_MS;
152
+ const canReadFs = Boolean(options.fs?.readTextFile || options.sandbox?.readFile);
153
+ const canWriteFs = Boolean(options.fs?.writeTextFile || options.sandbox?.writeFile);
154
+ const canTerminal = options.enableTerminal ?? Boolean(options.sandbox?.exec);
155
+ const activeTurns = new Map();
156
+ const terminals = new Map();
157
+ const sessionWriteAlways = new Set();
158
+ let initialized;
159
+ const emitBoth = (turn, event) => {
160
+ turn?.emit?.(event);
161
+ options.onEvent?.(event);
162
+ };
163
+ const handleSessionUpdate = (sessionId, update) => {
164
+ options.onSessionUpdate?.(sessionId, update);
165
+ const turn = activeTurns.get(sessionId);
166
+ const kind = String(update.sessionUpdate ?? '');
167
+ if (kind === 'agent_message_chunk') {
168
+ const delta = extractTextChunk(update);
169
+ if (delta) {
170
+ turn?.textChunks.push(delta);
171
+ emitBoth(turn, { event: 'text', data: { sessionId, delta } });
172
+ }
173
+ return;
174
+ }
175
+ if (kind === 'agent_thought_chunk') {
176
+ const delta = extractTextChunk(update);
177
+ if (delta) {
178
+ turn?.thoughtChunks.push(delta);
179
+ emitBoth(turn, { event: 'reasoning', data: { sessionId, delta } });
180
+ }
181
+ return;
182
+ }
183
+ if (kind === 'tool_call' || kind === 'tool_call_update') {
184
+ const toolCallId = typeof update.toolCallId === 'string' ? update.toolCallId : `tc_${randomUUID()}`;
185
+ const existing = turn?.toolCalls.get(toolCallId);
186
+ const status = update.status === 'pending' || update.status === 'in_progress' || update.status === 'completed' || update.status === 'failed'
187
+ ? update.status
188
+ : (existing?.status ?? (kind === 'tool_call' ? 'pending' : 'in_progress'));
189
+ const title = typeof update.title === 'string' ? update.title : (existing?.title ?? toolCallId);
190
+ const toolKind = typeof update.kind === 'string' ? update.kind : existing?.kind;
191
+ const rawInput = update.rawInput && typeof update.rawInput === 'object' && !Array.isArray(update.rawInput)
192
+ ? update.rawInput
193
+ : existing?.rawInput;
194
+ const rawOutput = 'rawOutput' in update ? update.rawOutput : existing?.rawOutput;
195
+ const newDiffs = extractDiffs(update.content);
196
+ const allDiffs = newDiffs.length ? [...(existing?.diffs ?? []), ...newDiffs] : existing?.diffs;
197
+ const record = {
198
+ toolCallId,
199
+ title,
200
+ ...(toolKind ? { kind: toolKind } : {}),
201
+ status,
202
+ ...(rawInput ? { rawInput } : {}),
203
+ ...(rawOutput !== undefined ? { rawOutput } : {}),
204
+ ...(allDiffs?.length ? { diffs: allDiffs } : {}),
205
+ };
206
+ turn?.toolCalls.set(toolCallId, record);
207
+ if (kind === 'tool_call' && !existing) {
208
+ emitBoth(turn, {
209
+ event: 'tool_call',
210
+ data: {
211
+ sessionId,
212
+ id: toolCallId,
213
+ name: title,
214
+ title,
215
+ kind: toolKind ?? 'tool',
216
+ input: rawInput ?? {},
217
+ status,
218
+ },
219
+ });
220
+ }
221
+ else {
222
+ emitBoth(turn, {
223
+ event: 'tool_call_update',
224
+ data: {
225
+ sessionId,
226
+ id: toolCallId,
227
+ title,
228
+ status,
229
+ ...(rawOutput !== undefined ? { output: rawOutput } : {}),
230
+ ...(newDiffs.length ? { diffs: newDiffs } : {}),
231
+ },
232
+ });
233
+ }
234
+ for (const diff of newDiffs) {
235
+ turn?.diffs.push(diff);
236
+ emitBoth(turn, { event: 'diff', data: { sessionId, toolCallId, title, ...diff } });
237
+ }
238
+ return;
239
+ }
240
+ if (kind === 'plan' && Array.isArray(update.entries)) {
241
+ const entries = [];
242
+ for (const raw of update.entries) {
243
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
244
+ continue;
245
+ const e = raw;
246
+ if (typeof e.content !== 'string')
247
+ continue;
248
+ const st = e.status === 'pending' || e.status === 'in_progress' || e.status === 'completed' ? e.status : 'pending';
249
+ const prio = e.priority === 'low' || e.priority === 'medium' || e.priority === 'high' ? e.priority : undefined;
250
+ entries.push({ content: e.content, status: st, ...(prio ? { priority: prio } : {}) });
251
+ }
252
+ if (turn)
253
+ turn.plan = entries;
254
+ emitBoth(turn, { event: 'plan', data: { sessionId, entries } });
255
+ return;
256
+ }
257
+ if (kind === 'current_mode_update' && typeof update.currentModeId === 'string') {
258
+ emitBoth(turn, { event: 'mode_changed', data: { sessionId, mode: update.currentModeId } });
259
+ }
260
+ };
261
+ const handleInboundRequest = async (method, params) => {
262
+ switch (method) {
263
+ case 'session/request_permission': {
264
+ const req = params;
265
+ const sessionId = typeof req.sessionId === 'string' ? req.sessionId : '';
266
+ const turn = activeTurns.get(sessionId);
267
+ const toolCall = req.toolCall ?? { toolCallId: `tc_${randomUUID()}` };
268
+ const opts = Array.isArray(req.options) ? req.options : [];
269
+ const permKind = mapAcpKindToPermissionKind(toolCall.kind);
270
+ const diffs = extractDiffs(toolCall.content);
271
+ const title = toolCall.title ?? toolCall.toolCallId;
272
+ if (!options.permissions) {
273
+ // Safe default when no broker is supplied: never silently allow writes; deny non-reads.
274
+ const isRead = permKind === 'read';
275
+ const picked = pickPermissionOption(opts, isRead ? 'allow_once' : 'reject_once');
276
+ return picked ? { outcome: { outcome: 'selected', optionId: picked.optionId } } : { outcome: { outcome: 'cancelled' } };
277
+ }
278
+ const permInput = {
279
+ id: `acp_perm_${toolCall.toolCallId}_${randomUUID().slice(0, 8)}`,
280
+ sessionId,
281
+ principal,
282
+ toolName: title,
283
+ title,
284
+ kind: permKind,
285
+ input: toolCall.rawInput ?? {},
286
+ readOnly: permKind === 'read',
287
+ destructive: permKind === 'delete',
288
+ ...(diffs[0] ? { diff: diffs[0].newText } : {}),
289
+ scopeKey: `acp:${toolCall.kind ?? 'tool'}:${title}`,
290
+ };
291
+ emitBoth(turn, { event: 'permission_request', data: { sessionId, request: permInput, options: opts } });
292
+ const decision = await options.permissions.authorize(permInput);
293
+ emitBoth(turn, { event: 'permission_resolved', data: { sessionId, requestId: permInput.id, decision } });
294
+ if (isPermissionAllowed(decision)) {
295
+ const targetPath = typeof toolCall.rawInput?.path === 'string' ? toolCall.rawInput.path : undefined;
296
+ if (targetPath)
297
+ turn?.approvedWritePaths.add(targetPath);
298
+ if (decision.outcome === 'allow_always' && (permKind === 'edit' || targetPath)) {
299
+ sessionWriteAlways.add(sessionId);
300
+ }
301
+ }
302
+ const picked = pickPermissionOption(opts, decision.outcome);
303
+ if (!picked) {
304
+ return { outcome: { outcome: 'cancelled' } };
305
+ }
306
+ return {
307
+ outcome: {
308
+ outcome: 'selected',
309
+ optionId: picked.optionId,
310
+ },
311
+ };
312
+ }
313
+ case 'fs/read_text_file': {
314
+ if (!canReadFs)
315
+ throw new JsonRpcError(JSON_RPC_ERRORS.METHOD_NOT_FOUND, 'fs/read_text_file is disabled.');
316
+ const sessionId = String(params.sessionId ?? '');
317
+ const filePath = validateFsPath(params.path);
318
+ const line = typeof params.line === 'number' ? params.line : undefined;
319
+ const limit = typeof params.limit === 'number' ? params.limit : undefined;
320
+ if (options.fs?.readTextFile) {
321
+ return options.fs.readTextFile({ sessionId, path: filePath, line, limit });
322
+ }
323
+ const full = await options.sandbox.readFile(filePath);
324
+ if (line === undefined && limit === undefined)
325
+ return { content: full };
326
+ const allLines = full.split('\n');
327
+ const start = Math.max(0, (line ?? 1) - 1);
328
+ const sliced = limit !== undefined ? allLines.slice(start, start + Math.max(0, limit)) : allLines.slice(start);
329
+ return { content: sliced.join('\n') };
330
+ }
331
+ case 'fs/write_text_file': {
332
+ if (!canWriteFs)
333
+ throw new JsonRpcError(JSON_RPC_ERRORS.METHOD_NOT_FOUND, 'fs/write_text_file is disabled.');
334
+ const sessionId = String(params.sessionId ?? '');
335
+ const filePath = validateFsPath(params.path);
336
+ const content = String(params.content ?? '');
337
+ const turn = activeTurns.get(sessionId);
338
+ let oldText;
339
+ if (canReadFs) {
340
+ try {
341
+ oldText = options.fs?.readTextFile
342
+ ? (await options.fs.readTextFile({ sessionId, path: filePath })).content
343
+ : await options.sandbox.readFile(filePath);
344
+ }
345
+ catch {
346
+ // New file or unreadable before write.
347
+ }
348
+ }
349
+ const alreadyApprovedInTurn = options.permissions &&
350
+ options.permissions.getMode() !== 'plan' &&
351
+ (turn?.approvedWritePaths.has(filePath) || sessionWriteAlways.has(sessionId));
352
+ if (options.permissions && !alreadyApprovedInTurn) {
353
+ const permInput = {
354
+ id: `acp_fs_${randomUUID().slice(0, 8)}`,
355
+ sessionId,
356
+ principal,
357
+ toolName: 'fs/write_text_file',
358
+ title: `Write ${filePath}`,
359
+ kind: 'edit',
360
+ input: { path: filePath, bytes: Buffer.byteLength(content, 'utf8') },
361
+ diff: content,
362
+ scopeKey: 'acp:fs:write_text_file',
363
+ };
364
+ emitBoth(turn, { event: 'permission_request', data: { sessionId, request: permInput } });
365
+ const decision = await options.permissions.authorize(permInput);
366
+ emitBoth(turn, { event: 'permission_resolved', data: { sessionId, requestId: permInput.id, decision } });
367
+ if (!isPermissionAllowed(decision)) {
368
+ throw new JsonRpcError(JSON_RPC_ERRORS.REQUEST_CANCELLED, decision.reason ?? 'Write denied by permission policy.');
369
+ }
370
+ }
371
+ if (options.fs?.writeTextFile) {
372
+ await options.fs.writeTextFile({ sessionId, path: filePath, content });
373
+ }
374
+ else {
375
+ await options.sandbox.writeFile(filePath, content);
376
+ }
377
+ const diffEntry = { path: filePath, ...(oldText !== undefined ? { oldText } : {}), newText: content };
378
+ turn?.diffs.push(diffEntry);
379
+ emitBoth(turn, { event: 'diff', data: { sessionId, title: `Write ${filePath}`, ...diffEntry } });
380
+ return {};
381
+ }
382
+ case 'terminal/create': {
383
+ if (!canTerminal || !options.sandbox) {
384
+ throw new JsonRpcError(JSON_RPC_ERRORS.METHOD_NOT_FOUND, 'terminal/create is disabled.');
385
+ }
386
+ const sessionId = String(params.sessionId ?? '');
387
+ const turn = activeTurns.get(sessionId);
388
+ const cmd = String(params.command ?? '').trim();
389
+ if (!cmd)
390
+ throw new JsonRpcError(JSON_RPC_ERRORS.INVALID_PARAMS, 'terminal/create requires a command.');
391
+ const cmdArgs = Array.isArray(params.args) ? params.args.map(String) : [];
392
+ const fullCmd = cmdArgs.length ? `${cmd} ${cmdArgs.map(shellQuote).join(' ')}` : cmd;
393
+ const cwd = typeof params.cwd === 'string' ? params.cwd : undefined;
394
+ const outputByteLimit = typeof params.outputByteLimit === 'number' && params.outputByteLimit > 0 ? Math.floor(params.outputByteLimit) : undefined;
395
+ if (options.permissions) {
396
+ const permInput = {
397
+ id: `acp_term_${randomUUID().slice(0, 8)}`,
398
+ sessionId,
399
+ principal,
400
+ toolName: 'terminal/create',
401
+ title: `Run ${fullCmd}`,
402
+ kind: 'execute',
403
+ input: { command: cmd, args: cmdArgs, ...(cwd ? { cwd } : {}) },
404
+ scopeKey: 'acp:terminal:create',
405
+ };
406
+ emitBoth(turn, { event: 'permission_request', data: { sessionId, request: permInput } });
407
+ const decision = await options.permissions.authorize(permInput);
408
+ emitBoth(turn, { event: 'permission_resolved', data: { sessionId, requestId: permInput.id, decision } });
409
+ if (!isPermissionAllowed(decision)) {
410
+ throw new JsonRpcError(JSON_RPC_ERRORS.REQUEST_CANCELLED, decision.reason ?? 'Command execution denied.');
411
+ }
412
+ }
413
+ const terminalId = `term_${randomUUID().slice(0, 12)}`;
414
+ const controller = new AbortController();
415
+ const applyLimit = (raw) => outputByteLimit !== undefined ? truncateUtf8Tail(raw, outputByteLimit) : { text: raw, truncated: false };
416
+ const entry = {
417
+ id: terminalId,
418
+ output: '',
419
+ truncated: false,
420
+ ...(outputByteLimit !== undefined ? { outputByteLimit } : {}),
421
+ controller,
422
+ done: options.sandbox
423
+ .exec(fullCmd, { ...(cwd ? { cwd } : {}), signal: controller.signal })
424
+ .then((res) => {
425
+ const combined = [res.stdout, res.stderr].filter(Boolean).join(res.stdout && res.stderr ? '\n' : '');
426
+ const bounded = applyLimit(combined);
427
+ entry.output = bounded.text;
428
+ entry.truncated = bounded.truncated;
429
+ entry.exitCode = res.exitCode;
430
+ return { exitCode: res.exitCode, output: bounded.text };
431
+ })
432
+ .catch((err) => {
433
+ const bounded = applyLimit(err instanceof Error ? err.message : String(err));
434
+ entry.output = bounded.text;
435
+ entry.truncated = bounded.truncated;
436
+ entry.exitCode = 1;
437
+ return { exitCode: 1, output: bounded.text };
438
+ }),
439
+ };
440
+ terminals.set(terminalId, entry);
441
+ return { terminalId };
442
+ }
443
+ case 'terminal/output': {
444
+ const term = terminals.get(String(params.terminalId ?? ''));
445
+ if (!term)
446
+ throw new JsonRpcError(JSON_RPC_ERRORS.RESOURCE_NOT_FOUND, 'Unknown terminalId.');
447
+ return {
448
+ output: term.output,
449
+ truncated: term.truncated,
450
+ ...(term.exitCode !== undefined ? { exitStatus: { exitCode: term.exitCode } } : {}),
451
+ };
452
+ }
453
+ case 'terminal/wait_for_exit': {
454
+ const term = terminals.get(String(params.terminalId ?? ''));
455
+ if (!term)
456
+ throw new JsonRpcError(JSON_RPC_ERRORS.RESOURCE_NOT_FOUND, 'Unknown terminalId.');
457
+ const res = await term.done;
458
+ return { exitCode: res.exitCode };
459
+ }
460
+ case 'terminal/kill': {
461
+ const term = terminals.get(String(params.terminalId ?? ''));
462
+ if (!term)
463
+ throw new JsonRpcError(JSON_RPC_ERRORS.RESOURCE_NOT_FOUND, 'Unknown terminalId.');
464
+ term.controller.abort();
465
+ return {};
466
+ }
467
+ case 'terminal/release': {
468
+ const id = String(params.terminalId ?? '');
469
+ const term = terminals.get(id);
470
+ if (term) {
471
+ term.controller.abort();
472
+ terminals.delete(id);
473
+ }
474
+ return {};
475
+ }
476
+ default:
477
+ throw new JsonRpcError(JSON_RPC_ERRORS.METHOD_NOT_FOUND, `Unsupported client method: ${method}`);
478
+ }
479
+ };
480
+ const peer = createJsonRpcPeer({
481
+ input,
482
+ output,
483
+ onRequest: handleInboundRequest,
484
+ onNotification: (method, params) => {
485
+ if (method === 'session/update') {
486
+ const sessionId = typeof params.sessionId === 'string' ? params.sessionId : '';
487
+ const update = params.update && typeof params.update === 'object' && !Array.isArray(params.update)
488
+ ? params.update
489
+ : {};
490
+ handleSessionUpdate(sessionId, update);
491
+ }
492
+ },
493
+ });
494
+ const clientCapabilities = {
495
+ fs: { readTextFile: canReadFs, writeTextFile: canWriteFs },
496
+ terminal: canTerminal,
497
+ auth: { terminal: false },
498
+ };
499
+ const initialize = async (signal) => {
500
+ if (initialized)
501
+ return initialized;
502
+ const raw = (await peer.request('initialize', {
503
+ protocolVersion: ACP_PROTOCOL_VERSION,
504
+ clientCapabilities,
505
+ clientInfo: options.clientInfo ?? DEFAULT_CLIENT_INFO,
506
+ }, { signal, timeoutMs: controlTimeoutMs })) ?? {};
507
+ const authMethods = Array.isArray(raw.authMethods)
508
+ ? raw.authMethods
509
+ .filter((m) => Boolean(m && typeof m === 'object' && typeof m.id === 'string'))
510
+ .map((m) => ({
511
+ id: m.id,
512
+ name: typeof m.name === 'string' ? m.name : m.id,
513
+ ...(typeof m.description === 'string' ? { description: m.description } : {}),
514
+ ...(typeof m.type === 'string' ? { type: m.type } : {}),
515
+ }))
516
+ : [];
517
+ const agentInfoRaw = raw.agentInfo && typeof raw.agentInfo === 'object' && !Array.isArray(raw.agentInfo)
518
+ ? raw.agentInfo
519
+ : undefined;
520
+ initialized = {
521
+ protocolVersion: typeof raw.protocolVersion === 'number' ? raw.protocolVersion : ACP_PROTOCOL_VERSION,
522
+ ...(agentInfoRaw && typeof agentInfoRaw.name === 'string'
523
+ ? {
524
+ agentInfo: {
525
+ name: agentInfoRaw.name,
526
+ version: typeof agentInfoRaw.version === 'string' ? agentInfoRaw.version : '0.0.0',
527
+ ...(typeof agentInfoRaw.title === 'string' ? { title: agentInfoRaw.title } : {}),
528
+ },
529
+ }
530
+ : {}),
531
+ agentCapabilities: raw.agentCapabilities && typeof raw.agentCapabilities === 'object' && !Array.isArray(raw.agentCapabilities)
532
+ ? raw.agentCapabilities
533
+ : {},
534
+ authMethods,
535
+ };
536
+ return initialized;
537
+ };
538
+ const parseSessionInfo = (raw, fallbackId) => {
539
+ const sessionId = typeof raw.sessionId === 'string' ? raw.sessionId : (fallbackId ?? '');
540
+ const modesRaw = raw.modes && typeof raw.modes === 'object' && !Array.isArray(raw.modes) ? raw.modes : undefined;
541
+ const configOptions = parseConfigOptions(raw.configOptions);
542
+ return {
543
+ sessionId,
544
+ ...(modesRaw && typeof modesRaw.currentModeId === 'string' && Array.isArray(modesRaw.availableModes)
545
+ ? {
546
+ modes: {
547
+ currentModeId: modesRaw.currentModeId,
548
+ availableModes: modesRaw.availableModes,
549
+ },
550
+ }
551
+ : {}),
552
+ ...(configOptions.length ? { configOptions } : {}),
553
+ };
554
+ };
555
+ return Object.freeze({
556
+ initialize,
557
+ async authenticate(methodId, signal) {
558
+ await initialize(signal);
559
+ await peer.request('authenticate', { methodId }, { signal, timeoutMs: controlTimeoutMs });
560
+ },
561
+ async newSession(params) {
562
+ await initialize(params.signal);
563
+ const raw = (await peer.request('session/new', {
564
+ cwd: params.cwd,
565
+ mcpServers: params.mcpServers ? [...params.mcpServers] : [],
566
+ ...(params._meta ? { _meta: params._meta } : {}),
567
+ }, { signal: params.signal, timeoutMs: controlTimeoutMs })) ?? {};
568
+ const info = parseSessionInfo(raw);
569
+ if (params.mode && info.sessionId) {
570
+ if (params.mode === 'plan' || params.mode === 'ask' || params.mode === 'auto') {
571
+ options.permissions?.setMode(params.mode);
572
+ }
573
+ await peer
574
+ .request('session/set_mode', { sessionId: info.sessionId, modeId: params.mode }, { signal: params.signal, timeoutMs: controlTimeoutMs })
575
+ .catch(() => {
576
+ // Some ACP adapters do not advertise modes; ignore mode-set refusal gracefully.
577
+ });
578
+ }
579
+ return info;
580
+ },
581
+ async loadSession(params) {
582
+ await initialize(params.signal);
583
+ const raw = (await peer.request('session/load', {
584
+ sessionId: params.sessionId,
585
+ cwd: params.cwd,
586
+ mcpServers: params.mcpServers ? [...params.mcpServers] : [],
587
+ }, { signal: params.signal, timeoutMs: controlTimeoutMs })) ?? {};
588
+ return parseSessionInfo(raw, params.sessionId);
589
+ },
590
+ async prompt(sessionId, promptInput, promptOptions) {
591
+ const blocks = typeof promptInput === 'string' ? [{ type: 'text', text: promptInput }] : promptInput;
592
+ const acc = {
593
+ sessionId,
594
+ emit: promptOptions?.emit,
595
+ textChunks: [],
596
+ thoughtChunks: [],
597
+ toolCalls: new Map(),
598
+ plan: [],
599
+ diffs: [],
600
+ approvedWritePaths: new Set(),
601
+ };
602
+ activeTurns.set(sessionId, acc);
603
+ const onAbort = () => {
604
+ peer.notify('session/cancel', { sessionId });
605
+ };
606
+ promptOptions?.signal?.addEventListener('abort', onAbort, { once: true });
607
+ try {
608
+ const raw = (await peer.request('session/prompt', {
609
+ sessionId,
610
+ prompt: blocks,
611
+ ...(promptOptions?._meta ? { _meta: promptOptions._meta } : {}),
612
+ }, { signal: promptOptions?.signal })) ?? {};
613
+ // Force-settle any still-running tool call rows on turn close (matches real-world ACP adapter quirks).
614
+ const settledCalls = [];
615
+ for (const call of acc.toolCalls.values()) {
616
+ if (call.status === 'pending' || call.status === 'in_progress') {
617
+ const settled = { ...call, status: 'completed' };
618
+ settledCalls.push(settled);
619
+ emitBoth(acc, { event: 'tool_call_update', data: { sessionId, id: call.toolCallId, status: 'completed' } });
620
+ }
621
+ else {
622
+ settledCalls.push(call);
623
+ }
624
+ }
625
+ const stopReason = raw.stopReason === 'end_turn' ||
626
+ raw.stopReason === 'max_tokens' ||
627
+ raw.stopReason === 'max_turn_requests' ||
628
+ raw.stopReason === 'refusal' ||
629
+ raw.stopReason === 'cancelled'
630
+ ? raw.stopReason
631
+ : 'end_turn';
632
+ emitBoth(acc, { event: 'done', data: { sessionId, stopReason } });
633
+ return {
634
+ sessionId,
635
+ stopReason,
636
+ text: acc.textChunks.join(''),
637
+ reasoning: acc.thoughtChunks.join(''),
638
+ toolCalls: settledCalls,
639
+ plan: acc.plan,
640
+ diffs: acc.diffs,
641
+ ...(raw._meta && typeof raw._meta === 'object' && !Array.isArray(raw._meta)
642
+ ? { _meta: raw._meta }
643
+ : {}),
644
+ };
645
+ }
646
+ finally {
647
+ promptOptions?.signal?.removeEventListener('abort', onAbort);
648
+ activeTurns.delete(sessionId);
649
+ }
650
+ },
651
+ async setMode(sessionId, modeId, signal) {
652
+ await peer.request('session/set_mode', { sessionId, modeId }, { signal, timeoutMs: controlTimeoutMs });
653
+ if (modeId === 'plan' || modeId === 'ask' || modeId === 'auto') {
654
+ options.permissions?.setMode(modeId);
655
+ }
656
+ },
657
+ async setConfigOption(sessionId, configId, value, signal) {
658
+ const raw = (await peer.request('session/set_config_option', { sessionId, configId, value }, { signal, timeoutMs: controlTimeoutMs })) ?? {};
659
+ return parseConfigOptions(raw.configOptions);
660
+ },
661
+ cancel(sessionId) {
662
+ peer.notify('session/cancel', { sessionId });
663
+ },
664
+ async close() {
665
+ for (const term of terminals.values())
666
+ term.controller.abort();
667
+ terminals.clear();
668
+ peer.close('ACP client closed.');
669
+ if (child) {
670
+ try {
671
+ child.stdin?.end();
672
+ }
673
+ catch {
674
+ // ignore
675
+ }
676
+ await killProcessTree(child);
677
+ }
678
+ },
679
+ });
680
+ }