@moxt-ai/mobius 0.0.40 → 0.0.42

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.
Files changed (41) hide show
  1. package/dist/acp/activity.d.ts.map +1 -1
  2. package/dist/acp/activity.js +52 -8
  3. package/dist/acp/activity.js.map +1 -1
  4. package/dist/acp/session-manager.d.ts +4 -3
  5. package/dist/acp/session-manager.d.ts.map +1 -1
  6. package/dist/acp/session-manager.js +511 -126
  7. package/dist/acp/session-manager.js.map +1 -1
  8. package/dist/agent-catalog/discover-local-agents.d.ts +0 -1
  9. package/dist/agent-catalog/discover-local-agents.d.ts.map +1 -1
  10. package/dist/agent-catalog/discover-local-agents.js +0 -1
  11. package/dist/agent-catalog/discover-local-agents.js.map +1 -1
  12. package/dist/artifacts/runtime-artifact-uploader.d.ts +2 -2
  13. package/dist/artifacts/runtime-artifact-uploader.d.ts.map +1 -1
  14. package/dist/artifacts/runtime-artifact-uploader.js +3 -3
  15. package/dist/artifacts/runtime-artifact-uploader.js.map +1 -1
  16. package/dist/authorization/local-artifact.d.ts +6 -0
  17. package/dist/authorization/local-artifact.d.ts.map +1 -0
  18. package/dist/authorization/local-artifact.js +2 -0
  19. package/dist/authorization/local-artifact.js.map +1 -0
  20. package/dist/authorization/local-video.d.ts +11 -0
  21. package/dist/authorization/local-video.d.ts.map +1 -0
  22. package/dist/authorization/local-video.js +48 -0
  23. package/dist/authorization/local-video.js.map +1 -0
  24. package/dist/bots/local-bot-grant-store.d.ts +1 -8
  25. package/dist/bots/local-bot-grant-store.d.ts.map +1 -1
  26. package/dist/bots/local-bot-grant-store.js +79 -121
  27. package/dist/bots/local-bot-grant-store.js.map +1 -1
  28. package/dist/cli.js +1647 -1276
  29. package/dist/cli.js.map +4 -4
  30. package/dist/index.js +800 -312
  31. package/dist/index.js.map +4 -4
  32. package/dist/run-daemon.js +2 -2
  33. package/dist/run-daemon.js.map +1 -1
  34. package/dist/runtime.d.ts.map +1 -1
  35. package/dist/runtime.js +792 -304
  36. package/dist/runtime.js.map +4 -4
  37. package/package.json +1 -1
  38. package/dist/bots/bot-approve-command.d.ts +0 -2
  39. package/dist/bots/bot-approve-command.d.ts.map +0 -1
  40. package/dist/bots/bot-approve-command.js +0 -78
  41. package/dist/bots/bot-approve-command.js.map +0 -1
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { methods, ndJsonStream, PROTOCOL_VERSION, RequestError, } from "@agentclientprotocol/sdk";
3
3
  import { AGENT_CONTENT_KIND, decodeAgentPromptResponse, SESSION_COMMANDS_UPDATED_KIND, SESSION_CONFIG_UPDATED_KIND, SESSION_ELICITATION_REQUESTED_KIND, SESSION_ELICITATION_RESOLVED_KIND, SESSION_INFO_UPDATED_KIND, SESSION_PERMISSION_REQUESTED_KIND, SESSION_PERMISSION_RESOLVED_KIND, SESSION_USAGE_UPDATED_KIND, } from "@moxt-ai/mobius-protocol";
4
4
  import { readAuthorizedRaster, readInlineRaster } from "../authorization/local-raster.js";
5
+ import { readInlineVideo } from "../authorization/local-video.js";
5
6
  import { unmeasuredOperationMetrics } from "../infra/operation-metrics.js";
6
7
  import { embedLocalHistoryImages } from "../native-sessions/history-images.js";
7
8
  import { captureProcessTree, revalidateExecutable, stopProcessTree, } from "../process/executable.js";
@@ -15,11 +16,12 @@ import { sessionConfigProtocolForAgent } from "./session-config/session-config-r
15
16
  import { AcpHistoryReplay } from "./session-history.js";
16
17
  import { AcpStoredSession, DeletedAcpStoredSession, FoundAcpStoredSession, MemoryAcpSessionStore, } from "./session-store.js";
17
18
  const PROCESS_STOP_TIMEOUT_MILLISECONDS = 1_000;
19
+ const MAX_ACP_PROCESSES = 10;
18
20
  const MAX_PRE_SESSION_UPDATES = 100;
19
21
  const MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
20
22
  const SESSION_CONTROL_COMMAND_ID = "session-control";
21
23
  export class NullAcpSessionObserver {
22
- importLocalImage = (_sessionId, _image, signal) => {
24
+ importLocalArtifact = (_sessionId, _artifact, signal) => {
23
25
  signal.throwIfAborted();
24
26
  return Promise.resolve("");
25
27
  };
@@ -73,6 +75,95 @@ class RetryableAcpInitializationError extends AcpExecutionError {
73
75
  this.name = "RetryableAcpInitializationError";
74
76
  }
75
77
  }
78
+ class AcpProcessCapacityLease {
79
+ #releaseCapacity;
80
+ #released = false;
81
+ constructor(releaseCapacity) {
82
+ this.#releaseCapacity = releaseCapacity;
83
+ }
84
+ release = () => {
85
+ if (this.#released) {
86
+ return;
87
+ }
88
+ this.#released = true;
89
+ this.#releaseCapacity();
90
+ };
91
+ }
92
+ class AcpProcessCapacityWaiter {
93
+ completion = Promise.withResolvers();
94
+ signal;
95
+ constructor(signal) {
96
+ this.signal = signal;
97
+ }
98
+ cancel = () => {
99
+ try {
100
+ this.signal.throwIfAborted();
101
+ }
102
+ catch (error) {
103
+ this.completion.reject(error);
104
+ }
105
+ };
106
+ }
107
+ class AcpProcessCapacityLock {
108
+ #locked = false;
109
+ #waiters = [];
110
+ acquire = async (signal) => {
111
+ signal.throwIfAborted();
112
+ if (!this.#locked) {
113
+ this.#locked = true;
114
+ return new AcpProcessCapacityLease(this.#release);
115
+ }
116
+ const waiter = new AcpProcessCapacityWaiter(signal);
117
+ this.#waiters.push(waiter);
118
+ signal.addEventListener("abort", waiter.cancel, { once: true });
119
+ if (signal.aborted) {
120
+ waiter.cancel();
121
+ }
122
+ try {
123
+ return await waiter.completion.promise;
124
+ }
125
+ finally {
126
+ signal.removeEventListener("abort", waiter.cancel);
127
+ const index = this.#waiters.indexOf(waiter);
128
+ if (index >= 0) {
129
+ this.#waiters.splice(index, 1);
130
+ }
131
+ }
132
+ };
133
+ #release = () => {
134
+ while (this.#waiters.length > 0) {
135
+ const waiter = this.#waiters.shift();
136
+ if (waiter === undefined || waiter.signal.aborted) {
137
+ continue;
138
+ }
139
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
140
+ return;
141
+ }
142
+ this.#locked = false;
143
+ };
144
+ }
145
+ async function waitForAcpProcessCapacity(completion, signal) {
146
+ signal.throwIfAborted();
147
+ const cancelled = Promise.withResolvers();
148
+ const cancel = () => {
149
+ try {
150
+ signal.throwIfAborted();
151
+ }
152
+ catch (error) {
153
+ cancelled.reject(error);
154
+ }
155
+ };
156
+ signal.addEventListener("abort", cancel, { once: true });
157
+ if (signal.aborted) {
158
+ cancel();
159
+ }
160
+ try {
161
+ await Promise.race([completion, cancelled.promise]);
162
+ }
163
+ finally {
164
+ signal.removeEventListener("abort", cancel);
165
+ }
166
+ }
76
167
  function readableWebStream(input) {
77
168
  let streamOpen = true;
78
169
  return new ReadableStream({
@@ -604,6 +695,13 @@ class AcpProcessSession {
604
695
  return await this.importRaster(raster, signal);
605
696
  }
606
697
  }
698
+ if (content.type === "video" && content.data.length > 0) {
699
+ const video = readInlineVideo(content.data, content.mimeType, content.name);
700
+ if (video === null) {
701
+ return { ...content, data: "" };
702
+ }
703
+ return await this.importVideo(video, AbortSignal.timeout(20_000));
704
+ }
607
705
  return content;
608
706
  };
609
707
  emitAgentContent = async (content, messageId) => {
@@ -629,9 +727,25 @@ class AcpProcessSession {
629
727
  });
630
728
  };
631
729
  importRaster = async (raster, signal) => {
632
- const artifactId = await this.#getObserver().importLocalImage(this.#mobiusSessionId, raster, signal);
730
+ const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, raster, signal);
633
731
  return imageDisplayContent(raster.mimeType, raster.name, artifactId.length > 0 ? "" : raster.base64(), artifactId);
634
732
  };
733
+ importVideo = async (video, signal) => {
734
+ const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, video, signal);
735
+ return {
736
+ artifactId,
737
+ data: artifactId.length > 0 ? "" : video.base64(),
738
+ mimeType: video.mimeType,
739
+ name: video.name,
740
+ newText: "",
741
+ oldText: "",
742
+ path: "",
743
+ terminalId: "",
744
+ text: "",
745
+ type: "video",
746
+ uri: "",
747
+ };
748
+ };
635
749
  async #initializeAgent(signal) {
636
750
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
637
751
  }
@@ -1238,18 +1352,22 @@ class AcpProcessSession {
1238
1352
  }
1239
1353
  };
1240
1354
  close = async () => {
1241
- await this.cancelPendingInteractions();
1242
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
1243
- try {
1244
- await this.#connection.agent.request(methods.agent.session.close, { sessionId: this.#nativeSessionId }, {
1245
- cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS),
1246
- });
1247
- }
1248
- catch {
1249
- // Process teardown below remains authoritative.
1355
+ try {
1356
+ await this.cancelPendingInteractions();
1357
+ if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
1358
+ try {
1359
+ await this.#connection.agent.request(methods.agent.session.close, { sessionId: this.#nativeSessionId }, {
1360
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS),
1361
+ });
1362
+ }
1363
+ catch {
1364
+ // Process teardown below remains authoritative.
1365
+ }
1250
1366
  }
1251
1367
  }
1252
- await this.closeProcess();
1368
+ finally {
1369
+ await this.closeProcess();
1370
+ }
1253
1371
  };
1254
1372
  closeProcess = async (capturedProcesses = []) => {
1255
1373
  try {
@@ -1354,6 +1472,31 @@ class AcpProcessSession {
1354
1472
  }
1355
1473
  };
1356
1474
  }
1475
+ class AcpProcessEvictionCandidate {
1476
+ }
1477
+ class MissingAcpProcessEvictionCandidate extends AcpProcessEvictionCandidate {
1478
+ }
1479
+ class FoundAcpProcessEvictionCandidate extends AcpProcessEvictionCandidate {
1480
+ runtime;
1481
+ constructor(runtime) {
1482
+ super();
1483
+ this.runtime = runtime;
1484
+ }
1485
+ }
1486
+ class FoundAcpSessionProcessEvictionCandidate extends FoundAcpProcessEvictionCandidate {
1487
+ sessionId;
1488
+ constructor(sessionId, runtime) {
1489
+ super(runtime);
1490
+ this.sessionId = sessionId;
1491
+ }
1492
+ }
1493
+ class FoundAcpNativeBrowserProcessEvictionCandidate extends FoundAcpProcessEvictionCandidate {
1494
+ sessionId;
1495
+ constructor(sessionId, runtime) {
1496
+ super(runtime);
1497
+ this.sessionId = sessionId;
1498
+ }
1499
+ }
1357
1500
  export class AcpSessionManager {
1358
1501
  #activeCommandIds = new Map();
1359
1502
  #agentSettingsObserver = new NullAcpSessionObserver();
@@ -1362,10 +1505,18 @@ export class AcpSessionManager {
1362
1505
  #nativeBrowserPreparing = new Map();
1363
1506
  #nativeBrowserSessions = new Map();
1364
1507
  #nativeBrowserStore = new MemoryAcpSessionStore();
1508
+ #nativeBrowserUseCounts = new Map();
1365
1509
  #activeSessionIds = new Set();
1366
1510
  #cancellationRequests = new Map();
1367
1511
  #preparing = new Map();
1512
+ #processCapacityChanged = Promise.withResolvers();
1513
+ #processCapacityLock = new AcpProcessCapacityLock();
1514
+ #retainedProcesses = new Map();
1515
+ #retiringProcessCount = 0;
1516
+ #sessionUseCounts = new Map();
1368
1517
  #sessions = new Map();
1518
+ #startingProcessCount = 0;
1519
+ #transientProcessCount = 0;
1369
1520
  #store;
1370
1521
  #observer;
1371
1522
  constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore()) {
@@ -1375,15 +1526,229 @@ export class AcpSessionManager {
1375
1526
  setObserver = (observer) => {
1376
1527
  this.#observer = observer;
1377
1528
  };
1529
+ #notifyProcessCapacityChanged() {
1530
+ const changed = this.#processCapacityChanged;
1531
+ this.#processCapacityChanged = Promise.withResolvers();
1532
+ changed.resolve();
1533
+ }
1534
+ #touchSession(sessionId) {
1535
+ const runtime = this.#sessions.get(sessionId);
1536
+ if (runtime === undefined) {
1537
+ return;
1538
+ }
1539
+ this.#touchProcess(runtime);
1540
+ }
1541
+ #touchExpectedSession(sessionId, expected) {
1542
+ if (this.#sessions.get(sessionId) !== expected) {
1543
+ return;
1544
+ }
1545
+ this.#touchProcess(expected);
1546
+ }
1547
+ #touchNativeBrowserSession(sessionId) {
1548
+ const runtime = this.#nativeBrowserSessions.get(sessionId);
1549
+ if (runtime === undefined) {
1550
+ return;
1551
+ }
1552
+ this.#touchProcess(runtime);
1553
+ }
1554
+ #touchExpectedNativeBrowserSession(sessionId, expected) {
1555
+ if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
1556
+ return;
1557
+ }
1558
+ this.#touchProcess(expected);
1559
+ }
1560
+ #touchProcess(runtime) {
1561
+ const retained = this.#retainedProcesses.get(runtime);
1562
+ if (retained === undefined) {
1563
+ return;
1564
+ }
1565
+ this.#retainedProcesses.delete(runtime);
1566
+ this.#retainedProcesses.set(runtime, retained);
1567
+ }
1568
+ #beginSessionUse(sessionId) {
1569
+ this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
1570
+ this.#touchSession(sessionId);
1571
+ }
1572
+ #endSessionUse(sessionId) {
1573
+ const count = this.#sessionUseCounts.get(sessionId) ?? 0;
1574
+ if (count <= 1) {
1575
+ this.#sessionUseCounts.delete(sessionId);
1576
+ }
1577
+ else {
1578
+ this.#sessionUseCounts.set(sessionId, count - 1);
1579
+ }
1580
+ this.#touchSession(sessionId);
1581
+ this.#notifyProcessCapacityChanged();
1582
+ }
1583
+ #beginNativeBrowserUse(sessionId) {
1584
+ this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
1585
+ this.#touchNativeBrowserSession(sessionId);
1586
+ }
1587
+ #endNativeBrowserUse(sessionId) {
1588
+ const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
1589
+ if (count <= 1) {
1590
+ this.#nativeBrowserUseCounts.delete(sessionId);
1591
+ }
1592
+ else {
1593
+ this.#nativeBrowserUseCounts.set(sessionId, count - 1);
1594
+ }
1595
+ this.#touchNativeBrowserSession(sessionId);
1596
+ this.#notifyProcessCapacityChanged();
1597
+ }
1598
+ #isNativeSessionOperationActive(sessionId) {
1599
+ const stored = this.#store.read(sessionId);
1600
+ return (stored instanceof FoundAcpStoredSession &&
1601
+ this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`));
1602
+ }
1603
+ #leastRecentlyUsedEvictionCandidate() {
1604
+ for (const candidate of this.#retainedProcesses.values()) {
1605
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
1606
+ if (this.#activeSessionIds.has(candidate.sessionId) ||
1607
+ this.#cancellationRequests.has(candidate.sessionId) ||
1608
+ this.#preparing.has(candidate.sessionId) ||
1609
+ (this.#sessionUseCounts.get(candidate.sessionId) ?? 0) > 0 ||
1610
+ this.#isNativeSessionOperationActive(candidate.sessionId)) {
1611
+ continue;
1612
+ }
1613
+ return candidate;
1614
+ }
1615
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate &&
1616
+ !this.#nativeBrowserPreparing.has(candidate.sessionId) &&
1617
+ (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
1618
+ return candidate;
1619
+ }
1620
+ }
1621
+ return new MissingAcpProcessEvictionCandidate();
1622
+ }
1623
+ #ownedProcessCount() {
1624
+ return (this.#retainedProcesses.size +
1625
+ this.#startingProcessCount +
1626
+ this.#transientProcessCount +
1627
+ this.#retiringProcessCount);
1628
+ }
1629
+ async #retireProcess(runtime, retained, close) {
1630
+ if (retained) {
1631
+ this.#retainedProcesses.delete(runtime);
1632
+ this.#retiringProcessCount += 1;
1633
+ }
1634
+ try {
1635
+ await close();
1636
+ }
1637
+ finally {
1638
+ if (retained) {
1639
+ this.#retiringProcessCount -= 1;
1640
+ this.#notifyProcessCapacityChanged();
1641
+ }
1642
+ }
1643
+ }
1644
+ async #retireSessionProcess(sessionId, runtime, close) {
1645
+ const retained = this.#sessions.get(sessionId) === runtime;
1646
+ if (retained) {
1647
+ this.#sessions.delete(sessionId);
1648
+ }
1649
+ await this.#retireProcess(runtime, retained, close);
1650
+ }
1651
+ async #retireNativeBrowserProcess(sessionId, runtime, close) {
1652
+ const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
1653
+ if (retained) {
1654
+ this.#nativeBrowserSessions.delete(sessionId);
1655
+ this.#nativeBrowserStore.remove(sessionId);
1656
+ }
1657
+ await this.#retireProcess(runtime, retained, close);
1658
+ }
1659
+ async #reserveProcessCapacity(signal) {
1660
+ const lease = await this.#processCapacityLock.acquire(signal);
1661
+ try {
1662
+ for (;;) {
1663
+ signal.throwIfAborted();
1664
+ if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
1665
+ this.#startingProcessCount += 1;
1666
+ return;
1667
+ }
1668
+ const candidate = this.#leastRecentlyUsedEvictionCandidate();
1669
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
1670
+ await this.#retireSessionProcess(candidate.sessionId, candidate.runtime, async () => await candidate.runtime.close());
1671
+ continue;
1672
+ }
1673
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
1674
+ await this.#retireNativeBrowserProcess(candidate.sessionId, candidate.runtime, async () => await candidate.runtime.close());
1675
+ continue;
1676
+ }
1677
+ const changed = this.#processCapacityChanged.promise;
1678
+ await waitForAcpProcessCapacity(changed, signal);
1679
+ }
1680
+ }
1681
+ finally {
1682
+ lease.release();
1683
+ }
1684
+ }
1685
+ async #startRetainedSessionProcess(options, start) {
1686
+ await this.#reserveProcessCapacity(options.signal);
1687
+ try {
1688
+ const runtime = await start();
1689
+ this.#startingProcessCount -= 1;
1690
+ this.#sessions.set(options.sessionId, runtime);
1691
+ this.#retainedProcesses.set(runtime, new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime));
1692
+ this.#notifyProcessCapacityChanged();
1693
+ return runtime;
1694
+ }
1695
+ catch (error) {
1696
+ this.#startingProcessCount -= 1;
1697
+ this.#notifyProcessCapacityChanged();
1698
+ throw error;
1699
+ }
1700
+ }
1701
+ async #startRetainedNativeBrowserProcess(options, start) {
1702
+ await this.#reserveProcessCapacity(options.signal);
1703
+ try {
1704
+ const runtime = await start();
1705
+ this.#startingProcessCount -= 1;
1706
+ this.#nativeBrowserSessions.set(options.sessionId, runtime);
1707
+ this.#retainedProcesses.set(runtime, new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime));
1708
+ this.#notifyProcessCapacityChanged();
1709
+ return runtime;
1710
+ }
1711
+ catch (error) {
1712
+ this.#startingProcessCount -= 1;
1713
+ this.#notifyProcessCapacityChanged();
1714
+ throw error;
1715
+ }
1716
+ }
1717
+ async #runWithTransientProcess(signal, start, operation, close) {
1718
+ await this.#reserveProcessCapacity(signal);
1719
+ let runtime;
1720
+ try {
1721
+ runtime = await start();
1722
+ }
1723
+ catch (error) {
1724
+ this.#startingProcessCount -= 1;
1725
+ this.#notifyProcessCapacityChanged();
1726
+ throw error;
1727
+ }
1728
+ this.#startingProcessCount -= 1;
1729
+ this.#transientProcessCount += 1;
1730
+ this.#notifyProcessCapacityChanged();
1731
+ try {
1732
+ return await operation(runtime);
1733
+ }
1734
+ finally {
1735
+ try {
1736
+ await close(runtime);
1737
+ }
1738
+ finally {
1739
+ this.#transientProcessCount -= 1;
1740
+ this.#notifyProcessCapacityChanged();
1741
+ }
1742
+ }
1743
+ }
1378
1744
  async #startNativeBrowserPreparation(options) {
1379
1745
  const operation = (async () => {
1380
1746
  try {
1381
- const runtime = await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore);
1382
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
1383
- return runtime;
1747
+ return await this.#startRetainedNativeBrowserProcess(options, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore));
1384
1748
  }
1385
1749
  finally {
1386
1750
  this.#nativeBrowserPreparing.delete(options.sessionId);
1751
+ this.#notifyProcessCapacityChanged();
1387
1752
  }
1388
1753
  })();
1389
1754
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -1392,15 +1757,12 @@ export class AcpSessionManager {
1392
1757
  async #replaceNativeBrowserPreparation(existing, options) {
1393
1758
  const operation = (async () => {
1394
1759
  try {
1395
- this.#nativeBrowserSessions.delete(options.sessionId);
1396
- await existing.close();
1397
- this.#nativeBrowserStore.remove(options.sessionId);
1398
- const runtime = await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore);
1399
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
1400
- return runtime;
1760
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
1761
+ return await this.#startRetainedNativeBrowserProcess(options, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore));
1401
1762
  }
1402
1763
  finally {
1403
1764
  this.#nativeBrowserPreparing.delete(options.sessionId);
1765
+ this.#notifyProcessCapacityChanged();
1404
1766
  }
1405
1767
  })();
1406
1768
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -1409,12 +1771,11 @@ export class AcpSessionManager {
1409
1771
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
1410
1772
  const operation = (async () => {
1411
1773
  try {
1412
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
1413
- this.#sessions.set(options.sessionId, runtime);
1414
- return runtime;
1774
+ return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics));
1415
1775
  }
1416
1776
  finally {
1417
1777
  this.#preparing.delete(options.sessionId);
1778
+ this.#notifyProcessCapacityChanged();
1418
1779
  }
1419
1780
  })();
1420
1781
  this.#preparing.set(options.sessionId, operation);
@@ -1423,12 +1784,11 @@ export class AcpSessionManager {
1423
1784
  async #startSessionForkAtTurnPreparation(options, sourceNativeSessionId, forkPoint) {
1424
1785
  const operation = (async () => {
1425
1786
  try {
1426
- const runtime = await AcpProcessSession.startSessionForkAtTurn(options, sourceNativeSessionId, forkPoint, () => this.#observer, this.#store);
1427
- this.#sessions.set(options.sessionId, runtime);
1428
- return runtime;
1787
+ return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.startSessionForkAtTurn(options, sourceNativeSessionId, forkPoint, () => this.#observer, this.#store));
1429
1788
  }
1430
1789
  finally {
1431
1790
  this.#preparing.delete(options.sessionId);
1791
+ this.#notifyProcessCapacityChanged();
1432
1792
  }
1433
1793
  })();
1434
1794
  this.#preparing.set(options.sessionId, operation);
@@ -1437,15 +1797,13 @@ export class AcpSessionManager {
1437
1797
  async #replacePreparation(existing, options, metrics) {
1438
1798
  const operation = (async () => {
1439
1799
  try {
1440
- this.#sessions.delete(options.sessionId);
1441
- await metrics.measure("runtime-replacement-close", async () => await existing.close());
1800
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await metrics.measure("runtime-replacement-close", async () => await existing.close()));
1442
1801
  this.#store.remove(options.sessionId);
1443
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
1444
- this.#sessions.set(options.sessionId, runtime);
1445
- return runtime;
1802
+ return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics));
1446
1803
  }
1447
1804
  finally {
1448
1805
  this.#preparing.delete(options.sessionId);
1806
+ this.#notifyProcessCapacityChanged();
1449
1807
  }
1450
1808
  })();
1451
1809
  this.#preparing.set(options.sessionId, operation);
@@ -1455,10 +1813,9 @@ export class AcpSessionManager {
1455
1813
  const desiredConfigOptions = existing.prepared().configOptions;
1456
1814
  const operation = (async () => {
1457
1815
  try {
1458
- this.#sessions.delete(options.sessionId);
1459
- await existing.close();
1816
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
1460
1817
  this.#store.remove(options.sessionId);
1461
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
1818
+ const runtime = await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store));
1462
1819
  try {
1463
1820
  for (const desired of desiredConfigOptions) {
1464
1821
  const current = runtime.prepared().configOptions.find((option) => option.id === desired.id);
@@ -1492,15 +1849,15 @@ export class AcpSessionManager {
1492
1849
  }
1493
1850
  }
1494
1851
  catch (error) {
1495
- await runtime.close();
1852
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
1496
1853
  this.#store.remove(options.sessionId);
1497
1854
  throw error;
1498
1855
  }
1499
- this.#sessions.set(options.sessionId, runtime);
1500
1856
  return runtime;
1501
1857
  }
1502
1858
  finally {
1503
1859
  this.#preparing.delete(options.sessionId);
1860
+ this.#notifyProcessCapacityChanged();
1504
1861
  }
1505
1862
  })();
1506
1863
  this.#preparing.set(options.sessionId, operation);
@@ -1519,6 +1876,7 @@ export class AcpSessionManager {
1519
1876
  if (pending !== undefined) {
1520
1877
  const runtime = await metrics.measure("session-preparation-wait", async () => await pending);
1521
1878
  if (runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1879
+ this.#touchExpectedSession(options.sessionId, runtime);
1522
1880
  return runtime.prepared();
1523
1881
  }
1524
1882
  return await this.prepareSession(options, metrics);
@@ -1526,6 +1884,7 @@ export class AcpSessionManager {
1526
1884
  const existing = this.#sessions.get(options.sessionId);
1527
1885
  if (existing !== undefined) {
1528
1886
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1887
+ this.#touchExpectedSession(options.sessionId, existing);
1529
1888
  return existing.prepared();
1530
1889
  }
1531
1890
  if (!existing.canRebind()) {
@@ -1542,19 +1901,13 @@ export class AcpSessionManager {
1542
1901
  * authoritative settings. Its identity and store are private to this
1543
1902
  * operation and never become a Mobius Session.
1544
1903
  */
1545
- inspectAgentSettings = async (options) => {
1546
- const runtime = await AcpProcessSession.start({
1547
- ...options,
1548
- sessionId: `agent-settings-${crypto.randomUUID()}`,
1549
- }, () => this.#agentSettingsObserver, new MemoryAcpSessionStore());
1550
- try {
1551
- const prepared = runtime.prepared();
1552
- return new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions);
1553
- }
1554
- finally {
1555
- await runtime.close();
1556
- }
1557
- };
1904
+ inspectAgentSettings = async (options) => await this.#runWithTransientProcess(options.signal, async () => await AcpProcessSession.start({
1905
+ ...options,
1906
+ sessionId: `agent-settings-${crypto.randomUUID()}`,
1907
+ }, () => this.#agentSettingsObserver, new MemoryAcpSessionStore()), (runtime) => {
1908
+ const prepared = runtime.prepared();
1909
+ return Promise.resolve(new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions));
1910
+ }, async (runtime) => await runtime.close());
1558
1911
  /**
1559
1912
  * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
1560
1913
  * Use inspectAgentSettings for Agent-scoped settings discovery.
@@ -1563,21 +1916,24 @@ export class AcpSessionManager {
1563
1916
  if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
1564
1917
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
1565
1918
  }
1566
- const runtime = await this.#startPreparation(options, metrics);
1919
+ this.#beginSessionUse(options.sessionId);
1567
1920
  try {
1568
- return runtime.prepared();
1569
- }
1570
- finally {
1571
- if (this.#sessions.get(options.sessionId) === runtime) {
1572
- this.#sessions.delete(options.sessionId);
1573
- }
1921
+ const runtime = await this.#startPreparation(options, metrics);
1574
1922
  try {
1575
- await runtime.close();
1923
+ return runtime.prepared();
1576
1924
  }
1577
1925
  finally {
1578
- this.#store.remove(options.sessionId);
1926
+ try {
1927
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
1928
+ }
1929
+ finally {
1930
+ this.#store.remove(options.sessionId);
1931
+ }
1579
1932
  }
1580
1933
  }
1934
+ finally {
1935
+ this.#endSessionUse(options.sessionId);
1936
+ }
1581
1937
  };
1582
1938
  prepareExecutionSession = async (options) => {
1583
1939
  const pending = this.#preparing.get(options.sessionId);
@@ -1593,6 +1949,7 @@ export class AcpSessionManager {
1593
1949
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
1594
1950
  }
1595
1951
  if (existing.usesEnvironment(options.agent.environment)) {
1952
+ this.#touchExpectedSession(options.sessionId, existing);
1596
1953
  return existing.prepared();
1597
1954
  }
1598
1955
  if (!existing.canRebind()) {
@@ -1605,6 +1962,7 @@ export class AcpSessionManager {
1605
1962
  if (pending !== undefined) {
1606
1963
  const runtime = await pending;
1607
1964
  if (runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1965
+ this.#touchExpectedNativeBrowserSession(options.sessionId, runtime);
1608
1966
  return runtime.prepared();
1609
1967
  }
1610
1968
  return await this.prepareNativeSessionBrowser(options);
@@ -1612,6 +1970,7 @@ export class AcpSessionManager {
1612
1970
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
1613
1971
  if (existing !== undefined) {
1614
1972
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1973
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
1615
1974
  return existing.prepared();
1616
1975
  }
1617
1976
  if (!existing.canRebind()) {
@@ -1624,8 +1983,14 @@ export class AcpSessionManager {
1624
1983
  return runtime.prepared();
1625
1984
  };
1626
1985
  configureSession = async (options) => {
1627
- const runtime = await this.ensureSession(options);
1628
- return await runtime.configure(options);
1986
+ this.#beginSessionUse(options.sessionId);
1987
+ try {
1988
+ const runtime = await this.ensureSession(options);
1989
+ return await runtime.configure(options);
1990
+ }
1991
+ finally {
1992
+ this.#endSessionUse(options.sessionId);
1993
+ }
1629
1994
  };
1630
1995
  cancelPrompt = async (sessionId) => {
1631
1996
  const existing = this.#cancellationRequests.get(sessionId);
@@ -1642,6 +2007,8 @@ export class AcpSessionManager {
1642
2007
  finally {
1643
2008
  if (this.#sessions.get(sessionId) === runtime) {
1644
2009
  this.#sessions.delete(sessionId);
2010
+ this.#retainedProcesses.delete(runtime);
2011
+ this.#notifyProcessCapacityChanged();
1645
2012
  }
1646
2013
  }
1647
2014
  }
@@ -1719,10 +2086,7 @@ export class AcpSessionManager {
1719
2086
  }
1720
2087
  catch (error) {
1721
2088
  if (this.#cancellationRequests.has(options.sessionId)) {
1722
- if (this.#sessions.get(options.sessionId) === runtime) {
1723
- this.#sessions.delete(options.sessionId);
1724
- }
1725
- await runtime.closeProcess();
2089
+ await this.#cancellationRequests.get(options.sessionId);
1726
2090
  return { stopReason: "cancelled" };
1727
2091
  }
1728
2092
  throw error;
@@ -1731,8 +2095,7 @@ export class AcpSessionManager {
1731
2095
  catch (error) {
1732
2096
  const failedRuntime = this.#sessions.get(options.sessionId);
1733
2097
  if (failedRuntime !== undefined) {
1734
- this.#sessions.delete(options.sessionId);
1735
- await failedRuntime.close();
2098
+ await this.#retireSessionProcess(options.sessionId, failedRuntime, async () => await failedRuntime.close());
1736
2099
  }
1737
2100
  if (this.#cancellationRequests.has(options.sessionId)) {
1738
2101
  return { stopReason: "cancelled" };
@@ -1755,6 +2118,8 @@ export class AcpSessionManager {
1755
2118
  this.#activeCommandIds.delete(options.sessionId);
1756
2119
  }
1757
2120
  this.#cancellationRequests.delete(options.sessionId);
2121
+ this.#touchSession(options.sessionId);
2122
+ this.#notifyProcessCapacityChanged();
1758
2123
  }
1759
2124
  }
1760
2125
  };
@@ -1773,11 +2138,12 @@ export class AcpSessionManager {
1773
2138
  await runtime.respondElicitation(options);
1774
2139
  };
1775
2140
  close = async () => {
1776
- const sessions = [...this.#sessions.values()];
1777
- const nativeBrowserSessions = [...this.#nativeBrowserSessions.values()];
1778
- this.#sessions.clear();
1779
- this.#nativeBrowserSessions.clear();
1780
- await Promise.all([...sessions, ...nativeBrowserSessions].map(async (session) => await session.close()));
2141
+ const sessions = [...this.#sessions.entries()];
2142
+ const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
2143
+ await Promise.all([
2144
+ ...sessions.map(async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())),
2145
+ ...nativeBrowserSessions.map(async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())),
2146
+ ]);
1781
2147
  };
1782
2148
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
1783
2149
  ensureSession = async (options) => {
@@ -1786,6 +2152,7 @@ export class AcpSessionManager {
1786
2152
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1787
2153
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
1788
2154
  }
2155
+ this.#touchExpectedSession(options.sessionId, existing);
1789
2156
  return existing;
1790
2157
  }
1791
2158
  await this.prepareSession(options);
@@ -1801,6 +2168,7 @@ export class AcpSessionManager {
1801
2168
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1802
2169
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
1803
2170
  }
2171
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
1804
2172
  return existing;
1805
2173
  }
1806
2174
  await this.prepareNativeSessionBrowser(options);
@@ -1810,7 +2178,15 @@ export class AcpSessionManager {
1810
2178
  }
1811
2179
  return started;
1812
2180
  }
1813
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
2181
+ listNativeSessions = async (options, cursor) => {
2182
+ this.#beginNativeBrowserUse(options.sessionId);
2183
+ try {
2184
+ return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
2185
+ }
2186
+ finally {
2187
+ this.#endNativeBrowserUse(options.sessionId);
2188
+ }
2189
+ };
1814
2190
  previewNativeSession = async (options, nativeSessionId) => {
1815
2191
  const key = `${options.agent.id}:${nativeSessionId}`;
1816
2192
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
@@ -1820,14 +2196,10 @@ export class AcpSessionManager {
1820
2196
  }
1821
2197
  this.#nativeOperations.add(key);
1822
2198
  try {
1823
- const runtime = await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, new MemoryAcpSessionStore());
1824
- try {
2199
+ return await this.#runWithTransientProcess(options.signal, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, new MemoryAcpSessionStore()), async (runtime) => {
1825
2200
  runtime.selectNativeSession(nativeSessionId);
1826
2201
  return await runtime.loadHistory(options.signal);
1827
- }
1828
- finally {
1829
- await runtime.closeProcess();
1830
- }
2202
+ }, async (runtime) => await runtime.closeProcess());
1831
2203
  }
1832
2204
  finally {
1833
2205
  this.#nativeOperations.delete(key);
@@ -1844,29 +2216,35 @@ export class AcpSessionManager {
1844
2216
  }
1845
2217
  const existing = linked[0];
1846
2218
  if (origin.kind === "import" && existing !== undefined) {
1847
- const runtime = await this.ensureSession({
1848
- ...options,
1849
- sessionId: existing.sessionId,
1850
- });
1851
- if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
1852
- throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
1853
- }
1854
- this.#nativeOperations.add(key);
2219
+ this.#beginSessionUse(existing.sessionId);
1855
2220
  try {
1856
- const history = await runtime.loadHistory(options.signal);
1857
- return {
1858
- prepared: runtime.prepared(),
2221
+ const runtime = await this.ensureSession({
2222
+ ...options,
1859
2223
  sessionId: existing.sessionId,
1860
- history,
1861
- };
1862
- }
1863
- catch (error) {
1864
- this.#sessions.delete(existing.sessionId);
1865
- await runtime.closeProcess();
1866
- throw error;
2224
+ });
2225
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
2226
+ throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
2227
+ }
2228
+ this.#nativeOperations.add(key);
2229
+ try {
2230
+ const history = await runtime.loadHistory(options.signal);
2231
+ return {
2232
+ prepared: runtime.prepared(),
2233
+ sessionId: existing.sessionId,
2234
+ history,
2235
+ };
2236
+ }
2237
+ catch (error) {
2238
+ await this.#retireSessionProcess(existing.sessionId, runtime, async () => await runtime.closeProcess());
2239
+ throw error;
2240
+ }
2241
+ finally {
2242
+ this.#nativeOperations.delete(key);
2243
+ this.#notifyProcessCapacityChanged();
2244
+ }
1867
2245
  }
1868
2246
  finally {
1869
- this.#nativeOperations.delete(key);
2247
+ this.#endSessionUse(existing.sessionId);
1870
2248
  }
1871
2249
  }
1872
2250
  if (this.#sessions.has(options.sessionId) ||
@@ -1875,6 +2253,7 @@ export class AcpSessionManager {
1875
2253
  this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
1876
2254
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
1877
2255
  }
2256
+ this.#beginSessionUse(options.sessionId);
1878
2257
  this.#nativeOperations.add(key);
1879
2258
  try {
1880
2259
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -1889,26 +2268,26 @@ export class AcpSessionManager {
1889
2268
  };
1890
2269
  }
1891
2270
  catch (error) {
1892
- this.#sessions.delete(options.sessionId);
1893
2271
  this.#store.remove(options.sessionId);
1894
- await runtime.closeProcess();
2272
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
1895
2273
  throw error;
1896
2274
  }
1897
2275
  finally {
1898
2276
  this.#nativeOperations.delete(openedKey);
2277
+ this.#notifyProcessCapacityChanged();
1899
2278
  }
1900
2279
  }
1901
2280
  catch (error) {
1902
2281
  this.#store.remove(options.sessionId);
1903
2282
  const runtime = this.#sessions.get(options.sessionId);
1904
- this.#sessions.delete(options.sessionId);
1905
2283
  if (runtime !== undefined) {
1906
- await runtime.closeProcess();
2284
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
1907
2285
  }
1908
2286
  throw error;
1909
2287
  }
1910
2288
  finally {
1911
2289
  this.#nativeOperations.delete(key);
2290
+ this.#endSessionUse(options.sessionId);
1912
2291
  }
1913
2292
  };
1914
2293
  forkSessionAtTurn = async (options, sourceSessionId, forkPoint) => {
@@ -1936,6 +2315,7 @@ export class AcpSessionManager {
1936
2315
  this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
1937
2316
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
1938
2317
  }
2318
+ this.#beginSessionUse(options.sessionId);
1939
2319
  this.#nativeOperations.add(key);
1940
2320
  try {
1941
2321
  const runtime = await this.#startSessionForkAtTurnPreparation(options, source.session.nativeSessionId, forkPoint);
@@ -1949,48 +2329,53 @@ export class AcpSessionManager {
1949
2329
  };
1950
2330
  }
1951
2331
  catch (error) {
1952
- this.#sessions.delete(options.sessionId);
1953
2332
  this.#store.remove(options.sessionId);
1954
- await runtime.closeProcess();
2333
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
1955
2334
  throw error;
1956
2335
  }
1957
2336
  finally {
1958
2337
  this.#nativeOperations.delete(openedKey);
2338
+ this.#notifyProcessCapacityChanged();
1959
2339
  }
1960
2340
  }
1961
2341
  finally {
1962
2342
  this.#nativeOperations.delete(key);
2343
+ this.#endSessionUse(options.sessionId);
1963
2344
  }
1964
2345
  };
1965
2346
  deleteNativeSession = async (options, nativeSessionId) => {
1966
- const runtime = await this.#ensureNativeSessionBrowser(options);
1967
- const key = `${options.agent.id}:${nativeSessionId}`;
1968
- const linked = this.#store.findNative(options.agent.id, nativeSessionId);
1969
- if (this.#nativeOperations.has(key) ||
1970
- linked.some((entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
1971
- throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
1972
- }
1973
- this.#nativeOperations.add(key);
2347
+ this.#beginNativeBrowserUse(options.sessionId);
1974
2348
  try {
1975
- for (const entry of linked) {
1976
- const active = this.#sessions.get(entry.sessionId);
1977
- if (active !== undefined && active !== runtime) {
1978
- this.#sessions.delete(entry.sessionId);
1979
- await active.close();
2349
+ const runtime = await this.#ensureNativeSessionBrowser(options);
2350
+ const key = `${options.agent.id}:${nativeSessionId}`;
2351
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
2352
+ if (this.#nativeOperations.has(key) ||
2353
+ linked.some((entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
2354
+ throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
2355
+ }
2356
+ this.#nativeOperations.add(key);
2357
+ try {
2358
+ for (const entry of linked) {
2359
+ const active = this.#sessions.get(entry.sessionId);
2360
+ if (active !== undefined && active !== runtime) {
2361
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
2362
+ }
2363
+ }
2364
+ options.signal.throwIfAborted();
2365
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
2366
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
2367
+ if (runtime.nativeSessionId() === nativeSessionId) {
2368
+ await this.#retireNativeBrowserProcess(options.sessionId, runtime, async () => await runtime.close());
1980
2369
  }
2370
+ return deleted;
1981
2371
  }
1982
- options.signal.throwIfAborted();
1983
- await runtime.deleteNativeSession(nativeSessionId, options.signal);
1984
- const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
1985
- if (runtime.nativeSessionId() === nativeSessionId) {
1986
- this.#nativeBrowserSessions.delete(options.sessionId);
1987
- this.#nativeBrowserStore.remove(options.sessionId);
1988
- await runtime.close();
2372
+ finally {
2373
+ this.#nativeOperations.delete(key);
2374
+ this.#notifyProcessCapacityChanged();
1989
2375
  }
1990
- return deleted;
1991
2376
  }
1992
2377
  finally {
1993
- this.#nativeOperations.delete(key);
2378
+ this.#endNativeBrowserUse(options.sessionId);
1994
2379
  }
1995
2380
  };
1996
2381
  }