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.

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