@moxt-ai/mobius 0.0.40 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/acp/activity.d.ts.map +1 -1
  2. package/dist/acp/activity.js +52 -8
  3. package/dist/acp/activity.js.map +1 -1
  4. package/dist/acp/session-manager.d.ts +4 -3
  5. package/dist/acp/session-manager.d.ts.map +1 -1
  6. package/dist/acp/session-manager.js +511 -126
  7. package/dist/acp/session-manager.js.map +1 -1
  8. package/dist/agent-catalog/discover-local-agents.d.ts +0 -1
  9. package/dist/agent-catalog/discover-local-agents.d.ts.map +1 -1
  10. package/dist/agent-catalog/discover-local-agents.js +0 -1
  11. package/dist/agent-catalog/discover-local-agents.js.map +1 -1
  12. package/dist/artifacts/runtime-artifact-uploader.d.ts +2 -2
  13. package/dist/artifacts/runtime-artifact-uploader.d.ts.map +1 -1
  14. package/dist/artifacts/runtime-artifact-uploader.js +3 -3
  15. package/dist/artifacts/runtime-artifact-uploader.js.map +1 -1
  16. package/dist/authorization/local-artifact.d.ts +6 -0
  17. package/dist/authorization/local-artifact.d.ts.map +1 -0
  18. package/dist/authorization/local-artifact.js +2 -0
  19. package/dist/authorization/local-artifact.js.map +1 -0
  20. package/dist/authorization/local-video.d.ts +11 -0
  21. package/dist/authorization/local-video.d.ts.map +1 -0
  22. package/dist/authorization/local-video.js +48 -0
  23. package/dist/authorization/local-video.js.map +1 -0
  24. package/dist/bots/local-bot-grant-store.d.ts +1 -8
  25. package/dist/bots/local-bot-grant-store.d.ts.map +1 -1
  26. package/dist/bots/local-bot-grant-store.js +79 -121
  27. package/dist/bots/local-bot-grant-store.js.map +1 -1
  28. package/dist/cli.js +1647 -1276
  29. package/dist/cli.js.map +4 -4
  30. package/dist/index.js +800 -312
  31. package/dist/index.js.map +4 -4
  32. package/dist/run-daemon.js +2 -2
  33. package/dist/run-daemon.js.map +1 -1
  34. package/dist/runtime.d.ts.map +1 -1
  35. package/dist/runtime.js +792 -304
  36. package/dist/runtime.js.map +4 -4
  37. package/package.json +1 -1
  38. package/dist/bots/bot-approve-command.d.ts +0 -2
  39. package/dist/bots/bot-approve-command.d.ts.map +0 -1
  40. package/dist/bots/bot-approve-command.js +0 -78
  41. package/dist/bots/bot-approve-command.js.map +0 -1
package/dist/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.42",
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) {
@@ -22944,7 +22933,7 @@ var displayContentSchema = external_exports.strictObject({
22944
22933
  path: external_exports.string().max(2048),
22945
22934
  terminalId: external_exports.string().max(255),
22946
22935
  text: LONG_TEXT,
22947
- type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text"]),
22936
+ type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text", "video"]),
22948
22937
  uri: external_exports.string().max(4096)
22949
22938
  }).readonly();
22950
22939
  var recordedDisplayContentSchema = external_exports.strictObject({
@@ -22957,7 +22946,7 @@ var recordedDisplayContentSchema = external_exports.strictObject({
22957
22946
  path: external_exports.string().max(2048),
22958
22947
  terminalId: external_exports.string().max(255),
22959
22948
  text: external_exports.string().max(4e6),
22960
- type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text"]),
22949
+ type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text", "video"]),
22961
22950
  uri: external_exports.string().max(4096)
22962
22951
  }).readonly();
22963
22952
  var promptImageSchema = external_exports.strictObject({
@@ -23004,8 +22993,17 @@ var sessionPrepareCommandSchema = external_exports.strictObject({
23004
22993
  }).readonly().optional(),
23005
22994
  kind: external_exports.literal(SESSION_PREPARE_KIND),
23006
22995
  requestId: IDENTIFIER,
22996
+ sessionState: external_exports.literal("provisioned").optional(),
23007
22997
  /** @deprecated Reserved for the legacy Bot Agent-configuration endpoint. */
23008
22998
  transient: external_exports.boolean().optional()
22999
+ }).superRefine((command, context) => {
23000
+ if (command.transient === true && command.sessionState === "provisioned") {
23001
+ context.addIssue({
23002
+ code: "custom",
23003
+ message: "A transient Session cannot already be provisioned",
23004
+ path: ["sessionState"]
23005
+ });
23006
+ }
23009
23007
  }).readonly();
23010
23008
  var runtimeTimingsSchema = external_exports.array(
23011
23009
  external_exports.strictObject({
@@ -23300,7 +23298,7 @@ var ProtocolMessageError = class extends Error {
23300
23298
  this.name = "ProtocolMessageError";
23301
23299
  }
23302
23300
  };
23303
- function isRecord4(value) {
23301
+ function isRecord5(value) {
23304
23302
  return typeof value === "object" && value !== null && !Array.isArray(value);
23305
23303
  }
23306
23304
  function parseJson2(encoded) {
@@ -23312,7 +23310,7 @@ function parseJson2(encoded) {
23312
23310
  cause: error62
23313
23311
  });
23314
23312
  }
23315
- if (!isRecord4(value)) {
23313
+ if (!isRecord5(value)) {
23316
23314
  throw new ProtocolMessageError("Message must be a JSON object");
23317
23315
  }
23318
23316
  return value;
@@ -23409,7 +23407,7 @@ function readActivityContent(value) {
23409
23407
  }
23410
23408
  function readActivityDetail(value) {
23411
23409
  const field = value["detail"];
23412
- if (!isRecord4(field)) {
23410
+ if (!isRecord5(field)) {
23413
23411
  throw new ProtocolMessageError("Invalid activity detail field");
23414
23412
  }
23415
23413
  const kind = readString(field, "kind", 32);
@@ -23896,7 +23894,7 @@ var BotSessionPromptCommand = class {
23896
23894
  };
23897
23895
  }
23898
23896
  };
23899
- function isRecord5(value) {
23897
+ function isRecord6(value) {
23900
23898
  return typeof value === "object" && value !== null && !Array.isArray(value);
23901
23899
  }
23902
23900
  function parseJson3(encoded) {
@@ -23906,7 +23904,7 @@ function parseJson3(encoded) {
23906
23904
  } catch (cause) {
23907
23905
  throw new ProtocolMessageError("Message is not valid JSON", { cause });
23908
23906
  }
23909
- if (!isRecord5(value)) {
23907
+ if (!isRecord6(value)) {
23910
23908
  throw new ProtocolMessageError("Message must be a JSON object");
23911
23909
  }
23912
23910
  return value;
@@ -23997,7 +23995,7 @@ function readTargets(value, key) {
23997
23995
  const identifiers = /* @__PURE__ */ new Set();
23998
23996
  const aliases = /* @__PURE__ */ new Set();
23999
23997
  for (const candidate of field) {
24000
- if (!isRecord5(candidate)) {
23998
+ if (!isRecord6(candidate)) {
24001
23999
  throw new ProtocolMessageError(`Invalid Bot delivery targets: ${key}`);
24002
24000
  }
24003
24001
  assertExactKeys2(candidate, ["alias", "deliveryTargetId"]);
@@ -24019,7 +24017,7 @@ function readSessionConfigurations(value) {
24019
24017
  return decodeSessionConfigurationSelections(value["sessionConfigurations"]);
24020
24018
  }
24021
24019
  function readCompletionPolicy(value) {
24022
- if (!isRecord5(value)) {
24020
+ if (!isRecord6(value)) {
24023
24021
  throw new ProtocolMessageError("Invalid Bot completion policy");
24024
24022
  }
24025
24023
  const kind = readText2(value, "kind", 32, false);
@@ -24037,7 +24035,7 @@ function readCompletionPolicy(value) {
24037
24035
  throw new ProtocolMessageError("Invalid Bot completion policy");
24038
24036
  }
24039
24037
  function readReplyRoute(value) {
24040
- if (!isRecord5(value)) {
24038
+ if (!isRecord6(value)) {
24041
24039
  throw new ProtocolMessageError("Invalid Bot reply route");
24042
24040
  }
24043
24041
  const kind = readText2(value, "kind", 32, false);
@@ -24530,14 +24528,10 @@ var decodeSessionEventAcknowledgement = (encoded) => decode5(encoded, eventAckno
24530
24528
  var decodeSessionEventDeferred = (encoded) => decode5(encoded, eventDeferredSchema);
24531
24529
  var decodeSessionEventRejection = (encoded) => decode5(encoded, eventRejectionSchema);
24532
24530
 
24533
- // src/pairing/pair-local-machine.ts
24534
- import { fetch as fetch2 } from "undici";
24535
-
24536
24531
  // src/config.ts
24537
- import { join as join15 } from "node:path";
24538
24532
  function loadDefaultWorkspace(environment = process.env) {
24539
24533
  const { MOBIUS_DEFAULT_WORKSPACE: configuredWorkspace } = environment;
24540
- return configuredWorkspace ?? join15(readStateDirectory(environment), "workspace");
24534
+ return configuredWorkspace ?? join14(readStateDirectory(environment), "workspace");
24541
24535
  }
24542
24536
  function createDaemonConfig(connection, agents = [], installableAgents = []) {
24543
24537
  return {
@@ -24553,6 +24547,11 @@ function createDaemonConfig(connection, agents = [], installableAgents = []) {
24553
24547
  }
24554
24548
 
24555
24549
  // src/pairing/pair-local-machine.ts
24550
+ import { randomUUID as randomUUID2 } from "node:crypto";
24551
+ import { mkdir as mkdir3, open as open4, realpath as realpath6, rename as rename3, stat as stat5, writeFile as writeFile2 } from "node:fs/promises";
24552
+ import { hostname as hostname3 } from "node:os";
24553
+ import { basename, join as join15, resolve as resolve3 } from "node:path";
24554
+ import { fetch as fetch2 } from "undici";
24556
24555
  var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
24557
24556
  var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
24558
24557
  var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
@@ -24570,7 +24569,7 @@ var PairingClientError = class extends Error {
24570
24569
  this.name = "PairingClientError";
24571
24570
  }
24572
24571
  };
24573
- function isRecord6(value) {
24572
+ function isRecord7(value) {
24574
24573
  return typeof value === "object" && value !== null && !Array.isArray(value);
24575
24574
  }
24576
24575
  function hasExactKeys(value, expectedKeys) {
@@ -24663,8 +24662,8 @@ async function resolveDefaultWorkspace(path2) {
24663
24662
  const requestedWorkspace = resolve3(path2);
24664
24663
  try {
24665
24664
  await mkdir3(requestedWorkspace, { recursive: true, mode: 448 });
24666
- const defaultWorkspace = await realpath7(requestedWorkspace);
24667
- const metadata = await stat6(defaultWorkspace);
24665
+ const defaultWorkspace = await realpath6(requestedWorkspace);
24666
+ const metadata = await stat5(defaultWorkspace);
24668
24667
  if (!metadata.isDirectory()) {
24669
24668
  throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
24670
24669
  }
@@ -24693,9 +24692,9 @@ async function readJsonResponse(response) {
24693
24692
  }
24694
24693
  }
24695
24694
  function readRelayError(value) {
24696
- if (isRecord6(value)) {
24695
+ if (isRecord7(value)) {
24697
24696
  const error62 = value["error"];
24698
- if (isRecord6(error62)) {
24697
+ if (isRecord7(error62)) {
24699
24698
  const code = error62["code"];
24700
24699
  const message = error62["message"];
24701
24700
  if (typeof code === "string" && typeof message === "string") {
@@ -24706,7 +24705,7 @@ function readRelayError(value) {
24706
24705
  return new PairingClientError("pairing_failed", "The relay could not pair this machine");
24707
24706
  }
24708
24707
  function decodePairingResponse(value, credentialField, expectedKeys) {
24709
- if (!isRecord6(value) || !hasExactKeys(value, expectedKeys)) {
24708
+ if (!isRecord7(value) || !hasExactKeys(value, expectedKeys)) {
24710
24709
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
24711
24710
  }
24712
24711
  const channelId = value["channelId"];
@@ -24736,7 +24735,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
24736
24735
  installableAgents,
24737
24736
  machineName: hostname3(),
24738
24737
  pairingCode: options.code,
24739
- workspaceName: basename2(defaultWorkspace) || "Local workspace"
24738
+ workspaceName: basename(defaultWorkspace) || "Local workspace"
24740
24739
  }),
24741
24740
  dispatcher: environmentProxyDispatcher,
24742
24741
  headers: { "content-type": "application/json" },
@@ -24753,10 +24752,10 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
24753
24752
  return options.pairingId.length > 0 ? decodePairingResponse(value, "runtimeCredential", REDEEM_RESPONSE_KEYS) : decodePairingResponse(value, "daemonToken", CLAIM_RESPONSE_KEYS);
24754
24753
  }
24755
24754
  async function persistConnection(channelId, relayOrigin, runtimeCredential2, defaultWorkspace, environment) {
24756
- const connectionsDirectory = join16(readStateDirectory(environment), "connections");
24755
+ const connectionsDirectory = join15(readStateDirectory(environment), "connections");
24757
24756
  await mkdir3(connectionsDirectory, { mode: 448, recursive: true });
24758
- const connectionPath = join16(connectionsDirectory, `${channelId}.json`);
24759
- const temporaryPath = join16(connectionsDirectory, `.${channelId}.${randomUUID()}.tmp`);
24757
+ const connectionPath = join15(connectionsDirectory, `${channelId}.json`);
24758
+ const temporaryPath = join15(connectionsDirectory, `.${channelId}.${randomUUID2()}.tmp`);
24760
24759
  await writeFile2(
24761
24760
  temporaryPath,
24762
24761
  `${JSON.stringify(
@@ -24776,7 +24775,7 @@ async function persistConnection(channelId, relayOrigin, runtimeCredential2, def
24776
24775
  return connectionPath;
24777
24776
  }
24778
24777
  function decodeSavedConnection(value, expectedChannelId) {
24779
- if (!isRecord6(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
24778
+ if (!isRecord7(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
24780
24779
  throw new PairingClientError("invalid_connection", "The saved connection is invalid");
24781
24780
  }
24782
24781
  const defaultWorkspace = value["defaultWorkspace"];
@@ -24794,7 +24793,7 @@ function decodeSavedConnection(value, expectedChannelId) {
24794
24793
  };
24795
24794
  }
24796
24795
  async function readSavedConnection(channelId, environment) {
24797
- const connectionPath = join16(readStateDirectory(environment), "connections", `${channelId}.json`);
24796
+ const connectionPath = join15(readStateDirectory(environment), "connections", `${channelId}.json`);
24798
24797
  let encoded = "";
24799
24798
  const handle = await open4(connectionPath, "r");
24800
24799
  try {
@@ -24830,7 +24829,7 @@ function buildPairedDaemon(connection, connectionPath, inventory, environment) {
24830
24829
  const relayUrl = mobiusApiUrl(connection.relayOrigin, "/v1/runtimes/connect");
24831
24830
  relayUrl.protocol = relayUrl.protocol === "https:" ? "wss:" : "ws:";
24832
24831
  relayUrl.searchParams.set("token", connection.runtimeCredential);
24833
- const auditDatabasePath = join16(readStateDirectory(environment), "audit", `${connection.channelId}.sqlite`);
24832
+ const auditDatabasePath = join15(readStateDirectory(environment), "audit", `${connection.channelId}.sqlite`);
24834
24833
  return {
24835
24834
  channelUrl: new URL(`/channels/${encodeURIComponent(connection.channelId)}`, connection.relayOrigin).toString(),
24836
24835
  config: createDaemonConfig(
@@ -24880,7 +24879,7 @@ async function pairLocalMachine(arguments_, signal = new AbortController().signa
24880
24879
  }
24881
24880
  async function resumeMobiusRuntime(channelId, signal, environment = process.env) {
24882
24881
  const normalizedChannelId = validatePairingId(channelId);
24883
- const connectionPath = join16(readStateDirectory(environment), "connections", `${normalizedChannelId}.json`);
24882
+ const connectionPath = join15(readStateDirectory(environment), "connections", `${normalizedChannelId}.json`);
24884
24883
  const connection = await readSavedConnection(normalizedChannelId, environment);
24885
24884
  const inventory = await discoverLocalAgentInventory({
24886
24885
  defaultWorkspace: connection.defaultWorkspace,
@@ -24893,753 +24892,15 @@ async function resumeLocalMachine(arguments_, signal = new AbortController().sig
24893
24892
  return await resumeMobiusRuntime(parseChannelArgument(arguments_), signal, process.env);
24894
24893
  }
24895
24894
 
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
24895
  // src/audit/audit-store.ts
25635
24896
  import { mkdirSync } from "node:fs";
25636
- import { dirname as dirname5 } from "node:path";
25637
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
24897
+ import { dirname as dirname3 } from "node:path";
24898
+ import { DatabaseSync } from "node:sqlite";
25638
24899
  var AuditStore = class {
25639
24900
  database;
25640
24901
  constructor(path2) {
25641
- mkdirSync(dirname5(path2), { recursive: true });
25642
- this.database = new DatabaseSync2(path2);
24902
+ mkdirSync(dirname3(path2), { recursive: true });
24903
+ this.database = new DatabaseSync(path2);
25643
24904
  this.database.exec(`
25644
24905
  CREATE TABLE IF NOT EXISTS audit_events (
25645
24906
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -25681,7 +24942,7 @@ var AuditStore = class {
25681
24942
 
25682
24943
  // src/run-daemon.ts
25683
24944
  import { randomUUID as randomUUID6 } from "node:crypto";
25684
- import { basename as basename5, join as join18 } from "node:path";
24945
+ import { basename as basename6, join as join17 } from "node:path";
25685
24946
  import { styleText } from "node:util";
25686
24947
  import { fetch as fetch7, WebSocket as WebSocket2 } from "undici";
25687
24948
 
@@ -25695,8 +24956,8 @@ import {
25695
24956
  } from "@agentclientprotocol/sdk";
25696
24957
 
25697
24958
  // 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";
24959
+ import { readFile as readFile2, realpath as realpath7, stat as stat6 } from "node:fs/promises";
24960
+ import { basename as basename2, isAbsolute as isAbsolute8, normalize as normalize2, relative as relative4, sep as sep4 } from "node:path";
25700
24961
  import { fileURLToPath } from "node:url";
25701
24962
  var MAX_LOCAL_RASTER_BYTES = 3e6;
25702
24963
  var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
@@ -25752,21 +25013,21 @@ function readInlineRaster(data, name = "Image") {
25752
25013
  if (mimeType === null) {
25753
25014
  return null;
25754
25015
  }
25755
- return new LocalRasterImage(basename3(name) || "Image", mimeType, bytes);
25016
+ return new LocalRasterImage(basename2(name) || "Image", mimeType, bytes);
25756
25017
  }
25757
25018
  function isInsideRoot(root, target) {
25758
- const relation = relative5(root, target);
25759
- return relation !== ".." && !relation.startsWith(`..${sep4}`) && !isAbsolute9(relation);
25019
+ const relation = relative4(root, target);
25020
+ return relation !== ".." && !relation.startsWith(`..${sep4}`) && !isAbsolute8(relation);
25760
25021
  }
25761
25022
  async function resolveCanonicalPath(requested, signal) {
25762
25023
  signal.throwIfAborted();
25763
- if (!isAbsolute9(requested) || requested.includes("\0") || normalize3(requested) !== requested) {
25024
+ if (!isAbsolute8(requested) || requested.includes("\0") || normalize2(requested) !== requested) {
25764
25025
  return null;
25765
25026
  }
25766
25027
  try {
25767
- const target = await realpath9(requested);
25028
+ const target = await realpath7(requested);
25768
25029
  signal.throwIfAborted();
25769
- if (!isAbsolute9(target) || normalize3(target) !== target) {
25030
+ if (!isAbsolute8(target) || normalize2(target) !== target) {
25770
25031
  return null;
25771
25032
  }
25772
25033
  return target;
@@ -25812,7 +25073,7 @@ async function readAuthorizedRaster(uri, roots, signal) {
25812
25073
  if (target === null) {
25813
25074
  return null;
25814
25075
  }
25815
- const targetMetadata = await stat8(target);
25076
+ const targetMetadata = await stat6(target);
25816
25077
  signal.throwIfAborted();
25817
25078
  if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
25818
25079
  return null;
@@ -25823,7 +25084,7 @@ async function readAuthorizedRaster(uri, roots, signal) {
25823
25084
  if (directory === null) {
25824
25085
  continue;
25825
25086
  }
25826
- const metadata = await stat8(directory);
25087
+ const metadata = await stat6(directory);
25827
25088
  signal.throwIfAborted();
25828
25089
  if (metadata.isDirectory()) {
25829
25090
  authorizedRoots.push(directory);
@@ -25841,7 +25102,56 @@ async function readAuthorizedRaster(uri, roots, signal) {
25841
25102
  if (mimeType === null) {
25842
25103
  return null;
25843
25104
  }
25844
- return new LocalRasterImage(basename3(target) || "Image", mimeType, bytes);
25105
+ return new LocalRasterImage(basename2(target) || "Image", mimeType, bytes);
25106
+ }
25107
+
25108
+ // src/authorization/local-video.ts
25109
+ import { basename as basename3 } from "node:path";
25110
+ var MAX_INLINE_VIDEO_BYTES = 3e6;
25111
+ var MP4_FILE_TYPE = new TextEncoder().encode("ftyp");
25112
+ var WEBM_SIGNATURE = Uint8Array.of(26, 69, 223, 163);
25113
+ var LocalVideo = class {
25114
+ bytes;
25115
+ mimeType;
25116
+ name;
25117
+ constructor(name, mimeType, bytes) {
25118
+ this.bytes = bytes;
25119
+ this.mimeType = mimeType;
25120
+ this.name = name;
25121
+ }
25122
+ base64 = () => Buffer.from(this.bytes).toString("base64");
25123
+ };
25124
+ function startsWith2(bytes, signature, offset = 0) {
25125
+ if (bytes.byteLength < offset + signature.byteLength) {
25126
+ return false;
25127
+ }
25128
+ return signature.every((value, index2) => bytes[offset + index2] === value);
25129
+ }
25130
+ function sniffVideoMime(bytes) {
25131
+ if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
25132
+ return "video/mp4";
25133
+ }
25134
+ if (startsWith2(bytes, WEBM_SIGNATURE)) {
25135
+ return "video/webm";
25136
+ }
25137
+ return null;
25138
+ }
25139
+ function readInlineVideo(data, declaredMimeType, name = "Video") {
25140
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_VIDEO_BYTES / 3) * 4 || data.length % 4 !== 0) {
25141
+ return null;
25142
+ }
25143
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
25144
+ return null;
25145
+ }
25146
+ const bytes = new Uint8Array(Buffer.from(data, "base64"));
25147
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_VIDEO_BYTES) {
25148
+ return null;
25149
+ }
25150
+ const mimeType = sniffVideoMime(bytes);
25151
+ if (mimeType === null || mimeType !== declaredMimeType) {
25152
+ return null;
25153
+ }
25154
+ return new LocalVideo(basename3(name) || "Video", mimeType, bytes);
25845
25155
  }
25846
25156
 
25847
25157
  // src/infra/operation-metrics.ts
@@ -26101,6 +25411,14 @@ function emptyDisplayContent(type) {
26101
25411
  uri: ""
26102
25412
  };
26103
25413
  }
25414
+ function resourceName(uri) {
25415
+ try {
25416
+ const pathname = new URL(uri).pathname;
25417
+ return decodeURIComponent(pathname.slice(pathname.lastIndexOf("/") + 1));
25418
+ } catch {
25419
+ return "";
25420
+ }
25421
+ }
26104
25422
  function imageDisplayContent(mimeType, name, data, artifactId = "", uri = "") {
26105
25423
  return {
26106
25424
  ...emptyDisplayContent("image"),
@@ -26132,18 +25450,21 @@ function normalizeContentBlock(content3) {
26132
25450
  };
26133
25451
  }
26134
25452
  if (content3.type === "resource") {
25453
+ const type = content3.resource.mimeType?.startsWith("video/") === true ? "video" : "resource";
26135
25454
  if ("text" in content3.resource) {
26136
25455
  return {
26137
- ...emptyDisplayContent("resource"),
25456
+ ...emptyDisplayContent(type),
26138
25457
  mimeType: content3.resource.mimeType ?? "",
25458
+ name: resourceName(content3.resource.uri),
26139
25459
  text: content3.resource.text,
26140
25460
  uri: content3.resource.uri
26141
25461
  };
26142
25462
  }
26143
25463
  return {
26144
- ...emptyDisplayContent("resource"),
25464
+ ...emptyDisplayContent(type),
26145
25465
  data: content3.resource.blob,
26146
25466
  mimeType: content3.resource.mimeType ?? "",
25467
+ name: resourceName(content3.resource.uri),
26147
25468
  uri: content3.resource.uri
26148
25469
  };
26149
25470
  }
@@ -26176,6 +25497,36 @@ async function normalizeToolContent(content3, prepareContent) {
26176
25497
  }
26177
25498
  return normalized;
26178
25499
  }
25500
+ function rawMcpToolContent(rawOutput) {
25501
+ if (!isRecord8(rawOutput)) {
25502
+ return [];
25503
+ }
25504
+ const result = isRecord8(rawOutput["result"]) ? rawOutput["result"] : rawOutput;
25505
+ const content3 = result["content"];
25506
+ if (!Array.isArray(content3)) {
25507
+ return [];
25508
+ }
25509
+ return content3.flatMap((item) => {
25510
+ if (!isRecord8(item) || item["type"] !== "image" || typeof item["data"] !== "string" || typeof item["mimeType"] !== "string") {
25511
+ return [];
25512
+ }
25513
+ const uri = item["uri"];
25514
+ return [
25515
+ {
25516
+ type: "content",
25517
+ content: {
25518
+ type: "image",
25519
+ data: item["data"],
25520
+ mimeType: item["mimeType"],
25521
+ ...typeof uri === "string" ? { uri } : {}
25522
+ }
25523
+ }
25524
+ ];
25525
+ });
25526
+ }
25527
+ function toolContent(content3, rawOutput) {
25528
+ return content3 !== void 0 && content3 !== null && content3.length > 0 ? content3 : rawMcpToolContent(rawOutput);
25529
+ }
26179
25530
  function normalizeLocations(locations) {
26180
25531
  const normalized = [];
26181
25532
  const unique = /* @__PURE__ */ new Set();
@@ -26339,7 +25690,10 @@ var AcpActivityTracker = class {
26339
25690
  const output2 = update.rawOutput === void 0 ? readContentOutput(update.content) : formatUnknown(update.rawOutput);
26340
25691
  const detailInput = update.rawInput === void 0 ? "" : formatUnknownDetail(update.rawInput);
26341
25692
  const detailOutput = update.rawOutput === void 0 ? readContentOutputDetail(update.content) : formatUnknownDetail(update.rawOutput);
26342
- const detailContent = await normalizeToolContent(update.content ?? [], this.#prepareContent);
25693
+ const detailContent = await normalizeToolContent(
25694
+ toolContent(update.content, update.rawOutput),
25695
+ this.#prepareContent
25696
+ );
26343
25697
  await this.#record(
26344
25698
  key,
26345
25699
  new AcpActivity(
@@ -26365,10 +25719,11 @@ var AcpActivityTracker = class {
26365
25719
  const identity2 = this.#identity(key);
26366
25720
  const previousDetail = recordedDetail(previous2);
26367
25721
  const output2 = update.rawOutput !== void 0 ? formatUnknown(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutput(update.content) : previous2?.output ?? "";
26368
- const content3 = update.content === void 0 || update.content === null ? previous2?.content ?? [] : await normalizeToolContent(update.content, this.#prepareContent);
25722
+ const nextContent = toolContent(update.content, update.rawOutput);
25723
+ const content3 = nextContent.length === 0 ? previous2?.content ?? [] : await normalizeToolContent(nextContent, this.#prepareContent);
26369
25724
  const detailInput = update.rawInput === void 0 ? previousDetail?.input ?? previous2?.input ?? "" : formatUnknownDetail(update.rawInput);
26370
25725
  const detailOutput = update.rawOutput !== void 0 ? formatUnknownDetail(update.rawOutput) : update.content !== void 0 && update.content !== null ? readContentOutputDetail(update.content) : previousDetail?.output ?? previous2?.output ?? "";
26371
- const detailContent = update.content === void 0 || update.content === null ? previousDetail?.content ?? previous2?.content ?? [] : content3;
25726
+ const detailContent = nextContent.length === 0 ? previousDetail?.content ?? previous2?.content ?? [] : content3;
26372
25727
  await this.#record(
26373
25728
  key,
26374
25729
  new AcpActivity(
@@ -30445,7 +29800,7 @@ var titleBefore = {
30445
29800
  };
30446
29801
  function tokenizeDefinition(effects, ok2, nok) {
30447
29802
  const self = this;
30448
- let identifier4;
29803
+ let identifier2;
30449
29804
  return start;
30450
29805
  function start(code) {
30451
29806
  effects.enter("definition");
@@ -30464,7 +29819,7 @@ function tokenizeDefinition(effects, ok2, nok) {
30464
29819
  )(code);
30465
29820
  }
30466
29821
  function labelAfter(code) {
30467
- identifier4 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
29822
+ identifier2 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
30468
29823
  if (code === 58) {
30469
29824
  effects.enter("definitionMarker");
30470
29825
  effects.consume(code);
@@ -30498,7 +29853,7 @@ function tokenizeDefinition(effects, ok2, nok) {
30498
29853
  function afterWhitespace(code) {
30499
29854
  if (code === null || markdownLineEnding(code)) {
30500
29855
  effects.exit("definition");
30501
- self.parser.defined.push(identifier4);
29856
+ self.parser.defined.push(identifier2);
30502
29857
  return ok2(code);
30503
29858
  }
30504
29859
  return nok(code);
@@ -34130,8 +33485,8 @@ var AcpHistoryReplay = class {
34130
33485
 
34131
33486
  // src/acp/session-store.ts
34132
33487
  import { mkdirSync as mkdirSync2 } from "node:fs";
34133
- import { dirname as dirname6 } from "node:path";
34134
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
33488
+ import { dirname as dirname4 } from "node:path";
33489
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
34135
33490
  var AcpStoredSession = class {
34136
33491
  additionalDirectories;
34137
33492
  agentId;
@@ -34233,8 +33588,8 @@ var MemoryAcpSessionStore = class {
34233
33588
  var SqliteAcpSessionStore = class {
34234
33589
  #database;
34235
33590
  constructor(path2) {
34236
- mkdirSync2(dirname6(path2), { recursive: true });
34237
- this.#database = new DatabaseSync3(path2);
33591
+ mkdirSync2(dirname4(path2), { recursive: true });
33592
+ this.#database = new DatabaseSync2(path2);
34238
33593
  this.#database.exec(`
34239
33594
  CREATE TABLE IF NOT EXISTS acp_deleted_sessions (session_id TEXT PRIMARY KEY) STRICT;
34240
33595
  CREATE TABLE IF NOT EXISTS acp_sessions (
@@ -34333,11 +33688,12 @@ var SqliteAcpSessionStore = class {
34333
33688
 
34334
33689
  // src/acp/session-manager.ts
34335
33690
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
33691
+ var MAX_ACP_PROCESSES = 10;
34336
33692
  var MAX_PRE_SESSION_UPDATES = 100;
34337
33693
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
34338
33694
  var SESSION_CONTROL_COMMAND_ID = "session-control";
34339
33695
  var NullAcpSessionObserver = class {
34340
- importLocalImage = (_sessionId, _image, signal) => {
33696
+ importLocalArtifact = (_sessionId, _artifact, signal) => {
34341
33697
  signal.throwIfAborted();
34342
33698
  return Promise.resolve("");
34343
33699
  };
@@ -34391,6 +33747,91 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
34391
33747
  this.name = "RetryableAcpInitializationError";
34392
33748
  }
34393
33749
  };
33750
+ var AcpProcessCapacityLease = class {
33751
+ #releaseCapacity;
33752
+ #released = false;
33753
+ constructor(releaseCapacity) {
33754
+ this.#releaseCapacity = releaseCapacity;
33755
+ }
33756
+ release = () => {
33757
+ if (this.#released) {
33758
+ return;
33759
+ }
33760
+ this.#released = true;
33761
+ this.#releaseCapacity();
33762
+ };
33763
+ };
33764
+ var AcpProcessCapacityWaiter = class {
33765
+ completion = Promise.withResolvers();
33766
+ signal;
33767
+ constructor(signal) {
33768
+ this.signal = signal;
33769
+ }
33770
+ cancel = () => {
33771
+ try {
33772
+ this.signal.throwIfAborted();
33773
+ } catch (error62) {
33774
+ this.completion.reject(error62);
33775
+ }
33776
+ };
33777
+ };
33778
+ var AcpProcessCapacityLock = class {
33779
+ #locked = false;
33780
+ #waiters = [];
33781
+ acquire = async (signal) => {
33782
+ signal.throwIfAborted();
33783
+ if (!this.#locked) {
33784
+ this.#locked = true;
33785
+ return new AcpProcessCapacityLease(this.#release);
33786
+ }
33787
+ const waiter = new AcpProcessCapacityWaiter(signal);
33788
+ this.#waiters.push(waiter);
33789
+ signal.addEventListener("abort", waiter.cancel, { once: true });
33790
+ if (signal.aborted) {
33791
+ waiter.cancel();
33792
+ }
33793
+ try {
33794
+ return await waiter.completion.promise;
33795
+ } finally {
33796
+ signal.removeEventListener("abort", waiter.cancel);
33797
+ const index2 = this.#waiters.indexOf(waiter);
33798
+ if (index2 >= 0) {
33799
+ this.#waiters.splice(index2, 1);
33800
+ }
33801
+ }
33802
+ };
33803
+ #release = () => {
33804
+ while (this.#waiters.length > 0) {
33805
+ const waiter = this.#waiters.shift();
33806
+ if (waiter === void 0 || waiter.signal.aborted) {
33807
+ continue;
33808
+ }
33809
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
33810
+ return;
33811
+ }
33812
+ this.#locked = false;
33813
+ };
33814
+ };
33815
+ async function waitForAcpProcessCapacity(completion, signal) {
33816
+ signal.throwIfAborted();
33817
+ const cancelled = Promise.withResolvers();
33818
+ const cancel = () => {
33819
+ try {
33820
+ signal.throwIfAborted();
33821
+ } catch (error62) {
33822
+ cancelled.reject(error62);
33823
+ }
33824
+ };
33825
+ signal.addEventListener("abort", cancel, { once: true });
33826
+ if (signal.aborted) {
33827
+ cancel();
33828
+ }
33829
+ try {
33830
+ await Promise.race([completion, cancelled.promise]);
33831
+ } finally {
33832
+ signal.removeEventListener("abort", cancel);
33833
+ }
33834
+ }
34394
33835
  function readableWebStream(input2) {
34395
33836
  let streamOpen = true;
34396
33837
  return new ReadableStream({
@@ -35019,6 +34460,13 @@ var AcpProcessSession = class _AcpProcessSession {
35019
34460
  return await this.importRaster(raster, signal);
35020
34461
  }
35021
34462
  }
34463
+ if (content3.type === "video" && content3.data.length > 0) {
34464
+ const video = readInlineVideo(content3.data, content3.mimeType, content3.name);
34465
+ if (video === null) {
34466
+ return { ...content3, data: "" };
34467
+ }
34468
+ return await this.importVideo(video, AbortSignal.timeout(2e4));
34469
+ }
35022
34470
  return content3;
35023
34471
  };
35024
34472
  emitAgentContent = async (content3, messageId) => {
@@ -35044,7 +34492,7 @@ var AcpProcessSession = class _AcpProcessSession {
35044
34492
  });
35045
34493
  };
35046
34494
  importRaster = async (raster, signal) => {
35047
- const artifactId = await this.#getObserver().importLocalImage(this.#mobiusSessionId, raster, signal);
34495
+ const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, raster, signal);
35048
34496
  return imageDisplayContent(
35049
34497
  raster.mimeType,
35050
34498
  raster.name,
@@ -35052,6 +34500,22 @@ var AcpProcessSession = class _AcpProcessSession {
35052
34500
  artifactId
35053
34501
  );
35054
34502
  };
34503
+ importVideo = async (video, signal) => {
34504
+ const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, video, signal);
34505
+ return {
34506
+ artifactId,
34507
+ data: artifactId.length > 0 ? "" : video.base64(),
34508
+ mimeType: video.mimeType,
34509
+ name: video.name,
34510
+ newText: "",
34511
+ oldText: "",
34512
+ path: "",
34513
+ terminalId: "",
34514
+ text: "",
34515
+ type: "video",
34516
+ uri: ""
34517
+ };
34518
+ };
35055
34519
  async #initializeAgent(signal) {
35056
34520
  await this.#metrics.measure("agent-initialize", async () => await this.#initializeAgentOperation(signal));
35057
34521
  }
@@ -35878,20 +35342,23 @@ var AcpProcessSession = class _AcpProcessSession {
35878
35342
  }
35879
35343
  };
35880
35344
  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 {
35345
+ try {
35346
+ await this.cancelPendingInteractions();
35347
+ if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
35348
+ try {
35349
+ await this.#connection.agent.request(
35350
+ methods6.agent.session.close,
35351
+ { sessionId: this.#nativeSessionId },
35352
+ {
35353
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
35354
+ }
35355
+ );
35356
+ } catch {
35357
+ }
35892
35358
  }
35359
+ } finally {
35360
+ await this.closeProcess();
35893
35361
  }
35894
- await this.closeProcess();
35895
35362
  };
35896
35363
  closeProcess = async (capturedProcesses = []) => {
35897
35364
  try {
@@ -35998,6 +35465,31 @@ var AcpProcessSession = class _AcpProcessSession {
35998
35465
  }
35999
35466
  };
36000
35467
  };
35468
+ var AcpProcessEvictionCandidate = class {
35469
+ };
35470
+ var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
35471
+ };
35472
+ var FoundAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
35473
+ runtime;
35474
+ constructor(runtime) {
35475
+ super();
35476
+ this.runtime = runtime;
35477
+ }
35478
+ };
35479
+ var FoundAcpSessionProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
35480
+ sessionId;
35481
+ constructor(sessionId, runtime) {
35482
+ super(runtime);
35483
+ this.sessionId = sessionId;
35484
+ }
35485
+ };
35486
+ var FoundAcpNativeBrowserProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
35487
+ sessionId;
35488
+ constructor(sessionId, runtime) {
35489
+ super(runtime);
35490
+ this.sessionId = sessionId;
35491
+ }
35492
+ };
36001
35493
  var AcpSessionManager = class {
36002
35494
  #activeCommandIds = /* @__PURE__ */ new Map();
36003
35495
  #agentSettingsObserver = new NullAcpSessionObserver();
@@ -36006,10 +35498,18 @@ var AcpSessionManager = class {
36006
35498
  #nativeBrowserPreparing = /* @__PURE__ */ new Map();
36007
35499
  #nativeBrowserSessions = /* @__PURE__ */ new Map();
36008
35500
  #nativeBrowserStore = new MemoryAcpSessionStore();
35501
+ #nativeBrowserUseCounts = /* @__PURE__ */ new Map();
36009
35502
  #activeSessionIds = /* @__PURE__ */ new Set();
36010
35503
  #cancellationRequests = /* @__PURE__ */ new Map();
36011
35504
  #preparing = /* @__PURE__ */ new Map();
35505
+ #processCapacityChanged = Promise.withResolvers();
35506
+ #processCapacityLock = new AcpProcessCapacityLock();
35507
+ #retainedProcesses = /* @__PURE__ */ new Map();
35508
+ #retiringProcessCount = 0;
35509
+ #sessionUseCounts = /* @__PURE__ */ new Map();
36012
35510
  #sessions = /* @__PURE__ */ new Map();
35511
+ #startingProcessCount = 0;
35512
+ #transientProcessCount = 0;
36013
35513
  #store;
36014
35514
  #observer;
36015
35515
  constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore()) {
@@ -36019,18 +35519,230 @@ var AcpSessionManager = class {
36019
35519
  setObserver = (observer) => {
36020
35520
  this.#observer = observer;
36021
35521
  };
35522
+ #notifyProcessCapacityChanged() {
35523
+ const changed = this.#processCapacityChanged;
35524
+ this.#processCapacityChanged = Promise.withResolvers();
35525
+ changed.resolve();
35526
+ }
35527
+ #touchSession(sessionId) {
35528
+ const runtime = this.#sessions.get(sessionId);
35529
+ if (runtime === void 0) {
35530
+ return;
35531
+ }
35532
+ this.#touchProcess(runtime);
35533
+ }
35534
+ #touchExpectedSession(sessionId, expected) {
35535
+ if (this.#sessions.get(sessionId) !== expected) {
35536
+ return;
35537
+ }
35538
+ this.#touchProcess(expected);
35539
+ }
35540
+ #touchNativeBrowserSession(sessionId) {
35541
+ const runtime = this.#nativeBrowserSessions.get(sessionId);
35542
+ if (runtime === void 0) {
35543
+ return;
35544
+ }
35545
+ this.#touchProcess(runtime);
35546
+ }
35547
+ #touchExpectedNativeBrowserSession(sessionId, expected) {
35548
+ if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
35549
+ return;
35550
+ }
35551
+ this.#touchProcess(expected);
35552
+ }
35553
+ #touchProcess(runtime) {
35554
+ const retained = this.#retainedProcesses.get(runtime);
35555
+ if (retained === void 0) {
35556
+ return;
35557
+ }
35558
+ this.#retainedProcesses.delete(runtime);
35559
+ this.#retainedProcesses.set(runtime, retained);
35560
+ }
35561
+ #beginSessionUse(sessionId) {
35562
+ this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
35563
+ this.#touchSession(sessionId);
35564
+ }
35565
+ #endSessionUse(sessionId) {
35566
+ const count = this.#sessionUseCounts.get(sessionId) ?? 0;
35567
+ if (count <= 1) {
35568
+ this.#sessionUseCounts.delete(sessionId);
35569
+ } else {
35570
+ this.#sessionUseCounts.set(sessionId, count - 1);
35571
+ }
35572
+ this.#touchSession(sessionId);
35573
+ this.#notifyProcessCapacityChanged();
35574
+ }
35575
+ #beginNativeBrowserUse(sessionId) {
35576
+ this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
35577
+ this.#touchNativeBrowserSession(sessionId);
35578
+ }
35579
+ #endNativeBrowserUse(sessionId) {
35580
+ const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
35581
+ if (count <= 1) {
35582
+ this.#nativeBrowserUseCounts.delete(sessionId);
35583
+ } else {
35584
+ this.#nativeBrowserUseCounts.set(sessionId, count - 1);
35585
+ }
35586
+ this.#touchNativeBrowserSession(sessionId);
35587
+ this.#notifyProcessCapacityChanged();
35588
+ }
35589
+ #isNativeSessionOperationActive(sessionId) {
35590
+ const stored = this.#store.read(sessionId);
35591
+ return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
35592
+ }
35593
+ #leastRecentlyUsedEvictionCandidate() {
35594
+ for (const candidate of this.#retainedProcesses.values()) {
35595
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
35596
+ 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)) {
35597
+ continue;
35598
+ }
35599
+ return candidate;
35600
+ }
35601
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate && !this.#nativeBrowserPreparing.has(candidate.sessionId) && (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
35602
+ return candidate;
35603
+ }
35604
+ }
35605
+ return new MissingAcpProcessEvictionCandidate();
35606
+ }
35607
+ #ownedProcessCount() {
35608
+ return this.#retainedProcesses.size + this.#startingProcessCount + this.#transientProcessCount + this.#retiringProcessCount;
35609
+ }
35610
+ async #retireProcess(runtime, retained, close) {
35611
+ if (retained) {
35612
+ this.#retainedProcesses.delete(runtime);
35613
+ this.#retiringProcessCount += 1;
35614
+ }
35615
+ try {
35616
+ await close();
35617
+ } finally {
35618
+ if (retained) {
35619
+ this.#retiringProcessCount -= 1;
35620
+ this.#notifyProcessCapacityChanged();
35621
+ }
35622
+ }
35623
+ }
35624
+ async #retireSessionProcess(sessionId, runtime, close) {
35625
+ const retained = this.#sessions.get(sessionId) === runtime;
35626
+ if (retained) {
35627
+ this.#sessions.delete(sessionId);
35628
+ }
35629
+ await this.#retireProcess(runtime, retained, close);
35630
+ }
35631
+ async #retireNativeBrowserProcess(sessionId, runtime, close) {
35632
+ const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
35633
+ if (retained) {
35634
+ this.#nativeBrowserSessions.delete(sessionId);
35635
+ this.#nativeBrowserStore.remove(sessionId);
35636
+ }
35637
+ await this.#retireProcess(runtime, retained, close);
35638
+ }
35639
+ async #reserveProcessCapacity(signal) {
35640
+ const lease = await this.#processCapacityLock.acquire(signal);
35641
+ try {
35642
+ for (; ; ) {
35643
+ signal.throwIfAborted();
35644
+ if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
35645
+ this.#startingProcessCount += 1;
35646
+ return;
35647
+ }
35648
+ const candidate = this.#leastRecentlyUsedEvictionCandidate();
35649
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
35650
+ await this.#retireSessionProcess(
35651
+ candidate.sessionId,
35652
+ candidate.runtime,
35653
+ async () => await candidate.runtime.close()
35654
+ );
35655
+ continue;
35656
+ }
35657
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
35658
+ await this.#retireNativeBrowserProcess(
35659
+ candidate.sessionId,
35660
+ candidate.runtime,
35661
+ async () => await candidate.runtime.close()
35662
+ );
35663
+ continue;
35664
+ }
35665
+ const changed = this.#processCapacityChanged.promise;
35666
+ await waitForAcpProcessCapacity(changed, signal);
35667
+ }
35668
+ } finally {
35669
+ lease.release();
35670
+ }
35671
+ }
35672
+ async #startRetainedSessionProcess(options, start) {
35673
+ await this.#reserveProcessCapacity(options.signal);
35674
+ try {
35675
+ const runtime = await start();
35676
+ this.#startingProcessCount -= 1;
35677
+ this.#sessions.set(options.sessionId, runtime);
35678
+ this.#retainedProcesses.set(
35679
+ runtime,
35680
+ new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime)
35681
+ );
35682
+ this.#notifyProcessCapacityChanged();
35683
+ return runtime;
35684
+ } catch (error62) {
35685
+ this.#startingProcessCount -= 1;
35686
+ this.#notifyProcessCapacityChanged();
35687
+ throw error62;
35688
+ }
35689
+ }
35690
+ async #startRetainedNativeBrowserProcess(options, start) {
35691
+ await this.#reserveProcessCapacity(options.signal);
35692
+ try {
35693
+ const runtime = await start();
35694
+ this.#startingProcessCount -= 1;
35695
+ this.#nativeBrowserSessions.set(options.sessionId, runtime);
35696
+ this.#retainedProcesses.set(
35697
+ runtime,
35698
+ new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime)
35699
+ );
35700
+ this.#notifyProcessCapacityChanged();
35701
+ return runtime;
35702
+ } catch (error62) {
35703
+ this.#startingProcessCount -= 1;
35704
+ this.#notifyProcessCapacityChanged();
35705
+ throw error62;
35706
+ }
35707
+ }
35708
+ async #runWithTransientProcess(signal, start, operation, close) {
35709
+ await this.#reserveProcessCapacity(signal);
35710
+ let runtime;
35711
+ try {
35712
+ runtime = await start();
35713
+ } catch (error62) {
35714
+ this.#startingProcessCount -= 1;
35715
+ this.#notifyProcessCapacityChanged();
35716
+ throw error62;
35717
+ }
35718
+ this.#startingProcessCount -= 1;
35719
+ this.#transientProcessCount += 1;
35720
+ this.#notifyProcessCapacityChanged();
35721
+ try {
35722
+ return await operation(runtime);
35723
+ } finally {
35724
+ try {
35725
+ await close(runtime);
35726
+ } finally {
35727
+ this.#transientProcessCount -= 1;
35728
+ this.#notifyProcessCapacityChanged();
35729
+ }
35730
+ }
35731
+ }
36022
35732
  async #startNativeBrowserPreparation(options) {
36023
35733
  const operation = (async () => {
36024
35734
  try {
36025
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35735
+ return await this.#startRetainedNativeBrowserProcess(
36026
35736
  options,
36027
- () => this.#nativeBrowserObserver,
36028
- this.#nativeBrowserStore
35737
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35738
+ options,
35739
+ () => this.#nativeBrowserObserver,
35740
+ this.#nativeBrowserStore
35741
+ )
36029
35742
  );
36030
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
36031
- return runtime;
36032
35743
  } finally {
36033
35744
  this.#nativeBrowserPreparing.delete(options.sessionId);
35745
+ this.#notifyProcessCapacityChanged();
36034
35746
  }
36035
35747
  })();
36036
35748
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -36039,18 +35751,18 @@ var AcpSessionManager = class {
36039
35751
  async #replaceNativeBrowserPreparation(existing, options) {
36040
35752
  const operation = (async () => {
36041
35753
  try {
36042
- this.#nativeBrowserSessions.delete(options.sessionId);
36043
- await existing.close();
36044
- this.#nativeBrowserStore.remove(options.sessionId);
36045
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35754
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
35755
+ return await this.#startRetainedNativeBrowserProcess(
36046
35756
  options,
36047
- () => this.#nativeBrowserObserver,
36048
- this.#nativeBrowserStore
35757
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35758
+ options,
35759
+ () => this.#nativeBrowserObserver,
35760
+ this.#nativeBrowserStore
35761
+ )
36049
35762
  );
36050
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
36051
- return runtime;
36052
35763
  } finally {
36053
35764
  this.#nativeBrowserPreparing.delete(options.sessionId);
35765
+ this.#notifyProcessCapacityChanged();
36054
35766
  }
36055
35767
  })();
36056
35768
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -36059,11 +35771,13 @@ var AcpSessionManager = class {
36059
35771
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
36060
35772
  const operation = (async () => {
36061
35773
  try {
36062
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
36063
- this.#sessions.set(options.sessionId, runtime);
36064
- return runtime;
35774
+ return await this.#startRetainedSessionProcess(
35775
+ options,
35776
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35777
+ );
36065
35778
  } finally {
36066
35779
  this.#preparing.delete(options.sessionId);
35780
+ this.#notifyProcessCapacityChanged();
36067
35781
  }
36068
35782
  })();
36069
35783
  this.#preparing.set(options.sessionId, operation);
@@ -36072,17 +35786,19 @@ var AcpSessionManager = class {
36072
35786
  async #startSessionForkAtTurnPreparation(options, sourceNativeSessionId, forkPoint) {
36073
35787
  const operation = (async () => {
36074
35788
  try {
36075
- const runtime = await AcpProcessSession.startSessionForkAtTurn(
35789
+ return await this.#startRetainedSessionProcess(
36076
35790
  options,
36077
- sourceNativeSessionId,
36078
- forkPoint,
36079
- () => this.#observer,
36080
- this.#store
35791
+ async () => await AcpProcessSession.startSessionForkAtTurn(
35792
+ options,
35793
+ sourceNativeSessionId,
35794
+ forkPoint,
35795
+ () => this.#observer,
35796
+ this.#store
35797
+ )
36081
35798
  );
36082
- this.#sessions.set(options.sessionId, runtime);
36083
- return runtime;
36084
35799
  } finally {
36085
35800
  this.#preparing.delete(options.sessionId);
35801
+ this.#notifyProcessCapacityChanged();
36086
35802
  }
36087
35803
  })();
36088
35804
  this.#preparing.set(options.sessionId, operation);
@@ -36091,14 +35807,19 @@ var AcpSessionManager = class {
36091
35807
  async #replacePreparation(existing, options, metrics) {
36092
35808
  const operation = (async () => {
36093
35809
  try {
36094
- this.#sessions.delete(options.sessionId);
36095
- await metrics.measure("runtime-replacement-close", async () => await existing.close());
35810
+ await this.#retireSessionProcess(
35811
+ options.sessionId,
35812
+ existing,
35813
+ async () => await metrics.measure("runtime-replacement-close", async () => await existing.close())
35814
+ );
36096
35815
  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;
35816
+ return await this.#startRetainedSessionProcess(
35817
+ options,
35818
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35819
+ );
36100
35820
  } finally {
36101
35821
  this.#preparing.delete(options.sessionId);
35822
+ this.#notifyProcessCapacityChanged();
36102
35823
  }
36103
35824
  })();
36104
35825
  this.#preparing.set(options.sessionId, operation);
@@ -36108,10 +35829,12 @@ var AcpSessionManager = class {
36108
35829
  const desiredConfigOptions = existing.prepared().configOptions;
36109
35830
  const operation = (async () => {
36110
35831
  try {
36111
- this.#sessions.delete(options.sessionId);
36112
- await existing.close();
35832
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
36113
35833
  this.#store.remove(options.sessionId);
36114
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
35834
+ const runtime = await this.#startRetainedSessionProcess(
35835
+ options,
35836
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
35837
+ );
36115
35838
  try {
36116
35839
  for (const desired of desiredConfigOptions) {
36117
35840
  const current = runtime.prepared().configOptions.find((option2) => option2.id === desired.id);
@@ -36143,14 +35866,14 @@ var AcpSessionManager = class {
36143
35866
  }
36144
35867
  }
36145
35868
  } catch (error62) {
36146
- await runtime.close();
35869
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
36147
35870
  this.#store.remove(options.sessionId);
36148
35871
  throw error62;
36149
35872
  }
36150
- this.#sessions.set(options.sessionId, runtime);
36151
35873
  return runtime;
36152
35874
  } finally {
36153
35875
  this.#preparing.delete(options.sessionId);
35876
+ this.#notifyProcessCapacityChanged();
36154
35877
  }
36155
35878
  })();
36156
35879
  this.#preparing.set(options.sessionId, operation);
@@ -36172,6 +35895,7 @@ var AcpSessionManager = class {
36172
35895
  if (pending !== void 0) {
36173
35896
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
36174
35897
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35898
+ this.#touchExpectedSession(options.sessionId, runtime2);
36175
35899
  return runtime2.prepared();
36176
35900
  }
36177
35901
  return await this.prepareSession(options, metrics);
@@ -36179,6 +35903,7 @@ var AcpSessionManager = class {
36179
35903
  const existing = this.#sessions.get(options.sessionId);
36180
35904
  if (existing !== void 0) {
36181
35905
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35906
+ this.#touchExpectedSession(options.sessionId, existing);
36182
35907
  return existing.prepared();
36183
35908
  }
36184
35909
  if (!existing.canRebind()) {
@@ -36199,22 +35924,24 @@ var AcpSessionManager = class {
36199
35924
  * authoritative settings. Its identity and store are private to this
36200
35925
  * operation and never become a Mobius Session.
36201
35926
  */
36202
- inspectAgentSettings = async (options) => {
36203
- const runtime = await AcpProcessSession.start(
35927
+ inspectAgentSettings = async (options) => await this.#runWithTransientProcess(
35928
+ options.signal,
35929
+ async () => await AcpProcessSession.start(
36204
35930
  {
36205
35931
  ...options,
36206
35932
  sessionId: `agent-settings-${crypto.randomUUID()}`
36207
35933
  },
36208
35934
  () => this.#agentSettingsObserver,
36209
35935
  new MemoryAcpSessionStore()
36210
- );
36211
- try {
35936
+ ),
35937
+ (runtime) => {
36212
35938
  const prepared = runtime.prepared();
36213
- return new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions);
36214
- } finally {
36215
- await runtime.close();
36216
- }
36217
- };
35939
+ return Promise.resolve(
35940
+ new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions)
35941
+ );
35942
+ },
35943
+ async (runtime) => await runtime.close()
35944
+ );
36218
35945
  /**
36219
35946
  * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
36220
35947
  * Use inspectAgentSettings for Agent-scoped settings discovery.
@@ -36223,18 +35950,20 @@ var AcpSessionManager = class {
36223
35950
  if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
36224
35951
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
36225
35952
  }
36226
- const runtime = await this.#startPreparation(options, metrics);
35953
+ this.#beginSessionUse(options.sessionId);
36227
35954
  try {
36228
- return runtime.prepared();
36229
- } finally {
36230
- if (this.#sessions.get(options.sessionId) === runtime) {
36231
- this.#sessions.delete(options.sessionId);
36232
- }
35955
+ const runtime = await this.#startPreparation(options, metrics);
36233
35956
  try {
36234
- await runtime.close();
35957
+ return runtime.prepared();
36235
35958
  } finally {
36236
- this.#store.remove(options.sessionId);
35959
+ try {
35960
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
35961
+ } finally {
35962
+ this.#store.remove(options.sessionId);
35963
+ }
36237
35964
  }
35965
+ } finally {
35966
+ this.#endSessionUse(options.sessionId);
36238
35967
  }
36239
35968
  };
36240
35969
  prepareExecutionSession = async (options) => {
@@ -36255,6 +35984,7 @@ var AcpSessionManager = class {
36255
35984
  );
36256
35985
  }
36257
35986
  if (existing.usesEnvironment(options.agent.environment)) {
35987
+ this.#touchExpectedSession(options.sessionId, existing);
36258
35988
  return existing.prepared();
36259
35989
  }
36260
35990
  if (!existing.canRebind()) {
@@ -36271,6 +36001,7 @@ var AcpSessionManager = class {
36271
36001
  if (pending !== void 0) {
36272
36002
  const runtime2 = await pending;
36273
36003
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
36004
+ this.#touchExpectedNativeBrowserSession(options.sessionId, runtime2);
36274
36005
  return runtime2.prepared();
36275
36006
  }
36276
36007
  return await this.prepareNativeSessionBrowser(options);
@@ -36278,6 +36009,7 @@ var AcpSessionManager = class {
36278
36009
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
36279
36010
  if (existing !== void 0) {
36280
36011
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
36012
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
36281
36013
  return existing.prepared();
36282
36014
  }
36283
36015
  if (!existing.canRebind()) {
@@ -36294,8 +36026,13 @@ var AcpSessionManager = class {
36294
36026
  return runtime.prepared();
36295
36027
  };
36296
36028
  configureSession = async (options) => {
36297
- const runtime = await this.ensureSession(options);
36298
- return await runtime.configure(options);
36029
+ this.#beginSessionUse(options.sessionId);
36030
+ try {
36031
+ const runtime = await this.ensureSession(options);
36032
+ return await runtime.configure(options);
36033
+ } finally {
36034
+ this.#endSessionUse(options.sessionId);
36035
+ }
36299
36036
  };
36300
36037
  cancelPrompt = async (sessionId) => {
36301
36038
  const existing = this.#cancellationRequests.get(sessionId);
@@ -36311,6 +36048,8 @@ var AcpSessionManager = class {
36311
36048
  } finally {
36312
36049
  if (this.#sessions.get(sessionId) === runtime) {
36313
36050
  this.#sessions.delete(sessionId);
36051
+ this.#retainedProcesses.delete(runtime);
36052
+ this.#notifyProcessCapacityChanged();
36314
36053
  }
36315
36054
  }
36316
36055
  }
@@ -36400,10 +36139,7 @@ var AcpSessionManager = class {
36400
36139
  return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
36401
36140
  } catch (error62) {
36402
36141
  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();
36142
+ await this.#cancellationRequests.get(options.sessionId);
36407
36143
  return { stopReason: "cancelled" };
36408
36144
  }
36409
36145
  throw error62;
@@ -36411,8 +36147,11 @@ var AcpSessionManager = class {
36411
36147
  } catch (error62) {
36412
36148
  const failedRuntime = this.#sessions.get(options.sessionId);
36413
36149
  if (failedRuntime !== void 0) {
36414
- this.#sessions.delete(options.sessionId);
36415
- await failedRuntime.close();
36150
+ await this.#retireSessionProcess(
36151
+ options.sessionId,
36152
+ failedRuntime,
36153
+ async () => await failedRuntime.close()
36154
+ );
36416
36155
  }
36417
36156
  if (this.#cancellationRequests.has(options.sessionId)) {
36418
36157
  return { stopReason: "cancelled" };
@@ -36433,6 +36172,8 @@ var AcpSessionManager = class {
36433
36172
  this.#activeCommandIds.delete(options.sessionId);
36434
36173
  }
36435
36174
  this.#cancellationRequests.delete(options.sessionId);
36175
+ this.#touchSession(options.sessionId);
36176
+ this.#notifyProcessCapacityChanged();
36436
36177
  }
36437
36178
  }
36438
36179
  };
@@ -36451,11 +36192,16 @@ var AcpSessionManager = class {
36451
36192
  await runtime.respondElicitation(options);
36452
36193
  };
36453
36194
  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()));
36195
+ const sessions = [...this.#sessions.entries()];
36196
+ const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
36197
+ await Promise.all([
36198
+ ...sessions.map(
36199
+ async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
36200
+ ),
36201
+ ...nativeBrowserSessions.map(
36202
+ async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
36203
+ )
36204
+ ]);
36459
36205
  };
36460
36206
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
36461
36207
  ensureSession = async (options) => {
@@ -36468,6 +36214,7 @@ var AcpSessionManager = class {
36468
36214
  "session_identity_mismatch"
36469
36215
  );
36470
36216
  }
36217
+ this.#touchExpectedSession(options.sessionId, existing);
36471
36218
  return existing;
36472
36219
  }
36473
36220
  await this.prepareSession(options);
@@ -36487,6 +36234,7 @@ var AcpSessionManager = class {
36487
36234
  "session_identity_mismatch"
36488
36235
  );
36489
36236
  }
36237
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
36490
36238
  return existing;
36491
36239
  }
36492
36240
  await this.prepareNativeSessionBrowser(options);
@@ -36496,7 +36244,14 @@ var AcpSessionManager = class {
36496
36244
  }
36497
36245
  return started;
36498
36246
  }
36499
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
36247
+ listNativeSessions = async (options, cursor) => {
36248
+ this.#beginNativeBrowserUse(options.sessionId);
36249
+ try {
36250
+ return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
36251
+ } finally {
36252
+ this.#endNativeBrowserUse(options.sessionId);
36253
+ }
36254
+ };
36500
36255
  previewNativeSession = async (options, nativeSessionId) => {
36501
36256
  const key = `${options.agent.id}:${nativeSessionId}`;
36502
36257
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
@@ -36509,17 +36264,19 @@ var AcpSessionManager = class {
36509
36264
  }
36510
36265
  this.#nativeOperations.add(key);
36511
36266
  try {
36512
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
36513
- options,
36514
- () => this.#nativeBrowserObserver,
36515
- new MemoryAcpSessionStore()
36267
+ return await this.#runWithTransientProcess(
36268
+ options.signal,
36269
+ async () => await AcpProcessSession.startNativeSessionBrowser(
36270
+ options,
36271
+ () => this.#nativeBrowserObserver,
36272
+ new MemoryAcpSessionStore()
36273
+ ),
36274
+ async (runtime) => {
36275
+ runtime.selectNativeSession(nativeSessionId);
36276
+ return await runtime.loadHistory(options.signal);
36277
+ },
36278
+ async (runtime) => await runtime.closeProcess()
36516
36279
  );
36517
- try {
36518
- runtime.selectNativeSession(nativeSessionId);
36519
- return await runtime.loadHistory(options.signal);
36520
- } finally {
36521
- await runtime.closeProcess();
36522
- }
36523
36280
  } finally {
36524
36281
  this.#nativeOperations.delete(key);
36525
36282
  }
@@ -36539,36 +36296,46 @@ var AcpSessionManager = class {
36539
36296
  }
36540
36297
  const existing = linked[0];
36541
36298
  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);
36299
+ this.#beginSessionUse(existing.sessionId);
36554
36300
  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;
36301
+ const runtime = await this.ensureSession({
36302
+ ...options,
36303
+ sessionId: existing.sessionId
36304
+ });
36305
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
36306
+ throw new AcpExecutionError(
36307
+ "Wait for the native session's running operation to finish",
36308
+ {},
36309
+ "session_busy"
36310
+ );
36311
+ }
36312
+ this.#nativeOperations.add(key);
36313
+ try {
36314
+ const history = await runtime.loadHistory(options.signal);
36315
+ return {
36316
+ prepared: runtime.prepared(),
36317
+ sessionId: existing.sessionId,
36318
+ history
36319
+ };
36320
+ } catch (error62) {
36321
+ await this.#retireSessionProcess(
36322
+ existing.sessionId,
36323
+ runtime,
36324
+ async () => await runtime.closeProcess()
36325
+ );
36326
+ throw error62;
36327
+ } finally {
36328
+ this.#nativeOperations.delete(key);
36329
+ this.#notifyProcessCapacityChanged();
36330
+ }
36565
36331
  } finally {
36566
- this.#nativeOperations.delete(key);
36332
+ this.#endSessionUse(existing.sessionId);
36567
36333
  }
36568
36334
  }
36569
36335
  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
36336
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
36571
36337
  }
36338
+ this.#beginSessionUse(options.sessionId);
36572
36339
  this.#nativeOperations.add(key);
36573
36340
  try {
36574
36341
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -36582,23 +36349,23 @@ var AcpSessionManager = class {
36582
36349
  history
36583
36350
  };
36584
36351
  } catch (error62) {
36585
- this.#sessions.delete(options.sessionId);
36586
36352
  this.#store.remove(options.sessionId);
36587
- await runtime.closeProcess();
36353
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
36588
36354
  throw error62;
36589
36355
  } finally {
36590
36356
  this.#nativeOperations.delete(openedKey);
36357
+ this.#notifyProcessCapacityChanged();
36591
36358
  }
36592
36359
  } catch (error62) {
36593
36360
  this.#store.remove(options.sessionId);
36594
36361
  const runtime = this.#sessions.get(options.sessionId);
36595
- this.#sessions.delete(options.sessionId);
36596
36362
  if (runtime !== void 0) {
36597
- await runtime.closeProcess();
36363
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
36598
36364
  }
36599
36365
  throw error62;
36600
36366
  } finally {
36601
36367
  this.#nativeOperations.delete(key);
36368
+ this.#endSessionUse(options.sessionId);
36602
36369
  }
36603
36370
  };
36604
36371
  forkSessionAtTurn = async (options, sourceSessionId, forkPoint) => {
@@ -36636,6 +36403,7 @@ var AcpSessionManager = class {
36636
36403
  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
36404
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
36638
36405
  }
36406
+ this.#beginSessionUse(options.sessionId);
36639
36407
  this.#nativeOperations.add(key);
36640
36408
  try {
36641
36409
  const runtime = await this.#startSessionForkAtTurnPreparation(
@@ -36652,48 +36420,58 @@ var AcpSessionManager = class {
36652
36420
  sessionId: options.sessionId
36653
36421
  };
36654
36422
  } catch (error62) {
36655
- this.#sessions.delete(options.sessionId);
36656
36423
  this.#store.remove(options.sessionId);
36657
- await runtime.closeProcess();
36424
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
36658
36425
  throw error62;
36659
36426
  } finally {
36660
36427
  this.#nativeOperations.delete(openedKey);
36428
+ this.#notifyProcessCapacityChanged();
36661
36429
  }
36662
36430
  } finally {
36663
36431
  this.#nativeOperations.delete(key);
36432
+ this.#endSessionUse(options.sessionId);
36664
36433
  }
36665
36434
  };
36666
36435
  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);
36436
+ this.#beginNativeBrowserUse(options.sessionId);
36678
36437
  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();
36438
+ const runtime = await this.#ensureNativeSessionBrowser(options);
36439
+ const key = `${options.agent.id}:${nativeSessionId}`;
36440
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
36441
+ if (this.#nativeOperations.has(key) || linked.some(
36442
+ (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
36443
+ )) {
36444
+ throw new AcpExecutionError(
36445
+ "Wait for the native session's running operation to finish",
36446
+ {},
36447
+ "session_busy"
36448
+ );
36449
+ }
36450
+ this.#nativeOperations.add(key);
36451
+ try {
36452
+ for (const entry of linked) {
36453
+ const active = this.#sessions.get(entry.sessionId);
36454
+ if (active !== void 0 && active !== runtime) {
36455
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
36456
+ }
36457
+ }
36458
+ options.signal.throwIfAborted();
36459
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
36460
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
36461
+ if (runtime.nativeSessionId() === nativeSessionId) {
36462
+ await this.#retireNativeBrowserProcess(
36463
+ options.sessionId,
36464
+ runtime,
36465
+ async () => await runtime.close()
36466
+ );
36684
36467
  }
36468
+ return deleted;
36469
+ } finally {
36470
+ this.#nativeOperations.delete(key);
36471
+ this.#notifyProcessCapacityChanged();
36685
36472
  }
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
36473
  } finally {
36696
- this.#nativeOperations.delete(key);
36474
+ this.#endNativeBrowserUse(options.sessionId);
36697
36475
  }
36698
36476
  };
36699
36477
  };
@@ -37238,7 +37016,7 @@ var FixedInstallationExecutor = class {
37238
37016
  };
37239
37017
 
37240
37018
  // src/artifacts/runtime-artifact-uploader.ts
37241
- import { createHash as createHash3 } from "node:crypto";
37019
+ import { createHash as createHash2 } from "node:crypto";
37242
37020
 
37243
37021
  // ../mobius-sdk/src/errors.ts
37244
37022
  var MobiusError = class extends Error {
@@ -37455,183 +37233,781 @@ var MobiusRuntimePairingLifecycle = Object.freeze({
37455
37233
  Revoked: "revoked"
37456
37234
  });
37457
37235
 
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 {
37236
+ // src/artifacts/runtime-artifact-uploader.ts
37237
+ import { fetch as fetch4 } from "undici";
37238
+ var UPLOAD_TIMEOUT_MILLISECONDS = 2e4;
37239
+ var RuntimeArtifactUploadError = class extends Error {
37240
+ code;
37241
+ constructor(code, message, options = {}) {
37242
+ super(message, options);
37243
+ this.code = code;
37244
+ this.name = "RuntimeArtifactUploadError";
37245
+ }
37246
+ };
37247
+ var UploadedRuntimeArtifact = class {
37248
+ artifactId;
37249
+ byteLength;
37250
+ mimeType;
37251
+ name;
37252
+ sha256;
37253
+ constructor(artifactId, name, mimeType, byteLength, sha256) {
37254
+ this.artifactId = artifactId;
37255
+ this.byteLength = byteLength;
37256
+ this.mimeType = mimeType;
37257
+ this.name = name;
37258
+ this.sha256 = sha256;
37259
+ }
37260
+ };
37261
+ function daemonToken(config2) {
37262
+ const token = config2.relayUrl.searchParams.get("token");
37263
+ if (token === null || token.length < 32) {
37264
+ throw new RuntimeArtifactUploadError("artifact_endpoint_invalid", "The Relay daemon token is missing");
37265
+ }
37266
+ return token;
37267
+ }
37268
+ function channelOrigin(config2) {
37269
+ const url2 = new URL(config2.relayUrl);
37270
+ url2.protocol = url2.protocol === "wss:" ? "https:" : "http:";
37271
+ let channelPath = "";
37272
+ if (url2.pathname.endsWith("/daemon")) {
37273
+ channelPath = url2.pathname.slice(0, -"/daemon".length);
37274
+ } else {
37275
+ const runtimePath = `${MOBIUS_API_PREFIX}/v1/runtimes/connect`;
37276
+ if (!url2.pathname.endsWith("/v1/runtimes/connect") && !url2.pathname.endsWith(runtimePath)) {
37277
+ throw new RuntimeArtifactUploadError("artifact_endpoint_invalid", "The Relay artifact endpoint is invalid");
37278
+ }
37279
+ channelPath = `${url2.pathname.replace(/\/v1\/runtimes\/connect$/, "")}/channels/${encodeURIComponent(config2.channelId)}`;
37280
+ }
37281
+ url2.pathname = channelPath;
37282
+ url2.search = "";
37283
+ url2.hash = "";
37284
+ return url2;
37285
+ }
37286
+ function uploadError(code, message, cause) {
37287
+ return new RuntimeArtifactUploadError(code, message, cause === void 0 ? {} : { cause });
37288
+ }
37289
+ function translateSdkError(cause) {
37290
+ if (cause instanceof MobiusValidationError) {
37291
+ throw uploadError("artifact_upload_failed", cause.message, cause);
37292
+ }
37293
+ if (cause instanceof MobiusProtocolError) {
37294
+ throw uploadError("artifact_upload_failed", "The Relay returned an invalid upload response", cause);
37295
+ }
37296
+ throw cause;
37297
+ }
37298
+ async function readJson(response) {
37299
+ try {
37300
+ return await response.json();
37301
+ } catch (cause) {
37302
+ throw uploadError("artifact_upload_failed", "The Relay returned an invalid upload response", cause);
37303
+ }
37304
+ }
37305
+ async function readAuthorization(response) {
37306
+ try {
37307
+ return decodeMobiusArtifactUpload(await readJson(response));
37308
+ } catch (cause) {
37309
+ translateSdkError(cause);
37310
+ }
37311
+ }
37312
+ function sessionArtifactUrl(origin, sessionId, resourcePath, token) {
37313
+ const url2 = new URL(`${origin.pathname}/sessions/${encodeURIComponent(sessionId)}/${resourcePath}`, origin);
37314
+ url2.searchParams.set("token", token);
37315
+ return url2;
37316
+ }
37317
+ async function postLease(url2, request, signal) {
37318
+ return await fetch4(url2, {
37319
+ dispatcher: environmentProxyDispatcher,
37320
+ headers: { "content-type": "application/json" },
37321
+ method: "POST",
37322
+ body: JSON.stringify(request),
37323
+ signal
37324
+ });
37325
+ }
37326
+ async function putContent(url2, authorization, bytes, signal) {
37327
+ return await fetch4(url2, {
37328
+ dispatcher: environmentProxyDispatcher,
37329
+ headers: {
37330
+ "content-type": authorization.mediaType,
37331
+ "x-mobius-upload-token": authorization.uploadToken
37332
+ },
37333
+ method: "PUT",
37334
+ body: bytes,
37335
+ signal
37336
+ });
37337
+ }
37338
+ async function uploadRuntimeArtifact(config2, sessionId, artifact, signal) {
37339
+ signal.throwIfAborted();
37340
+ let request;
37341
+ try {
37342
+ request = new MobiusArtifactUploadRequest(
37343
+ artifact.name,
37344
+ artifact.mimeType,
37345
+ artifact.bytes.byteLength,
37346
+ createHash2("sha256").update(artifact.bytes).digest("hex")
37347
+ );
37348
+ } catch (cause) {
37349
+ translateSdkError(cause);
37350
+ }
37351
+ const timeoutSignal = AbortSignal.timeout(UPLOAD_TIMEOUT_MILLISECONDS);
37352
+ const requestSignal = AbortSignal.any([signal, timeoutSignal]);
37353
+ const origin = channelOrigin(config2);
37354
+ const token = daemonToken(config2);
37355
+ let created;
37356
+ try {
37357
+ created = await postLease(
37358
+ sessionArtifactUrl(origin, sessionId, "artifacts/uploads", token),
37359
+ request,
37360
+ requestSignal
37361
+ );
37362
+ } catch (cause) {
37363
+ signal.throwIfAborted();
37364
+ throw uploadError(
37365
+ timeoutSignal.aborted ? "artifact_upload_timeout" : "artifact_upload_failed",
37366
+ timeoutSignal.aborted ? "The artifact upload authorization timed out" : "The artifact upload could not start",
37367
+ cause
37368
+ );
37369
+ }
37370
+ if (!created.ok) {
37371
+ await created.body?.cancel();
37372
+ throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact upload");
37373
+ }
37374
+ const authorization = await readAuthorization(created);
37375
+ let uploaded;
37376
+ try {
37377
+ uploaded = await putContent(
37378
+ sessionArtifactUrl(
37379
+ origin,
37380
+ sessionId,
37381
+ `artifacts/${encodeURIComponent(authorization.artifactId)}/content`,
37382
+ token
37383
+ ),
37384
+ authorization,
37385
+ artifact.bytes,
37386
+ requestSignal
37387
+ );
37388
+ } catch (cause) {
37389
+ signal.throwIfAborted();
37390
+ throw uploadError(
37391
+ timeoutSignal.aborted ? "artifact_upload_timeout" : "artifact_upload_failed",
37392
+ timeoutSignal.aborted ? "The artifact upload timed out" : "The artifact content could not be uploaded",
37393
+ cause
37394
+ );
37395
+ }
37396
+ if (!uploaded.ok) {
37397
+ await uploaded.body?.cancel();
37398
+ throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact content");
37399
+ }
37400
+ try {
37401
+ const available = decodeMobiusAvailableArtifact(await readJson(uploaded));
37402
+ return new UploadedRuntimeArtifact(
37403
+ available.artifactId,
37404
+ available.name,
37405
+ available.mediaType,
37406
+ available.byteLength,
37407
+ available.sha256
37408
+ );
37409
+ } catch (cause) {
37410
+ translateSdkError(cause);
37411
+ }
37412
+ }
37413
+
37414
+ // src/authorization/local-authorization-error.ts
37415
+ var LocalAuthorizationError = class extends Error {
37416
+ code = "local_authorization_failed";
37417
+ constructor(message, options = {}) {
37418
+ super(message, options);
37419
+ this.name = "LocalAuthorizationError";
37420
+ }
37421
+ };
37422
+
37423
+ // src/authorization/workspace-directory.ts
37424
+ import { readdir as readdir2, realpath as realpath8, stat as stat7 } from "node:fs/promises";
37425
+ import { homedir as homedir2 } from "node:os";
37426
+ import { basename as basename4, dirname as dirname5, isAbsolute as isAbsolute9, join as join16, normalize as normalize3, relative as relative5 } from "node:path";
37427
+ var WorkspaceDirectoryListing = class {
37428
+ directoryId;
37429
+ directoryLabel;
37430
+ entries;
37431
+ parentDirectoryId;
37432
+ constructor(directoryId2, directoryLabel, entries, parentDirectoryId) {
37433
+ this.directoryId = directoryId2;
37434
+ this.directoryLabel = directoryLabel;
37435
+ this.entries = entries;
37436
+ this.parentDirectoryId = parentDirectoryId;
37437
+ }
37438
+ };
37439
+ function encodePath(path2) {
37440
+ const encoded = Buffer.from(path2, "utf8").toString("base64url");
37441
+ if (encoded.length === 0 || encoded.length > 2e3) {
37442
+ throw new LocalAuthorizationError("The local directory path is too long to select");
37443
+ }
37444
+ return `path-${encoded}`;
37445
+ }
37446
+ function decodePath(value, prefix) {
37447
+ const encoded = value.slice(prefix.length);
37448
+ if (encoded.length === 0 || encoded.length > 2e3 || !/^[a-zA-Z0-9_-]+$/.test(encoded)) {
37449
+ throw new LocalAuthorizationError("The directory identifier is invalid");
37450
+ }
37451
+ const decoded = Buffer.from(encoded, "base64url").toString("utf8");
37452
+ if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize3(decoded) !== decoded) {
37453
+ throw new LocalAuthorizationError("The directory identifier is invalid");
37454
+ }
37455
+ return decoded;
37456
+ }
37457
+ var WorkspaceDirectoryService = class {
37458
+ #bindingId;
37459
+ #defaultWorkspace;
37460
+ constructor(bindingId, defaultWorkspace) {
37461
+ this.#bindingId = bindingId;
37462
+ this.#defaultWorkspace = defaultWorkspace;
37463
+ }
37464
+ authorizeMachine = (bindingId) => {
37465
+ if (bindingId !== this.#bindingId) {
37466
+ throw new LocalAuthorizationError("The runtime binding is not authorized");
37467
+ }
37468
+ };
37469
+ requestedPath = (id) => {
37470
+ if (id === "default") {
37471
+ return this.#defaultWorkspace;
37472
+ }
37473
+ if (id === "home") {
37474
+ return homedir2();
37475
+ }
37476
+ if (id.startsWith("path-")) {
37477
+ const path2 = decodePath(id, "path-");
37478
+ if (isAbsolute9(path2)) {
37479
+ return path2;
37480
+ }
37481
+ }
37482
+ throw new LocalAuthorizationError("The directory identifier is invalid");
37483
+ };
37484
+ resolvePath = async (requested, signal) => {
37485
+ signal.throwIfAborted();
37486
+ if (!isAbsolute9(requested) || requested.includes("\0") || normalize3(requested) !== requested) {
37487
+ throw new LocalAuthorizationError("The local directory path is invalid");
37488
+ }
37489
+ try {
37490
+ const target = await realpath8(requested);
37491
+ signal.throwIfAborted();
37492
+ const metadata = await stat7(target);
37493
+ signal.throwIfAborted();
37494
+ if (!isAbsolute9(target) || normalize3(target) !== target || !metadata.isDirectory()) {
37495
+ throw new LocalAuthorizationError("The selected location is not a directory");
37496
+ }
37497
+ return target;
37498
+ } catch (cause) {
37499
+ signal.throwIfAborted();
37500
+ if (cause instanceof LocalAuthorizationError) {
37501
+ throw cause;
37502
+ }
37503
+ throw new LocalAuthorizationError("This directory is missing or unavailable to your user account", {
37504
+ cause
37505
+ });
37506
+ }
37507
+ };
37508
+ label = (path2) => {
37509
+ const suffix = relative5(homedir2(), path2);
37510
+ return suffix === "" ? "~" : !isAbsolute9(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path2;
37511
+ };
37512
+ identify = async (bindingId, requestedPath, signal) => {
37513
+ this.authorizeMachine(bindingId);
37514
+ const path2 = await this.resolvePath(requestedPath, signal);
37515
+ return {
37516
+ path: path2,
37517
+ directoryId: encodePath(path2),
37518
+ name: basename4(path2) || path2,
37519
+ label: this.label(path2)
37520
+ };
37521
+ };
37522
+ resolve = async (bindingId, id, signal) => {
37523
+ this.authorizeMachine(bindingId);
37524
+ return await this.resolvePath(this.requestedPath(id), signal);
37525
+ };
37526
+ list = async (bindingId, id, signal) => {
37527
+ const target = await this.resolve(bindingId, id, signal);
37528
+ try {
37529
+ const children = await readdir2(target, { withFileTypes: true });
37530
+ signal.throwIfAborted();
37531
+ const entries = [];
37532
+ for (const child of children) {
37533
+ if (entries.length === 500) {
37534
+ break;
37535
+ }
37536
+ if (child.isFile() || child.isBlockDevice() || child.isCharacterDevice() || child.isFIFO() || child.isSocket()) {
37537
+ continue;
37538
+ }
37539
+ try {
37540
+ const path2 = await this.resolvePath(join16(target, child.name), signal);
37541
+ entries.push({ directoryId: encodePath(path2), name: child.name });
37542
+ } catch (cause) {
37543
+ signal.throwIfAborted();
37544
+ if (!(cause instanceof LocalAuthorizationError)) {
37545
+ throw cause;
37546
+ }
37547
+ }
37548
+ }
37549
+ entries.sort((a, b) => a.name.localeCompare(b.name));
37550
+ const parent = dirname5(target);
37551
+ return new WorkspaceDirectoryListing(
37552
+ id,
37553
+ this.label(target),
37554
+ entries,
37555
+ parent === target ? "" : encodePath(parent)
37556
+ );
37557
+ } catch (cause) {
37558
+ signal.throwIfAborted();
37559
+ if (cause instanceof LocalAuthorizationError) {
37560
+ throw cause;
37561
+ }
37562
+ throw new LocalAuthorizationError("This directory cannot be browsed by your user account", { cause });
37563
+ }
37564
+ };
37565
+ resolveMany = async (bindingId, ids, signal) => {
37566
+ const paths = /* @__PURE__ */ new Set();
37567
+ for (const id of ids) {
37568
+ paths.add(await this.resolve(bindingId, id, signal));
37569
+ }
37570
+ return [...paths];
37571
+ };
37572
+ };
37573
+
37574
+ // src/bots/local-bot-grant-store.ts
37575
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
37576
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
37577
+ var LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS = 90 * 24 * 60 * 60 * 1e3;
37578
+ var LocalBotAuthorizationError = class extends Error {
37462
37579
  code;
37463
37580
  constructor(code, message, options = {}) {
37464
37581
  super(message, options);
37465
37582
  this.code = code;
37466
- this.name = "RuntimeArtifactUploadError";
37583
+ this.name = "LocalBotAuthorizationError";
37467
37584
  }
37468
37585
  };
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;
37586
+ var LocalBotGrant = class {
37587
+ agent;
37588
+ agentIdentityDigest;
37589
+ allowedDeliveryTargetIds;
37590
+ behaviorDigest;
37591
+ behaviorRevisionId;
37592
+ bindingId;
37593
+ bindingRevision;
37594
+ botId;
37595
+ expiresAt;
37596
+ localGrantId;
37597
+ revocationEpoch;
37598
+ workspaceIdentityDigest;
37599
+ workspacePath;
37600
+ workspaceRef;
37601
+ constructor(localGrantId, botId, behaviorRevisionId, behaviorDigest, bindingId, bindingRevision, agent, agentIdentityDigest, workspaceRef, workspacePath, workspaceIdentityDigest, allowedDeliveryTargetIds, expiresAt, revocationEpoch) {
37602
+ this.localGrantId = localGrantId;
37603
+ this.botId = botId;
37604
+ this.behaviorRevisionId = behaviorRevisionId;
37605
+ this.behaviorDigest = behaviorDigest;
37606
+ this.bindingId = bindingId;
37607
+ this.bindingRevision = bindingRevision;
37608
+ this.agent = agent;
37609
+ this.agentIdentityDigest = agentIdentityDigest;
37610
+ this.workspaceRef = workspaceRef;
37611
+ this.workspacePath = workspacePath;
37612
+ this.workspaceIdentityDigest = workspaceIdentityDigest;
37613
+ this.allowedDeliveryTargetIds = Object.freeze([...allowedDeliveryTargetIds]);
37614
+ this.expiresAt = expiresAt;
37615
+ this.revocationEpoch = revocationEpoch;
37481
37616
  }
37482
37617
  };
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;
37618
+ function digest(value) {
37619
+ return createHash3("sha256").update(value, "utf8").digest("hex");
37489
37620
  }
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;
37621
+ function agentDigest(agent) {
37622
+ return digest(
37623
+ JSON.stringify({
37624
+ adapter: agent.adapterIdentity,
37625
+ agent: agent.agentIdentity,
37626
+ agentVersion: agent.agentVersion,
37627
+ arguments: agent.arguments,
37628
+ id: agent.id
37629
+ })
37630
+ );
37507
37631
  }
37508
- function uploadError(code, message, cause) {
37509
- return new RuntimeArtifactUploadError(code, message, cause === void 0 ? {} : { cause });
37632
+ function workspaceDigest(path2) {
37633
+ return digest(path2);
37510
37634
  }
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);
37635
+ function exactTargets(left, right) {
37636
+ if (left.length !== right.length) {
37637
+ return false;
37517
37638
  }
37518
- throw cause;
37639
+ const expected = [...left].sort();
37640
+ const actual = [...right].sort();
37641
+ return expected.every((target, index2) => target === actual[index2]);
37519
37642
  }
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);
37643
+ function exactSessionConfigurations(left, right) {
37644
+ if (left.length !== right.length) {
37645
+ return false;
37525
37646
  }
37647
+ const expected = new Map(left.map((selection) => [selection.configId, selection]));
37648
+ return right.every((selection) => {
37649
+ const approved = expected.get(selection.configId);
37650
+ return approved !== void 0 && approved.booleanValue === selection.booleanValue && approved.value === selection.value && approved.valueType === selection.valueType;
37651
+ });
37526
37652
  }
37527
- async function readAuthorization(response) {
37528
- try {
37529
- return decodeMobiusArtifactUpload(await readJson(response));
37530
- } catch (cause) {
37531
- translateSdkError(cause);
37653
+ function rowString(row, key) {
37654
+ const value = Reflect.get(row, key);
37655
+ if (typeof value !== "string") {
37656
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37532
37657
  }
37658
+ return value;
37533
37659
  }
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
- });
37660
+ function rowInteger(row, key) {
37661
+ const value = Reflect.get(row, key);
37662
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
37663
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37664
+ }
37665
+ return value;
37547
37666
  }
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
- });
37667
+ function rowHasInteger(row, key) {
37668
+ const value = Reflect.get(row, key);
37669
+ if (value === null) {
37670
+ return false;
37671
+ }
37672
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
37673
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37674
+ }
37675
+ return true;
37559
37676
  }
37560
- async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
37561
- signal.throwIfAborted();
37562
- let request;
37677
+ function parseTargets(encoded) {
37678
+ let value;
37563
37679
  try {
37564
- request = new MobiusArtifactUploadRequest(
37565
- image.name,
37566
- image.mimeType,
37567
- image.bytes.byteLength,
37568
- createHash3("sha256").update(image.bytes).digest("hex")
37569
- );
37680
+ value = JSON.parse(encoded);
37570
37681
  } catch (cause) {
37571
- translateSdkError(cause);
37682
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
37572
37683
  }
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;
37684
+ if (!Array.isArray(value) || value.some((target) => typeof target !== "string")) {
37685
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37686
+ }
37687
+ return value.filter((target) => typeof target === "string");
37688
+ }
37689
+ function parseSessionConfigurations(encoded) {
37690
+ let value;
37578
37691
  try {
37579
- created = await postLease(
37580
- sessionArtifactUrl(origin, sessionId, "artifacts/uploads", token),
37581
- request,
37582
- requestSignal
37583
- );
37692
+ value = JSON.parse(encoded);
37693
+ return decodeSessionConfigurationSelections(value);
37584
37694
  } 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
- );
37695
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
37591
37696
  }
37592
- if (!created.ok) {
37593
- await created.body?.cancel();
37594
- throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact upload");
37697
+ }
37698
+ var LocalBotGrantStore = class {
37699
+ #database;
37700
+ constructor(path2) {
37701
+ this.#database = new DatabaseSync3(path2);
37702
+ this.#database.exec(`
37703
+ CREATE TABLE IF NOT EXISTS local_bot_grants (
37704
+ local_grant_id TEXT PRIMARY KEY,
37705
+ bot_id TEXT NOT NULL,
37706
+ behavior_revision_id TEXT NOT NULL,
37707
+ behavior_digest TEXT NOT NULL,
37708
+ binding_id TEXT NOT NULL UNIQUE,
37709
+ binding_revision INTEGER NOT NULL,
37710
+ agent_ref TEXT NOT NULL,
37711
+ agent_identity_digest TEXT NOT NULL,
37712
+ workspace_ref TEXT NOT NULL,
37713
+ workspace_path TEXT NOT NULL,
37714
+ workspace_identity_digest TEXT NOT NULL,
37715
+ allowed_delivery_target_ids_json TEXT NOT NULL,
37716
+ unattended_policy_json TEXT NOT NULL,
37717
+ created_at INTEGER NOT NULL,
37718
+ expires_at INTEGER NOT NULL,
37719
+ revocation_epoch INTEGER NOT NULL DEFAULT 0,
37720
+ revoked_at INTEGER
37721
+ ) STRICT;
37722
+ CREATE TABLE IF NOT EXISTS local_bot_binding_resolutions (
37723
+ request_id TEXT PRIMARY KEY,
37724
+ binding_id TEXT NOT NULL,
37725
+ local_grant_id TEXT NOT NULL,
37726
+ resolved_at INTEGER NOT NULL,
37727
+ result TEXT NOT NULL CHECK (result IN ('approved', 'unavailable')),
37728
+ error_code TEXT,
37729
+ error_message TEXT
37730
+ ) STRICT;
37731
+ CREATE TABLE IF NOT EXISTS local_bot_grant_configurations (
37732
+ local_grant_id TEXT PRIMARY KEY,
37733
+ session_configurations_json TEXT NOT NULL
37734
+ ) STRICT;
37735
+ `);
37595
37736
  }
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
37737
+ approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
37738
+ signal.throwIfAborted();
37739
+ const existing = this.#database.prepare(
37740
+ `SELECT grants.* FROM local_bot_binding_resolutions AS resolutions
37741
+ INNER JOIN local_bot_grants AS grants
37742
+ ON grants.local_grant_id = resolutions.local_grant_id
37743
+ WHERE resolutions.request_id = ? AND resolutions.binding_id = ?
37744
+ AND resolutions.result = 'approved'`
37745
+ ).get(request.requestId, request.bindingId);
37746
+ if (existing !== void 0) {
37747
+ return new BotExecutionBindingApprovedEvent(
37748
+ request.requestId,
37749
+ request.botId,
37750
+ request.behaviorRevisionId,
37751
+ request.bindingId,
37752
+ request.bindingRevision,
37753
+ rowString(existing, "local_grant_id"),
37754
+ rowString(existing, "agent_identity_digest"),
37755
+ rowString(existing, "workspace_identity_digest")
37756
+ );
37757
+ }
37758
+ const resolved = await this.resolveProposal(request, catalog, directories, bindingAuthorityId, signal);
37759
+ const localGrantId = `lbg_${randomUUID3()}`;
37760
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
37761
+ this.#database.exec("BEGIN IMMEDIATE");
37762
+ try {
37763
+ this.#database.prepare(
37764
+ `INSERT INTO local_bot_grants (
37765
+ local_grant_id, bot_id, behavior_revision_id, behavior_digest,
37766
+ binding_id, binding_revision, agent_ref,
37767
+ agent_identity_digest, workspace_ref, workspace_path,
37768
+ workspace_identity_digest, allowed_delivery_target_ids_json,
37769
+ unattended_policy_json, created_at, expires_at
37770
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
37771
+ ).run(
37772
+ localGrantId,
37773
+ request.botId,
37774
+ request.behaviorRevisionId,
37775
+ request.behaviorDigest,
37776
+ request.bindingId,
37777
+ request.bindingRevision,
37778
+ request.agentRef,
37779
+ resolved.agentIdentityDigest,
37780
+ request.workspaceRef,
37781
+ resolved.workspacePath,
37782
+ resolved.workspaceIdentityDigest,
37783
+ JSON.stringify(request.allowedDeliveryTargets.map((target) => target.deliveryTargetId)),
37784
+ JSON.stringify({ localSideEffects: "owner-approval-required" }),
37785
+ now,
37786
+ expiresAt
37787
+ );
37788
+ this.#database.prepare(
37789
+ `INSERT INTO local_bot_grant_configurations (
37790
+ local_grant_id, session_configurations_json
37791
+ ) VALUES (?, ?)`
37792
+ ).run(localGrantId, JSON.stringify(request.sessionConfigurations));
37793
+ this.#database.prepare(
37794
+ `INSERT INTO local_bot_binding_resolutions (
37795
+ request_id, binding_id, local_grant_id, resolved_at, result
37796
+ ) VALUES (?, ?, ?, ?, 'approved')`
37797
+ ).run(request.requestId, request.bindingId, localGrantId, now);
37798
+ this.#database.exec("COMMIT");
37799
+ } catch (cause) {
37800
+ this.#database.exec("ROLLBACK");
37801
+ throw cause;
37802
+ }
37803
+ signal.throwIfAborted();
37804
+ return new BotExecutionBindingApprovedEvent(
37805
+ request.requestId,
37806
+ request.botId,
37807
+ request.behaviorRevisionId,
37808
+ request.bindingId,
37809
+ request.bindingRevision,
37810
+ localGrantId,
37811
+ resolved.agentIdentityDigest,
37812
+ resolved.workspaceIdentityDigest
37609
37813
  );
37610
- } catch (cause) {
37814
+ };
37815
+ resolveExecution = async (command, catalog, directories, bindingAuthorityId, now, signal) => {
37611
37816
  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
37817
+ const row = this.#database.prepare(
37818
+ `SELECT grants.*, COALESCE(configurations.session_configurations_json, '[]')
37819
+ AS session_configurations_json
37820
+ FROM local_bot_grants AS grants
37821
+ LEFT JOIN local_bot_grant_configurations AS configurations
37822
+ ON configurations.local_grant_id = grants.local_grant_id
37823
+ WHERE grants.local_grant_id = ? AND grants.bot_id = ?
37824
+ AND behavior_revision_id = ? AND behavior_digest = ?
37825
+ AND binding_id = ? AND binding_revision = ?
37826
+ AND agent_ref = ?`
37827
+ ).get(
37828
+ command.localGrantId,
37829
+ command.botId,
37830
+ command.behaviorRevisionId,
37831
+ command.behaviorDigest,
37832
+ command.bindingId,
37833
+ command.bindingRevision,
37834
+ command.agentId
37616
37835
  );
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
37836
+ if (row === void 0) {
37837
+ throw new LocalBotAuthorizationError(
37838
+ "binding_not_approved",
37839
+ "The Bot execution binding is not locally approved"
37840
+ );
37841
+ }
37842
+ const approvedTargets = parseTargets(rowString(row, "allowed_delivery_target_ids_json"));
37843
+ const requestedTargets = command.allowedDeliveryTargets.map((target) => target.deliveryTargetId);
37844
+ if (!exactTargets(approvedTargets, requestedTargets)) {
37845
+ throw new LocalBotAuthorizationError(
37846
+ "binding_not_approved",
37847
+ "The Bot execution target policy differs from its binding"
37848
+ );
37849
+ }
37850
+ const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
37851
+ if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
37852
+ throw new LocalBotAuthorizationError(
37853
+ "binding_not_approved",
37854
+ "The Bot Agent configuration differs from its binding"
37855
+ );
37856
+ }
37857
+ const agent = catalog.find(command.agentId);
37858
+ const [adapterUnchanged, agentUnchanged] = await Promise.all([
37859
+ revalidateExecutable(agent.adapterIdentity),
37860
+ revalidateExecutable(agent.agentIdentity)
37861
+ ]);
37862
+ signal.throwIfAborted();
37863
+ if (!adapterUnchanged || !agentUnchanged) {
37864
+ throw new LocalBotAuthorizationError(
37865
+ "binding_incompatible",
37866
+ "The local Agent executable changed while the Runtime is active; restart the Runtime"
37867
+ );
37868
+ }
37869
+ const workspaceRef = rowString(row, "workspace_ref");
37870
+ const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
37871
+ const currentAgentDigest = agentDigest(agent);
37872
+ const currentWorkspaceDigest = workspaceDigest(workspacePath);
37873
+ signal.throwIfAborted();
37874
+ let expiresAt = rowInteger(row, "expires_at");
37875
+ let revocationEpoch = rowInteger(row, "revocation_epoch");
37876
+ if (currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path") || expiresAt <= now || rowHasInteger(row, "revoked_at")) {
37877
+ const refreshed = this.refreshTarget(
37878
+ rowString(row, "local_grant_id"),
37879
+ currentAgentDigest,
37880
+ currentWorkspaceDigest,
37881
+ workspacePath,
37882
+ now
37883
+ );
37884
+ expiresAt = refreshed.expiresAt;
37885
+ revocationEpoch = refreshed.revocationEpoch;
37886
+ }
37887
+ if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
37888
+ throw new LocalBotAuthorizationError(
37889
+ "binding_incompatible",
37890
+ "The local Agent cannot apply the approved Bot behavior"
37891
+ );
37892
+ }
37893
+ return new LocalBotGrant(
37894
+ rowString(row, "local_grant_id"),
37895
+ command.botId,
37896
+ command.behaviorRevisionId,
37897
+ command.behaviorDigest,
37898
+ command.bindingId,
37899
+ command.bindingRevision,
37900
+ agent,
37901
+ currentAgentDigest,
37902
+ workspaceRef,
37903
+ workspacePath,
37904
+ currentWorkspaceDigest,
37905
+ approvedTargets,
37906
+ expiresAt,
37907
+ revocationEpoch
37630
37908
  );
37631
- } catch (cause) {
37632
- translateSdkError(cause);
37633
- }
37634
- }
37909
+ };
37910
+ recordUnavailable = (request, code, message, now) => {
37911
+ this.#database.prepare(
37912
+ `INSERT OR IGNORE INTO local_bot_binding_resolutions (
37913
+ request_id, binding_id, local_grant_id, resolved_at,
37914
+ result, error_code, error_message
37915
+ ) VALUES (?, ?, '', ?, 'unavailable', ?, ?)`
37916
+ ).run(request.requestId, request.bindingId, now, code, message);
37917
+ };
37918
+ close = () => {
37919
+ this.#database.close();
37920
+ };
37921
+ resolveProposal = async (request, catalog, directories, bindingAuthorityId, signal) => {
37922
+ const agent = catalog.find(request.agentRef);
37923
+ if (request.requiredCapabilities.includes("embedded-context") && !agent.capabilities.embeddedContextPrompt) {
37924
+ throw new LocalBotAuthorizationError(
37925
+ "binding_incompatible",
37926
+ "The local Agent cannot apply embedded Bot context"
37927
+ );
37928
+ }
37929
+ if (request.requiredCapabilities.some((capability) => capability !== "embedded-context")) {
37930
+ throw new LocalBotAuthorizationError(
37931
+ "binding_incompatible",
37932
+ "The Bot requires an unsupported local Agent capability"
37933
+ );
37934
+ }
37935
+ const [adapterUnchanged, agentUnchanged] = await Promise.all([
37936
+ revalidateExecutable(agent.adapterIdentity),
37937
+ revalidateExecutable(agent.agentIdentity)
37938
+ ]);
37939
+ signal.throwIfAborted();
37940
+ if (!adapterUnchanged || !agentUnchanged) {
37941
+ throw new LocalBotAuthorizationError(
37942
+ "binding_incompatible",
37943
+ "The local Agent executable changed before approval"
37944
+ );
37945
+ }
37946
+ const workspacePath = await directories.resolve(bindingAuthorityId, request.workspaceRef, signal);
37947
+ return {
37948
+ agent,
37949
+ agentIdentityDigest: agentDigest(agent),
37950
+ workspaceIdentityDigest: workspaceDigest(workspacePath),
37951
+ workspacePath
37952
+ };
37953
+ };
37954
+ refreshTarget = (localGrantId, agentIdentityDigest, workspaceIdentityDigest, workspacePath, now) => {
37955
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
37956
+ this.#database.exec("BEGIN IMMEDIATE");
37957
+ try {
37958
+ const current = this.#database.prepare("SELECT * FROM local_bot_grants WHERE local_grant_id = ?").get(localGrantId);
37959
+ if (current === void 0) {
37960
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is missing");
37961
+ }
37962
+ const currentExpiresAt = rowInteger(current, "expires_at");
37963
+ const currentRevocationEpoch = rowInteger(current, "revocation_epoch");
37964
+ if (agentIdentityDigest === rowString(current, "agent_identity_digest") && workspaceIdentityDigest === rowString(current, "workspace_identity_digest") && workspacePath === rowString(current, "workspace_path") && currentExpiresAt > now && !rowHasInteger(current, "revoked_at")) {
37965
+ this.#database.exec("COMMIT");
37966
+ return { expiresAt: currentExpiresAt, revocationEpoch: currentRevocationEpoch };
37967
+ }
37968
+ const result = this.#database.prepare(
37969
+ `UPDATE local_bot_grants
37970
+ SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
37971
+ expires_at = ?, revoked_at = NULL, revocation_epoch = revocation_epoch + 1
37972
+ WHERE local_grant_id = ? AND revocation_epoch = ?`
37973
+ ).run(
37974
+ agentIdentityDigest,
37975
+ workspaceIdentityDigest,
37976
+ workspacePath,
37977
+ expiresAt,
37978
+ localGrantId,
37979
+ currentRevocationEpoch
37980
+ );
37981
+ if (result.changes !== 1) {
37982
+ throw new LocalBotAuthorizationError(
37983
+ "local_grant_invalid",
37984
+ "The local Bot grant target could not be refreshed"
37985
+ );
37986
+ }
37987
+ this.#database.prepare(
37988
+ `INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
37989
+ VALUES (?, 'bot_binding_target_refreshed', ?, '', ?)`
37990
+ ).run(
37991
+ new Date(now).toISOString(),
37992
+ rowString(current, "binding_id"),
37993
+ JSON.stringify({
37994
+ agentIdentityChanged: agentIdentityDigest !== rowString(current, "agent_identity_digest"),
37995
+ bindingId: rowString(current, "binding_id"),
37996
+ botId: rowString(current, "bot_id"),
37997
+ expired: currentExpiresAt <= now,
37998
+ revived: rowHasInteger(current, "revoked_at"),
37999
+ workspaceIdentityChanged: workspaceIdentityDigest !== rowString(current, "workspace_identity_digest"),
38000
+ workspacePathChanged: workspacePath !== rowString(current, "workspace_path")
38001
+ })
38002
+ );
38003
+ this.#database.exec("COMMIT");
38004
+ return { expiresAt, revocationEpoch: currentRevocationEpoch + 1 };
38005
+ } catch (cause) {
38006
+ this.#database.exec("ROLLBACK");
38007
+ throw cause;
38008
+ }
38009
+ };
38010
+ };
37635
38011
 
37636
38012
  // src/bots/bot-context-applicator.ts
37637
38013
  var AppliedBotContext = class {
@@ -37768,7 +38144,7 @@ var BotExecutionContextRegistry = class {
37768
38144
  // src/bots/bot-outbound-ipc.ts
37769
38145
  import { chmod as chmod2, mkdir as mkdir4, unlink } from "node:fs/promises";
37770
38146
  import { createServer } from "node:net";
37771
- import { dirname as dirname7, isAbsolute as isAbsolute10 } from "node:path";
38147
+ import { dirname as dirname6, isAbsolute as isAbsolute10 } from "node:path";
37772
38148
  import { fetch as fetch5 } from "undici";
37773
38149
  var BOT_IPC_REQUEST_LIMIT = 32 * 1024;
37774
38150
  var BOT_IPC_TIMEOUT_MILLISECONDS2 = 2e4;
@@ -37881,7 +38257,7 @@ var BotOutboundIpcServer = class {
37881
38257
  listen = async (signal) => {
37882
38258
  signal.throwIfAborted();
37883
38259
  if (this.#usesFilesystemSocket) {
37884
- await mkdir4(dirname7(this.#socketPath), { mode: 448, recursive: true });
38260
+ await mkdir4(dirname6(this.#socketPath), { mode: 448, recursive: true });
37885
38261
  await unlink(this.#socketPath).catch((error62) => {
37886
38262
  if (!isRecord12(error62) || error62["code"] !== "ENOENT") {
37887
38263
  throw error62;
@@ -38006,7 +38382,7 @@ var BotOutboundIpcServer = class {
38006
38382
 
38007
38383
  // src/native-sessions/service.ts
38008
38384
  import { randomUUID as randomUUID4 } from "node:crypto";
38009
- import { basename as basename4 } from "node:path";
38385
+ import { basename as basename5 } from "node:path";
38010
38386
 
38011
38387
  // src/native-sessions/codex-history.ts
38012
38388
  import { spawn as spawn4 } from "node:child_process";
@@ -38515,7 +38891,7 @@ var NativeSessionService = class {
38515
38891
  }
38516
38892
  resolvedPaths.add(path2);
38517
38893
  additionalDirectories.push(path2);
38518
- additionalEntries.push({ directoryId: directoryId2, name: basename4(path2) });
38894
+ additionalEntries.push({ directoryId: directoryId2, name: basename5(path2) });
38519
38895
  }
38520
38896
  const listing = await this.#directories.list(this.#config.bindingId, command.directoryId, signal);
38521
38897
  const opened = await this.#sessions.forkSessionAtTurn(
@@ -39225,7 +39601,7 @@ var RelayConnectionLiveness = class {
39225
39601
 
39226
39602
  // src/relay-connection/session-event-outbox.ts
39227
39603
  import { mkdirSync as mkdirSync3 } from "node:fs";
39228
- import { dirname as dirname8 } from "node:path";
39604
+ import { dirname as dirname7 } from "node:path";
39229
39605
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
39230
39606
  var DEFAULT_OUTBOX_LIMITS = {
39231
39607
  criticalEventBytes: 136 * 1024 * 1024,
@@ -39291,7 +39667,7 @@ var SessionEventOutbox = class {
39291
39667
  constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
39292
39668
  validateLimits(limits);
39293
39669
  this.#limits = limits;
39294
- mkdirSync3(dirname8(path2), { recursive: true });
39670
+ mkdirSync3(dirname7(path2), { recursive: true });
39295
39671
  this.#database = new DatabaseSync4(path2);
39296
39672
  this.#database.exec(`
39297
39673
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
@@ -39828,7 +40204,7 @@ function botIpcSocketPath() {
39828
40204
  if (process.platform === "win32") {
39829
40205
  return `\\\\.\\pipe\\mobius-bot-${randomUUID6()}`;
39830
40206
  }
39831
- return join18("/tmp", `mobius-bot-${randomUUID6()}.sock`);
40207
+ return join17("/tmp", `mobius-bot-${randomUUID6()}.sock`);
39832
40208
  }
39833
40209
  var DaemonAcpObserver = class {
39834
40210
  #config;
@@ -39837,9 +40213,9 @@ var DaemonAcpObserver = class {
39837
40213
  this.#config = config2;
39838
40214
  this.#record = record3;
39839
40215
  }
39840
- importLocalImage = async (sessionId, image, signal) => {
40216
+ importLocalArtifact = async (sessionId, artifact, signal) => {
39841
40217
  try {
39842
- return (await uploadRuntimeArtifact(this.#config, sessionId, image, signal)).artifactId;
40218
+ return (await uploadRuntimeArtifact(this.#config, sessionId, artifact, signal)).artifactId;
39843
40219
  } catch (cause) {
39844
40220
  signal.throwIfAborted();
39845
40221
  if (cause instanceof Error && cause.name === "AbortError") {
@@ -40410,7 +40786,7 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
40410
40786
  additionalDirectories.push(directory);
40411
40787
  additionalDirectoryEntries.push({
40412
40788
  directoryId: additionalDirectoryId,
40413
- name: basename5(directory)
40789
+ name: basename6(directory)
40414
40790
  });
40415
40791
  }
40416
40792
  return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
@@ -42099,7 +42475,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
42099
42475
  }
42100
42476
 
42101
42477
  // src/runtime.ts
42102
- var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{43}$/;
42478
+ var RUNTIME_CREDENTIAL_PATTERN = /^(?:[a-zA-Z0-9_-]{43}|prj_[a-zA-Z0-9_-]{24}_[a-zA-Z0-9_-]{43}|prj_(?:wn|en|sa|we|ee|ap|oc|af|me)_01_[a-zA-Z0-9_-]{24}_[a-zA-Z0-9_-]{43})$/;
42103
42479
  var MobiusRuntimeConfigurationError = class extends Error {
42104
42480
  code = "runtime_configuration_invalid";
42105
42481
  constructor(message, options = {}) {
@@ -42164,7 +42540,6 @@ Usage:
42164
42540
  mobius pair --url <relay-url> --pairing <runtime-pairing-id> --code <pairing-code> [--workspace <directory>]
42165
42541
  mobius start --channel <channel-id>
42166
42542
  mobius agents [--json]
42167
- mobius bot approve --bot <bot-id> [--channel <channel-id>]
42168
42543
  mobius bot message send --target <current|alias> --text <message>
42169
42544
 
42170
42545
  Commands:
@@ -42172,7 +42547,7 @@ Commands:
42172
42547
  pair Pair this machine and start its local daemon
42173
42548
  start Start the local daemon for a saved channel
42174
42549
  agents Show detected, missing, and integration-ready Agents
42175
- bot Approve a saved Bot locally or send a message from an active execution
42550
+ bot Send a message from an active execution
42176
42551
 
42177
42552
  Pairing grants this browser access to the machine with your user account's permissions.
42178
42553
  New conversations default to ~/.mobius/workspace; choose other directories in the browser.
@@ -42203,10 +42578,6 @@ async function main() {
42203
42578
  return;
42204
42579
  }
42205
42580
  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
42581
  if (process.argv[3] !== "message" || process.argv[4] !== "send") {
42211
42582
  throw new BotMessageCommandError(
42212
42583
  "invalid_request",
@@ -42252,7 +42623,7 @@ try {
42252
42623
  } catch (error62) {
42253
42624
  if (!shutdown.signal.aborted) {
42254
42625
  const message = error62 instanceof Error ? error62.message : "Unknown failure";
42255
- const code = error62 instanceof BotMessageCommandError || error62 instanceof LocalBotAuthorizationError ? `${error62.code}: ` : "";
42626
+ const code = error62 instanceof BotMessageCommandError ? `${error62.code}: ` : "";
42256
42627
  process.stderr.write(`Mobius daemon failed: ${code}${message}
42257
42628
  `);
42258
42629
  process.exitCode = 1;