@wezzard/mcp-relay 0.0.0-stage → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +9 -0
- package/.mcp.json +10 -0
- package/LICENSE +21 -0
- package/README.md +421 -2
- package/agents/vm-relay-operator.md +39 -0
- package/commands/status.md +4 -0
- package/dist/NOTICE.txt +1 -0
- package/dist/build-info.json +982 -0
- package/dist/doctor.mjs +802 -0
- package/dist/integrity.json +6 -0
- package/dist/receiver.mjs +1341 -0
- package/dist/review-data.d.ts +68 -0
- package/dist/review-data.mjs +404 -0
- package/dist/server.mjs +30767 -0
- package/package.json +75 -4
- package/pi-mcp.json +1 -0
- package/pi-prompts/mcp-relay-status.md +4 -0
package/dist/doctor.mjs
ADDED
|
@@ -0,0 +1,802 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// src/doctor.ts
|
|
5
|
+
import { access, readFile as readFile2 } from "node:fs/promises";
|
|
6
|
+
import { join as join4 } from "node:path";
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
8
|
+
import { realpathSync as realpathSync2 } from "node:fs";
|
|
9
|
+
|
|
10
|
+
// src/util.ts
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
13
|
+
var hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
14
|
+
async function command(argv, options = {}) {
|
|
15
|
+
options.signal?.throwIfAborted();
|
|
16
|
+
return new Promise((resolve4, reject) => {
|
|
17
|
+
const child = spawn(argv[0], argv.slice(1), { cwd: options.cwd, env: options.env, stdio: ["ignore", "pipe", "pipe"], signal: options.signal });
|
|
18
|
+
let stdout = "", stderr = "", size = 0;
|
|
19
|
+
let failure;
|
|
20
|
+
const timer = setTimeout(() => {
|
|
21
|
+
failure = new Error(`Command timed out: ${argv[0]}`);
|
|
22
|
+
child.kill("SIGKILL");
|
|
23
|
+
}, options.timeoutMs ?? 1e4);
|
|
24
|
+
const consume = (channel, chunk) => {
|
|
25
|
+
size += chunk.length;
|
|
26
|
+
if (size > (options.maxBytes ?? 128 * 1024)) {
|
|
27
|
+
failure = new Error(`Command output exceeded limit: ${argv[0]}`);
|
|
28
|
+
child.kill("SIGKILL");
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (channel === "stdout") stdout += chunk;
|
|
32
|
+
else stderr += chunk;
|
|
33
|
+
};
|
|
34
|
+
child.stdout.on("data", (chunk) => consume("stdout", chunk));
|
|
35
|
+
child.stderr.on("data", (chunk) => consume("stderr", chunk));
|
|
36
|
+
child.on("error", (err) => {
|
|
37
|
+
clearTimeout(timer);
|
|
38
|
+
reject(err);
|
|
39
|
+
});
|
|
40
|
+
child.on("close", (code) => {
|
|
41
|
+
clearTimeout(timer);
|
|
42
|
+
if (failure) reject(failure);
|
|
43
|
+
else resolve4({ stdout, stderr, code: code ?? -1 });
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// src/vm-service.ts
|
|
49
|
+
import { isIP } from "node:net";
|
|
50
|
+
var VmServiceError = class extends Error {
|
|
51
|
+
constructor(message, status, responseBody, options) {
|
|
52
|
+
super(message, options);
|
|
53
|
+
this.status = status;
|
|
54
|
+
this.responseBody = responseBody;
|
|
55
|
+
this.name = "VmServiceError";
|
|
56
|
+
}
|
|
57
|
+
/** The host is at capacity, such as its limit on running macOS VMs: nothing was reserved, and the same acquisition may be asked again (DC-22). */
|
|
58
|
+
capacity = false;
|
|
59
|
+
};
|
|
60
|
+
function capacityRefusal(error) {
|
|
61
|
+
if (!(error instanceof VmServiceError) || error.status !== 409 || !error.responseBody) return false;
|
|
62
|
+
let body;
|
|
63
|
+
try {
|
|
64
|
+
body = JSON.parse(error.responseBody);
|
|
65
|
+
} catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
if (!body || typeof body !== "object") return false;
|
|
69
|
+
const { error: reason, outcome } = body;
|
|
70
|
+
return typeof reason === "string" && reason.startsWith("macOS VM limit reached") && outcome !== "uncertain";
|
|
71
|
+
}
|
|
72
|
+
var AcquireIndeterminateError = class extends VmServiceError {
|
|
73
|
+
constructor(purpose, cause) {
|
|
74
|
+
super(`Acquisition outcome unknown for purpose '${purpose}'; reconcile GET /vms before retrying or ending the enclosure`, void 0, void 0, { cause });
|
|
75
|
+
this.purpose = purpose;
|
|
76
|
+
this.name = "AcquireIndeterminateError";
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
function positive(value, label) {
|
|
80
|
+
if (!Number.isSafeInteger(value) || value <= 0 || value > 2147483647) throw new TypeError(`${label} must be a positive bounded integer`);
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
function record(value) {
|
|
84
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
85
|
+
}
|
|
86
|
+
function isLease(value) {
|
|
87
|
+
if (!record(value)) return false;
|
|
88
|
+
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";
|
|
89
|
+
}
|
|
90
|
+
var VmService = class {
|
|
91
|
+
baseUrl;
|
|
92
|
+
environment;
|
|
93
|
+
timeoutMs;
|
|
94
|
+
acquireTimeoutMs;
|
|
95
|
+
maxResponseBytes;
|
|
96
|
+
constructor(options = {}) {
|
|
97
|
+
if (typeof options === "string") options = { baseUrl: options };
|
|
98
|
+
this.environment = options.environment;
|
|
99
|
+
const url = new URL(options.baseUrl ?? options.environment?.profile.vmServiceUrl ?? "http://localhost:6240");
|
|
100
|
+
if (options.environment && url.origin !== new URL(options.environment.profile.vmServiceUrl).origin) throw new TypeError("Backend endpoint does not match the selected environment");
|
|
101
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
102
|
+
const loopback = host === "localhost" || host === "::1" || isIP(host) === 4 && host.startsWith("127.");
|
|
103
|
+
if (!loopback || !["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
|
104
|
+
throw new TypeError("vm-service baseUrl must be a loopback HTTP(S) origin without credentials, path, query or fragment");
|
|
105
|
+
}
|
|
106
|
+
this.baseUrl = url.origin;
|
|
107
|
+
this.timeoutMs = positive(options.timeoutMs ?? 66e4, "timeoutMs");
|
|
108
|
+
this.acquireTimeoutMs = positive(options.acquireTimeoutMs ?? 36e5, "acquireTimeoutMs");
|
|
109
|
+
this.maxResponseBytes = positive(options.maxResponseBytes ?? 4 * 1024 * 1024, "maxResponseBytes");
|
|
110
|
+
}
|
|
111
|
+
health(options = {}) {
|
|
112
|
+
return this.request("/health", void 0, options);
|
|
113
|
+
}
|
|
114
|
+
list(options = {}) {
|
|
115
|
+
return this.request("/vms", void 0, options);
|
|
116
|
+
}
|
|
117
|
+
images(options = {}) {
|
|
118
|
+
return this.request("/images", void 0, options);
|
|
119
|
+
}
|
|
120
|
+
applications(options = {}) {
|
|
121
|
+
return this.request("/applications", void 0, options);
|
|
122
|
+
}
|
|
123
|
+
acquisitionCapabilities(options = {}) {
|
|
124
|
+
return this.consoleRequest("/acquisition-capabilities", void 0, options);
|
|
125
|
+
}
|
|
126
|
+
consoleResolve(vm, body, options = {}) {
|
|
127
|
+
return this.consoleRequest(this.path(vm, "console/resolve"), body, options);
|
|
128
|
+
}
|
|
129
|
+
consoleOpen(vm, body, options = {}) {
|
|
130
|
+
return this.consoleRequest(this.path(vm, "console/open"), body, options);
|
|
131
|
+
}
|
|
132
|
+
consoleCancel(vm, body, options = {}) {
|
|
133
|
+
return this.consoleRequest(this.path(vm, "console/cancel"), body, options);
|
|
134
|
+
}
|
|
135
|
+
async consoleRequest(path, body, options) {
|
|
136
|
+
try {
|
|
137
|
+
return await this.request(path, body, options);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
throw new VmServiceError(`Console API unavailable or request outcome unknown${error instanceof VmServiceError && error.status ? ` (HTTP ${error.status})` : ""}; resolve before another open`, error instanceof VmServiceError ? error.status : void 0);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
get(vm, options = {}) {
|
|
143
|
+
return this.request(this.path(vm), void 0, options);
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Cancellation before dispatch prevents allocation. Once dispatched we deliberately
|
|
147
|
+
* do NOT abort the request: return the lease even if the caller cancels, so its
|
|
148
|
+
* finally/cleanup path can register and release it. Caller must track the returned
|
|
149
|
+
* lease before checking its signal. Network loss/deadline remains indeterminate
|
|
150
|
+
* (a daemon protocol limitation); never blindly retry acquisition.
|
|
151
|
+
*/
|
|
152
|
+
async acquire(body, options = {}) {
|
|
153
|
+
options.signal?.throwIfAborted();
|
|
154
|
+
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(body.purpose)) throw new TypeError("Invalid VM purpose");
|
|
155
|
+
const timeoutMs = positive(options.timeoutMs ?? this.acquireTimeoutMs, "timeoutMs");
|
|
156
|
+
try {
|
|
157
|
+
const lease = await this.request("/acquire", body, { timeoutMs });
|
|
158
|
+
if (!isLease(lease)) throw new VmServiceError("Invalid vm-service acquire response");
|
|
159
|
+
return lease;
|
|
160
|
+
} catch (error) {
|
|
161
|
+
const safeError = body.vnc ? new VmServiceError(`VNC acquisition refused or outcome unknown${error instanceof VmServiceError && error.status ? ` (HTTP ${error.status})` : ""}; inspect capabilities and reconcile ownership`, error instanceof VmServiceError ? error.status : void 0) : error;
|
|
162
|
+
if (safeError instanceof VmServiceError) safeError.capacity = capacityRefusal(error);
|
|
163
|
+
if (error instanceof VmServiceError && error.status !== void 0 && error.status >= 400 && error.status < 500) throw safeError;
|
|
164
|
+
throw new AcquireIndeterminateError(body.purpose, safeError);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
exec(vm, body, options = {}) {
|
|
168
|
+
return this.request(this.path(vm, "exec"), body, options);
|
|
169
|
+
}
|
|
170
|
+
push(vm, body, options = {}) {
|
|
171
|
+
return this.request(this.path(vm, "push"), body, options);
|
|
172
|
+
}
|
|
173
|
+
pull(vm, body, options = {}) {
|
|
174
|
+
return this.request(this.path(vm, "pull"), body, options);
|
|
175
|
+
}
|
|
176
|
+
heartbeat(vm, body = {}, options = {}) {
|
|
177
|
+
return this.request(this.path(vm, "heartbeat"), body, options);
|
|
178
|
+
}
|
|
179
|
+
release(vm, body = {}, options = {}) {
|
|
180
|
+
return this.request(this.path(vm, "release"), body, options);
|
|
181
|
+
}
|
|
182
|
+
path(vm, action) {
|
|
183
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(vm)) throw new TypeError("Invalid VM name");
|
|
184
|
+
return `/vms/${encodeURIComponent(vm)}${action ? `/${action}` : ""}`;
|
|
185
|
+
}
|
|
186
|
+
async request(path, body, options) {
|
|
187
|
+
options.signal?.throwIfAborted();
|
|
188
|
+
const timeoutMs = positive(options.timeoutMs ?? this.timeoutMs, "timeoutMs");
|
|
189
|
+
const controller = new AbortController();
|
|
190
|
+
const abort = () => controller.abort(options.signal?.reason);
|
|
191
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
192
|
+
const timer = setTimeout(() => controller.abort(new VmServiceError(`vm-service ${path} timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
193
|
+
try {
|
|
194
|
+
const response = await fetch(`${this.baseUrl}${path}`, {
|
|
195
|
+
method: body === void 0 ? "GET" : "POST",
|
|
196
|
+
headers: { ...body === void 0 ? {} : { "Content-Type": "application/json" }, ...this.environment ? { "X-VM-Environment-Fingerprint": this.environment.identity.fingerprint } : {} },
|
|
197
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
198
|
+
signal: controller.signal,
|
|
199
|
+
redirect: "error"
|
|
200
|
+
// Do not let a loopback service redirect to remote hosts.
|
|
201
|
+
});
|
|
202
|
+
const reader = response.body?.getReader();
|
|
203
|
+
const chunks = [];
|
|
204
|
+
let size = 0;
|
|
205
|
+
const bound = response.ok ? this.maxResponseBytes : Math.min(4096, this.maxResponseBytes);
|
|
206
|
+
let truncated = false;
|
|
207
|
+
if (reader) {
|
|
208
|
+
try {
|
|
209
|
+
for (; ; ) {
|
|
210
|
+
const { value, done } = await reader.read();
|
|
211
|
+
if (done) break;
|
|
212
|
+
const remaining = bound - size;
|
|
213
|
+
chunks.push(value.subarray(0, remaining));
|
|
214
|
+
size += Math.min(value.byteLength, remaining);
|
|
215
|
+
if (value.byteLength > remaining) {
|
|
216
|
+
truncated = true;
|
|
217
|
+
await reader.cancel();
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
} finally {
|
|
222
|
+
reader.releaseLock();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
226
|
+
if (!response.ok) throw new VmServiceError(`vm-service ${path}: HTTP ${response.status}: ${text}${truncated ? " [truncated]" : ""}`, response.status, text);
|
|
227
|
+
if (truncated) throw new VmServiceError(`vm-service ${path}: response exceeds ${bound} bytes`);
|
|
228
|
+
try {
|
|
229
|
+
return JSON.parse(text);
|
|
230
|
+
} catch (cause) {
|
|
231
|
+
throw new VmServiceError(`vm-service ${path}: invalid JSON response`, void 0, void 0, { cause });
|
|
232
|
+
}
|
|
233
|
+
} catch (cause) {
|
|
234
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
235
|
+
if (cause instanceof VmServiceError) throw cause;
|
|
236
|
+
throw new VmServiceError(`vm-service ${path}: request failed`, void 0, void 0, { cause });
|
|
237
|
+
} finally {
|
|
238
|
+
clearTimeout(timer);
|
|
239
|
+
options.signal?.removeEventListener("abort", abort);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
// src/registry.ts
|
|
245
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
246
|
+
import { link, lstat, mkdir, open, readFile, realpath, rename, unlink } from "node:fs/promises";
|
|
247
|
+
import { readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
|
|
248
|
+
import { homedir as homedir3 } from "node:os";
|
|
249
|
+
|
|
250
|
+
// src/config.ts
|
|
251
|
+
import { homedir as homedir2 } from "node:os";
|
|
252
|
+
import { isAbsolute as isAbsolute2, join as join2, normalize } from "node:path";
|
|
253
|
+
|
|
254
|
+
// src/environment.ts
|
|
255
|
+
import { accessSync, constants, lstatSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
256
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
257
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
258
|
+
import { homedir } from "node:os";
|
|
259
|
+
import { isIP as isIP2 } from "node:net";
|
|
260
|
+
var paths = ["imageRepository", "tartHome", "serviceStateDir", "imageStateDir", "relayStateDir", "vmctlPath", "tartPath"];
|
|
261
|
+
var mutable = ["tartHome", "serviceStateDir", "imageStateDir", "relayStateDir"];
|
|
262
|
+
function canonicalPath(value) {
|
|
263
|
+
if (typeof value !== "string" || !isAbsolute(value) || !value.trim() || /[\x00-\x1f\x7f\uD800-\uDFFF]/u.test(value)) throw new Error("Environment paths must be absolute and contain no control characters");
|
|
264
|
+
let ancestor = resolve(value);
|
|
265
|
+
const suffix = [];
|
|
266
|
+
for (; ; ) {
|
|
267
|
+
try {
|
|
268
|
+
return join(realpathSync(ancestor), ...suffix);
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (error.code !== "ENOENT") throw error;
|
|
271
|
+
try {
|
|
272
|
+
if (lstatSync(ancestor).isSymbolicLink()) throw new Error("Dangling environment path symlink");
|
|
273
|
+
} catch (entryError) {
|
|
274
|
+
if (entryError.code !== "ENOENT") throw entryError;
|
|
275
|
+
}
|
|
276
|
+
const parent = dirname(ancestor);
|
|
277
|
+
if (parent === ancestor) throw error;
|
|
278
|
+
suffix.unshift(relative(parent, ancestor));
|
|
279
|
+
ancestor = parent;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function overlaps(a, b) {
|
|
284
|
+
const below = (parent, child) => {
|
|
285
|
+
const r = relative(parent, child);
|
|
286
|
+
return r === "" || !r.startsWith("../") && r !== ".." && !isAbsolute(r);
|
|
287
|
+
};
|
|
288
|
+
return below(a, b) || below(b, a);
|
|
289
|
+
}
|
|
290
|
+
function endpoint(value) {
|
|
291
|
+
if (typeof value !== "string") throw new Error("vmServiceUrl must be a loopback HTTP origin with an explicit port");
|
|
292
|
+
const match = /^http:\/\/(localhost|127(?:\.\d{1,3}){3}|\[::1\]):([0-9]{1,5})\/?$/.exec(value);
|
|
293
|
+
if (!match || !["localhost", "[::1]"].includes(match[1]) && isIP2(match[1]) !== 4) throw new Error("vmServiceUrl must be a loopback HTTP origin with an explicit port");
|
|
294
|
+
const port = Number(match[2]);
|
|
295
|
+
if (port < 1 || port > 65535) throw new Error("Environment port must be between 1 and 65535");
|
|
296
|
+
return `http://${match[1]}:${port}`;
|
|
297
|
+
}
|
|
298
|
+
function loadEnvironment(path, env = process.env, home = env.HOME ?? homedir()) {
|
|
299
|
+
const canonical = canonicalPath(resolve(path));
|
|
300
|
+
const info = statSync(canonical);
|
|
301
|
+
if (!info.isFile() || info.size > 65536) throw new Error("Environment profile must be a regular JSON file under 64 KiB");
|
|
302
|
+
const bytes = readFileSync(canonical);
|
|
303
|
+
if (bytes.length > 65536) throw new Error("Environment profile exceeds 64 KiB");
|
|
304
|
+
const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
305
|
+
const raw = JSON.parse(text);
|
|
306
|
+
let depth = 0;
|
|
307
|
+
const seen = /* @__PURE__ */ new Set();
|
|
308
|
+
for (let i = 0; i < text.length; i++) {
|
|
309
|
+
if (text[i] === '"') {
|
|
310
|
+
const start = i++;
|
|
311
|
+
for (; i < text.length && text[i] !== '"'; i++) if (text[i] === "\\") i++;
|
|
312
|
+
let next = i + 1;
|
|
313
|
+
while (/\s/.test(text[next] ?? "") && next < text.length) next++;
|
|
314
|
+
if (depth === 1 && text[next] === ":") {
|
|
315
|
+
const key = JSON.parse(text.slice(start, i + 1));
|
|
316
|
+
if (seen.has(key)) throw new Error(`Duplicate environment profile key: ${key}`);
|
|
317
|
+
seen.add(key);
|
|
318
|
+
}
|
|
319
|
+
} else if (text[i] === "{" || text[i] === "[") depth++;
|
|
320
|
+
else if (text[i] === "}" || text[i] === "]") depth--;
|
|
321
|
+
}
|
|
322
|
+
const fields = ["schemaVersion", "id", "vmServiceUrl", ...paths].sort();
|
|
323
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw) || JSON.stringify(Object.keys(raw).sort()) !== JSON.stringify(fields)) throw new Error("Environment profile has missing or unknown fields");
|
|
324
|
+
const p = raw;
|
|
325
|
+
if (p.schemaVersion !== 1 || typeof p.id !== "string" || !/^[a-z0-9][a-z0-9-]{0,47}$/.test(p.id)) throw new Error("Invalid environment schemaVersion or id");
|
|
326
|
+
const profile = { schemaVersion: 1, id: p.id, vmServiceUrl: endpoint(p.vmServiceUrl) };
|
|
327
|
+
for (const key of paths) profile[key] = canonicalPath(p[key]);
|
|
328
|
+
if (!statSync(profile.imageRepository).isDirectory() || !statSync(join(profile.imageRepository, "images")).isDirectory()) throw new Error("Selected imageRepository must contain images/");
|
|
329
|
+
for (const key of ["vmctlPath", "tartPath"]) {
|
|
330
|
+
if (!statSync(profile[key]).isFile()) throw new Error(`${key} must be a regular executable file`);
|
|
331
|
+
accessSync(profile[key], constants.X_OK);
|
|
332
|
+
}
|
|
333
|
+
const state = env.XDG_STATE_HOME ? canonicalPath(env.XDG_STATE_HOME) : join(canonicalPath(home), ".local/state");
|
|
334
|
+
const names = ["vm-service", "pilot-images", "mcp-relay", "mcp-vm-relay"];
|
|
335
|
+
const defaults = [join(canonicalPath(home), ".tart"), ...names.map((n) => join(state, n)), ...names.map((n) => join(canonicalPath(home), ".local/state", n))].map(canonicalPath);
|
|
336
|
+
for (const key of mutable) {
|
|
337
|
+
const value = profile[key];
|
|
338
|
+
try {
|
|
339
|
+
if (!statSync(value).isDirectory()) throw new Error(`${key} must be a directory`);
|
|
340
|
+
} catch (error) {
|
|
341
|
+
if (error.code !== "ENOENT") throw error;
|
|
342
|
+
}
|
|
343
|
+
if (overlaps(value, profile.imageRepository) || defaults.some((root) => overlaps(value, root))) throw new Error(`${key} overlaps the repository or a legacy default store/state root`);
|
|
344
|
+
for (const other of mutable) if (key !== other && overlaps(value, profile[other])) throw new Error("Environment mutable roots must be disjoint");
|
|
345
|
+
}
|
|
346
|
+
const ordered = Object.fromEntries(Object.keys(profile).sort().map((k) => [k, profile[k]]));
|
|
347
|
+
const fingerprint = createHash2("sha256").update(JSON.stringify(ordered), "utf8").digest("hex");
|
|
348
|
+
const identity = Object.freeze({
|
|
349
|
+
id: profile.id,
|
|
350
|
+
fingerprint,
|
|
351
|
+
vmServiceUrl: profile.vmServiceUrl,
|
|
352
|
+
imageRepository: profile.imageRepository,
|
|
353
|
+
tartHome: profile.tartHome,
|
|
354
|
+
serviceStateDir: profile.serviceStateDir,
|
|
355
|
+
imageStateDir: profile.imageStateDir,
|
|
356
|
+
relayStateDir: profile.relayStateDir
|
|
357
|
+
});
|
|
358
|
+
return Object.freeze({ path: canonical, profile: Object.freeze(profile), identity });
|
|
359
|
+
}
|
|
360
|
+
function selectedEnvironment(env = process.env, home) {
|
|
361
|
+
if (env.VM_ENVIRONMENT_FILE === void 0) return void 0;
|
|
362
|
+
if (!env.VM_ENVIRONMENT_FILE.trim()) throw new Error("VM_ENVIRONMENT_FILE must not be blank");
|
|
363
|
+
return loadEnvironment(env.VM_ENVIRONMENT_FILE, env, home);
|
|
364
|
+
}
|
|
365
|
+
function environmentVariables(selected) {
|
|
366
|
+
const p = selected.profile;
|
|
367
|
+
const url = new URL(p.vmServiceUrl);
|
|
368
|
+
return {
|
|
369
|
+
VM_ENVIRONMENT_FILE: selected.path,
|
|
370
|
+
VM_ENVIRONMENT_FINGERPRINT: selected.identity.fingerprint,
|
|
371
|
+
PILOT_REPO: p.imageRepository,
|
|
372
|
+
TART_HOME: p.tartHome,
|
|
373
|
+
VM_SERVICE_STATE: p.serviceStateDir,
|
|
374
|
+
PILOT_IMAGES_STATE_DIR: p.imageStateDir,
|
|
375
|
+
VM_RELAY_STATE_DIR: p.relayStateDir,
|
|
376
|
+
VM_RELAY_URL: p.vmServiceUrl,
|
|
377
|
+
VM_SERVICE_HOST: url.hostname.replace(/^\[|\]$/g, ""),
|
|
378
|
+
VM_SERVICE_PORT: String(Number(p.vmServiceUrl.match(/:([0-9]+)$/)[1])),
|
|
379
|
+
VMCTL: p.vmctlPath,
|
|
380
|
+
TART: p.tartPath
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
function matchesEnvironment(actual, selected) {
|
|
384
|
+
if (!actual || typeof actual !== "object" || Array.isArray(actual)) return false;
|
|
385
|
+
const identity = actual;
|
|
386
|
+
return Object.keys(identity).length === Object.keys(selected.identity).length && Object.entries(selected.identity).every(([key, value]) => identity[key] === value);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// src/config.ts
|
|
390
|
+
function nonblank(value, label) {
|
|
391
|
+
if (!value.trim() || value.includes("\0")) throw new TypeError(`${label} must be nonblank text without NUL characters`);
|
|
392
|
+
return value;
|
|
393
|
+
}
|
|
394
|
+
function absolute(value, label) {
|
|
395
|
+
nonblank(value, label);
|
|
396
|
+
if (!isAbsolute2(value)) throw new TypeError(`${label} must be an absolute path`);
|
|
397
|
+
return normalize(value);
|
|
398
|
+
}
|
|
399
|
+
function relayStateRoot(options = {}) {
|
|
400
|
+
const env = options.env ?? process.env;
|
|
401
|
+
const selected = selectedEnvironment(env, options.home);
|
|
402
|
+
if (selected) return selected.profile.relayStateDir;
|
|
403
|
+
if (env.MCP_RELAY_STATE_DIR !== void 0) return absolute(env.MCP_RELAY_STATE_DIR, "MCP_RELAY_STATE_DIR");
|
|
404
|
+
if (env.XDG_STATE_HOME !== void 0) return join2(absolute(env.XDG_STATE_HOME, "XDG_STATE_HOME"), "mcp-relay");
|
|
405
|
+
return join2(absolute(options.home ?? env.HOME ?? homedir2(), "home"), ".local", "state", "mcp-relay");
|
|
406
|
+
}
|
|
407
|
+
function pythonExecutable(env = process.env) {
|
|
408
|
+
return nonblank(env.MCP_RELAY_PYTHON ?? "python3", "MCP_RELAY_PYTHON");
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// src/registry.ts
|
|
412
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
413
|
+
import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
|
|
414
|
+
var RegistryError = class extends Error {
|
|
415
|
+
constructor(message, options) {
|
|
416
|
+
super(message, options);
|
|
417
|
+
this.name = "RegistryError";
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
var columns = ["machine", "os", "taskName", "agent", "project", "startDate"];
|
|
421
|
+
function cells(row) {
|
|
422
|
+
return columns.map((key) => {
|
|
423
|
+
const value = row[key];
|
|
424
|
+
if (typeof value !== "string" || !value.trim() || value !== value.trim() || /[|\r\n\u0000-\u001f\u007f]/.test(value)) {
|
|
425
|
+
throw new RegistryError(`Registry ${key} must be nonempty trimmed text without pipes or control characters`);
|
|
426
|
+
}
|
|
427
|
+
return value;
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
function parse(line) {
|
|
431
|
+
const text = line.trim();
|
|
432
|
+
if (!text.startsWith("|") || !text.endsWith("|")) return void 0;
|
|
433
|
+
return text.slice(1, -1).split("|").map((cell) => cell.trim());
|
|
434
|
+
}
|
|
435
|
+
function linesOf(text) {
|
|
436
|
+
const lines = [];
|
|
437
|
+
const pattern = /[^\r\n]*(?:\r\n|\n|\r|$)/g;
|
|
438
|
+
for (const match of text.matchAll(pattern)) {
|
|
439
|
+
if (!match[0]) continue;
|
|
440
|
+
lines.push({ text: match[0].replace(/[\r\n]+$/, ""), start: match.index, end: match.index + match[0].length });
|
|
441
|
+
}
|
|
442
|
+
return lines;
|
|
443
|
+
}
|
|
444
|
+
function table(text) {
|
|
445
|
+
const lines = linesOf(text);
|
|
446
|
+
const sections = lines.map((line, index) => /^## Using VMs\s*$/.test(line.text) ? index : -1).filter((index) => index >= 0);
|
|
447
|
+
if (sections.length !== 1) throw new RegistryError("Expected exactly one '## Using VMs' section");
|
|
448
|
+
const begin = sections[0];
|
|
449
|
+
let end = lines.findIndex((line, index) => index > begin && /^#{1,2} /.test(line.text));
|
|
450
|
+
if (end < 0) end = lines.length;
|
|
451
|
+
const headers = lines.map((line, index) => index > begin && index < end && JSON.stringify(parse(line.text)) === JSON.stringify(["Machine", "OS", "Task Name", "Agent", "Project", "Start Date"]) ? index : -1).filter((index) => index >= 0);
|
|
452
|
+
if (headers.length !== 1) throw new RegistryError("Expected exactly one VM task registry table");
|
|
453
|
+
const header = headers[0];
|
|
454
|
+
const separator = lines[header + 1];
|
|
455
|
+
const separatorCells = separator && parse(separator.text);
|
|
456
|
+
if (!separatorCells || separatorCells.length !== 6 || !separatorCells.every((cell) => /^:?-{2,}:?$/.test(cell))) {
|
|
457
|
+
throw new RegistryError("Malformed VM task registry separator");
|
|
458
|
+
}
|
|
459
|
+
const rows = [];
|
|
460
|
+
for (let i = header + 2; i < end && lines[i].text.trim().startsWith("|"); i++) {
|
|
461
|
+
const line = lines[i];
|
|
462
|
+
if (parse(line.text)?.length !== 6) throw new RegistryError("Malformed VM task registry row");
|
|
463
|
+
rows.push(line);
|
|
464
|
+
}
|
|
465
|
+
const last = rows.at(-1) ?? separator;
|
|
466
|
+
return { rows, insertion: last.end, newline: text.includes("\r\n") ? "\r\n" : "\n" };
|
|
467
|
+
}
|
|
468
|
+
function validateRegistryText(text) {
|
|
469
|
+
table(text);
|
|
470
|
+
}
|
|
471
|
+
function resolveRegistry(options = {}) {
|
|
472
|
+
const env = options.env ?? process.env;
|
|
473
|
+
const root = options.managedRoot ?? selectedEnvironment(env, options.home)?.profile.relayStateDir;
|
|
474
|
+
if (root !== void 0 && options.path === void 0) return { path: join3(absolute(root, "managed registry root"), "registry.md"), managed: true };
|
|
475
|
+
const explicit = options.path ?? env.MCP_RELAY_REGISTRY;
|
|
476
|
+
const validate = (path) => {
|
|
477
|
+
if (!statSync2(path).isFile()) throw new RegistryError("Registry target must be a regular file");
|
|
478
|
+
table(readFileSync2(path, "utf8"));
|
|
479
|
+
};
|
|
480
|
+
if (explicit !== void 0) {
|
|
481
|
+
const path = options.path !== void 0 ? resolve3(nonblank(explicit, "Registry path")) : absolute(explicit, "MCP_RELAY_REGISTRY");
|
|
482
|
+
validate(path);
|
|
483
|
+
return { path, managed: false };
|
|
484
|
+
}
|
|
485
|
+
const legacy = join3(options.home ?? env.HOME ?? homedir3(), "AGENTS.md");
|
|
486
|
+
try {
|
|
487
|
+
validate(legacy);
|
|
488
|
+
return { path: resolve3(legacy), managed: false };
|
|
489
|
+
} catch (error) {
|
|
490
|
+
if (!(error instanceof RegistryError) && !errno(error, "ENOENT") && !errno(error, "ENOTDIR")) throw error;
|
|
491
|
+
}
|
|
492
|
+
return { path: join3(relayStateRoot(options), "registry.md"), managed: true };
|
|
493
|
+
}
|
|
494
|
+
var REGISTRY_LOCK_SUFFIX = ".mcp-vm-relay.lock";
|
|
495
|
+
var MANAGED_REGISTRY = `# mcp-relay task registry
|
|
496
|
+
|
|
497
|
+
## Using VMs
|
|
498
|
+
|
|
499
|
+
| Machine | OS | Task Name | Agent | Project | Start Date |
|
|
500
|
+
| ------- | -- | --------- | ----- | ------- | ---------- |
|
|
501
|
+
`;
|
|
502
|
+
function errno(error, code) {
|
|
503
|
+
return error instanceof Error && "code" in error && error.code === code;
|
|
504
|
+
}
|
|
505
|
+
function bounded(value, label) {
|
|
506
|
+
if (!Number.isSafeInteger(value) || value <= 0 || value > 2147483647) throw new TypeError(`${label} must be a positive bounded integer`);
|
|
507
|
+
return value;
|
|
508
|
+
}
|
|
509
|
+
var FLOCK_HELPER = `
|
|
510
|
+
import fcntl, os, select, sys, time
|
|
511
|
+
fd = os.open(sys.argv[1], os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
512
|
+
deadline = time.monotonic() + float(sys.argv[2])
|
|
513
|
+
while True:
|
|
514
|
+
try:
|
|
515
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
516
|
+
break
|
|
517
|
+
except BlockingIOError:
|
|
518
|
+
remaining = deadline - time.monotonic()
|
|
519
|
+
if remaining <= 0:
|
|
520
|
+
sys.stderr.write("registry lock timeout")
|
|
521
|
+
sys.exit(2)
|
|
522
|
+
readable, _, _ = select.select([sys.stdin], [], [], min(float(sys.argv[3]), remaining))
|
|
523
|
+
if readable:
|
|
524
|
+
sys.exit(3)
|
|
525
|
+
print("locked", flush=True)
|
|
526
|
+
sys.stdin.buffer.read()
|
|
527
|
+
os.close(fd)
|
|
528
|
+
`;
|
|
529
|
+
var Registry = class {
|
|
530
|
+
path;
|
|
531
|
+
managed;
|
|
532
|
+
lockTimeoutMs;
|
|
533
|
+
lockRetryMs;
|
|
534
|
+
pythonExecutable;
|
|
535
|
+
constructor(options = {}) {
|
|
536
|
+
if (typeof options === "string") options = { path: options };
|
|
537
|
+
const registry = resolveRegistry(options);
|
|
538
|
+
this.path = registry.path;
|
|
539
|
+
this.managed = registry.managed;
|
|
540
|
+
this.lockTimeoutMs = bounded(options.lockTimeoutMs ?? 1e4, "lockTimeoutMs");
|
|
541
|
+
this.lockRetryMs = bounded(options.lockRetryMs ?? 25, "lockRetryMs");
|
|
542
|
+
this.pythonExecutable = options.pythonExecutable === void 0 ? pythonExecutable(options.env) : nonblank(options.pythonExecutable, "pythonExecutable");
|
|
543
|
+
}
|
|
544
|
+
/** Returns false when this exact row is already registered (idempotent). */
|
|
545
|
+
async add(row, options = {}) {
|
|
546
|
+
const desired = cells(row);
|
|
547
|
+
return this.update((text) => {
|
|
548
|
+
const registry = table(text);
|
|
549
|
+
const matching = registry.rows.filter((line) => parse(line.text)[2] === row.taskName);
|
|
550
|
+
if (matching.length > 0) {
|
|
551
|
+
if (matching.length === 1 && JSON.stringify(parse(matching[0].text)) === JSON.stringify(desired)) return text;
|
|
552
|
+
throw new RegistryError(`Task '${row.taskName}' is already registered by a different owner or duplicated`);
|
|
553
|
+
}
|
|
554
|
+
const prefix = registry.insertion > 0 && !/[\r\n]/.test(text[registry.insertion - 1]) ? registry.newline : "";
|
|
555
|
+
const added = `${prefix}| ${desired.join(" | ")} |${registry.newline}`;
|
|
556
|
+
return text.slice(0, registry.insertion) + added + text.slice(registry.insertion);
|
|
557
|
+
}, options.signal);
|
|
558
|
+
}
|
|
559
|
+
/** Returns false when absent. Never removes a row whose ownership differs. */
|
|
560
|
+
async remove(row, options = {}) {
|
|
561
|
+
const desired = cells(row);
|
|
562
|
+
return this.update((text) => {
|
|
563
|
+
const registry = table(text);
|
|
564
|
+
const matching = registry.rows.filter((line2) => parse(line2.text)[2] === row.taskName);
|
|
565
|
+
if (matching.length === 0) return text;
|
|
566
|
+
if (matching.length !== 1 || JSON.stringify(parse(matching[0].text)) !== JSON.stringify(desired)) {
|
|
567
|
+
throw new RegistryError(`Refusing to remove task '${row.taskName}': ownership does not match`);
|
|
568
|
+
}
|
|
569
|
+
const line = matching[0];
|
|
570
|
+
return text.slice(0, line.start) + text.slice(line.end);
|
|
571
|
+
}, options.signal);
|
|
572
|
+
}
|
|
573
|
+
async update(transform, signal) {
|
|
574
|
+
signal?.throwIfAborted();
|
|
575
|
+
if (this.managed) {
|
|
576
|
+
await mkdir(dirname2(this.path), { recursive: true, mode: 448 });
|
|
577
|
+
const parent = await lstat(dirname2(this.path));
|
|
578
|
+
if (!parent.isDirectory()) throw new RegistryError("Managed registry parent must be a directory, not a symlink");
|
|
579
|
+
if ((parent.mode & 63) !== 0) throw new RegistryError("Managed registry parent must be private (0700); choose a private state directory. Existing directory permissions are not changed automatically.");
|
|
580
|
+
}
|
|
581
|
+
const target = this.managed ? join3(await realpath(dirname2(this.path)), "registry.md") : await realpath(this.path);
|
|
582
|
+
const lock = await this.lock(`${target}${REGISTRY_LOCK_SUFFIX}`, signal);
|
|
583
|
+
const token = randomUUID2();
|
|
584
|
+
let temporary;
|
|
585
|
+
try {
|
|
586
|
+
signal?.throwIfAborted();
|
|
587
|
+
if (this.managed) await this.initialize(target, lock.check);
|
|
588
|
+
const before = await lstat(target);
|
|
589
|
+
if (!before.isFile()) throw new RegistryError("Registry target must be a regular file");
|
|
590
|
+
const original = await readFile(target, "utf8");
|
|
591
|
+
const updated = transform(original);
|
|
592
|
+
if (original === updated) return false;
|
|
593
|
+
temporary = join3(dirname2(target), `.${target.split("/").at(-1)}.${token}.tmp`);
|
|
594
|
+
const handle = await open(temporary, "wx", before.mode & 511);
|
|
595
|
+
try {
|
|
596
|
+
await handle.chmod(before.mode & 511);
|
|
597
|
+
await handle.writeFile(updated, "utf8");
|
|
598
|
+
await handle.sync();
|
|
599
|
+
} finally {
|
|
600
|
+
await handle.close();
|
|
601
|
+
}
|
|
602
|
+
signal?.throwIfAborted();
|
|
603
|
+
const current = await lstat(target);
|
|
604
|
+
if (current.ino !== before.ino || current.mtimeMs !== before.mtimeMs || await readFile(target, "utf8") !== original) {
|
|
605
|
+
throw new RegistryError("Registry changed outside its lock; retry without overwriting those changes");
|
|
606
|
+
}
|
|
607
|
+
lock.check();
|
|
608
|
+
await rename(temporary, target);
|
|
609
|
+
temporary = void 0;
|
|
610
|
+
const dir = await open(dirname2(target), "r");
|
|
611
|
+
try {
|
|
612
|
+
await dir.sync();
|
|
613
|
+
} finally {
|
|
614
|
+
await dir.close();
|
|
615
|
+
}
|
|
616
|
+
return true;
|
|
617
|
+
} finally {
|
|
618
|
+
try {
|
|
619
|
+
if (temporary) await unlink(temporary).catch((error) => {
|
|
620
|
+
if (!errno(error, "ENOENT")) throw error;
|
|
621
|
+
});
|
|
622
|
+
} finally {
|
|
623
|
+
await lock.release();
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
/** Publish a complete initial table without replacing any existing path.
|
|
628
|
+
* Called only under the same cooperative lock used by all row updates. */
|
|
629
|
+
async initialize(target, check) {
|
|
630
|
+
try {
|
|
631
|
+
await lstat(target);
|
|
632
|
+
return;
|
|
633
|
+
} catch (error) {
|
|
634
|
+
if (!errno(error, "ENOENT")) throw error;
|
|
635
|
+
}
|
|
636
|
+
const temporary = join3(dirname2(target), `.registry.${randomUUID2()}.tmp`);
|
|
637
|
+
const handle = await open(temporary, "wx", 384);
|
|
638
|
+
try {
|
|
639
|
+
try {
|
|
640
|
+
await handle.chmod(384);
|
|
641
|
+
await handle.writeFile(MANAGED_REGISTRY, "utf8");
|
|
642
|
+
await handle.sync();
|
|
643
|
+
} finally {
|
|
644
|
+
await handle.close();
|
|
645
|
+
}
|
|
646
|
+
check();
|
|
647
|
+
try {
|
|
648
|
+
await link(temporary, target);
|
|
649
|
+
} catch (error) {
|
|
650
|
+
if (!errno(error, "EEXIST")) throw error;
|
|
651
|
+
}
|
|
652
|
+
const dir = await open(dirname2(target), "r");
|
|
653
|
+
try {
|
|
654
|
+
await dir.sync();
|
|
655
|
+
} finally {
|
|
656
|
+
await dir.close();
|
|
657
|
+
}
|
|
658
|
+
} finally {
|
|
659
|
+
await unlink(temporary);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
async lock(path, signal) {
|
|
663
|
+
signal?.throwIfAborted();
|
|
664
|
+
const child = spawn2(this.pythonExecutable, ["-u", "-c", FLOCK_HELPER, path, String(this.lockTimeoutMs / 1e3), String(this.lockRetryMs / 1e3)], { stdio: ["pipe", "pipe", "pipe"] });
|
|
665
|
+
let closed = false;
|
|
666
|
+
const exit = new Promise((resolveExit) => child.once("close", () => {
|
|
667
|
+
closed = true;
|
|
668
|
+
resolveExit();
|
|
669
|
+
}));
|
|
670
|
+
child.stdin.on("error", () => {
|
|
671
|
+
});
|
|
672
|
+
let failure;
|
|
673
|
+
let acquired = false;
|
|
674
|
+
let stderr = "";
|
|
675
|
+
child.stderr.on("data", (data) => {
|
|
676
|
+
stderr = (stderr + String(data)).slice(0, 4096);
|
|
677
|
+
});
|
|
678
|
+
const abort = () => {
|
|
679
|
+
failure = signal?.reason;
|
|
680
|
+
child.kill("SIGTERM");
|
|
681
|
+
};
|
|
682
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
683
|
+
const timer = setTimeout(() => {
|
|
684
|
+
failure = new RegistryError(`Timed out waiting for registry lock ${path}`);
|
|
685
|
+
child.kill("SIGTERM");
|
|
686
|
+
}, this.lockTimeoutMs + 1e3);
|
|
687
|
+
try {
|
|
688
|
+
await new Promise((resolveReady, rejectReady) => {
|
|
689
|
+
let output = "";
|
|
690
|
+
child.stdout.on("data", (data) => {
|
|
691
|
+
output += String(data);
|
|
692
|
+
if (output === "locked\n") {
|
|
693
|
+
acquired = true;
|
|
694
|
+
resolveReady();
|
|
695
|
+
} else if (output.length > 100) {
|
|
696
|
+
failure = new RegistryError("Invalid registry lock helper response");
|
|
697
|
+
child.kill("SIGTERM");
|
|
698
|
+
}
|
|
699
|
+
});
|
|
700
|
+
child.once("error", (error) => {
|
|
701
|
+
failure = new RegistryError("Cannot start Python flock helper", { cause: error });
|
|
702
|
+
});
|
|
703
|
+
child.once("close", () => {
|
|
704
|
+
if (!acquired) rejectReady(failure ?? new RegistryError(`Registry lock helper exited: ${stderr || "no ready response"}`));
|
|
705
|
+
});
|
|
706
|
+
});
|
|
707
|
+
} catch (error) {
|
|
708
|
+
child.stdin.end();
|
|
709
|
+
await exit;
|
|
710
|
+
throw error;
|
|
711
|
+
} finally {
|
|
712
|
+
clearTimeout(timer);
|
|
713
|
+
signal?.removeEventListener("abort", abort);
|
|
714
|
+
}
|
|
715
|
+
const check = () => {
|
|
716
|
+
if (closed || child.exitCode !== null || child.signalCode !== null) throw new RegistryError("Registry lock helper died during update; lock ownership was lost");
|
|
717
|
+
};
|
|
718
|
+
return { check, release: async () => {
|
|
719
|
+
check();
|
|
720
|
+
child.stdin.end();
|
|
721
|
+
await exit;
|
|
722
|
+
} };
|
|
723
|
+
}
|
|
724
|
+
};
|
|
725
|
+
|
|
726
|
+
// src/doctor.ts
|
|
727
|
+
async function installationReport(options = {}) {
|
|
728
|
+
const checks = [];
|
|
729
|
+
const check = async (name, fn) => {
|
|
730
|
+
try {
|
|
731
|
+
checks.push({ name, ok: true, detail: await fn() });
|
|
732
|
+
} catch (e) {
|
|
733
|
+
checks.push({ name, ok: false, detail: String(e) });
|
|
734
|
+
}
|
|
735
|
+
};
|
|
736
|
+
const environment = selectedEnvironment();
|
|
737
|
+
const run = options.run ?? command;
|
|
738
|
+
const assets = options.assetsDir ?? fileURLToPath(new URL("../dist/", import.meta.url));
|
|
739
|
+
await check("node", async () => {
|
|
740
|
+
if (Number(process.versions.node.split(".")[0]) < 22) throw Error("Install Node.js 22 or newer.");
|
|
741
|
+
return process.versions.node;
|
|
742
|
+
});
|
|
743
|
+
await check("host", async () => {
|
|
744
|
+
if (process.platform !== "darwin" || process.arch !== "arm64") throw Error("The supported local Tart/vm-service backend requires an Apple-silicon Mac. Ubuntu is a guest, not a substitute host.");
|
|
745
|
+
return `${process.platform}/${process.arch}`;
|
|
746
|
+
});
|
|
747
|
+
await check("python", async () => {
|
|
748
|
+
const r = await run([pythonExecutable(), "-c", "import fcntl, sys; print(sys.version.split()[0])"], { timeoutMs: 5e3 });
|
|
749
|
+
if (r.code !== 0) throw Error("Install Python 3 with fcntl, or set MCP_RELAY_PYTHON to its executable. " + r.stderr);
|
|
750
|
+
return r.stdout.trim();
|
|
751
|
+
});
|
|
752
|
+
await check("runtime-bundles", async () => {
|
|
753
|
+
const integrity = JSON.parse(await readFile2(join4(assets, "integrity.json"), "utf8"));
|
|
754
|
+
for (const name of ["server.mjs", "receiver.mjs", "doctor.mjs"]) {
|
|
755
|
+
const b = await readFile2(join4(assets, name));
|
|
756
|
+
if (hash(b) !== integrity[name]) throw Error(`Invalid/missing shipped ${name}; reinstall the package.`);
|
|
757
|
+
}
|
|
758
|
+
return "Host extension, guest receiver and doctor hashes verified";
|
|
759
|
+
});
|
|
760
|
+
await check("registry", async () => {
|
|
761
|
+
const registry = options.registry ?? new Registry(environment ? { managedRoot: environment.profile.relayStateDir } : {});
|
|
762
|
+
try {
|
|
763
|
+
await access(registry.path);
|
|
764
|
+
validateRegistryText(await readFile2(registry.path, "utf8"));
|
|
765
|
+
return `Existing registry: ${registry.path}`;
|
|
766
|
+
} catch (e) {
|
|
767
|
+
if (e.code !== "ENOENT") throw e;
|
|
768
|
+
if (process.env.MCP_RELAY_REGISTRY) throw Error("MCP_RELAY_REGISTRY must point to an existing Using VMs registry table.");
|
|
769
|
+
return `Managed registry will be created on first acquisition: ${registry.path}`;
|
|
770
|
+
}
|
|
771
|
+
});
|
|
772
|
+
await check("tart", async () => {
|
|
773
|
+
const r = await run([environment?.profile.tartPath ?? "tart", "list", "--format", "json"], { timeoutMs: 1e4, ...environment ? { env: { ...process.env, ...environmentVariables(environment) } } : {} });
|
|
774
|
+
if (r.code !== 0 || !Array.isArray(JSON.parse(r.stdout))) throw Error("Install Tart and ensure tart list --format json works; required for independent destruction verification.");
|
|
775
|
+
return "Read-only local inventory available";
|
|
776
|
+
});
|
|
777
|
+
await check("vm-service", async () => {
|
|
778
|
+
const vm = options.vm ?? new VmService({ baseUrl: environment?.profile.vmServiceUrl ?? process.env.MCP_RELAY_URL, environment });
|
|
779
|
+
const health = await vm.health({ timeoutMs: 5e3 });
|
|
780
|
+
if (!health.ok) throw Error("Service health check failed");
|
|
781
|
+
if (environment && !matchesEnvironment(health.environment, environment)) throw Error("VM service environment identity mismatch");
|
|
782
|
+
const images = await vm.images({ timeoutMs: 5e3 });
|
|
783
|
+
await vm.list({ timeoutMs: 5e3 });
|
|
784
|
+
const available = Object.entries(images.images).filter(([, v]) => v.base_available).map(([k]) => k);
|
|
785
|
+
if (!available.length) throw Error("vm-service is running but has no available golden images. Provision a supported image in the backend.");
|
|
786
|
+
return `HTTP API reachable; available images: ${available.join(", ")}. This inventory does not prove guest readiness. Use relay probe scope=guest for executable checks; capture and browser behavior require separate checks. Staging alone is not readiness.`;
|
|
787
|
+
});
|
|
788
|
+
return { formatVersion: 1, ready: checks.every((c) => c.ok), environment: environment?.identity, stateDirectory: environment?.profile.relayStateDir ?? relayStateRoot(), checks, note: "Read-only host/API prerequisite check. No VM acquired, input sent, screenshot captured or permissions changed. Claude Code (or another MCP client) must be installed separately." };
|
|
789
|
+
}
|
|
790
|
+
if (process.argv[1] && pathToFileURL(realpathSync2(process.argv[1])).href === import.meta.url) {
|
|
791
|
+
try {
|
|
792
|
+
const r = await installationReport();
|
|
793
|
+
console.log(JSON.stringify(r, null, 2));
|
|
794
|
+
process.exitCode = r.ready ? 0 : 1;
|
|
795
|
+
} catch (e) {
|
|
796
|
+
console.log(JSON.stringify({ ready: false, error: String(e), hint: "Check MCP_RELAY_* configuration and installation paths." }, null, 2));
|
|
797
|
+
process.exitCode = 1;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
export {
|
|
801
|
+
installationReport
|
|
802
|
+
};
|