@moxt-ai/mobius 0.0.40 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/acp/activity.d.ts.map +1 -1
  2. package/dist/acp/activity.js +52 -8
  3. package/dist/acp/activity.js.map +1 -1
  4. package/dist/acp/session-manager.d.ts +4 -3
  5. package/dist/acp/session-manager.d.ts.map +1 -1
  6. package/dist/acp/session-manager.js +511 -126
  7. package/dist/acp/session-manager.js.map +1 -1
  8. package/dist/agent-catalog/discover-local-agents.d.ts +0 -1
  9. package/dist/agent-catalog/discover-local-agents.d.ts.map +1 -1
  10. package/dist/agent-catalog/discover-local-agents.js +0 -1
  11. package/dist/agent-catalog/discover-local-agents.js.map +1 -1
  12. package/dist/artifacts/runtime-artifact-uploader.d.ts +2 -2
  13. package/dist/artifacts/runtime-artifact-uploader.d.ts.map +1 -1
  14. package/dist/artifacts/runtime-artifact-uploader.js +3 -3
  15. package/dist/artifacts/runtime-artifact-uploader.js.map +1 -1
  16. package/dist/authorization/local-artifact.d.ts +6 -0
  17. package/dist/authorization/local-artifact.d.ts.map +1 -0
  18. package/dist/authorization/local-artifact.js +2 -0
  19. package/dist/authorization/local-artifact.js.map +1 -0
  20. package/dist/authorization/local-video.d.ts +11 -0
  21. package/dist/authorization/local-video.d.ts.map +1 -0
  22. package/dist/authorization/local-video.js +48 -0
  23. package/dist/authorization/local-video.js.map +1 -0
  24. package/dist/bots/local-bot-grant-store.d.ts +1 -8
  25. package/dist/bots/local-bot-grant-store.d.ts.map +1 -1
  26. package/dist/bots/local-bot-grant-store.js +79 -121
  27. package/dist/bots/local-bot-grant-store.js.map +1 -1
  28. package/dist/cli.js +1647 -1276
  29. package/dist/cli.js.map +4 -4
  30. package/dist/index.js +800 -312
  31. package/dist/index.js.map +4 -4
  32. package/dist/run-daemon.js +2 -2
  33. package/dist/run-daemon.js.map +1 -1
  34. package/dist/runtime.d.ts.map +1 -1
  35. package/dist/runtime.js +792 -304
  36. package/dist/runtime.js.map +4 -4
  37. package/package.json +1 -1
  38. package/dist/bots/bot-approve-command.d.ts +0 -2
  39. package/dist/bots/bot-approve-command.d.ts.map +0 -1
  40. package/dist/bots/bot-approve-command.js +0 -78
  41. package/dist/bots/bot-approve-command.js.map +0 -1
package/dist/index.js CHANGED
@@ -19933,7 +19933,7 @@ var displayContentSchema = external_exports.strictObject({
19933
19933
  path: external_exports.string().max(2048),
19934
19934
  terminalId: external_exports.string().max(255),
19935
19935
  text: LONG_TEXT,
19936
- type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text"]),
19936
+ type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text", "video"]),
19937
19937
  uri: external_exports.string().max(4096)
19938
19938
  }).readonly();
19939
19939
  var recordedDisplayContentSchema = external_exports.strictObject({
@@ -19946,7 +19946,7 @@ var recordedDisplayContentSchema = external_exports.strictObject({
19946
19946
  path: external_exports.string().max(2048),
19947
19947
  terminalId: external_exports.string().max(255),
19948
19948
  text: external_exports.string().max(4e6),
19949
- type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text"]),
19949
+ type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text", "video"]),
19950
19950
  uri: external_exports.string().max(4096)
19951
19951
  }).readonly();
19952
19952
  var promptImageSchema = external_exports.strictObject({
@@ -19993,8 +19993,17 @@ var sessionPrepareCommandSchema = external_exports.strictObject({
19993
19993
  }).readonly().optional(),
19994
19994
  kind: external_exports.literal(SESSION_PREPARE_KIND),
19995
19995
  requestId: IDENTIFIER,
19996
+ sessionState: external_exports.literal("provisioned").optional(),
19996
19997
  /** @deprecated Reserved for the legacy Bot Agent-configuration endpoint. */
19997
19998
  transient: external_exports.boolean().optional()
19999
+ }).superRefine((command, context) => {
20000
+ if (command.transient === true && command.sessionState === "provisioned") {
20001
+ context.addIssue({
20002
+ code: "custom",
20003
+ message: "A transient Session cannot already be provisioned",
20004
+ path: ["sessionState"]
20005
+ });
20006
+ }
19998
20007
  }).readonly();
19999
20008
  var runtimeTimingsSchema = external_exports.array(
20000
20009
  external_exports.strictObject({
@@ -22430,6 +22439,55 @@ async function readAuthorizedRaster(uri, roots, signal) {
22430
22439
  return new LocalRasterImage(basename(target) || "Image", mimeType, bytes);
22431
22440
  }
22432
22441
 
22442
+ // src/authorization/local-video.ts
22443
+ import { basename as basename2 } from "node:path";
22444
+ var MAX_INLINE_VIDEO_BYTES = 3e6;
22445
+ var MP4_FILE_TYPE = new TextEncoder().encode("ftyp");
22446
+ var WEBM_SIGNATURE = Uint8Array.of(26, 69, 223, 163);
22447
+ var LocalVideo = class {
22448
+ bytes;
22449
+ mimeType;
22450
+ name;
22451
+ constructor(name, mimeType, bytes) {
22452
+ this.bytes = bytes;
22453
+ this.mimeType = mimeType;
22454
+ this.name = name;
22455
+ }
22456
+ base64 = () => Buffer.from(this.bytes).toString("base64");
22457
+ };
22458
+ function startsWith2(bytes, signature, offset = 0) {
22459
+ if (bytes.byteLength < offset + signature.byteLength) {
22460
+ return false;
22461
+ }
22462
+ return signature.every((value, index2) => bytes[offset + index2] === value);
22463
+ }
22464
+ function sniffVideoMime(bytes) {
22465
+ if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
22466
+ return "video/mp4";
22467
+ }
22468
+ if (startsWith2(bytes, WEBM_SIGNATURE)) {
22469
+ return "video/webm";
22470
+ }
22471
+ return null;
22472
+ }
22473
+ function readInlineVideo(data, declaredMimeType, name = "Video") {
22474
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_VIDEO_BYTES / 3) * 4 || data.length % 4 !== 0) {
22475
+ return null;
22476
+ }
22477
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
22478
+ return null;
22479
+ }
22480
+ const bytes = new Uint8Array(Buffer.from(data, "base64"));
22481
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_VIDEO_BYTES) {
22482
+ return null;
22483
+ }
22484
+ const mimeType = sniffVideoMime(bytes);
22485
+ if (mimeType === null || mimeType !== declaredMimeType) {
22486
+ return null;
22487
+ }
22488
+ return new LocalVideo(basename2(name) || "Video", mimeType, bytes);
22489
+ }
22490
+
22433
22491
  // src/infra/operation-metrics.ts
22434
22492
  var AccumulatingOperationMetrics = class {
22435
22493
  #durations = /* @__PURE__ */ new Map();
@@ -22687,6 +22745,14 @@ function emptyDisplayContent(type) {
22687
22745
  uri: ""
22688
22746
  };
22689
22747
  }
22748
+ function resourceName(uri) {
22749
+ try {
22750
+ const pathname = new URL(uri).pathname;
22751
+ return decodeURIComponent(pathname.slice(pathname.lastIndexOf("/") + 1));
22752
+ } catch {
22753
+ return "";
22754
+ }
22755
+ }
22690
22756
  function imageDisplayContent(mimeType, name, data, artifactId = "", uri = "") {
22691
22757
  return {
22692
22758
  ...emptyDisplayContent("image"),
@@ -22718,18 +22784,21 @@ function normalizeContentBlock(content3) {
22718
22784
  };
22719
22785
  }
22720
22786
  if (content3.type === "resource") {
22787
+ const type = content3.resource.mimeType?.startsWith("video/") === true ? "video" : "resource";
22721
22788
  if ("text" in content3.resource) {
22722
22789
  return {
22723
- ...emptyDisplayContent("resource"),
22790
+ ...emptyDisplayContent(type),
22724
22791
  mimeType: content3.resource.mimeType ?? "",
22792
+ name: resourceName(content3.resource.uri),
22725
22793
  text: content3.resource.text,
22726
22794
  uri: content3.resource.uri
22727
22795
  };
22728
22796
  }
22729
22797
  return {
22730
- ...emptyDisplayContent("resource"),
22798
+ ...emptyDisplayContent(type),
22731
22799
  data: content3.resource.blob,
22732
22800
  mimeType: content3.resource.mimeType ?? "",
22801
+ name: resourceName(content3.resource.uri),
22733
22802
  uri: content3.resource.uri
22734
22803
  };
22735
22804
  }
@@ -22762,6 +22831,36 @@ async function normalizeToolContent(content3, prepareContent) {
22762
22831
  }
22763
22832
  return normalized;
22764
22833
  }
22834
+ function rawMcpToolContent(rawOutput) {
22835
+ if (!isRecord4(rawOutput)) {
22836
+ return [];
22837
+ }
22838
+ const result = isRecord4(rawOutput["result"]) ? rawOutput["result"] : rawOutput;
22839
+ const content3 = result["content"];
22840
+ if (!Array.isArray(content3)) {
22841
+ return [];
22842
+ }
22843
+ return content3.flatMap((item) => {
22844
+ if (!isRecord4(item) || item["type"] !== "image" || typeof item["data"] !== "string" || typeof item["mimeType"] !== "string") {
22845
+ return [];
22846
+ }
22847
+ const uri = item["uri"];
22848
+ return [
22849
+ {
22850
+ type: "content",
22851
+ content: {
22852
+ type: "image",
22853
+ data: item["data"],
22854
+ mimeType: item["mimeType"],
22855
+ ...typeof uri === "string" ? { uri } : {}
22856
+ }
22857
+ }
22858
+ ];
22859
+ });
22860
+ }
22861
+ function toolContent(content3, rawOutput) {
22862
+ return content3 !== void 0 && content3 !== null && content3.length > 0 ? content3 : rawMcpToolContent(rawOutput);
22863
+ }
22765
22864
  function normalizeLocations(locations) {
22766
22865
  const normalized = [];
22767
22866
  const unique = /* @__PURE__ */ new Set();
@@ -22925,7 +23024,10 @@ var AcpActivityTracker = class {
22925
23024
  const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
22926
23025
  const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
22927
23026
  const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
22928
- const detailContent = await normalizeToolContent(update.content ?? [], this.#prepareContent);
23027
+ const detailContent = await normalizeToolContent(
23028
+ toolContent(update.content, update.rawOutput),
23029
+ this.#prepareContent
23030
+ );
22929
23031
  await this.#record(
22930
23032
  key,
22931
23033
  new AcpActivity(
@@ -22951,10 +23053,11 @@ var AcpActivityTracker = class {
22951
23053
  const identity2 = this.#identity(key);
22952
23054
  const previousDetail = recordedDetail(previous2);
22953
23055
  const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous2?.output ?? "";
22954
- const content3 = update.content === void 0 || update.content === null ? previous2?.content ?? [] : await normalizeToolContent(update.content, this.#prepareContent);
23056
+ const nextContent = toolContent(update.content, update.rawOutput);
23057
+ const content3 = nextContent.length === 0 ? previous2?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
22955
23058
  const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous2?.input ?? "" : formatUnknownDetail(update.rawInput);
22956
23059
  const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous2?.output ?? "";
22957
- const detailContent = update.content === void 0 || update.content === null ? previousDetail?.content ?? previous2?.content ?? [] : content3;
23060
+ const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous2?.content ?? [] : content3;
22958
23061
  await this.#record(
22959
23062
  key,
22960
23063
  new AcpActivity(
@@ -27031,7 +27134,7 @@ var titleBefore = {
27031
27134
  };
27032
27135
  function tokenizeDefinition(effects, ok2, nok) {
27033
27136
  const self = this;
27034
- let identifier3;
27137
+ let identifier2;
27035
27138
  return start;
27036
27139
  function start(code) {
27037
27140
  effects.enter("definition");
@@ -27050,7 +27153,7 @@ function tokenizeDefinition(effects, ok2, nok) {
27050
27153
  )(code);
27051
27154
  }
27052
27155
  function labelAfter(code) {
27053
- identifier3 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
27156
+ identifier2 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
27054
27157
  if (code === 58) {
27055
27158
  effects.enter("definitionMarker");
27056
27159
  effects.consume(code);
@@ -27084,7 +27187,7 @@ function tokenizeDefinition(effects, ok2, nok) {
27084
27187
  function afterWhitespace(code) {
27085
27188
  if (code === null || markdownLineEnding(code)) {
27086
27189
  effects.exit("definition");
27087
- self.parser.defined.push(identifier3);
27190
+ self.parser.defined.push(identifier2);
27088
27191
  return ok2(code);
27089
27192
  }
27090
27193
  return nok(code);
@@ -30919,11 +31022,12 @@ var SqliteAcpSessionStore = class {
30919
31022
 
30920
31023
  // src/acp/session-manager.ts
30921
31024
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
31025
+ var MAX_ACP_PROCESSES = 10;
30922
31026
  var MAX_PRE_SESSION_UPDATES = 100;
30923
31027
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
30924
31028
  var SESSION_CONTROL_COMMAND_ID = "session-control";
30925
31029
  var NullAcpSessionObserver = class {
30926
- importLocalImage = (_sessionId, _image, signal) => {
31030
+ importLocalArtifact = (_sessionId, _artifact, signal) => {
30927
31031
  signal.throwIfAborted();
30928
31032
  return Promise.resolve("");
30929
31033
  };
@@ -30977,6 +31081,91 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
30977
31081
  this.name = "RetryableAcpInitializationError";
30978
31082
  }
30979
31083
  };
31084
+ var AcpProcessCapacityLease = class {
31085
+ #releaseCapacity;
31086
+ #released = false;
31087
+ constructor(releaseCapacity) {
31088
+ this.#releaseCapacity = releaseCapacity;
31089
+ }
31090
+ release = () => {
31091
+ if (this.#released) {
31092
+ return;
31093
+ }
31094
+ this.#released = true;
31095
+ this.#releaseCapacity();
31096
+ };
31097
+ };
31098
+ var AcpProcessCapacityWaiter = class {
31099
+ completion = Promise.withResolvers();
31100
+ signal;
31101
+ constructor(signal) {
31102
+ this.signal = signal;
31103
+ }
31104
+ cancel = () => {
31105
+ try {
31106
+ this.signal.throwIfAborted();
31107
+ } catch (error62) {
31108
+ this.completion.reject(error62);
31109
+ }
31110
+ };
31111
+ };
31112
+ var AcpProcessCapacityLock = class {
31113
+ #locked = false;
31114
+ #waiters = [];
31115
+ acquire = async (signal) => {
31116
+ signal.throwIfAborted();
31117
+ if (!this.#locked) {
31118
+ this.#locked = true;
31119
+ return new AcpProcessCapacityLease(this.#release);
31120
+ }
31121
+ const waiter = new AcpProcessCapacityWaiter(signal);
31122
+ this.#waiters.push(waiter);
31123
+ signal.addEventListener("abort", waiter.cancel, { once: true });
31124
+ if (signal.aborted) {
31125
+ waiter.cancel();
31126
+ }
31127
+ try {
31128
+ return await waiter.completion.promise;
31129
+ } finally {
31130
+ signal.removeEventListener("abort", waiter.cancel);
31131
+ const index2 = this.#waiters.indexOf(waiter);
31132
+ if (index2 >= 0) {
31133
+ this.#waiters.splice(index2, 1);
31134
+ }
31135
+ }
31136
+ };
31137
+ #release = () => {
31138
+ while (this.#waiters.length > 0) {
31139
+ const waiter = this.#waiters.shift();
31140
+ if (waiter === void 0 || waiter.signal.aborted) {
31141
+ continue;
31142
+ }
31143
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
31144
+ return;
31145
+ }
31146
+ this.#locked = false;
31147
+ };
31148
+ };
31149
+ async function waitForAcpProcessCapacity(completion, signal) {
31150
+ signal.throwIfAborted();
31151
+ const cancelled = Promise.withResolvers();
31152
+ const cancel = () => {
31153
+ try {
31154
+ signal.throwIfAborted();
31155
+ } catch (error62) {
31156
+ cancelled.reject(error62);
31157
+ }
31158
+ };
31159
+ signal.addEventListener("abort", cancel, { once: true });
31160
+ if (signal.aborted) {
31161
+ cancel();
31162
+ }
31163
+ try {
31164
+ await Promise.race([completion, cancelled.promise]);
31165
+ } finally {
31166
+ signal.removeEventListener("abort", cancel);
31167
+ }
31168
+ }
30980
31169
  function readableWebStream(input2) {
30981
31170
  let streamOpen = true;
30982
31171
  return new ReadableStream({
@@ -31605,6 +31794,13 @@ var AcpProcessSession = class _AcpProcessSession {
31605
31794
  return await this.importRaster(raster, signal);
31606
31795
  }
31607
31796
  }
31797
+ if (content3.type === "video" && content3.data.length > 0) {
31798
+ const video = readInlineVideo(content3.data, content3.mimeType, content3.name);
31799
+ if (video === null) {
31800
+ return { ...content3, data: "" };
31801
+ }
31802
+ return await this.importVideo(video, AbortSignal.timeout(2e4));
31803
+ }
31608
31804
  return content3;
31609
31805
  };
31610
31806
  emitAgentContent = async (content3, messageId) => {
@@ -31630,7 +31826,7 @@ var AcpProcessSession = class _AcpProcessSession {
31630
31826
  });
31631
31827
  };
31632
31828
  importRaster = async (raster, signal) => {
31633
- const artifactId = await this.#getObserver().importLocalImage(this.#mobiusSessionId, raster, signal);
31829
+ const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, raster, signal);
31634
31830
  return imageDisplayContent(
31635
31831
  raster.mimeType,
31636
31832
  raster.name,
@@ -31638,6 +31834,22 @@ var AcpProcessSession = class _AcpProcessSession {
31638
31834
  artifactId
31639
31835
  );
31640
31836
  };
31837
+ importVideo = async (video, signal) => {
31838
+ const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, video, signal);
31839
+ return {
31840
+ artifactId,
31841
+ data: artifactId.length > 0 ? "" : video.base64(),
31842
+ mimeType: video.mimeType,
31843
+ name: video.name,
31844
+ newText: "",
31845
+ oldText: "",
31846
+ path: "",
31847
+ terminalId: "",
31848
+ text: "",
31849
+ type: "video",
31850
+ uri: ""
31851
+ };
31852
+ };
31641
31853
  async #initializeAgent(signal) {
31642
31854
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
31643
31855
  }
@@ -32464,20 +32676,23 @@ var AcpProcessSession = class _AcpProcessSession {
32464
32676
  }
32465
32677
  };
32466
32678
  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 {
32679
+ try {
32680
+ await this.cancelPendingInteractions();
32681
+ if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
32682
+ try {
32683
+ await this.#connection.agent.request(
32684
+ methods3.agent.session.close,
32685
+ { sessionId: this.#nativeSessionId },
32686
+ {
32687
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
32688
+ }
32689
+ );
32690
+ } catch {
32691
+ }
32478
32692
  }
32693
+ } finally {
32694
+ await this.closeProcess();
32479
32695
  }
32480
- await this.closeProcess();
32481
32696
  };
32482
32697
  closeProcess = async (capturedProcesses = []) => {
32483
32698
  try {
@@ -32584,6 +32799,31 @@ var AcpProcessSession = class _AcpProcessSession {
32584
32799
  }
32585
32800
  };
32586
32801
  };
32802
+ var AcpProcessEvictionCandidate = class {
32803
+ };
32804
+ var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
32805
+ };
32806
+ var FoundAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
32807
+ runtime;
32808
+ constructor(runtime) {
32809
+ super();
32810
+ this.runtime = runtime;
32811
+ }
32812
+ };
32813
+ var FoundAcpSessionProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
32814
+ sessionId;
32815
+ constructor(sessionId, runtime) {
32816
+ super(runtime);
32817
+ this.sessionId = sessionId;
32818
+ }
32819
+ };
32820
+ var FoundAcpNativeBrowserProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
32821
+ sessionId;
32822
+ constructor(sessionId, runtime) {
32823
+ super(runtime);
32824
+ this.sessionId = sessionId;
32825
+ }
32826
+ };
32587
32827
  var AcpSessionManager = class {
32588
32828
  #activeCommandIds = /* @__PURE__ */ new Map();
32589
32829
  #agentSettingsObserver = new NullAcpSessionObserver();
@@ -32592,10 +32832,18 @@ var AcpSessionManager = class {
32592
32832
  #nativeBrowserPreparing = /* @__PURE__ */ new Map();
32593
32833
  #nativeBrowserSessions = /* @__PURE__ */ new Map();
32594
32834
  #nativeBrowserStore = new MemoryAcpSessionStore();
32835
+ #nativeBrowserUseCounts = /* @__PURE__ */ new Map();
32595
32836
  #activeSessionIds = /* @__PURE__ */ new Set();
32596
32837
  #cancellationRequests = /* @__PURE__ */ new Map();
32597
32838
  #preparing = /* @__PURE__ */ new Map();
32839
+ #processCapacityChanged = Promise.withResolvers();
32840
+ #processCapacityLock = new AcpProcessCapacityLock();
32841
+ #retainedProcesses = /* @__PURE__ */ new Map();
32842
+ #retiringProcessCount = 0;
32843
+ #sessionUseCounts = /* @__PURE__ */ new Map();
32598
32844
  #sessions = /* @__PURE__ */ new Map();
32845
+ #startingProcessCount = 0;
32846
+ #transientProcessCount = 0;
32599
32847
  #store;
32600
32848
  #observer;
32601
32849
  constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore()) {
@@ -32605,18 +32853,230 @@ var AcpSessionManager = class {
32605
32853
  setObserver = (observer) => {
32606
32854
  this.#observer = observer;
32607
32855
  };
32856
+ #notifyProcessCapacityChanged() {
32857
+ const changed = this.#processCapacityChanged;
32858
+ this.#processCapacityChanged = Promise.withResolvers();
32859
+ changed.resolve();
32860
+ }
32861
+ #touchSession(sessionId) {
32862
+ const runtime = this.#sessions.get(sessionId);
32863
+ if (runtime === void 0) {
32864
+ return;
32865
+ }
32866
+ this.#touchProcess(runtime);
32867
+ }
32868
+ #touchExpectedSession(sessionId, expected) {
32869
+ if (this.#sessions.get(sessionId) !== expected) {
32870
+ return;
32871
+ }
32872
+ this.#touchProcess(expected);
32873
+ }
32874
+ #touchNativeBrowserSession(sessionId) {
32875
+ const runtime = this.#nativeBrowserSessions.get(sessionId);
32876
+ if (runtime === void 0) {
32877
+ return;
32878
+ }
32879
+ this.#touchProcess(runtime);
32880
+ }
32881
+ #touchExpectedNativeBrowserSession(sessionId, expected) {
32882
+ if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
32883
+ return;
32884
+ }
32885
+ this.#touchProcess(expected);
32886
+ }
32887
+ #touchProcess(runtime) {
32888
+ const retained = this.#retainedProcesses.get(runtime);
32889
+ if (retained === void 0) {
32890
+ return;
32891
+ }
32892
+ this.#retainedProcesses.delete(runtime);
32893
+ this.#retainedProcesses.set(runtime, retained);
32894
+ }
32895
+ #beginSessionUse(sessionId) {
32896
+ this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
32897
+ this.#touchSession(sessionId);
32898
+ }
32899
+ #endSessionUse(sessionId) {
32900
+ const count = this.#sessionUseCounts.get(sessionId) ?? 0;
32901
+ if (count <= 1) {
32902
+ this.#sessionUseCounts.delete(sessionId);
32903
+ } else {
32904
+ this.#sessionUseCounts.set(sessionId, count - 1);
32905
+ }
32906
+ this.#touchSession(sessionId);
32907
+ this.#notifyProcessCapacityChanged();
32908
+ }
32909
+ #beginNativeBrowserUse(sessionId) {
32910
+ this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
32911
+ this.#touchNativeBrowserSession(sessionId);
32912
+ }
32913
+ #endNativeBrowserUse(sessionId) {
32914
+ const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
32915
+ if (count <= 1) {
32916
+ this.#nativeBrowserUseCounts.delete(sessionId);
32917
+ } else {
32918
+ this.#nativeBrowserUseCounts.set(sessionId, count - 1);
32919
+ }
32920
+ this.#touchNativeBrowserSession(sessionId);
32921
+ this.#notifyProcessCapacityChanged();
32922
+ }
32923
+ #isNativeSessionOperationActive(sessionId) {
32924
+ const stored = this.#store.read(sessionId);
32925
+ return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
32926
+ }
32927
+ #leastRecentlyUsedEvictionCandidate() {
32928
+ for (const candidate of this.#retainedProcesses.values()) {
32929
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
32930
+ 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)) {
32931
+ continue;
32932
+ }
32933
+ return candidate;
32934
+ }
32935
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate && !this.#nativeBrowserPreparing.has(candidate.sessionId) && (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
32936
+ return candidate;
32937
+ }
32938
+ }
32939
+ return new MissingAcpProcessEvictionCandidate();
32940
+ }
32941
+ #ownedProcessCount() {
32942
+ return this.#retainedProcesses.size + this.#startingProcessCount + this.#transientProcessCount + this.#retiringProcessCount;
32943
+ }
32944
+ async #retireProcess(runtime, retained, close) {
32945
+ if (retained) {
32946
+ this.#retainedProcesses.delete(runtime);
32947
+ this.#retiringProcessCount += 1;
32948
+ }
32949
+ try {
32950
+ await close();
32951
+ } finally {
32952
+ if (retained) {
32953
+ this.#retiringProcessCount -= 1;
32954
+ this.#notifyProcessCapacityChanged();
32955
+ }
32956
+ }
32957
+ }
32958
+ async #retireSessionProcess(sessionId, runtime, close) {
32959
+ const retained = this.#sessions.get(sessionId) === runtime;
32960
+ if (retained) {
32961
+ this.#sessions.delete(sessionId);
32962
+ }
32963
+ await this.#retireProcess(runtime, retained, close);
32964
+ }
32965
+ async #retireNativeBrowserProcess(sessionId, runtime, close) {
32966
+ const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
32967
+ if (retained) {
32968
+ this.#nativeBrowserSessions.delete(sessionId);
32969
+ this.#nativeBrowserStore.remove(sessionId);
32970
+ }
32971
+ await this.#retireProcess(runtime, retained, close);
32972
+ }
32973
+ async #reserveProcessCapacity(signal) {
32974
+ const lease = await this.#processCapacityLock.acquire(signal);
32975
+ try {
32976
+ for (; ; ) {
32977
+ signal.throwIfAborted();
32978
+ if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
32979
+ this.#startingProcessCount += 1;
32980
+ return;
32981
+ }
32982
+ const candidate = this.#leastRecentlyUsedEvictionCandidate();
32983
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
32984
+ await this.#retireSessionProcess(
32985
+ candidate.sessionId,
32986
+ candidate.runtime,
32987
+ async () => await candidate.runtime.close()
32988
+ );
32989
+ continue;
32990
+ }
32991
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
32992
+ await this.#retireNativeBrowserProcess(
32993
+ candidate.sessionId,
32994
+ candidate.runtime,
32995
+ async () => await candidate.runtime.close()
32996
+ );
32997
+ continue;
32998
+ }
32999
+ const changed = this.#processCapacityChanged.promise;
33000
+ await waitForAcpProcessCapacity(changed, signal);
33001
+ }
33002
+ } finally {
33003
+ lease.release();
33004
+ }
33005
+ }
33006
+ async #startRetainedSessionProcess(options, start) {
33007
+ await this.#reserveProcessCapacity(options.signal);
33008
+ try {
33009
+ const runtime = await start();
33010
+ this.#startingProcessCount -= 1;
33011
+ this.#sessions.set(options.sessionId, runtime);
33012
+ this.#retainedProcesses.set(
33013
+ runtime,
33014
+ new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime)
33015
+ );
33016
+ this.#notifyProcessCapacityChanged();
33017
+ return runtime;
33018
+ } catch (error62) {
33019
+ this.#startingProcessCount -= 1;
33020
+ this.#notifyProcessCapacityChanged();
33021
+ throw error62;
33022
+ }
33023
+ }
33024
+ async #startRetainedNativeBrowserProcess(options, start) {
33025
+ await this.#reserveProcessCapacity(options.signal);
33026
+ try {
33027
+ const runtime = await start();
33028
+ this.#startingProcessCount -= 1;
33029
+ this.#nativeBrowserSessions.set(options.sessionId, runtime);
33030
+ this.#retainedProcesses.set(
33031
+ runtime,
33032
+ new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime)
33033
+ );
33034
+ this.#notifyProcessCapacityChanged();
33035
+ return runtime;
33036
+ } catch (error62) {
33037
+ this.#startingProcessCount -= 1;
33038
+ this.#notifyProcessCapacityChanged();
33039
+ throw error62;
33040
+ }
33041
+ }
33042
+ async #runWithTransientProcess(signal, start, operation, close) {
33043
+ await this.#reserveProcessCapacity(signal);
33044
+ let runtime;
33045
+ try {
33046
+ runtime = await start();
33047
+ } catch (error62) {
33048
+ this.#startingProcessCount -= 1;
33049
+ this.#notifyProcessCapacityChanged();
33050
+ throw error62;
33051
+ }
33052
+ this.#startingProcessCount -= 1;
33053
+ this.#transientProcessCount += 1;
33054
+ this.#notifyProcessCapacityChanged();
33055
+ try {
33056
+ return await operation(runtime);
33057
+ } finally {
33058
+ try {
33059
+ await close(runtime);
33060
+ } finally {
33061
+ this.#transientProcessCount -= 1;
33062
+ this.#notifyProcessCapacityChanged();
33063
+ }
33064
+ }
33065
+ }
32608
33066
  async #startNativeBrowserPreparation(options) {
32609
33067
  const operation = (async () => {
32610
33068
  try {
32611
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
33069
+ return await this.#startRetainedNativeBrowserProcess(
32612
33070
  options,
32613
- () => this.#nativeBrowserObserver,
32614
- this.#nativeBrowserStore
33071
+ async () => await AcpProcessSession.startNativeSessionBrowser(
33072
+ options,
33073
+ () => this.#nativeBrowserObserver,
33074
+ this.#nativeBrowserStore
33075
+ )
32615
33076
  );
32616
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
32617
- return runtime;
32618
33077
  } finally {
32619
33078
  this.#nativeBrowserPreparing.delete(options.sessionId);
33079
+ this.#notifyProcessCapacityChanged();
32620
33080
  }
32621
33081
  })();
32622
33082
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -32625,18 +33085,18 @@ var AcpSessionManager = class {
32625
33085
  async #replaceNativeBrowserPreparation(existing, options) {
32626
33086
  const operation = (async () => {
32627
33087
  try {
32628
- this.#nativeBrowserSessions.delete(options.sessionId);
32629
- await existing.close();
32630
- this.#nativeBrowserStore.remove(options.sessionId);
32631
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
33088
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
33089
+ return await this.#startRetainedNativeBrowserProcess(
32632
33090
  options,
32633
- () => this.#nativeBrowserObserver,
32634
- this.#nativeBrowserStore
33091
+ async () => await AcpProcessSession.startNativeSessionBrowser(
33092
+ options,
33093
+ () => this.#nativeBrowserObserver,
33094
+ this.#nativeBrowserStore
33095
+ )
32635
33096
  );
32636
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
32637
- return runtime;
32638
33097
  } finally {
32639
33098
  this.#nativeBrowserPreparing.delete(options.sessionId);
33099
+ this.#notifyProcessCapacityChanged();
32640
33100
  }
32641
33101
  })();
32642
33102
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -32645,11 +33105,13 @@ var AcpSessionManager = class {
32645
33105
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
32646
33106
  const operation = (async () => {
32647
33107
  try {
32648
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
32649
- this.#sessions.set(options.sessionId, runtime);
32650
- return runtime;
33108
+ return await this.#startRetainedSessionProcess(
33109
+ options,
33110
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
33111
+ );
32651
33112
  } finally {
32652
33113
  this.#preparing.delete(options.sessionId);
33114
+ this.#notifyProcessCapacityChanged();
32653
33115
  }
32654
33116
  })();
32655
33117
  this.#preparing.set(options.sessionId, operation);
@@ -32658,17 +33120,19 @@ var AcpSessionManager = class {
32658
33120
  async #startSessionForkAtTurnPreparation(options, sourceNativeSessionId, forkPoint) {
32659
33121
  const operation = (async () => {
32660
33122
  try {
32661
- const runtime = await AcpProcessSession.startSessionForkAtTurn(
33123
+ return await this.#startRetainedSessionProcess(
32662
33124
  options,
32663
- sourceNativeSessionId,
32664
- forkPoint,
32665
- () => this.#observer,
32666
- this.#store
33125
+ async () => await AcpProcessSession.startSessionForkAtTurn(
33126
+ options,
33127
+ sourceNativeSessionId,
33128
+ forkPoint,
33129
+ () => this.#observer,
33130
+ this.#store
33131
+ )
32667
33132
  );
32668
- this.#sessions.set(options.sessionId, runtime);
32669
- return runtime;
32670
33133
  } finally {
32671
33134
  this.#preparing.delete(options.sessionId);
33135
+ this.#notifyProcessCapacityChanged();
32672
33136
  }
32673
33137
  })();
32674
33138
  this.#preparing.set(options.sessionId, operation);
@@ -32677,14 +33141,19 @@ var AcpSessionManager = class {
32677
33141
  async #replacePreparation(existing, options, metrics) {
32678
33142
  const operation = (async () => {
32679
33143
  try {
32680
- this.#sessions.delete(options.sessionId);
32681
- await metrics.measure("runtime-replacement-close", async () => await existing.close());
33144
+ await this.#retireSessionProcess(
33145
+ options.sessionId,
33146
+ existing,
33147
+ async () => await metrics.measure("runtime-replacement-close", async () => await existing.close())
33148
+ );
32682
33149
  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;
33150
+ return await this.#startRetainedSessionProcess(
33151
+ options,
33152
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
33153
+ );
32686
33154
  } finally {
32687
33155
  this.#preparing.delete(options.sessionId);
33156
+ this.#notifyProcessCapacityChanged();
32688
33157
  }
32689
33158
  })();
32690
33159
  this.#preparing.set(options.sessionId, operation);
@@ -32694,10 +33163,12 @@ var AcpSessionManager = class {
32694
33163
  const desiredConfigOptions = existing.prepared().configOptions;
32695
33164
  const operation = (async () => {
32696
33165
  try {
32697
- this.#sessions.delete(options.sessionId);
32698
- await existing.close();
33166
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
32699
33167
  this.#store.remove(options.sessionId);
32700
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
33168
+ const runtime = await this.#startRetainedSessionProcess(
33169
+ options,
33170
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
33171
+ );
32701
33172
  try {
32702
33173
  for (const desired of desiredConfigOptions) {
32703
33174
  const current = runtime.prepared().configOptions.find((option2) => option2.id === desired.id);
@@ -32729,14 +33200,14 @@ var AcpSessionManager = class {
32729
33200
  }
32730
33201
  }
32731
33202
  } catch (error62) {
32732
- await runtime.close();
33203
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
32733
33204
  this.#store.remove(options.sessionId);
32734
33205
  throw error62;
32735
33206
  }
32736
- this.#sessions.set(options.sessionId, runtime);
32737
33207
  return runtime;
32738
33208
  } finally {
32739
33209
  this.#preparing.delete(options.sessionId);
33210
+ this.#notifyProcessCapacityChanged();
32740
33211
  }
32741
33212
  })();
32742
33213
  this.#preparing.set(options.sessionId, operation);
@@ -32758,6 +33229,7 @@ var AcpSessionManager = class {
32758
33229
  if (pending !== void 0) {
32759
33230
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
32760
33231
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
33232
+ this.#touchExpectedSession(options.sessionId, runtime2);
32761
33233
  return runtime2.prepared();
32762
33234
  }
32763
33235
  return await this.prepareSession(options, metrics);
@@ -32765,6 +33237,7 @@ var AcpSessionManager = class {
32765
33237
  const existing = this.#sessions.get(options.sessionId);
32766
33238
  if (existing !== void 0) {
32767
33239
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
33240
+ this.#touchExpectedSession(options.sessionId, existing);
32768
33241
  return existing.prepared();
32769
33242
  }
32770
33243
  if (!existing.canRebind()) {
@@ -32785,22 +33258,24 @@ var AcpSessionManager = class {
32785
33258
  * authoritative settings. Its identity and store are private to this
32786
33259
  * operation and never become a Mobius Session.
32787
33260
  */
32788
- inspectAgentSettings = async (options) => {
32789
- const runtime = await AcpProcessSession.start(
33261
+ inspectAgentSettings = async (options) => await this.#runWithTransientProcess(
33262
+ options.signal,
33263
+ async () => await AcpProcessSession.start(
32790
33264
  {
32791
33265
  ...options,
32792
33266
  sessionId: `agent-settings-${crypto.randomUUID()}`
32793
33267
  },
32794
33268
  () => this.#agentSettingsObserver,
32795
33269
  new MemoryAcpSessionStore()
32796
- );
32797
- try {
33270
+ ),
33271
+ (runtime) => {
32798
33272
  const prepared = runtime.prepared();
32799
- return new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions);
32800
- } finally {
32801
- await runtime.close();
32802
- }
32803
- };
33273
+ return Promise.resolve(
33274
+ new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions)
33275
+ );
33276
+ },
33277
+ async (runtime) => await runtime.close()
33278
+ );
32804
33279
  /**
32805
33280
  * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
32806
33281
  * Use inspectAgentSettings for Agent-scoped settings discovery.
@@ -32809,18 +33284,20 @@ var AcpSessionManager = class {
32809
33284
  if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
32810
33285
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
32811
33286
  }
32812
- const runtime = await this.#startPreparation(options, metrics);
33287
+ this.#beginSessionUse(options.sessionId);
32813
33288
  try {
32814
- return runtime.prepared();
32815
- } finally {
32816
- if (this.#sessions.get(options.sessionId) === runtime) {
32817
- this.#sessions.delete(options.sessionId);
32818
- }
33289
+ const runtime = await this.#startPreparation(options, metrics);
32819
33290
  try {
32820
- await runtime.close();
33291
+ return runtime.prepared();
32821
33292
  } finally {
32822
- this.#store.remove(options.sessionId);
33293
+ try {
33294
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
33295
+ } finally {
33296
+ this.#store.remove(options.sessionId);
33297
+ }
32823
33298
  }
33299
+ } finally {
33300
+ this.#endSessionUse(options.sessionId);
32824
33301
  }
32825
33302
  };
32826
33303
  prepareExecutionSession = async (options) => {
@@ -32841,6 +33318,7 @@ var AcpSessionManager = class {
32841
33318
  );
32842
33319
  }
32843
33320
  if (existing.usesEnvironment(options.agent.environment)) {
33321
+ this.#touchExpectedSession(options.sessionId, existing);
32844
33322
  return existing.prepared();
32845
33323
  }
32846
33324
  if (!existing.canRebind()) {
@@ -32857,6 +33335,7 @@ var AcpSessionManager = class {
32857
33335
  if (pending !== void 0) {
32858
33336
  const runtime2 = await pending;
32859
33337
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
33338
+ this.#touchExpectedNativeBrowserSession(options.sessionId, runtime2);
32860
33339
  return runtime2.prepared();
32861
33340
  }
32862
33341
  return await this.prepareNativeSessionBrowser(options);
@@ -32864,6 +33343,7 @@ var AcpSessionManager = class {
32864
33343
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
32865
33344
  if (existing !== void 0) {
32866
33345
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
33346
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
32867
33347
  return existing.prepared();
32868
33348
  }
32869
33349
  if (!existing.canRebind()) {
@@ -32880,8 +33360,13 @@ var AcpSessionManager = class {
32880
33360
  return runtime.prepared();
32881
33361
  };
32882
33362
  configureSession = async (options) => {
32883
- const runtime = await this.ensureSession(options);
32884
- return await runtime.configure(options);
33363
+ this.#beginSessionUse(options.sessionId);
33364
+ try {
33365
+ const runtime = await this.ensureSession(options);
33366
+ return await runtime.configure(options);
33367
+ } finally {
33368
+ this.#endSessionUse(options.sessionId);
33369
+ }
32885
33370
  };
32886
33371
  cancelPrompt = async (sessionId) => {
32887
33372
  const existing = this.#cancellationRequests.get(sessionId);
@@ -32897,6 +33382,8 @@ var AcpSessionManager = class {
32897
33382
  } finally {
32898
33383
  if (this.#sessions.get(sessionId) === runtime) {
32899
33384
  this.#sessions.delete(sessionId);
33385
+ this.#retainedProcesses.delete(runtime);
33386
+ this.#notifyProcessCapacityChanged();
32900
33387
  }
32901
33388
  }
32902
33389
  }
@@ -32986,10 +33473,7 @@ var AcpSessionManager = class {
32986
33473
  return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
32987
33474
  } catch (error62) {
32988
33475
  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();
33476
+ await this.#cancellationRequests.get(options.sessionId);
32993
33477
  return { stopReason: "cancelled" };
32994
33478
  }
32995
33479
  throw error62;
@@ -32997,8 +33481,11 @@ var AcpSessionManager = class {
32997
33481
  } catch (error62) {
32998
33482
  const failedRuntime = this.#sessions.get(options.sessionId);
32999
33483
  if (failedRuntime !== void 0) {
33000
- this.#sessions.delete(options.sessionId);
33001
- await failedRuntime.close();
33484
+ await this.#retireSessionProcess(
33485
+ options.sessionId,
33486
+ failedRuntime,
33487
+ async () => await failedRuntime.close()
33488
+ );
33002
33489
  }
33003
33490
  if (this.#cancellationRequests.has(options.sessionId)) {
33004
33491
  return { stopReason: "cancelled" };
@@ -33019,6 +33506,8 @@ var AcpSessionManager = class {
33019
33506
  this.#activeCommandIds.delete(options.sessionId);
33020
33507
  }
33021
33508
  this.#cancellationRequests.delete(options.sessionId);
33509
+ this.#touchSession(options.sessionId);
33510
+ this.#notifyProcessCapacityChanged();
33022
33511
  }
33023
33512
  }
33024
33513
  };
@@ -33037,11 +33526,16 @@ var AcpSessionManager = class {
33037
33526
  await runtime.respondElicitation(options);
33038
33527
  };
33039
33528
  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()));
33529
+ const sessions = [...this.#sessions.entries()];
33530
+ const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
33531
+ await Promise.all([
33532
+ ...sessions.map(
33533
+ async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
33534
+ ),
33535
+ ...nativeBrowserSessions.map(
33536
+ async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
33537
+ )
33538
+ ]);
33045
33539
  };
33046
33540
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
33047
33541
  ensureSession = async (options) => {
@@ -33054,6 +33548,7 @@ var AcpSessionManager = class {
33054
33548
  "session_identity_mismatch"
33055
33549
  );
33056
33550
  }
33551
+ this.#touchExpectedSession(options.sessionId, existing);
33057
33552
  return existing;
33058
33553
  }
33059
33554
  await this.prepareSession(options);
@@ -33073,6 +33568,7 @@ var AcpSessionManager = class {
33073
33568
  "session_identity_mismatch"
33074
33569
  );
33075
33570
  }
33571
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
33076
33572
  return existing;
33077
33573
  }
33078
33574
  await this.prepareNativeSessionBrowser(options);
@@ -33082,7 +33578,14 @@ var AcpSessionManager = class {
33082
33578
  }
33083
33579
  return started;
33084
33580
  }
33085
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
33581
+ listNativeSessions = async (options, cursor) => {
33582
+ this.#beginNativeBrowserUse(options.sessionId);
33583
+ try {
33584
+ return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
33585
+ } finally {
33586
+ this.#endNativeBrowserUse(options.sessionId);
33587
+ }
33588
+ };
33086
33589
  previewNativeSession = async (options, nativeSessionId) => {
33087
33590
  const key = `${options.agent.id}:${nativeSessionId}`;
33088
33591
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
@@ -33095,17 +33598,19 @@ var AcpSessionManager = class {
33095
33598
  }
33096
33599
  this.#nativeOperations.add(key);
33097
33600
  try {
33098
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
33099
- options,
33100
- () => this.#nativeBrowserObserver,
33101
- new MemoryAcpSessionStore()
33601
+ return await this.#runWithTransientProcess(
33602
+ options.signal,
33603
+ async () => await AcpProcessSession.startNativeSessionBrowser(
33604
+ options,
33605
+ () => this.#nativeBrowserObserver,
33606
+ new MemoryAcpSessionStore()
33607
+ ),
33608
+ async (runtime) => {
33609
+ runtime.selectNativeSession(nativeSessionId);
33610
+ return await runtime.loadHistory(options.signal);
33611
+ },
33612
+ async (runtime) => await runtime.closeProcess()
33102
33613
  );
33103
- try {
33104
- runtime.selectNativeSession(nativeSessionId);
33105
- return await runtime.loadHistory(options.signal);
33106
- } finally {
33107
- await runtime.closeProcess();
33108
- }
33109
33614
  } finally {
33110
33615
  this.#nativeOperations.delete(key);
33111
33616
  }
@@ -33125,36 +33630,46 @@ var AcpSessionManager = class {
33125
33630
  }
33126
33631
  const existing = linked[0];
33127
33632
  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);
33633
+ this.#beginSessionUse(existing.sessionId);
33140
33634
  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;
33635
+ const runtime = await this.ensureSession({
33636
+ ...options,
33637
+ sessionId: existing.sessionId
33638
+ });
33639
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
33640
+ throw new AcpExecutionError(
33641
+ "Wait for the native session's running operation to finish",
33642
+ {},
33643
+ "session_busy"
33644
+ );
33645
+ }
33646
+ this.#nativeOperations.add(key);
33647
+ try {
33648
+ const history = await runtime.loadHistory(options.signal);
33649
+ return {
33650
+ prepared: runtime.prepared(),
33651
+ sessionId: existing.sessionId,
33652
+ history
33653
+ };
33654
+ } catch (error62) {
33655
+ await this.#retireSessionProcess(
33656
+ existing.sessionId,
33657
+ runtime,
33658
+ async () => await runtime.closeProcess()
33659
+ );
33660
+ throw error62;
33661
+ } finally {
33662
+ this.#nativeOperations.delete(key);
33663
+ this.#notifyProcessCapacityChanged();
33664
+ }
33151
33665
  } finally {
33152
- this.#nativeOperations.delete(key);
33666
+ this.#endSessionUse(existing.sessionId);
33153
33667
  }
33154
33668
  }
33155
33669
  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
33670
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
33157
33671
  }
33672
+ this.#beginSessionUse(options.sessionId);
33158
33673
  this.#nativeOperations.add(key);
33159
33674
  try {
33160
33675
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -33168,23 +33683,23 @@ var AcpSessionManager = class {
33168
33683
  history
33169
33684
  };
33170
33685
  } catch (error62) {
33171
- this.#sessions.delete(options.sessionId);
33172
33686
  this.#store.remove(options.sessionId);
33173
- await runtime.closeProcess();
33687
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
33174
33688
  throw error62;
33175
33689
  } finally {
33176
33690
  this.#nativeOperations.delete(openedKey);
33691
+ this.#notifyProcessCapacityChanged();
33177
33692
  }
33178
33693
  } catch (error62) {
33179
33694
  this.#store.remove(options.sessionId);
33180
33695
  const runtime = this.#sessions.get(options.sessionId);
33181
- this.#sessions.delete(options.sessionId);
33182
33696
  if (runtime !== void 0) {
33183
- await runtime.closeProcess();
33697
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
33184
33698
  }
33185
33699
  throw error62;
33186
33700
  } finally {
33187
33701
  this.#nativeOperations.delete(key);
33702
+ this.#endSessionUse(options.sessionId);
33188
33703
  }
33189
33704
  };
33190
33705
  forkSessionAtTurn = async (options, sourceSessionId, forkPoint) => {
@@ -33222,6 +33737,7 @@ var AcpSessionManager = class {
33222
33737
  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
33738
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
33224
33739
  }
33740
+ this.#beginSessionUse(options.sessionId);
33225
33741
  this.#nativeOperations.add(key);
33226
33742
  try {
33227
33743
  const runtime = await this.#startSessionForkAtTurnPreparation(
@@ -33238,48 +33754,58 @@ var AcpSessionManager = class {
33238
33754
  sessionId: options.sessionId
33239
33755
  };
33240
33756
  } catch (error62) {
33241
- this.#sessions.delete(options.sessionId);
33242
33757
  this.#store.remove(options.sessionId);
33243
- await runtime.closeProcess();
33758
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
33244
33759
  throw error62;
33245
33760
  } finally {
33246
33761
  this.#nativeOperations.delete(openedKey);
33762
+ this.#notifyProcessCapacityChanged();
33247
33763
  }
33248
33764
  } finally {
33249
33765
  this.#nativeOperations.delete(key);
33766
+ this.#endSessionUse(options.sessionId);
33250
33767
  }
33251
33768
  };
33252
33769
  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);
33770
+ this.#beginNativeBrowserUse(options.sessionId);
33264
33771
  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();
33772
+ const runtime = await this.#ensureNativeSessionBrowser(options);
33773
+ const key = `${options.agent.id}:${nativeSessionId}`;
33774
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
33775
+ if (this.#nativeOperations.has(key) || linked.some(
33776
+ (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
33777
+ )) {
33778
+ throw new AcpExecutionError(
33779
+ "Wait for the native session's running operation to finish",
33780
+ {},
33781
+ "session_busy"
33782
+ );
33783
+ }
33784
+ this.#nativeOperations.add(key);
33785
+ try {
33786
+ for (const entry of linked) {
33787
+ const active = this.#sessions.get(entry.sessionId);
33788
+ if (active !== void 0 && active !== runtime) {
33789
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
33790
+ }
33270
33791
  }
33792
+ options.signal.throwIfAborted();
33793
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
33794
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
33795
+ if (runtime.nativeSessionId() === nativeSessionId) {
33796
+ await this.#retireNativeBrowserProcess(
33797
+ options.sessionId,
33798
+ runtime,
33799
+ async () => await runtime.close()
33800
+ );
33801
+ }
33802
+ return deleted;
33803
+ } finally {
33804
+ this.#nativeOperations.delete(key);
33805
+ this.#notifyProcessCapacityChanged();
33271
33806
  }
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
33807
  } finally {
33282
- this.#nativeOperations.delete(key);
33808
+ this.#endNativeBrowserUse(options.sessionId);
33283
33809
  }
33284
33810
  };
33285
33811
  };
@@ -33368,21 +33894,8 @@ import { randomBytes } from "node:crypto";
33368
33894
 
33369
33895
  // src/bots/local-bot-grant-store.ts
33370
33896
  import { createHash, randomUUID } from "node:crypto";
33371
- import { stat as stat3 } from "node:fs/promises";
33372
33897
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
33373
33898
  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
33899
  var LocalBotAuthorizationError = class extends Error {
33387
33900
  code;
33388
33901
  constructor(code, message, options = {}) {
@@ -33437,19 +33950,8 @@ function agentDigest(agent) {
33437
33950
  })
33438
33951
  );
33439
33952
  }
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
- );
33953
+ function workspaceDigest(path2) {
33954
+ return digest(path2);
33453
33955
  }
33454
33956
  function exactTargets(left, right) {
33455
33957
  if (left.length !== right.length) {
@@ -33483,6 +33985,16 @@ function rowInteger(row, key) {
33483
33985
  }
33484
33986
  return value;
33485
33987
  }
33988
+ function rowHasInteger(row, key) {
33989
+ const value = Reflect.get(row, key);
33990
+ if (value === null) {
33991
+ return false;
33992
+ }
33993
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
33994
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
33995
+ }
33996
+ return true;
33997
+ }
33486
33998
  function parseTargets(encoded) {
33487
33999
  let value;
33488
34000
  try {
@@ -33506,17 +34018,6 @@ function parseSessionConfigurations(encoded) {
33506
34018
  }
33507
34019
  var LocalBotGrantStore = class {
33508
34020
  #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
34021
  constructor(path2) {
33521
34022
  this.#database = new DatabaseSync3(path2);
33522
34023
  this.#database.exec(`
@@ -33554,78 +34055,6 @@ var LocalBotGrantStore = class {
33554
34055
  ) STRICT;
33555
34056
  `);
33556
34057
  }
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
34058
  approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
33630
34059
  signal.throwIfAborted();
33631
34060
  const existing = this.#database.prepare(
@@ -33715,8 +34144,7 @@ var LocalBotGrantStore = class {
33715
34144
  WHERE grants.local_grant_id = ? AND grants.bot_id = ?
33716
34145
  AND behavior_revision_id = ? AND behavior_digest = ?
33717
34146
  AND binding_id = ? AND binding_revision = ?
33718
- AND agent_ref = ?
33719
- AND revoked_at IS NULL AND expires_at > ?`
34147
+ AND agent_ref = ?`
33720
34148
  ).get(
33721
34149
  command.localGrantId,
33722
34150
  command.botId,
@@ -33724,8 +34152,7 @@ var LocalBotGrantStore = class {
33724
34152
  command.behaviorDigest,
33725
34153
  command.bindingId,
33726
34154
  command.bindingRevision,
33727
- command.agentId,
33728
- now
34155
+ command.agentId
33729
34156
  );
33730
34157
  if (row === void 0) {
33731
34158
  throw new LocalBotAuthorizationError(
@@ -33738,14 +34165,14 @@ var LocalBotGrantStore = class {
33738
34165
  if (!exactTargets(approvedTargets, requestedTargets)) {
33739
34166
  throw new LocalBotAuthorizationError(
33740
34167
  "binding_not_approved",
33741
- "The Bot execution target policy changed after local approval"
34168
+ "The Bot execution target policy differs from its binding"
33742
34169
  );
33743
34170
  }
33744
34171
  const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
33745
34172
  if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
33746
34173
  throw new LocalBotAuthorizationError(
33747
34174
  "binding_not_approved",
33748
- "The Bot Agent configuration changed after local approval"
34175
+ "The Bot Agent configuration differs from its binding"
33749
34176
  );
33750
34177
  }
33751
34178
  const agent = catalog.find(command.agentId);
@@ -33754,17 +34181,29 @@ var LocalBotGrantStore = class {
33754
34181
  revalidateExecutable(agent.agentIdentity)
33755
34182
  ]);
33756
34183
  signal.throwIfAborted();
34184
+ if (!adapterUnchanged || !agentUnchanged) {
34185
+ throw new LocalBotAuthorizationError(
34186
+ "binding_incompatible",
34187
+ "The local Agent executable changed while the Runtime is active; restart the Runtime"
34188
+ );
34189
+ }
33757
34190
  const workspaceRef = rowString(row, "workspace_ref");
33758
34191
  const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
33759
34192
  const currentAgentDigest = agentDigest(agent);
33760
- const currentWorkspaceDigest = await workspaceDigest(workspacePath);
34193
+ const currentWorkspaceDigest = workspaceDigest(workspacePath);
33761
34194
  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"
34195
+ let expiresAt = rowInteger(row, "expires_at");
34196
+ let revocationEpoch = rowInteger(row, "revocation_epoch");
34197
+ if (currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path") || expiresAt <= now || rowHasInteger(row, "revoked_at")) {
34198
+ const refreshed = this.refreshTarget(
34199
+ rowString(row, "local_grant_id"),
34200
+ currentAgentDigest,
34201
+ currentWorkspaceDigest,
34202
+ workspacePath,
34203
+ now
33767
34204
  );
34205
+ expiresAt = refreshed.expiresAt;
34206
+ revocationEpoch = refreshed.revocationEpoch;
33768
34207
  }
33769
34208
  if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
33770
34209
  throw new LocalBotAuthorizationError(
@@ -33785,8 +34224,8 @@ var LocalBotGrantStore = class {
33785
34224
  workspacePath,
33786
34225
  currentWorkspaceDigest,
33787
34226
  approvedTargets,
33788
- rowInteger(row, "expires_at"),
33789
- rowInteger(row, "revocation_epoch")
34227
+ expiresAt,
34228
+ revocationEpoch
33790
34229
  );
33791
34230
  };
33792
34231
  recordUnavailable = (request, code, message, now) => {
@@ -33829,16 +34268,65 @@ var LocalBotGrantStore = class {
33829
34268
  return {
33830
34269
  agent,
33831
34270
  agentIdentityDigest: agentDigest(agent),
33832
- workspaceIdentityDigest: await workspaceDigest(workspacePath),
34271
+ workspaceIdentityDigest: workspaceDigest(workspacePath),
33833
34272
  workspacePath
33834
34273
  };
33835
34274
  };
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);
34275
+ refreshTarget = (localGrantId, agentIdentityDigest, workspaceIdentityDigest, workspacePath, now) => {
34276
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
34277
+ this.#database.exec("BEGIN IMMEDIATE");
34278
+ try {
34279
+ const current = this.#database.prepare("SELECT * FROM local_bot_grants WHERE local_grant_id = ?").get(localGrantId);
34280
+ if (current === void 0) {
34281
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is missing");
34282
+ }
34283
+ const currentExpiresAt = rowInteger(current, "expires_at");
34284
+ const currentRevocationEpoch = rowInteger(current, "revocation_epoch");
34285
+ if (agentIdentityDigest === rowString(current, "agent_identity_digest") && workspaceIdentityDigest === rowString(current, "workspace_identity_digest") && workspacePath === rowString(current, "workspace_path") && currentExpiresAt > now && !rowHasInteger(current, "revoked_at")) {
34286
+ this.#database.exec("COMMIT");
34287
+ return { expiresAt: currentExpiresAt, revocationEpoch: currentRevocationEpoch };
34288
+ }
34289
+ const result = this.#database.prepare(
34290
+ `UPDATE local_bot_grants
34291
+ SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
34292
+ expires_at = ?, revoked_at = NULL, revocation_epoch = revocation_epoch + 1
34293
+ WHERE local_grant_id = ? AND revocation_epoch = ?`
34294
+ ).run(
34295
+ agentIdentityDigest,
34296
+ workspaceIdentityDigest,
34297
+ workspacePath,
34298
+ expiresAt,
34299
+ localGrantId,
34300
+ currentRevocationEpoch
34301
+ );
34302
+ if (result.changes !== 1) {
34303
+ throw new LocalBotAuthorizationError(
34304
+ "local_grant_invalid",
34305
+ "The local Bot grant target could not be refreshed"
34306
+ );
34307
+ }
34308
+ this.#database.prepare(
34309
+ `INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
34310
+ VALUES (?, 'bot_binding_target_refreshed', ?, '', ?)`
34311
+ ).run(
34312
+ new Date(now).toISOString(),
34313
+ rowString(current, "binding_id"),
34314
+ JSON.stringify({
34315
+ agentIdentityChanged: agentIdentityDigest !== rowString(current, "agent_identity_digest"),
34316
+ bindingId: rowString(current, "binding_id"),
34317
+ botId: rowString(current, "bot_id"),
34318
+ expired: currentExpiresAt <= now,
34319
+ revived: rowHasInteger(current, "revoked_at"),
34320
+ workspaceIdentityChanged: workspaceIdentityDigest !== rowString(current, "workspace_identity_digest"),
34321
+ workspacePathChanged: workspacePath !== rowString(current, "workspace_path")
34322
+ })
34323
+ );
34324
+ this.#database.exec("COMMIT");
34325
+ return { expiresAt, revocationEpoch: currentRevocationEpoch + 1 };
34326
+ } catch (cause) {
34327
+ this.#database.exec("ROLLBACK");
34328
+ throw cause;
34329
+ }
33842
34330
  };
33843
34331
  };
33844
34332
 
@@ -34336,9 +34824,9 @@ var BotOutboundIpcServer = class {
34336
34824
 
34337
34825
  // src/pairing/pair-local-machine.ts
34338
34826
  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";
34827
+ import { mkdir as mkdir4, open as open4, realpath as realpath7, rename as rename3, stat as stat6, writeFile as writeFile2 } from "node:fs/promises";
34340
34828
  import { hostname as hostname3 } from "node:os";
34341
- import { basename as basename2, join as join15, resolve as resolve3 } from "node:path";
34829
+ import { basename as basename3, join as join15, resolve as resolve3 } from "node:path";
34342
34830
  import { fetch as fetch3 } from "undici";
34343
34831
 
34344
34832
  // src/agent-catalog/agent-discovery.ts
@@ -34448,7 +34936,7 @@ var LocalAgentInventory = class {
34448
34936
  };
34449
34937
 
34450
34938
  // 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";
34939
+ import { mkdir as mkdir2, mkdtemp, open as open2, realpath as realpath3, rename, rm, stat as stat3 } from "node:fs/promises";
34452
34940
  import { delimiter, dirname as dirname4, isAbsolute as isAbsolute3, join as join4, relative as relative2, sep as sep2 } from "node:path";
34453
34941
  var INSTALL_TIMEOUT_MILLISECONDS = 5 * 60 * 1e3;
34454
34942
  var PACKAGE_METADATA_LIMIT_BYTES = 64 * 1024;
@@ -34670,7 +35158,7 @@ var ManagedNpmPackageInstaller = class {
34670
35158
  install = async (root, definition2, environment, signal) => {
34671
35159
  signal.throwIfAborted();
34672
35160
  try {
34673
- const metadata = await stat4(root);
35161
+ const metadata = await stat3(root);
34674
35162
  if (metadata.isDirectory()) {
34675
35163
  return await validateManagedNpmPackage(root, definition2);
34676
35164
  }
@@ -34992,7 +35480,7 @@ var CursorCliAgentSpecification = class extends DirectAcpAgentDefinition {
34992
35480
  };
34993
35481
 
34994
35482
  // src/agent-catalog/agents/deepseek-harness-agent.ts
34995
- import { realpath as realpath4, stat as stat5 } from "node:fs/promises";
35483
+ import { realpath as realpath4, stat as stat4 } from "node:fs/promises";
34996
35484
  import { isAbsolute as isAbsolute5, join as join7, normalize as normalize2 } from "node:path";
34997
35485
 
34998
35486
  // src/agent-installation/deepseek-managed-package.ts
@@ -35016,7 +35504,7 @@ async function validateAgentHome(path2) {
35016
35504
  }
35017
35505
  try {
35018
35506
  const resolved = await realpath4(path2);
35019
- const metadata = await stat5(resolved);
35507
+ const metadata = await stat4(resolved);
35020
35508
  if (!metadata.isDirectory() || typeof process.getuid === "function" && metadata.uid !== process.getuid()) {
35021
35509
  throw new Error("Agent home is not a user-owned directory");
35022
35510
  }
@@ -35298,7 +35786,7 @@ import { join as join10 } from "node:path";
35298
35786
  // src/agent-installation/managed-agent-archive.ts
35299
35787
  import { createHash as createHash2 } from "node:crypto";
35300
35788
  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";
35789
+ 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
35790
  import { delimiter as delimiter2, dirname as dirname5, isAbsolute as isAbsolute7, join as join9, relative as relative4, sep as sep4 } from "node:path";
35303
35791
 
35304
35792
  // src/agent-installation/verified-download.ts
@@ -35480,7 +35968,7 @@ async function readManifest(path2) {
35480
35968
  async function validateManagedAgentArchive(root, definition2, signal) {
35481
35969
  try {
35482
35970
  const rootPath = await realpath6(root);
35483
- const rootMetadata = await stat6(rootPath);
35971
+ const rootMetadata = await stat5(rootPath);
35484
35972
  if (!rootMetadata.isDirectory() || typeof process.getuid === "function" && rootMetadata.uid !== process.getuid()) {
35485
35973
  throw new Error("Managed Agent root is not user-owned");
35486
35974
  }
@@ -36443,7 +36931,7 @@ async function resolveDefaultWorkspace(path2) {
36443
36931
  try {
36444
36932
  await mkdir4(requestedWorkspace, { recursive: true, mode: 448 });
36445
36933
  const defaultWorkspace = await realpath7(requestedWorkspace);
36446
- const metadata = await stat7(defaultWorkspace);
36934
+ const metadata = await stat6(defaultWorkspace);
36447
36935
  if (!metadata.isDirectory()) {
36448
36936
  throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
36449
36937
  }
@@ -36515,7 +37003,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
36515
37003
  installableAgents,
36516
37004
  machineName: hostname3(),
36517
37005
  pairingCode: options.code,
36518
- workspaceName: basename2(defaultWorkspace) || "Local workspace"
37006
+ workspaceName: basename3(defaultWorkspace) || "Local workspace"
36519
37007
  }),
36520
37008
  dispatcher: environmentProxyDispatcher,
36521
37009
  headers: { "content-type": "application/json" },
@@ -36686,7 +37174,7 @@ async function resumeLocalMachine(arguments_, signal = new AbortController().sig
36686
37174
 
36687
37175
  // src/run-daemon.ts
36688
37176
  import { randomUUID as randomUUID6 } from "node:crypto";
36689
- import { basename as basename5, join as join17 } from "node:path";
37177
+ import { basename as basename6, join as join17 } from "node:path";
36690
37178
  import { styleText } from "node:util";
36691
37179
  import { fetch as fetch7, WebSocket as WebSocket2 } from "undici";
36692
37180
 
@@ -37549,15 +38037,15 @@ async function putContent(url2, authorization, bytes, signal) {
37549
38037
  signal
37550
38038
  });
37551
38039
  }
37552
- async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
38040
+ async function uploadRuntimeArtifact(config2, sessionId, artifact, signal) {
37553
38041
  signal.throwIfAborted();
37554
38042
  let request;
37555
38043
  try {
37556
38044
  request = new MobiusArtifactUploadRequest(
37557
- image.name,
37558
- image.mimeType,
37559
- image.bytes.byteLength,
37560
- createHash3("sha256").update(image.bytes).digest("hex")
38045
+ artifact.name,
38046
+ artifact.mimeType,
38047
+ artifact.bytes.byteLength,
38048
+ createHash3("sha256").update(artifact.bytes).digest("hex")
37561
38049
  );
37562
38050
  } catch (cause) {
37563
38051
  translateSdkError(cause);
@@ -37596,7 +38084,7 @@ async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
37596
38084
  token
37597
38085
  ),
37598
38086
  authorization,
37599
- image.bytes,
38087
+ artifact.bytes,
37600
38088
  requestSignal
37601
38089
  );
37602
38090
  } catch (cause) {
@@ -37626,9 +38114,9 @@ async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
37626
38114
  }
37627
38115
 
37628
38116
  // src/authorization/workspace-directory.ts
37629
- import { readdir as readdir2, realpath as realpath8, stat as stat8 } from "node:fs/promises";
38117
+ import { readdir as readdir2, realpath as realpath8, stat as stat7 } from "node:fs/promises";
37630
38118
  import { homedir as homedir2 } from "node:os";
37631
- import { basename as basename3, dirname as dirname6, isAbsolute as isAbsolute10, join as join16, normalize as normalize3, relative as relative5 } from "node:path";
38119
+ import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute10, join as join16, normalize as normalize3, relative as relative5 } from "node:path";
37632
38120
  var WorkspaceDirectoryListing = class {
37633
38121
  directoryId;
37634
38122
  directoryLabel;
@@ -37694,7 +38182,7 @@ var WorkspaceDirectoryService = class {
37694
38182
  try {
37695
38183
  const target = await realpath8(requested);
37696
38184
  signal.throwIfAborted();
37697
- const metadata = await stat8(target);
38185
+ const metadata = await stat7(target);
37698
38186
  signal.throwIfAborted();
37699
38187
  if (!isAbsolute10(target) || normalize3(target) !== target || !metadata.isDirectory()) {
37700
38188
  throw new LocalAuthorizationError("The selected location is not a directory");
@@ -37720,7 +38208,7 @@ var WorkspaceDirectoryService = class {
37720
38208
  return {
37721
38209
  path: path2,
37722
38210
  directoryId: encodePath(path2),
37723
- name: basename3(path2) || path2,
38211
+ name: basename4(path2) || path2,
37724
38212
  label: this.label(path2)
37725
38213
  };
37726
38214
  };
@@ -37814,7 +38302,7 @@ var EmbeddedBotContextApplicator = class {
37814
38302
 
37815
38303
  // src/native-sessions/service.ts
37816
38304
  import { randomUUID as randomUUID4 } from "node:crypto";
37817
- import { basename as basename4 } from "node:path";
38305
+ import { basename as basename5 } from "node:path";
37818
38306
 
37819
38307
  // src/native-sessions/codex-history.ts
37820
38308
  import { spawn as spawn4 } from "node:child_process";
@@ -38323,7 +38811,7 @@ var NativeSessionService = class {
38323
38811
  }
38324
38812
  resolvedPaths.add(path2);
38325
38813
  additionalDirectories.push(path2);
38326
- additionalEntries.push({ directoryId: directoryId2, name: basename4(path2) });
38814
+ additionalEntries.push({ directoryId: directoryId2, name: basename5(path2) });
38327
38815
  }
38328
38816
  const listing = await this.#directories.list(this.#config.bindingId, command.directoryId, signal);
38329
38817
  const opened = await this.#sessions.forkSessionAtTurn(
@@ -39645,9 +40133,9 @@ var DaemonAcpObserver = class {
39645
40133
  this.#config = config2;
39646
40134
  this.#record = record3;
39647
40135
  }
39648
- importLocalImage = async (sessionId, image, signal) => {
40136
+ importLocalArtifact = async (sessionId, artifact, signal) => {
39649
40137
  try {
39650
- return (await uploadRuntimeArtifact(this.#config, sessionId, image, signal)).artifactId;
40138
+ return (await uploadRuntimeArtifact(this.#config, sessionId, artifact, signal)).artifactId;
39651
40139
  } catch (cause) {
39652
40140
  signal.throwIfAborted();
39653
40141
  if (cause instanceof Error && cause.name === "AbortError") {
@@ -40218,7 +40706,7 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
40218
40706
  additionalDirectories.push(directory);
40219
40707
  additionalDirectoryEntries.push({
40220
40708
  directoryId: additionalDirectoryId,
40221
- name: basename5(directory)
40709
+ name: basename6(directory)
40222
40710
  });
40223
40711
  }
40224
40712
  return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
@@ -41907,10 +42395,10 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41907
42395
  }
41908
42396
 
41909
42397
  // src/runtime.ts
41910
- import { mkdir as mkdir5, realpath as realpath9, stat as stat9 } from "node:fs/promises";
42398
+ import { mkdir as mkdir5, realpath as realpath9, stat as stat8 } from "node:fs/promises";
41911
42399
  import { dirname as dirname8, join as join18, resolve as resolve5 } from "node:path";
41912
42400
  var IDENTIFIER_PATTERN9 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
41913
- var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{43}$/;
42401
+ var RUNTIME_CREDENTIAL_PATTERN = /^(?:[a-zA-Z0-9_-]{43}|prj_[a-zA-Z0-9_-]{24}_[a-zA-Z0-9_-]{43}|prj_(?:wn|en|sa|we|ee|ap|oc|af|me)_01_[a-zA-Z0-9_-]{24}_[a-zA-Z0-9_-]{43})$/;
41914
42402
  var MobiusRuntimeConfigurationError = class extends Error {
41915
42403
  code = "runtime_configuration_invalid";
41916
42404
  constructor(message, options = {}) {
@@ -41977,7 +42465,7 @@ async function resolveWorkspace(path2) {
41977
42465
  try {
41978
42466
  await mkdir5(requested, { recursive: true, mode: 448 });
41979
42467
  const resolved = await realpath9(requested);
41980
- const metadata = await stat9(resolved);
42468
+ const metadata = await stat8(resolved);
41981
42469
  if (!metadata.isDirectory()) {
41982
42470
  throw new MobiusRuntimeConfigurationError("The Runtime workspace is not a directory");
41983
42471
  }