| 1 | import type { JobCompletion, JobSpec } from "@diffinery/shared"; |
| 2 | import { LogBatcher, RunnerApi } from "./api.js"; |
| 3 | import { JobRunner, errMsg } from "./job.js"; |
| 4 | |
| 5 | export 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 | |
| 19 | export 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. */ |
| 25 | export 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 | } |