@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/cli.js CHANGED
@@ -6,12 +6,12 @@ var __export = (target, all2) => {
6
6
  };
7
7
 
8
8
  // src/cli.ts
9
- import { mkdir as mkdir4 } from "node:fs/promises";
9
+ import { mkdir as mkdir5 } from "node:fs/promises";
10
10
 
11
11
  // package.json
12
12
  var package_default = {
13
13
  name: "@moxt-ai/mobius",
14
- version: "0.0.49",
14
+ version: "0.0.50",
15
15
  description: "Mobius CLI for pairing and running local AI agent services.",
16
16
  type: "module",
17
17
  bin: {
@@ -5691,7 +5691,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
5691
5691
  var NONE = 0;
5692
5692
  var ASSUMED = 1;
5693
5693
  var PROVEN = 2;
5694
- function isRecursive(inst, stack, resolve5) {
5694
+ function isRecursive(inst, stack, resolve7) {
5695
5695
  const cached2 = recursive.get(inst);
5696
5696
  if (cached2 !== void 0)
5697
5697
  return cached2 ? PROVEN : NONE;
@@ -5701,7 +5701,7 @@ function isRecursive(inst, stack, resolve5) {
5701
5701
  let result = NONE;
5702
5702
  const check2 = (child) => {
5703
5703
  if (result !== PROVEN && child?._zod) {
5704
- const answer = isRecursive(child, stack, resolve5);
5704
+ const answer = isRecursive(child, stack, resolve7);
5705
5705
  if (answer > result)
5706
5706
  result = answer;
5707
5707
  }
@@ -5712,7 +5712,7 @@ function isRecursive(inst, stack, resolve5) {
5712
5712
  const desc = Object.getOwnPropertyDescriptor(sh, key);
5713
5713
  if (spread && !desc.enumerable)
5714
5714
  continue;
5715
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve5) : NONE;
5715
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve7) : NONE;
5716
5716
  if (child > answer)
5717
5717
  answer = child;
5718
5718
  }
@@ -5779,7 +5779,7 @@ function isRecursive(inst, stack, resolve5) {
5779
5779
  break;
5780
5780
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
5781
5781
  case "lazy": {
5782
- const inner = def._cachedInner ?? (resolve5 ? inst._zod.innerType : void 0);
5782
+ const inner = def._cachedInner ?? (resolve7 ? inst._zod.innerType : void 0);
5783
5783
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
5784
5784
  break;
5785
5785
  }
@@ -24124,12 +24124,40 @@ async function discoverLocalAgentInventory(options) {
24124
24124
  }
24125
24125
 
24126
24126
  // src/config.ts
24127
- import { join as join14 } from "node:path";
24127
+ import { join as join14, resolve as resolve3 } from "node:path";
24128
24128
  function loadDefaultWorkspace(environment = process.env) {
24129
24129
  const { MOBIUS_DEFAULT_WORKSPACE: configuredWorkspace } = environment;
24130
24130
  return configuredWorkspace ?? join14(readStateDirectory(environment), "workspace");
24131
24131
  }
24132
- function createDaemonConfig(connection, agents = [], installableAgents = []) {
24132
+ var DaemonLocalContext = class {
24133
+ environment;
24134
+ stateDirectory;
24135
+ constructor(stateDirectory, environment = process.env) {
24136
+ this.stateDirectory = resolve3(stateDirectory);
24137
+ this.environment = Object.freeze({ ...environment, MOBIUS_STATE_DIRECTORY: this.stateDirectory });
24138
+ }
24139
+ };
24140
+ var DaemonReconnectTarget = class {
24141
+ };
24142
+ var OpaqueDaemonReconnectTarget = class extends DaemonReconnectTarget {
24143
+ connectionId;
24144
+ commandArgument;
24145
+ constructor(connectionId2) {
24146
+ super();
24147
+ this.connectionId = connectionId2;
24148
+ this.commandArgument = `--connection ${connectionId2}`;
24149
+ }
24150
+ };
24151
+ var ChannelDaemonReconnectTarget = class extends DaemonReconnectTarget {
24152
+ channelId;
24153
+ commandArgument;
24154
+ constructor(channelId) {
24155
+ super();
24156
+ this.channelId = channelId;
24157
+ this.commandArgument = `--channel ${channelId}`;
24158
+ }
24159
+ };
24160
+ function createDaemonConfig(connection, agents = [], installableAgents = [], localContext = new DaemonLocalContext(readStateDirectory(), process.env), reconnectTarget = new ChannelDaemonReconnectTarget(connection.channelId)) {
24133
24161
  return {
24134
24162
  agents,
24135
24163
  defaultWorkspace: connection.defaultWorkspace,
@@ -24138,25 +24166,556 @@ function createDaemonConfig(connection, agents = [], installableAgents = []) {
24138
24166
  catalog: new LocalAgentCatalog(agents, installableAgents),
24139
24167
  channelId: connection.channelId,
24140
24168
  installableAgents,
24169
+ localContext,
24170
+ reconnectTarget,
24141
24171
  relayUrl: connection.relayUrl
24142
24172
  };
24143
24173
  }
24144
24174
 
24145
24175
  // src/pairing/pair-local-machine.ts
24146
- import { randomUUID } from "node:crypto";
24147
- import { mkdir as mkdir3, open as open4, realpath as realpath6, rename as rename3, stat as stat5, writeFile as writeFile2 } from "node:fs/promises";
24176
+ import { mkdir as mkdir4, realpath as realpath6, stat as stat5 } from "node:fs/promises";
24148
24177
  import { hostname as hostname3 } from "node:os";
24149
- import { basename, join as join15, resolve as resolve3 } from "node:path";
24178
+ import { basename, resolve as resolve5 } from "node:path";
24150
24179
  import { fetch as fetch2 } from "undici";
24180
+
24181
+ // src/storage/runtime-installation-store.ts
24182
+ import { createHash as createHash2, randomUUID } from "node:crypto";
24183
+ import { mkdir as mkdir3, open as open4, rename as rename3, unlink, writeFile as writeFile2 } from "node:fs/promises";
24184
+ import { dirname as dirname3, join as join15, resolve as resolve4 } from "node:path";
24185
+ var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
24186
+ var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
24187
+ var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
24188
+ var IDENTIFIER_PATTERN4 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
24189
+ var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
24190
+ var MAX_FILE_LENGTH = 16 * 1024;
24191
+ var INSTALLATION_POINTER_KEYS = ["installationId", "version"];
24192
+ var CHANNEL_INDEX_KEYS = [
24193
+ "applicationId",
24194
+ "channelId",
24195
+ "connectionId",
24196
+ "installationId",
24197
+ "version"
24198
+ ];
24199
+ var VERIFIED_CONNECTION_KEYS = [
24200
+ "applicationId",
24201
+ "channelId",
24202
+ "connectionId",
24203
+ "defaultWorkspace",
24204
+ "installationId",
24205
+ "kind",
24206
+ "relayOrigin",
24207
+ "runtimeCredential",
24208
+ "runtimeId",
24209
+ "version"
24210
+ ];
24211
+ var IMPORTED_LEGACY_CONNECTION_KEYS = [
24212
+ "applicationId",
24213
+ "channelId",
24214
+ "connectionId",
24215
+ "defaultWorkspace",
24216
+ "installationId",
24217
+ "kind",
24218
+ "relayOrigin",
24219
+ "runtimeCredential",
24220
+ "version"
24221
+ ];
24222
+ var CURRENT_CONNECTION_KEYS = [
24223
+ "defaultWorkspace",
24224
+ "channelId",
24225
+ "relayOrigin",
24226
+ "runtimeCredential"
24227
+ ];
24228
+ var LEGACY_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "daemonToken", "relayOrigin"];
24229
+ var RuntimeInstallationStoreError = class extends Error {
24230
+ code;
24231
+ constructor(code, message, options = {}) {
24232
+ super(message, options);
24233
+ this.code = code;
24234
+ this.name = "RuntimeInstallationStoreError";
24235
+ }
24236
+ };
24237
+ var StoredRuntimeConnection = class {
24238
+ applicationId;
24239
+ channelId;
24240
+ connectionId;
24241
+ defaultWorkspace;
24242
+ installationId;
24243
+ relayOrigin;
24244
+ runtimeCredential;
24245
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
24246
+ this.applicationId = applicationId;
24247
+ this.channelId = channelId;
24248
+ this.connectionId = connectionId2;
24249
+ this.defaultWorkspace = defaultWorkspace;
24250
+ this.installationId = installationId2;
24251
+ this.relayOrigin = relayOrigin;
24252
+ this.runtimeCredential = runtimeCredential2;
24253
+ }
24254
+ };
24255
+ var VerifiedRuntimeConnection = class extends StoredRuntimeConnection {
24256
+ kind = "verified";
24257
+ runtimeId;
24258
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2, runtimeId) {
24259
+ super(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2);
24260
+ this.runtimeId = runtimeId;
24261
+ }
24262
+ };
24263
+ var ImportedLegacyRuntimeConnection = class extends StoredRuntimeConnection {
24264
+ kind = "legacy_imported";
24265
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
24266
+ super(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2);
24267
+ }
24268
+ };
24269
+ function isRecord5(value) {
24270
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24271
+ }
24272
+ function hasExactKeys(value, expectedKeys) {
24273
+ const keys = Object.keys(value);
24274
+ return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
24275
+ }
24276
+ function isNodeError(error62, code) {
24277
+ return typeof error62 === "object" && error62 !== null && "code" in error62 && error62.code === code;
24278
+ }
24279
+ function validateApplicationId(value) {
24280
+ if (!APPLICATION_ID_PATTERN.test(value)) {
24281
+ throw new RuntimeInstallationStoreError("invalid_application_id", "The application ID is invalid");
24282
+ }
24283
+ return value;
24284
+ }
24285
+ function validateConnectionId(value) {
24286
+ if (!CONNECTION_ID_PATTERN.test(value)) {
24287
+ throw new RuntimeInstallationStoreError("invalid_connection_id", "The local connection ID is invalid");
24288
+ }
24289
+ return value;
24290
+ }
24291
+ function validateInstallationId(value) {
24292
+ if (!INSTALLATION_ID_PATTERN.test(value)) {
24293
+ throw new RuntimeInstallationStoreError("invalid_installation_id", "The installation ID is invalid");
24294
+ }
24295
+ return value;
24296
+ }
24297
+ function validateIdentifier(value, code) {
24298
+ if (!IDENTIFIER_PATTERN4.test(value)) {
24299
+ throw new RuntimeInstallationStoreError(code, "The saved Runtime connection is invalid");
24300
+ }
24301
+ return value;
24302
+ }
24303
+ function validateRuntimeCredential(value) {
24304
+ if (!RUNTIME_CREDENTIAL_PATTERN.test(value)) {
24305
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24306
+ }
24307
+ return value;
24308
+ }
24309
+ function parseRelayOrigin(value) {
24310
+ let origin;
24311
+ try {
24312
+ origin = new URL(value);
24313
+ } catch (cause) {
24314
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid", {
24315
+ cause
24316
+ });
24317
+ }
24318
+ 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") {
24319
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24320
+ }
24321
+ origin.hash = "";
24322
+ origin.pathname = "/";
24323
+ origin.search = "";
24324
+ return origin;
24325
+ }
24326
+ function connectionId() {
24327
+ return `mcn_${randomUUID().replaceAll("-", "")}`;
24328
+ }
24329
+ function installationId() {
24330
+ return `min_${randomUUID().replaceAll("-", "")}`;
24331
+ }
24332
+ function channelIndexFileName(channelId) {
24333
+ return `mci_${createHash2("sha256").update(channelId).digest("hex")}.json`;
24334
+ }
24335
+ function decodeInstallationPointer(value) {
24336
+ if (!isRecord5(value) || !hasExactKeys(value, INSTALLATION_POINTER_KEYS) || value["version"] !== 1) {
24337
+ throw new RuntimeInstallationStoreError("invalid_installation", "The local installation record is invalid");
24338
+ }
24339
+ const storedInstallationId = value["installationId"];
24340
+ if (typeof storedInstallationId !== "string") {
24341
+ throw new RuntimeInstallationStoreError("invalid_installation", "The local installation record is invalid");
24342
+ }
24343
+ return { installationId: validateInstallationId(storedInstallationId) };
24344
+ }
24345
+ function decodeChannelIndex(value) {
24346
+ if (!isRecord5(value) || !hasExactKeys(value, CHANNEL_INDEX_KEYS) || value["version"] !== 1) {
24347
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24348
+ }
24349
+ const applicationId = value["applicationId"];
24350
+ const channelId = value["channelId"];
24351
+ const connectionId2 = value["connectionId"];
24352
+ const storedInstallationId = value["installationId"];
24353
+ if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof storedInstallationId !== "string") {
24354
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24355
+ }
24356
+ return {
24357
+ applicationId: validateApplicationId(applicationId),
24358
+ channelId: validateIdentifier(channelId, "invalid_connection"),
24359
+ connectionId: validateConnectionId(connectionId2),
24360
+ installationId: validateInstallationId(storedInstallationId)
24361
+ };
24362
+ }
24363
+ function decodeVerifiedConnection(value) {
24364
+ if (!hasExactKeys(value, VERIFIED_CONNECTION_KEYS) || value["kind"] !== "verified" || value["version"] !== 1) {
24365
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24366
+ }
24367
+ const applicationId = value["applicationId"];
24368
+ const channelId = value["channelId"];
24369
+ const connectionId2 = value["connectionId"];
24370
+ const defaultWorkspace = value["defaultWorkspace"];
24371
+ const storedInstallationId = value["installationId"];
24372
+ const relayOrigin = value["relayOrigin"];
24373
+ const runtimeCredential2 = value["runtimeCredential"];
24374
+ const runtimeId = value["runtimeId"];
24375
+ 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") {
24376
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24377
+ }
24378
+ return new VerifiedRuntimeConnection(
24379
+ validateApplicationId(applicationId),
24380
+ validateInstallationId(storedInstallationId),
24381
+ validateConnectionId(connectionId2),
24382
+ validateIdentifier(channelId, "invalid_connection"),
24383
+ defaultWorkspace,
24384
+ parseRelayOrigin(relayOrigin),
24385
+ validateRuntimeCredential(runtimeCredential2),
24386
+ validateIdentifier(runtimeId, "invalid_connection")
24387
+ );
24388
+ }
24389
+ function decodeImportedLegacyConnection(value) {
24390
+ if (!hasExactKeys(value, IMPORTED_LEGACY_CONNECTION_KEYS) || value["kind"] !== "legacy_imported" || value["version"] !== 1) {
24391
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24392
+ }
24393
+ const applicationId = value["applicationId"];
24394
+ const channelId = value["channelId"];
24395
+ const connectionId2 = value["connectionId"];
24396
+ const defaultWorkspace = value["defaultWorkspace"];
24397
+ const storedInstallationId = value["installationId"];
24398
+ const relayOrigin = value["relayOrigin"];
24399
+ const runtimeCredential2 = value["runtimeCredential"];
24400
+ if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
24401
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24402
+ }
24403
+ return new ImportedLegacyRuntimeConnection(
24404
+ validateApplicationId(applicationId),
24405
+ validateInstallationId(storedInstallationId),
24406
+ validateConnectionId(connectionId2),
24407
+ validateIdentifier(channelId, "invalid_connection"),
24408
+ defaultWorkspace,
24409
+ parseRelayOrigin(relayOrigin),
24410
+ validateRuntimeCredential(runtimeCredential2)
24411
+ );
24412
+ }
24413
+ function decodeConnection(value) {
24414
+ if (!isRecord5(value)) {
24415
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24416
+ }
24417
+ if (value["kind"] === "verified") {
24418
+ return decodeVerifiedConnection(value);
24419
+ }
24420
+ if (value["kind"] === "legacy_imported") {
24421
+ return decodeImportedLegacyConnection(value);
24422
+ }
24423
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24424
+ }
24425
+ function decodeLegacyConnection(value, expectedChannelId) {
24426
+ if (!isRecord5(value) || !hasExactKeys(value, CURRENT_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_CONNECTION_KEYS)) {
24427
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24428
+ }
24429
+ const channelId = value["channelId"];
24430
+ const defaultWorkspace = value["defaultWorkspace"];
24431
+ const relayOrigin = value["relayOrigin"];
24432
+ const runtimeCredential2 = value["runtimeCredential"] ?? value["daemonToken"];
24433
+ if (typeof channelId !== "string" || channelId !== expectedChannelId || typeof defaultWorkspace !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
24434
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24435
+ }
24436
+ return {
24437
+ channelId: validateIdentifier(channelId, "invalid_connection"),
24438
+ defaultWorkspace,
24439
+ relayOrigin: parseRelayOrigin(relayOrigin),
24440
+ runtimeCredential: validateRuntimeCredential(runtimeCredential2)
24441
+ };
24442
+ }
24443
+ async function readJsonFile(path2, signal, missingCode) {
24444
+ signal.throwIfAborted();
24445
+ let handle;
24446
+ try {
24447
+ handle = await open4(path2, "r");
24448
+ } catch (cause) {
24449
+ if (isNodeError(cause, "ENOENT")) {
24450
+ throw new RuntimeInstallationStoreError(missingCode, "The saved Runtime connection was not found", {
24451
+ cause
24452
+ });
24453
+ }
24454
+ throw new RuntimeInstallationStoreError(
24455
+ "connection_unavailable",
24456
+ "The saved Runtime connection cannot be read",
24457
+ {
24458
+ cause
24459
+ }
24460
+ );
24461
+ }
24462
+ let encoded = "";
24463
+ try {
24464
+ const metadata = await handle.stat();
24465
+ if (!metadata.isFile() || metadata.size > MAX_FILE_LENGTH) {
24466
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
24467
+ }
24468
+ encoded = await handle.readFile({ encoding: "utf8" });
24469
+ } finally {
24470
+ await handle.close();
24471
+ }
24472
+ signal.throwIfAborted();
24473
+ try {
24474
+ return JSON.parse(encoded);
24475
+ } catch (cause) {
24476
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid", {
24477
+ cause
24478
+ });
24479
+ }
24480
+ }
24481
+ async function writeJsonAtomically(path2, value, signal) {
24482
+ signal.throwIfAborted();
24483
+ const directory = dirname3(path2);
24484
+ const temporaryPath = join15(directory, `.${randomUUID()}.tmp`);
24485
+ try {
24486
+ await mkdir3(directory, { mode: 448, recursive: true });
24487
+ signal.throwIfAborted();
24488
+ await writeFile2(temporaryPath, `${JSON.stringify(value, null, 2)}
24489
+ `, { flag: "wx", mode: 384 });
24490
+ signal.throwIfAborted();
24491
+ await rename3(temporaryPath, path2);
24492
+ } catch (cause) {
24493
+ await unlink(temporaryPath).catch(() => void 0);
24494
+ signal.throwIfAborted();
24495
+ throw new RuntimeInstallationStoreError("connection_unavailable", "The local Runtime state cannot be written", {
24496
+ cause
24497
+ });
24498
+ }
24499
+ }
24500
+ var RuntimeInstallationStore = class _RuntimeInstallationStore {
24501
+ applicationId;
24502
+ installationId;
24503
+ stateDirectory;
24504
+ #channelDirectory;
24505
+ #connectionDirectory;
24506
+ constructor(applicationId, installationId2, stateDirectory) {
24507
+ this.applicationId = applicationId;
24508
+ this.installationId = installationId2;
24509
+ this.stateDirectory = stateDirectory;
24510
+ this.#channelDirectory = join15(stateDirectory, "channels");
24511
+ this.#connectionDirectory = join15(stateDirectory, "connections");
24512
+ }
24513
+ static open = async (options, signal) => {
24514
+ signal.throwIfAborted();
24515
+ const applicationId = validateApplicationId(options.applicationId);
24516
+ const rootDirectory = resolve4(options.stateDirectory);
24517
+ const applicationDirectory = join15(rootDirectory, "installations", applicationId);
24518
+ try {
24519
+ await mkdir3(applicationDirectory, { mode: 448, recursive: true });
24520
+ } catch (cause) {
24521
+ throw new RuntimeInstallationStoreError(
24522
+ "installation_unavailable",
24523
+ "The local installation cannot be initialized",
24524
+ {
24525
+ cause
24526
+ }
24527
+ );
24528
+ }
24529
+ const storedInstallationId = await readOrCreateInstallationId(applicationDirectory, signal);
24530
+ const stateDirectory = join15(applicationDirectory, storedInstallationId);
24531
+ try {
24532
+ await mkdir3(stateDirectory, { mode: 448, recursive: true });
24533
+ } catch (cause) {
24534
+ throw new RuntimeInstallationStoreError(
24535
+ "installation_unavailable",
24536
+ "The local installation cannot be initialized",
24537
+ {
24538
+ cause
24539
+ }
24540
+ );
24541
+ }
24542
+ signal.throwIfAborted();
24543
+ return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
24544
+ };
24545
+ connectionPath = (connectionId2) => join15(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
24546
+ auditDatabasePath = (connectionId2) => join15(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
24547
+ channelIndexPath = (channelId) => join15(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
24548
+ readConnection = async (connectionId2, signal) => {
24549
+ const stored = decodeConnection(
24550
+ await readJsonFile(this.connectionPath(connectionId2), signal, "connection_not_found")
24551
+ );
24552
+ if (stored.applicationId !== this.applicationId || stored.installationId !== this.installationId) {
24553
+ throw new RuntimeInstallationStoreError(
24554
+ "connection_owner_mismatch",
24555
+ "The saved Runtime connection belongs to another installation"
24556
+ );
24557
+ }
24558
+ return stored;
24559
+ };
24560
+ #readConnectionForChannel = async (channelId, signal) => {
24561
+ const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
24562
+ const index2 = decodeChannelIndex(
24563
+ await readJsonFile(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
24564
+ );
24565
+ if (index2.applicationId !== this.applicationId || index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
24566
+ throw new RuntimeInstallationStoreError(
24567
+ "connection_owner_mismatch",
24568
+ "The saved Runtime connection belongs to another installation"
24569
+ );
24570
+ }
24571
+ return await this.readConnection(index2.connectionId, signal);
24572
+ };
24573
+ migrateLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
24574
+ try {
24575
+ return await this.#readConnectionForChannel(channelId, signal);
24576
+ } catch (cause) {
24577
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "connection_not_found") {
24578
+ throw cause;
24579
+ }
24580
+ }
24581
+ return await this.importLegacyConnection(legacyStateDirectory, channelId, signal);
24582
+ };
24583
+ saveConnection = async (input2, signal) => {
24584
+ const stored = new VerifiedRuntimeConnection(
24585
+ this.applicationId,
24586
+ this.installationId,
24587
+ connectionId(),
24588
+ validateIdentifier(input2.channelId, "invalid_connection"),
24589
+ input2.defaultWorkspace,
24590
+ parseRelayOrigin(input2.relayOrigin.toString()),
24591
+ validateRuntimeCredential(input2.runtimeCredential),
24592
+ validateIdentifier(input2.runtimeId, "invalid_connection")
24593
+ );
24594
+ await this.writeConnection(stored, signal);
24595
+ return stored;
24596
+ };
24597
+ importLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
24598
+ const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
24599
+ const legacyPath = join15(resolve4(legacyStateDirectory), "connections", `${normalizedChannelId}.json`);
24600
+ const legacy = decodeLegacyConnection(
24601
+ await readJsonFile(legacyPath, signal, "connection_not_found"),
24602
+ normalizedChannelId
24603
+ );
24604
+ const stored = new ImportedLegacyRuntimeConnection(
24605
+ this.applicationId,
24606
+ this.installationId,
24607
+ connectionId(),
24608
+ legacy.channelId,
24609
+ legacy.defaultWorkspace,
24610
+ legacy.relayOrigin,
24611
+ legacy.runtimeCredential
24612
+ );
24613
+ await this.writeConnection(stored, signal);
24614
+ return stored;
24615
+ };
24616
+ writeConnection = async (stored, signal) => {
24617
+ signal.throwIfAborted();
24618
+ try {
24619
+ await this.#readConnectionForChannel(stored.channelId, signal);
24620
+ throw new RuntimeInstallationStoreError(
24621
+ "connection_conflict",
24622
+ "A Runtime connection for this channel already exists in this installation"
24623
+ );
24624
+ } catch (cause) {
24625
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "connection_not_found") {
24626
+ throw cause;
24627
+ }
24628
+ }
24629
+ const connectionPath = this.connectionPath(stored.connectionId);
24630
+ if (stored instanceof VerifiedRuntimeConnection) {
24631
+ await writeJsonAtomically(
24632
+ connectionPath,
24633
+ {
24634
+ applicationId: stored.applicationId,
24635
+ channelId: stored.channelId,
24636
+ connectionId: stored.connectionId,
24637
+ defaultWorkspace: stored.defaultWorkspace,
24638
+ installationId: stored.installationId,
24639
+ kind: stored.kind,
24640
+ relayOrigin: stored.relayOrigin.toString(),
24641
+ runtimeCredential: stored.runtimeCredential,
24642
+ runtimeId: stored.runtimeId,
24643
+ version: 1
24644
+ },
24645
+ signal
24646
+ );
24647
+ } else {
24648
+ await writeJsonAtomically(
24649
+ connectionPath,
24650
+ {
24651
+ applicationId: stored.applicationId,
24652
+ channelId: stored.channelId,
24653
+ connectionId: stored.connectionId,
24654
+ defaultWorkspace: stored.defaultWorkspace,
24655
+ installationId: stored.installationId,
24656
+ kind: stored.kind,
24657
+ relayOrigin: stored.relayOrigin.toString(),
24658
+ runtimeCredential: stored.runtimeCredential,
24659
+ version: 1
24660
+ },
24661
+ signal
24662
+ );
24663
+ }
24664
+ await writeJsonAtomically(
24665
+ this.channelIndexPath(stored.channelId),
24666
+ {
24667
+ applicationId: this.applicationId,
24668
+ channelId: stored.channelId,
24669
+ connectionId: stored.connectionId,
24670
+ installationId: this.installationId,
24671
+ version: 1
24672
+ },
24673
+ signal
24674
+ );
24675
+ };
24676
+ };
24677
+ async function readOrCreateInstallationId(applicationDirectory, signal) {
24678
+ const pointerPath = join15(applicationDirectory, "current.json");
24679
+ try {
24680
+ return decodeInstallationPointer(await readJsonFile(pointerPath, signal, "installation_not_found")).installationId;
24681
+ } catch (cause) {
24682
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "installation_not_found") {
24683
+ throw cause;
24684
+ }
24685
+ }
24686
+ const candidate = installationId();
24687
+ try {
24688
+ await writeFile2(pointerPath, `${JSON.stringify({ installationId: candidate, version: 1 })}
24689
+ `, {
24690
+ flag: "wx",
24691
+ mode: 384
24692
+ });
24693
+ return candidate;
24694
+ } catch (cause) {
24695
+ if (!isNodeError(cause, "EEXIST")) {
24696
+ throw new RuntimeInstallationStoreError(
24697
+ "installation_unavailable",
24698
+ "The local installation cannot be initialized",
24699
+ {
24700
+ cause
24701
+ }
24702
+ );
24703
+ }
24704
+ return decodeInstallationPointer(await readJsonFile(pointerPath, signal, "installation_not_found")).installationId;
24705
+ }
24706
+ }
24707
+ async function openRuntimeInstallationStore(options, signal) {
24708
+ return await RuntimeInstallationStore.open(options, signal);
24709
+ }
24710
+
24711
+ // src/pairing/pair-local-machine.ts
24151
24712
  var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
24152
24713
  var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
24153
- var IDENTIFIER_PATTERN4 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
24714
+ var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
24154
24715
  var TOKEN_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
24155
- var MAX_CONNECTION_FILE_LENGTH = 16 * 1024;
24156
24716
  var CLAIM_RESPONSE_KEYS = ["channelId", "daemonToken", "runtimeId"];
24157
24717
  var REDEEM_RESPONSE_KEYS = ["channelId", "runtimeCredential", "runtimeId"];
24158
- var LEGACY_SAVED_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "daemonToken", "relayOrigin"];
24159
- var SAVED_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "relayOrigin", "runtimeCredential"];
24718
+ var MOBIUS_CLI_APPLICATION_ID = "dev.mobius.cli";
24160
24719
  var PairingClientError = class extends Error {
24161
24720
  code;
24162
24721
  constructor(code, message, options = {}) {
@@ -24165,10 +24724,10 @@ var PairingClientError = class extends Error {
24165
24724
  this.name = "PairingClientError";
24166
24725
  }
24167
24726
  };
24168
- function isRecord5(value) {
24727
+ function isRecord6(value) {
24169
24728
  return typeof value === "object" && value !== null && !Array.isArray(value);
24170
24729
  }
24171
- function hasExactKeys(value, expectedKeys) {
24730
+ function hasExactKeys2(value, expectedKeys) {
24172
24731
  const keys = Object.keys(value);
24173
24732
  return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
24174
24733
  }
@@ -24198,7 +24757,7 @@ function assertKnownArguments(arguments_) {
24198
24757
  }
24199
24758
  }
24200
24759
  }
24201
- function parseRelayOrigin(value) {
24760
+ function parseRelayOrigin2(value) {
24202
24761
  let url2;
24203
24762
  try {
24204
24763
  url2 = new URL(value);
@@ -24229,35 +24788,68 @@ function parsePairingCode(value) {
24229
24788
  }
24230
24789
  return code;
24231
24790
  }
24232
- function parsePairCommand(arguments_) {
24791
+ function parsePairCommand(arguments_, defaultWorkspace) {
24233
24792
  assertKnownArguments(arguments_);
24234
24793
  return {
24235
24794
  code: parsePairingCode(readSingleOption(arguments_, "--code")),
24236
24795
  pairingId: arguments_.includes("--pairing") ? validatePairingId(readSingleOption(arguments_, "--pairing")) : "",
24237
- relayOrigin: parseRelayOrigin(readSingleOption(arguments_, "--url")),
24238
- workspace: arguments_.includes("--workspace") ? readSingleOption(arguments_, "--workspace") : loadDefaultWorkspace()
24796
+ relayOrigin: parseRelayOrigin2(readSingleOption(arguments_, "--url")),
24797
+ workspace: arguments_.includes("--workspace") ? readSingleOption(arguments_, "--workspace") : defaultWorkspace
24239
24798
  };
24240
24799
  }
24241
24800
  function validatePairingId(value) {
24242
- if (!IDENTIFIER_PATTERN4.test(value)) {
24801
+ if (!IDENTIFIER_PATTERN5.test(value)) {
24243
24802
  throw new PairingClientError("invalid_pairing_id", "The Runtime pairing ID is invalid");
24244
24803
  }
24245
24804
  return value;
24246
24805
  }
24247
- function parseChannelArgument(arguments_) {
24248
- if (arguments_.length !== 2 || arguments_[0] !== "--channel") {
24249
- throw new PairingClientError("invalid_arguments", "Usage: mobius start --channel <channel-id>");
24806
+ var ResumeCommandTarget = class {
24807
+ };
24808
+ var ConnectionResumeCommandTarget = class extends ResumeCommandTarget {
24809
+ connectionId;
24810
+ constructor(connectionId2) {
24811
+ super();
24812
+ this.connectionId = connectionId2;
24250
24813
  }
24251
- const channelId = arguments_[1] ?? "";
24252
- if (!IDENTIFIER_PATTERN4.test(channelId)) {
24253
- throw new PairingClientError("invalid_channel_id", "The saved channel ID is invalid");
24814
+ resume = async (installation, signal, environment) => await resumeMobiusRuntime(installation, this.connectionId, signal, environment);
24815
+ };
24816
+ var LegacyChannelResumeCommandTarget = class extends ResumeCommandTarget {
24817
+ channelId;
24818
+ constructor(channelId) {
24819
+ super();
24820
+ this.channelId = channelId;
24821
+ }
24822
+ resume = async (installation, signal, environment) => await resumeLegacyChannel(installation, this.channelId, signal, environment);
24823
+ };
24824
+ function parseResumeArgument(arguments_) {
24825
+ if (arguments_.length !== 2) {
24826
+ throw new PairingClientError(
24827
+ "invalid_arguments",
24828
+ "Usage: mobius start --connection <connection-id> or mobius start --channel <legacy-channel-id>"
24829
+ );
24830
+ }
24831
+ const value = arguments_[1] ?? "";
24832
+ if (arguments_[0] === "--connection") {
24833
+ if (!/^mcn_[a-f0-9]{32}$/.test(value)) {
24834
+ throw new PairingClientError("invalid_connection_id", "The saved Runtime connection ID is invalid");
24835
+ }
24836
+ return new ConnectionResumeCommandTarget(value);
24837
+ }
24838
+ if (arguments_[0] === "--channel") {
24839
+ if (!IDENTIFIER_PATTERN5.test(value)) {
24840
+ throw new PairingClientError("invalid_channel_id", "The saved channel ID is invalid");
24841
+ }
24842
+ return new LegacyChannelResumeCommandTarget(value);
24254
24843
  }
24255
- return channelId;
24844
+ throw new PairingClientError(
24845
+ "invalid_arguments",
24846
+ "Usage: mobius start --connection <connection-id> or mobius start --channel <legacy-channel-id>"
24847
+ );
24256
24848
  }
24257
24849
  async function resolveDefaultWorkspace(path2) {
24258
- const requestedWorkspace = resolve3(path2);
24850
+ const requestedWorkspace = resolve5(path2);
24259
24851
  try {
24260
- await mkdir3(requestedWorkspace, { recursive: true, mode: 448 });
24852
+ await mkdir4(requestedWorkspace, { recursive: true, mode: 448 });
24261
24853
  const defaultWorkspace = await realpath6(requestedWorkspace);
24262
24854
  const metadata = await stat5(defaultWorkspace);
24263
24855
  if (!metadata.isDirectory()) {
@@ -24288,9 +24880,9 @@ async function readJsonResponse(response) {
24288
24880
  }
24289
24881
  }
24290
24882
  function readRelayError(value) {
24291
- if (isRecord5(value)) {
24883
+ if (isRecord6(value)) {
24292
24884
  const error62 = value["error"];
24293
- if (isRecord5(error62)) {
24885
+ if (isRecord6(error62)) {
24294
24886
  const code = error62["code"];
24295
24887
  const message = error62["message"];
24296
24888
  if (typeof code === "string" && typeof message === "string") {
@@ -24301,13 +24893,13 @@ function readRelayError(value) {
24301
24893
  return new PairingClientError("pairing_failed", "The relay could not pair this machine");
24302
24894
  }
24303
24895
  function decodePairingResponse(value, credentialField, expectedKeys) {
24304
- if (!isRecord5(value) || !hasExactKeys(value, expectedKeys)) {
24896
+ if (!isRecord6(value) || !hasExactKeys2(value, expectedKeys)) {
24305
24897
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
24306
24898
  }
24307
24899
  const channelId = value["channelId"];
24308
24900
  const runtimeCredential2 = value[credentialField];
24309
24901
  const runtimeId = value["runtimeId"];
24310
- if (typeof channelId !== "string" || !IDENTIFIER_PATTERN4.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN4.test(runtimeId)) {
24902
+ if (typeof channelId !== "string" || !IDENTIFIER_PATTERN5.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN5.test(runtimeId)) {
24311
24903
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
24312
24904
  }
24313
24905
  return { channelId, runtimeCredential: runtimeCredential2, runtimeId };
@@ -24347,155 +24939,114 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
24347
24939
  }
24348
24940
  return options.pairingId.length > 0 ? decodePairingResponse(value, "runtimeCredential", REDEEM_RESPONSE_KEYS) : decodePairingResponse(value, "daemonToken", CLAIM_RESPONSE_KEYS);
24349
24941
  }
24350
- async function persistConnection(channelId, relayOrigin, runtimeCredential2, defaultWorkspace, environment) {
24351
- const connectionsDirectory = join15(readStateDirectory(environment), "connections");
24352
- await mkdir3(connectionsDirectory, { mode: 448, recursive: true });
24353
- const connectionPath = join15(connectionsDirectory, `${channelId}.json`);
24354
- const temporaryPath = join15(connectionsDirectory, `.${channelId}.${randomUUID()}.tmp`);
24355
- await writeFile2(
24356
- temporaryPath,
24357
- `${JSON.stringify(
24358
- {
24359
- defaultWorkspace,
24360
- channelId,
24361
- relayOrigin: relayOrigin.toString(),
24362
- runtimeCredential: runtimeCredential2
24363
- },
24364
- null,
24365
- 2
24366
- )}
24367
- `,
24368
- { flag: "wx", mode: 384 }
24369
- );
24370
- await rename3(temporaryPath, connectionPath);
24371
- return connectionPath;
24372
- }
24373
- function decodeSavedConnection(value, expectedChannelId) {
24374
- if (!isRecord5(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
24375
- throw new PairingClientError("invalid_connection", "The saved connection is invalid");
24376
- }
24377
- const defaultWorkspace = value["defaultWorkspace"];
24378
- const channelId = value["channelId"];
24379
- const runtimeCredential2 = value["runtimeCredential"] ?? value["daemonToken"];
24380
- const relayOrigin = value["relayOrigin"];
24381
- if (typeof defaultWorkspace !== "string" || typeof channelId !== "string" || channelId !== expectedChannelId || !IDENTIFIER_PATTERN4.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof relayOrigin !== "string") {
24382
- throw new PairingClientError("invalid_connection", "The saved connection is invalid");
24383
- }
24384
- return {
24385
- defaultWorkspace,
24386
- channelId,
24387
- relayOrigin: parseRelayOrigin(relayOrigin),
24388
- runtimeCredential: runtimeCredential2
24389
- };
24390
- }
24391
- async function readSavedConnection(channelId, environment) {
24392
- const connectionPath = join15(readStateDirectory(environment), "connections", `${channelId}.json`);
24393
- let encoded = "";
24394
- const handle = await open4(connectionPath, "r");
24395
- try {
24396
- const metadata = await handle.stat();
24397
- if (!metadata.isFile() || metadata.size > MAX_CONNECTION_FILE_LENGTH) {
24398
- throw new PairingClientError("invalid_connection", "The saved connection is invalid");
24399
- }
24400
- encoded = await handle.readFile({ encoding: "utf8" });
24401
- } finally {
24402
- await handle.close();
24403
- }
24404
- let value;
24405
- try {
24406
- value = JSON.parse(encoded);
24407
- } catch (error62) {
24408
- throw new PairingClientError("invalid_connection", "The saved connection is invalid", { cause: error62 });
24409
- }
24410
- const connection = decodeSavedConnection(value, channelId);
24411
- return {
24412
- defaultWorkspace: await resolveDefaultWorkspace(connection.defaultWorkspace),
24413
- channelId: connection.channelId,
24414
- relayOrigin: connection.relayOrigin,
24415
- runtimeCredential: connection.runtimeCredential
24416
- };
24417
- }
24418
24942
  function assertInventoryUsable(inventory) {
24419
24943
  if (inventory.available.length + inventory.installable.length === 0) {
24420
24944
  throw new PairingClientError("no_supported_agent", "No supported Agent is available for local discovery");
24421
24945
  }
24422
24946
  }
24423
- function buildPairedDaemon(connection, connectionPath, inventory, environment) {
24947
+ function buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext) {
24424
24948
  assertInventoryUsable(inventory);
24425
24949
  const relayUrl = mobiusApiUrl(connection.relayOrigin, "/v1/runtimes/connect");
24426
24950
  relayUrl.protocol = relayUrl.protocol === "https:" ? "wss:" : "ws:";
24427
24951
  relayUrl.searchParams.set("token", connection.runtimeCredential);
24428
- const auditDatabasePath = join15(readStateDirectory(environment), "audit", `${connection.channelId}.sqlite`);
24429
24952
  return {
24430
24953
  channelUrl: new URL(`/channels/${encodeURIComponent(connection.channelId)}`, connection.relayOrigin).toString(),
24954
+ connectionId: connection.connectionId,
24431
24955
  config: createDaemonConfig(
24432
24956
  {
24433
- defaultWorkspace: connection.defaultWorkspace,
24434
- auditDatabasePath,
24957
+ defaultWorkspace,
24958
+ auditDatabasePath: installation.auditDatabasePath(connection.connectionId),
24435
24959
  channelId: connection.channelId,
24436
24960
  relayUrl
24437
24961
  },
24438
24962
  inventory.readyAgents(),
24439
- inventory.installable
24963
+ inventory.installable,
24964
+ localContext,
24965
+ new OpaqueDaemonReconnectTarget(connection.connectionId)
24440
24966
  ),
24441
- connectionPath
24967
+ connectionPath: installation.connectionPath(connection.connectionId)
24442
24968
  };
24443
24969
  }
24444
- async function pairRuntime(options, signal, environment) {
24970
+ async function pairRuntime(installation, options, signal, environment) {
24971
+ const localContext = new DaemonLocalContext(installation.stateDirectory, environment);
24445
24972
  const defaultWorkspace = await resolveDefaultWorkspace(options.workspace);
24446
24973
  const inventory = await discoverLocalAgentInventory({
24447
24974
  defaultWorkspace,
24448
- environment,
24975
+ environment: localContext.environment,
24449
24976
  signal
24450
24977
  });
24451
24978
  assertInventoryUsable(inventory);
24452
24979
  const agents = inventory.readyAgents();
24453
24980
  const claim2 = await claimPairing(options, defaultWorkspace, agents, inventory.installable, signal);
24454
- const connectionPath = await persistConnection(
24455
- claim2.channelId,
24456
- options.relayOrigin,
24457
- claim2.runtimeCredential,
24458
- defaultWorkspace,
24459
- environment
24460
- );
24461
- return buildPairedDaemon(
24981
+ const connection = await installation.saveConnection(
24462
24982
  {
24463
- defaultWorkspace,
24464
24983
  channelId: claim2.channelId,
24984
+ defaultWorkspace,
24465
24985
  relayOrigin: options.relayOrigin,
24466
- runtimeCredential: claim2.runtimeCredential
24986
+ runtimeCredential: claim2.runtimeCredential,
24987
+ runtimeId: claim2.runtimeId
24467
24988
  },
24468
- connectionPath,
24469
- inventory,
24470
- environment
24989
+ signal
24471
24990
  );
24991
+ return buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext);
24472
24992
  }
24473
- async function pairLocalMachine(arguments_, signal = new AbortController().signal) {
24474
- return await pairRuntime(parsePairCommand(arguments_), signal, process.env);
24475
- }
24476
- async function resumeMobiusRuntime(channelId, signal, environment = process.env) {
24477
- const normalizedChannelId = validatePairingId(channelId);
24478
- const connectionPath = join15(readStateDirectory(environment), "connections", `${normalizedChannelId}.json`);
24479
- const connection = await readSavedConnection(normalizedChannelId, environment);
24993
+ async function resumeRuntimeConnection(installation, connection, signal, environment) {
24994
+ const localContext = new DaemonLocalContext(installation.stateDirectory, environment);
24995
+ const defaultWorkspace = await resolveDefaultWorkspace(connection.defaultWorkspace);
24480
24996
  const inventory = await discoverLocalAgentInventory({
24481
- defaultWorkspace: connection.defaultWorkspace,
24482
- environment,
24997
+ defaultWorkspace,
24998
+ environment: localContext.environment,
24483
24999
  signal
24484
25000
  });
24485
- return buildPairedDaemon(connection, connectionPath, inventory, environment);
25001
+ return buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext);
25002
+ }
25003
+ async function resumeMobiusRuntime(installation, connectionId2, signal, environment = process.env) {
25004
+ const connection = await installation.readConnection(connectionId2, signal);
25005
+ return await resumeRuntimeConnection(installation, connection, signal, environment);
25006
+ }
25007
+ async function resumeLegacyChannel(installation, channelId, signal, environment) {
25008
+ const connection = await installation.migrateLegacyConnection(readStateDirectory(environment), channelId, signal);
25009
+ return await resumeRuntimeConnection(installation, connection, signal, environment);
25010
+ }
25011
+ async function openMobiusCliInstallation(signal, environment) {
25012
+ return await openRuntimeInstallationStore(
25013
+ {
25014
+ applicationId: MOBIUS_CLI_APPLICATION_ID,
25015
+ stateDirectory: readStateDirectory(environment)
25016
+ },
25017
+ signal
25018
+ );
25019
+ }
25020
+ async function pairLocalMachine(arguments_, signal = new AbortController().signal) {
25021
+ const requested = parsePairCommand(arguments_, "");
25022
+ const installation = await openMobiusCliInstallation(signal, process.env);
25023
+ const localContext = new DaemonLocalContext(installation.stateDirectory, process.env);
25024
+ return await pairRuntime(
25025
+ installation,
25026
+ {
25027
+ code: requested.code,
25028
+ pairingId: requested.pairingId,
25029
+ relayOrigin: requested.relayOrigin,
25030
+ workspace: arguments_.includes("--workspace") ? requested.workspace : loadDefaultWorkspace(localContext.environment)
25031
+ },
25032
+ signal,
25033
+ process.env
25034
+ );
24486
25035
  }
24487
25036
  async function resumeLocalMachine(arguments_, signal = new AbortController().signal) {
24488
- return await resumeMobiusRuntime(parseChannelArgument(arguments_), signal, process.env);
25037
+ const target = parseResumeArgument(arguments_);
25038
+ const installation = await openMobiusCliInstallation(signal, process.env);
25039
+ return await target.resume(installation, signal, process.env);
24489
25040
  }
24490
25041
 
24491
25042
  // src/audit/audit-store.ts
24492
25043
  import { mkdirSync } from "node:fs";
24493
- import { dirname as dirname3 } from "node:path";
25044
+ import { dirname as dirname4 } from "node:path";
24494
25045
  import { DatabaseSync } from "node:sqlite";
24495
25046
  var AuditStore = class {
24496
25047
  database;
24497
25048
  constructor(path2) {
24498
- mkdirSync(dirname3(path2), { recursive: true });
25049
+ mkdirSync(dirname4(path2), { recursive: true });
24499
25050
  this.database = new DatabaseSync(path2);
24500
25051
  this.database.exec(`
24501
25052
  CREATE TABLE IF NOT EXISTS audit_events (
@@ -24850,7 +25401,7 @@ async function replaceImageMarkers(text3, replace) {
24850
25401
 
24851
25402
  // src/acp/activity.ts
24852
25403
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
24853
- function isRecord6(value) {
25404
+ function isRecord7(value) {
24854
25405
  return typeof value === "object" && value !== null && !Array.isArray(value);
24855
25406
  }
24856
25407
  var AcpActivity = class _AcpActivity {
@@ -25084,16 +25635,16 @@ async function normalizeToolContent(content3, prepareContent) {
25084
25635
  return normalized;
25085
25636
  }
25086
25637
  function rawMcpToolContent(rawOutput) {
25087
- if (!isRecord6(rawOutput)) {
25638
+ if (!isRecord7(rawOutput)) {
25088
25639
  return [];
25089
25640
  }
25090
- const result = isRecord6(rawOutput["result"]) ? rawOutput["result"] : rawOutput;
25641
+ const result = isRecord7(rawOutput["result"]) ? rawOutput["result"] : rawOutput;
25091
25642
  const content3 = result["content"];
25092
25643
  if (!Array.isArray(content3)) {
25093
25644
  return [];
25094
25645
  }
25095
25646
  return content3.flatMap((item) => {
25096
- if (!isRecord6(item) || item["type"] !== "image" || typeof item["data"] !== "string" || typeof item["mimeType"] !== "string") {
25647
+ if (!isRecord7(item) || item["type"] !== "image" || typeof item["data"] !== "string" || typeof item["mimeType"] !== "string") {
25097
25648
  return [];
25098
25649
  }
25099
25650
  const uri = item["uri"];
@@ -25170,7 +25721,7 @@ function contentPhase(content3) {
25170
25721
  return "";
25171
25722
  }
25172
25723
  const codex = metadata["codex"];
25173
- if (!isRecord6(codex)) {
25724
+ if (!isRecord7(codex)) {
25174
25725
  return "";
25175
25726
  }
25176
25727
  const phase = codex["phase"];
@@ -27957,10 +28508,10 @@ function resolveAll(constructs2, events, context) {
27957
28508
  const called = [];
27958
28509
  let index2 = -1;
27959
28510
  while (++index2 < constructs2.length) {
27960
- const resolve5 = constructs2[index2].resolveAll;
27961
- if (resolve5 && !called.includes(resolve5)) {
27962
- events = resolve5(events, context);
27963
- called.push(resolve5);
28511
+ const resolve7 = constructs2[index2].resolveAll;
28512
+ if (resolve7 && !called.includes(resolve7)) {
28513
+ events = resolve7(events, context);
28514
+ called.push(resolve7);
27964
28515
  }
27965
28516
  }
27966
28517
  return events;
@@ -32599,7 +33150,7 @@ var SessionConfigProtocolError = class extends Error {
32599
33150
  this.name = "SessionConfigProtocolError";
32600
33151
  }
32601
33152
  };
32602
- function isRecord7(value) {
33153
+ function isRecord8(value) {
32603
33154
  return typeof value === "object" && value !== null && !Array.isArray(value);
32604
33155
  }
32605
33156
  function readString2(value, fallback = "") {
@@ -32626,7 +33177,7 @@ function normalizeConfigValues(value) {
32626
33177
  }
32627
33178
  const normalized = [];
32628
33179
  for (const entry of value) {
32629
- if (!isRecord7(entry)) {
33180
+ if (!isRecord8(entry)) {
32630
33181
  continue;
32631
33182
  }
32632
33183
  const groupedOptions = entry["options"];
@@ -32634,7 +33185,7 @@ function normalizeConfigValues(value) {
32634
33185
  const groupId = readString2(entry["group"]);
32635
33186
  const groupName = readString2(entry["name"]);
32636
33187
  for (const groupedOption of groupedOptions) {
32637
- if (isRecord7(groupedOption)) {
33188
+ if (isRecord8(groupedOption)) {
32638
33189
  normalized.push(normalizeConfigValue(groupedOption, groupId, groupName));
32639
33190
  }
32640
33191
  }
@@ -32648,7 +33199,7 @@ function normalizeConfigOptions(value, modes) {
32648
33199
  const normalized = [];
32649
33200
  if (Array.isArray(value)) {
32650
33201
  for (const option of value) {
32651
- if (!isRecord7(option)) {
33202
+ if (!isRecord8(option)) {
32652
33203
  continue;
32653
33204
  }
32654
33205
  const id = truncate2(readString2(option["id"]), 128);
@@ -32687,12 +33238,12 @@ function normalizeConfigOptions(value, modes) {
32687
33238
  }
32688
33239
  }
32689
33240
  }
32690
- if (isRecord7(modes)) {
33241
+ if (isRecord8(modes)) {
32691
33242
  const values = [];
32692
33243
  const availableModes = modes["availableModes"];
32693
33244
  if (Array.isArray(availableModes)) {
32694
33245
  for (const mode of availableModes) {
32695
- if (!isRecord7(mode)) {
33246
+ if (!isRecord8(mode)) {
32696
33247
  continue;
32697
33248
  }
32698
33249
  const id = truncate2(readString2(mode["id"]), 500);
@@ -32831,7 +33382,7 @@ function ensureRequiredExecutionOptions(current, permission) {
32831
33382
  return [permission, model, reasoningEffort, ...optional2].slice(0, MAXIMUM_CONFIG_OPTIONS);
32832
33383
  }
32833
33384
  function normalizeStandardLifecycle(response) {
32834
- const lifecycle = isRecord7(response) ? response : {};
33385
+ const lifecycle = isRecord8(response) ? response : {};
32835
33386
  return ensureReasoningEffortOption(normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]));
32836
33387
  }
32837
33388
  function replaceStandardConfigOptions(current, value) {
@@ -32873,7 +33424,7 @@ var StandardSessionConfigProtocol = class {
32873
33424
  "ACP agent exited while changing session configuration",
32874
33425
  change.signal
32875
33426
  );
32876
- if (!isRecord7(response) || !Array.isArray(response["configOptions"])) {
33427
+ if (!isRecord8(response) || !Array.isArray(response["configOptions"])) {
32877
33428
  throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
32878
33429
  }
32879
33430
  return replaceStandardConfigOptions(current, response["configOptions"]);
@@ -32887,18 +33438,18 @@ var standardSessionConfigProtocol = new StandardSessionConfigProtocol();
32887
33438
  var LEGACY_MODEL_CONFIG_ID = "grok_build_legacy_model";
32888
33439
  var LEGACY_REASONING_EFFORT_CONFIG_ID = "grok_build_legacy_reasoning_effort";
32889
33440
  function legacyOptions(response) {
32890
- if (!isRecord7(response)) {
33441
+ if (!isRecord8(response)) {
32891
33442
  return [];
32892
33443
  }
32893
33444
  const metadata = response["_meta"];
32894
- if (!isRecord7(metadata)) {
33445
+ if (!isRecord8(metadata)) {
32895
33446
  return [];
32896
33447
  }
32897
33448
  const sessionConfig = metadata["x.ai/sessionConfig"];
32898
- if (!isRecord7(sessionConfig) || !Array.isArray(sessionConfig["options"])) {
33449
+ if (!isRecord8(sessionConfig) || !Array.isArray(sessionConfig["options"])) {
32899
33450
  return [];
32900
33451
  }
32901
- return sessionConfig["options"].slice(0, 500).filter(isRecord7);
33452
+ return sessionConfig["options"].slice(0, 500).filter(isRecord8);
32902
33453
  }
32903
33454
  function legacyValue(option) {
32904
33455
  const value = readString2(option["id"]);
@@ -32911,7 +33462,7 @@ function legacyValue(option) {
32911
33462
  };
32912
33463
  }
32913
33464
  function modelsRecord(response) {
32914
- if (!isRecord7(response) || !isRecord7(response["models"])) {
33465
+ if (!isRecord8(response) || !isRecord8(response["models"])) {
32915
33466
  return {};
32916
33467
  }
32917
33468
  return response["models"];
@@ -32930,7 +33481,7 @@ function legacyModelOptions(response) {
32930
33481
  }
32931
33482
  if (values.length === 0 && Array.isArray(models["availableModels"])) {
32932
33483
  for (const model of models["availableModels"]) {
32933
- if (!isRecord7(model)) {
33484
+ if (!isRecord8(model)) {
32934
33485
  continue;
32935
33486
  }
32936
33487
  const value = readString2(model["modelId"]).slice(0, 500);
@@ -33010,7 +33561,7 @@ function legacyReasoningEffortOptions(response) {
33010
33561
  return [result];
33011
33562
  }
33012
33563
  function normalizeGrokLifecycle(response) {
33013
- const lifecycle = isRecord7(response) ? response : {};
33564
+ const lifecycle = isRecord8(response) ? response : {};
33014
33565
  const standard = normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]);
33015
33566
  const normalized = [...standard];
33016
33567
  if (!normalized.some((option) => option.category === "model")) {
@@ -33029,11 +33580,11 @@ function updateCurrentValue2(current, category, value) {
33029
33580
  return current.map((option) => option.category === category ? { ...option, currentValue: value } : option);
33030
33581
  }
33031
33582
  function validateGrokResponse(response, modelId) {
33032
- if (!isRecord7(response) || !isRecord7(response["_meta"])) {
33583
+ if (!isRecord8(response) || !isRecord8(response["_meta"])) {
33033
33584
  throw new SessionConfigProtocolError("Grok Build returned an invalid session configuration response");
33034
33585
  }
33035
33586
  const model = response["_meta"]["model"];
33036
- const appliedModel = isRecord7(model) ? model["Ok"] : model;
33587
+ const appliedModel = isRecord8(model) ? model["Ok"] : model;
33037
33588
  if (appliedModel !== modelId) {
33038
33589
  throw new SessionConfigProtocolError("Grok Build returned an invalid session configuration response");
33039
33590
  }
@@ -33140,7 +33691,7 @@ var AcpHistoryReplay = class {
33140
33691
 
33141
33692
  // src/acp/session-store.ts
33142
33693
  import { mkdirSync as mkdirSync2 } from "node:fs";
33143
- import { dirname as dirname4 } from "node:path";
33694
+ import { dirname as dirname5 } from "node:path";
33144
33695
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
33145
33696
  var AcpStoredSession = class {
33146
33697
  additionalDirectories;
@@ -33243,7 +33794,7 @@ var MemoryAcpSessionStore = class {
33243
33794
  var SqliteAcpSessionStore = class {
33244
33795
  #database;
33245
33796
  constructor(path2) {
33246
- mkdirSync2(dirname4(path2), { recursive: true });
33797
+ mkdirSync2(dirname5(path2), { recursive: true });
33247
33798
  this.#database = new DatabaseSync2(path2);
33248
33799
  this.#database.exec(`
33249
33800
  CREATE TABLE IF NOT EXISTS acp_deleted_sessions (session_id TEXT PRIMARY KEY) STRICT;
@@ -33544,7 +34095,7 @@ function createWritableAcpStream(output2) {
33544
34095
  if (outputFailure !== void 0) {
33545
34096
  return Promise.reject(outputFailure);
33546
34097
  }
33547
- return new Promise((resolve5, reject) => {
34098
+ return new Promise((resolve7, reject) => {
33548
34099
  pendingWriteFailures.add(reject);
33549
34100
  output2.write(chunk, (error62) => {
33550
34101
  pendingWriteFailures.delete(reject);
@@ -33557,7 +34108,7 @@ function createWritableAcpStream(output2) {
33557
34108
  reject(outputFailure);
33558
34109
  return;
33559
34110
  }
33560
- resolve5();
34111
+ resolve7();
33561
34112
  });
33562
34113
  });
33563
34114
  }
@@ -33566,7 +34117,7 @@ function createWritableAcpStream(output2) {
33566
34117
  function truncate3(value, maximumLength) {
33567
34118
  return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
33568
34119
  }
33569
- function isRecord8(value) {
34120
+ function isRecord9(value) {
33570
34121
  return typeof value === "object" && value !== null && !Array.isArray(value);
33571
34122
  }
33572
34123
  function readString4(value, fallback = "") {
@@ -33600,7 +34151,7 @@ function normalizeElicitationOptions(schema) {
33600
34151
  const oneOf = schema["oneOf"];
33601
34152
  if (Array.isArray(oneOf)) {
33602
34153
  for (const option of oneOf) {
33603
- if (isRecord8(option) && typeof option["const"] === "string") {
34154
+ if (isRecord9(option) && typeof option["const"] === "string") {
33604
34155
  normalized.push({
33605
34156
  description: truncate3(readString4(option["description"]), 500),
33606
34157
  label: truncate3(readString4(option["title"], option["const"]), 255),
@@ -33620,7 +34171,7 @@ function normalizeElicitationOptions(schema) {
33620
34171
  return normalized.slice(0, 200);
33621
34172
  }
33622
34173
  const items = schema["items"];
33623
- if (!isRecord8(items)) {
34174
+ if (!isRecord9(items)) {
33624
34175
  return normalized;
33625
34176
  }
33626
34177
  const anyOf = items["anyOf"];
@@ -33633,7 +34184,7 @@ function numericString(value) {
33633
34184
  return typeof value === "number" && Number.isFinite(value) ? value.toString() : "";
33634
34185
  }
33635
34186
  function normalizeElicitationFields(requestedSchema) {
33636
- if (!isRecord8(requestedSchema) || !isRecord8(requestedSchema["properties"])) {
34187
+ if (!isRecord9(requestedSchema) || !isRecord9(requestedSchema["properties"])) {
33637
34188
  return [];
33638
34189
  }
33639
34190
  const properties2 = requestedSchema["properties"];
@@ -33643,7 +34194,7 @@ function normalizeElicitationFields(requestedSchema) {
33643
34194
  );
33644
34195
  const normalized = [];
33645
34196
  for (const [name, property] of Object.entries(properties2)) {
33646
- if (!isRecord8(property)) {
34197
+ if (!isRecord9(property)) {
33647
34198
  continue;
33648
34199
  }
33649
34200
  const type = elicitationFieldType(property["type"]);
@@ -33734,7 +34285,7 @@ function validateElicitationContent(encoded, requestedSchema) {
33734
34285
  "invalid_elicitation_response"
33735
34286
  );
33736
34287
  }
33737
- if (!isRecord8(decoded) || !isRecord8(requestedSchema) || !isRecord8(requestedSchema["properties"])) {
34288
+ if (!isRecord9(decoded) || !isRecord9(requestedSchema) || !isRecord9(requestedSchema["properties"])) {
33738
34289
  throw new AcpExecutionError(
33739
34290
  "Elicitation response does not match the requested form",
33740
34291
  {},
@@ -33754,7 +34305,7 @@ function validateElicitationContent(encoded, requestedSchema) {
33754
34305
  const validated = {};
33755
34306
  for (const [name, value] of Object.entries(decoded)) {
33756
34307
  const property = properties2[name];
33757
- if (!isRecord8(property)) {
34308
+ if (!isRecord9(property)) {
33758
34309
  throw new AcpExecutionError(
33759
34310
  `Elicitation field ${name} was not requested`,
33760
34311
  {},
@@ -33970,9 +34521,9 @@ var AcpProcessSession = class _AcpProcessSession {
33970
34521
  stderr.on("data", (chunk) => {
33971
34522
  process.stderr.write(`[${agent.id}-acp] ${chunk}`);
33972
34523
  });
33973
- this.#processExit = new Promise((resolve5) => {
33974
- this.#child.once("error", resolve5);
33975
- this.#child.once("exit", resolve5);
34524
+ this.#processExit = new Promise((resolve7) => {
34525
+ this.#child.once("error", resolve7);
34526
+ this.#child.once("exit", resolve7);
33976
34527
  });
33977
34528
  const stream = ndJsonStream2(createWritableAcpStream(stdin), readableWebStream(stdout));
33978
34529
  this.#connection = createAcpClient(this).connect(stream);
@@ -34679,7 +35230,7 @@ var AcpProcessSession = class _AcpProcessSession {
34679
35230
  "ACP agent exited during steering",
34680
35231
  options.signal
34681
35232
  );
34682
- if (!isRecord8(response)) {
35233
+ if (!isRecord9(response)) {
34683
35234
  throw new AcpExecutionError(
34684
35235
  "ACP agent returned an invalid steering response",
34685
35236
  {},
@@ -36539,7 +37090,7 @@ var AgentInstallationManager = class {
36539
37090
 
36540
37091
  // src/agent-installation/fixed-installation-executor.ts
36541
37092
  import { realpathSync as realpathSync2, statSync as statSync2 } from "node:fs";
36542
- import { resolve as resolve4 } from "node:path";
37093
+ import { resolve as resolve6 } from "node:path";
36543
37094
  function findSpecification(specifications, agentId) {
36544
37095
  for (const specification of specifications) {
36545
37096
  if (specification.id === agentId) {
@@ -36550,7 +37101,7 @@ function findSpecification(specifications, agentId) {
36550
37101
  }
36551
37102
  function resolveDefaultWorkspace2(path2) {
36552
37103
  try {
36553
- const directory = realpathSync2(resolve4(path2));
37104
+ const directory = realpathSync2(resolve6(path2));
36554
37105
  if (!statSync2(directory).isDirectory()) {
36555
37106
  throw new Error("Default workspace is not a directory");
36556
37107
  }
@@ -36565,7 +37116,7 @@ function resolveDefaultWorkspace2(path2) {
36565
37116
  }
36566
37117
  function resolveIntegrationStateDirectory(path2) {
36567
37118
  try {
36568
- const directory = realpathSync2(resolve4(path2));
37119
+ const directory = realpathSync2(resolve6(path2));
36569
37120
  const metadata = statSync2(directory);
36570
37121
  if (!metadata.isDirectory() || typeof process.getuid === "function" && metadata.uid !== process.getuid()) {
36571
37122
  throw new Error("Installation directory is not user-owned");
@@ -36820,7 +37371,7 @@ async function streamLocalFile(command, send2, signal) {
36820
37371
  }
36821
37372
 
36822
37373
  // src/artifacts/runtime-artifact-uploader.ts
36823
- import { createHash as createHash2 } from "node:crypto";
37374
+ import { createHash as createHash3 } from "node:crypto";
36824
37375
 
36825
37376
  // ../mobius-sdk/src/errors.ts
36826
37377
  var MobiusError = class extends Error {
@@ -36845,15 +37396,15 @@ var MobiusValidationError = class extends MobiusError {
36845
37396
  };
36846
37397
 
36847
37398
  // ../mobius-sdk/src/resources.ts
36848
- var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
37399
+ var IDENTIFIER_PATTERN6 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
36849
37400
  function invalidResponse(message) {
36850
37401
  return new MobiusProtocolError(message);
36851
37402
  }
36852
- function isRecord9(value) {
37403
+ function isRecord10(value) {
36853
37404
  return typeof value === "object" && value !== null && !Array.isArray(value);
36854
37405
  }
36855
37406
  function record3(value, name) {
36856
- if (!isRecord9(value)) {
37407
+ if (!isRecord10(value)) {
36857
37408
  throw invalidResponse(`The service returned an invalid ${name}`);
36858
37409
  }
36859
37410
  return value;
@@ -36867,7 +37418,7 @@ function stringField(value, field, maximumLength = 85e5) {
36867
37418
  }
36868
37419
  function identifierField(value, field) {
36869
37420
  const candidate = stringField(value, field, 128);
36870
- if (!IDENTIFIER_PATTERN5.test(candidate)) {
37421
+ if (!IDENTIFIER_PATTERN6.test(candidate)) {
36871
37422
  throw invalidResponse(`The service returned an invalid ${field}`);
36872
37423
  }
36873
37424
  return candidate;
@@ -37139,7 +37690,7 @@ async function uploadRuntimeArtifact(config2, sessionId, artifact, signal) {
37139
37690
  artifact.name,
37140
37691
  artifact.mimeType,
37141
37692
  artifact.bytes.byteLength,
37142
- createHash2("sha256").update(artifact.bytes).digest("hex")
37693
+ createHash3("sha256").update(artifact.bytes).digest("hex")
37143
37694
  );
37144
37695
  } catch (cause) {
37145
37696
  translateSdkError(cause);
@@ -37216,7 +37767,7 @@ var LocalAuthorizationError = class extends Error {
37216
37767
  // src/authorization/workspace-directory.ts
37217
37768
  import { readdir as readdir2, realpath as realpath9, stat as stat8 } from "node:fs/promises";
37218
37769
  import { homedir as homedir2 } from "node:os";
37219
- import { basename as basename5, dirname as dirname5, isAbsolute as isAbsolute10, join as join16, normalize as normalize4, relative as relative4 } from "node:path";
37770
+ import { basename as basename5, dirname as dirname6, isAbsolute as isAbsolute10, join as join16, normalize as normalize4, relative as relative4 } from "node:path";
37220
37771
  var WorkspaceDirectoryListing = class {
37221
37772
  directoryId;
37222
37773
  directoryLabel;
@@ -37340,7 +37891,7 @@ var WorkspaceDirectoryService = class {
37340
37891
  }
37341
37892
  }
37342
37893
  entries.sort((a, b) => a.name.localeCompare(b.name));
37343
- const parent = dirname5(target);
37894
+ const parent = dirname6(target);
37344
37895
  return new WorkspaceDirectoryListing(
37345
37896
  id,
37346
37897
  this.label(target),
@@ -38032,13 +38583,13 @@ var NativeSessionService = class {
38032
38583
  };
38033
38584
 
38034
38585
  // src/prompt-artifact-resolver.ts
38035
- import { createHash as createHash3 } from "node:crypto";
38586
+ import { createHash as createHash4 } from "node:crypto";
38036
38587
  import { fetch as fetch5 } from "undici";
38037
38588
  var ARTIFACT_SCHEME = "mobius-artifact:";
38038
38589
  var ARTIFACT_DOWNLOAD_TIMEOUT_MILLISECONDS = 2e4;
38039
38590
  var MAX_AGENT_IMAGE_BASE64_LENGTH = 4e6;
38040
38591
  var MAX_AGENT_RESOURCE_BYTE_LENGTH = 1e6;
38041
- var IDENTIFIER_PATTERN6 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
38592
+ var IDENTIFIER_PATTERN7 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
38042
38593
  var PromptArtifactError = class extends Error {
38043
38594
  code;
38044
38595
  constructor(code, message, options = {}) {
@@ -38081,7 +38632,7 @@ function parseReference(resource) {
38081
38632
  const encodedByteLength2 = url2.searchParams.get("byteLength") ?? "";
38082
38633
  const sha256 = url2.searchParams.get("sha256") ?? "";
38083
38634
  const byteLength = Number(encodedByteLength2);
38084
- if (url2.protocol !== ARTIFACT_SCHEME || url2.hash.length > 0 || resource.type !== "link" || resource.text.length > 0 || !IDENTIFIER_PATTERN6.test(artifactId) || keys.length !== 2 || keys[0] !== "byteLength" || keys[1] !== "sha256" || !/^[1-9][0-9]*$/.test(encodedByteLength2) || !Number.isSafeInteger(byteLength) || !/^[a-f0-9]{64}$/.test(sha256)) {
38635
+ if (url2.protocol !== ARTIFACT_SCHEME || url2.hash.length > 0 || resource.type !== "link" || resource.text.length > 0 || !IDENTIFIER_PATTERN7.test(artifactId) || keys.length !== 2 || keys[0] !== "byteLength" || keys[1] !== "sha256" || !/^[1-9][0-9]*$/.test(encodedByteLength2) || !Number.isSafeInteger(byteLength) || !/^[a-f0-9]{64}$/.test(sha256)) {
38085
38636
  throw new PromptArtifactError("artifact_reference_invalid", "The prompt artifact reference is invalid");
38086
38637
  }
38087
38638
  return new PromptArtifactReference(artifactId, byteLength, sha256, resource);
@@ -38171,7 +38722,7 @@ async function download(config2, command, reference, signal) {
38171
38722
  );
38172
38723
  }
38173
38724
  const bytes = await responseBytes(response, reference.byteLength, requestSignal);
38174
- if (createHash3("sha256").update(bytes).digest("hex") !== reference.sha256) {
38725
+ if (createHash4("sha256").update(bytes).digest("hex") !== reference.sha256) {
38175
38726
  throw new PromptArtifactError(
38176
38727
  "artifact_integrity_failed",
38177
38728
  "The prompt artifact failed integrity validation"
@@ -38261,7 +38812,7 @@ var RelayConnectionError = class extends Error {
38261
38812
  };
38262
38813
  function connectRelay(url2, signal) {
38263
38814
  signal.throwIfAborted();
38264
- return new Promise((resolve5, reject) => {
38815
+ return new Promise((resolve7, reject) => {
38265
38816
  const endpoint = new URL(url2);
38266
38817
  const headers = runtimeAuthorization(endpoint);
38267
38818
  endpoint.searchParams.delete("token");
@@ -38324,7 +38875,7 @@ function connectRelay(url2, signal) {
38324
38875
  }
38325
38876
  finished = true;
38326
38877
  cleanup();
38327
- resolve5(socket);
38878
+ resolve7(socket);
38328
38879
  };
38329
38880
  function onTimeout() {
38330
38881
  fail(
@@ -38585,7 +39136,7 @@ var RelayConnectionLiveness = class {
38585
39136
 
38586
39137
  // src/relay-connection/session-event-outbox.ts
38587
39138
  import { mkdirSync as mkdirSync3 } from "node:fs";
38588
- import { dirname as dirname6 } from "node:path";
39139
+ import { dirname as dirname7 } from "node:path";
38589
39140
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
38590
39141
  var DEFAULT_OUTBOX_LIMITS = {
38591
39142
  criticalEventBytes: 136 * 1024 * 1024,
@@ -38651,7 +39202,7 @@ var SessionEventOutbox = class {
38651
39202
  constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
38652
39203
  validateLimits(limits);
38653
39204
  this.#limits = limits;
38654
- mkdirSync3(dirname6(path2), { recursive: true });
39205
+ mkdirSync3(dirname7(path2), { recursive: true });
38655
39206
  this.#database = new DatabaseSync3(path2);
38656
39207
  this.#database.exec(`
38657
39208
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
@@ -40322,12 +40873,12 @@ function waitForRelayRetry(signal, timer) {
40322
40873
  if (signal.aborted) {
40323
40874
  return Promise.resolve();
40324
40875
  }
40325
- return new Promise((resolve5) => {
40876
+ return new Promise((resolve7) => {
40326
40877
  const retry = timer.schedule(finish, RELAY_RECONNECT_DELAY_MILLISECONDS);
40327
40878
  function finish() {
40328
40879
  retry.cancel();
40329
40880
  signal.removeEventListener("abort", finish);
40330
- resolve5();
40881
+ resolve7();
40331
40882
  }
40332
40883
  signal.addEventListener("abort", finish, { once: true });
40333
40884
  });
@@ -40383,7 +40934,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40383
40934
  installationObserver.connect(socket);
40384
40935
  onConnected();
40385
40936
  try {
40386
- await new Promise((resolve5, reject) => {
40937
+ await new Promise((resolve7, reject) => {
40387
40938
  let finished = false;
40388
40939
  const cleanup = () => {
40389
40940
  connectionLiveness.close();
@@ -40401,7 +40952,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40401
40952
  }
40402
40953
  finished = true;
40403
40954
  cleanup();
40404
- resolve5();
40955
+ resolve7();
40405
40956
  };
40406
40957
  const rejectConnection = (failure2) => {
40407
40958
  if (finished) {
@@ -40848,7 +41399,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40848
41399
  try {
40849
41400
  operationSignal.throwIfAborted();
40850
41401
  if (previous2.length > 0) {
40851
- await new Promise((resolve6, reject2) => {
41402
+ await new Promise((resolve8, reject2) => {
40852
41403
  const cancel = () => reject2(operationSignal.reason);
40853
41404
  operationSignal.addEventListener("abort", cancel, {
40854
41405
  once: true
@@ -40856,7 +41407,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40856
41407
  void Promise.all(previous2.map((request) => request.completion)).then(
40857
41408
  () => {
40858
41409
  operationSignal.removeEventListener("abort", cancel);
40859
- resolve6();
41410
+ resolve8();
40860
41411
  },
40861
41412
  (error62) => {
40862
41413
  operationSignal.removeEventListener("abort", cancel);
@@ -40930,13 +41481,13 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40930
41481
  try {
40931
41482
  operationSignal.throwIfAborted();
40932
41483
  if (previous2.length > 0) {
40933
- await new Promise((resolve6, reject2) => {
41484
+ await new Promise((resolve8, reject2) => {
40934
41485
  const cancel = () => reject2(operationSignal.reason);
40935
41486
  operationSignal.addEventListener("abort", cancel, { once: true });
40936
41487
  void Promise.all(previous2.map((request) => request.completion)).then(
40937
41488
  () => {
40938
41489
  operationSignal.removeEventListener("abort", cancel);
40939
- resolve6();
41490
+ resolve8();
40940
41491
  },
40941
41492
  (error62) => {
40942
41493
  operationSignal.removeEventListener("abort", cancel);
@@ -41191,13 +41742,13 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41191
41742
  }
41192
41743
  async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41193
41744
  const installationAudit = new AuditInstallationEvents(audit);
41194
- const stateDirectory = readStateDirectory();
41745
+ const stateDirectory = config2.localContext.stateDirectory;
41195
41746
  const specifications = supportedLocalAgentSpecifications();
41196
41747
  const installationExecutor = new FixedInstallationExecutor({
41197
41748
  defaultWorkspace: config2.defaultWorkspace,
41198
41749
  audit: installationAudit,
41199
41750
  catalog: config2.catalog,
41200
- environment: process.env,
41751
+ environment: config2.localContext.environment,
41201
41752
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
41202
41753
  stateDirectory
41203
41754
  });
@@ -41256,10 +41807,10 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41256
41807
  return;
41257
41808
  }
41258
41809
  connectionAnnounced = true;
41259
- const reconnectCommand = `npx --yes @moxt-ai/mobius start --channel ${config2.channelId}`;
41810
+ const reconnectCommand = `npx --yes @moxt-ai/mobius start ${config2.reconnectTarget.commandArgument}`;
41260
41811
  process.stdout.write("Mobius daemon connected to the relay.\n\n");
41261
41812
  process.stdout.write(
41262
- `${styleText(["bold", "yellow"], `Reconnect this channel later:
41813
+ `${styleText(["bold", "yellow"], `Reconnect this local connection later:
41263
41814
  ${reconnectCommand}`)}
41264
41815
 
41265
41816
  `
@@ -41341,7 +41892,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41341
41892
  }
41342
41893
 
41343
41894
  // src/runtime.ts
41344
- var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
41895
+ var RUNTIME_CREDENTIAL_PATTERN2 = /^[a-zA-Z0-9_-]{32,256}$/;
41345
41896
  var MobiusRuntimeConfigurationError = class extends Error {
41346
41897
  code = "runtime_configuration_invalid";
41347
41898
  constructor(message, options = {}) {
@@ -41365,7 +41916,7 @@ function validateRuntimeRelay(relayUrl) {
41365
41916
  if (credential.length === 0) {
41366
41917
  throw new MobiusRuntimeConfigurationError("The Runtime relay credential is required");
41367
41918
  }
41368
- if (!RUNTIME_CREDENTIAL_PATTERN.test(credential)) {
41919
+ if (!RUNTIME_CREDENTIAL_PATTERN2.test(credential)) {
41369
41920
  throw new MobiusRuntimeConfigurationError("The Runtime relay credential is invalid");
41370
41921
  }
41371
41922
  }
@@ -41404,17 +41955,18 @@ var USAGE = `Mobius CLI
41404
41955
  Usage:
41405
41956
  mobius --version
41406
41957
  mobius pair --url <relay-url> --pairing <runtime-pairing-id> --code <pairing-code> [--workspace <directory>]
41407
- mobius start --channel <channel-id>
41958
+ mobius start --connection <connection-id>
41959
+ mobius start --channel <legacy-channel-id>
41408
41960
  mobius agents [--json]
41409
41961
 
41410
41962
  Commands:
41411
41963
  --version Print the installed Mobius CLI version
41412
41964
  pair Pair this machine and start its local daemon
41413
- start Start the local daemon for a saved channel
41965
+ start Start the local daemon for a saved connection
41414
41966
  agents Show detected, missing, and integration-ready Agents
41415
41967
 
41416
41968
  Pairing grants this browser access to the machine with your user account's permissions.
41417
- New conversations default to ~/.mobius/workspace; choose other directories in the browser.
41969
+ New conversations default to this Mobius installation's private workspace; choose other directories in the browser.
41418
41970
  `;
41419
41971
  async function main() {
41420
41972
  const command = process.argv[2];
@@ -41432,10 +41984,13 @@ async function main() {
41432
41984
  if (arguments_.length > 1 || arguments_.length === 1 && arguments_[0] !== "--json") {
41433
41985
  throw new Error("Usage: mobius agents [--json]");
41434
41986
  }
41435
- await mkdir4(loadDefaultWorkspace(), { recursive: true, mode: 448 });
41987
+ const installation = await openMobiusCliInstallation(shutdown.signal, process.env);
41988
+ const localContext = new DaemonLocalContext(installation.stateDirectory, process.env);
41989
+ const defaultWorkspace = loadDefaultWorkspace(localContext.environment);
41990
+ await mkdir5(defaultWorkspace, { recursive: true, mode: 448 });
41436
41991
  const inventory = await discoverLocalAgentInventory({
41437
- defaultWorkspace: loadDefaultWorkspace(),
41438
- environment: process.env,
41992
+ defaultWorkspace,
41993
+ environment: localContext.environment,
41439
41994
  signal: shutdown.signal
41440
41995
  });
41441
41996
  process.stdout.write(formatAgentDiagnostics(inventory, arguments_[0] === "--json"));
@@ -41449,6 +42004,10 @@ async function main() {
41449
42004
  config2 = paired.config;
41450
42005
  process.stdout.write("\nLocal machine paired.\n");
41451
42006
  process.stdout.write(`Channel: ${paired.channelUrl}
42007
+ `);
42008
+ process.stdout.write(`Connection ID: ${paired.connectionId}
42009
+ `);
42010
+ process.stdout.write(`Restart: mobius start --connection ${paired.connectionId}
41452
42011
  `);
41453
42012
  process.stdout.write("Open this channel in any browser while the daemon is running.\n");
41454
42013
  process.stdout.write(`Connection saved to ${paired.connectionPath}
@@ -41456,7 +42015,7 @@ async function main() {
41456
42015
  } else if (command === "start") {
41457
42016
  const paired = await resumeLocalMachine(process.argv.slice(3), shutdown.signal);
41458
42017
  config2 = paired.config;
41459
- process.stdout.write("\nSaved local machine channel loaded.\n");
42018
+ process.stdout.write("\nSaved local Runtime connection loaded.\n");
41460
42019
  process.stdout.write(`Channel: ${paired.channelUrl}
41461
42020
  `);
41462
42021
  process.stdout.write("Open this channel in any browser while the daemon is running.\n");