opencode-acp-provider 1.1.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.
@@ -12,8 +12,17 @@ import {
12
12
  import { AgentPool, type AgentLaunch, type AgentLease, type AgentSubscriber } from "./agent-pool.ts"
13
13
  import { applyCmdMods } from "./agents/cmd/index.ts"
14
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"
15
17
  import { runSetup } from "./setup.ts"
16
- 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"
17
26
 
18
27
  export interface AcpServerConfig {
19
28
  /** Stable id used for the OpenCode provider and tool arguments. */
@@ -66,6 +75,15 @@ export interface AcpModelInfo {
66
75
  id: string
67
76
  name: string
68
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
69
87
  }
70
88
 
71
89
  export interface AcpServerState {
@@ -77,7 +95,6 @@ export interface AcpServerState {
77
95
  /** Reasoning effort levels advertised by the agent, excluding the implicit default. */
78
96
  efforts: string[]
79
97
  effortConfigID?: string
80
- defaultEffort?: string
81
98
  error?: string
82
99
  /** False when retrying cannot help, e.g. a `models` allowlist that matches nothing. */
83
100
  retryable?: boolean
@@ -146,6 +163,7 @@ interface AcpSelection {
146
163
  interface PooledSession {
147
164
  server: string
148
165
  key: string
166
+ sessionKey: string
149
167
  sessionId: string
150
168
  client: AcpClient
151
169
  /** Undefined after a refused/uncertain config write; never assume it applied. */
@@ -162,6 +180,30 @@ interface PooledSession {
162
180
  failures: number
163
181
  broken: boolean
164
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
165
207
  }
166
208
 
167
209
  interface AcpRunResult {
@@ -188,6 +230,7 @@ const MAX_TURN_FAILURES = 3
188
230
  /** How long to wait for the command list an agent sends after `session/new`. */
189
231
  const COMMAND_SNAPSHOT_TIMEOUT_MS = 2_000
190
232
  const SWEEP_INTERVAL_MS = 60_000
233
+ const MAX_BACKGROUND_TOOLS = 64
191
234
 
192
235
  export class AcpServerManager {
193
236
  readonly servers = new Map<string, AcpServerState>()
@@ -215,6 +258,11 @@ export class AcpServerManager {
215
258
  private cmdSkillDir?: string
216
259
  private cmdOrchestration: boolean
217
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 }>()
218
266
  /** Pool that owns agent processes; shared with other OpenCode directories when passed in. */
219
267
  private agents: AgentPool
220
268
  private ownsAgents: boolean
@@ -245,6 +293,14 @@ export class AcpServerManager {
245
293
  cmdOrchestration?: boolean
246
294
  /** Called when a server's advertised command list changes. */
247
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
248
304
  /**
249
305
  * Pool that owns agent processes. Pass `sharedAgentPool()` to share them
250
306
  * across OpenCode directories; defaults to a private pool.
@@ -268,6 +324,10 @@ export class AcpServerManager {
268
324
  this.cmdSkillDir = input.cmdSkillDir
269
325
  this.cmdOrchestration = input.cmdOrchestration === true
270
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
271
331
  this.agents = input.agents ?? new AgentPool()
272
332
  this.ownsAgents = input.agents === undefined
273
333
 
@@ -358,12 +418,45 @@ export class AcpServerManager {
358
418
  this.onCommands?.(state.config.id)
359
419
  }
360
420
 
361
- /** Effort to apply for a run: explicit request, then server config, then agent default. */
362
- private resolveEffort(state: AcpServerState, requested?: string) {
363
- const effort = requested ?? state.config.effort ?? state.defaultEffort
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
364
431
  return effort && effort !== "default" ? effort : undefined
365
432
  }
366
433
 
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)
458
+ }
459
+
367
460
  private sessionDirectories(config: AcpServerConfig, client?: AcpClient) {
368
461
  const directories = [...(config.skills === false ? [] : (this.additionalDirectories ?? []))]
369
462
  const lease = this.leases.get(config.id)
@@ -403,15 +496,27 @@ export class AcpServerManager {
403
496
  return setup ? runSetup(setup, this.log) : Promise.resolve()
404
497
  }
405
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
+ */
406
504
  private async applyEffort(
407
505
  state: AcpServerState,
408
506
  client: AcpClient,
409
507
  sessionId: string,
508
+ model: string | undefined,
410
509
  effort: string | undefined,
411
510
  ) {
511
+ this.learnEfforts(state, model, client, sessionId)
412
512
  if (!effort) return
413
- if (state.efforts.length && !state.efforts.includes(effort)) {
414
- this.log("warn", `ACP server "${state.config.id}" does not support effort "${effort}" (available: ${state.efforts.join(", ")})`)
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
+ )
415
520
  return
416
521
  }
417
522
  await client.setEffort(sessionId, effort, state.effortConfigID)
@@ -428,20 +533,27 @@ export class AcpServerManager {
428
533
  const previous = pooled.selection
429
534
  if (previous && previous.model === selection.model && previous.effort === selection.effort) return
430
535
  pooled.selection = undefined
431
- const resetDefault =
432
- (!selection.model && previous?.model !== undefined) ||
433
- (!selection.effort && previous?.effort !== undefined)
434
- if (previous && !resetDefault) {
536
+ if (previous && (selection.model || previous.model === undefined)) {
435
537
  try {
436
538
  const modelChanged = previous.model !== selection.model
437
539
  if (modelChanged && selection.model) {
438
540
  await pooled.client.setModel(pooled.sessionId, selection.model, state.modelConfigID)
439
541
  }
440
- if (modelChanged || previous.effort !== selection.effort) {
441
- 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
442
556
  }
443
- pooled.selection = selection
444
- return
445
557
  } catch (error) {
446
558
  if (!isAcpError(error) || ![-32601, -32602].includes(error.code)) throw error
447
559
  this.log("debug", `ACP session refused a selection change; replaying in a fresh session: ${error.message}`)
@@ -450,14 +562,16 @@ export class AcpServerManager {
450
562
 
451
563
  // Some agents cannot change a live selection or reset to the provider default.
452
564
  // Keep the conversation queue, but replay history into a new ACP session.
453
- // Resolve the MCP servers again: a remote server's OAuth grant may have been
454
- // refreshed since this session opened, and ACP cannot update it in place.
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.
455
567
  const lease = this.mcp
456
568
  ? await this.mcp.servers(pooled.key, state.config).catch((error) => {
457
569
  this.log("warn", `could not refresh MCP servers for ${state.config.id}: ${errorMessage(error)}`)
458
570
  return undefined
459
571
  })
460
572
  : undefined
573
+ const sessionIdRef = { id: "" }
574
+ const callbacks = this.sessionCallbacks(state, poolKey, pooled.sessionKey, sessionIdRef)
461
575
  const session = await pooled.client
462
576
  .newSession(pooled.cwd, {
463
577
  model: selection.model,
@@ -466,11 +580,13 @@ export class AcpServerManager {
466
580
  additionalDirectories: this.sessionDirectories(state.config, pooled.client),
467
581
  owner: this,
468
582
  onCommands: (commands) => this.recordCommands(state, commands),
583
+ ...callbacks,
469
584
  })
470
585
  .catch((error) => {
471
586
  lease?.release()
472
587
  throw error
473
588
  })
589
+ sessionIdRef.id = session.sessionId
474
590
  if (this.disposed) {
475
591
  await pooled.client.closeSession(session.sessionId, this).catch(() => {})
476
592
  lease?.release()
@@ -478,7 +594,7 @@ export class AcpServerManager {
478
594
  }
479
595
  try {
480
596
  if (state.config.mode) await pooled.client.setMode(session.sessionId, state.config.mode).catch(() => {})
481
- await this.applyEffort(state, pooled.client, session.sessionId, selection.effort)
597
+ await this.applyEffort(state, pooled.client, session.sessionId, selection.model, selection.effort)
482
598
  } catch (error) {
483
599
  lease?.release()
484
600
  await pooled.client.closeSession(session.sessionId, this).catch(() => {})
@@ -496,6 +612,7 @@ export class AcpServerManager {
496
612
  pooled.sessionId = session.sessionId
497
613
  pooled.history = "fresh"
498
614
  pooled.selection = selection
615
+ pooled.backgroundTools.clear()
499
616
  if (lease) {
500
617
  pooled.mcpRelease?.()
501
618
  pooled.mcpServers = lease.servers
@@ -569,6 +686,32 @@ export class AcpServerManager {
569
686
  return promise
570
687
  }
571
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
+
572
715
  private async doPrepare(state: AcpServerState) {
573
716
  const config = state.config
574
717
  this.assertLive()
@@ -586,6 +729,7 @@ export class AcpServerManager {
586
729
  this.assertLive()
587
730
 
588
731
  const skillDir = config.skills === false ? undefined : this.cmdSkillDir
732
+ const launch = this.launchFor(config, skillDir)
589
733
  const subscriber: AgentSubscriber = {
590
734
  onLog: (level, message) => this.log(level, `[${config.id}] ${message}`),
591
735
  onExit: (error) => {
@@ -596,66 +740,84 @@ export class AcpServerManager {
596
740
  const dedicated = isCmdCommand(config.command) || config.share === false
597
741
  const lease = dedicated
598
742
  ? this.agents.dedicated({ launch: (dir) => this.launchFor(config, dir), skillDir }, subscriber)
599
- : this.agents.acquire(this.launchFor(config, skillDir), subscriber)
743
+ : this.agents.acquire(launch, subscriber)
600
744
  this.leases.set(config.id, lease)
601
745
  const client = lease.client
602
746
  state.client = client
603
747
  state.retryable = true
604
748
 
605
749
  try {
606
- const session = await client.newSession(config.cwd ?? this.defaultCwd, {
607
- meta: config.meta,
608
- additionalDirectories: this.sessionDirectories(config, client),
609
- owner: this,
610
- onCommands: (commands) => this.recordCommands(state, commands),
611
- })
612
- try {
613
- this.assertLive()
614
- const defaultModel = session.currentModel ?? (session.modelConfigID ? undefined : "default")
615
- let models = session.models.length
616
- ? session.models
617
- : defaultModel ? [{ id: defaultModel, name: session.currentModel ?? "Agent default" }] : []
618
- if (!session.modelConfigID && config.model && config.model !== defaultModel) {
619
- state.retryable = false
620
- throw new Error(`ACP server "${config.id}" does not expose an ACP model selector; use "default" or omit "model"`)
621
- }
622
- if (config.models?.length) {
623
- const allow = new Set(config.models)
624
- models = models.filter((model) => allow.has(model.id))
625
- if (!models.length) {
626
- state.retryable = false
627
- throw new Error(
628
- `ACP server "${config.id}" advertised no model matching "models" (${config.models.join(", ")})`,
629
- )
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(),
630
774
  }
631
- }
632
- if (config.model && models.length && !models.some((model) => model.id === config.model)) {
633
- this.log(
634
- "warn",
635
- `ACP server "${config.id}" does not advertise the configured model "${config.model}"; it will be sent anyway`,
636
- )
637
- }
638
- state.models = models
639
- state.defaultModel = defaultModel
640
- state.modelConfigID = session.modelConfigID
641
- state.efforts = (session.efforts ?? []).filter((value) => value !== "default")
642
- state.effortConfigID = session.effort?.configId
643
- state.defaultEffort = session.effort?.currentValue
644
- state.initialized = true
645
- state.error = undefined
646
- // The command list arrives as a notification just after `session/new`, so
647
- // wait for it before this discovery session is closed: once it is gone,
648
- // the only way to learn the list is to open another session.
649
- const commands = await client.waitForCommands(session.sessionId, COMMAND_SNAPSHOT_TIMEOUT_MS)
650
- if (commands) this.recordCommands(state, commands)
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
782
+ this.assertLive()
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) {
787
+ state.retryable = false
788
+ throw new Error(`ACP server "${config.id}" does not expose an ACP model selector; use "default" or omit "model"`)
789
+ }
790
+ if (!models.length) {
791
+ state.retryable = false
792
+ throw new Error(`ACP server "${config.id}" advertised no model matching "models" (${config.models?.join(", ")})`)
793
+ }
794
+ if (config.model && !models.some((model) => model.id === config.model)) {
651
795
  this.log(
652
- "info",
653
- `ACP server "${config.id}" ready with ${models.length} model(s)` +
654
- (state.efforts.length ? ` and effort levels: ${state.efforts.join(", ")}` : ""),
796
+ "warn",
797
+ `ACP server "${config.id}" does not advertise the configured model "${config.model}"; it will be sent anyway`,
655
798
  )
656
- } finally {
657
- await client.closeSession(session.sessionId, this).catch(() => {})
658
799
  }
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 })
818
+ state.initialized = true
819
+ state.error = undefined
820
+ this.log("info", `ACP server "${config.id}" ready with ${models.length} model(s)`)
659
821
  } catch (error) {
660
822
  if (this.leases.get(config.id) === lease) {
661
823
  lease.release()
@@ -682,6 +844,7 @@ export class AcpServerManager {
682
844
  effort?: string
683
845
  key?: string
684
846
  sessionKey?: string
847
+ continuation?: string
685
848
  signal?: AbortSignal
686
849
  onUpdate?: (update: SessionUpdate) => void
687
850
  }): Promise<AcpRunResult> {
@@ -717,7 +880,7 @@ export class AcpServerManager {
717
880
  }
718
881
  const model = state.modelConfigID ? requestedModel : undefined
719
882
  const mode = state.config.mode
720
- const effort = this.resolveEffort(state, input.effort)
883
+ const effort = this.requestedEffort(state, input.effort)
721
884
  const onPermission = this.permissionHandler(input.server, input.sessionKey)
722
885
 
723
886
  if (!input.key) {
@@ -735,7 +898,7 @@ export class AcpServerManager {
735
898
  }
736
899
  try {
737
900
  if (mode) await client.setMode(session.sessionId, mode).catch(() => {})
738
- await this.applyEffort(state, client, session.sessionId, effort)
901
+ await this.applyEffort(state, client, session.sessionId, model, effort)
739
902
  return await client.prompt(session.sessionId, prompt, {
740
903
  owner: this,
741
904
  onUpdate: input.onUpdate,
@@ -749,6 +912,50 @@ export class AcpServerManager {
749
912
 
750
913
  const poolKey = this.poolKey(input.server, input.key, cwd)
751
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
+
752
959
  let negotiating = this.negotiating.get(poolKey)
753
960
  if (!existing && !negotiating) {
754
961
  const eviction = this.reserveCapacity()
@@ -757,6 +964,9 @@ export class AcpServerManager {
757
964
  if (eviction) await eviction
758
965
  this.assertLive()
759
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)
760
970
  const lease = await this.mcp?.servers(input.key!, state.config)
761
971
  let session: { sessionId: string } | undefined
762
972
  let reused = false
@@ -777,6 +987,7 @@ export class AcpServerManager {
777
987
  additionalDirectories: this.sessionDirectories(state.config, client),
778
988
  owner: this,
779
989
  onCommands: (commands) => this.recordCommands(state, commands),
990
+ ...callbacks,
780
991
  })
781
992
  .catch(async (error) => {
782
993
  this.log(
@@ -793,6 +1004,7 @@ export class AcpServerManager {
793
1004
  }
794
1005
  if (restored) {
795
1006
  session = { sessionId: stored }
1007
+ sessionIdRef.id = stored
796
1008
  reused = true
797
1009
  await this.rememberSession(poolKey, stored)
798
1010
  this.log(
@@ -809,7 +1021,9 @@ export class AcpServerManager {
809
1021
  additionalDirectories: this.sessionDirectories(state.config, client),
810
1022
  owner: this,
811
1023
  onCommands: (commands) => this.recordCommands(state, commands),
1024
+ ...callbacks,
812
1025
  })
1026
+ sessionIdRef.id = session.sessionId
813
1027
  if (this.disposed) {
814
1028
  await client.closeSession(session.sessionId, this).catch(() => {})
815
1029
  lease?.release()
@@ -823,7 +1037,7 @@ export class AcpServerManager {
823
1037
  await client.setModel(session.sessionId, model, state.modelConfigID)
824
1038
  }
825
1039
  // Set effort after model: changing models can reset it.
826
- await this.applyEffort(state, client, session.sessionId, effort)
1040
+ await this.applyEffort(state, client, session.sessionId, model, effort)
827
1041
  } catch (error) {
828
1042
  lease?.release()
829
1043
  if (session) await client.closeSession(session.sessionId, this).catch(() => {})
@@ -837,6 +1051,7 @@ export class AcpServerManager {
837
1051
  const created: PooledSession = {
838
1052
  server: input.server,
839
1053
  key: input.key!,
1054
+ sessionKey: resolvedSessionKey,
840
1055
  sessionId: session.sessionId,
841
1056
  client,
842
1057
  selection: { model, effort },
@@ -850,6 +1065,8 @@ export class AcpServerManager {
850
1065
  failures: 0,
851
1066
  broken: false,
852
1067
  mcpRelease: lease?.release,
1068
+ backgroundTools: new Map(),
1069
+ pendingContinuations: new Map(),
853
1070
  }
854
1071
  this.pools.set(poolKey, created)
855
1072
  this.log(
@@ -880,6 +1097,9 @@ export class AcpServerManager {
880
1097
  const run = pooled.queue.then(async () => {
881
1098
  if (pooled.broken) throw new Error(`ACP session ${pooled.sessionId} is no longer usable`)
882
1099
  if (input.signal?.aborted) return { stopReason: "cancelled", text: "" }
1100
+ if (pooled.activeUnsolicited && !pooled.activeUnsolicited.attached) {
1101
+ pooled.activeUnsolicited.finish("end_turn")
1102
+ }
883
1103
  await this.select(state, pooled, { model, effort }, poolKey)
884
1104
  if (pooled.broken) throw new Error(`ACP session ${pooled.sessionId} is no longer usable`)
885
1105
  if (input.signal?.aborted) return { stopReason: "cancelled", text: "" }
@@ -890,13 +1110,21 @@ export class AcpServerManager {
890
1110
  pooled.active += 1
891
1111
  finishStarting()
892
1112
  pooled.history = "retained"
1113
+ const turnTools = new Map<string, TurnToolRecord>()
893
1114
  const turn = pooled.client
894
1115
  .prompt(pooled.sessionId, prompt, {
895
1116
  owner: this,
896
- onUpdate: input.onUpdate,
1117
+ onUpdate: (update) => {
1118
+ const mapped = this.trackAndRemapUpdate(pooled, update, turnTools)
1119
+ input.onUpdate?.(mapped)
1120
+ },
897
1121
  signal: input.signal,
898
1122
  requestPermission: onPermission,
899
1123
  })
1124
+ .then((result) => {
1125
+ this.recordUnfinishedTools(pooled, turnTools, result.stopReason)
1126
+ return result
1127
+ })
900
1128
  .finally(() => {
901
1129
  pooled.active = Math.max(0, pooled.active - 1)
902
1130
  })
@@ -964,10 +1192,201 @@ export class AcpServerManager {
964
1192
  private async dropPool(poolKey: string, pooled: PooledSession) {
965
1193
  pooled.broken = true
966
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)
967
1203
  pooled.mcpRelease?.()
968
1204
  await pooled.client.closeSession(pooled.sessionId, this).catch(() => {})
969
1205
  }
970
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
+ })
1388
+ }
1389
+
971
1390
  /**
972
1391
  * Whether an ACP turn is streaming for this OpenCode session right now.
973
1392
  * A turn still negotiating its ACP session counts too: a message sent in that
@@ -989,6 +1408,7 @@ export class AcpServerManager {
989
1408
  }
990
1409
 
991
1410
  pooled.client.cancelTurn(pooled.sessionId, this)
1411
+ if (pooled.activeUnsolicited?.attached) pooled.activeUnsolicited.cancel()
992
1412
  this.log("debug", `interrupted ACP session ${pooled.sessionId} so the queued message can be delivered`)
993
1413
  }
994
1414
 
@@ -1044,7 +1464,14 @@ export class AcpServerManager {
1044
1464
  let oldest: [string, PooledSession] | undefined
1045
1465
  for (const entry of this.pools) {
1046
1466
  const [key, pooled] = entry
1047
- 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
+ }
1048
1475
  if (!oldest || pooled.lastUsed < oldest[1].lastUsed) oldest = entry
1049
1476
  }
1050
1477
  if (!oldest) throw new Error(`ACP session pool at capacity (${this.maxSessions}); retry after a turn finishes`)
@@ -1055,7 +1482,15 @@ export class AcpServerManager {
1055
1482
  private sweepIdleSessions() {
1056
1483
  const cutoff = Date.now() - this.sessionIdleMs
1057
1484
  for (const [key, pooled] of this.pools) {
1058
- 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
+ }
1059
1494
  void this.dropPool(key, pooled)
1060
1495
  this.log("debug", `closed idle ACP session ${pooled.sessionId} after ${this.sessionIdleMs}ms`)
1061
1496
  }
@@ -1077,6 +1512,7 @@ export class AcpServerManager {
1077
1512
  this.sweeper = undefined
1078
1513
  this.preparing.clear()
1079
1514
  this.negotiating.clear()
1515
+ for (const server of this.catalogs.keys()) this.forgetCatalog(server)
1080
1516
  const pools = [...this.pools.values()]
1081
1517
  this.pools.clear()
1082
1518
  // Best effort: the agent may be shared with another directory, so do not
@@ -1085,6 +1521,13 @@ export class AcpServerManager {
1085
1521
  // end the turn here, or a shared agent would keep running one nobody reads.
1086
1522
  for (const pooled of pools) {
1087
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()
1088
1531
  pooled.mcpRelease?.()
1089
1532
  pooled.client.cancelTurn(pooled.sessionId, this)
1090
1533
  void pooled.client.closeSession(pooled.sessionId, this).catch(() => {})