big-spender 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +272 -2
- package/dist/cli.d.ts +10 -0
- package/dist/cli.js +106 -0
- package/dist/collector.mjs +779 -0
- package/dist/context.d.ts +22 -0
- package/dist/context.js +19 -0
- package/dist/devices.d.ts +22 -0
- package/dist/devices.js +24 -0
- package/dist/envfile.d.ts +12 -0
- package/dist/envfile.js +46 -0
- package/dist/history.d.ts +5 -0
- package/dist/history.js +85 -0
- package/dist/install.d.ts +5 -0
- package/dist/install.js +211 -0
- package/dist/page.d.ts +2 -0
- package/dist/page.js +88 -0
- package/dist/paths.d.ts +23 -0
- package/dist/paths.js +31 -0
- package/dist/prompt.d.ts +7 -0
- package/dist/prompt.js +38 -0
- package/dist/push.d.ts +3 -0
- package/dist/push.js +156 -0
- package/dist/scheduler.d.ts +24 -0
- package/dist/scheduler.js +153 -0
- package/dist/schema.d.ts +89 -0
- package/dist/schema.js +57 -0
- package/dist/serve.d.ts +14 -0
- package/dist/serve.js +138 -0
- package/dist/server/index.d.ts +19 -0
- package/dist/server/index.js +27 -0
- package/dist/server/ingest.d.ts +7 -0
- package/dist/server/ingest.js +93 -0
- package/dist/store.d.ts +7 -0
- package/dist/store.js +68 -0
- package/dist/summary.d.ts +87 -0
- package/dist/summary.js +150 -0
- package/package.json +65 -5
- package/templates/big-spender.service +14 -0
- package/templates/big-spender.timer +12 -0
- package/templates/env.example +9 -0
- package/templates/local.big-spender.plist +39 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type Paths } from './paths.ts';
|
|
2
|
+
import type { Ctl } from './scheduler.ts';
|
|
3
|
+
import { type Prompter } from './prompt.ts';
|
|
4
|
+
/** Everything a command reads from its surroundings, so tests can hand it a throwaway HOME. */
|
|
5
|
+
export type Context = {
|
|
6
|
+
env: NodeJS.ProcessEnv;
|
|
7
|
+
platform: NodeJS.Platform;
|
|
8
|
+
paths: Paths;
|
|
9
|
+
/** The collector bundled with this package. `install` copies it to `paths.collector`. */
|
|
10
|
+
collector: string;
|
|
11
|
+
templatesDir: string;
|
|
12
|
+
prompter: () => Prompter;
|
|
13
|
+
/** Replaces systemctl and launchctl, so tests can watch and fail the calls. */
|
|
14
|
+
ctl?: Ctl;
|
|
15
|
+
/** Releases the prompter if one was opened, so stdin does not keep the process alive. */
|
|
16
|
+
dispose(): void;
|
|
17
|
+
out(line: string): void;
|
|
18
|
+
err(line: string): void;
|
|
19
|
+
};
|
|
20
|
+
export declare function defaultContext(): Context;
|
|
21
|
+
export declare class UsageError extends Error {
|
|
22
|
+
}
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { resolvePaths } from './paths.js';
|
|
3
|
+
import { createPrompter } from './prompt.js';
|
|
4
|
+
export function defaultContext() {
|
|
5
|
+
let prompter;
|
|
6
|
+
return {
|
|
7
|
+
env: process.env,
|
|
8
|
+
platform: process.platform,
|
|
9
|
+
paths: resolvePaths(),
|
|
10
|
+
collector: fileURLToPath(new URL('./collector.mjs', import.meta.url)),
|
|
11
|
+
templatesDir: fileURLToPath(new URL('../templates', import.meta.url)),
|
|
12
|
+
prompter: () => (prompter ??= createPrompter()),
|
|
13
|
+
dispose: () => prompter?.close(),
|
|
14
|
+
out: (line) => console.log(line),
|
|
15
|
+
err: (line) => console.error(line)
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export class UsageError extends Error {
|
|
19
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type DeviceInfo = {
|
|
2
|
+
name: string;
|
|
3
|
+
color: string;
|
|
4
|
+
};
|
|
5
|
+
export type DeviceConfig = {
|
|
6
|
+
/** Known devices by id, in display order. */
|
|
7
|
+
devices: Record<string, DeviceInfo>;
|
|
8
|
+
/**
|
|
9
|
+
* Devices whose id is not listed above:
|
|
10
|
+
* - `'by-id'` (default): shown under their own id, with the next free palette colour.
|
|
11
|
+
* - `'other'`: merged into one "Other" line, so no device id is ever published. Use this
|
|
12
|
+
* when ids are hostnames you'd rather keep private.
|
|
13
|
+
*/
|
|
14
|
+
unknownDevices?: 'by-id' | 'other';
|
|
15
|
+
};
|
|
16
|
+
export type ResolvedDevice = DeviceInfo & {
|
|
17
|
+
order: number;
|
|
18
|
+
};
|
|
19
|
+
export declare const OTHER: DeviceInfo;
|
|
20
|
+
export declare const PALETTE: string[];
|
|
21
|
+
/** Maps every reporting device id to its public name, colour and display order. */
|
|
22
|
+
export declare function resolveDevices(ids: Iterable<string>, config: DeviceConfig): Map<string, ResolvedDevice>;
|
package/dist/devices.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Public names and colours for the devices that report usage. Collectors identify themselves by
|
|
2
|
+
// device id; the server maps each id to a public name here, before anything is published.
|
|
3
|
+
// Which devices exist and what they are called is the DeviceConfig the server is given.
|
|
4
|
+
export const OTHER = { name: 'Other', color: '#97a098' };
|
|
5
|
+
// Colours for devices without one. Validated with the dataviz palette checks (normal vision and
|
|
6
|
+
// CVD) against each other and the dark chart surface (#121614). Cycles after the last one.
|
|
7
|
+
export const PALETTE = ['#7fa034', '#3899e2', '#d77343', '#a03fa7'];
|
|
8
|
+
/** Maps every reporting device id to its public name, colour and display order. */
|
|
9
|
+
export function resolveDevices(ids, config) {
|
|
10
|
+
const out = new Map();
|
|
11
|
+
const known = Object.entries(config.devices);
|
|
12
|
+
known.forEach(([id, info], order) => out.set(id, { ...info, order }));
|
|
13
|
+
const unknown = [...new Set(ids)].filter((id) => !Object.hasOwn(config.devices, id)).sort();
|
|
14
|
+
if (config.unknownDevices === 'other') {
|
|
15
|
+
for (const id of unknown)
|
|
16
|
+
out.set(id, { ...OTHER, order: Number.MAX_SAFE_INTEGER });
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
19
|
+
const used = new Set(known.map(([, info]) => info.color.toLowerCase()));
|
|
20
|
+
const free = PALETTE.filter((c) => !used.has(c.toLowerCase()));
|
|
21
|
+
const colors = free.length ? free : PALETTE;
|
|
22
|
+
unknown.forEach((id, i) => out.set(id, { name: id, color: colors[i % colors.length], order: known.length + i }));
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare const SETTINGS: readonly ['DEVICE_ID', 'INGEST_URL', 'INGEST_TOKEN'];
|
|
2
|
+
export type Setting = (typeof SETTINGS)[number];
|
|
3
|
+
export declare function parseEnv(text: string): Record<string, string>;
|
|
4
|
+
/** The value of a setting under its current name, or the name collectors used before the rename. */
|
|
5
|
+
export declare function setting(vars: Record<string, string | undefined>, name: Setting): string;
|
|
6
|
+
/**
|
|
7
|
+
* Renames USAGE_DEVICE_ID, USAGE_INGEST_URL and USAGE_INGEST_TOKEN to their BIG_SPENDER_ names,
|
|
8
|
+
* keeping every value, comment and other line. A key whose new name is already defined is left alone.
|
|
9
|
+
*/
|
|
10
|
+
export declare function renameLegacyKeys(text: string): string;
|
|
11
|
+
/** Sets each key in place, or appends it, leaving all other lines as they are. */
|
|
12
|
+
export declare function upsertEnv(text: string, values: Record<string, string>): string;
|
package/dist/envfile.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// KEY=value lines, as the collector and systemd's EnvironmentFile read them.
|
|
2
|
+
const LINE = /^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*?)\s*$/;
|
|
3
|
+
export const SETTINGS = ['DEVICE_ID', 'INGEST_URL', 'INGEST_TOKEN'];
|
|
4
|
+
export function parseEnv(text) {
|
|
5
|
+
const out = {};
|
|
6
|
+
for (const raw of text.split('\n')) {
|
|
7
|
+
const m = LINE.exec(raw);
|
|
8
|
+
if (m)
|
|
9
|
+
out[m[1]] = m[2].replace(/^(['"])(.*)\1$/, '$2');
|
|
10
|
+
}
|
|
11
|
+
return out;
|
|
12
|
+
}
|
|
13
|
+
/** The value of a setting under its current name, or the name collectors used before the rename. */
|
|
14
|
+
export function setting(vars, name) {
|
|
15
|
+
return vars[`BIG_SPENDER_${name}`] || vars[`USAGE_${name}`] || '';
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Renames USAGE_DEVICE_ID, USAGE_INGEST_URL and USAGE_INGEST_TOKEN to their BIG_SPENDER_ names,
|
|
19
|
+
* keeping every value, comment and other line. A key whose new name is already defined is left alone.
|
|
20
|
+
*/
|
|
21
|
+
export function renameLegacyKeys(text) {
|
|
22
|
+
const defined = parseEnv(text);
|
|
23
|
+
return text
|
|
24
|
+
.split('\n')
|
|
25
|
+
.map((line) => {
|
|
26
|
+
const m = /^(\s*(?:export\s+)?)USAGE_(DEVICE_ID|INGEST_URL|INGEST_TOKEN)(\s*=.*)$/.exec(line);
|
|
27
|
+
if (!m || `BIG_SPENDER_${m[2]}` in defined)
|
|
28
|
+
return line;
|
|
29
|
+
return `${m[1]}BIG_SPENDER_${m[2]}${m[3]}`;
|
|
30
|
+
})
|
|
31
|
+
.join('\n');
|
|
32
|
+
}
|
|
33
|
+
/** Sets each key in place, or appends it, leaving all other lines as they are. */
|
|
34
|
+
export function upsertEnv(text, values) {
|
|
35
|
+
const lines = text.split('\n');
|
|
36
|
+
if (lines.at(-1) === '')
|
|
37
|
+
lines.pop();
|
|
38
|
+
for (const [key, value] of Object.entries(values)) {
|
|
39
|
+
const at = lines.findLastIndex((l) => LINE.exec(l)?.[1] === key);
|
|
40
|
+
if (at === -1)
|
|
41
|
+
lines.push(`${key}=${value}`);
|
|
42
|
+
else
|
|
43
|
+
lines[at] = `${key}=${value}`;
|
|
44
|
+
}
|
|
45
|
+
return `${lines.join('\n')}\n`;
|
|
46
|
+
}
|
package/dist/history.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { MAX_ROWS, usageRowSchema } from './schema.js';
|
|
2
|
+
const DAY_MS = 86_400_000;
|
|
3
|
+
const round = (n) => Math.round(n * 1e6) / 1e6;
|
|
4
|
+
const dayOf = (r) => Math.floor(Date.parse(r.hour) / DAY_MS);
|
|
5
|
+
const keyOf = (r) => `${dayOf(r)}|${r.provider}|${r.model}`;
|
|
6
|
+
function compareRows(a, b) {
|
|
7
|
+
return (Date.parse(a.hour) - Date.parse(b.hour) ||
|
|
8
|
+
a.provider.localeCompare(b.provider) ||
|
|
9
|
+
a.model.localeCompare(b.model) ||
|
|
10
|
+
(a.granularity ?? 'hour').localeCompare(b.granularity ?? 'hour'));
|
|
11
|
+
}
|
|
12
|
+
function group(rows) {
|
|
13
|
+
const out = new Map();
|
|
14
|
+
for (const r of rows) {
|
|
15
|
+
const key = keyOf(r);
|
|
16
|
+
const list = out.get(key);
|
|
17
|
+
if (list)
|
|
18
|
+
list.push(r);
|
|
19
|
+
else
|
|
20
|
+
out.set(key, [r]);
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
function rollUp(rows) {
|
|
25
|
+
const [first] = rows;
|
|
26
|
+
if (rows.length === 1 && first.granularity === 'day')
|
|
27
|
+
return rows;
|
|
28
|
+
const sum = (pick) => rows.reduce((total, r) => total + pick(r), 0);
|
|
29
|
+
const sessionsAtLeast = Math.max(...rows.map((r) => r.sessions));
|
|
30
|
+
const day = {
|
|
31
|
+
hour: new Date(dayOf(first) * DAY_MS).toISOString(),
|
|
32
|
+
granularity: 'day',
|
|
33
|
+
provider: first.provider,
|
|
34
|
+
model: first.model,
|
|
35
|
+
sessions: sessionsAtLeast,
|
|
36
|
+
inputTokens: sum((r) => r.inputTokens),
|
|
37
|
+
cacheReadTokens: sum((r) => r.cacheReadTokens),
|
|
38
|
+
cacheWrite5mTokens: sum((r) => r.cacheWrite5mTokens),
|
|
39
|
+
cacheWrite1hTokens: sum((r) => r.cacheWrite1hTokens),
|
|
40
|
+
outputTokens: sum((r) => r.outputTokens),
|
|
41
|
+
costUsd: {
|
|
42
|
+
input: round(sum((r) => r.costUsd.input)),
|
|
43
|
+
cacheRead: round(sum((r) => r.costUsd.cacheRead)),
|
|
44
|
+
cacheWrite: round(sum((r) => r.costUsd.cacheWrite)),
|
|
45
|
+
output: round(sum((r) => r.costUsd.output))
|
|
46
|
+
},
|
|
47
|
+
cacheSavingsUsd: round(sum((r) => r.cacheSavingsUsd))
|
|
48
|
+
};
|
|
49
|
+
// A sum can pass a field's cap, and a day can start outside the schema's date range.
|
|
50
|
+
return usageRowSchema.safeParse(day).success ? [day] : rows;
|
|
51
|
+
}
|
|
52
|
+
function dropOldestDays(rows, excess) {
|
|
53
|
+
let cut = 0;
|
|
54
|
+
let days = 0;
|
|
55
|
+
while (cut < excess) {
|
|
56
|
+
const day = dayOf(rows[cut]);
|
|
57
|
+
while (cut < rows.length && dayOf(rows[cut]) === day)
|
|
58
|
+
cut++;
|
|
59
|
+
days++;
|
|
60
|
+
}
|
|
61
|
+
return { rows: rows.slice(cut), days };
|
|
62
|
+
}
|
|
63
|
+
export function mergeSnapshots(stored, next) {
|
|
64
|
+
const fresh = [...next.hourly].sort(compareRows);
|
|
65
|
+
if (!stored)
|
|
66
|
+
return { snapshot: { ...next, hourly: fresh }, droppedDays: 0 };
|
|
67
|
+
const reported = new Set(fresh.map(keyOf));
|
|
68
|
+
const kept = [...group(stored.hourly)]
|
|
69
|
+
.filter(([key]) => !reported.has(key))
|
|
70
|
+
.flatMap(([, rows]) => rollUp(rows))
|
|
71
|
+
.sort(compareRows);
|
|
72
|
+
let coverage = Date.parse(stored.coverageStart) < Date.parse(next.coverageStart)
|
|
73
|
+
? stored.coverageStart
|
|
74
|
+
: next.coverageStart;
|
|
75
|
+
const trimmed = dropOldestDays(kept, kept.length + fresh.length - MAX_ROWS);
|
|
76
|
+
const droppedDays = trimmed.days;
|
|
77
|
+
const hourly = [...trimmed.rows, ...fresh].sort(compareRows);
|
|
78
|
+
if (droppedDays > 0) {
|
|
79
|
+
const earliest = dayOf(hourly[0]) * DAY_MS;
|
|
80
|
+
const latest = Math.min(earliest, Date.parse(next.coverageStart));
|
|
81
|
+
if (latest > Date.parse(coverage))
|
|
82
|
+
coverage = new Date(latest).toISOString();
|
|
83
|
+
}
|
|
84
|
+
return { snapshot: { ...next, coverageStart: coverage, hourly }, droppedDays };
|
|
85
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type Context } from './context.ts';
|
|
2
|
+
export declare const INSTALL_USAGE = "Usage: big-spender install --device <id> [--url <ingest url>] [--rename]\n\nCopies the collector to ~/.local/share/big-spender, schedules it hourly (systemd user timer on\nLinux, launchd agent on macOS) and runs it once. The ingest token comes from the existing env\nfile, BIG_SPENDER_INGEST_TOKEN, or a hidden prompt. It is never taken from a flag.\nRe-running is safe. A usage-collector install from before the rename is migrated in place.\nA machine that already has a device id keeps it: --device with a different id needs --rename,\nbecause the server would count the same history twice, under the old id and the new one.";
|
|
3
|
+
export declare function install(args: string[], ctx: Context): Promise<number>;
|
|
4
|
+
export declare const UNINSTALL_USAGE = "Usage: big-spender uninstall\n\nRemoves the schedule. The env file and state are kept.";
|
|
5
|
+
export declare function uninstall(args: string[], ctx: Context): Promise<number>;
|
package/dist/install.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { access, chmod, copyFile, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { delimiter, dirname, join } from 'node:path';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { UsageError } from './context.js';
|
|
6
|
+
import { parseEnv, renameLegacyKeys, setting, upsertEnv } from './envfile.js';
|
|
7
|
+
import { DEVICE_ID } from './schema.js';
|
|
8
|
+
import { pickScheduler } from './scheduler.js';
|
|
9
|
+
// The collector removes its lock when it finishes, so one this young belongs to a live run.
|
|
10
|
+
const LOCK_FRESH_MS = 30 * 60 * 1000;
|
|
11
|
+
// Written into the old cache before its schedule is removed, so a rerun after a crash still knows
|
|
12
|
+
// the old collector was scheduled. Not the old share dir: old uninstalls left that behind.
|
|
13
|
+
const WAS_SCHEDULED = '.big-spender-was-scheduled';
|
|
14
|
+
const exists = (path) => access(path).then(() => true, () => false);
|
|
15
|
+
const readText = (path) => readFile(path, 'utf8').catch(() => undefined);
|
|
16
|
+
async function writePrivate(path, text) {
|
|
17
|
+
await mkdir(dirname(path), { recursive: true });
|
|
18
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
19
|
+
await writeFile(tmp, text, { mode: 0o600 });
|
|
20
|
+
await rename(tmp, path);
|
|
21
|
+
await chmod(path, 0o600);
|
|
22
|
+
}
|
|
23
|
+
/** The `node` on PATH if it is new enough (stable across upgrades), else the one running us. */
|
|
24
|
+
function nodeForSchedule(ctx) {
|
|
25
|
+
for (const dir of (ctx.env.PATH ?? '').split(delimiter).filter(Boolean)) {
|
|
26
|
+
const candidate = join(dir, 'node');
|
|
27
|
+
try {
|
|
28
|
+
const major = Number(execFileSync(candidate, ['-p', 'process.versions.node.split(".")[0]'], {
|
|
29
|
+
encoding: 'utf8',
|
|
30
|
+
timeout: 10_000
|
|
31
|
+
}));
|
|
32
|
+
return major >= 20 ? candidate : process.execPath;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return process.execPath;
|
|
39
|
+
}
|
|
40
|
+
async function lockIsFresh(lock) {
|
|
41
|
+
const st = await stat(lock).catch(() => null);
|
|
42
|
+
return st !== null && Date.now() - st.mtimeMs < LOCK_FRESH_MS;
|
|
43
|
+
}
|
|
44
|
+
async function migrateConfig(ctx, log) {
|
|
45
|
+
const { paths } = ctx;
|
|
46
|
+
if (!(await exists(paths.configDir)) && (await exists(paths.legacy.configDir))) {
|
|
47
|
+
await rename(paths.legacy.configDir, paths.configDir);
|
|
48
|
+
log.push(`moved ${paths.legacy.configDir} to ${paths.configDir}`);
|
|
49
|
+
}
|
|
50
|
+
const text = await readText(paths.envFile);
|
|
51
|
+
if (text === undefined)
|
|
52
|
+
return;
|
|
53
|
+
const renamed = renameLegacyKeys(text);
|
|
54
|
+
if (renamed !== text) {
|
|
55
|
+
await writePrivate(paths.envFile, renamed);
|
|
56
|
+
log.push(`renamed USAGE_* keys in ${paths.envFile}`);
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
await chmod(paths.envFile, 0o600);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* What to do with the old collector's cache. `status` and `push` create a cache of their own
|
|
64
|
+
* from the logs still on disk, which lacks the days only the old state.json kept, so while the
|
|
65
|
+
* old collector is still scheduled, or wrote its state last, the old cache wins and the new one
|
|
66
|
+
* is set aside. Otherwise the new cache is the current one and the old one is left alone.
|
|
67
|
+
*/
|
|
68
|
+
function planCache(f) {
|
|
69
|
+
if (!f.legacyCache)
|
|
70
|
+
return 'none';
|
|
71
|
+
if (!f.newCache)
|
|
72
|
+
return 'move';
|
|
73
|
+
if (f.installed)
|
|
74
|
+
return 'keep';
|
|
75
|
+
return f.legacyScheduled || f.legacyStateNewer ? 'replace' : 'keep-older';
|
|
76
|
+
}
|
|
77
|
+
const mtime = async (path) => (await stat(path).catch(() => null))?.mtimeMs ?? -Infinity;
|
|
78
|
+
async function cacheFacts(ctx, legacyScheduled) {
|
|
79
|
+
const { paths } = ctx;
|
|
80
|
+
return {
|
|
81
|
+
legacyCache: await exists(paths.legacy.cacheDir),
|
|
82
|
+
newCache: await exists(paths.cacheDir),
|
|
83
|
+
installed: await exists(paths.collector),
|
|
84
|
+
legacyScheduled,
|
|
85
|
+
legacyStateNewer: (await mtime(join(paths.legacy.cacheDir, 'state.json'))) >
|
|
86
|
+
(await mtime(join(paths.cacheDir, 'state.json')))
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
async function migrateCache(ctx, plan, log) {
|
|
90
|
+
const { paths } = ctx;
|
|
91
|
+
if (plan === 'keep') {
|
|
92
|
+
log.push(`left ${paths.legacy.cacheDir} in place: ${paths.cacheDir} already exists, so the old state was not moved`);
|
|
93
|
+
}
|
|
94
|
+
if (plan === 'keep-older') {
|
|
95
|
+
log.push(`left ${paths.legacy.cacheDir} in place: it has no newer state than ${paths.cacheDir}, which stays the current cache`);
|
|
96
|
+
}
|
|
97
|
+
if (plan === 'replace') {
|
|
98
|
+
const aside = `${paths.cacheDir}.pre-install-${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
|
99
|
+
await rename(paths.cacheDir, aside);
|
|
100
|
+
log.push(`moved ${paths.cacheDir} to ${aside}: it was built before install, without the old state`);
|
|
101
|
+
}
|
|
102
|
+
if (plan === 'move' || plan === 'replace') {
|
|
103
|
+
await rename(paths.legacy.cacheDir, paths.cacheDir);
|
|
104
|
+
log.push(`moved ${paths.legacy.cacheDir} to ${paths.cacheDir}`);
|
|
105
|
+
// The old units are stopped by now, so a lock that came along belongs to a dead run.
|
|
106
|
+
await rm(paths.lock, { force: true });
|
|
107
|
+
await rm(join(paths.cacheDir, WAS_SCHEDULED), { force: true });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Settings already on this machine, from the new env file or the one the old collector made. */
|
|
111
|
+
async function existingSettings(ctx) {
|
|
112
|
+
const { paths } = ctx;
|
|
113
|
+
const text = (await readText(paths.envFile)) ?? (await readText(join(paths.legacy.configDir, 'env'))) ?? '';
|
|
114
|
+
const vars = parseEnv(text);
|
|
115
|
+
return {
|
|
116
|
+
deviceId: setting(vars, 'DEVICE_ID'),
|
|
117
|
+
url: setting(vars, 'INGEST_URL'),
|
|
118
|
+
token: setting(vars, 'INGEST_TOKEN')
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
export const INSTALL_USAGE = `Usage: big-spender install --device <id> [--url <ingest url>] [--rename]
|
|
122
|
+
|
|
123
|
+
Copies the collector to ~/.local/share/big-spender, schedules it hourly (systemd user timer on
|
|
124
|
+
Linux, launchd agent on macOS) and runs it once. The ingest token comes from the existing env
|
|
125
|
+
file, BIG_SPENDER_INGEST_TOKEN, or a hidden prompt. It is never taken from a flag.
|
|
126
|
+
Re-running is safe. A usage-collector install from before the rename is migrated in place.
|
|
127
|
+
A machine that already has a device id keeps it: --device with a different id needs --rename,
|
|
128
|
+
because the server would count the same history twice, under the old id and the new one.`;
|
|
129
|
+
export async function install(args, ctx) {
|
|
130
|
+
const { values } = parseArgs({
|
|
131
|
+
args,
|
|
132
|
+
options: {
|
|
133
|
+
device: { type: 'string' },
|
|
134
|
+
url: { type: 'string' },
|
|
135
|
+
rename: { type: 'boolean' }
|
|
136
|
+
},
|
|
137
|
+
strict: true
|
|
138
|
+
});
|
|
139
|
+
const { paths } = ctx;
|
|
140
|
+
const existing = await existingSettings(ctx);
|
|
141
|
+
const deviceId = values.device ?? ctx.env.BIG_SPENDER_DEVICE_ID ?? existing.deviceId;
|
|
142
|
+
if (!DEVICE_ID.test(deviceId)) {
|
|
143
|
+
throw new UsageError('--device must be a lowercase slug such as laptop or desktop');
|
|
144
|
+
}
|
|
145
|
+
if (existing.deviceId && deviceId !== existing.deviceId && !values.rename) {
|
|
146
|
+
throw new UsageError(`this machine already reports as "${existing.deviceId}", not "${deviceId}". Under a new id the server would count the same usage twice, because ${existing.deviceId}.json stays on the server next to the new one. Keep "${existing.deviceId}", or pass --rename if you mean to change it and will remove the old device's data on the server`);
|
|
147
|
+
}
|
|
148
|
+
const scheduler = pickScheduler(ctx.env, ctx.platform, paths, ctx.templatesDir, ctx.ctl);
|
|
149
|
+
await scheduler.check();
|
|
150
|
+
const legacySchedule = await scheduler.findLegacy();
|
|
151
|
+
const wasScheduled = join(paths.legacy.cacheDir, WAS_SCHEDULED);
|
|
152
|
+
const legacyScheduled = legacySchedule.length > 0 || (await exists(wasScheduled));
|
|
153
|
+
const cachePlan = planCache(await cacheFacts(ctx, legacyScheduled));
|
|
154
|
+
if ((cachePlan === 'move' || cachePlan === 'replace') && (await lockIsFresh(paths.legacy.lock))) {
|
|
155
|
+
throw new UsageError(`the old collector is running (${paths.legacy.lock} is recent); wait for it to finish and run install again`);
|
|
156
|
+
}
|
|
157
|
+
if (cachePlan === 'replace' && (await lockIsFresh(paths.lock))) {
|
|
158
|
+
throw new UsageError(`big-spender is running (${paths.lock} is recent), and install would move its cache aside; wait for it to finish and run install again`);
|
|
159
|
+
}
|
|
160
|
+
let url = values.url ?? ctx.env.BIG_SPENDER_INGEST_URL ?? existing.url;
|
|
161
|
+
let token = ctx.env.BIG_SPENDER_INGEST_TOKEN || existing.token;
|
|
162
|
+
if (!url)
|
|
163
|
+
url = await ctx.prompter().ask('Ingest URL (https://…/api/usage/ingest): ');
|
|
164
|
+
if (!token)
|
|
165
|
+
token = await ctx.prompter().askHidden('Ingest token: ');
|
|
166
|
+
if (!url || !token)
|
|
167
|
+
throw new UsageError('an ingest URL and token are required');
|
|
168
|
+
const log = [];
|
|
169
|
+
if (legacySchedule.length > 0 && (cachePlan === 'move' || cachePlan === 'replace')) {
|
|
170
|
+
await writeFile(wasScheduled, '');
|
|
171
|
+
}
|
|
172
|
+
for (const removed of await scheduler.removeLegacy())
|
|
173
|
+
log.push(`removed old schedule ${removed}`);
|
|
174
|
+
await migrateConfig(ctx, log);
|
|
175
|
+
await migrateCache(ctx, cachePlan, log);
|
|
176
|
+
if (await exists(paths.legacy.shareDir)) {
|
|
177
|
+
await rm(paths.legacy.shareDir, { recursive: true, force: true });
|
|
178
|
+
log.push(`removed ${paths.legacy.shareDir}`);
|
|
179
|
+
}
|
|
180
|
+
const base = (await readText(paths.envFile)) ??
|
|
181
|
+
(await readText(join(ctx.templatesDir, 'env.example'))) ??
|
|
182
|
+
'';
|
|
183
|
+
await writePrivate(paths.envFile, upsertEnv(base, {
|
|
184
|
+
BIG_SPENDER_DEVICE_ID: deviceId,
|
|
185
|
+
BIG_SPENDER_INGEST_URL: url,
|
|
186
|
+
BIG_SPENDER_INGEST_TOKEN: token
|
|
187
|
+
}));
|
|
188
|
+
await mkdir(paths.shareDir, { recursive: true });
|
|
189
|
+
await copyFile(ctx.collector, paths.collector);
|
|
190
|
+
await scheduler.install(nodeForSchedule(ctx));
|
|
191
|
+
for (const line of log)
|
|
192
|
+
ctx.out(line);
|
|
193
|
+
ctx.out(`Scheduled with ${scheduler.describe}`);
|
|
194
|
+
try {
|
|
195
|
+
await scheduler.runNow();
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
ctx.err(`The schedule is installed, but the first run failed: ${err instanceof Error ? err.message : err}`);
|
|
199
|
+
return 1;
|
|
200
|
+
}
|
|
201
|
+
return 0;
|
|
202
|
+
}
|
|
203
|
+
export const UNINSTALL_USAGE = 'Usage: big-spender uninstall\n\nRemoves the schedule. The env file and state are kept.';
|
|
204
|
+
export async function uninstall(args, ctx) {
|
|
205
|
+
parseArgs({ args, options: {}, strict: true });
|
|
206
|
+
const scheduler = pickScheduler(ctx.env, ctx.platform, ctx.paths, ctx.templatesDir, ctx.ctl);
|
|
207
|
+
await scheduler.removeLegacy();
|
|
208
|
+
await scheduler.uninstall();
|
|
209
|
+
ctx.out(`Schedule removed. Env (${ctx.paths.envFile}) and state (${ctx.paths.cacheDir}) were kept.`);
|
|
210
|
+
return 0;
|
|
211
|
+
}
|
package/dist/page.d.ts
ADDED
package/dist/page.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { RANGES } from './schema.js';
|
|
2
|
+
const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
3
|
+
const safeColor = (c) => (/^#[0-9a-f]{3,8}$/i.test(c) ? c : '#888888');
|
|
4
|
+
const usd = (n) => `$${n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
5
|
+
const tokens = (n) => n >= 1e9
|
|
6
|
+
? `${(n / 1e9).toFixed(2)}B`
|
|
7
|
+
: n >= 1e6
|
|
8
|
+
? `${(n / 1e6).toFixed(1)}M`
|
|
9
|
+
: n.toLocaleString('en-US');
|
|
10
|
+
const percent = (share) => `${(share * 100).toFixed(1)}%`;
|
|
11
|
+
const LABELS = { '7d': '7 days', '30d': '30 days', '90d': '90 days' };
|
|
12
|
+
const TOP_MODELS = 8;
|
|
13
|
+
const STYLE = `
|
|
14
|
+
:root { color-scheme: light dark; --bg: #fafaf7; --fg: #1b1f1c; --muted: #66706a; --card: #ffffff; --line: #dfe3dd; }
|
|
15
|
+
@media (prefers-color-scheme: dark) {
|
|
16
|
+
:root { --bg: #121614; --fg: #e6ebe7; --muted: #97a098; --card: #1a201d; --line: #2a322e; }
|
|
17
|
+
}
|
|
18
|
+
* { box-sizing: border-box; }
|
|
19
|
+
body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.5 system-ui, sans-serif; }
|
|
20
|
+
main { max-width: 56rem; margin: 0 auto; padding: 2rem 1rem 4rem; }
|
|
21
|
+
h1 { margin: 0; font-size: 1.5rem; }
|
|
22
|
+
h2 { margin: 2.5rem 0 0.75rem; font-size: 1.1rem; }
|
|
23
|
+
.sub { margin: 0.25rem 0 0; color: var(--muted); }
|
|
24
|
+
.totals { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap: 1rem; margin-top: 1.5rem; }
|
|
25
|
+
.card { background: var(--card); border: 1px solid var(--line); border-radius: 0.75rem; padding: 1rem; }
|
|
26
|
+
.card h3 { margin: 0; font-size: 0.85rem; font-weight: 500; color: var(--muted); }
|
|
27
|
+
.card .cost { margin: 0.25rem 0 0.5rem; font-size: 1.75rem; font-weight: 600; font-variant-numeric: tabular-nums; }
|
|
28
|
+
.card p { margin: 0; color: var(--muted); font-size: 0.9rem; }
|
|
29
|
+
table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
|
|
30
|
+
th, td { padding: 0.5rem 0.5rem; border-bottom: 1px solid var(--line); text-align: right; }
|
|
31
|
+
th:first-child, td:first-child { text-align: left; }
|
|
32
|
+
th { color: var(--muted); font-weight: 500; font-size: 0.85rem; }
|
|
33
|
+
.swatch { display: inline-block; width: 0.75rem; height: 0.75rem; margin-right: 0.5rem; border-radius: 50%; vertical-align: -0.05em; }
|
|
34
|
+
.scroll { overflow-x: auto; }
|
|
35
|
+
.empty { color: var(--muted); }
|
|
36
|
+
`;
|
|
37
|
+
function totalsCard(r) {
|
|
38
|
+
return `<section class="card"><h3>Last ${LABELS[r.range]}</h3>
|
|
39
|
+
<p class="cost">${usd(r.totalCost)}</p>
|
|
40
|
+
<p>${r.sessions.toLocaleString('en-US')} sessions · ${tokens(r.tokens.processed)} tokens</p>
|
|
41
|
+
<p>${usd(r.cacheSavings)} saved by caching</p></section>`;
|
|
42
|
+
}
|
|
43
|
+
function devicesTable(summary) {
|
|
44
|
+
const widest = summary.ranges['90d'];
|
|
45
|
+
if (!widest.devices.length)
|
|
46
|
+
return '<p class="empty">No devices have reported yet.</p>';
|
|
47
|
+
const rows = widest.devices.map((d) => {
|
|
48
|
+
const cells = RANGES.map((range) => {
|
|
49
|
+
const line = summary.ranges[range].devices.find((x) => x.name === d.name);
|
|
50
|
+
return `<td>${usd(line?.cost ?? 0)}</td>`;
|
|
51
|
+
});
|
|
52
|
+
return `<tr><td><span class="swatch" style="background:${safeColor(d.color)}"></span>${escapeHtml(d.name)}</td>${cells.join('')}</tr>`;
|
|
53
|
+
});
|
|
54
|
+
const heads = RANGES.map((range) => `<th>${LABELS[range]}</th>`).join('');
|
|
55
|
+
return `<div class="scroll"><table><thead><tr><th>Device</th>${heads}</tr></thead><tbody>${rows.join('')}</tbody></table></div>`;
|
|
56
|
+
}
|
|
57
|
+
function modelsTable(r) {
|
|
58
|
+
if (!r.models.length)
|
|
59
|
+
return '<p class="empty">No usage in this range.</p>';
|
|
60
|
+
const rows = r.models
|
|
61
|
+
.slice(0, TOP_MODELS)
|
|
62
|
+
.map((m) => `<tr><td>${escapeHtml(m.model)}</td><td>${escapeHtml(m.provider)}</td><td>${usd(m.cost)}</td><td>${percent(m.share)}</td><td>${tokens(m.tokens)}</td></tr>`);
|
|
63
|
+
return `<div class="scroll"><table><thead><tr><th>Model</th><th>Agent</th><th>Cost</th><th>Share</th><th>Tokens</th></tr></thead><tbody>${rows.join('')}</tbody></table></div>`;
|
|
64
|
+
}
|
|
65
|
+
export function renderPage(summary) {
|
|
66
|
+
const updated = escapeHtml(summary.generatedAt);
|
|
67
|
+
return `<!doctype html>
|
|
68
|
+
<html lang="en">
|
|
69
|
+
<head>
|
|
70
|
+
<meta charset="utf-8">
|
|
71
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
72
|
+
<title>big-spender</title>
|
|
73
|
+
<style>${STYLE}</style>
|
|
74
|
+
</head>
|
|
75
|
+
<body>
|
|
76
|
+
<main>
|
|
77
|
+
<h1>big-spender</h1>
|
|
78
|
+
<p class="sub">What AI coding agents would cost at API prices, across all devices. Computed ${updated}.</p>
|
|
79
|
+
<div class="totals">${RANGES.map((range) => totalsCard(summary.ranges[range])).join('\n')}</div>
|
|
80
|
+
<h2>Devices</h2>
|
|
81
|
+
${devicesTable(summary)}
|
|
82
|
+
<h2>Top models, last 30 days</h2>
|
|
83
|
+
${modelsTable(summary.ranges['30d'])}
|
|
84
|
+
</main>
|
|
85
|
+
</body>
|
|
86
|
+
</html>
|
|
87
|
+
`;
|
|
88
|
+
}
|
package/dist/paths.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Where everything lives on one machine, resolved once from the environment. */
|
|
2
|
+
export type Paths = {
|
|
3
|
+
home: string;
|
|
4
|
+
tmpDir: string;
|
|
5
|
+
envFile: string;
|
|
6
|
+
/** The env file the collector reads: envFile, unless BIG_SPENDER_ENV_FILE or USAGE_ENV_FILE names another. */
|
|
7
|
+
collectorEnvFile: string;
|
|
8
|
+
configDir: string;
|
|
9
|
+
cacheDir: string;
|
|
10
|
+
lock: string;
|
|
11
|
+
shareDir: string;
|
|
12
|
+
collector: string;
|
|
13
|
+
systemdDir: string;
|
|
14
|
+
launchAgentsDir: string;
|
|
15
|
+
logsDir: string;
|
|
16
|
+
legacy: {
|
|
17
|
+
configDir: string;
|
|
18
|
+
cacheDir: string;
|
|
19
|
+
shareDir: string;
|
|
20
|
+
lock: string;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
export declare function resolvePaths(env?: NodeJS.ProcessEnv, home?: string): Paths;
|
package/dist/paths.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
export function resolvePaths(env = process.env, home = homedir()) {
|
|
4
|
+
const config = env.XDG_CONFIG_HOME || join(home, '.config');
|
|
5
|
+
const cache = env.XDG_CACHE_HOME || join(home, '.cache');
|
|
6
|
+
const share = join(home, '.local', 'share');
|
|
7
|
+
const configDir = join(config, 'big-spender');
|
|
8
|
+
const shareDir = join(share, 'big-spender');
|
|
9
|
+
const legacyCacheDir = join(cache, 'usage-collector');
|
|
10
|
+
const envFile = join(configDir, 'env');
|
|
11
|
+
return {
|
|
12
|
+
home,
|
|
13
|
+
tmpDir: env.TMPDIR || env.TEMP || '/tmp',
|
|
14
|
+
envFile,
|
|
15
|
+
collectorEnvFile: env.BIG_SPENDER_ENV_FILE || env.USAGE_ENV_FILE || envFile,
|
|
16
|
+
configDir,
|
|
17
|
+
cacheDir: join(cache, 'big-spender'),
|
|
18
|
+
lock: join(cache, 'big-spender', 'run.lock'),
|
|
19
|
+
shareDir,
|
|
20
|
+
collector: join(shareDir, 'collector.mjs'),
|
|
21
|
+
systemdDir: join(config, 'systemd', 'user'),
|
|
22
|
+
launchAgentsDir: join(home, 'Library', 'LaunchAgents'),
|
|
23
|
+
logsDir: join(home, 'Library', 'Logs'),
|
|
24
|
+
legacy: {
|
|
25
|
+
configDir: join(config, 'usage-collector'),
|
|
26
|
+
cacheDir: legacyCacheDir,
|
|
27
|
+
shareDir: join(share, 'usage-collector'),
|
|
28
|
+
lock: join(legacyCacheDir, 'run.lock')
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
package/dist/prompt.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type Prompter = {
|
|
2
|
+
ask(question: string): Promise<string>;
|
|
3
|
+
/** Like `ask`, without echoing what is typed. */
|
|
4
|
+
askHidden(question: string): Promise<string>;
|
|
5
|
+
close(): void;
|
|
6
|
+
};
|
|
7
|
+
export declare function createPrompter(input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream): Prompter;
|
package/dist/prompt.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline';
|
|
2
|
+
import { Writable } from 'node:stream';
|
|
3
|
+
export function createPrompter(input = process.stdin, output = process.stdout) {
|
|
4
|
+
let muted = false;
|
|
5
|
+
const echo = new Writable({
|
|
6
|
+
write(chunk, _encoding, done) {
|
|
7
|
+
if (!muted)
|
|
8
|
+
output.write(chunk);
|
|
9
|
+
done();
|
|
10
|
+
}
|
|
11
|
+
});
|
|
12
|
+
const rl = createInterface({
|
|
13
|
+
input,
|
|
14
|
+
output: echo,
|
|
15
|
+
terminal: Boolean(input.isTTY)
|
|
16
|
+
});
|
|
17
|
+
const lines = rl[Symbol.asyncIterator]();
|
|
18
|
+
async function read(question, hidden) {
|
|
19
|
+
output.write(question);
|
|
20
|
+
muted = hidden;
|
|
21
|
+
try {
|
|
22
|
+
const next = await lines.next();
|
|
23
|
+
if (next.done)
|
|
24
|
+
throw new Error('no input: stdin closed while waiting for an answer');
|
|
25
|
+
return next.value.trim();
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
muted = false;
|
|
29
|
+
if (hidden)
|
|
30
|
+
output.write('\n');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
ask: (question) => read(question, false),
|
|
35
|
+
askHidden: (question) => read(question, true),
|
|
36
|
+
close: () => rl.close()
|
|
37
|
+
};
|
|
38
|
+
}
|