opencode-acp-provider 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1179 @@
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
+ /**
185
+ * The object that opened this session, usually the server manager. A call
186
+ * matches the session when it passes no owner, when the session has no
187
+ * owner, or when both are the same object; a mismatched call is refused.
188
+ */
189
+ owner?: object
190
+ /**
191
+ * The session's running prompt request, with rejections swallowed, so a new
192
+ * owner can wait for the turn to end before taking the session over.
193
+ */
194
+ turn?: Promise<unknown>
195
+ onUpdate?: (update: SessionUpdate) => void
196
+ requestPermission?: PermissionHandler
197
+ /** Called when this session's command list is advertised. */
198
+ onCommands?: (commands: AcpCommand[]) => void
199
+ }
200
+
201
+ interface RequestOptions {
202
+ timeout?: number
203
+ signal?: AbortSignal
204
+ /** Runs when the signal aborts, e.g. to send `session/cancel`. */
205
+ onAbort?: () => void
206
+ /** How long to wait for a reply after abort before rejecting. Defaults to 5s. */
207
+ abortGraceMs?: number
208
+ }
209
+
210
+ const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
211
+ const DEFAULT_PROMPT_TIMEOUT_MS = 30 * 60_000
212
+ const DEFAULT_ABORT_GRACE_MS = 5_000
213
+ const DEFAULT_MAX_FILE_BYTES = 16 * 1024 * 1024
214
+ const MAX_PROTOCOL_BUFFER = 64 * 1024 * 1024
215
+ const MAX_STDERR_BUFFER = 1024 * 1024
216
+ const SIGKILL_DELAY_MS = 2_000
217
+ /** JSON-RPC error code for a request that was cancelled. */
218
+ export const ACP_REQUEST_CANCELLED = -32800
219
+
220
+ /** `session/new`, `session/resume`, and `session/load` share these fields. */
221
+ function sessionParams(options: { mcpServers?: AcpMcpServer[]; additionalDirectories?: string[]; meta?: Record<string, unknown> }) {
222
+ return {
223
+ mcpServers: options.mcpServers ?? [],
224
+ ...(options.additionalDirectories?.length ? { additionalDirectories: options.additionalDirectories } : {}),
225
+ ...(options.meta ? { _meta: options.meta } : {}),
226
+ }
227
+ }
228
+
229
+ export class AcpError extends Error {
230
+ code: number
231
+ data: unknown
232
+ constructor(message: string, code = -32000, data?: unknown) {
233
+ super(message)
234
+ this.name = "AcpError"
235
+ this.code = code
236
+ this.data = data
237
+ }
238
+ }
239
+
240
+ /** True for an AcpError, including one built by another evaluation of this module. */
241
+ export function isAcpError(error: unknown): error is AcpError {
242
+ return error instanceof AcpError ||
243
+ (error instanceof Error && error.name === "AcpError" && typeof (error as { code?: unknown }).code === "number")
244
+ }
245
+
246
+ export class AcpClient {
247
+ private child?: ChildProcessWithoutNullStreams
248
+ private buffer = ""
249
+ private stderrBuffer = ""
250
+ private nextID = 1
251
+ private pending = new Map<number | string, Pending>()
252
+ private sessions = new Map<string, SessionState>()
253
+ /** Restores in flight per session id, so a takeover runs before the next restore. */
254
+ private restoring = new Map<string, Promise<unknown>>()
255
+ /** Slash commands each session advertised in `available_commands_update`. */
256
+ private commands = new Map<string, AcpCommand[]>()
257
+ /** Callers waiting for a session's first command list. */
258
+ private commandWaiters = new Map<string, (commands: AcpCommand[] | undefined) => void>()
259
+ /** Children signalled by `stop()` that have not reported `exit` yet. */
260
+ private stopping = new Set<ChildProcessWithoutNullStreams>()
261
+ private started?: Promise<AgentHandshake>
262
+ private handshake?: AgentHandshake
263
+ private closed = false
264
+ private disposed = false
265
+ private readonly options: AcpClientOptions
266
+
267
+ constructor(options: AcpClientOptions) {
268
+ this.options = options
269
+ }
270
+
271
+ private log(level: "debug" | "warn" | "error", message: string) {
272
+ this.options.onLog?.(level, message)
273
+ }
274
+
275
+ /**
276
+ * A call may touch a session when it passes no owner, when the session has
277
+ * no owner, or when it passes the session's owner.
278
+ */
279
+ private matchesOwner(session: SessionState | undefined, owner: object | undefined) {
280
+ if (!session) return true
281
+ return owner === undefined || session.owner === undefined || session.owner === owner
282
+ }
283
+
284
+ /** Spawn the agent and run the ACP initialize handshake, restarting if it died. */
285
+ start(): Promise<AgentHandshake> {
286
+ if (this.disposed) return Promise.reject(new AcpError("ACP client stopped"))
287
+ if (!this.started) {
288
+ const started = this.doStart()
289
+ this.started = started
290
+ started.catch(() => {
291
+ if (this.started === started) this.started = undefined
292
+ })
293
+ }
294
+ return this.started
295
+ }
296
+
297
+ private async doStart(): Promise<AgentHandshake> {
298
+ const detached = process.platform !== "win32"
299
+ const child = spawn(this.options.command, this.options.args ?? [], {
300
+ cwd: this.options.cwd,
301
+ env: { ...process.env, ...this.options.env },
302
+ stdio: ["pipe", "pipe", "pipe"],
303
+ // POSIX: give the agent its own process group so wrappers such as
304
+ // `npx` can be stopped together with the agent they launch.
305
+ detached,
306
+ })
307
+ this.child = child
308
+ this.closed = false
309
+ this.buffer = ""
310
+ this.stderrBuffer = ""
311
+
312
+ const current = () => this.child === child && !this.disposed
313
+ const exitWith = (error: Error) => {
314
+ if (this.child !== child) return
315
+ // A broken pipe can precede process exit (or the agent can stay alive).
316
+ if (child.pid && child.exitCode === null && child.signalCode === null) this.killChild(child, "SIGKILL")
317
+ this.handleExit(error)
318
+ }
319
+
320
+ child.stdout.setEncoding("utf8")
321
+ child.stdout.on("data", (chunk: string) => {
322
+ if (current()) this.onData(chunk)
323
+ })
324
+ child.stderr.setEncoding("utf8")
325
+ child.stderr.on("data", (chunk: string) => {
326
+ if (current()) this.onStderr(chunk)
327
+ })
328
+ child.on("exit", (code, signal) => {
329
+ exitWith(new AcpError(`ACP agent exited (code=${code ?? "null"}, signal=${signal ?? "null"})`))
330
+ })
331
+ child.on("error", (error) => exitWith(error))
332
+ // Writing to an agent that closed stdin emits EPIPE asynchronously; without
333
+ // a listener that becomes an uncaught exception in the OpenCode process.
334
+ child.stdin.on("error", (error) => {
335
+ this.log("warn", `ACP agent stdin failed: ${error.message}`)
336
+ exitWith(new AcpError(`ACP agent stdin failed: ${error.message}`))
337
+ })
338
+ child.stdout.on("error", (error) => exitWith(error))
339
+ child.stderr.on("error", (error) => this.log("warn", `ACP agent stderr failed: ${error.message}`))
340
+
341
+ try {
342
+ const result = await this.request(
343
+ "initialize",
344
+ {
345
+ protocolVersion: 1,
346
+ clientCapabilities: {
347
+ fs: { readTextFile: true, writeTextFile: true },
348
+ terminal: false,
349
+ },
350
+ clientInfo: { name: "opencode", version: "2" },
351
+ },
352
+ )
353
+
354
+ if (!current()) throw new AcpError("ACP agent stopped during initialization")
355
+ this.handshake = {
356
+ protocolVersion: result?.protocolVersion ?? 1,
357
+ agentInfo: result?.agentInfo,
358
+ agentCapabilities: result?.agentCapabilities ?? {},
359
+ authMethods: result?.authMethods ?? [],
360
+ }
361
+ this.log("debug", `initialized ACP agent ${JSON.stringify(this.handshake.agentInfo ?? {})}`)
362
+ return this.handshake
363
+ } catch (error) {
364
+ // Keep start() single-flight until this child is reaped, including on a
365
+ // timeout where the agent did not exit or close any streams.
366
+ if (child.pid && child.exitCode === null && child.signalCode === null) {
367
+ const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()))
368
+ this.killChild(child, "SIGKILL")
369
+ await exited
370
+ }
371
+ throw error
372
+ }
373
+ }
374
+
375
+ private handleExit(error: Error) {
376
+ const report = !this.closed && !this.disposed
377
+ this.closed = true
378
+ this.child = undefined
379
+ if (this.handshake) this.started = undefined
380
+ this.handshake = undefined
381
+ this.buffer = ""
382
+ this.stderrBuffer = ""
383
+ this.sessions.clear()
384
+ this.commands.clear()
385
+ for (const finish of [...this.commandWaiters.values()]) finish(undefined)
386
+ this.commandWaiters.clear()
387
+ const pending = [...this.pending.values()]
388
+ this.pending.clear()
389
+ for (const entry of pending) entry.reject(error)
390
+ if (report) {
391
+ this.log("warn", error.message)
392
+ this.options.onExit?.(error)
393
+ }
394
+ }
395
+
396
+ private onData(chunk: string) {
397
+ this.buffer += chunk
398
+ if (this.buffer.length > MAX_PROTOCOL_BUFFER && this.buffer.lastIndexOf("\n") < 0) {
399
+ this.log("error", `dropping oversized ACP output (${this.buffer.length} bytes without a newline)`)
400
+ this.buffer = ""
401
+ return
402
+ }
403
+ let index: number
404
+ while ((index = this.buffer.indexOf("\n")) >= 0) {
405
+ const line = this.buffer.slice(0, index).trim()
406
+ this.buffer = this.buffer.slice(index + 1)
407
+ if (!line) continue
408
+ let message: RpcMessage
409
+ try {
410
+ message = JSON.parse(line)
411
+ } catch {
412
+ this.log("warn", `ignoring non-JSON ACP output: ${line.slice(0, 200)}`)
413
+ continue
414
+ }
415
+ this.onMessage(message)
416
+ }
417
+ }
418
+
419
+ private onStderr(chunk: string) {
420
+ this.stderrBuffer += chunk
421
+ if (this.stderrBuffer.length > MAX_STDERR_BUFFER && this.stderrBuffer.lastIndexOf("\n") < 0) {
422
+ this.log("debug", this.stderrBuffer.slice(0, 2_000))
423
+ this.log("debug", `dropping oversized ACP stderr (${this.stderrBuffer.length} bytes without a newline)`)
424
+ this.stderrBuffer = ""
425
+ return
426
+ }
427
+ let index: number
428
+ while ((index = this.stderrBuffer.indexOf("\n")) >= 0) {
429
+ const line = this.stderrBuffer.slice(0, index).trim()
430
+ this.stderrBuffer = this.stderrBuffer.slice(index + 1)
431
+ if (line) this.log("debug", line)
432
+ }
433
+ }
434
+
435
+ private onMessage(message: RpcMessage) {
436
+ if (message.method && message.id !== undefined) {
437
+ void this.onRequest(message).catch((error) => {
438
+ this.log("error", `ACP request handler failed: ${errorMessage(error)}`)
439
+ })
440
+ return
441
+ }
442
+ if (message.method) {
443
+ this.onNotification(message)
444
+ return
445
+ }
446
+ if (message.id === undefined) return
447
+ const pending = this.pending.get(message.id)
448
+ if (!pending) return
449
+ this.pending.delete(message.id)
450
+ if (message.error) {
451
+ pending.reject(new AcpError(message.error.message, message.error.code, message.error.data))
452
+ } else {
453
+ pending.resolve(message.result ?? {})
454
+ }
455
+ }
456
+
457
+ private onNotification(message: RpcMessage) {
458
+ if (message.method !== "session/update") {
459
+ this.log("debug", `ACP notification ${message.method}`)
460
+ return
461
+ }
462
+ const sessionId = message.params?.sessionId
463
+ const update = message.params?.update as SessionUpdate | undefined
464
+ if (!sessionId || !update) return
465
+ // Kept outside `sessions`: the list can arrive before `session/new` resolves.
466
+ if (update.sessionUpdate === "available_commands_update" && Array.isArray(update.availableCommands)) {
467
+ const commands: AcpCommand[] = []
468
+ for (const command of update.availableCommands as Array<{ name?: unknown; description?: unknown; input?: unknown }>) {
469
+ if (typeof command?.name !== "string" || !command.name) continue
470
+ const hint = (command.input as { hint?: unknown } | null | undefined)?.hint
471
+ commands.push({
472
+ name: command.name,
473
+ ...(typeof command.description === "string" && command.description ? { description: command.description } : {}),
474
+ ...(typeof hint === "string" && hint ? { hint } : {}),
475
+ })
476
+ }
477
+ this.commands.set(sessionId, commands)
478
+ this.commandWaiters.get(sessionId)?.(commands)
479
+ this.options.onCommands?.(sessionId, commands)
480
+ this.sessions.get(sessionId)?.onCommands?.(commands)
481
+ } else if (update.sessionUpdate === "usage_update") {
482
+ this.log(
483
+ "debug",
484
+ `ACP context for ${sessionId}: ${update.used ?? "?"}/${update.size ?? "?"} tokens, cost ${JSON.stringify(update.cost ?? null)}`,
485
+ )
486
+ }
487
+ this.sessions.get(sessionId)?.onUpdate?.(update)
488
+ }
489
+
490
+ private async onRequest(message: RpcMessage) {
491
+ const method = message.method!
492
+ const child = this.child
493
+ try {
494
+ if (method === "session/request_permission") {
495
+ const params = message.params ?? {}
496
+ const options: Array<{ optionId?: string; kind?: string }> = params.options ?? []
497
+
498
+ const question = readQuestionText(params, options)
499
+ if (question) {
500
+ // Native ask-user tools are supposed to be disabled in favour of the
501
+ // MCP `question` tool. Never auto-approve one: the first option is an
502
+ // answer, not permission.
503
+ this.log("debug", `declining native ACP question: ${question}`)
504
+ this.reply(message.id!, { outcome: { outcome: "cancelled" } }, undefined, undefined, child)
505
+ return
506
+ }
507
+
508
+ const allow =
509
+ options.find((option) => option.optionId === "allow_once") ??
510
+ options.find((option) => option.optionId?.startsWith("allow")) ??
511
+ options.find((option) => option.kind?.startsWith("allow")) ??
512
+ options[0]
513
+ const info: PermissionRequestInfo = {
514
+ title: params.toolCall?.title ?? allow?.optionId ?? "ACP tool",
515
+ kind: params.toolCall?.kind,
516
+ detail: readToolCallText(params.toolCall?.content),
517
+ }
518
+ const handler = this.sessions.get(params.sessionId)?.requestPermission
519
+ const approved =
520
+ this.options.autoApprove !== false
521
+ ? Boolean(allow)
522
+ : handler
523
+ ? await handler(info).catch(() => false)
524
+ : false
525
+ if (!approved || !allow?.optionId) {
526
+ this.reply(message.id!, { outcome: { outcome: "cancelled" } }, undefined, undefined, child)
527
+ return
528
+ }
529
+ this.log("debug", `approving ACP permission: ${info.title}`)
530
+ this.reply(
531
+ message.id!,
532
+ { outcome: { outcome: "selected", optionId: allow.optionId } },
533
+ undefined,
534
+ undefined,
535
+ child,
536
+ )
537
+ return
538
+ }
539
+
540
+ if (method === "fs/read_text_file") {
541
+ const content = await this.readTextFile(message.params ?? {})
542
+ this.reply(message.id!, { content }, undefined, undefined, child)
543
+ return
544
+ }
545
+
546
+ if (method === "fs/write_text_file") {
547
+ await this.writeTextFile(message.params ?? {})
548
+ this.reply(message.id!, {}, undefined, undefined, child)
549
+ return
550
+ }
551
+
552
+ this.log("warn", `unsupported ACP client method: ${method}`)
553
+ this.reply(message.id!, undefined, -32601, `Method not supported by client: ${method}`, child)
554
+ } catch (error) {
555
+ const text = errorMessage(error)
556
+ const code = isAcpError(error) ? error.code : -32603
557
+ this.reply(message.id!, undefined, code, text, child)
558
+ }
559
+ }
560
+
561
+ private reply(
562
+ id: number | string,
563
+ result: any,
564
+ errorCode?: number,
565
+ errorMessage?: string,
566
+ child?: ChildProcessWithoutNullStreams,
567
+ ) {
568
+ if (child && this.child !== child) {
569
+ this.log("debug", "dropping reply to a request from a previous agent process")
570
+ return
571
+ }
572
+ try {
573
+ if (errorCode !== undefined) {
574
+ this.write({ jsonrpc: "2.0", id, error: { code: errorCode, message: errorMessage ?? "error" } })
575
+ } else {
576
+ this.write({ jsonrpc: "2.0", id, result })
577
+ }
578
+ } catch {
579
+ // The agent is gone; there is nobody left to answer.
580
+ }
581
+ }
582
+
583
+ private write(message: RpcMessage) {
584
+ const child = this.child
585
+ if (!child || this.closed || !child.stdin.writable) throw new AcpError("ACP agent is not running")
586
+ child.stdin.write(`${JSON.stringify(message)}\n`)
587
+ }
588
+
589
+ request(method: string, params?: unknown, options: RequestOptions = {}) {
590
+ const id = this.nextID++
591
+ const startedAt = performance.now()
592
+ return new Promise<any>((resolveValue, rejectValue) => {
593
+ let timer: ReturnType<typeof setTimeout> | undefined
594
+ let graceTimer: ReturnType<typeof setTimeout> | undefined
595
+ let abortListener: (() => void) | undefined
596
+
597
+ const cleanup = () => {
598
+ if (timer) clearTimeout(timer)
599
+ if (graceTimer) clearTimeout(graceTimer)
600
+ if (abortListener) options.signal?.removeEventListener("abort", abortListener)
601
+ this.pending.delete(id)
602
+ const elapsed = Math.round(performance.now() - startedAt)
603
+ this.log(
604
+ method !== "session/prompt" && elapsed >= 1_000 ? "warn" : "debug",
605
+ `ACP request ${method} settled in ${elapsed}ms`,
606
+ )
607
+ }
608
+ const succeed = (value: any) => {
609
+ cleanup()
610
+ resolveValue(value)
611
+ }
612
+ const fail = (error: Error) => {
613
+ cleanup()
614
+ rejectValue(error)
615
+ }
616
+
617
+ this.pending.set(id, { resolve: succeed, reject: fail, method })
618
+
619
+ const timeout = options.timeout ?? this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
620
+ if (timeout > 0 && Number.isFinite(timeout)) {
621
+ timer = setTimeout(
622
+ () => fail(new AcpError(`ACP request "${method}" timed out after ${timeout}ms`, -32001)),
623
+ timeout,
624
+ )
625
+ timer.unref?.()
626
+ }
627
+
628
+ if (options.signal) {
629
+ const onAbort = () => {
630
+ try {
631
+ options.onAbort?.()
632
+ } catch {
633
+ // the agent may already be gone
634
+ }
635
+ const grace = options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS
636
+ graceTimer = setTimeout(
637
+ () => fail(new AcpError(`ACP request "${method}" was cancelled`, ACP_REQUEST_CANCELLED)),
638
+ Math.max(0, grace),
639
+ )
640
+ graceTimer.unref?.()
641
+ }
642
+ if (options.signal.aborted) onAbort()
643
+ else {
644
+ abortListener = onAbort
645
+ options.signal.addEventListener("abort", abortListener, { once: true })
646
+ }
647
+ }
648
+
649
+ try {
650
+ this.write({ jsonrpc: "2.0", id, method, params })
651
+ } catch (error) {
652
+ fail(error instanceof Error ? error : new Error(String(error)))
653
+ }
654
+ })
655
+ }
656
+
657
+ notify(method: string, params?: unknown) {
658
+ this.write({ jsonrpc: "2.0", method, params })
659
+ }
660
+
661
+ /**
662
+ * Create a session and return its id plus the selectable models and reasoning
663
+ * effort levels advertised by the agent through `configOptions`.
664
+ */
665
+ async newSession(
666
+ cwd: string,
667
+ options: {
668
+ model?: string
669
+ effort?: string
670
+ mcpServers?: AcpMcpServer[]
671
+ additionalDirectories?: string[]
672
+ meta?: Record<string, unknown>
673
+ /** The object that owns this session, e.g. the server manager that opened it. */
674
+ owner?: object
675
+ /** Called when this session's command list is advertised, including one that arrived before registration. */
676
+ onCommands?: (commands: AcpCommand[]) => void
677
+ } = {},
678
+ ) {
679
+ await this.start()
680
+ const result = await this.request("session/new", { cwd, ...sessionParams(options) })
681
+ const sessionId: string = result.sessionId
682
+ if (!sessionId) throw new AcpError("ACP agent did not return a session id", -32603)
683
+ const configOptions: AcpConfigOption[] = result.configOptions ?? []
684
+ const modelOption = configOptions.find((option) => option.category === "model" || option.id === "model")
685
+ const models: Array<{ id: string; name: string; description?: string }> = (modelOption?.options ?? [])
686
+ .filter((option): option is { value: string; name?: string; description?: string } => {
687
+ return typeof option.value === "string" && option.value.length > 0
688
+ })
689
+ .map((option) => ({
690
+ id: option.value,
691
+ name: option.name || option.value,
692
+ description: option.description,
693
+ }))
694
+ const effort = readEffortConfig(configOptions)
695
+
696
+ this.sessions.set(sessionId, {
697
+ cwd,
698
+ additionalDirectories: options.additionalDirectories,
699
+ configOptions,
700
+ owner: options.owner,
701
+ onCommands: options.onCommands,
702
+ })
703
+ // The notification can arrive before the response that names the session.
704
+ const advertised = this.commands.get(sessionId)
705
+ if (advertised) options.onCommands?.(advertised)
706
+
707
+ try {
708
+ if (options.model && !modelOption) throw new AcpError("Agent does not expose an ACP model selector", -32602)
709
+ if (options.model && modelOption && options.model !== modelOption.currentValue) {
710
+ await this.setModel(sessionId, options.model, modelOption.id ?? "model")
711
+ }
712
+ if (options.effort && effort && options.effort !== effort.currentValue) {
713
+ await this.setEffort(sessionId, options.effort, effort.configId)
714
+ }
715
+ } catch (error) {
716
+ // The agent already created the session; close it so a rejected model or
717
+ // effort does not leak an ACP session that nobody can address anymore.
718
+ await this.closeSession(sessionId).catch(() => {})
719
+ throw error
720
+ }
721
+
722
+ return {
723
+ sessionId,
724
+ configOptions,
725
+ models,
726
+ modelConfigID: modelOption ? modelOption.id ?? "model" : undefined,
727
+ currentModel: options.model ?? modelOption?.currentValue,
728
+ efforts: effort?.values ?? [],
729
+ effort,
730
+ modes: result.modes,
731
+ }
732
+ }
733
+
734
+ /**
735
+ * Reattach to a session the agent persisted in an earlier process, keeping
736
+ * the conversation it holds. `session/resume` restores without replaying the
737
+ * transcript; `session/load` replays it, and those updates are ignored here
738
+ * because OpenCode already shows the conversation. Returns undefined when
739
+ * the agent advertises neither capability.
740
+ */
741
+ async restoreSession(
742
+ sessionId: string,
743
+ options: {
744
+ cwd: string
745
+ mcpServers?: AcpMcpServer[]
746
+ additionalDirectories?: string[]
747
+ meta?: Record<string, unknown>
748
+ /** The object that owns this session now, e.g. the server manager that restored it. */
749
+ owner?: object
750
+ /** Called when this session's command list is advertised, including one that arrived before registration. */
751
+ onCommands?: (commands: AcpCommand[]) => void
752
+ },
753
+ ): Promise<"resumed" | "loaded" | undefined> {
754
+ // Restores of one session run one at a time, so a takeover cannot interleave
755
+ // with another caller's resume.
756
+ const previous = this.restoring.get(sessionId)
757
+ const restore = (async () => {
758
+ if (previous) await previous.catch(() => {})
759
+ return await this.doRestoreSession(sessionId, options)
760
+ })()
761
+ this.restoring.set(sessionId, restore)
762
+ restore
763
+ .catch(() => {})
764
+ .finally(() => {
765
+ if (this.restoring.get(sessionId) === restore) this.restoring.delete(sessionId)
766
+ })
767
+ return await restore
768
+ }
769
+
770
+ private async doRestoreSession(
771
+ sessionId: string,
772
+ options: {
773
+ cwd: string
774
+ mcpServers?: AcpMcpServer[]
775
+ additionalDirectories?: string[]
776
+ meta?: Record<string, unknown>
777
+ owner?: object
778
+ onCommands?: (commands: AcpCommand[]) => void
779
+ },
780
+ ): Promise<"resumed" | "loaded" | undefined> {
781
+ const capabilities = (await this.start()).agentCapabilities
782
+ const resume = capabilities?.sessionCapabilities?.resume !== undefined
783
+ const load = capabilities?.loadSession === true
784
+ if (!resume && !load) return undefined
785
+
786
+ // Whoever holds the session may still be draining a turn: let that turn end,
787
+ // then close the session so the old owner's later calls are no-ops. The
788
+ // agent persists the conversation, and the resume below reattaches it.
789
+ const existing = this.sessions.get(sessionId)
790
+ if (existing && existing.owner !== options.owner) {
791
+ await existing.turn
792
+ if (this.sessions.get(sessionId) === existing) await this.closeSession(sessionId).catch(() => {})
793
+ }
794
+
795
+ const timeout = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
796
+ const result = await this.request(
797
+ resume ? "session/resume" : "session/load",
798
+ { sessionId, cwd: options.cwd, ...sessionParams(options) },
799
+ // Replaying a long conversation through session/load is not a control call.
800
+ { timeout: resume ? timeout : Math.max(60_000, timeout) },
801
+ )
802
+ this.sessions.set(sessionId, {
803
+ cwd: options.cwd,
804
+ additionalDirectories: options.additionalDirectories,
805
+ configOptions: result.configOptions ?? [],
806
+ owner: options.owner,
807
+ onCommands: options.onCommands,
808
+ })
809
+ // The notification can arrive before the response that names the session.
810
+ const advertised = this.commands.get(sessionId)
811
+ if (advertised) options.onCommands?.(advertised)
812
+ return resume ? "resumed" : "loaded"
813
+ }
814
+
815
+ /** Whether this client still holds the ACP session and can take another prompt. */
816
+ hasSession(sessionId: string, owner?: object) {
817
+ const session = this.sessions.get(sessionId)
818
+ if (!session) return false
819
+ return this.matchesOwner(session, owner)
820
+ }
821
+
822
+ /** Ids of the sessions whose owner is exactly this object. */
823
+ sessionsOwnedBy(owner: object): string[] {
824
+ const owned: string[] = []
825
+ for (const [sessionId, session] of this.sessions) {
826
+ if (session.owner === owner) owned.push(sessionId)
827
+ }
828
+ return owned
829
+ }
830
+
831
+ /** Whether the agent process is running and usable. */
832
+ get alive() {
833
+ return Boolean(this.child) && !this.closed && !this.disposed
834
+ }
835
+
836
+ configOption(sessionId: string, category: string) {
837
+ return this.sessions.get(sessionId)?.configOptions.find((option) => option.category === category)
838
+ }
839
+
840
+ async setModel(sessionId: string, modelId: string, configId = "model") {
841
+ return this.setConfigOption(sessionId, this.configOption(sessionId, "model")?.id ?? configId, modelId)
842
+ }
843
+ /** Set the agent's reasoning effort for a session. */
844
+ async setEffort(sessionId: string, effort: string, configId = "effort") {
845
+ return this.setConfigOption(sessionId, this.configOption(sessionId, "thought_level")?.id ?? configId, effort)
846
+ }
847
+
848
+ /** Set any agent-advertised session config option, e.g. "model" or "effort". */
849
+ async setConfigOption(sessionId: string, configId: string, value: string) {
850
+ const session = this.sessions.get(sessionId)
851
+ const option = session?.configOptions.find((option) => option.id === configId)
852
+ if (option?.currentValue === value) return
853
+ const result = await this.request("session/set_config_option", { sessionId, configId, value })
854
+ if (session) {
855
+ session.configOptions = Array.isArray(result.configOptions)
856
+ ? result.configOptions
857
+ : session.configOptions.map((current) => {
858
+ if (current.id === configId) return { ...current, currentValue: value }
859
+ // A model switch can reset effort; do not retain an unconfirmed value.
860
+ if (option?.category === "model" && current.category === "thought_level") {
861
+ return { ...current, currentValue: undefined }
862
+ }
863
+ return current
864
+ })
865
+ }
866
+ return result
867
+ }
868
+
869
+ async setMode(sessionId: string, modeId: string) {
870
+ return this.request("session/set_mode", { sessionId, modeId })
871
+ }
872
+
873
+ /** Send a prompt turn and stream `session/update` notifications. */
874
+ async prompt(
875
+ sessionId: string,
876
+ prompt: string | ContentBlock[],
877
+ handlers: {
878
+ /** The object that owns the session; a mismatched call is refused. */
879
+ owner?: object
880
+ onUpdate?: (update: SessionUpdate) => void
881
+ signal?: AbortSignal
882
+ requestPermission?: PermissionHandler
883
+ } = {},
884
+ ): Promise<PromptResult> {
885
+ if (handlers.signal?.aborted) return { stopReason: "cancelled", text: "" }
886
+ const blocks: ContentBlock[] = typeof prompt === "string" ? [{ type: "text", text: prompt }] : prompt
887
+ const session = this.sessions.get(sessionId)
888
+ if (!session) throw new AcpError(`Unknown ACP session: ${sessionId}`)
889
+ if (!this.matchesOwner(session, handlers.owner)) {
890
+ throw new AcpError("ACP session is owned by another client", -32003)
891
+ }
892
+ session.requestPermission = handlers.requestPermission
893
+
894
+ let text = ""
895
+ const onUpdate = (update: SessionUpdate) => {
896
+ if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text") {
897
+ text += update.content.text ?? ""
898
+ }
899
+ handlers.onUpdate?.(update)
900
+ }
901
+ session.onUpdate = onUpdate
902
+
903
+ const promptTimeout = this.options.promptTimeoutMs ?? DEFAULT_PROMPT_TIMEOUT_MS
904
+ const request = this.request(
905
+ "session/prompt",
906
+ { sessionId, prompt: blocks },
907
+ {
908
+ timeout: promptTimeout,
909
+ signal: handlers.signal,
910
+ onAbort: () => this.cancelTurn(sessionId, handlers.owner),
911
+ },
912
+ )
913
+ // A new owner waits on this turn to know the session is free; it must never
914
+ // reject, or a taken-over turn would surface as an unhandled rejection.
915
+ const turn = request.catch(() => {})
916
+ session.turn = turn
917
+ try {
918
+ const result = await request
919
+ // Usage stays in the debug log: no ACP number is right for both of the
920
+ // ways OpenCode reads a step's tokens (context size and spend).
921
+ if (result?.usage || result?._meta?.usage) {
922
+ this.log(
923
+ "debug",
924
+ `ACP turn usage for ${sessionId}: ${JSON.stringify(result.usage ?? null)} turn=${JSON.stringify(result._meta?.usage ?? null)}`,
925
+ )
926
+ }
927
+ return { stopReason: result?.stopReason ?? "end_turn", text }
928
+ } finally {
929
+ if (session.turn === turn) session.turn = undefined
930
+ const current = this.sessions.get(sessionId)
931
+ if (current?.onUpdate === onUpdate) {
932
+ current.onUpdate = undefined
933
+ current.requestPermission = undefined
934
+ }
935
+ }
936
+ }
937
+
938
+ /** Ask the agent to end the running turn; `session/prompt` then resolves with `cancelled`. */
939
+ cancelTurn(sessionId: string, owner?: object) {
940
+ if (!this.matchesOwner(this.sessions.get(sessionId), owner)) return
941
+ try {
942
+ this.notify("session/cancel", { sessionId })
943
+ } catch {
944
+ // the agent is already gone
945
+ }
946
+ }
947
+
948
+ /** Whether the agent advertised this slash command for the session. */
949
+ hasCommand(sessionId: string, name: string) {
950
+ return this.commands.get(sessionId)?.some((command) => command.name === name) === true
951
+ }
952
+
953
+ /**
954
+ * Resolve once the agent advertised a command list for this session, so a
955
+ * caller that is about to close a discovery session does not race the
956
+ * notification, which arrives separately from the `session/new` result.
957
+ * Resolves `undefined` if nothing arrives in time.
958
+ */
959
+ waitForCommands(sessionId: string, timeoutMs: number): Promise<AcpCommand[] | undefined> {
960
+ const known = this.commands.get(sessionId)
961
+ if (known) return Promise.resolve(known)
962
+ return new Promise((resolve) => {
963
+ let timer: ReturnType<typeof setTimeout> | undefined
964
+ const finish = (commands: AcpCommand[] | undefined) => {
965
+ if (timer) clearTimeout(timer)
966
+ this.commandWaiters.delete(sessionId)
967
+ resolve(commands)
968
+ }
969
+ this.commandWaiters.set(sessionId, finish)
970
+ if (timeoutMs > 0) {
971
+ timer = setTimeout(() => finish(undefined), timeoutMs)
972
+ timer.unref?.()
973
+ }
974
+ })
975
+ }
976
+
977
+ async closeSession(sessionId: string, owner?: object) {
978
+ if (!this.matchesOwner(this.sessions.get(sessionId), owner)) return
979
+ this.sessions.delete(sessionId)
980
+ this.commands.delete(sessionId)
981
+ this.commandWaiters.delete(sessionId)
982
+ if (this.handshake?.agentCapabilities?.sessionCapabilities?.close === false) {
983
+ // The agent has no close method; dropping our side is all we can do.
984
+ this.log("debug", `dropping ACP session ${sessionId} (agent does not support session/close)`)
985
+ return
986
+ }
987
+ try {
988
+ await this.request("session/close", { sessionId })
989
+
990
+ } catch {
991
+ // close is best effort
992
+ }
993
+ }
994
+
995
+ async stop() {
996
+ if (this.disposed) return
997
+ this.disposed = true
998
+ this.closed = true
999
+ this.started = undefined
1000
+ this.handshake = undefined
1001
+ this.sessions.clear()
1002
+ this.buffer = ""
1003
+ this.stderrBuffer = ""
1004
+ const pending = [...this.pending.values()]
1005
+ this.pending.clear()
1006
+ for (const entry of pending) entry.reject(new AcpError("ACP client stopped"))
1007
+ const child = this.child
1008
+ this.child = undefined
1009
+ if (child) {
1010
+ this.stopping.add(child)
1011
+ child.once("exit", () => this.stopping.delete(child))
1012
+ if (child.exitCode !== null || child.signalCode !== null) this.stopping.delete(child)
1013
+ this.killChild(child, "SIGTERM")
1014
+ const timer = setTimeout(() => {
1015
+ if (child.exitCode === null && child.signalCode === null) this.killChild(child, "SIGKILL")
1016
+ }, SIGKILL_DELAY_MS)
1017
+ timer.unref?.()
1018
+ }
1019
+ }
1020
+
1021
+ /** SIGKILL the agent (and its process group) right away, including one still stopping. Safe to call repeatedly; for `process.on("exit")`. */
1022
+ killSync() {
1023
+ for (const child of [this.child, ...this.stopping]) {
1024
+ if (child && child.exitCode === null && child.signalCode === null) this.killChild(child, "SIGKILL")
1025
+ }
1026
+ }
1027
+
1028
+ /** Kill the agent and, on POSIX, any wrapper it launched in its process group. */
1029
+ private killChild(child: ChildProcessWithoutNullStreams, signal: NodeJS.Signals) {
1030
+ if (process.platform !== "win32" && child.pid) {
1031
+ try {
1032
+ process.kill(-child.pid, signal)
1033
+ return
1034
+ } catch {
1035
+ // no process group (not detached, or it already exited)
1036
+ }
1037
+ }
1038
+ try {
1039
+ child.kill(signal)
1040
+ } catch {
1041
+ // already gone
1042
+ }
1043
+ }
1044
+
1045
+ // ---- filesystem methods -------------------------------------------------
1046
+
1047
+ private async readTextFile(params: { sessionId?: string; path?: string; line?: number; limit?: number }) {
1048
+ const target = await this.resolveTarget(params.sessionId, String(params.path ?? ""), "read")
1049
+ if (!target) throw new AcpError("fs/read_text_file requires a path", -32602)
1050
+ const line = typeof params.line === "number" && params.line > 0 ? Math.floor(params.line) : undefined
1051
+ const limit = typeof params.limit === "number" && params.limit > 0 ? Math.floor(params.limit) : undefined
1052
+ const maxBytes = this.options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES
1053
+ if (line !== undefined || limit !== undefined) {
1054
+ return (await readLines(target, line ? line - 1 : 0, limit ?? Infinity, maxBytes)).join("\n")
1055
+ }
1056
+ const info = await stat(target).catch(() => undefined)
1057
+ if (info && info.size > maxBytes) {
1058
+ throw new AcpError(`File is larger than ${maxBytes} bytes; request a line range instead`, -32603)
1059
+ }
1060
+ return await readFile(target, "utf8")
1061
+ }
1062
+
1063
+ private async writeTextFile(params: { sessionId?: string; path?: string; content?: string }) {
1064
+ const target = await this.resolveTarget(params.sessionId, String(params.path ?? ""), "write")
1065
+ if (!target) throw new AcpError("fs/write_text_file requires a path", -32602)
1066
+ await mkdir(dirname(target), { recursive: true })
1067
+ await writeFile(target, params.content ?? "", "utf8")
1068
+ }
1069
+
1070
+ /**
1071
+ * Resolve a path from the agent against the session directory and enforce the
1072
+ * sandbox. Returning the resolved path matters: checking one path and then
1073
+ * reading a relative one would touch the process cwd instead.
1074
+ *
1075
+ * Reads may also reach the session's additional directories (the skills
1076
+ * mirror); writes stay inside the session cwd. A root is matched both as
1077
+ * given and through its real path, because agents send absolute paths built
1078
+ * from the cwd they were given, which may run through a symlink such as
1079
+ * macOS `/var` -> `/private/var`.
1080
+ */
1081
+ private async resolveTarget(sessionId: string | undefined, target: string, access: "read" | "write"): Promise<string> {
1082
+ const raw = target.trim()
1083
+ if (!raw) return ""
1084
+ const session = sessionId ? this.sessions.get(sessionId) : undefined
1085
+ const root = session?.cwd
1086
+ if (this.options.allowPathsOutsideCwd) {
1087
+ return resolve(root ?? process.cwd(), raw)
1088
+ }
1089
+ if (!root) {
1090
+ throw new AcpError("filesystem access requires a known session root", -32602)
1091
+ }
1092
+ const roots = access === "read" ? [root, ...(session?.additionalDirectories ?? [])] : [root]
1093
+ const allowed = await Promise.all(
1094
+ roots.map(async (entry) => {
1095
+ const lexical = resolve(entry)
1096
+ return { lexical, real: await realpath(lexical).catch(() => lexical) }
1097
+ }),
1098
+ )
1099
+ const resolvedTarget = resolve(root, raw)
1100
+ if (!allowed.some(({ lexical, real }) => isInside(lexical, resolvedTarget) || isInside(real, resolvedTarget))) {
1101
+ throw new AcpError(`Path is outside the session directory: ${target}`, -32602)
1102
+ }
1103
+ // Refuse to follow a symlink out of the roots. For a path that does not
1104
+ // exist yet, check the deepest existing ancestor: a symlinked parent
1105
+ // directory would otherwise let a write escape even though the file itself
1106
+ // is new.
1107
+ const real = (await realpath(resolvedTarget).catch(() => undefined)) ?? (await realpathExistingAncestor(resolvedTarget))
1108
+ if (real && !allowed.some((entry) => isInside(entry.real, real))) {
1109
+ throw new AcpError(`Path resolves outside the session directory: ${target}`, -32602)
1110
+ }
1111
+ return resolvedTarget
1112
+ }
1113
+ }
1114
+
1115
+ function isInside(root: string, target: string) {
1116
+ const rel = relative(root, target)
1117
+ if (rel === "") return true
1118
+ // `..env` is a file inside the root; only a `..` segment escapes it.
1119
+ return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
1120
+ }
1121
+
1122
+ /**
1123
+ * The text of an ACP tool call's content, for the permission prompt. Content
1124
+ * entries are `{ type: "content", content: { type: "text", text } }`; diffs
1125
+ * carry `path` and `newText`.
1126
+ */
1127
+ function readToolCallText(content: unknown): string | undefined {
1128
+ if (!Array.isArray(content)) return undefined
1129
+ const parts: string[] = []
1130
+ for (const entry of content) {
1131
+ if (!entry || typeof entry !== "object") continue
1132
+ const item = entry as Record<string, any>
1133
+ if (item.type === "content" && item.content?.type === "text" && typeof item.content.text === "string") {
1134
+ parts.push(item.content.text)
1135
+ } else if (item.type === "diff" && typeof item.path === "string") {
1136
+ parts.push(typeof item.newText === "string" ? `${item.path}\n${item.newText}` : item.path)
1137
+ } else if (typeof item.text === "string") {
1138
+ parts.push(item.text)
1139
+ }
1140
+ }
1141
+ const text = parts.join("\n").trim()
1142
+ if (!text) return undefined
1143
+ return text.length > MAX_PERMISSION_DETAIL ? `${text.slice(0, MAX_PERMISSION_DETAIL)}…` : text
1144
+ }
1145
+
1146
+ const MAX_PERMISSION_DETAIL = 4_000
1147
+
1148
+ /** Resolve the real path of the closest ancestor that exists. */
1149
+ async function realpathExistingAncestor(target: string): Promise<string | undefined> {
1150
+ let current = target
1151
+ for (;;) {
1152
+ const real = await realpath(current).catch(() => undefined)
1153
+ if (real) return real
1154
+ const parent = dirname(current)
1155
+ if (parent === current) return undefined
1156
+ current = parent
1157
+ }
1158
+ }
1159
+
1160
+ async function readLines(path: string, offset: number, limit: number, maxBytes: number) {
1161
+ const stream = createReadStream(path, { encoding: "utf8" })
1162
+ const reader = createInterface({ input: stream, crlfDelay: Infinity })
1163
+ const lines: string[] = []
1164
+ let index = 0
1165
+ let bytes = 0
1166
+ try {
1167
+ for await (const line of reader) {
1168
+ if (index++ < offset) continue
1169
+ lines.push(line)
1170
+ bytes += line.length + 1
1171
+ if (bytes > maxBytes) throw new AcpError(`Requested range is larger than ${maxBytes} bytes`, -32603)
1172
+ if (lines.length >= limit) break
1173
+ }
1174
+ } finally {
1175
+ reader.close()
1176
+ stream.destroy()
1177
+ }
1178
+ return lines
1179
+ }