Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

172 lines · 7.9 KBRaw History
1/**
2 * Diffinery runner agent entry point.
3 *
4 * agent.mjs fetch the job from DIFFINERY_API_URL and run it
5 * agent.mjs --spec job.json run a JobSpec from a file (reports to spec.apiUrl,
6 * or DIFFINERY_API_URL; `--offline` logs to stdout only)
7 * agent.mjs --sandbox AI-agent sandbox HTTP server on :8080
8 * agent.mjs --sandbox-pool many sandboxes in one process, for local development and
9 * end-to-end tests (see sandbox-pool.ts)
10 * agent.mjs --jail ... run a terminal task's command in its jail (see jail.ts)
11 * agent.mjs --registry-relay HTTPS proxy for the Docker daemon that splits big
12 * image layer uploads to the Diffinery registry (see relay.ts)
13 *
14 * With DIFFINERY_IMPORT_ID and DIFFINERY_IMPORT_TOKEN set (instead of a job), it
15 * runs a GitHub import's Git transfer (see importer.ts) and exits. With
16 * DIFFINERY_GITHUB_JIT_CONFIG set, it runs GitHub's own runner for one job of a
17 * GitHub repository (see github-runner.ts) and exits.
18 */
19import { readFile } from "node:fs/promises";
20import type { JobSpec } from "@diffinery/shared";
21import { UsageSampler } from "./usage.js";
22import { apiBaseFor, runAgentJob } from "./agent.js";
23import { trustEgressCa } from "./egress.js";
24import { RunnerApi } from "./api.js";
25import { runJail } from "./jail.js";
26import { runImportAgent } from "./importer.js";
27import { startSandbox } from "./sandbox.js";
28import { startSandboxPool } from "./sandbox-pool.js";
29import { startRelay } from "./relay.js";
30import { runGitHubRunner } from "./github-runner.js";
31
32interface Args {
33 spec?: string;
34 sandbox: boolean;
35 pool: boolean;
36 relay: boolean;
37 offline: boolean;
38 workRoot?: string;
39}
40
41function parseArgs(argv: string[]): Args {
42 const a: Args = { sandbox: false, pool: false, relay: false, offline: false };
43 for (let i = 0; i < argv.length; i++) {
44 const v = argv[i]!;
45 if (v === "--spec") a.spec = argv[++i];
46 else if (v.startsWith("--spec=")) a.spec = v.slice(7);
47 else if (v === "--sandbox") a.sandbox = true;
48 else if (v === "--sandbox-pool") a.pool = true;
49 else if (v === "--registry-relay") a.relay = true;
50 else if (v === "--offline") a.offline = true;
51 else if (v === "--work-root") a.workRoot = argv[++i];
52 else if (v === "--help" || v === "-h") {
53 process.stdout.write("usage: agent.mjs [--spec job.json [--offline]] [--sandbox | --sandbox-pool] [--work-root dir]\n");
54 process.exit(0);
55 }
56 }
57 return a;
58}
59
60function fail(msg: string): never {
61 process.stderr.write(`[diffinery-runner] ${msg}\n`);
62 process.exit(2);
63}
64
65async function main(): Promise<void> {
66 if (process.argv[2] === "--jail") process.exit(await runJail(process.argv.slice(3)));
67 const args = parseArgs(process.argv.slice(2));
68 const env = process.env;
69 const workRoot = args.workRoot ?? env.DIFFINERY_WORK_ROOT ?? "/workspace";
70 await trustEgressCa(env);
71
72 if (args.relay) {
73 const { DIFFINERY_RELAY_HOST: host, DIFFINERY_RELAY_UPSTREAM: upstream, DIFFINERY_RELAY_CERT: cert, DIFFINERY_RELAY_KEY: key } = env;
74 if (!host || !upstream || !cert || !key) fail("DIFFINERY_RELAY_HOST, DIFFINERY_RELAY_UPSTREAM, DIFFINERY_RELAY_CERT and DIFFINERY_RELAY_KEY are required with --registry-relay");
75 await startRelay({ port: Number(env.DIFFINERY_RELAY_PORT ?? 3129), host, upstream, chunkSize: env.DIFFINERY_RELAY_CHUNK ? Number(env.DIFFINERY_RELAY_CHUNK) : undefined, cert: await readFile(cert, "utf8"), key: await readFile(key, "utf8") });
76 return;
77 }
78
79 if (args.pool) {
80 const secret = env.DIFFINERY_SANDBOX_POOL_SECRET;
81 if (!secret) fail("DIFFINERY_SANDBOX_POOL_SECRET is required in --sandbox-pool mode");
82 const pool = await startSandboxPool({ port: Number(env.DIFFINERY_SANDBOX_PORT ?? env.PORT ?? 8080), secret, workRoot });
83 process.stdout.write(`[sandbox-pool] listening on :${pool.port}\n`);
84 const stop = () => void pool.close().then(() => process.exit(0));
85 process.on("SIGTERM", stop);
86 process.on("SIGINT", stop);
87 return;
88 }
89 if (args.sandbox) {
90 const secret = env.DIFFINERY_SANDBOX_SECRET;
91 if (!secret) fail("DIFFINERY_SANDBOX_SECRET is required in --sandbox mode");
92 const h = await startSandbox({
93 port: Number(env.DIFFINERY_SANDBOX_PORT ?? env.PORT ?? 8080),
94 secret,
95 workRoot,
96 cloneUrl: env.DIFFINERY_CLONE_URL,
97 ref: env.DIFFINERY_REF,
98 token: env.DIFFINERY_JOB_TOKEN,
99 });
100 process.stdout.write(`[sandbox] listening on :${h.port}\n`);
101 const stop = () => void h.close().then(() => process.exit(0));
102 process.on("SIGTERM", stop);
103 process.on("SIGINT", stop);
104 return;
105 }
106
107 if (env.DIFFINERY_GITHUB_JIT_CONFIG) {
108 const code = await runGitHubRunner({ jitConfig: env.DIFFINERY_GITHUB_JIT_CONFIG });
109 process.stdout.write(`[diffinery-runner] GitHub's runner exited with code ${code}
110`);
111 process.exit(code);
112 }
113
114 if (env.DIFFINERY_IMPORT_ID) {
115 const api = env.DIFFINERY_API_URL;
116 const token = env.DIFFINERY_IMPORT_TOKEN;
117 if (!api || !token) fail("DIFFINERY_API_URL and DIFFINERY_IMPORT_TOKEN are required in import mode");
118 const chunk = Number(env.DIFFINERY_IMPORT_CHUNK_BYTES);
119 const large = Number(env.DIFFINERY_IMPORT_LARGE_BLOB_BYTES);
120 const result = await runImportAgent({ apiUrl: api, importId: env.DIFFINERY_IMPORT_ID, token, workRoot, chunkBytes: Number.isFinite(chunk) && chunk > 0 ? chunk : undefined, largeBlobBytes: Number.isFinite(large) && large > 0 ? large : undefined });
121 process.stdout.write(`[diffinery-import] ${result.ok ? "finished" : `failed: ${result.error}`}\n`);
122 process.exit(result.ok ? 0 : 1);
123 }
124
125 let spec: JobSpec;
126 let apiBase: string | null;
127 if (args.spec) {
128 spec = JSON.parse(await readFile(args.spec, "utf8")) as JobSpec;
129 if (env.DIFFINERY_JOB_TOKEN && !spec.token) spec.token = env.DIFFINERY_JOB_TOKEN;
130 apiBase = args.offline ? null : apiBaseFor(env.DIFFINERY_API_URL ?? spec.apiUrl, spec.jobId);
131 } else {
132 const api = env.DIFFINERY_API_URL;
133 const jobId = env.DIFFINERY_JOB_ID;
134 const token = env.DIFFINERY_JOB_TOKEN;
135 if (!api || !jobId || !token) fail("DIFFINERY_API_URL, DIFFINERY_JOB_ID and DIFFINERY_JOB_TOKEN are required (or pass --spec / --sandbox)");
136 apiBase = apiBaseFor(api, jobId);
137 const client = new RunnerApi(apiBase, token);
138 try {
139 spec = await client.getSpec();
140 } catch (e) {
141 const msg = e instanceof Error ? e.message : String(e);
142 try {
143 await client.complete({ conclusion: "failure", outputs: {}, failure: { message: `Runner could not fetch the job spec: ${msg}` } });
144 } catch {
145 /* nothing more we can do */
146 }
147 fail(`could not fetch job spec: ${msg}`);
148 }
149 spec.token ||= token;
150 spec.apiUrl ||= api;
151 }
152
153 const completion = await runAgentJob(spec, {
154 apiBase,
155 workRoot,
156 toolCache: env.RUNNER_TOOL_CACHE,
157 echoLogs: env.DIFFINERY_ECHO_LOGS === "1" || apiBase === null,
158 handleSignals: true,
159 // Cloudflare gives a container 15 minutes after SIGTERM during a rollout; the last
160 // two are for cancelling the steps and reporting the result before SIGKILL.
161 drainOnSigtermMs: args.spec ? undefined : 13 * 60_000,
162 // A hosted runner is its own machine (Cloudflare sets the Durable Object id in its container).
163 // test/docker-wrapper.test.ts runs the image's docker wrapper with the head start on.
164 prewarmDocker: !!env.CLOUDFLARE_DURABLE_OBJECT_ID,
165 prefetchTools: !!env.CLOUDFLARE_DURABLE_OBJECT_ID,
166 measureUsage: !!env.CLOUDFLARE_DURABLE_OBJECT_ID || env.DIFFINERY_MEASURE_USAGE === "1" ? new UsageSampler({ cores: Number(env.DIFFINERY_RUNNER_VCPU) || undefined }) : false,
167 });
168 process.stdout.write(`[diffinery-runner] job finished: ${completion.conclusion}\n`);
169 process.exit(completion.conclusion === "success" ? 0 : 1);
170}
171
172main().catch((e: unknown) => fail(e instanceof Error ? (e.stack ?? e.message) : String(e)));