opencode-acp-client 0.0.0-stage → 0.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.
Files changed (55) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +220 -2
  3. package/README.zh.md +199 -0
  4. package/dist/acp/capabilities.d.ts +168 -0
  5. package/dist/acp/capabilities.js +240 -0
  6. package/dist/acp/capabilities.js.map +1 -0
  7. package/dist/acp/client.d.ts +241 -0
  8. package/dist/acp/client.js +767 -0
  9. package/dist/acp/client.js.map +1 -0
  10. package/dist/acp/types.d.ts +228 -0
  11. package/dist/acp/types.js +23 -0
  12. package/dist/acp/types.js.map +1 -0
  13. package/dist/acp-replay.d.ts +60 -0
  14. package/dist/acp-replay.js +188 -0
  15. package/dist/acp-replay.js.map +1 -0
  16. package/dist/contract.d.ts +435 -0
  17. package/dist/contract.js +126 -0
  18. package/dist/contract.js.map +1 -0
  19. package/dist/daemons.d.ts +39 -0
  20. package/dist/daemons.js +112 -0
  21. package/dist/daemons.js.map +1 -0
  22. package/dist/index.d.ts +268 -0
  23. package/dist/index.js +1882 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/opencode-bin.d.ts +73 -0
  26. package/dist/opencode-bin.js +109 -0
  27. package/dist/opencode-bin.js.map +1 -0
  28. package/dist/project.d.ts +81 -0
  29. package/dist/project.js +230 -0
  30. package/dist/project.js.map +1 -0
  31. package/dist/server.d.ts +743 -0
  32. package/dist/server.js +5029 -0
  33. package/dist/server.js.map +1 -0
  34. package/dist/session-map.d.ts +89 -0
  35. package/dist/session-map.js +305 -0
  36. package/dist/session-map.js.map +1 -0
  37. package/dist/sessions-command.d.ts +70 -0
  38. package/dist/sessions-command.js +188 -0
  39. package/dist/sessions-command.js.map +1 -0
  40. package/dist/sse.d.ts +40 -0
  41. package/dist/sse.js +147 -0
  42. package/dist/sse.js.map +1 -0
  43. package/dist/state.d.ts +161 -0
  44. package/dist/state.js +135 -0
  45. package/dist/state.js.map +1 -0
  46. package/dist/subagent-sessions.d.ts +71 -0
  47. package/dist/subagent-sessions.js +107 -0
  48. package/dist/subagent-sessions.js.map +1 -0
  49. package/dist/translate/events.d.ts +231 -0
  50. package/dist/translate/events.js +1244 -0
  51. package/dist/translate/events.js.map +1 -0
  52. package/dist/upgrade.d.ts +56 -0
  53. package/dist/upgrade.js +162 -0
  54. package/dist/upgrade.js.map +1 -0
  55. package/package.json +66 -4
@@ -0,0 +1,767 @@
1
+ /**
2
+ * ACP client: spawns an agent process and speaks ACP JSON-RPC over stdio.
3
+ *
4
+ * Two rules drive the whole implementation:
5
+ *
6
+ * 1. **Every inbound request gets an answer.** An ACP agent that asks us
7
+ * something and hears nothing will wait forever. So anything we cannot
8
+ * service is answered with an explicit JSON-RPC error, never dropped.
9
+ * 2. **Timeouts are mandatory.** Several agents have bugs where a request
10
+ * simply never resolves. Without a timeout the HTTP request waiting on it
11
+ * would hang for the lifetime of the process.
12
+ */
13
+ import { spawn, spawnSync } from 'node:child_process';
14
+ /** `opencode acp`'s notification for one event in a delegated run (see subagent-sessions). */
15
+ export const CHILD_UPDATE_METHOD = 'opencode/session/child_update';
16
+ import { appendFileSync, existsSync, mkdirSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ import { writeFileSync } from 'node:fs';
19
+ import { EventEmitter } from 'node:events';
20
+ import { CLIENT_CAPABILITIES, NO_CAPABILITIES, clientCallbackSupport, effectiveCapabilities, } from './capabilities.js';
21
+ /** Raised when the agent answered with a JSON-RPC error. */
22
+ export class AcpError extends Error {
23
+ code;
24
+ constructor(message, code = 'acp-error') {
25
+ super(message);
26
+ this.code = code;
27
+ this.name = 'AcpError';
28
+ }
29
+ }
30
+ /** The agent does not implement the method we called. */
31
+ export class AcpMethodNotFound extends AcpError {
32
+ constructor(method) {
33
+ super(`agent does not implement ${method}`, -32601);
34
+ this.name = 'AcpMethodNotFound';
35
+ }
36
+ }
37
+ export class AcpClient extends EventEmitter {
38
+ options;
39
+ child;
40
+ pending = new Map();
41
+ timeoutMs;
42
+ promptTimeoutMs;
43
+ protocolVersion;
44
+ nextId = 1;
45
+ buffer = '';
46
+ closed = false;
47
+ caps = null;
48
+ agentVersion;
49
+ pendingRecordedFrames = [];
50
+ recordFlushed = false;
51
+ recordFile;
52
+ /** Permission requests the agent is currently blocked on. */
53
+ permissionHandler = null;
54
+ /** `elicitation/create` — the agent asking the user something. */
55
+ elicitationHandler = null;
56
+ constructor(options) {
57
+ super();
58
+ this.options = options;
59
+ this.timeoutMs = options.requestTimeoutMs ?? 120_000;
60
+ // ★ No prompt clock by default (2026-10-20). A real long task was killed
61
+ // twice at 30 minutes while the agent was still working; the TUI showed "timed
62
+ // out waiting for session/prompt", the agent kept its prompt active, and the
63
+ // user had to type "continue". ACP has no server-side prompt timeout, and the
64
+ // TUI's Esc/interrupt is the user's stop control. Set the env (or the option)
65
+ // to a positive number to restore a clock.
66
+ this.promptTimeoutMs =
67
+ options.promptTimeoutMs ??
68
+ (Number(process.env['OPENCODE_ACP_CLIENT_PROMPT_TIMEOUT_MS']) > 0
69
+ ? Number(process.env['OPENCODE_ACP_CLIENT_PROMPT_TIMEOUT_MS'])
70
+ : 0);
71
+ this.protocolVersion = options.protocolVersion ?? 1;
72
+ const env = { ...process.env, ...(options.env ?? {}) };
73
+ // Strip anything that would make the agent try to phone home during tests.
74
+ env.NO_COLOR = env.NO_COLOR ?? '1';
75
+ this.child = spawn(options.command, options.args ?? [], {
76
+ cwd: options.cwd,
77
+ env,
78
+ stdio: ['pipe', 'pipe', 'pipe'],
79
+ // Its own process group on POSIX, so dispose can kill the whole tree. An agent
80
+ // that forks helpers (shells, watchers) used to leave them behind: `child.kill`
81
+ // only reaches the direct child, and the survivors became `ppid=1` orphans that
82
+ // keep workspace locks (measured twice with dsh).
83
+ detached: process.platform !== 'win32',
84
+ });
85
+ this.child.stdout.setEncoding('utf8');
86
+ this.child.stdout.on('data', (chunk) => this.onStdout(chunk));
87
+ this.child.stderr.setEncoding('utf8');
88
+ this.child.stderr.on('data', (chunk) => {
89
+ for (const line of chunk.split('\n')) {
90
+ if (line.trim())
91
+ this.emit('log', `[agent] ${line}`);
92
+ }
93
+ });
94
+ this.child.on('error', (err) => {
95
+ this.failAll(new AcpError(`failed to start agent: ${err.message}`, 'spawn-failed'));
96
+ });
97
+ this.child.on('exit', (code, signal) => {
98
+ this.closed = true;
99
+ this.failAll(new AcpError(`agent exited (code=${code} signal=${signal})`, 'agent-exited'));
100
+ this.emit('exit', { code, signal });
101
+ });
102
+ }
103
+ get capabilities() {
104
+ // Before `initialize` answers, the honest profile is "nothing advertised".
105
+ return this.caps ?? NO_CAPABILITIES;
106
+ }
107
+ /** Register the handler used to resolve `session/request_permission`. */
108
+ onPermission(handler) {
109
+ this.permissionHandler = handler;
110
+ }
111
+ /**
112
+ * Register the handler used to answer `elicitation/create`.
113
+ *
114
+ * Only ever called for `mode: "form"` — the mode we advertise. The handler may
115
+ * throw to refuse the request outright; that becomes a JSON-RPC error, which is
116
+ * the honest answer when the requested schema cannot be rendered.
117
+ */
118
+ onElicitation(handler) {
119
+ this.elicitationHandler = handler;
120
+ }
121
+ /**
122
+ * `initialize`. Failure here is fatal: without it we do not know what the
123
+ * agent supports, and guessing is how hangs happen.
124
+ */
125
+ async initialize() {
126
+ const result = await this.request('initialize', {
127
+ protocolVersion: this.protocolVersion,
128
+ // Only what has a path behind it. See CLIENT_CAPABILITIES.
129
+ clientCapabilities: CLIENT_CAPABILITIES,
130
+ });
131
+ this.caps = effectiveCapabilities(result);
132
+ const info = result.agentInfo;
133
+ if (typeof info?.version === 'string')
134
+ this.agentVersion = info.version;
135
+ // The header needs the agent's name, which only exists after this response.
136
+ this.flushRecordedFrames();
137
+ this.emit('log', `initialized: ${JSON.stringify(this.caps)}`);
138
+ return this.caps;
139
+ }
140
+ async newSession(cwd) {
141
+ const result = await this.request('session/new', { cwd, mcpServers: [] });
142
+ this.catalog(result.sessionId).configOptions = result.configOptions ?? [];
143
+ this.noteStandardModels(result.sessionId, result);
144
+ if (process.env.OPENCODE_ACP_CLIENT_DUMP) {
145
+ try {
146
+ writeFileSync(process.env.OPENCODE_ACP_CLIENT_DUMP, JSON.stringify(result, null, 2));
147
+ }
148
+ catch {
149
+ /* diagnostics only */
150
+ }
151
+ }
152
+ return result;
153
+ }
154
+ /**
155
+ * Per-SESSION catalogs: the config options and the standard `models` list are
156
+ * session-scoped in ACP (`session/new`/`load`/`resume` each carry their own), so
157
+ * they are kept per session id rather than in one field. One field was fine while
158
+ * one client meant one session; a shared connection would let the newest session's
159
+ * defaults (and a `set_config_option` meant for another session) leak across.
160
+ */
161
+ catalogs = new Map();
162
+ lastSessionId;
163
+ /** (Re)select a session's catalog state, remembering it as the most recent one. */
164
+ catalog(sessionId) {
165
+ let state = this.catalogs.get(sessionId);
166
+ if (!state) {
167
+ state = { configOptions: [] };
168
+ this.catalogs.set(sessionId, state);
169
+ }
170
+ this.lastSessionId = sessionId;
171
+ return state;
172
+ }
173
+ /** The options a given session advertised; omitted = the most recently touched one. */
174
+ configOptionsFor(sessionId) {
175
+ const id = sessionId ?? this.lastSessionId;
176
+ return id ? (this.catalogs.get(id)?.configOptions ?? []) : [];
177
+ }
178
+ /** Any session on this connection advertised a catalog (pool-aware). */
179
+ hasCatalog() {
180
+ for (const state of this.catalogs.values()) {
181
+ if (state.configOptions.length > 0)
182
+ return true;
183
+ }
184
+ return false;
185
+ }
186
+ /**
187
+ * The ACP-standard model list: `models: {currentModelId, availableModels[]}`.
188
+ *
189
+ * Agents that use it (qwen, and per the ecosystem survey gemini and kimi) put their
190
+ * models here rather than in an opencode-shaped `configOptions` entry — we ignored
191
+ * the field entirely, so their model picker came up empty (`/api/model` stayed on the
192
+ * `acp/default` placeholder) even though the agent had just told us every model it
193
+ * has. Measured: qwen --acp returns four models this way.
194
+ */
195
+ noteStandardModels(sessionId, result) {
196
+ const models = result.models;
197
+ const available = models?.availableModels ?? [];
198
+ if (available.length === 0)
199
+ return;
200
+ const state = this.catalog(sessionId);
201
+ state.standardModels = models;
202
+ // ★ Merge the two sources by IDENTITY, and let `configOptions` own the spelling when
203
+ // both describe the same model.
204
+ //
205
+ // Measured on shapers that disagree:
206
+ // • codex-acp 2.8.0 — `configOptions` says `deepseek-flash`, while `models` says
207
+ // `deepseek-flash[none]` / `[high]` / `[max]` (a reasoning-effort suffix). Appending
208
+ // the second on top of the first put the suffixed values in the picker; the TUI
209
+ // submitted the unsuffixed one it had read from `configOptions`, the lookup found no
210
+ // match, the request fell back to `acp/deepseek-flash`, codex refused it with
211
+ // `Internal error`, and the session never set up.
212
+ // • qwen --acp — both lists carry the identical ids, so appending only duplicated rows.
213
+ //
214
+ // So: keep every `configOptions` value, and add a `models` entry only when no existing
215
+ // option already means that model (compared with any `[suffix]` stripped).
216
+ const existing = new Set();
217
+ for (const option of state.configOptions) {
218
+ if (option.category !== 'model' && option.id !== 'model')
219
+ continue;
220
+ for (const entry of option.options ?? []) {
221
+ const group = entry;
222
+ const values = Array.isArray(group.options)
223
+ ? group.options.map((choice) => choice.value)
224
+ : [group.value];
225
+ for (const value of values) {
226
+ if (typeof value !== 'string')
227
+ continue;
228
+ // `["provider","model"]` and `provider::model` both reduce to the model id.
229
+ const bare = value.replace(/\[[^\]]*\]$/, '');
230
+ existing.add(bare);
231
+ try {
232
+ const parsed = JSON.parse(value);
233
+ if (Array.isArray(parsed) && typeof parsed[1] === 'string')
234
+ existing.add(parsed[1]);
235
+ }
236
+ catch {
237
+ /* not JSON: the raw string is the id */
238
+ }
239
+ }
240
+ }
241
+ }
242
+ const novel = available.filter((model) => {
243
+ const id = String(model.modelId ?? '');
244
+ return id !== '' && !existing.has(id) && !existing.has(id.replace(/\[[^\]]*\]$/, ''));
245
+ });
246
+ if (novel.length === 0)
247
+ return;
248
+ state.configOptions = [
249
+ ...state.configOptions,
250
+ {
251
+ id: 'model',
252
+ name: 'Model',
253
+ category: 'model',
254
+ type: 'select',
255
+ currentValue: JSON.stringify([models?.currentModelId ?? novel[0]?.modelId ?? '', '']),
256
+ options: novel.map((model) => ({
257
+ value: JSON.stringify([model.modelId ?? '', model.modelId ?? '']),
258
+ name: model.name ?? String(model.modelId ?? ''),
259
+ })),
260
+ },
261
+ ];
262
+ }
263
+ get configOptions() {
264
+ return this.configOptionsFor();
265
+ }
266
+ /**
267
+ * `session/load`. Caller must check `capabilities.loadSession` first.
268
+ * Agents without `loadSession` get an explicit, catchable error.
269
+ */
270
+ async loadSession(sessionId, cwd) {
271
+ if (!this.capabilities.loadSession) {
272
+ throw new AcpMethodNotFound('session/load');
273
+ }
274
+ const result = await this.request('session/load', {
275
+ sessionId,
276
+ cwd,
277
+ mcpServers: [],
278
+ });
279
+ // A replay carries the session's config options too, and that is where a
280
+ // resumed session's model list comes from - `session/new` never runs for it.
281
+ // `?? []` and not `?? this.sessionConfig`... except agents that send the config
282
+ // as a `config_option_update` *notification* before the response (the fixture does;
283
+ // real agents vary) have it applied by the update listener already, and a bare
284
+ // response then wiped it back to empty — measured: the catalog stayed on the
285
+ // placeholder forever after a restart, the client showed `model-1 (unavailable)`
286
+ // and refused to submit. The response wins when it carries options; when it does
287
+ // not, whatever the notifications already applied stands.
288
+ if (Array.isArray(result.configOptions))
289
+ this.catalog(sessionId).configOptions = result.configOptions;
290
+ this.noteStandardModels(sessionId, result);
291
+ }
292
+ /**
293
+ * `session/resume`. ACP defines it as "reconnect to an existing session WITHOUT
294
+ * replaying history" — and that is all it promises.
295
+ *
296
+ * Measured on the backend's plain ACP profile (2026-10-17, probes in
297
+ * docs/KNOWN-ISSUES.md): the call succeeds, the response carries configOptions, no
298
+ * updates follow, and the next turn runs. Whether the agent's model actually still
299
+ * has the earlier conversation was **not consistent**: the same profile answered
300
+ * "there's no word I was asked to remember in this conversation" under one model
301
+ * and recalled the word correctly under another.
302
+ *
303
+ * So describe only what is guaranteed: same session id, empty transcript, and the
304
+ * conversation's continuity left to the agent. Never promise that context survived.
305
+ */
306
+ async resumeSession(sessionId, cwd) {
307
+ // ACP: a client MUST NOT call `session/resume` without
308
+ // `sessionCapabilities.resume`. Refusing here (as `listSessions` does) keeps
309
+ // the gate in one place, so no future caller can quietly violate it.
310
+ if (!this.capabilities.resumeSessions) {
311
+ throw new AcpMethodNotFound('session/resume');
312
+ }
313
+ const result = await this.request('session/resume', { sessionId, cwd });
314
+ this.catalog(sessionId).configOptions = result.configOptions ?? [];
315
+ this.noteStandardModels(sessionId, result);
316
+ return result;
317
+ }
318
+ /**
319
+ * `session/list`. the backend returns `{sessionId, cwd}` entries newest first, 100 per
320
+ * page with a cursor. An unpaginated read only ever sees recent sessions — for a
321
+ * directory whose sessions are all older, a "latest" lookup finds nothing.
322
+ */
323
+ async listSessions(cwd, maxPages = 10) {
324
+ // ACP: a client MUST NOT call `session/list` without `sessionCapabilities.list`.
325
+ // Refusing here (rather than in each caller) keeps the gate in one place.
326
+ if (!this.capabilities.listSessions) {
327
+ throw new AcpMethodNotFound('session/list');
328
+ }
329
+ const all = [];
330
+ let cursor;
331
+ for (let page = 0; page < maxPages; page += 1) {
332
+ const result = await this.request('session/list', cursor ? { cwd, cursor } : { cwd });
333
+ all.push(...(result.sessions ?? []));
334
+ cursor = result.nextCursor ?? undefined;
335
+ if (!cursor)
336
+ break;
337
+ }
338
+ return all;
339
+ }
340
+ async prompt(sessionId, prompt) {
341
+ return this.request('session/prompt', { sessionId, prompt }, this.promptTimeoutMs > 0 ? this.promptTimeoutMs : null);
342
+ }
343
+ /**
344
+ * `session/set_config_option`. the backend advertises models through a config option
345
+ * (`id: "model"`), so this is how a model switch reaches the agent.
346
+ *
347
+ * Returns the config state the agent answered with: the spec requires the
348
+ * response to carry the **complete** list, which is how dependent changes
349
+ * (reasoning options that follow the model, for instance) reach us at all.
350
+ */
351
+ /**
352
+ * Tell the agent a session is gone (`session/delete`, a stable agent method).
353
+ *
354
+ * Without this the agent keeps the session it created: the bridge forgets it, the
355
+ * UI forgets it, and the agent's own store keeps growing. Best-effort by design —
356
+ * the user asked to delete, and that must succeed locally even if the agent cannot
357
+ * honour it.
358
+ */
359
+ async deleteSession(sessionId) {
360
+ await this.request('session/delete', { sessionId });
361
+ }
362
+ /**
363
+ * The spelling `set_model` expects for a model the caller names by its bare id.
364
+ *
365
+ * An agent that publishes `models.availableModels` may append a variant to the id
366
+ * (`deepseek-flash[high]`) while `configOptions` offers the bare one; the two
367
+ * methods accept different spellings (see `setConfig`). Match on the bare part and
368
+ * return the standard list's own string, so neither the picker nor the wire has to
369
+ * know which surface the user clicked on.
370
+ */
371
+ resolveStandardModelId(state, modelId) {
372
+ const available = state.standardModels?.availableModels ?? [];
373
+ if (available.length === 0)
374
+ return undefined;
375
+ const bare = (id) => id.replace(/\[[^\]]*\]$/, '');
376
+ const exact = available.find((model) => model.modelId === modelId);
377
+ if (exact?.modelId)
378
+ return exact.modelId;
379
+ const sameModel = available.find((model) => typeof model.modelId === 'string' && bare(model.modelId) === bare(modelId));
380
+ return sameModel?.modelId;
381
+ }
382
+ async setConfig(sessionId, configId, value) {
383
+ // An agent whose models arrived in the standard `models` field switches them with
384
+ // `session/set_model` (that is the family gemini and kimi use too), not by writing
385
+ // a config option we synthesised on its behalf.
386
+ const state = this.catalog(sessionId);
387
+ if (configId === 'model' && state.standardModels) {
388
+ let modelId = value;
389
+ try {
390
+ const parsed = JSON.parse(value);
391
+ if (Array.isArray(parsed) && typeof parsed[1] === 'string')
392
+ modelId = parsed[1];
393
+ }
394
+ catch {
395
+ /* a bare model id is fine too */
396
+ }
397
+ // ★ `set_model` wants the id EXACTLY as `models.availableModels` spells it, which
398
+ // is not always what `configOptions` offers. Measured on codex-acp 2.8.0:
399
+ // session/set_config_option + `deepseek-flash` -> OK
400
+ // session/set_model + `deepseek-flash` -> "Unsupported format of
401
+ // modelId … Expected: modelId[effort]"
402
+ // session/set_model + `deepseek-flash[high]` -> OK
403
+ // The caller has the bare id (that is what the picker shows), so resolve it
404
+ // against the standard list before switching — matching on the part before
405
+ // `[`, which is the model's identity on both sides.
406
+ const wanted = this.resolveStandardModelId(state, modelId) ?? modelId;
407
+ await this.request('session/set_model', { sessionId, modelId: wanted });
408
+ if (state.standardModels)
409
+ state.standardModels.currentModelId = wanted;
410
+ return state.configOptions;
411
+ }
412
+ // `value` goes on the wire as a bare string, NOT as the `{type:"id", value}`
413
+ // envelope the ACP SDK types declare. the backend validates the envelope away with
414
+ // zod and hands the inner value straight to a `typeof value !== "string"`
415
+ // check, so the SDK-shaped object is rejected as "Invalid params".
416
+ //
417
+ // Probed against the backend directly:
418
+ // {type:"id", value:"['p','m']"} -> Invalid params
419
+ // "['p','m']" -> accepted, configOptions returned
420
+ const result = await this.request('session/set_config_option', { sessionId, configId, value });
421
+ this.applyConfigOptions(sessionId, result?.configOptions);
422
+ return state.configOptions;
423
+ }
424
+ /**
425
+ * Replace the session's config options.
426
+ *
427
+ * Used for both halves of the negotiation: the reply to a `set_config_option`,
428
+ * and an agent-pushed `config_option_update` (the spec sends the complete state
429
+ * in both, so replacing is correct — merging would keep stale values alive).
430
+ */
431
+ applyConfigOptions(sessionId, options) {
432
+ if (Array.isArray(options))
433
+ this.catalog(sessionId).configOptions = options;
434
+ }
435
+ /** `session/cancel` is a notification: fire and forget, per the spec. */
436
+ cancel(sessionId) {
437
+ this.notify('session/cancel', { sessionId });
438
+ }
439
+ /** Terminate the agent. Safe to call repeatedly. */
440
+ /** Signal the agent AND its descendants (one process group on POSIX). */
441
+ killGroup(signal) {
442
+ const pid = this.child.pid;
443
+ if (pid === undefined)
444
+ return;
445
+ if (process.platform === 'win32') {
446
+ // Windows has no process group we can signal: `taskkill /T` walks the tree.
447
+ // Without /F it asks the app to close (our SIGTERM step); /F is the force
448
+ // step. A failure falls through to the direct-child kill below.
449
+ try {
450
+ spawnSync('taskkill', windowsKillArgs(pid, signal), { stdio: 'ignore' });
451
+ return;
452
+ }
453
+ catch {
454
+ /* taskkill missing; fall through */
455
+ }
456
+ }
457
+ if (process.platform !== 'win32') {
458
+ try {
459
+ process.kill(-pid, signal);
460
+ return;
461
+ }
462
+ catch {
463
+ /* the group is already gone, or it never became a group leader */
464
+ }
465
+ }
466
+ try {
467
+ this.child.kill(signal);
468
+ }
469
+ catch {
470
+ /* already gone */
471
+ }
472
+ }
473
+ async dispose() {
474
+ if (this.closed)
475
+ return;
476
+ this.closed = true;
477
+ this.failAll(new AcpError('client disposed', 'disposed'));
478
+ try {
479
+ this.child.stdin.end();
480
+ }
481
+ catch {
482
+ /* already gone */
483
+ }
484
+ await new Promise((resolve) => {
485
+ const t = setTimeout(() => {
486
+ try {
487
+ this.killGroup('SIGKILL');
488
+ }
489
+ catch {
490
+ /* ignore */
491
+ }
492
+ resolve();
493
+ }, 3000);
494
+ this.child.once('exit', () => {
495
+ clearTimeout(t);
496
+ // The leader is gone; helpers that ignored SIGTERM would linger as orphans.
497
+ this.killGroup('SIGKILL');
498
+ resolve();
499
+ });
500
+ try {
501
+ this.killGroup('SIGTERM');
502
+ }
503
+ catch {
504
+ clearTimeout(t);
505
+ resolve();
506
+ }
507
+ });
508
+ }
509
+ // ---------------------------------------------------------------- internals
510
+ onStdout(chunk) {
511
+ this.buffer += chunk;
512
+ let index;
513
+ while ((index = this.buffer.indexOf('\n')) >= 0) {
514
+ const line = this.buffer.slice(0, index).trim();
515
+ this.buffer = this.buffer.slice(index + 1);
516
+ if (!line)
517
+ continue;
518
+ let msg;
519
+ try {
520
+ msg = JSON.parse(line);
521
+ }
522
+ catch {
523
+ this.emit('log', `[agent] unparseable frame: ${line.slice(0, 200)}`);
524
+ continue;
525
+ }
526
+ this.recordFrame(msg);
527
+ void this.onMessage(msg);
528
+ }
529
+ }
530
+ /**
531
+ * `OPENCODE_ACP_CLIENT_RECORD_FRAMES=<dir>`: append every inbound frame to
532
+ * `<dir>/<backend>.jsonl`, headed by a provenance line.
533
+ *
534
+ * A recorded turn is the only fixture that carries a REAL agent's shapes — the
535
+ * synthetic fake agent can only exercise shapes we thought of. The corpus format
536
+ * follows KiroCrew's: the first line is `_meta` (backend, recorded, date,
537
+ * agent_version) and every line after it is the wire verbatim, so a replay can
538
+ * be weighed against what produced it. Recording never breaks the wire: a
539
+ * write failure is logged and dropped.
540
+ */
541
+ recordFrame(msg) {
542
+ if (!process.env.OPENCODE_ACP_CLIENT_RECORD_FRAMES)
543
+ return;
544
+ if (this.recordFlushed && this.recordFile) {
545
+ try {
546
+ appendFileSync(this.recordFile, `${JSON.stringify(msg)}\n`);
547
+ }
548
+ catch (err) {
549
+ this.emit('log', `[record] ${String(err)}`);
550
+ }
551
+ return;
552
+ }
553
+ this.pendingRecordedFrames.push(msg);
554
+ // Frames that arrive before `initialize` answers are buffered: the header needs
555
+ // the agent's own name, and writing it first with `unknown` would mislabel a
556
+ // corpus that a replay later weighs by its backend.
557
+ if (this.caps)
558
+ this.flushRecordedFrames();
559
+ }
560
+ /** Write the buffered frames (header first) once the backend is known. */
561
+ flushRecordedFrames() {
562
+ const dir = process.env.OPENCODE_ACP_CLIENT_RECORD_FRAMES;
563
+ if (!dir || this.recordFlushed)
564
+ return;
565
+ this.recordFlushed = true;
566
+ try {
567
+ mkdirSync(dir, { recursive: true });
568
+ const backend = (this.caps?.agentName ?? 'unknown').replace(/[^\w.-]+/g, '-');
569
+ const file = join(dir, `${backend}.jsonl`);
570
+ this.recordFile = file;
571
+ const header = {
572
+ _meta: {
573
+ backend,
574
+ recorded: 'live',
575
+ date: new Date().toISOString().slice(0, 10),
576
+ agent_version: this.agentVersion ?? 'unmeasured',
577
+ },
578
+ };
579
+ const body = this.pendingRecordedFrames.map((frame) => JSON.stringify(frame)).join('\n');
580
+ appendFileSync(file, `${JSON.stringify(header)}\n${body}${body ? '\n' : ''}`);
581
+ this.pendingRecordedFrames = [];
582
+ }
583
+ catch (err) {
584
+ this.emit('log', `[record] ${String(err)}`);
585
+ }
586
+ }
587
+ async onMessage(msg) {
588
+ // Raw frame tracing: the only way to tell "the agent sent nothing" apart
589
+ // from "we dropped what it sent".
590
+ if (process.env.OPENCODE_ACP_CLIENT_TRACE) {
591
+ this.emit('log', `[recv] ${JSON.stringify(msg).slice(0, 4000)}`);
592
+ }
593
+ if ('method' in msg && msg.method) {
594
+ if ('id' in msg && msg.id !== undefined) {
595
+ await this.onRequest(msg.id, msg.method, msg.params);
596
+ }
597
+ else {
598
+ this.onNotification(msg.method, msg.params);
599
+ }
600
+ return;
601
+ }
602
+ const response = msg;
603
+ const pending = this.pending.get(response.id);
604
+ if (!pending) {
605
+ this.emit('log', `[agent] response for unknown id ${String(response.id)}`);
606
+ return;
607
+ }
608
+ this.pending.delete(response.id);
609
+ clearTimeout(pending.timer);
610
+ if (response.error) {
611
+ pending.reject(new AcpError(response.error.message, response.error.code));
612
+ }
613
+ else {
614
+ pending.resolve(response.result);
615
+ }
616
+ }
617
+ onNotification(method, params) {
618
+ if (method === 'session/update') {
619
+ const p = (params ?? {});
620
+ if (typeof p.sessionId === 'string' && p.update) {
621
+ // Config state is recorded on the client, not by a listener: the
622
+ // translator attaches on the first prompt, and an agent that announces
623
+ // new options between session/new and that point would otherwise be
624
+ // silently ignored (and its model change lost).
625
+ if (p.update.sessionUpdate === 'config_option_update') {
626
+ this.applyConfigOptions(p.sessionId, p.update['configOptions']);
627
+ }
628
+ // `_meta` may sit on the notification params, on the update, or both.
629
+ // ACP reserves it for extensions, so it is merged and handed on rather
630
+ // than dropped — never overwriting the agent's own keys.
631
+ const paramsMeta = p._meta;
632
+ const updateMeta = p.update['_meta'];
633
+ const meta = {
634
+ ...(paramsMeta && typeof paramsMeta === 'object' ? paramsMeta : {}),
635
+ ...(updateMeta && typeof updateMeta === 'object' ? updateMeta : {}),
636
+ };
637
+ this.emit('update', p.sessionId, Object.keys(meta).length > 0 ? { ...p.update, _meta: meta } : p.update);
638
+ }
639
+ return;
640
+ }
641
+ // opencode's delegated-run stream: a second stream of `session/update`-shaped frames
642
+ // belonging to the same session as its parent. Handed to the translator, which owns
643
+ // everything the client renders.
644
+ if (method === CHILD_UPDATE_METHOD) {
645
+ const p = (params ?? {});
646
+ if (typeof p.rootSessionId === 'string') {
647
+ this.emit('child', p.rootSessionId, params);
648
+ return;
649
+ }
650
+ }
651
+ this.emit('log', `[agent] notification ${method}`);
652
+ }
653
+ /**
654
+ * Agent→client request. This is where "answer everything" matters most:
655
+ * an unhandled request is a deadlock, and a *silently* unhandled one is the
656
+ * hardest class of bug to find later.
657
+ */
658
+ async onRequest(id, method, params) {
659
+ try {
660
+ if (method === 'session/request_permission') {
661
+ const req = (params ?? {});
662
+ if (!this.permissionHandler) {
663
+ // Nobody is listening. Answer with an explicit cancel so the agent can
664
+ // fail closed rather than wait forever.
665
+ this.respond(id, { outcome: { outcome: 'cancelled' } });
666
+ return;
667
+ }
668
+ const answer = await this.permissionHandler(req);
669
+ this.respond(id, answer);
670
+ return;
671
+ }
672
+ if (method === 'elicitation/create') {
673
+ const req = (params ?? {});
674
+ // Checked before the handler: we advertise `form` only, and a url request
675
+ // must be refused rather than answered with a form (the spec forbids that
676
+ // fallback precisely because url mode carries the sensitive flows).
677
+ if (req.mode !== 'form') {
678
+ this.respondError(id, -32602, `only form elicitation is supported (mode=${req.mode === undefined ? 'undefined' : String(req.mode)})`);
679
+ return;
680
+ }
681
+ if (!this.elicitationHandler) {
682
+ // Fail closed, not silent: `cancel` is one of the three documented
683
+ // outcomes, and the agent is required to cope with it.
684
+ this.respond(id, { action: 'cancel' });
685
+ return;
686
+ }
687
+ this.respond(id, await this.elicitationHandler(req));
688
+ return;
689
+ }
690
+ const support = clientCallbackSupport(method);
691
+ if (!support.supported) {
692
+ // Explicit refusal beats silence: the agent can degrade.
693
+ this.respondError(id, -32601, support.reason);
694
+ return;
695
+ }
696
+ this.respondError(id, -32601, `bridge does not handle ${method}`);
697
+ }
698
+ catch (err) {
699
+ // An `AcpError` carries a deliberate code (e.g. -32602 for a schema we
700
+ // cannot render); anything else is an internal failure.
701
+ if (err instanceof AcpError && typeof err.code === 'number') {
702
+ this.respondError(id, err.code, err.message);
703
+ return;
704
+ }
705
+ this.respondError(id, -32603, err instanceof Error ? err.message : String(err));
706
+ }
707
+ }
708
+ request(method, params, timeoutMs = this.timeoutMs) {
709
+ if (this.closed) {
710
+ return Promise.reject(new AcpError('agent is not running', 'agent-exited'));
711
+ }
712
+ const id = this.nextId++;
713
+ return new Promise((resolve, reject) => {
714
+ const timer = timeoutMs === null
715
+ ? undefined
716
+ : setTimeout(() => {
717
+ this.pending.delete(id);
718
+ reject(new AcpError(`timed out waiting for ${method}`, 'timeout'));
719
+ }, timeoutMs);
720
+ timer?.unref?.();
721
+ this.pending.set(id, {
722
+ method,
723
+ timer,
724
+ resolve: resolve,
725
+ reject,
726
+ });
727
+ this.write({ jsonrpc: '2.0', id, method, params });
728
+ });
729
+ }
730
+ notify(method, params) {
731
+ this.write({ jsonrpc: '2.0', method, params });
732
+ }
733
+ respond(id, result) {
734
+ this.write({ jsonrpc: '2.0', id, result });
735
+ }
736
+ respondError(id, code, message) {
737
+ this.write({ jsonrpc: '2.0', id, error: { code, message } });
738
+ }
739
+ write(message) {
740
+ if (this.closed)
741
+ return;
742
+ try {
743
+ this.child.stdin.write(`${JSON.stringify(message)}\n`);
744
+ }
745
+ catch (err) {
746
+ this.emit('log', `failed to write to agent: ${String(err)}`);
747
+ }
748
+ }
749
+ failAll(err) {
750
+ for (const [id, pending] of this.pending) {
751
+ clearTimeout(pending.timer);
752
+ pending.reject(err);
753
+ this.pending.delete(id);
754
+ }
755
+ }
756
+ }
757
+ /**
758
+ * The `taskkill` arguments that end an agent AND its descendants on Windows.
759
+ *
760
+ * Windows has no signalable process groups, so the portable `process.kill(-pid)`
761
+ * has nothing to do; `taskkill /T` is the tree walk. `/F` is the force step: the
762
+ * SIGKILL pass uses it, the SIGTERM pass lets the app close first.
763
+ */
764
+ export function windowsKillArgs(pid, signal) {
765
+ return ['/PID', String(pid), '/T', ...(signal === 'SIGKILL' ? ['/F'] : [])];
766
+ }
767
+ //# sourceMappingURL=client.js.map