@wezzard/mcp-relay 0.16.0 → 0.17.1
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/.claude-plugin/plugin.json +1 -1
- package/README.md +27 -7
- package/agents/vm-relay-operator.md +3 -2
- package/dist/build-info.json +7 -5
- package/dist/doctor.mjs +114 -29
- package/dist/integrity.json +2 -2
- package/dist/server.mjs +448 -182
- package/package.json +1 -1
- package/pi-mcp.json +1 -1
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((
|
|
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(
|
|
7603
|
+
function defineLazy(object6, key, getter) {
|
|
7604
7604
|
let value = void 0;
|
|
7605
|
-
Object.defineProperty(
|
|
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(
|
|
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
|
|
11972
|
-
for (const key in
|
|
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
|
|
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((
|
|
11992
|
+
if (objects.every((object6) => object6.additionalProperties === false)) {
|
|
11993
11993
|
folded.additionalProperties = false;
|
|
11994
11994
|
} else {
|
|
11995
11995
|
const constraints = [];
|
|
11996
|
-
for (const
|
|
11997
|
-
const constraint = undeclaredConstraint(
|
|
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
|
|
17187
|
+
import { mkdir as mkdir10, readFile as readFile9, readdir as readdir7, rm as rm5, cp, access, statfs } 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
|
|
17246
|
-
const raw = JSON.parse(
|
|
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 <
|
|
17250
|
-
if (
|
|
17249
|
+
for (let i = 0; i < text5.length; i++) {
|
|
17250
|
+
if (text5[i] === '"') {
|
|
17251
17251
|
const start = i++;
|
|
17252
|
-
for (; i <
|
|
17252
|
+
for (; i < text5.length && text5[i] !== '"'; i++) if (text5[i] === "\\") i++;
|
|
17253
17253
|
let next = i + 1;
|
|
17254
|
-
while (/\s/.test(
|
|
17255
|
-
if (depth === 1 &&
|
|
17256
|
-
const key = JSON.parse(
|
|
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 (
|
|
17261
|
-
else if (
|
|
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:
|
|
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 =
|
|
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:
|
|
17663
|
-
const codeSha256 =
|
|
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,8 @@ 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";
|
|
17752
|
+
import { open as open2, rm } from "node:fs/promises";
|
|
17751
17753
|
var MachineServiceError = class extends Error {
|
|
17752
17754
|
constructor(message3, status, responseBody, options) {
|
|
17753
17755
|
super(message3, options);
|
|
@@ -17770,13 +17772,14 @@ function capacityRefusal(error2) {
|
|
|
17770
17772
|
}
|
|
17771
17773
|
if (!body || typeof body !== "object") return false;
|
|
17772
17774
|
const { error: reason2, outcome } = body;
|
|
17773
|
-
return typeof reason2 === "string" &&
|
|
17775
|
+
return typeof reason2 === "string" && /^(macOS VM limit reached|durable machine leased|durable machine unavailable)/.test(reason2) && outcome !== "uncertain";
|
|
17774
17776
|
}
|
|
17775
17777
|
var SERVICE_NAME = "machine-service";
|
|
17776
17778
|
function expectMachineService(health, origin) {
|
|
17777
17779
|
if (health.service === SERVICE_NAME) return;
|
|
17778
17780
|
throw new Error(`The service at ${origin} answers as ${JSON.stringify(health.service ?? null)}, not ${SERVICE_NAME}. This relay speaks only machine-service's /machines API: install machine-service, which replaced vm-service.`);
|
|
17779
17781
|
}
|
|
17782
|
+
var PULL_IDLE_MS = 12e4;
|
|
17780
17783
|
var AcquireIndeterminateError = class extends MachineServiceError {
|
|
17781
17784
|
constructor(purpose, cause) {
|
|
17782
17785
|
super(`Acquisition outcome unknown for purpose '${purpose}'; reconcile GET /machines before retrying or ending the enclosure`, void 0, void 0, { cause });
|
|
@@ -17792,8 +17795,16 @@ function positive(value, label) {
|
|
|
17792
17795
|
function record2(value) {
|
|
17793
17796
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
17794
17797
|
}
|
|
17798
|
+
function named(value) {
|
|
17799
|
+
const fields = value;
|
|
17800
|
+
if (record2(value) && fields.kind === "durable" && typeof fields.vm !== "string" && typeof fields.name === "string") fields.vm = fields.name;
|
|
17801
|
+
return value;
|
|
17802
|
+
}
|
|
17795
17803
|
function isLease(value) {
|
|
17796
17804
|
if (!record2(value)) return false;
|
|
17805
|
+
if (named(value).kind === "durable") {
|
|
17806
|
+
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]));
|
|
17807
|
+
}
|
|
17797
17808
|
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
17809
|
}
|
|
17799
17810
|
var MachineService = class {
|
|
@@ -17809,8 +17820,8 @@ var MachineService = class {
|
|
|
17809
17820
|
if (options.environment && url.origin !== new URL(options.environment.profile.vmServiceUrl).origin) throw new TypeError("Backend endpoint does not match the selected environment");
|
|
17810
17821
|
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
17811
17822
|
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");
|
|
17823
|
+
if (!loopback && !options.listed || !["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
|
17824
|
+
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
17825
|
}
|
|
17815
17826
|
this.baseUrl = url.origin;
|
|
17816
17827
|
this.timeoutMs = positive(options.timeoutMs ?? 66e4, "timeoutMs");
|
|
@@ -17820,8 +17831,10 @@ var MachineService = class {
|
|
|
17820
17831
|
health(options = {}) {
|
|
17821
17832
|
return this.request("/health", void 0, options);
|
|
17822
17833
|
}
|
|
17823
|
-
list(options = {}) {
|
|
17824
|
-
|
|
17834
|
+
async list(options = {}) {
|
|
17835
|
+
const list = await this.request("/machines", void 0, options);
|
|
17836
|
+
if (record2(list.machines)) Object.values(list.machines).forEach(named);
|
|
17837
|
+
return list;
|
|
17825
17838
|
}
|
|
17826
17839
|
images(options = {}) {
|
|
17827
17840
|
return this.request("/images", void 0, options);
|
|
@@ -17848,8 +17861,8 @@ var MachineService = class {
|
|
|
17848
17861
|
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
17862
|
}
|
|
17850
17863
|
}
|
|
17851
|
-
get(vm, options = {}) {
|
|
17852
|
-
return this.request(this.path(vm), void 0, options);
|
|
17864
|
+
async get(vm, options = {}) {
|
|
17865
|
+
return named(await this.request(this.path(vm), void 0, options));
|
|
17853
17866
|
}
|
|
17854
17867
|
/**
|
|
17855
17868
|
* Cancellation before dispatch prevents allocation. Once dispatched we deliberately
|
|
@@ -17882,42 +17895,118 @@ var MachineService = class {
|
|
|
17882
17895
|
pull(vm, body, options = {}) {
|
|
17883
17896
|
return this.request(this.path(vm, "pull"), body, options);
|
|
17884
17897
|
}
|
|
17885
|
-
heartbeat(vm, body = {}, options = {}) {
|
|
17886
|
-
return this.request(this.path(vm, "heartbeat"), body, options);
|
|
17898
|
+
async heartbeat(vm, body = {}, options = {}) {
|
|
17899
|
+
return named(await this.request(this.path(vm, "heartbeat"), body, options));
|
|
17887
17900
|
}
|
|
17888
17901
|
release(vm, body = {}, options = {}) {
|
|
17889
17902
|
return this.request(this.path(vm, "release"), body, options);
|
|
17890
17903
|
}
|
|
17904
|
+
/**
|
|
17905
|
+
* Push one file as bytes, `PUT /machines/<name>/files` (FD-4): the instance
|
|
17906
|
+
* checks the digest before it writes, so a client on another Mac needs no
|
|
17907
|
+
* host path the instance could read (DC-31).
|
|
17908
|
+
*/
|
|
17909
|
+
async pushBytes(vm, body, options = {}) {
|
|
17910
|
+
const sha256 = createHash3("sha256").update(body.bytes).digest("hex");
|
|
17911
|
+
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.buffer, body.bytes.byteOffset, body.bytes.byteLength) }, options, this.maxResponseBytes);
|
|
17912
|
+
const answer = this.json(response.path, response.text);
|
|
17913
|
+
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`);
|
|
17914
|
+
return answer;
|
|
17915
|
+
}
|
|
17916
|
+
/**
|
|
17917
|
+
* Pull one file as bytes, `GET /machines/<name>/files`, into `to`, which
|
|
17918
|
+
* must not exist. The bytes stream to disk as they are hashed, so a file of
|
|
17919
|
+
* any size needs no memory of its size, and the pull is abandoned only when
|
|
17920
|
+
* no byte arrives for its timeout. The file is removed unless the bytes
|
|
17921
|
+
* match the digest the instance states (DC-31).
|
|
17922
|
+
*/
|
|
17923
|
+
async pullBytes(vm, body, options = {}) {
|
|
17924
|
+
const hash3 = createHash3("sha256"), file = await open2(body.to, "wx", 384);
|
|
17925
|
+
let bytes = 0;
|
|
17926
|
+
try {
|
|
17927
|
+
const response = await this.fetchBounded(this.filesPath(vm, body.remote_path, body.lease_id), { method: "GET" }, { ...options, timeoutMs: options.timeoutMs ?? PULL_IDLE_MS }, Number.MAX_SAFE_INTEGER, { idle: true, sink: async (chunk) => {
|
|
17928
|
+
hash3.update(chunk);
|
|
17929
|
+
bytes += chunk.byteLength;
|
|
17930
|
+
await file.write(chunk);
|
|
17931
|
+
} });
|
|
17932
|
+
if (response.contentType !== "application/octet-stream") throw new MachineServiceError(`machine-service ${response.path}: expected one file, got ${response.contentType ?? "no content type"}`);
|
|
17933
|
+
const digest = hash3.digest("hex");
|
|
17934
|
+
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"}`);
|
|
17935
|
+
await file.sync();
|
|
17936
|
+
await file.close();
|
|
17937
|
+
return { sha256: digest, bytes };
|
|
17938
|
+
} catch (error2) {
|
|
17939
|
+
await file.close().catch(() => {
|
|
17940
|
+
});
|
|
17941
|
+
await rm(body.to, { force: true });
|
|
17942
|
+
throw error2;
|
|
17943
|
+
}
|
|
17944
|
+
}
|
|
17945
|
+
filesPath(vm, remote, lease_id) {
|
|
17946
|
+
const query = new URLSearchParams({ ...lease_id ? { lease_id } : {}, path: remote });
|
|
17947
|
+
return `${this.path(vm, "files")}?${query}`;
|
|
17948
|
+
}
|
|
17891
17949
|
path(vm, action) {
|
|
17892
17950
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(vm)) throw new TypeError("Invalid VM name");
|
|
17893
17951
|
return `/machines/${encodeURIComponent(vm)}${action ? `/${action}` : ""}`;
|
|
17894
17952
|
}
|
|
17895
17953
|
async request(path, body, options) {
|
|
17954
|
+
const response = await this.fetchBounded(path, {
|
|
17955
|
+
method: body === void 0 ? "GET" : "POST",
|
|
17956
|
+
headers: body === void 0 ? {} : { "Content-Type": "application/json" },
|
|
17957
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
17958
|
+
}, options, this.maxResponseBytes);
|
|
17959
|
+
return this.json(path, response.text);
|
|
17960
|
+
}
|
|
17961
|
+
json(path, text5) {
|
|
17962
|
+
try {
|
|
17963
|
+
return JSON.parse(text5);
|
|
17964
|
+
} catch (cause) {
|
|
17965
|
+
throw new MachineServiceError(`machine-service ${path}: invalid JSON response`, void 0, void 0, { cause });
|
|
17966
|
+
}
|
|
17967
|
+
}
|
|
17968
|
+
/**
|
|
17969
|
+
* One request whose answer is read up to `maxBytes`; an error answer is read
|
|
17970
|
+
* up to 4 KiB and thrown with its status. With `sink`, a successful answer is
|
|
17971
|
+
* handed over chunk by chunk instead of kept; with `idle`, the timeout counts
|
|
17972
|
+
* from the last chunk rather than from the start.
|
|
17973
|
+
*/
|
|
17974
|
+
async fetchBounded(path, init, options, maxBytes, stream = {}) {
|
|
17896
17975
|
options.signal?.throwIfAborted();
|
|
17897
17976
|
const timeoutMs2 = positive(options.timeoutMs ?? this.timeoutMs, "timeoutMs");
|
|
17898
17977
|
const controller = new AbortController();
|
|
17899
17978
|
const abort = () => controller.abort(options.signal?.reason);
|
|
17900
17979
|
options.signal?.addEventListener("abort", abort, { once: true });
|
|
17901
|
-
const
|
|
17980
|
+
const expire = () => controller.abort(new MachineServiceError(`machine-service ${path} timed out after ${timeoutMs2}ms${stream.idle ? " without a byte" : ""}`));
|
|
17981
|
+
let timer = setTimeout(expire, timeoutMs2);
|
|
17902
17982
|
try {
|
|
17903
17983
|
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
17904
|
-
method:
|
|
17905
|
-
headers: { ...
|
|
17906
|
-
...body === void 0 ? {} : { body:
|
|
17984
|
+
method: init.method,
|
|
17985
|
+
headers: { ...init.headers, ...this.environment ? { "X-VM-Environment-Fingerprint": this.environment.identity.fingerprint } : {} },
|
|
17986
|
+
...init.body === void 0 ? {} : { body: init.body },
|
|
17907
17987
|
signal: controller.signal,
|
|
17908
17988
|
redirect: "error"
|
|
17909
|
-
// Do not let a
|
|
17989
|
+
// Do not let a service redirect to another host.
|
|
17910
17990
|
});
|
|
17911
17991
|
const reader = response.body?.getReader();
|
|
17912
17992
|
const chunks = [];
|
|
17913
17993
|
let size = 0;
|
|
17914
|
-
const bound = response.ok ?
|
|
17994
|
+
const bound = response.ok ? maxBytes : Math.min(4096, maxBytes);
|
|
17915
17995
|
let truncated = false;
|
|
17916
17996
|
if (reader) {
|
|
17917
17997
|
try {
|
|
17918
17998
|
for (; ; ) {
|
|
17919
17999
|
const { value, done } = await reader.read();
|
|
17920
18000
|
if (done) break;
|
|
18001
|
+
if (stream.idle) {
|
|
18002
|
+
clearTimeout(timer);
|
|
18003
|
+
timer = setTimeout(expire, timeoutMs2);
|
|
18004
|
+
}
|
|
18005
|
+
if (response.ok && stream.sink) {
|
|
18006
|
+
size += value.byteLength;
|
|
18007
|
+
await stream.sink(value);
|
|
18008
|
+
continue;
|
|
18009
|
+
}
|
|
17921
18010
|
const remaining = bound - size;
|
|
17922
18011
|
chunks.push(value.subarray(0, remaining));
|
|
17923
18012
|
size += Math.min(value.byteLength, remaining);
|
|
@@ -17931,18 +18020,14 @@ var MachineService = class {
|
|
|
17931
18020
|
reader.releaseLock();
|
|
17932
18021
|
}
|
|
17933
18022
|
}
|
|
17934
|
-
const
|
|
17935
|
-
if (!response.ok) throw new MachineServiceError(`machine-service ${path}: HTTP ${response.status}: ${
|
|
18023
|
+
const bytes = Buffer.concat(chunks), text5 = bytes.toString("utf8");
|
|
18024
|
+
if (!response.ok) throw new MachineServiceError(`machine-service ${path}: HTTP ${response.status}: ${text5}${truncated ? " [truncated]" : ""}`, response.status, text5);
|
|
17936
18025
|
if (truncated) throw new MachineServiceError(`machine-service ${path}: response exceeds ${bound} bytes`);
|
|
17937
|
-
|
|
17938
|
-
return JSON.parse(text4);
|
|
17939
|
-
} catch (cause) {
|
|
17940
|
-
throw new MachineServiceError(`machine-service ${path}: invalid JSON response`, void 0, void 0, { cause });
|
|
17941
|
-
}
|
|
18026
|
+
return { path, bytes, text: text5, contentType: response.headers.get("content-type") ?? void 0, sha256: response.headers.get("x-content-sha256") ?? void 0 };
|
|
17942
18027
|
} catch (cause) {
|
|
17943
18028
|
if (controller.signal.aborted) throw controller.signal.reason;
|
|
17944
18029
|
if (cause instanceof MachineServiceError) throw cause;
|
|
17945
|
-
throw new MachineServiceError(`machine-service ${path}: request failed`, void 0, void 0, { cause });
|
|
18030
|
+
throw new MachineServiceError(`machine-service ${path}: request failed${cause instanceof Error ? `: ${cause.message}` : ""}`, void 0, void 0, { cause });
|
|
17946
18031
|
} finally {
|
|
17947
18032
|
clearTimeout(timer);
|
|
17948
18033
|
options.signal?.removeEventListener("abort", abort);
|
|
@@ -17955,7 +18040,7 @@ import { homedir as homedir4 } from "node:os";
|
|
|
17955
18040
|
|
|
17956
18041
|
// src/registry.ts
|
|
17957
18042
|
import { randomUUID } from "node:crypto";
|
|
17958
|
-
import { link, lstat, mkdir as mkdir2, open as
|
|
18043
|
+
import { link, lstat, mkdir as mkdir2, open as open3, readFile as readFile3, realpath, rename as rename2, unlink } from "node:fs/promises";
|
|
17959
18044
|
import { readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
|
|
17960
18045
|
import { homedir as homedir3 } from "node:os";
|
|
17961
18046
|
import { spawn as spawn2 } from "node:child_process";
|
|
@@ -17977,21 +18062,21 @@ function cells(row) {
|
|
|
17977
18062
|
});
|
|
17978
18063
|
}
|
|
17979
18064
|
function parse3(line) {
|
|
17980
|
-
const
|
|
17981
|
-
if (!
|
|
17982
|
-
return
|
|
18065
|
+
const text5 = line.trim();
|
|
18066
|
+
if (!text5.startsWith("|") || !text5.endsWith("|")) return void 0;
|
|
18067
|
+
return text5.slice(1, -1).split("|").map((cell) => cell.trim());
|
|
17983
18068
|
}
|
|
17984
|
-
function linesOf(
|
|
18069
|
+
function linesOf(text5) {
|
|
17985
18070
|
const lines = [];
|
|
17986
18071
|
const pattern = /[^\r\n]*(?:\r\n|\n|\r|$)/g;
|
|
17987
|
-
for (const match of
|
|
18072
|
+
for (const match of text5.matchAll(pattern)) {
|
|
17988
18073
|
if (!match[0]) continue;
|
|
17989
18074
|
lines.push({ text: match[0].replace(/[\r\n]+$/, ""), start: match.index, end: match.index + match[0].length });
|
|
17990
18075
|
}
|
|
17991
18076
|
return lines;
|
|
17992
18077
|
}
|
|
17993
|
-
function table(
|
|
17994
|
-
const lines = linesOf(
|
|
18078
|
+
function table(text5) {
|
|
18079
|
+
const lines = linesOf(text5);
|
|
17995
18080
|
const sections = lines.map((line, index) => /^## Using VMs\s*$/.test(line.text) ? index : -1).filter((index) => index >= 0);
|
|
17996
18081
|
if (sections.length !== 1) throw new RegistryError("Expected exactly one '## Using VMs' section");
|
|
17997
18082
|
const begin = sections[0];
|
|
@@ -18012,7 +18097,7 @@ function table(text4) {
|
|
|
18012
18097
|
rows.push(line);
|
|
18013
18098
|
}
|
|
18014
18099
|
const last = rows.at(-1) ?? separator;
|
|
18015
|
-
return { rows, insertion: last.end, newline:
|
|
18100
|
+
return { rows, insertion: last.end, newline: text5.includes("\r\n") ? "\r\n" : "\n" };
|
|
18016
18101
|
}
|
|
18017
18102
|
function resolveRegistry(options = {}) {
|
|
18018
18103
|
const env = options.env ?? process.env;
|
|
@@ -18090,30 +18175,30 @@ var Registry = class {
|
|
|
18090
18175
|
/** Returns false when this exact row is already registered (idempotent). */
|
|
18091
18176
|
async add(row, options = {}) {
|
|
18092
18177
|
const desired = cells(row);
|
|
18093
|
-
return this.update((
|
|
18094
|
-
const registry2 = table(
|
|
18178
|
+
return this.update((text5) => {
|
|
18179
|
+
const registry2 = table(text5);
|
|
18095
18180
|
const matching = registry2.rows.filter((line) => parse3(line.text)[2] === row.taskName);
|
|
18096
18181
|
if (matching.length > 0) {
|
|
18097
|
-
if (matching.length === 1 && JSON.stringify(parse3(matching[0].text)) === JSON.stringify(desired)) return
|
|
18182
|
+
if (matching.length === 1 && JSON.stringify(parse3(matching[0].text)) === JSON.stringify(desired)) return text5;
|
|
18098
18183
|
throw new RegistryError(`Task '${row.taskName}' is already registered by a different owner or duplicated`);
|
|
18099
18184
|
}
|
|
18100
|
-
const prefix = registry2.insertion > 0 && !/[\r\n]/.test(
|
|
18185
|
+
const prefix = registry2.insertion > 0 && !/[\r\n]/.test(text5[registry2.insertion - 1]) ? registry2.newline : "";
|
|
18101
18186
|
const added = `${prefix}| ${desired.join(" | ")} |${registry2.newline}`;
|
|
18102
|
-
return
|
|
18187
|
+
return text5.slice(0, registry2.insertion) + added + text5.slice(registry2.insertion);
|
|
18103
18188
|
}, options.signal);
|
|
18104
18189
|
}
|
|
18105
18190
|
/** Returns false when absent. Never removes a row whose ownership differs. */
|
|
18106
18191
|
async remove(row, options = {}) {
|
|
18107
18192
|
const desired = cells(row);
|
|
18108
|
-
return this.update((
|
|
18109
|
-
const registry2 = table(
|
|
18193
|
+
return this.update((text5) => {
|
|
18194
|
+
const registry2 = table(text5);
|
|
18110
18195
|
const matching = registry2.rows.filter((line2) => parse3(line2.text)[2] === row.taskName);
|
|
18111
|
-
if (matching.length === 0) return
|
|
18196
|
+
if (matching.length === 0) return text5;
|
|
18112
18197
|
if (matching.length !== 1 || JSON.stringify(parse3(matching[0].text)) !== JSON.stringify(desired)) {
|
|
18113
18198
|
throw new RegistryError(`Refusing to remove task '${row.taskName}': ownership does not match`);
|
|
18114
18199
|
}
|
|
18115
18200
|
const line = matching[0];
|
|
18116
|
-
return
|
|
18201
|
+
return text5.slice(0, line.start) + text5.slice(line.end);
|
|
18117
18202
|
}, options.signal);
|
|
18118
18203
|
}
|
|
18119
18204
|
async update(transform2, signal) {
|
|
@@ -18137,7 +18222,7 @@ var Registry = class {
|
|
|
18137
18222
|
const updated = transform2(original);
|
|
18138
18223
|
if (original === updated) return false;
|
|
18139
18224
|
temporary = join5(dirname3(target), `.${target.split("/").at(-1)}.${token2}.tmp`);
|
|
18140
|
-
const handle = await
|
|
18225
|
+
const handle = await open3(temporary, "wx", before.mode & 511);
|
|
18141
18226
|
try {
|
|
18142
18227
|
await handle.chmod(before.mode & 511);
|
|
18143
18228
|
await handle.writeFile(updated, "utf8");
|
|
@@ -18153,7 +18238,7 @@ var Registry = class {
|
|
|
18153
18238
|
lock.check();
|
|
18154
18239
|
await rename2(temporary, target);
|
|
18155
18240
|
temporary = void 0;
|
|
18156
|
-
const dir = await
|
|
18241
|
+
const dir = await open3(dirname3(target), "r");
|
|
18157
18242
|
try {
|
|
18158
18243
|
await dir.sync();
|
|
18159
18244
|
} finally {
|
|
@@ -18180,7 +18265,7 @@ var Registry = class {
|
|
|
18180
18265
|
if (!errno(error2, "ENOENT")) throw error2;
|
|
18181
18266
|
}
|
|
18182
18267
|
const temporary = join5(dirname3(target), `.registry.${randomUUID()}.tmp`);
|
|
18183
|
-
const handle = await
|
|
18268
|
+
const handle = await open3(temporary, "wx", 384);
|
|
18184
18269
|
try {
|
|
18185
18270
|
try {
|
|
18186
18271
|
await handle.chmod(384);
|
|
@@ -18195,7 +18280,7 @@ var Registry = class {
|
|
|
18195
18280
|
} catch (error2) {
|
|
18196
18281
|
if (!errno(error2, "EEXIST")) throw error2;
|
|
18197
18282
|
}
|
|
18198
|
-
const dir = await
|
|
18283
|
+
const dir = await open3(dirname3(target), "r");
|
|
18199
18284
|
try {
|
|
18200
18285
|
await dir.sync();
|
|
18201
18286
|
} finally {
|
|
@@ -18270,7 +18355,7 @@ var Registry = class {
|
|
|
18270
18355
|
};
|
|
18271
18356
|
|
|
18272
18357
|
// src/transfer.ts
|
|
18273
|
-
import { copyFile, mkdir as mkdir5, readFile as readFile5, lstat as lstat3, mkdtemp, rm, open as
|
|
18358
|
+
import { copyFile, mkdir as mkdir5, readFile as readFile5, lstat as lstat3, mkdtemp, rm as rm2, open as open6, link as link2 } from "node:fs/promises";
|
|
18274
18359
|
import { constants as constants3, linkSync } from "node:fs";
|
|
18275
18360
|
import { dirname as dirname6, join as join7, resolve as resolve5, relative as relative4, isAbsolute as isAbsolute4 } from "node:path";
|
|
18276
18361
|
import { tmpdir } from "node:os";
|
|
@@ -18278,14 +18363,14 @@ import { randomUUID as randomUUID3 } from "node:crypto";
|
|
|
18278
18363
|
|
|
18279
18364
|
// src/util.ts
|
|
18280
18365
|
import { spawn as spawn3 } from "node:child_process";
|
|
18281
|
-
import { createHash as
|
|
18282
|
-
import { mkdir as mkdir3, rename as rename3, lstat as lstat2, readdir as readdir2, open as
|
|
18366
|
+
import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
|
|
18367
|
+
import { mkdir as mkdir3, rename as rename3, lstat as lstat2, readdir as readdir2, open as open4 } from "node:fs/promises";
|
|
18283
18368
|
import { dirname as dirname4, join as join6, resolve as resolve4, relative as relative3, isAbsolute as isAbsolute3 } from "node:path";
|
|
18284
|
-
var hash = (bytes) =>
|
|
18369
|
+
var hash = (bytes) => createHash4("sha256").update(bytes).digest("hex");
|
|
18285
18370
|
async function hashFile(path) {
|
|
18286
|
-
const file = await
|
|
18371
|
+
const file = await open4(path, "r");
|
|
18287
18372
|
try {
|
|
18288
|
-
const digest =
|
|
18373
|
+
const digest = createHash4("sha256"), chunk = Buffer.alloc(8 * 1024 * 1024);
|
|
18289
18374
|
let bytes = 0;
|
|
18290
18375
|
for (; ; ) {
|
|
18291
18376
|
const { bytesRead } = await file.read(chunk, 0, chunk.length, null);
|
|
@@ -18301,7 +18386,7 @@ async function hashFile(path) {
|
|
|
18301
18386
|
async function jsonFile(path, value) {
|
|
18302
18387
|
await mkdir3(dirname4(path), { recursive: true, mode: 448 });
|
|
18303
18388
|
const tmp = `${path}.${randomUUID2()}.tmp`;
|
|
18304
|
-
const file = await
|
|
18389
|
+
const file = await open4(tmp, "wx", 384);
|
|
18305
18390
|
try {
|
|
18306
18391
|
await file.writeFile(JSON.stringify(value, null, 2) + "\n");
|
|
18307
18392
|
await file.sync();
|
|
@@ -18309,7 +18394,7 @@ async function jsonFile(path, value) {
|
|
|
18309
18394
|
await file.close();
|
|
18310
18395
|
}
|
|
18311
18396
|
await rename3(tmp, path);
|
|
18312
|
-
const directory2 = await
|
|
18397
|
+
const directory2 = await open4(dirname4(path), "r");
|
|
18313
18398
|
try {
|
|
18314
18399
|
await directory2.sync();
|
|
18315
18400
|
} finally {
|
|
@@ -18373,9 +18458,9 @@ async function command(argv, options = {}) {
|
|
|
18373
18458
|
}
|
|
18374
18459
|
|
|
18375
18460
|
// src/archive.ts
|
|
18376
|
-
import { open as
|
|
18461
|
+
import { open as open5, mkdir as mkdir4 } from "node:fs/promises";
|
|
18377
18462
|
import { constants as constants2 } from "node:fs";
|
|
18378
|
-
import { createHash as
|
|
18463
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
18379
18464
|
import { dirname as dirname5 } from "node:path";
|
|
18380
18465
|
var MAX_LINE_BYTES = 64 * 1024;
|
|
18381
18466
|
var header = (path, bytes) => `${JSON.stringify({ path, bytes })}
|
|
@@ -18402,7 +18487,7 @@ function archiveChunks(files, maxArgvBytes = 64 * 1024) {
|
|
|
18402
18487
|
return chunks;
|
|
18403
18488
|
}
|
|
18404
18489
|
async function unpackArchive(archive, directory2, requested, options = {}) {
|
|
18405
|
-
const input = await
|
|
18490
|
+
const input = await open5(archive, constants2.O_RDONLY | constants2.O_NOFOLLOW);
|
|
18406
18491
|
const unpacked = [];
|
|
18407
18492
|
try {
|
|
18408
18493
|
const buffer = Buffer.alloc(8 * 1024 * 1024);
|
|
@@ -18425,9 +18510,9 @@ async function unpackArchive(archive, directory2, requested, options = {}) {
|
|
|
18425
18510
|
for (; ; ) {
|
|
18426
18511
|
const at = buffer.indexOf(10, start);
|
|
18427
18512
|
if (at >= 0 && at < end) {
|
|
18428
|
-
const
|
|
18513
|
+
const text5 = buffer.toString("utf8", start, at);
|
|
18429
18514
|
start = at + 1;
|
|
18430
|
-
const value = JSON.parse(
|
|
18515
|
+
const value = JSON.parse(text5);
|
|
18431
18516
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid archive line");
|
|
18432
18517
|
return value;
|
|
18433
18518
|
}
|
|
@@ -18448,8 +18533,8 @@ async function unpackArchive(archive, directory2, requested, options = {}) {
|
|
|
18448
18533
|
const bytes = head.bytes;
|
|
18449
18534
|
const target = within(directory2, fact.path);
|
|
18450
18535
|
await mkdir4(dirname5(target), { recursive: true, mode: 448 });
|
|
18451
|
-
const output = await
|
|
18452
|
-
const digest =
|
|
18536
|
+
const output = await open5(target, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | constants2.O_NOFOLLOW, 384);
|
|
18537
|
+
const digest = createHash5("sha256");
|
|
18453
18538
|
try {
|
|
18454
18539
|
for (let left = bytes; left > 0; ) {
|
|
18455
18540
|
if (start === end) {
|
|
@@ -18770,7 +18855,7 @@ var Transfer = class {
|
|
|
18770
18855
|
const info = await lstat3(path);
|
|
18771
18856
|
if (!info.isFile()) throw new ImageTransferError("unsafe-path", "Expected a regular local image");
|
|
18772
18857
|
if (info.size !== identity.bytes) throw new ImageTransferError("integrity-failed", "Local image size conflicts with original");
|
|
18773
|
-
const fd = await
|
|
18858
|
+
const fd = await open6(path, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
|
|
18774
18859
|
try {
|
|
18775
18860
|
const same = (s) => s.isFile() && s.dev === info.dev && s.ino === info.ino && s.size === info.size && s.mtimeMs === info.mtimeMs && s.ctimeMs === info.ctimeMs;
|
|
18776
18861
|
if (!same(await fd.stat())) throw new ImageTransferError("integrity-failed", "Local image changed before verification");
|
|
@@ -18788,10 +18873,10 @@ var Transfer = class {
|
|
|
18788
18873
|
if (!imageFormat(result2)) throw new ImageTransferError("unsafe-path", "Unsupported image format");
|
|
18789
18874
|
} else {
|
|
18790
18875
|
try {
|
|
18791
|
-
const
|
|
18876
|
+
const text5 = new TextDecoder("utf-8", { fatal: true }).decode(result2);
|
|
18792
18877
|
if (options.metadataFormat === "jsonl") {
|
|
18793
|
-
for (const line of
|
|
18794
|
-
} else JSON.parse(
|
|
18878
|
+
for (const line of text5.split("\n")) if (line.trim()) JSON.parse(line);
|
|
18879
|
+
} else JSON.parse(text5);
|
|
18795
18880
|
} catch (cause) {
|
|
18796
18881
|
throw new ImageTransferError("integrity-failed", "Invalid image metadata JSON", { cause });
|
|
18797
18882
|
}
|
|
@@ -18850,7 +18935,7 @@ var Transfer = class {
|
|
|
18850
18935
|
const clean = async () => {
|
|
18851
18936
|
try {
|
|
18852
18937
|
await assertHostPath(approvedLocalRoot, staging);
|
|
18853
|
-
await
|
|
18938
|
+
await rm2(staging, { recursive: true, force: true });
|
|
18854
18939
|
} catch {
|
|
18855
18940
|
}
|
|
18856
18941
|
};
|
|
@@ -18948,7 +19033,7 @@ var Transfer = class {
|
|
|
18948
19033
|
await this.checked([this.node, "-e", REMOVE_FRAME, guestRoot, frame]);
|
|
18949
19034
|
} finally {
|
|
18950
19035
|
await assertHostPath(tempRoot, hostDirectory);
|
|
18951
|
-
await
|
|
19036
|
+
await rm2(hostDirectory, { recursive: true, force: true });
|
|
18952
19037
|
}
|
|
18953
19038
|
}
|
|
18954
19039
|
}
|
|
@@ -18973,7 +19058,7 @@ var Transfer = class {
|
|
|
18973
19058
|
}
|
|
18974
19059
|
if (written) {
|
|
18975
19060
|
await assertHostPath(localRoot, path);
|
|
18976
|
-
await
|
|
19061
|
+
await rm2(path, { force: true });
|
|
18977
19062
|
}
|
|
18978
19063
|
}
|
|
18979
19064
|
return false;
|
|
@@ -19029,7 +19114,7 @@ var Transfer = class {
|
|
|
19029
19114
|
await this.checked([this.node, "-e", REMOVE_FRAME, guestRoot, archive]);
|
|
19030
19115
|
} finally {
|
|
19031
19116
|
await assertHostPath(localRoot, staging);
|
|
19032
|
-
await
|
|
19117
|
+
await rm2(staging, { recursive: true, force: true });
|
|
19033
19118
|
}
|
|
19034
19119
|
}
|
|
19035
19120
|
}
|
|
@@ -19181,11 +19266,11 @@ var VmTransport = class {
|
|
|
19181
19266
|
};
|
|
19182
19267
|
|
|
19183
19268
|
// src/package.ts
|
|
19184
|
-
import { createHash as
|
|
19185
|
-
import { lstat as lstat4, readFile as readFile6, readdir as readdir3, mkdir as mkdir6, writeFile as writeFile3, rm as
|
|
19269
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
19270
|
+
import { lstat as lstat4, readFile as readFile6, readdir as readdir3, mkdir as mkdir6, writeFile as writeFile3, rm as rm3 } from "node:fs/promises";
|
|
19186
19271
|
import { dirname as dirname7, join as join9, resolve as resolve6, parse as parse4 } from "node:path";
|
|
19187
19272
|
var generated = ["OPENING.txt", "manifest.json"];
|
|
19188
|
-
var hash2 = (bytes) =>
|
|
19273
|
+
var hash2 = (bytes) => createHash6("sha256").update(bytes).digest("hex");
|
|
19189
19274
|
var json = (value) => JSON.stringify(value, null, 2) + "\n";
|
|
19190
19275
|
function object3(value, label) {
|
|
19191
19276
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`invalid ${label}`);
|
|
@@ -19577,7 +19662,7 @@ async function deliverPackage(rootDir, options) {
|
|
|
19577
19662
|
})));
|
|
19578
19663
|
return await verifyDeliveredPackage(root);
|
|
19579
19664
|
} catch (error2) {
|
|
19580
|
-
for (const path of created.reverse()) await
|
|
19665
|
+
for (const path of created.reverse()) await rm3(join9(root, path), { force: true });
|
|
19581
19666
|
throw error2;
|
|
19582
19667
|
}
|
|
19583
19668
|
}
|
|
@@ -19628,16 +19713,16 @@ async function probeLocal(run = command, platform = process.platform) {
|
|
|
19628
19713
|
}
|
|
19629
19714
|
const permissions = await observe(["cua-driver", "permissions", "status", "--json"], JSON.parse);
|
|
19630
19715
|
const recorder = await observe(["cua-driver", "call", "get_recording_state", "--json", "{}"], JSON.parse);
|
|
19631
|
-
const foreground = await observe(["cua-driver", "call", "list_apps", "--json", "{}"], (
|
|
19632
|
-
const data = JSON.parse(
|
|
19716
|
+
const foreground = await observe(["cua-driver", "call", "list_apps", "--json", "{}"], (text5) => {
|
|
19717
|
+
const data = JSON.parse(text5);
|
|
19633
19718
|
return data.apps?.filter((app) => app.active).map((app) => ({ name: app.name, bundleId: app.bundle_id, pid: app.pid })) ?? null;
|
|
19634
19719
|
});
|
|
19635
|
-
const session = platform === "darwin" ? await observe(["/usr/bin/stat", "-f", "%Su", "/dev/console"], (
|
|
19636
|
-
const idle = platform === "darwin" ? await observe(["/usr/sbin/ioreg", "-r", "-c", "IOHIDSystem"], (
|
|
19637
|
-
const m =
|
|
19720
|
+
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");
|
|
19721
|
+
const idle = platform === "darwin" ? await observe(["/usr/sbin/ioreg", "-r", "-c", "IOHIDSystem"], (text5) => {
|
|
19722
|
+
const m = text5.match(/"HIDIdleTime"\s*=\s*(\d+)/);
|
|
19638
19723
|
return m ? Number(m[1]) / 1e9 : null;
|
|
19639
|
-
}) : await observe(["xprintidle"], (
|
|
19640
|
-
const n = Number(
|
|
19724
|
+
}) : await observe(["xprintidle"], (text5) => {
|
|
19725
|
+
const n = Number(text5.trim());
|
|
19641
19726
|
return Number.isFinite(n) ? n / 1e3 : null;
|
|
19642
19727
|
});
|
|
19643
19728
|
return {
|
|
@@ -19654,7 +19739,7 @@ async function probeLocal(run = command, platform = process.platform) {
|
|
|
19654
19739
|
// src/owner-lock.ts
|
|
19655
19740
|
import { spawn as spawn4 } from "node:child_process";
|
|
19656
19741
|
import { constants as constants4 } from "node:fs";
|
|
19657
|
-
import { open as
|
|
19742
|
+
import { open as open7 } from "node:fs/promises";
|
|
19658
19743
|
var OwnerLockError = class extends Error {
|
|
19659
19744
|
constructor(message3, options) {
|
|
19660
19745
|
super(message3, options);
|
|
@@ -19679,7 +19764,7 @@ async function acquireOwnerLock(path, options = {}) {
|
|
|
19679
19764
|
const executable = options.pythonExecutable === void 0 ? pythonExecutable() : nonblank(options.pythonExecutable, "pythonExecutable");
|
|
19680
19765
|
const signal = options.signal;
|
|
19681
19766
|
signal?.throwIfAborted();
|
|
19682
|
-
const file = await
|
|
19767
|
+
const file = await open7(path, constants4.O_RDWR | constants4.O_CREAT | constants4.O_NOFOLLOW, 384);
|
|
19683
19768
|
try {
|
|
19684
19769
|
if (!(await file.stat()).isFile()) throw new OwnerLockError("Owner lock must be a regular file");
|
|
19685
19770
|
signal?.throwIfAborted();
|
|
@@ -23341,8 +23426,8 @@ function FromObject4(properties) {
|
|
|
23341
23426
|
|
|
23342
23427
|
// node_modules/typebox/build/type/engine/object/from_tuple.mjs
|
|
23343
23428
|
function FromTuple(types) {
|
|
23344
|
-
const
|
|
23345
|
-
const result2 = FromType8(
|
|
23429
|
+
const object6 = TupleToObject(Tuple(types));
|
|
23430
|
+
const result2 = FromType8(object6);
|
|
23346
23431
|
return result2;
|
|
23347
23432
|
}
|
|
23348
23433
|
|
|
@@ -27367,8 +27452,8 @@ var normalizeSearchName = (name) => name.trim().toLowerCase();
|
|
|
27367
27452
|
var serializeSearchResult = (result2) => JSON.stringify(result2, null, 2);
|
|
27368
27453
|
function validateCatalog(value) {
|
|
27369
27454
|
if (!Check2(catalogSchema, value)) throw new Error("Invalid application catalog schema");
|
|
27370
|
-
const bounded3 = (
|
|
27371
|
-
if (Array.from(
|
|
27455
|
+
const bounded3 = (text5, limit) => {
|
|
27456
|
+
if (Array.from(text5).length > limit) throw new Error("Application catalog exceeds text limit");
|
|
27372
27457
|
};
|
|
27373
27458
|
for (const image of value.images) for (const app of image.applications) {
|
|
27374
27459
|
bounded3(app.id, 128);
|
|
@@ -27581,13 +27666,13 @@ function acquisitionCapabilities(value) {
|
|
|
27581
27666
|
}
|
|
27582
27667
|
|
|
27583
27668
|
// src/images.ts
|
|
27584
|
-
import { mkdir as mkdir8, lstat as lstat6, open as
|
|
27669
|
+
import { mkdir as mkdir8, lstat as lstat6, open as open8, readdir as readdir5, rm as rm4 } from "node:fs/promises";
|
|
27585
27670
|
import { constants as constants5, linkSync as linkSync2 } from "node:fs";
|
|
27586
27671
|
import { join as join11, dirname as dirname8, extname } from "node:path";
|
|
27587
27672
|
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
27588
27673
|
|
|
27589
27674
|
// src/image-presentation.ts
|
|
27590
|
-
import { createHash as
|
|
27675
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
27591
27676
|
import { deflateSync, inflateSync } from "node:zlib";
|
|
27592
27677
|
var IMAGE_PRESENTATION_POLICY = Object.freeze({
|
|
27593
27678
|
version: 1,
|
|
@@ -27993,7 +28078,7 @@ async function prepareImage(bytes, mimeType) {
|
|
|
27993
28078
|
width: size.width,
|
|
27994
28079
|
height: size.height,
|
|
27995
28080
|
mimeType: presentedType,
|
|
27996
|
-
sha256:
|
|
28081
|
+
sha256: createHash7("sha256").update(presented).digest("hex"),
|
|
27997
28082
|
bytes: presented.length,
|
|
27998
28083
|
transformed: presentedType !== mimeType || !original.equals(presented),
|
|
27999
28084
|
policy
|
|
@@ -28092,7 +28177,7 @@ async function readBounded(root, path, limit, signal) {
|
|
|
28092
28177
|
const before = await lstat6(path);
|
|
28093
28178
|
if (!before.isFile()) fail("unsafe-path", "Image evidence must be a regular file.");
|
|
28094
28179
|
if (before.size < 1 || before.size > limit) fail("integrity-failed", "Image evidence exceeds its size bound.");
|
|
28095
|
-
const fd = await
|
|
28180
|
+
const fd = await open8(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
28096
28181
|
try {
|
|
28097
28182
|
const same = (s) => s.isFile() && s.dev === before.dev && s.ino === before.ino && s.size === before.size && s.mtimeMs === before.mtimeMs && s.ctimeMs === before.ctimeMs;
|
|
28098
28183
|
if (!same(await fd.stat())) fail("integrity-failed", "Image evidence changed before reading.");
|
|
@@ -28138,7 +28223,7 @@ async function publish(root, path, bytes, signal) {
|
|
|
28138
28223
|
await hostPath(root, path, true);
|
|
28139
28224
|
guard(signal);
|
|
28140
28225
|
const temporary = join11(dirname8(path), `.image-${randomUUID5()}.tmp`);
|
|
28141
|
-
const fd = await
|
|
28226
|
+
const fd = await open8(temporary, "wx", 384);
|
|
28142
28227
|
try {
|
|
28143
28228
|
try {
|
|
28144
28229
|
await fd.writeFile(bytes);
|
|
@@ -28157,9 +28242,9 @@ async function publish(root, path, bytes, signal) {
|
|
|
28157
28242
|
}
|
|
28158
28243
|
} finally {
|
|
28159
28244
|
await hostPath(root, temporary, true);
|
|
28160
|
-
await
|
|
28245
|
+
await rm4(temporary, { force: true });
|
|
28161
28246
|
}
|
|
28162
|
-
const directory2 = await
|
|
28247
|
+
const directory2 = await open8(dirname8(path), "r");
|
|
28163
28248
|
try {
|
|
28164
28249
|
await directory2.sync();
|
|
28165
28250
|
} finally {
|
|
@@ -28312,7 +28397,7 @@ var ImageStore = class {
|
|
|
28312
28397
|
const request = await optional2(() => readMetadata(recording.path, join11(recording.path, "host", "requests", `${target.executionId}.json`), options.signal));
|
|
28313
28398
|
if (!request) fail("unauthorized-reference", "Execution does not belong to this enclosure.");
|
|
28314
28399
|
if (request.sessionId !== target.sessionId || request.executionId !== target.executionId) fail("integrity-failed", "Execution identity does not match its recording.");
|
|
28315
|
-
if (request.capture === false) return { status: "not-requested", diagnostic: "
|
|
28400
|
+
if (request.capture === false) return { status: "not-requested", diagnostic: "This lease's runs take no snapshots: its image lists no capture software (cua-driver), or its durable machine's cua-driver daemon cannot record the screen, as relay_stage's `snapshots.reason` says; so this run took none." };
|
|
28316
28401
|
const group = request.snapshots?.group;
|
|
28317
28402
|
const requested = !request.diagnostic && (target.phase === "before" ? !group || group.phase === "first" : !group || group.phase === "last");
|
|
28318
28403
|
if (!requested) return { status: "not-requested", diagnostic: "The declared snapshot plan does not capture this phase." };
|
|
@@ -28743,12 +28828,84 @@ async function refreshEvidenceState(incoming, destination, archiveRoot, options
|
|
|
28743
28828
|
if (archived) await copy(archived, retained);
|
|
28744
28829
|
}
|
|
28745
28830
|
|
|
28831
|
+
// src/discovery.ts
|
|
28832
|
+
var TIMEOUT_MS = 5e3;
|
|
28833
|
+
function consulAddress(value = process.env.CONSUL_HTTP_ADDR) {
|
|
28834
|
+
const address = value?.trim() || "http://127.0.0.1:8500";
|
|
28835
|
+
return new URL(/^[a-z]+:\/\//i.test(address) ? address : `http://${address}`).origin;
|
|
28836
|
+
}
|
|
28837
|
+
async function fetchJson(url) {
|
|
28838
|
+
const response = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
28839
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
28840
|
+
return response.json();
|
|
28841
|
+
}
|
|
28842
|
+
var text3 = (value) => typeof value === "string" ? value : "";
|
|
28843
|
+
function parseRegistrations(answer) {
|
|
28844
|
+
if (!Array.isArray(answer)) throw new Error("Consul answered with no list of registrations");
|
|
28845
|
+
return answer.flatMap((entry) => {
|
|
28846
|
+
const node2 = entry?.Node, service = entry?.Service, port = service?.Port;
|
|
28847
|
+
const host = text3(service?.Address) || text3(node2?.Address);
|
|
28848
|
+
if (!host || !Number.isSafeInteger(port)) return [];
|
|
28849
|
+
const meta2 = service?.Meta ?? {};
|
|
28850
|
+
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" }];
|
|
28851
|
+
});
|
|
28852
|
+
}
|
|
28853
|
+
async function findDurableOwner(machine, options) {
|
|
28854
|
+
const consul = options.consul ?? consulAddress();
|
|
28855
|
+
const make = options.backend ?? ((origin) => new MachineService({ baseUrl: origin, listed: true }));
|
|
28856
|
+
const candidates = [{ origin: new URL(options.local.baseUrl).origin, backend: options.local }];
|
|
28857
|
+
let consulError;
|
|
28858
|
+
try {
|
|
28859
|
+
for (const registration of parseRegistrations(await (options.fetchJson ?? fetchJson)(`${consul}/v1/health/service/machine-service`))) {
|
|
28860
|
+
if (registration.loopbackOnly || candidates.some((candidate) => candidate.origin === registration.origin)) continue;
|
|
28861
|
+
candidates.push({ origin: registration.origin, backend: make(registration.origin) });
|
|
28862
|
+
}
|
|
28863
|
+
} catch (error2) {
|
|
28864
|
+
consulError = `the Consul agent at ${consul} did not answer (${error2 instanceof Error ? error2.message : String(error2)})`;
|
|
28865
|
+
}
|
|
28866
|
+
const owners = [];
|
|
28867
|
+
await Promise.all(candidates.map(async ({ origin, backend }) => {
|
|
28868
|
+
try {
|
|
28869
|
+
const list = await backend.list({ timeoutMs: TIMEOUT_MS });
|
|
28870
|
+
const record3 = list.machines[machine];
|
|
28871
|
+
if (record3?.kind === "durable") owners.push({ backend, origin, instance: record3.instance ?? machine });
|
|
28872
|
+
} catch {
|
|
28873
|
+
}
|
|
28874
|
+
}));
|
|
28875
|
+
if (owners.length === 1) return owners[0];
|
|
28876
|
+
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`);
|
|
28877
|
+
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.`);
|
|
28878
|
+
}
|
|
28879
|
+
|
|
28880
|
+
// src/capture-gate.ts
|
|
28881
|
+
var object5 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
28882
|
+
function durableCapture(machine, software, answer) {
|
|
28883
|
+
const version2 = object5(software)?.cua_driver;
|
|
28884
|
+
if (typeof version2 !== "string" || !version2) return { capture: false, state: "absent", reason: `${machine} lists no cua-driver in its capabilities, so runs take no snapshots.` };
|
|
28885
|
+
if (!answer) return { capture: false, state: "unknown", reason: `cua-driver's permission status on ${machine} was not read, so runs take no snapshots.` };
|
|
28886
|
+
if ("error" in answer || answer.code !== 0) {
|
|
28887
|
+
const why = "error" in answer ? answer.error : `exit ${answer.code}: ${(answer.stderr || answer.stdout).trim().slice(0, 300)}`;
|
|
28888
|
+
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.` };
|
|
28889
|
+
}
|
|
28890
|
+
let status;
|
|
28891
|
+
try {
|
|
28892
|
+
status = object5(JSON.parse(answer.stdout));
|
|
28893
|
+
} catch {
|
|
28894
|
+
}
|
|
28895
|
+
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.` };
|
|
28896
|
+
const attribution = object5(status.source)?.attribution;
|
|
28897
|
+
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.` };
|
|
28898
|
+
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.` };
|
|
28899
|
+
return { capture: true, state: "granted", reason: `The cua-driver daemon on ${machine} holds Screen Recording, so each run takes before and after snapshots.` };
|
|
28900
|
+
}
|
|
28901
|
+
|
|
28746
28902
|
// src/manager.ts
|
|
28747
28903
|
var SCRIPT_EXTENSIONS = { shell: "sh", javascript: "js", typescript: "ts", python: "py" };
|
|
28748
28904
|
var RENEWAL_WINDOW_MS = 15 * 6e4;
|
|
28749
28905
|
var MIN_RENEWAL_MS = 0.1 * 36e5;
|
|
28750
28906
|
var DEFAULT_AFTER_INTERVAL_MS = 500;
|
|
28751
28907
|
var CAPTURE_SOFTWARE = ["bundle:com.trycua.driver", "dpkg:cua-driver"];
|
|
28908
|
+
var durableRoot = (workspace, purpose) => join13(workspace, "work", `mcp-relay-${purpose}`);
|
|
28752
28909
|
var DOWNLOAD_BOUND = 64;
|
|
28753
28910
|
var DOWNLOAD_RETRY_DELAYS_MS = [1e3, 3e3];
|
|
28754
28911
|
var CAPACITY_RETRY_MS = 15e3;
|
|
@@ -28763,7 +28920,7 @@ async function settleEach(work) {
|
|
|
28763
28920
|
const failed = (await Promise.allSettled(work)).find((result2) => result2.status === "rejected");
|
|
28764
28921
|
if (failed) throw failed.reason;
|
|
28765
28922
|
}
|
|
28766
|
-
var instructions = "This server offers fourteen tools for guests,
|
|
28923
|
+
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
28924
|
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
28925
|
var RelayManager = class {
|
|
28769
28926
|
constructor(options) {
|
|
@@ -28780,14 +28937,6 @@ var RelayManager = class {
|
|
|
28780
28937
|
this.vm = options.vm ?? new MachineService({ baseUrl: this.environment?.profile.vmServiceUrl ?? process.env.MCP_RELAY_URL, environment: this.environment });
|
|
28781
28938
|
this.registry = options.registry ?? new Registry(this.environment ? { managedRoot: this.environment.profile.relayStateDir } : {});
|
|
28782
28939
|
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
28940
|
}
|
|
28792
28941
|
options;
|
|
28793
28942
|
vm;
|
|
@@ -28796,7 +28945,6 @@ var RelayManager = class {
|
|
|
28796
28945
|
tartPath;
|
|
28797
28946
|
registry;
|
|
28798
28947
|
root;
|
|
28799
|
-
channel;
|
|
28800
28948
|
/** The most guests this session holds at once (DC-20). */
|
|
28801
28949
|
maxGuests;
|
|
28802
28950
|
/** How long an acquisition waits for a host at capacity, and how often it is asked again (DC-22). */
|
|
@@ -28812,6 +28960,10 @@ var RelayManager = class {
|
|
|
28812
28960
|
ownerLock;
|
|
28813
28961
|
/** Set once shutdown has paused the guests: no new acquisition or guest operation starts. */
|
|
28814
28962
|
shuttingDown = false;
|
|
28963
|
+
/** The instance that owns a durable machine, found as machctl finds it (DC-29). */
|
|
28964
|
+
durableOwner(machine) {
|
|
28965
|
+
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 } : {} });
|
|
28966
|
+
}
|
|
28815
28967
|
serialized(fn) {
|
|
28816
28968
|
const next = this.queue.then(fn, fn);
|
|
28817
28969
|
this.queue = next.catch(() => {
|
|
@@ -28937,6 +29089,7 @@ var RelayManager = class {
|
|
|
28937
29089
|
return { endpoint: this.vm.baseUrl, tartHome: this.tartHome, ...this.environment ? { environmentFingerprint: this.environment.identity.fingerprint } : {} };
|
|
28938
29090
|
}
|
|
28939
29091
|
bindingMatches(e) {
|
|
29092
|
+
if (e.machine) return !!e.backend?.endpoint && !!e.backend.instance;
|
|
28940
29093
|
if (e.backend) {
|
|
28941
29094
|
const expected = this.binding();
|
|
28942
29095
|
return Object.keys(e.backend).length === Object.keys(expected).length && Object.entries(expected).every(([key, value]) => e.backend[key] === value);
|
|
@@ -29058,6 +29211,9 @@ var RelayManager = class {
|
|
|
29058
29211
|
const network2 = this.options.guestNetwork ?? guestNetwork();
|
|
29059
29212
|
if (!GUEST_NETWORKS.includes(network2)) throw new Error(`guestNetwork must be nat or internet, not ${JSON.stringify(network2)}`);
|
|
29060
29213
|
if (typeof input.task !== "string" || !TASK.test(input.task)) throw new Error("task must be a lowercase slug (1\u201336 chars)");
|
|
29214
|
+
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");
|
|
29215
|
+
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");
|
|
29216
|
+
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
29217
|
if (!Array.isArray(input.extractions) || input.extractions.length > 100) throw new Error("Declare up to 100 extractions before work");
|
|
29062
29218
|
const names = /* @__PURE__ */ new Set();
|
|
29063
29219
|
for (const extraction of input.extractions) {
|
|
@@ -29252,6 +29408,52 @@ var Guest = class {
|
|
|
29252
29408
|
closed = false;
|
|
29253
29409
|
/** After-image downloads, outside the serialized section (docs/screenshot-delivery.md §10). */
|
|
29254
29410
|
downloads;
|
|
29411
|
+
/** A durable machine's owner, once found (DC-29). */
|
|
29412
|
+
owner;
|
|
29413
|
+
/** The backend this guest's lease lives on: the loopback instance, or a durable machine's owner. */
|
|
29414
|
+
get vm() {
|
|
29415
|
+
const e = this.enclosure;
|
|
29416
|
+
if (!e?.machine) return this.m.vm;
|
|
29417
|
+
if (this.owner) return this.owner;
|
|
29418
|
+
if (!e.backend?.endpoint || e.backend.endpoint === this.m.vm.baseUrl) return this.owner = this.m.vm;
|
|
29419
|
+
throw new Error(`The owner of durable machine ${e.machine} has not been found again in this process; nothing was sent`);
|
|
29420
|
+
}
|
|
29421
|
+
/**
|
|
29422
|
+
* machine-service as the guest's only channel. Every call names the lease's
|
|
29423
|
+
* `lease_id` (DC-30); on a durable machine every file goes as bytes (DC-31).
|
|
29424
|
+
*/
|
|
29425
|
+
get channel() {
|
|
29426
|
+
const identity = () => {
|
|
29427
|
+
const id2 = this.enclosure?.lease?.lease_id;
|
|
29428
|
+
return id2 ? { lease_id: id2 } : {};
|
|
29429
|
+
};
|
|
29430
|
+
const durable = !!this.enclosure?.machine;
|
|
29431
|
+
return {
|
|
29432
|
+
exec: async (name, argv, timeoutMs2 = 18e4, options) => {
|
|
29433
|
+
const result2 = await this.vm.exec(name, { argv, timeout: Math.ceil(timeoutMs2 / 1e3), ...identity() }, { timeoutMs: options?.timeoutMs ?? timeoutMs2 + 3e4, signal: options?.signal });
|
|
29434
|
+
return { stdout: result2.output, stderr: result2.output, code: result2.rc };
|
|
29435
|
+
},
|
|
29436
|
+
push: async (name, local_path, remote_path) => {
|
|
29437
|
+
if (!durable) return this.vm.push(name, { local_path, remote_path, ...identity() });
|
|
29438
|
+
if (!this.vm.pushBytes) throw new Error("Backend lacks byte transfers; upgrade machine-service");
|
|
29439
|
+
return this.vm.pushBytes(name, { remote_path, bytes: await readFile9(local_path), ...identity() });
|
|
29440
|
+
},
|
|
29441
|
+
pull: async (name, remote_path, local_path, options) => {
|
|
29442
|
+
if (!durable) return this.vm.pull(name, { remote_path, local_path, ...identity() }, options);
|
|
29443
|
+
if (!this.vm.pullBytes) throw new Error("Backend lacks byte transfers; upgrade machine-service");
|
|
29444
|
+
await rm5(local_path, { force: true });
|
|
29445
|
+
await this.vm.pullBytes(name, { remote_path, to: local_path, ...identity() }, options);
|
|
29446
|
+
return { vm: name, pulled: remote_path, to: local_path };
|
|
29447
|
+
}
|
|
29448
|
+
};
|
|
29449
|
+
}
|
|
29450
|
+
/** Find a durable machine's owner again, and refuse when its origin or instance changed (DC-29). */
|
|
29451
|
+
async findOwner(e) {
|
|
29452
|
+
if (!e.machine || this.owner) return;
|
|
29453
|
+
const owner = await this.m.durableOwner(e.machine);
|
|
29454
|
+
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`);
|
|
29455
|
+
this.owner = owner.backend;
|
|
29456
|
+
}
|
|
29255
29457
|
serialized(fn) {
|
|
29256
29458
|
const next = this.queue.then(fn, fn);
|
|
29257
29459
|
this.queue = next.catch(() => {
|
|
@@ -29304,15 +29506,25 @@ var Guest = class {
|
|
|
29304
29506
|
if (!e) return;
|
|
29305
29507
|
this.assertBinding();
|
|
29306
29508
|
await this.m.assertBackend();
|
|
29509
|
+
await this.findOwner(e);
|
|
29307
29510
|
e.backend ??= this.m.binding();
|
|
29308
29511
|
if (!e.lease) {
|
|
29309
|
-
const matches = Object.values((await this.
|
|
29512
|
+
const matches = Object.values((await this.vm.list({ timeoutMs: 1e4 })).machines).filter((v) => v.purpose === e.purpose);
|
|
29310
29513
|
if (matches.length !== 1) throw new Error(`Cannot reconcile acquisition for ${e.purpose}; ownership retained, never automatically reacquire`);
|
|
29311
29514
|
e.lease = matches[0];
|
|
29312
29515
|
e.acquisitionInFlight = false;
|
|
29516
|
+
if (e.machine && e.lease.workspace) e.guestRoot = durableRoot(e.lease.workspace, e.purpose);
|
|
29313
29517
|
}
|
|
29314
29518
|
try {
|
|
29315
|
-
const lease = await this.
|
|
29519
|
+
const lease = await this.vm.get(e.lease.vm, { timeoutMs: 1e4 });
|
|
29520
|
+
if (e.machine && lease.lease_id !== e.lease.lease_id) {
|
|
29521
|
+
await this.m.registry.remove(e.row);
|
|
29522
|
+
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() });
|
|
29523
|
+
this.enclosure = void 0;
|
|
29524
|
+
await this.save();
|
|
29525
|
+
await this.m.forget(this);
|
|
29526
|
+
return;
|
|
29527
|
+
}
|
|
29316
29528
|
if (lease.purpose !== e.purpose || e.lease.lease_id && lease.lease_id !== e.lease.lease_id) throw new Error("Lease ownership identity mismatch");
|
|
29317
29529
|
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
29530
|
if (lease.console) {
|
|
@@ -29360,7 +29572,7 @@ var Guest = class {
|
|
|
29360
29572
|
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
29573
|
const required2 = name === "node";
|
|
29362
29574
|
try {
|
|
29363
|
-
const r = await this.
|
|
29575
|
+
const r = await this.channel.exec(e.lease.vm, [...argv], 1e4);
|
|
29364
29576
|
checks.push({ name, language: language2, required: required2, ...r, ready: r.code === 0 });
|
|
29365
29577
|
} catch (error2) {
|
|
29366
29578
|
checks.push({ name, language: language2, required: required2, ready: false, diagnostic: String(error2) });
|
|
@@ -29369,15 +29581,16 @@ var Guest = class {
|
|
|
29369
29581
|
const tsx = checks[1], nodeVersion = /^v(\d+)\.(\d+)/.exec(String(checks[0].stdout ?? ""));
|
|
29370
29582
|
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
29583
|
let software;
|
|
29372
|
-
|
|
29373
|
-
|
|
29584
|
+
if (e.machine) software = { machine: e.machine, software: (await this.vm.get(e.lease.vm, { timeoutMs: 1e4 })).capabilities?.software ?? null };
|
|
29585
|
+
else try {
|
|
29586
|
+
const catalog = await this.vm.applications({ timeoutMs: 1e4 });
|
|
29374
29587
|
validateCatalog(catalog);
|
|
29375
29588
|
const listed = catalog.images.find((image) => image.image === e.image);
|
|
29376
29589
|
software = listed ? { image: e.image, applications: listed.applications } : { image: e.image, applications: [], diagnostic: `The catalog does not list ${e.image}.` };
|
|
29377
29590
|
} catch (error2) {
|
|
29378
29591
|
software = { image: e.image, diagnostic: `The image catalog could not be read: ${message(error2)}` };
|
|
29379
29592
|
}
|
|
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);
|
|
29593
|
+
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
29594
|
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
29595
|
await this.log("guest-readiness", void 0, facts);
|
|
29383
29596
|
return facts;
|
|
@@ -29393,10 +29606,10 @@ var Guest = class {
|
|
|
29393
29606
|
}
|
|
29394
29607
|
async resolveConsole(signal) {
|
|
29395
29608
|
const e = await this.consoleOwner(signal);
|
|
29396
|
-
if (!this.
|
|
29609
|
+
if (!this.vm.consoleResolve) throw new Error("Backend lacks console API; upgrade machine-service");
|
|
29397
29610
|
let observation;
|
|
29398
29611
|
try {
|
|
29399
|
-
observation = consoleStatus(await this.
|
|
29612
|
+
observation = consoleStatus(await this.vm.consoleResolve(e.lease.vm, { lease_id: e.lease.lease_id }, { signal, timeoutMs: 1e4 }));
|
|
29400
29613
|
} catch (error2) {
|
|
29401
29614
|
if (e.consoleObservation && e.consoleObservation.status !== "revoked") e.consoleObservation = { ...e.consoleObservation, status: "unknown" };
|
|
29402
29615
|
await this.save();
|
|
@@ -29419,7 +29632,7 @@ var Guest = class {
|
|
|
29419
29632
|
const resolved = await this.resolveConsole(signal), e = this.current();
|
|
29420
29633
|
if (!e.lease.console?.console_id) throw new Error("This lease has no acquired console; automatic VNC retrofit is forbidden");
|
|
29421
29634
|
if (resolved.console_id !== input.console_id) throw new Error("Console instance identity mismatch");
|
|
29422
|
-
const method = operation === "open" ? this.
|
|
29635
|
+
const method = operation === "open" ? this.vm.consoleOpen : this.vm.consoleCancel;
|
|
29423
29636
|
if (!method) throw new Error("Backend lacks console API; upgrade machine-service");
|
|
29424
29637
|
if (operation === "open") {
|
|
29425
29638
|
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 +29651,7 @@ var Guest = class {
|
|
|
29438
29651
|
await this.save();
|
|
29439
29652
|
await this.log(`console-${operation}-intent`, "reason" in input ? input.reason : void 0, { ...body, ..."expected" in input ? { expected: input.expected } : {}, screenshotEvidence: false });
|
|
29440
29653
|
try {
|
|
29441
|
-
const observation = consoleStatus(await method.call(this.
|
|
29654
|
+
const observation = consoleStatus(await method.call(this.vm, e.lease.vm, body, { signal, timeoutMs: 3e4 }));
|
|
29442
29655
|
this.assertConsoleIdentity(observation, e);
|
|
29443
29656
|
if (observation.console_id !== body.console_id || observation.attempt?.attempt_id !== body.attempt_id) throw new Error("Console response identity mismatch");
|
|
29444
29657
|
e.consoleObservation = observation;
|
|
@@ -29459,7 +29672,7 @@ var Guest = class {
|
|
|
29459
29672
|
transfer() {
|
|
29460
29673
|
const e = this.current();
|
|
29461
29674
|
if (!e.node) throw new Error("Stage runtime first");
|
|
29462
|
-
return new Transfer(this.
|
|
29675
|
+
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
29676
|
}
|
|
29464
29677
|
async log(kind, because, details = {}) {
|
|
29465
29678
|
if (because !== void 0) this.m.reason(because);
|
|
@@ -29474,13 +29687,17 @@ var Guest = class {
|
|
|
29474
29687
|
*/
|
|
29475
29688
|
async acquire(input, network, signal) {
|
|
29476
29689
|
const ttlHours = input.ttlHours ?? 4;
|
|
29690
|
+
let owner;
|
|
29477
29691
|
try {
|
|
29478
29692
|
if (this.m.shuttingDown || this.closed) throw new Error("Relay manager is shutting down");
|
|
29479
|
-
|
|
29480
|
-
|
|
29481
|
-
|
|
29482
|
-
|
|
29483
|
-
if (
|
|
29693
|
+
if (input.machine) owner = await this.m.durableOwner(input.machine);
|
|
29694
|
+
else {
|
|
29695
|
+
const image = input.image, images = await this.vm.images({ timeoutMs: 5e3, signal });
|
|
29696
|
+
if (!images.images[image]?.base_available) throw new Error(`Image unavailable: ${image}`);
|
|
29697
|
+
if (input.vnc) {
|
|
29698
|
+
const capabilities = await this.m.readAcquisitionCapabilities(signal);
|
|
29699
|
+
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");
|
|
29700
|
+
}
|
|
29484
29701
|
}
|
|
29485
29702
|
await this.lock();
|
|
29486
29703
|
} catch (error2) {
|
|
@@ -29492,8 +29709,10 @@ var Guest = class {
|
|
|
29492
29709
|
const stamp = startedAt.slice(0, 19).replace(/[T:]/g, "-") + "-Z";
|
|
29493
29710
|
const project = this.m.options.project, environment = this.m.environment;
|
|
29494
29711
|
const hostRoot = join13(this.m.options.outputRoot ?? resolve9(project, "relay-evidence"), purpose);
|
|
29495
|
-
const
|
|
29496
|
-
const
|
|
29712
|
+
const subject = input.machine ?? input.image;
|
|
29713
|
+
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 };
|
|
29714
|
+
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 };
|
|
29715
|
+
if (owner) this.owner = owner.backend;
|
|
29497
29716
|
let refused = false;
|
|
29498
29717
|
try {
|
|
29499
29718
|
await this.save();
|
|
@@ -29516,7 +29735,9 @@ var Guest = class {
|
|
|
29516
29735
|
await this.save();
|
|
29517
29736
|
const asked = Date.now();
|
|
29518
29737
|
try {
|
|
29519
|
-
|
|
29738
|
+
const ttl_hours = Math.min(this.m.renewalWindowMs(), ttlHours * 36e5) / 36e5;
|
|
29739
|
+
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 });
|
|
29740
|
+
if (e.machine) e.guestRoot = durableRoot(e.lease.workspace, purpose);
|
|
29520
29741
|
e.acquisitionInFlight = false;
|
|
29521
29742
|
granted = asked;
|
|
29522
29743
|
break;
|
|
@@ -29548,7 +29769,7 @@ var Guest = class {
|
|
|
29548
29769
|
this.startHeartbeat();
|
|
29549
29770
|
await this.save();
|
|
29550
29771
|
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 };
|
|
29772
|
+
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
29773
|
} catch (error2) {
|
|
29553
29774
|
if (refused && await this.withdraw(error2)) throw error2;
|
|
29554
29775
|
await this.fail(error2);
|
|
@@ -29593,7 +29814,7 @@ Guest ${this.name} keeps this acquisition's ownership record: name it to reconci
|
|
|
29593
29814
|
async withdraw(error2) {
|
|
29594
29815
|
const e = this.enclosure;
|
|
29595
29816
|
try {
|
|
29596
|
-
if (Object.values((await this.
|
|
29817
|
+
if (Object.values((await this.vm.list({ timeoutMs: 1e4 })).machines).some((lease) => lease.purpose === e.purpose)) return false;
|
|
29597
29818
|
await this.m.registry.remove(e.row);
|
|
29598
29819
|
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
29820
|
this.enclosure = void 0;
|
|
@@ -29647,7 +29868,7 @@ Guest ${this.name} keeps this acquisition's ownership record: name it to reconci
|
|
|
29647
29868
|
}
|
|
29648
29869
|
this.assertBinding();
|
|
29649
29870
|
await this.m.assertBackend();
|
|
29650
|
-
const renewed = await this.
|
|
29871
|
+
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
29872
|
if (this.enclosure !== e || e.released) return;
|
|
29652
29873
|
e.expiresAt = renewed.ttl_expires_at;
|
|
29653
29874
|
e.guestState = renewed.state;
|
|
@@ -29700,18 +29921,24 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
29700
29921
|
const workspace = input.workspace === void 0 ? void 0 : await this.m.projectPath(input.workspace, "workspace");
|
|
29701
29922
|
const bundle = this.m.options.runtimeBundle ?? fileURLToPath(new URL("../dist/receiver.mjs", import.meta.url));
|
|
29702
29923
|
await access(bundle);
|
|
29703
|
-
if (e.capture === void 0 && !e.staged) {
|
|
29924
|
+
if (!e.machine && e.capture === void 0 && !e.staged) {
|
|
29704
29925
|
e.capture = await this.captureSoftware(e, signal);
|
|
29705
29926
|
await this.save();
|
|
29706
29927
|
}
|
|
29707
29928
|
const node2 = input.nodePath ?? e.node ?? "node";
|
|
29708
|
-
const transfer = new Transfer(this.
|
|
29929
|
+
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
29930
|
try {
|
|
29710
29931
|
await transfer.checked([node2, "--version"]);
|
|
29711
29932
|
} catch (error2) {
|
|
29712
29933
|
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
29934
|
}
|
|
29714
|
-
const cuaDriver = input.cuaDriver ?? e.cuaDriver ?? (e.lease.image_kind === "macos" ? "/Applications/CuaDriver.app/Contents/MacOS/cua-driver" : "cua-driver");
|
|
29935
|
+
const cuaDriver = input.cuaDriver ?? e.cuaDriver ?? (e.lease.image_kind === "macos" || e.machine ? "/Applications/CuaDriver.app/Contents/MacOS/cua-driver" : "cua-driver");
|
|
29936
|
+
if (e.machine) {
|
|
29937
|
+
const decision = await this.durableCapture(e, cuaDriver, signal);
|
|
29938
|
+
e.capture = decision.capture;
|
|
29939
|
+
e.captureReason = decision.reason;
|
|
29940
|
+
await this.save();
|
|
29941
|
+
}
|
|
29715
29942
|
if (e.capture !== false) await this.awaitCapture(transfer, e, node2, cuaDriver, signal);
|
|
29716
29943
|
e.node = node2;
|
|
29717
29944
|
e.cuaDriver = cuaDriver;
|
|
@@ -29730,7 +29957,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
29730
29957
|
this.transport = new VmTransport(transfer, e.guestRoot, join13(e.hostRoot, "host"), e.cuaDriver);
|
|
29731
29958
|
this.transport.capture = e.capture !== false;
|
|
29732
29959
|
relay.useTransport(() => this.transport);
|
|
29733
|
-
this.session = await relay.start({ taskId: e.purpose, target: `machine-service:${e.lease.vm}` });
|
|
29960
|
+
this.session = await relay.start({ taskId: e.purpose, target: `machine-service:${e.machine ? `durable:${e.machine}` : e.lease.vm}` });
|
|
29734
29961
|
e.sessionId = this.session.sessionId;
|
|
29735
29962
|
e.staged = true;
|
|
29736
29963
|
await this.save();
|
|
@@ -29744,7 +29971,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
29744
29971
|
async captureSoftware(e, signal) {
|
|
29745
29972
|
let catalog;
|
|
29746
29973
|
try {
|
|
29747
|
-
catalog = await this.
|
|
29974
|
+
catalog = await this.vm.applications({ timeoutMs: 1e4, signal });
|
|
29748
29975
|
validateCatalog(catalog);
|
|
29749
29976
|
} catch (error2) {
|
|
29750
29977
|
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 +29980,26 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
29753
29980
|
await this.log("capture-software", void 0, { image: e.image, capture, ids: CAPTURE_SOFTWARE });
|
|
29754
29981
|
return capture;
|
|
29755
29982
|
}
|
|
29983
|
+
/**
|
|
29984
|
+
* Whether a durable machine's runs take snapshots: its capabilities list
|
|
29985
|
+
* cua-driver, and the cua-driver daemon, not machine-service, holds Screen
|
|
29986
|
+
* Recording (DC-32).
|
|
29987
|
+
*/
|
|
29988
|
+
async durableCapture(e, cuaDriver, signal) {
|
|
29989
|
+
const software = (await this.vm.get(e.lease.vm, { timeoutMs: 1e4, signal })).capabilities?.software;
|
|
29990
|
+
let answer;
|
|
29991
|
+
if (software && typeof software === "object" && software.cua_driver) {
|
|
29992
|
+
try {
|
|
29993
|
+
answer = await this.channel.exec(e.lease.vm, [cuaDriver, "permissions", "status", "--json"], 3e4, { signal });
|
|
29994
|
+
} catch (error2) {
|
|
29995
|
+
if (signal?.aborted) throw error2;
|
|
29996
|
+
answer = { error: message(error2) };
|
|
29997
|
+
}
|
|
29998
|
+
}
|
|
29999
|
+
const decision = durableCapture(e.machine, software, answer);
|
|
30000
|
+
await this.log("capture-permission", void 0, { machine: e.machine, ...decision, answer });
|
|
30001
|
+
return decision;
|
|
30002
|
+
}
|
|
29756
30003
|
/**
|
|
29757
30004
|
* Waits until the guest's cua-driver takes a screenshot, as each run's
|
|
29758
30005
|
* snapshots do (DC-24). The image starts its daemon at login, which can
|
|
@@ -29786,6 +30033,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
29786
30033
|
}
|
|
29787
30034
|
/** What a lease's runs record: snapshots when its image lists cua-driver, none otherwise. */
|
|
29788
30035
|
snapshotFacts(e) {
|
|
30036
|
+
if (e.machine) return { taken: e.capture === true, reason: e.captureReason ?? "Decided at relay_stage." };
|
|
29789
30037
|
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
30038
|
}
|
|
29791
30039
|
async run(input, signal) {
|
|
@@ -29860,12 +30108,12 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
29860
30108
|
ensureGuest: async (signal, deadline) => {
|
|
29861
30109
|
const options = { signal, timeoutMs: Math.max(1, Math.min(1e4, deadline - Date.now())) };
|
|
29862
30110
|
if (this.m.environment) {
|
|
29863
|
-
const health = await this.
|
|
30111
|
+
const health = await this.vm.health(options);
|
|
29864
30112
|
if (!health.ok || !matchesEnvironment(health.environment, this.m.environment)) throw Object.assign(new Error("Selected backend identity changed."), { code: "unauthorized-reference" });
|
|
29865
30113
|
}
|
|
29866
30114
|
try {
|
|
29867
|
-
const lease = await this.
|
|
29868
|
-
if (lease.purpose !== e.purpose) throw Object.assign(new Error("Lease ownership identity changed."), { code: "unauthorized-reference" });
|
|
30115
|
+
const lease = await this.vm.get(e.lease.vm, options);
|
|
30116
|
+
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
30117
|
} catch (error2) {
|
|
29870
30118
|
if (error2 instanceof MachineServiceError && error2.status === 404) throw Object.assign(new Error("Saved image guest is no longer available."), { code: "stale-reference" });
|
|
29871
30119
|
throw error2;
|
|
@@ -29894,16 +30142,16 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
29894
30142
|
}
|
|
29895
30143
|
const store = this.imageStore(), result2 = await store.get(target, bounded3, deadline);
|
|
29896
30144
|
if (result2.status !== "unauthorized-reference" || target.source !== "reference") return result2;
|
|
29897
|
-
const
|
|
29898
|
-
if (
|
|
29899
|
-
const resolved = await store.get({ source: "display", sessionId:
|
|
30145
|
+
const named2 = job?.image ?? await this.namedImage(target.imageId);
|
|
30146
|
+
if (named2?.source !== "display") return result2;
|
|
30147
|
+
const resolved = await store.get({ source: "display", sessionId: named2.sessionId, executionId: named2.executionId, phase: named2.phase }, bounded3, deadline);
|
|
29900
30148
|
return resolved.image && resolved.image.imageId !== target.imageId ? { status: "integrity-failed", diagnostic: "The display selector no longer names the referenced image." } : resolved;
|
|
29901
30149
|
}
|
|
29902
30150
|
/** The image a run named with this reference, from the step download records. No guest I/O. */
|
|
29903
30151
|
async namedImage(imageId) {
|
|
29904
30152
|
const records = join13(this.current().hostRoot, "host", "evidence-downloads");
|
|
29905
30153
|
for (const name of (await readdir7(records).catch(() => [])).filter((n) => n.endsWith(".json"))) {
|
|
29906
|
-
const image = await readFile9(join13(records, name), "utf8").then((
|
|
30154
|
+
const image = await readFile9(join13(records, name), "utf8").then((text5) => JSON.parse(text5)?.image, () => void 0);
|
|
29907
30155
|
if (image?.imageId === imageId) return image;
|
|
29908
30156
|
}
|
|
29909
30157
|
return void 0;
|
|
@@ -29952,7 +30200,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
29952
30200
|
for (let attempt = 1; !files; attempt++) {
|
|
29953
30201
|
try {
|
|
29954
30202
|
await assertHostPath(e.hostRoot, folder, true);
|
|
29955
|
-
await
|
|
30203
|
+
await rm5(folder, { recursive: true, force: true });
|
|
29956
30204
|
files = await this.transfer().pullArchive(e.guestRoot, e.guestRoot, requested, folder, e.hostRoot, { present: true, once: true, signal: bounded3 });
|
|
29957
30205
|
} catch (error2) {
|
|
29958
30206
|
const transient2 = !bounded3.aborted && transientTransfer(error2);
|
|
@@ -30014,7 +30262,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
30014
30262
|
async removeStepFolders(recording) {
|
|
30015
30263
|
const steps = join13(recording, "host", "steps");
|
|
30016
30264
|
await assertHostPath(recording, steps, true);
|
|
30017
|
-
await
|
|
30265
|
+
await rm5(steps, { recursive: true, force: true });
|
|
30018
30266
|
}
|
|
30019
30267
|
/** A lifecycle operation's gate (AD-5): every download ends before the guest state is touched; the queue opens again after. */
|
|
30020
30268
|
async drained(fn) {
|
|
@@ -30178,7 +30426,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
30178
30426
|
await jsonFile(join13(e.hostRoot, "host", "diagnostics", `${executionId}.request.json`), request);
|
|
30179
30427
|
let result2;
|
|
30180
30428
|
try {
|
|
30181
|
-
const r = await this.
|
|
30429
|
+
const r = await this.channel.exec(e.lease.vm, argv, timeoutMs2, { signal });
|
|
30182
30430
|
result2 = { executionId, outcome: { kind: "completed", exitStatus: { code: r.code, signal: null } }, output: r.stdout, outputStreams: "stdout and stderr combined" };
|
|
30183
30431
|
} catch (error2) {
|
|
30184
30432
|
result2 = { executionId, outcome: { kind: "uncertain", diagnostic: String(error2) }, output: "", outputStreams: "stdout and stderr combined" };
|
|
@@ -30251,10 +30499,11 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
30251
30499
|
await this.m.assertBackend();
|
|
30252
30500
|
const e = this.enclosure;
|
|
30253
30501
|
if (!e) return;
|
|
30502
|
+
await this.findOwner(e);
|
|
30254
30503
|
this.stopTimer();
|
|
30255
30504
|
if (!e.released) {
|
|
30256
30505
|
if (!e.lease) {
|
|
30257
|
-
const list = await this.
|
|
30506
|
+
const list = await this.vm.list({ timeoutMs: 1e4 });
|
|
30258
30507
|
const matches = Object.values(list.machines).filter((lease) => lease.purpose === e.purpose);
|
|
30259
30508
|
if (matches.length > 1) throw new Error("Ambiguous acquisition; refusing to remove ownership record");
|
|
30260
30509
|
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 +30515,24 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
30266
30515
|
let released = false;
|
|
30267
30516
|
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
30268
30517
|
try {
|
|
30269
|
-
const response = await this.
|
|
30518
|
+
const response = await this.vm.release(e.lease.vm, { reason: reason2, ...e.lease.lease_id ? { lease_id: e.lease.lease_id } : {} }, { timeoutMs: timeoutMs2 });
|
|
30270
30519
|
if (!response.released) throw new Error("machine-service did not confirm destruction");
|
|
30520
|
+
if (e.machine) {
|
|
30521
|
+
e.hygiene = response.hygiene;
|
|
30522
|
+
await this.save().catch(() => {
|
|
30523
|
+
});
|
|
30524
|
+
}
|
|
30271
30525
|
released = true;
|
|
30272
30526
|
break;
|
|
30273
30527
|
} catch (error2) {
|
|
30274
30528
|
await this.log("release-error", void 0, { vm: e.lease.vm, cause: reason2, attempt: attempt + 1, error: String(error2) }).catch(() => {
|
|
30275
30529
|
});
|
|
30276
30530
|
try {
|
|
30277
|
-
await this.
|
|
30531
|
+
const record3 = await this.vm.get(e.lease.vm, { timeoutMs: 5e3 });
|
|
30532
|
+
if (e.machine && record3.lease_id !== e.lease.lease_id) {
|
|
30533
|
+
released = true;
|
|
30534
|
+
break;
|
|
30535
|
+
}
|
|
30278
30536
|
} catch (getError) {
|
|
30279
30537
|
if (getError instanceof MachineServiceError && getError.status === 404) {
|
|
30280
30538
|
released = true;
|
|
@@ -30285,7 +30543,9 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
30285
30543
|
}
|
|
30286
30544
|
}
|
|
30287
30545
|
if (!released) throw new Error("Lease release unconfirmed");
|
|
30288
|
-
if (
|
|
30546
|
+
if (e.machine) {
|
|
30547
|
+
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.`);
|
|
30548
|
+
} 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
30549
|
}
|
|
30290
30550
|
e.released = true;
|
|
30291
30551
|
await this.save().catch(() => {
|
|
@@ -30295,12 +30555,16 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
30295
30555
|
await this.session?.close();
|
|
30296
30556
|
this.session = void 0;
|
|
30297
30557
|
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(() => {
|
|
30558
|
+
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
30559
|
});
|
|
30300
30560
|
this.enclosure = void 0;
|
|
30301
30561
|
await this.save();
|
|
30302
30562
|
await this.m.forget(this);
|
|
30303
30563
|
}
|
|
30564
|
+
/** A durable release is verified when the machine no longer names the lease (DC-33). */
|
|
30565
|
+
async durableReleased(e) {
|
|
30566
|
+
return (await this.vm.get(e.lease.vm, { timeoutMs: 1e4 })).lease_id !== e.lease.lease_id;
|
|
30567
|
+
}
|
|
30304
30568
|
async destroyed(vm) {
|
|
30305
30569
|
if (this.m.options.verifyDestroyed) return this.m.options.verifyDestroyed(vm);
|
|
30306
30570
|
const environment = this.m.environment;
|
|
@@ -30333,7 +30597,7 @@ VM state: ${JSON.stringify(this.status())}`, { cause: error2 });
|
|
|
30333
30597
|
const remaining = this.remainingMs(e);
|
|
30334
30598
|
if (remaining < MIN_RENEWAL_MS) return;
|
|
30335
30599
|
try {
|
|
30336
|
-
const renewed = await this.
|
|
30600
|
+
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
30601
|
if (this.enclosure === e && !e.released) {
|
|
30338
30602
|
e.expiresAt = renewed.ttl_expires_at;
|
|
30339
30603
|
e.guestState = renewed.state;
|
|
@@ -30375,7 +30639,8 @@ var relayContract = typebox_exports.Union([
|
|
|
30375
30639
|
typebox_exports.Object({
|
|
30376
30640
|
action: typebox_exports.Literal("acquire"),
|
|
30377
30641
|
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." }),
|
|
30642
|
+
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." })),
|
|
30643
|
+
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
30644
|
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
30645
|
vnc: typebox_exports.Optional(typebox_exports.Boolean({ description: "Prepare guest console sharing, default false. Never opens a viewer automatically." })),
|
|
30381
30646
|
ttlHours: typebox_exports.Optional(typebox_exports.Number({ minimum: 0.1, maximum: 720 })),
|
|
@@ -30432,6 +30697,7 @@ function toolInputSchema(action) {
|
|
|
30432
30697
|
function validateRelayInput(value) {
|
|
30433
30698
|
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
30699
|
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.');
|
|
30700
|
+
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
30701
|
if (value.action === "run") {
|
|
30436
30702
|
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
30703
|
if (value.diagnostic && value.snapshots?.group) throw new Error("Diagnostic scripts cannot join snapshot groups.");
|
|
@@ -30472,9 +30738,9 @@ var relayTools = [
|
|
|
30472
30738
|
{
|
|
30473
30739
|
name: "relay_acquire",
|
|
30474
30740
|
action: "acquire",
|
|
30475
|
-
title: "Acquire a
|
|
30741
|
+
title: "Acquire a machine",
|
|
30476
30742
|
annotations: acts(false),
|
|
30477
|
-
description: "Acquire one
|
|
30743
|
+
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
30744
|
},
|
|
30479
30745
|
{
|
|
30480
30746
|
name: "relay_stage",
|
|
@@ -30551,15 +30817,15 @@ function relayToolInput(name, args) {
|
|
|
30551
30817
|
var relayResultKind = "relay-image-result-v1";
|
|
30552
30818
|
async function renderRelayResult(value, resultRoot = join14(tmpdir2(), "mcp-relay-results"), indent = 2) {
|
|
30553
30819
|
const full = JSON.stringify(value, null, indent);
|
|
30554
|
-
const
|
|
30555
|
-
if (
|
|
30820
|
+
const text5 = new TextDecoder().decode(Buffer.from(full.split("\n").slice(0, 2e3).join("\n")).subarray(0, 50 * 1024), { stream: true });
|
|
30821
|
+
if (text5 !== full) {
|
|
30556
30822
|
await mkdir11(resultRoot, { recursive: true, mode: 448 });
|
|
30557
30823
|
const path = join14(resultRoot, `${randomUUID7()}.json`);
|
|
30558
30824
|
await writeFile4(path, full, { mode: 384 });
|
|
30559
|
-
return { text: `${
|
|
30825
|
+
return { text: `${text5}
|
|
30560
30826
|
[Truncated. Full result: ${path}]`, details: { resultPath: path }, resultPath: path };
|
|
30561
30827
|
}
|
|
30562
|
-
return { text:
|
|
30828
|
+
return { text: text5, details: value };
|
|
30563
30829
|
}
|
|
30564
30830
|
async function imageResult(value, delivery, executionFailed = false) {
|
|
30565
30831
|
const { content: image, ...imageDelivery } = delivery;
|
|
@@ -30636,11 +30902,11 @@ async function relayCall(host, raw, options = {}) {
|
|
|
30636
30902
|
|
|
30637
30903
|
// src/server.ts
|
|
30638
30904
|
var SERVER_NAME = "relay";
|
|
30639
|
-
var SERVER_VERSION = true ? "0.
|
|
30905
|
+
var SERVER_VERSION = true ? "0.17.1" : JSON.parse(readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8")).version;
|
|
30640
30906
|
var STATUS_TOOL = "relay_status";
|
|
30641
30907
|
var PLUGIN_TOOL_PREFIX = "mcp__plugin_mcp-relay_relay__";
|
|
30642
30908
|
var message2 = (error2) => error2 instanceof Error ? error2.message : String(error2);
|
|
30643
|
-
var
|
|
30909
|
+
var text4 = (value, isError = false) => ({ content: [{ type: "text", text: value }], isError });
|
|
30644
30910
|
function relayContent(result2) {
|
|
30645
30911
|
return { content: [{ type: "text", text: result2.text }, ...result2.image ? [{ type: "image", data: result2.image.data, mimeType: result2.image.mimeType }] : []], isError: result2.isError };
|
|
30646
30912
|
}
|
|
@@ -30689,11 +30955,11 @@ function createRelayServer(options = {}) {
|
|
|
30689
30955
|
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
30690
30956
|
const { name, arguments: args } = request.params;
|
|
30691
30957
|
try {
|
|
30692
|
-
if (name === STATUS_TOOL) return
|
|
30958
|
+
if (name === STATUS_TOOL) return text4(JSON.stringify(statusPayload(), null, 2));
|
|
30693
30959
|
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
30960
|
throw new Error(`Unknown tool: ${name}`);
|
|
30695
30961
|
} catch (error2) {
|
|
30696
|
-
return
|
|
30962
|
+
return text4(message2(error2), true);
|
|
30697
30963
|
}
|
|
30698
30964
|
});
|
|
30699
30965
|
const cleanup = async (reason2) => {
|