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.

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