opencode-acp-provider 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,15 @@
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"
12
15
  import { runSetup } from "./setup.ts"
@@ -26,10 +29,21 @@ export interface AcpServerConfig {
26
29
  * failure is logged and the agent still starts.
27
30
  */
28
31
  setup?: string
29
- /** Working directory for the agent process. Defaults to the OpenCode location. */
32
+ /**
33
+ * Working directory for the agent process and its sessions. When unset,
34
+ * sessions use the OpenCode location, and the process starts in the home
35
+ * directory if it is shared across directories (else in the OpenCode location).
36
+ */
30
37
  cwd?: string
31
38
  /** Extra environment variables for the agent process. */
32
39
  env?: Record<string, string>
40
+ /**
41
+ * Share one agent process across OpenCode directories. Defaults to true,
42
+ * except for Command Code (`cmd`), which binds a process to one directory and
43
+ * always gets its own process with a warm spare. Set false for other agents
44
+ * that serve one directory per process.
45
+ */
46
+ share?: boolean
33
47
  /** Optional allowlist of ACP model ids to expose. */
34
48
  models?: string[]
35
49
  /** Default ACP model for direct tool calls. */
@@ -201,6 +215,11 @@ export class AcpServerManager {
201
215
  private cmdSkillDir?: string
202
216
  private cmdOrchestration: boolean
203
217
  private onCommands?: (server: string) => void
218
+ /** Pool that owns agent processes; shared with other OpenCode directories when passed in. */
219
+ private agents: AgentPool
220
+ private ownsAgents: boolean
221
+ /** The pool lease each server's client came from, so released sessions do not outlive it. */
222
+ private leases = new Map<string, AgentLease>()
204
223
  private disposed = false
205
224
 
206
225
  constructor(input: {
@@ -226,6 +245,11 @@ export class AcpServerManager {
226
245
  cmdOrchestration?: boolean
227
246
  /** Called when a server's advertised command list changes. */
228
247
  onCommands?: (server: string) => void
248
+ /**
249
+ * Pool that owns agent processes. Pass `sharedAgentPool()` to share them
250
+ * across OpenCode directories; defaults to a private pool.
251
+ */
252
+ agents?: AgentPool
229
253
  }) {
230
254
  this.defaultCwd = input.defaultCwd
231
255
  this.permissionResolver = input.requestPermission
@@ -244,6 +268,8 @@ export class AcpServerManager {
244
268
  this.cmdSkillDir = input.cmdSkillDir
245
269
  this.cmdOrchestration = input.cmdOrchestration === true
246
270
  this.onCommands = input.onCommands
271
+ this.agents = input.agents ?? new AgentPool()
272
+ this.ownsAgents = input.agents === undefined
247
273
 
248
274
  for (const config of input.servers) {
249
275
  if (!config?.id || !config.command) continue
@@ -338,15 +364,37 @@ export class AcpServerManager {
338
364
  return effort && effort !== "default" ? effort : undefined
339
365
  }
340
366
 
341
- private sessionDirectories(config: AcpServerConfig) {
342
- return config.skills === false ? undefined : this.additionalDirectories
367
+ private sessionDirectories(config: AcpServerConfig, client?: AcpClient) {
368
+ const directories = [...(config.skills === false ? [] : (this.additionalDirectories ?? []))]
369
+ const lease = this.leases.get(config.id)
370
+ if (client && lease?.client === client) directories.push(...lease.readRoots)
371
+ return directories.length ? directories : undefined
343
372
  }
344
373
 
345
- private commandFor(config: AcpServerConfig) {
346
- return applyCmdMods(config.command, {
347
- orchestration: this.cmdOrchestration,
348
- skillDir: config.skills === false ? undefined : this.cmdSkillDir,
349
- })
374
+ private launchFor(config: AcpServerConfig, skillDir: string | undefined): AgentLaunch {
375
+ const { command, args } = normalizeCommand(
376
+ applyCmdMods(config.command, { orchestration: this.cmdOrchestration, skillDir }),
377
+ )
378
+ const env: Record<string, string> = { ...config.env }
379
+ if (skillDir !== undefined && isCmdCommand(config.command)) {
380
+ // Read by agents/cmd/mods/opencode-skills.ts, which registers the directory
381
+ // because `cmd acp` does not apply the global `--skill` flag.
382
+ env.OPENCODE_ACP_PROVIDER_SKILL_DIR = skillDir
383
+ }
384
+ return {
385
+ command,
386
+ args,
387
+ env,
388
+ cwd:
389
+ config.cwd ??
390
+ (this.ownsAgents || (!isAbsolute(command) && /[\\/]/.test(command)) ? this.defaultCwd : homedir()),
391
+ scope: this.ownsAgents ? config.id : undefined,
392
+ autoApprove: config.autoApprove !== false,
393
+ requestTimeoutMs: this.requestTimeoutMs,
394
+ promptTimeoutMs: this.promptTimeoutMs,
395
+ allowPathsOutsideCwd: this.allowPathsOutsideCwd,
396
+ maxFileBytes: this.maxFileBytes,
397
+ }
350
398
  }
351
399
 
352
400
  /** Install or update the agent before it is spawned; memoized per script. */
@@ -395,7 +443,7 @@ export class AcpServerManager {
395
443
  pooled.selection = selection
396
444
  return
397
445
  } catch (error) {
398
- if (!(error instanceof AcpError) || ![-32601, -32602].includes(error.code)) throw error
446
+ if (!isAcpError(error) || ![-32601, -32602].includes(error.code)) throw error
399
447
  this.log("debug", `ACP session refused a selection change; replaying in a fresh session: ${error.message}`)
400
448
  }
401
449
  }
@@ -415,18 +463,25 @@ export class AcpServerManager {
415
463
  model: selection.model,
416
464
  mcpServers: lease?.servers ?? pooled.mcpServers,
417
465
  meta: state.config.meta,
418
- additionalDirectories: this.sessionDirectories(state.config),
466
+ additionalDirectories: this.sessionDirectories(state.config, pooled.client),
467
+ owner: this,
468
+ onCommands: (commands) => this.recordCommands(state, commands),
419
469
  })
420
470
  .catch((error) => {
421
471
  lease?.release()
422
472
  throw error
423
473
  })
474
+ if (this.disposed) {
475
+ await pooled.client.closeSession(session.sessionId, this).catch(() => {})
476
+ lease?.release()
477
+ throw new Error("ACP server manager is stopped")
478
+ }
424
479
  try {
425
480
  if (state.config.mode) await pooled.client.setMode(session.sessionId, state.config.mode).catch(() => {})
426
481
  await this.applyEffort(state, pooled.client, session.sessionId, selection.effort)
427
482
  } catch (error) {
428
483
  lease?.release()
429
- await pooled.client.closeSession(session.sessionId).catch(() => {})
484
+ await pooled.client.closeSession(session.sessionId, this).catch(() => {})
430
485
  throw error
431
486
  }
432
487
  // The pool may have been closed while the new session was being prepared
@@ -434,7 +489,7 @@ export class AcpServerManager {
434
489
  // fresh lease here keeps its bridge token from outliving a dead pool.
435
490
  if (pooled.broken) {
436
491
  lease?.release()
437
- await pooled.client.closeSession(session.sessionId).catch(() => {})
492
+ await pooled.client.closeSession(session.sessionId, this).catch(() => {})
438
493
  throw new Error(`ACP session for key ${pooled.key.slice(0, 24)} was closed while changing selection`)
439
494
  }
440
495
  const oldSession = pooled.sessionId
@@ -447,7 +502,7 @@ export class AcpServerManager {
447
502
  pooled.mcpRelease = lease.release
448
503
  }
449
504
  await this.rememberSession(poolKey, session.sessionId)
450
- await pooled.client.closeSession(oldSession).catch(() => {})
505
+ await pooled.client.closeSession(oldSession, this).catch(() => {})
451
506
  }
452
507
 
453
508
  /** Discover enabled agents in parallel and report each result independently. */
@@ -521,92 +576,91 @@ export class AcpServerManager {
521
576
  // instant when discovery already ran it.
522
577
  await this.setupFor(state)
523
578
  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
579
 
533
580
  const previous = state.client
534
581
  if (previous) {
535
582
  await this.closePoolsFor(config.id)
536
- await previous.stop().catch(() => {})
583
+ this.leases.get(config.id)?.release()
584
+ this.leases.delete(config.id)
537
585
  }
586
+ this.assertLive()
538
587
 
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),
588
+ const skillDir = config.skills === false ? undefined : this.cmdSkillDir
589
+ const subscriber: AgentSubscriber = {
590
+ onLog: (level, message) => this.log(level, `[${config.id}] ${message}`),
551
591
  onExit: (error) => {
552
592
  this.log("warn", `ACP agent "${config.id}" exited; pooled sessions were dropped: ${error.message}`)
553
593
  void this.closePoolsFor(config.id)
554
594
  },
555
- })
595
+ }
596
+ const dedicated = isCmdCommand(config.command) || config.share === false
597
+ const lease = dedicated
598
+ ? this.agents.dedicated({ launch: (dir) => this.launchFor(config, dir), skillDir }, subscriber)
599
+ : this.agents.acquire(this.launchFor(config, skillDir), subscriber)
600
+ this.leases.set(config.id, lease)
601
+ const client = lease.client
556
602
  state.client = client
557
603
  state.retryable = true
558
604
 
559
605
  try {
560
606
  const session = await client.newSession(config.cwd ?? this.defaultCwd, {
561
607
  meta: config.meta,
562
- additionalDirectories: this.sessionDirectories(config),
608
+ additionalDirectories: this.sessionDirectories(config, client),
609
+ owner: this,
610
+ onCommands: (commands) => this.recordCommands(state, commands),
563
611
  })
564
- this.assertLive()
565
- const defaultModel = session.currentModel ?? (session.modelConfigID ? undefined : "default")
566
- let models = session.models.length
567
- ? session.models
568
- : defaultModel ? [{ id: defaultModel, name: session.currentModel ?? "Agent default" }] : []
569
- if (!session.modelConfigID && config.model && config.model !== defaultModel) {
570
- state.retryable = false
571
- throw new Error(`ACP server "${config.id}" does not expose an ACP model selector; use "default" or omit "model"`)
572
- }
573
- if (config.models?.length) {
574
- const allow = new Set(config.models)
575
- models = models.filter((model) => allow.has(model.id))
576
- if (!models.length) {
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) {
577
619
  state.retryable = false
578
- throw new Error(
579
- `ACP server "${config.id}" advertised no model matching "models" (${config.models.join(", ")})`,
620
+ throw new Error(`ACP server "${config.id}" does not expose an ACP model selector; use "default" or omit "model"`)
621
+ }
622
+ if (config.models?.length) {
623
+ const allow = new Set(config.models)
624
+ models = models.filter((model) => allow.has(model.id))
625
+ if (!models.length) {
626
+ state.retryable = false
627
+ throw new Error(
628
+ `ACP server "${config.id}" advertised no model matching "models" (${config.models.join(", ")})`,
629
+ )
630
+ }
631
+ }
632
+ if (config.model && models.length && !models.some((model) => model.id === config.model)) {
633
+ this.log(
634
+ "warn",
635
+ `ACP server "${config.id}" does not advertise the configured model "${config.model}"; it will be sent anyway`,
580
636
  )
581
637
  }
582
- }
583
- if (config.model && models.length && !models.some((model) => model.id === config.model)) {
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)
584
651
  this.log(
585
- "warn",
586
- `ACP server "${config.id}" does not advertise the configured model "${config.model}"; it will be sent anyway`,
652
+ "info",
653
+ `ACP server "${config.id}" ready with ${models.length} model(s)` +
654
+ (state.efforts.length ? ` and effort levels: ${state.efforts.join(", ")}` : ""),
587
655
  )
656
+ } finally {
657
+ await client.closeSession(session.sessionId, this).catch(() => {})
588
658
  }
589
- state.models = models
590
- state.defaultModel = defaultModel
591
- state.modelConfigID = session.modelConfigID
592
- state.efforts = (session.efforts ?? []).filter((value) => value !== "default")
593
- state.effortConfigID = session.effort?.configId
594
- state.defaultEffort = session.effort?.currentValue
595
- state.initialized = true
596
- state.error = undefined
597
- // The command list arrives as a notification just after `session/new`, so
598
- // wait for it before this discovery session is closed: once it is gone,
599
- // the only way to learn the list is to open another session.
600
- const commands = await client.waitForCommands(session.sessionId, COMMAND_SNAPSHOT_TIMEOUT_MS)
601
- if (commands) this.recordCommands(state, commands)
602
- await client.closeSession(session.sessionId).catch(() => {})
603
- this.log(
604
- "info",
605
- `ACP server "${config.id}" ready with ${models.length} model(s)` +
606
- (state.efforts.length ? ` and effort levels: ${state.efforts.join(", ")}` : ""),
607
- )
608
659
  } catch (error) {
609
- await client.stop().catch(() => {})
660
+ if (this.leases.get(config.id) === lease) {
661
+ lease.release()
662
+ this.leases.delete(config.id)
663
+ }
610
664
  if (state.client === client) state.client = undefined
611
665
  throw error
612
666
  }
@@ -671,18 +725,25 @@ export class AcpServerManager {
671
725
  const session = await client.newSession(cwd, {
672
726
  model,
673
727
  meta: state.config.meta,
674
- additionalDirectories: this.sessionDirectories(state.config),
728
+ additionalDirectories: this.sessionDirectories(state.config, client),
729
+ owner: this,
730
+ onCommands: (commands) => this.recordCommands(state, commands),
675
731
  })
732
+ if (this.disposed) {
733
+ await client.closeSession(session.sessionId, this).catch(() => {})
734
+ throw new Error("ACP server manager is stopped")
735
+ }
676
736
  try {
677
737
  if (mode) await client.setMode(session.sessionId, mode).catch(() => {})
678
738
  await this.applyEffort(state, client, session.sessionId, effort)
679
739
  return await client.prompt(session.sessionId, prompt, {
740
+ owner: this,
680
741
  onUpdate: input.onUpdate,
681
742
  signal: input.signal,
682
743
  requestPermission: onPermission,
683
744
  })
684
745
  } finally {
685
- await client.closeSession(session.sessionId)
746
+ await client.closeSession(session.sessionId, this)
686
747
  }
687
748
  }
688
749
 
@@ -713,7 +774,9 @@ export class AcpServerManager {
713
774
  cwd,
714
775
  mcpServers: lease?.servers,
715
776
  meta: state.config.meta,
716
- additionalDirectories: this.sessionDirectories(state.config),
777
+ additionalDirectories: this.sessionDirectories(state.config, client),
778
+ owner: this,
779
+ onCommands: (commands) => this.recordCommands(state, commands),
717
780
  })
718
781
  .catch(async (error) => {
719
782
  this.log(
@@ -723,6 +786,11 @@ export class AcpServerManager {
723
786
  await this.forgetSession(poolKey)
724
787
  return undefined
725
788
  })
789
+ if (this.disposed) {
790
+ if (restored) await client.closeSession(stored, this).catch(() => {})
791
+ lease?.release()
792
+ throw new Error("ACP server manager is stopped")
793
+ }
726
794
  if (restored) {
727
795
  session = { sessionId: stored }
728
796
  reused = true
@@ -738,8 +806,15 @@ export class AcpServerManager {
738
806
  model,
739
807
  mcpServers: lease?.servers,
740
808
  meta: state.config.meta,
741
- additionalDirectories: this.sessionDirectories(state.config),
809
+ additionalDirectories: this.sessionDirectories(state.config, client),
810
+ owner: this,
811
+ onCommands: (commands) => this.recordCommands(state, commands),
742
812
  })
813
+ if (this.disposed) {
814
+ await client.closeSession(session.sessionId, this).catch(() => {})
815
+ lease?.release()
816
+ throw new Error("ACP server manager is stopped")
817
+ }
743
818
  await this.rememberSession(poolKey, session.sessionId)
744
819
  }
745
820
  if (mode) await client.setMode(session.sessionId, mode).catch(() => {})
@@ -751,9 +826,14 @@ export class AcpServerManager {
751
826
  await this.applyEffort(state, client, session.sessionId, effort)
752
827
  } catch (error) {
753
828
  lease?.release()
754
- if (session) await client.closeSession(session.sessionId).catch(() => {})
829
+ if (session) await client.closeSession(session.sessionId, this).catch(() => {})
755
830
  throw error
756
831
  }
832
+ if (this.disposed) {
833
+ await client.closeSession(session.sessionId, this).catch(() => {})
834
+ lease?.release()
835
+ throw new Error("ACP server manager is stopped")
836
+ }
757
837
  const created: PooledSession = {
758
838
  server: input.server,
759
839
  key: input.key!,
@@ -812,6 +892,7 @@ export class AcpServerManager {
812
892
  pooled.history = "retained"
813
893
  const turn = pooled.client
814
894
  .prompt(pooled.sessionId, prompt, {
895
+ owner: this,
815
896
  onUpdate: input.onUpdate,
816
897
  signal: input.signal,
817
898
  requestPermission: onPermission,
@@ -822,7 +903,7 @@ export class AcpServerManager {
822
903
  // `prompt` has already written the request, so the agent sees the cancel
823
904
  // after the prompt it belongs to.
824
905
  if (key && this.startCancels.delete(key)) {
825
- pooled.client.cancelTurn(pooled.sessionId)
906
+ pooled.client.cancelTurn(pooled.sessionId, this)
826
907
  this.log("debug", `cancelled ACP session ${pooled.sessionId} for a steer that arrived while it was starting`)
827
908
  }
828
909
  return turn
@@ -852,13 +933,13 @@ export class AcpServerManager {
852
933
  if (this.pools.get(poolKey) !== pooled) return
853
934
  const message = errorMessage(error)
854
935
  const unknown = isUnknownSession(error)
855
- if (unknown || !pooled.client.alive || !pooled.client.hasSession(pooled.sessionId)) {
936
+ if (unknown || !pooled.client.alive || !pooled.client.hasSession(pooled.sessionId, this)) {
856
937
  void this.dropPool(poolKey, pooled)
857
938
  if (unknown) void this.forgetSession(poolKey)
858
939
  return
859
940
  }
860
941
  pooled.failures += 1
861
- if (error instanceof AcpError && error.code === ACP_REQUEST_CANCELLED) {
942
+ if (isAcpError(error) && error.code === ACP_REQUEST_CANCELLED) {
862
943
  // A stopped turn is normal; the agent already ended it, so the session
863
944
  // is intact and the next prompt picks up the same conversation.
864
945
  pooled.failures = 0
@@ -875,7 +956,7 @@ export class AcpServerManager {
875
956
  }
876
957
  // Ask the agent to end whatever it is still running so the queued or next
877
958
  // prompt enters the same context at a clean boundary.
878
- pooled.client.cancelTurn(pooled.sessionId)
959
+ pooled.client.cancelTurn(pooled.sessionId, this)
879
960
  this.log("debug", `keeping ACP session ${pooled.sessionId} after a failed turn: ${message}`)
880
961
  }
881
962
 
@@ -884,7 +965,7 @@ export class AcpServerManager {
884
965
  pooled.broken = true
885
966
  if (this.pools.get(poolKey) === pooled) this.pools.delete(poolKey)
886
967
  pooled.mcpRelease?.()
887
- await pooled.client.closeSession(pooled.sessionId).catch(() => {})
968
+ await pooled.client.closeSession(pooled.sessionId, this).catch(() => {})
888
969
  }
889
970
 
890
971
  /**
@@ -907,7 +988,7 @@ export class AcpServerManager {
907
988
  return
908
989
  }
909
990
 
910
- pooled.client.cancelTurn(pooled.sessionId)
991
+ pooled.client.cancelTurn(pooled.sessionId, this)
911
992
  this.log("debug", `interrupted ACP session ${pooled.sessionId} so the queued message can be delivered`)
912
993
  }
913
994
 
@@ -930,6 +1011,7 @@ export class AcpServerManager {
930
1011
  const run = pooled.queue.then(() => {
931
1012
  if (pooled.broken) throw new Error(`ACP session ${pooled.sessionId} is no longer usable`)
932
1013
  return pooled.client.prompt(pooled.sessionId, "/compact", {
1014
+ owner: this,
933
1015
  onUpdate: (update) => {
934
1016
  // Claude Code reports a compaction as a tool call with its context size before and after.
935
1017
  const output = update.rawOutput as { preTokens?: unknown; postTokens?: unknown } | undefined
@@ -997,19 +1079,32 @@ export class AcpServerManager {
997
1079
  this.negotiating.clear()
998
1080
  const pools = [...this.pools.values()]
999
1081
  this.pools.clear()
1000
- // Best effort: the agents are killed below, so do not wait on a close
1001
- // handshake that could hang shutdown.
1082
+ // Best effort: the agent may be shared with another directory, so do not
1083
+ // wait on a close handshake that could hang shutdown. Closing drops the
1084
+ // session from the client, so its owner loop below can no longer see it:
1085
+ // end the turn here, or a shared agent would keep running one nobody reads.
1002
1086
  for (const pooled of pools) {
1003
1087
  pooled.broken = true
1004
1088
  pooled.mcpRelease?.()
1005
- void pooled.client.closeSession(pooled.sessionId).catch(() => {})
1089
+ pooled.client.cancelTurn(pooled.sessionId, this)
1090
+ void pooled.client.closeSession(pooled.sessionId, this).catch(() => {})
1091
+ }
1092
+ // Only this manager's sessions close; another directory's stay on the client.
1093
+ for (const lease of this.leases.values()) {
1094
+ for (const sessionId of lease.client.sessionsOwnedBy(this)) {
1095
+ lease.client.cancelTurn(sessionId, this)
1096
+ void lease.client.closeSession(sessionId, this).catch(() => {})
1097
+ }
1006
1098
  }
1007
- await Promise.allSettled([...this.servers.values()].map((state) => state.client?.stop()))
1099
+ for (const lease of this.leases.values()) lease.release()
1100
+ this.leases.clear()
1101
+ for (const state of this.servers.values()) state.client = undefined
1102
+ if (this.ownsAgents) await this.agents.stop()
1008
1103
  }
1009
1104
  }
1010
1105
 
1011
1106
  function isUnknownSession(error: unknown) {
1012
- if (!(error instanceof AcpError)) return false
1107
+ if (!isAcpError(error)) return false
1013
1108
  if (error.code === ACP_UNKNOWN_SESSION) return true
1014
1109
  return /unknown (acp )?session|session .*not found|session .*does not exist/i.test(error.message)
1015
1110
  }