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