@moxt-ai/mobius 0.0.40 → 0.0.41

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.
@@ -15,6 +15,7 @@ import { sessionConfigProtocolForAgent } from "./session-config/session-config-r
15
15
  import { AcpHistoryReplay } from "./session-history.js";
16
16
  import { AcpStoredSession, DeletedAcpStoredSession, FoundAcpStoredSession, MemoryAcpSessionStore, } from "./session-store.js";
17
17
  const PROCESS_STOP_TIMEOUT_MILLISECONDS = 1_000;
18
+ const MAX_ACP_PROCESSES = 10;
18
19
  const MAX_PRE_SESSION_UPDATES = 100;
19
20
  const MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
20
21
  const SESSION_CONTROL_COMMAND_ID = "session-control";
@@ -73,6 +74,95 @@ class RetryableAcpInitializationError extends AcpExecutionError {
73
74
  this.name = "RetryableAcpInitializationError";
74
75
  }
75
76
  }
77
+ class AcpProcessCapacityLease {
78
+ #releaseCapacity;
79
+ #released = false;
80
+ constructor(releaseCapacity) {
81
+ this.#releaseCapacity = releaseCapacity;
82
+ }
83
+ release = () => {
84
+ if (this.#released) {
85
+ return;
86
+ }
87
+ this.#released = true;
88
+ this.#releaseCapacity();
89
+ };
90
+ }
91
+ class AcpProcessCapacityWaiter {
92
+ completion = Promise.withResolvers();
93
+ signal;
94
+ constructor(signal) {
95
+ this.signal = signal;
96
+ }
97
+ cancel = () => {
98
+ try {
99
+ this.signal.throwIfAborted();
100
+ }
101
+ catch (error) {
102
+ this.completion.reject(error);
103
+ }
104
+ };
105
+ }
106
+ class AcpProcessCapacityLock {
107
+ #locked = false;
108
+ #waiters = [];
109
+ acquire = async (signal) => {
110
+ signal.throwIfAborted();
111
+ if (!this.#locked) {
112
+ this.#locked = true;
113
+ return new AcpProcessCapacityLease(this.#release);
114
+ }
115
+ const waiter = new AcpProcessCapacityWaiter(signal);
116
+ this.#waiters.push(waiter);
117
+ signal.addEventListener("abort", waiter.cancel, { once: true });
118
+ if (signal.aborted) {
119
+ waiter.cancel();
120
+ }
121
+ try {
122
+ return await waiter.completion.promise;
123
+ }
124
+ finally {
125
+ signal.removeEventListener("abort", waiter.cancel);
126
+ const index = this.#waiters.indexOf(waiter);
127
+ if (index >= 0) {
128
+ this.#waiters.splice(index, 1);
129
+ }
130
+ }
131
+ };
132
+ #release = () => {
133
+ while (this.#waiters.length > 0) {
134
+ const waiter = this.#waiters.shift();
135
+ if (waiter === undefined || waiter.signal.aborted) {
136
+ continue;
137
+ }
138
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
139
+ return;
140
+ }
141
+ this.#locked = false;
142
+ };
143
+ }
144
+ async function waitForAcpProcessCapacity(completion, signal) {
145
+ signal.throwIfAborted();
146
+ const cancelled = Promise.withResolvers();
147
+ const cancel = () => {
148
+ try {
149
+ signal.throwIfAborted();
150
+ }
151
+ catch (error) {
152
+ cancelled.reject(error);
153
+ }
154
+ };
155
+ signal.addEventListener("abort", cancel, { once: true });
156
+ if (signal.aborted) {
157
+ cancel();
158
+ }
159
+ try {
160
+ await Promise.race([completion, cancelled.promise]);
161
+ }
162
+ finally {
163
+ signal.removeEventListener("abort", cancel);
164
+ }
165
+ }
76
166
  function readableWebStream(input) {
77
167
  let streamOpen = true;
78
168
  return new ReadableStream({
@@ -1238,18 +1328,22 @@ class AcpProcessSession {
1238
1328
  }
1239
1329
  };
1240
1330
  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.
1331
+ try {
1332
+ await this.cancelPendingInteractions();
1333
+ if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
1334
+ try {
1335
+ await this.#connection.agent.request(methods.agent.session.close, { sessionId: this.#nativeSessionId }, {
1336
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS),
1337
+ });
1338
+ }
1339
+ catch {
1340
+ // Process teardown below remains authoritative.
1341
+ }
1250
1342
  }
1251
1343
  }
1252
- await this.closeProcess();
1344
+ finally {
1345
+ await this.closeProcess();
1346
+ }
1253
1347
  };
1254
1348
  closeProcess = async (capturedProcesses = []) => {
1255
1349
  try {
@@ -1354,6 +1448,31 @@ class AcpProcessSession {
1354
1448
  }
1355
1449
  };
1356
1450
  }
1451
+ class AcpProcessEvictionCandidate {
1452
+ }
1453
+ class MissingAcpProcessEvictionCandidate extends AcpProcessEvictionCandidate {
1454
+ }
1455
+ class FoundAcpProcessEvictionCandidate extends AcpProcessEvictionCandidate {
1456
+ runtime;
1457
+ constructor(runtime) {
1458
+ super();
1459
+ this.runtime = runtime;
1460
+ }
1461
+ }
1462
+ class FoundAcpSessionProcessEvictionCandidate extends FoundAcpProcessEvictionCandidate {
1463
+ sessionId;
1464
+ constructor(sessionId, runtime) {
1465
+ super(runtime);
1466
+ this.sessionId = sessionId;
1467
+ }
1468
+ }
1469
+ class FoundAcpNativeBrowserProcessEvictionCandidate extends FoundAcpProcessEvictionCandidate {
1470
+ sessionId;
1471
+ constructor(sessionId, runtime) {
1472
+ super(runtime);
1473
+ this.sessionId = sessionId;
1474
+ }
1475
+ }
1357
1476
  export class AcpSessionManager {
1358
1477
  #activeCommandIds = new Map();
1359
1478
  #agentSettingsObserver = new NullAcpSessionObserver();
@@ -1362,10 +1481,18 @@ export class AcpSessionManager {
1362
1481
  #nativeBrowserPreparing = new Map();
1363
1482
  #nativeBrowserSessions = new Map();
1364
1483
  #nativeBrowserStore = new MemoryAcpSessionStore();
1484
+ #nativeBrowserUseCounts = new Map();
1365
1485
  #activeSessionIds = new Set();
1366
1486
  #cancellationRequests = new Map();
1367
1487
  #preparing = new Map();
1488
+ #processCapacityChanged = Promise.withResolvers();
1489
+ #processCapacityLock = new AcpProcessCapacityLock();
1490
+ #retainedProcesses = new Map();
1491
+ #retiringProcessCount = 0;
1492
+ #sessionUseCounts = new Map();
1368
1493
  #sessions = new Map();
1494
+ #startingProcessCount = 0;
1495
+ #transientProcessCount = 0;
1369
1496
  #store;
1370
1497
  #observer;
1371
1498
  constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore()) {
@@ -1375,15 +1502,229 @@ export class AcpSessionManager {
1375
1502
  setObserver = (observer) => {
1376
1503
  this.#observer = observer;
1377
1504
  };
1505
+ #notifyProcessCapacityChanged() {
1506
+ const changed = this.#processCapacityChanged;
1507
+ this.#processCapacityChanged = Promise.withResolvers();
1508
+ changed.resolve();
1509
+ }
1510
+ #touchSession(sessionId) {
1511
+ const runtime = this.#sessions.get(sessionId);
1512
+ if (runtime === undefined) {
1513
+ return;
1514
+ }
1515
+ this.#touchProcess(runtime);
1516
+ }
1517
+ #touchExpectedSession(sessionId, expected) {
1518
+ if (this.#sessions.get(sessionId) !== expected) {
1519
+ return;
1520
+ }
1521
+ this.#touchProcess(expected);
1522
+ }
1523
+ #touchNativeBrowserSession(sessionId) {
1524
+ const runtime = this.#nativeBrowserSessions.get(sessionId);
1525
+ if (runtime === undefined) {
1526
+ return;
1527
+ }
1528
+ this.#touchProcess(runtime);
1529
+ }
1530
+ #touchExpectedNativeBrowserSession(sessionId, expected) {
1531
+ if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
1532
+ return;
1533
+ }
1534
+ this.#touchProcess(expected);
1535
+ }
1536
+ #touchProcess(runtime) {
1537
+ const retained = this.#retainedProcesses.get(runtime);
1538
+ if (retained === undefined) {
1539
+ return;
1540
+ }
1541
+ this.#retainedProcesses.delete(runtime);
1542
+ this.#retainedProcesses.set(runtime, retained);
1543
+ }
1544
+ #beginSessionUse(sessionId) {
1545
+ this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
1546
+ this.#touchSession(sessionId);
1547
+ }
1548
+ #endSessionUse(sessionId) {
1549
+ const count = this.#sessionUseCounts.get(sessionId) ?? 0;
1550
+ if (count <= 1) {
1551
+ this.#sessionUseCounts.delete(sessionId);
1552
+ }
1553
+ else {
1554
+ this.#sessionUseCounts.set(sessionId, count - 1);
1555
+ }
1556
+ this.#touchSession(sessionId);
1557
+ this.#notifyProcessCapacityChanged();
1558
+ }
1559
+ #beginNativeBrowserUse(sessionId) {
1560
+ this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
1561
+ this.#touchNativeBrowserSession(sessionId);
1562
+ }
1563
+ #endNativeBrowserUse(sessionId) {
1564
+ const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
1565
+ if (count <= 1) {
1566
+ this.#nativeBrowserUseCounts.delete(sessionId);
1567
+ }
1568
+ else {
1569
+ this.#nativeBrowserUseCounts.set(sessionId, count - 1);
1570
+ }
1571
+ this.#touchNativeBrowserSession(sessionId);
1572
+ this.#notifyProcessCapacityChanged();
1573
+ }
1574
+ #isNativeSessionOperationActive(sessionId) {
1575
+ const stored = this.#store.read(sessionId);
1576
+ return (stored instanceof FoundAcpStoredSession &&
1577
+ this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`));
1578
+ }
1579
+ #leastRecentlyUsedEvictionCandidate() {
1580
+ for (const candidate of this.#retainedProcesses.values()) {
1581
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
1582
+ if (this.#activeSessionIds.has(candidate.sessionId) ||
1583
+ this.#cancellationRequests.has(candidate.sessionId) ||
1584
+ this.#preparing.has(candidate.sessionId) ||
1585
+ (this.#sessionUseCounts.get(candidate.sessionId) ?? 0) > 0 ||
1586
+ this.#isNativeSessionOperationActive(candidate.sessionId)) {
1587
+ continue;
1588
+ }
1589
+ return candidate;
1590
+ }
1591
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate &&
1592
+ !this.#nativeBrowserPreparing.has(candidate.sessionId) &&
1593
+ (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
1594
+ return candidate;
1595
+ }
1596
+ }
1597
+ return new MissingAcpProcessEvictionCandidate();
1598
+ }
1599
+ #ownedProcessCount() {
1600
+ return (this.#retainedProcesses.size +
1601
+ this.#startingProcessCount +
1602
+ this.#transientProcessCount +
1603
+ this.#retiringProcessCount);
1604
+ }
1605
+ async #retireProcess(runtime, retained, close) {
1606
+ if (retained) {
1607
+ this.#retainedProcesses.delete(runtime);
1608
+ this.#retiringProcessCount += 1;
1609
+ }
1610
+ try {
1611
+ await close();
1612
+ }
1613
+ finally {
1614
+ if (retained) {
1615
+ this.#retiringProcessCount -= 1;
1616
+ this.#notifyProcessCapacityChanged();
1617
+ }
1618
+ }
1619
+ }
1620
+ async #retireSessionProcess(sessionId, runtime, close) {
1621
+ const retained = this.#sessions.get(sessionId) === runtime;
1622
+ if (retained) {
1623
+ this.#sessions.delete(sessionId);
1624
+ }
1625
+ await this.#retireProcess(runtime, retained, close);
1626
+ }
1627
+ async #retireNativeBrowserProcess(sessionId, runtime, close) {
1628
+ const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
1629
+ if (retained) {
1630
+ this.#nativeBrowserSessions.delete(sessionId);
1631
+ this.#nativeBrowserStore.remove(sessionId);
1632
+ }
1633
+ await this.#retireProcess(runtime, retained, close);
1634
+ }
1635
+ async #reserveProcessCapacity(signal) {
1636
+ const lease = await this.#processCapacityLock.acquire(signal);
1637
+ try {
1638
+ for (;;) {
1639
+ signal.throwIfAborted();
1640
+ if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
1641
+ this.#startingProcessCount += 1;
1642
+ return;
1643
+ }
1644
+ const candidate = this.#leastRecentlyUsedEvictionCandidate();
1645
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
1646
+ await this.#retireSessionProcess(candidate.sessionId, candidate.runtime, async () => await candidate.runtime.close());
1647
+ continue;
1648
+ }
1649
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
1650
+ await this.#retireNativeBrowserProcess(candidate.sessionId, candidate.runtime, async () => await candidate.runtime.close());
1651
+ continue;
1652
+ }
1653
+ const changed = this.#processCapacityChanged.promise;
1654
+ await waitForAcpProcessCapacity(changed, signal);
1655
+ }
1656
+ }
1657
+ finally {
1658
+ lease.release();
1659
+ }
1660
+ }
1661
+ async #startRetainedSessionProcess(options, start) {
1662
+ await this.#reserveProcessCapacity(options.signal);
1663
+ try {
1664
+ const runtime = await start();
1665
+ this.#startingProcessCount -= 1;
1666
+ this.#sessions.set(options.sessionId, runtime);
1667
+ this.#retainedProcesses.set(runtime, new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime));
1668
+ this.#notifyProcessCapacityChanged();
1669
+ return runtime;
1670
+ }
1671
+ catch (error) {
1672
+ this.#startingProcessCount -= 1;
1673
+ this.#notifyProcessCapacityChanged();
1674
+ throw error;
1675
+ }
1676
+ }
1677
+ async #startRetainedNativeBrowserProcess(options, start) {
1678
+ await this.#reserveProcessCapacity(options.signal);
1679
+ try {
1680
+ const runtime = await start();
1681
+ this.#startingProcessCount -= 1;
1682
+ this.#nativeBrowserSessions.set(options.sessionId, runtime);
1683
+ this.#retainedProcesses.set(runtime, new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime));
1684
+ this.#notifyProcessCapacityChanged();
1685
+ return runtime;
1686
+ }
1687
+ catch (error) {
1688
+ this.#startingProcessCount -= 1;
1689
+ this.#notifyProcessCapacityChanged();
1690
+ throw error;
1691
+ }
1692
+ }
1693
+ async #runWithTransientProcess(signal, start, operation, close) {
1694
+ await this.#reserveProcessCapacity(signal);
1695
+ let runtime;
1696
+ try {
1697
+ runtime = await start();
1698
+ }
1699
+ catch (error) {
1700
+ this.#startingProcessCount -= 1;
1701
+ this.#notifyProcessCapacityChanged();
1702
+ throw error;
1703
+ }
1704
+ this.#startingProcessCount -= 1;
1705
+ this.#transientProcessCount += 1;
1706
+ this.#notifyProcessCapacityChanged();
1707
+ try {
1708
+ return await operation(runtime);
1709
+ }
1710
+ finally {
1711
+ try {
1712
+ await close(runtime);
1713
+ }
1714
+ finally {
1715
+ this.#transientProcessCount -= 1;
1716
+ this.#notifyProcessCapacityChanged();
1717
+ }
1718
+ }
1719
+ }
1378
1720
  async #startNativeBrowserPreparation(options) {
1379
1721
  const operation = (async () => {
1380
1722
  try {
1381
- const runtime = await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore);
1382
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
1383
- return runtime;
1723
+ return await this.#startRetainedNativeBrowserProcess(options, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore));
1384
1724
  }
1385
1725
  finally {
1386
1726
  this.#nativeBrowserPreparing.delete(options.sessionId);
1727
+ this.#notifyProcessCapacityChanged();
1387
1728
  }
1388
1729
  })();
1389
1730
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -1392,15 +1733,12 @@ export class AcpSessionManager {
1392
1733
  async #replaceNativeBrowserPreparation(existing, options) {
1393
1734
  const operation = (async () => {
1394
1735
  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;
1736
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
1737
+ return await this.#startRetainedNativeBrowserProcess(options, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, this.#nativeBrowserStore));
1401
1738
  }
1402
1739
  finally {
1403
1740
  this.#nativeBrowserPreparing.delete(options.sessionId);
1741
+ this.#notifyProcessCapacityChanged();
1404
1742
  }
1405
1743
  })();
1406
1744
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -1409,12 +1747,11 @@ export class AcpSessionManager {
1409
1747
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
1410
1748
  const operation = (async () => {
1411
1749
  try {
1412
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
1413
- this.#sessions.set(options.sessionId, runtime);
1414
- return runtime;
1750
+ return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics));
1415
1751
  }
1416
1752
  finally {
1417
1753
  this.#preparing.delete(options.sessionId);
1754
+ this.#notifyProcessCapacityChanged();
1418
1755
  }
1419
1756
  })();
1420
1757
  this.#preparing.set(options.sessionId, operation);
@@ -1423,12 +1760,11 @@ export class AcpSessionManager {
1423
1760
  async #startSessionForkAtTurnPreparation(options, sourceNativeSessionId, forkPoint) {
1424
1761
  const operation = (async () => {
1425
1762
  try {
1426
- const runtime = await AcpProcessSession.startSessionForkAtTurn(options, sourceNativeSessionId, forkPoint, () => this.#observer, this.#store);
1427
- this.#sessions.set(options.sessionId, runtime);
1428
- return runtime;
1763
+ return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.startSessionForkAtTurn(options, sourceNativeSessionId, forkPoint, () => this.#observer, this.#store));
1429
1764
  }
1430
1765
  finally {
1431
1766
  this.#preparing.delete(options.sessionId);
1767
+ this.#notifyProcessCapacityChanged();
1432
1768
  }
1433
1769
  })();
1434
1770
  this.#preparing.set(options.sessionId, operation);
@@ -1437,15 +1773,13 @@ export class AcpSessionManager {
1437
1773
  async #replacePreparation(existing, options, metrics) {
1438
1774
  const operation = (async () => {
1439
1775
  try {
1440
- this.#sessions.delete(options.sessionId);
1441
- await metrics.measure("runtime-replacement-close", async () => await existing.close());
1776
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await metrics.measure("runtime-replacement-close", async () => await existing.close()));
1442
1777
  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;
1778
+ return await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics));
1446
1779
  }
1447
1780
  finally {
1448
1781
  this.#preparing.delete(options.sessionId);
1782
+ this.#notifyProcessCapacityChanged();
1449
1783
  }
1450
1784
  })();
1451
1785
  this.#preparing.set(options.sessionId, operation);
@@ -1455,10 +1789,9 @@ export class AcpSessionManager {
1455
1789
  const desiredConfigOptions = existing.prepared().configOptions;
1456
1790
  const operation = (async () => {
1457
1791
  try {
1458
- this.#sessions.delete(options.sessionId);
1459
- await existing.close();
1792
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
1460
1793
  this.#store.remove(options.sessionId);
1461
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
1794
+ const runtime = await this.#startRetainedSessionProcess(options, async () => await AcpProcessSession.start(options, () => this.#observer, this.#store));
1462
1795
  try {
1463
1796
  for (const desired of desiredConfigOptions) {
1464
1797
  const current = runtime.prepared().configOptions.find((option) => option.id === desired.id);
@@ -1492,15 +1825,15 @@ export class AcpSessionManager {
1492
1825
  }
1493
1826
  }
1494
1827
  catch (error) {
1495
- await runtime.close();
1828
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
1496
1829
  this.#store.remove(options.sessionId);
1497
1830
  throw error;
1498
1831
  }
1499
- this.#sessions.set(options.sessionId, runtime);
1500
1832
  return runtime;
1501
1833
  }
1502
1834
  finally {
1503
1835
  this.#preparing.delete(options.sessionId);
1836
+ this.#notifyProcessCapacityChanged();
1504
1837
  }
1505
1838
  })();
1506
1839
  this.#preparing.set(options.sessionId, operation);
@@ -1519,6 +1852,7 @@ export class AcpSessionManager {
1519
1852
  if (pending !== undefined) {
1520
1853
  const runtime = await metrics.measure("session-preparation-wait", async () => await pending);
1521
1854
  if (runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1855
+ this.#touchExpectedSession(options.sessionId, runtime);
1522
1856
  return runtime.prepared();
1523
1857
  }
1524
1858
  return await this.prepareSession(options, metrics);
@@ -1526,6 +1860,7 @@ export class AcpSessionManager {
1526
1860
  const existing = this.#sessions.get(options.sessionId);
1527
1861
  if (existing !== undefined) {
1528
1862
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1863
+ this.#touchExpectedSession(options.sessionId, existing);
1529
1864
  return existing.prepared();
1530
1865
  }
1531
1866
  if (!existing.canRebind()) {
@@ -1542,19 +1877,13 @@ export class AcpSessionManager {
1542
1877
  * authoritative settings. Its identity and store are private to this
1543
1878
  * operation and never become a Mobius Session.
1544
1879
  */
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
- };
1880
+ inspectAgentSettings = async (options) => await this.#runWithTransientProcess(options.signal, async () => await AcpProcessSession.start({
1881
+ ...options,
1882
+ sessionId: `agent-settings-${crypto.randomUUID()}`,
1883
+ }, () => this.#agentSettingsObserver, new MemoryAcpSessionStore()), (runtime) => {
1884
+ const prepared = runtime.prepared();
1885
+ return Promise.resolve(new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions));
1886
+ }, async (runtime) => await runtime.close());
1558
1887
  /**
1559
1888
  * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
1560
1889
  * Use inspectAgentSettings for Agent-scoped settings discovery.
@@ -1563,21 +1892,24 @@ export class AcpSessionManager {
1563
1892
  if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
1564
1893
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
1565
1894
  }
1566
- const runtime = await this.#startPreparation(options, metrics);
1895
+ this.#beginSessionUse(options.sessionId);
1567
1896
  try {
1568
- return runtime.prepared();
1569
- }
1570
- finally {
1571
- if (this.#sessions.get(options.sessionId) === runtime) {
1572
- this.#sessions.delete(options.sessionId);
1573
- }
1897
+ const runtime = await this.#startPreparation(options, metrics);
1574
1898
  try {
1575
- await runtime.close();
1899
+ return runtime.prepared();
1576
1900
  }
1577
1901
  finally {
1578
- this.#store.remove(options.sessionId);
1902
+ try {
1903
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
1904
+ }
1905
+ finally {
1906
+ this.#store.remove(options.sessionId);
1907
+ }
1579
1908
  }
1580
1909
  }
1910
+ finally {
1911
+ this.#endSessionUse(options.sessionId);
1912
+ }
1581
1913
  };
1582
1914
  prepareExecutionSession = async (options) => {
1583
1915
  const pending = this.#preparing.get(options.sessionId);
@@ -1593,6 +1925,7 @@ export class AcpSessionManager {
1593
1925
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
1594
1926
  }
1595
1927
  if (existing.usesEnvironment(options.agent.environment)) {
1928
+ this.#touchExpectedSession(options.sessionId, existing);
1596
1929
  return existing.prepared();
1597
1930
  }
1598
1931
  if (!existing.canRebind()) {
@@ -1605,6 +1938,7 @@ export class AcpSessionManager {
1605
1938
  if (pending !== undefined) {
1606
1939
  const runtime = await pending;
1607
1940
  if (runtime.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1941
+ this.#touchExpectedNativeBrowserSession(options.sessionId, runtime);
1608
1942
  return runtime.prepared();
1609
1943
  }
1610
1944
  return await this.prepareNativeSessionBrowser(options);
@@ -1612,6 +1946,7 @@ export class AcpSessionManager {
1612
1946
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
1613
1947
  if (existing !== undefined) {
1614
1948
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1949
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
1615
1950
  return existing.prepared();
1616
1951
  }
1617
1952
  if (!existing.canRebind()) {
@@ -1624,8 +1959,14 @@ export class AcpSessionManager {
1624
1959
  return runtime.prepared();
1625
1960
  };
1626
1961
  configureSession = async (options) => {
1627
- const runtime = await this.ensureSession(options);
1628
- return await runtime.configure(options);
1962
+ this.#beginSessionUse(options.sessionId);
1963
+ try {
1964
+ const runtime = await this.ensureSession(options);
1965
+ return await runtime.configure(options);
1966
+ }
1967
+ finally {
1968
+ this.#endSessionUse(options.sessionId);
1969
+ }
1629
1970
  };
1630
1971
  cancelPrompt = async (sessionId) => {
1631
1972
  const existing = this.#cancellationRequests.get(sessionId);
@@ -1642,6 +1983,8 @@ export class AcpSessionManager {
1642
1983
  finally {
1643
1984
  if (this.#sessions.get(sessionId) === runtime) {
1644
1985
  this.#sessions.delete(sessionId);
1986
+ this.#retainedProcesses.delete(runtime);
1987
+ this.#notifyProcessCapacityChanged();
1645
1988
  }
1646
1989
  }
1647
1990
  }
@@ -1719,10 +2062,7 @@ export class AcpSessionManager {
1719
2062
  }
1720
2063
  catch (error) {
1721
2064
  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();
2065
+ await this.#cancellationRequests.get(options.sessionId);
1726
2066
  return { stopReason: "cancelled" };
1727
2067
  }
1728
2068
  throw error;
@@ -1731,8 +2071,7 @@ export class AcpSessionManager {
1731
2071
  catch (error) {
1732
2072
  const failedRuntime = this.#sessions.get(options.sessionId);
1733
2073
  if (failedRuntime !== undefined) {
1734
- this.#sessions.delete(options.sessionId);
1735
- await failedRuntime.close();
2074
+ await this.#retireSessionProcess(options.sessionId, failedRuntime, async () => await failedRuntime.close());
1736
2075
  }
1737
2076
  if (this.#cancellationRequests.has(options.sessionId)) {
1738
2077
  return { stopReason: "cancelled" };
@@ -1755,6 +2094,8 @@ export class AcpSessionManager {
1755
2094
  this.#activeCommandIds.delete(options.sessionId);
1756
2095
  }
1757
2096
  this.#cancellationRequests.delete(options.sessionId);
2097
+ this.#touchSession(options.sessionId);
2098
+ this.#notifyProcessCapacityChanged();
1758
2099
  }
1759
2100
  }
1760
2101
  };
@@ -1773,11 +2114,12 @@ export class AcpSessionManager {
1773
2114
  await runtime.respondElicitation(options);
1774
2115
  };
1775
2116
  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()));
2117
+ const sessions = [...this.#sessions.entries()];
2118
+ const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
2119
+ await Promise.all([
2120
+ ...sessions.map(async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())),
2121
+ ...nativeBrowserSessions.map(async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())),
2122
+ ]);
1781
2123
  };
1782
2124
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
1783
2125
  ensureSession = async (options) => {
@@ -1786,6 +2128,7 @@ export class AcpSessionManager {
1786
2128
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1787
2129
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
1788
2130
  }
2131
+ this.#touchExpectedSession(options.sessionId, existing);
1789
2132
  return existing;
1790
2133
  }
1791
2134
  await this.prepareSession(options);
@@ -1801,6 +2144,7 @@ export class AcpSessionManager {
1801
2144
  if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
1802
2145
  throw new AcpExecutionError("The agent or workspace cannot change after a conversation has started", {}, "session_identity_mismatch");
1803
2146
  }
2147
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
1804
2148
  return existing;
1805
2149
  }
1806
2150
  await this.prepareNativeSessionBrowser(options);
@@ -1810,7 +2154,15 @@ export class AcpSessionManager {
1810
2154
  }
1811
2155
  return started;
1812
2156
  }
1813
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
2157
+ listNativeSessions = async (options, cursor) => {
2158
+ this.#beginNativeBrowserUse(options.sessionId);
2159
+ try {
2160
+ return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
2161
+ }
2162
+ finally {
2163
+ this.#endNativeBrowserUse(options.sessionId);
2164
+ }
2165
+ };
1814
2166
  previewNativeSession = async (options, nativeSessionId) => {
1815
2167
  const key = `${options.agent.id}:${nativeSessionId}`;
1816
2168
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
@@ -1820,14 +2172,10 @@ export class AcpSessionManager {
1820
2172
  }
1821
2173
  this.#nativeOperations.add(key);
1822
2174
  try {
1823
- const runtime = await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, new MemoryAcpSessionStore());
1824
- try {
2175
+ return await this.#runWithTransientProcess(options.signal, async () => await AcpProcessSession.startNativeSessionBrowser(options, () => this.#nativeBrowserObserver, new MemoryAcpSessionStore()), async (runtime) => {
1825
2176
  runtime.selectNativeSession(nativeSessionId);
1826
2177
  return await runtime.loadHistory(options.signal);
1827
- }
1828
- finally {
1829
- await runtime.closeProcess();
1830
- }
2178
+ }, async (runtime) => await runtime.closeProcess());
1831
2179
  }
1832
2180
  finally {
1833
2181
  this.#nativeOperations.delete(key);
@@ -1844,29 +2192,35 @@ export class AcpSessionManager {
1844
2192
  }
1845
2193
  const existing = linked[0];
1846
2194
  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);
2195
+ this.#beginSessionUse(existing.sessionId);
1855
2196
  try {
1856
- const history = await runtime.loadHistory(options.signal);
1857
- return {
1858
- prepared: runtime.prepared(),
2197
+ const runtime = await this.ensureSession({
2198
+ ...options,
1859
2199
  sessionId: existing.sessionId,
1860
- history,
1861
- };
1862
- }
1863
- catch (error) {
1864
- this.#sessions.delete(existing.sessionId);
1865
- await runtime.closeProcess();
1866
- throw error;
2200
+ });
2201
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
2202
+ throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
2203
+ }
2204
+ this.#nativeOperations.add(key);
2205
+ try {
2206
+ const history = await runtime.loadHistory(options.signal);
2207
+ return {
2208
+ prepared: runtime.prepared(),
2209
+ sessionId: existing.sessionId,
2210
+ history,
2211
+ };
2212
+ }
2213
+ catch (error) {
2214
+ await this.#retireSessionProcess(existing.sessionId, runtime, async () => await runtime.closeProcess());
2215
+ throw error;
2216
+ }
2217
+ finally {
2218
+ this.#nativeOperations.delete(key);
2219
+ this.#notifyProcessCapacityChanged();
2220
+ }
1867
2221
  }
1868
2222
  finally {
1869
- this.#nativeOperations.delete(key);
2223
+ this.#endSessionUse(existing.sessionId);
1870
2224
  }
1871
2225
  }
1872
2226
  if (this.#sessions.has(options.sessionId) ||
@@ -1875,6 +2229,7 @@ export class AcpSessionManager {
1875
2229
  this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
1876
2230
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
1877
2231
  }
2232
+ this.#beginSessionUse(options.sessionId);
1878
2233
  this.#nativeOperations.add(key);
1879
2234
  try {
1880
2235
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -1889,26 +2244,26 @@ export class AcpSessionManager {
1889
2244
  };
1890
2245
  }
1891
2246
  catch (error) {
1892
- this.#sessions.delete(options.sessionId);
1893
2247
  this.#store.remove(options.sessionId);
1894
- await runtime.closeProcess();
2248
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
1895
2249
  throw error;
1896
2250
  }
1897
2251
  finally {
1898
2252
  this.#nativeOperations.delete(openedKey);
2253
+ this.#notifyProcessCapacityChanged();
1899
2254
  }
1900
2255
  }
1901
2256
  catch (error) {
1902
2257
  this.#store.remove(options.sessionId);
1903
2258
  const runtime = this.#sessions.get(options.sessionId);
1904
- this.#sessions.delete(options.sessionId);
1905
2259
  if (runtime !== undefined) {
1906
- await runtime.closeProcess();
2260
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
1907
2261
  }
1908
2262
  throw error;
1909
2263
  }
1910
2264
  finally {
1911
2265
  this.#nativeOperations.delete(key);
2266
+ this.#endSessionUse(options.sessionId);
1912
2267
  }
1913
2268
  };
1914
2269
  forkSessionAtTurn = async (options, sourceSessionId, forkPoint) => {
@@ -1936,6 +2291,7 @@ export class AcpSessionManager {
1936
2291
  this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
1937
2292
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
1938
2293
  }
2294
+ this.#beginSessionUse(options.sessionId);
1939
2295
  this.#nativeOperations.add(key);
1940
2296
  try {
1941
2297
  const runtime = await this.#startSessionForkAtTurnPreparation(options, source.session.nativeSessionId, forkPoint);
@@ -1949,48 +2305,53 @@ export class AcpSessionManager {
1949
2305
  };
1950
2306
  }
1951
2307
  catch (error) {
1952
- this.#sessions.delete(options.sessionId);
1953
2308
  this.#store.remove(options.sessionId);
1954
- await runtime.closeProcess();
2309
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
1955
2310
  throw error;
1956
2311
  }
1957
2312
  finally {
1958
2313
  this.#nativeOperations.delete(openedKey);
2314
+ this.#notifyProcessCapacityChanged();
1959
2315
  }
1960
2316
  }
1961
2317
  finally {
1962
2318
  this.#nativeOperations.delete(key);
2319
+ this.#endSessionUse(options.sessionId);
1963
2320
  }
1964
2321
  };
1965
2322
  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);
2323
+ this.#beginNativeBrowserUse(options.sessionId);
1974
2324
  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();
2325
+ const runtime = await this.#ensureNativeSessionBrowser(options);
2326
+ const key = `${options.agent.id}:${nativeSessionId}`;
2327
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
2328
+ if (this.#nativeOperations.has(key) ||
2329
+ linked.some((entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
2330
+ throw new AcpExecutionError("Wait for the native session's running operation to finish", {}, "session_busy");
2331
+ }
2332
+ this.#nativeOperations.add(key);
2333
+ try {
2334
+ for (const entry of linked) {
2335
+ const active = this.#sessions.get(entry.sessionId);
2336
+ if (active !== undefined && active !== runtime) {
2337
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
2338
+ }
2339
+ }
2340
+ options.signal.throwIfAborted();
2341
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
2342
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
2343
+ if (runtime.nativeSessionId() === nativeSessionId) {
2344
+ await this.#retireNativeBrowserProcess(options.sessionId, runtime, async () => await runtime.close());
1980
2345
  }
2346
+ return deleted;
1981
2347
  }
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();
2348
+ finally {
2349
+ this.#nativeOperations.delete(key);
2350
+ this.#notifyProcessCapacityChanged();
1989
2351
  }
1990
- return deleted;
1991
2352
  }
1992
2353
  finally {
1993
- this.#nativeOperations.delete(key);
2354
+ this.#endNativeBrowserUse(options.sessionId);
1994
2355
  }
1995
2356
  };
1996
2357
  }