relayrunner 0.6.0 → 0.8.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 (3) hide show
  1. package/README.md +49 -1
  2. package/dist/cli.js +947 -124
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -2,16 +2,16 @@
2
2
  import * as clack from "@clack/prompts";
3
3
  import { defineCommand, runMain } from "citty";
4
4
  import { z } from "zod";
5
- import { arch, cpus, homedir, hostname, platform, totalmem } from "node:os";
5
+ import { arch, availableParallelism, cpus, homedir, hostname, platform, release, tmpdir, totalmem } from "node:os";
6
6
  import { basename, dirname, join, resolve } from "node:path";
7
- import { chmodSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
7
+ import { appendFileSync, chmodSync, constants, cpSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
8
8
  import { execFile, spawn } 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";
12
12
  import { styleText } from "node:util";
13
13
  import { Scalar, YAMLSeq, isMap, isScalar, isSeq, parseDocument } from "yaml";
14
- const version = z.literal(1);
14
+ const version$1 = z.literal(1);
15
15
  const routeId = z.string().min(1);
16
16
  const DeviceKind = z.enum([
17
17
  "laptop",
@@ -31,7 +31,7 @@ const Device = z.object({
31
31
  osVersion: text.optional()
32
32
  });
33
33
  const HelloMessage = z.object({
34
- v: version,
34
+ v: version$1,
35
35
  type: z.literal("hello"),
36
36
  machineId: z.string().min(1),
37
37
  os: z.enum([
@@ -45,16 +45,19 @@ const HelloMessage = z.object({
45
45
  "arm"
46
46
  ]),
47
47
  runnerVersion: z.string().min(1),
48
+ cliVersion: z.string().trim().min(1).max(40).optional(),
48
49
  device: Device.optional().catch(void 0),
49
- rotatesToken: z.boolean().optional()
50
+ rotatesToken: z.boolean().optional(),
51
+ slots: z.number().int().positive().max(1e3).optional()
50
52
  });
51
53
  const StatusMessage = z.object({
52
- v: version,
54
+ v: version$1,
53
55
  type: z.literal("status"),
54
- state: z.enum(["idle", "busy"])
56
+ state: z.enum(["idle", "busy"]),
57
+ running: z.number().int().nonnegative().max(1e3).optional()
55
58
  });
56
59
  const JobMessage = z.object({
57
- v: version,
60
+ v: version$1,
58
61
  type: z.literal("job"),
59
62
  routeId,
60
63
  state: z.enum([
@@ -65,7 +68,7 @@ const JobMessage = z.object({
65
68
  message: z.string().optional()
66
69
  });
67
70
  const TokenSavedMessage = z.object({
68
- v: version,
71
+ v: version$1,
69
72
  type: z.literal("token_saved")
70
73
  });
71
74
  z.discriminatedUnion("type", [
@@ -75,25 +78,25 @@ z.discriminatedUnion("type", [
75
78
  TokenSavedMessage
76
79
  ]);
77
80
  const RunMessage = z.object({
78
- v: version,
81
+ v: version$1,
79
82
  type: z.literal("run"),
80
83
  routeId,
81
84
  jitConfig: z.string().min(1)
82
85
  });
83
86
  const ErrorMessage = z.object({
84
- v: version,
87
+ v: version$1,
85
88
  type: z.literal("error"),
86
89
  code: z.enum(["version_mismatch", "invalid_message"]),
87
90
  message: z.string()
88
91
  });
89
92
  const PausedMessage = z.object({
90
- v: version,
93
+ v: version$1,
91
94
  type: z.literal("paused"),
92
95
  paused: z.boolean(),
93
96
  by: z.string().nullable()
94
97
  });
95
98
  const TokenMessage = z.object({
96
- v: version,
99
+ v: version$1,
97
100
  type: z.literal("token"),
98
101
  token: z.string().min(1)
99
102
  });
@@ -104,12 +107,12 @@ const GatewayMessage = z.discriminatedUnion("type", [
104
107
  TokenMessage
105
108
  ]);
106
109
  function parseGatewayMessage(frame) {
107
- return parse(GatewayMessage, frame);
110
+ return parse$1(GatewayMessage, frame);
108
111
  }
109
112
  function encodeMessage(message) {
110
113
  return JSON.stringify(message);
111
114
  }
112
- function parse(schema, frame) {
115
+ function parse$1(schema, frame) {
113
116
  let data;
114
117
  try {
115
118
  data = JSON.parse(frame);
@@ -142,6 +145,25 @@ function parse(schema, frame) {
142
145
  function isRunnerForRoute(runnerName, routeId) {
143
146
  return runnerName.endsWith(`-${routeId}`);
144
147
  }
148
+ // ../../packages/machine-protocol/src/cli-version.ts
149
+ /** Whether `candidate` is a newer release than `current`. Only plain x.y.z releases count, so a prerelease never reads as newer. */
150
+ function isNewerVersion(candidate, current) {
151
+ const a = parse(candidate);
152
+ const b = parse(current);
153
+ if (!a || !b) return false;
154
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
155
+ return false;
156
+ }
157
+ function parse(version) {
158
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version.trim());
159
+ return match ? [
160
+ Number(match[1]),
161
+ Number(match[2]),
162
+ Number(match[3])
163
+ ] : null;
164
+ }
165
+ // version.ts
166
+ const cliVersion = "0.8.0";
145
167
  // paths.ts
146
168
  function relayrunnerHome() {
147
169
  return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), ".relayrunner"));
@@ -149,7 +171,7 @@ function relayrunnerHome() {
149
171
  function runnersDir() {
150
172
  return join(relayrunnerHome(), "runner");
151
173
  }
152
- const userAgent = "relayrunner-cli";
174
+ const userAgent = `relayrunner-cli/${cliVersion}`;
153
175
  const CLOSE_POLICY = 1008;
154
176
  const NodeWebSocket = WebSocket;
155
177
  function connectUrl(server) {
@@ -165,9 +187,11 @@ async function connect(options) {
165
187
  const heartbeatMs = options.heartbeatMs ?? 3e4;
166
188
  const minBackoffMs = options.minBackoffMs ?? 1e3;
167
189
  const maxBackoffMs = options.maxBackoffMs ?? 3e4;
190
+ const reconnectSpreadMs = options.reconnectSpreadMs ?? 1e4;
168
191
  const emit = options.onEvent ?? (() => {});
169
192
  const signal = options.signal;
170
- let state = "idle";
193
+ const slots = options.slots ?? 1;
194
+ const busy = /* @__PURE__ */ new Set();
171
195
  let socket = null;
172
196
  let token = options.token;
173
197
  const pending = [];
@@ -179,7 +203,8 @@ async function connect(options) {
179
203
  const sendStatus = () => send({
180
204
  v: 1,
181
205
  type: "status",
182
- state
206
+ state: busy.size > 0 ? "busy" : "idle",
207
+ running: busy.size
183
208
  });
184
209
  const saveToken = (next) => {
185
210
  if (!options.saveToken) return;
@@ -199,15 +224,18 @@ async function connect(options) {
199
224
  });
200
225
  };
201
226
  const startJob = (run) => {
202
- if (state === "busy") {
227
+ let slot = 1;
228
+ while (busy.has(slot)) slot++;
229
+ if (slot > slots) {
203
230
  emit({
204
231
  type: "run-refused",
205
- routeId: run.routeId
232
+ routeId: run.routeId,
233
+ running: busy.size
206
234
  });
207
235
  const update = {
208
236
  routeId: run.routeId,
209
237
  state: "failed",
210
- message: "The machine is already running a job."
238
+ message: busy.size === 1 ? "The machine is already running a job." : `The machine is already running ${busy.size} jobs.`
211
239
  };
212
240
  send({
213
241
  v: 1,
@@ -218,14 +246,16 @@ async function connect(options) {
218
246
  }
219
247
  emit({
220
248
  type: "run",
221
- routeId: run.routeId
249
+ routeId: run.routeId,
250
+ slot
222
251
  });
223
- state = "busy";
252
+ busy.add(slot);
224
253
  sendStatus();
225
- options.runJob(run, (update) => {
254
+ options.runJob(run, slot, (update) => {
226
255
  emit({
227
256
  type: "job",
228
- update
257
+ update,
258
+ slot
229
259
  });
230
260
  send({
231
261
  v: 1,
@@ -233,7 +263,7 @@ async function connect(options) {
233
263
  ...update
234
264
  });
235
265
  }).finally(() => {
236
- state = "idle";
266
+ busy.delete(slot);
237
267
  sendStatus();
238
268
  });
239
269
  };
@@ -271,6 +301,7 @@ async function connect(options) {
271
301
  v: 1,
272
302
  type: "hello",
273
303
  ...options.hello,
304
+ slots,
274
305
  rotatesToken
275
306
  }));
276
307
  sendStatus();
@@ -337,7 +368,7 @@ async function connect(options) {
337
368
  message: gatewayError || reason || "protocol error"
338
369
  };
339
370
  if (!opened && await tokenRejected()) return { reason: "revoked" };
340
- const retryInMs = backoff(attempt, minBackoffMs, maxBackoffMs);
371
+ const retryInMs = opened ? Math.round(Math.random() * reconnectSpreadMs) : backoff(attempt, minBackoffMs, maxBackoffMs);
341
372
  emit({
342
373
  type: "disconnected",
343
374
  code,
@@ -407,13 +438,23 @@ function pickDownload(release, target) {
407
438
  sha256
408
439
  };
409
440
  }
410
- async function latestDownload(target) {
441
+ async function latestRelease() {
411
442
  const response = await fetch(LATEST_RELEASE, { headers: {
412
443
  accept: "application/vnd.github+json",
413
444
  "user-agent": userAgent
414
445
  } });
415
446
  if (!response.ok) throw new RunnerError("RUNNER_DOWNLOAD", `Could not look up the latest actions/runner release (HTTP ${response.status}).`);
416
- return pickDownload(await response.json(), target);
447
+ return response.json();
448
+ }
449
+ async function latestRunnerVersion(log = () => {}) {
450
+ try {
451
+ return Release.parse(await latestRelease()).tag_name.slice(1);
452
+ } catch (error) {
453
+ const [newest] = installedRunners();
454
+ if (!newest) throw error;
455
+ log(`Couldn't check for a newer runner (${error.message}). Using ${newest.version}.`);
456
+ return newest.version;
457
+ }
417
458
  }
418
459
  function installedRunners(root = runnersDir()) {
419
460
  if (!existsSync(root)) return [];
@@ -433,7 +474,7 @@ async function ensureRunner(options = {}) {
433
474
  const target = runnerPlatform();
434
475
  let download;
435
476
  try {
436
- download = await latestDownload(target);
477
+ download = pickDownload(await latestRelease(), target);
437
478
  } catch (error) {
438
479
  const [newest] = installedRunners(root);
439
480
  if (newest) {
@@ -609,7 +650,7 @@ const run = (command, args) => new Promise((resolve) => {
609
650
  resolve(error ? null : stdout.trim() || null);
610
651
  });
611
652
  });
612
- const read$1 = (path) => {
653
+ const read = (path) => {
613
654
  try {
614
655
  return readFileSync(path, "utf8").replaceAll("\0", "").trim() || null;
615
656
  } catch {
@@ -620,7 +661,7 @@ function defaultSources() {
620
661
  const list = cpus();
621
662
  return {
622
663
  run,
623
- read: read$1,
664
+ read,
624
665
  cpuModel: list[0]?.model,
625
666
  cpuCount: list.length,
626
667
  totalMemory: totalmem()
@@ -774,11 +815,8 @@ function compact(device) {
774
815
  }
775
816
  return out;
776
817
  }
777
- // declined.ts
778
- function declinedPath(home = relayrunnerHome()) {
779
- return join(home, "declined-repos.json");
780
- }
781
- function read(path) {
818
+ // list-file.ts
819
+ function readList(path) {
782
820
  try {
783
821
  const value = JSON.parse(readFileSync(path, "utf8"));
784
822
  return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
@@ -786,17 +824,23 @@ function read(path) {
786
824
  return [];
787
825
  }
788
826
  }
789
- function isDeclined(repo, path = declinedPath()) {
790
- return read(path).includes(repo);
791
- }
792
- function rememberDeclined(repo, path = declinedPath()) {
793
- const repos = read(path);
794
- if (repos.includes(repo)) return;
827
+ function writeList(path, list) {
795
828
  mkdirSync(dirname(path), {
796
829
  recursive: true,
797
830
  mode: 448
798
831
  });
799
- writeFileSync(path, `${JSON.stringify([...repos, repo], null, 2)}\n`);
832
+ writeFileSync(path, `${JSON.stringify(list, null, 2)}\n`);
833
+ }
834
+ // declined.ts
835
+ function declinedPath(home = relayrunnerHome()) {
836
+ return join(home, "declined-repos.json");
837
+ }
838
+ function isDeclined(repo, path = declinedPath()) {
839
+ return readList(path).includes(repo);
840
+ }
841
+ function rememberDeclined(repo, path = declinedPath()) {
842
+ const repos = readList(path);
843
+ if (!repos.includes(repo)) writeList(path, [...repos, repo]);
800
844
  }
801
845
  // diff.ts
802
846
  function unifiedDiff(before, after, file, context = 2) {
@@ -936,7 +980,13 @@ const RATES = {
936
980
  macos: "runner"
937
981
  }
938
982
  };
939
- const isRate = (provider, rate) => Object.hasOwn(RATES, provider) && Object.hasOwn(RATES[provider], rate);
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;
940
990
  const vcpu = (perRunner, vcpus) => perRunner / vcpus;
941
991
  const BASE_PRICES = [
942
992
  {
@@ -1131,7 +1181,9 @@ const LABEL_PREFIXES = {
1131
1181
  ubicloud: ["ubicloud-"],
1132
1182
  "runs-on": ["runs-on=", "runs-on/"]
1133
1183
  };
1134
- const matches = (provider, lower) => LABEL_PREFIXES[provider].some((prefix) => lower.startsWith(prefix) || prefix.endsWith("-") && lower === prefix.slice(0, -1));
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);
1135
1187
  /** The hosted provider whose runners a label asks for, or null. */
1136
1188
  function hostedProviderOf(label) {
1137
1189
  const lower = label.toLowerCase();
@@ -1711,79 +1763,81 @@ const runnerEnv = () => Object.fromEntries([
1711
1763
  "TMPDIR",
1712
1764
  "SHELL"
1713
1765
  ].flatMap((key) => process.env[key] === void 0 ? [] : [[key, process.env[key]]]));
1714
- const JOB_STATE = [
1715
- "_work",
1716
- ".runner",
1717
- ".credentials",
1718
- ".credentials_rsaparams"
1719
- ];
1720
1766
  async function runJob(run, options) {
1721
- const { runner, report } = options;
1767
+ const { launcher, report } = options;
1768
+ const { routeId } = run;
1722
1769
  const output = options.output ?? ((chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk));
1723
1770
  const finish = (update) => {
1724
1771
  report(update);
1725
1772
  return update;
1726
1773
  };
1727
- const checked = checkJitConfig(run.jitConfig, run.routeId);
1728
- if (!checked.ok) return finish({
1729
- routeId: run.routeId,
1774
+ const failed = (message) => finish({
1775
+ routeId,
1730
1776
  state: "failed",
1731
- message: `Refused the job's runner config: ${checked.reason}.`
1777
+ message
1732
1778
  });
1779
+ const checked = checkJitConfig(run.jitConfig, routeId);
1780
+ if (!checked.ok) return failed(`Refused the job's runner config: ${checked.reason}.`);
1733
1781
  options.onChecked?.(checked.target);
1734
- const lock = join(runner.dir, "job.lock");
1735
- if (!takeLock(lock)) return finish({
1736
- routeId: run.routeId,
1737
- state: "failed",
1738
- message: `Another job is using the runner in ${runner.dir}.`
1739
- });
1782
+ let clean = false;
1740
1783
  try {
1741
- clean(runner.dir);
1742
- const child = spawn(join(runner.dir, "run.sh"), ["--jitconfig", run.jitConfig], {
1743
- cwd: runner.dir,
1744
- env: runnerEnv(),
1745
- stdio: [
1746
- "ignore",
1747
- "pipe",
1748
- "pipe"
1749
- ]
1750
- });
1784
+ const child = launcher.start(run);
1751
1785
  child.stdout.on("data", (chunk) => output(chunk, "stdout"));
1752
1786
  child.stderr.on("data", (chunk) => output(chunk, "stderr"));
1753
1787
  const started = await new Promise((resolve) => {
1754
1788
  child.once("spawn", () => resolve(null));
1755
1789
  child.once("error", resolve);
1756
1790
  });
1757
- if (started) return finish({
1758
- routeId: run.routeId,
1759
- state: "failed",
1760
- message: `Could not start the runner: ${started.message}`
1761
- });
1791
+ if (started) return failed(`Could not start the runner: ${started.message}`);
1762
1792
  report({
1763
- routeId: run.routeId,
1793
+ routeId,
1764
1794
  state: "started"
1765
1795
  });
1766
1796
  const [code, signal] = await new Promise((resolve) => child.once("close", (code, signal) => resolve([code, signal])));
1767
- if (code === 0) return finish({
1768
- routeId: run.routeId,
1797
+ clean = code === 0;
1798
+ if (clean) return finish({
1799
+ routeId,
1769
1800
  state: "finished"
1770
1801
  });
1771
- return finish({
1772
- routeId: run.routeId,
1773
- state: "failed",
1774
- message: signal ? `run.sh was stopped by ${signal}` : `run.sh exited with ${code}`
1775
- });
1802
+ return failed(signal ? `The runner was stopped by ${signal}` : `The runner exited with ${code}`);
1776
1803
  } catch (error) {
1777
- return finish({
1778
- routeId: run.routeId,
1779
- state: "failed",
1780
- message: error instanceof Error ? error.message : String(error)
1781
- });
1804
+ return failed(error instanceof Error ? error.message : String(error));
1782
1805
  } finally {
1783
- clean(runner.dir);
1784
- rmSync(lock, { force: true });
1806
+ await launcher.cleanup(run, clean);
1785
1807
  }
1786
1808
  }
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
+ };
1840
+ }
1787
1841
  function clean(dir) {
1788
1842
  for (const name of JOB_STATE) rmSync(join(dir, name), {
1789
1843
  recursive: true,
@@ -1810,11 +1864,307 @@ function isAlive(pid) {
1810
1864
  return error.code === "EPERM";
1811
1865
  }
1812
1866
  }
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
+ };
1890
+ }
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;
1899
+ }
1900
+ async function isolationAvailable(command = "container", reason = unsupportedReason()) {
1901
+ return reason === null && await call(command, ["--version"], NO_LOG, true) === 0;
1902
+ }
1903
+ function debugLog(path = join(relayrunnerHome(), "isolated.log")) {
1904
+ const home = homedir();
1905
+ const write = (text, flag = "a") => {
1906
+ 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");
1918
+ return {
1919
+ path,
1920
+ write
1921
+ };
1922
+ }
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
+ }
1952
+ }
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
+ `;
1985
+ }
1986
+ function jobImage(base) {
1987
+ return `relayrunner-runner:${createHash("sha256").update(dockerfile(base)).update(START_SCRIPT).digest("hex").slice(0, 12)}`;
1988
+ }
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
+ };
1995
+ }
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"]);
2048
+ }
2049
+ }
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
+ }
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 {}
2080
+ }
2081
+ function containerName(routeId) {
2082
+ return `relayrunner-${routeId.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
2083
+ }
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
+ ];
2108
+ }
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
+ };
2141
+ }
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
+ });
2162
+ }
1813
2163
  // live.ts
1814
2164
  const INITIAL_STATE = {
1815
2165
  link: "connecting",
1816
2166
  paused: false,
1817
- job: null
2167
+ jobs: []
1818
2168
  };
1819
2169
  /** The state after a connection event. */
1820
2170
  function nextState(state, event) {
@@ -1833,11 +2183,11 @@ function nextState(state, event) {
1833
2183
  };
1834
2184
  case "run": return {
1835
2185
  ...state,
1836
- job: event.routeId
2186
+ jobs: [...state.jobs, event.routeId]
1837
2187
  };
1838
- case "job": return event.update.state === "started" || event.update.routeId !== state.job ? state : {
2188
+ case "job": return event.update.state === "started" || !state.jobs.includes(event.update.routeId) ? state : {
1839
2189
  ...state,
1840
- job: null
2190
+ jobs: state.jobs.filter((id) => id !== event.update.routeId)
1841
2191
  };
1842
2192
  case "paused": return {
1843
2193
  ...state,
@@ -1853,10 +2203,11 @@ function nextState(state, event) {
1853
2203
  function titleFor(state, machine) {
1854
2204
  return `RelayRunner · ${machine} · ${statusText(state)}`;
1855
2205
  }
1856
- function statusText({ link, paused, job }) {
2206
+ function statusText({ link, paused, jobs }) {
2207
+ const running = jobs.length === 1 ? "Running a job" : `Running ${jobs.length} jobs`;
1857
2208
  if (link === "connecting") return "Connecting…";
1858
- if (link === "reconnecting") return job ? "Running a job, reconnecting…" : "Reconnecting…";
1859
- if (job) return paused ? "Running a job, then paused" : "Running a job";
2209
+ if (link === "reconnecting") return jobs.length ? `${running}, reconnecting…` : "Reconnecting…";
2210
+ if (jobs.length) return paused ? `${running}, then paused` : running;
1860
2211
  return paused ? "Paused" : "Waiting for jobs";
1861
2212
  }
1862
2213
  const ESC = "\x1B";
@@ -1922,6 +2273,71 @@ function startLive(options) {
1922
2273
  }
1923
2274
  };
1924
2275
  }
2276
+ // update-check.ts
2277
+ const CHECK_INTERVAL_MS = 864e5;
2278
+ const REGISTRY_URL = "https://registry.npmjs.org/relayrunner/latest";
2279
+ const TIMEOUT_MS = 3e3;
2280
+ const Cache = z.object({
2281
+ checkedAt: z.number(),
2282
+ latest: z.string()
2283
+ });
2284
+ /** The newer version npm has, or null when this CLI is current or the check couldn't tell. */
2285
+ async function checkForUpdate(options = {}) {
2286
+ const now = options.now ?? Date.now();
2287
+ const current = options.current ?? cliVersion;
2288
+ let cache = readCache();
2289
+ if (!cache || now - cache.checkedAt >= 864e5) {
2290
+ const latest = await fetchLatest(options.fetch ?? fetch);
2291
+ if (latest) {
2292
+ cache = {
2293
+ checkedAt: now,
2294
+ latest
2295
+ };
2296
+ writeCache(cache);
2297
+ }
2298
+ }
2299
+ return cache && isNewerVersion(cache.latest, current) ? cache.latest : null;
2300
+ }
2301
+ /** The line to print for a newer version, with the command that updates the way this one runs. */
2302
+ function updateNotice(latest, current = cliVersion, argv1 = process.argv[1] ?? "") {
2303
+ return `relayrunner ${latest} is available (you have ${current}). Update with \`${/[\\/]_npx[\\/]/.test(argv1) ? "npx relayrunner@latest connect" : "npm install --global relayrunner@latest"}\`.`;
2304
+ }
2305
+ async function fetchLatest(fetcher) {
2306
+ try {
2307
+ const response = await fetcher(REGISTRY_URL, {
2308
+ headers: {
2309
+ accept: "application/json",
2310
+ "user-agent": userAgent
2311
+ },
2312
+ signal: AbortSignal.timeout(TIMEOUT_MS)
2313
+ });
2314
+ if (!response.ok) {
2315
+ await response.body?.cancel();
2316
+ return null;
2317
+ }
2318
+ const body = z.object({ version: z.string() }).safeParse(await response.json());
2319
+ return body.success ? body.data.version : null;
2320
+ } catch {
2321
+ return null;
2322
+ }
2323
+ }
2324
+ function cachePath() {
2325
+ return join(relayrunnerHome(), "update-check.json");
2326
+ }
2327
+ function readCache() {
2328
+ try {
2329
+ const parsed = Cache.safeParse(JSON.parse(readFileSync(cachePath(), "utf8")));
2330
+ return parsed.success ? parsed.data : null;
2331
+ } catch {
2332
+ return null;
2333
+ }
2334
+ }
2335
+ function writeCache(cache) {
2336
+ try {
2337
+ mkdirSync(relayrunnerHome(), { recursive: true });
2338
+ writeFileSync(cachePath(), `${JSON.stringify(cache)}\n`);
2339
+ } catch {}
2340
+ }
1925
2341
  // workspaces.ts
1926
2342
  const Workspace = z.object({
1927
2343
  id: z.string().min(1),
@@ -2131,6 +2547,62 @@ function pauseMachine(credentials, paused) {
2131
2547
  paused
2132
2548
  }));
2133
2549
  }
2550
+ // slots.ts
2551
+ const MAX_SLOTS = 1e3;
2552
+ function defaultConcurrency(cores = availableParallelism()) {
2553
+ return cores >= 8 ? 2 : 1;
2554
+ }
2555
+ function parseConcurrency(value, cores) {
2556
+ if (value === void 0 || value === "") return defaultConcurrency(cores);
2557
+ const n = Number(value);
2558
+ if (!/^\d+$/.test(value.trim()) || !Number.isSafeInteger(n) || n < 1 || n > 1e3) throw new Error(`--concurrency takes a whole number from 1 to ${MAX_SLOTS}, not "${value}".`);
2559
+ return n;
2560
+ }
2561
+ function slotDir(runner, slot) {
2562
+ return join(runner.dir, `slot-${slot}`);
2563
+ }
2564
+ function ensureSlots(runner, count, log = () => {}) {
2565
+ const dirs = [];
2566
+ const missing = [];
2567
+ for (let slot = 1; slot <= count; slot++) {
2568
+ const dir = slotDir(runner, slot);
2569
+ dirs.push(dir);
2570
+ if (!existsSync(join(dir, "run.sh"))) missing.push(slot);
2571
+ }
2572
+ if (missing.length > 0) log(missing.length === 1 ? `Setting up runner slot ${missing[0]}…` : `Setting up ${missing.length} runner slots…`);
2573
+ for (const slot of missing) copySlot(runner.dir, slotDir(runner, slot));
2574
+ return dirs;
2575
+ }
2576
+ const SKIP = /^(slot-\d+|\.slot-.*|_work|_diag|\.runner|\.credentials.*|job\.lock)$/;
2577
+ function copySlot(source, dir) {
2578
+ rmSync(dir, {
2579
+ recursive: true,
2580
+ force: true
2581
+ });
2582
+ const temp = mkdtempSync(join(source, `.${basename(dir)}-`));
2583
+ try {
2584
+ for (const name of readdirSync(source)) {
2585
+ if (SKIP.test(name)) continue;
2586
+ cpSync(join(source, name), join(temp, name), {
2587
+ recursive: true,
2588
+ mode: constants.COPYFILE_FICLONE,
2589
+ verbatimSymlinks: true,
2590
+ preserveTimestamps: true
2591
+ });
2592
+ }
2593
+ try {
2594
+ renameSync(temp, dir);
2595
+ } catch (error) {
2596
+ const code = error.code;
2597
+ if (code !== "EEXIST" && code !== "ENOTEMPTY") throw error;
2598
+ }
2599
+ } finally {
2600
+ rmSync(temp, {
2601
+ recursive: true,
2602
+ force: true
2603
+ });
2604
+ }
2605
+ }
2134
2606
  // share.ts
2135
2607
  const SHARE_CHOICES = ["only-me", "anyone"];
2136
2608
  const MachineSharing = z.enum(["only_me", "anyone"]);
@@ -2237,6 +2709,279 @@ async function whoami(options) {
2237
2709
  identity: parsed.data
2238
2710
  };
2239
2711
  }
2712
+ // machine-workspaces.ts
2713
+ const Choice = z.object({
2714
+ id: z.string().min(1),
2715
+ name: z.string(),
2716
+ slug: z.string().nullish()
2717
+ });
2718
+ const MachineWorkspaces = z.object({
2719
+ machine: z.object({
2720
+ id: z.string().min(1),
2721
+ name: z.string(),
2722
+ sharing: z.enum(["only_me", "anyone"])
2723
+ }),
2724
+ workspaces: z.array(Choice),
2725
+ others: z.array(Choice)
2726
+ });
2727
+ /** GET the machine's workspaces, or PUT/DELETE one of them when `change` is given. */
2728
+ async function machineWorkspaces(options) {
2729
+ const fetcher = options.fetcher ?? fetch;
2730
+ const { change } = options;
2731
+ const path = change ? `/api/machines/me/workspaces/${encodeURIComponent(change.workspaceId)}` : "/api/machines/me/workspaces";
2732
+ let response;
2733
+ try {
2734
+ response = await fetcher(new URL(path, options.server), {
2735
+ method: change ? change.action === "add" ? "PUT" : "DELETE" : "GET",
2736
+ headers: {
2737
+ authorization: `Bearer ${options.token}`,
2738
+ "user-agent": userAgent
2739
+ }
2740
+ });
2741
+ } catch (error) {
2742
+ const cause = error.cause?.message;
2743
+ return {
2744
+ status: "failed",
2745
+ reason: `couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
2746
+ };
2747
+ }
2748
+ if (response.status === 401) return { status: "revoked" };
2749
+ const body = await response.json().catch(() => null);
2750
+ if (change && response.status === 404 && body?.error === "not_found") return { status: "not_found" };
2751
+ if (response.status === 404 || response.status === 405) return {
2752
+ status: "failed",
2753
+ reason: `${options.server} doesn't support choosing workspaces yet`
2754
+ };
2755
+ if (response.status === 403) return {
2756
+ status: "failed",
2757
+ reason: "only the machine's owner can change its workspaces"
2758
+ };
2759
+ if (!response.ok) return {
2760
+ status: "failed",
2761
+ reason: `${options.server} answered HTTP ${response.status}`
2762
+ };
2763
+ const parsed = MachineWorkspaces.safeParse(body);
2764
+ if (!parsed.success) return {
2765
+ status: "failed",
2766
+ reason: `${options.server} sent an unexpected response`
2767
+ };
2768
+ return {
2769
+ status: "ok",
2770
+ choice: parsed.data
2771
+ };
2772
+ }
2773
+ /** The workspace `query` names: its id, or its name or slug in any case. */
2774
+ function matchWorkspace(workspaces, query) {
2775
+ const byId = workspaces.find((workspace) => workspace.id === query);
2776
+ if (byId) return {
2777
+ status: "one",
2778
+ workspace: byId
2779
+ };
2780
+ const wanted = query.trim().toLowerCase();
2781
+ const found = workspaces.filter((workspace) => workspace.name.toLowerCase() === wanted || workspace.slug?.toLowerCase() === wanted);
2782
+ if (found.length === 1) return {
2783
+ status: "one",
2784
+ workspace: found[0]
2785
+ };
2786
+ return found.length ? {
2787
+ status: "several",
2788
+ workspaces: found
2789
+ } : { status: "none" };
2790
+ }
2791
+ /** "Acme (acme)" for listing, so two workspaces with the same name can be told apart. */
2792
+ function labelWorkspace(workspace, withId = false) {
2793
+ const slug = workspace.slug && workspace.slug !== workspace.name ? ` (${workspace.slug})` : "";
2794
+ return `${workspace.name}${slug}${withId ? ` ${workspace.id}` : ""}`;
2795
+ }
2796
+ /** What `relayrunner workspaces` prints. */
2797
+ function describeMachineWorkspaces({ machine, workspaces, others }) {
2798
+ const lines = [];
2799
+ if (!workspaces.length && !others.length) {
2800
+ lines.push(`${machine.name} isn't in a workspace yet. It takes jobs once RelayRunner is installed on a GitHub account or org you belong to.`);
2801
+ return lines.join("\n");
2802
+ }
2803
+ lines.push(`${machine.name} runs jobs in:`);
2804
+ if (workspaces.length) for (const w of workspaces) lines.push(` ✓ ${labelWorkspace(w)}`);
2805
+ else lines.push(" (none: it takes no jobs)");
2806
+ if (others.length) {
2807
+ lines.push("", "Not in:");
2808
+ for (const w of others) lines.push(` · ${labelWorkspace(w)}`);
2809
+ }
2810
+ lines.push("", `Sharing: ${toChoice(machine.sharing)}: ${sharingMeaning(machine.sharing, "these workspaces")}`);
2811
+ if (others.length) lines.push("Add one with `relayrunner workspaces add <name>`.");
2812
+ else if (workspaces.length) lines.push("Remove one with `relayrunner workspaces remove <name>`.");
2813
+ return lines.join("\n");
2814
+ }
2815
+ /** Said when `add` puts a machine that runs anyone's jobs into another workspace. */
2816
+ function anyoneWarning(machine, workspace) {
2817
+ return `${machine} is set to run anyone's jobs, so anyone who can push to ${workspace}'s private repos can run jobs on it. Use \`relayrunner share only-me\` to limit it to jobs you started.`;
2818
+ }
2819
+ // workspaces-command.ts
2820
+ function signedIn() {
2821
+ const credentials = readCredentials();
2822
+ if (!credentials) {
2823
+ console.error("Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.");
2824
+ process.exitCode = 1;
2825
+ }
2826
+ return credentials;
2827
+ }
2828
+ function revoked(name) {
2829
+ console.error(`${name} was removed or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`);
2830
+ process.exitCode = 1;
2831
+ }
2832
+ const listCommand = defineCommand({
2833
+ meta: {
2834
+ name: "list",
2835
+ description: "List your workspaces, showing which ones this machine runs jobs in."
2836
+ },
2837
+ args: { json: {
2838
+ type: "boolean",
2839
+ description: "Print the result as JSON"
2840
+ } },
2841
+ async run({ args }) {
2842
+ const credentials = signedIn();
2843
+ if (!credentials) return;
2844
+ const result = await withCurrentToken(credentials, (token) => machineWorkspaces({
2845
+ server: credentials.server,
2846
+ token
2847
+ }));
2848
+ if (result.status === "revoked") return revoked(credentials.machine.name);
2849
+ if (result.status !== "ok") {
2850
+ console.error(`Couldn't list workspaces for ${credentials.machine.name}: ${result.status === "failed" ? result.reason : "not found"}.`);
2851
+ process.exitCode = 1;
2852
+ return;
2853
+ }
2854
+ console.log(args.json ? JSON.stringify(result.choice, null, 2) : describeMachineWorkspaces(result.choice));
2855
+ }
2856
+ });
2857
+ function changeCommand(action) {
2858
+ const adding = action === "add";
2859
+ return defineCommand({
2860
+ meta: {
2861
+ name: action,
2862
+ description: adding ? "Run jobs from one more of your workspaces on this machine." : "Stop running jobs from one of your workspaces on this machine. It keeps running jobs in the others."
2863
+ },
2864
+ args: { workspace: {
2865
+ type: "positional",
2866
+ required: false,
2867
+ description: "The workspace's name, slug or id; leave out to pick from a list"
2868
+ } },
2869
+ async run({ args }) {
2870
+ const credentials = signedIn();
2871
+ if (!credentials) return;
2872
+ const { server, machine } = credentials;
2873
+ const current = await withCurrentToken(credentials, (token) => machineWorkspaces({
2874
+ server,
2875
+ token
2876
+ }));
2877
+ if (current.status === "revoked") return revoked(machine.name);
2878
+ if (current.status !== "ok") {
2879
+ console.error(`Couldn't ${action} a workspace for ${machine.name}: ${current.status === "failed" ? current.reason : "not found"}.`);
2880
+ process.exitCode = 1;
2881
+ return;
2882
+ }
2883
+ const { workspaces, others } = current.choice;
2884
+ const picked = await pick(adding ? others : workspaces, args.workspace, {
2885
+ action,
2886
+ machine: machine.name,
2887
+ elsewhere: adding ? workspaces : others,
2888
+ noWorkspaces: !workspaces.length && !others.length,
2889
+ server
2890
+ });
2891
+ if (!picked) return;
2892
+ const result = await withCurrentToken(credentials, (token) => machineWorkspaces({
2893
+ server,
2894
+ token,
2895
+ change: {
2896
+ action,
2897
+ workspaceId: picked.id
2898
+ }
2899
+ }));
2900
+ if (result.status === "revoked") return revoked(machine.name);
2901
+ if (result.status === "not_found") {
2902
+ console.error(`You're no longer a member of ${picked.name}.`);
2903
+ process.exitCode = 1;
2904
+ return;
2905
+ }
2906
+ if (result.status === "failed") {
2907
+ console.error(`Couldn't ${action} ${picked.name}: ${result.reason}.`);
2908
+ process.exitCode = 1;
2909
+ return;
2910
+ }
2911
+ const now = result.choice;
2912
+ if (adding) {
2913
+ console.log(`${machine.name} now runs jobs in ${workspaceNames(now.workspaces)}.`);
2914
+ if (now.machine.sharing === "anyone") console.warn(`Warning: ${anyoneWarning(machine.name, picked.name)}`);
2915
+ } else if (now.workspaces.length) console.log(`${machine.name} no longer runs jobs in ${picked.name}. It still runs jobs in ${workspaceNames(now.workspaces)}.`);
2916
+ else {
2917
+ console.log(`${machine.name} no longer runs jobs in ${picked.name}.`);
2918
+ console.warn(`${machine.name} isn't in any workspace now, so it takes no jobs. Add one with \`relayrunner workspaces add <name>\`.`);
2919
+ }
2920
+ }
2921
+ });
2922
+ }
2923
+ /** The workspace to add or remove: named on the command line, or picked from a list in a terminal. */
2924
+ async function pick(candidates, query, context) {
2925
+ const fail = (message) => {
2926
+ console.error(message);
2927
+ process.exitCode = 1;
2928
+ return null;
2929
+ };
2930
+ if (context.noWorkspaces) return fail(noWorkspaceYet(context.machine, context.server));
2931
+ const adding = context.action === "add";
2932
+ if (query) {
2933
+ const match = matchWorkspace(candidates, query);
2934
+ if (match.status === "one") return match.workspace;
2935
+ if (match.status === "several") return fail([`More than one workspace is called ${JSON.stringify(query)}. Name it by id:`, ...match.workspaces.map((w) => ` ${labelWorkspace(w, true)}`)].join("\n"));
2936
+ const other = matchWorkspace(context.elsewhere, query);
2937
+ if (other.status !== "none") {
2938
+ const name = other.status === "one" ? other.workspace.name : query;
2939
+ console.log(adding ? `${context.machine} already runs jobs in ${name}.` : `${context.machine} doesn't run jobs in ${name}.`);
2940
+ return null;
2941
+ }
2942
+ return fail([`None of your workspaces is called ${JSON.stringify(query)}.`, ...candidates.length ? [adding ? "Workspaces you can add:" : "Workspaces you can remove:", ...candidates.map((w) => ` ${labelWorkspace(w)}`)] : []].join("\n"));
2943
+ }
2944
+ if (!candidates.length) {
2945
+ console.log(adding ? `${context.machine} already runs jobs in all your workspaces.` : `${context.machine} isn't in any workspace.`);
2946
+ return null;
2947
+ }
2948
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return fail(`Name the workspace: \`relayrunner workspaces ${context.action} <name>\`.`);
2949
+ const choice = await clack.select({
2950
+ message: adding ? `Which workspace should ${context.machine} run jobs in too?` : `Which workspace should ${context.machine} stop running jobs in?`,
2951
+ options: candidates.map((w) => ({
2952
+ value: w.id,
2953
+ label: w.name,
2954
+ ...w.slug && w.slug !== w.name && { hint: w.slug }
2955
+ }))
2956
+ });
2957
+ if (clack.isCancel(choice)) return null;
2958
+ return candidates.find((w) => w.id === choice) ?? null;
2959
+ }
2960
+ const workspacesCommand = defineCommand({
2961
+ meta: {
2962
+ name: "workspaces",
2963
+ description: "Show or change which of your workspaces this machine runs jobs in: `list` (the default), `add <name>`, `remove <name>`."
2964
+ },
2965
+ default: "list",
2966
+ subCommands: {
2967
+ list: listCommand,
2968
+ add: changeCommand("add"),
2969
+ remove: changeCommand("remove")
2970
+ }
2971
+ });
2972
+ /**
2973
+ * Why a machine has no workspaces, for `connect` and `whoami`: its owner has none yet (install
2974
+ * RelayRunner), or the machine just isn't in any of theirs (`relayrunner workspaces add`).
2975
+ */
2976
+ async function emptyWorkspacesNotice(credentials) {
2977
+ const { server, machine } = credentials;
2978
+ const result = await withCurrentToken(credentials, (token) => machineWorkspaces({
2979
+ server,
2980
+ token
2981
+ }));
2982
+ if (result.status === "ok" && result.choice.others.length) return `${machine.name} isn't in any of your workspaces, so it takes no jobs. Add one with \`relayrunner workspaces add <name>\` (${workspaceNames(result.choice.others)}).`;
2983
+ return noWorkspaceYet(machine.name, server);
2984
+ }
2240
2985
  // cli.ts
2241
2986
  const DEFAULT_SERVER = "https://app.relayrunner.app";
2242
2987
  const connectCommand = defineCommand({
@@ -2256,12 +3001,39 @@ const connectCommand = defineCommand({
2256
3001
  share: {
2257
3002
  type: "string",
2258
3003
  description: "Who can run jobs on this machine: only-me (jobs you started) or anyone in your workspaces. Skips the question."
3004
+ },
3005
+ concurrency: {
3006
+ type: "string",
3007
+ description: "How many jobs to run at once (default: 2 with 8 or more CPU cores, otherwise 1)"
3008
+ },
3009
+ isolated: {
3010
+ 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."
3012
+ },
3013
+ image: {
3014
+ type: "string",
3015
+ description: "With --isolated, the runner image to build on (default: GitHub's runner image)"
3016
+ },
3017
+ "local-network": {
3018
+ type: "boolean",
3019
+ description: "With --isolated, let jobs reach this Mac and your local network. They can't by default."
2259
3020
  }
2260
3021
  },
2261
3022
  async run({ args }) {
2262
3023
  clack.intro("RelayRunner");
3024
+ let concurrency;
3025
+ try {
3026
+ concurrency = parseConcurrency(args.concurrency);
3027
+ } catch (error) {
3028
+ clack.log.error(error.message);
3029
+ process.exitCode = 1;
3030
+ return;
3031
+ }
2263
3032
  try {
2264
- await connectMachine(args);
3033
+ await connectMachine({
3034
+ ...args,
3035
+ concurrency
3036
+ });
2265
3037
  } catch (error) {
2266
3038
  if (!(error instanceof LoginError || error instanceof RunnerError)) throw error;
2267
3039
  clack.log.error(error.message);
@@ -2271,7 +3043,15 @@ const connectCommand = defineCommand({
2271
3043
  });
2272
3044
  async function connectMachine(args) {
2273
3045
  const share = shareArg(args.share);
2274
- const platform = machinePlatform();
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.");
3048
+ const host = machinePlatform();
3049
+ const unsupported = args.isolated ? unsupportedReason() : null;
3050
+ if (unsupported) throw new RunnerError("ISOLATED_UNSUPPORTED", unsupported);
3051
+ const platform = args.isolated ? {
3052
+ os: "linux",
3053
+ arch: host.arch
3054
+ } : host;
2275
3055
  let credentials = readCredentials();
2276
3056
  const server = serverFor(args.server, credentials);
2277
3057
  if (credentials && credentials.server !== server) {
@@ -2284,7 +3064,36 @@ async function connectMachine(args) {
2284
3064
  if (share) await applySharing(credentials, share, null);
2285
3065
  }
2286
3066
  if (process.stdin.isTTY && process.stdout.isTTY) await offerSetup();
2287
- const runner = await ensureRunner({ log: (line) => clack.log.info(line) });
3067
+ let updateTimer;
3068
+ if (process.stdout.isTTY && !process.env.CI) {
3069
+ const notifyUpdate = () => void checkForUpdate().then((latest) => {
3070
+ if (latest) clack.log.warn(updateNotice(latest));
3071
+ });
3072
+ notifyUpdate();
3073
+ updateTimer = setInterval(notifyUpdate, CHECK_INTERVAL_MS);
3074
+ updateTimer.unref();
3075
+ }
3076
+ const slots = args.concurrency;
3077
+ const log = (line) => clack.log.info(line);
3078
+ let runnerVersion;
3079
+ let launchers;
3080
+ if (args.isolated) {
3081
+ const isolation = await prepareIsolation({
3082
+ slots,
3083
+ image: args.image,
3084
+ localNetwork: args["local-network"],
3085
+ log,
3086
+ debug: debugLog()
3087
+ });
3088
+ runnerVersion = isolation.runnerVersion;
3089
+ launchers = Array(slots).fill(isolatedLauncher(isolation));
3090
+ } else {
3091
+ const [runner, canIsolate] = await Promise.all([ensureRunner({ log }), isolationAvailable()]);
3092
+ runnerVersion = runner.version;
3093
+ 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.");
3095
+ }
3096
+ clack.log.info(slots === 1 ? "Running 1 job at a time. Change with --concurrency." : `Running up to ${slots} jobs at once. Change with --concurrency.`);
2288
3097
  const device = await detectDevice();
2289
3098
  const stop = new AbortController();
2290
3099
  const enrolled = credentials;
@@ -2316,25 +3125,36 @@ async function connectMachine(args) {
2316
3125
  hello: {
2317
3126
  machineId: credentials.machine.id,
2318
3127
  ...platform,
2319
- runnerVersion: runner.version,
3128
+ runnerVersion,
3129
+ cliVersion,
2320
3130
  device
2321
3131
  },
2322
- runJob: (run, report) => runJob(run, {
2323
- runner,
2324
- report,
2325
- onChecked: (target) => {
2326
- if (target) clack.log.info(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} Job ${run.routeId} is from ${target}`);
3132
+ slots,
3133
+ runJob: async (run, slot, report) => {
3134
+ const prefixed = slots > 1 ? prefixLines(`[slot ${slot}] `, (chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk)) : void 0;
3135
+ try {
3136
+ return await runJob(run, {
3137
+ launcher: launchers[slot - 1],
3138
+ report,
3139
+ output: prefixed?.output,
3140
+ onChecked: (target) => {
3141
+ if (target) clack.log.info(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} Job ${run.routeId}${slots > 1 ? ` (slot ${slot})` : ""} is from ${target}`);
3142
+ }
3143
+ });
3144
+ } finally {
3145
+ prefixed?.flush();
2327
3146
  }
2328
- }),
3147
+ },
2329
3148
  saveToken: (token) => saveRotatedToken(credentials, token),
2330
3149
  onEvent: (event) => {
2331
3150
  if (event.type === "connected") online = true;
2332
- show(event);
3151
+ show(event, slots > 1);
2333
3152
  live.onEvent(event);
2334
3153
  },
2335
3154
  signal: stop.signal
2336
3155
  });
2337
3156
  } finally {
3157
+ clearInterval(updateTimer);
2338
3158
  live.end();
2339
3159
  process.off("SIGINT", onInterrupt);
2340
3160
  }
@@ -2403,7 +3223,7 @@ async function applySharing(credentials, choice, workspaces) {
2403
3223
  const loginCommand = defineCommand({
2404
3224
  meta: {
2405
3225
  name: "login",
2406
- description: "Sign this machine in without putting it online. It's in all your workspaces. Run `relayrunner connect` afterwards to take jobs."
3226
+ description: "Sign this machine in without putting it online. You pick its workspaces when you approve it. Run `relayrunner connect` afterwards to take jobs."
2407
3227
  },
2408
3228
  args: {
2409
3229
  server: {
@@ -2468,9 +3288,9 @@ function machinePlatform() {
2468
3288
  async function enroll(server, name, platform, share) {
2469
3289
  const { credentials, workspaces } = await signIn(server, name || await defaultMachineName(), platform);
2470
3290
  writeCredentials(credentials);
2471
- const where = workspaces.length ? ` in ${workspaceNames(workspaces)}` : "";
2472
- clack.log.success(`Enrolled as ${credentials.machine.name}${where}. Token saved to ${credentialsPath()}.`);
2473
- if (!workspaces.length) clack.log.warn(noWorkspaceYet(credentials.machine.name, server));
3291
+ clack.log.success(`Enrolled as ${credentials.machine.name}. Token saved to ${credentialsPath()}.`);
3292
+ if (workspaces.length) clack.log.info(`Runs jobs in ${workspaceNames(workspaces)}.\nChange with: relayrunner workspaces`);
3293
+ else clack.log.warn(await emptyWorkspacesNotice(credentials));
2474
3294
  let choice = share;
2475
3295
  if (!choice && hasTeammates(workspaces)) {
2476
3296
  if (process.stdin.isTTY && process.stdout.isTTY) choice = await askSharing(workspaces);
@@ -2499,7 +3319,7 @@ async function signIn(server, name, platform) {
2499
3319
  throw error;
2500
3320
  }
2501
3321
  }
2502
- function show(event) {
3322
+ function show(event, slotted) {
2503
3323
  const at = (/* @__PURE__ */ new Date()).toLocaleTimeString();
2504
3324
  switch (event.type) {
2505
3325
  case "connecting":
@@ -2515,7 +3335,7 @@ function show(event) {
2515
3335
  clack.log.error(`${at} Gateway: ${event.message}`);
2516
3336
  break;
2517
3337
  case "run":
2518
- clack.log.step(`${at} Starting job ${event.routeId}`);
3338
+ clack.log.step(`${at} Starting job ${event.routeId}${slotted ? ` in slot ${event.slot}` : ""}`);
2519
3339
  break;
2520
3340
  case "paused":
2521
3341
  if (event.paused) clack.log.warn(`${at} Paused${event.by ? ` by ${event.by}` : ""}. Staying online, but new jobs skip this machine until it's resumed.${process.stdin.isTTY ? " Press p to resume." : ""}`);
@@ -2525,11 +3345,11 @@ function show(event) {
2525
3345
  clack.log.warn(`${at} Couldn't save the machine's new token (${event.message}). Keeping the old one.`);
2526
3346
  break;
2527
3347
  case "run-refused":
2528
- clack.log.warn(`${at} Turned down job ${event.routeId}: already running one.`);
3348
+ clack.log.warn(`${at} Turned down job ${event.routeId}: already running ${event.running === 1 ? "one" : `${event.running}`}.`);
2529
3349
  break;
2530
3350
  case "job": {
2531
3351
  const { routeId, state, message } = event.update;
2532
- const line = `${at} Job ${routeId} ${state}${message ? `: ${message}` : ""}`;
3352
+ const line = `${at} Job ${routeId}${slotted ? ` (slot ${event.slot})` : ""} ${state}${message ? `: ${message}` : ""}`;
2533
3353
  if (state === "failed") clack.log.error(line);
2534
3354
  else if (state === "finished") clack.log.success(line);
2535
3355
  else clack.log.info(line);
@@ -2575,7 +3395,7 @@ const whoamiCommand = defineCommand({
2575
3395
  }));
2576
3396
  switch (result.status) {
2577
3397
  case "ok":
2578
- print(describeIdentity(credentials.server, result.identity), {
3398
+ print(describeIdentity(credentials.server, result.identity, !args.json && !readWorkspaces(result.identity).length ? await emptyWorkspacesNotice(credentials) : void 0), {
2579
3399
  status: "ok",
2580
3400
  server: credentials.server,
2581
3401
  ...result.identity
@@ -2596,19 +3416,20 @@ const whoamiCommand = defineCommand({
2596
3416
  }
2597
3417
  }
2598
3418
  });
2599
- function describeIdentity(server, identity) {
3419
+ function describeIdentity(server, identity, emptyNotice) {
2600
3420
  const { machine, enrolledBy } = identity;
2601
3421
  const workspaces = readWorkspaces(identity);
2602
3422
  const status = (machine.status.online ? `online${machine.status.state ? `, ${machine.status.state}` : ""}` : "offline") + (machine.paused ? `, paused${machine.paused.by ? ` by ${machine.paused.by}` : ""}` : "");
2603
3423
  const enrolled = [enrolledBy && `by ${enrolledBy.name} <${enrolledBy.email}>`, `on ${new Date(machine.createdAt).toLocaleDateString()}`].filter(Boolean).join(" ");
2604
- return table(`${machine.name} (${machine.id})`, [
2605
- ["Workspaces", workspaces.length ? workspaceNames(workspaces) : "none yet: install RelayRunner on GitHub to get one"],
3424
+ const details = table(`${machine.name} (${machine.id})`, [
3425
+ ["Workspaces", workspaces.length ? workspaceNames(workspaces) : "none"],
2606
3426
  ["Platform", [machine.os, machine.arch].filter(Boolean).join(" ") || "unknown"],
2607
3427
  ["Enrolled", enrolled],
2608
3428
  ["Status", status],
2609
3429
  ...machine.sharing ? [["Sharing", describeSharing(machine.sharing, sharingScope(workspaces))]] : [],
2610
3430
  ["Gateway", server]
2611
3431
  ]);
3432
+ return emptyNotice ? `${details}\n\n${emptyNotice}` : details;
2612
3433
  }
2613
3434
  function describeSaved(saved) {
2614
3435
  return table(`${saved.machine.name} (${saved.machine.id})`, [["Gateway", saved.server]]);
@@ -2718,6 +3539,7 @@ const shareCommand = defineCommand({
2718
3539
  const main = defineCommand({
2719
3540
  meta: {
2720
3541
  name: "relayrunner",
3542
+ version: cliVersion,
2721
3543
  description: "Run GitHub Actions jobs on your machine through the RelayRunner gateway."
2722
3544
  },
2723
3545
  subCommands: {
@@ -2727,7 +3549,8 @@ const main = defineCommand({
2727
3549
  init: initCommand,
2728
3550
  pause: pauseCommand(true),
2729
3551
  resume: pauseCommand(false),
2730
- share: shareCommand
3552
+ share: shareCommand,
3553
+ workspaces: workspacesCommand
2731
3554
  }
2732
3555
  });
2733
3556
  runMain(main);