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.

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