relayrunner 0.0.0-stage → 0.1.1

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 CHANGED
@@ -1,3 +1,48 @@
1
- # Temporary Holding Version
1
+ # RelayRunner
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run selected GitHub Actions jobs on your own machine during development, then
4
+ switch future jobs back to GitHub-hosted runners.
5
+
6
+ ## Install
7
+
8
+ ### Install with an agent
9
+
10
+ Paste this into your agent from the checkout you want to set up:
11
+
12
+ ```text
13
+ Set up RelayRunner in this checkout using https://raw.githubusercontent.com/atticoos/RelayRunner/main/docs/agent-install.md
14
+ ```
15
+
16
+ ### Install manually
17
+
18
+ ```sh
19
+ npm install --global relayrunner
20
+ relayrunner --help
21
+ ```
22
+
23
+ RelayRunner requires Node.js 22+, Git, and an authenticated GitHub CLI. Runner
24
+ setup supports macOS and Linux on x64 and ARM64.
25
+
26
+ ## Set up a repository
27
+
28
+ If RelayRunner is installed, paste this into your agent from the target checkout:
29
+
30
+ ```text
31
+ Use the RelayRunner skill to set up this repository. Show me the eligible jobs, let me choose which ones to opt in, and show me the workflow patch for approval before applying it.
32
+ ```
33
+
34
+ From a private GitHub repository checkout, discover eligible jobs and preview
35
+ the workflow change for the job you want to opt in:
36
+
37
+ ```sh
38
+ relayrunner discover
39
+ relayrunner preview --job .github/workflows/ci.yml:test
40
+ ```
41
+
42
+ Use the job ID from discovery. Review the patch before approving setup with
43
+ the preview's fingerprint. Setup registers a runner that executes jobs under
44
+ your local account.
45
+
46
+ The package includes the RelayRunner skill for Codex, Claude Code, and Cursor.
47
+ See the [project README](https://github.com/atticoos/RelayRunner#readme) for
48
+ skill installation, repository setup, and switching runners.
package/dist/SKILL.md ADDED
@@ -0,0 +1,15 @@
1
+ ---
2
+ name: relayrunner
3
+ description: Set up RelayRunner, switch between local and GitHub-hosted runners, and check routing for selected GitHub Actions jobs in a private repository. Discover jobs, show the workflow patch, and install and verify the developer's GitHub runner.
4
+ ---
5
+
6
+ Use the RelayRunner CLI from a trusted installed copy. If it is unavailable, use the installation instructions in the RelayRunner repository README. Run commands with `--json` and use `--cwd` to target the developer's checkout.
7
+
8
+ 1. Run `relayrunner discover --cwd <checkout> --json`. Confirm the repository and let the user select jobs using the returned IDs. A job needs to be compatible with the developer's OS and tools. Check its steps and dependencies before recommending it.
9
+ 2. Run `relayrunner preview --cwd <checkout> --job <id> --json`, repeating `--job` for every selected job. Show the actual patch, target branch, and the hosted fallback. Explain that setup starts GitHub's runner under the developer's local account. Use the user's existing authorization if it covers the displayed patch and runner setup. Otherwise obtain it before proceeding. Only set up repositories whose workflow authors the user trusts.
10
+ 3. Run `relayrunner setup` with the same checkout and job arguments, plus `--approve <fingerprint> --json`. Use the fingerprint from the authorized preview. For a stale preview, show the new patch before applying it. For an interrupted setup, rerun the same command if the fingerprint is still current. If the patch was applied, a fresh preview can verify that no workflow changes remain.
11
+ 4. Report the returned online status, runner label, and local workflow changes. The checkout changes need to go through the usual commit and push workflow before GitHub can use them. Commit or push only within the user's authorization.
12
+
13
+ For `GITHUB_ACCESS`, report the need for authorized GitHub CLI credentials and repository administration permission. If the environment restricts existing credential access, use its approved execution mechanism. Keep authentication and runner registration inside the CLI. Setup leaves routing inactive.
14
+
15
+ After the setup changes are committed and pushed, use `relayrunner switch local` to route opted-in jobs across the repository. Use `relayrunner status` to report the current route and runner availability. Use `relayrunner switch hosted` when the user wants to restore hosted execution for future jobs, and report any queued jobs or warning returned by the command.
package/dist/cli.js ADDED
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs, styleText } from 'node:util';
3
+ import { api, git, SetupError } from "./system.js";
4
+ import { repository, workflows, plan } from "./workflows.js";
5
+ import { withRunner } from "./runner.js";
6
+ import { routeJobs } from "./routing.js";
7
+ const usage = `relayrunner discover [--cwd PATH] [--json]
8
+ relayrunner preview --job PATH:JOB [--job PATH:JOB ...] [--cwd PATH] [--json]
9
+ relayrunner setup --job PATH:JOB [--job PATH:JOB ...] --approve FINGERPRINT [--cwd PATH] [--json]
10
+ relayrunner switch <local|hosted> [--cwd PATH] [--json]
11
+ relayrunner status [--cwd PATH] [--json]`;
12
+ async function main() {
13
+ const { values, positionals } = parseArgs({
14
+ allowPositionals: true,
15
+ options: {
16
+ cwd: { type: 'string', default: process.cwd() },
17
+ job: { type: 'string', multiple: true },
18
+ approve: { type: 'string' },
19
+ json: { type: 'boolean' },
20
+ help: { type: 'boolean', short: 'h' },
21
+ },
22
+ });
23
+ const [command, mode] = positionals;
24
+ if (values.help || !command) {
25
+ console.log(usage);
26
+ return;
27
+ }
28
+ const routing = command === 'switch' || command === 'status';
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;
128
+ });
@@ -0,0 +1,74 @@
1
+ import { api, SetupError } from "./system.js";
2
+ import { registeredRunner, runnerLabel, withRunnerLock } from "./runner.js";
3
+ import { workflows } from "./workflows.js";
4
+ const refKey = 'RELAYRUNNER_REF';
5
+ const labelKey = 'RELAYRUNNER_LABEL';
6
+ function pages(endpoint, query = '') {
7
+ return api(`${endpoint}?per_page=100${query}`, ['--paginate', '--slurp']);
8
+ }
9
+ function setVariable(endpoint, variables, name, value) {
10
+ if (variables.get(name) === value)
11
+ return;
12
+ if (variables.has(name)) {
13
+ api(`${endpoint}/${name}`, ['-X', 'PATCH', '-f', `value=${value}`]);
14
+ }
15
+ else {
16
+ api(endpoint, ['-X', 'POST', '-f', `name=${name}`, '-f', `value=${value}`]);
17
+ }
18
+ }
19
+ function queuedJobs(actions, label) {
20
+ if (!label)
21
+ return [];
22
+ const runIds = new Set(['queued', 'in_progress'].flatMap(status => pages(`${actions}/runs`, `&status=${status}`)
23
+ .flatMap(page => page.workflow_runs.map(run => run.id))));
24
+ return [...runIds]
25
+ .flatMap(id => pages(`${actions}/runs/${id}/jobs`).flatMap(page => page.jobs))
26
+ .filter(job => job.status === 'queued' && job.labels.some(item => item.toLowerCase() === label.toLowerCase()))
27
+ .map(({ id, name, html_url: url }) => ({ id, name, url }));
28
+ }
29
+ function routing(target, mode) {
30
+ const actions = `repos/${target.repo}/actions`;
31
+ const endpoint = `${actions}/variables`;
32
+ const variables = new Map(pages(endpoint).flatMap(page => page.variables)
33
+ .map(({ name, value }) => [name, value]));
34
+ const label = variables.get(labelKey);
35
+ if (mode === 'hosted') {
36
+ for (const name of [labelKey, refKey]) {
37
+ if (variables.has(name))
38
+ api(`${endpoint}/${name}`, ['-X', 'DELETE']);
39
+ }
40
+ const result = { repo: target.repo, route: 'hosted' };
41
+ try {
42
+ return { ...result, queuedJobs: queuedJobs(actions, label || runnerLabel(target)) };
43
+ }
44
+ catch (error) {
45
+ if (!(error instanceof SetupError))
46
+ throw error;
47
+ return { ...result, queuedJobs: null, warning: `Could not check queued jobs. ${error.message}` };
48
+ }
49
+ }
50
+ const localLabel = runnerLabel(target);
51
+ if (mode === 'local' && label && label !== localLabel) {
52
+ throw new SetupError('ROUTE_CONFLICT', `Local routing already targets ${label}. Run relayrunner switch hosted first.`);
53
+ }
54
+ const selectedLabel = label || localLabel;
55
+ const runner = registeredRunner(target, selectedLabel);
56
+ const online = runner?.status === 'online' && runner.labels?.some(item => item.name === selectedLabel);
57
+ const availability = !selectedLabel ? null : online ? (runner.busy ? 'busy' : 'online') : 'offline';
58
+ const runnerStatus = selectedLabel ? { label: selectedLabel, status: availability } : null;
59
+ if (mode === 'status') {
60
+ return { repo: target.repo, route: label ? 'local' : 'hosted', runner: runnerStatus };
61
+ }
62
+ if (!online || !localLabel)
63
+ throw new SetupError('RUNNER_OFFLINE', 'Set up this checkout and verify its local runner is online before switching.');
64
+ if (!workflows(target.root).some(job => job.alreadySetUp && !job.needsUpdate)) {
65
+ throw new SetupError('WORKFLOW_SETUP_REQUIRED', 'Set up or upgrade at least one eligible job and commit and push the workflow changes.');
66
+ }
67
+ if (variables.has(refKey))
68
+ api(`${endpoint}/${refKey}`, ['-X', 'DELETE']);
69
+ setVariable(endpoint, variables, labelKey, localLabel);
70
+ return { repo: target.repo, route: 'local', runner: runnerStatus };
71
+ }
72
+ export function routeJobs(target, mode) {
73
+ return mode === 'status' ? routing(target, mode) : withRunnerLock(target, () => routing(target, mode));
74
+ }
package/dist/runner.js ADDED
@@ -0,0 +1,152 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
4
+ import { arch, homedir, platform } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { setTimeout as sleep } from 'node:timers/promises';
7
+ import { api, run, SetupError } from "./system.js";
8
+ const runnerEnv = Object.fromEntries(['HOME', 'USER', 'LOGNAME', 'PATH', 'LANG', 'LC_ALL', 'TMPDIR', 'SHELL'].flatMap(key => process.env[key] === undefined ? [] : [[key, process.env[key]]]));
9
+ async function install(dir, endpoint) {
10
+ const system = platform();
11
+ const os = system === 'darwin' ? 'osx' : system;
12
+ const architecture = arch();
13
+ if ((os !== 'osx' && os !== 'linux') || (architecture !== 'x64' && architecture !== 'arm64') || process.getuid?.() === 0) {
14
+ throw new SetupError('UNSUPPORTED_MACHINE', 'Run as a regular user on macOS or Linux (x64 or arm64).');
15
+ }
16
+ const download = api(`${endpoint}/downloads`).find(item => item.os === os && item.architecture === architecture);
17
+ if (!download || !/^https:\/\/github\.com\/actions\/runner\/releases\/download\/v[\d.]+\/actions-runner-[\w.-]+\.tar\.gz$/.test(download.download_url) ||
18
+ !/^[a-f\d]{64}$/i.test(download.sha256_checksum)) {
19
+ throw new SetupError('RUNNER_DOWNLOAD', 'GitHub did not provide a supported runner archive with a SHA-256 checksum.');
20
+ }
21
+ const temp = mkdtempSync(join(dir, 'install-'));
22
+ try {
23
+ const archive = join(temp, 'runner.tar.gz');
24
+ const result = run('curl', ['-q', '--fail', '--silent', '--show-error', '--location',
25
+ '--proto', '=https', '--proto-redir', '=https', '--output', archive, download.download_url], { env: runnerEnv, timeout: 600_000 });
26
+ if (result.status !== 0)
27
+ throw new SetupError('RUNNER_DOWNLOAD', 'Runner download failed. Check curl and network access.');
28
+ const hash = createHash('sha256');
29
+ for await (const chunk of createReadStream(archive))
30
+ hash.update(chunk);
31
+ if (hash.digest('hex') !== download.sha256_checksum.toLowerCase()) {
32
+ throw new SetupError('RUNNER_CHECKSUM', 'The runner archive failed SHA-256 verification.');
33
+ }
34
+ const unpacked = join(temp, 'runner');
35
+ mkdirSync(unpacked, { mode: 0o700 });
36
+ if (run('tar', ['-xzf', archive, '-C', unpacked], { env: runnerEnv }).status !== 0) {
37
+ throw new SetupError('RUNNER_EXTRACT', 'Could not unpack the runner archive. Check tar and available disk space.');
38
+ }
39
+ renameSync(unpacked, join(dir, 'runner'));
40
+ }
41
+ finally {
42
+ rmSync(temp, { recursive: true, force: true });
43
+ }
44
+ }
45
+ function runnerDirectory(target) {
46
+ if (!Number.isSafeInteger(target.id))
47
+ throw new SetupError('GITHUB_REQUEST_FAILED', 'GitHub returned an invalid repository ID.');
48
+ return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), '.relayrunner'), String(target.id));
49
+ }
50
+ export function runnerLabel(target) {
51
+ const identity = join(runnerDirectory(target), 'identity');
52
+ if (!existsSync(identity))
53
+ return null;
54
+ const label = readFileSync(identity, 'utf8');
55
+ if (!/^relayrunner-[a-f\d-]{36}$/.test(label))
56
+ throw new SetupError('RUNNER_STATE', 'Runner identity is invalid.');
57
+ return label;
58
+ }
59
+ export function registeredRunner(target, label) {
60
+ if (!label)
61
+ return null;
62
+ return api(`repos/${target.repo}/actions/runners?per_page=100`, ['--paginate', '--slurp'])
63
+ .flatMap(page => page.runners).find(runner => runner.name === label) ?? null;
64
+ }
65
+ export async function withRunnerLock(target, work) {
66
+ const dir = runnerDirectory(target);
67
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
68
+ const lock = join(dir, 'setup.lock');
69
+ try {
70
+ symlinkSync(String(process.pid), lock);
71
+ }
72
+ catch (error) {
73
+ if (error.code !== 'EEXIST')
74
+ throw error;
75
+ throw new SetupError('SETUP_LOCKED', `Setup is locked at ${lock}. If its recorded PID has exited, remove the lock and retry.`);
76
+ }
77
+ try {
78
+ return await work(dir);
79
+ }
80
+ finally {
81
+ rmSync(lock);
82
+ }
83
+ }
84
+ export async function withRunner(target, finish) {
85
+ return withRunnerLock(target, async (dir) => {
86
+ const cwd = join(dir, 'runner');
87
+ const endpoint = `repos/${target.repo}/actions/runners`;
88
+ const identity = join(dir, 'identity');
89
+ if (!existsSync(identity)) {
90
+ writeFileSync(`${identity}.tmp`, `relayrunner-${randomUUID()}`, { mode: 0o600 });
91
+ renameSync(`${identity}.tmp`, identity);
92
+ }
93
+ const label = runnerLabel(target);
94
+ if (!label)
95
+ throw new SetupError('RUNNER_STATE', 'Runner identity is missing.');
96
+ const lookup = () => registeredRunner(target, label);
97
+ const existing = lookup();
98
+ if (!existsSync(cwd))
99
+ await install(dir, endpoint);
100
+ const config = join(cwd, '.runner');
101
+ if (!existsSync(config)) {
102
+ if (existing?.status === 'online' || existing?.busy) {
103
+ throw new SetupError('RUNNER_STATE', 'The runner identity is already active. Recover its local configuration before retrying.');
104
+ }
105
+ const { token } = api(`${endpoint}/registration-token`, ['-X', 'POST']);
106
+ if (!token)
107
+ throw new SetupError('RUNNER_CONFIG', 'GitHub did not provide a registration token.');
108
+ const args = ['--unattended', '--url', `https://github.com/${target.repo}`,
109
+ '--name', label, '--labels', label, '--no-default-labels'];
110
+ if (existing)
111
+ args.push('--replace');
112
+ const result = run('./config.sh', args, {
113
+ cwd, env: { ...runnerEnv, ACTIONS_RUNNER_INPUT_TOKEN: token }, stdio: 'ignore',
114
+ });
115
+ if (result.status !== 0) {
116
+ throw new SetupError('RUNNER_CONFIG', 'Runner registration failed. Check organization policy and the official runner runtime prerequisites, then retry.');
117
+ }
118
+ }
119
+ else if (!existing) {
120
+ throw new SetupError('RUNNER_STATE', 'Local configuration exists but GitHub cannot find the runner. Restore or remove the stale local installation before retrying.');
121
+ }
122
+ let runner = lookup();
123
+ if (runner?.status !== 'online') {
124
+ const pidFile = join(dir, 'listener.pid');
125
+ let running = false;
126
+ if (existsSync(pidFile)) {
127
+ const pid = readFileSync(pidFile, 'utf8').trim();
128
+ if (/^[1-9]\d*$/.test(pid)) {
129
+ const result = run('ps', ['-p', pid, '-o', 'command=']);
130
+ running = result.status === 0 && result.stdout.includes(join(cwd, 'run.sh'));
131
+ }
132
+ }
133
+ if (!running) {
134
+ const child = spawn(join(cwd, 'run.sh'), [], { cwd, env: runnerEnv, detached: true, stdio: 'ignore' });
135
+ await new Promise((resolve, reject) => {
136
+ child.once('spawn', resolve);
137
+ child.once('error', () => reject(new SetupError('RUNNER_START', 'Could not start the official runner.')));
138
+ });
139
+ child.unref();
140
+ writeFileSync(pidFile, String(child.pid), { mode: 0o600 });
141
+ }
142
+ for (let attempt = 0; attempt < 20 && runner?.status !== 'online'; attempt++) {
143
+ await sleep(1500);
144
+ runner = lookup();
145
+ }
146
+ }
147
+ if (runner?.status !== 'online' || !runner.labels?.some(item => item.name === label)) {
148
+ throw new SetupError('RUNNER_OFFLINE', `GitHub has not confirmed the runner online with label ${label}. Check runner diagnostics under ${cwd}/_diag and retry.`);
149
+ }
150
+ return finish({ id: runner.id, label, status: runner.status });
151
+ });
152
+ }
package/dist/system.js ADDED
@@ -0,0 +1,41 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ export class SetupError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.code = code;
7
+ }
8
+ }
9
+ export function run(command, args, options = {}) {
10
+ return spawnSync(command, args, {
11
+ encoding: 'utf8',
12
+ maxBuffer: 16 * 1024 * 1024,
13
+ timeout: 120_000,
14
+ ...options,
15
+ });
16
+ }
17
+ export function git(cwd, args, options) {
18
+ const result = run('git', args, { cwd, ...options });
19
+ if (result.status !== 0) {
20
+ throw new SetupError('GIT_FAILED', `git ${args[0]} failed. Check the checkout and preview again.`);
21
+ }
22
+ return result.stdout;
23
+ }
24
+ export function api(endpoint, args = []) {
25
+ const { GH_DEBUG: _ghDebug, DEBUG: _debug, ...env } = process.env;
26
+ const result = run('gh', ['api', '--hostname', 'github.com', endpoint, ...args], {
27
+ env: { ...env, GH_PROMPT_DISABLED: '1' },
28
+ });
29
+ if (result.error?.code === 'ENOENT') {
30
+ throw new SetupError('MISSING_GH', 'Install the GitHub CLI and make it available on PATH.');
31
+ }
32
+ if (result.status !== 0) {
33
+ const status = result.stderr?.match(/HTTP (\d{3})/)?.[1];
34
+ if (['401', '403', '404'].includes(status ?? '') ||
35
+ /auth login|no oauth token|token invalid|requires authentication/i.test(result.stderr ?? '')) {
36
+ throw new SetupError('GITHUB_ACCESS', 'Use an authorized GitHub CLI session with access to this private repository. Runner setup requires repository administration access and must be allowed by organization policy.');
37
+ }
38
+ throw new SetupError('GITHUB_REQUEST_FAILED', 'GitHub API request failed. Check network access and retry.');
39
+ }
40
+ return result.stdout.trim() ? JSON.parse(result.stdout) : undefined;
41
+ }
@@ -0,0 +1,109 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync, lstatSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { isMap, isScalar, parseDocument } from 'yaml';
6
+ import { api, git, run, SetupError } from "./system.js";
7
+ const hosted = /^(?:ubuntu-(?:latest|(?:20|22|24|26)\.04(?:-arm)?)|macos-(?:latest|(?:13|14|15|26)(?:-intel)?)|windows-(?:latest|2019|2022|2025))$/;
8
+ const legacyRoute = "${{ github.event_name == 'push' && github.ref_type == 'branch' && github.ref == vars.RELAYRUNNER_REF && vars.RELAYRUNNER_LABEL != '' && vars.RELAYRUNNER_LABEL || '{hosted}' }}";
9
+ const branchRoute = "${{ ((github.event.pull_request && github.event.pull_request.head.repo.id == fromJSON(github.repository_id) && format('refs/heads/{0}', github.head_ref) == vars.RELAYRUNNER_REF) || (!github.event.pull_request && github.ref_type == 'branch' && github.ref == vars.RELAYRUNNER_REF)) && vars.RELAYRUNNER_LABEL != '' && vars.RELAYRUNNER_LABEL || '{hosted}' }}";
10
+ const route = "${{ vars.RELAYRUNNER_LABEL || '{hosted}' }}";
11
+ export function repository(cwd) {
12
+ const root = git(cwd, ['rev-parse', '--show-toplevel']).trim();
13
+ const origin = git(root, ['remote', 'get-url', 'origin']).trim();
14
+ const remote = origin.match(/^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w-]+\/[\w.-]+?)\/?$/i);
15
+ if (!remote)
16
+ throw new SetupError('UNSUPPORTED_REMOTE', 'Use a checkout with a github.com origin.');
17
+ const repo = api(`repos/${remote[1].replace(/\.git$/, '')}`);
18
+ if (repo.visibility !== 'private' || repo.fork || !/^[\w-]+\/[\w.-]+$/.test(repo.full_name)) {
19
+ throw new SetupError('UNSUPPORTED_REPO', 'Setup requires a private, non-fork GitHub repository.');
20
+ }
21
+ return { root, repo: repo.full_name, id: repo.id };
22
+ }
23
+ export function workflows(root) {
24
+ const files = git(root, ['ls-files', '-z', '--', '.github/workflows']).split('\0')
25
+ .filter(file => /^\.github\/workflows\/[\w.-]+\.ya?ml$/.test(file));
26
+ return [...new Set(files)].flatMap(file => {
27
+ const path = join(root, file);
28
+ try {
29
+ if (!lstatSync(path).isFile() || !lstatSync(join(root, '.github')).isDirectory() ||
30
+ !lstatSync(join(root, '.github/workflows')).isDirectory())
31
+ return [];
32
+ }
33
+ catch (error) {
34
+ if (error.code === 'ENOENT')
35
+ return [];
36
+ throw error;
37
+ }
38
+ const source = readFileSync(path, 'utf8');
39
+ const doc = parseDocument(source);
40
+ if (doc.errors.length)
41
+ throw new SetupError('INVALID_WORKFLOW', `Cannot parse ${file}.`);
42
+ const jobs = doc.get('jobs');
43
+ if (!isMap(jobs) || jobs.anchor)
44
+ return [];
45
+ return jobs.items.flatMap(({ key, value }) => {
46
+ if (!isScalar(key) || typeof key.value !== 'string' || !isMap(value) || value.anchor)
47
+ return [];
48
+ const node = value.get('runs-on', true);
49
+ if (!isScalar(node) || typeof node.value !== 'string' || node.anchor || node.tag ||
50
+ !['PLAIN', 'QUOTE_SINGLE', 'QUOTE_DOUBLE'].includes(node.type ?? '') || !node.range)
51
+ return [];
52
+ const [start, end] = node.range;
53
+ if (/[\r\n]/.test(source.slice(start, end)))
54
+ return [];
55
+ const fallback = node.value.match(/\|\| '([^']+)' \}\}$/)?.[1];
56
+ const alreadySetUp = fallback !== undefined && hosted.test(fallback) &&
57
+ route.replace('{hosted}', fallback) === node.value;
58
+ const needsUpdate = fallback !== undefined && hosted.test(fallback) &&
59
+ [legacyRoute, branchRoute].some(template => template.replace('{hosted}', fallback) === node.value);
60
+ if (!alreadySetUp && !needsUpdate && !hosted.test(node.value))
61
+ return [];
62
+ const hostedRunner = alreadySetUp || needsUpdate ? fallback : node.value;
63
+ return [{ id: `${file}:${key.value}`, file, source, start, end, runsOn: node.value,
64
+ alreadySetUp: alreadySetUp || needsUpdate, needsUpdate, hostedRunner }];
65
+ });
66
+ });
67
+ }
68
+ function patchFor(file, before, after) {
69
+ const dir = mkdtempSync(join(tmpdir(), 'relayrunner-patch-'));
70
+ try {
71
+ writeFileSync(join(dir, 'before'), before);
72
+ writeFileSync(join(dir, 'after'), after);
73
+ const diff = run('git', ['diff', '--no-index', '--no-color', '--no-ext-diff', '--text', '--', 'before', 'after'], { cwd: dir });
74
+ if (diff.status !== 1 || !diff.stdout.includes('\n@@ ')) {
75
+ throw new SetupError('PATCH_FAILED', `Could not generate patch for ${file}.`);
76
+ }
77
+ return `diff --git a/${file} b/${file}\n--- a/${file}\n+++ b/${file}\n` +
78
+ diff.stdout.slice(diff.stdout.indexOf('\n@@ ') + 1);
79
+ }
80
+ finally {
81
+ rmSync(dir, { recursive: true, force: true });
82
+ }
83
+ }
84
+ export function plan(target, ids) {
85
+ const available = workflows(target.root);
86
+ const selected = [...new Set(ids)].sort().map(id => {
87
+ const job = available.find(candidate => candidate.id === id);
88
+ if (!job)
89
+ throw new SetupError('INELIGIBLE_JOB', `Job is unavailable or unsupported: ${id}`);
90
+ return job;
91
+ });
92
+ const files = Map.groupBy(selected.filter(job => !job.alreadySetUp || job.needsUpdate), job => job.file);
93
+ const patch = [...files].map(([file, jobs]) => {
94
+ const before = jobs[0].source;
95
+ let after = before;
96
+ for (const { start, end, hostedRunner } of jobs.sort((a, b) => b.start - a.start)) {
97
+ after = after.slice(0, start) + JSON.stringify(route.replace('{hosted}', hostedRunner)) + after.slice(end);
98
+ }
99
+ return patchFor(file, before, after);
100
+ }).join('');
101
+ const head = git(target.root, ['rev-parse', 'HEAD']).trim();
102
+ const branch = git(target.root, ['branch', '--show-current']).trim();
103
+ if (!branch)
104
+ throw new SetupError('DETACHED_HEAD', 'Switch to a named branch before previewing setup.');
105
+ const fingerprint = createHash('sha256').update(JSON.stringify([
106
+ target.repo, head, branch, selected.map(({ id, source }) => [id, source]), patch,
107
+ ])).digest('hex');
108
+ return { repo: target.repo, branch, jobs: selected.map(job => job.id), fingerprint, patch };
109
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "relayrunner",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Switch selected GitHub Actions jobs between GitHub-hosted runners and your machine.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/atticoos/RelayRunner.git",
8
+ "directory": "apps/cli"
9
+ },
10
+ "type": "module",
11
+ "engines": {
12
+ "node": ">=22"
13
+ },
14
+ "bin": {
15
+ "relayrunner": "./dist/cli.js"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "dependencies": {
21
+ "yaml": "2.9.0"
22
+ },
23
+ "scripts": {
24
+ "build": "tsc -p tsconfig.build.json",
25
+ "test": "vitest run"
26
+ }
6
27
  }