@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/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
@@ -22691,7 +22691,7 @@ var displayContentSchema = external_exports.strictObject({
22691
22691
  path: external_exports.string().max(2048),
22692
22692
  terminalId: external_exports.string().max(255),
22693
22693
  text: LONG_TEXT,
22694
- type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text"]),
22694
+ type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text", "video"]),
22695
22695
  uri: external_exports.string().max(4096)
22696
22696
  }).readonly();
22697
22697
  var recordedDisplayContentSchema = external_exports.strictObject({
@@ -22704,7 +22704,7 @@ var recordedDisplayContentSchema = external_exports.strictObject({
22704
22704
  path: external_exports.string().max(2048),
22705
22705
  terminalId: external_exports.string().max(255),
22706
22706
  text: external_exports.string().max(4e6),
22707
- type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text"]),
22707
+ type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text", "video"]),
22708
22708
  uri: external_exports.string().max(4096)
22709
22709
  }).readonly();
22710
22710
  var promptImageSchema = external_exports.strictObject({
@@ -22751,8 +22751,17 @@ var sessionPrepareCommandSchema = external_exports.strictObject({
22751
22751
  }).readonly().optional(),
22752
22752
  kind: external_exports.literal(SESSION_PREPARE_KIND),
22753
22753
  requestId: IDENTIFIER,
22754
+ sessionState: external_exports.literal("provisioned").optional(),
22754
22755
  /** @deprecated Reserved for the legacy Bot Agent-configuration endpoint. */
22755
22756
  transient: external_exports.boolean().optional()
22757
+ }).superRefine((command, context) => {
22758
+ if (command.transient === true && command.sessionState === "provisioned") {
22759
+ context.addIssue({
22760
+ code: "custom",
22761
+ message: "A transient Session cannot already be provisioned",
22762
+ path: ["sessionState"]
22763
+ });
22764
+ }
22756
22765
  }).readonly();
22757
22766
  var runtimeTimingsSchema = external_exports.array(
22758
22767
  external_exports.strictObject({
@@ -24297,7 +24306,7 @@ function createDaemonConfig(connection, agents = [], installableAgents = []) {
24297
24306
 
24298
24307
  // src/run-daemon.ts
24299
24308
  import { randomUUID as randomUUID4 } from "node:crypto";
24300
- import { basename as basename4, join as join16 } from "node:path";
24309
+ import { basename as basename5, join as join16 } from "node:path";
24301
24310
  import { styleText } from "node:util";
24302
24311
  import { fetch as fetch6, WebSocket as WebSocket2 } from "undici";
24303
24312
 
@@ -24460,6 +24469,55 @@ async function readAuthorizedRaster(uri, roots, signal) {
24460
24469
  return new LocalRasterImage(basename(target) || "Image", mimeType, bytes);
24461
24470
  }
24462
24471
 
24472
+ // src/authorization/local-video.ts
24473
+ import { basename as basename2 } from "node:path";
24474
+ var MAX_INLINE_VIDEO_BYTES = 3e6;
24475
+ var MP4_FILE_TYPE = new TextEncoder().encode("ftyp");
24476
+ var WEBM_SIGNATURE = Uint8Array.of(26, 69, 223, 163);
24477
+ var LocalVideo = class {
24478
+ bytes;
24479
+ mimeType;
24480
+ name;
24481
+ constructor(name, mimeType, bytes) {
24482
+ this.bytes = bytes;
24483
+ this.mimeType = mimeType;
24484
+ this.name = name;
24485
+ }
24486
+ base64 = () => Buffer.from(this.bytes).toString("base64");
24487
+ };
24488
+ function startsWith2(bytes, signature, offset = 0) {
24489
+ if (bytes.byteLength < offset + signature.byteLength) {
24490
+ return false;
24491
+ }
24492
+ return signature.every((value, index2) => bytes[offset + index2] === value);
24493
+ }
24494
+ function sniffVideoMime(bytes) {
24495
+ if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
24496
+ return "video/mp4";
24497
+ }
24498
+ if (startsWith2(bytes, WEBM_SIGNATURE)) {
24499
+ return "video/webm";
24500
+ }
24501
+ return null;
24502
+ }
24503
+ function readInlineVideo(data, declaredMimeType, name = "Video") {
24504
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_VIDEO_BYTES / 3) * 4 || data.length % 4 !== 0) {
24505
+ return null;
24506
+ }
24507
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
24508
+ return null;
24509
+ }
24510
+ const bytes = new Uint8Array(Buffer.from(data, "base64"));
24511
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_VIDEO_BYTES) {
24512
+ return null;
24513
+ }
24514
+ const mimeType = sniffVideoMime(bytes);
24515
+ if (mimeType === null || mimeType !== declaredMimeType) {
24516
+ return null;
24517
+ }
24518
+ return new LocalVideo(basename2(name) || "Video", mimeType, bytes);
24519
+ }
24520
+
24463
24521
  // src/infra/operation-metrics.ts
24464
24522
  var AccumulatingOperationMetrics = class {
24465
24523
  #durations = /* @__PURE__ */ new Map();
@@ -24717,6 +24775,14 @@ function emptyDisplayContent(type) {
24717
24775
  uri: ""
24718
24776
  };
24719
24777
  }
24778
+ function resourceName(uri) {
24779
+ try {
24780
+ const pathname = new URL(uri).pathname;
24781
+ return decodeURIComponent(pathname.slice(pathname.lastIndexOf("/") + 1));
24782
+ } catch {
24783
+ return "";
24784
+ }
24785
+ }
24720
24786
  function imageDisplayContent(mimeType, name, data, artifactId = "", uri = "") {
24721
24787
  return {
24722
24788
  ...emptyDisplayContent("image"),
@@ -24748,18 +24814,21 @@ function normalizeContentBlock(content3) {
24748
24814
  };
24749
24815
  }
24750
24816
  if (content3.type === "resource") {
24817
+ const type = content3.resource.mimeType?.startsWith("video/") === true ? "video" : "resource";
24751
24818
  if ("text" in content3.resource) {
24752
24819
  return {
24753
- ...emptyDisplayContent("resource"),
24820
+ ...emptyDisplayContent(type),
24754
24821
  mimeType: content3.resource.mimeType ?? "",
24822
+ name: resourceName(content3.resource.uri),
24755
24823
  text: content3.resource.text,
24756
24824
  uri: content3.resource.uri
24757
24825
  };
24758
24826
  }
24759
24827
  return {
24760
- ...emptyDisplayContent("resource"),
24828
+ ...emptyDisplayContent(type),
24761
24829
  data: content3.resource.blob,
24762
24830
  mimeType: content3.resource.mimeType ?? "",
24831
+ name: resourceName(content3.resource.uri),
24763
24832
  uri: content3.resource.uri
24764
24833
  };
24765
24834
  }
@@ -24792,6 +24861,36 @@ async function normalizeToolContent(content3, prepareContent) {
24792
24861
  }
24793
24862
  return normalized;
24794
24863
  }
24864
+ function rawMcpToolContent(rawOutput) {
24865
+ if (!isRecord6(rawOutput)) {
24866
+ return [];
24867
+ }
24868
+ const result = isRecord6(rawOutput["result"]) ? rawOutput["result"] : rawOutput;
24869
+ const content3 = result["content"];
24870
+ if (!Array.isArray(content3)) {
24871
+ return [];
24872
+ }
24873
+ return content3.flatMap((item) => {
24874
+ if (!isRecord6(item) || item["type"] !== "image" || typeof item["data"] !== "string" || typeof item["mimeType"] !== "string") {
24875
+ return [];
24876
+ }
24877
+ const uri = item["uri"];
24878
+ return [
24879
+ {
24880
+ type: "content",
24881
+ content: {
24882
+ type: "image",
24883
+ data: item["data"],
24884
+ mimeType: item["mimeType"],
24885
+ ...typeof uri === "string" ? { uri } : {}
24886
+ }
24887
+ }
24888
+ ];
24889
+ });
24890
+ }
24891
+ function toolContent(content3, rawOutput) {
24892
+ return content3 !== void 0 && content3 !== null && content3.length > 0 ? content3 : rawMcpToolContent(rawOutput);
24893
+ }
24795
24894
  function normalizeLocations(locations) {
24796
24895
  const normalized = [];
24797
24896
  const unique = /* @__PURE__ */ new Set();
@@ -24955,7 +25054,10 @@ var AcpActivityTracker = class {
24955
25054
  const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
24956
25055
  const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
24957
25056
  const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
24958
- const detailContent = await normalizeToolContent(update.content ?? [], this.#prepareContent);
25057
+ const detailContent = await normalizeToolContent(
25058
+ toolContent(update.content, update.rawOutput),
25059
+ this.#prepareContent
25060
+ );
24959
25061
  await this.#record(
24960
25062
  key,
24961
25063
  new AcpActivity(
@@ -24981,10 +25083,11 @@ var AcpActivityTracker = class {
24981
25083
  const identity2 = this.#identity(key);
24982
25084
  const previousDetail = recordedDetail(previous2);
24983
25085
  const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous2?.output ?? "";
24984
- const content3 = update.content === void 0 || update.content === null ? previous2?.content ?? [] : await normalizeToolContent(update.content, this.#prepareContent);
25086
+ const nextContent = toolContent(update.content, update.rawOutput);
25087
+ const content3 = nextContent.length === 0 ? previous2?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
24985
25088
  const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous2?.input ?? "" : formatUnknownDetail(update.rawInput);
24986
25089
  const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous2?.output ?? "";
24987
- const detailContent = update.content === void 0 || update.content === null ? previousDetail?.content ?? previous2?.content ?? [] : content3;
25090
+ const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous2?.content ?? [] : content3;
24988
25091
  await this.#record(
24989
25092
  key,
24990
25093
  new AcpActivity(
@@ -29061,7 +29164,7 @@ var titleBefore = {
29061
29164
  };
29062
29165
  function tokenizeDefinition(effects, ok2, nok) {
29063
29166
  const self = this;
29064
- let identifier3;
29167
+ let identifier2;
29065
29168
  return start;
29066
29169
  function start(code) {
29067
29170
  effects.enter("definition");
@@ -29080,7 +29183,7 @@ function tokenizeDefinition(effects, ok2, nok) {
29080
29183
  )(code);
29081
29184
  }
29082
29185
  function labelAfter(code) {
29083
- identifier3 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
29186
+ identifier2 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
29084
29187
  if (code === 58) {
29085
29188
  effects.enter("definitionMarker");
29086
29189
  effects.consume(code);
@@ -29114,7 +29217,7 @@ function tokenizeDefinition(effects, ok2, nok) {
29114
29217
  function afterWhitespace(code) {
29115
29218
  if (code === null || markdownLineEnding(code)) {
29116
29219
  effects.exit("definition");
29117
- self.parser.defined.push(identifier3);
29220
+ self.parser.defined.push(identifier2);
29118
29221
  return ok2(code);
29119
29222
  }
29120
29223
  return nok(code);
@@ -32949,11 +33052,12 @@ var SqliteAcpSessionStore = class {
32949
33052
 
32950
33053
  // src/acp/session-manager.ts
32951
33054
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
33055
+ var MAX_ACP_PROCESSES = 10;
32952
33056
  var MAX_PRE_SESSION_UPDATES = 100;
32953
33057
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
32954
33058
  var SESSION_CONTROL_COMMAND_ID = "session-control";
32955
33059
  var NullAcpSessionObserver = class {
32956
- importLocalImage = (_sessionId, _image, signal) => {
33060
+ importLocalArtifact = (_sessionId, _artifact, signal) => {
32957
33061
  signal.throwIfAborted();
32958
33062
  return Promise.resolve("");
32959
33063
  };
@@ -33007,6 +33111,91 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
33007
33111
  this.name = "RetryableAcpInitializationError";
33008
33112
  }
33009
33113
  };
33114
+ var AcpProcessCapacityLease = class {
33115
+ #releaseCapacity;
33116
+ #released = false;
33117
+ constructor(releaseCapacity) {
33118
+ this.#releaseCapacity = releaseCapacity;
33119
+ }
33120
+ release = () => {
33121
+ if (this.#released) {
33122
+ return;
33123
+ }
33124
+ this.#released = true;
33125
+ this.#releaseCapacity();
33126
+ };
33127
+ };
33128
+ var AcpProcessCapacityWaiter = class {
33129
+ completion = Promise.withResolvers();
33130
+ signal;
33131
+ constructor(signal) {
33132
+ this.signal = signal;
33133
+ }
33134
+ cancel = () => {
33135
+ try {
33136
+ this.signal.throwIfAborted();
33137
+ } catch (error62) {
33138
+ this.completion.reject(error62);
33139
+ }
33140
+ };
33141
+ };
33142
+ var AcpProcessCapacityLock = class {
33143
+ #locked = false;
33144
+ #waiters = [];
33145
+ acquire = async (signal) => {
33146
+ signal.throwIfAborted();
33147
+ if (!this.#locked) {
33148
+ this.#locked = true;
33149
+ return new AcpProcessCapacityLease(this.#release);
33150
+ }
33151
+ const waiter = new AcpProcessCapacityWaiter(signal);
33152
+ this.#waiters.push(waiter);
33153
+ signal.addEventListener("abort", waiter.cancel, { once: true });
33154
+ if (signal.aborted) {
33155
+ waiter.cancel();
33156
+ }
33157
+ try {
33158
+ return await waiter.completion.promise;
33159
+ } finally {
33160
+ signal.removeEventListener("abort", waiter.cancel);
33161
+ const index2 = this.#waiters.indexOf(waiter);
33162
+ if (index2 >= 0) {
33163
+ this.#waiters.splice(index2, 1);
33164
+ }
33165
+ }
33166
+ };
33167
+ #release = () => {
33168
+ while (this.#waiters.length > 0) {
33169
+ const waiter = this.#waiters.shift();
33170
+ if (waiter === void 0 || waiter.signal.aborted) {
33171
+ continue;
33172
+ }
33173
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
33174
+ return;
33175
+ }
33176
+ this.#locked = false;
33177
+ };
33178
+ };
33179
+ async function waitForAcpProcessCapacity(completion, signal) {
33180
+ signal.throwIfAborted();
33181
+ const cancelled = Promise.withResolvers();
33182
+ const cancel = () => {
33183
+ try {
33184
+ signal.throwIfAborted();
33185
+ } catch (error62) {
33186
+ cancelled.reject(error62);
33187
+ }
33188
+ };
33189
+ signal.addEventListener("abort", cancel, { once: true });
33190
+ if (signal.aborted) {
33191
+ cancel();
33192
+ }
33193
+ try {
33194
+ await Promise.race([completion, cancelled.promise]);
33195
+ } finally {
33196
+ signal.removeEventListener("abort", cancel);
33197
+ }
33198
+ }
33010
33199
  function readableWebStream(input2) {
33011
33200
  let streamOpen = true;
33012
33201
  return new ReadableStream({
@@ -33635,6 +33824,13 @@ var AcpProcessSession = class _AcpProcessSession {
33635
33824
  return await this.importRaster(raster, signal);
33636
33825
  }
33637
33826
  }
33827
+ if (content3.type === "video" && content3.data.length > 0) {
33828
+ const video = readInlineVideo(content3.data, content3.mimeType, content3.name);
33829
+ if (video === null) {
33830
+ return { ...content3, data: "" };
33831
+ }
33832
+ return await this.importVideo(video, AbortSignal.timeout(2e4));
33833
+ }
33638
33834
  return content3;
33639
33835
  };
33640
33836
  emitAgentContent = async (content3, messageId) => {
@@ -33660,7 +33856,7 @@ var AcpProcessSession = class _AcpProcessSession {
33660
33856
  });
33661
33857
  };
33662
33858
  importRaster = async (raster, signal) => {
33663
- const artifactId = await this.#getObserver().importLocalImage(this.#mobiusSessionId, raster, signal);
33859
+ const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, raster, signal);
33664
33860
  return imageDisplayContent(
33665
33861
  raster.mimeType,
33666
33862
  raster.name,
@@ -33668,6 +33864,22 @@ var AcpProcessSession = class _AcpProcessSession {
33668
33864
  artifactId
33669
33865
  );
33670
33866
  };
33867
+ importVideo = async (video, signal) => {
33868
+ const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, video, signal);
33869
+ return {
33870
+ artifactId,
33871
+ data: artifactId.length > 0 ? "" : video.base64(),
33872
+ mimeType: video.mimeType,
33873
+ name: video.name,
33874
+ newText: "",
33875
+ oldText: "",
33876
+ path: "",
33877
+ terminalId: "",
33878
+ text: "",
33879
+ type: "video",
33880
+ uri: ""
33881
+ };
33882
+ };
33671
33883
  async #initializeAgent(signal) {
33672
33884
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
33673
33885
  }
@@ -34494,20 +34706,23 @@ var AcpProcessSession = class _AcpProcessSession {
34494
34706
  }
34495
34707
  };
34496
34708
  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 {
34709
+ try {
34710
+ await this.cancelPendingInteractions();
34711
+ if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
34712
+ try {
34713
+ await this.#connection.agent.request(
34714
+ methods6.agent.session.close,
34715
+ { sessionId: this.#nativeSessionId },
34716
+ {
34717
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
34718
+ }
34719
+ );
34720
+ } catch {
34721
+ }
34508
34722
  }
34723
+ } finally {
34724
+ await this.closeProcess();
34509
34725
  }
34510
- await this.closeProcess();
34511
34726
  };
34512
34727
  closeProcess = async (capturedProcesses = []) => {
34513
34728
  try {
@@ -34614,6 +34829,31 @@ var AcpProcessSession = class _AcpProcessSession {
34614
34829
  }
34615
34830
  };
34616
34831
  };
34832
+ var AcpProcessEvictionCandidate = class {
34833
+ };
34834
+ var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
34835
+ };
34836
+ var FoundAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
34837
+ runtime;
34838
+ constructor(runtime) {
34839
+ super();
34840
+ this.runtime = runtime;
34841
+ }
34842
+ };
34843
+ var FoundAcpSessionProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
34844
+ sessionId;
34845
+ constructor(sessionId, runtime) {
34846
+ super(runtime);
34847
+ this.sessionId = sessionId;
34848
+ }
34849
+ };
34850
+ var FoundAcpNativeBrowserProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
34851
+ sessionId;
34852
+ constructor(sessionId, runtime) {
34853
+ super(runtime);
34854
+ this.sessionId = sessionId;
34855
+ }
34856
+ };
34617
34857
  var AcpSessionManager = class {
34618
34858
  #activeCommandIds = /* @__PURE__ */ new Map();
34619
34859
  #agentSettingsObserver = new NullAcpSessionObserver();
@@ -34622,10 +34862,18 @@ var AcpSessionManager = class {
34622
34862
  #nativeBrowserPreparing = /* @__PURE__ */ new Map();
34623
34863
  #nativeBrowserSessions = /* @__PURE__ */ new Map();
34624
34864
  #nativeBrowserStore = new MemoryAcpSessionStore();
34865
+ #nativeBrowserUseCounts = /* @__PURE__ */ new Map();
34625
34866
  #activeSessionIds = /* @__PURE__ */ new Set();
34626
34867
  #cancellationRequests = /* @__PURE__ */ new Map();
34627
34868
  #preparing = /* @__PURE__ */ new Map();
34869
+ #processCapacityChanged = Promise.withResolvers();
34870
+ #processCapacityLock = new AcpProcessCapacityLock();
34871
+ #retainedProcesses = /* @__PURE__ */ new Map();
34872
+ #retiringProcessCount = 0;
34873
+ #sessionUseCounts = /* @__PURE__ */ new Map();
34628
34874
  #sessions = /* @__PURE__ */ new Map();
34875
+ #startingProcessCount = 0;
34876
+ #transientProcessCount = 0;
34629
34877
  #store;
34630
34878
  #observer;
34631
34879
  constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore()) {
@@ -34635,18 +34883,230 @@ var AcpSessionManager = class {
34635
34883
  setObserver = (observer) => {
34636
34884
  this.#observer = observer;
34637
34885
  };
34886
+ #notifyProcessCapacityChanged() {
34887
+ const changed = this.#processCapacityChanged;
34888
+ this.#processCapacityChanged = Promise.withResolvers();
34889
+ changed.resolve();
34890
+ }
34891
+ #touchSession(sessionId) {
34892
+ const runtime = this.#sessions.get(sessionId);
34893
+ if (runtime === void 0) {
34894
+ return;
34895
+ }
34896
+ this.#touchProcess(runtime);
34897
+ }
34898
+ #touchExpectedSession(sessionId, expected) {
34899
+ if (this.#sessions.get(sessionId) !== expected) {
34900
+ return;
34901
+ }
34902
+ this.#touchProcess(expected);
34903
+ }
34904
+ #touchNativeBrowserSession(sessionId) {
34905
+ const runtime = this.#nativeBrowserSessions.get(sessionId);
34906
+ if (runtime === void 0) {
34907
+ return;
34908
+ }
34909
+ this.#touchProcess(runtime);
34910
+ }
34911
+ #touchExpectedNativeBrowserSession(sessionId, expected) {
34912
+ if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
34913
+ return;
34914
+ }
34915
+ this.#touchProcess(expected);
34916
+ }
34917
+ #touchProcess(runtime) {
34918
+ const retained = this.#retainedProcesses.get(runtime);
34919
+ if (retained === void 0) {
34920
+ return;
34921
+ }
34922
+ this.#retainedProcesses.delete(runtime);
34923
+ this.#retainedProcesses.set(runtime, retained);
34924
+ }
34925
+ #beginSessionUse(sessionId) {
34926
+ this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
34927
+ this.#touchSession(sessionId);
34928
+ }
34929
+ #endSessionUse(sessionId) {
34930
+ const count = this.#sessionUseCounts.get(sessionId) ?? 0;
34931
+ if (count <= 1) {
34932
+ this.#sessionUseCounts.delete(sessionId);
34933
+ } else {
34934
+ this.#sessionUseCounts.set(sessionId, count - 1);
34935
+ }
34936
+ this.#touchSession(sessionId);
34937
+ this.#notifyProcessCapacityChanged();
34938
+ }
34939
+ #beginNativeBrowserUse(sessionId) {
34940
+ this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
34941
+ this.#touchNativeBrowserSession(sessionId);
34942
+ }
34943
+ #endNativeBrowserUse(sessionId) {
34944
+ const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
34945
+ if (count <= 1) {
34946
+ this.#nativeBrowserUseCounts.delete(sessionId);
34947
+ } else {
34948
+ this.#nativeBrowserUseCounts.set(sessionId, count - 1);
34949
+ }
34950
+ this.#touchNativeBrowserSession(sessionId);
34951
+ this.#notifyProcessCapacityChanged();
34952
+ }
34953
+ #isNativeSessionOperationActive(sessionId) {
34954
+ const stored = this.#store.read(sessionId);
34955
+ return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
34956
+ }
34957
+ #leastRecentlyUsedEvictionCandidate() {
34958
+ for (const candidate of this.#retainedProcesses.values()) {
34959
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
34960
+ 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)) {
34961
+ continue;
34962
+ }
34963
+ return candidate;
34964
+ }
34965
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate && !this.#nativeBrowserPreparing.has(candidate.sessionId) && (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
34966
+ return candidate;
34967
+ }
34968
+ }
34969
+ return new MissingAcpProcessEvictionCandidate();
34970
+ }
34971
+ #ownedProcessCount() {
34972
+ return this.#retainedProcesses.size + this.#startingProcessCount + this.#transientProcessCount + this.#retiringProcessCount;
34973
+ }
34974
+ async #retireProcess(runtime, retained, close) {
34975
+ if (retained) {
34976
+ this.#retainedProcesses.delete(runtime);
34977
+ this.#retiringProcessCount += 1;
34978
+ }
34979
+ try {
34980
+ await close();
34981
+ } finally {
34982
+ if (retained) {
34983
+ this.#retiringProcessCount -= 1;
34984
+ this.#notifyProcessCapacityChanged();
34985
+ }
34986
+ }
34987
+ }
34988
+ async #retireSessionProcess(sessionId, runtime, close) {
34989
+ const retained = this.#sessions.get(sessionId) === runtime;
34990
+ if (retained) {
34991
+ this.#sessions.delete(sessionId);
34992
+ }
34993
+ await this.#retireProcess(runtime, retained, close);
34994
+ }
34995
+ async #retireNativeBrowserProcess(sessionId, runtime, close) {
34996
+ const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
34997
+ if (retained) {
34998
+ this.#nativeBrowserSessions.delete(sessionId);
34999
+ this.#nativeBrowserStore.remove(sessionId);
35000
+ }
35001
+ await this.#retireProcess(runtime, retained, close);
35002
+ }
35003
+ async #reserveProcessCapacity(signal) {
35004
+ const lease = await this.#processCapacityLock.acquire(signal);
35005
+ try {
35006
+ for (; ; ) {
35007
+ signal.throwIfAborted();
35008
+ if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
35009
+ this.#startingProcessCount += 1;
35010
+ return;
35011
+ }
35012
+ const candidate = this.#leastRecentlyUsedEvictionCandidate();
35013
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
35014
+ await this.#retireSessionProcess(
35015
+ candidate.sessionId,
35016
+ candidate.runtime,
35017
+ async () => await candidate.runtime.close()
35018
+ );
35019
+ continue;
35020
+ }
35021
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
35022
+ await this.#retireNativeBrowserProcess(
35023
+ candidate.sessionId,
35024
+ candidate.runtime,
35025
+ async () => await candidate.runtime.close()
35026
+ );
35027
+ continue;
35028
+ }
35029
+ const changed = this.#processCapacityChanged.promise;
35030
+ await waitForAcpProcessCapacity(changed, signal);
35031
+ }
35032
+ } finally {
35033
+ lease.release();
35034
+ }
35035
+ }
35036
+ async #startRetainedSessionProcess(options, start) {
35037
+ await this.#reserveProcessCapacity(options.signal);
35038
+ try {
35039
+ const runtime = await start();
35040
+ this.#startingProcessCount -= 1;
35041
+ this.#sessions.set(options.sessionId, runtime);
35042
+ this.#retainedProcesses.set(
35043
+ runtime,
35044
+ new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime)
35045
+ );
35046
+ this.#notifyProcessCapacityChanged();
35047
+ return runtime;
35048
+ } catch (error62) {
35049
+ this.#startingProcessCount -= 1;
35050
+ this.#notifyProcessCapacityChanged();
35051
+ throw error62;
35052
+ }
35053
+ }
35054
+ async #startRetainedNativeBrowserProcess(options, start) {
35055
+ await this.#reserveProcessCapacity(options.signal);
35056
+ try {
35057
+ const runtime = await start();
35058
+ this.#startingProcessCount -= 1;
35059
+ this.#nativeBrowserSessions.set(options.sessionId, runtime);
35060
+ this.#retainedProcesses.set(
35061
+ runtime,
35062
+ new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime)
35063
+ );
35064
+ this.#notifyProcessCapacityChanged();
35065
+ return runtime;
35066
+ } catch (error62) {
35067
+ this.#startingProcessCount -= 1;
35068
+ this.#notifyProcessCapacityChanged();
35069
+ throw error62;
35070
+ }
35071
+ }
35072
+ async #runWithTransientProcess(signal, start, operation, close) {
35073
+ await this.#reserveProcessCapacity(signal);
35074
+ let runtime;
35075
+ try {
35076
+ runtime = await start();
35077
+ } catch (error62) {
35078
+ this.#startingProcessCount -= 1;
35079
+ this.#notifyProcessCapacityChanged();
35080
+ throw error62;
35081
+ }
35082
+ this.#startingProcessCount -= 1;
35083
+ this.#transientProcessCount += 1;
35084
+ this.#notifyProcessCapacityChanged();
35085
+ try {
35086
+ return await operation(runtime);
35087
+ } finally {
35088
+ try {
35089
+ await close(runtime);
35090
+ } finally {
35091
+ this.#transientProcessCount -= 1;
35092
+ this.#notifyProcessCapacityChanged();
35093
+ }
35094
+ }
35095
+ }
34638
35096
  async #startNativeBrowserPreparation(options) {
34639
35097
  const operation = (async () => {
34640
35098
  try {
34641
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35099
+ return await this.#startRetainedNativeBrowserProcess(
34642
35100
  options,
34643
- () => this.#nativeBrowserObserver,
34644
- this.#nativeBrowserStore
35101
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35102
+ options,
35103
+ () => this.#nativeBrowserObserver,
35104
+ this.#nativeBrowserStore
35105
+ )
34645
35106
  );
34646
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
34647
- return runtime;
34648
35107
  } finally {
34649
35108
  this.#nativeBrowserPreparing.delete(options.sessionId);
35109
+ this.#notifyProcessCapacityChanged();
34650
35110
  }
34651
35111
  })();
34652
35112
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -34655,18 +35115,18 @@ var AcpSessionManager = class {
34655
35115
  async #replaceNativeBrowserPreparation(existing, options) {
34656
35116
  const operation = (async () => {
34657
35117
  try {
34658
- this.#nativeBrowserSessions.delete(options.sessionId);
34659
- await existing.close();
34660
- this.#nativeBrowserStore.remove(options.sessionId);
34661
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35118
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
35119
+ return await this.#startRetainedNativeBrowserProcess(
34662
35120
  options,
34663
- () => this.#nativeBrowserObserver,
34664
- this.#nativeBrowserStore
35121
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35122
+ options,
35123
+ () => this.#nativeBrowserObserver,
35124
+ this.#nativeBrowserStore
35125
+ )
34665
35126
  );
34666
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
34667
- return runtime;
34668
35127
  } finally {
34669
35128
  this.#nativeBrowserPreparing.delete(options.sessionId);
35129
+ this.#notifyProcessCapacityChanged();
34670
35130
  }
34671
35131
  })();
34672
35132
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -34675,11 +35135,13 @@ var AcpSessionManager = class {
34675
35135
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
34676
35136
  const operation = (async () => {
34677
35137
  try {
34678
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
34679
- this.#sessions.set(options.sessionId, runtime);
34680
- return runtime;
35138
+ return await this.#startRetainedSessionProcess(
35139
+ options,
35140
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35141
+ );
34681
35142
  } finally {
34682
35143
  this.#preparing.delete(options.sessionId);
35144
+ this.#notifyProcessCapacityChanged();
34683
35145
  }
34684
35146
  })();
34685
35147
  this.#preparing.set(options.sessionId, operation);
@@ -34688,17 +35150,19 @@ var AcpSessionManager = class {
34688
35150
  async #startSessionForkAtTurnPreparation(options, sourceNativeSessionId, forkPoint) {
34689
35151
  const operation = (async () => {
34690
35152
  try {
34691
- const runtime = await AcpProcessSession.startSessionForkAtTurn(
35153
+ return await this.#startRetainedSessionProcess(
34692
35154
  options,
34693
- sourceNativeSessionId,
34694
- forkPoint,
34695
- () => this.#observer,
34696
- this.#store
35155
+ async () => await AcpProcessSession.startSessionForkAtTurn(
35156
+ options,
35157
+ sourceNativeSessionId,
35158
+ forkPoint,
35159
+ () => this.#observer,
35160
+ this.#store
35161
+ )
34697
35162
  );
34698
- this.#sessions.set(options.sessionId, runtime);
34699
- return runtime;
34700
35163
  } finally {
34701
35164
  this.#preparing.delete(options.sessionId);
35165
+ this.#notifyProcessCapacityChanged();
34702
35166
  }
34703
35167
  })();
34704
35168
  this.#preparing.set(options.sessionId, operation);
@@ -34707,14 +35171,19 @@ var AcpSessionManager = class {
34707
35171
  async #replacePreparation(existing, options, metrics) {
34708
35172
  const operation = (async () => {
34709
35173
  try {
34710
- this.#sessions.delete(options.sessionId);
34711
- await metrics.measure("runtime-replacement-close", async () => await existing.close());
35174
+ await this.#retireSessionProcess(
35175
+ options.sessionId,
35176
+ existing,
35177
+ async () => await metrics.measure("runtime-replacement-close", async () => await existing.close())
35178
+ );
34712
35179
  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;
35180
+ return await this.#startRetainedSessionProcess(
35181
+ options,
35182
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35183
+ );
34716
35184
  } finally {
34717
35185
  this.#preparing.delete(options.sessionId);
35186
+ this.#notifyProcessCapacityChanged();
34718
35187
  }
34719
35188
  })();
34720
35189
  this.#preparing.set(options.sessionId, operation);
@@ -34724,10 +35193,12 @@ var AcpSessionManager = class {
34724
35193
  const desiredConfigOptions = existing.prepared().configOptions;
34725
35194
  const operation = (async () => {
34726
35195
  try {
34727
- this.#sessions.delete(options.sessionId);
34728
- await existing.close();
35196
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
34729
35197
  this.#store.remove(options.sessionId);
34730
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
35198
+ const runtime = await this.#startRetainedSessionProcess(
35199
+ options,
35200
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
35201
+ );
34731
35202
  try {
34732
35203
  for (const desired of desiredConfigOptions) {
34733
35204
  const current = runtime.prepared().configOptions.find((option) => option.id === desired.id);
@@ -34759,14 +35230,14 @@ var AcpSessionManager = class {
34759
35230
  }
34760
35231
  }
34761
35232
  } catch (error62) {
34762
- await runtime.close();
35233
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
34763
35234
  this.#store.remove(options.sessionId);
34764
35235
  throw error62;
34765
35236
  }
34766
- this.#sessions.set(options.sessionId, runtime);
34767
35237
  return runtime;
34768
35238
  } finally {
34769
35239
  this.#preparing.delete(options.sessionId);
35240
+ this.#notifyProcessCapacityChanged();
34770
35241
  }
34771
35242
  })();
34772
35243
  this.#preparing.set(options.sessionId, operation);
@@ -34788,6 +35259,7 @@ var AcpSessionManager = class {
34788
35259
  if (pending !== void 0) {
34789
35260
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
34790
35261
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35262
+ this.#touchExpectedSession(options.sessionId, runtime2);
34791
35263
  return runtime2.prepared();
34792
35264
  }
34793
35265
  return await this.prepareSession(options, metrics);
@@ -34795,6 +35267,7 @@ var AcpSessionManager = class {
34795
35267
  const existing = this.#sessions.get(options.sessionId);
34796
35268
  if (existing !== void 0) {
34797
35269
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35270
+ this.#touchExpectedSession(options.sessionId, existing);
34798
35271
  return existing.prepared();
34799
35272
  }
34800
35273
  if (!existing.canRebind()) {
@@ -34815,22 +35288,24 @@ var AcpSessionManager = class {
34815
35288
  * authoritative settings. Its identity and store are private to this
34816
35289
  * operation and never become a Mobius Session.
34817
35290
  */
34818
- inspectAgentSettings = async (options) => {
34819
- const runtime = await AcpProcessSession.start(
35291
+ inspectAgentSettings = async (options) => await this.#runWithTransientProcess(
35292
+ options.signal,
35293
+ async () => await AcpProcessSession.start(
34820
35294
  {
34821
35295
  ...options,
34822
35296
  sessionId: `agent-settings-${crypto.randomUUID()}`
34823
35297
  },
34824
35298
  () => this.#agentSettingsObserver,
34825
35299
  new MemoryAcpSessionStore()
34826
- );
34827
- try {
35300
+ ),
35301
+ (runtime) => {
34828
35302
  const prepared = runtime.prepared();
34829
- return new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions);
34830
- } finally {
34831
- await runtime.close();
34832
- }
34833
- };
35303
+ return Promise.resolve(
35304
+ new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions)
35305
+ );
35306
+ },
35307
+ async (runtime) => await runtime.close()
35308
+ );
34834
35309
  /**
34835
35310
  * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
34836
35311
  * Use inspectAgentSettings for Agent-scoped settings discovery.
@@ -34839,18 +35314,20 @@ var AcpSessionManager = class {
34839
35314
  if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
34840
35315
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
34841
35316
  }
34842
- const runtime = await this.#startPreparation(options, metrics);
35317
+ this.#beginSessionUse(options.sessionId);
34843
35318
  try {
34844
- return runtime.prepared();
34845
- } finally {
34846
- if (this.#sessions.get(options.sessionId) === runtime) {
34847
- this.#sessions.delete(options.sessionId);
34848
- }
35319
+ const runtime = await this.#startPreparation(options, metrics);
34849
35320
  try {
34850
- await runtime.close();
35321
+ return runtime.prepared();
34851
35322
  } finally {
34852
- this.#store.remove(options.sessionId);
35323
+ try {
35324
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
35325
+ } finally {
35326
+ this.#store.remove(options.sessionId);
35327
+ }
34853
35328
  }
35329
+ } finally {
35330
+ this.#endSessionUse(options.sessionId);
34854
35331
  }
34855
35332
  };
34856
35333
  prepareExecutionSession = async (options) => {
@@ -34871,6 +35348,7 @@ var AcpSessionManager = class {
34871
35348
  );
34872
35349
  }
34873
35350
  if (existing.usesEnvironment(options.agent.environment)) {
35351
+ this.#touchExpectedSession(options.sessionId, existing);
34874
35352
  return existing.prepared();
34875
35353
  }
34876
35354
  if (!existing.canRebind()) {
@@ -34887,6 +35365,7 @@ var AcpSessionManager = class {
34887
35365
  if (pending !== void 0) {
34888
35366
  const runtime2 = await pending;
34889
35367
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35368
+ this.#touchExpectedNativeBrowserSession(options.sessionId, runtime2);
34890
35369
  return runtime2.prepared();
34891
35370
  }
34892
35371
  return await this.prepareNativeSessionBrowser(options);
@@ -34894,6 +35373,7 @@ var AcpSessionManager = class {
34894
35373
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
34895
35374
  if (existing !== void 0) {
34896
35375
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35376
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
34897
35377
  return existing.prepared();
34898
35378
  }
34899
35379
  if (!existing.canRebind()) {
@@ -34910,8 +35390,13 @@ var AcpSessionManager = class {
34910
35390
  return runtime.prepared();
34911
35391
  };
34912
35392
  configureSession = async (options) => {
34913
- const runtime = await this.ensureSession(options);
34914
- return await runtime.configure(options);
35393
+ this.#beginSessionUse(options.sessionId);
35394
+ try {
35395
+ const runtime = await this.ensureSession(options);
35396
+ return await runtime.configure(options);
35397
+ } finally {
35398
+ this.#endSessionUse(options.sessionId);
35399
+ }
34915
35400
  };
34916
35401
  cancelPrompt = async (sessionId) => {
34917
35402
  const existing = this.#cancellationRequests.get(sessionId);
@@ -34927,6 +35412,8 @@ var AcpSessionManager = class {
34927
35412
  } finally {
34928
35413
  if (this.#sessions.get(sessionId) === runtime) {
34929
35414
  this.#sessions.delete(sessionId);
35415
+ this.#retainedProcesses.delete(runtime);
35416
+ this.#notifyProcessCapacityChanged();
34930
35417
  }
34931
35418
  }
34932
35419
  }
@@ -35016,10 +35503,7 @@ var AcpSessionManager = class {
35016
35503
  return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
35017
35504
  } catch (error62) {
35018
35505
  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();
35506
+ await this.#cancellationRequests.get(options.sessionId);
35023
35507
  return { stopReason: "cancelled" };
35024
35508
  }
35025
35509
  throw error62;
@@ -35027,8 +35511,11 @@ var AcpSessionManager = class {
35027
35511
  } catch (error62) {
35028
35512
  const failedRuntime = this.#sessions.get(options.sessionId);
35029
35513
  if (failedRuntime !== void 0) {
35030
- this.#sessions.delete(options.sessionId);
35031
- await failedRuntime.close();
35514
+ await this.#retireSessionProcess(
35515
+ options.sessionId,
35516
+ failedRuntime,
35517
+ async () => await failedRuntime.close()
35518
+ );
35032
35519
  }
35033
35520
  if (this.#cancellationRequests.has(options.sessionId)) {
35034
35521
  return { stopReason: "cancelled" };
@@ -35049,6 +35536,8 @@ var AcpSessionManager = class {
35049
35536
  this.#activeCommandIds.delete(options.sessionId);
35050
35537
  }
35051
35538
  this.#cancellationRequests.delete(options.sessionId);
35539
+ this.#touchSession(options.sessionId);
35540
+ this.#notifyProcessCapacityChanged();
35052
35541
  }
35053
35542
  }
35054
35543
  };
@@ -35067,11 +35556,16 @@ var AcpSessionManager = class {
35067
35556
  await runtime.respondElicitation(options);
35068
35557
  };
35069
35558
  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()));
35559
+ const sessions = [...this.#sessions.entries()];
35560
+ const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
35561
+ await Promise.all([
35562
+ ...sessions.map(
35563
+ async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
35564
+ ),
35565
+ ...nativeBrowserSessions.map(
35566
+ async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
35567
+ )
35568
+ ]);
35075
35569
  };
35076
35570
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
35077
35571
  ensureSession = async (options) => {
@@ -35084,6 +35578,7 @@ var AcpSessionManager = class {
35084
35578
  "session_identity_mismatch"
35085
35579
  );
35086
35580
  }
35581
+ this.#touchExpectedSession(options.sessionId, existing);
35087
35582
  return existing;
35088
35583
  }
35089
35584
  await this.prepareSession(options);
@@ -35103,6 +35598,7 @@ var AcpSessionManager = class {
35103
35598
  "session_identity_mismatch"
35104
35599
  );
35105
35600
  }
35601
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
35106
35602
  return existing;
35107
35603
  }
35108
35604
  await this.prepareNativeSessionBrowser(options);
@@ -35112,7 +35608,14 @@ var AcpSessionManager = class {
35112
35608
  }
35113
35609
  return started;
35114
35610
  }
35115
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
35611
+ listNativeSessions = async (options, cursor) => {
35612
+ this.#beginNativeBrowserUse(options.sessionId);
35613
+ try {
35614
+ return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
35615
+ } finally {
35616
+ this.#endNativeBrowserUse(options.sessionId);
35617
+ }
35618
+ };
35116
35619
  previewNativeSession = async (options, nativeSessionId) => {
35117
35620
  const key = `${options.agent.id}:${nativeSessionId}`;
35118
35621
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
@@ -35125,17 +35628,19 @@ var AcpSessionManager = class {
35125
35628
  }
35126
35629
  this.#nativeOperations.add(key);
35127
35630
  try {
35128
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35129
- options,
35130
- () => this.#nativeBrowserObserver,
35131
- new MemoryAcpSessionStore()
35631
+ return await this.#runWithTransientProcess(
35632
+ options.signal,
35633
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35634
+ options,
35635
+ () => this.#nativeBrowserObserver,
35636
+ new MemoryAcpSessionStore()
35637
+ ),
35638
+ async (runtime) => {
35639
+ runtime.selectNativeSession(nativeSessionId);
35640
+ return await runtime.loadHistory(options.signal);
35641
+ },
35642
+ async (runtime) => await runtime.closeProcess()
35132
35643
  );
35133
- try {
35134
- runtime.selectNativeSession(nativeSessionId);
35135
- return await runtime.loadHistory(options.signal);
35136
- } finally {
35137
- await runtime.closeProcess();
35138
- }
35139
35644
  } finally {
35140
35645
  this.#nativeOperations.delete(key);
35141
35646
  }
@@ -35155,36 +35660,46 @@ var AcpSessionManager = class {
35155
35660
  }
35156
35661
  const existing = linked[0];
35157
35662
  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);
35663
+ this.#beginSessionUse(existing.sessionId);
35170
35664
  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;
35665
+ const runtime = await this.ensureSession({
35666
+ ...options,
35667
+ sessionId: existing.sessionId
35668
+ });
35669
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
35670
+ throw new AcpExecutionError(
35671
+ "Wait for the native session's running operation to finish",
35672
+ {},
35673
+ "session_busy"
35674
+ );
35675
+ }
35676
+ this.#nativeOperations.add(key);
35677
+ try {
35678
+ const history = await runtime.loadHistory(options.signal);
35679
+ return {
35680
+ prepared: runtime.prepared(),
35681
+ sessionId: existing.sessionId,
35682
+ history
35683
+ };
35684
+ } catch (error62) {
35685
+ await this.#retireSessionProcess(
35686
+ existing.sessionId,
35687
+ runtime,
35688
+ async () => await runtime.closeProcess()
35689
+ );
35690
+ throw error62;
35691
+ } finally {
35692
+ this.#nativeOperations.delete(key);
35693
+ this.#notifyProcessCapacityChanged();
35694
+ }
35181
35695
  } finally {
35182
- this.#nativeOperations.delete(key);
35696
+ this.#endSessionUse(existing.sessionId);
35183
35697
  }
35184
35698
  }
35185
35699
  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
35700
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
35187
35701
  }
35702
+ this.#beginSessionUse(options.sessionId);
35188
35703
  this.#nativeOperations.add(key);
35189
35704
  try {
35190
35705
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -35198,23 +35713,23 @@ var AcpSessionManager = class {
35198
35713
  history
35199
35714
  };
35200
35715
  } catch (error62) {
35201
- this.#sessions.delete(options.sessionId);
35202
35716
  this.#store.remove(options.sessionId);
35203
- await runtime.closeProcess();
35717
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
35204
35718
  throw error62;
35205
35719
  } finally {
35206
35720
  this.#nativeOperations.delete(openedKey);
35721
+ this.#notifyProcessCapacityChanged();
35207
35722
  }
35208
35723
  } catch (error62) {
35209
35724
  this.#store.remove(options.sessionId);
35210
35725
  const runtime = this.#sessions.get(options.sessionId);
35211
- this.#sessions.delete(options.sessionId);
35212
35726
  if (runtime !== void 0) {
35213
- await runtime.closeProcess();
35727
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
35214
35728
  }
35215
35729
  throw error62;
35216
35730
  } finally {
35217
35731
  this.#nativeOperations.delete(key);
35732
+ this.#endSessionUse(options.sessionId);
35218
35733
  }
35219
35734
  };
35220
35735
  forkSessionAtTurn = async (options, sourceSessionId, forkPoint) => {
@@ -35252,6 +35767,7 @@ var AcpSessionManager = class {
35252
35767
  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
35768
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
35254
35769
  }
35770
+ this.#beginSessionUse(options.sessionId);
35255
35771
  this.#nativeOperations.add(key);
35256
35772
  try {
35257
35773
  const runtime = await this.#startSessionForkAtTurnPreparation(
@@ -35268,48 +35784,58 @@ var AcpSessionManager = class {
35268
35784
  sessionId: options.sessionId
35269
35785
  };
35270
35786
  } catch (error62) {
35271
- this.#sessions.delete(options.sessionId);
35272
35787
  this.#store.remove(options.sessionId);
35273
- await runtime.closeProcess();
35788
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
35274
35789
  throw error62;
35275
35790
  } finally {
35276
35791
  this.#nativeOperations.delete(openedKey);
35792
+ this.#notifyProcessCapacityChanged();
35277
35793
  }
35278
35794
  } finally {
35279
35795
  this.#nativeOperations.delete(key);
35796
+ this.#endSessionUse(options.sessionId);
35280
35797
  }
35281
35798
  };
35282
35799
  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);
35800
+ this.#beginNativeBrowserUse(options.sessionId);
35294
35801
  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();
35802
+ const runtime = await this.#ensureNativeSessionBrowser(options);
35803
+ const key = `${options.agent.id}:${nativeSessionId}`;
35804
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
35805
+ if (this.#nativeOperations.has(key) || linked.some(
35806
+ (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
35807
+ )) {
35808
+ throw new AcpExecutionError(
35809
+ "Wait for the native session's running operation to finish",
35810
+ {},
35811
+ "session_busy"
35812
+ );
35813
+ }
35814
+ this.#nativeOperations.add(key);
35815
+ try {
35816
+ for (const entry of linked) {
35817
+ const active = this.#sessions.get(entry.sessionId);
35818
+ if (active !== void 0 && active !== runtime) {
35819
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
35820
+ }
35300
35821
  }
35822
+ options.signal.throwIfAborted();
35823
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
35824
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
35825
+ if (runtime.nativeSessionId() === nativeSessionId) {
35826
+ await this.#retireNativeBrowserProcess(
35827
+ options.sessionId,
35828
+ runtime,
35829
+ async () => await runtime.close()
35830
+ );
35831
+ }
35832
+ return deleted;
35833
+ } finally {
35834
+ this.#nativeOperations.delete(key);
35835
+ this.#notifyProcessCapacityChanged();
35301
35836
  }
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
35837
  } finally {
35312
- this.#nativeOperations.delete(key);
35838
+ this.#endNativeBrowserUse(options.sessionId);
35313
35839
  }
35314
35840
  };
35315
35841
  };
@@ -36173,15 +36699,15 @@ async function putContent(url2, authorization, bytes, signal) {
36173
36699
  signal
36174
36700
  });
36175
36701
  }
36176
- async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
36702
+ async function uploadRuntimeArtifact(config2, sessionId, artifact, signal) {
36177
36703
  signal.throwIfAborted();
36178
36704
  let request;
36179
36705
  try {
36180
36706
  request = new MobiusArtifactUploadRequest(
36181
- image.name,
36182
- image.mimeType,
36183
- image.bytes.byteLength,
36184
- createHash2("sha256").update(image.bytes).digest("hex")
36707
+ artifact.name,
36708
+ artifact.mimeType,
36709
+ artifact.bytes.byteLength,
36710
+ createHash2("sha256").update(artifact.bytes).digest("hex")
36185
36711
  );
36186
36712
  } catch (cause) {
36187
36713
  translateSdkError(cause);
@@ -36220,7 +36746,7 @@ async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
36220
36746
  token
36221
36747
  ),
36222
36748
  authorization,
36223
- image.bytes,
36749
+ artifact.bytes,
36224
36750
  requestSignal
36225
36751
  );
36226
36752
  } catch (cause) {
@@ -36261,7 +36787,7 @@ var LocalAuthorizationError = class extends Error {
36261
36787
  // src/authorization/workspace-directory.ts
36262
36788
  import { readdir as readdir2, realpath as realpath7, stat as stat6 } from "node:fs/promises";
36263
36789
  import { homedir as homedir2 } from "node:os";
36264
- import { basename as basename2, dirname as dirname5, isAbsolute as isAbsolute9, join as join15, normalize as normalize3, relative as relative5 } from "node:path";
36790
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute9, join as join15, normalize as normalize3, relative as relative5 } from "node:path";
36265
36791
  var WorkspaceDirectoryListing = class {
36266
36792
  directoryId;
36267
36793
  directoryLabel;
@@ -36353,7 +36879,7 @@ var WorkspaceDirectoryService = class {
36353
36879
  return {
36354
36880
  path: path2,
36355
36881
  directoryId: encodePath(path2),
36356
- name: basename2(path2) || path2,
36882
+ name: basename3(path2) || path2,
36357
36883
  label: this.label(path2)
36358
36884
  };
36359
36885
  };
@@ -36411,21 +36937,8 @@ var WorkspaceDirectoryService = class {
36411
36937
 
36412
36938
  // src/bots/local-bot-grant-store.ts
36413
36939
  import { createHash as createHash3, randomUUID } from "node:crypto";
36414
- import { stat as stat7 } from "node:fs/promises";
36415
36940
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
36416
36941
  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
36942
  var LocalBotAuthorizationError = class extends Error {
36430
36943
  code;
36431
36944
  constructor(code, message, options = {}) {
@@ -36480,19 +36993,8 @@ function agentDigest(agent) {
36480
36993
  })
36481
36994
  );
36482
36995
  }
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
- );
36996
+ function workspaceDigest(path2) {
36997
+ return digest(path2);
36496
36998
  }
36497
36999
  function exactTargets(left, right) {
36498
37000
  if (left.length !== right.length) {
@@ -36526,6 +37028,16 @@ function rowInteger(row, key) {
36526
37028
  }
36527
37029
  return value;
36528
37030
  }
37031
+ function rowHasInteger(row, key) {
37032
+ const value = Reflect.get(row, key);
37033
+ if (value === null) {
37034
+ return false;
37035
+ }
37036
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
37037
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37038
+ }
37039
+ return true;
37040
+ }
36529
37041
  function parseTargets(encoded) {
36530
37042
  let value;
36531
37043
  try {
@@ -36549,17 +37061,6 @@ function parseSessionConfigurations(encoded) {
36549
37061
  }
36550
37062
  var LocalBotGrantStore = class {
36551
37063
  #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
37064
  constructor(path2) {
36564
37065
  this.#database = new DatabaseSync3(path2);
36565
37066
  this.#database.exec(`
@@ -36597,78 +37098,6 @@ var LocalBotGrantStore = class {
36597
37098
  ) STRICT;
36598
37099
  `);
36599
37100
  }
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
37101
  approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
36673
37102
  signal.throwIfAborted();
36674
37103
  const existing = this.#database.prepare(
@@ -36758,8 +37187,7 @@ var LocalBotGrantStore = class {
36758
37187
  WHERE grants.local_grant_id = ? AND grants.bot_id = ?
36759
37188
  AND behavior_revision_id = ? AND behavior_digest = ?
36760
37189
  AND binding_id = ? AND binding_revision = ?
36761
- AND agent_ref = ?
36762
- AND revoked_at IS NULL AND expires_at > ?`
37190
+ AND agent_ref = ?`
36763
37191
  ).get(
36764
37192
  command.localGrantId,
36765
37193
  command.botId,
@@ -36767,8 +37195,7 @@ var LocalBotGrantStore = class {
36767
37195
  command.behaviorDigest,
36768
37196
  command.bindingId,
36769
37197
  command.bindingRevision,
36770
- command.agentId,
36771
- now
37198
+ command.agentId
36772
37199
  );
36773
37200
  if (row === void 0) {
36774
37201
  throw new LocalBotAuthorizationError(
@@ -36781,14 +37208,14 @@ var LocalBotGrantStore = class {
36781
37208
  if (!exactTargets(approvedTargets, requestedTargets)) {
36782
37209
  throw new LocalBotAuthorizationError(
36783
37210
  "binding_not_approved",
36784
- "The Bot execution target policy changed after local approval"
37211
+ "The Bot execution target policy differs from its binding"
36785
37212
  );
36786
37213
  }
36787
37214
  const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
36788
37215
  if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
36789
37216
  throw new LocalBotAuthorizationError(
36790
37217
  "binding_not_approved",
36791
- "The Bot Agent configuration changed after local approval"
37218
+ "The Bot Agent configuration differs from its binding"
36792
37219
  );
36793
37220
  }
36794
37221
  const agent = catalog.find(command.agentId);
@@ -36797,17 +37224,29 @@ var LocalBotGrantStore = class {
36797
37224
  revalidateExecutable(agent.agentIdentity)
36798
37225
  ]);
36799
37226
  signal.throwIfAborted();
37227
+ if (!adapterUnchanged || !agentUnchanged) {
37228
+ throw new LocalBotAuthorizationError(
37229
+ "binding_incompatible",
37230
+ "The local Agent executable changed while the Runtime is active; restart the Runtime"
37231
+ );
37232
+ }
36800
37233
  const workspaceRef = rowString(row, "workspace_ref");
36801
37234
  const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
36802
37235
  const currentAgentDigest = agentDigest(agent);
36803
- const currentWorkspaceDigest = await workspaceDigest(workspacePath);
37236
+ const currentWorkspaceDigest = workspaceDigest(workspacePath);
36804
37237
  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"
37238
+ let expiresAt = rowInteger(row, "expires_at");
37239
+ let revocationEpoch = rowInteger(row, "revocation_epoch");
37240
+ if (currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path") || expiresAt <= now || rowHasInteger(row, "revoked_at")) {
37241
+ const refreshed = this.refreshTarget(
37242
+ rowString(row, "local_grant_id"),
37243
+ currentAgentDigest,
37244
+ currentWorkspaceDigest,
37245
+ workspacePath,
37246
+ now
36810
37247
  );
37248
+ expiresAt = refreshed.expiresAt;
37249
+ revocationEpoch = refreshed.revocationEpoch;
36811
37250
  }
36812
37251
  if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
36813
37252
  throw new LocalBotAuthorizationError(
@@ -36828,8 +37267,8 @@ var LocalBotGrantStore = class {
36828
37267
  workspacePath,
36829
37268
  currentWorkspaceDigest,
36830
37269
  approvedTargets,
36831
- rowInteger(row, "expires_at"),
36832
- rowInteger(row, "revocation_epoch")
37270
+ expiresAt,
37271
+ revocationEpoch
36833
37272
  );
36834
37273
  };
36835
37274
  recordUnavailable = (request, code, message, now) => {
@@ -36872,16 +37311,65 @@ var LocalBotGrantStore = class {
36872
37311
  return {
36873
37312
  agent,
36874
37313
  agentIdentityDigest: agentDigest(agent),
36875
- workspaceIdentityDigest: await workspaceDigest(workspacePath),
37314
+ workspaceIdentityDigest: workspaceDigest(workspacePath),
36876
37315
  workspacePath
36877
37316
  };
36878
37317
  };
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);
37318
+ refreshTarget = (localGrantId, agentIdentityDigest, workspaceIdentityDigest, workspacePath, now) => {
37319
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
37320
+ this.#database.exec("BEGIN IMMEDIATE");
37321
+ try {
37322
+ const current = this.#database.prepare("SELECT * FROM local_bot_grants WHERE local_grant_id = ?").get(localGrantId);
37323
+ if (current === void 0) {
37324
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is missing");
37325
+ }
37326
+ const currentExpiresAt = rowInteger(current, "expires_at");
37327
+ const currentRevocationEpoch = rowInteger(current, "revocation_epoch");
37328
+ if (agentIdentityDigest === rowString(current, "agent_identity_digest") && workspaceIdentityDigest === rowString(current, "workspace_identity_digest") && workspacePath === rowString(current, "workspace_path") && currentExpiresAt > now && !rowHasInteger(current, "revoked_at")) {
37329
+ this.#database.exec("COMMIT");
37330
+ return { expiresAt: currentExpiresAt, revocationEpoch: currentRevocationEpoch };
37331
+ }
37332
+ const result = this.#database.prepare(
37333
+ `UPDATE local_bot_grants
37334
+ SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
37335
+ expires_at = ?, revoked_at = NULL, revocation_epoch = revocation_epoch + 1
37336
+ WHERE local_grant_id = ? AND revocation_epoch = ?`
37337
+ ).run(
37338
+ agentIdentityDigest,
37339
+ workspaceIdentityDigest,
37340
+ workspacePath,
37341
+ expiresAt,
37342
+ localGrantId,
37343
+ currentRevocationEpoch
37344
+ );
37345
+ if (result.changes !== 1) {
37346
+ throw new LocalBotAuthorizationError(
37347
+ "local_grant_invalid",
37348
+ "The local Bot grant target could not be refreshed"
37349
+ );
37350
+ }
37351
+ this.#database.prepare(
37352
+ `INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
37353
+ VALUES (?, 'bot_binding_target_refreshed', ?, '', ?)`
37354
+ ).run(
37355
+ new Date(now).toISOString(),
37356
+ rowString(current, "binding_id"),
37357
+ JSON.stringify({
37358
+ agentIdentityChanged: agentIdentityDigest !== rowString(current, "agent_identity_digest"),
37359
+ bindingId: rowString(current, "binding_id"),
37360
+ botId: rowString(current, "bot_id"),
37361
+ expired: currentExpiresAt <= now,
37362
+ revived: rowHasInteger(current, "revoked_at"),
37363
+ workspaceIdentityChanged: workspaceIdentityDigest !== rowString(current, "workspace_identity_digest"),
37364
+ workspacePathChanged: workspacePath !== rowString(current, "workspace_path")
37365
+ })
37366
+ );
37367
+ this.#database.exec("COMMIT");
37368
+ return { expiresAt, revocationEpoch: currentRevocationEpoch + 1 };
37369
+ } catch (cause) {
37370
+ this.#database.exec("ROLLBACK");
37371
+ throw cause;
37372
+ }
36885
37373
  };
36886
37374
  };
36887
37375
 
@@ -37258,7 +37746,7 @@ var BotOutboundIpcServer = class {
37258
37746
 
37259
37747
  // src/native-sessions/service.ts
37260
37748
  import { randomUUID as randomUUID2 } from "node:crypto";
37261
- import { basename as basename3 } from "node:path";
37749
+ import { basename as basename4 } from "node:path";
37262
37750
 
37263
37751
  // src/native-sessions/codex-history.ts
37264
37752
  import { spawn as spawn4 } from "node:child_process";
@@ -37767,7 +38255,7 @@ var NativeSessionService = class {
37767
38255
  }
37768
38256
  resolvedPaths.add(path2);
37769
38257
  additionalDirectories.push(path2);
37770
- additionalEntries.push({ directoryId: directoryId2, name: basename3(path2) });
38258
+ additionalEntries.push({ directoryId: directoryId2, name: basename4(path2) });
37771
38259
  }
37772
38260
  const listing = await this.#directories.list(this.#config.bindingId, command.directoryId, signal);
37773
38261
  const opened = await this.#sessions.forkSessionAtTurn(
@@ -39089,9 +39577,9 @@ var DaemonAcpObserver = class {
39089
39577
  this.#config = config2;
39090
39578
  this.#record = record3;
39091
39579
  }
39092
- importLocalImage = async (sessionId, image, signal) => {
39580
+ importLocalArtifact = async (sessionId, artifact, signal) => {
39093
39581
  try {
39094
- return (await uploadRuntimeArtifact(this.#config, sessionId, image, signal)).artifactId;
39582
+ return (await uploadRuntimeArtifact(this.#config, sessionId, artifact, signal)).artifactId;
39095
39583
  } catch (cause) {
39096
39584
  signal.throwIfAborted();
39097
39585
  if (cause instanceof Error && cause.name === "AbortError") {
@@ -39662,7 +40150,7 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
39662
40150
  additionalDirectories.push(directory);
39663
40151
  additionalDirectoryEntries.push({
39664
40152
  directoryId: additionalDirectoryId,
39665
- name: basename4(directory)
40153
+ name: basename5(directory)
39666
40154
  });
39667
40155
  }
39668
40156
  return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
@@ -41352,9 +41840,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41352
41840
 
41353
41841
  // src/pairing/pair-local-machine.ts
41354
41842
  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";
41843
+ import { mkdir as mkdir4, open as open4, realpath as realpath8, rename as rename3, stat as stat7, writeFile as writeFile2 } from "node:fs/promises";
41356
41844
  import { hostname as hostname3 } from "node:os";
41357
- import { basename as basename5, join as join17, resolve as resolve4 } from "node:path";
41845
+ import { basename as basename6, join as join17, resolve as resolve4 } from "node:path";
41358
41846
  import { fetch as fetch7 } from "undici";
41359
41847
  var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
41360
41848
  var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
@@ -41422,7 +41910,7 @@ async function resolveDefaultWorkspace2(path2) {
41422
41910
  try {
41423
41911
  await mkdir4(requestedWorkspace, { recursive: true, mode: 448 });
41424
41912
  const defaultWorkspace = await realpath8(requestedWorkspace);
41425
- const metadata = await stat8(defaultWorkspace);
41913
+ const metadata = await stat7(defaultWorkspace);
41426
41914
  if (!metadata.isDirectory()) {
41427
41915
  throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
41428
41916
  }
@@ -41494,7 +41982,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
41494
41982
  installableAgents,
41495
41983
  machineName: hostname3(),
41496
41984
  pairingCode: options.code,
41497
- workspaceName: basename5(defaultWorkspace) || "Local workspace"
41985
+ workspaceName: basename6(defaultWorkspace) || "Local workspace"
41498
41986
  }),
41499
41987
  dispatcher: environmentProxyDispatcher,
41500
41988
  headers: { "content-type": "application/json" },
@@ -41659,7 +42147,7 @@ async function resumeMobiusRuntime(channelId, signal, environment = process.env)
41659
42147
 
41660
42148
  // src/runtime.ts
41661
42149
  var IDENTIFIER_PATTERN9 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
41662
- var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{43}$/;
42150
+ 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})$/;
41663
42151
  var MobiusRuntimeConfigurationError = class extends Error {
41664
42152
  code = "runtime_configuration_invalid";
41665
42153
  constructor(message, options = {}) {
@@ -41726,7 +42214,7 @@ async function resolveWorkspace(path2) {
41726
42214
  try {
41727
42215
  await mkdir5(requested, { recursive: true, mode: 448 });
41728
42216
  const resolved = await realpath9(requested);
41729
- const metadata = await stat9(resolved);
42217
+ const metadata = await stat8(resolved);
41730
42218
  if (!metadata.isDirectory()) {
41731
42219
  throw new MobiusRuntimeConfigurationError("The Runtime workspace is not a directory");
41732
42220
  }