opencode-acp-provider 1.0.0 → 1.1.1

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.
@@ -1,16 +1,28 @@
1
+ import { homedir } from "node:os"
2
+ import { isAbsolute } from "node:path"
1
3
  import {
2
4
  ACP_REQUEST_CANCELLED,
3
5
  AcpClient,
4
- AcpError,
6
+ isAcpError,
5
7
  type AcpCommand,
6
8
  type AcpMcpServer,
7
9
  type SessionUpdate,
8
10
  type PermissionHandler,
9
11
  } from "./acp-client.ts"
12
+ import { AgentPool, type AgentLaunch, type AgentLease, type AgentSubscriber } from "./agent-pool.ts"
10
13
  import { applyCmdMods } from "./agents/cmd/index.ts"
11
14
  import { isCmdCommand } from "./agent-command.ts"
15
+ import { commandOf, record, text } from "./acp-tools/shared.ts"
16
+ import { effortLevels, inventoryKey, type AcpCatalog } from "./inventory.ts"
12
17
  import { runSetup } from "./setup.ts"
13
- import { errorMessage } from "./util.ts"
18
+ import {
19
+ isUnsolicitedActivity,
20
+ unsolicitedSummary,
21
+ UnsolicitedTurn,
22
+ type BackgroundToolRecord,
23
+ type UnsolicitedTimingOptions,
24
+ } from "./unsolicited.ts"
25
+ import { agentName, errorMessage } from "./util.ts"
14
26
 
15
27
  export interface AcpServerConfig {
16
28
  /** Stable id used for the OpenCode provider and tool arguments. */
@@ -26,10 +38,21 @@ export interface AcpServerConfig {
26
38
  * failure is logged and the agent still starts.
27
39
  */
28
40
  setup?: string
29
- /** Working directory for the agent process. Defaults to the OpenCode location. */
41
+ /**
42
+ * Working directory for the agent process and its sessions. When unset,
43
+ * sessions use the OpenCode location, and the process starts in the home
44
+ * directory if it is shared across directories (else in the OpenCode location).
45
+ */
30
46
  cwd?: string
31
47
  /** Extra environment variables for the agent process. */
32
48
  env?: Record<string, string>
49
+ /**
50
+ * Share one agent process across OpenCode directories. Defaults to true,
51
+ * except for Command Code (`cmd`), which binds a process to one directory and
52
+ * always gets its own process with a warm spare. Set false for other agents
53
+ * that serve one directory per process.
54
+ */
55
+ share?: boolean
33
56
  /** Optional allowlist of ACP model ids to expose. */
34
57
  models?: string[]
35
58
  /** Default ACP model for direct tool calls. */
@@ -52,6 +75,15 @@ export interface AcpModelInfo {
52
75
  id: string
53
76
  name: string
54
77
  description?: string
78
+ /**
79
+ * Effort levels this model offers, excluding the implicit default. Agents such
80
+ * as Antigravity offer different levels per model, and some models none at
81
+ * all. Learned when the model is first selected; until then it is undefined
82
+ * and the server-wide list applies.
83
+ */
84
+ efforts?: string[]
85
+ /** The agent's own effort for this model, as reported before any effort was set. */
86
+ defaultEffort?: string
55
87
  }
56
88
 
57
89
  export interface AcpServerState {
@@ -63,7 +95,6 @@ export interface AcpServerState {
63
95
  /** Reasoning effort levels advertised by the agent, excluding the implicit default. */
64
96
  efforts: string[]
65
97
  effortConfigID?: string
66
- defaultEffort?: string
67
98
  error?: string
68
99
  /** False when retrying cannot help, e.g. a `models` allowlist that matches nothing. */
69
100
  retryable?: boolean
@@ -132,6 +163,7 @@ interface AcpSelection {
132
163
  interface PooledSession {
133
164
  server: string
134
165
  key: string
166
+ sessionKey: string
135
167
  sessionId: string
136
168
  client: AcpClient
137
169
  /** Undefined after a refused/uncertain config write; never assume it applied. */
@@ -148,6 +180,30 @@ interface PooledSession {
148
180
  failures: number
149
181
  broken: boolean
150
182
  mcpRelease?: () => void
183
+ /** Tools started in an earlier turn that had not settled when that turn returned. */
184
+ backgroundTools: Map<string, TrackedBackgroundTool>
185
+ /** Autonomous post-turn continuation currently streaming for this session, if any. */
186
+ activeUnsolicited?: UnsolicitedTurn
187
+ activeUnsolicitedTools?: Map<string, TurnToolRecord>
188
+ /** Buffered/live unsolicited turns keyed by their continuation token. */
189
+ pendingContinuations: Map<string, UnsolicitedTurn>
190
+ }
191
+
192
+ interface TrackedBackgroundTool extends BackgroundToolRecord {
193
+ kind?: string
194
+ meta?: Record<string, unknown>
195
+ }
196
+
197
+ interface TurnToolRecord extends TrackedBackgroundTool {
198
+ terminal: boolean
199
+ }
200
+
201
+ export interface AcpUnsolicitedTurnInfo {
202
+ readonly server: string
203
+ readonly sessionKey: string
204
+ readonly token: string
205
+ readonly description: string
206
+ readonly text: string
151
207
  }
152
208
 
153
209
  interface AcpRunResult {
@@ -174,6 +230,7 @@ const MAX_TURN_FAILURES = 3
174
230
  /** How long to wait for the command list an agent sends after `session/new`. */
175
231
  const COMMAND_SNAPSHOT_TIMEOUT_MS = 2_000
176
232
  const SWEEP_INTERVAL_MS = 60_000
233
+ const MAX_BACKGROUND_TOOLS = 64
177
234
 
178
235
  export class AcpServerManager {
179
236
  readonly servers = new Map<string, AcpServerState>()
@@ -201,6 +258,16 @@ export class AcpServerManager {
201
258
  private cmdSkillDir?: string
202
259
  private cmdOrchestration: boolean
203
260
  private onCommands?: (server: string) => void
261
+ private onModels?: (server: string) => void
262
+ private onUnsolicited?: (turn: AcpUnsolicitedTurnInfo) => void
263
+ private unsolicitedTiming?: UnsolicitedTimingOptions
264
+ private discoverCommands: boolean
265
+ private catalogs = new Map<string, { catalog: AcpCatalog; onModels: () => void }>()
266
+ /** Pool that owns agent processes; shared with other OpenCode directories when passed in. */
267
+ private agents: AgentPool
268
+ private ownsAgents: boolean
269
+ /** The pool lease each server's client came from, so released sessions do not outlive it. */
270
+ private leases = new Map<string, AgentLease>()
204
271
  private disposed = false
205
272
 
206
273
  constructor(input: {
@@ -226,6 +293,19 @@ export class AcpServerManager {
226
293
  cmdOrchestration?: boolean
227
294
  /** Called when a server's advertised command list changes. */
228
295
  onCommands?: (server: string) => void
296
+ /** Open a local session to discover this location's slash commands. */
297
+ discoverCommands?: boolean
298
+ /** Called when a model's effort levels are learned, which changes its variants. */
299
+ onModels?: (server: string) => void
300
+ /** Called when an idle pooled session emits unsolicited post-turn agent activity. */
301
+ onUnsolicited?: (turn: AcpUnsolicitedTurnInfo) => void
302
+ /** Override idle timers for unsolicited turns (primarily for testing). */
303
+ unsolicitedTiming?: UnsolicitedTimingOptions
304
+ /**
305
+ * Pool that owns agent processes. Pass `sharedAgentPool()` to share them
306
+ * across OpenCode directories; defaults to a private pool.
307
+ */
308
+ agents?: AgentPool
229
309
  }) {
230
310
  this.defaultCwd = input.defaultCwd
231
311
  this.permissionResolver = input.requestPermission
@@ -244,6 +324,12 @@ export class AcpServerManager {
244
324
  this.cmdSkillDir = input.cmdSkillDir
245
325
  this.cmdOrchestration = input.cmdOrchestration === true
246
326
  this.onCommands = input.onCommands
327
+ this.discoverCommands = input.discoverCommands !== false
328
+ this.onModels = input.onModels
329
+ this.onUnsolicited = input.onUnsolicited
330
+ this.unsolicitedTiming = input.unsolicitedTiming
331
+ this.agents = input.agents ?? new AgentPool()
332
+ this.ownsAgents = input.agents === undefined
247
333
 
248
334
  for (const config of input.servers) {
249
335
  if (!config?.id || !config.command) continue
@@ -332,21 +418,76 @@ export class AcpServerManager {
332
418
  this.onCommands?.(state.config.id)
333
419
  }
334
420
 
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
421
+ /** Effort levels and default for a model, falling back to the server-wide list until it is learned. */
422
+ private effortsFor(state: AcpServerState, model: string | undefined) {
423
+ const info = state.models.find((candidate) => candidate.id === (model ?? state.defaultModel))
424
+ if (info?.efforts) return { values: info.efforts, defaultValue: info.defaultEffort, known: true }
425
+ return { values: state.efforts, defaultValue: undefined, known: false }
426
+ }
427
+
428
+ /** The effort a run asks for: the request, then the server config. Nothing means the agent's default. */
429
+ private requestedEffort(state: AcpServerState, requested?: string) {
430
+ const effort = requested ?? state.config.effort
338
431
  return effort && effort !== "default" ? effort : undefined
339
432
  }
340
433
 
341
- private sessionDirectories(config: AcpServerConfig) {
342
- return config.skills === false ? undefined : this.additionalDirectories
434
+ /**
435
+ * Record what the session reports for its current model's effort select.
436
+ * Efforts are learned per model on first selection rather than by switching
437
+ * through every model at discovery.
438
+ */
439
+ private learnEfforts(state: AcpServerState, model: string | undefined, client: AcpClient, sessionId: string) {
440
+ const id = model ?? state.defaultModel
441
+ const catalog = this.catalogs.get(state.config.id)?.catalog
442
+ const current = catalog?.models.find((candidate) => candidate.id === id)
443
+ if (!catalog || !current || current.efforts !== undefined) return
444
+ const observed = client.observedEffort(sessionId)
445
+ if (!observed) return
446
+ const efforts = effortLevels(observed.config?.values ?? [])
447
+ catalog.models = catalog.models.map((candidate) =>
448
+ candidate === current ? { ...current, efforts, ...(observed.defaultValue ? { defaultEffort: observed.defaultValue } : {}) } : candidate,
449
+ )
450
+ this.log("debug", `ACP model "${id}" offers effort levels: ${efforts.join(", ") || "none"}`)
451
+ for (const onModels of catalog.onModels) onModels()
452
+ }
453
+
454
+ private forgetCatalog(server: string) {
455
+ const subscription = this.catalogs.get(server)
456
+ subscription?.catalog.onModels.delete(subscription.onModels)
457
+ this.catalogs.delete(server)
343
458
  }
344
459
 
345
- private commandFor(config: AcpServerConfig) {
346
- return applyCmdMods(config.command, {
347
- orchestration: this.cmdOrchestration,
348
- skillDir: config.skills === false ? undefined : this.cmdSkillDir,
349
- })
460
+ private sessionDirectories(config: AcpServerConfig, client?: AcpClient) {
461
+ const directories = [...(config.skills === false ? [] : (this.additionalDirectories ?? []))]
462
+ const lease = this.leases.get(config.id)
463
+ if (client && lease?.client === client) directories.push(...lease.readRoots)
464
+ return directories.length ? directories : undefined
465
+ }
466
+
467
+ private launchFor(config: AcpServerConfig, skillDir: string | undefined): AgentLaunch {
468
+ const { command, args } = normalizeCommand(
469
+ applyCmdMods(config.command, { orchestration: this.cmdOrchestration, skillDir }),
470
+ )
471
+ const env: Record<string, string> = { ...config.env }
472
+ if (skillDir !== undefined && isCmdCommand(config.command)) {
473
+ // Read by agents/cmd/mods/opencode-skills.ts, which registers the directory
474
+ // because `cmd acp` does not apply the global `--skill` flag.
475
+ env.OPENCODE_ACP_PROVIDER_SKILL_DIR = skillDir
476
+ }
477
+ return {
478
+ command,
479
+ args,
480
+ env,
481
+ cwd:
482
+ config.cwd ??
483
+ (this.ownsAgents || (!isAbsolute(command) && /[\\/]/.test(command)) ? this.defaultCwd : homedir()),
484
+ scope: this.ownsAgents ? config.id : undefined,
485
+ autoApprove: config.autoApprove !== false,
486
+ requestTimeoutMs: this.requestTimeoutMs,
487
+ promptTimeoutMs: this.promptTimeoutMs,
488
+ allowPathsOutsideCwd: this.allowPathsOutsideCwd,
489
+ maxFileBytes: this.maxFileBytes,
490
+ }
350
491
  }
351
492
 
352
493
  /** Install or update the agent before it is spawned; memoized per script. */
@@ -355,15 +496,27 @@ export class AcpServerManager {
355
496
  return setup ? runSetup(setup, this.log) : Promise.resolve()
356
497
  }
357
498
 
499
+ /**
500
+ * Set a requested effort once the session's model is selected. Learns the
501
+ * model's levels first, and sends nothing to a model that has no effort
502
+ * select or does not offer the level.
503
+ */
358
504
  private async applyEffort(
359
505
  state: AcpServerState,
360
506
  client: AcpClient,
361
507
  sessionId: string,
508
+ model: string | undefined,
362
509
  effort: string | undefined,
363
510
  ) {
511
+ this.learnEfforts(state, model, client, sessionId)
364
512
  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(", ")})`)
513
+ const { values, known } = this.effortsFor(state, model)
514
+ if (known && !values.includes(effort) && effort !== "default") {
515
+ this.log(
516
+ "debug",
517
+ `ACP model "${model ?? state.defaultModel ?? "default"}" does not offer effort "${effort}"` +
518
+ (values.length ? ` (available: ${values.join(", ")})` : "; it has no effort levels"),
519
+ )
367
520
  return
368
521
  }
369
522
  await client.setEffort(sessionId, effort, state.effortConfigID)
@@ -380,53 +533,71 @@ export class AcpServerManager {
380
533
  const previous = pooled.selection
381
534
  if (previous && previous.model === selection.model && previous.effort === selection.effort) return
382
535
  pooled.selection = undefined
383
- const resetDefault =
384
- (!selection.model && previous?.model !== undefined) ||
385
- (!selection.effort && previous?.effort !== undefined)
386
- if (previous && !resetDefault) {
536
+ if (previous && (selection.model || previous.model === undefined)) {
387
537
  try {
388
538
  const modelChanged = previous.model !== selection.model
389
539
  if (modelChanged && selection.model) {
390
540
  await pooled.client.setModel(pooled.sessionId, selection.model, state.modelConfigID)
391
541
  }
392
- if (modelChanged || previous.effort !== selection.effort) {
393
- await this.applyEffort(state, pooled.client, pooled.sessionId, selection.effort)
542
+ // After a model switch the agent picks the new model's effort itself.
543
+ // Going back to the default on the same model needs that default.
544
+ let effort = selection.effort
545
+ let live = true
546
+ if (!effort && !modelChanged && previous.effort) {
547
+ this.learnEfforts(state, selection.model, pooled.client, pooled.sessionId)
548
+ const { values, defaultValue, known } = this.effortsFor(state, selection.model)
549
+ if (defaultValue) effort = defaultValue
550
+ else live = known && !values.length
551
+ }
552
+ if (live) {
553
+ await this.applyEffort(state, pooled.client, pooled.sessionId, selection.model, effort)
554
+ pooled.selection = selection
555
+ return
394
556
  }
395
- pooled.selection = selection
396
- return
397
557
  } catch (error) {
398
- if (!(error instanceof AcpError) || ![-32601, -32602].includes(error.code)) throw error
558
+ if (!isAcpError(error) || ![-32601, -32602].includes(error.code)) throw error
399
559
  this.log("debug", `ACP session refused a selection change; replaying in a fresh session: ${error.message}`)
400
560
  }
401
561
  }
402
562
 
403
563
  // Some agents cannot change a live selection or reset to the provider default.
404
564
  // 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.
565
+ // Issue a fresh MCP bridge lease for the replacement ACP session so it
566
+ // starts with its own lease before the old session releases its token.
407
567
  const lease = this.mcp
408
568
  ? await this.mcp.servers(pooled.key, state.config).catch((error) => {
409
569
  this.log("warn", `could not refresh MCP servers for ${state.config.id}: ${errorMessage(error)}`)
410
570
  return undefined
411
571
  })
412
572
  : undefined
573
+ const sessionIdRef = { id: "" }
574
+ const callbacks = this.sessionCallbacks(state, poolKey, pooled.sessionKey, sessionIdRef)
413
575
  const session = await pooled.client
414
576
  .newSession(pooled.cwd, {
415
577
  model: selection.model,
416
578
  mcpServers: lease?.servers ?? pooled.mcpServers,
417
579
  meta: state.config.meta,
418
- additionalDirectories: this.sessionDirectories(state.config),
580
+ additionalDirectories: this.sessionDirectories(state.config, pooled.client),
581
+ owner: this,
582
+ onCommands: (commands) => this.recordCommands(state, commands),
583
+ ...callbacks,
419
584
  })
420
585
  .catch((error) => {
421
586
  lease?.release()
422
587
  throw error
423
588
  })
589
+ sessionIdRef.id = session.sessionId
590
+ if (this.disposed) {
591
+ await pooled.client.closeSession(session.sessionId, this).catch(() => {})
592
+ lease?.release()
593
+ throw new Error("ACP server manager is stopped")
594
+ }
424
595
  try {
425
596
  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)
597
+ await this.applyEffort(state, pooled.client, session.sessionId, selection.model, selection.effort)
427
598
  } catch (error) {
428
599
  lease?.release()
429
- await pooled.client.closeSession(session.sessionId).catch(() => {})
600
+ await pooled.client.closeSession(session.sessionId, this).catch(() => {})
430
601
  throw error
431
602
  }
432
603
  // The pool may have been closed while the new session was being prepared
@@ -434,20 +605,21 @@ export class AcpServerManager {
434
605
  // fresh lease here keeps its bridge token from outliving a dead pool.
435
606
  if (pooled.broken) {
436
607
  lease?.release()
437
- await pooled.client.closeSession(session.sessionId).catch(() => {})
608
+ await pooled.client.closeSession(session.sessionId, this).catch(() => {})
438
609
  throw new Error(`ACP session for key ${pooled.key.slice(0, 24)} was closed while changing selection`)
439
610
  }
440
611
  const oldSession = pooled.sessionId
441
612
  pooled.sessionId = session.sessionId
442
613
  pooled.history = "fresh"
443
614
  pooled.selection = selection
615
+ pooled.backgroundTools.clear()
444
616
  if (lease) {
445
617
  pooled.mcpRelease?.()
446
618
  pooled.mcpServers = lease.servers
447
619
  pooled.mcpRelease = lease.release
448
620
  }
449
621
  await this.rememberSession(poolKey, session.sessionId)
450
- await pooled.client.closeSession(oldSession).catch(() => {})
622
+ await pooled.client.closeSession(oldSession, this).catch(() => {})
451
623
  }
452
624
 
453
625
  /** Discover enabled agents in parallel and report each result independently. */
@@ -514,6 +686,32 @@ export class AcpServerManager {
514
686
  return promise
515
687
  }
516
688
 
689
+ private async withDiscoverySession<T>(
690
+ state: AcpServerState,
691
+ client: AcpClient,
692
+ read: (session: Awaited<ReturnType<AcpClient["newSession"]>>) => T,
693
+ ) {
694
+ const config = state.config
695
+ const session = await client.newSession(config.cwd ?? this.defaultCwd, {
696
+ meta: config.meta,
697
+ additionalDirectories: this.sessionDirectories(config, client),
698
+ owner: this,
699
+ onCommands: this.discoverCommands ? (commands) => this.recordCommands(state, commands) : undefined,
700
+ })
701
+ try {
702
+ this.assertLive()
703
+ const result = read(session)
704
+ if (this.discoverCommands) {
705
+ // Commands are location-specific and may arrive just after session/new.
706
+ const commands = await client.waitForCommands(session.sessionId, COMMAND_SNAPSHOT_TIMEOUT_MS)
707
+ if (commands) this.recordCommands(state, commands)
708
+ }
709
+ return result
710
+ } finally {
711
+ await client.closeSession(session.sessionId, this).catch(() => {})
712
+ }
713
+ }
714
+
517
715
  private async doPrepare(state: AcpServerState) {
518
716
  const config = state.config
519
717
  this.assertLive()
@@ -521,92 +719,110 @@ export class AcpServerManager {
521
719
  // instant when discovery already ran it.
522
720
  await this.setupFor(state)
523
721
  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
722
 
533
723
  const previous = state.client
534
724
  if (previous) {
535
725
  await this.closePoolsFor(config.id)
536
- await previous.stop().catch(() => {})
726
+ this.leases.get(config.id)?.release()
727
+ this.leases.delete(config.id)
537
728
  }
729
+ this.assertLive()
538
730
 
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),
731
+ const skillDir = config.skills === false ? undefined : this.cmdSkillDir
732
+ const launch = this.launchFor(config, skillDir)
733
+ const subscriber: AgentSubscriber = {
734
+ onLog: (level, message) => this.log(level, `[${config.id}] ${message}`),
551
735
  onExit: (error) => {
552
736
  this.log("warn", `ACP agent "${config.id}" exited; pooled sessions were dropped: ${error.message}`)
553
737
  void this.closePoolsFor(config.id)
554
738
  },
555
- })
739
+ }
740
+ const dedicated = isCmdCommand(config.command) || config.share === false
741
+ const lease = dedicated
742
+ ? this.agents.dedicated({ launch: (dir) => this.launchFor(config, dir), skillDir }, subscriber)
743
+ : this.agents.acquire(launch, subscriber)
744
+ this.leases.set(config.id, lease)
745
+ const client = lease.client
556
746
  state.client = client
557
747
  state.retryable = true
558
748
 
559
749
  try {
560
- const session = await client.newSession(config.cwd ?? this.defaultCwd, {
561
- meta: config.meta,
562
- additionalDirectories: this.sessionDirectories(config),
563
- })
750
+ // The allowlist is a local view, not part of what the agent advertises.
751
+ const { command, args } = normalizeCommand(config.command)
752
+ const agent = inventoryKey({ ...config, command: [command, ...args], models: undefined })
753
+ const commandCwd = !isAbsolute(launch.command) && /[\\/]/.test(launch.command) ? launch.cwd : undefined
754
+ const key = JSON.stringify([agent, config.cwd ?? commandCwd])
755
+ const cached = this.agents.catalogs.get(key)
756
+ let discovery = cached
757
+ if (!discovery) {
758
+ discovery = this.withDiscoverySession(state, client, (session): AcpCatalog => {
759
+ const defaultModel = session.currentModel ?? (session.modelConfigID ? undefined : "default")
760
+ const models = session.models.length
761
+ ? session.models
762
+ : defaultModel ? [{ id: defaultModel, name: session.currentModel ?? "Agent default" }] : []
763
+ if (!models.length) throw new Error(`ACP server "${config.id}" advertised no models`)
764
+ const observed = client.observedEffort(session.sessionId)
765
+ return {
766
+ models: models.map((model) => observed && model.id === defaultModel
767
+ ? { ...model, efforts: effortLevels(observed.config?.values ?? []), defaultEffort: observed.defaultValue }
768
+ : model),
769
+ defaultModel,
770
+ modelConfigID: session.modelConfigID,
771
+ efforts: effortLevels(session.efforts ?? []),
772
+ effortConfigID: session.effort?.configId,
773
+ onModels: new Set(),
774
+ }
775
+ })
776
+ this.agents.catalogs.set(key, discovery)
777
+ void discovery.catch(() => {
778
+ if (this.agents.catalogs.get(key) === discovery) this.agents.catalogs.delete(key)
779
+ })
780
+ }
781
+ const catalog = await discovery
564
782
  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) {
783
+ const allow = config.models?.length ? new Set(config.models) : undefined
784
+ const visible = () => allow ? catalog.models.filter((model) => allow.has(model.id)) : catalog.models
785
+ const models = visible()
786
+ if (!catalog.modelConfigID && config.model && config.model !== catalog.defaultModel) {
570
787
  state.retryable = false
571
788
  throw new Error(`ACP server "${config.id}" does not expose an ACP model selector; use "default" or omit "model"`)
572
789
  }
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
- }
790
+ if (!models.length) {
791
+ state.retryable = false
792
+ throw new Error(`ACP server "${config.id}" advertised no model matching "models" (${config.models?.join(", ")})`)
582
793
  }
583
- if (config.model && models.length && !models.some((model) => model.id === config.model)) {
794
+ if (config.model && !models.some((model) => model.id === config.model)) {
584
795
  this.log(
585
796
  "warn",
586
797
  `ACP server "${config.id}" does not advertise the configured model "${config.model}"; it will be sent anyway`,
587
798
  )
588
799
  }
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
800
+ if (cached && this.discoverCommands) {
801
+ await this.withDiscoverySession(state, client, () => {}).catch((error) => {
802
+ this.log("debug", `could not discover ACP commands for "${config.id}": ${errorMessage(error)}`)
803
+ })
804
+ this.assertLive()
805
+ }
806
+ state.models = visible()
807
+ state.defaultModel = catalog.defaultModel
808
+ state.modelConfigID = catalog.modelConfigID
809
+ state.efforts = catalog.efforts
810
+ state.effortConfigID = catalog.effortConfigID
811
+ const onModels = () => {
812
+ state.models = visible()
813
+ this.onModels?.(config.id)
814
+ }
815
+ this.forgetCatalog(config.id)
816
+ catalog.onModels.add(onModels)
817
+ this.catalogs.set(config.id, { catalog, onModels })
595
818
  state.initialized = true
596
819
  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
- )
820
+ this.log("info", `ACP server "${config.id}" ready with ${models.length} model(s)`)
608
821
  } catch (error) {
609
- await client.stop().catch(() => {})
822
+ if (this.leases.get(config.id) === lease) {
823
+ lease.release()
824
+ this.leases.delete(config.id)
825
+ }
610
826
  if (state.client === client) state.client = undefined
611
827
  throw error
612
828
  }
@@ -628,6 +844,7 @@ export class AcpServerManager {
628
844
  effort?: string
629
845
  key?: string
630
846
  sessionKey?: string
847
+ continuation?: string
631
848
  signal?: AbortSignal
632
849
  onUpdate?: (update: SessionUpdate) => void
633
850
  }): Promise<AcpRunResult> {
@@ -663,7 +880,7 @@ export class AcpServerManager {
663
880
  }
664
881
  const model = state.modelConfigID ? requestedModel : undefined
665
882
  const mode = state.config.mode
666
- const effort = this.resolveEffort(state, input.effort)
883
+ const effort = this.requestedEffort(state, input.effort)
667
884
  const onPermission = this.permissionHandler(input.server, input.sessionKey)
668
885
 
669
886
  if (!input.key) {
@@ -671,23 +888,74 @@ export class AcpServerManager {
671
888
  const session = await client.newSession(cwd, {
672
889
  model,
673
890
  meta: state.config.meta,
674
- additionalDirectories: this.sessionDirectories(state.config),
891
+ additionalDirectories: this.sessionDirectories(state.config, client),
892
+ owner: this,
893
+ onCommands: (commands) => this.recordCommands(state, commands),
675
894
  })
895
+ if (this.disposed) {
896
+ await client.closeSession(session.sessionId, this).catch(() => {})
897
+ throw new Error("ACP server manager is stopped")
898
+ }
676
899
  try {
677
900
  if (mode) await client.setMode(session.sessionId, mode).catch(() => {})
678
- await this.applyEffort(state, client, session.sessionId, effort)
901
+ await this.applyEffort(state, client, session.sessionId, model, effort)
679
902
  return await client.prompt(session.sessionId, prompt, {
903
+ owner: this,
680
904
  onUpdate: input.onUpdate,
681
905
  signal: input.signal,
682
906
  requestPermission: onPermission,
683
907
  })
684
908
  } finally {
685
- await client.closeSession(session.sessionId)
909
+ await client.closeSession(session.sessionId, this)
686
910
  }
687
911
  }
688
912
 
689
913
  const poolKey = this.poolKey(input.server, input.key, cwd)
690
914
  const existing = this.pools.get(poolKey)
915
+ if (input.continuation) {
916
+ const turn = existing && !existing.broken ? existing.pendingContinuations.get(input.continuation) : undefined
917
+ if (!existing || existing.broken || !turn) {
918
+ this.log("debug", `ignoring expired ACP continuation ${input.continuation} for key ${input.key.slice(0, 24)}`)
919
+ return { stopReason: "end_turn", text: "" }
920
+ }
921
+ existing.pendingContinuations.delete(input.continuation)
922
+ existing.lastUsed = Date.now()
923
+ existing.pending += 1
924
+ const run = existing.queue.then(async () => {
925
+ if (existing.broken) throw new Error(`ACP session ${existing.sessionId} is no longer usable`)
926
+ if (input.signal?.aborted) {
927
+ turn.cancel()
928
+ return { stopReason: "cancelled", text: "" }
929
+ }
930
+ existing.active += 1
931
+ finishStarting()
932
+ try {
933
+ if (key && this.startCancels.delete(key)) {
934
+ existing.client.cancelTurn(existing.sessionId, this)
935
+ turn.cancel()
936
+ }
937
+ return await turn.attach(input.onUpdate, input.signal, () => {
938
+ existing.client.cancelTurn(existing.sessionId, this)
939
+ })
940
+ } finally {
941
+ existing.active = Math.max(0, existing.active - 1)
942
+ }
943
+ })
944
+ existing.queue = run.catch(() => {})
945
+ void run
946
+ .then(
947
+ () => {
948
+ existing.failures = 0
949
+ },
950
+ (error: unknown) => this.onTurnFailed(poolKey, existing, error),
951
+ )
952
+ .finally(() => {
953
+ existing.pending = Math.max(0, existing.pending - 1)
954
+ existing.lastUsed = Date.now()
955
+ })
956
+ return await run
957
+ }
958
+
691
959
  let negotiating = this.negotiating.get(poolKey)
692
960
  if (!existing && !negotiating) {
693
961
  const eviction = this.reserveCapacity()
@@ -696,6 +964,9 @@ export class AcpServerManager {
696
964
  if (eviction) await eviction
697
965
  this.assertLive()
698
966
  const sessionStartedAt = Date.now()
967
+ const resolvedSessionKey = input.sessionKey ?? input.key!
968
+ const sessionIdRef = { id: "" }
969
+ const callbacks = this.sessionCallbacks(state, poolKey, resolvedSessionKey, sessionIdRef)
699
970
  const lease = await this.mcp?.servers(input.key!, state.config)
700
971
  let session: { sessionId: string } | undefined
701
972
  let reused = false
@@ -713,7 +984,10 @@ export class AcpServerManager {
713
984
  cwd,
714
985
  mcpServers: lease?.servers,
715
986
  meta: state.config.meta,
716
- additionalDirectories: this.sessionDirectories(state.config),
987
+ additionalDirectories: this.sessionDirectories(state.config, client),
988
+ owner: this,
989
+ onCommands: (commands) => this.recordCommands(state, commands),
990
+ ...callbacks,
717
991
  })
718
992
  .catch(async (error) => {
719
993
  this.log(
@@ -723,8 +997,14 @@ export class AcpServerManager {
723
997
  await this.forgetSession(poolKey)
724
998
  return undefined
725
999
  })
1000
+ if (this.disposed) {
1001
+ if (restored) await client.closeSession(stored, this).catch(() => {})
1002
+ lease?.release()
1003
+ throw new Error("ACP server manager is stopped")
1004
+ }
726
1005
  if (restored) {
727
1006
  session = { sessionId: stored }
1007
+ sessionIdRef.id = stored
728
1008
  reused = true
729
1009
  await this.rememberSession(poolKey, stored)
730
1010
  this.log(
@@ -738,8 +1018,17 @@ export class AcpServerManager {
738
1018
  model,
739
1019
  mcpServers: lease?.servers,
740
1020
  meta: state.config.meta,
741
- additionalDirectories: this.sessionDirectories(state.config),
1021
+ additionalDirectories: this.sessionDirectories(state.config, client),
1022
+ owner: this,
1023
+ onCommands: (commands) => this.recordCommands(state, commands),
1024
+ ...callbacks,
742
1025
  })
1026
+ sessionIdRef.id = session.sessionId
1027
+ if (this.disposed) {
1028
+ await client.closeSession(session.sessionId, this).catch(() => {})
1029
+ lease?.release()
1030
+ throw new Error("ACP server manager is stopped")
1031
+ }
743
1032
  await this.rememberSession(poolKey, session.sessionId)
744
1033
  }
745
1034
  if (mode) await client.setMode(session.sessionId, mode).catch(() => {})
@@ -748,15 +1037,21 @@ export class AcpServerManager {
748
1037
  await client.setModel(session.sessionId, model, state.modelConfigID)
749
1038
  }
750
1039
  // Set effort after model: changing models can reset it.
751
- await this.applyEffort(state, client, session.sessionId, effort)
1040
+ await this.applyEffort(state, client, session.sessionId, model, effort)
752
1041
  } catch (error) {
753
1042
  lease?.release()
754
- if (session) await client.closeSession(session.sessionId).catch(() => {})
1043
+ if (session) await client.closeSession(session.sessionId, this).catch(() => {})
755
1044
  throw error
756
1045
  }
1046
+ if (this.disposed) {
1047
+ await client.closeSession(session.sessionId, this).catch(() => {})
1048
+ lease?.release()
1049
+ throw new Error("ACP server manager is stopped")
1050
+ }
757
1051
  const created: PooledSession = {
758
1052
  server: input.server,
759
1053
  key: input.key!,
1054
+ sessionKey: resolvedSessionKey,
760
1055
  sessionId: session.sessionId,
761
1056
  client,
762
1057
  selection: { model, effort },
@@ -770,6 +1065,8 @@ export class AcpServerManager {
770
1065
  failures: 0,
771
1066
  broken: false,
772
1067
  mcpRelease: lease?.release,
1068
+ backgroundTools: new Map(),
1069
+ pendingContinuations: new Map(),
773
1070
  }
774
1071
  this.pools.set(poolKey, created)
775
1072
  this.log(
@@ -800,6 +1097,9 @@ export class AcpServerManager {
800
1097
  const run = pooled.queue.then(async () => {
801
1098
  if (pooled.broken) throw new Error(`ACP session ${pooled.sessionId} is no longer usable`)
802
1099
  if (input.signal?.aborted) return { stopReason: "cancelled", text: "" }
1100
+ if (pooled.activeUnsolicited && !pooled.activeUnsolicited.attached) {
1101
+ pooled.activeUnsolicited.finish("end_turn")
1102
+ }
803
1103
  await this.select(state, pooled, { model, effort }, poolKey)
804
1104
  if (pooled.broken) throw new Error(`ACP session ${pooled.sessionId} is no longer usable`)
805
1105
  if (input.signal?.aborted) return { stopReason: "cancelled", text: "" }
@@ -810,19 +1110,28 @@ export class AcpServerManager {
810
1110
  pooled.active += 1
811
1111
  finishStarting()
812
1112
  pooled.history = "retained"
1113
+ const turnTools = new Map<string, TurnToolRecord>()
813
1114
  const turn = pooled.client
814
1115
  .prompt(pooled.sessionId, prompt, {
815
- onUpdate: input.onUpdate,
1116
+ owner: this,
1117
+ onUpdate: (update) => {
1118
+ const mapped = this.trackAndRemapUpdate(pooled, update, turnTools)
1119
+ input.onUpdate?.(mapped)
1120
+ },
816
1121
  signal: input.signal,
817
1122
  requestPermission: onPermission,
818
1123
  })
1124
+ .then((result) => {
1125
+ this.recordUnfinishedTools(pooled, turnTools, result.stopReason)
1126
+ return result
1127
+ })
819
1128
  .finally(() => {
820
1129
  pooled.active = Math.max(0, pooled.active - 1)
821
1130
  })
822
1131
  // `prompt` has already written the request, so the agent sees the cancel
823
1132
  // after the prompt it belongs to.
824
1133
  if (key && this.startCancels.delete(key)) {
825
- pooled.client.cancelTurn(pooled.sessionId)
1134
+ pooled.client.cancelTurn(pooled.sessionId, this)
826
1135
  this.log("debug", `cancelled ACP session ${pooled.sessionId} for a steer that arrived while it was starting`)
827
1136
  }
828
1137
  return turn
@@ -852,13 +1161,13 @@ export class AcpServerManager {
852
1161
  if (this.pools.get(poolKey) !== pooled) return
853
1162
  const message = errorMessage(error)
854
1163
  const unknown = isUnknownSession(error)
855
- if (unknown || !pooled.client.alive || !pooled.client.hasSession(pooled.sessionId)) {
1164
+ if (unknown || !pooled.client.alive || !pooled.client.hasSession(pooled.sessionId, this)) {
856
1165
  void this.dropPool(poolKey, pooled)
857
1166
  if (unknown) void this.forgetSession(poolKey)
858
1167
  return
859
1168
  }
860
1169
  pooled.failures += 1
861
- if (error instanceof AcpError && error.code === ACP_REQUEST_CANCELLED) {
1170
+ if (isAcpError(error) && error.code === ACP_REQUEST_CANCELLED) {
862
1171
  // A stopped turn is normal; the agent already ended it, so the session
863
1172
  // is intact and the next prompt picks up the same conversation.
864
1173
  pooled.failures = 0
@@ -875,7 +1184,7 @@ export class AcpServerManager {
875
1184
  }
876
1185
  // Ask the agent to end whatever it is still running so the queued or next
877
1186
  // prompt enters the same context at a clean boundary.
878
- pooled.client.cancelTurn(pooled.sessionId)
1187
+ pooled.client.cancelTurn(pooled.sessionId, this)
879
1188
  this.log("debug", `keeping ACP session ${pooled.sessionId} after a failed turn: ${message}`)
880
1189
  }
881
1190
 
@@ -883,8 +1192,199 @@ export class AcpServerManager {
883
1192
  private async dropPool(poolKey: string, pooled: PooledSession) {
884
1193
  pooled.broken = true
885
1194
  if (this.pools.get(poolKey) === pooled) this.pools.delete(poolKey)
1195
+ const turns = new Set(pooled.pendingContinuations.values())
1196
+ if (pooled.activeUnsolicited) turns.add(pooled.activeUnsolicited)
1197
+ pooled.pendingContinuations.clear()
1198
+ pooled.activeUnsolicited = undefined
1199
+ pooled.activeUnsolicitedTools = undefined
1200
+ pooled.backgroundTools.clear()
1201
+ const error = new Error(`ACP session ${pooled.sessionId} was closed`)
1202
+ for (const turn of turns) turn.fail(error)
886
1203
  pooled.mcpRelease?.()
887
- await pooled.client.closeSession(pooled.sessionId).catch(() => {})
1204
+ await pooled.client.closeSession(pooled.sessionId, this).catch(() => {})
1205
+ }
1206
+
1207
+ /** Whether an unattached or active continuation exists for this OpenCode session and token. */
1208
+ hasContinuation(sessionKey: string, token: string): boolean {
1209
+ return [...this.pools.values()].some(
1210
+ (pooled) => pooled.key === sessionKey && !pooled.broken && pooled.pendingContinuations.has(token),
1211
+ )
1212
+ }
1213
+
1214
+ /** Find an unattached continuation token matching a synthetic wake-up message's text. */
1215
+ findContinuationByText(sessionKey: string, promptText: string): string | undefined {
1216
+ for (const pooled of this.pools.values()) {
1217
+ if (pooled.key !== sessionKey || pooled.broken) continue
1218
+ for (const turn of pooled.pendingContinuations.values()) {
1219
+ if (!turn.attached && turn.text === promptText) return turn.token
1220
+ }
1221
+ }
1222
+ return undefined
1223
+ }
1224
+
1225
+ /** Cancel and discard a pending continuation whose OpenCode wake-up could not proceed. */
1226
+ dropContinuation(sessionKey: string, token: string): void {
1227
+ for (const pooled of this.pools.values()) {
1228
+ if (pooled.key !== sessionKey) continue
1229
+ const turn = pooled.pendingContinuations.get(token)
1230
+ if (!turn) continue
1231
+ pooled.pendingContinuations.delete(token)
1232
+ if (pooled.activeUnsolicited === turn) {
1233
+ pooled.activeUnsolicited = undefined
1234
+ pooled.activeUnsolicitedTools = undefined
1235
+ }
1236
+ turn.dispose()
1237
+ return
1238
+ }
1239
+ }
1240
+
1241
+ private sessionCallbacks(
1242
+ state: AcpServerState,
1243
+ poolKey: string,
1244
+ sessionKey: string,
1245
+ sessionIdRef: { id: string },
1246
+ ) {
1247
+ return {
1248
+ onUnsolicitedUpdate: (update: SessionUpdate) => {
1249
+ const pooled = this.pools.get(poolKey)
1250
+ if (!pooled || pooled.broken || pooled.sessionId !== sessionIdRef.id) return
1251
+ this.handleUnsolicitedUpdate(state, pooled, update)
1252
+ },
1253
+ requestPermission: this.permissionHandler(state.config.id, sessionKey),
1254
+ onPermissionChange: (delta: 1 | -1) => {
1255
+ const pooled = this.pools.get(poolKey)
1256
+ const active = pooled?.activeUnsolicited
1257
+ if (!active || pooled.sessionId !== sessionIdRef.id) return
1258
+ if (delta === 1) active.permissionStarted()
1259
+ else active.permissionEnded()
1260
+ },
1261
+ }
1262
+ }
1263
+
1264
+ private trackAndRemapUpdate(
1265
+ pooled: PooledSession,
1266
+ update: SessionUpdate,
1267
+ turnTools: Map<string, TurnToolRecord>,
1268
+ ): SessionUpdate {
1269
+ if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") return update
1270
+ const rawId = text(update.toolCallId)
1271
+ if (!rawId) return update
1272
+
1273
+ const status = text(update.status)
1274
+ const terminal = status === "completed" || status === "failed"
1275
+ const incomingRaw = record(update.rawInput)
1276
+ const hasIncomingRaw = incomingRaw !== undefined && Object.keys(incomingRaw).length > 0
1277
+ const name = text(update.name)
1278
+ const title = text(update.title)
1279
+ const kind = text(update.kind)
1280
+ const meta = record(update._meta)
1281
+ const command = commandOf(incomingRaw?.CommandLine ?? incomingRaw?.command)
1282
+
1283
+ const background = pooled.backgroundTools.get(rawId)
1284
+ if (background) {
1285
+ const mergedRaw = hasIncomingRaw ? incomingRaw : background.rawInput
1286
+ const remapped: SessionUpdate = {
1287
+ ...update,
1288
+ toolCallId: `${rawId}:result`,
1289
+ ...(!name && background.name ? { name: background.name } : {}),
1290
+ ...(!title && background.title ? { title: background.title } : {}),
1291
+ ...(!kind && background.kind ? { kind: background.kind } : {}),
1292
+ ...(!meta && background.meta ? { _meta: background.meta } : {}),
1293
+ ...(mergedRaw ? { rawInput: mergedRaw } : {}),
1294
+ }
1295
+ if (terminal) pooled.backgroundTools.delete(rawId)
1296
+ return remapped
1297
+ }
1298
+
1299
+ const prior = turnTools.get(rawId)
1300
+ turnTools.set(rawId, {
1301
+ name: name ?? prior?.name,
1302
+ title: title ?? prior?.title,
1303
+ kind: kind ?? prior?.kind,
1304
+ meta: meta ?? prior?.meta,
1305
+ command: command ?? prior?.command,
1306
+ rawInput: hasIncomingRaw ? incomingRaw : prior?.rawInput,
1307
+ terminal: terminal || Boolean(prior?.terminal),
1308
+ })
1309
+ return update
1310
+ }
1311
+
1312
+ private recordUnfinishedTools(
1313
+ pooled: PooledSession,
1314
+ turnTools: Map<string, TurnToolRecord>,
1315
+ stopReason: string,
1316
+ ) {
1317
+ if (stopReason === "cancelled") return
1318
+ for (const [id, info] of turnTools) {
1319
+ if (info.terminal) {
1320
+ pooled.backgroundTools.delete(id)
1321
+ continue
1322
+ }
1323
+ if (pooled.backgroundTools.has(id)) pooled.backgroundTools.delete(id)
1324
+ while (pooled.backgroundTools.size >= MAX_BACKGROUND_TOOLS) {
1325
+ const oldest = pooled.backgroundTools.keys().next().value
1326
+ if (oldest === undefined) break
1327
+ pooled.backgroundTools.delete(oldest)
1328
+ }
1329
+ pooled.backgroundTools.set(id, {
1330
+ name: info.name,
1331
+ title: info.title,
1332
+ command: info.command,
1333
+ rawInput: info.rawInput,
1334
+ kind: info.kind,
1335
+ meta: info.meta,
1336
+ })
1337
+ }
1338
+ }
1339
+
1340
+ private handleUnsolicitedUpdate(state: AcpServerState, pooled: PooledSession, update: SessionUpdate) {
1341
+ if (this.disposed || pooled.broken) return
1342
+
1343
+ if (pooled.activeUnsolicited && pooled.activeUnsolicitedTools) {
1344
+ pooled.lastUsed = Date.now()
1345
+ const mapped = this.trackAndRemapUpdate(pooled, update, pooled.activeUnsolicitedTools)
1346
+ pooled.activeUnsolicited.push(mapped)
1347
+ return
1348
+ }
1349
+
1350
+ if (!isUnsolicitedActivity(update)) return
1351
+
1352
+ const rawId = text(update.toolCallId)
1353
+ const background = rawId ? pooled.backgroundTools.get(rawId) : undefined
1354
+ const { description, text: summaryText } = unsolicitedSummary(update, background, agentName(state.config))
1355
+ const turnTools = new Map<string, TurnToolRecord>()
1356
+ const turn = new UnsolicitedTurn({
1357
+ description,
1358
+ text: summaryText,
1359
+ timing: { maxTurnMs: this.promptTimeoutMs, ...this.unsolicitedTiming },
1360
+ onSettled: (result) => {
1361
+ if (pooled.activeUnsolicited === turn) {
1362
+ pooled.activeUnsolicited = undefined
1363
+ pooled.activeUnsolicitedTools = undefined
1364
+ }
1365
+ this.recordUnfinishedTools(pooled, turnTools, result.stopReason)
1366
+ pooled.lastUsed = Date.now()
1367
+ },
1368
+ onExpire: () => {
1369
+ if (pooled.pendingContinuations.get(turn.token) === turn) {
1370
+ pooled.pendingContinuations.delete(turn.token)
1371
+ }
1372
+ },
1373
+ })
1374
+
1375
+ pooled.activeUnsolicited = turn
1376
+ pooled.activeUnsolicitedTools = turnTools
1377
+ pooled.pendingContinuations.set(turn.token, turn)
1378
+ pooled.lastUsed = Date.now()
1379
+
1380
+ turn.push(this.trackAndRemapUpdate(pooled, update, turnTools))
1381
+ this.onUnsolicited?.({
1382
+ server: state.config.id,
1383
+ sessionKey: pooled.key,
1384
+ token: turn.token,
1385
+ description: turn.description,
1386
+ text: turn.text,
1387
+ })
888
1388
  }
889
1389
 
890
1390
  /**
@@ -907,7 +1407,8 @@ export class AcpServerManager {
907
1407
  return
908
1408
  }
909
1409
 
910
- pooled.client.cancelTurn(pooled.sessionId)
1410
+ pooled.client.cancelTurn(pooled.sessionId, this)
1411
+ if (pooled.activeUnsolicited?.attached) pooled.activeUnsolicited.cancel()
911
1412
  this.log("debug", `interrupted ACP session ${pooled.sessionId} so the queued message can be delivered`)
912
1413
  }
913
1414
 
@@ -930,6 +1431,7 @@ export class AcpServerManager {
930
1431
  const run = pooled.queue.then(() => {
931
1432
  if (pooled.broken) throw new Error(`ACP session ${pooled.sessionId} is no longer usable`)
932
1433
  return pooled.client.prompt(pooled.sessionId, "/compact", {
1434
+ owner: this,
933
1435
  onUpdate: (update) => {
934
1436
  // Claude Code reports a compaction as a tool call with its context size before and after.
935
1437
  const output = update.rawOutput as { preTokens?: unknown; postTokens?: unknown } | undefined
@@ -962,7 +1464,14 @@ export class AcpServerManager {
962
1464
  let oldest: [string, PooledSession] | undefined
963
1465
  for (const entry of this.pools) {
964
1466
  const [key, pooled] = entry
965
- if (pooled.pending > 0 || this.negotiating.has(key)) continue
1467
+ if (
1468
+ pooled.pending > 0 ||
1469
+ this.negotiating.has(key) ||
1470
+ pooled.activeUnsolicited !== undefined ||
1471
+ pooled.pendingContinuations.size > 0
1472
+ ) {
1473
+ continue
1474
+ }
966
1475
  if (!oldest || pooled.lastUsed < oldest[1].lastUsed) oldest = entry
967
1476
  }
968
1477
  if (!oldest) throw new Error(`ACP session pool at capacity (${this.maxSessions}); retry after a turn finishes`)
@@ -973,7 +1482,15 @@ export class AcpServerManager {
973
1482
  private sweepIdleSessions() {
974
1483
  const cutoff = Date.now() - this.sessionIdleMs
975
1484
  for (const [key, pooled] of this.pools) {
976
- if (pooled.pending > 0 || this.negotiating.has(key) || pooled.lastUsed > cutoff) continue
1485
+ if (
1486
+ pooled.pending > 0 ||
1487
+ this.negotiating.has(key) ||
1488
+ pooled.lastUsed > cutoff ||
1489
+ pooled.activeUnsolicited !== undefined ||
1490
+ pooled.pendingContinuations.size > 0
1491
+ ) {
1492
+ continue
1493
+ }
977
1494
  void this.dropPool(key, pooled)
978
1495
  this.log("debug", `closed idle ACP session ${pooled.sessionId} after ${this.sessionIdleMs}ms`)
979
1496
  }
@@ -995,21 +1512,42 @@ export class AcpServerManager {
995
1512
  this.sweeper = undefined
996
1513
  this.preparing.clear()
997
1514
  this.negotiating.clear()
1515
+ for (const server of this.catalogs.keys()) this.forgetCatalog(server)
998
1516
  const pools = [...this.pools.values()]
999
1517
  this.pools.clear()
1000
- // Best effort: the agents are killed below, so do not wait on a close
1001
- // handshake that could hang shutdown.
1518
+ // Best effort: the agent may be shared with another directory, so do not
1519
+ // wait on a close handshake that could hang shutdown. Closing drops the
1520
+ // session from the client, so its owner loop below can no longer see it:
1521
+ // end the turn here, or a shared agent would keep running one nobody reads.
1002
1522
  for (const pooled of pools) {
1003
1523
  pooled.broken = true
1524
+ const turns = new Set(pooled.pendingContinuations.values())
1525
+ if (pooled.activeUnsolicited) turns.add(pooled.activeUnsolicited)
1526
+ pooled.pendingContinuations.clear()
1527
+ pooled.activeUnsolicited = undefined
1528
+ pooled.activeUnsolicitedTools = undefined
1529
+ pooled.backgroundTools.clear()
1530
+ for (const turn of turns) turn.dispose()
1004
1531
  pooled.mcpRelease?.()
1005
- void pooled.client.closeSession(pooled.sessionId).catch(() => {})
1532
+ pooled.client.cancelTurn(pooled.sessionId, this)
1533
+ void pooled.client.closeSession(pooled.sessionId, this).catch(() => {})
1534
+ }
1535
+ // Only this manager's sessions close; another directory's stay on the client.
1536
+ for (const lease of this.leases.values()) {
1537
+ for (const sessionId of lease.client.sessionsOwnedBy(this)) {
1538
+ lease.client.cancelTurn(sessionId, this)
1539
+ void lease.client.closeSession(sessionId, this).catch(() => {})
1540
+ }
1006
1541
  }
1007
- await Promise.allSettled([...this.servers.values()].map((state) => state.client?.stop()))
1542
+ for (const lease of this.leases.values()) lease.release()
1543
+ this.leases.clear()
1544
+ for (const state of this.servers.values()) state.client = undefined
1545
+ if (this.ownsAgents) await this.agents.stop()
1008
1546
  }
1009
1547
  }
1010
1548
 
1011
1549
  function isUnknownSession(error: unknown) {
1012
- if (!(error instanceof AcpError)) return false
1550
+ if (!isAcpError(error)) return false
1013
1551
  if (error.code === ACP_UNKNOWN_SESSION) return true
1014
1552
  return /unknown (acp )?session|session .*not found|session .*does not exist/i.test(error.message)
1015
1553
  }