@moxt-ai/mobius 0.0.49 → 0.0.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/runtime.js CHANGED
@@ -5,8 +5,8 @@ var __export = (target, all2) => {
5
5
  };
6
6
 
7
7
  // src/runtime.ts
8
- import { mkdir as mkdir4, realpath as realpath10, stat as stat9 } from "node:fs/promises";
9
- import { dirname as dirname7, join as join17, resolve as resolve5 } from "node:path";
8
+ import { mkdir as mkdir5, realpath as realpath10, stat as stat9 } from "node:fs/promises";
9
+ import { dirname as dirname8, join as join17, resolve as resolve7 } from "node:path";
10
10
 
11
11
  // src/agent-catalog/local-agent.ts
12
12
  import { realpathSync, statSync } from "node:fs";
@@ -5624,7 +5624,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
5624
5624
  var NONE = 0;
5625
5625
  var ASSUMED = 1;
5626
5626
  var PROVEN = 2;
5627
- function isRecursive(inst, stack, resolve6) {
5627
+ function isRecursive(inst, stack, resolve8) {
5628
5628
  const cached2 = recursive.get(inst);
5629
5629
  if (cached2 !== void 0)
5630
5630
  return cached2 ? PROVEN : NONE;
@@ -5634,7 +5634,7 @@ function isRecursive(inst, stack, resolve6) {
5634
5634
  let result = NONE;
5635
5635
  const check2 = (child) => {
5636
5636
  if (result !== PROVEN && child?._zod) {
5637
- const answer = isRecursive(child, stack, resolve6);
5637
+ const answer = isRecursive(child, stack, resolve8);
5638
5638
  if (answer > result)
5639
5639
  result = answer;
5640
5640
  }
@@ -5645,7 +5645,7 @@ function isRecursive(inst, stack, resolve6) {
5645
5645
  const desc = Object.getOwnPropertyDescriptor(sh, key);
5646
5646
  if (spread && !desc.enumerable)
5647
5647
  continue;
5648
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve6) : NONE;
5648
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve8) : NONE;
5649
5649
  if (child > answer)
5650
5650
  answer = child;
5651
5651
  }
@@ -5712,7 +5712,7 @@ function isRecursive(inst, stack, resolve6) {
5712
5712
  break;
5713
5713
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
5714
5714
  case "lazy": {
5715
- const inner = def._cachedInner ?? (resolve6 ? inst._zod.innerType : void 0);
5715
+ const inner = def._cachedInner ?? (resolve8 ? inst._zod.innerType : void 0);
5716
5716
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
5717
5717
  break;
5718
5718
  }
@@ -24040,12 +24040,40 @@ var AuditStore = class {
24040
24040
  };
24041
24041
 
24042
24042
  // src/config.ts
24043
- import { join as join14 } from "node:path";
24043
+ import { join as join14, resolve as resolve3 } from "node:path";
24044
24044
  function loadDefaultWorkspace(environment = process.env) {
24045
24045
  const { MOBIUS_DEFAULT_WORKSPACE: configuredWorkspace } = environment;
24046
24046
  return configuredWorkspace ?? join14(readStateDirectory(environment), "workspace");
24047
24047
  }
24048
- function createDaemonConfig(connection, agents = [], installableAgents = []) {
24048
+ var DaemonLocalContext = class {
24049
+ environment;
24050
+ stateDirectory;
24051
+ constructor(stateDirectory, environment = process.env) {
24052
+ this.stateDirectory = resolve3(stateDirectory);
24053
+ this.environment = Object.freeze({ ...environment, MOBIUS_STATE_DIRECTORY: this.stateDirectory });
24054
+ }
24055
+ };
24056
+ var DaemonReconnectTarget = class {
24057
+ };
24058
+ var OpaqueDaemonReconnectTarget = class extends DaemonReconnectTarget {
24059
+ connectionId;
24060
+ commandArgument;
24061
+ constructor(connectionId2) {
24062
+ super();
24063
+ this.connectionId = connectionId2;
24064
+ this.commandArgument = `--connection ${connectionId2}`;
24065
+ }
24066
+ };
24067
+ var ChannelDaemonReconnectTarget = class extends DaemonReconnectTarget {
24068
+ channelId;
24069
+ commandArgument;
24070
+ constructor(channelId) {
24071
+ super();
24072
+ this.channelId = channelId;
24073
+ this.commandArgument = `--channel ${channelId}`;
24074
+ }
24075
+ };
24076
+ function createDaemonConfig(connection, agents = [], installableAgents = [], localContext = new DaemonLocalContext(readStateDirectory(), process.env), reconnectTarget = new ChannelDaemonReconnectTarget(connection.channelId)) {
24049
24077
  return {
24050
24078
  agents,
24051
24079
  defaultWorkspace: connection.defaultWorkspace,
@@ -24054,6 +24082,8 @@ function createDaemonConfig(connection, agents = [], installableAgents = []) {
24054
24082
  catalog: new LocalAgentCatalog(agents, installableAgents),
24055
24083
  channelId: connection.channelId,
24056
24084
  installableAgents,
24085
+ localContext,
24086
+ reconnectTarget,
24057
24087
  relayUrl: connection.relayUrl
24058
24088
  };
24059
24089
  }
@@ -27479,10 +27509,10 @@ function resolveAll(constructs2, events, context) {
27479
27509
  const called = [];
27480
27510
  let index2 = -1;
27481
27511
  while (++index2 < constructs2.length) {
27482
- const resolve6 = constructs2[index2].resolveAll;
27483
- if (resolve6 && !called.includes(resolve6)) {
27484
- events = resolve6(events, context);
27485
- called.push(resolve6);
27512
+ const resolve8 = constructs2[index2].resolveAll;
27513
+ if (resolve8 && !called.includes(resolve8)) {
27514
+ events = resolve8(events, context);
27515
+ called.push(resolve8);
27486
27516
  }
27487
27517
  }
27488
27518
  return events;
@@ -33066,7 +33096,7 @@ function createWritableAcpStream(output2) {
33066
33096
  if (outputFailure !== void 0) {
33067
33097
  return Promise.reject(outputFailure);
33068
33098
  }
33069
- return new Promise((resolve6, reject) => {
33099
+ return new Promise((resolve8, reject) => {
33070
33100
  pendingWriteFailures.add(reject);
33071
33101
  output2.write(chunk, (error62) => {
33072
33102
  pendingWriteFailures.delete(reject);
@@ -33079,7 +33109,7 @@ function createWritableAcpStream(output2) {
33079
33109
  reject(outputFailure);
33080
33110
  return;
33081
33111
  }
33082
- resolve6();
33112
+ resolve8();
33083
33113
  });
33084
33114
  });
33085
33115
  }
@@ -33492,9 +33522,9 @@ var AcpProcessSession = class _AcpProcessSession {
33492
33522
  stderr.on("data", (chunk) => {
33493
33523
  process.stderr.write(`[${agent.id}-acp] ${chunk}`);
33494
33524
  });
33495
- this.#processExit = new Promise((resolve6) => {
33496
- this.#child.once("error", resolve6);
33497
- this.#child.once("exit", resolve6);
33525
+ this.#processExit = new Promise((resolve8) => {
33526
+ this.#child.once("error", resolve8);
33527
+ this.#child.once("exit", resolve8);
33498
33528
  });
33499
33529
  const stream = ndJsonStream2(createWritableAcpStream(stdin), readableWebStream(stdout));
33500
33530
  this.#connection = createAcpClient(this).connect(stream);
@@ -36061,7 +36091,7 @@ var AgentInstallationManager = class {
36061
36091
 
36062
36092
  // src/agent-installation/fixed-installation-executor.ts
36063
36093
  import { realpathSync as realpathSync2, statSync as statSync2 } from "node:fs";
36064
- import { resolve as resolve3 } from "node:path";
36094
+ import { resolve as resolve4 } from "node:path";
36065
36095
  function findSpecification(specifications, agentId) {
36066
36096
  for (const specification of specifications) {
36067
36097
  if (specification.id === agentId) {
@@ -36072,7 +36102,7 @@ function findSpecification(specifications, agentId) {
36072
36102
  }
36073
36103
  function resolveDefaultWorkspace(path2) {
36074
36104
  try {
36075
- const directory = realpathSync2(resolve3(path2));
36105
+ const directory = realpathSync2(resolve4(path2));
36076
36106
  if (!statSync2(directory).isDirectory()) {
36077
36107
  throw new Error("Default workspace is not a directory");
36078
36108
  }
@@ -36087,7 +36117,7 @@ function resolveDefaultWorkspace(path2) {
36087
36117
  }
36088
36118
  function resolveIntegrationStateDirectory(path2) {
36089
36119
  try {
36090
- const directory = realpathSync2(resolve3(path2));
36120
+ const directory = realpathSync2(resolve4(path2));
36091
36121
  const metadata = statSync2(directory);
36092
36122
  if (!metadata.isDirectory() || typeof process.getuid === "function" && metadata.uid !== process.getuid()) {
36093
36123
  throw new Error("Installation directory is not user-owned");
@@ -37783,7 +37813,7 @@ var RelayConnectionError = class extends Error {
37783
37813
  };
37784
37814
  function connectRelay(url2, signal) {
37785
37815
  signal.throwIfAborted();
37786
- return new Promise((resolve6, reject) => {
37816
+ return new Promise((resolve8, reject) => {
37787
37817
  const endpoint = new URL(url2);
37788
37818
  const headers = runtimeAuthorization(endpoint);
37789
37819
  endpoint.searchParams.delete("token");
@@ -37846,7 +37876,7 @@ function connectRelay(url2, signal) {
37846
37876
  }
37847
37877
  finished = true;
37848
37878
  cleanup();
37849
- resolve6(socket);
37879
+ resolve8(socket);
37850
37880
  };
37851
37881
  function onTimeout() {
37852
37882
  fail(
@@ -39844,12 +39874,12 @@ function waitForRelayRetry(signal, timer) {
39844
39874
  if (signal.aborted) {
39845
39875
  return Promise.resolve();
39846
39876
  }
39847
- return new Promise((resolve6) => {
39877
+ return new Promise((resolve8) => {
39848
39878
  const retry = timer.schedule(finish, RELAY_RECONNECT_DELAY_MILLISECONDS);
39849
39879
  function finish() {
39850
39880
  retry.cancel();
39851
39881
  signal.removeEventListener("abort", finish);
39852
- resolve6();
39882
+ resolve8();
39853
39883
  }
39854
39884
  signal.addEventListener("abort", finish, { once: true });
39855
39885
  });
@@ -39905,7 +39935,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39905
39935
  installationObserver.connect(socket);
39906
39936
  onConnected();
39907
39937
  try {
39908
- await new Promise((resolve6, reject) => {
39938
+ await new Promise((resolve8, reject) => {
39909
39939
  let finished = false;
39910
39940
  const cleanup = () => {
39911
39941
  connectionLiveness.close();
@@ -39923,7 +39953,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39923
39953
  }
39924
39954
  finished = true;
39925
39955
  cleanup();
39926
- resolve6();
39956
+ resolve8();
39927
39957
  };
39928
39958
  const rejectConnection = (failure2) => {
39929
39959
  if (finished) {
@@ -40370,7 +40400,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40370
40400
  try {
40371
40401
  operationSignal.throwIfAborted();
40372
40402
  if (previous2.length > 0) {
40373
- await new Promise((resolve7, reject2) => {
40403
+ await new Promise((resolve9, reject2) => {
40374
40404
  const cancel = () => reject2(operationSignal.reason);
40375
40405
  operationSignal.addEventListener("abort", cancel, {
40376
40406
  once: true
@@ -40378,7 +40408,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40378
40408
  void Promise.all(previous2.map((request) => request.completion)).then(
40379
40409
  () => {
40380
40410
  operationSignal.removeEventListener("abort", cancel);
40381
- resolve7();
40411
+ resolve9();
40382
40412
  },
40383
40413
  (error62) => {
40384
40414
  operationSignal.removeEventListener("abort", cancel);
@@ -40452,13 +40482,13 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40452
40482
  try {
40453
40483
  operationSignal.throwIfAborted();
40454
40484
  if (previous2.length > 0) {
40455
- await new Promise((resolve7, reject2) => {
40485
+ await new Promise((resolve9, reject2) => {
40456
40486
  const cancel = () => reject2(operationSignal.reason);
40457
40487
  operationSignal.addEventListener("abort", cancel, { once: true });
40458
40488
  void Promise.all(previous2.map((request) => request.completion)).then(
40459
40489
  () => {
40460
40490
  operationSignal.removeEventListener("abort", cancel);
40461
- resolve7();
40491
+ resolve9();
40462
40492
  },
40463
40493
  (error62) => {
40464
40494
  operationSignal.removeEventListener("abort", cancel);
@@ -40713,13 +40743,13 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40713
40743
  }
40714
40744
  async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
40715
40745
  const installationAudit = new AuditInstallationEvents(audit);
40716
- const stateDirectory = readStateDirectory();
40746
+ const stateDirectory = config2.localContext.stateDirectory;
40717
40747
  const specifications = supportedLocalAgentSpecifications();
40718
40748
  const installationExecutor = new FixedInstallationExecutor({
40719
40749
  defaultWorkspace: config2.defaultWorkspace,
40720
40750
  audit: installationAudit,
40721
40751
  catalog: config2.catalog,
40722
- environment: process.env,
40752
+ environment: config2.localContext.environment,
40723
40753
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
40724
40754
  stateDirectory
40725
40755
  });
@@ -40778,10 +40808,10 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
40778
40808
  return;
40779
40809
  }
40780
40810
  connectionAnnounced = true;
40781
- const reconnectCommand = `npx --yes @moxt-ai/mobius start --channel ${config2.channelId}`;
40811
+ const reconnectCommand = `npx --yes @moxt-ai/mobius start ${config2.reconnectTarget.commandArgument}`;
40782
40812
  process.stdout.write("Mobius daemon connected to the relay.\n\n");
40783
40813
  process.stdout.write(
40784
- `${styleText(["bold", "yellow"], `Reconnect this channel later:
40814
+ `${styleText(["bold", "yellow"], `Reconnect this local connection later:
40785
40815
  ${reconnectCommand}`)}
40786
40816
 
40787
40817
  `
@@ -40863,20 +40893,548 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
40863
40893
  }
40864
40894
 
40865
40895
  // src/pairing/pair-local-machine.ts
40866
- import { randomUUID as randomUUID4 } from "node:crypto";
40867
- import { mkdir as mkdir3, open as open5, realpath as realpath9, rename as rename3, stat as stat8, writeFile as writeFile2 } from "node:fs/promises";
40896
+ import { mkdir as mkdir4, realpath as realpath9, stat as stat8 } from "node:fs/promises";
40868
40897
  import { hostname as hostname3 } from "node:os";
40869
- import { basename as basename7, join as join16, resolve as resolve4 } from "node:path";
40898
+ import { basename as basename7, resolve as resolve6 } from "node:path";
40870
40899
  import { fetch as fetch6 } from "undici";
40900
+
40901
+ // src/storage/runtime-installation-store.ts
40902
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
40903
+ import { mkdir as mkdir3, open as open5, rename as rename3, unlink, writeFile as writeFile2 } from "node:fs/promises";
40904
+ import { dirname as dirname7, join as join16, resolve as resolve5 } from "node:path";
40905
+ var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
40906
+ var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
40907
+ var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
40908
+ var IDENTIFIER_PATTERN6 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
40909
+ var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
40910
+ var MAX_FILE_LENGTH = 16 * 1024;
40911
+ var INSTALLATION_POINTER_KEYS = ["installationId", "version"];
40912
+ var CHANNEL_INDEX_KEYS = [
40913
+ "applicationId",
40914
+ "channelId",
40915
+ "connectionId",
40916
+ "installationId",
40917
+ "version"
40918
+ ];
40919
+ var VERIFIED_CONNECTION_KEYS = [
40920
+ "applicationId",
40921
+ "channelId",
40922
+ "connectionId",
40923
+ "defaultWorkspace",
40924
+ "installationId",
40925
+ "kind",
40926
+ "relayOrigin",
40927
+ "runtimeCredential",
40928
+ "runtimeId",
40929
+ "version"
40930
+ ];
40931
+ var IMPORTED_LEGACY_CONNECTION_KEYS = [
40932
+ "applicationId",
40933
+ "channelId",
40934
+ "connectionId",
40935
+ "defaultWorkspace",
40936
+ "installationId",
40937
+ "kind",
40938
+ "relayOrigin",
40939
+ "runtimeCredential",
40940
+ "version"
40941
+ ];
40942
+ var CURRENT_CONNECTION_KEYS = [
40943
+ "defaultWorkspace",
40944
+ "channelId",
40945
+ "relayOrigin",
40946
+ "runtimeCredential"
40947
+ ];
40948
+ var LEGACY_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "daemonToken", "relayOrigin"];
40949
+ var RuntimeInstallationStoreError = class extends Error {
40950
+ code;
40951
+ constructor(code, message, options = {}) {
40952
+ super(message, options);
40953
+ this.code = code;
40954
+ this.name = "RuntimeInstallationStoreError";
40955
+ }
40956
+ };
40957
+ var StoredRuntimeConnection = class {
40958
+ applicationId;
40959
+ channelId;
40960
+ connectionId;
40961
+ defaultWorkspace;
40962
+ installationId;
40963
+ relayOrigin;
40964
+ runtimeCredential;
40965
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
40966
+ this.applicationId = applicationId;
40967
+ this.channelId = channelId;
40968
+ this.connectionId = connectionId2;
40969
+ this.defaultWorkspace = defaultWorkspace;
40970
+ this.installationId = installationId2;
40971
+ this.relayOrigin = relayOrigin;
40972
+ this.runtimeCredential = runtimeCredential2;
40973
+ }
40974
+ };
40975
+ var VerifiedRuntimeConnection = class extends StoredRuntimeConnection {
40976
+ kind = "verified";
40977
+ runtimeId;
40978
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2, runtimeId) {
40979
+ super(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2);
40980
+ this.runtimeId = runtimeId;
40981
+ }
40982
+ };
40983
+ var ImportedLegacyRuntimeConnection = class extends StoredRuntimeConnection {
40984
+ kind = "legacy_imported";
40985
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
40986
+ super(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2);
40987
+ }
40988
+ };
40989
+ function isRecord9(value) {
40990
+ return typeof value === "object" && value !== null && !Array.isArray(value);
40991
+ }
40992
+ function hasExactKeys(value, expectedKeys) {
40993
+ const keys = Object.keys(value);
40994
+ return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
40995
+ }
40996
+ function isNodeError(error62, code) {
40997
+ return typeof error62 === "object" && error62 !== null && "code" in error62 && error62.code === code;
40998
+ }
40999
+ function validateApplicationId(value) {
41000
+ if (!APPLICATION_ID_PATTERN.test(value)) {
41001
+ throw new RuntimeInstallationStoreError("invalid_application_id", "The application ID is invalid");
41002
+ }
41003
+ return value;
41004
+ }
41005
+ function validateConnectionId(value) {
41006
+ if (!CONNECTION_ID_PATTERN.test(value)) {
41007
+ throw new RuntimeInstallationStoreError("invalid_connection_id", "The local connection ID is invalid");
41008
+ }
41009
+ return value;
41010
+ }
41011
+ function validateInstallationId(value) {
41012
+ if (!INSTALLATION_ID_PATTERN.test(value)) {
41013
+ throw new RuntimeInstallationStoreError("invalid_installation_id", "The installation ID is invalid");
41014
+ }
41015
+ return value;
41016
+ }
41017
+ function validateIdentifier(value, code) {
41018
+ if (!IDENTIFIER_PATTERN6.test(value)) {
41019
+ throw new RuntimeInstallationStoreError(code, "The saved Runtime connection is invalid");
41020
+ }
41021
+ return value;
41022
+ }
41023
+ function validateRuntimeCredential(value) {
41024
+ if (!RUNTIME_CREDENTIAL_PATTERN.test(value)) {
41025
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41026
+ }
41027
+ return value;
41028
+ }
41029
+ function parseRelayOrigin(value) {
41030
+ let origin;
41031
+ try {
41032
+ origin = new URL(value);
41033
+ } catch (cause) {
41034
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid", {
41035
+ cause
41036
+ });
41037
+ }
41038
+ if (origin.protocol !== "https:" && origin.protocol !== "http:" || origin.username.length > 0 || origin.password.length > 0 || origin.protocol === "http:" && origin.hostname !== "127.0.0.1" && origin.hostname !== "localhost") {
41039
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41040
+ }
41041
+ origin.hash = "";
41042
+ origin.pathname = "/";
41043
+ origin.search = "";
41044
+ return origin;
41045
+ }
41046
+ function connectionId() {
41047
+ return `mcn_${randomUUID4().replaceAll("-", "")}`;
41048
+ }
41049
+ function installationId() {
41050
+ return `min_${randomUUID4().replaceAll("-", "")}`;
41051
+ }
41052
+ function channelIndexFileName(channelId) {
41053
+ return `mci_${createHash4("sha256").update(channelId).digest("hex")}.json`;
41054
+ }
41055
+ function decodeInstallationPointer(value) {
41056
+ if (!isRecord9(value) || !hasExactKeys(value, INSTALLATION_POINTER_KEYS) || value["version"] !== 1) {
41057
+ throw new RuntimeInstallationStoreError("invalid_installation", "The local installation record is invalid");
41058
+ }
41059
+ const storedInstallationId = value["installationId"];
41060
+ if (typeof storedInstallationId !== "string") {
41061
+ throw new RuntimeInstallationStoreError("invalid_installation", "The local installation record is invalid");
41062
+ }
41063
+ return { installationId: validateInstallationId(storedInstallationId) };
41064
+ }
41065
+ function decodeChannelIndex(value) {
41066
+ if (!isRecord9(value) || !hasExactKeys(value, CHANNEL_INDEX_KEYS) || value["version"] !== 1) {
41067
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41068
+ }
41069
+ const applicationId = value["applicationId"];
41070
+ const channelId = value["channelId"];
41071
+ const connectionId2 = value["connectionId"];
41072
+ const storedInstallationId = value["installationId"];
41073
+ if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof storedInstallationId !== "string") {
41074
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41075
+ }
41076
+ return {
41077
+ applicationId: validateApplicationId(applicationId),
41078
+ channelId: validateIdentifier(channelId, "invalid_connection"),
41079
+ connectionId: validateConnectionId(connectionId2),
41080
+ installationId: validateInstallationId(storedInstallationId)
41081
+ };
41082
+ }
41083
+ function decodeVerifiedConnection(value) {
41084
+ if (!hasExactKeys(value, VERIFIED_CONNECTION_KEYS) || value["kind"] !== "verified" || value["version"] !== 1) {
41085
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41086
+ }
41087
+ const applicationId = value["applicationId"];
41088
+ const channelId = value["channelId"];
41089
+ const connectionId2 = value["connectionId"];
41090
+ const defaultWorkspace = value["defaultWorkspace"];
41091
+ const storedInstallationId = value["installationId"];
41092
+ const relayOrigin = value["relayOrigin"];
41093
+ const runtimeCredential2 = value["runtimeCredential"];
41094
+ const runtimeId = value["runtimeId"];
41095
+ 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") {
41096
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41097
+ }
41098
+ return new VerifiedRuntimeConnection(
41099
+ validateApplicationId(applicationId),
41100
+ validateInstallationId(storedInstallationId),
41101
+ validateConnectionId(connectionId2),
41102
+ validateIdentifier(channelId, "invalid_connection"),
41103
+ defaultWorkspace,
41104
+ parseRelayOrigin(relayOrigin),
41105
+ validateRuntimeCredential(runtimeCredential2),
41106
+ validateIdentifier(runtimeId, "invalid_connection")
41107
+ );
41108
+ }
41109
+ function decodeImportedLegacyConnection(value) {
41110
+ if (!hasExactKeys(value, IMPORTED_LEGACY_CONNECTION_KEYS) || value["kind"] !== "legacy_imported" || value["version"] !== 1) {
41111
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41112
+ }
41113
+ const applicationId = value["applicationId"];
41114
+ const channelId = value["channelId"];
41115
+ const connectionId2 = value["connectionId"];
41116
+ const defaultWorkspace = value["defaultWorkspace"];
41117
+ const storedInstallationId = value["installationId"];
41118
+ const relayOrigin = value["relayOrigin"];
41119
+ const runtimeCredential2 = value["runtimeCredential"];
41120
+ if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
41121
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41122
+ }
41123
+ return new ImportedLegacyRuntimeConnection(
41124
+ validateApplicationId(applicationId),
41125
+ validateInstallationId(storedInstallationId),
41126
+ validateConnectionId(connectionId2),
41127
+ validateIdentifier(channelId, "invalid_connection"),
41128
+ defaultWorkspace,
41129
+ parseRelayOrigin(relayOrigin),
41130
+ validateRuntimeCredential(runtimeCredential2)
41131
+ );
41132
+ }
41133
+ function decodeConnection(value) {
41134
+ if (!isRecord9(value)) {
41135
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41136
+ }
41137
+ if (value["kind"] === "verified") {
41138
+ return decodeVerifiedConnection(value);
41139
+ }
41140
+ if (value["kind"] === "legacy_imported") {
41141
+ return decodeImportedLegacyConnection(value);
41142
+ }
41143
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41144
+ }
41145
+ function decodeLegacyConnection(value, expectedChannelId) {
41146
+ if (!isRecord9(value) || !hasExactKeys(value, CURRENT_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_CONNECTION_KEYS)) {
41147
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41148
+ }
41149
+ const channelId = value["channelId"];
41150
+ const defaultWorkspace = value["defaultWorkspace"];
41151
+ const relayOrigin = value["relayOrigin"];
41152
+ const runtimeCredential2 = value["runtimeCredential"] ?? value["daemonToken"];
41153
+ if (typeof channelId !== "string" || channelId !== expectedChannelId || typeof defaultWorkspace !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
41154
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41155
+ }
41156
+ return {
41157
+ channelId: validateIdentifier(channelId, "invalid_connection"),
41158
+ defaultWorkspace,
41159
+ relayOrigin: parseRelayOrigin(relayOrigin),
41160
+ runtimeCredential: validateRuntimeCredential(runtimeCredential2)
41161
+ };
41162
+ }
41163
+ async function readJsonFile(path2, signal, missingCode) {
41164
+ signal.throwIfAborted();
41165
+ let handle;
41166
+ try {
41167
+ handle = await open5(path2, "r");
41168
+ } catch (cause) {
41169
+ if (isNodeError(cause, "ENOENT")) {
41170
+ throw new RuntimeInstallationStoreError(missingCode, "The saved Runtime connection was not found", {
41171
+ cause
41172
+ });
41173
+ }
41174
+ throw new RuntimeInstallationStoreError(
41175
+ "connection_unavailable",
41176
+ "The saved Runtime connection cannot be read",
41177
+ {
41178
+ cause
41179
+ }
41180
+ );
41181
+ }
41182
+ let encoded = "";
41183
+ try {
41184
+ const metadata = await handle.stat();
41185
+ if (!metadata.isFile() || metadata.size > MAX_FILE_LENGTH) {
41186
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41187
+ }
41188
+ encoded = await handle.readFile({ encoding: "utf8" });
41189
+ } finally {
41190
+ await handle.close();
41191
+ }
41192
+ signal.throwIfAborted();
41193
+ try {
41194
+ return JSON.parse(encoded);
41195
+ } catch (cause) {
41196
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid", {
41197
+ cause
41198
+ });
41199
+ }
41200
+ }
41201
+ async function writeJsonAtomically(path2, value, signal) {
41202
+ signal.throwIfAborted();
41203
+ const directory = dirname7(path2);
41204
+ const temporaryPath = join16(directory, `.${randomUUID4()}.tmp`);
41205
+ try {
41206
+ await mkdir3(directory, { mode: 448, recursive: true });
41207
+ signal.throwIfAborted();
41208
+ await writeFile2(temporaryPath, `${JSON.stringify(value, null, 2)}
41209
+ `, { flag: "wx", mode: 384 });
41210
+ signal.throwIfAborted();
41211
+ await rename3(temporaryPath, path2);
41212
+ } catch (cause) {
41213
+ await unlink(temporaryPath).catch(() => void 0);
41214
+ signal.throwIfAborted();
41215
+ throw new RuntimeInstallationStoreError("connection_unavailable", "The local Runtime state cannot be written", {
41216
+ cause
41217
+ });
41218
+ }
41219
+ }
41220
+ var RuntimeInstallationStore = class _RuntimeInstallationStore {
41221
+ applicationId;
41222
+ installationId;
41223
+ stateDirectory;
41224
+ #channelDirectory;
41225
+ #connectionDirectory;
41226
+ constructor(applicationId, installationId2, stateDirectory) {
41227
+ this.applicationId = applicationId;
41228
+ this.installationId = installationId2;
41229
+ this.stateDirectory = stateDirectory;
41230
+ this.#channelDirectory = join16(stateDirectory, "channels");
41231
+ this.#connectionDirectory = join16(stateDirectory, "connections");
41232
+ }
41233
+ static open = async (options, signal) => {
41234
+ signal.throwIfAborted();
41235
+ const applicationId = validateApplicationId(options.applicationId);
41236
+ const rootDirectory = resolve5(options.stateDirectory);
41237
+ const applicationDirectory = join16(rootDirectory, "installations", applicationId);
41238
+ try {
41239
+ await mkdir3(applicationDirectory, { mode: 448, recursive: true });
41240
+ } catch (cause) {
41241
+ throw new RuntimeInstallationStoreError(
41242
+ "installation_unavailable",
41243
+ "The local installation cannot be initialized",
41244
+ {
41245
+ cause
41246
+ }
41247
+ );
41248
+ }
41249
+ const storedInstallationId = await readOrCreateInstallationId(applicationDirectory, signal);
41250
+ const stateDirectory = join16(applicationDirectory, storedInstallationId);
41251
+ try {
41252
+ await mkdir3(stateDirectory, { mode: 448, recursive: true });
41253
+ } catch (cause) {
41254
+ throw new RuntimeInstallationStoreError(
41255
+ "installation_unavailable",
41256
+ "The local installation cannot be initialized",
41257
+ {
41258
+ cause
41259
+ }
41260
+ );
41261
+ }
41262
+ signal.throwIfAborted();
41263
+ return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
41264
+ };
41265
+ connectionPath = (connectionId2) => join16(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
41266
+ auditDatabasePath = (connectionId2) => join16(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
41267
+ channelIndexPath = (channelId) => join16(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
41268
+ readConnection = async (connectionId2, signal) => {
41269
+ const stored = decodeConnection(
41270
+ await readJsonFile(this.connectionPath(connectionId2), signal, "connection_not_found")
41271
+ );
41272
+ if (stored.applicationId !== this.applicationId || stored.installationId !== this.installationId) {
41273
+ throw new RuntimeInstallationStoreError(
41274
+ "connection_owner_mismatch",
41275
+ "The saved Runtime connection belongs to another installation"
41276
+ );
41277
+ }
41278
+ return stored;
41279
+ };
41280
+ #readConnectionForChannel = async (channelId, signal) => {
41281
+ const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
41282
+ const index2 = decodeChannelIndex(
41283
+ await readJsonFile(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
41284
+ );
41285
+ if (index2.applicationId !== this.applicationId || index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
41286
+ throw new RuntimeInstallationStoreError(
41287
+ "connection_owner_mismatch",
41288
+ "The saved Runtime connection belongs to another installation"
41289
+ );
41290
+ }
41291
+ return await this.readConnection(index2.connectionId, signal);
41292
+ };
41293
+ migrateLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
41294
+ try {
41295
+ return await this.#readConnectionForChannel(channelId, signal);
41296
+ } catch (cause) {
41297
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "connection_not_found") {
41298
+ throw cause;
41299
+ }
41300
+ }
41301
+ return await this.importLegacyConnection(legacyStateDirectory, channelId, signal);
41302
+ };
41303
+ saveConnection = async (input2, signal) => {
41304
+ const stored = new VerifiedRuntimeConnection(
41305
+ this.applicationId,
41306
+ this.installationId,
41307
+ connectionId(),
41308
+ validateIdentifier(input2.channelId, "invalid_connection"),
41309
+ input2.defaultWorkspace,
41310
+ parseRelayOrigin(input2.relayOrigin.toString()),
41311
+ validateRuntimeCredential(input2.runtimeCredential),
41312
+ validateIdentifier(input2.runtimeId, "invalid_connection")
41313
+ );
41314
+ await this.writeConnection(stored, signal);
41315
+ return stored;
41316
+ };
41317
+ importLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
41318
+ const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
41319
+ const legacyPath = join16(resolve5(legacyStateDirectory), "connections", `${normalizedChannelId}.json`);
41320
+ const legacy = decodeLegacyConnection(
41321
+ await readJsonFile(legacyPath, signal, "connection_not_found"),
41322
+ normalizedChannelId
41323
+ );
41324
+ const stored = new ImportedLegacyRuntimeConnection(
41325
+ this.applicationId,
41326
+ this.installationId,
41327
+ connectionId(),
41328
+ legacy.channelId,
41329
+ legacy.defaultWorkspace,
41330
+ legacy.relayOrigin,
41331
+ legacy.runtimeCredential
41332
+ );
41333
+ await this.writeConnection(stored, signal);
41334
+ return stored;
41335
+ };
41336
+ writeConnection = async (stored, signal) => {
41337
+ signal.throwIfAborted();
41338
+ try {
41339
+ await this.#readConnectionForChannel(stored.channelId, signal);
41340
+ throw new RuntimeInstallationStoreError(
41341
+ "connection_conflict",
41342
+ "A Runtime connection for this channel already exists in this installation"
41343
+ );
41344
+ } catch (cause) {
41345
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "connection_not_found") {
41346
+ throw cause;
41347
+ }
41348
+ }
41349
+ const connectionPath = this.connectionPath(stored.connectionId);
41350
+ if (stored instanceof VerifiedRuntimeConnection) {
41351
+ await writeJsonAtomically(
41352
+ connectionPath,
41353
+ {
41354
+ applicationId: stored.applicationId,
41355
+ channelId: stored.channelId,
41356
+ connectionId: stored.connectionId,
41357
+ defaultWorkspace: stored.defaultWorkspace,
41358
+ installationId: stored.installationId,
41359
+ kind: stored.kind,
41360
+ relayOrigin: stored.relayOrigin.toString(),
41361
+ runtimeCredential: stored.runtimeCredential,
41362
+ runtimeId: stored.runtimeId,
41363
+ version: 1
41364
+ },
41365
+ signal
41366
+ );
41367
+ } else {
41368
+ await writeJsonAtomically(
41369
+ connectionPath,
41370
+ {
41371
+ applicationId: stored.applicationId,
41372
+ channelId: stored.channelId,
41373
+ connectionId: stored.connectionId,
41374
+ defaultWorkspace: stored.defaultWorkspace,
41375
+ installationId: stored.installationId,
41376
+ kind: stored.kind,
41377
+ relayOrigin: stored.relayOrigin.toString(),
41378
+ runtimeCredential: stored.runtimeCredential,
41379
+ version: 1
41380
+ },
41381
+ signal
41382
+ );
41383
+ }
41384
+ await writeJsonAtomically(
41385
+ this.channelIndexPath(stored.channelId),
41386
+ {
41387
+ applicationId: this.applicationId,
41388
+ channelId: stored.channelId,
41389
+ connectionId: stored.connectionId,
41390
+ installationId: this.installationId,
41391
+ version: 1
41392
+ },
41393
+ signal
41394
+ );
41395
+ };
41396
+ };
41397
+ async function readOrCreateInstallationId(applicationDirectory, signal) {
41398
+ const pointerPath = join16(applicationDirectory, "current.json");
41399
+ try {
41400
+ return decodeInstallationPointer(await readJsonFile(pointerPath, signal, "installation_not_found")).installationId;
41401
+ } catch (cause) {
41402
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "installation_not_found") {
41403
+ throw cause;
41404
+ }
41405
+ }
41406
+ const candidate = installationId();
41407
+ try {
41408
+ await writeFile2(pointerPath, `${JSON.stringify({ installationId: candidate, version: 1 })}
41409
+ `, {
41410
+ flag: "wx",
41411
+ mode: 384
41412
+ });
41413
+ return candidate;
41414
+ } catch (cause) {
41415
+ if (!isNodeError(cause, "EEXIST")) {
41416
+ throw new RuntimeInstallationStoreError(
41417
+ "installation_unavailable",
41418
+ "The local installation cannot be initialized",
41419
+ {
41420
+ cause
41421
+ }
41422
+ );
41423
+ }
41424
+ return decodeInstallationPointer(await readJsonFile(pointerPath, signal, "installation_not_found")).installationId;
41425
+ }
41426
+ }
41427
+ async function openRuntimeInstallationStore(options, signal) {
41428
+ return await RuntimeInstallationStore.open(options, signal);
41429
+ }
41430
+
41431
+ // src/pairing/pair-local-machine.ts
40871
41432
  var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
40872
41433
  var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
40873
- var IDENTIFIER_PATTERN6 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
41434
+ var IDENTIFIER_PATTERN7 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
40874
41435
  var TOKEN_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
40875
- var MAX_CONNECTION_FILE_LENGTH = 16 * 1024;
40876
41436
  var CLAIM_RESPONSE_KEYS = ["channelId", "daemonToken", "runtimeId"];
40877
41437
  var REDEEM_RESPONSE_KEYS = ["channelId", "runtimeCredential", "runtimeId"];
40878
- var LEGACY_SAVED_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "daemonToken", "relayOrigin"];
40879
- var SAVED_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "relayOrigin", "runtimeCredential"];
40880
41438
  var PairingClientError = class extends Error {
40881
41439
  code;
40882
41440
  constructor(code, message, options = {}) {
@@ -40885,14 +41443,14 @@ var PairingClientError = class extends Error {
40885
41443
  this.name = "PairingClientError";
40886
41444
  }
40887
41445
  };
40888
- function isRecord9(value) {
41446
+ function isRecord10(value) {
40889
41447
  return typeof value === "object" && value !== null && !Array.isArray(value);
40890
41448
  }
40891
- function hasExactKeys(value, expectedKeys) {
41449
+ function hasExactKeys2(value, expectedKeys) {
40892
41450
  const keys = Object.keys(value);
40893
41451
  return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
40894
41452
  }
40895
- function parseRelayOrigin(value) {
41453
+ function parseRelayOrigin2(value) {
40896
41454
  let url2;
40897
41455
  try {
40898
41456
  url2 = new URL(value);
@@ -40924,15 +41482,15 @@ function parsePairingCode(value) {
40924
41482
  return code;
40925
41483
  }
40926
41484
  function validatePairingId(value) {
40927
- if (!IDENTIFIER_PATTERN6.test(value)) {
41485
+ if (!IDENTIFIER_PATTERN7.test(value)) {
40928
41486
  throw new PairingClientError("invalid_pairing_id", "The Runtime pairing ID is invalid");
40929
41487
  }
40930
41488
  return value;
40931
41489
  }
40932
41490
  async function resolveDefaultWorkspace2(path2) {
40933
- const requestedWorkspace = resolve4(path2);
41491
+ const requestedWorkspace = resolve6(path2);
40934
41492
  try {
40935
- await mkdir3(requestedWorkspace, { recursive: true, mode: 448 });
41493
+ await mkdir4(requestedWorkspace, { recursive: true, mode: 448 });
40936
41494
  const defaultWorkspace = await realpath9(requestedWorkspace);
40937
41495
  const metadata = await stat8(defaultWorkspace);
40938
41496
  if (!metadata.isDirectory()) {
@@ -40963,9 +41521,9 @@ async function readJsonResponse(response) {
40963
41521
  }
40964
41522
  }
40965
41523
  function readRelayError(value) {
40966
- if (isRecord9(value)) {
41524
+ if (isRecord10(value)) {
40967
41525
  const error62 = value["error"];
40968
- if (isRecord9(error62)) {
41526
+ if (isRecord10(error62)) {
40969
41527
  const code = error62["code"];
40970
41528
  const message = error62["message"];
40971
41529
  if (typeof code === "string" && typeof message === "string") {
@@ -40976,13 +41534,13 @@ function readRelayError(value) {
40976
41534
  return new PairingClientError("pairing_failed", "The relay could not pair this machine");
40977
41535
  }
40978
41536
  function decodePairingResponse(value, credentialField, expectedKeys) {
40979
- if (!isRecord9(value) || !hasExactKeys(value, expectedKeys)) {
41537
+ if (!isRecord10(value) || !hasExactKeys2(value, expectedKeys)) {
40980
41538
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
40981
41539
  }
40982
41540
  const channelId = value["channelId"];
40983
41541
  const runtimeCredential2 = value[credentialField];
40984
41542
  const runtimeId = value["runtimeId"];
40985
- if (typeof channelId !== "string" || !IDENTIFIER_PATTERN6.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN6.test(runtimeId)) {
41543
+ if (typeof channelId !== "string" || !IDENTIFIER_PATTERN7.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN7.test(runtimeId)) {
40986
41544
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
40987
41545
  }
40988
41546
  return { channelId, runtimeCredential: runtimeCredential2, runtimeId };
@@ -41022,156 +41580,88 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
41022
41580
  }
41023
41581
  return options.pairingId.length > 0 ? decodePairingResponse(value, "runtimeCredential", REDEEM_RESPONSE_KEYS) : decodePairingResponse(value, "daemonToken", CLAIM_RESPONSE_KEYS);
41024
41582
  }
41025
- async function persistConnection(channelId, relayOrigin, runtimeCredential2, defaultWorkspace, environment) {
41026
- const connectionsDirectory = join16(readStateDirectory(environment), "connections");
41027
- await mkdir3(connectionsDirectory, { mode: 448, recursive: true });
41028
- const connectionPath = join16(connectionsDirectory, `${channelId}.json`);
41029
- const temporaryPath = join16(connectionsDirectory, `.${channelId}.${randomUUID4()}.tmp`);
41030
- await writeFile2(
41031
- temporaryPath,
41032
- `${JSON.stringify(
41033
- {
41034
- defaultWorkspace,
41035
- channelId,
41036
- relayOrigin: relayOrigin.toString(),
41037
- runtimeCredential: runtimeCredential2
41038
- },
41039
- null,
41040
- 2
41041
- )}
41042
- `,
41043
- { flag: "wx", mode: 384 }
41044
- );
41045
- await rename3(temporaryPath, connectionPath);
41046
- return connectionPath;
41047
- }
41048
- function decodeSavedConnection(value, expectedChannelId) {
41049
- if (!isRecord9(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
41050
- throw new PairingClientError("invalid_connection", "The saved connection is invalid");
41051
- }
41052
- const defaultWorkspace = value["defaultWorkspace"];
41053
- const channelId = value["channelId"];
41054
- const runtimeCredential2 = value["runtimeCredential"] ?? value["daemonToken"];
41055
- const relayOrigin = value["relayOrigin"];
41056
- if (typeof defaultWorkspace !== "string" || typeof channelId !== "string" || channelId !== expectedChannelId || !IDENTIFIER_PATTERN6.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof relayOrigin !== "string") {
41057
- throw new PairingClientError("invalid_connection", "The saved connection is invalid");
41058
- }
41059
- return {
41060
- defaultWorkspace,
41061
- channelId,
41062
- relayOrigin: parseRelayOrigin(relayOrigin),
41063
- runtimeCredential: runtimeCredential2
41064
- };
41065
- }
41066
- async function readSavedConnection(channelId, environment) {
41067
- const connectionPath = join16(readStateDirectory(environment), "connections", `${channelId}.json`);
41068
- let encoded = "";
41069
- const handle = await open5(connectionPath, "r");
41070
- try {
41071
- const metadata = await handle.stat();
41072
- if (!metadata.isFile() || metadata.size > MAX_CONNECTION_FILE_LENGTH) {
41073
- throw new PairingClientError("invalid_connection", "The saved connection is invalid");
41074
- }
41075
- encoded = await handle.readFile({ encoding: "utf8" });
41076
- } finally {
41077
- await handle.close();
41078
- }
41079
- let value;
41080
- try {
41081
- value = JSON.parse(encoded);
41082
- } catch (error62) {
41083
- throw new PairingClientError("invalid_connection", "The saved connection is invalid", { cause: error62 });
41084
- }
41085
- const connection = decodeSavedConnection(value, channelId);
41086
- return {
41087
- defaultWorkspace: await resolveDefaultWorkspace2(connection.defaultWorkspace),
41088
- channelId: connection.channelId,
41089
- relayOrigin: connection.relayOrigin,
41090
- runtimeCredential: connection.runtimeCredential
41091
- };
41092
- }
41093
41583
  function assertInventoryUsable(inventory) {
41094
41584
  if (inventory.available.length + inventory.installable.length === 0) {
41095
41585
  throw new PairingClientError("no_supported_agent", "No supported Agent is available for local discovery");
41096
41586
  }
41097
41587
  }
41098
- function buildPairedDaemon(connection, connectionPath, inventory, environment) {
41588
+ function buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext) {
41099
41589
  assertInventoryUsable(inventory);
41100
41590
  const relayUrl = mobiusApiUrl(connection.relayOrigin, "/v1/runtimes/connect");
41101
41591
  relayUrl.protocol = relayUrl.protocol === "https:" ? "wss:" : "ws:";
41102
41592
  relayUrl.searchParams.set("token", connection.runtimeCredential);
41103
- const auditDatabasePath = join16(readStateDirectory(environment), "audit", `${connection.channelId}.sqlite`);
41104
41593
  return {
41105
41594
  channelUrl: new URL(`/channels/${encodeURIComponent(connection.channelId)}`, connection.relayOrigin).toString(),
41595
+ connectionId: connection.connectionId,
41106
41596
  config: createDaemonConfig(
41107
41597
  {
41108
- defaultWorkspace: connection.defaultWorkspace,
41109
- auditDatabasePath,
41598
+ defaultWorkspace,
41599
+ auditDatabasePath: installation.auditDatabasePath(connection.connectionId),
41110
41600
  channelId: connection.channelId,
41111
41601
  relayUrl
41112
41602
  },
41113
41603
  inventory.readyAgents(),
41114
- inventory.installable
41604
+ inventory.installable,
41605
+ localContext,
41606
+ new OpaqueDaemonReconnectTarget(connection.connectionId)
41115
41607
  ),
41116
- connectionPath
41608
+ connectionPath: installation.connectionPath(connection.connectionId)
41117
41609
  };
41118
41610
  }
41119
- async function pairRuntime(options, signal, environment) {
41611
+ async function pairRuntime(installation, options, signal, environment) {
41612
+ const localContext = new DaemonLocalContext(installation.stateDirectory, environment);
41120
41613
  const defaultWorkspace = await resolveDefaultWorkspace2(options.workspace);
41121
41614
  const inventory = await discoverLocalAgentInventory({
41122
41615
  defaultWorkspace,
41123
- environment,
41616
+ environment: localContext.environment,
41124
41617
  signal
41125
41618
  });
41126
41619
  assertInventoryUsable(inventory);
41127
41620
  const agents = inventory.readyAgents();
41128
41621
  const claim2 = await claimPairing(options, defaultWorkspace, agents, inventory.installable, signal);
41129
- const connectionPath = await persistConnection(
41130
- claim2.channelId,
41131
- options.relayOrigin,
41132
- claim2.runtimeCredential,
41133
- defaultWorkspace,
41134
- environment
41135
- );
41136
- return buildPairedDaemon(
41622
+ const connection = await installation.saveConnection(
41137
41623
  {
41138
- defaultWorkspace,
41139
41624
  channelId: claim2.channelId,
41625
+ defaultWorkspace,
41140
41626
  relayOrigin: options.relayOrigin,
41141
- runtimeCredential: claim2.runtimeCredential
41627
+ runtimeCredential: claim2.runtimeCredential,
41628
+ runtimeId: claim2.runtimeId
41142
41629
  },
41143
- connectionPath,
41144
- inventory,
41145
- environment
41630
+ signal
41146
41631
  );
41632
+ return buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext);
41147
41633
  }
41148
- async function pairMobiusRuntime(options, signal, environment = process.env) {
41634
+ async function pairMobiusRuntime(installation, options, signal, environment = process.env) {
41149
41635
  return await pairRuntime(
41636
+ installation,
41150
41637
  {
41151
41638
  code: parsePairingCode(options.pairingCode),
41152
41639
  pairingId: validatePairingId(options.pairingId),
41153
- relayOrigin: parseRelayOrigin(options.relayOrigin),
41640
+ relayOrigin: parseRelayOrigin2(options.relayOrigin),
41154
41641
  workspace: options.defaultWorkspace
41155
41642
  },
41156
41643
  signal,
41157
41644
  environment
41158
41645
  );
41159
41646
  }
41160
- async function resumeMobiusRuntime(channelId, signal, environment = process.env) {
41161
- const normalizedChannelId = validatePairingId(channelId);
41162
- const connectionPath = join16(readStateDirectory(environment), "connections", `${normalizedChannelId}.json`);
41163
- const connection = await readSavedConnection(normalizedChannelId, environment);
41647
+ async function resumeRuntimeConnection(installation, connection, signal, environment) {
41648
+ const localContext = new DaemonLocalContext(installation.stateDirectory, environment);
41649
+ const defaultWorkspace = await resolveDefaultWorkspace2(connection.defaultWorkspace);
41164
41650
  const inventory = await discoverLocalAgentInventory({
41165
- defaultWorkspace: connection.defaultWorkspace,
41166
- environment,
41651
+ defaultWorkspace,
41652
+ environment: localContext.environment,
41167
41653
  signal
41168
41654
  });
41169
- return buildPairedDaemon(connection, connectionPath, inventory, environment);
41655
+ return buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext);
41656
+ }
41657
+ async function resumeMobiusRuntime(installation, connectionId2, signal, environment = process.env) {
41658
+ const connection = await installation.readConnection(connectionId2, signal);
41659
+ return await resumeRuntimeConnection(installation, connection, signal, environment);
41170
41660
  }
41171
41661
 
41172
41662
  // src/runtime.ts
41173
- var IDENTIFIER_PATTERN7 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
41174
- var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
41663
+ var IDENTIFIER_PATTERN8 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
41664
+ var RUNTIME_CREDENTIAL_PATTERN2 = /^[a-zA-Z0-9_-]{32,256}$/;
41175
41665
  var MobiusRuntimeConfigurationError = class extends Error {
41176
41666
  code = "runtime_configuration_invalid";
41177
41667
  constructor(message, options = {}) {
@@ -41195,7 +41685,7 @@ function validateRuntimeRelay(relayUrl) {
41195
41685
  if (credential.length === 0) {
41196
41686
  throw new MobiusRuntimeConfigurationError("The Runtime relay credential is required");
41197
41687
  }
41198
- if (!RUNTIME_CREDENTIAL_PATTERN.test(credential)) {
41688
+ if (!RUNTIME_CREDENTIAL_PATTERN2.test(credential)) {
41199
41689
  throw new MobiusRuntimeConfigurationError("The Runtime relay credential is invalid");
41200
41690
  }
41201
41691
  }
@@ -41222,7 +41712,7 @@ function relayUrlFromConnection(connection) {
41222
41712
  }
41223
41713
  function loadMobiusRuntimeConnection(environment = process.env) {
41224
41714
  const channelId = requiredEnvironmentValue(environment, "MOBIUS_CHANNEL_ID");
41225
- if (!IDENTIFIER_PATTERN7.test(channelId)) {
41715
+ if (!IDENTIFIER_PATTERN8.test(channelId)) {
41226
41716
  throw new MobiusRuntimeConfigurationError("MOBIUS_CHANNEL_ID is invalid");
41227
41717
  }
41228
41718
  return Object.freeze({
@@ -41234,9 +41724,9 @@ function loadMobiusRuntimeConnection(environment = process.env) {
41234
41724
  });
41235
41725
  }
41236
41726
  async function resolveWorkspace(path2) {
41237
- const requested = resolve5(path2);
41727
+ const requested = resolve7(path2);
41238
41728
  try {
41239
- await mkdir4(requested, { recursive: true, mode: 448 });
41729
+ await mkdir5(requested, { recursive: true, mode: 448 });
41240
41730
  const resolved = await realpath10(requested);
41241
41731
  const metadata = await stat9(resolved);
41242
41732
  if (!metadata.isDirectory()) {
@@ -41252,13 +41742,14 @@ async function resolveWorkspace(path2) {
41252
41742
  }
41253
41743
  async function createMobiusRuntimeEngine(connection, signal, environment = process.env) {
41254
41744
  signal.throwIfAborted();
41745
+ const localContext = new DaemonLocalContext(readStateDirectory(environment), environment);
41255
41746
  const relayUrl = relayUrlFromConnection(connection);
41256
41747
  const defaultWorkspace = await resolveWorkspace(connection.defaultWorkspace);
41257
- const auditDatabasePath = resolve5(connection.auditDatabasePath);
41258
- await mkdir4(dirname7(auditDatabasePath), { recursive: true, mode: 448 });
41748
+ const auditDatabasePath = resolve7(connection.auditDatabasePath);
41749
+ await mkdir5(dirname8(auditDatabasePath), { recursive: true, mode: 448 });
41259
41750
  const inventory = await discoverLocalAgentInventory({
41260
41751
  defaultWorkspace,
41261
- environment,
41752
+ environment: localContext.environment,
41262
41753
  signal
41263
41754
  });
41264
41755
  if (inventory.available.length + inventory.installable.length === 0) {
@@ -41273,7 +41764,8 @@ async function createMobiusRuntimeEngine(connection, signal, environment = proce
41273
41764
  relayUrl
41274
41765
  },
41275
41766
  inventory.readyAgents(),
41276
- inventory.installable
41767
+ inventory.installable,
41768
+ localContext
41277
41769
  )
41278
41770
  );
41279
41771
  }
@@ -41300,12 +41792,22 @@ var MobiusRuntimeEngine = class {
41300
41792
  };
41301
41793
  };
41302
41794
  export {
41795
+ ChannelDaemonReconnectTarget,
41796
+ DaemonLocalContext,
41797
+ DaemonReconnectTarget,
41798
+ ImportedLegacyRuntimeConnection,
41303
41799
  MobiusRuntimeConfigurationError,
41304
41800
  MobiusRuntimeEngine,
41801
+ OpaqueDaemonReconnectTarget,
41305
41802
  PairingClientError,
41803
+ RuntimeInstallationStore,
41804
+ RuntimeInstallationStoreError,
41805
+ StoredRuntimeConnection,
41806
+ VerifiedRuntimeConnection,
41306
41807
  createDaemonConfig,
41307
41808
  createMobiusRuntimeEngine,
41308
41809
  loadMobiusRuntimeConnection,
41810
+ openRuntimeInstallationStore,
41309
41811
  pairMobiusRuntime,
41310
41812
  resumeMobiusRuntime
41311
41813
  };