@softure-ai/ci-usage 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +21 -0
  3. package/README.md +128 -2
  4. package/dist/billing.d.ts +37 -0
  5. package/dist/billing.d.ts.map +1 -0
  6. package/dist/billing.js +83 -0
  7. package/dist/billing.js.map +1 -0
  8. package/dist/cli/command.d.ts +33 -0
  9. package/dist/cli/command.d.ts.map +1 -0
  10. package/dist/cli/command.js +203 -0
  11. package/dist/cli/command.js.map +1 -0
  12. package/dist/cli/main.d.ts +3 -0
  13. package/dist/cli/main.d.ts.map +1 -0
  14. package/dist/cli/main.js +10 -0
  15. package/dist/cli/main.js.map +1 -0
  16. package/dist/collect.d.ts +45 -0
  17. package/dist/collect.d.ts.map +1 -0
  18. package/dist/collect.js +189 -0
  19. package/dist/collect.js.map +1 -0
  20. package/dist/github.d.ts +41 -0
  21. package/dist/github.d.ts.map +1 -0
  22. package/dist/github.js +91 -0
  23. package/dist/github.js.map +1 -0
  24. package/dist/index.d.ts +10 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +11 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/messages/en.d.ts +51 -0
  29. package/dist/messages/en.d.ts.map +1 -0
  30. package/dist/messages/en.js +51 -0
  31. package/dist/messages/en.js.map +1 -0
  32. package/dist/messages/index.d.ts +11 -0
  33. package/dist/messages/index.d.ts.map +1 -0
  34. package/dist/messages/index.js +13 -0
  35. package/dist/messages/index.js.map +1 -0
  36. package/dist/prices.d.ts +32 -0
  37. package/dist/prices.d.ts.map +1 -0
  38. package/dist/prices.js +52 -0
  39. package/dist/prices.js.map +1 -0
  40. package/dist/publish.d.ts +29 -0
  41. package/dist/publish.d.ts.map +1 -0
  42. package/dist/publish.js +91 -0
  43. package/dist/publish.js.map +1 -0
  44. package/dist/report.d.ts +57 -0
  45. package/dist/report.d.ts.map +1 -0
  46. package/dist/report.js +168 -0
  47. package/dist/report.js.map +1 -0
  48. package/dist/runner.d.ts +28 -0
  49. package/dist/runner.d.ts.map +1 -0
  50. package/dist/runner.js +55 -0
  51. package/dist/runner.js.map +1 -0
  52. package/dist/usage.d.ts +67 -0
  53. package/dist/usage.d.ts.map +1 -0
  54. package/dist/usage.js +112 -0
  55. package/dist/usage.js.map +1 -0
  56. package/examples/ci-usage.yml +34 -0
  57. package/package.json +42 -4
  58. package/src/billing.ts +102 -0
  59. package/src/cli/command.ts +212 -0
  60. package/src/cli/main.ts +10 -0
  61. package/src/collect.ts +230 -0
  62. package/src/github.ts +113 -0
  63. package/src/index.ts +10 -0
  64. package/src/messages/en.ts +52 -0
  65. package/src/messages/index.ts +15 -0
  66. package/src/prices.ts +74 -0
  67. package/src/publish.ts +95 -0
  68. package/src/report.ts +215 -0
  69. package/src/runner.ts +64 -0
  70. package/src/usage.ts +192 -0
package/src/collect.ts ADDED
@@ -0,0 +1,230 @@
1
+ // The jobs of every finished workflow run created in a period, read through the Actions API one day at a time.
2
+ import { z } from "zod";
3
+ import type { GithubClient } from "./github.js";
4
+ import type { JobRecord } from "./usage.js";
5
+
6
+ const RUN = z.object({
7
+ id: z.number(),
8
+ name: z.string().nullable().optional(),
9
+ path: z.string(),
10
+ // A run in progress has no conclusion key at all in some answers.
11
+ status: z.string().nullable().optional(),
12
+ conclusion: z.string().nullable().optional(),
13
+ run_attempt: z.number().optional(),
14
+ updated_at: z.string(),
15
+ });
16
+
17
+ const RUNS_PAGE = z.object({ total_count: z.number(), workflow_runs: z.array(RUN) });
18
+
19
+ const JOB = z.object({
20
+ id: z.number(),
21
+ run_id: z.number(),
22
+ run_attempt: z.number().optional(),
23
+ name: z.string(),
24
+ workflow_name: z.string().nullable().optional(),
25
+ started_at: z.string().nullable().optional(),
26
+ completed_at: z.string().nullable().optional(),
27
+ labels: z.array(z.string()),
28
+ runner_group_name: z.string().nullable().optional(),
29
+ html_url: z.string().nullable().optional(),
30
+ });
31
+
32
+ const JOBS_PAGE = z.object({ total_count: z.number(), jobs: z.array(JOB) });
33
+
34
+ type Run = z.infer<typeof RUN>;
35
+
36
+ /** Finished runs read earlier, keyed by `<run id>:<attempt>`, so a repeated report reads only new runs. */
37
+ export interface RunCache {
38
+ version: 1;
39
+ runs: Record<string, { updatedAt: string; jobs: JobRecord[] }>;
40
+ }
41
+
42
+ const CACHE = z.object({ version: z.literal(1), runs: z.record(z.string(), z.object({ updatedAt: z.string(), jobs: z.array(z.unknown()) })) });
43
+
44
+ /** Reads a cache file's text; anything unreadable starts an empty cache (it is only an optimisation). */
45
+ export function parseRunCache(text: string | null): RunCache {
46
+ if (text === null) return { version: 1, runs: {} };
47
+ try {
48
+ const parsed = CACHE.safeParse(JSON.parse(text));
49
+ return parsed.success ? (parsed.data as RunCache) : { version: 1, runs: {} };
50
+ } catch {
51
+ return { version: 1, runs: {} };
52
+ }
53
+ }
54
+
55
+ /** GitHub returns at most 1,000 runs for a filtered query. */
56
+ export const MAX_RUNS_PER_QUERY = 1000;
57
+ const HOUR_MS = 3_600_000;
58
+ const DAY_MS = 24 * HOUR_MS;
59
+
60
+ export interface CollectOptions {
61
+ client: GithubClient;
62
+ /** `owner/name`. */
63
+ repository: string;
64
+ from: Date;
65
+ to: Date;
66
+ cache: RunCache;
67
+ }
68
+
69
+ export interface CollectResult {
70
+ repository: string;
71
+ jobs: JobRecord[];
72
+ /** Why the numbers may be short; empty when the period is complete. Runs still running are counted apart. */
73
+ partial: string[];
74
+ runs: { counted: number; fromCache: number; running: number; skipped: number };
75
+ /** The cache to write back: the runs this collection saw, nothing older. */
76
+ cache: RunCache;
77
+ /** A failure that left the repository unread (no access, unknown repository). */
78
+ error: string | null;
79
+ }
80
+
81
+ /** UTC day slices of [from, to); the first and the last may be shorter. */
82
+ export function getSlices(from: Date, to: Date, stepMs: number = DAY_MS): { from: Date; to: Date }[] {
83
+ const slices: { from: Date; to: Date }[] = [];
84
+ let start = from.getTime();
85
+ while (start < to.getTime()) {
86
+ const end = Math.min(to.getTime(), (Math.floor(start / stepMs) + 1) * stepMs);
87
+ slices.push({ from: new Date(start), to: new Date(end) });
88
+ start = end;
89
+ }
90
+ return slices;
91
+ }
92
+
93
+ /** GitHub's `created` range; the end is exclusive here, so one millisecond less, at second precision. */
94
+ function getCreatedRange(slice: { from: Date; to: Date }): string {
95
+ const last = new Date(slice.to.getTime() - 1000);
96
+ const format = (date: Date): string => date.toISOString().replace(/\.\d{3}Z$/, "Z");
97
+ return `${format(slice.from)}..${format(last)}`;
98
+ }
99
+
100
+ function toJobRecord(job: z.infer<typeof JOB>, run: Run): JobRecord {
101
+ return {
102
+ id: job.id,
103
+ runId: job.run_id,
104
+ runAttempt: job.run_attempt ?? 1,
105
+ name: job.name,
106
+ workflowName: job.workflow_name ?? run.name ?? run.path,
107
+ workflowPath: run.path,
108
+ startedAt: job.started_at ?? null,
109
+ completedAt: job.completed_at ?? null,
110
+ runUpdatedAt: run.updated_at,
111
+ labels: job.labels,
112
+ runnerGroupName: job.runner_group_name ?? null,
113
+ htmlUrl: job.html_url ?? "",
114
+ };
115
+ }
116
+
117
+ type Step<T> = { ok: true; value: T } | { ok: false; kind: "budget" | "http"; message: string };
118
+
119
+ async function listRuns(client: GithubClient, repository: string, slice: { from: Date; to: Date }): Promise<Step<{ total: number; runs: Run[] }>> {
120
+ const runs: Run[] = [];
121
+ let total = 0;
122
+ let next: string | null = `/repos/${repository}/actions/runs`;
123
+ let query: Record<string, string> | undefined = { created: getCreatedRange(slice), per_page: "100", exclude_pull_requests: "true" };
124
+ while (next !== null) {
125
+ const result = await client.get(next, query);
126
+ if (!result.ok) return result;
127
+ const page = RUNS_PAGE.safeParse(result.data);
128
+ if (!page.success) return { ok: false, kind: "http", message: `GET /repos/${repository}/actions/runs answered an unexpected shape` };
129
+ total = page.data.total_count;
130
+ runs.push(...page.data.workflow_runs);
131
+ next = result.next;
132
+ query = undefined;
133
+ }
134
+ return { ok: true, value: { total, runs } };
135
+ }
136
+
137
+ async function listJobs(client: GithubClient, repository: string, run: Run): Promise<Step<JobRecord[]>> {
138
+ const jobs: JobRecord[] = [];
139
+ let next: string | null = `/repos/${repository}/actions/runs/${String(run.id)}/jobs`;
140
+ let query: Record<string, string> | undefined = { filter: "all", per_page: "100" };
141
+ while (next !== null) {
142
+ const result = await client.get(next, query);
143
+ if (!result.ok) return result;
144
+ const page = JOBS_PAGE.safeParse(result.data);
145
+ if (!page.success) return { ok: false, kind: "http", message: `GET /repos/${repository}/actions/runs/${String(run.id)}/jobs answered an unexpected shape` };
146
+ jobs.push(...page.data.jobs.map((job) => toJobRecord(job, run)));
147
+ next = result.next;
148
+ query = undefined;
149
+ }
150
+ return { ok: true, value: jobs };
151
+ }
152
+
153
+ function formatTime(date: Date): string {
154
+ return date.toISOString().replace(/:\d{2}\.\d{3}Z$/, "Z");
155
+ }
156
+
157
+ /** Reads the runs of each slice, splitting a day into hours when it holds more runs than one query returns. */
158
+ async function listAllRuns(options: CollectOptions, partial: string[]): Promise<Step<Run[]>> {
159
+ const runs: Run[] = [];
160
+ for (const day of getSlices(options.from, options.to)) {
161
+ const first = await listRuns(options.client, options.repository, day);
162
+ if (!first.ok) return first;
163
+ if (first.value.total <= MAX_RUNS_PER_QUERY) {
164
+ runs.push(...first.value.runs);
165
+ continue;
166
+ }
167
+ for (const hour of getSlices(day.from, day.to, HOUR_MS)) {
168
+ const listed = await listRuns(options.client, options.repository, hour);
169
+ if (!listed.ok) return listed;
170
+ if (listed.value.total > MAX_RUNS_PER_QUERY) {
171
+ partial.push(`${String(listed.value.total)} runs created between ${formatTime(hour.from)} and ${formatTime(hour.to)}: only ${String(MAX_RUNS_PER_QUERY)} counted`);
172
+ }
173
+ runs.push(...listed.value.runs);
174
+ }
175
+ }
176
+ return { ok: true, value: runs };
177
+ }
178
+
179
+ export async function collectRepository(options: CollectOptions): Promise<CollectResult> {
180
+ const { client, repository } = options;
181
+ const partial: string[] = [];
182
+ const cache: RunCache = { version: 1, runs: {} };
183
+ const jobs: JobRecord[] = [];
184
+ const counts = { counted: 0, fromCache: 0, running: 0, skipped: 0 };
185
+ const done = (error: string | null = null): CollectResult => ({ repository, jobs, partial, runs: counts, cache, error });
186
+
187
+ const listed = await listAllRuns(options, partial);
188
+ if (!listed.ok) {
189
+ if (listed.kind === "budget") {
190
+ partial.push(`the run list stopped early: ${listed.message}`);
191
+ return done();
192
+ }
193
+ return done(listed.message);
194
+ }
195
+
196
+ // Oldest first, so a budget stop leaves a clean "counted up to" boundary.
197
+ const runs = [...listed.value].sort((a, b) => a.id - b.id);
198
+ for (const [index, run] of runs.entries()) {
199
+ if (run.status !== "completed") {
200
+ counts.running += 1;
201
+ continue;
202
+ }
203
+ if (run.conclusion === "skipped") {
204
+ counts.skipped += 1;
205
+ continue;
206
+ }
207
+ const key = `${String(run.id)}:${String(run.run_attempt ?? 1)}`;
208
+ const cached = options.cache.runs[key];
209
+ if (cached?.updatedAt === run.updated_at) {
210
+ jobs.push(...cached.jobs);
211
+ cache.runs[key] = cached;
212
+ counts.counted += 1;
213
+ counts.fromCache += 1;
214
+ continue;
215
+ }
216
+ const read = await listJobs(client, repository, run);
217
+ if (!read.ok) {
218
+ if (read.kind === "budget") {
219
+ partial.push(`stopped at the rate limit: ${String(runs.length - index)} of ${String(runs.length)} runs not counted (${read.message})`);
220
+ return done();
221
+ }
222
+ partial.push(`run ${String(run.id)} not counted: ${read.message}`);
223
+ continue;
224
+ }
225
+ jobs.push(...read.value);
226
+ cache.runs[key] = { updatedAt: run.updated_at, jobs: read.value };
227
+ counts.counted += 1;
228
+ }
229
+ return done();
230
+ }
package/src/github.ts ADDED
@@ -0,0 +1,113 @@
1
+ // A small GitHub REST client on the built-in fetch: JSON GETs, Link pagination and a request budget read from the
2
+ // rate-limit headers, so a busy repository ends in a partial report instead of a failed or sleeping job.
3
+
4
+ export type FetchLike = (url: string, init: { method: string; headers: Record<string, string>; body?: string }) => Promise<Response>;
5
+
6
+ export interface GithubClientOptions {
7
+ token: string;
8
+ fetch?: FetchLike;
9
+ baseUrl?: string;
10
+ /** Requests kept in reserve: the client stops reading when `x-ratelimit-remaining` reaches it. */
11
+ reserve?: number;
12
+ }
13
+
14
+ export type GithubResult<T> =
15
+ | { ok: true; data: T; next: string | null }
16
+ | { ok: false; kind: "budget"; message: string }
17
+ | { ok: false; kind: "http"; status: number; message: string };
18
+
19
+ export interface GithubClient {
20
+ get: (pathOrUrl: string, query?: Record<string, string>) => Promise<GithubResult<unknown>>;
21
+ /** A JSON POST or PATCH; writes ignore the reserve (they are few and the report depends on them). */
22
+ send: (method: "POST" | "PATCH", path: string, body: unknown) => Promise<GithubResult<unknown>>;
23
+ /** Requests sent so far. */
24
+ getRequestCount: () => number;
25
+ /** The last `x-ratelimit-remaining` seen, or null before the first answer. */
26
+ getRemaining: () => number | null;
27
+ }
28
+
29
+ export const DEFAULT_BASE_URL = "https://api.github.com";
30
+ export const DEFAULT_RESERVE = 50;
31
+ const API_VERSION = "2022-11-28";
32
+
33
+ /** The `rel="next"` address of a Link header, or null. */
34
+ export function getNextLink(header: string | null): string | null {
35
+ if (header === null) return null;
36
+ // Plain string parsing: the header comes from the network, so no backtracking pattern runs over it.
37
+ for (const part of header.split(",")) {
38
+ const [target, ...params] = part.split(";").map((piece) => piece.trim());
39
+ if (target === undefined || !target.startsWith("<") || !target.endsWith(">")) continue;
40
+ if (params.some((param) => param.replace(/ /g, "") === 'rel="next"')) return target.slice(1, -1);
41
+ }
42
+ return null;
43
+ }
44
+
45
+ function buildUrl(baseUrl: string, pathOrUrl: string, query: Record<string, string> | undefined): string {
46
+ const url = new URL(pathOrUrl.startsWith("https://") ? pathOrUrl : `${baseUrl}${pathOrUrl}`);
47
+ for (const [key, value] of Object.entries(query ?? {})) url.searchParams.set(key, value);
48
+ return url.toString();
49
+ }
50
+
51
+ async function readMessage(response: Response): Promise<string> {
52
+ try {
53
+ const body = (await response.json()) as { message?: unknown };
54
+ return typeof body.message === "string" ? body.message : response.statusText;
55
+ } catch {
56
+ return response.statusText;
57
+ }
58
+ }
59
+
60
+ export function createGithubClient(options: GithubClientOptions): GithubClient {
61
+ const fetchJson = options.fetch ?? ((url, init) => fetch(url, init));
62
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
63
+ const reserve = options.reserve ?? DEFAULT_RESERVE;
64
+ let requests = 0;
65
+ let remaining: number | null = null;
66
+
67
+ async function request(method: "GET" | "POST" | "PATCH", url: string, body: unknown): Promise<GithubResult<unknown>> {
68
+ // The path, never the token, names the request in every message.
69
+ const name = `${method} ${new URL(url).pathname}`;
70
+ if (method === "GET" && remaining !== null && remaining <= reserve) {
71
+ return { ok: false, kind: "budget", message: `${name}: the rate limit is down to ${String(remaining)} requests (reserve ${String(reserve)})` };
72
+ }
73
+ requests += 1;
74
+ let response: Response;
75
+ try {
76
+ response = await fetchJson(url, {
77
+ method,
78
+ headers: {
79
+ accept: "application/vnd.github+json",
80
+ authorization: `Bearer ${options.token}`,
81
+ "x-github-api-version": API_VERSION,
82
+ "user-agent": "softure-ci-usage",
83
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
84
+ },
85
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
86
+ });
87
+ } catch (error) {
88
+ return { ok: false, kind: "http", status: 0, message: `${name} failed: ${error instanceof Error ? error.message : String(error)}` };
89
+ }
90
+ const header = response.headers.get("x-ratelimit-remaining");
91
+ if (header !== null && Number.isFinite(Number(header))) remaining = Number(header);
92
+ if (!response.ok) {
93
+ const message = await readMessage(response);
94
+ const limited = (response.status === 403 || response.status === 429) && (remaining === 0 || response.headers.has("retry-after"));
95
+ if (limited) return { ok: false, kind: "budget", message: `${name}: rate limited (${message})` };
96
+ return { ok: false, kind: "http", status: response.status, message: `${name} answered ${String(response.status)}: ${message}` };
97
+ }
98
+ let data: unknown;
99
+ try {
100
+ data = await response.json();
101
+ } catch {
102
+ return { ok: false, kind: "http", status: response.status, message: `${name} answered with a body that is not JSON` };
103
+ }
104
+ return { ok: true, data, next: getNextLink(response.headers.get("link")) };
105
+ }
106
+
107
+ return {
108
+ get: (pathOrUrl, query) => request("GET", buildUrl(baseUrl, pathOrUrl, query), undefined),
109
+ send: (method, path, body) => request(method, buildUrl(baseUrl, path, undefined), body),
110
+ getRequestCount: () => requests,
111
+ getRemaining: () => remaining,
112
+ };
113
+ }
package/src/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ // @softure-ai/ci-usage: billable CI minutes and their estimated cost per repository, workflow and job.
2
+ export { getBillingUsage, parseBillingAccount, type BillingAccount, type BilledSku, type BillingResult } from "./billing.js";
3
+ export { collectRepository, getSlices, parseRunCache, MAX_RUNS_PER_QUERY, type CollectOptions, type CollectResult, type RunCache } from "./collect.js";
4
+ export { createGithubClient, getNextLink, DEFAULT_RESERVE, type FetchLike, type GithubClient, type GithubResult } from "./github.js";
5
+ export { ciUsageMessages, formatMessage, type CiUsageMessages } from "./messages/index.js";
6
+ export { DEFAULT_PRICES, getMinutePrice, parsePriceOverrides, type PriceOptions, type PriceTable } from "./prices.js";
7
+ export { buildComment, buildIssueBody, publishReport, ISSUE_LABEL, MAX_BODY, type PublishResult } from "./publish.js";
8
+ export { buildReport, renderMarkdown, JSON_FILE, MARKDOWN_FILE, REPORT_MARKER, SCHEMA_VERSION, type CiUsageReport, type RepositoryReport } from "./report.js";
9
+ export { classifyRunner, GITHUB_SKUS, type GithubSku, type Provider, type RunnerClass } from "./runner.js";
10
+ export { getJobMinutes, summarizeUsage, type Cost, type JobRecord, type JobUsage, type RepositoryUsage, type WorkflowUsage } from "./usage.js";
@@ -0,0 +1,52 @@
1
+ /** Copy of the CI usage report (Markdown, the issue and its comments). English, the only built-in language. */
2
+ export const en = {
3
+ title: "CI usage report",
4
+ /** `{from}` and `{to}` are UTC times, `{days}` the length of the period. */
5
+ period: "Period: {from} to {to} UTC ({days} days). Generated {generated} UTC.",
6
+ complete: "Status: complete.",
7
+ partial: "Status: partial, some runs are not counted (see the notes of each repository).",
8
+ howToRead:
9
+ "Minutes are billable minutes: each job rounded up to a whole minute, reruns included. USD is the estimate at list price (public repositories pay nothing for standard GitHub runners; the plan's included minutes are not subtracted).",
10
+ totalsHeading: "Totals",
11
+ repository: "Repository",
12
+ minutes: "Minutes",
13
+ usd: "Est. USD",
14
+ githubHosted: "GitHub-hosted",
15
+ ubicloud: "Ubicloud",
16
+ selfHosted: "Self-hosted",
17
+ runs: "Runs",
18
+ jobs: "Jobs",
19
+ workflowsHeading: "Workflows",
20
+ workflow: "Workflow",
21
+ share: "Share",
22
+ topJobsHeading: "Jobs that use the most minutes",
23
+ job: "Job",
24
+ runner: "Runner",
25
+ count: "Count",
26
+ p50: "p50 min",
27
+ p95: "p95 min",
28
+ longestHeading: "Longest single jobs",
29
+ /** One list item; `{url}` links the job. */
30
+ longestItem: "[{minutes} min]({url}) {workflow} / {job} on `{runner}`",
31
+ billingHeading: "Billed by GitHub",
32
+ sku: "SKU",
33
+ gross: "Gross USD",
34
+ net: "Net USD",
35
+ notesHeading: "Notes",
36
+ /** Runs still running when the report was made: counted next time. */
37
+ running: "{count} runs were still running and are left out.",
38
+ fromCache: "{count} of {total} runs came from the cache of earlier reports.",
39
+ unknownPrice: "{minutes} minutes ran on runners without a known price (set the `prices` input to price them).",
40
+ error: "Not read: {error}",
41
+ noRuns: "No finished runs in the period.",
42
+ unknown: "unknown",
43
+ /** Under the report; `{source}` lists the price pages, `{checkedOn}` the day they were read. */
44
+ prices: "Prices: {source} (checked {checkedOn}){premium}.",
45
+ premium: ", Ubicloud priced as premium",
46
+ jsonSummary: "The report as JSON",
47
+ jsonTooLong: "The JSON report is too long for this issue: it is in the run's artifact `ci-usage-report`.",
48
+ issueIntro:
49
+ "This issue is kept up to date by the ci-usage workflow (@softure-ai/ci-usage): its body is always the latest report, and every run adds a comment with its totals.",
50
+ /** The comment one run adds; `{url}` is the run. */
51
+ comment: "{from} to {to} UTC: {minutes} minutes, {usd} USD estimated, {runs} runs. [Run]({url})",
52
+ } as const;
@@ -0,0 +1,15 @@
1
+ import { en } from "./en.js";
2
+
3
+ export type CiUsageMessages = { [Key in keyof typeof en]: string };
4
+
5
+ /** The copy of the report; an app passes its own object of the same shape to change the wording. */
6
+ export const ciUsageMessages: { en: CiUsageMessages } = { en };
7
+
8
+ /** Replaces every `{name}` in `template` with its value; an unknown placeholder is a bug, so it throws. */
9
+ export function formatMessage(template: string, values: Record<string, string | number>): string {
10
+ return template.replace(/\{([a-zA-Z]+)\}/g, (placeholder, name: string) => {
11
+ const value = values[name];
12
+ if (value === undefined) throw new Error(`formatMessage: no value for ${placeholder} in "${template}".`);
13
+ return String(value);
14
+ });
15
+ }
package/src/prices.ts ADDED
@@ -0,0 +1,74 @@
1
+ // What a runner minute costs, from the providers' published price lists, with the caller's overrides on top.
2
+ import { z } from "zod";
3
+ import type { GithubSku, RunnerClass } from "./runner.js";
4
+
5
+ export interface PriceTable {
6
+ /** USD per minute of GitHub's standard hosted runners, by billing SKU. */
7
+ github: Record<GithubSku, number>;
8
+ /** USD per minute of Ubicloud standard runners (x64 and arm64 cost the same), by vCPU count. */
9
+ ubicloudStandard: Record<string, number>;
10
+ /** USD per minute of Ubicloud premium runners, by vCPU count. */
11
+ ubicloudPremium: Record<string, number>;
12
+ /** USD per minute by exact runner label; wins over everything above (larger GitHub runners, own runners). */
13
+ labels: Record<string, number>;
14
+ /** Where the built-in numbers come from and when they were checked. */
15
+ source: string;
16
+ checkedOn: string;
17
+ }
18
+
19
+ export const DEFAULT_PRICES: PriceTable = {
20
+ github: {
21
+ actions_linux_slim: 0.002,
22
+ actions_linux: 0.006,
23
+ actions_linux_arm: 0.005,
24
+ actions_windows: 0.01,
25
+ actions_windows_arm: 0.01,
26
+ actions_macos: 0.062,
27
+ },
28
+ ubicloudStandard: { "2": 0.00125, "4": 0.0025, "8": 0.005, "16": 0.01, "30": 0.01875 },
29
+ ubicloudPremium: { "2": 0.002, "4": 0.004, "8": 0.008, "16": 0.016, "30": 0.03 },
30
+ labels: {},
31
+ source: "https://docs.github.com/en/billing/reference/actions-runner-pricing, https://ubicloud.com/docs/about/pricing",
32
+ checkedOn: "2026-11-18",
33
+ };
34
+
35
+ const PRICE = z.number().finite().nonnegative();
36
+ const OVERRIDES = z.record(z.string().min(1), PRICE);
37
+
38
+ export type PricesResult = { ok: true; prices: PriceTable } | { ok: false; error: string };
39
+
40
+ /** Merges a JSON object of `label → USD per minute` over the built-in table. An empty value keeps the table. */
41
+ export function parsePriceOverrides(json: string | undefined, base: PriceTable = DEFAULT_PRICES): PricesResult {
42
+ if (json === undefined || json.trim() === "") return { ok: true, prices: base };
43
+ let value: unknown;
44
+ try {
45
+ value = JSON.parse(json);
46
+ } catch {
47
+ return { ok: false, error: `--prices is not JSON: ${json}` };
48
+ }
49
+ const parsed = OVERRIDES.safeParse(value);
50
+ if (!parsed.success) return { ok: false, error: `--prices must be a JSON object of runner label to USD per minute, such as {"my-runner":0.004}` };
51
+ return { ok: true, prices: { ...base, labels: { ...base.labels, ...parsed.data } } };
52
+ }
53
+
54
+ export interface PriceOptions {
55
+ prices: PriceTable;
56
+ /** Ubicloud premium is an account setting the job does not show; true prices every Ubicloud minute as premium. */
57
+ ubicloudPremium: boolean;
58
+ }
59
+
60
+ /** USD per minute of one runner, or null when neither the table nor the caller knows it. */
61
+ export function getMinutePrice(runner: RunnerClass, options: PriceOptions): number | null {
62
+ const byLabel = options.prices.labels[runner.label];
63
+ if (byLabel !== undefined) return byLabel;
64
+ switch (runner.provider) {
65
+ case "github-hosted":
66
+ return options.prices.github[runner.sku];
67
+ case "ubicloud": {
68
+ const table = options.ubicloudPremium ? options.prices.ubicloudPremium : options.prices.ubicloudStandard;
69
+ return table[String(runner.vcpu)] ?? null;
70
+ }
71
+ case "self-hosted":
72
+ return null;
73
+ }
74
+ }
package/src/publish.ts ADDED
@@ -0,0 +1,95 @@
1
+ // Keeps one rolling issue per repository up to date with the latest report, and adds a comment per run, so people
2
+ // and agents (with the GitHub tools they already have) read the usage without the artifact.
3
+ import { z } from "zod";
4
+ import type { GithubClient } from "./github.js";
5
+ import { ciUsageMessages, formatMessage, type CiUsageMessages } from "./messages/index.js";
6
+ import { REPORT_MARKER, type CiUsageReport } from "./report.js";
7
+
8
+ export const ISSUE_LABEL = "ci-usage";
9
+ const LABEL_COLOR = "5319e7";
10
+ const LABEL_DESCRIPTION = "The CI usage report of @softure-ai/ci-usage";
11
+ /** GitHub refuses an issue body above 65,536 characters; a margin keeps the closing lines. */
12
+ export const MAX_BODY = 65_000;
13
+
14
+ const ISSUE = z.object({ number: z.number(), body: z.string().nullable().optional(), html_url: z.string(), pull_request: z.unknown().optional() });
15
+
16
+ export type PublishResult = { ok: true; issue: number; url: string; created: boolean } | { ok: false; error: string };
17
+
18
+ /** The issue body: the Markdown report, then the JSON in a collapsed block when the whole still fits. */
19
+ export function buildIssueBody(markdown: string, report: CiUsageReport, messages: CiUsageMessages = ciUsageMessages.en): string {
20
+ const head = `${messages.issueIntro}\n\n${markdown.trimEnd()}\n`;
21
+ const json = `\n<details><summary>${messages.jsonSummary}</summary>\n\n\`\`\`json\n${JSON.stringify(report)}\n\`\`\`\n\n</details>\n`;
22
+ if (head.length + json.length <= MAX_BODY) return head + json;
23
+ const note = `\n${messages.jsonTooLong}\n`;
24
+ if (head.length + note.length <= MAX_BODY) return head + note;
25
+ return `${head.slice(0, MAX_BODY - note.length - 2)}\n…${note}`;
26
+ }
27
+
28
+ export function buildComment(report: CiUsageReport, runUrl: string, messages: CiUsageMessages = ciUsageMessages.en): string {
29
+ return formatMessage(messages.comment, {
30
+ from: report.period.from.slice(0, 16).replace("T", " "),
31
+ to: report.period.to.slice(0, 16).replace("T", " "),
32
+ minutes: report.totals.minutes,
33
+ usd: report.totals.usd === null ? messages.unknown : report.totals.usd.toFixed(2),
34
+ runs: report.totals.runs,
35
+ url: runUrl,
36
+ });
37
+ }
38
+
39
+ async function ensureLabel(client: GithubClient, repository: string): Promise<string | null> {
40
+ const found = await client.get(`/repos/${repository}/labels/${ISSUE_LABEL}`);
41
+ if (found.ok) return null;
42
+ if (found.kind === "http" && found.status !== 404) return found.message;
43
+ const created = await client.send("POST", `/repos/${repository}/labels`, { name: ISSUE_LABEL, color: LABEL_COLOR, description: LABEL_DESCRIPTION });
44
+ // 422: another run created it in the meantime.
45
+ if (!created.ok && !(created.kind === "http" && created.status === 422)) return created.message;
46
+ return null;
47
+ }
48
+
49
+ async function findIssue(client: GithubClient, repository: string): Promise<{ ok: true; number: number | null } | { ok: false; error: string }> {
50
+ const listed = await client.get(`/repos/${repository}/issues`, { labels: ISSUE_LABEL, state: "open", per_page: "100" });
51
+ if (!listed.ok) return { ok: false, error: listed.message };
52
+ const issues = z.array(ISSUE).safeParse(listed.data);
53
+ if (!issues.success) return { ok: false, error: `GET /repos/${repository}/issues answered an unexpected shape` };
54
+ const ours = issues.data.filter((issue) => issue.pull_request === undefined && (issue.body ?? "").includes(REPORT_MARKER)).sort((a, b) => a.number - b.number);
55
+ return { ok: true, number: ours[0]?.number ?? null };
56
+ }
57
+
58
+ export interface PublishOptions {
59
+ client: GithubClient;
60
+ repository: string;
61
+ report: CiUsageReport;
62
+ markdown: string;
63
+ runUrl: string;
64
+ messages?: CiUsageMessages;
65
+ }
66
+
67
+ /** Creates the issue the first time, replaces its body afterwards, and comments the run's totals. */
68
+ export async function publishReport(options: PublishOptions): Promise<PublishResult> {
69
+ const { client, repository } = options;
70
+ const messages = options.messages ?? ciUsageMessages.en;
71
+ const labelError = await ensureLabel(client, repository);
72
+ if (labelError !== null) return { ok: false, error: labelError };
73
+ const found = await findIssue(client, repository);
74
+ if (!found.ok) return found;
75
+ const body = buildIssueBody(options.markdown, options.report, messages);
76
+ let number = found.number;
77
+ let url: string;
78
+ const created = number === null;
79
+ if (number === null) {
80
+ const result = await client.send("POST", `/repos/${repository}/issues`, { title: messages.title, body, labels: [ISSUE_LABEL] });
81
+ if (!result.ok) return { ok: false, error: result.message };
82
+ const issue = ISSUE.safeParse(result.data);
83
+ if (!issue.success) return { ok: false, error: `POST /repos/${repository}/issues answered an unexpected shape` };
84
+ number = issue.data.number;
85
+ url = issue.data.html_url;
86
+ } else {
87
+ const result = await client.send("PATCH", `/repos/${repository}/issues/${String(number)}`, { body });
88
+ if (!result.ok) return { ok: false, error: result.message };
89
+ const issue = ISSUE.safeParse(result.data);
90
+ url = issue.success ? issue.data.html_url : `https://github.com/${repository}/issues/${String(number)}`;
91
+ }
92
+ const comment = await client.send("POST", `/repos/${repository}/issues/${String(number)}/comments`, { body: buildComment(options.report, options.runUrl, messages) });
93
+ if (!comment.ok) return { ok: false, error: comment.message };
94
+ return { ok: true, issue: number, url, created };
95
+ }