@wezzard/mcp-relay 0.18.0 → 0.19.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-relay",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "Runs an agent's code on fresh, isolated VMs, several at once, each run recorded with evidence",
5
5
  "author": {
6
6
  "name": "WeZZard"
package/README.md CHANGED
@@ -304,7 +304,7 @@ installation or platform acceptance is claimed here.
304
304
  ## Durable machines
305
305
 
306
306
  `relay_acquire` takes `machine` in place of `image` to lease a durable machine,
307
- a real Mac that machine-service exposes, such as `Build-Mac-1`. Every other
307
+ a real Mac that machine-service exposes, such as `Mac-A`. Every other
308
308
  tool works on it as on a VM ([docs/durable-machines.md](docs/durable-machines.md)).
309
309
 
310
310
  - The relay finds the instance that owns the machine as `machctl list` does:
@@ -315,6 +315,13 @@ tool works on it as on a VM ([docs/durable-machines.md](docs/durable-machines.md
315
315
  instance found is used only once its `/health` confirms its ID.
316
316
  - Every call carries the lease's `lease_id`, files go as bytes, and the relay
317
317
  stages under the lease's workspace, which machine-service removes at release.
318
+ - When machine-service reports `machine_id`, the relay saves it and can resume
319
+ the same lease after the Mac is renamed or its address changes. Requests keep
320
+ using the name the lease was granted under. Older services keep the existing
321
+ name and origin checks.
322
+ - A durable 404 never proves release. The relay finds the owner again and
323
+ verifies that its machine record no longer names the lease. An unreachable
324
+ owner leaves the lease retained with guest state `unknown`.
318
325
  - Runs take snapshots only while the Mac's cua-driver daemon (`CuaDriver.app`,
319
326
  `com.trycua.driver`) holds Screen Recording, read with
320
327
  `cua-driver permissions status --json` in the lease. machine-service's own
@@ -958,7 +958,7 @@
958
958
  "src/config.ts": "3fbc475596ec0a1b6122ea963bf2769420a8a2a0e62fda55e66018fb3a6d53b3",
959
959
  "src/console.ts": "d8258173a24449c2a394289b14983b9575c5ce753ab267d4e13213f3abfcb72d",
960
960
  "src/core.ts": "dd889fda6af982ab47b40b346e7fbc41a213b6d258d3d5fe56cd8c5373221159",
961
- "src/discovery.ts": "cd66b470615f7e2bf1d5d2cdf8065b6e0ec601a0929f7be063bc18bfcfbc342d",
961
+ "src/discovery.ts": "9a46e6ba9808d085b3294ab1d2e4fcf69f9ec86b5af79b758e19beac6bb7ee12",
962
962
  "src/doctor.ts": "8249e9fa78b679e9ef7fd30f617bf07848961346101d3b64c42f779cfb042671",
963
963
  "src/downloads.ts": "4f37b5bb4fac96f9260a3a87c83bacf715b9add5ae9926d3fe0994000c70a8dd",
964
964
  "src/environment.ts": "5770e966e49d78ae069614078c667f94e70074b150f83111049529ff613aa215",
@@ -967,9 +967,9 @@
967
967
  "src/guest/receiver.ts": "92fc8d3bfe95ed56d43cfe5b46eb196034ade5e4e9f58ed202465531458f697d",
968
968
  "src/image-presentation.ts": "64ca29a3444a04606cb783c81ac2d0f3136f9a9ac730ae9074156f0a63256c76",
969
969
  "src/images.ts": "415bfb37966a60ef3e407236295b9aeeb314f7fb33de55a6ada512cff6661908",
970
- "src/machine-service.ts": "1f7c63d295b2551728f975451bd1ab29a57cf4cab9f16510b7e3fcd1a6160205",
971
- "src/manager.ts": "7bbff05dd7d3c3c98f2d71e72834e1e08b0c96a963fb76876895537d75436749",
972
- "src/mdns.ts": "b85df92dfe3cd0807725a3115ecfdd21d1530a98528b6a55454370d6e4baf98c",
970
+ "src/machine-service.ts": "a6343138b2bb689772310b9798f6cb9d8bc16033f0ba3562039838c7aca1941e",
971
+ "src/manager.ts": "9f989175d07e8629ef8518c90a35db4131d2ea01e96a5de6d287c3d7a7f99ea5",
972
+ "src/mdns.ts": "cbff562d06db1edebb79a467f8fb90eb575647b4eb8efd1e28fb4b9b67a85a96",
973
973
  "src/owner-lock.ts": "a99cbaba67b4aff0e646dc5d5967db4497ba6dbda83fb1838c55f0bf0f6e0367",
974
974
  "src/package.ts": "a52ed791813922e3ace9144706ddde8313a67d8580a3acd54a0799de3ebe44d2",
975
975
  "src/probe.ts": "40a123f725aad7c22fe63707dd2de99646cb1f307d7d660927e8ca2b973e9ce0",
@@ -978,7 +978,7 @@
978
978
  "src/schema.ts": "7f68a85c9593fc2ad1455efd6e757c43f8ed591293fd820f1a08408db17c1912",
979
979
  "src/search-diagnostics.ts": "cea037618c56f075d51155101ad1cc0314bfa67b174bdb070191e0ea5ea04679",
980
980
  "src/search.ts": "8aaf544fcb27e7e018bd976e1ba7d3c70c047aeda3182b3dce91873a901a245e",
981
- "src/server.ts": "bff4c09c29890aa62175ead36d9cfd6f8fa7334d2ee0929b51a0371d38c5df1c",
981
+ "src/server.ts": "ed2475e4834484076ad51f216bacb5aea0f624129401ba9c688a6b0ed651659e",
982
982
  "src/surface.ts": "25681325cb01dfb04524bca8e0e5f3d4b4795d3db814384c7d1e9a8ec831eb16",
983
983
  "src/transfer.ts": "f27d65c0b42f9933e6a7f950f56111b84c644e8739bab44805aebfb54d77e320",
984
984
  "src/transport.ts": "35df20b321f52c4a371f1e29923e957e7c85d58001e2864f0fd13c2c2838945f",
package/dist/doctor.mjs CHANGED
@@ -161,7 +161,8 @@ var MachineService = class {
161
161
  }
162
162
  }
163
163
  async get(vm, options = {}) {
164
- return named(await this.request(this.path(vm), void 0, options));
164
+ const path = this.path(vm) + (options.lease_id ? `?${new URLSearchParams({ lease_id: options.lease_id })}` : "");
165
+ return named(await this.request(path, void 0, options));
165
166
  }
166
167
  /**
167
168
  * Cancellation before dispatch prevents allocation. Once dispatched we deliberately
@@ -276,7 +277,7 @@ var MachineService = class {
276
277
  const controller = new AbortController();
277
278
  const abort = () => controller.abort(options.signal?.reason);
278
279
  options.signal?.addEventListener("abort", abort, { once: true });
279
- const expire = () => controller.abort(new MachineServiceError(`machine-service ${path} timed out after ${timeoutMs}ms${stream.idle ? " without a byte" : ""}`));
280
+ const expire = () => controller.abort(Object.assign(new MachineServiceError(`machine-service ${path} timed out after ${timeoutMs}ms${stream.idle ? " without a byte" : ""}`), { code: "ETIMEDOUT" }));
280
281
  let timer = setTimeout(expire, timeoutMs);
281
282
  try {
282
283
  const response = await fetch(`${this.baseUrl}${path}`, {
@@ -1,6 +1,6 @@
1
1
  {
2
- "server.mjs": "2b04c5cf78833f392f9fe8570a0099a1f276c2c24ad036dc8107f9c24371c95a",
2
+ "server.mjs": "e4b503891cf0d2d6b331bf208298cc7261f8be2bcf936275cf8ea9e13cd75b43",
3
3
  "receiver.mjs": "8b5b6fdd6cb789cdc4060e367a155cb42e7cf34187044c899789bf76b7bb0e14",
4
- "doctor.mjs": "4e3d5a58ead4be3afe461691b6bff6f1f933bbde70b19fd67677f158975b6e3f",
4
+ "doctor.mjs": "179feaa8bfa45ebb3a8c9b7a52dd86c008c1b248a1e3c638bf53d64e6e7b991b",
5
5
  "review-data.mjs": "da7b6b35d060e09cfc445df4febda02a1a0c0f23d9b854866aed8d604cbb3993"
6
6
  }
package/dist/server.mjs CHANGED
@@ -17862,7 +17862,8 @@ var MachineService = class {
17862
17862
  }
17863
17863
  }
17864
17864
  async get(vm, options = {}) {
17865
- return named(await this.request(this.path(vm), void 0, options));
17865
+ const path = this.path(vm) + (options.lease_id ? `?${new URLSearchParams({ lease_id: options.lease_id })}` : "");
17866
+ return named(await this.request(path, void 0, options));
17866
17867
  }
17867
17868
  /**
17868
17869
  * Cancellation before dispatch prevents allocation. Once dispatched we deliberately
@@ -17977,7 +17978,7 @@ var MachineService = class {
17977
17978
  const controller = new AbortController();
17978
17979
  const abort = () => controller.abort(options.signal?.reason);
17979
17980
  options.signal?.addEventListener("abort", abort, { once: true });
17980
- const expire = () => controller.abort(new MachineServiceError(`machine-service ${path} timed out after ${timeoutMs2}ms${stream.idle ? " without a byte" : ""}`));
17981
+ const expire = () => controller.abort(Object.assign(new MachineServiceError(`machine-service ${path} timed out after ${timeoutMs2}ms${stream.idle ? " without a byte" : ""}`), { code: "ETIMEDOUT" }));
17981
17982
  let timer = setTimeout(expire, timeoutMs2);
17982
17983
  try {
17983
17984
  const response = await fetch(`${this.baseUrl}${path}`, {
@@ -28828,8 +28829,13 @@ async function refreshEvidenceState(incoming, destination, archiveRoot, options
28828
28829
  if (archived) await copy(archived, retained);
28829
28830
  }
28830
28831
 
28832
+ // src/discovery.ts
28833
+ import { existsSync } from "node:fs";
28834
+
28831
28835
  // src/mdns.ts
28836
+ import { spawn as spawn5 } from "node:child_process";
28832
28837
  import { createSocket } from "node:dgram";
28838
+ import { lookup } from "node:dns/promises";
28833
28839
  var TYPE = { A: 1, PTR: 12, TXT: 16, SRV: 33 };
28834
28840
  var GROUP = "224.0.0.251";
28835
28841
  var PORT = 5353;
@@ -28913,7 +28919,7 @@ function assemble(service, records) {
28913
28919
  const txt = Object.assign({}, ...by(TYPE.TXT, full).map((r) => txtOf(r.data)));
28914
28920
  const a = by(TYPE.A, host).find((r) => r.data.length === 4);
28915
28921
  const name = full.slice(0, full.length - service.length - 1);
28916
- found.push({ name, instance: txt.instance || name, host: host.replace(/\.$/, ""), ...a ? { address: [...a.data].join(".") } : {}, port, txt });
28922
+ found.push({ name, instance: txt.instance || name, ...txt.machine_id ? { machine_id: txt.machine_id } : {}, host: host.replace(/\.$/, ""), ...a ? { address: [...a.data].join(".") } : {}, port, txt });
28917
28923
  }
28918
28924
  return found.sort((x, y) => x.name.localeCompare(y.name));
28919
28925
  }
@@ -28931,8 +28937,11 @@ async function browse(service, windowMs = 2e3, followUpMs = 1e3, open9 = udpTran
28931
28937
  const records = [];
28932
28938
  const transport = await open9((message3) => records.push(...parseRecords(message3)));
28933
28939
  try {
28934
- transport.send(encodeQuery([{ name: service, type: TYPE.PTR }]));
28935
- await wait(windowMs);
28940
+ const question = encodeQuery([{ name: service, type: TYPE.PTR }]);
28941
+ transport.send(question);
28942
+ await wait(windowMs / 2);
28943
+ transport.send(question);
28944
+ await wait(windowMs / 2);
28936
28945
  const missing = [...new Set(records.filter((r) => r.type === TYPE.PTR && key(r.name) === key(service)).map((r) => readName(r.message, r.offset)[0]))].filter((full) => !assemble(service, records).some((found) => key(`${found.name}.${service}`) === key(full) && found.address));
28937
28946
  if (missing.length) {
28938
28947
  const hosts = records.filter((r) => r.type === TYPE.SRV).map((r) => readName(r.message, r.offset + 6)[0]);
@@ -28944,6 +28953,62 @@ async function browse(service, windowMs = 2e3, followUpMs = 1e3, open9 = udpTran
28944
28953
  transport.close();
28945
28954
  }
28946
28955
  }
28956
+ var unescape2 = (text5) => Buffer.from(text5.replace(/\\(\d{3})|\\(.)/g, (_, code, char) => code ? String.fromCharCode(Number(code)) : char), "latin1").toString("utf8");
28957
+ function parseZone(zone) {
28958
+ const lines = zone.split("\n").map((line) => line.replace(/\s;.*$/, "").trim()).filter((line) => line && !line.startsWith(";"));
28959
+ const field = (line) => line.match(/^(\S+)\s+(PTR|SRV|TXT)\s+(.*)$/);
28960
+ const order = [], srv = /* @__PURE__ */ new Map(), txt = /* @__PURE__ */ new Map();
28961
+ for (const line of lines) {
28962
+ const match = field(line);
28963
+ if (!match) continue;
28964
+ const [, owner, type, rest] = match;
28965
+ if (type === "PTR") {
28966
+ const full = rest.trim();
28967
+ if (!order.includes(full)) order.push(full);
28968
+ } else if (type === "SRV") {
28969
+ const [, , port, host] = rest.trim().split(/\s+/);
28970
+ if (port && host) srv.set(owner, { port: Number(port), host: host.replace(/\.$/, "") });
28971
+ } else txt.set(owner, Object.fromEntries([...rest.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map(([, pair]) => unescape2(pair)).filter((pair) => pair).map((pair) => {
28972
+ const at = pair.indexOf("=");
28973
+ return at < 0 ? [pair.toLowerCase(), ""] : [pair.slice(0, at).toLowerCase(), pair.slice(at + 1)];
28974
+ })));
28975
+ }
28976
+ return order.flatMap((full) => {
28977
+ const target = srv.get(full);
28978
+ if (!target) return [];
28979
+ const name = unescape2(full.split(/(?<!\\)\./)[0]);
28980
+ const record3 = txt.get(full) ?? {};
28981
+ return [{ name, instance: record3.instance || name, ...record3.machine_id ? { machine_id: record3.machine_id } : {}, host: target.host, port: target.port, txt: record3 }];
28982
+ });
28983
+ }
28984
+ var systemTools = {
28985
+ run: (argv, ms) => new Promise((resolve11) => {
28986
+ const child = spawn5(argv[0], argv.slice(1), { stdio: ["ignore", "pipe", "ignore"] });
28987
+ let out = "";
28988
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
28989
+ out += chunk;
28990
+ });
28991
+ const timer = setTimeout(() => child.kill("SIGTERM"), ms);
28992
+ child.on("close", () => {
28993
+ clearTimeout(timer);
28994
+ resolve11(out);
28995
+ });
28996
+ child.on("error", () => {
28997
+ clearTimeout(timer);
28998
+ resolve11(out);
28999
+ });
29000
+ }),
29001
+ lookup: (host) => lookup(host, { family: 4 }).then((found) => found.address, () => void 0)
29002
+ };
29003
+ var DNS_SD = "/usr/bin/dns-sd";
29004
+ async function systemBrowse(service, windowMs = 1500, tools = systemTools) {
29005
+ const type = service.replace(/\.local\.?$/, "");
29006
+ const found = parseZone(await tools.run([DNS_SD, "-Z", type, "local."], windowMs));
29007
+ return Promise.all(found.map(async (advert) => {
29008
+ const address = await tools.lookup(advert.host);
29009
+ return address ? { ...advert, address } : advert;
29010
+ }));
29011
+ }
28947
29012
 
28948
29013
  // src/discovery.ts
28949
29014
  var SERVICE_TYPE = "_machine-service._tcp.local";
@@ -28970,14 +29035,14 @@ function parseRegistrations(answer) {
28970
29035
  const host = text3(service?.Address) || text3(node2?.Address);
28971
29036
  if (!host || !Number.isSafeInteger(port)) return [];
28972
29037
  const meta2 = service?.Meta ?? {};
28973
- 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" }];
29038
+ return [{ node: text3(node2?.Node), origin: new URL(`http://${host.includes(":") ? `[${host}]` : host}:${port}`).origin, ...text3(meta2.instance) ? { instance: text3(meta2.instance) } : {}, ...text3(meta2.machine_id) ? { machine_id: text3(meta2.machine_id) } : {}, loopbackOnly: meta2.loopback_only === "true" }];
28974
29039
  });
28975
29040
  }
28976
29041
  async function candidates(options, mode) {
28977
29042
  if (mode === "bonjour") {
28978
29043
  try {
28979
- const advertised = await (options.browse ?? (() => browse(SERVICE_TYPE)))();
28980
- return { found: advertised.map((a) => ({ origin: new URL(`http://${a.address ?? a.host}:${a.port}`).origin, expected: a.instance })) };
29044
+ const advertised = await (options.browse ?? (() => existsSync(DNS_SD) ? systemBrowse(SERVICE_TYPE) : browse(SERVICE_TYPE)))();
29045
+ return { found: advertised.map((a) => ({ origin: new URL(`http://${a.address ?? a.host}:${a.port}`).origin, expected: a.instance, ...a.machine_id || a.txt.machine_id ? { machine_id: a.machine_id || a.txt.machine_id } : {} })) };
28981
29046
  } catch (error2) {
28982
29047
  return { found: [], error: `the Bonjour browse failed (${error2 instanceof Error ? error2.message : String(error2)})` };
28983
29048
  }
@@ -28985,46 +29050,74 @@ async function candidates(options, mode) {
28985
29050
  const consul = options.consul ?? consulAddress();
28986
29051
  try {
28987
29052
  const rows = parseRegistrations(await (options.fetchJson ?? fetchJson)(`${consul}/v1/health/service/machine-service`));
28988
- return { found: rows.filter((row) => !row.loopbackOnly).map((row) => ({ origin: row.origin, ...row.instance ? { expected: row.instance } : {} })) };
29053
+ return { found: rows.filter((row) => !row.loopbackOnly).map((row) => ({ origin: row.origin, ...row.instance ? { expected: row.instance } : {}, ...row.machine_id ? { machine_id: row.machine_id } : {} })) };
28989
29054
  } catch (error2) {
28990
29055
  return { found: [], error: `the Consul agent at ${consul} did not answer (${error2 instanceof Error ? error2.message : String(error2)})` };
28991
29056
  }
28992
29057
  }
28993
- async function confirmed(backend, expected) {
28994
- const health = await backend.health({ timeoutMs: TIMEOUT_MS });
29058
+ function confirmed(health, expected, machine_id) {
28995
29059
  if (health.service !== void 0 && health.service !== "machine-service") return `it answers as ${String(health.service)}, not machine-service`;
28996
- if (health.instance !== expected) return `it was found as ${expected}, but its /health answers ${String(health.instance ?? "no instance")}`;
29060
+ if (machine_id) return health.machine_id === machine_id ? void 0 : `it was found with machine_id ${machine_id}, but its /health answers machine_id ${String(health.machine_id ?? "none")}`;
29061
+ if (expected && health.instance !== expected) return `it was found as ${expected}, but its /health answers ${String(health.instance ?? "no instance")}`;
28997
29062
  return void 0;
28998
29063
  }
28999
- async function findDurableOwner(machine, options) {
29064
+ function findDurableOwner(machine, options) {
29065
+ return findOwner({ name: machine }, options);
29066
+ }
29067
+ function findDurableOwnerById(machine_id, options) {
29068
+ return findOwner({ machine_id }, options);
29069
+ }
29070
+ async function findOwner(target, options) {
29071
+ const machine = target.name ?? `with machine_id ${target.machine_id}`;
29000
29072
  const mode = options.mode ?? discoveryMode();
29001
29073
  const make = options.backend ?? ((origin) => new MachineService({ baseUrl: origin, listed: true }));
29002
29074
  const localOrigin = new URL(options.local.baseUrl).origin;
29003
- const { found, error: discoveryError } = await candidates(options, mode);
29004
- const asked = [{ origin: localOrigin, backend: options.local }];
29005
- for (const candidate of found) if (!asked.some((a) => a.origin === candidate.origin)) asked.push({ ...candidate, backend: make(candidate.origin) });
29006
- const owners = [];
29007
- const refused = [];
29008
- await Promise.all(asked.map(async ({ origin, backend, expected }) => {
29009
- try {
29010
- if (expected) {
29011
- const why = await confirmed(backend, expected);
29075
+ const look = async () => {
29076
+ const { found, error: discoveryError2 } = await candidates(options, mode);
29077
+ const asked = [{ origin: localOrigin, backend: options.local }];
29078
+ for (const candidate of found) if (!asked.some((a) => a.origin === candidate.origin)) asked.push({ ...candidate, backend: make(candidate.origin) });
29079
+ const owners = [];
29080
+ const refused2 = [];
29081
+ await Promise.all(asked.map(async ({ origin, backend, expected, machine_id: advertisedId }) => {
29082
+ try {
29083
+ const health = await backend.health({ timeoutMs: TIMEOUT_MS }).catch((error2) => {
29084
+ if (expected || advertisedId || target.machine_id) throw error2;
29085
+ return {};
29086
+ });
29087
+ const why = confirmed(health, expected, advertisedId);
29012
29088
  if (why) {
29013
- refused.push(`${origin}: ${why}`);
29089
+ refused2.push(`${origin}: ${why}`);
29014
29090
  return;
29015
29091
  }
29092
+ if (target.machine_id && health.machine_id !== target.machine_id) return;
29093
+ const machines = (await backend.list({ timeoutMs: TIMEOUT_MS })).machines;
29094
+ const record3 = target.name ? machines[target.name] : Object.values(machines).find((record4) => record4.kind === "durable" && (!record4.machine_id || record4.machine_id === target.machine_id));
29095
+ if (record3?.kind === "durable") {
29096
+ const recordId = text3(record3.machine_id), healthId = text3(health.machine_id);
29097
+ if (recordId && healthId && recordId !== healthId) {
29098
+ refused2.push(`${origin}: its durable record machine_id ${recordId} differs from /health machine_id ${healthId}`);
29099
+ return;
29100
+ }
29101
+ const machine_id = healthId || recordId;
29102
+ owners.push({ backend, origin, instance: machine_id && text3(health.instance) || record3.instance || machine, ...machine_id ? { machine_id } : {} });
29103
+ }
29104
+ } catch {
29016
29105
  }
29017
- const record3 = (await backend.list({ timeoutMs: TIMEOUT_MS })).machines[machine];
29018
- if (record3?.kind === "durable") owners.push({ backend, origin, instance: record3.instance ?? machine });
29019
- } catch {
29020
- }
29021
- }));
29022
- owners.sort((a, b) => Number(b.origin === localOrigin) - Number(a.origin === localOrigin));
29023
- const distinct = owners.filter((owner, index) => owners.findIndex((other) => other.instance === owner.instance) === index);
29106
+ }));
29107
+ owners.sort((a, b) => Number(b.origin === localOrigin) - Number(a.origin === localOrigin));
29108
+ const identity = (owner) => owner.machine_id ? `${owner.machine_id}:${new URL(owner.origin).port || (new URL(owner.origin).protocol === "https:" ? "443" : "80")}` : owner.instance;
29109
+ const distinct2 = owners.filter((owner, index) => owners.findIndex((other) => identity(other) === identity(owner)) === index);
29110
+ return { distinct: distinct2, refused: refused2, discoveryError: discoveryError2 };
29111
+ };
29112
+ let { distinct, refused, discoveryError } = await look();
29113
+ if (!distinct.length && mode === "bonjour") {
29114
+ await new Promise((resolve11) => setTimeout(resolve11, options.secondLookMs ?? 2e3));
29115
+ ({ distinct, refused, discoveryError } = await look());
29116
+ }
29024
29117
  if (distinct.length === 1) return distinct[0];
29025
29118
  if (distinct.length > 1) throw new Error(`Durable machine ${machine} is listed by more than one instance (${distinct.map((owner) => owner.origin).join(", ")}); nothing was acquired`);
29026
29119
  const hint = mode === "bonjour" ? "Check the name with `machctl list`; the Mac's machine-service must be bound to all interfaces to advertise itself, or set MACHINE_SERVICE_DISCOVERY=consul to use a Consul agent." : "Check the name with `machctl list`, and point CONSUL_HTTP_ADDR at a reachable Consul agent.";
29027
- throw new Error(`No machine-service instance lists a durable machine named ${machine}${discoveryError ? `, and ${discoveryError}` : ""}${refused.length ? `; unconfirmed: ${refused.join("; ")}` : ""}; nothing was acquired. ${hint}`);
29120
+ throw new Error(`No machine-service instance lists a durable machine ${target.name ? `named ${target.name}` : machine}${discoveryError ? `, and ${discoveryError}` : ""}${refused.length ? `; unconfirmed: ${refused.join("; ")}` : ""}; nothing was acquired. ${hint}`);
29028
29121
  }
29029
29122
 
29030
29123
  // src/capture-gate.ts
@@ -29070,6 +29163,15 @@ async function settleEach(work) {
29070
29163
  const failed = (await Promise.allSettled(work)).find((result2) => result2.status === "rejected");
29071
29164
  if (failed) throw failed.reason;
29072
29165
  }
29166
+ function originUnavailable(error2) {
29167
+ if (!(error2 instanceof MachineServiceError) || error2.status !== void 0) return false;
29168
+ const seen = /* @__PURE__ */ new Set();
29169
+ for (let cause = error2; cause instanceof Error && !seen.has(cause); cause = cause.cause) {
29170
+ seen.add(cause);
29171
+ if (["ECONNREFUSED", "ECONNRESET", "EPIPE", "UND_ERR_SOCKET", "ETIMEDOUT", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT"].includes(String(cause.code))) return true;
29172
+ }
29173
+ return false;
29174
+ }
29073
29175
  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.";
29074
29176
  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.";
29075
29177
  var RelayManager = class {
@@ -29111,8 +29213,8 @@ var RelayManager = class {
29111
29213
  /** Set once shutdown has paused the guests: no new acquisition or guest operation starts. */
29112
29214
  shuttingDown = false;
29113
29215
  /** The instance that owns a durable machine, found as machctl finds it (DC-29). */
29114
- durableOwner(machine) {
29115
- return findDurableOwner(machine, { local: this.vm, ...this.options.discovery ? { mode: this.options.discovery } : {}, ...this.options.bonjourBrowse ? { browse: this.options.bonjourBrowse } : {}, ...this.options.consul ? { consul: this.options.consul } : {}, ...this.options.durableBackend ? { backend: this.options.durableBackend } : {}, ...this.options.consulFetch ? { fetchJson: this.options.consulFetch } : {} });
29216
+ durableOwner(machine, machineId) {
29217
+ return (machineId ? findDurableOwnerById : findDurableOwner)(machineId ?? machine, { local: this.vm, ...this.options.discovery ? { mode: this.options.discovery } : {}, ...this.options.bonjourBrowse ? { browse: this.options.bonjourBrowse } : {}, ...this.options.consul ? { consul: this.options.consul } : {}, ...this.options.durableBackend ? { backend: this.options.durableBackend } : {}, ...this.options.consulFetch ? { fetchJson: this.options.consulFetch } : {} });
29116
29218
  }
29117
29219
  serialized(fn) {
29118
29220
  const next = this.queue.then(fn, fn);
@@ -29260,6 +29362,17 @@ var RelayManager = class {
29260
29362
  }
29261
29363
  }
29262
29364
  /** Every guest the session holds, with its state; `active` is true while any guest's lease is being renewed. */
29365
+ /**
29366
+ * The status after reading the session's saved guests, host-only, so a
29367
+ * restarted relay reports what it still owns. A session with nothing saved
29368
+ * creates nothing, and a session it cannot load reports what it has in memory.
29369
+ */
29370
+ async loadedStatus() {
29371
+ const saved = await Promise.all([join13(this.root, "guests"), join13(this.root, "lease.json")].map((path) => access(path).then(() => true, () => false)));
29372
+ if (saved.some(Boolean)) await this.load().catch(() => {
29373
+ });
29374
+ return this.status();
29375
+ }
29263
29376
  status() {
29264
29377
  const guests = [...this.guests.values()].map((guest2) => guest2.status());
29265
29378
  return { active: guests.some((guest2) => guest2.active), guests, maxGuests: this.maxGuests };
@@ -29580,29 +29693,92 @@ var Guest = class {
29580
29693
  const durable = !!this.enclosure?.machine;
29581
29694
  return {
29582
29695
  exec: async (name, argv, timeoutMs2 = 18e4, options) => {
29583
- const result2 = await this.vm.exec(name, { argv, timeout: Math.ceil(timeoutMs2 / 1e3), ...identity() }, { timeoutMs: options?.timeoutMs ?? timeoutMs2 + 3e4, signal: options?.signal });
29696
+ const result2 = await this.withOwner((backend) => backend.exec(this.enclosure?.machine ?? name, { argv, timeout: Math.ceil(timeoutMs2 / 1e3), ...identity() }, { timeoutMs: options?.timeoutMs ?? timeoutMs2 + 3e4, signal: options?.signal }), options);
29584
29697
  return { stdout: result2.output, stderr: result2.output, code: result2.rc };
29585
29698
  },
29586
29699
  push: async (name, local_path, remote_path) => {
29587
29700
  if (!durable) return this.vm.push(name, { local_path, remote_path, ...identity() });
29588
- if (!this.vm.pushBytes) throw new Error("Backend lacks byte transfers; upgrade machine-service");
29589
- return this.vm.pushBytes(name, { remote_path, bytes: await readFile9(local_path), ...identity() });
29701
+ const bytes = await readFile9(local_path);
29702
+ return this.withOwner((backend) => {
29703
+ if (!backend.pushBytes) throw new Error("Backend lacks byte transfers; upgrade machine-service");
29704
+ return backend.pushBytes(this.enclosure.machine, { remote_path, bytes, ...identity() });
29705
+ });
29590
29706
  },
29591
29707
  pull: async (name, remote_path, local_path, options) => {
29592
29708
  if (!durable) return this.vm.pull(name, { remote_path, local_path, ...identity() }, options);
29593
- if (!this.vm.pullBytes) throw new Error("Backend lacks byte transfers; upgrade machine-service");
29594
29709
  await rm5(local_path, { force: true });
29595
- await this.vm.pullBytes(name, { remote_path, to: local_path, ...identity() }, options);
29710
+ await this.withOwner((backend) => {
29711
+ if (!backend.pullBytes) throw new Error("Backend lacks byte transfers; upgrade machine-service");
29712
+ return backend.pullBytes(this.enclosure.machine, { remote_path, to: local_path, ...identity() }, options);
29713
+ }, options);
29596
29714
  return { vm: name, pulled: remote_path, to: local_path };
29597
29715
  }
29598
29716
  };
29599
29717
  }
29600
- /** Find a durable machine's owner again, and refuse when its origin or instance changed (DC-29). */
29601
- async findOwner(e) {
29602
- if (!e.machine || this.owner) return;
29603
- const owner = await this.m.durableOwner(e.machine);
29604
- 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`);
29605
- this.owner = owner.backend;
29718
+ /** A saved machine ID survives renames; legacy ownership still requires its name and origin. */
29719
+ async findOwner(e, force = false) {
29720
+ if (!e.machine || this.owner && !force) return;
29721
+ try {
29722
+ const owner = await this.m.durableOwner(e.machine, e.backend?.machine_id);
29723
+ if (e.backend?.machine_id) {
29724
+ if (owner.machine_id !== e.backend.machine_id) throw new Error(`Durable owner machine_id mismatch; nothing was sent`);
29725
+ } else if (e.backend?.endpoint && (owner.origin !== e.backend.endpoint || owner.instance !== e.backend.instance)) {
29726
+ 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`);
29727
+ }
29728
+ this.owner = owner.backend;
29729
+ e.backend = { ...e.backend, endpoint: owner.origin, instance: owner.instance };
29730
+ await this.save();
29731
+ } catch (error2) {
29732
+ await this.unknownOwner(e, error2);
29733
+ }
29734
+ }
29735
+ async unknownOwner(e, cause) {
29736
+ this.owner = void 0;
29737
+ e.guestState = "unknown";
29738
+ const error2 = new Error(`Cannot confirm durable machine ${e.machine}: ${message(cause)}; ownership retained, guest state unknown`, { cause });
29739
+ e.lastError = error2.message;
29740
+ await this.save();
29741
+ throw error2;
29742
+ }
29743
+ /** Retry a durable request once after discovery confirms the saved machine ID. Acquisition never uses this. */
29744
+ async withOwner(operation, options = {}) {
29745
+ options.signal?.throwIfAborted();
29746
+ if (this.enclosure?.machine && !this.owner) await this.findOwner(this.enclosure);
29747
+ try {
29748
+ return await operation(this.vm);
29749
+ } catch (error2) {
29750
+ const e = this.enclosure;
29751
+ if (!e?.machine || !e.backend?.machine_id || options.signal?.aborted || !originUnavailable(error2)) throw error2;
29752
+ await this.findOwner(e, true);
29753
+ options.signal?.throwIfAborted();
29754
+ try {
29755
+ return await operation(this.vm);
29756
+ } catch (retryError) {
29757
+ if (!options.signal?.aborted && originUnavailable(retryError)) return this.unknownOwner(e, retryError);
29758
+ throw retryError;
29759
+ }
29760
+ }
29761
+ }
29762
+ /** A durable 404 proves nothing: rediscover and inspect the owner's inventory (DC-36). */
29763
+ async leaseRecord(e, options = {}) {
29764
+ const request = { timeoutMs: 1e4, ...options };
29765
+ try {
29766
+ try {
29767
+ const record3 = await this.withOwner((backend) => backend.get(e.machine ?? e.lease.vm, { ...request, ...e.machine ? { lease_id: e.lease?.lease_id } : {} }), request);
29768
+ if (e.machine && e.backend?.machine_id && record3.machine_id && record3.machine_id !== e.backend.machine_id) throw new Error("Durable owner machine_id mismatch");
29769
+ return record3;
29770
+ } catch (error2) {
29771
+ if (!e.machine || !(error2 instanceof MachineServiceError) || error2.status !== 404) throw error2;
29772
+ await this.findOwner(e, true);
29773
+ const records = Object.entries((await this.vm.list(request)).machines).filter(([name, record4]) => record4.kind === "durable" && (e.backend?.machine_id ? !record4.machine_id || record4.machine_id === e.backend.machine_id : name === e.machine));
29774
+ const record3 = records.length === 1 ? records[0][1] : void 0;
29775
+ if (!record3) throw new Error(`Cannot read the record of durable machine ${e.machine}`);
29776
+ return record3;
29777
+ }
29778
+ } catch (error2) {
29779
+ if (e.machine && !options.signal?.aborted) return this.unknownOwner(e, error2);
29780
+ throw error2;
29781
+ }
29606
29782
  }
29607
29783
  serialized(fn) {
29608
29784
  const next = this.queue.then(fn, fn);
@@ -29659,14 +29835,14 @@ var Guest = class {
29659
29835
  await this.findOwner(e);
29660
29836
  e.backend ??= this.m.binding();
29661
29837
  if (!e.lease) {
29662
- const matches = Object.values((await this.vm.list({ timeoutMs: 1e4 })).machines).filter((v) => v.purpose === e.purpose);
29838
+ const matches = Object.values((await this.withOwner((backend) => backend.list({ timeoutMs: 1e4 }))).machines).filter((v) => v.purpose === e.purpose);
29663
29839
  if (matches.length !== 1) throw new Error(`Cannot reconcile acquisition for ${e.purpose}; ownership retained, never automatically reacquire`);
29664
29840
  e.lease = matches[0];
29665
29841
  e.acquisitionInFlight = false;
29666
29842
  if (e.machine && e.lease.workspace) e.guestRoot = durableRoot(e.lease.workspace, e.purpose);
29667
29843
  }
29668
29844
  try {
29669
- const lease = await this.vm.get(e.lease.vm, { timeoutMs: 1e4 });
29845
+ const lease = await this.leaseRecord(e);
29670
29846
  if (e.machine && lease.lease_id !== e.lease.lease_id) {
29671
29847
  await this.m.registry.remove(e.row);
29672
29848
  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() });
@@ -29681,7 +29857,7 @@ var Guest = class {
29681
29857
  lease.console = consoleStatus(lease.console);
29682
29858
  if (lease.console.status === "revoked") e.consoleObservation = lease.console;
29683
29859
  }
29684
- e.lease = lease;
29860
+ e.lease = e.machine ? { ...lease, vm: e.machine } : lease;
29685
29861
  e.guestState = lease.state;
29686
29862
  e.expiresAt = lease.ttl_expires_at;
29687
29863
  if (e.failed) {
@@ -29691,7 +29867,7 @@ var Guest = class {
29691
29867
  await this.save();
29692
29868
  } catch (error2) {
29693
29869
  e.guestState = "unknown";
29694
- if (error2 instanceof MachineServiceError && error2.status === 404 && await this.destroyed(e.lease.vm)) {
29870
+ if (!e.machine && error2 instanceof MachineServiceError && error2.status === 404 && await this.destroyed(e.lease.vm)) {
29695
29871
  await this.m.registry.remove(e.row);
29696
29872
  await jsonFile(`${e.hostRoot}.lifecycle.json`, { purpose: e.purpose, vm: e.lease.vm, released: true, reason: "backend lease absent and destruction verified", finishedAt: (/* @__PURE__ */ new Date()).toISOString() });
29697
29873
  this.enclosure = void 0;
@@ -29731,7 +29907,7 @@ var Guest = class {
29731
29907
  const tsx = checks[1], nodeVersion = /^v(\d+)\.(\d+)/.exec(String(checks[0].stdout ?? ""));
29732
29908
  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" });
29733
29909
  let software;
29734
- if (e.machine) software = { machine: e.machine, software: (await this.vm.get(e.lease.vm, { timeoutMs: 1e4 })).capabilities?.software ?? null };
29910
+ if (e.machine) software = { machine: e.machine, software: (await this.leaseRecord(e)).capabilities?.software ?? null };
29735
29911
  else try {
29736
29912
  const catalog = await this.vm.applications({ timeoutMs: 1e4 });
29737
29913
  validateCatalog(catalog);
@@ -29861,7 +30037,7 @@ var Guest = class {
29861
30037
  const hostRoot = join13(this.m.options.outputRoot ?? resolve9(project, "relay-evidence"), purpose);
29862
30038
  const subject = input.machine ?? input.image;
29863
30039
  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 };
29864
- 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 };
30040
+ const e = this.enclosure = { backend: owner ? { endpoint: owner.origin, instance: owner.instance, ...owner.machine_id ? { machine_id: owner.machine_id } : {} } : 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 };
29865
30041
  if (owner) this.owner = owner.backend;
29866
30042
  let refused = false;
29867
30043
  try {
@@ -29887,7 +30063,12 @@ var Guest = class {
29887
30063
  try {
29888
30064
  const ttl_hours = Math.min(this.m.renewalWindowMs(), ttlHours * 36e5) / 36e5;
29889
30065
  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 });
29890
- if (e.machine) e.guestRoot = durableRoot(e.lease.workspace, purpose);
30066
+ if (e.machine) {
30067
+ e.lease.vm = e.machine;
30068
+ if (e.backend?.machine_id && e.lease.machine_id && e.lease.machine_id !== e.backend.machine_id) await this.unknownOwner(e, new Error("Durable owner machine_id mismatch"));
30069
+ e.backend.machine_id ??= e.lease.machine_id;
30070
+ e.guestRoot = durableRoot(e.lease.workspace, purpose);
30071
+ }
29891
30072
  e.acquisitionInFlight = false;
29892
30073
  granted = asked;
29893
30074
  break;
@@ -30018,7 +30199,7 @@ Guest ${this.name} keeps this acquisition's ownership record: name it to reconci
30018
30199
  }
30019
30200
  this.assertBinding();
30020
30201
  await this.m.assertBackend();
30021
- 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 });
30202
+ const renewed = await this.withOwner((backend) => backend.heartbeat(e.machine ?? lease.vm, { ttl_hours: Math.min(this.m.renewalWindowMs(), remaining) / 36e5, ...lease.lease_id ? { lease_id: lease.lease_id } : {} }, { timeoutMs: 1e4 }));
30022
30203
  if (this.enclosure !== e || e.released) return;
30023
30204
  e.expiresAt = renewed.ttl_expires_at;
30024
30205
  e.guestState = renewed.state;
@@ -30136,7 +30317,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30136
30317
  * Recording (DC-32).
30137
30318
  */
30138
30319
  async durableCapture(e, cuaDriver, signal) {
30139
- const software = (await this.vm.get(e.lease.vm, { timeoutMs: 1e4, signal })).capabilities?.software;
30320
+ const software = (await this.leaseRecord(e, { signal })).capabilities?.software;
30140
30321
  let answer;
30141
30322
  if (software && typeof software === "object" && software.cua_driver) {
30142
30323
  try {
@@ -30247,7 +30428,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30247
30428
  return new ImageStore({
30248
30429
  owner: this.m.options.sessionId,
30249
30430
  enclosure: e.purpose,
30250
- backend: e.backend,
30431
+ backend: e.machine && e.backend?.machine_id ? { machine_id: e.backend.machine_id } : e.backend,
30251
30432
  catalogRoot: join13(this.m.root, "image-catalog", e.purpose),
30252
30433
  hostRoot: e.hostRoot,
30253
30434
  guestRoot: e.guestRoot,
@@ -30262,7 +30443,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30262
30443
  if (!health.ok || !matchesEnvironment(health.environment, this.m.environment)) throw Object.assign(new Error("Selected backend identity changed."), { code: "unauthorized-reference" });
30263
30444
  }
30264
30445
  try {
30265
- const lease = await this.vm.get(e.lease.vm, options);
30446
+ const lease = await this.leaseRecord(e, options);
30266
30447
  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" });
30267
30448
  } catch (error2) {
30268
30449
  if (error2 instanceof MachineServiceError && error2.status === 404) throw Object.assign(new Error("Saved image guest is no longer available."), { code: "stale-reference" });
@@ -30653,11 +30834,12 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30653
30834
  this.stopTimer();
30654
30835
  if (!e.released) {
30655
30836
  if (!e.lease) {
30656
- const list = await this.vm.list({ timeoutMs: 1e4 });
30837
+ const list = await this.withOwner((backend) => backend.list({ timeoutMs: 1e4 }));
30657
30838
  const matches = Object.values(list.machines).filter((lease) => lease.purpose === e.purpose);
30658
30839
  if (matches.length > 1) throw new Error("Ambiguous acquisition; refusing to remove ownership record");
30659
30840
  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.`);
30660
30841
  e.lease = matches[0];
30842
+ if (e.machine && e.lease) e.lease.vm = e.machine;
30661
30843
  await this.save().catch(() => {
30662
30844
  });
30663
30845
  }
@@ -30665,7 +30847,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30665
30847
  let released = false;
30666
30848
  for (let attempt = 0; attempt < attempts; attempt++) {
30667
30849
  try {
30668
- const response = await this.vm.release(e.lease.vm, { reason: reason2, ...e.lease.lease_id ? { lease_id: e.lease.lease_id } : {} }, { timeoutMs: timeoutMs2 });
30850
+ const response = await this.withOwner((backend) => backend.release(e.machine ?? e.lease.vm, { reason: reason2, ...e.lease.lease_id ? { lease_id: e.lease.lease_id } : {} }, { timeoutMs: timeoutMs2 }));
30669
30851
  if (!response.released) throw new Error("machine-service did not confirm destruction");
30670
30852
  if (e.machine) {
30671
30853
  e.hygiene = response.hygiene;
@@ -30677,16 +30859,20 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30677
30859
  } catch (error2) {
30678
30860
  await this.log("release-error", void 0, { vm: e.lease.vm, cause: reason2, attempt: attempt + 1, error: String(error2) }).catch(() => {
30679
30861
  });
30680
- try {
30681
- const record3 = await this.vm.get(e.lease.vm, { timeoutMs: 5e3 });
30682
- if (e.machine && record3.lease_id !== e.lease.lease_id) {
30862
+ if (e.machine) {
30863
+ if (error2 instanceof MachineServiceError && error2.status === 404) await this.findOwner(e, true);
30864
+ if (await this.durableReleased(e)) {
30683
30865
  released = true;
30684
30866
  break;
30685
30867
  }
30686
- } catch (getError) {
30687
- if (getError instanceof MachineServiceError && getError.status === 404) {
30688
- released = true;
30689
- break;
30868
+ } else {
30869
+ try {
30870
+ await this.vm.get(e.lease.vm, { timeoutMs: 5e3 });
30871
+ } catch (getError) {
30872
+ if (getError instanceof MachineServiceError && getError.status === 404) {
30873
+ released = true;
30874
+ break;
30875
+ }
30690
30876
  }
30691
30877
  }
30692
30878
  if (attempt === attempts - 1) throw error2;
@@ -30713,7 +30899,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30713
30899
  }
30714
30900
  /** A durable release is verified when the machine no longer names the lease (DC-33). */
30715
30901
  async durableReleased(e) {
30716
- return (await this.vm.get(e.lease.vm, { timeoutMs: 1e4 })).lease_id !== e.lease.lease_id;
30902
+ return (await this.leaseRecord(e)).lease_id !== e.lease.lease_id;
30717
30903
  }
30718
30904
  async destroyed(vm) {
30719
30905
  if (this.m.options.verifyDestroyed) return this.m.options.verifyDestroyed(vm);
@@ -30747,7 +30933,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
30747
30933
  const remaining = this.remainingMs(e);
30748
30934
  if (remaining < MIN_RENEWAL_MS) return;
30749
30935
  try {
30750
- 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 });
30936
+ const renewed = await this.withOwner((backend) => backend.heartbeat(e.machine ?? e.lease.vm, { ttl_hours: remaining / 36e5, ...e.lease.lease_id ? { lease_id: e.lease.lease_id } : {} }, { timeoutMs: 1e4 }));
30751
30937
  if (this.enclosure === e && !e.released) {
30752
30938
  e.expiresAt = renewed.ttl_expires_at;
30753
30939
  e.guestState = renewed.state;
@@ -31052,7 +31238,7 @@ async function relayCall(host, raw, options = {}) {
31052
31238
 
31053
31239
  // src/server.ts
31054
31240
  var SERVER_NAME = "relay";
31055
- var SERVER_VERSION = true ? "0.18.0" : JSON.parse(readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8")).version;
31241
+ var SERVER_VERSION = true ? "0.19.0" : JSON.parse(readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8")).version;
31056
31242
  var STATUS_TOOL = "relay_status";
31057
31243
  var PLUGIN_TOOL_PREFIX = "mcp__plugin_mcp-relay_relay__";
31058
31244
  var message2 = (error2) => error2 instanceof Error ? error2.message : String(error2);
@@ -31094,10 +31280,11 @@ function createRelayServer(options = {}) {
31094
31280
  }
31095
31281
  return manager;
31096
31282
  });
31097
- const statusPayload = () => {
31283
+ const statusPayload = async () => {
31098
31284
  const environment = selectedEnvironment();
31099
31285
  const service = environment?.profile.vmServiceUrl ?? process.env.MCP_RELAY_URL ?? "http://localhost:6240";
31100
- return { ...manager ? manager.status() : { active: false, guests: [], maxGuests: maxGuests() }, project, service, environment: environment?.identity };
31286
+ const owned = get();
31287
+ return { ...await owned.loadedStatus(), project, service, environment: environment?.identity };
31101
31288
  };
31102
31289
  const shutdownController = new AbortController();
31103
31290
  const server = new Server({ name: SERVER_NAME, version: SERVER_VERSION }, { capabilities: { tools: {} }, instructions });
@@ -31105,7 +31292,7 @@ function createRelayServer(options = {}) {
31105
31292
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
31106
31293
  const { name, arguments: args } = request.params;
31107
31294
  try {
31108
- if (name === STATUS_TOOL) return text4(JSON.stringify(statusPayload(), null, 2));
31295
+ if (name === STATUS_TOOL) return text4(JSON.stringify(await statusPayload(), null, 2));
31109
31296
  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) }));
31110
31297
  throw new Error(`Unknown tool: ${name}`);
31111
31298
  } catch (error2) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wezzard/mcp-relay",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "type": "module",
5
5
  "description": "MCP server and Claude Code plugin. Runs an agent's code on fresh, isolated VMs, several at once, each run recorded with evidence",
6
6
  "license": "MIT",
@@ -55,7 +55,7 @@
55
55
  "build": "node scripts/build.mjs",
56
56
  "setup:dev": "node scripts/setup-dev.mjs",
57
57
  "typecheck": "tsc --noEmit",
58
- "test": "tsx --test tests/*.test.ts scripts/selected-image-x11.test.ts",
58
+ "test": "tsx --test --test-concurrency=1 tests/*.test.ts scripts/selected-image-x11.test.ts",
59
59
  "check": "npm run build && npm run typecheck && npm test",
60
60
  "test:e2e": "tsx --test tests/e2e/headless.test.ts",
61
61
  "verify:package": "node scripts/verify-package.mjs"
package/pi-mcp.json CHANGED
@@ -1 +1 @@
1
- {"mcpServers":{"relay":{"command":"npx","args":["-y","@wezzard/mcp-relay@0.18.0"],"lifecycle":"lazy-keep-alive","requestTimeoutMs":3900000,"directTools":true,"toolPrefix":"none"}}}
1
+ {"mcpServers":{"relay":{"command":"npx","args":["-y","@wezzard/mcp-relay@0.19.0"],"lifecycle":"lazy-keep-alive","requestTimeoutMs":3900000,"directTools":true,"toolPrefix":"none"}}}