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.

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