@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.
package/dist/index.js CHANGED
@@ -27031,7 +27031,7 @@ var titleBefore = {
27031
27031
  };
27032
27032
  function tokenizeDefinition(effects, ok2, nok) {
27033
27033
  const self = this;
27034
- let identifier3;
27034
+ let identifier2;
27035
27035
  return start;
27036
27036
  function start(code) {
27037
27037
  effects.enter("definition");
@@ -27050,7 +27050,7 @@ function tokenizeDefinition(effects, ok2, nok) {
27050
27050
  )(code);
27051
27051
  }
27052
27052
  function labelAfter(code) {
27053
- identifier3 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
27053
+ identifier2 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
27054
27054
  if (code === 58) {
27055
27055
  effects.enter("definitionMarker");
27056
27056
  effects.consume(code);
@@ -27084,7 +27084,7 @@ function tokenizeDefinition(effects, ok2, nok) {
27084
27084
  function afterWhitespace(code) {
27085
27085
  if (code === null || markdownLineEnding(code)) {
27086
27086
  effects.exit("definition");
27087
- self.parser.defined.push(identifier3);
27087
+ self.parser.defined.push(identifier2);
27088
27088
  return ok2(code);
27089
27089
  }
27090
27090
  return nok(code);
@@ -30919,6 +30919,7 @@ var SqliteAcpSessionStore = class {
30919
30919
 
30920
30920
  // src/acp/session-manager.ts
30921
30921
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
30922
+ var MAX_ACP_PROCESSES = 10;
30922
30923
  var MAX_PRE_SESSION_UPDATES = 100;
30923
30924
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
30924
30925
  var SESSION_CONTROL_COMMAND_ID = "session-control";
@@ -30977,6 +30978,91 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
30977
30978
  this.name = "RetryableAcpInitializationError";
30978
30979
  }
30979
30980
  };
30981
+ var AcpProcessCapacityLease = class {
30982
+ #releaseCapacity;
30983
+ #released = false;
30984
+ constructor(releaseCapacity) {
30985
+ this.#releaseCapacity = releaseCapacity;
30986
+ }
30987
+ release = () => {
30988
+ if (this.#released) {
30989
+ return;
30990
+ }
30991
+ this.#released = true;
30992
+ this.#releaseCapacity();
30993
+ };
30994
+ };
30995
+ var AcpProcessCapacityWaiter = class {
30996
+ completion = Promise.withResolvers();
30997
+ signal;
30998
+ constructor(signal) {
30999
+ this.signal = signal;
31000
+ }
31001
+ cancel = () => {
31002
+ try {
31003
+ this.signal.throwIfAborted();
31004
+ } catch (error62) {
31005
+ this.completion.reject(error62);
31006
+ }
31007
+ };
31008
+ };
31009
+ var AcpProcessCapacityLock = class {
31010
+ #locked = false;
31011
+ #waiters = [];
31012
+ acquire = async (signal) => {
31013
+ signal.throwIfAborted();
31014
+ if (!this.#locked) {
31015
+ this.#locked = true;
31016
+ return new AcpProcessCapacityLease(this.#release);
31017
+ }
31018
+ const waiter = new AcpProcessCapacityWaiter(signal);
31019
+ this.#waiters.push(waiter);
31020
+ signal.addEventListener("abort", waiter.cancel, { once: true });
31021
+ if (signal.aborted) {
31022
+ waiter.cancel();
31023
+ }
31024
+ try {
31025
+ return await waiter.completion.promise;
31026
+ } finally {
31027
+ signal.removeEventListener("abort", waiter.cancel);
31028
+ const index2 = this.#waiters.indexOf(waiter);
31029
+ if (index2 >= 0) {
31030
+ this.#waiters.splice(index2, 1);
31031
+ }
31032
+ }
31033
+ };
31034
+ #release = () => {
31035
+ while (this.#waiters.length > 0) {
31036
+ const waiter = this.#waiters.shift();
31037
+ if (waiter === void 0 || waiter.signal.aborted) {
31038
+ continue;
31039
+ }
31040
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
31041
+ return;
31042
+ }
31043
+ this.#locked = false;
31044
+ };
31045
+ };
31046
+ async function waitForAcpProcessCapacity(completion, signal) {
31047
+ signal.throwIfAborted();
31048
+ const cancelled = Promise.withResolvers();
31049
+ const cancel = () => {
31050
+ try {
31051
+ signal.throwIfAborted();
31052
+ } catch (error62) {
31053
+ cancelled.reject(error62);
31054
+ }
31055
+ };
31056
+ signal.addEventListener("abort", cancel, { once: true });
31057
+ if (signal.aborted) {
31058
+ cancel();
31059
+ }
31060
+ try {
31061
+ await Promise.race([completion, cancelled.promise]);
31062
+ } finally {
31063
+ signal.removeEventListener("abort", cancel);
31064
+ }
31065
+ }
30980
31066
  function readableWebStream(input2) {
30981
31067
  let streamOpen = true;
30982
31068
  return new ReadableStream({
@@ -32464,20 +32550,23 @@ var AcpProcessSession = class _AcpProcessSession {
32464
32550
  }
32465
32551
  };
32466
32552
  close = async () => {
32467
- await this.cancelPendingInteractions();
32468
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
32469
- try {
32470
- await this.#connection.agent.request(
32471
- methods3.agent.session.close,
32472
- { sessionId: this.#nativeSessionId },
32473
- {
32474
- cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
32475
- }
32476
- );
32477
- } catch {
32553
+ try {
32554
+ await this.cancelPendingInteractions();
32555
+ if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
32556
+ try {
32557
+ await this.#connection.agent.request(
32558
+ methods3.agent.session.close,
32559
+ { sessionId: this.#nativeSessionId },
32560
+ {
32561
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
32562
+ }
32563
+ );
32564
+ } catch {
32565
+ }
32478
32566
  }
32567
+ } finally {
32568
+ await this.closeProcess();
32479
32569
  }
32480
- await this.closeProcess();
32481
32570
  };
32482
32571
  closeProcess = async (capturedProcesses = []) => {
32483
32572
  try {
@@ -32584,6 +32673,31 @@ var AcpProcessSession = class _AcpProcessSession {
32584
32673
  }
32585
32674
  };
32586
32675
  };
32676
+ var AcpProcessEvictionCandidate = class {
32677
+ };
32678
+ var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
32679
+ };
32680
+ var FoundAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
32681
+ runtime;
32682
+ constructor(runtime) {
32683
+ super();
32684
+ this.runtime = runtime;
32685
+ }
32686
+ };
32687
+ var FoundAcpSessionProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
32688
+ sessionId;
32689
+ constructor(sessionId, runtime) {
32690
+ super(runtime);
32691
+ this.sessionId = sessionId;
32692
+ }
32693
+ };
32694
+ var FoundAcpNativeBrowserProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
32695
+ sessionId;
32696
+ constructor(sessionId, runtime) {
32697
+ super(runtime);
32698
+ this.sessionId = sessionId;
32699
+ }
32700
+ };
32587
32701
  var AcpSessionManager = class {
32588
32702
  #activeCommandIds = /* @__PURE__ */ new Map();
32589
32703
  #agentSettingsObserver = new NullAcpSessionObserver();
@@ -32592,10 +32706,18 @@ var AcpSessionManager = class {
32592
32706
  #nativeBrowserPreparing = /* @__PURE__ */ new Map();
32593
32707
  #nativeBrowserSessions = /* @__PURE__ */ new Map();
32594
32708
  #nativeBrowserStore = new MemoryAcpSessionStore();
32709
+ #nativeBrowserUseCounts = /* @__PURE__ */ new Map();
32595
32710
  #activeSessionIds = /* @__PURE__ */ new Set();
32596
32711
  #cancellationRequests = /* @__PURE__ */ new Map();
32597
32712
  #preparing = /* @__PURE__ */ new Map();
32713
+ #processCapacityChanged = Promise.withResolvers();
32714
+ #processCapacityLock = new AcpProcessCapacityLock();
32715
+ #retainedProcesses = /* @__PURE__ */ new Map();
32716
+ #retiringProcessCount = 0;
32717
+ #sessionUseCounts = /* @__PURE__ */ new Map();
32598
32718
  #sessions = /* @__PURE__ */ new Map();
32719
+ #startingProcessCount = 0;
32720
+ #transientProcessCount = 0;
32599
32721
  #store;
32600
32722
  #observer;
32601
32723
  constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore()) {
@@ -32605,18 +32727,230 @@ var AcpSessionManager = class {
32605
32727
  setObserver = (observer) => {
32606
32728
  this.#observer = observer;
32607
32729
  };
32730
+ #notifyProcessCapacityChanged() {
32731
+ const changed = this.#processCapacityChanged;
32732
+ this.#processCapacityChanged = Promise.withResolvers();
32733
+ changed.resolve();
32734
+ }
32735
+ #touchSession(sessionId) {
32736
+ const runtime = this.#sessions.get(sessionId);
32737
+ if (runtime === void 0) {
32738
+ return;
32739
+ }
32740
+ this.#touchProcess(runtime);
32741
+ }
32742
+ #touchExpectedSession(sessionId, expected) {
32743
+ if (this.#sessions.get(sessionId) !== expected) {
32744
+ return;
32745
+ }
32746
+ this.#touchProcess(expected);
32747
+ }
32748
+ #touchNativeBrowserSession(sessionId) {
32749
+ const runtime = this.#nativeBrowserSessions.get(sessionId);
32750
+ if (runtime === void 0) {
32751
+ return;
32752
+ }
32753
+ this.#touchProcess(runtime);
32754
+ }
32755
+ #touchExpectedNativeBrowserSession(sessionId, expected) {
32756
+ if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
32757
+ return;
32758
+ }
32759
+ this.#touchProcess(expected);
32760
+ }
32761
+ #touchProcess(runtime) {
32762
+ const retained = this.#retainedProcesses.get(runtime);
32763
+ if (retained === void 0) {
32764
+ return;
32765
+ }
32766
+ this.#retainedProcesses.delete(runtime);
32767
+ this.#retainedProcesses.set(runtime, retained);
32768
+ }
32769
+ #beginSessionUse(sessionId) {
32770
+ this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
32771
+ this.#touchSession(sessionId);
32772
+ }
32773
+ #endSessionUse(sessionId) {
32774
+ const count = this.#sessionUseCounts.get(sessionId) ?? 0;
32775
+ if (count <= 1) {
32776
+ this.#sessionUseCounts.delete(sessionId);
32777
+ } else {
32778
+ this.#sessionUseCounts.set(sessionId, count - 1);
32779
+ }
32780
+ this.#touchSession(sessionId);
32781
+ this.#notifyProcessCapacityChanged();
32782
+ }
32783
+ #beginNativeBrowserUse(sessionId) {
32784
+ this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
32785
+ this.#touchNativeBrowserSession(sessionId);
32786
+ }
32787
+ #endNativeBrowserUse(sessionId) {
32788
+ const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
32789
+ if (count <= 1) {
32790
+ this.#nativeBrowserUseCounts.delete(sessionId);
32791
+ } else {
32792
+ this.#nativeBrowserUseCounts.set(sessionId, count - 1);
32793
+ }
32794
+ this.#touchNativeBrowserSession(sessionId);
32795
+ this.#notifyProcessCapacityChanged();
32796
+ }
32797
+ #isNativeSessionOperationActive(sessionId) {
32798
+ const stored = this.#store.read(sessionId);
32799
+ return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
32800
+ }
32801
+ #leastRecentlyUsedEvictionCandidate() {
32802
+ for (const candidate of this.#retainedProcesses.values()) {
32803
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
32804
+ if (this.#activeSessionIds.has(candidate.sessionId) || this.#cancellationRequests.has(candidate.sessionId) || this.#preparing.has(candidate.sessionId) || (this.#sessionUseCounts.get(candidate.sessionId) ?? 0) > 0 || this.#isNativeSessionOperationActive(candidate.sessionId)) {
32805
+ continue;
32806
+ }
32807
+ return candidate;
32808
+ }
32809
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate && !this.#nativeBrowserPreparing.has(candidate.sessionId) && (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
32810
+ return candidate;
32811
+ }
32812
+ }
32813
+ return new MissingAcpProcessEvictionCandidate();
32814
+ }
32815
+ #ownedProcessCount() {
32816
+ return this.#retainedProcesses.size + this.#startingProcessCount + this.#transientProcessCount + this.#retiringProcessCount;
32817
+ }
32818
+ async #retireProcess(runtime, retained, close) {
32819
+ if (retained) {
32820
+ this.#retainedProcesses.delete(runtime);
32821
+ this.#retiringProcessCount += 1;
32822
+ }
32823
+ try {
32824
+ await close();
32825
+ } finally {
32826
+ if (retained) {
32827
+ this.#retiringProcessCount -= 1;
32828
+ this.#notifyProcessCapacityChanged();
32829
+ }
32830
+ }
32831
+ }
32832
+ async #retireSessionProcess(sessionId, runtime, close) {
32833
+ const retained = this.#sessions.get(sessionId) === runtime;
32834
+ if (retained) {
32835
+ this.#sessions.delete(sessionId);
32836
+ }
32837
+ await this.#retireProcess(runtime, retained, close);
32838
+ }
32839
+ async #retireNativeBrowserProcess(sessionId, runtime, close) {
32840
+ const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
32841
+ if (retained) {
32842
+ this.#nativeBrowserSessions.delete(sessionId);
32843
+ this.#nativeBrowserStore.remove(sessionId);
32844
+ }
32845
+ await this.#retireProcess(runtime, retained, close);
32846
+ }
32847
+ async #reserveProcessCapacity(signal) {
32848
+ const lease = await this.#processCapacityLock.acquire(signal);
32849
+ try {
32850
+ for (; ; ) {
32851
+ signal.throwIfAborted();
32852
+ if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
32853
+ this.#startingProcessCount += 1;
32854
+ return;
32855
+ }
32856
+ const candidate = this.#leastRecentlyUsedEvictionCandidate();
32857
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
32858
+ await this.#retireSessionProcess(
32859
+ candidate.sessionId,
32860
+ candidate.runtime,
32861
+ async () => await candidate.runtime.close()
32862
+ );
32863
+ continue;
32864
+ }
32865
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
32866
+ await this.#retireNativeBrowserProcess(
32867
+ candidate.sessionId,
32868
+ candidate.runtime,
32869
+ async () => await candidate.runtime.close()
32870
+ );
32871
+ continue;
32872
+ }
32873
+ const changed = this.#processCapacityChanged.promise;
32874
+ await waitForAcpProcessCapacity(changed, signal);
32875
+ }
32876
+ } finally {
32877
+ lease.release();
32878
+ }
32879
+ }
32880
+ async #startRetainedSessionProcess(options, start) {
32881
+ await this.#reserveProcessCapacity(options.signal);
32882
+ try {
32883
+ const runtime = await start();
32884
+ this.#startingProcessCount -= 1;
32885
+ this.#sessions.set(options.sessionId, runtime);
32886
+ this.#retainedProcesses.set(
32887
+ runtime,
32888
+ new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime)
32889
+ );
32890
+ this.#notifyProcessCapacityChanged();
32891
+ return runtime;
32892
+ } catch (error62) {
32893
+ this.#startingProcessCount -= 1;
32894
+ this.#notifyProcessCapacityChanged();
32895
+ throw error62;
32896
+ }
32897
+ }
32898
+ async #startRetainedNativeBrowserProcess(options, start) {
32899
+ await this.#reserveProcessCapacity(options.signal);
32900
+ try {
32901
+ const runtime = await start();
32902
+ this.#startingProcessCount -= 1;
32903
+ this.#nativeBrowserSessions.set(options.sessionId, runtime);
32904
+ this.#retainedProcesses.set(
32905
+ runtime,
32906
+ new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime)
32907
+ );
32908
+ this.#notifyProcessCapacityChanged();
32909
+ return runtime;
32910
+ } catch (error62) {
32911
+ this.#startingProcessCount -= 1;
32912
+ this.#notifyProcessCapacityChanged();
32913
+ throw error62;
32914
+ }
32915
+ }
32916
+ async #runWithTransientProcess(signal, start, operation, close) {
32917
+ await this.#reserveProcessCapacity(signal);
32918
+ let runtime;
32919
+ try {
32920
+ runtime = await start();
32921
+ } catch (error62) {
32922
+ this.#startingProcessCount -= 1;
32923
+ this.#notifyProcessCapacityChanged();
32924
+ throw error62;
32925
+ }
32926
+ this.#startingProcessCount -= 1;
32927
+ this.#transientProcessCount += 1;
32928
+ this.#notifyProcessCapacityChanged();
32929
+ try {
32930
+ return await operation(runtime);
32931
+ } finally {
32932
+ try {
32933
+ await close(runtime);
32934
+ } finally {
32935
+ this.#transientProcessCount -= 1;
32936
+ this.#notifyProcessCapacityChanged();
32937
+ }
32938
+ }
32939
+ }
32608
32940
  async #startNativeBrowserPreparation(options) {
32609
32941
  const operation = (async () => {
32610
32942
  try {
32611
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
32943
+ return await this.#startRetainedNativeBrowserProcess(
32612
32944
  options,
32613
- () => this.#nativeBrowserObserver,
32614
- this.#nativeBrowserStore
32945
+ async () => await AcpProcessSession.startNativeSessionBrowser(
32946
+ options,
32947
+ () => this.#nativeBrowserObserver,
32948
+ this.#nativeBrowserStore
32949
+ )
32615
32950
  );
32616
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
32617
- return runtime;
32618
32951
  } finally {
32619
32952
  this.#nativeBrowserPreparing.delete(options.sessionId);
32953
+ this.#notifyProcessCapacityChanged();
32620
32954
  }
32621
32955
  })();
32622
32956
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -32625,18 +32959,18 @@ var AcpSessionManager = class {
32625
32959
  async #replaceNativeBrowserPreparation(existing, options) {
32626
32960
  const operation = (async () => {
32627
32961
  try {
32628
- this.#nativeBrowserSessions.delete(options.sessionId);
32629
- await existing.close();
32630
- this.#nativeBrowserStore.remove(options.sessionId);
32631
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
32962
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
32963
+ return await this.#startRetainedNativeBrowserProcess(
32632
32964
  options,
32633
- () => this.#nativeBrowserObserver,
32634
- this.#nativeBrowserStore
32965
+ async () => await AcpProcessSession.startNativeSessionBrowser(
32966
+ options,
32967
+ () => this.#nativeBrowserObserver,
32968
+ this.#nativeBrowserStore
32969
+ )
32635
32970
  );
32636
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
32637
- return runtime;
32638
32971
  } finally {
32639
32972
  this.#nativeBrowserPreparing.delete(options.sessionId);
32973
+ this.#notifyProcessCapacityChanged();
32640
32974
  }
32641
32975
  })();
32642
32976
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -32645,11 +32979,13 @@ var AcpSessionManager = class {
32645
32979
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
32646
32980
  const operation = (async () => {
32647
32981
  try {
32648
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
32649
- this.#sessions.set(options.sessionId, runtime);
32650
- return runtime;
32982
+ return await this.#startRetainedSessionProcess(
32983
+ options,
32984
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
32985
+ );
32651
32986
  } finally {
32652
32987
  this.#preparing.delete(options.sessionId);
32988
+ this.#notifyProcessCapacityChanged();
32653
32989
  }
32654
32990
  })();
32655
32991
  this.#preparing.set(options.sessionId, operation);
@@ -32658,17 +32994,19 @@ var AcpSessionManager = class {
32658
32994
  async #startSessionForkAtTurnPreparation(options, sourceNativeSessionId, forkPoint) {
32659
32995
  const operation = (async () => {
32660
32996
  try {
32661
- const runtime = await AcpProcessSession.startSessionForkAtTurn(
32997
+ return await this.#startRetainedSessionProcess(
32662
32998
  options,
32663
- sourceNativeSessionId,
32664
- forkPoint,
32665
- () => this.#observer,
32666
- this.#store
32999
+ async () => await AcpProcessSession.startSessionForkAtTurn(
33000
+ options,
33001
+ sourceNativeSessionId,
33002
+ forkPoint,
33003
+ () => this.#observer,
33004
+ this.#store
33005
+ )
32667
33006
  );
32668
- this.#sessions.set(options.sessionId, runtime);
32669
- return runtime;
32670
33007
  } finally {
32671
33008
  this.#preparing.delete(options.sessionId);
33009
+ this.#notifyProcessCapacityChanged();
32672
33010
  }
32673
33011
  })();
32674
33012
  this.#preparing.set(options.sessionId, operation);
@@ -32677,14 +33015,19 @@ var AcpSessionManager = class {
32677
33015
  async #replacePreparation(existing, options, metrics) {
32678
33016
  const operation = (async () => {
32679
33017
  try {
32680
- this.#sessions.delete(options.sessionId);
32681
- await metrics.measure("runtime-replacement-close", async () => await existing.close());
33018
+ await this.#retireSessionProcess(
33019
+ options.sessionId,
33020
+ existing,
33021
+ async () => await metrics.measure("runtime-replacement-close", async () => await existing.close())
33022
+ );
32682
33023
  this.#store.remove(options.sessionId);
32683
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
32684
- this.#sessions.set(options.sessionId, runtime);
32685
- return runtime;
33024
+ return await this.#startRetainedSessionProcess(
33025
+ options,
33026
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
33027
+ );
32686
33028
  } finally {
32687
33029
  this.#preparing.delete(options.sessionId);
33030
+ this.#notifyProcessCapacityChanged();
32688
33031
  }
32689
33032
  })();
32690
33033
  this.#preparing.set(options.sessionId, operation);
@@ -32694,10 +33037,12 @@ var AcpSessionManager = class {
32694
33037
  const desiredConfigOptions = existing.prepared().configOptions;
32695
33038
  const operation = (async () => {
32696
33039
  try {
32697
- this.#sessions.delete(options.sessionId);
32698
- await existing.close();
33040
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
32699
33041
  this.#store.remove(options.sessionId);
32700
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
33042
+ const runtime = await this.#startRetainedSessionProcess(
33043
+ options,
33044
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
33045
+ );
32701
33046
  try {
32702
33047
  for (const desired of desiredConfigOptions) {
32703
33048
  const current = runtime.prepared().configOptions.find((option2) => option2.id === desired.id);
@@ -32729,14 +33074,14 @@ var AcpSessionManager = class {
32729
33074
  }
32730
33075
  }
32731
33076
  } catch (error62) {
32732
- await runtime.close();
33077
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
32733
33078
  this.#store.remove(options.sessionId);
32734
33079
  throw error62;
32735
33080
  }
32736
- this.#sessions.set(options.sessionId, runtime);
32737
33081
  return runtime;
32738
33082
  } finally {
32739
33083
  this.#preparing.delete(options.sessionId);
33084
+ this.#notifyProcessCapacityChanged();
32740
33085
  }
32741
33086
  })();
32742
33087
  this.#preparing.set(options.sessionId, operation);
@@ -32758,6 +33103,7 @@ var AcpSessionManager = class {
32758
33103
  if (pending !== void 0) {
32759
33104
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
32760
33105
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
33106
+ this.#touchExpectedSession(options.sessionId, runtime2);
32761
33107
  return runtime2.prepared();
32762
33108
  }
32763
33109
  return await this.prepareSession(options, metrics);
@@ -32765,6 +33111,7 @@ var AcpSessionManager = class {
32765
33111
  const existing = this.#sessions.get(options.sessionId);
32766
33112
  if (existing !== void 0) {
32767
33113
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
33114
+ this.#touchExpectedSession(options.sessionId, existing);
32768
33115
  return existing.prepared();
32769
33116
  }
32770
33117
  if (!existing.canRebind()) {
@@ -32785,22 +33132,24 @@ var AcpSessionManager = class {
32785
33132
  * authoritative settings. Its identity and store are private to this
32786
33133
  * operation and never become a Mobius Session.
32787
33134
  */
32788
- inspectAgentSettings = async (options) => {
32789
- const runtime = await AcpProcessSession.start(
33135
+ inspectAgentSettings = async (options) => await this.#runWithTransientProcess(
33136
+ options.signal,
33137
+ async () => await AcpProcessSession.start(
32790
33138
  {
32791
33139
  ...options,
32792
33140
  sessionId: `agent-settings-${crypto.randomUUID()}`
32793
33141
  },
32794
33142
  () => this.#agentSettingsObserver,
32795
33143
  new MemoryAcpSessionStore()
32796
- );
32797
- try {
33144
+ ),
33145
+ (runtime) => {
32798
33146
  const prepared = runtime.prepared();
32799
- return new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions);
32800
- } finally {
32801
- await runtime.close();
32802
- }
32803
- };
33147
+ return Promise.resolve(
33148
+ new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions)
33149
+ );
33150
+ },
33151
+ async (runtime) => await runtime.close()
33152
+ );
32804
33153
  /**
32805
33154
  * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
32806
33155
  * Use inspectAgentSettings for Agent-scoped settings discovery.
@@ -32809,18 +33158,20 @@ var AcpSessionManager = class {
32809
33158
  if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
32810
33159
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
32811
33160
  }
32812
- const runtime = await this.#startPreparation(options, metrics);
33161
+ this.#beginSessionUse(options.sessionId);
32813
33162
  try {
32814
- return runtime.prepared();
32815
- } finally {
32816
- if (this.#sessions.get(options.sessionId) === runtime) {
32817
- this.#sessions.delete(options.sessionId);
32818
- }
33163
+ const runtime = await this.#startPreparation(options, metrics);
32819
33164
  try {
32820
- await runtime.close();
33165
+ return runtime.prepared();
32821
33166
  } finally {
32822
- this.#store.remove(options.sessionId);
33167
+ try {
33168
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
33169
+ } finally {
33170
+ this.#store.remove(options.sessionId);
33171
+ }
32823
33172
  }
33173
+ } finally {
33174
+ this.#endSessionUse(options.sessionId);
32824
33175
  }
32825
33176
  };
32826
33177
  prepareExecutionSession = async (options) => {
@@ -32841,6 +33192,7 @@ var AcpSessionManager = class {
32841
33192
  );
32842
33193
  }
32843
33194
  if (existing.usesEnvironment(options.agent.environment)) {
33195
+ this.#touchExpectedSession(options.sessionId, existing);
32844
33196
  return existing.prepared();
32845
33197
  }
32846
33198
  if (!existing.canRebind()) {
@@ -32857,6 +33209,7 @@ var AcpSessionManager = class {
32857
33209
  if (pending !== void 0) {
32858
33210
  const runtime2 = await pending;
32859
33211
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
33212
+ this.#touchExpectedNativeBrowserSession(options.sessionId, runtime2);
32860
33213
  return runtime2.prepared();
32861
33214
  }
32862
33215
  return await this.prepareNativeSessionBrowser(options);
@@ -32864,6 +33217,7 @@ var AcpSessionManager = class {
32864
33217
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
32865
33218
  if (existing !== void 0) {
32866
33219
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
33220
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
32867
33221
  return existing.prepared();
32868
33222
  }
32869
33223
  if (!existing.canRebind()) {
@@ -32880,8 +33234,13 @@ var AcpSessionManager = class {
32880
33234
  return runtime.prepared();
32881
33235
  };
32882
33236
  configureSession = async (options) => {
32883
- const runtime = await this.ensureSession(options);
32884
- return await runtime.configure(options);
33237
+ this.#beginSessionUse(options.sessionId);
33238
+ try {
33239
+ const runtime = await this.ensureSession(options);
33240
+ return await runtime.configure(options);
33241
+ } finally {
33242
+ this.#endSessionUse(options.sessionId);
33243
+ }
32885
33244
  };
32886
33245
  cancelPrompt = async (sessionId) => {
32887
33246
  const existing = this.#cancellationRequests.get(sessionId);
@@ -32897,6 +33256,8 @@ var AcpSessionManager = class {
32897
33256
  } finally {
32898
33257
  if (this.#sessions.get(sessionId) === runtime) {
32899
33258
  this.#sessions.delete(sessionId);
33259
+ this.#retainedProcesses.delete(runtime);
33260
+ this.#notifyProcessCapacityChanged();
32900
33261
  }
32901
33262
  }
32902
33263
  }
@@ -32986,10 +33347,7 @@ var AcpSessionManager = class {
32986
33347
  return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
32987
33348
  } catch (error62) {
32988
33349
  if (this.#cancellationRequests.has(options.sessionId)) {
32989
- if (this.#sessions.get(options.sessionId) === runtime) {
32990
- this.#sessions.delete(options.sessionId);
32991
- }
32992
- await runtime.closeProcess();
33350
+ await this.#cancellationRequests.get(options.sessionId);
32993
33351
  return { stopReason: "cancelled" };
32994
33352
  }
32995
33353
  throw error62;
@@ -32997,8 +33355,11 @@ var AcpSessionManager = class {
32997
33355
  } catch (error62) {
32998
33356
  const failedRuntime = this.#sessions.get(options.sessionId);
32999
33357
  if (failedRuntime !== void 0) {
33000
- this.#sessions.delete(options.sessionId);
33001
- await failedRuntime.close();
33358
+ await this.#retireSessionProcess(
33359
+ options.sessionId,
33360
+ failedRuntime,
33361
+ async () => await failedRuntime.close()
33362
+ );
33002
33363
  }
33003
33364
  if (this.#cancellationRequests.has(options.sessionId)) {
33004
33365
  return { stopReason: "cancelled" };
@@ -33019,6 +33380,8 @@ var AcpSessionManager = class {
33019
33380
  this.#activeCommandIds.delete(options.sessionId);
33020
33381
  }
33021
33382
  this.#cancellationRequests.delete(options.sessionId);
33383
+ this.#touchSession(options.sessionId);
33384
+ this.#notifyProcessCapacityChanged();
33022
33385
  }
33023
33386
  }
33024
33387
  };
@@ -33037,11 +33400,16 @@ var AcpSessionManager = class {
33037
33400
  await runtime.respondElicitation(options);
33038
33401
  };
33039
33402
  close = async () => {
33040
- const sessions = [...this.#sessions.values()];
33041
- const nativeBrowserSessions = [...this.#nativeBrowserSessions.values()];
33042
- this.#sessions.clear();
33043
- this.#nativeBrowserSessions.clear();
33044
- await Promise.all([...sessions, ...nativeBrowserSessions].map(async (session) => await session.close()));
33403
+ const sessions = [...this.#sessions.entries()];
33404
+ const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
33405
+ await Promise.all([
33406
+ ...sessions.map(
33407
+ async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
33408
+ ),
33409
+ ...nativeBrowserSessions.map(
33410
+ async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
33411
+ )
33412
+ ]);
33045
33413
  };
33046
33414
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
33047
33415
  ensureSession = async (options) => {
@@ -33054,6 +33422,7 @@ var AcpSessionManager = class {
33054
33422
  "session_identity_mismatch"
33055
33423
  );
33056
33424
  }
33425
+ this.#touchExpectedSession(options.sessionId, existing);
33057
33426
  return existing;
33058
33427
  }
33059
33428
  await this.prepareSession(options);
@@ -33073,6 +33442,7 @@ var AcpSessionManager = class {
33073
33442
  "session_identity_mismatch"
33074
33443
  );
33075
33444
  }
33445
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
33076
33446
  return existing;
33077
33447
  }
33078
33448
  await this.prepareNativeSessionBrowser(options);
@@ -33082,7 +33452,14 @@ var AcpSessionManager = class {
33082
33452
  }
33083
33453
  return started;
33084
33454
  }
33085
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
33455
+ listNativeSessions = async (options, cursor) => {
33456
+ this.#beginNativeBrowserUse(options.sessionId);
33457
+ try {
33458
+ return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
33459
+ } finally {
33460
+ this.#endNativeBrowserUse(options.sessionId);
33461
+ }
33462
+ };
33086
33463
  previewNativeSession = async (options, nativeSessionId) => {
33087
33464
  const key = `${options.agent.id}:${nativeSessionId}`;
33088
33465
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
@@ -33095,17 +33472,19 @@ var AcpSessionManager = class {
33095
33472
  }
33096
33473
  this.#nativeOperations.add(key);
33097
33474
  try {
33098
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
33099
- options,
33100
- () => this.#nativeBrowserObserver,
33101
- new MemoryAcpSessionStore()
33475
+ return await this.#runWithTransientProcess(
33476
+ options.signal,
33477
+ async () => await AcpProcessSession.startNativeSessionBrowser(
33478
+ options,
33479
+ () => this.#nativeBrowserObserver,
33480
+ new MemoryAcpSessionStore()
33481
+ ),
33482
+ async (runtime) => {
33483
+ runtime.selectNativeSession(nativeSessionId);
33484
+ return await runtime.loadHistory(options.signal);
33485
+ },
33486
+ async (runtime) => await runtime.closeProcess()
33102
33487
  );
33103
- try {
33104
- runtime.selectNativeSession(nativeSessionId);
33105
- return await runtime.loadHistory(options.signal);
33106
- } finally {
33107
- await runtime.closeProcess();
33108
- }
33109
33488
  } finally {
33110
33489
  this.#nativeOperations.delete(key);
33111
33490
  }
@@ -33125,36 +33504,46 @@ var AcpSessionManager = class {
33125
33504
  }
33126
33505
  const existing = linked[0];
33127
33506
  if (origin.kind === "import" && existing !== void 0) {
33128
- const runtime = await this.ensureSession({
33129
- ...options,
33130
- sessionId: existing.sessionId
33131
- });
33132
- if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
33133
- throw new AcpExecutionError(
33134
- "Wait for the native session's running operation to finish",
33135
- {},
33136
- "session_busy"
33137
- );
33138
- }
33139
- this.#nativeOperations.add(key);
33507
+ this.#beginSessionUse(existing.sessionId);
33140
33508
  try {
33141
- const history = await runtime.loadHistory(options.signal);
33142
- return {
33143
- prepared: runtime.prepared(),
33144
- sessionId: existing.sessionId,
33145
- history
33146
- };
33147
- } catch (error62) {
33148
- this.#sessions.delete(existing.sessionId);
33149
- await runtime.closeProcess();
33150
- throw error62;
33509
+ const runtime = await this.ensureSession({
33510
+ ...options,
33511
+ sessionId: existing.sessionId
33512
+ });
33513
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
33514
+ throw new AcpExecutionError(
33515
+ "Wait for the native session's running operation to finish",
33516
+ {},
33517
+ "session_busy"
33518
+ );
33519
+ }
33520
+ this.#nativeOperations.add(key);
33521
+ try {
33522
+ const history = await runtime.loadHistory(options.signal);
33523
+ return {
33524
+ prepared: runtime.prepared(),
33525
+ sessionId: existing.sessionId,
33526
+ history
33527
+ };
33528
+ } catch (error62) {
33529
+ await this.#retireSessionProcess(
33530
+ existing.sessionId,
33531
+ runtime,
33532
+ async () => await runtime.closeProcess()
33533
+ );
33534
+ throw error62;
33535
+ } finally {
33536
+ this.#nativeOperations.delete(key);
33537
+ this.#notifyProcessCapacityChanged();
33538
+ }
33151
33539
  } finally {
33152
- this.#nativeOperations.delete(key);
33540
+ this.#endSessionUse(existing.sessionId);
33153
33541
  }
33154
33542
  }
33155
33543
  if (this.#sessions.has(options.sessionId) || this.#preparing.has(options.sessionId) || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
33156
33544
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
33157
33545
  }
33546
+ this.#beginSessionUse(options.sessionId);
33158
33547
  this.#nativeOperations.add(key);
33159
33548
  try {
33160
33549
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -33168,23 +33557,23 @@ var AcpSessionManager = class {
33168
33557
  history
33169
33558
  };
33170
33559
  } catch (error62) {
33171
- this.#sessions.delete(options.sessionId);
33172
33560
  this.#store.remove(options.sessionId);
33173
- await runtime.closeProcess();
33561
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
33174
33562
  throw error62;
33175
33563
  } finally {
33176
33564
  this.#nativeOperations.delete(openedKey);
33565
+ this.#notifyProcessCapacityChanged();
33177
33566
  }
33178
33567
  } catch (error62) {
33179
33568
  this.#store.remove(options.sessionId);
33180
33569
  const runtime = this.#sessions.get(options.sessionId);
33181
- this.#sessions.delete(options.sessionId);
33182
33570
  if (runtime !== void 0) {
33183
- await runtime.closeProcess();
33571
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
33184
33572
  }
33185
33573
  throw error62;
33186
33574
  } finally {
33187
33575
  this.#nativeOperations.delete(key);
33576
+ this.#endSessionUse(options.sessionId);
33188
33577
  }
33189
33578
  };
33190
33579
  forkSessionAtTurn = async (options, sourceSessionId, forkPoint) => {
@@ -33222,6 +33611,7 @@ var AcpSessionManager = class {
33222
33611
  if (this.#sessions.has(options.sessionId) || this.#preparing.has(options.sessionId) || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
33223
33612
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
33224
33613
  }
33614
+ this.#beginSessionUse(options.sessionId);
33225
33615
  this.#nativeOperations.add(key);
33226
33616
  try {
33227
33617
  const runtime = await this.#startSessionForkAtTurnPreparation(
@@ -33238,48 +33628,58 @@ var AcpSessionManager = class {
33238
33628
  sessionId: options.sessionId
33239
33629
  };
33240
33630
  } catch (error62) {
33241
- this.#sessions.delete(options.sessionId);
33242
33631
  this.#store.remove(options.sessionId);
33243
- await runtime.closeProcess();
33632
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
33244
33633
  throw error62;
33245
33634
  } finally {
33246
33635
  this.#nativeOperations.delete(openedKey);
33636
+ this.#notifyProcessCapacityChanged();
33247
33637
  }
33248
33638
  } finally {
33249
33639
  this.#nativeOperations.delete(key);
33640
+ this.#endSessionUse(options.sessionId);
33250
33641
  }
33251
33642
  };
33252
33643
  deleteNativeSession = async (options, nativeSessionId) => {
33253
- const runtime = await this.#ensureNativeSessionBrowser(options);
33254
- const key = `${options.agent.id}:${nativeSessionId}`;
33255
- const linked = this.#store.findNative(options.agent.id, nativeSessionId);
33256
- if (this.#nativeOperations.has(key) || linked.some((entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
33257
- throw new AcpExecutionError(
33258
- "Wait for the native session's running operation to finish",
33259
- {},
33260
- "session_busy"
33261
- );
33262
- }
33263
- this.#nativeOperations.add(key);
33644
+ this.#beginNativeBrowserUse(options.sessionId);
33264
33645
  try {
33265
- for (const entry of linked) {
33266
- const active = this.#sessions.get(entry.sessionId);
33267
- if (active !== void 0 && active !== runtime) {
33268
- this.#sessions.delete(entry.sessionId);
33269
- await active.close();
33646
+ const runtime = await this.#ensureNativeSessionBrowser(options);
33647
+ const key = `${options.agent.id}:${nativeSessionId}`;
33648
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
33649
+ if (this.#nativeOperations.has(key) || linked.some(
33650
+ (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
33651
+ )) {
33652
+ throw new AcpExecutionError(
33653
+ "Wait for the native session's running operation to finish",
33654
+ {},
33655
+ "session_busy"
33656
+ );
33657
+ }
33658
+ this.#nativeOperations.add(key);
33659
+ try {
33660
+ for (const entry of linked) {
33661
+ const active = this.#sessions.get(entry.sessionId);
33662
+ if (active !== void 0 && active !== runtime) {
33663
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
33664
+ }
33270
33665
  }
33666
+ options.signal.throwIfAborted();
33667
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
33668
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
33669
+ if (runtime.nativeSessionId() === nativeSessionId) {
33670
+ await this.#retireNativeBrowserProcess(
33671
+ options.sessionId,
33672
+ runtime,
33673
+ async () => await runtime.close()
33674
+ );
33675
+ }
33676
+ return deleted;
33677
+ } finally {
33678
+ this.#nativeOperations.delete(key);
33679
+ this.#notifyProcessCapacityChanged();
33271
33680
  }
33272
- options.signal.throwIfAborted();
33273
- await runtime.deleteNativeSession(nativeSessionId, options.signal);
33274
- const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
33275
- if (runtime.nativeSessionId() === nativeSessionId) {
33276
- this.#nativeBrowserSessions.delete(options.sessionId);
33277
- this.#nativeBrowserStore.remove(options.sessionId);
33278
- await runtime.close();
33279
- }
33280
- return deleted;
33281
33681
  } finally {
33282
- this.#nativeOperations.delete(key);
33682
+ this.#endNativeBrowserUse(options.sessionId);
33283
33683
  }
33284
33684
  };
33285
33685
  };
@@ -33368,21 +33768,8 @@ import { randomBytes } from "node:crypto";
33368
33768
 
33369
33769
  // src/bots/local-bot-grant-store.ts
33370
33770
  import { createHash, randomUUID } from "node:crypto";
33371
- import { stat as stat3 } from "node:fs/promises";
33372
33771
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
33373
33772
  var LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS = 90 * 24 * 60 * 60 * 1e3;
33374
- var identifier2 = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
33375
- var savedApprovalSchema = external_exports.object({
33376
- local_grant_id: identifier2,
33377
- bot_id: identifier2,
33378
- binding_id: identifier2,
33379
- binding_revision: external_exports.number().int().positive(),
33380
- agent_ref: identifier2,
33381
- workspace_ref: external_exports.string().min(1).max(2048),
33382
- revocation_epoch: external_exports.number().int().nonnegative(),
33383
- agent_identity_digest: external_exports.string().regex(/^[a-f0-9]{64}$/),
33384
- workspace_identity_digest: external_exports.string().regex(/^[a-f0-9]{64}$/)
33385
- }).readonly();
33386
33773
  var LocalBotAuthorizationError = class extends Error {
33387
33774
  code;
33388
33775
  constructor(code, message, options = {}) {
@@ -33437,19 +33824,8 @@ function agentDigest(agent) {
33437
33824
  })
33438
33825
  );
33439
33826
  }
33440
- async function workspaceDigest(path2) {
33441
- const metadata = await stat3(path2);
33442
- if (!metadata.isDirectory()) {
33443
- throw new LocalBotAuthorizationError("binding_incompatible", "The Bot workspace is not a directory");
33444
- }
33445
- return digest(
33446
- JSON.stringify({
33447
- changedAtMilliseconds: metadata.ctimeMs,
33448
- device: metadata.dev,
33449
- inode: metadata.ino,
33450
- path: path2
33451
- })
33452
- );
33827
+ function workspaceDigest(path2) {
33828
+ return digest(path2);
33453
33829
  }
33454
33830
  function exactTargets(left, right) {
33455
33831
  if (left.length !== right.length) {
@@ -33483,6 +33859,16 @@ function rowInteger(row, key) {
33483
33859
  }
33484
33860
  return value;
33485
33861
  }
33862
+ function rowHasInteger(row, key) {
33863
+ const value = Reflect.get(row, key);
33864
+ if (value === null) {
33865
+ return false;
33866
+ }
33867
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
33868
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
33869
+ }
33870
+ return true;
33871
+ }
33486
33872
  function parseTargets(encoded) {
33487
33873
  let value;
33488
33874
  try {
@@ -33506,17 +33892,6 @@ function parseSessionConfigurations(encoded) {
33506
33892
  }
33507
33893
  var LocalBotGrantStore = class {
33508
33894
  #database;
33509
- static containsBot = (path2, botId) => {
33510
- const database = new DatabaseSync3(path2, { readOnly: true });
33511
- try {
33512
- if (database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_bot_grants'").get() === void 0) {
33513
- return false;
33514
- }
33515
- return database.prepare("SELECT local_grant_id FROM local_bot_grants WHERE bot_id = ? LIMIT 1").get(botId) !== void 0;
33516
- } finally {
33517
- database.close();
33518
- }
33519
- };
33520
33895
  constructor(path2) {
33521
33896
  this.#database = new DatabaseSync3(path2);
33522
33897
  this.#database.exec(`
@@ -33554,78 +33929,6 @@ var LocalBotGrantStore = class {
33554
33929
  ) STRICT;
33555
33930
  `);
33556
33931
  }
33557
- /** Only the local CLI may invoke this explicit approval transition. */
33558
- reapprove = async (botId, catalog, directories, bindingAuthorityId, now, signal) => {
33559
- signal.throwIfAborted();
33560
- if (!identifier2.safeParse(botId).success) {
33561
- throw new LocalBotAuthorizationError("invalid_request", "The Bot ID is invalid");
33562
- }
33563
- const row = this.#database.prepare("SELECT * FROM local_bot_grants WHERE bot_id = ? ORDER BY binding_revision DESC LIMIT 1").get(botId);
33564
- if (row === void 0) {
33565
- throw new LocalBotAuthorizationError("bot_not_found", "This machine has no saved approval for that Bot");
33566
- }
33567
- const parsed = savedApprovalSchema.safeParse(row);
33568
- if (!parsed.success) {
33569
- throw new LocalBotAuthorizationError("local_grant_invalid", "The saved Bot approval is invalid", {
33570
- cause: parsed.error
33571
- });
33572
- }
33573
- const saved = parsed.data;
33574
- const agent = catalog.find(saved.agent_ref);
33575
- if (!agent.capabilities.embeddedContextPrompt) {
33576
- throw new LocalBotAuthorizationError("binding_incompatible", "The local Agent cannot apply Bot context");
33577
- }
33578
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
33579
- revalidateExecutable(agent.adapterIdentity),
33580
- revalidateExecutable(agent.agentIdentity)
33581
- ]);
33582
- signal.throwIfAborted();
33583
- if (!adapterUnchanged || !agentUnchanged) {
33584
- throw new LocalBotAuthorizationError(
33585
- "binding_incompatible",
33586
- "The local Agent executable changed before approval"
33587
- );
33588
- }
33589
- const workspacePath = await directories.resolve(bindingAuthorityId, saved.workspace_ref, signal);
33590
- const workspaceIdentityDigest = await workspaceDigest(workspacePath);
33591
- signal.throwIfAborted();
33592
- this.#database.exec("BEGIN IMMEDIATE");
33593
- try {
33594
- const result = this.#database.prepare(`UPDATE local_bot_grants
33595
- SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
33596
- revoked_at = NULL, expires_at = ?, revocation_epoch = revocation_epoch + 1
33597
- WHERE local_grant_id = ? AND revocation_epoch = ?
33598
- AND agent_identity_digest = ? AND workspace_identity_digest = ?
33599
- AND binding_revision = (SELECT MAX(binding_revision) FROM local_bot_grants WHERE bot_id = ?)`).run(
33600
- agentDigest(agent),
33601
- workspaceIdentityDigest,
33602
- workspacePath,
33603
- now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS,
33604
- saved.local_grant_id,
33605
- saved.revocation_epoch,
33606
- saved.agent_identity_digest,
33607
- saved.workspace_identity_digest,
33608
- botId
33609
- );
33610
- if (result.changes !== 1) {
33611
- throw new LocalBotAuthorizationError(
33612
- "binding_not_approved",
33613
- "The Bot binding changed during approval; run the command again"
33614
- );
33615
- }
33616
- this.#database.prepare(`INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
33617
- VALUES (?, 'bot_binding_locally_reapproved', ?, '', ?)`).run(
33618
- new Date(now).toISOString(),
33619
- saved.binding_id,
33620
- JSON.stringify({ botId, bindingId: saved.binding_id, agentRef: saved.agent_ref })
33621
- );
33622
- this.#database.exec("COMMIT");
33623
- } catch (cause) {
33624
- this.#database.exec("ROLLBACK");
33625
- throw cause;
33626
- }
33627
- return { bindingId: saved.binding_id, workspacePath, agentRef: saved.agent_ref };
33628
- };
33629
33932
  approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
33630
33933
  signal.throwIfAborted();
33631
33934
  const existing = this.#database.prepare(
@@ -33715,8 +34018,7 @@ var LocalBotGrantStore = class {
33715
34018
  WHERE grants.local_grant_id = ? AND grants.bot_id = ?
33716
34019
  AND behavior_revision_id = ? AND behavior_digest = ?
33717
34020
  AND binding_id = ? AND binding_revision = ?
33718
- AND agent_ref = ?
33719
- AND revoked_at IS NULL AND expires_at > ?`
34021
+ AND agent_ref = ?`
33720
34022
  ).get(
33721
34023
  command.localGrantId,
33722
34024
  command.botId,
@@ -33724,8 +34026,7 @@ var LocalBotGrantStore = class {
33724
34026
  command.behaviorDigest,
33725
34027
  command.bindingId,
33726
34028
  command.bindingRevision,
33727
- command.agentId,
33728
- now
34029
+ command.agentId
33729
34030
  );
33730
34031
  if (row === void 0) {
33731
34032
  throw new LocalBotAuthorizationError(
@@ -33738,14 +34039,14 @@ var LocalBotGrantStore = class {
33738
34039
  if (!exactTargets(approvedTargets, requestedTargets)) {
33739
34040
  throw new LocalBotAuthorizationError(
33740
34041
  "binding_not_approved",
33741
- "The Bot execution target policy changed after local approval"
34042
+ "The Bot execution target policy differs from its binding"
33742
34043
  );
33743
34044
  }
33744
34045
  const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
33745
34046
  if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
33746
34047
  throw new LocalBotAuthorizationError(
33747
34048
  "binding_not_approved",
33748
- "The Bot Agent configuration changed after local approval"
34049
+ "The Bot Agent configuration differs from its binding"
33749
34050
  );
33750
34051
  }
33751
34052
  const agent = catalog.find(command.agentId);
@@ -33754,17 +34055,29 @@ var LocalBotGrantStore = class {
33754
34055
  revalidateExecutable(agent.agentIdentity)
33755
34056
  ]);
33756
34057
  signal.throwIfAborted();
34058
+ if (!adapterUnchanged || !agentUnchanged) {
34059
+ throw new LocalBotAuthorizationError(
34060
+ "binding_incompatible",
34061
+ "The local Agent executable changed while the Runtime is active; restart the Runtime"
34062
+ );
34063
+ }
33757
34064
  const workspaceRef = rowString(row, "workspace_ref");
33758
34065
  const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
33759
34066
  const currentAgentDigest = agentDigest(agent);
33760
- const currentWorkspaceDigest = await workspaceDigest(workspacePath);
34067
+ const currentWorkspaceDigest = workspaceDigest(workspacePath);
33761
34068
  signal.throwIfAborted();
33762
- if (!adapterUnchanged || !agentUnchanged || currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path")) {
33763
- this.revoke(rowString(row, "local_grant_id"), now);
33764
- throw new LocalBotAuthorizationError(
33765
- "binding_not_approved",
33766
- "The Bot execution target changed and requires local approval"
34069
+ let expiresAt = rowInteger(row, "expires_at");
34070
+ let revocationEpoch = rowInteger(row, "revocation_epoch");
34071
+ if (currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path") || expiresAt <= now || rowHasInteger(row, "revoked_at")) {
34072
+ const refreshed = this.refreshTarget(
34073
+ rowString(row, "local_grant_id"),
34074
+ currentAgentDigest,
34075
+ currentWorkspaceDigest,
34076
+ workspacePath,
34077
+ now
33767
34078
  );
34079
+ expiresAt = refreshed.expiresAt;
34080
+ revocationEpoch = refreshed.revocationEpoch;
33768
34081
  }
33769
34082
  if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
33770
34083
  throw new LocalBotAuthorizationError(
@@ -33785,8 +34098,8 @@ var LocalBotGrantStore = class {
33785
34098
  workspacePath,
33786
34099
  currentWorkspaceDigest,
33787
34100
  approvedTargets,
33788
- rowInteger(row, "expires_at"),
33789
- rowInteger(row, "revocation_epoch")
34101
+ expiresAt,
34102
+ revocationEpoch
33790
34103
  );
33791
34104
  };
33792
34105
  recordUnavailable = (request, code, message, now) => {
@@ -33829,16 +34142,65 @@ var LocalBotGrantStore = class {
33829
34142
  return {
33830
34143
  agent,
33831
34144
  agentIdentityDigest: agentDigest(agent),
33832
- workspaceIdentityDigest: await workspaceDigest(workspacePath),
34145
+ workspaceIdentityDigest: workspaceDigest(workspacePath),
33833
34146
  workspacePath
33834
34147
  };
33835
34148
  };
33836
- revoke = (localGrantId, now) => {
33837
- this.#database.prepare(
33838
- `UPDATE local_bot_grants
33839
- SET revoked_at = COALESCE(revoked_at, ?), revocation_epoch = revocation_epoch + 1
33840
- WHERE local_grant_id = ? AND revoked_at IS NULL`
33841
- ).run(now, localGrantId);
34149
+ refreshTarget = (localGrantId, agentIdentityDigest, workspaceIdentityDigest, workspacePath, now) => {
34150
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
34151
+ this.#database.exec("BEGIN IMMEDIATE");
34152
+ try {
34153
+ const current = this.#database.prepare("SELECT * FROM local_bot_grants WHERE local_grant_id = ?").get(localGrantId);
34154
+ if (current === void 0) {
34155
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is missing");
34156
+ }
34157
+ const currentExpiresAt = rowInteger(current, "expires_at");
34158
+ const currentRevocationEpoch = rowInteger(current, "revocation_epoch");
34159
+ if (agentIdentityDigest === rowString(current, "agent_identity_digest") && workspaceIdentityDigest === rowString(current, "workspace_identity_digest") && workspacePath === rowString(current, "workspace_path") && currentExpiresAt > now && !rowHasInteger(current, "revoked_at")) {
34160
+ this.#database.exec("COMMIT");
34161
+ return { expiresAt: currentExpiresAt, revocationEpoch: currentRevocationEpoch };
34162
+ }
34163
+ const result = this.#database.prepare(
34164
+ `UPDATE local_bot_grants
34165
+ SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
34166
+ expires_at = ?, revoked_at = NULL, revocation_epoch = revocation_epoch + 1
34167
+ WHERE local_grant_id = ? AND revocation_epoch = ?`
34168
+ ).run(
34169
+ agentIdentityDigest,
34170
+ workspaceIdentityDigest,
34171
+ workspacePath,
34172
+ expiresAt,
34173
+ localGrantId,
34174
+ currentRevocationEpoch
34175
+ );
34176
+ if (result.changes !== 1) {
34177
+ throw new LocalBotAuthorizationError(
34178
+ "local_grant_invalid",
34179
+ "The local Bot grant target could not be refreshed"
34180
+ );
34181
+ }
34182
+ this.#database.prepare(
34183
+ `INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
34184
+ VALUES (?, 'bot_binding_target_refreshed', ?, '', ?)`
34185
+ ).run(
34186
+ new Date(now).toISOString(),
34187
+ rowString(current, "binding_id"),
34188
+ JSON.stringify({
34189
+ agentIdentityChanged: agentIdentityDigest !== rowString(current, "agent_identity_digest"),
34190
+ bindingId: rowString(current, "binding_id"),
34191
+ botId: rowString(current, "bot_id"),
34192
+ expired: currentExpiresAt <= now,
34193
+ revived: rowHasInteger(current, "revoked_at"),
34194
+ workspaceIdentityChanged: workspaceIdentityDigest !== rowString(current, "workspace_identity_digest"),
34195
+ workspacePathChanged: workspacePath !== rowString(current, "workspace_path")
34196
+ })
34197
+ );
34198
+ this.#database.exec("COMMIT");
34199
+ return { expiresAt, revocationEpoch: currentRevocationEpoch + 1 };
34200
+ } catch (cause) {
34201
+ this.#database.exec("ROLLBACK");
34202
+ throw cause;
34203
+ }
33842
34204
  };
33843
34205
  };
33844
34206
 
@@ -34336,7 +34698,7 @@ var BotOutboundIpcServer = class {
34336
34698
 
34337
34699
  // src/pairing/pair-local-machine.ts
34338
34700
  import { randomUUID as randomUUID3 } from "node:crypto";
34339
- import { mkdir as mkdir4, open as open4, realpath as realpath7, rename as rename3, stat as stat7, writeFile as writeFile2 } from "node:fs/promises";
34701
+ import { mkdir as mkdir4, open as open4, realpath as realpath7, rename as rename3, stat as stat6, writeFile as writeFile2 } from "node:fs/promises";
34340
34702
  import { hostname as hostname3 } from "node:os";
34341
34703
  import { basename as basename2, join as join15, resolve as resolve3 } from "node:path";
34342
34704
  import { fetch as fetch3 } from "undici";
@@ -34448,7 +34810,7 @@ var LocalAgentInventory = class {
34448
34810
  };
34449
34811
 
34450
34812
  // src/agent-installation/managed-npm-package.ts
34451
- import { mkdir as mkdir2, mkdtemp, open as open2, realpath as realpath3, rename, rm, stat as stat4 } from "node:fs/promises";
34813
+ import { mkdir as mkdir2, mkdtemp, open as open2, realpath as realpath3, rename, rm, stat as stat3 } from "node:fs/promises";
34452
34814
  import { delimiter, dirname as dirname4, isAbsolute as isAbsolute3, join as join4, relative as relative2, sep as sep2 } from "node:path";
34453
34815
  var INSTALL_TIMEOUT_MILLISECONDS = 5 * 60 * 1e3;
34454
34816
  var PACKAGE_METADATA_LIMIT_BYTES = 64 * 1024;
@@ -34670,7 +35032,7 @@ var ManagedNpmPackageInstaller = class {
34670
35032
  install = async (root, definition2, environment, signal) => {
34671
35033
  signal.throwIfAborted();
34672
35034
  try {
34673
- const metadata = await stat4(root);
35035
+ const metadata = await stat3(root);
34674
35036
  if (metadata.isDirectory()) {
34675
35037
  return await validateManagedNpmPackage(root, definition2);
34676
35038
  }
@@ -34992,7 +35354,7 @@ var CursorCliAgentSpecification = class extends DirectAcpAgentDefinition {
34992
35354
  };
34993
35355
 
34994
35356
  // src/agent-catalog/agents/deepseek-harness-agent.ts
34995
- import { realpath as realpath4, stat as stat5 } from "node:fs/promises";
35357
+ import { realpath as realpath4, stat as stat4 } from "node:fs/promises";
34996
35358
  import { isAbsolute as isAbsolute5, join as join7, normalize as normalize2 } from "node:path";
34997
35359
 
34998
35360
  // src/agent-installation/deepseek-managed-package.ts
@@ -35016,7 +35378,7 @@ async function validateAgentHome(path2) {
35016
35378
  }
35017
35379
  try {
35018
35380
  const resolved = await realpath4(path2);
35019
- const metadata = await stat5(resolved);
35381
+ const metadata = await stat4(resolved);
35020
35382
  if (!metadata.isDirectory() || typeof process.getuid === "function" && metadata.uid !== process.getuid()) {
35021
35383
  throw new Error("Agent home is not a user-owned directory");
35022
35384
  }
@@ -35298,7 +35660,7 @@ import { join as join10 } from "node:path";
35298
35660
  // src/agent-installation/managed-agent-archive.ts
35299
35661
  import { createHash as createHash2 } from "node:crypto";
35300
35662
  import { createReadStream } from "node:fs";
35301
- import { chmod as chmod2, copyFile, mkdir as mkdir3, mkdtemp as mkdtemp2, open as open3, realpath as realpath6, rename as rename2, rm as rm2, stat as stat6, writeFile } from "node:fs/promises";
35663
+ import { chmod as chmod2, copyFile, mkdir as mkdir3, mkdtemp as mkdtemp2, open as open3, realpath as realpath6, rename as rename2, rm as rm2, stat as stat5, writeFile } from "node:fs/promises";
35302
35664
  import { delimiter as delimiter2, dirname as dirname5, isAbsolute as isAbsolute7, join as join9, relative as relative4, sep as sep4 } from "node:path";
35303
35665
 
35304
35666
  // src/agent-installation/verified-download.ts
@@ -35480,7 +35842,7 @@ async function readManifest(path2) {
35480
35842
  async function validateManagedAgentArchive(root, definition2, signal) {
35481
35843
  try {
35482
35844
  const rootPath = await realpath6(root);
35483
- const rootMetadata = await stat6(rootPath);
35845
+ const rootMetadata = await stat5(rootPath);
35484
35846
  if (!rootMetadata.isDirectory() || typeof process.getuid === "function" && rootMetadata.uid !== process.getuid()) {
35485
35847
  throw new Error("Managed Agent root is not user-owned");
35486
35848
  }
@@ -36443,7 +36805,7 @@ async function resolveDefaultWorkspace(path2) {
36443
36805
  try {
36444
36806
  await mkdir4(requestedWorkspace, { recursive: true, mode: 448 });
36445
36807
  const defaultWorkspace = await realpath7(requestedWorkspace);
36446
- const metadata = await stat7(defaultWorkspace);
36808
+ const metadata = await stat6(defaultWorkspace);
36447
36809
  if (!metadata.isDirectory()) {
36448
36810
  throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
36449
36811
  }
@@ -37626,7 +37988,7 @@ async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
37626
37988
  }
37627
37989
 
37628
37990
  // src/authorization/workspace-directory.ts
37629
- import { readdir as readdir2, realpath as realpath8, stat as stat8 } from "node:fs/promises";
37991
+ import { readdir as readdir2, realpath as realpath8, stat as stat7 } from "node:fs/promises";
37630
37992
  import { homedir as homedir2 } from "node:os";
37631
37993
  import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute10, join as join16, normalize as normalize3, relative as relative5 } from "node:path";
37632
37994
  var WorkspaceDirectoryListing = class {
@@ -37694,7 +38056,7 @@ var WorkspaceDirectoryService = class {
37694
38056
  try {
37695
38057
  const target = await realpath8(requested);
37696
38058
  signal.throwIfAborted();
37697
- const metadata = await stat8(target);
38059
+ const metadata = await stat7(target);
37698
38060
  signal.throwIfAborted();
37699
38061
  if (!isAbsolute10(target) || normalize3(target) !== target || !metadata.isDirectory()) {
37700
38062
  throw new LocalAuthorizationError("The selected location is not a directory");
@@ -41907,7 +42269,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41907
42269
  }
41908
42270
 
41909
42271
  // src/runtime.ts
41910
- import { mkdir as mkdir5, realpath as realpath9, stat as stat9 } from "node:fs/promises";
42272
+ import { mkdir as mkdir5, realpath as realpath9, stat as stat8 } from "node:fs/promises";
41911
42273
  import { dirname as dirname8, join as join18, resolve as resolve5 } from "node:path";
41912
42274
  var IDENTIFIER_PATTERN9 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
41913
42275
  var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{43}$/;
@@ -41977,7 +42339,7 @@ async function resolveWorkspace(path2) {
41977
42339
  try {
41978
42340
  await mkdir5(requested, { recursive: true, mode: 448 });
41979
42341
  const resolved = await realpath9(requested);
41980
- const metadata = await stat9(resolved);
42342
+ const metadata = await stat8(resolved);
41981
42343
  if (!metadata.isDirectory()) {
41982
42344
  throw new MobiusRuntimeConfigurationError("The Runtime workspace is not a directory");
41983
42345
  }