wachiman 1.14.0 → 1.15.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.
- package/README.md +1 -1
- package/package.json +4 -2
- package/src/accounts/confirm.ts +62 -3
- package/src/cli.ts +107 -122
- package/src/engine.ts +14 -0
- package/src/help.ts +555 -0
- package/src/init/options.ts +1 -1
- package/src/init/run.ts +43 -17
- package/src/ledger-read/command.ts +106 -0
- package/src/ledger-read/credentials.ts +103 -0
- package/src/ledger-read/files.ts +141 -0
- package/src/ledger-read/pull.ts +69 -0
- package/src/ledger-read/rows.ts +60 -0
- package/src/ledger-read/types.ts +127 -0
- package/src/ledger.ts +34 -18
- package/src/setup/run.ts +27 -10
- package/src/spend/report.ts +349 -0
- package/src/status/command.ts +150 -36
- package/src/store/command.ts +20 -3
- package/src/store/html.ts +205 -8
- package/src/store/index.ts +64 -5
- package/src/store/rows.ts +103 -0
- package/src/wizard/interactive.ts +11 -0
- package/src/wizard/launcher.ts +340 -0
- package/src/wizard/load.ts +30 -0
- package/src/wizard/mascot.ts +223 -0
- package/src/wizard/prompt-fancy.ts +127 -0
- package/src/wizard/prompt.ts +95 -61
- package/src/wizard/style.ts +93 -13
- package/src/wizard/tone.ts +11 -0
- package/src/wizard/ui.ts +78 -0
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One spend report for laptop runs and GitHub Actions runs (ADR 0039). Pure: rows in, report out. No
|
|
3
|
+
* file, no network, no Bun-only API, so a web page can reuse it. Dollars are never summed across the
|
|
4
|
+
* credential split without the split travelling with them: every figure is a `Split`.
|
|
5
|
+
*
|
|
6
|
+
* Spend is the dollars of finished runs (`settled`). Reservations that never settled and runs that
|
|
7
|
+
* were not reserved are reported as their own lines (`aside`), not as spend. A period outside what was
|
|
8
|
+
* downloaded is `known: false`, never zero.
|
|
9
|
+
*/
|
|
10
|
+
export type Source = "laptop" | "actions";
|
|
11
|
+
export const SOURCES: readonly Source[] = ["laptop", "actions"];
|
|
12
|
+
export type RowState = "settled" | "reserved" | "unsettled" | "unreserved";
|
|
13
|
+
export type Credential = "billed" | "estimated" | "unknown";
|
|
14
|
+
export const CREDENTIALS: readonly Credential[] = ["billed", "estimated", "unknown"];
|
|
15
|
+
|
|
16
|
+
/** `api-key` is billed; a subscription token or login gives an API-price estimate, not a charge. */
|
|
17
|
+
export function credentialOf(auth: string): Credential {
|
|
18
|
+
if (auth === "api-key") return "billed";
|
|
19
|
+
if (auth === "oauth-token" || auth === "subscription") return "estimated";
|
|
20
|
+
return "unknown";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface SpendCall {
|
|
24
|
+
model: string;
|
|
25
|
+
auth: string;
|
|
26
|
+
costUsd: number;
|
|
27
|
+
costKnown: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SpendRow {
|
|
31
|
+
source: Source;
|
|
32
|
+
state: RowState;
|
|
33
|
+
/** UTC `YYYY-MM-DD`. */
|
|
34
|
+
day: string;
|
|
35
|
+
/** The Monday of the row's week, UTC. */
|
|
36
|
+
week: string;
|
|
37
|
+
repositoryKey: string;
|
|
38
|
+
repository: string;
|
|
39
|
+
pr: number | null;
|
|
40
|
+
runId: string;
|
|
41
|
+
profile: string;
|
|
42
|
+
/** Dollars the run spent: for `settled` and `unreserved` rows; 0 for the others. */
|
|
43
|
+
costUsd: number;
|
|
44
|
+
/** Dollars held by a reservation (`reserved`, `unsettled`), else 0. */
|
|
45
|
+
reservedUsd: number;
|
|
46
|
+
calls: SpendCall[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface Money {
|
|
50
|
+
runs: number;
|
|
51
|
+
calls: number;
|
|
52
|
+
usd: number;
|
|
53
|
+
}
|
|
54
|
+
export interface Split {
|
|
55
|
+
total: Money;
|
|
56
|
+
bySource: Record<Source, Money>;
|
|
57
|
+
byCredential: Record<Credential, Money>;
|
|
58
|
+
}
|
|
59
|
+
export interface Aside {
|
|
60
|
+
runs: number;
|
|
61
|
+
/** Dollars the run itself recorded (`unreserved`). */
|
|
62
|
+
usd: number;
|
|
63
|
+
/** Dollars held by reservations (`reserved`, `unsettled`). */
|
|
64
|
+
reservedUsd: number;
|
|
65
|
+
}
|
|
66
|
+
export interface AsideLines {
|
|
67
|
+
unreserved: Aside;
|
|
68
|
+
unsettled: Aside;
|
|
69
|
+
reserved: Aside;
|
|
70
|
+
}
|
|
71
|
+
export interface Range {
|
|
72
|
+
from: string;
|
|
73
|
+
to: string;
|
|
74
|
+
}
|
|
75
|
+
export interface Limits {
|
|
76
|
+
dailyUsd: number | null;
|
|
77
|
+
weeklyUsd: number | null;
|
|
78
|
+
}
|
|
79
|
+
export interface Bucket {
|
|
80
|
+
key: string;
|
|
81
|
+
/** Per source: whether the downloaded or kept data covers this period at all. */
|
|
82
|
+
known: Record<Source, boolean>;
|
|
83
|
+
/** The period is only partly inside the data of some source that covers it. */
|
|
84
|
+
partial: boolean;
|
|
85
|
+
spend: Split;
|
|
86
|
+
aside: AsideLines;
|
|
87
|
+
/** Actions only: settled + unreserved + reserved/unsettled holds, what the limit counts. Null without Actions data. */
|
|
88
|
+
countedAgainstLimitUsd: number | null;
|
|
89
|
+
}
|
|
90
|
+
export interface Group {
|
|
91
|
+
key: string;
|
|
92
|
+
label: string;
|
|
93
|
+
split: Split;
|
|
94
|
+
}
|
|
95
|
+
export type GroupBy = "day" | "week" | "repo" | "pr" | "model" | "profile" | "source";
|
|
96
|
+
|
|
97
|
+
export interface Report {
|
|
98
|
+
filters: { sources: Source[] };
|
|
99
|
+
coverage: Record<Source, Range | null>;
|
|
100
|
+
pulledAt: string | null;
|
|
101
|
+
limits: Limits | null;
|
|
102
|
+
totals: Split;
|
|
103
|
+
aside: AsideLines;
|
|
104
|
+
days: Bucket[];
|
|
105
|
+
weeks: Bucket[];
|
|
106
|
+
groups: { repository: Group[]; pr: Group[]; model: Group[] };
|
|
107
|
+
/** Calls whose dollar cost is unknown (counted as 0 in the figures). */
|
|
108
|
+
unknownCostCalls: number;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const zero = (): Money => ({ runs: 0, calls: 0, usd: 0 });
|
|
112
|
+
const emptySplit = (): Split => ({
|
|
113
|
+
total: zero(),
|
|
114
|
+
bySource: { laptop: zero(), actions: zero() },
|
|
115
|
+
byCredential: { billed: zero(), estimated: zero(), unknown: zero() },
|
|
116
|
+
});
|
|
117
|
+
const emptyAside = (): AsideLines => ({ unreserved: { runs: 0, usd: 0, reservedUsd: 0 }, unsettled: { runs: 0, usd: 0, reservedUsd: 0 }, reserved: { runs: 0, usd: 0, reservedUsd: 0 } });
|
|
118
|
+
|
|
119
|
+
/** Six decimals hide floating-point noise and lose no cent. */
|
|
120
|
+
export const roundUsd = (n: number) => Math.round(n * 1e6) / 1e6;
|
|
121
|
+
|
|
122
|
+
/** The spend of a row broken down by credential; dollars no call accounts for go to `unknown`. */
|
|
123
|
+
function creditBreakdown(row: SpendRow): { credential: Credential; calls: number; usd: number }[] {
|
|
124
|
+
const out = new Map<Credential, { credential: Credential; calls: number; usd: number }>();
|
|
125
|
+
const add = (credential: Credential, calls: number, usd: number) => {
|
|
126
|
+
const e = out.get(credential) ?? { credential, calls: 0, usd: 0 };
|
|
127
|
+
e.calls += calls;
|
|
128
|
+
e.usd += usd;
|
|
129
|
+
out.set(credential, e);
|
|
130
|
+
};
|
|
131
|
+
let itemised = 0;
|
|
132
|
+
for (const c of row.calls) {
|
|
133
|
+
add(credentialOf(c.auth), 1, c.costUsd);
|
|
134
|
+
itemised += c.costUsd;
|
|
135
|
+
}
|
|
136
|
+
const rest = row.costUsd - itemised;
|
|
137
|
+
if (rest > 1e-9) add("unknown", 0, rest);
|
|
138
|
+
return [...out.values()];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function addSpend(split: Split, row: SpendRow) {
|
|
142
|
+
const calls = row.calls.length;
|
|
143
|
+
for (const m of [split.total, split.bySource[row.source]]) {
|
|
144
|
+
m.runs++;
|
|
145
|
+
m.calls += calls;
|
|
146
|
+
m.usd += row.costUsd;
|
|
147
|
+
}
|
|
148
|
+
for (const b of creditBreakdown(row)) {
|
|
149
|
+
const m = split.byCredential[b.credential];
|
|
150
|
+
m.runs++;
|
|
151
|
+
m.calls += b.calls;
|
|
152
|
+
m.usd += b.usd;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function roundSplit(split: Split): Split {
|
|
157
|
+
for (const m of [split.total, ...Object.values(split.bySource), ...Object.values(split.byCredential)]) m.usd = roundUsd(m.usd);
|
|
158
|
+
return split;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function addAside(aside: AsideLines, row: SpendRow) {
|
|
162
|
+
if (row.state === "settled") return;
|
|
163
|
+
const line = aside[row.state];
|
|
164
|
+
line.runs++;
|
|
165
|
+
line.usd += row.state === "unreserved" ? row.costUsd : 0;
|
|
166
|
+
line.reservedUsd += row.reservedUsd;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const roundAside = (a: AsideLines): AsideLines => {
|
|
170
|
+
for (const l of Object.values(a)) {
|
|
171
|
+
l.usd = roundUsd(l.usd);
|
|
172
|
+
l.reservedUsd = roundUsd(l.reservedUsd);
|
|
173
|
+
}
|
|
174
|
+
return a;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
/** What the ledger limit counts for one Actions row: spend, a reservation hold, or a late record. */
|
|
178
|
+
const counted = (row: SpendRow) => (row.source !== "actions" ? 0 : row.state === "settled" || row.state === "unreserved" ? row.costUsd : row.reservedUsd);
|
|
179
|
+
|
|
180
|
+
/** The Monday (UTC) of the week that contains `day`. */
|
|
181
|
+
export function weekStart(day: string): string {
|
|
182
|
+
const t = Date.parse(`${day}T00:00:00Z`);
|
|
183
|
+
const dow = (new Date(t).getUTCDay() + 6) % 7;
|
|
184
|
+
return new Date(t - dow * 86_400_000).toISOString().slice(0, 10);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const addDays = (day: string, n: number) => new Date(Date.parse(`${day}T00:00:00Z`) + n * 86_400_000).toISOString().slice(0, 10);
|
|
188
|
+
|
|
189
|
+
function modelOf(call: SpendCall) {
|
|
190
|
+
return call.model === "" ? "(unknown model)" : call.model;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Groups rows. `model` groups by call: a run with two models appears in both, with only that model's calls and dollars. */
|
|
194
|
+
export function group(rows: SpendRow[], by: GroupBy): Group[] {
|
|
195
|
+
const map = new Map<string, Group>();
|
|
196
|
+
const get = (key: string, label: string) => {
|
|
197
|
+
let g = map.get(key);
|
|
198
|
+
if (!g) map.set(key, (g = { key, label, split: emptySplit() }));
|
|
199
|
+
return g;
|
|
200
|
+
};
|
|
201
|
+
for (const row of rows) {
|
|
202
|
+
if (row.state !== "settled") continue;
|
|
203
|
+
if (by === "model") {
|
|
204
|
+
const byModel = new Map<string, SpendRow>();
|
|
205
|
+
const itemised = row.calls.reduce((n, c) => n + c.costUsd, 0);
|
|
206
|
+
for (const c of row.calls) {
|
|
207
|
+
const key = modelOf(c);
|
|
208
|
+
const part = byModel.get(key) ?? { ...row, calls: [], costUsd: 0 };
|
|
209
|
+
part.calls = [...part.calls, c];
|
|
210
|
+
part.costUsd += c.costUsd;
|
|
211
|
+
byModel.set(key, part);
|
|
212
|
+
}
|
|
213
|
+
if (row.costUsd - itemised > 1e-9) byModel.set("(not itemised)", { ...row, calls: [], costUsd: row.costUsd - itemised });
|
|
214
|
+
if (byModel.size === 0) byModel.set("(no calls recorded)", row);
|
|
215
|
+
for (const [key, part] of byModel) addSpend(get(key, key).split, part);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const [key, label] =
|
|
219
|
+
by === "day"
|
|
220
|
+
? [row.day, row.day]
|
|
221
|
+
: by === "week"
|
|
222
|
+
? [row.week, row.week]
|
|
223
|
+
: by === "repo"
|
|
224
|
+
? [row.repositoryKey, row.repository]
|
|
225
|
+
: by === "pr"
|
|
226
|
+
? row.pr !== null
|
|
227
|
+
? [`${row.repositoryKey}#${row.pr}`, `${row.repository} #${row.pr}`]
|
|
228
|
+
: row.source === "laptop"
|
|
229
|
+
? [`${row.repositoryKey}#local`, `${row.repository} (local branch)`]
|
|
230
|
+
: [`${row.repositoryKey}#none`, `${row.repository} (no pull request)`]
|
|
231
|
+
: by === "profile"
|
|
232
|
+
? [row.profile || "(none)", row.profile || "(none)"]
|
|
233
|
+
: [row.source, row.source === "actions" ? "GitHub Actions" : "Laptop"];
|
|
234
|
+
addSpend(get(key, label).split, row);
|
|
235
|
+
}
|
|
236
|
+
const groups = [...map.values()];
|
|
237
|
+
for (const g of groups) roundSplit(g.split);
|
|
238
|
+
return groups.sort((a, b) => (by === "day" || by === "week" ? b.key.localeCompare(a.key) : b.split.total.usd - a.split.total.usd || a.key.localeCompare(b.key)));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export interface ReportInput {
|
|
242
|
+
rows: SpendRow[];
|
|
243
|
+
/** Which sources the caller asked for; the others are `known: false`. */
|
|
244
|
+
sources?: Source[];
|
|
245
|
+
/** The days each source's data covers, as separate ranges: the pulls for Actions, first kept run to today for the laptop. Empty: no data. */
|
|
246
|
+
coverage: Record<Source, Range[]>;
|
|
247
|
+
limits?: Limits | null;
|
|
248
|
+
pulledAt?: string | null;
|
|
249
|
+
now: Date;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** The laptop covers from its first kept run to today, whatever the filters; Actions covers what the last pull asked for. */
|
|
253
|
+
export function deriveCoverage(allRows: SpendRow[], actions: Range[], now: Date): Record<Source, Range[]> {
|
|
254
|
+
const days = allRows.filter((r) => r.source === "laptop").map((r) => r.day).sort();
|
|
255
|
+
return { laptop: days.length ? [{ from: days[0], to: now.toISOString().slice(0, 10) }] : [], actions: mergeRanges(actions) };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Sorted ranges where those that overlap or touch (the next starts the day after the previous ends) become one. */
|
|
259
|
+
export function mergeRanges(ranges: Range[]): Range[] {
|
|
260
|
+
const out: Range[] = [];
|
|
261
|
+
for (const r of [...ranges].sort((a, b) => a.from.localeCompare(b.from))) {
|
|
262
|
+
const last = out.at(-1);
|
|
263
|
+
if (last && r.from <= addDays(last.to, 1)) last.to = r.to > last.to ? r.to : last.to;
|
|
264
|
+
else out.push({ ...r });
|
|
265
|
+
}
|
|
266
|
+
return out;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const hull = (ranges: Range[]): Range | null => (ranges.length ? { from: ranges[0].from, to: ranges.at(-1)!.to } : null);
|
|
270
|
+
|
|
271
|
+
const MAX_BUCKETS = 120;
|
|
272
|
+
|
|
273
|
+
function buckets(input: ReportInput, kind: "day" | "week", sources: Source[]): Bucket[] {
|
|
274
|
+
const today = input.now.toISOString().slice(0, 10);
|
|
275
|
+
const ranges = sources.flatMap((s) => input.coverage[s]);
|
|
276
|
+
if (ranges.length === 0) return [];
|
|
277
|
+
const first = ranges.map((r) => r.from).sort()[0];
|
|
278
|
+
const last = [today, ...ranges.map((r) => r.to)].sort().at(-1)!;
|
|
279
|
+
const step = kind === "day" ? 1 : 7;
|
|
280
|
+
// The newest periods are kept: with a long history it is the old ones that fall off the chart.
|
|
281
|
+
const lastKey = kind === "day" ? last : weekStart(last);
|
|
282
|
+
const oldest = addDays(lastKey, -(MAX_BUCKETS - 1) * step);
|
|
283
|
+
const firstKey = kind === "day" ? first : weekStart(first);
|
|
284
|
+
const keys: string[] = [];
|
|
285
|
+
for (let k = firstKey > oldest ? firstKey : oldest; k <= lastKey; k = addDays(k, step)) keys.push(k);
|
|
286
|
+
const rows = input.rows.filter((r) => sources.includes(r.source));
|
|
287
|
+
return keys.map((key): Bucket => {
|
|
288
|
+
const end = kind === "day" ? key : addDays(key, 6);
|
|
289
|
+
const known = { laptop: false, actions: false } as Record<Source, boolean>;
|
|
290
|
+
let partial = false;
|
|
291
|
+
const wanted = end > today ? today : end;
|
|
292
|
+
for (const s of sources) {
|
|
293
|
+
const ranges = input.coverage[s];
|
|
294
|
+
if (!ranges.some((r) => r.to >= key && r.from <= end)) continue;
|
|
295
|
+
known[s] = true;
|
|
296
|
+
if (!ranges.some((r) => r.from <= key && r.to >= wanted)) partial = true;
|
|
297
|
+
}
|
|
298
|
+
const spend = emptySplit();
|
|
299
|
+
const aside = emptyAside();
|
|
300
|
+
let limitUse = 0;
|
|
301
|
+
for (const row of rows) {
|
|
302
|
+
if ((kind === "day" ? row.day : row.week) !== key) continue;
|
|
303
|
+
if (row.state === "settled") addSpend(spend, row);
|
|
304
|
+
addAside(aside, row);
|
|
305
|
+
limitUse += counted(row);
|
|
306
|
+
}
|
|
307
|
+
return { key, known, partial, spend: roundSplit(spend), aside: roundAside(aside), countedAgainstLimitUsd: known.actions ? roundUsd(limitUse) : null };
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export interface LimitUse {
|
|
312
|
+
key: string;
|
|
313
|
+
/** Dollars the ledger counts in this period; null when the downloaded days do not cover it. */
|
|
314
|
+
usedUsd: number | null;
|
|
315
|
+
limitUsd: number;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Today's and this week's figure against the ledger limits. Give it a report built from every Actions row of the account, unfiltered. */
|
|
319
|
+
export function limitUse(report: Report, now: Date): { day: LimitUse | null; week: LimitUse | null } {
|
|
320
|
+
const today = now.toISOString().slice(0, 10);
|
|
321
|
+
const one = (buckets: Bucket[], key: string, limit: number | null): LimitUse | null =>
|
|
322
|
+
report.limits === null || limit === null ? null : { key, usedUsd: buckets.find((b) => b.key === key)?.countedAgainstLimitUsd ?? null, limitUsd: limit };
|
|
323
|
+
return { day: one(report.days, today, report.limits?.dailyUsd ?? null), week: one(report.weeks, weekStart(today), report.limits?.weeklyUsd ?? null) };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export function buildReport(input: ReportInput): Report {
|
|
327
|
+
const sources = input.sources ?? [...SOURCES];
|
|
328
|
+
const rows = input.rows.filter((r) => sources.includes(r.source));
|
|
329
|
+
const totals = emptySplit();
|
|
330
|
+
const aside = emptyAside();
|
|
331
|
+
let unknownCostCalls = 0;
|
|
332
|
+
for (const row of rows) {
|
|
333
|
+
if (row.state === "settled") addSpend(totals, row);
|
|
334
|
+
addAside(aside, row);
|
|
335
|
+
unknownCostCalls += row.calls.filter((c) => !c.costKnown).length;
|
|
336
|
+
}
|
|
337
|
+
return {
|
|
338
|
+
filters: { sources },
|
|
339
|
+
coverage: { laptop: sources.includes("laptop") ? hull(input.coverage.laptop) : null, actions: sources.includes("actions") ? hull(input.coverage.actions) : null },
|
|
340
|
+
pulledAt: input.pulledAt ?? null,
|
|
341
|
+
limits: input.limits ?? null,
|
|
342
|
+
totals: roundSplit(totals),
|
|
343
|
+
aside: roundAside(aside),
|
|
344
|
+
days: buckets(input, "day", sources),
|
|
345
|
+
weeks: buckets(input, "week", sources),
|
|
346
|
+
groups: { repository: group(rows, "repo"), pr: group(rows, "pr"), model: group(rows, "model") },
|
|
347
|
+
unknownCostCalls,
|
|
348
|
+
};
|
|
349
|
+
}
|
package/src/status/command.ts
CHANGED
|
@@ -1,19 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `wachiman status`: what this laptop knows about its own local runs, and what they cost. It reads
|
|
3
3
|
* the history files (`local --history`) and local git metadata only: no `claude`, no GitHub, no
|
|
4
|
-
* network. Damaged history files are moved aside with a warning. Runs made by the GitHub Actions workflow
|
|
4
|
+
* network. Damaged history files are moved aside with a warning. Runs made by the GitHub Actions workflow
|
|
5
|
+
* are not in these files and are not counted, unless the user connected a ledger and pulled it (ADR 0039):
|
|
6
|
+
* then the pulled day files are read directly (never the index, so `status` answers even when the index
|
|
7
|
+
* cannot be written) and one report covers both sources.
|
|
5
8
|
*/
|
|
6
9
|
import { UsageError } from "../config";
|
|
7
10
|
import { wachimanHome } from "../accounts/config";
|
|
8
11
|
import { historySettings, historyRoot, listKeys, readRuns, repositoryKey } from "../history/store";
|
|
9
12
|
import type { HistoryRun } from "../history/types";
|
|
13
|
+
import { readLedgerFromFiles } from "../ledger-read/rows";
|
|
14
|
+
import { buildReport, deriveCoverage, group as groupRows, limitUse, SOURCES, weekStart, type GroupBy, type LimitUse, type Report, type Source, type Split, type SpendRow } from "../spend/report";
|
|
10
15
|
|
|
11
16
|
export const STATUS_FORMAT = "wachiman.status/1";
|
|
12
17
|
|
|
13
18
|
export const statusUsage = `wachiman status [--json] [--since <n>d] [--all-repos] [--repo <name|key>] [--model <text>]
|
|
14
|
-
[--profile <name>] [--by day|repo|model|profile] [--
|
|
19
|
+
[--profile <name>] [--by day|week|repo|pr|model|profile|source] [--source laptop|actions|all]
|
|
20
|
+
[--refresh] [--repo-dir <dir>]`;
|
|
15
21
|
|
|
16
|
-
export const GROUPS = ["day", "repo", "model", "profile"] as const;
|
|
22
|
+
export const GROUPS = ["day", "week", "repo", "pr", "model", "profile", "source"] as const;
|
|
17
23
|
export type Group = (typeof GROUPS)[number];
|
|
18
24
|
|
|
19
25
|
export interface StatusArgs {
|
|
@@ -24,11 +30,14 @@ export interface StatusArgs {
|
|
|
24
30
|
model?: string;
|
|
25
31
|
profile?: string;
|
|
26
32
|
by: Group;
|
|
33
|
+
source: Source | "all";
|
|
34
|
+
/** Download the ledger first (the only request `status` can make). */
|
|
35
|
+
refresh: boolean;
|
|
27
36
|
}
|
|
28
37
|
|
|
29
38
|
/** The arguments after `status` (`--repo-dir` is already taken out). Both `--x v` and `--x=v`. */
|
|
30
39
|
export function parseStatusArgs(argv: string[]): StatusArgs | { help: true } {
|
|
31
|
-
const args: StatusArgs = { json: false, allRepos: false, by: "day" };
|
|
40
|
+
const args: StatusArgs = { json: false, allRepos: false, by: "day", source: "all", refresh: false };
|
|
32
41
|
for (let i = 0; i < argv.length; i++) {
|
|
33
42
|
const arg = argv[i];
|
|
34
43
|
if (arg === "--help" || arg === "-h") return { help: true };
|
|
@@ -45,6 +54,12 @@ export function parseStatusArgs(argv: string[]): StatusArgs | { help: true } {
|
|
|
45
54
|
};
|
|
46
55
|
if (name === "--json") (flag(), (args.json = true));
|
|
47
56
|
else if (name === "--all-repos") (flag(), (args.allRepos = true));
|
|
57
|
+
else if (name === "--refresh") (flag(), (args.refresh = true));
|
|
58
|
+
else if (name === "--source") {
|
|
59
|
+
const v = value();
|
|
60
|
+
if (v !== "all" && !(SOURCES as readonly string[]).includes(v)) throw new UsageError(`--source is one of laptop, actions, all; got "${v}".`);
|
|
61
|
+
args.source = v as Source | "all";
|
|
62
|
+
}
|
|
48
63
|
else if (name === "--repo") args.repo = value();
|
|
49
64
|
else if (name === "--model") args.model = value();
|
|
50
65
|
else if (name === "--profile") args.profile = value();
|
|
@@ -97,29 +112,34 @@ export function flatten(run: HistoryRun): StatusRun {
|
|
|
97
112
|
};
|
|
98
113
|
}
|
|
99
114
|
|
|
100
|
-
const keyOf: Record<Group, (r: StatusRun) => string> = {
|
|
101
|
-
day: (r) => r.at.slice(0, 10),
|
|
102
|
-
repo: (r) => r.repositoryKey,
|
|
103
|
-
model: (r) => (r.effort ? `${r.model} (${r.effort})` : r.model),
|
|
104
|
-
profile: (r) => r.profile || "(none)",
|
|
105
|
-
};
|
|
106
|
-
|
|
107
115
|
export interface StatusGroup {
|
|
108
116
|
key: string;
|
|
109
117
|
runs: number;
|
|
110
118
|
costUsdEstimate: number;
|
|
111
119
|
}
|
|
112
120
|
|
|
121
|
+
/** A laptop run in the row shape of the spend report. A local run is an API-equivalent estimate (ADR 0019). */
|
|
122
|
+
export function toRow(r: StatusRun): SpendRow {
|
|
123
|
+
const day = r.at.slice(0, 10);
|
|
124
|
+
return {
|
|
125
|
+
source: "laptop",
|
|
126
|
+
state: "settled",
|
|
127
|
+
day,
|
|
128
|
+
week: weekStart(day),
|
|
129
|
+
repositoryKey: r.repositoryKey,
|
|
130
|
+
repository: r.repository,
|
|
131
|
+
pr: null,
|
|
132
|
+
runId: `${r.repositoryKey}@${r.at}`,
|
|
133
|
+
profile: r.profile,
|
|
134
|
+
costUsd: r.costUsdEstimate,
|
|
135
|
+
reservedUsd: 0,
|
|
136
|
+
calls: [{ model: r.effort ? `${r.model} (${r.effort})` : r.model, auth: "subscription", costUsd: r.costUsdEstimate, costKnown: true }],
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Groups laptop runs through the spend report; kept for the callers that group `StatusRun`s. */
|
|
113
141
|
export function group(runs: StatusRun[], by: Group): StatusGroup[] {
|
|
114
|
-
|
|
115
|
-
for (const r of runs) {
|
|
116
|
-
const key = keyOf[by](r);
|
|
117
|
-
const g = map.get(key) ?? { key, runs: 0, costUsdEstimate: 0 };
|
|
118
|
-
g.runs++;
|
|
119
|
-
g.costUsdEstimate += r.costUsdEstimate;
|
|
120
|
-
map.set(key, g);
|
|
121
|
-
}
|
|
122
|
-
return [...map.values()].sort((a, b) => (by === "day" ? b.key.localeCompare(a.key) : b.costUsdEstimate - a.costUsdEstimate));
|
|
142
|
+
return groupRows(runs.map(toRow), by as GroupBy).map((g) => ({ key: g.key, runs: g.split.total.runs, costUsdEstimate: g.split.total.usd }));
|
|
123
143
|
}
|
|
124
144
|
|
|
125
145
|
export function filterRuns(runs: StatusRun[], args: StatusArgs, now: Date): StatusRun[] {
|
|
@@ -133,10 +153,8 @@ export function filterRuns(runs: StatusRun[], args: StatusArgs, now: Date): Stat
|
|
|
133
153
|
);
|
|
134
154
|
}
|
|
135
155
|
|
|
136
|
-
const usd = (n: number) => `$${n.toFixed(2)}`;
|
|
137
|
-
const pad = (text: string, width: number) => text + " ".repeat(Math.max(0, width - text.length));
|
|
138
|
-
|
|
139
156
|
export const LOCAL_ONLY = "Local runs only: those kept by `wachiman local --history`. Runs by the GitHub Actions workflow are not counted.";
|
|
157
|
+
export const WITH_LEDGER = "Laptop runs kept by `wachiman local --history` and GitHub Actions runs downloaded from the ledger. The ledger limit is best-effort and counts Actions runs only.";
|
|
140
158
|
|
|
141
159
|
export interface StatusIo {
|
|
142
160
|
stdout: (text: string) => void;
|
|
@@ -145,11 +163,69 @@ export interface StatusIo {
|
|
|
145
163
|
version: string;
|
|
146
164
|
}
|
|
147
165
|
|
|
166
|
+
/** `owner/name` of the clone's `origin`, lower case, when it has one. */
|
|
167
|
+
function remoteSlug(remote: string | undefined): string | undefined {
|
|
168
|
+
return remote?.match(/\/([^/]+\/[^/]+)$/)?.[1]?.toLowerCase();
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Ledger rows kept by the same filters as the laptop runs; `slug` scopes them to one repository. */
|
|
172
|
+
function filterLedgerRows(rows: SpendRow[], args: StatusArgs, now: Date, slug: string | undefined, all: StatusRun[]): SpendRow[] {
|
|
173
|
+
const cutoff = args.sinceDays === undefined ? undefined : now.getTime() - args.sinceDays * 86_400_000;
|
|
174
|
+
const tail = (r: SpendRow) => r.repository.split("/").at(-1)?.toLowerCase();
|
|
175
|
+
const wanted = args.repo?.toLowerCase();
|
|
176
|
+
const repoMatches = (r: SpendRow) => {
|
|
177
|
+
if (args.repo !== undefined) return r.repository.toLowerCase() === args.repo.toLowerCase() || tail(r) === wanted || all.some((l) => l.repositoryKey === args.repo && l.repository.toLowerCase() === tail(r));
|
|
178
|
+
return args.allRepos || (slug !== undefined && r.repository.toLowerCase() === slug);
|
|
179
|
+
};
|
|
180
|
+
return rows.filter(
|
|
181
|
+
(r) =>
|
|
182
|
+
r.source === "actions" &&
|
|
183
|
+
(cutoff === undefined || Date.parse(`${r.day}T23:59:59Z`) >= cutoff) &&
|
|
184
|
+
repoMatches(r) &&
|
|
185
|
+
(args.model === undefined || r.calls.some((c) => c.model.includes(args.model!))) &&
|
|
186
|
+
args.profile === undefined,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const usd = (n: number) => `$${n.toFixed(2)}`;
|
|
191
|
+
const pad = (text: string, width: number) => text + " ".repeat(Math.max(0, width - text.length));
|
|
192
|
+
|
|
193
|
+
/** Estimated dollars, with unknown-credential dollars named beside them and never added in. */
|
|
194
|
+
function estimatedWithUnknown(s: Split): string {
|
|
195
|
+
const c = s.byCredential;
|
|
196
|
+
return c.unknown.usd > 0 ? `${usd(c.estimated.usd)} + ${usd(c.unknown.usd)} unknown` : usd(c.estimated.usd);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function creditLine(report: Report): string {
|
|
200
|
+
const c = report.totals.byCredential;
|
|
201
|
+
const parts = [`${usd(c.billed.usd)} billed (API key)`, `${usd(c.estimated.usd)} estimated (subscription, API-equivalent, not a bill)`];
|
|
202
|
+
if (c.unknown.usd > 0) parts.push(`${usd(c.unknown.usd)} of unknown credential`);
|
|
203
|
+
return parts.join(" + ");
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The ledger limit is per account across every repository, so these figures never see `--repo`, `--model`, `--since` or `--profile`. */
|
|
207
|
+
function limitLines(use: { day: LimitUse | null; week: LimitUse | null }, now: Date): string[] {
|
|
208
|
+
const today = now.toISOString().slice(0, 10);
|
|
209
|
+
const one = (label: string, u: LimitUse | null) =>
|
|
210
|
+
u ? [`${label}: ${u.usedUsd === null ? "no data" : `${usd(u.usedUsd)} of ${usd(u.limitUsd)}`} counted against the ledger limit (Actions runs only, whole account, all repositories, best-effort)`] : [];
|
|
211
|
+
return [...one(`Today (${today} UTC)`, use.day), ...one(`This week (Monday ${weekStart(today)} UTC)`, use.week)];
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function asideLine(report: Report): string[] {
|
|
215
|
+
const a = report.aside;
|
|
216
|
+
const parts: string[] = [];
|
|
217
|
+
if (a.unreserved.runs) parts.push(`${a.unreserved.runs} run${a.unreserved.runs === 1 ? "" : "s"} not reserved (${usd(a.unreserved.usd)} recorded after the fact)`);
|
|
218
|
+
if (a.unsettled.runs) parts.push(`${a.unsettled.runs} reservation${a.unsettled.runs === 1 ? "" : "s"} never settled (${usd(a.unsettled.reservedUsd)} held, not spent)`);
|
|
219
|
+
if (a.reserved.runs) parts.push(`${a.reserved.runs} run${a.reserved.runs === 1 ? "" : "s"} still reserved (${usd(a.reserved.reservedUsd)} held)`);
|
|
220
|
+
return parts.length ? [`Not counted as spend: ${parts.join("; ")}.`] : [];
|
|
221
|
+
}
|
|
222
|
+
|
|
148
223
|
export function runStatus(args: StatusArgs, repoDir: string, env: Record<string, string | undefined>, io: StatusIo): number {
|
|
149
224
|
const home = wachimanHome(env);
|
|
150
225
|
const root = historyRoot(home);
|
|
151
226
|
const now = io.now?.() ?? new Date();
|
|
152
|
-
const
|
|
227
|
+
const repo = args.allRepos || args.repo !== undefined ? undefined : repositoryKey(repoDir);
|
|
228
|
+
const keys = args.allRepos || args.repo !== undefined ? listKeys(root) : [repo!.key];
|
|
153
229
|
const all = keys.flatMap((key) => readRuns(root, key, io.stderr)).map(flatten);
|
|
154
230
|
const retentionDays = historySettings(env, true).days;
|
|
155
231
|
if (args.repo !== undefined && !all.some(r => r.repositoryKey === args.repo)) {
|
|
@@ -158,44 +234,82 @@ export function runStatus(args: StatusArgs, repoDir: string, env: Record<string,
|
|
|
158
234
|
}
|
|
159
235
|
const effectiveArgs = args.repo !== undefined && all.some(r => r.repositoryKey === args.repo) ? { ...args, repo: undefined } : args;
|
|
160
236
|
const scoped = effectiveArgs !== args ? all.filter(r => r.repositoryKey === args.repo) : all;
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
237
|
+
const laptopRuns = filterRuns(scoped, effectiveArgs, now).sort((a, b) => a.at.localeCompare(b.at));
|
|
238
|
+
|
|
239
|
+
// The ledger is read only from files the user pulled; with none, everything below is the local-only status.
|
|
240
|
+
const ledger = readLedgerFromFiles(home, io.stderr);
|
|
241
|
+
const hasLedger = ledger.pulledAt !== null;
|
|
242
|
+
if (!hasLedger && args.source === "actions") throw new UsageError("--source actions needs a pulled ledger: run `wachiman ledger connect`, then `wachiman ledger pull`.");
|
|
243
|
+
const actionsRows = hasLedger ? filterLedgerRows(ledger.rows, args, now, remoteSlug(repo?.remote), all) : [];
|
|
244
|
+
const sources: Source[] = args.source === "all" ? [...SOURCES] : [args.source];
|
|
245
|
+
const useLaptop = sources.includes("laptop");
|
|
246
|
+
const rows = [...(useLaptop ? laptopRuns.map(toRow) : []), ...(sources.includes("actions") ? actionsRows : [])];
|
|
247
|
+
const report = buildReport({
|
|
248
|
+
rows,
|
|
249
|
+
sources: hasLedger ? sources : ["laptop"],
|
|
250
|
+
coverage: deriveCoverage(scoped.map(toRow), ledger.ranges, now),
|
|
251
|
+
limits: ledger.limits,
|
|
252
|
+
pulledAt: ledger.pulledAt,
|
|
253
|
+
now,
|
|
254
|
+
});
|
|
255
|
+
// The limit figures come from every ledger row of the account, whatever the filters say.
|
|
256
|
+
const limitReport = buildReport({ rows: ledger.rows, sources: ["actions"], coverage: { laptop: [], actions: ledger.ranges }, limits: ledger.limits, pulledAt: ledger.pulledAt, now });
|
|
257
|
+
const limits = limitUse(limitReport, now);
|
|
258
|
+
const groups = groupRows(rows, args.by as GroupBy);
|
|
259
|
+
const settled = rows.filter((r) => r.state === "settled");
|
|
260
|
+
const total = report.totals.total.usd;
|
|
164
261
|
const filters = {
|
|
165
262
|
scope: args.allRepos ? "all-repos" : args.repo !== undefined ? "repo" : "this-repo",
|
|
166
263
|
...(args.repo !== undefined ? { repo: args.repo } : {}),
|
|
167
264
|
...(args.sinceDays !== undefined ? { sinceDays: args.sinceDays } : {}),
|
|
168
265
|
...(args.model !== undefined ? { model: args.model } : {}),
|
|
169
266
|
...(args.profile !== undefined ? { profile: args.profile } : {}),
|
|
267
|
+
...(hasLedger ? { source: args.source } : {}),
|
|
170
268
|
};
|
|
269
|
+
const legacyGroups = groups.map((g) => ({ key: g.key, runs: g.split.total.runs, costUsdEstimate: g.split.total.usd }));
|
|
171
270
|
|
|
172
271
|
if (args.json) {
|
|
173
272
|
const doc = {
|
|
174
273
|
format: STATUS_FORMAT,
|
|
175
274
|
version: io.version,
|
|
176
275
|
home,
|
|
177
|
-
scope: LOCAL_ONLY,
|
|
276
|
+
scope: hasLedger ? WITH_LEDGER : LOCAL_ONLY,
|
|
178
277
|
retentionDays,
|
|
179
278
|
filters,
|
|
180
279
|
by: args.by,
|
|
181
|
-
totals: { runs:
|
|
182
|
-
groups,
|
|
183
|
-
runs,
|
|
280
|
+
totals: { runs: settled.length, costUsdEstimate: total },
|
|
281
|
+
groups: hasLedger ? groups.map((g, i) => ({ ...legacyGroups[i], label: g.label, split: g.split })) : legacyGroups,
|
|
282
|
+
runs: useLaptop ? laptopRuns : [],
|
|
283
|
+
...(hasLedger ? { report, limitUse: limits } : {}),
|
|
184
284
|
};
|
|
185
285
|
io.stdout(`${JSON.stringify(doc, null, 2)}\n`);
|
|
186
286
|
return 0;
|
|
187
287
|
}
|
|
188
288
|
|
|
189
|
-
const lines = [`Wachiman ${io.version} (home ${home})`, LOCAL_ONLY, ""];
|
|
190
|
-
if (
|
|
289
|
+
const lines = [`Wachiman ${io.version} (home ${home})`, hasLedger ? WITH_LEDGER : LOCAL_ONLY, ""];
|
|
290
|
+
if (settled.length === 0 && !hasLedger) {
|
|
191
291
|
lines.push(all.length === 0 ? "No local runs kept yet: run `wachiman local --history` to start. Run `wachiman doctor` to check this machine." : `No run matches the filters (${all.length} kept before filtering).`);
|
|
192
292
|
io.stdout(`${lines.join("\n")}\n`);
|
|
193
293
|
return 0;
|
|
194
294
|
}
|
|
295
|
+
if (settled.length === 0) {
|
|
296
|
+
lines.push(all.length === 0 && actionsRows.length === 0 ? "No run to show: no local run is kept and no ledger entry matches. Run `wachiman ledger pull` to refresh the ledger." : "No run matches the filters.");
|
|
297
|
+
lines.push(...asideLine(report), ...limitLines(limits, now));
|
|
298
|
+
io.stdout(`${lines.join("\n")}\n`);
|
|
299
|
+
return 0;
|
|
300
|
+
}
|
|
195
301
|
const w = Math.max(args.by.length, ...groups.map((g) => g.key.length));
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
302
|
+
const days = settled.map((r) => r.day).sort();
|
|
303
|
+
if (hasLedger) {
|
|
304
|
+
lines.push(`${settled.length} run${settled.length === 1 ? "" : "s"}, ${creditLine(report)}, ${days[0]} → ${days.at(-1)}`);
|
|
305
|
+
lines.push(...limitLines(limits, now), ...asideLine(report), "");
|
|
306
|
+
lines.push(` ${pad(args.by, w)} runs calls billed estimated`);
|
|
307
|
+
for (const g of groups) lines.push(` ${pad(g.key, w)} ${pad(String(g.split.total.runs), 4)} ${pad(String(g.split.total.calls), 5)} ${pad(usd(g.split.byCredential.billed.usd), 6)} ${estimatedWithUnknown(g.split)}`);
|
|
308
|
+
} else {
|
|
309
|
+
lines.push(`${settled.length} run${settled.length === 1 ? "" : "s"}, ${usd(total)} estimated (API-equivalent, not a bill), ${laptopRuns[0].at.slice(0, 10)} → ${laptopRuns.at(-1)!.at.slice(0, 10)}`, "");
|
|
310
|
+
lines.push(` ${pad(args.by, w)} runs cost`);
|
|
311
|
+
for (const g of legacyGroups) lines.push(` ${pad(g.key, w)} ${pad(String(g.runs), 4)} ${usd(g.costUsdEstimate)}`);
|
|
312
|
+
}
|
|
199
313
|
lines.push("", retentionDays === 0 ? "New `--history` runs keep all runs (WACHIMAN_HISTORY_DAYS=0). `--json` lists every run with its attributes." : `A new \`--history\` run deletes runs older than ${retentionDays} days (WACHIMAN_HISTORY_DAYS changes that). \`--json\` lists every run with its attributes.`);
|
|
200
314
|
io.stdout(`${lines.join("\n")}\n`);
|
|
201
315
|
return 0;
|