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,1137 @@
1
+ import { homedir } from "node:os"
2
+ import { isAbsolute } from "node:path"
3
+ import {
4
+ ACP_REQUEST_CANCELLED,
5
+ AcpClient,
6
+ isAcpError,
7
+ type AcpCommand,
8
+ type AcpMcpServer,
9
+ type SessionUpdate,
10
+ type PermissionHandler,
11
+ } from "./acp-client.ts"
12
+ import { AgentPool, type AgentLaunch, type AgentLease, type AgentSubscriber } from "./agent-pool.ts"
13
+ import { applyCmdMods } from "./agents/cmd/index.ts"
14
+ import { isCmdCommand } from "./agent-command.ts"
15
+ import { runSetup } from "./setup.ts"
16
+ import { errorMessage } from "./util.ts"
17
+
18
+ export interface AcpServerConfig {
19
+ /** Stable id used for the OpenCode provider and tool arguments. */
20
+ id: string
21
+ /** Display name for the provider. Defaults to the id. */
22
+ name?: string
23
+ /** Command and arguments that start the ACP agent, e.g. ["cmd", "acp"]. */
24
+ command: string | string[]
25
+ /**
26
+ * Shell command run once before the agent is first spawned. Not limited to
27
+ * installation, e.g. `"vp add -g command-code@latest"` installs while a login
28
+ * or config-write command works too. Runs once per plugin-module lifetime; a
29
+ * failure is logged and the agent still starts.
30
+ */
31
+ setup?: string
32
+ /**
33
+ * Working directory for the agent process and its sessions. When unset,
34
+ * sessions use the OpenCode location, and the process starts in the home
35
+ * directory if it is shared across directories (else in the OpenCode location).
36
+ */
37
+ cwd?: string
38
+ /** Extra environment variables for the agent process. */
39
+ env?: Record<string, string>
40
+ /**
41
+ * Share one agent process across OpenCode directories. Defaults to true,
42
+ * except for Command Code (`cmd`), which binds a process to one directory and
43
+ * always gets its own process with a warm spare. Set false for other agents
44
+ * that serve one directory per process.
45
+ */
46
+ share?: boolean
47
+ /** Optional allowlist of ACP model ids to expose. */
48
+ models?: string[]
49
+ /** Default ACP model for direct tool calls. */
50
+ model?: string
51
+ /** ACP reasoning effort for pooled sessions, e.g. "off", "low", "high". */
52
+ effort?: string
53
+ /** ACP session mode applied to pooled sessions, e.g. "auto-accept". */
54
+ mode?: string
55
+ /** ACP `_meta` passed to `session/new`, e.g. Claude's `claudeCode.options`. */
56
+ meta?: Record<string, unknown>
57
+ /** Auto-approve ACP permission requests. Defaults to true. */
58
+ autoApprove?: boolean
59
+ /** Expose OpenCode's skills through the agent's native skill discovery. Defaults to true. */
60
+ skills?: boolean
61
+ /** Disable this server without removing its configuration. */
62
+ disabled?: boolean
63
+ }
64
+
65
+ export interface AcpModelInfo {
66
+ id: string
67
+ name: string
68
+ description?: string
69
+ }
70
+
71
+ export interface AcpServerState {
72
+ config: AcpServerConfig
73
+ client?: AcpClient
74
+ models: AcpModelInfo[]
75
+ defaultModel?: string
76
+ modelConfigID?: string
77
+ /** Reasoning effort levels advertised by the agent, excluding the implicit default. */
78
+ efforts: string[]
79
+ effortConfigID?: string
80
+ defaultEffort?: string
81
+ error?: string
82
+ /** False when retrying cannot help, e.g. a `models` allowlist that matches nothing. */
83
+ retryable?: boolean
84
+ initialized: boolean
85
+ /**
86
+ * Slash commands the agent has advertised. The setup session is closed after
87
+ * discovery, so this starts as a snapshot and is replaced whenever a live
88
+ * session advertises a newer list.
89
+ */
90
+ commands?: AcpCommand[]
91
+ }
92
+
93
+ export interface AcpPermissionInput {
94
+ server: string
95
+ sessionKey: string
96
+ title: string
97
+ kind?: string
98
+ detail?: string
99
+ }
100
+
101
+ export type PermissionResolver = (input: AcpPermissionInput) => Promise<boolean>
102
+
103
+ export type LogFn = (level: "debug" | "info" | "warn" | "error", message: string) => void
104
+
105
+ export interface McpLease {
106
+ servers: AcpMcpServer[]
107
+ release: () => void
108
+ }
109
+
110
+ export interface McpProvider {
111
+ /** `agent` is the server whose ACP session is being opened. */
112
+ servers: (sessionKey: string, agent: AcpServerConfig) => Promise<McpLease>
113
+ }
114
+
115
+ /**
116
+ * Remembers which ACP session belongs to an OpenCode session. A plugin reload
117
+ * or a crashed agent starts a new process with no in-memory sessions; looking
118
+ * the id up lets it reattach with `session/resume` instead of starting over
119
+ * with no context. Implementations are expected to persist across processes.
120
+ */
121
+ export interface AcpSessionStore {
122
+ get(key: string): Promise<string | undefined>
123
+ set(key: string, sessionId: string): Promise<void>
124
+ delete(key: string): Promise<void>
125
+ }
126
+
127
+ function normalizeCommand(command: string | string[]): { command: string; args: string[] } {
128
+ if (Array.isArray(command)) {
129
+ if (!command.length || typeof command[0] !== "string" || !command[0].trim()) {
130
+ throw new Error("command must contain an executable")
131
+ }
132
+ return { command: command[0], args: command.slice(1) }
133
+ }
134
+ if (!command.trim()) throw new Error("command must not be empty")
135
+ if (/\s/.test(command.trim())) {
136
+ throw new Error(`command "${command}" contains whitespace; pass an array such as ["cmd", "acp"] instead`)
137
+ }
138
+ return { command: command.trim(), args: [] }
139
+ }
140
+
141
+ interface AcpSelection {
142
+ model?: string
143
+ effort?: string
144
+ }
145
+
146
+ interface PooledSession {
147
+ server: string
148
+ key: string
149
+ sessionId: string
150
+ client: AcpClient
151
+ /** Undefined after a refused/uncertain config write; never assume it applied. */
152
+ selection?: AcpSelection
153
+ history: "fresh" | "retained"
154
+ mcpServers?: AcpMcpServer[]
155
+ cwd: string
156
+ queue: Promise<unknown>
157
+ lastUsed: number
158
+ pending: number
159
+ /** Prompts actually being streamed right now, as opposed to queued behind them. */
160
+ active: number
161
+ /** Consecutive turns that failed; the session is recycled after a few. */
162
+ failures: number
163
+ broken: boolean
164
+ mcpRelease?: () => void
165
+ }
166
+
167
+ interface AcpRunResult {
168
+ stopReason: string
169
+ text: string
170
+ }
171
+
172
+ export type AcpCompactResult =
173
+ /** `text` is what the agent said; `tokens` is its context size before and after, when it reports them. */
174
+ | { status: "compacted"; text: string; tokens?: { before: number; after: number } }
175
+ /** The agent has no `/compact` command; it manages its context on its own. */
176
+ | { status: "unsupported" }
177
+ /** No live ACP session holds this conversation, so there is nothing to compact. */
178
+ | { status: "no-session" }
179
+
180
+ const DEFAULT_MAX_SESSIONS = 32
181
+ const DEFAULT_SESSION_IDLE_MS = 30 * 60_000
182
+ const DEFAULT_INIT_TIMEOUT_MS = 20_000
183
+
184
+ /** ACP's "resource not found": the agent no longer knows the session. */
185
+ const ACP_UNKNOWN_SESSION = -32002
186
+ /** Failed turns in a row before the pooled session is recycled. */
187
+ const MAX_TURN_FAILURES = 3
188
+ /** How long to wait for the command list an agent sends after `session/new`. */
189
+ const COMMAND_SNAPSHOT_TIMEOUT_MS = 2_000
190
+ const SWEEP_INTERVAL_MS = 60_000
191
+
192
+ export class AcpServerManager {
193
+ readonly servers = new Map<string, AcpServerState>()
194
+ private permissionResolver?: PermissionResolver
195
+ private log: LogFn
196
+ private defaultCwd: string
197
+ private pools = new Map<string, PooledSession>()
198
+ private negotiating = new Map<string, Promise<PooledSession>>()
199
+ private preparing = new Map<string, Promise<void>>()
200
+ /** Keys whose ACP turn is still being negotiated, before a prompt is in flight. */
201
+ private starting = new Map<string, number>()
202
+ /** Keys whose starting turn must be cancelled as soon as its prompt is sent. */
203
+ private startCancels = new Set<string>()
204
+ private mcp?: McpProvider
205
+ private sessions?: AcpSessionStore
206
+ private sweeper?: ReturnType<typeof setInterval>
207
+ private maxSessions: number
208
+ private sessionIdleMs: number
209
+ private initTimeoutMs: number
210
+ private requestTimeoutMs?: number
211
+ private promptTimeoutMs?: number
212
+ private allowPathsOutsideCwd: boolean
213
+ private maxFileBytes?: number
214
+ private additionalDirectories?: string[]
215
+ private cmdSkillDir?: string
216
+ private cmdOrchestration: boolean
217
+ private onCommands?: (server: string) => void
218
+ /** Pool that owns agent processes; shared with other OpenCode directories when passed in. */
219
+ private agents: AgentPool
220
+ private ownsAgents: boolean
221
+ /** The pool lease each server's client came from, so released sessions do not outlive it. */
222
+ private leases = new Map<string, AgentLease>()
223
+ private disposed = false
224
+
225
+ constructor(input: {
226
+ servers: AcpServerConfig[]
227
+ defaultCwd: string
228
+ requestPermission?: PermissionResolver
229
+ mcp?: McpProvider
230
+ /** Persisted ACP session ids, so a restarted agent can resume its conversation. */
231
+ sessions?: AcpSessionStore
232
+ log?: LogFn
233
+ initTimeoutMs?: number
234
+ requestTimeoutMs?: number
235
+ promptTimeoutMs?: number
236
+ maxSessions?: number
237
+ sessionIdleMs?: number
238
+ allowPathsOutsideCwd?: boolean
239
+ maxFileBytes?: number
240
+ /** Extra roots offered to ACP agents, e.g. the generated skills mirror. */
241
+ additionalDirectories?: string[]
242
+ /** Directory passed to cmd through its global `--skill` flag. */
243
+ cmdSkillDir?: string
244
+ /** Load the cmd mod that hides native orchestration tools (set when the MCP bridge is on). */
245
+ cmdOrchestration?: boolean
246
+ /** Called when a server's advertised command list changes. */
247
+ onCommands?: (server: string) => void
248
+ /**
249
+ * Pool that owns agent processes. Pass `sharedAgentPool()` to share them
250
+ * across OpenCode directories; defaults to a private pool.
251
+ */
252
+ agents?: AgentPool
253
+ }) {
254
+ this.defaultCwd = input.defaultCwd
255
+ this.permissionResolver = input.requestPermission
256
+ this.mcp = input.mcp
257
+ this.sessions = input.sessions
258
+ this.log = input.log ?? (() => {})
259
+ this.initTimeoutMs = input.initTimeoutMs ?? DEFAULT_INIT_TIMEOUT_MS
260
+ this.requestTimeoutMs = input.requestTimeoutMs
261
+ this.promptTimeoutMs = input.promptTimeoutMs
262
+ const maxSessions = input.maxSessions ?? DEFAULT_MAX_SESSIONS
263
+ this.maxSessions = Number.isFinite(maxSessions) ? Math.max(1, Math.floor(maxSessions)) : DEFAULT_MAX_SESSIONS
264
+ this.sessionIdleMs = Math.max(0, input.sessionIdleMs ?? DEFAULT_SESSION_IDLE_MS)
265
+ this.allowPathsOutsideCwd = input.allowPathsOutsideCwd === true
266
+ this.maxFileBytes = input.maxFileBytes
267
+ this.additionalDirectories = input.additionalDirectories?.filter((directory) => directory.trim())
268
+ this.cmdSkillDir = input.cmdSkillDir
269
+ this.cmdOrchestration = input.cmdOrchestration === true
270
+ this.onCommands = input.onCommands
271
+ this.agents = input.agents ?? new AgentPool()
272
+ this.ownsAgents = input.agents === undefined
273
+
274
+ for (const config of input.servers) {
275
+ if (!config?.id || !config.command) continue
276
+ if (this.servers.has(config.id)) {
277
+ this.log("warn", `ignoring duplicate ACP server id "${config.id}"`)
278
+ continue
279
+ }
280
+ try {
281
+ normalizeCommand(config.command)
282
+ } catch (error) {
283
+ this.log(
284
+ "error",
285
+ `ignoring ACP server "${config.id}": ${errorMessage(error)}`,
286
+ )
287
+ continue
288
+ }
289
+ this.servers.set(config.id, {
290
+ config,
291
+ models: [],
292
+ efforts: [],
293
+ initialized: false,
294
+ })
295
+ }
296
+
297
+ if (this.sessionIdleMs > 0) {
298
+ this.sweeper = setInterval(() => this.sweepIdleSessions(), SWEEP_INTERVAL_MS)
299
+ this.sweeper.unref?.()
300
+ }
301
+ }
302
+
303
+ private assertLive() {
304
+ if (this.disposed) throw new Error("ACP server manager is stopped")
305
+ }
306
+
307
+ get list() {
308
+ return [...this.servers.values()].filter((state) => !state.config.disabled)
309
+ }
310
+
311
+ get(id: string) {
312
+ const state = this.servers.get(id)
313
+ return state && !state.config.disabled ? state : undefined
314
+ }
315
+
316
+ private poolKey(server: string, key: string, cwd: string) {
317
+ return `${server}\u0000${key}\u0000${cwd}`
318
+ }
319
+
320
+ private async storedSession(poolKey: string) {
321
+ if (!this.sessions) return undefined
322
+ try {
323
+ return await this.sessions.get(poolKey)
324
+ } catch (error) {
325
+ this.log("warn", `could not read a stored ACP session: ${errorMessage(error)}`)
326
+ return undefined
327
+ }
328
+ }
329
+
330
+ private async rememberSession(poolKey: string, sessionId: string) {
331
+ if (!this.sessions) return
332
+ try {
333
+ await this.sessions.set(poolKey, sessionId)
334
+ } catch (error) {
335
+ this.log("warn", `could not store ACP session ${sessionId}: ${errorMessage(error)}`)
336
+ }
337
+ }
338
+
339
+ private async forgetSession(poolKey: string) {
340
+ if (!this.sessions) return
341
+ try {
342
+ await this.sessions.delete(poolKey)
343
+ } catch {
344
+ // a stale id only costs one failed resume
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Keep the newest command list the agent advertised. Agents send this during
350
+ * `session/new` and can replace it later in the life of a session, so the
351
+ * snapshot taken at setup goes stale; listeners are told so they can rebuild.
352
+ */
353
+ private recordCommands(state: AcpServerState, commands: AcpCommand[]) {
354
+ const previous = state.commands
355
+ if (previous && sameCommands(previous, commands)) return
356
+ state.commands = commands
357
+ this.log("debug", `ACP server "${state.config.id}" advertised ${commands.length} command(s)`)
358
+ this.onCommands?.(state.config.id)
359
+ }
360
+
361
+ /** Effort to apply for a run: explicit request, then server config, then agent default. */
362
+ private resolveEffort(state: AcpServerState, requested?: string) {
363
+ const effort = requested ?? state.config.effort ?? state.defaultEffort
364
+ return effort && effort !== "default" ? effort : undefined
365
+ }
366
+
367
+ private sessionDirectories(config: AcpServerConfig, client?: AcpClient) {
368
+ const directories = [...(config.skills === false ? [] : (this.additionalDirectories ?? []))]
369
+ const lease = this.leases.get(config.id)
370
+ if (client && lease?.client === client) directories.push(...lease.readRoots)
371
+ return directories.length ? directories : undefined
372
+ }
373
+
374
+ private launchFor(config: AcpServerConfig, skillDir: string | undefined): AgentLaunch {
375
+ const { command, args } = normalizeCommand(
376
+ applyCmdMods(config.command, { orchestration: this.cmdOrchestration, skillDir }),
377
+ )
378
+ const env: Record<string, string> = { ...config.env }
379
+ if (skillDir !== undefined && isCmdCommand(config.command)) {
380
+ // Read by agents/cmd/mods/opencode-skills.ts, which registers the directory
381
+ // because `cmd acp` does not apply the global `--skill` flag.
382
+ env.OPENCODE_ACP_PROVIDER_SKILL_DIR = skillDir
383
+ }
384
+ return {
385
+ command,
386
+ args,
387
+ env,
388
+ cwd:
389
+ config.cwd ??
390
+ (this.ownsAgents || (!isAbsolute(command) && /[\\/]/.test(command)) ? this.defaultCwd : homedir()),
391
+ scope: this.ownsAgents ? config.id : undefined,
392
+ autoApprove: config.autoApprove !== false,
393
+ requestTimeoutMs: this.requestTimeoutMs,
394
+ promptTimeoutMs: this.promptTimeoutMs,
395
+ allowPathsOutsideCwd: this.allowPathsOutsideCwd,
396
+ maxFileBytes: this.maxFileBytes,
397
+ }
398
+ }
399
+
400
+ /** Install or update the agent before it is spawned; memoized per script. */
401
+ private setupFor(state: AcpServerState) {
402
+ const setup = state.config.setup?.trim()
403
+ return setup ? runSetup(setup, this.log) : Promise.resolve()
404
+ }
405
+
406
+ private async applyEffort(
407
+ state: AcpServerState,
408
+ client: AcpClient,
409
+ sessionId: string,
410
+ effort: string | undefined,
411
+ ) {
412
+ if (!effort) return
413
+ if (state.efforts.length && !state.efforts.includes(effort)) {
414
+ this.log("warn", `ACP server "${state.config.id}" does not support effort "${effort}" (available: ${state.efforts.join(", ")})`)
415
+ return
416
+ }
417
+ await client.setEffort(sessionId, effort, state.effortConfigID)
418
+ this.log("debug", `ACP effort set to ${effort}`)
419
+ }
420
+
421
+ /** Called only inside the conversation's queue, before its next prompt. */
422
+ private async select(
423
+ state: AcpServerState,
424
+ pooled: PooledSession,
425
+ selection: AcpSelection,
426
+ poolKey: string,
427
+ ) {
428
+ const previous = pooled.selection
429
+ if (previous && previous.model === selection.model && previous.effort === selection.effort) return
430
+ pooled.selection = undefined
431
+ const resetDefault =
432
+ (!selection.model && previous?.model !== undefined) ||
433
+ (!selection.effort && previous?.effort !== undefined)
434
+ if (previous && !resetDefault) {
435
+ try {
436
+ const modelChanged = previous.model !== selection.model
437
+ if (modelChanged && selection.model) {
438
+ await pooled.client.setModel(pooled.sessionId, selection.model, state.modelConfigID)
439
+ }
440
+ if (modelChanged || previous.effort !== selection.effort) {
441
+ await this.applyEffort(state, pooled.client, pooled.sessionId, selection.effort)
442
+ }
443
+ pooled.selection = selection
444
+ return
445
+ } catch (error) {
446
+ if (!isAcpError(error) || ![-32601, -32602].includes(error.code)) throw error
447
+ this.log("debug", `ACP session refused a selection change; replaying in a fresh session: ${error.message}`)
448
+ }
449
+ }
450
+
451
+ // Some agents cannot change a live selection or reset to the provider default.
452
+ // Keep the conversation queue, but replay history into a new ACP session.
453
+ // Resolve the MCP servers again: a remote server's OAuth grant may have been
454
+ // refreshed since this session opened, and ACP cannot update it in place.
455
+ const lease = this.mcp
456
+ ? await this.mcp.servers(pooled.key, state.config).catch((error) => {
457
+ this.log("warn", `could not refresh MCP servers for ${state.config.id}: ${errorMessage(error)}`)
458
+ return undefined
459
+ })
460
+ : undefined
461
+ const session = await pooled.client
462
+ .newSession(pooled.cwd, {
463
+ model: selection.model,
464
+ mcpServers: lease?.servers ?? pooled.mcpServers,
465
+ meta: state.config.meta,
466
+ additionalDirectories: this.sessionDirectories(state.config, pooled.client),
467
+ owner: this,
468
+ onCommands: (commands) => this.recordCommands(state, commands),
469
+ })
470
+ .catch((error) => {
471
+ lease?.release()
472
+ throw error
473
+ })
474
+ if (this.disposed) {
475
+ await pooled.client.closeSession(session.sessionId, this).catch(() => {})
476
+ lease?.release()
477
+ throw new Error("ACP server manager is stopped")
478
+ }
479
+ try {
480
+ if (state.config.mode) await pooled.client.setMode(session.sessionId, state.config.mode).catch(() => {})
481
+ await this.applyEffort(state, pooled.client, session.sessionId, selection.effort)
482
+ } catch (error) {
483
+ lease?.release()
484
+ await pooled.client.closeSession(session.sessionId, this).catch(() => {})
485
+ throw error
486
+ }
487
+ // The pool may have been closed while the new session was being prepared
488
+ // (an agent reload or shutdown does not wait for this queue). Releasing the
489
+ // fresh lease here keeps its bridge token from outliving a dead pool.
490
+ if (pooled.broken) {
491
+ lease?.release()
492
+ await pooled.client.closeSession(session.sessionId, this).catch(() => {})
493
+ throw new Error(`ACP session for key ${pooled.key.slice(0, 24)} was closed while changing selection`)
494
+ }
495
+ const oldSession = pooled.sessionId
496
+ pooled.sessionId = session.sessionId
497
+ pooled.history = "fresh"
498
+ pooled.selection = selection
499
+ if (lease) {
500
+ pooled.mcpRelease?.()
501
+ pooled.mcpServers = lease.servers
502
+ pooled.mcpRelease = lease.release
503
+ }
504
+ await this.rememberSession(poolKey, session.sessionId)
505
+ await pooled.client.closeSession(oldSession, this).catch(() => {})
506
+ }
507
+
508
+ /** Discover enabled agents in parallel and report each result independently. */
509
+ async initialize(onSettled?: (state: AcpServerState) => Promise<void>) {
510
+ if (this.disposed) return
511
+ await Promise.all(
512
+ this.list.map(async (state) => {
513
+ try {
514
+ // Installing or updating the agent is not part of the timed handshake.
515
+ await this.setupFor(state)
516
+ if (this.disposed) return
517
+ await withTimeout(
518
+ this.prepare(state),
519
+ this.initTimeoutMs,
520
+ `ACP server "${state.config.id}" did not initialize within ${this.initTimeoutMs}ms`,
521
+ )
522
+ } catch (error) {
523
+ if (this.disposed) return
524
+ state.error = errorMessage(error)
525
+ this.log("error", `ACP server "${state.config.id}" failed to initialize: ${state.error}`)
526
+ // Do not stop the client here: a timed-out prepare may still finish.
527
+ // It stops its own client on failure, and a success is still usable.
528
+ }
529
+ if (!this.disposed) await onSettled?.(state)
530
+ }),
531
+ )
532
+ }
533
+
534
+ /** Re-run discovery, e.g. after a server failed to start during setup. */
535
+ async refresh(state: AcpServerState) {
536
+ this.assertLive()
537
+ const id = state.config.id
538
+ // Setup runs outside the timed work: a slow install is not an init timeout.
539
+ await this.setupFor(state)
540
+ this.assertLive()
541
+ const work = (async () => {
542
+ const inFlight = this.preparing.get(id)
543
+ if (inFlight) await inFlight.catch(() => {})
544
+ if (state.initialized && state.models.length) return
545
+ this.assertLive()
546
+ state.initialized = false
547
+ state.error = undefined
548
+ await this.prepare(state)
549
+ })()
550
+ try {
551
+ await withTimeout(work, this.initTimeoutMs, `ACP server "${id}" did not initialize within ${this.initTimeoutMs}ms`)
552
+ } catch (error) {
553
+ state.error = errorMessage(error)
554
+ throw error
555
+ }
556
+ }
557
+
558
+ private prepare(state: AcpServerState): Promise<void> {
559
+ if (this.disposed) return Promise.reject(new Error("ACP server manager is stopped"))
560
+ if (state.initialized) return Promise.resolve()
561
+ const id = state.config.id
562
+ const existing = this.preparing.get(id)
563
+ if (existing) return existing
564
+ let promise: Promise<void>
565
+ promise = this.doPrepare(state).finally(() => {
566
+ if (this.preparing.get(id) === promise) this.preparing.delete(id)
567
+ })
568
+ this.preparing.set(id, promise)
569
+ return promise
570
+ }
571
+
572
+ private async doPrepare(state: AcpServerState) {
573
+ const config = state.config
574
+ this.assertLive()
575
+ // The lazy path through `prepare()` waits for setup too; the memo makes it
576
+ // instant when discovery already ran it.
577
+ await this.setupFor(state)
578
+ this.assertLive()
579
+
580
+ const previous = state.client
581
+ if (previous) {
582
+ await this.closePoolsFor(config.id)
583
+ this.leases.get(config.id)?.release()
584
+ this.leases.delete(config.id)
585
+ }
586
+ this.assertLive()
587
+
588
+ const skillDir = config.skills === false ? undefined : this.cmdSkillDir
589
+ const subscriber: AgentSubscriber = {
590
+ onLog: (level, message) => this.log(level, `[${config.id}] ${message}`),
591
+ onExit: (error) => {
592
+ this.log("warn", `ACP agent "${config.id}" exited; pooled sessions were dropped: ${error.message}`)
593
+ void this.closePoolsFor(config.id)
594
+ },
595
+ }
596
+ const dedicated = isCmdCommand(config.command) || config.share === false
597
+ const lease = dedicated
598
+ ? this.agents.dedicated({ launch: (dir) => this.launchFor(config, dir), skillDir }, subscriber)
599
+ : this.agents.acquire(this.launchFor(config, skillDir), subscriber)
600
+ this.leases.set(config.id, lease)
601
+ const client = lease.client
602
+ state.client = client
603
+ state.retryable = true
604
+
605
+ try {
606
+ const session = await client.newSession(config.cwd ?? this.defaultCwd, {
607
+ meta: config.meta,
608
+ additionalDirectories: this.sessionDirectories(config, client),
609
+ owner: this,
610
+ onCommands: (commands) => this.recordCommands(state, commands),
611
+ })
612
+ try {
613
+ this.assertLive()
614
+ const defaultModel = session.currentModel ?? (session.modelConfigID ? undefined : "default")
615
+ let models = session.models.length
616
+ ? session.models
617
+ : defaultModel ? [{ id: defaultModel, name: session.currentModel ?? "Agent default" }] : []
618
+ if (!session.modelConfigID && config.model && config.model !== defaultModel) {
619
+ state.retryable = false
620
+ throw new Error(`ACP server "${config.id}" does not expose an ACP model selector; use "default" or omit "model"`)
621
+ }
622
+ if (config.models?.length) {
623
+ const allow = new Set(config.models)
624
+ models = models.filter((model) => allow.has(model.id))
625
+ if (!models.length) {
626
+ state.retryable = false
627
+ throw new Error(
628
+ `ACP server "${config.id}" advertised no model matching "models" (${config.models.join(", ")})`,
629
+ )
630
+ }
631
+ }
632
+ if (config.model && models.length && !models.some((model) => model.id === config.model)) {
633
+ this.log(
634
+ "warn",
635
+ `ACP server "${config.id}" does not advertise the configured model "${config.model}"; it will be sent anyway`,
636
+ )
637
+ }
638
+ state.models = models
639
+ state.defaultModel = defaultModel
640
+ state.modelConfigID = session.modelConfigID
641
+ state.efforts = (session.efforts ?? []).filter((value) => value !== "default")
642
+ state.effortConfigID = session.effort?.configId
643
+ state.defaultEffort = session.effort?.currentValue
644
+ state.initialized = true
645
+ state.error = undefined
646
+ // The command list arrives as a notification just after `session/new`, so
647
+ // wait for it before this discovery session is closed: once it is gone,
648
+ // the only way to learn the list is to open another session.
649
+ const commands = await client.waitForCommands(session.sessionId, COMMAND_SNAPSHOT_TIMEOUT_MS)
650
+ if (commands) this.recordCommands(state, commands)
651
+ this.log(
652
+ "info",
653
+ `ACP server "${config.id}" ready with ${models.length} model(s)` +
654
+ (state.efforts.length ? ` and effort levels: ${state.efforts.join(", ")}` : ""),
655
+ )
656
+ } finally {
657
+ await client.closeSession(session.sessionId, this).catch(() => {})
658
+ }
659
+ } catch (error) {
660
+ if (this.leases.get(config.id) === lease) {
661
+ lease.release()
662
+ this.leases.delete(config.id)
663
+ }
664
+ if (state.client === client) state.client = undefined
665
+ throw error
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Run one prompt. When `key` is supplied the ACP session is reused across
671
+ * calls, which keeps the agent's context (and cost) down; otherwise a fresh
672
+ * session is created and closed.
673
+ *
674
+ * `prompt.fresh` is used when a new ACP session is created; `prompt.reused`
675
+ * is used when an existing one is resumed. The decision is made inside the
676
+ * pool so it cannot race with eviction or failure cleanup.
677
+ */
678
+ async run(input: {
679
+ server: string
680
+ prompt: string | { fresh: string; reused: string }
681
+ model?: string
682
+ effort?: string
683
+ key?: string
684
+ sessionKey?: string
685
+ signal?: AbortSignal
686
+ onUpdate?: (update: SessionUpdate) => void
687
+ }): Promise<AcpRunResult> {
688
+ if (input.signal?.aborted) return { stopReason: "cancelled", text: "" }
689
+ // Negotiating a cold or restored ACP session takes a moment. Mark the turn
690
+ // as starting before the first await so a steer that arrives in that window
691
+ // is not mistaken for an idle session.
692
+ const key = input.key
693
+ let starting = false
694
+ if (key) {
695
+ starting = true
696
+ this.starting.set(key, (this.starting.get(key) ?? 0) + 1)
697
+ }
698
+ const finishStarting = () => {
699
+ if (!starting || !key) return
700
+ starting = false
701
+ const remaining = (this.starting.get(key) ?? 1) - 1
702
+ if (remaining > 0) this.starting.set(key, remaining)
703
+ else this.starting.delete(key)
704
+ }
705
+
706
+ try {
707
+ const state = this.get(input.server)
708
+ if (!state) throw new Error(`Unknown ACP server: ${input.server}`)
709
+ await this.prepare(state)
710
+ const client = state.client
711
+ if (!client) throw new Error(`ACP server "${input.server}" is not ready`)
712
+
713
+ const cwd = state.config.cwd ?? this.defaultCwd
714
+ const requestedModel = input.model ?? state.config.model ?? state.defaultModel
715
+ if (!state.modelConfigID && requestedModel !== state.defaultModel) {
716
+ throw new Error(`ACP server "${input.server}" does not expose an ACP model selector`)
717
+ }
718
+ const model = state.modelConfigID ? requestedModel : undefined
719
+ const mode = state.config.mode
720
+ const effort = this.resolveEffort(state, input.effort)
721
+ const onPermission = this.permissionHandler(input.server, input.sessionKey)
722
+
723
+ if (!input.key) {
724
+ const prompt = typeof input.prompt === "string" ? input.prompt : input.prompt.fresh
725
+ const session = await client.newSession(cwd, {
726
+ model,
727
+ meta: state.config.meta,
728
+ additionalDirectories: this.sessionDirectories(state.config, client),
729
+ owner: this,
730
+ onCommands: (commands) => this.recordCommands(state, commands),
731
+ })
732
+ if (this.disposed) {
733
+ await client.closeSession(session.sessionId, this).catch(() => {})
734
+ throw new Error("ACP server manager is stopped")
735
+ }
736
+ try {
737
+ if (mode) await client.setMode(session.sessionId, mode).catch(() => {})
738
+ await this.applyEffort(state, client, session.sessionId, effort)
739
+ return await client.prompt(session.sessionId, prompt, {
740
+ owner: this,
741
+ onUpdate: input.onUpdate,
742
+ signal: input.signal,
743
+ requestPermission: onPermission,
744
+ })
745
+ } finally {
746
+ await client.closeSession(session.sessionId, this)
747
+ }
748
+ }
749
+
750
+ const poolKey = this.poolKey(input.server, input.key, cwd)
751
+ const existing = this.pools.get(poolKey)
752
+ let negotiating = this.negotiating.get(poolKey)
753
+ if (!existing && !negotiating) {
754
+ const eviction = this.reserveCapacity()
755
+ // Install this reservation before the negotiation can open a session.
756
+ negotiating = Promise.resolve().then(async () => {
757
+ if (eviction) await eviction
758
+ this.assertLive()
759
+ const sessionStartedAt = Date.now()
760
+ const lease = await this.mcp?.servers(input.key!, state.config)
761
+ let session: { sessionId: string } | undefined
762
+ let reused = false
763
+ try {
764
+ // A plugin reload or an agent crash leaves a fresh process with no
765
+ // sessions. Reattach to the one this OpenCode session had instead of
766
+ // starting over and losing the conversation.
767
+ // Migrate the previously variant-keyed store without losing an
768
+ // existing conversation on the first run after upgrading.
769
+ const legacyKey = `${input.server}\u0000${input.key}\u0000${model ?? ""}\u0000${cwd}\u0000${effort ?? ""}`
770
+ const stored = (await this.storedSession(poolKey)) ?? (await this.storedSession(legacyKey))
771
+ if (stored) {
772
+ const restored = await client
773
+ .restoreSession(stored, {
774
+ cwd,
775
+ mcpServers: lease?.servers,
776
+ meta: state.config.meta,
777
+ additionalDirectories: this.sessionDirectories(state.config, client),
778
+ owner: this,
779
+ onCommands: (commands) => this.recordCommands(state, commands),
780
+ })
781
+ .catch(async (error) => {
782
+ this.log(
783
+ "warn",
784
+ `could not restore ACP session ${stored} for key ${input.key!.slice(0, 24)}: ${errorMessage(error)}; starting a new one`,
785
+ )
786
+ await this.forgetSession(poolKey)
787
+ return undefined
788
+ })
789
+ if (this.disposed) {
790
+ if (restored) await client.closeSession(stored, this).catch(() => {})
791
+ lease?.release()
792
+ throw new Error("ACP server manager is stopped")
793
+ }
794
+ if (restored) {
795
+ session = { sessionId: stored }
796
+ reused = true
797
+ await this.rememberSession(poolKey, stored)
798
+ this.log(
799
+ "debug",
800
+ `restored ACP session ${stored} (${restored}) for key ${input.key!.slice(0, 24)}`,
801
+ )
802
+ }
803
+ }
804
+ if (!session) {
805
+ session = await client.newSession(cwd, {
806
+ model,
807
+ mcpServers: lease?.servers,
808
+ meta: state.config.meta,
809
+ additionalDirectories: this.sessionDirectories(state.config, client),
810
+ owner: this,
811
+ onCommands: (commands) => this.recordCommands(state, commands),
812
+ })
813
+ if (this.disposed) {
814
+ await client.closeSession(session.sessionId, this).catch(() => {})
815
+ lease?.release()
816
+ throw new Error("ACP server manager is stopped")
817
+ }
818
+ await this.rememberSession(poolKey, session.sessionId)
819
+ }
820
+ if (mode) await client.setMode(session.sessionId, mode).catch(() => {})
821
+ // A restored session keeps its old model, so put the requested one back.
822
+ if (reused && model) {
823
+ await client.setModel(session.sessionId, model, state.modelConfigID)
824
+ }
825
+ // Set effort after model: changing models can reset it.
826
+ await this.applyEffort(state, client, session.sessionId, effort)
827
+ } catch (error) {
828
+ lease?.release()
829
+ if (session) await client.closeSession(session.sessionId, this).catch(() => {})
830
+ throw error
831
+ }
832
+ if (this.disposed) {
833
+ await client.closeSession(session.sessionId, this).catch(() => {})
834
+ lease?.release()
835
+ throw new Error("ACP server manager is stopped")
836
+ }
837
+ const created: PooledSession = {
838
+ server: input.server,
839
+ key: input.key!,
840
+ sessionId: session.sessionId,
841
+ client,
842
+ selection: { model, effort },
843
+ history: reused ? "retained" : "fresh",
844
+ mcpServers: lease?.servers,
845
+ cwd,
846
+ queue: Promise.resolve(),
847
+ lastUsed: Date.now(),
848
+ pending: 0,
849
+ active: 0,
850
+ failures: 0,
851
+ broken: false,
852
+ mcpRelease: lease?.release,
853
+ }
854
+ this.pools.set(poolKey, created)
855
+ this.log(
856
+ "debug",
857
+ `opened ACP session ${session.sessionId} for key ${input.key!.slice(0, 24)} in ${Date.now() - sessionStartedAt}ms`,
858
+ )
859
+ return created
860
+ })
861
+ this.negotiating.set(poolKey, negotiating)
862
+ }
863
+ let pooled: PooledSession
864
+ if (existing) {
865
+ pooled = existing
866
+ this.log("debug", `reusing ACP session ${pooled.sessionId} for key ${input.key.slice(0, 24)}`)
867
+ } else {
868
+ try {
869
+ pooled = await negotiating!
870
+ } finally {
871
+ if (this.negotiating.get(poolKey) === negotiating) this.negotiating.delete(poolKey)
872
+ }
873
+ }
874
+ if (pooled.broken || this.pools.get(poolKey) !== pooled) {
875
+ throw new Error(`ACP session for key ${input.key.slice(0, 24)} was closed after an earlier turn failed`)
876
+ }
877
+
878
+ pooled.lastUsed = Date.now()
879
+ pooled.pending += 1
880
+ const run = pooled.queue.then(async () => {
881
+ if (pooled.broken) throw new Error(`ACP session ${pooled.sessionId} is no longer usable`)
882
+ if (input.signal?.aborted) return { stopReason: "cancelled", text: "" }
883
+ await this.select(state, pooled, { model, effort }, poolKey)
884
+ if (pooled.broken) throw new Error(`ACP session ${pooled.sessionId} is no longer usable`)
885
+ if (input.signal?.aborted) return { stopReason: "cancelled", text: "" }
886
+ const prompt =
887
+ typeof input.prompt === "string"
888
+ ? input.prompt
889
+ : pooled.history === "retained" ? input.prompt.reused : input.prompt.fresh
890
+ pooled.active += 1
891
+ finishStarting()
892
+ pooled.history = "retained"
893
+ const turn = pooled.client
894
+ .prompt(pooled.sessionId, prompt, {
895
+ owner: this,
896
+ onUpdate: input.onUpdate,
897
+ signal: input.signal,
898
+ requestPermission: onPermission,
899
+ })
900
+ .finally(() => {
901
+ pooled.active = Math.max(0, pooled.active - 1)
902
+ })
903
+ // `prompt` has already written the request, so the agent sees the cancel
904
+ // after the prompt it belongs to.
905
+ if (key && this.startCancels.delete(key)) {
906
+ pooled.client.cancelTurn(pooled.sessionId, this)
907
+ this.log("debug", `cancelled ACP session ${pooled.sessionId} for a steer that arrived while it was starting`)
908
+ }
909
+ return turn
910
+ })
911
+ pooled.queue = run.catch(() => {})
912
+ void run.then(
913
+ () => {
914
+ pooled.failures = 0
915
+ },
916
+ (error: unknown) => this.onTurnFailed(poolKey, pooled, error),
917
+ ).finally(() => {
918
+ pooled.pending = Math.max(0, pooled.pending - 1)
919
+ pooled.lastUsed = Date.now()
920
+ })
921
+ return await run
922
+ } finally {
923
+ finishStarting()
924
+ if (key && !this.starting.has(key)) this.startCancels.delete(key)
925
+ }
926
+ }
927
+
928
+ private onTurnFailed(poolKey: string, pooled: PooledSession, error: unknown) {
929
+ // A failed turn does not necessarily invalidate the ACP session. The
930
+ // process dying or the agent forgetting the session does; everything else
931
+ // (cancel, timeout, reset) keeps the context, so a retry resumes the same
932
+ // conversation instead of starting a new one.
933
+ if (this.pools.get(poolKey) !== pooled) return
934
+ const message = errorMessage(error)
935
+ const unknown = isUnknownSession(error)
936
+ if (unknown || !pooled.client.alive || !pooled.client.hasSession(pooled.sessionId, this)) {
937
+ void this.dropPool(poolKey, pooled)
938
+ if (unknown) void this.forgetSession(poolKey)
939
+ return
940
+ }
941
+ pooled.failures += 1
942
+ if (isAcpError(error) && error.code === ACP_REQUEST_CANCELLED) {
943
+ // A stopped turn is normal; the agent already ended it, so the session
944
+ // is intact and the next prompt picks up the same conversation.
945
+ pooled.failures = 0
946
+ this.log("debug", `kept ACP session ${pooled.sessionId} after a cancelled turn`)
947
+ return
948
+ }
949
+ if (pooled.failures >= MAX_TURN_FAILURES) {
950
+ this.log("warn", `dropping ACP session ${pooled.sessionId} after ${pooled.failures} failed turns: ${message}`)
951
+ void this.dropPool(poolKey, pooled)
952
+ // A session that failed this many times in a row should not be restored
953
+ // into the same state on the next turn.
954
+ void this.forgetSession(poolKey)
955
+ return
956
+ }
957
+ // Ask the agent to end whatever it is still running so the queued or next
958
+ // prompt enters the same context at a clean boundary.
959
+ pooled.client.cancelTurn(pooled.sessionId, this)
960
+ this.log("debug", `keeping ACP session ${pooled.sessionId} after a failed turn: ${message}`)
961
+ }
962
+
963
+ /** Drop a pooled session on our side, leaving its stored id unless callers forget it. */
964
+ private async dropPool(poolKey: string, pooled: PooledSession) {
965
+ pooled.broken = true
966
+ if (this.pools.get(poolKey) === pooled) this.pools.delete(poolKey)
967
+ pooled.mcpRelease?.()
968
+ await pooled.client.closeSession(pooled.sessionId, this).catch(() => {})
969
+ }
970
+
971
+ /**
972
+ * Whether an ACP turn is streaming for this OpenCode session right now.
973
+ * A turn still negotiating its ACP session counts too: a message sent in that
974
+ * window has to be steered even though no prompt is in flight yet.
975
+ */
976
+ running(key: string) {
977
+ if (this.starting.has(key)) return true
978
+ return [...this.pools.values()].some((entry) => entry.key === key && entry.active > 0 && !entry.broken)
979
+ }
980
+
981
+ /** End the current ACP turn so OpenCode can deliver its queued steer next. */
982
+ interrupt(key: string) {
983
+ const pooled = [...this.pools.values()]
984
+ .filter((entry) => entry.key === key && entry.active > 0 && !entry.broken)
985
+ .sort((left, right) => right.lastUsed - left.lastUsed)[0]
986
+ if (!pooled) {
987
+ if (this.starting.has(key)) this.startCancels.add(key)
988
+ return
989
+ }
990
+
991
+ pooled.client.cancelTurn(pooled.sessionId, this)
992
+ this.log("debug", `interrupted ACP session ${pooled.sessionId} so the queued message can be delivered`)
993
+ }
994
+
995
+ /**
996
+ * Compact the agent's own context for an OpenCode session with the agent's
997
+ * `/compact` command. Only an existing pooled session is compacted; opening
998
+ * one would compact nothing. The command waits behind any running turn.
999
+ */
1000
+ async compact(input: { server: string; key: string }): Promise<AcpCompactResult> {
1001
+ const prefix = `${input.server}\u0000${input.key}\u0000`
1002
+ const pooled = [...this.pools.entries()]
1003
+ .filter(([poolKey, entry]) => poolKey.startsWith(prefix) && !entry.broken)
1004
+ .map(([, entry]) => entry)
1005
+ .sort((left, right) => right.lastUsed - left.lastUsed)[0]
1006
+ if (!pooled) return { status: "no-session" }
1007
+ if (!pooled.client.hasCommand(pooled.sessionId, "compact")) return { status: "unsupported" }
1008
+
1009
+ let tokens: { before: number; after: number } | undefined
1010
+ pooled.pending += 1
1011
+ const run = pooled.queue.then(() => {
1012
+ if (pooled.broken) throw new Error(`ACP session ${pooled.sessionId} is no longer usable`)
1013
+ return pooled.client.prompt(pooled.sessionId, "/compact", {
1014
+ owner: this,
1015
+ onUpdate: (update) => {
1016
+ // Claude Code reports a compaction as a tool call with its context size before and after.
1017
+ const output = update.rawOutput as { preTokens?: unknown; postTokens?: unknown } | undefined
1018
+ if (typeof output?.preTokens === "number" && typeof output.postTokens === "number") {
1019
+ tokens = { before: output.preTokens, after: output.postTokens }
1020
+ }
1021
+ },
1022
+ })
1023
+ })
1024
+ pooled.queue = run.catch(() => {})
1025
+ try {
1026
+ const result = await run
1027
+ return { status: "compacted", text: result.text.trim(), ...(tokens ? { tokens } : {}) }
1028
+ } finally {
1029
+ pooled.pending = Math.max(0, pooled.pending - 1)
1030
+ pooled.lastUsed = Date.now()
1031
+ }
1032
+ }
1033
+
1034
+ private permissionHandler(server: string, sessionKey: string | undefined): PermissionHandler | undefined {
1035
+ const resolver = this.permissionResolver
1036
+ if (!resolver || !sessionKey) return undefined
1037
+ return (request) => resolver({ ...request, server, sessionKey })
1038
+ }
1039
+
1040
+ private reserveCapacity(): Promise<void> | undefined {
1041
+ let reserved = this.pools.size
1042
+ for (const key of this.negotiating.keys()) if (!this.pools.has(key)) reserved++
1043
+ if (reserved < this.maxSessions) return
1044
+ let oldest: [string, PooledSession] | undefined
1045
+ for (const entry of this.pools) {
1046
+ const [key, pooled] = entry
1047
+ if (pooled.pending > 0 || this.negotiating.has(key)) continue
1048
+ if (!oldest || pooled.lastUsed < oldest[1].lastUsed) oldest = entry
1049
+ }
1050
+ if (!oldest) throw new Error(`ACP session pool at capacity (${this.maxSessions}); retry after a turn finishes`)
1051
+ this.log("debug", `evicting idle ACP session ${oldest[1].sessionId} (capacity ${this.maxSessions})`)
1052
+ return this.dropPool(...oldest)
1053
+ }
1054
+
1055
+ private sweepIdleSessions() {
1056
+ const cutoff = Date.now() - this.sessionIdleMs
1057
+ for (const [key, pooled] of this.pools) {
1058
+ if (pooled.pending > 0 || this.negotiating.has(key) || pooled.lastUsed > cutoff) continue
1059
+ void this.dropPool(key, pooled)
1060
+ this.log("debug", `closed idle ACP session ${pooled.sessionId} after ${this.sessionIdleMs}ms`)
1061
+ }
1062
+ }
1063
+
1064
+ private async closePoolsFor(server: string) {
1065
+ const prefix = `${server}\u0000`
1066
+ const closed: Array<Promise<unknown>> = []
1067
+ for (const [key, pooled] of this.pools) {
1068
+ if (key.startsWith(prefix)) closed.push(this.dropPool(key, pooled))
1069
+ }
1070
+
1071
+ await Promise.allSettled(closed)
1072
+ }
1073
+
1074
+ async stop() {
1075
+ this.disposed = true
1076
+ if (this.sweeper) clearInterval(this.sweeper)
1077
+ this.sweeper = undefined
1078
+ this.preparing.clear()
1079
+ this.negotiating.clear()
1080
+ const pools = [...this.pools.values()]
1081
+ this.pools.clear()
1082
+ // Best effort: the agent may be shared with another directory, so do not
1083
+ // wait on a close handshake that could hang shutdown. Closing drops the
1084
+ // session from the client, so its owner loop below can no longer see it:
1085
+ // end the turn here, or a shared agent would keep running one nobody reads.
1086
+ for (const pooled of pools) {
1087
+ pooled.broken = true
1088
+ pooled.mcpRelease?.()
1089
+ pooled.client.cancelTurn(pooled.sessionId, this)
1090
+ void pooled.client.closeSession(pooled.sessionId, this).catch(() => {})
1091
+ }
1092
+ // Only this manager's sessions close; another directory's stay on the client.
1093
+ for (const lease of this.leases.values()) {
1094
+ for (const sessionId of lease.client.sessionsOwnedBy(this)) {
1095
+ lease.client.cancelTurn(sessionId, this)
1096
+ void lease.client.closeSession(sessionId, this).catch(() => {})
1097
+ }
1098
+ }
1099
+ for (const lease of this.leases.values()) lease.release()
1100
+ this.leases.clear()
1101
+ for (const state of this.servers.values()) state.client = undefined
1102
+ if (this.ownsAgents) await this.agents.stop()
1103
+ }
1104
+ }
1105
+
1106
+ function isUnknownSession(error: unknown) {
1107
+ if (!isAcpError(error)) return false
1108
+ if (error.code === ACP_UNKNOWN_SESSION) return true
1109
+ return /unknown (acp )?session|session .*not found|session .*does not exist/i.test(error.message)
1110
+ }
1111
+
1112
+ /** Whether two advertised command lists are the same, so a rebuild can be skipped. */
1113
+ function sameCommands(left: AcpCommand[], right: AcpCommand[]) {
1114
+ if (left.length !== right.length) return false
1115
+ return left.every((command, index) => {
1116
+ const other = right[index]
1117
+ return command.name === other.name && command.description === other.description && command.hint === other.hint
1118
+ })
1119
+ }
1120
+
1121
+ function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
1122
+ if (!(ms > 0) || !Number.isFinite(ms)) return promise
1123
+ return new Promise<T>((resolve, reject) => {
1124
+ const timer = setTimeout(() => reject(new Error(message)), ms)
1125
+ timer.unref?.()
1126
+ promise.then(
1127
+ (value) => {
1128
+ clearTimeout(timer)
1129
+ resolve(value)
1130
+ },
1131
+ (error) => {
1132
+ clearTimeout(timer)
1133
+ reject(error)
1134
+ },
1135
+ )
1136
+ })
1137
+ }