relayrunner 0.1.1 → 0.2.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 +47 -31
- package/dist/cli.js +1110 -126
- package/package.json +13 -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,1112 @@
|
|
|
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
|
-
if (routing) {
|
|
30
|
-
const routeMode = command === 'status' && positionals.length === 1 ? 'status'
|
|
31
|
-
: command === 'switch' && positionals.length === 2 && (mode === 'local' || mode === 'hosted') ? mode : null;
|
|
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, homedir, hostname, platform } from "node:os";
|
|
3
|
+
import * as clack from "@clack/prompts";
|
|
4
|
+
import { defineCommand, runMain } from "citty";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { join, resolve } from "node:path";
|
|
7
|
+
import { chmodSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { Readable, Transform } from "node:stream";
|
|
11
|
+
import { pipeline } from "node:stream/promises";
|
|
12
|
+
const version = z.literal(1);
|
|
13
|
+
const routeId = z.string().min(1);
|
|
14
|
+
const HelloMessage = z.object({
|
|
15
|
+
v: version,
|
|
16
|
+
type: z.literal("hello"),
|
|
17
|
+
machineId: z.string().min(1),
|
|
18
|
+
os: z.enum([
|
|
19
|
+
"linux",
|
|
20
|
+
"macos",
|
|
21
|
+
"windows"
|
|
22
|
+
]),
|
|
23
|
+
arch: z.enum([
|
|
24
|
+
"x64",
|
|
25
|
+
"arm64",
|
|
26
|
+
"arm"
|
|
27
|
+
]),
|
|
28
|
+
runnerVersion: z.string().min(1)
|
|
128
29
|
});
|
|
30
|
+
const StatusMessage = z.object({
|
|
31
|
+
v: version,
|
|
32
|
+
type: z.literal("status"),
|
|
33
|
+
state: z.enum(["idle", "busy"])
|
|
34
|
+
});
|
|
35
|
+
const JobMessage = z.object({
|
|
36
|
+
v: version,
|
|
37
|
+
type: z.literal("job"),
|
|
38
|
+
routeId,
|
|
39
|
+
state: z.enum([
|
|
40
|
+
"started",
|
|
41
|
+
"finished",
|
|
42
|
+
"failed"
|
|
43
|
+
]),
|
|
44
|
+
message: z.string().optional()
|
|
45
|
+
});
|
|
46
|
+
z.discriminatedUnion("type", [
|
|
47
|
+
HelloMessage,
|
|
48
|
+
StatusMessage,
|
|
49
|
+
JobMessage
|
|
50
|
+
]);
|
|
51
|
+
const RunMessage = z.object({
|
|
52
|
+
v: version,
|
|
53
|
+
type: z.literal("run"),
|
|
54
|
+
routeId,
|
|
55
|
+
jitConfig: z.string().min(1)
|
|
56
|
+
});
|
|
57
|
+
const ErrorMessage = z.object({
|
|
58
|
+
v: version,
|
|
59
|
+
type: z.literal("error"),
|
|
60
|
+
code: z.enum(["version_mismatch", "invalid_message"]),
|
|
61
|
+
message: z.string()
|
|
62
|
+
});
|
|
63
|
+
const PausedMessage = z.object({
|
|
64
|
+
v: version,
|
|
65
|
+
type: z.literal("paused"),
|
|
66
|
+
paused: z.boolean(),
|
|
67
|
+
by: z.string().nullable()
|
|
68
|
+
});
|
|
69
|
+
const GatewayMessage = z.discriminatedUnion("type", [
|
|
70
|
+
RunMessage,
|
|
71
|
+
ErrorMessage,
|
|
72
|
+
PausedMessage
|
|
73
|
+
]);
|
|
74
|
+
function parseGatewayMessage(frame) {
|
|
75
|
+
return parse(GatewayMessage, frame);
|
|
76
|
+
}
|
|
77
|
+
function encodeMessage(message) {
|
|
78
|
+
return JSON.stringify(message);
|
|
79
|
+
}
|
|
80
|
+
function parse(schema, frame) {
|
|
81
|
+
let data;
|
|
82
|
+
try {
|
|
83
|
+
data = JSON.parse(frame);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
return {
|
|
86
|
+
ok: false,
|
|
87
|
+
reason: "invalid_json",
|
|
88
|
+
error: String(error)
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const v = typeof data === "object" && data !== null ? data.v : void 0;
|
|
92
|
+
if (v !== 1) return {
|
|
93
|
+
ok: false,
|
|
94
|
+
reason: "version_mismatch",
|
|
95
|
+
error: `expected protocol version 1, got ${JSON.stringify(v) ?? "none"}`
|
|
96
|
+
};
|
|
97
|
+
const result = schema.safeParse(data);
|
|
98
|
+
if (!result.success) return {
|
|
99
|
+
ok: false,
|
|
100
|
+
reason: "invalid_message",
|
|
101
|
+
error: z.prettifyError(result.error)
|
|
102
|
+
};
|
|
103
|
+
return {
|
|
104
|
+
ok: true,
|
|
105
|
+
message: result.data
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
// paths.ts
|
|
109
|
+
function relayrunnerHome() {
|
|
110
|
+
return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), ".relayrunner"));
|
|
111
|
+
}
|
|
112
|
+
function runnersDir() {
|
|
113
|
+
return join(relayrunnerHome(), "runner");
|
|
114
|
+
}
|
|
115
|
+
const userAgent = "relayrunner-cli";
|
|
116
|
+
const CLOSE_POLICY = 1008;
|
|
117
|
+
const NodeWebSocket = WebSocket;
|
|
118
|
+
function connectUrl(server) {
|
|
119
|
+
const url = new URL("/api/machines/connect", server);
|
|
120
|
+
url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
|
|
121
|
+
return url.toString();
|
|
122
|
+
}
|
|
123
|
+
function backoff(attempt, min, max, random = Math.random) {
|
|
124
|
+
const base = Math.min(max, min * 2 ** Math.max(0, attempt - 1));
|
|
125
|
+
return Math.round(base * (.75 + random() * .5));
|
|
126
|
+
}
|
|
127
|
+
async function connect(options) {
|
|
128
|
+
const heartbeatMs = options.heartbeatMs ?? 3e4;
|
|
129
|
+
const minBackoffMs = options.minBackoffMs ?? 1e3;
|
|
130
|
+
const maxBackoffMs = options.maxBackoffMs ?? 3e4;
|
|
131
|
+
const emit = options.onEvent ?? (() => {});
|
|
132
|
+
const signal = options.signal;
|
|
133
|
+
let state = "idle";
|
|
134
|
+
let socket = null;
|
|
135
|
+
const pending = [];
|
|
136
|
+
let gatewayError = "";
|
|
137
|
+
const send = (message) => {
|
|
138
|
+
if (socket?.readyState === WebSocket.OPEN) socket.send(encodeMessage(message));
|
|
139
|
+
else if (message.type === "job") pending.push(message);
|
|
140
|
+
};
|
|
141
|
+
const sendStatus = () => send({
|
|
142
|
+
v: 1,
|
|
143
|
+
type: "status",
|
|
144
|
+
state
|
|
145
|
+
});
|
|
146
|
+
const startJob = (run) => {
|
|
147
|
+
if (state === "busy") {
|
|
148
|
+
emit({
|
|
149
|
+
type: "run-refused",
|
|
150
|
+
routeId: run.routeId
|
|
151
|
+
});
|
|
152
|
+
const update = {
|
|
153
|
+
routeId: run.routeId,
|
|
154
|
+
state: "failed",
|
|
155
|
+
message: "The machine is already running a job."
|
|
156
|
+
};
|
|
157
|
+
send({
|
|
158
|
+
v: 1,
|
|
159
|
+
type: "job",
|
|
160
|
+
...update
|
|
161
|
+
});
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
emit({
|
|
165
|
+
type: "run",
|
|
166
|
+
routeId: run.routeId
|
|
167
|
+
});
|
|
168
|
+
state = "busy";
|
|
169
|
+
sendStatus();
|
|
170
|
+
options.runJob(run, (update) => {
|
|
171
|
+
emit({
|
|
172
|
+
type: "job",
|
|
173
|
+
update
|
|
174
|
+
});
|
|
175
|
+
send({
|
|
176
|
+
v: 1,
|
|
177
|
+
type: "job",
|
|
178
|
+
...update
|
|
179
|
+
});
|
|
180
|
+
}).finally(() => {
|
|
181
|
+
state = "idle";
|
|
182
|
+
sendStatus();
|
|
183
|
+
});
|
|
184
|
+
};
|
|
185
|
+
const session = () => new Promise((resolve) => {
|
|
186
|
+
let opened = false;
|
|
187
|
+
let heartbeat;
|
|
188
|
+
const ws = new NodeWebSocket(connectUrl(options.server), { headers: {
|
|
189
|
+
authorization: `Bearer ${options.token}`,
|
|
190
|
+
"user-agent": userAgent
|
|
191
|
+
} });
|
|
192
|
+
socket = ws;
|
|
193
|
+
let settled = false;
|
|
194
|
+
const finish = (code, reason) => {
|
|
195
|
+
if (settled) return;
|
|
196
|
+
settled = true;
|
|
197
|
+
clearInterval(heartbeat);
|
|
198
|
+
signal?.removeEventListener("abort", onAbort);
|
|
199
|
+
if (socket === ws) socket = null;
|
|
200
|
+
resolve({
|
|
201
|
+
opened,
|
|
202
|
+
code,
|
|
203
|
+
reason
|
|
204
|
+
});
|
|
205
|
+
};
|
|
206
|
+
const onAbort = () => {
|
|
207
|
+
ws.close(1e3, "machine going offline");
|
|
208
|
+
finish(1e3, "machine going offline");
|
|
209
|
+
};
|
|
210
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
211
|
+
ws.addEventListener("open", () => {
|
|
212
|
+
opened = true;
|
|
213
|
+
emit({ type: "connected" });
|
|
214
|
+
ws.send(encodeMessage({
|
|
215
|
+
v: 1,
|
|
216
|
+
type: "hello",
|
|
217
|
+
...options.hello
|
|
218
|
+
}));
|
|
219
|
+
sendStatus();
|
|
220
|
+
for (const message of pending.splice(0)) send(message);
|
|
221
|
+
heartbeat = setInterval(sendStatus, heartbeatMs);
|
|
222
|
+
});
|
|
223
|
+
ws.addEventListener("message", (event) => {
|
|
224
|
+
if (typeof event.data !== "string") return;
|
|
225
|
+
const parsed = parseGatewayMessage(event.data);
|
|
226
|
+
if (!parsed.ok) {
|
|
227
|
+
emit({
|
|
228
|
+
type: "gateway-error",
|
|
229
|
+
code: parsed.reason,
|
|
230
|
+
message: parsed.error
|
|
231
|
+
});
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
const message = parsed.message;
|
|
235
|
+
if (message.type === "run") startJob(message);
|
|
236
|
+
else if (message.type === "paused") emit({
|
|
237
|
+
type: "paused",
|
|
238
|
+
paused: message.paused,
|
|
239
|
+
by: message.by
|
|
240
|
+
});
|
|
241
|
+
else {
|
|
242
|
+
gatewayError = message.message;
|
|
243
|
+
emit({
|
|
244
|
+
type: "gateway-error",
|
|
245
|
+
code: message.code,
|
|
246
|
+
message: message.message
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
ws.addEventListener("close", (event) => finish(event.code, event.reason));
|
|
251
|
+
ws.addEventListener("error", () => {
|
|
252
|
+
if (!opened) finish(1006, "");
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
const tokenRejected = () => fetch(new URL("/api/machines/connect", options.server), {
|
|
256
|
+
headers: {
|
|
257
|
+
authorization: `Bearer ${options.token}`,
|
|
258
|
+
"user-agent": userAgent
|
|
259
|
+
},
|
|
260
|
+
signal: AbortSignal.timeout(1e4)
|
|
261
|
+
}).then(async (response) => {
|
|
262
|
+
await response.body?.cancel();
|
|
263
|
+
return response.status === 401;
|
|
264
|
+
}, () => false);
|
|
265
|
+
let attempt = 0;
|
|
266
|
+
while (!signal?.aborted) {
|
|
267
|
+
attempt++;
|
|
268
|
+
emit({
|
|
269
|
+
type: "connecting",
|
|
270
|
+
attempt
|
|
271
|
+
});
|
|
272
|
+
const { opened, code, reason } = await session();
|
|
273
|
+
if (signal?.aborted) break;
|
|
274
|
+
if (opened) attempt = 1;
|
|
275
|
+
if (code === 4001) return { reason: "revoked" };
|
|
276
|
+
if (code === 4002) return { reason: "replaced" };
|
|
277
|
+
if (code === CLOSE_POLICY) return {
|
|
278
|
+
reason: "rejected",
|
|
279
|
+
message: gatewayError || reason || "protocol error"
|
|
280
|
+
};
|
|
281
|
+
if (!opened && await tokenRejected()) return { reason: "revoked" };
|
|
282
|
+
const retryInMs = backoff(attempt, minBackoffMs, maxBackoffMs);
|
|
283
|
+
emit({
|
|
284
|
+
type: "disconnected",
|
|
285
|
+
code,
|
|
286
|
+
reason,
|
|
287
|
+
retryInMs
|
|
288
|
+
});
|
|
289
|
+
await delay(retryInMs, signal);
|
|
290
|
+
}
|
|
291
|
+
return { reason: "stopped" };
|
|
292
|
+
}
|
|
293
|
+
function delay(ms, signal) {
|
|
294
|
+
return new Promise((resolve) => {
|
|
295
|
+
const timer = setTimeout(done, ms);
|
|
296
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
297
|
+
function done() {
|
|
298
|
+
clearTimeout(timer);
|
|
299
|
+
signal?.removeEventListener("abort", done);
|
|
300
|
+
resolve();
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
// credentials.ts
|
|
305
|
+
const Credentials = z.object({
|
|
306
|
+
server: z.url(),
|
|
307
|
+
machine: z.object({
|
|
308
|
+
id: z.string().min(1),
|
|
309
|
+
name: z.string()
|
|
310
|
+
}),
|
|
311
|
+
workspace: z.object({
|
|
312
|
+
id: z.string().min(1),
|
|
313
|
+
name: z.string(),
|
|
314
|
+
slug: z.string().nullish()
|
|
315
|
+
}),
|
|
316
|
+
token: z.string().min(1)
|
|
317
|
+
});
|
|
318
|
+
function credentialsPath(home = relayrunnerHome()) {
|
|
319
|
+
return join(home, "machine.json");
|
|
320
|
+
}
|
|
321
|
+
function readCredentials(path = credentialsPath()) {
|
|
322
|
+
let text;
|
|
323
|
+
try {
|
|
324
|
+
text = readFileSync(path, "utf8");
|
|
325
|
+
} catch (error) {
|
|
326
|
+
if (error.code === "ENOENT") return null;
|
|
327
|
+
throw error;
|
|
328
|
+
}
|
|
329
|
+
try {
|
|
330
|
+
const parsed = Credentials.safeParse(JSON.parse(text));
|
|
331
|
+
return parsed.success ? parsed.data : null;
|
|
332
|
+
} catch {
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
function writeCredentials(credentials, path = credentialsPath()) {
|
|
337
|
+
const dir = join(path, "..");
|
|
338
|
+
mkdirSync(dir, {
|
|
339
|
+
recursive: true,
|
|
340
|
+
mode: 448
|
|
341
|
+
});
|
|
342
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
343
|
+
writeFileSync(temp, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 384 });
|
|
344
|
+
chmodSync(temp, 384);
|
|
345
|
+
renameSync(temp, path);
|
|
346
|
+
}
|
|
347
|
+
function deleteCredentials(path = credentialsPath()) {
|
|
348
|
+
rmSync(path, { force: true });
|
|
349
|
+
}
|
|
350
|
+
// install.ts
|
|
351
|
+
var RunnerError = class extends Error {
|
|
352
|
+
code;
|
|
353
|
+
constructor(code, message) {
|
|
354
|
+
super(message);
|
|
355
|
+
this.code = code;
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
const LATEST_RELEASE = "https://api.github.com/repos/actions/runner/releases/latest";
|
|
359
|
+
const ARCHIVE_URL = /^https:\/\/github\.com\/actions\/runner\/releases\/download\/v[\d.]+\/actions-runner-[\w.-]+\.tar\.gz$/;
|
|
360
|
+
const SHA256 = /^[a-f\d]{64}$/;
|
|
361
|
+
const Release = z.object({
|
|
362
|
+
tag_name: z.string().regex(/^v\d+\.\d+\.\d+$/),
|
|
363
|
+
body: z.string().nullish(),
|
|
364
|
+
assets: z.array(z.object({
|
|
365
|
+
name: z.string(),
|
|
366
|
+
browser_download_url: z.string(),
|
|
367
|
+
digest: z.string().nullish()
|
|
368
|
+
}))
|
|
369
|
+
});
|
|
370
|
+
function runnerPlatform() {
|
|
371
|
+
const system = platform();
|
|
372
|
+
const os = system === "darwin" ? "osx" : system;
|
|
373
|
+
const architecture = arch();
|
|
374
|
+
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).");
|
|
375
|
+
return {
|
|
376
|
+
os,
|
|
377
|
+
arch: architecture
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
function pickDownload(release, target) {
|
|
381
|
+
const parsed = Release.safeParse(release);
|
|
382
|
+
if (!parsed.success) throw new RunnerError("RUNNER_DOWNLOAD", "GitHub returned an unexpected runner release.");
|
|
383
|
+
const { tag_name, body, assets } = parsed.data;
|
|
384
|
+
const version = tag_name.slice(1);
|
|
385
|
+
const name = `actions-runner-${target.os}-${target.arch}-${version}.tar.gz`;
|
|
386
|
+
const asset = assets.find((item) => item.name === name);
|
|
387
|
+
const key = `${target.os}-${target.arch}`;
|
|
388
|
+
const fromNotes = body?.match(new RegExp(`<!-- BEGIN SHA ${key} -->\\s*([a-fA-F\\d]{64})\\s*<!-- END SHA ${key} -->`))?.[1]?.toLowerCase();
|
|
389
|
+
const fromDigest = asset?.digest?.match(/^sha256:([a-fA-F\d]{64})$/)?.[1]?.toLowerCase();
|
|
390
|
+
const sha256 = fromDigest ?? fromNotes;
|
|
391
|
+
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.`);
|
|
392
|
+
return {
|
|
393
|
+
version,
|
|
394
|
+
url: asset.browser_download_url,
|
|
395
|
+
sha256
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
async function latestDownload(target) {
|
|
399
|
+
const response = await fetch(LATEST_RELEASE, { headers: {
|
|
400
|
+
accept: "application/vnd.github+json",
|
|
401
|
+
"user-agent": userAgent
|
|
402
|
+
} });
|
|
403
|
+
if (!response.ok) throw new RunnerError("RUNNER_DOWNLOAD", `Could not look up the latest actions/runner release (HTTP ${response.status}).`);
|
|
404
|
+
return pickDownload(await response.json(), target);
|
|
405
|
+
}
|
|
406
|
+
function installedRunners(root = runnersDir()) {
|
|
407
|
+
if (!existsSync(root)) return [];
|
|
408
|
+
return readdirSync(root).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && existsSync(join(root, name, "run.sh"))).sort((a, b) => compareVersions(b, a)).map((version) => ({
|
|
409
|
+
version,
|
|
410
|
+
dir: join(root, version)
|
|
411
|
+
}));
|
|
412
|
+
}
|
|
413
|
+
function compareVersions(a, b) {
|
|
414
|
+
const [x, y] = [a, b].map((v) => v.split(".").map(Number));
|
|
415
|
+
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];
|
|
416
|
+
return 0;
|
|
417
|
+
}
|
|
418
|
+
async function ensureRunner(options = {}) {
|
|
419
|
+
const root = options.root ?? runnersDir();
|
|
420
|
+
const log = options.log ?? (() => {});
|
|
421
|
+
const target = runnerPlatform();
|
|
422
|
+
let download;
|
|
423
|
+
try {
|
|
424
|
+
download = await latestDownload(target);
|
|
425
|
+
} catch (error) {
|
|
426
|
+
const [newest] = installedRunners(root);
|
|
427
|
+
if (newest) {
|
|
428
|
+
log(`Couldn't check for a newer runner (${error.message}). Using ${newest.version}.`);
|
|
429
|
+
return newest;
|
|
430
|
+
}
|
|
431
|
+
throw error;
|
|
432
|
+
}
|
|
433
|
+
const dir = join(root, download.version);
|
|
434
|
+
if (existsSync(join(dir, "run.sh"))) return {
|
|
435
|
+
version: download.version,
|
|
436
|
+
dir
|
|
437
|
+
};
|
|
438
|
+
log(`Downloading actions/runner ${download.version}…`);
|
|
439
|
+
await install(root, download);
|
|
440
|
+
log(`Installed actions/runner ${download.version} in ${dir}`);
|
|
441
|
+
return {
|
|
442
|
+
version: download.version,
|
|
443
|
+
dir
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
async function install(root, download, fetcher = fetch) {
|
|
447
|
+
mkdirSync(root, {
|
|
448
|
+
recursive: true,
|
|
449
|
+
mode: 448
|
|
450
|
+
});
|
|
451
|
+
const temp = mkdtempSync(join(root, ".install-"));
|
|
452
|
+
try {
|
|
453
|
+
const archive = join(temp, "runner.tar.gz");
|
|
454
|
+
const response = await fetcher(download.url, {
|
|
455
|
+
headers: { "user-agent": userAgent },
|
|
456
|
+
signal: AbortSignal.timeout(6e5)
|
|
457
|
+
});
|
|
458
|
+
if (!response.ok || !response.body) throw new RunnerError("RUNNER_DOWNLOAD", `Runner download failed (HTTP ${response.status}). Check network access.`);
|
|
459
|
+
const hash = createHash("sha256");
|
|
460
|
+
await pipeline(Readable.fromWeb(response.body), new Transform({ transform(chunk, _encoding, done) {
|
|
461
|
+
hash.update(chunk);
|
|
462
|
+
done(null, chunk);
|
|
463
|
+
} }), createWriteStream(archive, { mode: 384 }));
|
|
464
|
+
if (hash.digest("hex") !== download.sha256) throw new RunnerError("RUNNER_CHECKSUM", "The runner archive failed SHA-256 verification.");
|
|
465
|
+
const unpacked = join(temp, "runner");
|
|
466
|
+
mkdirSync(unpacked, { mode: 448 });
|
|
467
|
+
if (await exitCode("tar", [
|
|
468
|
+
"-xzf",
|
|
469
|
+
archive,
|
|
470
|
+
"-C",
|
|
471
|
+
unpacked
|
|
472
|
+
]) !== 0) throw new RunnerError("RUNNER_EXTRACT", "Could not unpack the runner archive. Check tar and available disk space.");
|
|
473
|
+
try {
|
|
474
|
+
renameSync(unpacked, join(root, download.version));
|
|
475
|
+
} catch (error) {
|
|
476
|
+
const code = error.code;
|
|
477
|
+
if (code !== "EEXIST" && code !== "ENOTEMPTY") throw error;
|
|
478
|
+
}
|
|
479
|
+
} finally {
|
|
480
|
+
rmSync(temp, {
|
|
481
|
+
recursive: true,
|
|
482
|
+
force: true
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
function exitCode(command, args) {
|
|
487
|
+
return new Promise((resolve) => {
|
|
488
|
+
const child = spawn(command, args, { stdio: "ignore" });
|
|
489
|
+
child.once("error", () => resolve(null));
|
|
490
|
+
child.once("exit", (code) => resolve(code));
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
// job.ts
|
|
494
|
+
const runnerEnv = () => Object.fromEntries([
|
|
495
|
+
"HOME",
|
|
496
|
+
"USER",
|
|
497
|
+
"LOGNAME",
|
|
498
|
+
"PATH",
|
|
499
|
+
"LANG",
|
|
500
|
+
"LC_ALL",
|
|
501
|
+
"TMPDIR",
|
|
502
|
+
"SHELL"
|
|
503
|
+
].flatMap((key) => process.env[key] === void 0 ? [] : [[key, process.env[key]]]));
|
|
504
|
+
const JOB_STATE = [
|
|
505
|
+
"_work",
|
|
506
|
+
".runner",
|
|
507
|
+
".credentials",
|
|
508
|
+
".credentials_rsaparams"
|
|
509
|
+
];
|
|
510
|
+
async function runJob(run, options) {
|
|
511
|
+
const { runner, report } = options;
|
|
512
|
+
const output = options.output ?? ((chunk, stream) => (stream === "stdout" ? process.stdout : process.stderr).write(chunk));
|
|
513
|
+
const finish = (update) => {
|
|
514
|
+
report(update);
|
|
515
|
+
return update;
|
|
516
|
+
};
|
|
517
|
+
const lock = join(runner.dir, "job.lock");
|
|
518
|
+
if (!takeLock(lock)) return finish({
|
|
519
|
+
routeId: run.routeId,
|
|
520
|
+
state: "failed",
|
|
521
|
+
message: `Another job is using the runner in ${runner.dir}.`
|
|
522
|
+
});
|
|
523
|
+
try {
|
|
524
|
+
clean(runner.dir);
|
|
525
|
+
const child = spawn(join(runner.dir, "run.sh"), ["--jitconfig", run.jitConfig], {
|
|
526
|
+
cwd: runner.dir,
|
|
527
|
+
env: runnerEnv(),
|
|
528
|
+
stdio: [
|
|
529
|
+
"ignore",
|
|
530
|
+
"pipe",
|
|
531
|
+
"pipe"
|
|
532
|
+
]
|
|
533
|
+
});
|
|
534
|
+
child.stdout.on("data", (chunk) => output(chunk, "stdout"));
|
|
535
|
+
child.stderr.on("data", (chunk) => output(chunk, "stderr"));
|
|
536
|
+
const started = await new Promise((resolve) => {
|
|
537
|
+
child.once("spawn", () => resolve(null));
|
|
538
|
+
child.once("error", resolve);
|
|
539
|
+
});
|
|
540
|
+
if (started) return finish({
|
|
541
|
+
routeId: run.routeId,
|
|
542
|
+
state: "failed",
|
|
543
|
+
message: `Could not start the runner: ${started.message}`
|
|
544
|
+
});
|
|
545
|
+
report({
|
|
546
|
+
routeId: run.routeId,
|
|
547
|
+
state: "started"
|
|
548
|
+
});
|
|
549
|
+
const [code, signal] = await new Promise((resolve) => child.once("close", (code, signal) => resolve([code, signal])));
|
|
550
|
+
if (code === 0) return finish({
|
|
551
|
+
routeId: run.routeId,
|
|
552
|
+
state: "finished"
|
|
553
|
+
});
|
|
554
|
+
return finish({
|
|
555
|
+
routeId: run.routeId,
|
|
556
|
+
state: "failed",
|
|
557
|
+
message: signal ? `run.sh was stopped by ${signal}` : `run.sh exited with ${code}`
|
|
558
|
+
});
|
|
559
|
+
} catch (error) {
|
|
560
|
+
return finish({
|
|
561
|
+
routeId: run.routeId,
|
|
562
|
+
state: "failed",
|
|
563
|
+
message: error instanceof Error ? error.message : String(error)
|
|
564
|
+
});
|
|
565
|
+
} finally {
|
|
566
|
+
clean(runner.dir);
|
|
567
|
+
rmSync(lock, { force: true });
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
function clean(dir) {
|
|
571
|
+
for (const name of JOB_STATE) rmSync(join(dir, name), {
|
|
572
|
+
recursive: true,
|
|
573
|
+
force: true
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
function takeLock(lock) {
|
|
577
|
+
for (let attempt = 0; attempt < 2; attempt++) try {
|
|
578
|
+
symlinkSync(String(process.pid), lock);
|
|
579
|
+
return true;
|
|
580
|
+
} catch (error) {
|
|
581
|
+
if (error.code !== "EEXIST") throw error;
|
|
582
|
+
if (isAlive(Number(readlinkSync(lock)))) return false;
|
|
583
|
+
rmSync(lock, { force: true });
|
|
584
|
+
}
|
|
585
|
+
return false;
|
|
586
|
+
}
|
|
587
|
+
function isAlive(pid) {
|
|
588
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
589
|
+
try {
|
|
590
|
+
process.kill(pid, 0);
|
|
591
|
+
return true;
|
|
592
|
+
} catch (error) {
|
|
593
|
+
return error.code === "EPERM";
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
// login.ts
|
|
597
|
+
const CLIENT_ID = "relayrunner-cli";
|
|
598
|
+
const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
599
|
+
var LoginError = class extends Error {
|
|
600
|
+
code;
|
|
601
|
+
constructor(code, message) {
|
|
602
|
+
super(message);
|
|
603
|
+
this.code = code;
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
const CodeResponse = z.object({
|
|
607
|
+
device_code: z.string().min(1),
|
|
608
|
+
user_code: z.string().min(1),
|
|
609
|
+
verification_uri: z.string(),
|
|
610
|
+
verification_uri_complete: z.string().optional(),
|
|
611
|
+
expires_in: z.number().positive(),
|
|
612
|
+
interval: z.number().positive().optional()
|
|
613
|
+
});
|
|
614
|
+
const TokenResponse = z.object({ access_token: z.string().min(1) });
|
|
615
|
+
const OAuthError = z.object({
|
|
616
|
+
error: z.string(),
|
|
617
|
+
error_description: z.string().optional()
|
|
618
|
+
});
|
|
619
|
+
const ClaimResponse = z.object({
|
|
620
|
+
machine: z.object({
|
|
621
|
+
id: z.string().min(1),
|
|
622
|
+
name: z.string()
|
|
623
|
+
}),
|
|
624
|
+
workspace: z.object({
|
|
625
|
+
id: z.string().min(1),
|
|
626
|
+
name: z.string(),
|
|
627
|
+
slug: z.string().nullish()
|
|
628
|
+
}),
|
|
629
|
+
token: z.string().min(1)
|
|
630
|
+
});
|
|
631
|
+
async function login(options) {
|
|
632
|
+
const fetcher = options.fetcher ?? fetch;
|
|
633
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
634
|
+
const now = options.now ?? Date.now;
|
|
635
|
+
const api = (path) => new URL(path, options.server).toString();
|
|
636
|
+
const post = (path, body, headers = {}) => fetcher(api(path), {
|
|
637
|
+
method: "POST",
|
|
638
|
+
headers: {
|
|
639
|
+
"content-type": "application/json",
|
|
640
|
+
"user-agent": userAgent,
|
|
641
|
+
...headers
|
|
642
|
+
},
|
|
643
|
+
body: JSON.stringify(body)
|
|
644
|
+
});
|
|
645
|
+
const codeResponse = await post("/api/auth/device/code", { client_id: CLIENT_ID }).catch((error) => {
|
|
646
|
+
const cause = error.cause?.message;
|
|
647
|
+
throw new LoginError("UNREACHABLE", `Couldn't reach RelayRunner at ${options.server}${cause ? ` (${cause})` : ""}.`);
|
|
648
|
+
});
|
|
649
|
+
if (!codeResponse.ok) throw new LoginError("CODE_FAILED", `The gateway at ${options.server} wouldn't start a sign-in (HTTP ${codeResponse.status}).`);
|
|
650
|
+
const code = CodeResponse.parse(await codeResponse.json());
|
|
651
|
+
const url = new URL(code.verification_uri_complete ?? code.verification_uri);
|
|
652
|
+
if (!url.searchParams.has("user_code")) url.searchParams.set("user_code", code.user_code);
|
|
653
|
+
url.searchParams.set("name", options.name);
|
|
654
|
+
const expiresAt = now() + code.expires_in * 1e3;
|
|
655
|
+
await options.onCode({
|
|
656
|
+
userCode: code.user_code,
|
|
657
|
+
url: url.toString(),
|
|
658
|
+
expiresAt
|
|
659
|
+
});
|
|
660
|
+
let interval = (code.interval ?? 5) * 1e3;
|
|
661
|
+
let accessToken;
|
|
662
|
+
while (!accessToken) {
|
|
663
|
+
if (now() >= expiresAt) throw new LoginError("EXPIRED", "The sign-in code expired before it was approved.");
|
|
664
|
+
await sleep(interval);
|
|
665
|
+
let response;
|
|
666
|
+
try {
|
|
667
|
+
response = await post("/api/auth/device/token", {
|
|
668
|
+
grant_type: DEVICE_GRANT,
|
|
669
|
+
device_code: code.device_code,
|
|
670
|
+
client_id: CLIENT_ID
|
|
671
|
+
});
|
|
672
|
+
} catch {
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
const body = await response.json().catch(() => null);
|
|
676
|
+
if (response.ok) {
|
|
677
|
+
accessToken = TokenResponse.parse(body).access_token;
|
|
678
|
+
break;
|
|
679
|
+
}
|
|
680
|
+
const error = OAuthError.safeParse(body);
|
|
681
|
+
switch (error.success ? error.data.error : void 0) {
|
|
682
|
+
case "authorization_pending": continue;
|
|
683
|
+
case "slow_down":
|
|
684
|
+
interval += 5e3;
|
|
685
|
+
continue;
|
|
686
|
+
case "access_denied": throw new LoginError("DENIED", "The sign-in was denied in the browser.");
|
|
687
|
+
case "expired_token": throw new LoginError("EXPIRED", "The sign-in code expired before it was approved.");
|
|
688
|
+
default:
|
|
689
|
+
if (response.status >= 500) continue;
|
|
690
|
+
throw new LoginError("TOKEN_FAILED", `Signing in failed: ${error.success ? error.data.error_description ?? error.data.error : `HTTP ${response.status}`}.`);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
const claimResponse = await post("/api/machines/claim", {
|
|
694
|
+
deviceCode: code.device_code,
|
|
695
|
+
...options.platform
|
|
696
|
+
}, { authorization: `Bearer ${accessToken}` });
|
|
697
|
+
if (!claimResponse.ok) throw new LoginError("CLAIM_FAILED", `The gateway approved the sign-in but wouldn't enroll this machine (HTTP ${claimResponse.status}).`);
|
|
698
|
+
const claimed = ClaimResponse.parse(await claimResponse.json());
|
|
699
|
+
return {
|
|
700
|
+
server: new URL(options.server).origin,
|
|
701
|
+
machine: {
|
|
702
|
+
id: claimed.machine.id,
|
|
703
|
+
name: claimed.machine.name
|
|
704
|
+
},
|
|
705
|
+
workspace: claimed.workspace,
|
|
706
|
+
token: claimed.token
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
function openBrowser(url) {
|
|
710
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", [
|
|
711
|
+
"/c",
|
|
712
|
+
"start",
|
|
713
|
+
"",
|
|
714
|
+
url
|
|
715
|
+
]] : ["xdg-open", [url]];
|
|
716
|
+
try {
|
|
717
|
+
const child = spawn(command, args, {
|
|
718
|
+
stdio: "ignore",
|
|
719
|
+
detached: true
|
|
720
|
+
});
|
|
721
|
+
child.on("error", () => {});
|
|
722
|
+
child.unref();
|
|
723
|
+
} catch {}
|
|
724
|
+
}
|
|
725
|
+
// pause.ts
|
|
726
|
+
const PauseResponse = z.object({ machine: z.object({
|
|
727
|
+
name: z.string(),
|
|
728
|
+
paused: z.object({ by: z.string().nullable() }).nullable(),
|
|
729
|
+
status: z.object({ state: z.string().nullable() }).optional()
|
|
730
|
+
}) });
|
|
731
|
+
async function setPaused(options) {
|
|
732
|
+
const fetcher = options.fetcher ?? fetch;
|
|
733
|
+
const action = options.paused ? "pause" : "resume";
|
|
734
|
+
let response;
|
|
735
|
+
try {
|
|
736
|
+
response = await fetcher(new URL(`/api/machines/me/${action}`, options.server), {
|
|
737
|
+
method: "POST",
|
|
738
|
+
headers: {
|
|
739
|
+
authorization: `Bearer ${options.token}`,
|
|
740
|
+
"user-agent": userAgent
|
|
741
|
+
}
|
|
742
|
+
});
|
|
743
|
+
} catch (error) {
|
|
744
|
+
const cause = error.cause?.message;
|
|
745
|
+
return {
|
|
746
|
+
status: "failed",
|
|
747
|
+
reason: `couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
if (response.status === 401) return { status: "revoked" };
|
|
751
|
+
if (!response.ok) return {
|
|
752
|
+
status: "failed",
|
|
753
|
+
reason: `${options.server} answered HTTP ${response.status}`
|
|
754
|
+
};
|
|
755
|
+
const parsed = PauseResponse.safeParse(await response.json().catch(() => null));
|
|
756
|
+
if (!parsed.success) return {
|
|
757
|
+
status: "failed",
|
|
758
|
+
reason: `${options.server} sent an unexpected response`
|
|
759
|
+
};
|
|
760
|
+
return {
|
|
761
|
+
status: "ok",
|
|
762
|
+
paused: parsed.data.machine.paused !== null,
|
|
763
|
+
busy: parsed.data.machine.status?.state === "busy"
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
// whoami.ts
|
|
767
|
+
const WhoamiResponse = z.object({
|
|
768
|
+
machine: z.object({
|
|
769
|
+
id: z.string().min(1),
|
|
770
|
+
name: z.string(),
|
|
771
|
+
os: z.string().nullable(),
|
|
772
|
+
arch: z.string().nullable(),
|
|
773
|
+
createdAt: z.union([z.string(), z.number()]),
|
|
774
|
+
lastSeenAt: z.union([z.string(), z.number()]).nullable(),
|
|
775
|
+
status: z.object({
|
|
776
|
+
online: z.boolean(),
|
|
777
|
+
state: z.string().nullable()
|
|
778
|
+
}),
|
|
779
|
+
paused: z.object({ by: z.string().nullable() }).nullish()
|
|
780
|
+
}),
|
|
781
|
+
workspace: z.object({
|
|
782
|
+
id: z.string().min(1),
|
|
783
|
+
name: z.string(),
|
|
784
|
+
slug: z.string().nullish()
|
|
785
|
+
}),
|
|
786
|
+
enrolledBy: z.object({
|
|
787
|
+
name: z.string(),
|
|
788
|
+
email: z.string()
|
|
789
|
+
}).nullable()
|
|
790
|
+
});
|
|
791
|
+
async function whoami(options) {
|
|
792
|
+
const fetcher = options.fetcher ?? fetch;
|
|
793
|
+
let response;
|
|
794
|
+
try {
|
|
795
|
+
response = await fetcher(new URL("/api/machines/me", options.server), { headers: {
|
|
796
|
+
authorization: `Bearer ${options.token}`,
|
|
797
|
+
"user-agent": userAgent
|
|
798
|
+
} });
|
|
799
|
+
} catch (error) {
|
|
800
|
+
const cause = error.cause?.message;
|
|
801
|
+
return {
|
|
802
|
+
status: "unverified",
|
|
803
|
+
reason: `Couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
if (response.status === 401) return { status: "revoked" };
|
|
807
|
+
if (!response.ok) return {
|
|
808
|
+
status: "unverified",
|
|
809
|
+
reason: `${options.server} answered HTTP ${response.status}`
|
|
810
|
+
};
|
|
811
|
+
const parsed = WhoamiResponse.safeParse(await response.json().catch(() => null));
|
|
812
|
+
if (!parsed.success) return {
|
|
813
|
+
status: "unverified",
|
|
814
|
+
reason: `${options.server} sent an unexpected response`
|
|
815
|
+
};
|
|
816
|
+
return {
|
|
817
|
+
status: "ok",
|
|
818
|
+
identity: parsed.data
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
// cli.ts
|
|
822
|
+
const DEFAULT_SERVER = "https://relayrunner-app.relayrun.workers.dev";
|
|
823
|
+
const connectCommand = defineCommand({
|
|
824
|
+
meta: {
|
|
825
|
+
name: "connect",
|
|
826
|
+
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."
|
|
827
|
+
},
|
|
828
|
+
args: {
|
|
829
|
+
server: {
|
|
830
|
+
type: "string",
|
|
831
|
+
description: `RelayRunner URL (default: $RELAYRUNNER_URL or ${DEFAULT_SERVER})`
|
|
832
|
+
},
|
|
833
|
+
name: {
|
|
834
|
+
type: "string",
|
|
835
|
+
description: "Suggested machine name when signing in (default: this computer's hostname)"
|
|
836
|
+
}
|
|
837
|
+
},
|
|
838
|
+
async run({ args }) {
|
|
839
|
+
clack.intro("RelayRunner");
|
|
840
|
+
try {
|
|
841
|
+
await connectMachine(args);
|
|
842
|
+
} catch (error) {
|
|
843
|
+
if (!(error instanceof LoginError || error instanceof RunnerError)) throw error;
|
|
844
|
+
clack.log.error(error.message);
|
|
845
|
+
process.exitCode = 1;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
});
|
|
849
|
+
async function connectMachine(args) {
|
|
850
|
+
const requested = args.server || process.env.RELAYRUNNER_URL;
|
|
851
|
+
const target = runnerPlatform();
|
|
852
|
+
const platform = {
|
|
853
|
+
os: target.os === "osx" ? "macos" : "linux",
|
|
854
|
+
arch: target.arch
|
|
855
|
+
};
|
|
856
|
+
let credentials = readCredentials();
|
|
857
|
+
const server = normalizeServer(requested || credentials?.server || DEFAULT_SERVER);
|
|
858
|
+
if (credentials && credentials.server !== server) {
|
|
859
|
+
clack.log.warn(`This machine is enrolled with ${credentials.server}, not ${server}. Signing in again.`);
|
|
860
|
+
credentials = null;
|
|
861
|
+
}
|
|
862
|
+
if (!credentials) {
|
|
863
|
+
credentials = await signIn(server, args.name || hostname(), platform);
|
|
864
|
+
writeCredentials(credentials);
|
|
865
|
+
clack.log.success(`Enrolled as ${credentials.machine.name} in ${credentials.workspace.name}. Token saved to ${credentialsPath()}.`);
|
|
866
|
+
} else clack.log.info(`Machine ${credentials.machine.name} in ${credentials.workspace.name} (${credentials.server})`);
|
|
867
|
+
const runner = await ensureRunner({ log: (line) => clack.log.info(line) });
|
|
868
|
+
const stop = new AbortController();
|
|
869
|
+
const onInterrupt = () => {
|
|
870
|
+
if (stop.signal.aborted) process.exit(130);
|
|
871
|
+
stop.abort();
|
|
872
|
+
};
|
|
873
|
+
process.on("SIGINT", onInterrupt);
|
|
874
|
+
let online = false;
|
|
875
|
+
const end = await connect({
|
|
876
|
+
server: credentials.server,
|
|
877
|
+
token: credentials.token,
|
|
878
|
+
hello: {
|
|
879
|
+
machineId: credentials.machine.id,
|
|
880
|
+
...platform,
|
|
881
|
+
runnerVersion: runner.version
|
|
882
|
+
},
|
|
883
|
+
runJob: (run, report) => runJob(run, {
|
|
884
|
+
runner,
|
|
885
|
+
report
|
|
886
|
+
}),
|
|
887
|
+
onEvent: (event) => {
|
|
888
|
+
if (event.type === "connected") online = true;
|
|
889
|
+
show(event);
|
|
890
|
+
},
|
|
891
|
+
signal: stop.signal
|
|
892
|
+
});
|
|
893
|
+
process.off("SIGINT", onInterrupt);
|
|
894
|
+
switch (end.reason) {
|
|
895
|
+
case "stopped":
|
|
896
|
+
clack.outro("Offline.");
|
|
897
|
+
break;
|
|
898
|
+
case "revoked":
|
|
899
|
+
deleteCredentials();
|
|
900
|
+
if (!online) {
|
|
901
|
+
clack.log.warn("This machine was removed from the workspace or its token is no longer valid. Signing in again.");
|
|
902
|
+
return connectMachine({
|
|
903
|
+
...args,
|
|
904
|
+
server: credentials.server
|
|
905
|
+
});
|
|
906
|
+
}
|
|
907
|
+
clack.log.error("This machine was removed from the workspace or its token is no longer valid.");
|
|
908
|
+
clack.outro("Run `relayrunner connect` again to sign in.");
|
|
909
|
+
process.exitCode = 1;
|
|
910
|
+
break;
|
|
911
|
+
case "replaced":
|
|
912
|
+
clack.log.warn("Another `relayrunner connect` for this machine took over.");
|
|
913
|
+
clack.outro("Offline here.");
|
|
914
|
+
process.exitCode = 1;
|
|
915
|
+
break;
|
|
916
|
+
case "rejected":
|
|
917
|
+
clack.log.error(`The gateway rejected this CLI: ${end.message}`);
|
|
918
|
+
clack.outro("Update it with `npx relayrunner@latest connect`.");
|
|
919
|
+
process.exitCode = 1;
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
async function signIn(server, name, platform) {
|
|
923
|
+
const waiting = clack.spinner();
|
|
924
|
+
try {
|
|
925
|
+
const credentials = await login({
|
|
926
|
+
server,
|
|
927
|
+
name,
|
|
928
|
+
platform,
|
|
929
|
+
onCode: ({ userCode, url }) => {
|
|
930
|
+
clack.note(`${url}\n\nConfirm the code ${userCode} matches the one in your browser.`, "Sign in");
|
|
931
|
+
openBrowser(url);
|
|
932
|
+
waiting.start("Waiting for approval in the browser");
|
|
933
|
+
}
|
|
934
|
+
});
|
|
935
|
+
waiting.stop("Approved");
|
|
936
|
+
return credentials;
|
|
937
|
+
} catch (error) {
|
|
938
|
+
waiting.error("Sign-in failed");
|
|
939
|
+
throw error;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
function show(event) {
|
|
943
|
+
const at = (/* @__PURE__ */ new Date()).toLocaleTimeString();
|
|
944
|
+
switch (event.type) {
|
|
945
|
+
case "connecting":
|
|
946
|
+
if (event.attempt === 1) clack.log.step(`${at} Connecting…`);
|
|
947
|
+
break;
|
|
948
|
+
case "connected":
|
|
949
|
+
clack.log.success(`${at} Online. Waiting for jobs.`);
|
|
950
|
+
break;
|
|
951
|
+
case "disconnected":
|
|
952
|
+
clack.log.warn(`${at} Disconnected (${event.code}${event.reason ? ` ${event.reason}` : ""}). Retrying in ${Math.ceil(event.retryInMs / 1e3)}s.`);
|
|
953
|
+
break;
|
|
954
|
+
case "gateway-error":
|
|
955
|
+
clack.log.error(`${at} Gateway: ${event.message}`);
|
|
956
|
+
break;
|
|
957
|
+
case "run":
|
|
958
|
+
clack.log.step(`${at} Starting job ${event.routeId}`);
|
|
959
|
+
break;
|
|
960
|
+
case "paused":
|
|
961
|
+
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.`);
|
|
962
|
+
else clack.log.success(`${at} Resumed${event.by ? ` by ${event.by}` : ""}. Waiting for jobs.`);
|
|
963
|
+
break;
|
|
964
|
+
case "run-refused":
|
|
965
|
+
clack.log.warn(`${at} Turned down job ${event.routeId}: already running one.`);
|
|
966
|
+
break;
|
|
967
|
+
case "job": {
|
|
968
|
+
const { routeId, state, message } = event.update;
|
|
969
|
+
const line = `${at} Job ${routeId} ${state}${message ? `: ${message}` : ""}`;
|
|
970
|
+
if (state === "failed") clack.log.error(line);
|
|
971
|
+
else if (state === "finished") clack.log.success(line);
|
|
972
|
+
else clack.log.info(line);
|
|
973
|
+
break;
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
const whoamiCommand = defineCommand({
|
|
978
|
+
meta: {
|
|
979
|
+
name: "whoami",
|
|
980
|
+
description: "Show which machine and workspace this computer is signed in as, checked with the gateway."
|
|
981
|
+
},
|
|
982
|
+
args: {
|
|
983
|
+
server: {
|
|
984
|
+
type: "string",
|
|
985
|
+
description: "Only report a sign-in for this RelayRunner URL (default: the saved one)"
|
|
986
|
+
},
|
|
987
|
+
json: {
|
|
988
|
+
type: "boolean",
|
|
989
|
+
description: "Print the result as JSON"
|
|
990
|
+
}
|
|
991
|
+
},
|
|
992
|
+
async run({ args }) {
|
|
993
|
+
const print = (human, json) => console.log(args.json ? JSON.stringify(json, null, 2) : human);
|
|
994
|
+
const credentials = readCredentials();
|
|
995
|
+
const requested = args.server || process.env.RELAYRUNNER_URL;
|
|
996
|
+
const server = requested ? normalizeServer(requested) : credentials?.server;
|
|
997
|
+
if (!credentials || credentials.server !== server) {
|
|
998
|
+
print(credentials ? `Not signed in to ${server}. This machine is enrolled with ${credentials.server}.` : "Not signed in. Run `relayrunner connect` to sign in.", {
|
|
999
|
+
status: "signed_out",
|
|
1000
|
+
server: server ?? null
|
|
1001
|
+
});
|
|
1002
|
+
process.exitCode = 1;
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
const saved = {
|
|
1006
|
+
server: credentials.server,
|
|
1007
|
+
machine: credentials.machine,
|
|
1008
|
+
workspace: credentials.workspace
|
|
1009
|
+
};
|
|
1010
|
+
const result = await whoami({
|
|
1011
|
+
server: credentials.server,
|
|
1012
|
+
token: credentials.token
|
|
1013
|
+
});
|
|
1014
|
+
switch (result.status) {
|
|
1015
|
+
case "ok":
|
|
1016
|
+
print(describeIdentity(credentials.server, result.identity), {
|
|
1017
|
+
status: "ok",
|
|
1018
|
+
server: credentials.server,
|
|
1019
|
+
...result.identity
|
|
1020
|
+
});
|
|
1021
|
+
break;
|
|
1022
|
+
case "revoked":
|
|
1023
|
+
print(`${credentials.machine.name} was removed from ${credentials.workspace.name} or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`, {
|
|
1024
|
+
status: "revoked",
|
|
1025
|
+
...saved
|
|
1026
|
+
});
|
|
1027
|
+
process.exitCode = 1;
|
|
1028
|
+
break;
|
|
1029
|
+
case "unverified": print(`${describeSaved(saved)}\n\nUnverified: ${result.reason}. This is what's saved in ${credentialsPath()}.`, {
|
|
1030
|
+
status: "unverified",
|
|
1031
|
+
reason: result.reason,
|
|
1032
|
+
...saved
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
});
|
|
1037
|
+
function describeIdentity(server, identity) {
|
|
1038
|
+
const { machine, workspace, enrolledBy } = identity;
|
|
1039
|
+
const status = (machine.status.online ? `online${machine.status.state ? `, ${machine.status.state}` : ""}` : "offline") + (machine.paused ? `, paused${machine.paused.by ? ` by ${machine.paused.by}` : ""}` : "");
|
|
1040
|
+
const enrolled = [enrolledBy && `by ${enrolledBy.name} <${enrolledBy.email}>`, `on ${new Date(machine.createdAt).toLocaleDateString()}`].filter(Boolean).join(" ");
|
|
1041
|
+
return table(`${machine.name} (${machine.id})`, [
|
|
1042
|
+
["Workspace", workspace.slug ? `${workspace.name} (${workspace.slug})` : workspace.name],
|
|
1043
|
+
["Platform", [machine.os, machine.arch].filter(Boolean).join(" ") || "unknown"],
|
|
1044
|
+
["Enrolled", enrolled],
|
|
1045
|
+
["Status", status],
|
|
1046
|
+
["Gateway", server]
|
|
1047
|
+
]);
|
|
1048
|
+
}
|
|
1049
|
+
function describeSaved(saved) {
|
|
1050
|
+
return table(`${saved.machine.name} (${saved.machine.id})`, [["Workspace", saved.workspace.name], ["Gateway", saved.server]]);
|
|
1051
|
+
}
|
|
1052
|
+
function table(title, rows) {
|
|
1053
|
+
const width = Math.max(...rows.map(([label]) => label.length));
|
|
1054
|
+
return [title, ...rows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`)].join("\n");
|
|
1055
|
+
}
|
|
1056
|
+
function normalizeServer(value) {
|
|
1057
|
+
try {
|
|
1058
|
+
const url = new URL(value);
|
|
1059
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error();
|
|
1060
|
+
return url.origin;
|
|
1061
|
+
} catch {
|
|
1062
|
+
throw new RunnerError("USAGE", `Not a valid RelayRunner URL: ${value}`);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
function pauseCommand(paused) {
|
|
1066
|
+
return defineCommand({
|
|
1067
|
+
meta: {
|
|
1068
|
+
name: paused ? "pause" : "resume",
|
|
1069
|
+
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`."
|
|
1070
|
+
},
|
|
1071
|
+
async run() {
|
|
1072
|
+
const credentials = readCredentials();
|
|
1073
|
+
if (!credentials) {
|
|
1074
|
+
console.error("Not signed in. Run `relayrunner connect` to sign in.");
|
|
1075
|
+
process.exitCode = 1;
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
const result = await setPaused({
|
|
1079
|
+
server: credentials.server,
|
|
1080
|
+
token: credentials.token,
|
|
1081
|
+
paused
|
|
1082
|
+
});
|
|
1083
|
+
const name = credentials.machine.name;
|
|
1084
|
+
switch (result.status) {
|
|
1085
|
+
case "ok":
|
|
1086
|
+
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.`);
|
|
1087
|
+
break;
|
|
1088
|
+
case "revoked":
|
|
1089
|
+
console.error(`${name} was removed from ${credentials.workspace.name} or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`);
|
|
1090
|
+
process.exitCode = 1;
|
|
1091
|
+
break;
|
|
1092
|
+
case "failed":
|
|
1093
|
+
console.error(`Couldn't ${paused ? "pause" : "resume"} ${name}: ${result.reason}.`);
|
|
1094
|
+
process.exitCode = 1;
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
const main = defineCommand({
|
|
1100
|
+
meta: {
|
|
1101
|
+
name: "relayrunner",
|
|
1102
|
+
description: "Run GitHub Actions jobs on your machine through the RelayRunner gateway."
|
|
1103
|
+
},
|
|
1104
|
+
subCommands: {
|
|
1105
|
+
connect: connectCommand,
|
|
1106
|
+
whoami: whoamiCommand,
|
|
1107
|
+
pause: pauseCommand(true),
|
|
1108
|
+
resume: pauseCommand(false)
|
|
1109
|
+
}
|
|
1110
|
+
});
|
|
1111
|
+
runMain(main);
|
|
1112
|
+
export {};
|