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.

850 lines · 34.8 KBRaw History
1import type { ChildProcess } from "node:child_process";
2import { randomUUID } from "node:crypto";
3import { existsSync } from "node:fs";
4import { mkdir, readFile, writeFile } from "node:fs/promises";
5import path from "node:path";
6import type { Readable } from "node:stream";
7import type { Conclusion, ContainerSpec, JobCompletion, JobSpec, StepReport, StepSpec } from "@diffinery/shared";
8import { evaluate, evaluateIf, interpolate, type StatusFns } from "@diffinery/workflow-yaml";
9import { cpuTimes, runnerInfo, type RunnerApi } from "./api.js";
10import { parseKeyValueFile, parsePathFile } from "./commands.js";
11import { Docker, type Wrap } from "./docker.js";
12import { JobLogger, OutputProcessor, type Annotation, type OutputSink } from "./log.js";
13import { Masker } from "./mask.js";
14import { ToolPrefetch } from "./prefetch.js";
15import { RuntimeClient } from "./runtime.js";
16import { runAction } from "./steps/actions.js";
17import { runScript } from "./steps/run.js";
18import { exec, hashFiles, killTree, nowIso, runnerArch, type ExecResult } from "./util.js";
19
20export type Outcome = "success" | "failure" | "cancelled" | "skipped";
21
22export interface StepContextEntry {
23 outputs: Record<string, string>;
24 outcome: Outcome;
25 conclusion: Outcome;
26}
27
28/** Execution scope: the job itself, or the inside of a composite action. */
29export interface Scope {
30 steps: Record<string, StepContextEntry>;
31 inputs: Record<string, unknown>;
32 /** A step in this scope failed (without continue-on-error). */
33 failed: boolean;
34 /** Env inherited from the calling step (composite actions). */
35 inheritedEnv: Record<string, string>;
36 composite: boolean;
37 action?: { path: string; repository: string; ref: string };
38 depth: number;
39}
40
41export interface StepIO extends OutputSink {
42 /** Short reason recorded when the step fails (e.g. exit code). */
43 reason?: string;
44}
45
46export interface StepResult {
47 outcome: Outcome;
48 conclusion: Outcome;
49 outputs: Record<string, string>;
50}
51
52export interface PostStep {
53 name: string;
54 /** Expression evaluated with job status (e.g. `always()`, `success()`). */
55 condition: string;
56 run: (logIndex: number) => Promise<void>;
57}
58
59export interface RunnerOptions {
60 workRoot: string;
61 /** Tool cache dir; defaults to `${workRoot}/_tool` (or RUNNER_TOOL_CACHE). */
62 toolCache?: string;
63 echoLogs?: boolean;
64 /** Base env for child processes (defaults to process.env). */
65 baseEnv?: NodeJS.ProcessEnv;
66 /** Start the Docker daemon as the job begins when the job will use Docker (hosted runners). */
67 prewarmDocker?: boolean;
68 /** Hosted runners: start installing the job's Go or Java toolchain as the job begins (prefetch.ts). */
69 prefetchTools?: boolean;
70}
71
72export class StepFailure extends Error {}
73
74/**
75 * Whether a job will use Docker: job or service containers, `docker://` actions, or a step that names
76 * docker (a `run:` script, or an action such as docker/build-push-action). A guess, so only for a head start.
77 */
78export function jobUsesDocker(spec: JobSpec): boolean {
79 if (spec.container?.image || Object.keys(spec.services ?? {}).length) return true;
80 return spec.steps.some((s) => /\bdocker\b|testcontainers/i.test(`${s.uses ?? ""}\n${s.run ?? ""}`));
81}
82
83/** The runner's own credentials: never in a step's environment. */
84const SENSITIVE_ENV = ["DIFFINERY_JOB_TOKEN", "DIFFINERY_SANDBOX_SECRET", "DIFFINERY_GITHUB_TOKEN"];
85
86export class JobRunner {
87 readonly masker = new Masker();
88 readonly logger: JobLogger;
89 readonly workspace: string;
90 readonly tempDir: string;
91 readonly toolCache: string;
92 readonly actionsDir: string;
93 readonly fileCmdDir: string;
94 readonly eventPath: string;
95 readonly debug: boolean;
96
97 /** Accumulated GITHUB_ENV values. */
98 envAccum: Record<string, string> = {};
99 /** Accumulated GITHUB_PATH entries, most recent first. */
100 pathAccum: string[] = [];
101 jobEnv: Record<string, string> = {};
102 readonly summaries: string[] = [];
103 readonly posts: PostStep[] = [];
104 readonly children = new Set<ChildProcess>();
105 /** Aborted when the job is cancelled or times out, for work the runner does itself (downloads). */
106 private readonly aborter = new AbortController();
107 readonly stepErrors = new Map<number, Annotation[]>();
108 readonly stepReasons = new Map<number, string>();
109 /** Job and service containers, and Docker actions (self-hosted runners with Docker). */
110 readonly docker: Docker;
111 readonly prefetch = new ToolPrefetch(this);
112 /** The Actions runtime services client (null when the server sent none). */
113 readonly runtime: RuntimeClient | null;
114
115 private stopping: null | "cancelled" | "timeout" = null;
116 /** Set when the platform signals that it is replacing this runner (a container rollout). */
117 replacing = false;
118 private firstFailure: { step?: number; message: string } | null = null;
119 /** The vCPUs' time when a hosted job started, to say at the end how much of it the host took (steal). */
120 private cpuAtStart: { total: number; steal: number } | null = null;
121 private githubCtx: Record<string, unknown> = {};
122 private defaultEnv: Record<string, string> = {};
123 /**
124 * The Actions runtime services' variables. Like GitHub, only JavaScript and
125 * Docker actions get them (and the built-ins, which call the services directly);
126 * `run:` steps do not.
127 */
128 runtimeEnv: Record<string, string> = {};
129 private baseEnv: NodeJS.ProcessEnv;
130 private secrets: Record<string, string>;
131
132 constructor(
133 readonly spec: JobSpec,
134 readonly api: RunnerApi,
135 logger: JobLogger | null,
136 readonly opts: RunnerOptions,
137 batcher: import("./api.js").LogBatcher | null = null,
138 ) {
139 this.logger = logger ?? new JobLogger(this.masker, batcher, !!opts.echoLogs);
140 this.workspace = path.join(opts.workRoot, spec.repo.name);
141 this.tempDir = path.join(opts.workRoot, "_temp");
142 this.toolCache = opts.toolCache ?? process.env.RUNNER_TOOL_CACHE ?? path.join(opts.workRoot, "_tool");
143 this.actionsDir = path.join(opts.workRoot, "_actions");
144 this.fileCmdDir = path.join(this.tempDir, "_runner_file_commands");
145 this.eventPath = path.join(this.tempDir, "_github_workflow", "event.json");
146 this.secrets = { ...spec.secrets, GITHUB_TOKEN: spec.token };
147 this.debug = this.secrets.ACTIONS_STEP_DEBUG === "true" || spec.vars?.ACTIONS_STEP_DEBUG === "true";
148 const base = { ...(opts.baseEnv ?? process.env) };
149 for (const k of SENSITIVE_ENV) delete base[k];
150 this.baseEnv = base;
151 for (const v of Object.values(this.secrets)) this.masker.add(v);
152 if (spec.runtime) this.masker.add(spec.runtime.token);
153 this.runtime = RuntimeClient.fromSpec(spec);
154 this.docker = new Docker(this);
155 }
156
157 /** The runner's own environment (for internal tools such as the docker CLI). */
158 hostEnv(): NodeJS.ProcessEnv {
159 return { ...this.baseEnv };
160 }
161
162 // ------------------------------------------------------------ public
163
164 get signal(): AbortSignal {
165 return this.aborter.signal;
166 }
167
168 get isStopping(): boolean {
169 return this.stopping !== null;
170 }
171
172 /** SIGTERM / external cancellation. */
173 cancel(reason: "cancelled" | "timeout" = "cancelled"): void {
174 if (this.stopping) return;
175 this.stopping = reason;
176 this.aborter.abort();
177 for (const c of this.children) killTree(c);
178 }
179
180 async run(): Promise<JobCompletion> {
181 const spec = this.spec;
182 let jobTimer: NodeJS.Timeout | undefined;
183 if (spec.timeoutMinutes > 0) {
184 jobTimer = setTimeout(() => {
185 this.logger.line(-1, `##[error]The job running on runner has exceeded the maximum execution time of ${spec.timeoutMinutes} minutes.`);
186 this.cancel("timeout");
187 }, spec.timeoutMinutes * 60_000);
188 jobTimer.unref();
189 }
190 const top: Scope = { steps: {}, inputs: spec.inputs ?? {}, failed: false, inheritedEnv: {}, composite: false, depth: 0 };
191 if (this.opts.prewarmDocker && jobUsesDocker(spec)) this.docker.prewarm();
192 if (this.opts.prefetchTools) this.prefetch.start(spec);
193 try {
194 await this.setup();
195 await this.initContainers(top);
196 for (let i = 0; i < spec.steps.length; i++) {
197 const step = spec.steps[i]!;
198 const fallbackName = defaultStepName(step);
199 if (this.stopping) {
200 await this.report(i, { status: "completed", conclusion: "cancelled", name: safeName(step, fallbackName), completedAt: nowIso() });
201 continue;
202 }
203 const startedAt = nowIso();
204 let started = false;
205 const res = await this.executeStep(step, top, i, async (name) => {
206 started = true;
207 await this.report(i, { status: "in_progress", name, startedAt });
208 });
209 await this.report(i, {
210 status: "completed",
211 conclusion: res.conclusion,
212 name: res.name ?? fallbackName,
213 ...(started ? { startedAt } : {}),
214 completedAt: nowIso(),
215 });
216 }
217 if (!this.stopping) await this.runPosts(top);
218 } catch (e) {
219 const msg = e instanceof Error ? e.message : String(e);
220 this.logger.line(-1, `##[error]${msg}`);
221 top.failed = true;
222 this.firstFailure ??= { message: msg };
223 } finally {
224 if (jobTimer) clearTimeout(jobTimer);
225 await this.prefetch.stop();
226 try {
227 await this.docker.cleanup({ logIndex: -1, outputs: {}, state: {} });
228 } catch (e) {
229 this.logger.line(-1, `##[warning]Could not remove the job's containers: ${errMsg(e)}`);
230 }
231 }
232
233 let conclusion: Conclusion = top.failed ? "failure" : "success";
234 if (this.stopping === "cancelled") conclusion = "cancelled";
235 if (this.stopping === "timeout") {
236 conclusion = "failure";
237 this.firstFailure = { ...(this.firstFailure ?? {}), message: `The job exceeded the maximum execution time of ${spec.timeoutMinutes} minutes.` };
238 }
239 const outputs = this.jobOutputs(top);
240 const completion: JobCompletion = { conclusion, outputs };
241 const summary = this.summaries.filter((s) => s.trim() !== "").join("\n");
242 if (summary) completion.summary = this.masker.mask(summary);
243 if (conclusion === "failure" && this.firstFailure) completion.failure = { ...this.firstFailure, message: this.masker.mask(this.firstFailure.message) };
244 if (conclusion === "cancelled") completion.failure = { message: "The job was cancelled." };
245 if (this.replacing && conclusion !== "success") completion.replaced = true;
246 const stolen = this.stolenShare();
247 if (stolen !== null) this.logger.line(-1, `Host: ${stolen}% of the vCPUs' time went to other work on the host (steal)`);
248 this.logger.line(-1, `Job completed with conclusion: ${conclusion}`);
249 return completion;
250 }
251
252 /** The share of the vCPUs' time since the job started that the hypervisor gave to other work, in percent. */
253 private stolenShare(): number | null {
254 const end = this.cpuAtStart && cpuTimes();
255 if (!this.cpuAtStart || !end || end.total <= this.cpuAtStart.total) return null;
256 return Math.round((100 * (end.steal - this.cpuAtStart.steal)) / (end.total - this.cpuAtStart.total));
257 }
258
259 // ------------------------------------------------------------ setup
260
261 private async setup(): Promise<void> {
262 const spec = this.spec;
263 await mkdir(this.workspace, { recursive: true });
264 await mkdir(this.fileCmdDir, { recursive: true });
265 await mkdir(this.toolCache, { recursive: true });
266 await mkdir(this.actionsDir, { recursive: true });
267 await mkdir(path.dirname(this.eventPath), { recursive: true });
268 const g = spec.github ?? {};
269 const refName = String(g.ref_name ?? spec.ref.replace(/^refs\/(heads|tags)\//, ""));
270 const refType = String(g.ref_type ?? (spec.ref.startsWith("refs/tags/") ? "tag" : "branch"));
271 const server = spec.apiUrl.replace(/\/$/, "");
272 const repoFull = `${spec.repo.owner}/${spec.repo.name}`;
273 this.githubCtx = {
274 repository: repoFull,
275 repository_owner: spec.repo.owner,
276 sha: spec.sha,
277 ref: spec.ref,
278 ref_name: refName,
279 ref_type: refType,
280 run_id: spec.runId,
281 run_number: g.run_number ?? "1",
282 run_attempt: g.run_attempt ?? "1",
283 job: spec.jobKey,
284 workflow: spec.workflowPath,
285 event_name: "push",
286 event: {},
287 actor: "diffinery",
288 server_url: server,
289 api_url: `${server}/api/v3`,
290 graphql_url: `${server}/api/graphql`,
291 ...g,
292 workspace: this.workspace,
293 token: spec.token,
294 action: "",
295 action_path: "",
296 };
297 await writeFile(this.eventPath, JSON.stringify(this.githubCtx.event ?? {}, null, 2));
298 const str = (v: unknown) => (v === undefined || v === null ? "" : String(v));
299 const d: Record<string, string> = {
300 CI: "true",
301 GITHUB_ACTIONS: "true",
302 DIFFINERY: "true",
303 GITHUB_REPOSITORY: repoFull,
304 GITHUB_REPOSITORY_OWNER: spec.repo.owner,
305 GITHUB_SHA: spec.sha,
306 GITHUB_REF: spec.ref,
307 GITHUB_REF_NAME: refName,
308 GITHUB_REF_TYPE: refType,
309 GITHUB_HEAD_REF: str(g.head_ref),
310 GITHUB_BASE_REF: str(g.base_ref),
311 GITHUB_RUN_ID: str(this.githubCtx.run_id),
312 GITHUB_RUN_NUMBER: str(this.githubCtx.run_number),
313 GITHUB_RUN_ATTEMPT: str(this.githubCtx.run_attempt),
314 GITHUB_JOB: spec.jobKey,
315 GITHUB_ACTOR: str(this.githubCtx.actor),
316 GITHUB_TRIGGERING_ACTOR: str(g.triggering_actor ?? this.githubCtx.actor),
317 GITHUB_EVENT_NAME: str(this.githubCtx.event_name),
318 GITHUB_EVENT_PATH: this.eventPath,
319 GITHUB_SERVER_URL: server,
320 GITHUB_API_URL: `${server}/api/v3`,
321 GITHUB_GRAPHQL_URL: `${server}/api/graphql`,
322 // GitHub Enterprise's names for the same two URLs. Tools such as super-linter build api.github.com from a
323 // default domain unless these are set, and would send the job's token there.
324 GITHUB_CUSTOM_API_URL: `${server}/api/v3`,
325 GITHUB_CUSTOM_SERVER_URL: server,
326 GITHUB_WORKFLOW: str(g.workflow ?? spec.workflowPath),
327 GITHUB_WORKFLOW_REF: str(g.workflow_ref ?? `${repoFull}/${spec.workflowPath}@${spec.ref}`),
328 GITHUB_WORKSPACE: this.workspace,
329 GITHUB_RETENTION_DAYS: "90",
330 RUNNER_OS: "Linux",
331 RUNNER_ARCH: runnerArch(),
332 RUNNER_NAME: "diffinery",
333 RUNNER_ENVIRONMENT: "diffinery-hosted",
334 RUNNER_TEMP: this.tempDir,
335 RUNNER_TOOL_CACHE: this.toolCache,
336 RUNNER_WORKSPACE: path.dirname(this.workspace),
337 AGENT_TOOLSDIRECTORY: this.toolCache,
338 // What hosted ubuntu-24.04 runners report; setup-* actions key tool and dependency caches on it.
339 ImageOS: process.env.ImageOS ?? "ubuntu24",
340 ImageVersion: process.env.ImageVersion ?? process.env.DIFFINERY_IMAGE_VERSION ?? "20250101.1",
341 };
342 if (this.debug || this.secrets.ACTIONS_RUNNER_DEBUG === "true" || spec.vars?.ACTIONS_RUNNER_DEBUG === "true") d.RUNNER_DEBUG = "1";
343 if (spec.runtime) {
344 // The Actions runtime services (cache, artifacts), scoped to this job and expiring with it.
345 this.runtimeEnv = {
346 ACTIONS_RUNTIME_TOKEN: spec.runtime.token,
347 ACTIONS_RESULTS_URL: spec.runtime.resultsUrl,
348 ACTIONS_CACHE_URL: spec.runtime.cacheUrl,
349 ACTIONS_RUNTIME_URL: spec.runtime.runtimeUrl,
350 ACTIONS_CACHE_SERVICE_V2: "true",
351 };
352 }
353 if (spec.idToken && this.api.online) {
354 // @actions/core appends `&audience=...`, so the URL must already carry a query string.
355 d.ACTIONS_ID_TOKEN_REQUEST_URL = `${this.api.url("/oidc")}?api-version=2.0`;
356 d.ACTIONS_ID_TOKEN_REQUEST_TOKEN = spec.token;
357 }
358 this.defaultEnv = d;
359 this.logger.line(-1, `Diffinery runner: job ${spec.jobKey} (${spec.name}) for ${repoFull}@${spec.sha.slice(0, 12)}`);
360 const where = runnerInfo();
361 if (Object.keys(where).length) this.logger.line(-1, `Runner: ${[where.image && `image ${where.image}`, where.location && `in ${where.location}`, where.instance && `container ${where.instance}`].filter(Boolean).join(", ")}`);
362 if (spec.runnerSize) this.logger.line(-1, spec.runnerSize);
363 if (where.cpu) {
364 this.logger.line(-1, `Host: ${where.cpu}`);
365 this.cpuAtStart = cpuTimes();
366 }
367 this.logger.line(-1, `Workspace: ${this.workspace}`);
368 // job-level env
369 const ctx = this.contexts({ steps: {}, inputs: spec.inputs ?? {}, failed: false, inheritedEnv: {}, composite: false, depth: 0 }, {});
370 for (const [k, v] of Object.entries(spec.env ?? {})) {
371 this.jobEnv[k] = this.interp(String(v ?? ""), ctx);
372 }
373 }
374
375 // ------------------------------------------------------------ containers
376
377 private evalContainer(spec: ContainerSpec, ctx: Record<string, unknown>): ContainerSpec {
378 const i = (v: unknown) => this.interp(v === undefined || v === null ? "" : String(v), ctx);
379 const out: ContainerSpec = { image: i(spec.image).trim() };
380 if (spec.credentials) out.credentials = { username: i(spec.credentials.username), password: i(spec.credentials.password) };
381 if (spec.env) out.env = Object.fromEntries(Object.entries(spec.env).map(([k, v]) => [k, i(v)]));
382 if (spec.ports) out.ports = spec.ports.map((p) => i(p)).filter(Boolean);
383 if (spec.volumes) out.volumes = spec.volumes.map((v) => i(v)).filter(Boolean);
384 if (spec.options) out.options = i(spec.options);
385 return out;
386 }
387
388 /** Starts service containers and the job container, like GitHub's "Initialize containers". */
389 private async initContainers(top: Scope): Promise<void> {
390 const spec = this.spec;
391 if (!spec.container && !Object.keys(spec.services ?? {}).length) return;
392 const ctx = this.contexts(top, { ...this.jobEnv });
393 const container = spec.container ? this.evalContainer(spec.container, ctx) : null;
394 // A service whose image evaluates to an empty string is skipped (GitHub does the same).
395 const services = Object.entries(spec.services ?? {})
396 .map(([k, s]) => [k, this.evalContainer(s, ctx)] as const)
397 .filter(([, s]) => s.image);
398 if (!container?.image && !services.length) return;
399 const io: StepIO = { logIndex: -1, outputs: {}, state: {} };
400 this.logger.line(-1, "##[group]Initialize containers");
401 try {
402 await this.docker.ensure(io, container?.image ? "Job containers (jobs.<id>.container)" : "Service containers (jobs.<id>.services)");
403 for (const [key, s] of services) await this.docker.startService(io, key, s);
404 if (container?.image) await this.docker.startJobContainer(io, container);
405 } finally {
406 this.logger.line(-1, "##[endgroup]");
407 }
408 }
409
410 /** Wraps a step process so it runs in the job container, when there is one. */
411 containerWrap(): Wrap | undefined {
412 return this.docker.execWrap();
413 }
414
415 /** The node binary JavaScript actions run with (the runner's own, mounted into a job container). */
416 nodePath(): string {
417 return this.docker.container ? "/__e/node" : process.execPath;
418 }
419
420 // ------------------------------------------------------------ contexts
421
422 statusFns(scope: Scope): StatusFns {
423 return {
424 success: () => !scope.failed && this.stopping === null,
425 failure: () => scope.failed,
426 cancelled: () => this.stopping !== null,
427 always: () => true,
428 };
429 }
430
431 extra(): { hashFiles: (...p: string[]) => string } {
432 return { hashFiles: (...patterns: string[]) => hashFiles(this.workspace, patterns) };
433 }
434
435 /** Env context visible to a step before its own `env:` is applied. */
436 baseEnvContext(scope: Scope): Record<string, string> {
437 return { ...this.jobEnv, ...this.envAccum, ...scope.inheritedEnv };
438 }
439
440 contexts(scope: Scope, env: Record<string, string>): Record<string, unknown> {
441 const spec = this.spec;
442 const github = { ...this.githubCtx };
443 if (scope.action) {
444 github.action_path = scope.action.path;
445 github.action_repository = scope.action.repository;
446 github.action_ref = scope.action.ref;
447 }
448 return {
449 github,
450 env,
451 vars: spec.vars ?? {},
452 secrets: this.secrets,
453 matrix: spec.matrix ?? {},
454 needs: spec.needs ?? {},
455 steps: scope.steps,
456 runner: {
457 os: "Linux",
458 arch: runnerArch(),
459 name: "diffinery",
460 temp: this.tempDir,
461 tool_cache: this.toolCache,
462 workspace: path.dirname(this.workspace),
463 debug: this.debug ? "1" : "",
464 environment: "diffinery-hosted",
465 },
466 inputs: scope.inputs,
467 job: {
468 status: this.stopping ? "cancelled" : scope.failed ? "failure" : "success",
469 container: this.docker.container ? { id: this.docker.container.id, network: this.docker.container.network } : {},
470 services: Object.fromEntries(Object.entries(this.docker.services).map(([k, v]) => [k, { id: v.id, network: v.network, ports: v.ports }])),
471 },
472 strategy: spec.strategy ?? {},
473 };
474 }
475
476 interp(template: string, ctx: Record<string, unknown>, scope?: Scope): string {
477 if (!template.includes("${{")) return template;
478 const status = scope ? this.statusFns(scope) : undefined;
479 return interpolate(template, ctx, status, this.extra());
480 }
481
482 evalIf(cond: string | undefined, ctx: Record<string, unknown>, scope: Scope): boolean {
483 return evaluateIf(cond, ctx, this.statusFns(scope), this.extra());
484 }
485
486 evalExpr(expr: string, ctx: Record<string, unknown>, scope: Scope): unknown {
487 return evaluate(expr, ctx, this.statusFns(scope), this.extra());
488 }
489
490 /**
491 * Layers workflow env over the runner's defaults. Like GitHub, workflows can
492 * override defaults such as CI or DIFFINERY, but not GITHUB_* or RUNNER_*.
493 */
494 withDefaults(envCtx: Record<string, string>): Record<string, string> {
495 const env = { ...this.defaultEnv, ...envCtx };
496 for (const [k, v] of Object.entries(this.defaultEnv)) if (/^(GITHUB|RUNNER)_/.test(k)) env[k] = v;
497 return env;
498 }
499
500 /** Builds the environment for a child process. */
501 processEnv(envCtx: Record<string, string>, extra: Record<string, string> = {}): NodeJS.ProcessEnv {
502 const env: NodeJS.ProcessEnv = { ...this.baseEnv, ...this.withDefaults(envCtx), ...extra };
503 const basePath = envCtx.PATH ?? this.baseEnv.PATH ?? "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
504 env.PATH = [...this.pathAccum, basePath].filter(Boolean).join(path.delimiter);
505 return env;
506 }
507
508 // ------------------------------------------------------------ steps
509
510 /**
511 * Evaluates `if`, env, name; runs the step; updates the scope's steps
512 * context and failure state.
513 */
514 async executeStep(step: StepSpec, scope: Scope, logIndex: number, onStart?: (name: string) => Promise<void>): Promise<StepResult & { name: string }> {
515 const baseEnv = this.baseEnvContext(scope);
516 let ctx = this.contexts(scope, baseEnv);
517 let name = defaultStepName(step);
518 try {
519 name = step.name !== undefined ? this.interp(String(step.name), ctx, scope) : name;
520 } catch {
521 /* keep default */
522 }
523 const id = step.id;
524 const record = (outcome: Outcome, conclusion: Outcome, outputs: Record<string, string>) => {
525 if (id) scope.steps[id] = { outputs, outcome, conclusion };
526 };
527
528 let run: boolean;
529 try {
530 run = evaluateIf(step.if, ctx, this.statusFns(scope), this.extra());
531 } catch (e) {
532 this.logger.line(logIndex, `##[error]Error evaluating 'if' condition: ${errMsg(e)}`);
533 this.noteFailure(logIndex, `Error evaluating 'if' condition of step '${name}': ${errMsg(e)}`);
534 scope.failed = true;
535 record("failure", "failure", {});
536 return { outcome: "failure", conclusion: "failure", outputs: {}, name };
537 }
538 if (!run) {
539 if (scope.depth > 0) this.logger.line(logIndex, `Skipping step '${name}' (condition not met)`);
540 record("skipped", "skipped", {});
541 return { outcome: "skipped", conclusion: "skipped", outputs: {}, name };
542 }
543 await onStart?.(name);
544 if (scope.depth === 0) await this.prefetch.wait(logIndex, (m) => this.logger.line(logIndex, m));
545
546 const io: StepIO = { logIndex, outputs: {}, state: {} };
547 let outcome: Outcome = "success";
548 let continueOnError = false;
549 try {
550 continueOnError = this.evalBoolish(step["continue-on-error"], ctx, scope);
551 const stepEnv: Record<string, string> = {};
552 const envCtx = { ...baseEnv };
553 ctx = this.contexts(scope, envCtx);
554 for (const [k, v] of Object.entries(step.env ?? {})) {
555 stepEnv[k] = this.interp(String(v ?? ""), ctx, scope);
556 envCtx[k] = stepEnv[k]!;
557 }
558 const timeoutMin = this.evalNumber(step["timeout-minutes"], ctx, scope);
559 const timeoutMs = timeoutMin > 0 ? timeoutMin * 60_000 : 0;
560 if (step.run !== undefined) {
561 await runScript(this, { step, scope, ctx, envCtx, io, timeoutMs, name });
562 } else if (step.uses) {
563 await runAction(this, { step, scope, ctx, envCtx, io, timeoutMs, name });
564 } else {
565 throw new StepFailure("Step has neither `run` nor `uses`.");
566 }
567 if (this.stopping) outcome = "cancelled";
568 } catch (e) {
569 if (this.stopping) {
570 outcome = "cancelled";
571 } else {
572 outcome = "failure";
573 const msg = errMsg(e);
574 if (!(e instanceof StepFailure && (e as StepFailure & { logged?: boolean }).logged)) {
575 this.logger.line(logIndex, `##[error]${msg}`);
576 this.addAnnotation(logIndex, { level: "error", message: msg });
577 }
578 io.reason ??= msg;
579 }
580 }
581
582 let conclusion: Outcome = outcome;
583 if (outcome === "failure") {
584 if (continueOnError) {
585 conclusion = "success";
586 this.logger.line(logIndex, "##[warning]Step failed but continue-on-error is set; continuing.");
587 } else {
588 scope.failed = true;
589 this.noteFailure(logIndex, io.reason);
590 }
591 }
592 record(outcome, conclusion, io.outputs);
593 return { outcome, conclusion, outputs: io.outputs, name };
594 }
595
596 private evalBoolish(v: unknown, ctx: Record<string, unknown>, scope: Scope): boolean {
597 if (v === undefined || v === null || v === false) return false;
598 if (v === true) return true;
599 let s = String(v).trim();
600 if (s.includes("${{")) s = this.interp(s, ctx, scope);
601 return s === "true";
602 }
603
604 private evalNumber(v: unknown, ctx: Record<string, unknown>, scope: Scope): number {
605 if (v === undefined || v === null || v === "") return 0;
606 if (typeof v === "number") return v;
607 let s = String(v);
608 if (s.includes("${{")) s = this.interp(s, ctx, scope);
609 const n = Number(s);
610 return Number.isFinite(n) ? n : 0;
611 }
612
613 addAnnotation(logIndex: number, a: Annotation): void {
614 let list = this.stepErrors.get(logIndex);
615 if (!list) this.stepErrors.set(logIndex, (list = []));
616 list.push(a);
617 }
618
619 private noteFailure(logIndex: number, reason?: string): void {
620 if (this.firstFailure) return;
621 const errs = (this.stepErrors.get(logIndex) ?? []).filter((a) => a.level === "error");
622 // prefer annotations emitted by the step itself over our generic "exit code" message
623 const userErr = [...errs].reverse().find((a) => a.message !== reason);
624 let message: string;
625 if (userErr) {
626 const loc = userErr.file ? `${userErr.file}${userErr.line ? `:${userErr.line}` : ""}: ` : "";
627 message = `${loc}${userErr.title ? `${userErr.title}: ` : ""}${userErr.message}`;
628 } else {
629 const tail = this.logger.tail(logIndex, 20).filter((l) => !l.startsWith("##[error]"));
630 message = [reason ?? "Step failed", ...(tail.length ? ["", ...tail] : [])].join("\n");
631 }
632 this.firstFailure = { step: logIndex >= 0 ? logIndex : undefined, message };
633 if (this.firstFailure.step === undefined) delete this.firstFailure.step;
634 }
635
636 /**
637 * Runs a process for a step with fresh file-command files, interpreting
638 * workflow commands, then applies GITHUB_ENV/PATH/OUTPUT/STATE/SUMMARY.
639 */
640 async runStepProcess(
641 argv: string[],
642 o: {
643 cwd: string;
644 envCtx: Record<string, string>;
645 io: StepIO;
646 timeoutMs?: number;
647 extraEnv?: Record<string, string>;
648 timeoutLabel?: string;
649 /** Run the process somewhere else (the job container, or a Docker action's container). */
650 wrap?: Wrap;
651 },
652 ): Promise<ExecResult> {
653 const id = randomUUID();
654 const files = {
655 GITHUB_ENV: path.join(this.fileCmdDir, `set_env_${id}`),
656 GITHUB_PATH: path.join(this.fileCmdDir, `add_path_${id}`),
657 GITHUB_OUTPUT: path.join(this.fileCmdDir, `set_output_${id}`),
658 GITHUB_STATE: path.join(this.fileCmdDir, `save_state_${id}`),
659 GITHUB_STEP_SUMMARY: path.join(this.fileCmdDir, `step_summary_${id}`),
660 };
661 await mkdir(this.fileCmdDir, { recursive: true });
662 await Promise.all(Object.values(files).map((f) => writeFile(f, "")));
663 const proc = this.processor(o.io);
664 if (!existsSync(o.cwd)) {
665 throw new StepFailure(`An error occurred trying to start process '${argv[0]}' with working directory '${o.cwd}'. No such file or directory`);
666 }
667 let cmd = argv;
668 let cwd = o.cwd;
669 let env = this.processEnv(o.envCtx, { ...(o.extraEnv ?? {}), ...files });
670 if (o.wrap) ({ argv: cmd, cwd, env } = o.wrap(argv, { ...this.withDefaults(o.envCtx), ...(o.extraEnv ?? {}), ...files }, o.cwd));
671 const res = await exec(cmd[0]!, cmd.slice(1), {
672 cwd,
673 env,
674 timeoutMs: o.timeoutMs,
675 onLine: (l) => proc.handle(l),
676 onSpawn: (c) => {
677 this.children.add(c);
678 c.once("close", () => this.children.delete(c));
679 },
680 });
681 await this.applyFileCommands(files, o.io);
682 if (res.signal && this.replacing && !this.stopping) {
683 // The platform's SIGTERM (a rollout, or a move) reaches every process in the container, not only the agent. The job
684 // can't succeed now, so stop it and report at once: Diffinery starts it again on a new runner.
685 const msg = "The platform stopped this step's processes while stopping the runner.";
686 this.logger.line(o.io.logIndex, `##[error]${msg}`);
687 this.addAnnotation(o.io.logIndex, { level: "error", message: msg });
688 this.cancel("cancelled");
689 }
690 if (res.timedOut) {
691 const mins = (o.timeoutMs ?? 0) / 60000;
692 const msg = `The ${o.timeoutLabel ?? "step"} has timed out after ${Number(mins.toFixed(2))} minutes.`;
693 this.logger.line(o.io.logIndex, `##[error]${msg}`);
694 this.addAnnotation(o.io.logIndex, { level: "error", message: msg });
695 o.io.reason = msg;
696 }
697 return res;
698 }
699
700 processor(io: StepIO): OutputProcessor {
701 return new OutputProcessor(this.logger, this.masker, io, {
702 debug: this.debug,
703 onAnnotation: (a) => this.addAnnotation(io.logIndex, a),
704 });
705 }
706
707 private async applyFileCommands(files: Record<string, string>, io: StepIO): Promise<void> {
708 const read = async (f: string) => {
709 try {
710 return await readFile(f, "utf8");
711 } catch {
712 return "";
713 }
714 };
715 const [envC, pathC, outC, stateC, sumC] = await Promise.all([
716 read(files.GITHUB_ENV!),
717 read(files.GITHUB_PATH!),
718 read(files.GITHUB_OUTPUT!),
719 read(files.GITHUB_STATE!),
720 read(files.GITHUB_STEP_SUMMARY!),
721 ]);
722 const safe = (label: string, fn: () => void) => {
723 try {
724 fn();
725 } catch (e) {
726 this.logger.line(io.logIndex, `##[error]Unable to process file command '${label}' successfully: ${errMsg(e)}`);
727 this.addAnnotation(io.logIndex, { level: "error", message: `Unable to process file command '${label}': ${errMsg(e)}` });
728 }
729 };
730 safe("env", () => {
731 for (const [k, v] of parseKeyValueFile(envC)) {
732 if (k === "NODE_OPTIONS" && /--require|-r\b/.test(v)) continue;
733 this.envAccum[k] = v;
734 }
735 });
736 safe("path", () => {
737 for (const p of parsePathFile(pathC)) this.addPath(p);
738 });
739 safe("output", () => {
740 for (const [k, v] of parseKeyValueFile(outC)) io.outputs[k] = v;
741 });
742 safe("state", () => {
743 for (const [k, v] of parseKeyValueFile(stateC)) io.state[k] = v;
744 });
745 if (sumC.trim()) this.summaries.push(sumC);
746 }
747
748 addPath(p: string): void {
749 this.pathAccum = [p, ...this.pathAccum.filter((x) => x !== p)];
750 }
751
752 /** Runs an internal tool (git, tar, ...) streaming its output into the step log. */
753 async tool(cmd: string, args: string[], o: { io: StepIO; cwd?: string; env?: NodeJS.ProcessEnv; capture?: boolean; silent?: boolean; input?: string | Readable }): Promise<ExecResult> {
754 return exec(cmd, args, {
755 cwd: o.cwd ?? this.workspace,
756 env: o.env ?? this.processEnv(this.baseEnvContext({ steps: {}, inputs: {}, failed: false, inheritedEnv: {}, composite: false, depth: 0 })),
757 capture: o.capture,
758 input: o.input,
759 onLine: o.silent ? undefined : (l) => this.logger.line(o.io.logIndex, l),
760 onSpawn: (c) => {
761 this.children.add(c);
762 c.once("close", () => this.children.delete(c));
763 },
764 });
765 }
766
767 registerPost(p: PostStep): void {
768 this.posts.push(p);
769 }
770
771 private async runPosts(top: Scope): Promise<void> {
772 const posts = [...this.posts].reverse();
773 let index = this.spec.steps.length;
774 for (const p of posts) {
775 const logIndex = index++;
776 if (this.stopping) break;
777 let ok: boolean;
778 try {
779 ok = evaluateIf(p.condition, this.contexts(top, this.baseEnvContext(top)), this.statusFns(top), this.extra());
780 } catch {
781 ok = false;
782 }
783 if (!ok) continue;
784 const startedAt = nowIso();
785 await this.report(logIndex, { status: "in_progress", name: p.name, startedAt });
786 let conclusion: Conclusion = "success";
787 try {
788 await p.run(logIndex);
789 } catch (e) {
790 conclusion = "failure";
791 const msg = errMsg(e);
792 if (!(e instanceof StepFailure && (e as StepFailure & { logged?: boolean }).logged)) {
793 this.logger.line(logIndex, `##[error]${msg}`);
794 this.addAnnotation(logIndex, { level: "error", message: msg });
795 }
796 top.failed = true;
797 this.noteFailure(logIndex, msg);
798 }
799 if (this.stopping) conclusion = "cancelled";
800 await this.report(logIndex, { status: "completed", conclusion, name: p.name, startedAt, completedAt: nowIso() });
801 }
802 }
803
804 private jobOutputs(top: Scope): Record<string, string> {
805 const out: Record<string, string> = {};
806 const ctx = this.contexts(top, this.baseEnvContext(top));
807 for (const [k, expr] of Object.entries(this.spec.outputs ?? {})) {
808 try {
809 const v = this.interp(String(expr), ctx, top);
810 if (this.masker.containsSecret(v)) {
811 this.logger.line(-1, `##[warning]Skip output '${k}' since it may contain secret.`);
812 continue;
813 }
814 out[k] = v;
815 } catch (e) {
816 this.logger.line(-1, `##[warning]Failed to evaluate job output '${k}': ${errMsg(e)}`);
817 }
818 }
819 return out;
820 }
821
822 private async report(index: number, r: StepReport): Promise<void> {
823 try {
824 await this.api.postStep(index, { ...r, name: this.masker.mask(r.name) });
825 } catch (e) {
826 this.logger.line(-1, `##[warning]Failed to report step ${index}: ${errMsg(e)}`);
827 }
828 }
829}
830
831export function errMsg(e: unknown): string {
832 return e instanceof Error ? e.message : String(e);
833}
834
835export function failure(message: string, logged = false): StepFailure {
836 const f = new StepFailure(message) as StepFailure & { logged?: boolean };
837 f.logged = logged;
838 return f;
839}
840
841export function defaultStepName(step: StepSpec): string {
842 if (step.name) return String(step.name);
843 if (step.uses) return `Run ${step.uses}`;
844 if (step.run) return `Run ${String(step.run).trim().split("\n")[0]}`;
845 return "Step";
846}
847
848function safeName(step: StepSpec, fallback: string): string {
849 return step.name && !String(step.name).includes("${{") ? String(step.name) : fallback;
850}