@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/runtime.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all2) => {
5
5
  };
6
6
 
7
7
  // src/runtime.ts
8
- import { mkdir as mkdir5, realpath as realpath9, stat as stat9 } from "node:fs/promises";
8
+ import { mkdir as mkdir5, realpath as realpath9, stat as stat8 } from "node:fs/promises";
9
9
  import { dirname as dirname8, join as join18, resolve as resolve5 } from "node:path";
10
10
 
11
11
  // src/agent-catalog/local-agent.ts
@@ -29061,7 +29061,7 @@ var titleBefore = {
29061
29061
  };
29062
29062
  function tokenizeDefinition(effects, ok2, nok) {
29063
29063
  const self = this;
29064
- let identifier3;
29064
+ let identifier2;
29065
29065
  return start;
29066
29066
  function start(code) {
29067
29067
  effects.enter("definition");
@@ -29080,7 +29080,7 @@ function tokenizeDefinition(effects, ok2, nok) {
29080
29080
  )(code);
29081
29081
  }
29082
29082
  function labelAfter(code) {
29083
- identifier3 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
29083
+ identifier2 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
29084
29084
  if (code === 58) {
29085
29085
  effects.enter("definitionMarker");
29086
29086
  effects.consume(code);
@@ -29114,7 +29114,7 @@ function tokenizeDefinition(effects, ok2, nok) {
29114
29114
  function afterWhitespace(code) {
29115
29115
  if (code === null || markdownLineEnding(code)) {
29116
29116
  effects.exit("definition");
29117
- self.parser.defined.push(identifier3);
29117
+ self.parser.defined.push(identifier2);
29118
29118
  return ok2(code);
29119
29119
  }
29120
29120
  return nok(code);
@@ -32949,6 +32949,7 @@ var SqliteAcpSessionStore = class {
32949
32949
 
32950
32950
  // src/acp/session-manager.ts
32951
32951
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
32952
+ var MAX_ACP_PROCESSES = 10;
32952
32953
  var MAX_PRE_SESSION_UPDATES = 100;
32953
32954
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
32954
32955
  var SESSION_CONTROL_COMMAND_ID = "session-control";
@@ -33007,6 +33008,91 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
33007
33008
  this.name = "RetryableAcpInitializationError";
33008
33009
  }
33009
33010
  };
33011
+ var AcpProcessCapacityLease = class {
33012
+ #releaseCapacity;
33013
+ #released = false;
33014
+ constructor(releaseCapacity) {
33015
+ this.#releaseCapacity = releaseCapacity;
33016
+ }
33017
+ release = () => {
33018
+ if (this.#released) {
33019
+ return;
33020
+ }
33021
+ this.#released = true;
33022
+ this.#releaseCapacity();
33023
+ };
33024
+ };
33025
+ var AcpProcessCapacityWaiter = class {
33026
+ completion = Promise.withResolvers();
33027
+ signal;
33028
+ constructor(signal) {
33029
+ this.signal = signal;
33030
+ }
33031
+ cancel = () => {
33032
+ try {
33033
+ this.signal.throwIfAborted();
33034
+ } catch (error62) {
33035
+ this.completion.reject(error62);
33036
+ }
33037
+ };
33038
+ };
33039
+ var AcpProcessCapacityLock = class {
33040
+ #locked = false;
33041
+ #waiters = [];
33042
+ acquire = async (signal) => {
33043
+ signal.throwIfAborted();
33044
+ if (!this.#locked) {
33045
+ this.#locked = true;
33046
+ return new AcpProcessCapacityLease(this.#release);
33047
+ }
33048
+ const waiter = new AcpProcessCapacityWaiter(signal);
33049
+ this.#waiters.push(waiter);
33050
+ signal.addEventListener("abort", waiter.cancel, { once: true });
33051
+ if (signal.aborted) {
33052
+ waiter.cancel();
33053
+ }
33054
+ try {
33055
+ return await waiter.completion.promise;
33056
+ } finally {
33057
+ signal.removeEventListener("abort", waiter.cancel);
33058
+ const index2 = this.#waiters.indexOf(waiter);
33059
+ if (index2 >= 0) {
33060
+ this.#waiters.splice(index2, 1);
33061
+ }
33062
+ }
33063
+ };
33064
+ #release = () => {
33065
+ while (this.#waiters.length > 0) {
33066
+ const waiter = this.#waiters.shift();
33067
+ if (waiter === void 0 || waiter.signal.aborted) {
33068
+ continue;
33069
+ }
33070
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
33071
+ return;
33072
+ }
33073
+ this.#locked = false;
33074
+ };
33075
+ };
33076
+ async function waitForAcpProcessCapacity(completion, signal) {
33077
+ signal.throwIfAborted();
33078
+ const cancelled = Promise.withResolvers();
33079
+ const cancel = () => {
33080
+ try {
33081
+ signal.throwIfAborted();
33082
+ } catch (error62) {
33083
+ cancelled.reject(error62);
33084
+ }
33085
+ };
33086
+ signal.addEventListener("abort", cancel, { once: true });
33087
+ if (signal.aborted) {
33088
+ cancel();
33089
+ }
33090
+ try {
33091
+ await Promise.race([completion, cancelled.promise]);
33092
+ } finally {
33093
+ signal.removeEventListener("abort", cancel);
33094
+ }
33095
+ }
33010
33096
  function readableWebStream(input2) {
33011
33097
  let streamOpen = true;
33012
33098
  return new ReadableStream({
@@ -34494,20 +34580,23 @@ var AcpProcessSession = class _AcpProcessSession {
34494
34580
  }
34495
34581
  };
34496
34582
  close = async () => {
34497
- await this.cancelPendingInteractions();
34498
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
34499
- try {
34500
- await this.#connection.agent.request(
34501
- methods6.agent.session.close,
34502
- { sessionId: this.#nativeSessionId },
34503
- {
34504
- cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
34505
- }
34506
- );
34507
- } catch {
34583
+ try {
34584
+ await this.cancelPendingInteractions();
34585
+ if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
34586
+ try {
34587
+ await this.#connection.agent.request(
34588
+ methods6.agent.session.close,
34589
+ { sessionId: this.#nativeSessionId },
34590
+ {
34591
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
34592
+ }
34593
+ );
34594
+ } catch {
34595
+ }
34508
34596
  }
34597
+ } finally {
34598
+ await this.closeProcess();
34509
34599
  }
34510
- await this.closeProcess();
34511
34600
  };
34512
34601
  closeProcess = async (capturedProcesses = []) => {
34513
34602
  try {
@@ -34614,6 +34703,31 @@ var AcpProcessSession = class _AcpProcessSession {
34614
34703
  }
34615
34704
  };
34616
34705
  };
34706
+ var AcpProcessEvictionCandidate = class {
34707
+ };
34708
+ var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
34709
+ };
34710
+ var FoundAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
34711
+ runtime;
34712
+ constructor(runtime) {
34713
+ super();
34714
+ this.runtime = runtime;
34715
+ }
34716
+ };
34717
+ var FoundAcpSessionProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
34718
+ sessionId;
34719
+ constructor(sessionId, runtime) {
34720
+ super(runtime);
34721
+ this.sessionId = sessionId;
34722
+ }
34723
+ };
34724
+ var FoundAcpNativeBrowserProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
34725
+ sessionId;
34726
+ constructor(sessionId, runtime) {
34727
+ super(runtime);
34728
+ this.sessionId = sessionId;
34729
+ }
34730
+ };
34617
34731
  var AcpSessionManager = class {
34618
34732
  #activeCommandIds = /* @__PURE__ */ new Map();
34619
34733
  #agentSettingsObserver = new NullAcpSessionObserver();
@@ -34622,10 +34736,18 @@ var AcpSessionManager = class {
34622
34736
  #nativeBrowserPreparing = /* @__PURE__ */ new Map();
34623
34737
  #nativeBrowserSessions = /* @__PURE__ */ new Map();
34624
34738
  #nativeBrowserStore = new MemoryAcpSessionStore();
34739
+ #nativeBrowserUseCounts = /* @__PURE__ */ new Map();
34625
34740
  #activeSessionIds = /* @__PURE__ */ new Set();
34626
34741
  #cancellationRequests = /* @__PURE__ */ new Map();
34627
34742
  #preparing = /* @__PURE__ */ new Map();
34743
+ #processCapacityChanged = Promise.withResolvers();
34744
+ #processCapacityLock = new AcpProcessCapacityLock();
34745
+ #retainedProcesses = /* @__PURE__ */ new Map();
34746
+ #retiringProcessCount = 0;
34747
+ #sessionUseCounts = /* @__PURE__ */ new Map();
34628
34748
  #sessions = /* @__PURE__ */ new Map();
34749
+ #startingProcessCount = 0;
34750
+ #transientProcessCount = 0;
34629
34751
  #store;
34630
34752
  #observer;
34631
34753
  constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore()) {
@@ -34635,18 +34757,230 @@ var AcpSessionManager = class {
34635
34757
  setObserver = (observer) => {
34636
34758
  this.#observer = observer;
34637
34759
  };
34760
+ #notifyProcessCapacityChanged() {
34761
+ const changed = this.#processCapacityChanged;
34762
+ this.#processCapacityChanged = Promise.withResolvers();
34763
+ changed.resolve();
34764
+ }
34765
+ #touchSession(sessionId) {
34766
+ const runtime = this.#sessions.get(sessionId);
34767
+ if (runtime === void 0) {
34768
+ return;
34769
+ }
34770
+ this.#touchProcess(runtime);
34771
+ }
34772
+ #touchExpectedSession(sessionId, expected) {
34773
+ if (this.#sessions.get(sessionId) !== expected) {
34774
+ return;
34775
+ }
34776
+ this.#touchProcess(expected);
34777
+ }
34778
+ #touchNativeBrowserSession(sessionId) {
34779
+ const runtime = this.#nativeBrowserSessions.get(sessionId);
34780
+ if (runtime === void 0) {
34781
+ return;
34782
+ }
34783
+ this.#touchProcess(runtime);
34784
+ }
34785
+ #touchExpectedNativeBrowserSession(sessionId, expected) {
34786
+ if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
34787
+ return;
34788
+ }
34789
+ this.#touchProcess(expected);
34790
+ }
34791
+ #touchProcess(runtime) {
34792
+ const retained = this.#retainedProcesses.get(runtime);
34793
+ if (retained === void 0) {
34794
+ return;
34795
+ }
34796
+ this.#retainedProcesses.delete(runtime);
34797
+ this.#retainedProcesses.set(runtime, retained);
34798
+ }
34799
+ #beginSessionUse(sessionId) {
34800
+ this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
34801
+ this.#touchSession(sessionId);
34802
+ }
34803
+ #endSessionUse(sessionId) {
34804
+ const count = this.#sessionUseCounts.get(sessionId) ?? 0;
34805
+ if (count <= 1) {
34806
+ this.#sessionUseCounts.delete(sessionId);
34807
+ } else {
34808
+ this.#sessionUseCounts.set(sessionId, count - 1);
34809
+ }
34810
+ this.#touchSession(sessionId);
34811
+ this.#notifyProcessCapacityChanged();
34812
+ }
34813
+ #beginNativeBrowserUse(sessionId) {
34814
+ this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
34815
+ this.#touchNativeBrowserSession(sessionId);
34816
+ }
34817
+ #endNativeBrowserUse(sessionId) {
34818
+ const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
34819
+ if (count <= 1) {
34820
+ this.#nativeBrowserUseCounts.delete(sessionId);
34821
+ } else {
34822
+ this.#nativeBrowserUseCounts.set(sessionId, count - 1);
34823
+ }
34824
+ this.#touchNativeBrowserSession(sessionId);
34825
+ this.#notifyProcessCapacityChanged();
34826
+ }
34827
+ #isNativeSessionOperationActive(sessionId) {
34828
+ const stored = this.#store.read(sessionId);
34829
+ return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
34830
+ }
34831
+ #leastRecentlyUsedEvictionCandidate() {
34832
+ for (const candidate of this.#retainedProcesses.values()) {
34833
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
34834
+ 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)) {
34835
+ continue;
34836
+ }
34837
+ return candidate;
34838
+ }
34839
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate && !this.#nativeBrowserPreparing.has(candidate.sessionId) && (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
34840
+ return candidate;
34841
+ }
34842
+ }
34843
+ return new MissingAcpProcessEvictionCandidate();
34844
+ }
34845
+ #ownedProcessCount() {
34846
+ return this.#retainedProcesses.size + this.#startingProcessCount + this.#transientProcessCount + this.#retiringProcessCount;
34847
+ }
34848
+ async #retireProcess(runtime, retained, close) {
34849
+ if (retained) {
34850
+ this.#retainedProcesses.delete(runtime);
34851
+ this.#retiringProcessCount += 1;
34852
+ }
34853
+ try {
34854
+ await close();
34855
+ } finally {
34856
+ if (retained) {
34857
+ this.#retiringProcessCount -= 1;
34858
+ this.#notifyProcessCapacityChanged();
34859
+ }
34860
+ }
34861
+ }
34862
+ async #retireSessionProcess(sessionId, runtime, close) {
34863
+ const retained = this.#sessions.get(sessionId) === runtime;
34864
+ if (retained) {
34865
+ this.#sessions.delete(sessionId);
34866
+ }
34867
+ await this.#retireProcess(runtime, retained, close);
34868
+ }
34869
+ async #retireNativeBrowserProcess(sessionId, runtime, close) {
34870
+ const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
34871
+ if (retained) {
34872
+ this.#nativeBrowserSessions.delete(sessionId);
34873
+ this.#nativeBrowserStore.remove(sessionId);
34874
+ }
34875
+ await this.#retireProcess(runtime, retained, close);
34876
+ }
34877
+ async #reserveProcessCapacity(signal) {
34878
+ const lease = await this.#processCapacityLock.acquire(signal);
34879
+ try {
34880
+ for (; ; ) {
34881
+ signal.throwIfAborted();
34882
+ if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
34883
+ this.#startingProcessCount += 1;
34884
+ return;
34885
+ }
34886
+ const candidate = this.#leastRecentlyUsedEvictionCandidate();
34887
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
34888
+ await this.#retireSessionProcess(
34889
+ candidate.sessionId,
34890
+ candidate.runtime,
34891
+ async () => await candidate.runtime.close()
34892
+ );
34893
+ continue;
34894
+ }
34895
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
34896
+ await this.#retireNativeBrowserProcess(
34897
+ candidate.sessionId,
34898
+ candidate.runtime,
34899
+ async () => await candidate.runtime.close()
34900
+ );
34901
+ continue;
34902
+ }
34903
+ const changed = this.#processCapacityChanged.promise;
34904
+ await waitForAcpProcessCapacity(changed, signal);
34905
+ }
34906
+ } finally {
34907
+ lease.release();
34908
+ }
34909
+ }
34910
+ async #startRetainedSessionProcess(options, start) {
34911
+ await this.#reserveProcessCapacity(options.signal);
34912
+ try {
34913
+ const runtime = await start();
34914
+ this.#startingProcessCount -= 1;
34915
+ this.#sessions.set(options.sessionId, runtime);
34916
+ this.#retainedProcesses.set(
34917
+ runtime,
34918
+ new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime)
34919
+ );
34920
+ this.#notifyProcessCapacityChanged();
34921
+ return runtime;
34922
+ } catch (error62) {
34923
+ this.#startingProcessCount -= 1;
34924
+ this.#notifyProcessCapacityChanged();
34925
+ throw error62;
34926
+ }
34927
+ }
34928
+ async #startRetainedNativeBrowserProcess(options, start) {
34929
+ await this.#reserveProcessCapacity(options.signal);
34930
+ try {
34931
+ const runtime = await start();
34932
+ this.#startingProcessCount -= 1;
34933
+ this.#nativeBrowserSessions.set(options.sessionId, runtime);
34934
+ this.#retainedProcesses.set(
34935
+ runtime,
34936
+ new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime)
34937
+ );
34938
+ this.#notifyProcessCapacityChanged();
34939
+ return runtime;
34940
+ } catch (error62) {
34941
+ this.#startingProcessCount -= 1;
34942
+ this.#notifyProcessCapacityChanged();
34943
+ throw error62;
34944
+ }
34945
+ }
34946
+ async #runWithTransientProcess(signal, start, operation, close) {
34947
+ await this.#reserveProcessCapacity(signal);
34948
+ let runtime;
34949
+ try {
34950
+ runtime = await start();
34951
+ } catch (error62) {
34952
+ this.#startingProcessCount -= 1;
34953
+ this.#notifyProcessCapacityChanged();
34954
+ throw error62;
34955
+ }
34956
+ this.#startingProcessCount -= 1;
34957
+ this.#transientProcessCount += 1;
34958
+ this.#notifyProcessCapacityChanged();
34959
+ try {
34960
+ return await operation(runtime);
34961
+ } finally {
34962
+ try {
34963
+ await close(runtime);
34964
+ } finally {
34965
+ this.#transientProcessCount -= 1;
34966
+ this.#notifyProcessCapacityChanged();
34967
+ }
34968
+ }
34969
+ }
34638
34970
  async #startNativeBrowserPreparation(options) {
34639
34971
  const operation = (async () => {
34640
34972
  try {
34641
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
34973
+ return await this.#startRetainedNativeBrowserProcess(
34642
34974
  options,
34643
- () => this.#nativeBrowserObserver,
34644
- this.#nativeBrowserStore
34975
+ async () => await AcpProcessSession.startNativeSessionBrowser(
34976
+ options,
34977
+ () => this.#nativeBrowserObserver,
34978
+ this.#nativeBrowserStore
34979
+ )
34645
34980
  );
34646
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
34647
- return runtime;
34648
34981
  } finally {
34649
34982
  this.#nativeBrowserPreparing.delete(options.sessionId);
34983
+ this.#notifyProcessCapacityChanged();
34650
34984
  }
34651
34985
  })();
34652
34986
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -34655,18 +34989,18 @@ var AcpSessionManager = class {
34655
34989
  async #replaceNativeBrowserPreparation(existing, options) {
34656
34990
  const operation = (async () => {
34657
34991
  try {
34658
- this.#nativeBrowserSessions.delete(options.sessionId);
34659
- await existing.close();
34660
- this.#nativeBrowserStore.remove(options.sessionId);
34661
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
34992
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
34993
+ return await this.#startRetainedNativeBrowserProcess(
34662
34994
  options,
34663
- () => this.#nativeBrowserObserver,
34664
- this.#nativeBrowserStore
34995
+ async () => await AcpProcessSession.startNativeSessionBrowser(
34996
+ options,
34997
+ () => this.#nativeBrowserObserver,
34998
+ this.#nativeBrowserStore
34999
+ )
34665
35000
  );
34666
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
34667
- return runtime;
34668
35001
  } finally {
34669
35002
  this.#nativeBrowserPreparing.delete(options.sessionId);
35003
+ this.#notifyProcessCapacityChanged();
34670
35004
  }
34671
35005
  })();
34672
35006
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -34675,11 +35009,13 @@ var AcpSessionManager = class {
34675
35009
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
34676
35010
  const operation = (async () => {
34677
35011
  try {
34678
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
34679
- this.#sessions.set(options.sessionId, runtime);
34680
- return runtime;
35012
+ return await this.#startRetainedSessionProcess(
35013
+ options,
35014
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35015
+ );
34681
35016
  } finally {
34682
35017
  this.#preparing.delete(options.sessionId);
35018
+ this.#notifyProcessCapacityChanged();
34683
35019
  }
34684
35020
  })();
34685
35021
  this.#preparing.set(options.sessionId, operation);
@@ -34688,17 +35024,19 @@ var AcpSessionManager = class {
34688
35024
  async #startSessionForkAtTurnPreparation(options, sourceNativeSessionId, forkPoint) {
34689
35025
  const operation = (async () => {
34690
35026
  try {
34691
- const runtime = await AcpProcessSession.startSessionForkAtTurn(
35027
+ return await this.#startRetainedSessionProcess(
34692
35028
  options,
34693
- sourceNativeSessionId,
34694
- forkPoint,
34695
- () => this.#observer,
34696
- this.#store
35029
+ async () => await AcpProcessSession.startSessionForkAtTurn(
35030
+ options,
35031
+ sourceNativeSessionId,
35032
+ forkPoint,
35033
+ () => this.#observer,
35034
+ this.#store
35035
+ )
34697
35036
  );
34698
- this.#sessions.set(options.sessionId, runtime);
34699
- return runtime;
34700
35037
  } finally {
34701
35038
  this.#preparing.delete(options.sessionId);
35039
+ this.#notifyProcessCapacityChanged();
34702
35040
  }
34703
35041
  })();
34704
35042
  this.#preparing.set(options.sessionId, operation);
@@ -34707,14 +35045,19 @@ var AcpSessionManager = class {
34707
35045
  async #replacePreparation(existing, options, metrics) {
34708
35046
  const operation = (async () => {
34709
35047
  try {
34710
- this.#sessions.delete(options.sessionId);
34711
- await metrics.measure("runtime-replacement-close", async () => await existing.close());
35048
+ await this.#retireSessionProcess(
35049
+ options.sessionId,
35050
+ existing,
35051
+ async () => await metrics.measure("runtime-replacement-close", async () => await existing.close())
35052
+ );
34712
35053
  this.#store.remove(options.sessionId);
34713
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
34714
- this.#sessions.set(options.sessionId, runtime);
34715
- return runtime;
35054
+ return await this.#startRetainedSessionProcess(
35055
+ options,
35056
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35057
+ );
34716
35058
  } finally {
34717
35059
  this.#preparing.delete(options.sessionId);
35060
+ this.#notifyProcessCapacityChanged();
34718
35061
  }
34719
35062
  })();
34720
35063
  this.#preparing.set(options.sessionId, operation);
@@ -34724,10 +35067,12 @@ var AcpSessionManager = class {
34724
35067
  const desiredConfigOptions = existing.prepared().configOptions;
34725
35068
  const operation = (async () => {
34726
35069
  try {
34727
- this.#sessions.delete(options.sessionId);
34728
- await existing.close();
35070
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
34729
35071
  this.#store.remove(options.sessionId);
34730
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
35072
+ const runtime = await this.#startRetainedSessionProcess(
35073
+ options,
35074
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
35075
+ );
34731
35076
  try {
34732
35077
  for (const desired of desiredConfigOptions) {
34733
35078
  const current = runtime.prepared().configOptions.find((option) => option.id === desired.id);
@@ -34759,14 +35104,14 @@ var AcpSessionManager = class {
34759
35104
  }
34760
35105
  }
34761
35106
  } catch (error62) {
34762
- await runtime.close();
35107
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
34763
35108
  this.#store.remove(options.sessionId);
34764
35109
  throw error62;
34765
35110
  }
34766
- this.#sessions.set(options.sessionId, runtime);
34767
35111
  return runtime;
34768
35112
  } finally {
34769
35113
  this.#preparing.delete(options.sessionId);
35114
+ this.#notifyProcessCapacityChanged();
34770
35115
  }
34771
35116
  })();
34772
35117
  this.#preparing.set(options.sessionId, operation);
@@ -34788,6 +35133,7 @@ var AcpSessionManager = class {
34788
35133
  if (pending !== void 0) {
34789
35134
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
34790
35135
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35136
+ this.#touchExpectedSession(options.sessionId, runtime2);
34791
35137
  return runtime2.prepared();
34792
35138
  }
34793
35139
  return await this.prepareSession(options, metrics);
@@ -34795,6 +35141,7 @@ var AcpSessionManager = class {
34795
35141
  const existing = this.#sessions.get(options.sessionId);
34796
35142
  if (existing !== void 0) {
34797
35143
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35144
+ this.#touchExpectedSession(options.sessionId, existing);
34798
35145
  return existing.prepared();
34799
35146
  }
34800
35147
  if (!existing.canRebind()) {
@@ -34815,22 +35162,24 @@ var AcpSessionManager = class {
34815
35162
  * authoritative settings. Its identity and store are private to this
34816
35163
  * operation and never become a Mobius Session.
34817
35164
  */
34818
- inspectAgentSettings = async (options) => {
34819
- const runtime = await AcpProcessSession.start(
35165
+ inspectAgentSettings = async (options) => await this.#runWithTransientProcess(
35166
+ options.signal,
35167
+ async () => await AcpProcessSession.start(
34820
35168
  {
34821
35169
  ...options,
34822
35170
  sessionId: `agent-settings-${crypto.randomUUID()}`
34823
35171
  },
34824
35172
  () => this.#agentSettingsObserver,
34825
35173
  new MemoryAcpSessionStore()
34826
- );
34827
- try {
35174
+ ),
35175
+ (runtime) => {
34828
35176
  const prepared = runtime.prepared();
34829
- return new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions);
34830
- } finally {
34831
- await runtime.close();
34832
- }
34833
- };
35177
+ return Promise.resolve(
35178
+ new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions)
35179
+ );
35180
+ },
35181
+ async (runtime) => await runtime.close()
35182
+ );
34834
35183
  /**
34835
35184
  * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
34836
35185
  * Use inspectAgentSettings for Agent-scoped settings discovery.
@@ -34839,18 +35188,20 @@ var AcpSessionManager = class {
34839
35188
  if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
34840
35189
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
34841
35190
  }
34842
- const runtime = await this.#startPreparation(options, metrics);
35191
+ this.#beginSessionUse(options.sessionId);
34843
35192
  try {
34844
- return runtime.prepared();
34845
- } finally {
34846
- if (this.#sessions.get(options.sessionId) === runtime) {
34847
- this.#sessions.delete(options.sessionId);
34848
- }
35193
+ const runtime = await this.#startPreparation(options, metrics);
34849
35194
  try {
34850
- await runtime.close();
35195
+ return runtime.prepared();
34851
35196
  } finally {
34852
- this.#store.remove(options.sessionId);
35197
+ try {
35198
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
35199
+ } finally {
35200
+ this.#store.remove(options.sessionId);
35201
+ }
34853
35202
  }
35203
+ } finally {
35204
+ this.#endSessionUse(options.sessionId);
34854
35205
  }
34855
35206
  };
34856
35207
  prepareExecutionSession = async (options) => {
@@ -34871,6 +35222,7 @@ var AcpSessionManager = class {
34871
35222
  );
34872
35223
  }
34873
35224
  if (existing.usesEnvironment(options.agent.environment)) {
35225
+ this.#touchExpectedSession(options.sessionId, existing);
34874
35226
  return existing.prepared();
34875
35227
  }
34876
35228
  if (!existing.canRebind()) {
@@ -34887,6 +35239,7 @@ var AcpSessionManager = class {
34887
35239
  if (pending !== void 0) {
34888
35240
  const runtime2 = await pending;
34889
35241
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35242
+ this.#touchExpectedNativeBrowserSession(options.sessionId, runtime2);
34890
35243
  return runtime2.prepared();
34891
35244
  }
34892
35245
  return await this.prepareNativeSessionBrowser(options);
@@ -34894,6 +35247,7 @@ var AcpSessionManager = class {
34894
35247
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
34895
35248
  if (existing !== void 0) {
34896
35249
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35250
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
34897
35251
  return existing.prepared();
34898
35252
  }
34899
35253
  if (!existing.canRebind()) {
@@ -34910,8 +35264,13 @@ var AcpSessionManager = class {
34910
35264
  return runtime.prepared();
34911
35265
  };
34912
35266
  configureSession = async (options) => {
34913
- const runtime = await this.ensureSession(options);
34914
- return await runtime.configure(options);
35267
+ this.#beginSessionUse(options.sessionId);
35268
+ try {
35269
+ const runtime = await this.ensureSession(options);
35270
+ return await runtime.configure(options);
35271
+ } finally {
35272
+ this.#endSessionUse(options.sessionId);
35273
+ }
34915
35274
  };
34916
35275
  cancelPrompt = async (sessionId) => {
34917
35276
  const existing = this.#cancellationRequests.get(sessionId);
@@ -34927,6 +35286,8 @@ var AcpSessionManager = class {
34927
35286
  } finally {
34928
35287
  if (this.#sessions.get(sessionId) === runtime) {
34929
35288
  this.#sessions.delete(sessionId);
35289
+ this.#retainedProcesses.delete(runtime);
35290
+ this.#notifyProcessCapacityChanged();
34930
35291
  }
34931
35292
  }
34932
35293
  }
@@ -35016,10 +35377,7 @@ var AcpSessionManager = class {
35016
35377
  return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
35017
35378
  } catch (error62) {
35018
35379
  if (this.#cancellationRequests.has(options.sessionId)) {
35019
- if (this.#sessions.get(options.sessionId) === runtime) {
35020
- this.#sessions.delete(options.sessionId);
35021
- }
35022
- await runtime.closeProcess();
35380
+ await this.#cancellationRequests.get(options.sessionId);
35023
35381
  return { stopReason: "cancelled" };
35024
35382
  }
35025
35383
  throw error62;
@@ -35027,8 +35385,11 @@ var AcpSessionManager = class {
35027
35385
  } catch (error62) {
35028
35386
  const failedRuntime = this.#sessions.get(options.sessionId);
35029
35387
  if (failedRuntime !== void 0) {
35030
- this.#sessions.delete(options.sessionId);
35031
- await failedRuntime.close();
35388
+ await this.#retireSessionProcess(
35389
+ options.sessionId,
35390
+ failedRuntime,
35391
+ async () => await failedRuntime.close()
35392
+ );
35032
35393
  }
35033
35394
  if (this.#cancellationRequests.has(options.sessionId)) {
35034
35395
  return { stopReason: "cancelled" };
@@ -35049,6 +35410,8 @@ var AcpSessionManager = class {
35049
35410
  this.#activeCommandIds.delete(options.sessionId);
35050
35411
  }
35051
35412
  this.#cancellationRequests.delete(options.sessionId);
35413
+ this.#touchSession(options.sessionId);
35414
+ this.#notifyProcessCapacityChanged();
35052
35415
  }
35053
35416
  }
35054
35417
  };
@@ -35067,11 +35430,16 @@ var AcpSessionManager = class {
35067
35430
  await runtime.respondElicitation(options);
35068
35431
  };
35069
35432
  close = async () => {
35070
- const sessions = [...this.#sessions.values()];
35071
- const nativeBrowserSessions = [...this.#nativeBrowserSessions.values()];
35072
- this.#sessions.clear();
35073
- this.#nativeBrowserSessions.clear();
35074
- await Promise.all([...sessions, ...nativeBrowserSessions].map(async (session) => await session.close()));
35433
+ const sessions = [...this.#sessions.entries()];
35434
+ const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
35435
+ await Promise.all([
35436
+ ...sessions.map(
35437
+ async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
35438
+ ),
35439
+ ...nativeBrowserSessions.map(
35440
+ async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
35441
+ )
35442
+ ]);
35075
35443
  };
35076
35444
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
35077
35445
  ensureSession = async (options) => {
@@ -35084,6 +35452,7 @@ var AcpSessionManager = class {
35084
35452
  "session_identity_mismatch"
35085
35453
  );
35086
35454
  }
35455
+ this.#touchExpectedSession(options.sessionId, existing);
35087
35456
  return existing;
35088
35457
  }
35089
35458
  await this.prepareSession(options);
@@ -35103,6 +35472,7 @@ var AcpSessionManager = class {
35103
35472
  "session_identity_mismatch"
35104
35473
  );
35105
35474
  }
35475
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
35106
35476
  return existing;
35107
35477
  }
35108
35478
  await this.prepareNativeSessionBrowser(options);
@@ -35112,7 +35482,14 @@ var AcpSessionManager = class {
35112
35482
  }
35113
35483
  return started;
35114
35484
  }
35115
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
35485
+ listNativeSessions = async (options, cursor) => {
35486
+ this.#beginNativeBrowserUse(options.sessionId);
35487
+ try {
35488
+ return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
35489
+ } finally {
35490
+ this.#endNativeBrowserUse(options.sessionId);
35491
+ }
35492
+ };
35116
35493
  previewNativeSession = async (options, nativeSessionId) => {
35117
35494
  const key = `${options.agent.id}:${nativeSessionId}`;
35118
35495
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
@@ -35125,17 +35502,19 @@ var AcpSessionManager = class {
35125
35502
  }
35126
35503
  this.#nativeOperations.add(key);
35127
35504
  try {
35128
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35129
- options,
35130
- () => this.#nativeBrowserObserver,
35131
- new MemoryAcpSessionStore()
35505
+ return await this.#runWithTransientProcess(
35506
+ options.signal,
35507
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35508
+ options,
35509
+ () => this.#nativeBrowserObserver,
35510
+ new MemoryAcpSessionStore()
35511
+ ),
35512
+ async (runtime) => {
35513
+ runtime.selectNativeSession(nativeSessionId);
35514
+ return await runtime.loadHistory(options.signal);
35515
+ },
35516
+ async (runtime) => await runtime.closeProcess()
35132
35517
  );
35133
- try {
35134
- runtime.selectNativeSession(nativeSessionId);
35135
- return await runtime.loadHistory(options.signal);
35136
- } finally {
35137
- await runtime.closeProcess();
35138
- }
35139
35518
  } finally {
35140
35519
  this.#nativeOperations.delete(key);
35141
35520
  }
@@ -35155,36 +35534,46 @@ var AcpSessionManager = class {
35155
35534
  }
35156
35535
  const existing = linked[0];
35157
35536
  if (origin.kind === "import" && existing !== void 0) {
35158
- const runtime = await this.ensureSession({
35159
- ...options,
35160
- sessionId: existing.sessionId
35161
- });
35162
- if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
35163
- throw new AcpExecutionError(
35164
- "Wait for the native session's running operation to finish",
35165
- {},
35166
- "session_busy"
35167
- );
35168
- }
35169
- this.#nativeOperations.add(key);
35537
+ this.#beginSessionUse(existing.sessionId);
35170
35538
  try {
35171
- const history = await runtime.loadHistory(options.signal);
35172
- return {
35173
- prepared: runtime.prepared(),
35174
- sessionId: existing.sessionId,
35175
- history
35176
- };
35177
- } catch (error62) {
35178
- this.#sessions.delete(existing.sessionId);
35179
- await runtime.closeProcess();
35180
- throw error62;
35539
+ const runtime = await this.ensureSession({
35540
+ ...options,
35541
+ sessionId: existing.sessionId
35542
+ });
35543
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
35544
+ throw new AcpExecutionError(
35545
+ "Wait for the native session's running operation to finish",
35546
+ {},
35547
+ "session_busy"
35548
+ );
35549
+ }
35550
+ this.#nativeOperations.add(key);
35551
+ try {
35552
+ const history = await runtime.loadHistory(options.signal);
35553
+ return {
35554
+ prepared: runtime.prepared(),
35555
+ sessionId: existing.sessionId,
35556
+ history
35557
+ };
35558
+ } catch (error62) {
35559
+ await this.#retireSessionProcess(
35560
+ existing.sessionId,
35561
+ runtime,
35562
+ async () => await runtime.closeProcess()
35563
+ );
35564
+ throw error62;
35565
+ } finally {
35566
+ this.#nativeOperations.delete(key);
35567
+ this.#notifyProcessCapacityChanged();
35568
+ }
35181
35569
  } finally {
35182
- this.#nativeOperations.delete(key);
35570
+ this.#endSessionUse(existing.sessionId);
35183
35571
  }
35184
35572
  }
35185
35573
  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) {
35186
35574
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
35187
35575
  }
35576
+ this.#beginSessionUse(options.sessionId);
35188
35577
  this.#nativeOperations.add(key);
35189
35578
  try {
35190
35579
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -35198,23 +35587,23 @@ var AcpSessionManager = class {
35198
35587
  history
35199
35588
  };
35200
35589
  } catch (error62) {
35201
- this.#sessions.delete(options.sessionId);
35202
35590
  this.#store.remove(options.sessionId);
35203
- await runtime.closeProcess();
35591
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
35204
35592
  throw error62;
35205
35593
  } finally {
35206
35594
  this.#nativeOperations.delete(openedKey);
35595
+ this.#notifyProcessCapacityChanged();
35207
35596
  }
35208
35597
  } catch (error62) {
35209
35598
  this.#store.remove(options.sessionId);
35210
35599
  const runtime = this.#sessions.get(options.sessionId);
35211
- this.#sessions.delete(options.sessionId);
35212
35600
  if (runtime !== void 0) {
35213
- await runtime.closeProcess();
35601
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
35214
35602
  }
35215
35603
  throw error62;
35216
35604
  } finally {
35217
35605
  this.#nativeOperations.delete(key);
35606
+ this.#endSessionUse(options.sessionId);
35218
35607
  }
35219
35608
  };
35220
35609
  forkSessionAtTurn = async (options, sourceSessionId, forkPoint) => {
@@ -35252,6 +35641,7 @@ var AcpSessionManager = class {
35252
35641
  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) {
35253
35642
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
35254
35643
  }
35644
+ this.#beginSessionUse(options.sessionId);
35255
35645
  this.#nativeOperations.add(key);
35256
35646
  try {
35257
35647
  const runtime = await this.#startSessionForkAtTurnPreparation(
@@ -35268,48 +35658,58 @@ var AcpSessionManager = class {
35268
35658
  sessionId: options.sessionId
35269
35659
  };
35270
35660
  } catch (error62) {
35271
- this.#sessions.delete(options.sessionId);
35272
35661
  this.#store.remove(options.sessionId);
35273
- await runtime.closeProcess();
35662
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
35274
35663
  throw error62;
35275
35664
  } finally {
35276
35665
  this.#nativeOperations.delete(openedKey);
35666
+ this.#notifyProcessCapacityChanged();
35277
35667
  }
35278
35668
  } finally {
35279
35669
  this.#nativeOperations.delete(key);
35670
+ this.#endSessionUse(options.sessionId);
35280
35671
  }
35281
35672
  };
35282
35673
  deleteNativeSession = async (options, nativeSessionId) => {
35283
- const runtime = await this.#ensureNativeSessionBrowser(options);
35284
- const key = `${options.agent.id}:${nativeSessionId}`;
35285
- const linked = this.#store.findNative(options.agent.id, nativeSessionId);
35286
- if (this.#nativeOperations.has(key) || linked.some((entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
35287
- throw new AcpExecutionError(
35288
- "Wait for the native session's running operation to finish",
35289
- {},
35290
- "session_busy"
35291
- );
35292
- }
35293
- this.#nativeOperations.add(key);
35674
+ this.#beginNativeBrowserUse(options.sessionId);
35294
35675
  try {
35295
- for (const entry of linked) {
35296
- const active = this.#sessions.get(entry.sessionId);
35297
- if (active !== void 0 && active !== runtime) {
35298
- this.#sessions.delete(entry.sessionId);
35299
- await active.close();
35676
+ const runtime = await this.#ensureNativeSessionBrowser(options);
35677
+ const key = `${options.agent.id}:${nativeSessionId}`;
35678
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
35679
+ if (this.#nativeOperations.has(key) || linked.some(
35680
+ (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
35681
+ )) {
35682
+ throw new AcpExecutionError(
35683
+ "Wait for the native session's running operation to finish",
35684
+ {},
35685
+ "session_busy"
35686
+ );
35687
+ }
35688
+ this.#nativeOperations.add(key);
35689
+ try {
35690
+ for (const entry of linked) {
35691
+ const active = this.#sessions.get(entry.sessionId);
35692
+ if (active !== void 0 && active !== runtime) {
35693
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
35694
+ }
35300
35695
  }
35696
+ options.signal.throwIfAborted();
35697
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
35698
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
35699
+ if (runtime.nativeSessionId() === nativeSessionId) {
35700
+ await this.#retireNativeBrowserProcess(
35701
+ options.sessionId,
35702
+ runtime,
35703
+ async () => await runtime.close()
35704
+ );
35705
+ }
35706
+ return deleted;
35707
+ } finally {
35708
+ this.#nativeOperations.delete(key);
35709
+ this.#notifyProcessCapacityChanged();
35301
35710
  }
35302
- options.signal.throwIfAborted();
35303
- await runtime.deleteNativeSession(nativeSessionId, options.signal);
35304
- const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
35305
- if (runtime.nativeSessionId() === nativeSessionId) {
35306
- this.#nativeBrowserSessions.delete(options.sessionId);
35307
- this.#nativeBrowserStore.remove(options.sessionId);
35308
- await runtime.close();
35309
- }
35310
- return deleted;
35311
35711
  } finally {
35312
- this.#nativeOperations.delete(key);
35712
+ this.#endNativeBrowserUse(options.sessionId);
35313
35713
  }
35314
35714
  };
35315
35715
  };
@@ -36411,21 +36811,8 @@ var WorkspaceDirectoryService = class {
36411
36811
 
36412
36812
  // src/bots/local-bot-grant-store.ts
36413
36813
  import { createHash as createHash3, randomUUID } from "node:crypto";
36414
- import { stat as stat7 } from "node:fs/promises";
36415
36814
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
36416
36815
  var LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS = 90 * 24 * 60 * 60 * 1e3;
36417
- var identifier2 = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
36418
- var savedApprovalSchema = external_exports.object({
36419
- local_grant_id: identifier2,
36420
- bot_id: identifier2,
36421
- binding_id: identifier2,
36422
- binding_revision: external_exports.number().int().positive(),
36423
- agent_ref: identifier2,
36424
- workspace_ref: external_exports.string().min(1).max(2048),
36425
- revocation_epoch: external_exports.number().int().nonnegative(),
36426
- agent_identity_digest: external_exports.string().regex(/^[a-f0-9]{64}$/),
36427
- workspace_identity_digest: external_exports.string().regex(/^[a-f0-9]{64}$/)
36428
- }).readonly();
36429
36816
  var LocalBotAuthorizationError = class extends Error {
36430
36817
  code;
36431
36818
  constructor(code, message, options = {}) {
@@ -36480,19 +36867,8 @@ function agentDigest(agent) {
36480
36867
  })
36481
36868
  );
36482
36869
  }
36483
- async function workspaceDigest(path2) {
36484
- const metadata = await stat7(path2);
36485
- if (!metadata.isDirectory()) {
36486
- throw new LocalBotAuthorizationError("binding_incompatible", "The Bot workspace is not a directory");
36487
- }
36488
- return digest(
36489
- JSON.stringify({
36490
- changedAtMilliseconds: metadata.ctimeMs,
36491
- device: metadata.dev,
36492
- inode: metadata.ino,
36493
- path: path2
36494
- })
36495
- );
36870
+ function workspaceDigest(path2) {
36871
+ return digest(path2);
36496
36872
  }
36497
36873
  function exactTargets(left, right) {
36498
36874
  if (left.length !== right.length) {
@@ -36526,6 +36902,16 @@ function rowInteger(row, key) {
36526
36902
  }
36527
36903
  return value;
36528
36904
  }
36905
+ function rowHasInteger(row, key) {
36906
+ const value = Reflect.get(row, key);
36907
+ if (value === null) {
36908
+ return false;
36909
+ }
36910
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
36911
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
36912
+ }
36913
+ return true;
36914
+ }
36529
36915
  function parseTargets(encoded) {
36530
36916
  let value;
36531
36917
  try {
@@ -36549,17 +36935,6 @@ function parseSessionConfigurations(encoded) {
36549
36935
  }
36550
36936
  var LocalBotGrantStore = class {
36551
36937
  #database;
36552
- static containsBot = (path2, botId) => {
36553
- const database = new DatabaseSync3(path2, { readOnly: true });
36554
- try {
36555
- if (database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_bot_grants'").get() === void 0) {
36556
- return false;
36557
- }
36558
- return database.prepare("SELECT local_grant_id FROM local_bot_grants WHERE bot_id = ? LIMIT 1").get(botId) !== void 0;
36559
- } finally {
36560
- database.close();
36561
- }
36562
- };
36563
36938
  constructor(path2) {
36564
36939
  this.#database = new DatabaseSync3(path2);
36565
36940
  this.#database.exec(`
@@ -36597,78 +36972,6 @@ var LocalBotGrantStore = class {
36597
36972
  ) STRICT;
36598
36973
  `);
36599
36974
  }
36600
- /** Only the local CLI may invoke this explicit approval transition. */
36601
- reapprove = async (botId, catalog, directories, bindingAuthorityId, now, signal) => {
36602
- signal.throwIfAborted();
36603
- if (!identifier2.safeParse(botId).success) {
36604
- throw new LocalBotAuthorizationError("invalid_request", "The Bot ID is invalid");
36605
- }
36606
- const row = this.#database.prepare("SELECT * FROM local_bot_grants WHERE bot_id = ? ORDER BY binding_revision DESC LIMIT 1").get(botId);
36607
- if (row === void 0) {
36608
- throw new LocalBotAuthorizationError("bot_not_found", "This machine has no saved approval for that Bot");
36609
- }
36610
- const parsed = savedApprovalSchema.safeParse(row);
36611
- if (!parsed.success) {
36612
- throw new LocalBotAuthorizationError("local_grant_invalid", "The saved Bot approval is invalid", {
36613
- cause: parsed.error
36614
- });
36615
- }
36616
- const saved = parsed.data;
36617
- const agent = catalog.find(saved.agent_ref);
36618
- if (!agent.capabilities.embeddedContextPrompt) {
36619
- throw new LocalBotAuthorizationError("binding_incompatible", "The local Agent cannot apply Bot context");
36620
- }
36621
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
36622
- revalidateExecutable(agent.adapterIdentity),
36623
- revalidateExecutable(agent.agentIdentity)
36624
- ]);
36625
- signal.throwIfAborted();
36626
- if (!adapterUnchanged || !agentUnchanged) {
36627
- throw new LocalBotAuthorizationError(
36628
- "binding_incompatible",
36629
- "The local Agent executable changed before approval"
36630
- );
36631
- }
36632
- const workspacePath = await directories.resolve(bindingAuthorityId, saved.workspace_ref, signal);
36633
- const workspaceIdentityDigest = await workspaceDigest(workspacePath);
36634
- signal.throwIfAborted();
36635
- this.#database.exec("BEGIN IMMEDIATE");
36636
- try {
36637
- const result = this.#database.prepare(`UPDATE local_bot_grants
36638
- SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
36639
- revoked_at = NULL, expires_at = ?, revocation_epoch = revocation_epoch + 1
36640
- WHERE local_grant_id = ? AND revocation_epoch = ?
36641
- AND agent_identity_digest = ? AND workspace_identity_digest = ?
36642
- AND binding_revision = (SELECT MAX(binding_revision) FROM local_bot_grants WHERE bot_id = ?)`).run(
36643
- agentDigest(agent),
36644
- workspaceIdentityDigest,
36645
- workspacePath,
36646
- now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS,
36647
- saved.local_grant_id,
36648
- saved.revocation_epoch,
36649
- saved.agent_identity_digest,
36650
- saved.workspace_identity_digest,
36651
- botId
36652
- );
36653
- if (result.changes !== 1) {
36654
- throw new LocalBotAuthorizationError(
36655
- "binding_not_approved",
36656
- "The Bot binding changed during approval; run the command again"
36657
- );
36658
- }
36659
- this.#database.prepare(`INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
36660
- VALUES (?, 'bot_binding_locally_reapproved', ?, '', ?)`).run(
36661
- new Date(now).toISOString(),
36662
- saved.binding_id,
36663
- JSON.stringify({ botId, bindingId: saved.binding_id, agentRef: saved.agent_ref })
36664
- );
36665
- this.#database.exec("COMMIT");
36666
- } catch (cause) {
36667
- this.#database.exec("ROLLBACK");
36668
- throw cause;
36669
- }
36670
- return { bindingId: saved.binding_id, workspacePath, agentRef: saved.agent_ref };
36671
- };
36672
36975
  approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
36673
36976
  signal.throwIfAborted();
36674
36977
  const existing = this.#database.prepare(
@@ -36758,8 +37061,7 @@ var LocalBotGrantStore = class {
36758
37061
  WHERE grants.local_grant_id = ? AND grants.bot_id = ?
36759
37062
  AND behavior_revision_id = ? AND behavior_digest = ?
36760
37063
  AND binding_id = ? AND binding_revision = ?
36761
- AND agent_ref = ?
36762
- AND revoked_at IS NULL AND expires_at > ?`
37064
+ AND agent_ref = ?`
36763
37065
  ).get(
36764
37066
  command.localGrantId,
36765
37067
  command.botId,
@@ -36767,8 +37069,7 @@ var LocalBotGrantStore = class {
36767
37069
  command.behaviorDigest,
36768
37070
  command.bindingId,
36769
37071
  command.bindingRevision,
36770
- command.agentId,
36771
- now
37072
+ command.agentId
36772
37073
  );
36773
37074
  if (row === void 0) {
36774
37075
  throw new LocalBotAuthorizationError(
@@ -36781,14 +37082,14 @@ var LocalBotGrantStore = class {
36781
37082
  if (!exactTargets(approvedTargets, requestedTargets)) {
36782
37083
  throw new LocalBotAuthorizationError(
36783
37084
  "binding_not_approved",
36784
- "The Bot execution target policy changed after local approval"
37085
+ "The Bot execution target policy differs from its binding"
36785
37086
  );
36786
37087
  }
36787
37088
  const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
36788
37089
  if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
36789
37090
  throw new LocalBotAuthorizationError(
36790
37091
  "binding_not_approved",
36791
- "The Bot Agent configuration changed after local approval"
37092
+ "The Bot Agent configuration differs from its binding"
36792
37093
  );
36793
37094
  }
36794
37095
  const agent = catalog.find(command.agentId);
@@ -36797,17 +37098,29 @@ var LocalBotGrantStore = class {
36797
37098
  revalidateExecutable(agent.agentIdentity)
36798
37099
  ]);
36799
37100
  signal.throwIfAborted();
37101
+ if (!adapterUnchanged || !agentUnchanged) {
37102
+ throw new LocalBotAuthorizationError(
37103
+ "binding_incompatible",
37104
+ "The local Agent executable changed while the Runtime is active; restart the Runtime"
37105
+ );
37106
+ }
36800
37107
  const workspaceRef = rowString(row, "workspace_ref");
36801
37108
  const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
36802
37109
  const currentAgentDigest = agentDigest(agent);
36803
- const currentWorkspaceDigest = await workspaceDigest(workspacePath);
37110
+ const currentWorkspaceDigest = workspaceDigest(workspacePath);
36804
37111
  signal.throwIfAborted();
36805
- if (!adapterUnchanged || !agentUnchanged || currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path")) {
36806
- this.revoke(rowString(row, "local_grant_id"), now);
36807
- throw new LocalBotAuthorizationError(
36808
- "binding_not_approved",
36809
- "The Bot execution target changed and requires local approval"
37112
+ let expiresAt = rowInteger(row, "expires_at");
37113
+ let revocationEpoch = rowInteger(row, "revocation_epoch");
37114
+ if (currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path") || expiresAt <= now || rowHasInteger(row, "revoked_at")) {
37115
+ const refreshed = this.refreshTarget(
37116
+ rowString(row, "local_grant_id"),
37117
+ currentAgentDigest,
37118
+ currentWorkspaceDigest,
37119
+ workspacePath,
37120
+ now
36810
37121
  );
37122
+ expiresAt = refreshed.expiresAt;
37123
+ revocationEpoch = refreshed.revocationEpoch;
36811
37124
  }
36812
37125
  if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
36813
37126
  throw new LocalBotAuthorizationError(
@@ -36828,8 +37141,8 @@ var LocalBotGrantStore = class {
36828
37141
  workspacePath,
36829
37142
  currentWorkspaceDigest,
36830
37143
  approvedTargets,
36831
- rowInteger(row, "expires_at"),
36832
- rowInteger(row, "revocation_epoch")
37144
+ expiresAt,
37145
+ revocationEpoch
36833
37146
  );
36834
37147
  };
36835
37148
  recordUnavailable = (request, code, message, now) => {
@@ -36872,16 +37185,65 @@ var LocalBotGrantStore = class {
36872
37185
  return {
36873
37186
  agent,
36874
37187
  agentIdentityDigest: agentDigest(agent),
36875
- workspaceIdentityDigest: await workspaceDigest(workspacePath),
37188
+ workspaceIdentityDigest: workspaceDigest(workspacePath),
36876
37189
  workspacePath
36877
37190
  };
36878
37191
  };
36879
- revoke = (localGrantId, now) => {
36880
- this.#database.prepare(
36881
- `UPDATE local_bot_grants
36882
- SET revoked_at = COALESCE(revoked_at, ?), revocation_epoch = revocation_epoch + 1
36883
- WHERE local_grant_id = ? AND revoked_at IS NULL`
36884
- ).run(now, localGrantId);
37192
+ refreshTarget = (localGrantId, agentIdentityDigest, workspaceIdentityDigest, workspacePath, now) => {
37193
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
37194
+ this.#database.exec("BEGIN IMMEDIATE");
37195
+ try {
37196
+ const current = this.#database.prepare("SELECT * FROM local_bot_grants WHERE local_grant_id = ?").get(localGrantId);
37197
+ if (current === void 0) {
37198
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is missing");
37199
+ }
37200
+ const currentExpiresAt = rowInteger(current, "expires_at");
37201
+ const currentRevocationEpoch = rowInteger(current, "revocation_epoch");
37202
+ if (agentIdentityDigest === rowString(current, "agent_identity_digest") && workspaceIdentityDigest === rowString(current, "workspace_identity_digest") && workspacePath === rowString(current, "workspace_path") && currentExpiresAt > now && !rowHasInteger(current, "revoked_at")) {
37203
+ this.#database.exec("COMMIT");
37204
+ return { expiresAt: currentExpiresAt, revocationEpoch: currentRevocationEpoch };
37205
+ }
37206
+ const result = this.#database.prepare(
37207
+ `UPDATE local_bot_grants
37208
+ SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
37209
+ expires_at = ?, revoked_at = NULL, revocation_epoch = revocation_epoch + 1
37210
+ WHERE local_grant_id = ? AND revocation_epoch = ?`
37211
+ ).run(
37212
+ agentIdentityDigest,
37213
+ workspaceIdentityDigest,
37214
+ workspacePath,
37215
+ expiresAt,
37216
+ localGrantId,
37217
+ currentRevocationEpoch
37218
+ );
37219
+ if (result.changes !== 1) {
37220
+ throw new LocalBotAuthorizationError(
37221
+ "local_grant_invalid",
37222
+ "The local Bot grant target could not be refreshed"
37223
+ );
37224
+ }
37225
+ this.#database.prepare(
37226
+ `INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
37227
+ VALUES (?, 'bot_binding_target_refreshed', ?, '', ?)`
37228
+ ).run(
37229
+ new Date(now).toISOString(),
37230
+ rowString(current, "binding_id"),
37231
+ JSON.stringify({
37232
+ agentIdentityChanged: agentIdentityDigest !== rowString(current, "agent_identity_digest"),
37233
+ bindingId: rowString(current, "binding_id"),
37234
+ botId: rowString(current, "bot_id"),
37235
+ expired: currentExpiresAt <= now,
37236
+ revived: rowHasInteger(current, "revoked_at"),
37237
+ workspaceIdentityChanged: workspaceIdentityDigest !== rowString(current, "workspace_identity_digest"),
37238
+ workspacePathChanged: workspacePath !== rowString(current, "workspace_path")
37239
+ })
37240
+ );
37241
+ this.#database.exec("COMMIT");
37242
+ return { expiresAt, revocationEpoch: currentRevocationEpoch + 1 };
37243
+ } catch (cause) {
37244
+ this.#database.exec("ROLLBACK");
37245
+ throw cause;
37246
+ }
36885
37247
  };
36886
37248
  };
36887
37249
 
@@ -41352,7 +41714,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41352
41714
 
41353
41715
  // src/pairing/pair-local-machine.ts
41354
41716
  import { randomUUID as randomUUID5 } from "node:crypto";
41355
- import { mkdir as mkdir4, open as open4, realpath as realpath8, rename as rename3, stat as stat8, writeFile as writeFile2 } from "node:fs/promises";
41717
+ import { mkdir as mkdir4, open as open4, realpath as realpath8, rename as rename3, stat as stat7, writeFile as writeFile2 } from "node:fs/promises";
41356
41718
  import { hostname as hostname3 } from "node:os";
41357
41719
  import { basename as basename5, join as join17, resolve as resolve4 } from "node:path";
41358
41720
  import { fetch as fetch7 } from "undici";
@@ -41422,7 +41784,7 @@ async function resolveDefaultWorkspace2(path2) {
41422
41784
  try {
41423
41785
  await mkdir4(requestedWorkspace, { recursive: true, mode: 448 });
41424
41786
  const defaultWorkspace = await realpath8(requestedWorkspace);
41425
- const metadata = await stat8(defaultWorkspace);
41787
+ const metadata = await stat7(defaultWorkspace);
41426
41788
  if (!metadata.isDirectory()) {
41427
41789
  throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
41428
41790
  }
@@ -41726,7 +42088,7 @@ async function resolveWorkspace(path2) {
41726
42088
  try {
41727
42089
  await mkdir5(requested, { recursive: true, mode: 448 });
41728
42090
  const resolved = await realpath9(requested);
41729
- const metadata = await stat9(resolved);
42091
+ const metadata = await stat8(resolved);
41730
42092
  if (!metadata.isDirectory()) {
41731
42093
  throw new MobiusRuntimeConfigurationError("The Runtime workspace is not a directory");
41732
42094
  }