@wezzard/mcp-relay 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -4633,7 +4633,7 @@ var require_core = __commonJS({
4633
4633
  errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
4634
4634
  if (!errors || errors.length === 0)
4635
4635
  return "No errors";
4636
- return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text4, msg) => text4 + separator + msg);
4636
+ return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text5, msg) => text5 + separator + msg);
4637
4637
  }
4638
4638
  $dataMetaSchema(metaSchema, keywordsJsonPointers) {
4639
4639
  const rules = this.RULES.all;
@@ -7600,9 +7600,9 @@ function floatSafeRemainder(val, step2) {
7600
7600
  return ratio - roundedRatio;
7601
7601
  }
7602
7602
  var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
7603
- function defineLazy(object5, key, getter) {
7603
+ function defineLazy(object6, key, getter) {
7604
7604
  let value = void 0;
7605
- Object.defineProperty(object5, key, {
7605
+ Object.defineProperty(object6, key, {
7606
7606
  get() {
7607
7607
  if (value === EVALUATING) {
7608
7608
  return void 0;
@@ -7614,7 +7614,7 @@ function defineLazy(object5, key, getter) {
7614
7614
  return value;
7615
7615
  },
7616
7616
  set(v) {
7617
- Object.defineProperty(object5, key, {
7617
+ Object.defineProperty(object6, key, {
7618
7618
  value: v
7619
7619
  // configurable: true,
7620
7620
  });
@@ -11968,8 +11968,8 @@ function foldObjects(members2) {
11968
11968
  }
11969
11969
  const properties = {};
11970
11970
  const required2 = /* @__PURE__ */ new Set();
11971
- for (const object5 of objects) {
11972
- for (const key in object5.properties) {
11971
+ for (const object6 of objects) {
11972
+ for (const key in object6.properties) {
11973
11973
  if (Object.prototype.hasOwnProperty.call(properties, key))
11974
11974
  continue;
11975
11975
  const parts = [];
@@ -11983,18 +11983,18 @@ function foldObjects(members2) {
11983
11983
  const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts };
11984
11984
  assignProp(properties, key, merged);
11985
11985
  }
11986
- for (const key of object5.required ?? [])
11986
+ for (const key of object6.required ?? [])
11987
11987
  required2.add(key);
11988
11988
  }
11989
11989
  const folded = { type: "object", properties };
11990
11990
  if (required2.size)
11991
11991
  folded.required = [...required2];
11992
- if (objects.every((object5) => object5.additionalProperties === false)) {
11992
+ if (objects.every((object6) => object6.additionalProperties === false)) {
11993
11993
  folded.additionalProperties = false;
11994
11994
  } else {
11995
11995
  const constraints = [];
11996
- for (const object5 of objects) {
11997
- const constraint = undeclaredConstraint(object5);
11996
+ for (const object6 of objects) {
11997
+ const constraint = undeclaredConstraint(object6);
11998
11998
  if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))
11999
11999
  constraints.push(constraint);
12000
12000
  }
@@ -17184,7 +17184,7 @@ var StdioServerTransport = class {
17184
17184
 
17185
17185
  // src/manager.ts
17186
17186
  import { randomUUID as randomUUID6 } from "node:crypto";
17187
- import { mkdir as mkdir10, readFile as readFile9, readdir as readdir7, rm as rm4, cp, access, statfs } from "node:fs/promises";
17187
+ import { mkdir as mkdir10, readFile as readFile9, readdir as readdir7, rm as rm4, cp, access, statfs, writeFile as writeFile4 } from "node:fs/promises";
17188
17188
  import { join as join13, resolve as resolve9 } from "node:path";
17189
17189
 
17190
17190
  // src/config.ts
@@ -17197,8 +17197,9 @@ import { createHash } from "node:crypto";
17197
17197
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
17198
17198
  import { homedir } from "node:os";
17199
17199
  import { isIP } from "node:net";
17200
- var paths = ["imageRepository", "tartHome", "serviceStateDir", "imageStateDir", "relayStateDir", "vmctlPath", "tartPath"];
17200
+ var paths = ["imageRepository", "tartHome", "serviceStateDir", "imageStateDir", "relayStateDir", "machctlPath", "tartPath"];
17201
17201
  var mutable = ["tartHome", "serviceStateDir", "imageStateDir", "relayStateDir"];
17202
+ var LEGACY_PROFILE = "Environment profile is from before the machine-service rename, which reads only schemaVersion 2 with machctlPath: a profile at schemaVersion 1 or with vmctlPath is refused. Rename vmctlPath to machctlPath, naming the machctl executable, and set schemaVersion to 2.";
17202
17203
  function canonicalPath(value) {
17203
17204
  if (typeof value !== "string" || !isAbsolute(value) || !value.trim() || /[\x00-\x1f\x7f\uD800-\uDFFF]/u.test(value)) throw new Error("Environment paths must be absolute and contain no control characters");
17204
17205
  let ancestor = resolve(value);
@@ -17241,37 +17242,38 @@ function loadEnvironment(path, env = process.env, home = env.HOME ?? homedir())
17241
17242
  if (!info.isFile() || info.size > 65536) throw new Error("Environment profile must be a regular JSON file under 64 KiB");
17242
17243
  const bytes = readFileSync(canonical2);
17243
17244
  if (bytes.length > 65536) throw new Error("Environment profile exceeds 64 KiB");
17244
- const text4 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
17245
- const raw = JSON.parse(text4);
17245
+ const text5 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
17246
+ const raw = JSON.parse(text5);
17246
17247
  let depth = 0;
17247
17248
  const seen = /* @__PURE__ */ new Set();
17248
- for (let i = 0; i < text4.length; i++) {
17249
- if (text4[i] === '"') {
17249
+ for (let i = 0; i < text5.length; i++) {
17250
+ if (text5[i] === '"') {
17250
17251
  const start = i++;
17251
- for (; i < text4.length && text4[i] !== '"'; i++) if (text4[i] === "\\") i++;
17252
+ for (; i < text5.length && text5[i] !== '"'; i++) if (text5[i] === "\\") i++;
17252
17253
  let next = i + 1;
17253
- while (/\s/.test(text4[next] ?? "") && next < text4.length) next++;
17254
- if (depth === 1 && text4[next] === ":") {
17255
- const key = JSON.parse(text4.slice(start, i + 1));
17254
+ while (/\s/.test(text5[next] ?? "") && next < text5.length) next++;
17255
+ if (depth === 1 && text5[next] === ":") {
17256
+ const key = JSON.parse(text5.slice(start, i + 1));
17256
17257
  if (seen.has(key)) throw new Error(`Duplicate environment profile key: ${key}`);
17257
17258
  seen.add(key);
17258
17259
  }
17259
- } else if (text4[i] === "{" || text4[i] === "[") depth++;
17260
- else if (text4[i] === "}" || text4[i] === "]") depth--;
17260
+ } else if (text5[i] === "{" || text5[i] === "[") depth++;
17261
+ else if (text5[i] === "}" || text5[i] === "]") depth--;
17261
17262
  }
17263
+ if (raw && typeof raw === "object" && !Array.isArray(raw) && (raw.schemaVersion === 1 || Object.hasOwn(raw, "vmctlPath"))) throw new Error(LEGACY_PROFILE);
17262
17264
  const fields = ["schemaVersion", "id", "vmServiceUrl", ...paths].sort();
17263
17265
  if (!raw || typeof raw !== "object" || Array.isArray(raw) || JSON.stringify(Object.keys(raw).sort()) !== JSON.stringify(fields)) throw new Error("Environment profile has missing or unknown fields");
17264
17266
  const p = raw;
17265
- if (p.schemaVersion !== 1 || typeof p.id !== "string" || !/^[a-z0-9][a-z0-9-]{0,47}$/.test(p.id)) throw new Error("Invalid environment schemaVersion or id");
17266
- const profile = { schemaVersion: 1, id: p.id, vmServiceUrl: endpoint(p.vmServiceUrl) };
17267
+ if (p.schemaVersion !== 2 || typeof p.id !== "string" || !/^[a-z0-9][a-z0-9-]{0,47}$/.test(p.id)) throw new Error("Invalid environment schemaVersion or id");
17268
+ const profile = { schemaVersion: 2, id: p.id, vmServiceUrl: endpoint(p.vmServiceUrl) };
17267
17269
  for (const key of paths) profile[key] = canonicalPath(p[key]);
17268
17270
  if (!statSync(profile.imageRepository).isDirectory() || !statSync(join(profile.imageRepository, "images")).isDirectory()) throw new Error("Selected imageRepository must contain images/");
17269
- for (const key of ["vmctlPath", "tartPath"]) {
17271
+ for (const key of ["machctlPath", "tartPath"]) {
17270
17272
  if (!statSync(profile[key]).isFile()) throw new Error(`${key} must be a regular executable file`);
17271
17273
  accessSync(profile[key], constants.X_OK);
17272
17274
  }
17273
17275
  const state = env.XDG_STATE_HOME ? canonicalPath(env.XDG_STATE_HOME) : join(canonicalPath(home), ".local/state");
17274
- const names = ["vm-service", "pilot-images", "mcp-relay", "mcp-vm-relay"];
17276
+ const names = ["machine-service", "vm-service", "pilot-images", "mcp-relay", "mcp-vm-relay"];
17275
17277
  const defaults = [join(canonicalPath(home), ".tart"), ...names.map((n) => join(state, n)), ...names.map((n) => join(canonicalPath(home), ".local/state", n))].map(canonicalPath);
17276
17278
  for (const key of mutable) {
17277
17279
  const value = profile[key];
@@ -17310,13 +17312,13 @@ function environmentVariables(selected) {
17310
17312
  VM_ENVIRONMENT_FINGERPRINT: selected.identity.fingerprint,
17311
17313
  PILOT_REPO: p.imageRepository,
17312
17314
  TART_HOME: p.tartHome,
17313
- VM_SERVICE_STATE: p.serviceStateDir,
17315
+ MACHINE_SERVICE_STATE: p.serviceStateDir,
17314
17316
  PILOT_IMAGES_STATE_DIR: p.imageStateDir,
17315
17317
  VM_RELAY_STATE_DIR: p.relayStateDir,
17316
17318
  VM_RELAY_URL: p.vmServiceUrl,
17317
- VM_SERVICE_HOST: url.hostname.replace(/^\[|\]$/g, ""),
17318
- VM_SERVICE_PORT: String(Number(p.vmServiceUrl.match(/:([0-9]+)$/)[1])),
17319
- VMCTL: p.vmctlPath,
17319
+ MACHINE_SERVICE_HOST: url.hostname.replace(/^\[|\]$/g, ""),
17320
+ MACHINE_SERVICE_PORT: String(Number(p.vmServiceUrl.match(/:([0-9]+)$/)[1])),
17321
+ MACHCTL: p.machctlPath,
17320
17322
  TART: p.tartPath
17321
17323
  };
17322
17324
  }
@@ -17606,10 +17608,10 @@ var Session = class {
17606
17608
  * transmission; the same outcome states as exec() apply (D14/D17).
17607
17609
  */
17608
17610
  async runScript(localPath, remotePath, language2, options = {}) {
17609
- const { createHash: createHash7 } = await import("node:crypto");
17611
+ const { createHash: createHash8 } = await import("node:crypto");
17610
17612
  const { readFile: readFile10 } = await import("node:fs/promises");
17611
17613
  const bytes = await readFile10(localPath);
17612
- const scriptSha256 = createHash7("sha256").update(bytes).digest("hex");
17614
+ const scriptSha256 = createHash8("sha256").update(bytes).digest("hex");
17613
17615
  const upload = await this.transport.upload(localPath, { remotePath });
17614
17616
  const executionId = formatId(allocateId("execution"));
17615
17617
  const interpreter = language2 === "python" ? "python3" : language2 === "typescript" ? "tsx" : "node";
@@ -17657,8 +17659,8 @@ var Session = class {
17657
17659
  * remote after receipt. Same outcome states as exec() (D14/D17).
17658
17660
  */
17659
17661
  async runCode(code, language2, options = {}) {
17660
- const { createHash: createHash7 } = await import("node:crypto");
17661
- const codeSha256 = createHash7("sha256").update(code, "utf8").digest("hex");
17662
+ const { createHash: createHash8 } = await import("node:crypto");
17663
+ const codeSha256 = createHash8("sha256").update(code, "utf8").digest("hex");
17662
17664
  const executionId = formatId(allocateId("execution"));
17663
17665
  const interpreter = language2 === "python" ? "python3" : language2 === "typescript" ? "tsx" : "node";
17664
17666
  const submission = {
@@ -17744,14 +17746,15 @@ var Session = class {
17744
17746
  // node_modules/@wezzard/relay-driver-host-sdk/dist/src/index.js
17745
17747
  init_evidence_package();
17746
17748
 
17747
- // src/vm-service.ts
17749
+ // src/machine-service.ts
17748
17750
  import { isIP as isIP2 } from "node:net";
17749
- var VmServiceError = class extends Error {
17751
+ import { createHash as createHash3 } from "node:crypto";
17752
+ var MachineServiceError = class extends Error {
17750
17753
  constructor(message3, status, responseBody, options) {
17751
17754
  super(message3, options);
17752
17755
  this.status = status;
17753
17756
  this.responseBody = responseBody;
17754
- this.name = "VmServiceError";
17757
+ this.name = "MachineServiceError";
17755
17758
  }
17756
17759
  status;
17757
17760
  responseBody;
@@ -17759,7 +17762,7 @@ var VmServiceError = class extends Error {
17759
17762
  capacity = false;
17760
17763
  };
17761
17764
  function capacityRefusal(error2) {
17762
- if (!(error2 instanceof VmServiceError) || error2.status !== 409 || !error2.responseBody) return false;
17765
+ if (!(error2 instanceof MachineServiceError) || error2.status !== 409 || !error2.responseBody) return false;
17763
17766
  let body;
17764
17767
  try {
17765
17768
  body = JSON.parse(error2.responseBody);
@@ -17768,11 +17771,16 @@ function capacityRefusal(error2) {
17768
17771
  }
17769
17772
  if (!body || typeof body !== "object") return false;
17770
17773
  const { error: reason2, outcome } = body;
17771
- return typeof reason2 === "string" && reason2.startsWith("macOS VM limit reached") && outcome !== "uncertain";
17774
+ return typeof reason2 === "string" && /^(macOS VM limit reached|durable machine leased|durable machine unavailable)/.test(reason2) && outcome !== "uncertain";
17772
17775
  }
17773
- var AcquireIndeterminateError = class extends VmServiceError {
17776
+ var SERVICE_NAME = "machine-service";
17777
+ function expectMachineService(health, origin) {
17778
+ if (health.service === SERVICE_NAME) return;
17779
+ throw new Error(`The service at ${origin} answers as ${JSON.stringify(health.service ?? null)}, not ${SERVICE_NAME}. This relay speaks only machine-service's /machines API: install machine-service, which replaced vm-service.`);
17780
+ }
17781
+ var AcquireIndeterminateError = class extends MachineServiceError {
17774
17782
  constructor(purpose, cause) {
17775
- super(`Acquisition outcome unknown for purpose '${purpose}'; reconcile GET /vms before retrying or ending the enclosure`, void 0, void 0, { cause });
17783
+ super(`Acquisition outcome unknown for purpose '${purpose}'; reconcile GET /machines before retrying or ending the enclosure`, void 0, void 0, { cause });
17776
17784
  this.purpose = purpose;
17777
17785
  this.name = "AcquireIndeterminateError";
17778
17786
  }
@@ -17785,11 +17793,19 @@ function positive(value, label) {
17785
17793
  function record2(value) {
17786
17794
  return value !== null && typeof value === "object" && !Array.isArray(value);
17787
17795
  }
17796
+ function named(value) {
17797
+ const fields = value;
17798
+ if (record2(value) && fields.kind === "durable" && typeof fields.vm !== "string" && typeof fields.name === "string") fields.vm = fields.name;
17799
+ return value;
17800
+ }
17788
17801
  function isLease(value) {
17789
17802
  if (!record2(value)) return false;
17803
+ if (named(value).kind === "durable") {
17804
+ return ["vm", "purpose", "lease_id", "workspace"].every((k) => typeof value[k] === "string" && value[k] !== "") && value.image === null && value.image_kind === null && value.state === "leased" && ["created_at", "ttl_expires_at"].every((k) => typeof value[k] === "number" && Number.isFinite(value[k]));
17805
+ }
17790
17806
  return ["vm", "purpose", "image"].every((k) => typeof value[k] === "string" && value[k] !== "") && ["macos", "linux"].includes(String(value.image_kind)) && ["pending", "provisioning", "running", "releasing"].includes(String(value.state)) && ["created_at", "ttl_expires_at"].every((k) => typeof value[k] === "number" && Number.isFinite(value[k])) && ["cpu", "memory_mb", "disk_gb", "grace_until"].every((k) => value[k] === null || typeof value[k] === "number") && ["env", "ip"].every((k) => value[k] === null || typeof value[k] === "string") && typeof value.warned === "boolean";
17791
17807
  }
17792
- var VmService = class {
17808
+ var MachineService = class {
17793
17809
  baseUrl;
17794
17810
  environment;
17795
17811
  timeoutMs;
@@ -17802,8 +17818,8 @@ var VmService = class {
17802
17818
  if (options.environment && url.origin !== new URL(options.environment.profile.vmServiceUrl).origin) throw new TypeError("Backend endpoint does not match the selected environment");
17803
17819
  const host = url.hostname.replace(/^\[|\]$/g, "");
17804
17820
  const loopback = host === "localhost" || host === "::1" || isIP2(host) === 4 && host.startsWith("127.");
17805
- if (!loopback || !["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
17806
- throw new TypeError("vm-service baseUrl must be a loopback HTTP(S) origin without credentials, path, query or fragment");
17821
+ if (!loopback && !options.listed || !["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
17822
+ throw new TypeError("machine-service baseUrl must be a loopback HTTP(S) origin, or one Consul lists as machine-service, without credentials, path, query or fragment");
17807
17823
  }
17808
17824
  this.baseUrl = url.origin;
17809
17825
  this.timeoutMs = positive(options.timeoutMs ?? 66e4, "timeoutMs");
@@ -17813,8 +17829,10 @@ var VmService = class {
17813
17829
  health(options = {}) {
17814
17830
  return this.request("/health", void 0, options);
17815
17831
  }
17816
- list(options = {}) {
17817
- return this.request("/vms", void 0, options);
17832
+ async list(options = {}) {
17833
+ const list = await this.request("/machines", void 0, options);
17834
+ if (record2(list.machines)) Object.values(list.machines).forEach(named);
17835
+ return list;
17818
17836
  }
17819
17837
  images(options = {}) {
17820
17838
  return this.request("/images", void 0, options);
@@ -17838,11 +17856,11 @@ var VmService = class {
17838
17856
  try {
17839
17857
  return await this.request(path, body, options);
17840
17858
  } catch (error2) {
17841
- throw new VmServiceError(`Console API unavailable or request outcome unknown${error2 instanceof VmServiceError && error2.status ? ` (HTTP ${error2.status})` : ""}; resolve before another open`, error2 instanceof VmServiceError ? error2.status : void 0);
17859
+ throw new MachineServiceError(`Console API unavailable or request outcome unknown${error2 instanceof MachineServiceError && error2.status ? ` (HTTP ${error2.status})` : ""}; resolve before another open`, error2 instanceof MachineServiceError ? error2.status : void 0);
17842
17860
  }
17843
17861
  }
17844
- get(vm, options = {}) {
17845
- return this.request(this.path(vm), void 0, options);
17862
+ async get(vm, options = {}) {
17863
+ return named(await this.request(this.path(vm), void 0, options));
17846
17864
  }
17847
17865
  /**
17848
17866
  * Cancellation before dispatch prevents allocation. Once dispatched we deliberately
@@ -17857,12 +17875,12 @@ var VmService = class {
17857
17875
  const timeoutMs2 = positive(options.timeoutMs ?? this.acquireTimeoutMs, "timeoutMs");
17858
17876
  try {
17859
17877
  const lease = await this.request("/acquire", body, { timeoutMs: timeoutMs2 });
17860
- if (!isLease(lease)) throw new VmServiceError("Invalid vm-service acquire response");
17878
+ if (!isLease(lease)) throw new MachineServiceError("Invalid machine-service acquire response");
17861
17879
  return lease;
17862
17880
  } catch (error2) {
17863
- const safeError = body.vnc ? new VmServiceError(`VNC acquisition refused or outcome unknown${error2 instanceof VmServiceError && error2.status ? ` (HTTP ${error2.status})` : ""}; inspect capabilities and reconcile ownership`, error2 instanceof VmServiceError ? error2.status : void 0) : error2;
17864
- if (safeError instanceof VmServiceError) safeError.capacity = capacityRefusal(error2);
17865
- if (error2 instanceof VmServiceError && error2.status !== void 0 && error2.status >= 400 && error2.status < 500) throw safeError;
17881
+ const safeError = body.vnc ? new MachineServiceError(`VNC acquisition refused or outcome unknown${error2 instanceof MachineServiceError && error2.status ? ` (HTTP ${error2.status})` : ""}; inspect capabilities and reconcile ownership`, error2 instanceof MachineServiceError ? error2.status : void 0) : error2;
17882
+ if (safeError instanceof MachineServiceError) safeError.capacity = capacityRefusal(error2);
17883
+ if (error2 instanceof MachineServiceError && error2.status !== void 0 && error2.status >= 400 && error2.status < 500) throw safeError;
17866
17884
  throw new AcquireIndeterminateError(body.purpose, safeError);
17867
17885
  }
17868
17886
  }
@@ -17875,36 +17893,76 @@ var VmService = class {
17875
17893
  pull(vm, body, options = {}) {
17876
17894
  return this.request(this.path(vm, "pull"), body, options);
17877
17895
  }
17878
- heartbeat(vm, body = {}, options = {}) {
17879
- return this.request(this.path(vm, "heartbeat"), body, options);
17896
+ async heartbeat(vm, body = {}, options = {}) {
17897
+ return named(await this.request(this.path(vm, "heartbeat"), body, options));
17880
17898
  }
17881
17899
  release(vm, body = {}, options = {}) {
17882
17900
  return this.request(this.path(vm, "release"), body, options);
17883
17901
  }
17902
+ /**
17903
+ * Push one file as bytes, `PUT /machines/<name>/files` (FD-4): the instance
17904
+ * checks the digest before it writes, so a client on another Mac needs no
17905
+ * host path the instance could read (DC-31).
17906
+ */
17907
+ async pushBytes(vm, body, options = {}) {
17908
+ const sha256 = createHash3("sha256").update(body.bytes).digest("hex");
17909
+ const response = await this.fetchBounded(this.filesPath(vm, body.remote_path, body.lease_id), { method: "PUT", headers: { "Content-Type": "application/octet-stream", "X-Content-SHA256": sha256 }, body: new Uint8Array(body.bytes) }, options, this.maxResponseBytes);
17910
+ const answer = this.json(response.path, response.text);
17911
+ if (answer.sha256 !== sha256 || answer.bytes !== body.bytes.length) throw new MachineServiceError(`machine-service ${response.path}: the instance stored ${answer.bytes} bytes with SHA-256 ${answer.sha256}, not what was sent`);
17912
+ return answer;
17913
+ }
17914
+ /** Pull one file as bytes, `GET /machines/<name>/files`; refused unless the bytes match the digest the instance states (DC-31). */
17915
+ async pullBytes(vm, body, options = {}) {
17916
+ const response = await this.fetchBounded(this.filesPath(vm, body.remote_path, body.lease_id), { method: "GET" }, options, body.maxBytes);
17917
+ if (response.contentType !== "application/octet-stream") throw new MachineServiceError(`machine-service ${response.path}: expected one file, got ${response.contentType ?? "no content type"}`);
17918
+ const digest = createHash3("sha256").update(response.bytes).digest("hex");
17919
+ if (!response.sha256 || digest !== response.sha256.toLowerCase()) throw new MachineServiceError(`machine-service ${response.path}: the bytes' SHA-256 ${digest} differs from the stated ${response.sha256 ?? "none"}`);
17920
+ return response.bytes;
17921
+ }
17922
+ filesPath(vm, remote, lease_id) {
17923
+ const query = new URLSearchParams({ ...lease_id ? { lease_id } : {}, path: remote });
17924
+ return `${this.path(vm, "files")}?${query}`;
17925
+ }
17884
17926
  path(vm, action) {
17885
17927
  if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(vm)) throw new TypeError("Invalid VM name");
17886
- return `/vms/${encodeURIComponent(vm)}${action ? `/${action}` : ""}`;
17928
+ return `/machines/${encodeURIComponent(vm)}${action ? `/${action}` : ""}`;
17887
17929
  }
17888
17930
  async request(path, body, options) {
17931
+ const response = await this.fetchBounded(path, {
17932
+ method: body === void 0 ? "GET" : "POST",
17933
+ headers: body === void 0 ? {} : { "Content-Type": "application/json" },
17934
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
17935
+ }, options, this.maxResponseBytes);
17936
+ return this.json(path, response.text);
17937
+ }
17938
+ json(path, text5) {
17939
+ try {
17940
+ return JSON.parse(text5);
17941
+ } catch (cause) {
17942
+ throw new MachineServiceError(`machine-service ${path}: invalid JSON response`, void 0, void 0, { cause });
17943
+ }
17944
+ }
17945
+ /** One request whose answer is read up to `maxBytes`; an error answer is read up to 4 KiB and thrown with its status. */
17946
+ async fetchBounded(path, init, options, maxBytes) {
17889
17947
  options.signal?.throwIfAborted();
17890
17948
  const timeoutMs2 = positive(options.timeoutMs ?? this.timeoutMs, "timeoutMs");
17891
17949
  const controller = new AbortController();
17892
17950
  const abort = () => controller.abort(options.signal?.reason);
17893
17951
  options.signal?.addEventListener("abort", abort, { once: true });
17894
- const timer = setTimeout(() => controller.abort(new VmServiceError(`vm-service ${path} timed out after ${timeoutMs2}ms`)), timeoutMs2);
17952
+ const timer = setTimeout(() => controller.abort(new MachineServiceError(`machine-service ${path} timed out after ${timeoutMs2}ms`)), timeoutMs2);
17895
17953
  try {
17896
17954
  const response = await fetch(`${this.baseUrl}${path}`, {
17897
- method: body === void 0 ? "GET" : "POST",
17898
- headers: { ...body === void 0 ? {} : { "Content-Type": "application/json" }, ...this.environment ? { "X-VM-Environment-Fingerprint": this.environment.identity.fingerprint } : {} },
17899
- ...body === void 0 ? {} : { body: JSON.stringify(body) },
17955
+ method: init.method,
17956
+ headers: { ...init.headers, ...this.environment ? { "X-VM-Environment-Fingerprint": this.environment.identity.fingerprint } : {} },
17957
+ ...init.body === void 0 ? {} : { body: init.body },
17900
17958
  signal: controller.signal,
17901
17959
  redirect: "error"
17902
- // Do not let a loopback service redirect to remote hosts.
17960
+ // Do not let a service redirect to another host.
17903
17961
  });
17904
17962
  const reader = response.body?.getReader();
17905
17963
  const chunks = [];
17906
17964
  let size = 0;
17907
- const bound = response.ok ? this.maxResponseBytes : Math.min(4096, this.maxResponseBytes);
17965
+ const bound = response.ok ? maxBytes : Math.min(4096, maxBytes);
17908
17966
  let truncated = false;
17909
17967
  if (reader) {
17910
17968
  try {
@@ -17924,18 +17982,14 @@ var VmService = class {
17924
17982
  reader.releaseLock();
17925
17983
  }
17926
17984
  }
17927
- const text4 = Buffer.concat(chunks).toString("utf8");
17928
- if (!response.ok) throw new VmServiceError(`vm-service ${path}: HTTP ${response.status}: ${text4}${truncated ? " [truncated]" : ""}`, response.status, text4);
17929
- if (truncated) throw new VmServiceError(`vm-service ${path}: response exceeds ${bound} bytes`);
17930
- try {
17931
- return JSON.parse(text4);
17932
- } catch (cause) {
17933
- throw new VmServiceError(`vm-service ${path}: invalid JSON response`, void 0, void 0, { cause });
17934
- }
17985
+ const bytes = Buffer.concat(chunks), text5 = bytes.toString("utf8");
17986
+ if (!response.ok) throw new MachineServiceError(`machine-service ${path}: HTTP ${response.status}: ${text5}${truncated ? " [truncated]" : ""}`, response.status, text5);
17987
+ if (truncated) throw new MachineServiceError(`machine-service ${path}: response exceeds ${bound} bytes`);
17988
+ return { path, bytes, text: text5, contentType: response.headers.get("content-type") ?? void 0, sha256: response.headers.get("x-content-sha256") ?? void 0 };
17935
17989
  } catch (cause) {
17936
17990
  if (controller.signal.aborted) throw controller.signal.reason;
17937
- if (cause instanceof VmServiceError) throw cause;
17938
- throw new VmServiceError(`vm-service ${path}: request failed`, void 0, void 0, { cause });
17991
+ if (cause instanceof MachineServiceError) throw cause;
17992
+ throw new MachineServiceError(`machine-service ${path}: request failed`, void 0, void 0, { cause });
17939
17993
  } finally {
17940
17994
  clearTimeout(timer);
17941
17995
  options.signal?.removeEventListener("abort", abort);
@@ -17970,21 +18024,21 @@ function cells(row) {
17970
18024
  });
17971
18025
  }
17972
18026
  function parse3(line) {
17973
- const text4 = line.trim();
17974
- if (!text4.startsWith("|") || !text4.endsWith("|")) return void 0;
17975
- return text4.slice(1, -1).split("|").map((cell) => cell.trim());
18027
+ const text5 = line.trim();
18028
+ if (!text5.startsWith("|") || !text5.endsWith("|")) return void 0;
18029
+ return text5.slice(1, -1).split("|").map((cell) => cell.trim());
17976
18030
  }
17977
- function linesOf(text4) {
18031
+ function linesOf(text5) {
17978
18032
  const lines = [];
17979
18033
  const pattern = /[^\r\n]*(?:\r\n|\n|\r|$)/g;
17980
- for (const match of text4.matchAll(pattern)) {
18034
+ for (const match of text5.matchAll(pattern)) {
17981
18035
  if (!match[0]) continue;
17982
18036
  lines.push({ text: match[0].replace(/[\r\n]+$/, ""), start: match.index, end: match.index + match[0].length });
17983
18037
  }
17984
18038
  return lines;
17985
18039
  }
17986
- function table(text4) {
17987
- const lines = linesOf(text4);
18040
+ function table(text5) {
18041
+ const lines = linesOf(text5);
17988
18042
  const sections = lines.map((line, index) => /^## Using VMs\s*$/.test(line.text) ? index : -1).filter((index) => index >= 0);
17989
18043
  if (sections.length !== 1) throw new RegistryError("Expected exactly one '## Using VMs' section");
17990
18044
  const begin = sections[0];
@@ -18005,7 +18059,7 @@ function table(text4) {
18005
18059
  rows.push(line);
18006
18060
  }
18007
18061
  const last = rows.at(-1) ?? separator;
18008
- return { rows, insertion: last.end, newline: text4.includes("\r\n") ? "\r\n" : "\n" };
18062
+ return { rows, insertion: last.end, newline: text5.includes("\r\n") ? "\r\n" : "\n" };
18009
18063
  }
18010
18064
  function resolveRegistry(options = {}) {
18011
18065
  const env = options.env ?? process.env;
@@ -18083,30 +18137,30 @@ var Registry = class {
18083
18137
  /** Returns false when this exact row is already registered (idempotent). */
18084
18138
  async add(row, options = {}) {
18085
18139
  const desired = cells(row);
18086
- return this.update((text4) => {
18087
- const registry2 = table(text4);
18140
+ return this.update((text5) => {
18141
+ const registry2 = table(text5);
18088
18142
  const matching = registry2.rows.filter((line) => parse3(line.text)[2] === row.taskName);
18089
18143
  if (matching.length > 0) {
18090
- if (matching.length === 1 && JSON.stringify(parse3(matching[0].text)) === JSON.stringify(desired)) return text4;
18144
+ if (matching.length === 1 && JSON.stringify(parse3(matching[0].text)) === JSON.stringify(desired)) return text5;
18091
18145
  throw new RegistryError(`Task '${row.taskName}' is already registered by a different owner or duplicated`);
18092
18146
  }
18093
- const prefix = registry2.insertion > 0 && !/[\r\n]/.test(text4[registry2.insertion - 1]) ? registry2.newline : "";
18147
+ const prefix = registry2.insertion > 0 && !/[\r\n]/.test(text5[registry2.insertion - 1]) ? registry2.newline : "";
18094
18148
  const added = `${prefix}| ${desired.join(" | ")} |${registry2.newline}`;
18095
- return text4.slice(0, registry2.insertion) + added + text4.slice(registry2.insertion);
18149
+ return text5.slice(0, registry2.insertion) + added + text5.slice(registry2.insertion);
18096
18150
  }, options.signal);
18097
18151
  }
18098
18152
  /** Returns false when absent. Never removes a row whose ownership differs. */
18099
18153
  async remove(row, options = {}) {
18100
18154
  const desired = cells(row);
18101
- return this.update((text4) => {
18102
- const registry2 = table(text4);
18155
+ return this.update((text5) => {
18156
+ const registry2 = table(text5);
18103
18157
  const matching = registry2.rows.filter((line2) => parse3(line2.text)[2] === row.taskName);
18104
- if (matching.length === 0) return text4;
18158
+ if (matching.length === 0) return text5;
18105
18159
  if (matching.length !== 1 || JSON.stringify(parse3(matching[0].text)) !== JSON.stringify(desired)) {
18106
18160
  throw new RegistryError(`Refusing to remove task '${row.taskName}': ownership does not match`);
18107
18161
  }
18108
18162
  const line = matching[0];
18109
- return text4.slice(0, line.start) + text4.slice(line.end);
18163
+ return text5.slice(0, line.start) + text5.slice(line.end);
18110
18164
  }, options.signal);
18111
18165
  }
18112
18166
  async update(transform2, signal) {
@@ -18271,14 +18325,14 @@ import { randomUUID as randomUUID3 } from "node:crypto";
18271
18325
 
18272
18326
  // src/util.ts
18273
18327
  import { spawn as spawn3 } from "node:child_process";
18274
- import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
18328
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
18275
18329
  import { mkdir as mkdir3, rename as rename3, lstat as lstat2, readdir as readdir2, open as open3 } from "node:fs/promises";
18276
18330
  import { dirname as dirname4, join as join6, resolve as resolve4, relative as relative3, isAbsolute as isAbsolute3 } from "node:path";
18277
- var hash = (bytes) => createHash3("sha256").update(bytes).digest("hex");
18331
+ var hash = (bytes) => createHash4("sha256").update(bytes).digest("hex");
18278
18332
  async function hashFile(path) {
18279
18333
  const file = await open3(path, "r");
18280
18334
  try {
18281
- const digest = createHash3("sha256"), chunk = Buffer.alloc(8 * 1024 * 1024);
18335
+ const digest = createHash4("sha256"), chunk = Buffer.alloc(8 * 1024 * 1024);
18282
18336
  let bytes = 0;
18283
18337
  for (; ; ) {
18284
18338
  const { bytesRead } = await file.read(chunk, 0, chunk.length, null);
@@ -18368,7 +18422,7 @@ async function command(argv, options = {}) {
18368
18422
  // src/archive.ts
18369
18423
  import { open as open4, mkdir as mkdir4 } from "node:fs/promises";
18370
18424
  import { constants as constants2 } from "node:fs";
18371
- import { createHash as createHash4 } from "node:crypto";
18425
+ import { createHash as createHash5 } from "node:crypto";
18372
18426
  import { dirname as dirname5 } from "node:path";
18373
18427
  var MAX_LINE_BYTES = 64 * 1024;
18374
18428
  var header = (path, bytes) => `${JSON.stringify({ path, bytes })}
@@ -18418,9 +18472,9 @@ async function unpackArchive(archive, directory2, requested, options = {}) {
18418
18472
  for (; ; ) {
18419
18473
  const at = buffer.indexOf(10, start);
18420
18474
  if (at >= 0 && at < end) {
18421
- const text4 = buffer.toString("utf8", start, at);
18475
+ const text5 = buffer.toString("utf8", start, at);
18422
18476
  start = at + 1;
18423
- const value = JSON.parse(text4);
18477
+ const value = JSON.parse(text5);
18424
18478
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid archive line");
18425
18479
  return value;
18426
18480
  }
@@ -18442,7 +18496,7 @@ async function unpackArchive(archive, directory2, requested, options = {}) {
18442
18496
  const target = within(directory2, fact.path);
18443
18497
  await mkdir4(dirname5(target), { recursive: true, mode: 448 });
18444
18498
  const output = await open4(target, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | constants2.O_NOFOLLOW, 384);
18445
- const digest = createHash4("sha256");
18499
+ const digest = createHash5("sha256");
18446
18500
  try {
18447
18501
  for (let left = bytes; left > 0; ) {
18448
18502
  if (start === end) {
@@ -18781,10 +18835,10 @@ var Transfer = class {
18781
18835
  if (!imageFormat(result2)) throw new ImageTransferError("unsafe-path", "Unsupported image format");
18782
18836
  } else {
18783
18837
  try {
18784
- const text4 = new TextDecoder("utf-8", { fatal: true }).decode(result2);
18838
+ const text5 = new TextDecoder("utf-8", { fatal: true }).decode(result2);
18785
18839
  if (options.metadataFormat === "jsonl") {
18786
- for (const line of text4.split("\n")) if (line.trim()) JSON.parse(line);
18787
- } else JSON.parse(text4);
18840
+ for (const line of text5.split("\n")) if (line.trim()) JSON.parse(line);
18841
+ } else JSON.parse(text5);
18788
18842
  } catch (cause) {
18789
18843
  throw new ImageTransferError("integrity-failed", "Invalid image metadata JSON", { cause });
18790
18844
  }
@@ -19174,11 +19228,11 @@ var VmTransport = class {
19174
19228
  };
19175
19229
 
19176
19230
  // src/package.ts
19177
- import { createHash as createHash5 } from "node:crypto";
19231
+ import { createHash as createHash6 } from "node:crypto";
19178
19232
  import { lstat as lstat4, readFile as readFile6, readdir as readdir3, mkdir as mkdir6, writeFile as writeFile3, rm as rm2 } from "node:fs/promises";
19179
19233
  import { dirname as dirname7, join as join9, resolve as resolve6, parse as parse4 } from "node:path";
19180
19234
  var generated = ["OPENING.txt", "manifest.json"];
19181
- var hash2 = (bytes) => createHash5("sha256").update(bytes).digest("hex");
19235
+ var hash2 = (bytes) => createHash6("sha256").update(bytes).digest("hex");
19182
19236
  var json = (value) => JSON.stringify(value, null, 2) + "\n";
19183
19237
  function object3(value, label) {
19184
19238
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`invalid ${label}`);
@@ -19621,16 +19675,16 @@ async function probeLocal(run = command, platform = process.platform) {
19621
19675
  }
19622
19676
  const permissions = await observe(["cua-driver", "permissions", "status", "--json"], JSON.parse);
19623
19677
  const recorder = await observe(["cua-driver", "call", "get_recording_state", "--json", "{}"], JSON.parse);
19624
- const foreground = await observe(["cua-driver", "call", "list_apps", "--json", "{}"], (text4) => {
19625
- const data = JSON.parse(text4);
19678
+ const foreground = await observe(["cua-driver", "call", "list_apps", "--json", "{}"], (text5) => {
19679
+ const data = JSON.parse(text5);
19626
19680
  return data.apps?.filter((app) => app.active).map((app) => ({ name: app.name, bundleId: app.bundle_id, pid: app.pid })) ?? null;
19627
19681
  });
19628
- const session = platform === "darwin" ? await observe(["/usr/bin/stat", "-f", "%Su", "/dev/console"], (text4) => !["root", "loginwindow", ""].includes(text4.trim())) : await observe(["loginctl", "show-session", "self", "-p", "Active", "--value"], (text4) => text4.trim() === "yes");
19629
- const idle = platform === "darwin" ? await observe(["/usr/sbin/ioreg", "-r", "-c", "IOHIDSystem"], (text4) => {
19630
- const m = text4.match(/"HIDIdleTime"\s*=\s*(\d+)/);
19682
+ const session = platform === "darwin" ? await observe(["/usr/bin/stat", "-f", "%Su", "/dev/console"], (text5) => !["root", "loginwindow", ""].includes(text5.trim())) : await observe(["loginctl", "show-session", "self", "-p", "Active", "--value"], (text5) => text5.trim() === "yes");
19683
+ const idle = platform === "darwin" ? await observe(["/usr/sbin/ioreg", "-r", "-c", "IOHIDSystem"], (text5) => {
19684
+ const m = text5.match(/"HIDIdleTime"\s*=\s*(\d+)/);
19631
19685
  return m ? Number(m[1]) / 1e9 : null;
19632
- }) : await observe(["xprintidle"], (text4) => {
19633
- const n = Number(text4.trim());
19686
+ }) : await observe(["xprintidle"], (text5) => {
19687
+ const n = Number(text5.trim());
19634
19688
  return Number.isFinite(n) ? n / 1e3 : null;
19635
19689
  });
19636
19690
  return {
@@ -23334,8 +23388,8 @@ function FromObject4(properties) {
23334
23388
 
23335
23389
  // node_modules/typebox/build/type/engine/object/from_tuple.mjs
23336
23390
  function FromTuple(types) {
23337
- const object5 = TupleToObject(Tuple(types));
23338
- const result2 = FromType8(object5);
23391
+ const object6 = TupleToObject(Tuple(types));
23392
+ const result2 = FromType8(object6);
23339
23393
  return result2;
23340
23394
  }
23341
23395
 
@@ -27360,8 +27414,8 @@ var normalizeSearchName = (name) => name.trim().toLowerCase();
27360
27414
  var serializeSearchResult = (result2) => JSON.stringify(result2, null, 2);
27361
27415
  function validateCatalog(value) {
27362
27416
  if (!Check2(catalogSchema, value)) throw new Error("Invalid application catalog schema");
27363
- const bounded3 = (text4, limit) => {
27364
- if (Array.from(text4).length > limit) throw new Error("Application catalog exceeds text limit");
27417
+ const bounded3 = (text5, limit) => {
27418
+ if (Array.from(text5).length > limit) throw new Error("Application catalog exceeds text limit");
27365
27419
  };
27366
27420
  for (const image of value.images) for (const app of image.applications) {
27367
27421
  bounded3(app.id, 128);
@@ -27580,7 +27634,7 @@ import { join as join11, dirname as dirname8, extname } from "node:path";
27580
27634
  import { randomUUID as randomUUID5 } from "node:crypto";
27581
27635
 
27582
27636
  // src/image-presentation.ts
27583
- import { createHash as createHash6 } from "node:crypto";
27637
+ import { createHash as createHash7 } from "node:crypto";
27584
27638
  import { deflateSync, inflateSync } from "node:zlib";
27585
27639
  var IMAGE_PRESENTATION_POLICY = Object.freeze({
27586
27640
  version: 1,
@@ -27986,7 +28040,7 @@ async function prepareImage(bytes, mimeType) {
27986
28040
  width: size.width,
27987
28041
  height: size.height,
27988
28042
  mimeType: presentedType,
27989
- sha256: createHash6("sha256").update(presented).digest("hex"),
28043
+ sha256: createHash7("sha256").update(presented).digest("hex"),
27990
28044
  bytes: presented.length,
27991
28045
  transformed: presentedType !== mimeType || !original.equals(presented),
27992
28046
  policy
@@ -28736,12 +28790,85 @@ async function refreshEvidenceState(incoming, destination, archiveRoot, options
28736
28790
  if (archived) await copy(archived, retained);
28737
28791
  }
28738
28792
 
28793
+ // src/discovery.ts
28794
+ var TIMEOUT_MS = 5e3;
28795
+ function consulAddress(value = process.env.CONSUL_HTTP_ADDR) {
28796
+ const address = value?.trim() || "http://127.0.0.1:8500";
28797
+ return new URL(/^[a-z]+:\/\//i.test(address) ? address : `http://${address}`).origin;
28798
+ }
28799
+ async function fetchJson(url) {
28800
+ const response = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
28801
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
28802
+ return response.json();
28803
+ }
28804
+ var text3 = (value) => typeof value === "string" ? value : "";
28805
+ function parseRegistrations(answer) {
28806
+ if (!Array.isArray(answer)) throw new Error("Consul answered with no list of registrations");
28807
+ return answer.flatMap((entry) => {
28808
+ const node2 = entry?.Node, service = entry?.Service, port = service?.Port;
28809
+ const host = text3(service?.Address) || text3(node2?.Address);
28810
+ if (!host || !Number.isSafeInteger(port)) return [];
28811
+ const meta2 = service?.Meta ?? {};
28812
+ return [{ node: text3(node2?.Node), origin: new URL(`http://${host.includes(":") ? `[${host}]` : host}:${port}`).origin, ...text3(meta2.instance) ? { instance: text3(meta2.instance) } : {}, loopbackOnly: meta2.loopback_only === "true" }];
28813
+ });
28814
+ }
28815
+ async function findDurableOwner(machine, options) {
28816
+ const consul = options.consul ?? consulAddress();
28817
+ const make = options.backend ?? ((origin) => new MachineService({ baseUrl: origin, listed: true }));
28818
+ const candidates = [{ origin: new URL(options.local.baseUrl).origin, backend: options.local }];
28819
+ let consulError;
28820
+ try {
28821
+ for (const registration of parseRegistrations(await (options.fetchJson ?? fetchJson)(`${consul}/v1/health/service/machine-service`))) {
28822
+ if (registration.loopbackOnly || candidates.some((candidate) => candidate.origin === registration.origin)) continue;
28823
+ candidates.push({ origin: registration.origin, backend: make(registration.origin) });
28824
+ }
28825
+ } catch (error2) {
28826
+ consulError = `the Consul agent at ${consul} did not answer (${error2 instanceof Error ? error2.message : String(error2)})`;
28827
+ }
28828
+ const owners = [];
28829
+ await Promise.all(candidates.map(async ({ origin, backend }) => {
28830
+ try {
28831
+ const list = await backend.list({ timeoutMs: TIMEOUT_MS });
28832
+ const record3 = list.machines[machine];
28833
+ if (record3?.kind === "durable") owners.push({ backend, origin, instance: record3.instance ?? machine });
28834
+ } catch {
28835
+ }
28836
+ }));
28837
+ if (owners.length === 1) return owners[0];
28838
+ if (owners.length > 1) throw new Error(`Durable machine ${machine} is listed by more than one instance (${owners.map((owner) => owner.origin).join(", ")}); nothing was acquired`);
28839
+ throw new Error(`No machine-service instance lists a durable machine named ${machine}${consulError ? `, and ${consulError}` : ""}; nothing was acquired. Check the name with \`machctl list\`, and point CONSUL_HTTP_ADDR at a reachable Consul agent.`);
28840
+ }
28841
+
28842
+ // src/capture-gate.ts
28843
+ var object5 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
28844
+ function durableCapture(machine, software, answer) {
28845
+ const version2 = object5(software)?.cua_driver;
28846
+ if (typeof version2 !== "string" || !version2) return { capture: false, state: "absent", reason: `${machine} lists no cua-driver in its capabilities, so runs take no snapshots.` };
28847
+ if (!answer) return { capture: false, state: "unknown", reason: `cua-driver's permission status on ${machine} was not read, so runs take no snapshots.` };
28848
+ if ("error" in answer || answer.code !== 0) {
28849
+ const why = "error" in answer ? answer.error : `exit ${answer.code}: ${(answer.stderr || answer.stdout).trim().slice(0, 300)}`;
28850
+ return { capture: false, state: "unknown", reason: `\`cua-driver permissions status --json\` failed on ${machine} (${why}), so whether its daemon may record the screen is unknown and runs take no snapshots.` };
28851
+ }
28852
+ let status;
28853
+ try {
28854
+ status = object5(JSON.parse(answer.stdout));
28855
+ } catch {
28856
+ }
28857
+ if (!status || typeof status.screen_recording !== "boolean") return { capture: false, state: "unknown", reason: `cua-driver's permission status on ${machine} is not the expected JSON, so whether its daemon may record the screen is unknown and runs take no snapshots.` };
28858
+ const attribution = object5(status.source)?.attribution;
28859
+ if (attribution !== "driver-daemon") return { capture: false, state: "daemon-not-running", reason: `cua-driver on ${machine} answered for ${typeof attribution === "string" ? `"${attribution}"` : "no source"}, not for its daemon, so the \`cua-driver serve\` daemon is not running and runs take no snapshots. Start CuaDriver on the Mac, then call relay_stage again.` };
28860
+ if (status.screen_recording !== true) return { capture: false, state: "denied", reason: `The cua-driver daemon on ${machine} lacks Screen Recording, so runs take no snapshots. Grant it to CuaDriver in System Settings on the Mac, then call relay_stage again.` };
28861
+ return { capture: true, state: "granted", reason: `The cua-driver daemon on ${machine} holds Screen Recording, so each run takes before and after snapshots.` };
28862
+ }
28863
+
28739
28864
  // src/manager.ts
28740
28865
  var SCRIPT_EXTENSIONS = { shell: "sh", javascript: "js", typescript: "ts", python: "py" };
28741
28866
  var RENEWAL_WINDOW_MS = 15 * 6e4;
28742
28867
  var MIN_RENEWAL_MS = 0.1 * 36e5;
28743
28868
  var DEFAULT_AFTER_INTERVAL_MS = 500;
28744
28869
  var CAPTURE_SOFTWARE = ["bundle:com.trycua.driver", "dpkg:cua-driver"];
28870
+ var durableRoot = (workspace, purpose) => join13(workspace, "work", `mcp-relay-${purpose}`);
28871
+ var PULL_MAX_BYTES = 2 * 1024 * 1024 * 1024 - 1;
28745
28872
  var DOWNLOAD_BOUND = 64;
28746
28873
  var DOWNLOAD_RETRY_DELAYS_MS = [1e3, 3e3];
28747
28874
  var CAPACITY_RETRY_MS = 15e3;
@@ -28756,7 +28883,7 @@ async function settleEach(work) {
28756
28883
  const failed = (await Promise.allSettled(work)).find((result2) => result2.status === "rejected");
28757
28884
  if (failed) throw failed.reason;
28758
28885
  }
28759
- var instructions = "This server offers fourteen tools for guests, VMs that run the work you choose to run there: relay_search, relay_probe, relay_acquisition_capabilities, relay_acquire, relay_stage, the run tool relay_script, relay_image, relay_extract, relay_finish, relay_release, relay_console_resolve, relay_console_open, relay_console_cancel and relay_status. relay_script runs a shell, JavaScript, TypeScript or Python script, given inline or as a project file; a command is a shell script, and the script drives whatever the image lists, such as cua-driver, Playwright or Chrome DevTools, through their own libraries or command lines. Staging needs only Node.js in the guest, and a run takes before and after snapshots only when the image lists capture software (cua-driver). Evidence is automatic, and a run's after-image is returned as pending and downloaded in the background, so call relay_image with the imageId when you need to see it. Acquire one guest for each machine your work needs; several guests may run at once, up to the session's limit that relay_status reports. relay_acquire answers each guest's name, `guest`, and every call that acts on a guest names it with `guest`. Calls on different guests run at the same time; calls on one guest keep their order. Work each guest in order: relay_probe, then relay_acquire, then relay_stage, then relay_script, then relay_image or relay_extract as needed, then relay_finish or relay_release; finishing or releasing one guest leaves the others running. Always call relay_finish or relay_release explicitly for every guest before you return an answer; ending the session never finishes a guest: it pauses lease renewal and keeps the VMs or, where the relay is set up to, releases them, and the backend's own expiry is the last-resort safeguard. A refused, uncertain or nonzero operation keeps the VM so you can diagnose and submit a corrected operation; never replay input whose effect is uncertain. A tool result, an attached image or a verified evidence package, is evidence for a human reviewer, never the review itself. The relay never targets a physical or local display and offers no video or spawn API. Every tool's text result is capped at 50 KiB / 2000 lines; a larger result is retained whole in a local file the result names.";
28886
+ var instructions = "This server offers fourteen tools for guests, machines that run the work you choose to run there: VMs from an image, or durable machines, real Macs named with `machine`: relay_search, relay_probe, relay_acquisition_capabilities, relay_acquire, relay_stage, the run tool relay_script, relay_image, relay_extract, relay_finish, relay_release, relay_console_resolve, relay_console_open, relay_console_cancel and relay_status. relay_script runs a shell, JavaScript, TypeScript or Python script, given inline or as a project file; a command is a shell script, and the script drives whatever the image lists, such as cua-driver, Playwright or Chrome DevTools, through their own libraries or command lines. Staging needs only Node.js in the guest, and a run takes before and after snapshots only when the image lists capture software (cua-driver). Evidence is automatic, and a run's after-image is returned as pending and downloaded in the background, so call relay_image with the imageId when you need to see it. Acquire one guest for each machine your work needs; several guests may run at once, up to the session's limit that relay_status reports. relay_acquire answers each guest's name, `guest`, and every call that acts on a guest names it with `guest`. Calls on different guests run at the same time; calls on one guest keep their order. Work each guest in order: relay_probe, then relay_acquire, then relay_stage, then relay_script, then relay_image or relay_extract as needed, then relay_finish or relay_release; finishing or releasing one guest leaves the others running. Always call relay_finish or relay_release explicitly for every guest before you return an answer; ending the session never finishes a guest: it pauses lease renewal and keeps the VMs or, where the relay is set up to, releases them, and the backend's own expiry is the last-resort safeguard. A refused, uncertain or nonzero operation keeps the VM so you can diagnose and submit a corrected operation; never replay input whose effect is uncertain. A tool result, an attached image or a verified evidence package, is evidence for a human reviewer, never the review itself. A durable machine is a real Mac on the home network, leased whole for one session: it is not isolated from the home network, a CI job may share its desktop, and its runs take snapshots only while its cua-driver daemon holds Screen Recording. The relay never targets its own host's display and offers no video or spawn API. Every tool's text result is capped at 50 KiB / 2000 lines; a larger result is retained whole in a local file the result names.";
28760
28887
  var NO_OWNED_LEASE = "This session owns no lease: it holds no guest, so nothing was released. Each server process has its own session identity (a new random one unless MCP_RELAY_SESSION sets it); a lease acquired under another identity is not visible here. Restart the server with that MCP_RELAY_SESSION to reconcile and release it, or let the backend TTL expire it.";
28761
28888
  var RelayManager = class {
28762
28889
  constructor(options) {
@@ -28770,17 +28897,9 @@ var RelayManager = class {
28770
28897
  this.capacityWaitMs = options.capacityWaitMs ?? capacityWait() * 1e3;
28771
28898
  this.capacityRetryMs = options.capacityRetryMs ?? CAPACITY_RETRY_MS;
28772
28899
  if (!Number.isFinite(this.capacityWaitMs) || this.capacityWaitMs < 0 || !Number.isFinite(this.capacityRetryMs) || this.capacityRetryMs <= 0) throw new Error("capacityWaitMs must be nonnegative and capacityRetryMs positive");
28773
- this.vm = options.vm ?? new VmService({ baseUrl: this.environment?.profile.vmServiceUrl ?? process.env.MCP_RELAY_URL, environment: this.environment });
28900
+ this.vm = options.vm ?? new MachineService({ baseUrl: this.environment?.profile.vmServiceUrl ?? process.env.MCP_RELAY_URL, environment: this.environment });
28774
28901
  this.registry = options.registry ?? new Registry(this.environment ? { managedRoot: this.environment.profile.relayStateDir } : {});
28775
28902
  this.root = join13(this.environment?.profile.relayStateDir ?? options.stateRoot ?? relayStateRoot(), hash(options.sessionId).slice(0, 32));
28776
- this.channel = {
28777
- exec: async (name, argv, timeoutMs2 = 18e4, options2) => {
28778
- const result2 = await this.vm.exec(name, { argv, timeout: Math.ceil(timeoutMs2 / 1e3) }, { timeoutMs: options2?.timeoutMs ?? timeoutMs2 + 3e4, signal: options2?.signal });
28779
- return { stdout: result2.output, stderr: result2.output, code: result2.rc };
28780
- },
28781
- push: (name, local_path, remote_path) => this.vm.push(name, { local_path, remote_path }),
28782
- pull: (name, remote_path, local_path, options2) => this.vm.pull(name, { remote_path, local_path }, options2)
28783
- };
28784
28903
  }
28785
28904
  options;
28786
28905
  vm;
@@ -28789,7 +28908,6 @@ var RelayManager = class {
28789
28908
  tartPath;
28790
28909
  registry;
28791
28910
  root;
28792
- channel;
28793
28911
  /** The most guests this session holds at once (DC-20). */
28794
28912
  maxGuests;
28795
28913
  /** How long an acquisition waits for a host at capacity, and how often it is asked again (DC-22). */
@@ -28805,6 +28923,10 @@ var RelayManager = class {
28805
28923
  ownerLock;
28806
28924
  /** Set once shutdown has paused the guests: no new acquisition or guest operation starts. */
28807
28925
  shuttingDown = false;
28926
+ /** The instance that owns a durable machine, found as machctl finds it (DC-29). */
28927
+ durableOwner(machine) {
28928
+ return findDurableOwner(machine, { local: this.vm, ...this.options.consul ? { consul: this.options.consul } : {}, ...this.options.durableBackend ? { backend: this.options.durableBackend } : {}, ...this.options.consulFetch ? { fetchJson: this.options.consulFetch } : {} });
28929
+ }
28808
28930
  serialized(fn) {
28809
28931
  const next = this.queue.then(fn, fn);
28810
28932
  this.queue = next.catch(() => {
@@ -28930,6 +29052,7 @@ var RelayManager = class {
28930
29052
  return { endpoint: this.vm.baseUrl, tartHome: this.tartHome, ...this.environment ? { environmentFingerprint: this.environment.identity.fingerprint } : {} };
28931
29053
  }
28932
29054
  bindingMatches(e) {
29055
+ if (e.machine) return !!e.backend?.endpoint && !!e.backend.instance;
28933
29056
  if (e.backend) {
28934
29057
  const expected = this.binding();
28935
29058
  return Object.keys(e.backend).length === Object.keys(expected).length && Object.entries(expected).every(([key, value]) => e.backend[key] === value);
@@ -28940,7 +29063,8 @@ var RelayManager = class {
28940
29063
  if (!this.environment) return;
28941
29064
  if (new URL(this.vm.baseUrl).origin !== new URL(this.environment.profile.vmServiceUrl).origin) throw new Error("Injected backend endpoint does not match selected environment");
28942
29065
  const health = await this.vm.health({ timeoutMs: 5e3 });
28943
- if (!health.ok || !matchesEnvironment(health.environment, this.environment)) throw new Error("VM service environment identity mismatch; no lease operation was performed");
29066
+ expectMachineService(health, this.vm.baseUrl);
29067
+ if (!health.ok || !matchesEnvironment(health.environment, this.environment)) throw new Error("machine-service environment identity mismatch; no lease operation was performed");
28944
29068
  }
28945
29069
  async unlock() {
28946
29070
  if (this.ownerLock) {
@@ -28999,7 +29123,7 @@ var RelayManager = class {
28999
29123
  async readAcquisitionCapabilities(signal) {
29000
29124
  signal?.throwIfAborted();
29001
29125
  await this.assertBackend();
29002
- if (!this.vm.acquisitionCapabilities) throw new Error("Backend lacks acquisition-capabilities; upgrade vm-service for VNC");
29126
+ if (!this.vm.acquisitionCapabilities) throw new Error("Backend lacks acquisition-capabilities; upgrade machine-service for VNC");
29003
29127
  return acquisitionCapabilities(await this.vm.acquisitionCapabilities({ signal, timeoutMs: 1e4 }));
29004
29128
  }
29005
29129
  acquisitionCapabilities(signal) {
@@ -29050,6 +29174,9 @@ var RelayManager = class {
29050
29174
  const network2 = this.options.guestNetwork ?? guestNetwork();
29051
29175
  if (!GUEST_NETWORKS.includes(network2)) throw new Error(`guestNetwork must be nat or internet, not ${JSON.stringify(network2)}`);
29052
29176
  if (typeof input.task !== "string" || !TASK.test(input.task)) throw new Error("task must be a lowercase slug (1\u201336 chars)");
29177
+ if (input.image === void 0 === (input.machine === void 0)) throw new Error("relay_acquire takes exactly one of image, a VM image, and machine, a durable machine's name");
29178
+ if (input.machine !== void 0 && (typeof input.machine !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(input.machine))) throw new Error("machine must be a durable machine's name, as machctl list shows it");
29179
+ if (input.machine !== void 0 && input.vnc) throw new Error("A durable machine has no console: view it with Screen Sharing, outside the relay; nothing was acquired");
29053
29180
  if (!Array.isArray(input.extractions) || input.extractions.length > 100) throw new Error("Declare up to 100 extractions before work");
29054
29181
  const names = /* @__PURE__ */ new Set();
29055
29182
  for (const extraction of input.extractions) {
@@ -29244,6 +29371,53 @@ var Guest = class {
29244
29371
  closed = false;
29245
29372
  /** After-image downloads, outside the serialized section (docs/screenshot-delivery.md §10). */
29246
29373
  downloads;
29374
+ /** A durable machine's owner, once found (DC-29). */
29375
+ owner;
29376
+ /** The backend this guest's lease lives on: the loopback instance, or a durable machine's owner. */
29377
+ get vm() {
29378
+ const e = this.enclosure;
29379
+ if (!e?.machine) return this.m.vm;
29380
+ if (this.owner) return this.owner;
29381
+ if (!e.backend?.endpoint || e.backend.endpoint === this.m.vm.baseUrl) return this.owner = this.m.vm;
29382
+ throw new Error(`The owner of durable machine ${e.machine} has not been found again in this process; nothing was sent`);
29383
+ }
29384
+ /**
29385
+ * machine-service as the guest's only channel. Every call names the lease's
29386
+ * `lease_id` (DC-30); on a durable machine every file goes as bytes (DC-31).
29387
+ */
29388
+ get channel() {
29389
+ const identity = () => {
29390
+ const id2 = this.enclosure?.lease?.lease_id;
29391
+ return id2 ? { lease_id: id2 } : {};
29392
+ };
29393
+ const durable = !!this.enclosure?.machine;
29394
+ return {
29395
+ exec: async (name, argv, timeoutMs2 = 18e4, options) => {
29396
+ const result2 = await this.vm.exec(name, { argv, timeout: Math.ceil(timeoutMs2 / 1e3), ...identity() }, { timeoutMs: options?.timeoutMs ?? timeoutMs2 + 3e4, signal: options?.signal });
29397
+ return { stdout: result2.output, stderr: result2.output, code: result2.rc };
29398
+ },
29399
+ push: async (name, local_path, remote_path) => {
29400
+ if (!durable) return this.vm.push(name, { local_path, remote_path, ...identity() });
29401
+ if (!this.vm.pushBytes) throw new Error("Backend lacks byte transfers; upgrade machine-service");
29402
+ return this.vm.pushBytes(name, { remote_path, bytes: await readFile9(local_path), ...identity() });
29403
+ },
29404
+ pull: async (name, remote_path, local_path, options) => {
29405
+ if (!durable) return this.vm.pull(name, { remote_path, local_path, ...identity() }, options);
29406
+ if (!this.vm.pullBytes) throw new Error("Backend lacks byte transfers; upgrade machine-service");
29407
+ const bytes = await this.vm.pullBytes(name, { remote_path, maxBytes: PULL_MAX_BYTES, ...identity() }, options);
29408
+ await rm4(local_path, { force: true });
29409
+ await writeFile4(local_path, bytes, { flag: "wx", mode: 384 });
29410
+ return { vm: name, pulled: remote_path, to: local_path };
29411
+ }
29412
+ };
29413
+ }
29414
+ /** Find a durable machine's owner again, and refuse when its origin or instance changed (DC-29). */
29415
+ async findOwner(e) {
29416
+ if (!e.machine || this.owner) return;
29417
+ const owner = await this.m.durableOwner(e.machine);
29418
+ if (e.backend?.endpoint && (owner.origin !== e.backend.endpoint || owner.instance !== e.backend.instance)) throw new Error(`Durable machine ${e.machine} is now listed by ${owner.origin} (${owner.instance}), not by ${e.backend.endpoint} (${e.backend.instance}) where this guest leased it; ownership retained, nothing was sent`);
29419
+ this.owner = owner.backend;
29420
+ }
29247
29421
  serialized(fn) {
29248
29422
  const next = this.queue.then(fn, fn);
29249
29423
  this.queue = next.catch(() => {
@@ -29296,15 +29470,25 @@ var Guest = class {
29296
29470
  if (!e) return;
29297
29471
  this.assertBinding();
29298
29472
  await this.m.assertBackend();
29473
+ await this.findOwner(e);
29299
29474
  e.backend ??= this.m.binding();
29300
29475
  if (!e.lease) {
29301
- const matches = Object.values((await this.m.vm.list({ timeoutMs: 1e4 })).vms).filter((v) => v.purpose === e.purpose);
29476
+ const matches = Object.values((await this.vm.list({ timeoutMs: 1e4 })).machines).filter((v) => v.purpose === e.purpose);
29302
29477
  if (matches.length !== 1) throw new Error(`Cannot reconcile acquisition for ${e.purpose}; ownership retained, never automatically reacquire`);
29303
29478
  e.lease = matches[0];
29304
29479
  e.acquisitionInFlight = false;
29480
+ if (e.machine && e.lease.workspace) e.guestRoot = durableRoot(e.lease.workspace, e.purpose);
29305
29481
  }
29306
29482
  try {
29307
- const lease = await this.m.vm.get(e.lease.vm, { timeoutMs: 1e4 });
29483
+ const lease = await this.vm.get(e.lease.vm, { timeoutMs: 1e4 });
29484
+ if (e.machine && lease.lease_id !== e.lease.lease_id) {
29485
+ await this.m.registry.remove(e.row);
29486
+ await jsonFile(`${e.hostRoot}.lifecycle.json`, { purpose: e.purpose, machine: e.machine, released: true, reason: "the durable machine no longer names this lease", finishedAt: (/* @__PURE__ */ new Date()).toISOString() });
29487
+ this.enclosure = void 0;
29488
+ await this.save();
29489
+ await this.m.forget(this);
29490
+ return;
29491
+ }
29308
29492
  if (lease.purpose !== e.purpose || e.lease.lease_id && lease.lease_id !== e.lease.lease_id) throw new Error("Lease ownership identity mismatch");
29309
29493
  if (e.lease.console?.console_id && lease.console?.console_id !== e.lease.console.console_id) throw new Error("Console instance identity mismatch during lease reconciliation");
29310
29494
  if (lease.console) {
@@ -29321,7 +29505,7 @@ var Guest = class {
29321
29505
  await this.save();
29322
29506
  } catch (error2) {
29323
29507
  e.guestState = "unknown";
29324
- if (error2 instanceof VmServiceError && error2.status === 404 && await this.destroyed(e.lease.vm)) {
29508
+ if (error2 instanceof MachineServiceError && error2.status === 404 && await this.destroyed(e.lease.vm)) {
29325
29509
  await this.m.registry.remove(e.row);
29326
29510
  await jsonFile(`${e.hostRoot}.lifecycle.json`, { purpose: e.purpose, vm: e.lease.vm, released: true, reason: "backend lease absent and destruction verified", finishedAt: (/* @__PURE__ */ new Date()).toISOString() });
29327
29511
  this.enclosure = void 0;
@@ -29352,7 +29536,7 @@ var Guest = class {
29352
29536
  for (const [name, language2, argv] of [["node", "javascript", [e.node ?? "node", "--version"]], ["tsx", "typescript", ["tsx", "--version"]], ["python3", "python", ["python3", "--version"]], ["sh", "shell", ["/bin/sh", "-c", "exit 0"]]]) {
29353
29537
  const required2 = name === "node";
29354
29538
  try {
29355
- const r = await this.m.channel.exec(e.lease.vm, [...argv], 1e4);
29539
+ const r = await this.channel.exec(e.lease.vm, [...argv], 1e4);
29356
29540
  checks.push({ name, language: language2, required: required2, ...r, ready: r.code === 0 });
29357
29541
  } catch (error2) {
29358
29542
  checks.push({ name, language: language2, required: required2, ready: false, diagnostic: String(error2) });
@@ -29361,15 +29545,16 @@ var Guest = class {
29361
29545
  const tsx = checks[1], nodeVersion = /^v(\d+)\.(\d+)/.exec(String(checks[0].stdout ?? ""));
29362
29546
  if (!tsx.ready && nodeVersion && (Number(nodeVersion[1]) > 22 || Number(nodeVersion[1]) === 22 && Number(nodeVersion[2]) >= 6)) Object.assign(tsx, { ready: true, runsWith: "Node.js type stripping" });
29363
29547
  let software;
29364
- try {
29365
- const catalog = await this.m.vm.applications({ timeoutMs: 1e4 });
29548
+ if (e.machine) software = { machine: e.machine, software: (await this.vm.get(e.lease.vm, { timeoutMs: 1e4 })).capabilities?.software ?? null };
29549
+ else try {
29550
+ const catalog = await this.vm.applications({ timeoutMs: 1e4 });
29366
29551
  validateCatalog(catalog);
29367
29552
  const listed = catalog.images.find((image) => image.image === e.image);
29368
29553
  software = listed ? { image: e.image, applications: listed.applications } : { image: e.image, applications: [], diagnostic: `The catalog does not list ${e.image}.` };
29369
29554
  } catch (error2) {
29370
29555
  software = { image: e.image, diagnostic: `The image catalog could not be read: ${message(error2)}` };
29371
29556
  }
29372
- const snapshots2 = e.capture === void 0 && !e.staged ? { taken: null, reason: "Decided at relay_stage: runs take snapshots only when the image lists capture software (cua-driver)." } : this.snapshotFacts(e);
29557
+ const snapshots2 = e.capture === void 0 && !e.staged ? { taken: null, reason: e.machine ? "Decided at relay_stage: runs take snapshots only when the machine's cua-driver daemon holds Screen Recording." : "Decided at relay_stage: runs take snapshots only when the image lists capture software (cua-driver)." } : this.snapshotFacts(e);
29373
29558
  const facts = { scope: "guest", guest: this.name, observedAt: (/* @__PURE__ */ new Date()).toISOString(), owned: this.status(), checks, software, snapshots: snapshots2, note: "A ready runtime means its --version, or for /bin/sh `exit 0`, exited 0. Listed software is what the catalog says the image holds; it never proves that a program runs, that a browser renders on the display or that capture works.", captureVerified: false, browserVerified: false };
29374
29559
  await this.log("guest-readiness", void 0, facts);
29375
29560
  return facts;
@@ -29385,10 +29570,10 @@ var Guest = class {
29385
29570
  }
29386
29571
  async resolveConsole(signal) {
29387
29572
  const e = await this.consoleOwner(signal);
29388
- if (!this.m.vm.consoleResolve) throw new Error("Backend lacks console API; upgrade vm-service");
29573
+ if (!this.vm.consoleResolve) throw new Error("Backend lacks console API; upgrade machine-service");
29389
29574
  let observation;
29390
29575
  try {
29391
- observation = consoleStatus(await this.m.vm.consoleResolve(e.lease.vm, { lease_id: e.lease.lease_id }, { signal, timeoutMs: 1e4 }));
29576
+ observation = consoleStatus(await this.vm.consoleResolve(e.lease.vm, { lease_id: e.lease.lease_id }, { signal, timeoutMs: 1e4 }));
29392
29577
  } catch (error2) {
29393
29578
  if (e.consoleObservation && e.consoleObservation.status !== "revoked") e.consoleObservation = { ...e.consoleObservation, status: "unknown" };
29394
29579
  await this.save();
@@ -29411,8 +29596,8 @@ var Guest = class {
29411
29596
  const resolved = await this.resolveConsole(signal), e = this.current();
29412
29597
  if (!e.lease.console?.console_id) throw new Error("This lease has no acquired console; automatic VNC retrofit is forbidden");
29413
29598
  if (resolved.console_id !== input.console_id) throw new Error("Console instance identity mismatch");
29414
- const method = operation === "open" ? this.m.vm.consoleOpen : this.m.vm.consoleCancel;
29415
- if (!method) throw new Error("Backend lacks console API; upgrade vm-service");
29599
+ const method = operation === "open" ? this.vm.consoleOpen : this.vm.consoleCancel;
29600
+ if (!method) throw new Error("Backend lacks console API; upgrade machine-service");
29416
29601
  if (operation === "open") {
29417
29602
  if (resolved.viewer_location !== "service-host") throw new Error("Only a viewer on the declared service host is supported; no remote-client viewer fallback");
29418
29603
  if (e.lease.state !== "running" || !Number.isFinite(e.lease.ttl_expires_at) || e.lease.ttl_expires_at <= Date.now() / 1e3) throw new Error("Console lease is not running or has expired");
@@ -29430,7 +29615,7 @@ var Guest = class {
29430
29615
  await this.save();
29431
29616
  await this.log(`console-${operation}-intent`, "reason" in input ? input.reason : void 0, { ...body, ..."expected" in input ? { expected: input.expected } : {}, screenshotEvidence: false });
29432
29617
  try {
29433
- const observation = consoleStatus(await method.call(this.m.vm, e.lease.vm, body, { signal, timeoutMs: 3e4 }));
29618
+ const observation = consoleStatus(await method.call(this.vm, e.lease.vm, body, { signal, timeoutMs: 3e4 }));
29434
29619
  this.assertConsoleIdentity(observation, e);
29435
29620
  if (observation.console_id !== body.console_id || observation.attempt?.attempt_id !== body.attempt_id) throw new Error("Console response identity mismatch");
29436
29621
  e.consoleObservation = observation;
@@ -29451,7 +29636,7 @@ var Guest = class {
29451
29636
  transfer() {
29452
29637
  const e = this.current();
29453
29638
  if (!e.node) throw new Error("Stage runtime first");
29454
- return new Transfer(this.m.channel, e.lease.vm, e.node, { guestRoot: e.guestRoot, hostTempRoot: join13(this.m.root, "transfer-tmp"), onRetry: (event) => this.log("transfer-retry", void 0, event), onArchiveFallback: (event) => this.log("archive-fallback", void 0, event) });
29639
+ return new Transfer(this.channel, e.lease.vm, e.node, { guestRoot: e.guestRoot, hostTempRoot: join13(this.m.root, "transfer-tmp"), onRetry: (event) => this.log("transfer-retry", void 0, event), onArchiveFallback: (event) => this.log("archive-fallback", void 0, event) });
29455
29640
  }
29456
29641
  async log(kind, because, details = {}) {
29457
29642
  if (because !== void 0) this.m.reason(because);
@@ -29460,19 +29645,23 @@ var Guest = class {
29460
29645
  }
29461
29646
  /**
29462
29647
  * The acquisition, in this guest's own order. Its ownership intent is
29463
- * persisted and registered before vm-service is asked. A refusal before
29464
- * that, or vm-service's own refusal, leaves the session without the guest;
29648
+ * persisted and registered before machine-service is asked. A refusal before
29649
+ * that, or machine-service's own refusal, leaves the session without the guest;
29465
29650
  * any other failure keeps the guest's record for reconciliation.
29466
29651
  */
29467
29652
  async acquire(input, network, signal) {
29468
29653
  const ttlHours = input.ttlHours ?? 4;
29654
+ let owner;
29469
29655
  try {
29470
29656
  if (this.m.shuttingDown || this.closed) throw new Error("Relay manager is shutting down");
29471
- const images = await this.m.vm.images({ timeoutMs: 5e3, signal });
29472
- if (!images.images[input.image]?.base_available) throw new Error(`Image unavailable: ${input.image}`);
29473
- if (input.vnc) {
29474
- const capabilities = await this.m.readAcquisitionCapabilities(signal);
29475
- if (!capabilities.options.vnc.backends[images.images[input.image].kind].available) throw new Error("VNC backend unavailable for this image OS; ordinary acquisition was not attempted");
29657
+ if (input.machine) owner = await this.m.durableOwner(input.machine);
29658
+ else {
29659
+ const image = input.image, images = await this.vm.images({ timeoutMs: 5e3, signal });
29660
+ if (!images.images[image]?.base_available) throw new Error(`Image unavailable: ${image}`);
29661
+ if (input.vnc) {
29662
+ const capabilities = await this.m.readAcquisitionCapabilities(signal);
29663
+ if (!capabilities.options.vnc.backends[images.images[image].kind].available) throw new Error("VNC backend unavailable for this image OS; ordinary acquisition was not attempted");
29664
+ }
29476
29665
  }
29477
29666
  await this.lock();
29478
29667
  } catch (error2) {
@@ -29484,8 +29673,10 @@ var Guest = class {
29484
29673
  const stamp = startedAt.slice(0, 19).replace(/[T:]/g, "-") + "-Z";
29485
29674
  const project = this.m.options.project, environment = this.m.environment;
29486
29675
  const hostRoot = join13(this.m.options.outputRoot ?? resolve9(project, "relay-evidence"), purpose);
29487
- const row = { machine: environment ? `${environment.profile.vmServiceUrl} (${environment.profile.id}; ${purpose})` : `127.0.0.1 (vm-service ${purpose})`, os: input.image, taskName: purpose, agent: `mcp-relay ${this.m.options.sessionId}`, project: resolve9(project), startDate: stamp };
29488
- const e = this.enclosure = { backend: this.m.binding(), purpose, task: input.task, image: input.image, project, startedAt, guestRoot: `/var/tmp/${stamp}-mcp-relay-${purpose}`, hostRoot, ttlHours, extractions: input.extractions, fullWorkspace: input.fullWorkspace ?? false, row, staged: false };
29676
+ const subject = input.machine ?? input.image;
29677
+ const row = { machine: owner ? `${input.machine} (durable, ${owner.origin}; ${purpose})` : environment ? `${environment.profile.vmServiceUrl} (${environment.profile.id}; ${purpose})` : `127.0.0.1 (machine-service ${purpose})`, os: owner ? "macos (durable)" : subject, taskName: purpose, agent: `mcp-relay ${this.m.options.sessionId}`, project: resolve9(project), startDate: stamp };
29678
+ const e = this.enclosure = { backend: owner ? { endpoint: owner.origin, instance: owner.instance } : this.m.binding(), purpose, task: input.task, image: subject, ...input.machine ? { machine: input.machine } : {}, project, startedAt, guestRoot: `/var/tmp/${stamp}-mcp-relay-${purpose}`, hostRoot, ttlHours, extractions: input.extractions, fullWorkspace: input.fullWorkspace ?? false, row, staged: false };
29679
+ if (owner) this.owner = owner.backend;
29489
29680
  let refused = false;
29490
29681
  try {
29491
29682
  await this.save();
@@ -29508,17 +29699,19 @@ var Guest = class {
29508
29699
  await this.save();
29509
29700
  const asked = Date.now();
29510
29701
  try {
29511
- e.lease = await this.m.vm.acquire({ purpose, image: input.image, env: input.env ?? "none", ttl_hours: Math.min(this.m.renewalWindowMs(), ttlHours * 36e5) / 36e5, wait: true, network, ...input.vnc === void 0 ? {} : { vnc: input.vnc } }, { signal });
29702
+ const ttl_hours = Math.min(this.m.renewalWindowMs(), ttlHours * 36e5) / 36e5;
29703
+ e.lease = await this.vm.acquire(input.machine ? { purpose, machine: input.machine, env: input.env ?? "none", ttl_hours } : { purpose, image: input.image, env: input.env ?? "none", ttl_hours, wait: true, network, ...input.vnc === void 0 ? {} : { vnc: input.vnc } }, { signal });
29704
+ if (e.machine) e.guestRoot = durableRoot(e.lease.workspace, purpose);
29512
29705
  e.acquisitionInFlight = false;
29513
29706
  granted = asked;
29514
29707
  break;
29515
29708
  } catch (error2) {
29516
29709
  if (signal?.aborted && error2 === signal.reason) e.acquisitionInFlight = false;
29517
- else if (error2 instanceof VmServiceError && error2.status !== void 0 && error2.status >= 400 && error2.status < 500) {
29710
+ else if (error2 instanceof MachineServiceError && error2.status !== void 0 && error2.status >= 400 && error2.status < 500) {
29518
29711
  e.acquisitionInFlight = false;
29519
29712
  refused = true;
29520
29713
  }
29521
- if (!refused || !(error2 instanceof VmServiceError && error2.capacity) || this.m.capacityWaitMs <= 0) throw error2;
29714
+ if (!refused || !(error2 instanceof MachineServiceError && error2.capacity) || this.m.capacityWaitMs <= 0) throw error2;
29522
29715
  firstRefusal ??= asked;
29523
29716
  await this.waitForCapacity(e, error2, firstRefusal, signal);
29524
29717
  refused = false;
@@ -29540,7 +29733,7 @@ var Guest = class {
29540
29733
  this.startHeartbeat();
29541
29734
  await this.save();
29542
29735
  if (signal?.aborted) throw new Error(`${String(signal.reason)}; the acquisition completed after it was cancelled: VM ${e.lease.vm} is owned by this session as guest ${this.name}, retained and renewed. Continue with relay_stage, or call relay_finish or relay_release, naming guest ${this.name}.`, { cause: signal.reason });
29543
- return { ...this.status(), guestRoot: e.guestRoot, workspace: join13(e.guestRoot, "workspace"), declarations: input.extractions, network, waitedForCapacityMs };
29736
+ return { ...this.status(), guestRoot: e.guestRoot, workspace: join13(e.guestRoot, "workspace"), declarations: input.extractions, ...e.machine ? { machine: e.machine, kind: "durable", network: "lan" } : { network }, waitedForCapacityMs };
29544
29737
  } catch (error2) {
29545
29738
  if (refused && await this.withdraw(error2)) throw error2;
29546
29739
  await this.fail(error2);
@@ -29552,7 +29745,7 @@ Guest ${this.name} keeps this acquisition's ownership record: name it to reconci
29552
29745
  /**
29553
29746
  * The host is at capacity: wait one retry interval, or what is left of
29554
29747
  * MCP_RELAY_CAPACITY_WAIT, before the acquisition is asked again. Refuses
29555
- * with vm-service's reason and the time waited once the wait has run out,
29748
+ * with machine-service's reason and the time waited once the wait has run out,
29556
29749
  * or when the call is cancelled or the session ends (DC-22).
29557
29750
  */
29558
29751
  async waitForCapacity(e, refusal, since, signal) {
@@ -29578,16 +29771,16 @@ Guest ${this.name} keeps this acquisition's ownership record: name it to reconci
29578
29771
  if (stop.aborted) throw new Error(`${signal?.aborted ? String(signal.reason) : "The relay session ended"} while the acquisition waited ${seconds(Date.now() - since)} s for capacity (${refusal.message}), so nothing was acquired`, { cause: refusal });
29579
29772
  }
29580
29773
  /**
29581
- * A refused acquisition acquired nothing: once vm-service lists no VM for
29774
+ * A refused acquisition acquired nothing: once machine-service lists no VM for
29582
29775
  * its purpose, its registry row goes and the guest leaves the session.
29583
29776
  * False when that cannot be established, so the record stays.
29584
29777
  */
29585
29778
  async withdraw(error2) {
29586
29779
  const e = this.enclosure;
29587
29780
  try {
29588
- if (Object.values((await this.m.vm.list({ timeoutMs: 1e4 })).vms).some((lease) => lease.purpose === e.purpose)) return false;
29781
+ if (Object.values((await this.vm.list({ timeoutMs: 1e4 })).machines).some((lease) => lease.purpose === e.purpose)) return false;
29589
29782
  await this.m.registry.remove(e.row);
29590
- await jsonFile(`${e.hostRoot}.lifecycle.json`, { purpose: e.purpose, released: false, acquired: false, reason: "vm-service refused the acquisition", error: String(error2), finishedAt: (/* @__PURE__ */ new Date()).toISOString() });
29783
+ await jsonFile(`${e.hostRoot}.lifecycle.json`, { purpose: e.purpose, released: false, acquired: false, reason: "machine-service refused the acquisition", error: String(error2), finishedAt: (/* @__PURE__ */ new Date()).toISOString() });
29591
29784
  this.enclosure = void 0;
29592
29785
  await this.save();
29593
29786
  await this.m.forget(this);
@@ -29639,7 +29832,7 @@ Guest ${this.name} keeps this acquisition's ownership record: name it to reconci
29639
29832
  }
29640
29833
  this.assertBinding();
29641
29834
  await this.m.assertBackend();
29642
- const renewed = await this.m.vm.heartbeat(lease.vm, { ttl_hours: Math.min(this.m.renewalWindowMs(), remaining) / 36e5 }, { timeoutMs: 1e4 });
29835
+ const renewed = await this.vm.heartbeat(lease.vm, { ttl_hours: Math.min(this.m.renewalWindowMs(), remaining) / 36e5, ...lease.lease_id ? { lease_id: lease.lease_id } : {} }, { timeoutMs: 1e4 });
29643
29836
  if (this.enclosure !== e || e.released) return;
29644
29837
  e.expiresAt = renewed.ttl_expires_at;
29645
29838
  e.guestState = renewed.state;
@@ -29692,18 +29885,24 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29692
29885
  const workspace = input.workspace === void 0 ? void 0 : await this.m.projectPath(input.workspace, "workspace");
29693
29886
  const bundle = this.m.options.runtimeBundle ?? fileURLToPath(new URL("../dist/receiver.mjs", import.meta.url));
29694
29887
  await access(bundle);
29695
- if (e.capture === void 0 && !e.staged) {
29888
+ if (!e.machine && e.capture === void 0 && !e.staged) {
29696
29889
  e.capture = await this.captureSoftware(e, signal);
29697
29890
  await this.save();
29698
29891
  }
29699
29892
  const node2 = input.nodePath ?? e.node ?? "node";
29700
- const transfer = new Transfer(this.m.channel, e.lease.vm, node2, { guestRoot: e.guestRoot, hostTempRoot: join13(this.m.root, "transfer-tmp"), onRetry: (event) => this.log("transfer-retry", void 0, event), onArchiveFallback: (event) => this.log("archive-fallback", void 0, event) });
29893
+ const transfer = new Transfer(this.channel, e.lease.vm, node2, { guestRoot: e.guestRoot, hostTempRoot: join13(this.m.root, "transfer-tmp"), onRetry: (event) => this.log("transfer-retry", void 0, event), onArchiveFallback: (event) => this.log("archive-fallback", void 0, event) });
29701
29894
  try {
29702
29895
  await transfer.checked([node2, "--version"]);
29703
29896
  } catch (error2) {
29704
29897
  throw new Error(`relay_stage needs Node.js in the guest to run the relay's own code, and \`${node2} --version\` failed: ${error2 instanceof Error ? error2.message : String(error2)}. The relay pushes no runtime, so an image without Node.js cannot be staged; choose an image that lists Node.js (relay_search), or name the guest's Node.js with nodePath.`, { cause: error2 });
29705
29898
  }
29706
- const cuaDriver = input.cuaDriver ?? e.cuaDriver ?? (e.lease.image_kind === "macos" ? "/Applications/CuaDriver.app/Contents/MacOS/cua-driver" : "cua-driver");
29899
+ const cuaDriver = input.cuaDriver ?? e.cuaDriver ?? (e.lease.image_kind === "macos" || e.machine ? "/Applications/CuaDriver.app/Contents/MacOS/cua-driver" : "cua-driver");
29900
+ if (e.machine) {
29901
+ const decision = await this.durableCapture(e, cuaDriver, signal);
29902
+ e.capture = decision.capture;
29903
+ e.captureReason = decision.reason;
29904
+ await this.save();
29905
+ }
29707
29906
  if (e.capture !== false) await this.awaitCapture(transfer, e, node2, cuaDriver, signal);
29708
29907
  e.node = node2;
29709
29908
  e.cuaDriver = cuaDriver;
@@ -29722,7 +29921,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29722
29921
  this.transport = new VmTransport(transfer, e.guestRoot, join13(e.hostRoot, "host"), e.cuaDriver);
29723
29922
  this.transport.capture = e.capture !== false;
29724
29923
  relay.useTransport(() => this.transport);
29725
- this.session = await relay.start({ taskId: e.purpose, target: `vm-service:${e.lease.vm}` });
29924
+ this.session = await relay.start({ taskId: e.purpose, target: `machine-service:${e.machine ? `durable:${e.machine}` : e.lease.vm}` });
29726
29925
  e.sessionId = this.session.sessionId;
29727
29926
  e.staged = true;
29728
29927
  await this.save();
@@ -29736,7 +29935,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29736
29935
  async captureSoftware(e, signal) {
29737
29936
  let catalog;
29738
29937
  try {
29739
- catalog = await this.m.vm.applications({ timeoutMs: 1e4, signal });
29938
+ catalog = await this.vm.applications({ timeoutMs: 1e4, signal });
29740
29939
  validateCatalog(catalog);
29741
29940
  } catch (error2) {
29742
29941
  throw new Error(`relay_stage could not read the image catalog to learn whether ${e.image} lists capture software (cua-driver), so nothing was staged: ${error2 instanceof Error ? error2.message : String(error2)}`, { cause: error2 });
@@ -29745,6 +29944,26 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29745
29944
  await this.log("capture-software", void 0, { image: e.image, capture, ids: CAPTURE_SOFTWARE });
29746
29945
  return capture;
29747
29946
  }
29947
+ /**
29948
+ * Whether a durable machine's runs take snapshots: its capabilities list
29949
+ * cua-driver, and the cua-driver daemon, not machine-service, holds Screen
29950
+ * Recording (DC-32).
29951
+ */
29952
+ async durableCapture(e, cuaDriver, signal) {
29953
+ const software = (await this.vm.get(e.lease.vm, { timeoutMs: 1e4, signal })).capabilities?.software;
29954
+ let answer;
29955
+ if (software && typeof software === "object" && software.cua_driver) {
29956
+ try {
29957
+ answer = await this.channel.exec(e.lease.vm, [cuaDriver, "permissions", "status", "--json"], 3e4, { signal });
29958
+ } catch (error2) {
29959
+ if (signal?.aborted) throw error2;
29960
+ answer = { error: message(error2) };
29961
+ }
29962
+ }
29963
+ const decision = durableCapture(e.machine, software, answer);
29964
+ await this.log("capture-permission", void 0, { machine: e.machine, ...decision, answer });
29965
+ return decision;
29966
+ }
29748
29967
  /**
29749
29968
  * Waits until the guest's cua-driver takes a screenshot, as each run's
29750
29969
  * snapshots do (DC-24). The image starts its daemon at login, which can
@@ -29778,13 +29997,14 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29778
29997
  }
29779
29998
  /** What a lease's runs record: snapshots when its image lists cua-driver, none otherwise. */
29780
29999
  snapshotFacts(e) {
30000
+ if (e.machine) return { taken: e.capture === true, reason: e.captureReason ?? "Decided at relay_stage." };
29781
30001
  return e.capture === false ? { taken: false, reason: `${e.image} lists no capture software (cua-driver), so runs take no snapshots and their records have none.` } : { taken: true, reason: e.capture ? `${e.image} lists cua-driver, so each run takes before and after snapshots.` : "This lease predates the capture decision, so each run takes before and after snapshots." };
29782
30002
  }
29783
30003
  async run(input, signal) {
29784
30004
  const e = this.current();
29785
30005
  const timeoutMs2 = input.timeoutMs ?? 12e4;
29786
30006
  if (!Number.isSafeInteger(timeoutMs2) || timeoutMs2 < 1 || timeoutMs2 > 36e5) throw new Error("timeoutMs must be an integer from 1 to 3600000");
29787
- if (input.diagnostic && input.language !== "shell") throw new Error("Only a shell script may be diagnostic, because a diagnostic run goes through vm-service without the receiver");
30007
+ if (input.diagnostic && input.language !== "shell") throw new Error("Only a shell script may be diagnostic, because a diagnostic run goes through machine-service without the receiver");
29788
30008
  if (e.delivered) throw new Error("Evidence already sealed; release this VM explicitly");
29789
30009
  if (input.diagnostic) return this.diagnostic(input, timeoutMs2, signal);
29790
30010
  if (e.pendingReset) throw new Error("Recording reset is pending; retry stage to reconcile it, or use a shell relay_script with diagnostic: true");
@@ -29852,14 +30072,14 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29852
30072
  ensureGuest: async (signal, deadline) => {
29853
30073
  const options = { signal, timeoutMs: Math.max(1, Math.min(1e4, deadline - Date.now())) };
29854
30074
  if (this.m.environment) {
29855
- const health = await this.m.vm.health(options);
30075
+ const health = await this.vm.health(options);
29856
30076
  if (!health.ok || !matchesEnvironment(health.environment, this.m.environment)) throw Object.assign(new Error("Selected backend identity changed."), { code: "unauthorized-reference" });
29857
30077
  }
29858
30078
  try {
29859
- const lease = await this.m.vm.get(e.lease.vm, options);
29860
- if (lease.purpose !== e.purpose) throw Object.assign(new Error("Lease ownership identity changed."), { code: "unauthorized-reference" });
30079
+ const lease = await this.vm.get(e.lease.vm, options);
30080
+ if (lease.purpose !== e.purpose || e.lease.lease_id && lease.lease_id !== e.lease.lease_id) throw Object.assign(new Error("Lease ownership identity changed."), { code: "unauthorized-reference" });
29861
30081
  } catch (error2) {
29862
- if (error2 instanceof VmServiceError && error2.status === 404) throw Object.assign(new Error("Saved image guest is no longer available."), { code: "stale-reference" });
30082
+ if (error2 instanceof MachineServiceError && error2.status === 404) throw Object.assign(new Error("Saved image guest is no longer available."), { code: "stale-reference" });
29863
30083
  throw error2;
29864
30084
  }
29865
30085
  }
@@ -29886,16 +30106,16 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29886
30106
  }
29887
30107
  const store = this.imageStore(), result2 = await store.get(target, bounded3, deadline);
29888
30108
  if (result2.status !== "unauthorized-reference" || target.source !== "reference") return result2;
29889
- const named = job?.image ?? await this.namedImage(target.imageId);
29890
- if (named?.source !== "display") return result2;
29891
- const resolved = await store.get({ source: "display", sessionId: named.sessionId, executionId: named.executionId, phase: named.phase }, bounded3, deadline);
30109
+ const named2 = job?.image ?? await this.namedImage(target.imageId);
30110
+ if (named2?.source !== "display") return result2;
30111
+ const resolved = await store.get({ source: "display", sessionId: named2.sessionId, executionId: named2.executionId, phase: named2.phase }, bounded3, deadline);
29892
30112
  return resolved.image && resolved.image.imageId !== target.imageId ? { status: "integrity-failed", diagnostic: "The display selector no longer names the referenced image." } : resolved;
29893
30113
  }
29894
30114
  /** The image a run named with this reference, from the step download records. No guest I/O. */
29895
30115
  async namedImage(imageId) {
29896
30116
  const records = join13(this.current().hostRoot, "host", "evidence-downloads");
29897
30117
  for (const name of (await readdir7(records).catch(() => [])).filter((n) => n.endsWith(".json"))) {
29898
- const image = await readFile9(join13(records, name), "utf8").then((text4) => JSON.parse(text4)?.image, () => void 0);
30118
+ const image = await readFile9(join13(records, name), "utf8").then((text5) => JSON.parse(text5)?.image, () => void 0);
29899
30119
  if (image?.imageId === imageId) return image;
29900
30120
  }
29901
30121
  return void 0;
@@ -30170,7 +30390,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30170
30390
  await jsonFile(join13(e.hostRoot, "host", "diagnostics", `${executionId}.request.json`), request);
30171
30391
  let result2;
30172
30392
  try {
30173
- const r = await this.m.channel.exec(e.lease.vm, argv, timeoutMs2, { signal });
30393
+ const r = await this.channel.exec(e.lease.vm, argv, timeoutMs2, { signal });
30174
30394
  result2 = { executionId, outcome: { kind: "completed", exitStatus: { code: r.code, signal: null } }, output: r.stdout, outputStreams: "stdout and stderr combined" };
30175
30395
  } catch (error2) {
30176
30396
  result2 = { executionId, outcome: { kind: "uncertain", diagnostic: String(error2) }, output: "", outputStreams: "stdout and stderr combined" };
@@ -30243,11 +30463,12 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30243
30463
  await this.m.assertBackend();
30244
30464
  const e = this.enclosure;
30245
30465
  if (!e) return;
30466
+ await this.findOwner(e);
30246
30467
  this.stopTimer();
30247
30468
  if (!e.released) {
30248
30469
  if (!e.lease) {
30249
- const list = await this.m.vm.list({ timeoutMs: 1e4 });
30250
- const matches = Object.values(list.vms).filter((lease) => lease.purpose === e.purpose);
30470
+ const list = await this.vm.list({ timeoutMs: 1e4 });
30471
+ const matches = Object.values(list.machines).filter((lease) => lease.purpose === e.purpose);
30251
30472
  if (matches.length > 1) throw new Error("Ambiguous acquisition; refusing to remove ownership record");
30252
30473
  if (!matches.length && e.acquisitionInFlight) throw new Error(`Acquire outcome still indeterminate for ${e.purpose}; ownership record retained at ${this.dir}. Reconcile before retrying; never blindly acquire again.`);
30253
30474
  e.lease = matches[0];
@@ -30258,17 +30479,26 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30258
30479
  let released = false;
30259
30480
  for (let attempt = 0; attempt < attempts; attempt++) {
30260
30481
  try {
30261
- const response = await this.m.vm.release(e.lease.vm, { reason: reason2 }, { timeoutMs: timeoutMs2 });
30262
- if (!response.released) throw new Error("vm-service did not confirm destruction");
30482
+ const response = await this.vm.release(e.lease.vm, { reason: reason2, ...e.lease.lease_id ? { lease_id: e.lease.lease_id } : {} }, { timeoutMs: timeoutMs2 });
30483
+ if (!response.released) throw new Error("machine-service did not confirm destruction");
30484
+ if (e.machine) {
30485
+ e.hygiene = response.hygiene;
30486
+ await this.save().catch(() => {
30487
+ });
30488
+ }
30263
30489
  released = true;
30264
30490
  break;
30265
30491
  } catch (error2) {
30266
30492
  await this.log("release-error", void 0, { vm: e.lease.vm, cause: reason2, attempt: attempt + 1, error: String(error2) }).catch(() => {
30267
30493
  });
30268
30494
  try {
30269
- await this.m.vm.get(e.lease.vm, { timeoutMs: 5e3 });
30495
+ const record3 = await this.vm.get(e.lease.vm, { timeoutMs: 5e3 });
30496
+ if (e.machine && record3.lease_id !== e.lease.lease_id) {
30497
+ released = true;
30498
+ break;
30499
+ }
30270
30500
  } catch (getError) {
30271
- if (getError instanceof VmServiceError && getError.status === 404) {
30501
+ if (getError instanceof MachineServiceError && getError.status === 404) {
30272
30502
  released = true;
30273
30503
  break;
30274
30504
  }
@@ -30277,7 +30507,9 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30277
30507
  }
30278
30508
  }
30279
30509
  if (!released) throw new Error("Lease release unconfirmed");
30280
- if (!await this.destroyed(e.lease.vm)) throw new Error(`vm-service relinquished ${e.lease.vm}, but Tart still lists it. Destruction is unverified; ownership retained. See docs/verification.md dependency limitation.`);
30510
+ if (e.machine) {
30511
+ if (!await this.durableReleased(e)) throw new Error(`machine-service confirmed the release of ${e.machine}, but the machine still names lease ${e.lease.lease_id}. The release is unverified; ownership retained.`);
30512
+ } else if (!await this.destroyed(e.lease.vm)) throw new Error(`machine-service relinquished ${e.lease.vm}, but Tart still lists it. Destruction is unverified; ownership retained. See docs/verification.md dependency limitation.`);
30281
30513
  }
30282
30514
  e.released = true;
30283
30515
  await this.save().catch(() => {
@@ -30287,12 +30519,16 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30287
30519
  await this.session?.close();
30288
30520
  this.session = void 0;
30289
30521
  this.transport = void 0;
30290
- await jsonFile(`${e.hostRoot}.lifecycle.json`, { purpose: e.purpose, guest: this.name, vm: e.lease?.vm, released: true, reason: reason2, failed: e.failed, delivered: e.delivered, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).catch(() => {
30522
+ await jsonFile(`${e.hostRoot}.lifecycle.json`, { purpose: e.purpose, guest: this.name, vm: e.lease?.vm, ...e.machine ? { machine: e.machine, lease_id: e.lease?.lease_id, hygiene: e.hygiene ?? null } : {}, released: true, reason: reason2, failed: e.failed, delivered: e.delivered, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).catch(() => {
30291
30523
  });
30292
30524
  this.enclosure = void 0;
30293
30525
  await this.save();
30294
30526
  await this.m.forget(this);
30295
30527
  }
30528
+ /** A durable release is verified when the machine no longer names the lease (DC-33). */
30529
+ async durableReleased(e) {
30530
+ return (await this.vm.get(e.lease.vm, { timeoutMs: 1e4 })).lease_id !== e.lease.lease_id;
30531
+ }
30296
30532
  async destroyed(vm) {
30297
30533
  if (this.m.options.verifyDestroyed) return this.m.options.verifyDestroyed(vm);
30298
30534
  const environment = this.m.environment;
@@ -30325,7 +30561,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30325
30561
  const remaining = this.remainingMs(e);
30326
30562
  if (remaining < MIN_RENEWAL_MS) return;
30327
30563
  try {
30328
- const renewed = await this.m.vm.heartbeat(e.lease.vm, { ttl_hours: remaining / 36e5 }, { timeoutMs: 1e4 });
30564
+ const renewed = await this.vm.heartbeat(e.lease.vm, { ttl_hours: remaining / 36e5, ...e.lease.lease_id ? { lease_id: e.lease.lease_id } : {} }, { timeoutMs: 1e4 });
30329
30565
  if (this.enclosure === e && !e.released) {
30330
30566
  e.expiresAt = renewed.ttl_expires_at;
30331
30567
  e.guestState = renewed.state;
@@ -30367,7 +30603,8 @@ var relayContract = typebox_exports.Union([
30367
30603
  typebox_exports.Object({
30368
30604
  action: typebox_exports.Literal("acquire"),
30369
30605
  task: typebox_exports.String({ pattern: "^[a-z0-9][a-z0-9-]{0,35}$" }),
30370
- image: typebox_exports.String({ description: "Image key from relay action=probe, e.g. ubuntu2404 or macos26." }),
30606
+ image: typebox_exports.Optional(typebox_exports.String({ description: "Image key from relay action=probe, e.g. ubuntu2404 or macos26, for a fresh VM. Give exactly one of image and machine." })),
30607
+ machine: typebox_exports.Optional(typebox_exports.String({ pattern: "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", description: "A durable machine, a real Mac leased whole, by the name machctl list shows, e.g. Build-Mac-1. Give exactly one of image and machine." })),
30371
30608
  extractions: typebox_exports.Array(typebox_exports.Object({ path: typebox_exports.String({ description: "Relative guest-workspace path; no traversal or symlinks." }), name: typebox_exports.String({ description: "Unique output basename." }) }, closed2), { maxItems: 100 }),
30372
30609
  vnc: typebox_exports.Optional(typebox_exports.Boolean({ description: "Prepare guest console sharing, default false. Never opens a viewer automatically." })),
30373
30610
  ttlHours: typebox_exports.Optional(typebox_exports.Number({ minimum: 0.1, maximum: 720 })),
@@ -30424,8 +30661,9 @@ function toolInputSchema(action) {
30424
30661
  function validateRelayInput(value) {
30425
30662
  if (!Check2(relayContract, value)) throw new Error("Invalid relay input: action is required; a call that acts on a guest names it with guest, the name relay_acquire answered; console-open requires nonblank reason. Supply only the fields for the selected action.");
30426
30663
  if (value.action === "probe" && value.scope === "guest" && value.guest === void 0) throw new Error('Invalid relay input: relay_probe with scope "guest" names the guest to probe with guest, the name relay_acquire answered.');
30664
+ if (value.action === "acquire" && value.image === void 0 === (value.machine === void 0)) throw new Error("Invalid relay input: relay_acquire takes exactly one of image, a VM image, and machine, a durable machine's name.");
30427
30665
  if (value.action === "run") {
30428
- if (value.diagnostic && value.language !== "shell") throw new Error("Invalid relay input: only a shell script may be diagnostic, because a diagnostic run goes through vm-service without the receiver.");
30666
+ if (value.diagnostic && value.language !== "shell") throw new Error("Invalid relay input: only a shell script may be diagnostic, because a diagnostic run goes through machine-service without the receiver.");
30429
30667
  if (value.diagnostic && value.snapshots?.group) throw new Error("Diagnostic scripts cannot join snapshot groups.");
30430
30668
  const given = value.inline ? value.code : value.localPath, other = value.inline ? value.localPath : value.code;
30431
30669
  if (given === void 0 || other !== void 0) throw new Error(value.inline ? "Invalid relay input: relay_script with inline: true takes the script as code, and no localPath." : "Invalid relay input: relay_script with inline: false takes the script file as localPath, and no code.");
@@ -30433,7 +30671,7 @@ function validateRelayInput(value) {
30433
30671
  }
30434
30672
 
30435
30673
  // src/surface.ts
30436
- import { mkdir as mkdir11, writeFile as writeFile4 } from "node:fs/promises";
30674
+ import { mkdir as mkdir11, writeFile as writeFile5 } from "node:fs/promises";
30437
30675
  import { join as join14 } from "node:path";
30438
30676
  import { tmpdir as tmpdir2 } from "node:os";
30439
30677
  import { randomUUID as randomUUID7 } from "node:crypto";
@@ -30464,9 +30702,9 @@ var relayTools = [
30464
30702
  {
30465
30703
  name: "relay_acquire",
30466
30704
  action: "acquire",
30467
- title: "Acquire a VM",
30705
+ title: "Acquire a machine",
30468
30706
  annotations: acts(false),
30469
- description: "Acquire one fresh VM, a guest, and start its ownership heartbeat. The result's `guest` is the guest's name in this session, such as `login-test-1`; every later call on this guest names it with `guest`. Requires `task` (a short slug), `image` (a key from relay_probe or relay_search) and `extractions`: every output you intend to bring home, declared before any work (`[]` is allowed; nothing is extracted automatically). Optional `ttlHours` (default 4), `env` (a credential pack, never baked into images), `fullWorkspace` (opt in to deliver the whole workspace) and `vnc` (default false; only prepares console-sharing capacity, never opens a viewer). Acquire one guest for each machine the work needs: several guests may run at once, each with its own lease, evidence and finish, up to the session's limit (relay_status reports `maxGuests`, MCP_RELAY_MAX_GUESTS, default 4); an acquisition beyond it is refused with the names of the guests held. When the host is at capacity, such as at its limit on running macOS VMs, the acquisition waits for it, asking again every 15 s for up to MCP_RELAY_CAPACITY_WAIT (30 minutes by default), and the result's `waitedForCapacityMs` says how long it waited; once the wait runs out it is refused with the backend's reason and the time waited. The backend's other refusals pass through at once. Continue with relay_stage, relay_script, relay_image/relay_extract, then relay_finish or relay_release explicitly before you return; a failed step keeps the VM for repair rather than replaying uncertain input."
30707
+ description: "Acquire one machine, a guest, and start its ownership heartbeat: a fresh VM from `image` (a key from relay_probe or relay_search), or a durable machine, a real Mac leased whole, by `machine` (its name as machctl list shows it, such as Build-Mac-1). Give exactly one of them. A durable machine is on the home network and not isolated from it, a CI job may share its desktop, it has no console (`vnc` is refused), and its runs take snapshots only while its cua-driver daemon holds Screen Recording; every other call works on it as on a VM. The result's `guest` is the guest's name in this session, such as `login-test-1`; every later call on this guest names it with `guest`. Requires `task` (a short slug), `image` or `machine`, and `extractions`: every output you intend to bring home, declared before any work (`[]` is allowed; nothing is extracted automatically). Optional `ttlHours` (default 4), `env` (a credential pack, never baked into images), `fullWorkspace` (opt in to deliver the whole workspace) and `vnc` (default false; only prepares console-sharing capacity, never opens a viewer). Acquire one guest for each machine the work needs: several guests may run at once, each with its own lease, evidence and finish, up to the session's limit (relay_status reports `maxGuests`, MCP_RELAY_MAX_GUESTS, default 4); an acquisition beyond it is refused with the names of the guests held. When the host is at capacity, such as at its limit on running macOS VMs, or the durable machine is leased by someone else, the acquisition waits for it, asking again every 15 s for up to MCP_RELAY_CAPACITY_WAIT (30 minutes by default), and the result's `waitedForCapacityMs` says how long it waited; once the wait runs out it is refused with the backend's reason and the time waited. The backend's other refusals pass through at once. Continue with relay_stage, relay_script, relay_image/relay_extract, then relay_finish or relay_release explicitly before you return; a failed step keeps the VM for repair rather than replaying uncertain input."
30470
30708
  },
30471
30709
  {
30472
30710
  name: "relay_stage",
@@ -30543,15 +30781,15 @@ function relayToolInput(name, args) {
30543
30781
  var relayResultKind = "relay-image-result-v1";
30544
30782
  async function renderRelayResult(value, resultRoot = join14(tmpdir2(), "mcp-relay-results"), indent = 2) {
30545
30783
  const full = JSON.stringify(value, null, indent);
30546
- const text4 = new TextDecoder().decode(Buffer.from(full.split("\n").slice(0, 2e3).join("\n")).subarray(0, 50 * 1024), { stream: true });
30547
- if (text4 !== full) {
30784
+ const text5 = new TextDecoder().decode(Buffer.from(full.split("\n").slice(0, 2e3).join("\n")).subarray(0, 50 * 1024), { stream: true });
30785
+ if (text5 !== full) {
30548
30786
  await mkdir11(resultRoot, { recursive: true, mode: 448 });
30549
30787
  const path = join14(resultRoot, `${randomUUID7()}.json`);
30550
- await writeFile4(path, full, { mode: 384 });
30551
- return { text: `${text4}
30788
+ await writeFile5(path, full, { mode: 384 });
30789
+ return { text: `${text5}
30552
30790
  [Truncated. Full result: ${path}]`, details: { resultPath: path }, resultPath: path };
30553
30791
  }
30554
- return { text: text4, details: value };
30792
+ return { text: text5, details: value };
30555
30793
  }
30556
30794
  async function imageResult(value, delivery, executionFailed = false) {
30557
30795
  const { content: image, ...imageDelivery } = delivery;
@@ -30628,11 +30866,11 @@ async function relayCall(host, raw, options = {}) {
30628
30866
 
30629
30867
  // src/server.ts
30630
30868
  var SERVER_NAME = "relay";
30631
- var SERVER_VERSION = true ? "0.15.0" : JSON.parse(readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8")).version;
30869
+ var SERVER_VERSION = true ? "0.17.0" : JSON.parse(readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8")).version;
30632
30870
  var STATUS_TOOL = "relay_status";
30633
30871
  var PLUGIN_TOOL_PREFIX = "mcp__plugin_mcp-relay_relay__";
30634
30872
  var message2 = (error2) => error2 instanceof Error ? error2.message : String(error2);
30635
- var text3 = (value, isError = false) => ({ content: [{ type: "text", text: value }], isError });
30873
+ var text4 = (value, isError = false) => ({ content: [{ type: "text", text: value }], isError });
30636
30874
  function relayContent(result2) {
30637
30875
  return { content: [{ type: "text", text: result2.text }, ...result2.image ? [{ type: "image", data: result2.image.data, mimeType: result2.image.mimeType }] : []], isError: result2.isError };
30638
30876
  }
@@ -30681,11 +30919,11 @@ function createRelayServer(options = {}) {
30681
30919
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
30682
30920
  const { name, arguments: args } = request.params;
30683
30921
  try {
30684
- if (name === STATUS_TOOL) return text3(JSON.stringify(statusPayload(), null, 2));
30922
+ if (name === STATUS_TOOL) return text4(JSON.stringify(statusPayload(), null, 2));
30685
30923
  if (relayTools.some((tool) => tool.name === name)) return relayContent(await relayCall(get, relayToolInput(name, args ?? {}), { signal: AbortSignal.any([extra.signal, shutdownController.signal]), toolCallId: String(extra.requestId) }));
30686
30924
  throw new Error(`Unknown tool: ${name}`);
30687
30925
  } catch (error2) {
30688
- return text3(message2(error2), true);
30926
+ return text4(message2(error2), true);
30689
30927
  }
30690
30928
  });
30691
30929
  const cleanup = async (reason2) => {