@moxt-ai/mobius 0.0.39 → 0.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/acp/session-manager.d.ts.map +1 -1
  2. package/dist/acp/session-manager.js +485 -124
  3. package/dist/acp/session-manager.js.map +1 -1
  4. package/dist/agent-catalog/agent-discovery.d.ts +2 -2
  5. package/dist/agent-catalog/agent-discovery.d.ts.map +1 -1
  6. package/dist/agent-catalog/agent-discovery.js +3 -2
  7. package/dist/agent-catalog/agent-discovery.js.map +1 -1
  8. package/dist/agent-catalog/agents/grok-build-agent.d.ts +1 -1
  9. package/dist/agent-catalog/agents/grok-build-agent.d.ts.map +1 -1
  10. package/dist/agent-catalog/agents/grok-build-agent.js +18 -8
  11. package/dist/agent-catalog/agents/grok-build-agent.js.map +1 -1
  12. package/dist/agent-catalog/discover-agent.js +1 -1
  13. package/dist/agent-catalog/discover-agent.js.map +1 -1
  14. package/dist/agent-catalog/discover-local-agents.d.ts +0 -1
  15. package/dist/agent-catalog/discover-local-agents.d.ts.map +1 -1
  16. package/dist/agent-catalog/discover-local-agents.js +0 -1
  17. package/dist/agent-catalog/discover-local-agents.js.map +1 -1
  18. package/dist/agent-installation/fixed-installation-executor.js +2 -2
  19. package/dist/agent-installation/fixed-installation-executor.js.map +1 -1
  20. package/dist/bots/local-bot-grant-store.d.ts +1 -8
  21. package/dist/bots/local-bot-grant-store.d.ts.map +1 -1
  22. package/dist/bots/local-bot-grant-store.js +79 -121
  23. package/dist/bots/local-bot-grant-store.js.map +1 -1
  24. package/dist/cli.js +1639 -1325
  25. package/dist/cli.js.map +4 -4
  26. package/dist/index.js +800 -369
  27. package/dist/index.js.map +3 -3
  28. package/dist/run-daemon.d.ts.map +1 -1
  29. package/dist/run-daemon.js +89 -57
  30. package/dist/run-daemon.js.map +1 -1
  31. package/dist/runtime.js +794 -363
  32. package/dist/runtime.js.map +3 -3
  33. package/package.json +1 -1
  34. package/dist/bots/bot-approve-command.d.ts +0 -2
  35. package/dist/bots/bot-approve-command.d.ts.map +0 -1
  36. package/dist/bots/bot-approve-command.js +0 -78
  37. package/dist/bots/bot-approve-command.js.map +0 -1
package/dist/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.39",
14
+ version: "0.0.41",
15
15
  description: "Mobius CLI for pairing and running local AI agent services.",
16
16
  type: "module",
17
17
  bin: {
@@ -841,10 +841,11 @@ var IntegrationProbeFailed = class extends UnavailableInstalledAgent {
841
841
  };
842
842
  var IncompatibleAdapter = class extends UnavailableInstalledAgent {
843
843
  code = "acp_incompatible";
844
- message = "ACP adapter is incompatible";
844
+ message;
845
845
  status = "incompatible_adapter";
846
- constructor(specification, agent) {
846
+ constructor(specification, agent, message) {
847
847
  super(specification, agent);
848
+ this.message = message;
848
849
  }
849
850
  };
850
851
  var AuthenticationRequiredAgent = class extends UnavailableInstalledAgent {
@@ -1645,6 +1646,9 @@ var GeminiCliAgentSpecification = class extends DirectAcpAgentDefinition {
1645
1646
  // src/agent-catalog/agents/grok-build-agent.ts
1646
1647
  import { realpath as realpath4 } from "node:fs/promises";
1647
1648
  import { isAbsolute as isAbsolute4, join as join7, relative as relative2, sep as sep2 } from "node:path";
1649
+ import {
1650
+ RequestError
1651
+ } from "@agentclientprotocol/sdk";
1648
1652
 
1649
1653
  // src/agent-installation/grok-managed-package.ts
1650
1654
  var GROK_BUILD_MANAGED_VERSION = "1.0.21";
@@ -1757,11 +1761,23 @@ var GrokBuildAgentSpecification = class extends DirectAcpAgentDefinition {
1757
1761
  };
1758
1762
  verifyAcp = async (connection, initialized, defaultWorkspace, signal) => {
1759
1763
  const capabilities = initialized.agentCapabilities ?? {};
1760
- const session = capabilities.sessionCapabilities;
1761
- if (capabilities.loadSession !== true || session?.close == null || session.list == null || session.resume == null || !(initialized.authMethods ?? []).some((method) => method.id === "xai.api_key" || method.id === "grok.com")) {
1762
- throw new AgentProbeError("acp_incompatible", "Grok Build reported an unsupported ACP capability set");
1764
+ if (capabilities.loadSession !== true) {
1765
+ throw new AgentProbeError("acp_incompatible", "Grok Build did not report ACP session loading");
1766
+ }
1767
+ const authMethods = initialized.authMethods ?? [];
1768
+ if (authMethods.length === 0) {
1769
+ throw new AgentProbeError("acp_incompatible", "Grok Build did not report an ACP authentication method");
1770
+ }
1771
+ try {
1772
+ await verifySessionCreation(connection, capabilities, defaultWorkspace, signal, this.label);
1773
+ } catch (cause) {
1774
+ const detail = cause instanceof RequestError ? `ACP error ${cause.code}: ${cause.message}` : cause instanceof Error ? `${cause.name}: ${cause.message}` : "unknown error";
1775
+ throw new AgentProbeError(
1776
+ "acp_incompatible",
1777
+ `Grok Build could not create an ACP session (${detail}; auth methods: ${authMethods.map(({ id }) => id).join(", ")})`,
1778
+ { cause }
1779
+ );
1763
1780
  }
1764
- await verifySessionCreation(connection, capabilities, defaultWorkspace, signal, this.label);
1765
1781
  };
1766
1782
  };
1767
1783
 
@@ -2304,7 +2320,7 @@ import {
2304
2320
  methods as methods4,
2305
2321
  ndJsonStream,
2306
2322
  PROTOCOL_VERSION,
2307
- RequestError
2323
+ RequestError as RequestError2
2308
2324
  } from "@agentclientprotocol/sdk";
2309
2325
 
2310
2326
  // src/acp/create-client.ts
@@ -2482,7 +2498,7 @@ async function probeAcpReadiness(specification, agent, environment, defaultWorks
2482
2498
  if (error62 instanceof AgentProbeError) {
2483
2499
  throw error62;
2484
2500
  }
2485
- if (error62 instanceof RequestError && error62.code === -32e3 && specification.authenticationCommand().length > 0) {
2501
+ if (error62 instanceof RequestError2 && error62.code === -32e3 && specification.authenticationCommand().length > 0) {
2486
2502
  throw new AgentProbeError("authentication_required", "Agent authentication is required", { cause: error62 });
2487
2503
  }
2488
2504
  throw new AgentProbeError("acp_incompatible", "ACP adapter initialization failed", { cause: error62 });
@@ -2719,7 +2735,7 @@ function integrationProbeFailure(specification, agent, error62) {
2719
2735
  if (error62.code === "authentication_required") {
2720
2736
  return new AuthenticationRequiredAgent(specification, agent);
2721
2737
  }
2722
- return error62.code === "acp_incompatible" ? new IncompatibleAdapter(specification, agent) : new IntegrationProbeFailed(specification, agent, error62.code, error62.message);
2738
+ return error62.code === "acp_incompatible" ? new IncompatibleAdapter(specification, agent, error62.message) : new IntegrationProbeFailed(specification, agent, error62.code, error62.message);
2723
2739
  }
2724
2740
  if (error62 instanceof ProcessExecutionError) {
2725
2741
  const code = error62.code === "process_timeout" ? "adapter_probe_timeout" : "adapter_probe_failed";
@@ -2858,9 +2874,166 @@ async function discoverLocalAgentInventory(options) {
2858
2874
  return new LocalAgentInventory(discoveries);
2859
2875
  }
2860
2876
 
2861
- // src/bots/bot-approve-command.ts
2862
- import { readdir as readdir3, realpath as realpath8 } from "node:fs/promises";
2863
- 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";
2864
3037
 
2865
3038
  // ../../node_modules/.pnpm/zod@4.6.2/node_modules/zod/v4/classic/external.js
2866
3039
  var external_exports = {};
@@ -22537,174 +22710,6 @@ function date4(params) {
22537
22710
  return _coercedDate(ZodDate, params);
22538
22711
  }
22539
22712
 
22540
- // src/authorization/workspace-directory.ts
22541
- import { readdir as readdir2, realpath as realpath6, stat as stat5 } from "node:fs/promises";
22542
- import { homedir as homedir2 } from "node:os";
22543
- import { basename, dirname as dirname3, isAbsolute as isAbsolute8, join as join14, normalize as normalize2, relative as relative4 } from "node:path";
22544
-
22545
- // src/authorization/local-authorization-error.ts
22546
- var LocalAuthorizationError = class extends Error {
22547
- code = "local_authorization_failed";
22548
- constructor(message, options = {}) {
22549
- super(message, options);
22550
- this.name = "LocalAuthorizationError";
22551
- }
22552
- };
22553
-
22554
- // src/authorization/workspace-directory.ts
22555
- var WorkspaceDirectoryListing = class {
22556
- directoryId;
22557
- directoryLabel;
22558
- entries;
22559
- parentDirectoryId;
22560
- constructor(directoryId2, directoryLabel, entries, parentDirectoryId) {
22561
- this.directoryId = directoryId2;
22562
- this.directoryLabel = directoryLabel;
22563
- this.entries = entries;
22564
- this.parentDirectoryId = parentDirectoryId;
22565
- }
22566
- };
22567
- function encodePath(path2) {
22568
- const encoded = Buffer.from(path2, "utf8").toString("base64url");
22569
- if (encoded.length === 0 || encoded.length > 2e3) {
22570
- throw new LocalAuthorizationError("The local directory path is too long to select");
22571
- }
22572
- return `path-${encoded}`;
22573
- }
22574
- function decodePath(value, prefix) {
22575
- const encoded = value.slice(prefix.length);
22576
- if (encoded.length === 0 || encoded.length > 2e3 || !/^[a-zA-Z0-9_-]+$/.test(encoded)) {
22577
- throw new LocalAuthorizationError("The directory identifier is invalid");
22578
- }
22579
- const decoded = Buffer.from(encoded, "base64url").toString("utf8");
22580
- if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize2(decoded) !== decoded) {
22581
- throw new LocalAuthorizationError("The directory identifier is invalid");
22582
- }
22583
- return decoded;
22584
- }
22585
- var WorkspaceDirectoryService = class {
22586
- #bindingId;
22587
- #defaultWorkspace;
22588
- constructor(bindingId, defaultWorkspace) {
22589
- this.#bindingId = bindingId;
22590
- this.#defaultWorkspace = defaultWorkspace;
22591
- }
22592
- authorizeMachine = (bindingId) => {
22593
- if (bindingId !== this.#bindingId) {
22594
- throw new LocalAuthorizationError("The runtime binding is not authorized");
22595
- }
22596
- };
22597
- requestedPath = (id) => {
22598
- if (id === "default") {
22599
- return this.#defaultWorkspace;
22600
- }
22601
- if (id === "home") {
22602
- return homedir2();
22603
- }
22604
- if (id.startsWith("path-")) {
22605
- const path2 = decodePath(id, "path-");
22606
- if (isAbsolute8(path2)) {
22607
- return path2;
22608
- }
22609
- }
22610
- throw new LocalAuthorizationError("The directory identifier is invalid");
22611
- };
22612
- resolvePath = async (requested, signal) => {
22613
- signal.throwIfAborted();
22614
- if (!isAbsolute8(requested) || requested.includes("\0") || normalize2(requested) !== requested) {
22615
- throw new LocalAuthorizationError("The local directory path is invalid");
22616
- }
22617
- try {
22618
- const target = await realpath6(requested);
22619
- signal.throwIfAborted();
22620
- const metadata = await stat5(target);
22621
- signal.throwIfAborted();
22622
- if (!isAbsolute8(target) || normalize2(target) !== target || !metadata.isDirectory()) {
22623
- throw new LocalAuthorizationError("The selected location is not a directory");
22624
- }
22625
- return target;
22626
- } catch (cause) {
22627
- signal.throwIfAborted();
22628
- if (cause instanceof LocalAuthorizationError) {
22629
- throw cause;
22630
- }
22631
- throw new LocalAuthorizationError("This directory is missing or unavailable to your user account", {
22632
- cause
22633
- });
22634
- }
22635
- };
22636
- label = (path2) => {
22637
- const suffix = relative4(homedir2(), path2);
22638
- return suffix === "" ? "~" : !isAbsolute8(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path2;
22639
- };
22640
- identify = async (bindingId, requestedPath, signal) => {
22641
- this.authorizeMachine(bindingId);
22642
- const path2 = await this.resolvePath(requestedPath, signal);
22643
- return {
22644
- path: path2,
22645
- directoryId: encodePath(path2),
22646
- name: basename(path2) || path2,
22647
- label: this.label(path2)
22648
- };
22649
- };
22650
- resolve = async (bindingId, id, signal) => {
22651
- this.authorizeMachine(bindingId);
22652
- return await this.resolvePath(this.requestedPath(id), signal);
22653
- };
22654
- list = async (bindingId, id, signal) => {
22655
- const target = await this.resolve(bindingId, id, signal);
22656
- try {
22657
- const children = await readdir2(target, { withFileTypes: true });
22658
- signal.throwIfAborted();
22659
- const entries = [];
22660
- for (const child of children) {
22661
- if (entries.length === 500) {
22662
- break;
22663
- }
22664
- if (child.isFile() || child.isBlockDevice() || child.isCharacterDevice() || child.isFIFO() || child.isSocket()) {
22665
- continue;
22666
- }
22667
- try {
22668
- const path2 = await this.resolvePath(join14(target, child.name), signal);
22669
- entries.push({ directoryId: encodePath(path2), name: child.name });
22670
- } catch (cause) {
22671
- signal.throwIfAborted();
22672
- if (!(cause instanceof LocalAuthorizationError)) {
22673
- throw cause;
22674
- }
22675
- }
22676
- }
22677
- entries.sort((a, b) => a.name.localeCompare(b.name));
22678
- const parent = dirname3(target);
22679
- return new WorkspaceDirectoryListing(
22680
- id,
22681
- this.label(target),
22682
- entries,
22683
- parent === target ? "" : encodePath(parent)
22684
- );
22685
- } catch (cause) {
22686
- signal.throwIfAborted();
22687
- if (cause instanceof LocalAuthorizationError) {
22688
- throw cause;
22689
- }
22690
- throw new LocalAuthorizationError("This directory cannot be browsed by your user account", { cause });
22691
- }
22692
- };
22693
- resolveMany = async (bindingId, ids, signal) => {
22694
- const paths = /* @__PURE__ */ new Set();
22695
- for (const id of ids) {
22696
- paths.add(await this.resolve(bindingId, id, signal));
22697
- }
22698
- return [...paths];
22699
- };
22700
- };
22701
-
22702
- // src/pairing/pair-local-machine.ts
22703
- import { randomUUID } from "node:crypto";
22704
- import { mkdir as mkdir3, open as open4, realpath as realpath7, rename as rename3, stat as stat6, writeFile as writeFile2 } from "node:fs/promises";
22705
- import { hostname as hostname3 } from "node:os";
22706
- import { basename as basename2, join as join16, resolve as resolve3 } from "node:path";
22707
-
22708
22713
  // ../protocol/src/prompt-usage.ts
22709
22714
  var TOKEN_COUNT = external_exports.number().int().nonnegative();
22710
22715
  function normalizeQuotaTokenCount(value) {
@@ -23284,7 +23289,7 @@ var ProtocolMessageError = class extends Error {
23284
23289
  this.name = "ProtocolMessageError";
23285
23290
  }
23286
23291
  };
23287
- function isRecord4(value) {
23292
+ function isRecord5(value) {
23288
23293
  return typeof value === "object" && value !== null && !Array.isArray(value);
23289
23294
  }
23290
23295
  function parseJson2(encoded) {
@@ -23296,7 +23301,7 @@ function parseJson2(encoded) {
23296
23301
  cause: error62
23297
23302
  });
23298
23303
  }
23299
- if (!isRecord4(value)) {
23304
+ if (!isRecord5(value)) {
23300
23305
  throw new ProtocolMessageError("Message must be a JSON object");
23301
23306
  }
23302
23307
  return value;
@@ -23393,7 +23398,7 @@ function readActivityContent(value) {
23393
23398
  }
23394
23399
  function readActivityDetail(value) {
23395
23400
  const field = value["detail"];
23396
- if (!isRecord4(field)) {
23401
+ if (!isRecord5(field)) {
23397
23402
  throw new ProtocolMessageError("Invalid activity detail field");
23398
23403
  }
23399
23404
  const kind = readString(field, "kind", 32);
@@ -23824,6 +23829,7 @@ var BotSessionPromptCommand = class {
23824
23829
  commandId;
23825
23830
  conversationId;
23826
23831
  directoryId;
23832
+ disposition;
23827
23833
  executionCapabilityId;
23828
23834
  executionCapabilitySecret;
23829
23835
  executionDeadlineAt;
@@ -23836,13 +23842,15 @@ var BotSessionPromptCommand = class {
23836
23842
  resources;
23837
23843
  sessionConfigurations;
23838
23844
  sessionId;
23845
+ targetCommandId;
23839
23846
  turnId;
23840
- constructor(sessionId, commandId, agentId, bindingId, directoryId2, additionalDirectoryIds, images, resources, prompt, executionId, executionCapabilityId, executionCapabilitySecret, executionDeadlineAt, botId, conversationId, turnId, behaviorRevisionId, bindingRevision, localGrantId, behaviorInstructions, behaviorDigest, allowedDeliveryTargets, replyRoute, sessionConfigurations = []) {
23847
+ constructor(sessionId, commandId, agentId, bindingId, directoryId2, additionalDirectoryIds, images, resources, prompt, executionId, executionCapabilityId, executionCapabilitySecret, executionDeadlineAt, botId, conversationId, turnId, behaviorRevisionId, bindingRevision, localGrantId, behaviorInstructions, behaviorDigest, allowedDeliveryTargets, replyRoute, sessionConfigurations = [], disposition = SessionPromptDisposition.Reject, targetCommandId = "") {
23841
23848
  this.sessionId = sessionId;
23842
23849
  this.commandId = commandId;
23843
23850
  this.agentId = agentId;
23844
23851
  this.bindingId = bindingId;
23845
23852
  this.directoryId = directoryId2;
23853
+ this.disposition = disposition;
23846
23854
  this.additionalDirectoryIds = Object.freeze([...additionalDirectoryIds]);
23847
23855
  this.images = Object.freeze([...images]);
23848
23856
  this.resources = Object.freeze([...resources]);
@@ -23866,16 +23874,18 @@ var BotSessionPromptCommand = class {
23866
23874
  );
23867
23875
  this.replyRoute = replyRoute;
23868
23876
  this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
23877
+ this.targetCommandId = targetCommandId;
23869
23878
  }
23870
23879
  toJSON() {
23871
- const { sessionConfigurations, ...command } = this;
23880
+ const { disposition, sessionConfigurations, targetCommandId, ...command } = this;
23872
23881
  return {
23873
23882
  ...command,
23874
- ...sessionConfigurations.length === 0 ? {} : { sessionConfigurations }
23883
+ ...sessionConfigurations.length === 0 ? {} : { sessionConfigurations },
23884
+ ...disposition === SessionPromptDisposition.Reject ? {} : { disposition, targetCommandId }
23875
23885
  };
23876
23886
  }
23877
23887
  };
23878
- function isRecord5(value) {
23888
+ function isRecord6(value) {
23879
23889
  return typeof value === "object" && value !== null && !Array.isArray(value);
23880
23890
  }
23881
23891
  function parseJson3(encoded) {
@@ -23885,7 +23895,7 @@ function parseJson3(encoded) {
23885
23895
  } catch (cause) {
23886
23896
  throw new ProtocolMessageError("Message is not valid JSON", { cause });
23887
23897
  }
23888
- if (!isRecord5(value)) {
23898
+ if (!isRecord6(value)) {
23889
23899
  throw new ProtocolMessageError("Message must be a JSON object");
23890
23900
  }
23891
23901
  return value;
@@ -23976,7 +23986,7 @@ function readTargets(value, key) {
23976
23986
  const identifiers = /* @__PURE__ */ new Set();
23977
23987
  const aliases = /* @__PURE__ */ new Set();
23978
23988
  for (const candidate of field) {
23979
- if (!isRecord5(candidate)) {
23989
+ if (!isRecord6(candidate)) {
23980
23990
  throw new ProtocolMessageError(`Invalid Bot delivery targets: ${key}`);
23981
23991
  }
23982
23992
  assertExactKeys2(candidate, ["alias", "deliveryTargetId"]);
@@ -23998,7 +24008,7 @@ function readSessionConfigurations(value) {
23998
24008
  return decodeSessionConfigurationSelections(value["sessionConfigurations"]);
23999
24009
  }
24000
24010
  function readCompletionPolicy(value) {
24001
- if (!isRecord5(value)) {
24011
+ if (!isRecord6(value)) {
24002
24012
  throw new ProtocolMessageError("Invalid Bot completion policy");
24003
24013
  }
24004
24014
  const kind = readText2(value, "kind", 32, false);
@@ -24016,7 +24026,7 @@ function readCompletionPolicy(value) {
24016
24026
  throw new ProtocolMessageError("Invalid Bot completion policy");
24017
24027
  }
24018
24028
  function readReplyRoute(value) {
24019
- if (!isRecord5(value)) {
24029
+ if (!isRecord6(value)) {
24020
24030
  throw new ProtocolMessageError("Invalid Bot reply route");
24021
24031
  }
24022
24032
  const kind = readText2(value, "kind", 32, false);
@@ -24165,11 +24175,26 @@ function decodeBotSessionPromptCommand(encoded) {
24165
24175
  "sessionId",
24166
24176
  "turnId"
24167
24177
  ],
24168
- ["sessionConfigurations"]
24178
+ ["disposition", "sessionConfigurations", "targetCommandId"]
24169
24179
  );
24170
24180
  if (value["kind"] !== BOT_SESSION_PROMPT_KIND) {
24171
24181
  throw new ProtocolMessageError("Invalid Bot Session prompt kind");
24172
24182
  }
24183
+ const rawDisposition = value["disposition"];
24184
+ let disposition;
24185
+ if (rawDisposition === void 0 || rawDisposition === SessionPromptDisposition.Reject) {
24186
+ disposition = SessionPromptDisposition.Reject;
24187
+ } else if (rawDisposition === SessionPromptDisposition.Queue) {
24188
+ disposition = SessionPromptDisposition.Queue;
24189
+ } else if (rawDisposition === SessionPromptDisposition.Steer) {
24190
+ disposition = SessionPromptDisposition.Steer;
24191
+ } else {
24192
+ throw new ProtocolMessageError("Invalid Bot Session prompt disposition");
24193
+ }
24194
+ const targetCommandId = value["targetCommandId"] === void 0 ? "" : readText2(value, "targetCommandId", 128, false);
24195
+ if (disposition === SessionPromptDisposition.Reject && targetCommandId.length > 0 || disposition !== SessionPromptDisposition.Reject && !IDENTIFIER_PATTERN3.test(targetCommandId)) {
24196
+ throw new ProtocolMessageError("Bot Session prompt disposition has an invalid target command");
24197
+ }
24173
24198
  return new BotSessionPromptCommand(
24174
24199
  readIdentifier2(value, "sessionId"),
24175
24200
  readIdentifier2(value, "commandId"),
@@ -24194,7 +24219,9 @@ function decodeBotSessionPromptCommand(encoded) {
24194
24219
  readDigest(value, "behaviorDigest"),
24195
24220
  readTargets(value, "allowedDeliveryTargets"),
24196
24221
  readReplyRoute(value["replyRoute"]),
24197
- readSessionConfigurations(value)
24222
+ readSessionConfigurations(value),
24223
+ disposition,
24224
+ targetCommandId
24198
24225
  );
24199
24226
  }
24200
24227
 
@@ -24492,14 +24519,10 @@ var decodeSessionEventAcknowledgement = (encoded) => decode5(encoded, eventAckno
24492
24519
  var decodeSessionEventDeferred = (encoded) => decode5(encoded, eventDeferredSchema);
24493
24520
  var decodeSessionEventRejection = (encoded) => decode5(encoded, eventRejectionSchema);
24494
24521
 
24495
- // src/pairing/pair-local-machine.ts
24496
- import { fetch as fetch2 } from "undici";
24497
-
24498
24522
  // src/config.ts
24499
- import { join as join15 } from "node:path";
24500
24523
  function loadDefaultWorkspace(environment = process.env) {
24501
24524
  const { MOBIUS_DEFAULT_WORKSPACE: configuredWorkspace } = environment;
24502
- return configuredWorkspace ?? join15(readStateDirectory(environment), "workspace");
24525
+ return configuredWorkspace ?? join14(readStateDirectory(environment), "workspace");
24503
24526
  }
24504
24527
  function createDaemonConfig(connection, agents = [], installableAgents = []) {
24505
24528
  return {
@@ -24515,6 +24538,11 @@ function createDaemonConfig(connection, agents = [], installableAgents = []) {
24515
24538
  }
24516
24539
 
24517
24540
  // src/pairing/pair-local-machine.ts
24541
+ import { randomUUID as randomUUID2 } from "node:crypto";
24542
+ import { mkdir as mkdir3, open as open4, realpath as realpath6, rename as rename3, stat as stat5, writeFile as writeFile2 } from "node:fs/promises";
24543
+ import { hostname as hostname3 } from "node:os";
24544
+ import { basename, join as join15, resolve as resolve3 } from "node:path";
24545
+ import { fetch as fetch2 } from "undici";
24518
24546
  var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
24519
24547
  var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
24520
24548
  var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
@@ -24532,7 +24560,7 @@ var PairingClientError = class extends Error {
24532
24560
  this.name = "PairingClientError";
24533
24561
  }
24534
24562
  };
24535
- function isRecord6(value) {
24563
+ function isRecord7(value) {
24536
24564
  return typeof value === "object" && value !== null && !Array.isArray(value);
24537
24565
  }
24538
24566
  function hasExactKeys(value, expectedKeys) {
@@ -24625,8 +24653,8 @@ async function resolveDefaultWorkspace(path2) {
24625
24653
  const requestedWorkspace = resolve3(path2);
24626
24654
  try {
24627
24655
  await mkdir3(requestedWorkspace, { recursive: true, mode: 448 });
24628
- const defaultWorkspace = await realpath7(requestedWorkspace);
24629
- const metadata = await stat6(defaultWorkspace);
24656
+ const defaultWorkspace = await realpath6(requestedWorkspace);
24657
+ const metadata = await stat5(defaultWorkspace);
24630
24658
  if (!metadata.isDirectory()) {
24631
24659
  throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
24632
24660
  }
@@ -24655,9 +24683,9 @@ async function readJsonResponse(response) {
24655
24683
  }
24656
24684
  }
24657
24685
  function readRelayError(value) {
24658
- if (isRecord6(value)) {
24686
+ if (isRecord7(value)) {
24659
24687
  const error62 = value["error"];
24660
- if (isRecord6(error62)) {
24688
+ if (isRecord7(error62)) {
24661
24689
  const code = error62["code"];
24662
24690
  const message = error62["message"];
24663
24691
  if (typeof code === "string" && typeof message === "string") {
@@ -24668,7 +24696,7 @@ function readRelayError(value) {
24668
24696
  return new PairingClientError("pairing_failed", "The relay could not pair this machine");
24669
24697
  }
24670
24698
  function decodePairingResponse(value, credentialField, expectedKeys) {
24671
- if (!isRecord6(value) || !hasExactKeys(value, expectedKeys)) {
24699
+ if (!isRecord7(value) || !hasExactKeys(value, expectedKeys)) {
24672
24700
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
24673
24701
  }
24674
24702
  const channelId = value["channelId"];
@@ -24698,7 +24726,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
24698
24726
  installableAgents,
24699
24727
  machineName: hostname3(),
24700
24728
  pairingCode: options.code,
24701
- workspaceName: basename2(defaultWorkspace) || "Local workspace"
24729
+ workspaceName: basename(defaultWorkspace) || "Local workspace"
24702
24730
  }),
24703
24731
  dispatcher: environmentProxyDispatcher,
24704
24732
  headers: { "content-type": "application/json" },
@@ -24715,10 +24743,10 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
24715
24743
  return options.pairingId.length > 0 ? decodePairingResponse(value, "runtimeCredential", REDEEM_RESPONSE_KEYS) : decodePairingResponse(value, "daemonToken", CLAIM_RESPONSE_KEYS);
24716
24744
  }
24717
24745
  async function persistConnection(channelId, relayOrigin, runtimeCredential2, defaultWorkspace, environment) {
24718
- const connectionsDirectory = join16(readStateDirectory(environment), "connections");
24746
+ const connectionsDirectory = join15(readStateDirectory(environment), "connections");
24719
24747
  await mkdir3(connectionsDirectory, { mode: 448, recursive: true });
24720
- const connectionPath = join16(connectionsDirectory, `${channelId}.json`);
24721
- const temporaryPath = join16(connectionsDirectory, `.${channelId}.${randomUUID()}.tmp`);
24748
+ const connectionPath = join15(connectionsDirectory, `${channelId}.json`);
24749
+ const temporaryPath = join15(connectionsDirectory, `.${channelId}.${randomUUID2()}.tmp`);
24722
24750
  await writeFile2(
24723
24751
  temporaryPath,
24724
24752
  `${JSON.stringify(
@@ -24738,7 +24766,7 @@ async function persistConnection(channelId, relayOrigin, runtimeCredential2, def
24738
24766
  return connectionPath;
24739
24767
  }
24740
24768
  function decodeSavedConnection(value, expectedChannelId) {
24741
- if (!isRecord6(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
24769
+ if (!isRecord7(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
24742
24770
  throw new PairingClientError("invalid_connection", "The saved connection is invalid");
24743
24771
  }
24744
24772
  const defaultWorkspace = value["defaultWorkspace"];
@@ -24756,7 +24784,7 @@ function decodeSavedConnection(value, expectedChannelId) {
24756
24784
  };
24757
24785
  }
24758
24786
  async function readSavedConnection(channelId, environment) {
24759
- const connectionPath = join16(readStateDirectory(environment), "connections", `${channelId}.json`);
24787
+ const connectionPath = join15(readStateDirectory(environment), "connections", `${channelId}.json`);
24760
24788
  let encoded = "";
24761
24789
  const handle = await open4(connectionPath, "r");
24762
24790
  try {
@@ -24792,7 +24820,7 @@ function buildPairedDaemon(connection, connectionPath, inventory, environment) {
24792
24820
  const relayUrl = mobiusApiUrl(connection.relayOrigin, "/v1/runtimes/connect");
24793
24821
  relayUrl.protocol = relayUrl.protocol === "https:" ? "wss:" : "ws:";
24794
24822
  relayUrl.searchParams.set("token", connection.runtimeCredential);
24795
- const auditDatabasePath = join16(readStateDirectory(environment), "audit", `${connection.channelId}.sqlite`);
24823
+ const auditDatabasePath = join15(readStateDirectory(environment), "audit", `${connection.channelId}.sqlite`);
24796
24824
  return {
24797
24825
  channelUrl: new URL(`/channels/${encodeURIComponent(connection.channelId)}`, connection.relayOrigin).toString(),
24798
24826
  config: createDaemonConfig(
@@ -24842,7 +24870,7 @@ async function pairLocalMachine(arguments_, signal = new AbortController().signa
24842
24870
  }
24843
24871
  async function resumeMobiusRuntime(channelId, signal, environment = process.env) {
24844
24872
  const normalizedChannelId = validatePairingId(channelId);
24845
- const connectionPath = join16(readStateDirectory(environment), "connections", `${normalizedChannelId}.json`);
24873
+ const connectionPath = join15(readStateDirectory(environment), "connections", `${normalizedChannelId}.json`);
24846
24874
  const connection = await readSavedConnection(normalizedChannelId, environment);
24847
24875
  const inventory = await discoverLocalAgentInventory({
24848
24876
  defaultWorkspace: connection.defaultWorkspace,
@@ -24855,753 +24883,15 @@ async function resumeLocalMachine(arguments_, signal = new AbortController().sig
24855
24883
  return await resumeMobiusRuntime(parseChannelArgument(arguments_), signal, process.env);
24856
24884
  }
24857
24885
 
24858
- // src/bots/local-bot-grant-store.ts
24859
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
24860
- import { stat as stat7 } from "node:fs/promises";
24861
- import { DatabaseSync } from "node:sqlite";
24862
- var LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS = 90 * 24 * 60 * 60 * 1e3;
24863
- var identifier2 = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
24864
- var savedApprovalSchema = external_exports.object({
24865
- local_grant_id: identifier2,
24866
- bot_id: identifier2,
24867
- binding_id: identifier2,
24868
- binding_revision: external_exports.number().int().positive(),
24869
- agent_ref: identifier2,
24870
- workspace_ref: external_exports.string().min(1).max(2048),
24871
- revocation_epoch: external_exports.number().int().nonnegative(),
24872
- agent_identity_digest: external_exports.string().regex(/^[a-f0-9]{64}$/),
24873
- workspace_identity_digest: external_exports.string().regex(/^[a-f0-9]{64}$/)
24874
- }).readonly();
24875
- var LocalBotAuthorizationError = class extends Error {
24876
- code;
24877
- constructor(code, message, options = {}) {
24878
- super(message, options);
24879
- this.code = code;
24880
- this.name = "LocalBotAuthorizationError";
24881
- }
24882
- };
24883
- var LocalBotGrant = class {
24884
- agent;
24885
- agentIdentityDigest;
24886
- allowedDeliveryTargetIds;
24887
- behaviorDigest;
24888
- behaviorRevisionId;
24889
- bindingId;
24890
- bindingRevision;
24891
- botId;
24892
- expiresAt;
24893
- localGrantId;
24894
- revocationEpoch;
24895
- workspaceIdentityDigest;
24896
- workspacePath;
24897
- workspaceRef;
24898
- constructor(localGrantId, botId, behaviorRevisionId, behaviorDigest, bindingId, bindingRevision, agent, agentIdentityDigest, workspaceRef, workspacePath, workspaceIdentityDigest, allowedDeliveryTargetIds, expiresAt, revocationEpoch) {
24899
- this.localGrantId = localGrantId;
24900
- this.botId = botId;
24901
- this.behaviorRevisionId = behaviorRevisionId;
24902
- this.behaviorDigest = behaviorDigest;
24903
- this.bindingId = bindingId;
24904
- this.bindingRevision = bindingRevision;
24905
- this.agent = agent;
24906
- this.agentIdentityDigest = agentIdentityDigest;
24907
- this.workspaceRef = workspaceRef;
24908
- this.workspacePath = workspacePath;
24909
- this.workspaceIdentityDigest = workspaceIdentityDigest;
24910
- this.allowedDeliveryTargetIds = Object.freeze([...allowedDeliveryTargetIds]);
24911
- this.expiresAt = expiresAt;
24912
- this.revocationEpoch = revocationEpoch;
24913
- }
24914
- };
24915
- function digest(value) {
24916
- return createHash2("sha256").update(value, "utf8").digest("hex");
24917
- }
24918
- function agentDigest(agent) {
24919
- return digest(
24920
- JSON.stringify({
24921
- adapter: agent.adapterIdentity,
24922
- agent: agent.agentIdentity,
24923
- agentVersion: agent.agentVersion,
24924
- arguments: agent.arguments,
24925
- id: agent.id
24926
- })
24927
- );
24928
- }
24929
- async function workspaceDigest(path2) {
24930
- const metadata = await stat7(path2);
24931
- if (!metadata.isDirectory()) {
24932
- throw new LocalBotAuthorizationError("binding_incompatible", "The Bot workspace is not a directory");
24933
- }
24934
- return digest(
24935
- JSON.stringify({
24936
- changedAtMilliseconds: metadata.ctimeMs,
24937
- device: metadata.dev,
24938
- inode: metadata.ino,
24939
- path: path2
24940
- })
24941
- );
24942
- }
24943
- function exactTargets(left, right) {
24944
- if (left.length !== right.length) {
24945
- return false;
24946
- }
24947
- const expected = [...left].sort();
24948
- const actual = [...right].sort();
24949
- return expected.every((target, index2) => target === actual[index2]);
24950
- }
24951
- function exactSessionConfigurations(left, right) {
24952
- if (left.length !== right.length) {
24953
- return false;
24954
- }
24955
- const expected = new Map(left.map((selection) => [selection.configId, selection]));
24956
- return right.every((selection) => {
24957
- const approved = expected.get(selection.configId);
24958
- return approved !== void 0 && approved.booleanValue === selection.booleanValue && approved.value === selection.value && approved.valueType === selection.valueType;
24959
- });
24960
- }
24961
- function rowString(row, key) {
24962
- const value = Reflect.get(row, key);
24963
- if (typeof value !== "string") {
24964
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
24965
- }
24966
- return value;
24967
- }
24968
- function rowInteger(row, key) {
24969
- const value = Reflect.get(row, key);
24970
- if (typeof value !== "number" || !Number.isSafeInteger(value)) {
24971
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
24972
- }
24973
- return value;
24974
- }
24975
- function parseTargets(encoded) {
24976
- let value;
24977
- try {
24978
- value = JSON.parse(encoded);
24979
- } catch (cause) {
24980
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
24981
- }
24982
- if (!Array.isArray(value) || value.some((target) => typeof target !== "string")) {
24983
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
24984
- }
24985
- return value.filter((target) => typeof target === "string");
24986
- }
24987
- function parseSessionConfigurations(encoded) {
24988
- let value;
24989
- try {
24990
- value = JSON.parse(encoded);
24991
- return decodeSessionConfigurationSelections(value);
24992
- } catch (cause) {
24993
- throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
24994
- }
24995
- }
24996
- var LocalBotGrantStore = class {
24997
- #database;
24998
- static containsBot = (path2, botId) => {
24999
- const database = new DatabaseSync(path2, { readOnly: true });
25000
- try {
25001
- if (database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_bot_grants'").get() === void 0) {
25002
- return false;
25003
- }
25004
- return database.prepare("SELECT local_grant_id FROM local_bot_grants WHERE bot_id = ? LIMIT 1").get(botId) !== void 0;
25005
- } finally {
25006
- database.close();
25007
- }
25008
- };
25009
- constructor(path2) {
25010
- this.#database = new DatabaseSync(path2);
25011
- this.#database.exec(`
25012
- CREATE TABLE IF NOT EXISTS local_bot_grants (
25013
- local_grant_id TEXT PRIMARY KEY,
25014
- bot_id TEXT NOT NULL,
25015
- behavior_revision_id TEXT NOT NULL,
25016
- behavior_digest TEXT NOT NULL,
25017
- binding_id TEXT NOT NULL UNIQUE,
25018
- binding_revision INTEGER NOT NULL,
25019
- agent_ref TEXT NOT NULL,
25020
- agent_identity_digest TEXT NOT NULL,
25021
- workspace_ref TEXT NOT NULL,
25022
- workspace_path TEXT NOT NULL,
25023
- workspace_identity_digest TEXT NOT NULL,
25024
- allowed_delivery_target_ids_json TEXT NOT NULL,
25025
- unattended_policy_json TEXT NOT NULL,
25026
- created_at INTEGER NOT NULL,
25027
- expires_at INTEGER NOT NULL,
25028
- revocation_epoch INTEGER NOT NULL DEFAULT 0,
25029
- revoked_at INTEGER
25030
- ) STRICT;
25031
- CREATE TABLE IF NOT EXISTS local_bot_binding_resolutions (
25032
- request_id TEXT PRIMARY KEY,
25033
- binding_id TEXT NOT NULL,
25034
- local_grant_id TEXT NOT NULL,
25035
- resolved_at INTEGER NOT NULL,
25036
- result TEXT NOT NULL CHECK (result IN ('approved', 'unavailable')),
25037
- error_code TEXT,
25038
- error_message TEXT
25039
- ) STRICT;
25040
- CREATE TABLE IF NOT EXISTS local_bot_grant_configurations (
25041
- local_grant_id TEXT PRIMARY KEY,
25042
- session_configurations_json TEXT NOT NULL
25043
- ) STRICT;
25044
- `);
25045
- }
25046
- /** Only the local CLI may invoke this explicit approval transition. */
25047
- reapprove = async (botId, catalog, directories, bindingAuthorityId, now, signal) => {
25048
- signal.throwIfAborted();
25049
- if (!identifier2.safeParse(botId).success) {
25050
- throw new LocalBotAuthorizationError("invalid_request", "The Bot ID is invalid");
25051
- }
25052
- const row = this.#database.prepare("SELECT * FROM local_bot_grants WHERE bot_id = ? ORDER BY binding_revision DESC LIMIT 1").get(botId);
25053
- if (row === void 0) {
25054
- throw new LocalBotAuthorizationError("bot_not_found", "This machine has no saved approval for that Bot");
25055
- }
25056
- const parsed = savedApprovalSchema.safeParse(row);
25057
- if (!parsed.success) {
25058
- throw new LocalBotAuthorizationError("local_grant_invalid", "The saved Bot approval is invalid", {
25059
- cause: parsed.error
25060
- });
25061
- }
25062
- const saved = parsed.data;
25063
- const agent = catalog.find(saved.agent_ref);
25064
- if (!agent.capabilities.embeddedContextPrompt) {
25065
- throw new LocalBotAuthorizationError("binding_incompatible", "The local Agent cannot apply Bot context");
25066
- }
25067
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
25068
- revalidateExecutable(agent.adapterIdentity),
25069
- revalidateExecutable(agent.agentIdentity)
25070
- ]);
25071
- signal.throwIfAborted();
25072
- if (!adapterUnchanged || !agentUnchanged) {
25073
- throw new LocalBotAuthorizationError(
25074
- "binding_incompatible",
25075
- "The local Agent executable changed before approval"
25076
- );
25077
- }
25078
- const workspacePath = await directories.resolve(bindingAuthorityId, saved.workspace_ref, signal);
25079
- const workspaceIdentityDigest = await workspaceDigest(workspacePath);
25080
- signal.throwIfAborted();
25081
- this.#database.exec("BEGIN IMMEDIATE");
25082
- try {
25083
- const result = this.#database.prepare(`UPDATE local_bot_grants
25084
- SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
25085
- revoked_at = NULL, expires_at = ?, revocation_epoch = revocation_epoch + 1
25086
- WHERE local_grant_id = ? AND revocation_epoch = ?
25087
- AND agent_identity_digest = ? AND workspace_identity_digest = ?
25088
- AND binding_revision = (SELECT MAX(binding_revision) FROM local_bot_grants WHERE bot_id = ?)`).run(
25089
- agentDigest(agent),
25090
- workspaceIdentityDigest,
25091
- workspacePath,
25092
- now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS,
25093
- saved.local_grant_id,
25094
- saved.revocation_epoch,
25095
- saved.agent_identity_digest,
25096
- saved.workspace_identity_digest,
25097
- botId
25098
- );
25099
- if (result.changes !== 1) {
25100
- throw new LocalBotAuthorizationError(
25101
- "binding_not_approved",
25102
- "The Bot binding changed during approval; run the command again"
25103
- );
25104
- }
25105
- this.#database.prepare(`INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
25106
- VALUES (?, 'bot_binding_locally_reapproved', ?, '', ?)`).run(
25107
- new Date(now).toISOString(),
25108
- saved.binding_id,
25109
- JSON.stringify({ botId, bindingId: saved.binding_id, agentRef: saved.agent_ref })
25110
- );
25111
- this.#database.exec("COMMIT");
25112
- } catch (cause) {
25113
- this.#database.exec("ROLLBACK");
25114
- throw cause;
25115
- }
25116
- return { bindingId: saved.binding_id, workspacePath, agentRef: saved.agent_ref };
25117
- };
25118
- approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
25119
- signal.throwIfAborted();
25120
- const existing = this.#database.prepare(
25121
- `SELECT grants.* FROM local_bot_binding_resolutions AS resolutions
25122
- INNER JOIN local_bot_grants AS grants
25123
- ON grants.local_grant_id = resolutions.local_grant_id
25124
- WHERE resolutions.request_id = ? AND resolutions.binding_id = ?
25125
- AND resolutions.result = 'approved'`
25126
- ).get(request.requestId, request.bindingId);
25127
- if (existing !== void 0) {
25128
- return new BotExecutionBindingApprovedEvent(
25129
- request.requestId,
25130
- request.botId,
25131
- request.behaviorRevisionId,
25132
- request.bindingId,
25133
- request.bindingRevision,
25134
- rowString(existing, "local_grant_id"),
25135
- rowString(existing, "agent_identity_digest"),
25136
- rowString(existing, "workspace_identity_digest")
25137
- );
25138
- }
25139
- const resolved = await this.resolveProposal(request, catalog, directories, bindingAuthorityId, signal);
25140
- const localGrantId = `lbg_${randomUUID2()}`;
25141
- const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
25142
- this.#database.exec("BEGIN IMMEDIATE");
25143
- try {
25144
- this.#database.prepare(
25145
- `INSERT INTO local_bot_grants (
25146
- local_grant_id, bot_id, behavior_revision_id, behavior_digest,
25147
- binding_id, binding_revision, agent_ref,
25148
- agent_identity_digest, workspace_ref, workspace_path,
25149
- workspace_identity_digest, allowed_delivery_target_ids_json,
25150
- unattended_policy_json, created_at, expires_at
25151
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
25152
- ).run(
25153
- localGrantId,
25154
- request.botId,
25155
- request.behaviorRevisionId,
25156
- request.behaviorDigest,
25157
- request.bindingId,
25158
- request.bindingRevision,
25159
- request.agentRef,
25160
- resolved.agentIdentityDigest,
25161
- request.workspaceRef,
25162
- resolved.workspacePath,
25163
- resolved.workspaceIdentityDigest,
25164
- JSON.stringify(request.allowedDeliveryTargets.map((target) => target.deliveryTargetId)),
25165
- JSON.stringify({ localSideEffects: "owner-approval-required" }),
25166
- now,
25167
- expiresAt
25168
- );
25169
- this.#database.prepare(
25170
- `INSERT INTO local_bot_grant_configurations (
25171
- local_grant_id, session_configurations_json
25172
- ) VALUES (?, ?)`
25173
- ).run(localGrantId, JSON.stringify(request.sessionConfigurations));
25174
- this.#database.prepare(
25175
- `INSERT INTO local_bot_binding_resolutions (
25176
- request_id, binding_id, local_grant_id, resolved_at, result
25177
- ) VALUES (?, ?, ?, ?, 'approved')`
25178
- ).run(request.requestId, request.bindingId, localGrantId, now);
25179
- this.#database.exec("COMMIT");
25180
- } catch (cause) {
25181
- this.#database.exec("ROLLBACK");
25182
- throw cause;
25183
- }
25184
- signal.throwIfAborted();
25185
- return new BotExecutionBindingApprovedEvent(
25186
- request.requestId,
25187
- request.botId,
25188
- request.behaviorRevisionId,
25189
- request.bindingId,
25190
- request.bindingRevision,
25191
- localGrantId,
25192
- resolved.agentIdentityDigest,
25193
- resolved.workspaceIdentityDigest
25194
- );
25195
- };
25196
- resolveExecution = async (command, catalog, directories, bindingAuthorityId, now, signal) => {
25197
- signal.throwIfAborted();
25198
- const row = this.#database.prepare(
25199
- `SELECT grants.*, COALESCE(configurations.session_configurations_json, '[]')
25200
- AS session_configurations_json
25201
- FROM local_bot_grants AS grants
25202
- LEFT JOIN local_bot_grant_configurations AS configurations
25203
- ON configurations.local_grant_id = grants.local_grant_id
25204
- WHERE grants.local_grant_id = ? AND grants.bot_id = ?
25205
- AND behavior_revision_id = ? AND behavior_digest = ?
25206
- AND binding_id = ? AND binding_revision = ?
25207
- AND agent_ref = ?
25208
- AND revoked_at IS NULL AND expires_at > ?`
25209
- ).get(
25210
- command.localGrantId,
25211
- command.botId,
25212
- command.behaviorRevisionId,
25213
- command.behaviorDigest,
25214
- command.bindingId,
25215
- command.bindingRevision,
25216
- command.agentId,
25217
- now
25218
- );
25219
- if (row === void 0) {
25220
- throw new LocalBotAuthorizationError(
25221
- "binding_not_approved",
25222
- "The Bot execution binding is not locally approved"
25223
- );
25224
- }
25225
- const approvedTargets = parseTargets(rowString(row, "allowed_delivery_target_ids_json"));
25226
- const requestedTargets = command.allowedDeliveryTargets.map((target) => target.deliveryTargetId);
25227
- if (!exactTargets(approvedTargets, requestedTargets)) {
25228
- throw new LocalBotAuthorizationError(
25229
- "binding_not_approved",
25230
- "The Bot execution target policy changed after local approval"
25231
- );
25232
- }
25233
- const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
25234
- if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
25235
- throw new LocalBotAuthorizationError(
25236
- "binding_not_approved",
25237
- "The Bot Agent configuration changed after local approval"
25238
- );
25239
- }
25240
- const agent = catalog.find(command.agentId);
25241
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
25242
- revalidateExecutable(agent.adapterIdentity),
25243
- revalidateExecutable(agent.agentIdentity)
25244
- ]);
25245
- signal.throwIfAborted();
25246
- const workspaceRef = rowString(row, "workspace_ref");
25247
- const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
25248
- const currentAgentDigest = agentDigest(agent);
25249
- const currentWorkspaceDigest = await workspaceDigest(workspacePath);
25250
- signal.throwIfAborted();
25251
- if (!adapterUnchanged || !agentUnchanged || currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path")) {
25252
- this.revoke(rowString(row, "local_grant_id"), now);
25253
- throw new LocalBotAuthorizationError(
25254
- "binding_not_approved",
25255
- "The Bot execution target changed and requires local approval"
25256
- );
25257
- }
25258
- if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
25259
- throw new LocalBotAuthorizationError(
25260
- "binding_incompatible",
25261
- "The local Agent cannot apply the approved Bot behavior"
25262
- );
25263
- }
25264
- return new LocalBotGrant(
25265
- rowString(row, "local_grant_id"),
25266
- command.botId,
25267
- command.behaviorRevisionId,
25268
- command.behaviorDigest,
25269
- command.bindingId,
25270
- command.bindingRevision,
25271
- agent,
25272
- currentAgentDigest,
25273
- workspaceRef,
25274
- workspacePath,
25275
- currentWorkspaceDigest,
25276
- approvedTargets,
25277
- rowInteger(row, "expires_at"),
25278
- rowInteger(row, "revocation_epoch")
25279
- );
25280
- };
25281
- recordUnavailable = (request, code, message, now) => {
25282
- this.#database.prepare(
25283
- `INSERT OR IGNORE INTO local_bot_binding_resolutions (
25284
- request_id, binding_id, local_grant_id, resolved_at,
25285
- result, error_code, error_message
25286
- ) VALUES (?, ?, '', ?, 'unavailable', ?, ?)`
25287
- ).run(request.requestId, request.bindingId, now, code, message);
25288
- };
25289
- close = () => {
25290
- this.#database.close();
25291
- };
25292
- resolveProposal = async (request, catalog, directories, bindingAuthorityId, signal) => {
25293
- const agent = catalog.find(request.agentRef);
25294
- if (request.requiredCapabilities.includes("embedded-context") && !agent.capabilities.embeddedContextPrompt) {
25295
- throw new LocalBotAuthorizationError(
25296
- "binding_incompatible",
25297
- "The local Agent cannot apply embedded Bot context"
25298
- );
25299
- }
25300
- if (request.requiredCapabilities.some((capability) => capability !== "embedded-context")) {
25301
- throw new LocalBotAuthorizationError(
25302
- "binding_incompatible",
25303
- "The Bot requires an unsupported local Agent capability"
25304
- );
25305
- }
25306
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
25307
- revalidateExecutable(agent.adapterIdentity),
25308
- revalidateExecutable(agent.agentIdentity)
25309
- ]);
25310
- signal.throwIfAborted();
25311
- if (!adapterUnchanged || !agentUnchanged) {
25312
- throw new LocalBotAuthorizationError(
25313
- "binding_incompatible",
25314
- "The local Agent executable changed before approval"
25315
- );
25316
- }
25317
- const workspacePath = await directories.resolve(bindingAuthorityId, request.workspaceRef, signal);
25318
- return {
25319
- agent,
25320
- agentIdentityDigest: agentDigest(agent),
25321
- workspaceIdentityDigest: await workspaceDigest(workspacePath),
25322
- workspacePath
25323
- };
25324
- };
25325
- revoke = (localGrantId, now) => {
25326
- this.#database.prepare(
25327
- `UPDATE local_bot_grants
25328
- SET revoked_at = COALESCE(revoked_at, ?), revocation_epoch = revocation_epoch + 1
25329
- WHERE local_grant_id = ? AND revoked_at IS NULL`
25330
- ).run(now, localGrantId);
25331
- };
25332
- };
25333
-
25334
- // src/bots/bot-approve-command.ts
25335
- var identifier3 = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
25336
- var argumentsSchema = external_exports.union([
25337
- external_exports.tuple([external_exports.literal("--bot"), identifier3]),
25338
- external_exports.tuple([external_exports.literal("--bot"), identifier3, external_exports.literal("--channel"), identifier3])
25339
- ]);
25340
- async function executeBotApproveCommand(arguments_, environment, parent) {
25341
- const parsed = argumentsSchema.safeParse(arguments_);
25342
- if (!parsed.success) {
25343
- throw new LocalBotAuthorizationError(
25344
- "invalid_arguments",
25345
- "Usage: mobius bot approve --bot <bot-id> [--channel <channel-id>]"
25346
- );
25347
- }
25348
- const [, botId, , requestedChannel] = parsed.data;
25349
- const signal = AbortSignal.any([parent, AbortSignal.timeout(3e4)]);
25350
- signal.throwIfAborted();
25351
- try {
25352
- const stateDirectory = await realpath8(readStateDirectory(environment));
25353
- const auditDirectory = await realpath8(join17(stateDirectory, "audit"));
25354
- if (dirname4(auditDirectory) !== stateDirectory) {
25355
- throw new LocalBotAuthorizationError(
25356
- "local_grant_invalid",
25357
- "The local approval directory is outside the Mobius state directory"
25358
- );
25359
- }
25360
- const channels = [];
25361
- for (const entry of await readdir3(auditDirectory, { withFileTypes: true })) {
25362
- signal.throwIfAborted();
25363
- if (!entry.isFile() || !entry.name.endsWith(".sqlite")) {
25364
- continue;
25365
- }
25366
- const channelId2 = entry.name.slice(0, -7);
25367
- if (!identifier3.safeParse(channelId2).success || requestedChannel !== void 0 && requestedChannel !== channelId2) {
25368
- continue;
25369
- }
25370
- const databasePath = await realpath8(join17(auditDirectory, entry.name));
25371
- if (dirname4(databasePath) !== auditDirectory) {
25372
- throw new LocalBotAuthorizationError(
25373
- "local_grant_invalid",
25374
- "The local approval database is outside the Mobius audit directory"
25375
- );
25376
- }
25377
- if (LocalBotGrantStore.containsBot(databasePath, botId)) {
25378
- channels.push(channelId2);
25379
- }
25380
- }
25381
- const channelId = channels[0];
25382
- if (channelId === void 0) {
25383
- throw new LocalBotAuthorizationError(
25384
- "bot_not_found",
25385
- "No saved approval for this Bot was found. Run this command on the machine hosting the Bot."
25386
- );
25387
- }
25388
- if (channels.length !== 1) {
25389
- throw new LocalBotAuthorizationError(
25390
- "binding_ambiguous",
25391
- `This Bot has approvals in multiple local channels. Add --channel with the intended channel: ${channels.join(", ")}`
25392
- );
25393
- }
25394
- const { config: config2 } = await resumeMobiusRuntime(channelId, signal, environment);
25395
- signal.throwIfAborted();
25396
- const grants = new LocalBotGrantStore(config2.auditDatabasePath);
25397
- try {
25398
- const approval = await grants.reapprove(
25399
- botId,
25400
- config2.catalog,
25401
- new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace),
25402
- config2.bindingId,
25403
- Date.now(),
25404
- signal
25405
- );
25406
- return `Approved Bot ${botId}
25407
- Binding: ${approval.bindingId}
25408
- Agent: ${approval.agentRef}
25409
- Workspace: ${approval.workspacePath}
25410
- Keep your daemon running and resend your message in the same Chat conversation.
25411
- `;
25412
- } finally {
25413
- grants.close();
25414
- }
25415
- } catch (cause) {
25416
- parent.throwIfAborted();
25417
- if (signal.aborted) {
25418
- throw new LocalBotAuthorizationError("approval_timeout", "Local Bot approval timed out", { cause });
25419
- }
25420
- if (cause instanceof LocalBotAuthorizationError) {
25421
- throw cause;
25422
- }
25423
- if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") {
25424
- throw new LocalBotAuthorizationError(
25425
- "bot_not_found",
25426
- "No saved local approval or Runtime connection was found for this Bot",
25427
- { cause }
25428
- );
25429
- }
25430
- throw new LocalBotAuthorizationError(
25431
- "local_approval_failed",
25432
- "Local Bot approval failed. Check the saved Runtime connection and local Agent installation.",
25433
- { cause }
25434
- );
25435
- }
25436
- }
25437
-
25438
- // src/bots/bot-message-command.ts
25439
- import { randomUUID as randomUUID3 } from "node:crypto";
25440
- import { createConnection } from "node:net";
25441
- var BOT_IPC_RESPONSE_LIMIT = 64 * 1024;
25442
- var BOT_IPC_TIMEOUT_MILLISECONDS = 2e4;
25443
- var BotMessageCommandError = class extends Error {
25444
- code;
25445
- constructor(code, message, options = {}) {
25446
- super(message, options);
25447
- this.code = code;
25448
- this.name = "BotMessageCommandError";
25449
- }
25450
- };
25451
- function isRecord7(value) {
25452
- return typeof value === "object" && value !== null && !Array.isArray(value);
25453
- }
25454
- function requiredEnvironment(environment, name) {
25455
- const value = environment[name]?.trim();
25456
- if (value === void 0 || value.length === 0) {
25457
- throw new BotMessageCommandError(
25458
- "execution_context_required",
25459
- "This command is available only inside an active Mobius Bot execution"
25460
- );
25461
- }
25462
- return value;
25463
- }
25464
- function option(arguments_, name) {
25465
- const index2 = arguments_.indexOf(name);
25466
- if (index2 < 0 || index2 + 1 >= arguments_.length || arguments_[index2 + 1]?.startsWith("--") === true) {
25467
- throw new BotMessageCommandError(
25468
- "invalid_request",
25469
- "Usage: mobius bot message send --target <current|alias> --text <message>"
25470
- );
25471
- }
25472
- const value = arguments_[index2 + 1];
25473
- if (value === void 0) {
25474
- throw new BotMessageCommandError("invalid_request", "The Bot message option is missing");
25475
- }
25476
- return value;
25477
- }
25478
- function validateArguments(arguments_) {
25479
- if (arguments_.length !== 4) {
25480
- throw new BotMessageCommandError(
25481
- "invalid_request",
25482
- "Usage: mobius bot message send --target <current|alias> --text <message>"
25483
- );
25484
- }
25485
- const names = [arguments_[0], arguments_[2]];
25486
- if (!names.includes("--target") || !names.includes("--text") || names[0] === names[1]) {
25487
- throw new BotMessageCommandError(
25488
- "invalid_request",
25489
- "Usage: mobius bot message send --target <current|alias> --text <message>"
25490
- );
25491
- }
25492
- }
25493
- function decodeResponse(encoded) {
25494
- let value;
25495
- try {
25496
- value = JSON.parse(encoded);
25497
- } catch (cause) {
25498
- throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data", {
25499
- cause
25500
- });
25501
- }
25502
- if (!isRecord7(value) || typeof value["ok"] !== "boolean") {
25503
- throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data");
25504
- }
25505
- if (value["ok"] === true && typeof value["outboundMessageId"] === "string") {
25506
- return value["outboundMessageId"];
25507
- }
25508
- const error62 = value["error"];
25509
- if (value["ok"] === false && isRecord7(error62) && typeof error62["code"] === "string" && typeof error62["message"] === "string") {
25510
- throw new BotMessageCommandError(error62["code"], error62["message"]);
25511
- }
25512
- throw new BotMessageCommandError("bot_service_unavailable", "The local Bot service returned invalid data");
25513
- }
25514
- async function requestLocalBotService(socketPath, payload, signal) {
25515
- signal.throwIfAborted();
25516
- return await new Promise((resolve5, reject) => {
25517
- const socket = createConnection(socketPath);
25518
- const chunks = [];
25519
- let length = 0;
25520
- let finished = false;
25521
- const finish = () => {
25522
- socket.removeAllListeners();
25523
- socket.destroy();
25524
- };
25525
- const fail = (error62) => {
25526
- if (finished) {
25527
- return;
25528
- }
25529
- finished = true;
25530
- finish();
25531
- if (error62 instanceof BotMessageCommandError) {
25532
- reject(error62);
25533
- return;
25534
- }
25535
- reject(
25536
- new BotMessageCommandError(
25537
- "execution_context_required",
25538
- "The active Mobius Bot execution is unavailable",
25539
- { cause: error62 }
25540
- )
25541
- );
25542
- };
25543
- const abort = () => fail(signal.reason);
25544
- socket.setTimeout(BOT_IPC_TIMEOUT_MILLISECONDS, () => {
25545
- fail(new BotMessageCommandError("bot_service_unavailable", "The local Bot service timed out"));
25546
- });
25547
- socket.once("error", fail);
25548
- socket.once("connect", () => socket.end(`${payload}
25549
- `));
25550
- socket.on("data", (chunk) => {
25551
- length += chunk.byteLength;
25552
- if (length > BOT_IPC_RESPONSE_LIMIT) {
25553
- fail(new BotMessageCommandError("bot_service_unavailable", "The local Bot response is too large"));
25554
- return;
25555
- }
25556
- chunks.push(chunk);
25557
- });
25558
- socket.once("end", () => {
25559
- if (finished) {
25560
- return;
25561
- }
25562
- finished = true;
25563
- signal.removeEventListener("abort", abort);
25564
- try {
25565
- resolve5(decodeResponse(Buffer.concat(chunks).toString("utf8")));
25566
- } catch (error62) {
25567
- reject(error62);
25568
- } finally {
25569
- finish();
25570
- }
25571
- });
25572
- signal.addEventListener("abort", abort, { once: true });
25573
- });
25574
- }
25575
- async function executeBotMessageCommand(arguments_, environment, signal) {
25576
- validateArguments(arguments_);
25577
- const contextHandle = requiredEnvironment(environment, "MOBIUS_BOT_CONTEXT");
25578
- const socketPath = requiredEnvironment(environment, "MOBIUS_BOT_SOCKET");
25579
- const target = option(arguments_, "--target");
25580
- const text3 = option(arguments_, "--text");
25581
- if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(target) || text3.trim().length === 0 || text3.length > 1e4) {
25582
- throw new BotMessageCommandError("invalid_request", "The Bot outbound message is invalid");
25583
- }
25584
- return await requestLocalBotService(
25585
- socketPath,
25586
- JSON.stringify({
25587
- contextHandle,
25588
- idempotencyKey: `cli_${randomUUID3()}`,
25589
- target,
25590
- text: text3
25591
- }),
25592
- signal
25593
- );
25594
- }
25595
-
25596
24886
  // src/audit/audit-store.ts
25597
24887
  import { mkdirSync } from "node:fs";
25598
- import { dirname as dirname5 } from "node:path";
25599
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
24888
+ import { dirname as dirname3 } from "node:path";
24889
+ import { DatabaseSync } from "node:sqlite";
25600
24890
  var AuditStore = class {
25601
24891
  database;
25602
24892
  constructor(path2) {
25603
- mkdirSync(dirname5(path2), { recursive: true });
25604
- this.database = new DatabaseSync2(path2);
24893
+ mkdirSync(dirname3(path2), { recursive: true });
24894
+ this.database = new DatabaseSync(path2);
25605
24895
  this.database.exec(`
25606
24896
  CREATE TABLE IF NOT EXISTS audit_events (
25607
24897
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -25643,7 +24933,7 @@ var AuditStore = class {
25643
24933
 
25644
24934
  // src/run-daemon.ts
25645
24935
  import { randomUUID as randomUUID6 } from "node:crypto";
25646
- import { basename as basename5, join as join18 } from "node:path";
24936
+ import { basename as basename5, join as join17 } from "node:path";
25647
24937
  import { styleText } from "node:util";
25648
24938
  import { fetch as fetch7, WebSocket as WebSocket2 } from "undici";
25649
24939
 
@@ -25653,12 +24943,12 @@ import {
25653
24943
  methods as methods6,
25654
24944
  ndJsonStream as ndJsonStream2,
25655
24945
  PROTOCOL_VERSION as PROTOCOL_VERSION2,
25656
- RequestError as RequestError2
24946
+ RequestError as RequestError3
25657
24947
  } from "@agentclientprotocol/sdk";
25658
24948
 
25659
24949
  // src/authorization/local-raster.ts
25660
- import { readFile as readFile2, realpath as realpath9, stat as stat8 } from "node:fs/promises";
25661
- import { basename as basename3, isAbsolute as isAbsolute9, normalize as normalize3, relative as relative5, sep as sep4 } from "node:path";
24950
+ import { readFile as readFile2, realpath as realpath7, stat as stat6 } from "node:fs/promises";
24951
+ import { basename as basename2, isAbsolute as isAbsolute8, normalize as normalize2, relative as relative4, sep as sep4 } from "node:path";
25662
24952
  import { fileURLToPath } from "node:url";
25663
24953
  var MAX_LOCAL_RASTER_BYTES = 3e6;
25664
24954
  var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
@@ -25714,21 +25004,21 @@ function readInlineRaster(data, name = "Image") {
25714
25004
  if (mimeType === null) {
25715
25005
  return null;
25716
25006
  }
25717
- return new LocalRasterImage(basename3(name) || "Image", mimeType, bytes);
25007
+ return new LocalRasterImage(basename2(name) || "Image", mimeType, bytes);
25718
25008
  }
25719
25009
  function isInsideRoot(root, target) {
25720
- const relation = relative5(root, target);
25721
- return relation !== ".." && !relation.startsWith(`..${sep4}`) && !isAbsolute9(relation);
25010
+ const relation = relative4(root, target);
25011
+ return relation !== ".." && !relation.startsWith(`..${sep4}`) && !isAbsolute8(relation);
25722
25012
  }
25723
25013
  async function resolveCanonicalPath(requested, signal) {
25724
25014
  signal.throwIfAborted();
25725
- if (!isAbsolute9(requested) || requested.includes("\0") || normalize3(requested) !== requested) {
25015
+ if (!isAbsolute8(requested) || requested.includes("\0") || normalize2(requested) !== requested) {
25726
25016
  return null;
25727
25017
  }
25728
25018
  try {
25729
- const target = await realpath9(requested);
25019
+ const target = await realpath7(requested);
25730
25020
  signal.throwIfAborted();
25731
- if (!isAbsolute9(target) || normalize3(target) !== target) {
25021
+ if (!isAbsolute8(target) || normalize2(target) !== target) {
25732
25022
  return null;
25733
25023
  }
25734
25024
  return target;
@@ -25774,7 +25064,7 @@ async function readAuthorizedRaster(uri, roots, signal) {
25774
25064
  if (target === null) {
25775
25065
  return null;
25776
25066
  }
25777
- const targetMetadata = await stat8(target);
25067
+ const targetMetadata = await stat6(target);
25778
25068
  signal.throwIfAborted();
25779
25069
  if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
25780
25070
  return null;
@@ -25785,7 +25075,7 @@ async function readAuthorizedRaster(uri, roots, signal) {
25785
25075
  if (directory === null) {
25786
25076
  continue;
25787
25077
  }
25788
- const metadata = await stat8(directory);
25078
+ const metadata = await stat6(directory);
25789
25079
  signal.throwIfAborted();
25790
25080
  if (metadata.isDirectory()) {
25791
25081
  authorizedRoots.push(directory);
@@ -25803,7 +25093,7 @@ async function readAuthorizedRaster(uri, roots, signal) {
25803
25093
  if (mimeType === null) {
25804
25094
  return null;
25805
25095
  }
25806
- return new LocalRasterImage(basename3(target) || "Image", mimeType, bytes);
25096
+ return new LocalRasterImage(basename2(target) || "Image", mimeType, bytes);
25807
25097
  }
25808
25098
 
25809
25099
  // src/infra/operation-metrics.ts
@@ -30407,7 +29697,7 @@ var titleBefore = {
30407
29697
  };
30408
29698
  function tokenizeDefinition(effects, ok2, nok) {
30409
29699
  const self = this;
30410
- let identifier4;
29700
+ let identifier2;
30411
29701
  return start;
30412
29702
  function start(code) {
30413
29703
  effects.enter("definition");
@@ -30426,7 +29716,7 @@ function tokenizeDefinition(effects, ok2, nok) {
30426
29716
  )(code);
30427
29717
  }
30428
29718
  function labelAfter(code) {
30429
- identifier4 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
29719
+ identifier2 = normalizeIdentifier(self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1));
30430
29720
  if (code === 58) {
30431
29721
  effects.enter("definitionMarker");
30432
29722
  effects.consume(code);
@@ -30460,7 +29750,7 @@ function tokenizeDefinition(effects, ok2, nok) {
30460
29750
  function afterWhitespace(code) {
30461
29751
  if (code === null || markdownLineEnding(code)) {
30462
29752
  effects.exit("definition");
30463
- self.parser.defined.push(identifier4);
29753
+ self.parser.defined.push(identifier2);
30464
29754
  return ok2(code);
30465
29755
  }
30466
29756
  return nok(code);
@@ -34092,8 +33382,8 @@ var AcpHistoryReplay = class {
34092
33382
 
34093
33383
  // src/acp/session-store.ts
34094
33384
  import { mkdirSync as mkdirSync2 } from "node:fs";
34095
- import { dirname as dirname6 } from "node:path";
34096
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
33385
+ import { dirname as dirname4 } from "node:path";
33386
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
34097
33387
  var AcpStoredSession = class {
34098
33388
  additionalDirectories;
34099
33389
  agentId;
@@ -34195,8 +33485,8 @@ var MemoryAcpSessionStore = class {
34195
33485
  var SqliteAcpSessionStore = class {
34196
33486
  #database;
34197
33487
  constructor(path2) {
34198
- mkdirSync2(dirname6(path2), { recursive: true });
34199
- this.#database = new DatabaseSync3(path2);
33488
+ mkdirSync2(dirname4(path2), { recursive: true });
33489
+ this.#database = new DatabaseSync2(path2);
34200
33490
  this.#database.exec(`
34201
33491
  CREATE TABLE IF NOT EXISTS acp_deleted_sessions (session_id TEXT PRIMARY KEY) STRICT;
34202
33492
  CREATE TABLE IF NOT EXISTS acp_sessions (
@@ -34295,6 +33585,7 @@ var SqliteAcpSessionStore = class {
34295
33585
 
34296
33586
  // src/acp/session-manager.ts
34297
33587
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
33588
+ var MAX_ACP_PROCESSES = 10;
34298
33589
  var MAX_PRE_SESSION_UPDATES = 100;
34299
33590
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
34300
33591
  var SESSION_CONTROL_COMMAND_ID = "session-control";
@@ -34353,6 +33644,91 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
34353
33644
  this.name = "RetryableAcpInitializationError";
34354
33645
  }
34355
33646
  };
33647
+ var AcpProcessCapacityLease = class {
33648
+ #releaseCapacity;
33649
+ #released = false;
33650
+ constructor(releaseCapacity) {
33651
+ this.#releaseCapacity = releaseCapacity;
33652
+ }
33653
+ release = () => {
33654
+ if (this.#released) {
33655
+ return;
33656
+ }
33657
+ this.#released = true;
33658
+ this.#releaseCapacity();
33659
+ };
33660
+ };
33661
+ var AcpProcessCapacityWaiter = class {
33662
+ completion = Promise.withResolvers();
33663
+ signal;
33664
+ constructor(signal) {
33665
+ this.signal = signal;
33666
+ }
33667
+ cancel = () => {
33668
+ try {
33669
+ this.signal.throwIfAborted();
33670
+ } catch (error62) {
33671
+ this.completion.reject(error62);
33672
+ }
33673
+ };
33674
+ };
33675
+ var AcpProcessCapacityLock = class {
33676
+ #locked = false;
33677
+ #waiters = [];
33678
+ acquire = async (signal) => {
33679
+ signal.throwIfAborted();
33680
+ if (!this.#locked) {
33681
+ this.#locked = true;
33682
+ return new AcpProcessCapacityLease(this.#release);
33683
+ }
33684
+ const waiter = new AcpProcessCapacityWaiter(signal);
33685
+ this.#waiters.push(waiter);
33686
+ signal.addEventListener("abort", waiter.cancel, { once: true });
33687
+ if (signal.aborted) {
33688
+ waiter.cancel();
33689
+ }
33690
+ try {
33691
+ return await waiter.completion.promise;
33692
+ } finally {
33693
+ signal.removeEventListener("abort", waiter.cancel);
33694
+ const index2 = this.#waiters.indexOf(waiter);
33695
+ if (index2 >= 0) {
33696
+ this.#waiters.splice(index2, 1);
33697
+ }
33698
+ }
33699
+ };
33700
+ #release = () => {
33701
+ while (this.#waiters.length > 0) {
33702
+ const waiter = this.#waiters.shift();
33703
+ if (waiter === void 0 || waiter.signal.aborted) {
33704
+ continue;
33705
+ }
33706
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
33707
+ return;
33708
+ }
33709
+ this.#locked = false;
33710
+ };
33711
+ };
33712
+ async function waitForAcpProcessCapacity(completion, signal) {
33713
+ signal.throwIfAborted();
33714
+ const cancelled = Promise.withResolvers();
33715
+ const cancel = () => {
33716
+ try {
33717
+ signal.throwIfAborted();
33718
+ } catch (error62) {
33719
+ cancelled.reject(error62);
33720
+ }
33721
+ };
33722
+ signal.addEventListener("abort", cancel, { once: true });
33723
+ if (signal.aborted) {
33724
+ cancel();
33725
+ }
33726
+ try {
33727
+ await Promise.race([completion, cancelled.promise]);
33728
+ } finally {
33729
+ signal.removeEventListener("abort", cancel);
33730
+ }
33731
+ }
34356
33732
  function readableWebStream(input2) {
34357
33733
  let streamOpen = true;
34358
33734
  return new ReadableStream({
@@ -35840,20 +35216,23 @@ var AcpProcessSession = class _AcpProcessSession {
35840
35216
  }
35841
35217
  };
35842
35218
  close = async () => {
35843
- await this.cancelPendingInteractions();
35844
- if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
35845
- try {
35846
- await this.#connection.agent.request(
35847
- methods6.agent.session.close,
35848
- { sessionId: this.#nativeSessionId },
35849
- {
35850
- cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
35851
- }
35852
- );
35853
- } catch {
35219
+ try {
35220
+ await this.cancelPendingInteractions();
35221
+ if (this.#capabilities.closeSession && this.#nativeSessionId.length > 0) {
35222
+ try {
35223
+ await this.#connection.agent.request(
35224
+ methods6.agent.session.close,
35225
+ { sessionId: this.#nativeSessionId },
35226
+ {
35227
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
35228
+ }
35229
+ );
35230
+ } catch {
35231
+ }
35854
35232
  }
35233
+ } finally {
35234
+ await this.closeProcess();
35855
35235
  }
35856
- await this.closeProcess();
35857
35236
  };
35858
35237
  closeProcess = async (capturedProcesses = []) => {
35859
35238
  try {
@@ -35886,7 +35265,7 @@ var AcpProcessSession = class _AcpProcessSession {
35886
35265
  ]);
35887
35266
  } catch (error62) {
35888
35267
  signal.throwIfAborted();
35889
- if (error62 instanceof RequestError2 && error62.code === -32e3) {
35268
+ if (error62 instanceof RequestError3 && error62.code === -32e3) {
35890
35269
  throw new AcpExecutionError(
35891
35270
  "Agent authentication is required",
35892
35271
  { cause: error62 },
@@ -35960,6 +35339,31 @@ var AcpProcessSession = class _AcpProcessSession {
35960
35339
  }
35961
35340
  };
35962
35341
  };
35342
+ var AcpProcessEvictionCandidate = class {
35343
+ };
35344
+ var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
35345
+ };
35346
+ var FoundAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
35347
+ runtime;
35348
+ constructor(runtime) {
35349
+ super();
35350
+ this.runtime = runtime;
35351
+ }
35352
+ };
35353
+ var FoundAcpSessionProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
35354
+ sessionId;
35355
+ constructor(sessionId, runtime) {
35356
+ super(runtime);
35357
+ this.sessionId = sessionId;
35358
+ }
35359
+ };
35360
+ var FoundAcpNativeBrowserProcessEvictionCandidate = class extends FoundAcpProcessEvictionCandidate {
35361
+ sessionId;
35362
+ constructor(sessionId, runtime) {
35363
+ super(runtime);
35364
+ this.sessionId = sessionId;
35365
+ }
35366
+ };
35963
35367
  var AcpSessionManager = class {
35964
35368
  #activeCommandIds = /* @__PURE__ */ new Map();
35965
35369
  #agentSettingsObserver = new NullAcpSessionObserver();
@@ -35968,10 +35372,18 @@ var AcpSessionManager = class {
35968
35372
  #nativeBrowserPreparing = /* @__PURE__ */ new Map();
35969
35373
  #nativeBrowserSessions = /* @__PURE__ */ new Map();
35970
35374
  #nativeBrowserStore = new MemoryAcpSessionStore();
35375
+ #nativeBrowserUseCounts = /* @__PURE__ */ new Map();
35971
35376
  #activeSessionIds = /* @__PURE__ */ new Set();
35972
35377
  #cancellationRequests = /* @__PURE__ */ new Map();
35973
35378
  #preparing = /* @__PURE__ */ new Map();
35379
+ #processCapacityChanged = Promise.withResolvers();
35380
+ #processCapacityLock = new AcpProcessCapacityLock();
35381
+ #retainedProcesses = /* @__PURE__ */ new Map();
35382
+ #retiringProcessCount = 0;
35383
+ #sessionUseCounts = /* @__PURE__ */ new Map();
35974
35384
  #sessions = /* @__PURE__ */ new Map();
35385
+ #startingProcessCount = 0;
35386
+ #transientProcessCount = 0;
35975
35387
  #store;
35976
35388
  #observer;
35977
35389
  constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore()) {
@@ -35981,18 +35393,230 @@ var AcpSessionManager = class {
35981
35393
  setObserver = (observer) => {
35982
35394
  this.#observer = observer;
35983
35395
  };
35396
+ #notifyProcessCapacityChanged() {
35397
+ const changed = this.#processCapacityChanged;
35398
+ this.#processCapacityChanged = Promise.withResolvers();
35399
+ changed.resolve();
35400
+ }
35401
+ #touchSession(sessionId) {
35402
+ const runtime = this.#sessions.get(sessionId);
35403
+ if (runtime === void 0) {
35404
+ return;
35405
+ }
35406
+ this.#touchProcess(runtime);
35407
+ }
35408
+ #touchExpectedSession(sessionId, expected) {
35409
+ if (this.#sessions.get(sessionId) !== expected) {
35410
+ return;
35411
+ }
35412
+ this.#touchProcess(expected);
35413
+ }
35414
+ #touchNativeBrowserSession(sessionId) {
35415
+ const runtime = this.#nativeBrowserSessions.get(sessionId);
35416
+ if (runtime === void 0) {
35417
+ return;
35418
+ }
35419
+ this.#touchProcess(runtime);
35420
+ }
35421
+ #touchExpectedNativeBrowserSession(sessionId, expected) {
35422
+ if (this.#nativeBrowserSessions.get(sessionId) !== expected) {
35423
+ return;
35424
+ }
35425
+ this.#touchProcess(expected);
35426
+ }
35427
+ #touchProcess(runtime) {
35428
+ const retained = this.#retainedProcesses.get(runtime);
35429
+ if (retained === void 0) {
35430
+ return;
35431
+ }
35432
+ this.#retainedProcesses.delete(runtime);
35433
+ this.#retainedProcesses.set(runtime, retained);
35434
+ }
35435
+ #beginSessionUse(sessionId) {
35436
+ this.#sessionUseCounts.set(sessionId, (this.#sessionUseCounts.get(sessionId) ?? 0) + 1);
35437
+ this.#touchSession(sessionId);
35438
+ }
35439
+ #endSessionUse(sessionId) {
35440
+ const count = this.#sessionUseCounts.get(sessionId) ?? 0;
35441
+ if (count <= 1) {
35442
+ this.#sessionUseCounts.delete(sessionId);
35443
+ } else {
35444
+ this.#sessionUseCounts.set(sessionId, count - 1);
35445
+ }
35446
+ this.#touchSession(sessionId);
35447
+ this.#notifyProcessCapacityChanged();
35448
+ }
35449
+ #beginNativeBrowserUse(sessionId) {
35450
+ this.#nativeBrowserUseCounts.set(sessionId, (this.#nativeBrowserUseCounts.get(sessionId) ?? 0) + 1);
35451
+ this.#touchNativeBrowserSession(sessionId);
35452
+ }
35453
+ #endNativeBrowserUse(sessionId) {
35454
+ const count = this.#nativeBrowserUseCounts.get(sessionId) ?? 0;
35455
+ if (count <= 1) {
35456
+ this.#nativeBrowserUseCounts.delete(sessionId);
35457
+ } else {
35458
+ this.#nativeBrowserUseCounts.set(sessionId, count - 1);
35459
+ }
35460
+ this.#touchNativeBrowserSession(sessionId);
35461
+ this.#notifyProcessCapacityChanged();
35462
+ }
35463
+ #isNativeSessionOperationActive(sessionId) {
35464
+ const stored = this.#store.read(sessionId);
35465
+ return stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`);
35466
+ }
35467
+ #leastRecentlyUsedEvictionCandidate() {
35468
+ for (const candidate of this.#retainedProcesses.values()) {
35469
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
35470
+ if (this.#activeSessionIds.has(candidate.sessionId) || this.#cancellationRequests.has(candidate.sessionId) || this.#preparing.has(candidate.sessionId) || (this.#sessionUseCounts.get(candidate.sessionId) ?? 0) > 0 || this.#isNativeSessionOperationActive(candidate.sessionId)) {
35471
+ continue;
35472
+ }
35473
+ return candidate;
35474
+ }
35475
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate && !this.#nativeBrowserPreparing.has(candidate.sessionId) && (this.#nativeBrowserUseCounts.get(candidate.sessionId) ?? 0) === 0) {
35476
+ return candidate;
35477
+ }
35478
+ }
35479
+ return new MissingAcpProcessEvictionCandidate();
35480
+ }
35481
+ #ownedProcessCount() {
35482
+ return this.#retainedProcesses.size + this.#startingProcessCount + this.#transientProcessCount + this.#retiringProcessCount;
35483
+ }
35484
+ async #retireProcess(runtime, retained, close) {
35485
+ if (retained) {
35486
+ this.#retainedProcesses.delete(runtime);
35487
+ this.#retiringProcessCount += 1;
35488
+ }
35489
+ try {
35490
+ await close();
35491
+ } finally {
35492
+ if (retained) {
35493
+ this.#retiringProcessCount -= 1;
35494
+ this.#notifyProcessCapacityChanged();
35495
+ }
35496
+ }
35497
+ }
35498
+ async #retireSessionProcess(sessionId, runtime, close) {
35499
+ const retained = this.#sessions.get(sessionId) === runtime;
35500
+ if (retained) {
35501
+ this.#sessions.delete(sessionId);
35502
+ }
35503
+ await this.#retireProcess(runtime, retained, close);
35504
+ }
35505
+ async #retireNativeBrowserProcess(sessionId, runtime, close) {
35506
+ const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
35507
+ if (retained) {
35508
+ this.#nativeBrowserSessions.delete(sessionId);
35509
+ this.#nativeBrowserStore.remove(sessionId);
35510
+ }
35511
+ await this.#retireProcess(runtime, retained, close);
35512
+ }
35513
+ async #reserveProcessCapacity(signal) {
35514
+ const lease = await this.#processCapacityLock.acquire(signal);
35515
+ try {
35516
+ for (; ; ) {
35517
+ signal.throwIfAborted();
35518
+ if (this.#ownedProcessCount() < MAX_ACP_PROCESSES) {
35519
+ this.#startingProcessCount += 1;
35520
+ return;
35521
+ }
35522
+ const candidate = this.#leastRecentlyUsedEvictionCandidate();
35523
+ if (candidate instanceof FoundAcpSessionProcessEvictionCandidate) {
35524
+ await this.#retireSessionProcess(
35525
+ candidate.sessionId,
35526
+ candidate.runtime,
35527
+ async () => await candidate.runtime.close()
35528
+ );
35529
+ continue;
35530
+ }
35531
+ if (candidate instanceof FoundAcpNativeBrowserProcessEvictionCandidate) {
35532
+ await this.#retireNativeBrowserProcess(
35533
+ candidate.sessionId,
35534
+ candidate.runtime,
35535
+ async () => await candidate.runtime.close()
35536
+ );
35537
+ continue;
35538
+ }
35539
+ const changed = this.#processCapacityChanged.promise;
35540
+ await waitForAcpProcessCapacity(changed, signal);
35541
+ }
35542
+ } finally {
35543
+ lease.release();
35544
+ }
35545
+ }
35546
+ async #startRetainedSessionProcess(options, start) {
35547
+ await this.#reserveProcessCapacity(options.signal);
35548
+ try {
35549
+ const runtime = await start();
35550
+ this.#startingProcessCount -= 1;
35551
+ this.#sessions.set(options.sessionId, runtime);
35552
+ this.#retainedProcesses.set(
35553
+ runtime,
35554
+ new FoundAcpSessionProcessEvictionCandidate(options.sessionId, runtime)
35555
+ );
35556
+ this.#notifyProcessCapacityChanged();
35557
+ return runtime;
35558
+ } catch (error62) {
35559
+ this.#startingProcessCount -= 1;
35560
+ this.#notifyProcessCapacityChanged();
35561
+ throw error62;
35562
+ }
35563
+ }
35564
+ async #startRetainedNativeBrowserProcess(options, start) {
35565
+ await this.#reserveProcessCapacity(options.signal);
35566
+ try {
35567
+ const runtime = await start();
35568
+ this.#startingProcessCount -= 1;
35569
+ this.#nativeBrowserSessions.set(options.sessionId, runtime);
35570
+ this.#retainedProcesses.set(
35571
+ runtime,
35572
+ new FoundAcpNativeBrowserProcessEvictionCandidate(options.sessionId, runtime)
35573
+ );
35574
+ this.#notifyProcessCapacityChanged();
35575
+ return runtime;
35576
+ } catch (error62) {
35577
+ this.#startingProcessCount -= 1;
35578
+ this.#notifyProcessCapacityChanged();
35579
+ throw error62;
35580
+ }
35581
+ }
35582
+ async #runWithTransientProcess(signal, start, operation, close) {
35583
+ await this.#reserveProcessCapacity(signal);
35584
+ let runtime;
35585
+ try {
35586
+ runtime = await start();
35587
+ } catch (error62) {
35588
+ this.#startingProcessCount -= 1;
35589
+ this.#notifyProcessCapacityChanged();
35590
+ throw error62;
35591
+ }
35592
+ this.#startingProcessCount -= 1;
35593
+ this.#transientProcessCount += 1;
35594
+ this.#notifyProcessCapacityChanged();
35595
+ try {
35596
+ return await operation(runtime);
35597
+ } finally {
35598
+ try {
35599
+ await close(runtime);
35600
+ } finally {
35601
+ this.#transientProcessCount -= 1;
35602
+ this.#notifyProcessCapacityChanged();
35603
+ }
35604
+ }
35605
+ }
35984
35606
  async #startNativeBrowserPreparation(options) {
35985
35607
  const operation = (async () => {
35986
35608
  try {
35987
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35609
+ return await this.#startRetainedNativeBrowserProcess(
35988
35610
  options,
35989
- () => this.#nativeBrowserObserver,
35990
- this.#nativeBrowserStore
35611
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35612
+ options,
35613
+ () => this.#nativeBrowserObserver,
35614
+ this.#nativeBrowserStore
35615
+ )
35991
35616
  );
35992
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
35993
- return runtime;
35994
35617
  } finally {
35995
35618
  this.#nativeBrowserPreparing.delete(options.sessionId);
35619
+ this.#notifyProcessCapacityChanged();
35996
35620
  }
35997
35621
  })();
35998
35622
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -36001,18 +35625,18 @@ var AcpSessionManager = class {
36001
35625
  async #replaceNativeBrowserPreparation(existing, options) {
36002
35626
  const operation = (async () => {
36003
35627
  try {
36004
- this.#nativeBrowserSessions.delete(options.sessionId);
36005
- await existing.close();
36006
- this.#nativeBrowserStore.remove(options.sessionId);
36007
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
35628
+ await this.#retireNativeBrowserProcess(options.sessionId, existing, async () => await existing.close());
35629
+ return await this.#startRetainedNativeBrowserProcess(
36008
35630
  options,
36009
- () => this.#nativeBrowserObserver,
36010
- this.#nativeBrowserStore
35631
+ async () => await AcpProcessSession.startNativeSessionBrowser(
35632
+ options,
35633
+ () => this.#nativeBrowserObserver,
35634
+ this.#nativeBrowserStore
35635
+ )
36011
35636
  );
36012
- this.#nativeBrowserSessions.set(options.sessionId, runtime);
36013
- return runtime;
36014
35637
  } finally {
36015
35638
  this.#nativeBrowserPreparing.delete(options.sessionId);
35639
+ this.#notifyProcessCapacityChanged();
36016
35640
  }
36017
35641
  })();
36018
35642
  this.#nativeBrowserPreparing.set(options.sessionId, operation);
@@ -36021,11 +35645,13 @@ var AcpSessionManager = class {
36021
35645
  async #startPreparation(options, metrics = unmeasuredOperationMetrics) {
36022
35646
  const operation = (async () => {
36023
35647
  try {
36024
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
36025
- this.#sessions.set(options.sessionId, runtime);
36026
- return runtime;
35648
+ return await this.#startRetainedSessionProcess(
35649
+ options,
35650
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35651
+ );
36027
35652
  } finally {
36028
35653
  this.#preparing.delete(options.sessionId);
35654
+ this.#notifyProcessCapacityChanged();
36029
35655
  }
36030
35656
  })();
36031
35657
  this.#preparing.set(options.sessionId, operation);
@@ -36034,17 +35660,19 @@ var AcpSessionManager = class {
36034
35660
  async #startSessionForkAtTurnPreparation(options, sourceNativeSessionId, forkPoint) {
36035
35661
  const operation = (async () => {
36036
35662
  try {
36037
- const runtime = await AcpProcessSession.startSessionForkAtTurn(
35663
+ return await this.#startRetainedSessionProcess(
36038
35664
  options,
36039
- sourceNativeSessionId,
36040
- forkPoint,
36041
- () => this.#observer,
36042
- this.#store
35665
+ async () => await AcpProcessSession.startSessionForkAtTurn(
35666
+ options,
35667
+ sourceNativeSessionId,
35668
+ forkPoint,
35669
+ () => this.#observer,
35670
+ this.#store
35671
+ )
36043
35672
  );
36044
- this.#sessions.set(options.sessionId, runtime);
36045
- return runtime;
36046
35673
  } finally {
36047
35674
  this.#preparing.delete(options.sessionId);
35675
+ this.#notifyProcessCapacityChanged();
36048
35676
  }
36049
35677
  })();
36050
35678
  this.#preparing.set(options.sessionId, operation);
@@ -36053,14 +35681,19 @@ var AcpSessionManager = class {
36053
35681
  async #replacePreparation(existing, options, metrics) {
36054
35682
  const operation = (async () => {
36055
35683
  try {
36056
- this.#sessions.delete(options.sessionId);
36057
- await metrics.measure("runtime-replacement-close", async () => await existing.close());
35684
+ await this.#retireSessionProcess(
35685
+ options.sessionId,
35686
+ existing,
35687
+ async () => await metrics.measure("runtime-replacement-close", async () => await existing.close())
35688
+ );
36058
35689
  this.#store.remove(options.sessionId);
36059
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics);
36060
- this.#sessions.set(options.sessionId, runtime);
36061
- return runtime;
35690
+ return await this.#startRetainedSessionProcess(
35691
+ options,
35692
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
35693
+ );
36062
35694
  } finally {
36063
35695
  this.#preparing.delete(options.sessionId);
35696
+ this.#notifyProcessCapacityChanged();
36064
35697
  }
36065
35698
  })();
36066
35699
  this.#preparing.set(options.sessionId, operation);
@@ -36070,10 +35703,12 @@ var AcpSessionManager = class {
36070
35703
  const desiredConfigOptions = existing.prepared().configOptions;
36071
35704
  const operation = (async () => {
36072
35705
  try {
36073
- this.#sessions.delete(options.sessionId);
36074
- await existing.close();
35706
+ await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
36075
35707
  this.#store.remove(options.sessionId);
36076
- const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
35708
+ const runtime = await this.#startRetainedSessionProcess(
35709
+ options,
35710
+ async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
35711
+ );
36077
35712
  try {
36078
35713
  for (const desired of desiredConfigOptions) {
36079
35714
  const current = runtime.prepared().configOptions.find((option2) => option2.id === desired.id);
@@ -36105,14 +35740,14 @@ var AcpSessionManager = class {
36105
35740
  }
36106
35741
  }
36107
35742
  } catch (error62) {
36108
- await runtime.close();
35743
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
36109
35744
  this.#store.remove(options.sessionId);
36110
35745
  throw error62;
36111
35746
  }
36112
- this.#sessions.set(options.sessionId, runtime);
36113
35747
  return runtime;
36114
35748
  } finally {
36115
35749
  this.#preparing.delete(options.sessionId);
35750
+ this.#notifyProcessCapacityChanged();
36116
35751
  }
36117
35752
  })();
36118
35753
  this.#preparing.set(options.sessionId, operation);
@@ -36134,6 +35769,7 @@ var AcpSessionManager = class {
36134
35769
  if (pending !== void 0) {
36135
35770
  const runtime2 = await metrics.measure("session-preparation-wait", async () => await pending);
36136
35771
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35772
+ this.#touchExpectedSession(options.sessionId, runtime2);
36137
35773
  return runtime2.prepared();
36138
35774
  }
36139
35775
  return await this.prepareSession(options, metrics);
@@ -36141,6 +35777,7 @@ var AcpSessionManager = class {
36141
35777
  const existing = this.#sessions.get(options.sessionId);
36142
35778
  if (existing !== void 0) {
36143
35779
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35780
+ this.#touchExpectedSession(options.sessionId, existing);
36144
35781
  return existing.prepared();
36145
35782
  }
36146
35783
  if (!existing.canRebind()) {
@@ -36161,22 +35798,24 @@ var AcpSessionManager = class {
36161
35798
  * authoritative settings. Its identity and store are private to this
36162
35799
  * operation and never become a Mobius Session.
36163
35800
  */
36164
- inspectAgentSettings = async (options) => {
36165
- const runtime = await AcpProcessSession.start(
35801
+ inspectAgentSettings = async (options) => await this.#runWithTransientProcess(
35802
+ options.signal,
35803
+ async () => await AcpProcessSession.start(
36166
35804
  {
36167
35805
  ...options,
36168
35806
  sessionId: `agent-settings-${crypto.randomUUID()}`
36169
35807
  },
36170
35808
  () => this.#agentSettingsObserver,
36171
35809
  new MemoryAcpSessionStore()
36172
- );
36173
- try {
35810
+ ),
35811
+ (runtime) => {
36174
35812
  const prepared = runtime.prepared();
36175
- return new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions);
36176
- } finally {
36177
- await runtime.close();
36178
- }
36179
- };
35813
+ return Promise.resolve(
35814
+ new AcpAgentSettingsSnapshot(prepared.agentName, prepared.agentVersion, prepared.configOptions)
35815
+ );
35816
+ },
35817
+ async (runtime) => await runtime.close()
35818
+ );
36180
35819
  /**
36181
35820
  * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
36182
35821
  * Use inspectAgentSettings for Agent-scoped settings discovery.
@@ -36185,18 +35824,20 @@ var AcpSessionManager = class {
36185
35824
  if (this.#preparing.has(options.sessionId) || this.#sessions.has(options.sessionId)) {
36186
35825
  throw new AcpExecutionError("The configuration inspection session is already in use", {}, "session_busy");
36187
35826
  }
36188
- const runtime = await this.#startPreparation(options, metrics);
35827
+ this.#beginSessionUse(options.sessionId);
36189
35828
  try {
36190
- return runtime.prepared();
36191
- } finally {
36192
- if (this.#sessions.get(options.sessionId) === runtime) {
36193
- this.#sessions.delete(options.sessionId);
36194
- }
35829
+ const runtime = await this.#startPreparation(options, metrics);
36195
35830
  try {
36196
- await runtime.close();
35831
+ return runtime.prepared();
36197
35832
  } finally {
36198
- this.#store.remove(options.sessionId);
35833
+ try {
35834
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
35835
+ } finally {
35836
+ this.#store.remove(options.sessionId);
35837
+ }
36199
35838
  }
35839
+ } finally {
35840
+ this.#endSessionUse(options.sessionId);
36200
35841
  }
36201
35842
  };
36202
35843
  prepareExecutionSession = async (options) => {
@@ -36217,6 +35858,7 @@ var AcpSessionManager = class {
36217
35858
  );
36218
35859
  }
36219
35860
  if (existing.usesEnvironment(options.agent.environment)) {
35861
+ this.#touchExpectedSession(options.sessionId, existing);
36220
35862
  return existing.prepared();
36221
35863
  }
36222
35864
  if (!existing.canRebind()) {
@@ -36233,6 +35875,7 @@ var AcpSessionManager = class {
36233
35875
  if (pending !== void 0) {
36234
35876
  const runtime2 = await pending;
36235
35877
  if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35878
+ this.#touchExpectedNativeBrowserSession(options.sessionId, runtime2);
36236
35879
  return runtime2.prepared();
36237
35880
  }
36238
35881
  return await this.prepareNativeSessionBrowser(options);
@@ -36240,6 +35883,7 @@ var AcpSessionManager = class {
36240
35883
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
36241
35884
  if (existing !== void 0) {
36242
35885
  if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
35886
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
36243
35887
  return existing.prepared();
36244
35888
  }
36245
35889
  if (!existing.canRebind()) {
@@ -36256,8 +35900,13 @@ var AcpSessionManager = class {
36256
35900
  return runtime.prepared();
36257
35901
  };
36258
35902
  configureSession = async (options) => {
36259
- const runtime = await this.ensureSession(options);
36260
- return await runtime.configure(options);
35903
+ this.#beginSessionUse(options.sessionId);
35904
+ try {
35905
+ const runtime = await this.ensureSession(options);
35906
+ return await runtime.configure(options);
35907
+ } finally {
35908
+ this.#endSessionUse(options.sessionId);
35909
+ }
36261
35910
  };
36262
35911
  cancelPrompt = async (sessionId) => {
36263
35912
  const existing = this.#cancellationRequests.get(sessionId);
@@ -36273,6 +35922,8 @@ var AcpSessionManager = class {
36273
35922
  } finally {
36274
35923
  if (this.#sessions.get(sessionId) === runtime) {
36275
35924
  this.#sessions.delete(sessionId);
35925
+ this.#retainedProcesses.delete(runtime);
35926
+ this.#notifyProcessCapacityChanged();
36276
35927
  }
36277
35928
  }
36278
35929
  }
@@ -36362,10 +36013,7 @@ var AcpSessionManager = class {
36362
36013
  return this.#cancellationRequests.has(options.sessionId) ? { stopReason: "cancelled" } : result;
36363
36014
  } catch (error62) {
36364
36015
  if (this.#cancellationRequests.has(options.sessionId)) {
36365
- if (this.#sessions.get(options.sessionId) === runtime) {
36366
- this.#sessions.delete(options.sessionId);
36367
- }
36368
- await runtime.closeProcess();
36016
+ await this.#cancellationRequests.get(options.sessionId);
36369
36017
  return { stopReason: "cancelled" };
36370
36018
  }
36371
36019
  throw error62;
@@ -36373,8 +36021,11 @@ var AcpSessionManager = class {
36373
36021
  } catch (error62) {
36374
36022
  const failedRuntime = this.#sessions.get(options.sessionId);
36375
36023
  if (failedRuntime !== void 0) {
36376
- this.#sessions.delete(options.sessionId);
36377
- await failedRuntime.close();
36024
+ await this.#retireSessionProcess(
36025
+ options.sessionId,
36026
+ failedRuntime,
36027
+ async () => await failedRuntime.close()
36028
+ );
36378
36029
  }
36379
36030
  if (this.#cancellationRequests.has(options.sessionId)) {
36380
36031
  return { stopReason: "cancelled" };
@@ -36395,6 +36046,8 @@ var AcpSessionManager = class {
36395
36046
  this.#activeCommandIds.delete(options.sessionId);
36396
36047
  }
36397
36048
  this.#cancellationRequests.delete(options.sessionId);
36049
+ this.#touchSession(options.sessionId);
36050
+ this.#notifyProcessCapacityChanged();
36398
36051
  }
36399
36052
  }
36400
36053
  };
@@ -36413,11 +36066,16 @@ var AcpSessionManager = class {
36413
36066
  await runtime.respondElicitation(options);
36414
36067
  };
36415
36068
  close = async () => {
36416
- const sessions = [...this.#sessions.values()];
36417
- const nativeBrowserSessions = [...this.#nativeBrowserSessions.values()];
36418
- this.#sessions.clear();
36419
- this.#nativeBrowserSessions.clear();
36420
- await Promise.all([...sessions, ...nativeBrowserSessions].map(async (session) => await session.close()));
36069
+ const sessions = [...this.#sessions.entries()];
36070
+ const nativeBrowserSessions = [...this.#nativeBrowserSessions.entries()];
36071
+ await Promise.all([
36072
+ ...sessions.map(
36073
+ async ([sessionId, runtime]) => await this.#retireSessionProcess(sessionId, runtime, async () => await runtime.close())
36074
+ ),
36075
+ ...nativeBrowserSessions.map(
36076
+ async ([sessionId, runtime]) => await this.#retireNativeBrowserProcess(sessionId, runtime, async () => await runtime.close())
36077
+ )
36078
+ ]);
36421
36079
  };
36422
36080
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
36423
36081
  ensureSession = async (options) => {
@@ -36430,6 +36088,7 @@ var AcpSessionManager = class {
36430
36088
  "session_identity_mismatch"
36431
36089
  );
36432
36090
  }
36091
+ this.#touchExpectedSession(options.sessionId, existing);
36433
36092
  return existing;
36434
36093
  }
36435
36094
  await this.prepareSession(options);
@@ -36449,6 +36108,7 @@ var AcpSessionManager = class {
36449
36108
  "session_identity_mismatch"
36450
36109
  );
36451
36110
  }
36111
+ this.#touchExpectedNativeBrowserSession(options.sessionId, existing);
36452
36112
  return existing;
36453
36113
  }
36454
36114
  await this.prepareNativeSessionBrowser(options);
@@ -36458,7 +36118,14 @@ var AcpSessionManager = class {
36458
36118
  }
36459
36119
  return started;
36460
36120
  }
36461
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
36121
+ listNativeSessions = async (options, cursor) => {
36122
+ this.#beginNativeBrowserUse(options.sessionId);
36123
+ try {
36124
+ return await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
36125
+ } finally {
36126
+ this.#endNativeBrowserUse(options.sessionId);
36127
+ }
36128
+ };
36462
36129
  previewNativeSession = async (options, nativeSessionId) => {
36463
36130
  const key = `${options.agent.id}:${nativeSessionId}`;
36464
36131
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
@@ -36471,17 +36138,19 @@ var AcpSessionManager = class {
36471
36138
  }
36472
36139
  this.#nativeOperations.add(key);
36473
36140
  try {
36474
- const runtime = await AcpProcessSession.startNativeSessionBrowser(
36475
- options,
36476
- () => this.#nativeBrowserObserver,
36477
- new MemoryAcpSessionStore()
36141
+ return await this.#runWithTransientProcess(
36142
+ options.signal,
36143
+ async () => await AcpProcessSession.startNativeSessionBrowser(
36144
+ options,
36145
+ () => this.#nativeBrowserObserver,
36146
+ new MemoryAcpSessionStore()
36147
+ ),
36148
+ async (runtime) => {
36149
+ runtime.selectNativeSession(nativeSessionId);
36150
+ return await runtime.loadHistory(options.signal);
36151
+ },
36152
+ async (runtime) => await runtime.closeProcess()
36478
36153
  );
36479
- try {
36480
- runtime.selectNativeSession(nativeSessionId);
36481
- return await runtime.loadHistory(options.signal);
36482
- } finally {
36483
- await runtime.closeProcess();
36484
- }
36485
36154
  } finally {
36486
36155
  this.#nativeOperations.delete(key);
36487
36156
  }
@@ -36501,36 +36170,46 @@ var AcpSessionManager = class {
36501
36170
  }
36502
36171
  const existing = linked[0];
36503
36172
  if (origin.kind === "import" && existing !== void 0) {
36504
- const runtime = await this.ensureSession({
36505
- ...options,
36506
- sessionId: existing.sessionId
36507
- });
36508
- if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
36509
- throw new AcpExecutionError(
36510
- "Wait for the native session's running operation to finish",
36511
- {},
36512
- "session_busy"
36513
- );
36514
- }
36515
- this.#nativeOperations.add(key);
36173
+ this.#beginSessionUse(existing.sessionId);
36516
36174
  try {
36517
- const history = await runtime.loadHistory(options.signal);
36518
- return {
36519
- prepared: runtime.prepared(),
36520
- sessionId: existing.sessionId,
36521
- history
36522
- };
36523
- } catch (error62) {
36524
- this.#sessions.delete(existing.sessionId);
36525
- await runtime.closeProcess();
36526
- throw error62;
36175
+ const runtime = await this.ensureSession({
36176
+ ...options,
36177
+ sessionId: existing.sessionId
36178
+ });
36179
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
36180
+ throw new AcpExecutionError(
36181
+ "Wait for the native session's running operation to finish",
36182
+ {},
36183
+ "session_busy"
36184
+ );
36185
+ }
36186
+ this.#nativeOperations.add(key);
36187
+ try {
36188
+ const history = await runtime.loadHistory(options.signal);
36189
+ return {
36190
+ prepared: runtime.prepared(),
36191
+ sessionId: existing.sessionId,
36192
+ history
36193
+ };
36194
+ } catch (error62) {
36195
+ await this.#retireSessionProcess(
36196
+ existing.sessionId,
36197
+ runtime,
36198
+ async () => await runtime.closeProcess()
36199
+ );
36200
+ throw error62;
36201
+ } finally {
36202
+ this.#nativeOperations.delete(key);
36203
+ this.#notifyProcessCapacityChanged();
36204
+ }
36527
36205
  } finally {
36528
- this.#nativeOperations.delete(key);
36206
+ this.#endSessionUse(existing.sessionId);
36529
36207
  }
36530
36208
  }
36531
36209
  if (this.#sessions.has(options.sessionId) || this.#preparing.has(options.sessionId) || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
36532
36210
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
36533
36211
  }
36212
+ this.#beginSessionUse(options.sessionId);
36534
36213
  this.#nativeOperations.add(key);
36535
36214
  try {
36536
36215
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -36544,23 +36223,23 @@ var AcpSessionManager = class {
36544
36223
  history
36545
36224
  };
36546
36225
  } catch (error62) {
36547
- this.#sessions.delete(options.sessionId);
36548
36226
  this.#store.remove(options.sessionId);
36549
- await runtime.closeProcess();
36227
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
36550
36228
  throw error62;
36551
36229
  } finally {
36552
36230
  this.#nativeOperations.delete(openedKey);
36231
+ this.#notifyProcessCapacityChanged();
36553
36232
  }
36554
36233
  } catch (error62) {
36555
36234
  this.#store.remove(options.sessionId);
36556
36235
  const runtime = this.#sessions.get(options.sessionId);
36557
- this.#sessions.delete(options.sessionId);
36558
36236
  if (runtime !== void 0) {
36559
- await runtime.closeProcess();
36237
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
36560
36238
  }
36561
36239
  throw error62;
36562
36240
  } finally {
36563
36241
  this.#nativeOperations.delete(key);
36242
+ this.#endSessionUse(options.sessionId);
36564
36243
  }
36565
36244
  };
36566
36245
  forkSessionAtTurn = async (options, sourceSessionId, forkPoint) => {
@@ -36598,6 +36277,7 @@ var AcpSessionManager = class {
36598
36277
  if (this.#sessions.has(options.sessionId) || this.#preparing.has(options.sessionId) || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
36599
36278
  throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
36600
36279
  }
36280
+ this.#beginSessionUse(options.sessionId);
36601
36281
  this.#nativeOperations.add(key);
36602
36282
  try {
36603
36283
  const runtime = await this.#startSessionForkAtTurnPreparation(
@@ -36614,48 +36294,58 @@ var AcpSessionManager = class {
36614
36294
  sessionId: options.sessionId
36615
36295
  };
36616
36296
  } catch (error62) {
36617
- this.#sessions.delete(options.sessionId);
36618
36297
  this.#store.remove(options.sessionId);
36619
- await runtime.closeProcess();
36298
+ await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.closeProcess());
36620
36299
  throw error62;
36621
36300
  } finally {
36622
36301
  this.#nativeOperations.delete(openedKey);
36302
+ this.#notifyProcessCapacityChanged();
36623
36303
  }
36624
36304
  } finally {
36625
36305
  this.#nativeOperations.delete(key);
36306
+ this.#endSessionUse(options.sessionId);
36626
36307
  }
36627
36308
  };
36628
36309
  deleteNativeSession = async (options, nativeSessionId) => {
36629
- const runtime = await this.#ensureNativeSessionBrowser(options);
36630
- const key = `${options.agent.id}:${nativeSessionId}`;
36631
- const linked = this.#store.findNative(options.agent.id, nativeSessionId);
36632
- if (this.#nativeOperations.has(key) || linked.some((entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
36633
- throw new AcpExecutionError(
36634
- "Wait for the native session's running operation to finish",
36635
- {},
36636
- "session_busy"
36637
- );
36638
- }
36639
- this.#nativeOperations.add(key);
36310
+ this.#beginNativeBrowserUse(options.sessionId);
36640
36311
  try {
36641
- for (const entry of linked) {
36642
- const active = this.#sessions.get(entry.sessionId);
36643
- if (active !== void 0 && active !== runtime) {
36644
- this.#sessions.delete(entry.sessionId);
36645
- await active.close();
36312
+ const runtime = await this.#ensureNativeSessionBrowser(options);
36313
+ const key = `${options.agent.id}:${nativeSessionId}`;
36314
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
36315
+ if (this.#nativeOperations.has(key) || linked.some(
36316
+ (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
36317
+ )) {
36318
+ throw new AcpExecutionError(
36319
+ "Wait for the native session's running operation to finish",
36320
+ {},
36321
+ "session_busy"
36322
+ );
36323
+ }
36324
+ this.#nativeOperations.add(key);
36325
+ try {
36326
+ for (const entry of linked) {
36327
+ const active = this.#sessions.get(entry.sessionId);
36328
+ if (active !== void 0 && active !== runtime) {
36329
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
36330
+ }
36331
+ }
36332
+ options.signal.throwIfAborted();
36333
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
36334
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
36335
+ if (runtime.nativeSessionId() === nativeSessionId) {
36336
+ await this.#retireNativeBrowserProcess(
36337
+ options.sessionId,
36338
+ runtime,
36339
+ async () => await runtime.close()
36340
+ );
36646
36341
  }
36342
+ return deleted;
36343
+ } finally {
36344
+ this.#nativeOperations.delete(key);
36345
+ this.#notifyProcessCapacityChanged();
36647
36346
  }
36648
- options.signal.throwIfAborted();
36649
- await runtime.deleteNativeSession(nativeSessionId, options.signal);
36650
- const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
36651
- if (runtime.nativeSessionId() === nativeSessionId) {
36652
- this.#nativeBrowserSessions.delete(options.sessionId);
36653
- this.#nativeBrowserStore.remove(options.sessionId);
36654
- await runtime.close();
36655
- }
36656
- return deleted;
36657
36347
  } finally {
36658
- this.#nativeOperations.delete(key);
36348
+ this.#endNativeBrowserUse(options.sessionId);
36659
36349
  }
36660
36350
  };
36661
36351
  };
@@ -37112,14 +36802,14 @@ var FixedInstallationExecutor = class {
37112
36802
  if (initialDiscovery instanceof MissingAgent) {
37113
36803
  throw new InstallationManagerError(
37114
36804
  "agent_not_installed",
37115
- `Install ${specification.label} on this machine, then try installing the integration again.`
36805
+ `Install ${specification.label} on this machine, then check local Agents again.`
37116
36806
  );
37117
36807
  }
37118
36808
  const verifiedAgent = await findVerifiedAgentExecutable(specification, discoveryOptions);
37119
36809
  if (verifiedAgent === null) {
37120
36810
  throw new InstallationManagerError(
37121
36811
  "agent_not_installed",
37122
- `Install ${specification.label} on this machine, then try installing the integration again.`
36812
+ `Install ${specification.label} on this machine, then check local Agents again.`
37123
36813
  );
37124
36814
  }
37125
36815
  const agent = verifiedAgent.executable;
@@ -37200,7 +36890,7 @@ var FixedInstallationExecutor = class {
37200
36890
  };
37201
36891
 
37202
36892
  // src/artifacts/runtime-artifact-uploader.ts
37203
- import { createHash as createHash3 } from "node:crypto";
36893
+ import { createHash as createHash2 } from "node:crypto";
37204
36894
 
37205
36895
  // ../mobius-sdk/src/errors.ts
37206
36896
  var MobiusError = class extends Error {
@@ -37447,153 +37137,751 @@ function daemonToken(config2) {
37447
37137
  if (token === null || token.length < 32) {
37448
37138
  throw new RuntimeArtifactUploadError("artifact_endpoint_invalid", "The Relay daemon token is missing");
37449
37139
  }
37450
- return token;
37140
+ return token;
37141
+ }
37142
+ function channelOrigin(config2) {
37143
+ const url2 = new URL(config2.relayUrl);
37144
+ url2.protocol = url2.protocol === "wss:" ? "https:" : "http:";
37145
+ let channelPath = "";
37146
+ if (url2.pathname.endsWith("/daemon")) {
37147
+ channelPath = url2.pathname.slice(0, -"/daemon".length);
37148
+ } else {
37149
+ const runtimePath = `${MOBIUS_API_PREFIX}/v1/runtimes/connect`;
37150
+ if (!url2.pathname.endsWith("/v1/runtimes/connect") && !url2.pathname.endsWith(runtimePath)) {
37151
+ throw new RuntimeArtifactUploadError("artifact_endpoint_invalid", "The Relay artifact endpoint is invalid");
37152
+ }
37153
+ channelPath = `${url2.pathname.replace(/\/v1\/runtimes\/connect$/, "")}/channels/${encodeURIComponent(config2.channelId)}`;
37154
+ }
37155
+ url2.pathname = channelPath;
37156
+ url2.search = "";
37157
+ url2.hash = "";
37158
+ return url2;
37159
+ }
37160
+ function uploadError(code, message, cause) {
37161
+ return new RuntimeArtifactUploadError(code, message, cause === void 0 ? {} : { cause });
37162
+ }
37163
+ function translateSdkError(cause) {
37164
+ if (cause instanceof MobiusValidationError) {
37165
+ throw uploadError("artifact_upload_failed", cause.message, cause);
37166
+ }
37167
+ if (cause instanceof MobiusProtocolError) {
37168
+ throw uploadError("artifact_upload_failed", "The Relay returned an invalid upload response", cause);
37169
+ }
37170
+ throw cause;
37171
+ }
37172
+ async function readJson(response) {
37173
+ try {
37174
+ return await response.json();
37175
+ } catch (cause) {
37176
+ throw uploadError("artifact_upload_failed", "The Relay returned an invalid upload response", cause);
37177
+ }
37178
+ }
37179
+ async function readAuthorization(response) {
37180
+ try {
37181
+ return decodeMobiusArtifactUpload(await readJson(response));
37182
+ } catch (cause) {
37183
+ translateSdkError(cause);
37184
+ }
37185
+ }
37186
+ function sessionArtifactUrl(origin, sessionId, resourcePath, token) {
37187
+ const url2 = new URL(`${origin.pathname}/sessions/${encodeURIComponent(sessionId)}/${resourcePath}`, origin);
37188
+ url2.searchParams.set("token", token);
37189
+ return url2;
37190
+ }
37191
+ async function postLease(url2, request, signal) {
37192
+ return await fetch4(url2, {
37193
+ dispatcher: environmentProxyDispatcher,
37194
+ headers: { "content-type": "application/json" },
37195
+ method: "POST",
37196
+ body: JSON.stringify(request),
37197
+ signal
37198
+ });
37199
+ }
37200
+ async function putContent(url2, authorization, bytes, signal) {
37201
+ return await fetch4(url2, {
37202
+ dispatcher: environmentProxyDispatcher,
37203
+ headers: {
37204
+ "content-type": authorization.mediaType,
37205
+ "x-mobius-upload-token": authorization.uploadToken
37206
+ },
37207
+ method: "PUT",
37208
+ body: bytes,
37209
+ signal
37210
+ });
37211
+ }
37212
+ async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
37213
+ signal.throwIfAborted();
37214
+ let request;
37215
+ try {
37216
+ request = new MobiusArtifactUploadRequest(
37217
+ image.name,
37218
+ image.mimeType,
37219
+ image.bytes.byteLength,
37220
+ createHash2("sha256").update(image.bytes).digest("hex")
37221
+ );
37222
+ } catch (cause) {
37223
+ translateSdkError(cause);
37224
+ }
37225
+ const timeoutSignal = AbortSignal.timeout(UPLOAD_TIMEOUT_MILLISECONDS);
37226
+ const requestSignal = AbortSignal.any([signal, timeoutSignal]);
37227
+ const origin = channelOrigin(config2);
37228
+ const token = daemonToken(config2);
37229
+ let created;
37230
+ try {
37231
+ created = await postLease(
37232
+ sessionArtifactUrl(origin, sessionId, "artifacts/uploads", token),
37233
+ request,
37234
+ requestSignal
37235
+ );
37236
+ } catch (cause) {
37237
+ signal.throwIfAborted();
37238
+ throw uploadError(
37239
+ timeoutSignal.aborted ? "artifact_upload_timeout" : "artifact_upload_failed",
37240
+ timeoutSignal.aborted ? "The artifact upload authorization timed out" : "The artifact upload could not start",
37241
+ cause
37242
+ );
37243
+ }
37244
+ if (!created.ok) {
37245
+ await created.body?.cancel();
37246
+ throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact upload");
37247
+ }
37248
+ const authorization = await readAuthorization(created);
37249
+ let uploaded;
37250
+ try {
37251
+ uploaded = await putContent(
37252
+ sessionArtifactUrl(
37253
+ origin,
37254
+ sessionId,
37255
+ `artifacts/${encodeURIComponent(authorization.artifactId)}/content`,
37256
+ token
37257
+ ),
37258
+ authorization,
37259
+ image.bytes,
37260
+ requestSignal
37261
+ );
37262
+ } catch (cause) {
37263
+ signal.throwIfAborted();
37264
+ throw uploadError(
37265
+ timeoutSignal.aborted ? "artifact_upload_timeout" : "artifact_upload_failed",
37266
+ timeoutSignal.aborted ? "The artifact upload timed out" : "The artifact content could not be uploaded",
37267
+ cause
37268
+ );
37269
+ }
37270
+ if (!uploaded.ok) {
37271
+ await uploaded.body?.cancel();
37272
+ throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact content");
37273
+ }
37274
+ try {
37275
+ const available = decodeMobiusAvailableArtifact(await readJson(uploaded));
37276
+ return new UploadedRuntimeArtifact(
37277
+ available.artifactId,
37278
+ available.name,
37279
+ available.mediaType,
37280
+ available.byteLength,
37281
+ available.sha256
37282
+ );
37283
+ } catch (cause) {
37284
+ translateSdkError(cause);
37285
+ }
37286
+ }
37287
+
37288
+ // src/authorization/local-authorization-error.ts
37289
+ var LocalAuthorizationError = class extends Error {
37290
+ code = "local_authorization_failed";
37291
+ constructor(message, options = {}) {
37292
+ super(message, options);
37293
+ this.name = "LocalAuthorizationError";
37294
+ }
37295
+ };
37296
+
37297
+ // src/authorization/workspace-directory.ts
37298
+ import { readdir as readdir2, realpath as realpath8, stat as stat7 } from "node:fs/promises";
37299
+ import { homedir as homedir2 } from "node:os";
37300
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute9, join as join16, normalize as normalize3, relative as relative5 } from "node:path";
37301
+ var WorkspaceDirectoryListing = class {
37302
+ directoryId;
37303
+ directoryLabel;
37304
+ entries;
37305
+ parentDirectoryId;
37306
+ constructor(directoryId2, directoryLabel, entries, parentDirectoryId) {
37307
+ this.directoryId = directoryId2;
37308
+ this.directoryLabel = directoryLabel;
37309
+ this.entries = entries;
37310
+ this.parentDirectoryId = parentDirectoryId;
37311
+ }
37312
+ };
37313
+ function encodePath(path2) {
37314
+ const encoded = Buffer.from(path2, "utf8").toString("base64url");
37315
+ if (encoded.length === 0 || encoded.length > 2e3) {
37316
+ throw new LocalAuthorizationError("The local directory path is too long to select");
37317
+ }
37318
+ return `path-${encoded}`;
37319
+ }
37320
+ function decodePath(value, prefix) {
37321
+ const encoded = value.slice(prefix.length);
37322
+ if (encoded.length === 0 || encoded.length > 2e3 || !/^[a-zA-Z0-9_-]+$/.test(encoded)) {
37323
+ throw new LocalAuthorizationError("The directory identifier is invalid");
37324
+ }
37325
+ const decoded = Buffer.from(encoded, "base64url").toString("utf8");
37326
+ if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize3(decoded) !== decoded) {
37327
+ throw new LocalAuthorizationError("The directory identifier is invalid");
37328
+ }
37329
+ return decoded;
37330
+ }
37331
+ var WorkspaceDirectoryService = class {
37332
+ #bindingId;
37333
+ #defaultWorkspace;
37334
+ constructor(bindingId, defaultWorkspace) {
37335
+ this.#bindingId = bindingId;
37336
+ this.#defaultWorkspace = defaultWorkspace;
37337
+ }
37338
+ authorizeMachine = (bindingId) => {
37339
+ if (bindingId !== this.#bindingId) {
37340
+ throw new LocalAuthorizationError("The runtime binding is not authorized");
37341
+ }
37342
+ };
37343
+ requestedPath = (id) => {
37344
+ if (id === "default") {
37345
+ return this.#defaultWorkspace;
37346
+ }
37347
+ if (id === "home") {
37348
+ return homedir2();
37349
+ }
37350
+ if (id.startsWith("path-")) {
37351
+ const path2 = decodePath(id, "path-");
37352
+ if (isAbsolute9(path2)) {
37353
+ return path2;
37354
+ }
37355
+ }
37356
+ throw new LocalAuthorizationError("The directory identifier is invalid");
37357
+ };
37358
+ resolvePath = async (requested, signal) => {
37359
+ signal.throwIfAborted();
37360
+ if (!isAbsolute9(requested) || requested.includes("\0") || normalize3(requested) !== requested) {
37361
+ throw new LocalAuthorizationError("The local directory path is invalid");
37362
+ }
37363
+ try {
37364
+ const target = await realpath8(requested);
37365
+ signal.throwIfAborted();
37366
+ const metadata = await stat7(target);
37367
+ signal.throwIfAborted();
37368
+ if (!isAbsolute9(target) || normalize3(target) !== target || !metadata.isDirectory()) {
37369
+ throw new LocalAuthorizationError("The selected location is not a directory");
37370
+ }
37371
+ return target;
37372
+ } catch (cause) {
37373
+ signal.throwIfAborted();
37374
+ if (cause instanceof LocalAuthorizationError) {
37375
+ throw cause;
37376
+ }
37377
+ throw new LocalAuthorizationError("This directory is missing or unavailable to your user account", {
37378
+ cause
37379
+ });
37380
+ }
37381
+ };
37382
+ label = (path2) => {
37383
+ const suffix = relative5(homedir2(), path2);
37384
+ return suffix === "" ? "~" : !isAbsolute9(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path2;
37385
+ };
37386
+ identify = async (bindingId, requestedPath, signal) => {
37387
+ this.authorizeMachine(bindingId);
37388
+ const path2 = await this.resolvePath(requestedPath, signal);
37389
+ return {
37390
+ path: path2,
37391
+ directoryId: encodePath(path2),
37392
+ name: basename3(path2) || path2,
37393
+ label: this.label(path2)
37394
+ };
37395
+ };
37396
+ resolve = async (bindingId, id, signal) => {
37397
+ this.authorizeMachine(bindingId);
37398
+ return await this.resolvePath(this.requestedPath(id), signal);
37399
+ };
37400
+ list = async (bindingId, id, signal) => {
37401
+ const target = await this.resolve(bindingId, id, signal);
37402
+ try {
37403
+ const children = await readdir2(target, { withFileTypes: true });
37404
+ signal.throwIfAborted();
37405
+ const entries = [];
37406
+ for (const child of children) {
37407
+ if (entries.length === 500) {
37408
+ break;
37409
+ }
37410
+ if (child.isFile() || child.isBlockDevice() || child.isCharacterDevice() || child.isFIFO() || child.isSocket()) {
37411
+ continue;
37412
+ }
37413
+ try {
37414
+ const path2 = await this.resolvePath(join16(target, child.name), signal);
37415
+ entries.push({ directoryId: encodePath(path2), name: child.name });
37416
+ } catch (cause) {
37417
+ signal.throwIfAborted();
37418
+ if (!(cause instanceof LocalAuthorizationError)) {
37419
+ throw cause;
37420
+ }
37421
+ }
37422
+ }
37423
+ entries.sort((a, b) => a.name.localeCompare(b.name));
37424
+ const parent = dirname5(target);
37425
+ return new WorkspaceDirectoryListing(
37426
+ id,
37427
+ this.label(target),
37428
+ entries,
37429
+ parent === target ? "" : encodePath(parent)
37430
+ );
37431
+ } catch (cause) {
37432
+ signal.throwIfAborted();
37433
+ if (cause instanceof LocalAuthorizationError) {
37434
+ throw cause;
37435
+ }
37436
+ throw new LocalAuthorizationError("This directory cannot be browsed by your user account", { cause });
37437
+ }
37438
+ };
37439
+ resolveMany = async (bindingId, ids, signal) => {
37440
+ const paths = /* @__PURE__ */ new Set();
37441
+ for (const id of ids) {
37442
+ paths.add(await this.resolve(bindingId, id, signal));
37443
+ }
37444
+ return [...paths];
37445
+ };
37446
+ };
37447
+
37448
+ // src/bots/local-bot-grant-store.ts
37449
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
37450
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
37451
+ var LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS = 90 * 24 * 60 * 60 * 1e3;
37452
+ var LocalBotAuthorizationError = class extends Error {
37453
+ code;
37454
+ constructor(code, message, options = {}) {
37455
+ super(message, options);
37456
+ this.code = code;
37457
+ this.name = "LocalBotAuthorizationError";
37458
+ }
37459
+ };
37460
+ var LocalBotGrant = class {
37461
+ agent;
37462
+ agentIdentityDigest;
37463
+ allowedDeliveryTargetIds;
37464
+ behaviorDigest;
37465
+ behaviorRevisionId;
37466
+ bindingId;
37467
+ bindingRevision;
37468
+ botId;
37469
+ expiresAt;
37470
+ localGrantId;
37471
+ revocationEpoch;
37472
+ workspaceIdentityDigest;
37473
+ workspacePath;
37474
+ workspaceRef;
37475
+ constructor(localGrantId, botId, behaviorRevisionId, behaviorDigest, bindingId, bindingRevision, agent, agentIdentityDigest, workspaceRef, workspacePath, workspaceIdentityDigest, allowedDeliveryTargetIds, expiresAt, revocationEpoch) {
37476
+ this.localGrantId = localGrantId;
37477
+ this.botId = botId;
37478
+ this.behaviorRevisionId = behaviorRevisionId;
37479
+ this.behaviorDigest = behaviorDigest;
37480
+ this.bindingId = bindingId;
37481
+ this.bindingRevision = bindingRevision;
37482
+ this.agent = agent;
37483
+ this.agentIdentityDigest = agentIdentityDigest;
37484
+ this.workspaceRef = workspaceRef;
37485
+ this.workspacePath = workspacePath;
37486
+ this.workspaceIdentityDigest = workspaceIdentityDigest;
37487
+ this.allowedDeliveryTargetIds = Object.freeze([...allowedDeliveryTargetIds]);
37488
+ this.expiresAt = expiresAt;
37489
+ this.revocationEpoch = revocationEpoch;
37490
+ }
37491
+ };
37492
+ function digest(value) {
37493
+ return createHash3("sha256").update(value, "utf8").digest("hex");
37494
+ }
37495
+ function agentDigest(agent) {
37496
+ return digest(
37497
+ JSON.stringify({
37498
+ adapter: agent.adapterIdentity,
37499
+ agent: agent.agentIdentity,
37500
+ agentVersion: agent.agentVersion,
37501
+ arguments: agent.arguments,
37502
+ id: agent.id
37503
+ })
37504
+ );
37505
+ }
37506
+ function workspaceDigest(path2) {
37507
+ return digest(path2);
37508
+ }
37509
+ function exactTargets(left, right) {
37510
+ if (left.length !== right.length) {
37511
+ return false;
37512
+ }
37513
+ const expected = [...left].sort();
37514
+ const actual = [...right].sort();
37515
+ return expected.every((target, index2) => target === actual[index2]);
37516
+ }
37517
+ function exactSessionConfigurations(left, right) {
37518
+ if (left.length !== right.length) {
37519
+ return false;
37520
+ }
37521
+ const expected = new Map(left.map((selection) => [selection.configId, selection]));
37522
+ return right.every((selection) => {
37523
+ const approved = expected.get(selection.configId);
37524
+ return approved !== void 0 && approved.booleanValue === selection.booleanValue && approved.value === selection.value && approved.valueType === selection.valueType;
37525
+ });
37451
37526
  }
37452
- function channelOrigin(config2) {
37453
- const url2 = new URL(config2.relayUrl);
37454
- url2.protocol = url2.protocol === "wss:" ? "https:" : "http:";
37455
- let channelPath = "";
37456
- if (url2.pathname.endsWith("/daemon")) {
37457
- channelPath = url2.pathname.slice(0, -"/daemon".length);
37458
- } else {
37459
- const runtimePath = `${MOBIUS_API_PREFIX}/v1/runtimes/connect`;
37460
- if (!url2.pathname.endsWith("/v1/runtimes/connect") && !url2.pathname.endsWith(runtimePath)) {
37461
- throw new RuntimeArtifactUploadError("artifact_endpoint_invalid", "The Relay artifact endpoint is invalid");
37462
- }
37463
- channelPath = `${url2.pathname.replace(/\/v1\/runtimes\/connect$/, "")}/channels/${encodeURIComponent(config2.channelId)}`;
37527
+ function rowString(row, key) {
37528
+ const value = Reflect.get(row, key);
37529
+ if (typeof value !== "string") {
37530
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37464
37531
  }
37465
- url2.pathname = channelPath;
37466
- url2.search = "";
37467
- url2.hash = "";
37468
- return url2;
37532
+ return value;
37469
37533
  }
37470
- function uploadError(code, message, cause) {
37471
- return new RuntimeArtifactUploadError(code, message, cause === void 0 ? {} : { cause });
37534
+ function rowInteger(row, key) {
37535
+ const value = Reflect.get(row, key);
37536
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
37537
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37538
+ }
37539
+ return value;
37472
37540
  }
37473
- function translateSdkError(cause) {
37474
- if (cause instanceof MobiusValidationError) {
37475
- throw uploadError("artifact_upload_failed", cause.message, cause);
37541
+ function rowHasInteger(row, key) {
37542
+ const value = Reflect.get(row, key);
37543
+ if (value === null) {
37544
+ return false;
37476
37545
  }
37477
- if (cause instanceof MobiusProtocolError) {
37478
- throw uploadError("artifact_upload_failed", "The Relay returned an invalid upload response", cause);
37546
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
37547
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37479
37548
  }
37480
- throw cause;
37549
+ return true;
37481
37550
  }
37482
- async function readJson(response) {
37551
+ function parseTargets(encoded) {
37552
+ let value;
37483
37553
  try {
37484
- return await response.json();
37554
+ value = JSON.parse(encoded);
37485
37555
  } catch (cause) {
37486
- throw uploadError("artifact_upload_failed", "The Relay returned an invalid upload response", cause);
37556
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
37557
+ }
37558
+ if (!Array.isArray(value) || value.some((target) => typeof target !== "string")) {
37559
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid");
37487
37560
  }
37561
+ return value.filter((target) => typeof target === "string");
37488
37562
  }
37489
- async function readAuthorization(response) {
37563
+ function parseSessionConfigurations(encoded) {
37564
+ let value;
37490
37565
  try {
37491
- return decodeMobiusArtifactUpload(await readJson(response));
37566
+ value = JSON.parse(encoded);
37567
+ return decodeSessionConfigurationSelections(value);
37492
37568
  } catch (cause) {
37493
- translateSdkError(cause);
37569
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is invalid", { cause });
37494
37570
  }
37495
37571
  }
37496
- function sessionArtifactUrl(origin, sessionId, resourcePath, token) {
37497
- const url2 = new URL(`${origin.pathname}/sessions/${encodeURIComponent(sessionId)}/${resourcePath}`, origin);
37498
- url2.searchParams.set("token", token);
37499
- return url2;
37500
- }
37501
- async function postLease(url2, request, signal) {
37502
- return await fetch4(url2, {
37503
- dispatcher: environmentProxyDispatcher,
37504
- headers: { "content-type": "application/json" },
37505
- method: "POST",
37506
- body: JSON.stringify(request),
37507
- signal
37508
- });
37509
- }
37510
- async function putContent(url2, authorization, bytes, signal) {
37511
- return await fetch4(url2, {
37512
- dispatcher: environmentProxyDispatcher,
37513
- headers: {
37514
- "content-type": authorization.mediaType,
37515
- "x-mobius-upload-token": authorization.uploadToken
37516
- },
37517
- method: "PUT",
37518
- body: bytes,
37519
- signal
37520
- });
37521
- }
37522
- async function uploadRuntimeArtifact(config2, sessionId, image, signal) {
37523
- signal.throwIfAborted();
37524
- let request;
37525
- try {
37526
- request = new MobiusArtifactUploadRequest(
37527
- image.name,
37528
- image.mimeType,
37529
- image.bytes.byteLength,
37530
- createHash3("sha256").update(image.bytes).digest("hex")
37531
- );
37532
- } catch (cause) {
37533
- translateSdkError(cause);
37572
+ var LocalBotGrantStore = class {
37573
+ #database;
37574
+ constructor(path2) {
37575
+ this.#database = new DatabaseSync3(path2);
37576
+ this.#database.exec(`
37577
+ CREATE TABLE IF NOT EXISTS local_bot_grants (
37578
+ local_grant_id TEXT PRIMARY KEY,
37579
+ bot_id TEXT NOT NULL,
37580
+ behavior_revision_id TEXT NOT NULL,
37581
+ behavior_digest TEXT NOT NULL,
37582
+ binding_id TEXT NOT NULL UNIQUE,
37583
+ binding_revision INTEGER NOT NULL,
37584
+ agent_ref TEXT NOT NULL,
37585
+ agent_identity_digest TEXT NOT NULL,
37586
+ workspace_ref TEXT NOT NULL,
37587
+ workspace_path TEXT NOT NULL,
37588
+ workspace_identity_digest TEXT NOT NULL,
37589
+ allowed_delivery_target_ids_json TEXT NOT NULL,
37590
+ unattended_policy_json TEXT NOT NULL,
37591
+ created_at INTEGER NOT NULL,
37592
+ expires_at INTEGER NOT NULL,
37593
+ revocation_epoch INTEGER NOT NULL DEFAULT 0,
37594
+ revoked_at INTEGER
37595
+ ) STRICT;
37596
+ CREATE TABLE IF NOT EXISTS local_bot_binding_resolutions (
37597
+ request_id TEXT PRIMARY KEY,
37598
+ binding_id TEXT NOT NULL,
37599
+ local_grant_id TEXT NOT NULL,
37600
+ resolved_at INTEGER NOT NULL,
37601
+ result TEXT NOT NULL CHECK (result IN ('approved', 'unavailable')),
37602
+ error_code TEXT,
37603
+ error_message TEXT
37604
+ ) STRICT;
37605
+ CREATE TABLE IF NOT EXISTS local_bot_grant_configurations (
37606
+ local_grant_id TEXT PRIMARY KEY,
37607
+ session_configurations_json TEXT NOT NULL
37608
+ ) STRICT;
37609
+ `);
37534
37610
  }
37535
- const timeoutSignal = AbortSignal.timeout(UPLOAD_TIMEOUT_MILLISECONDS);
37536
- const requestSignal = AbortSignal.any([signal, timeoutSignal]);
37537
- const origin = channelOrigin(config2);
37538
- const token = daemonToken(config2);
37539
- let created;
37540
- try {
37541
- created = await postLease(
37542
- sessionArtifactUrl(origin, sessionId, "artifacts/uploads", token),
37543
- request,
37544
- requestSignal
37545
- );
37546
- } catch (cause) {
37611
+ approve = async (request, catalog, directories, bindingAuthorityId, now, signal) => {
37547
37612
  signal.throwIfAborted();
37548
- throw uploadError(
37549
- timeoutSignal.aborted ? "artifact_upload_timeout" : "artifact_upload_failed",
37550
- timeoutSignal.aborted ? "The artifact upload authorization timed out" : "The artifact upload could not start",
37551
- cause
37552
- );
37553
- }
37554
- if (!created.ok) {
37555
- await created.body?.cancel();
37556
- throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact upload");
37557
- }
37558
- const authorization = await readAuthorization(created);
37559
- let uploaded;
37560
- try {
37561
- uploaded = await putContent(
37562
- sessionArtifactUrl(
37563
- origin,
37564
- sessionId,
37565
- `artifacts/${encodeURIComponent(authorization.artifactId)}/content`,
37566
- token
37567
- ),
37568
- authorization,
37569
- image.bytes,
37570
- requestSignal
37613
+ const existing = this.#database.prepare(
37614
+ `SELECT grants.* FROM local_bot_binding_resolutions AS resolutions
37615
+ INNER JOIN local_bot_grants AS grants
37616
+ ON grants.local_grant_id = resolutions.local_grant_id
37617
+ WHERE resolutions.request_id = ? AND resolutions.binding_id = ?
37618
+ AND resolutions.result = 'approved'`
37619
+ ).get(request.requestId, request.bindingId);
37620
+ if (existing !== void 0) {
37621
+ return new BotExecutionBindingApprovedEvent(
37622
+ request.requestId,
37623
+ request.botId,
37624
+ request.behaviorRevisionId,
37625
+ request.bindingId,
37626
+ request.bindingRevision,
37627
+ rowString(existing, "local_grant_id"),
37628
+ rowString(existing, "agent_identity_digest"),
37629
+ rowString(existing, "workspace_identity_digest")
37630
+ );
37631
+ }
37632
+ const resolved = await this.resolveProposal(request, catalog, directories, bindingAuthorityId, signal);
37633
+ const localGrantId = `lbg_${randomUUID3()}`;
37634
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
37635
+ this.#database.exec("BEGIN IMMEDIATE");
37636
+ try {
37637
+ this.#database.prepare(
37638
+ `INSERT INTO local_bot_grants (
37639
+ local_grant_id, bot_id, behavior_revision_id, behavior_digest,
37640
+ binding_id, binding_revision, agent_ref,
37641
+ agent_identity_digest, workspace_ref, workspace_path,
37642
+ workspace_identity_digest, allowed_delivery_target_ids_json,
37643
+ unattended_policy_json, created_at, expires_at
37644
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
37645
+ ).run(
37646
+ localGrantId,
37647
+ request.botId,
37648
+ request.behaviorRevisionId,
37649
+ request.behaviorDigest,
37650
+ request.bindingId,
37651
+ request.bindingRevision,
37652
+ request.agentRef,
37653
+ resolved.agentIdentityDigest,
37654
+ request.workspaceRef,
37655
+ resolved.workspacePath,
37656
+ resolved.workspaceIdentityDigest,
37657
+ JSON.stringify(request.allowedDeliveryTargets.map((target) => target.deliveryTargetId)),
37658
+ JSON.stringify({ localSideEffects: "owner-approval-required" }),
37659
+ now,
37660
+ expiresAt
37661
+ );
37662
+ this.#database.prepare(
37663
+ `INSERT INTO local_bot_grant_configurations (
37664
+ local_grant_id, session_configurations_json
37665
+ ) VALUES (?, ?)`
37666
+ ).run(localGrantId, JSON.stringify(request.sessionConfigurations));
37667
+ this.#database.prepare(
37668
+ `INSERT INTO local_bot_binding_resolutions (
37669
+ request_id, binding_id, local_grant_id, resolved_at, result
37670
+ ) VALUES (?, ?, ?, ?, 'approved')`
37671
+ ).run(request.requestId, request.bindingId, localGrantId, now);
37672
+ this.#database.exec("COMMIT");
37673
+ } catch (cause) {
37674
+ this.#database.exec("ROLLBACK");
37675
+ throw cause;
37676
+ }
37677
+ signal.throwIfAborted();
37678
+ return new BotExecutionBindingApprovedEvent(
37679
+ request.requestId,
37680
+ request.botId,
37681
+ request.behaviorRevisionId,
37682
+ request.bindingId,
37683
+ request.bindingRevision,
37684
+ localGrantId,
37685
+ resolved.agentIdentityDigest,
37686
+ resolved.workspaceIdentityDigest
37571
37687
  );
37572
- } catch (cause) {
37688
+ };
37689
+ resolveExecution = async (command, catalog, directories, bindingAuthorityId, now, signal) => {
37573
37690
  signal.throwIfAborted();
37574
- throw uploadError(
37575
- timeoutSignal.aborted ? "artifact_upload_timeout" : "artifact_upload_failed",
37576
- timeoutSignal.aborted ? "The artifact upload timed out" : "The artifact content could not be uploaded",
37577
- cause
37691
+ const row = this.#database.prepare(
37692
+ `SELECT grants.*, COALESCE(configurations.session_configurations_json, '[]')
37693
+ AS session_configurations_json
37694
+ FROM local_bot_grants AS grants
37695
+ LEFT JOIN local_bot_grant_configurations AS configurations
37696
+ ON configurations.local_grant_id = grants.local_grant_id
37697
+ WHERE grants.local_grant_id = ? AND grants.bot_id = ?
37698
+ AND behavior_revision_id = ? AND behavior_digest = ?
37699
+ AND binding_id = ? AND binding_revision = ?
37700
+ AND agent_ref = ?`
37701
+ ).get(
37702
+ command.localGrantId,
37703
+ command.botId,
37704
+ command.behaviorRevisionId,
37705
+ command.behaviorDigest,
37706
+ command.bindingId,
37707
+ command.bindingRevision,
37708
+ command.agentId
37578
37709
  );
37579
- }
37580
- if (!uploaded.ok) {
37581
- await uploaded.body?.cancel();
37582
- throw uploadError("artifact_upload_rejected", "The Relay rejected the artifact content");
37583
- }
37584
- try {
37585
- const available = decodeMobiusAvailableArtifact(await readJson(uploaded));
37586
- return new UploadedRuntimeArtifact(
37587
- available.artifactId,
37588
- available.name,
37589
- available.mediaType,
37590
- available.byteLength,
37591
- available.sha256
37710
+ if (row === void 0) {
37711
+ throw new LocalBotAuthorizationError(
37712
+ "binding_not_approved",
37713
+ "The Bot execution binding is not locally approved"
37714
+ );
37715
+ }
37716
+ const approvedTargets = parseTargets(rowString(row, "allowed_delivery_target_ids_json"));
37717
+ const requestedTargets = command.allowedDeliveryTargets.map((target) => target.deliveryTargetId);
37718
+ if (!exactTargets(approvedTargets, requestedTargets)) {
37719
+ throw new LocalBotAuthorizationError(
37720
+ "binding_not_approved",
37721
+ "The Bot execution target policy differs from its binding"
37722
+ );
37723
+ }
37724
+ const approvedConfigurations = parseSessionConfigurations(rowString(row, "session_configurations_json"));
37725
+ if (!exactSessionConfigurations(approvedConfigurations, command.sessionConfigurations)) {
37726
+ throw new LocalBotAuthorizationError(
37727
+ "binding_not_approved",
37728
+ "The Bot Agent configuration differs from its binding"
37729
+ );
37730
+ }
37731
+ const agent = catalog.find(command.agentId);
37732
+ const [adapterUnchanged, agentUnchanged] = await Promise.all([
37733
+ revalidateExecutable(agent.adapterIdentity),
37734
+ revalidateExecutable(agent.agentIdentity)
37735
+ ]);
37736
+ signal.throwIfAborted();
37737
+ if (!adapterUnchanged || !agentUnchanged) {
37738
+ throw new LocalBotAuthorizationError(
37739
+ "binding_incompatible",
37740
+ "The local Agent executable changed while the Runtime is active; restart the Runtime"
37741
+ );
37742
+ }
37743
+ const workspaceRef = rowString(row, "workspace_ref");
37744
+ const workspacePath = await directories.resolve(bindingAuthorityId, workspaceRef, signal);
37745
+ const currentAgentDigest = agentDigest(agent);
37746
+ const currentWorkspaceDigest = workspaceDigest(workspacePath);
37747
+ signal.throwIfAborted();
37748
+ let expiresAt = rowInteger(row, "expires_at");
37749
+ let revocationEpoch = rowInteger(row, "revocation_epoch");
37750
+ if (currentAgentDigest !== rowString(row, "agent_identity_digest") || currentWorkspaceDigest !== rowString(row, "workspace_identity_digest") || workspacePath !== rowString(row, "workspace_path") || expiresAt <= now || rowHasInteger(row, "revoked_at")) {
37751
+ const refreshed = this.refreshTarget(
37752
+ rowString(row, "local_grant_id"),
37753
+ currentAgentDigest,
37754
+ currentWorkspaceDigest,
37755
+ workspacePath,
37756
+ now
37757
+ );
37758
+ expiresAt = refreshed.expiresAt;
37759
+ revocationEpoch = refreshed.revocationEpoch;
37760
+ }
37761
+ if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
37762
+ throw new LocalBotAuthorizationError(
37763
+ "binding_incompatible",
37764
+ "The local Agent cannot apply the approved Bot behavior"
37765
+ );
37766
+ }
37767
+ return new LocalBotGrant(
37768
+ rowString(row, "local_grant_id"),
37769
+ command.botId,
37770
+ command.behaviorRevisionId,
37771
+ command.behaviorDigest,
37772
+ command.bindingId,
37773
+ command.bindingRevision,
37774
+ agent,
37775
+ currentAgentDigest,
37776
+ workspaceRef,
37777
+ workspacePath,
37778
+ currentWorkspaceDigest,
37779
+ approvedTargets,
37780
+ expiresAt,
37781
+ revocationEpoch
37592
37782
  );
37593
- } catch (cause) {
37594
- translateSdkError(cause);
37595
- }
37596
- }
37783
+ };
37784
+ recordUnavailable = (request, code, message, now) => {
37785
+ this.#database.prepare(
37786
+ `INSERT OR IGNORE INTO local_bot_binding_resolutions (
37787
+ request_id, binding_id, local_grant_id, resolved_at,
37788
+ result, error_code, error_message
37789
+ ) VALUES (?, ?, '', ?, 'unavailable', ?, ?)`
37790
+ ).run(request.requestId, request.bindingId, now, code, message);
37791
+ };
37792
+ close = () => {
37793
+ this.#database.close();
37794
+ };
37795
+ resolveProposal = async (request, catalog, directories, bindingAuthorityId, signal) => {
37796
+ const agent = catalog.find(request.agentRef);
37797
+ if (request.requiredCapabilities.includes("embedded-context") && !agent.capabilities.embeddedContextPrompt) {
37798
+ throw new LocalBotAuthorizationError(
37799
+ "binding_incompatible",
37800
+ "The local Agent cannot apply embedded Bot context"
37801
+ );
37802
+ }
37803
+ if (request.requiredCapabilities.some((capability) => capability !== "embedded-context")) {
37804
+ throw new LocalBotAuthorizationError(
37805
+ "binding_incompatible",
37806
+ "The Bot requires an unsupported local Agent capability"
37807
+ );
37808
+ }
37809
+ const [adapterUnchanged, agentUnchanged] = await Promise.all([
37810
+ revalidateExecutable(agent.adapterIdentity),
37811
+ revalidateExecutable(agent.agentIdentity)
37812
+ ]);
37813
+ signal.throwIfAborted();
37814
+ if (!adapterUnchanged || !agentUnchanged) {
37815
+ throw new LocalBotAuthorizationError(
37816
+ "binding_incompatible",
37817
+ "The local Agent executable changed before approval"
37818
+ );
37819
+ }
37820
+ const workspacePath = await directories.resolve(bindingAuthorityId, request.workspaceRef, signal);
37821
+ return {
37822
+ agent,
37823
+ agentIdentityDigest: agentDigest(agent),
37824
+ workspaceIdentityDigest: workspaceDigest(workspacePath),
37825
+ workspacePath
37826
+ };
37827
+ };
37828
+ refreshTarget = (localGrantId, agentIdentityDigest, workspaceIdentityDigest, workspacePath, now) => {
37829
+ const expiresAt = now + LOCAL_BOT_GRANT_LIFETIME_MILLISECONDS;
37830
+ this.#database.exec("BEGIN IMMEDIATE");
37831
+ try {
37832
+ const current = this.#database.prepare("SELECT * FROM local_bot_grants WHERE local_grant_id = ?").get(localGrantId);
37833
+ if (current === void 0) {
37834
+ throw new LocalBotAuthorizationError("local_grant_invalid", "The local Bot grant is missing");
37835
+ }
37836
+ const currentExpiresAt = rowInteger(current, "expires_at");
37837
+ const currentRevocationEpoch = rowInteger(current, "revocation_epoch");
37838
+ if (agentIdentityDigest === rowString(current, "agent_identity_digest") && workspaceIdentityDigest === rowString(current, "workspace_identity_digest") && workspacePath === rowString(current, "workspace_path") && currentExpiresAt > now && !rowHasInteger(current, "revoked_at")) {
37839
+ this.#database.exec("COMMIT");
37840
+ return { expiresAt: currentExpiresAt, revocationEpoch: currentRevocationEpoch };
37841
+ }
37842
+ const result = this.#database.prepare(
37843
+ `UPDATE local_bot_grants
37844
+ SET agent_identity_digest = ?, workspace_identity_digest = ?, workspace_path = ?,
37845
+ expires_at = ?, revoked_at = NULL, revocation_epoch = revocation_epoch + 1
37846
+ WHERE local_grant_id = ? AND revocation_epoch = ?`
37847
+ ).run(
37848
+ agentIdentityDigest,
37849
+ workspaceIdentityDigest,
37850
+ workspacePath,
37851
+ expiresAt,
37852
+ localGrantId,
37853
+ currentRevocationEpoch
37854
+ );
37855
+ if (result.changes !== 1) {
37856
+ throw new LocalBotAuthorizationError(
37857
+ "local_grant_invalid",
37858
+ "The local Bot grant target could not be refreshed"
37859
+ );
37860
+ }
37861
+ this.#database.prepare(
37862
+ `INSERT INTO audit_events (recorded_at, event, command_id, session_id, details_json)
37863
+ VALUES (?, 'bot_binding_target_refreshed', ?, '', ?)`
37864
+ ).run(
37865
+ new Date(now).toISOString(),
37866
+ rowString(current, "binding_id"),
37867
+ JSON.stringify({
37868
+ agentIdentityChanged: agentIdentityDigest !== rowString(current, "agent_identity_digest"),
37869
+ bindingId: rowString(current, "binding_id"),
37870
+ botId: rowString(current, "bot_id"),
37871
+ expired: currentExpiresAt <= now,
37872
+ revived: rowHasInteger(current, "revoked_at"),
37873
+ workspaceIdentityChanged: workspaceIdentityDigest !== rowString(current, "workspace_identity_digest"),
37874
+ workspacePathChanged: workspacePath !== rowString(current, "workspace_path")
37875
+ })
37876
+ );
37877
+ this.#database.exec("COMMIT");
37878
+ return { expiresAt, revocationEpoch: currentRevocationEpoch + 1 };
37879
+ } catch (cause) {
37880
+ this.#database.exec("ROLLBACK");
37881
+ throw cause;
37882
+ }
37883
+ };
37884
+ };
37597
37885
 
37598
37886
  // src/bots/bot-context-applicator.ts
37599
37887
  var AppliedBotContext = class {
@@ -37730,7 +38018,7 @@ var BotExecutionContextRegistry = class {
37730
38018
  // src/bots/bot-outbound-ipc.ts
37731
38019
  import { chmod as chmod2, mkdir as mkdir4, unlink } from "node:fs/promises";
37732
38020
  import { createServer } from "node:net";
37733
- import { dirname as dirname7, isAbsolute as isAbsolute10 } from "node:path";
38021
+ import { dirname as dirname6, isAbsolute as isAbsolute10 } from "node:path";
37734
38022
  import { fetch as fetch5 } from "undici";
37735
38023
  var BOT_IPC_REQUEST_LIMIT = 32 * 1024;
37736
38024
  var BOT_IPC_TIMEOUT_MILLISECONDS2 = 2e4;
@@ -37843,7 +38131,7 @@ var BotOutboundIpcServer = class {
37843
38131
  listen = async (signal) => {
37844
38132
  signal.throwIfAborted();
37845
38133
  if (this.#usesFilesystemSocket) {
37846
- await mkdir4(dirname7(this.#socketPath), { mode: 448, recursive: true });
38134
+ await mkdir4(dirname6(this.#socketPath), { mode: 448, recursive: true });
37847
38135
  await unlink(this.#socketPath).catch((error62) => {
37848
38136
  if (!isRecord12(error62) || error62["code"] !== "ENOENT") {
37849
38137
  throw error62;
@@ -39187,7 +39475,7 @@ var RelayConnectionLiveness = class {
39187
39475
 
39188
39476
  // src/relay-connection/session-event-outbox.ts
39189
39477
  import { mkdirSync as mkdirSync3 } from "node:fs";
39190
- import { dirname as dirname8 } from "node:path";
39478
+ import { dirname as dirname7 } from "node:path";
39191
39479
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
39192
39480
  var DEFAULT_OUTBOX_LIMITS = {
39193
39481
  criticalEventBytes: 136 * 1024 * 1024,
@@ -39253,7 +39541,7 @@ var SessionEventOutbox = class {
39253
39541
  constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
39254
39542
  validateLimits(limits);
39255
39543
  this.#limits = limits;
39256
- mkdirSync3(dirname8(path2), { recursive: true });
39544
+ mkdirSync3(dirname7(path2), { recursive: true });
39257
39545
  this.#database = new DatabaseSync4(path2);
39258
39546
  this.#database.exec(`
39259
39547
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
@@ -39790,7 +40078,7 @@ function botIpcSocketPath() {
39790
40078
  if (process.platform === "win32") {
39791
40079
  return `\\\\.\\pipe\\mobius-bot-${randomUUID6()}`;
39792
40080
  }
39793
- return join18("/tmp", `mobius-bot-${randomUUID6()}.sock`);
40081
+ return join17("/tmp", `mobius-bot-${randomUUID6()}.sock`);
39794
40082
  }
39795
40083
  var DaemonAcpObserver = class {
39796
40084
  #config;
@@ -40756,32 +41044,9 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
40756
41044
  }
40757
41045
  const attachments = await resolvePromptArtifacts(config2, command, signal);
40758
41046
  const applied = await applicator.apply(command, grant, attachments.resources, signal);
40759
- const lease = contexts.activate(command);
40760
- try {
40761
- const deadlineSignal = AbortSignal.timeout(remaining);
40762
- const executionSignal = AbortSignal.any([signal, deadlineSignal]);
40763
- const agent = botExecutionAgent(grant.agent, lease.context.contextHandle, ipc.socketPath);
40764
- await sessions.prepareExecutionSession({
40765
- additionalDirectories: resolved.additionalDirectories,
40766
- agent,
40767
- cwd: resolved.cwd,
40768
- sessionId: command.sessionId,
40769
- signal: executionSignal
40770
- });
40771
- for (const selection of command.sessionConfigurations) {
40772
- await sessions.configureSession({
40773
- additionalDirectories: resolved.additionalDirectories,
40774
- agent,
40775
- booleanValue: selection.booleanValue,
40776
- configId: selection.configId,
40777
- cwd: resolved.cwd,
40778
- requestId: `cfg_${randomUUID6()}`,
40779
- sessionId: command.sessionId,
40780
- signal: executionSignal,
40781
- value: selection.value,
40782
- valueType: selection.valueType
40783
- });
40784
- }
41047
+ const deadlineSignal = AbortSignal.timeout(remaining);
41048
+ const executionSignal = AbortSignal.any([signal, deadlineSignal]);
41049
+ const startExecution = () => {
40785
41050
  audit.record({
40786
41051
  commandId: command.commandId,
40787
41052
  details: {
@@ -40806,56 +41071,106 @@ async function executeBotPrompt(outbox, publisher, command, config2, directories
40806
41071
  attemptId
40807
41072
  );
40808
41073
  activateAttempt();
40809
- const result = await sessions.runPrompt({
41074
+ };
41075
+ let stopReason = "steered";
41076
+ if (command.disposition === SessionPromptDisposition.Steer) {
41077
+ startExecution();
41078
+ await sessions.steerPrompt({
40810
41079
  additionalDirectories: resolved.additionalDirectories,
40811
- agent,
41080
+ agent: grant.agent,
40812
41081
  commandId: command.commandId,
40813
41082
  cwd: resolved.cwd,
40814
41083
  images: attachments.images,
40815
- onActivity: activities.record,
40816
- onText: (text3, messageId) => {
40817
- publisher.recordAttempt(
40818
- command.sessionId,
40819
- encodeAgentMessageDeltaEvent({
40820
- commandId: command.commandId,
40821
- kind: AGENT_MESSAGE_DELTA_KIND,
40822
- messageId,
40823
- sessionId: command.sessionId,
40824
- text: text3
40825
- }),
40826
- attemptId
40827
- );
40828
- return Promise.resolve();
40829
- },
40830
41084
  prompt: command.prompt,
40831
41085
  resources: applied.resources,
40832
41086
  sessionId: command.sessionId,
40833
- signal: executionSignal
41087
+ signal: executionSignal,
41088
+ targetCommandId: command.targetCommandId
40834
41089
  });
40835
- activities.flush();
40836
- publisher.recordAttempt(
40837
- command.sessionId,
40838
- encodeSessionCompletedEvent({
41090
+ } else {
41091
+ if (command.disposition === SessionPromptDisposition.Queue && !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
41092
+ throw new AcpExecutionError(
41093
+ "The queued Bot prompt target is unavailable",
41094
+ {},
41095
+ "prompt_queue_target_unavailable"
41096
+ );
41097
+ }
41098
+ const lease = contexts.activate(command);
41099
+ try {
41100
+ const agent = botExecutionAgent(grant.agent, lease.context.contextHandle, ipc.socketPath);
41101
+ await sessions.prepareExecutionSession({
41102
+ additionalDirectories: resolved.additionalDirectories,
41103
+ agent,
41104
+ cwd: resolved.cwd,
41105
+ sessionId: command.sessionId,
41106
+ signal: executionSignal
41107
+ });
41108
+ for (const selection of command.sessionConfigurations) {
41109
+ await sessions.configureSession({
41110
+ additionalDirectories: resolved.additionalDirectories,
41111
+ agent,
41112
+ booleanValue: selection.booleanValue,
41113
+ configId: selection.configId,
41114
+ cwd: resolved.cwd,
41115
+ requestId: `cfg_${randomUUID6()}`,
41116
+ sessionId: command.sessionId,
41117
+ signal: executionSignal,
41118
+ value: selection.value,
41119
+ valueType: selection.valueType
41120
+ });
41121
+ }
41122
+ startExecution();
41123
+ const result = await sessions.runPrompt({
41124
+ additionalDirectories: resolved.additionalDirectories,
41125
+ agent,
40839
41126
  commandId: command.commandId,
40840
- kind: SESSION_COMPLETED_KIND,
41127
+ cwd: resolved.cwd,
41128
+ disposition: command.disposition,
41129
+ images: attachments.images,
41130
+ onActivity: activities.record,
41131
+ onText: (text3, messageId) => {
41132
+ publisher.recordAttempt(
41133
+ command.sessionId,
41134
+ encodeAgentMessageDeltaEvent({
41135
+ commandId: command.commandId,
41136
+ kind: AGENT_MESSAGE_DELTA_KIND,
41137
+ messageId,
41138
+ sessionId: command.sessionId,
41139
+ text: text3
41140
+ }),
41141
+ attemptId
41142
+ );
41143
+ return Promise.resolve();
41144
+ },
41145
+ prompt: command.prompt,
41146
+ resources: applied.resources,
40841
41147
  sessionId: command.sessionId,
40842
- stopReason: result.stopReason
40843
- }),
40844
- attemptId
40845
- );
40846
- outbox.transitionExecution(
40847
- command.commandId,
40848
- result.stopReason === "cancelled" ? "cancelled" : "succeeded"
40849
- );
40850
- audit.record({
40851
- commandId: command.commandId,
40852
- details: { botId: command.botId, executionId: command.executionId },
40853
- event: result.stopReason === "cancelled" ? "bot_session_cancelled" : "bot_session_completed",
40854
- sessionId: command.sessionId
40855
- });
40856
- } finally {
40857
- lease.release();
41148
+ signal: executionSignal,
41149
+ targetCommandId: command.targetCommandId
41150
+ });
41151
+ stopReason = result.stopReason;
41152
+ } finally {
41153
+ lease.release();
41154
+ }
40858
41155
  }
41156
+ activities.flush();
41157
+ publisher.recordAttempt(
41158
+ command.sessionId,
41159
+ encodeSessionCompletedEvent({
41160
+ commandId: command.commandId,
41161
+ kind: SESSION_COMPLETED_KIND,
41162
+ sessionId: command.sessionId,
41163
+ stopReason
41164
+ }),
41165
+ attemptId
41166
+ );
41167
+ outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
41168
+ audit.record({
41169
+ commandId: command.commandId,
41170
+ details: { botId: command.botId, executionId: command.executionId },
41171
+ event: stopReason === "cancelled" ? "bot_session_cancelled" : "bot_session_completed",
41172
+ sessionId: command.sessionId
41173
+ });
40859
41174
  } catch (error62) {
40860
41175
  activities.flush();
40861
41176
  const failure2 = Date.parse(command.executionDeadlineAt) <= Date.now() ? new LocalBotAuthorizationError("turn_expired", "The Bot execution deadline has expired", {
@@ -41106,7 +41421,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41106
41421
  await processDeliveredPrompt(
41107
41422
  delivery,
41108
41423
  command,
41109
- true,
41424
+ command.disposition !== SessionPromptDisposition.Steer,
41110
41425
  (attemptId, activateAttempt, executionSignal) => executeBotPrompt(
41111
41426
  outbox,
41112
41427
  publisher,
@@ -41759,7 +42074,11 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41759
42074
  applicator,
41760
42075
  ipc,
41761
42076
  receipt2.attemptId,
41762
- () => activeAttemptIds.set(command2.sessionId, receipt2.attemptId),
42077
+ () => {
42078
+ if (command2.disposition !== SessionPromptDisposition.Steer) {
42079
+ activeAttemptIds.set(command2.sessionId, receipt2.attemptId);
42080
+ }
42081
+ },
41763
42082
  timer,
41764
42083
  turn2.signal
41765
42084
  ).catch((error62) => {
@@ -42095,7 +42414,6 @@ Usage:
42095
42414
  mobius pair --url <relay-url> --pairing <runtime-pairing-id> --code <pairing-code> [--workspace <directory>]
42096
42415
  mobius start --channel <channel-id>
42097
42416
  mobius agents [--json]
42098
- mobius bot approve --bot <bot-id> [--channel <channel-id>]
42099
42417
  mobius bot message send --target <current|alias> --text <message>
42100
42418
 
42101
42419
  Commands:
@@ -42103,7 +42421,7 @@ Commands:
42103
42421
  pair Pair this machine and start its local daemon
42104
42422
  start Start the local daemon for a saved channel
42105
42423
  agents Show detected, missing, and integration-ready Agents
42106
- bot Approve a saved Bot locally or send a message from an active execution
42424
+ bot Send a message from an active execution
42107
42425
 
42108
42426
  Pairing grants this browser access to the machine with your user account's permissions.
42109
42427
  New conversations default to ~/.mobius/workspace; choose other directories in the browser.
@@ -42134,10 +42452,6 @@ async function main() {
42134
42452
  return;
42135
42453
  }
42136
42454
  if (command === "bot") {
42137
- if (process.argv[3] === "approve") {
42138
- process.stdout.write(await executeBotApproveCommand(process.argv.slice(4), process.env, shutdown.signal));
42139
- return;
42140
- }
42141
42455
  if (process.argv[3] !== "message" || process.argv[4] !== "send") {
42142
42456
  throw new BotMessageCommandError(
42143
42457
  "invalid_request",
@@ -42183,7 +42497,7 @@ try {
42183
42497
  } catch (error62) {
42184
42498
  if (!shutdown.signal.aborted) {
42185
42499
  const message = error62 instanceof Error ? error62.message : "Unknown failure";
42186
- const code = error62 instanceof BotMessageCommandError || error62 instanceof LocalBotAuthorizationError ? `${error62.code}: ` : "";
42500
+ const code = error62 instanceof BotMessageCommandError ? `${error62.code}: ` : "";
42187
42501
  process.stderr.write(`Mobius daemon failed: ${code}${message}
42188
42502
  `);
42189
42503
  process.exitCode = 1;