@moxt-ai/mobius 0.0.40 → 0.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import { mkdir as mkdir5 } from "node:fs/promises";
11
11
  // package.json
12
12
  var package_default = {
13
13
  name: "@moxt-ai/mobius",
14
- version: "0.0.40",
14
+ version: "0.0.41",
15
15
  description: "Mobius CLI for pairing and running local AI agent services.",
16
16
  type: "module",
17
17
  bin: {
@@ -2874,9 +2874,166 @@ async function discoverLocalAgentInventory(options) {
2874
2874
  return new LocalAgentInventory(discoveries);
2875
2875
  }
2876
2876
 
2877
- // src/bots/bot-approve-command.ts
2878
- import { readdir as readdir3, realpath as realpath8 } from "node:fs/promises";
2879
- import { dirname as dirname4, join as join17 } from "node:path";
2877
+ // src/bots/bot-message-command.ts
2878
+ import { randomUUID } from "node:crypto";
2879
+ import { createConnection } from "node:net";
2880
+ var BOT_IPC_RESPONSE_LIMIT = 64 * 1024;
2881
+ var BOT_IPC_TIMEOUT_MILLISECONDS = 2e4;
2882
+ var BotMessageCommandError = class extends Error {
2883
+ code;
2884
+ constructor(code, message, options = {}) {
2885
+ super(message, options);
2886
+ this.code = code;
2887
+ this.name = "BotMessageCommandError";
2888
+ }
2889
+ };
2890
+ function isRecord4(value) {
2891
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2892
+ }
2893
+ function requiredEnvironment(environment, name) {
2894
+ const value = environment[name]?.trim();
2895
+ if (value === void 0 || value.length === 0) {
2896
+ throw new BotMessageCommandError(
2897
+ "execution_context_required",
2898
+ "This command is available only inside an active Mobius Bot execution"
2899
+ );
2900
+ }
2901
+ return value;
2902
+ }
2903
+ function option(arguments_, name) {
2904
+ const index2 = arguments_.indexOf(name);
2905
+ if (index2 < 0 || index2 + 1 >= arguments_.length || arguments_[index2 + 1]?.startsWith("--") === true) {
2906
+ throw new BotMessageCommandError(
2907
+ "invalid_request",
2908
+ "Usage: mobius bot message send --target <current|alias> --text <message>"
2909
+ );
2910
+ }
2911
+ const value = arguments_[index2 + 1];
2912
+ if (value === void 0) {
2913
+ throw new BotMessageCommandError("invalid_request", "The Bot message option is missing");
2914
+ }
2915
+ return value;
2916
+ }
2917
+ function validateArguments(arguments_) {
2918
+ if (arguments_.length !== 4) {
2919
+ throw new BotMessageCommandError(
2920
+ "invalid_request",
2921
+ "Usage: mobius bot message send --target <current|alias> --text <message>"
2922
+ );
2923
+ }
2924
+ const names = [arguments_[0], arguments_[2]];
2925
+ if (!names.includes("--target") || !names.includes("--text") || names[0] === names[1]) {
2926
+ throw new BotMessageCommandError(
2927
+ "invalid_request",
2928
+ "Usage: mobius bot message send --target <current|alias> --text <message>"
2929
+ );
2930
+ }
2931
+ }
2932
+ function decodeResponse(encoded) {
2933
+ let value;
2934
+ try {
2935
+ value = JSON.parse(encoded);
2936
+ } catch (cause) {
2937
+ throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data", {
2938
+ cause
2939
+ });
2940
+ }
2941
+ if (!isRecord4(value) || typeof value["ok"] !== "boolean") {
2942
+ throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data");
2943
+ }
2944
+ if (value["ok"] === true && typeof value["outboundMessageId"] === "string") {
2945
+ return value["outboundMessageId"];
2946
+ }
2947
+ const error62 = value["error"];
2948
+ if (value["ok"] === false && isRecord4(error62) && typeof error62["code"] === "string" && typeof error62["message"] === "string") {
2949
+ throw new BotMessageCommandError(error62["code"], error62["message"]);
2950
+ }
2951
+ throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data");
2952
+ }
2953
+ async function requestLocalBotService(socketPath, payload, signal) {
2954
+ signal.throwIfAborted();
2955
+ return await new Promise((resolve5, reject) => {
2956
+ const socket = createConnection(socketPath);
2957
+ const chunks = [];
2958
+ let length = 0;
2959
+ let finished = false;
2960
+ const finish = () => {
2961
+ socket.removeAllListeners();
2962
+ socket.destroy();
2963
+ };
2964
+ const fail = (error62) => {
2965
+ if (finished) {
2966
+ return;
2967
+ }
2968
+ finished = true;
2969
+ finish();
2970
+ if (error62 instanceof BotMessageCommandError) {
2971
+ reject(error62);
2972
+ return;
2973
+ }
2974
+ reject(
2975
+ new BotMessageCommandError(
2976
+ "execution_context_required",
2977
+ "The active Mobius Bot execution is unavailable",
2978
+ { cause: error62 }
2979
+ )
2980
+ );
2981
+ };
2982
+ const abort = () => fail(signal.reason);
2983
+ socket.setTimeout(BOT_IPC_TIMEOUT_MILLISECONDS, () => {
2984
+ fail(new BotMessageCommandError("bot_service_unavailable", "The local Bot service timed out"));
2985
+ });
2986
+ socket.once("error", fail);
2987
+ socket.once("connect", () => socket.end(`${payload}
2988
+ `));
2989
+ socket.on("data", (chunk) => {
2990
+ length += chunk.byteLength;
2991
+ if (length > BOT_IPC_RESPONSE_LIMIT) {
2992
+ fail(new BotMessageCommandError("bot_service_unavailable", "The local Bot response is too large"));
2993
+ return;
2994
+ }
2995
+ chunks.push(chunk);
2996
+ });
2997
+ socket.once("end", () => {
2998
+ if (finished) {
2999
+ return;
3000
+ }
3001
+ finished = true;
3002
+ signal.removeEventListener("abort", abort);
3003
+ try {
3004
+ resolve5(decodeResponse(Buffer.concat(chunks).toString("utf8")));
3005
+ } catch (error62) {
3006
+ reject(error62);
3007
+ } finally {
3008
+ finish();
3009
+ }
3010
+ });
3011
+ signal.addEventListener("abort", abort, { once: true });
3012
+ });
3013
+ }
3014
+ async function executeBotMessageCommand(arguments_, environment, signal) {
3015
+ validateArguments(arguments_);
3016
+ const contextHandle = requiredEnvironment(environment, "MOBIUS_BOT_CONTEXT");
3017
+ const socketPath = requiredEnvironment(environment, "MOBIUS_BOT_SOCKET");
3018
+ const target = option(arguments_, "--target");
3019
+ const text3 = option(arguments_, "--text");
3020
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(target) || text3.trim().length === 0 || text3.length > 1e4) {
3021
+ throw new BotMessageCommandError("invalid_request", "The Bot outbound message is invalid");
3022
+ }
3023
+ return await requestLocalBotService(
3024
+ socketPath,
3025
+ JSON.stringify({
3026
+ contextHandle,
3027
+ idempotencyKey: `cli_${randomUUID()}`,
3028
+ target,
3029
+ text: text3
3030
+ }),
3031
+ signal
3032
+ );
3033
+ }
3034
+
3035
+ // src/config.ts
3036
+ import { join as join14 } from "node:path";
2880
3037
 
2881
3038
  // ../../node_modules/.pnpm/zod@4.6.2/node_modules/zod/v4/classic/external.js
2882
3039
  var external_exports = {};
@@ -22553,174 +22710,6 @@ function date4(params) {
22553
22710
  return _coercedDate(ZodDate, params);
22554
22711
  }
22555
22712
 
22556
- // src/authorization/workspace-directory.ts
22557
- import { readdir as readdir2, realpath as realpath6, stat as stat5 } from "node:fs/promises";
22558
- import { homedir as homedir2 } from "node:os";
22559
- import { basename, dirname as dirname3, isAbsolute as isAbsolute8, join as join14, normalize as normalize2, relative as relative4 } from "node:path";
22560
-
22561
- // src/authorization/local-authorization-error.ts
22562
- var LocalAuthorizationError = class extends Error {
22563
- code = "local_authorization_failed";
22564
- constructor(message, options = {}) {
22565
- super(message, options);
22566
- this.name = "LocalAuthorizationError";
22567
- }
22568
- };
22569
-
22570
- // src/authorization/workspace-directory.ts
22571
- var WorkspaceDirectoryListing = class {
22572
- directoryId;
22573
- directoryLabel;
22574
- entries;
22575
- parentDirectoryId;
22576
- constructor(directoryId2, directoryLabel, entries, parentDirectoryId) {
22577
- this.directoryId = directoryId2;
22578
- this.directoryLabel = directoryLabel;
22579
- this.entries = entries;
22580
- this.parentDirectoryId = parentDirectoryId;
22581
- }
22582
- };
22583
- function encodePath(path2) {
22584
- const encoded = Buffer.from(path2, "utf8").toString("base64url");
22585
- if (encoded.length === 0 || encoded.length > 2e3) {
22586
- throw new LocalAuthorizationError("The local directory path is too long to select");
22587
- }
22588
- return `path-${encoded}`;
22589
- }
22590
- function decodePath(value, prefix) {
22591
- const encoded = value.slice(prefix.length);
22592
- if (encoded.length === 0 || encoded.length > 2e3 || !/^[a-zA-Z0-9_-]+$/.test(encoded)) {
22593
- throw new LocalAuthorizationError("The directory identifier is invalid");
22594
- }
22595
- const decoded = Buffer.from(encoded, "base64url").toString("utf8");
22596
- if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize2(decoded) !== decoded) {
22597
- throw new LocalAuthorizationError("The directory identifier is invalid");
22598
- }
22599
- return decoded;
22600
- }
22601
- var WorkspaceDirectoryService = class {
22602
- #bindingId;
22603
- #defaultWorkspace;
22604
- constructor(bindingId, defaultWorkspace) {
22605
- this.#bindingId = bindingId;
22606
- this.#defaultWorkspace = defaultWorkspace;
22607
- }
22608
- authorizeMachine = (bindingId) => {
22609
- if (bindingId !== this.#bindingId) {
22610
- throw new LocalAuthorizationError("The runtime binding is not authorized");
22611
- }
22612
- };
22613
- requestedPath = (id) => {
22614
- if (id === "default") {
22615
- return this.#defaultWorkspace;
22616
- }
22617
- if (id === "home") {
22618
- return homedir2();
22619
- }
22620
- if (id.startsWith("path-")) {
22621
- const path2 = decodePath(id, "path-");
22622
- if (isAbsolute8(path2)) {
22623
- return path2;
22624
- }
22625
- }
22626
- throw new LocalAuthorizationError("The directory identifier is invalid");
22627
- };
22628
- resolvePath = async (requested, signal) => {
22629
- signal.throwIfAborted();
22630
- if (!isAbsolute8(requested) || requested.includes("\0") || normalize2(requested) !== requested) {
22631
- throw new LocalAuthorizationError("The local directory path is invalid");
22632
- }
22633
- try {
22634
- const target = await realpath6(requested);
22635
- signal.throwIfAborted();
22636
- const metadata = await stat5(target);
22637
- signal.throwIfAborted();
22638
- if (!isAbsolute8(target) || normalize2(target) !== target || !metadata.isDirectory()) {
22639
- throw new LocalAuthorizationError("The selected location is not a directory");
22640
- }
22641
- return target;
22642
- } catch (cause) {
22643
- signal.throwIfAborted();
22644
- if (cause instanceof LocalAuthorizationError) {
22645
- throw cause;
22646
- }
22647
- throw new LocalAuthorizationError("This directory is missing or unavailable to your user account", {
22648
- cause
22649
- });
22650
- }
22651
- };
22652
- label = (path2) => {
22653
- const suffix = relative4(homedir2(), path2);
22654
- return suffix === "" ? "~" : !isAbsolute8(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path2;
22655
- };
22656
- identify = async (bindingId, requestedPath, signal) => {
22657
- this.authorizeMachine(bindingId);
22658
- const path2 = await this.resolvePath(requestedPath, signal);
22659
- return {
22660
- path: path2,
22661
- directoryId: encodePath(path2),
22662
- name: basename(path2) || path2,
22663
- label: this.label(path2)
22664
- };
22665
- };
22666
- resolve = async (bindingId, id, signal) => {
22667
- this.authorizeMachine(bindingId);
22668
- return await this.resolvePath(this.requestedPath(id), signal);
22669
- };
22670
- list = async (bindingId, id, signal) => {
22671
- const target = await this.resolve(bindingId, id, signal);
22672
- try {
22673
- const children = await readdir2(target, { withFileTypes: true });
22674
- signal.throwIfAborted();
22675
- const entries = [];
22676
- for (const child of children) {
22677
- if (entries.length === 500) {
22678
- break;
22679
- }
22680
- if (child.isFile() || child.isBlockDevice() || child.isCharacterDevice() || child.isFIFO() || child.isSocket()) {
22681
- continue;
22682
- }
22683
- try {
22684
- const path2 = await this.resolvePath(join14(target, child.name), signal);
22685
- entries.push({ directoryId: encodePath(path2), name: child.name });
22686
- } catch (cause) {
22687
- signal.throwIfAborted();
22688
- if (!(cause instanceof LocalAuthorizationError)) {
22689
- throw cause;
22690
- }
22691
- }
22692
- }
22693
- entries.sort((a, b) => a.name.localeCompare(b.name));
22694
- const parent = dirname3(target);
22695
- return new WorkspaceDirectoryListing(
22696
- id,
22697
- this.label(target),
22698
- entries,
22699
- parent === target ? "" : encodePath(parent)
22700
- );
22701
- } catch (cause) {
22702
- signal.throwIfAborted();
22703
- if (cause instanceof LocalAuthorizationError) {
22704
- throw cause;
22705
- }
22706
- throw new LocalAuthorizationError("This directory cannot be browsed by your user account", { cause });
22707
- }
22708
- };
22709
- resolveMany = async (bindingId, ids, signal) => {
22710
- const paths = /* @__PURE__ */ new Set();
22711
- for (const id of ids) {
22712
- paths.add(await this.resolve(bindingId, id, signal));
22713
- }
22714
- return [...paths];
22715
- };
22716
- };
22717
-
22718
- // src/pairing/pair-local-machine.ts
22719
- import { randomUUID } from "node:crypto";
22720
- import { mkdir as mkdir3, open as open4, realpath as realpath7, rename as rename3, stat as stat6, writeFile as writeFile2 } from "node:fs/promises";
22721
- import { hostname as hostname3 } from "node:os";
22722
- import { basename as basename2, join as join16, resolve as resolve3 } from "node:path";
22723
-
22724
22713
  // ../protocol/src/prompt-usage.ts
22725
22714
  var TOKEN_COUNT = external_exports.number().int().nonnegative();
22726
22715
  function normalizeQuotaTokenCount(value) {
@@ -23300,7 +23289,7 @@ var ProtocolMessageError = class extends Error {
23300
23289
  this.name = "ProtocolMessageError";
23301
23290
  }
23302
23291
  };
23303
- function isRecord4(value) {
23292
+ function isRecord5(value) {
23304
23293
  return typeof value === "object" && value !== null && !Array.isArray(value);
23305
23294
  }
23306
23295
  function parseJson2(encoded) {
@@ -23312,7 +23301,7 @@ function parseJson2(encoded) {
23312
23301
  cause: error62
23313
23302
  });
23314
23303
  }
23315
- if (!isRecord4(value)) {
23304
+ if (!isRecord5(value)) {
23316
23305
  throw new ProtocolMessageError("Message must be a JSON object");
23317
23306
  }
23318
23307
  return value;
@@ -23409,7 +23398,7 @@ function readActivityContent(value) {
23409
23398
  }
23410
23399
  function readActivityDetail(value) {
23411
23400
  const field = value["detail"];
23412
- if (!isRecord4(field)) {
23401
+ if (!isRecord5(field)) {
23413
23402
  throw new ProtocolMessageError("Invalid activity detail field");
23414
23403
  }
23415
23404
  const kind = readString(field, "kind", 32);
@@ -23896,7 +23885,7 @@ var BotSessionPromptCommand = class {
23896
23885
  };
23897
23886
  }
23898
23887
  };
23899
- function isRecord5(value) {
23888
+ function isRecord6(value) {
23900
23889
  return typeof value === "object" && value !== null && !Array.isArray(value);
23901
23890
  }
23902
23891
  function parseJson3(encoded) {
@@ -23906,7 +23895,7 @@ function parseJson3(encoded) {
23906
23895
  } catch (cause) {
23907
23896
  throw new ProtocolMessageError("Message is not valid JSON", { cause });
23908
23897
  }
23909
- if (!isRecord5(value)) {
23898
+ if (!isRecord6(value)) {
23910
23899
  throw new ProtocolMessageError("Message must be a JSON object");
23911
23900
  }
23912
23901
  return value;
@@ -23997,7 +23986,7 @@ function readTargets(value, key) {
23997
23986
  const identifiers = /* @__PURE__ */ new Set();
23998
23987
  const aliases = /* @__PURE__ */ new Set();
23999
23988
  for (const candidate of field) {
24000
- if (!isRecord5(candidate)) {
23989
+ if (!isRecord6(candidate)) {
24001
23990
  throw new ProtocolMessageError(`Invalid Bot delivery targets: ${key}`);
24002
23991
  }
24003
23992
  assertExactKeys2(candidate, ["alias", "deliveryTargetId"]);
@@ -24019,7 +24008,7 @@ function readSessionConfigurations(value) {
24019
24008
  return decodeSessionConfigurationSelections(value["sessionConfigurations"]);
24020
24009
  }
24021
24010
  function readCompletionPolicy(value) {
24022
- if (!isRecord5(value)) {
24011
+ if (!isRecord6(value)) {
24023
24012
  throw new ProtocolMessageError("Invalid Bot completion policy");
24024
24013
  }
24025
24014
  const kind = readText2(value, "kind", 32, false);
@@ -24037,7 +24026,7 @@ function readCompletionPolicy(value) {
24037
24026
  throw new ProtocolMessageError("Invalid Bot completion policy");
24038
24027
  }
24039
24028
  function readReplyRoute(value) {
24040
- if (!isRecord5(value)) {
24029
+ if (!isRecord6(value)) {
24041
24030
  throw new ProtocolMessageError("Invalid Bot reply route");
24042
24031
  }
24043
24032
  const kind = readText2(value, "kind", 32, false);
@@ -24530,14 +24519,10 @@ var decodeSessionEventAcknowledgement = (encoded) => decode5(encoded, eventAckno
24530
24519
  var decodeSessionEventDeferred = (encoded) => decode5(encoded, eventDeferredSchema);
24531
24520
  var decodeSessionEventRejection = (encoded) => decode5(encoded, eventRejectionSchema);
24532
24521
 
24533
- // src/pairing/pair-local-machine.ts
24534
- import { fetch as fetch2 } from "undici";
24535
-
24536
24522
  // src/config.ts
24537
- import { join as join15 } from "node:path";
24538
24523
  function loadDefaultWorkspace(environment = process.env) {
24539
24524
  const { MOBIUS_DEFAULT_WORKSPACE: configuredWorkspace } = environment;
24540
- return configuredWorkspace ?? join15(readStateDirectory(environment), "workspace");
24525
+ return configuredWorkspace ?? join14(readStateDirectory(environment), "workspace");
24541
24526
  }
24542
24527
  function createDaemonConfig(connection, agents = [], installableAgents = []) {
24543
24528
  return {
@@ -24553,6 +24538,11 @@ function createDaemonConfig(connection, agents = [], installableAgents = []) {
24553
24538
  }
24554
24539
 
24555
24540
  // src/pairing/pair-local-machine.ts
24541
+ import { randomUUID as randomUUID2 } from "node:crypto";
24542
+ import { mkdir as mkdir3, open as open4, realpath as realpath6, rename as rename3, stat as stat5, writeFile as writeFile2 } from "node:fs/promises";
24543
+ import { hostname as hostname3 } from "node:os";
24544
+ import { basename, join as join15, resolve as resolve3 } from "node:path";
24545
+ import { fetch as fetch2 } from "undici";
24556
24546
  var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
24557
24547
  var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
24558
24548
  var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
@@ -24570,7 +24560,7 @@ var PairingClientError = class extends Error {
24570
24560
  this.name = "PairingClientError";
24571
24561
  }
24572
24562
  };
24573
- function isRecord6(value) {
24563
+ function isRecord7(value) {
24574
24564
  return typeof value === "object" && value !== null && !Array.isArray(value);
24575
24565
  }
24576
24566
  function hasExactKeys(value, expectedKeys) {
@@ -24663,8 +24653,8 @@ async function resolveDefaultWorkspace(path2) {
24663
24653
  const requestedWorkspace = resolve3(path2);
24664
24654
  try {
24665
24655
  await mkdir3(requestedWorkspace, { recursive: true, mode: 448 });
24666
- const defaultWorkspace = await realpath7(requestedWorkspace);
24667
- const metadata = await stat6(defaultWorkspace);
24656
+ const defaultWorkspace = await realpath6(requestedWorkspace);
24657
+ const metadata = await stat5(defaultWorkspace);
24668
24658
  if (!metadata.isDirectory()) {
24669
24659
  throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
24670
24660
  }
@@ -24693,9 +24683,9 @@ async function readJsonResponse(response) {
24693
24683
  }
24694
24684
  }
24695
24685
  function readRelayError(value) {
24696
- if (isRecord6(value)) {
24686
+ if (isRecord7(value)) {
24697
24687
  const error62 = value["error"];
24698
- if (isRecord6(error62)) {
24688
+ if (isRecord7(error62)) {
24699
24689
  const code = error62["code"];
24700
24690
  const message = error62["message"];
24701
24691
  if (typeof code === "string" && typeof message === "string") {
@@ -24706,7 +24696,7 @@ function readRelayError(value) {
24706
24696
  return new PairingClientError("pairing_failed", "The relay could not pair this machine");
24707
24697
  }
24708
24698
  function decodePairingResponse(value, credentialField, expectedKeys) {
24709
- if (!isRecord6(value) || !hasExactKeys(value, expectedKeys)) {
24699
+ if (!isRecord7(value) || !hasExactKeys(value, expectedKeys)) {
24710
24700
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
24711
24701
  }
24712
24702
  const channelId = value["channelId"];
@@ -24736,7 +24726,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
24736
24726
  installableAgents,
24737
24727
  machineName: hostname3(),
24738
24728
  pairingCode: options.code,
24739
- workspaceName: basename2(defaultWorkspace) || "Local workspace"
24729
+ workspaceName: basename(defaultWorkspace) || "Local workspace"
24740
24730
  }),
24741
24731
  dispatcher: environmentProxyDispatcher,
24742
24732
  headers: { "content-type": "application/json" },
@@ -24753,10 +24743,10 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
24753
24743
  return options.pairingId.length > 0 ? decodePairingResponse(value, "runtimeCredential", REDEEM_RESPONSE_KEYS) : decodePairingResponse(value, "daemonToken", CLAIM_RESPONSE_KEYS);
24754
24744
  }
24755
24745
  async function persistConnection(channelId, relayOrigin, runtimeCredential2, defaultWorkspace, environment) {
24756
- const connectionsDirectory = join16(readStateDirectory(environment), "connections");
24746
+ const connectionsDirectory = join15(readStateDirectory(environment), "connections");
24757
24747
  await mkdir3(connectionsDirectory, { mode: 448, recursive: true });
24758
- const connectionPath = join16(connectionsDirectory, `${channelId}.json`);
24759
- const temporaryPath = join16(connectionsDirectory, `.${channelId}.${randomUUID()}.tmp`);
24748
+ const connectionPath = join15(connectionsDirectory, `${channelId}.json`);
24749
+ const temporaryPath = join15(connectionsDirectory, `.${channelId}.${randomUUID2()}.tmp`);
24760
24750
  await writeFile2(
24761
24751
  temporaryPath,
24762
24752
  `${JSON.stringify(
@@ -24776,7 +24766,7 @@ async function persistConnection(channelId, relayOrigin, runtimeCredential2, def
24776
24766
  return connectionPath;
24777
24767
  }
24778
24768
  function decodeSavedConnection(value, expectedChannelId) {
24779
- if (!isRecord6(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
24769
+ if (!isRecord7(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
24780
24770
  throw new PairingClientError("invalid_connection", "The saved connection is invalid");
24781
24771
  }
24782
24772
  const defaultWorkspace = value["defaultWorkspace"];
@@ -24794,7 +24784,7 @@ function decodeSavedConnection(value, expectedChannelId) {
24794
24784
  };
24795
24785
  }
24796
24786
  async function readSavedConnection(channelId, environment) {
24797
- const connectionPath = join16(readStateDirectory(environment), "connections", `${channelId}.json`);
24787
+ const connectionPath = join15(readStateDirectory(environment), "connections", `${channelId}.json`);
24798
24788
  let encoded = "";
24799
24789
  const handle = await open4(connectionPath, "r");
24800
24790
  try {
@@ -24830,7 +24820,7 @@ function buildPairedDaemon(connection, connectionPath, inventory, environment) {
24830
24820
  const relayUrl = mobiusApiUrl(connection.relayOrigin, "/v1/runtimes/connect");
24831
24821
  relayUrl.protocol = relayUrl.protocol === "https:" ? "wss:" : "ws:";
24832
24822
  relayUrl.searchParams.set("token", connection.runtimeCredential);
24833
- const auditDatabasePath = join16(readStateDirectory(environment), "audit", `${connection.channelId}.sqlite`);
24823
+ const auditDatabasePath = join15(readStateDirectory(environment), "audit", `${connection.channelId}.sqlite`);
24834
24824
  return {
24835
24825
  channelUrl: new URL(`/channels/${encodeURIComponent(connection.channelId)}`, connection.relayOrigin).toString(),
24836
24826
  config: createDaemonConfig(
@@ -24880,7 +24870,7 @@ async function pairLocalMachine(arguments_, signal = new AbortController().signa
24880
24870
  }
24881
24871
  async function resumeMobiusRuntime(channelId, signal, environment = process.env) {
24882
24872
  const normalizedChannelId = validatePairingId(channelId);
24883
- const connectionPath = join16(readStateDirectory(environment), "connections", `${normalizedChannelId}.json`);
24873
+ const connectionPath = join15(readStateDirectory(environment), "connections", `${normalizedChannelId}.json`);
24884
24874
  const connection = await readSavedConnection(normalizedChannelId, environment);
24885
24875
  const inventory = await discoverLocalAgentInventory({
24886
24876
  defaultWorkspace: connection.defaultWorkspace,
@@ -24893,753 +24883,15 @@ async function resumeLocalMachine(arguments_, signal = new AbortController().sig
24893
24883
  return await resumeMobiusRuntime(parseChannelArgument(arguments_), signal, process.env);
24894
24884
  }
24895
24885
 
24896
- // src/bots/local-bot-grant-store.ts
24897
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
24898
- import { stat as stat7 } from "node:fs/promises";
24899
- import { DatabaseSync } from "node:sqlite";
24900
- var LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS = 90 * 24 * 60 * 60 * 1e3;
24901
- var identifier2 = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
24902
- var savedApprovalSchema = external_exports.object({
24903
- local_grant_id: identifier2,
24904
- bot_id: identifier2,
24905
- binding_id: identifier2,
24906
- binding_revision: external_exports.number().int().positive(),
24907
- agent_ref: identifier2,
24908
- workspace_ref: external_exports.string().min(1).max(2048),
24909
- revocation_epoch: external_exports.number().int().nonnegative(),
24910
- agent_identity_digest: external_exports.string().regex(/^[a-f0-9]{64}$/),
24911
- workspace_identity_digest: external_exports.string().regex(/^[a-f0-9]{64}$/)
24912
- }).readonly();
24913
- var LocalBotAuthorizationError = class extends Error {
24914
- code;
24915
- constructor(code, message, options = {}) {
24916
- super(message, options);
24917
- this.code = code;
24918
- this.name = "LocalBotAuthorizationError";
24919
- }
24920
- };
24921
- var LocalBotGrant = class {
24922
- agent;
24923
- agentIdentityDigest;
24924
- allowedDeliveryTargetIds;
24925
- behaviorDigest;
24926
- behaviorRevisionId;
24927
- bindingId;
24928
- bindingRevision;
24929
- botId;
24930
- expiresAt;
24931
- localGrantId;
24932
- revocationEpoch;
24933
- workspaceIdentityDigest;
24934
- workspacePath;
24935
- workspaceRef;
24936
- constructor(localGrantId, botId, behaviorRevisionId, behaviorDigest, bindingId, bindingRevision, agent, agentIdentityDigest, workspaceRef, workspacePath, workspaceIdentityDigest, allowedDeliveryTargetIds, expiresAt, revocationEpoch) {
24937
- this.localGrantId = localGrantId;
24938
- this.botId = botId;
24939
- this.behaviorRevisionId = behaviorRevisionId;
24940
- this.behaviorDigest = behaviorDigest;
24941
- this.bindingId = bindingId;
24942
- this.bindingRevision = bindingRevision;
24943
- this.agent = agent;
24944
- this.agentIdentityDigest = agentIdentityDigest;
24945
- this.workspaceRef = workspaceRef;
24946
- this.workspacePath = workspacePath;
24947
- this.workspaceIdentityDigest = workspaceIdentityDigest;
24948
- this.allowedDeliveryTargetIds = Object.freeze([...allowedDeliveryTargetIds]);
24949
- this.expiresAt = expiresAt;
24950
- this.revocationEpoch = revocationEpoch;
24951
- }
24952
- };
24953
- function digest(value) {
24954
- return createHash2("sha256").update(value, "utf8").digest("hex");
24955
- }
24956
- function agentDigest(agent) {
24957
- return digest(
24958
- JSON.stringify({
24959
- adapter: agent.adapterIdentity,
24960
- agent: agent.agentIdentity,
24961
- agentVersion: agent.agentVersion,
24962
- arguments: agent.arguments,
24963
- id: agent.id
24964
- })
24965
- );
24966
- }
24967
- async function workspaceDigest(path2) {
24968
- const metadata = await stat7(path2);
24969
- if (!metadata.isDirectory()) {
24970
- throw new LocalBotAuthorizationError("binding_incompatible", "The Bot workspace is not a directory");
24971
- }
24972
- return digest(
24973
- JSON.stringify({
24974
- changedAtMilliseconds: metadata.ctimeMs,
24975
- device: metadata.dev,
24976
- inode: metadata.ino,
24977
- path: path2
24978
- })
24979
- );
24980
- }
24981
- function exactTargets(left, right) {
24982
- if (left.length !== right.length) {
24983
- return false;
24984
- }
24985
- const expected = [...left].sort();
24986
- const actual = [...right].sort();
24987
- return expected.every((target, index2) => target === actual[index2]);
24988
- }
24989
- function exactSessionConfigurations(left, right) {
24990
- if (left.length !== right.length) {
24991
- return false;
24992
- }
24993
- const expected = new Map(left.map((selection) => [selection.configId, selection]));
24994
- return right.every((selection) => {
24995
- const approved = expected.get(selection.configId);
24996
- return approved !== void 0 && approved.booleanValue === selection.booleanValue && approved.value === selection.value && approved.valueType === selection.valueType;
24997
- });
24998
- }
24999
- function rowString(row, key) {
25000
- const value = Reflect.get(row, key);
25001
- if (typeof value !== "string") {
25002
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
25003
- }
25004
- return value;
25005
- }
25006
- function rowInteger(row, key) {
25007
- const value = Reflect.get(row, key);
25008
- if (typeof value !== "number" || !Number.isSafeInteger(value)) {
25009
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
25010
- }
25011
- return value;
25012
- }
25013
- function parseTargets(encoded) {
25014
- let value;
25015
- try {
25016
- value = JSON.parse(encoded);
25017
- } catch (cause) {
25018
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
25019
- }
25020
- if (!Array.isArray(value) || value.some((target) => typeof target !== "string")) {
25021
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
25022
- }
25023
- return value.filter((target) => typeof target === "string");
25024
- }
25025
- function parseSessionConfigurations(encoded) {
25026
- let value;
25027
- try {
25028
- value = JSON.parse(encoded);
25029
- return decodeSessionConfigurationSelections(value);
25030
- } catch (cause) {
25031
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
25032
- }
25033
- }
25034
- var LocalBotGrantStore = class {
25035
- #database;
25036
- static containsBot = (path2, botId) => {
25037
- const database = new DatabaseSync(path2, { readOnly: true });
25038
- try {
25039
- if (database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_bot_grants'").get() === void 0) {
25040
- return false;
25041
- }
25042
- return database.prepare("SELECT local_grant_id FROM local_bot_grants WHERE bot_id = ? LIMIT 1").get(botId) !== void 0;
25043
- } finally {
25044
- database.close();
25045
- }
25046
- };
25047
- constructor(path2) {
25048
- this.#database = new DatabaseSync(path2);
25049
- this.#database.exec(`
25050
- CREATE TABLE IF NOT EXISTS local_bot_grants (
25051
- local_grant_id TEXT PRIMARY KEY,
25052
- bot_id TEXT NOT NULL,
25053
- behavior_revision_id TEXT NOT NULL,
25054
- behavior_digest TEXT NOT NULL,
25055
- binding_id TEXT NOT NULL UNIQUE,
25056
- binding_revision INTEGER NOT NULL,
25057
- agent_ref TEXT NOT NULL,
25058
- agent_identity_digest TEXT NOT NULL,
25059
- workspace_ref TEXT NOT NULL,
25060
- workspace_path TEXT NOT NULL,
25061
- workspace_identity_digest TEXT NOT NULL,
25062
- allowed_delivery_target_ids_json TEXT NOT NULL,
25063
- unattended_policy_json TEXT NOT NULL,
25064
- created_at INTEGER NOT NULL,
25065
- expires_at INTEGER NOT NULL,
25066
- revocation_epoch INTEGER NOT NULL DEFAULT 0,
25067
- revoked_at INTEGER
25068
- ) STRICT;
25069
- CREATE TABLE IF NOT EXISTS local_bot_binding_resolutions (
25070
- request_id TEXT PRIMARY KEY,
25071
- binding_id TEXT NOT NULL,
25072
- local_grant_id TEXT NOT NULL,
25073
- resolved_at INTEGER NOT NULL,
25074
- result TEXT NOT NULL CHECK (result IN ('approved', 'unavailable')),
25075
- error_code TEXT,
25076
- error_message TEXT
25077
- ) STRICT;
25078
- CREATE TABLE IF NOT EXISTS local_bot_grant_configurations (
25079
- local_grant_id TEXT PRIMARY KEY,
25080
- session_configurations_json TEXT NOT NULL
25081
- ) STRICT;
25082
- `);
25083
- }
25084
- /** Only the local CLI may invoke this explicit approval transition. */
25085
- reapprove = async (botId, catalog, directories, bindingAuthorityId, now, signal) => {
25086
- signal.throwIfAborted();
25087
- if (!identifier2.safeParse(botId).success) {
25088
- throw new LocalBotAuthorizationError("invalid_request", "The Bot ID is invalid");
25089
- }
25090
- const row = this.#database.prepare("SELECT * FROM local_bot_grants WHERE bot_id = ? ORDER BY binding_revision DESC LIMIT 1").get(botId);
25091
- if (row === void 0) {
25092
- throw new LocalBotAuthorizationError("bot_not_found", "This machine has no saved approval for that Bot");
25093
- }
25094
- const parsed = savedApprovalSchema.safeParse(row);
25095
- if (!parsed.success) {
25096
- throw new LocalBotAuthorizationError("local_grant_invalid", "The saved Bot approval is invalid", {
25097
- cause: parsed.error
25098
- });
25099
- }
25100
- const saved = parsed.data;
25101
- const agent = catalog.find(saved.agent_ref);
25102
- if (!agent.capabilities.embeddedContextPrompt) {
25103
- throw new LocalBotAuthorizationError("binding_incompatible", "The local Agent cannot apply Bot context");
25104
- }
25105
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
25106
- revalidateExecutable(agent.adapterIdentity),
25107
- revalidateExecutable(agent.agentIdentity)
25108
- ]);
25109
- signal.throwIfAborted();
25110
- if (!adapterUnchanged || !agentUnchanged) {
25111
- throw new LocalBotAuthorizationError(
25112
- "binding_incompatible",
25113
- "The local Agent executable changed before approval"
25114
- );
25115
- }
25116
- const workspacePath = await directories.resolve(bindingAuthorityId, saved.workspace_ref, signal);
25117
- const workspaceIdentityDigest = await workspaceDigest(workspacePath);
25118
- signal.throwIfAborted();
25119
- this.#database.exec("BEGIN IMMEDIATE");
25120
- try {
25121
- const result = this.#database.prepare(`UPDATE local_bot_grants
25122
- SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
25123
- revoked_at = NULL, expires_at = ?, revocation_epoch = revocation_epoch + 1
25124
- WHERE local_grant_id = ? AND revocation_epoch = ?
25125
- AND agent_identity_digest = ? AND workspace_identity_digest = ?
25126
- AND binding_revision = (SELECT MAX(binding_revision) FROM local_bot_grants WHERE bot_id = ?)`).run(
25127
- agentDigest(agent),
25128
- workspaceIdentityDigest,
25129
- workspacePath,
25130
- now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS,
25131
- saved.local_grant_id,
25132
- saved.revocation_epoch,
25133
- saved.agent_identity_digest,
25134
- saved.workspace_identity_digest,
25135
- botId
25136
- );
25137
- if (result.changes !== 1) {
25138
- throw new LocalBotAuthorizationError(
25139
- "binding_not_approved",
25140
- "The Bot binding changed during approval; run the command again"
25141
- );
25142
- }
25143
- this.#database.prepare(`INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
25144
- VALUES (?, 'bot_binding_locally_reapproved', ?, '', ?)`).run(
25145
- new Date(now).toISOString(),
25146
- saved.binding_id,
25147
- JSON.stringify({ botId, bindingId: saved.binding_id, agentRef: saved.agent_ref })
25148
- );
25149
- this.#database.exec("COMMIT");
25150
- } catch (cause) {
25151
- this.#database.exec("ROLLBACK");
25152
- throw cause;
25153
- }
25154
- return { bindingId: saved.binding_id, workspacePath, agentRef: saved.agent_ref };
25155
- };
25156
- approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
25157
- signal.throwIfAborted();
25158
- const existing = this.#database.prepare(
25159
- `SELECT grants.* FROM local_bot_binding_resolutions AS resolutions
25160
- INNER JOIN local_bot_grants AS grants
25161
- ON grants.local_grant_id = resolutions.local_grant_id
25162
- WHERE resolutions.request_id = ? AND resolutions.binding_id = ?
25163
- AND resolutions.result = 'approved'`
25164
- ).get(request.requestId, request.bindingId);
25165
- if (existing !== void 0) {
25166
- return new BotExecutionBindingApprovedEvent(
25167
- request.requestId,
25168
- request.botId,
25169
- request.behaviorRevisionId,
25170
- request.bindingId,
25171
- request.bindingRevision,
25172
- rowString(existing, "local_grant_id"),
25173
- rowString(existing, "agent_identity_digest"),
25174
- rowString(existing, "workspace_identity_digest")
25175
- );
25176
- }
25177
- const resolved = await this.resolveProposal(request, catalog, directories, bindingAuthorityId, signal);
25178
- const localGrantId = `lbg_${randomUUID2()}`;
25179
- const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
25180
- this.#database.exec("BEGIN IMMEDIATE");
25181
- try {
25182
- this.#database.prepare(
25183
- `INSERT INTO local_bot_grants (
25184
- local_grant_id, bot_id, behavior_revision_id, behavior_digest,
25185
- binding_id, binding_revision, agent_ref,
25186
- agent_identity_digest, workspace_ref, workspace_path,
25187
- workspace_identity_digest, allowed_delivery_target_ids_json,
25188
- unattended_policy_json, created_at, expires_at
25189
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
25190
- ).run(
25191
- localGrantId,
25192
- request.botId,
25193
- request.behaviorRevisionId,
25194
- request.behaviorDigest,
25195
- request.bindingId,
25196
- request.bindingRevision,
25197
- request.agentRef,
25198
- resolved.agentIdentityDigest,
25199
- request.workspaceRef,
25200
- resolved.workspacePath,
25201
- resolved.workspaceIdentityDigest,
25202
- JSON.stringify(request.allowedDeliveryTargets.map((target) => target.deliveryTargetId)),
25203
- JSON.stringify({ localSideEffects: "owner-approval-required" }),
25204
- now,
25205
- expiresAt
25206
- );
25207
- this.#database.prepare(
25208
- `INSERT INTO local_bot_grant_configurations (
25209
- local_grant_id, session_configurations_json
25210
- ) VALUES (?, ?)`
25211
- ).run(localGrantId, JSON.stringify(request.sessionConfigurations));
25212
- this.#database.prepare(
25213
- `INSERT INTO local_bot_binding_resolutions (
25214
- request_id, binding_id, local_grant_id, resolved_at, result
25215
- ) VALUES (?, ?, ?, ?, 'approved')`
25216
- ).run(request.requestId, request.bindingId, localGrantId, now);
25217
- this.#database.exec("COMMIT");
25218
- } catch (cause) {
25219
- this.#database.exec("ROLLBACK");
25220
- throw cause;
25221
- }
25222
- signal.throwIfAborted();
25223
- return new BotExecutionBindingApprovedEvent(
25224
- request.requestId,
25225
- request.botId,
25226
- request.behaviorRevisionId,
25227
- request.bindingId,
25228
- request.bindingRevision,
25229
- localGrantId,
25230
- resolved.agentIdentityDigest,
25231
- resolved.workspaceIdentityDigest
25232
- );
25233
- };
25234
- resolveExecution = async (command, catalog, directories, bindingAuthorityId, now, signal) => {
25235
- signal.throwIfAborted();
25236
- const row = this.#database.prepare(
25237
- `SELECT grants.*, COALESCE(configurations.session_configurations_json, '[]')
25238
- AS session_configurations_json
25239
- FROM local_bot_grants AS grants
25240
- LEFT JOIN local_bot_grant_configurations AS configurations
25241
- ON configurations.local_grant_id = grants.local_grant_id
25242
- WHERE grants.local_grant_id = ? AND grants.bot_id = ?
25243
- AND behavior_revision_id = ? AND behavior_digest = ?
25244
- AND binding_id = ? AND binding_revision = ?
25245
- AND agent_ref = ?
25246
- AND revoked_at IS NULL AND expires_at > ?`
25247
- ).get(
25248
- command.localGrantId,
25249
- command.botId,
25250
- command.behaviorRevisionId,
25251
- command.behaviorDigest,
25252
- command.bindingId,
25253
- command.bindingRevision,
25254
- command.agentId,
25255
- now
25256
- );
25257
- if (row === void 0) {
25258
- throw new LocalBotAuthorizationError(
25259
- "binding_not_approved",
25260
- "The Bot execution binding is not locally approved"
25261
- );
25262
- }
25263
- const approvedTargets = parseTargets(rowString(row, "allowed_delivery_target_ids_json"));
25264
- const requestedTargets = command.allowedDeliveryTargets.map((target) => target.deliveryTargetId);
25265
- if (!exactTargets(approvedTargets, requestedTargets)) {
25266
- throw new LocalBotAuthorizationError(
25267
- "binding_not_approved",
25268
- "The Bot execution target policy changed after local approval"
25269
- );
25270
- }
25271
- const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
25272
- if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
25273
- throw new LocalBotAuthorizationError(
25274
- "binding_not_approved",
25275
- "The Bot Agent configuration changed after local approval"
25276
- );
25277
- }
25278
- const agent = catalog.find(command.agentId);
25279
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
25280
- revalidateExecutable(agent.adapterIdentity),
25281
- revalidateExecutable(agent.agentIdentity)
25282
- ]);
25283
- signal.throwIfAborted();
25284
- const workspaceRef = rowString(row, "workspace_ref");
25285
- const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
25286
- const currentAgentDigest = agentDigest(agent);
25287
- const currentWorkspaceDigest = await workspaceDigest(workspacePath);
25288
- signal.throwIfAborted();
25289
- if (!adapterUnchanged || !agentUnchanged || currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path")) {
25290
- this.revoke(rowString(row, "local_grant_id"), now);
25291
- throw new LocalBotAuthorizationError(
25292
- "binding_not_approved",
25293
- "The Bot execution target changed and requires local approval"
25294
- );
25295
- }
25296
- if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
25297
- throw new LocalBotAuthorizationError(
25298
- "binding_incompatible",
25299
- "The local Agent cannot apply the approved Bot behavior"
25300
- );
25301
- }
25302
- return new LocalBotGrant(
25303
- rowString(row, "local_grant_id"),
25304
- command.botId,
25305
- command.behaviorRevisionId,
25306
- command.behaviorDigest,
25307
- command.bindingId,
25308
- command.bindingRevision,
25309
- agent,
25310
- currentAgentDigest,
25311
- workspaceRef,
25312
- workspacePath,
25313
- currentWorkspaceDigest,
25314
- approvedTargets,
25315
- rowInteger(row, "expires_at"),
25316
- rowInteger(row, "revocation_epoch")
25317
- );
25318
- };
25319
- recordUnavailable = (request, code, message, now) => {
25320
- this.#database.prepare(
25321
- `INSERT OR IGNORE INTO local_bot_binding_resolutions (
25322
- request_id, binding_id, local_grant_id, resolved_at,
25323
- result, error_code, error_message
25324
- ) VALUES (?, ?, '', ?, 'unavailable', ?, ?)`
25325
- ).run(request.requestId, request.bindingId, now, code, message);
25326
- };
25327
- close = () => {
25328
- this.#database.close();
25329
- };
25330
- resolveProposal = async (request, catalog, directories, bindingAuthorityId, signal) => {
25331
- const agent = catalog.find(request.agentRef);
25332
- if (request.requiredCapabilities.includes("embedded-context") && !agent.capabilities.embeddedContextPrompt) {
25333
- throw new LocalBotAuthorizationError(
25334
- "binding_incompatible",
25335
- "The local Agent cannot apply embedded Bot context"
25336
- );
25337
- }
25338
- if (request.requiredCapabilities.some((capability) => capability !== "embedded-context")) {
25339
- throw new LocalBotAuthorizationError(
25340
- "binding_incompatible",
25341
- "The Bot requires an unsupported local Agent capability"
25342
- );
25343
- }
25344
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
25345
- revalidateExecutable(agent.adapterIdentity),
25346
- revalidateExecutable(agent.agentIdentity)
25347
- ]);
25348
- signal.throwIfAborted();
25349
- if (!adapterUnchanged || !agentUnchanged) {
25350
- throw new LocalBotAuthorizationError(
25351
- "binding_incompatible",
25352
- "The local Agent executable changed before approval"
25353
- );
25354
- }
25355
- const workspacePath = await directories.resolve(bindingAuthorityId, request.workspaceRef, signal);
25356
- return {
25357
- agent,
25358
- agentIdentityDigest: agentDigest(agent),
25359
- workspaceIdentityDigest: await workspaceDigest(workspacePath),
25360
- workspacePath
25361
- };
25362
- };
25363
- revoke = (localGrantId, now) => {
25364
- this.#database.prepare(
25365
- `UPDATE local_bot_grants
25366
- SET revoked_at = COALESCE(revoked_at, ?), revocation_epoch = revocation_epoch + 1
25367
- WHERE local_grant_id = ? AND revoked_at IS NULL`
25368
- ).run(now, localGrantId);
25369
- };
25370
- };
25371
-
25372
- // src/bots/bot-approve-command.ts
25373
- var identifier3 = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
25374
- var argumentsSchema = external_exports.union([
25375
- external_exports.tuple([external_exports.literal("--bot"), identifier3]),
25376
- external_exports.tuple([external_exports.literal("--bot"), identifier3, external_exports.literal("--channel"), identifier3])
25377
- ]);
25378
- async function executeBotApproveCommand(arguments_, environment, parent) {
25379
- const parsed = argumentsSchema.safeParse(arguments_);
25380
- if (!parsed.success) {
25381
- throw new LocalBotAuthorizationError(
25382
- "invalid_arguments",
25383
- "Usage: mobius bot approve --bot <bot-id> [--channel <channel-id>]"
25384
- );
25385
- }
25386
- const [, botId, , requestedChannel] = parsed.data;
25387
- const signal = AbortSignal.any([parent, AbortSignal.timeout(3e4)]);
25388
- signal.throwIfAborted();
25389
- try {
25390
- const stateDirectory = await realpath8(readStateDirectory(environment));
25391
- const auditDirectory = await realpath8(join17(stateDirectory, "audit"));
25392
- if (dirname4(auditDirectory) !== stateDirectory) {
25393
- throw new LocalBotAuthorizationError(
25394
- "local_grant_invalid",
25395
- "The local approval directory is outside the Mobius state directory"
25396
- );
25397
- }
25398
- const channels = [];
25399
- for (const entry of await readdir3(auditDirectory, { withFileTypes: true })) {
25400
- signal.throwIfAborted();
25401
- if (!entry.isFile() || !entry.name.endsWith(".sqlite")) {
25402
- continue;
25403
- }
25404
- const channelId2 = entry.name.slice(0, -7);
25405
- if (!identifier3.safeParse(channelId2).success || requestedChannel !== void 0 && requestedChannel !== channelId2) {
25406
- continue;
25407
- }
25408
- const databasePath = await realpath8(join17(auditDirectory, entry.name));
25409
- if (dirname4(databasePath) !== auditDirectory) {
25410
- throw new LocalBotAuthorizationError(
25411
- "local_grant_invalid",
25412
- "The local approval database is outside the Mobius audit directory"
25413
- );
25414
- }
25415
- if (LocalBotGrantStore.containsBot(databasePath, botId)) {
25416
- channels.push(channelId2);
25417
- }
25418
- }
25419
- const channelId = channels[0];
25420
- if (channelId === void 0) {
25421
- throw new LocalBotAuthorizationError(
25422
- "bot_not_found",
25423
- "No saved approval for this Bot was found. Run this command on the machine hosting the Bot."
25424
- );
25425
- }
25426
- if (channels.length !== 1) {
25427
- throw new LocalBotAuthorizationError(
25428
- "binding_ambiguous",
25429
- `This Bot has approvals in multiple local channels. Add --channel with the intended channel: ${channels.join(", ")}`
25430
- );
25431
- }
25432
- const { config: config2 } = await resumeMobiusRuntime(channelId, signal, environment);
25433
- signal.throwIfAborted();
25434
- const grants = new LocalBotGrantStore(config2.auditDatabasePath);
25435
- try {
25436
- const approval = await grants.reapprove(
25437
- botId,
25438
- config2.catalog,
25439
- new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace),
25440
- config2.bindingId,
25441
- Date.now(),
25442
- signal
25443
- );
25444
- return `Approved Bot ${botId}
25445
- Binding: ${approval.bindingId}
25446
- Agent: ${approval.agentRef}
25447
- Workspace: ${approval.workspacePath}
25448
- Keep your daemon running and resend your message in the same Chat conversation.
25449
- `;
25450
- } finally {
25451
- grants.close();
25452
- }
25453
- } catch (cause) {
25454
- parent.throwIfAborted();
25455
- if (signal.aborted) {
25456
- throw new LocalBotAuthorizationError("approval_timeout", "Local Bot approval timed out", { cause });
25457
- }
25458
- if (cause instanceof LocalBotAuthorizationError) {
25459
- throw cause;
25460
- }
25461
- if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
25462
- throw new LocalBotAuthorizationError(
25463
- "bot_not_found",
25464
- "No saved local approval or Runtime connection was found for this Bot",
25465
- { cause }
25466
- );
25467
- }
25468
- throw new LocalBotAuthorizationError(
25469
- "local_approval_failed",
25470
- "Local Bot approval failed. Check the saved Runtime connection and local Agent installation.",
25471
- { cause }
25472
- );
25473
- }
25474
- }
25475
-
25476
- // src/bots/bot-message-command.ts
25477
- import { randomUUID as randomUUID3 } from "node:crypto";
25478
- import { createConnection } from "node:net";
25479
- var BOT_IPC_RESPONSE_LIMIT = 64 * 1024;
25480
- var BOT_IPC_TIMEOUT_MILLISECONDS = 2e4;
25481
- var BotMessageCommandError = class extends Error {
25482
- code;
25483
- constructor(code, message, options = {}) {
25484
- super(message, options);
25485
- this.code = code;
25486
- this.name = "BotMessageCommandError";
25487
- }
25488
- };
25489
- function isRecord7(value) {
25490
- return typeof value === "object" && value !== null && !Array.isArray(value);
25491
- }
25492
- function requiredEnvironment(environment, name) {
25493
- const value = environment[name]?.trim();
25494
- if (value === void 0 || value.length === 0) {
25495
- throw new BotMessageCommandError(
25496
- "execution_context_required",
25497
- "This command is available only inside an active Mobius Bot execution"
25498
- );
25499
- }
25500
- return value;
25501
- }
25502
- function option(arguments_, name) {
25503
- const index2 = arguments_.indexOf(name);
25504
- if (index2 < 0 || index2 + 1 >= arguments_.length || arguments_[index2 + 1]?.startsWith("--") === true) {
25505
- throw new BotMessageCommandError(
25506
- "invalid_request",
25507
- "Usage: mobius bot message send --target <current|alias> --text <message>"
25508
- );
25509
- }
25510
- const value = arguments_[index2 + 1];
25511
- if (value === void 0) {
25512
- throw new BotMessageCommandError("invalid_request", "The Bot message option is missing");
25513
- }
25514
- return value;
25515
- }
25516
- function validateArguments(arguments_) {
25517
- if (arguments_.length !== 4) {
25518
- throw new BotMessageCommandError(
25519
- "invalid_request",
25520
- "Usage: mobius bot message send --target <current|alias> --text <message>"
25521
- );
25522
- }
25523
- const names = [arguments_[0], arguments_[2]];
25524
- if (!names.includes("--target") || !names.includes("--text") || names[0] === names[1]) {
25525
- throw new BotMessageCommandError(
25526
- "invalid_request",
25527
- "Usage: mobius bot message send --target <current|alias> --text <message>"
25528
- );
25529
- }
25530
- }
25531
- function decodeResponse(encoded) {
25532
- let value;
25533
- try {
25534
- value = JSON.parse(encoded);
25535
- } catch (cause) {
25536
- throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data", {
25537
- cause
25538
- });
25539
- }
25540
- if (!isRecord7(value) || typeof value["ok"] !== "boolean") {
25541
- throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data");
25542
- }
25543
- if (value["ok"] === true && typeof value["outboundMessageId"] === "string") {
25544
- return value["outboundMessageId"];
25545
- }
25546
- const error62 = value["error"];
25547
- if (value["ok"] === false && isRecord7(error62) && typeof error62["code"] === "string" && typeof error62["message"] === "string") {
25548
- throw new BotMessageCommandError(error62["code"], error62["message"]);
25549
- }
25550
- throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data");
25551
- }
25552
- async function requestLocalBotService(socketPath, payload, signal) {
25553
- signal.throwIfAborted();
25554
- return await new Promise((resolve5, reject) => {
25555
- const socket = createConnection(socketPath);
25556
- const chunks = [];
25557
- let length = 0;
25558
- let finished = false;
25559
- const finish = () => {
25560
- socket.removeAllListeners();
25561
- socket.destroy();
25562
- };
25563
- const fail = (error62) => {
25564
- if (finished) {
25565
- return;
25566
- }
25567
- finished = true;
25568
- finish();
25569
- if (error62 instanceof BotMessageCommandError) {
25570
- reject(error62);
25571
- return;
25572
- }
25573
- reject(
25574
- new BotMessageCommandError(
25575
- "execution_context_required",
25576
- "The active Mobius Bot execution is unavailable",
25577
- { cause: error62 }
25578
- )
25579
- );
25580
- };
25581
- const abort = () => fail(signal.reason);
25582
- socket.setTimeout(BOT_IPC_TIMEOUT_MILLISECONDS, () => {
25583
- fail(new BotMessageCommandError("bot_service_unavailable", "The local Bot service timed out"));
25584
- });
25585
- socket.once("error", fail);
25586
- socket.once("connect", () => socket.end(`${payload}
25587
- `));
25588
- socket.on("data", (chunk) => {
25589
- length += chunk.byteLength;
25590
- if (length > BOT_IPC_RESPONSE_LIMIT) {
25591
- fail(new BotMessageCommandError("bot_service_unavailable", "The local Bot response is too large"));
25592
- return;
25593
- }
25594
- chunks.push(chunk);
25595
- });
25596
- socket.once("end", () => {
25597
- if (finished) {
25598
- return;
25599
- }
25600
- finished = true;
25601
- signal.removeEventListener("abort", abort);
25602
- try {
25603
- resolve5(decodeResponse(Buffer.concat(chunks).toString("utf8")));
25604
- } catch (error62) {
25605
- reject(error62);
25606
- } finally {
25607
- finish();
25608
- }
25609
- });
25610
- signal.addEventListener("abort", abort, { once: true });
25611
- });
25612
- }
25613
- async function executeBotMessageCommand(arguments_, environment, signal) {
25614
- validateArguments(arguments_);
25615
- const contextHandle = requiredEnvironment(environment, "MOBIUS_BOT_CONTEXT");
25616
- const socketPath = requiredEnvironment(environment, "MOBIUS_BOT_SOCKET");
25617
- const target = option(arguments_, "--target");
25618
- const text3 = option(arguments_, "--text");
25619
- if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(target) || text3.trim().length === 0 || text3.length > 1e4) {
25620
- throw new BotMessageCommandError("invalid_request", "The Bot outbound message is invalid");
25621
- }
25622
- return await requestLocalBotService(
25623
- socketPath,
25624
- JSON.stringify({
25625
- contextHandle,
25626
- idempotencyKey: `cli_${randomUUID3()}`,
25627
- target,
25628
- text: text3
25629
- }),
25630
- signal
25631
- );
25632
- }
25633
-
25634
24886
  // src/audit/audit-store.ts
25635
24887
  import { mkdirSync } from "node:fs";
25636
- import { dirname as dirname5 } from "node:path";
25637
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
24888
+ import { dirname as dirname3 } from "node:path";
24889
+ import { DatabaseSync } from "node:sqlite";
25638
24890
  var AuditStore = class {
25639
24891
  database;
25640
24892
  constructor(path2) {
25641
- mkdirSync(dirname5(path2), { recursive: true });
25642
- this.database = new DatabaseSync2(path2);
24893
+ mkdirSync(dirname3(path2), { recursive: true });
24894
+ this.database = new DatabaseSync(path2);
25643
24895
  this.database.exec(`
25644
24896
  CREATE TABLE IF NOT EXISTS audit_events (
25645
24897
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -25681,7 +24933,7 @@ var AuditStore = class {
25681
24933
 
25682
24934
  // src/run-daemon.ts
25683
24935
  import { randomUUID as randomUUID6 } from "node:crypto";
25684
- import { basename as basename5, join as join18 } from "node:path";
24936
+ import { basename as basename5, join as join17 } from "node:path";
25685
24937
  import { styleText } from "node:util";
25686
24938
  import { fetch as fetch7, WebSocket as WebSocket2 } from "undici";
25687
24939
 
@@ -25695,8 +24947,8 @@ import {
25695
24947
  } from "@agentclientprotocol/sdk";
25696
24948
 
25697
24949
  // src/authorization/local-raster.ts
25698
- import { readFile as readFile2, realpath as realpath9, stat as stat8 } from "node:fs/promises";
25699
- import { basename as basename3, isAbsolute as isAbsolute9, normalize as normalize3, relative as relative5, sep as sep4 } from "node:path";
24950
+ import { readFile as readFile2, realpath as realpath7, stat as stat6 } from "node:fs/promises";
24951
+ import { basename as basename2, isAbsolute as isAbsolute8, normalize as normalize2, relative as relative4, sep as sep4 } from "node:path";
25700
24952
  import { fileURLToPath } from "node:url";
25701
24953
  var MAX_LOCAL_RASTER_BYTES = 3e6;
25702
24954
  var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
@@ -25752,21 +25004,21 @@ function readInlineRaster(data, name = "Image") {
25752
25004
  if (mimeType === null) {
25753
25005
  return null;
25754
25006
  }
25755
- return new LocalRasterImage(basename3(name) || "Image", mimeType, bytes);
25007
+ return new LocalRasterImage(basename2(name) || "Image", mimeType, bytes);
25756
25008
  }
25757
25009
  function isInsideRoot(root, target) {
25758
- const relation = relative5(root, target);
25759
- return relation !== ".." && !relation.startsWith(`..${sep4}`) && !isAbsolute9(relation);
25010
+ const relation = relative4(root, target);
25011
+ return relation !== ".." && !relation.startsWith(`..${sep4}`) && !isAbsolute8(relation);
25760
25012
  }
25761
25013
  async function resolveCanonicalPath(requested, signal) {
25762
25014
  signal.throwIfAborted();
25763
- if (!isAbsolute9(requested) || requested.includes("\0") || normalize3(requested) !== requested) {
25015
+ if (!isAbsolute8(requested) || requested.includes("\0") || normalize2(requested) !== requested) {
25764
25016
  return null;
25765
25017
  }
25766
25018
  try {
25767
- const target = await realpath9(requested);
25019
+ const target = await realpath7(requested);
25768
25020
  signal.throwIfAborted();
25769
- if (!isAbsolute9(target) || normalize3(target) !== target) {
25021
+ if (!isAbsolute8(target) || normalize2(target) !== target) {
25770
25022
  return null;
25771
25023
  }
25772
25024
  return target;
@@ -25812,7 +25064,7 @@ async function readAuthorizedRaster(uri, roots, signal) {
25812
25064
  if (target === null) {
25813
25065
  return null;
25814
25066
  }
25815
- const targetMetadata = await stat8(target);
25067
+ const targetMetadata = await stat6(target);
25816
25068
  signal.throwIfAborted();
25817
25069
  if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
25818
25070
  return null;
@@ -25823,7 +25075,7 @@ async function readAuthorizedRaster(uri, roots, signal) {
25823
25075
  if (directory === null) {
25824
25076
  continue;
25825
25077
  }
25826
- const metadata = await stat8(directory);
25078
+ const metadata = await stat6(directory);
25827
25079
  signal.throwIfAborted();
25828
25080
  if (metadata.isDirectory()) {
25829
25081
  authorizedRoots.push(directory);
@@ -25841,7 +25093,7 @@ async function readAuthorizedRaster(uri, roots, signal) {
25841
25093
  if (mimeType === null) {
25842
25094
  return null;
25843
25095
  }
25844
- return new LocalRasterImage(basename3(target) || "Image", mimeType, bytes);
25096
+ return new LocalRasterImage(basename2(target) || "Image", mimeType, bytes);
25845
25097
  }
25846
25098
 
25847
25099
  // src/infra/operation-metrics.ts
@@ -30445,7 +29697,7 @@ var titleBefore = {
30445
29697
  };
30446
29698
  function tokenizeDefinition(effects, ok2, nok) {
30447
29699
  const self = this;
30448
- let identifier4;
29700
+ let identifier2;
30449
29701
  return start;
30450
29702
  function start(code) {
30451
29703
  effects.enter("definition");
@@ -30464,7 +29716,7 @@ function tokenizeDefinition(effects, ok2, nok) {
30464
29716
  )(code);
30465
29717
  }
30466
29718
  function labelAfter(code) {
30467
- identifier4 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
29719
+ identifier2 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
30468
29720
  if (code === 58) {
30469
29721
  effects.enter("definitionMarker");
30470
29722
  effects.consume(code);
@@ -30498,7 +29750,7 @@ function tokenizeDefinition(effects, ok2, nok) {
30498
29750
  function afterWhitespace(code) {
30499
29751
  if (code === null || markdownLineEnding(code)) {
30500
29752
  effects.exit("definition");
30501
- self.parser.defined.push(identifier4);
29753
+ self.parser.defined.push(identifier2);
30502
29754
  return ok2(code);
30503
29755
  }
30504
29756
  return nok(code);
@@ -34130,8 +33382,8 @@ var AcpHistoryReplay = class {
34130
33382
 
34131
33383
  // src/acp/session-store.ts
34132
33384
  import { mkdirSync as mkdirSync2 } from "node:fs";
34133
- import { dirname as dirname6 } from "node:path";
34134
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
33385
+ import { dirname as dirname4 } from "node:path";
33386
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
34135
33387
  var AcpStoredSession = class {
34136
33388
  additionalDirectories;
34137
33389
  agentId;
@@ -34233,8 +33485,8 @@ var MemoryAcpSessionStore = class {
34233
33485
  var SqliteAcpSessionStore = class {
34234
33486
  #database;
34235
33487
  constructor(path2) {
34236
- mkdirSync2(dirname6(path2), { recursive: true });
34237
- this.#database = new DatabaseSync3(path2);
33488
+ mkdirSync2(dirname4(path2), { recursive: true });
33489
+ this.#database = new DatabaseSync2(path2);
34238
33490
  this.#database.exec(`
34239
33491
  CREATE TABLE IF NOT EXISTS acp_deleted_sessions (session_id TEXT PRIMARY KEY) STRICT;
34240
33492
  CREATE TABLE IF NOT EXISTS acp_sessions (
@@ -34333,6 +33585,7 @@ var SqliteAcpSessionStore = class {
34333
33585
 
34334
33586
  // src/acp/session-manager.ts
34335
33587
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
33588
+ var MAX_ACP_PROCESSES = 10;
34336
33589
  var MAX_PRE_SESSION_UPDATES = 100;
34337
33590
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
34338
33591
  var SESSION_CONTROL_COMMAND_ID = "session-control";
@@ -34391,6 +33644,91 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
34391
33644
  this.name = "RetryableAcpInitializationError";
34392
33645
  }
34393
33646
  };
33647
+ var AcpProcessCapacityLease = class {
33648
+ #releaseCapacity;
33649
+ #released = false;
33650
+ constructor(releaseCapacity) {
33651
+ this.#releaseCapacity = releaseCapacity;
33652
+ }
33653
+ release = () => {
33654
+ if (this.#released) {
33655
+ return;
33656
+ }
33657
+ this.#released = true;
33658
+ this.#releaseCapacity();
33659
+ };
33660
+ };
33661
+ var AcpProcessCapacityWaiter = class {
33662
+ completion = Promise.withResolvers();
33663
+ signal;
33664
+ constructor(signal) {
33665
+ this.signal = signal;
33666
+ }
33667
+ cancel = () => {
33668
+ try {
33669
+ this.signal.throwIfAborted();
33670
+ } catch (error62) {
33671
+ this.completion.reject(error62);
33672
+ }
33673
+ };
33674
+ };
33675
+ var AcpProcessCapacityLock = class {
33676
+ #locked = false;
33677
+ #waiters = [];
33678
+ acquire = async (signal) => {
33679
+ signal.throwIfAborted();
33680
+ if (!this.#locked) {
33681
+ this.#locked = true;
33682
+ return new AcpProcessCapacityLease(this.#release);
33683
+ }
33684
+ const waiter = new AcpProcessCapacityWaiter(signal);
33685
+ this.#waiters.push(waiter);
33686
+ signal.addEventListener("abort", waiter.cancel, { once: true });
33687
+ if (signal.aborted) {
33688
+ waiter.cancel();
33689
+ }
33690
+ try {
33691
+ return await waiter.completion.promise;
33692
+ } finally {
33693
+ signal.removeEventListener("abort", waiter.cancel);
33694
+ const index2 = this.#waiters.indexOf(waiter);
33695
+ if (index2 >= 0) {
33696
+ this.#waiters.splice(index2, 1);
33697
+ }
33698
+ }
33699
+ };
33700
+ #release = () => {
33701
+ while (this.#waiters.length > 0) {
33702
+ const waiter = this.#waiters.shift();
33703
+ if (waiter === void 0 || waiter.signal.aborted) {
33704
+ continue;
33705
+ }
33706
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
33707
+ return;
33708
+ }
33709
+ this.#locked = false;
33710
+ };
33711
+ };
33712
+ async function waitForAcpProcessCapacity(completion, signal) {
33713
+ signal.throwIfAborted();
33714
+ const cancelled = Promise.withResolvers();
33715
+ const cancel = () => {
33716
+ try {
33717
+ signal.throwIfAborted();
33718
+ } catch (error62) {
33719
+ cancelled.reject(error62);
33720
+ }
33721
+ };
33722
+ signal.addEventListener("abort", cancel, { once: true });
33723
+ if (signal.aborted) {
33724
+ cancel();
33725
+ }
33726
+ try {
33727
+ await Promise.race([completion, cancelled.promise]);
33728
+ } finally {
33729
+ signal.removeEventListener("abort", cancel);
33730
+ }
33731
+ }
34394
33732
  function readableWebStream(input2) {
34395
33733
  let streamOpen = true;
34396
33734
  return new ReadableStream({
@@ -35878,20 +35216,23 @@ var AcpProcessSession = class _AcpProcessSession {
35878
35216
  }
35879
35217
  };
35880
35218
  close = async () => {
35881
- await this.cancelPendingInteractions();
35882
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
35883
- try {
35884
- await this.#connection.agent.request(
35885
- methods6.agent.session.close,
35886
- { sessionId: this.#nativeSessionId },
35887
- {
35888
- cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
35889
- }
35890
- );
35891
- } catch {
35219
+ try {
35220
+ await this.cancelPendingInteractions();
35221
+ if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
35222
+ try {
35223
+ await this.#connection.agent.request(
35224
+ methods6.agent.session.close,
35225
+ { sessionId: this.#nativeSessionId },
35226
+ {
35227
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
35228
+ }
35229
+ );
35230
+ } catch {
35231
+ }
35892
35232
  }
35233
+ } finally {
35234
+ await this.closeProcess();
35893
35235
  }
35894
- await this.closeProcess();
35895
35236
  };
35896
35237
  closeProcess = async (capturedProcesses = []) => {
35897
35238
  try {
@@ -35998,6 +35339,31 @@ var AcpProcessSession = class _AcpProcessSession {
35998
35339
  }
35999
35340
  };
36000
35341
  };
35342
+ var AcpProcessEvictionCandidate = class {
35343
+ };
35344
+ var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
35345
+ };
35346
+ var FoundAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
35347
+ runtime;
35348
+ constructor(runtime) {
35349
+ super();
35350
+ this.runtime = runtime;
35351
+ }
35352
+ };
35353
+ var FoundAcpSessionProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
35354
+ sessionId;
35355
+ constructor(sessionId, runtime) {
35356
+ super(runtime);
35357
+ this.sessionId = sessionId;
35358
+ }
35359
+ };
35360
+ var FoundAcpNativeBrowserProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
35361
+ sessionId;
35362
+ constructor(sessionId, runtime) {
35363
+ super(runtime);
35364
+ this.sessionId = sessionId;
35365
+ }
35366
+ };
36001
35367
  var AcpSessionManager = class {
36002
35368
  #activeCommandIds = /* @__PURE__ */ new Map();
36003
35369
  #agentSettingsObserver = new NullAcpSessionObserver();
@@ -36006,10 +35372,18 @@ var AcpSessionManager = class {
36006
35372
  #nativeBrowserPreparing = /* @__PURE__ */ new Map();
36007
35373
  #nativeBrowserSessions = /* @__PURE__ */ new Map();
36008
35374
  #nativeBrowserStore = new MemoryAcpSessionStore();
35375
+ #nativeBrowserUseCounts = /* @__PURE__ */ new Map();
36009
35376
  #activeSessionIds = /* @__PURE__ */ new Set();
36010
35377
  #cancellationRequests = /* @__PURE__ */ new Map();
36011
35378
  #preparing = /* @__PURE__ */ new Map();
35379
+ #processCapacityChanged = Promise.withResolvers();
35380
+ #processCapacityLock = new AcpProcessCapacityLock();
35381
+ #retainedProcesses = /* @__PURE__ */ new Map();
35382
+ #retiringProcessCount = 0;
35383
+ #sessionUseCounts = /* @__PURE__ */ new Map();
36012
35384
  #sessions = /* @__PURE__ */ new Map();
35385
+ #startingProcessCount = 0;
35386
+ #transientProcessCount = 0;
36013
35387
  #store;
36014
35388
  #observer;
36015
35389
  constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore()) {
@@ -36019,18 +35393,230 @@ var AcpSessionManager = class {
36019
35393
  setObserver = (observer) => {
36020
35394
  this.#observer = observer;
36021
35395
  };
35396
+ #notifyProcessCapacityChanged() {
35397
+ const changed = this.#processCapacityChanged;
35398
+ this.#processCapacityChanged = Promise.withResolvers();
35399
+ changed.resolve();
35400
+ }
35401
+ #touchSession(sessionId) {
35402
+ const runtime = this.#sessions.get(sessionId);
35403
+ if (runtime === void 0) {
35404
+ return;
35405
+ }
35406
+ this.#touchProcess(runtime);
35407
+ }
35408
+ #touchExpectedSession(sessionId, expected) {
35409
+ if (this.#sessions.get(sessionId) !== expected) {
35410
+ return;
35411
+ }
35412
+ this.#touchProcess(expected);
35413
+ }
35414
+ #touchNativeBrowserSession(sessionId) {
35415
+ const runtime = this.#nativeBrowserSessions.get(sessionId);
35416
+ if (runtime === void 0) {
35417
+ return;
35418
+ }
35419
+ this.#touchProcess(runtime);
35420
+ }
35421
+ #touchExpectedNativeBrowserSession(sessionId, expected) {
35422
+ if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
35423
+ return;
35424
+ }
35425
+ this.#touchProcess(expected);
35426
+ }
35427
+ #touchProcess(runtime) {
35428
+ const retained = this.#retainedProcesses.get(runtime);
35429
+ if (retained === void 0) {
35430
+ return;
35431
+ }
35432
+ this.#retainedProcesses.delete(runtime);
35433
+ this.#retainedProcesses.set(runtime, retained);
35434
+ }
35435
+ #beginSessionUse(sessionId) {
35436
+ this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
35437
+ this.#touchSession(sessionId);
35438
+ }
35439
+ #endSessionUse(sessionId) {
35440
+ const count = this.#sessionUseCounts.get(sessionId) ?? 0;
35441
+ if (count <= 1) {
35442
+ this.#sessionUseCounts.delete(sessionId);
35443
+ } else {
35444
+ this.#sessionUseCounts.set(sessionId, count - 1);
35445
+ }
35446
+ this.#touchSession(sessionId);
35447
+ this.#notifyProcessCapacityChanged();
35448
+ }
35449
+ #beginNativeBrowserUse(sessionId) {
35450
+ this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
35451
+ this.#touchNativeBrowserSession(sessionId);
35452
+ }
35453
+ #endNativeBrowserUse(sessionId) {
35454
+ const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
35455
+ if (count <= 1) {
35456
+ this.#nativeBrowserUseCounts.delete(sessionId);
35457
+ } else {
35458
+ this.#nativeBrowserUseCounts.set(sessionId, count - 1);
35459
+ }
35460
+ this.#touchNativeBrowserSession(sessionId);
35461
+ this.#notifyProcessCapacityChanged();
35462
+ }
35463
+ #isNativeSessionOperationActive(sessionId) {
35464
+ const stored = this.#store.read(sessionId);
35465
+ return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
35466
+ }
35467
+ #leastRecentlyUsedEvictionCandidate() {
35468
+ for (const candidate of this.#retainedProcesses.values()) {
35469
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
35470
+ 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)) {
35471
+ continue;
35472
+ }
35473
+ return candidate;
35474
+ }
35475
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate && !this.#nativeBrowserPreparing.has(candidate.sessionId) && (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
35476
+ return candidate;
35477
+ }
35478
+ }
35479
+ return new MissingAcpProcessEvictionCandidate();
35480
+ }
35481
+ #ownedProcessCount() {
35482
+ return this.#retainedProcesses.size + this.#startingProcessCount + this.#transientProcessCount + this.#retiringProcessCount;
35483
+ }
35484
+ async #retireProcess(runtime, retained, close) {
35485
+ if (retained) {
35486
+ this.#retainedProcesses.delete(runtime);
35487
+ this.#retiringProcessCount += 1;
35488
+ }
35489
+ try {
35490
+ await close();
35491
+ } finally {
35492
+ if (retained) {
35493
+ this.#retiringProcessCount -= 1;
35494
+ this.#notifyProcessCapacityChanged();
35495
+ }
35496
+ }
35497
+ }
35498
+ async #retireSessionProcess(sessionId, runtime, close) {
35499
+ const retained = this.#sessions.get(sessionId) === runtime;
35500
+ if (retained) {
35501
+ this.#sessions.delete(sessionId);
35502
+ }
35503
+ await this.#retireProcess(runtime, retained, close);
35504
+ }
35505
+ async #retireNativeBrowserProcess(sessionId, runtime, close) {
35506
+ const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
35507
+ if (retained) {
35508
+ this.#nativeBrowserSessions.delete(sessionId);
35509
+ this.#nativeBrowserStore.remove(sessionId);
35510
+ }
35511
+ await this.#retireProcess(runtime, retained, close);
35512
+ }
35513
+ async #reserveProcessCapacity(signal) {
35514
+ const lease = await this.#processCapacityLock.acquire(signal);
35515
+ try {
35516
+ for (; ; ) {
35517
+ signal.throwIfAborted();
35518
+ if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
35519
+ this.#startingProcessCount += 1;
35520
+ return;
35521
+ }
35522
+ const candidate = this.#leastRecentlyUsedEvictionCandidate();
35523
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
35524
+ await this.#retireSessionProcess(
35525
+ candidate.sessionId,
35526
+ candidate.runtime,
35527
+ async () => await candidate.runtime.close()
35528
+ );
35529
+ continue;
35530
+ }
35531
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
35532
+ await this.#retireNativeBrowserProcess(
35533
+ candidate.sessionId,
35534
+ candidate.runtime,
35535
+ async () => await candidate.runtime.close()
35536
+ );
35537
+ continue;
35538
+ }
35539
+ const changed = this.#processCapacityChanged.promise;
35540
+ await waitForAcpProcessCapacity(changed, signal);
35541
+ }
35542
+ } finally {
35543
+ lease.release();
35544
+ }
35545
+ }
35546
+ async #startRetainedSessionProcess(options, start) {
35547
+ await this.#reserveProcessCapacity(options.signal);
35548
+ try {
35549
+ const runtime = await start();
35550
+ this.#startingProcessCount -= 1;
35551
+ this.#sessions.set(options.sessionId, runtime);
35552
+ this.#retainedProcesses.set(
35553
+ runtime,
35554
+ new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime)
35555
+ );
35556
+ this.#notifyProcessCapacityChanged();
35557
+ return runtime;
35558
+ } catch (error62) {
35559
+ this.#startingProcessCount -= 1;
35560
+ this.#notifyProcessCapacityChanged();
35561
+ throw error62;
35562
+ }
35563
+ }
35564
+ async #startRetainedNativeBrowserProcess(options, start) {
35565
+ await this.#reserveProcessCapacity(options.signal);
35566
+ try {
35567
+ const runtime = await start();
35568
+ this.#startingProcessCount -= 1;
35569
+ this.#nativeBrowserSessions.set(options.sessionId, runtime);
35570
+ this.#retainedProcesses.set(
35571
+ runtime,
35572
+ new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime)
35573
+ );
35574
+ this.#notifyProcessCapacityChanged();
35575
+ return runtime;
35576
+ } catch (error62) {
35577
+ this.#startingProcessCount -= 1;
35578
+ this.#notifyProcessCapacityChanged();
35579
+ throw error62;
35580
+ }
35581
+ }
35582
+ async #runWithTransientProcess(signal, start, operation, close) {
35583
+ await this.#reserveProcessCapacity(signal);
35584
+ let runtime;
35585
+ try {
35586
+ runtime = await start();
35587
+ } catch (error62) {
35588
+ this.#startingProcessCount -= 1;
35589
+ this.#notifyProcessCapacityChanged();
35590
+ throw error62;
35591
+ }
35592
+ this.#startingProcessCount -= 1;
35593
+ this.#transientProcessCount += 1;
35594
+ this.#notifyProcessCapacityChanged();
35595
+ try {
35596
+ return await operation(runtime);
35597
+ } finally {
35598
+ try {
35599
+ await close(runtime);
35600
+ } finally {
35601
+ this.#transientProcessCount -= 1;
35602
+ this.#notifyProcessCapacityChanged();
35603
+ }
35604
+ }
35605
+ }
36022
35606
  async #startNativeBrowserPreparation(options) {
36023
35607
  const operation = (async () => {
36024
35608
  try {
36025
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35609
+ return await this.#startRetainedNativeBrowserProcess(
36026
35610
  options,
36027
- () => this.#nativeBrowserObserver,
36028
- this.#nativeBrowserStore
35611
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35612
+ options,
35613
+ () => this.#nativeBrowserObserver,
35614
+ this.#nativeBrowserStore
35615
+ )
36029
35616
  );
36030
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
36031
- return runtime;
36032
35617
  } finally {
36033
35618
  this.#nativeBrowserPreparing.delete(options.sessionId);
35619
+ this.#notifyProcessCapacityChanged();
36034
35620
  }
36035
35621
  })();
36036
35622
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -36039,18 +35625,18 @@ var AcpSessionManager = class {
36039
35625
  async #replaceNativeBrowserPreparation(existing, options) {
36040
35626
  const operation = (async () => {
36041
35627
  try {
36042
- this.#nativeBrowserSessions.delete(options.sessionId);
36043
- await existing.close();
36044
- this.#nativeBrowserStore.remove(options.sessionId);
36045
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35628
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
35629
+ return await this.#startRetainedNativeBrowserProcess(
36046
35630
  options,
36047
- () => this.#nativeBrowserObserver,
36048
- this.#nativeBrowserStore
35631
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35632
+ options,
35633
+ () => this.#nativeBrowserObserver,
35634
+ this.#nativeBrowserStore
35635
+ )
36049
35636
  );
36050
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
36051
- return runtime;
36052
35637
  } finally {
36053
35638
  this.#nativeBrowserPreparing.delete(options.sessionId);
35639
+ this.#notifyProcessCapacityChanged();
36054
35640
  }
36055
35641
  })();
36056
35642
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -36059,11 +35645,13 @@ var AcpSessionManager = class {
36059
35645
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
36060
35646
  const operation = (async () => {
36061
35647
  try {
36062
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
36063
- this.#sessions.set(options.sessionId, runtime);
36064
- return runtime;
35648
+ return await this.#startRetainedSessionProcess(
35649
+ options,
35650
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35651
+ );
36065
35652
  } finally {
36066
35653
  this.#preparing.delete(options.sessionId);
35654
+ this.#notifyProcessCapacityChanged();
36067
35655
  }
36068
35656
  })();
36069
35657
  this.#preparing.set(options.sessionId, operation);
@@ -36072,17 +35660,19 @@ var AcpSessionManager = class {
36072
35660
  async #startSessionForkAtTurnPreparation(options, sourceNativeSessionId, forkPoint) {
36073
35661
  const operation = (async () => {
36074
35662
  try {
36075
- const runtime = await AcpProcessSession.startSessionForkAtTurn(
35663
+ return await this.#startRetainedSessionProcess(
36076
35664
  options,
36077
- sourceNativeSessionId,
36078
- forkPoint,
36079
- () => this.#observer,
36080
- this.#store
35665
+ async () => await AcpProcessSession.startSessionForkAtTurn(
35666
+ options,
35667
+ sourceNativeSessionId,
35668
+ forkPoint,
35669
+ () => this.#observer,
35670
+ this.#store
35671
+ )
36081
35672
  );
36082
- this.#sessions.set(options.sessionId, runtime);
36083
- return runtime;
36084
35673
  } finally {
36085
35674
  this.#preparing.delete(options.sessionId);
35675
+ this.#notifyProcessCapacityChanged();
36086
35676
  }
36087
35677
  })();
36088
35678
  this.#preparing.set(options.sessionId, operation);
@@ -36091,14 +35681,19 @@ var AcpSessionManager = class {
36091
35681
  async #replacePreparation(existing, options, metrics) {
36092
35682
  const operation = (async () => {
36093
35683
  try {
36094
- this.#sessions.delete(options.sessionId);
36095
- await metrics.measure("runtime-replacement-close", async () => await existing.close());
35684
+ await this.#retireSessionProcess(
35685
+ options.sessionId,
35686
+ existing,
35687
+ async () => await metrics.measure("runtime-replacement-close", async () => await existing.close())
35688
+ );
36096
35689
  this.#store.remove(options.sessionId);
36097
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
36098
- this.#sessions.set(options.sessionId, runtime);
36099
- return runtime;
35690
+ return await this.#startRetainedSessionProcess(
35691
+ options,
35692
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35693
+ );
36100
35694
  } finally {
36101
35695
  this.#preparing.delete(options.sessionId);
35696
+ this.#notifyProcessCapacityChanged();
36102
35697
  }
36103
35698
  })();
36104
35699
  this.#preparing.set(options.sessionId, operation);
@@ -36108,10 +35703,12 @@ var AcpSessionManager = class {
36108
35703
  const desiredConfigOptions = existing.prepared().configOptions;
36109
35704
  const operation = (async () => {
36110
35705
  try {
36111
- this.#sessions.delete(options.sessionId);
36112
- await existing.close();
35706
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
36113
35707
  this.#store.remove(options.sessionId);
36114
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
35708
+ const runtime = await this.#startRetainedSessionProcess(
35709
+ options,
35710
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
35711
+ );
36115
35712
  try {
36116
35713
  for (const desired of desiredConfigOptions) {
36117
35714
  const current = runtime.prepared().configOptions.find((option2) => option2.id === desired.id);
@@ -36143,14 +35740,14 @@ var AcpSessionManager = class {
36143
35740
  }
36144
35741
  }
36145
35742
  } catch (error62) {
36146
- await runtime.close();
35743
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
36147
35744
  this.#store.remove(options.sessionId);
36148
35745
  throw error62;
36149
35746
  }
36150
- this.#sessions.set(options.sessionId, runtime);
36151
35747
  return runtime;
36152
35748
  } finally {
36153
35749
  this.#preparing.delete(options.sessionId);
35750
+ this.#notifyProcessCapacityChanged();
36154
35751
  }
36155
35752
  })();
36156
35753
  this.#preparing.set(options.sessionId, operation);
@@ -36172,6 +35769,7 @@ var AcpSessionManager = class {
36172
35769
  if (pending !== void 0) {
36173
35770
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
36174
35771
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35772
+ this.#touchExpectedSession(options.sessionId, runtime2);
36175
35773
  return runtime2.prepared();
36176
35774
  }
36177
35775
  return await this.prepareSession(options, metrics);
@@ -36179,6 +35777,7 @@ var AcpSessionManager = class {
36179
35777
  const existing = this.#sessions.get(options.sessionId);
36180
35778
  if (existing !== void 0) {
36181
35779
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35780
+ this.#touchExpectedSession(options.sessionId, existing);
36182
35781
  return existing.prepared();
36183
35782
  }
36184
35783
  if (!existing.canRebind()) {
@@ -36199,22 +35798,24 @@ var AcpSessionManager = class {
36199
35798
  * authoritative settings. Its identity and store are private to this
36200
35799
  * operation and never become a Mobius Session.
36201
35800
  */
36202
- inspectAgentSettings = async (options) => {
36203
- const runtime = await AcpProcessSession.start(
35801
+ inspectAgentSettings = async (options) => await this.#runWithTransientProcess(
35802
+ options.signal,
35803
+ async () => await AcpProcessSession.start(
36204
35804
  {
36205
35805
  ...options,
36206
35806
  sessionId: `agent-settings-${crypto.randomUUID()}`
36207
35807
  },
36208
35808
  () => this.#agentSettingsObserver,
36209
35809
  new MemoryAcpSessionStore()
36210
- );
36211
- try {
35810
+ ),
35811
+ (runtime) => {
36212
35812
  const prepared = runtime.prepared();
36213
- return new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions);
36214
- } finally {
36215
- await runtime.close();
36216
- }
36217
- };
35813
+ return Promise.resolve(
35814
+ new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions)
35815
+ );
35816
+ },
35817
+ async (runtime) => await runtime.close()
35818
+ );
36218
35819
  /**
36219
35820
  * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
36220
35821
  * Use inspectAgentSettings for Agent-scoped settings discovery.
@@ -36223,18 +35824,20 @@ var AcpSessionManager = class {
36223
35824
  if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
36224
35825
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
36225
35826
  }
36226
- const runtime = await this.#startPreparation(options, metrics);
35827
+ this.#beginSessionUse(options.sessionId);
36227
35828
  try {
36228
- return runtime.prepared();
36229
- } finally {
36230
- if (this.#sessions.get(options.sessionId) === runtime) {
36231
- this.#sessions.delete(options.sessionId);
36232
- }
35829
+ const runtime = await this.#startPreparation(options, metrics);
36233
35830
  try {
36234
- await runtime.close();
35831
+ return runtime.prepared();
36235
35832
  } finally {
36236
- this.#store.remove(options.sessionId);
35833
+ try {
35834
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
35835
+ } finally {
35836
+ this.#store.remove(options.sessionId);
35837
+ }
36237
35838
  }
35839
+ } finally {
35840
+ this.#endSessionUse(options.sessionId);
36238
35841
  }
36239
35842
  };
36240
35843
  prepareExecutionSession = async (options) => {
@@ -36255,6 +35858,7 @@ var AcpSessionManager = class {
36255
35858
  );
36256
35859
  }
36257
35860
  if (existing.usesEnvironment(options.agent.environment)) {
35861
+ this.#touchExpectedSession(options.sessionId, existing);
36258
35862
  return existing.prepared();
36259
35863
  }
36260
35864
  if (!existing.canRebind()) {
@@ -36271,6 +35875,7 @@ var AcpSessionManager = class {
36271
35875
  if (pending !== void 0) {
36272
35876
  const runtime2 = await pending;
36273
35877
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35878
+ this.#touchExpectedNativeBrowserSession(options.sessionId, runtime2);
36274
35879
  return runtime2.prepared();
36275
35880
  }
36276
35881
  return await this.prepareNativeSessionBrowser(options);
@@ -36278,6 +35883,7 @@ var AcpSessionManager = class {
36278
35883
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
36279
35884
  if (existing !== void 0) {
36280
35885
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35886
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
36281
35887
  return existing.prepared();
36282
35888
  }
36283
35889
  if (!existing.canRebind()) {
@@ -36294,8 +35900,13 @@ var AcpSessionManager = class {
36294
35900
  return runtime.prepared();
36295
35901
  };
36296
35902
  configureSession = async (options) => {
36297
- const runtime = await this.ensureSession(options);
36298
- return await runtime.configure(options);
35903
+ this.#beginSessionUse(options.sessionId);
35904
+ try {
35905
+ const runtime = await this.ensureSession(options);
35906
+ return await runtime.configure(options);
35907
+ } finally {
35908
+ this.#endSessionUse(options.sessionId);
35909
+ }
36299
35910
  };
36300
35911
  cancelPrompt = async (sessionId) => {
36301
35912
  const existing = this.#cancellationRequests.get(sessionId);
@@ -36311,6 +35922,8 @@ var AcpSessionManager = class {
36311
35922
  } finally {
36312
35923
  if (this.#sessions.get(sessionId) === runtime) {
36313
35924
  this.#sessions.delete(sessionId);
35925
+ this.#retainedProcesses.delete(runtime);
35926
+ this.#notifyProcessCapacityChanged();
36314
35927
  }
36315
35928
  }
36316
35929
  }
@@ -36400,10 +36013,7 @@ var AcpSessionManager = class {
36400
36013
  return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
36401
36014
  } catch (error62) {
36402
36015
  if (this.#cancellationRequests.has(options.sessionId)) {
36403
- if (this.#sessions.get(options.sessionId) === runtime) {
36404
- this.#sessions.delete(options.sessionId);
36405
- }
36406
- await runtime.closeProcess();
36016
+ await this.#cancellationRequests.get(options.sessionId);
36407
36017
  return { stopReason: "cancelled" };
36408
36018
  }
36409
36019
  throw error62;
@@ -36411,8 +36021,11 @@ var AcpSessionManager = class {
36411
36021
  } catch (error62) {
36412
36022
  const failedRuntime = this.#sessions.get(options.sessionId);
36413
36023
  if (failedRuntime !== void 0) {
36414
- this.#sessions.delete(options.sessionId);
36415
- await failedRuntime.close();
36024
+ await this.#retireSessionProcess(
36025
+ options.sessionId,
36026
+ failedRuntime,
36027
+ async () => await failedRuntime.close()
36028
+ );
36416
36029
  }
36417
36030
  if (this.#cancellationRequests.has(options.sessionId)) {
36418
36031
  return { stopReason: "cancelled" };
@@ -36433,6 +36046,8 @@ var AcpSessionManager = class {
36433
36046
  this.#activeCommandIds.delete(options.sessionId);
36434
36047
  }
36435
36048
  this.#cancellationRequests.delete(options.sessionId);
36049
+ this.#touchSession(options.sessionId);
36050
+ this.#notifyProcessCapacityChanged();
36436
36051
  }
36437
36052
  }
36438
36053
  };
@@ -36451,11 +36066,16 @@ var AcpSessionManager = class {
36451
36066
  await runtime.respondElicitation(options);
36452
36067
  };
36453
36068
  close = async () => {
36454
- const sessions = [...this.#sessions.values()];
36455
- const nativeBrowserSessions = [...this.#nativeBrowserSessions.values()];
36456
- this.#sessions.clear();
36457
- this.#nativeBrowserSessions.clear();
36458
- await Promise.all([...sessions, ...nativeBrowserSessions].map(async (session) => await session.close()));
36069
+ const sessions = [...this.#sessions.entries()];
36070
+ const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
36071
+ await Promise.all([
36072
+ ...sessions.map(
36073
+ async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
36074
+ ),
36075
+ ...nativeBrowserSessions.map(
36076
+ async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
36077
+ )
36078
+ ]);
36459
36079
  };
36460
36080
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
36461
36081
  ensureSession = async (options) => {
@@ -36468,6 +36088,7 @@ var AcpSessionManager = class {
36468
36088
  "session_identity_mismatch"
36469
36089
  );
36470
36090
  }
36091
+ this.#touchExpectedSession(options.sessionId, existing);
36471
36092
  return existing;
36472
36093
  }
36473
36094
  await this.prepareSession(options);
@@ -36487,6 +36108,7 @@ var AcpSessionManager = class {
36487
36108
  "session_identity_mismatch"
36488
36109
  );
36489
36110
  }
36111
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
36490
36112
  return existing;
36491
36113
  }
36492
36114
  await this.prepareNativeSessionBrowser(options);
@@ -36496,7 +36118,14 @@ var AcpSessionManager = class {
36496
36118
  }
36497
36119
  return started;
36498
36120
  }
36499
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
36121
+ listNativeSessions = async (options, cursor) => {
36122
+ this.#beginNativeBrowserUse(options.sessionId);
36123
+ try {
36124
+ return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
36125
+ } finally {
36126
+ this.#endNativeBrowserUse(options.sessionId);
36127
+ }
36128
+ };
36500
36129
  previewNativeSession = async (options, nativeSessionId) => {
36501
36130
  const key = `${options.agent.id}:${nativeSessionId}`;
36502
36131
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
@@ -36509,17 +36138,19 @@ var AcpSessionManager = class {
36509
36138
  }
36510
36139
  this.#nativeOperations.add(key);
36511
36140
  try {
36512
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
36513
- options,
36514
- () => this.#nativeBrowserObserver,
36515
- new MemoryAcpSessionStore()
36141
+ return await this.#runWithTransientProcess(
36142
+ options.signal,
36143
+ async () => await AcpProcessSession.startNativeSessionBrowser(
36144
+ options,
36145
+ () => this.#nativeBrowserObserver,
36146
+ new MemoryAcpSessionStore()
36147
+ ),
36148
+ async (runtime) => {
36149
+ runtime.selectNativeSession(nativeSessionId);
36150
+ return await runtime.loadHistory(options.signal);
36151
+ },
36152
+ async (runtime) => await runtime.closeProcess()
36516
36153
  );
36517
- try {
36518
- runtime.selectNativeSession(nativeSessionId);
36519
- return await runtime.loadHistory(options.signal);
36520
- } finally {
36521
- await runtime.closeProcess();
36522
- }
36523
36154
  } finally {
36524
36155
  this.#nativeOperations.delete(key);
36525
36156
  }
@@ -36539,36 +36170,46 @@ var AcpSessionManager = class {
36539
36170
  }
36540
36171
  const existing = linked[0];
36541
36172
  if (origin.kind === "import" && existing !== void 0) {
36542
- const runtime = await this.ensureSession({
36543
- ...options,
36544
- sessionId: existing.sessionId
36545
- });
36546
- if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
36547
- throw new AcpExecutionError(
36548
- "Wait for the native session's running operation to finish",
36549
- {},
36550
- "session_busy"
36551
- );
36552
- }
36553
- this.#nativeOperations.add(key);
36173
+ this.#beginSessionUse(existing.sessionId);
36554
36174
  try {
36555
- const history = await runtime.loadHistory(options.signal);
36556
- return {
36557
- prepared: runtime.prepared(),
36558
- sessionId: existing.sessionId,
36559
- history
36560
- };
36561
- } catch (error62) {
36562
- this.#sessions.delete(existing.sessionId);
36563
- await runtime.closeProcess();
36564
- throw error62;
36175
+ const runtime = await this.ensureSession({
36176
+ ...options,
36177
+ sessionId: existing.sessionId
36178
+ });
36179
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
36180
+ throw new AcpExecutionError(
36181
+ "Wait for the native session's running operation to finish",
36182
+ {},
36183
+ "session_busy"
36184
+ );
36185
+ }
36186
+ this.#nativeOperations.add(key);
36187
+ try {
36188
+ const history = await runtime.loadHistory(options.signal);
36189
+ return {
36190
+ prepared: runtime.prepared(),
36191
+ sessionId: existing.sessionId,
36192
+ history
36193
+ };
36194
+ } catch (error62) {
36195
+ await this.#retireSessionProcess(
36196
+ existing.sessionId,
36197
+ runtime,
36198
+ async () => await runtime.closeProcess()
36199
+ );
36200
+ throw error62;
36201
+ } finally {
36202
+ this.#nativeOperations.delete(key);
36203
+ this.#notifyProcessCapacityChanged();
36204
+ }
36565
36205
  } finally {
36566
- this.#nativeOperations.delete(key);
36206
+ this.#endSessionUse(existing.sessionId);
36567
36207
  }
36568
36208
  }
36569
36209
  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) {
36570
36210
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
36571
36211
  }
36212
+ this.#beginSessionUse(options.sessionId);
36572
36213
  this.#nativeOperations.add(key);
36573
36214
  try {
36574
36215
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -36582,23 +36223,23 @@ var AcpSessionManager = class {
36582
36223
  history
36583
36224
  };
36584
36225
  } catch (error62) {
36585
- this.#sessions.delete(options.sessionId);
36586
36226
  this.#store.remove(options.sessionId);
36587
- await runtime.closeProcess();
36227
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
36588
36228
  throw error62;
36589
36229
  } finally {
36590
36230
  this.#nativeOperations.delete(openedKey);
36231
+ this.#notifyProcessCapacityChanged();
36591
36232
  }
36592
36233
  } catch (error62) {
36593
36234
  this.#store.remove(options.sessionId);
36594
36235
  const runtime = this.#sessions.get(options.sessionId);
36595
- this.#sessions.delete(options.sessionId);
36596
36236
  if (runtime !== void 0) {
36597
- await runtime.closeProcess();
36237
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
36598
36238
  }
36599
36239
  throw error62;
36600
36240
  } finally {
36601
36241
  this.#nativeOperations.delete(key);
36242
+ this.#endSessionUse(options.sessionId);
36602
36243
  }
36603
36244
  };
36604
36245
  forkSessionAtTurn = async (options, sourceSessionId, forkPoint) => {
@@ -36636,6 +36277,7 @@ var AcpSessionManager = class {
36636
36277
  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) {
36637
36278
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
36638
36279
  }
36280
+ this.#beginSessionUse(options.sessionId);
36639
36281
  this.#nativeOperations.add(key);
36640
36282
  try {
36641
36283
  const runtime = await this.#startSessionForkAtTurnPreparation(
@@ -36652,48 +36294,58 @@ var AcpSessionManager = class {
36652
36294
  sessionId: options.sessionId
36653
36295
  };
36654
36296
  } catch (error62) {
36655
- this.#sessions.delete(options.sessionId);
36656
36297
  this.#store.remove(options.sessionId);
36657
- await runtime.closeProcess();
36298
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
36658
36299
  throw error62;
36659
36300
  } finally {
36660
36301
  this.#nativeOperations.delete(openedKey);
36302
+ this.#notifyProcessCapacityChanged();
36661
36303
  }
36662
36304
  } finally {
36663
36305
  this.#nativeOperations.delete(key);
36306
+ this.#endSessionUse(options.sessionId);
36664
36307
  }
36665
36308
  };
36666
36309
  deleteNativeSession = async (options, nativeSessionId) => {
36667
- const runtime = await this.#ensureNativeSessionBrowser(options);
36668
- const key = `${options.agent.id}:${nativeSessionId}`;
36669
- const linked = this.#store.findNative(options.agent.id, nativeSessionId);
36670
- if (this.#nativeOperations.has(key) || linked.some((entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
36671
- throw new AcpExecutionError(
36672
- "Wait for the native session's running operation to finish",
36673
- {},
36674
- "session_busy"
36675
- );
36676
- }
36677
- this.#nativeOperations.add(key);
36310
+ this.#beginNativeBrowserUse(options.sessionId);
36678
36311
  try {
36679
- for (const entry of linked) {
36680
- const active = this.#sessions.get(entry.sessionId);
36681
- if (active !== void 0 && active !== runtime) {
36682
- this.#sessions.delete(entry.sessionId);
36683
- await active.close();
36312
+ const runtime = await this.#ensureNativeSessionBrowser(options);
36313
+ const key = `${options.agent.id}:${nativeSessionId}`;
36314
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
36315
+ if (this.#nativeOperations.has(key) || linked.some(
36316
+ (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
36317
+ )) {
36318
+ throw new AcpExecutionError(
36319
+ "Wait for the native session's running operation to finish",
36320
+ {},
36321
+ "session_busy"
36322
+ );
36323
+ }
36324
+ this.#nativeOperations.add(key);
36325
+ try {
36326
+ for (const entry of linked) {
36327
+ const active = this.#sessions.get(entry.sessionId);
36328
+ if (active !== void 0 && active !== runtime) {
36329
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
36330
+ }
36331
+ }
36332
+ options.signal.throwIfAborted();
36333
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
36334
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
36335
+ if (runtime.nativeSessionId() === nativeSessionId) {
36336
+ await this.#retireNativeBrowserProcess(
36337
+ options.sessionId,
36338
+ runtime,
36339
+ async () => await runtime.close()
36340
+ );
36684
36341
  }
36342
+ return deleted;
36343
+ } finally {
36344
+ this.#nativeOperations.delete(key);
36345
+ this.#notifyProcessCapacityChanged();
36685
36346
  }
36686
- options.signal.throwIfAborted();
36687
- await runtime.deleteNativeSession(nativeSessionId, options.signal);
36688
- const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
36689
- if (runtime.nativeSessionId() === nativeSessionId) {
36690
- this.#nativeBrowserSessions.delete(options.sessionId);
36691
- this.#nativeBrowserStore.remove(options.sessionId);
36692
- await runtime.close();
36693
- }
36694
- return deleted;
36695
36347
  } finally {
36696
- this.#nativeOperations.delete(key);
36348
+ this.#endNativeBrowserUse(options.sessionId);
36697
36349
  }
36698
36350
  };
36699
36351
  };
@@ -37238,7 +36890,7 @@ var FixedInstallationExecutor = class {
37238
36890
  };
37239
36891
 
37240
36892
  // src/artifacts/runtime-artifact-uploader.ts
37241
- import { createHash as createHash3 } from "node:crypto";
36893
+ import { createHash as createHash2 } from "node:crypto";
37242
36894
 
37243
36895
  // ../mobius-sdk/src/errors.ts
37244
36896
  var MobiusError = class extends Error {
@@ -37455,183 +37107,781 @@ var MobiusRuntimePairingLifecycle = Object.freeze({
37455
37107
  Revoked: "revoked"
37456
37108
  });
37457
37109
 
37458
- // src/artifacts/runtime-artifact-uploader.ts
37459
- import { fetch as fetch4 } from "undici";
37460
- var UPLOAD_TIMEOUT_MILLISECONDS = 2e4;
37461
- var RuntimeArtifactUploadError = class extends Error {
37110
+ // src/artifacts/runtime-artifact-uploader.ts
37111
+ import { fetch as fetch4 } from "undici";
37112
+ var UPLOAD_TIMEOUT_MILLISECONDS = 2e4;
37113
+ var RuntimeArtifactUploadError = class extends Error {
37114
+ code;
37115
+ constructor(code, message, options = {}) {
37116
+ super(message, options);
37117
+ this.code = code;
37118
+ this.name = "RuntimeArtifactUploadError";
37119
+ }
37120
+ };
37121
+ var UploadedRuntimeArtifact = class {
37122
+ artifactId;
37123
+ byteLength;
37124
+ mimeType;
37125
+ name;
37126
+ sha256;
37127
+ constructor(artifactId, name, mimeType, byteLength, sha256) {
37128
+ this.artifactId = artifactId;
37129
+ this.byteLength = byteLength;
37130
+ this.mimeType = mimeType;
37131
+ this.name = name;
37132
+ this.sha256 = sha256;
37133
+ }
37134
+ };
37135
+ function daemonToken(config2) {
37136
+ const token = config2.relayUrl.searchParams.get("token");
37137
+ if (token === null || token.length < 32) {
37138
+ throw new RuntimeArtifactUploadError("artifact_endpoint_invalid", "The Relay daemon token is missing");
37139
+ }
37140
+ return token;
37141
+ }
37142
+ function channelOrigin(config2) {
37143
+ const url2 = new URL(config2.relayUrl);
37144
+ url2.protocol = url2.protocol === "wss:" ? "https:" : "http:";
37145
+ let channelPath = "";
37146
+ if (url2.pathname.endsWith("/daemon")) {
37147
+ channelPath = url2.pathname.slice(0, -"/daemon".length);
37148
+ } else {
37149
+ const runtimePath = `${MOBIUS_API_PREFIX}/v1/runtimes/connect`;
37150
+ if (!url2.pathname.endsWith("/v1/runtimes/connect") && !url2.pathname.endsWith(runtimePath)) {
37151
+ throw new RuntimeArtifactUploadError("artifact_endpoint_invalid", "The Relay artifact endpoint is invalid");
37152
+ }
37153
+ channelPath = `${url2.pathname.replace(/\/v1\/runtimes\/connect$/, "")}/channels/${encodeURIComponent(config2.channelId)}`;
37154
+ }
37155
+ url2.pathname = channelPath;
37156
+ url2.search = "";
37157
+ url2.hash = "";
37158
+ return url2;
37159
+ }
37160
+ function uploadError(code, message, cause) {
37161
+ return new RuntimeArtifactUploadError(code, message, cause === void 0 ? {} : { cause });
37162
+ }
37163
+ function translateSdkError(cause) {
37164
+ if (cause instanceof MobiusValidationError) {
37165
+ throw uploadError("artifact_upload_failed", cause.message, cause);
37166
+ }
37167
+ if (cause instanceof MobiusProtocolError) {
37168
+ throw uploadError("artifact_upload_failed", "The Relay returned an invalid upload response", cause);
37169
+ }
37170
+ throw cause;
37171
+ }
37172
+ async function readJson(response) {
37173
+ try {
37174
+ return await response.json();
37175
+ } catch (cause) {
37176
+ throw uploadError("artifact_upload_failed", "The Relay returned an invalid upload response", cause);
37177
+ }
37178
+ }
37179
+ async function readAuthorization(response) {
37180
+ try {
37181
+ return decodeMobiusArtifactUpload(await readJson(response));
37182
+ } catch (cause) {
37183
+ translateSdkError(cause);
37184
+ }
37185
+ }
37186
+ function sessionArtifactUrl(origin, sessionId, resourcePath, token) {
37187
+ const url2 = new URL(`${origin.pathname}/sessions/${encodeURIComponent(sessionId)}/${resourcePath}`, origin);
37188
+ url2.searchParams.set("token", token);
37189
+ return url2;
37190
+ }
37191
+ async function postLease(url2, request, signal) {
37192
+ return await fetch4(url2, {
37193
+ dispatcher: environmentProxyDispatcher,
37194
+ headers: { "content-type": "application/json" },
37195
+ method: "POST",
37196
+ body: JSON.stringify(request),
37197
+ signal
37198
+ });
37199
+ }
37200
+ async function putContent(url2, authorization, bytes, signal) {
37201
+ return await fetch4(url2, {
37202
+ dispatcher: environmentProxyDispatcher,
37203
+ headers: {
37204
+ "content-type": authorization.mediaType,
37205
+ "x-mobius-upload-token": authorization.uploadToken
37206
+ },
37207
+ method: "PUT",
37208
+ body: bytes,
37209
+ signal
37210
+ });
37211
+ }
37212
+ async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
37213
+ signal.throwIfAborted();
37214
+ let request;
37215
+ try {
37216
+ request = new MobiusArtifactUploadRequest(
37217
+ image.name,
37218
+ image.mimeType,
37219
+ image.bytes.byteLength,
37220
+ createHash2("sha256").update(image.bytes).digest("hex")
37221
+ );
37222
+ } catch (cause) {
37223
+ translateSdkError(cause);
37224
+ }
37225
+ const timeoutSignal = AbortSignal.timeout(UPLOAD_TIMEOUT_MILLISECONDS);
37226
+ const requestSignal = AbortSignal.any([signal, timeoutSignal]);
37227
+ const origin = channelOrigin(config2);
37228
+ const token = daemonToken(config2);
37229
+ let created;
37230
+ try {
37231
+ created = await postLease(
37232
+ sessionArtifactUrl(origin, sessionId, "artifacts/uploads", token),
37233
+ request,
37234
+ requestSignal
37235
+ );
37236
+ } catch (cause) {
37237
+ signal.throwIfAborted();
37238
+ throw uploadError(
37239
+ timeoutSignal.aborted ? "artifact_upload_timeout" : "artifact_upload_failed",
37240
+ timeoutSignal.aborted ? "The artifact upload authorization timed out" : "The artifact upload could not start",
37241
+ cause
37242
+ );
37243
+ }
37244
+ if (!created.ok) {
37245
+ await created.body?.cancel();
37246
+ throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact upload");
37247
+ }
37248
+ const authorization = await readAuthorization(created);
37249
+ let uploaded;
37250
+ try {
37251
+ uploaded = await putContent(
37252
+ sessionArtifactUrl(
37253
+ origin,
37254
+ sessionId,
37255
+ `artifacts/${encodeURIComponent(authorization.artifactId)}/content`,
37256
+ token
37257
+ ),
37258
+ authorization,
37259
+ image.bytes,
37260
+ requestSignal
37261
+ );
37262
+ } catch (cause) {
37263
+ signal.throwIfAborted();
37264
+ throw uploadError(
37265
+ timeoutSignal.aborted ? "artifact_upload_timeout" : "artifact_upload_failed",
37266
+ timeoutSignal.aborted ? "The artifact upload timed out" : "The artifact content could not be uploaded",
37267
+ cause
37268
+ );
37269
+ }
37270
+ if (!uploaded.ok) {
37271
+ await uploaded.body?.cancel();
37272
+ throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact content");
37273
+ }
37274
+ try {
37275
+ const available = decodeMobiusAvailableArtifact(await readJson(uploaded));
37276
+ return new UploadedRuntimeArtifact(
37277
+ available.artifactId,
37278
+ available.name,
37279
+ available.mediaType,
37280
+ available.byteLength,
37281
+ available.sha256
37282
+ );
37283
+ } catch (cause) {
37284
+ translateSdkError(cause);
37285
+ }
37286
+ }
37287
+
37288
+ // src/authorization/local-authorization-error.ts
37289
+ var LocalAuthorizationError = class extends Error {
37290
+ code = "local_authorization_failed";
37291
+ constructor(message, options = {}) {
37292
+ super(message, options);
37293
+ this.name = "LocalAuthorizationError";
37294
+ }
37295
+ };
37296
+
37297
+ // src/authorization/workspace-directory.ts
37298
+ import { readdir as readdir2, realpath as realpath8, stat as stat7 } from "node:fs/promises";
37299
+ import { homedir as homedir2 } from "node:os";
37300
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute9, join as join16, normalize as normalize3, relative as relative5 } from "node:path";
37301
+ var WorkspaceDirectoryListing = class {
37302
+ directoryId;
37303
+ directoryLabel;
37304
+ entries;
37305
+ parentDirectoryId;
37306
+ constructor(directoryId2, directoryLabel, entries, parentDirectoryId) {
37307
+ this.directoryId = directoryId2;
37308
+ this.directoryLabel = directoryLabel;
37309
+ this.entries = entries;
37310
+ this.parentDirectoryId = parentDirectoryId;
37311
+ }
37312
+ };
37313
+ function encodePath(path2) {
37314
+ const encoded = Buffer.from(path2, "utf8").toString("base64url");
37315
+ if (encoded.length === 0 || encoded.length > 2e3) {
37316
+ throw new LocalAuthorizationError("The local directory path is too long to select");
37317
+ }
37318
+ return `path-${encoded}`;
37319
+ }
37320
+ function decodePath(value, prefix) {
37321
+ const encoded = value.slice(prefix.length);
37322
+ if (encoded.length === 0 || encoded.length > 2e3 || !/^[a-zA-Z0-9_-]+$/.test(encoded)) {
37323
+ throw new LocalAuthorizationError("The directory identifier is invalid");
37324
+ }
37325
+ const decoded = Buffer.from(encoded, "base64url").toString("utf8");
37326
+ if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize3(decoded) !== decoded) {
37327
+ throw new LocalAuthorizationError("The directory identifier is invalid");
37328
+ }
37329
+ return decoded;
37330
+ }
37331
+ var WorkspaceDirectoryService = class {
37332
+ #bindingId;
37333
+ #defaultWorkspace;
37334
+ constructor(bindingId, defaultWorkspace) {
37335
+ this.#bindingId = bindingId;
37336
+ this.#defaultWorkspace = defaultWorkspace;
37337
+ }
37338
+ authorizeMachine = (bindingId) => {
37339
+ if (bindingId !== this.#bindingId) {
37340
+ throw new LocalAuthorizationError("The runtime binding is not authorized");
37341
+ }
37342
+ };
37343
+ requestedPath = (id) => {
37344
+ if (id === "default") {
37345
+ return this.#defaultWorkspace;
37346
+ }
37347
+ if (id === "home") {
37348
+ return homedir2();
37349
+ }
37350
+ if (id.startsWith("path-")) {
37351
+ const path2 = decodePath(id, "path-");
37352
+ if (isAbsolute9(path2)) {
37353
+ return path2;
37354
+ }
37355
+ }
37356
+ throw new LocalAuthorizationError("The directory identifier is invalid");
37357
+ };
37358
+ resolvePath = async (requested, signal) => {
37359
+ signal.throwIfAborted();
37360
+ if (!isAbsolute9(requested) || requested.includes("\0") || normalize3(requested) !== requested) {
37361
+ throw new LocalAuthorizationError("The local directory path is invalid");
37362
+ }
37363
+ try {
37364
+ const target = await realpath8(requested);
37365
+ signal.throwIfAborted();
37366
+ const metadata = await stat7(target);
37367
+ signal.throwIfAborted();
37368
+ if (!isAbsolute9(target) || normalize3(target) !== target || !metadata.isDirectory()) {
37369
+ throw new LocalAuthorizationError("The selected location is not a directory");
37370
+ }
37371
+ return target;
37372
+ } catch (cause) {
37373
+ signal.throwIfAborted();
37374
+ if (cause instanceof LocalAuthorizationError) {
37375
+ throw cause;
37376
+ }
37377
+ throw new LocalAuthorizationError("This directory is missing or unavailable to your user account", {
37378
+ cause
37379
+ });
37380
+ }
37381
+ };
37382
+ label = (path2) => {
37383
+ const suffix = relative5(homedir2(), path2);
37384
+ return suffix === "" ? "~" : !isAbsolute9(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path2;
37385
+ };
37386
+ identify = async (bindingId, requestedPath, signal) => {
37387
+ this.authorizeMachine(bindingId);
37388
+ const path2 = await this.resolvePath(requestedPath, signal);
37389
+ return {
37390
+ path: path2,
37391
+ directoryId: encodePath(path2),
37392
+ name: basename3(path2) || path2,
37393
+ label: this.label(path2)
37394
+ };
37395
+ };
37396
+ resolve = async (bindingId, id, signal) => {
37397
+ this.authorizeMachine(bindingId);
37398
+ return await this.resolvePath(this.requestedPath(id), signal);
37399
+ };
37400
+ list = async (bindingId, id, signal) => {
37401
+ const target = await this.resolve(bindingId, id, signal);
37402
+ try {
37403
+ const children = await readdir2(target, { withFileTypes: true });
37404
+ signal.throwIfAborted();
37405
+ const entries = [];
37406
+ for (const child of children) {
37407
+ if (entries.length === 500) {
37408
+ break;
37409
+ }
37410
+ if (child.isFile() || child.isBlockDevice() || child.isCharacterDevice() || child.isFIFO() || child.isSocket()) {
37411
+ continue;
37412
+ }
37413
+ try {
37414
+ const path2 = await this.resolvePath(join16(target, child.name), signal);
37415
+ entries.push({ directoryId: encodePath(path2), name: child.name });
37416
+ } catch (cause) {
37417
+ signal.throwIfAborted();
37418
+ if (!(cause instanceof LocalAuthorizationError)) {
37419
+ throw cause;
37420
+ }
37421
+ }
37422
+ }
37423
+ entries.sort((a, b) => a.name.localeCompare(b.name));
37424
+ const parent = dirname5(target);
37425
+ return new WorkspaceDirectoryListing(
37426
+ id,
37427
+ this.label(target),
37428
+ entries,
37429
+ parent === target ? "" : encodePath(parent)
37430
+ );
37431
+ } catch (cause) {
37432
+ signal.throwIfAborted();
37433
+ if (cause instanceof LocalAuthorizationError) {
37434
+ throw cause;
37435
+ }
37436
+ throw new LocalAuthorizationError("This directory cannot be browsed by your user account", { cause });
37437
+ }
37438
+ };
37439
+ resolveMany = async (bindingId, ids, signal) => {
37440
+ const paths = /* @__PURE__ */ new Set();
37441
+ for (const id of ids) {
37442
+ paths.add(await this.resolve(bindingId, id, signal));
37443
+ }
37444
+ return [...paths];
37445
+ };
37446
+ };
37447
+
37448
+ // src/bots/local-bot-grant-store.ts
37449
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
37450
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
37451
+ var LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS = 90 * 24 * 60 * 60 * 1e3;
37452
+ var LocalBotAuthorizationError = class extends Error {
37462
37453
  code;
37463
37454
  constructor(code, message, options = {}) {
37464
37455
  super(message, options);
37465
37456
  this.code = code;
37466
- this.name = "RuntimeArtifactUploadError";
37457
+ this.name = "LocalBotAuthorizationError";
37467
37458
  }
37468
37459
  };
37469
- var UploadedRuntimeArtifact = class {
37470
- artifactId;
37471
- byteLength;
37472
- mimeType;
37473
- name;
37474
- sha256;
37475
- constructor(artifactId, name, mimeType, byteLength, sha256) {
37476
- this.artifactId = artifactId;
37477
- this.byteLength = byteLength;
37478
- this.mimeType = mimeType;
37479
- this.name = name;
37480
- this.sha256 = sha256;
37460
+ var LocalBotGrant = class {
37461
+ agent;
37462
+ agentIdentityDigest;
37463
+ allowedDeliveryTargetIds;
37464
+ behaviorDigest;
37465
+ behaviorRevisionId;
37466
+ bindingId;
37467
+ bindingRevision;
37468
+ botId;
37469
+ expiresAt;
37470
+ localGrantId;
37471
+ revocationEpoch;
37472
+ workspaceIdentityDigest;
37473
+ workspacePath;
37474
+ workspaceRef;
37475
+ constructor(localGrantId, botId, behaviorRevisionId, behaviorDigest, bindingId, bindingRevision, agent, agentIdentityDigest, workspaceRef, workspacePath, workspaceIdentityDigest, allowedDeliveryTargetIds, expiresAt, revocationEpoch) {
37476
+ this.localGrantId = localGrantId;
37477
+ this.botId = botId;
37478
+ this.behaviorRevisionId = behaviorRevisionId;
37479
+ this.behaviorDigest = behaviorDigest;
37480
+ this.bindingId = bindingId;
37481
+ this.bindingRevision = bindingRevision;
37482
+ this.agent = agent;
37483
+ this.agentIdentityDigest = agentIdentityDigest;
37484
+ this.workspaceRef = workspaceRef;
37485
+ this.workspacePath = workspacePath;
37486
+ this.workspaceIdentityDigest = workspaceIdentityDigest;
37487
+ this.allowedDeliveryTargetIds = Object.freeze([...allowedDeliveryTargetIds]);
37488
+ this.expiresAt = expiresAt;
37489
+ this.revocationEpoch = revocationEpoch;
37481
37490
  }
37482
37491
  };
37483
- function daemonToken(config2) {
37484
- const token = config2.relayUrl.searchParams.get("token");
37485
- if (token === null || token.length < 32) {
37486
- throw new RuntimeArtifactUploadError("artifact_endpoint_invalid", "The Relay daemon token is missing");
37487
- }
37488
- return token;
37492
+ function digest(value) {
37493
+ return createHash3("sha256").update(value, "utf8").digest("hex");
37489
37494
  }
37490
- function channelOrigin(config2) {
37491
- const url2 = new URL(config2.relayUrl);
37492
- url2.protocol = url2.protocol === "wss:" ? "https:" : "http:";
37493
- let channelPath = "";
37494
- if (url2.pathname.endsWith("/daemon")) {
37495
- channelPath = url2.pathname.slice(0, -"/daemon".length);
37496
- } else {
37497
- const runtimePath = `${MOBIUS_API_PREFIX}/v1/runtimes/connect`;
37498
- if (!url2.pathname.endsWith("/v1/runtimes/connect") && !url2.pathname.endsWith(runtimePath)) {
37499
- throw new RuntimeArtifactUploadError("artifact_endpoint_invalid", "The Relay artifact endpoint is invalid");
37500
- }
37501
- channelPath = `${url2.pathname.replace(/\/v1\/runtimes\/connect$/, "")}/channels/${encodeURIComponent(config2.channelId)}`;
37502
- }
37503
- url2.pathname = channelPath;
37504
- url2.search = "";
37505
- url2.hash = "";
37506
- return url2;
37495
+ function agentDigest(agent) {
37496
+ return digest(
37497
+ JSON.stringify({
37498
+ adapter: agent.adapterIdentity,
37499
+ agent: agent.agentIdentity,
37500
+ agentVersion: agent.agentVersion,
37501
+ arguments: agent.arguments,
37502
+ id: agent.id
37503
+ })
37504
+ );
37507
37505
  }
37508
- function uploadError(code, message, cause) {
37509
- return new RuntimeArtifactUploadError(code, message, cause === void 0 ? {} : { cause });
37506
+ function workspaceDigest(path2) {
37507
+ return digest(path2);
37510
37508
  }
37511
- function translateSdkError(cause) {
37512
- if (cause instanceof MobiusValidationError) {
37513
- throw uploadError("artifact_upload_failed", cause.message, cause);
37514
- }
37515
- if (cause instanceof MobiusProtocolError) {
37516
- throw uploadError("artifact_upload_failed", "The Relay returned an invalid upload response", cause);
37509
+ function exactTargets(left, right) {
37510
+ if (left.length !== right.length) {
37511
+ return false;
37517
37512
  }
37518
- throw cause;
37513
+ const expected = [...left].sort();
37514
+ const actual = [...right].sort();
37515
+ return expected.every((target, index2) => target === actual[index2]);
37519
37516
  }
37520
- async function readJson(response) {
37521
- try {
37522
- return await response.json();
37523
- } catch (cause) {
37524
- throw uploadError("artifact_upload_failed", "The Relay returned an invalid upload response", cause);
37517
+ function exactSessionConfigurations(left, right) {
37518
+ if (left.length !== right.length) {
37519
+ return false;
37525
37520
  }
37521
+ const expected = new Map(left.map((selection) => [selection.configId, selection]));
37522
+ return right.every((selection) => {
37523
+ const approved = expected.get(selection.configId);
37524
+ return approved !== void 0 && approved.booleanValue === selection.booleanValue && approved.value === selection.value && approved.valueType === selection.valueType;
37525
+ });
37526
37526
  }
37527
- async function readAuthorization(response) {
37528
- try {
37529
- return decodeMobiusArtifactUpload(await readJson(response));
37530
- } catch (cause) {
37531
- translateSdkError(cause);
37527
+ function rowString(row, key) {
37528
+ const value = Reflect.get(row, key);
37529
+ if (typeof value !== "string") {
37530
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37532
37531
  }
37532
+ return value;
37533
37533
  }
37534
- function sessionArtifactUrl(origin, sessionId, resourcePath, token) {
37535
- const url2 = new URL(`${origin.pathname}/sessions/${encodeURIComponent(sessionId)}/${resourcePath}`, origin);
37536
- url2.searchParams.set("token", token);
37537
- return url2;
37538
- }
37539
- async function postLease(url2, request, signal) {
37540
- return await fetch4(url2, {
37541
- dispatcher: environmentProxyDispatcher,
37542
- headers: { "content-type": "application/json" },
37543
- method: "POST",
37544
- body: JSON.stringify(request),
37545
- signal
37546
- });
37534
+ function rowInteger(row, key) {
37535
+ const value = Reflect.get(row, key);
37536
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
37537
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37538
+ }
37539
+ return value;
37547
37540
  }
37548
- async function putContent(url2, authorization, bytes, signal) {
37549
- return await fetch4(url2, {
37550
- dispatcher: environmentProxyDispatcher,
37551
- headers: {
37552
- "content-type": authorization.mediaType,
37553
- "x-mobius-upload-token": authorization.uploadToken
37554
- },
37555
- method: "PUT",
37556
- body: bytes,
37557
- signal
37558
- });
37541
+ function rowHasInteger(row, key) {
37542
+ const value = Reflect.get(row, key);
37543
+ if (value === null) {
37544
+ return false;
37545
+ }
37546
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
37547
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37548
+ }
37549
+ return true;
37559
37550
  }
37560
- async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
37561
- signal.throwIfAborted();
37562
- let request;
37551
+ function parseTargets(encoded) {
37552
+ let value;
37563
37553
  try {
37564
- request = new MobiusArtifactUploadRequest(
37565
- image.name,
37566
- image.mimeType,
37567
- image.bytes.byteLength,
37568
- createHash3("sha256").update(image.bytes).digest("hex")
37569
- );
37554
+ value = JSON.parse(encoded);
37570
37555
  } catch (cause) {
37571
- translateSdkError(cause);
37556
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
37572
37557
  }
37573
- const timeoutSignal = AbortSignal.timeout(UPLOAD_TIMEOUT_MILLISECONDS);
37574
- const requestSignal = AbortSignal.any([signal, timeoutSignal]);
37575
- const origin = channelOrigin(config2);
37576
- const token = daemonToken(config2);
37577
- let created;
37558
+ if (!Array.isArray(value) || value.some((target) => typeof target !== "string")) {
37559
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37560
+ }
37561
+ return value.filter((target) => typeof target === "string");
37562
+ }
37563
+ function parseSessionConfigurations(encoded) {
37564
+ let value;
37578
37565
  try {
37579
- created = await postLease(
37580
- sessionArtifactUrl(origin, sessionId, "artifacts/uploads", token),
37581
- request,
37582
- requestSignal
37583
- );
37566
+ value = JSON.parse(encoded);
37567
+ return decodeSessionConfigurationSelections(value);
37584
37568
  } catch (cause) {
37585
- signal.throwIfAborted();
37586
- throw uploadError(
37587
- timeoutSignal.aborted ? "artifact_upload_timeout" : "artifact_upload_failed",
37588
- timeoutSignal.aborted ? "The artifact upload authorization timed out" : "The artifact upload could not start",
37589
- cause
37590
- );
37569
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
37591
37570
  }
37592
- if (!created.ok) {
37593
- await created.body?.cancel();
37594
- throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact upload");
37571
+ }
37572
+ var LocalBotGrantStore = class {
37573
+ #database;
37574
+ constructor(path2) {
37575
+ this.#database = new DatabaseSync3(path2);
37576
+ this.#database.exec(`
37577
+ CREATE TABLE IF NOT EXISTS local_bot_grants (
37578
+ local_grant_id TEXT PRIMARY KEY,
37579
+ bot_id TEXT NOT NULL,
37580
+ behavior_revision_id TEXT NOT NULL,
37581
+ behavior_digest TEXT NOT NULL,
37582
+ binding_id TEXT NOT NULL UNIQUE,
37583
+ binding_revision INTEGER NOT NULL,
37584
+ agent_ref TEXT NOT NULL,
37585
+ agent_identity_digest TEXT NOT NULL,
37586
+ workspace_ref TEXT NOT NULL,
37587
+ workspace_path TEXT NOT NULL,
37588
+ workspace_identity_digest TEXT NOT NULL,
37589
+ allowed_delivery_target_ids_json TEXT NOT NULL,
37590
+ unattended_policy_json TEXT NOT NULL,
37591
+ created_at INTEGER NOT NULL,
37592
+ expires_at INTEGER NOT NULL,
37593
+ revocation_epoch INTEGER NOT NULL DEFAULT 0,
37594
+ revoked_at INTEGER
37595
+ ) STRICT;
37596
+ CREATE TABLE IF NOT EXISTS local_bot_binding_resolutions (
37597
+ request_id TEXT PRIMARY KEY,
37598
+ binding_id TEXT NOT NULL,
37599
+ local_grant_id TEXT NOT NULL,
37600
+ resolved_at INTEGER NOT NULL,
37601
+ result TEXT NOT NULL CHECK (result IN ('approved', 'unavailable')),
37602
+ error_code TEXT,
37603
+ error_message TEXT
37604
+ ) STRICT;
37605
+ CREATE TABLE IF NOT EXISTS local_bot_grant_configurations (
37606
+ local_grant_id TEXT PRIMARY KEY,
37607
+ session_configurations_json TEXT NOT NULL
37608
+ ) STRICT;
37609
+ `);
37595
37610
  }
37596
- const authorization = await readAuthorization(created);
37597
- let uploaded;
37598
- try {
37599
- uploaded = await putContent(
37600
- sessionArtifactUrl(
37601
- origin,
37602
- sessionId,
37603
- `artifacts/${encodeURIComponent(authorization.artifactId)}/content`,
37604
- token
37605
- ),
37606
- authorization,
37607
- image.bytes,
37608
- requestSignal
37611
+ approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
37612
+ signal.throwIfAborted();
37613
+ const existing = this.#database.prepare(
37614
+ `SELECT grants.* FROM local_bot_binding_resolutions AS resolutions
37615
+ INNER JOIN local_bot_grants AS grants
37616
+ ON grants.local_grant_id = resolutions.local_grant_id
37617
+ WHERE resolutions.request_id = ? AND resolutions.binding_id = ?
37618
+ AND resolutions.result = 'approved'`
37619
+ ).get(request.requestId, request.bindingId);
37620
+ if (existing !== void 0) {
37621
+ return new BotExecutionBindingApprovedEvent(
37622
+ request.requestId,
37623
+ request.botId,
37624
+ request.behaviorRevisionId,
37625
+ request.bindingId,
37626
+ request.bindingRevision,
37627
+ rowString(existing, "local_grant_id"),
37628
+ rowString(existing, "agent_identity_digest"),
37629
+ rowString(existing, "workspace_identity_digest")
37630
+ );
37631
+ }
37632
+ const resolved = await this.resolveProposal(request, catalog, directories, bindingAuthorityId, signal);
37633
+ const localGrantId = `lbg_${randomUUID3()}`;
37634
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
37635
+ this.#database.exec("BEGIN IMMEDIATE");
37636
+ try {
37637
+ this.#database.prepare(
37638
+ `INSERT INTO local_bot_grants (
37639
+ local_grant_id, bot_id, behavior_revision_id, behavior_digest,
37640
+ binding_id, binding_revision, agent_ref,
37641
+ agent_identity_digest, workspace_ref, workspace_path,
37642
+ workspace_identity_digest, allowed_delivery_target_ids_json,
37643
+ unattended_policy_json, created_at, expires_at
37644
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
37645
+ ).run(
37646
+ localGrantId,
37647
+ request.botId,
37648
+ request.behaviorRevisionId,
37649
+ request.behaviorDigest,
37650
+ request.bindingId,
37651
+ request.bindingRevision,
37652
+ request.agentRef,
37653
+ resolved.agentIdentityDigest,
37654
+ request.workspaceRef,
37655
+ resolved.workspacePath,
37656
+ resolved.workspaceIdentityDigest,
37657
+ JSON.stringify(request.allowedDeliveryTargets.map((target) => target.deliveryTargetId)),
37658
+ JSON.stringify({ localSideEffects: "owner-approval-required" }),
37659
+ now,
37660
+ expiresAt
37661
+ );
37662
+ this.#database.prepare(
37663
+ `INSERT INTO local_bot_grant_configurations (
37664
+ local_grant_id, session_configurations_json
37665
+ ) VALUES (?, ?)`
37666
+ ).run(localGrantId, JSON.stringify(request.sessionConfigurations));
37667
+ this.#database.prepare(
37668
+ `INSERT INTO local_bot_binding_resolutions (
37669
+ request_id, binding_id, local_grant_id, resolved_at, result
37670
+ ) VALUES (?, ?, ?, ?, 'approved')`
37671
+ ).run(request.requestId, request.bindingId, localGrantId, now);
37672
+ this.#database.exec("COMMIT");
37673
+ } catch (cause) {
37674
+ this.#database.exec("ROLLBACK");
37675
+ throw cause;
37676
+ }
37677
+ signal.throwIfAborted();
37678
+ return new BotExecutionBindingApprovedEvent(
37679
+ request.requestId,
37680
+ request.botId,
37681
+ request.behaviorRevisionId,
37682
+ request.bindingId,
37683
+ request.bindingRevision,
37684
+ localGrantId,
37685
+ resolved.agentIdentityDigest,
37686
+ resolved.workspaceIdentityDigest
37609
37687
  );
37610
- } catch (cause) {
37688
+ };
37689
+ resolveExecution = async (command, catalog, directories, bindingAuthorityId, now, signal) => {
37611
37690
  signal.throwIfAborted();
37612
- throw uploadError(
37613
- timeoutSignal.aborted ? "artifact_upload_timeout" : "artifact_upload_failed",
37614
- timeoutSignal.aborted ? "The artifact upload timed out" : "The artifact content could not be uploaded",
37615
- cause
37691
+ const row = this.#database.prepare(
37692
+ `SELECT grants.*, COALESCE(configurations.session_configurations_json, '[]')
37693
+ AS session_configurations_json
37694
+ FROM local_bot_grants AS grants
37695
+ LEFT JOIN local_bot_grant_configurations AS configurations
37696
+ ON configurations.local_grant_id = grants.local_grant_id
37697
+ WHERE grants.local_grant_id = ? AND grants.bot_id = ?
37698
+ AND behavior_revision_id = ? AND behavior_digest = ?
37699
+ AND binding_id = ? AND binding_revision = ?
37700
+ AND agent_ref = ?`
37701
+ ).get(
37702
+ command.localGrantId,
37703
+ command.botId,
37704
+ command.behaviorRevisionId,
37705
+ command.behaviorDigest,
37706
+ command.bindingId,
37707
+ command.bindingRevision,
37708
+ command.agentId
37616
37709
  );
37617
- }
37618
- if (!uploaded.ok) {
37619
- await uploaded.body?.cancel();
37620
- throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact content");
37621
- }
37622
- try {
37623
- const available = decodeMobiusAvailableArtifact(await readJson(uploaded));
37624
- return new UploadedRuntimeArtifact(
37625
- available.artifactId,
37626
- available.name,
37627
- available.mediaType,
37628
- available.byteLength,
37629
- available.sha256
37710
+ if (row === void 0) {
37711
+ throw new LocalBotAuthorizationError(
37712
+ "binding_not_approved",
37713
+ "The Bot execution binding is not locally approved"
37714
+ );
37715
+ }
37716
+ const approvedTargets = parseTargets(rowString(row, "allowed_delivery_target_ids_json"));
37717
+ const requestedTargets = command.allowedDeliveryTargets.map((target) => target.deliveryTargetId);
37718
+ if (!exactTargets(approvedTargets, requestedTargets)) {
37719
+ throw new LocalBotAuthorizationError(
37720
+ "binding_not_approved",
37721
+ "The Bot execution target policy differs from its binding"
37722
+ );
37723
+ }
37724
+ const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
37725
+ if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
37726
+ throw new LocalBotAuthorizationError(
37727
+ "binding_not_approved",
37728
+ "The Bot Agent configuration differs from its binding"
37729
+ );
37730
+ }
37731
+ const agent = catalog.find(command.agentId);
37732
+ const [adapterUnchanged, agentUnchanged] = await Promise.all([
37733
+ revalidateExecutable(agent.adapterIdentity),
37734
+ revalidateExecutable(agent.agentIdentity)
37735
+ ]);
37736
+ signal.throwIfAborted();
37737
+ if (!adapterUnchanged || !agentUnchanged) {
37738
+ throw new LocalBotAuthorizationError(
37739
+ "binding_incompatible",
37740
+ "The local Agent executable changed while the Runtime is active; restart the Runtime"
37741
+ );
37742
+ }
37743
+ const workspaceRef = rowString(row, "workspace_ref");
37744
+ const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
37745
+ const currentAgentDigest = agentDigest(agent);
37746
+ const currentWorkspaceDigest = workspaceDigest(workspacePath);
37747
+ signal.throwIfAborted();
37748
+ let expiresAt = rowInteger(row, "expires_at");
37749
+ let revocationEpoch = rowInteger(row, "revocation_epoch");
37750
+ if (currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path") || expiresAt <= now || rowHasInteger(row, "revoked_at")) {
37751
+ const refreshed = this.refreshTarget(
37752
+ rowString(row, "local_grant_id"),
37753
+ currentAgentDigest,
37754
+ currentWorkspaceDigest,
37755
+ workspacePath,
37756
+ now
37757
+ );
37758
+ expiresAt = refreshed.expiresAt;
37759
+ revocationEpoch = refreshed.revocationEpoch;
37760
+ }
37761
+ if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
37762
+ throw new LocalBotAuthorizationError(
37763
+ "binding_incompatible",
37764
+ "The local Agent cannot apply the approved Bot behavior"
37765
+ );
37766
+ }
37767
+ return new LocalBotGrant(
37768
+ rowString(row, "local_grant_id"),
37769
+ command.botId,
37770
+ command.behaviorRevisionId,
37771
+ command.behaviorDigest,
37772
+ command.bindingId,
37773
+ command.bindingRevision,
37774
+ agent,
37775
+ currentAgentDigest,
37776
+ workspaceRef,
37777
+ workspacePath,
37778
+ currentWorkspaceDigest,
37779
+ approvedTargets,
37780
+ expiresAt,
37781
+ revocationEpoch
37630
37782
  );
37631
- } catch (cause) {
37632
- translateSdkError(cause);
37633
- }
37634
- }
37783
+ };
37784
+ recordUnavailable = (request, code, message, now) => {
37785
+ this.#database.prepare(
37786
+ `INSERT OR IGNORE INTO local_bot_binding_resolutions (
37787
+ request_id, binding_id, local_grant_id, resolved_at,
37788
+ result, error_code, error_message
37789
+ ) VALUES (?, ?, '', ?, 'unavailable', ?, ?)`
37790
+ ).run(request.requestId, request.bindingId, now, code, message);
37791
+ };
37792
+ close = () => {
37793
+ this.#database.close();
37794
+ };
37795
+ resolveProposal = async (request, catalog, directories, bindingAuthorityId, signal) => {
37796
+ const agent = catalog.find(request.agentRef);
37797
+ if (request.requiredCapabilities.includes("embedded-context") && !agent.capabilities.embeddedContextPrompt) {
37798
+ throw new LocalBotAuthorizationError(
37799
+ "binding_incompatible",
37800
+ "The local Agent cannot apply embedded Bot context"
37801
+ );
37802
+ }
37803
+ if (request.requiredCapabilities.some((capability) => capability !== "embedded-context")) {
37804
+ throw new LocalBotAuthorizationError(
37805
+ "binding_incompatible",
37806
+ "The Bot requires an unsupported local Agent capability"
37807
+ );
37808
+ }
37809
+ const [adapterUnchanged, agentUnchanged] = await Promise.all([
37810
+ revalidateExecutable(agent.adapterIdentity),
37811
+ revalidateExecutable(agent.agentIdentity)
37812
+ ]);
37813
+ signal.throwIfAborted();
37814
+ if (!adapterUnchanged || !agentUnchanged) {
37815
+ throw new LocalBotAuthorizationError(
37816
+ "binding_incompatible",
37817
+ "The local Agent executable changed before approval"
37818
+ );
37819
+ }
37820
+ const workspacePath = await directories.resolve(bindingAuthorityId, request.workspaceRef, signal);
37821
+ return {
37822
+ agent,
37823
+ agentIdentityDigest: agentDigest(agent),
37824
+ workspaceIdentityDigest: workspaceDigest(workspacePath),
37825
+ workspacePath
37826
+ };
37827
+ };
37828
+ refreshTarget = (localGrantId, agentIdentityDigest, workspaceIdentityDigest, workspacePath, now) => {
37829
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
37830
+ this.#database.exec("BEGIN IMMEDIATE");
37831
+ try {
37832
+ const current = this.#database.prepare("SELECT * FROM local_bot_grants WHERE local_grant_id = ?").get(localGrantId);
37833
+ if (current === void 0) {
37834
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is missing");
37835
+ }
37836
+ const currentExpiresAt = rowInteger(current, "expires_at");
37837
+ const currentRevocationEpoch = rowInteger(current, "revocation_epoch");
37838
+ if (agentIdentityDigest === rowString(current, "agent_identity_digest") && workspaceIdentityDigest === rowString(current, "workspace_identity_digest") && workspacePath === rowString(current, "workspace_path") && currentExpiresAt > now && !rowHasInteger(current, "revoked_at")) {
37839
+ this.#database.exec("COMMIT");
37840
+ return { expiresAt: currentExpiresAt, revocationEpoch: currentRevocationEpoch };
37841
+ }
37842
+ const result = this.#database.prepare(
37843
+ `UPDATE local_bot_grants
37844
+ SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
37845
+ expires_at = ?, revoked_at = NULL, revocation_epoch = revocation_epoch + 1
37846
+ WHERE local_grant_id = ? AND revocation_epoch = ?`
37847
+ ).run(
37848
+ agentIdentityDigest,
37849
+ workspaceIdentityDigest,
37850
+ workspacePath,
37851
+ expiresAt,
37852
+ localGrantId,
37853
+ currentRevocationEpoch
37854
+ );
37855
+ if (result.changes !== 1) {
37856
+ throw new LocalBotAuthorizationError(
37857
+ "local_grant_invalid",
37858
+ "The local Bot grant target could not be refreshed"
37859
+ );
37860
+ }
37861
+ this.#database.prepare(
37862
+ `INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
37863
+ VALUES (?, 'bot_binding_target_refreshed', ?, '', ?)`
37864
+ ).run(
37865
+ new Date(now).toISOString(),
37866
+ rowString(current, "binding_id"),
37867
+ JSON.stringify({
37868
+ agentIdentityChanged: agentIdentityDigest !== rowString(current, "agent_identity_digest"),
37869
+ bindingId: rowString(current, "binding_id"),
37870
+ botId: rowString(current, "bot_id"),
37871
+ expired: currentExpiresAt <= now,
37872
+ revived: rowHasInteger(current, "revoked_at"),
37873
+ workspaceIdentityChanged: workspaceIdentityDigest !== rowString(current, "workspace_identity_digest"),
37874
+ workspacePathChanged: workspacePath !== rowString(current, "workspace_path")
37875
+ })
37876
+ );
37877
+ this.#database.exec("COMMIT");
37878
+ return { expiresAt, revocationEpoch: currentRevocationEpoch + 1 };
37879
+ } catch (cause) {
37880
+ this.#database.exec("ROLLBACK");
37881
+ throw cause;
37882
+ }
37883
+ };
37884
+ };
37635
37885
 
37636
37886
  // src/bots/bot-context-applicator.ts
37637
37887
  var AppliedBotContext = class {
@@ -37768,7 +38018,7 @@ var BotExecutionContextRegistry = class {
37768
38018
  // src/bots/bot-outbound-ipc.ts
37769
38019
  import { chmod as chmod2, mkdir as mkdir4, unlink } from "node:fs/promises";
37770
38020
  import { createServer } from "node:net";
37771
- import { dirname as dirname7, isAbsolute as isAbsolute10 } from "node:path";
38021
+ import { dirname as dirname6, isAbsolute as isAbsolute10 } from "node:path";
37772
38022
  import { fetch as fetch5 } from "undici";
37773
38023
  var BOT_IPC_REQUEST_LIMIT = 32 * 1024;
37774
38024
  var BOT_IPC_TIMEOUT_MILLISECONDS2 = 2e4;
@@ -37881,7 +38131,7 @@ var BotOutboundIpcServer = class {
37881
38131
  listen = async (signal) => {
37882
38132
  signal.throwIfAborted();
37883
38133
  if (this.#usesFilesystemSocket) {
37884
- await mkdir4(dirname7(this.#socketPath), { mode: 448, recursive: true });
38134
+ await mkdir4(dirname6(this.#socketPath), { mode: 448, recursive: true });
37885
38135
  await unlink(this.#socketPath).catch((error62) => {
37886
38136
  if (!isRecord12(error62) || error62["code"] !== "ENOENT") {
37887
38137
  throw error62;
@@ -39225,7 +39475,7 @@ var RelayConnectionLiveness = class {
39225
39475
 
39226
39476
  // src/relay-connection/session-event-outbox.ts
39227
39477
  import { mkdirSync as mkdirSync3 } from "node:fs";
39228
- import { dirname as dirname8 } from "node:path";
39478
+ import { dirname as dirname7 } from "node:path";
39229
39479
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
39230
39480
  var DEFAULT_OUTBOX_LIMITS = {
39231
39481
  criticalEventBytes: 136 * 1024 * 1024,
@@ -39291,7 +39541,7 @@ var SessionEventOutbox = class {
39291
39541
  constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
39292
39542
  validateLimits(limits);
39293
39543
  this.#limits = limits;
39294
- mkdirSync3(dirname8(path2), { recursive: true });
39544
+ mkdirSync3(dirname7(path2), { recursive: true });
39295
39545
  this.#database = new DatabaseSync4(path2);
39296
39546
  this.#database.exec(`
39297
39547
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
@@ -39828,7 +40078,7 @@ function botIpcSocketPath() {
39828
40078
  if (process.platform === "win32") {
39829
40079
  return `\\\\.\\pipe\\mobius-bot-${randomUUID6()}`;
39830
40080
  }
39831
- return join18("/tmp", `mobius-bot-${randomUUID6()}.sock`);
40081
+ return join17("/tmp", `mobius-bot-${randomUUID6()}.sock`);
39832
40082
  }
39833
40083
  var DaemonAcpObserver = class {
39834
40084
  #config;
@@ -42164,7 +42414,6 @@ Usage:
42164
42414
  mobius pair --url <relay-url> --pairing <runtime-pairing-id> --code <pairing-code> [--workspace <directory>]
42165
42415
  mobius start --channel <channel-id>
42166
42416
  mobius agents [--json]
42167
- mobius bot approve --bot <bot-id> [--channel <channel-id>]
42168
42417
  mobius bot message send --target <current|alias> --text <message>
42169
42418
 
42170
42419
  Commands:
@@ -42172,7 +42421,7 @@ Commands:
42172
42421
  pair Pair this machine and start its local daemon
42173
42422
  start Start the local daemon for a saved channel
42174
42423
  agents Show detected, missing, and integration-ready Agents
42175
- bot Approve a saved Bot locally or send a message from an active execution
42424
+ bot Send a message from an active execution
42176
42425
 
42177
42426
  Pairing grants this browser access to the machine with your user account's permissions.
42178
42427
  New conversations default to ~/.mobius/workspace; choose other directories in the browser.
@@ -42203,10 +42452,6 @@ async function main() {
42203
42452
  return;
42204
42453
  }
42205
42454
  if (command === "bot") {
42206
- if (process.argv[3] === "approve") {
42207
- process.stdout.write(await executeBotApproveCommand(process.argv.slice(4), process.env, shutdown.signal));
42208
- return;
42209
- }
42210
42455
  if (process.argv[3] !== "message" || process.argv[4] !== "send") {
42211
42456
  throw new BotMessageCommandError(
42212
42457
  "invalid_request",
@@ -42252,7 +42497,7 @@ try {
42252
42497
  } catch (error62) {
42253
42498
  if (!shutdown.signal.aborted) {
42254
42499
  const message = error62 instanceof Error ? error62.message : "Unknown failure";
42255
- const code = error62 instanceof BotMessageCommandError || error62 instanceof LocalBotAuthorizationError ? `${error62.code}: ` : "";
42500
+ const code = error62 instanceof BotMessageCommandError ? `${error62.code}: ` : "";
42256
42501
  process.stderr.write(`Mobius daemon failed: ${code}${message}
42257
42502
  `);
42258
42503
  process.exitCode = 1;