relayrunner 0.1.1 → 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 +130 -27
- package/dist/cli.js +2105 -126
- package/package.json +14 -6
- package/dist/SKILL.md +0 -15
- package/dist/routing.js +0 -74
- package/dist/runner.js +0 -152
- package/dist/system.js +0 -41
- package/dist/workflows.js +0 -109
package/dist/cli.js
CHANGED
|
@@ -1,128 +1,2107 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
if (!routeMode || values.job || values.approve !== undefined)
|
|
33
|
-
throw new SetupError('USAGE', usage);
|
|
34
|
-
const result = await routeJobs(repository(values.cwd), routeMode);
|
|
35
|
-
if (values.json) {
|
|
36
|
-
console.log(JSON.stringify({ ok: true, ...result }));
|
|
37
|
-
}
|
|
38
|
-
else {
|
|
39
|
-
console.log(`${result.repo}: ${result.route === 'local' ? 'local (repository-wide)' : 'GitHub-hosted'}`);
|
|
40
|
-
if (result.runner)
|
|
41
|
-
console.log(`Runner ${result.runner.label}: ${result.runner.status}`);
|
|
42
|
-
else if (command === 'status')
|
|
43
|
-
console.log('No local runner configured.');
|
|
44
|
-
if ('warning' in result)
|
|
45
|
-
console.log(result.warning);
|
|
46
|
-
if ('queuedJobs' in result && result.queuedJobs) {
|
|
47
|
-
console.log(`Jobs still queued for the local runner: ${result.queuedJobs.length}`);
|
|
48
|
-
for (const job of result.queuedJobs)
|
|
49
|
-
console.log(` ${job.name} ${job.url}`);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
if (positionals.length !== 1 || !['discover', 'preview', 'setup'].includes(command)) {
|
|
55
|
-
throw new SetupError('USAGE', usage);
|
|
56
|
-
}
|
|
57
|
-
const jobs = values.job;
|
|
58
|
-
if ((command !== 'discover' && !jobs?.length) || (command === 'setup' && !values.approve)) {
|
|
59
|
-
throw new SetupError('USAGE', usage);
|
|
60
|
-
}
|
|
61
|
-
const target = repository(values.cwd);
|
|
62
|
-
if (command === 'discover') {
|
|
63
|
-
const discovered = workflows(target.root);
|
|
64
|
-
if (values.json) {
|
|
65
|
-
const output = discovered.map(({ id, runsOn, alreadySetUp }) => ({ id, runsOn, alreadySetUp }));
|
|
66
|
-
console.log(JSON.stringify({ ok: true, repo: target.repo, jobs: output }));
|
|
67
|
-
}
|
|
68
|
-
else {
|
|
69
|
-
console.log(target.repo);
|
|
70
|
-
for (const job of discovered) {
|
|
71
|
-
const hosted = styleText('cyan', `☁️ GitHub-hosted ${job.hostedRunner}`);
|
|
72
|
-
const local = styleText('green', '💻 local runner');
|
|
73
|
-
const routing = job.alreadySetUp
|
|
74
|
-
? `${local} when enabled, otherwise ${hosted}${job.needsUpdate ? ' (rerun setup to enable repository-wide routing)' : ''}`
|
|
75
|
-
: hosted;
|
|
76
|
-
console.log(` ${job.id} (${routing})`);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
return;
|
|
80
|
-
}
|
|
81
|
-
const selected = jobs ?? [];
|
|
82
|
-
const preview = plan(target, selected);
|
|
83
|
-
if (command === 'preview') {
|
|
84
|
-
if (values.json)
|
|
85
|
-
console.log(JSON.stringify({ ok: true, ...preview }));
|
|
86
|
-
else
|
|
87
|
-
console.log(`${preview.repo} on ${preview.branch}\n${preview.patch || 'No workflow changes needed.\n'}\nApproval fingerprint ${preview.fingerprint}`);
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
if (values.approve !== preview.fingerprint) {
|
|
91
|
-
throw new SetupError('STALE_PREVIEW', 'The approved preview differs from the current checkout or selection. Preview again.');
|
|
92
|
-
}
|
|
93
|
-
const check = () => {
|
|
94
|
-
if (plan(target, selected).fingerprint !== preview.fingerprint) {
|
|
95
|
-
throw new SetupError('STALE_PREVIEW', 'The checkout changed during setup. Preview again.');
|
|
96
|
-
}
|
|
97
|
-
if (preview.patch)
|
|
98
|
-
git(target.root, ['apply', '--whitespace=nowarn', '--check', '-'], { input: preview.patch });
|
|
99
|
-
};
|
|
100
|
-
check();
|
|
101
|
-
if (preview.patch) {
|
|
102
|
-
const pages = api(`repos/${target.repo}/actions/variables?per_page=100`, ['--paginate', '--slurp']);
|
|
103
|
-
if (pages.some(page => page.variables.some(variable => ['RELAYRUNNER_REF', 'RELAYRUNNER_LABEL'].includes(variable.name) && variable.value))) {
|
|
104
|
-
throw new SetupError('ROUTE_CONFIGURED', 'Clear the existing RelayRunner routing variables before setting up more jobs.');
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
const runner = await withRunner(target, online => {
|
|
108
|
-
check();
|
|
109
|
-
if (preview.patch)
|
|
110
|
-
git(target.root, ['apply', '--whitespace=nowarn', '-'], { input: preview.patch });
|
|
111
|
-
return online;
|
|
112
|
-
});
|
|
113
|
-
const workflowChanges = preview.patch ? 'applied' : 'already-applied';
|
|
114
|
-
if (values.json)
|
|
115
|
-
console.log(JSON.stringify({ ok: true, ...preview, runner, workflowChanges }));
|
|
116
|
-
else
|
|
117
|
-
console.log(`Runner ${runner.label} is online for ${preview.repo}. Workflow changes ${workflowChanges}.\nCommit and push the reviewed workflow changes through your usual Git workflow.`);
|
|
118
|
-
}
|
|
119
|
-
main().catch(error => {
|
|
120
|
-
const known = error instanceof SetupError || error.code?.startsWith('ERR_PARSE_ARGS');
|
|
121
|
-
const code = error instanceof SetupError ? error.code : known ? 'USAGE' : 'SETUP_FAILED';
|
|
122
|
-
const message = known ? error.message : 'Setup could not complete. Check the checkout and local RelayRunner state permissions, then retry.';
|
|
123
|
-
if (process.argv.includes('--json'))
|
|
124
|
-
console.log(JSON.stringify({ ok: false, error: { code, message } }));
|
|
125
|
-
else
|
|
126
|
-
console.error(message);
|
|
127
|
-
process.exitCode = 1;
|
|
2
|
+
import { arch, cpus, homedir, hostname, platform, totalmem } from "node:os";
|
|
3
|
+
import * as clack from "@clack/prompts";
|
|
4
|
+
import { defineCommand, runMain } from "citty";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
7
|
+
import { chmodSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { execFile, spawn } from "node:child_process";
|
|
9
|
+
import { styleText } from "node:util";
|
|
10
|
+
import { Scalar, YAMLSeq, isMap, isScalar, isSeq, parseDocument } from "yaml";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { Readable, Transform } from "node:stream";
|
|
13
|
+
import { pipeline } from "node:stream/promises";
|
|
14
|
+
const version = z.literal(1);
|
|
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()
|
|
128
32
|
});
|
|
33
|
+
const HelloMessage = z.object({
|
|
34
|
+
v: version,
|
|
35
|
+
type: z.literal("hello"),
|
|
36
|
+
machineId: z.string().min(1),
|
|
37
|
+
os: z.enum([
|
|
38
|
+
"linux",
|
|
39
|
+
"macos",
|
|
40
|
+
"windows"
|
|
41
|
+
]),
|
|
42
|
+
arch: z.enum([
|
|
43
|
+
"x64",
|
|
44
|
+
"arm64",
|
|
45
|
+
"arm"
|
|
46
|
+
]),
|
|
47
|
+
runnerVersion: z.string().min(1),
|
|
48
|
+
device: Device.optional().catch(void 0)
|
|
49
|
+
});
|
|
50
|
+
const StatusMessage = z.object({
|
|
51
|
+
v: version,
|
|
52
|
+
type: z.literal("status"),
|
|
53
|
+
state: z.enum(["idle", "busy"])
|
|
54
|
+
});
|
|
55
|
+
const JobMessage = z.object({
|
|
56
|
+
v: version,
|
|
57
|
+
type: z.literal("job"),
|
|
58
|
+
routeId,
|
|
59
|
+
state: z.enum([
|
|
60
|
+
"started",
|
|
61
|
+
"finished",
|
|
62
|
+
"failed"
|
|
63
|
+
]),
|
|
64
|
+
message: z.string().optional()
|
|
65
|
+
});
|
|
66
|
+
z.discriminatedUnion("type", [
|
|
67
|
+
HelloMessage,
|
|
68
|
+
StatusMessage,
|
|
69
|
+
JobMessage
|
|
70
|
+
]);
|
|
71
|
+
const RunMessage = z.object({
|
|
72
|
+
v: version,
|
|
73
|
+
type: z.literal("run"),
|
|
74
|
+
routeId,
|
|
75
|
+
jitConfig: z.string().min(1)
|
|
76
|
+
});
|
|
77
|
+
const ErrorMessage = z.object({
|
|
78
|
+
v: version,
|
|
79
|
+
type: z.literal("error"),
|
|
80
|
+
code: z.enum(["version_mismatch", "invalid_message"]),
|
|
81
|
+
message: z.string()
|
|
82
|
+
});
|
|
83
|
+
const PausedMessage = z.object({
|
|
84
|
+
v: version,
|
|
85
|
+
type: z.literal("paused"),
|
|
86
|
+
paused: z.boolean(),
|
|
87
|
+
by: z.string().nullable()
|
|
88
|
+
});
|
|
89
|
+
const GatewayMessage = z.discriminatedUnion("type", [
|
|
90
|
+
RunMessage,
|
|
91
|
+
ErrorMessage,
|
|
92
|
+
PausedMessage
|
|
93
|
+
]);
|
|
94
|
+
function parseGatewayMessage(frame) {
|
|
95
|
+
return parse(GatewayMessage, frame);
|
|
96
|
+
}
|
|
97
|
+
function encodeMessage(message) {
|
|
98
|
+
return JSON.stringify(message);
|
|
99
|
+
}
|
|
100
|
+
function parse(schema, frame) {
|
|
101
|
+
let data;
|
|
102
|
+
try {
|
|
103
|
+
data = JSON.parse(frame);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
return {
|
|
106
|
+
ok: false,
|
|
107
|
+
reason: "invalid_json",
|
|
108
|
+
error: String(error)
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
const v = typeof data === "object" && data !== null ? data.v : void 0;
|
|
112
|
+
if (v !== 1) return {
|
|
113
|
+
ok: false,
|
|
114
|
+
reason: "version_mismatch",
|
|
115
|
+
error: `expected protocol version 1, got ${JSON.stringify(v) ?? "none"}`
|
|
116
|
+
};
|
|
117
|
+
const result = schema.safeParse(data);
|
|
118
|
+
if (!result.success) return {
|
|
119
|
+
ok: false,
|
|
120
|
+
reason: "invalid_message",
|
|
121
|
+
error: z.prettifyError(result.error)
|
|
122
|
+
};
|
|
123
|
+
return {
|
|
124
|
+
ok: true,
|
|
125
|
+
message: result.data
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
// paths.ts
|
|
129
|
+
function relayrunnerHome() {
|
|
130
|
+
return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), ".relayrunner"));
|
|
131
|
+
}
|
|
132
|
+
function runnersDir() {
|
|
133
|
+
return join(relayrunnerHome(), "runner");
|
|
134
|
+
}
|
|
135
|
+
const userAgent = "relayrunner-cli";
|
|
136
|
+
const CLOSE_POLICY = 1008;
|
|
137
|
+
const NodeWebSocket = WebSocket;
|
|
138
|
+
function connectUrl(server) {
|
|
139
|
+
const url = new URL("/api/machines/connect", server);
|
|
140
|
+
url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
|
|
141
|
+
return url.toString();
|
|
142
|
+
}
|
|
143
|
+
function backoff(attempt, min, max, random = Math.random) {
|
|
144
|
+
const base = Math.min(max, min * 2 ** Math.max(0, attempt - 1));
|
|
145
|
+
return Math.round(base * (.75 + random() * .5));
|
|
146
|
+
}
|
|
147
|
+
async function connect(options) {
|
|
148
|
+
const heartbeatMs = options.heartbeatMs ?? 3e4;
|
|
149
|
+
const minBackoffMs = options.minBackoffMs ?? 1e3;
|
|
150
|
+
const maxBackoffMs = options.maxBackoffMs ?? 3e4;
|
|
151
|
+
const emit = options.onEvent ?? (() => {});
|
|
152
|
+
const signal = options.signal;
|
|
153
|
+
let state = "idle";
|
|
154
|
+
let socket = null;
|
|
155
|
+
const pending = [];
|
|
156
|
+
let gatewayError = "";
|
|
157
|
+
const send = (message) => {
|
|
158
|
+
if (socket?.readyState === WebSocket.OPEN) socket.send(encodeMessage(message));
|
|
159
|
+
else if (message.type === "job") pending.push(message);
|
|
160
|
+
};
|
|
161
|
+
const sendStatus = () => send({
|
|
162
|
+
v: 1,
|
|
163
|
+
type: "status",
|
|
164
|
+
state
|
|
165
|
+
});
|
|
166
|
+
const startJob = (run) => {
|
|
167
|
+
if (state === "busy") {
|
|
168
|
+
emit({
|
|
169
|
+
type: "run-refused",
|
|
170
|
+
routeId: run.routeId
|
|
171
|
+
});
|
|
172
|
+
const update = {
|
|
173
|
+
routeId: run.routeId,
|
|
174
|
+
state: "failed",
|
|
175
|
+
message: "The machine is already running a job."
|
|
176
|
+
};
|
|
177
|
+
send({
|
|
178
|
+
v: 1,
|
|
179
|
+
type: "job",
|
|
180
|
+
...update
|
|
181
|
+
});
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
emit({
|
|
185
|
+
type: "run",
|
|
186
|
+
routeId: run.routeId
|
|
187
|
+
});
|
|
188
|
+
state = "busy";
|
|
189
|
+
sendStatus();
|
|
190
|
+
options.runJob(run, (update) => {
|
|
191
|
+
emit({
|
|
192
|
+
type: "job",
|
|
193
|
+
update
|
|
194
|
+
});
|
|
195
|
+
send({
|
|
196
|
+
v: 1,
|
|
197
|
+
type: "job",
|
|
198
|
+
...update
|
|
199
|
+
});
|
|
200
|
+
}).finally(() => {
|
|
201
|
+
state = "idle";
|
|
202
|
+
sendStatus();
|
|
203
|
+
});
|
|
204
|
+
};
|
|
205
|
+
const session = () => new Promise((resolve) => {
|
|
206
|
+
let opened = false;
|
|
207
|
+
let heartbeat;
|
|
208
|
+
const ws = new NodeWebSocket(connectUrl(options.server), { headers: {
|
|
209
|
+
authorization: `Bearer ${options.token}`,
|
|
210
|
+
"user-agent": userAgent
|
|
211
|
+
} });
|
|
212
|
+
socket = ws;
|
|
213
|
+
let settled = false;
|
|
214
|
+
const finish = (code, reason) => {
|
|
215
|
+
if (settled) return;
|
|
216
|
+
settled = true;
|
|
217
|
+
clearInterval(heartbeat);
|
|
218
|
+
signal?.removeEventListener("abort", onAbort);
|
|
219
|
+
if (socket === ws) socket = null;
|
|
220
|
+
resolve({
|
|
221
|
+
opened,
|
|
222
|
+
code,
|
|
223
|
+
reason
|
|
224
|
+
});
|
|
225
|
+
};
|
|
226
|
+
const onAbort = () => {
|
|
227
|
+
ws.close(1e3, "machine going offline");
|
|
228
|
+
finish(1e3, "machine going offline");
|
|
229
|
+
};
|
|
230
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
231
|
+
ws.addEventListener("open", () => {
|
|
232
|
+
opened = true;
|
|
233
|
+
emit({ type: "connected" });
|
|
234
|
+
ws.send(encodeMessage({
|
|
235
|
+
v: 1,
|
|
236
|
+
type: "hello",
|
|
237
|
+
...options.hello
|
|
238
|
+
}));
|
|
239
|
+
sendStatus();
|
|
240
|
+
for (const message of pending.splice(0)) send(message);
|
|
241
|
+
heartbeat = setInterval(sendStatus, heartbeatMs);
|
|
242
|
+
});
|
|
243
|
+
ws.addEventListener("message", (event) => {
|
|
244
|
+
if (typeof event.data !== "string") return;
|
|
245
|
+
const parsed = parseGatewayMessage(event.data);
|
|
246
|
+
if (!parsed.ok) {
|
|
247
|
+
emit({
|
|
248
|
+
type: "gateway-error",
|
|
249
|
+
code: parsed.reason,
|
|
250
|
+
message: parsed.error
|
|
251
|
+
});
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const message = parsed.message;
|
|
255
|
+
if (message.type === "run") startJob(message);
|
|
256
|
+
else if (message.type === "paused") emit({
|
|
257
|
+
type: "paused",
|
|
258
|
+
paused: message.paused,
|
|
259
|
+
by: message.by
|
|
260
|
+
});
|
|
261
|
+
else {
|
|
262
|
+
gatewayError = message.message;
|
|
263
|
+
emit({
|
|
264
|
+
type: "gateway-error",
|
|
265
|
+
code: message.code,
|
|
266
|
+
message: message.message
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
ws.addEventListener("close", (event) => finish(event.code, event.reason));
|
|
271
|
+
ws.addEventListener("error", () => {
|
|
272
|
+
if (!opened) finish(1006, "");
|
|
273
|
+
});
|
|
274
|
+
});
|
|
275
|
+
const tokenRejected = () => fetch(new URL("/api/machines/connect", options.server), {
|
|
276
|
+
headers: {
|
|
277
|
+
authorization: `Bearer ${options.token}`,
|
|
278
|
+
"user-agent": userAgent
|
|
279
|
+
},
|
|
280
|
+
signal: AbortSignal.timeout(1e4)
|
|
281
|
+
}).then(async (response) => {
|
|
282
|
+
await response.body?.cancel();
|
|
283
|
+
return response.status === 401;
|
|
284
|
+
}, () => false);
|
|
285
|
+
let attempt = 0;
|
|
286
|
+
while (!signal?.aborted) {
|
|
287
|
+
attempt++;
|
|
288
|
+
emit({
|
|
289
|
+
type: "connecting",
|
|
290
|
+
attempt
|
|
291
|
+
});
|
|
292
|
+
const { opened, code, reason } = await session();
|
|
293
|
+
if (signal?.aborted) break;
|
|
294
|
+
if (opened) attempt = 1;
|
|
295
|
+
if (code === 4001) return { reason: "revoked" };
|
|
296
|
+
if (code === 4002) return { reason: "replaced" };
|
|
297
|
+
if (code === CLOSE_POLICY) return {
|
|
298
|
+
reason: "rejected",
|
|
299
|
+
message: gatewayError || reason || "protocol error"
|
|
300
|
+
};
|
|
301
|
+
if (!opened && await tokenRejected()) return { reason: "revoked" };
|
|
302
|
+
const retryInMs = backoff(attempt, minBackoffMs, maxBackoffMs);
|
|
303
|
+
emit({
|
|
304
|
+
type: "disconnected",
|
|
305
|
+
code,
|
|
306
|
+
reason,
|
|
307
|
+
retryInMs
|
|
308
|
+
});
|
|
309
|
+
await delay(retryInMs, signal);
|
|
310
|
+
}
|
|
311
|
+
return { reason: "stopped" };
|
|
312
|
+
}
|
|
313
|
+
function delay(ms, signal) {
|
|
314
|
+
return new Promise((resolve) => {
|
|
315
|
+
const timer = setTimeout(done, ms);
|
|
316
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
317
|
+
function done() {
|
|
318
|
+
clearTimeout(timer);
|
|
319
|
+
signal?.removeEventListener("abort", done);
|
|
320
|
+
resolve();
|
|
321
|
+
}
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
// credentials.ts
|
|
325
|
+
const Credentials = z.object({
|
|
326
|
+
server: z.url(),
|
|
327
|
+
machine: z.object({
|
|
328
|
+
id: z.string().min(1),
|
|
329
|
+
name: z.string()
|
|
330
|
+
}),
|
|
331
|
+
workspace: z.object({
|
|
332
|
+
id: z.string().min(1),
|
|
333
|
+
name: z.string(),
|
|
334
|
+
slug: z.string().nullish()
|
|
335
|
+
}),
|
|
336
|
+
token: z.string().min(1)
|
|
337
|
+
});
|
|
338
|
+
function credentialsPath(home = relayrunnerHome()) {
|
|
339
|
+
return join(home, "machine.json");
|
|
340
|
+
}
|
|
341
|
+
function readCredentials(path = credentialsPath()) {
|
|
342
|
+
let text;
|
|
343
|
+
try {
|
|
344
|
+
text = readFileSync(path, "utf8");
|
|
345
|
+
} catch (error) {
|
|
346
|
+
if (error.code === "ENOENT") return null;
|
|
347
|
+
throw error;
|
|
348
|
+
}
|
|
349
|
+
try {
|
|
350
|
+
const parsed = Credentials.safeParse(JSON.parse(text));
|
|
351
|
+
return parsed.success ? parsed.data : null;
|
|
352
|
+
} catch {
|
|
353
|
+
return null;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function writeCredentials(credentials, path = credentialsPath()) {
|
|
357
|
+
const dir = join(path, "..");
|
|
358
|
+
mkdirSync(dir, {
|
|
359
|
+
recursive: true,
|
|
360
|
+
mode: 448
|
|
361
|
+
});
|
|
362
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
363
|
+
writeFileSync(temp, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 384 });
|
|
364
|
+
chmodSync(temp, 384);
|
|
365
|
+
renameSync(temp, path);
|
|
366
|
+
}
|
|
367
|
+
function deleteCredentials(path = credentialsPath()) {
|
|
368
|
+
rmSync(path, { force: true });
|
|
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
|
+
}
|
|
1101
|
+
// install.ts
|
|
1102
|
+
var RunnerError = class extends Error {
|
|
1103
|
+
code;
|
|
1104
|
+
constructor(code, message) {
|
|
1105
|
+
super(message);
|
|
1106
|
+
this.code = code;
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
const LATEST_RELEASE = "https://api.github.com/repos/actions/runner/releases/latest";
|
|
1110
|
+
const ARCHIVE_URL = /^https:\/\/github\.com\/actions\/runner\/releases\/download\/v[\d.]+\/actions-runner-[\w.-]+\.tar\.gz$/;
|
|
1111
|
+
const SHA256 = /^[a-f\d]{64}$/;
|
|
1112
|
+
const Release = z.object({
|
|
1113
|
+
tag_name: z.string().regex(/^v\d+\.\d+\.\d+$/),
|
|
1114
|
+
body: z.string().nullish(),
|
|
1115
|
+
assets: z.array(z.object({
|
|
1116
|
+
name: z.string(),
|
|
1117
|
+
browser_download_url: z.string(),
|
|
1118
|
+
digest: z.string().nullish()
|
|
1119
|
+
}))
|
|
1120
|
+
});
|
|
1121
|
+
function runnerPlatform() {
|
|
1122
|
+
const system = platform();
|
|
1123
|
+
const os = system === "darwin" ? "osx" : system;
|
|
1124
|
+
const architecture = arch();
|
|
1125
|
+
if (os !== "osx" && os !== "linux" || architecture !== "x64" && architecture !== "arm64" || process.getuid?.() === 0) throw new RunnerError("UNSUPPORTED_MACHINE", "Run as a regular user on macOS or Linux (x64 or arm64).");
|
|
1126
|
+
return {
|
|
1127
|
+
os,
|
|
1128
|
+
arch: architecture
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
function pickDownload(release, target) {
|
|
1132
|
+
const parsed = Release.safeParse(release);
|
|
1133
|
+
if (!parsed.success) throw new RunnerError("RUNNER_DOWNLOAD", "GitHub returned an unexpected runner release.");
|
|
1134
|
+
const { tag_name, body, assets } = parsed.data;
|
|
1135
|
+
const version = tag_name.slice(1);
|
|
1136
|
+
const name = `actions-runner-${target.os}-${target.arch}-${version}.tar.gz`;
|
|
1137
|
+
const asset = assets.find((item) => item.name === name);
|
|
1138
|
+
const key = `${target.os}-${target.arch}`;
|
|
1139
|
+
const fromNotes = body?.match(new RegExp(`<!-- BEGIN SHA ${key} -->\\s*([a-fA-F\\d]{64})\\s*<!-- END SHA ${key} -->`))?.[1]?.toLowerCase();
|
|
1140
|
+
const fromDigest = asset?.digest?.match(/^sha256:([a-fA-F\d]{64})$/)?.[1]?.toLowerCase();
|
|
1141
|
+
const sha256 = fromDigest ?? fromNotes;
|
|
1142
|
+
if (!asset || !ARCHIVE_URL.test(asset.browser_download_url) || !sha256 || !SHA256.test(sha256) || fromDigest && fromNotes && fromDigest !== fromNotes) throw new RunnerError("RUNNER_DOWNLOAD", `GitHub did not provide a ${name} archive with a SHA-256 checksum.`);
|
|
1143
|
+
return {
|
|
1144
|
+
version,
|
|
1145
|
+
url: asset.browser_download_url,
|
|
1146
|
+
sha256
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
async function latestDownload(target) {
|
|
1150
|
+
const response = await fetch(LATEST_RELEASE, { headers: {
|
|
1151
|
+
accept: "application/vnd.github+json",
|
|
1152
|
+
"user-agent": userAgent
|
|
1153
|
+
} });
|
|
1154
|
+
if (!response.ok) throw new RunnerError("RUNNER_DOWNLOAD", `Could not look up the latest actions/runner release (HTTP ${response.status}).`);
|
|
1155
|
+
return pickDownload(await response.json(), target);
|
|
1156
|
+
}
|
|
1157
|
+
function installedRunners(root = runnersDir()) {
|
|
1158
|
+
if (!existsSync(root)) return [];
|
|
1159
|
+
return readdirSync(root).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && existsSync(join(root, name, "run.sh"))).sort((a, b) => compareVersions(b, a)).map((version) => ({
|
|
1160
|
+
version,
|
|
1161
|
+
dir: join(root, version)
|
|
1162
|
+
}));
|
|
1163
|
+
}
|
|
1164
|
+
function compareVersions(a, b) {
|
|
1165
|
+
const [x, y] = [a, b].map((v) => v.split(".").map(Number));
|
|
1166
|
+
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];
|
|
1167
|
+
return 0;
|
|
1168
|
+
}
|
|
1169
|
+
async function ensureRunner(options = {}) {
|
|
1170
|
+
const root = options.root ?? runnersDir();
|
|
1171
|
+
const log = options.log ?? (() => {});
|
|
1172
|
+
const target = runnerPlatform();
|
|
1173
|
+
let download;
|
|
1174
|
+
try {
|
|
1175
|
+
download = await latestDownload(target);
|
|
1176
|
+
} catch (error) {
|
|
1177
|
+
const [newest] = installedRunners(root);
|
|
1178
|
+
if (newest) {
|
|
1179
|
+
log(`Couldn't check for a newer runner (${error.message}). Using ${newest.version}.`);
|
|
1180
|
+
return newest;
|
|
1181
|
+
}
|
|
1182
|
+
throw error;
|
|
1183
|
+
}
|
|
1184
|
+
const dir = join(root, download.version);
|
|
1185
|
+
if (existsSync(join(dir, "run.sh"))) return {
|
|
1186
|
+
version: download.version,
|
|
1187
|
+
dir
|
|
1188
|
+
};
|
|
1189
|
+
log(`Downloading actions/runner ${download.version}…`);
|
|
1190
|
+
await install(root, download);
|
|
1191
|
+
log(`Installed actions/runner ${download.version} in ${dir}`);
|
|
1192
|
+
return {
|
|
1193
|
+
version: download.version,
|
|
1194
|
+
dir
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
async function install(root, download, fetcher = fetch) {
|
|
1198
|
+
mkdirSync(root, {
|
|
1199
|
+
recursive: true,
|
|
1200
|
+
mode: 448
|
|
1201
|
+
});
|
|
1202
|
+
const temp = mkdtempSync(join(root, ".install-"));
|
|
1203
|
+
try {
|
|
1204
|
+
const archive = join(temp, "runner.tar.gz");
|
|
1205
|
+
const response = await fetcher(download.url, {
|
|
1206
|
+
headers: { "user-agent": userAgent },
|
|
1207
|
+
signal: AbortSignal.timeout(6e5)
|
|
1208
|
+
});
|
|
1209
|
+
if (!response.ok || !response.body) throw new RunnerError("RUNNER_DOWNLOAD", `Runner download failed (HTTP ${response.status}). Check network access.`);
|
|
1210
|
+
const hash = createHash("sha256");
|
|
1211
|
+
await pipeline(Readable.fromWeb(response.body), new Transform({ transform(chunk, _encoding, done) {
|
|
1212
|
+
hash.update(chunk);
|
|
1213
|
+
done(null, chunk);
|
|
1214
|
+
} }), createWriteStream(archive, { mode: 384 }));
|
|
1215
|
+
if (hash.digest("hex") !== download.sha256) throw new RunnerError("RUNNER_CHECKSUM", "The runner archive failed SHA-256 verification.");
|
|
1216
|
+
const unpacked = join(temp, "runner");
|
|
1217
|
+
mkdirSync(unpacked, { mode: 448 });
|
|
1218
|
+
if (await exitCode("tar", [
|
|
1219
|
+
"-xzf",
|
|
1220
|
+
archive,
|
|
1221
|
+
"-C",
|
|
1222
|
+
unpacked
|
|
1223
|
+
]) !== 0) throw new RunnerError("RUNNER_EXTRACT", "Could not unpack the runner archive. Check tar and available disk space.");
|
|
1224
|
+
try {
|
|
1225
|
+
renameSync(unpacked, join(root, download.version));
|
|
1226
|
+
} catch (error) {
|
|
1227
|
+
const code = error.code;
|
|
1228
|
+
if (code !== "EEXIST" && code !== "ENOTEMPTY") throw error;
|
|
1229
|
+
}
|
|
1230
|
+
} finally {
|
|
1231
|
+
rmSync(temp, {
|
|
1232
|
+
recursive: true,
|
|
1233
|
+
force: true
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
function exitCode(command, args) {
|
|
1238
|
+
return new Promise((resolve) => {
|
|
1239
|
+
const child = spawn(command, args, { stdio: "ignore" });
|
|
1240
|
+
child.once("error", () => resolve(null));
|
|
1241
|
+
child.once("exit", (code) => resolve(code));
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
// job.ts
|
|
1245
|
+
const runnerEnv = () => Object.fromEntries([
|
|
1246
|
+
"HOME",
|
|
1247
|
+
"USER",
|
|
1248
|
+
"LOGNAME",
|
|
1249
|
+
"PATH",
|
|
1250
|
+
"LANG",
|
|
1251
|
+
"LC_ALL",
|
|
1252
|
+
"TMPDIR",
|
|
1253
|
+
"SHELL"
|
|
1254
|
+
].flatMap((key) => process.env[key] === void 0 ? [] : [[key, process.env[key]]]));
|
|
1255
|
+
const JOB_STATE = [
|
|
1256
|
+
"_work",
|
|
1257
|
+
".runner",
|
|
1258
|
+
".credentials",
|
|
1259
|
+
".credentials_rsaparams"
|
|
1260
|
+
];
|
|
1261
|
+
async function runJob(run, options) {
|
|
1262
|
+
const { runner, report } = options;
|
|
1263
|
+
const output = options.output ?? ((chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk));
|
|
1264
|
+
const finish = (update) => {
|
|
1265
|
+
report(update);
|
|
1266
|
+
return update;
|
|
1267
|
+
};
|
|
1268
|
+
const lock = join(runner.dir, "job.lock");
|
|
1269
|
+
if (!takeLock(lock)) return finish({
|
|
1270
|
+
routeId: run.routeId,
|
|
1271
|
+
state: "failed",
|
|
1272
|
+
message: `Another job is using the runner in ${runner.dir}.`
|
|
1273
|
+
});
|
|
1274
|
+
try {
|
|
1275
|
+
clean(runner.dir);
|
|
1276
|
+
const child = spawn(join(runner.dir, "run.sh"), ["--jitconfig", run.jitConfig], {
|
|
1277
|
+
cwd: runner.dir,
|
|
1278
|
+
env: runnerEnv(),
|
|
1279
|
+
stdio: [
|
|
1280
|
+
"ignore",
|
|
1281
|
+
"pipe",
|
|
1282
|
+
"pipe"
|
|
1283
|
+
]
|
|
1284
|
+
});
|
|
1285
|
+
child.stdout.on("data", (chunk) => output(chunk, "stdout"));
|
|
1286
|
+
child.stderr.on("data", (chunk) => output(chunk, "stderr"));
|
|
1287
|
+
const started = await new Promise((resolve) => {
|
|
1288
|
+
child.once("spawn", () => resolve(null));
|
|
1289
|
+
child.once("error", resolve);
|
|
1290
|
+
});
|
|
1291
|
+
if (started) return finish({
|
|
1292
|
+
routeId: run.routeId,
|
|
1293
|
+
state: "failed",
|
|
1294
|
+
message: `Could not start the runner: ${started.message}`
|
|
1295
|
+
});
|
|
1296
|
+
report({
|
|
1297
|
+
routeId: run.routeId,
|
|
1298
|
+
state: "started"
|
|
1299
|
+
});
|
|
1300
|
+
const [code, signal] = await new Promise((resolve) => child.once("close", (code, signal) => resolve([code, signal])));
|
|
1301
|
+
if (code === 0) return finish({
|
|
1302
|
+
routeId: run.routeId,
|
|
1303
|
+
state: "finished"
|
|
1304
|
+
});
|
|
1305
|
+
return finish({
|
|
1306
|
+
routeId: run.routeId,
|
|
1307
|
+
state: "failed",
|
|
1308
|
+
message: signal ? `run.sh was stopped by ${signal}` : `run.sh exited with ${code}`
|
|
1309
|
+
});
|
|
1310
|
+
} catch (error) {
|
|
1311
|
+
return finish({
|
|
1312
|
+
routeId: run.routeId,
|
|
1313
|
+
state: "failed",
|
|
1314
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1315
|
+
});
|
|
1316
|
+
} finally {
|
|
1317
|
+
clean(runner.dir);
|
|
1318
|
+
rmSync(lock, { force: true });
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
function clean(dir) {
|
|
1322
|
+
for (const name of JOB_STATE) rmSync(join(dir, name), {
|
|
1323
|
+
recursive: true,
|
|
1324
|
+
force: true
|
|
1325
|
+
});
|
|
1326
|
+
}
|
|
1327
|
+
function takeLock(lock) {
|
|
1328
|
+
for (let attempt = 0; attempt < 2; attempt++) try {
|
|
1329
|
+
symlinkSync(String(process.pid), lock);
|
|
1330
|
+
return true;
|
|
1331
|
+
} catch (error) {
|
|
1332
|
+
if (error.code !== "EEXIST") throw error;
|
|
1333
|
+
if (isAlive(Number(readlinkSync(lock)))) return false;
|
|
1334
|
+
rmSync(lock, { force: true });
|
|
1335
|
+
}
|
|
1336
|
+
return false;
|
|
1337
|
+
}
|
|
1338
|
+
function isAlive(pid) {
|
|
1339
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
1340
|
+
try {
|
|
1341
|
+
process.kill(pid, 0);
|
|
1342
|
+
return true;
|
|
1343
|
+
} catch (error) {
|
|
1344
|
+
return error.code === "EPERM";
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
// login.ts
|
|
1348
|
+
const CLIENT_ID = "relayrunner-cli";
|
|
1349
|
+
const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
1350
|
+
var LoginError = class extends Error {
|
|
1351
|
+
code;
|
|
1352
|
+
constructor(code, message) {
|
|
1353
|
+
super(message);
|
|
1354
|
+
this.code = code;
|
|
1355
|
+
}
|
|
1356
|
+
};
|
|
1357
|
+
const CodeResponse = z.object({
|
|
1358
|
+
device_code: z.string().min(1),
|
|
1359
|
+
user_code: z.string().min(1),
|
|
1360
|
+
verification_uri: z.string(),
|
|
1361
|
+
verification_uri_complete: z.string().optional(),
|
|
1362
|
+
expires_in: z.number().positive(),
|
|
1363
|
+
interval: z.number().positive().optional()
|
|
1364
|
+
});
|
|
1365
|
+
const TokenResponse = z.object({ access_token: z.string().min(1) });
|
|
1366
|
+
const OAuthError = z.object({
|
|
1367
|
+
error: z.string(),
|
|
1368
|
+
error_description: z.string().optional()
|
|
1369
|
+
});
|
|
1370
|
+
const ClaimResponse = z.object({
|
|
1371
|
+
machine: z.object({
|
|
1372
|
+
id: z.string().min(1),
|
|
1373
|
+
name: z.string()
|
|
1374
|
+
}),
|
|
1375
|
+
workspace: z.object({
|
|
1376
|
+
id: z.string().min(1),
|
|
1377
|
+
name: z.string(),
|
|
1378
|
+
slug: z.string().nullish(),
|
|
1379
|
+
memberCount: z.number().int().nonnegative().optional()
|
|
1380
|
+
}),
|
|
1381
|
+
token: z.string().min(1)
|
|
1382
|
+
});
|
|
1383
|
+
async function login(options) {
|
|
1384
|
+
const fetcher = options.fetcher ?? fetch;
|
|
1385
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1386
|
+
const now = options.now ?? Date.now;
|
|
1387
|
+
const api = (path) => new URL(path, options.server).toString();
|
|
1388
|
+
const post = (path, body, headers = {}) => fetcher(api(path), {
|
|
1389
|
+
method: "POST",
|
|
1390
|
+
headers: {
|
|
1391
|
+
"content-type": "application/json",
|
|
1392
|
+
"user-agent": userAgent,
|
|
1393
|
+
...headers
|
|
1394
|
+
},
|
|
1395
|
+
body: JSON.stringify(body)
|
|
1396
|
+
});
|
|
1397
|
+
const codeResponse = await post("/api/auth/device/code", { client_id: CLIENT_ID }).catch((error) => {
|
|
1398
|
+
const cause = error.cause?.message;
|
|
1399
|
+
throw new LoginError("UNREACHABLE", `Couldn't reach RelayRunner at ${options.server}${cause ? ` (${cause})` : ""}.`);
|
|
1400
|
+
});
|
|
1401
|
+
if (!codeResponse.ok) throw new LoginError("CODE_FAILED", `The gateway at ${options.server} wouldn't start a sign-in (HTTP ${codeResponse.status}).`);
|
|
1402
|
+
const code = CodeResponse.parse(await codeResponse.json());
|
|
1403
|
+
const url = new URL(code.verification_uri_complete ?? code.verification_uri);
|
|
1404
|
+
if (!url.searchParams.has("user_code")) url.searchParams.set("user_code", code.user_code);
|
|
1405
|
+
url.searchParams.set("name", options.name);
|
|
1406
|
+
const expiresAt = now() + code.expires_in * 1e3;
|
|
1407
|
+
await options.onCode({
|
|
1408
|
+
userCode: code.user_code,
|
|
1409
|
+
url: url.toString(),
|
|
1410
|
+
expiresAt
|
|
1411
|
+
});
|
|
1412
|
+
let interval = (code.interval ?? 5) * 1e3;
|
|
1413
|
+
let accessToken;
|
|
1414
|
+
while (!accessToken) {
|
|
1415
|
+
if (now() >= expiresAt) throw new LoginError("EXPIRED", "The sign-in code expired before it was approved.");
|
|
1416
|
+
await sleep(interval);
|
|
1417
|
+
let response;
|
|
1418
|
+
try {
|
|
1419
|
+
response = await post("/api/auth/device/token", {
|
|
1420
|
+
grant_type: DEVICE_GRANT,
|
|
1421
|
+
device_code: code.device_code,
|
|
1422
|
+
client_id: CLIENT_ID
|
|
1423
|
+
});
|
|
1424
|
+
} catch {
|
|
1425
|
+
continue;
|
|
1426
|
+
}
|
|
1427
|
+
const body = await response.json().catch(() => null);
|
|
1428
|
+
if (response.ok) {
|
|
1429
|
+
accessToken = TokenResponse.parse(body).access_token;
|
|
1430
|
+
break;
|
|
1431
|
+
}
|
|
1432
|
+
const error = OAuthError.safeParse(body);
|
|
1433
|
+
switch (error.success ? error.data.error : void 0) {
|
|
1434
|
+
case "authorization_pending": continue;
|
|
1435
|
+
case "slow_down":
|
|
1436
|
+
interval += 5e3;
|
|
1437
|
+
continue;
|
|
1438
|
+
case "access_denied": throw new LoginError("DENIED", "The sign-in was denied in the browser.");
|
|
1439
|
+
case "expired_token": throw new LoginError("EXPIRED", "The sign-in code expired before it was approved.");
|
|
1440
|
+
default:
|
|
1441
|
+
if (response.status >= 500) continue;
|
|
1442
|
+
throw new LoginError("TOKEN_FAILED", `Signing in failed: ${error.success ? error.data.error_description ?? error.data.error : `HTTP ${response.status}`}.`);
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
const claimResponse = await post("/api/machines/claim", {
|
|
1446
|
+
deviceCode: code.device_code,
|
|
1447
|
+
...options.platform
|
|
1448
|
+
}, { authorization: `Bearer ${accessToken}` });
|
|
1449
|
+
if (!claimResponse.ok) throw new LoginError("CLAIM_FAILED", `The gateway approved the sign-in but wouldn't enroll this machine (HTTP ${claimResponse.status}).`);
|
|
1450
|
+
const claimed = ClaimResponse.parse(await claimResponse.json());
|
|
1451
|
+
const { memberCount, ...workspace } = claimed.workspace;
|
|
1452
|
+
return {
|
|
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
|
|
1461
|
+
},
|
|
1462
|
+
memberCount: memberCount ?? null
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
function openBrowser(url) {
|
|
1466
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", [
|
|
1467
|
+
"/c",
|
|
1468
|
+
"start",
|
|
1469
|
+
"",
|
|
1470
|
+
url
|
|
1471
|
+
]] : ["xdg-open", [url]];
|
|
1472
|
+
try {
|
|
1473
|
+
const child = spawn(command, args, {
|
|
1474
|
+
stdio: "ignore",
|
|
1475
|
+
detached: true
|
|
1476
|
+
});
|
|
1477
|
+
child.on("error", () => {});
|
|
1478
|
+
child.unref();
|
|
1479
|
+
} catch {}
|
|
1480
|
+
}
|
|
1481
|
+
// pause.ts
|
|
1482
|
+
const PauseResponse = z.object({ machine: z.object({
|
|
1483
|
+
name: z.string(),
|
|
1484
|
+
paused: z.object({ by: z.string().nullable() }).nullable(),
|
|
1485
|
+
status: z.object({ state: z.string().nullable() }).optional()
|
|
1486
|
+
}) });
|
|
1487
|
+
async function setPaused(options) {
|
|
1488
|
+
const fetcher = options.fetcher ?? fetch;
|
|
1489
|
+
const action = options.paused ? "pause" : "resume";
|
|
1490
|
+
let response;
|
|
1491
|
+
try {
|
|
1492
|
+
response = await fetcher(new URL(`/api/machines/me/${action}`, options.server), {
|
|
1493
|
+
method: "POST",
|
|
1494
|
+
headers: {
|
|
1495
|
+
authorization: `Bearer ${options.token}`,
|
|
1496
|
+
"user-agent": userAgent
|
|
1497
|
+
}
|
|
1498
|
+
});
|
|
1499
|
+
} catch (error) {
|
|
1500
|
+
const cause = error.cause?.message;
|
|
1501
|
+
return {
|
|
1502
|
+
status: "failed",
|
|
1503
|
+
reason: `couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
1504
|
+
};
|
|
1505
|
+
}
|
|
1506
|
+
if (response.status === 401) return { status: "revoked" };
|
|
1507
|
+
if (!response.ok) return {
|
|
1508
|
+
status: "failed",
|
|
1509
|
+
reason: `${options.server} answered HTTP ${response.status}`
|
|
1510
|
+
};
|
|
1511
|
+
const parsed = PauseResponse.safeParse(await response.json().catch(() => null));
|
|
1512
|
+
if (!parsed.success) return {
|
|
1513
|
+
status: "failed",
|
|
1514
|
+
reason: `${options.server} sent an unexpected response`
|
|
1515
|
+
};
|
|
1516
|
+
return {
|
|
1517
|
+
status: "ok",
|
|
1518
|
+
paused: parsed.data.machine.paused !== null,
|
|
1519
|
+
busy: parsed.data.machine.status?.state === "busy"
|
|
1520
|
+
};
|
|
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
|
+
}
|
|
1576
|
+
// whoami.ts
|
|
1577
|
+
const WhoamiResponse = z.object({
|
|
1578
|
+
machine: z.object({
|
|
1579
|
+
id: z.string().min(1),
|
|
1580
|
+
name: z.string(),
|
|
1581
|
+
os: z.string().nullable(),
|
|
1582
|
+
arch: z.string().nullable(),
|
|
1583
|
+
createdAt: z.union([z.string(), z.number()]),
|
|
1584
|
+
lastSeenAt: z.union([z.string(), z.number()]).nullable(),
|
|
1585
|
+
status: z.object({
|
|
1586
|
+
online: z.boolean(),
|
|
1587
|
+
state: z.string().nullable()
|
|
1588
|
+
}),
|
|
1589
|
+
paused: z.object({ by: z.string().nullable() }).nullish(),
|
|
1590
|
+
sharing: z.enum(["only_me", "anyone"]).optional()
|
|
1591
|
+
}),
|
|
1592
|
+
workspace: z.object({
|
|
1593
|
+
id: z.string().min(1),
|
|
1594
|
+
name: z.string(),
|
|
1595
|
+
slug: z.string().nullish(),
|
|
1596
|
+
memberCount: z.number().int().nonnegative().optional()
|
|
1597
|
+
}),
|
|
1598
|
+
enrolledBy: z.object({
|
|
1599
|
+
name: z.string(),
|
|
1600
|
+
email: z.string()
|
|
1601
|
+
}).nullable()
|
|
1602
|
+
});
|
|
1603
|
+
async function whoami(options) {
|
|
1604
|
+
const fetcher = options.fetcher ?? fetch;
|
|
1605
|
+
let response;
|
|
1606
|
+
try {
|
|
1607
|
+
response = await fetcher(new URL("/api/machines/me", options.server), { headers: {
|
|
1608
|
+
authorization: `Bearer ${options.token}`,
|
|
1609
|
+
"user-agent": userAgent
|
|
1610
|
+
} });
|
|
1611
|
+
} catch (error) {
|
|
1612
|
+
const cause = error.cause?.message;
|
|
1613
|
+
return {
|
|
1614
|
+
status: "unverified",
|
|
1615
|
+
reason: `Couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
if (response.status === 401) return { status: "revoked" };
|
|
1619
|
+
if (!response.ok) return {
|
|
1620
|
+
status: "unverified",
|
|
1621
|
+
reason: `${options.server} answered HTTP ${response.status}`
|
|
1622
|
+
};
|
|
1623
|
+
const parsed = WhoamiResponse.safeParse(await response.json().catch(() => null));
|
|
1624
|
+
if (!parsed.success) return {
|
|
1625
|
+
status: "unverified",
|
|
1626
|
+
reason: `${options.server} sent an unexpected response`
|
|
1627
|
+
};
|
|
1628
|
+
return {
|
|
1629
|
+
status: "ok",
|
|
1630
|
+
identity: parsed.data
|
|
1631
|
+
};
|
|
1632
|
+
}
|
|
1633
|
+
// cli.ts
|
|
1634
|
+
const DEFAULT_SERVER = "https://app.relayrunner.app";
|
|
1635
|
+
const connectCommand = defineCommand({
|
|
1636
|
+
meta: {
|
|
1637
|
+
name: "connect",
|
|
1638
|
+
description: "Put this machine online for your workspace and run the jobs the gateway sends it. Signs in on first run; Ctrl-C takes the machine offline."
|
|
1639
|
+
},
|
|
1640
|
+
args: {
|
|
1641
|
+
server: {
|
|
1642
|
+
type: "string",
|
|
1643
|
+
description: `RelayRunner URL (default: $RELAYRUNNER_URL or ${DEFAULT_SERVER})`
|
|
1644
|
+
},
|
|
1645
|
+
name: {
|
|
1646
|
+
type: "string",
|
|
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."
|
|
1652
|
+
}
|
|
1653
|
+
},
|
|
1654
|
+
async run({ args }) {
|
|
1655
|
+
clack.intro("RelayRunner");
|
|
1656
|
+
try {
|
|
1657
|
+
await connectMachine(args);
|
|
1658
|
+
} catch (error) {
|
|
1659
|
+
if (!(error instanceof LoginError || error instanceof RunnerError)) throw error;
|
|
1660
|
+
clack.log.error(error.message);
|
|
1661
|
+
process.exitCode = 1;
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
});
|
|
1665
|
+
async function connectMachine(args) {
|
|
1666
|
+
const share = shareArg(args.share);
|
|
1667
|
+
const platform = machinePlatform();
|
|
1668
|
+
let credentials = readCredentials();
|
|
1669
|
+
const server = serverFor(args.server, credentials);
|
|
1670
|
+
if (credentials && credentials.server !== server) {
|
|
1671
|
+
clack.log.warn(`This machine is enrolled with ${credentials.server}, not ${server}. Signing in again.`);
|
|
1672
|
+
credentials = null;
|
|
1673
|
+
}
|
|
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();
|
|
1680
|
+
const runner = await ensureRunner({ log: (line) => clack.log.info(line) });
|
|
1681
|
+
const device = await detectDevice();
|
|
1682
|
+
const stop = new AbortController();
|
|
1683
|
+
const onInterrupt = () => {
|
|
1684
|
+
if (stop.signal.aborted) process.exit(130);
|
|
1685
|
+
stop.abort();
|
|
1686
|
+
};
|
|
1687
|
+
process.on("SIGINT", onInterrupt);
|
|
1688
|
+
let online = false;
|
|
1689
|
+
const end = await connect({
|
|
1690
|
+
server: credentials.server,
|
|
1691
|
+
token: credentials.token,
|
|
1692
|
+
hello: {
|
|
1693
|
+
machineId: credentials.machine.id,
|
|
1694
|
+
...platform,
|
|
1695
|
+
runnerVersion: runner.version,
|
|
1696
|
+
device
|
|
1697
|
+
},
|
|
1698
|
+
runJob: (run, report) => runJob(run, {
|
|
1699
|
+
runner,
|
|
1700
|
+
report
|
|
1701
|
+
}),
|
|
1702
|
+
onEvent: (event) => {
|
|
1703
|
+
if (event.type === "connected") online = true;
|
|
1704
|
+
show(event);
|
|
1705
|
+
},
|
|
1706
|
+
signal: stop.signal
|
|
1707
|
+
});
|
|
1708
|
+
process.off("SIGINT", onInterrupt);
|
|
1709
|
+
switch (end.reason) {
|
|
1710
|
+
case "stopped":
|
|
1711
|
+
clack.outro("Offline.");
|
|
1712
|
+
break;
|
|
1713
|
+
case "revoked":
|
|
1714
|
+
deleteCredentials();
|
|
1715
|
+
if (!online) {
|
|
1716
|
+
clack.log.warn("This machine was removed from the workspace or its token is no longer valid. Signing in again.");
|
|
1717
|
+
return connectMachine({
|
|
1718
|
+
...args,
|
|
1719
|
+
server: credentials.server
|
|
1720
|
+
});
|
|
1721
|
+
}
|
|
1722
|
+
clack.log.error("This machine was removed from the workspace or its token is no longer valid.");
|
|
1723
|
+
clack.outro("Run `relayrunner connect` again to sign in.");
|
|
1724
|
+
process.exitCode = 1;
|
|
1725
|
+
break;
|
|
1726
|
+
case "replaced":
|
|
1727
|
+
clack.log.warn("Another `relayrunner connect` for this machine took over.");
|
|
1728
|
+
clack.outro("Offline here.");
|
|
1729
|
+
process.exitCode = 1;
|
|
1730
|
+
break;
|
|
1731
|
+
case "rejected":
|
|
1732
|
+
clack.log.error(`The gateway rejected this CLI: ${end.message}`);
|
|
1733
|
+
clack.outro("Update it with `npx relayrunner@latest connect`.");
|
|
1734
|
+
process.exitCode = 1;
|
|
1735
|
+
}
|
|
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
|
+
}
|
|
1846
|
+
async function signIn(server, name, platform) {
|
|
1847
|
+
const waiting = clack.spinner();
|
|
1848
|
+
try {
|
|
1849
|
+
const credentials = await login({
|
|
1850
|
+
server,
|
|
1851
|
+
name,
|
|
1852
|
+
platform,
|
|
1853
|
+
onCode: ({ userCode, url }) => {
|
|
1854
|
+
clack.note(`${url}\n\nConfirm the code ${userCode} matches the one in your browser.`, "Sign in");
|
|
1855
|
+
openBrowser(url);
|
|
1856
|
+
waiting.start("Waiting for approval in the browser");
|
|
1857
|
+
}
|
|
1858
|
+
});
|
|
1859
|
+
waiting.stop("Approved");
|
|
1860
|
+
return credentials;
|
|
1861
|
+
} catch (error) {
|
|
1862
|
+
waiting.error("Sign-in failed");
|
|
1863
|
+
throw error;
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
function show(event) {
|
|
1867
|
+
const at = (/* @__PURE__ */ new Date()).toLocaleTimeString();
|
|
1868
|
+
switch (event.type) {
|
|
1869
|
+
case "connecting":
|
|
1870
|
+
if (event.attempt === 1) clack.log.step(`${at} Connecting…`);
|
|
1871
|
+
break;
|
|
1872
|
+
case "connected":
|
|
1873
|
+
clack.log.success(`${at} Online. Waiting for jobs.`);
|
|
1874
|
+
break;
|
|
1875
|
+
case "disconnected":
|
|
1876
|
+
clack.log.warn(`${at} Disconnected (${event.code}${event.reason ? ` ${event.reason}` : ""}). Retrying in ${Math.ceil(event.retryInMs / 1e3)}s.`);
|
|
1877
|
+
break;
|
|
1878
|
+
case "gateway-error":
|
|
1879
|
+
clack.log.error(`${at} Gateway: ${event.message}`);
|
|
1880
|
+
break;
|
|
1881
|
+
case "run":
|
|
1882
|
+
clack.log.step(`${at} Starting job ${event.routeId}`);
|
|
1883
|
+
break;
|
|
1884
|
+
case "paused":
|
|
1885
|
+
if (event.paused) clack.log.warn(`${at} Paused${event.by ? ` by ${event.by}` : ""}. Staying online, but new jobs skip this machine until it's resumed.`);
|
|
1886
|
+
else clack.log.success(`${at} Resumed${event.by ? ` by ${event.by}` : ""}. Waiting for jobs.`);
|
|
1887
|
+
break;
|
|
1888
|
+
case "run-refused":
|
|
1889
|
+
clack.log.warn(`${at} Turned down job ${event.routeId}: already running one.`);
|
|
1890
|
+
break;
|
|
1891
|
+
case "job": {
|
|
1892
|
+
const { routeId, state, message } = event.update;
|
|
1893
|
+
const line = `${at} Job ${routeId} ${state}${message ? `: ${message}` : ""}`;
|
|
1894
|
+
if (state === "failed") clack.log.error(line);
|
|
1895
|
+
else if (state === "finished") clack.log.success(line);
|
|
1896
|
+
else clack.log.info(line);
|
|
1897
|
+
break;
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
const whoamiCommand = defineCommand({
|
|
1902
|
+
meta: {
|
|
1903
|
+
name: "whoami",
|
|
1904
|
+
description: "Show which machine and workspace this computer is signed in as, checked with the gateway."
|
|
1905
|
+
},
|
|
1906
|
+
args: {
|
|
1907
|
+
server: {
|
|
1908
|
+
type: "string",
|
|
1909
|
+
description: "Only report a sign-in for this RelayRunner URL (default: the saved one)"
|
|
1910
|
+
},
|
|
1911
|
+
json: {
|
|
1912
|
+
type: "boolean",
|
|
1913
|
+
description: "Print the result as JSON"
|
|
1914
|
+
}
|
|
1915
|
+
},
|
|
1916
|
+
async run({ args }) {
|
|
1917
|
+
const print = (human, json) => console.log(args.json ? JSON.stringify(json, null, 2) : human);
|
|
1918
|
+
const credentials = readCredentials();
|
|
1919
|
+
const requested = args.server || process.env.RELAYRUNNER_URL;
|
|
1920
|
+
const server = requested ? normalizeServer(requested) : credentials?.server;
|
|
1921
|
+
if (!credentials || credentials.server !== server) {
|
|
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.", {
|
|
1923
|
+
status: "signed_out",
|
|
1924
|
+
server: server ?? null
|
|
1925
|
+
});
|
|
1926
|
+
process.exitCode = 1;
|
|
1927
|
+
return;
|
|
1928
|
+
}
|
|
1929
|
+
const saved = {
|
|
1930
|
+
server: credentials.server,
|
|
1931
|
+
machine: credentials.machine,
|
|
1932
|
+
workspace: credentials.workspace
|
|
1933
|
+
};
|
|
1934
|
+
const result = await whoami({
|
|
1935
|
+
server: credentials.server,
|
|
1936
|
+
token: credentials.token
|
|
1937
|
+
});
|
|
1938
|
+
switch (result.status) {
|
|
1939
|
+
case "ok":
|
|
1940
|
+
print(describeIdentity(credentials.server, result.identity), {
|
|
1941
|
+
status: "ok",
|
|
1942
|
+
server: credentials.server,
|
|
1943
|
+
...result.identity
|
|
1944
|
+
});
|
|
1945
|
+
break;
|
|
1946
|
+
case "revoked":
|
|
1947
|
+
print(`${credentials.machine.name} was removed from ${credentials.workspace.name} or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`, {
|
|
1948
|
+
status: "revoked",
|
|
1949
|
+
...saved
|
|
1950
|
+
});
|
|
1951
|
+
process.exitCode = 1;
|
|
1952
|
+
break;
|
|
1953
|
+
case "unverified": print(`${describeSaved(saved)}\n\nUnverified: ${result.reason}. This is what's saved in ${credentialsPath()}.`, {
|
|
1954
|
+
status: "unverified",
|
|
1955
|
+
reason: result.reason,
|
|
1956
|
+
...saved
|
|
1957
|
+
});
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
});
|
|
1961
|
+
function describeIdentity(server, identity) {
|
|
1962
|
+
const { machine, workspace, enrolledBy } = identity;
|
|
1963
|
+
const status = (machine.status.online ? `online${machine.status.state ? `, ${machine.status.state}` : ""}` : "offline") + (machine.paused ? `, paused${machine.paused.by ? ` by ${machine.paused.by}` : ""}` : "");
|
|
1964
|
+
const enrolled = [enrolledBy && `by ${enrolledBy.name} <${enrolledBy.email}>`, `on ${new Date(machine.createdAt).toLocaleDateString()}`].filter(Boolean).join(" ");
|
|
1965
|
+
return table(`${machine.name} (${machine.id})`, [
|
|
1966
|
+
["Workspace", workspace.slug ? `${workspace.name} (${workspace.slug})` : workspace.name],
|
|
1967
|
+
["Platform", [machine.os, machine.arch].filter(Boolean).join(" ") || "unknown"],
|
|
1968
|
+
["Enrolled", enrolled],
|
|
1969
|
+
["Status", status],
|
|
1970
|
+
...machine.sharing ? [["Sharing", describeSharing(machine.sharing, workspace.name)]] : [],
|
|
1971
|
+
["Gateway", server]
|
|
1972
|
+
]);
|
|
1973
|
+
}
|
|
1974
|
+
function describeSaved(saved) {
|
|
1975
|
+
return table(`${saved.machine.name} (${saved.machine.id})`, [["Workspace", saved.workspace.name], ["Gateway", saved.server]]);
|
|
1976
|
+
}
|
|
1977
|
+
function table(title, rows) {
|
|
1978
|
+
const width = Math.max(...rows.map(([label]) => label.length));
|
|
1979
|
+
return [title, ...rows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`)].join("\n");
|
|
1980
|
+
}
|
|
1981
|
+
function normalizeServer(value) {
|
|
1982
|
+
try {
|
|
1983
|
+
const url = new URL(value);
|
|
1984
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error();
|
|
1985
|
+
return url.origin;
|
|
1986
|
+
} catch {
|
|
1987
|
+
throw new RunnerError("USAGE", `Not a valid RelayRunner URL: ${value}`);
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
function pauseCommand(paused) {
|
|
1991
|
+
return defineCommand({
|
|
1992
|
+
meta: {
|
|
1993
|
+
name: paused ? "pause" : "resume",
|
|
1994
|
+
description: paused ? "Stop new jobs routing to this machine. It stays connected and finishes a job it's running." : "Let jobs route to this machine again after `relayrunner pause`."
|
|
1995
|
+
},
|
|
1996
|
+
async run() {
|
|
1997
|
+
const credentials = readCredentials();
|
|
1998
|
+
if (!credentials) {
|
|
1999
|
+
console.error("Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.");
|
|
2000
|
+
process.exitCode = 1;
|
|
2001
|
+
return;
|
|
2002
|
+
}
|
|
2003
|
+
const result = await setPaused({
|
|
2004
|
+
server: credentials.server,
|
|
2005
|
+
token: credentials.token,
|
|
2006
|
+
paused
|
|
2007
|
+
});
|
|
2008
|
+
const name = credentials.machine.name;
|
|
2009
|
+
switch (result.status) {
|
|
2010
|
+
case "ok":
|
|
2011
|
+
console.log(paused ? `Paused ${name}. It stays connected, and new jobs will skip it.${result.busy ? "\nIt finishes the job it's running first." : ""}\nRun \`relayrunner resume\` to take jobs again.` : `Resumed ${name}. Jobs can route here again.`);
|
|
2012
|
+
break;
|
|
2013
|
+
case "revoked":
|
|
2014
|
+
console.error(`${name} was removed from ${credentials.workspace.name} or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`);
|
|
2015
|
+
process.exitCode = 1;
|
|
2016
|
+
break;
|
|
2017
|
+
case "failed":
|
|
2018
|
+
console.error(`Couldn't ${paused ? "pause" : "resume"} ${name}: ${result.reason}.`);
|
|
2019
|
+
process.exitCode = 1;
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
});
|
|
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
|
+
});
|
|
2091
|
+
const main = defineCommand({
|
|
2092
|
+
meta: {
|
|
2093
|
+
name: "relayrunner",
|
|
2094
|
+
description: "Run GitHub Actions jobs on your machine through the RelayRunner gateway."
|
|
2095
|
+
},
|
|
2096
|
+
subCommands: {
|
|
2097
|
+
connect: connectCommand,
|
|
2098
|
+
login: loginCommand,
|
|
2099
|
+
whoami: whoamiCommand,
|
|
2100
|
+
init: initCommand,
|
|
2101
|
+
pause: pauseCommand(true),
|
|
2102
|
+
resume: pauseCommand(false),
|
|
2103
|
+
share: shareCommand
|
|
2104
|
+
}
|
|
2105
|
+
});
|
|
2106
|
+
runMain(main);
|
|
2107
|
+
export {};
|