opencode-acp-provider 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1033 @@
1
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"
2
+ import { createReadStream } from "node:fs"
3
+ import { mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises"
4
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path"
5
+ import { createInterface } from "node:readline"
6
+ import { errorMessage } from "./util.ts"
7
+
8
+ /**
9
+ * Minimal Agent Client Protocol (ACP) client.
10
+ *
11
+ * Speaks newline-delimited JSON-RPC 2.0 over the child's stdio, the transport
12
+ * used by `cmd acp`, Zed, and other ACP agents.
13
+ */
14
+
15
+ export type Json = null | boolean | number | string | Json[] | { [key: string]: Json }
16
+
17
+ export type ContentBlock =
18
+ | { type: "text"; text: string }
19
+ | { type: "image"; data: string; mimeType: string }
20
+ | { type: "resource_link"; uri: string; name?: string; mimeType?: string }
21
+ | { type: "resource"; resource: { uri: string; mimeType?: string; text?: string } }
22
+
23
+ export interface SessionUpdate {
24
+ sessionUpdate: string
25
+ content?: { type?: string; text?: string }
26
+ [key: string]: unknown
27
+ }
28
+
29
+ export interface PromptResult {
30
+ stopReason: string
31
+ text: string
32
+ }
33
+
34
+ /** MCP servers the agent should connect to for a session (ACP `session/new`). */
35
+ export type AcpMcpServer =
36
+ | {
37
+ type: "stdio"
38
+ name: string
39
+ command: string
40
+ args: string[]
41
+ env?: Array<{ name: string; value: string }>
42
+ }
43
+ | {
44
+ type: "http" | "sse"
45
+ name: string
46
+ url: string
47
+ headers: Array<{ name: string; value: string }>
48
+ }
49
+
50
+ export interface AcpConfigOption {
51
+ id?: string
52
+ name?: string
53
+ description?: string
54
+ category?: string
55
+ type?: string
56
+ currentValue?: string
57
+ options?: Array<{ value?: string; name?: string; description?: string }>
58
+ }
59
+
60
+ /** A reasoning-effort select advertised by the agent in `session/new`. */
61
+ export interface AcpEffortConfig {
62
+ /** Config id to pass to `session/set_config_option` (usually "effort"). */
63
+ configId: string
64
+ name?: string
65
+ currentValue?: string
66
+ values: string[]
67
+ }
68
+
69
+ /** A slash command the agent advertised through `available_commands_update`. */
70
+ export interface AcpCommand {
71
+ name: string
72
+ description?: string
73
+ /** Usage hint the agent shows for the command's arguments, e.g. "[interval] [prompt]". */
74
+ hint?: string
75
+ }
76
+
77
+ /** A permission request forwarded from the agent to the client. */
78
+ export interface PermissionRequestInfo {
79
+ title: string
80
+ kind?: string
81
+ detail?: string
82
+ }
83
+
84
+ export type PermissionHandler = (request: PermissionRequestInfo) => Promise<boolean>
85
+
86
+ interface AgentHandshake {
87
+ protocolVersion: number
88
+ agentInfo: unknown
89
+ agentCapabilities: {
90
+ /** The agent can reload a persisted session with `session/load`. */
91
+ loadSession?: boolean
92
+ sessionCapabilities?: { close?: boolean; resume?: unknown }
93
+ [key: string]: unknown
94
+ }
95
+ authMethods: unknown
96
+ }
97
+
98
+ /**
99
+ * Recognise an ask-user prompt that an agent sent through
100
+ * `session/request_permission`. Command Code marks every choice as
101
+ * `allow_once` and numbers the option ids `option_0`, `option_1`, …, so option
102
+ * `kind` cannot tell a question apart from a permission. The raw question text
103
+ * is the reliable signal; numbered ids or option labels keep ordinary tool
104
+ * prompts out.
105
+ *
106
+ * Native question tools must be disabled in the agent's own configuration so
107
+ * agents use OpenCode's MCP `question` tool instead. If one still asks this
108
+ * way, the request is declined rather than answered with the first option.
109
+ */
110
+ function readQuestionText(params: any, options: Array<{ optionId?: string }>): string | undefined {
111
+ const raw = params?.toolCall?.rawInput
112
+ const question = typeof raw?.question === "string" ? raw.question.trim() : ""
113
+ if (!question || !options.length) return undefined
114
+ const labels: unknown[] = Array.isArray(raw?.options) ? raw.options : []
115
+ const numbered = options.every(
116
+ (option) => typeof option.optionId === "string" && /^option_\d+$/.test(option.optionId),
117
+ )
118
+ if (!numbered && !labels.length) return undefined
119
+ return question
120
+ }
121
+
122
+ function readEffortConfig(configOptions: AcpConfigOption[]): AcpEffortConfig | undefined {
123
+ const option =
124
+ configOptions.find((candidate) => candidate.id === "effort") ??
125
+ configOptions.find((candidate) => candidate.category === "thought_level")
126
+ if (!option) return undefined
127
+ const values = (option.options ?? [])
128
+ .map((choice) => choice.value)
129
+ .filter((value): value is string => typeof value === "string" && value.length > 0)
130
+ if (!values.length) return undefined
131
+ return {
132
+ configId: option.id ?? "effort",
133
+ name: option.name,
134
+ currentValue: option.currentValue,
135
+ values,
136
+ }
137
+ }
138
+
139
+ export interface AcpClientOptions {
140
+ command: string
141
+ args?: string[]
142
+ cwd: string
143
+ env?: Record<string, string>
144
+ /** Log stderr and protocol errors through this callback. */
145
+ onLog?: (level: "debug" | "warn" | "error", message: string) => void
146
+ /** Called when the agent process exits unexpectedly, so callers can drop stale sessions. */
147
+ onExit?: (error: Error) => void
148
+ /**
149
+ * Called with the full command list whenever the agent advertises one for a
150
+ * session. Agents send this during `session/new` and can replace it later.
151
+ */
152
+ onCommands?: (sessionId: string, commands: AcpCommand[]) => void
153
+ /**
154
+ * Auto-approve real `session/request_permission` requests. Questions that an
155
+ * agent encodes as permission requests are declined instead. Defaults to true.
156
+ */
157
+ autoApprove?: boolean
158
+ /** Timeout for handshake and control calls. Defaults to 15s; 0 disables. */
159
+ requestTimeoutMs?: number
160
+ /** Timeout for one prompt turn. Defaults to 30 minutes; 0 disables. */
161
+ promptTimeoutMs?: number
162
+ /** Allow filesystem methods to touch paths outside the session directory. Defaults to false. */
163
+ allowPathsOutsideCwd?: boolean
164
+ /** Largest file the client will read for the agent. Defaults to 16 MB. */
165
+ maxFileBytes?: number
166
+ }
167
+
168
+ interface RpcMessage {
169
+ jsonrpc?: string
170
+ id?: number | string
171
+ method?: string
172
+ params?: any
173
+ result?: any
174
+ error?: { code: number; message: string; data?: unknown }
175
+ }
176
+
177
+ type Pending = { resolve: (value: any) => void; reject: (reason: Error) => void; method: string }
178
+
179
+ interface SessionState {
180
+ cwd: string
181
+ /** Extra directories granted at session/new; readable through client fs. */
182
+ additionalDirectories?: string[]
183
+ configOptions: AcpConfigOption[]
184
+ onUpdate?: (update: SessionUpdate) => void
185
+ requestPermission?: PermissionHandler
186
+ }
187
+
188
+ interface RequestOptions {
189
+ timeout?: number
190
+ signal?: AbortSignal
191
+ /** Runs when the signal aborts, e.g. to send `session/cancel`. */
192
+ onAbort?: () => void
193
+ /** How long to wait for a reply after abort before rejecting. Defaults to 5s. */
194
+ abortGraceMs?: number
195
+ }
196
+
197
+ const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
198
+ const DEFAULT_PROMPT_TIMEOUT_MS = 30 * 60_000
199
+ const DEFAULT_ABORT_GRACE_MS = 5_000
200
+ const DEFAULT_MAX_FILE_BYTES = 16 * 1024 * 1024
201
+ const MAX_PROTOCOL_BUFFER = 64 * 1024 * 1024
202
+ const MAX_STDERR_BUFFER = 1024 * 1024
203
+ const SIGKILL_DELAY_MS = 2_000
204
+ /** JSON-RPC error code for a request that was cancelled. */
205
+ export const ACP_REQUEST_CANCELLED = -32800
206
+
207
+ /** `session/new`, `session/resume`, and `session/load` share these fields. */
208
+ function sessionParams(options: { mcpServers?: AcpMcpServer[]; additionalDirectories?: string[]; meta?: Record<string, unknown> }) {
209
+ return {
210
+ mcpServers: options.mcpServers ?? [],
211
+ ...(options.additionalDirectories?.length ? { additionalDirectories: options.additionalDirectories } : {}),
212
+ ...(options.meta ? { _meta: options.meta } : {}),
213
+ }
214
+ }
215
+
216
+ export class AcpError extends Error {
217
+ code: number
218
+ data: unknown
219
+ constructor(message: string, code = -32000, data?: unknown) {
220
+ super(message)
221
+ this.name = "AcpError"
222
+ this.code = code
223
+ this.data = data
224
+ }
225
+ }
226
+
227
+ export class AcpClient {
228
+ private child?: ChildProcessWithoutNullStreams
229
+ private buffer = ""
230
+ private stderrBuffer = ""
231
+ private nextID = 1
232
+ private pending = new Map<number | string, Pending>()
233
+ private sessions = new Map<string, SessionState>()
234
+ /** Slash commands each session advertised in `available_commands_update`. */
235
+ private commands = new Map<string, AcpCommand[]>()
236
+ /** Callers waiting for a session's first command list. */
237
+ private commandWaiters = new Map<string, (commands: AcpCommand[] | undefined) => void>()
238
+ private started?: Promise<AgentHandshake>
239
+ private handshake?: AgentHandshake
240
+ private closed = false
241
+ private disposed = false
242
+ private readonly options: AcpClientOptions
243
+
244
+ constructor(options: AcpClientOptions) {
245
+ this.options = options
246
+ }
247
+
248
+ private log(level: "debug" | "warn" | "error", message: string) {
249
+ this.options.onLog?.(level, message)
250
+ }
251
+
252
+ /** Spawn the agent and run the ACP initialize handshake, restarting if it died. */
253
+ start(): Promise<AgentHandshake> {
254
+ if (this.disposed) return Promise.reject(new AcpError("ACP client stopped"))
255
+ if (!this.started) {
256
+ const started = this.doStart()
257
+ this.started = started
258
+ started.catch(() => {
259
+ if (this.started === started) this.started = undefined
260
+ })
261
+ }
262
+ return this.started
263
+ }
264
+
265
+ private async doStart(): Promise<AgentHandshake> {
266
+ const detached = process.platform !== "win32"
267
+ const child = spawn(this.options.command, this.options.args ?? [], {
268
+ cwd: this.options.cwd,
269
+ env: { ...process.env, ...this.options.env },
270
+ stdio: ["pipe", "pipe", "pipe"],
271
+ // POSIX: give the agent its own process group so wrappers such as
272
+ // `npx` can be stopped together with the agent they launch.
273
+ detached,
274
+ })
275
+ this.child = child
276
+ this.closed = false
277
+ this.buffer = ""
278
+ this.stderrBuffer = ""
279
+
280
+ const current = () => this.child === child && !this.disposed
281
+ const exitWith = (error: Error) => {
282
+ if (this.child !== child) return
283
+ // A broken pipe can precede process exit (or the agent can stay alive).
284
+ if (child.pid && child.exitCode === null && child.signalCode === null) this.killChild(child, "SIGKILL")
285
+ this.handleExit(error)
286
+ }
287
+
288
+ child.stdout.setEncoding("utf8")
289
+ child.stdout.on("data", (chunk: string) => {
290
+ if (current()) this.onData(chunk)
291
+ })
292
+ child.stderr.setEncoding("utf8")
293
+ child.stderr.on("data", (chunk: string) => {
294
+ if (current()) this.onStderr(chunk)
295
+ })
296
+ child.on("exit", (code, signal) => {
297
+ exitWith(new AcpError(`ACP agent exited (code=${code ?? "null"}, signal=${signal ?? "null"})`))
298
+ })
299
+ child.on("error", (error) => exitWith(error))
300
+ // Writing to an agent that closed stdin emits EPIPE asynchronously; without
301
+ // a listener that becomes an uncaught exception in the OpenCode process.
302
+ child.stdin.on("error", (error) => {
303
+ this.log("warn", `ACP agent stdin failed: ${error.message}`)
304
+ exitWith(new AcpError(`ACP agent stdin failed: ${error.message}`))
305
+ })
306
+ child.stdout.on("error", (error) => exitWith(error))
307
+ child.stderr.on("error", (error) => this.log("warn", `ACP agent stderr failed: ${error.message}`))
308
+
309
+ try {
310
+ const result = await this.request(
311
+ "initialize",
312
+ {
313
+ protocolVersion: 1,
314
+ clientCapabilities: {
315
+ fs: { readTextFile: true, writeTextFile: true },
316
+ terminal: false,
317
+ },
318
+ clientInfo: { name: "opencode", version: "2" },
319
+ },
320
+ )
321
+
322
+ if (!current()) throw new AcpError("ACP agent stopped during initialization")
323
+ this.handshake = {
324
+ protocolVersion: result?.protocolVersion ?? 1,
325
+ agentInfo: result?.agentInfo,
326
+ agentCapabilities: result?.agentCapabilities ?? {},
327
+ authMethods: result?.authMethods ?? [],
328
+ }
329
+ this.log("debug", `initialized ACP agent ${JSON.stringify(this.handshake.agentInfo ?? {})}`)
330
+ return this.handshake
331
+ } catch (error) {
332
+ // Keep start() single-flight until this child is reaped, including on a
333
+ // timeout where the agent did not exit or close any streams.
334
+ if (child.pid && child.exitCode === null && child.signalCode === null) {
335
+ const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()))
336
+ this.killChild(child, "SIGKILL")
337
+ await exited
338
+ }
339
+ throw error
340
+ }
341
+ }
342
+
343
+ private handleExit(error: Error) {
344
+ const report = !this.closed && !this.disposed
345
+ this.closed = true
346
+ this.child = undefined
347
+ if (this.handshake) this.started = undefined
348
+ this.handshake = undefined
349
+ this.buffer = ""
350
+ this.stderrBuffer = ""
351
+ this.sessions.clear()
352
+ const pending = [...this.pending.values()]
353
+ this.pending.clear()
354
+ for (const entry of pending) entry.reject(error)
355
+ if (report) {
356
+ this.log("warn", error.message)
357
+ this.options.onExit?.(error)
358
+ }
359
+ }
360
+
361
+ private onData(chunk: string) {
362
+ this.buffer += chunk
363
+ if (this.buffer.length > MAX_PROTOCOL_BUFFER && this.buffer.lastIndexOf("\n") < 0) {
364
+ this.log("error", `dropping oversized ACP output (${this.buffer.length} bytes without a newline)`)
365
+ this.buffer = ""
366
+ return
367
+ }
368
+ let index: number
369
+ while ((index = this.buffer.indexOf("\n")) >= 0) {
370
+ const line = this.buffer.slice(0, index).trim()
371
+ this.buffer = this.buffer.slice(index + 1)
372
+ if (!line) continue
373
+ let message: RpcMessage
374
+ try {
375
+ message = JSON.parse(line)
376
+ } catch {
377
+ this.log("warn", `ignoring non-JSON ACP output: ${line.slice(0, 200)}`)
378
+ continue
379
+ }
380
+ this.onMessage(message)
381
+ }
382
+ }
383
+
384
+ private onStderr(chunk: string) {
385
+ this.stderrBuffer += chunk
386
+ if (this.stderrBuffer.length > MAX_STDERR_BUFFER && this.stderrBuffer.lastIndexOf("\n") < 0) {
387
+ this.log("debug", this.stderrBuffer.slice(0, 2_000))
388
+ this.log("debug", `dropping oversized ACP stderr (${this.stderrBuffer.length} bytes without a newline)`)
389
+ this.stderrBuffer = ""
390
+ return
391
+ }
392
+ let index: number
393
+ while ((index = this.stderrBuffer.indexOf("\n")) >= 0) {
394
+ const line = this.stderrBuffer.slice(0, index).trim()
395
+ this.stderrBuffer = this.stderrBuffer.slice(index + 1)
396
+ if (line) this.log("debug", line)
397
+ }
398
+ }
399
+
400
+ private onMessage(message: RpcMessage) {
401
+ if (message.method && message.id !== undefined) {
402
+ void this.onRequest(message).catch((error) => {
403
+ this.log("error", `ACP request handler failed: ${errorMessage(error)}`)
404
+ })
405
+ return
406
+ }
407
+ if (message.method) {
408
+ this.onNotification(message)
409
+ return
410
+ }
411
+ if (message.id === undefined) return
412
+ const pending = this.pending.get(message.id)
413
+ if (!pending) return
414
+ this.pending.delete(message.id)
415
+ if (message.error) {
416
+ pending.reject(new AcpError(message.error.message, message.error.code, message.error.data))
417
+ } else {
418
+ pending.resolve(message.result ?? {})
419
+ }
420
+ }
421
+
422
+ private onNotification(message: RpcMessage) {
423
+ if (message.method !== "session/update") {
424
+ this.log("debug", `ACP notification ${message.method}`)
425
+ return
426
+ }
427
+ const sessionId = message.params?.sessionId
428
+ const update = message.params?.update as SessionUpdate | undefined
429
+ if (!sessionId || !update) return
430
+ // Kept outside `sessions`: the list can arrive before `session/new` resolves.
431
+ if (update.sessionUpdate === "available_commands_update" && Array.isArray(update.availableCommands)) {
432
+ const commands: AcpCommand[] = []
433
+ for (const command of update.availableCommands as Array<{ name?: unknown; description?: unknown; input?: unknown }>) {
434
+ if (typeof command?.name !== "string" || !command.name) continue
435
+ const hint = (command.input as { hint?: unknown } | null | undefined)?.hint
436
+ commands.push({
437
+ name: command.name,
438
+ ...(typeof command.description === "string" && command.description ? { description: command.description } : {}),
439
+ ...(typeof hint === "string" && hint ? { hint } : {}),
440
+ })
441
+ }
442
+ this.commands.set(sessionId, commands)
443
+ this.commandWaiters.get(sessionId)?.(commands)
444
+ this.options.onCommands?.(sessionId, commands)
445
+ } else if (update.sessionUpdate === "usage_update") {
446
+ this.log(
447
+ "debug",
448
+ `ACP context for ${sessionId}: ${update.used ?? "?"}/${update.size ?? "?"} tokens, cost ${JSON.stringify(update.cost ?? null)}`,
449
+ )
450
+ }
451
+ this.sessions.get(sessionId)?.onUpdate?.(update)
452
+ }
453
+
454
+ private async onRequest(message: RpcMessage) {
455
+ const method = message.method!
456
+ try {
457
+ if (method === "session/request_permission") {
458
+ const params = message.params ?? {}
459
+ const options: Array<{ optionId?: string; kind?: string }> = params.options ?? []
460
+
461
+ const question = readQuestionText(params, options)
462
+ if (question) {
463
+ // Native ask-user tools are supposed to be disabled in favour of the
464
+ // MCP `question` tool. Never auto-approve one: the first option is an
465
+ // answer, not permission.
466
+ this.log("debug", `declining native ACP question: ${question}`)
467
+ this.reply(message.id!, { outcome: { outcome: "cancelled" } })
468
+ return
469
+ }
470
+
471
+ const allow =
472
+ options.find((option) => option.optionId === "allow_once") ??
473
+ options.find((option) => option.optionId?.startsWith("allow")) ??
474
+ options.find((option) => option.kind?.startsWith("allow")) ??
475
+ options[0]
476
+ const info: PermissionRequestInfo = {
477
+ title: params.toolCall?.title ?? allow?.optionId ?? "ACP tool",
478
+ kind: params.toolCall?.kind,
479
+ detail: readToolCallText(params.toolCall?.content),
480
+ }
481
+ const handler = this.sessions.get(params.sessionId)?.requestPermission
482
+ const approved =
483
+ this.options.autoApprove !== false
484
+ ? Boolean(allow)
485
+ : handler
486
+ ? await handler(info).catch(() => false)
487
+ : false
488
+ if (!approved || !allow?.optionId) {
489
+ this.reply(message.id!, { outcome: { outcome: "cancelled" } })
490
+ return
491
+ }
492
+ this.log("debug", `approving ACP permission: ${info.title}`)
493
+ this.reply(message.id!, { outcome: { outcome: "selected", optionId: allow.optionId } })
494
+ return
495
+ }
496
+
497
+ if (method === "fs/read_text_file") {
498
+ const content = await this.readTextFile(message.params ?? {})
499
+ this.reply(message.id!, { content })
500
+ return
501
+ }
502
+
503
+ if (method === "fs/write_text_file") {
504
+ await this.writeTextFile(message.params ?? {})
505
+ this.reply(message.id!, {})
506
+ return
507
+ }
508
+
509
+ this.log("warn", `unsupported ACP client method: ${method}`)
510
+ this.reply(message.id!, undefined, -32601, `Method not supported by client: ${method}`)
511
+ } catch (error) {
512
+ const text = errorMessage(error)
513
+ const code = error instanceof AcpError ? error.code : -32603
514
+ this.reply(message.id!, undefined, code, text)
515
+ }
516
+ }
517
+
518
+ private reply(id: number | string, result: any, errorCode?: number, errorMessage?: string) {
519
+ try {
520
+ if (errorCode !== undefined) {
521
+ this.write({ jsonrpc: "2.0", id, error: { code: errorCode, message: errorMessage ?? "error" } })
522
+ } else {
523
+ this.write({ jsonrpc: "2.0", id, result })
524
+ }
525
+ } catch {
526
+ // The agent is gone; there is nobody left to answer.
527
+ }
528
+ }
529
+
530
+ private write(message: RpcMessage) {
531
+ const child = this.child
532
+ if (!child || this.closed || !child.stdin.writable) throw new AcpError("ACP agent is not running")
533
+ child.stdin.write(`${JSON.stringify(message)}\n`)
534
+ }
535
+
536
+ request(method: string, params?: unknown, options: RequestOptions = {}) {
537
+ const id = this.nextID++
538
+ const startedAt = performance.now()
539
+ return new Promise<any>((resolveValue, rejectValue) => {
540
+ let timer: ReturnType<typeof setTimeout> | undefined
541
+ let graceTimer: ReturnType<typeof setTimeout> | undefined
542
+ let abortListener: (() => void) | undefined
543
+
544
+ const cleanup = () => {
545
+ if (timer) clearTimeout(timer)
546
+ if (graceTimer) clearTimeout(graceTimer)
547
+ if (abortListener) options.signal?.removeEventListener("abort", abortListener)
548
+ this.pending.delete(id)
549
+ const elapsed = Math.round(performance.now() - startedAt)
550
+ this.log(
551
+ method !== "session/prompt" && elapsed >= 1_000 ? "warn" : "debug",
552
+ `ACP request ${method} settled in ${elapsed}ms`,
553
+ )
554
+ }
555
+ const succeed = (value: any) => {
556
+ cleanup()
557
+ resolveValue(value)
558
+ }
559
+ const fail = (error: Error) => {
560
+ cleanup()
561
+ rejectValue(error)
562
+ }
563
+
564
+ this.pending.set(id, { resolve: succeed, reject: fail, method })
565
+
566
+ const timeout = options.timeout ?? this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
567
+ if (timeout > 0 && Number.isFinite(timeout)) {
568
+ timer = setTimeout(
569
+ () => fail(new AcpError(`ACP request "${method}" timed out after ${timeout}ms`, -32001)),
570
+ timeout,
571
+ )
572
+ timer.unref?.()
573
+ }
574
+
575
+ if (options.signal) {
576
+ const onAbort = () => {
577
+ try {
578
+ options.onAbort?.()
579
+ } catch {
580
+ // the agent may already be gone
581
+ }
582
+ const grace = options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS
583
+ graceTimer = setTimeout(
584
+ () => fail(new AcpError(`ACP request "${method}" was cancelled`, ACP_REQUEST_CANCELLED)),
585
+ Math.max(0, grace),
586
+ )
587
+ graceTimer.unref?.()
588
+ }
589
+ if (options.signal.aborted) onAbort()
590
+ else {
591
+ abortListener = onAbort
592
+ options.signal.addEventListener("abort", abortListener, { once: true })
593
+ }
594
+ }
595
+
596
+ try {
597
+ this.write({ jsonrpc: "2.0", id, method, params })
598
+ } catch (error) {
599
+ fail(error instanceof Error ? error : new Error(String(error)))
600
+ }
601
+ })
602
+ }
603
+
604
+ notify(method: string, params?: unknown) {
605
+ this.write({ jsonrpc: "2.0", method, params })
606
+ }
607
+
608
+ /**
609
+ * Create a session and return its id plus the selectable models and reasoning
610
+ * effort levels advertised by the agent through `configOptions`.
611
+ */
612
+ async newSession(
613
+ cwd: string,
614
+ options: {
615
+ model?: string
616
+ effort?: string
617
+ mcpServers?: AcpMcpServer[]
618
+ additionalDirectories?: string[]
619
+ meta?: Record<string, unknown>
620
+ } = {},
621
+ ) {
622
+ await this.start()
623
+ const result = await this.request("session/new", { cwd, ...sessionParams(options) })
624
+ const sessionId: string = result.sessionId
625
+ if (!sessionId) throw new AcpError("ACP agent did not return a session id", -32603)
626
+ const configOptions: AcpConfigOption[] = result.configOptions ?? []
627
+ const modelOption = configOptions.find((option) => option.category === "model" || option.id === "model")
628
+ const models: Array<{ id: string; name: string; description?: string }> = (modelOption?.options ?? [])
629
+ .filter((option): option is { value: string; name?: string; description?: string } => {
630
+ return typeof option.value === "string" && option.value.length > 0
631
+ })
632
+ .map((option) => ({
633
+ id: option.value,
634
+ name: option.name || option.value,
635
+ description: option.description,
636
+ }))
637
+ const effort = readEffortConfig(configOptions)
638
+
639
+ this.sessions.set(sessionId, { cwd, additionalDirectories: options.additionalDirectories, configOptions })
640
+
641
+ try {
642
+ if (options.model && !modelOption) throw new AcpError("Agent does not expose an ACP model selector", -32602)
643
+ if (options.model && modelOption && options.model !== modelOption.currentValue) {
644
+ await this.setModel(sessionId, options.model, modelOption.id ?? "model")
645
+ }
646
+ if (options.effort && effort && options.effort !== effort.currentValue) {
647
+ await this.setEffort(sessionId, options.effort, effort.configId)
648
+ }
649
+ } catch (error) {
650
+ // The agent already created the session; close it so a rejected model or
651
+ // effort does not leak an ACP session that nobody can address anymore.
652
+ await this.closeSession(sessionId).catch(() => {})
653
+ throw error
654
+ }
655
+
656
+ return {
657
+ sessionId,
658
+ configOptions,
659
+ models,
660
+ modelConfigID: modelOption ? modelOption.id ?? "model" : undefined,
661
+ currentModel: options.model ?? modelOption?.currentValue,
662
+ efforts: effort?.values ?? [],
663
+ effort,
664
+ modes: result.modes,
665
+ }
666
+ }
667
+
668
+ /**
669
+ * Reattach to a session the agent persisted in an earlier process, keeping
670
+ * the conversation it holds. `session/resume` restores without replaying the
671
+ * transcript; `session/load` replays it, and those updates are ignored here
672
+ * because OpenCode already shows the conversation. Returns undefined when
673
+ * the agent advertises neither capability.
674
+ */
675
+ async restoreSession(
676
+ sessionId: string,
677
+ options: {
678
+ cwd: string
679
+ mcpServers?: AcpMcpServer[]
680
+ additionalDirectories?: string[]
681
+ meta?: Record<string, unknown>
682
+ },
683
+ ): Promise<"resumed" | "loaded" | undefined> {
684
+ const capabilities = (await this.start()).agentCapabilities
685
+ const resume = capabilities?.sessionCapabilities?.resume !== undefined
686
+ const load = capabilities?.loadSession === true
687
+ if (!resume && !load) return undefined
688
+ const timeout = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
689
+ const result = await this.request(
690
+ resume ? "session/resume" : "session/load",
691
+ { sessionId, cwd: options.cwd, ...sessionParams(options) },
692
+ // Replaying a long conversation through session/load is not a control call.
693
+ { timeout: resume ? timeout : Math.max(60_000, timeout) },
694
+ )
695
+ this.sessions.set(sessionId, {
696
+ cwd: options.cwd,
697
+ additionalDirectories: options.additionalDirectories,
698
+ configOptions: result.configOptions ?? [],
699
+ })
700
+ return resume ? "resumed" : "loaded"
701
+ }
702
+
703
+ /** Whether this client still holds the ACP session and can take another prompt. */
704
+ hasSession(sessionId: string) {
705
+ return this.sessions.has(sessionId)
706
+ }
707
+
708
+ /** Whether the agent process is running and usable. */
709
+ get alive() {
710
+ return Boolean(this.child) && !this.closed && !this.disposed
711
+ }
712
+
713
+ configOption(sessionId: string, category: string) {
714
+ return this.sessions.get(sessionId)?.configOptions.find((option) => option.category === category)
715
+ }
716
+
717
+ async setModel(sessionId: string, modelId: string, configId = "model") {
718
+ return this.setConfigOption(sessionId, this.configOption(sessionId, "model")?.id ?? configId, modelId)
719
+ }
720
+ /** Set the agent's reasoning effort for a session. */
721
+ async setEffort(sessionId: string, effort: string, configId = "effort") {
722
+ return this.setConfigOption(sessionId, this.configOption(sessionId, "thought_level")?.id ?? configId, effort)
723
+ }
724
+
725
+ /** Set any agent-advertised session config option, e.g. "model" or "effort". */
726
+ async setConfigOption(sessionId: string, configId: string, value: string) {
727
+ const session = this.sessions.get(sessionId)
728
+ const option = session?.configOptions.find((option) => option.id === configId)
729
+ if (option?.currentValue === value) return
730
+ const result = await this.request("session/set_config_option", { sessionId, configId, value })
731
+ if (session) {
732
+ session.configOptions = Array.isArray(result.configOptions)
733
+ ? result.configOptions
734
+ : session.configOptions.map((current) => {
735
+ if (current.id === configId) return { ...current, currentValue: value }
736
+ // A model switch can reset effort; do not retain an unconfirmed value.
737
+ if (option?.category === "model" && current.category === "thought_level") {
738
+ return { ...current, currentValue: undefined }
739
+ }
740
+ return current
741
+ })
742
+ }
743
+ return result
744
+ }
745
+
746
+ async setMode(sessionId: string, modeId: string) {
747
+ return this.request("session/set_mode", { sessionId, modeId })
748
+ }
749
+
750
+ /** Send a prompt turn and stream `session/update` notifications. */
751
+ async prompt(
752
+ sessionId: string,
753
+ prompt: string | ContentBlock[],
754
+ handlers: {
755
+ onUpdate?: (update: SessionUpdate) => void
756
+ signal?: AbortSignal
757
+ requestPermission?: PermissionHandler
758
+ } = {},
759
+ ): Promise<PromptResult> {
760
+ if (handlers.signal?.aborted) return { stopReason: "cancelled", text: "" }
761
+ const blocks: ContentBlock[] = typeof prompt === "string" ? [{ type: "text", text: prompt }] : prompt
762
+ const session = this.sessions.get(sessionId)
763
+ if (!session) throw new AcpError(`Unknown ACP session: ${sessionId}`)
764
+ session.requestPermission = handlers.requestPermission
765
+
766
+ let text = ""
767
+ const onUpdate = (update: SessionUpdate) => {
768
+ if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text") {
769
+ text += update.content.text ?? ""
770
+ }
771
+ handlers.onUpdate?.(update)
772
+ }
773
+ session.onUpdate = onUpdate
774
+
775
+ const promptTimeout = this.options.promptTimeoutMs ?? DEFAULT_PROMPT_TIMEOUT_MS
776
+ try {
777
+ const result = await this.request(
778
+ "session/prompt",
779
+ { sessionId, prompt: blocks },
780
+ {
781
+ timeout: promptTimeout,
782
+ signal: handlers.signal,
783
+ onAbort: () => this.cancelTurn(sessionId),
784
+ },
785
+ )
786
+ // Usage stays in the debug log: no ACP number is right for both of the
787
+ // ways OpenCode reads a step's tokens (context size and spend).
788
+ if (result?.usage || result?._meta?.usage) {
789
+ this.log(
790
+ "debug",
791
+ `ACP turn usage for ${sessionId}: ${JSON.stringify(result.usage ?? null)} turn=${JSON.stringify(result._meta?.usage ?? null)}`,
792
+ )
793
+ }
794
+ return { stopReason: result?.stopReason ?? "end_turn", text }
795
+ } finally {
796
+ const current = this.sessions.get(sessionId)
797
+ if (current?.onUpdate === onUpdate) {
798
+ current.onUpdate = undefined
799
+ current.requestPermission = undefined
800
+ }
801
+ }
802
+ }
803
+
804
+ /** Ask the agent to end the running turn; `session/prompt` then resolves with `cancelled`. */
805
+ cancelTurn(sessionId: string) {
806
+ try {
807
+ this.notify("session/cancel", { sessionId })
808
+ } catch {
809
+ // the agent is already gone
810
+ }
811
+ }
812
+
813
+ /** Whether the agent advertised this slash command for the session. */
814
+ hasCommand(sessionId: string, name: string) {
815
+ return this.commands.get(sessionId)?.some((command) => command.name === name) === true
816
+ }
817
+
818
+ /**
819
+ * Resolve once the agent advertised a command list for this session, so a
820
+ * caller that is about to close a discovery session does not race the
821
+ * notification, which arrives separately from the `session/new` result.
822
+ * Resolves `undefined` if nothing arrives in time.
823
+ */
824
+ waitForCommands(sessionId: string, timeoutMs: number): Promise<AcpCommand[] | undefined> {
825
+ const known = this.commands.get(sessionId)
826
+ if (known) return Promise.resolve(known)
827
+ return new Promise((resolve) => {
828
+ let timer: ReturnType<typeof setTimeout> | undefined
829
+ const finish = (commands: AcpCommand[] | undefined) => {
830
+ if (timer) clearTimeout(timer)
831
+ this.commandWaiters.delete(sessionId)
832
+ resolve(commands)
833
+ }
834
+ this.commandWaiters.set(sessionId, finish)
835
+ if (timeoutMs > 0) {
836
+ timer = setTimeout(() => finish(undefined), timeoutMs)
837
+ timer.unref?.()
838
+ }
839
+ })
840
+ }
841
+
842
+ async closeSession(sessionId: string) {
843
+ this.sessions.delete(sessionId)
844
+ this.commands.delete(sessionId)
845
+ this.commandWaiters.delete(sessionId)
846
+ if (this.handshake?.agentCapabilities?.sessionCapabilities?.close === false) {
847
+ // The agent has no close method; dropping our side is all we can do.
848
+ this.log("debug", `dropping ACP session ${sessionId} (agent does not support session/close)`)
849
+ return
850
+ }
851
+ try {
852
+ await this.request("session/close", { sessionId })
853
+
854
+ } catch {
855
+ // close is best effort
856
+ }
857
+ }
858
+
859
+ async stop() {
860
+ if (this.disposed) return
861
+ this.disposed = true
862
+ this.closed = true
863
+ this.started = undefined
864
+ this.handshake = undefined
865
+ this.sessions.clear()
866
+ this.buffer = ""
867
+ this.stderrBuffer = ""
868
+ const pending = [...this.pending.values()]
869
+ this.pending.clear()
870
+ for (const entry of pending) entry.reject(new AcpError("ACP client stopped"))
871
+ const child = this.child
872
+ this.child = undefined
873
+ if (child) {
874
+ this.killChild(child, "SIGTERM")
875
+ const timer = setTimeout(() => {
876
+ if (child.exitCode === null && child.signalCode === null) this.killChild(child, "SIGKILL")
877
+ }, SIGKILL_DELAY_MS)
878
+ timer.unref?.()
879
+ }
880
+ }
881
+
882
+ /** Kill the agent and, on POSIX, any wrapper it launched in its process group. */
883
+ private killChild(child: ChildProcessWithoutNullStreams, signal: NodeJS.Signals) {
884
+ if (process.platform !== "win32" && child.pid) {
885
+ try {
886
+ process.kill(-child.pid, signal)
887
+ return
888
+ } catch {
889
+ // no process group (not detached, or it already exited)
890
+ }
891
+ }
892
+ try {
893
+ child.kill(signal)
894
+ } catch {
895
+ // already gone
896
+ }
897
+ }
898
+
899
+ // ---- filesystem methods -------------------------------------------------
900
+
901
+ private async readTextFile(params: { sessionId?: string; path?: string; line?: number; limit?: number }) {
902
+ const target = await this.resolveTarget(params.sessionId, String(params.path ?? ""), "read")
903
+ if (!target) throw new AcpError("fs/read_text_file requires a path", -32602)
904
+ const line = typeof params.line === "number" && params.line > 0 ? Math.floor(params.line) : undefined
905
+ const limit = typeof params.limit === "number" && params.limit > 0 ? Math.floor(params.limit) : undefined
906
+ const maxBytes = this.options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES
907
+ if (line !== undefined || limit !== undefined) {
908
+ return (await readLines(target, line ? line - 1 : 0, limit ?? Infinity, maxBytes)).join("\n")
909
+ }
910
+ const info = await stat(target).catch(() => undefined)
911
+ if (info && info.size > maxBytes) {
912
+ throw new AcpError(`File is larger than ${maxBytes} bytes; request a line range instead`, -32603)
913
+ }
914
+ return await readFile(target, "utf8")
915
+ }
916
+
917
+ private async writeTextFile(params: { sessionId?: string; path?: string; content?: string }) {
918
+ const target = await this.resolveTarget(params.sessionId, String(params.path ?? ""), "write")
919
+ if (!target) throw new AcpError("fs/write_text_file requires a path", -32602)
920
+ await mkdir(dirname(target), { recursive: true })
921
+ await writeFile(target, params.content ?? "", "utf8")
922
+ }
923
+
924
+ /**
925
+ * Resolve a path from the agent against the session directory and enforce the
926
+ * sandbox. Returning the resolved path matters: checking one path and then
927
+ * reading a relative one would touch the process cwd instead.
928
+ *
929
+ * Reads may also reach the session's additional directories (the skills
930
+ * mirror); writes stay inside the session cwd. A root is matched both as
931
+ * given and through its real path, because agents send absolute paths built
932
+ * from the cwd they were given, which may run through a symlink such as
933
+ * macOS `/var` -> `/private/var`.
934
+ */
935
+ private async resolveTarget(sessionId: string | undefined, target: string, access: "read" | "write"): Promise<string> {
936
+ const raw = target.trim()
937
+ if (!raw) return ""
938
+ const session = sessionId ? this.sessions.get(sessionId) : undefined
939
+ const root = session?.cwd
940
+ if (this.options.allowPathsOutsideCwd) {
941
+ return resolve(root ?? process.cwd(), raw)
942
+ }
943
+ if (!root) {
944
+ throw new AcpError("filesystem access requires a known session root", -32602)
945
+ }
946
+ const roots = access === "read" ? [root, ...(session?.additionalDirectories ?? [])] : [root]
947
+ const allowed = await Promise.all(
948
+ roots.map(async (entry) => {
949
+ const lexical = resolve(entry)
950
+ return { lexical, real: await realpath(lexical).catch(() => lexical) }
951
+ }),
952
+ )
953
+ const resolvedTarget = resolve(root, raw)
954
+ if (!allowed.some(({ lexical, real }) => isInside(lexical, resolvedTarget) || isInside(real, resolvedTarget))) {
955
+ throw new AcpError(`Path is outside the session directory: ${target}`, -32602)
956
+ }
957
+ // Refuse to follow a symlink out of the roots. For a path that does not
958
+ // exist yet, check the deepest existing ancestor: a symlinked parent
959
+ // directory would otherwise let a write escape even though the file itself
960
+ // is new.
961
+ const real = (await realpath(resolvedTarget).catch(() => undefined)) ?? (await realpathExistingAncestor(resolvedTarget))
962
+ if (real && !allowed.some((entry) => isInside(entry.real, real))) {
963
+ throw new AcpError(`Path resolves outside the session directory: ${target}`, -32602)
964
+ }
965
+ return resolvedTarget
966
+ }
967
+ }
968
+
969
+ function isInside(root: string, target: string) {
970
+ const rel = relative(root, target)
971
+ if (rel === "") return true
972
+ // `..env` is a file inside the root; only a `..` segment escapes it.
973
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
974
+ }
975
+
976
+ /**
977
+ * The text of an ACP tool call's content, for the permission prompt. Content
978
+ * entries are `{ type: "content", content: { type: "text", text } }`; diffs
979
+ * carry `path` and `newText`.
980
+ */
981
+ function readToolCallText(content: unknown): string | undefined {
982
+ if (!Array.isArray(content)) return undefined
983
+ const parts: string[] = []
984
+ for (const entry of content) {
985
+ if (!entry || typeof entry !== "object") continue
986
+ const item = entry as Record<string, any>
987
+ if (item.type === "content" && item.content?.type === "text" && typeof item.content.text === "string") {
988
+ parts.push(item.content.text)
989
+ } else if (item.type === "diff" && typeof item.path === "string") {
990
+ parts.push(typeof item.newText === "string" ? `${item.path}\n${item.newText}` : item.path)
991
+ } else if (typeof item.text === "string") {
992
+ parts.push(item.text)
993
+ }
994
+ }
995
+ const text = parts.join("\n").trim()
996
+ if (!text) return undefined
997
+ return text.length > MAX_PERMISSION_DETAIL ? `${text.slice(0, MAX_PERMISSION_DETAIL)}…` : text
998
+ }
999
+
1000
+ const MAX_PERMISSION_DETAIL = 4_000
1001
+
1002
+ /** Resolve the real path of the closest ancestor that exists. */
1003
+ async function realpathExistingAncestor(target: string): Promise<string | undefined> {
1004
+ let current = target
1005
+ for (;;) {
1006
+ const real = await realpath(current).catch(() => undefined)
1007
+ if (real) return real
1008
+ const parent = dirname(current)
1009
+ if (parent === current) return undefined
1010
+ current = parent
1011
+ }
1012
+ }
1013
+
1014
+ async function readLines(path: string, offset: number, limit: number, maxBytes: number) {
1015
+ const stream = createReadStream(path, { encoding: "utf8" })
1016
+ const reader = createInterface({ input: stream, crlfDelay: Infinity })
1017
+ const lines: string[] = []
1018
+ let index = 0
1019
+ let bytes = 0
1020
+ try {
1021
+ for await (const line of reader) {
1022
+ if (index++ < offset) continue
1023
+ lines.push(line)
1024
+ bytes += line.length + 1
1025
+ if (bytes > maxBytes) throw new AcpError(`Requested range is larger than ${maxBytes} bytes`, -32603)
1026
+ if (lines.length >= limit) break
1027
+ }
1028
+ } finally {
1029
+ reader.close()
1030
+ stream.destroy()
1031
+ }
1032
+ return lines
1033
+ }