Diffinery

codician/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.

65 lines · 2.4 KBRaw History
1import type { JobCompletion, JobSpec } from "@diffinery/shared";
2import { LogBatcher, RunnerApi } from "./api.js";
3import { JobRunner, errMsg } from "./job.js";
4
5export interface AgentOptions {
6 /** `${apiUrl}/runner/jobs/${jobId}`, or null for offline mode (logs to stdout, no reports). */
7 apiBase: string | null;
8 workRoot: string;
9 toolCache?: string;
10 echoLogs?: boolean;
11 /** Install a SIGTERM/SIGINT handler that cancels the job. */
12 handleSignals?: boolean;
13 /** Exposes the runner (e.g. so tests can cancel). */
14 onRunner?: (r: JobRunner) => void;
15 logIntervalMs?: number;
16 baseEnv?: NodeJS.ProcessEnv;
17}
18
19export function apiBaseFor(apiUrl: string | undefined | null, jobId: string): string | null {
20 if (!apiUrl) return null;
21 return `${apiUrl.replace(/\/$/, "")}/runner/jobs/${encodeURIComponent(jobId)}`;
22}
23
24/** Runs one job end-to-end: execute steps, ship logs, POST completion. */
25export async function runAgentJob(spec: JobSpec, o: AgentOptions): Promise<JobCompletion> {
26 const api = new RunnerApi(o.apiBase, spec.token);
27 const batcher = api.online
28 ? new LogBatcher((lines) => api.postLogs(lines), {
29 intervalMs: o.logIntervalMs ?? 500,
30 onError: (e) => process.stderr.write(`[diffinery-runner] log upload failed: ${errMsg(e)}\n`),
31 })
32 : null;
33 const runner = new JobRunner(spec, api, null, { workRoot: o.workRoot, toolCache: o.toolCache, echoLogs: o.echoLogs ?? !api.online, baseEnv: o.baseEnv }, batcher);
34 o.onRunner?.(runner);
35 const onSignal = (sig: string) => {
36 runner.logger.line(-1, `##[error]Received ${sig}; cancelling the job.`);
37 runner.cancel("cancelled");
38 };
39 const sigterm = () => onSignal("SIGTERM");
40 const sigint = () => onSignal("SIGINT");
41 if (o.handleSignals) {
42 process.on("SIGTERM", sigterm);
43 process.on("SIGINT", sigint);
44 }
45 let completion: JobCompletion;
46 try {
47 completion = await runner.run();
48 } catch (e) {
49 completion = { conclusion: "failure", outputs: {}, failure: { message: `Runner error: ${errMsg(e)}` } };
50 }
51 if (batcher) {
52 const ok = await batcher.close(120_000);
53 if (!ok) process.stderr.write(`[diffinery-runner] gave up shipping ${batcher.pending} log lines\n`);
54 }
55 try {
56 await api.complete(completion);
57 } catch (e) {
58 process.stderr.write(`[diffinery-runner] failed to report completion: ${errMsg(e)}\n`);
59 }
60 if (o.handleSignals) {
61 process.off("SIGTERM", sigterm);
62 process.off("SIGINT", sigint);
63 }
64 return completion;
65}