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.

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