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.

790 lines · 31.3 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_WORKFLOW: str(g.workflow ?? spec.workflowPath),
283 GITHUB_WORKFLOW_REF: str(g.workflow_ref ?? `${repoFull}/${spec.workflowPath}@${spec.ref}`),
284 GITHUB_WORKSPACE: this.workspace,
285 GITHUB_RETENTION_DAYS: "90",
286 RUNNER_OS: "Linux",
287 RUNNER_ARCH: runnerArch(),
288 RUNNER_NAME: "diffinery",
289 RUNNER_ENVIRONMENT: "diffinery-hosted",
290 RUNNER_TEMP: this.tempDir,
291 RUNNER_TOOL_CACHE: this.toolCache,
292 RUNNER_WORKSPACE: path.dirname(this.workspace),
293 AGENT_TOOLSDIRECTORY: this.toolCache,
294 // What hosted ubuntu-24.04 runners report; setup-* actions key tool and dependency caches on it.
295 ImageOS: process.env.ImageOS ?? "ubuntu24",
296 ImageVersion: process.env.ImageVersion ?? process.env.DIFFINERY_IMAGE_VERSION ?? "20250101.1",
297 };
298 if (this.debug || this.secrets.ACTIONS_RUNNER_DEBUG === "true" || spec.vars?.ACTIONS_RUNNER_DEBUG === "true") d.RUNNER_DEBUG = "1";
299 if (spec.runtime) {
300 // The Actions runtime services (cache, artifacts), scoped to this job and expiring with it.
301 this.runtimeEnv = {
302 ACTIONS_RUNTIME_TOKEN: spec.runtime.token,
303 ACTIONS_RESULTS_URL: spec.runtime.resultsUrl,
304 ACTIONS_CACHE_URL: spec.runtime.cacheUrl,
305 ACTIONS_RUNTIME_URL: spec.runtime.runtimeUrl,
306 ACTIONS_CACHE_SERVICE_V2: "true",
307 };
308 }
309 if (spec.idToken && this.api.online) {
310 // @actions/core appends `&audience=...`, so the URL must already carry a query string.
311 d.ACTIONS_ID_TOKEN_REQUEST_URL = `${this.api.url("/oidc")}?api-version=2.0`;
312 d.ACTIONS_ID_TOKEN_REQUEST_TOKEN = spec.token;
313 }
314 this.defaultEnv = d;
315 this.logger.line(-1, `Diffinery runner: job ${spec.jobKey} (${spec.name}) for ${repoFull}@${spec.sha.slice(0, 12)}`);
316 this.logger.line(-1, `Workspace: ${this.workspace}`);
317 // job-level env
318 const ctx = this.contexts({ steps: {}, inputs: spec.inputs ?? {}, failed: false, inheritedEnv: {}, composite: false, depth: 0 }, {});
319 for (const [k, v] of Object.entries(spec.env ?? {})) {
320 this.jobEnv[k] = this.interp(String(v ?? ""), ctx);
321 }
322 }
323
324 // ------------------------------------------------------------ containers
325
326 private evalContainer(spec: ContainerSpec, ctx: Record<string, unknown>): ContainerSpec {
327 const i = (v: unknown) => this.interp(v === undefined || v === null ? "" : String(v), ctx);
328 const out: ContainerSpec = { image: i(spec.image).trim() };
329 if (spec.credentials) out.credentials = { username: i(spec.credentials.username), password: i(spec.credentials.password) };
330 if (spec.env) out.env = Object.fromEntries(Object.entries(spec.env).map(([k, v]) => [k, i(v)]));
331 if (spec.ports) out.ports = spec.ports.map((p) => i(p)).filter(Boolean);
332 if (spec.volumes) out.volumes = spec.volumes.map((v) => i(v)).filter(Boolean);
333 if (spec.options) out.options = i(spec.options);
334 return out;
335 }
336
337 /** Starts service containers and the job container, like GitHub's "Initialize containers". */
338 private async initContainers(top: Scope): Promise<void> {
339 const spec = this.spec;
340 if (!spec.container && !Object.keys(spec.services ?? {}).length) return;
341 const ctx = this.contexts(top, { ...this.jobEnv });
342 const container = spec.container ? this.evalContainer(spec.container, ctx) : null;
343 // A service whose image evaluates to an empty string is skipped (GitHub does the same).
344 const services = Object.entries(spec.services ?? {})
345 .map(([k, s]) => [k, this.evalContainer(s, ctx)] as const)
346 .filter(([, s]) => s.image);
347 if (!container?.image && !services.length) return;
348 const io: StepIO = { logIndex: -1, outputs: {}, state: {} };
349 this.logger.line(-1, "##[group]Initialize containers");
350 try {
351 await this.docker.ensure(io, container?.image ? "Job containers (jobs.<id>.container)" : "Service containers (jobs.<id>.services)");
352 for (const [key, s] of services) await this.docker.startService(io, key, s);
353 if (container?.image) await this.docker.startJobContainer(io, container);
354 } finally {
355 this.logger.line(-1, "##[endgroup]");
356 }
357 }
358
359 /** Wraps a step process so it runs in the job container, when there is one. */
360 containerWrap(): Wrap | undefined {
361 return this.docker.execWrap();
362 }
363
364 /** The node binary JavaScript actions run with (the runner's own, mounted into a job container). */
365 nodePath(): string {
366 return this.docker.container ? "/__e/node" : process.execPath;
367 }
368
369 // ------------------------------------------------------------ contexts
370
371 statusFns(scope: Scope): StatusFns {
372 return {
373 success: () => !scope.failed && this.stopping === null,
374 failure: () => scope.failed,
375 cancelled: () => this.stopping !== null,
376 always: () => true,
377 };
378 }
379
380 extra(): { hashFiles: (...p: string[]) => string } {
381 return { hashFiles: (...patterns: string[]) => hashFiles(this.workspace, patterns) };
382 }
383
384 /** Env context visible to a step before its own `env:` is applied. */
385 baseEnvContext(scope: Scope): Record<string, string> {
386 return { ...this.jobEnv, ...this.envAccum, ...scope.inheritedEnv };
387 }
388
389 contexts(scope: Scope, env: Record<string, string>): Record<string, unknown> {
390 const spec = this.spec;
391 const github = { ...this.githubCtx };
392 if (scope.action) {
393 github.action_path = scope.action.path;
394 github.action_repository = scope.action.repository;
395 github.action_ref = scope.action.ref;
396 }
397 return {
398 github,
399 env,
400 vars: spec.vars ?? {},
401 secrets: this.secrets,
402 matrix: spec.matrix ?? {},
403 needs: spec.needs ?? {},
404 steps: scope.steps,
405 runner: {
406 os: "Linux",
407 arch: runnerArch(),
408 name: "diffinery",
409 temp: this.tempDir,
410 tool_cache: this.toolCache,
411 workspace: path.dirname(this.workspace),
412 debug: this.debug ? "1" : "",
413 environment: "diffinery-hosted",
414 },
415 inputs: scope.inputs,
416 job: {
417 status: this.stopping ? "cancelled" : scope.failed ? "failure" : "success",
418 container: this.docker.container ? { id: this.docker.container.id, network: this.docker.container.network } : {},
419 services: Object.fromEntries(Object.entries(this.docker.services).map(([k, v]) => [k, { id: v.id, network: v.network, ports: v.ports }])),
420 },
421 strategy: spec.strategy ?? {},
422 };
423 }
424
425 interp(template: string, ctx: Record<string, unknown>, scope?: Scope): string {
426 if (!template.includes("${{")) return template;
427 const status = scope ? this.statusFns(scope) : undefined;
428 return interpolate(template, ctx, status, this.extra());
429 }
430
431 evalIf(cond: string | undefined, ctx: Record<string, unknown>, scope: Scope): boolean {
432 return evaluateIf(cond, ctx, this.statusFns(scope), this.extra());
433 }
434
435 evalExpr(expr: string, ctx: Record<string, unknown>, scope: Scope): unknown {
436 return evaluate(expr, ctx, this.statusFns(scope), this.extra());
437 }
438
439 /**
440 * Layers workflow env over the runner's defaults. Like GitHub, workflows can
441 * override defaults such as CI or DIFFINERY, but not GITHUB_* or RUNNER_*.
442 */
443 withDefaults(envCtx: Record<string, string>): Record<string, string> {
444 const env = { ...this.defaultEnv, ...envCtx };
445 for (const [k, v] of Object.entries(this.defaultEnv)) if (/^(GITHUB|RUNNER)_/.test(k)) env[k] = v;
446 return env;
447 }
448
449 /** Builds the environment for a child process. */
450 processEnv(envCtx: Record<string, string>, extra: Record<string, string> = {}): NodeJS.ProcessEnv {
451 const env: NodeJS.ProcessEnv = { ...this.baseEnv, ...this.withDefaults(envCtx), ...extra };
452 const basePath = envCtx.PATH ?? this.baseEnv.PATH ?? "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
453 env.PATH = [...this.pathAccum, basePath].filter(Boolean).join(path.delimiter);
454 return env;
455 }
456
457 // ------------------------------------------------------------ steps
458
459 /**
460 * Evaluates `if`, env, name; runs the step; updates the scope's steps
461 * context and failure state.
462 */
463 async executeStep(step: StepSpec, scope: Scope, logIndex: number, onStart?: (name: string) => Promise<void>): Promise<StepResult & { name: string }> {
464 const baseEnv = this.baseEnvContext(scope);
465 let ctx = this.contexts(scope, baseEnv);
466 let name = defaultStepName(step);
467 try {
468 name = step.name !== undefined ? this.interp(String(step.name), ctx, scope) : name;
469 } catch {
470 /* keep default */
471 }
472 const id = step.id;
473 const record = (outcome: Outcome, conclusion: Outcome, outputs: Record<string, string>) => {
474 if (id) scope.steps[id] = { outputs, outcome, conclusion };
475 };
476
477 let run: boolean;
478 try {
479 run = evaluateIf(step.if, ctx, this.statusFns(scope), this.extra());
480 } catch (e) {
481 this.logger.line(logIndex, `##[error]Error evaluating 'if' condition: ${errMsg(e)}`);
482 this.noteFailure(logIndex, `Error evaluating 'if' condition of step '${name}': ${errMsg(e)}`);
483 scope.failed = true;
484 record("failure", "failure", {});
485 return { outcome: "failure", conclusion: "failure", outputs: {}, name };
486 }
487 if (!run) {
488 if (scope.depth > 0) this.logger.line(logIndex, `Skipping step '${name}' (condition not met)`);
489 record("skipped", "skipped", {});
490 return { outcome: "skipped", conclusion: "skipped", outputs: {}, name };
491 }
492 await onStart?.(name);
493
494 const io: StepIO = { logIndex, outputs: {}, state: {} };
495 let outcome: Outcome = "success";
496 let continueOnError = false;
497 try {
498 continueOnError = this.evalBoolish(step["continue-on-error"], ctx, scope);
499 const stepEnv: Record<string, string> = {};
500 const envCtx = { ...baseEnv };
501 ctx = this.contexts(scope, envCtx);
502 for (const [k, v] of Object.entries(step.env ?? {})) {
503 stepEnv[k] = this.interp(String(v ?? ""), ctx, scope);
504 envCtx[k] = stepEnv[k]!;
505 }
506 const timeoutMin = this.evalNumber(step["timeout-minutes"], ctx, scope);
507 const timeoutMs = timeoutMin > 0 ? timeoutMin * 60_000 : 0;
508 if (step.run !== undefined) {
509 await runScript(this, { step, scope, ctx, envCtx, io, timeoutMs, name });
510 } else if (step.uses) {
511 await runAction(this, { step, scope, ctx, envCtx, io, timeoutMs, name });
512 } else {
513 throw new StepFailure("Step has neither `run` nor `uses`.");
514 }
515 if (this.stopping) outcome = "cancelled";
516 } catch (e) {
517 if (this.stopping) {
518 outcome = "cancelled";
519 } else {
520 outcome = "failure";
521 const msg = errMsg(e);
522 if (!(e instanceof StepFailure && (e as StepFailure & { logged?: boolean }).logged)) {
523 this.logger.line(logIndex, `##[error]${msg}`);
524 this.addAnnotation(logIndex, { level: "error", message: msg });
525 }
526 io.reason ??= msg;
527 }
528 }
529
530 let conclusion: Outcome = outcome;
531 if (outcome === "failure") {
532 if (continueOnError) {
533 conclusion = "success";
534 this.logger.line(logIndex, "##[warning]Step failed but continue-on-error is set; continuing.");
535 } else {
536 scope.failed = true;
537 this.noteFailure(logIndex, io.reason);
538 }
539 }
540 record(outcome, conclusion, io.outputs);
541 return { outcome, conclusion, outputs: io.outputs, name };
542 }
543
544 private evalBoolish(v: unknown, ctx: Record<string, unknown>, scope: Scope): boolean {
545 if (v === undefined || v === null || v === false) return false;
546 if (v === true) return true;
547 let s = String(v).trim();
548 if (s.includes("${{")) s = this.interp(s, ctx, scope);
549 return s === "true";
550 }
551
552 private evalNumber(v: unknown, ctx: Record<string, unknown>, scope: Scope): number {
553 if (v === undefined || v === null || v === "") return 0;
554 if (typeof v === "number") return v;
555 let s = String(v);
556 if (s.includes("${{")) s = this.interp(s, ctx, scope);
557 const n = Number(s);
558 return Number.isFinite(n) ? n : 0;
559 }
560
561 addAnnotation(logIndex: number, a: Annotation): void {
562 let list = this.stepErrors.get(logIndex);
563 if (!list) this.stepErrors.set(logIndex, (list = []));
564 list.push(a);
565 }
566
567 private noteFailure(logIndex: number, reason?: string): void {
568 if (this.firstFailure) return;
569 const errs = (this.stepErrors.get(logIndex) ?? []).filter((a) => a.level === "error");
570 // prefer annotations emitted by the step itself over our generic "exit code" message
571 const userErr = [...errs].reverse().find((a) => a.message !== reason);
572 let message: string;
573 if (userErr) {
574 const loc = userErr.file ? `${userErr.file}${userErr.line ? `:${userErr.line}` : ""}: ` : "";
575 message = `${loc}${userErr.title ? `${userErr.title}: ` : ""}${userErr.message}`;
576 } else {
577 const tail = this.logger.tail(logIndex, 20).filter((l) => !l.startsWith("##[error]"));
578 message = [reason ?? "Step failed", ...(tail.length ? ["", ...tail] : [])].join("\n");
579 }
580 this.firstFailure = { step: logIndex >= 0 ? logIndex : undefined, message };
581 if (this.firstFailure.step === undefined) delete this.firstFailure.step;
582 }
583
584 /**
585 * Runs a process for a step with fresh file-command files, interpreting
586 * workflow commands, then applies GITHUB_ENV/PATH/OUTPUT/STATE/SUMMARY.
587 */
588 async runStepProcess(
589 argv: string[],
590 o: {
591 cwd: string;
592 envCtx: Record<string, string>;
593 io: StepIO;
594 timeoutMs?: number;
595 extraEnv?: Record<string, string>;
596 timeoutLabel?: string;
597 /** Run the process somewhere else (the job container, or a Docker action's container). */
598 wrap?: Wrap;
599 },
600 ): Promise<ExecResult> {
601 const id = randomUUID();
602 const files = {
603 GITHUB_ENV: path.join(this.fileCmdDir, `set_env_${id}`),
604 GITHUB_PATH: path.join(this.fileCmdDir, `add_path_${id}`),
605 GITHUB_OUTPUT: path.join(this.fileCmdDir, `set_output_${id}`),
606 GITHUB_STATE: path.join(this.fileCmdDir, `save_state_${id}`),
607 GITHUB_STEP_SUMMARY: path.join(this.fileCmdDir, `step_summary_${id}`),
608 };
609 await mkdir(this.fileCmdDir, { recursive: true });
610 await Promise.all(Object.values(files).map((f) => writeFile(f, "")));
611 const proc = this.processor(o.io);
612 if (!existsSync(o.cwd)) {
613 throw new StepFailure(`An error occurred trying to start process '${argv[0]}' with working directory '${o.cwd}'. No such file or directory`);
614 }
615 let cmd = argv;
616 let cwd = o.cwd;
617 let env = this.processEnv(o.envCtx, { ...(o.extraEnv ?? {}), ...files });
618 if (o.wrap) ({ argv: cmd, cwd, env } = o.wrap(argv, { ...this.withDefaults(o.envCtx), ...(o.extraEnv ?? {}), ...files }, o.cwd));
619 const res = await exec(cmd[0]!, cmd.slice(1), {
620 cwd,
621 env,
622 timeoutMs: o.timeoutMs,
623 onLine: (l) => proc.handle(l),
624 onSpawn: (c) => {
625 this.children.add(c);
626 c.once("close", () => this.children.delete(c));
627 },
628 });
629 await this.applyFileCommands(files, o.io);
630 if (res.timedOut) {
631 const mins = (o.timeoutMs ?? 0) / 60000;
632 const msg = `The ${o.timeoutLabel ?? "step"} has timed out after ${Number(mins.toFixed(2))} minutes.`;
633 this.logger.line(o.io.logIndex, `##[error]${msg}`);
634 this.addAnnotation(o.io.logIndex, { level: "error", message: msg });
635 o.io.reason = msg;
636 }
637 return res;
638 }
639
640 processor(io: StepIO): OutputProcessor {
641 return new OutputProcessor(this.logger, this.masker, io, {
642 debug: this.debug,
643 onAnnotation: (a) => this.addAnnotation(io.logIndex, a),
644 });
645 }
646
647 private async applyFileCommands(files: Record<string, string>, io: StepIO): Promise<void> {
648 const read = async (f: string) => {
649 try {
650 return await readFile(f, "utf8");
651 } catch {
652 return "";
653 }
654 };
655 const [envC, pathC, outC, stateC, sumC] = await Promise.all([
656 read(files.GITHUB_ENV!),
657 read(files.GITHUB_PATH!),
658 read(files.GITHUB_OUTPUT!),
659 read(files.GITHUB_STATE!),
660 read(files.GITHUB_STEP_SUMMARY!),
661 ]);
662 const safe = (label: string, fn: () => void) => {
663 try {
664 fn();
665 } catch (e) {
666 this.logger.line(io.logIndex, `##[error]Unable to process file command '${label}' successfully: ${errMsg(e)}`);
667 this.addAnnotation(io.logIndex, { level: "error", message: `Unable to process file command '${label}': ${errMsg(e)}` });
668 }
669 };
670 safe("env", () => {
671 for (const [k, v] of parseKeyValueFile(envC)) {
672 if (k === "NODE_OPTIONS" && /--require|-r\b/.test(v)) continue;
673 this.envAccum[k] = v;
674 }
675 });
676 safe("path", () => {
677 for (const p of parsePathFile(pathC)) this.addPath(p);
678 });
679 safe("output", () => {
680 for (const [k, v] of parseKeyValueFile(outC)) io.outputs[k] = v;
681 });
682 safe("state", () => {
683 for (const [k, v] of parseKeyValueFile(stateC)) io.state[k] = v;
684 });
685 if (sumC.trim()) this.summaries.push(sumC);
686 }
687
688 addPath(p: string): void {
689 this.pathAccum = [p, ...this.pathAccum.filter((x) => x !== p)];
690 }
691
692 /** Runs an internal tool (git, tar, ...) streaming its output into the step log. */
693 async tool(cmd: string, args: string[], o: { io: StepIO; cwd?: string; env?: NodeJS.ProcessEnv; capture?: boolean; silent?: boolean; input?: string }): Promise<ExecResult> {
694 return exec(cmd, args, {
695 cwd: o.cwd ?? this.workspace,
696 env: o.env ?? this.processEnv(this.baseEnvContext({ steps: {}, inputs: {}, failed: false, inheritedEnv: {}, composite: false, depth: 0 })),
697 capture: o.capture,
698 input: o.input,
699 onLine: o.silent ? undefined : (l) => this.logger.line(o.io.logIndex, l),
700 onSpawn: (c) => {
701 this.children.add(c);
702 c.once("close", () => this.children.delete(c));
703 },
704 });
705 }
706
707 registerPost(p: PostStep): void {
708 this.posts.push(p);
709 }
710
711 private async runPosts(top: Scope): Promise<void> {
712 const posts = [...this.posts].reverse();
713 let index = this.spec.steps.length;
714 for (const p of posts) {
715 const logIndex = index++;
716 if (this.stopping) break;
717 let ok: boolean;
718 try {
719 ok = evaluateIf(p.condition, this.contexts(top, this.baseEnvContext(top)), this.statusFns(top), this.extra());
720 } catch {
721 ok = false;
722 }
723 if (!ok) continue;
724 const startedAt = nowIso();
725 await this.report(logIndex, { status: "in_progress", name: p.name, startedAt });
726 let conclusion: Conclusion = "success";
727 try {
728 await p.run(logIndex);
729 } catch (e) {
730 conclusion = "failure";
731 const msg = errMsg(e);
732 if (!(e instanceof StepFailure && (e as StepFailure & { logged?: boolean }).logged)) {
733 this.logger.line(logIndex, `##[error]${msg}`);
734 this.addAnnotation(logIndex, { level: "error", message: msg });
735 }
736 top.failed = true;
737 this.noteFailure(logIndex, msg);
738 }
739 if (this.stopping) conclusion = "cancelled";
740 await this.report(logIndex, { status: "completed", conclusion, name: p.name, startedAt, completedAt: nowIso() });
741 }
742 }
743
744 private jobOutputs(top: Scope): Record<string, string> {
745 const out: Record<string, string> = {};
746 const ctx = this.contexts(top, this.baseEnvContext(top));
747 for (const [k, expr] of Object.entries(this.spec.outputs ?? {})) {
748 try {
749 const v = this.interp(String(expr), ctx, top);
750 if (this.masker.containsSecret(v)) {
751 this.logger.line(-1, `##[warning]Skip output '${k}' since it may contain secret.`);
752 continue;
753 }
754 out[k] = v;
755 } catch (e) {
756 this.logger.line(-1, `##[warning]Failed to evaluate job output '${k}': ${errMsg(e)}`);
757 }
758 }
759 return out;
760 }
761
762 private async report(index: number, r: StepReport): Promise<void> {
763 try {
764 await this.api.postStep(index, { ...r, name: this.masker.mask(r.name) });
765 } catch (e) {
766 this.logger.line(-1, `##[warning]Failed to report step ${index}: ${errMsg(e)}`);
767 }
768 }
769}
770
771export function errMsg(e: unknown): string {
772 return e instanceof Error ? e.message : String(e);
773}
774
775export function failure(message: string, logged = false): StepFailure {
776 const f = new StepFailure(message) as StepFailure & { logged?: boolean };
777 f.logged = logged;
778 return f;
779}
780
781export function defaultStepName(step: StepSpec): string {
782 if (step.name) return String(step.name);
783 if (step.uses) return `Run ${step.uses}`;
784 if (step.run) return `Run ${String(step.run).trim().split("\n")[0]}`;
785 return "Step";
786}
787
788function safeName(step: StepSpec, fallback: string): string {
789 return step.name && !String(step.name).includes("${{") ? String(step.name) : fallback;
790}