@moxt-ai/mobius 0.0.343 → 0.0.345

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 (162) hide show
  1. package/dist/cli/handler/agents/index.js +4 -4
  2. package/dist/cli/handler/agents/index.js.map +1 -1
  3. package/dist/cli/handler/agents/logic/agent-diagnostics.js +1 -1
  4. package/dist/cli/handler/agents/logic/agent-diagnostics.js.map +1 -1
  5. package/dist/cli/handler/daemon/start.js +2 -2
  6. package/dist/cli/handler/daemon/start.js.map +1 -1
  7. package/dist/cli/handler/logs/logic/collect-local-logs.js +2 -2
  8. package/dist/cli/handler/logs/logic/collect-local-logs.js.map +1 -1
  9. package/dist/cli/handler/pair/logic/pair-list-output.js +1 -1
  10. package/dist/cli/handler/pair/logic/pair-list-output.js.map +1 -1
  11. package/dist/cli/handler/pair/pair.js +2 -2
  12. package/dist/cli/handler/pair/pair.js.map +1 -1
  13. package/dist/cli/index.js +1 -1
  14. package/dist/cli/index.js.map +1 -1
  15. package/dist/cli.js +10089 -9978
  16. package/dist/cli.js.map +4 -4
  17. package/dist/daemon/config.d.ts +5 -0
  18. package/dist/daemon/config.d.ts.map +1 -0
  19. package/dist/daemon/config.js +40 -0
  20. package/dist/daemon/config.js.map +1 -0
  21. package/dist/daemon/control/local-client.d.ts.map +1 -1
  22. package/dist/daemon/control/local-client.js +1 -1
  23. package/dist/daemon/control/local-client.js.map +1 -1
  24. package/dist/daemon/control/local-server.d.ts.map +1 -1
  25. package/dist/daemon/control/local-server.js +1 -1
  26. package/dist/daemon/control/local-server.js.map +1 -1
  27. package/dist/daemon/lifecycle/manager-client.d.ts.map +1 -1
  28. package/dist/daemon/lifecycle/manager-client.js +3 -3
  29. package/dist/daemon/lifecycle/manager-client.js.map +1 -1
  30. package/dist/daemon/lifecycle/manager.d.ts.map +1 -1
  31. package/dist/daemon/lifecycle/manager.js +1 -1
  32. package/dist/daemon/lifecycle/manager.js.map +1 -1
  33. package/dist/daemon/lifecycle/worker.d.ts.map +1 -1
  34. package/dist/daemon/lifecycle/worker.js +6 -3
  35. package/dist/daemon/lifecycle/worker.js.map +1 -1
  36. package/dist/daemon/pairing/pair-local-machine.d.ts.map +1 -1
  37. package/dist/daemon/pairing/pair-local-machine.js +26 -21
  38. package/dist/daemon/pairing/pair-local-machine.js.map +1 -1
  39. package/dist/daemon/upgrades/data.d.ts.map +1 -1
  40. package/dist/daemon/upgrades/data.js +2 -2
  41. package/dist/daemon/upgrades/data.js.map +1 -1
  42. package/dist/daemon/upgrades/package.d.ts.map +1 -1
  43. package/dist/daemon/upgrades/package.js +1 -1
  44. package/dist/daemon/upgrades/package.js.map +1 -1
  45. package/dist/engine/index.d.ts +1 -1
  46. package/dist/engine/index.d.ts.map +1 -1
  47. package/dist/engine/index.js +1 -1
  48. package/dist/engine/index.js.map +1 -1
  49. package/dist/engine/runtime/catalog/refresh-agent-catalog.js +1 -1
  50. package/dist/engine/runtime/catalog/refresh-agent-catalog.js.map +1 -1
  51. package/dist/engine/runtime/catalog/resolve-catalog-agent.js +1 -1
  52. package/dist/engine/runtime/catalog/resolve-catalog-agent.js.map +1 -1
  53. package/dist/engine/runtime/command/registry/index.d.ts.map +1 -1
  54. package/dist/engine/runtime/command/registry/index.js +18 -1
  55. package/dist/engine/runtime/command/registry/index.js.map +1 -1
  56. package/dist/engine/runtime/config.d.ts +6 -8
  57. package/dist/engine/runtime/config.d.ts.map +1 -1
  58. package/dist/engine/runtime/config.js +9 -15
  59. package/dist/engine/runtime/config.js.map +1 -1
  60. package/dist/engine/runtime/connection/runtime-connection.d.ts +1 -2
  61. package/dist/engine/runtime/connection/runtime-connection.d.ts.map +1 -1
  62. package/dist/engine/runtime/connection/runtime-connection.js +1 -3
  63. package/dist/engine/runtime/connection/runtime-connection.js.map +1 -1
  64. package/dist/engine/runtime/connection/runtime-installation-store.d.ts +4 -7
  65. package/dist/engine/runtime/connection/runtime-installation-store.d.ts.map +1 -1
  66. package/dist/engine/runtime/connection/runtime-installation-store.js +56 -60
  67. package/dist/engine/runtime/connection/runtime-installation-store.js.map +1 -1
  68. package/dist/engine/runtime/engine.d.ts +10 -4
  69. package/dist/engine/runtime/engine.d.ts.map +1 -1
  70. package/dist/engine/runtime/engine.js +6 -25
  71. package/dist/engine/runtime/engine.js.map +1 -1
  72. package/dist/engine/runtime/relay/diagnostics.d.ts.map +1 -1
  73. package/dist/engine/runtime/relay/diagnostics.js +15 -0
  74. package/dist/engine/runtime/relay/diagnostics.js.map +1 -1
  75. package/dist/engine/runtime/relay/run-relay-connection.d.ts.map +1 -1
  76. package/dist/engine/runtime/relay/run-relay-connection.js +3 -0
  77. package/dist/engine/runtime/relay/run-relay-connection.js.map +1 -1
  78. package/dist/engine/runtime/run.js +2 -2
  79. package/dist/engine/runtime/run.js.map +1 -1
  80. package/dist/engine/session/api/session-layer.d.ts.map +1 -1
  81. package/dist/engine/session/api/session-layer.js +16 -10
  82. package/dist/engine/session/api/session-layer.js.map +1 -1
  83. package/dist/engine/session/native/native-session-browser.d.ts +1 -1
  84. package/dist/engine/session/native/native-session-browser.d.ts.map +1 -1
  85. package/dist/engine/session/native/native-session-browser.js.map +1 -1
  86. package/dist/engine/session/process/agent-process-pool.d.ts +0 -1
  87. package/dist/engine/session/process/agent-process-pool.d.ts.map +1 -1
  88. package/dist/engine/session/process/agent-process-pool.js +0 -14
  89. package/dist/engine/session/process/agent-process-pool.js.map +1 -1
  90. package/dist/engine/session/prompt/execute-prompt.d.ts.map +1 -1
  91. package/dist/engine/session/prompt/execute-prompt.js +10 -1
  92. package/dist/engine/session/prompt/execute-prompt.js.map +1 -1
  93. package/dist/engine/session/prompt/prompt-artifacts.d.ts.map +1 -1
  94. package/dist/engine/session/prompt/prompt-artifacts.js +6 -7
  95. package/dist/engine/session/prompt/prompt-artifacts.js.map +1 -1
  96. package/dist/engine/session/turn/execution-receipts.d.ts +3 -1
  97. package/dist/engine/session/turn/execution-receipts.d.ts.map +1 -1
  98. package/dist/engine/session/turn/execution-receipts.js +28 -0
  99. package/dist/engine/session/turn/execution-receipts.js.map +1 -1
  100. package/dist/engine/storage/installation/installation-files.d.ts +3 -4
  101. package/dist/engine/storage/installation/installation-files.d.ts.map +1 -1
  102. package/dist/engine/storage/installation/installation-files.js +5 -9
  103. package/dist/engine/storage/installation/installation-files.js.map +1 -1
  104. package/dist/engine/storage/logs/log-files.d.ts +2 -26
  105. package/dist/engine/storage/logs/log-files.d.ts.map +1 -1
  106. package/dist/engine/storage/logs/log-files.js +5 -128
  107. package/dist/engine/storage/logs/log-files.js.map +1 -1
  108. package/dist/engine.js +552 -486
  109. package/dist/engine.js.map +4 -4
  110. package/dist/{engine/storage → storage}/daemon/control-token.d.ts +1 -1
  111. package/dist/storage/daemon/control-token.d.ts.map +1 -0
  112. package/dist/{engine/storage → storage}/daemon/control-token.js +1 -1
  113. package/dist/storage/daemon/control-token.js.map +1 -0
  114. package/dist/{engine/storage → storage}/daemon/manager-lock.d.ts +1 -1
  115. package/dist/storage/daemon/manager-lock.d.ts.map +1 -0
  116. package/dist/{engine/storage → storage}/daemon/manager-lock.js +1 -1
  117. package/dist/storage/daemon/manager-lock.js.map +1 -0
  118. package/dist/storage/daemon/release-files.d.ts.map +1 -0
  119. package/dist/storage/daemon/release-files.js.map +1 -0
  120. package/dist/{engine/storage → storage}/daemon/version-data.d.ts +2 -0
  121. package/dist/storage/daemon/version-data.d.ts.map +1 -0
  122. package/dist/{engine/storage → storage}/daemon/version-data.js +17 -2
  123. package/dist/storage/daemon/version-data.js.map +1 -0
  124. package/dist/storage/files/output-file.d.ts.map +1 -0
  125. package/dist/{engine/storage → storage}/files/output-file.js +1 -1
  126. package/dist/storage/files/output-file.js.map +1 -0
  127. package/dist/storage/logs/log-files.d.ts +24 -0
  128. package/dist/storage/logs/log-files.d.ts.map +1 -0
  129. package/dist/storage/logs/log-files.js +122 -0
  130. package/dist/storage/logs/log-files.js.map +1 -0
  131. package/dist/storage/state-directory.d.ts.map +1 -0
  132. package/dist/storage/state-directory.js.map +1 -0
  133. package/dist/storage/state-root-layout.d.ts.map +1 -0
  134. package/dist/storage/state-root-layout.js.map +1 -0
  135. package/dist/storage/state-root.d.ts.map +1 -0
  136. package/dist/{engine/storage → storage}/state-root.js +1 -1
  137. package/dist/storage/state-root.js.map +1 -0
  138. package/package.json +2 -2
  139. package/dist/engine/storage/daemon/control-token.d.ts.map +0 -1
  140. package/dist/engine/storage/daemon/control-token.js.map +0 -1
  141. package/dist/engine/storage/daemon/manager-lock.d.ts.map +0 -1
  142. package/dist/engine/storage/daemon/manager-lock.js.map +0 -1
  143. package/dist/engine/storage/daemon/release-files.d.ts.map +0 -1
  144. package/dist/engine/storage/daemon/release-files.js.map +0 -1
  145. package/dist/engine/storage/daemon/version-data.d.ts.map +0 -1
  146. package/dist/engine/storage/daemon/version-data.js.map +0 -1
  147. package/dist/engine/storage/files/output-file.d.ts.map +0 -1
  148. package/dist/engine/storage/files/output-file.js.map +0 -1
  149. package/dist/engine/storage/state-directory.d.ts.map +0 -1
  150. package/dist/engine/storage/state-directory.js.map +0 -1
  151. package/dist/engine/storage/state-root-layout.d.ts.map +0 -1
  152. package/dist/engine/storage/state-root-layout.js.map +0 -1
  153. package/dist/engine/storage/state-root.d.ts.map +0 -1
  154. package/dist/engine/storage/state-root.js.map +0 -1
  155. /package/dist/{engine/storage → storage}/daemon/release-files.d.ts +0 -0
  156. /package/dist/{engine/storage → storage}/daemon/release-files.js +0 -0
  157. /package/dist/{engine/storage → storage}/files/output-file.d.ts +0 -0
  158. /package/dist/{engine/storage → storage}/state-directory.d.ts +0 -0
  159. /package/dist/{engine/storage → storage}/state-directory.js +0 -0
  160. /package/dist/{engine/storage → storage}/state-root-layout.d.ts +0 -0
  161. /package/dist/{engine/storage → storage}/state-root-layout.js +0 -0
  162. /package/dist/{engine/storage → storage}/state-root.d.ts +0 -0
package/dist/engine.js CHANGED
@@ -51,7 +51,7 @@ var __callDispose = (stack, error62, hasError) => {
51
51
 
52
52
  // src/daemon/pairing/pair-local-machine.ts
53
53
  import { hostname as hostname3 } from "node:os";
54
- import { basename as basename6, join as join26, resolve as resolve16 } from "node:path";
54
+ import { basename as basename9, join as join31, resolve as resolve16 } from "node:path";
55
55
 
56
56
  // ../mobius-sdk/src/protocol/platform/mobius-api.ts
57
57
  var MOBIUS_API_PREFIX = "/mobius/api";
@@ -5102,7 +5102,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
5102
5102
  var NONE = 0;
5103
5103
  var ASSUMED = 1;
5104
5104
  var PROVEN = 2;
5105
- function isRecursive(inst, stack, resolve18) {
5105
+ function isRecursive(inst, stack, resolve17) {
5106
5106
  const cached2 = recursive.get(inst);
5107
5107
  if (cached2 !== void 0)
5108
5108
  return cached2 ? PROVEN : NONE;
@@ -5112,7 +5112,7 @@ function isRecursive(inst, stack, resolve18) {
5112
5112
  let result = NONE;
5113
5113
  const check2 = (child) => {
5114
5114
  if (result !== PROVEN && child?._zod) {
5115
- const answer = isRecursive(child, stack, resolve18);
5115
+ const answer = isRecursive(child, stack, resolve17);
5116
5116
  if (answer > result)
5117
5117
  result = answer;
5118
5118
  }
@@ -5123,7 +5123,7 @@ function isRecursive(inst, stack, resolve18) {
5123
5123
  const desc2 = Object.getOwnPropertyDescriptor(sh, key);
5124
5124
  if (spread && !desc2.enumerable)
5125
5125
  continue;
5126
- const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve18) : NONE;
5126
+ const child = desc2.get ? ASSUMED : desc2.value?._zod ? isRecursive(desc2.value, stack, resolve17) : NONE;
5127
5127
  if (child > answer)
5128
5128
  answer = child;
5129
5129
  }
@@ -5187,7 +5187,7 @@ function isRecursive(inst, stack, resolve18) {
5187
5187
  break;
5188
5188
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
5189
5189
  case "lazy": {
5190
- const inner = def._cachedInner ?? (resolve18 ? inst._zod.innerType : void 0);
5190
+ const inner = def._cachedInner ?? (resolve17 ? inst._zod.innerType : void 0);
5191
5191
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
5192
5192
  break;
5193
5193
  }
@@ -19757,7 +19757,7 @@ function decodeIdentifier(value) {
19757
19757
 
19758
19758
  // ../mobius-sdk/src/protocol/runtime/diagnostics.ts
19759
19759
  var identifier = external_exports.custom(isIdentifier);
19760
- var runtimeDiagnosticsRequestSchema = external_exports.strictObject({
19760
+ var runtimeDiagnosticsRequestSchema = external_exports.object({
19761
19761
  kind: external_exports.literal("runtime.diagnostics.read"),
19762
19762
  requestId: identifier
19763
19763
  });
@@ -21316,6 +21316,16 @@ var activeTurnSnapshotSchema = external_exports.object({
21316
21316
  sequence: external_exports.number().int().nonnegative(),
21317
21317
  state: external_exports.literal("running")
21318
21318
  }).readonly();
21319
+ var commandDeliverySchema = external_exports.discriminatedUnion("state", [
21320
+ // No receipt: the command has not arrived. A delayed submission may still arrive later.
21321
+ external_exports.object({ state: external_exports.literal("unknown") }).readonly(),
21322
+ // The Runtime holds the command and has not finished it; it may be waiting or running.
21323
+ external_exports.object({ state: external_exports.literal("accepted") }).readonly(),
21324
+ external_exports.object({ state: external_exports.literal("completed"), stopReason: external_exports.string().max(2048) }).readonly(),
21325
+ external_exports.object({ code: identifierStringSchema, state: external_exports.literal("failed") }).readonly(),
21326
+ // The command started, but the Runtime no longer retains its result.
21327
+ external_exports.object({ state: external_exports.literal("expired") }).readonly()
21328
+ ]);
21319
21329
  var identity = {
21320
21330
  ...envelope,
21321
21331
  kind: external_exports.literal(NATIVE_SESSION_REQUEST_KIND),
@@ -21325,7 +21335,14 @@ var identity = {
21325
21335
  directoryId: DIRECTORY_IDENTIFIER
21326
21336
  };
21327
21337
  var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
21328
- external_exports.object({ ...identity, action: external_exports.literal("active-turn"), targetSessionId: identifierStringSchema }).readonly(),
21338
+ external_exports.object({
21339
+ ...identity,
21340
+ action: external_exports.literal("active-turn"),
21341
+ // Asks the Runtime for this command's delivery alongside the execution snapshot. It is not
21342
+ // named `commandId`, which routes a request as the command it names.
21343
+ deliveryCommandId: identifierStringSchema.optional(),
21344
+ targetSessionId: identifierStringSchema
21345
+ }).readonly(),
21329
21346
  external_exports.object({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifierStringSchema }).readonly(),
21330
21347
  external_exports.object({
21331
21348
  ...identity,
@@ -21340,7 +21357,14 @@ var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
21340
21357
  }).readonly()
21341
21358
  ]);
21342
21359
  var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
21343
- external_exports.object({ ...identity, action: external_exports.literal("active-turn"), targetSessionId: identifierStringSchema }).readonly(),
21360
+ external_exports.object({
21361
+ ...identity,
21362
+ action: external_exports.literal("active-turn"),
21363
+ // Asks the Runtime for this command's delivery alongside the execution snapshot. It is not
21364
+ // named `commandId`, which routes a request as the command it names.
21365
+ deliveryCommandId: identifierStringSchema.optional(),
21366
+ targetSessionId: identifierStringSchema
21367
+ }).readonly(),
21344
21368
  external_exports.object({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifierStringSchema }).readonly(),
21345
21369
  external_exports.object({
21346
21370
  ...identity,
@@ -21380,7 +21404,10 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
21380
21404
  attachments: external_exports.array(promptAttachmentSchema).max(16).readonly()
21381
21405
  }).readonly()
21382
21406
  ).readonly(),
21383
- turn: activeTurnSnapshotSchema.nullable()
21407
+ turn: activeTurnSnapshotSchema.nullable(),
21408
+ // Present only when the request named a command and every hop understands it. An
21409
+ // unrecognized delivery from a newer peer reads as absent instead of failing the snapshot.
21410
+ command: commandDeliverySchema.optional().catch(void 0)
21384
21411
  }).readonly(),
21385
21412
  external_exports.object({
21386
21413
  ...resultEnvelope,
@@ -21735,12 +21762,12 @@ var serviceToDaemonSignatures = {
21735
21762
  };
21736
21763
  var serviceToDaemonRegistry = serviceToDaemonSignatures;
21737
21764
  function decodeKnownServiceToDaemonMessage(encoded) {
21738
- const kind = decodeMessageKind(encoded);
21739
- const signature = serviceToDaemonRegistry[kind];
21740
- if (signature === void 0) {
21741
- return null;
21742
- }
21743
21765
  try {
21766
+ const kind = decodeMessageKind(encoded);
21767
+ const signature = serviceToDaemonRegistry[kind];
21768
+ if (signature === void 0) {
21769
+ return null;
21770
+ }
21744
21771
  return signature.decoder(encoded);
21745
21772
  } catch {
21746
21773
  return null;
@@ -21884,7 +21911,7 @@ import { fetch as fetch3 } from "undici";
21884
21911
  // package.json
21885
21912
  var package_default = {
21886
21913
  name: "@moxt-ai/mobius",
21887
- version: "0.0.343",
21914
+ version: "0.0.345",
21888
21915
  description: "Mobius CLI for pairing and running local AI agent services.",
21889
21916
  type: "module",
21890
21917
  bin: {
@@ -58963,11 +58990,11 @@ var Pushable = class {
58963
58990
  done = false;
58964
58991
  push(item) {
58965
58992
  if (this.resolvers.length > 0) {
58966
- const resolve18 = this.resolvers.shift();
58967
- if (resolve18 === void 0) {
58993
+ const resolve17 = this.resolvers.shift();
58994
+ if (resolve17 === void 0) {
58968
58995
  return;
58969
58996
  }
58970
- resolve18({ value: item, done: false });
58997
+ resolve17({ value: item, done: false });
58971
58998
  } else {
58972
58999
  this.queue.push(item);
58973
59000
  }
@@ -58975,8 +59002,8 @@ var Pushable = class {
58975
59002
  end() {
58976
59003
  this.done = true;
58977
59004
  while (this.resolvers.length > 0) {
58978
- const resolve18 = this.resolvers.shift();
58979
- resolve18?.({ done: true, value: void 0 });
59005
+ const resolve17 = this.resolvers.shift();
59006
+ resolve17?.({ done: true, value: void 0 });
58980
59007
  }
58981
59008
  }
58982
59009
  [Symbol.asyncIterator]() {
@@ -58992,8 +59019,8 @@ var Pushable = class {
58992
59019
  if (this.done) {
58993
59020
  return Promise.resolve({ done: true, value: void 0 });
58994
59021
  }
58995
- return new Promise((resolve18) => {
58996
- this.resolvers.push(resolve18);
59022
+ return new Promise((resolve17) => {
59023
+ this.resolvers.push(resolve17);
58997
59024
  });
58998
59025
  }
58999
59026
  };
@@ -59011,14 +59038,14 @@ function unreachable(value, logger = console) {
59011
59038
  async function withDeadline(signal, timeoutMilliseconds, operation) {
59012
59039
  const deadline = AbortSignal.any([signal, AbortSignal.timeout(timeoutMilliseconds)]);
59013
59040
  deadline.throwIfAborted();
59014
- return await new Promise((resolve18, reject2) => {
59041
+ return await new Promise((resolve17, reject2) => {
59015
59042
  const settle2 = (callback) => {
59016
59043
  deadline.removeEventListener("abort", onAbort);
59017
59044
  callback();
59018
59045
  };
59019
59046
  const onAbort = () => settle2(() => reject2(deadline.reason));
59020
59047
  deadline.addEventListener("abort", onAbort, { once: true });
59021
- operation().then((value) => settle2(() => resolve18(value)), (error62) => settle2(() => reject2(error62)));
59048
+ operation().then((value) => settle2(() => resolve17(value)), (error62) => settle2(() => reject2(error62)));
59022
59049
  });
59023
59050
  }
59024
59051
  var environmentChain = Promise.resolve();
@@ -59561,8 +59588,8 @@ function inputPath(context, key) {
59561
59588
  return plainString(context.input[key]);
59562
59589
  }
59563
59590
  function isInside(directory, candidate) {
59564
- const relative4 = path.relative(path.resolve(directory), path.resolve(candidate));
59565
- return relative4 === "" || !relative4.startsWith(`..${path.sep}`) && relative4 !== "..";
59591
+ const relative3 = path.relative(path.resolve(directory), path.resolve(candidate));
59592
+ return relative3 === "" || !relative3.startsWith(`..${path.sep}`) && relative3 !== "..";
59566
59593
  }
59567
59594
  function hasSessionAllowRuleFor(changeSet, toolName) {
59568
59595
  return !!changeSet?.updates.some((update) => update.type === "addRules" && update.destination === "session" && update.behavior === "allow" && update.rules.some((rule) => rule.toolName === toolName));
@@ -61711,14 +61738,14 @@ function waitUnlessAborted(milliseconds, signal) {
61711
61738
  if (signal.aborted) {
61712
61739
  return Promise.resolve(false);
61713
61740
  }
61714
- return new Promise((resolve18) => {
61741
+ return new Promise((resolve17) => {
61715
61742
  const timer = setTimeout(() => {
61716
61743
  signal.removeEventListener("abort", onAbort);
61717
- resolve18(true);
61744
+ resolve17(true);
61718
61745
  }, milliseconds);
61719
61746
  const onAbort = () => {
61720
61747
  clearTimeout(timer);
61721
- resolve18(false);
61748
+ resolve17(false);
61722
61749
  };
61723
61750
  signal.addEventListener("abort", onAbort, { once: true });
61724
61751
  });
@@ -61964,7 +61991,7 @@ var ClientConnection = class {
61964
61991
  }
61965
61992
  };
61966
61993
  function raceWithAbort(operation, signal) {
61967
- return new Promise((resolve18, reject2) => {
61994
+ return new Promise((resolve17, reject2) => {
61968
61995
  const cleanup = () => signal.removeEventListener("abort", onAbort);
61969
61996
  const onAbort = () => {
61970
61997
  cleanup();
@@ -61976,7 +62003,7 @@ function raceWithAbort(operation, signal) {
61976
62003
  }
61977
62004
  void operation.then((value) => {
61978
62005
  cleanup();
61979
- resolve18(value);
62006
+ resolve17(value);
61980
62007
  }, (error62) => {
61981
62008
  cleanup();
61982
62009
  reject2(error62);
@@ -62559,12 +62586,12 @@ var ClaudeAcpAgent = class {
62559
62586
  }
62560
62587
  };
62561
62588
  let completeTurn;
62562
- turn.completion = new Promise((resolve18) => {
62563
- completeTurn = resolve18;
62589
+ turn.completion = new Promise((resolve17) => {
62590
+ completeTurn = resolve17;
62564
62591
  });
62565
- const response = new Promise((resolve18, reject2) => {
62592
+ const response = new Promise((resolve17, reject2) => {
62566
62593
  turn.resolve = (result) => {
62567
- resolve18(result);
62594
+ resolve17(result);
62568
62595
  completeTurn();
62569
62596
  };
62570
62597
  turn.reject = (error62) => {
@@ -62979,8 +63006,8 @@ var ClaudeAcpAgent = class {
62979
63006
  pendingNext ??= session.query.next().then((result) => ({ kind: "message", result }));
62980
63007
  const nextMessage = pendingNext;
62981
63008
  let onAbort;
62982
- const abortRace = new Promise((resolve18) => {
62983
- onAbort = () => resolve18("abort");
63009
+ const abortRace = new Promise((resolve17) => {
63010
+ onAbort = () => resolve17("abort");
62984
63011
  cancelController.signal.addEventListener("abort", onAbort, { once: true });
62985
63012
  });
62986
63013
  const raced = await Promise.race([nextMessage, abortRace]);
@@ -70567,10 +70594,10 @@ var PiRpcProcess = class _PiRpcProcess {
70567
70594
  shell: shouldUseShellForPiCommand(cmd)
70568
70595
  });
70569
70596
  try {
70570
- await new Promise((resolve18, reject2) => {
70597
+ await new Promise((resolve17, reject2) => {
70571
70598
  const onSpawn = () => {
70572
70599
  cleanup();
70573
- resolve18();
70600
+ resolve17();
70574
70601
  };
70575
70602
  const onError = (err) => {
70576
70603
  cleanup();
@@ -70772,7 +70799,7 @@ var PiRpcProcess = class _PiRpcProcess {
70772
70799
  const timeoutMs = opts?.timeoutMs;
70773
70800
  const line = `${JSON.stringify(withId)}
70774
70801
  `;
70775
- return new Promise((resolve18, reject2) => {
70802
+ return new Promise((resolve17, reject2) => {
70776
70803
  const signal = opts?.signal;
70777
70804
  if (signal?.aborted === true) {
70778
70805
  reject2(signal.reason);
@@ -70794,7 +70821,7 @@ var PiRpcProcess = class _PiRpcProcess {
70794
70821
  this.pending.set(id, {
70795
70822
  resolve: (res) => {
70796
70823
  drop();
70797
- resolve18(res);
70824
+ resolve17(res);
70798
70825
  },
70799
70826
  reject: (error62) => {
70800
70827
  drop();
@@ -70827,14 +70854,14 @@ var PiRpcProcess = class _PiRpcProcess {
70827
70854
  });
70828
70855
  }
70829
70856
  writeLine(line) {
70830
- return new Promise((resolve18, reject2) => {
70857
+ return new Promise((resolve17, reject2) => {
70831
70858
  try {
70832
70859
  this.child.stdin.write(line, (error62) => {
70833
70860
  if (error62) {
70834
70861
  reject2(error62);
70835
70862
  return;
70836
70863
  }
70837
- resolve18();
70864
+ resolve17();
70838
70865
  });
70839
70866
  } catch (error62) {
70840
70867
  reject2(error62);
@@ -72105,8 +72132,8 @@ var PiAcpSession = class {
72105
72132
  }
72106
72133
  async prompt(message, images = []) {
72107
72134
  const expandedMessage = expandSlashCommand(message, this.fileCommands);
72108
- const turnPromise = new Promise((resolve18, reject2) => {
72109
- const queued = { message: expandedMessage, images, resolve: resolve18, reject: reject2 };
72135
+ const turnPromise = new Promise((resolve17, reject2) => {
72136
+ const queued = { message: expandedMessage, images, resolve: resolve17, reject: reject2 };
72110
72137
  if (this.pendingTurn) {
72111
72138
  this.turnQueue.push(queued);
72112
72139
  this.emit({
@@ -75073,8 +75100,8 @@ var AdapterRegistry = class {
75073
75100
  #resolve;
75074
75101
  #dependencies;
75075
75102
  #adapters = /* @__PURE__ */ new Map();
75076
- constructor(resolve18, dependencies) {
75077
- this.#resolve = resolve18;
75103
+ constructor(resolve17, dependencies) {
75104
+ this.#resolve = resolve17;
75078
75105
  this.#dependencies = dependencies;
75079
75106
  }
75080
75107
  resolve = (agent) => {
@@ -76066,14 +76093,14 @@ function mergeTextChunk(previous, incoming) {
76066
76093
  var SessionEventHistoryProjection = class {
76067
76094
  #toolCallEventIds = /* @__PURE__ */ new Map();
76068
76095
  #latestEvent = null;
76069
- apply = (liveEvent2, resolve18) => {
76096
+ apply = (liveEvent2, resolve17) => {
76070
76097
  if (liveEvent2.type === "lifecycle-metadata") {
76071
76098
  this.#latestEvent = null;
76072
76099
  return { kind: "skip" };
76073
76100
  }
76074
76101
  if (liveEvent2.type === "acp" && liveEvent2.payload.sessionUpdate === "tool_call_update") {
76075
76102
  const targetEventId = this.#toolCallEventIds.get(liveEvent2.payload.toolCallId);
76076
- const current = targetEventId === void 0 ? void 0 : resolve18([targetEventId]).get(targetEventId);
76103
+ const current = targetEventId === void 0 ? void 0 : resolve17([targetEventId]).get(targetEventId);
76077
76104
  if (current?.type === "acp" && (current.payload.sessionUpdate === "tool_call" || current.payload.sessionUpdate === "tool_call_update")) {
76078
76105
  return this.#replace(
76079
76106
  current,
@@ -76097,12 +76124,12 @@ var SessionEventHistoryProjection = class {
76097
76124
  * The projected tool call announced with this identifier, in its current
76098
76125
  * merged form, or `undefined` when the projection has not recorded one.
76099
76126
  */
76100
- getToolCall = (toolCallId, resolve18) => {
76127
+ getToolCall = (toolCallId, resolve17) => {
76101
76128
  const eventId = this.#toolCallEventIds.get(toolCallId);
76102
76129
  if (eventId === void 0) {
76103
76130
  return void 0;
76104
76131
  }
76105
- const event = resolve18([eventId]).get(eventId);
76132
+ const event = resolve17([eventId]).get(eventId);
76106
76133
  if (event?.type === "acp" && (event.payload.sessionUpdate === "tool_call" || event.payload.sessionUpdate === "tool_call_update")) {
76107
76134
  return event.payload;
76108
76135
  }
@@ -76162,8 +76189,8 @@ var SessionEvents = class {
76162
76189
  this.sessionGenerationId = sessionGenerationId;
76163
76190
  this.#projection = new SessionEventHistoryProjection();
76164
76191
  }
76165
- apply = (event, resolve18) => {
76166
- const projected = this.#projection.apply(event, resolve18);
76192
+ apply = (event, resolve17) => {
76193
+ const projected = this.#projection.apply(event, resolve17);
76167
76194
  this.#throughPosition = event.position;
76168
76195
  if (projected.kind === "skip") {
76169
76196
  return;
@@ -76190,7 +76217,7 @@ var SessionEvents = class {
76190
76217
  return this.#cachedItemsByEventId.size;
76191
76218
  }
76192
76219
  /** The projected tool call for this identifier, materializing it if needed. */
76193
- toolCall = (toolCallId, resolve18) => this.#projection.getToolCall(toolCallId, resolve18);
76220
+ toolCall = (toolCallId, resolve17) => this.#projection.getToolCall(toolCallId, resolve17);
76194
76221
  endIndex = (cursor) => {
76195
76222
  if (cursor === null) {
76196
76223
  return this.#eventIds.length;
@@ -77544,7 +77571,7 @@ function sql(strings, ...params) {
77544
77571
  return new SQL([new StringChunk(str)]);
77545
77572
  }
77546
77573
  _sql.raw = raw;
77547
- function join34(chunks, separator) {
77574
+ function join32(chunks, separator) {
77548
77575
  const result = [];
77549
77576
  for (const [i, chunk] of chunks.entries()) {
77550
77577
  if (i > 0 && separator !== void 0) result.push(separator);
@@ -77552,7 +77579,7 @@ function sql(strings, ...params) {
77552
77579
  }
77553
77580
  return new SQL(result);
77554
77581
  }
77555
- _sql.join = join34;
77582
+ _sql.join = join32;
77556
77583
  function identifier2(value) {
77557
77584
  return new Name(value);
77558
77585
  }
@@ -79273,7 +79300,7 @@ var SQLiteSelectBase = class extends TypedQueryBuilder {
79273
79300
  const baseTableName = this.tableName;
79274
79301
  const tableName = getTableLikeName(table);
79275
79302
  for (const item of extractUsedTable(table)) this.usedTables.add(item);
79276
- if (typeof tableName === "string" && this.config.joins?.some((join34) => join34.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
79303
+ if (typeof tableName === "string" && this.config.joins?.some((join32) => join32.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
79277
79304
  if (!this.isPartialSelect) {
79278
79305
  if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") this.config.fields = { [baseTableName]: this.config.fields };
79279
79306
  if (typeof tableName === "string" && !is(table, SQL)) {
@@ -80819,7 +80846,7 @@ var SQLiteDialect = class {
80819
80846
  if (!joins2) return;
80820
80847
  const withEntries = Object.entries(joins2).filter(([_, v]) => v);
80821
80848
  if (!withEntries.length) return;
80822
- return sql.join(withEntries.map(([k2, join34]) => {
80849
+ return sql.join(withEntries.map(([k2, join32]) => {
80823
80850
  const relation = tableConfig.relations[k2];
80824
80851
  const isSingle2 = is(relation, One2);
80825
80852
  const targetTable = aliasedTable(relation.targetTable, `d${currentDepth + 1}`);
@@ -80830,7 +80857,7 @@ var SQLiteDialect = class {
80830
80857
  table: targetTable,
80831
80858
  mode: isSingle2 ? "first" : "many",
80832
80859
  schema,
80833
- queryConfig: join34,
80860
+ queryConfig: join32,
80834
80861
  tableConfig: schema[relation.targetTableName],
80835
80862
  relationWhere: filter,
80836
80863
  isNested: true,
@@ -80844,7 +80871,7 @@ var SQLiteDialect = class {
80844
80871
  key: k2,
80845
80872
  selection: innerQuery.selection,
80846
80873
  isArray: !isSingle2,
80847
- isOptional: (relation.optional ?? false) || join34 !== true && !!join34.where
80874
+ isOptional: (relation.optional ?? false) || join32 !== true && !!join32.where
80848
80875
  });
80849
80876
  const jsonColumns = sql.join(innerQuery.selection.map((s) => {
80850
80877
  return sql`${sql.raw(this.escapeString(s.key))}, ${s.selection ? sql`${jsonb}(${sql.identifier(s.key)})` : sql.identifier(s.key)}`;
@@ -81198,7 +81225,7 @@ var SQLiteUpdateBase = class {
81198
81225
  createJoin(joinType) {
81199
81226
  return ((table, on2) => {
81200
81227
  const tableName = getTableLikeName(table);
81201
- if (typeof tableName === "string" && this.config.joins.some((join34) => join34.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
81228
+ if (typeof tableName === "string" && this.config.joins.some((join32) => join32.alias === tableName)) throw new Error(`Alias "${tableName}" is already used in this query`);
81202
81229
  if (typeof on2 === "function") {
81203
81230
  const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : void 0 : void 0;
81204
81231
  on2 = on2(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({
@@ -82858,7 +82885,7 @@ async function publishAgentCatalog(config2, signal) {
82858
82885
  }
82859
82886
 
82860
82887
  // src/engine/runtime/config.ts
82861
- import { join as join24, resolve as resolve14 } from "node:path";
82888
+ import { resolve as resolve13 } from "node:path";
82862
82889
 
82863
82890
  // src/engine/util/serial-task-queue.ts
82864
82891
  var SerialTaskQueue = class {
@@ -82929,24 +82956,15 @@ var LocalAgentCatalog = class {
82929
82956
  };
82930
82957
  };
82931
82958
 
82932
- // src/engine/storage/state-directory.ts
82933
- import { homedir as homedir3 } from "node:os";
82934
- import { join as join23, resolve as resolve13 } from "node:path";
82935
- var stateRootSchema = external_exports.string().brand();
82936
- function readStateDirectory(environment = process.env) {
82937
- const configured = environment["MOBIUS_STATE_DIRECTORY"]?.trim();
82938
- return stateRootSchema.parse(
82939
- configured !== void 0 && configured.length > 0 ? resolve13(configured) : join23(homedir3(), ".mobius")
82940
- );
82941
- }
82942
-
82943
82959
  // src/engine/runtime/config.ts
82944
82960
  var RuntimeLocalContext = class {
82945
- environment;
82961
+ agentLaunchEnvironment;
82946
82962
  stateDirectory;
82947
- constructor(stateDirectory, environment = process.env) {
82948
- this.stateDirectory = resolve14(stateDirectory);
82949
- this.environment = Object.freeze({ ...environment });
82963
+ maxAcpProcesses;
82964
+ constructor(stateDirectory, agentLaunchEnvironment, maxAcpProcesses = 1e3) {
82965
+ this.stateDirectory = resolve13(stateDirectory);
82966
+ this.agentLaunchEnvironment = Object.freeze({ ...agentLaunchEnvironment });
82967
+ this.maxAcpProcesses = maxAcpProcesses;
82950
82968
  }
82951
82969
  };
82952
82970
  function withRuntimeEnvironment(agent, environment) {
@@ -82969,8 +82987,10 @@ var OpaqueRuntimeReconnectTarget = class extends RuntimeReconnectTarget {
82969
82987
  this.commandArgument = `--connection ${connectionId2}`;
82970
82988
  }
82971
82989
  };
82972
- function createRuntimeConfig(connection, dependencies = new RuntimeAgentDependencies([]), localContext = new RuntimeLocalContext(readStateDirectory(), process.env), reconnectTarget = null, resolveAgent, rediscoverAgents) {
82973
- const runtimeAgents = dependencies.agents.map((agent) => withRuntimeEnvironment(agent, localContext.environment));
82990
+ function createRuntimeConfig(connection, dependencies, localContext, reconnectTarget = null, resolveAgent, rediscoverAgents) {
82991
+ const runtimeAgents = dependencies.agents.map(
82992
+ (agent) => withRuntimeEnvironment(agent, localContext.agentLaunchEnvironment)
82993
+ );
82974
82994
  return {
82975
82995
  adapters: dependencies.adapters,
82976
82996
  agents: runtimeAgents,
@@ -83012,7 +83032,7 @@ function createCatalogAgentResolver(discover, readConfig, publish) {
83012
83032
  signal.throwIfAborted();
83013
83033
  const inventory = await discover(signal);
83014
83034
  signal.throwIfAborted();
83015
- const rediscovered = inventory.readyAgents().filter((ready) => ready.id === agent.id).map((ready) => withRuntimeEnvironment(ready, config2.localContext.environment));
83035
+ const rediscovered = inventory.readyAgents().filter((ready) => ready.id === agent.id).map((ready) => withRuntimeEnvironment(ready, config2.localContext.agentLaunchEnvironment));
83016
83036
  await config2.catalog.replaceAndPublish(
83017
83037
  (current) => {
83018
83038
  if (!current.some((entry) => entry.id === agent.id)) {
@@ -83043,51 +83063,35 @@ async function unchangedIdentity(agent, signal) {
83043
83063
 
83044
83064
  // src/engine/runtime/connection/runtime-installation-store.ts
83045
83065
  import { randomUUID as randomUUID13 } from "node:crypto";
83046
- import { resolve as resolve15 } from "node:path";
83066
+ import { resolve as resolve14 } from "node:path";
83047
83067
 
83048
83068
  // src/engine/storage/installation/installation-files.ts
83049
83069
  import { createHash as createHash5, randomUUID as randomUUID12 } from "node:crypto";
83050
83070
  import { mkdir as mkdir4, open as open5, readdir as readdir5, rename as rename3, unlink as unlink3, writeFile } from "node:fs/promises";
83051
- import { dirname as dirname9, join as join25 } from "node:path";
83071
+ import { dirname as dirname9, join as join23 } from "node:path";
83052
83072
 
83053
83073
  // src/engine/util/node-error.ts
83054
83074
  function isNodeError(error62, code) {
83055
83075
  return typeof error62 === "object" && error62 !== null && "code" in error62 && error62.code === code;
83056
83076
  }
83057
83077
 
83058
- // src/engine/storage/state-root-layout.ts
83059
- var STATE_ROOT_LAYOUT = Object.freeze({
83060
- /** Names the version whose data is current. */
83061
- currentData: "current-data.txt",
83062
- /** Applications' installations: `installations/<application>/<installation>`. */
83063
- installations: "installations",
83064
- /** Managed CLI releases: `npm/<version>`. */
83065
- releases: "npm",
83066
- /** Each CLI version's data: `versions/<version>`. */
83067
- versions: "versions"
83068
- });
83069
- var STATE_ROOT_ENTRY_NAMES = new Set(Object.values(STATE_ROOT_LAYOUT));
83070
-
83071
83078
  // src/engine/storage/installation/installation-files.ts
83072
83079
  var MAXIMUM_FILE_BYTES = 16 * 1024;
83073
- function applicationDirectory(root, applicationId) {
83074
- return join25(root, STATE_ROOT_LAYOUT.installations, applicationId);
83075
- }
83076
- function installationPointerPath(applicationDirectory2) {
83077
- return join25(applicationDirectory2, "current.json");
83080
+ function installationPointerPath(engineDataDir) {
83081
+ return join23(engineDataDir, "current.json");
83078
83082
  }
83079
83083
  var installationDirectorySchema = external_exports.string().brand();
83080
- function installationDirectory(applicationDirectory2, installationId2) {
83081
- return installationDirectorySchema.parse(join25(applicationDirectory2, installationId2));
83084
+ function installationDirectory(engineDataDir, installationId2) {
83085
+ return installationDirectorySchema.parse(join23(engineDataDir, installationId2));
83082
83086
  }
83083
83087
  function connectionDirectory(installationDirectory2) {
83084
- return join25(installationDirectory2, "connections");
83088
+ return join23(installationDirectory2, "connections");
83085
83089
  }
83086
83090
  function connectionFilePath(connectionDirectory2, connectionId2) {
83087
- return join25(connectionDirectory2, `${connectionId2}.json`);
83091
+ return join23(connectionDirectory2, `${connectionId2}.json`);
83088
83092
  }
83089
83093
  function channelIndexFilePath(installationDirectory2, channelId) {
83090
- return join25(installationDirectory2, "channels", `mci_${createHash5("sha256").update(channelId).digest("hex")}.json`);
83094
+ return join23(installationDirectory2, "channels", `mci_${createHash5("sha256").update(channelId).digest("hex")}.json`);
83091
83095
  }
83092
83096
  async function readInstallationFile(path7) {
83093
83097
  let handle;
@@ -83109,7 +83113,7 @@ async function readInstallationFile(path7) {
83109
83113
  async function writeInstallationFile(path7, text2, signal) {
83110
83114
  signal.throwIfAborted();
83111
83115
  const directory = dirname9(path7);
83112
- const temporaryPath = join25(directory, `.${randomUUID12()}.tmp`);
83116
+ const temporaryPath = join23(directory, `.${randomUUID12()}.tmp`);
83113
83117
  try {
83114
83118
  await mkdir4(directory, { mode: 448, recursive: true });
83115
83119
  signal.throwIfAborted();
@@ -83147,7 +83151,6 @@ var VerifiedRuntimeConnection = class {
83147
83151
  kind = "verified";
83148
83152
  activation;
83149
83153
  appId;
83150
- applicationId;
83151
83154
  channelId;
83152
83155
  connectionId;
83153
83156
  defaultWorkspace;
@@ -83156,9 +83159,8 @@ var VerifiedRuntimeConnection = class {
83156
83159
  relayOrigin;
83157
83160
  runtimeCredential;
83158
83161
  runtimeId;
83159
- constructor(activation, applicationId, appId, installationId2, connectionId2, channelId, defaultWorkspace, pairingId, relayOrigin, runtimeCredential2, runtimeId) {
83162
+ constructor(activation, appId, installationId2, connectionId2, channelId, defaultWorkspace, pairingId, relayOrigin, runtimeCredential2, runtimeId) {
83160
83163
  this.activation = activation;
83161
- this.applicationId = applicationId;
83162
83164
  this.appId = appId;
83163
83165
  this.channelId = channelId;
83164
83166
  this.connectionId = connectionId2;
@@ -83172,22 +83174,14 @@ var VerifiedRuntimeConnection = class {
83172
83174
  };
83173
83175
 
83174
83176
  // src/engine/runtime/connection/runtime-installation-store.ts
83175
- var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
83176
83177
  var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
83177
83178
  var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
83178
83179
  var RUNTIME_CREDENTIAL_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
83179
83180
  var INSTALLATION_POINTER_KEYS = ["installationId", "version"];
83180
- var CHANNEL_INDEX_KEYS = [
83181
- "applicationId",
83182
- "channelId",
83183
- "connectionId",
83184
- "installationId",
83185
- "version"
83186
- ];
83181
+ var CHANNEL_INDEX_KEYS = ["channelId", "connectionId", "installationId", "version"];
83187
83182
  var VERIFIED_CONNECTION_KEYS = [
83188
83183
  "activation",
83189
83184
  "appId",
83190
- "applicationId",
83191
83185
  "channelId",
83192
83186
  "connectionId",
83193
83187
  "defaultWorkspace",
@@ -83214,12 +83208,6 @@ function hasExactKeys(value, expectedKeys) {
83214
83208
  const keys = Object.keys(value);
83215
83209
  return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
83216
83210
  }
83217
- function validateApplicationId(value) {
83218
- if (!APPLICATION_ID_PATTERN.test(value)) {
83219
- throw new RuntimeInstallationStoreError("invalid_application_id", "The application ID is invalid");
83220
- }
83221
- return value;
83222
- }
83223
83211
  function validateRemoteAppId(value) {
83224
83212
  if (!isIdentifier(value)) {
83225
83213
  throw new RuntimeInstallationStoreError("invalid_app_id", "The remote App ID is invalid");
@@ -83283,29 +83271,33 @@ function decodeInstallationPointer(value) {
83283
83271
  }
83284
83272
  return { installationId: validateInstallationId(storedInstallationId) };
83285
83273
  }
83286
- function decodeChannelIndex(value) {
83287
- if (!isRecord8(value) || !hasExactKeys(value, CHANNEL_INDEX_KEYS) || value["version"] !== 1) {
83274
+ function retainedFields(value, keys) {
83275
+ return Object.fromEntries(keys.filter((key) => Object.hasOwn(value, key)).map((key) => [key, value[key]]));
83276
+ }
83277
+ function decodeChannelIndex(input2) {
83278
+ if (!isRecord8(input2)) {
83279
+ throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
83280
+ }
83281
+ const value = input2["version"] === 1 ? retainedFields(input2, CHANNEL_INDEX_KEYS) : input2;
83282
+ if (!hasExactKeys(value, CHANNEL_INDEX_KEYS) || value["version"] !== 1 && value["version"] !== 2) {
83288
83283
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
83289
83284
  }
83290
- const applicationId = value["applicationId"];
83291
83285
  const channelId = value["channelId"];
83292
83286
  const connectionId2 = value["connectionId"];
83293
83287
  const storedInstallationId = value["installationId"];
83294
- if (typeof applicationId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof storedInstallationId !== "string") {
83288
+ if (typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof storedInstallationId !== "string") {
83295
83289
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
83296
83290
  }
83297
83291
  return {
83298
- applicationId: validateApplicationId(applicationId),
83299
83292
  channelId: validateIdentifier(channelId, "invalid_connection"),
83300
83293
  connectionId: validateConnectionId(connectionId2),
83301
83294
  installationId: validateInstallationId(storedInstallationId)
83302
83295
  };
83303
83296
  }
83304
83297
  function decodeVerifiedConnection(value) {
83305
- if (!hasExactKeys(value, VERIFIED_CONNECTION_KEYS) || value["version"] !== 5 || value["kind"] !== "verified") {
83298
+ if (!hasExactKeys(value, VERIFIED_CONNECTION_KEYS) || value["version"] !== 5 && value["version"] !== 6 || value["kind"] !== "verified") {
83306
83299
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
83307
83300
  }
83308
- const applicationId = value["applicationId"];
83309
83301
  const activation = value["activation"];
83310
83302
  const appId = value["appId"];
83311
83303
  const channelId = value["channelId"];
@@ -83316,12 +83308,11 @@ function decodeVerifiedConnection(value) {
83316
83308
  const relayOrigin = value["relayOrigin"];
83317
83309
  const runtimeCredential2 = value["runtimeCredential"];
83318
83310
  const runtimeId = value["runtimeId"];
83319
- if (typeof applicationId !== "string" || activation !== "active" && activation !== "stopped" || typeof appId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || typeof pairingId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string" || typeof runtimeId !== "string") {
83311
+ if (activation !== "active" && activation !== "stopped" || typeof appId !== "string" || typeof channelId !== "string" || typeof connectionId2 !== "string" || typeof defaultWorkspace !== "string" || typeof storedInstallationId !== "string" || typeof pairingId !== "string" || typeof relayOrigin !== "string" || typeof runtimeCredential2 !== "string" || typeof runtimeId !== "string") {
83320
83312
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
83321
83313
  }
83322
83314
  return new VerifiedRuntimeConnection(
83323
83315
  activation,
83324
- validateApplicationId(applicationId),
83325
83316
  validateRemoteAppId(appId),
83326
83317
  validateInstallationId(storedInstallationId),
83327
83318
  validateConnectionId(connectionId2),
@@ -83337,7 +83328,7 @@ function decodeConnection(value) {
83337
83328
  if (!isRecord8(value)) {
83338
83329
  throw new RuntimeInstallationStoreError("invalid_connection", "The saved Runtime connection is invalid");
83339
83330
  }
83340
- return decodeVerifiedConnection(value);
83331
+ return decodeVerifiedConnection(value["version"] === 5 ? retainedFields(value, VERIFIED_CONNECTION_KEYS) : value);
83341
83332
  }
83342
83333
  async function readJsonFile2(path7, signal, missingCode) {
83343
83334
  signal.throwIfAborted();
@@ -83381,25 +83372,20 @@ async function writeJsonAtomically(path7, value, signal) {
83381
83372
  }
83382
83373
  }
83383
83374
  var RuntimeInstallationStore = class _RuntimeInstallationStore {
83384
- applicationId;
83385
83375
  installationId;
83386
83376
  stateDirectory;
83387
83377
  #connectionDirectory;
83388
- constructor(applicationId, installationId2, stateDirectory) {
83389
- this.applicationId = applicationId;
83378
+ constructor(installationId2, stateDirectory) {
83390
83379
  this.installationId = installationId2;
83391
83380
  this.stateDirectory = stateDirectory;
83392
83381
  this.#connectionDirectory = connectionDirectory(stateDirectory);
83393
83382
  }
83394
- static open = async (options, signal) => {
83383
+ static open = async (engineDataDir, signal) => {
83395
83384
  signal.throwIfAborted();
83396
- const applicationId = validateApplicationId(options.applicationId);
83397
- const rootDirectory = resolve15(options.stateDirectory);
83398
- const applicationDirectory2 = applicationDirectory(rootDirectory, applicationId);
83385
+ const dataDirectory = resolve14(engineDataDir);
83399
83386
  try {
83400
- await ensurePrivateDirectory(rootDirectory);
83401
- await validateLocalPath(rootDirectory, true, true, signal);
83402
- await ensurePrivateDirectory(applicationDirectory2);
83387
+ await ensurePrivateDirectory(dataDirectory);
83388
+ await validateLocalPath(dataDirectory, true, true, signal);
83403
83389
  } catch (cause) {
83404
83390
  throw new RuntimeInstallationStoreError(
83405
83391
  "installation_unavailable",
@@ -83409,8 +83395,8 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
83409
83395
  }
83410
83396
  );
83411
83397
  }
83412
- const storedInstallationId = await readOrCreateInstallationId(applicationDirectory2, signal);
83413
- const stateDirectory = installationDirectory(applicationDirectory2, storedInstallationId);
83398
+ const storedInstallationId = await readOrCreateInstallationId(dataDirectory, signal);
83399
+ const stateDirectory = installationDirectory(dataDirectory, storedInstallationId);
83414
83400
  try {
83415
83401
  await ensurePrivateDirectory(stateDirectory);
83416
83402
  } catch (cause) {
@@ -83423,15 +83409,18 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
83423
83409
  );
83424
83410
  }
83425
83411
  signal.throwIfAborted();
83426
- return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
83412
+ return new _RuntimeInstallationStore(storedInstallationId, stateDirectory);
83427
83413
  };
83428
83414
  connectionPath = (connectionId2) => connectionFilePath(this.#connectionDirectory, validateConnectionId(connectionId2));
83429
83415
  channelIndexPath = (channelId) => channelIndexFilePath(this.stateDirectory, validateIdentifier(channelId, "invalid_channel_id"));
83430
83416
  readConnection = async (connectionId2, signal) => {
83431
- const stored = decodeConnection(
83417
+ return this.decodeOwnedConnection(
83432
83418
  await readJsonFile2(this.connectionPath(connectionId2), signal, "connection_not_found")
83433
83419
  );
83434
- if (stored.applicationId !== this.applicationId || stored.installationId !== this.installationId) {
83420
+ };
83421
+ decodeOwnedConnection = (record2) => {
83422
+ const stored = decodeConnection(record2);
83423
+ if (stored.installationId !== this.installationId) {
83435
83424
  throw new RuntimeInstallationStoreError(
83436
83425
  "connection_owner_mismatch",
83437
83426
  "The saved Runtime connection belongs to another installation"
@@ -83444,7 +83433,7 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
83444
83433
  const index2 = decodeChannelIndex(
83445
83434
  await readJsonFile2(this.channelIndexPath(normalizedChannelId), signal, "connection_not_found")
83446
83435
  );
83447
- if (index2.applicationId !== this.applicationId || index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
83436
+ if (index2.installationId !== this.installationId || index2.channelId !== normalizedChannelId) {
83448
83437
  throw new RuntimeInstallationStoreError(
83449
83438
  "connection_owner_mismatch",
83450
83439
  "The saved Runtime connection belongs to another installation"
@@ -83455,7 +83444,6 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
83455
83444
  saveConnection = async (input2, signal) => {
83456
83445
  const stored = new VerifiedRuntimeConnection(
83457
83446
  "active",
83458
- this.applicationId,
83459
83447
  validateRemoteAppId(input2.appId),
83460
83448
  this.installationId,
83461
83449
  connectionId(),
@@ -83486,11 +83474,10 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
83486
83474
  await writeJsonAtomically(
83487
83475
  this.channelIndexPath(stored.channelId),
83488
83476
  {
83489
- applicationId: this.applicationId,
83490
83477
  channelId: stored.channelId,
83491
83478
  connectionId: stored.connectionId,
83492
83479
  installationId: this.installationId,
83493
- version: 1
83480
+ version: 2
83494
83481
  },
83495
83482
  signal
83496
83483
  );
@@ -83528,10 +83515,10 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
83528
83515
  return connections.find((connection) => connection.pairingId === normalizedPairingId) ?? null;
83529
83516
  };
83530
83517
  setConnectionActivation = async (connectionId2, activation, signal) => {
83531
- const connection = await this.readConnection(connectionId2, signal);
83518
+ const record2 = await readJsonFile2(this.connectionPath(connectionId2), signal, "connection_not_found");
83519
+ const connection = this.decodeOwnedConnection(record2);
83532
83520
  const updated = new VerifiedRuntimeConnection(
83533
83521
  activation,
83534
- connection.applicationId,
83535
83522
  connection.appId,
83536
83523
  connection.installationId,
83537
83524
  connection.connectionId,
@@ -83542,7 +83529,11 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
83542
83529
  connection.runtimeCredential,
83543
83530
  connection.runtimeId
83544
83531
  );
83545
- await this.overwriteConnection(updated, signal);
83532
+ if (isRecord8(record2) && record2["version"] === 5) {
83533
+ await writeJsonAtomically(this.connectionPath(connectionId2), { ...record2, activation }, signal);
83534
+ } else {
83535
+ await this.overwriteConnection(updated, signal);
83536
+ }
83546
83537
  return updated;
83547
83538
  };
83548
83539
  removeConnection = async (connectionId2, signal) => {
@@ -83570,7 +83561,6 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
83570
83561
  connectionPath,
83571
83562
  {
83572
83563
  activation: connection.activation,
83573
- applicationId: connection.applicationId,
83574
83564
  appId: connection.appId,
83575
83565
  channelId: connection.channelId,
83576
83566
  connectionId: connection.connectionId,
@@ -83581,14 +83571,14 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
83581
83571
  relayOrigin: connection.relayOrigin.toString(),
83582
83572
  runtimeCredential: connection.runtimeCredential,
83583
83573
  runtimeId: connection.runtimeId,
83584
- version: 5
83574
+ version: 6
83585
83575
  },
83586
83576
  signal
83587
83577
  );
83588
83578
  };
83589
83579
  };
83590
- async function readOrCreateInstallationId(applicationDirectory2, signal) {
83591
- const pointerPath = installationPointerPath(applicationDirectory2);
83580
+ async function readOrCreateInstallationId(engineDataDir, signal) {
83581
+ const pointerPath = installationPointerPath(engineDataDir);
83592
83582
  try {
83593
83583
  return decodeInstallationPointer(await readJsonFile2(pointerPath, signal, "installation_not_found")).installationId;
83594
83584
  } catch (cause) {
@@ -83614,243 +83604,25 @@ async function readOrCreateInstallationId(applicationDirectory2, signal) {
83614
83604
  return decodeInstallationPointer(await readJsonFile2(pointerPath, signal, "installation_not_found")).installationId;
83615
83605
  }
83616
83606
  }
83617
- async function openRuntimeInstallationStore(options, signal) {
83618
- return await RuntimeInstallationStore.open(options, signal);
83607
+ async function openRuntimeInstallationStore(engineDataDir, signal) {
83608
+ return await RuntimeInstallationStore.open(engineDataDir, signal);
83619
83609
  }
83620
83610
 
83621
- // src/daemon/pairing/pair-local-machine.ts
83622
- var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
83623
- var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
83624
- var TOKEN_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
83625
- var CLAIM_RESPONSE_KEYS = ["appId", "channelId", "daemonToken", "runtimeId"];
83626
- var REDEEM_RESPONSE_KEYS = ["appId", "channelId", "runtimeCredential", "runtimeId"];
83627
- var PairingClientError = class extends Error {
83628
- code;
83629
- constructor(code, message, options = {}) {
83630
- super(message, options);
83631
- this.code = code;
83632
- this.name = "PairingClientError";
83633
- }
83634
- };
83635
- function hasExactKeys2(value, expectedKeys) {
83636
- const keys = Object.keys(value);
83637
- return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
83638
- }
83639
- function parseRelayOrigin2(value) {
83640
- let url2;
83641
- try {
83642
- url2 = new URL(value);
83643
- } catch (error62) {
83644
- throw new PairingClientError("invalid_relay_url", "The relay URL is invalid", { cause: error62 });
83645
- }
83646
- if (url2.protocol !== "https:" && url2.protocol !== "http:") {
83647
- throw new PairingClientError("invalid_relay_url", "The relay URL must use http or https");
83648
- }
83649
- if (url2.username.length > 0 || url2.password.length > 0) {
83650
- throw new PairingClientError("invalid_relay_url", "The relay URL cannot contain credentials");
83651
- }
83652
- if (url2.protocol === "http:" && url2.hostname !== "127.0.0.1" && url2.hostname !== "localhost") {
83653
- throw new PairingClientError("invalid_relay_url", "A remote relay must use https");
83654
- }
83655
- url2.hash = "";
83656
- url2.pathname = "/";
83657
- url2.search = "";
83658
- return url2;
83659
- }
83660
- function parsePairingCode(value) {
83661
- const code = value.trim().toUpperCase();
83662
- if (!PAIRING_CODE_PATTERN.test(code)) {
83663
- throw new PairingClientError(
83664
- "invalid_pairing_code",
83665
- "The pairing code must match the code shown in the browser"
83666
- );
83667
- }
83668
- return code;
83669
- }
83670
- function validatePairingId(value) {
83671
- if (!isIdentifier(value)) {
83672
- throw new PairingClientError("invalid_pairing_id", "The Runtime pairing ID is invalid");
83673
- }
83674
- return value;
83675
- }
83676
- async function resolveDefaultWorkspace(path7) {
83677
- const requestedWorkspace = resolve16(path7);
83678
- let defaultWorkspace;
83679
- try {
83680
- defaultWorkspace = await ensureCanonicalDirectory(requestedWorkspace);
83681
- } catch (error62) {
83682
- throw new PairingClientError("invalid_workspace", "The default workspace cannot be resolved", { cause: error62 });
83683
- }
83684
- if (defaultWorkspace === null) {
83685
- throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
83686
- }
83687
- return defaultWorkspace;
83688
- }
83689
- async function readJsonResponse(response) {
83690
- if (response.headers.get("cf-mitigated") === "challenge") {
83691
- throw new PairingClientError(
83692
- "relay_challenge",
83693
- "Cloudflare is protecting this temporary preview. Claim the deployment or use an authenticated deployment, then pair again"
83694
- );
83695
- }
83696
- const encoded = await response.text();
83697
- try {
83698
- return JSON.parse(encoded);
83699
- } catch (error62) {
83700
- throw new PairingClientError("invalid_relay_response", "The relay returned an invalid response", {
83701
- cause: error62
83702
- });
83703
- }
83704
- }
83705
- function readRelayError(value) {
83706
- if (isRecord3(value)) {
83707
- const error62 = value["error"];
83708
- if (isRecord3(error62)) {
83709
- const code = error62["code"];
83710
- const message = error62["message"];
83711
- if (typeof code === "string" && typeof message === "string") {
83712
- return new PairingClientError(code, message);
83713
- }
83714
- }
83715
- }
83716
- return new PairingClientError("pairing_failed", "The relay could not pair this machine");
83717
- }
83718
- function decodePairingResponse(value, credentialField, expectedKeys) {
83719
- if (!isRecord3(value) || !hasExactKeys2(value, expectedKeys)) {
83720
- throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
83721
- }
83722
- const appId = value["appId"];
83723
- const channelId = value["channelId"];
83724
- const runtimeCredential2 = value[credentialField];
83725
- const runtimeId = value["runtimeId"];
83726
- if (typeof appId !== "string" || !isIdentifier(appId) || typeof channelId !== "string" || !isIdentifier(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof runtimeId !== "string" || !isIdentifier(runtimeId)) {
83727
- throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
83728
- }
83729
- return { appId, channelId, runtimeCredential: runtimeCredential2, runtimeId };
83730
- }
83731
- async function claimPairing(options, defaultWorkspace, localAgents, signal) {
83732
- const agents = localAgents.map((agent) => ({
83733
- agentPath: agent.agentIdentity.requestedPath,
83734
- agentVersion: agent.agentVersion,
83735
- agentSettingsDiscovery: true,
83736
- capabilities: agent.capabilities,
83737
- id: agent.id,
83738
- label: agent.label,
83739
- sessionTurnConfiguration: true
83740
- }));
83741
- const endpoint = options.pairingId.length > 0 ? mobiusApiUrl(options.relayOrigin, `/v1/runtime-pairings/${encodeURIComponent(options.pairingId)}/redeem`) : mobiusApiUrl(options.relayOrigin, "/pairings/claim");
83742
- let response;
83743
- try {
83744
- response = await fetch3(endpoint, {
83745
- body: JSON.stringify({
83746
- agents,
83747
- machineName: hostname3(),
83748
- pairingCode: options.code,
83749
- workspaceName: basename6(defaultWorkspace) || "Local workspace"
83750
- }),
83751
- dispatcher: environmentProxyDispatcher,
83752
- headers: { "content-type": "application/json" },
83753
- method: "POST",
83754
- signal: AbortSignal.any([signal, AbortSignal.timeout(PAIRING_TIMEOUT_MILLISECONDS)])
83755
- });
83756
- } catch (error62) {
83757
- throw new PairingClientError("relay_unavailable", "The pairing relay could not be reached", { cause: error62 });
83758
- }
83759
- const value = await readJsonResponse(response);
83760
- if (!response.ok) {
83761
- throw readRelayError(value);
83762
- }
83763
- return options.pairingId.length > 0 ? decodePairingResponse(value, "runtimeCredential", REDEEM_RESPONSE_KEYS) : decodePairingResponse(value, "daemonToken", CLAIM_RESPONSE_KEYS);
83764
- }
83765
- function buildPairedRuntime(installation, connection, defaultWorkspace, inventory, localContext) {
83766
- const relayUrl = mobiusApiUrl(connection.relayOrigin, "/v1/runtimes/connect");
83767
- relayUrl.protocol = relayUrl.protocol === "https:" ? "wss:" : "ws:";
83768
- relayUrl.searchParams.set("token", connection.runtimeCredential);
83769
- const config2 = createRuntimeConfig(
83770
- {
83771
- defaultWorkspace,
83772
- channelId: connection.channelId,
83773
- relayUrl
83774
- },
83775
- new RuntimeAgentDependencies(inventory.readyAgents()),
83776
- localContext,
83777
- new OpaqueRuntimeReconnectTarget(connection.connectionId),
83778
- createCatalogAgentResolver(
83779
- (refreshSignal) => discoverLocalAgentInventory({
83780
- defaultWorkspace,
83781
- dataDirectory: localContext.stateDirectory,
83782
- environment: localContext.environment,
83783
- signal: refreshSignal
83784
- }),
83785
- () => config2,
83786
- publishAgentCatalog
83787
- ),
83788
- (refreshSignal) => discoverLocalAgentInventory({
83789
- defaultWorkspace,
83790
- dataDirectory: localContext.stateDirectory,
83791
- environment: localContext.environment,
83792
- signal: refreshSignal
83793
- }).then((inventory2) => inventory2.readyAgents())
83794
- );
83795
- return {
83796
- channelUrl: new URL(`/channels/${encodeURIComponent(connection.channelId)}`, connection.relayOrigin).toString(),
83797
- connectionId: connection.connectionId,
83798
- config: config2,
83799
- connectionPath: installation.connectionPath(connection.connectionId)
83800
- };
83801
- }
83802
- async function pairRuntime(installation, options, signal, environment) {
83803
- const localContext = new RuntimeLocalContext(installation.stateDirectory, environment);
83804
- const defaultWorkspace = await resolveDefaultWorkspace(options.workspace);
83805
- const inventory = await discoverLocalAgentInventory({
83806
- defaultWorkspace,
83807
- dataDirectory: localContext.stateDirectory,
83808
- environment: localContext.environment,
83809
- signal
83810
- });
83811
- const claim2 = await claimPairing(options, defaultWorkspace, inventory.readyAgents(), signal);
83812
- const connection = await installation.saveConnection(
83813
- {
83814
- appId: claim2.appId,
83815
- channelId: claim2.channelId,
83816
- defaultWorkspace,
83817
- pairingId: options.pairingId,
83818
- relayOrigin: options.relayOrigin,
83819
- runtimeCredential: claim2.runtimeCredential,
83820
- runtimeId: claim2.runtimeId
83821
- },
83822
- signal
83823
- );
83824
- return buildPairedRuntime(installation, connection, defaultWorkspace, inventory, localContext);
83825
- }
83826
- async function pairMobiusRuntime(installation, options, signal, environment = process.env) {
83827
- return await pairRuntime(
83828
- installation,
83829
- {
83830
- code: parsePairingCode(options.pairingCode),
83831
- pairingId: validatePairingId(options.pairingId),
83832
- relayOrigin: parseRelayOrigin2(options.relayOrigin),
83833
- workspace: options.defaultWorkspace
83834
- },
83835
- signal,
83836
- environment
83837
- );
83838
- }
83839
- async function resumeRuntimeConnection(installation, connection, signal, environment) {
83840
- const localContext = new RuntimeLocalContext(installation.stateDirectory, environment);
83841
- const defaultWorkspace = await resolveDefaultWorkspace(connection.defaultWorkspace);
83842
- const inventory = await discoverLocalAgentInventory({
83843
- defaultWorkspace,
83844
- dataDirectory: localContext.stateDirectory,
83845
- environment: localContext.environment,
83846
- signal
83847
- });
83848
- return buildPairedRuntime(installation, connection, defaultWorkspace, inventory, localContext);
83849
- }
83850
- async function resumeMobiusRuntime(installation, connectionId2, signal, environment = process.env) {
83851
- const connection = await installation.readConnection(connectionId2, signal);
83852
- return await resumeRuntimeConnection(installation, connection, signal, environment);
83853
- }
83611
+ // src/storage/state-root-layout.ts
83612
+ var STATE_ROOT_LAYOUT = Object.freeze({
83613
+ /** Names the version whose data is current. */
83614
+ currentData: "current-data.txt",
83615
+ /** Applications' installations: `installations/<application>/<installation>`. */
83616
+ installations: "installations",
83617
+ /** Managed CLI releases: `npm/<version>`. */
83618
+ releases: "npm",
83619
+ /** Each CLI version's data: `versions/<version>`. */
83620
+ versions: "versions"
83621
+ });
83622
+ var STATE_ROOT_ENTRY_NAMES = new Set(Object.values(STATE_ROOT_LAYOUT));
83623
+
83624
+ // src/storage/state-directory.ts
83625
+ var stateRootSchema = external_exports.string().brand();
83854
83626
 
83855
83627
  // src/engine/runtime/run.ts
83856
83628
  import { styleText } from "node:util";
@@ -87273,6 +87045,32 @@ var ExecutionReceipts = class {
87273
87045
  const receipt = this.#executions.get(commandId);
87274
87046
  return receipt?.outcome === null || receipt === void 0 ? void 0 : decodeKnownSessionEventPayload(JSON.parse(receipt.outcome)) ?? void 0;
87275
87047
  };
87048
+ /** The command's delivery as these receipts know it; another Session's command reads as unknown. */
87049
+ delivery = (commandId, sessionId) => {
87050
+ const receipt = this.#executions.get(commandId);
87051
+ if (receipt === void 0) {
87052
+ return this.#table.identity(commandId)?.sessionId === sessionId ? { state: "expired" } : { state: "unknown" };
87053
+ }
87054
+ if (receipt.sessionId !== sessionId) {
87055
+ return { state: "unknown" };
87056
+ }
87057
+ if (receipt.outcome === null) {
87058
+ return { state: "accepted" };
87059
+ }
87060
+ const outcome = this.outcome(commandId);
87061
+ if (outcome?.type !== "lifecycle-metadata") {
87062
+ return { state: "expired" };
87063
+ }
87064
+ switch (outcome.payload.kind) {
87065
+ case "prompt.completed":
87066
+ return { state: "completed", stopReason: outcome.payload.stopReason };
87067
+ case "prompt.failed":
87068
+ case "prompt.failed-before-start":
87069
+ return { code: outcome.payload.code, state: "failed" };
87070
+ default:
87071
+ return { state: "expired" };
87072
+ }
87073
+ };
87276
87074
  /** Reserves an unseen command for cancellation before a delayed prompt can claim its identity. */
87277
87075
  recordCancellationBeforeAdmission = (commandId, sessionId) => {
87278
87076
  const existing = this.#executions.get(commandId);
@@ -87450,8 +87248,8 @@ var RuntimeTurnActivity = class {
87450
87248
  #changed() {
87451
87249
  this.#changedAt = Date.now();
87452
87250
  if (this.count() === 0) {
87453
- for (const resolve18 of this.#idleWaiters) {
87454
- resolve18();
87251
+ for (const resolve17 of this.#idleWaiters) {
87252
+ resolve17();
87455
87253
  }
87456
87254
  this.#idleWaiters.clear();
87457
87255
  }
@@ -87461,14 +87259,14 @@ var RuntimeTurnActivity = class {
87461
87259
  if (this.count() === 0) {
87462
87260
  return Promise.resolve();
87463
87261
  }
87464
- return new Promise((resolve18, reject2) => {
87262
+ return new Promise((resolve17, reject2) => {
87465
87263
  const abort = () => {
87466
87264
  this.#idleWaiters.delete(idle);
87467
87265
  reject2(signal.reason);
87468
87266
  };
87469
87267
  const idle = () => {
87470
87268
  signal.removeEventListener("abort", abort);
87471
- resolve18();
87269
+ resolve17();
87472
87270
  };
87473
87271
  this.#idleWaiters.add(idle);
87474
87272
  signal.addEventListener("abort", abort, { once: true });
@@ -87598,7 +87396,7 @@ var ActiveRuntimeTurn = class {
87598
87396
  // src/engine/session/turn/session-execution.ts
87599
87397
  var waitForTurnCompletion = (turn, waitSignal) => {
87600
87398
  waitSignal.throwIfAborted();
87601
- return new Promise((resolve18, reject2) => {
87399
+ return new Promise((resolve17, reject2) => {
87602
87400
  let settled = false;
87603
87401
  const finish = (result) => {
87604
87402
  if (settled) {
@@ -87607,7 +87405,7 @@ var waitForTurnCompletion = (turn, waitSignal) => {
87607
87405
  settled = true;
87608
87406
  waitSignal.removeEventListener("abort", onAbort);
87609
87407
  if (result.kind === "completed") {
87610
- resolve18();
87408
+ resolve17();
87611
87409
  } else {
87612
87410
  reject2(result.error);
87613
87411
  }
@@ -87789,8 +87587,8 @@ var SessionTurns = class {
87789
87587
  };
87790
87588
 
87791
87589
  // src/engine/session/workspace/workspace-directory.ts
87792
- import { homedir as homedir4 } from "node:os";
87793
- import { basename as basename7, dirname as dirname10, isAbsolute as isAbsolute15, join as join27, normalize as normalize2, relative as relative2 } from "node:path";
87590
+ import { homedir as homedir3 } from "node:os";
87591
+ import { basename as basename6, dirname as dirname10, isAbsolute as isAbsolute15, join as join24, normalize as normalize2, relative as relative2 } from "node:path";
87794
87592
  var WorkspaceDirectoryListing = class {
87795
87593
  directoryId;
87796
87594
  directoryLabel;
@@ -87811,7 +87609,7 @@ function encodePath(path7) {
87811
87609
  return `path-${encoded}`;
87812
87610
  }
87813
87611
  function expandCurrentUserHome(path7) {
87814
- return path7.replace(/^~(?=$|\/|\\)/, homedir4());
87612
+ return path7.replace(/^~(?=$|\/|\\)/, homedir3());
87815
87613
  }
87816
87614
  function decodePath(value, prefix) {
87817
87615
  const encoded = value.slice(prefix.length);
@@ -87842,7 +87640,7 @@ var WorkspaceDirectoryService = class {
87842
87640
  return this.#defaultWorkspace;
87843
87641
  }
87844
87642
  if (id === "home") {
87845
- return homedir4();
87643
+ return homedir3();
87846
87644
  }
87847
87645
  if (id.startsWith("path-")) {
87848
87646
  const path7 = expandCurrentUserHome(decodePath(id, "path-"));
@@ -87877,7 +87675,7 @@ var WorkspaceDirectoryService = class {
87877
87675
  }
87878
87676
  };
87879
87677
  label = (path7) => {
87880
- const suffix = relative2(homedir4(), path7);
87678
+ const suffix = relative2(homedir3(), path7);
87881
87679
  return suffix === "" ? "~" : !isAbsolute15(suffix) && suffix !== ".." && !suffix.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ? `~/${suffix.replaceAll("\\", "/")}` : path7;
87882
87680
  };
87883
87681
  identify = async (bindingId, requestedPath2, signal) => {
@@ -87886,7 +87684,7 @@ var WorkspaceDirectoryService = class {
87886
87684
  return {
87887
87685
  path: path7,
87888
87686
  directoryId: encodePath(path7),
87889
- name: basename7(path7) || path7,
87687
+ name: basename6(path7) || path7,
87890
87688
  label: this.label(path7)
87891
87689
  };
87892
87690
  };
@@ -87912,7 +87710,7 @@ var WorkspaceDirectoryService = class {
87912
87710
  continue;
87913
87711
  }
87914
87712
  try {
87915
- const path7 = await this.resolvePath(join27(target, child.name), signal);
87713
+ const path7 = await this.resolvePath(join24(target, child.name), signal);
87916
87714
  entries.push({ directoryId: encodePath(path7), name: child.name });
87917
87715
  } catch (cause) {
87918
87716
  signal.throwIfAborted();
@@ -88026,20 +87824,23 @@ function buildSessionLayer(options) {
88026
87824
  resolveAgent,
88027
87825
  directories,
88028
87826
  manager,
88029
- async (request, requestOptions) => await activeSessions.executionSnapshot(async (command) => {
88030
- if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
88031
- return false;
88032
- }
88033
- const cwd = await directories.resolve(command.bindingId, command.directoryId, requestOptions.signal);
88034
- const additionalDirectories = await directories.resolveMany(
88035
- command.bindingId,
88036
- command.additionalDirectoryIds,
88037
- requestOptions.signal
88038
- );
88039
- return cwd === requestOptions.cwd && additionalDirectories.length === requestOptions.additionalDirectories.length && additionalDirectories.every(
88040
- (directory, index2) => directory === requestOptions.additionalDirectories[index2]
88041
- );
88042
- })
87827
+ async (request, requestOptions) => {
87828
+ const snapshot = await activeSessions.executionSnapshot(async (command) => {
87829
+ if (command.sessionId !== request.targetSessionId || command.agentId !== request.agentId) {
87830
+ return false;
87831
+ }
87832
+ const cwd = await directories.resolve(command.bindingId, command.directoryId, requestOptions.signal);
87833
+ const additionalDirectories = await directories.resolveMany(
87834
+ command.bindingId,
87835
+ command.additionalDirectoryIds,
87836
+ requestOptions.signal
87837
+ );
87838
+ return cwd === requestOptions.cwd && additionalDirectories.length === requestOptions.additionalDirectories.length && additionalDirectories.every(
87839
+ (directory, index2) => directory === requestOptions.additionalDirectories[index2]
87840
+ );
87841
+ });
87842
+ return request.deliveryCommandId === void 0 ? snapshot : { ...snapshot, command: operations.delivery(request.deliveryCommandId, request.targetSessionId) };
87843
+ }
88043
87844
  );
88044
87845
  const recoveredEvents = operations.recover().map(({ sessionId, event, recordedAt }) => events.append(sessionId, event, recordedAt));
88045
87846
  return {
@@ -88060,12 +87861,12 @@ function buildSessionLayer(options) {
88060
87861
 
88061
87862
  // src/engine/session/content/external-content-store.ts
88062
87863
  import { createHash as createHash7 } from "node:crypto";
88063
- import { join as join29 } from "node:path";
87864
+ import { join as join26 } from "node:path";
88064
87865
 
88065
87866
  // src/engine/storage/files/scratch-directory.ts
88066
87867
  import { randomUUID as randomUUID17 } from "node:crypto";
88067
87868
  import { lstat as lstat4, mkdir as mkdir5, readdir as readdir6, readFile as readFile6, realpath as realpath7, rename as rename4, rm as rm3, stat as stat6, utimes, writeFile as writeFile2 } from "node:fs/promises";
88068
- import { dirname as dirname11, join as join28 } from "node:path";
87869
+ import { dirname as dirname11, join as join25 } from "node:path";
88069
87870
  async function atomicWrite(path7, bytes, signal) {
88070
87871
  const temporary = `${path7}.${randomUUID17()}.tmp`;
88071
87872
  try {
@@ -88079,7 +87880,7 @@ async function atomicWrite(path7, bytes, signal) {
88079
87880
  var ScratchDirectory = class {
88080
87881
  #root;
88081
87882
  constructor(parent) {
88082
- this.#root = join28(parent, randomUUID17());
87883
+ this.#root = join25(parent, randomUUID17());
88083
87884
  }
88084
87885
  /** Refreshes this directory's lease and removes sibling directories whose lease is older than `leaseMilliseconds`. */
88085
87886
  refreshLease = async (leaseMilliseconds) => {
@@ -88090,7 +87891,7 @@ var ScratchDirectory = class {
88090
87891
  if (!directory.isDirectory() || !/^[a-f0-9-]{36}$/u.test(directory.name)) {
88091
87892
  continue;
88092
87893
  }
88093
- const path7 = join28(dirname11(this.#root), directory.name);
87894
+ const path7 = join25(dirname11(this.#root), directory.name);
88094
87895
  if (path7 === this.#root) {
88095
87896
  continue;
88096
87897
  }
@@ -88105,10 +87906,10 @@ var ScratchDirectory = class {
88105
87906
  };
88106
87907
  /** Writes `bytes` atomically to `<group>/<name>` with owner-only permissions and returns the path. */
88107
87908
  write = async (group, name2, bytes, signal) => {
88108
- const directory = join28(this.#root, group);
87909
+ const directory = join25(this.#root, group);
88109
87910
  await mkdir5(directory, { mode: 448, recursive: true });
88110
87911
  signal.throwIfAborted();
88111
- const path7 = join28(directory, name2);
87912
+ const path7 = join25(directory, name2);
88112
87913
  await atomicWrite(path7, bytes, signal);
88113
87914
  return path7;
88114
87915
  };
@@ -88155,7 +87956,7 @@ var LocalExternalContentStore = class {
88155
87956
  #expirationTimer;
88156
87957
  #cleanup = Promise.resolve();
88157
87958
  constructor(stateDirectory) {
88158
- this.#scratch = new ScratchDirectory(join29(stateDirectory, "tmp", "session-content"));
87959
+ this.#scratch = new ScratchDirectory(join26(stateDirectory, "tmp", "session-content"));
88159
87960
  this.#expirationTimer = setInterval(() => {
88160
87961
  void this.#expire().catch(() => void 0);
88161
87962
  }, 6e4);
@@ -88353,18 +88154,6 @@ async function waitForAcpProcessCapacity(completion, signal) {
88353
88154
  var DEFAULT_MAX_ACP_PROCESSES = 1e3;
88354
88155
  var MAX_CONCURRENT_STARTS = 8;
88355
88156
  var ACP_PROCESS_IDLE_TIMEOUT_MILLISECONDS = 2 * 60 * 60 * 1e3;
88356
- var MAX_ACP_PROCESSES_ENVIRONMENT_KEY = "MOBIUS_MAX_ACP_PROCESSES";
88357
- function resolveMaxAcpProcesses(environment) {
88358
- const configured = environment[MAX_ACP_PROCESSES_ENVIRONMENT_KEY];
88359
- if (configured === void 0 || configured === "") {
88360
- return DEFAULT_MAX_ACP_PROCESSES;
88361
- }
88362
- const parsed = Number(configured);
88363
- if (!Number.isInteger(parsed) || parsed < 1) {
88364
- throw new Error(`${MAX_ACP_PROCESSES_ENVIRONMENT_KEY} must be a positive integer`);
88365
- }
88366
- return parsed;
88367
- }
88368
88157
  var AgentProcessPool = class {
88369
88158
  #maxProcesses;
88370
88159
  #timer;
@@ -88538,11 +88327,11 @@ var AgentProcessPool = class {
88538
88327
  };
88539
88328
 
88540
88329
  // src/engine/runtime/observability/diagnostic-log.ts
88541
- import { join as join32 } from "node:path";
88330
+ import { join as join29 } from "node:path";
88542
88331
 
88543
88332
  // src/engine/storage/logs/bounded-log.ts
88544
88333
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync4, readFileSync as readFileSync9, renameSync as renameSync2, statSync as statSync5, writeFileSync as writeFileSync2 } from "node:fs";
88545
- import { join as join30 } from "node:path";
88334
+ import { join as join27 } from "node:path";
88546
88335
  var BoundedLineLog = class {
88547
88336
  #path;
88548
88337
  #maximumBytes;
@@ -88551,7 +88340,7 @@ var BoundedLineLog = class {
88551
88340
  #onWriteFailure;
88552
88341
  constructor(directory, filename, maximumBytes, onWriteFailure = () => void 0) {
88553
88342
  this.#directory = directory;
88554
- this.#path = join30(directory, filename);
88343
+ this.#path = join27(directory, filename);
88555
88344
  this.#maximumBytes = maximumBytes;
88556
88345
  this.#onWriteFailure = onWriteFailure;
88557
88346
  }
@@ -88602,21 +88391,21 @@ var BoundedLineLog = class {
88602
88391
 
88603
88392
  // src/engine/storage/logs/log-files.ts
88604
88393
  import { readFileSync as readFileSync10 } from "node:fs";
88605
- import { join as join31, relative as relative3 } from "node:path";
88394
+ import { join as join28 } from "node:path";
88606
88395
  var DAEMON_LOG_FILENAME = "daemon.log";
88607
88396
  var WORKER_LIFECYCLE_LOG_FILENAME = "worker-lifecycle.log";
88608
88397
  function unhandledRejectionLogFilename(role) {
88609
88398
  return `unhandled-rejections-${role}.log`;
88610
88399
  }
88611
- function logDirectory(stateDirectory) {
88612
- return join31(stateDirectory, "logs");
88400
+ function logDirectory(dataDirectory) {
88401
+ return join28(dataDirectory, "logs");
88613
88402
  }
88614
- function processLogPaths(stateDirectory) {
88403
+ function processLogPaths(dataDirectory) {
88615
88404
  return [
88616
88405
  WORKER_LIFECYCLE_LOG_FILENAME,
88617
88406
  unhandledRejectionLogFilename("manager"),
88618
88407
  unhandledRejectionLogFilename("worker")
88619
- ].map((filename) => join31(logDirectory(stateDirectory), filename));
88408
+ ].map((filename) => join28(logDirectory(dataDirectory), filename));
88620
88409
  }
88621
88410
  function readLogText(path7) {
88622
88411
  try {
@@ -88672,7 +88461,7 @@ var RuntimeDiagnosticLog = class {
88672
88461
  this.#maximumBytes = maximumBytes;
88673
88462
  const processLogsDirectory = options.processLogsDirectory;
88674
88463
  this.#sources = [
88675
- { maximumBytes, path: join32(directory, DAEMON_LOG_FILENAME) },
88464
+ { maximumBytes, path: join29(directory, DAEMON_LOG_FILENAME) },
88676
88465
  // The process logs a Runtime does not own, but must read to explain its own deaths.
88677
88466
  ...processLogsDirectory === void 0 ? [] : processLogPaths(processLogsDirectory).map((path7) => ({ maximumBytes: null, path: path7 }))
88678
88467
  ];
@@ -88785,6 +88574,8 @@ function addFailureDetails(details, failure2) {
88785
88574
  }
88786
88575
  }
88787
88576
  var RelayConnectionDiagnostics = class {
88577
+ #lastSkippedLogAt = Number.NEGATIVE_INFINITY;
88578
+ #skippedCount = 0;
88788
88579
  #channelId;
88789
88580
  #localLog;
88790
88581
  #lastClosedEpoch = 0;
@@ -88859,6 +88650,16 @@ var RelayConnectionDiagnostics = class {
88859
88650
  );
88860
88651
  };
88861
88652
  daemonDiagnostic = (event, requestId, details, failure2) => {
88653
+ if (event === "protocol_message_discarded" || event === "content_frame_discarded" || event === "content_chunk_discarded" || event === "prompt_attachments_skipped") {
88654
+ this.#skippedCount += 1;
88655
+ const now = Date.now();
88656
+ if (now - this.#lastSkippedLogAt < 6e4) {
88657
+ return;
88658
+ }
88659
+ details = { ...details, skippedCount: this.#skippedCount.toString() };
88660
+ this.#lastSkippedLogAt = now;
88661
+ this.#skippedCount = 0;
88662
+ }
88862
88663
  const recordedDetails = { ...details };
88863
88664
  if (failure2 !== void 0) {
88864
88665
  addFailureDetails(recordedDetails, failure2);
@@ -88930,7 +88731,7 @@ async function refreshAgentCatalog(config2, discover, signal) {
88930
88731
  const readyAgents = await discover(signal);
88931
88732
  signal.throwIfAborted();
88932
88733
  return await config2.catalog.replaceAndPublish(
88933
- () => readyAgents.map((agent) => withRuntimeEnvironment(agent, config2.localContext.environment)),
88734
+ () => readyAgents.map((agent) => withRuntimeEnvironment(agent, config2.localContext.agentLaunchEnvironment)),
88934
88735
  (publishSignal) => publishAgentCatalog(config2, publishSignal),
88935
88736
  signal
88936
88737
  );
@@ -89655,7 +89456,7 @@ function createContentWriteCommands(context) {
89655
89456
  import { WebSocket as WebSocket5 } from "undici";
89656
89457
 
89657
89458
  // src/engine/session/content/session-files.ts
89658
- import { basename as basename8, extname as extname3, isAbsolute as isAbsolute16, join as join33, normalize as normalize3, resolve as resolve17 } from "node:path";
89459
+ import { basename as basename7, extname as extname3, isAbsolute as isAbsolute16, join as join30, normalize as normalize3, resolve as resolve15 } from "node:path";
89659
89460
  import { fileURLToPath as fileURLToPath2 } from "node:url";
89660
89461
  function requestedPath(value) {
89661
89462
  if (value.includes("\0")) {
@@ -89679,7 +89480,7 @@ async function resolveFile(value, workingDirectory, signal) {
89679
89480
  if (isAbsolute16(requested.path) && normalize3(requested.path) !== requested.path) {
89680
89481
  return null;
89681
89482
  }
89682
- const candidates = requested.explicitUrl || workingDirectory === null ? [requested.path] : isAbsolute16(requested.path) ? [join33(workingDirectory, requested.path), requested.path] : [resolve17(workingDirectory, requested.path)];
89483
+ const candidates = requested.explicitUrl || workingDirectory === null ? [requested.path] : isAbsolute16(requested.path) ? [join30(workingDirectory, requested.path), requested.path] : [resolve15(workingDirectory, requested.path)];
89683
89484
  for (const candidate of candidates) {
89684
89485
  if (!isAbsolute16(candidate) || normalize3(candidate) !== candidate) {
89685
89486
  continue;
@@ -89713,7 +89514,7 @@ async function streamLocalFile(command, send2, sendChunk, signal, workingDirecto
89713
89514
  kind: FILE_BEGIN_KIND,
89714
89515
  mediaType: external?.mediaType ?? raster?.mimeType ?? (extname3(target).toLowerCase() === ".svg" ? "image/svg+xml" : "application/octet-stream"),
89715
89516
  modifiedAt: before.modifiedAt.toISOString(),
89716
- name: external?.name ?? (basename8(target) || "file"),
89517
+ name: external?.name ?? (basename7(target) || "file"),
89717
89518
  requestId: command.requestId,
89718
89519
  sessionId: command.sessionId
89719
89520
  });
@@ -89764,7 +89565,7 @@ var fileReadCommand = {
89764
89565
  };
89765
89566
 
89766
89567
  // src/engine/session/workspace/resolve-session-directories.ts
89767
- import { basename as basename9 } from "node:path";
89568
+ import { basename as basename8 } from "node:path";
89768
89569
  var ResolvedSessionDirectories = class {
89769
89570
  additionalDirectories;
89770
89571
  additionalDirectoryEntries;
@@ -89792,7 +89593,7 @@ async function resolveSessionDirectories(directories, bindingId, directoryId, ad
89792
89593
  additionalDirectories.push(directory);
89793
89594
  additionalDirectoryEntries.push({
89794
89595
  directoryId: additionalDirectoryId,
89795
- name: basename9(directory)
89596
+ name: basename8(directory)
89796
89597
  });
89797
89598
  }
89798
89599
  return new ResolvedSessionDirectories(cwd, selection.label, additionalDirectories, additionalDirectoryEntries);
@@ -90134,13 +89935,13 @@ function createNativeSessionRequestHandler(dependencies) {
90134
89935
  operationSignal.throwIfAborted();
90135
89936
  const skipPrevious = command.action === "active-turn";
90136
89937
  if (previous.length > 0 && !skipPrevious) {
90137
- await new Promise((resolve18, reject2) => {
89938
+ await new Promise((resolve17, reject2) => {
90138
89939
  const onAbort = () => reject2(operationSignal.reason);
90139
89940
  operationSignal.addEventListener("abort", onAbort, { once: true });
90140
89941
  void Promise.all(previous.map((request) => request.completion)).then(
90141
89942
  () => {
90142
89943
  operationSignal.removeEventListener("abort", onAbort);
90143
- resolve18();
89944
+ resolve17();
90144
89945
  },
90145
89946
  (error62) => {
90146
89947
  operationSignal.removeEventListener("abort", onAbort);
@@ -90459,10 +90260,7 @@ async function resolvePromptArtifacts(read, attachments, signal) {
90459
90260
  }
90460
90261
  if (attachment.kind === "image") {
90461
90262
  if (bytes.byteLength > PROMPT_IMAGE_MAX_BYTES || images.length >= 8) {
90462
- throw new PromptArtifactError(
90463
- "artifact_too_large_for_agent",
90464
- "The prompt attachment exceeds the Agent image limit"
90465
- );
90263
+ continue;
90466
90264
  }
90467
90265
  images.push({
90468
90266
  data: Buffer.from(bytes).toString("base64"),
@@ -90472,28 +90270,17 @@ async function resolvePromptArtifacts(read, attachments, signal) {
90472
90270
  continue;
90473
90271
  }
90474
90272
  if (!isTextMediaType(attachment.mimeType)) {
90475
- throw new PromptArtifactError(
90476
- "artifact_media_type_unsupported",
90477
- "The Agent cannot consume this prompt attachment media type"
90478
- );
90273
+ continue;
90479
90274
  }
90480
90275
  if (bytes.byteLength > MAX_AGENT_RESOURCE_BYTE_LENGTH || resources.length >= 16) {
90481
- throw new PromptArtifactError(
90482
- "artifact_too_large_for_agent",
90483
- "The prompt attachment exceeds the Agent resource limit"
90484
- );
90276
+ continue;
90485
90277
  }
90486
90278
  let text2;
90487
90279
  try {
90488
90280
  text2 = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
90489
- } catch (cause) {
90490
- throw new PromptArtifactError(
90491
- "artifact_encoding_invalid",
90492
- "The prompt attachment is not valid UTF-8 text",
90493
- {
90494
- cause
90495
- }
90496
- );
90281
+ } catch {
90282
+ signal.throwIfAborted();
90283
+ continue;
90497
90284
  }
90498
90285
  resources.push({ mimeType: attachment.mimeType, text: text2, type: "embedded", uri: attachment.uri });
90499
90286
  }
@@ -90585,6 +90372,13 @@ async function executePrompt({
90585
90372
  availability.disposition
90586
90373
  );
90587
90374
  const attachments = await resolvePromptArtifacts(readArtifact, command.attachments, signal);
90375
+ const skipped = command.attachments.length - attachments.images.length - attachments.resources.length;
90376
+ if (skipped > 0) {
90377
+ reportFailure("prompt_attachments_skipped", command.commandId, { count: skipped.toString() });
90378
+ }
90379
+ if (command.prompt.trim().length === 0 && attachments.images.length === 0 && attachments.resources.length === 0) {
90380
+ throw new PromptArtifactError("prompt_attachments_unsupported", "No supported prompt content remains");
90381
+ }
90588
90382
  let stopReason;
90589
90383
  if (availability.disposition === SessionPromptDisposition.Steer) {
90590
90384
  await sessions.steerPrompt({
@@ -91184,7 +90978,21 @@ function createCommandRegistry(context) {
91184
90978
  }
91185
90979
  command.handle(context, message);
91186
90980
  },
91187
- dispatchChunk: (message) => contentWrites.receiveChunk(decodeContentChunkFrame(message)),
90981
+ dispatchChunk: (message) => {
90982
+ const frame = (() => {
90983
+ try {
90984
+ return decodeContentChunkFrame(message);
90985
+ } catch {
90986
+ context.diagnostics.daemonDiagnostic("content_frame_discarded", "unknown", {
90987
+ reason: "unsupported_frame"
90988
+ });
90989
+ return null;
90990
+ }
90991
+ })();
90992
+ if (frame !== null) {
90993
+ contentWrites.receiveChunk(frame);
90994
+ }
90995
+ },
91188
90996
  settle: async () => {
91189
90997
  await Promise.all([
91190
90998
  contentWrites.settle(),
@@ -91234,7 +91042,7 @@ var RelayConnectionError = class extends Error {
91234
91042
  };
91235
91043
  function connectRelay(url2, signal) {
91236
91044
  signal.throwIfAborted();
91237
- return new Promise((resolve18, reject2) => {
91045
+ return new Promise((resolve17, reject2) => {
91238
91046
  let dispatchController;
91239
91047
  const dispatcher = environmentProxyDispatcher.compose((dispatch) => (options, handler) => {
91240
91048
  const trackedHandler = Object.create(handler);
@@ -91320,7 +91128,7 @@ function connectRelay(url2, signal) {
91320
91128
  }
91321
91129
  finished = true;
91322
91130
  cleanup();
91323
- resolve18({ release, socket });
91131
+ resolve17({ release, socket });
91324
91132
  };
91325
91133
  function onTimeout() {
91326
91134
  fail(
@@ -91496,7 +91304,7 @@ async function runRelayConnection({
91496
91304
  }
91497
91305
  });
91498
91306
  try {
91499
- await new Promise((resolve18, reject2) => {
91307
+ await new Promise((resolve17, reject2) => {
91500
91308
  let finished = false;
91501
91309
  let ready = false;
91502
91310
  const cleanup = () => {
@@ -91514,7 +91322,7 @@ async function runRelayConnection({
91514
91322
  }
91515
91323
  finished = true;
91516
91324
  cleanup();
91517
- resolve18();
91325
+ resolve17();
91518
91326
  };
91519
91327
  const rejectConnection = (failure2) => {
91520
91328
  if (finished) {
@@ -91601,6 +91409,9 @@ async function runRelayConnection({
91601
91409
  try {
91602
91410
  const message = decodeKnownServiceToDaemonMessage(encoded);
91603
91411
  if (message === null) {
91412
+ diagnostics.daemonDiagnostic("protocol_message_discarded", "unknown", {
91413
+ reason: "unsupported_message"
91414
+ });
91604
91415
  return;
91605
91416
  }
91606
91417
  const kind = message.kind;
@@ -91823,12 +91634,12 @@ function waitForRelayRetry(signal, timer) {
91823
91634
  if (signal.aborted) {
91824
91635
  return Promise.resolve();
91825
91636
  }
91826
- return new Promise((resolve18) => {
91637
+ return new Promise((resolve17) => {
91827
91638
  const retry = timer.schedule(finish, RELAY_RECONNECT_DELAY_MILLISECONDS);
91828
91639
  function finish() {
91829
91640
  retry.cancel();
91830
91641
  signal.removeEventListener("abort", finish);
91831
- resolve18();
91642
+ resolve17();
91832
91643
  }
91833
91644
  signal.addEventListener("abort", finish, { once: true });
91834
91645
  });
@@ -91871,7 +91682,7 @@ async function runRuntime(config2, parentSignal, timer = systemTimer, options =
91871
91682
  );
91872
91683
  const publisher = new RuntimeSessionEventPublisher(timer);
91873
91684
  const externalContent = __using(_stack, new LocalExternalContentStore(stateDirectory), true);
91874
- const processes = new AgentProcessPool(resolveMaxAcpProcesses(config2.localContext.environment) ?? void 0, timer);
91685
+ const processes = new AgentProcessPool(config2.localContext.maxAcpProcesses, timer);
91875
91686
  const adapters = createRuntimeAdapterRegistry(
91876
91687
  config2.adapters,
91877
91688
  processes,
@@ -92073,6 +91884,261 @@ var MobiusRuntimeEngine = class {
92073
91884
  }
92074
91885
  };
92075
91886
  };
91887
+
91888
+ // src/daemon/config.ts
91889
+ function resolveMaxAcpProcesses(environment) {
91890
+ const configured = environment["MOBIUS_MAX_ACP_PROCESSES"];
91891
+ if (configured === void 0 || configured === "") {
91892
+ return 1e3;
91893
+ }
91894
+ const parsed = Number(configured);
91895
+ if (!Number.isInteger(parsed) || parsed < 1) {
91896
+ throw new Error("MOBIUS_MAX_ACP_PROCESSES must be a positive integer");
91897
+ }
91898
+ return parsed;
91899
+ }
91900
+
91901
+ // src/daemon/pairing/pair-local-machine.ts
91902
+ var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
91903
+ var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
91904
+ var TOKEN_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
91905
+ var CLAIM_RESPONSE_KEYS = ["appId", "channelId", "daemonToken", "runtimeId"];
91906
+ var REDEEM_RESPONSE_KEYS = ["appId", "channelId", "runtimeCredential", "runtimeId"];
91907
+ var PairingClientError = class extends Error {
91908
+ code;
91909
+ constructor(code, message, options = {}) {
91910
+ super(message, options);
91911
+ this.code = code;
91912
+ this.name = "PairingClientError";
91913
+ }
91914
+ };
91915
+ function hasExactKeys2(value, expectedKeys) {
91916
+ const keys = Object.keys(value);
91917
+ return keys.length === expectedKeys.length && expectedKeys.every((key) => Object.hasOwn(value, key));
91918
+ }
91919
+ function parseRelayOrigin2(value) {
91920
+ let url2;
91921
+ try {
91922
+ url2 = new URL(value);
91923
+ } catch (error62) {
91924
+ throw new PairingClientError("invalid_relay_url", "The relay URL is invalid", { cause: error62 });
91925
+ }
91926
+ if (url2.protocol !== "https:" && url2.protocol !== "http:") {
91927
+ throw new PairingClientError("invalid_relay_url", "The relay URL must use http or https");
91928
+ }
91929
+ if (url2.username.length > 0 || url2.password.length > 0) {
91930
+ throw new PairingClientError("invalid_relay_url", "The relay URL cannot contain credentials");
91931
+ }
91932
+ if (url2.protocol === "http:" && url2.hostname !== "127.0.0.1" && url2.hostname !== "localhost") {
91933
+ throw new PairingClientError("invalid_relay_url", "A remote relay must use https");
91934
+ }
91935
+ url2.hash = "";
91936
+ url2.pathname = "/";
91937
+ url2.search = "";
91938
+ return url2;
91939
+ }
91940
+ function parsePairingCode(value) {
91941
+ const code = value.trim().toUpperCase();
91942
+ if (!PAIRING_CODE_PATTERN.test(code)) {
91943
+ throw new PairingClientError(
91944
+ "invalid_pairing_code",
91945
+ "The pairing code must match the code shown in the browser"
91946
+ );
91947
+ }
91948
+ return code;
91949
+ }
91950
+ function validatePairingId(value) {
91951
+ if (!isIdentifier(value)) {
91952
+ throw new PairingClientError("invalid_pairing_id", "The Runtime pairing ID is invalid");
91953
+ }
91954
+ return value;
91955
+ }
91956
+ async function resolveDefaultWorkspace(path7) {
91957
+ const requestedWorkspace = resolve16(path7);
91958
+ let defaultWorkspace;
91959
+ try {
91960
+ defaultWorkspace = await ensureCanonicalDirectory(requestedWorkspace);
91961
+ } catch (error62) {
91962
+ throw new PairingClientError("invalid_workspace", "The default workspace cannot be resolved", { cause: error62 });
91963
+ }
91964
+ if (defaultWorkspace === null) {
91965
+ throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
91966
+ }
91967
+ return defaultWorkspace;
91968
+ }
91969
+ async function readJsonResponse(response) {
91970
+ if (response.headers.get("cf-mitigated") === "challenge") {
91971
+ throw new PairingClientError(
91972
+ "relay_challenge",
91973
+ "Cloudflare is protecting this temporary preview. Claim the deployment or use an authenticated deployment, then pair again"
91974
+ );
91975
+ }
91976
+ const encoded = await response.text();
91977
+ try {
91978
+ return JSON.parse(encoded);
91979
+ } catch (error62) {
91980
+ throw new PairingClientError("invalid_relay_response", "The relay returned an invalid response", {
91981
+ cause: error62
91982
+ });
91983
+ }
91984
+ }
91985
+ function readRelayError(value) {
91986
+ if (isRecord3(value)) {
91987
+ const error62 = value["error"];
91988
+ if (isRecord3(error62)) {
91989
+ const code = error62["code"];
91990
+ const message = error62["message"];
91991
+ if (typeof code === "string" && typeof message === "string") {
91992
+ return new PairingClientError(code, message);
91993
+ }
91994
+ }
91995
+ }
91996
+ return new PairingClientError("pairing_failed", "The relay could not pair this machine");
91997
+ }
91998
+ function decodePairingResponse(value, credentialField, expectedKeys) {
91999
+ if (!isRecord3(value) || !hasExactKeys2(value, expectedKeys)) {
92000
+ throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
92001
+ }
92002
+ const appId = value["appId"];
92003
+ const channelId = value["channelId"];
92004
+ const runtimeCredential2 = value[credentialField];
92005
+ const runtimeId = value["runtimeId"];
92006
+ if (typeof appId !== "string" || !isIdentifier(appId) || typeof channelId !== "string" || !isIdentifier(channelId) || typeof runtimeCredential2 !== "string" || !TOKEN_PATTERN.test(runtimeCredential2) || typeof runtimeId !== "string" || !isIdentifier(runtimeId)) {
92007
+ throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
92008
+ }
92009
+ return { appId, channelId, runtimeCredential: runtimeCredential2, runtimeId };
92010
+ }
92011
+ async function claimPairing(options, defaultWorkspace, localAgents, signal) {
92012
+ const agents = localAgents.map((agent) => ({
92013
+ agentPath: agent.agentIdentity.requestedPath,
92014
+ agentVersion: agent.agentVersion,
92015
+ agentSettingsDiscovery: true,
92016
+ capabilities: agent.capabilities,
92017
+ id: agent.id,
92018
+ label: agent.label,
92019
+ sessionTurnConfiguration: true
92020
+ }));
92021
+ const endpoint = options.pairingId.length > 0 ? mobiusApiUrl(options.relayOrigin, `/v1/runtime-pairings/${encodeURIComponent(options.pairingId)}/redeem`) : mobiusApiUrl(options.relayOrigin, "/pairings/claim");
92022
+ let response;
92023
+ try {
92024
+ response = await fetch3(endpoint, {
92025
+ body: JSON.stringify({
92026
+ agents,
92027
+ machineName: hostname3(),
92028
+ pairingCode: options.code,
92029
+ workspaceName: basename9(defaultWorkspace) || "Local workspace"
92030
+ }),
92031
+ dispatcher: environmentProxyDispatcher,
92032
+ headers: { "content-type": "application/json" },
92033
+ method: "POST",
92034
+ signal: AbortSignal.any([signal, AbortSignal.timeout(PAIRING_TIMEOUT_MILLISECONDS)])
92035
+ });
92036
+ } catch (error62) {
92037
+ throw new PairingClientError("relay_unavailable", "The pairing relay could not be reached", { cause: error62 });
92038
+ }
92039
+ const value = await readJsonResponse(response);
92040
+ if (!response.ok) {
92041
+ throw readRelayError(value);
92042
+ }
92043
+ return options.pairingId.length > 0 ? decodePairingResponse(value, "runtimeCredential", REDEEM_RESPONSE_KEYS) : decodePairingResponse(value, "daemonToken", CLAIM_RESPONSE_KEYS);
92044
+ }
92045
+ function buildPairedRuntime(installation, connection, defaultWorkspace, inventory, localContext) {
92046
+ const relayUrl = mobiusApiUrl(connection.relayOrigin, "/v1/runtimes/connect");
92047
+ relayUrl.protocol = relayUrl.protocol === "https:" ? "wss:" : "ws:";
92048
+ relayUrl.searchParams.set("token", connection.runtimeCredential);
92049
+ const config2 = createRuntimeConfig(
92050
+ {
92051
+ defaultWorkspace,
92052
+ channelId: connection.channelId,
92053
+ relayUrl
92054
+ },
92055
+ new RuntimeAgentDependencies(inventory.readyAgents()),
92056
+ localContext,
92057
+ new OpaqueRuntimeReconnectTarget(connection.connectionId),
92058
+ createCatalogAgentResolver(
92059
+ (refreshSignal) => discoverLocalAgentInventory({
92060
+ defaultWorkspace,
92061
+ dataDirectory: localContext.stateDirectory,
92062
+ environment: localContext.agentLaunchEnvironment,
92063
+ signal: refreshSignal
92064
+ }),
92065
+ () => config2,
92066
+ publishAgentCatalog
92067
+ ),
92068
+ (refreshSignal) => discoverLocalAgentInventory({
92069
+ defaultWorkspace,
92070
+ dataDirectory: localContext.stateDirectory,
92071
+ environment: localContext.agentLaunchEnvironment,
92072
+ signal: refreshSignal
92073
+ }).then((inventory2) => inventory2.readyAgents())
92074
+ );
92075
+ return {
92076
+ channelUrl: new URL(`/channels/${encodeURIComponent(connection.channelId)}`, connection.relayOrigin).toString(),
92077
+ connectionId: connection.connectionId,
92078
+ config: config2,
92079
+ connectionPath: installation.connectionPath(connection.connectionId)
92080
+ };
92081
+ }
92082
+ async function pairRuntime(installation, options, signal, environment) {
92083
+ const localContext = new RuntimeLocalContext(
92084
+ installation.stateDirectory,
92085
+ environment,
92086
+ resolveMaxAcpProcesses(environment)
92087
+ );
92088
+ const defaultWorkspace = await resolveDefaultWorkspace(options.workspace);
92089
+ const inventory = await discoverLocalAgentInventory({
92090
+ defaultWorkspace,
92091
+ dataDirectory: localContext.stateDirectory,
92092
+ environment: localContext.agentLaunchEnvironment,
92093
+ signal
92094
+ });
92095
+ const claim2 = await claimPairing(options, defaultWorkspace, inventory.readyAgents(), signal);
92096
+ const connection = await installation.saveConnection(
92097
+ {
92098
+ appId: claim2.appId,
92099
+ channelId: claim2.channelId,
92100
+ defaultWorkspace,
92101
+ pairingId: options.pairingId,
92102
+ relayOrigin: options.relayOrigin,
92103
+ runtimeCredential: claim2.runtimeCredential,
92104
+ runtimeId: claim2.runtimeId
92105
+ },
92106
+ signal
92107
+ );
92108
+ return buildPairedRuntime(installation, connection, defaultWorkspace, inventory, localContext);
92109
+ }
92110
+ async function pairMobiusRuntime(installation, options, signal, environment = process.env) {
92111
+ return await pairRuntime(
92112
+ installation,
92113
+ {
92114
+ code: parsePairingCode(options.pairingCode),
92115
+ pairingId: validatePairingId(options.pairingId),
92116
+ relayOrigin: parseRelayOrigin2(options.relayOrigin),
92117
+ workspace: options.defaultWorkspace
92118
+ },
92119
+ signal,
92120
+ environment
92121
+ );
92122
+ }
92123
+ async function resumeRuntimeConnection(installation, connection, signal, environment) {
92124
+ const localContext = new RuntimeLocalContext(
92125
+ installation.stateDirectory,
92126
+ environment,
92127
+ resolveMaxAcpProcesses(environment)
92128
+ );
92129
+ const defaultWorkspace = await resolveDefaultWorkspace(connection.defaultWorkspace);
92130
+ const inventory = await discoverLocalAgentInventory({
92131
+ defaultWorkspace,
92132
+ dataDirectory: localContext.stateDirectory,
92133
+ environment: localContext.agentLaunchEnvironment,
92134
+ signal
92135
+ });
92136
+ return buildPairedRuntime(installation, connection, defaultWorkspace, inventory, localContext);
92137
+ }
92138
+ async function resumeMobiusRuntime(installation, connectionId2, signal, environment = process.env) {
92139
+ const connection = await installation.readConnection(connectionId2, signal);
92140
+ return await resumeRuntimeConnection(installation, connection, signal, environment);
92141
+ }
92076
92142
  export {
92077
92143
  MobiusRuntimeEngine,
92078
92144
  RuntimeRelayRevokedError,