@moxt-ai/mobius 0.0.81 → 0.0.88

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 (107) hide show
  1. package/dist/acp/codex/app-server-protocol.d.ts +2 -2
  2. package/dist/acp/codex/app-server-protocol.d.ts.map +1 -1
  3. package/dist/acp/codex/app-server-protocol.js +5 -3
  4. package/dist/acp/codex/app-server-protocol.js.map +1 -1
  5. package/dist/acp/session-config/session-config-registry.d.ts +1 -1
  6. package/dist/acp/session-config/session-config-registry.d.ts.map +1 -1
  7. package/dist/acp/session-config/session-config-registry.js +2 -3
  8. package/dist/acp/session-config/session-config-registry.js.map +1 -1
  9. package/dist/agent-catalog/agent-specification.d.ts +2 -0
  10. package/dist/agent-catalog/agent-specification.d.ts.map +1 -1
  11. package/dist/agent-catalog/agent-specification.js +2 -0
  12. package/dist/agent-catalog/agent-specification.js.map +1 -1
  13. package/dist/agent-catalog/agent-version.d.ts +3 -0
  14. package/dist/agent-catalog/agent-version.d.ts.map +1 -0
  15. package/dist/agent-catalog/agent-version.js +54 -0
  16. package/dist/agent-catalog/agent-version.js.map +1 -0
  17. package/dist/agent-catalog/agents/claude-code-agent.d.ts +2 -0
  18. package/dist/agent-catalog/agents/claude-code-agent.d.ts.map +1 -1
  19. package/dist/agent-catalog/agents/claude-code-agent.js +2 -0
  20. package/dist/agent-catalog/agents/claude-code-agent.js.map +1 -1
  21. package/dist/agent-catalog/agents/codex-agent.d.ts +2 -0
  22. package/dist/agent-catalog/agents/codex-agent.d.ts.map +1 -1
  23. package/dist/agent-catalog/agents/codex-agent.js +2 -0
  24. package/dist/agent-catalog/agents/codex-agent.js.map +1 -1
  25. package/dist/agent-catalog/agents/copilot-cli-agent.d.ts +2 -0
  26. package/dist/agent-catalog/agents/copilot-cli-agent.d.ts.map +1 -1
  27. package/dist/agent-catalog/agents/copilot-cli-agent.js +2 -0
  28. package/dist/agent-catalog/agents/copilot-cli-agent.js.map +1 -1
  29. package/dist/agent-catalog/agents/cursor-cli-agent.d.ts +2 -0
  30. package/dist/agent-catalog/agents/cursor-cli-agent.d.ts.map +1 -1
  31. package/dist/agent-catalog/agents/cursor-cli-agent.js +2 -0
  32. package/dist/agent-catalog/agents/cursor-cli-agent.js.map +1 -1
  33. package/dist/agent-catalog/agents/deepseek-harness-agent.d.ts +2 -0
  34. package/dist/agent-catalog/agents/deepseek-harness-agent.d.ts.map +1 -1
  35. package/dist/agent-catalog/agents/deepseek-harness-agent.js +2 -0
  36. package/dist/agent-catalog/agents/deepseek-harness-agent.js.map +1 -1
  37. package/dist/agent-catalog/agents/gemini-cli-agent.d.ts +2 -0
  38. package/dist/agent-catalog/agents/gemini-cli-agent.d.ts.map +1 -1
  39. package/dist/agent-catalog/agents/gemini-cli-agent.js +2 -0
  40. package/dist/agent-catalog/agents/gemini-cli-agent.js.map +1 -1
  41. package/dist/agent-catalog/agents/grok-build-agent.d.ts +2 -0
  42. package/dist/agent-catalog/agents/grok-build-agent.d.ts.map +1 -1
  43. package/dist/agent-catalog/agents/grok-build-agent.js +2 -0
  44. package/dist/agent-catalog/agents/grok-build-agent.js.map +1 -1
  45. package/dist/agent-catalog/agents/hermes-agent.d.ts +2 -0
  46. package/dist/agent-catalog/agents/hermes-agent.d.ts.map +1 -1
  47. package/dist/agent-catalog/agents/hermes-agent.js +2 -0
  48. package/dist/agent-catalog/agents/hermes-agent.js.map +1 -1
  49. package/dist/agent-catalog/agents/oh-my-pi-agent.d.ts +2 -0
  50. package/dist/agent-catalog/agents/oh-my-pi-agent.d.ts.map +1 -1
  51. package/dist/agent-catalog/agents/oh-my-pi-agent.js +2 -0
  52. package/dist/agent-catalog/agents/oh-my-pi-agent.js.map +1 -1
  53. package/dist/agent-catalog/agents/opencode-agent.d.ts +2 -0
  54. package/dist/agent-catalog/agents/opencode-agent.d.ts.map +1 -1
  55. package/dist/agent-catalog/agents/opencode-agent.js +2 -0
  56. package/dist/agent-catalog/agents/opencode-agent.js.map +1 -1
  57. package/dist/agent-catalog/agents/pi-agent.d.ts +2 -0
  58. package/dist/agent-catalog/agents/pi-agent.d.ts.map +1 -1
  59. package/dist/agent-catalog/agents/pi-agent.js +2 -0
  60. package/dist/agent-catalog/agents/pi-agent.js.map +1 -1
  61. package/dist/agent-catalog/agents/workbuddy-agent.d.ts +2 -0
  62. package/dist/agent-catalog/agents/workbuddy-agent.d.ts.map +1 -1
  63. package/dist/agent-catalog/agents/workbuddy-agent.js +2 -0
  64. package/dist/agent-catalog/agents/workbuddy-agent.js.map +1 -1
  65. package/dist/agent-catalog/discover-agent.d.ts.map +1 -1
  66. package/dist/agent-catalog/discover-agent.js +9 -0
  67. package/dist/agent-catalog/discover-agent.js.map +1 -1
  68. package/dist/agent-installation/deepseek-managed-package.d.ts.map +1 -1
  69. package/dist/agent-installation/deepseek-managed-package.js +3 -2
  70. package/dist/agent-installation/deepseek-managed-package.js.map +1 -1
  71. package/dist/cli.js +1154 -538
  72. package/dist/cli.js.map +4 -4
  73. package/dist/config.d.ts +2 -7
  74. package/dist/config.d.ts.map +1 -1
  75. package/dist/config.js +1 -10
  76. package/dist/config.js.map +1 -1
  77. package/dist/daemon-manager.d.ts +51 -0
  78. package/dist/daemon-manager.d.ts.map +1 -0
  79. package/dist/daemon-manager.js +589 -0
  80. package/dist/daemon-manager.js.map +1 -0
  81. package/dist/index.d.ts +2 -2
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +339 -433
  84. package/dist/index.js.map +4 -4
  85. package/dist/pairing/pair-local-machine.d.ts.map +1 -1
  86. package/dist/pairing/pair-local-machine.js +26 -40
  87. package/dist/pairing/pair-local-machine.js.map +1 -1
  88. package/dist/relay-connection/session-event-outbox.d.ts.map +1 -1
  89. package/dist/relay-connection/session-event-outbox.js +0 -62
  90. package/dist/relay-connection/session-event-outbox.js.map +1 -1
  91. package/dist/run-daemon.d.ts +1 -0
  92. package/dist/run-daemon.d.ts.map +1 -1
  93. package/dist/run-daemon.js +16 -4
  94. package/dist/run-daemon.js.map +1 -1
  95. package/dist/runtime.d.ts +3 -2
  96. package/dist/runtime.d.ts.map +1 -1
  97. package/dist/runtime.js +320 -385
  98. package/dist/runtime.js.map +4 -4
  99. package/dist/storage/runtime-installation-store.d.ts +14 -5
  100. package/dist/storage/runtime-installation-store.d.ts.map +1 -1
  101. package/dist/storage/runtime-installation-store.js +134 -89
  102. package/dist/storage/runtime-installation-store.js.map +1 -1
  103. package/package.json +1 -1
  104. package/dist/acp/session-config/grok-build-session-config.d.ts +0 -10
  105. package/dist/acp/session-config/grok-build-session-config.d.ts.map +0 -1
  106. package/dist/acp/session-config/grok-build-session-config.js +0 -197
  107. package/dist/acp/session-config/grok-build-session-config.js.map +0 -1
package/dist/cli.js CHANGED
@@ -6,12 +6,14 @@ var __export = (target, all2) => {
6
6
  };
7
7
 
8
8
  // src/cli.ts
9
- import { mkdir as mkdir6 } from "node:fs/promises";
9
+ import { constants as constants2 } from "node:fs";
10
+ import { mkdir as mkdir6, open as open7 } from "node:fs/promises";
11
+ import { resolve as resolve7 } from "node:path";
10
12
 
11
13
  // package.json
12
14
  var package_default = {
13
15
  name: "@moxt-ai/mobius",
14
- version: "0.0.81",
16
+ version: "0.0.88",
15
17
  description: "Mobius CLI for pairing and running local AI agent services.",
16
18
  type: "module",
17
19
  bin: {
@@ -1309,6 +1311,8 @@ function normalizeVersionOutput(output2) {
1309
1311
  var VERSION_PROBE_TIMEOUT_MILLISECONDS = 3e4;
1310
1312
  var ACP_PROBE_TIMEOUT_MILLISECONDS = 6e4;
1311
1313
  var LocalAgentSpecification = class {
1314
+ minimumSupportedAgentVersion = "0.0.0";
1315
+ maximumTestedAgentVersion = "0.0.0";
1312
1316
  acpProbeTimeoutMilliseconds = ACP_PROBE_TIMEOUT_MILLISECONDS;
1313
1317
  authenticationCommand = () => "";
1314
1318
  adapterVersionArguments = ["--version"];
@@ -1391,6 +1395,8 @@ var ClaudeCodeAgentSpecification = class extends BridgedAcpAgentDefinition {
1391
1395
  agentOverrideVariable = "MOBIUS_CLAUDE_PATH";
1392
1396
  id = "claude";
1393
1397
  label = "Claude Code";
1398
+ minimumSupportedAgentVersion = "2.1.273";
1399
+ maximumTestedAgentVersion = "2.1.273";
1394
1400
  managedAdapterExecutablePath = [
1395
1401
  "adapters",
1396
1402
  "claude",
@@ -6478,7 +6484,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
6478
6484
  var NONE = 0;
6479
6485
  var ASSUMED = 1;
6480
6486
  var PROVEN = 2;
6481
- function isRecursive(inst, stack, resolve7) {
6487
+ function isRecursive(inst, stack, resolve8) {
6482
6488
  const cached2 = recursive.get(inst);
6483
6489
  if (cached2 !== void 0)
6484
6490
  return cached2 ? PROVEN : NONE;
@@ -6488,7 +6494,7 @@ function isRecursive(inst, stack, resolve7) {
6488
6494
  let result = NONE;
6489
6495
  const check2 = (child) => {
6490
6496
  if (result !== PROVEN && child?._zod) {
6491
- const answer = isRecursive(child, stack, resolve7);
6497
+ const answer = isRecursive(child, stack, resolve8);
6492
6498
  if (answer > result)
6493
6499
  result = answer;
6494
6500
  }
@@ -6499,7 +6505,7 @@ function isRecursive(inst, stack, resolve7) {
6499
6505
  const desc = Object.getOwnPropertyDescriptor(sh, key);
6500
6506
  if (spread && !desc.enumerable)
6501
6507
  continue;
6502
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve7) : NONE;
6508
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve8) : NONE;
6503
6509
  if (child > answer)
6504
6510
  answer = child;
6505
6511
  }
@@ -6563,7 +6569,7 @@ function isRecursive(inst, stack, resolve7) {
6563
6569
  break;
6564
6570
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
6565
6571
  case "lazy": {
6566
- const inner = def._cachedInner ?? (resolve7 ? inst._zod.innerType : void 0);
6572
+ const inner = def._cachedInner ?? (resolve8 ? inst._zod.innerType : void 0);
6567
6573
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
6568
6574
  break;
6569
6575
  }
@@ -21303,11 +21309,12 @@ var threadLifecycleResponseSchema = external_exports.object({
21303
21309
  });
21304
21310
  var threadResumeResponseSchema = threadLifecycleResponseSchema;
21305
21311
  var threadForkResponseSchema = threadLifecycleResponseSchema;
21312
+ var threadTitleSchema = external_exports.string().transform((value) => value.slice(0, 500));
21306
21313
  var threadSummarySchema = external_exports.object({
21307
21314
  cwd: boundedText(2048),
21308
21315
  id: boundedText(256),
21309
- name: boundedText(500).nullish(),
21310
- preview: boundedText(500).nullish(),
21316
+ name: threadTitleSchema.nullish(),
21317
+ preview: threadTitleSchema.nullish(),
21311
21318
  updatedAt: external_exports.number().int().nonnegative()
21312
21319
  });
21313
21320
  var threadListResponseSchema = external_exports.object({
@@ -22622,6 +22629,8 @@ var CodexAgentSpecification = class extends InProcessAcpAgentDefinition2 {
22622
22629
  createEndpoint = (options) => new CodexAcpAgent(options);
22623
22630
  id = "codex";
22624
22631
  label = "Codex";
22632
+ minimumSupportedAgentVersion = "0.153.0";
22633
+ maximumTestedAgentVersion = "0.154.0";
22625
22634
  constructor() {
22626
22635
  super("MOBIUS_CODEX_PATH", ["agents", "codex", "bin", "codex"]);
22627
22636
  }
@@ -22684,6 +22693,8 @@ var CopilotCliAgentSpecification = class extends DirectAcpAgentDefinition {
22684
22693
  agentExecutable = "copilot";
22685
22694
  id = "github-copilot-cli";
22686
22695
  label = "GitHub Copilot CLI";
22696
+ minimumSupportedAgentVersion = COPILOT_CLI_TESTED_VERSION;
22697
+ maximumTestedAgentVersion = COPILOT_CLI_TESTED_VERSION;
22687
22698
  versionProbeTimeoutMilliseconds = 1e4;
22688
22699
  constructor() {
22689
22700
  super(
@@ -22714,6 +22725,8 @@ var CursorCliAgentSpecification = class extends DirectAcpAgentDefinition {
22714
22725
  agentExecutable = "cursor-agent";
22715
22726
  id = "cursor";
22716
22727
  label = "Cursor CLI";
22728
+ minimumSupportedAgentVersion = CURSOR_CLI_TESTED_VERSION;
22729
+ maximumTestedAgentVersion = CURSOR_CLI_TESTED_VERSION;
22717
22730
  constructor() {
22718
22731
  super(
22719
22732
  "MOBIUS_CURSOR_PATH",
@@ -22736,16 +22749,16 @@ import { isAbsolute as isAbsolute3, join as join6, normalize } from "node:path";
22736
22749
 
22737
22750
  // src/agent-installation/deepseek-managed-package.ts
22738
22751
  var DeepSeekHarnessManagedPackage = class extends SriManagedNpmPackageDefinition {
22739
- dependencyResolutionArguments = Object.freeze(["--before=2026-09-18T00:00:00.000Z"]);
22752
+ dependencyResolutionArguments = Object.freeze(["--before=2026-09-23T00:00:00.000Z"]);
22740
22753
  includeOptionalDependencies = true;
22741
22754
  verifyDependencyClosure = true;
22742
22755
  };
22743
22756
  var DEEPSEEK_HARNESS_PACKAGE = new DeepSeekHarnessManagedPackage(
22744
22757
  "@deepseek-ai/dsh",
22745
- "0.1.5-rc.2",
22758
+ "0.1.5-rc.3",
22746
22759
  "dsh",
22747
- "sha512-8Xc8hCQHcIWRmTCVU/xZdp6/qMsWMeAd2ObChKDEsfhUPJFXx6H0lgeb1DxUMD86HZrrVN+1bCvn1ppjZ/fOxw==",
22748
- "https://registry.npmjs.org/@deepseek-ai/dsh/-/dsh-0.1.5-rc.2.tgz"
22760
+ "sha512-c0W6Xqc4ChjFcCJkbzPeIxZQdnbKqe+QAcJzWGtogg0ZzsnZRcw3vopMyZ5oZU6E2fmyqGcyDR1sBeiCH4yHcg==",
22761
+ "https://registry.npmjs.org/@deepseek-ai/dsh/-/dsh-0.1.5-rc.3.tgz"
22749
22762
  );
22750
22763
 
22751
22764
  // src/storage/state-directory.ts
@@ -22800,6 +22813,8 @@ var DeepSeekHarnessAgentSpecification = class extends DirectAcpAgentDefinition {
22800
22813
  agentExecutable = "dsh";
22801
22814
  id = "deepseek-harness";
22802
22815
  label = "DeepSeek Harness";
22816
+ minimumSupportedAgentVersion = "0.1.2-rc.1";
22817
+ maximumTestedAgentVersion = DEEPSEEK_HARNESS_PACKAGE.version;
22803
22818
  constructor() {
22804
22819
  super(
22805
22820
  "MOBIUS_DEEPSEEK_HARNESS_PATH",
@@ -22870,6 +22885,8 @@ var GeminiCliAgentSpecification = class extends DirectAcpAgentDefinition {
22870
22885
  agentExecutable = "gemini";
22871
22886
  id = "gemini-cli";
22872
22887
  label = "Gemini CLI";
22888
+ minimumSupportedAgentVersion = GEMINI_CLI_TESTED_VERSION;
22889
+ maximumTestedAgentVersion = GEMINI_CLI_TESTED_VERSION;
22873
22890
  versionProbeTimeoutMilliseconds = 1e4;
22874
22891
  constructor() {
22875
22892
  super(
@@ -22971,6 +22988,8 @@ var GrokBuildAgentSpecification = class extends DirectAcpAgentDefinition {
22971
22988
  adapterVersionArguments = ["version"];
22972
22989
  id = "grok-build";
22973
22990
  label = "Grok Build";
22991
+ minimumSupportedAgentVersion = GROK_BUILD_MANAGED_VERSION;
22992
+ maximumTestedAgentVersion = GROK_BUILD_MANAGED_VERSION;
22974
22993
  constructor() {
22975
22994
  super(
22976
22995
  "MOBIUS_GROK_BUILD_PATH",
@@ -23042,6 +23061,8 @@ var HermesAgentSpecification = class extends DirectAcpAgentDefinition {
23042
23061
  agentVersionArguments = ["acp", "--version"];
23043
23062
  id = "hermes";
23044
23063
  label = "Hermes Agent";
23064
+ minimumSupportedAgentVersion = HERMES_TESTED_VERSION;
23065
+ maximumTestedAgentVersion = HERMES_TESTED_VERSION;
23045
23066
  constructor() {
23046
23067
  super("MOBIUS_HERMES_PATH", ["acp"], ["agents", "hermes", HERMES_TESTED_VERSION, "bin", "hermes"]);
23047
23068
  }
@@ -23070,6 +23091,8 @@ var OhMyPiAgentSpecification = class extends DirectAcpAgentDefinition {
23070
23091
  agentOverrideVariable = "MOBIUS_OH_MY_PI_PATH";
23071
23092
  id = "oh-my-pi";
23072
23093
  label = "Oh My Pi";
23094
+ minimumSupportedAgentVersion = OH_MY_PI_TESTED_VERSION;
23095
+ maximumTestedAgentVersion = OH_MY_PI_TESTED_VERSION;
23073
23096
  constructor() {
23074
23097
  super("MOBIUS_OH_MY_PI_PATH", ["acp"], ["agents", "oh-my-pi", OH_MY_PI_TESTED_VERSION, "bin", "omp"]);
23075
23098
  }
@@ -23461,6 +23484,8 @@ var OpenCodeAgentSpecification = class extends DirectAcpAgentDefinition {
23461
23484
  agentExecutable = "opencode";
23462
23485
  id = "opencode";
23463
23486
  label = "OpenCode";
23487
+ minimumSupportedAgentVersion = OPENCODE_MANAGED_VERSION;
23488
+ maximumTestedAgentVersion = OPENCODE_MANAGED_VERSION;
23464
23489
  constructor() {
23465
23490
  super(
23466
23491
  "MOBIUS_OPENCODE_PATH",
@@ -23535,6 +23560,8 @@ var PiAgentSpecification = class extends BridgedAcpAgentDefinition {
23535
23560
  agentOverrideVariable = "MOBIUS_PI_PATH";
23536
23561
  id = "pi";
23537
23562
  label = "Pi";
23563
+ minimumSupportedAgentVersion = PI_AGENT_PACKAGE.version;
23564
+ maximumTestedAgentVersion = PI_AGENT_PACKAGE.version;
23538
23565
  managedAdapterExecutablePath = [
23539
23566
  "adapters",
23540
23567
  "pi",
@@ -23629,6 +23656,8 @@ var WorkBuddyAgentSpecification = class extends DirectAcpAgentDefinition {
23629
23656
  agentExecutable = "codebuddy";
23630
23657
  id = "workbuddy";
23631
23658
  label = "WorkBuddy";
23659
+ minimumSupportedAgentVersion = "2.115.0";
23660
+ maximumTestedAgentVersion = WORKBUDDY_MANAGED_VERSION;
23632
23661
  constructor() {
23633
23662
  super(
23634
23663
  "MOBIUS_WORKBUDDY_PATH",
@@ -23756,41 +23785,41 @@ var DiscoveryAcpHandler = class {
23756
23785
  };
23757
23786
  function readableAcpStream(input2) {
23758
23787
  let byteLength = 0;
23759
- let open6 = true;
23788
+ let open8 = true;
23760
23789
  return new ReadableStream({
23761
23790
  start(controller) {
23762
23791
  input2.on("data", (chunk) => {
23763
- if (!open6) {
23792
+ if (!open8) {
23764
23793
  return;
23765
23794
  }
23766
23795
  if (!(chunk instanceof Uint8Array)) {
23767
- open6 = false;
23796
+ open8 = false;
23768
23797
  controller.error(new Error("ACP adapter produced invalid output"));
23769
23798
  return;
23770
23799
  }
23771
23800
  byteLength += chunk.byteLength;
23772
23801
  if (byteLength > ACP_OUTPUT_LIMIT_BYTES) {
23773
- open6 = false;
23802
+ open8 = false;
23774
23803
  controller.error(new Error("ACP adapter output limit exceeded"));
23775
23804
  return;
23776
23805
  }
23777
23806
  controller.enqueue(new Uint8Array(chunk));
23778
23807
  });
23779
23808
  input2.once("end", () => {
23780
- if (open6) {
23781
- open6 = false;
23809
+ if (open8) {
23810
+ open8 = false;
23782
23811
  controller.close();
23783
23812
  }
23784
23813
  });
23785
23814
  input2.once("error", (error62) => {
23786
- if (open6) {
23787
- open6 = false;
23815
+ if (open8) {
23816
+ open8 = false;
23788
23817
  controller.error(error62);
23789
23818
  }
23790
23819
  });
23791
23820
  },
23792
23821
  cancel() {
23793
- open6 = false;
23822
+ open8 = false;
23794
23823
  }
23795
23824
  });
23796
23825
  }
@@ -23971,6 +24000,61 @@ async function probeAcpReadiness(specification, agent, environment, defaultWorks
23971
24000
  }
23972
24001
  }
23973
24002
 
24003
+ // src/agent-catalog/agent-version.ts
24004
+ function parseVersion(value) {
24005
+ const match = /(?:^|[^0-9])v?(\d+(?:\.\d+)+)(?:-([0-9A-Za-z.-]+))?/u.exec(value);
24006
+ if (match?.[1] === void 0) {
24007
+ return null;
24008
+ }
24009
+ return {
24010
+ core: match[1].split(".").map(Number),
24011
+ prerelease: match[2]?.split(".") ?? []
24012
+ };
24013
+ }
24014
+ function comparePrerelease(left, right) {
24015
+ if (left.length === 0 || right.length === 0) {
24016
+ return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
24017
+ }
24018
+ for (let index2 = 0; index2 < Math.max(left.length, right.length); index2 += 1) {
24019
+ const leftPart = left[index2];
24020
+ const rightPart = right[index2];
24021
+ if (leftPart === void 0 || rightPart === void 0) {
24022
+ return leftPart === rightPart ? 0 : leftPart === void 0 ? -1 : 1;
24023
+ }
24024
+ if (leftPart === rightPart) {
24025
+ continue;
24026
+ }
24027
+ const leftNumber = /^\d+$/u.test(leftPart) ? Number(leftPart) : null;
24028
+ const rightNumber = /^\d+$/u.test(rightPart) ? Number(rightPart) : null;
24029
+ if (leftNumber !== null && rightNumber !== null) {
24030
+ return Math.sign(leftNumber - rightNumber);
24031
+ }
24032
+ if (leftNumber !== null || rightNumber !== null) {
24033
+ return leftNumber !== null ? -1 : 1;
24034
+ }
24035
+ return leftPart.localeCompare(rightPart);
24036
+ }
24037
+ return 0;
24038
+ }
24039
+ function compareAgentVersions(left, right) {
24040
+ const parsedLeft = parseVersion(left);
24041
+ const parsedRight = parseVersion(right);
24042
+ if (parsedLeft === null || parsedRight === null) {
24043
+ return null;
24044
+ }
24045
+ for (let index2 = 0; index2 < Math.max(parsedLeft.core.length, parsedRight.core.length); index2 += 1) {
24046
+ const difference = (parsedLeft.core[index2] ?? 0) - (parsedRight.core[index2] ?? 0);
24047
+ if (difference !== 0) {
24048
+ return Math.sign(difference);
24049
+ }
24050
+ }
24051
+ return comparePrerelease(parsedLeft.prerelease, parsedRight.prerelease);
24052
+ }
24053
+ function isAgentVersionSupported(reportedVersion, minimumSupportedVersion) {
24054
+ const comparison = compareAgentVersions(reportedVersion, minimumSupportedVersion);
24055
+ return comparison === null ? null : comparison >= 0;
24056
+ }
24057
+
23974
24058
  // src/agent-catalog/executable-discovery.ts
23975
24059
  import { isAbsolute as isAbsolute7, join as join13 } from "node:path";
23976
24060
 
@@ -24252,6 +24336,18 @@ async function discoverAgent(specification, context) {
24252
24336
  lastFailure = agentProbeFailure(specification, error62);
24253
24337
  continue;
24254
24338
  }
24339
+ const supportedVersion = isAgentVersionSupported(agentVersion, specification.minimumSupportedAgentVersion);
24340
+ if (supportedVersion === null) {
24341
+ lastFailure = new AgentProbeFailed(
24342
+ specification,
24343
+ "agent_probe_failed",
24344
+ "Agent reported an unrecognized version"
24345
+ );
24346
+ continue;
24347
+ }
24348
+ if (!supportedVersion) {
24349
+ continue;
24350
+ }
24255
24351
  const installedAgent = new AgentIntegrationDefinition(
24256
24352
  specification.id,
24257
24353
  specification.label,
@@ -26255,16 +26351,7 @@ var OpaqueDaemonReconnectTarget = class extends DaemonReconnectTarget {
26255
26351
  this.commandArgument = `--connection ${connectionId2}`;
26256
26352
  }
26257
26353
  };
26258
- var ChannelDaemonReconnectTarget = class extends DaemonReconnectTarget {
26259
- channelId;
26260
- commandArgument;
26261
- constructor(channelId) {
26262
- super();
26263
- this.channelId = channelId;
26264
- this.commandArgument = `--channel ${channelId}`;
26265
- }
26266
- };
26267
- function createDaemonConfig(connection, agents = [], installableAgents = [], localContext = new DaemonLocalContext(readStateDirectory(), process.env), reconnectTarget = new ChannelDaemonReconnectTarget(connection.channelId)) {
26354
+ function createDaemonConfig(connection, agents = [], installableAgents = [], localContext = new DaemonLocalContext(readStateDirectory(), process.env), reconnectTarget = null) {
26268
26355
  const daemonAgents = agents.map((agent) => withDaemonEnvironment(agent, localContext.environment));
26269
26356
  return {
26270
26357
  agents: daemonAgents,
@@ -26280,6 +26367,14 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
26280
26367
  };
26281
26368
  }
26282
26369
 
26370
+ // src/daemon-manager.ts
26371
+ import { spawn as spawn6 } from "node:child_process";
26372
+ import { createHash as createHash5, randomBytes } from "node:crypto";
26373
+ import { open as open6, readFile as readFile3, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
26374
+ import { createConnection, createServer } from "node:net";
26375
+ import { tmpdir } from "node:os";
26376
+ import { join as join18 } from "node:path";
26377
+
26283
26378
  // src/pairing/pair-local-machine.ts
26284
26379
  import { mkdir as mkdir5, realpath as realpath6, stat as stat5 } from "node:fs/promises";
26285
26380
  import { hostname as hostname3 } from "node:os";
@@ -26288,7 +26383,7 @@ import { fetch as fetch2 } from "undici";
26288
26383
 
26289
26384
  // src/storage/runtime-installation-store.ts
26290
26385
  import { createHash as createHash2, randomUUID } from "node:crypto";
26291
- import { mkdir as mkdir4, open as open4, rename as rename3, unlink, writeFile as writeFile3 } from "node:fs/promises";
26386
+ import { mkdir as mkdir4, open as open4, readdir as readdir2, rename as rename3, unlink, writeFile as writeFile3 } from "node:fs/promises";
26292
26387
  import { dirname as dirname3, join as join15, resolve as resolve4 } from "node:path";
26293
26388
  var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
26294
26389
  var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
@@ -26305,18 +26400,31 @@ var CHANNEL_INDEX_KEYS = [
26305
26400
  "version"
26306
26401
  ];
26307
26402
  var VERIFIED_CONNECTION_KEYS = [
26403
+ "activation",
26404
+ "appId",
26308
26405
  "applicationId",
26309
26406
  "channelId",
26310
26407
  "connectionId",
26311
26408
  "defaultWorkspace",
26312
26409
  "installationId",
26313
26410
  "kind",
26411
+ "pairingId",
26314
26412
  "relayOrigin",
26315
26413
  "runtimeCredential",
26316
26414
  "runtimeId",
26317
26415
  "version"
26318
26416
  ];
26417
+ var VERSION_THREE_VERIFIED_CONNECTION_KEYS = VERIFIED_CONNECTION_KEYS.filter(
26418
+ (key) => key !== "activation"
26419
+ );
26420
+ var VERSION_TWO_VERIFIED_CONNECTION_KEYS = VERSION_THREE_VERIFIED_CONNECTION_KEYS.filter(
26421
+ (key) => key !== "pairingId"
26422
+ );
26423
+ var LEGACY_VERIFIED_CONNECTION_KEYS = VERSION_TWO_VERIFIED_CONNECTION_KEYS.filter(
26424
+ (key) => key !== "appId"
26425
+ );
26319
26426
  var IMPORTED_LEGACY_CONNECTION_KEYS = [
26427
+ "activation",
26320
26428
  "applicationId",
26321
26429
  "channelId",
26322
26430
  "connectionId",
@@ -26327,13 +26435,9 @@ var IMPORTED_LEGACY_CONNECTION_KEYS = [
26327
26435
  "runtimeCredential",
26328
26436
  "version"
26329
26437
  ];
26330
- var CURRENT_CONNECTION_KEYS = [
26331
- "defaultWorkspace",
26332
- "channelId",
26333
- "relayOrigin",
26334
- "runtimeCredential"
26335
- ];
26336
- var LEGACY_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "daemonToken", "relayOrigin"];
26438
+ var VERSION_ONE_IMPORTED_LEGACY_CONNECTION_KEYS = IMPORTED_LEGACY_CONNECTION_KEYS.filter(
26439
+ (key) => key !== "activation"
26440
+ );
26337
26441
  var RuntimeInstallationStoreError = class extends Error {
26338
26442
  code;
26339
26443
  constructor(code, message, options = {}) {
@@ -26343,19 +26447,25 @@ var RuntimeInstallationStoreError = class extends Error {
26343
26447
  }
26344
26448
  };
26345
26449
  var StoredRuntimeConnection = class {
26450
+ activation;
26451
+ appId;
26346
26452
  applicationId;
26347
26453
  channelId;
26348
26454
  connectionId;
26349
26455
  defaultWorkspace;
26350
26456
  installationId;
26457
+ pairingId;
26351
26458
  relayOrigin;
26352
26459
  runtimeCredential;
26353
- constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
26460
+ constructor(activation, applicationId, appId, installationId2, connectionId2, channelId, defaultWorkspace, pairingId, relayOrigin, runtimeCredential2) {
26461
+ this.activation = activation;
26354
26462
  this.applicationId = applicationId;
26463
+ this.appId = appId;
26355
26464
  this.channelId = channelId;
26356
26465
  this.connectionId = connectionId2;
26357
26466
  this.defaultWorkspace = defaultWorkspace;
26358
26467
  this.installationId = installationId2;
26468
+ this.pairingId = pairingId;
26359
26469
  this.relayOrigin = relayOrigin;
26360
26470
  this.runtimeCredential = runtimeCredential2;
26361
26471
  }
@@ -26363,15 +26473,37 @@ var StoredRuntimeConnection = class {
26363
26473
  var VerifiedRuntimeConnection = class extends StoredRuntimeConnection {
26364
26474
  kind = "verified";
26365
26475
  runtimeId;
26366
- constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2, runtimeId) {
26367
- super(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2);
26476
+ constructor(activation, applicationId, appId, installationId2, connectionId2, channelId, defaultWorkspace, pairingId, relayOrigin, runtimeCredential2, runtimeId) {
26477
+ super(
26478
+ activation,
26479
+ applicationId,
26480
+ appId,
26481
+ installationId2,
26482
+ connectionId2,
26483
+ channelId,
26484
+ defaultWorkspace,
26485
+ pairingId,
26486
+ relayOrigin,
26487
+ runtimeCredential2
26488
+ );
26368
26489
  this.runtimeId = runtimeId;
26369
26490
  }
26370
26491
  };
26371
26492
  var ImportedLegacyRuntimeConnection = class extends StoredRuntimeConnection {
26372
26493
  kind = "legacy_imported";
26373
- constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
26374
- super(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2);
26494
+ constructor(activation, applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
26495
+ super(
26496
+ activation,
26497
+ applicationId,
26498
+ "unknown",
26499
+ installationId2,
26500
+ connectionId2,
26501
+ channelId,
26502
+ defaultWorkspace,
26503
+ "",
26504
+ relayOrigin,
26505
+ runtimeCredential2
26506
+ );
26375
26507
  }
26376
26508
  };
26377
26509
  function isRecord5(value) {
@@ -26390,6 +26522,12 @@ function validateApplicationId(value) {
26390
26522
  }
26391
26523
  return value;
26392
26524
  }
26525
+ function validateRemoteAppId(value) {
26526
+ if (!IDENTIFIER_PATTERN4.test(value)) {
26527
+ throw new RuntimeInstallationStoreError("invalid_app_id", "The remote App ID is invalid");
26528
+ }
26529
+ return value;
26530
+ }
26393
26531
  function validateConnectionId(value) {
26394
26532
  if (!CONNECTION_ID_PATTERN.test(value)) {
26395
26533
  throw new RuntimeInstallationStoreError("invalid_connection_id", "The local connection ID is invalid");
@@ -26469,46 +26607,61 @@ function decodeChannelIndex(value) {
26469
26607
  };
26470
26608
  }
26471
26609
  function decodeVerifiedConnection(value) {
26472
- if (!hasExactKeys(value, VERIFIED_CONNECTION_KEYS) || value["kind"] !== "verified" || value["version"] !== 1) {
26610
+ const current = hasExactKeys(value, VERIFIED_CONNECTION_KEYS) && value["version"] === 4;
26611
+ const versionThree = hasExactKeys(value, VERSION_THREE_VERIFIED_CONNECTION_KEYS) && value["version"] === 3;
26612
+ const versionTwo = hasExactKeys(value, VERSION_TWO_VERIFIED_CONNECTION_KEYS) && value["version"] === 2;
26613
+ const legacy = hasExactKeys(value, LEGACY_VERIFIED_CONNECTION_KEYS) && value["version"] === 1;
26614
+ if (!current && !versionThree && !versionTwo && !legacy || value["kind"] !== "verified") {
26473
26615
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
26474
26616
  }
26475
26617
  const applicationId = value["applicationId"];
26618
+ const activation = current ? value["activation"] : "active";
26619
+ const appId = typeof value["appId"] === "string" ? value["appId"] : "unknown";
26476
26620
  const channelId = value["channelId"];
26477
26621
  const connectionId2 = value["connectionId"];
26478
26622
  const defaultWorkspace = value["defaultWorkspace"];
26479
26623
  const storedInstallationId = value["installationId"];
26624
+ const pairingId = value["pairingId"];
26625
+ const savedPairingId = typeof pairingId === "string" ? pairingId : "";
26480
26626
  const relayOrigin = value["relayOrigin"];
26481
26627
  const runtimeCredential2 = value["runtimeCredential"];
26482
26628
  const runtimeId = value["runtimeId"];
26483
- if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string" || typeof runtimeId !== "string") {
26629
+ if (typeof applicationId !== "string" || activation !== "active" && activation !== "stopped" || (current || versionThree || versionTwo) && typeof value["appId"] !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || (current || versionThree) && typeof pairingId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string" || typeof runtimeId !== "string") {
26484
26630
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
26485
26631
  }
26486
26632
  return new VerifiedRuntimeConnection(
26633
+ activation,
26487
26634
  validateApplicationId(applicationId),
26635
+ validateRemoteAppId(appId),
26488
26636
  validateInstallationId(storedInstallationId),
26489
26637
  validateConnectionId(connectionId2),
26490
26638
  validateIdentifier(channelId, "invalid_connection"),
26491
26639
  defaultWorkspace,
26640
+ current || versionThree ? validateIdentifier(savedPairingId, "invalid_connection") : "",
26492
26641
  parseRelayOrigin(relayOrigin),
26493
26642
  validateRuntimeCredential(runtimeCredential2),
26494
26643
  validateIdentifier(runtimeId, "invalid_connection")
26495
26644
  );
26496
26645
  }
26497
26646
  function decodeImportedLegacyConnection(value) {
26498
- if (!hasExactKeys(value, IMPORTED_LEGACY_CONNECTION_KEYS) || value["kind"] !== "legacy_imported" || value["version"] !== 1) {
26647
+ const current = hasExactKeys(value, IMPORTED_LEGACY_CONNECTION_KEYS) && value["version"] === 2;
26648
+ const legacy = hasExactKeys(value, VERSION_ONE_IMPORTED_LEGACY_CONNECTION_KEYS) && value["version"] === 1;
26649
+ if (!current && !legacy || value["kind"] !== "legacy_imported" || value["version"] !== 1 && value["version"] !== 2) {
26499
26650
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
26500
26651
  }
26501
26652
  const applicationId = value["applicationId"];
26653
+ const activation = current ? value["activation"] : "active";
26502
26654
  const channelId = value["channelId"];
26503
26655
  const connectionId2 = value["connectionId"];
26504
26656
  const defaultWorkspace = value["defaultWorkspace"];
26505
26657
  const storedInstallationId = value["installationId"];
26506
26658
  const relayOrigin = value["relayOrigin"];
26507
26659
  const runtimeCredential2 = value["runtimeCredential"];
26508
- if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
26660
+ if (typeof applicationId !== "string" || activation !== "active" && activation !== "stopped" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
26509
26661
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
26510
26662
  }
26511
26663
  return new ImportedLegacyRuntimeConnection(
26664
+ activation,
26512
26665
  validateApplicationId(applicationId),
26513
26666
  validateInstallationId(storedInstallationId),
26514
26667
  validateConnectionId(connectionId2),
@@ -26530,24 +26683,6 @@ function decodeConnection(value) {
26530
26683
  }
26531
26684
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
26532
26685
  }
26533
- function decodeLegacyConnection(value, expectedChannelId) {
26534
- if (!isRecord5(value) || !hasExactKeys(value, CURRENT_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_CONNECTION_KEYS)) {
26535
- throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
26536
- }
26537
- const channelId = value["channelId"];
26538
- const defaultWorkspace = value["defaultWorkspace"];
26539
- const relayOrigin = value["relayOrigin"];
26540
- const runtimeCredential2 = value["runtimeCredential"] ?? value["daemonToken"];
26541
- if (typeof channelId !== "string" || channelId !== expectedChannelId || typeof defaultWorkspace !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
26542
- throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
26543
- }
26544
- return {
26545
- channelId: validateIdentifier(channelId, "invalid_connection"),
26546
- defaultWorkspace,
26547
- relayOrigin: parseRelayOrigin(relayOrigin),
26548
- runtimeCredential: validateRuntimeCredential(runtimeCredential2)
26549
- };
26550
- }
26551
26686
  async function readJsonFile(path2, signal, missingCode) {
26552
26687
  signal.throwIfAborted();
26553
26688
  let handle;
@@ -26678,23 +26813,16 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
26678
26813
  }
26679
26814
  return await this.readConnection(index2.connectionId, signal);
26680
26815
  };
26681
- migrateLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
26682
- try {
26683
- return await this.#readConnectionForChannel(channelId, signal);
26684
- } catch (cause) {
26685
- if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "connection_not_found") {
26686
- throw cause;
26687
- }
26688
- }
26689
- return await this.importLegacyConnection(legacyStateDirectory, channelId, signal);
26690
- };
26691
26816
  saveConnection = async (input2, signal) => {
26692
26817
  const stored = new VerifiedRuntimeConnection(
26818
+ "active",
26693
26819
  this.applicationId,
26820
+ validateRemoteAppId(input2.appId),
26694
26821
  this.installationId,
26695
26822
  connectionId(),
26696
26823
  validateIdentifier(input2.channelId, "invalid_connection"),
26697
26824
  input2.defaultWorkspace,
26825
+ input2.pairingId.length === 0 ? "" : validateIdentifier(input2.pairingId, "invalid_pairing_id"),
26698
26826
  parseRelayOrigin(input2.relayOrigin.toString()),
26699
26827
  validateRuntimeCredential(input2.runtimeCredential),
26700
26828
  validateIdentifier(input2.runtimeId, "invalid_connection")
@@ -26702,25 +26830,6 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
26702
26830
  await this.writeConnection(stored, signal);
26703
26831
  return stored;
26704
26832
  };
26705
- importLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
26706
- const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
26707
- const legacyPath = join15(resolve4(legacyStateDirectory), "connections", `${normalizedChannelId}.json`);
26708
- const legacy = decodeLegacyConnection(
26709
- await readJsonFile(legacyPath, signal, "connection_not_found"),
26710
- normalizedChannelId
26711
- );
26712
- const stored = new ImportedLegacyRuntimeConnection(
26713
- this.applicationId,
26714
- this.installationId,
26715
- connectionId(),
26716
- legacy.channelId,
26717
- legacy.defaultWorkspace,
26718
- legacy.relayOrigin,
26719
- legacy.runtimeCredential
26720
- );
26721
- await this.writeConnection(stored, signal);
26722
- return stored;
26723
- };
26724
26833
  writeConnection = async (stored, signal) => {
26725
26834
  signal.throwIfAborted();
26726
26835
  try {
@@ -26734,49 +26843,134 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
26734
26843
  throw cause;
26735
26844
  }
26736
26845
  }
26737
- const connectionPath = this.connectionPath(stored.connectionId);
26738
- if (stored instanceof VerifiedRuntimeConnection) {
26739
- await writeJsonAtomically(
26740
- connectionPath,
26846
+ await this.overwriteConnection(stored, signal);
26847
+ await writeJsonAtomically(
26848
+ this.channelIndexPath(stored.channelId),
26849
+ {
26850
+ applicationId: this.applicationId,
26851
+ channelId: stored.channelId,
26852
+ connectionId: stored.connectionId,
26853
+ installationId: this.installationId,
26854
+ version: 1
26855
+ },
26856
+ signal
26857
+ );
26858
+ };
26859
+ listConnections = async (signal) => {
26860
+ signal.throwIfAborted();
26861
+ let entries;
26862
+ try {
26863
+ entries = await readdir2(this.#connectionDirectory);
26864
+ } catch (cause) {
26865
+ if (isNodeError(cause, "ENOENT")) {
26866
+ return [];
26867
+ }
26868
+ throw new RuntimeInstallationStoreError(
26869
+ "connection_unavailable",
26870
+ "Saved Runtime connections cannot be listed",
26741
26871
  {
26742
- applicationId: stored.applicationId,
26743
- channelId: stored.channelId,
26744
- connectionId: stored.connectionId,
26745
- defaultWorkspace: stored.defaultWorkspace,
26746
- installationId: stored.installationId,
26747
- kind: stored.kind,
26748
- relayOrigin: stored.relayOrigin.toString(),
26749
- runtimeCredential: stored.runtimeCredential,
26750
- runtimeId: stored.runtimeId,
26751
- version: 1
26752
- },
26753
- signal
26872
+ cause
26873
+ }
26754
26874
  );
26755
- } else {
26875
+ }
26876
+ const connections = [];
26877
+ for (const entry of [...entries].sort()) {
26878
+ signal.throwIfAborted();
26879
+ const match = /^(mcn_[a-f0-9]{32})\.json$/.exec(entry);
26880
+ if (match?.[1] !== void 0) {
26881
+ connections.push(await this.readConnection(match[1], signal));
26882
+ }
26883
+ }
26884
+ return connections;
26885
+ };
26886
+ readConnectionForPairing = async (pairingId, signal) => {
26887
+ const normalizedPairingId = validateIdentifier(pairingId, "invalid_pairing_id");
26888
+ const connections = await this.listConnections(signal);
26889
+ return connections.find((connection) => connection.pairingId === normalizedPairingId) ?? null;
26890
+ };
26891
+ setConnectionActivation = async (connectionId2, activation, signal) => {
26892
+ const connection = await this.readConnection(connectionId2, signal);
26893
+ const updated = connection instanceof VerifiedRuntimeConnection ? new VerifiedRuntimeConnection(
26894
+ activation,
26895
+ connection.applicationId,
26896
+ connection.appId,
26897
+ connection.installationId,
26898
+ connection.connectionId,
26899
+ connection.channelId,
26900
+ connection.defaultWorkspace,
26901
+ connection.pairingId,
26902
+ connection.relayOrigin,
26903
+ connection.runtimeCredential,
26904
+ connection.runtimeId
26905
+ ) : new ImportedLegacyRuntimeConnection(
26906
+ activation,
26907
+ connection.applicationId,
26908
+ connection.installationId,
26909
+ connection.connectionId,
26910
+ connection.channelId,
26911
+ connection.defaultWorkspace,
26912
+ connection.relayOrigin,
26913
+ connection.runtimeCredential
26914
+ );
26915
+ await this.overwriteConnection(updated, signal);
26916
+ return updated;
26917
+ };
26918
+ removeConnection = async (connectionId2, signal) => {
26919
+ const connection = await this.readConnection(connectionId2, signal);
26920
+ signal.throwIfAborted();
26921
+ try {
26922
+ await unlink(this.connectionPath(connection.connectionId));
26923
+ signal.throwIfAborted();
26924
+ await unlink(this.channelIndexPath(connection.channelId));
26925
+ } catch (cause) {
26926
+ signal.throwIfAborted();
26927
+ if (isNodeError(cause, "ENOENT")) {
26928
+ return;
26929
+ }
26930
+ throw new RuntimeInstallationStoreError(
26931
+ "connection_unavailable",
26932
+ "The saved Runtime connection cannot be removed",
26933
+ { cause }
26934
+ );
26935
+ }
26936
+ };
26937
+ overwriteConnection = async (connection, signal) => {
26938
+ const connectionPath = this.connectionPath(connection.connectionId);
26939
+ if (connection instanceof VerifiedRuntimeConnection) {
26756
26940
  await writeJsonAtomically(
26757
26941
  connectionPath,
26758
26942
  {
26759
- applicationId: stored.applicationId,
26760
- channelId: stored.channelId,
26761
- connectionId: stored.connectionId,
26762
- defaultWorkspace: stored.defaultWorkspace,
26763
- installationId: stored.installationId,
26764
- kind: stored.kind,
26765
- relayOrigin: stored.relayOrigin.toString(),
26766
- runtimeCredential: stored.runtimeCredential,
26767
- version: 1
26943
+ activation: connection.activation,
26944
+ applicationId: connection.applicationId,
26945
+ appId: connection.appId,
26946
+ channelId: connection.channelId,
26947
+ connectionId: connection.connectionId,
26948
+ defaultWorkspace: connection.defaultWorkspace,
26949
+ installationId: connection.installationId,
26950
+ kind: connection.kind,
26951
+ pairingId: connection.pairingId,
26952
+ relayOrigin: connection.relayOrigin.toString(),
26953
+ runtimeCredential: connection.runtimeCredential,
26954
+ runtimeId: connection.runtimeId,
26955
+ version: 4
26768
26956
  },
26769
26957
  signal
26770
26958
  );
26959
+ return;
26771
26960
  }
26772
26961
  await writeJsonAtomically(
26773
- this.channelIndexPath(stored.channelId),
26962
+ connectionPath,
26774
26963
  {
26775
- applicationId: this.applicationId,
26776
- channelId: stored.channelId,
26777
- connectionId: stored.connectionId,
26778
- installationId: this.installationId,
26779
- version: 1
26964
+ activation: connection.activation,
26965
+ applicationId: connection.applicationId,
26966
+ channelId: connection.channelId,
26967
+ connectionId: connection.connectionId,
26968
+ defaultWorkspace: connection.defaultWorkspace,
26969
+ installationId: connection.installationId,
26970
+ kind: connection.kind,
26971
+ relayOrigin: connection.relayOrigin.toString(),
26972
+ runtimeCredential: connection.runtimeCredential,
26973
+ version: 2
26780
26974
  },
26781
26975
  signal
26782
26976
  );
@@ -26860,7 +27054,7 @@ function readSingleOption(arguments_, option) {
26860
27054
  function assertKnownArguments(arguments_) {
26861
27055
  for (let index2 = 0; index2 < arguments_.length; index2 += 2) {
26862
27056
  const option = arguments_[index2];
26863
- if (option !== "--url" && option !== "--code" && option !== "--pairing" && option !== "--workspace") {
27057
+ if (option !== "--url" && option !== "--code" && option !== "--pairing" && option !== "--workspace" && option !== "--app-id") {
26864
27058
  throw new PairingClientError("invalid_arguments", `Unknown pairing option: ${option ?? "missing option"}`);
26865
27059
  }
26866
27060
  }
@@ -26899,6 +27093,7 @@ function parsePairingCode(value) {
26899
27093
  function parsePairCommand(arguments_, defaultWorkspace) {
26900
27094
  assertKnownArguments(arguments_);
26901
27095
  return {
27096
+ appId: arguments_.includes("--app-id") ? validatePairingId(readSingleOption(arguments_, "--app-id")) : "standalone",
26902
27097
  code: parsePairingCode(readSingleOption(arguments_, "--code")),
26903
27098
  pairingId: arguments_.includes("--pairing") ? validatePairingId(readSingleOption(arguments_, "--pairing")) : "",
26904
27099
  relayOrigin: parseRelayOrigin2(readSingleOption(arguments_, "--url")),
@@ -26911,48 +27106,15 @@ function validatePairingId(value) {
26911
27106
  }
26912
27107
  return value;
26913
27108
  }
26914
- var ResumeCommandTarget = class {
26915
- };
26916
- var ConnectionResumeCommandTarget = class extends ResumeCommandTarget {
26917
- connectionId;
26918
- constructor(connectionId2) {
26919
- super();
26920
- this.connectionId = connectionId2;
26921
- }
26922
- resume = async (installation, signal, environment) => await resumeMobiusRuntime(installation, this.connectionId, signal, environment);
26923
- };
26924
- var LegacyChannelResumeCommandTarget = class extends ResumeCommandTarget {
26925
- channelId;
26926
- constructor(channelId) {
26927
- super();
26928
- this.channelId = channelId;
26929
- }
26930
- resume = async (installation, signal, environment) => await resumeLegacyChannel(installation, this.channelId, signal, environment);
26931
- };
26932
- function parseResumeArgument(arguments_) {
26933
- if (arguments_.length !== 2) {
26934
- throw new PairingClientError(
26935
- "invalid_arguments",
26936
- "Usage: mobius start --connection <connection-id> or mobius start --channel <legacy-channel-id>"
26937
- );
27109
+ function parseResumeConnectionId(arguments_) {
27110
+ if (arguments_.length !== 2 || arguments_[0] !== "--connection") {
27111
+ throw new PairingClientError("invalid_arguments", "Usage: mobius start --connection <connection-id>");
26938
27112
  }
26939
27113
  const value = arguments_[1] ?? "";
26940
- if (arguments_[0] === "--connection") {
26941
- if (!/^mcn_[a-f0-9]{32}$/.test(value)) {
26942
- throw new PairingClientError("invalid_connection_id", "The saved Runtime connection ID is invalid");
26943
- }
26944
- return new ConnectionResumeCommandTarget(value);
26945
- }
26946
- if (arguments_[0] === "--channel") {
26947
- if (!IDENTIFIER_PATTERN5.test(value)) {
26948
- throw new PairingClientError("invalid_channel_id", "The saved channel ID is invalid");
26949
- }
26950
- return new LegacyChannelResumeCommandTarget(value);
27114
+ if (!/^mcn_[a-f0-9]{32}$/.test(value)) {
27115
+ throw new PairingClientError("invalid_connection_id", "The saved Runtime connection ID is invalid");
26951
27116
  }
26952
- throw new PairingClientError(
26953
- "invalid_arguments",
26954
- "Usage: mobius start --connection <connection-id> or mobius start --channel <legacy-channel-id>"
26955
- );
27117
+ return value;
26956
27118
  }
26957
27119
  async function resolveDefaultWorkspace(path2) {
26958
27120
  const requestedWorkspace = resolve5(path2);
@@ -27088,8 +27250,10 @@ async function pairRuntime(installation, options, signal, environment) {
27088
27250
  const claim2 = await claimPairing(options, defaultWorkspace, agents, inventory.installable, signal);
27089
27251
  const connection = await installation.saveConnection(
27090
27252
  {
27253
+ appId: options.appId,
27091
27254
  channelId: claim2.channelId,
27092
27255
  defaultWorkspace,
27256
+ pairingId: options.pairingId,
27093
27257
  relayOrigin: options.relayOrigin,
27094
27258
  runtimeCredential: claim2.runtimeCredential,
27095
27259
  runtimeId: claim2.runtimeId
@@ -27112,10 +27276,6 @@ async function resumeMobiusRuntime(installation, connectionId2, signal, environm
27112
27276
  const connection = await installation.readConnection(connectionId2, signal);
27113
27277
  return await resumeRuntimeConnection(installation, connection, signal, environment);
27114
27278
  }
27115
- async function resumeLegacyChannel(installation, channelId, signal, environment) {
27116
- const connection = await installation.migrateLegacyConnection(readStateDirectory(environment), channelId, signal);
27117
- return await resumeRuntimeConnection(installation, connection, signal, environment);
27118
- }
27119
27279
  async function openMobiusCliInstallation(signal, environment) {
27120
27280
  return await openRuntimeInstallationStore(
27121
27281
  {
@@ -27129,9 +27289,16 @@ async function pairLocalMachine(arguments_, signal = new AbortController().signa
27129
27289
  const requested = parsePairCommand(arguments_, "");
27130
27290
  const installation = await openMobiusCliInstallation(signal, process.env);
27131
27291
  const localContext = new DaemonLocalContext(installation.stateDirectory, process.env);
27292
+ if (requested.pairingId.length > 0) {
27293
+ const existing = await installation.readConnectionForPairing(requested.pairingId, signal);
27294
+ if (existing !== null) {
27295
+ return await resumeRuntimeConnection(installation, existing, signal, process.env);
27296
+ }
27297
+ }
27132
27298
  return await pairRuntime(
27133
27299
  installation,
27134
27300
  {
27301
+ appId: requested.appId,
27135
27302
  code: requested.code,
27136
27303
  pairingId: requested.pairingId,
27137
27304
  relayOrigin: requested.relayOrigin,
@@ -27142,9 +27309,9 @@ async function pairLocalMachine(arguments_, signal = new AbortController().signa
27142
27309
  );
27143
27310
  }
27144
27311
  async function resumeLocalMachine(arguments_, signal = new AbortController().signal) {
27145
- const target = parseResumeArgument(arguments_);
27312
+ const connectionId2 = parseResumeConnectionId(arguments_);
27146
27313
  const installation = await openMobiusCliInstallation(signal, process.env);
27147
- return await target.resume(installation, signal, process.env);
27314
+ return await resumeMobiusRuntime(installation, connectionId2, signal, process.env);
27148
27315
  }
27149
27316
 
27150
27317
  // src/audit/audit-store.ts
@@ -30663,10 +30830,10 @@ function resolveAll(constructs2, events, context) {
30663
30830
  const called = [];
30664
30831
  let index2 = -1;
30665
30832
  while (++index2 < constructs2.length) {
30666
- const resolve7 = constructs2[index2].resolveAll;
30667
- if (resolve7 && !called.includes(resolve7)) {
30668
- events = resolve7(events, context);
30669
- called.push(resolve7);
30833
+ const resolve8 = constructs2[index2].resolveAll;
30834
+ if (resolve8 && !called.includes(resolve8)) {
30835
+ events = resolve8(events, context);
30836
+ called.push(resolve8);
30670
30837
  }
30671
30838
  }
30672
30839
  return events;
@@ -30680,7 +30847,7 @@ var attention = {
30680
30847
  };
30681
30848
  function resolveAllAttention(events, context) {
30682
30849
  let index2 = -1;
30683
- let open6;
30850
+ let open8;
30684
30851
  let group;
30685
30852
  let text3;
30686
30853
  let openingSequence;
@@ -30690,16 +30857,16 @@ function resolveAllAttention(events, context) {
30690
30857
  let offset;
30691
30858
  while (++index2 < events.length) {
30692
30859
  if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
30693
- open6 = index2;
30694
- while (open6--) {
30695
- if (events[open6][0] === "exit" && events[open6][1].type === "attentionSequence" && events[open6][1]._open && // If the markers are the same:
30696
- context.sliceSerialize(events[open6][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
30697
- if ((events[open6][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open6][1].end.offset - events[open6][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
30860
+ open8 = index2;
30861
+ while (open8--) {
30862
+ if (events[open8][0] === "exit" && events[open8][1].type === "attentionSequence" && events[open8][1]._open && // If the markers are the same:
30863
+ context.sliceSerialize(events[open8][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
30864
+ if ((events[open8][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open8][1].end.offset - events[open8][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
30698
30865
  continue;
30699
30866
  }
30700
- use = events[open6][1].end.offset - events[open6][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
30867
+ use = events[open8][1].end.offset - events[open8][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
30701
30868
  const start = {
30702
- ...events[open6][1].end
30869
+ ...events[open8][1].end
30703
30870
  };
30704
30871
  const end = {
30705
30872
  ...events[index2][1].start
@@ -30710,7 +30877,7 @@ function resolveAllAttention(events, context) {
30710
30877
  type: use > 1 ? "strongSequence" : "emphasisSequence",
30711
30878
  start,
30712
30879
  end: {
30713
- ...events[open6][1].end
30880
+ ...events[open8][1].end
30714
30881
  }
30715
30882
  };
30716
30883
  closingSequence = {
@@ -30723,7 +30890,7 @@ function resolveAllAttention(events, context) {
30723
30890
  text3 = {
30724
30891
  type: use > 1 ? "strongText" : "emphasisText",
30725
30892
  start: {
30726
- ...events[open6][1].end
30893
+ ...events[open8][1].end
30727
30894
  },
30728
30895
  end: {
30729
30896
  ...events[index2][1].start
@@ -30738,18 +30905,18 @@ function resolveAllAttention(events, context) {
30738
30905
  ...closingSequence.end
30739
30906
  }
30740
30907
  };
30741
- events[open6][1].end = {
30908
+ events[open8][1].end = {
30742
30909
  ...openingSequence.start
30743
30910
  };
30744
30911
  events[index2][1].start = {
30745
30912
  ...closingSequence.end
30746
30913
  };
30747
30914
  nextEvents = [];
30748
- if (events[open6][1].end.offset - events[open6][1].start.offset) {
30749
- nextEvents = push(nextEvents, [["enter", events[open6][1], context], ["exit", events[open6][1], context]]);
30915
+ if (events[open8][1].end.offset - events[open8][1].start.offset) {
30916
+ nextEvents = push(nextEvents, [["enter", events[open8][1], context], ["exit", events[open8][1], context]]);
30750
30917
  }
30751
30918
  nextEvents = push(nextEvents, [["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text3, context]]);
30752
- nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open6 + 1, index2), context));
30919
+ nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open8 + 1, index2), context));
30753
30920
  nextEvents = push(nextEvents, [["exit", text3, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context]]);
30754
30921
  if (events[index2][1].end.offset - events[index2][1].start.offset) {
30755
30922
  offset = 2;
@@ -30757,8 +30924,8 @@ function resolveAllAttention(events, context) {
30757
30924
  } else {
30758
30925
  offset = 0;
30759
30926
  }
30760
- splice(events, open6 - 1, index2 - open6 + 3, nextEvents);
30761
- index2 = open6 + nextEvents.length - offset - 2;
30927
+ splice(events, open8 - 1, index2 - open8 + 3, nextEvents);
30928
+ index2 = open8 + nextEvents.length - offset - 2;
30762
30929
  break;
30763
30930
  }
30764
30931
  }
@@ -30790,10 +30957,10 @@ function tokenizeAttention(effects, ok2) {
30790
30957
  }
30791
30958
  const token = effects.exit("attentionSequence");
30792
30959
  const after = classifyCharacter(code);
30793
- const open6 = !after || after === 2 && before || attentionMarkers2.includes(code);
30960
+ const open8 = !after || after === 2 && before || attentionMarkers2.includes(code);
30794
30961
  const close = !before || before === 2 && after || attentionMarkers2.includes(previous2);
30795
- token._open = Boolean(marker === 42 ? open6 : open6 && (before || !close));
30796
- token._close = Boolean(marker === 42 ? close : close && (after || !open6));
30962
+ token._open = Boolean(marker === 42 ? open8 : open8 && (before || !close));
30963
+ token._close = Boolean(marker === 42 ? close : close && (after || !open8));
30797
30964
  return ok2(code);
30798
30965
  }
30799
30966
  }
@@ -30817,9 +30984,9 @@ function tokenizeAutolink(effects, ok2, nok) {
30817
30984
  effects.consume(code);
30818
30985
  effects.exit("autolinkMarker");
30819
30986
  effects.enter("autolinkProtocol");
30820
- return open6;
30987
+ return open8;
30821
30988
  }
30822
- function open6(code) {
30989
+ function open8(code) {
30823
30990
  if (asciiAlpha(code)) {
30824
30991
  effects.consume(code);
30825
30992
  return schemeOrEmailAtext;
@@ -31019,9 +31186,9 @@ function tokenizeCharacterReference(effects, ok2, nok) {
31019
31186
  effects.enter("characterReferenceMarker");
31020
31187
  effects.consume(code);
31021
31188
  effects.exit("characterReferenceMarker");
31022
- return open6;
31189
+ return open8;
31023
31190
  }
31024
- function open6(code) {
31191
+ function open8(code) {
31025
31192
  if (code === 35) {
31026
31193
  effects.enter("characterReferenceMarkerNumeric");
31027
31194
  effects.consume(code);
@@ -32390,9 +32557,9 @@ function tokenizeHtmlFlow(effects, ok2, nok) {
32390
32557
  effects.enter("htmlFlow");
32391
32558
  effects.enter("htmlFlowData");
32392
32559
  effects.consume(code);
32393
- return open6;
32560
+ return open8;
32394
32561
  }
32395
- function open6(code) {
32562
+ function open8(code) {
32396
32563
  if (code === 33) {
32397
32564
  effects.consume(code);
32398
32565
  return declarationOpen;
@@ -32740,9 +32907,9 @@ function tokenizeHtmlText(effects, ok2, nok) {
32740
32907
  effects.enter("htmlText");
32741
32908
  effects.enter("htmlTextData");
32742
32909
  effects.consume(code);
32743
- return open6;
32910
+ return open8;
32744
32911
  }
32745
- function open6(code) {
32912
+ function open8(code) {
32746
32913
  if (code === 33) {
32747
32914
  effects.consume(code);
32748
32915
  return declarationOpen;
@@ -33068,12 +33235,12 @@ function resolveToLabelEnd(events, context) {
33068
33235
  let index2 = events.length;
33069
33236
  let offset = 0;
33070
33237
  let token;
33071
- let open6;
33238
+ let open8;
33072
33239
  let close;
33073
33240
  let media;
33074
33241
  while (index2--) {
33075
33242
  token = events[index2][1];
33076
- if (open6) {
33243
+ if (open8) {
33077
33244
  if (token.type === "link" || token.type === "labelLink" && token._inactive) {
33078
33245
  break;
33079
33246
  }
@@ -33082,7 +33249,7 @@ function resolveToLabelEnd(events, context) {
33082
33249
  }
33083
33250
  } else if (close) {
33084
33251
  if (events[index2][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced) {
33085
- open6 = index2;
33252
+ open8 = index2;
33086
33253
  if (token.type !== "labelLink") {
33087
33254
  offset = 2;
33088
33255
  break;
@@ -33093,9 +33260,9 @@ function resolveToLabelEnd(events, context) {
33093
33260
  }
33094
33261
  }
33095
33262
  const group = {
33096
- type: events[open6][1].type === "labelLink" ? "link" : "image",
33263
+ type: events[open8][1].type === "labelLink" ? "link" : "image",
33097
33264
  start: {
33098
- ...events[open6][1].start
33265
+ ...events[open8][1].start
33099
33266
  },
33100
33267
  end: {
33101
33268
  ...events[events.length - 1][1].end
@@ -33104,7 +33271,7 @@ function resolveToLabelEnd(events, context) {
33104
33271
  const label = {
33105
33272
  type: "label",
33106
33273
  start: {
33107
- ...events[open6][1].start
33274
+ ...events[open8][1].start
33108
33275
  },
33109
33276
  end: {
33110
33277
  ...events[close][1].end
@@ -33113,20 +33280,20 @@ function resolveToLabelEnd(events, context) {
33113
33280
  const text3 = {
33114
33281
  type: "labelText",
33115
33282
  start: {
33116
- ...events[open6 + offset + 2][1].end
33283
+ ...events[open8 + offset + 2][1].end
33117
33284
  },
33118
33285
  end: {
33119
33286
  ...events[close - 2][1].start
33120
33287
  }
33121
33288
  };
33122
33289
  media = [["enter", group, context], ["enter", label, context]];
33123
- media = push(media, events.slice(open6 + 1, open6 + offset + 3));
33290
+ media = push(media, events.slice(open8 + 1, open8 + offset + 3));
33124
33291
  media = push(media, [["enter", text3, context]]);
33125
- media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open6 + offset + 4, close - 3), context));
33292
+ media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open8 + offset + 4, close - 3), context));
33126
33293
  media = push(media, [["exit", text3, context], events[close - 2], events[close - 1], ["exit", label, context]]);
33127
33294
  media = push(media, events.slice(close + 1));
33128
33295
  media = push(media, [["exit", group, context]]);
33129
- splice(events, open6, events.length, media);
33296
+ splice(events, open8, events.length, media);
33130
33297
  return events;
33131
33298
  }
33132
33299
  function tokenizeLabelEnd(effects, ok2, nok) {
@@ -33271,9 +33438,9 @@ function tokenizeLabelStartImage(effects, ok2, nok) {
33271
33438
  effects.enter("labelImageMarker");
33272
33439
  effects.consume(code);
33273
33440
  effects.exit("labelImageMarker");
33274
- return open6;
33441
+ return open8;
33275
33442
  }
33276
- function open6(code) {
33443
+ function open8(code) {
33277
33444
  if (code === 91) {
33278
33445
  effects.enter("labelMarker");
33279
33446
  effects.consume(code);
@@ -34577,8 +34744,8 @@ function compiler(options) {
34577
34744
  return length;
34578
34745
  }
34579
34746
  function opener(create, and) {
34580
- return open6;
34581
- function open6(token) {
34747
+ return open8;
34748
+ function open8(token) {
34582
34749
  enter.call(this, create(token), token);
34583
34750
  if (and) and.call(this, token);
34584
34751
  }
@@ -34610,18 +34777,18 @@ function compiler(options) {
34610
34777
  }
34611
34778
  function exit2(token, onExitError) {
34612
34779
  const node3 = this.stack.pop();
34613
- const open6 = this.tokenStack.pop();
34614
- if (!open6) {
34780
+ const open8 = this.tokenStack.pop();
34781
+ if (!open8) {
34615
34782
  throw new Error("Cannot close `" + token.type + "` (" + stringifyPosition({
34616
34783
  start: token.start,
34617
34784
  end: token.end
34618
34785
  }) + "): it\u2019s not open");
34619
- } else if (open6[0].type !== token.type) {
34786
+ } else if (open8[0].type !== token.type) {
34620
34787
  if (onExitError) {
34621
- onExitError.call(this, token, open6[0]);
34788
+ onExitError.call(this, token, open8[0]);
34622
34789
  } else {
34623
- const handler = open6[1] || defaultOnError;
34624
- handler.call(this, token, open6[0]);
34790
+ const handler = open8[1] || defaultOnError;
34791
+ handler.call(this, token, open8[0]);
34625
34792
  }
34626
34793
  }
34627
34794
  node3.position.end = point2(token.end);
@@ -35296,7 +35463,6 @@ var nativeSessionPageSchema = external_exports.object({
35296
35463
 
35297
35464
  // src/acp/session-config/session-config-protocol.ts
35298
35465
  import { methods as methods7 } from "@agentclientprotocol/sdk";
35299
- var AGENT_DEFAULT_REASONING_EFFORT = "agent_default";
35300
35466
  var MAXIMUM_CONFIG_OPTIONS = 100;
35301
35467
  var SessionConfigProtocolError = class extends Error {
35302
35468
  code = "invalid_session_configuration_response";
@@ -35494,207 +35660,9 @@ var StandardSessionConfigProtocol = class {
35494
35660
  };
35495
35661
  var standardSessionConfigProtocol = new StandardSessionConfigProtocol();
35496
35662
 
35497
- // src/acp/session-config/grok-build-session-config.ts
35498
- var LEGACY_MODEL_CONFIG_ID = "grok_build_legacy_model";
35499
- var LEGACY_REASONING_EFFORT_CONFIG_ID = "grok_build_legacy_reasoning_effort";
35500
- function legacyOptions(response) {
35501
- if (!isRecord8(response)) {
35502
- return [];
35503
- }
35504
- const metadata = response["_meta"];
35505
- if (!isRecord8(metadata)) {
35506
- return [];
35507
- }
35508
- const sessionConfig = metadata["x.ai/sessionConfig"];
35509
- if (!isRecord8(sessionConfig) || !Array.isArray(sessionConfig["options"])) {
35510
- return [];
35511
- }
35512
- return sessionConfig["options"].slice(0, 500).filter(isRecord8);
35513
- }
35514
- function legacyValue(option) {
35515
- const value = readString2(option["id"]);
35516
- return {
35517
- description: readString2(option["description"]).slice(0, 500),
35518
- groupId: "",
35519
- groupName: "",
35520
- name: readString2(option["label"], value).slice(0, 255),
35521
- value: value.slice(0, 500)
35522
- };
35523
- }
35524
- function modelsRecord(response) {
35525
- if (!isRecord8(response) || !isRecord8(response["models"])) {
35526
- return {};
35527
- }
35528
- return response["models"];
35529
- }
35530
- function legacyModelOptions(response) {
35531
- const options = legacyOptions(response);
35532
- const models = modelsRecord(response);
35533
- const values = [];
35534
- for (const option of options) {
35535
- if (option["category"] === "model") {
35536
- const value = legacyValue(option);
35537
- if (value.value.length > 0 && !values.some((existing) => existing.value === value.value)) {
35538
- values.push(value);
35539
- }
35540
- }
35541
- }
35542
- if (values.length === 0 && Array.isArray(models["availableModels"])) {
35543
- for (const model of models["availableModels"]) {
35544
- if (!isRecord8(model)) {
35545
- continue;
35546
- }
35547
- const value = readString2(model["modelId"]).slice(0, 500);
35548
- if (value.length === 0) {
35549
- continue;
35550
- }
35551
- if (!values.some((existing) => existing.value === value)) {
35552
- values.push({
35553
- description: "",
35554
- groupId: "",
35555
- groupName: "",
35556
- name: readString2(model["name"], value).slice(0, 255),
35557
- value
35558
- });
35559
- }
35560
- }
35561
- }
35562
- const selected = options.find((option) => option["category"] === "model" && option["selected"] === true);
35563
- const currentValue = readString2(
35564
- models["currentModelId"],
35565
- selected === void 0 ? "" : readString2(selected["id"])
35566
- ).slice(0, 500);
35567
- if (values.length === 0 || !values.some((value) => value.value === currentValue)) {
35568
- return [];
35569
- }
35570
- const result = {
35571
- booleanValue: false,
35572
- category: "model",
35573
- currentValue,
35574
- description: "Model used by Grok Build",
35575
- id: LEGACY_MODEL_CONFIG_ID,
35576
- name: "Model",
35577
- type: "select",
35578
- values: values.slice(0, 500)
35579
- };
35580
- return [result];
35581
- }
35582
- function legacyReasoningEffortOptions(response) {
35583
- const options = legacyOptions(response);
35584
- const values = [];
35585
- for (const option of options) {
35586
- if (option["category"] !== "mode") {
35587
- continue;
35588
- }
35589
- const value = legacyValue(option);
35590
- if (value.value.length > 0 && !values.some((existing) => existing.value === value.value)) {
35591
- values.push(value);
35592
- }
35593
- }
35594
- if (values.length === 0) {
35595
- return [];
35596
- }
35597
- const selected = options.find((option) => option["category"] === "mode" && option["selected"] === true);
35598
- if (selected === void 0) {
35599
- values.unshift({
35600
- description: "Use the selected model's default reasoning effort",
35601
- groupId: "",
35602
- groupName: "",
35603
- name: "Agent default",
35604
- value: AGENT_DEFAULT_REASONING_EFFORT
35605
- });
35606
- }
35607
- const currentValue = selected === void 0 ? AGENT_DEFAULT_REASONING_EFFORT : readString2(selected["id"], AGENT_DEFAULT_REASONING_EFFORT);
35608
- if (!values.some((value) => value.value === currentValue)) {
35609
- return [];
35610
- }
35611
- const result = {
35612
- booleanValue: false,
35613
- category: "thought_level",
35614
- currentValue,
35615
- description: "Reasoning effort used by Grok Build",
35616
- id: LEGACY_REASONING_EFFORT_CONFIG_ID,
35617
- name: "Reasoning effort",
35618
- type: "select",
35619
- values: values.slice(0, 500)
35620
- };
35621
- return [result];
35622
- }
35623
- function normalizeGrokLifecycle(response) {
35624
- const lifecycle = isRecord8(response) ? response : {};
35625
- const standard = normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]);
35626
- const normalized = [...standard];
35627
- if (!normalized.some((option) => option.category === "model")) {
35628
- normalized.push(...legacyModelOptions(response));
35629
- }
35630
- if (!normalized.some((option) => option.category === "thought_level")) {
35631
- const efforts = legacyReasoningEffortOptions(response);
35632
- if (efforts.length > 0) {
35633
- const modelIndex = normalized.findIndex((option) => option.category === "model");
35634
- normalized.splice(modelIndex < 0 ? normalized.length : modelIndex + 1, 0, ...efforts);
35635
- }
35636
- }
35637
- return normalized.slice(0, 100);
35638
- }
35639
- function updateCurrentValue2(current, category, value) {
35640
- return current.map((option) => option.category === category ? { ...option, currentValue: value } : option);
35641
- }
35642
- function validateGrokResponse(response, modelId) {
35643
- if (!isRecord8(response) || !isRecord8(response["_meta"])) {
35644
- throw new SessionConfigProtocolError("Grok Build returned an invalid session configuration response");
35645
- }
35646
- const model = response["_meta"]["model"];
35647
- const appliedModel = isRecord8(model) ? model["Ok"] : model;
35648
- if (appliedModel !== modelId) {
35649
- throw new SessionConfigProtocolError("Grok Build returned an invalid session configuration response");
35650
- }
35651
- }
35652
- var GrokBuildSessionConfigProtocol = class {
35653
- configure = async (current, change, nativeSessionId, transport) => {
35654
- const existing = current.find((option) => option.id === change.configId);
35655
- if (existing === void 0 || existing.id !== LEGACY_MODEL_CONFIG_ID && existing.id !== LEGACY_REASONING_EFFORT_CONFIG_ID) {
35656
- return await standardSessionConfigProtocol.configure(current, change, nativeSessionId, transport);
35657
- }
35658
- const model = current.find((option) => option.category === "model");
35659
- if (model === void 0) {
35660
- return current;
35661
- }
35662
- if (existing.category === "thought_level" && change.value === AGENT_DEFAULT_REASONING_EFFORT) {
35663
- return current;
35664
- }
35665
- const modelId = existing.category === "model" ? change.value : model.currentValue;
35666
- const params = {
35667
- modelId,
35668
- sessionId: nativeSessionId
35669
- };
35670
- if (existing.category === "thought_level") {
35671
- params["_meta"] = {
35672
- reasoningEffort: change.value
35673
- };
35674
- }
35675
- const response = await transport.request(
35676
- "session/set_model",
35677
- params,
35678
- existing.category === "model" ? "Grok Build exited while setting the session model" : "Grok Build exited while setting reasoning effort",
35679
- change.signal
35680
- );
35681
- validateGrokResponse(response, modelId);
35682
- const updated = updateCurrentValue2(current, existing.category, change.value);
35683
- return existing.category === "thought_level" ? updated.map(
35684
- (option) => option.category === "thought_level" ? {
35685
- ...option,
35686
- values: option.values.filter((value) => value.value !== AGENT_DEFAULT_REASONING_EFFORT)
35687
- } : option
35688
- ) : updated;
35689
- };
35690
- normalizeLifecycle = (response) => normalizeGrokLifecycle(response);
35691
- normalizeUpdate = (current, value) => standardSessionConfigProtocol.normalizeUpdate(current, value);
35692
- };
35693
- var grokBuildSessionConfigProtocol = new GrokBuildSessionConfigProtocol();
35694
-
35695
35663
  // src/acp/session-config/session-config-registry.ts
35696
- function sessionConfigProtocolForAgent(agentId) {
35697
- return agentId === "grok-build" ? grokBuildSessionConfigProtocol : standardSessionConfigProtocol;
35664
+ function sessionConfigProtocolForAgent(_agentId) {
35665
+ return standardSessionConfigProtocol;
35698
35666
  }
35699
35667
 
35700
35668
  // src/acp/session-history.ts
@@ -36305,7 +36273,7 @@ function createWritableAcpStream(output2) {
36305
36273
  if (outputFailure !== void 0) {
36306
36274
  return Promise.reject(outputFailure);
36307
36275
  }
36308
- return new Promise((resolve7, reject) => {
36276
+ return new Promise((resolve8, reject) => {
36309
36277
  pendingWriteFailures.add(reject);
36310
36278
  output2.write(chunk, (error62) => {
36311
36279
  pendingWriteFailures.delete(reject);
@@ -36318,7 +36286,7 @@ function createWritableAcpStream(output2) {
36318
36286
  reject(outputFailure);
36319
36287
  return;
36320
36288
  }
36321
- resolve7();
36289
+ resolve8();
36322
36290
  });
36323
36291
  });
36324
36292
  }
@@ -36735,12 +36703,12 @@ var AcpProcessSession = class _AcpProcessSession {
36735
36703
  stderr.on("data", (chunk) => {
36736
36704
  process.stderr.write(`[${agent.id}-acp] ${chunk}`);
36737
36705
  });
36738
- this.#termination = new Promise((resolve7) => {
36706
+ this.#termination = new Promise((resolve8) => {
36739
36707
  child.once("error", (cause) => {
36740
- resolve7({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
36708
+ resolve8({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
36741
36709
  });
36742
36710
  child.once("exit", (code, signal) => {
36743
- resolve7({
36711
+ resolve8({
36744
36712
  kind: "failed",
36745
36713
  error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } })
36746
36714
  });
@@ -39858,7 +39826,7 @@ var LocalAuthorizationError = class extends Error {
39858
39826
  };
39859
39827
 
39860
39828
  // src/authorization/workspace-directory.ts
39861
- import { readdir as readdir2, realpath as realpath9, stat as stat8 } from "node:fs/promises";
39829
+ import { readdir as readdir3, realpath as realpath9, stat as stat8 } from "node:fs/promises";
39862
39830
  import { homedir as homedir2 } from "node:os";
39863
39831
  import { basename as basename5, dirname as dirname6, isAbsolute as isAbsolute10, join as join16, normalize as normalize4, relative as relative4 } from "node:path";
39864
39832
  var WorkspaceDirectoryListing = class {
@@ -39963,7 +39931,7 @@ var WorkspaceDirectoryService = class {
39963
39931
  list = async (bindingId, id, signal) => {
39964
39932
  const target = await this.resolve(bindingId, id, signal);
39965
39933
  try {
39966
- const children = await readdir2(target, { withFileTypes: true });
39934
+ const children = await readdir3(target, { withFileTypes: true });
39967
39935
  signal.throwIfAborted();
39968
39936
  const entries = [];
39969
39937
  for (const child of children) {
@@ -41212,7 +41180,7 @@ var RelayConnectionError = class extends Error {
41212
41180
  };
41213
41181
  function connectRelay(url2, signal) {
41214
41182
  signal.throwIfAborted();
41215
- return new Promise((resolve7, reject) => {
41183
+ return new Promise((resolve8, reject) => {
41216
41184
  const endpoint = new URL(url2);
41217
41185
  const headers = runtimeAuthorization(endpoint);
41218
41186
  endpoint.searchParams.delete("token");
@@ -41279,7 +41247,7 @@ function connectRelay(url2, signal) {
41279
41247
  }
41280
41248
  finished = true;
41281
41249
  cleanup();
41282
- resolve7(socket);
41250
+ resolve8(socket);
41283
41251
  };
41284
41252
  function onTimeout() {
41285
41253
  fail(
@@ -41698,71 +41666,7 @@ var SessionEventOutbox = class {
41698
41666
  received_at INTEGER NOT NULL
41699
41667
  ) STRICT;
41700
41668
  `);
41701
- const deadLetterTable = this.#database.prepare(
41702
- `SELECT sql FROM sqlite_master
41703
- WHERE type = 'table' AND name = 'relay_session_event_dead_letters'`
41704
- ).get();
41705
- const deadLetterSql = typeof deadLetterTable === "object" && deadLetterTable !== null ? Reflect.get(deadLetterTable, "sql") : void 0;
41706
- if (typeof deadLetterSql !== "string" || !deadLetterSql.includes("'session_rejected'")) {
41707
- this.#database.exec(`
41708
- BEGIN IMMEDIATE;
41709
- ALTER TABLE relay_session_event_dead_letters
41710
- RENAME TO relay_session_event_dead_letters_legacy;
41711
- CREATE TABLE relay_session_event_dead_letters (
41712
- ordinal INTEGER PRIMARY KEY,
41713
- event_id TEXT NOT NULL UNIQUE,
41714
- session_id TEXT NOT NULL,
41715
- envelope_json TEXT NOT NULL,
41716
- rejection_code TEXT NOT NULL CHECK (
41717
- rejection_code IN ('session_deleted', 'session_not_found', 'session_rejected')
41718
- )
41719
- ) STRICT;
41720
- INSERT INTO relay_session_event_dead_letters (
41721
- ordinal, event_id, session_id, envelope_json, rejection_code
41722
- )
41723
- SELECT ordinal, event_id, session_id, envelope_json, rejection_code
41724
- FROM relay_session_event_dead_letters_legacy;
41725
- DROP TABLE relay_session_event_dead_letters_legacy;
41726
- COMMIT;
41727
- `);
41728
- }
41729
- const outboxColumns = this.#database.prepare("PRAGMA table_info(relay_session_event_outbox)").all();
41730
- const hasSourceKey = outboxColumns.some(
41731
- (column) => typeof column === "object" && column !== null && Reflect.get(column, "name") === "source_key"
41732
- );
41733
- if (!hasSourceKey) {
41734
- this.#database.exec(`
41735
- ALTER TABLE relay_session_event_outbox
41736
- ADD COLUMN source_key TEXT NOT NULL DEFAULT '';
41737
- `);
41738
- }
41739
- const hasByteLength = outboxColumns.some(
41740
- (column) => typeof column === "object" && column !== null && Reflect.get(column, "name") === "byte_length"
41741
- );
41742
- if (!hasByteLength) {
41743
- this.#database.exec(`
41744
- ALTER TABLE relay_session_event_outbox
41745
- ADD COLUMN byte_length INTEGER NOT NULL DEFAULT 0;
41746
- `);
41747
- }
41748
41669
  this.#database.exec(`
41749
- UPDATE relay_session_event_outbox
41750
- SET source_key = CASE json_extract(envelope_json, '$.source.kind')
41751
- WHEN 'attempt' THEN
41752
- 'attempt:' || session_id || ':' || json_extract(envelope_json, '$.source.attemptId')
41753
- ELSE 'runtime:' || session_id
41754
- END
41755
- WHERE source_key = '';
41756
- UPDATE relay_session_event_outbox
41757
- SET byte_length = length(CAST(envelope_json AS BLOB))
41758
- WHERE byte_length = 0;
41759
- UPDATE relay_session_event_outbox_state
41760
- SET event_count = (SELECT COUNT(*) FROM relay_session_event_outbox),
41761
- total_bytes = (
41762
- SELECT COALESCE(SUM(byte_length), 0)
41763
- FROM relay_session_event_outbox
41764
- )
41765
- WHERE singleton = 1;
41766
41670
  CREATE INDEX IF NOT EXISTS relay_session_event_outbox_source_order
41767
41671
  ON relay_session_event_outbox(source_key, ordinal);
41768
41672
  `);
@@ -43822,12 +43726,12 @@ function waitForRelayRetry(signal, timer) {
43822
43726
  if (signal.aborted) {
43823
43727
  return Promise.resolve();
43824
43728
  }
43825
- return new Promise((resolve7) => {
43729
+ return new Promise((resolve8) => {
43826
43730
  const retry = timer.schedule(finish, RELAY_RECONNECT_DELAY_MILLISECONDS);
43827
43731
  function finish() {
43828
43732
  retry.cancel();
43829
43733
  signal.removeEventListener("abort", finish);
43830
- resolve7();
43734
+ resolve8();
43831
43735
  }
43832
43736
  signal.addEventListener("abort", finish, { once: true });
43833
43737
  });
@@ -43923,7 +43827,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43923
43827
  installationObserver.connect(socket);
43924
43828
  onConnected();
43925
43829
  try {
43926
- await new Promise((resolve7, reject) => {
43830
+ await new Promise((resolve8, reject) => {
43927
43831
  let finished = false;
43928
43832
  const cleanup = () => {
43929
43833
  connectionLiveness.close();
@@ -43941,7 +43845,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43941
43845
  }
43942
43846
  finished = true;
43943
43847
  cleanup();
43944
- resolve7();
43848
+ resolve8();
43945
43849
  };
43946
43850
  const rejectConnection = (failure2) => {
43947
43851
  if (finished) {
@@ -44530,7 +44434,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
44530
44434
  try {
44531
44435
  operationSignal.throwIfAborted();
44532
44436
  if (previous2.length > 0) {
44533
- await new Promise((resolve8, reject2) => {
44437
+ await new Promise((resolve9, reject2) => {
44534
44438
  const cancel = () => reject2(operationSignal.reason);
44535
44439
  operationSignal.addEventListener("abort", cancel, {
44536
44440
  once: true
@@ -44538,7 +44442,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
44538
44442
  void Promise.all(previous2.map((request) => request.completion)).then(
44539
44443
  () => {
44540
44444
  operationSignal.removeEventListener("abort", cancel);
44541
- resolve8();
44445
+ resolve9();
44542
44446
  },
44543
44447
  (error62) => {
44544
44448
  operationSignal.removeEventListener("abort", cancel);
@@ -44623,13 +44527,13 @@ async function runRelayConnection(config2, directories, audit, sessions, install
44623
44527
  try {
44624
44528
  operationSignal.throwIfAborted();
44625
44529
  if (previous2.length > 0) {
44626
- await new Promise((resolve8, reject2) => {
44530
+ await new Promise((resolve9, reject2) => {
44627
44531
  const cancel = () => reject2(operationSignal.reason);
44628
44532
  operationSignal.addEventListener("abort", cancel, { once: true });
44629
44533
  void Promise.all(previous2.map((request) => request.completion)).then(
44630
44534
  () => {
44631
44535
  operationSignal.removeEventListener("abort", cancel);
44632
- resolve8();
44536
+ resolve9();
44633
44537
  },
44634
44538
  (error62) => {
44635
44539
  operationSignal.removeEventListener("abort", cancel);
@@ -44974,7 +44878,11 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
44974
44878
  );
44975
44879
  };
44976
44880
  const announceReadiness = () => {
44977
- if (!connectionAnnounced || !catalogPublished || readinessAnnounced) {
44881
+ if (!connectionAnnounced || !catalogPublished) {
44882
+ return;
44883
+ }
44884
+ options.onConnectionStatus?.("online");
44885
+ if (readinessAnnounced) {
44978
44886
  return;
44979
44887
  }
44980
44888
  readinessAnnounced = true;
@@ -44985,14 +44893,16 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
44985
44893
  return;
44986
44894
  }
44987
44895
  connectionAnnounced = true;
44988
- const reconnectCommand = `npx --yes @moxt-ai/mobius start ${config2.reconnectTarget.commandArgument}`;
44989
44896
  process.stdout.write("Mobius daemon connected to the relay.\n\n");
44990
- process.stdout.write(
44991
- `${styleText(["bold", "yellow"], `Reconnect this local connection later:
44897
+ if (config2.reconnectTarget !== null) {
44898
+ const reconnectCommand = `mobius start ${config2.reconnectTarget.commandArgument}`;
44899
+ process.stdout.write(
44900
+ `${styleText(["bold", "yellow"], `Reconnect this local connection later:
44992
44901
  ${reconnectCommand}`)}
44993
44902
 
44994
44903
  `
44995
- );
44904
+ );
44905
+ }
44996
44906
  announceReadiness();
44997
44907
  startAutomaticIntegrationProvisioning();
44998
44908
  };
@@ -45023,7 +44933,12 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
45023
44933
  activeAttemptIds,
45024
44934
  connectionEpoch,
45025
44935
  diagnostics,
45026
- announceConnection,
44936
+ () => {
44937
+ if (catalogPublished) {
44938
+ options.onConnectionStatus?.("online");
44939
+ }
44940
+ announceConnection();
44941
+ },
45027
44942
  signal,
45028
44943
  timer,
45029
44944
  resolveAgentCatalogEnvironment
@@ -45037,6 +44952,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
45037
44952
  }
45038
44953
  diagnostics.connectionFailed(connectionEpoch, error62, "connection");
45039
44954
  }
44955
+ options.onConnectionStatus?.("reconnecting");
45040
44956
  await waitForRelayRetry(signal, timer);
45041
44957
  }
45042
44958
  } finally {
@@ -45123,6 +45039,7 @@ var MobiusRuntimeEngine = class {
45123
45039
  const audit = new AuditStore(this.#config.auditDatabasePath);
45124
45040
  try {
45125
45041
  await runDaemon(this.#config, audit, signal, void 0, {
45042
+ ...this.#options.onConnectionStatus === void 0 ? {} : { onConnectionStatus: this.#options.onConnectionStatus },
45126
45043
  ...this.#options.resolveAgentCatalogEnvironment === void 0 ? {} : { resolveAgentCatalogEnvironment: this.#options.resolveAgentCatalogEnvironment }
45127
45044
  });
45128
45045
  } finally {
@@ -45132,6 +45049,567 @@ var MobiusRuntimeEngine = class {
45132
45049
  };
45133
45050
  };
45134
45051
 
45052
+ // src/daemon-manager.ts
45053
+ var CONTROL_TIMEOUT_MILLISECONDS = 13e4;
45054
+ var START_TIMEOUT_MILLISECONDS = 12e4;
45055
+ var MAXIMUM_MESSAGE_BYTES = 64 * 1024;
45056
+ var CONNECTION_ID_PATTERN2 = /^mcn_[a-f0-9]{32}$/;
45057
+ async function acquireManagerLock(stateDirectory) {
45058
+ const path2 = join18(stateDirectory, "manager.lock");
45059
+ for (let attempt = 0; attempt < 2; attempt += 1) {
45060
+ try {
45061
+ await writeFile4(path2, `${process.pid.toString()}
45062
+ `, { flag: "wx", mode: 384 });
45063
+ return async () => await unlink2(path2).catch(() => void 0);
45064
+ } catch (cause) {
45065
+ if (!isNodeError2(cause, "EEXIST")) {
45066
+ throw cause;
45067
+ }
45068
+ const encoded = await readFile3(path2, "utf8").catch(() => "");
45069
+ const pid = Number(encoded.trim());
45070
+ if (Number.isSafeInteger(pid) && pid > 1) {
45071
+ try {
45072
+ process.kill(pid, 0);
45073
+ return null;
45074
+ } catch (probeCause) {
45075
+ if (!isNodeError2(probeCause, "ESRCH")) {
45076
+ return null;
45077
+ }
45078
+ }
45079
+ }
45080
+ await unlink2(path2).catch(() => void 0);
45081
+ }
45082
+ }
45083
+ return null;
45084
+ }
45085
+ function isRecord11(value) {
45086
+ return typeof value === "object" && value !== null && !Array.isArray(value);
45087
+ }
45088
+ function controlSocketPath(stateDirectory) {
45089
+ const installationHash = createHash5("sha256").update(stateDirectory).digest("hex").slice(0, 32);
45090
+ return process.platform === "win32" ? `\\\\.\\pipe\\mobius-${installationHash}` : join18(tmpdir(), `mobius-${installationHash}.sock`);
45091
+ }
45092
+ function controlTokenPath(stateDirectory) {
45093
+ return join18(stateDirectory, "manager.token");
45094
+ }
45095
+ async function readOrCreateControlToken(stateDirectory) {
45096
+ const path2 = controlTokenPath(stateDirectory);
45097
+ try {
45098
+ return (await readFile3(path2, "utf8")).trim();
45099
+ } catch (cause) {
45100
+ if (!isNodeError2(cause, "ENOENT")) {
45101
+ throw cause;
45102
+ }
45103
+ }
45104
+ const token = randomBytes(32).toString("base64url");
45105
+ try {
45106
+ await writeFile4(path2, `${token}
45107
+ `, { flag: "wx", mode: 384 });
45108
+ return token;
45109
+ } catch (cause) {
45110
+ if (!isNodeError2(cause, "EEXIST")) {
45111
+ throw cause;
45112
+ }
45113
+ return (await readFile3(path2, "utf8")).trim();
45114
+ }
45115
+ }
45116
+ function isNodeError2(error62, code) {
45117
+ return typeof error62 === "object" && error62 !== null && "code" in error62 && error62.code === code;
45118
+ }
45119
+ function decodeCommand(value, expectedToken) {
45120
+ if (!isRecord11(value) || value["token"] !== expectedToken || typeof value["kind"] !== "string") {
45121
+ throw new Error("The manager request is invalid");
45122
+ }
45123
+ if (value["kind"] === "list" || value["kind"] === "stop") {
45124
+ return { kind: value["kind"] };
45125
+ }
45126
+ if ((value["kind"] === "remove-pair" || value["kind"] === "stop-pair") && typeof value["connectionId"] === "string" && CONNECTION_ID_PATTERN2.test(value["connectionId"])) {
45127
+ return { connectionId: value["connectionId"], kind: value["kind"] };
45128
+ }
45129
+ if (value["kind"] === "pair" || value["kind"] === "start") {
45130
+ const arguments_ = value["arguments"];
45131
+ if (!Array.isArray(arguments_) || arguments_.length > 16 || !arguments_.every((argument) => typeof argument === "string" && argument.length <= 4096)) {
45132
+ throw new Error("The manager command arguments are invalid");
45133
+ }
45134
+ return { arguments: arguments_, kind: value["kind"] };
45135
+ }
45136
+ throw new Error("The manager command is unsupported");
45137
+ }
45138
+ function decodeResponse(value) {
45139
+ if (!isRecord11(value) || typeof value["kind"] !== "string") {
45140
+ throw new Error("The Mobius manager returned an invalid response");
45141
+ }
45142
+ if (value["kind"] === "error" && typeof value["code"] === "string" && typeof value["message"] === "string") {
45143
+ return { code: value["code"], kind: "error", message: value["message"] };
45144
+ }
45145
+ if (value["kind"] === "stopped") {
45146
+ return { kind: "stopped" };
45147
+ }
45148
+ if (value["kind"] === "pair-stopped" && isManagedRuntimeSummary(value["pair"])) {
45149
+ return { kind: "pair-stopped", pair: value["pair"] };
45150
+ }
45151
+ if (value["kind"] === "pair-removed" && typeof value["connectionId"] === "string") {
45152
+ return { connectionId: value["connectionId"], kind: "pair-removed" };
45153
+ }
45154
+ if (value["kind"] === "ready" && typeof value["alreadyOnline"] === "boolean" && isManagedRuntimeSummary(value["pair"])) {
45155
+ return { alreadyOnline: value["alreadyOnline"], kind: "ready", pair: value["pair"] };
45156
+ }
45157
+ if (value["kind"] === "listed" && Array.isArray(value["pairs"]) && value["pairs"].every(isManagedRuntimeSummary)) {
45158
+ const managerVersion = value["managerVersion"];
45159
+ if (managerVersion === void 0) {
45160
+ return { kind: "legacy-listed", pairs: value["pairs"] };
45161
+ }
45162
+ if (typeof managerVersion === "string" && managerVersion.length > 0 && managerVersion.length <= 128) {
45163
+ return { kind: "listed", managerVersion, pairs: value["pairs"] };
45164
+ }
45165
+ }
45166
+ throw new Error("The Mobius manager returned an invalid response");
45167
+ }
45168
+ function isManagedRuntimeSummary(value) {
45169
+ return isRecord11(value) && typeof value["appId"] === "string" && typeof value["connectionId"] === "string" && typeof value["runtimeId"] === "string" && typeof value["workspace"] === "string" && ["starting", "online", "reconnecting", "failed", "stopped"].includes(String(value["status"]));
45170
+ }
45171
+ function summary(connection, status) {
45172
+ return {
45173
+ appId: connection.appId,
45174
+ connectionId: connection.connectionId,
45175
+ runtimeId: connection instanceof VerifiedRuntimeConnection ? connection.runtimeId : "unknown",
45176
+ status,
45177
+ workspace: connection.defaultWorkspace
45178
+ };
45179
+ }
45180
+ var RuntimeSupervisor = class {
45181
+ #failed = /* @__PURE__ */ new Map();
45182
+ #installation;
45183
+ #pairingRequests = /* @__PURE__ */ new Map();
45184
+ #restoring = /* @__PURE__ */ new Map();
45185
+ #runtimes = /* @__PURE__ */ new Map();
45186
+ #stopped = /* @__PURE__ */ new Map();
45187
+ constructor(installation) {
45188
+ this.#installation = installation;
45189
+ }
45190
+ restore = async (signal) => {
45191
+ const connections = await this.#installation.listConnections(signal);
45192
+ for (const connection of connections) {
45193
+ if (connection.activation === "stopped") {
45194
+ this.#stopped.set(connection.connectionId, connection);
45195
+ } else {
45196
+ this.#restoring.set(connection.connectionId, connection);
45197
+ }
45198
+ }
45199
+ await Promise.all(
45200
+ connections.filter((connection) => connection.activation === "active").map(async (connection) => {
45201
+ try {
45202
+ const paired = await resumeLocalMachine(["--connection", connection.connectionId], signal);
45203
+ this.#activate(connection, paired);
45204
+ } catch (cause) {
45205
+ this.#restoring.delete(connection.connectionId);
45206
+ this.#failed.set(connection.connectionId, connection);
45207
+ process.stderr.write(`Could not restore ${connection.connectionId}: ${errorMessage2(cause)}
45208
+ `);
45209
+ }
45210
+ })
45211
+ );
45212
+ };
45213
+ pair = async (arguments_, signal) => {
45214
+ const pairingId = pairingIdentifier(arguments_);
45215
+ if (pairingId === null) {
45216
+ return await this.#pair(arguments_, signal);
45217
+ }
45218
+ const pending = this.#pairingRequests.get(pairingId);
45219
+ if (pending !== void 0) {
45220
+ return await pending;
45221
+ }
45222
+ const request = this.#pair(arguments_, signal);
45223
+ this.#pairingRequests.set(pairingId, request);
45224
+ try {
45225
+ return await request;
45226
+ } finally {
45227
+ if (this.#pairingRequests.get(pairingId) === request) {
45228
+ this.#pairingRequests.delete(pairingId);
45229
+ }
45230
+ }
45231
+ };
45232
+ #pair = async (arguments_, signal) => {
45233
+ const paired = await pairLocalMachine(arguments_, signal);
45234
+ const connection = await this.#installation.setConnectionActivation(paired.connectionId, "active", signal);
45235
+ const alreadyOnline = this.#runtimes.get(connection.connectionId)?.status === "online";
45236
+ const active = this.#activate(connection, paired);
45237
+ await waitForReady(active, signal);
45238
+ return { alreadyOnline, pair: summary(connection, active.status) };
45239
+ };
45240
+ start = async (arguments_, signal) => {
45241
+ const paired = await resumeLocalMachine(arguments_, signal);
45242
+ const connection = await this.#installation.setConnectionActivation(paired.connectionId, "active", signal);
45243
+ const active = this.#activate(connection, paired);
45244
+ await waitForReady(active, signal);
45245
+ return summary(connection, active.status);
45246
+ };
45247
+ stop = async (connectionId2, signal) => {
45248
+ let connection = await this.#installation.readConnection(connectionId2, signal);
45249
+ const active = this.#runtimes.get(connection.connectionId);
45250
+ if (active !== void 0) {
45251
+ active.controller.abort();
45252
+ await active.completion;
45253
+ this.#runtimes.delete(connection.connectionId);
45254
+ }
45255
+ connection = await this.#installation.setConnectionActivation(connection.connectionId, "stopped", signal);
45256
+ this.#failed.delete(connection.connectionId);
45257
+ this.#stopped.set(connection.connectionId, connection);
45258
+ return summary(connection, "stopped");
45259
+ };
45260
+ remove = async (connectionId2, signal) => {
45261
+ const stopped = await this.stop(connectionId2, signal);
45262
+ await this.#installation.removeConnection(stopped.connectionId, signal);
45263
+ this.#stopped.delete(stopped.connectionId);
45264
+ return stopped.connectionId;
45265
+ };
45266
+ list = () => [
45267
+ ...[...this.#runtimes.values()].map((active) => summary(active.connection, active.status)),
45268
+ ...[...this.#restoring.values()].map((connection) => summary(connection, "starting")),
45269
+ ...[...this.#failed.values()].map((connection) => summary(connection, "failed")),
45270
+ ...[...this.#stopped.values()].map((connection) => summary(connection, "stopped"))
45271
+ ].sort(
45272
+ (left, right) => left.appId.localeCompare(right.appId) || left.connectionId.localeCompare(right.connectionId)
45273
+ );
45274
+ close = async () => {
45275
+ const runtimes = [...this.#runtimes.values()];
45276
+ for (const runtime of runtimes) {
45277
+ runtime.controller.abort();
45278
+ }
45279
+ await Promise.all(runtimes.map(async (runtime) => await runtime.completion));
45280
+ };
45281
+ #activate(connection, paired) {
45282
+ const existing = this.#runtimes.get(connection.connectionId);
45283
+ if (existing !== void 0) {
45284
+ return existing;
45285
+ }
45286
+ const controller = new AbortController();
45287
+ const readiness = Promise.withResolvers();
45288
+ const completion = Promise.withResolvers();
45289
+ const active = {
45290
+ connection,
45291
+ controller,
45292
+ completion: completion.promise,
45293
+ ready: readiness.promise,
45294
+ resolveReady: readiness.resolve,
45295
+ status: "starting"
45296
+ };
45297
+ const engine = new MobiusRuntimeEngine(paired.config, {
45298
+ onConnectionStatus: (status) => {
45299
+ active.status = status;
45300
+ if (status === "online") {
45301
+ active.resolveReady();
45302
+ }
45303
+ }
45304
+ });
45305
+ void engine.run(controller.signal).catch((cause) => {
45306
+ if (!controller.signal.aborted) {
45307
+ active.status = "failed";
45308
+ this.#runtimes.delete(connection.connectionId);
45309
+ this.#failed.set(connection.connectionId, connection);
45310
+ active.resolveReady();
45311
+ process.stderr.write(`Runtime ${connection.connectionId} failed: ${errorMessage2(cause)}
45312
+ `);
45313
+ }
45314
+ }).finally(completion.resolve);
45315
+ this.#runtimes.set(connection.connectionId, active);
45316
+ this.#restoring.delete(connection.connectionId);
45317
+ this.#failed.delete(connection.connectionId);
45318
+ this.#stopped.delete(connection.connectionId);
45319
+ return active;
45320
+ }
45321
+ };
45322
+ function pairingIdentifier(arguments_) {
45323
+ const indexes = arguments_.flatMap((argument, index3) => argument === "--pairing" ? [index3] : []);
45324
+ if (indexes.length !== 1) {
45325
+ return null;
45326
+ }
45327
+ const index2 = indexes[0];
45328
+ return index2 === void 0 ? null : arguments_[index2 + 1] ?? null;
45329
+ }
45330
+ async function waitForReady(active, signal) {
45331
+ if (active.status === "online") {
45332
+ return;
45333
+ }
45334
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(START_TIMEOUT_MILLISECONDS)]);
45335
+ await new Promise((resolve8, reject) => {
45336
+ const abort = () => reject(deadline.reason);
45337
+ active.ready.then(resolve8, reject).finally(() => deadline.removeEventListener("abort", abort));
45338
+ deadline.addEventListener("abort", abort, { once: true });
45339
+ });
45340
+ if (active.status === "failed") {
45341
+ throw new Error("The Runtime failed before connecting");
45342
+ }
45343
+ }
45344
+ function errorMessage2(error62) {
45345
+ return error62 instanceof Error ? error62.message : "Unknown failure";
45346
+ }
45347
+ async function readSocketMessage(socket, signal) {
45348
+ return await new Promise((resolve8, reject) => {
45349
+ let encoded = "";
45350
+ const finish = (error62, value) => {
45351
+ signal.removeEventListener("abort", abort);
45352
+ socket.removeAllListeners("data");
45353
+ socket.removeAllListeners("error");
45354
+ socket.removeAllListeners("end");
45355
+ if (error62 === void 0) {
45356
+ resolve8(value);
45357
+ } else {
45358
+ reject(error62);
45359
+ }
45360
+ };
45361
+ const abort = () => {
45362
+ socket.destroy();
45363
+ finish(signal.reason);
45364
+ };
45365
+ socket.on("data", (chunk) => {
45366
+ encoded += chunk.toString("utf8");
45367
+ if (encoded.length > MAXIMUM_MESSAGE_BYTES) {
45368
+ finish(new Error("The manager message is too large"));
45369
+ socket.destroy();
45370
+ return;
45371
+ }
45372
+ const newline = encoded.indexOf("\n");
45373
+ if (newline >= 0) {
45374
+ try {
45375
+ finish(void 0, JSON.parse(encoded.slice(0, newline)));
45376
+ } catch (cause) {
45377
+ finish(cause);
45378
+ }
45379
+ }
45380
+ });
45381
+ socket.once("error", finish);
45382
+ socket.once("end", () => finish(new Error("The manager connection closed without a response")));
45383
+ signal.addEventListener("abort", abort, { once: true });
45384
+ });
45385
+ }
45386
+ async function sendControlRequest(stateDirectory, command, signal) {
45387
+ const token = await readOrCreateControlToken(stateDirectory);
45388
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(CONTROL_TIMEOUT_MILLISECONDS)]);
45389
+ const socket = createConnection(controlSocketPath(stateDirectory));
45390
+ try {
45391
+ await new Promise((resolve8, reject) => {
45392
+ const abort = () => {
45393
+ socket.destroy();
45394
+ reject(deadline.reason);
45395
+ };
45396
+ socket.once("connect", () => {
45397
+ deadline.removeEventListener("abort", abort);
45398
+ resolve8();
45399
+ });
45400
+ socket.once("error", reject);
45401
+ deadline.addEventListener("abort", abort, { once: true });
45402
+ });
45403
+ socket.write(`${JSON.stringify({ ...command, token })}
45404
+ `);
45405
+ return decodeResponse(await readSocketMessage(socket, deadline));
45406
+ } finally {
45407
+ socket.destroy();
45408
+ }
45409
+ }
45410
+ async function spawnManager(stateDirectory) {
45411
+ const log = await open6(join18(stateDirectory, "manager.log"), "a", 384);
45412
+ try {
45413
+ const child = spawn6(process.execPath, [process.argv[1] ?? "", "__manager"], {
45414
+ detached: true,
45415
+ env: process.env,
45416
+ stdio: ["ignore", log.fd, log.fd]
45417
+ });
45418
+ child.unref();
45419
+ return child;
45420
+ } finally {
45421
+ await log.close();
45422
+ }
45423
+ }
45424
+ async function launchManager(stateDirectory, managerVersion) {
45425
+ process.stdout.write(`Starting mobius daemon ${managerVersion}
45426
+ `);
45427
+ await spawnManager(stateDirectory);
45428
+ }
45429
+ async function waitForManagerExit(stateDirectory, signal) {
45430
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(1e4)]);
45431
+ while (!deadline.aborted) {
45432
+ try {
45433
+ await sendControlRequest(stateDirectory, { kind: "list" }, AbortSignal.timeout(200));
45434
+ } catch (cause) {
45435
+ if (isNodeError2(cause, "ENOENT") || isNodeError2(cause, "ECONNREFUSED")) {
45436
+ return;
45437
+ }
45438
+ }
45439
+ await new Promise((resolve8, reject) => {
45440
+ const timeout = setTimeout(resolve8, 20);
45441
+ deadline.addEventListener(
45442
+ "abort",
45443
+ () => {
45444
+ clearTimeout(timeout);
45445
+ reject(deadline.reason);
45446
+ },
45447
+ { once: true }
45448
+ );
45449
+ });
45450
+ }
45451
+ throw deadline.reason;
45452
+ }
45453
+ async function requestManager(installation, managerVersion, command, signal) {
45454
+ if (managerVersion.length === 0 || managerVersion.length > 128) {
45455
+ throw new Error("The Mobius manager version is invalid");
45456
+ }
45457
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(CONTROL_TIMEOUT_MILLISECONDS)]);
45458
+ if (command.kind === "stop") {
45459
+ return await stopManager(installation.stateDirectory, deadline);
45460
+ }
45461
+ const listed = await ensureMatchingManager(installation.stateDirectory, managerVersion, deadline);
45462
+ if (command.kind === "list") {
45463
+ return listed;
45464
+ }
45465
+ const response = await sendControlRequest(installation.stateDirectory, command, deadline);
45466
+ if (response.kind === "legacy-listed") {
45467
+ throw new Error("The Mobius manager returned an unexpected response");
45468
+ }
45469
+ return response;
45470
+ }
45471
+ async function ensureMatchingManager(stateDirectory, managerVersion, signal) {
45472
+ let managerStarted = false;
45473
+ while (!signal.aborted) {
45474
+ try {
45475
+ const response = await sendControlRequest(stateDirectory, { kind: "list" }, signal);
45476
+ if (response.kind === "listed" && response.managerVersion === managerVersion) {
45477
+ if (managerStarted) {
45478
+ process.stdout.write(`Mobius daemon ${managerVersion} started
45479
+ `);
45480
+ }
45481
+ return response;
45482
+ }
45483
+ if (response.kind !== "listed" && response.kind !== "legacy-listed") {
45484
+ if (response.kind === "error") {
45485
+ throw new Error(response.message);
45486
+ }
45487
+ throw new Error("The Mobius manager returned an unexpected response");
45488
+ }
45489
+ await stopManager(stateDirectory, signal);
45490
+ await launchManager(stateDirectory, managerVersion);
45491
+ managerStarted = true;
45492
+ } catch (cause) {
45493
+ if (!isNodeError2(cause, "ENOENT") && !isNodeError2(cause, "ECONNREFUSED")) {
45494
+ throw cause;
45495
+ }
45496
+ if (!managerStarted) {
45497
+ await launchManager(stateDirectory, managerVersion);
45498
+ managerStarted = true;
45499
+ }
45500
+ await new Promise((resolve8, reject) => {
45501
+ const timeout = setTimeout(finish, 50);
45502
+ const abort = () => finish(signal.reason);
45503
+ function finish(cause2) {
45504
+ clearTimeout(timeout);
45505
+ signal.removeEventListener("abort", abort);
45506
+ cause2 === void 0 ? resolve8() : reject(cause2);
45507
+ }
45508
+ signal.addEventListener("abort", abort, { once: true });
45509
+ });
45510
+ }
45511
+ }
45512
+ throw signal.reason;
45513
+ }
45514
+ async function stopManager(stateDirectory, signal) {
45515
+ try {
45516
+ const response = await sendControlRequest(stateDirectory, { kind: "stop" }, signal);
45517
+ if (response.kind === "error") {
45518
+ throw new Error(response.message);
45519
+ }
45520
+ if (response.kind !== "stopped") {
45521
+ throw new Error("The Mobius manager returned an unexpected response");
45522
+ }
45523
+ await waitForManagerExit(stateDirectory, signal);
45524
+ return response;
45525
+ } catch (cause) {
45526
+ if (isNodeError2(cause, "ENOENT") || isNodeError2(cause, "ECONNREFUSED")) {
45527
+ return { kind: "stopped" };
45528
+ }
45529
+ throw cause;
45530
+ }
45531
+ }
45532
+ async function runManager(installation, managerVersion, signal) {
45533
+ const releaseLock = await acquireManagerLock(installation.stateDirectory);
45534
+ if (releaseLock === null) {
45535
+ return;
45536
+ }
45537
+ const token = await readOrCreateControlToken(installation.stateDirectory);
45538
+ const socketPath = controlSocketPath(installation.stateDirectory);
45539
+ const shutdown2 = new AbortController();
45540
+ const combined = AbortSignal.any([signal, shutdown2.signal]);
45541
+ const supervisor = new RuntimeSupervisor(installation);
45542
+ try {
45543
+ await supervisor.restore(combined);
45544
+ } catch (cause) {
45545
+ combined.throwIfAborted();
45546
+ process.stderr.write(`Could not restore saved Runtime connections: ${errorMessage2(cause)}
45547
+ `);
45548
+ }
45549
+ const server = createServer((socket) => {
45550
+ void (async () => {
45551
+ try {
45552
+ const request = decodeCommand(await readSocketMessage(socket, combined), token);
45553
+ let response;
45554
+ if (request.kind === "list") {
45555
+ response = { kind: "listed", managerVersion, pairs: supervisor.list() };
45556
+ } else if (request.kind === "pair") {
45557
+ const paired = await supervisor.pair(request.arguments, combined);
45558
+ response = { alreadyOnline: paired.alreadyOnline, kind: "ready", pair: paired.pair };
45559
+ } else if (request.kind === "start") {
45560
+ response = {
45561
+ alreadyOnline: false,
45562
+ kind: "ready",
45563
+ pair: await supervisor.start(request.arguments, combined)
45564
+ };
45565
+ } else if (request.kind === "stop-pair") {
45566
+ response = { kind: "pair-stopped", pair: await supervisor.stop(request.connectionId, combined) };
45567
+ } else if (request.kind === "remove-pair") {
45568
+ response = {
45569
+ connectionId: await supervisor.remove(request.connectionId, combined),
45570
+ kind: "pair-removed"
45571
+ };
45572
+ } else {
45573
+ response = { kind: "stopped" };
45574
+ shutdown2.abort();
45575
+ }
45576
+ socket.end(`${JSON.stringify(response)}
45577
+ `);
45578
+ } catch (cause) {
45579
+ socket.end(
45580
+ `${JSON.stringify({ kind: "error", code: "manager_command_failed", message: errorMessage2(cause) })}
45581
+ `
45582
+ );
45583
+ }
45584
+ })();
45585
+ });
45586
+ if (process.platform !== "win32") {
45587
+ await unlink2(socketPath).catch((cause) => {
45588
+ if (!isNodeError2(cause, "ENOENT")) {
45589
+ throw cause;
45590
+ }
45591
+ });
45592
+ }
45593
+ server.listen(socketPath);
45594
+ await new Promise((resolve8, reject) => {
45595
+ server.once("listening", resolve8);
45596
+ server.once("error", reject);
45597
+ });
45598
+ if (process.platform !== "win32") {
45599
+ await import("node:fs/promises").then(async ({ chmod: chmod2 }) => await chmod2(socketPath, 384));
45600
+ }
45601
+ try {
45602
+ await new Promise((resolve8) => combined.addEventListener("abort", () => resolve8(), { once: true }));
45603
+ await new Promise((resolve8) => server.close(() => resolve8()));
45604
+ await supervisor.close();
45605
+ } finally {
45606
+ if (process.platform !== "win32") {
45607
+ await unlink2(socketPath).catch(() => void 0);
45608
+ }
45609
+ await releaseLock();
45610
+ }
45611
+ }
45612
+
45135
45613
  // src/cli.ts
45136
45614
  var shutdown = new AbortController();
45137
45615
  process.once("SIGINT", () => shutdown.abort());
@@ -45140,20 +45618,78 @@ var USAGE = `Mobius CLI
45140
45618
 
45141
45619
  Usage:
45142
45620
  mobius --version
45143
- mobius pair --url <relay-url> --pairing <runtime-pairing-id> --code <pairing-code> [--workspace <directory>]
45621
+ mobius pair --url <relay-url> --pairing <runtime-pairing-id> --code <pairing-code> [--app-id <app-id>] [--workspace <directory>]
45622
+ mobius pair list [--output-json=<existing-file.json>]
45623
+ mobius pair stop --connection <connection-id>
45624
+ mobius pair remove --connection <connection-id>
45144
45625
  mobius start --connection <connection-id>
45145
- mobius start --channel <legacy-channel-id>
45626
+ mobius quit
45146
45627
  mobius agents [--json]
45147
45628
 
45148
45629
  Commands:
45149
45630
  --version Print the installed Mobius CLI version
45150
- pair Pair this machine and start its local daemon
45151
- start Start the local daemon for a saved connection
45631
+ pair Pair this machine or list, stop, and remove managed pairings
45632
+ start Start the manager and activate a saved connection
45633
+ quit Stop the manager and every active Runtime
45152
45634
  agents Show detected, missing, and integration-ready Agents
45153
45635
 
45154
45636
  Pairing grants this browser access to the machine with your user account's permissions.
45155
45637
  New conversations default to this Mobius installation's private workspace; choose other directories in the browser.
45156
45638
  `;
45639
+ function formatPairTable(pairs) {
45640
+ const headers = ["connection_id", "app_id", "runtime_id", "workspace", "status"];
45641
+ const rows = pairs.map((pair) => [pair.connectionId, pair.appId, pair.runtimeId, pair.workspace, pair.status]);
45642
+ const widths = headers.map(
45643
+ (header, index2) => Math.max(header.length, ...rows.map((row) => row[index2]?.length ?? 0))
45644
+ );
45645
+ const line = (row) => `| ${row.map((value, index2) => value.padEnd(widths[index2] ?? value.length)).join(" | ")} |`;
45646
+ const divider = `|-${widths.map((width) => "-".repeat(width)).join("-|-")}-|`;
45647
+ return `${line(headers)}
45648
+ ${divider}
45649
+ ${rows.map(line).join("\n")}${rows.length === 0 ? "" : "\n"}`;
45650
+ }
45651
+ function pairListOutputPath(arguments_) {
45652
+ if (arguments_.length === 0) {
45653
+ return null;
45654
+ }
45655
+ const prefix = "--output-json=";
45656
+ const option = arguments_.length === 1 ? arguments_[0] : void 0;
45657
+ if (option === void 0 || !option.startsWith(prefix) || option.length === prefix.length) {
45658
+ throw new Error("Usage: mobius pair list [--output-json=<existing-file.json>]");
45659
+ }
45660
+ return resolve7(option.slice(prefix.length));
45661
+ }
45662
+ async function writePairList(path2, pairs) {
45663
+ shutdown.signal.throwIfAborted();
45664
+ let file2;
45665
+ try {
45666
+ file2 = await open7(path2, constants2.O_WRONLY | constants2.O_NOFOLLOW);
45667
+ } catch (cause) {
45668
+ if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") {
45669
+ throw new Error("The JSON output file does not exist", { cause });
45670
+ }
45671
+ throw new Error("The JSON output file cannot be written", { cause });
45672
+ }
45673
+ try {
45674
+ const metadata = await file2.stat();
45675
+ if (!metadata.isFile()) {
45676
+ throw new Error("The JSON output path is not a regular file");
45677
+ }
45678
+ const output2 = pairs.map((pair) => ({
45679
+ app_id: pair.appId,
45680
+ connection_id: pair.connectionId,
45681
+ runtime_id: pair.runtimeId,
45682
+ status: pair.status,
45683
+ workspace: pair.workspace
45684
+ }));
45685
+ shutdown.signal.throwIfAborted();
45686
+ await file2.truncate(0);
45687
+ await file2.writeFile(`${JSON.stringify(output2, null, 2)}
45688
+ `, "utf8");
45689
+ } finally {
45690
+ await file2.close();
45691
+ }
45692
+ }
45157
45693
  async function main() {
45158
45694
  const command = process.argv[2];
45159
45695
  if (command === void 0 || command === "--help" || command === "-h") {
@@ -45170,8 +45706,8 @@ async function main() {
45170
45706
  if (arguments_.length > 1 || arguments_.length === 1 && arguments_[0] !== "--json") {
45171
45707
  throw new Error("Usage: mobius agents [--json]");
45172
45708
  }
45173
- const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
45174
- const localContext = new DaemonLocalContext(installation.stateDirectory, process.env);
45709
+ const installation2 = await openMobiusCliInstallation(shutdown.signal, process.env);
45710
+ const localContext = new DaemonLocalContext(installation2.stateDirectory, process.env);
45175
45711
  const defaultWorkspace = loadDefaultWorkspace(localContext.environment);
45176
45712
  await mkdir6(defaultWorkspace, { recursive: true, mode: 448 });
45177
45713
  const inventory = await discoverLocalAgentInventory({
@@ -45182,38 +45718,118 @@ async function main() {
45182
45718
  process.stdout.write(formatAgentDiagnostics(inventory, arguments_[0] === "--json"));
45183
45719
  return;
45184
45720
  }
45185
- let config2;
45721
+ const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
45722
+ if (command === "__manager") {
45723
+ await runManager(installation, package_default.version, shutdown.signal);
45724
+ return;
45725
+ }
45186
45726
  if (command === "pair") {
45187
- process.stdout.write(`mobius version: ${package_default.version}
45727
+ if (process.argv[3] === "list") {
45728
+ const outputPath = pairListOutputPath(process.argv.slice(4));
45729
+ const response2 = await requestManager(
45730
+ installation,
45731
+ package_default.version,
45732
+ { kind: "list" },
45733
+ shutdown.signal
45734
+ );
45735
+ if (response2.kind === "error") {
45736
+ throw new Error(response2.message);
45737
+ }
45738
+ if (response2.kind !== "listed") {
45739
+ throw new Error("The Mobius manager returned an unexpected response");
45740
+ }
45741
+ if (outputPath === null) {
45742
+ process.stdout.write(formatPairTable(response2.pairs));
45743
+ } else {
45744
+ await writePairList(outputPath, response2.pairs);
45745
+ }
45746
+ return;
45747
+ }
45748
+ const pairAction = process.argv[3];
45749
+ if (pairAction === "stop" || pairAction === "remove") {
45750
+ if (process.argv.length !== 6 || process.argv[4] !== "--connection" || process.argv[5] === void 0) {
45751
+ throw new Error(`Usage: mobius pair ${pairAction} --connection <connection-id>`);
45752
+ }
45753
+ const response2 = await requestManager(
45754
+ installation,
45755
+ package_default.version,
45756
+ {
45757
+ connectionId: process.argv[5],
45758
+ kind: pairAction === "stop" ? "stop-pair" : "remove-pair"
45759
+ },
45760
+ shutdown.signal
45761
+ );
45762
+ if (response2.kind === "error") {
45763
+ throw new Error(response2.message);
45764
+ }
45765
+ if (pairAction === "stop" && response2.kind === "pair-stopped") {
45766
+ process.stdout.write(`Pairing stopped: ${response2.pair.connectionId}
45188
45767
  `);
45189
- const paired = await pairLocalMachine(process.argv.slice(3), shutdown.signal);
45190
- config2 = paired.config;
45191
- process.stdout.write("\nLocal machine paired.\n");
45192
- process.stdout.write(`Channel: ${paired.channelUrl}
45768
+ return;
45769
+ }
45770
+ if (pairAction === "remove" && response2.kind === "pair-removed") {
45771
+ process.stdout.write(`Pairing removed: ${response2.connectionId}
45193
45772
  `);
45194
- process.stdout.write(`Connection ID: ${paired.connectionId}
45773
+ return;
45774
+ }
45775
+ throw new Error("The Mobius manager returned an unexpected response");
45776
+ }
45777
+ process.stdout.write(`mobius version: ${package_default.version}
45195
45778
  `);
45196
- process.stdout.write(`Restart: mobius start --connection ${paired.connectionId}
45779
+ const response = await requestManager(
45780
+ installation,
45781
+ package_default.version,
45782
+ { arguments: process.argv.slice(3), kind: "pair" },
45783
+ shutdown.signal
45784
+ );
45785
+ if (response.kind === "error") {
45786
+ throw new Error(response.message);
45787
+ }
45788
+ if (response.kind !== "ready") {
45789
+ throw new Error("The Mobius manager returned an unexpected response");
45790
+ }
45791
+ process.stdout.write(
45792
+ response.alreadyOnline ? "\nThis pairing is already online.\n" : "\nLocal machine paired.\n"
45793
+ );
45794
+ process.stdout.write(`App ID: ${response.pair.appId}
45795
+ `);
45796
+ process.stdout.write(`Connection ID: ${response.pair.connectionId}
45197
45797
  `);
45198
- process.stdout.write("Open this channel in any browser while the daemon is running.\n");
45199
- process.stdout.write(`Connection saved to ${paired.connectionPath}
45798
+ process.stdout.write(`Status: ${response.pair.status}
45200
45799
  `);
45800
+ process.stdout.write("Mobius daemon is ready for Agent requests.\n");
45201
45801
  } else if (command === "start") {
45202
- const paired = await resumeLocalMachine(process.argv.slice(3), shutdown.signal);
45203
- config2 = paired.config;
45802
+ const response = await requestManager(
45803
+ installation,
45804
+ package_default.version,
45805
+ { arguments: process.argv.slice(3), kind: "start" },
45806
+ shutdown.signal
45807
+ );
45808
+ if (response.kind === "error") {
45809
+ throw new Error(response.message);
45810
+ }
45811
+ if (response.kind !== "ready") {
45812
+ throw new Error("The Mobius manager returned an unexpected response");
45813
+ }
45204
45814
  process.stdout.write("\nSaved local Runtime connection loaded.\n");
45205
- process.stdout.write(`Channel: ${paired.channelUrl}
45815
+ process.stdout.write(`Connection ID: ${response.pair.connectionId}
45206
45816
  `);
45207
- process.stdout.write("Open this channel in any browser while the daemon is running.\n");
45817
+ process.stdout.write(`Status: ${response.pair.status}
45818
+ `);
45819
+ process.stdout.write("Mobius daemon is ready for Agent requests.\n");
45820
+ } else if (command === "quit") {
45821
+ if (process.argv.length !== 3) {
45822
+ throw new Error("Usage: mobius quit");
45823
+ }
45824
+ const response = await requestManager(installation, package_default.version, { kind: "stop" }, shutdown.signal);
45825
+ if (response.kind === "error") {
45826
+ throw new Error(response.message);
45827
+ }
45828
+ process.stdout.write("Mobius daemon stopped.\n");
45829
+ return;
45208
45830
  } else {
45209
45831
  throw new Error(USAGE.trimEnd());
45210
45832
  }
45211
- process.stdout.write("Starting the local daemon. Keep this terminal open.\n\n");
45212
- process.stdout.write("This paired browser can use the machine with your user account's permissions.\n");
45213
- process.stdout.write(`Default workspace: ${config2.defaultWorkspace}
45214
-
45215
- `);
45216
- await new MobiusRuntimeEngine(config2).run(shutdown.signal);
45217
45833
  }
45218
45834
  try {
45219
45835
  await main();