@moxt-ai/mobius 0.0.48 → 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.
Files changed (63) hide show
  1. package/dist/acp/session-manager.d.ts +2 -1
  2. package/dist/acp/session-manager.d.ts.map +1 -1
  3. package/dist/acp/session-manager.js +34 -11
  4. package/dist/acp/session-manager.js.map +1 -1
  5. package/dist/agent-catalog/publish-agent-catalog.d.ts.map +1 -1
  6. package/dist/agent-catalog/publish-agent-catalog.js +0 -1
  7. package/dist/agent-catalog/publish-agent-catalog.js.map +1 -1
  8. package/dist/artifacts/local-file-streamer.d.ts +3 -0
  9. package/dist/artifacts/local-file-streamer.d.ts.map +1 -0
  10. package/dist/artifacts/local-file-streamer.js +82 -0
  11. package/dist/artifacts/local-file-streamer.js.map +1 -0
  12. package/dist/authorization/local-raster.d.ts +4 -3
  13. package/dist/authorization/local-raster.d.ts.map +1 -1
  14. package/dist/authorization/local-raster.js +22 -12
  15. package/dist/authorization/local-raster.js.map +1 -1
  16. package/dist/cli.js +1227 -1798
  17. package/dist/cli.js.map +4 -4
  18. package/dist/config.d.ts +21 -1
  19. package/dist/config.d.ts.map +1 -1
  20. package/dist/config.js +32 -2
  21. package/dist/config.js.map +1 -1
  22. package/dist/index.d.ts +2 -4
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1280 -1839
  25. package/dist/index.js.map +4 -4
  26. package/dist/native-sessions/history-images.js +1 -1
  27. package/dist/native-sessions/history-images.js.map +1 -1
  28. package/dist/pairing/pair-local-machine.d.ts +5 -2
  29. package/dist/pairing/pair-local-machine.d.ts.map +1 -1
  30. package/dist/pairing/pair-local-machine.js +93 -112
  31. package/dist/pairing/pair-local-machine.js.map +1 -1
  32. package/dist/run-daemon.d.ts.map +1 -1
  33. package/dist/run-daemon.js +30 -275
  34. package/dist/run-daemon.js.map +1 -1
  35. package/dist/runtime.d.ts +2 -1
  36. package/dist/runtime.d.ts.map +1 -1
  37. package/dist/runtime.js +1028 -1483
  38. package/dist/runtime.js.map +4 -4
  39. package/dist/storage/runtime-installation-store.d.ts +53 -0
  40. package/dist/storage/runtime-installation-store.d.ts.map +1 -0
  41. package/dist/storage/runtime-installation-store.js +491 -0
  42. package/dist/storage/runtime-installation-store.js.map +1 -0
  43. package/package.json +1 -1
  44. package/dist/bots/bot-context-applicator.d.ts +0 -14
  45. package/dist/bots/bot-context-applicator.d.ts.map +0 -1
  46. package/dist/bots/bot-context-applicator.js +0 -32
  47. package/dist/bots/bot-context-applicator.js.map +0 -1
  48. package/dist/bots/bot-execution-context.d.ts +0 -19
  49. package/dist/bots/bot-execution-context.d.ts.map +0 -1
  50. package/dist/bots/bot-execution-context.js +0 -75
  51. package/dist/bots/bot-execution-context.js.map +0 -1
  52. package/dist/bots/bot-message-command.d.ts +0 -6
  53. package/dist/bots/bot-message-command.d.ts.map +0 -1
  54. package/dist/bots/bot-message-command.js +0 -140
  55. package/dist/bots/bot-message-command.js.map +0 -1
  56. package/dist/bots/bot-outbound-ipc.d.ts +0 -12
  57. package/dist/bots/bot-outbound-ipc.d.ts.map +0 -1
  58. package/dist/bots/bot-outbound-ipc.js +0 -245
  59. package/dist/bots/bot-outbound-ipc.js.map +0 -1
  60. package/dist/bots/local-bot-execution-authorizer.d.ts +0 -23
  61. package/dist/bots/local-bot-execution-authorizer.d.ts.map +0 -1
  62. package/dist/bots/local-bot-execution-authorizer.js +0 -62
  63. package/dist/bots/local-bot-execution-authorizer.js.map +0 -1
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 mkdir5, realpath as realpath9, stat as stat8 } from "node:fs/promises";
9
- import { dirname as dirname8, join as join18, 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";
@@ -78,12 +78,12 @@ var ExecutableIdentity = class {
78
78
  realPath;
79
79
  requestedPath;
80
80
  size;
81
- constructor(requestedPath, realPath_, device, inode, size, changedAtMilliseconds) {
81
+ constructor(requestedPath2, realPath_, device, inode, size, changedAtMilliseconds) {
82
82
  this.changedAtMilliseconds = changedAtMilliseconds;
83
83
  this.device = device;
84
84
  this.inode = inode;
85
85
  this.realPath = realPath_;
86
- this.requestedPath = requestedPath;
86
+ this.requestedPath = requestedPath2;
87
87
  this.size = size;
88
88
  }
89
89
  matches = (candidate) => this.requestedPath === candidate.requestedPath && this.realPath === candidate.realPath && this.device === candidate.device && this.inode === candidate.inode && this.size === candidate.size && this.changedAtMilliseconds === candidate.changedAtMilliseconds;
@@ -123,8 +123,8 @@ function executableExtensions(executableName, environment, platform) {
123
123
  const extensions = configured.split(";").map((extension2) => extension2.trim()).filter((extension2) => extension2.length > 0).map((extension2) => extension2.startsWith(".") ? extension2 : `.${extension2}`);
124
124
  return extensions.length > 0 ? extensions : [".EXE"];
125
125
  }
126
- async function resolveExecutablePath(requestedPath, platform = process.platform) {
127
- const absoluteRequestedPath = resolve(requestedPath);
126
+ async function resolveExecutablePath(requestedPath2, platform = process.platform) {
127
+ const absoluteRequestedPath = resolve(requestedPath2);
128
128
  try {
129
129
  const resolvedPath = await realpath(absoluteRequestedPath);
130
130
  const metadata = await stat(resolvedPath);
@@ -157,8 +157,8 @@ async function findExecutableOnPath(executableName, environment, platform = proc
157
157
  continue;
158
158
  }
159
159
  for (const extension2 of extensions) {
160
- const requestedPath = resolve(join(entry, `${executableName}${extension2}`));
161
- const executable = await resolveExecutablePath(requestedPath, platform);
160
+ const requestedPath2 = resolve(join(entry, `${executableName}${extension2}`));
161
+ const executable = await resolveExecutablePath(requestedPath2, platform);
162
162
  if (executable !== null) {
163
163
  return executable;
164
164
  }
@@ -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
  }
@@ -20364,6 +20364,11 @@ var AGENT_INSTALL_CANCELLED_KIND = "agent.integration.install.cancelled";
20364
20364
  var AGENT_SETTINGS_DISCOVER_KIND = "agent.settings.discover";
20365
20365
  var AGENT_SETTINGS_DISCOVERED_KIND = "agent.settings.discovered";
20366
20366
  var AGENT_SETTINGS_DISCOVERY_FAILED_KIND = "agent.settings.discovery.failed";
20367
+ var FILE_READ_KIND = "file.read";
20368
+ var FILE_BEGIN_KIND = "file.begin";
20369
+ var FILE_CHUNK_KIND = "file.chunk";
20370
+ var FILE_END_KIND = "file.end";
20371
+ var FILE_FAILED_KIND = "file.failed";
20367
20372
  var IDENTIFIER_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
20368
20373
  var DIRECTORY_IDENTIFIER_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
20369
20374
  var IDENTIFIER = external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN);
@@ -20374,6 +20379,41 @@ var workspaceEntrySchema = external_exports.strictObject({
20374
20379
  directoryId: DIRECTORY_IDENTIFIER,
20375
20380
  name: external_exports.string().min(1).max(255)
20376
20381
  }).readonly();
20382
+ var fileReadCommandSchema = external_exports.strictObject({
20383
+ kind: external_exports.literal(FILE_READ_KIND),
20384
+ maxBytes: external_exports.number().int().positive().max(128 * 1024 * 1024),
20385
+ requestId: IDENTIFIER,
20386
+ sessionId: IDENTIFIER,
20387
+ path: external_exports.string().min(1).max(4096)
20388
+ }).readonly();
20389
+ var fileBeginEventSchema = external_exports.strictObject({
20390
+ byteLength: external_exports.number().int().positive().max(128 * 1024 * 1024),
20391
+ kind: external_exports.literal(FILE_BEGIN_KIND),
20392
+ mediaType: external_exports.string().min(1).max(255),
20393
+ modifiedAt: external_exports.iso.datetime({ offset: true }),
20394
+ name: external_exports.string().min(1).max(500),
20395
+ requestId: IDENTIFIER,
20396
+ sessionId: IDENTIFIER
20397
+ }).readonly();
20398
+ var fileChunkEventSchema = external_exports.strictObject({
20399
+ data: external_exports.string().min(1).max(4e5),
20400
+ kind: external_exports.literal(FILE_CHUNK_KIND),
20401
+ requestId: IDENTIFIER,
20402
+ sequence: external_exports.number().int().nonnegative().max(1024),
20403
+ sessionId: IDENTIFIER
20404
+ }).readonly();
20405
+ var fileEndEventSchema = external_exports.strictObject({
20406
+ kind: external_exports.literal(FILE_END_KIND),
20407
+ requestId: IDENTIFIER,
20408
+ sessionId: IDENTIFIER
20409
+ }).readonly();
20410
+ var fileFailedEventSchema = external_exports.strictObject({
20411
+ code: IDENTIFIER,
20412
+ kind: external_exports.literal(FILE_FAILED_KIND),
20413
+ message: external_exports.string().min(1).max(500),
20414
+ requestId: IDENTIFIER,
20415
+ sessionId: IDENTIFIER
20416
+ }).readonly();
20377
20417
  var configValueSchema = external_exports.strictObject({
20378
20418
  description: SHORT_TEXT,
20379
20419
  groupId: external_exports.string().max(128),
@@ -20590,7 +20630,7 @@ var sessionPrepareCommandSchema = external_exports.strictObject({
20590
20630
  kind: external_exports.literal(SESSION_PREPARE_KIND),
20591
20631
  requestId: IDENTIFIER,
20592
20632
  sessionState: external_exports.literal("provisioned").optional(),
20593
- /** @deprecated Reserved for the legacy Bot Agent-configuration endpoint. */
20633
+ /** Marks an inspection-only Session preparation. */
20594
20634
  transient: external_exports.boolean().optional()
20595
20635
  }).superRefine((command, context) => {
20596
20636
  if (command.transient === true && command.sessionState === "provisioned") {
@@ -20811,11 +20851,15 @@ var decodeRecordedAgentContentValue = (value) => decodeValue(value, recordedDisp
20811
20851
  var decodePromptImagesValue = (value) => decodeValue(value, external_exports.array(promptImageSchema).max(8).readonly());
20812
20852
  var decodePromptResourcesValue = (value) => decodeValue(value, external_exports.array(promptResourceSchema).max(16).readonly());
20813
20853
  var decodeSessionConfigurationSelections = (value) => decodeValue(value, sessionConfigurationSelectionsSchema);
20814
- var decodeAgentExecutionConfiguration = (value) => decodeValue(value, agentExecutionConfigurationSchema);
20815
20854
  var encode3 = (message, schema) => JSON.stringify(decodeValue(message, schema));
20816
20855
  var decodeAgentSettingsDiscoverCommand = (encoded) => decode3(encoded, agentSettingsDiscoverCommandSchema);
20817
20856
  var encodeAgentSettingsDiscoveredEvent = (message) => encode3(message, agentSettingsDiscoveredEventSchema);
20818
20857
  var encodeAgentSettingsDiscoveryFailedEvent = (message) => encode3(message, agentSettingsDiscoveryFailedEventSchema);
20858
+ var decodeFileReadCommand = (encoded) => decode3(encoded, fileReadCommandSchema);
20859
+ var encodeFileBeginEvent = (message) => encode3(message, fileBeginEventSchema);
20860
+ var encodeFileChunkEvent = (message) => encode3(message, fileChunkEventSchema);
20861
+ var encodeFileEndEvent = (message) => encode3(message, fileEndEventSchema);
20862
+ var encodeFileFailedEvent = (message) => encode3(message, fileFailedEventSchema);
20819
20863
  var decodeWorkspaceListCommand = (encoded) => decode3(encoded, workspaceListCommandSchema);
20820
20864
  var encodeWorkspaceEntriesEvent = (message) => encode3(message, workspaceEntriesEventSchema);
20821
20865
  var decodeSessionPrepareCommand = (encoded) => decode3(encoded, sessionPrepareCommandSchema);
@@ -21295,325 +21339,6 @@ function encodeSessionFailedEvent(message) {
21295
21339
  return JSON.stringify(decodeSessionFailedEvent(JSON.stringify(message)));
21296
21340
  }
21297
21341
 
21298
- // ../protocol/src/bot.ts
21299
- var BOT_SESSION_PROMPT_KIND = "bot.session.prompt";
21300
- var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
21301
- var DIRECTORY_IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/;
21302
- var TOKEN_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
21303
- var SHA256_PATTERN = /^[a-f0-9]{64}$/;
21304
- var MAX_INSTRUCTIONS_LENGTH = 1e5;
21305
- var BotDeliveryTargetReference = class {
21306
- alias;
21307
- deliveryTargetId;
21308
- constructor(alias, deliveryTargetId) {
21309
- this.alias = alias;
21310
- this.deliveryTargetId = deliveryTargetId;
21311
- }
21312
- };
21313
- var BotReplyRoute = class {
21314
- };
21315
- var OwnerBotReplyRoute = class extends BotReplyRoute {
21316
- kind = "owner";
21317
- };
21318
- var BotConnectionReplyRoute = class extends BotReplyRoute {
21319
- connectionId;
21320
- deliveryTargetId;
21321
- kind = "connection";
21322
- constructor(connectionId, deliveryTargetId) {
21323
- super();
21324
- this.connectionId = connectionId;
21325
- this.deliveryTargetId = deliveryTargetId;
21326
- }
21327
- };
21328
- var BotSessionPromptCommand = class {
21329
- additionalDirectoryIds;
21330
- agentId;
21331
- allowedDeliveryTargets;
21332
- behaviorDigest;
21333
- behaviorInstructions;
21334
- behaviorRevisionId;
21335
- bindingId;
21336
- bindingRevision;
21337
- botId;
21338
- commandId;
21339
- conversationId;
21340
- directoryId;
21341
- disposition;
21342
- executionCapabilityId;
21343
- executionCapabilitySecret;
21344
- executionDeadlineAt;
21345
- executionId;
21346
- executionConfiguration;
21347
- images;
21348
- kind = BOT_SESSION_PROMPT_KIND;
21349
- prompt;
21350
- replyRoute;
21351
- resources;
21352
- sessionConfigurations;
21353
- sessionId;
21354
- targetCommandId;
21355
- turnId;
21356
- constructor(sessionId, commandId, agentId, bindingId, directoryId2, additionalDirectoryIds, images, resources, prompt, executionId, executionCapabilityId, executionCapabilitySecret, executionDeadlineAt, botId, conversationId, turnId, behaviorRevisionId, bindingRevision, behaviorInstructions, behaviorDigest, allowedDeliveryTargets, replyRoute, executionConfiguration, sessionConfigurations = [], disposition = SessionPromptDisposition.Reject, targetCommandId = "") {
21357
- this.sessionId = sessionId;
21358
- this.commandId = commandId;
21359
- this.agentId = agentId;
21360
- this.bindingId = bindingId;
21361
- this.directoryId = directoryId2;
21362
- this.disposition = disposition;
21363
- this.additionalDirectoryIds = Object.freeze([...additionalDirectoryIds]);
21364
- this.images = Object.freeze([...images]);
21365
- this.resources = Object.freeze([...resources]);
21366
- this.prompt = prompt;
21367
- this.executionId = executionId;
21368
- this.executionCapabilityId = executionCapabilityId;
21369
- this.executionCapabilitySecret = executionCapabilitySecret;
21370
- this.executionDeadlineAt = executionDeadlineAt;
21371
- this.botId = botId;
21372
- this.conversationId = conversationId;
21373
- this.turnId = turnId;
21374
- this.behaviorRevisionId = behaviorRevisionId;
21375
- this.bindingRevision = bindingRevision;
21376
- this.behaviorInstructions = behaviorInstructions;
21377
- this.behaviorDigest = behaviorDigest;
21378
- this.allowedDeliveryTargets = Object.freeze(
21379
- allowedDeliveryTargets.map(
21380
- (target) => new BotDeliveryTargetReference(target.alias, target.deliveryTargetId)
21381
- )
21382
- );
21383
- this.replyRoute = replyRoute;
21384
- this.executionConfiguration = decodeAgentExecutionConfiguration(executionConfiguration);
21385
- this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
21386
- this.targetCommandId = targetCommandId;
21387
- }
21388
- toJSON() {
21389
- const { disposition, sessionConfigurations, targetCommandId, ...command } = this;
21390
- return {
21391
- ...command,
21392
- ...sessionConfigurations.length === 0 ? {} : { sessionConfigurations },
21393
- ...disposition === SessionPromptDisposition.Reject ? {} : { disposition, targetCommandId }
21394
- };
21395
- }
21396
- };
21397
- function isRecord3(value) {
21398
- return typeof value === "object" && value !== null && !Array.isArray(value);
21399
- }
21400
- function parseJson3(encoded) {
21401
- let value;
21402
- try {
21403
- value = JSON.parse(encoded);
21404
- } catch (cause) {
21405
- throw new ProtocolMessageError("Message is not valid JSON", { cause });
21406
- }
21407
- if (!isRecord3(value)) {
21408
- throw new ProtocolMessageError("Message must be a JSON object");
21409
- }
21410
- return value;
21411
- }
21412
- function assertExactKeys2(value, expected) {
21413
- const keys = Object.keys(value);
21414
- if (keys.length !== expected.length || keys.some((key) => !expected.includes(key))) {
21415
- throw new ProtocolMessageError("Message fields do not match the Bot protocol");
21416
- }
21417
- }
21418
- function assertKeysWithOptional(value, expected, optional2) {
21419
- const keys = Object.keys(value);
21420
- if (keys.length < expected.length || keys.length > expected.length + optional2.length || expected.some((key) => !Object.hasOwn(value, key)) || keys.some((key) => !expected.includes(key) && !optional2.includes(key))) {
21421
- throw new ProtocolMessageError("Message fields do not match the Bot protocol");
21422
- }
21423
- }
21424
- function readText2(value, key, maximumLength, allowEmpty) {
21425
- const field = value[key];
21426
- if (typeof field !== "string" || field.length > maximumLength || !allowEmpty && field.length === 0) {
21427
- throw new ProtocolMessageError(`Invalid Bot protocol field: ${key}`);
21428
- }
21429
- return field;
21430
- }
21431
- function readIdentifier2(value, key) {
21432
- const field = readText2(value, key, 128, false);
21433
- if (!IDENTIFIER_PATTERN3.test(field)) {
21434
- throw new ProtocolMessageError(`Invalid Bot identifier field: ${key}`);
21435
- }
21436
- return field;
21437
- }
21438
- function readDirectoryIdentifier2(value, key) {
21439
- const field = readText2(value, key, 2048, false);
21440
- if (!DIRECTORY_IDENTIFIER_PATTERN3.test(field)) {
21441
- throw new ProtocolMessageError(`Invalid Bot directory field: ${key}`);
21442
- }
21443
- return field;
21444
- }
21445
- function readInteger(value, key) {
21446
- const field = value[key];
21447
- if (typeof field !== "number" || !Number.isSafeInteger(field) || field < 1) {
21448
- throw new ProtocolMessageError(`Invalid Bot integer field: ${key}`);
21449
- }
21450
- return field;
21451
- }
21452
- function readTimestamp(value, key) {
21453
- const field = readText2(value, key, 64, false);
21454
- if (Number.isNaN(Date.parse(field))) {
21455
- throw new ProtocolMessageError(`Invalid Bot timestamp field: ${key}`);
21456
- }
21457
- return field;
21458
- }
21459
- function readDigest(value, key) {
21460
- const field = readText2(value, key, 64, false);
21461
- if (!SHA256_PATTERN.test(field)) {
21462
- throw new ProtocolMessageError(`Invalid Bot digest field: ${key}`);
21463
- }
21464
- return field;
21465
- }
21466
- function readToken(value, key) {
21467
- const field = readText2(value, key, 256, false);
21468
- if (!TOKEN_PATTERN.test(field)) {
21469
- throw new ProtocolMessageError(`Invalid Bot token field: ${key}`);
21470
- }
21471
- return field;
21472
- }
21473
- function readIdentifiers(value, key, maximumCount) {
21474
- const field = value[key];
21475
- if (!Array.isArray(field) || field.length > maximumCount) {
21476
- throw new ProtocolMessageError(`Invalid Bot identifier list: ${key}`);
21477
- }
21478
- const identifiers = [];
21479
- const unique = /* @__PURE__ */ new Set();
21480
- for (const candidate of field) {
21481
- if (typeof candidate !== "string" || !IDENTIFIER_PATTERN3.test(candidate) || unique.has(candidate)) {
21482
- throw new ProtocolMessageError(`Invalid Bot identifier list: ${key}`);
21483
- }
21484
- unique.add(candidate);
21485
- identifiers.push(candidate);
21486
- }
21487
- return Object.freeze(identifiers);
21488
- }
21489
- function readTargets(value, key) {
21490
- const field = value[key];
21491
- if (!Array.isArray(field) || field.length > 64) {
21492
- throw new ProtocolMessageError(`Invalid Bot delivery targets: ${key}`);
21493
- }
21494
- const targets = [];
21495
- const identifiers = /* @__PURE__ */ new Set();
21496
- const aliases = /* @__PURE__ */ new Set();
21497
- for (const candidate of field) {
21498
- if (!isRecord3(candidate)) {
21499
- throw new ProtocolMessageError(`Invalid Bot delivery targets: ${key}`);
21500
- }
21501
- assertExactKeys2(candidate, ["alias", "deliveryTargetId"]);
21502
- const alias = readIdentifier2(candidate, "alias");
21503
- const deliveryTargetId = readIdentifier2(candidate, "deliveryTargetId");
21504
- if (aliases.has(alias) || identifiers.has(deliveryTargetId)) {
21505
- throw new ProtocolMessageError(`Duplicate Bot delivery target: ${key}`);
21506
- }
21507
- aliases.add(alias);
21508
- identifiers.add(deliveryTargetId);
21509
- targets.push(new BotDeliveryTargetReference(alias, deliveryTargetId));
21510
- }
21511
- return Object.freeze(targets);
21512
- }
21513
- function readSessionConfigurations(value) {
21514
- if (!Object.hasOwn(value, "sessionConfigurations")) {
21515
- return [];
21516
- }
21517
- return decodeSessionConfigurationSelections(value["sessionConfigurations"]);
21518
- }
21519
- function readReplyRoute(value) {
21520
- if (!isRecord3(value)) {
21521
- throw new ProtocolMessageError("Invalid Bot reply route");
21522
- }
21523
- const kind = readText2(value, "kind", 32, false);
21524
- if (kind === "owner") {
21525
- assertExactKeys2(value, ["kind"]);
21526
- return new OwnerBotReplyRoute();
21527
- }
21528
- if (kind === "connection") {
21529
- assertExactKeys2(value, ["connectionId", "deliveryTargetId", "kind"]);
21530
- return new BotConnectionReplyRoute(
21531
- readIdentifier2(value, "connectionId"),
21532
- readIdentifier2(value, "deliveryTargetId")
21533
- );
21534
- }
21535
- throw new ProtocolMessageError("Invalid Bot reply route");
21536
- }
21537
- function decodeBotSessionPromptCommand(encoded) {
21538
- const value = parseJson3(encoded);
21539
- assertKeysWithOptional(
21540
- value,
21541
- [
21542
- "additionalDirectoryIds",
21543
- "agentId",
21544
- "allowedDeliveryTargets",
21545
- "behaviorDigest",
21546
- "behaviorInstructions",
21547
- "behaviorRevisionId",
21548
- "bindingId",
21549
- "bindingRevision",
21550
- "botId",
21551
- "commandId",
21552
- "conversationId",
21553
- "directoryId",
21554
- "executionCapabilityId",
21555
- "executionCapabilitySecret",
21556
- "executionDeadlineAt",
21557
- "executionId",
21558
- "executionConfiguration",
21559
- "images",
21560
- "kind",
21561
- "prompt",
21562
- "replyRoute",
21563
- "resources",
21564
- "sessionId",
21565
- "turnId"
21566
- ],
21567
- ["disposition", "sessionConfigurations", "targetCommandId"]
21568
- );
21569
- if (value["kind"] !== BOT_SESSION_PROMPT_KIND) {
21570
- throw new ProtocolMessageError("Invalid Bot Session prompt kind");
21571
- }
21572
- const rawDisposition = value["disposition"];
21573
- let disposition;
21574
- if (rawDisposition === void 0 || rawDisposition === SessionPromptDisposition.Reject) {
21575
- disposition = SessionPromptDisposition.Reject;
21576
- } else if (rawDisposition === SessionPromptDisposition.Queue) {
21577
- disposition = SessionPromptDisposition.Queue;
21578
- } else if (rawDisposition === SessionPromptDisposition.Steer) {
21579
- disposition = SessionPromptDisposition.Steer;
21580
- } else {
21581
- throw new ProtocolMessageError("Invalid Bot Session prompt disposition");
21582
- }
21583
- const targetCommandId = value["targetCommandId"] === void 0 ? "" : readText2(value, "targetCommandId", 128, false);
21584
- if (disposition === SessionPromptDisposition.Reject && targetCommandId.length > 0 || disposition !== SessionPromptDisposition.Reject && !IDENTIFIER_PATTERN3.test(targetCommandId)) {
21585
- throw new ProtocolMessageError("Bot Session prompt disposition has an invalid target command");
21586
- }
21587
- return new BotSessionPromptCommand(
21588
- readIdentifier2(value, "sessionId"),
21589
- readIdentifier2(value, "commandId"),
21590
- readIdentifier2(value, "agentId"),
21591
- readIdentifier2(value, "bindingId"),
21592
- readDirectoryIdentifier2(value, "directoryId"),
21593
- readIdentifiers(value, "additionalDirectoryIds", 16),
21594
- decodePromptImagesValue(value["images"]),
21595
- decodePromptResourcesValue(value["resources"]),
21596
- readText2(value, "prompt", 1e4, false),
21597
- readIdentifier2(value, "executionId"),
21598
- readIdentifier2(value, "executionCapabilityId"),
21599
- readToken(value, "executionCapabilitySecret"),
21600
- readTimestamp(value, "executionDeadlineAt"),
21601
- readIdentifier2(value, "botId"),
21602
- readIdentifier2(value, "conversationId"),
21603
- readIdentifier2(value, "turnId"),
21604
- readIdentifier2(value, "behaviorRevisionId"),
21605
- readInteger(value, "bindingRevision"),
21606
- readText2(value, "behaviorInstructions", MAX_INSTRUCTIONS_LENGTH, true),
21607
- readDigest(value, "behaviorDigest"),
21608
- readTargets(value, "allowedDeliveryTargets"),
21609
- readReplyRoute(value["replyRoute"]),
21610
- decodeAgentExecutionConfiguration(value["executionConfiguration"]),
21611
- readSessionConfigurations(value),
21612
- disposition,
21613
- targetCommandId
21614
- );
21615
- }
21616
-
21617
21342
  // ../protocol/src/mobius-api.ts
21618
21343
  var MOBIUS_API_PREFIX = "/mobius/api";
21619
21344
  var API_PREFIX_PATTERN = /^\/[a-zA-Z0-9._~-]+(?:\/[a-zA-Z0-9._~-]+)*$/;
@@ -21826,13 +21551,13 @@ var SessionEventRejectionCode = {
21826
21551
  SessionNotFound: "session_not_found",
21827
21552
  SessionRejected: "session_rejected"
21828
21553
  };
21829
- var IDENTIFIER_PATTERN4 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
21554
+ var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
21830
21555
  var CURSOR_PATTERN = /^[A-Za-z0-9_-]{1,512}$/;
21831
21556
  var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
21832
21557
  var DECIMAL_SEQUENCE_PATTERN = /^(?:0|[1-9][0-9]*)$/;
21833
21558
  var eventSourceSchema = external_exports.discriminatedUnion("kind", [
21834
21559
  external_exports.strictObject({
21835
- attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21560
+ attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21836
21561
  kind: external_exports.literal("attempt"),
21837
21562
  sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
21838
21563
  }).readonly(),
@@ -21842,41 +21567,41 @@ var eventSourceSchema = external_exports.discriminatedUnion("kind", [
21842
21567
  }).readonly()
21843
21568
  ]);
21844
21569
  var eventEnvelopeSchema = external_exports.strictObject({
21845
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21570
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21846
21571
  kind: external_exports.literal(SESSION_EVENT_KIND),
21847
21572
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
21848
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21573
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21849
21574
  source: eventSourceSchema
21850
21575
  }).readonly();
21851
21576
  var committedEventSchema = external_exports.strictObject({
21852
21577
  cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
21853
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21578
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21854
21579
  kind: external_exports.literal(SESSION_EVENT_COMMITTED_KIND),
21855
21580
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
21856
21581
  recordedAt: external_exports.string().datetime({ offset: true }),
21857
21582
  sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
21858
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21583
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21859
21584
  source: eventSourceSchema
21860
21585
  }).readonly();
21861
21586
  var eventAcknowledgementSchema = external_exports.strictObject({
21862
21587
  cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
21863
21588
  duplicate: external_exports.boolean(),
21864
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21589
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21865
21590
  kind: external_exports.literal(SESSION_EVENT_ACK_KIND),
21866
21591
  sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
21867
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4)
21592
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21868
21593
  }).readonly();
21869
21594
  var eventDeferredSchema = external_exports.strictObject({
21870
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21595
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21871
21596
  kind: external_exports.literal(SESSION_EVENT_DEFERRED_KIND),
21872
21597
  retryAfterMilliseconds: external_exports.number().int().min(100).max(6e4),
21873
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4)
21598
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21874
21599
  }).readonly();
21875
21600
  var eventRejectionSchema = external_exports.strictObject({
21876
21601
  code: external_exports.enum(SessionEventRejectionCode),
21877
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
21602
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
21878
21603
  kind: external_exports.literal(SESSION_EVENT_REJECTED_KIND),
21879
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4)
21604
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
21880
21605
  }).readonly();
21881
21606
  function decode5(encoded, schema) {
21882
21607
  let value;
@@ -22391,7 +22116,7 @@ var ManagedNpmPackageError = class extends Error {
22391
22116
  this.name = "ManagedNpmPackageError";
22392
22117
  }
22393
22118
  };
22394
- function isRecord4(value) {
22119
+ function isRecord3(value) {
22395
22120
  return typeof value === "object" && value !== null && !Array.isArray(value);
22396
22121
  }
22397
22122
  function packagePath(root, packageName) {
@@ -22413,7 +22138,7 @@ async function readJsonRecord(path2, maximumBytes) {
22413
22138
  );
22414
22139
  }
22415
22140
  const value = JSON.parse(await handle.readFile({ encoding: "utf8" }));
22416
- if (!isRecord4(value)) {
22141
+ if (!isRecord3(value)) {
22417
22142
  throw new ManagedNpmPackageError(
22418
22143
  "managed_package_verification_failed",
22419
22144
  "The managed npm package metadata is invalid"
@@ -22439,7 +22164,7 @@ function readBinPath(packageMetadata, executableName) {
22439
22164
  if (typeof bin === "string") {
22440
22165
  return bin;
22441
22166
  }
22442
- if (isRecord4(bin) && typeof bin[executableName] === "string") {
22167
+ if (isRecord3(bin) && typeof bin[executableName] === "string") {
22443
22168
  return bin[executableName];
22444
22169
  }
22445
22170
  throw new ManagedNpmPackageError(
@@ -22455,7 +22180,7 @@ function verifyPackageLockEntry(lock, definition2, verifyDependencyClosure) {
22455
22180
  );
22456
22181
  }
22457
22182
  const packages = lock["packages"];
22458
- if (!isRecord4(packages)) {
22183
+ if (!isRecord3(packages)) {
22459
22184
  throw new ManagedNpmPackageError(
22460
22185
  "managed_package_verification_failed",
22461
22186
  "The managed npm package lockfile is invalid"
@@ -22469,7 +22194,7 @@ function verifyPackageLockEntry(lock, definition2, verifyDependencyClosure) {
22469
22194
  if (verifyDependencyClosure && normalizedKey.length > 0) {
22470
22195
  let resolved;
22471
22196
  try {
22472
- if (!normalizedKey.split("/").includes("node_modules") || !isRecord4(candidate) || typeof candidate["version"] !== "string" || candidate["version"].length === 0 || typeof candidate["integrity"] !== "string" || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(candidate["integrity"]) || typeof candidate["resolved"] !== "string") {
22197
+ if (!normalizedKey.split("/").includes("node_modules") || !isRecord3(candidate) || typeof candidate["version"] !== "string" || candidate["version"].length === 0 || typeof candidate["integrity"] !== "string" || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(candidate["integrity"]) || typeof candidate["resolved"] !== "string") {
22473
22198
  throw new Error("Invalid locked dependency");
22474
22199
  }
22475
22200
  resolved = new URL(candidate["resolved"]);
@@ -22492,7 +22217,7 @@ function verifyPackageLockEntry(lock, definition2, verifyDependencyClosure) {
22492
22217
  matches += 1;
22493
22218
  }
22494
22219
  }
22495
- if (matches !== 1 || !isRecord4(entry) || entry["integrity"] !== definition2.integrity || entry["resolved"] !== definition2.tarballUrl || entry["version"] !== definition2.version) {
22220
+ if (matches !== 1 || !isRecord3(entry) || entry["integrity"] !== definition2.integrity || entry["resolved"] !== definition2.tarballUrl || entry["version"] !== definition2.version) {
22496
22221
  throw new ManagedNpmPackageError(
22497
22222
  "managed_package_verification_failed",
22498
22223
  "The managed npm package lockfile does not match the pinned artifact"
@@ -23303,7 +23028,7 @@ var ManagedAgentArchiveError = class extends Error {
23303
23028
  this.name = "ManagedAgentArchiveError";
23304
23029
  }
23305
23030
  };
23306
- function isRecord5(value) {
23031
+ function isRecord4(value) {
23307
23032
  return typeof value === "object" && value !== null && !Array.isArray(value);
23308
23033
  }
23309
23034
  function isContainedPath3(root, candidate) {
@@ -23360,7 +23085,7 @@ async function readManifest(path2) {
23360
23085
  );
23361
23086
  }
23362
23087
  const parsed = JSON.parse(await handle.readFile({ encoding: "utf8" }));
23363
- if (!isRecord5(parsed)) {
23088
+ if (!isRecord4(parsed)) {
23364
23089
  throw new ManagedAgentArchiveError(
23365
23090
  "managed_archive_verification_failed",
23366
23091
  "The managed Agent archive manifest is invalid"
@@ -23673,8 +23398,8 @@ var WorkBuddyAgentSpecification = class extends DirectAcpAgentDefinition {
23673
23398
  requestedPaths.unshift(join11(homeDirectory, "Applications", ...WORKBUDDY_MACOS_EXECUTABLE_PATH));
23674
23399
  }
23675
23400
  const executables = [];
23676
- for (const requestedPath of requestedPaths) {
23677
- const executable = await resolveExecutablePath(requestedPath, "darwin");
23401
+ for (const requestedPath2 of requestedPaths) {
23402
+ const executable = await resolveExecutablePath(requestedPath2, "darwin");
23678
23403
  context.signal.throwIfAborted();
23679
23404
  if (executable !== null) {
23680
23405
  executables.push(executable);
@@ -23762,41 +23487,41 @@ var DiscoveryAcpHandler = class {
23762
23487
  };
23763
23488
  function readableAcpStream(input2) {
23764
23489
  let byteLength = 0;
23765
- let open5 = true;
23490
+ let open6 = true;
23766
23491
  return new ReadableStream({
23767
23492
  start(controller) {
23768
23493
  input2.on("data", (chunk) => {
23769
- if (!open5) {
23494
+ if (!open6) {
23770
23495
  return;
23771
23496
  }
23772
23497
  if (!(chunk instanceof Uint8Array)) {
23773
- open5 = false;
23498
+ open6 = false;
23774
23499
  controller.error(new Error("ACP adapter produced invalid output"));
23775
23500
  return;
23776
23501
  }
23777
23502
  byteLength += chunk.byteLength;
23778
23503
  if (byteLength > ACP_OUTPUT_LIMIT_BYTES) {
23779
- open5 = false;
23504
+ open6 = false;
23780
23505
  controller.error(new Error("ACP adapter output limit exceeded"));
23781
23506
  return;
23782
23507
  }
23783
23508
  controller.enqueue(new Uint8Array(chunk));
23784
23509
  });
23785
23510
  input2.once("end", () => {
23786
- if (open5) {
23787
- open5 = false;
23511
+ if (open6) {
23512
+ open6 = false;
23788
23513
  controller.close();
23789
23514
  }
23790
23515
  });
23791
23516
  input2.once("error", (error62) => {
23792
- if (open5) {
23793
- open5 = false;
23517
+ if (open6) {
23518
+ open6 = false;
23794
23519
  controller.error(error62);
23795
23520
  }
23796
23521
  });
23797
23522
  },
23798
23523
  cancel() {
23799
- open5 = false;
23524
+ open6 = false;
23800
23525
  }
23801
23526
  });
23802
23527
  }
@@ -24067,7 +23792,7 @@ async function resolveAdapterExecutable(specification, context) {
24067
23792
  const executables = await resolveAdapterExecutables(specification, context);
24068
23793
  return executables[0] ?? null;
24069
23794
  }
24070
- async function probeVersion(executable, arguments_, environment, defaultWorkspace, signal, timeoutMilliseconds, normalize4 = normalizeVersionOutput) {
23795
+ async function probeVersion(executable, arguments_, environment, defaultWorkspace, signal, timeoutMilliseconds, normalize5 = normalizeVersionOutput) {
24071
23796
  const result = await runBoundedProcess({
24072
23797
  arguments: arguments_,
24073
23798
  command: executable.path,
@@ -24076,7 +23801,7 @@ async function probeVersion(executable, arguments_, environment, defaultWorkspac
24076
23801
  signal,
24077
23802
  timeoutMilliseconds
24078
23803
  });
24079
- const version2 = normalize4(result.stdout || result.stderr);
23804
+ const version2 = normalize5(result.stdout || result.stderr);
24080
23805
  if (version2.length === 0) {
24081
23806
  throw new ProcessExecutionError("process_exit_failed", "The executable did not report a version");
24082
23807
  }
@@ -24315,12 +24040,40 @@ var AuditStore = class {
24315
24040
  };
24316
24041
 
24317
24042
  // src/config.ts
24318
- import { join as join14 } from "node:path";
24043
+ import { join as join14, resolve as resolve3 } from "node:path";
24319
24044
  function loadDefaultWorkspace(environment = process.env) {
24320
24045
  const { MOBIUS_DEFAULT_WORKSPACE: configuredWorkspace } = environment;
24321
24046
  return configuredWorkspace ?? join14(readStateDirectory(environment), "workspace");
24322
24047
  }
24323
- 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)) {
24324
24077
  return {
24325
24078
  agents,
24326
24079
  defaultWorkspace: connection.defaultWorkspace,
@@ -24329,15 +24082,17 @@ function createDaemonConfig(connection, agents = [], installableAgents = []) {
24329
24082
  catalog: new LocalAgentCatalog(agents, installableAgents),
24330
24083
  channelId: connection.channelId,
24331
24084
  installableAgents,
24085
+ localContext,
24086
+ reconnectTarget,
24332
24087
  relayUrl: connection.relayUrl
24333
24088
  };
24334
24089
  }
24335
24090
 
24336
24091
  // src/run-daemon.ts
24337
24092
  import { randomUUID as randomUUID3 } from "node:crypto";
24338
- import { basename as basename5, join as join16 } from "node:path";
24093
+ import { basename as basename6 } from "node:path";
24339
24094
  import { styleText } from "node:util";
24340
- import { fetch as fetch6, WebSocket as WebSocket2 } from "undici";
24095
+ import { fetch as fetch5, WebSocket as WebSocket2 } from "undici";
24341
24096
 
24342
24097
  // src/acp/session-manager.ts
24343
24098
  import { spawn as spawn3 } from "node:child_process";
@@ -24349,10 +24104,11 @@ import {
24349
24104
  } from "@agentclientprotocol/sdk";
24350
24105
 
24351
24106
  // src/authorization/local-raster.ts
24352
- import { readFile as readFile2, realpath as realpath6, stat as stat5 } from "node:fs/promises";
24107
+ import { open as open4, readFile as readFile2, realpath as realpath6, stat as stat5 } from "node:fs/promises";
24353
24108
  import { basename, isAbsolute as isAbsolute8, normalize as normalize2 } from "node:path";
24354
24109
  import { fileURLToPath } from "node:url";
24355
- var MAX_LOCAL_RASTER_BYTES = 3e6;
24110
+ var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
24111
+ var MAX_INLINE_RASTER_BYTES = 3e6;
24356
24112
  var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
24357
24113
  var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
24358
24114
  var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
@@ -24363,12 +24119,17 @@ var LocalRasterImage = class {
24363
24119
  bytes;
24364
24120
  mimeType;
24365
24121
  name;
24366
- constructor(name, mimeType, bytes) {
24122
+ sourceUri;
24123
+ constructor(name, mimeType, bytes, sourceUri = "") {
24367
24124
  this.bytes = bytes;
24368
24125
  this.mimeType = mimeType;
24369
24126
  this.name = name;
24127
+ this.sourceUri = sourceUri;
24370
24128
  }
24371
- base64 = () => Buffer.from(this.bytes).toString("base64");
24129
+ base64 = async () => {
24130
+ const bytes = this.bytes ?? new Uint8Array(await readFile2(this.sourceUri));
24131
+ return Buffer.from(bytes).toString("base64");
24132
+ };
24372
24133
  };
24373
24134
  function startsWith(bytes, signature, offset = 0) {
24374
24135
  if (bytes.byteLength < offset + signature.byteLength) {
@@ -24392,14 +24153,14 @@ function sniffRasterMime(bytes) {
24392
24153
  return null;
24393
24154
  }
24394
24155
  function readInlineRaster(data, name = "Image") {
24395
- if (data.length === 0 || data.length > Math.ceil(MAX_LOCAL_RASTER_BYTES / 3) * 4 || data.length % 4 !== 0) {
24156
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_RASTER_BYTES / 3) * 4 || data.length % 4 !== 0) {
24396
24157
  return null;
24397
24158
  }
24398
24159
  if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
24399
24160
  return null;
24400
24161
  }
24401
24162
  const bytes = new Uint8Array(Buffer.from(data, "base64"));
24402
- if (bytes.byteLength < 1 || bytes.byteLength > MAX_LOCAL_RASTER_BYTES) {
24163
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_RASTER_BYTES) {
24403
24164
  return null;
24404
24165
  }
24405
24166
  const mimeType = sniffRasterMime(bytes);
@@ -24467,16 +24228,19 @@ async function readLocalRaster(uri, signal) {
24467
24228
  if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
24468
24229
  return null;
24469
24230
  }
24470
- const bytes = new Uint8Array(await readFile2(target));
24471
- signal.throwIfAborted();
24472
- if (bytes.byteLength < 1 || bytes.byteLength > MAX_LOCAL_RASTER_BYTES) {
24473
- return null;
24231
+ const handle = await open4(target, "r");
24232
+ const header = new Uint8Array(12);
24233
+ try {
24234
+ await handle.read(header, 0, header.byteLength, 0);
24235
+ } finally {
24236
+ await handle.close();
24474
24237
  }
24475
- const mimeType = sniffRasterMime(bytes);
24238
+ signal.throwIfAborted();
24239
+ const mimeType = sniffRasterMime(header);
24476
24240
  if (mimeType === null) {
24477
24241
  return null;
24478
24242
  }
24479
- return new LocalRasterImage(basename(target) || "Image", mimeType, bytes);
24243
+ return new LocalRasterImage(basename(target) || "Image", mimeType, null, target);
24480
24244
  }
24481
24245
 
24482
24246
  // src/authorization/local-video.ts
@@ -24602,7 +24366,7 @@ async function resolveMessageImages(message, usedCharacters, signal) {
24602
24366
  if (local === null) {
24603
24367
  return "[Image unavailable]";
24604
24368
  }
24605
- const data = local.base64();
24369
+ const data = await local.base64();
24606
24370
  if (usedCharacters + imageCharacters + data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
24607
24371
  return "[Image unavailable]";
24608
24372
  }
@@ -24638,7 +24402,7 @@ async function replaceImageMarkers(text3, replace) {
24638
24402
 
24639
24403
  // src/acp/activity.ts
24640
24404
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
24641
- function isRecord6(value) {
24405
+ function isRecord5(value) {
24642
24406
  return typeof value === "object" && value !== null && !Array.isArray(value);
24643
24407
  }
24644
24408
  var AcpActivity = class _AcpActivity {
@@ -24872,16 +24636,16 @@ async function normalizeToolContent(content3, prepareContent) {
24872
24636
  return normalized;
24873
24637
  }
24874
24638
  function rawMcpToolContent(rawOutput) {
24875
- if (!isRecord6(rawOutput)) {
24639
+ if (!isRecord5(rawOutput)) {
24876
24640
  return [];
24877
24641
  }
24878
- const result = isRecord6(rawOutput["result"]) ? rawOutput["result"] : rawOutput;
24642
+ const result = isRecord5(rawOutput["result"]) ? rawOutput["result"] : rawOutput;
24879
24643
  const content3 = result["content"];
24880
24644
  if (!Array.isArray(content3)) {
24881
24645
  return [];
24882
24646
  }
24883
24647
  return content3.flatMap((item) => {
24884
- if (!isRecord6(item) || item["type"] !== "image" || typeof item["data"] !== "string" || typeof item["mimeType"] !== "string") {
24648
+ if (!isRecord5(item) || item["type"] !== "image" || typeof item["data"] !== "string" || typeof item["mimeType"] !== "string") {
24885
24649
  return [];
24886
24650
  }
24887
24651
  const uri = item["uri"];
@@ -24958,7 +24722,7 @@ function contentPhase(content3) {
24958
24722
  return "";
24959
24723
  }
24960
24724
  const codex = metadata["codex"];
24961
- if (!isRecord6(codex)) {
24725
+ if (!isRecord5(codex)) {
24962
24726
  return "";
24963
24727
  }
24964
24728
  const phase = codex["phase"];
@@ -27745,10 +27509,10 @@ function resolveAll(constructs2, events, context) {
27745
27509
  const called = [];
27746
27510
  let index2 = -1;
27747
27511
  while (++index2 < constructs2.length) {
27748
- const resolve6 = constructs2[index2].resolveAll;
27749
- if (resolve6 && !called.includes(resolve6)) {
27750
- events = resolve6(events, context);
27751
- called.push(resolve6);
27512
+ const resolve8 = constructs2[index2].resolveAll;
27513
+ if (resolve8 && !called.includes(resolve8)) {
27514
+ events = resolve8(events, context);
27515
+ called.push(resolve8);
27752
27516
  }
27753
27517
  }
27754
27518
  return events;
@@ -27762,7 +27526,7 @@ var attention = {
27762
27526
  };
27763
27527
  function resolveAllAttention(events, context) {
27764
27528
  let index2 = -1;
27765
- let open5;
27529
+ let open6;
27766
27530
  let group;
27767
27531
  let text3;
27768
27532
  let openingSequence;
@@ -27772,16 +27536,16 @@ function resolveAllAttention(events, context) {
27772
27536
  let offset;
27773
27537
  while (++index2 < events.length) {
27774
27538
  if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
27775
- open5 = index2;
27776
- while (open5--) {
27777
- if (events[open5][0] === "exit" && events[open5][1].type === "attentionSequence" && events[open5][1]._open && // If the markers are the same:
27778
- context.sliceSerialize(events[open5][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
27779
- if ((events[open5][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open5][1].end.offset - events[open5][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
27539
+ open6 = index2;
27540
+ while (open6--) {
27541
+ if (events[open6][0] === "exit" && events[open6][1].type === "attentionSequence" && events[open6][1]._open && // If the markers are the same:
27542
+ context.sliceSerialize(events[open6][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
27543
+ if ((events[open6][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open6][1].end.offset - events[open6][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
27780
27544
  continue;
27781
27545
  }
27782
- use = events[open5][1].end.offset - events[open5][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
27546
+ use = events[open6][1].end.offset - events[open6][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
27783
27547
  const start = {
27784
- ...events[open5][1].end
27548
+ ...events[open6][1].end
27785
27549
  };
27786
27550
  const end = {
27787
27551
  ...events[index2][1].start
@@ -27792,7 +27556,7 @@ function resolveAllAttention(events, context) {
27792
27556
  type: use > 1 ? "strongSequence" : "emphasisSequence",
27793
27557
  start,
27794
27558
  end: {
27795
- ...events[open5][1].end
27559
+ ...events[open6][1].end
27796
27560
  }
27797
27561
  };
27798
27562
  closingSequence = {
@@ -27805,7 +27569,7 @@ function resolveAllAttention(events, context) {
27805
27569
  text3 = {
27806
27570
  type: use > 1 ? "strongText" : "emphasisText",
27807
27571
  start: {
27808
- ...events[open5][1].end
27572
+ ...events[open6][1].end
27809
27573
  },
27810
27574
  end: {
27811
27575
  ...events[index2][1].start
@@ -27820,18 +27584,18 @@ function resolveAllAttention(events, context) {
27820
27584
  ...closingSequence.end
27821
27585
  }
27822
27586
  };
27823
- events[open5][1].end = {
27587
+ events[open6][1].end = {
27824
27588
  ...openingSequence.start
27825
27589
  };
27826
27590
  events[index2][1].start = {
27827
27591
  ...closingSequence.end
27828
27592
  };
27829
27593
  nextEvents = [];
27830
- if (events[open5][1].end.offset - events[open5][1].start.offset) {
27831
- nextEvents = push(nextEvents, [["enter", events[open5][1], context], ["exit", events[open5][1], context]]);
27594
+ if (events[open6][1].end.offset - events[open6][1].start.offset) {
27595
+ nextEvents = push(nextEvents, [["enter", events[open6][1], context], ["exit", events[open6][1], context]]);
27832
27596
  }
27833
27597
  nextEvents = push(nextEvents, [["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text3, context]]);
27834
- nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open5 + 1, index2), context));
27598
+ nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open6 + 1, index2), context));
27835
27599
  nextEvents = push(nextEvents, [["exit", text3, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context]]);
27836
27600
  if (events[index2][1].end.offset - events[index2][1].start.offset) {
27837
27601
  offset = 2;
@@ -27839,8 +27603,8 @@ function resolveAllAttention(events, context) {
27839
27603
  } else {
27840
27604
  offset = 0;
27841
27605
  }
27842
- splice(events, open5 - 1, index2 - open5 + 3, nextEvents);
27843
- index2 = open5 + nextEvents.length - offset - 2;
27606
+ splice(events, open6 - 1, index2 - open6 + 3, nextEvents);
27607
+ index2 = open6 + nextEvents.length - offset - 2;
27844
27608
  break;
27845
27609
  }
27846
27610
  }
@@ -27872,10 +27636,10 @@ function tokenizeAttention(effects, ok2) {
27872
27636
  }
27873
27637
  const token = effects.exit("attentionSequence");
27874
27638
  const after = classifyCharacter(code);
27875
- const open5 = !after || after === 2 && before || attentionMarkers2.includes(code);
27639
+ const open6 = !after || after === 2 && before || attentionMarkers2.includes(code);
27876
27640
  const close = !before || before === 2 && after || attentionMarkers2.includes(previous2);
27877
- token._open = Boolean(marker === 42 ? open5 : open5 && (before || !close));
27878
- token._close = Boolean(marker === 42 ? close : close && (after || !open5));
27641
+ token._open = Boolean(marker === 42 ? open6 : open6 && (before || !close));
27642
+ token._close = Boolean(marker === 42 ? close : close && (after || !open6));
27879
27643
  return ok2(code);
27880
27644
  }
27881
27645
  }
@@ -27899,9 +27663,9 @@ function tokenizeAutolink(effects, ok2, nok) {
27899
27663
  effects.consume(code);
27900
27664
  effects.exit("autolinkMarker");
27901
27665
  effects.enter("autolinkProtocol");
27902
- return open5;
27666
+ return open6;
27903
27667
  }
27904
- function open5(code) {
27668
+ function open6(code) {
27905
27669
  if (asciiAlpha(code)) {
27906
27670
  effects.consume(code);
27907
27671
  return schemeOrEmailAtext;
@@ -28101,9 +27865,9 @@ function tokenizeCharacterReference(effects, ok2, nok) {
28101
27865
  effects.enter("characterReferenceMarker");
28102
27866
  effects.consume(code);
28103
27867
  effects.exit("characterReferenceMarker");
28104
- return open5;
27868
+ return open6;
28105
27869
  }
28106
- function open5(code) {
27870
+ function open6(code) {
28107
27871
  if (code === 35) {
28108
27872
  effects.enter("characterReferenceMarkerNumeric");
28109
27873
  effects.consume(code);
@@ -29472,9 +29236,9 @@ function tokenizeHtmlFlow(effects, ok2, nok) {
29472
29236
  effects.enter("htmlFlow");
29473
29237
  effects.enter("htmlFlowData");
29474
29238
  effects.consume(code);
29475
- return open5;
29239
+ return open6;
29476
29240
  }
29477
- function open5(code) {
29241
+ function open6(code) {
29478
29242
  if (code === 33) {
29479
29243
  effects.consume(code);
29480
29244
  return declarationOpen;
@@ -29822,9 +29586,9 @@ function tokenizeHtmlText(effects, ok2, nok) {
29822
29586
  effects.enter("htmlText");
29823
29587
  effects.enter("htmlTextData");
29824
29588
  effects.consume(code);
29825
- return open5;
29589
+ return open6;
29826
29590
  }
29827
- function open5(code) {
29591
+ function open6(code) {
29828
29592
  if (code === 33) {
29829
29593
  effects.consume(code);
29830
29594
  return declarationOpen;
@@ -30150,12 +29914,12 @@ function resolveToLabelEnd(events, context) {
30150
29914
  let index2 = events.length;
30151
29915
  let offset = 0;
30152
29916
  let token;
30153
- let open5;
29917
+ let open6;
30154
29918
  let close;
30155
29919
  let media;
30156
29920
  while (index2--) {
30157
29921
  token = events[index2][1];
30158
- if (open5) {
29922
+ if (open6) {
30159
29923
  if (token.type === "link" || token.type === "labelLink" && token._inactive) {
30160
29924
  break;
30161
29925
  }
@@ -30164,7 +29928,7 @@ function resolveToLabelEnd(events, context) {
30164
29928
  }
30165
29929
  } else if (close) {
30166
29930
  if (events[index2][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced) {
30167
- open5 = index2;
29931
+ open6 = index2;
30168
29932
  if (token.type !== "labelLink") {
30169
29933
  offset = 2;
30170
29934
  break;
@@ -30175,9 +29939,9 @@ function resolveToLabelEnd(events, context) {
30175
29939
  }
30176
29940
  }
30177
29941
  const group = {
30178
- type: events[open5][1].type === "labelLink" ? "link" : "image",
29942
+ type: events[open6][1].type === "labelLink" ? "link" : "image",
30179
29943
  start: {
30180
- ...events[open5][1].start
29944
+ ...events[open6][1].start
30181
29945
  },
30182
29946
  end: {
30183
29947
  ...events[events.length - 1][1].end
@@ -30186,7 +29950,7 @@ function resolveToLabelEnd(events, context) {
30186
29950
  const label = {
30187
29951
  type: "label",
30188
29952
  start: {
30189
- ...events[open5][1].start
29953
+ ...events[open6][1].start
30190
29954
  },
30191
29955
  end: {
30192
29956
  ...events[close][1].end
@@ -30195,20 +29959,20 @@ function resolveToLabelEnd(events, context) {
30195
29959
  const text3 = {
30196
29960
  type: "labelText",
30197
29961
  start: {
30198
- ...events[open5 + offset + 2][1].end
29962
+ ...events[open6 + offset + 2][1].end
30199
29963
  },
30200
29964
  end: {
30201
29965
  ...events[close - 2][1].start
30202
29966
  }
30203
29967
  };
30204
29968
  media = [["enter", group, context], ["enter", label, context]];
30205
- media = push(media, events.slice(open5 + 1, open5 + offset + 3));
29969
+ media = push(media, events.slice(open6 + 1, open6 + offset + 3));
30206
29970
  media = push(media, [["enter", text3, context]]);
30207
- media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open5 + offset + 4, close - 3), context));
29971
+ media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open6 + offset + 4, close - 3), context));
30208
29972
  media = push(media, [["exit", text3, context], events[close - 2], events[close - 1], ["exit", label, context]]);
30209
29973
  media = push(media, events.slice(close + 1));
30210
29974
  media = push(media, [["exit", group, context]]);
30211
- splice(events, open5, events.length, media);
29975
+ splice(events, open6, events.length, media);
30212
29976
  return events;
30213
29977
  }
30214
29978
  function tokenizeLabelEnd(effects, ok2, nok) {
@@ -30353,9 +30117,9 @@ function tokenizeLabelStartImage(effects, ok2, nok) {
30353
30117
  effects.enter("labelImageMarker");
30354
30118
  effects.consume(code);
30355
30119
  effects.exit("labelImageMarker");
30356
- return open5;
30120
+ return open6;
30357
30121
  }
30358
- function open5(code) {
30122
+ function open6(code) {
30359
30123
  if (code === 91) {
30360
30124
  effects.enter("labelMarker");
30361
30125
  effects.consume(code);
@@ -31659,8 +31423,8 @@ function compiler(options) {
31659
31423
  return length;
31660
31424
  }
31661
31425
  function opener(create, and) {
31662
- return open5;
31663
- function open5(token) {
31426
+ return open6;
31427
+ function open6(token) {
31664
31428
  enter.call(this, create(token), token);
31665
31429
  if (and) and.call(this, token);
31666
31430
  }
@@ -31692,18 +31456,18 @@ function compiler(options) {
31692
31456
  }
31693
31457
  function exit2(token, onExitError) {
31694
31458
  const node3 = this.stack.pop();
31695
- const open5 = this.tokenStack.pop();
31696
- if (!open5) {
31459
+ const open6 = this.tokenStack.pop();
31460
+ if (!open6) {
31697
31461
  throw new Error("Cannot close `" + token.type + "` (" + stringifyPosition({
31698
31462
  start: token.start,
31699
31463
  end: token.end
31700
31464
  }) + "): it\u2019s not open");
31701
- } else if (open5[0].type !== token.type) {
31465
+ } else if (open6[0].type !== token.type) {
31702
31466
  if (onExitError) {
31703
- onExitError.call(this, token, open5[0]);
31467
+ onExitError.call(this, token, open6[0]);
31704
31468
  } else {
31705
- const handler = open5[1] || defaultOnError;
31706
- handler.call(this, token, open5[0]);
31469
+ const handler = open6[1] || defaultOnError;
31470
+ handler.call(this, token, open6[0]);
31707
31471
  }
31708
31472
  }
31709
31473
  node3.position.end = point2(token.end);
@@ -32387,7 +32151,7 @@ var SessionConfigProtocolError = class extends Error {
32387
32151
  this.name = "SessionConfigProtocolError";
32388
32152
  }
32389
32153
  };
32390
- function isRecord7(value) {
32154
+ function isRecord6(value) {
32391
32155
  return typeof value === "object" && value !== null && !Array.isArray(value);
32392
32156
  }
32393
32157
  function readString2(value, fallback = "") {
@@ -32414,7 +32178,7 @@ function normalizeConfigValues(value) {
32414
32178
  }
32415
32179
  const normalized = [];
32416
32180
  for (const entry of value) {
32417
- if (!isRecord7(entry)) {
32181
+ if (!isRecord6(entry)) {
32418
32182
  continue;
32419
32183
  }
32420
32184
  const groupedOptions = entry["options"];
@@ -32422,7 +32186,7 @@ function normalizeConfigValues(value) {
32422
32186
  const groupId = readString2(entry["group"]);
32423
32187
  const groupName = readString2(entry["name"]);
32424
32188
  for (const groupedOption of groupedOptions) {
32425
- if (isRecord7(groupedOption)) {
32189
+ if (isRecord6(groupedOption)) {
32426
32190
  normalized.push(normalizeConfigValue(groupedOption, groupId, groupName));
32427
32191
  }
32428
32192
  }
@@ -32436,7 +32200,7 @@ function normalizeConfigOptions(value, modes) {
32436
32200
  const normalized = [];
32437
32201
  if (Array.isArray(value)) {
32438
32202
  for (const option of value) {
32439
- if (!isRecord7(option)) {
32203
+ if (!isRecord6(option)) {
32440
32204
  continue;
32441
32205
  }
32442
32206
  const id = truncate2(readString2(option["id"]), 128);
@@ -32475,12 +32239,12 @@ function normalizeConfigOptions(value, modes) {
32475
32239
  }
32476
32240
  }
32477
32241
  }
32478
- if (isRecord7(modes)) {
32242
+ if (isRecord6(modes)) {
32479
32243
  const values = [];
32480
32244
  const availableModes = modes["availableModes"];
32481
32245
  if (Array.isArray(availableModes)) {
32482
32246
  for (const mode of availableModes) {
32483
- if (!isRecord7(mode)) {
32247
+ if (!isRecord6(mode)) {
32484
32248
  continue;
32485
32249
  }
32486
32250
  const id = truncate2(readString2(mode["id"]), 500);
@@ -32619,7 +32383,7 @@ function ensureRequiredExecutionOptions(current, permission) {
32619
32383
  return [permission, model, reasoningEffort, ...optional2].slice(0, MAXIMUM_CONFIG_OPTIONS);
32620
32384
  }
32621
32385
  function normalizeStandardLifecycle(response) {
32622
- const lifecycle = isRecord7(response) ? response : {};
32386
+ const lifecycle = isRecord6(response) ? response : {};
32623
32387
  return ensureReasoningEffortOption(normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]));
32624
32388
  }
32625
32389
  function replaceStandardConfigOptions(current, value) {
@@ -32661,7 +32425,7 @@ var StandardSessionConfigProtocol = class {
32661
32425
  "ACP agent exited while changing session configuration",
32662
32426
  change.signal
32663
32427
  );
32664
- if (!isRecord7(response) || !Array.isArray(response["configOptions"])) {
32428
+ if (!isRecord6(response) || !Array.isArray(response["configOptions"])) {
32665
32429
  throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
32666
32430
  }
32667
32431
  return replaceStandardConfigOptions(current, response["configOptions"]);
@@ -32675,18 +32439,18 @@ var standardSessionConfigProtocol = new StandardSessionConfigProtocol();
32675
32439
  var LEGACY_MODEL_CONFIG_ID = "grok_build_legacy_model";
32676
32440
  var LEGACY_REASONING_EFFORT_CONFIG_ID = "grok_build_legacy_reasoning_effort";
32677
32441
  function legacyOptions(response) {
32678
- if (!isRecord7(response)) {
32442
+ if (!isRecord6(response)) {
32679
32443
  return [];
32680
32444
  }
32681
32445
  const metadata = response["_meta"];
32682
- if (!isRecord7(metadata)) {
32446
+ if (!isRecord6(metadata)) {
32683
32447
  return [];
32684
32448
  }
32685
32449
  const sessionConfig = metadata["x.ai/sessionConfig"];
32686
- if (!isRecord7(sessionConfig) || !Array.isArray(sessionConfig["options"])) {
32450
+ if (!isRecord6(sessionConfig) || !Array.isArray(sessionConfig["options"])) {
32687
32451
  return [];
32688
32452
  }
32689
- return sessionConfig["options"].slice(0, 500).filter(isRecord7);
32453
+ return sessionConfig["options"].slice(0, 500).filter(isRecord6);
32690
32454
  }
32691
32455
  function legacyValue(option) {
32692
32456
  const value = readString2(option["id"]);
@@ -32699,7 +32463,7 @@ function legacyValue(option) {
32699
32463
  };
32700
32464
  }
32701
32465
  function modelsRecord(response) {
32702
- if (!isRecord7(response) || !isRecord7(response["models"])) {
32466
+ if (!isRecord6(response) || !isRecord6(response["models"])) {
32703
32467
  return {};
32704
32468
  }
32705
32469
  return response["models"];
@@ -32718,7 +32482,7 @@ function legacyModelOptions(response) {
32718
32482
  }
32719
32483
  if (values.length === 0 && Array.isArray(models["availableModels"])) {
32720
32484
  for (const model of models["availableModels"]) {
32721
- if (!isRecord7(model)) {
32485
+ if (!isRecord6(model)) {
32722
32486
  continue;
32723
32487
  }
32724
32488
  const value = readString2(model["modelId"]).slice(0, 500);
@@ -32798,7 +32562,7 @@ function legacyReasoningEffortOptions(response) {
32798
32562
  return [result];
32799
32563
  }
32800
32564
  function normalizeGrokLifecycle(response) {
32801
- const lifecycle = isRecord7(response) ? response : {};
32565
+ const lifecycle = isRecord6(response) ? response : {};
32802
32566
  const standard = normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]);
32803
32567
  const normalized = [...standard];
32804
32568
  if (!normalized.some((option) => option.category === "model")) {
@@ -32817,11 +32581,11 @@ function updateCurrentValue2(current, category, value) {
32817
32581
  return current.map((option) => option.category === category ? { ...option, currentValue: value } : option);
32818
32582
  }
32819
32583
  function validateGrokResponse(response, modelId) {
32820
- if (!isRecord7(response) || !isRecord7(response["_meta"])) {
32584
+ if (!isRecord6(response) || !isRecord6(response["_meta"])) {
32821
32585
  throw new SessionConfigProtocolError("Grok Build returned an invalid session configuration response");
32822
32586
  }
32823
32587
  const model = response["_meta"]["model"];
32824
- const appliedModel = isRecord7(model) ? model["Ok"] : model;
32588
+ const appliedModel = isRecord6(model) ? model["Ok"] : model;
32825
32589
  if (appliedModel !== modelId) {
32826
32590
  throw new SessionConfigProtocolError("Grok Build returned an invalid session configuration response");
32827
32591
  }
@@ -33332,7 +33096,7 @@ function createWritableAcpStream(output2) {
33332
33096
  if (outputFailure !== void 0) {
33333
33097
  return Promise.reject(outputFailure);
33334
33098
  }
33335
- return new Promise((resolve6, reject) => {
33099
+ return new Promise((resolve8, reject) => {
33336
33100
  pendingWriteFailures.add(reject);
33337
33101
  output2.write(chunk, (error62) => {
33338
33102
  pendingWriteFailures.delete(reject);
@@ -33345,7 +33109,7 @@ function createWritableAcpStream(output2) {
33345
33109
  reject(outputFailure);
33346
33110
  return;
33347
33111
  }
33348
- resolve6();
33112
+ resolve8();
33349
33113
  });
33350
33114
  });
33351
33115
  }
@@ -33354,7 +33118,7 @@ function createWritableAcpStream(output2) {
33354
33118
  function truncate3(value, maximumLength) {
33355
33119
  return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
33356
33120
  }
33357
- function isRecord8(value) {
33121
+ function isRecord7(value) {
33358
33122
  return typeof value === "object" && value !== null && !Array.isArray(value);
33359
33123
  }
33360
33124
  function readString4(value, fallback = "") {
@@ -33388,7 +33152,7 @@ function normalizeElicitationOptions(schema) {
33388
33152
  const oneOf = schema["oneOf"];
33389
33153
  if (Array.isArray(oneOf)) {
33390
33154
  for (const option of oneOf) {
33391
- if (isRecord8(option) && typeof option["const"] === "string") {
33155
+ if (isRecord7(option) && typeof option["const"] === "string") {
33392
33156
  normalized.push({
33393
33157
  description: truncate3(readString4(option["description"]), 500),
33394
33158
  label: truncate3(readString4(option["title"], option["const"]), 255),
@@ -33408,7 +33172,7 @@ function normalizeElicitationOptions(schema) {
33408
33172
  return normalized.slice(0, 200);
33409
33173
  }
33410
33174
  const items = schema["items"];
33411
- if (!isRecord8(items)) {
33175
+ if (!isRecord7(items)) {
33412
33176
  return normalized;
33413
33177
  }
33414
33178
  const anyOf = items["anyOf"];
@@ -33421,7 +33185,7 @@ function numericString(value) {
33421
33185
  return typeof value === "number" && Number.isFinite(value) ? value.toString() : "";
33422
33186
  }
33423
33187
  function normalizeElicitationFields(requestedSchema) {
33424
- if (!isRecord8(requestedSchema) || !isRecord8(requestedSchema["properties"])) {
33188
+ if (!isRecord7(requestedSchema) || !isRecord7(requestedSchema["properties"])) {
33425
33189
  return [];
33426
33190
  }
33427
33191
  const properties2 = requestedSchema["properties"];
@@ -33431,7 +33195,7 @@ function normalizeElicitationFields(requestedSchema) {
33431
33195
  );
33432
33196
  const normalized = [];
33433
33197
  for (const [name, property] of Object.entries(properties2)) {
33434
- if (!isRecord8(property)) {
33198
+ if (!isRecord7(property)) {
33435
33199
  continue;
33436
33200
  }
33437
33201
  const type = elicitationFieldType(property["type"]);
@@ -33522,7 +33286,7 @@ function validateElicitationContent(encoded, requestedSchema) {
33522
33286
  "invalid_elicitation_response"
33523
33287
  );
33524
33288
  }
33525
- if (!isRecord8(decoded) || !isRecord8(requestedSchema) || !isRecord8(requestedSchema["properties"])) {
33289
+ if (!isRecord7(decoded) || !isRecord7(requestedSchema) || !isRecord7(requestedSchema["properties"])) {
33526
33290
  throw new AcpExecutionError(
33527
33291
  "Elicitation response does not match the requested form",
33528
33292
  {},
@@ -33542,7 +33306,7 @@ function validateElicitationContent(encoded, requestedSchema) {
33542
33306
  const validated = {};
33543
33307
  for (const [name, value] of Object.entries(decoded)) {
33544
33308
  const property = properties2[name];
33545
- if (!isRecord8(property)) {
33309
+ if (!isRecord7(property)) {
33546
33310
  throw new AcpExecutionError(
33547
33311
  `Elicitation field ${name} was not requested`,
33548
33312
  {},
@@ -33695,6 +33459,7 @@ var AcpProcessSession = class _AcpProcessSession {
33695
33459
  #permissionProfile;
33696
33460
  #sessionConfigProtocol;
33697
33461
  #store;
33462
+ #emittedToolImages = /* @__PURE__ */ new Set();
33698
33463
  #verifiedAgentVersion;
33699
33464
  #preSessionUpdateBytes = 0;
33700
33465
  #agentName = "";
@@ -33757,9 +33522,9 @@ var AcpProcessSession = class _AcpProcessSession {
33757
33522
  stderr.on("data", (chunk) => {
33758
33523
  process.stderr.write(`[${agent.id}-acp] ${chunk}`);
33759
33524
  });
33760
- this.#processExit = new Promise((resolve6) => {
33761
- this.#child.once("error", resolve6);
33762
- this.#child.once("exit", resolve6);
33525
+ this.#processExit = new Promise((resolve8) => {
33526
+ this.#child.once("error", resolve8);
33527
+ this.#child.once("exit", resolve8);
33763
33528
  });
33764
33529
  const stream = ndJsonStream2(createWritableAcpStream(stdin), readableWebStream(stdout));
33765
33530
  this.#connection = createAcpClient(this).connect(stream);
@@ -33915,19 +33680,19 @@ var AcpProcessSession = class _AcpProcessSession {
33915
33680
  }
33916
33681
  };
33917
33682
  prepareAgentContent = async (content3) => {
33918
- if (content3.type === "image" && content3.data.length > 0) {
33919
- const raster = readInlineRaster(content3.data, content3.name);
33920
- if (raster !== null) {
33921
- return await this.importRaster(raster, AbortSignal.timeout(2e4));
33922
- }
33923
- }
33924
- if (content3.type === "image" && content3.data.length === 0 && content3.uri.length > 0) {
33683
+ if (content3.type === "image" && content3.uri.length > 0) {
33925
33684
  const signal = AbortSignal.timeout(2e4);
33926
33685
  const raster = await readLocalRaster(content3.uri, signal);
33927
33686
  if (raster !== null) {
33928
33687
  return await this.importRaster(raster, signal);
33929
33688
  }
33930
33689
  }
33690
+ if (content3.type === "image" && content3.data.length > 0) {
33691
+ const raster = readInlineRaster(content3.data, content3.name);
33692
+ if (raster !== null) {
33693
+ return await this.importRaster(raster, AbortSignal.timeout(2e4));
33694
+ }
33695
+ }
33931
33696
  if (content3.type === "video" && content3.data.length > 0) {
33932
33697
  const video = readInlineVideo(content3.data, content3.mimeType, content3.name);
33933
33698
  if (video === null) {
@@ -33948,6 +33713,22 @@ var AcpProcessSession = class _AcpProcessSession {
33948
33713
  sessionId: this.#mobiusSessionId
33949
33714
  });
33950
33715
  };
33716
+ emitToolImages = async (update) => {
33717
+ if (update.status !== "completed") {
33718
+ return;
33719
+ }
33720
+ for (const [index2, item] of (update.content ?? []).entries()) {
33721
+ if (item.type !== "content" || item.content.type !== "image") {
33722
+ continue;
33723
+ }
33724
+ const key = `${update.toolCallId}:${index2.toString()}`;
33725
+ if (this.#emittedToolImages.has(key)) {
33726
+ continue;
33727
+ }
33728
+ this.#emittedToolImages.add(key);
33729
+ await this.emitAgentContent(normalizeContentBlock(item.content), `tool-${key}`);
33730
+ }
33731
+ };
33951
33732
  emitRaster = async (raster, messageId, signal) => {
33952
33733
  const content3 = await this.importRaster(raster, signal);
33953
33734
  await this.#getObserver().onContent({
@@ -33959,14 +33740,14 @@ var AcpProcessSession = class _AcpProcessSession {
33959
33740
  sessionId: this.#mobiusSessionId
33960
33741
  });
33961
33742
  };
33962
- importRaster = async (raster, signal) => {
33963
- const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, raster, signal);
33964
- return imageDisplayContent(
33965
- raster.mimeType,
33966
- raster.name,
33967
- artifactId.length > 0 ? "" : raster.base64(),
33968
- artifactId
33969
- );
33743
+ importRaster = async (raster, _signal) => {
33744
+ if (raster.sourceUri.length > 0) {
33745
+ return {
33746
+ ...imageDisplayContent(raster.mimeType, raster.name, "", ""),
33747
+ uri: raster.sourceUri
33748
+ };
33749
+ }
33750
+ return imageDisplayContent(raster.mimeType, raster.name, await raster.base64(), "");
33970
33751
  };
33971
33752
  importVideo = async (video, signal) => {
33972
33753
  const artifactId = await this.#getObserver().importLocalArtifact(this.#mobiusSessionId, video, signal);
@@ -34450,7 +34231,7 @@ var AcpProcessSession = class _AcpProcessSession {
34450
34231
  "ACP agent exited during steering",
34451
34232
  options.signal
34452
34233
  );
34453
- if (!isRecord8(response)) {
34234
+ if (!isRecord7(response)) {
34454
34235
  throw new AcpExecutionError(
34455
34236
  "ACP agent returned an invalid steering response",
34456
34237
  {},
@@ -34746,6 +34527,7 @@ var AcpProcessSession = class _AcpProcessSession {
34746
34527
  }
34747
34528
  if (update.sessionUpdate === "tool_call_update") {
34748
34529
  await this.#turn.activities.recordToolCallUpdate(update);
34530
+ await this.emitToolImages(update);
34749
34531
  return;
34750
34532
  }
34751
34533
  if (update.sessionUpdate === "plan") {
@@ -35424,7 +35206,7 @@ var AcpSessionManager = class {
35424
35206
  async (runtime) => await runtime.close()
35425
35207
  );
35426
35208
  /**
35427
- * @deprecated Retained for the Bot-scoped legacy Agent-configuration API.
35209
+ * Retained for Agents that expose a separate persisted configuration channel.
35428
35210
  * Use inspectAgentSettings for Agent-scoped settings discovery.
35429
35211
  */
35430
35212
  inspectSession = async (options, metrics = unmeasuredOperationMetrics) => {
@@ -36018,7 +35800,6 @@ async function publishAgentCatalog(config2, signal) {
36018
35800
  agentPath: agent.agentIdentity.requestedPath,
36019
35801
  agentVersion: agent.agentVersion,
36020
35802
  agentSettingsDiscovery: true,
36021
- botSessionConfiguration: true,
36022
35803
  capabilities: agent.capabilities,
36023
35804
  id: agent.id,
36024
35805
  label: agent.label,
@@ -36310,7 +36091,7 @@ var AgentInstallationManager = class {
36310
36091
 
36311
36092
  // src/agent-installation/fixed-installation-executor.ts
36312
36093
  import { realpathSync as realpathSync2, statSync as statSync2 } from "node:fs";
36313
- import { resolve as resolve3 } from "node:path";
36094
+ import { resolve as resolve4 } from "node:path";
36314
36095
  function findSpecification(specifications, agentId) {
36315
36096
  for (const specification of specifications) {
36316
36097
  if (specification.id === agentId) {
@@ -36321,7 +36102,7 @@ function findSpecification(specifications, agentId) {
36321
36102
  }
36322
36103
  function resolveDefaultWorkspace(path2) {
36323
36104
  try {
36324
- const directory = realpathSync2(resolve3(path2));
36105
+ const directory = realpathSync2(resolve4(path2));
36325
36106
  if (!statSync2(directory).isDirectory()) {
36326
36107
  throw new Error("Default workspace is not a directory");
36327
36108
  }
@@ -36336,7 +36117,7 @@ function resolveDefaultWorkspace(path2) {
36336
36117
  }
36337
36118
  function resolveIntegrationStateDirectory(path2) {
36338
36119
  try {
36339
- const directory = realpathSync2(resolve3(path2));
36120
+ const directory = realpathSync2(resolve4(path2));
36340
36121
  const metadata = statSync2(directory);
36341
36122
  if (!metadata.isDirectory() || typeof process.getuid === "function" && metadata.uid !== process.getuid()) {
36342
36123
  throw new Error("Installation directory is not user-owned");
@@ -36505,6 +36286,91 @@ var FixedInstallationExecutor = class {
36505
36286
  };
36506
36287
  };
36507
36288
 
36289
+ // src/artifacts/local-file-streamer.ts
36290
+ import { createReadStream as createReadStream2 } from "node:fs";
36291
+ import { realpath as realpath7, stat as stat6 } from "node:fs/promises";
36292
+ import { basename as basename3, isAbsolute as isAbsolute9, normalize as normalize3 } from "node:path";
36293
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
36294
+ var CHUNK_BYTES = 192 * 1024;
36295
+ function requestedPath(value) {
36296
+ if (value.includes("\0")) {
36297
+ return null;
36298
+ }
36299
+ if (value.startsWith("file:")) {
36300
+ try {
36301
+ const url2 = new URL(value);
36302
+ return url2.protocol === "file:" && url2.host.length === 0 ? fileURLToPath2(url2) : null;
36303
+ } catch {
36304
+ return null;
36305
+ }
36306
+ }
36307
+ return value;
36308
+ }
36309
+ async function resolveFile(value, signal) {
36310
+ const requested = requestedPath(value);
36311
+ if (requested === null || !isAbsolute9(requested) || normalize3(requested) !== requested) {
36312
+ return null;
36313
+ }
36314
+ try {
36315
+ const target = await realpath7(requested);
36316
+ signal.throwIfAborted();
36317
+ return isAbsolute9(target) && normalize3(target) === target ? target : null;
36318
+ } catch {
36319
+ signal.throwIfAborted();
36320
+ return null;
36321
+ }
36322
+ }
36323
+ async function streamLocalFile(command, send2, signal) {
36324
+ const target = await resolveFile(command.path, signal);
36325
+ if (target === null) {
36326
+ throw new Error("The local file is unavailable");
36327
+ }
36328
+ const before = await stat6(target);
36329
+ signal.throwIfAborted();
36330
+ if (!before.isFile() || before.size < 1 || before.size > command.maxBytes) {
36331
+ throw new Error("The local file is too large to read");
36332
+ }
36333
+ const raster = await readLocalRaster(target, signal);
36334
+ send2(
36335
+ encodeFileBeginEvent({
36336
+ byteLength: before.size,
36337
+ kind: FILE_BEGIN_KIND,
36338
+ mediaType: raster?.mimeType ?? "application/octet-stream",
36339
+ modifiedAt: before.mtime.toISOString(),
36340
+ name: basename3(target) || "file",
36341
+ requestId: command.requestId,
36342
+ sessionId: command.sessionId
36343
+ })
36344
+ );
36345
+ let sequence = 0;
36346
+ const stream = createReadStream2(target, { highWaterMark: CHUNK_BYTES, signal });
36347
+ for await (const value of stream) {
36348
+ const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
36349
+ send2(
36350
+ encodeFileChunkEvent({
36351
+ data: Buffer.from(bytes).toString("base64"),
36352
+ kind: FILE_CHUNK_KIND,
36353
+ requestId: command.requestId,
36354
+ sequence,
36355
+ sessionId: command.sessionId
36356
+ })
36357
+ );
36358
+ sequence += 1;
36359
+ }
36360
+ const after = await stat6(target);
36361
+ signal.throwIfAborted();
36362
+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) {
36363
+ throw new Error("The local file changed during transfer");
36364
+ }
36365
+ send2(
36366
+ encodeFileEndEvent({
36367
+ kind: FILE_END_KIND,
36368
+ requestId: command.requestId,
36369
+ sessionId: command.sessionId
36370
+ })
36371
+ );
36372
+ }
36373
+
36508
36374
  // src/artifacts/runtime-artifact-uploader.ts
36509
36375
  import { createHash as createHash2 } from "node:crypto";
36510
36376
 
@@ -36531,15 +36397,15 @@ var MobiusValidationError = class extends MobiusError {
36531
36397
  };
36532
36398
 
36533
36399
  // ../mobius-sdk/src/resources.ts
36534
- var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
36400
+ var IDENTIFIER_PATTERN4 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
36535
36401
  function invalidResponse(message) {
36536
36402
  return new MobiusProtocolError(message);
36537
36403
  }
36538
- function isRecord9(value) {
36404
+ function isRecord8(value) {
36539
36405
  return typeof value === "object" && value !== null && !Array.isArray(value);
36540
36406
  }
36541
36407
  function record3(value, name) {
36542
- if (!isRecord9(value)) {
36408
+ if (!isRecord8(value)) {
36543
36409
  throw invalidResponse(`The service returned an invalid ${name}`);
36544
36410
  }
36545
36411
  return value;
@@ -36553,7 +36419,7 @@ function stringField(value, field, maximumLength = 85e5) {
36553
36419
  }
36554
36420
  function identifierField(value, field) {
36555
36421
  const candidate = stringField(value, field, 128);
36556
- if (!IDENTIFIER_PATTERN5.test(candidate)) {
36422
+ if (!IDENTIFIER_PATTERN4.test(candidate)) {
36557
36423
  throw invalidResponse(`The service returned an invalid ${field}`);
36558
36424
  }
36559
36425
  return candidate;
@@ -36900,9 +36766,9 @@ var LocalAuthorizationError = class extends Error {
36900
36766
  };
36901
36767
 
36902
36768
  // src/authorization/workspace-directory.ts
36903
- import { readdir as readdir2, realpath as realpath7, stat as stat6 } from "node:fs/promises";
36769
+ import { readdir as readdir2, realpath as realpath8, stat as stat7 } from "node:fs/promises";
36904
36770
  import { homedir as homedir2 } from "node:os";
36905
- import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute9, join as join15, normalize as normalize3, relative as relative4 } from "node:path";
36771
+ import { basename as basename4, dirname as dirname5, isAbsolute as isAbsolute10, join as join15, normalize as normalize4, relative as relative4 } from "node:path";
36906
36772
  var WorkspaceDirectoryListing = class {
36907
36773
  directoryId;
36908
36774
  directoryLabel;
@@ -36928,7 +36794,7 @@ function decodePath(value, prefix) {
36928
36794
  throw new LocalAuthorizationError("The directory identifier is invalid");
36929
36795
  }
36930
36796
  const decoded = Buffer.from(encoded, "base64url").toString("utf8");
36931
- if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize3(decoded) !== decoded) {
36797
+ if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize4(decoded) !== decoded) {
36932
36798
  throw new LocalAuthorizationError("The directory identifier is invalid");
36933
36799
  }
36934
36800
  return decoded;
@@ -36954,7 +36820,7 @@ var WorkspaceDirectoryService = class {
36954
36820
  }
36955
36821
  if (id.startsWith("path-")) {
36956
36822
  const path2 = decodePath(id, "path-");
36957
- if (isAbsolute9(path2)) {
36823
+ if (isAbsolute10(path2)) {
36958
36824
  return path2;
36959
36825
  }
36960
36826
  }
@@ -36962,15 +36828,15 @@ var WorkspaceDirectoryService = class {
36962
36828
  };
36963
36829
  resolvePath = async (requested, signal) => {
36964
36830
  signal.throwIfAborted();
36965
- if (!isAbsolute9(requested) || requested.includes("\0") || normalize3(requested) !== requested) {
36831
+ if (!isAbsolute10(requested) || requested.includes("\0") || normalize4(requested) !== requested) {
36966
36832
  throw new LocalAuthorizationError("The local directory path is invalid");
36967
36833
  }
36968
36834
  try {
36969
- const target = await realpath7(requested);
36835
+ const target = await realpath8(requested);
36970
36836
  signal.throwIfAborted();
36971
- const metadata = await stat6(target);
36837
+ const metadata = await stat7(target);
36972
36838
  signal.throwIfAborted();
36973
- if (!isAbsolute9(target) || normalize3(target) !== target || !metadata.isDirectory()) {
36839
+ if (!isAbsolute10(target) || normalize4(target) !== target || !metadata.isDirectory()) {
36974
36840
  throw new LocalAuthorizationError("The selected location is not a directory");
36975
36841
  }
36976
36842
  return target;
@@ -36986,15 +36852,15 @@ var WorkspaceDirectoryService = class {
36986
36852
  };
36987
36853
  label = (path2) => {
36988
36854
  const suffix = relative4(homedir2(), path2);
36989
- return suffix === "" ? "~" : !isAbsolute9(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path2;
36855
+ return suffix === "" ? "~" : !isAbsolute10(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path2;
36990
36856
  };
36991
- identify = async (bindingId, requestedPath, signal) => {
36857
+ identify = async (bindingId, requestedPath2, signal) => {
36992
36858
  this.authorizeMachine(bindingId);
36993
- const path2 = await this.resolvePath(requestedPath, signal);
36859
+ const path2 = await this.resolvePath(requestedPath2, signal);
36994
36860
  return {
36995
36861
  path: path2,
36996
36862
  directoryId: encodePath(path2),
36997
- name: basename3(path2) || path2,
36863
+ name: basename4(path2) || path2,
36998
36864
  label: this.label(path2)
36999
36865
  };
37000
36866
  };
@@ -37050,436 +36916,9 @@ var WorkspaceDirectoryService = class {
37050
36916
  };
37051
36917
  };
37052
36918
 
37053
- // src/bots/local-bot-execution-authorizer.ts
37054
- var LocalBotAuthorizationError = class extends Error {
37055
- code;
37056
- constructor(code, message, options = {}) {
37057
- super(message, options);
37058
- this.code = code;
37059
- this.name = "LocalBotAuthorizationError";
37060
- }
37061
- };
37062
- var AuthorizedLocalBotExecution = class {
37063
- agent;
37064
- behaviorDigest;
37065
- behaviorRevisionId;
37066
- bindingId;
37067
- bindingRevision;
37068
- botId;
37069
- executionConfiguration;
37070
- workspacePath;
37071
- workspaceRef;
37072
- constructor(command, agent, workspacePath) {
37073
- this.agent = agent;
37074
- this.behaviorDigest = command.behaviorDigest;
37075
- this.behaviorRevisionId = command.behaviorRevisionId;
37076
- this.bindingId = command.bindingId;
37077
- this.bindingRevision = command.bindingRevision;
37078
- this.botId = command.botId;
37079
- this.executionConfiguration = command.executionConfiguration;
37080
- this.workspacePath = workspacePath;
37081
- this.workspaceRef = command.directoryId;
37082
- }
37083
- };
37084
- var LocalBotExecutionAuthorizer = class {
37085
- authorize = async (command, catalog, directories, bindingAuthorityId, signal) => {
37086
- signal.throwIfAborted();
37087
- let agent;
37088
- try {
37089
- agent = catalog.find(command.agentId).withPermissionMode(command.executionConfiguration.permissionMode);
37090
- } catch (cause) {
37091
- if (cause instanceof AgentPermissionConfigurationError) {
37092
- throw new LocalBotAuthorizationError("binding_incompatible", cause.message, { cause });
37093
- }
37094
- throw cause;
37095
- }
37096
- const [adapterUnchanged, agentUnchanged] = await Promise.all([
37097
- revalidateExecutable(agent.adapterIdentity),
37098
- revalidateExecutable(agent.agentIdentity)
37099
- ]);
37100
- signal.throwIfAborted();
37101
- if (!adapterUnchanged || !agentUnchanged) {
37102
- throw new LocalBotAuthorizationError(
37103
- "binding_incompatible",
37104
- "The local Agent executable changed while the Runtime is active; restart the Runtime"
37105
- );
37106
- }
37107
- if (command.behaviorInstructions.length > 0 && !agent.capabilities.embeddedContextPrompt) {
37108
- throw new LocalBotAuthorizationError(
37109
- "binding_incompatible",
37110
- "The local Agent cannot apply the Bot behavior"
37111
- );
37112
- }
37113
- const workspacePath = await directories.resolve(bindingAuthorityId, command.directoryId, signal);
37114
- signal.throwIfAborted();
37115
- return new AuthorizedLocalBotExecution(command, agent, workspacePath);
37116
- };
37117
- };
37118
-
37119
- // src/bots/bot-context-applicator.ts
37120
- var AppliedBotContext = class {
37121
- resources;
37122
- constructor(resources) {
37123
- this.resources = Object.freeze([...resources]);
37124
- }
37125
- };
37126
- var EmbeddedBotContextApplicator = class {
37127
- apply = async (command, execution, resources, signal) => {
37128
- signal.throwIfAborted();
37129
- if (execution.botId !== command.botId || execution.behaviorRevisionId !== command.behaviorRevisionId || execution.behaviorDigest !== command.behaviorDigest) {
37130
- throw new LocalBotAuthorizationError(
37131
- "binding_incompatible",
37132
- "The Bot behavior does not match the execution target"
37133
- );
37134
- }
37135
- if (command.behaviorInstructions.length === 0) {
37136
- return new AppliedBotContext(resources);
37137
- }
37138
- if (!execution.agent.capabilities.embeddedContextPrompt) {
37139
- throw new LocalBotAuthorizationError(
37140
- "binding_incompatible",
37141
- "The local Agent cannot enforce the Bot behavior context"
37142
- );
37143
- }
37144
- const trustedContext = {
37145
- mimeType: "text/markdown",
37146
- name: "Mobius Bot behavior",
37147
- text: command.behaviorInstructions,
37148
- type: "embedded",
37149
- uri: `mobius://bots/${encodeURIComponent(command.botId)}/behavior-revisions/${encodeURIComponent(command.behaviorRevisionId)}?sha256=${command.behaviorDigest}`
37150
- };
37151
- return new AppliedBotContext([trustedContext, ...resources]);
37152
- };
37153
- };
37154
-
37155
- // src/bots/bot-execution-context.ts
37156
- import { randomBytes } from "node:crypto";
37157
- var ActiveBotExecutionContext = class {
37158
- command;
37159
- contextHandle;
37160
- constructor(contextHandle, command) {
37161
- this.contextHandle = contextHandle;
37162
- this.command = command;
37163
- }
37164
- resolveTarget = (target) => {
37165
- if (target === "current") {
37166
- if (!(this.command.replyRoute instanceof BotConnectionReplyRoute)) {
37167
- throw new LocalBotAuthorizationError(
37168
- "delivery_target_not_allowed",
37169
- "This Bot conversation has no external reply target"
37170
- );
37171
- }
37172
- return this.command.replyRoute.deliveryTargetId;
37173
- }
37174
- const resolved = this.command.allowedDeliveryTargets.find((candidate) => candidate.alias === target);
37175
- if (resolved === void 0) {
37176
- throw new LocalBotAuthorizationError(
37177
- "delivery_target_not_allowed",
37178
- "The named Bot delivery target is not approved"
37179
- );
37180
- }
37181
- return resolved.deliveryTargetId;
37182
- };
37183
- };
37184
- var BotExecutionContextLease = class {
37185
- context;
37186
- #release;
37187
- #released = false;
37188
- constructor(context, release) {
37189
- this.context = context;
37190
- this.#release = release;
37191
- }
37192
- release = () => {
37193
- if (this.#released) {
37194
- return;
37195
- }
37196
- this.#released = true;
37197
- this.#release();
37198
- };
37199
- };
37200
- var BotExecutionContextRegistry = class {
37201
- #activeByHandle = /* @__PURE__ */ new Map();
37202
- #handlesBySession = /* @__PURE__ */ new Map();
37203
- #inactiveHandles = /* @__PURE__ */ new Set();
37204
- activate = (command) => {
37205
- let handle = this.#handlesBySession.get(command.sessionId);
37206
- if (handle === void 0) {
37207
- handle = `ctx_${Buffer.from(randomBytes(32)).toString("base64url")}`;
37208
- this.#handlesBySession.set(command.sessionId, handle);
37209
- }
37210
- if (this.#activeByHandle.has(handle)) {
37211
- throw new LocalBotAuthorizationError("session_busy", "The Bot execution context is already active");
37212
- }
37213
- const context = new ActiveBotExecutionContext(handle, command);
37214
- this.#inactiveHandles.delete(handle);
37215
- this.#activeByHandle.set(handle, context);
37216
- return new BotExecutionContextLease(context, () => {
37217
- if (this.#activeByHandle.get(handle) === context) {
37218
- this.#activeByHandle.delete(handle);
37219
- this.#inactiveHandles.add(handle);
37220
- }
37221
- });
37222
- };
37223
- read = (handle) => {
37224
- const context = this.#activeByHandle.get(handle);
37225
- if (context === void 0) {
37226
- if (this.#inactiveHandles.has(handle)) {
37227
- throw new LocalBotAuthorizationError(
37228
- "execution_capability_expired",
37229
- "The Bot execution capability has expired"
37230
- );
37231
- }
37232
- throw new LocalBotAuthorizationError(
37233
- "execution_context_required",
37234
- "An active Bot execution context is required"
37235
- );
37236
- }
37237
- return context;
37238
- };
37239
- };
37240
-
37241
- // src/bots/bot-outbound-ipc.ts
37242
- import { chmod as chmod2, mkdir as mkdir3, unlink } from "node:fs/promises";
37243
- import { createServer } from "node:net";
37244
- import { dirname as dirname6, isAbsolute as isAbsolute10 } from "node:path";
37245
- import { fetch as fetch4 } from "undici";
37246
- var BOT_IPC_REQUEST_LIMIT = 32 * 1024;
37247
- var BOT_IPC_TIMEOUT_MILLISECONDS = 2e4;
37248
- var BOT_RELAY_TIMEOUT_MILLISECONDS = 2e4;
37249
- var IDENTIFIER_PATTERN6 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
37250
- var WINDOWS_NAMED_PIPE_PREFIX = "\\\\.\\pipe\\";
37251
- var BotOutboundIpcRequest = class {
37252
- contextHandle;
37253
- idempotencyKey;
37254
- target;
37255
- text;
37256
- constructor(contextHandle, idempotencyKey, target, text3) {
37257
- this.contextHandle = contextHandle;
37258
- this.idempotencyKey = idempotencyKey;
37259
- this.target = target;
37260
- this.text = text3;
37261
- }
37262
- };
37263
- function isRecord10(value) {
37264
- return typeof value === "object" && value !== null && !Array.isArray(value);
37265
- }
37266
- function decodeRequest(encoded) {
37267
- let value;
37268
- try {
37269
- value = JSON.parse(encoded);
37270
- } catch (cause) {
37271
- throw new LocalBotAuthorizationError("invalid_request", "The local Bot request is invalid", { cause });
37272
- }
37273
- if (!isRecord10(value)) {
37274
- throw new LocalBotAuthorizationError("invalid_request", "The local Bot request is invalid");
37275
- }
37276
- const keys = Object.keys(value);
37277
- if (keys.length !== 4 || !keys.every((key) => ["contextHandle", "idempotencyKey", "target", "text"].includes(key))) {
37278
- throw new LocalBotAuthorizationError("invalid_request", "The local Bot request fields are invalid");
37279
- }
37280
- const contextHandle = value["contextHandle"];
37281
- const idempotencyKey = value["idempotencyKey"];
37282
- const target = value["target"];
37283
- const text3 = value["text"];
37284
- if (typeof contextHandle !== "string" || !/^ctx_[a-zA-Z0-9_-]{43}$/.test(contextHandle) || typeof idempotencyKey !== "string" || !IDENTIFIER_PATTERN6.test(idempotencyKey) || typeof target !== "string" || !IDENTIFIER_PATTERN6.test(target) || typeof text3 !== "string" || text3.trim().length === 0 || text3.length > 1e4) {
37285
- throw new LocalBotAuthorizationError("invalid_request", "The local Bot request is invalid");
37286
- }
37287
- return new BotOutboundIpcRequest(contextHandle, idempotencyKey, target, text3);
37288
- }
37289
- function relayEndpoint(relayUrl, context, target) {
37290
- const endpoint = new URL(relayUrl);
37291
- if (endpoint.protocol !== "ws:" && endpoint.protocol !== "wss:") {
37292
- throw new LocalBotAuthorizationError("bot_service_unavailable", "The Mobius Relay URL is invalid");
37293
- }
37294
- endpoint.protocol = endpoint.protocol === "wss:" ? "https:" : "http:";
37295
- endpoint.search = "";
37296
- const execution = encodeURIComponent(context.command.executionId);
37297
- if (target === "current") {
37298
- context.resolveTarget(target);
37299
- endpoint.pathname = `${MOBIUS_API_PREFIX}/v1/bot-executions/${execution}/reply-messages`;
37300
- return endpoint;
37301
- }
37302
- const deliveryTargetId = context.resolveTarget(target);
37303
- endpoint.pathname = `${MOBIUS_API_PREFIX}/v1/bot-executions/${execution}/delivery-targets/${encodeURIComponent(deliveryTargetId)}/messages`;
37304
- return endpoint;
37305
- }
37306
- function daemonToken(relayUrl) {
37307
- const token = relayUrl.searchParams.get("token") ?? "";
37308
- if (!/^[a-zA-Z0-9_-]{32,256}$/.test(token)) {
37309
- throw new LocalBotAuthorizationError("bot_service_unavailable", "The Runtime credential is unavailable");
37310
- }
37311
- return token;
37312
- }
37313
- async function decodeRelayResponse(response) {
37314
- const encoded = await response.text();
37315
- let value;
37316
- try {
37317
- value = JSON.parse(encoded);
37318
- } catch (cause) {
37319
- throw new LocalBotAuthorizationError("bot_service_unavailable", "The Mobius Relay returned invalid data", {
37320
- cause
37321
- });
37322
- }
37323
- if (response.status === 202 && isRecord10(value) && typeof value["outboundMessageId"] === "string") {
37324
- return value["outboundMessageId"];
37325
- }
37326
- if (isRecord10(value) && isRecord10(value["error"])) {
37327
- const error62 = value["error"];
37328
- if (typeof error62["code"] === "string" && typeof error62["message"] === "string") {
37329
- throw new LocalBotAuthorizationError(error62["code"], error62["message"]);
37330
- }
37331
- }
37332
- throw new LocalBotAuthorizationError("bot_service_unavailable", "The Mobius Relay rejected the Bot action");
37333
- }
37334
- var BotOutboundIpcServer = class {
37335
- #registry;
37336
- #relayUrl;
37337
- #server;
37338
- #socketPath;
37339
- #usesFilesystemSocket;
37340
- constructor(socketPath, relayUrl, registry2) {
37341
- const usesFilesystemSocket = !socketPath.startsWith(WINDOWS_NAMED_PIPE_PREFIX);
37342
- if (usesFilesystemSocket && !isAbsolute10(socketPath)) {
37343
- throw new Error("The Bot IPC path must be absolute");
37344
- }
37345
- this.#registry = registry2;
37346
- this.#relayUrl = new URL(relayUrl);
37347
- this.#server = createServer({ allowHalfOpen: true }, (socket) => this.accept(socket));
37348
- this.#socketPath = socketPath;
37349
- this.#usesFilesystemSocket = usesFilesystemSocket;
37350
- }
37351
- get socketPath() {
37352
- return this.#socketPath;
37353
- }
37354
- listen = async (signal) => {
37355
- signal.throwIfAborted();
37356
- if (this.#usesFilesystemSocket) {
37357
- await mkdir3(dirname6(this.#socketPath), { mode: 448, recursive: true });
37358
- await unlink(this.#socketPath).catch((error62) => {
37359
- if (!isRecord10(error62) || error62["code"] !== "ENOENT") {
37360
- throw error62;
37361
- }
37362
- });
37363
- }
37364
- await new Promise((resolve6, reject) => {
37365
- const fail = (error62) => reject(error62);
37366
- this.#server.once("error", fail);
37367
- this.#server.listen(this.#socketPath, () => {
37368
- this.#server.removeListener("error", fail);
37369
- resolve6();
37370
- });
37371
- });
37372
- if (this.#usesFilesystemSocket) {
37373
- await chmod2(this.#socketPath, 384);
37374
- }
37375
- signal.addEventListener("abort", this.abort, { once: true });
37376
- if (signal.aborted) {
37377
- this.abort();
37378
- }
37379
- };
37380
- close = async () => {
37381
- if (this.#server.listening) {
37382
- await new Promise((resolve6, reject) => {
37383
- this.#server.close((error62) => {
37384
- if (error62 === void 0) {
37385
- resolve6();
37386
- return;
37387
- }
37388
- reject(error62);
37389
- });
37390
- });
37391
- }
37392
- if (this.#usesFilesystemSocket) {
37393
- await unlink(this.#socketPath).catch((error62) => {
37394
- if (!isRecord10(error62) || error62["code"] !== "ENOENT") {
37395
- throw error62;
37396
- }
37397
- });
37398
- }
37399
- };
37400
- #abort = () => {
37401
- this.#server.close();
37402
- };
37403
- abort = () => this.#abort();
37404
- accept = (socket) => {
37405
- const chunks = [];
37406
- let length = 0;
37407
- let rejected = false;
37408
- const controller = new AbortController();
37409
- socket.setTimeout(BOT_IPC_TIMEOUT_MILLISECONDS, () => {
37410
- controller.abort(new Error("Bot IPC request timed out"));
37411
- socket.destroy();
37412
- });
37413
- socket.on("data", (chunk) => {
37414
- length += chunk.byteLength;
37415
- if (length > BOT_IPC_REQUEST_LIMIT) {
37416
- rejected = true;
37417
- controller.abort(new Error("Bot IPC request is too large"));
37418
- socket.end(
37419
- JSON.stringify({
37420
- error: { code: "invalid_request", message: "The local Bot request is too large" },
37421
- ok: false
37422
- })
37423
- );
37424
- return;
37425
- }
37426
- chunks.push(chunk);
37427
- });
37428
- socket.once("error", () => controller.abort());
37429
- socket.once("close", () => controller.abort());
37430
- socket.once("end", () => {
37431
- if (rejected) {
37432
- return;
37433
- }
37434
- void this.handle(Buffer.concat(chunks).toString("utf8").trim(), controller.signal).then(
37435
- (outboundMessageId) => {
37436
- if (!socket.destroyed) {
37437
- socket.end(JSON.stringify({ ok: true, outboundMessageId }));
37438
- }
37439
- },
37440
- (error62) => {
37441
- if (socket.destroyed) {
37442
- return;
37443
- }
37444
- const code = error62 instanceof LocalBotAuthorizationError ? error62.code : "bot_service_unavailable";
37445
- const message = error62 instanceof LocalBotAuthorizationError ? error62.message : "The local Bot action could not be completed";
37446
- socket.end(JSON.stringify({ error: { code, message }, ok: false }));
37447
- }
37448
- );
37449
- });
37450
- };
37451
- handle = async (encoded, signal) => {
37452
- const request = decodeRequest(encoded);
37453
- const context = this.#registry.read(request.contextHandle);
37454
- const timeout = AbortSignal.timeout(BOT_RELAY_TIMEOUT_MILLISECONDS);
37455
- const requestSignal = AbortSignal.any([signal, timeout]);
37456
- let response;
37457
- try {
37458
- response = await fetch4(relayEndpoint(this.#relayUrl, context, request.target), {
37459
- body: JSON.stringify({ idempotencyKey: request.idempotencyKey, text: request.text }),
37460
- headers: {
37461
- authorization: `Bearer ${daemonToken(this.#relayUrl)}`,
37462
- "content-type": "application/json",
37463
- "x-mobius-bot-execution-capability": context.command.executionCapabilitySecret
37464
- },
37465
- method: "POST",
37466
- signal: requestSignal
37467
- });
37468
- } catch (cause) {
37469
- signal.throwIfAborted();
37470
- throw new LocalBotAuthorizationError(
37471
- timeout.aborted ? "bot_service_timeout" : "bot_service_unavailable",
37472
- timeout.aborted ? "The Mobius Bot action timed out" : "The Mobius Relay is unavailable",
37473
- { cause }
37474
- );
37475
- }
37476
- return await decodeRelayResponse(response);
37477
- };
37478
- };
37479
-
37480
36919
  // src/native-sessions/service.ts
37481
36920
  import { randomUUID } from "node:crypto";
37482
- import { basename as basename4 } from "node:path";
36921
+ import { basename as basename5 } from "node:path";
37483
36922
 
37484
36923
  // src/native-sessions/codex-history.ts
37485
36924
  import { spawn as spawn4 } from "node:child_process";
@@ -37988,7 +37427,7 @@ var NativeSessionService = class {
37988
37427
  }
37989
37428
  resolvedPaths.add(path2);
37990
37429
  additionalDirectories.push(path2);
37991
- additionalEntries.push({ directoryId: directoryId2, name: basename4(path2) });
37430
+ additionalEntries.push({ directoryId: directoryId2, name: basename5(path2) });
37992
37431
  }
37993
37432
  const listing = await this.#directories.list(this.#config.bindingId, command.directoryId, signal);
37994
37433
  const opened = await this.#sessions.forkSessionAtTurn(
@@ -38146,12 +37585,12 @@ var NativeSessionService = class {
38146
37585
 
38147
37586
  // src/prompt-artifact-resolver.ts
38148
37587
  import { createHash as createHash3 } from "node:crypto";
38149
- import { fetch as fetch5 } from "undici";
37588
+ import { fetch as fetch4 } from "undici";
38150
37589
  var ARTIFACT_SCHEME = "mobius-artifact:";
38151
37590
  var ARTIFACT_DOWNLOAD_TIMEOUT_MILLISECONDS = 2e4;
38152
37591
  var MAX_AGENT_IMAGE_BASE64_LENGTH = 4e6;
38153
37592
  var MAX_AGENT_RESOURCE_BYTE_LENGTH = 1e6;
38154
- var IDENTIFIER_PATTERN7 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
37593
+ var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
38155
37594
  var PromptArtifactError = class extends Error {
38156
37595
  code;
38157
37596
  constructor(code, message, options = {}) {
@@ -38194,7 +37633,7 @@ function parseReference(resource) {
38194
37633
  const encodedByteLength2 = url2.searchParams.get("byteLength") ?? "";
38195
37634
  const sha256 = url2.searchParams.get("sha256") ?? "";
38196
37635
  const byteLength = Number(encodedByteLength2);
38197
- 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)) {
37636
+ if (url2.protocol !== ARTIFACT_SCHEME || url2.hash.length > 0 || resource.type !== "link" || resource.text.length > 0 || !IDENTIFIER_PATTERN5.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)) {
38198
37637
  throw new PromptArtifactError("artifact_reference_invalid", "The prompt artifact reference is invalid");
38199
37638
  }
38200
37639
  return new PromptArtifactReference(artifactId, byteLength, sha256, resource);
@@ -38260,7 +37699,7 @@ async function download(config2, command, reference, signal) {
38260
37699
  const requestSignal = AbortSignal.any([signal, timeoutSignal]);
38261
37700
  let response;
38262
37701
  try {
38263
- response = await fetch5(downloadUrl(config2, command, reference), {
37702
+ response = await fetch4(downloadUrl(config2, command, reference), {
38264
37703
  dispatcher: environmentProxyDispatcher,
38265
37704
  headers: {
38266
37705
  accept: reference.resource.mimeType,
@@ -38374,7 +37813,7 @@ var RelayConnectionError = class extends Error {
38374
37813
  };
38375
37814
  function connectRelay(url2, signal) {
38376
37815
  signal.throwIfAborted();
38377
- return new Promise((resolve6, reject) => {
37816
+ return new Promise((resolve8, reject) => {
38378
37817
  const endpoint = new URL(url2);
38379
37818
  const headers = runtimeAuthorization(endpoint);
38380
37819
  endpoint.searchParams.delete("token");
@@ -38437,7 +37876,7 @@ function connectRelay(url2, signal) {
38437
37876
  }
38438
37877
  finished = true;
38439
37878
  cleanup();
38440
- resolve6(socket);
37879
+ resolve8(socket);
38441
37880
  };
38442
37881
  function onTimeout() {
38443
37882
  fail(
@@ -38698,7 +38137,7 @@ var RelayConnectionLiveness = class {
38698
38137
 
38699
38138
  // src/relay-connection/session-event-outbox.ts
38700
38139
  import { mkdirSync as mkdirSync3 } from "node:fs";
38701
- import { dirname as dirname7 } from "node:path";
38140
+ import { dirname as dirname6 } from "node:path";
38702
38141
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
38703
38142
  var DEFAULT_OUTBOX_LIMITS = {
38704
38143
  criticalEventBytes: 136 * 1024 * 1024,
@@ -38764,7 +38203,7 @@ var SessionEventOutbox = class {
38764
38203
  constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
38765
38204
  validateLimits(limits);
38766
38205
  this.#limits = limits;
38767
- mkdirSync3(dirname7(path2), { recursive: true });
38206
+ mkdirSync3(dirname6(path2), { recursive: true });
38768
38207
  this.#database = new DatabaseSync3(path2);
38769
38208
  this.#database.exec(`
38770
38209
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
@@ -39297,12 +38736,6 @@ var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
39297
38736
  var AGENT_ACTIVITY_COALESCING_MILLISECONDS = 100;
39298
38737
  var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
39299
38738
  var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
39300
- function botIpcSocketPath() {
39301
- if (process.platform === "win32") {
39302
- return `\\\\.\\pipe\\mobius-bot-${randomUUID3()}`;
39303
- }
39304
- return join16("/tmp", `mobius-bot-${randomUUID3()}.sock`);
39305
- }
39306
38739
  var DaemonAcpObserver = class {
39307
38740
  #config;
39308
38741
  #record;
@@ -39520,7 +38953,7 @@ async function reconcileActiveTurn(config2, turn, signal) {
39520
38953
  const requestSignal = AbortSignal.any([signal, timeoutSignal]);
39521
38954
  let response;
39522
38955
  try {
39523
- response = await fetch6(activeTurnReconciliationEndpoint(config2, turn), {
38956
+ response = await fetch5(activeTurnReconciliationEndpoint(config2, turn), {
39524
38957
  body: JSON.stringify({ outcome: { kind: "running" } }),
39525
38958
  dispatcher: environmentProxyDispatcher,
39526
38959
  headers: { ...runtimeAuthorization(config2.relayUrl), "content-type": "application/json" },
@@ -39832,13 +39265,13 @@ function reportFailure(publisher, command, code, message, attemptId) {
39832
39265
  );
39833
39266
  }
39834
39267
  function operationErrorCode(error62) {
39835
- if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof LocalBotAuthorizationError || error62 instanceof PromptArtifactError) {
39268
+ if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
39836
39269
  return error62.code;
39837
39270
  }
39838
39271
  return "session_operation_failed";
39839
39272
  }
39840
39273
  function operationErrorMessage(error62) {
39841
- if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof LocalBotAuthorizationError || error62 instanceof PromptArtifactError) {
39274
+ if (error62 instanceof AcpExecutionError || error62 instanceof LocalAuthorizationError || error62 instanceof LocalAgentCatalogError || error62 instanceof PromptArtifactError) {
39842
39275
  return error62.message;
39843
39276
  }
39844
39277
  return "The local agent operation could not be completed";
@@ -39873,7 +39306,7 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
39873
39306
  additionalDirectories.push(directory);
39874
39307
  additionalDirectoryEntries.push({
39875
39308
  directoryId: additionalDirectoryId,
39876
- name: basename5(directory)
39309
+ name: basename6(directory)
39877
39310
  });
39878
39311
  }
39879
39312
  return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
@@ -40425,37 +39858,6 @@ async function applyCompleteSessionConfiguration(sessions, audit, initialOptions
40425
39858
  }
40426
39859
  assertAppliedSessionConfiguration(options, selections);
40427
39860
  }
40428
- function botExecutionAgent(agent, contextHandle, socketPath) {
40429
- return new LocalAgentDefinition(
40430
- agent.id,
40431
- agent.label,
40432
- agent.command,
40433
- agent.arguments,
40434
- {
40435
- ...agent.environment,
40436
- MOBIUS_BOT_CONTEXT: contextHandle,
40437
- MOBIUS_BOT_SOCKET: socketPath,
40438
- MOBIUS_RELAY_TOKEN: "",
40439
- MOBIUS_RELAY_URL: ""
40440
- },
40441
- agent.adapterVersion,
40442
- agent.agentVersion,
40443
- agent.adapterIdentity,
40444
- agent.agentIdentity,
40445
- agent.capabilities,
40446
- agent.permissionProfile
40447
- );
40448
- }
40449
- function assertPreparedPermission(configOptions, permissionMode) {
40450
- const permission = configOptions.find((option) => option.id === "permission_mode");
40451
- if (permission === void 0 || permission.type !== "select" || permissionMode !== AGENT_DEFAULT_EXECUTION_SETTING && permission.currentValue !== permissionMode) {
40452
- throw new AcpExecutionError(
40453
- "The required Agent permission mode is unavailable",
40454
- {},
40455
- "invalid_session_configuration"
40456
- );
40457
- }
40458
- }
40459
39861
  function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selection, category, reason) {
40460
39862
  const details = {
40461
39863
  agentId,
@@ -40468,284 +39870,16 @@ function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selecti
40468
39870
  process.stderr.write(`Mobius daemon warning ${JSON.stringify({ commandId, event, sessionId, ...details })}
40469
39871
  `);
40470
39872
  }
40471
- async function applySupportedExecutionSelection(sessions, audit, configOptions, selection, category, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
40472
- if (selection.value === AGENT_DEFAULT_EXECUTION_SETTING) {
40473
- return configOptions;
40474
- }
40475
- const option = configOptions.find((candidate) => candidate.id === selection.configId);
40476
- if (option === void 0) {
40477
- warnIgnoredSetting(
40478
- audit,
40479
- "bot_execution_setting_ignored",
40480
- commandId,
40481
- sessionId,
40482
- agent.id,
40483
- selection,
40484
- category,
40485
- "setting_unavailable"
40486
- );
40487
- return configOptions;
40488
- }
40489
- if (option.type !== "select" || option.category !== category) {
40490
- warnIgnoredSetting(
40491
- audit,
40492
- "bot_execution_setting_ignored",
40493
- commandId,
40494
- sessionId,
40495
- agent.id,
40496
- selection,
40497
- category,
40498
- "setting_schema_mismatch"
40499
- );
40500
- return configOptions;
40501
- }
40502
- if (selection.valueType !== "select" || selection.booleanValue) {
40503
- warnIgnoredSetting(
40504
- audit,
40505
- "bot_execution_setting_ignored",
40506
- commandId,
40507
- sessionId,
40508
- agent.id,
40509
- selection,
40510
- category,
40511
- "selection_schema_mismatch"
40512
- );
40513
- return configOptions;
40514
- }
40515
- if (!option.values.some((value) => value.value === selection.value)) {
40516
- warnIgnoredSetting(
40517
- audit,
40518
- "bot_execution_setting_ignored",
40519
- commandId,
40520
- sessionId,
40521
- agent.id,
40522
- selection,
40523
- category,
40524
- "value_unavailable"
40525
- );
40526
- return configOptions;
40527
- }
40528
- if (option.currentValue === selection.value) {
40529
- return configOptions;
40530
- }
40531
- return await sessions.configureSession({
40532
- additionalDirectories,
40533
- agent,
40534
- booleanValue: false,
40535
- configId: selection.configId,
40536
- cwd,
40537
- requestId: `cfg_${randomUUID3()}`,
40538
- sessionId,
40539
- signal,
40540
- value: selection.value,
40541
- valueType: "select"
40542
- });
40543
- }
40544
- async function executeBotPrompt(outbox, publisher, command, config2, directories, audit, sessions, authorizer, contexts, applicator, ipc, attemptId, activateAttempt, timer, signal) {
40545
- const activities = new CoalescingDaemonActivityPublisher(timer, (activity) => {
40546
- publisher.recordAttempt(command.sessionId, encodeDaemonActivity(command, activity), attemptId);
40547
- });
40548
- try {
40549
- const startDeadline = Date.parse(command.executionDeadlineAt);
40550
- if (!Number.isSafeInteger(startDeadline) || startDeadline <= Date.now()) {
40551
- throw new LocalBotAuthorizationError("turn_expired", "The Bot execution start deadline has expired");
40552
- }
40553
- const execution = await authorizer.authorize(command, config2.catalog, directories, config2.bindingId, signal);
40554
- const resolved = await resolveSessionDirectories(
40555
- directories,
40556
- config2.bindingId,
40557
- command.directoryId,
40558
- command.additionalDirectoryIds,
40559
- signal
40560
- );
40561
- const attachments = await resolvePromptArtifacts(config2, command, signal);
40562
- const applied = await applicator.apply(command, execution, attachments.resources, signal);
40563
- const startExecution = () => {
40564
- audit.record({
40565
- commandId: command.commandId,
40566
- details: {
40567
- behaviorRevisionId: command.behaviorRevisionId,
40568
- bindingId: command.bindingId,
40569
- botId: command.botId,
40570
- executionId: command.executionId
40571
- },
40572
- event: "bot_session_authorized",
40573
- sessionId: command.sessionId
40574
- });
40575
- outbox.transitionExecution(command.commandId, "running");
40576
- publisher.recordAttempt(
40577
- command.sessionId,
40578
- encodeSessionStartedEvent({
40579
- attemptId,
40580
- commandId: command.commandId,
40581
- kind: SESSION_STARTED_KIND,
40582
- sessionId: command.sessionId
40583
- }),
40584
- attemptId
40585
- );
40586
- activateAttempt();
40587
- };
40588
- let stopReason = "steered";
40589
- if (command.disposition === SessionPromptDisposition.Steer) {
40590
- startExecution();
40591
- await sessions.steerPrompt({
40592
- additionalDirectories: resolved.additionalDirectories,
40593
- agent: execution.agent,
40594
- commandId: command.commandId,
40595
- cwd: resolved.cwd,
40596
- images: attachments.images,
40597
- prompt: command.prompt,
40598
- resources: applied.resources,
40599
- sessionId: command.sessionId,
40600
- signal,
40601
- targetCommandId: command.targetCommandId
40602
- });
40603
- } else {
40604
- if (command.disposition === SessionPromptDisposition.Queue && !outbox.isTerminalExecution(command.targetCommandId, command.sessionId)) {
40605
- throw new AcpExecutionError(
40606
- "The queued Bot prompt target is unavailable",
40607
- {},
40608
- "prompt_queue_target_unavailable"
40609
- );
40610
- }
40611
- const lease = contexts.activate(command);
40612
- try {
40613
- const agent = botExecutionAgent(execution.agent, lease.context.contextHandle, ipc.socketPath);
40614
- const prepared = await sessions.prepareExecutionSession({
40615
- additionalDirectories: resolved.additionalDirectories,
40616
- agent,
40617
- cwd: resolved.cwd,
40618
- sessionId: command.sessionId,
40619
- signal
40620
- });
40621
- assertPreparedPermission(prepared.configOptions, execution.executionConfiguration.permissionMode);
40622
- let configOptions = await applySupportedExecutionSelection(
40623
- sessions,
40624
- audit,
40625
- prepared.configOptions,
40626
- execution.executionConfiguration.model,
40627
- "model",
40628
- agent,
40629
- resolved.cwd,
40630
- resolved.additionalDirectories,
40631
- command.commandId,
40632
- command.sessionId,
40633
- signal
40634
- );
40635
- configOptions = await applySupportedExecutionSelection(
40636
- sessions,
40637
- audit,
40638
- configOptions,
40639
- execution.executionConfiguration.reasoningEffort,
40640
- "thought_level",
40641
- agent,
40642
- resolved.cwd,
40643
- resolved.additionalDirectories,
40644
- command.commandId,
40645
- command.sessionId,
40646
- signal
40647
- );
40648
- for (const selection of command.sessionConfigurations) {
40649
- await sessions.configureSession({
40650
- additionalDirectories: resolved.additionalDirectories,
40651
- agent,
40652
- booleanValue: selection.booleanValue,
40653
- configId: selection.configId,
40654
- cwd: resolved.cwd,
40655
- requestId: `cfg_${randomUUID3()}`,
40656
- sessionId: command.sessionId,
40657
- signal,
40658
- value: selection.value,
40659
- valueType: selection.valueType
40660
- });
40661
- }
40662
- startExecution();
40663
- const result = await sessions.runPrompt({
40664
- additionalDirectories: resolved.additionalDirectories,
40665
- agent,
40666
- commandId: command.commandId,
40667
- cwd: resolved.cwd,
40668
- disposition: command.disposition,
40669
- images: attachments.images,
40670
- onActivity: activities.record,
40671
- onText: (text3, messageId) => {
40672
- publisher.recordAttempt(
40673
- command.sessionId,
40674
- encodeAgentMessageDeltaEvent({
40675
- commandId: command.commandId,
40676
- kind: AGENT_MESSAGE_DELTA_KIND,
40677
- messageId,
40678
- sessionId: command.sessionId,
40679
- text: text3
40680
- }),
40681
- attemptId
40682
- );
40683
- return Promise.resolve();
40684
- },
40685
- prompt: command.prompt,
40686
- resources: applied.resources,
40687
- sessionId: command.sessionId,
40688
- signal,
40689
- targetCommandId: command.targetCommandId
40690
- });
40691
- stopReason = result.stopReason;
40692
- } finally {
40693
- lease.release();
40694
- }
40695
- }
40696
- activities.flush();
40697
- publisher.recordAttempt(
40698
- command.sessionId,
40699
- encodeSessionCompletedEvent({
40700
- commandId: command.commandId,
40701
- kind: SESSION_COMPLETED_KIND,
40702
- sessionId: command.sessionId,
40703
- stopReason
40704
- }),
40705
- attemptId
40706
- );
40707
- outbox.transitionExecution(command.commandId, stopReason === "cancelled" ? "cancelled" : "succeeded");
40708
- audit.record({
40709
- commandId: command.commandId,
40710
- details: { botId: command.botId, executionId: command.executionId },
40711
- event: stopReason === "cancelled" ? "bot_session_cancelled" : "bot_session_completed",
40712
- sessionId: command.sessionId
40713
- });
40714
- } catch (error62) {
40715
- activities.flush();
40716
- const failure2 = error62;
40717
- audit.record({
40718
- commandId: command.commandId,
40719
- details: {
40720
- botId: command.botId,
40721
- code: operationErrorCode(failure2),
40722
- executionId: command.executionId
40723
- },
40724
- event: "bot_session_failed",
40725
- sessionId: command.sessionId
40726
- });
40727
- const code = operationErrorCode(failure2);
40728
- reportFailure(
40729
- publisher,
40730
- command,
40731
- code === "session_operation_failed" ? "agent_execution_failed" : code,
40732
- code === "session_operation_failed" ? "The local agent could not complete the Bot request" : operationErrorMessage(failure2),
40733
- attemptId
40734
- );
40735
- outbox.transitionExecution(command.commandId, "failed");
40736
- console.error("Mobius daemon Bot command failed", failure2);
40737
- }
40738
- }
40739
39873
  function waitForRelayRetry(signal, timer) {
40740
39874
  if (signal.aborted) {
40741
39875
  return Promise.resolve();
40742
39876
  }
40743
- return new Promise((resolve6) => {
39877
+ return new Promise((resolve8) => {
40744
39878
  const retry = timer.schedule(finish, RELAY_RECONNECT_DELAY_MILLISECONDS);
40745
39879
  function finish() {
40746
39880
  retry.cancel();
40747
39881
  signal.removeEventListener("abort", finish);
40748
- resolve6();
39882
+ resolve8();
40749
39883
  }
40750
39884
  signal.addEventListener("abort", finish, { once: true });
40751
39885
  });
@@ -40788,7 +39922,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
40788
39922
  );
40789
39923
  }
40790
39924
  }
40791
- async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, outbox, publisher, authorizer, contexts, applicator, ipc, activeTurns, activeAttemptIds, connectionEpoch, diagnostics, onConnected, signal, timer) {
39925
+ async function runRelayConnection(config2, directories, audit, sessions, installations, installationObserver, nativeSessions, outbox, publisher, activeTurns, activeAttemptIds, connectionEpoch, diagnostics, onConnected, signal, timer) {
40792
39926
  const relayUrl = new URL(config2.relayUrl);
40793
39927
  relayUrl.searchParams.set("deliveryReceipts", "1");
40794
39928
  relayUrl.searchParams.set("liveness", "1");
@@ -40801,7 +39935,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40801
39935
  installationObserver.connect(socket);
40802
39936
  onConnected();
40803
39937
  try {
40804
- await new Promise((resolve6, reject) => {
39938
+ await new Promise((resolve8, reject) => {
40805
39939
  let finished = false;
40806
39940
  const cleanup = () => {
40807
39941
  connectionLiveness.close();
@@ -40819,7 +39953,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40819
39953
  }
40820
39954
  finished = true;
40821
39955
  cleanup();
40822
- resolve6();
39956
+ resolve8();
40823
39957
  };
40824
39958
  const rejectConnection = (failure2) => {
40825
39959
  if (finished) {
@@ -40954,32 +40088,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
40954
40088
  }
40955
40089
  return;
40956
40090
  }
40957
- if (kind === BOT_SESSION_PROMPT_KIND) {
40958
- const command = decodeBotSessionPromptCommand(delivery.payload);
40959
- await processDeliveredPrompt(
40960
- delivery,
40961
- command,
40962
- command.disposition !== SessionPromptDisposition.Steer,
40963
- (attemptId, activateAttempt, executionSignal) => executeBotPrompt(
40964
- outbox,
40965
- publisher,
40966
- command,
40967
- config2,
40968
- directories,
40969
- audit,
40970
- sessions,
40971
- authorizer,
40972
- contexts,
40973
- applicator,
40974
- ipc,
40975
- attemptId,
40976
- activateAttempt,
40977
- timer,
40978
- executionSignal
40979
- )
40980
- );
40981
- return;
40982
- }
40983
40091
  if (kind === SESSION_PROMPT_KIND) {
40984
40092
  const command = decodeSessionPromptCommand(delivery.payload);
40985
40093
  await processDeliveredPrompt(
@@ -41037,8 +40145,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41037
40145
  payloadSessionId = decodeSessionElicitationRespondCommand(delivery.payload).sessionId;
41038
40146
  } else if (payloadKind === SESSION_PROMPT_KIND) {
41039
40147
  payloadSessionId = decodeSessionPromptCommand(delivery.payload).sessionId;
41040
- } else if (payloadKind === BOT_SESSION_PROMPT_KIND) {
41041
- payloadSessionId = decodeBotSessionPromptCommand(delivery.payload).sessionId;
41042
40148
  } else {
41043
40149
  throw new Error("Runtime delivery contains an unsupported protocol message");
41044
40150
  }
@@ -41294,7 +40400,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41294
40400
  try {
41295
40401
  operationSignal.throwIfAborted();
41296
40402
  if (previous2.length > 0) {
41297
- await new Promise((resolve7, reject2) => {
40403
+ await new Promise((resolve9, reject2) => {
41298
40404
  const cancel = () => reject2(operationSignal.reason);
41299
40405
  operationSignal.addEventListener("abort", cancel, {
41300
40406
  once: true
@@ -41302,7 +40408,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41302
40408
  void Promise.all(previous2.map((request) => request.completion)).then(
41303
40409
  () => {
41304
40410
  operationSignal.removeEventListener("abort", cancel);
41305
- resolve7();
40411
+ resolve9();
41306
40412
  },
41307
40413
  (error62) => {
41308
40414
  operationSignal.removeEventListener("abort", cancel);
@@ -41376,13 +40482,13 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41376
40482
  try {
41377
40483
  operationSignal.throwIfAborted();
41378
40484
  if (previous2.length > 0) {
41379
- await new Promise((resolve7, reject2) => {
40485
+ await new Promise((resolve9, reject2) => {
41380
40486
  const cancel = () => reject2(operationSignal.reason);
41381
40487
  operationSignal.addEventListener("abort", cancel, { once: true });
41382
40488
  void Promise.all(previous2.map((request) => request.completion)).then(
41383
40489
  () => {
41384
40490
  operationSignal.removeEventListener("abort", cancel);
41385
- resolve7();
40491
+ resolve9();
41386
40492
  },
41387
40493
  (error62) => {
41388
40494
  operationSignal.removeEventListener("abort", cancel);
@@ -41431,6 +40537,29 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41431
40537
  connectionLiveness.acknowledge(decodeRuntimeHeartbeatAckEvent(encoded));
41432
40538
  return;
41433
40539
  }
40540
+ if (kind === FILE_READ_KIND) {
40541
+ const command2 = decodeFileReadCommand(encoded);
40542
+ void streamLocalFile(
40543
+ command2,
40544
+ (message) => send(socket, message),
40545
+ connectionController.signal
40546
+ ).catch((error62) => {
40547
+ if (socket.readyState !== WebSocket2.OPEN || connectionController.signal.aborted) {
40548
+ return;
40549
+ }
40550
+ send(
40551
+ socket,
40552
+ encodeFileFailedEvent({
40553
+ code: "file_unavailable",
40554
+ kind: FILE_FAILED_KIND,
40555
+ message: error62 instanceof Error ? error62.message : "The local file is unavailable",
40556
+ requestId: command2.requestId,
40557
+ sessionId: command2.sessionId
40558
+ })
40559
+ );
40560
+ });
40561
+ return;
40562
+ }
41434
40563
  if (kind === SESSION_CANCEL_KIND) {
41435
40564
  const cancellation = decodeSessionCancelCommand(encoded);
41436
40565
  const turn2 = activeTurns.get(cancellation.commandId);
@@ -41524,48 +40653,6 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41524
40653
  });
41525
40654
  return;
41526
40655
  }
41527
- if (kind === BOT_SESSION_PROMPT_KIND) {
41528
- const command2 = decodeBotSessionPromptCommand(encoded);
41529
- if (activeTurns.has(command2.commandId)) {
41530
- return;
41531
- }
41532
- const receipt2 = outbox.claimExecution(command2.commandId, command2.sessionId, encoded);
41533
- if (receipt2.kind === "duplicate") {
41534
- return;
41535
- }
41536
- const turn2 = new ActiveDaemonTurn(command2, receipt2.attemptId);
41537
- activeTurns.set(command2.commandId, turn2);
41538
- void executeBotPrompt(
41539
- outbox,
41540
- publisher,
41541
- command2,
41542
- config2,
41543
- directories,
41544
- audit,
41545
- sessions,
41546
- authorizer,
41547
- contexts,
41548
- applicator,
41549
- ipc,
41550
- receipt2.attemptId,
41551
- () => {
41552
- if (command2.disposition !== SessionPromptDisposition.Steer) {
41553
- activeAttemptIds.set(command2.sessionId, receipt2.attemptId);
41554
- }
41555
- },
41556
- timer,
41557
- turn2.signal
41558
- ).catch((error62) => {
41559
- console.error("Mobius daemon Bot turn failed", error62);
41560
- }).finally(() => {
41561
- activeTurns.delete(command2.commandId);
41562
- if (activeAttemptIds.get(command2.sessionId) === receipt2.attemptId) {
41563
- activeAttemptIds.delete(command2.sessionId);
41564
- }
41565
- turn2.finish();
41566
- });
41567
- return;
41568
- }
41569
40656
  if (kind !== SESSION_PROMPT_KIND) {
41570
40657
  throw new Error("Unsupported protocol message");
41571
40658
  }
@@ -41656,23 +40743,19 @@ async function runRelayConnection(config2, directories, audit, sessions, install
41656
40743
  }
41657
40744
  async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41658
40745
  const installationAudit = new AuditInstallationEvents(audit);
41659
- const stateDirectory = readStateDirectory();
40746
+ const stateDirectory = config2.localContext.stateDirectory;
41660
40747
  const specifications = supportedLocalAgentSpecifications();
41661
40748
  const installationExecutor = new FixedInstallationExecutor({
41662
40749
  defaultWorkspace: config2.defaultWorkspace,
41663
40750
  audit: installationAudit,
41664
40751
  catalog: config2.catalog,
41665
- environment: process.env,
40752
+ environment: config2.localContext.environment,
41666
40753
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
41667
40754
  stateDirectory
41668
40755
  });
41669
40756
  const sessionStore = new SqliteAcpSessionStore(config2.auditDatabasePath);
41670
40757
  const outbox = new SessionEventOutbox(config2.auditDatabasePath);
41671
40758
  const publisher = new DaemonSessionEventPublisher(outbox, timer);
41672
- const authorizer = new LocalBotExecutionAuthorizer();
41673
- const contexts = new BotExecutionContextRegistry();
41674
- const applicator = new EmbeddedBotContextApplicator();
41675
- const ipc = new BotOutboundIpcServer(botIpcSocketPath(), config2.relayUrl, contexts);
41676
40759
  const activeTurns = /* @__PURE__ */ new Map();
41677
40760
  const activeAttemptIds = /* @__PURE__ */ new Map();
41678
40761
  const recordSessionEvent = (sessionId, payload) => {
@@ -41725,10 +40808,10 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41725
40808
  return;
41726
40809
  }
41727
40810
  connectionAnnounced = true;
41728
- const reconnectCommand = `npx --yes @moxt-ai/mobius start --channel ${config2.channelId}`;
40811
+ const reconnectCommand = `npx --yes @moxt-ai/mobius start ${config2.reconnectTarget.commandArgument}`;
41729
40812
  process.stdout.write("Mobius daemon connected to the relay.\n\n");
41730
40813
  process.stdout.write(
41731
- `${styleText(["bold", "yellow"], `Reconnect this channel later:
40814
+ `${styleText(["bold", "yellow"], `Reconnect this local connection later:
41732
40815
  ${reconnectCommand}`)}
41733
40816
 
41734
40817
  `
@@ -41746,7 +40829,6 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41746
40829
  startAutomaticIntegrationProvisioning();
41747
40830
  });
41748
40831
  try {
41749
- await ipc.listen(signal);
41750
40832
  while (!signal.aborted) {
41751
40833
  connectionEpoch += 1;
41752
40834
  try {
@@ -41760,10 +40842,6 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41760
40842
  nativeSessions,
41761
40843
  outbox,
41762
40844
  publisher,
41763
- authorizer,
41764
- contexts,
41765
- applicator,
41766
- ipc,
41767
40845
  activeTurns,
41768
40846
  activeAttemptIds,
41769
40847
  connectionEpoch,
@@ -41796,19 +40874,15 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41796
40874
  await installations.close();
41797
40875
  } finally {
41798
40876
  try {
41799
- await ipc.close();
40877
+ await sessions.close();
41800
40878
  } finally {
41801
40879
  try {
41802
- await sessions.close();
40880
+ sessionStore.close();
41803
40881
  } finally {
41804
40882
  try {
41805
- sessionStore.close();
40883
+ publisher.close();
41806
40884
  } finally {
41807
- try {
41808
- publisher.close();
41809
- } finally {
41810
- outbox.close();
41811
- }
40885
+ outbox.close();
41812
40886
  }
41813
40887
  }
41814
40888
  }
@@ -41819,20 +40893,548 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
41819
40893
  }
41820
40894
 
41821
40895
  // src/pairing/pair-local-machine.ts
41822
- import { randomUUID as randomUUID4 } from "node:crypto";
41823
- import { mkdir as mkdir4, open as open4, realpath as realpath8, rename as rename3, stat as stat7, writeFile as writeFile2 } from "node:fs/promises";
40896
+ import { mkdir as mkdir4, realpath as realpath9, stat as stat8 } from "node:fs/promises";
41824
40897
  import { hostname as hostname3 } from "node:os";
41825
- import { basename as basename6, join as join17, resolve as resolve4 } from "node:path";
41826
- import { fetch as fetch7 } from "undici";
40898
+ import { basename as basename7, resolve as resolve6 } from "node:path";
40899
+ import { fetch as fetch6 } from "undici";
40900
+
40901
+ // src/storage/runtime-installation-store.ts
40902
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
40903
+ import { mkdir as mkdir3, open as open5, rename as rename3, unlink, writeFile as writeFile2 } from "node:fs/promises";
40904
+ import { dirname as dirname7, join as join16, resolve as resolve5 } from "node:path";
40905
+ var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
40906
+ var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
40907
+ var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
40908
+ var IDENTIFIER_PATTERN6 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
40909
+ var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
40910
+ var MAX_FILE_LENGTH = 16 * 1024;
40911
+ var INSTALLATION_POINTER_KEYS = ["installationId", "version"];
40912
+ var CHANNEL_INDEX_KEYS = [
40913
+ "applicationId",
40914
+ "channelId",
40915
+ "connectionId",
40916
+ "installationId",
40917
+ "version"
40918
+ ];
40919
+ var VERIFIED_CONNECTION_KEYS = [
40920
+ "applicationId",
40921
+ "channelId",
40922
+ "connectionId",
40923
+ "defaultWorkspace",
40924
+ "installationId",
40925
+ "kind",
40926
+ "relayOrigin",
40927
+ "runtimeCredential",
40928
+ "runtimeId",
40929
+ "version"
40930
+ ];
40931
+ var IMPORTED_LEGACY_CONNECTION_KEYS = [
40932
+ "applicationId",
40933
+ "channelId",
40934
+ "connectionId",
40935
+ "defaultWorkspace",
40936
+ "installationId",
40937
+ "kind",
40938
+ "relayOrigin",
40939
+ "runtimeCredential",
40940
+ "version"
40941
+ ];
40942
+ var CURRENT_CONNECTION_KEYS = [
40943
+ "defaultWorkspace",
40944
+ "channelId",
40945
+ "relayOrigin",
40946
+ "runtimeCredential"
40947
+ ];
40948
+ var LEGACY_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "daemonToken", "relayOrigin"];
40949
+ var RuntimeInstallationStoreError = class extends Error {
40950
+ code;
40951
+ constructor(code, message, options = {}) {
40952
+ super(message, options);
40953
+ this.code = code;
40954
+ this.name = "RuntimeInstallationStoreError";
40955
+ }
40956
+ };
40957
+ var StoredRuntimeConnection = class {
40958
+ applicationId;
40959
+ channelId;
40960
+ connectionId;
40961
+ defaultWorkspace;
40962
+ installationId;
40963
+ relayOrigin;
40964
+ runtimeCredential;
40965
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
40966
+ this.applicationId = applicationId;
40967
+ this.channelId = channelId;
40968
+ this.connectionId = connectionId2;
40969
+ this.defaultWorkspace = defaultWorkspace;
40970
+ this.installationId = installationId2;
40971
+ this.relayOrigin = relayOrigin;
40972
+ this.runtimeCredential = runtimeCredential2;
40973
+ }
40974
+ };
40975
+ var VerifiedRuntimeConnection = class extends StoredRuntimeConnection {
40976
+ kind = "verified";
40977
+ runtimeId;
40978
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2, runtimeId) {
40979
+ super(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2);
40980
+ this.runtimeId = runtimeId;
40981
+ }
40982
+ };
40983
+ var ImportedLegacyRuntimeConnection = class extends StoredRuntimeConnection {
40984
+ kind = "legacy_imported";
40985
+ constructor(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2) {
40986
+ super(applicationId, installationId2, connectionId2, channelId, defaultWorkspace, relayOrigin, runtimeCredential2);
40987
+ }
40988
+ };
40989
+ function isRecord9(value) {
40990
+ return typeof value === "object" && value !== null && !Array.isArray(value);
40991
+ }
40992
+ function hasExactKeys(value, expectedKeys) {
40993
+ const keys = Object.keys(value);
40994
+ return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
40995
+ }
40996
+ function isNodeError(error62, code) {
40997
+ return typeof error62 === "object" && error62 !== null && "code" in error62 && error62.code === code;
40998
+ }
40999
+ function validateApplicationId(value) {
41000
+ if (!APPLICATION_ID_PATTERN.test(value)) {
41001
+ throw new RuntimeInstallationStoreError("invalid_application_id", "The application ID is invalid");
41002
+ }
41003
+ return value;
41004
+ }
41005
+ function validateConnectionId(value) {
41006
+ if (!CONNECTION_ID_PATTERN.test(value)) {
41007
+ throw new RuntimeInstallationStoreError("invalid_connection_id", "The local connection ID is invalid");
41008
+ }
41009
+ return value;
41010
+ }
41011
+ function validateInstallationId(value) {
41012
+ if (!INSTALLATION_ID_PATTERN.test(value)) {
41013
+ throw new RuntimeInstallationStoreError("invalid_installation_id", "The installation ID is invalid");
41014
+ }
41015
+ return value;
41016
+ }
41017
+ function validateIdentifier(value, code) {
41018
+ if (!IDENTIFIER_PATTERN6.test(value)) {
41019
+ throw new RuntimeInstallationStoreError(code, "The saved Runtime connection is invalid");
41020
+ }
41021
+ return value;
41022
+ }
41023
+ function validateRuntimeCredential(value) {
41024
+ if (!RUNTIME_CREDENTIAL_PATTERN.test(value)) {
41025
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41026
+ }
41027
+ return value;
41028
+ }
41029
+ function parseRelayOrigin(value) {
41030
+ let origin;
41031
+ try {
41032
+ origin = new URL(value);
41033
+ } catch (cause) {
41034
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid", {
41035
+ cause
41036
+ });
41037
+ }
41038
+ if (origin.protocol !== "https:" && origin.protocol !== "http:" || origin.username.length > 0 || origin.password.length > 0 || origin.protocol === "http:" && origin.hostname !== "127.0.0.1" && origin.hostname !== "localhost") {
41039
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41040
+ }
41041
+ origin.hash = "";
41042
+ origin.pathname = "/";
41043
+ origin.search = "";
41044
+ return origin;
41045
+ }
41046
+ function connectionId() {
41047
+ return `mcn_${randomUUID4().replaceAll("-", "")}`;
41048
+ }
41049
+ function installationId() {
41050
+ return `min_${randomUUID4().replaceAll("-", "")}`;
41051
+ }
41052
+ function channelIndexFileName(channelId) {
41053
+ return `mci_${createHash4("sha256").update(channelId).digest("hex")}.json`;
41054
+ }
41055
+ function decodeInstallationPointer(value) {
41056
+ if (!isRecord9(value) || !hasExactKeys(value, INSTALLATION_POINTER_KEYS) || value["version"] !== 1) {
41057
+ throw new RuntimeInstallationStoreError("invalid_installation", "The local installation record is invalid");
41058
+ }
41059
+ const storedInstallationId = value["installationId"];
41060
+ if (typeof storedInstallationId !== "string") {
41061
+ throw new RuntimeInstallationStoreError("invalid_installation", "The local installation record is invalid");
41062
+ }
41063
+ return { installationId: validateInstallationId(storedInstallationId) };
41064
+ }
41065
+ function decodeChannelIndex(value) {
41066
+ if (!isRecord9(value) || !hasExactKeys(value, CHANNEL_INDEX_KEYS) || value["version"] !== 1) {
41067
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41068
+ }
41069
+ const applicationId = value["applicationId"];
41070
+ const channelId = value["channelId"];
41071
+ const connectionId2 = value["connectionId"];
41072
+ const storedInstallationId = value["installationId"];
41073
+ if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof storedInstallationId !== "string") {
41074
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41075
+ }
41076
+ return {
41077
+ applicationId: validateApplicationId(applicationId),
41078
+ channelId: validateIdentifier(channelId, "invalid_connection"),
41079
+ connectionId: validateConnectionId(connectionId2),
41080
+ installationId: validateInstallationId(storedInstallationId)
41081
+ };
41082
+ }
41083
+ function decodeVerifiedConnection(value) {
41084
+ if (!hasExactKeys(value, VERIFIED_CONNECTION_KEYS) || value["kind"] !== "verified" || value["version"] !== 1) {
41085
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41086
+ }
41087
+ const applicationId = value["applicationId"];
41088
+ const channelId = value["channelId"];
41089
+ const connectionId2 = value["connectionId"];
41090
+ const defaultWorkspace = value["defaultWorkspace"];
41091
+ const storedInstallationId = value["installationId"];
41092
+ const relayOrigin = value["relayOrigin"];
41093
+ const runtimeCredential2 = value["runtimeCredential"];
41094
+ const runtimeId = value["runtimeId"];
41095
+ if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string" || typeof runtimeId !== "string") {
41096
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41097
+ }
41098
+ return new VerifiedRuntimeConnection(
41099
+ validateApplicationId(applicationId),
41100
+ validateInstallationId(storedInstallationId),
41101
+ validateConnectionId(connectionId2),
41102
+ validateIdentifier(channelId, "invalid_connection"),
41103
+ defaultWorkspace,
41104
+ parseRelayOrigin(relayOrigin),
41105
+ validateRuntimeCredential(runtimeCredential2),
41106
+ validateIdentifier(runtimeId, "invalid_connection")
41107
+ );
41108
+ }
41109
+ function decodeImportedLegacyConnection(value) {
41110
+ if (!hasExactKeys(value, IMPORTED_LEGACY_CONNECTION_KEYS) || value["kind"] !== "legacy_imported" || value["version"] !== 1) {
41111
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41112
+ }
41113
+ const applicationId = value["applicationId"];
41114
+ const channelId = value["channelId"];
41115
+ const connectionId2 = value["connectionId"];
41116
+ const defaultWorkspace = value["defaultWorkspace"];
41117
+ const storedInstallationId = value["installationId"];
41118
+ const relayOrigin = value["relayOrigin"];
41119
+ const runtimeCredential2 = value["runtimeCredential"];
41120
+ if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
41121
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41122
+ }
41123
+ return new ImportedLegacyRuntimeConnection(
41124
+ validateApplicationId(applicationId),
41125
+ validateInstallationId(storedInstallationId),
41126
+ validateConnectionId(connectionId2),
41127
+ validateIdentifier(channelId, "invalid_connection"),
41128
+ defaultWorkspace,
41129
+ parseRelayOrigin(relayOrigin),
41130
+ validateRuntimeCredential(runtimeCredential2)
41131
+ );
41132
+ }
41133
+ function decodeConnection(value) {
41134
+ if (!isRecord9(value)) {
41135
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41136
+ }
41137
+ if (value["kind"] === "verified") {
41138
+ return decodeVerifiedConnection(value);
41139
+ }
41140
+ if (value["kind"] === "legacy_imported") {
41141
+ return decodeImportedLegacyConnection(value);
41142
+ }
41143
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41144
+ }
41145
+ function decodeLegacyConnection(value, expectedChannelId) {
41146
+ if (!isRecord9(value) || !hasExactKeys(value, CURRENT_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_CONNECTION_KEYS)) {
41147
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41148
+ }
41149
+ const channelId = value["channelId"];
41150
+ const defaultWorkspace = value["defaultWorkspace"];
41151
+ const relayOrigin = value["relayOrigin"];
41152
+ const runtimeCredential2 = value["runtimeCredential"] ?? value["daemonToken"];
41153
+ if (typeof channelId !== "string" || channelId !== expectedChannelId || typeof defaultWorkspace !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string") {
41154
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41155
+ }
41156
+ return {
41157
+ channelId: validateIdentifier(channelId, "invalid_connection"),
41158
+ defaultWorkspace,
41159
+ relayOrigin: parseRelayOrigin(relayOrigin),
41160
+ runtimeCredential: validateRuntimeCredential(runtimeCredential2)
41161
+ };
41162
+ }
41163
+ async function readJsonFile(path2, signal, missingCode) {
41164
+ signal.throwIfAborted();
41165
+ let handle;
41166
+ try {
41167
+ handle = await open5(path2, "r");
41168
+ } catch (cause) {
41169
+ if (isNodeError(cause, "ENOENT")) {
41170
+ throw new RuntimeInstallationStoreError(missingCode, "The saved Runtime connection was not found", {
41171
+ cause
41172
+ });
41173
+ }
41174
+ throw new RuntimeInstallationStoreError(
41175
+ "connection_unavailable",
41176
+ "The saved Runtime connection cannot be read",
41177
+ {
41178
+ cause
41179
+ }
41180
+ );
41181
+ }
41182
+ let encoded = "";
41183
+ try {
41184
+ const metadata = await handle.stat();
41185
+ if (!metadata.isFile() || metadata.size > MAX_FILE_LENGTH) {
41186
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
41187
+ }
41188
+ encoded = await handle.readFile({ encoding: "utf8" });
41189
+ } finally {
41190
+ await handle.close();
41191
+ }
41192
+ signal.throwIfAborted();
41193
+ try {
41194
+ return JSON.parse(encoded);
41195
+ } catch (cause) {
41196
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid", {
41197
+ cause
41198
+ });
41199
+ }
41200
+ }
41201
+ async function writeJsonAtomically(path2, value, signal) {
41202
+ signal.throwIfAborted();
41203
+ const directory = dirname7(path2);
41204
+ const temporaryPath = join16(directory, `.${randomUUID4()}.tmp`);
41205
+ try {
41206
+ await mkdir3(directory, { mode: 448, recursive: true });
41207
+ signal.throwIfAborted();
41208
+ await writeFile2(temporaryPath, `${JSON.stringify(value, null, 2)}
41209
+ `, { flag: "wx", mode: 384 });
41210
+ signal.throwIfAborted();
41211
+ await rename3(temporaryPath, path2);
41212
+ } catch (cause) {
41213
+ await unlink(temporaryPath).catch(() => void 0);
41214
+ signal.throwIfAborted();
41215
+ throw new RuntimeInstallationStoreError("connection_unavailable", "The local Runtime state cannot be written", {
41216
+ cause
41217
+ });
41218
+ }
41219
+ }
41220
+ var RuntimeInstallationStore = class _RuntimeInstallationStore {
41221
+ applicationId;
41222
+ installationId;
41223
+ stateDirectory;
41224
+ #channelDirectory;
41225
+ #connectionDirectory;
41226
+ constructor(applicationId, installationId2, stateDirectory) {
41227
+ this.applicationId = applicationId;
41228
+ this.installationId = installationId2;
41229
+ this.stateDirectory = stateDirectory;
41230
+ this.#channelDirectory = join16(stateDirectory, "channels");
41231
+ this.#connectionDirectory = join16(stateDirectory, "connections");
41232
+ }
41233
+ static open = async (options, signal) => {
41234
+ signal.throwIfAborted();
41235
+ const applicationId = validateApplicationId(options.applicationId);
41236
+ const rootDirectory = resolve5(options.stateDirectory);
41237
+ const applicationDirectory = join16(rootDirectory, "installations", applicationId);
41238
+ try {
41239
+ await mkdir3(applicationDirectory, { mode: 448, recursive: true });
41240
+ } catch (cause) {
41241
+ throw new RuntimeInstallationStoreError(
41242
+ "installation_unavailable",
41243
+ "The local installation cannot be initialized",
41244
+ {
41245
+ cause
41246
+ }
41247
+ );
41248
+ }
41249
+ const storedInstallationId = await readOrCreateInstallationId(applicationDirectory, signal);
41250
+ const stateDirectory = join16(applicationDirectory, storedInstallationId);
41251
+ try {
41252
+ await mkdir3(stateDirectory, { mode: 448, recursive: true });
41253
+ } catch (cause) {
41254
+ throw new RuntimeInstallationStoreError(
41255
+ "installation_unavailable",
41256
+ "The local installation cannot be initialized",
41257
+ {
41258
+ cause
41259
+ }
41260
+ );
41261
+ }
41262
+ signal.throwIfAborted();
41263
+ return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
41264
+ };
41265
+ connectionPath = (connectionId2) => join16(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
41266
+ auditDatabasePath = (connectionId2) => join16(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
41267
+ channelIndexPath = (channelId) => join16(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
41268
+ readConnection = async (connectionId2, signal) => {
41269
+ const stored = decodeConnection(
41270
+ await readJsonFile(this.connectionPath(connectionId2), signal, "connection_not_found")
41271
+ );
41272
+ if (stored.applicationId !== this.applicationId || stored.installationId !== this.installationId) {
41273
+ throw new RuntimeInstallationStoreError(
41274
+ "connection_owner_mismatch",
41275
+ "The saved Runtime connection belongs to another installation"
41276
+ );
41277
+ }
41278
+ return stored;
41279
+ };
41280
+ #readConnectionForChannel = async (channelId, signal) => {
41281
+ const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
41282
+ const index2 = decodeChannelIndex(
41283
+ await readJsonFile(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
41284
+ );
41285
+ if (index2.applicationId !== this.applicationId || index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
41286
+ throw new RuntimeInstallationStoreError(
41287
+ "connection_owner_mismatch",
41288
+ "The saved Runtime connection belongs to another installation"
41289
+ );
41290
+ }
41291
+ return await this.readConnection(index2.connectionId, signal);
41292
+ };
41293
+ migrateLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
41294
+ try {
41295
+ return await this.#readConnectionForChannel(channelId, signal);
41296
+ } catch (cause) {
41297
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "connection_not_found") {
41298
+ throw cause;
41299
+ }
41300
+ }
41301
+ return await this.importLegacyConnection(legacyStateDirectory, channelId, signal);
41302
+ };
41303
+ saveConnection = async (input2, signal) => {
41304
+ const stored = new VerifiedRuntimeConnection(
41305
+ this.applicationId,
41306
+ this.installationId,
41307
+ connectionId(),
41308
+ validateIdentifier(input2.channelId, "invalid_connection"),
41309
+ input2.defaultWorkspace,
41310
+ parseRelayOrigin(input2.relayOrigin.toString()),
41311
+ validateRuntimeCredential(input2.runtimeCredential),
41312
+ validateIdentifier(input2.runtimeId, "invalid_connection")
41313
+ );
41314
+ await this.writeConnection(stored, signal);
41315
+ return stored;
41316
+ };
41317
+ importLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
41318
+ const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
41319
+ const legacyPath = join16(resolve5(legacyStateDirectory), "connections", `${normalizedChannelId}.json`);
41320
+ const legacy = decodeLegacyConnection(
41321
+ await readJsonFile(legacyPath, signal, "connection_not_found"),
41322
+ normalizedChannelId
41323
+ );
41324
+ const stored = new ImportedLegacyRuntimeConnection(
41325
+ this.applicationId,
41326
+ this.installationId,
41327
+ connectionId(),
41328
+ legacy.channelId,
41329
+ legacy.defaultWorkspace,
41330
+ legacy.relayOrigin,
41331
+ legacy.runtimeCredential
41332
+ );
41333
+ await this.writeConnection(stored, signal);
41334
+ return stored;
41335
+ };
41336
+ writeConnection = async (stored, signal) => {
41337
+ signal.throwIfAborted();
41338
+ try {
41339
+ await this.#readConnectionForChannel(stored.channelId, signal);
41340
+ throw new RuntimeInstallationStoreError(
41341
+ "connection_conflict",
41342
+ "A Runtime connection for this channel already exists in this installation"
41343
+ );
41344
+ } catch (cause) {
41345
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "connection_not_found") {
41346
+ throw cause;
41347
+ }
41348
+ }
41349
+ const connectionPath = this.connectionPath(stored.connectionId);
41350
+ if (stored instanceof VerifiedRuntimeConnection) {
41351
+ await writeJsonAtomically(
41352
+ connectionPath,
41353
+ {
41354
+ applicationId: stored.applicationId,
41355
+ channelId: stored.channelId,
41356
+ connectionId: stored.connectionId,
41357
+ defaultWorkspace: stored.defaultWorkspace,
41358
+ installationId: stored.installationId,
41359
+ kind: stored.kind,
41360
+ relayOrigin: stored.relayOrigin.toString(),
41361
+ runtimeCredential: stored.runtimeCredential,
41362
+ runtimeId: stored.runtimeId,
41363
+ version: 1
41364
+ },
41365
+ signal
41366
+ );
41367
+ } else {
41368
+ await writeJsonAtomically(
41369
+ connectionPath,
41370
+ {
41371
+ applicationId: stored.applicationId,
41372
+ channelId: stored.channelId,
41373
+ connectionId: stored.connectionId,
41374
+ defaultWorkspace: stored.defaultWorkspace,
41375
+ installationId: stored.installationId,
41376
+ kind: stored.kind,
41377
+ relayOrigin: stored.relayOrigin.toString(),
41378
+ runtimeCredential: stored.runtimeCredential,
41379
+ version: 1
41380
+ },
41381
+ signal
41382
+ );
41383
+ }
41384
+ await writeJsonAtomically(
41385
+ this.channelIndexPath(stored.channelId),
41386
+ {
41387
+ applicationId: this.applicationId,
41388
+ channelId: stored.channelId,
41389
+ connectionId: stored.connectionId,
41390
+ installationId: this.installationId,
41391
+ version: 1
41392
+ },
41393
+ signal
41394
+ );
41395
+ };
41396
+ };
41397
+ async function readOrCreateInstallationId(applicationDirectory, signal) {
41398
+ const pointerPath = join16(applicationDirectory, "current.json");
41399
+ try {
41400
+ return decodeInstallationPointer(await readJsonFile(pointerPath, signal, "installation_not_found")).installationId;
41401
+ } catch (cause) {
41402
+ if (!(cause instanceof RuntimeInstallationStoreError) || cause.code !== "installation_not_found") {
41403
+ throw cause;
41404
+ }
41405
+ }
41406
+ const candidate = installationId();
41407
+ try {
41408
+ await writeFile2(pointerPath, `${JSON.stringify({ installationId: candidate, version: 1 })}
41409
+ `, {
41410
+ flag: "wx",
41411
+ mode: 384
41412
+ });
41413
+ return candidate;
41414
+ } catch (cause) {
41415
+ if (!isNodeError(cause, "EEXIST")) {
41416
+ throw new RuntimeInstallationStoreError(
41417
+ "installation_unavailable",
41418
+ "The local installation cannot be initialized",
41419
+ {
41420
+ cause
41421
+ }
41422
+ );
41423
+ }
41424
+ return decodeInstallationPointer(await readJsonFile(pointerPath, signal, "installation_not_found")).installationId;
41425
+ }
41426
+ }
41427
+ async function openRuntimeInstallationStore(options, signal) {
41428
+ return await RuntimeInstallationStore.open(options, signal);
41429
+ }
41430
+
41431
+ // src/pairing/pair-local-machine.ts
41827
41432
  var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
41828
41433
  var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
41829
- var IDENTIFIER_PATTERN8 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
41830
- var TOKEN_PATTERN2 = /^[a-zA-Z0-9_-]{32,256}$/;
41831
- var MAX_CONNECTION_FILE_LENGTH = 16 * 1024;
41434
+ var IDENTIFIER_PATTERN7 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
41435
+ var TOKEN_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
41832
41436
  var CLAIM_RESPONSE_KEYS = ["channelId", "daemonToken", "runtimeId"];
41833
41437
  var REDEEM_RESPONSE_KEYS = ["channelId", "runtimeCredential", "runtimeId"];
41834
- var LEGACY_SAVED_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "daemonToken", "relayOrigin"];
41835
- var SAVED_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "relayOrigin", "runtimeCredential"];
41836
41438
  var PairingClientError = class extends Error {
41837
41439
  code;
41838
41440
  constructor(code, message, options = {}) {
@@ -41841,14 +41443,14 @@ var PairingClientError = class extends Error {
41841
41443
  this.name = "PairingClientError";
41842
41444
  }
41843
41445
  };
41844
- function isRecord11(value) {
41446
+ function isRecord10(value) {
41845
41447
  return typeof value === "object" && value !== null && !Array.isArray(value);
41846
41448
  }
41847
- function hasExactKeys(value, expectedKeys) {
41449
+ function hasExactKeys2(value, expectedKeys) {
41848
41450
  const keys = Object.keys(value);
41849
41451
  return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
41850
41452
  }
41851
- function parseRelayOrigin(value) {
41453
+ function parseRelayOrigin2(value) {
41852
41454
  let url2;
41853
41455
  try {
41854
41456
  url2 = new URL(value);
@@ -41880,17 +41482,17 @@ function parsePairingCode(value) {
41880
41482
  return code;
41881
41483
  }
41882
41484
  function validatePairingId(value) {
41883
- if (!IDENTIFIER_PATTERN8.test(value)) {
41485
+ if (!IDENTIFIER_PATTERN7.test(value)) {
41884
41486
  throw new PairingClientError("invalid_pairing_id", "The Runtime pairing ID is invalid");
41885
41487
  }
41886
41488
  return value;
41887
41489
  }
41888
41490
  async function resolveDefaultWorkspace2(path2) {
41889
- const requestedWorkspace = resolve4(path2);
41491
+ const requestedWorkspace = resolve6(path2);
41890
41492
  try {
41891
41493
  await mkdir4(requestedWorkspace, { recursive: true, mode: 448 });
41892
- const defaultWorkspace = await realpath8(requestedWorkspace);
41893
- const metadata = await stat7(defaultWorkspace);
41494
+ const defaultWorkspace = await realpath9(requestedWorkspace);
41495
+ const metadata = await stat8(defaultWorkspace);
41894
41496
  if (!metadata.isDirectory()) {
41895
41497
  throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
41896
41498
  }
@@ -41919,9 +41521,9 @@ async function readJsonResponse(response) {
41919
41521
  }
41920
41522
  }
41921
41523
  function readRelayError(value) {
41922
- if (isRecord11(value)) {
41524
+ if (isRecord10(value)) {
41923
41525
  const error62 = value["error"];
41924
- if (isRecord11(error62)) {
41526
+ if (isRecord10(error62)) {
41925
41527
  const code = error62["code"];
41926
41528
  const message = error62["message"];
41927
41529
  if (typeof code === "string" && typeof message === "string") {
@@ -41932,13 +41534,13 @@ function readRelayError(value) {
41932
41534
  return new PairingClientError("pairing_failed", "The relay could not pair this machine");
41933
41535
  }
41934
41536
  function decodePairingResponse(value, credentialField, expectedKeys) {
41935
- if (!isRecord11(value) || !hasExactKeys(value, expectedKeys)) {
41537
+ if (!isRecord10(value) || !hasExactKeys2(value, expectedKeys)) {
41936
41538
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
41937
41539
  }
41938
41540
  const channelId = value["channelId"];
41939
41541
  const runtimeCredential2 = value[credentialField];
41940
41542
  const runtimeId = value["runtimeId"];
41941
- if (typeof channelId !== "string" || !IDENTIFIER_PATTERN8.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN2.test(runtimeCredential2) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN8.test(runtimeId)) {
41543
+ if (typeof channelId !== "string" || !IDENTIFIER_PATTERN7.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN7.test(runtimeId)) {
41942
41544
  throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
41943
41545
  }
41944
41546
  return { channelId, runtimeCredential: runtimeCredential2, runtimeId };
@@ -41948,7 +41550,6 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
41948
41550
  agentPath: agent.agentIdentity.requestedPath,
41949
41551
  agentVersion: agent.agentVersion,
41950
41552
  agentSettingsDiscovery: true,
41951
- botSessionConfiguration: true,
41952
41553
  capabilities: agent.capabilities,
41953
41554
  id: agent.id,
41954
41555
  label: agent.label,
@@ -41957,13 +41558,13 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
41957
41558
  const endpoint = options.pairingId.length > 0 ? mobiusApiUrl(options.relayOrigin, `/v1/runtime-pairings/${encodeURIComponent(options.pairingId)}/redeem`) : mobiusApiUrl(options.relayOrigin, "/pairings/claim");
41958
41559
  let response;
41959
41560
  try {
41960
- response = await fetch7(endpoint, {
41561
+ response = await fetch6(endpoint, {
41961
41562
  body: JSON.stringify({
41962
41563
  agents,
41963
41564
  installableAgents,
41964
41565
  machineName: hostname3(),
41965
41566
  pairingCode: options.code,
41966
- workspaceName: basename6(defaultWorkspace) || "Local workspace"
41567
+ workspaceName: basename7(defaultWorkspace) || "Local workspace"
41967
41568
  }),
41968
41569
  dispatcher: environmentProxyDispatcher,
41969
41570
  headers: { "content-type": "application/json" },
@@ -41979,156 +41580,88 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
41979
41580
  }
41980
41581
  return options.pairingId.length > 0 ? decodePairingResponse(value, "runtimeCredential", REDEEM_RESPONSE_KEYS) : decodePairingResponse(value, "daemonToken", CLAIM_RESPONSE_KEYS);
41981
41582
  }
41982
- async function persistConnection(channelId, relayOrigin, runtimeCredential2, defaultWorkspace, environment) {
41983
- const connectionsDirectory = join17(readStateDirectory(environment), "connections");
41984
- await mkdir4(connectionsDirectory, { mode: 448, recursive: true });
41985
- const connectionPath = join17(connectionsDirectory, `${channelId}.json`);
41986
- const temporaryPath = join17(connectionsDirectory, `.${channelId}.${randomUUID4()}.tmp`);
41987
- await writeFile2(
41988
- temporaryPath,
41989
- `${JSON.stringify(
41990
- {
41991
- defaultWorkspace,
41992
- channelId,
41993
- relayOrigin: relayOrigin.toString(),
41994
- runtimeCredential: runtimeCredential2
41995
- },
41996
- null,
41997
- 2
41998
- )}
41999
- `,
42000
- { flag: "wx", mode: 384 }
42001
- );
42002
- await rename3(temporaryPath, connectionPath);
42003
- return connectionPath;
42004
- }
42005
- function decodeSavedConnection(value, expectedChannelId) {
42006
- if (!isRecord11(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS) && !hasExactKeys(value, LEGACY_SAVED_CONNECTION_KEYS)) {
42007
- throw new PairingClientError("invalid_connection", "The saved connection is invalid");
42008
- }
42009
- const defaultWorkspace = value["defaultWorkspace"];
42010
- const channelId = value["channelId"];
42011
- const runtimeCredential2 = value["runtimeCredential"] ?? value["daemonToken"];
42012
- const relayOrigin = value["relayOrigin"];
42013
- if (typeof defaultWorkspace !== "string" || typeof channelId !== "string" || channelId !== expectedChannelId || !IDENTIFIER_PATTERN8.test(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN2.test(runtimeCredential2) || typeof relayOrigin !== "string") {
42014
- throw new PairingClientError("invalid_connection", "The saved connection is invalid");
42015
- }
42016
- return {
42017
- defaultWorkspace,
42018
- channelId,
42019
- relayOrigin: parseRelayOrigin(relayOrigin),
42020
- runtimeCredential: runtimeCredential2
42021
- };
42022
- }
42023
- async function readSavedConnection(channelId, environment) {
42024
- const connectionPath = join17(readStateDirectory(environment), "connections", `${channelId}.json`);
42025
- let encoded = "";
42026
- const handle = await open4(connectionPath, "r");
42027
- try {
42028
- const metadata = await handle.stat();
42029
- if (!metadata.isFile() || metadata.size > MAX_CONNECTION_FILE_LENGTH) {
42030
- throw new PairingClientError("invalid_connection", "The saved connection is invalid");
42031
- }
42032
- encoded = await handle.readFile({ encoding: "utf8" });
42033
- } finally {
42034
- await handle.close();
42035
- }
42036
- let value;
42037
- try {
42038
- value = JSON.parse(encoded);
42039
- } catch (error62) {
42040
- throw new PairingClientError("invalid_connection", "The saved connection is invalid", { cause: error62 });
42041
- }
42042
- const connection = decodeSavedConnection(value, channelId);
42043
- return {
42044
- defaultWorkspace: await resolveDefaultWorkspace2(connection.defaultWorkspace),
42045
- channelId: connection.channelId,
42046
- relayOrigin: connection.relayOrigin,
42047
- runtimeCredential: connection.runtimeCredential
42048
- };
42049
- }
42050
41583
  function assertInventoryUsable(inventory) {
42051
41584
  if (inventory.available.length + inventory.installable.length === 0) {
42052
41585
  throw new PairingClientError("no_supported_agent", "No supported Agent is available for local discovery");
42053
41586
  }
42054
41587
  }
42055
- function buildPairedDaemon(connection, connectionPath, inventory, environment) {
41588
+ function buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext) {
42056
41589
  assertInventoryUsable(inventory);
42057
41590
  const relayUrl = mobiusApiUrl(connection.relayOrigin, "/v1/runtimes/connect");
42058
41591
  relayUrl.protocol = relayUrl.protocol === "https:" ? "wss:" : "ws:";
42059
41592
  relayUrl.searchParams.set("token", connection.runtimeCredential);
42060
- const auditDatabasePath = join17(readStateDirectory(environment), "audit", `${connection.channelId}.sqlite`);
42061
41593
  return {
42062
41594
  channelUrl: new URL(`/channels/${encodeURIComponent(connection.channelId)}`, connection.relayOrigin).toString(),
41595
+ connectionId: connection.connectionId,
42063
41596
  config: createDaemonConfig(
42064
41597
  {
42065
- defaultWorkspace: connection.defaultWorkspace,
42066
- auditDatabasePath,
41598
+ defaultWorkspace,
41599
+ auditDatabasePath: installation.auditDatabasePath(connection.connectionId),
42067
41600
  channelId: connection.channelId,
42068
41601
  relayUrl
42069
41602
  },
42070
41603
  inventory.readyAgents(),
42071
- inventory.installable
41604
+ inventory.installable,
41605
+ localContext,
41606
+ new OpaqueDaemonReconnectTarget(connection.connectionId)
42072
41607
  ),
42073
- connectionPath
41608
+ connectionPath: installation.connectionPath(connection.connectionId)
42074
41609
  };
42075
41610
  }
42076
- async function pairRuntime(options, signal, environment) {
41611
+ async function pairRuntime(installation, options, signal, environment) {
41612
+ const localContext = new DaemonLocalContext(installation.stateDirectory, environment);
42077
41613
  const defaultWorkspace = await resolveDefaultWorkspace2(options.workspace);
42078
41614
  const inventory = await discoverLocalAgentInventory({
42079
41615
  defaultWorkspace,
42080
- environment,
41616
+ environment: localContext.environment,
42081
41617
  signal
42082
41618
  });
42083
41619
  assertInventoryUsable(inventory);
42084
41620
  const agents = inventory.readyAgents();
42085
41621
  const claim2 = await claimPairing(options, defaultWorkspace, agents, inventory.installable, signal);
42086
- const connectionPath = await persistConnection(
42087
- claim2.channelId,
42088
- options.relayOrigin,
42089
- claim2.runtimeCredential,
42090
- defaultWorkspace,
42091
- environment
42092
- );
42093
- return buildPairedDaemon(
41622
+ const connection = await installation.saveConnection(
42094
41623
  {
42095
- defaultWorkspace,
42096
41624
  channelId: claim2.channelId,
41625
+ defaultWorkspace,
42097
41626
  relayOrigin: options.relayOrigin,
42098
- runtimeCredential: claim2.runtimeCredential
41627
+ runtimeCredential: claim2.runtimeCredential,
41628
+ runtimeId: claim2.runtimeId
42099
41629
  },
42100
- connectionPath,
42101
- inventory,
42102
- environment
41630
+ signal
42103
41631
  );
41632
+ return buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext);
42104
41633
  }
42105
- async function pairMobiusRuntime(options, signal, environment = process.env) {
41634
+ async function pairMobiusRuntime(installation, options, signal, environment = process.env) {
42106
41635
  return await pairRuntime(
41636
+ installation,
42107
41637
  {
42108
41638
  code: parsePairingCode(options.pairingCode),
42109
41639
  pairingId: validatePairingId(options.pairingId),
42110
- relayOrigin: parseRelayOrigin(options.relayOrigin),
41640
+ relayOrigin: parseRelayOrigin2(options.relayOrigin),
42111
41641
  workspace: options.defaultWorkspace
42112
41642
  },
42113
41643
  signal,
42114
41644
  environment
42115
41645
  );
42116
41646
  }
42117
- async function resumeMobiusRuntime(channelId, signal, environment = process.env) {
42118
- const normalizedChannelId = validatePairingId(channelId);
42119
- const connectionPath = join17(readStateDirectory(environment), "connections", `${normalizedChannelId}.json`);
42120
- const connection = await readSavedConnection(normalizedChannelId, environment);
41647
+ async function resumeRuntimeConnection(installation, connection, signal, environment) {
41648
+ const localContext = new DaemonLocalContext(installation.stateDirectory, environment);
41649
+ const defaultWorkspace = await resolveDefaultWorkspace2(connection.defaultWorkspace);
42121
41650
  const inventory = await discoverLocalAgentInventory({
42122
- defaultWorkspace: connection.defaultWorkspace,
42123
- environment,
41651
+ defaultWorkspace,
41652
+ environment: localContext.environment,
42124
41653
  signal
42125
41654
  });
42126
- return buildPairedDaemon(connection, connectionPath, inventory, environment);
41655
+ return buildPairedDaemon(installation, connection, defaultWorkspace, inventory, localContext);
41656
+ }
41657
+ async function resumeMobiusRuntime(installation, connectionId2, signal, environment = process.env) {
41658
+ const connection = await installation.readConnection(connectionId2, signal);
41659
+ return await resumeRuntimeConnection(installation, connection, signal, environment);
42127
41660
  }
42128
41661
 
42129
41662
  // src/runtime.ts
42130
- var IDENTIFIER_PATTERN9 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
42131
- var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
41663
+ var IDENTIFIER_PATTERN8 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
41664
+ var RUNTIME_CREDENTIAL_PATTERN2 = /^[a-zA-Z0-9_-]{32,256}$/;
42132
41665
  var MobiusRuntimeConfigurationError = class extends Error {
42133
41666
  code = "runtime_configuration_invalid";
42134
41667
  constructor(message, options = {}) {
@@ -42152,7 +41685,7 @@ function validateRuntimeRelay(relayUrl) {
42152
41685
  if (credential.length === 0) {
42153
41686
  throw new MobiusRuntimeConfigurationError("The Runtime relay credential is required");
42154
41687
  }
42155
- if (!RUNTIME_CREDENTIAL_PATTERN.test(credential)) {
41688
+ if (!RUNTIME_CREDENTIAL_PATTERN2.test(credential)) {
42156
41689
  throw new MobiusRuntimeConfigurationError("The Runtime relay credential is invalid");
42157
41690
  }
42158
41691
  }
@@ -42179,11 +41712,11 @@ function relayUrlFromConnection(connection) {
42179
41712
  }
42180
41713
  function loadMobiusRuntimeConnection(environment = process.env) {
42181
41714
  const channelId = requiredEnvironmentValue(environment, "MOBIUS_CHANNEL_ID");
42182
- if (!IDENTIFIER_PATTERN9.test(channelId)) {
41715
+ if (!IDENTIFIER_PATTERN8.test(channelId)) {
42183
41716
  throw new MobiusRuntimeConfigurationError("MOBIUS_CHANNEL_ID is invalid");
42184
41717
  }
42185
41718
  return Object.freeze({
42186
- auditDatabasePath: environment["MOBIUS_AUDIT_DATABASE"]?.trim() || join18(readStateDirectory(environment), "audit", `${channelId}.sqlite`),
41719
+ auditDatabasePath: environment["MOBIUS_AUDIT_DATABASE"]?.trim() || join17(readStateDirectory(environment), "audit", `${channelId}.sqlite`),
42187
41720
  channelId,
42188
41721
  defaultWorkspace: loadDefaultWorkspace(environment),
42189
41722
  relayUrl: requiredEnvironmentValue(environment, "MOBIUS_RELAY_URL"),
@@ -42191,11 +41724,11 @@ function loadMobiusRuntimeConnection(environment = process.env) {
42191
41724
  });
42192
41725
  }
42193
41726
  async function resolveWorkspace(path2) {
42194
- const requested = resolve5(path2);
41727
+ const requested = resolve7(path2);
42195
41728
  try {
42196
41729
  await mkdir5(requested, { recursive: true, mode: 448 });
42197
- const resolved = await realpath9(requested);
42198
- const metadata = await stat8(resolved);
41730
+ const resolved = await realpath10(requested);
41731
+ const metadata = await stat9(resolved);
42199
41732
  if (!metadata.isDirectory()) {
42200
41733
  throw new MobiusRuntimeConfigurationError("The Runtime workspace is not a directory");
42201
41734
  }
@@ -42209,13 +41742,14 @@ async function resolveWorkspace(path2) {
42209
41742
  }
42210
41743
  async function createMobiusRuntimeEngine(connection, signal, environment = process.env) {
42211
41744
  signal.throwIfAborted();
41745
+ const localContext = new DaemonLocalContext(readStateDirectory(environment), environment);
42212
41746
  const relayUrl = relayUrlFromConnection(connection);
42213
41747
  const defaultWorkspace = await resolveWorkspace(connection.defaultWorkspace);
42214
- const auditDatabasePath = resolve5(connection.auditDatabasePath);
41748
+ const auditDatabasePath = resolve7(connection.auditDatabasePath);
42215
41749
  await mkdir5(dirname8(auditDatabasePath), { recursive: true, mode: 448 });
42216
41750
  const inventory = await discoverLocalAgentInventory({
42217
41751
  defaultWorkspace,
42218
- environment,
41752
+ environment: localContext.environment,
42219
41753
  signal
42220
41754
  });
42221
41755
  if (inventory.available.length + inventory.installable.length === 0) {
@@ -42230,7 +41764,8 @@ async function createMobiusRuntimeEngine(connection, signal, environment = proce
42230
41764
  relayUrl
42231
41765
  },
42232
41766
  inventory.readyAgents(),
42233
- inventory.installable
41767
+ inventory.installable,
41768
+ localContext
42234
41769
  )
42235
41770
  );
42236
41771
  }
@@ -42257,12 +41792,22 @@ var MobiusRuntimeEngine = class {
42257
41792
  };
42258
41793
  };
42259
41794
  export {
41795
+ ChannelDaemonReconnectTarget,
41796
+ DaemonLocalContext,
41797
+ DaemonReconnectTarget,
41798
+ ImportedLegacyRuntimeConnection,
42260
41799
  MobiusRuntimeConfigurationError,
42261
41800
  MobiusRuntimeEngine,
41801
+ OpaqueDaemonReconnectTarget,
42262
41802
  PairingClientError,
41803
+ RuntimeInstallationStore,
41804
+ RuntimeInstallationStoreError,
41805
+ StoredRuntimeConnection,
41806
+ VerifiedRuntimeConnection,
42263
41807
  createDaemonConfig,
42264
41808
  createMobiusRuntimeEngine,
42265
41809
  loadMobiusRuntimeConnection,
41810
+ openRuntimeInstallationStore,
42266
41811
  pairMobiusRuntime,
42267
41812
  resumeMobiusRuntime
42268
41813
  };