relayrunner 0.7.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 +42 -0
  2. package/dist/cli.js +710 -100
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -64,6 +64,23 @@ approved the machine also gets an email, since someone else may have its token.
64
64
  `~/.relayrunner/runner/<version>/slot-<n>/`, made when `connect` starts (a
65
65
  copy-on-write clone where the disk supports it). With more than one slot,
66
66
  each line of a job's output starts with its slot, such as `[slot 2]`.
67
+ - `--isolated` (experimental) runs each job in its own Linux VM, so a job can't
68
+ read your files or the machine token. It needs a Mac with Apple silicon,
69
+ macOS 26 and Apple's [container](https://github.com/apple/container/releases)
70
+ tool, started with `container system start`. Each VM starts from GitHub's
71
+ runner image with nothing mounted and is deleted when the job ends. Jobs run
72
+ on Linux arm64, and Docker works in them. `connect` builds the job image
73
+ once per runner version.
74
+ - A firewall in the VM lets the job reach the internet but not your Mac or
75
+ your local network. It guards against accidents: a job that sets out to
76
+ remove it can, through Docker. `--local-network` turns the firewall off,
77
+ for jobs that need something on your network.
78
+ - `--image <image>` starts from another runner image.
79
+ - `connect` removes the images it downloaded or built for older runner
80
+ versions. It never removes images you got yourself.
81
+ - `~/.relayrunner/isolated.log` records each `container` command and its
82
+ result, never a job's output or credentials. Send it along when you report
83
+ a problem.
67
84
  - If the machine is removed in the dashboard, `connect` deletes the saved token.
68
85
  A running `connect` exits and asks you to run it again; a new one signs in
69
86
  straight away.
@@ -74,6 +91,10 @@ this machine?": Only me, or Anyone in your workspaces (teammates' and bots' jobs
74
91
  too). It doesn't ask when you're alone in all of them, on later runs, or without
75
92
  a terminal to answer. [`relayrunner share`](#relayrunner-share) changes it later.
76
93
 
94
+ When you approve the machine in the browser, you pick which of your workspaces it
95
+ runs jobs in. `connect` then prints them with `Change with: relayrunner workspaces`
96
+ ([`relayrunner workspaces`](#relayrunner-workspaces)).
97
+
77
98
  Run inside a checkout of a private repo where no job uses RelayRunner yet,
78
99
  `connect` first asks whether to set it up (default no). Yes runs the same picker
79
100
  as [`relayrunner init`](#relayrunner-init). No is remembered for that repo in
@@ -179,6 +200,27 @@ It's the same setting as the sharing icon on the machine's card on the Runners
179
200
  page, and only the machine's owner can change it there. `relayrunner whoami`
180
201
  shows it too. Exits 1 when not signed in or when the token is no longer valid.
181
202
 
203
+ ## `relayrunner workspaces`
204
+
205
+ ```sh
206
+ npx relayrunner workspaces # list the ones it's in and the ones it isn't
207
+ npx relayrunner workspaces add acme # run jobs from Acme here too
208
+ npx relayrunner workspaces remove acme # stop running Acme's jobs here
209
+ ```
210
+
211
+ Which of your workspaces this machine runs jobs in, the same choice as the
212
+ "Run jobs in" checkboxes when you approve it. `list` (the default) shows the
213
+ workspaces it's in, the ones it isn't, and its sharing; `--json` prints the same
214
+ as JSON. `add` and `remove` take a workspace's name or slug in any case, or its
215
+ id when two have the same name. Leave the name out in a terminal to pick from a
216
+ list.
217
+
218
+ Adding a workspace while the machine is set to `anyone` warns that anyone who can
219
+ push to that workspace's private repos can run jobs on it. Removing the last one
220
+ leaves the machine connected but taking no jobs until you add one back. Exits 1
221
+ when not signed in, when the token is no longer valid, or when no workspace has
222
+ that name.
223
+
182
224
  ## Building
183
225
 
184
226
  `pnpm --filter relayrunner build` bundles the CLI into `dist/cli.js` with
package/dist/cli.js CHANGED
@@ -2,9 +2,9 @@
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, 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, constants, cpSync, 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";
@@ -145,8 +145,25 @@ function parse$1(schema, frame) {
145
145
  function isRunnerForRoute(runnerName, routeId) {
146
146
  return runnerName.endsWith(`-${routeId}`);
147
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
+ }
148
165
  // version.ts
149
- const cliVersion = "0.7.0";
166
+ const cliVersion = "0.8.0";
150
167
  // paths.ts
151
168
  function relayrunnerHome() {
152
169
  return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), ".relayrunner"));
@@ -170,6 +187,7 @@ async function connect(options) {
170
187
  const heartbeatMs = options.heartbeatMs ?? 3e4;
171
188
  const minBackoffMs = options.minBackoffMs ?? 1e3;
172
189
  const maxBackoffMs = options.maxBackoffMs ?? 3e4;
190
+ const reconnectSpreadMs = options.reconnectSpreadMs ?? 1e4;
173
191
  const emit = options.onEvent ?? (() => {});
174
192
  const signal = options.signal;
175
193
  const slots = options.slots ?? 1;
@@ -350,7 +368,7 @@ async function connect(options) {
350
368
  message: gatewayError || reason || "protocol error"
351
369
  };
352
370
  if (!opened && await tokenRejected()) return { reason: "revoked" };
353
- const retryInMs = backoff(attempt, minBackoffMs, maxBackoffMs);
371
+ const retryInMs = opened ? Math.round(Math.random() * reconnectSpreadMs) : backoff(attempt, minBackoffMs, maxBackoffMs);
354
372
  emit({
355
373
  type: "disconnected",
356
374
  code,
@@ -420,13 +438,23 @@ function pickDownload(release, target) {
420
438
  sha256
421
439
  };
422
440
  }
423
- async function latestDownload(target) {
441
+ async function latestRelease() {
424
442
  const response = await fetch(LATEST_RELEASE, { headers: {
425
443
  accept: "application/vnd.github+json",
426
444
  "user-agent": userAgent
427
445
  } });
428
446
  if (!response.ok) throw new RunnerError("RUNNER_DOWNLOAD", `Could not look up the latest actions/runner release (HTTP ${response.status}).`);
429
- 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
+ }
430
458
  }
431
459
  function installedRunners(root = runnersDir()) {
432
460
  if (!existsSync(root)) return [];
@@ -446,7 +474,7 @@ async function ensureRunner(options = {}) {
446
474
  const target = runnerPlatform();
447
475
  let download;
448
476
  try {
449
- download = await latestDownload(target);
477
+ download = pickDownload(await latestRelease(), target);
450
478
  } catch (error) {
451
479
  const [newest] = installedRunners(root);
452
480
  if (newest) {
@@ -622,7 +650,7 @@ const run = (command, args) => new Promise((resolve) => {
622
650
  resolve(error ? null : stdout.trim() || null);
623
651
  });
624
652
  });
625
- const read$1 = (path) => {
653
+ const read = (path) => {
626
654
  try {
627
655
  return readFileSync(path, "utf8").replaceAll("\0", "").trim() || null;
628
656
  } catch {
@@ -633,7 +661,7 @@ function defaultSources() {
633
661
  const list = cpus();
634
662
  return {
635
663
  run,
636
- read: read$1,
664
+ read,
637
665
  cpuModel: list[0]?.model,
638
666
  cpuCount: list.length,
639
667
  totalMemory: totalmem()
@@ -787,11 +815,8 @@ function compact(device) {
787
815
  }
788
816
  return out;
789
817
  }
790
- // declined.ts
791
- function declinedPath(home = relayrunnerHome()) {
792
- return join(home, "declined-repos.json");
793
- }
794
- function read(path) {
818
+ // list-file.ts
819
+ function readList(path) {
795
820
  try {
796
821
  const value = JSON.parse(readFileSync(path, "utf8"));
797
822
  return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
@@ -799,17 +824,23 @@ function read(path) {
799
824
  return [];
800
825
  }
801
826
  }
802
- function isDeclined(repo, path = declinedPath()) {
803
- return read(path).includes(repo);
804
- }
805
- function rememberDeclined(repo, path = declinedPath()) {
806
- const repos = read(path);
807
- if (repos.includes(repo)) return;
827
+ function writeList(path, list) {
808
828
  mkdirSync(dirname(path), {
809
829
  recursive: true,
810
830
  mode: 448
811
831
  });
812
- 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]);
813
844
  }
814
845
  // diff.ts
815
846
  function unifiedDiff(before, after, file, context = 2) {
@@ -949,7 +980,13 @@ const RATES = {
949
980
  macos: "runner"
950
981
  }
951
982
  };
952
- 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;
953
990
  const vcpu = (perRunner, vcpus) => perRunner / vcpus;
954
991
  const BASE_PRICES = [
955
992
  {
@@ -1144,7 +1181,9 @@ const LABEL_PREFIXES = {
1144
1181
  ubicloud: ["ubicloud-"],
1145
1182
  "runs-on": ["runs-on=", "runs-on/"]
1146
1183
  };
1147
- 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);
1148
1187
  /** The hosted provider whose runners a label asks for, or null. */
1149
1188
  function hostedProviderOf(label) {
1150
1189
  const lower = label.toLowerCase();
@@ -1724,79 +1763,81 @@ const runnerEnv = () => Object.fromEntries([
1724
1763
  "TMPDIR",
1725
1764
  "SHELL"
1726
1765
  ].flatMap((key) => process.env[key] === void 0 ? [] : [[key, process.env[key]]]));
1727
- const JOB_STATE = [
1728
- "_work",
1729
- ".runner",
1730
- ".credentials",
1731
- ".credentials_rsaparams"
1732
- ];
1733
1766
  async function runJob(run, options) {
1734
- const { dir, report } = options;
1767
+ const { launcher, report } = options;
1768
+ const { routeId } = run;
1735
1769
  const output = options.output ?? ((chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk));
1736
1770
  const finish = (update) => {
1737
1771
  report(update);
1738
1772
  return update;
1739
1773
  };
1740
- const checked = checkJitConfig(run.jitConfig, run.routeId);
1741
- if (!checked.ok) return finish({
1742
- routeId: run.routeId,
1774
+ const failed = (message) => finish({
1775
+ routeId,
1743
1776
  state: "failed",
1744
- message: `Refused the job's runner config: ${checked.reason}.`
1777
+ message
1745
1778
  });
1779
+ const checked = checkJitConfig(run.jitConfig, routeId);
1780
+ if (!checked.ok) return failed(`Refused the job's runner config: ${checked.reason}.`);
1746
1781
  options.onChecked?.(checked.target);
1747
- const lock = join(dir, "job.lock");
1748
- if (!takeLock(lock)) return finish({
1749
- routeId: run.routeId,
1750
- state: "failed",
1751
- message: `Another job is using the runner in ${dir}.`
1752
- });
1782
+ let clean = false;
1753
1783
  try {
1754
- clean(dir);
1755
- const child = spawn(join(dir, "run.sh"), ["--jitconfig", run.jitConfig], {
1756
- cwd: dir,
1757
- env: runnerEnv(),
1758
- stdio: [
1759
- "ignore",
1760
- "pipe",
1761
- "pipe"
1762
- ]
1763
- });
1784
+ const child = launcher.start(run);
1764
1785
  child.stdout.on("data", (chunk) => output(chunk, "stdout"));
1765
1786
  child.stderr.on("data", (chunk) => output(chunk, "stderr"));
1766
1787
  const started = await new Promise((resolve) => {
1767
1788
  child.once("spawn", () => resolve(null));
1768
1789
  child.once("error", resolve);
1769
1790
  });
1770
- if (started) return finish({
1771
- routeId: run.routeId,
1772
- state: "failed",
1773
- message: `Could not start the runner: ${started.message}`
1774
- });
1791
+ if (started) return failed(`Could not start the runner: ${started.message}`);
1775
1792
  report({
1776
- routeId: run.routeId,
1793
+ routeId,
1777
1794
  state: "started"
1778
1795
  });
1779
1796
  const [code, signal] = await new Promise((resolve) => child.once("close", (code, signal) => resolve([code, signal])));
1780
- if (code === 0) return finish({
1781
- routeId: run.routeId,
1797
+ clean = code === 0;
1798
+ if (clean) return finish({
1799
+ routeId,
1782
1800
  state: "finished"
1783
1801
  });
1784
- return finish({
1785
- routeId: run.routeId,
1786
- state: "failed",
1787
- message: signal ? `run.sh was stopped by ${signal}` : `run.sh exited with ${code}`
1788
- });
1802
+ return failed(signal ? `The runner was stopped by ${signal}` : `The runner exited with ${code}`);
1789
1803
  } catch (error) {
1790
- return finish({
1791
- routeId: run.routeId,
1792
- state: "failed",
1793
- message: error instanceof Error ? error.message : String(error)
1794
- });
1804
+ return failed(error instanceof Error ? error.message : String(error));
1795
1805
  } finally {
1796
- clean(dir);
1797
- rmSync(lock, { force: true });
1806
+ await launcher.cleanup(run, clean);
1798
1807
  }
1799
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
+ }
1800
1841
  function clean(dir) {
1801
1842
  for (const name of JOB_STATE) rmSync(join(dir, name), {
1802
1843
  recursive: true,
@@ -1847,6 +1888,278 @@ function prefixLines(prefix, write) {
1847
1888
  flush
1848
1889
  };
1849
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
+ }
1850
2163
  // live.ts
1851
2164
  const INITIAL_STATE = {
1852
2165
  link: "connecting",
@@ -1983,27 +2296,12 @@ async function checkForUpdate(options = {}) {
1983
2296
  writeCache(cache);
1984
2297
  }
1985
2298
  }
1986
- return cache && isNewer(cache.latest, current) ? cache.latest : null;
2299
+ return cache && isNewerVersion(cache.latest, current) ? cache.latest : null;
1987
2300
  }
1988
2301
  /** The line to print for a newer version, with the command that updates the way this one runs. */
1989
2302
  function updateNotice(latest, current = cliVersion, argv1 = process.argv[1] ?? "") {
1990
2303
  return `relayrunner ${latest} is available (you have ${current}). Update with \`${/[\\/]_npx[\\/]/.test(argv1) ? "npx relayrunner@latest connect" : "npm install --global relayrunner@latest"}\`.`;
1991
2304
  }
1992
- function isNewer(candidate, current) {
1993
- const a = parse(candidate);
1994
- const b = parse(current);
1995
- if (!a || !b) return false;
1996
- for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
1997
- return false;
1998
- }
1999
- function parse(version) {
2000
- const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version.trim());
2001
- return match ? [
2002
- Number(match[1]),
2003
- Number(match[2]),
2004
- Number(match[3])
2005
- ] : null;
2006
- }
2007
2305
  async function fetchLatest(fetcher) {
2008
2306
  try {
2009
2307
  const response = await fetcher(REGISTRY_URL, {
@@ -2411,6 +2709,279 @@ async function whoami(options) {
2411
2709
  identity: parsed.data
2412
2710
  };
2413
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
+ }
2414
2985
  // cli.ts
2415
2986
  const DEFAULT_SERVER = "https://app.relayrunner.app";
2416
2987
  const connectCommand = defineCommand({
@@ -2434,6 +3005,18 @@ const connectCommand = defineCommand({
2434
3005
  concurrency: {
2435
3006
  type: "string",
2436
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."
2437
3020
  }
2438
3021
  },
2439
3022
  async run({ args }) {
@@ -2460,7 +3043,15 @@ const connectCommand = defineCommand({
2460
3043
  });
2461
3044
  async function connectMachine(args) {
2462
3045
  const share = shareArg(args.share);
2463
- 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;
2464
3055
  let credentials = readCredentials();
2465
3056
  const server = serverFor(args.server, credentials);
2466
3057
  if (credentials && credentials.server !== server) {
@@ -2482,9 +3073,26 @@ async function connectMachine(args) {
2482
3073
  updateTimer = setInterval(notifyUpdate, CHECK_INTERVAL_MS);
2483
3074
  updateTimer.unref();
2484
3075
  }
2485
- const runner = await ensureRunner({ log: (line) => clack.log.info(line) });
2486
3076
  const slots = args.concurrency;
2487
- const slotDirs = ensureSlots(runner, slots, (line) => clack.log.info(line));
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
+ }
2488
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.`);
2489
3097
  const device = await detectDevice();
2490
3098
  const stop = new AbortController();
@@ -2517,7 +3125,7 @@ async function connectMachine(args) {
2517
3125
  hello: {
2518
3126
  machineId: credentials.machine.id,
2519
3127
  ...platform,
2520
- runnerVersion: runner.version,
3128
+ runnerVersion,
2521
3129
  cliVersion,
2522
3130
  device
2523
3131
  },
@@ -2526,7 +3134,7 @@ async function connectMachine(args) {
2526
3134
  const prefixed = slots > 1 ? prefixLines(`[slot ${slot}] `, (chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk)) : void 0;
2527
3135
  try {
2528
3136
  return await runJob(run, {
2529
- dir: slotDirs[slot - 1],
3137
+ launcher: launchers[slot - 1],
2530
3138
  report,
2531
3139
  output: prefixed?.output,
2532
3140
  onChecked: (target) => {
@@ -2615,7 +3223,7 @@ async function applySharing(credentials, choice, workspaces) {
2615
3223
  const loginCommand = defineCommand({
2616
3224
  meta: {
2617
3225
  name: "login",
2618
- 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."
2619
3227
  },
2620
3228
  args: {
2621
3229
  server: {
@@ -2680,9 +3288,9 @@ function machinePlatform() {
2680
3288
  async function enroll(server, name, platform, share) {
2681
3289
  const { credentials, workspaces } = await signIn(server, name || await defaultMachineName(), platform);
2682
3290
  writeCredentials(credentials);
2683
- const where = workspaces.length ? ` in ${workspaceNames(workspaces)}` : "";
2684
- clack.log.success(`Enrolled as ${credentials.machine.name}${where}. Token saved to ${credentialsPath()}.`);
2685
- 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));
2686
3294
  let choice = share;
2687
3295
  if (!choice && hasTeammates(workspaces)) {
2688
3296
  if (process.stdin.isTTY && process.stdout.isTTY) choice = await askSharing(workspaces);
@@ -2787,7 +3395,7 @@ const whoamiCommand = defineCommand({
2787
3395
  }));
2788
3396
  switch (result.status) {
2789
3397
  case "ok":
2790
- print(describeIdentity(credentials.server, result.identity), {
3398
+ print(describeIdentity(credentials.server, result.identity, !args.json && !readWorkspaces(result.identity).length ? await emptyWorkspacesNotice(credentials) : void 0), {
2791
3399
  status: "ok",
2792
3400
  server: credentials.server,
2793
3401
  ...result.identity
@@ -2808,19 +3416,20 @@ const whoamiCommand = defineCommand({
2808
3416
  }
2809
3417
  }
2810
3418
  });
2811
- function describeIdentity(server, identity) {
3419
+ function describeIdentity(server, identity, emptyNotice) {
2812
3420
  const { machine, enrolledBy } = identity;
2813
3421
  const workspaces = readWorkspaces(identity);
2814
3422
  const status = (machine.status.online ? `online${machine.status.state ? `, ${machine.status.state}` : ""}` : "offline") + (machine.paused ? `, paused${machine.paused.by ? ` by ${machine.paused.by}` : ""}` : "");
2815
3423
  const enrolled = [enrolledBy && `by ${enrolledBy.name} <${enrolledBy.email}>`, `on ${new Date(machine.createdAt).toLocaleDateString()}`].filter(Boolean).join(" ");
2816
- return table(`${machine.name} (${machine.id})`, [
2817
- ["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"],
2818
3426
  ["Platform", [machine.os, machine.arch].filter(Boolean).join(" ") || "unknown"],
2819
3427
  ["Enrolled", enrolled],
2820
3428
  ["Status", status],
2821
3429
  ...machine.sharing ? [["Sharing", describeSharing(machine.sharing, sharingScope(workspaces))]] : [],
2822
3430
  ["Gateway", server]
2823
3431
  ]);
3432
+ return emptyNotice ? `${details}\n\n${emptyNotice}` : details;
2824
3433
  }
2825
3434
  function describeSaved(saved) {
2826
3435
  return table(`${saved.machine.name} (${saved.machine.id})`, [["Gateway", saved.server]]);
@@ -2940,7 +3549,8 @@ const main = defineCommand({
2940
3549
  init: initCommand,
2941
3550
  pause: pauseCommand(true),
2942
3551
  resume: pauseCommand(false),
2943
- share: shareCommand
3552
+ share: shareCommand,
3553
+ workspaces: workspacesCommand
2944
3554
  }
2945
3555
  });
2946
3556
  runMain(main);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "relayrunner",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Run GitHub Actions jobs on your machine through the RelayRunner gateway.",
5
5
  "repository": {
6
6
  "type": "git",