@wezzard/mcp-relay 0.16.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
@@ -17242,23 +17242,23 @@ function loadEnvironment(path, env = process.env, home = env.HOME ?? homedir())
17242
17242
  if (!info.isFile() || info.size > 65536) throw new Error("Environment profile must be a regular JSON file under 64 KiB");
17243
17243
  const bytes = readFileSync(canonical2);
17244
17244
  if (bytes.length > 65536) throw new Error("Environment profile exceeds 64 KiB");
17245
- const text4 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
17246
- const raw = JSON.parse(text4);
17245
+ const text5 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
17246
+ const raw = JSON.parse(text5);
17247
17247
  let depth = 0;
17248
17248
  const seen = /* @__PURE__ */ new Set();
17249
- for (let i = 0; i < text4.length; i++) {
17250
- if (text4[i] === '"') {
17249
+ for (let i = 0; i < text5.length; i++) {
17250
+ if (text5[i] === '"') {
17251
17251
  const start = i++;
17252
- for (; i < text4.length && text4[i] !== '"'; i++) if (text4[i] === "\\") i++;
17252
+ for (; i < text5.length && text5[i] !== '"'; i++) if (text5[i] === "\\") i++;
17253
17253
  let next = i + 1;
17254
- while (/\s/.test(text4[next] ?? "") && next < text4.length) next++;
17255
- if (depth === 1 && text4[next] === ":") {
17256
- 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));
17257
17257
  if (seen.has(key)) throw new Error(`Duplicate environment profile key: ${key}`);
17258
17258
  seen.add(key);
17259
17259
  }
17260
- } else if (text4[i] === "{" || text4[i] === "[") depth++;
17261
- else if (text4[i] === "}" || text4[i] === "]") depth--;
17260
+ } else if (text5[i] === "{" || text5[i] === "[") depth++;
17261
+ else if (text5[i] === "}" || text5[i] === "]") depth--;
17262
17262
  }
17263
17263
  if (raw && typeof raw === "object" && !Array.isArray(raw) && (raw.schemaVersion === 1 || Object.hasOwn(raw, "vmctlPath"))) throw new Error(LEGACY_PROFILE);
17264
17264
  const fields = ["schemaVersion", "id", "vmServiceUrl", ...paths].sort();
@@ -17608,10 +17608,10 @@ var Session = class {
17608
17608
  * transmission; the same outcome states as exec() apply (D14/D17).
17609
17609
  */
17610
17610
  async runScript(localPath, remotePath, language2, options = {}) {
17611
- const { createHash: createHash7 } = await import("node:crypto");
17611
+ const { createHash: createHash8 } = await import("node:crypto");
17612
17612
  const { readFile: readFile10 } = await import("node:fs/promises");
17613
17613
  const bytes = await readFile10(localPath);
17614
- const scriptSha256 = createHash7("sha256").update(bytes).digest("hex");
17614
+ const scriptSha256 = createHash8("sha256").update(bytes).digest("hex");
17615
17615
  const upload = await this.transport.upload(localPath, { remotePath });
17616
17616
  const executionId = formatId(allocateId("execution"));
17617
17617
  const interpreter = language2 === "python" ? "python3" : language2 === "typescript" ? "tsx" : "node";
@@ -17659,8 +17659,8 @@ var Session = class {
17659
17659
  * remote after receipt. Same outcome states as exec() (D14/D17).
17660
17660
  */
17661
17661
  async runCode(code, language2, options = {}) {
17662
- const { createHash: createHash7 } = await import("node:crypto");
17663
- 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");
17664
17664
  const executionId = formatId(allocateId("execution"));
17665
17665
  const interpreter = language2 === "python" ? "python3" : language2 === "typescript" ? "tsx" : "node";
17666
17666
  const submission = {
@@ -17748,6 +17748,7 @@ init_evidence_package();
17748
17748
 
17749
17749
  // src/machine-service.ts
17750
17750
  import { isIP as isIP2 } from "node:net";
17751
+ import { createHash as createHash3 } from "node:crypto";
17751
17752
  var MachineServiceError = class extends Error {
17752
17753
  constructor(message3, status, responseBody, options) {
17753
17754
  super(message3, options);
@@ -17770,7 +17771,7 @@ function capacityRefusal(error2) {
17770
17771
  }
17771
17772
  if (!body || typeof body !== "object") return false;
17772
17773
  const { error: reason2, outcome } = body;
17773
- 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";
17774
17775
  }
17775
17776
  var SERVICE_NAME = "machine-service";
17776
17777
  function expectMachineService(health, origin) {
@@ -17792,8 +17793,16 @@ function positive(value, label) {
17792
17793
  function record2(value) {
17793
17794
  return value !== null && typeof value === "object" && !Array.isArray(value);
17794
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
+ }
17795
17801
  function isLease(value) {
17796
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
+ }
17797
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";
17798
17807
  }
17799
17808
  var MachineService = class {
@@ -17809,8 +17818,8 @@ var MachineService = class {
17809
17818
  if (options.environment && url.origin !== new URL(options.environment.profile.vmServiceUrl).origin) throw new TypeError("Backend endpoint does not match the selected environment");
17810
17819
  const host = url.hostname.replace(/^\[|\]$/g, "");
17811
17820
  const loopback = host === "localhost" || host === "::1" || isIP2(host) === 4 && host.startsWith("127.");
17812
- if (!loopback || !["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
17813
- throw new TypeError("machine-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");
17814
17823
  }
17815
17824
  this.baseUrl = url.origin;
17816
17825
  this.timeoutMs = positive(options.timeoutMs ?? 66e4, "timeoutMs");
@@ -17820,8 +17829,10 @@ var MachineService = class {
17820
17829
  health(options = {}) {
17821
17830
  return this.request("/health", void 0, options);
17822
17831
  }
17823
- list(options = {}) {
17824
- return this.request("/machines", 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;
17825
17836
  }
17826
17837
  images(options = {}) {
17827
17838
  return this.request("/images", void 0, options);
@@ -17848,8 +17859,8 @@ var MachineService = class {
17848
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);
17849
17860
  }
17850
17861
  }
17851
- get(vm, options = {}) {
17852
- 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));
17853
17864
  }
17854
17865
  /**
17855
17866
  * Cancellation before dispatch prevents allocation. Once dispatched we deliberately
@@ -17882,17 +17893,57 @@ var MachineService = class {
17882
17893
  pull(vm, body, options = {}) {
17883
17894
  return this.request(this.path(vm, "pull"), body, options);
17884
17895
  }
17885
- heartbeat(vm, body = {}, options = {}) {
17886
- 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));
17887
17898
  }
17888
17899
  release(vm, body = {}, options = {}) {
17889
17900
  return this.request(this.path(vm, "release"), body, options);
17890
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
+ }
17891
17926
  path(vm, action) {
17892
17927
  if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(vm)) throw new TypeError("Invalid VM name");
17893
17928
  return `/machines/${encodeURIComponent(vm)}${action ? `/${action}` : ""}`;
17894
17929
  }
17895
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) {
17896
17947
  options.signal?.throwIfAborted();
17897
17948
  const timeoutMs2 = positive(options.timeoutMs ?? this.timeoutMs, "timeoutMs");
17898
17949
  const controller = new AbortController();
@@ -17901,17 +17952,17 @@ var MachineService = class {
17901
17952
  const timer = setTimeout(() => controller.abort(new MachineServiceError(`machine-service ${path} timed out after ${timeoutMs2}ms`)), timeoutMs2);
17902
17953
  try {
17903
17954
  const response = await fetch(`${this.baseUrl}${path}`, {
17904
- method: body === void 0 ? "GET" : "POST",
17905
- headers: { ...body === void 0 ? {} : { "Content-Type": "application/json" }, ...this.environment ? { "X-VM-Environment-Fingerprint": this.environment.identity.fingerprint } : {} },
17906
- ...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 },
17907
17958
  signal: controller.signal,
17908
17959
  redirect: "error"
17909
- // Do not let a loopback service redirect to remote hosts.
17960
+ // Do not let a service redirect to another host.
17910
17961
  });
17911
17962
  const reader = response.body?.getReader();
17912
17963
  const chunks = [];
17913
17964
  let size = 0;
17914
- const bound = response.ok ? this.maxResponseBytes : Math.min(4096, this.maxResponseBytes);
17965
+ const bound = response.ok ? maxBytes : Math.min(4096, maxBytes);
17915
17966
  let truncated = false;
17916
17967
  if (reader) {
17917
17968
  try {
@@ -17931,14 +17982,10 @@ var MachineService = class {
17931
17982
  reader.releaseLock();
17932
17983
  }
17933
17984
  }
17934
- const text4 = Buffer.concat(chunks).toString("utf8");
17935
- if (!response.ok) throw new MachineServiceError(`machine-service ${path}: HTTP ${response.status}: ${text4}${truncated ? " [truncated]" : ""}`, response.status, text4);
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);
17936
17987
  if (truncated) throw new MachineServiceError(`machine-service ${path}: response exceeds ${bound} bytes`);
17937
- try {
17938
- return JSON.parse(text4);
17939
- } catch (cause) {
17940
- throw new MachineServiceError(`machine-service ${path}: invalid JSON response`, void 0, void 0, { cause });
17941
- }
17988
+ return { path, bytes, text: text5, contentType: response.headers.get("content-type") ?? void 0, sha256: response.headers.get("x-content-sha256") ?? void 0 };
17942
17989
  } catch (cause) {
17943
17990
  if (controller.signal.aborted) throw controller.signal.reason;
17944
17991
  if (cause instanceof MachineServiceError) throw cause;
@@ -17977,21 +18024,21 @@ function cells(row) {
17977
18024
  });
17978
18025
  }
17979
18026
  function parse3(line) {
17980
- const text4 = line.trim();
17981
- if (!text4.startsWith("|") || !text4.endsWith("|")) return void 0;
17982
- 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());
17983
18030
  }
17984
- function linesOf(text4) {
18031
+ function linesOf(text5) {
17985
18032
  const lines = [];
17986
18033
  const pattern = /[^\r\n]*(?:\r\n|\n|\r|$)/g;
17987
- for (const match of text4.matchAll(pattern)) {
18034
+ for (const match of text5.matchAll(pattern)) {
17988
18035
  if (!match[0]) continue;
17989
18036
  lines.push({ text: match[0].replace(/[\r\n]+$/, ""), start: match.index, end: match.index + match[0].length });
17990
18037
  }
17991
18038
  return lines;
17992
18039
  }
17993
- function table(text4) {
17994
- const lines = linesOf(text4);
18040
+ function table(text5) {
18041
+ const lines = linesOf(text5);
17995
18042
  const sections = lines.map((line, index) => /^## Using VMs\s*$/.test(line.text) ? index : -1).filter((index) => index >= 0);
17996
18043
  if (sections.length !== 1) throw new RegistryError("Expected exactly one '## Using VMs' section");
17997
18044
  const begin = sections[0];
@@ -18012,7 +18059,7 @@ function table(text4) {
18012
18059
  rows.push(line);
18013
18060
  }
18014
18061
  const last = rows.at(-1) ?? separator;
18015
- 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" };
18016
18063
  }
18017
18064
  function resolveRegistry(options = {}) {
18018
18065
  const env = options.env ?? process.env;
@@ -18090,30 +18137,30 @@ var Registry = class {
18090
18137
  /** Returns false when this exact row is already registered (idempotent). */
18091
18138
  async add(row, options = {}) {
18092
18139
  const desired = cells(row);
18093
- return this.update((text4) => {
18094
- const registry2 = table(text4);
18140
+ return this.update((text5) => {
18141
+ const registry2 = table(text5);
18095
18142
  const matching = registry2.rows.filter((line) => parse3(line.text)[2] === row.taskName);
18096
18143
  if (matching.length > 0) {
18097
- 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;
18098
18145
  throw new RegistryError(`Task '${row.taskName}' is already registered by a different owner or duplicated`);
18099
18146
  }
18100
- 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 : "";
18101
18148
  const added = `${prefix}| ${desired.join(" | ")} |${registry2.newline}`;
18102
- return text4.slice(0, registry2.insertion) + added + text4.slice(registry2.insertion);
18149
+ return text5.slice(0, registry2.insertion) + added + text5.slice(registry2.insertion);
18103
18150
  }, options.signal);
18104
18151
  }
18105
18152
  /** Returns false when absent. Never removes a row whose ownership differs. */
18106
18153
  async remove(row, options = {}) {
18107
18154
  const desired = cells(row);
18108
- return this.update((text4) => {
18109
- const registry2 = table(text4);
18155
+ return this.update((text5) => {
18156
+ const registry2 = table(text5);
18110
18157
  const matching = registry2.rows.filter((line2) => parse3(line2.text)[2] === row.taskName);
18111
- if (matching.length === 0) return text4;
18158
+ if (matching.length === 0) return text5;
18112
18159
  if (matching.length !== 1 || JSON.stringify(parse3(matching[0].text)) !== JSON.stringify(desired)) {
18113
18160
  throw new RegistryError(`Refusing to remove task '${row.taskName}': ownership does not match`);
18114
18161
  }
18115
18162
  const line = matching[0];
18116
- return text4.slice(0, line.start) + text4.slice(line.end);
18163
+ return text5.slice(0, line.start) + text5.slice(line.end);
18117
18164
  }, options.signal);
18118
18165
  }
18119
18166
  async update(transform2, signal) {
@@ -18278,14 +18325,14 @@ import { randomUUID as randomUUID3 } from "node:crypto";
18278
18325
 
18279
18326
  // src/util.ts
18280
18327
  import { spawn as spawn3 } from "node:child_process";
18281
- import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
18328
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
18282
18329
  import { mkdir as mkdir3, rename as rename3, lstat as lstat2, readdir as readdir2, open as open3 } from "node:fs/promises";
18283
18330
  import { dirname as dirname4, join as join6, resolve as resolve4, relative as relative3, isAbsolute as isAbsolute3 } from "node:path";
18284
- var hash = (bytes) => createHash3("sha256").update(bytes).digest("hex");
18331
+ var hash = (bytes) => createHash4("sha256").update(bytes).digest("hex");
18285
18332
  async function hashFile(path) {
18286
18333
  const file = await open3(path, "r");
18287
18334
  try {
18288
- const digest = createHash3("sha256"), chunk = Buffer.alloc(8 * 1024 * 1024);
18335
+ const digest = createHash4("sha256"), chunk = Buffer.alloc(8 * 1024 * 1024);
18289
18336
  let bytes = 0;
18290
18337
  for (; ; ) {
18291
18338
  const { bytesRead } = await file.read(chunk, 0, chunk.length, null);
@@ -18375,7 +18422,7 @@ async function command(argv, options = {}) {
18375
18422
  // src/archive.ts
18376
18423
  import { open as open4, mkdir as mkdir4 } from "node:fs/promises";
18377
18424
  import { constants as constants2 } from "node:fs";
18378
- import { createHash as createHash4 } from "node:crypto";
18425
+ import { createHash as createHash5 } from "node:crypto";
18379
18426
  import { dirname as dirname5 } from "node:path";
18380
18427
  var MAX_LINE_BYTES = 64 * 1024;
18381
18428
  var header = (path, bytes) => `${JSON.stringify({ path, bytes })}
@@ -18425,9 +18472,9 @@ async function unpackArchive(archive, directory2, requested, options = {}) {
18425
18472
  for (; ; ) {
18426
18473
  const at = buffer.indexOf(10, start);
18427
18474
  if (at >= 0 && at < end) {
18428
- const text4 = buffer.toString("utf8", start, at);
18475
+ const text5 = buffer.toString("utf8", start, at);
18429
18476
  start = at + 1;
18430
- const value = JSON.parse(text4);
18477
+ const value = JSON.parse(text5);
18431
18478
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid archive line");
18432
18479
  return value;
18433
18480
  }
@@ -18449,7 +18496,7 @@ async function unpackArchive(archive, directory2, requested, options = {}) {
18449
18496
  const target = within(directory2, fact.path);
18450
18497
  await mkdir4(dirname5(target), { recursive: true, mode: 448 });
18451
18498
  const output = await open4(target, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | constants2.O_NOFOLLOW, 384);
18452
- const digest = createHash4("sha256");
18499
+ const digest = createHash5("sha256");
18453
18500
  try {
18454
18501
  for (let left = bytes; left > 0; ) {
18455
18502
  if (start === end) {
@@ -18788,10 +18835,10 @@ var Transfer = class {
18788
18835
  if (!imageFormat(result2)) throw new ImageTransferError("unsafe-path", "Unsupported image format");
18789
18836
  } else {
18790
18837
  try {
18791
- const text4 = new TextDecoder("utf-8", { fatal: true }).decode(result2);
18838
+ const text5 = new TextDecoder("utf-8", { fatal: true }).decode(result2);
18792
18839
  if (options.metadataFormat === "jsonl") {
18793
- for (const line of text4.split("\n")) if (line.trim()) JSON.parse(line);
18794
- } else JSON.parse(text4);
18840
+ for (const line of text5.split("\n")) if (line.trim()) JSON.parse(line);
18841
+ } else JSON.parse(text5);
18795
18842
  } catch (cause) {
18796
18843
  throw new ImageTransferError("integrity-failed", "Invalid image metadata JSON", { cause });
18797
18844
  }
@@ -19181,11 +19228,11 @@ var VmTransport = class {
19181
19228
  };
19182
19229
 
19183
19230
  // src/package.ts
19184
- import { createHash as createHash5 } from "node:crypto";
19231
+ import { createHash as createHash6 } from "node:crypto";
19185
19232
  import { lstat as lstat4, readFile as readFile6, readdir as readdir3, mkdir as mkdir6, writeFile as writeFile3, rm as rm2 } from "node:fs/promises";
19186
19233
  import { dirname as dirname7, join as join9, resolve as resolve6, parse as parse4 } from "node:path";
19187
19234
  var generated = ["OPENING.txt", "manifest.json"];
19188
- var hash2 = (bytes) => createHash5("sha256").update(bytes).digest("hex");
19235
+ var hash2 = (bytes) => createHash6("sha256").update(bytes).digest("hex");
19189
19236
  var json = (value) => JSON.stringify(value, null, 2) + "\n";
19190
19237
  function object3(value, label) {
19191
19238
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`invalid ${label}`);
@@ -19628,16 +19675,16 @@ async function probeLocal(run = command, platform = process.platform) {
19628
19675
  }
19629
19676
  const permissions = await observe(["cua-driver", "permissions", "status", "--json"], JSON.parse);
19630
19677
  const recorder = await observe(["cua-driver", "call", "get_recording_state", "--json", "{}"], JSON.parse);
19631
- const foreground = await observe(["cua-driver", "call", "list_apps", "--json", "{}"], (text4) => {
19632
- const data = JSON.parse(text4);
19678
+ const foreground = await observe(["cua-driver", "call", "list_apps", "--json", "{}"], (text5) => {
19679
+ const data = JSON.parse(text5);
19633
19680
  return data.apps?.filter((app) => app.active).map((app) => ({ name: app.name, bundleId: app.bundle_id, pid: app.pid })) ?? null;
19634
19681
  });
19635
- 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");
19636
- const idle = platform === "darwin" ? await observe(["/usr/sbin/ioreg", "-r", "-c", "IOHIDSystem"], (text4) => {
19637
- 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+)/);
19638
19685
  return m ? Number(m[1]) / 1e9 : null;
19639
- }) : await observe(["xprintidle"], (text4) => {
19640
- const n = Number(text4.trim());
19686
+ }) : await observe(["xprintidle"], (text5) => {
19687
+ const n = Number(text5.trim());
19641
19688
  return Number.isFinite(n) ? n / 1e3 : null;
19642
19689
  });
19643
19690
  return {
@@ -23341,8 +23388,8 @@ function FromObject4(properties) {
23341
23388
 
23342
23389
  // node_modules/typebox/build/type/engine/object/from_tuple.mjs
23343
23390
  function FromTuple(types) {
23344
- const object5 = TupleToObject(Tuple(types));
23345
- const result2 = FromType8(object5);
23391
+ const object6 = TupleToObject(Tuple(types));
23392
+ const result2 = FromType8(object6);
23346
23393
  return result2;
23347
23394
  }
23348
23395
 
@@ -27367,8 +27414,8 @@ var normalizeSearchName = (name) => name.trim().toLowerCase();
27367
27414
  var serializeSearchResult = (result2) => JSON.stringify(result2, null, 2);
27368
27415
  function validateCatalog(value) {
27369
27416
  if (!Check2(catalogSchema, value)) throw new Error("Invalid application catalog schema");
27370
- const bounded3 = (text4, limit) => {
27371
- 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");
27372
27419
  };
27373
27420
  for (const image of value.images) for (const app of image.applications) {
27374
27421
  bounded3(app.id, 128);
@@ -27587,7 +27634,7 @@ import { join as join11, dirname as dirname8, extname } from "node:path";
27587
27634
  import { randomUUID as randomUUID5 } from "node:crypto";
27588
27635
 
27589
27636
  // src/image-presentation.ts
27590
- import { createHash as createHash6 } from "node:crypto";
27637
+ import { createHash as createHash7 } from "node:crypto";
27591
27638
  import { deflateSync, inflateSync } from "node:zlib";
27592
27639
  var IMAGE_PRESENTATION_POLICY = Object.freeze({
27593
27640
  version: 1,
@@ -27993,7 +28040,7 @@ async function prepareImage(bytes, mimeType) {
27993
28040
  width: size.width,
27994
28041
  height: size.height,
27995
28042
  mimeType: presentedType,
27996
- sha256: createHash6("sha256").update(presented).digest("hex"),
28043
+ sha256: createHash7("sha256").update(presented).digest("hex"),
27997
28044
  bytes: presented.length,
27998
28045
  transformed: presentedType !== mimeType || !original.equals(presented),
27999
28046
  policy
@@ -28743,12 +28790,85 @@ async function refreshEvidenceState(incoming, destination, archiveRoot, options
28743
28790
  if (archived) await copy(archived, retained);
28744
28791
  }
28745
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
+
28746
28864
  // src/manager.ts
28747
28865
  var SCRIPT_EXTENSIONS = { shell: "sh", javascript: "js", typescript: "ts", python: "py" };
28748
28866
  var RENEWAL_WINDOW_MS = 15 * 6e4;
28749
28867
  var MIN_RENEWAL_MS = 0.1 * 36e5;
28750
28868
  var DEFAULT_AFTER_INTERVAL_MS = 500;
28751
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;
28752
28872
  var DOWNLOAD_BOUND = 64;
28753
28873
  var DOWNLOAD_RETRY_DELAYS_MS = [1e3, 3e3];
28754
28874
  var CAPACITY_RETRY_MS = 15e3;
@@ -28763,7 +28883,7 @@ async function settleEach(work) {
28763
28883
  const failed = (await Promise.allSettled(work)).find((result2) => result2.status === "rejected");
28764
28884
  if (failed) throw failed.reason;
28765
28885
  }
28766
- 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.";
28767
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.";
28768
28888
  var RelayManager = class {
28769
28889
  constructor(options) {
@@ -28780,14 +28900,6 @@ var RelayManager = class {
28780
28900
  this.vm = options.vm ?? new MachineService({ baseUrl: this.environment?.profile.vmServiceUrl ?? process.env.MCP_RELAY_URL, environment: this.environment });
28781
28901
  this.registry = options.registry ?? new Registry(this.environment ? { managedRoot: this.environment.profile.relayStateDir } : {});
28782
28902
  this.root = join13(this.environment?.profile.relayStateDir ?? options.stateRoot ?? relayStateRoot(), hash(options.sessionId).slice(0, 32));
28783
- this.channel = {
28784
- exec: async (name, argv, timeoutMs2 = 18e4, options2) => {
28785
- const result2 = await this.vm.exec(name, { argv, timeout: Math.ceil(timeoutMs2 / 1e3) }, { timeoutMs: options2?.timeoutMs ?? timeoutMs2 + 3e4, signal: options2?.signal });
28786
- return { stdout: result2.output, stderr: result2.output, code: result2.rc };
28787
- },
28788
- push: (name, local_path, remote_path) => this.vm.push(name, { local_path, remote_path }),
28789
- pull: (name, remote_path, local_path, options2) => this.vm.pull(name, { remote_path, local_path }, options2)
28790
- };
28791
28903
  }
28792
28904
  options;
28793
28905
  vm;
@@ -28796,7 +28908,6 @@ var RelayManager = class {
28796
28908
  tartPath;
28797
28909
  registry;
28798
28910
  root;
28799
- channel;
28800
28911
  /** The most guests this session holds at once (DC-20). */
28801
28912
  maxGuests;
28802
28913
  /** How long an acquisition waits for a host at capacity, and how often it is asked again (DC-22). */
@@ -28812,6 +28923,10 @@ var RelayManager = class {
28812
28923
  ownerLock;
28813
28924
  /** Set once shutdown has paused the guests: no new acquisition or guest operation starts. */
28814
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
+ }
28815
28930
  serialized(fn) {
28816
28931
  const next = this.queue.then(fn, fn);
28817
28932
  this.queue = next.catch(() => {
@@ -28937,6 +29052,7 @@ var RelayManager = class {
28937
29052
  return { endpoint: this.vm.baseUrl, tartHome: this.tartHome, ...this.environment ? { environmentFingerprint: this.environment.identity.fingerprint } : {} };
28938
29053
  }
28939
29054
  bindingMatches(e) {
29055
+ if (e.machine) return !!e.backend?.endpoint && !!e.backend.instance;
28940
29056
  if (e.backend) {
28941
29057
  const expected = this.binding();
28942
29058
  return Object.keys(e.backend).length === Object.keys(expected).length && Object.entries(expected).every(([key, value]) => e.backend[key] === value);
@@ -29058,6 +29174,9 @@ var RelayManager = class {
29058
29174
  const network2 = this.options.guestNetwork ?? guestNetwork();
29059
29175
  if (!GUEST_NETWORKS.includes(network2)) throw new Error(`guestNetwork must be nat or internet, not ${JSON.stringify(network2)}`);
29060
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");
29061
29180
  if (!Array.isArray(input.extractions) || input.extractions.length > 100) throw new Error("Declare up to 100 extractions before work");
29062
29181
  const names = /* @__PURE__ */ new Set();
29063
29182
  for (const extraction of input.extractions) {
@@ -29252,6 +29371,53 @@ var Guest = class {
29252
29371
  closed = false;
29253
29372
  /** After-image downloads, outside the serialized section (docs/screenshot-delivery.md §10). */
29254
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
+ }
29255
29421
  serialized(fn) {
29256
29422
  const next = this.queue.then(fn, fn);
29257
29423
  this.queue = next.catch(() => {
@@ -29304,15 +29470,25 @@ var Guest = class {
29304
29470
  if (!e) return;
29305
29471
  this.assertBinding();
29306
29472
  await this.m.assertBackend();
29473
+ await this.findOwner(e);
29307
29474
  e.backend ??= this.m.binding();
29308
29475
  if (!e.lease) {
29309
- const matches = Object.values((await this.m.vm.list({ timeoutMs: 1e4 })).machines).filter((v) => v.purpose === e.purpose);
29476
+ const matches = Object.values((await this.vm.list({ timeoutMs: 1e4 })).machines).filter((v) => v.purpose === e.purpose);
29310
29477
  if (matches.length !== 1) throw new Error(`Cannot reconcile acquisition for ${e.purpose}; ownership retained, never automatically reacquire`);
29311
29478
  e.lease = matches[0];
29312
29479
  e.acquisitionInFlight = false;
29480
+ if (e.machine && e.lease.workspace) e.guestRoot = durableRoot(e.lease.workspace, e.purpose);
29313
29481
  }
29314
29482
  try {
29315
- 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
+ }
29316
29492
  if (lease.purpose !== e.purpose || e.lease.lease_id && lease.lease_id !== e.lease.lease_id) throw new Error("Lease ownership identity mismatch");
29317
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");
29318
29494
  if (lease.console) {
@@ -29360,7 +29536,7 @@ var Guest = class {
29360
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"]]]) {
29361
29537
  const required2 = name === "node";
29362
29538
  try {
29363
- const r = await this.m.channel.exec(e.lease.vm, [...argv], 1e4);
29539
+ const r = await this.channel.exec(e.lease.vm, [...argv], 1e4);
29364
29540
  checks.push({ name, language: language2, required: required2, ...r, ready: r.code === 0 });
29365
29541
  } catch (error2) {
29366
29542
  checks.push({ name, language: language2, required: required2, ready: false, diagnostic: String(error2) });
@@ -29369,15 +29545,16 @@ var Guest = class {
29369
29545
  const tsx = checks[1], nodeVersion = /^v(\d+)\.(\d+)/.exec(String(checks[0].stdout ?? ""));
29370
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" });
29371
29547
  let software;
29372
- try {
29373
- 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 });
29374
29551
  validateCatalog(catalog);
29375
29552
  const listed = catalog.images.find((image) => image.image === e.image);
29376
29553
  software = listed ? { image: e.image, applications: listed.applications } : { image: e.image, applications: [], diagnostic: `The catalog does not list ${e.image}.` };
29377
29554
  } catch (error2) {
29378
29555
  software = { image: e.image, diagnostic: `The image catalog could not be read: ${message(error2)}` };
29379
29556
  }
29380
- 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);
29381
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 };
29382
29559
  await this.log("guest-readiness", void 0, facts);
29383
29560
  return facts;
@@ -29393,10 +29570,10 @@ var Guest = class {
29393
29570
  }
29394
29571
  async resolveConsole(signal) {
29395
29572
  const e = await this.consoleOwner(signal);
29396
- if (!this.m.vm.consoleResolve) throw new Error("Backend lacks console API; upgrade machine-service");
29573
+ if (!this.vm.consoleResolve) throw new Error("Backend lacks console API; upgrade machine-service");
29397
29574
  let observation;
29398
29575
  try {
29399
- 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 }));
29400
29577
  } catch (error2) {
29401
29578
  if (e.consoleObservation && e.consoleObservation.status !== "revoked") e.consoleObservation = { ...e.consoleObservation, status: "unknown" };
29402
29579
  await this.save();
@@ -29419,7 +29596,7 @@ var Guest = class {
29419
29596
  const resolved = await this.resolveConsole(signal), e = this.current();
29420
29597
  if (!e.lease.console?.console_id) throw new Error("This lease has no acquired console; automatic VNC retrofit is forbidden");
29421
29598
  if (resolved.console_id !== input.console_id) throw new Error("Console instance identity mismatch");
29422
- const method = operation === "open" ? this.m.vm.consoleOpen : this.m.vm.consoleCancel;
29599
+ const method = operation === "open" ? this.vm.consoleOpen : this.vm.consoleCancel;
29423
29600
  if (!method) throw new Error("Backend lacks console API; upgrade machine-service");
29424
29601
  if (operation === "open") {
29425
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");
@@ -29438,7 +29615,7 @@ var Guest = class {
29438
29615
  await this.save();
29439
29616
  await this.log(`console-${operation}-intent`, "reason" in input ? input.reason : void 0, { ...body, ..."expected" in input ? { expected: input.expected } : {}, screenshotEvidence: false });
29440
29617
  try {
29441
- 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 }));
29442
29619
  this.assertConsoleIdentity(observation, e);
29443
29620
  if (observation.console_id !== body.console_id || observation.attempt?.attempt_id !== body.attempt_id) throw new Error("Console response identity mismatch");
29444
29621
  e.consoleObservation = observation;
@@ -29459,7 +29636,7 @@ var Guest = class {
29459
29636
  transfer() {
29460
29637
  const e = this.current();
29461
29638
  if (!e.node) throw new Error("Stage runtime first");
29462
- 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) });
29463
29640
  }
29464
29641
  async log(kind, because, details = {}) {
29465
29642
  if (because !== void 0) this.m.reason(because);
@@ -29474,13 +29651,17 @@ var Guest = class {
29474
29651
  */
29475
29652
  async acquire(input, network, signal) {
29476
29653
  const ttlHours = input.ttlHours ?? 4;
29654
+ let owner;
29477
29655
  try {
29478
29656
  if (this.m.shuttingDown || this.closed) throw new Error("Relay manager is shutting down");
29479
- const images = await this.m.vm.images({ timeoutMs: 5e3, signal });
29480
- if (!images.images[input.image]?.base_available) throw new Error(`Image unavailable: ${input.image}`);
29481
- if (input.vnc) {
29482
- const capabilities = await this.m.readAcquisitionCapabilities(signal);
29483
- 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
+ }
29484
29665
  }
29485
29666
  await this.lock();
29486
29667
  } catch (error2) {
@@ -29492,8 +29673,10 @@ var Guest = class {
29492
29673
  const stamp = startedAt.slice(0, 19).replace(/[T:]/g, "-") + "-Z";
29493
29674
  const project = this.m.options.project, environment = this.m.environment;
29494
29675
  const hostRoot = join13(this.m.options.outputRoot ?? resolve9(project, "relay-evidence"), purpose);
29495
- const row = { machine: environment ? `${environment.profile.vmServiceUrl} (${environment.profile.id}; ${purpose})` : `127.0.0.1 (machine-service ${purpose})`, os: input.image, taskName: purpose, agent: `mcp-relay ${this.m.options.sessionId}`, project: resolve9(project), startDate: stamp };
29496
- 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;
29497
29680
  let refused = false;
29498
29681
  try {
29499
29682
  await this.save();
@@ -29516,7 +29699,9 @@ var Guest = class {
29516
29699
  await this.save();
29517
29700
  const asked = Date.now();
29518
29701
  try {
29519
- 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);
29520
29705
  e.acquisitionInFlight = false;
29521
29706
  granted = asked;
29522
29707
  break;
@@ -29548,7 +29733,7 @@ var Guest = class {
29548
29733
  this.startHeartbeat();
29549
29734
  await this.save();
29550
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 });
29551
- 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 };
29552
29737
  } catch (error2) {
29553
29738
  if (refused && await this.withdraw(error2)) throw error2;
29554
29739
  await this.fail(error2);
@@ -29593,7 +29778,7 @@ Guest ${this.name} keeps this acquisition's ownership record: name it to reconci
29593
29778
  async withdraw(error2) {
29594
29779
  const e = this.enclosure;
29595
29780
  try {
29596
- if (Object.values((await this.m.vm.list({ timeoutMs: 1e4 })).machines).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;
29597
29782
  await this.m.registry.remove(e.row);
29598
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() });
29599
29784
  this.enclosure = void 0;
@@ -29647,7 +29832,7 @@ Guest ${this.name} keeps this acquisition's ownership record: name it to reconci
29647
29832
  }
29648
29833
  this.assertBinding();
29649
29834
  await this.m.assertBackend();
29650
- 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 });
29651
29836
  if (this.enclosure !== e || e.released) return;
29652
29837
  e.expiresAt = renewed.ttl_expires_at;
29653
29838
  e.guestState = renewed.state;
@@ -29700,18 +29885,24 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29700
29885
  const workspace = input.workspace === void 0 ? void 0 : await this.m.projectPath(input.workspace, "workspace");
29701
29886
  const bundle = this.m.options.runtimeBundle ?? fileURLToPath(new URL("../dist/receiver.mjs", import.meta.url));
29702
29887
  await access(bundle);
29703
- if (e.capture === void 0 && !e.staged) {
29888
+ if (!e.machine && e.capture === void 0 && !e.staged) {
29704
29889
  e.capture = await this.captureSoftware(e, signal);
29705
29890
  await this.save();
29706
29891
  }
29707
29892
  const node2 = input.nodePath ?? e.node ?? "node";
29708
- 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) });
29709
29894
  try {
29710
29895
  await transfer.checked([node2, "--version"]);
29711
29896
  } catch (error2) {
29712
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 });
29713
29898
  }
29714
- 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
+ }
29715
29906
  if (e.capture !== false) await this.awaitCapture(transfer, e, node2, cuaDriver, signal);
29716
29907
  e.node = node2;
29717
29908
  e.cuaDriver = cuaDriver;
@@ -29730,7 +29921,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29730
29921
  this.transport = new VmTransport(transfer, e.guestRoot, join13(e.hostRoot, "host"), e.cuaDriver);
29731
29922
  this.transport.capture = e.capture !== false;
29732
29923
  relay.useTransport(() => this.transport);
29733
- this.session = await relay.start({ taskId: e.purpose, target: `machine-service:${e.lease.vm}` });
29924
+ this.session = await relay.start({ taskId: e.purpose, target: `machine-service:${e.machine ? `durable:${e.machine}` : e.lease.vm}` });
29734
29925
  e.sessionId = this.session.sessionId;
29735
29926
  e.staged = true;
29736
29927
  await this.save();
@@ -29744,7 +29935,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29744
29935
  async captureSoftware(e, signal) {
29745
29936
  let catalog;
29746
29937
  try {
29747
- catalog = await this.m.vm.applications({ timeoutMs: 1e4, signal });
29938
+ catalog = await this.vm.applications({ timeoutMs: 1e4, signal });
29748
29939
  validateCatalog(catalog);
29749
29940
  } catch (error2) {
29750
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 });
@@ -29753,6 +29944,26 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29753
29944
  await this.log("capture-software", void 0, { image: e.image, capture, ids: CAPTURE_SOFTWARE });
29754
29945
  return capture;
29755
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
+ }
29756
29967
  /**
29757
29968
  * Waits until the guest's cua-driver takes a screenshot, as each run's
29758
29969
  * snapshots do (DC-24). The image starts its daemon at login, which can
@@ -29786,6 +29997,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29786
29997
  }
29787
29998
  /** What a lease's runs record: snapshots when its image lists cua-driver, none otherwise. */
29788
29999
  snapshotFacts(e) {
30000
+ if (e.machine) return { taken: e.capture === true, reason: e.captureReason ?? "Decided at relay_stage." };
29789
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." };
29790
30002
  }
29791
30003
  async run(input, signal) {
@@ -29860,12 +30072,12 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29860
30072
  ensureGuest: async (signal, deadline) => {
29861
30073
  const options = { signal, timeoutMs: Math.max(1, Math.min(1e4, deadline - Date.now())) };
29862
30074
  if (this.m.environment) {
29863
- const health = await this.m.vm.health(options);
30075
+ const health = await this.vm.health(options);
29864
30076
  if (!health.ok || !matchesEnvironment(health.environment, this.m.environment)) throw Object.assign(new Error("Selected backend identity changed."), { code: "unauthorized-reference" });
29865
30077
  }
29866
30078
  try {
29867
- const lease = await this.m.vm.get(e.lease.vm, options);
29868
- 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" });
29869
30081
  } catch (error2) {
29870
30082
  if (error2 instanceof MachineServiceError && error2.status === 404) throw Object.assign(new Error("Saved image guest is no longer available."), { code: "stale-reference" });
29871
30083
  throw error2;
@@ -29894,16 +30106,16 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
29894
30106
  }
29895
30107
  const store = this.imageStore(), result2 = await store.get(target, bounded3, deadline);
29896
30108
  if (result2.status !== "unauthorized-reference" || target.source !== "reference") return result2;
29897
- const named = job?.image ?? await this.namedImage(target.imageId);
29898
- if (named?.source !== "display") return result2;
29899
- 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);
29900
30112
  return resolved.image && resolved.image.imageId !== target.imageId ? { status: "integrity-failed", diagnostic: "The display selector no longer names the referenced image." } : resolved;
29901
30113
  }
29902
30114
  /** The image a run named with this reference, from the step download records. No guest I/O. */
29903
30115
  async namedImage(imageId) {
29904
30116
  const records = join13(this.current().hostRoot, "host", "evidence-downloads");
29905
30117
  for (const name of (await readdir7(records).catch(() => [])).filter((n) => n.endsWith(".json"))) {
29906
- 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);
29907
30119
  if (image?.imageId === imageId) return image;
29908
30120
  }
29909
30121
  return void 0;
@@ -30178,7 +30390,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30178
30390
  await jsonFile(join13(e.hostRoot, "host", "diagnostics", `${executionId}.request.json`), request);
30179
30391
  let result2;
30180
30392
  try {
30181
- 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 });
30182
30394
  result2 = { executionId, outcome: { kind: "completed", exitStatus: { code: r.code, signal: null } }, output: r.stdout, outputStreams: "stdout and stderr combined" };
30183
30395
  } catch (error2) {
30184
30396
  result2 = { executionId, outcome: { kind: "uncertain", diagnostic: String(error2) }, output: "", outputStreams: "stdout and stderr combined" };
@@ -30251,10 +30463,11 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30251
30463
  await this.m.assertBackend();
30252
30464
  const e = this.enclosure;
30253
30465
  if (!e) return;
30466
+ await this.findOwner(e);
30254
30467
  this.stopTimer();
30255
30468
  if (!e.released) {
30256
30469
  if (!e.lease) {
30257
- const list = await this.m.vm.list({ timeoutMs: 1e4 });
30470
+ const list = await this.vm.list({ timeoutMs: 1e4 });
30258
30471
  const matches = Object.values(list.machines).filter((lease) => lease.purpose === e.purpose);
30259
30472
  if (matches.length > 1) throw new Error("Ambiguous acquisition; refusing to remove ownership record");
30260
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.`);
@@ -30266,15 +30479,24 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30266
30479
  let released = false;
30267
30480
  for (let attempt = 0; attempt < attempts; attempt++) {
30268
30481
  try {
30269
- const response = await this.m.vm.release(e.lease.vm, { reason: reason2 }, { timeoutMs: timeoutMs2 });
30482
+ const response = await this.vm.release(e.lease.vm, { reason: reason2, ...e.lease.lease_id ? { lease_id: e.lease.lease_id } : {} }, { timeoutMs: timeoutMs2 });
30270
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
+ }
30271
30489
  released = true;
30272
30490
  break;
30273
30491
  } catch (error2) {
30274
30492
  await this.log("release-error", void 0, { vm: e.lease.vm, cause: reason2, attempt: attempt + 1, error: String(error2) }).catch(() => {
30275
30493
  });
30276
30494
  try {
30277
- 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
+ }
30278
30500
  } catch (getError) {
30279
30501
  if (getError instanceof MachineServiceError && getError.status === 404) {
30280
30502
  released = true;
@@ -30285,7 +30507,9 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30285
30507
  }
30286
30508
  }
30287
30509
  if (!released) throw new Error("Lease release unconfirmed");
30288
- 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.`);
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.`);
30289
30513
  }
30290
30514
  e.released = true;
30291
30515
  await this.save().catch(() => {
@@ -30295,12 +30519,16 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30295
30519
  await this.session?.close();
30296
30520
  this.session = void 0;
30297
30521
  this.transport = void 0;
30298
- 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(() => {
30299
30523
  });
30300
30524
  this.enclosure = void 0;
30301
30525
  await this.save();
30302
30526
  await this.m.forget(this);
30303
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
+ }
30304
30532
  async destroyed(vm) {
30305
30533
  if (this.m.options.verifyDestroyed) return this.m.options.verifyDestroyed(vm);
30306
30534
  const environment = this.m.environment;
@@ -30333,7 +30561,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30333
30561
  const remaining = this.remainingMs(e);
30334
30562
  if (remaining < MIN_RENEWAL_MS) return;
30335
30563
  try {
30336
- 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 });
30337
30565
  if (this.enclosure === e && !e.released) {
30338
30566
  e.expiresAt = renewed.ttl_expires_at;
30339
30567
  e.guestState = renewed.state;
@@ -30375,7 +30603,8 @@ var relayContract = typebox_exports.Union([
30375
30603
  typebox_exports.Object({
30376
30604
  action: typebox_exports.Literal("acquire"),
30377
30605
  task: typebox_exports.String({ pattern: "^[a-z0-9][a-z0-9-]{0,35}$" }),
30378
- 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." })),
30379
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 }),
30380
30609
  vnc: typebox_exports.Optional(typebox_exports.Boolean({ description: "Prepare guest console sharing, default false. Never opens a viewer automatically." })),
30381
30610
  ttlHours: typebox_exports.Optional(typebox_exports.Number({ minimum: 0.1, maximum: 720 })),
@@ -30432,6 +30661,7 @@ function toolInputSchema(action) {
30432
30661
  function validateRelayInput(value) {
30433
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.");
30434
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.");
30435
30665
  if (value.action === "run") {
30436
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.");
30437
30667
  if (value.diagnostic && value.snapshots?.group) throw new Error("Diagnostic scripts cannot join snapshot groups.");
@@ -30441,7 +30671,7 @@ function validateRelayInput(value) {
30441
30671
  }
30442
30672
 
30443
30673
  // src/surface.ts
30444
- import { mkdir as mkdir11, writeFile as writeFile4 } from "node:fs/promises";
30674
+ import { mkdir as mkdir11, writeFile as writeFile5 } from "node:fs/promises";
30445
30675
  import { join as join14 } from "node:path";
30446
30676
  import { tmpdir as tmpdir2 } from "node:os";
30447
30677
  import { randomUUID as randomUUID7 } from "node:crypto";
@@ -30472,9 +30702,9 @@ var relayTools = [
30472
30702
  {
30473
30703
  name: "relay_acquire",
30474
30704
  action: "acquire",
30475
- title: "Acquire a VM",
30705
+ title: "Acquire a machine",
30476
30706
  annotations: acts(false),
30477
- 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."
30478
30708
  },
30479
30709
  {
30480
30710
  name: "relay_stage",
@@ -30551,15 +30781,15 @@ function relayToolInput(name, args) {
30551
30781
  var relayResultKind = "relay-image-result-v1";
30552
30782
  async function renderRelayResult(value, resultRoot = join14(tmpdir2(), "mcp-relay-results"), indent = 2) {
30553
30783
  const full = JSON.stringify(value, null, indent);
30554
- const text4 = new TextDecoder().decode(Buffer.from(full.split("\n").slice(0, 2e3).join("\n")).subarray(0, 50 * 1024), { stream: true });
30555
- 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) {
30556
30786
  await mkdir11(resultRoot, { recursive: true, mode: 448 });
30557
30787
  const path = join14(resultRoot, `${randomUUID7()}.json`);
30558
- await writeFile4(path, full, { mode: 384 });
30559
- return { text: `${text4}
30788
+ await writeFile5(path, full, { mode: 384 });
30789
+ return { text: `${text5}
30560
30790
  [Truncated. Full result: ${path}]`, details: { resultPath: path }, resultPath: path };
30561
30791
  }
30562
- return { text: text4, details: value };
30792
+ return { text: text5, details: value };
30563
30793
  }
30564
30794
  async function imageResult(value, delivery, executionFailed = false) {
30565
30795
  const { content: image, ...imageDelivery } = delivery;
@@ -30636,11 +30866,11 @@ async function relayCall(host, raw, options = {}) {
30636
30866
 
30637
30867
  // src/server.ts
30638
30868
  var SERVER_NAME = "relay";
30639
- var SERVER_VERSION = true ? "0.16.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;
30640
30870
  var STATUS_TOOL = "relay_status";
30641
30871
  var PLUGIN_TOOL_PREFIX = "mcp__plugin_mcp-relay_relay__";
30642
30872
  var message2 = (error2) => error2 instanceof Error ? error2.message : String(error2);
30643
- var text3 = (value, isError = false) => ({ content: [{ type: "text", text: value }], isError });
30873
+ var text4 = (value, isError = false) => ({ content: [{ type: "text", text: value }], isError });
30644
30874
  function relayContent(result2) {
30645
30875
  return { content: [{ type: "text", text: result2.text }, ...result2.image ? [{ type: "image", data: result2.image.data, mimeType: result2.image.mimeType }] : []], isError: result2.isError };
30646
30876
  }
@@ -30689,11 +30919,11 @@ function createRelayServer(options = {}) {
30689
30919
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
30690
30920
  const { name, arguments: args } = request.params;
30691
30921
  try {
30692
- if (name === STATUS_TOOL) return text3(JSON.stringify(statusPayload(), null, 2));
30922
+ if (name === STATUS_TOOL) return text4(JSON.stringify(statusPayload(), null, 2));
30693
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) }));
30694
30924
  throw new Error(`Unknown tool: ${name}`);
30695
30925
  } catch (error2) {
30696
- return text3(message2(error2), true);
30926
+ return text4(message2(error2), true);
30697
30927
  }
30698
30928
  });
30699
30929
  const cleanup = async (reason2) => {