@wezzard/mcp-relay 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/receiver.mjs CHANGED
@@ -3,7 +3,7 @@ import { createRequire as __createRequire } from 'node:module'; const require =
3
3
  // src/guest/receiver.ts
4
4
  import { spawn, execFile } from "node:child_process";
5
5
  import { createHash as createHash2, randomUUID } from "node:crypto";
6
- import { mkdir as mkdir3, open, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2, realpath } from "node:fs/promises";
6
+ import { access, constants, mkdir as mkdir3, open, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2, realpath } from "node:fs/promises";
7
7
  import { dirname as dirname2, isAbsolute, join as join3, resolve } from "node:path";
8
8
  import { pathToFileURL } from "node:url";
9
9
 
@@ -830,7 +830,7 @@ function describe(value) {
830
830
  // src/guest/image-evidence.ts
831
831
  var safeId = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,159}$/.test(value);
832
832
  function afterRequested(request) {
833
- return !(request?.kind === "exec" && request.diagnostic === true) && request?.capture !== false && !["first", "member"].includes(request?.snapshots?.group?.phase ?? "");
833
+ return request?.diagnostic !== true && request?.capture !== false && !["first", "member"].includes(request?.snapshots?.group?.phase ?? "");
834
834
  }
835
835
  function validateImageEvidence(value, request, authoritativeSnapshots) {
836
836
  const fail = () => {
@@ -901,10 +901,9 @@ async function optionalJson(path) {
901
901
  function validate(request) {
902
902
  if (!safeId(request.executionId) || !safeId(request.sessionId) || !safeId(request.attemptId)) throw new Error("safe executionId, sessionId and attemptId are required");
903
903
  if (typeof request.because !== "string" || !request.because.trim() || request.because.length > 16384) throw new Error("nonblank because is required (maximum 16384 characters)");
904
- if (!["exec", "script", "code"].includes(request.kind)) throw new Error("kind must be exec, script or code");
905
904
  if (request.cwd !== void 0 && (!text(request.cwd) || !isAbsolute(request.cwd))) throw new Error("cwd must be an absolute path");
906
905
  if (request.timeoutMs !== void 0 && (!Number.isInteger(request.timeoutMs) || request.timeoutMs < 1 || request.timeoutMs > MAX_TIMEOUT_MS)) throw new Error("timeoutMs must be an integer from 1 to 3600000");
907
- if (request.diagnostic !== void 0 && (typeof request.diagnostic !== "boolean" || request.kind !== "exec")) throw new Error("diagnostic is allowed only for exec and must be boolean");
906
+ if (request.diagnostic !== void 0 && (typeof request.diagnostic !== "boolean" || request.language !== "shell")) throw new Error("diagnostic is allowed only for a shell script and must be boolean");
908
907
  if (request.step !== void 0 && (!request.step || !safeId(request.step.id) || !text(request.step.title) || request.step.expected !== void 0 && typeof request.step.expected !== "string" || request.step.inputMode !== void 0 && !["ordinary", "accessibility"].includes(request.step.inputMode))) throw new Error("invalid step metadata");
909
908
  const snapshots = request.snapshots;
910
909
  if (!snapshots || typeof snapshots !== "object" || Array.isArray(snapshots)) throw new Error("snapshots are required; no implicit interval");
@@ -916,11 +915,12 @@ function validate(request) {
916
915
  if (group.afterIntervalMs !== void 0 && !interval(group.afterIntervalMs)) throw new Error("invalid group afterIntervalMs");
917
916
  if (group.phase === "last" && !interval(group.afterIntervalMs ?? snapshots.afterIntervalMs)) throw new Error("last group member requires afterIntervalMs");
918
917
  } else if (!interval(snapshots.afterIntervalMs)) throw new Error("afterIntervalMs is required; no default");
919
- if (request.kind !== "code" && (!Array.isArray(request.argv) || request.argv.length === 0 || request.argv.length > 256 || !request.argv.every((arg, index) => typeof arg === "string" && !arg.includes("\0") && (index > 0 || arg.length > 0)))) throw new Error("argv must be a nonempty string vector without NULs (maximum 256 entries)");
920
- if (request.kind !== "exec" && !["javascript", "typescript", "python"].includes(request.language ?? "")) throw new Error("script/code language is required");
921
- if (request.kind === "code" && (typeof request.code !== "string" || !/^[a-f0-9]{64}$/.test(request.codeSha256 ?? ""))) throw new Error("code and its SHA-256 are required");
918
+ if (!["shell", "javascript", "typescript", "python"].includes(request.language ?? "")) throw new Error("language must be shell, javascript, typescript or python");
919
+ const inline = request.code !== void 0, file = request.remotePath !== void 0;
920
+ if (inline === file) throw new Error("a request holds either the script's code or its uploaded remotePath");
921
+ if (inline && (typeof request.code !== "string" || !/^[a-f0-9]{64}$/.test(request.codeSha256 ?? ""))) throw new Error("code and its SHA-256 are required");
922
922
  if (request.capture !== void 0 && typeof request.capture !== "boolean") throw new Error("capture must be boolean");
923
- if (request.kind === "script" && (!text(request.remotePath) || !isAbsolute(request.remotePath) || !/^[a-f0-9]{64}$/.test(request.scriptSha256 ?? ""))) throw new Error("absolute remotePath and script SHA-256 are required");
923
+ if (file && (!text(request.remotePath) || !isAbsolute(request.remotePath) || !/^[a-f0-9]{64}$/.test(request.scriptSha256 ?? ""))) throw new Error("absolute remotePath and script SHA-256 are required");
924
924
  }
925
925
  function groupAbsentFromProcessTable(group, table) {
926
926
  const lines = table.split("\n").map((line) => line.trim()).filter(Boolean);
@@ -1025,6 +1025,41 @@ async function runArgv(argv, options, onSpawn) {
1025
1025
  });
1026
1026
  });
1027
1027
  }
1028
+ async function executable(path) {
1029
+ try {
1030
+ await access(path, constants.X_OK);
1031
+ return true;
1032
+ } catch {
1033
+ return false;
1034
+ }
1035
+ }
1036
+ async function onPath(name) {
1037
+ for (const dir of (process.env.PATH ?? "").split(":")) {
1038
+ if (!dir) continue;
1039
+ try {
1040
+ await access(join3(dir, name), constants.X_OK);
1041
+ return true;
1042
+ } catch {
1043
+ }
1044
+ }
1045
+ return false;
1046
+ }
1047
+ async function interpreterArgv(language, path, find = onPath, node = { execPath: process.execPath, version: process.versions.node, strips: Boolean(process.features.typescript) }, shell = executable) {
1048
+ if (language === "shell") {
1049
+ if (!await shell("/bin/sh")) throw new Error("the guest has no /bin/sh, so a shell script cannot run");
1050
+ return ["/bin/sh", path];
1051
+ }
1052
+ if (language === "python") {
1053
+ if (!await find("python3")) throw new Error("python3 is not on the guest's PATH, so a Python script cannot run; relay_probe scope=guest reports which runtimes the guest has");
1054
+ return ["python3", path];
1055
+ }
1056
+ if (language !== "typescript") return [node.execPath, path];
1057
+ if (await find("tsx")) return ["tsx", path];
1058
+ if (node.strips) return [node.execPath, "--disable-warning=ExperimentalWarning", path];
1059
+ const [major = 0, minor = 0] = node.version.split(".").map(Number);
1060
+ if (major > 22 || major === 22 && minor >= 6) return [node.execPath, "--experimental-strip-types", "--disable-warning=ExperimentalWarning", path];
1061
+ throw new Error(`the guest has no tsx on its PATH, and its Node.js ${node.version} predates type stripping (22.6), so a TypeScript script cannot run; write it in JavaScript instead`);
1062
+ }
1028
1063
  async function captureWithDriver(outFile, driver, dispatch = runArgv) {
1029
1064
  const result = await dispatch([driver, "call", "get_desktop_state", "--json", JSON.stringify({ screenshot_out_file: outFile })], { env: process.env, timeoutMs: 6e4 });
1030
1065
  if (result.exitStatus.code !== 0 || result.timedOut || result.outputTruncated || result.spawnError || result.terminationConfirmed !== true) throw new Error(`display capture unavailable: ${JSON.stringify({ exitStatus: result.exitStatus, timedOut: result.timedOut, outputTruncated: result.outputTruncated, spawnError: result.spawnError, terminationConfirmed: result.terminationConfirmed, terminationDiagnostic: result.terminationDiagnostic, stdout: result.stdout?.slice(0, 1500), stderr: result.stderr?.slice(0, 1500) })}`);
@@ -1034,7 +1069,7 @@ async function captureWithDriver(outFile, driver, dispatch = runArgv) {
1034
1069
  async function receive(input, options = {}) {
1035
1070
  const request = input;
1036
1071
  const executionId = request && safeId(request.executionId) ? request.executionId : "unknown";
1037
- const evidenceMode = request?.kind === "exec" && request.diagnostic === true ? "diagnostic" : void 0;
1072
+ const evidenceMode = request?.diagnostic === true ? "diagnostic" : void 0;
1038
1073
  const uncaptured = request?.capture === false;
1039
1074
  const timeoutMs = request?.timeoutMs ?? 12e4;
1040
1075
  let imageEvidence = { status: afterRequested(request) ? "capture-unknown" : "not-requested", snapshots: [] };
@@ -1058,10 +1093,10 @@ async function receive(input, options = {}) {
1058
1093
  const operationPids = [];
1059
1094
  let pendingSpawn = false;
1060
1095
  const markLock = (active, settled = false) => durableJson(ownerPath, { pid: process.pid, executionId, active, operationPids, pendingSpawn, settled });
1061
- const runOwned = async (argv, dispatchOptions) => {
1096
+ const runOwned = async (argv2, dispatchOptions) => {
1062
1097
  pendingSpawn = true;
1063
1098
  await markLock(true);
1064
- const result = await runArgv(argv, dispatchOptions, async (pid) => {
1099
+ const result = await runArgv(argv2, dispatchOptions, async (pid) => {
1065
1100
  operationPids.push(pid);
1066
1101
  pendingSpawn = false;
1067
1102
  await markLock(true);
@@ -1073,6 +1108,7 @@ async function receive(input, options = {}) {
1073
1108
  };
1074
1109
  let reconcileGroup;
1075
1110
  let dispatchResult;
1111
+ let argv;
1076
1112
  const output = () => dispatchResult ? { stdout: bounded(dispatchResult.stdout), stderr: bounded(dispatchResult.stderr), timedOut: !!dispatchResult.timedOut, outputTruncated: !!dispatchResult.outputTruncated, terminationConfirmed: dispatchResult.terminationConfirmed } : {};
1077
1113
  try {
1078
1114
  await mkdir3(root, { recursive: true });
@@ -1163,7 +1199,7 @@ async function receive(input, options = {}) {
1163
1199
  imageEvidence = candidate;
1164
1200
  result = JSON.parse(JSON.stringify({ ...result, imageEvidence, evidenceMode, timeoutMs, ...output() }));
1165
1201
  if (result.outcome.kind !== "completed" || result.outcome.exitStatus.code !== 0) await reconcileGroup?.("operation failed or incomplete");
1166
- await store.putExecution({ executionId, ...ids, state: result.outcome.kind === "completed" ? "recorded" : result.outcome.kind, argv: request.argv, scriptId: request.scriptId, exitStatus: result.outcome.kind === "completed" ? result.outcome.exitStatus : void 0 });
1202
+ await store.putExecution({ executionId, ...ids, state: result.outcome.kind === "completed" ? "recorded" : result.outcome.kind, argv, scriptId: request.scriptId, exitStatus: result.outcome.kind === "completed" ? result.outcome.exitStatus : void 0 });
1167
1203
  await store.appendJournal({ kind: "execution-completion", ...ids, executionId, state: result.outcome.kind === "completed" ? "recorded" : result.outcome.kind, response: result }, { durable: true });
1168
1204
  await durableJson(receiptPath, result);
1169
1205
  return result;
@@ -1196,19 +1232,15 @@ async function receive(input, options = {}) {
1196
1232
  if (groups.active && (!group || group.groupId !== groups.active.groupId || request.sessionId !== groups.active.sessionId || request.attemptId !== groups.active.attemptId || group.phase === "first")) return await refuse("coalescing group is open; unrelated input is forbidden until its last member");
1197
1233
  if (!groups.active && group && (group.phase !== "first" || groups.used.includes(group.groupId))) return await refuse("coalescing group must begin with a fresh first member; group IDs cannot be reused");
1198
1234
  reconcileGroup = abandonGroup;
1199
- let argv = request.argv ?? [];
1200
1235
  try {
1201
- if (request.kind === "script") {
1236
+ if (request.remotePath !== void 0) {
1202
1237
  const info = await stat2(request.remotePath);
1203
1238
  if (!info.isFile() || info.size > MAX_SCRIPT_BYTES) throw new Error("script missing or exceeds size bound");
1204
1239
  if (hash(await readFile2(request.remotePath)) !== request.scriptSha256) throw new Error("script hash mismatch");
1205
- const expected = request.language === "python" ? "python3" : request.language === "typescript" ? "tsx" : "node";
1206
- if (argv.length !== 2 || argv[0].split("/").at(-1) !== expected || argv[1] !== request.remotePath) throw new Error("script argv must be [interpreter, verified remotePath]");
1207
- if (request.language === "javascript") argv = [process.execPath, request.remotePath];
1208
- } else if (request.kind === "code") {
1240
+ argv = await interpreterArgv(request.language, request.remotePath);
1241
+ } else {
1209
1242
  if (hash(request.code) !== request.codeSha256) throw new Error("streamed code hash mismatch");
1210
- const extension = request.language === "python" ? "py" : request.language === "typescript" ? "ts" : "js";
1211
- const path = join3(root, "streamed", `${executionId}.${extension}`);
1243
+ const path = join3(root, "streamed", `${executionId}.${{ shell: "sh", python: "py", typescript: "ts", javascript: "js" }[request.language]}`);
1212
1244
  await mkdir3(dirname2(path), { recursive: true });
1213
1245
  const file = await open(path, "wx", 384);
1214
1246
  try {
@@ -1218,12 +1250,13 @@ async function receive(input, options = {}) {
1218
1250
  await file.close();
1219
1251
  }
1220
1252
  if (hash(await readFile2(path)) !== request.codeSha256) throw new Error("materialized streamed code hash mismatch");
1221
- argv = [request.language === "python" ? "python3" : request.language === "typescript" ? "tsx" : process.execPath, path];
1253
+ argv = await interpreterArgv(request.language, path);
1222
1254
  }
1223
1255
  } catch (error) {
1224
1256
  return await refuse(message(error));
1225
1257
  }
1226
- await store.appendJournal({ kind: "execution-start", ...ids, executionId, state: "admitted", argv, cwd: request.cwd, step: request.step, evidenceMode, timeoutMs, ...uncaptured ? { capture: false } : {}, scriptIdentity: request.kind === "exec" ? void 0 : { sha256: request.kind === "code" ? request.codeSha256 : request.scriptSha256, language: request.language, remotePath: argv.at(-1) } }, { durable: true });
1258
+ const command = argv;
1259
+ await store.appendJournal({ kind: "execution-start", ...ids, executionId, state: "admitted", argv, cwd: request.cwd, step: request.step, evidenceMode, timeoutMs, ...uncaptured ? { capture: false } : {}, scriptIdentity: { sha256: request.remotePath === void 0 ? request.codeSha256 : request.scriptSha256, language: request.language, remotePath: argv.at(-1) } }, { durable: true });
1227
1260
  if (group?.phase === "first") {
1228
1261
  groups.active = { groupId: group.groupId, ...ids };
1229
1262
  groups.used.push(group.groupId);
@@ -1248,7 +1281,7 @@ async function receive(input, options = {}) {
1248
1281
  await markLock(true);
1249
1282
  try {
1250
1283
  const dispatchOptions = { cwd: request.cwd, env: process.env, timeoutMs };
1251
- dispatchResult = options.dispatch ? await options.dispatch(argv, dispatchOptions) : await runOwned(argv, dispatchOptions);
1284
+ dispatchResult = options.dispatch ? await options.dispatch(command, dispatchOptions) : await runOwned(command, dispatchOptions);
1252
1285
  return dispatchResult;
1253
1286
  } finally {
1254
1287
  if (dispatchResult && dispatchResult.terminationConfirmed !== false && !keepLock) {
@@ -1262,18 +1295,6 @@ async function receive(input, options = {}) {
1262
1295
  const diagnostic = captureFailure ?? engine.evidenceFailure ?? "missing required snapshot evidence";
1263
1296
  return await retain(response("uncertain", diagnostic));
1264
1297
  }
1265
- const driver = options.cuaDriver ?? process.env.RELAY_CUA_DRIVER;
1266
- if (request.kind === "exec" && driver && argv[0] === driver && argv[1] === "call" && outcome.exitStatus.code === 0) {
1267
- let value;
1268
- try {
1269
- value = JSON.parse(outcome.stdout ?? "");
1270
- } catch {
1271
- }
1272
- if (value && typeof value === "object" && (value.isError === true || value.error || typeof value.code === "string" && value.code.length > 0)) {
1273
- const diagnostic = `CUA structured failure: ${JSON.stringify(value)}`;
1274
- return await retain({ ...response(value.code === "desktop_escalation_required" ? "refused" : "uncertain", diagnostic), stdout: bounded(outcome.stdout), stderr: bounded(outcome.stderr) });
1275
- }
1276
- }
1277
1298
  const result = outcome.spawnError || outcome.timedOut || outcome.outputTruncated ? response("uncertain", outcome.spawnError ?? (outcome.timedOut ? "execution timed out" : "execution exceeded output bound")) : { executionId, outcome: { kind: "completed", exitStatus: outcome.exitStatus } };
1278
1299
  if (group?.phase === "last" && result.outcome.kind === "completed" && result.outcome.exitStatus.code === 0) {
1279
1300
  delete groups.active;
@@ -1336,6 +1357,7 @@ export {
1336
1357
  afterRequested,
1337
1358
  confirmProcessGroupExit,
1338
1359
  groupAbsentFromProcessTable,
1360
+ interpreterArgv,
1339
1361
  receive,
1340
1362
  validateImageEvidence
1341
1363
  };
@@ -1,7 +1,12 @@
1
1
  import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __esm = (fn, res) => function __init() {
4
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
3
+ var __esm = (fn, res, err) => function __init() {
4
+ if (err) throw err[0];
5
+ try {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ } catch (e) {
8
+ throw err = [e], e;
9
+ }
5
10
  };
6
11
 
7
12
  // node_modules/@wezzard/relay-driver-host-sdk/dist/src/evidence-package.js