relayrunner 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -2
- package/dist/cli.js +1025 -30
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
# RelayRunner CLI
|
|
2
2
|
|
|
3
3
|
Connects a machine to the RelayRunner gateway so it can run your workspace's
|
|
4
|
-
GitHub Actions jobs.
|
|
5
|
-
|
|
4
|
+
GitHub Actions jobs. It's published to npm as
|
|
5
|
+
[`relayrunner`](https://www.npmjs.com/package/relayrunner) and needs Node.js 22
|
|
6
|
+
or newer on macOS or Linux (x64 or ARM64).
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install --global relayrunner # or use npx relayrunner
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Machines only take jobs from private repositories. To opt jobs in, see the
|
|
13
|
+
[root README](../../README.md#how-it-works) or
|
|
14
|
+
[docs/agent-install.md](../../docs/agent-install.md).
|
|
6
15
|
|
|
7
16
|
## `relayrunner connect`
|
|
8
17
|
|
|
@@ -21,14 +30,45 @@ running stops with it.
|
|
|
21
30
|
|
|
22
31
|
- `--server <url>` or `RELAYRUNNER_URL` points it at another gateway. Changing it signs in again.
|
|
23
32
|
- `--name <name>` changes the suggested machine name (default: the hostname).
|
|
33
|
+
- `--share only-me|anyone` sets who can run jobs on this machine without asking.
|
|
34
|
+
It works on a machine that's already signed in too.
|
|
24
35
|
- If the machine is removed in the dashboard, `connect` deletes the saved token.
|
|
25
36
|
A running `connect` exits and asks you to run it again; a new one signs in
|
|
26
37
|
straight away.
|
|
27
38
|
|
|
39
|
+
A new machine runs only jobs you started (`only-me`). Right after signing in,
|
|
40
|
+
if the workspace has other members, `connect` asks "Who can run jobs on this
|
|
41
|
+
machine?": Only me, or Anyone in the workspace (teammates' and bots' jobs too).
|
|
42
|
+
It doesn't ask in a workspace of one, on later runs, or without a terminal to
|
|
43
|
+
answer. [`relayrunner share`](#relayrunner-share) changes it later.
|
|
44
|
+
|
|
45
|
+
Run inside a checkout of a private repo where no job uses RelayRunner yet,
|
|
46
|
+
`connect` first asks whether to set it up (default no). Yes runs the same picker
|
|
47
|
+
as [`relayrunner init`](#relayrunner-init). No is remembered for that repo in
|
|
48
|
+
`~/.relayrunner/declined-repos.json`, so it doesn't ask again; `init` still
|
|
49
|
+
works there. It never asks outside a repo, in a public repo, in a repo that's
|
|
50
|
+
already set up, or without a terminal to answer.
|
|
51
|
+
|
|
28
52
|
Jobs run in `actions/runner`, which is downloaded into
|
|
29
53
|
`~/.relayrunner/runner/<version>` on first connect and checked against its
|
|
30
54
|
SHA-256. Set `RELAYRUNNER_HOME` to keep everything somewhere else.
|
|
31
55
|
|
|
56
|
+
## `relayrunner login`
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
npx relayrunner login
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Signs this machine in without putting it online: the same browser sign-in as the
|
|
63
|
+
first `connect`, then it saves the token and exits. It's for a coding agent
|
|
64
|
+
setting up RelayRunner (see [docs/agent-install.md](../../docs/agent-install.md)),
|
|
65
|
+
which can't keep `connect` running after its session ends. Run `connect`
|
|
66
|
+
afterwards to take jobs.
|
|
67
|
+
|
|
68
|
+
If the machine is already signed in to that gateway, it says so and exits. A
|
|
69
|
+
token that's no longer valid is replaced. `--server`, `--name` and `--share` work as they do
|
|
70
|
+
for `connect`.
|
|
71
|
+
|
|
32
72
|
## `relayrunner whoami`
|
|
33
73
|
|
|
34
74
|
```sh
|
|
@@ -45,6 +85,39 @@ its workspace, who enrolled it (name and email) and whether it's online now.
|
|
|
45
85
|
- `--json` prints the same as JSON (never the token). `--server <url>` or
|
|
46
86
|
`RELAYRUNNER_URL` only reports a sign-in for that gateway.
|
|
47
87
|
|
|
88
|
+
## `relayrunner init`
|
|
89
|
+
|
|
90
|
+
```sh
|
|
91
|
+
npx relayrunner init
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Run inside a checkout, it routes the repo's GitHub Actions jobs through
|
|
95
|
+
RelayRunner: each chosen job gets a `relay-<job>` job in front of it (the
|
|
96
|
+
reusable workflow in [relayrunner/actions](https://github.com/relayrunner/actions)),
|
|
97
|
+
and its `runs-on` becomes the relay's answer. The job's old label becomes the
|
|
98
|
+
fallback when no machine is free. It only edits `.github/workflows/`, keeps
|
|
99
|
+
comments and formatting, and never commits.
|
|
100
|
+
|
|
101
|
+
It sorts every job into one of three groups:
|
|
102
|
+
|
|
103
|
+
- **Ready**: a plain GitHub-hosted (`ubuntu-*`, `macos-*`) or Blacksmith
|
|
104
|
+
(`blacksmith-*`) label. A `macos-*` job only routes to macOS machines.
|
|
105
|
+
Warnings flag what to check first: services or containers (need Docker),
|
|
106
|
+
Linux package installs on a Mac, Blacksmith-only actions.
|
|
107
|
+
- **Already routed**: the job runs where a relay sends it.
|
|
108
|
+
- **Skipped, with the reason**: a matrix, a `runs-on` expression, list or
|
|
109
|
+
group, a reusable workflow, a deploy job (`environment`, `id-token: write`,
|
|
110
|
+
or secrets other than `GITHUB_TOKEN`), Windows, or an unknown label.
|
|
111
|
+
|
|
112
|
+
A public repo is refused: machines never take public repos' jobs. Visibility is
|
|
113
|
+
checked with an anonymous GitHub API call, so it doesn't matter which account
|
|
114
|
+
`gh` or git is signed in as.
|
|
115
|
+
|
|
116
|
+
- `--plan` lists the jobs and changes nothing; `--plan --json` prints them as JSON.
|
|
117
|
+
- `--apply <jobs>` routes jobs without prompting. Name them by id (`test`),
|
|
118
|
+
`file:id` (`ci.yml:test`) when an id is in several workflows, or `all` for
|
|
119
|
+
every ready job. Add `--json` for a JSON result.
|
|
120
|
+
|
|
48
121
|
## `relayrunner pause` and `relayrunner resume`
|
|
49
122
|
|
|
50
123
|
```sh
|
|
@@ -58,6 +131,20 @@ again. Anyone in the workspace can do the same from the machine's ⋯ menu on th
|
|
|
58
131
|
Runners page, and a running `relayrunner connect` prints when that happens.
|
|
59
132
|
Both exit 1 when not signed in or when the token is no longer valid.
|
|
60
133
|
|
|
134
|
+
## `relayrunner share`
|
|
135
|
+
|
|
136
|
+
```sh
|
|
137
|
+
npx relayrunner share # show the current setting
|
|
138
|
+
npx relayrunner share only-me # run only jobs you started
|
|
139
|
+
npx relayrunner share anyone # run any job in the workspace
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Who can run jobs on this machine. `only-me` takes only jobs you started on
|
|
143
|
+
GitHub; `anyone` takes any job in the workspace, including teammates' and bots'.
|
|
144
|
+
It's the same setting as the sharing icon on the machine's card on the Runners
|
|
145
|
+
page, and only the machine's owner can change it there. `relayrunner whoami`
|
|
146
|
+
shows it too. Exits 1 when not signed in or when the token is no longer valid.
|
|
147
|
+
|
|
61
148
|
## Building
|
|
62
149
|
|
|
63
150
|
`pnpm --filter relayrunner build` bundles the CLI into `dist/cli.js` with
|
package/dist/cli.js
CHANGED
|
@@ -1,16 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { arch, homedir, hostname, platform } from "node:os";
|
|
2
|
+
import { arch, cpus, homedir, hostname, platform, totalmem } from "node:os";
|
|
3
3
|
import * as clack from "@clack/prompts";
|
|
4
4
|
import { defineCommand, runMain } from "citty";
|
|
5
5
|
import { z } from "zod";
|
|
6
|
-
import { join, resolve } from "node:path";
|
|
6
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
7
7
|
import { chmodSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
8
|
-
import { spawn } from "node:child_process";
|
|
8
|
+
import { execFile, spawn } from "node:child_process";
|
|
9
|
+
import { styleText } from "node:util";
|
|
10
|
+
import { Scalar, YAMLSeq, isMap, isScalar, isSeq, parseDocument } from "yaml";
|
|
9
11
|
import { createHash } from "node:crypto";
|
|
10
12
|
import { Readable, Transform } from "node:stream";
|
|
11
13
|
import { pipeline } from "node:stream/promises";
|
|
12
14
|
const version = z.literal(1);
|
|
13
15
|
const routeId = z.string().min(1);
|
|
16
|
+
const DeviceKind = z.enum([
|
|
17
|
+
"laptop",
|
|
18
|
+
"desktop",
|
|
19
|
+
"server",
|
|
20
|
+
"vm",
|
|
21
|
+
"unknown"
|
|
22
|
+
]);
|
|
23
|
+
const text = z.string().trim().min(1).max(120);
|
|
24
|
+
const Device = z.object({
|
|
25
|
+
kind: DeviceKind,
|
|
26
|
+
model: text.optional(),
|
|
27
|
+
modelId: text.optional(),
|
|
28
|
+
chip: text.optional(),
|
|
29
|
+
cpuCores: z.number().int().positive().max(1e5).optional(),
|
|
30
|
+
memoryMb: z.number().int().positive().max(1e9).optional(),
|
|
31
|
+
osVersion: text.optional()
|
|
32
|
+
});
|
|
14
33
|
const HelloMessage = z.object({
|
|
15
34
|
v: version,
|
|
16
35
|
type: z.literal("hello"),
|
|
@@ -25,7 +44,8 @@ const HelloMessage = z.object({
|
|
|
25
44
|
"arm64",
|
|
26
45
|
"arm"
|
|
27
46
|
]),
|
|
28
|
-
runnerVersion: z.string().min(1)
|
|
47
|
+
runnerVersion: z.string().min(1),
|
|
48
|
+
device: Device.optional().catch(void 0)
|
|
29
49
|
});
|
|
30
50
|
const StatusMessage = z.object({
|
|
31
51
|
v: version,
|
|
@@ -347,6 +367,737 @@ function writeCredentials(credentials, path = credentialsPath()) {
|
|
|
347
367
|
function deleteCredentials(path = credentialsPath()) {
|
|
348
368
|
rmSync(path, { force: true });
|
|
349
369
|
}
|
|
370
|
+
// device.ts
|
|
371
|
+
const run = (command, args) => new Promise((resolve) => {
|
|
372
|
+
execFile(command, args, {
|
|
373
|
+
timeout: 3e3,
|
|
374
|
+
encoding: "utf8"
|
|
375
|
+
}, (error, stdout) => {
|
|
376
|
+
resolve(error ? null : stdout.trim() || null);
|
|
377
|
+
});
|
|
378
|
+
});
|
|
379
|
+
const read$1 = (path) => {
|
|
380
|
+
try {
|
|
381
|
+
return readFileSync(path, "utf8").replaceAll("\0", "").trim() || null;
|
|
382
|
+
} catch {
|
|
383
|
+
return null;
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
function defaultSources() {
|
|
387
|
+
const list = cpus();
|
|
388
|
+
return {
|
|
389
|
+
run,
|
|
390
|
+
read: read$1,
|
|
391
|
+
cpuModel: list[0]?.model,
|
|
392
|
+
cpuCount: list.length,
|
|
393
|
+
totalMemory: totalmem()
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
/** This machine's device, or undefined on a platform it can't read. Never throws. */
|
|
397
|
+
async function detectDevice(sources = defaultSources()) {
|
|
398
|
+
try {
|
|
399
|
+
const system = platform();
|
|
400
|
+
const found = system === "darwin" ? await macDevice(sources) : system === "linux" ? await linuxDevice(sources) : void 0;
|
|
401
|
+
return found && compact(found);
|
|
402
|
+
} catch {
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
/** The specs every platform reads the same way. */
|
|
407
|
+
function commonSpecs(sources) {
|
|
408
|
+
return {
|
|
409
|
+
chip: cleanChip(sources.cpuModel),
|
|
410
|
+
cpuCores: sources.cpuCount > 0 ? sources.cpuCount : void 0,
|
|
411
|
+
memoryMb: sources.totalMemory > 0 ? Math.round(sources.totalMemory / 1024 / 1024) : void 0
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
async function macDevice(sources) {
|
|
415
|
+
const [modelId, profile, virtual, version] = await Promise.all([
|
|
416
|
+
sources.run("sysctl", ["-n", "hw.model"]),
|
|
417
|
+
sources.run("system_profiler", ["SPHardwareDataType", "-json"]),
|
|
418
|
+
sources.run("sysctl", ["-n", "kern.hv_vmm_present"]),
|
|
419
|
+
sources.run("sw_vers", ["-productVersion"])
|
|
420
|
+
]);
|
|
421
|
+
const model = profileModel(profile) ?? macModelFromId(modelId);
|
|
422
|
+
const isVm = virtual === "1" || Boolean(modelId?.startsWith("VirtualMac"));
|
|
423
|
+
return {
|
|
424
|
+
kind: isVm ? "vm" : macKind(model),
|
|
425
|
+
model: isVm ? void 0 : model,
|
|
426
|
+
modelId: modelId ?? void 0,
|
|
427
|
+
...commonSpecs(sources),
|
|
428
|
+
osVersion: version ? `macOS ${version}` : void 0
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
function profileModel(json) {
|
|
432
|
+
if (!json) return void 0;
|
|
433
|
+
try {
|
|
434
|
+
const name = JSON.parse(json).SPHardwareDataType?.[0]?.machine_name;
|
|
435
|
+
return typeof name === "string" && name.trim() ? name.trim() : void 0;
|
|
436
|
+
} catch {
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const MAC_FAMILIES = [
|
|
441
|
+
["MacBookPro", "MacBook Pro"],
|
|
442
|
+
["MacBookAir", "MacBook Air"],
|
|
443
|
+
["MacBook", "MacBook"],
|
|
444
|
+
["Macmini", "Mac mini"],
|
|
445
|
+
["MacPro", "Mac Pro"],
|
|
446
|
+
["iMacPro", "iMac Pro"],
|
|
447
|
+
["iMac", "iMac"]
|
|
448
|
+
];
|
|
449
|
+
function macModelFromId(modelId) {
|
|
450
|
+
if (!modelId) return void 0;
|
|
451
|
+
return MAC_FAMILIES.find(([prefix]) => modelId.startsWith(prefix))?.[1];
|
|
452
|
+
}
|
|
453
|
+
function macKind(model) {
|
|
454
|
+
if (!model) return "unknown";
|
|
455
|
+
if (model.startsWith("MacBook")) return "laptop";
|
|
456
|
+
if (/^(iMac|Mac mini|Mac Studio|Mac Pro)/.test(model)) return "desktop";
|
|
457
|
+
return "unknown";
|
|
458
|
+
}
|
|
459
|
+
async function linuxDevice(sources) {
|
|
460
|
+
const dmi = (name) => sources.read(`/sys/class/dmi/id/${name}`);
|
|
461
|
+
const vendor = dmi("sys_vendor");
|
|
462
|
+
const product = dmi("product_name");
|
|
463
|
+
const lenovoName = vendor?.toUpperCase() === "LENOVO" ? dmi("product_version") : null;
|
|
464
|
+
const boardModel = sources.read("/proc/device-tree/model");
|
|
465
|
+
const rawModel = realName(lenovoName) ?? realName(product) ?? realName(boardModel);
|
|
466
|
+
return {
|
|
467
|
+
kind: await isLinuxVm(sources, vendor, product) ? "vm" : chassisKind(dmi("chassis_type")),
|
|
468
|
+
model: rawModel,
|
|
469
|
+
modelId: product ?? boardModel ?? void 0,
|
|
470
|
+
...commonSpecs(sources),
|
|
471
|
+
osVersion: osRelease(sources.read("/etc/os-release"))
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
const VM_VENDORS = /qemu|kvm|vmware|virtualbox|innotek|xen|bochs|parallels|amazon ec2|google/i;
|
|
475
|
+
async function isLinuxVm(sources, vendor, product) {
|
|
476
|
+
const virt = await sources.run("systemd-detect-virt", ["--vm"]);
|
|
477
|
+
if (virt && virt !== "none") return true;
|
|
478
|
+
if (vendor && VM_VENDORS.test(vendor)) return true;
|
|
479
|
+
if (product && /virtual machine|vmware|virtualbox|kvm|hvm domu/i.test(product)) return true;
|
|
480
|
+
return /^flags\s*:.*\bhypervisor\b/m.test(sources.read("/proc/cpuinfo") ?? "");
|
|
481
|
+
}
|
|
482
|
+
const CHASSIS = {
|
|
483
|
+
3: "desktop",
|
|
484
|
+
4: "desktop",
|
|
485
|
+
5: "desktop",
|
|
486
|
+
6: "desktop",
|
|
487
|
+
7: "desktop",
|
|
488
|
+
8: "laptop",
|
|
489
|
+
9: "laptop",
|
|
490
|
+
10: "laptop",
|
|
491
|
+
13: "desktop",
|
|
492
|
+
14: "laptop",
|
|
493
|
+
15: "desktop",
|
|
494
|
+
16: "desktop",
|
|
495
|
+
17: "server",
|
|
496
|
+
23: "server",
|
|
497
|
+
24: "desktop",
|
|
498
|
+
25: "server",
|
|
499
|
+
28: "server",
|
|
500
|
+
29: "server",
|
|
501
|
+
31: "laptop",
|
|
502
|
+
32: "laptop",
|
|
503
|
+
35: "desktop",
|
|
504
|
+
36: "desktop"
|
|
505
|
+
};
|
|
506
|
+
function chassisKind(chassisType) {
|
|
507
|
+
return CHASSIS[Number(chassisType)] ?? "unknown";
|
|
508
|
+
}
|
|
509
|
+
const PLACEHOLDERS = [
|
|
510
|
+
/^to be filled by o\.?e\.?m\.?$/i,
|
|
511
|
+
/^system product name$/i,
|
|
512
|
+
/^system version$/i,
|
|
513
|
+
/^default string$/i,
|
|
514
|
+
/^not (specified|applicable)$/i,
|
|
515
|
+
/^o\.?e\.?m\.?$/i,
|
|
516
|
+
/^none$/i,
|
|
517
|
+
/^unknown$/i,
|
|
518
|
+
/^standard pc\b/i,
|
|
519
|
+
/^\d+$/
|
|
520
|
+
];
|
|
521
|
+
/** A model name worth showing, or undefined for a placeholder. */
|
|
522
|
+
function realName(name) {
|
|
523
|
+
const trimmed = name?.trim();
|
|
524
|
+
if (!trimmed || PLACEHOLDERS.some((pattern) => pattern.test(trimmed))) return void 0;
|
|
525
|
+
return trimmed;
|
|
526
|
+
}
|
|
527
|
+
/** "Intel(R) Xeon(R) Gold 6338 CPU @ 2.00GHz" → "Intel Xeon Gold 6338". */
|
|
528
|
+
function cleanChip(model) {
|
|
529
|
+
const cleaned = model?.replace(/\((R|TM|C)\)/gi, "").replace(/\s+CPU\s*@.*$/i, "").replace(/\s+@\s*[\d.]+\s*GHz$/i, "").replace(/\s+\d+-Core Processor$/i, "").replace(/\s+/g, " ").trim();
|
|
530
|
+
return cleaned && cleaned.toLowerCase() !== "unknown" ? cleaned : void 0;
|
|
531
|
+
}
|
|
532
|
+
/** PRETTY_NAME from /etc/os-release, such as "Ubuntu 24.04.1 LTS". */
|
|
533
|
+
function osRelease(text) {
|
|
534
|
+
return (text?.split("\n").find((l) => l.startsWith("PRETTY_NAME=")))?.slice(12).trim().replace(/^["']|["']$/g, "") || void 0;
|
|
535
|
+
}
|
|
536
|
+
function compact(device) {
|
|
537
|
+
const out = {};
|
|
538
|
+
for (const [key, value] of Object.entries(device)) {
|
|
539
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
540
|
+
out[key] = typeof value === "string" ? value.slice(0, 120) : value;
|
|
541
|
+
}
|
|
542
|
+
return out;
|
|
543
|
+
}
|
|
544
|
+
// declined.ts
|
|
545
|
+
function declinedPath(home = relayrunnerHome()) {
|
|
546
|
+
return join(home, "declined-repos.json");
|
|
547
|
+
}
|
|
548
|
+
function read(path) {
|
|
549
|
+
try {
|
|
550
|
+
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
551
|
+
return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
|
|
552
|
+
} catch {
|
|
553
|
+
return [];
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
function isDeclined(repo, path = declinedPath()) {
|
|
557
|
+
return read(path).includes(repo);
|
|
558
|
+
}
|
|
559
|
+
function rememberDeclined(repo, path = declinedPath()) {
|
|
560
|
+
const repos = read(path);
|
|
561
|
+
if (repos.includes(repo)) return;
|
|
562
|
+
mkdirSync(dirname(path), {
|
|
563
|
+
recursive: true,
|
|
564
|
+
mode: 448
|
|
565
|
+
});
|
|
566
|
+
writeFileSync(path, `${JSON.stringify([...repos, repo], null, 2)}\n`);
|
|
567
|
+
}
|
|
568
|
+
// diff.ts
|
|
569
|
+
function unifiedDiff(before, after, file, context = 2) {
|
|
570
|
+
const a = before.split("\n");
|
|
571
|
+
const b = after.split("\n");
|
|
572
|
+
const lcs = Array.from({ length: a.length + 1 }, () => Array.from({ length: b.length + 1 }).fill(0));
|
|
573
|
+
for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
|
|
574
|
+
const lines = [];
|
|
575
|
+
let i = 0;
|
|
576
|
+
let j = 0;
|
|
577
|
+
while (i < a.length || j < b.length) if (i < a.length && j < b.length && a[i] === b[j]) lines.push({
|
|
578
|
+
kind: " ",
|
|
579
|
+
text: a[i],
|
|
580
|
+
a: i++,
|
|
581
|
+
b: j++
|
|
582
|
+
});
|
|
583
|
+
else if (i < a.length && (j >= b.length || lcs[i + 1][j] >= lcs[i][j + 1])) lines.push({
|
|
584
|
+
kind: "-",
|
|
585
|
+
text: a[i],
|
|
586
|
+
a: i++,
|
|
587
|
+
b: j
|
|
588
|
+
});
|
|
589
|
+
else lines.push({
|
|
590
|
+
kind: "+",
|
|
591
|
+
text: b[j],
|
|
592
|
+
a: i,
|
|
593
|
+
b: j++
|
|
594
|
+
});
|
|
595
|
+
const changed = lines.flatMap((line, index) => line.kind === " " ? [] : [index]);
|
|
596
|
+
if (!changed.length) return "";
|
|
597
|
+
const out = [`--- a/${file}`, `+++ b/${file}`];
|
|
598
|
+
let start = 0;
|
|
599
|
+
while (start < changed.length) {
|
|
600
|
+
let end = start;
|
|
601
|
+
while (end + 1 < changed.length && changed[end + 1] - changed[end] <= context * 2 + 1) end++;
|
|
602
|
+
const from = Math.max(0, changed[start] - context);
|
|
603
|
+
const to = Math.min(lines.length - 1, changed[end] + context);
|
|
604
|
+
const hunk = lines.slice(from, to + 1);
|
|
605
|
+
const aCount = hunk.filter((line) => line.kind !== "+").length;
|
|
606
|
+
const bCount = hunk.filter((line) => line.kind !== "-").length;
|
|
607
|
+
out.push(`@@ -${hunk[0].a + 1},${aCount} +${hunk[0].b + 1},${bCount} @@`);
|
|
608
|
+
for (const line of hunk) out.push(`${line.kind}${line.text}`);
|
|
609
|
+
start = end + 1;
|
|
610
|
+
}
|
|
611
|
+
return out.join("\n");
|
|
612
|
+
}
|
|
613
|
+
// repo.ts
|
|
614
|
+
const WORKFLOWS_DIR = ".github/workflows";
|
|
615
|
+
/** The nearest directory at or above `from` that holds a `.git`, or null outside a checkout. */
|
|
616
|
+
function findRepoRoot(from = process.cwd()) {
|
|
617
|
+
let dir = resolve(from);
|
|
618
|
+
for (;;) {
|
|
619
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
620
|
+
const parent = dirname(dir);
|
|
621
|
+
if (parent === dir) return null;
|
|
622
|
+
dir = parent;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
function readWorkflowFiles(root) {
|
|
626
|
+
const dir = join(root, WORKFLOWS_DIR);
|
|
627
|
+
if (!existsSync(dir)) return [];
|
|
628
|
+
return readdirSync(dir).filter((name) => /\.ya?ml$/.test(name)).sort().map((name) => ({
|
|
629
|
+
file: `${WORKFLOWS_DIR}/${name}`,
|
|
630
|
+
source: readFileSync(join(dir, name), "utf8")
|
|
631
|
+
}));
|
|
632
|
+
}
|
|
633
|
+
/** `owner/name` from a GitHub remote URL (https or ssh), or null for anything else. */
|
|
634
|
+
function parseGitHubRemote(url) {
|
|
635
|
+
const match = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url.trim());
|
|
636
|
+
return match ? `${match[1]}/${match[2]}` : null;
|
|
637
|
+
}
|
|
638
|
+
function originRepo(root) {
|
|
639
|
+
return new Promise((done) => {
|
|
640
|
+
execFile("git", [
|
|
641
|
+
"-C",
|
|
642
|
+
root,
|
|
643
|
+
"remote",
|
|
644
|
+
"get-url",
|
|
645
|
+
"origin"
|
|
646
|
+
], {
|
|
647
|
+
timeout: 3e3,
|
|
648
|
+
encoding: "utf8"
|
|
649
|
+
}, (error, stdout) => done(error ? null : parseGitHubRemote(stdout)));
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Asks GitHub without signing in. A public repo answers; a private one (or one that doesn't exist)
|
|
654
|
+
* is a 404 to an anonymous caller. Anything else, such as no network or a rate limit, is unknown.
|
|
655
|
+
*/
|
|
656
|
+
async function repoVisibility(repo, fetcher = fetch) {
|
|
657
|
+
try {
|
|
658
|
+
const response = await fetcher(`https://api.github.com/repos/${repo}`, {
|
|
659
|
+
headers: {
|
|
660
|
+
accept: "application/vnd.github+json",
|
|
661
|
+
"user-agent": userAgent
|
|
662
|
+
},
|
|
663
|
+
signal: AbortSignal.timeout(5e3)
|
|
664
|
+
});
|
|
665
|
+
if (response.status === 404) return "private";
|
|
666
|
+
if (!response.ok) return "unknown";
|
|
667
|
+
return (await response.json()).private === false ? "public" : "private";
|
|
668
|
+
} catch {
|
|
669
|
+
return "unknown";
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
// workflows.ts
|
|
673
|
+
/** The relay version `init` writes. Bump it with each relayrunner/actions release. */
|
|
674
|
+
const RELAY_REF = "v1.0.0-beta.4";
|
|
675
|
+
const RELAY_WORKFLOW = "relayrunner/actions/.github/workflows/relay.yml";
|
|
676
|
+
const DEPLOY_SECRET = /\bsecrets\.(?!GITHUB_TOKEN\b)[A-Za-z_][A-Za-z0-9_]*/;
|
|
677
|
+
const LINUX_PACKAGE_MANAGER = /(^|[\s;&|(])(sudo\s+)?(apt-get|apt|yum|dnf|apk)\s+(install|update|add)\b/m;
|
|
678
|
+
function analyzeWorkflows(files, options = {}) {
|
|
679
|
+
const jobs = [];
|
|
680
|
+
const errors = [];
|
|
681
|
+
for (const { file, source } of files) {
|
|
682
|
+
const doc = parseDocument(source);
|
|
683
|
+
if (doc.errors.length) {
|
|
684
|
+
errors.push({
|
|
685
|
+
file,
|
|
686
|
+
message: doc.errors[0].message.split("\n")[0]
|
|
687
|
+
});
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
const workflow = doc.toJS();
|
|
691
|
+
if (!workflow || typeof workflow !== "object") continue;
|
|
692
|
+
const all = workflow.jobs;
|
|
693
|
+
if (!all || typeof all !== "object") continue;
|
|
694
|
+
const relays = new Set(Object.entries(all).filter(([, job]) => isRelayJob(job)).map(([id]) => id));
|
|
695
|
+
const reusableOnly = onlyWorkflowCall(workflow.on);
|
|
696
|
+
for (const [id, raw] of Object.entries(all)) {
|
|
697
|
+
if (!raw || typeof raw !== "object") continue;
|
|
698
|
+
const job = raw;
|
|
699
|
+
if (relays.has(id)) continue;
|
|
700
|
+
jobs.push(judge(file, id, job, workflow, relays, reusableOnly, options));
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return {
|
|
704
|
+
jobs,
|
|
705
|
+
errors
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
/** True when any job already runs where a relay sends it. */
|
|
709
|
+
function isSetUp(jobs) {
|
|
710
|
+
return jobs.some((job) => job.verdict === "routed");
|
|
711
|
+
}
|
|
712
|
+
function judge(file, id, job, workflow, relays, reusableOnly, options) {
|
|
713
|
+
const base = {
|
|
714
|
+
file,
|
|
715
|
+
job: id,
|
|
716
|
+
warnings: []
|
|
717
|
+
};
|
|
718
|
+
const skip = (reason) => ({
|
|
719
|
+
...base,
|
|
720
|
+
verdict: "skipped",
|
|
721
|
+
reason
|
|
722
|
+
});
|
|
723
|
+
if (typeof job.uses === "string") return skip("calls a reusable workflow");
|
|
724
|
+
if (reusableOnly) return skip("part of a reusable workflow; it runs wherever the calling workflow sends it");
|
|
725
|
+
const runsOn = job["runs-on"];
|
|
726
|
+
if (runsOn === void 0) return skip("has no runs-on");
|
|
727
|
+
if (typeof runsOn !== "string") return skip("runs-on is a list of labels or a runner group");
|
|
728
|
+
if (runsOn.includes("${{")) {
|
|
729
|
+
const relay = /^\$\{\{\s*needs\.([\w-]+)\.outputs\.runner\s*\}\}$/.exec(runsOn.trim())?.[1];
|
|
730
|
+
if (relay && relays.has(relay)) return {
|
|
731
|
+
...base,
|
|
732
|
+
verdict: "routed"
|
|
733
|
+
};
|
|
734
|
+
return skip("runs-on is an expression");
|
|
735
|
+
}
|
|
736
|
+
if (hasMatrix(job)) return skip("uses a matrix, and one relay can't serve every leg");
|
|
737
|
+
const deploy = deploySignal(job, workflow);
|
|
738
|
+
if (deploy) return skip(`looks like a deploy job (${deploy})`);
|
|
739
|
+
const label = runsOn.trim();
|
|
740
|
+
const lower = label.toLowerCase();
|
|
741
|
+
let provider;
|
|
742
|
+
let machine = "self-hosted";
|
|
743
|
+
if (lower.startsWith("blacksmith-")) provider = "blacksmith";
|
|
744
|
+
else if (/^(ubuntu|macos)-/.test(lower)) {
|
|
745
|
+
provider = "github";
|
|
746
|
+
if (lower.startsWith("macos-")) machine = "macOS";
|
|
747
|
+
} else if (lower.startsWith("windows-")) return skip("Windows jobs can't run on machines yet");
|
|
748
|
+
else if (lower === "relayrunner") return skip("already runs on RelayRunner");
|
|
749
|
+
else if (lower === "self-hosted") return skip("already runs on a self-hosted runner");
|
|
750
|
+
else return skip(`${label} isn't a GitHub-hosted or Blacksmith label`);
|
|
751
|
+
const warnings = jobWarnings(job, options);
|
|
752
|
+
return {
|
|
753
|
+
...base,
|
|
754
|
+
verdict: "ready",
|
|
755
|
+
provider,
|
|
756
|
+
label,
|
|
757
|
+
machine,
|
|
758
|
+
warnings
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
function isRelayJob(job) {
|
|
762
|
+
return typeof job?.uses === "string" && job.uses.split("@")[0] === "relayrunner/actions/.github/workflows/relay.yml";
|
|
763
|
+
}
|
|
764
|
+
function onlyWorkflowCall(on) {
|
|
765
|
+
if (on === "workflow_call") return true;
|
|
766
|
+
if (Array.isArray(on)) return on.length > 0 && on.every((event) => event === "workflow_call");
|
|
767
|
+
if (on && typeof on === "object") {
|
|
768
|
+
const events = Object.keys(on);
|
|
769
|
+
return events.length > 0 && events.every((event) => event === "workflow_call");
|
|
770
|
+
}
|
|
771
|
+
return false;
|
|
772
|
+
}
|
|
773
|
+
function hasMatrix(job) {
|
|
774
|
+
const strategy = job.strategy;
|
|
775
|
+
return !!strategy && typeof strategy === "object" && strategy.matrix !== void 0;
|
|
776
|
+
}
|
|
777
|
+
function deploySignal(job, workflow) {
|
|
778
|
+
if (job.environment !== void 0) return "environment";
|
|
779
|
+
const permissions = job.permissions ?? workflow.permissions;
|
|
780
|
+
if (permissions === "write-all") return "write-all permissions";
|
|
781
|
+
if (permissions && typeof permissions === "object" && permissions["id-token"] === "write") return "id-token: write";
|
|
782
|
+
const secret = DEPLOY_SECRET.exec(JSON.stringify(job))?.[0];
|
|
783
|
+
if (secret) return `uses ${secret}`;
|
|
784
|
+
return null;
|
|
785
|
+
}
|
|
786
|
+
function jobWarnings(job, options) {
|
|
787
|
+
const warnings = [];
|
|
788
|
+
if (job.services !== void 0) warnings.push("uses services, which need Docker on the machine");
|
|
789
|
+
if (job.container !== void 0) warnings.push("runs in a container, which needs Docker on the machine");
|
|
790
|
+
const steps = Array.isArray(job.steps) ? job.steps : [];
|
|
791
|
+
const providerActions = /* @__PURE__ */ new Set();
|
|
792
|
+
let packages = false;
|
|
793
|
+
for (const step of steps) {
|
|
794
|
+
if (!step || typeof step !== "object") continue;
|
|
795
|
+
if (typeof step.run === "string" && LINUX_PACKAGE_MANAGER.test(step.run)) packages = true;
|
|
796
|
+
if (typeof step.uses === "string") {
|
|
797
|
+
const action = step.uses.split("@")[0];
|
|
798
|
+
if (action.startsWith("useblacksmith/")) providerActions.add(action);
|
|
799
|
+
if (action.startsWith("docker://")) warnings.push("runs a Docker action, which needs Docker on the machine");
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
if (packages && options.hostOs !== "linux") warnings.push(options.hostOs === "macos" ? "installs Linux packages (apt-get, yum or apk), which macOS doesn't have" : "installs Linux packages (apt-get, yum or apk)");
|
|
803
|
+
for (const action of providerActions) warnings.push(`uses ${action}, which is made for Blacksmith runners`);
|
|
804
|
+
return warnings;
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Routes the given jobs of one workflow file through the relay. Returns the new file contents.
|
|
808
|
+
* Each job must have come back `ready` from analyzeWorkflows for this same source.
|
|
809
|
+
*/
|
|
810
|
+
function routeJobs(source, jobs) {
|
|
811
|
+
const doc = parseDocument(source);
|
|
812
|
+
const all = doc.get("jobs");
|
|
813
|
+
if (!isMap(all)) throw new Error("This workflow has no jobs map.");
|
|
814
|
+
for (const job of jobs) {
|
|
815
|
+
if (job.verdict !== "ready" || !job.provider || !job.label) throw new Error(`${job.job} isn't ready to route.`);
|
|
816
|
+
routeJob(doc, all, job);
|
|
817
|
+
}
|
|
818
|
+
return doc.toString({
|
|
819
|
+
lineWidth: 0,
|
|
820
|
+
flowCollectionPadding: false
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
function routeJob(doc, all, job) {
|
|
824
|
+
const index = all.items.findIndex((pair) => isScalar(pair.key) && pair.key.value === job.job);
|
|
825
|
+
const pair = all.items[index];
|
|
826
|
+
if (!pair || !isMap(pair.value)) throw new Error(`No job ${job.job} in this workflow.`);
|
|
827
|
+
const node = pair.value;
|
|
828
|
+
const relayId = freeId(all, `relay-${job.job}`);
|
|
829
|
+
const relay = doc.createNode({
|
|
830
|
+
uses: `${RELAY_WORKFLOW}@${RELAY_REF}`,
|
|
831
|
+
with: {
|
|
832
|
+
machine: job.machine ?? "self-hosted",
|
|
833
|
+
[job.provider]: job.label
|
|
834
|
+
}
|
|
835
|
+
});
|
|
836
|
+
const key = new Scalar(relayId);
|
|
837
|
+
const jobKey = pair.key;
|
|
838
|
+
key.spaceBefore = jobKey.spaceBefore;
|
|
839
|
+
if (key.spaceBefore === void 0 && index > 0) key.spaceBefore = true;
|
|
840
|
+
key.commentBefore = jobKey.commentBefore;
|
|
841
|
+
jobKey.commentBefore = void 0;
|
|
842
|
+
jobKey.spaceBefore = true;
|
|
843
|
+
all.items.splice(index, 0, doc.createPair(key, relay));
|
|
844
|
+
const runsOn = node.get("runs-on", true);
|
|
845
|
+
const target = `\${{ needs.${relayId}.outputs.runner }}`;
|
|
846
|
+
if (isScalar(runsOn)) {
|
|
847
|
+
runsOn.value = target;
|
|
848
|
+
runsOn.type = Scalar.PLAIN;
|
|
849
|
+
} else node.set("runs-on", target);
|
|
850
|
+
const needs = node.get("needs", true);
|
|
851
|
+
if (needs === void 0) {
|
|
852
|
+
const at = node.items.findIndex((item) => isScalar(item.key) && item.key.value === "runs-on");
|
|
853
|
+
node.items.splice(Math.max(at, 0), 0, doc.createPair("needs", relayId));
|
|
854
|
+
} else if (isSeq(needs)) needs.add(doc.createNode(relayId));
|
|
855
|
+
else if (isScalar(needs)) {
|
|
856
|
+
const list = new YAMLSeq();
|
|
857
|
+
list.flow = true;
|
|
858
|
+
list.add(doc.createNode(needs.value));
|
|
859
|
+
list.add(doc.createNode(relayId));
|
|
860
|
+
node.set("needs", list);
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
function freeId(all, wanted) {
|
|
864
|
+
const taken = new Set(all.items.map((pair) => isScalar(pair.key) ? String(pair.key.value) : ""));
|
|
865
|
+
if (!taken.has(wanted)) return wanted;
|
|
866
|
+
for (let n = 2;; n++) if (!taken.has(`${wanted}-${n}`)) return `${wanted}-${n}`;
|
|
867
|
+
}
|
|
868
|
+
// init.ts
|
|
869
|
+
var InitError = class extends Error {};
|
|
870
|
+
async function planInit(cwd = process.cwd(), options = {}) {
|
|
871
|
+
const root = findRepoRoot(cwd);
|
|
872
|
+
if (!root) throw new InitError("Not in a git checkout. Run `relayrunner init` inside a repo.");
|
|
873
|
+
const repo = await originRepo(root);
|
|
874
|
+
const visibility = repo ? await repoVisibility(repo, options.fetcher) : "unknown";
|
|
875
|
+
const files = readWorkflowFiles(root);
|
|
876
|
+
const { jobs, errors } = analyzeWorkflows(files, { hostOs: options.hostOs ?? hostOs() });
|
|
877
|
+
return {
|
|
878
|
+
root,
|
|
879
|
+
repo,
|
|
880
|
+
visibility,
|
|
881
|
+
files,
|
|
882
|
+
jobs,
|
|
883
|
+
errors
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
/** Picks jobs by `job`, `file:job` or `all`. Throws when a name is unknown, ambiguous or not ready. */
|
|
887
|
+
function selectJobs(jobs, names) {
|
|
888
|
+
const ready = jobs.filter((job) => job.verdict === "ready");
|
|
889
|
+
if (names.length === 1 && names[0] === "all") return ready;
|
|
890
|
+
const picked = /* @__PURE__ */ new Map();
|
|
891
|
+
for (const name of names) {
|
|
892
|
+
const [file, id] = name.includes(":") ? name.split(/:(?=[^:]*$)/) : [void 0, name];
|
|
893
|
+
const matches = jobs.filter((job) => job.job === id && (!file || job.file === file || shortFile(job.file) === file));
|
|
894
|
+
if (!matches.length) throw new InitError(`No job named ${name}.`);
|
|
895
|
+
if (matches.length > 1) throw new InitError(`${name} is in more than one workflow. Name it as ${matches.map((job) => `${job.file}:${job.job}`).join(" or ")}.`);
|
|
896
|
+
const job = matches[0];
|
|
897
|
+
if (job.verdict === "routed") throw new InitError(`${name} is already routed.`);
|
|
898
|
+
if (job.verdict === "skipped") throw new InitError(`${name} can't be routed: ${job.reason}.`);
|
|
899
|
+
picked.set(`${job.file}:${job.job}`, job);
|
|
900
|
+
}
|
|
901
|
+
return [...picked.values()];
|
|
902
|
+
}
|
|
903
|
+
/** The new contents of each workflow file the chosen jobs live in. */
|
|
904
|
+
function changesFor(plan, chosen) {
|
|
905
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
906
|
+
for (const job of chosen) byFile.set(job.file, [...byFile.get(job.file) ?? [], job]);
|
|
907
|
+
return [...byFile].map(([file, jobs]) => {
|
|
908
|
+
const before = plan.files.find((entry) => entry.file === file).source;
|
|
909
|
+
return {
|
|
910
|
+
file,
|
|
911
|
+
jobs,
|
|
912
|
+
before,
|
|
913
|
+
after: routeJobs(before, jobs)
|
|
914
|
+
};
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
function writeChanges(root, changes) {
|
|
918
|
+
for (const change of changes) writeFileSync(join(root, change.file), change.after);
|
|
919
|
+
}
|
|
920
|
+
function hostOs() {
|
|
921
|
+
if (process.platform === "darwin") return "macos";
|
|
922
|
+
if (process.platform === "linux") return "linux";
|
|
923
|
+
}
|
|
924
|
+
const PUBLIC_REPO = "This repo is public, and machines never take jobs from public repos. There's nothing for init to set up here.";
|
|
925
|
+
const initCommand = defineCommand({
|
|
926
|
+
meta: {
|
|
927
|
+
name: "init",
|
|
928
|
+
description: "Route this repo's GitHub Actions jobs through RelayRunner, so they run on your machine when it's online. Edits workflow files; never commits."
|
|
929
|
+
},
|
|
930
|
+
args: {
|
|
931
|
+
plan: {
|
|
932
|
+
type: "boolean",
|
|
933
|
+
description: "List every job and whether it can be routed. Changes nothing."
|
|
934
|
+
},
|
|
935
|
+
apply: {
|
|
936
|
+
type: "string",
|
|
937
|
+
description: "Route these jobs without prompting: comma-separated ids or file:job, or `all` for every ready job"
|
|
938
|
+
},
|
|
939
|
+
json: {
|
|
940
|
+
type: "boolean",
|
|
941
|
+
description: "Print the result as JSON (with --plan or --apply)"
|
|
942
|
+
}
|
|
943
|
+
},
|
|
944
|
+
async run({ args }) {
|
|
945
|
+
try {
|
|
946
|
+
const plan = await planInit();
|
|
947
|
+
if (args.apply !== void 0) return apply(plan, args.apply, !!args.json);
|
|
948
|
+
if (args.plan || args.json) return printPlan(plan, !!args.json);
|
|
949
|
+
if (!process.stdin.isTTY) {
|
|
950
|
+
printPlan(plan, false);
|
|
951
|
+
console.log("\nRun `relayrunner init --apply <jobs>` to route jobs without prompts.");
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
await interactive(plan);
|
|
955
|
+
} catch (error) {
|
|
956
|
+
if (!(error instanceof InitError)) throw error;
|
|
957
|
+
if (args.json) console.log(JSON.stringify({ error: error.message }, null, 2));
|
|
958
|
+
else console.error(error.message);
|
|
959
|
+
process.exitCode = 1;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
});
|
|
963
|
+
function planJson(plan) {
|
|
964
|
+
return {
|
|
965
|
+
repo: plan.repo,
|
|
966
|
+
visibility: plan.visibility,
|
|
967
|
+
relay: RELAY_REF,
|
|
968
|
+
setUp: isSetUp(plan.jobs),
|
|
969
|
+
...plan.visibility === "public" ? { refused: "public_repo" } : {},
|
|
970
|
+
jobs: plan.jobs,
|
|
971
|
+
errors: plan.errors
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
function printPlan(plan, json) {
|
|
975
|
+
if (json) return console.log(JSON.stringify(planJson(plan), null, 2));
|
|
976
|
+
console.log(describeRepo(plan));
|
|
977
|
+
if (plan.visibility === "public") return console.log(PUBLIC_REPO);
|
|
978
|
+
if (!plan.files.length) return console.log("No workflows in .github/workflows.");
|
|
979
|
+
for (const [title, verdict] of [
|
|
980
|
+
["Ready to route", "ready"],
|
|
981
|
+
["Already routed", "routed"],
|
|
982
|
+
["Skipped", "skipped"]
|
|
983
|
+
]) {
|
|
984
|
+
const jobs = plan.jobs.filter((job) => job.verdict === verdict);
|
|
985
|
+
if (!jobs.length) continue;
|
|
986
|
+
console.log(`\n${title}`);
|
|
987
|
+
for (const job of jobs) console.log(` ${jobLine(job)}`);
|
|
988
|
+
}
|
|
989
|
+
for (const error of plan.errors) console.log(`\nCouldn't read ${error.file}: ${error.message}`);
|
|
990
|
+
}
|
|
991
|
+
function apply(plan, list, json) {
|
|
992
|
+
if (plan.visibility === "public") throw new InitError(PUBLIC_REPO);
|
|
993
|
+
const names = list.split(",").map((name) => name.trim()).filter(Boolean);
|
|
994
|
+
if (!names.length) throw new InitError("Name the jobs to route, or `all`.");
|
|
995
|
+
const chosen = selectJobs(plan.jobs, names);
|
|
996
|
+
if (!chosen.length) throw new InitError("No jobs are ready to route.");
|
|
997
|
+
const changes = changesFor(plan, chosen);
|
|
998
|
+
writeChanges(plan.root, changes);
|
|
999
|
+
const routed = chosen.map(({ file, job, warnings }) => ({
|
|
1000
|
+
file,
|
|
1001
|
+
job,
|
|
1002
|
+
warnings
|
|
1003
|
+
}));
|
|
1004
|
+
if (json) return console.log(JSON.stringify({
|
|
1005
|
+
relay: RELAY_REF,
|
|
1006
|
+
routed
|
|
1007
|
+
}, null, 2));
|
|
1008
|
+
for (const change of changes) console.log(`Updated ${change.file} (${change.jobs.map((job) => job.job).join(", ")})`);
|
|
1009
|
+
console.log("Commit and push to start routing.");
|
|
1010
|
+
}
|
|
1011
|
+
async function interactive(plan) {
|
|
1012
|
+
clack.intro("RelayRunner init");
|
|
1013
|
+
clack.log.info(describeRepo(plan));
|
|
1014
|
+
if (plan.visibility === "public") return clack.outro(PUBLIC_REPO);
|
|
1015
|
+
if (plan.visibility === "unknown") clack.log.warn("Couldn't check whether this repo is public. Machines only take jobs from private repos.");
|
|
1016
|
+
for (const error of plan.errors) clack.log.warn(`Couldn't read ${error.file}: ${error.message}`);
|
|
1017
|
+
if (!plan.files.length) return clack.outro("No workflows in .github/workflows.");
|
|
1018
|
+
await chooseAndWrite(plan, (message) => clack.outro(message));
|
|
1019
|
+
}
|
|
1020
|
+
/** Lists the jobs, lets the user pick, shows the diff and writes it. `finish` gets the last line. */
|
|
1021
|
+
async function chooseAndWrite(plan, finish) {
|
|
1022
|
+
const routed = plan.jobs.filter((job) => job.verdict === "routed");
|
|
1023
|
+
const skipped = plan.jobs.filter((job) => job.verdict === "skipped");
|
|
1024
|
+
const ready = plan.jobs.filter((job) => job.verdict === "ready");
|
|
1025
|
+
if (routed.length) clack.note(routed.map(jobLine).join("\n"), "Already routed");
|
|
1026
|
+
if (skipped.length) clack.note(skipped.map(jobLine).join("\n"), "Skipped");
|
|
1027
|
+
if (!ready.length) return finish("No other jobs to route.");
|
|
1028
|
+
const picked = await clack.multiselect({
|
|
1029
|
+
message: "Route these jobs through RelayRunner?",
|
|
1030
|
+
options: ready.map((job) => ({
|
|
1031
|
+
value: job,
|
|
1032
|
+
label: `${shortFile(job.file)} › ${job.job}`,
|
|
1033
|
+
hint: [`${job.label} when your machine is offline`, ...job.warnings].join("; ")
|
|
1034
|
+
})),
|
|
1035
|
+
initialValues: ready,
|
|
1036
|
+
required: false
|
|
1037
|
+
});
|
|
1038
|
+
if (clack.isCancel(picked) || !picked.length) return finish("Nothing changed.");
|
|
1039
|
+
const changes = changesFor(plan, picked);
|
|
1040
|
+
for (const change of changes) console.log(`${colorDiff(unifiedDiff(change.before, change.after, change.file))}\n`);
|
|
1041
|
+
const ok = await clack.confirm({ message: `Write ${changes.length === 1 ? "this change" : `these ${changes.length} changes`}?` });
|
|
1042
|
+
if (clack.isCancel(ok) || !ok) return finish("Nothing changed.");
|
|
1043
|
+
writeChanges(plan.root, changes);
|
|
1044
|
+
const warned = picked.filter((job) => job.warnings.length);
|
|
1045
|
+
if (warned.length) clack.note(warned.map((job) => `${job.job}: ${job.warnings.join("; ")}`).join("\n"), "Check before it runs on your machine");
|
|
1046
|
+
finish(`Updated ${changes.map((change) => change.file).join(", ")}. Commit and push to start routing.`);
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* Whether `connect` should offer to set up this checkout: it's not public, nothing in it is routed
|
|
1050
|
+
* yet, and at least one job could be.
|
|
1051
|
+
*/
|
|
1052
|
+
function shouldOfferSetup(plan) {
|
|
1053
|
+
return plan.visibility !== "public" && !isSetUp(plan.jobs) && plan.jobs.some((job) => job.verdict === "ready");
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Run by `connect` before it goes online. Inside a repo that could use RelayRunner but doesn't
|
|
1057
|
+
* yet, asks once whether to set it up (default no) and runs the same picker as `init`. A "no" is
|
|
1058
|
+
* remembered for that repo, so later runs don't ask again; `relayrunner init` still works. Never
|
|
1059
|
+
* throws: setup is a convenience, and `connect` goes online either way.
|
|
1060
|
+
*/
|
|
1061
|
+
async function offerSetup(cwd = process.cwd()) {
|
|
1062
|
+
try {
|
|
1063
|
+
const plan = await planInit(cwd).catch((error) => {
|
|
1064
|
+
if (error instanceof InitError) return null;
|
|
1065
|
+
throw error;
|
|
1066
|
+
});
|
|
1067
|
+
if (!plan || !shouldOfferSetup(plan)) return;
|
|
1068
|
+
const key = plan.repo ?? plan.root;
|
|
1069
|
+
if (isDeclined(key)) return;
|
|
1070
|
+
const answer = await clack.confirm({
|
|
1071
|
+
message: `Set up ${plan.repo ?? basename(plan.root)} to run its CI on this machine?`,
|
|
1072
|
+
initialValue: false
|
|
1073
|
+
});
|
|
1074
|
+
if (clack.isCancel(answer)) return;
|
|
1075
|
+
if (!answer) {
|
|
1076
|
+
rememberDeclined(key);
|
|
1077
|
+
clack.log.info("Not now. Run `relayrunner init` in this repo any time to set it up.");
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
await chooseAndWrite(plan, (message) => clack.log.success(message));
|
|
1081
|
+
} catch (error) {
|
|
1082
|
+
clack.log.warn(`Couldn't check this repo's workflows: ${error instanceof Error ? error.message : String(error)}`);
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
function describeRepo(plan) {
|
|
1086
|
+
if (!plan.repo) return `${plan.root} (no GitHub remote named origin)`;
|
|
1087
|
+
return plan.visibility === "unknown" ? plan.repo : `${plan.repo} (${plan.visibility})`;
|
|
1088
|
+
}
|
|
1089
|
+
function jobLine(job) {
|
|
1090
|
+
const name = `${shortFile(job.file)} › ${job.job}`;
|
|
1091
|
+
if (job.verdict === "skipped") return `${name}: ${job.reason}`;
|
|
1092
|
+
if (job.verdict === "routed") return name;
|
|
1093
|
+
return `${name}: ${[`falls back to ${job.label}`, ...job.warnings].join("; ")}`;
|
|
1094
|
+
}
|
|
1095
|
+
function shortFile(file) {
|
|
1096
|
+
return file.replace(/^\.github\/workflows\//, "");
|
|
1097
|
+
}
|
|
1098
|
+
function colorDiff(diff) {
|
|
1099
|
+
return diff.split("\n").map((line) => line.startsWith("+") && !line.startsWith("+++") ? styleText("green", line) : line.startsWith("-") && !line.startsWith("---") ? styleText("red", line) : styleText("dim", line)).join("\n");
|
|
1100
|
+
}
|
|
350
1101
|
// install.ts
|
|
351
1102
|
var RunnerError = class extends Error {
|
|
352
1103
|
code;
|
|
@@ -624,7 +1375,8 @@ const ClaimResponse = z.object({
|
|
|
624
1375
|
workspace: z.object({
|
|
625
1376
|
id: z.string().min(1),
|
|
626
1377
|
name: z.string(),
|
|
627
|
-
slug: z.string().nullish()
|
|
1378
|
+
slug: z.string().nullish(),
|
|
1379
|
+
memberCount: z.number().int().nonnegative().optional()
|
|
628
1380
|
}),
|
|
629
1381
|
token: z.string().min(1)
|
|
630
1382
|
});
|
|
@@ -696,14 +1448,18 @@ async function login(options) {
|
|
|
696
1448
|
}, { authorization: `Bearer ${accessToken}` });
|
|
697
1449
|
if (!claimResponse.ok) throw new LoginError("CLAIM_FAILED", `The gateway approved the sign-in but wouldn't enroll this machine (HTTP ${claimResponse.status}).`);
|
|
698
1450
|
const claimed = ClaimResponse.parse(await claimResponse.json());
|
|
1451
|
+
const { memberCount, ...workspace } = claimed.workspace;
|
|
699
1452
|
return {
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
1453
|
+
credentials: {
|
|
1454
|
+
server: new URL(options.server).origin,
|
|
1455
|
+
machine: {
|
|
1456
|
+
id: claimed.machine.id,
|
|
1457
|
+
name: claimed.machine.name
|
|
1458
|
+
},
|
|
1459
|
+
workspace,
|
|
1460
|
+
token: claimed.token
|
|
704
1461
|
},
|
|
705
|
-
|
|
706
|
-
token: claimed.token
|
|
1462
|
+
memberCount: memberCount ?? null
|
|
707
1463
|
};
|
|
708
1464
|
}
|
|
709
1465
|
function openBrowser(url) {
|
|
@@ -763,6 +1519,60 @@ async function setPaused(options) {
|
|
|
763
1519
|
busy: parsed.data.machine.status?.state === "busy"
|
|
764
1520
|
};
|
|
765
1521
|
}
|
|
1522
|
+
// share.ts
|
|
1523
|
+
const SHARE_CHOICES = ["only-me", "anyone"];
|
|
1524
|
+
const MachineSharing = z.enum(["only_me", "anyone"]);
|
|
1525
|
+
function parseShareChoice(value) {
|
|
1526
|
+
return SHARE_CHOICES.includes(value) ? value : null;
|
|
1527
|
+
}
|
|
1528
|
+
const toSharing = (choice) => choice === "only-me" ? "only_me" : "anyone";
|
|
1529
|
+
const toChoice = (sharing) => sharing === "only_me" ? "only-me" : "anyone";
|
|
1530
|
+
function sharingMeaning(sharing, workspace) {
|
|
1531
|
+
return sharing === "only_me" ? "runs only jobs you started" : `runs any job in ${workspace ?? "the workspace"}, including teammates' and bots'`;
|
|
1532
|
+
}
|
|
1533
|
+
function describeSharing(sharing, workspace) {
|
|
1534
|
+
return `${toChoice(sharing)}: ${sharingMeaning(sharing, workspace)}`;
|
|
1535
|
+
}
|
|
1536
|
+
const SharingResponse = z.object({ machine: z.object({ sharing: MachineSharing }) });
|
|
1537
|
+
async function setSharing(options) {
|
|
1538
|
+
const fetcher = options.fetcher ?? fetch;
|
|
1539
|
+
let response;
|
|
1540
|
+
try {
|
|
1541
|
+
response = await fetcher(new URL("/api/machines/me/sharing", options.server), {
|
|
1542
|
+
method: "PUT",
|
|
1543
|
+
headers: {
|
|
1544
|
+
authorization: `Bearer ${options.token}`,
|
|
1545
|
+
"content-type": "application/json",
|
|
1546
|
+
"user-agent": userAgent
|
|
1547
|
+
},
|
|
1548
|
+
body: JSON.stringify({ sharing: options.sharing })
|
|
1549
|
+
});
|
|
1550
|
+
} catch (error) {
|
|
1551
|
+
const cause = error.cause?.message;
|
|
1552
|
+
return {
|
|
1553
|
+
status: "failed",
|
|
1554
|
+
reason: `couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
1555
|
+
};
|
|
1556
|
+
}
|
|
1557
|
+
if (response.status === 401) return { status: "revoked" };
|
|
1558
|
+
if (response.status === 404 || response.status === 405) return {
|
|
1559
|
+
status: "failed",
|
|
1560
|
+
reason: `${options.server} doesn't support sharing yet`
|
|
1561
|
+
};
|
|
1562
|
+
if (!response.ok) return {
|
|
1563
|
+
status: "failed",
|
|
1564
|
+
reason: `${options.server} answered HTTP ${response.status}`
|
|
1565
|
+
};
|
|
1566
|
+
const parsed = SharingResponse.safeParse(await response.json().catch(() => null));
|
|
1567
|
+
if (!parsed.success) return {
|
|
1568
|
+
status: "failed",
|
|
1569
|
+
reason: `${options.server} sent an unexpected response`
|
|
1570
|
+
};
|
|
1571
|
+
return {
|
|
1572
|
+
status: "ok",
|
|
1573
|
+
sharing: parsed.data.machine.sharing
|
|
1574
|
+
};
|
|
1575
|
+
}
|
|
766
1576
|
// whoami.ts
|
|
767
1577
|
const WhoamiResponse = z.object({
|
|
768
1578
|
machine: z.object({
|
|
@@ -776,12 +1586,14 @@ const WhoamiResponse = z.object({
|
|
|
776
1586
|
online: z.boolean(),
|
|
777
1587
|
state: z.string().nullable()
|
|
778
1588
|
}),
|
|
779
|
-
paused: z.object({ by: z.string().nullable() }).nullish()
|
|
1589
|
+
paused: z.object({ by: z.string().nullable() }).nullish(),
|
|
1590
|
+
sharing: z.enum(["only_me", "anyone"]).optional()
|
|
780
1591
|
}),
|
|
781
1592
|
workspace: z.object({
|
|
782
1593
|
id: z.string().min(1),
|
|
783
1594
|
name: z.string(),
|
|
784
|
-
slug: z.string().nullish()
|
|
1595
|
+
slug: z.string().nullish(),
|
|
1596
|
+
memberCount: z.number().int().nonnegative().optional()
|
|
785
1597
|
}),
|
|
786
1598
|
enrolledBy: z.object({
|
|
787
1599
|
name: z.string(),
|
|
@@ -819,7 +1631,7 @@ async function whoami(options) {
|
|
|
819
1631
|
};
|
|
820
1632
|
}
|
|
821
1633
|
// cli.ts
|
|
822
|
-
const DEFAULT_SERVER = "https://
|
|
1634
|
+
const DEFAULT_SERVER = "https://app.relayrunner.app";
|
|
823
1635
|
const connectCommand = defineCommand({
|
|
824
1636
|
meta: {
|
|
825
1637
|
name: "connect",
|
|
@@ -833,6 +1645,10 @@ const connectCommand = defineCommand({
|
|
|
833
1645
|
name: {
|
|
834
1646
|
type: "string",
|
|
835
1647
|
description: "Suggested machine name when signing in (default: this computer's hostname)"
|
|
1648
|
+
},
|
|
1649
|
+
share: {
|
|
1650
|
+
type: "string",
|
|
1651
|
+
description: "Who can run jobs on this machine: only-me (jobs you started) or anyone in the workspace. Skips the question."
|
|
836
1652
|
}
|
|
837
1653
|
},
|
|
838
1654
|
async run({ args }) {
|
|
@@ -847,24 +1663,22 @@ const connectCommand = defineCommand({
|
|
|
847
1663
|
}
|
|
848
1664
|
});
|
|
849
1665
|
async function connectMachine(args) {
|
|
850
|
-
const
|
|
851
|
-
const
|
|
852
|
-
const platform = {
|
|
853
|
-
os: target.os === "osx" ? "macos" : "linux",
|
|
854
|
-
arch: target.arch
|
|
855
|
-
};
|
|
1666
|
+
const share = shareArg(args.share);
|
|
1667
|
+
const platform = machinePlatform();
|
|
856
1668
|
let credentials = readCredentials();
|
|
857
|
-
const server =
|
|
1669
|
+
const server = serverFor(args.server, credentials);
|
|
858
1670
|
if (credentials && credentials.server !== server) {
|
|
859
1671
|
clack.log.warn(`This machine is enrolled with ${credentials.server}, not ${server}. Signing in again.`);
|
|
860
1672
|
credentials = null;
|
|
861
1673
|
}
|
|
862
|
-
if (!credentials)
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
}
|
|
1674
|
+
if (!credentials) credentials = await enroll(server, args.name, platform, share);
|
|
1675
|
+
else {
|
|
1676
|
+
clack.log.info(`Machine ${credentials.machine.name} in ${credentials.workspace.name} (${credentials.server})`);
|
|
1677
|
+
if (share) await applySharing(credentials, share);
|
|
1678
|
+
}
|
|
1679
|
+
if (process.stdin.isTTY && process.stdout.isTTY) await offerSetup();
|
|
867
1680
|
const runner = await ensureRunner({ log: (line) => clack.log.info(line) });
|
|
1681
|
+
const device = await detectDevice();
|
|
868
1682
|
const stop = new AbortController();
|
|
869
1683
|
const onInterrupt = () => {
|
|
870
1684
|
if (stop.signal.aborted) process.exit(130);
|
|
@@ -878,7 +1692,8 @@ async function connectMachine(args) {
|
|
|
878
1692
|
hello: {
|
|
879
1693
|
machineId: credentials.machine.id,
|
|
880
1694
|
...platform,
|
|
881
|
-
runnerVersion: runner.version
|
|
1695
|
+
runnerVersion: runner.version,
|
|
1696
|
+
device
|
|
882
1697
|
},
|
|
883
1698
|
runJob: (run, report) => runJob(run, {
|
|
884
1699
|
runner,
|
|
@@ -919,6 +1734,115 @@ async function connectMachine(args) {
|
|
|
919
1734
|
process.exitCode = 1;
|
|
920
1735
|
}
|
|
921
1736
|
}
|
|
1737
|
+
async function askSharing(workspace) {
|
|
1738
|
+
const picked = await clack.select({
|
|
1739
|
+
message: "Who can run jobs on this machine?",
|
|
1740
|
+
options: [{
|
|
1741
|
+
value: "only-me",
|
|
1742
|
+
label: "Only me",
|
|
1743
|
+
hint: "jobs you started"
|
|
1744
|
+
}, {
|
|
1745
|
+
value: "anyone",
|
|
1746
|
+
label: `Anyone in ${workspace}`,
|
|
1747
|
+
hint: "teammates' and bots' jobs too"
|
|
1748
|
+
}],
|
|
1749
|
+
initialValue: "only-me"
|
|
1750
|
+
});
|
|
1751
|
+
if (clack.isCancel(picked)) {
|
|
1752
|
+
clack.log.info("Keeping only-me. Change it any time with `relayrunner share`.");
|
|
1753
|
+
return null;
|
|
1754
|
+
}
|
|
1755
|
+
return picked;
|
|
1756
|
+
}
|
|
1757
|
+
async function applySharing(credentials, choice) {
|
|
1758
|
+
const result = await setSharing({
|
|
1759
|
+
server: credentials.server,
|
|
1760
|
+
token: credentials.token,
|
|
1761
|
+
sharing: toSharing(choice)
|
|
1762
|
+
});
|
|
1763
|
+
switch (result.status) {
|
|
1764
|
+
case "ok":
|
|
1765
|
+
clack.log.info(`Sharing: ${describeSharing(result.sharing, credentials.workspace.name)}`);
|
|
1766
|
+
break;
|
|
1767
|
+
case "revoked": break;
|
|
1768
|
+
case "failed": clack.log.warn(`Couldn't set sharing: ${result.reason}. Run \`relayrunner share ${choice}\` to try again.`);
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
const loginCommand = defineCommand({
|
|
1772
|
+
meta: {
|
|
1773
|
+
name: "login",
|
|
1774
|
+
description: "Sign this machine in to your workspace without putting it online. Run `relayrunner connect` afterwards to take jobs."
|
|
1775
|
+
},
|
|
1776
|
+
args: {
|
|
1777
|
+
server: {
|
|
1778
|
+
type: "string",
|
|
1779
|
+
description: `RelayRunner URL (default: $RELAYRUNNER_URL or ${DEFAULT_SERVER})`
|
|
1780
|
+
},
|
|
1781
|
+
name: {
|
|
1782
|
+
type: "string",
|
|
1783
|
+
description: "Suggested machine name (default: this computer's hostname)"
|
|
1784
|
+
},
|
|
1785
|
+
share: {
|
|
1786
|
+
type: "string",
|
|
1787
|
+
description: "Who can run jobs on this machine: only-me (jobs you started) or anyone in the workspace. Skips the question."
|
|
1788
|
+
}
|
|
1789
|
+
},
|
|
1790
|
+
async run({ args }) {
|
|
1791
|
+
clack.intro("RelayRunner");
|
|
1792
|
+
try {
|
|
1793
|
+
const share = shareArg(args.share);
|
|
1794
|
+
const saved = readCredentials();
|
|
1795
|
+
const server = serverFor(args.server, saved);
|
|
1796
|
+
if (saved && saved.server === server) {
|
|
1797
|
+
if ((await whoami({
|
|
1798
|
+
server,
|
|
1799
|
+
token: saved.token
|
|
1800
|
+
})).status !== "revoked") {
|
|
1801
|
+
if (share) await applySharing(saved, share);
|
|
1802
|
+
clack.outro(`Already signed in as ${saved.machine.name} in ${saved.workspace.name}. Run \`relayrunner connect\` to go online.`);
|
|
1803
|
+
return;
|
|
1804
|
+
}
|
|
1805
|
+
clack.log.warn(`${saved.machine.name} is no longer enrolled in ${saved.workspace.name}. Signing in again.`);
|
|
1806
|
+
} else if (saved) clack.log.warn(`This machine is enrolled with ${saved.server}, not ${server}. Signing in again.`);
|
|
1807
|
+
await enroll(server, args.name, machinePlatform(), share);
|
|
1808
|
+
clack.outro("Run `relayrunner connect` to put this machine online.");
|
|
1809
|
+
} catch (error) {
|
|
1810
|
+
if (!(error instanceof LoginError || error instanceof RunnerError)) throw error;
|
|
1811
|
+
clack.log.error(error.message);
|
|
1812
|
+
process.exitCode = 1;
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
});
|
|
1816
|
+
function shareArg(value) {
|
|
1817
|
+
const share = value ? parseShareChoice(value) : null;
|
|
1818
|
+
if (value && !share) throw new RunnerError("USAGE", `--share takes ${SHARE_CHOICES.join(" or ")}, not ${JSON.stringify(value)}.`);
|
|
1819
|
+
return share;
|
|
1820
|
+
}
|
|
1821
|
+
/** An explicit --server or RELAYRUNNER_URL wins; otherwise the gateway this machine enrolled with. */
|
|
1822
|
+
function serverFor(requested, saved) {
|
|
1823
|
+
return normalizeServer(requested || process.env.RELAYRUNNER_URL || saved?.server || DEFAULT_SERVER);
|
|
1824
|
+
}
|
|
1825
|
+
function machinePlatform() {
|
|
1826
|
+
const target = runnerPlatform();
|
|
1827
|
+
return {
|
|
1828
|
+
os: target.os === "osx" ? "macos" : "linux",
|
|
1829
|
+
arch: target.arch
|
|
1830
|
+
};
|
|
1831
|
+
}
|
|
1832
|
+
/** Signs in through the browser, saves the machine token, and settles who can run jobs here. */
|
|
1833
|
+
async function enroll(server, name, platform, share) {
|
|
1834
|
+
const signedIn = await signIn(server, name || hostname(), platform);
|
|
1835
|
+
const credentials = signedIn.credentials;
|
|
1836
|
+
writeCredentials(credentials);
|
|
1837
|
+
clack.log.success(`Enrolled as ${credentials.machine.name} in ${credentials.workspace.name}. Token saved to ${credentialsPath()}.`);
|
|
1838
|
+
let choice = share;
|
|
1839
|
+
if (!choice && (signedIn.memberCount ?? 0) > 1) {
|
|
1840
|
+
if (process.stdin.isTTY && process.stdout.isTTY) choice = await askSharing(credentials.workspace.name);
|
|
1841
|
+
else clack.log.info("Only jobs you started run here. `relayrunner share anyone` lets teammates' jobs run here too.");
|
|
1842
|
+
}
|
|
1843
|
+
if (choice) await applySharing(credentials, choice);
|
|
1844
|
+
return credentials;
|
|
1845
|
+
}
|
|
922
1846
|
async function signIn(server, name, platform) {
|
|
923
1847
|
const waiting = clack.spinner();
|
|
924
1848
|
try {
|
|
@@ -995,7 +1919,7 @@ const whoamiCommand = defineCommand({
|
|
|
995
1919
|
const requested = args.server || process.env.RELAYRUNNER_URL;
|
|
996
1920
|
const server = requested ? normalizeServer(requested) : credentials?.server;
|
|
997
1921
|
if (!credentials || credentials.server !== server) {
|
|
998
|
-
print(credentials ? `Not signed in to ${server}. This machine is enrolled with ${credentials.server}.` : "Not signed in. Run `relayrunner connect` to sign in.", {
|
|
1922
|
+
print(credentials ? `Not signed in to ${server}. This machine is enrolled with ${credentials.server}.` : "Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.", {
|
|
999
1923
|
status: "signed_out",
|
|
1000
1924
|
server: server ?? null
|
|
1001
1925
|
});
|
|
@@ -1043,6 +1967,7 @@ function describeIdentity(server, identity) {
|
|
|
1043
1967
|
["Platform", [machine.os, machine.arch].filter(Boolean).join(" ") || "unknown"],
|
|
1044
1968
|
["Enrolled", enrolled],
|
|
1045
1969
|
["Status", status],
|
|
1970
|
+
...machine.sharing ? [["Sharing", describeSharing(machine.sharing, workspace.name)]] : [],
|
|
1046
1971
|
["Gateway", server]
|
|
1047
1972
|
]);
|
|
1048
1973
|
}
|
|
@@ -1071,7 +1996,7 @@ function pauseCommand(paused) {
|
|
|
1071
1996
|
async run() {
|
|
1072
1997
|
const credentials = readCredentials();
|
|
1073
1998
|
if (!credentials) {
|
|
1074
|
-
console.error("Not signed in. Run `relayrunner connect` to sign in.");
|
|
1999
|
+
console.error("Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.");
|
|
1075
2000
|
process.exitCode = 1;
|
|
1076
2001
|
return;
|
|
1077
2002
|
}
|
|
@@ -1096,6 +2021,73 @@ function pauseCommand(paused) {
|
|
|
1096
2021
|
}
|
|
1097
2022
|
});
|
|
1098
2023
|
}
|
|
2024
|
+
const shareCommand = defineCommand({
|
|
2025
|
+
meta: {
|
|
2026
|
+
name: "share",
|
|
2027
|
+
description: "Show or change who can run jobs on this machine: only-me (jobs you started) or anyone in the workspace."
|
|
2028
|
+
},
|
|
2029
|
+
args: { who: {
|
|
2030
|
+
type: "positional",
|
|
2031
|
+
required: false,
|
|
2032
|
+
description: `${SHARE_CHOICES.join(" or ")}; leave out to show the current setting`
|
|
2033
|
+
} },
|
|
2034
|
+
async run({ args }) {
|
|
2035
|
+
const credentials = readCredentials();
|
|
2036
|
+
if (!credentials) {
|
|
2037
|
+
console.error("Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.");
|
|
2038
|
+
process.exitCode = 1;
|
|
2039
|
+
return;
|
|
2040
|
+
}
|
|
2041
|
+
const { name } = credentials.machine;
|
|
2042
|
+
const workspace = credentials.workspace.name;
|
|
2043
|
+
const revoked = () => {
|
|
2044
|
+
console.error(`${name} was removed from ${workspace} or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`);
|
|
2045
|
+
process.exitCode = 1;
|
|
2046
|
+
};
|
|
2047
|
+
if (args.who) {
|
|
2048
|
+
const choice = parseShareChoice(args.who);
|
|
2049
|
+
if (!choice) {
|
|
2050
|
+
console.error(`Use \`relayrunner share ${SHARE_CHOICES.join("` or `relayrunner share ")}\`.`);
|
|
2051
|
+
process.exitCode = 1;
|
|
2052
|
+
return;
|
|
2053
|
+
}
|
|
2054
|
+
const result = await setSharing({
|
|
2055
|
+
server: credentials.server,
|
|
2056
|
+
token: credentials.token,
|
|
2057
|
+
sharing: toSharing(choice)
|
|
2058
|
+
});
|
|
2059
|
+
if (result.status === "revoked") return revoked();
|
|
2060
|
+
if (result.status === "failed") {
|
|
2061
|
+
console.error(`Couldn't change sharing for ${name}: ${result.reason}.`);
|
|
2062
|
+
process.exitCode = 1;
|
|
2063
|
+
return;
|
|
2064
|
+
}
|
|
2065
|
+
console.log(`${name} now ${sharingMeaning(result.sharing, workspace)}.`);
|
|
2066
|
+
return;
|
|
2067
|
+
}
|
|
2068
|
+
const result = await whoami({
|
|
2069
|
+
server: credentials.server,
|
|
2070
|
+
token: credentials.token
|
|
2071
|
+
});
|
|
2072
|
+
if (result.status === "revoked") return revoked();
|
|
2073
|
+
if (result.status === "unverified") {
|
|
2074
|
+
console.error(`Couldn't check sharing for ${name}: ${result.reason}.`);
|
|
2075
|
+
process.exitCode = 1;
|
|
2076
|
+
return;
|
|
2077
|
+
}
|
|
2078
|
+
const { sharing } = result.identity.machine;
|
|
2079
|
+
if (!sharing) {
|
|
2080
|
+
console.error(`${credentials.server} doesn't support sharing yet.`);
|
|
2081
|
+
process.exitCode = 1;
|
|
2082
|
+
return;
|
|
2083
|
+
}
|
|
2084
|
+
const other = sharing === "only_me" ? "anyone" : "only-me";
|
|
2085
|
+
const lines = [`${name} ${sharingMeaning(sharing, workspace)} (${toChoice(sharing)}).`];
|
|
2086
|
+
if (result.identity.workspace.memberCount === 1) lines.push(`Nobody else is in ${workspace} yet, so this matters once a teammate joins.`);
|
|
2087
|
+
lines.push(`Change it with \`relayrunner share ${other}\`.`);
|
|
2088
|
+
console.log(lines.join("\n"));
|
|
2089
|
+
}
|
|
2090
|
+
});
|
|
1099
2091
|
const main = defineCommand({
|
|
1100
2092
|
meta: {
|
|
1101
2093
|
name: "relayrunner",
|
|
@@ -1103,9 +2095,12 @@ const main = defineCommand({
|
|
|
1103
2095
|
},
|
|
1104
2096
|
subCommands: {
|
|
1105
2097
|
connect: connectCommand,
|
|
2098
|
+
login: loginCommand,
|
|
1106
2099
|
whoami: whoamiCommand,
|
|
2100
|
+
init: initCommand,
|
|
1107
2101
|
pause: pauseCommand(true),
|
|
1108
|
-
resume: pauseCommand(false)
|
|
2102
|
+
resume: pauseCommand(false),
|
|
2103
|
+
share: shareCommand
|
|
1109
2104
|
}
|
|
1110
2105
|
});
|
|
1111
2106
|
runMain(main);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "relayrunner",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Run GitHub Actions jobs on your machine through the RelayRunner gateway.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"dependencies": {
|
|
21
21
|
"@clack/prompts": "^1.8.1",
|
|
22
22
|
"citty": "^0.2.2",
|
|
23
|
+
"yaml": "^2.9.1",
|
|
23
24
|
"zod": "^4.6.7"
|
|
24
25
|
},
|
|
25
26
|
"devDependencies": {
|