@moxt-ai/mobius 0.0.39 → 0.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/acp/session-manager.d.ts.map +1 -1
  2. package/dist/acp/session-manager.js +485 -124
  3. package/dist/acp/session-manager.js.map +1 -1
  4. package/dist/agent-catalog/agent-discovery.d.ts +2 -2
  5. package/dist/agent-catalog/agent-discovery.d.ts.map +1 -1
  6. package/dist/agent-catalog/agent-discovery.js +3 -2
  7. package/dist/agent-catalog/agent-discovery.js.map +1 -1
  8. package/dist/agent-catalog/agents/grok-build-agent.d.ts +1 -1
  9. package/dist/agent-catalog/agents/grok-build-agent.d.ts.map +1 -1
  10. package/dist/agent-catalog/agents/grok-build-agent.js +18 -8
  11. package/dist/agent-catalog/agents/grok-build-agent.js.map +1 -1
  12. package/dist/agent-catalog/discover-agent.js +1 -1
  13. package/dist/agent-catalog/discover-agent.js.map +1 -1
  14. package/dist/agent-catalog/discover-local-agents.d.ts +0 -1
  15. package/dist/agent-catalog/discover-local-agents.d.ts.map +1 -1
  16. package/dist/agent-catalog/discover-local-agents.js +0 -1
  17. package/dist/agent-catalog/discover-local-agents.js.map +1 -1
  18. package/dist/agent-installation/fixed-installation-executor.js +2 -2
  19. package/dist/agent-installation/fixed-installation-executor.js.map +1 -1
  20. package/dist/bots/local-bot-grant-store.d.ts +1 -8
  21. package/dist/bots/local-bot-grant-store.d.ts.map +1 -1
  22. package/dist/bots/local-bot-grant-store.js +79 -121
  23. package/dist/bots/local-bot-grant-store.js.map +1 -1
  24. package/dist/cli.js +1639 -1325
  25. package/dist/cli.js.map +4 -4
  26. package/dist/index.js +800 -369
  27. package/dist/index.js.map +3 -3
  28. package/dist/run-daemon.d.ts.map +1 -1
  29. package/dist/run-daemon.js +89 -57
  30. package/dist/run-daemon.js.map +1 -1
  31. package/dist/runtime.js +794 -363
  32. package/dist/runtime.js.map +3 -3
  33. package/package.json +1 -1
  34. package/dist/bots/bot-approve-command.d.ts +0 -2
  35. package/dist/bots/bot-approve-command.d.ts.map +0 -1
  36. package/dist/bots/bot-approve-command.js +0 -78
  37. 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
@@ -774,10 +774,11 @@ var IntegrationProbeFailed = class extends UnavailableInstalledAgent {
774
774
  };
775
775
  var IncompatibleAdapter = class extends UnavailableInstalledAgent {
776
776
  code = "acp_incompatible";
777
- message = "ACP adapter is incompatible";
777
+ message;
778
778
  status = "incompatible_adapter";
779
- constructor(specification, agent) {
779
+ constructor(specification, agent, message) {
780
780
  super(specification, agent);
781
+ this.message = message;
781
782
  }
782
783
  };
783
784
  var AuthenticationRequiredAgent = class extends UnavailableInstalledAgent {
@@ -1513,6 +1514,9 @@ var GeminiCliAgentSpecification = class extends DirectAcpAgentDefinition {
1513
1514
  // src/agent-catalog/agents/grok-build-agent.ts
1514
1515
  import { realpath as realpath4 } from "node:fs/promises";
1515
1516
  import { isAbsolute as isAbsolute4, join as join7, relative as relative2, sep as sep2 } from "node:path";
1517
+ import {
1518
+ RequestError
1519
+ } from "@agentclientprotocol/sdk";
1516
1520
 
1517
1521
  // src/agent-installation/grok-managed-package.ts
1518
1522
  var GROK_BUILD_MANAGED_VERSION = "1.0.21";
@@ -1625,11 +1629,23 @@ var GrokBuildAgentSpecification = class extends DirectAcpAgentDefinition {
1625
1629
  };
1626
1630
  verifyAcp = async (connection, initialized, defaultWorkspace, signal) => {
1627
1631
  const capabilities = initialized.agentCapabilities ?? {};
1628
- const session = capabilities.sessionCapabilities;
1629
- if (capabilities.loadSession !== true || session?.close == null || session.list == null || session.resume == null || !(initialized.authMethods ?? []).some((method) => method.id === "xai.api_key" || method.id === "grok.com")) {
1630
- throw new AgentProbeError("acp_incompatible", "Grok Build reported an unsupported ACP capability set");
1632
+ if (capabilities.loadSession !== true) {
1633
+ throw new AgentProbeError("acp_incompatible", "Grok Build did not report ACP session loading");
1634
+ }
1635
+ const authMethods = initialized.authMethods ?? [];
1636
+ if (authMethods.length === 0) {
1637
+ throw new AgentProbeError("acp_incompatible", "Grok Build did not report an ACP authentication method");
1638
+ }
1639
+ try {
1640
+ await verifySessionCreation(connection, capabilities, defaultWorkspace, signal, this.label);
1641
+ } catch (cause) {
1642
+ const detail = cause instanceof RequestError ? `ACP error ${cause.code}: ${cause.message}` : cause instanceof Error ? `${cause.name}: ${cause.message}` : "unknown error";
1643
+ throw new AgentProbeError(
1644
+ "acp_incompatible",
1645
+ `Grok Build could not create an ACP session (${detail}; auth methods: ${authMethods.map(({ id }) => id).join(", ")})`,
1646
+ { cause }
1647
+ );
1631
1648
  }
1632
- await verifySessionCreation(connection, capabilities, defaultWorkspace, signal, this.label);
1633
1649
  };
1634
1650
  };
1635
1651
 
@@ -2172,7 +2188,7 @@ import {
2172
2188
  methods as methods4,
2173
2189
  ndJsonStream,
2174
2190
  PROTOCOL_VERSION,
2175
- RequestError
2191
+ RequestError as RequestError2
2176
2192
  } from "@agentclientprotocol/sdk";
2177
2193
 
2178
2194
  // src/acp/create-client.ts
@@ -2350,7 +2366,7 @@ async function probeAcpReadiness(specification, agent, environment, defaultWorks
2350
2366
  if (error62 instanceof AgentProbeError) {
2351
2367
  throw error62;
2352
2368
  }
2353
- if (error62 instanceof RequestError && error62.code === -32e3 && specification.authenticationCommand().length > 0) {
2369
+ if (error62 instanceof RequestError2 && error62.code === -32e3 && specification.authenticationCommand().length > 0) {
2354
2370
  throw new AgentProbeError("authentication_required", "Agent authentication is required", { cause: error62 });
2355
2371
  }
2356
2372
  throw new AgentProbeError("acp_incompatible", "ACP adapter initialization failed", { cause: error62 });
@@ -2587,7 +2603,7 @@ function integrationProbeFailure(specification, agent, error62) {
2587
2603
  if (error62.code === "authentication_required") {
2588
2604
  return new AuthenticationRequiredAgent(specification, agent);
2589
2605
  }
2590
- return error62.code === "acp_incompatible" ? new IncompatibleAdapter(specification, agent) : new IntegrationProbeFailed(specification, agent, error62.code, error62.message);
2606
+ return error62.code === "acp_incompatible" ? new IncompatibleAdapter(specification, agent, error62.message) : new IntegrationProbeFailed(specification, agent, error62.code, error62.message);
2591
2607
  }
2592
2608
  if (error62 instanceof ProcessExecutionError) {
2593
2609
  const code = error62.code === "process_timeout" ? "adapter_probe_timeout" : "adapter_probe_failed";
@@ -23571,6 +23587,7 @@ var BotSessionPromptCommand = class {
23571
23587
  commandId;
23572
23588
  conversationId;
23573
23589
  directoryId;
23590
+ disposition;
23574
23591
  executionCapabilityId;
23575
23592
  executionCapabilitySecret;
23576
23593
  executionDeadlineAt;
@@ -23583,13 +23600,15 @@ var BotSessionPromptCommand = class {
23583
23600
  resources;
23584
23601
  sessionConfigurations;
23585
23602
  sessionId;
23603
+ targetCommandId;
23586
23604
  turnId;
23587
- constructor(sessionId, commandId, agentId, bindingId, directoryId2, additionalDirectoryIds, images, resources, prompt, executionId, executionCapabilityId, executionCapabilitySecret, executionDeadlineAt, botId, conversationId, turnId, behaviorRevisionId, bindingRevision, localGrantId, behaviorInstructions, behaviorDigest, allowedDeliveryTargets, replyRoute, sessionConfigurations = []) {
23605
+ constructor(sessionId, commandId, agentId, bindingId, directoryId2, additionalDirectoryIds, images, resources, prompt, executionId, executionCapabilityId, executionCapabilitySecret, executionDeadlineAt, botId, conversationId, turnId, behaviorRevisionId, bindingRevision, localGrantId, behaviorInstructions, behaviorDigest, allowedDeliveryTargets, replyRoute, sessionConfigurations = [], disposition = SessionPromptDisposition.Reject, targetCommandId = "") {
23588
23606
  this.sessionId = sessionId;
23589
23607
  this.commandId = commandId;
23590
23608
  this.agentId = agentId;
23591
23609
  this.bindingId = bindingId;
23592
23610
  this.directoryId = directoryId2;
23611
+ this.disposition = disposition;
23593
23612
  this.additionalDirectoryIds = Object.freeze([...additionalDirectoryIds]);
23594
23613
  this.images = Object.freeze([...images]);
23595
23614
  this.resources = Object.freeze([...resources]);
@@ -23613,12 +23632,14 @@ var BotSessionPromptCommand = class {
23613
23632
  );
23614
23633
  this.replyRoute = replyRoute;
23615
23634
  this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
23635
+ this.targetCommandId = targetCommandId;
23616
23636
  }
23617
23637
  toJSON() {
23618
- const { sessionConfigurations, ...command } = this;
23638
+ const { disposition, sessionConfigurations, targetCommandId, ...command } = this;
23619
23639
  return {
23620
23640
  ...command,
23621
- ...sessionConfigurations.length === 0 ? {} : { sessionConfigurations }
23641
+ ...sessionConfigurations.length === 0 ? {} : { sessionConfigurations },
23642
+ ...disposition === SessionPromptDisposition.Reject ? {} : { disposition, targetCommandId }
23622
23643
  };
23623
23644
  }
23624
23645
  };
@@ -23912,11 +23933,26 @@ function decodeBotSessionPromptCommand(encoded) {
23912
23933
  "sessionId",
23913
23934
  "turnId"
23914
23935
  ],
23915
- ["sessionConfigurations"]
23936
+ ["disposition", "sessionConfigurations", "targetCommandId"]
23916
23937
  );
23917
23938
  if (value["kind"] !== BOT_SESSION_PROMPT_KIND) {
23918
23939
  throw new ProtocolMessageError("Invalid Bot Session prompt kind");
23919
23940
  }
23941
+ const rawDisposition = value["disposition"];
23942
+ let disposition;
23943
+ if (rawDisposition === void 0 || rawDisposition === SessionPromptDisposition.Reject) {
23944
+ disposition = SessionPromptDisposition.Reject;
23945
+ } else if (rawDisposition === SessionPromptDisposition.Queue) {
23946
+ disposition = SessionPromptDisposition.Queue;
23947
+ } else if (rawDisposition === SessionPromptDisposition.Steer) {
23948
+ disposition = SessionPromptDisposition.Steer;
23949
+ } else {
23950
+ throw new ProtocolMessageError("Invalid Bot Session prompt disposition");
23951
+ }
23952
+ const targetCommandId = value["targetCommandId"] === void 0 ? "" : readText2(value, "targetCommandId", 128, false);
23953
+ if (disposition === SessionPromptDisposition.Reject && targetCommandId.length > 0 || disposition !== SessionPromptDisposition.Reject && !IDENTIFIER_PATTERN3.test(targetCommandId)) {
23954
+ throw new ProtocolMessageError("Bot Session prompt disposition has an invalid target command");
23955
+ }
23920
23956
  return new BotSessionPromptCommand(
23921
23957
  readIdentifier2(value, "sessionId"),
23922
23958
  readIdentifier2(value, "commandId"),
@@ -23941,7 +23977,9 @@ function decodeBotSessionPromptCommand(encoded) {
23941
23977
  readDigest(value, "behaviorDigest"),
23942
23978
  readTargets(value, "allowedDeliveryTargets"),
23943
23979
  readReplyRoute(value["replyRoute"]),
23944
- readSessionConfigurations(value)
23980
+ readSessionConfigurations(value),
23981
+ disposition,
23982
+ targetCommandId
23945
23983
  );
23946
23984
  }
23947
23985
 
@@ -24269,7 +24307,7 @@ import {
24269
24307
  methods as methods6,
24270
24308
  ndJsonStream as ndJsonStream2,
24271
24309
  PROTOCOL_VERSION as PROTOCOL_VERSION2,
24272
- RequestError as RequestError2
24310
+ RequestError as RequestError3
24273
24311
  } from "@agentclientprotocol/sdk";
24274
24312
 
24275
24313
  // src/authorization/local-raster.ts
@@ -29023,7 +29061,7 @@ var titleBefore = {
29023
29061
  };
29024
29062
  function tokenizeDefinition(effects, ok2, nok) {
29025
29063
  const self = this;
29026
- let identifier3;
29064
+ let identifier2;
29027
29065
  return start;
29028
29066
  function start(code) {
29029
29067
  effects.enter("definition");
@@ -29042,7 +29080,7 @@ function tokenizeDefinition(effects, ok2, nok) {
29042
29080
  )(code);
29043
29081
  }
29044
29082
  function labelAfter(code) {
29045
- identifier3 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
29083
+ identifier2 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
29046
29084
  if (code === 58) {
29047
29085
  effects.enter("definitionMarker");
29048
29086
  effects.consume(code);
@@ -29076,7 +29114,7 @@ function tokenizeDefinition(effects, ok2, nok) {
29076
29114
  function afterWhitespace(code) {
29077
29115
  if (code === null || markdownLineEnding(code)) {
29078
29116
  effects.exit("definition");
29079
- self.parser.defined.push(identifier3);
29117
+ self.parser.defined.push(identifier2);
29080
29118
  return ok2(code);
29081
29119
  }
29082
29120
  return nok(code);
@@ -32911,6 +32949,7 @@ var SqliteAcpSessionStore = class {
32911
32949
 
32912
32950
  // src/acp/session-manager.ts
32913
32951
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
32952
+ var MAX_ACP_PROCESSES = 10;
32914
32953
  var MAX_PRE_SESSION_UPDATES = 100;
32915
32954
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
32916
32955
  var SESSION_CONTROL_COMMAND_ID = "session-control";
@@ -32969,6 +33008,91 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
32969
33008
  this.name = "RetryableAcpInitializationError";
32970
33009
  }
32971
33010
  };
33011
+ var AcpProcessCapacityLease = class {
33012
+ #releaseCapacity;
33013
+ #released = false;
33014
+ constructor(releaseCapacity) {
33015
+ this.#releaseCapacity = releaseCapacity;
33016
+ }
33017
+ release = () => {
33018
+ if (this.#released) {
33019
+ return;
33020
+ }
33021
+ this.#released = true;
33022
+ this.#releaseCapacity();
33023
+ };
33024
+ };
33025
+ var AcpProcessCapacityWaiter = class {
33026
+ completion = Promise.withResolvers();
33027
+ signal;
33028
+ constructor(signal) {
33029
+ this.signal = signal;
33030
+ }
33031
+ cancel = () => {
33032
+ try {
33033
+ this.signal.throwIfAborted();
33034
+ } catch (error62) {
33035
+ this.completion.reject(error62);
33036
+ }
33037
+ };
33038
+ };
33039
+ var AcpProcessCapacityLock = class {
33040
+ #locked = false;
33041
+ #waiters = [];
33042
+ acquire = async (signal) => {
33043
+ signal.throwIfAborted();
33044
+ if (!this.#locked) {
33045
+ this.#locked = true;
33046
+ return new AcpProcessCapacityLease(this.#release);
33047
+ }
33048
+ const waiter = new AcpProcessCapacityWaiter(signal);
33049
+ this.#waiters.push(waiter);
33050
+ signal.addEventListener("abort", waiter.cancel, { once: true });
33051
+ if (signal.aborted) {
33052
+ waiter.cancel();
33053
+ }
33054
+ try {
33055
+ return await waiter.completion.promise;
33056
+ } finally {
33057
+ signal.removeEventListener("abort", waiter.cancel);
33058
+ const index2 = this.#waiters.indexOf(waiter);
33059
+ if (index2 >= 0) {
33060
+ this.#waiters.splice(index2, 1);
33061
+ }
33062
+ }
33063
+ };
33064
+ #release = () => {
33065
+ while (this.#waiters.length > 0) {
33066
+ const waiter = this.#waiters.shift();
33067
+ if (waiter === void 0 || waiter.signal.aborted) {
33068
+ continue;
33069
+ }
33070
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
33071
+ return;
33072
+ }
33073
+ this.#locked = false;
33074
+ };
33075
+ };
33076
+ async function waitForAcpProcessCapacity(completion, signal) {
33077
+ signal.throwIfAborted();
33078
+ const cancelled = Promise.withResolvers();
33079
+ const cancel = () => {
33080
+ try {
33081
+ signal.throwIfAborted();
33082
+ } catch (error62) {
33083
+ cancelled.reject(error62);
33084
+ }
33085
+ };
33086
+ signal.addEventListener("abort", cancel, { once: true });
33087
+ if (signal.aborted) {
33088
+ cancel();
33089
+ }
33090
+ try {
33091
+ await Promise.race([completion, cancelled.promise]);
33092
+ } finally {
33093
+ signal.removeEventListener("abort", cancel);
33094
+ }
33095
+ }
32972
33096
  function readableWebStream(input2) {
32973
33097
  let streamOpen = true;
32974
33098
  return new ReadableStream({
@@ -34456,20 +34580,23 @@ var AcpProcessSession = class _AcpProcessSession {
34456
34580
  }
34457
34581
  };
34458
34582
  close = async () => {
34459
- await this.cancelPendingInteractions();
34460
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
34461
- try {
34462
- await this.#connection.agent.request(
34463
- methods6.agent.session.close,
34464
- { sessionId: this.#nativeSessionId },
34465
- {
34466
- cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
34467
- }
34468
- );
34469
- } catch {
34583
+ try {
34584
+ await this.cancelPendingInteractions();
34585
+ if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
34586
+ try {
34587
+ await this.#connection.agent.request(
34588
+ methods6.agent.session.close,
34589
+ { sessionId: this.#nativeSessionId },
34590
+ {
34591
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
34592
+ }
34593
+ );
34594
+ } catch {
34595
+ }
34470
34596
  }
34597
+ } finally {
34598
+ await this.closeProcess();
34471
34599
  }
34472
- await this.closeProcess();
34473
34600
  };
34474
34601
  closeProcess = async (capturedProcesses = []) => {
34475
34602
  try {
@@ -34502,7 +34629,7 @@ var AcpProcessSession = class _AcpProcessSession {
34502
34629
  ]);
34503
34630
  } catch (error62) {
34504
34631
  signal.throwIfAborted();
34505
- if (error62 instanceof RequestError2 && error62.code === -32e3) {
34632
+ if (error62 instanceof RequestError3 && error62.code === -32e3) {
34506
34633
  throw new AcpExecutionError(
34507
34634
  "Agent authentication is required",
34508
34635
  { cause: error62 },
@@ -34576,6 +34703,31 @@ var AcpProcessSession = class _AcpProcessSession {
34576
34703
  }
34577
34704
  };
34578
34705
  };
34706
+ var AcpProcessEvictionCandidate = class {
34707
+ };
34708
+ var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
34709
+ };
34710
+ var FoundAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
34711
+ runtime;
34712
+ constructor(runtime) {
34713
+ super();
34714
+ this.runtime = runtime;
34715
+ }
34716
+ };
34717
+ var FoundAcpSessionProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
34718
+ sessionId;
34719
+ constructor(sessionId, runtime) {
34720
+ super(runtime);
34721
+ this.sessionId = sessionId;
34722
+ }
34723
+ };
34724
+ var FoundAcpNativeBrowserProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
34725
+ sessionId;
34726
+ constructor(sessionId, runtime) {
34727
+ super(runtime);
34728
+ this.sessionId = sessionId;
34729
+ }
34730
+ };
34579
34731
  var AcpSessionManager = class {
34580
34732
  #activeCommandIds = /* @__PURE__ */ new Map();
34581
34733
  #agentSettingsObserver = new NullAcpSessionObserver();
@@ -34584,10 +34736,18 @@ var AcpSessionManager = class {
34584
34736
  #nativeBrowserPreparing = /* @__PURE__ */ new Map();
34585
34737
  #nativeBrowserSessions = /* @__PURE__ */ new Map();
34586
34738
  #nativeBrowserStore = new MemoryAcpSessionStore();
34739
+ #nativeBrowserUseCounts = /* @__PURE__ */ new Map();
34587
34740
  #activeSessionIds = /* @__PURE__ */ new Set();
34588
34741
  #cancellationRequests = /* @__PURE__ */ new Map();
34589
34742
  #preparing = /* @__PURE__ */ new Map();
34743
+ #processCapacityChanged = Promise.withResolvers();
34744
+ #processCapacityLock = new AcpProcessCapacityLock();
34745
+ #retainedProcesses = /* @__PURE__ */ new Map();
34746
+ #retiringProcessCount = 0;
34747
+ #sessionUseCounts = /* @__PURE__ */ new Map();
34590
34748
  #sessions = /* @__PURE__ */ new Map();
34749
+ #startingProcessCount = 0;
34750
+ #transientProcessCount = 0;
34591
34751
  #store;
34592
34752
  #observer;
34593
34753
  constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore()) {
@@ -34597,18 +34757,230 @@ var AcpSessionManager = class {
34597
34757
  setObserver = (observer) => {
34598
34758
  this.#observer = observer;
34599
34759
  };
34760
+ #notifyProcessCapacityChanged() {
34761
+ const changed = this.#processCapacityChanged;
34762
+ this.#processCapacityChanged = Promise.withResolvers();
34763
+ changed.resolve();
34764
+ }
34765
+ #touchSession(sessionId) {
34766
+ const runtime = this.#sessions.get(sessionId);
34767
+ if (runtime === void 0) {
34768
+ return;
34769
+ }
34770
+ this.#touchProcess(runtime);
34771
+ }
34772
+ #touchExpectedSession(sessionId, expected) {
34773
+ if (this.#sessions.get(sessionId) !== expected) {
34774
+ return;
34775
+ }
34776
+ this.#touchProcess(expected);
34777
+ }
34778
+ #touchNativeBrowserSession(sessionId) {
34779
+ const runtime = this.#nativeBrowserSessions.get(sessionId);
34780
+ if (runtime === void 0) {
34781
+ return;
34782
+ }
34783
+ this.#touchProcess(runtime);
34784
+ }
34785
+ #touchExpectedNativeBrowserSession(sessionId, expected) {
34786
+ if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
34787
+ return;
34788
+ }
34789
+ this.#touchProcess(expected);
34790
+ }
34791
+ #touchProcess(runtime) {
34792
+ const retained = this.#retainedProcesses.get(runtime);
34793
+ if (retained === void 0) {
34794
+ return;
34795
+ }
34796
+ this.#retainedProcesses.delete(runtime);
34797
+ this.#retainedProcesses.set(runtime, retained);
34798
+ }
34799
+ #beginSessionUse(sessionId) {
34800
+ this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
34801
+ this.#touchSession(sessionId);
34802
+ }
34803
+ #endSessionUse(sessionId) {
34804
+ const count = this.#sessionUseCounts.get(sessionId) ?? 0;
34805
+ if (count <= 1) {
34806
+ this.#sessionUseCounts.delete(sessionId);
34807
+ } else {
34808
+ this.#sessionUseCounts.set(sessionId, count - 1);
34809
+ }
34810
+ this.#touchSession(sessionId);
34811
+ this.#notifyProcessCapacityChanged();
34812
+ }
34813
+ #beginNativeBrowserUse(sessionId) {
34814
+ this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
34815
+ this.#touchNativeBrowserSession(sessionId);
34816
+ }
34817
+ #endNativeBrowserUse(sessionId) {
34818
+ const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
34819
+ if (count <= 1) {
34820
+ this.#nativeBrowserUseCounts.delete(sessionId);
34821
+ } else {
34822
+ this.#nativeBrowserUseCounts.set(sessionId, count - 1);
34823
+ }
34824
+ this.#touchNativeBrowserSession(sessionId);
34825
+ this.#notifyProcessCapacityChanged();
34826
+ }
34827
+ #isNativeSessionOperationActive(sessionId) {
34828
+ const stored = this.#store.read(sessionId);
34829
+ return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
34830
+ }
34831
+ #leastRecentlyUsedEvictionCandidate() {
34832
+ for (const candidate of this.#retainedProcesses.values()) {
34833
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
34834
+ if (this.#activeSessionIds.has(candidate.sessionId) || this.#cancellationRequests.has(candidate.sessionId) || this.#preparing.has(candidate.sessionId) || (this.#sessionUseCounts.get(candidate.sessionId) ?? 0) > 0 || this.#isNativeSessionOperationActive(candidate.sessionId)) {
34835
+ continue;
34836
+ }
34837
+ return candidate;
34838
+ }
34839
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate && !this.#nativeBrowserPreparing.has(candidate.sessionId) && (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
34840
+ return candidate;
34841
+ }
34842
+ }
34843
+ return new MissingAcpProcessEvictionCandidate();
34844
+ }
34845
+ #ownedProcessCount() {
34846
+ return this.#retainedProcesses.size + this.#startingProcessCount + this.#transientProcessCount + this.#retiringProcessCount;
34847
+ }
34848
+ async #retireProcess(runtime, retained, close) {
34849
+ if (retained) {
34850
+ this.#retainedProcesses.delete(runtime);
34851
+ this.#retiringProcessCount += 1;
34852
+ }
34853
+ try {
34854
+ await close();
34855
+ } finally {
34856
+ if (retained) {
34857
+ this.#retiringProcessCount -= 1;
34858
+ this.#notifyProcessCapacityChanged();
34859
+ }
34860
+ }
34861
+ }
34862
+ async #retireSessionProcess(sessionId, runtime, close) {
34863
+ const retained = this.#sessions.get(sessionId) === runtime;
34864
+ if (retained) {
34865
+ this.#sessions.delete(sessionId);
34866
+ }
34867
+ await this.#retireProcess(runtime, retained, close);
34868
+ }
34869
+ async #retireNativeBrowserProcess(sessionId, runtime, close) {
34870
+ const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
34871
+ if (retained) {
34872
+ this.#nativeBrowserSessions.delete(sessionId);
34873
+ this.#nativeBrowserStore.remove(sessionId);
34874
+ }
34875
+ await this.#retireProcess(runtime, retained, close);
34876
+ }
34877
+ async #reserveProcessCapacity(signal) {
34878
+ const lease = await this.#processCapacityLock.acquire(signal);
34879
+ try {
34880
+ for (; ; ) {
34881
+ signal.throwIfAborted();
34882
+ if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
34883
+ this.#startingProcessCount += 1;
34884
+ return;
34885
+ }
34886
+ const candidate = this.#leastRecentlyUsedEvictionCandidate();
34887
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
34888
+ await this.#retireSessionProcess(
34889
+ candidate.sessionId,
34890
+ candidate.runtime,
34891
+ async () => await candidate.runtime.close()
34892
+ );
34893
+ continue;
34894
+ }
34895
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
34896
+ await this.#retireNativeBrowserProcess(
34897
+ candidate.sessionId,
34898
+ candidate.runtime,
34899
+ async () => await candidate.runtime.close()
34900
+ );
34901
+ continue;
34902
+ }
34903
+ const changed = this.#processCapacityChanged.promise;
34904
+ await waitForAcpProcessCapacity(changed, signal);
34905
+ }
34906
+ } finally {
34907
+ lease.release();
34908
+ }
34909
+ }
34910
+ async #startRetainedSessionProcess(options, start) {
34911
+ await this.#reserveProcessCapacity(options.signal);
34912
+ try {
34913
+ const runtime = await start();
34914
+ this.#startingProcessCount -= 1;
34915
+ this.#sessions.set(options.sessionId, runtime);
34916
+ this.#retainedProcesses.set(
34917
+ runtime,
34918
+ new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime)
34919
+ );
34920
+ this.#notifyProcessCapacityChanged();
34921
+ return runtime;
34922
+ } catch (error62) {
34923
+ this.#startingProcessCount -= 1;
34924
+ this.#notifyProcessCapacityChanged();
34925
+ throw error62;
34926
+ }
34927
+ }
34928
+ async #startRetainedNativeBrowserProcess(options, start) {
34929
+ await this.#reserveProcessCapacity(options.signal);
34930
+ try {
34931
+ const runtime = await start();
34932
+ this.#startingProcessCount -= 1;
34933
+ this.#nativeBrowserSessions.set(options.sessionId, runtime);
34934
+ this.#retainedProcesses.set(
34935
+ runtime,
34936
+ new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime)
34937
+ );
34938
+ this.#notifyProcessCapacityChanged();
34939
+ return runtime;
34940
+ } catch (error62) {
34941
+ this.#startingProcessCount -= 1;
34942
+ this.#notifyProcessCapacityChanged();
34943
+ throw error62;
34944
+ }
34945
+ }
34946
+ async #runWithTransientProcess(signal, start, operation, close) {
34947
+ await this.#reserveProcessCapacity(signal);
34948
+ let runtime;
34949
+ try {
34950
+ runtime = await start();
34951
+ } catch (error62) {
34952
+ this.#startingProcessCount -= 1;
34953
+ this.#notifyProcessCapacityChanged();
34954
+ throw error62;
34955
+ }
34956
+ this.#startingProcessCount -= 1;
34957
+ this.#transientProcessCount += 1;
34958
+ this.#notifyProcessCapacityChanged();
34959
+ try {
34960
+ return await operation(runtime);
34961
+ } finally {
34962
+ try {
34963
+ await close(runtime);
34964
+ } finally {
34965
+ this.#transientProcessCount -= 1;
34966
+ this.#notifyProcessCapacityChanged();
34967
+ }
34968
+ }
34969
+ }
34600
34970
  async #startNativeBrowserPreparation(options) {
34601
34971
  const operation = (async () => {
34602
34972
  try {
34603
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
34973
+ return await this.#startRetainedNativeBrowserProcess(
34604
34974
  options,
34605
- () => this.#nativeBrowserObserver,
34606
- this.#nativeBrowserStore
34975
+ async () => await AcpProcessSession.startNativeSessionBrowser(
34976
+ options,
34977
+ () => this.#nativeBrowserObserver,
34978
+ this.#nativeBrowserStore
34979
+ )
34607
34980
  );
34608
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
34609
- return runtime;
34610
34981
  } finally {
34611
34982
  this.#nativeBrowserPreparing.delete(options.sessionId);
34983
+ this.#notifyProcessCapacityChanged();
34612
34984
  }
34613
34985
  })();
34614
34986
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -34617,18 +34989,18 @@ var AcpSessionManager = class {
34617
34989
  async #replaceNativeBrowserPreparation(existing, options) {
34618
34990
  const operation = (async () => {
34619
34991
  try {
34620
- this.#nativeBrowserSessions.delete(options.sessionId);
34621
- await existing.close();
34622
- this.#nativeBrowserStore.remove(options.sessionId);
34623
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
34992
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
34993
+ return await this.#startRetainedNativeBrowserProcess(
34624
34994
  options,
34625
- () => this.#nativeBrowserObserver,
34626
- this.#nativeBrowserStore
34995
+ async () => await AcpProcessSession.startNativeSessionBrowser(
34996
+ options,
34997
+ () => this.#nativeBrowserObserver,
34998
+ this.#nativeBrowserStore
34999
+ )
34627
35000
  );
34628
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
34629
- return runtime;
34630
35001
  } finally {
34631
35002
  this.#nativeBrowserPreparing.delete(options.sessionId);
35003
+ this.#notifyProcessCapacityChanged();
34632
35004
  }
34633
35005
  })();
34634
35006
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -34637,11 +35009,13 @@ var AcpSessionManager = class {
34637
35009
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
34638
35010
  const operation = (async () => {
34639
35011
  try {
34640
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
34641
- this.#sessions.set(options.sessionId, runtime);
34642
- return runtime;
35012
+ return await this.#startRetainedSessionProcess(
35013
+ options,
35014
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35015
+ );
34643
35016
  } finally {
34644
35017
  this.#preparing.delete(options.sessionId);
35018
+ this.#notifyProcessCapacityChanged();
34645
35019
  }
34646
35020
  })();
34647
35021
  this.#preparing.set(options.sessionId, operation);
@@ -34650,17 +35024,19 @@ var AcpSessionManager = class {
34650
35024
  async #startSessionForkAtTurnPreparation(options, sourceNativeSessionId, forkPoint) {
34651
35025
  const operation = (async () => {
34652
35026
  try {
34653
- const runtime = await AcpProcessSession.startSessionForkAtTurn(
35027
+ return await this.#startRetainedSessionProcess(
34654
35028
  options,
34655
- sourceNativeSessionId,
34656
- forkPoint,
34657
- () => this.#observer,
34658
- this.#store
35029
+ async () => await AcpProcessSession.startSessionForkAtTurn(
35030
+ options,
35031
+ sourceNativeSessionId,
35032
+ forkPoint,
35033
+ () => this.#observer,
35034
+ this.#store
35035
+ )
34659
35036
  );
34660
- this.#sessions.set(options.sessionId, runtime);
34661
- return runtime;
34662
35037
  } finally {
34663
35038
  this.#preparing.delete(options.sessionId);
35039
+ this.#notifyProcessCapacityChanged();
34664
35040
  }
34665
35041
  })();
34666
35042
  this.#preparing.set(options.sessionId, operation);
@@ -34669,14 +35045,19 @@ var AcpSessionManager = class {
34669
35045
  async #replacePreparation(existing, options, metrics) {
34670
35046
  const operation = (async () => {
34671
35047
  try {
34672
- this.#sessions.delete(options.sessionId);
34673
- await metrics.measure("runtime-replacement-close", async () => await existing.close());
35048
+ await this.#retireSessionProcess(
35049
+ options.sessionId,
35050
+ existing,
35051
+ async () => await metrics.measure("runtime-replacement-close", async () => await existing.close())
35052
+ );
34674
35053
  this.#store.remove(options.sessionId);
34675
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
34676
- this.#sessions.set(options.sessionId, runtime);
34677
- return runtime;
35054
+ return await this.#startRetainedSessionProcess(
35055
+ options,
35056
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35057
+ );
34678
35058
  } finally {
34679
35059
  this.#preparing.delete(options.sessionId);
35060
+ this.#notifyProcessCapacityChanged();
34680
35061
  }
34681
35062
  })();
34682
35063
  this.#preparing.set(options.sessionId, operation);
@@ -34686,10 +35067,12 @@ var AcpSessionManager = class {
34686
35067
  const desiredConfigOptions = existing.prepared().configOptions;
34687
35068
  const operation = (async () => {
34688
35069
  try {
34689
- this.#sessions.delete(options.sessionId);
34690
- await existing.close();
35070
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
34691
35071
  this.#store.remove(options.sessionId);
34692
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
35072
+ const runtime = await this.#startRetainedSessionProcess(
35073
+ options,
35074
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
35075
+ );
34693
35076
  try {
34694
35077
  for (const desired of desiredConfigOptions) {
34695
35078
  const current = runtime.prepared().configOptions.find((option) => option.id === desired.id);
@@ -34721,14 +35104,14 @@ var AcpSessionManager = class {
34721
35104
  }
34722
35105
  }
34723
35106
  } catch (error62) {
34724
- await runtime.close();
35107
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
34725
35108
  this.#store.remove(options.sessionId);
34726
35109
  throw error62;
34727
35110
  }
34728
- this.#sessions.set(options.sessionId, runtime);
34729
35111
  return runtime;
34730
35112
  } finally {
34731
35113
  this.#preparing.delete(options.sessionId);
35114
+ this.#notifyProcessCapacityChanged();
34732
35115
  }
34733
35116
  })();
34734
35117
  this.#preparing.set(options.sessionId, operation);
@@ -34750,6 +35133,7 @@ var AcpSessionManager = class {
34750
35133
  if (pending !== void 0) {
34751
35134
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
34752
35135
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35136
+ this.#touchExpectedSession(options.sessionId, runtime2);
34753
35137
  return runtime2.prepared();
34754
35138
  }
34755
35139
  return await this.prepareSession(options, metrics);
@@ -34757,6 +35141,7 @@ var AcpSessionManager = class {
34757
35141
  const existing = this.#sessions.get(options.sessionId);
34758
35142
  if (existing !== void 0) {
34759
35143
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35144
+ this.#touchExpectedSession(options.sessionId, existing);
34760
35145
  return existing.prepared();
34761
35146
  }
34762
35147
  if (!existing.canRebind()) {
@@ -34777,22 +35162,24 @@ var AcpSessionManager = class {
34777
35162
  * authoritative settings. Its identity and store are private to this
34778
35163
  * operation and never become a Mobius Session.
34779
35164
  */
34780
- inspectAgentSettings = async (options) => {
34781
- const runtime = await AcpProcessSession.start(
35165
+ inspectAgentSettings = async (options) => await this.#runWithTransientProcess(
35166
+ options.signal,
35167
+ async () => await AcpProcessSession.start(
34782
35168
  {
34783
35169
  ...options,
34784
35170
  sessionId: `agent-settings-${crypto.randomUUID()}`
34785
35171
  },
34786
35172
  () => this.#agentSettingsObserver,
34787
35173
  new MemoryAcpSessionStore()
34788
- );
34789
- try {
35174
+ ),
35175
+ (runtime) => {
34790
35176
  const prepared = runtime.prepared();
34791
- return new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions);
34792
- } finally {
34793
- await runtime.close();
34794
- }
34795
- };
35177
+ return Promise.resolve(
35178
+ new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions)
35179
+ );
35180
+ },
35181
+ async (runtime) => await runtime.close()
35182
+ );
34796
35183
  /**
34797
35184
  * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
34798
35185
  * Use inspectAgentSettings for Agent-scoped settings discovery.
@@ -34801,18 +35188,20 @@ var AcpSessionManager = class {
34801
35188
  if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
34802
35189
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
34803
35190
  }
34804
- const runtime = await this.#startPreparation(options, metrics);
35191
+ this.#beginSessionUse(options.sessionId);
34805
35192
  try {
34806
- return runtime.prepared();
34807
- } finally {
34808
- if (this.#sessions.get(options.sessionId) === runtime) {
34809
- this.#sessions.delete(options.sessionId);
34810
- }
35193
+ const runtime = await this.#startPreparation(options, metrics);
34811
35194
  try {
34812
- await runtime.close();
35195
+ return runtime.prepared();
34813
35196
  } finally {
34814
- this.#store.remove(options.sessionId);
35197
+ try {
35198
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
35199
+ } finally {
35200
+ this.#store.remove(options.sessionId);
35201
+ }
34815
35202
  }
35203
+ } finally {
35204
+ this.#endSessionUse(options.sessionId);
34816
35205
  }
34817
35206
  };
34818
35207
  prepareExecutionSession = async (options) => {
@@ -34833,6 +35222,7 @@ var AcpSessionManager = class {
34833
35222
  );
34834
35223
  }
34835
35224
  if (existing.usesEnvironment(options.agent.environment)) {
35225
+ this.#touchExpectedSession(options.sessionId, existing);
34836
35226
  return existing.prepared();
34837
35227
  }
34838
35228
  if (!existing.canRebind()) {
@@ -34849,6 +35239,7 @@ var AcpSessionManager = class {
34849
35239
  if (pending !== void 0) {
34850
35240
  const runtime2 = await pending;
34851
35241
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35242
+ this.#touchExpectedNativeBrowserSession(options.sessionId, runtime2);
34852
35243
  return runtime2.prepared();
34853
35244
  }
34854
35245
  return await this.prepareNativeSessionBrowser(options);
@@ -34856,6 +35247,7 @@ var AcpSessionManager = class {
34856
35247
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
34857
35248
  if (existing !== void 0) {
34858
35249
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35250
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
34859
35251
  return existing.prepared();
34860
35252
  }
34861
35253
  if (!existing.canRebind()) {
@@ -34872,8 +35264,13 @@ var AcpSessionManager = class {
34872
35264
  return runtime.prepared();
34873
35265
  };
34874
35266
  configureSession = async (options) => {
34875
- const runtime = await this.ensureSession(options);
34876
- return await runtime.configure(options);
35267
+ this.#beginSessionUse(options.sessionId);
35268
+ try {
35269
+ const runtime = await this.ensureSession(options);
35270
+ return await runtime.configure(options);
35271
+ } finally {
35272
+ this.#endSessionUse(options.sessionId);
35273
+ }
34877
35274
  };
34878
35275
  cancelPrompt = async (sessionId) => {
34879
35276
  const existing = this.#cancellationRequests.get(sessionId);
@@ -34889,6 +35286,8 @@ var AcpSessionManager = class {
34889
35286
  } finally {
34890
35287
  if (this.#sessions.get(sessionId) === runtime) {
34891
35288
  this.#sessions.delete(sessionId);
35289
+ this.#retainedProcesses.delete(runtime);
35290
+ this.#notifyProcessCapacityChanged();
34892
35291
  }
34893
35292
  }
34894
35293
  }
@@ -34978,10 +35377,7 @@ var AcpSessionManager = class {
34978
35377
  return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
34979
35378
  } catch (error62) {
34980
35379
  if (this.#cancellationRequests.has(options.sessionId)) {
34981
- if (this.#sessions.get(options.sessionId) === runtime) {
34982
- this.#sessions.delete(options.sessionId);
34983
- }
34984
- await runtime.closeProcess();
35380
+ await this.#cancellationRequests.get(options.sessionId);
34985
35381
  return { stopReason: "cancelled" };
34986
35382
  }
34987
35383
  throw error62;
@@ -34989,8 +35385,11 @@ var AcpSessionManager = class {
34989
35385
  } catch (error62) {
34990
35386
  const failedRuntime = this.#sessions.get(options.sessionId);
34991
35387
  if (failedRuntime !== void 0) {
34992
- this.#sessions.delete(options.sessionId);
34993
- await failedRuntime.close();
35388
+ await this.#retireSessionProcess(
35389
+ options.sessionId,
35390
+ failedRuntime,
35391
+ async () => await failedRuntime.close()
35392
+ );
34994
35393
  }
34995
35394
  if (this.#cancellationRequests.has(options.sessionId)) {
34996
35395
  return { stopReason: "cancelled" };
@@ -35011,6 +35410,8 @@ var AcpSessionManager = class {
35011
35410
  this.#activeCommandIds.delete(options.sessionId);
35012
35411
  }
35013
35412
  this.#cancellationRequests.delete(options.sessionId);
35413
+ this.#touchSession(options.sessionId);
35414
+ this.#notifyProcessCapacityChanged();
35014
35415
  }
35015
35416
  }
35016
35417
  };
@@ -35029,11 +35430,16 @@ var AcpSessionManager = class {
35029
35430
  await runtime.respondElicitation(options);
35030
35431
  };
35031
35432
  close = async () => {
35032
- const sessions = [...this.#sessions.values()];
35033
- const nativeBrowserSessions = [...this.#nativeBrowserSessions.values()];
35034
- this.#sessions.clear();
35035
- this.#nativeBrowserSessions.clear();
35036
- await Promise.all([...sessions, ...nativeBrowserSessions].map(async (session) => await session.close()));
35433
+ const sessions = [...this.#sessions.entries()];
35434
+ const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
35435
+ await Promise.all([
35436
+ ...sessions.map(
35437
+ async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
35438
+ ),
35439
+ ...nativeBrowserSessions.map(
35440
+ async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
35441
+ )
35442
+ ]);
35037
35443
  };
35038
35444
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
35039
35445
  ensureSession = async (options) => {
@@ -35046,6 +35452,7 @@ var AcpSessionManager = class {
35046
35452
  "session_identity_mismatch"
35047
35453
  );
35048
35454
  }
35455
+ this.#touchExpectedSession(options.sessionId, existing);
35049
35456
  return existing;
35050
35457
  }
35051
35458
  await this.prepareSession(options);
@@ -35065,6 +35472,7 @@ var AcpSessionManager = class {
35065
35472
  "session_identity_mismatch"
35066
35473
  );
35067
35474
  }
35475
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
35068
35476
  return existing;
35069
35477
  }
35070
35478
  await this.prepareNativeSessionBrowser(options);
@@ -35074,7 +35482,14 @@ var AcpSessionManager = class {
35074
35482
  }
35075
35483
  return started;
35076
35484
  }
35077
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
35485
+ listNativeSessions = async (options, cursor) => {
35486
+ this.#beginNativeBrowserUse(options.sessionId);
35487
+ try {
35488
+ return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
35489
+ } finally {
35490
+ this.#endNativeBrowserUse(options.sessionId);
35491
+ }
35492
+ };
35078
35493
  previewNativeSession = async (options, nativeSessionId) => {
35079
35494
  const key = `${options.agent.id}:${nativeSessionId}`;
35080
35495
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
@@ -35087,17 +35502,19 @@ var AcpSessionManager = class {
35087
35502
  }
35088
35503
  this.#nativeOperations.add(key);
35089
35504
  try {
35090
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35091
- options,
35092
- () => this.#nativeBrowserObserver,
35093
- new MemoryAcpSessionStore()
35505
+ return await this.#runWithTransientProcess(
35506
+ options.signal,
35507
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35508
+ options,
35509
+ () => this.#nativeBrowserObserver,
35510
+ new MemoryAcpSessionStore()
35511
+ ),
35512
+ async (runtime) => {
35513
+ runtime.selectNativeSession(nativeSessionId);
35514
+ return await runtime.loadHistory(options.signal);
35515
+ },
35516
+ async (runtime) => await runtime.closeProcess()
35094
35517
  );
35095
- try {
35096
- runtime.selectNativeSession(nativeSessionId);
35097
- return await runtime.loadHistory(options.signal);
35098
- } finally {
35099
- await runtime.closeProcess();
35100
- }
35101
35518
  } finally {
35102
35519
  this.#nativeOperations.delete(key);
35103
35520
  }
@@ -35117,36 +35534,46 @@ var AcpSessionManager = class {
35117
35534
  }
35118
35535
  const existing = linked[0];
35119
35536
  if (origin.kind === "import" && existing !== void 0) {
35120
- const runtime = await this.ensureSession({
35121
- ...options,
35122
- sessionId: existing.sessionId
35123
- });
35124
- if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
35125
- throw new AcpExecutionError(
35126
- "Wait for the native session's running operation to finish",
35127
- {},
35128
- "session_busy"
35129
- );
35130
- }
35131
- this.#nativeOperations.add(key);
35537
+ this.#beginSessionUse(existing.sessionId);
35132
35538
  try {
35133
- const history = await runtime.loadHistory(options.signal);
35134
- return {
35135
- prepared: runtime.prepared(),
35136
- sessionId: existing.sessionId,
35137
- history
35138
- };
35139
- } catch (error62) {
35140
- this.#sessions.delete(existing.sessionId);
35141
- await runtime.closeProcess();
35142
- throw error62;
35539
+ const runtime = await this.ensureSession({
35540
+ ...options,
35541
+ sessionId: existing.sessionId
35542
+ });
35543
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
35544
+ throw new AcpExecutionError(
35545
+ "Wait for the native session's running operation to finish",
35546
+ {},
35547
+ "session_busy"
35548
+ );
35549
+ }
35550
+ this.#nativeOperations.add(key);
35551
+ try {
35552
+ const history = await runtime.loadHistory(options.signal);
35553
+ return {
35554
+ prepared: runtime.prepared(),
35555
+ sessionId: existing.sessionId,
35556
+ history
35557
+ };
35558
+ } catch (error62) {
35559
+ await this.#retireSessionProcess(
35560
+ existing.sessionId,
35561
+ runtime,
35562
+ async () => await runtime.closeProcess()
35563
+ );
35564
+ throw error62;
35565
+ } finally {
35566
+ this.#nativeOperations.delete(key);
35567
+ this.#notifyProcessCapacityChanged();
35568
+ }
35143
35569
  } finally {
35144
- this.#nativeOperations.delete(key);
35570
+ this.#endSessionUse(existing.sessionId);
35145
35571
  }
35146
35572
  }
35147
35573
  if (this.#sessions.has(options.sessionId) || this.#preparing.has(options.sessionId) || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
35148
35574
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
35149
35575
  }
35576
+ this.#beginSessionUse(options.sessionId);
35150
35577
  this.#nativeOperations.add(key);
35151
35578
  try {
35152
35579
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -35160,23 +35587,23 @@ var AcpSessionManager = class {
35160
35587
  history
35161
35588
  };
35162
35589
  } catch (error62) {
35163
- this.#sessions.delete(options.sessionId);
35164
35590
  this.#store.remove(options.sessionId);
35165
- await runtime.closeProcess();
35591
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
35166
35592
  throw error62;
35167
35593
  } finally {
35168
35594
  this.#nativeOperations.delete(openedKey);
35595
+ this.#notifyProcessCapacityChanged();
35169
35596
  }
35170
35597
  } catch (error62) {
35171
35598
  this.#store.remove(options.sessionId);
35172
35599
  const runtime = this.#sessions.get(options.sessionId);
35173
- this.#sessions.delete(options.sessionId);
35174
35600
  if (runtime !== void 0) {
35175
- await runtime.closeProcess();
35601
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
35176
35602
  }
35177
35603
  throw error62;
35178
35604
  } finally {
35179
35605
  this.#nativeOperations.delete(key);
35606
+ this.#endSessionUse(options.sessionId);
35180
35607
  }
35181
35608
  };
35182
35609
  forkSessionAtTurn = async (options, sourceSessionId, forkPoint) => {
@@ -35214,6 +35641,7 @@ var AcpSessionManager = class {
35214
35641
  if (this.#sessions.has(options.sessionId) || this.#preparing.has(options.sessionId) || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
35215
35642
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
35216
35643
  }
35644
+ this.#beginSessionUse(options.sessionId);
35217
35645
  this.#nativeOperations.add(key);
35218
35646
  try {
35219
35647
  const runtime = await this.#startSessionForkAtTurnPreparation(
@@ -35230,48 +35658,58 @@ var AcpSessionManager = class {
35230
35658
  sessionId: options.sessionId
35231
35659
  };
35232
35660
  } catch (error62) {
35233
- this.#sessions.delete(options.sessionId);
35234
35661
  this.#store.remove(options.sessionId);
35235
- await runtime.closeProcess();
35662
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
35236
35663
  throw error62;
35237
35664
  } finally {
35238
35665
  this.#nativeOperations.delete(openedKey);
35666
+ this.#notifyProcessCapacityChanged();
35239
35667
  }
35240
35668
  } finally {
35241
35669
  this.#nativeOperations.delete(key);
35670
+ this.#endSessionUse(options.sessionId);
35242
35671
  }
35243
35672
  };
35244
35673
  deleteNativeSession = async (options, nativeSessionId) => {
35245
- const runtime = await this.#ensureNativeSessionBrowser(options);
35246
- const key = `${options.agent.id}:${nativeSessionId}`;
35247
- const linked = this.#store.findNative(options.agent.id, nativeSessionId);
35248
- if (this.#nativeOperations.has(key) || linked.some((entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
35249
- throw new AcpExecutionError(
35250
- "Wait for the native session's running operation to finish",
35251
- {},
35252
- "session_busy"
35253
- );
35254
- }
35255
- this.#nativeOperations.add(key);
35674
+ this.#beginNativeBrowserUse(options.sessionId);
35256
35675
  try {
35257
- for (const entry of linked) {
35258
- const active = this.#sessions.get(entry.sessionId);
35259
- if (active !== void 0 && active !== runtime) {
35260
- this.#sessions.delete(entry.sessionId);
35261
- await active.close();
35676
+ const runtime = await this.#ensureNativeSessionBrowser(options);
35677
+ const key = `${options.agent.id}:${nativeSessionId}`;
35678
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
35679
+ if (this.#nativeOperations.has(key) || linked.some(
35680
+ (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
35681
+ )) {
35682
+ throw new AcpExecutionError(
35683
+ "Wait for the native session's running operation to finish",
35684
+ {},
35685
+ "session_busy"
35686
+ );
35687
+ }
35688
+ this.#nativeOperations.add(key);
35689
+ try {
35690
+ for (const entry of linked) {
35691
+ const active = this.#sessions.get(entry.sessionId);
35692
+ if (active !== void 0 && active !== runtime) {
35693
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
35694
+ }
35262
35695
  }
35696
+ options.signal.throwIfAborted();
35697
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
35698
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
35699
+ if (runtime.nativeSessionId() === nativeSessionId) {
35700
+ await this.#retireNativeBrowserProcess(
35701
+ options.sessionId,
35702
+ runtime,
35703
+ async () => await runtime.close()
35704
+ );
35705
+ }
35706
+ return deleted;
35707
+ } finally {
35708
+ this.#nativeOperations.delete(key);
35709
+ this.#notifyProcessCapacityChanged();
35263
35710
  }
35264
- options.signal.throwIfAborted();
35265
- await runtime.deleteNativeSession(nativeSessionId, options.signal);
35266
- const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
35267
- if (runtime.nativeSessionId() === nativeSessionId) {
35268
- this.#nativeBrowserSessions.delete(options.sessionId);
35269
- this.#nativeBrowserStore.remove(options.sessionId);
35270
- await runtime.close();
35271
- }
35272
- return deleted;
35273
35711
  } finally {
35274
- this.#nativeOperations.delete(key);
35712
+ this.#endNativeBrowserUse(options.sessionId);
35275
35713
  }
35276
35714
  };
35277
35715
  };
@@ -35728,14 +36166,14 @@ var FixedInstallationExecutor = class {
35728
36166
  if (initialDiscovery instanceof MissingAgent) {
35729
36167
  throw new InstallationManagerError(
35730
36168
  "agent_not_installed",
35731
- `Install ${specification.label} on this machine, then try installing the integration again.`
36169
+ `Install ${specification.label} on this machine, then check local Agents again.`
35732
36170
  );
35733
36171
  }
35734
36172
  const verifiedAgent = await findVerifiedAgentExecutable(specification, discoveryOptions);
35735
36173
  if (verifiedAgent === null) {
35736
36174
  throw new InstallationManagerError(
35737
36175
  "agent_not_installed",
35738
- `Install ${specification.label} on this machine, then try installing the integration again.`
36176
+ `Install ${specification.label} on this machine, then check local Agents again.`
35739
36177
  );
35740
36178
  }
35741
36179
  const agent = verifiedAgent.executable;
@@ -36373,21 +36811,8 @@ var WorkspaceDirectoryService = class {
36373
36811
 
36374
36812
  // src/bots/local-bot-grant-store.ts
36375
36813
  import { createHash as createHash3, randomUUID } from "node:crypto";
36376
- import { stat as stat7 } from "node:fs/promises";
36377
36814
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
36378
36815
  var LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS = 90 * 24 * 60 * 60 * 1e3;
36379
- var identifier2 = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
36380
- var savedApprovalSchema = external_exports.object({
36381
- local_grant_id: identifier2,
36382
- bot_id: identifier2,
36383
- binding_id: identifier2,
36384
- binding_revision: external_exports.number().int().positive(),
36385
- agent_ref: identifier2,
36386
- workspace_ref: external_exports.string().min(1).max(2048),
36387
- revocation_epoch: external_exports.number().int().nonnegative(),
36388
- agent_identity_digest: external_exports.string().regex(/^[a-f0-9]{64}$/),
36389
- workspace_identity_digest: external_exports.string().regex(/^[a-f0-9]{64}$/)
36390
- }).readonly();
36391
36816
  var LocalBotAuthorizationError = class extends Error {
36392
36817
  code;
36393
36818
  constructor(code, message, options = {}) {
@@ -36442,19 +36867,8 @@ function agentDigest(agent) {
36442
36867
  })
36443
36868
  );
36444
36869
  }
36445
- async function workspaceDigest(path2) {
36446
- const metadata = await stat7(path2);
36447
- if (!metadata.isDirectory()) {
36448
- throw new LocalBotAuthorizationError("binding_incompatible", "The Bot workspace is not a directory");
36449
- }
36450
- return digest(
36451
- JSON.stringify({
36452
- changedAtMilliseconds: metadata.ctimeMs,
36453
- device: metadata.dev,
36454
- inode: metadata.ino,
36455
- path: path2
36456
- })
36457
- );
36870
+ function workspaceDigest(path2) {
36871
+ return digest(path2);
36458
36872
  }
36459
36873
  function exactTargets(left, right) {
36460
36874
  if (left.length !== right.length) {
@@ -36488,6 +36902,16 @@ function rowInteger(row, key) {
36488
36902
  }
36489
36903
  return value;
36490
36904
  }
36905
+ function rowHasInteger(row, key) {
36906
+ const value = Reflect.get(row, key);
36907
+ if (value === null) {
36908
+ return false;
36909
+ }
36910
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
36911
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
36912
+ }
36913
+ return true;
36914
+ }
36491
36915
  function parseTargets(encoded) {
36492
36916
  let value;
36493
36917
  try {
@@ -36511,17 +36935,6 @@ function parseSessionConfigurations(encoded) {
36511
36935
  }
36512
36936
  var LocalBotGrantStore = class {
36513
36937
  #database;
36514
- static containsBot = (path2, botId) => {
36515
- const database = new DatabaseSync3(path2, { readOnly: true });
36516
- try {
36517
- if (database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_bot_grants'").get() === void 0) {
36518
- return false;
36519
- }
36520
- return database.prepare("SELECT local_grant_id FROM local_bot_grants WHERE bot_id = ? LIMIT 1").get(botId) !== void 0;
36521
- } finally {
36522
- database.close();
36523
- }
36524
- };
36525
36938
  constructor(path2) {
36526
36939
  this.#database = new DatabaseSync3(path2);
36527
36940
  this.#database.exec(`
@@ -36559,78 +36972,6 @@ var LocalBotGrantStore = class {
36559
36972
  ) STRICT;
36560
36973
  `);
36561
36974
  }
36562
- /** Only the local CLI may invoke this explicit approval transition. */
36563
- reapprove = async (botId, catalog, directories, bindingAuthorityId, now, signal) => {
36564
- signal.throwIfAborted();
36565
- if (!identifier2.safeParse(botId).success) {
36566
- throw new LocalBotAuthorizationError("invalid_request", "The Bot ID is invalid");
36567
- }
36568
- const row = this.#database.prepare("SELECT * FROM local_bot_grants WHERE bot_id = ? ORDER BY binding_revision DESC LIMIT 1").get(botId);
36569
- if (row === void 0) {
36570
- throw new LocalBotAuthorizationError("bot_not_found", "This machine has no saved approval for that Bot");
36571
- }
36572
- const parsed = savedApprovalSchema.safeParse(row);
36573
- if (!parsed.success) {
36574
- throw new LocalBotAuthorizationError("local_grant_invalid", "The saved Bot approval is invalid", {
36575
- cause: parsed.error
36576
- });
36577
- }
36578
- const saved = parsed.data;
36579
- const agent = catalog.find(saved.agent_ref);
36580
- if (!agent.capabilities.embeddedContextPrompt) {
36581
- throw new LocalBotAuthorizationError("binding_incompatible", "The local Agent cannot apply Bot context");
36582
- }
36583
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
36584
- revalidateExecutable(agent.adapterIdentity),
36585
- revalidateExecutable(agent.agentIdentity)
36586
- ]);
36587
- signal.throwIfAborted();
36588
- if (!adapterUnchanged || !agentUnchanged) {
36589
- throw new LocalBotAuthorizationError(
36590
- "binding_incompatible",
36591
- "The local Agent executable changed before approval"
36592
- );
36593
- }
36594
- const workspacePath = await directories.resolve(bindingAuthorityId, saved.workspace_ref, signal);
36595
- const workspaceIdentityDigest = await workspaceDigest(workspacePath);
36596
- signal.throwIfAborted();
36597
- this.#database.exec("BEGIN IMMEDIATE");
36598
- try {
36599
- const result = this.#database.prepare(`UPDATE local_bot_grants
36600
- SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
36601
- revoked_at = NULL, expires_at = ?, revocation_epoch = revocation_epoch + 1
36602
- WHERE local_grant_id = ? AND revocation_epoch = ?
36603
- AND agent_identity_digest = ? AND workspace_identity_digest = ?
36604
- AND binding_revision = (SELECT MAX(binding_revision) FROM local_bot_grants WHERE bot_id = ?)`).run(
36605
- agentDigest(agent),
36606
- workspaceIdentityDigest,
36607
- workspacePath,
36608
- now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS,
36609
- saved.local_grant_id,
36610
- saved.revocation_epoch,
36611
- saved.agent_identity_digest,
36612
- saved.workspace_identity_digest,
36613
- botId
36614
- );
36615
- if (result.changes !== 1) {
36616
- throw new LocalBotAuthorizationError(
36617
- "binding_not_approved",
36618
- "The Bot binding changed during approval; run the command again"
36619
- );
36620
- }
36621
- this.#database.prepare(`INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
36622
- VALUES (?, 'bot_binding_locally_reapproved', ?, '', ?)`).run(
36623
- new Date(now).toISOString(),
36624
- saved.binding_id,
36625
- JSON.stringify({ botId, bindingId: saved.binding_id, agentRef: saved.agent_ref })
36626
- );
36627
- this.#database.exec("COMMIT");
36628
- } catch (cause) {
36629
- this.#database.exec("ROLLBACK");
36630
- throw cause;
36631
- }
36632
- return { bindingId: saved.binding_id, workspacePath, agentRef: saved.agent_ref };
36633
- };
36634
36975
  approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
36635
36976
  signal.throwIfAborted();
36636
36977
  const existing = this.#database.prepare(
@@ -36720,8 +37061,7 @@ var LocalBotGrantStore = class {
36720
37061
  WHERE grants.local_grant_id = ? AND grants.bot_id = ?
36721
37062
  AND behavior_revision_id = ? AND behavior_digest = ?
36722
37063
  AND binding_id = ? AND binding_revision = ?
36723
- AND agent_ref = ?
36724
- AND revoked_at IS NULL AND expires_at > ?`
37064
+ AND agent_ref = ?`
36725
37065
  ).get(
36726
37066
  command.localGrantId,
36727
37067
  command.botId,
@@ -36729,8 +37069,7 @@ var LocalBotGrantStore = class {
36729
37069
  command.behaviorDigest,
36730
37070
  command.bindingId,
36731
37071
  command.bindingRevision,
36732
- command.agentId,
36733
- now
37072
+ command.agentId
36734
37073
  );
36735
37074
  if (row === void 0) {
36736
37075
  throw new LocalBotAuthorizationError(
@@ -36743,14 +37082,14 @@ var LocalBotGrantStore = class {
36743
37082
  if (!exactTargets(approvedTargets, requestedTargets)) {
36744
37083
  throw new LocalBotAuthorizationError(
36745
37084
  "binding_not_approved",
36746
- "The Bot execution target policy changed after local approval"
37085
+ "The Bot execution target policy differs from its binding"
36747
37086
  );
36748
37087
  }
36749
37088
  const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
36750
37089
  if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
36751
37090
  throw new LocalBotAuthorizationError(
36752
37091
  "binding_not_approved",
36753
- "The Bot Agent configuration changed after local approval"
37092
+ "The Bot Agent configuration differs from its binding"
36754
37093
  );
36755
37094
  }
36756
37095
  const agent = catalog.find(command.agentId);
@@ -36759,17 +37098,29 @@ var LocalBotGrantStore = class {
36759
37098
  revalidateExecutable(agent.agentIdentity)
36760
37099
  ]);
36761
37100
  signal.throwIfAborted();
37101
+ if (!adapterUnchanged || !agentUnchanged) {
37102
+ throw new LocalBotAuthorizationError(
37103
+ "binding_incompatible",
37104
+ "The local Agent executable changed while the Runtime is active; restart the Runtime"
37105
+ );
37106
+ }
36762
37107
  const workspaceRef = rowString(row, "workspace_ref");
36763
37108
  const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
36764
37109
  const currentAgentDigest = agentDigest(agent);
36765
- const currentWorkspaceDigest = await workspaceDigest(workspacePath);
37110
+ const currentWorkspaceDigest = workspaceDigest(workspacePath);
36766
37111
  signal.throwIfAborted();
36767
- if (!adapterUnchanged || !agentUnchanged || currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path")) {
36768
- this.revoke(rowString(row, "local_grant_id"), now);
36769
- throw new LocalBotAuthorizationError(
36770
- "binding_not_approved",
36771
- "The Bot execution target changed and requires local approval"
37112
+ let expiresAt = rowInteger(row, "expires_at");
37113
+ let revocationEpoch = rowInteger(row, "revocation_epoch");
37114
+ if (currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path") || expiresAt <= now || rowHasInteger(row, "revoked_at")) {
37115
+ const refreshed = this.refreshTarget(
37116
+ rowString(row, "local_grant_id"),
37117
+ currentAgentDigest,
37118
+ currentWorkspaceDigest,
37119
+ workspacePath,
37120
+ now
36772
37121
  );
37122
+ expiresAt = refreshed.expiresAt;
37123
+ revocationEpoch = refreshed.revocationEpoch;
36773
37124
  }
36774
37125
  if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
36775
37126
  throw new LocalBotAuthorizationError(
@@ -36790,8 +37141,8 @@ var LocalBotGrantStore = class {
36790
37141
  workspacePath,
36791
37142
  currentWorkspaceDigest,
36792
37143
  approvedTargets,
36793
- rowInteger(row, "expires_at"),
36794
- rowInteger(row, "revocation_epoch")
37144
+ expiresAt,
37145
+ revocationEpoch
36795
37146
  );
36796
37147
  };
36797
37148
  recordUnavailable = (request, code, message, now) => {
@@ -36834,16 +37185,65 @@ var LocalBotGrantStore = class {
36834
37185
  return {
36835
37186
  agent,
36836
37187
  agentIdentityDigest: agentDigest(agent),
36837
- workspaceIdentityDigest: await workspaceDigest(workspacePath),
37188
+ workspaceIdentityDigest: workspaceDigest(workspacePath),
36838
37189
  workspacePath
36839
37190
  };
36840
37191
  };
36841
- revoke = (localGrantId, now) => {
36842
- this.#database.prepare(
36843
- `UPDATE local_bot_grants
36844
- SET revoked_at = COALESCE(revoked_at, ?), revocation_epoch = revocation_epoch + 1
36845
- WHERE local_grant_id = ? AND revoked_at IS NULL`
36846
- ).run(now, localGrantId);
37192
+ refreshTarget = (localGrantId, agentIdentityDigest, workspaceIdentityDigest, workspacePath, now) => {
37193
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
37194
+ this.#database.exec("BEGIN IMMEDIATE");
37195
+ try {
37196
+ const current = this.#database.prepare("SELECT * FROM local_bot_grants WHERE local_grant_id = ?").get(localGrantId);
37197
+ if (current === void 0) {
37198
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is missing");
37199
+ }
37200
+ const currentExpiresAt = rowInteger(current, "expires_at");
37201
+ const currentRevocationEpoch = rowInteger(current, "revocation_epoch");
37202
+ if (agentIdentityDigest === rowString(current, "agent_identity_digest") && workspaceIdentityDigest === rowString(current, "workspace_identity_digest") && workspacePath === rowString(current, "workspace_path") && currentExpiresAt > now && !rowHasInteger(current, "revoked_at")) {
37203
+ this.#database.exec("COMMIT");
37204
+ return { expiresAt: currentExpiresAt, revocationEpoch: currentRevocationEpoch };
37205
+ }
37206
+ const result = this.#database.prepare(
37207
+ `UPDATE local_bot_grants
37208
+ SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
37209
+ expires_at = ?, revoked_at = NULL, revocation_epoch = revocation_epoch + 1
37210
+ WHERE local_grant_id = ? AND revocation_epoch = ?`
37211
+ ).run(
37212
+ agentIdentityDigest,
37213
+ workspaceIdentityDigest,
37214
+ workspacePath,
37215
+ expiresAt,
37216
+ localGrantId,
37217
+ currentRevocationEpoch
37218
+ );
37219
+ if (result.changes !== 1) {
37220
+ throw new LocalBotAuthorizationError(
37221
+ "local_grant_invalid",
37222
+ "The local Bot grant target could not be refreshed"
37223
+ );
37224
+ }
37225
+ this.#database.prepare(
37226
+ `INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
37227
+ VALUES (?, 'bot_binding_target_refreshed', ?, '', ?)`
37228
+ ).run(
37229
+ new Date(now).toISOString(),
37230
+ rowString(current, "binding_id"),
37231
+ JSON.stringify({
37232
+ agentIdentityChanged: agentIdentityDigest !== rowString(current, "agent_identity_digest"),
37233
+ bindingId: rowString(current, "binding_id"),
37234
+ botId: rowString(current, "bot_id"),
37235
+ expired: currentExpiresAt <= now,
37236
+ revived: rowHasInteger(current, "revoked_at"),
37237
+ workspaceIdentityChanged: workspaceIdentityDigest !== rowString(current, "workspace_identity_digest"),
37238
+ workspacePathChanged: workspacePath !== rowString(current, "workspace_path")
37239
+ })
37240
+ );
37241
+ this.#database.exec("COMMIT");
37242
+ return { expiresAt, revocationEpoch: currentRevocationEpoch + 1 };
37243
+ } catch (cause) {
37244
+ this.#database.exec("ROLLBACK");
37245
+ throw cause;
37246
+ }
36847
37247
  };
36848
37248
  };
36849
37249
 
@@ -40008,32 +40408,9 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
40008
40408
  }
40009
40409
  const attachments = await resolvePromptArtifacts(config2, command, signal);
40010
40410
  const applied = await applicator.apply(command, grant, attachments.resources, signal);
40011
- const lease = contexts.activate(command);
40012
- try {
40013
- const deadlineSignal = AbortSignal.timeout(remaining);
40014
- const executionSignal = AbortSignal.any([signal, deadlineSignal]);
40015
- const agent = botExecutionAgent(grant.agent, lease.context.contextHandle, ipc.socketPath);
40016
- await sessions.prepareExecutionSession({
40017
- additionalDirectories: resolved.additionalDirectories,
40018
- agent,
40019
- cwd: resolved.cwd,
40020
- sessionId: command.sessionId,
40021
- signal: executionSignal
40022
- });
40023
- for (const selection of command.sessionConfigurations) {
40024
- await sessions.configureSession({
40025
- additionalDirectories: resolved.additionalDirectories,
40026
- agent,
40027
- booleanValue: selection.booleanValue,
40028
- configId: selection.configId,
40029
- cwd: resolved.cwd,
40030
- requestId: `cfg_${randomUUID4()}`,
40031
- sessionId: command.sessionId,
40032
- signal: executionSignal,
40033
- value: selection.value,
40034
- valueType: selection.valueType
40035
- });
40036
- }
40411
+ const deadlineSignal = AbortSignal.timeout(remaining);
40412
+ const executionSignal = AbortSignal.any([signal, deadlineSignal]);
40413
+ const startExecution = () => {
40037
40414
  audit.record({
40038
40415
  commandId: command.commandId,
40039
40416
  details: {
@@ -40058,56 +40435,106 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
40058
40435
  attemptId
40059
40436
  );
40060
40437
  activateAttempt();
40061
- const result = await sessions.runPrompt({
40438
+ };
40439
+ let stopReason = "steered";
40440
+ if (command.disposition === SessionPromptDisposition.Steer) {
40441
+ startExecution();
40442
+ await sessions.steerPrompt({
40062
40443
  additionalDirectories: resolved.additionalDirectories,
40063
- agent,
40444
+ agent: grant.agent,
40064
40445
  commandId: command.commandId,
40065
40446
  cwd: resolved.cwd,
40066
40447
  images: attachments.images,
40067
- onActivity: activities.record,
40068
- onText: (text3, messageId) => {
40069
- publisher.recordAttempt(
40070
- command.sessionId,
40071
- encodeAgentMessageDeltaEvent({
40072
- commandId: command.commandId,
40073
- kind: AGENT_MESSAGE_DELTA_KIND,
40074
- messageId,
40075
- sessionId: command.sessionId,
40076
- text: text3
40077
- }),
40078
- attemptId
40079
- );
40080
- return Promise.resolve();
40081
- },
40082
40448
  prompt: command.prompt,
40083
40449
  resources: applied.resources,
40084
40450
  sessionId: command.sessionId,
40085
- signal: executionSignal
40451
+ signal: executionSignal,
40452
+ targetCommandId: command.targetCommandId
40086
40453
  });
40087
- activities.flush();
40088
- publisher.recordAttempt(
40089
- command.sessionId,
40090
- encodeSessionCompletedEvent({
40454
+ } else {
40455
+ if (command.disposition === SessionPromptDisposition.Queue && !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
40456
+ throw new AcpExecutionError(
40457
+ "The queued Bot prompt target is unavailable",
40458
+ {},
40459
+ "prompt_queue_target_unavailable"
40460
+ );
40461
+ }
40462
+ const lease = contexts.activate(command);
40463
+ try {
40464
+ const agent = botExecutionAgent(grant.agent, lease.context.contextHandle, ipc.socketPath);
40465
+ await sessions.prepareExecutionSession({
40466
+ additionalDirectories: resolved.additionalDirectories,
40467
+ agent,
40468
+ cwd: resolved.cwd,
40469
+ sessionId: command.sessionId,
40470
+ signal: executionSignal
40471
+ });
40472
+ for (const selection of command.sessionConfigurations) {
40473
+ await sessions.configureSession({
40474
+ additionalDirectories: resolved.additionalDirectories,
40475
+ agent,
40476
+ booleanValue: selection.booleanValue,
40477
+ configId: selection.configId,
40478
+ cwd: resolved.cwd,
40479
+ requestId: `cfg_${randomUUID4()}`,
40480
+ sessionId: command.sessionId,
40481
+ signal: executionSignal,
40482
+ value: selection.value,
40483
+ valueType: selection.valueType
40484
+ });
40485
+ }
40486
+ startExecution();
40487
+ const result = await sessions.runPrompt({
40488
+ additionalDirectories: resolved.additionalDirectories,
40489
+ agent,
40091
40490
  commandId: command.commandId,
40092
- kind: SESSION_COMPLETED_KIND,
40491
+ cwd: resolved.cwd,
40492
+ disposition: command.disposition,
40493
+ images: attachments.images,
40494
+ onActivity: activities.record,
40495
+ onText: (text3, messageId) => {
40496
+ publisher.recordAttempt(
40497
+ command.sessionId,
40498
+ encodeAgentMessageDeltaEvent({
40499
+ commandId: command.commandId,
40500
+ kind: AGENT_MESSAGE_DELTA_KIND,
40501
+ messageId,
40502
+ sessionId: command.sessionId,
40503
+ text: text3
40504
+ }),
40505
+ attemptId
40506
+ );
40507
+ return Promise.resolve();
40508
+ },
40509
+ prompt: command.prompt,
40510
+ resources: applied.resources,
40093
40511
  sessionId: command.sessionId,
40094
- stopReason: result.stopReason
40095
- }),
40096
- attemptId
40097
- );
40098
- outbox.transitionExecution(
40099
- command.commandId,
40100
- result.stopReason === "cancelled" ? "cancelled" : "succeeded"
40101
- );
40102
- audit.record({
40103
- commandId: command.commandId,
40104
- details: { botId: command.botId, executionId: command.executionId },
40105
- event: result.stopReason === "cancelled" ? "bot_session_cancelled" : "bot_session_completed",
40106
- sessionId: command.sessionId
40107
- });
40108
- } finally {
40109
- lease.release();
40512
+ signal: executionSignal,
40513
+ targetCommandId: command.targetCommandId
40514
+ });
40515
+ stopReason = result.stopReason;
40516
+ } finally {
40517
+ lease.release();
40518
+ }
40110
40519
  }
40520
+ activities.flush();
40521
+ publisher.recordAttempt(
40522
+ command.sessionId,
40523
+ encodeSessionCompletedEvent({
40524
+ commandId: command.commandId,
40525
+ kind: SESSION_COMPLETED_KIND,
40526
+ sessionId: command.sessionId,
40527
+ stopReason
40528
+ }),
40529
+ attemptId
40530
+ );
40531
+ outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
40532
+ audit.record({
40533
+ commandId: command.commandId,
40534
+ details: { botId: command.botId, executionId: command.executionId },
40535
+ event: stopReason === "cancelled" ? "bot_session_cancelled" : "bot_session_completed",
40536
+ sessionId: command.sessionId
40537
+ });
40111
40538
  } catch (error62) {
40112
40539
  activities.flush();
40113
40540
  const failure2 = Date.parse(command.executionDeadlineAt) <= Date.now() ? new LocalBotAuthorizationError("turn_expired", "The Bot execution deadline has expired", {
@@ -40358,7 +40785,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40358
40785
  await processDeliveredPrompt(
40359
40786
  delivery,
40360
40787
  command,
40361
- true,
40788
+ command.disposition !== SessionPromptDisposition.Steer,
40362
40789
  (attemptId, activateAttempt, executionSignal) => executeBotPrompt(
40363
40790
  outbox,
40364
40791
  publisher,
@@ -41011,7 +41438,11 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41011
41438
  applicator,
41012
41439
  ipc,
41013
41440
  receipt2.attemptId,
41014
- () => activeAttemptIds.set(command2.sessionId, receipt2.attemptId),
41441
+ () => {
41442
+ if (command2.disposition !== SessionPromptDisposition.Steer) {
41443
+ activeAttemptIds.set(command2.sessionId, receipt2.attemptId);
41444
+ }
41445
+ },
41015
41446
  timer,
41016
41447
  turn2.signal
41017
41448
  ).catch((error62) => {
@@ -41283,7 +41714,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41283
41714
 
41284
41715
  // src/pairing/pair-local-machine.ts
41285
41716
  import { randomUUID as randomUUID5 } from "node:crypto";
41286
- import { mkdir as mkdir4, open as open4, realpath as realpath8, rename as rename3, stat as stat8, writeFile as writeFile2 } from "node:fs/promises";
41717
+ import { mkdir as mkdir4, open as open4, realpath as realpath8, rename as rename3, stat as stat7, writeFile as writeFile2 } from "node:fs/promises";
41287
41718
  import { hostname as hostname3 } from "node:os";
41288
41719
  import { basename as basename5, join as join17, resolve as resolve4 } from "node:path";
41289
41720
  import { fetch as fetch7 } from "undici";
@@ -41353,7 +41784,7 @@ async function resolveDefaultWorkspace2(path2) {
41353
41784
  try {
41354
41785
  await mkdir4(requestedWorkspace, { recursive: true, mode: 448 });
41355
41786
  const defaultWorkspace = await realpath8(requestedWorkspace);
41356
- const metadata = await stat8(defaultWorkspace);
41787
+ const metadata = await stat7(defaultWorkspace);
41357
41788
  if (!metadata.isDirectory()) {
41358
41789
  throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
41359
41790
  }
@@ -41657,7 +42088,7 @@ async function resolveWorkspace(path2) {
41657
42088
  try {
41658
42089
  await mkdir5(requested, { recursive: true, mode: 448 });
41659
42090
  const resolved = await realpath9(requested);
41660
- const metadata = await stat9(resolved);
42091
+ const metadata = await stat8(resolved);
41661
42092
  if (!metadata.isDirectory()) {
41662
42093
  throw new MobiusRuntimeConfigurationError("The Runtime workspace is not a directory");
41663
42094
  }