relayrunner 0.8.0 → 0.9.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.
Files changed (4) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +22 -10
  3. package/dist/cli.js +1453 -1216
  4. package/package.json +2 -1
package/dist/cli.js CHANGED
@@ -2,10 +2,10 @@
2
2
  import * as clack from "@clack/prompts";
3
3
  import { defineCommand, runMain } from "citty";
4
4
  import { z } from "zod";
5
- import { arch, availableParallelism, cpus, homedir, hostname, platform, release, tmpdir, totalmem } from "node:os";
5
+ import { arch, availableParallelism, cpus, homedir, hostname, networkInterfaces, platform, release, tmpdir, totalmem } from "node:os";
6
6
  import { basename, dirname, join, resolve } from "node:path";
7
7
  import { appendFileSync, chmodSync, constants, cpSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
8
- import { execFile, spawn } from "node:child_process";
8
+ import { execFile, spawn, spawnSync } from "node:child_process";
9
9
  import { createHash } from "node:crypto";
10
10
  import { Readable, Transform } from "node:stream";
11
11
  import { pipeline } from "node:stream/promises";
@@ -30,25 +30,31 @@ const Device = z.object({
30
30
  memoryMb: z.number().int().positive().max(1e9).optional(),
31
31
  osVersion: text.optional()
32
32
  });
33
+ const os = z.enum([
34
+ "linux",
35
+ "macos",
36
+ "windows"
37
+ ]);
38
+ const arch$1 = z.enum([
39
+ "x64",
40
+ "arm64",
41
+ "arm"
42
+ ]);
33
43
  const HelloMessage = z.object({
34
44
  v: version$1,
35
45
  type: z.literal("hello"),
36
46
  machineId: z.string().min(1),
37
- os: z.enum([
38
- "linux",
39
- "macos",
40
- "windows"
41
- ]),
42
- arch: z.enum([
43
- "x64",
44
- "arm64",
45
- "arm"
46
- ]),
47
+ os,
48
+ arch: arch$1,
47
49
  runnerVersion: z.string().min(1),
48
50
  cliVersion: z.string().trim().min(1).max(40).optional(),
49
51
  device: Device.optional().catch(void 0),
50
52
  rotatesToken: z.boolean().optional(),
51
- slots: z.number().int().positive().max(1e3).optional()
53
+ slots: z.number().int().positive().max(1e3).optional(),
54
+ isolated: z.object({
55
+ os,
56
+ arch: arch$1
57
+ }).optional()
52
58
  });
53
59
  const StatusMessage = z.object({
54
60
  v: version$1,
@@ -81,7 +87,8 @@ const RunMessage = z.object({
81
87
  v: version$1,
82
88
  type: z.literal("run"),
83
89
  routeId,
84
- jitConfig: z.string().min(1)
90
+ jitConfig: z.string().min(1),
91
+ isolated: z.boolean().optional()
85
92
  });
86
93
  const ErrorMessage = z.object({
87
94
  v: version$1,
@@ -163,7 +170,7 @@ function parse(version) {
163
170
  ] : null;
164
171
  }
165
172
  // version.ts
166
- const cliVersion = "0.8.0";
173
+ const cliVersion = "0.9.0";
167
174
  // paths.ts
168
175
  function relayrunnerHome() {
169
176
  return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), ".relayrunner"));
@@ -887,1278 +894,1335 @@ function unifiedDiff(before, after, file, context = 2) {
887
894
  }
888
895
  return out.join("\n");
889
896
  }
890
- // repo.ts
891
- const WORKFLOWS_DIR = ".github/workflows";
892
- /** The nearest directory at or above `from` that holds a `.git`, or null outside a checkout. */
893
- function findRepoRoot(from = process.cwd()) {
894
- let dir = resolve(from);
895
- for (;;) {
896
- if (existsSync(join(dir, ".git"))) return dir;
897
- const parent = dirname(dir);
898
- if (parent === dir) return null;
899
- dir = parent;
897
+ // jit-config.ts
898
+ const GITHUB_HOSTS = [
899
+ /^github\.com$/,
900
+ /\.github\.com$/,
901
+ /\.githubusercontent\.com$/
902
+ ];
903
+ const FILES = [
904
+ ".runner",
905
+ ".credentials",
906
+ ".credentials_rsaparams"
907
+ ];
908
+ const URL_FIELDS = /* @__PURE__ */ new Set([
909
+ "serverurl",
910
+ "serverurlv2",
911
+ "githuburl",
912
+ "authorizationurl"
913
+ ]);
914
+ function checkJitConfig(encoded, routeId) {
915
+ let files;
916
+ try {
917
+ files = decodeJson(encoded);
918
+ if (!files || typeof files !== "object") throw new Error();
919
+ } catch {
920
+ return {
921
+ ok: false,
922
+ reason: "it isn't a runner config"
923
+ };
924
+ }
925
+ const names = Object.keys(files);
926
+ if (names.length !== FILES.length || !FILES.every((name) => names.includes(name))) return {
927
+ ok: false,
928
+ reason: `it holds ${names.join(", ") || "nothing"}, not GitHub's files`
929
+ };
930
+ const decoded = {};
931
+ for (const [name, value] of Object.entries(files)) {
932
+ if (typeof value !== "string") return {
933
+ ok: false,
934
+ reason: `${name} isn't a file`
935
+ };
936
+ try {
937
+ decoded[name] = decodeJson(value);
938
+ } catch {
939
+ return {
940
+ ok: false,
941
+ reason: `${name} isn't JSON`
942
+ };
943
+ }
944
+ }
945
+ const runner = decoded[".runner"];
946
+ if (!runner || typeof runner !== "object") return {
947
+ ok: false,
948
+ reason: "it has no .runner"
949
+ };
950
+ const duplicate = duplicateKey(decoded);
951
+ if (duplicate) return {
952
+ ok: false,
953
+ reason: `it has ${duplicate} twice`
954
+ };
955
+ for (const url of urls(decoded)) {
956
+ const parsed = URL.canParse(url) ? new URL(url) : null;
957
+ if (!parsed) return {
958
+ ok: false,
959
+ reason: `it names a URL that doesn't parse: ${url}`
960
+ };
961
+ if (parsed.protocol !== "https:" || !GITHUB_HOSTS.some((host) => host.test(parsed.hostname))) return {
962
+ ok: false,
963
+ reason: `it points the runner at ${parsed.origin}, not GitHub`
964
+ };
900
965
  }
966
+ const field = (key) => {
967
+ const entry = Object.entries(runner).find(([name]) => name.toLowerCase() === key);
968
+ return typeof entry?.[1] === "string" ? entry[1] : null;
969
+ };
970
+ if (!field("serverurl") && !field("serverurlv2")) return {
971
+ ok: false,
972
+ reason: "it doesn't say which GitHub server to use"
973
+ };
974
+ const runnerName = field("agentname");
975
+ if (!runnerName || !isRunnerForRoute(runnerName, routeId)) return {
976
+ ok: false,
977
+ reason: `its runner ${runnerName ?? "(no name)"} isn't for job ${routeId}`
978
+ };
979
+ return {
980
+ ok: true,
981
+ target: target(field("githuburl"))
982
+ };
901
983
  }
902
- function readWorkflowFiles(root) {
903
- const dir = join(root, WORKFLOWS_DIR);
904
- if (!existsSync(dir)) return [];
905
- return readdirSync(dir).filter((name) => /\.ya?ml$/.test(name)).sort().map((name) => ({
906
- file: `${WORKFLOWS_DIR}/${name}`,
907
- source: readFileSync(join(dir, name), "utf8")
908
- }));
984
+ function target(url) {
985
+ if (!url || !URL.canParse(url)) return null;
986
+ const path = new URL(url).pathname.split("/").filter(Boolean).slice(0, 2);
987
+ return path.length ? path.join("/") : null;
909
988
  }
910
- /** `owner/name` from a GitHub remote URL (https or ssh), or null for anything else. */
911
- function parseGitHubRemote(url) {
912
- const match = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url.trim());
913
- return match ? `${match[1]}/${match[2]}` : null;
989
+ function urls(value, found = [], key = "") {
990
+ if (typeof value === "string") {
991
+ const text = value.trim();
992
+ if (text && (URL_FIELDS.has(key.toLowerCase()) || /^[a-z][a-z0-9+.-]*:/i.test(text))) found.push(text);
993
+ } else if (Array.isArray(value)) for (const item of value) urls(item, found);
994
+ else if (value && typeof value === "object") for (const [name, item] of Object.entries(value)) urls(item, found, name);
995
+ return found;
914
996
  }
915
- function originRepo(root) {
916
- return new Promise((done) => {
917
- execFile("git", [
918
- "-C",
919
- root,
920
- "remote",
921
- "get-url",
922
- "origin"
923
- ], {
924
- timeout: 3e3,
925
- encoding: "utf8"
926
- }, (error, stdout) => done(error ? null : parseGitHubRemote(stdout)));
927
- });
997
+ function duplicateKey(value) {
998
+ if (Array.isArray(value)) for (const item of value) {
999
+ const found = duplicateKey(item);
1000
+ if (found) return found;
1001
+ }
1002
+ else if (value && typeof value === "object") {
1003
+ const seen = /* @__PURE__ */ new Set();
1004
+ for (const [name, item] of Object.entries(value)) {
1005
+ if (seen.has(name.toLowerCase())) return name;
1006
+ seen.add(name.toLowerCase());
1007
+ const found = duplicateKey(item);
1008
+ if (found) return found;
1009
+ }
1010
+ }
1011
+ return null;
928
1012
  }
929
- /**
930
- * Asks GitHub without signing in. A public repo answers; a private one (or one that doesn't exist)
931
- * is a 404 to an anonymous caller. Anything else, such as no network or a rate limit, is unknown.
932
- */
933
- async function repoVisibility(repo, fetcher = fetch) {
1013
+ function decodeJson(base64) {
1014
+ return JSON.parse(Buffer.from(base64, "base64").toString("utf8").replace(/^/, ""));
1015
+ }
1016
+ // job.ts
1017
+ const runnerEnv = () => Object.fromEntries([
1018
+ "HOME",
1019
+ "USER",
1020
+ "LOGNAME",
1021
+ "PATH",
1022
+ "LANG",
1023
+ "LC_ALL",
1024
+ "TMPDIR",
1025
+ "SHELL"
1026
+ ].flatMap((key) => process.env[key] === void 0 ? [] : [[key, process.env[key]]]));
1027
+ async function runJob(run, options) {
1028
+ const { launcher, report } = options;
1029
+ const { routeId } = run;
1030
+ const output = options.output ?? ((chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk));
1031
+ const finish = (update) => {
1032
+ report(update);
1033
+ return update;
1034
+ };
1035
+ const failed = (message) => finish({
1036
+ routeId,
1037
+ state: "failed",
1038
+ message
1039
+ });
1040
+ const checked = checkJitConfig(run.jitConfig, routeId);
1041
+ if (!checked.ok) return failed(`Refused the job's runner config: ${checked.reason}.`);
1042
+ options.onChecked?.(checked.target);
1043
+ let clean = false;
934
1044
  try {
935
- const response = await fetcher(`https://api.github.com/repos/${repo}`, {
936
- headers: {
937
- accept: "application/vnd.github+json",
938
- "user-agent": userAgent
939
- },
940
- signal: AbortSignal.timeout(5e3)
1045
+ const child = launcher.start(run);
1046
+ child.stdout.on("data", (chunk) => output(chunk, "stdout"));
1047
+ child.stderr.on("data", (chunk) => output(chunk, "stderr"));
1048
+ const started = await new Promise((resolve) => {
1049
+ child.once("spawn", () => resolve(null));
1050
+ child.once("error", resolve);
941
1051
  });
942
- if (response.status === 404) return "private";
943
- if (!response.ok) return "unknown";
944
- return (await response.json()).private === false ? "public" : "private";
945
- } catch {
946
- return "unknown";
1052
+ if (started) return failed(`Could not start the runner: ${started.message}`);
1053
+ report({
1054
+ routeId,
1055
+ state: "started"
1056
+ });
1057
+ const [code, signal] = await new Promise((resolve) => child.once("close", (code, signal) => resolve([code, signal])));
1058
+ clean = code === 0;
1059
+ if (clean) return finish({
1060
+ routeId,
1061
+ state: "finished"
1062
+ });
1063
+ return failed(signal ? `The runner was stopped by ${signal}` : `The runner exited with ${code}`);
1064
+ } catch (error) {
1065
+ return failed(error instanceof Error ? error.message : String(error));
1066
+ } finally {
1067
+ await launcher.cleanup(run, clean);
947
1068
  }
948
1069
  }
949
- // ../../packages/providers/src/prices.ts
950
- /** A provider's rates, and what one minute of each is per. */
951
- const RATES = {
952
- blacksmith: {
953
- linux: "vcpu",
954
- arm: "vcpu",
955
- windows: "vcpu",
956
- macos: "vcpu"
957
- },
958
- depot: {
959
- linux: "vcpu",
960
- arm: "vcpu",
961
- windows: "vcpu",
962
- macos: "vcpu"
963
- },
964
- warpbuild: {
965
- linux: "vcpu",
966
- arm: "vcpu",
967
- windows: "vcpu",
968
- macos: "vcpu"
969
- },
970
- ubicloud: {
971
- standard: "vcpu",
972
- premium: "vcpu"
973
- },
974
- github: {
975
- "linux-1-core": "runner",
976
- "linux-2-core": "runner",
977
- "linux-arm-2-core": "runner",
978
- "windows-2-core": "runner",
979
- "windows-arm-2-core": "runner",
980
- macos: "runner"
981
- }
982
- };
983
- /** The one rate a provider operators added has: a minute of any of its runners. */
984
- const ADDED_RATE = "runner";
985
- /**
986
- * Whether a provider has this rate: one RATES lists, or the per-runner rate of a provider RATES
987
- * doesn't price (the admin only records that one for providers operators added).
988
- */
989
- const isRate = (provider, rate) => Object.hasOwn(RATES, provider) ? Object.hasOwn(RATES[provider], rate) : rate === ADDED_RATE;
990
- const vcpu = (perRunner, vcpus) => perRunner / vcpus;
991
- const BASE_PRICES = [
992
- {
993
- provider: "blacksmith",
994
- rate: "linux",
995
- usd: vcpu(.004, 2),
996
- from: "2026-11-11"
997
- },
998
- {
999
- provider: "blacksmith",
1000
- rate: "arm",
1001
- usd: vcpu(.0025, 2),
1002
- from: "2026-11-11"
1003
- },
1004
- {
1005
- provider: "blacksmith",
1006
- rate: "windows",
1007
- usd: vcpu(.008, 2),
1008
- from: "2026-11-11"
1009
- },
1010
- {
1011
- provider: "blacksmith",
1012
- rate: "macos",
1013
- usd: vcpu(.08, 6),
1014
- from: "2026-11-11"
1015
- },
1016
- {
1017
- provider: "depot",
1018
- rate: "linux",
1019
- usd: vcpu(.006, 2),
1020
- from: "2026-11-11"
1021
- },
1022
- {
1023
- provider: "depot",
1024
- rate: "arm",
1025
- usd: vcpu(.006, 2),
1026
- from: "2026-11-11"
1027
- },
1028
- {
1029
- provider: "depot",
1030
- rate: "windows",
1031
- usd: vcpu(.008, 2),
1032
- from: "2026-11-11"
1033
- },
1034
- {
1035
- provider: "depot",
1036
- rate: "macos",
1037
- usd: vcpu(.08, 8),
1038
- from: "2026-11-11"
1039
- },
1040
- {
1041
- provider: "warpbuild",
1042
- rate: "linux",
1043
- usd: vcpu(.004, 2),
1044
- from: "2026-11-11"
1045
- },
1046
- {
1047
- provider: "warpbuild",
1048
- rate: "arm",
1049
- usd: vcpu(.003, 2),
1050
- from: "2026-11-11"
1051
- },
1052
- {
1053
- provider: "warpbuild",
1054
- rate: "windows",
1055
- usd: vcpu(.016, 4),
1056
- from: "2026-11-11"
1057
- },
1058
- {
1059
- provider: "warpbuild",
1060
- rate: "macos",
1061
- usd: vcpu(.08, 6),
1062
- from: "2026-11-11"
1063
- },
1064
- {
1065
- provider: "ubicloud",
1066
- rate: "standard",
1067
- usd: vcpu(8e-4, 2),
1068
- from: "2023-01-01"
1069
- },
1070
- {
1071
- provider: "ubicloud",
1072
- rate: "standard",
1073
- usd: vcpu(.001, 2),
1074
- from: "2026-05-01"
1075
- },
1076
- {
1077
- provider: "ubicloud",
1078
- rate: "standard",
1079
- usd: vcpu(.00125, 2),
1080
- from: "2026-09-01"
1081
- },
1082
- {
1083
- provider: "ubicloud",
1084
- rate: "premium",
1085
- usd: vcpu(.0016, 2),
1086
- from: "2025-05-01"
1087
- },
1088
- {
1089
- provider: "ubicloud",
1090
- rate: "premium",
1091
- usd: vcpu(.002, 2),
1092
- from: "2026-09-01"
1093
- },
1094
- {
1095
- provider: "github",
1096
- rate: "linux-1-core",
1097
- usd: .002,
1098
- from: "2026-11-11"
1099
- },
1100
- {
1101
- provider: "github",
1102
- rate: "linux-2-core",
1103
- usd: .006,
1104
- from: "2026-11-11"
1105
- },
1106
- {
1107
- provider: "github",
1108
- rate: "linux-arm-2-core",
1109
- usd: .005,
1110
- from: "2026-11-11"
1111
- },
1112
- {
1113
- provider: "github",
1114
- rate: "windows-2-core",
1115
- usd: .01,
1116
- from: "2026-11-11"
1117
- },
1118
- {
1119
- provider: "github",
1120
- rate: "windows-arm-2-core",
1121
- usd: .01,
1122
- from: "2026-11-11"
1123
- },
1124
- {
1125
- provider: "github",
1126
- rate: "macos",
1127
- usd: .062,
1128
- from: "2026-11-11"
1129
- }
1070
+ const JOB_STATE = [
1071
+ "_work",
1072
+ ".runner",
1073
+ ".credentials",
1074
+ ".credentials_rsaparams"
1130
1075
  ];
1131
- /** A UTC day (YYYY-MM-DD) as epoch ms at its midnight. */
1132
- const dayMs = (day) => Date.parse(`${day}T00:00:00Z`);
1133
- /**
1134
- * Looks up price rows, leaving out any for a rate RATES doesn't list. Rows for the same rate and
1135
- * day replace earlier ones in the list, so rows added on top of BASE_PRICES win.
1136
- */
1137
- function priceBook(rows) {
1138
- const byRate = /* @__PURE__ */ new Map();
1139
- for (const row of rows) {
1140
- if (!isRate(row.provider, row.rate)) continue;
1141
- const key = `${row.provider}:${row.rate}`;
1142
- const days = byRate.get(key) ?? /* @__PURE__ */ new Map();
1143
- days.set(row.from, row);
1144
- byRate.set(key, days);
1145
- }
1146
- const histories = new Map([...byRate].map(([key, days]) => [key, [...days.values()].sort((a, b) => a.from.localeCompare(b.from))]));
1147
- const changes = /* @__PURE__ */ new Set();
1148
- for (const history of histories.values()) for (const row of history.slice(1)) changes.add(dayMs(row.from));
1149
- const history = (provider, rate) => histories.get(`${provider}:${rate}`) ?? [];
1076
+ function hostLauncher(dir) {
1077
+ const lock = join(dir, "job.lock");
1078
+ let locked = false;
1150
1079
  return {
1151
- usd(provider, rate, at) {
1152
- let usd = null;
1153
- for (const [i, row] of history(provider, rate).entries()) if (i === 0 || dayMs(row.from) <= at) usd = row.usd;
1154
- return usd;
1080
+ start(run) {
1081
+ locked = takeLock(lock);
1082
+ if (!locked) throw new Error(`Another job is using the runner in ${dir}.`);
1083
+ clean(dir);
1084
+ return spawn(join(dir, "run.sh"), ["--jitconfig", run.jitConfig], {
1085
+ cwd: dir,
1086
+ env: runnerEnv(),
1087
+ stdio: [
1088
+ "ignore",
1089
+ "pipe",
1090
+ "pipe"
1091
+ ]
1092
+ });
1155
1093
  },
1156
- history,
1157
- changes: [...changes].sort((a, b) => a - b)
1094
+ cleanup() {
1095
+ if (!locked) return;
1096
+ clean(dir);
1097
+ rmSync(lock, { force: true });
1098
+ locked = false;
1099
+ }
1158
1100
  };
1159
1101
  }
1160
- priceBook(BASE_PRICES);
1161
- // ../../packages/providers/src/index.ts
1162
- /**
1163
- * The hosted runner services a relay can send a job to. Each runs a job under the customer's own
1164
- * account through its own GitHub App, which picks up any job queued with one of its labels, so
1165
- * routing to one only means answering one of its labels. Each is a step in the runner order and an
1166
- * input on the relay, both named by its id.
1167
- */
1168
- const HOSTED_PROVIDER_IDS = [
1169
- "blacksmith",
1170
- "depot",
1171
- "namespace",
1172
- "warpbuild",
1173
- "ubicloud",
1174
- "runs-on"
1175
- ];
1176
- const LABEL_PREFIXES = {
1177
- blacksmith: ["blacksmith-"],
1178
- depot: ["depot-"],
1179
- namespace: ["namespace-profile-", "nscloud-"],
1180
- warpbuild: ["warp-"],
1181
- ubicloud: ["ubicloud-"],
1182
- "runs-on": ["runs-on=", "runs-on/"]
1183
- };
1184
- /** Whether a lowercase label starts with one of `prefixes`, or is the bare name one ends in `-`. */
1185
- const matchesPrefix = (prefixes, lower) => prefixes.some((prefix) => lower.startsWith(prefix) || prefix.endsWith("-") && lower === prefix.slice(0, -1));
1186
- const matches = (provider, lower) => matchesPrefix(LABEL_PREFIXES[provider], lower);
1187
- /** The hosted provider whose runners a label asks for, or null. */
1188
- function hostedProviderOf(label) {
1189
- const lower = label.toLowerCase();
1190
- return HOSTED_PROVIDER_IDS.find((id) => matches(id, lower)) ?? null;
1102
+ function clean(dir) {
1103
+ for (const name of JOB_STATE) rmSync(join(dir, name), {
1104
+ recursive: true,
1105
+ force: true
1106
+ });
1191
1107
  }
1192
- // workflows.ts
1193
- /** The relay version `init` writes. Bump it with each relayrunner/actions release. */
1194
- const RELAY_REF = "v1.0.0-beta.5";
1195
- const RELAY_WORKFLOW = "relayrunner/actions/.github/workflows/relay.yml";
1196
- const DEPLOY_SECRET = /\bsecrets\.(?!GITHUB_TOKEN\b)[A-Za-z_][A-Za-z0-9_]*/;
1197
- const LINUX_PACKAGE_MANAGER = /(^|[\s;&|(])(sudo\s+)?(apt-get|apt|yum|dnf|apk)\s+(install|update|add)\b/m;
1198
- function analyzeWorkflows(files, options = {}) {
1199
- const jobs = [];
1200
- const errors = [];
1201
- for (const { file, source } of files) {
1202
- const doc = parseDocument(source);
1203
- if (doc.errors.length) {
1204
- errors.push({
1205
- file,
1206
- message: doc.errors[0].message.split("\n")[0]
1207
- });
1208
- continue;
1209
- }
1210
- const workflow = doc.toJS();
1211
- if (!workflow || typeof workflow !== "object") continue;
1212
- const all = workflow.jobs;
1213
- if (!all || typeof all !== "object") continue;
1214
- const relays = new Set(Object.entries(all).filter(([, job]) => isRelayJob(job)).map(([id]) => id));
1215
- const reusableOnly = onlyWorkflowCall(workflow.on);
1216
- for (const [id, raw] of Object.entries(all)) {
1217
- if (!raw || typeof raw !== "object") continue;
1218
- const job = raw;
1219
- if (relays.has(id)) continue;
1220
- jobs.push(judge(file, id, job, workflow, relays, reusableOnly, options));
1221
- }
1108
+ function takeLock(lock) {
1109
+ for (let attempt = 0; attempt < 2; attempt++) try {
1110
+ symlinkSync(String(process.pid), lock);
1111
+ return true;
1112
+ } catch (error) {
1113
+ if (error.code !== "EEXIST") throw error;
1114
+ if (isAlive(Number(readlinkSync(lock)))) return false;
1115
+ rmSync(lock, { force: true });
1116
+ }
1117
+ return false;
1118
+ }
1119
+ function isAlive(pid) {
1120
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
1121
+ try {
1122
+ process.kill(pid, 0);
1123
+ return true;
1124
+ } catch (error) {
1125
+ return error.code === "EPERM";
1222
1126
  }
1127
+ }
1128
+ function prefixLines(prefix, write) {
1129
+ const partial = {
1130
+ stdout: "",
1131
+ stderr: ""
1132
+ };
1133
+ const output = (chunk, stream) => {
1134
+ const text = partial[stream] + chunk.toString();
1135
+ const end = text.lastIndexOf("\n") + 1;
1136
+ partial[stream] = text.slice(end);
1137
+ if (end === 0) return;
1138
+ const lines = text.slice(0, end).replace(/^(?=.)/gm, prefix);
1139
+ write(Buffer.from(lines), stream);
1140
+ };
1141
+ const flush = () => {
1142
+ for (const stream of ["stdout", "stderr"]) {
1143
+ if (partial[stream]) write(Buffer.from(`${prefix}${partial[stream]}\n`), stream);
1144
+ partial[stream] = "";
1145
+ }
1146
+ };
1223
1147
  return {
1224
- jobs,
1225
- errors
1148
+ output,
1149
+ flush
1226
1150
  };
1227
1151
  }
1228
- /** True when any job already runs where a relay sends it. */
1229
- function isSetUp(jobs) {
1230
- return jobs.some((job) => job.verdict === "routed");
1152
+ // isolated.ts
1153
+ const RUNNER_IMAGE = "ghcr.io/actions/actions-runner";
1154
+ const RELEASES = "https://github.com/apple/container/releases";
1155
+ function unsupportedReason(system = platform(), chip = arch(), darwin = release()) {
1156
+ if (system !== "darwin") return "Running jobs in VMs needs a Mac with Apple silicon and macOS 26 or later.";
1157
+ if (chip !== "arm64") return "Running jobs in VMs needs a Mac with Apple silicon. This one has an Intel chip.";
1158
+ if (Number.parseInt(darwin, 10) < 25) return "Running jobs in VMs needs macOS 26 or later. Update macOS, then try again.";
1159
+ return null;
1231
1160
  }
1232
- function judge(file, id, job, workflow, relays, reusableOnly, options) {
1233
- const base = {
1234
- file,
1235
- job: id,
1236
- warnings: []
1161
+ async function isolationState(command = "container", reason = unsupportedReason()) {
1162
+ if (reason !== null) return "unsupported";
1163
+ const status = await call(command, ["system", "status"], NO_LOG, true);
1164
+ if (status === null) return "missing";
1165
+ return status === 0 ? "ready" : "stopped";
1166
+ }
1167
+ function setupHint(state) {
1168
+ if (state !== "missing" && state !== "stopped") return null;
1169
+ return `Jobs run on this Mac itself, where they can read your files. To run each job in its own Linux VM, ${state === "missing" ? `install Apple's container tool from ${RELEASES} and run \`container system start\`` : "run `container system start`"}.`;
1170
+ }
1171
+ function debugLog(path = join(relayrunnerHome(), "isolated.log")) {
1172
+ const home = homedir();
1173
+ const write = (text, flag = "a") => {
1174
+ try {
1175
+ const stamped = `${(/* @__PURE__ */ new Date()).toISOString()} ${text.trimEnd().replaceAll(home, "~")}\n`;
1176
+ if (flag === "w") {
1177
+ rmSync(path, { force: true });
1178
+ writeFileSync(path, stamped, { mode: 384 });
1179
+ } else appendFileSync(path, stamped);
1180
+ } catch {}
1237
1181
  };
1238
- const skip = (reason) => ({
1239
- ...base,
1240
- verdict: "skipped",
1241
- reason
1242
- });
1243
- if (typeof job.uses === "string") return skip("calls a reusable workflow");
1244
- if (reusableOnly) return skip("part of a reusable workflow; it runs wherever the calling workflow sends it");
1245
- const runsOn = job["runs-on"];
1246
- if (runsOn === void 0) return skip("has no runs-on");
1247
- if (typeof runsOn !== "string") return skip("runs-on is a list of labels or a runner group");
1248
- if (runsOn.includes("${{")) {
1249
- const relay = /^\$\{\{\s*needs\.([\w-]+)\.outputs\.runner\s*\}\}$/.exec(runsOn.trim())?.[1];
1250
- if (relay && relays.has(relay)) return {
1251
- ...base,
1252
- verdict: "routed"
1253
- };
1254
- return skip("runs-on is an expression");
1255
- }
1256
- if (hasMatrix(job)) return skip("uses a matrix, and one relay can't serve every leg");
1257
- const deploy = deploySignal(job, workflow);
1258
- if (deploy) return skip(`looks like a deploy job (${deploy})`);
1259
- const label = runsOn.trim();
1260
- const lower = label.toLowerCase();
1261
- let provider;
1262
- let machine = "self-hosted";
1263
- const hosted = hostedProviderOf(lower);
1264
- if (/(^|-)windows-/.test(lower)) return skip("Windows jobs can't run on machines yet");
1265
- if (hosted) {
1266
- provider = hosted;
1267
- if (lower.includes("macos")) machine = "macOS";
1268
- } else if (/^(ubuntu|macos)-/.test(lower)) {
1269
- provider = "github";
1270
- if (lower.startsWith("macos-")) machine = "macOS";
1271
- } else if (lower === "relayrunner") return skip("already runs on RelayRunner");
1272
- else if (lower === "self-hosted") return skip("already runs on a self-hosted runner");
1273
- else return skip(`${label} isn't a GitHub-hosted or hosted provider label`);
1274
- const warnings = jobWarnings(job, options);
1182
+ try {
1183
+ mkdirSync(dirname(path), { recursive: true });
1184
+ } catch {}
1185
+ write(`relayrunner ${cliVersion}, ${platform()} ${release()} ${arch()}, ${availableParallelism()} cores, ${Math.round(totalmem() / 1024 ** 3)} GB`, "w");
1275
1186
  return {
1276
- ...base,
1277
- verdict: "ready",
1278
- provider,
1279
- label,
1280
- machine,
1281
- warnings
1187
+ path,
1188
+ write
1282
1189
  };
1283
1190
  }
1284
- function isRelayJob(job) {
1285
- return typeof job?.uses === "string" && job.uses.split("@")[0] === "relayrunner/actions/.github/workflows/relay.yml";
1191
+ const NO_LOG = {
1192
+ path: "",
1193
+ write: () => {}
1194
+ };
1195
+ const START_SCRIPT = `#!/bin/sh
1196
+ set -eu
1197
+ drop=""
1198
+ if [ "\${RELAYRUNNER_LOCAL_NETWORK:-}" != 1 ]; then
1199
+ drop="--bounding-set -net_admin,-net_raw"
1200
+ dns=$(awk '$1 == "nameserver" && $2 ~ /^[0-9.]+$/ { printf "%s%s", sep, $2; sep = ", " }' /etc/resolv.conf)
1201
+ allow_dns=""
1202
+ [ -z "$dns" ] || allow_dns="ip daddr { $dns } meta l4proto { tcp, udp } th dport 53 accept"
1203
+ nft -f - <<EOF
1204
+ table inet relayrunner {
1205
+ chain private {
1206
+ oifname { "lo", "docker0" } accept
1207
+ oifname "br-*" accept
1208
+ $allow_dns
1209
+ ip daddr { 10.0.0.0/8, 100.64.0.0/10, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16 } drop
1210
+ meta nfproto ipv6 drop
1211
+ }
1212
+ chain out {
1213
+ type filter hook output priority 0; policy accept;
1214
+ jump private
1215
+ }
1216
+ chain forward {
1217
+ type filter hook forward priority 0; policy accept;
1218
+ jump private
1219
+ }
1286
1220
  }
1287
- function onlyWorkflowCall(on) {
1288
- if (on === "workflow_call") return true;
1289
- if (Array.isArray(on)) return on.length > 0 && on.every((event) => event === "workflow_call");
1290
- if (on && typeof on === "object") {
1291
- const events = Object.keys(on);
1292
- return events.length > 0 && events.every((event) => event === "workflow_call");
1293
- }
1294
- return false;
1221
+ EOF
1222
+ fi
1223
+ # Docker sets kernel network settings under /proc/sys, which starts read-only. A job without
1224
+ # Docker loses nothing if it can't start, so failures here only reach the Docker log.
1225
+ if command -v dockerd >/dev/null 2>&1; then
1226
+ mount -o remount,rw /proc/sys 2>/dev/null || true
1227
+ dockerd >/var/log/dockerd.log 2>&1 &
1228
+ tries=0
1229
+ until docker info >/dev/null 2>&1 || [ "$tries" -ge 50 ]; do
1230
+ tries=$((tries + 1))
1231
+ sleep 0.2
1232
+ done
1233
+ fi
1234
+ # A new VM's DNS answers nothing for its first 2 seconds or so, and a lookup sent then waits 5
1235
+ # seconds to ask again. So the runner starts once a lookup gets through, or after 5 tries.
1236
+ tries=0
1237
+ until RES_OPTIONS="timeout:1 attempts:1" getent hosts github.com >/dev/null 2>&1 || [ "$tries" -ge 4 ]; do
1238
+ tries=$((tries + 1))
1239
+ done
1240
+ cd /home/runner
1241
+ # With arguments, runs them in place of the runner, to check the VM by hand.
1242
+ [ $# -gt 0 ] || set -- ./run.sh --jitconfig "$RUNNER_JIT_CONFIG"
1243
+ exec setpriv --reuid runner --regid runner --init-groups $drop \\
1244
+ env HOME=/home/runner USER=runner LOGNAME=runner "$@"
1245
+ `;
1246
+ const START_PATH = "/usr/local/bin/relayrunner-start";
1247
+ const TOOLS = [
1248
+ "build-essential pkg-config cmake",
1249
+ "python3-pip python3-venv python-is-python3",
1250
+ "zip xz-utils zstd bzip2",
1251
+ "wget rsync file gettext-base bc time",
1252
+ "git-lfs sqlite3",
1253
+ "docker-compose-v2",
1254
+ "netcat-openbsd iputils-ping dnsutils iproute2",
1255
+ "libssl-dev",
1256
+ "gh"
1257
+ ].join(" ");
1258
+ const GH_KEYRING = "/usr/share/keyrings/githubcli-archive-keyring.gpg";
1259
+ function dockerfile(base, tools = true) {
1260
+ const install = `RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg -o ${GH_KEYRING} \\
1261
+ && echo "deb [arch=$(dpkg --print-architecture) signed-by=${GH_KEYRING}] https://cli.github.com/packages stable main" > /etc/apt/sources.list.d/github-cli.list \\
1262
+ && apt-get update && apt-get install -y --no-install-recommends ${TOOLS} \\
1263
+ && apt-get clean && rm -rf /var/lib/apt/lists/*
1264
+ RUN node=$(ls -d /home/runner/externals/node[0-9]* 2>/dev/null | sort -V | tail -n 1) \\
1265
+ && { [ -z "$node" ] || { ln -sf "$node"/bin/* /usr/local/bin/ \\
1266
+ && echo prefix=/usr/local > "$node"/lib/node_modules/npm/npmrc \\
1267
+ && mkdir -p /usr/local/lib/node_modules \\
1268
+ && chown runner /usr/local/bin /usr/local/lib/node_modules; }; }
1269
+ `;
1270
+ return `FROM ${base}
1271
+ USER root
1272
+ RUN apt-get update && apt-get install -y --no-install-recommends iptables nftables && apt-get clean
1273
+ ${tools ? install : ""}COPY --chmod=755 start.sh ${START_PATH}
1274
+ `;
1295
1275
  }
1296
- function hasMatrix(job) {
1297
- const strategy = job.strategy;
1298
- return !!strategy && typeof strategy === "object" && strategy.matrix !== void 0;
1276
+ function jobImage(base, tools = true) {
1277
+ return `relayrunner-runner:${createHash("sha256").update(dockerfile(base, tools)).update(START_SCRIPT).digest("hex").slice(0, 12)}`;
1299
1278
  }
1300
- function deploySignal(job, workflow) {
1301
- if (job.environment !== void 0) return "environment";
1302
- const permissions = job.permissions ?? workflow.permissions;
1303
- if (permissions === "write-all") return "write-all permissions";
1304
- if (permissions && typeof permissions === "object" && permissions["id-token"] === "write") return "id-token: write";
1305
- const secret = DEPLOY_SECRET.exec(JSON.stringify(job))?.[0];
1306
- if (secret) return `uses ${secret}`;
1307
- return null;
1279
+ function parseVmSize(cpus, memory, cores = availableParallelism(), memoryBytes = totalmem()) {
1280
+ const whole = (flag, value, most, unit) => {
1281
+ if (value === void 0 || value === "") return void 0;
1282
+ const n = Number(value);
1283
+ if (!/^\d+$/.test(value.trim()) || n < 1) throw new RunnerError("USAGE", `${flag} takes a whole number, not "${value}".`);
1284
+ if (n > most) throw new RunnerError("USAGE", `${flag} ${n} is more than this machine's ${most} ${unit}.`);
1285
+ return n;
1286
+ };
1287
+ return {
1288
+ cpus: whole("--cpus", cpus, cores, "CPU cores"),
1289
+ memoryGb: whole("--memory", memory, Math.floor(memoryBytes / 1024 ** 3), "GB of memory")
1290
+ };
1308
1291
  }
1309
- function jobWarnings(job, options) {
1310
- const warnings = [];
1311
- if (job.services !== void 0) warnings.push("uses services, which need Docker on the machine");
1312
- if (job.container !== void 0) warnings.push("runs in a container, which needs Docker on the machine");
1313
- const steps = Array.isArray(job.steps) ? job.steps : [];
1314
- const providerActions = /* @__PURE__ */ new Set();
1315
- let packages = false;
1316
- for (const step of steps) {
1317
- if (!step || typeof step !== "object") continue;
1318
- if (typeof step.run === "string" && LINUX_PACKAGE_MANAGER.test(step.run)) packages = true;
1319
- if (typeof step.uses === "string") {
1320
- const action = step.uses.split("@")[0];
1321
- if (action.startsWith("useblacksmith/")) providerActions.add(action);
1322
- if (action.startsWith("docker://")) warnings.push("runs a Docker action, which needs Docker on the machine");
1323
- }
1324
- }
1325
- if (packages && options.hostOs !== "linux") warnings.push(options.hostOs === "macos" ? "installs Linux packages (apt-get, yum or apk), which macOS doesn't have" : "installs Linux packages (apt-get, yum or apk)");
1326
- for (const action of providerActions) warnings.push(`uses ${action}, which is made for Blacksmith runners`);
1327
- return warnings;
1292
+ function slotsFor(size, cores = availableParallelism(), memoryBytes = totalmem()) {
1293
+ if (size.cpus === void 0 && size.memoryGb === void 0) return void 0;
1294
+ const gb = memoryBytes / 1024 ** 3;
1295
+ const byCpu = size.cpus ? Math.floor(cores / size.cpus) : Infinity;
1296
+ const byMemory = size.memoryGb ? Math.floor(gb / 2 / size.memoryGb) : Infinity;
1297
+ return Math.max(1, Math.min(byCpu, byMemory));
1328
1298
  }
1329
- /**
1330
- * Routes the given jobs of one workflow file through the relay. Returns the new file contents.
1331
- * Each job must have come back `ready` from analyzeWorkflows for this same source.
1332
- */
1333
- function routeJobs(source, jobs) {
1334
- const doc = parseDocument(source);
1335
- const all = doc.get("jobs");
1336
- if (!isMap(all)) throw new Error("This workflow has no jobs map.");
1337
- for (const job of jobs) {
1338
- if (job.verdict !== "ready" || !job.provider || !job.label) throw new Error(`${job.job} isn't ready to route.`);
1339
- routeJob(doc, all, job);
1340
- }
1341
- return doc.toString({
1342
- lineWidth: 0,
1343
- flowCollectionPadding: false
1344
- });
1299
+ function checkFits(size, slots, memoryBytes = totalmem()) {
1300
+ const gb = Math.floor(memoryBytes / 1024 ** 3);
1301
+ if (size.memoryGb !== void 0 && size.memoryGb * slots > gb) throw new RunnerError("USAGE", `${slots} jobs with ${size.memoryGb} GB each is more than this machine's ${gb} GB of memory. Lower --concurrency or --memory.`);
1345
1302
  }
1346
- function routeJob(doc, all, job) {
1347
- const index = all.items.findIndex((pair) => isScalar(pair.key) && pair.key.value === job.job);
1348
- const pair = all.items[index];
1349
- if (!pair || !isMap(pair.value)) throw new Error(`No job ${job.job} in this workflow.`);
1350
- const node = pair.value;
1351
- const relayId = freeId(all, `relay-${job.job}`);
1352
- const relay = doc.createNode({
1353
- uses: `${RELAY_WORKFLOW}@${RELAY_REF}`,
1354
- with: {
1355
- machine: job.machine ?? "self-hosted",
1356
- [job.provider]: job.label
1357
- }
1358
- });
1359
- const key = new Scalar(relayId);
1360
- const jobKey = pair.key;
1361
- key.spaceBefore = jobKey.spaceBefore;
1362
- if (key.spaceBefore === void 0 && index > 0) key.spaceBefore = true;
1363
- key.commentBefore = jobKey.commentBefore;
1364
- jobKey.commentBefore = void 0;
1365
- jobKey.spaceBefore = true;
1366
- all.items.splice(index, 0, doc.createPair(key, relay));
1367
- const runsOn = node.get("runs-on", true);
1368
- const target = `\${{ needs.${relayId}.outputs.runner }}`;
1369
- if (isScalar(runsOn)) {
1370
- runsOn.value = target;
1371
- runsOn.type = Scalar.PLAIN;
1372
- } else node.set("runs-on", target);
1373
- const needs = node.get("needs", true);
1374
- if (needs === void 0) {
1375
- const at = node.items.findIndex((item) => isScalar(item.key) && item.key.value === "runs-on");
1376
- node.items.splice(Math.max(at, 0), 0, doc.createPair("needs", relayId));
1377
- } else if (isSeq(needs)) needs.add(doc.createNode(relayId));
1378
- else if (isScalar(needs)) {
1379
- const list = new YAMLSeq();
1380
- list.flow = true;
1381
- list.add(doc.createNode(needs.value));
1382
- list.add(doc.createNode(relayId));
1383
- node.set("needs", list);
1384
- }
1385
- }
1386
- function freeId(all, wanted) {
1387
- const taken = new Set(all.items.map((pair) => isScalar(pair.key) ? String(pair.key.value) : ""));
1388
- if (!taken.has(wanted)) return wanted;
1389
- for (let n = 2;; n++) if (!taken.has(`${wanted}-${n}`)) return `${wanted}-${n}`;
1390
- }
1391
- // init.ts
1392
- var InitError = class extends Error {};
1393
- async function planInit(cwd = process.cwd(), options = {}) {
1394
- const root = findRepoRoot(cwd);
1395
- if (!root) throw new InitError("Not in a git checkout. Run `relayrunner init` inside a repo.");
1396
- const repo = await originRepo(root);
1397
- const visibility = repo ? await repoVisibility(repo, options.fetcher) : "unknown";
1398
- const files = readWorkflowFiles(root);
1399
- const { jobs, errors } = analyzeWorkflows(files, { hostOs: options.hostOs ?? hostOs() });
1303
+ function vmSize(slots, wanted = {}, cores = availableParallelism(), memoryBytes = totalmem()) {
1304
+ const gb = memoryBytes / 1024 ** 3;
1400
1305
  return {
1401
- root,
1402
- repo,
1403
- visibility,
1404
- files,
1405
- jobs,
1406
- errors
1306
+ cpus: wanted.cpus ?? Math.max(2, Math.floor(cores / slots)),
1307
+ memoryGb: wanted.memoryGb ?? Math.min(16, Math.max(2, Math.floor(gb / 2 / slots)))
1407
1308
  };
1408
1309
  }
1409
- /** Picks jobs by `job`, `file:job` or `all`. Throws when a name is unknown, ambiguous or not ready. */
1410
- function selectJobs(jobs, names) {
1411
- const ready = jobs.filter((job) => job.verdict === "ready");
1412
- if (names.length === 1 && names[0] === "all") return ready;
1413
- const picked = /* @__PURE__ */ new Map();
1414
- for (const name of names) {
1415
- const [file, id] = name.includes(":") ? name.split(/:(?=[^:]*$)/) : [void 0, name];
1416
- const matches = jobs.filter((job) => job.job === id && (!file || job.file === file || shortFile(job.file) === file));
1417
- if (!matches.length) throw new InitError(`No job named ${name}.`);
1418
- if (matches.length > 1) throw new InitError(`${name} is in more than one workflow. Name it as ${matches.map((job) => `${job.file}:${job.job}`).join(" or ")}.`);
1419
- const job = matches[0];
1420
- if (job.verdict === "routed") throw new InitError(`${name} is already routed.`);
1421
- if (job.verdict === "skipped") throw new InitError(`${name} can't be routed: ${job.reason}.`);
1422
- picked.set(`${job.file}:${job.job}`, job);
1310
+ async function prepareIsolation(options) {
1311
+ const command = options.command ?? "container";
1312
+ const log = options.log ?? (() => {});
1313
+ const debug = options.debug ?? NO_LOG;
1314
+ const localNetwork = options.localNetwork ?? false;
1315
+ const tool = (args) => call(command, args, debug);
1316
+ const hasImage = async (image) => await call(command, [
1317
+ "image",
1318
+ "inspect",
1319
+ image
1320
+ ], debug, true) === 0;
1321
+ const fail = (code, message) => new RunnerError(code, debug.path ? `${message} Details are in ${debug.path}.` : message);
1322
+ const latest = latestRunnerVersion(log);
1323
+ latest.catch(() => {});
1324
+ const [status] = await Promise.all([tool(["system", "status"]), tool(["--version"])]);
1325
+ if (status === null) throw new RunnerError("ISOLATED_SETUP", `Running jobs in VMs needs Apple's container tool. Install it from ${RELEASES}, then run \`container system start\`.`);
1326
+ if (status !== 0) throw fail("ISOLATED_SETUP", "Apple's container tool isn't running. Run `container system start`, then try again.");
1327
+ const runnerVersion = await latest;
1328
+ const base = options.image ?? `${RUNNER_IMAGE}:${runnerVersion}`;
1329
+ const mine = [];
1330
+ if (!await hasImage(base)) {
1331
+ log(`Downloading ${base}. This happens once per runner version…`);
1332
+ if (await tool([
1333
+ "image",
1334
+ "pull",
1335
+ base
1336
+ ]) !== 0) throw fail("ISOLATED_IMAGE", `Could not download ${base}.`);
1337
+ if (!options.image) mine.push(base);
1423
1338
  }
1424
- return [...picked.values()];
1425
- }
1426
- /** The new contents of each workflow file the chosen jobs live in. */
1427
- function changesFor(plan, chosen) {
1428
- const byFile = /* @__PURE__ */ new Map();
1429
- for (const job of chosen) byFile.set(job.file, [...byFile.get(job.file) ?? [], job]);
1430
- return [...byFile].map(([file, jobs]) => {
1431
- const before = plan.files.find((entry) => entry.file === file).source;
1432
- return {
1433
- file,
1434
- jobs,
1435
- before,
1436
- after: routeJobs(before, jobs)
1437
- };
1438
- });
1439
- }
1440
- function writeChanges(root, changes) {
1441
- for (const change of changes) writeFileSync(join(root, change.file), change.after);
1442
- }
1443
- function hostOs() {
1444
- if (process.platform === "darwin") return "macos";
1445
- if (process.platform === "linux") return "linux";
1446
- }
1447
- const PUBLIC_REPO = "This repo is public, and machines never take jobs from public repos. There's nothing for init to set up here.";
1448
- const initCommand = defineCommand({
1449
- meta: {
1450
- name: "init",
1451
- description: "Route this repo's GitHub Actions jobs through RelayRunner, so they run on your machine when it's online. Edits workflow files; never commits."
1452
- },
1453
- args: {
1454
- plan: {
1455
- type: "boolean",
1456
- description: "List every job and whether it can be routed. Changes nothing."
1457
- },
1458
- apply: {
1459
- type: "string",
1460
- description: "Route these jobs without prompting: comma-separated ids or file:job, or `all` for every ready job"
1461
- },
1462
- json: {
1463
- type: "boolean",
1464
- description: "Print the result as JSON (with --plan or --apply)"
1465
- }
1466
- },
1467
- async run({ args }) {
1339
+ const image = jobImage(base, !options.image);
1340
+ mine.push(image);
1341
+ if (!await hasImage(image)) {
1342
+ log(`Building the job image from ${base}. This happens once per runner version…`);
1343
+ const context = mkdtempSync(join(tmpdir(), "relayrunner-image-"));
1468
1344
  try {
1469
- const plan = await planInit();
1470
- if (args.apply !== void 0) return apply(plan, args.apply, !!args.json);
1471
- if (args.plan || args.json) return printPlan(plan, !!args.json);
1472
- if (!process.stdin.isTTY) {
1473
- printPlan(plan, false);
1474
- console.log("\nRun `relayrunner init --apply <jobs>` to route jobs without prompts.");
1475
- return;
1476
- }
1477
- await interactive(plan);
1478
- } catch (error) {
1479
- if (!(error instanceof InitError)) throw error;
1480
- if (args.json) console.log(JSON.stringify({ error: error.message }, null, 2));
1481
- else console.error(error.message);
1482
- process.exitCode = 1;
1345
+ writeFileSync(join(context, "Dockerfile"), dockerfile(base, !options.image));
1346
+ writeFileSync(join(context, "start.sh"), START_SCRIPT);
1347
+ if (await tool([
1348
+ "build",
1349
+ "--progress",
1350
+ "plain",
1351
+ "--tag",
1352
+ image,
1353
+ context
1354
+ ]) !== 0) throw fail("ISOLATED_IMAGE", `Could not build the job image from ${base}.`);
1355
+ } finally {
1356
+ rmSync(context, {
1357
+ recursive: true,
1358
+ force: true
1359
+ });
1360
+ await tool(["builder", "stop"]);
1361
+ await tool(["builder", "delete"]);
1483
1362
  }
1484
1363
  }
1485
- });
1486
- function planJson(plan) {
1364
+ await pruneImages(options.managed ?? managedImagesFile(), [base, image], mine, tool, log);
1365
+ const size = vmSize(options.slots, options.size);
1366
+ log(`Each job runs in its own Linux VM with ${size.cpus} CPUs and ${size.memoryGb} GB of memory.`);
1367
+ if (localNetwork) log("Jobs can reach this Mac and your local network.");
1368
+ if (debug.path) log(`If something goes wrong, ${debug.path} has the details.`);
1487
1369
  return {
1488
- repo: plan.repo,
1489
- visibility: plan.visibility,
1490
- relay: RELAY_REF,
1491
- setUp: isSetUp(plan.jobs),
1492
- ...plan.visibility === "public" ? { refused: "public_repo" } : {},
1493
- jobs: plan.jobs,
1494
- errors: plan.errors
1370
+ command,
1371
+ image,
1372
+ localNetwork,
1373
+ debug,
1374
+ runnerVersion,
1375
+ ...size
1495
1376
  };
1496
1377
  }
1497
- function printPlan(plan, json) {
1498
- if (json) return console.log(JSON.stringify(planJson(plan), null, 2));
1499
- console.log(describeRepo(plan));
1500
- if (plan.visibility === "public") return console.log(PUBLIC_REPO);
1501
- if (!plan.files.length) return console.log("No workflows in .github/workflows.");
1502
- for (const [title, verdict] of [
1503
- ["Ready to route", "ready"],
1504
- ["Already routed", "routed"],
1505
- ["Skipped", "skipped"]
1506
- ]) {
1507
- const jobs = plan.jobs.filter((job) => job.verdict === verdict);
1508
- if (!jobs.length) continue;
1509
- console.log(`\n${title}`);
1510
- for (const job of jobs) console.log(` ${jobLine(job)}`);
1511
- }
1512
- for (const error of plan.errors) console.log(`\nCouldn't read ${error.file}: ${error.message}`);
1378
+ function managedImagesFile() {
1379
+ return join(relayrunnerHome(), "isolated-images.json");
1513
1380
  }
1514
- function apply(plan, list, json) {
1515
- if (plan.visibility === "public") throw new InitError(PUBLIC_REPO);
1516
- const names = list.split(",").map((name) => name.trim()).filter(Boolean);
1517
- if (!names.length) throw new InitError("Name the jobs to route, or `all`.");
1518
- const chosen = selectJobs(plan.jobs, names);
1519
- if (!chosen.length) throw new InitError("No jobs are ready to route.");
1520
- const changes = changesFor(plan, chosen);
1521
- writeChanges(plan.root, changes);
1522
- const routed = chosen.map(({ file, job, warnings }) => ({
1523
- file,
1524
- job,
1525
- warnings
1526
- }));
1527
- if (json) return console.log(JSON.stringify({
1528
- relay: RELAY_REF,
1529
- routed
1530
- }, null, 2));
1531
- for (const change of changes) console.log(`Updated ${change.file} (${change.jobs.map((job) => job.job).join(", ")})`);
1532
- console.log("Commit and push to start routing.");
1381
+ async function pruneImages(file, inUse, mine, tool, log) {
1382
+ const recorded = readList(file);
1383
+ for (const image of recorded) {
1384
+ if (inUse.includes(image)) continue;
1385
+ if (await tool([
1386
+ "image",
1387
+ "delete",
1388
+ image
1389
+ ]) === 0) log(`Removed the old image ${image}.`);
1390
+ }
1391
+ try {
1392
+ writeList(file, inUse.filter((image) => recorded.includes(image) || mine.includes(image)));
1393
+ } catch {}
1533
1394
  }
1534
- async function interactive(plan) {
1535
- clack.intro("RelayRunner init");
1536
- clack.log.info(describeRepo(plan));
1537
- if (plan.visibility === "public") return clack.outro(PUBLIC_REPO);
1538
- if (plan.visibility === "unknown") clack.log.warn("Couldn't check whether this repo is public. Machines only take jobs from private repos.");
1539
- for (const error of plan.errors) clack.log.warn(`Couldn't read ${error.file}: ${error.message}`);
1540
- if (!plan.files.length) return clack.outro("No workflows in .github/workflows.");
1541
- await chooseAndWrite(plan, (message) => clack.outro(message));
1395
+ function containerName(routeId) {
1396
+ return `relayrunner-${routeId.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
1542
1397
  }
1543
- /** Lists the jobs, lets the user pick, shows the diff and writes it. `finish` gets the last line. */
1544
- async function chooseAndWrite(plan, finish) {
1545
- const routed = plan.jobs.filter((job) => job.verdict === "routed");
1546
- const skipped = plan.jobs.filter((job) => job.verdict === "skipped");
1547
- const ready = plan.jobs.filter((job) => job.verdict === "ready");
1548
- if (routed.length) clack.note(routed.map(jobLine).join("\n"), "Already routed");
1549
- if (skipped.length) clack.note(skipped.map(jobLine).join("\n"), "Skipped");
1550
- if (!ready.length) return finish("No other jobs to route.");
1551
- const picked = await clack.multiselect({
1552
- message: "Route these jobs through RelayRunner?",
1553
- options: ready.map((job) => ({
1554
- value: job,
1555
- label: `${shortFile(job.file)} › ${job.job}`,
1556
- hint: [`${job.label} when your machine is offline`, ...job.warnings].join("; ")
1557
- })),
1558
- initialValues: ready,
1559
- required: false
1398
+ function runArgs(routeId, isolation) {
1399
+ return [
1400
+ "run",
1401
+ "--rm",
1402
+ "--name",
1403
+ containerName(routeId),
1404
+ "--cpus",
1405
+ String(isolation.cpus),
1406
+ "--memory",
1407
+ `${isolation.memoryGb}g`,
1408
+ "--progress",
1409
+ "none",
1410
+ "-e",
1411
+ "RUNNER_JIT_CONFIG",
1412
+ "-e",
1413
+ "ACTIONS_RUNNER_PRINT_LOG_TO_STDOUT=false",
1414
+ ...isolation.localNetwork ? ["-e", "RELAYRUNNER_LOCAL_NETWORK=1"] : [],
1415
+ "--user",
1416
+ "0",
1417
+ "--cap-add",
1418
+ "ALL",
1419
+ isolation.image,
1420
+ START_PATH
1421
+ ];
1422
+ }
1423
+ function isolatedLauncher(isolation) {
1424
+ const { command, debug } = isolation;
1425
+ return {
1426
+ start(run) {
1427
+ const name = containerName(run.routeId);
1428
+ const args = runArgs(run.routeId, isolation);
1429
+ debug.write(`$ ${command} ${args.join(" ")}`);
1430
+ const child = spawn(command, args, {
1431
+ env: {
1432
+ ...runnerEnv(),
1433
+ RUNNER_JIT_CONFIG: run.jitConfig
1434
+ },
1435
+ stdio: [
1436
+ "ignore",
1437
+ "pipe",
1438
+ "pipe"
1439
+ ]
1440
+ });
1441
+ child.once("error", (error) => debug.write(`${name}: ${error.message}`));
1442
+ child.once("close", (code, signal) => debug.write(`${name}: exit ${signal ?? code}`));
1443
+ return child;
1444
+ },
1445
+ async cleanup(run, clean) {
1446
+ if (clean) return;
1447
+ const args = [
1448
+ "delete",
1449
+ "--force",
1450
+ containerName(run.routeId)
1451
+ ];
1452
+ if (await call(command, args, debug) !== 0) await call(command, args, debug);
1453
+ }
1454
+ };
1455
+ }
1456
+ function call(command, args, debug, quiet = false) {
1457
+ return new Promise((resolve) => {
1458
+ const child = spawn(command, args, { stdio: [
1459
+ "ignore",
1460
+ "pipe",
1461
+ "pipe"
1462
+ ] });
1463
+ let output = "";
1464
+ const keep = (chunk) => {
1465
+ if (!quiet) output += chunk.toString();
1466
+ };
1467
+ child.stdout.on("data", keep);
1468
+ child.stderr.on("data", keep);
1469
+ const done = (code, extra = "") => {
1470
+ debug.write(`$ ${command} ${args.join(" ")}\n${output}${extra}exit ${code}`);
1471
+ resolve(code);
1472
+ };
1473
+ child.once("error", (error) => done(null, `${error.message}\n`));
1474
+ child.once("close", (code) => done(code));
1560
1475
  });
1561
- if (clack.isCancel(picked) || !picked.length) return finish("Nothing changed.");
1562
- const changes = changesFor(plan, picked);
1563
- for (const change of changes) console.log(`${colorDiff(unifiedDiff(change.before, change.after, change.file))}\n`);
1564
- const ok = await clack.confirm({ message: `Write ${changes.length === 1 ? "this change" : `these ${changes.length} changes`}?` });
1565
- if (clack.isCancel(ok) || !ok) return finish("Nothing changed.");
1566
- writeChanges(plan.root, changes);
1567
- const warned = picked.filter((job) => job.warnings.length);
1568
- if (warned.length) clack.note(warned.map((job) => `${job.job}: ${job.warnings.join("; ")}`).join("\n"), "Check before it runs on your machine");
1569
- finish(`Updated ${changes.map((change) => change.file).join(", ")}. Commit and push to start routing.`);
1570
1476
  }
1477
+ // repo.ts
1478
+ const WORKFLOWS_DIR = ".github/workflows";
1479
+ /** The nearest directory at or above `from` that holds a `.git`, or null outside a checkout. */
1480
+ function findRepoRoot(from = process.cwd()) {
1481
+ let dir = resolve(from);
1482
+ for (;;) {
1483
+ if (existsSync(join(dir, ".git"))) return dir;
1484
+ const parent = dirname(dir);
1485
+ if (parent === dir) return null;
1486
+ dir = parent;
1487
+ }
1488
+ }
1489
+ function readWorkflowFiles(root) {
1490
+ const dir = join(root, WORKFLOWS_DIR);
1491
+ if (!existsSync(dir)) return [];
1492
+ return readdirSync(dir).filter((name) => /\.ya?ml$/.test(name)).sort().map((name) => ({
1493
+ file: `${WORKFLOWS_DIR}/${name}`,
1494
+ source: readFileSync(join(dir, name), "utf8")
1495
+ }));
1496
+ }
1497
+ /** `owner/name` from a GitHub remote URL (https or ssh), or null for anything else. */
1498
+ function parseGitHubRemote(url) {
1499
+ const match = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url.trim());
1500
+ return match ? `${match[1]}/${match[2]}` : null;
1501
+ }
1502
+ function originRepo(root) {
1503
+ return new Promise((done) => {
1504
+ execFile("git", [
1505
+ "-C",
1506
+ root,
1507
+ "remote",
1508
+ "get-url",
1509
+ "origin"
1510
+ ], {
1511
+ timeout: 3e3,
1512
+ encoding: "utf8"
1513
+ }, (error, stdout) => done(error ? null : parseGitHubRemote(stdout)));
1514
+ });
1515
+ }
1516
+ /**
1517
+ * Asks GitHub without signing in. A public repo answers; a private one (or one that doesn't exist)
1518
+ * is a 404 to an anonymous caller. Anything else, such as no network or a rate limit, is unknown.
1519
+ */
1520
+ async function repoVisibility(repo, fetcher = fetch) {
1521
+ try {
1522
+ const response = await fetcher(`https://api.github.com/repos/${repo}`, {
1523
+ headers: {
1524
+ accept: "application/vnd.github+json",
1525
+ "user-agent": userAgent
1526
+ },
1527
+ signal: AbortSignal.timeout(5e3)
1528
+ });
1529
+ if (response.status === 404) return "private";
1530
+ if (!response.ok) return "unknown";
1531
+ return (await response.json()).private === false ? "public" : "private";
1532
+ } catch {
1533
+ return "unknown";
1534
+ }
1535
+ }
1536
+ // ../../packages/providers/src/prices.ts
1537
+ /** A provider's rates, and what one minute of each is per. */
1538
+ const RATES = {
1539
+ blacksmith: {
1540
+ linux: "vcpu",
1541
+ arm: "vcpu",
1542
+ windows: "vcpu",
1543
+ macos: "vcpu"
1544
+ },
1545
+ depot: {
1546
+ linux: "vcpu",
1547
+ arm: "vcpu",
1548
+ windows: "vcpu",
1549
+ macos: "vcpu"
1550
+ },
1551
+ warpbuild: {
1552
+ linux: "vcpu",
1553
+ arm: "vcpu",
1554
+ windows: "vcpu",
1555
+ macos: "vcpu"
1556
+ },
1557
+ ubicloud: {
1558
+ standard: "vcpu",
1559
+ premium: "vcpu"
1560
+ },
1561
+ github: {
1562
+ "linux-1-core": "runner",
1563
+ "linux-2-core": "runner",
1564
+ "linux-arm-2-core": "runner",
1565
+ "windows-2-core": "runner",
1566
+ "windows-arm-2-core": "runner",
1567
+ macos: "runner"
1568
+ }
1569
+ };
1570
+ /** The one rate a provider operators added has: a minute of any of its runners. */
1571
+ const ADDED_RATE = "runner";
1572
+ /**
1573
+ * Whether a provider has this rate: one RATES lists, or the per-runner rate of a provider RATES
1574
+ * doesn't price (the admin only records that one for providers operators added).
1575
+ */
1576
+ const isRate = (provider, rate) => Object.hasOwn(RATES, provider) ? Object.hasOwn(RATES[provider], rate) : rate === ADDED_RATE;
1577
+ const vcpu = (perRunner, vcpus) => perRunner / vcpus;
1578
+ const BASE_PRICES = [
1579
+ {
1580
+ provider: "blacksmith",
1581
+ rate: "linux",
1582
+ usd: vcpu(.004, 2),
1583
+ from: "2026-11-11"
1584
+ },
1585
+ {
1586
+ provider: "blacksmith",
1587
+ rate: "arm",
1588
+ usd: vcpu(.0025, 2),
1589
+ from: "2026-11-11"
1590
+ },
1591
+ {
1592
+ provider: "blacksmith",
1593
+ rate: "windows",
1594
+ usd: vcpu(.008, 2),
1595
+ from: "2026-11-11"
1596
+ },
1597
+ {
1598
+ provider: "blacksmith",
1599
+ rate: "macos",
1600
+ usd: vcpu(.08, 6),
1601
+ from: "2026-11-11"
1602
+ },
1603
+ {
1604
+ provider: "depot",
1605
+ rate: "linux",
1606
+ usd: vcpu(.006, 2),
1607
+ from: "2026-11-11"
1608
+ },
1609
+ {
1610
+ provider: "depot",
1611
+ rate: "arm",
1612
+ usd: vcpu(.006, 2),
1613
+ from: "2026-11-11"
1614
+ },
1615
+ {
1616
+ provider: "depot",
1617
+ rate: "windows",
1618
+ usd: vcpu(.008, 2),
1619
+ from: "2026-11-11"
1620
+ },
1621
+ {
1622
+ provider: "depot",
1623
+ rate: "macos",
1624
+ usd: vcpu(.08, 8),
1625
+ from: "2026-11-11"
1626
+ },
1627
+ {
1628
+ provider: "warpbuild",
1629
+ rate: "linux",
1630
+ usd: vcpu(.004, 2),
1631
+ from: "2026-11-11"
1632
+ },
1633
+ {
1634
+ provider: "warpbuild",
1635
+ rate: "arm",
1636
+ usd: vcpu(.003, 2),
1637
+ from: "2026-11-11"
1638
+ },
1639
+ {
1640
+ provider: "warpbuild",
1641
+ rate: "windows",
1642
+ usd: vcpu(.016, 4),
1643
+ from: "2026-11-11"
1644
+ },
1645
+ {
1646
+ provider: "warpbuild",
1647
+ rate: "macos",
1648
+ usd: vcpu(.08, 6),
1649
+ from: "2026-11-11"
1650
+ },
1651
+ {
1652
+ provider: "ubicloud",
1653
+ rate: "standard",
1654
+ usd: vcpu(8e-4, 2),
1655
+ from: "2023-01-01"
1656
+ },
1657
+ {
1658
+ provider: "ubicloud",
1659
+ rate: "standard",
1660
+ usd: vcpu(.001, 2),
1661
+ from: "2026-05-01"
1662
+ },
1663
+ {
1664
+ provider: "ubicloud",
1665
+ rate: "standard",
1666
+ usd: vcpu(.00125, 2),
1667
+ from: "2026-09-01"
1668
+ },
1669
+ {
1670
+ provider: "ubicloud",
1671
+ rate: "premium",
1672
+ usd: vcpu(.0016, 2),
1673
+ from: "2025-05-01"
1674
+ },
1675
+ {
1676
+ provider: "ubicloud",
1677
+ rate: "premium",
1678
+ usd: vcpu(.002, 2),
1679
+ from: "2026-09-01"
1680
+ },
1681
+ {
1682
+ provider: "github",
1683
+ rate: "linux-1-core",
1684
+ usd: .002,
1685
+ from: "2026-11-11"
1686
+ },
1687
+ {
1688
+ provider: "github",
1689
+ rate: "linux-2-core",
1690
+ usd: .006,
1691
+ from: "2026-11-11"
1692
+ },
1693
+ {
1694
+ provider: "github",
1695
+ rate: "linux-arm-2-core",
1696
+ usd: .005,
1697
+ from: "2026-11-11"
1698
+ },
1699
+ {
1700
+ provider: "github",
1701
+ rate: "windows-2-core",
1702
+ usd: .01,
1703
+ from: "2026-11-11"
1704
+ },
1705
+ {
1706
+ provider: "github",
1707
+ rate: "windows-arm-2-core",
1708
+ usd: .01,
1709
+ from: "2026-11-11"
1710
+ },
1711
+ {
1712
+ provider: "github",
1713
+ rate: "macos",
1714
+ usd: .062,
1715
+ from: "2026-11-11"
1716
+ }
1717
+ ];
1718
+ /** A UTC day (YYYY-MM-DD) as epoch ms at its midnight. */
1719
+ const dayMs = (day) => Date.parse(`${day}T00:00:00Z`);
1571
1720
  /**
1572
- * Whether `connect` should offer to set up this checkout: it's not public, nothing in it is routed
1573
- * yet, and at least one job could be.
1721
+ * Looks up price rows, leaving out any for a rate RATES doesn't list. Rows for the same rate and
1722
+ * day replace earlier ones in the list, so rows added on top of BASE_PRICES win.
1574
1723
  */
1575
- function shouldOfferSetup(plan) {
1576
- return plan.visibility !== "public" && !isSetUp(plan.jobs) && plan.jobs.some((job) => job.verdict === "ready");
1724
+ function priceBook(rows) {
1725
+ const byRate = /* @__PURE__ */ new Map();
1726
+ for (const row of rows) {
1727
+ if (!isRate(row.provider, row.rate)) continue;
1728
+ const key = `${row.provider}:${row.rate}`;
1729
+ const days = byRate.get(key) ?? /* @__PURE__ */ new Map();
1730
+ days.set(row.from, row);
1731
+ byRate.set(key, days);
1732
+ }
1733
+ const histories = new Map([...byRate].map(([key, days]) => [key, [...days.values()].sort((a, b) => a.from.localeCompare(b.from))]));
1734
+ const changes = /* @__PURE__ */ new Set();
1735
+ for (const history of histories.values()) for (const row of history.slice(1)) changes.add(dayMs(row.from));
1736
+ const history = (provider, rate) => histories.get(`${provider}:${rate}`) ?? [];
1737
+ return {
1738
+ usd(provider, rate, at) {
1739
+ let usd = null;
1740
+ for (const [i, row] of history(provider, rate).entries()) if (i === 0 || dayMs(row.from) <= at) usd = row.usd;
1741
+ return usd;
1742
+ },
1743
+ history,
1744
+ changes: [...changes].sort((a, b) => a - b)
1745
+ };
1577
1746
  }
1747
+ priceBook(BASE_PRICES);
1748
+ // ../../packages/providers/src/index.ts
1578
1749
  /**
1579
- * Run by `connect` before it goes online. Inside a repo that could use RelayRunner but doesn't
1580
- * yet, asks once whether to set it up (default no) and runs the same picker as `init`. A "no" is
1581
- * remembered for that repo, so later runs don't ask again; `relayrunner init` still works. Never
1582
- * throws: setup is a convenience, and `connect` goes online either way.
1750
+ * The hosted runner services a relay can send a job to. Each runs a job under the customer's own
1751
+ * account through its own GitHub App, which picks up any job queued with one of its labels, so
1752
+ * routing to one only means answering one of its labels. Each is a step in the runner order and an
1753
+ * input on the relay, both named by its id.
1583
1754
  */
1584
- async function offerSetup(cwd = process.cwd()) {
1585
- try {
1586
- const plan = await planInit(cwd).catch((error) => {
1587
- if (error instanceof InitError) return null;
1588
- throw error;
1589
- });
1590
- if (!plan || !shouldOfferSetup(plan)) return;
1591
- const key = plan.repo ?? plan.root;
1592
- if (isDeclined(key)) return;
1593
- const answer = await clack.confirm({
1594
- message: `Set up ${plan.repo ?? basename(plan.root)} to run its CI on this machine?`,
1595
- initialValue: false
1596
- });
1597
- if (clack.isCancel(answer)) return;
1598
- if (!answer) {
1599
- rememberDeclined(key);
1600
- clack.log.info("Not now. Run `relayrunner init` in this repo any time to set it up.");
1601
- return;
1602
- }
1603
- await chooseAndWrite(plan, (message) => clack.log.success(message));
1604
- } catch (error) {
1605
- clack.log.warn(`Couldn't check this repo's workflows: ${error instanceof Error ? error.message : String(error)}`);
1606
- }
1607
- }
1608
- function describeRepo(plan) {
1609
- if (!plan.repo) return `${plan.root} (no GitHub remote named origin)`;
1610
- return plan.visibility === "unknown" ? plan.repo : `${plan.repo} (${plan.visibility})`;
1611
- }
1612
- function jobLine(job) {
1613
- const name = `${shortFile(job.file)} › ${job.job}`;
1614
- if (job.verdict === "skipped") return `${name}: ${job.reason}`;
1615
- if (job.verdict === "routed") return name;
1616
- return `${name}: ${[`falls back to ${job.label}`, ...job.warnings].join("; ")}`;
1617
- }
1618
- function shortFile(file) {
1619
- return file.replace(/^\.github\/workflows\//, "");
1620
- }
1621
- function colorDiff(diff) {
1622
- return diff.split("\n").map((line) => line.startsWith("+") && !line.startsWith("+++") ? styleText("green", line) : line.startsWith("-") && !line.startsWith("---") ? styleText("red", line) : styleText("dim", line)).join("\n");
1623
- }
1624
- // machine-name.ts
1625
- const MAX_LENGTH = 64;
1626
- async function defaultMachineName(run$1 = run, system = platform(), host = hostname()) {
1627
- const names = [];
1628
- if (system === "darwin") for (const key of [
1629
- "HostName",
1630
- "ComputerName",
1631
- "LocalHostName"
1632
- ]) names.push(await run$1("scutil", ["--get", key]));
1633
- names.push(host.replace(/\.local$/i, ""));
1634
- return (names.find((name) => name?.trim()) ?? "").trim().slice(0, MAX_LENGTH);
1635
- }
1636
- // jit-config.ts
1637
- const GITHUB_HOSTS = [
1638
- /^github\.com$/,
1639
- /\.github\.com$/,
1640
- /\.githubusercontent\.com$/
1641
- ];
1642
- const FILES = [
1643
- ".runner",
1644
- ".credentials",
1645
- ".credentials_rsaparams"
1755
+ const HOSTED_PROVIDER_IDS = [
1756
+ "blacksmith",
1757
+ "depot",
1758
+ "namespace",
1759
+ "warpbuild",
1760
+ "ubicloud",
1761
+ "runs-on"
1646
1762
  ];
1647
- const URL_FIELDS = /* @__PURE__ */ new Set([
1648
- "serverurl",
1649
- "serverurlv2",
1650
- "githuburl",
1651
- "authorizationurl"
1652
- ]);
1653
- function checkJitConfig(encoded, routeId) {
1654
- let files;
1655
- try {
1656
- files = decodeJson(encoded);
1657
- if (!files || typeof files !== "object") throw new Error();
1658
- } catch {
1659
- return {
1660
- ok: false,
1661
- reason: "it isn't a runner config"
1662
- };
1663
- }
1664
- const names = Object.keys(files);
1665
- if (names.length !== FILES.length || !FILES.every((name) => names.includes(name))) return {
1666
- ok: false,
1667
- reason: `it holds ${names.join(", ") || "nothing"}, not GitHub's files`
1668
- };
1669
- const decoded = {};
1670
- for (const [name, value] of Object.entries(files)) {
1671
- if (typeof value !== "string") return {
1672
- ok: false,
1673
- reason: `${name} isn't a file`
1674
- };
1675
- try {
1676
- decoded[name] = decodeJson(value);
1677
- } catch {
1678
- return {
1679
- ok: false,
1680
- reason: `${name} isn't JSON`
1681
- };
1763
+ const LABEL_PREFIXES = {
1764
+ blacksmith: ["blacksmith-"],
1765
+ depot: ["depot-"],
1766
+ namespace: ["namespace-profile-", "nscloud-"],
1767
+ warpbuild: ["warp-"],
1768
+ ubicloud: ["ubicloud-"],
1769
+ "runs-on": ["runs-on=", "runs-on/"]
1770
+ };
1771
+ /** Whether a lowercase label starts with one of `prefixes`, or is the bare name one ends in `-`. */
1772
+ const matchesPrefix = (prefixes, lower) => prefixes.some((prefix) => lower.startsWith(prefix) || prefix.endsWith("-") && lower === prefix.slice(0, -1));
1773
+ const matches = (provider, lower) => matchesPrefix(LABEL_PREFIXES[provider], lower);
1774
+ /** The hosted provider whose runners a label asks for, or null. */
1775
+ function hostedProviderOf(label) {
1776
+ const lower = label.toLowerCase();
1777
+ return HOSTED_PROVIDER_IDS.find((id) => matches(id, lower)) ?? null;
1778
+ }
1779
+ // workflows.ts
1780
+ /** The relay version `init` writes. Bump it with each relayrunner/actions release. */
1781
+ const RELAY_REF = "v1.0.0-beta.5";
1782
+ const RELAY_WORKFLOW = "relayrunner/actions/.github/workflows/relay.yml";
1783
+ const DEPLOY_SECRET = /\bsecrets\.(?!GITHUB_TOKEN\b)[A-Za-z_][A-Za-z0-9_]*/;
1784
+ const LINUX_PACKAGE_MANAGER = /(^|[\s;&|(])(sudo\s+)?(apt-get|apt|yum|dnf|apk)\s+(install|update|add)\b/m;
1785
+ function analyzeWorkflows(files, options = {}) {
1786
+ const jobs = [];
1787
+ const errors = [];
1788
+ for (const { file, source } of files) {
1789
+ const doc = parseDocument(source);
1790
+ if (doc.errors.length) {
1791
+ errors.push({
1792
+ file,
1793
+ message: doc.errors[0].message.split("\n")[0]
1794
+ });
1795
+ continue;
1796
+ }
1797
+ const workflow = doc.toJS();
1798
+ if (!workflow || typeof workflow !== "object") continue;
1799
+ const all = workflow.jobs;
1800
+ if (!all || typeof all !== "object") continue;
1801
+ const relays = new Set(Object.entries(all).filter(([, job]) => isRelayJob(job)).map(([id]) => id));
1802
+ const reusableOnly = onlyWorkflowCall(workflow.on);
1803
+ for (const [id, raw] of Object.entries(all)) {
1804
+ if (!raw || typeof raw !== "object") continue;
1805
+ const job = raw;
1806
+ if (relays.has(id)) continue;
1807
+ jobs.push(judge(file, id, job, workflow, relays, reusableOnly, options));
1682
1808
  }
1683
1809
  }
1684
- const runner = decoded[".runner"];
1685
- if (!runner || typeof runner !== "object") return {
1686
- ok: false,
1687
- reason: "it has no .runner"
1810
+ return {
1811
+ jobs,
1812
+ errors
1688
1813
  };
1689
- const duplicate = duplicateKey(decoded);
1690
- if (duplicate) return {
1691
- ok: false,
1692
- reason: `it has ${duplicate} twice`
1814
+ }
1815
+ /** True when any job already runs where a relay sends it. */
1816
+ function isSetUp(jobs) {
1817
+ return jobs.some((job) => job.verdict === "routed");
1818
+ }
1819
+ function judge(file, id, job, workflow, relays, reusableOnly, options) {
1820
+ const base = {
1821
+ file,
1822
+ job: id,
1823
+ warnings: []
1693
1824
  };
1694
- for (const url of urls(decoded)) {
1695
- const parsed = URL.canParse(url) ? new URL(url) : null;
1696
- if (!parsed) return {
1697
- ok: false,
1698
- reason: `it names a URL that doesn't parse: ${url}`
1699
- };
1700
- if (parsed.protocol !== "https:" || !GITHUB_HOSTS.some((host) => host.test(parsed.hostname))) return {
1701
- ok: false,
1702
- reason: `it points the runner at ${parsed.origin}, not GitHub`
1825
+ const skip = (reason) => ({
1826
+ ...base,
1827
+ verdict: "skipped",
1828
+ reason
1829
+ });
1830
+ if (typeof job.uses === "string") return skip("calls a reusable workflow");
1831
+ if (reusableOnly) return skip("part of a reusable workflow; it runs wherever the calling workflow sends it");
1832
+ const runsOn = job["runs-on"];
1833
+ if (runsOn === void 0) return skip("has no runs-on");
1834
+ if (typeof runsOn !== "string") return skip("runs-on is a list of labels or a runner group");
1835
+ if (runsOn.includes("${{")) {
1836
+ const relay = /^\$\{\{\s*needs\.([\w-]+)\.outputs\.runner\s*\}\}$/.exec(runsOn.trim())?.[1];
1837
+ if (relay && relays.has(relay)) return {
1838
+ ...base,
1839
+ verdict: "routed"
1703
1840
  };
1841
+ return skip("runs-on is an expression");
1704
1842
  }
1705
- const field = (key) => {
1706
- const entry = Object.entries(runner).find(([name]) => name.toLowerCase() === key);
1707
- return typeof entry?.[1] === "string" ? entry[1] : null;
1708
- };
1709
- if (!field("serverurl") && !field("serverurlv2")) return {
1710
- ok: false,
1711
- reason: "it doesn't say which GitHub server to use"
1712
- };
1713
- const runnerName = field("agentname");
1714
- if (!runnerName || !isRunnerForRoute(runnerName, routeId)) return {
1715
- ok: false,
1716
- reason: `its runner ${runnerName ?? "(no name)"} isn't for job ${routeId}`
1717
- };
1843
+ if (hasMatrix(job)) return skip("uses a matrix, and one relay can't serve every leg");
1844
+ const deploy = deploySignal(job, workflow);
1845
+ if (deploy) return skip(`looks like a deploy job (${deploy})`);
1846
+ const label = runsOn.trim();
1847
+ const lower = label.toLowerCase();
1848
+ let provider;
1849
+ let machine = "self-hosted";
1850
+ const hosted = hostedProviderOf(lower);
1851
+ if (/(^|-)windows-/.test(lower)) return skip("Windows jobs can't run on machines yet");
1852
+ if (hosted) {
1853
+ provider = hosted;
1854
+ if (lower.includes("macos")) machine = "macOS";
1855
+ } else if (/^(ubuntu|macos)-/.test(lower)) {
1856
+ provider = "github";
1857
+ if (lower.startsWith("macos-")) machine = "macOS";
1858
+ } else if (lower === "relayrunner") return skip("already runs on RelayRunner");
1859
+ else if (lower === "self-hosted") return skip("already runs on a self-hosted runner");
1860
+ else return skip(`${label} isn't a GitHub-hosted or hosted provider label`);
1861
+ const warnings = jobWarnings(job, options);
1718
1862
  return {
1719
- ok: true,
1720
- target: target(field("githuburl"))
1863
+ ...base,
1864
+ verdict: "ready",
1865
+ provider,
1866
+ label,
1867
+ machine,
1868
+ warnings
1721
1869
  };
1722
1870
  }
1723
- function target(url) {
1724
- if (!url || !URL.canParse(url)) return null;
1725
- const path = new URL(url).pathname.split("/").filter(Boolean).slice(0, 2);
1726
- return path.length ? path.join("/") : null;
1727
- }
1728
- function urls(value, found = [], key = "") {
1729
- if (typeof value === "string") {
1730
- const text = value.trim();
1731
- if (text && (URL_FIELDS.has(key.toLowerCase()) || /^[a-z][a-z0-9+.-]*:/i.test(text))) found.push(text);
1732
- } else if (Array.isArray(value)) for (const item of value) urls(item, found);
1733
- else if (value && typeof value === "object") for (const [name, item] of Object.entries(value)) urls(item, found, name);
1734
- return found;
1871
+ function isRelayJob(job) {
1872
+ return typeof job?.uses === "string" && job.uses.split("@")[0] === "relayrunner/actions/.github/workflows/relay.yml";
1735
1873
  }
1736
- function duplicateKey(value) {
1737
- if (Array.isArray(value)) for (const item of value) {
1738
- const found = duplicateKey(item);
1739
- if (found) return found;
1874
+ function onlyWorkflowCall(on) {
1875
+ if (on === "workflow_call") return true;
1876
+ if (Array.isArray(on)) return on.length > 0 && on.every((event) => event === "workflow_call");
1877
+ if (on && typeof on === "object") {
1878
+ const events = Object.keys(on);
1879
+ return events.length > 0 && events.every((event) => event === "workflow_call");
1740
1880
  }
1741
- else if (value && typeof value === "object") {
1742
- const seen = /* @__PURE__ */ new Set();
1743
- for (const [name, item] of Object.entries(value)) {
1744
- if (seen.has(name.toLowerCase())) return name;
1745
- seen.add(name.toLowerCase());
1746
- const found = duplicateKey(item);
1747
- if (found) return found;
1881
+ return false;
1882
+ }
1883
+ function hasMatrix(job) {
1884
+ const strategy = job.strategy;
1885
+ return !!strategy && typeof strategy === "object" && strategy.matrix !== void 0;
1886
+ }
1887
+ function deploySignal(job, workflow) {
1888
+ if (job.environment !== void 0) return "environment";
1889
+ const permissions = job.permissions ?? workflow.permissions;
1890
+ if (permissions === "write-all") return "write-all permissions";
1891
+ if (permissions && typeof permissions === "object" && permissions["id-token"] === "write") return "id-token: write";
1892
+ const secret = DEPLOY_SECRET.exec(JSON.stringify(job))?.[0];
1893
+ if (secret) return `uses ${secret}`;
1894
+ return null;
1895
+ }
1896
+ function jobWarnings(job, options) {
1897
+ const warnings = [];
1898
+ const docker = !options.vm;
1899
+ if (docker && job.services !== void 0) warnings.push("uses services, which need Docker on the machine");
1900
+ if (docker && job.container !== void 0) warnings.push("runs in a container, which needs Docker on the machine");
1901
+ const steps = Array.isArray(job.steps) ? job.steps : [];
1902
+ const providerActions = /* @__PURE__ */ new Set();
1903
+ let packages = false;
1904
+ for (const step of steps) {
1905
+ if (!step || typeof step !== "object") continue;
1906
+ if (typeof step.run === "string" && LINUX_PACKAGE_MANAGER.test(step.run)) packages = true;
1907
+ if (typeof step.uses === "string") {
1908
+ const action = step.uses.split("@")[0];
1909
+ if (action.startsWith("useblacksmith/")) providerActions.add(action);
1910
+ if (docker && action.startsWith("docker://")) warnings.push("runs a Docker action, which needs Docker on the machine");
1748
1911
  }
1749
1912
  }
1750
- return null;
1913
+ if (packages && !options.vm && options.hostOs !== "linux") warnings.push(options.hostOs === "macos" ? "installs Linux packages (apt-get, yum or apk), which macOS doesn't have" : "installs Linux packages (apt-get, yum or apk)");
1914
+ for (const action of providerActions) warnings.push(`uses ${action}, which is made for Blacksmith runners`);
1915
+ return warnings;
1751
1916
  }
1752
- function decodeJson(base64) {
1753
- return JSON.parse(Buffer.from(base64, "base64").toString("utf8").replace(/^/, ""));
1917
+ /**
1918
+ * Routes the given jobs of one workflow file through the relay. Returns the new file contents.
1919
+ * Each job must have come back `ready` from analyzeWorkflows for this same source.
1920
+ */
1921
+ function routeJobs(source, jobs) {
1922
+ const doc = parseDocument(source);
1923
+ const all = doc.get("jobs");
1924
+ if (!isMap(all)) throw new Error("This workflow has no jobs map.");
1925
+ for (const job of jobs) {
1926
+ if (job.verdict !== "ready" || !job.provider || !job.label) throw new Error(`${job.job} isn't ready to route.`);
1927
+ routeJob(doc, all, job);
1928
+ }
1929
+ return doc.toString({
1930
+ lineWidth: 0,
1931
+ flowCollectionPadding: false
1932
+ });
1754
1933
  }
1755
- // job.ts
1756
- const runnerEnv = () => Object.fromEntries([
1757
- "HOME",
1758
- "USER",
1759
- "LOGNAME",
1760
- "PATH",
1761
- "LANG",
1762
- "LC_ALL",
1763
- "TMPDIR",
1764
- "SHELL"
1765
- ].flatMap((key) => process.env[key] === void 0 ? [] : [[key, process.env[key]]]));
1766
- async function runJob(run, options) {
1767
- const { launcher, report } = options;
1768
- const { routeId } = run;
1769
- const output = options.output ?? ((chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk));
1770
- const finish = (update) => {
1771
- report(update);
1772
- return update;
1773
- };
1774
- const failed = (message) => finish({
1775
- routeId,
1776
- state: "failed",
1777
- message
1934
+ function routeJob(doc, all, job) {
1935
+ const index = all.items.findIndex((pair) => isScalar(pair.key) && pair.key.value === job.job);
1936
+ const pair = all.items[index];
1937
+ if (!pair || !isMap(pair.value)) throw new Error(`No job ${job.job} in this workflow.`);
1938
+ const node = pair.value;
1939
+ const relayId = freeId(all, `relay-${job.job}`);
1940
+ const relay = doc.createNode({
1941
+ uses: `${RELAY_WORKFLOW}@${RELAY_REF}`,
1942
+ with: {
1943
+ machine: job.machine ?? "self-hosted",
1944
+ [job.provider]: job.label
1945
+ }
1778
1946
  });
1779
- const checked = checkJitConfig(run.jitConfig, routeId);
1780
- if (!checked.ok) return failed(`Refused the job's runner config: ${checked.reason}.`);
1781
- options.onChecked?.(checked.target);
1782
- let clean = false;
1783
- try {
1784
- const child = launcher.start(run);
1785
- child.stdout.on("data", (chunk) => output(chunk, "stdout"));
1786
- child.stderr.on("data", (chunk) => output(chunk, "stderr"));
1787
- const started = await new Promise((resolve) => {
1788
- child.once("spawn", () => resolve(null));
1789
- child.once("error", resolve);
1790
- });
1791
- if (started) return failed(`Could not start the runner: ${started.message}`);
1792
- report({
1793
- routeId,
1794
- state: "started"
1795
- });
1796
- const [code, signal] = await new Promise((resolve) => child.once("close", (code, signal) => resolve([code, signal])));
1797
- clean = code === 0;
1798
- if (clean) return finish({
1799
- routeId,
1800
- state: "finished"
1801
- });
1802
- return failed(signal ? `The runner was stopped by ${signal}` : `The runner exited with ${code}`);
1803
- } catch (error) {
1804
- return failed(error instanceof Error ? error.message : String(error));
1805
- } finally {
1806
- await launcher.cleanup(run, clean);
1947
+ const key = new Scalar(relayId);
1948
+ const jobKey = pair.key;
1949
+ key.spaceBefore = jobKey.spaceBefore;
1950
+ if (key.spaceBefore === void 0 && index > 0) key.spaceBefore = true;
1951
+ key.commentBefore = jobKey.commentBefore;
1952
+ jobKey.commentBefore = void 0;
1953
+ jobKey.spaceBefore = true;
1954
+ all.items.splice(index, 0, doc.createPair(key, relay));
1955
+ const runsOn = node.get("runs-on", true);
1956
+ const target = `\${{ needs.${relayId}.outputs.runner }}`;
1957
+ if (isScalar(runsOn)) {
1958
+ runsOn.value = target;
1959
+ runsOn.type = Scalar.PLAIN;
1960
+ } else node.set("runs-on", target);
1961
+ const needs = node.get("needs", true);
1962
+ if (needs === void 0) {
1963
+ const at = node.items.findIndex((item) => isScalar(item.key) && item.key.value === "runs-on");
1964
+ node.items.splice(Math.max(at, 0), 0, doc.createPair("needs", relayId));
1965
+ } else if (isSeq(needs)) needs.add(doc.createNode(relayId));
1966
+ else if (isScalar(needs)) {
1967
+ const list = new YAMLSeq();
1968
+ list.flow = true;
1969
+ list.add(doc.createNode(needs.value));
1970
+ list.add(doc.createNode(relayId));
1971
+ node.set("needs", list);
1807
1972
  }
1808
1973
  }
1809
- const JOB_STATE = [
1810
- "_work",
1811
- ".runner",
1812
- ".credentials",
1813
- ".credentials_rsaparams"
1814
- ];
1815
- function hostLauncher(dir) {
1816
- const lock = join(dir, "job.lock");
1817
- let locked = false;
1818
- return {
1819
- start(run) {
1820
- locked = takeLock(lock);
1821
- if (!locked) throw new Error(`Another job is using the runner in ${dir}.`);
1822
- clean(dir);
1823
- return spawn(join(dir, "run.sh"), ["--jitconfig", run.jitConfig], {
1824
- cwd: dir,
1825
- env: runnerEnv(),
1826
- stdio: [
1827
- "ignore",
1828
- "pipe",
1829
- "pipe"
1830
- ]
1831
- });
1832
- },
1833
- cleanup() {
1834
- if (!locked) return;
1835
- clean(dir);
1836
- rmSync(lock, { force: true });
1837
- locked = false;
1838
- }
1839
- };
1974
+ function freeId(all, wanted) {
1975
+ const taken = new Set(all.items.map((pair) => isScalar(pair.key) ? String(pair.key.value) : ""));
1976
+ if (!taken.has(wanted)) return wanted;
1977
+ for (let n = 2;; n++) if (!taken.has(`${wanted}-${n}`)) return `${wanted}-${n}`;
1840
1978
  }
1841
- function clean(dir) {
1842
- for (const name of JOB_STATE) rmSync(join(dir, name), {
1843
- recursive: true,
1844
- force: true
1979
+ // init.ts
1980
+ var InitError = class extends Error {};
1981
+ async function planInit(cwd = process.cwd(), options = {}) {
1982
+ const root = findRepoRoot(cwd);
1983
+ if (!root) throw new InitError("Not in a git checkout. Run `relayrunner init` inside a repo.");
1984
+ const repo = await originRepo(root);
1985
+ const visibility = repo ? await repoVisibility(repo, options.fetcher) : "unknown";
1986
+ const files = readWorkflowFiles(root);
1987
+ const { jobs, errors } = analyzeWorkflows(files, options.hostOs ? options : {
1988
+ hostOs: hostOs(),
1989
+ vm: await isolationState() === "ready"
1845
1990
  });
1991
+ return {
1992
+ root,
1993
+ repo,
1994
+ visibility,
1995
+ files,
1996
+ jobs,
1997
+ errors
1998
+ };
1846
1999
  }
1847
- function takeLock(lock) {
1848
- for (let attempt = 0; attempt < 2; attempt++) try {
1849
- symlinkSync(String(process.pid), lock);
1850
- return true;
1851
- } catch (error) {
1852
- if (error.code !== "EEXIST") throw error;
1853
- if (isAlive(Number(readlinkSync(lock)))) return false;
1854
- rmSync(lock, { force: true });
1855
- }
1856
- return false;
1857
- }
1858
- function isAlive(pid) {
1859
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
1860
- try {
1861
- process.kill(pid, 0);
1862
- return true;
1863
- } catch (error) {
1864
- return error.code === "EPERM";
2000
+ /** Picks jobs by `job`, `file:job` or `all`. Throws when a name is unknown, ambiguous or not ready. */
2001
+ function selectJobs(jobs, names) {
2002
+ const ready = jobs.filter((job) => job.verdict === "ready");
2003
+ if (names.length === 1 && names[0] === "all") return ready;
2004
+ const picked = /* @__PURE__ */ new Map();
2005
+ for (const name of names) {
2006
+ const [file, id] = name.includes(":") ? name.split(/:(?=[^:]*$)/) : [void 0, name];
2007
+ const matches = jobs.filter((job) => job.job === id && (!file || job.file === file || shortFile(job.file) === file));
2008
+ if (!matches.length) throw new InitError(`No job named ${name}.`);
2009
+ if (matches.length > 1) throw new InitError(`${name} is in more than one workflow. Name it as ${matches.map((job) => `${job.file}:${job.job}`).join(" or ")}.`);
2010
+ const job = matches[0];
2011
+ if (job.verdict === "routed") throw new InitError(`${name} is already routed.`);
2012
+ if (job.verdict === "skipped") throw new InitError(`${name} can't be routed: ${job.reason}.`);
2013
+ picked.set(`${job.file}:${job.job}`, job);
1865
2014
  }
2015
+ return [...picked.values()];
1866
2016
  }
1867
- function prefixLines(prefix, write) {
1868
- const partial = {
1869
- stdout: "",
1870
- stderr: ""
1871
- };
1872
- const output = (chunk, stream) => {
1873
- const text = partial[stream] + chunk.toString();
1874
- const end = text.lastIndexOf("\n") + 1;
1875
- partial[stream] = text.slice(end);
1876
- if (end === 0) return;
1877
- const lines = text.slice(0, end).replace(/^(?=.)/gm, prefix);
1878
- write(Buffer.from(lines), stream);
1879
- };
1880
- const flush = () => {
1881
- for (const stream of ["stdout", "stderr"]) {
1882
- if (partial[stream]) write(Buffer.from(`${prefix}${partial[stream]}\n`), stream);
1883
- partial[stream] = "";
1884
- }
1885
- };
1886
- return {
1887
- output,
1888
- flush
1889
- };
2017
+ /** The new contents of each workflow file the chosen jobs live in. */
2018
+ function changesFor(plan, chosen) {
2019
+ const byFile = /* @__PURE__ */ new Map();
2020
+ for (const job of chosen) byFile.set(job.file, [...byFile.get(job.file) ?? [], job]);
2021
+ return [...byFile].map(([file, jobs]) => {
2022
+ const before = plan.files.find((entry) => entry.file === file).source;
2023
+ return {
2024
+ file,
2025
+ jobs,
2026
+ before,
2027
+ after: routeJobs(before, jobs)
2028
+ };
2029
+ });
1890
2030
  }
1891
- // isolated.ts
1892
- const RUNNER_IMAGE = "ghcr.io/actions/actions-runner";
1893
- const RELEASES = "https://github.com/apple/container/releases";
1894
- function unsupportedReason(system = platform(), chip = arch(), darwin = release()) {
1895
- if (system !== "darwin") return "--isolated needs a Mac with Apple silicon and macOS 26 or later.";
1896
- if (chip !== "arm64") return "--isolated needs a Mac with Apple silicon. This one has an Intel chip.";
1897
- if (Number.parseInt(darwin, 10) < 25) return "--isolated needs macOS 26 or later. Update macOS, then try again.";
1898
- return null;
2031
+ function writeChanges(root, changes) {
2032
+ for (const change of changes) writeFileSync(join(root, change.file), change.after);
1899
2033
  }
1900
- async function isolationAvailable(command = "container", reason = unsupportedReason()) {
1901
- return reason === null && await call(command, ["--version"], NO_LOG, true) === 0;
2034
+ function hostOs() {
2035
+ if (process.platform === "darwin") return "macos";
2036
+ if (process.platform === "linux") return "linux";
1902
2037
  }
1903
- function debugLog(path = join(relayrunnerHome(), "isolated.log")) {
1904
- const home = homedir();
1905
- const write = (text, flag = "a") => {
2038
+ const PUBLIC_REPO = "This repo is public, and machines never take jobs from public repos. There's nothing for init to set up here.";
2039
+ const initCommand = defineCommand({
2040
+ meta: {
2041
+ name: "init",
2042
+ description: "Route this repo's GitHub Actions jobs through RelayRunner, so they run on your machine when it's online. Edits workflow files; never commits."
2043
+ },
2044
+ args: {
2045
+ plan: {
2046
+ type: "boolean",
2047
+ description: "List every job and whether it can be routed. Changes nothing."
2048
+ },
2049
+ apply: {
2050
+ type: "string",
2051
+ description: "Route these jobs without prompting: comma-separated ids or file:job, or `all` for every ready job"
2052
+ },
2053
+ json: {
2054
+ type: "boolean",
2055
+ description: "Print the result as JSON (with --plan or --apply)"
2056
+ }
2057
+ },
2058
+ async run({ args }) {
1906
2059
  try {
1907
- const stamped = `${(/* @__PURE__ */ new Date()).toISOString()} ${text.trimEnd().replaceAll(home, "~")}\n`;
1908
- if (flag === "w") {
1909
- rmSync(path, { force: true });
1910
- writeFileSync(path, stamped, { mode: 384 });
1911
- } else appendFileSync(path, stamped);
1912
- } catch {}
1913
- };
1914
- try {
1915
- mkdirSync(dirname(path), { recursive: true });
1916
- } catch {}
1917
- write(`relayrunner ${cliVersion}, ${platform()} ${release()} ${arch()}, ${availableParallelism()} cores, ${Math.round(totalmem() / 1024 ** 3)} GB`, "w");
2060
+ const plan = await planInit();
2061
+ if (args.apply !== void 0) return apply(plan, args.apply, !!args.json);
2062
+ if (args.plan || args.json) return printPlan(plan, !!args.json);
2063
+ if (!process.stdin.isTTY) {
2064
+ printPlan(plan, false);
2065
+ console.log("\nRun `relayrunner init --apply <jobs>` to route jobs without prompts.");
2066
+ return;
2067
+ }
2068
+ await interactive(plan);
2069
+ } catch (error) {
2070
+ if (!(error instanceof InitError)) throw error;
2071
+ if (args.json) console.log(JSON.stringify({ error: error.message }, null, 2));
2072
+ else console.error(error.message);
2073
+ process.exitCode = 1;
2074
+ }
2075
+ }
2076
+ });
2077
+ function planJson(plan) {
1918
2078
  return {
1919
- path,
1920
- write
2079
+ repo: plan.repo,
2080
+ visibility: plan.visibility,
2081
+ relay: RELAY_REF,
2082
+ setUp: isSetUp(plan.jobs),
2083
+ ...plan.visibility === "public" ? { refused: "public_repo" } : {},
2084
+ jobs: plan.jobs,
2085
+ errors: plan.errors
1921
2086
  };
1922
2087
  }
1923
- const NO_LOG = {
1924
- path: "",
1925
- write: () => {}
1926
- };
1927
- const START_SCRIPT = `#!/bin/sh
1928
- set -eu
1929
- drop=""
1930
- if [ "\${RELAYRUNNER_LOCAL_NETWORK:-}" != 1 ]; then
1931
- drop="--bounding-set -net_admin,-net_raw"
1932
- dns=$(awk '$1 == "nameserver" && $2 ~ /^[0-9.]+$/ { printf "%s%s", sep, $2; sep = ", " }' /etc/resolv.conf)
1933
- allow_dns=""
1934
- [ -z "$dns" ] || allow_dns="ip daddr { $dns } meta l4proto { tcp, udp } th dport 53 accept"
1935
- nft -f - <<EOF
1936
- table inet relayrunner {
1937
- chain private {
1938
- oifname { "lo", "docker0" } accept
1939
- oifname "br-*" accept
1940
- $allow_dns
1941
- ip daddr { 10.0.0.0/8, 100.64.0.0/10, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16 } drop
1942
- meta nfproto ipv6 drop
1943
- }
1944
- chain out {
1945
- type filter hook output priority 0; policy accept;
1946
- jump private
1947
- }
1948
- chain forward {
1949
- type filter hook forward priority 0; policy accept;
1950
- jump private
1951
- }
2088
+ function printPlan(plan, json) {
2089
+ if (json) return console.log(JSON.stringify(planJson(plan), null, 2));
2090
+ console.log(describeRepo(plan));
2091
+ if (plan.visibility === "public") return console.log(PUBLIC_REPO);
2092
+ if (!plan.files.length) return console.log("No workflows in .github/workflows.");
2093
+ for (const [title, verdict] of [
2094
+ ["Ready to route", "ready"],
2095
+ ["Already routed", "routed"],
2096
+ ["Skipped", "skipped"]
2097
+ ]) {
2098
+ const jobs = plan.jobs.filter((job) => job.verdict === verdict);
2099
+ if (!jobs.length) continue;
2100
+ console.log(`\n${title}`);
2101
+ for (const job of jobs) console.log(` ${jobLine(job)}`);
2102
+ }
2103
+ for (const error of plan.errors) console.log(`\nCouldn't read ${error.file}: ${error.message}`);
1952
2104
  }
1953
- EOF
1954
- fi
1955
- # Docker sets kernel network settings under /proc/sys, which starts read-only. A job without
1956
- # Docker loses nothing if it can't start, so failures here only reach the Docker log.
1957
- if command -v dockerd >/dev/null 2>&1; then
1958
- mount -o remount,rw /proc/sys 2>/dev/null || true
1959
- dockerd >/var/log/dockerd.log 2>&1 &
1960
- tries=0
1961
- until docker info >/dev/null 2>&1 || [ "$tries" -ge 50 ]; do
1962
- tries=$((tries + 1))
1963
- sleep 0.2
1964
- done
1965
- fi
1966
- # A new VM's DNS answers nothing for its first 2 seconds or so, and a lookup sent then waits 5
1967
- # seconds to ask again. So the runner starts once a lookup gets through, or after 5 tries.
1968
- tries=0
1969
- until RES_OPTIONS="timeout:1 attempts:1" getent hosts github.com >/dev/null 2>&1 || [ "$tries" -ge 4 ]; do
1970
- tries=$((tries + 1))
1971
- done
1972
- cd /home/runner
1973
- # With arguments, runs them in place of the runner, to check the VM by hand.
1974
- [ $# -gt 0 ] || set -- ./run.sh --jitconfig "$RUNNER_JIT_CONFIG"
1975
- exec setpriv --reuid runner --regid runner --init-groups $drop \\
1976
- env HOME=/home/runner USER=runner LOGNAME=runner "$@"
1977
- `;
1978
- const START_PATH = "/usr/local/bin/relayrunner-start";
1979
- function dockerfile(base) {
1980
- return `FROM ${base}
1981
- USER root
1982
- RUN apt-get update && apt-get install -y --no-install-recommends iptables nftables && apt-get clean
1983
- COPY --chmod=755 start.sh ${START_PATH}
1984
- `;
2105
+ function apply(plan, list, json) {
2106
+ if (plan.visibility === "public") throw new InitError(PUBLIC_REPO);
2107
+ const names = list.split(",").map((name) => name.trim()).filter(Boolean);
2108
+ if (!names.length) throw new InitError("Name the jobs to route, or `all`.");
2109
+ const chosen = selectJobs(plan.jobs, names);
2110
+ if (!chosen.length) throw new InitError("No jobs are ready to route.");
2111
+ const changes = changesFor(plan, chosen);
2112
+ writeChanges(plan.root, changes);
2113
+ const routed = chosen.map(({ file, job, warnings }) => ({
2114
+ file,
2115
+ job,
2116
+ warnings
2117
+ }));
2118
+ if (json) return console.log(JSON.stringify({
2119
+ relay: RELAY_REF,
2120
+ routed
2121
+ }, null, 2));
2122
+ for (const change of changes) console.log(`Updated ${change.file} (${change.jobs.map((job) => job.job).join(", ")})`);
2123
+ console.log("Commit and push to start routing.");
1985
2124
  }
1986
- function jobImage(base) {
1987
- return `relayrunner-runner:${createHash("sha256").update(dockerfile(base)).update(START_SCRIPT).digest("hex").slice(0, 12)}`;
2125
+ async function interactive(plan) {
2126
+ clack.intro("RelayRunner init");
2127
+ clack.log.info(describeRepo(plan));
2128
+ if (plan.visibility === "public") return clack.outro(PUBLIC_REPO);
2129
+ if (plan.visibility === "unknown") clack.log.warn("Couldn't check whether this repo is public. Machines only take jobs from private repos.");
2130
+ for (const error of plan.errors) clack.log.warn(`Couldn't read ${error.file}: ${error.message}`);
2131
+ if (!plan.files.length) return clack.outro("No workflows in .github/workflows.");
2132
+ await chooseAndWrite(plan, (message) => clack.outro(message));
2133
+ }
2134
+ /** Lists the jobs, lets the user pick, shows the diff and writes it. `finish` gets the last line. */
2135
+ async function chooseAndWrite(plan, finish) {
2136
+ const routed = plan.jobs.filter((job) => job.verdict === "routed");
2137
+ const skipped = plan.jobs.filter((job) => job.verdict === "skipped");
2138
+ const ready = plan.jobs.filter((job) => job.verdict === "ready");
2139
+ if (routed.length) clack.note(routed.map(jobLine).join("\n"), "Already routed");
2140
+ if (skipped.length) clack.note(skipped.map(jobLine).join("\n"), "Skipped");
2141
+ if (!ready.length) return finish("No other jobs to route.");
2142
+ const picked = await clack.multiselect({
2143
+ message: "Route these jobs through RelayRunner?",
2144
+ options: ready.map((job) => ({
2145
+ value: job,
2146
+ label: `${shortFile(job.file)} › ${job.job}`,
2147
+ hint: [`${job.label} when your machine is offline`, ...job.warnings].join("; ")
2148
+ })),
2149
+ initialValues: ready,
2150
+ required: false
2151
+ });
2152
+ if (clack.isCancel(picked) || !picked.length) return finish("Nothing changed.");
2153
+ const changes = changesFor(plan, picked);
2154
+ for (const change of changes) console.log(`${colorDiff(unifiedDiff(change.before, change.after, change.file))}\n`);
2155
+ const ok = await clack.confirm({ message: `Write ${changes.length === 1 ? "this change" : `these ${changes.length} changes`}?` });
2156
+ if (clack.isCancel(ok) || !ok) return finish("Nothing changed.");
2157
+ writeChanges(plan.root, changes);
2158
+ const warned = picked.filter((job) => job.warnings.length);
2159
+ if (warned.length) clack.note(warned.map((job) => `${job.job}: ${job.warnings.join("; ")}`).join("\n"), "Check before it runs on your machine");
2160
+ finish(`Updated ${changes.map((change) => change.file).join(", ")}. Commit and push to start routing.`);
1988
2161
  }
1989
- function vmSize(slots, cores = availableParallelism(), memoryBytes = totalmem()) {
1990
- const gb = memoryBytes / 1024 ** 3;
1991
- return {
1992
- cpus: Math.max(2, Math.floor(cores / slots)),
1993
- memoryGb: Math.min(16, Math.max(2, Math.floor(gb / 2 / slots)))
1994
- };
2162
+ /**
2163
+ * Whether `connect` should offer to set up this checkout: it's not public, nothing in it is routed
2164
+ * yet, and at least one job could be.
2165
+ */
2166
+ function shouldOfferSetup(plan) {
2167
+ return plan.visibility !== "public" && !isSetUp(plan.jobs) && plan.jobs.some((job) => job.verdict === "ready");
1995
2168
  }
1996
- async function prepareIsolation(options) {
1997
- const command = options.command ?? "container";
1998
- const log = options.log ?? (() => {});
1999
- const debug = options.debug ?? NO_LOG;
2000
- const localNetwork = options.localNetwork ?? false;
2001
- const tool = (args) => call(command, args, debug);
2002
- const hasImage = async (image) => await call(command, [
2003
- "image",
2004
- "inspect",
2005
- image
2006
- ], debug, true) === 0;
2007
- const fail = (code, message) => new RunnerError(code, debug.path ? `${message} Details are in ${debug.path}.` : message);
2008
- const latest = latestRunnerVersion(log);
2009
- latest.catch(() => {});
2010
- const [status] = await Promise.all([tool(["system", "status"]), tool(["--version"])]);
2011
- if (status === null) throw new RunnerError("ISOLATED_SETUP", `--isolated needs Apple's container tool. Install it from ${RELEASES}, then run \`container system start\`.`);
2012
- if (status !== 0) throw fail("ISOLATED_SETUP", "Apple's container tool isn't running. Run `container system start`, then try again.");
2013
- const runnerVersion = await latest;
2014
- const base = options.image ?? `${RUNNER_IMAGE}:${runnerVersion}`;
2015
- const mine = [];
2016
- if (!await hasImage(base)) {
2017
- log(`Downloading ${base}. This happens once per runner version…`);
2018
- if (await tool([
2019
- "image",
2020
- "pull",
2021
- base
2022
- ]) !== 0) throw fail("ISOLATED_IMAGE", `Could not download ${base}.`);
2023
- if (!options.image) mine.push(base);
2024
- }
2025
- const image = jobImage(base);
2026
- mine.push(image);
2027
- if (!await hasImage(image)) {
2028
- log(`Building the job image from ${base}. This happens once per runner version…`);
2029
- const context = mkdtempSync(join(tmpdir(), "relayrunner-image-"));
2030
- try {
2031
- writeFileSync(join(context, "Dockerfile"), dockerfile(base));
2032
- writeFileSync(join(context, "start.sh"), START_SCRIPT);
2033
- if (await tool([
2034
- "build",
2035
- "--progress",
2036
- "plain",
2037
- "--tag",
2038
- image,
2039
- context
2040
- ]) !== 0) throw fail("ISOLATED_IMAGE", `Could not build the job image from ${base}.`);
2041
- } finally {
2042
- rmSync(context, {
2043
- recursive: true,
2044
- force: true
2045
- });
2046
- await tool(["builder", "stop"]);
2047
- await tool(["builder", "delete"]);
2169
+ /**
2170
+ * Run by `connect` before it goes online. Inside a repo that could use RelayRunner but doesn't
2171
+ * yet, asks once whether to set it up (default no) and runs the same picker as `init`. A "no" is
2172
+ * remembered for that repo, so later runs don't ask again; `relayrunner init` still works. Never
2173
+ * throws: setup is a convenience, and `connect` goes online either way.
2174
+ */
2175
+ async function offerSetup(cwd = process.cwd()) {
2176
+ try {
2177
+ const plan = await planInit(cwd).catch((error) => {
2178
+ if (error instanceof InitError) return null;
2179
+ throw error;
2180
+ });
2181
+ if (!plan || !shouldOfferSetup(plan)) return;
2182
+ const key = plan.repo ?? plan.root;
2183
+ if (isDeclined(key)) return;
2184
+ const answer = await clack.confirm({
2185
+ message: `Set up ${plan.repo ?? basename(plan.root)} to run its CI on this machine?`,
2186
+ initialValue: false
2187
+ });
2188
+ if (clack.isCancel(answer)) return;
2189
+ if (!answer) {
2190
+ rememberDeclined(key);
2191
+ clack.log.info("Not now. Run `relayrunner init` in this repo any time to set it up.");
2192
+ return;
2048
2193
  }
2194
+ await chooseAndWrite(plan, (message) => clack.log.success(message));
2195
+ } catch (error) {
2196
+ clack.log.warn(`Couldn't check this repo's workflows: ${error instanceof Error ? error.message : String(error)}`);
2049
2197
  }
2050
- await pruneImages(options.managed ?? managedImagesFile(), [base, image], mine, tool, log);
2051
- const size = vmSize(options.slots);
2052
- log(`Each job runs in its own Linux VM with ${size.cpus} CPUs and ${size.memoryGb} GB of memory.`);
2053
- if (localNetwork) log("Jobs can reach this Mac and your local network.");
2054
- if (debug.path) log(`If something goes wrong, ${debug.path} has the details.`);
2055
- return {
2056
- command,
2057
- image,
2058
- localNetwork,
2059
- debug,
2060
- runnerVersion,
2061
- ...size
2062
- };
2063
- }
2064
- function managedImagesFile() {
2065
- return join(relayrunnerHome(), "isolated-images.json");
2066
2198
  }
2067
- async function pruneImages(file, inUse, mine, tool, log) {
2068
- const recorded = readList(file);
2069
- for (const image of recorded) {
2070
- if (inUse.includes(image)) continue;
2071
- if (await tool([
2072
- "image",
2073
- "delete",
2074
- image
2075
- ]) === 0) log(`Removed the old image ${image}.`);
2076
- }
2077
- try {
2078
- writeList(file, inUse.filter((image) => recorded.includes(image) || mine.includes(image)));
2079
- } catch {}
2199
+ function describeRepo(plan) {
2200
+ if (!plan.repo) return `${plan.root} (no GitHub remote named origin)`;
2201
+ return plan.visibility === "unknown" ? plan.repo : `${plan.repo} (${plan.visibility})`;
2080
2202
  }
2081
- function containerName(routeId) {
2082
- return `relayrunner-${routeId.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
2203
+ function jobLine(job) {
2204
+ const name = `${shortFile(job.file)} › ${job.job}`;
2205
+ if (job.verdict === "skipped") return `${name}: ${job.reason}`;
2206
+ if (job.verdict === "routed") return name;
2207
+ return `${name}: ${[`falls back to ${job.label}`, ...job.warnings].join("; ")}`;
2083
2208
  }
2084
- function runArgs(routeId, isolation) {
2085
- return [
2086
- "run",
2087
- "--rm",
2088
- "--name",
2089
- containerName(routeId),
2090
- "--cpus",
2091
- String(isolation.cpus),
2092
- "--memory",
2093
- `${isolation.memoryGb}g`,
2094
- "--progress",
2095
- "none",
2096
- "-e",
2097
- "RUNNER_JIT_CONFIG",
2098
- "-e",
2099
- "ACTIONS_RUNNER_PRINT_LOG_TO_STDOUT=false",
2100
- ...isolation.localNetwork ? ["-e", "RELAYRUNNER_LOCAL_NETWORK=1"] : [],
2101
- "--user",
2102
- "0",
2103
- "--cap-add",
2104
- "ALL",
2105
- isolation.image,
2106
- START_PATH
2107
- ];
2209
+ function shortFile(file) {
2210
+ return file.replace(/^\.github\/workflows\//, "");
2108
2211
  }
2109
- function isolatedLauncher(isolation) {
2110
- const { command, debug } = isolation;
2111
- return {
2112
- start(run) {
2113
- const name = containerName(run.routeId);
2114
- const args = runArgs(run.routeId, isolation);
2115
- debug.write(`$ ${command} ${args.join(" ")}`);
2116
- const child = spawn(command, args, {
2117
- env: {
2118
- ...runnerEnv(),
2119
- RUNNER_JIT_CONFIG: run.jitConfig
2120
- },
2121
- stdio: [
2122
- "ignore",
2123
- "pipe",
2124
- "pipe"
2125
- ]
2126
- });
2127
- child.once("error", (error) => debug.write(`${name}: ${error.message}`));
2128
- child.once("close", (code, signal) => debug.write(`${name}: exit ${signal ?? code}`));
2129
- return child;
2130
- },
2131
- async cleanup(run, clean) {
2132
- if (clean) return;
2133
- const args = [
2134
- "delete",
2135
- "--force",
2136
- containerName(run.routeId)
2137
- ];
2138
- if (await call(command, args, debug) !== 0) await call(command, args, debug);
2139
- }
2140
- };
2212
+ function colorDiff(diff) {
2213
+ return diff.split("\n").map((line) => line.startsWith("+") && !line.startsWith("+++") ? styleText("green", line) : line.startsWith("-") && !line.startsWith("---") ? styleText("red", line) : styleText("dim", line)).join("\n");
2141
2214
  }
2142
- function call(command, args, debug, quiet = false) {
2143
- return new Promise((resolve) => {
2144
- const child = spawn(command, args, { stdio: [
2145
- "ignore",
2146
- "pipe",
2147
- "pipe"
2148
- ] });
2149
- let output = "";
2150
- const keep = (chunk) => {
2151
- if (!quiet) output += chunk.toString();
2152
- };
2153
- child.stdout.on("data", keep);
2154
- child.stderr.on("data", keep);
2155
- const done = (code, extra = "") => {
2156
- debug.write(`$ ${command} ${args.join(" ")}\n${output}${extra}exit ${code}`);
2157
- resolve(code);
2158
- };
2159
- child.once("error", (error) => done(null, `${error.message}\n`));
2160
- child.once("close", (code) => done(code));
2161
- });
2215
+ // machine-name.ts
2216
+ const MAX_LENGTH = 64;
2217
+ async function defaultMachineName(run$1 = run, system = platform(), host = hostname()) {
2218
+ const names = [];
2219
+ if (system === "darwin") for (const key of [
2220
+ "HostName",
2221
+ "ComputerName",
2222
+ "LocalHostName"
2223
+ ]) names.push(await run$1("scutil", ["--get", key]));
2224
+ names.push(host.replace(/\.local$/i, ""));
2225
+ return (names.find((name) => name?.trim()) ?? "").trim().slice(0, MAX_LENGTH);
2162
2226
  }
2163
2227
  // live.ts
2164
2228
  const INITIAL_STATE = {
@@ -2657,6 +2721,124 @@ async function setSharing(options) {
2657
2721
  sharing: parsed.data.machine.sharing
2658
2722
  };
2659
2723
  }
2724
+ // firewall.ts
2725
+ const ANCHOR = "com.apple/relayrunner";
2726
+ const LABEL = "app.relayrunner.firewall";
2727
+ const RULES_FILE = "/etc/pf.anchors/app.relayrunner";
2728
+ const DAEMON_FILE = `/Library/LaunchDaemons/${LABEL}.plist`;
2729
+ const VM_NETWORK = "192.168.64.0/24";
2730
+ const VM_GATEWAY = "192.168.64.1";
2731
+ const DEFAULT_INTERFACE = "bridge100";
2732
+ function vmInterface(interfaces = networkInterfaces()) {
2733
+ for (const [name, addresses] of Object.entries(interfaces)) if (addresses?.some((address) => address.address === VM_GATEWAY)) return name;
2734
+ return DEFAULT_INTERFACE;
2735
+ }
2736
+ function firewallRules(iface) {
2737
+ return `pass in quick on ${iface} proto udp from any port 68 to any port 67
2738
+ block drop in quick on ${iface} inet from ! ${VM_NETWORK} to any
2739
+ pass in quick on ${iface} proto { udp, tcp } from ${VM_NETWORK} to ${VM_GATEWAY} port 53
2740
+ block drop in quick on ${iface} inet to { 10.0.0.0/8, 100.64.0.0/10, 169.254.0.0/16, 172.16.0.0/12, 192.168.0.0/16 }
2741
+ pass in quick on ${iface} inet6 proto icmp6 icmp6-type { neighbrsol, neighbradv, routersol }
2742
+ block drop in quick on ${iface} inet6 all
2743
+ `;
2744
+ }
2745
+ const LOAD = `/sbin/pfctl -q -a ${ANCHOR} -f ${RULES_FILE}; /sbin/pfctl -s info 2>/dev/null | /usr/bin/grep -q "Status: Enabled" || /sbin/pfctl -q -E`;
2746
+ function daemonPlist() {
2747
+ return `<?xml version="1.0" encoding="UTF-8"?>
2748
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2749
+ <plist version="1.0">
2750
+ <dict>
2751
+ <key>Label</key>
2752
+ <string>${LABEL}</string>
2753
+ <key>ProgramArguments</key>
2754
+ <array>
2755
+ <string>/bin/sh</string>
2756
+ <string>-c</string>
2757
+ <string>${LOAD.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")}</string>
2758
+ </array>
2759
+ <key>RunAtLoad</key>
2760
+ <true/>
2761
+ <key>StartInterval</key>
2762
+ <integer>300</integer>
2763
+ </dict>
2764
+ </plist>
2765
+ `;
2766
+ }
2767
+ function onScript(rules, plist) {
2768
+ return [
2769
+ "set -e",
2770
+ `install -m 644 -o root -g wheel "${rules}" ${RULES_FILE}`,
2771
+ `install -m 644 -o root -g wheel "${plist}" ${DAEMON_FILE}`,
2772
+ `launchctl bootout system/${LABEL} 2>/dev/null || true`,
2773
+ `launchctl bootstrap system ${DAEMON_FILE}`,
2774
+ LOAD
2775
+ ].join("\n");
2776
+ }
2777
+ function offScript() {
2778
+ return [
2779
+ `launchctl bootout system/${LABEL} 2>/dev/null || true`,
2780
+ `rm -f ${DAEMON_FILE} ${RULES_FILE}`,
2781
+ `/sbin/pfctl -q -a ${ANCHOR} -F all 2>/dev/null || true`
2782
+ ].join("\n");
2783
+ }
2784
+ function firewallInstalled(exists = existsSync) {
2785
+ return exists("/etc/pf.anchors/app.relayrunner") && exists("/Library/LaunchDaemons/app.relayrunner.firewall.plist");
2786
+ }
2787
+ function sudo(script) {
2788
+ console.log("This needs your password, to change the Mac's firewall.");
2789
+ return spawnSync("sudo", [
2790
+ "/bin/sh",
2791
+ "-c",
2792
+ script
2793
+ ], { stdio: "inherit" }).status === 0;
2794
+ }
2795
+ function status() {
2796
+ if (!firewallInstalled()) {
2797
+ console.log("The firewall on this Mac is off. Isolated jobs rely on the firewall inside each VM, which a job using Docker can remove.\nTurn it on with `relayrunner firewall on`.");
2798
+ return;
2799
+ }
2800
+ console.log("The firewall on this Mac is on. Isolated jobs can reach the internet, not this Mac or your local network.\nTurn it off with `relayrunner firewall off`.");
2801
+ }
2802
+ const firewallCommand = defineCommand({
2803
+ meta: {
2804
+ name: "firewall",
2805
+ description: "Show or change the firewall on this Mac that keeps isolated jobs off the Mac and your local network."
2806
+ },
2807
+ args: { state: {
2808
+ type: "positional",
2809
+ required: false,
2810
+ description: "on or off; leave out to show the current setting"
2811
+ } },
2812
+ run({ args }) {
2813
+ const fail = (message) => {
2814
+ console.error(message);
2815
+ process.exitCode = 1;
2816
+ };
2817
+ const unsupported = unsupportedReason();
2818
+ if (unsupported) return fail(unsupported.replace("Running jobs in VMs needs", "The firewall needs"));
2819
+ if (!args.state) return status();
2820
+ if (args.state === "off") {
2821
+ if (!sudo(offScript())) return fail("Couldn't turn the firewall off.");
2822
+ console.log("The firewall on this Mac is off.");
2823
+ return;
2824
+ }
2825
+ if (args.state !== "on") return fail("Use `relayrunner firewall on` or `relayrunner firewall off`.");
2826
+ const dir = mkdtempSync(join(tmpdir(), "relayrunner-firewall-"));
2827
+ try {
2828
+ const rules = join(dir, "rules");
2829
+ const plist = join(dir, "daemon.plist");
2830
+ writeFileSync(rules, firewallRules(vmInterface()));
2831
+ writeFileSync(plist, daemonPlist());
2832
+ if (!sudo(onScript(rules, plist))) return fail("Couldn't turn the firewall on.");
2833
+ } finally {
2834
+ rmSync(dir, {
2835
+ recursive: true,
2836
+ force: true
2837
+ });
2838
+ }
2839
+ console.log("The firewall on this Mac is on. Isolated jobs can reach the internet, not this Mac or your local network.\nIt also applies to other VMs that use Apple's shared VM network. Turn it off with `relayrunner firewall off`.");
2840
+ }
2841
+ });
2660
2842
  // whoami.ts
2661
2843
  const WhoamiResponse = z.object({
2662
2844
  machine: z.object({
@@ -3004,26 +3186,42 @@ const connectCommand = defineCommand({
3004
3186
  },
3005
3187
  concurrency: {
3006
3188
  type: "string",
3007
- description: "How many jobs to run at once (default: 2 with 8 or more CPU cores, otherwise 1)"
3189
+ description: "How many jobs to run at once (default: 2 with 8 or more CPU cores, otherwise 1; with --cpus or --memory, as many as fit)"
3008
3190
  },
3009
3191
  isolated: {
3010
3192
  type: "boolean",
3011
- description: "Run each job in its own Linux VM, away from your files. Needs a Mac with Apple silicon and Apple's container tool."
3193
+ description: "Run each job in its own Linux VM, away from your files. The default on a Mac with Apple silicon and Apple's container tool.",
3194
+ negativeDescription: "Run jobs on this machine itself, where they can read your files."
3195
+ },
3196
+ macos: {
3197
+ type: "boolean",
3198
+ description: "Also take macOS jobs, which run on this Mac itself. Linux jobs still run in a VM."
3199
+ },
3200
+ cpus: {
3201
+ type: "string",
3202
+ description: "CPUs for each job's VM (default: an even share of this Mac's cores)"
3203
+ },
3204
+ memory: {
3205
+ type: "string",
3206
+ description: "Memory for each job's VM, in GB (default: an even share of half this Mac's)"
3012
3207
  },
3013
3208
  image: {
3014
3209
  type: "string",
3015
- description: "With --isolated, the runner image to build on (default: GitHub's runner image)"
3210
+ description: "Your own runner image for the VMs (default: GitHub's, with everyday tools)"
3016
3211
  },
3017
3212
  "local-network": {
3018
3213
  type: "boolean",
3019
- description: "With --isolated, let jobs reach this Mac and your local network. They can't by default."
3214
+ description: "Let jobs in VMs reach this Mac and your local network. They can't by default."
3020
3215
  }
3021
3216
  },
3022
3217
  async run({ args }) {
3023
3218
  clack.intro("RelayRunner");
3024
3219
  let concurrency;
3220
+ let size;
3025
3221
  try {
3026
- concurrency = parseConcurrency(args.concurrency);
3222
+ size = parseVmSize(args.cpus, args.memory);
3223
+ concurrency = args.concurrency ? parseConcurrency(args.concurrency) : slotsFor(size) ?? parseConcurrency(void 0);
3224
+ checkFits(size, concurrency);
3027
3225
  } catch (error) {
3028
3226
  clack.log.error(error.message);
3029
3227
  process.exitCode = 1;
@@ -3032,7 +3230,8 @@ const connectCommand = defineCommand({
3032
3230
  try {
3033
3231
  await connectMachine({
3034
3232
  ...args,
3035
- concurrency
3233
+ concurrency,
3234
+ size
3036
3235
  });
3037
3236
  } catch (error) {
3038
3237
  if (!(error instanceof LoginError || error instanceof RunnerError)) throw error;
@@ -3043,15 +3242,26 @@ const connectCommand = defineCommand({
3043
3242
  });
3044
3243
  async function connectMachine(args) {
3045
3244
  const share = shareArg(args.share);
3046
- if (args.image && !args.isolated) throw new RunnerError("USAGE", "--image goes with --isolated.");
3047
- if (args["local-network"] && !args.isolated) throw new RunnerError("USAGE", "--local-network goes with --isolated.");
3245
+ const vmFlag = [
3246
+ "macos",
3247
+ "image",
3248
+ "local-network"
3249
+ ].find((flag) => args[flag]) ?? (args.size.cpus !== void 0 ? "cpus" : args.size.memoryGb !== void 0 ? "memory" : null);
3250
+ if (args.isolated === false && vmFlag) throw new RunnerError("USAGE", `--${vmFlag} doesn't go with --no-isolated.`);
3048
3251
  const host = machinePlatform();
3049
- const unsupported = args.isolated ? unsupportedReason() : null;
3252
+ const asked = args.isolated === true || Boolean(vmFlag);
3253
+ const unsupported = asked ? unsupportedReason() : null;
3050
3254
  if (unsupported) throw new RunnerError("ISOLATED_UNSUPPORTED", unsupported);
3051
- const platform = args.isolated ? {
3255
+ const state = asked || args.isolated === false ? null : await isolationState();
3256
+ const isolated = asked || state === "ready";
3257
+ const vm = {
3052
3258
  os: "linux",
3053
3259
  arch: host.arch
3054
- } : host;
3260
+ };
3261
+ const platform = !isolated ? host : args.macos ? {
3262
+ ...host,
3263
+ isolated: vm
3264
+ } : vm;
3055
3265
  let credentials = readCredentials();
3056
3266
  const server = serverFor(args.server, credentials);
3057
3267
  if (credentials && credentials.server !== server) {
@@ -3075,23 +3285,39 @@ async function connectMachine(args) {
3075
3285
  }
3076
3286
  const slots = args.concurrency;
3077
3287
  const log = (line) => clack.log.info(line);
3078
- let runnerVersion;
3079
- let launchers;
3080
- if (args.isolated) {
3288
+ const onHost = !isolated || args.macos ? ensureRunner({ log }) : void 0;
3289
+ onHost?.catch(() => {});
3290
+ let runnerVersion = "";
3291
+ let launchers = [];
3292
+ let vmLauncher;
3293
+ let isolatedOnly;
3294
+ if (isolated) {
3295
+ const firewall = firewallInstalled();
3296
+ if (firewall) log(args["local-network"] ? "The firewall on this Mac is on, so --local-network has no effect. Turn it off with `relayrunner firewall off`." : "The firewall on this Mac is on.");
3081
3297
  const isolation = await prepareIsolation({
3082
3298
  slots,
3299
+ size: args.size,
3083
3300
  image: args.image,
3084
- localNetwork: args["local-network"],
3301
+ localNetwork: args["local-network"] && !firewall,
3085
3302
  log,
3086
3303
  debug: debugLog()
3087
3304
  });
3088
3305
  runnerVersion = isolation.runnerVersion;
3089
- launchers = Array(slots).fill(isolatedLauncher(isolation));
3090
- } else {
3091
- const [runner, canIsolate] = await Promise.all([ensureRunner({ log }), isolationAvailable()]);
3306
+ const launcher = isolatedLauncher(isolation);
3307
+ if (args.macos) vmLauncher = launcher;
3308
+ else {
3309
+ launchers = Array.from({ length: slots }, () => isolatedOnly = launcher);
3310
+ log("Jobs run in a Linux VM on this Mac. To take macOS jobs too, run `relayrunner connect --macos`.");
3311
+ }
3312
+ }
3313
+ if (onHost) {
3314
+ const runner = await onHost;
3092
3315
  runnerVersion = runner.version;
3093
3316
  launchers = ensureSlots(runner, slots, log).map(hostLauncher);
3094
- if (canIsolate) log("This Mac can run each job in its own Linux VM, away from your files. Add --isolated.");
3317
+ const hint = !isolated && state ? setupHint(state) : null;
3318
+ if (hint) clack.log.warn(hint);
3319
+ if (args.macos) clack.log.warn("Linux jobs run in a VM. macOS jobs run on this Mac itself, where they can read your files. Only take macOS jobs from repos you trust.");
3320
+ else if (args.isolated === false) clack.log.warn("Jobs run on this machine itself, where they can read your files. Only take jobs from repos you trust.");
3095
3321
  }
3096
3322
  clack.log.info(slots === 1 ? "Running 1 job at a time. Change with --concurrency." : `Running up to ${slots} jobs at once. Change with --concurrency.`);
3097
3323
  const device = await detectDevice();
@@ -3132,9 +3358,19 @@ async function connectMachine(args) {
3132
3358
  slots,
3133
3359
  runJob: async (run, slot, report) => {
3134
3360
  const prefixed = slots > 1 ? prefixLines(`[slot ${slot}] `, (chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk)) : void 0;
3361
+ const launcher = run.isolated ? vmLauncher ?? isolatedOnly : launchers[slot - 1];
3362
+ if (!launcher) {
3363
+ const update = {
3364
+ routeId: run.routeId,
3365
+ state: "failed",
3366
+ message: "The job was sent for a VM, and this machine isn't running jobs in one."
3367
+ };
3368
+ report(update);
3369
+ return update;
3370
+ }
3135
3371
  try {
3136
3372
  return await runJob(run, {
3137
- launcher: launchers[slot - 1],
3373
+ launcher,
3138
3374
  report,
3139
3375
  output: prefixed?.output,
3140
3376
  onChecked: (target) => {
@@ -3550,7 +3786,8 @@ const main = defineCommand({
3550
3786
  pause: pauseCommand(true),
3551
3787
  resume: pauseCommand(false),
3552
3788
  share: shareCommand,
3553
- workspaces: workspacesCommand
3789
+ workspaces: workspacesCommand,
3790
+ firewall: firewallCommand
3554
3791
  }
3555
3792
  });
3556
3793
  runMain(main);