@moxt-ai/mobius 0.0.49 → 0.0.51

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);
@@ -33577,6 +33607,7 @@ var AcpProcessSession = class _AcpProcessSession {
33577
33607
  belongsTo = (agentId, cwd, additionalDirectories) => this.#agentId === agentId && this.#cwd === cwd && arraysEqual(this.#additionalDirectories, additionalDirectories);
33578
33608
  usesEnvironment = (environment) => recordsEqual(this.#environment, environment);
33579
33609
  canRebind = () => !this.#prompted && !this.#turn.running;
33610
+ hasRunningTurn = () => this.#turn.running;
33580
33611
  prepared = () => new AcpPreparedSession(
33581
33612
  this.#agentName,
33582
33613
  this.#agentVersion,
@@ -35060,7 +35091,6 @@ var AcpSessionManager = class {
35060
35091
  const operation = (async () => {
35061
35092
  try {
35062
35093
  await this.#retireSessionProcess(options.sessionId, existing, async () => await existing.close());
35063
- this.#store.remove(options.sessionId);
35064
35094
  const runtime = await this.#startRetainedSessionProcess(
35065
35095
  options,
35066
35096
  async () => await AcpProcessSession.start(options, () => this.#observer, this.#store)
@@ -35100,7 +35130,6 @@ var AcpSessionManager = class {
35100
35130
  }
35101
35131
  } catch (error62) {
35102
35132
  await this.#retireSessionProcess(options.sessionId, runtime, async () => await runtime.close());
35103
- this.#store.remove(options.sessionId);
35104
35133
  throw error62;
35105
35134
  }
35106
35135
  return runtime;
@@ -35220,11 +35249,11 @@ var AcpSessionManager = class {
35220
35249
  this.#touchExpectedSession(options.sessionId, existing);
35221
35250
  return existing.prepared();
35222
35251
  }
35223
- if (!existing.canRebind()) {
35252
+ if (existing.hasRunningTurn()) {
35224
35253
  throw new AcpExecutionError(
35225
- "The execution environment cannot change after a conversation has started",
35254
+ "The execution environment cannot change while a conversation turn is running",
35226
35255
  {},
35227
- "session_identity_mismatch"
35256
+ "session_busy"
35228
35257
  );
35229
35258
  }
35230
35259
  return (await this.#replaceExecutionPreparation(existing, options)).prepared();
@@ -36061,7 +36090,7 @@ var AgentInstallationManager = class {
36061
36090
 
36062
36091
  // src/agent-installation/fixed-installation-executor.ts
36063
36092
  import { realpathSync as realpathSync2, statSync as statSync2 } from "node:fs";
36064
- import { resolve as resolve3 } from "node:path";
36093
+ import { resolve as resolve4 } from "node:path";
36065
36094
  function findSpecification(specifications, agentId) {
36066
36095
  for (const specification of specifications) {
36067
36096
  if (specification.id === agentId) {
@@ -36072,7 +36101,7 @@ function findSpecification(specifications, agentId) {
36072
36101
  }
36073
36102
  function resolveDefaultWorkspace(path2) {
36074
36103
  try {
36075
- const directory = realpathSync2(resolve3(path2));
36104
+ const directory = realpathSync2(resolve4(path2));
36076
36105
  if (!statSync2(directory).isDirectory()) {
36077
36106
  throw new Error("Default workspace is not a directory");
36078
36107
  }
@@ -36087,7 +36116,7 @@ function resolveDefaultWorkspace(path2) {
36087
36116
  }
36088
36117
  function resolveIntegrationStateDirectory(path2) {
36089
36118
  try {
36090
- const directory = realpathSync2(resolve3(path2));
36119
+ const directory = realpathSync2(resolve4(path2));
36091
36120
  const metadata = statSync2(directory);
36092
36121
  if (!metadata.isDirectory() || typeof process.getuid === "function" && metadata.uid !== process.getuid()) {
36093
36122
  throw new Error("Installation directory is not user-owned");
@@ -37783,7 +37812,7 @@ var RelayConnectionError = class extends Error {
37783
37812
  };
37784
37813
  function connectRelay(url2, signal) {
37785
37814
  signal.throwIfAborted();
37786
- return new Promise((resolve6, reject) => {
37815
+ return new Promise((resolve8, reject) => {
37787
37816
  const endpoint = new URL(url2);
37788
37817
  const headers = runtimeAuthorization(endpoint);
37789
37818
  endpoint.searchParams.delete("token");
@@ -37846,7 +37875,7 @@ function connectRelay(url2, signal) {
37846
37875
  }
37847
37876
  finished = true;
37848
37877
  cleanup();
37849
- resolve6(socket);
37878
+ resolve8(socket);
37850
37879
  };
37851
37880
  function onTimeout() {
37852
37881
  fail(
@@ -39493,10 +39522,11 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
39493
39522
  "prompt_queue_target_unavailable"
39494
39523
  );
39495
39524
  }
39525
+ const executionAgent = command.sessionConfigurations === void 0 ? agent : agentForSessionConfiguration(agent, command.sessionConfigurations);
39496
39526
  if (command.sessionConfigurations !== void 0) {
39497
39527
  const prepared = await sessions.prepareExecutionSession({
39498
39528
  additionalDirectories: resolved.additionalDirectories,
39499
- agent,
39529
+ agent: executionAgent,
39500
39530
  cwd: resolved.cwd,
39501
39531
  sessionId: command.sessionId,
39502
39532
  signal
@@ -39509,7 +39539,7 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
39509
39539
  audit,
39510
39540
  prepared.configOptions,
39511
39541
  command.sessionConfigurations,
39512
- agent,
39542
+ executionAgent,
39513
39543
  resolved.cwd,
39514
39544
  resolved.additionalDirectories,
39515
39545
  command.commandId,
@@ -39540,7 +39570,7 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
39540
39570
  if (command.disposition === SessionPromptDisposition.Steer) {
39541
39571
  await sessions.steerPrompt({
39542
39572
  additionalDirectories: resolved.additionalDirectories,
39543
- agent,
39573
+ agent: executionAgent,
39544
39574
  commandId: command.commandId,
39545
39575
  cwd: resolved.cwd,
39546
39576
  images: attachments.images,
@@ -39554,7 +39584,7 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
39554
39584
  } else {
39555
39585
  const result = await sessions.runPrompt({
39556
39586
  additionalDirectories: resolved.additionalDirectories,
39557
- agent,
39587
+ agent: executionAgent,
39558
39588
  commandId: command.commandId,
39559
39589
  cwd: resolved.cwd,
39560
39590
  disposition: command.disposition,
@@ -39621,6 +39651,16 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
39621
39651
  function invalidSessionConfiguration(message) {
39622
39652
  return new AcpExecutionError(message, {}, "invalid_session_configuration");
39623
39653
  }
39654
+ function agentForSessionConfiguration(agent, selections) {
39655
+ const permission = selections.find((selection) => selection.configId === AGENT_PERMISSION_MODE_CONFIG_ID);
39656
+ if (permission === void 0) {
39657
+ throw invalidSessionConfiguration(
39658
+ `The Turn configuration does not match Agent setting ${AGENT_PERMISSION_MODE_CONFIG_ID}`
39659
+ );
39660
+ }
39661
+ validateSessionConfigurationSelection(agent.permissionProfile.option(agent.environment), permission);
39662
+ return agent.withPermissionMode(permission.value);
39663
+ }
39624
39664
  function validateSessionConfigurationSelection(option, selection) {
39625
39665
  if (option.type !== selection.valueType) {
39626
39666
  throw invalidSessionConfiguration(`The Agent setting ${selection.configId} changed type`);
@@ -39844,12 +39884,12 @@ function waitForRelayRetry(signal, timer) {
39844
39884
  if (signal.aborted) {
39845
39885
  return Promise.resolve();
39846
39886
  }
39847
- return new Promise((resolve6) => {
39887
+ return new Promise((resolve8) => {
39848
39888
  const retry = timer.schedule(finish, RELAY_RECONNECT_DELAY_MILLISECONDS);
39849
39889
  function finish() {
39850
39890
  retry.cancel();
39851
39891
  signal.removeEventListener("abort", finish);
39852
- resolve6();
39892
+ resolve8();
39853
39893
  }
39854
39894
  signal.addEventListener("abort", finish, { once: true });
39855
39895
  });
@@ -39905,7 +39945,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39905
39945
  installationObserver.connect(socket);
39906
39946
  onConnected();
39907
39947
  try {
39908
- await new Promise((resolve6, reject) => {
39948
+ await new Promise((resolve8, reject) => {
39909
39949
  let finished = false;
39910
39950
  const cleanup = () => {
39911
39951
  connectionLiveness.close();
@@ -39923,7 +39963,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
39923
39963
  }
39924
39964
  finished = true;
39925
39965
  cleanup();
39926
- resolve6();
39966
+ resolve8();
39927
39967
  };
39928
39968
  const rejectConnection = (failure2) => {
39929
39969
  if (finished) {
@@ -40370,7 +40410,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40370
40410
  try {
40371
40411
  operationSignal.throwIfAborted();
40372
40412
  if (previous2.length > 0) {
40373
- await new Promise((resolve7, reject2) => {
40413
+ await new Promise((resolve9, reject2) => {
40374
40414
  const cancel = () => reject2(operationSignal.reason);
40375
40415
  operationSignal.addEventListener("abort", cancel, {
40376
40416
  once: true
@@ -40378,7 +40418,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40378
40418
  void Promise.all(previous2.map((request) => request.completion)).then(
40379
40419
  () => {
40380
40420
  operationSignal.removeEventListener("abort", cancel);
40381
- resolve7();
40421
+ resolve9();
40382
40422
  },
40383
40423
  (error62) => {
40384
40424
  operationSignal.removeEventListener("abort", cancel);
@@ -40452,13 +40492,13 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40452
40492
  try {
40453
40493
  operationSignal.throwIfAborted();
40454
40494
  if (previous2.length > 0) {
40455
- await new Promise((resolve7, reject2) => {
40495
+ await new Promise((resolve9, reject2) => {
40456
40496
  const cancel = () => reject2(operationSignal.reason);
40457
40497
  operationSignal.addEventListener("abort", cancel, { once: true });
40458
40498
  void Promise.all(previous2.map((request) => request.completion)).then(
40459
40499
  () => {
40460
40500
  operationSignal.removeEventListener("abort", cancel);
40461
- resolve7();
40501
+ resolve9();
40462
40502
  },
40463
40503
  (error62) => {
40464
40504
  operationSignal.removeEventListener("abort", cancel);
@@ -40713,13 +40753,13 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40713
40753
  }
40714
40754
  async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
40715
40755
  const installationAudit = new AuditInstallationEvents(audit);
40716
- const stateDirectory = readStateDirectory();
40756
+ const stateDirectory = config2.localContext.stateDirectory;
40717
40757
  const specifications = supportedLocalAgentSpecifications();
40718
40758
  const installationExecutor = new FixedInstallationExecutor({
40719
40759
  defaultWorkspace: config2.defaultWorkspace,
40720
40760
  audit: installationAudit,
40721
40761
  catalog: config2.catalog,
40722
- environment: process.env,
40762
+ environment: config2.localContext.environment,
40723
40763
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
40724
40764
  stateDirectory
40725
40765
  });
@@ -40778,10 +40818,10 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
40778
40818
  return;
40779
40819
  }
40780
40820
  connectionAnnounced = true;
40781
- const reconnectCommand = `npx --yes @moxt-ai/mobius start --channel ${config2.channelId}`;
40821
+ const reconnectCommand = `npx --yes @moxt-ai/mobius start ${config2.reconnectTarget.commandArgument}`;
40782
40822
  process.stdout.write("Mobius daemon connected to the relay.\n\n");
40783
40823
  process.stdout.write(
40784
- `${styleText(["bold", "yellow"], `Reconnect this channel later:
40824
+ `${styleText(["bold", "yellow"], `Reconnect this local connection later:
40785
40825
  ${reconnectCommand}`)}
40786
40826
 
40787
40827
  `
@@ -40863,20 +40903,548 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
40863
40903
  }
40864
40904
 
40865
40905
  // 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";
40906
+ import { mkdir as mkdir4, realpath as realpath9, stat as stat8 } from "node:fs/promises";
40868
40907
  import { hostname as hostname3 } from "node:os";
40869
- import { basename as basename7, join as join16, resolve as resolve4 } from "node:path";
40908
+ import { basename as basename7, resolve as resolve6 } from "node:path";
40870
40909
  import { fetch as fetch6 } from "undici";
40910
+
40911
+ // src/storage/runtime-installation-store.ts
40912
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
40913
+ import { mkdir as mkdir3, open as open5, rename as rename3, unlink, writeFile as writeFile2 } from "node:fs/promises";
40914
+ import { dirname as dirname7, join as join16, resolve as resolve5 } from "node:path";
40915
+ var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
40916
+ var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
40917
+ var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
40918
+ var IDENTIFIER_PATTERN6 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
40919
+ var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
40920
+ var MAX_FILE_LENGTH = 16 * 1024;
40921
+ var INSTALLATION_POINTER_KEYS = ["installationId", "version"];
40922
+ var CHANNEL_INDEX_KEYS = [
40923
+ "applicationId",
40924
+ "channelId",
40925
+ "connectionId",
40926
+ "installationId",
40927
+ "version"
40928
+ ];
40929
+ var VERIFIED_CONNECTION_KEYS = [
40930
+ "applicationId",
40931
+ "channelId",
40932
+ "connectionId",
40933
+ "defaultWorkspace",
40934
+ "installationId",
40935
+ "kind",
40936
+ "relayOrigin",
40937
+ "runtimeCredential",
40938
+ "runtimeId",
40939
+ "version"
40940
+ ];
40941
+ var IMPORTED_LEGACY_CONNECTION_KEYS = [
40942
+ "applicationId",
40943
+ "channelId",
40944
+ "connectionId",
40945
+ "defaultWorkspace",
40946
+ "installationId",
40947
+ "kind",
40948
+ "relayOrigin",
40949
+ "runtimeCredential",
40950
+ "version"
40951
+ ];
40952
+ var CURRENT_CONNECTION_KEYS = [
40953
+ "defaultWorkspace",
40954
+ "channelId",
40955
+ "relayOrigin",
40956
+ "runtimeCredential"
40957
+ ];
40958
+ var LEGACY_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "daemonToken", "relayOrigin"];
40959
+ var RuntimeInstallationStoreError = class extends Error {
40960
+ code;
40961
+ constructor(code, message, options = {}) {
40962
+ super(message, options);
40963
+ this.code = code;
40964
+ this.name = "RuntimeInstallationStoreError";
40965
+ }
40966
+ };
40967
+ var StoredRuntimeConnection = class {
40968
+ applicationId;
40969
+ channelId;
40970
+ connectionId;
40971
+ defaultWorkspace;
40972
+ installationId;
40973
+ relayOrigin;
40974
+ runtimeCredential;
40975
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
40976
+ this.applicationId = applicationId;
40977
+ this.channelId = channelId;
40978
+ this.connectionId = connectionId2;
40979
+ this.defaultWorkspace = defaultWorkspace;
40980
+ this.installationId = installationId2;
40981
+ this.relayOrigin = relayOrigin;
40982
+ this.runtimeCredential = runtimeCredential2;
40983
+ }
40984
+ };
40985
+ var VerifiedRuntimeConnection = class extends StoredRuntimeConnection {
40986
+ kind = "verified";
40987
+ runtimeId;
40988
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2, runtimeId) {
40989
+ super(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2);
40990
+ this.runtimeId = runtimeId;
40991
+ }
40992
+ };
40993
+ var ImportedLegacyRuntimeConnection = class extends StoredRuntimeConnection {
40994
+ kind = "legacy_imported";
40995
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
40996
+ super(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2);
40997
+ }
40998
+ };
40999
+ function isRecord9(value) {
41000
+ return typeof value === "object" && value !== null && !Array.isArray(value);
41001
+ }
41002
+ function hasExactKeys(value, expectedKeys) {
41003
+ const keys = Object.keys(value);
41004
+ return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
41005
+ }
41006
+ function isNodeError(error62, code) {
41007
+ return typeof error62 === "object" && error62 !== null && "code" in error62 && error62.code === code;
41008
+ }
41009
+ function validateApplicationId(value) {
41010
+ if (!APPLICATION_ID_PATTERN.test(value)) {
41011
+ throw new RuntimeInstallationStoreError("invalid_application_id", "The application ID is invalid");
41012
+ }
41013
+ return value;
41014
+ }
41015
+ function validateConnectionId(value) {
41016
+ if (!CONNECTION_ID_PATTERN.test(value)) {
41017
+ throw new RuntimeInstallationStoreError("invalid_connection_id", "The local connection ID is invalid");
41018
+ }
41019
+ return value;
41020
+ }
41021
+ function validateInstallationId(value) {
41022
+ if (!INSTALLATION_ID_PATTERN.test(value)) {
41023
+ throw new RuntimeInstallationStoreError("invalid_installation_id", "The installation ID is invalid");
41024
+ }
41025
+ return value;
41026
+ }
41027
+ function validateIdentifier(value, code) {
41028
+ if (!IDENTIFIER_PATTERN6.test(value)) {
41029
+ throw new RuntimeInstallationStoreError(code, "The saved Runtime connection is invalid");
41030
+ }
41031
+ return value;
41032
+ }
41033
+ function validateRuntimeCredential(value) {
41034
+ if (!RUNTIME_CREDENTIAL_PATTERN.test(value)) {
41035
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41036
+ }
41037
+ return value;
41038
+ }
41039
+ function parseRelayOrigin(value) {
41040
+ let origin;
41041
+ try {
41042
+ origin = new URL(value);
41043
+ } catch (cause) {
41044
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid", {
41045
+ cause
41046
+ });
41047
+ }
41048
+ 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") {
41049
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41050
+ }
41051
+ origin.hash = "";
41052
+ origin.pathname = "/";
41053
+ origin.search = "";
41054
+ return origin;
41055
+ }
41056
+ function connectionId() {
41057
+ return `mcn_${randomUUID4().replaceAll("-", "")}`;
41058
+ }
41059
+ function installationId() {
41060
+ return `min_${randomUUID4().replaceAll("-", "")}`;
41061
+ }
41062
+ function channelIndexFileName(channelId) {
41063
+ return `mci_${createHash4("sha256").update(channelId).digest("hex")}.json`;
41064
+ }
41065
+ function decodeInstallationPointer(value) {
41066
+ if (!isRecord9(value) || !hasExactKeys(value, INSTALLATION_POINTER_KEYS) || value["version"] !== 1) {
41067
+ throw new RuntimeInstallationStoreError("invalid_installation", "The local installation record is invalid");
41068
+ }
41069
+ const storedInstallationId = value["installationId"];
41070
+ if (typeof storedInstallationId !== "string") {
41071
+ throw new RuntimeInstallationStoreError("invalid_installation", "The local installation record is invalid");
41072
+ }
41073
+ return { installationId: validateInstallationId(storedInstallationId) };
41074
+ }
41075
+ function decodeChannelIndex(value) {
41076
+ if (!isRecord9(value) || !hasExactKeys(value, CHANNEL_INDEX_KEYS) || value["version"] !== 1) {
41077
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41078
+ }
41079
+ const applicationId = value["applicationId"];
41080
+ const channelId = value["channelId"];
41081
+ const connectionId2 = value["connectionId"];
41082
+ const storedInstallationId = value["installationId"];
41083
+ if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof storedInstallationId !== "string") {
41084
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41085
+ }
41086
+ return {
41087
+ applicationId: validateApplicationId(applicationId),
41088
+ channelId: validateIdentifier(channelId, "invalid_connection"),
41089
+ connectionId: validateConnectionId(connectionId2),
41090
+ installationId: validateInstallationId(storedInstallationId)
41091
+ };
41092
+ }
41093
+ function decodeVerifiedConnection(value) {
41094
+ if (!hasExactKeys(value, VERIFIED_CONNECTION_KEYS) || value["kind"] !== "verified" || value["version"] !== 1) {
41095
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41096
+ }
41097
+ const applicationId = value["applicationId"];
41098
+ const channelId = value["channelId"];
41099
+ const connectionId2 = value["connectionId"];
41100
+ const defaultWorkspace = value["defaultWorkspace"];
41101
+ const storedInstallationId = value["installationId"];
41102
+ const relayOrigin = value["relayOrigin"];
41103
+ const runtimeCredential2 = value["runtimeCredential"];
41104
+ const runtimeId = value["runtimeId"];
41105
+ 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") {
41106
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41107
+ }
41108
+ return new VerifiedRuntimeConnection(
41109
+ validateApplicationId(applicationId),
41110
+ validateInstallationId(storedInstallationId),
41111
+ validateConnectionId(connectionId2),
41112
+ validateIdentifier(channelId, "invalid_connection"),
41113
+ defaultWorkspace,
41114
+ parseRelayOrigin(relayOrigin),
41115
+ validateRuntimeCredential(runtimeCredential2),
41116
+ validateIdentifier(runtimeId, "invalid_connection")
41117
+ );
41118
+ }
41119
+ function decodeImportedLegacyConnection(value) {
41120
+ if (!hasExactKeys(value, IMPORTED_LEGACY_CONNECTION_KEYS) || value["kind"] !== "legacy_imported" || value["version"] !== 1) {
41121
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41122
+ }
41123
+ const applicationId = value["applicationId"];
41124
+ const channelId = value["channelId"];
41125
+ const connectionId2 = value["connectionId"];
41126
+ const defaultWorkspace = value["defaultWorkspace"];
41127
+ const storedInstallationId = value["installationId"];
41128
+ const relayOrigin = value["relayOrigin"];
41129
+ const runtimeCredential2 = value["runtimeCredential"];
41130
+ if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
41131
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41132
+ }
41133
+ return new ImportedLegacyRuntimeConnection(
41134
+ validateApplicationId(applicationId),
41135
+ validateInstallationId(storedInstallationId),
41136
+ validateConnectionId(connectionId2),
41137
+ validateIdentifier(channelId, "invalid_connection"),
41138
+ defaultWorkspace,
41139
+ parseRelayOrigin(relayOrigin),
41140
+ validateRuntimeCredential(runtimeCredential2)
41141
+ );
41142
+ }
41143
+ function decodeConnection(value) {
41144
+ if (!isRecord9(value)) {
41145
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41146
+ }
41147
+ if (value["kind"] === "verified") {
41148
+ return decodeVerifiedConnection(value);
41149
+ }
41150
+ if (value["kind"] === "legacy_imported") {
41151
+ return decodeImportedLegacyConnection(value);
41152
+ }
41153
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41154
+ }
41155
+ function decodeLegacyConnection(value, expectedChannelId) {
41156
+ if (!isRecord9(value) || !hasExactKeys(value, CURRENT_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_CONNECTION_KEYS)) {
41157
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41158
+ }
41159
+ const channelId = value["channelId"];
41160
+ const defaultWorkspace = value["defaultWorkspace"];
41161
+ const relayOrigin = value["relayOrigin"];
41162
+ const runtimeCredential2 = value["runtimeCredential"] ?? value["daemonToken"];
41163
+ if (typeof channelId !== "string" || channelId !== expectedChannelId || typeof defaultWorkspace !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
41164
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41165
+ }
41166
+ return {
41167
+ channelId: validateIdentifier(channelId, "invalid_connection"),
41168
+ defaultWorkspace,
41169
+ relayOrigin: parseRelayOrigin(relayOrigin),
41170
+ runtimeCredential: validateRuntimeCredential(runtimeCredential2)
41171
+ };
41172
+ }
41173
+ async function readJsonFile(path2, signal, missingCode) {
41174
+ signal.throwIfAborted();
41175
+ let handle;
41176
+ try {
41177
+ handle = await open5(path2, "r");
41178
+ } catch (cause) {
41179
+ if (isNodeError(cause, "ENOENT")) {
41180
+ throw new RuntimeInstallationStoreError(missingCode, "The saved Runtime connection was not found", {
41181
+ cause
41182
+ });
41183
+ }
41184
+ throw new RuntimeInstallationStoreError(
41185
+ "connection_unavailable",
41186
+ "The saved Runtime connection cannot be read",
41187
+ {
41188
+ cause
41189
+ }
41190
+ );
41191
+ }
41192
+ let encoded = "";
41193
+ try {
41194
+ const metadata = await handle.stat();
41195
+ if (!metadata.isFile() || metadata.size > MAX_FILE_LENGTH) {
41196
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41197
+ }
41198
+ encoded = await handle.readFile({ encoding: "utf8" });
41199
+ } finally {
41200
+ await handle.close();
41201
+ }
41202
+ signal.throwIfAborted();
41203
+ try {
41204
+ return JSON.parse(encoded);
41205
+ } catch (cause) {
41206
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid", {
41207
+ cause
41208
+ });
41209
+ }
41210
+ }
41211
+ async function writeJsonAtomically(path2, value, signal) {
41212
+ signal.throwIfAborted();
41213
+ const directory = dirname7(path2);
41214
+ const temporaryPath = join16(directory, `.${randomUUID4()}.tmp`);
41215
+ try {
41216
+ await mkdir3(directory, { mode: 448, recursive: true });
41217
+ signal.throwIfAborted();
41218
+ await writeFile2(temporaryPath, `${JSON.stringify(value, null, 2)}
41219
+ `, { flag: "wx", mode: 384 });
41220
+ signal.throwIfAborted();
41221
+ await rename3(temporaryPath, path2);
41222
+ } catch (cause) {
41223
+ await unlink(temporaryPath).catch(() => void 0);
41224
+ signal.throwIfAborted();
41225
+ throw new RuntimeInstallationStoreError("connection_unavailable", "The local Runtime state cannot be written", {
41226
+ cause
41227
+ });
41228
+ }
41229
+ }
41230
+ var RuntimeInstallationStore = class _RuntimeInstallationStore {
41231
+ applicationId;
41232
+ installationId;
41233
+ stateDirectory;
41234
+ #channelDirectory;
41235
+ #connectionDirectory;
41236
+ constructor(applicationId, installationId2, stateDirectory) {
41237
+ this.applicationId = applicationId;
41238
+ this.installationId = installationId2;
41239
+ this.stateDirectory = stateDirectory;
41240
+ this.#channelDirectory = join16(stateDirectory, "channels");
41241
+ this.#connectionDirectory = join16(stateDirectory, "connections");
41242
+ }
41243
+ static open = async (options, signal) => {
41244
+ signal.throwIfAborted();
41245
+ const applicationId = validateApplicationId(options.applicationId);
41246
+ const rootDirectory = resolve5(options.stateDirectory);
41247
+ const applicationDirectory = join16(rootDirectory, "installations", applicationId);
41248
+ try {
41249
+ await mkdir3(applicationDirectory, { mode: 448, recursive: true });
41250
+ } catch (cause) {
41251
+ throw new RuntimeInstallationStoreError(
41252
+ "installation_unavailable",
41253
+ "The local installation cannot be initialized",
41254
+ {
41255
+ cause
41256
+ }
41257
+ );
41258
+ }
41259
+ const storedInstallationId = await readOrCreateInstallationId(applicationDirectory, signal);
41260
+ const stateDirectory = join16(applicationDirectory, storedInstallationId);
41261
+ try {
41262
+ await mkdir3(stateDirectory, { mode: 448, recursive: true });
41263
+ } catch (cause) {
41264
+ throw new RuntimeInstallationStoreError(
41265
+ "installation_unavailable",
41266
+ "The local installation cannot be initialized",
41267
+ {
41268
+ cause
41269
+ }
41270
+ );
41271
+ }
41272
+ signal.throwIfAborted();
41273
+ return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
41274
+ };
41275
+ connectionPath = (connectionId2) => join16(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
41276
+ auditDatabasePath = (connectionId2) => join16(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
41277
+ channelIndexPath = (channelId) => join16(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
41278
+ readConnection = async (connectionId2, signal) => {
41279
+ const stored = decodeConnection(
41280
+ await readJsonFile(this.connectionPath(connectionId2), signal, "connection_not_found")
41281
+ );
41282
+ if (stored.applicationId !== this.applicationId || stored.installationId !== this.installationId) {
41283
+ throw new RuntimeInstallationStoreError(
41284
+ "connection_owner_mismatch",
41285
+ "The saved Runtime connection belongs to another installation"
41286
+ );
41287
+ }
41288
+ return stored;
41289
+ };
41290
+ #readConnectionForChannel = async (channelId, signal) => {
41291
+ const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
41292
+ const index2 = decodeChannelIndex(
41293
+ await readJsonFile(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
41294
+ );
41295
+ if (index2.applicationId !== this.applicationId || index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
41296
+ throw new RuntimeInstallationStoreError(
41297
+ "connection_owner_mismatch",
41298
+ "The saved Runtime connection belongs to another installation"
41299
+ );
41300
+ }
41301
+ return await this.readConnection(index2.connectionId, signal);
41302
+ };
41303
+ migrateLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
41304
+ try {
41305
+ return await this.#readConnectionForChannel(channelId, signal);
41306
+ } catch (cause) {
41307
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "connection_not_found") {
41308
+ throw cause;
41309
+ }
41310
+ }
41311
+ return await this.importLegacyConnection(legacyStateDirectory, channelId, signal);
41312
+ };
41313
+ saveConnection = async (input2, signal) => {
41314
+ const stored = new VerifiedRuntimeConnection(
41315
+ this.applicationId,
41316
+ this.installationId,
41317
+ connectionId(),
41318
+ validateIdentifier(input2.channelId, "invalid_connection"),
41319
+ input2.defaultWorkspace,
41320
+ parseRelayOrigin(input2.relayOrigin.toString()),
41321
+ validateRuntimeCredential(input2.runtimeCredential),
41322
+ validateIdentifier(input2.runtimeId, "invalid_connection")
41323
+ );
41324
+ await this.writeConnection(stored, signal);
41325
+ return stored;
41326
+ };
41327
+ importLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
41328
+ const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
41329
+ const legacyPath = join16(resolve5(legacyStateDirectory), "connections", `${normalizedChannelId}.json`);
41330
+ const legacy = decodeLegacyConnection(
41331
+ await readJsonFile(legacyPath, signal, "connection_not_found"),
41332
+ normalizedChannelId
41333
+ );
41334
+ const stored = new ImportedLegacyRuntimeConnection(
41335
+ this.applicationId,
41336
+ this.installationId,
41337
+ connectionId(),
41338
+ legacy.channelId,
41339
+ legacy.defaultWorkspace,
41340
+ legacy.relayOrigin,
41341
+ legacy.runtimeCredential
41342
+ );
41343
+ await this.writeConnection(stored, signal);
41344
+ return stored;
41345
+ };
41346
+ writeConnection = async (stored, signal) => {
41347
+ signal.throwIfAborted();
41348
+ try {
41349
+ await this.#readConnectionForChannel(stored.channelId, signal);
41350
+ throw new RuntimeInstallationStoreError(
41351
+ "connection_conflict",
41352
+ "A Runtime connection for this channel already exists in this installation"
41353
+ );
41354
+ } catch (cause) {
41355
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "connection_not_found") {
41356
+ throw cause;
41357
+ }
41358
+ }
41359
+ const connectionPath = this.connectionPath(stored.connectionId);
41360
+ if (stored instanceof VerifiedRuntimeConnection) {
41361
+ await writeJsonAtomically(
41362
+ connectionPath,
41363
+ {
41364
+ applicationId: stored.applicationId,
41365
+ channelId: stored.channelId,
41366
+ connectionId: stored.connectionId,
41367
+ defaultWorkspace: stored.defaultWorkspace,
41368
+ installationId: stored.installationId,
41369
+ kind: stored.kind,
41370
+ relayOrigin: stored.relayOrigin.toString(),
41371
+ runtimeCredential: stored.runtimeCredential,
41372
+ runtimeId: stored.runtimeId,
41373
+ version: 1
41374
+ },
41375
+ signal
41376
+ );
41377
+ } else {
41378
+ await writeJsonAtomically(
41379
+ connectionPath,
41380
+ {
41381
+ applicationId: stored.applicationId,
41382
+ channelId: stored.channelId,
41383
+ connectionId: stored.connectionId,
41384
+ defaultWorkspace: stored.defaultWorkspace,
41385
+ installationId: stored.installationId,
41386
+ kind: stored.kind,
41387
+ relayOrigin: stored.relayOrigin.toString(),
41388
+ runtimeCredential: stored.runtimeCredential,
41389
+ version: 1
41390
+ },
41391
+ signal
41392
+ );
41393
+ }
41394
+ await writeJsonAtomically(
41395
+ this.channelIndexPath(stored.channelId),
41396
+ {
41397
+ applicationId: this.applicationId,
41398
+ channelId: stored.channelId,
41399
+ connectionId: stored.connectionId,
41400
+ installationId: this.installationId,
41401
+ version: 1
41402
+ },
41403
+ signal
41404
+ );
41405
+ };
41406
+ };
41407
+ async function readOrCreateInstallationId(applicationDirectory, signal) {
41408
+ const pointerPath = join16(applicationDirectory, "current.json");
41409
+ try {
41410
+ return decodeInstallationPointer(await readJsonFile(pointerPath, signal, "installation_not_found")).installationId;
41411
+ } catch (cause) {
41412
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "installation_not_found") {
41413
+ throw cause;
41414
+ }
41415
+ }
41416
+ const candidate = installationId();
41417
+ try {
41418
+ await writeFile2(pointerPath, `${JSON.stringify({ installationId: candidate, version: 1 })}
41419
+ `, {
41420
+ flag: "wx",
41421
+ mode: 384
41422
+ });
41423
+ return candidate;
41424
+ } catch (cause) {
41425
+ if (!isNodeError(cause, "EEXIST")) {
41426
+ throw new RuntimeInstallationStoreError(
41427
+ "installation_unavailable",
41428
+ "The local installation cannot be initialized",
41429
+ {
41430
+ cause
41431
+ }
41432
+ );
41433
+ }
41434
+ return decodeInstallationPointer(await readJsonFile(pointerPath, signal, "installation_not_found")).installationId;
41435
+ }
41436
+ }
41437
+ async function openRuntimeInstallationStore(options, signal) {
41438
+ return await RuntimeInstallationStore.open(options, signal);
41439
+ }
41440
+
41441
+ // src/pairing/pair-local-machine.ts
40871
41442
  var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
40872
41443
  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}$/;
41444
+ var IDENTIFIER_PATTERN7 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
40874
41445
  var TOKEN_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
40875
- var MAX_CONNECTION_FILE_LENGTH = 16 * 1024;
40876
41446
  var CLAIM_RESPONSE_KEYS = ["channelId", "daemonToken", "runtimeId"];
40877
41447
  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
41448
  var PairingClientError = class extends Error {
40881
41449
  code;
40882
41450
  constructor(code, message, options = {}) {
@@ -40885,14 +41453,14 @@ var PairingClientError = class extends Error {
40885
41453
  this.name = "PairingClientError";
40886
41454
  }
40887
41455
  };
40888
- function isRecord9(value) {
41456
+ function isRecord10(value) {
40889
41457
  return typeof value === "object" && value !== null && !Array.isArray(value);
40890
41458
  }
40891
- function hasExactKeys(value, expectedKeys) {
41459
+ function hasExactKeys2(value, expectedKeys) {
40892
41460
  const keys = Object.keys(value);
40893
41461
  return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
40894
41462
  }
40895
- function parseRelayOrigin(value) {
41463
+ function parseRelayOrigin2(value) {
40896
41464
  let url2;
40897
41465
  try {
40898
41466
  url2 = new URL(value);
@@ -40924,15 +41492,15 @@ function parsePairingCode(value) {
40924
41492
  return code;
40925
41493
  }
40926
41494
  function validatePairingId(value) {
40927
- if (!IDENTIFIER_PATTERN6.test(value)) {
41495
+ if (!IDENTIFIER_PATTERN7.test(value)) {
40928
41496
  throw new PairingClientError("invalid_pairing_id", "The Runtime pairing ID is invalid");
40929
41497
  }
40930
41498
  return value;
40931
41499
  }
40932
41500
  async function resolveDefaultWorkspace2(path2) {
40933
- const requestedWorkspace = resolve4(path2);
41501
+ const requestedWorkspace = resolve6(path2);
40934
41502
  try {
40935
- await mkdir3(requestedWorkspace, { recursive: true, mode: 448 });
41503
+ await mkdir4(requestedWorkspace, { recursive: true, mode: 448 });
40936
41504
  const defaultWorkspace = await realpath9(requestedWorkspace);
40937
41505
  const metadata = await stat8(defaultWorkspace);
40938
41506
  if (!metadata.isDirectory()) {
@@ -40963,9 +41531,9 @@ async function readJsonResponse(response) {
40963
41531
  }
40964
41532
  }
40965
41533
  function readRelayError(value) {
40966
- if (isRecord9(value)) {
41534
+ if (isRecord10(value)) {
40967
41535
  const error62 = value["error"];
40968
- if (isRecord9(error62)) {
41536
+ if (isRecord10(error62)) {
40969
41537
  const code = error62["code"];
40970
41538
  const message = error62["message"];
40971
41539
  if (typeof code === "string" && typeof message === "string") {
@@ -40976,13 +41544,13 @@ function readRelayError(value) {
40976
41544
  return new PairingClientError("pairing_failed", "The relay could not pair this machine");
40977
41545
  }
40978
41546
  function decodePairingResponse(value, credentialField, expectedKeys) {
40979
- if (!isRecord9(value) || !hasExactKeys(value, expectedKeys)) {
41547
+ if (!isRecord10(value) || !hasExactKeys2(value, expectedKeys)) {
40980
41548
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
40981
41549
  }
40982
41550
  const channelId = value["channelId"];
40983
41551
  const runtimeCredential2 = value[credentialField];
40984
41552
  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)) {
41553
+ if (typeof channelId !== "string" || !IDENTIFIER_PATTERN7.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN7.test(runtimeId)) {
40986
41554
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
40987
41555
  }
40988
41556
  return { channelId, runtimeCredential: runtimeCredential2, runtimeId };
@@ -41022,156 +41590,88 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
41022
41590
  }
41023
41591
  return options.pairingId.length > 0 ? decodePairingResponse(value, "runtimeCredential", REDEEM_RESPONSE_KEYS) : decodePairingResponse(value, "daemonToken", CLAIM_RESPONSE_KEYS);
41024
41592
  }
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
41593
  function assertInventoryUsable(inventory) {
41094
41594
  if (inventory.available.length + inventory.installable.length === 0) {
41095
41595
  throw new PairingClientError("no_supported_agent", "No supported Agent is available for local discovery");
41096
41596
  }
41097
41597
  }
41098
- function buildPairedDaemon(connection, connectionPath, inventory, environment) {
41598
+ function buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext) {
41099
41599
  assertInventoryUsable(inventory);
41100
41600
  const relayUrl = mobiusApiUrl(connection.relayOrigin, "/v1/runtimes/connect");
41101
41601
  relayUrl.protocol = relayUrl.protocol === "https:" ? "wss:" : "ws:";
41102
41602
  relayUrl.searchParams.set("token", connection.runtimeCredential);
41103
- const auditDatabasePath = join16(readStateDirectory(environment), "audit", `${connection.channelId}.sqlite`);
41104
41603
  return {
41105
41604
  channelUrl: new URL(`/channels/${encodeURIComponent(connection.channelId)}`, connection.relayOrigin).toString(),
41605
+ connectionId: connection.connectionId,
41106
41606
  config: createDaemonConfig(
41107
41607
  {
41108
- defaultWorkspace: connection.defaultWorkspace,
41109
- auditDatabasePath,
41608
+ defaultWorkspace,
41609
+ auditDatabasePath: installation.auditDatabasePath(connection.connectionId),
41110
41610
  channelId: connection.channelId,
41111
41611
  relayUrl
41112
41612
  },
41113
41613
  inventory.readyAgents(),
41114
- inventory.installable
41614
+ inventory.installable,
41615
+ localContext,
41616
+ new OpaqueDaemonReconnectTarget(connection.connectionId)
41115
41617
  ),
41116
- connectionPath
41618
+ connectionPath: installation.connectionPath(connection.connectionId)
41117
41619
  };
41118
41620
  }
41119
- async function pairRuntime(options, signal, environment) {
41621
+ async function pairRuntime(installation, options, signal, environment) {
41622
+ const localContext = new DaemonLocalContext(installation.stateDirectory, environment);
41120
41623
  const defaultWorkspace = await resolveDefaultWorkspace2(options.workspace);
41121
41624
  const inventory = await discoverLocalAgentInventory({
41122
41625
  defaultWorkspace,
41123
- environment,
41626
+ environment: localContext.environment,
41124
41627
  signal
41125
41628
  });
41126
41629
  assertInventoryUsable(inventory);
41127
41630
  const agents = inventory.readyAgents();
41128
41631
  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(
41632
+ const connection = await installation.saveConnection(
41137
41633
  {
41138
- defaultWorkspace,
41139
41634
  channelId: claim2.channelId,
41635
+ defaultWorkspace,
41140
41636
  relayOrigin: options.relayOrigin,
41141
- runtimeCredential: claim2.runtimeCredential
41637
+ runtimeCredential: claim2.runtimeCredential,
41638
+ runtimeId: claim2.runtimeId
41142
41639
  },
41143
- connectionPath,
41144
- inventory,
41145
- environment
41640
+ signal
41146
41641
  );
41642
+ return buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext);
41147
41643
  }
41148
- async function pairMobiusRuntime(options, signal, environment = process.env) {
41644
+ async function pairMobiusRuntime(installation, options, signal, environment = process.env) {
41149
41645
  return await pairRuntime(
41646
+ installation,
41150
41647
  {
41151
41648
  code: parsePairingCode(options.pairingCode),
41152
41649
  pairingId: validatePairingId(options.pairingId),
41153
- relayOrigin: parseRelayOrigin(options.relayOrigin),
41650
+ relayOrigin: parseRelayOrigin2(options.relayOrigin),
41154
41651
  workspace: options.defaultWorkspace
41155
41652
  },
41156
41653
  signal,
41157
41654
  environment
41158
41655
  );
41159
41656
  }
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);
41657
+ async function resumeRuntimeConnection(installation, connection, signal, environment) {
41658
+ const localContext = new DaemonLocalContext(installation.stateDirectory, environment);
41659
+ const defaultWorkspace = await resolveDefaultWorkspace2(connection.defaultWorkspace);
41164
41660
  const inventory = await discoverLocalAgentInventory({
41165
- defaultWorkspace: connection.defaultWorkspace,
41166
- environment,
41661
+ defaultWorkspace,
41662
+ environment: localContext.environment,
41167
41663
  signal
41168
41664
  });
41169
- return buildPairedDaemon(connection, connectionPath, inventory, environment);
41665
+ return buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext);
41666
+ }
41667
+ async function resumeMobiusRuntime(installation, connectionId2, signal, environment = process.env) {
41668
+ const connection = await installation.readConnection(connectionId2, signal);
41669
+ return await resumeRuntimeConnection(installation, connection, signal, environment);
41170
41670
  }
41171
41671
 
41172
41672
  // 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}$/;
41673
+ var IDENTIFIER_PATTERN8 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
41674
+ var RUNTIME_CREDENTIAL_PATTERN2 = /^[a-zA-Z0-9_-]{32,256}$/;
41175
41675
  var MobiusRuntimeConfigurationError = class extends Error {
41176
41676
  code = "runtime_configuration_invalid";
41177
41677
  constructor(message, options = {}) {
@@ -41195,7 +41695,7 @@ function validateRuntimeRelay(relayUrl) {
41195
41695
  if (credential.length === 0) {
41196
41696
  throw new MobiusRuntimeConfigurationError("The Runtime relay credential is required");
41197
41697
  }
41198
- if (!RUNTIME_CREDENTIAL_PATTERN.test(credential)) {
41698
+ if (!RUNTIME_CREDENTIAL_PATTERN2.test(credential)) {
41199
41699
  throw new MobiusRuntimeConfigurationError("The Runtime relay credential is invalid");
41200
41700
  }
41201
41701
  }
@@ -41222,7 +41722,7 @@ function relayUrlFromConnection(connection) {
41222
41722
  }
41223
41723
  function loadMobiusRuntimeConnection(environment = process.env) {
41224
41724
  const channelId = requiredEnvironmentValue(environment, "MOBIUS_CHANNEL_ID");
41225
- if (!IDENTIFIER_PATTERN7.test(channelId)) {
41725
+ if (!IDENTIFIER_PATTERN8.test(channelId)) {
41226
41726
  throw new MobiusRuntimeConfigurationError("MOBIUS_CHANNEL_ID is invalid");
41227
41727
  }
41228
41728
  return Object.freeze({
@@ -41234,9 +41734,9 @@ function loadMobiusRuntimeConnection(environment = process.env) {
41234
41734
  });
41235
41735
  }
41236
41736
  async function resolveWorkspace(path2) {
41237
- const requested = resolve5(path2);
41737
+ const requested = resolve7(path2);
41238
41738
  try {
41239
- await mkdir4(requested, { recursive: true, mode: 448 });
41739
+ await mkdir5(requested, { recursive: true, mode: 448 });
41240
41740
  const resolved = await realpath10(requested);
41241
41741
  const metadata = await stat9(resolved);
41242
41742
  if (!metadata.isDirectory()) {
@@ -41252,13 +41752,14 @@ async function resolveWorkspace(path2) {
41252
41752
  }
41253
41753
  async function createMobiusRuntimeEngine(connection, signal, environment = process.env) {
41254
41754
  signal.throwIfAborted();
41755
+ const localContext = new DaemonLocalContext(readStateDirectory(environment), environment);
41255
41756
  const relayUrl = relayUrlFromConnection(connection);
41256
41757
  const defaultWorkspace = await resolveWorkspace(connection.defaultWorkspace);
41257
- const auditDatabasePath = resolve5(connection.auditDatabasePath);
41258
- await mkdir4(dirname7(auditDatabasePath), { recursive: true, mode: 448 });
41758
+ const auditDatabasePath = resolve7(connection.auditDatabasePath);
41759
+ await mkdir5(dirname8(auditDatabasePath), { recursive: true, mode: 448 });
41259
41760
  const inventory = await discoverLocalAgentInventory({
41260
41761
  defaultWorkspace,
41261
- environment,
41762
+ environment: localContext.environment,
41262
41763
  signal
41263
41764
  });
41264
41765
  if (inventory.available.length + inventory.installable.length === 0) {
@@ -41273,7 +41774,8 @@ async function createMobiusRuntimeEngine(connection, signal, environment = proce
41273
41774
  relayUrl
41274
41775
  },
41275
41776
  inventory.readyAgents(),
41276
- inventory.installable
41777
+ inventory.installable,
41778
+ localContext
41277
41779
  )
41278
41780
  );
41279
41781
  }
@@ -41300,12 +41802,22 @@ var MobiusRuntimeEngine = class {
41300
41802
  };
41301
41803
  };
41302
41804
  export {
41805
+ ChannelDaemonReconnectTarget,
41806
+ DaemonLocalContext,
41807
+ DaemonReconnectTarget,
41808
+ ImportedLegacyRuntimeConnection,
41303
41809
  MobiusRuntimeConfigurationError,
41304
41810
  MobiusRuntimeEngine,
41811
+ OpaqueDaemonReconnectTarget,
41305
41812
  PairingClientError,
41813
+ RuntimeInstallationStore,
41814
+ RuntimeInstallationStoreError,
41815
+ StoredRuntimeConnection,
41816
+ VerifiedRuntimeConnection,
41306
41817
  createDaemonConfig,
41307
41818
  createMobiusRuntimeEngine,
41308
41819
  loadMobiusRuntimeConnection,
41820
+ openRuntimeInstallationStore,
41309
41821
  pairMobiusRuntime,
41310
41822
  resumeMobiusRuntime
41311
41823
  };