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.

289 lines · 15.2 KBRaw History
1import { DurableObject } from "cloudflare:workers";
2import { Container } from "@cloudflare/containers";
3import type { StopParams } from "@cloudflare/containers";
4import type { Env } from "../env.js";
5import { egressStart, type Egress } from "../lib/egress.js";
6import { endCompute, startCompute } from "../lib/quotas.js";
7import { blockedBy, killSwitches } from "../lib/killswitch.js";
8
9/**
10 * Hosted compute (jobs and sandboxes) under the instance's egress policy (lib/egress.ts), set before
11 * each start. A limited one is kept in storage, so the container starting again from this Durable
12 * Object with its defaults (a sandbox after its idle sleep) is limited too; the allowed hosts are
13 * kept by the library itself.
14 */
15abstract class HostedContainer extends Container<Env> {
16 override enableInternet = true;
17
18 constructor(ctx: DurableObject["ctx"], env: Env) {
19 super(ctx, env);
20 const kept = ctx.storage.kv.get<Egress>("egress");
21 if (kept) this.adopt(kept);
22 }
23
24 /** Applies the policy before a start and returns the variables that tell the agent about it. */
25 protected async useEgress(egress: Egress): Promise<Record<string, string>> {
26 const o = this.adopt(egress);
27 if (o.allowedHosts) await this.setAllowedHosts(o.allowedHosts);
28 if (egress !== "open") this.ctx.storage.kv.put("egress", egress);
29 return o.envVars;
30 }
31
32 private adopt(egress: Egress) {
33 const o = egressStart(egress);
34 this.enableInternet = o.enableInternet;
35 this.interceptHttps = o.interceptHttps;
36 return o;
37 }
38}
39
40/** The job a runner container runs; stopRequested once Diffinery asked it to stop (stopJob). */
41type RunnerJob = { repoId: string; jobId: string; container?: string; stopRequested?: boolean };
42/** A GitHub job's runner (github-runners/): GitHub's own runner, for the account that pays. */
43type GitHubRunner = { accountId: string; runnerId: string; container?: string };
44
45/** How long a job's container may take to come up, and how often it is checked meanwhile. */
46const START_WAIT_MS = 180_000;
47const START_POLL_MS = 500;
48
49/**
50 * One container per workflow job. The runner agent inside fetches its job spec
51 * from the Diffinery API, runs the steps and reports back, then exits.
52 */
53export class RunnerContainer extends HostedContainer {
54 // Jobs make no inbound requests, so activity-based sleep must not stop them.
55 override sleepAfter = "6h";
56 /** True while start() runs (startRunner). */
57 private starting = false;
58
59 async startJob(input: { repoId: string; jobId: string; container?: string; token: string; apiUrl: string; egress?: Egress; vcpu?: number }): Promise<void> {
60 await this.ctx.storage.put("job", { repoId: input.repoId, jobId: input.jobId, container: input.container });
61 await this.startRunner({
62 DIFFINERY_API_URL: input.apiUrl,
63 DIFFINERY_JOB_ID: input.jobId,
64 DIFFINERY_JOB_TOKEN: input.token,
65 // The runner's share of CPU, which the agent measures the job's use against (runner/sizes.ts).
66 ...(input.vcpu ? { DIFFINERY_RUNNER_VCPU: String(input.vcpu) } : {}),
67 ...(await this.useEgress(input.egress ?? "open")),
68 });
69 }
70
71 /**
72 * A GitHub job's runner (github-runners/service.ts): the agent runs GitHub's runner with the just-in-time
73 * configuration GitHub made for it, which holds the runner's credentials, so it is only ever in the
74 * container's environment.
75 */
76 async startGitHubRunner(input: { accountId: string; runnerId: string; container?: string; jitConfig: string; egress: Egress; vcpu: number }): Promise<void> {
77 await this.ctx.storage.put("github", { accountId: input.accountId, runnerId: input.runnerId, container: input.container } satisfies GitHubRunner);
78 await this.startRunner({ DIFFINERY_GITHUB_JIT_CONFIG: input.jitConfig, DIFFINERY_RUNNER_VCPU: String(input.vcpu), ...(await this.useEgress(input.egress)) });
79 }
80
81 private async startRunner(envVars: Record<string, string>): Promise<void> {
82 this.starting = true;
83 try {
84 await this.start(
85 { envVars },
86 // The library gives up after 8 s and reports "no container instance", but a container on a host
87 // that hasn't pulled the runner image yet takes longer than that to come up: such jobs went back
88 // in line for 30 to 90 s more (measured on 10-leg matrices). Wait for it instead.
89 // The runner listens on no port: the library's own fallback port (33) answers "not listening" once it is up.
90 // Each check can itself take up to 5 s, so the signal bounds the whole wait.
91 { portToCheck: 33, waitInterval: START_POLL_MS, retries: Math.ceil(START_WAIT_MS / START_POLL_MS), signal: AbortSignal.timeout(START_WAIT_MS + 60_000) },
92 );
93 } finally {
94 this.starting = false;
95 }
96 }
97
98 /**
99 * Diffinery ended the job (a timeout, fail-fast, a newer run in its concurrency group): the container
100 * goes at once. `graceful` (someone cancelled the run) sends SIGINT instead: the runner stops the step
101 * under way, runs the steps that run after a cancel and reports. The agent reads SIGTERM as a platform
102 * rollout and keeps the job running for up to 14 minutes, which a cancelled job must not do.
103 */
104 async stopJob(graceful = false): Promise<void> {
105 // Noted first, so onStop can tell Diffinery's own stop (a cancel, a timeout) from the platform's.
106 const job = await this.ctx.storage.get<RunnerJob>("job");
107 if (job) await this.ctx.storage.put("job", { ...job, stopRequested: true });
108 if (!this.ctx.container?.running) return;
109 if (graceful) await this.stop("SIGINT");
110 else await this.destroy();
111 }
112
113 override async onStop(params: StopParams): Promise<void> {
114 const gh = await this.ctx.storage.get<GitHubRunner>("github");
115 if (gh) {
116 // While a start the platform had no machine for is tried again, the library's alarm reports the container
117 // stopped with exit code 0, though nothing ran and the start goes on. Told so, Diffinery removed the runner
118 // from GitHub and its job waited 24 hours for another (2 or 3 jobs of 10 started at once). The start ends in
119 // a running runner, or in an error that github-runners/service.ts place() handles.
120 if (this.starting) return;
121 const ns = this.env.GITHUB_RUNNERS;
122 if (ns) await ns.get(ns.idFromName(gh.accountId)).stopped(gh.accountId, gh.runnerId, params.exitCode ?? null, gh.container);
123 await this.ctx.storage.delete("github");
124 return;
125 }
126 const job = await this.ctx.storage.get<RunnerJob>("job");
127 if (!job) return;
128 const repo = this.env.REPO.get(this.env.REPO.idFromName(job.repoId));
129 await repo.containerStopped(job.jobId, params.exitCode ?? null, job.container, !!job.stopRequested);
130 await this.ctx.storage.delete("job");
131 }
132
133 override onError(error: unknown): void {
134 console.error("runner container error", error);
135 }
136}
137
138/**
139 * The smaller hosted runner sizes (runner/sizes.ts): the same runner on smaller Cloudflare instance
140 * types, each its own container class because a container class has one instance type.
141 */
142export class RunnerContainerMedium extends RunnerContainer {}
143export class RunnerContainerSmall extends RunnerContainer {}
144export class RunnerContainerTiny extends RunnerContainer {}
145
146/**
147 * Long-lived task sandbox for AI agents: the repo checked out with toolchains,
148 * and an HTTP API (exec, read/write files) on port 8080.
149 */
150export class SandboxContainer extends HostedContainer {
151 override defaultPort = 8080;
152 override sleepAfter = "30m";
153
154 async boot(envVars: Record<string, string>, secret: string, _name?: string, usage?: { id: string; accountId: string; repoId: string }, egress: Egress = "open"): Promise<void> {
155 await this.ctx.storage.put("secret", secret);
156 // Its running time counts against the repository owner's hosted minutes (lib/quotas.ts).
157 if (usage) await this.ctx.storage.put("usage", usage);
158 envVars = { ...envVars, ...(await this.useEgress(egress)) };
159 // The first start on a host after a deploy pulls the runner image, which takes
160 // well over the library's 8 s / 20 s defaults.
161 await this.startAndWaitForPorts({
162 ports: 8080,
163 startOptions: { envVars, entrypoint: ["node", "/opt/diffinery/agent.mjs", "--sandbox"] },
164 cancellationOptions: { instanceGetTimeoutMS: 180_000, portReadyTimeoutMS: 120_000, waitInterval: 500 },
165 });
166 }
167
168 /** Forward an API call (JSON text) to the sandbox's HTTP server with its secret attached. */
169 async call(path: string, body: string): Promise<{ status: number; body: string; json: boolean }> {
170 const secret = await this.ctx.storage.get<string>("secret");
171 // A sandbox that slept after 30 idle minutes starts again for this call: its time counts again.
172 const usage = await this.ctx.storage.get<{ id: string; accountId: string; repoId: string; part?: number }>("usage");
173 if (usage && !this.ctx.container?.running) {
174 // It doesn't wake while a kill switch stops sandboxes (lib/killswitch.ts).
175 const block = await killSwitches(this.env, usage.repoId).then(
176 (k) => blockedBy(k, "sandbox"),
177 () => null,
178 );
179 if (block) return { status: 403, body: JSON.stringify({ message: block }), json: true };
180 const part = (usage.part ?? 0) + 1;
181 await startCompute(this.env, { id: `${usage.id}:${part}`, accountId: usage.accountId, repoId: usage.repoId, kind: "sandbox" });
182 await this.ctx.storage.put("usage", { ...usage, part });
183 }
184 const res = await this.containerFetch(`http://sandbox${path}`, {
185 method: "POST",
186 headers: { "content-type": "application/json", authorization: `Bearer ${secret}` },
187 body: body || "{}",
188 });
189 return { status: res.status, body: await res.text(), json: (res.headers.get("content-type") ?? "").includes("json") };
190 }
191
192 async shutdown(): Promise<void> {
193 if (this.ctx.container?.running) await this.stop();
194 }
195
196 /** Whether the container is up (calling into a stopped one would start it without its checkout). */
197 async running(): Promise<boolean> {
198 return !!this.ctx.container?.running && !!(await this.ctx.storage.get<string>("secret"));
199 }
200
201 /**
202 * A web terminal's socket (agentic/terminal-web.ts checked who is asking): only a WebSocket
203 * upgrade to /pty, with the sandbox's secret added. A sandbox that isn't running isn't started
204 * again (it would come up without its checkout), and nothing else of the sandbox is reachable here.
205 */
206 override async fetch(request: Request): Promise<Response> {
207 const url = new URL(request.url);
208 if (url.pathname !== "/pty" || request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("not found", { status: 404 });
209 const secret = await this.ctx.storage.get<string>("secret");
210 if (!secret || !this.ctx.container?.running) return new Response("the terminal isn't running", { status: 410 });
211 const headers = new Headers({ upgrade: "websocket", authorization: `Bearer ${secret}` });
212 return this.containerFetch(new Request(`http://sandbox/pty${url.search}`, { headers }), 8080);
213 }
214
215 override async onStop(): Promise<void> {
216 const usage = await this.ctx.storage.get<{ id: string; part?: number }>("usage");
217 if (usage) await endCompute(this.env, usage.part ? `${usage.id}:${usage.part}` : usage.id);
218 }
219}
220
221/**
222 * Local development and end-to-end tests only: `env.dev` binds SANDBOX to this
223 * instead of SandboxContainer, because containers don't run under `wrangler dev`.
224 * The same calls, served by one `agent.mjs --sandbox-pool` process at
225 * SANDBOX_POOL_URL that runs each sandbox's server.
226 */
227export class SandboxPoolDO extends DurableObject<Env> {
228 private poolAuth() {
229 return { authorization: `Bearer ${this.env.SANDBOX_POOL_SECRET ?? ""}` };
230 }
231
232 async boot(envVars: Record<string, string>, secret: string, name?: string): Promise<void> {
233 if (!this.env.SANDBOX_POOL_URL || !name) throw new Error("SANDBOX_POOL_URL is not set: start `agent.mjs --sandbox-pool` for sandboxes under wrangler dev");
234 await this.ctx.storage.put({ secret, name });
235 const r = await fetch(`${this.env.SANDBOX_POOL_URL}/boot`, { method: "POST", headers: this.poolAuth(), body: JSON.stringify({ id: name, secret, env: envVars }) });
236 if (!r.ok) throw new Error(`sandbox pool boot failed: ${r.status} ${await r.text()}`);
237 }
238
239 async call(path: string, body: string): Promise<{ status: number; body: string; json: boolean }> {
240 const [secret, name] = await Promise.all([this.ctx.storage.get<string>("secret"), this.ctx.storage.get<string>("name")]);
241 if (!name) return { status: 404, body: JSON.stringify({ error: "sandbox not found" }), json: true };
242 const res = await fetch(`${this.env.SANDBOX_POOL_URL}/s/${name}${path}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${secret}` }, body: body || "{}" });
243 return { status: res.status, body: await res.text(), json: (res.headers.get("content-type") ?? "").includes("json") };
244 }
245
246 async shutdown(): Promise<void> {
247 const name = await this.ctx.storage.get<string>("name");
248 if (name) await fetch(`${this.env.SANDBOX_POOL_URL}/shutdown/${name}`, { method: "POST", headers: this.poolAuth() }).catch(() => {});
249 }
250
251 async running(): Promise<boolean> {
252 if (!(await this.ctx.storage.get<string>("name"))) return false;
253 return (await this.call("/pty/status", "{}").catch(() => ({ status: 0 }))).status === 200;
254 }
255
256 /** As SandboxContainer.fetch: a terminal's WebSocket, through the pool. */
257 override async fetch(request: Request): Promise<Response> {
258 const url = new URL(request.url);
259 if (url.pathname !== "/pty" || request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("not found", { status: 404 });
260 const [secret, name] = await Promise.all([this.ctx.storage.get<string>("secret"), this.ctx.storage.get<string>("name")]);
261 if (!secret || !name) return new Response("the terminal isn't running", { status: 410 });
262 const res = await fetch(`${this.env.SANDBOX_POOL_URL}/s/${name}/pty${url.search}`, { headers: { upgrade: "websocket", authorization: `Bearer ${secret}` } });
263 if (!res.webSocket) return new Response(await res.text(), { status: res.status === 101 ? 502 : res.status });
264 return pipeSocket(res.webSocket);
265 }
266}
267
268/** Hands a WebSocket this Durable Object holds to the caller, relaying frames and closes both ways. */
269function pipeSocket(upstream: WebSocket): Response {
270 const [client, server] = Object.values(new WebSocketPair()) as [WebSocket, WebSocket];
271 upstream.accept();
272 server.accept();
273 const code = (c: number) => (c === 1005 || c === 1006 ? 1000 : c);
274 // Binary frames can arrive as Blobs; reading one is async, so each direction keeps its order with a chain.
275 const relay = (from: WebSocket, to: WebSocket) => {
276 let chain = Promise.resolve();
277 from.addEventListener("message", (e) => {
278 const data = e.data as string | ArrayBuffer | Blob;
279 chain = chain.then(async () => to.send(data instanceof Blob ? await data.arrayBuffer() : data)).catch(() => to.close(1011, "relay failed"));
280 });
281 };
282 relay(server, upstream);
283 relay(upstream, server);
284 server.addEventListener("close", (e) => upstream.close(code(e.code), e.reason));
285 upstream.addEventListener("close", (e) => server.close(code(e.code), e.reason));
286 server.addEventListener("error", () => upstream.close(1011, "client error"));
287 upstream.addEventListener("error", () => server.close(1011, "sandbox error"));
288 return new Response(null, { status: 101, webSocket: client });
289}