opencode-acp-provider 0.0.0-stage → 1.0.0

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