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
package/dist/push.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type Context } from './context.ts';
|
|
2
|
+
export declare const PUSH_USAGE = "Usage: big-spender push <device> [--dry-run] [--url <ingest url>]\n\nOne-off push from a machine without a schedule. Builds the snapshot, shows what it would publish\nand stops if a model name looks like a cloud resource id (for example a Bedrock inference-profile\nARN, which contains an account id). Asks before sending. The URL comes from --url,\nBIG_SPENDER_INGEST_URL or a prompt, and the token from BIG_SPENDER_INGEST_TOKEN or a hidden\nprompt, so neither is written to this machine. Nothing is scheduled.\n\n--dry-run prints the overview, writes the exact JSON that would be sent to\n$TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the\ncollector's local state in ~/.cache/big-spender (which logs were read), never anything remote.";
|
|
3
|
+
export declare function push(args: string[], ctx: Context): Promise<number>;
|
package/dist/push.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { gzipSync } from 'node:zlib';
|
|
6
|
+
import { UsageError } from './context.js';
|
|
7
|
+
import { parseEnv, setting } from './envfile.js';
|
|
8
|
+
import { DEVICE_ID } from './schema.js';
|
|
9
|
+
export const PUSH_USAGE = `Usage: big-spender push <device> [--dry-run] [--url <ingest url>]
|
|
10
|
+
|
|
11
|
+
One-off push from a machine without a schedule. Builds the snapshot, shows what it would publish
|
|
12
|
+
and stops if a model name looks like a cloud resource id (for example a Bedrock inference-profile
|
|
13
|
+
ARN, which contains an account id). Asks before sending. The URL comes from --url,
|
|
14
|
+
BIG_SPENDER_INGEST_URL or a prompt, and the token from BIG_SPENDER_INGEST_TOKEN or a hidden
|
|
15
|
+
prompt, so neither is written to this machine. Nothing is scheduled.
|
|
16
|
+
|
|
17
|
+
--dry-run prints the overview, writes the exact JSON that would be sent to
|
|
18
|
+
$TMPDIR/big-spender-snapshot-<device>.json and never asks for the token. Both modes update the
|
|
19
|
+
collector's local state in ~/.cache/big-spender (which logs were read), never anything remote.`;
|
|
20
|
+
const MAX_SNAPSHOT_BYTES = 512 * 1024 * 1024;
|
|
21
|
+
const POST_ATTEMPTS = 4;
|
|
22
|
+
function runCollector(ctx, extraEnv, args) {
|
|
23
|
+
return new Promise((resolve) => {
|
|
24
|
+
execFile(process.execPath, [ctx.collector, ...args], { env: { ...ctx.env, ...extraEnv }, maxBuffer: MAX_SNAPSHOT_BYTES }, (err, stdout, stderr) => {
|
|
25
|
+
const code = err ? (typeof err.code === 'number' ? err.code : 1) : 0;
|
|
26
|
+
resolve({ code, stdout, stderr });
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
function overview(snapshot, gzipped) {
|
|
31
|
+
const byModel = new Map();
|
|
32
|
+
for (const r of snapshot.hourly) {
|
|
33
|
+
const key = `${r.provider} ${r.model}`;
|
|
34
|
+
const m = byModel.get(key) ?? { tokens: 0, cost: 0 };
|
|
35
|
+
m.tokens +=
|
|
36
|
+
r.inputTokens +
|
|
37
|
+
r.cacheReadTokens +
|
|
38
|
+
r.cacheWrite5mTokens +
|
|
39
|
+
r.cacheWrite1hTokens +
|
|
40
|
+
r.outputTokens;
|
|
41
|
+
m.cost += r.costUsd.input + r.costUsd.cacheRead + r.costUsd.cacheWrite + r.costUsd.output;
|
|
42
|
+
byModel.set(key, m);
|
|
43
|
+
}
|
|
44
|
+
const rows = [...byModel].sort((a, b) => b[1].cost - a[1].cost);
|
|
45
|
+
const width = Math.max(20, ...rows.map(([k]) => k.length));
|
|
46
|
+
const days = snapshot.hourly.map((r) => r.hour.slice(0, 10)).sort();
|
|
47
|
+
const line = (label, tokens, cost) => ` ${label.padEnd(width)} ${`${(tokens / 1e6).toFixed(1)}M`.padStart(10)} ${`$${cost.toFixed(2)}`.padStart(10)}`;
|
|
48
|
+
let tokens = 0;
|
|
49
|
+
let cost = 0;
|
|
50
|
+
for (const [, m] of rows) {
|
|
51
|
+
tokens += m.tokens;
|
|
52
|
+
cost += m.cost;
|
|
53
|
+
}
|
|
54
|
+
return [
|
|
55
|
+
'',
|
|
56
|
+
`Snapshot for "${snapshot.deviceId}": ${snapshot.hourly.length} rows, ${days[0] ?? '-'} to ${days.at(-1) ?? '-'}, ${gzipped} bytes gzipped`,
|
|
57
|
+
'Model names are published on the server as shown.',
|
|
58
|
+
'',
|
|
59
|
+
` ${'provider model'.padEnd(width)} ${'tokens'.padStart(10)} ${'cost'.padStart(10)}`,
|
|
60
|
+
...rows.map(([k, m]) => line(k, m.tokens, m.cost)),
|
|
61
|
+
line('total', tokens, cost)
|
|
62
|
+
];
|
|
63
|
+
}
|
|
64
|
+
export async function push(args, ctx) {
|
|
65
|
+
const { values, positionals } = parseArgs({
|
|
66
|
+
args,
|
|
67
|
+
options: { 'dry-run': { type: 'boolean' }, url: { type: 'string' } },
|
|
68
|
+
allowPositionals: true,
|
|
69
|
+
strict: true
|
|
70
|
+
});
|
|
71
|
+
const deviceId = positionals[0] ?? '';
|
|
72
|
+
if (positionals.length !== 1 || !DEVICE_ID.test(deviceId)) {
|
|
73
|
+
throw new UsageError('<device> must be a lowercase slug such as laptop or desktop');
|
|
74
|
+
}
|
|
75
|
+
const built = await runCollector(ctx, { BIG_SPENDER_DEVICE_ID: deviceId }, ['--dry-run']);
|
|
76
|
+
if (built.code !== 0) {
|
|
77
|
+
ctx.err(built.stderr.trimEnd());
|
|
78
|
+
return 1;
|
|
79
|
+
}
|
|
80
|
+
for (const line of built.stderr.split('\n'))
|
|
81
|
+
if (/warning/i.test(line))
|
|
82
|
+
ctx.err(line);
|
|
83
|
+
const snapshot = JSON.parse(built.stdout);
|
|
84
|
+
const body = gzipSync(built.stdout);
|
|
85
|
+
for (const line of overview(snapshot, body.length))
|
|
86
|
+
ctx.out(line);
|
|
87
|
+
const blocked = snapshot.hourly.some((r) => /arn:|\//i.test(r.model));
|
|
88
|
+
if (blocked) {
|
|
89
|
+
ctx.err('\nWould NOT send: a model name looks like a cloud resource id or gateway path.');
|
|
90
|
+
}
|
|
91
|
+
if (values['dry-run']) {
|
|
92
|
+
const file = join(ctx.paths.tmpDir, `big-spender-snapshot-${deviceId}.json`);
|
|
93
|
+
await writeFile(file, built.stdout);
|
|
94
|
+
ctx.out(`\nDry run: nothing sent. The exact JSON that would be sent is in ${file}`);
|
|
95
|
+
return blocked ? 1 : 0;
|
|
96
|
+
}
|
|
97
|
+
if (blocked)
|
|
98
|
+
return 1;
|
|
99
|
+
const prompter = ctx.prompter();
|
|
100
|
+
const answer = await prompter.ask(`\nSend this snapshot as "${deviceId}"? [y/N] `);
|
|
101
|
+
if (!/^[yY]$/.test(answer)) {
|
|
102
|
+
ctx.out('Nothing sent.');
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
const saved = parseEnv(await readFile(ctx.paths.collectorEnvFile, 'utf8').catch(() => ''));
|
|
106
|
+
const url = values.url ??
|
|
107
|
+
(setting(ctx.env, 'INGEST_URL') ||
|
|
108
|
+
(await prompter.ask('Ingest URL (https://…/api/usage/ingest): ')) ||
|
|
109
|
+
setting(saved, 'INGEST_URL'));
|
|
110
|
+
const token = (setting(ctx.env, 'INGEST_TOKEN') ||
|
|
111
|
+
(await prompter.askHidden('Ingest token: ')) ||
|
|
112
|
+
setting(saved, 'INGEST_TOKEN')).trim();
|
|
113
|
+
if (!url || !token)
|
|
114
|
+
throw new Error('an ingest URL and token are required');
|
|
115
|
+
// fetch quotes the whole header in its error for some of these, which would print the token.
|
|
116
|
+
if (!/^[\x21-\x7e]+$/.test(token)) {
|
|
117
|
+
throw new Error('the ingest token contains characters that are not allowed in an HTTP header; check it for spaces or a stray newline');
|
|
118
|
+
}
|
|
119
|
+
const result = await send(ctx, url, token, body);
|
|
120
|
+
ctx.out(`posted ${snapshot.hourly.length} rows (${body.length} bytes gzipped): ${result}`);
|
|
121
|
+
return 0;
|
|
122
|
+
}
|
|
123
|
+
/** POSTs the reviewed bytes with the collector's retry policy and returns the server's reply. */
|
|
124
|
+
async function send(ctx, url, token, body) {
|
|
125
|
+
let lastErr = new Error('not sent');
|
|
126
|
+
for (let attempt = 1; attempt <= POST_ATTEMPTS; attempt++) {
|
|
127
|
+
try {
|
|
128
|
+
const res = await fetch(url, {
|
|
129
|
+
method: 'POST',
|
|
130
|
+
headers: {
|
|
131
|
+
authorization: `Bearer ${token}`,
|
|
132
|
+
'content-type': 'application/json',
|
|
133
|
+
'content-encoding': 'gzip'
|
|
134
|
+
},
|
|
135
|
+
body,
|
|
136
|
+
signal: AbortSignal.timeout(30_000)
|
|
137
|
+
});
|
|
138
|
+
const text = (await res.text()).slice(0, 300);
|
|
139
|
+
if (res.ok)
|
|
140
|
+
return text;
|
|
141
|
+
lastErr = new Error(`HTTP ${res.status}: ${text}`);
|
|
142
|
+
// Client errors other than rate limiting won't fix themselves.
|
|
143
|
+
if (res.status >= 400 && res.status < 500 && res.status !== 429)
|
|
144
|
+
break;
|
|
145
|
+
}
|
|
146
|
+
catch (err) {
|
|
147
|
+
lastErr = err instanceof Error ? err : new Error(String(err));
|
|
148
|
+
}
|
|
149
|
+
if (attempt < POST_ATTEMPTS) {
|
|
150
|
+
const wait = 2 ** attempt * 1000;
|
|
151
|
+
ctx.err(`POST failed (${lastErr.message}); retrying in ${wait / 1000}s`);
|
|
152
|
+
await new Promise((r) => setTimeout(r, wait));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
throw lastErr;
|
|
156
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Paths } from './paths.ts';
|
|
2
|
+
export type Scheduler = {
|
|
3
|
+
/** Fails with a clear message if the schedule cannot be managed from here. Changes nothing. */
|
|
4
|
+
check(): Promise<void>;
|
|
5
|
+
/** The schedule files the site's usage-collector installed that are still here. Changes nothing. */
|
|
6
|
+
findLegacy(): Promise<string[]>;
|
|
7
|
+
/** Removes schedules the site's usage-collector installed. Returns what it removed. */
|
|
8
|
+
removeLegacy(): Promise<string[]>;
|
|
9
|
+
/** Writes the schedule from the templates and enables it. */
|
|
10
|
+
install(node: string): Promise<void>;
|
|
11
|
+
uninstall(): Promise<void>;
|
|
12
|
+
/** Runs the collector once now. Some schedulers already do that when enabled. */
|
|
13
|
+
runNow(): Promise<void>;
|
|
14
|
+
describe: string;
|
|
15
|
+
};
|
|
16
|
+
export type Ctl = (cmd: string, args: string[], opts?: {
|
|
17
|
+
tolerate?: boolean;
|
|
18
|
+
}) => Promise<void>;
|
|
19
|
+
/**
|
|
20
|
+
* The only place that talks to systemctl and launchctl. BIG_SPENDER_SCHEDULER=none turns every
|
|
21
|
+
* call into a no-op so tests can run `install` against a throwaway HOME.
|
|
22
|
+
*/
|
|
23
|
+
export declare function makeCtl(env: NodeJS.ProcessEnv): Ctl;
|
|
24
|
+
export declare function pickScheduler(env: NodeJS.ProcessEnv, platform: NodeJS.Platform, paths: Paths, templatesDir: string, ctl?: Ctl): Scheduler;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { readdir, readFile, rm, copyFile, mkdir, writeFile, access } from 'node:fs/promises';
|
|
3
|
+
import { basename, join } from 'node:path';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
const execFileAsync = promisify(execFile);
|
|
6
|
+
const LEGACY_SCRIPT = '.local/share/usage-collector/collector.mjs';
|
|
7
|
+
/**
|
|
8
|
+
* The only place that talks to systemctl and launchctl. BIG_SPENDER_SCHEDULER=none turns every
|
|
9
|
+
* call into a no-op so tests can run `install` against a throwaway HOME.
|
|
10
|
+
*/
|
|
11
|
+
export function makeCtl(env) {
|
|
12
|
+
if (env.BIG_SPENDER_SCHEDULER === 'none')
|
|
13
|
+
return async () => { };
|
|
14
|
+
return async (cmd, args, opts) => {
|
|
15
|
+
try {
|
|
16
|
+
await execFileAsync(cmd, args);
|
|
17
|
+
}
|
|
18
|
+
catch (err) {
|
|
19
|
+
if (!opts?.tolerate)
|
|
20
|
+
throw err;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
const exists = (path) => access(path).then(() => true, () => false);
|
|
25
|
+
async function render(templatesDir, name, vars) {
|
|
26
|
+
let text = await readFile(join(templatesDir, name), 'utf8');
|
|
27
|
+
for (const [key, value] of Object.entries(vars))
|
|
28
|
+
text = text.replaceAll(key, value);
|
|
29
|
+
return text;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Without a user manager (no login session, no lingering) disable and stop fail quietly, and
|
|
33
|
+
* deleting the unit files afterwards would leave a timer nobody can stop and no way to retry.
|
|
34
|
+
*/
|
|
35
|
+
async function requireManager(ctl) {
|
|
36
|
+
try {
|
|
37
|
+
await ctl('systemctl', ['--user', 'show-environment']);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new Error('cannot reach the systemd user manager (systemctl --user failed). Run this from a login session, or enable lingering with `loginctl enable-linger $USER`, then run install again. Nothing was changed.');
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function systemd(paths, templatesDir, ctl, xdg) {
|
|
44
|
+
const user = ['--user'];
|
|
45
|
+
const legacyFiles = ['usage-collector.service', 'usage-collector.timer'].map((f) => join(paths.systemdDir, f));
|
|
46
|
+
const findLegacy = async () => (await Promise.all(legacyFiles.map(async (f) => ((await exists(f)) ? f : null)))).filter((f) => f !== null);
|
|
47
|
+
return {
|
|
48
|
+
describe: 'systemd user timer (hourly). Log: journalctl --user -u big-spender',
|
|
49
|
+
check: () => requireManager(ctl),
|
|
50
|
+
findLegacy,
|
|
51
|
+
async removeLegacy() {
|
|
52
|
+
const present = await findLegacy();
|
|
53
|
+
await ctl('systemctl', [...user, 'disable', '--now', 'usage-collector.timer'], {
|
|
54
|
+
tolerate: true
|
|
55
|
+
});
|
|
56
|
+
await ctl('systemctl', [...user, 'stop', 'usage-collector.service'], { tolerate: true });
|
|
57
|
+
if (!present.length)
|
|
58
|
+
return [];
|
|
59
|
+
await requireManager(ctl);
|
|
60
|
+
for (const f of present)
|
|
61
|
+
await rm(f, { force: true });
|
|
62
|
+
await ctl('systemctl', [...user, 'daemon-reload']);
|
|
63
|
+
return present;
|
|
64
|
+
},
|
|
65
|
+
async install(node) {
|
|
66
|
+
await mkdir(paths.systemdDir, { recursive: true });
|
|
67
|
+
await writeFile(join(paths.systemdDir, 'big-spender.service'), await render(templatesDir, 'big-spender.service', {
|
|
68
|
+
__NODE__: node,
|
|
69
|
+
__HOME__: paths.home,
|
|
70
|
+
__ENV_FILE__: paths.envFile,
|
|
71
|
+
'__ENVIRONMENT__\n': xdg.map(([k, v]) => `Environment="${k}=${v}"\n`).join('')
|
|
72
|
+
}));
|
|
73
|
+
await copyFile(join(templatesDir, 'big-spender.timer'), join(paths.systemdDir, 'big-spender.timer'));
|
|
74
|
+
await ctl('systemctl', [...user, 'daemon-reload']);
|
|
75
|
+
await ctl('systemctl', [...user, 'enable', '--now', 'big-spender.timer']);
|
|
76
|
+
},
|
|
77
|
+
async uninstall() {
|
|
78
|
+
await ctl('systemctl', [...user, 'disable', '--now', 'big-spender.timer'], {
|
|
79
|
+
tolerate: true
|
|
80
|
+
});
|
|
81
|
+
await rm(join(paths.systemdDir, 'big-spender.service'), { force: true });
|
|
82
|
+
await rm(join(paths.systemdDir, 'big-spender.timer'), { force: true });
|
|
83
|
+
await ctl('systemctl', [...user, 'daemon-reload']);
|
|
84
|
+
},
|
|
85
|
+
async runNow() {
|
|
86
|
+
await ctl('systemctl', [...user, 'start', 'big-spender.service']);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function launchd(paths, templatesDir, ctl, xdg) {
|
|
91
|
+
const label = 'local.big-spender';
|
|
92
|
+
const plist = join(paths.launchAgentsDir, `${label}.plist`);
|
|
93
|
+
const domain = `gui/${process.getuid?.() ?? 0}`;
|
|
94
|
+
const bootout = (name) => ctl('launchctl', ['bootout', `${domain}/${name}`], { tolerate: true });
|
|
95
|
+
const findLegacy = async () => {
|
|
96
|
+
const found = [];
|
|
97
|
+
const names = await readdir(paths.launchAgentsDir).catch(() => []);
|
|
98
|
+
for (const name of names.filter((n) => n.endsWith('.usage-collector.plist'))) {
|
|
99
|
+
const file = join(paths.launchAgentsDir, name);
|
|
100
|
+
const isOurs = name === 'local.usage-collector.plist' ||
|
|
101
|
+
(await readFile(file, 'utf8').catch(() => '')).includes(LEGACY_SCRIPT);
|
|
102
|
+
if (isOurs)
|
|
103
|
+
found.push(file);
|
|
104
|
+
}
|
|
105
|
+
return found;
|
|
106
|
+
};
|
|
107
|
+
return {
|
|
108
|
+
check: async () => { },
|
|
109
|
+
describe: `launchd agent (hourly + at login). Log: ${join(paths.logsDir, 'big-spender.log')}`,
|
|
110
|
+
findLegacy,
|
|
111
|
+
async removeLegacy() {
|
|
112
|
+
const found = await findLegacy();
|
|
113
|
+
for (const file of found) {
|
|
114
|
+
await bootout(basename(file, '.plist'));
|
|
115
|
+
await rm(file, { force: true });
|
|
116
|
+
}
|
|
117
|
+
return found;
|
|
118
|
+
},
|
|
119
|
+
async install(node) {
|
|
120
|
+
await mkdir(paths.launchAgentsDir, { recursive: true });
|
|
121
|
+
await mkdir(paths.logsDir, { recursive: true });
|
|
122
|
+
await writeFile(plist, await render(templatesDir, 'local.big-spender.plist', {
|
|
123
|
+
__NODE__: node,
|
|
124
|
+
__HOME__: paths.home,
|
|
125
|
+
'__ENVIRONMENT__\n': xdg.length
|
|
126
|
+
? `\t<key>EnvironmentVariables</key>\n\t<dict>\n${xdg
|
|
127
|
+
.map(([k, v]) => `\t\t<key>${k}</key>\n\t\t<string>${v}</string>\n`)
|
|
128
|
+
.join('')}\t</dict>\n`
|
|
129
|
+
: ''
|
|
130
|
+
}));
|
|
131
|
+
await bootout(label);
|
|
132
|
+
await ctl('launchctl', ['bootstrap', domain, plist]);
|
|
133
|
+
},
|
|
134
|
+
async uninstall() {
|
|
135
|
+
await bootout(label);
|
|
136
|
+
await rm(plist, { force: true });
|
|
137
|
+
},
|
|
138
|
+
async runNow() {
|
|
139
|
+
// RunAtLoad already ran it when the agent was bootstrapped.
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
export function pickScheduler(env, platform, paths, templatesDir, ctl = makeCtl(env)) {
|
|
144
|
+
const xdg = ['XDG_CONFIG_HOME', 'XDG_CACHE_HOME'].flatMap((k) => env[k] ? [[k, env[k]]] : []);
|
|
145
|
+
const table = {
|
|
146
|
+
linux: () => systemd(paths, templatesDir, ctl, xdg),
|
|
147
|
+
darwin: () => launchd(paths, templatesDir, ctl, xdg)
|
|
148
|
+
};
|
|
149
|
+
const make = table[platform] ?? (env.BIG_SPENDER_SCHEDULER === 'none' ? table.linux : undefined);
|
|
150
|
+
if (!make)
|
|
151
|
+
throw new Error(`scheduling is not supported on ${platform}; run \`big-spender push\` instead`);
|
|
152
|
+
return make();
|
|
153
|
+
}
|
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const MAX_ROWS = 50000;
|
|
3
|
+
export declare const DEVICE_ID: RegExp;
|
|
4
|
+
export declare const PROVIDERS: readonly ['claude', 'codex'];
|
|
5
|
+
export declare const RANGES: readonly ['7d', '30d', '90d'];
|
|
6
|
+
export declare const usageRowSchema: z.ZodObject<{
|
|
7
|
+
hour: z.ZodISODateTime;
|
|
8
|
+
granularity: z.ZodOptional<z.ZodEnum<{
|
|
9
|
+
day: "day";
|
|
10
|
+
hour: "hour";
|
|
11
|
+
}>>;
|
|
12
|
+
provider: z.ZodEnum<{
|
|
13
|
+
claude: "claude";
|
|
14
|
+
codex: "codex";
|
|
15
|
+
}>;
|
|
16
|
+
model: z.ZodString;
|
|
17
|
+
sessions: z.ZodNumber;
|
|
18
|
+
inputTokens: z.ZodNumber;
|
|
19
|
+
cacheReadTokens: z.ZodNumber;
|
|
20
|
+
cacheWrite5mTokens: z.ZodNumber;
|
|
21
|
+
cacheWrite1hTokens: z.ZodNumber;
|
|
22
|
+
outputTokens: z.ZodNumber;
|
|
23
|
+
costUsd: z.ZodObject<{
|
|
24
|
+
input: z.ZodNumber;
|
|
25
|
+
cacheRead: z.ZodNumber;
|
|
26
|
+
cacheWrite: z.ZodNumber;
|
|
27
|
+
output: z.ZodNumber;
|
|
28
|
+
}, z.core.$strict>;
|
|
29
|
+
cacheSavingsUsd: z.ZodNumber;
|
|
30
|
+
}, z.core.$strict>;
|
|
31
|
+
export declare const usageSnapshotSchema: z.ZodObject<{
|
|
32
|
+
schemaVersion: z.ZodLiteral<1>;
|
|
33
|
+
deviceId: z.ZodString;
|
|
34
|
+
generatedAt: z.ZodISODateTime;
|
|
35
|
+
coverageStart: z.ZodISODateTime;
|
|
36
|
+
pricingSource: z.ZodString;
|
|
37
|
+
hourly: z.ZodArray<z.ZodObject<{
|
|
38
|
+
hour: z.ZodISODateTime;
|
|
39
|
+
granularity: z.ZodOptional<z.ZodEnum<{
|
|
40
|
+
day: "day";
|
|
41
|
+
hour: "hour";
|
|
42
|
+
}>>;
|
|
43
|
+
provider: z.ZodEnum<{
|
|
44
|
+
claude: "claude";
|
|
45
|
+
codex: "codex";
|
|
46
|
+
}>;
|
|
47
|
+
model: z.ZodString;
|
|
48
|
+
sessions: z.ZodNumber;
|
|
49
|
+
inputTokens: z.ZodNumber;
|
|
50
|
+
cacheReadTokens: z.ZodNumber;
|
|
51
|
+
cacheWrite5mTokens: z.ZodNumber;
|
|
52
|
+
cacheWrite1hTokens: z.ZodNumber;
|
|
53
|
+
outputTokens: z.ZodNumber;
|
|
54
|
+
costUsd: z.ZodObject<{
|
|
55
|
+
input: z.ZodNumber;
|
|
56
|
+
cacheRead: z.ZodNumber;
|
|
57
|
+
cacheWrite: z.ZodNumber;
|
|
58
|
+
output: z.ZodNumber;
|
|
59
|
+
}, z.core.$strict>;
|
|
60
|
+
cacheSavingsUsd: z.ZodNumber;
|
|
61
|
+
}, z.core.$strict>>;
|
|
62
|
+
sessionsTotal: z.ZodNumber;
|
|
63
|
+
sessionCounts: z.ZodOptional<z.ZodObject<{
|
|
64
|
+
'24h': z.ZodOptional<z.ZodObject<{
|
|
65
|
+
claude: z.ZodNumber;
|
|
66
|
+
codex: z.ZodNumber;
|
|
67
|
+
all: z.ZodNumber;
|
|
68
|
+
}, z.core.$strict>>;
|
|
69
|
+
'7d': z.ZodObject<{
|
|
70
|
+
claude: z.ZodNumber;
|
|
71
|
+
codex: z.ZodNumber;
|
|
72
|
+
all: z.ZodNumber;
|
|
73
|
+
}, z.core.$strict>;
|
|
74
|
+
'30d': z.ZodObject<{
|
|
75
|
+
claude: z.ZodNumber;
|
|
76
|
+
codex: z.ZodNumber;
|
|
77
|
+
all: z.ZodNumber;
|
|
78
|
+
}, z.core.$strict>;
|
|
79
|
+
'90d': z.ZodObject<{
|
|
80
|
+
claude: z.ZodNumber;
|
|
81
|
+
codex: z.ZodNumber;
|
|
82
|
+
all: z.ZodNumber;
|
|
83
|
+
}, z.core.$strict>;
|
|
84
|
+
}, z.core.$strict>>;
|
|
85
|
+
}, z.core.$strict>;
|
|
86
|
+
export type UsageRow = z.infer<typeof usageRowSchema>;
|
|
87
|
+
export type UsageSnapshot = z.infer<typeof usageSnapshotSchema>;
|
|
88
|
+
export type UsageProvider = (typeof PROVIDERS)[number];
|
|
89
|
+
export type UsageRange = (typeof RANGES)[number];
|
package/dist/schema.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
// Snapshot one device's collector sends to POST /api/usage/ingest.
|
|
3
|
+
// Objects are strict: unknown keys are rejected, so nothing beyond numbers,
|
|
4
|
+
// model names, timestamps and the device id can be stored or served.
|
|
5
|
+
const tokens = z.number().int().nonnegative().max(1e15);
|
|
6
|
+
const usd = z.number().nonnegative().max(1e9);
|
|
7
|
+
const isoDate = z.iso.datetime({ offset: true });
|
|
8
|
+
export const MAX_ROWS = 50_000;
|
|
9
|
+
export const DEVICE_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
10
|
+
export const PROVIDERS = ['claude', 'codex'];
|
|
11
|
+
// Public ranges. All are day-granular: an hourly view would show when each machine is in use.
|
|
12
|
+
export const RANGES = ['7d', '30d', '90d'];
|
|
13
|
+
export const usageRowSchema = z.strictObject({
|
|
14
|
+
hour: isoDate,
|
|
15
|
+
granularity: z.enum(['hour', 'day']).optional(),
|
|
16
|
+
provider: z.enum(PROVIDERS),
|
|
17
|
+
model: z
|
|
18
|
+
.string()
|
|
19
|
+
.min(1)
|
|
20
|
+
.max(100)
|
|
21
|
+
.regex(/^[A-Za-z0-9._:/@-]+$/),
|
|
22
|
+
sessions: z.number().int().nonnegative().max(1e6),
|
|
23
|
+
inputTokens: tokens,
|
|
24
|
+
cacheReadTokens: tokens,
|
|
25
|
+
cacheWrite5mTokens: tokens,
|
|
26
|
+
cacheWrite1hTokens: tokens,
|
|
27
|
+
outputTokens: tokens,
|
|
28
|
+
costUsd: z.strictObject({ input: usd, cacheRead: usd, cacheWrite: usd, output: usd }),
|
|
29
|
+
cacheSavingsUsd: usd
|
|
30
|
+
});
|
|
31
|
+
const sessionCount = z.strictObject({
|
|
32
|
+
claude: z.number().int().nonnegative(),
|
|
33
|
+
codex: z.number().int().nonnegative(),
|
|
34
|
+
all: z.number().int().nonnegative()
|
|
35
|
+
});
|
|
36
|
+
export const usageSnapshotSchema = z.strictObject({
|
|
37
|
+
schemaVersion: z.literal(1),
|
|
38
|
+
deviceId: z.string().regex(DEVICE_ID),
|
|
39
|
+
generatedAt: isoDate,
|
|
40
|
+
coverageStart: isoDate,
|
|
41
|
+
pricingSource: z
|
|
42
|
+
.string()
|
|
43
|
+
.max(80)
|
|
44
|
+
.regex(/^[A-Za-z0-9@._:/-]+$/),
|
|
45
|
+
hourly: z.array(usageRowSchema).max(MAX_ROWS),
|
|
46
|
+
sessionsTotal: z.number().int().nonnegative(),
|
|
47
|
+
// Distinct sessions per range, counted on the device (session ids are never sent).
|
|
48
|
+
sessionCounts: z
|
|
49
|
+
.strictObject({
|
|
50
|
+
// Sent by older collectors only; accepted and ignored.
|
|
51
|
+
'24h': sessionCount.optional(),
|
|
52
|
+
'7d': sessionCount,
|
|
53
|
+
'30d': sessionCount,
|
|
54
|
+
'90d': sessionCount
|
|
55
|
+
})
|
|
56
|
+
.optional()
|
|
57
|
+
});
|
package/dist/serve.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type Server } from 'node:http';
|
|
2
|
+
import type { DeviceConfig } from './devices.ts';
|
|
3
|
+
import { type BigSpender } from './server/index.ts';
|
|
4
|
+
export type ServeConfig = {
|
|
5
|
+
port: number;
|
|
6
|
+
host: string;
|
|
7
|
+
dataDir: string;
|
|
8
|
+
ingestToken: string | undefined;
|
|
9
|
+
devices: DeviceConfig;
|
|
10
|
+
};
|
|
11
|
+
export declare const SERVE_USAGE = "Usage: big-spender serve [--port 8787] [--host 0.0.0.0] [--data ./data] [--devices devices.json]\n\nEnvironment:\n PORT, HOST listen address (flags win)\n BIG_SPENDER_DATA_DIR where per-device snapshots are stored (default ./data)\n BIG_SPENDER_INGEST_TOKEN bearer token collectors must send; ingest is off without it\n BIG_SPENDER_DEVICES_FILE JSON device names and colours (see the README)";
|
|
12
|
+
export declare function loadServeConfig(argv: string[], env?: NodeJS.ProcessEnv): Promise<ServeConfig>;
|
|
13
|
+
export declare function createHttpServer(bs: BigSpender): Server;
|
|
14
|
+
export declare function serve(argv: string[]): Promise<void>;
|
package/dist/serve.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { Readable } from 'node:stream';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { renderPage } from './page.js';
|
|
7
|
+
import { createBigSpender } from './server/index.js';
|
|
8
|
+
const deviceConfigSchema = z.strictObject({
|
|
9
|
+
devices: z.record(z.string(), z.strictObject({ name: z.string().min(1), color: z.string().min(1) })),
|
|
10
|
+
unknownDevices: z.enum(['by-id', 'other']).optional()
|
|
11
|
+
});
|
|
12
|
+
const DEFAULT_DEVICES = { devices: {}, unknownDevices: 'by-id' };
|
|
13
|
+
export const SERVE_USAGE = `Usage: big-spender serve [--port 8787] [--host 0.0.0.0] [--data ./data] [--devices devices.json]
|
|
14
|
+
|
|
15
|
+
Environment:
|
|
16
|
+
PORT, HOST listen address (flags win)
|
|
17
|
+
BIG_SPENDER_DATA_DIR where per-device snapshots are stored (default ./data)
|
|
18
|
+
BIG_SPENDER_INGEST_TOKEN bearer token collectors must send; ingest is off without it
|
|
19
|
+
BIG_SPENDER_DEVICES_FILE JSON device names and colours (see the README)`;
|
|
20
|
+
export async function loadServeConfig(argv, env = process.env) {
|
|
21
|
+
const { values } = parseArgs({
|
|
22
|
+
args: argv,
|
|
23
|
+
options: {
|
|
24
|
+
port: { type: 'string' },
|
|
25
|
+
host: { type: 'string' },
|
|
26
|
+
data: { type: 'string' },
|
|
27
|
+
devices: { type: 'string' }
|
|
28
|
+
},
|
|
29
|
+
strict: true
|
|
30
|
+
});
|
|
31
|
+
const rawPort = values.port ?? env.PORT ?? '8787';
|
|
32
|
+
const port = Number(rawPort);
|
|
33
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
34
|
+
throw new Error(`invalid port "${rawPort}"`);
|
|
35
|
+
}
|
|
36
|
+
const devicesFile = values.devices ?? env.BIG_SPENDER_DEVICES_FILE;
|
|
37
|
+
let devices = DEFAULT_DEVICES;
|
|
38
|
+
if (devicesFile) {
|
|
39
|
+
const parsed = deviceConfigSchema.safeParse(JSON.parse(await readFile(devicesFile, 'utf8')));
|
|
40
|
+
if (!parsed.success) {
|
|
41
|
+
const issues = parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);
|
|
42
|
+
throw new Error(`invalid devices file ${devicesFile}: ${issues.join('; ')}`);
|
|
43
|
+
}
|
|
44
|
+
devices = parsed.data;
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
port,
|
|
48
|
+
host: values.host ?? env.HOST ?? '0.0.0.0',
|
|
49
|
+
dataDir: values.data ?? env.BIG_SPENDER_DATA_DIR ?? './data',
|
|
50
|
+
ingestToken: env.BIG_SPENDER_INGEST_TOKEN?.trim() || undefined,
|
|
51
|
+
devices
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const SECURITY_HEADERS = {
|
|
55
|
+
'x-content-type-options': 'nosniff',
|
|
56
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'"
|
|
57
|
+
};
|
|
58
|
+
const routes = {
|
|
59
|
+
'/api/usage/ingest': { methods: ['POST'], handle: (bs, request) => bs.ingest(request) },
|
|
60
|
+
'/api/usage': {
|
|
61
|
+
methods: ['GET', 'HEAD'],
|
|
62
|
+
handle: async (bs) => Response.json(await bs.summary(), {
|
|
63
|
+
headers: { 'cache-control': 'public, max-age=300, stale-while-revalidate=900' }
|
|
64
|
+
})
|
|
65
|
+
},
|
|
66
|
+
'/': {
|
|
67
|
+
methods: ['GET', 'HEAD'],
|
|
68
|
+
handle: async (bs) => new Response(renderPage(await bs.summary()), {
|
|
69
|
+
headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' }
|
|
70
|
+
})
|
|
71
|
+
},
|
|
72
|
+
'/healthz': { methods: ['GET', 'HEAD'], handle: async () => new Response('ok\n') }
|
|
73
|
+
};
|
|
74
|
+
function toRequest(req) {
|
|
75
|
+
const headers = new Headers();
|
|
76
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
77
|
+
for (const v of Array.isArray(value) ? value : [value])
|
|
78
|
+
if (v !== undefined)
|
|
79
|
+
headers.append(name, v);
|
|
80
|
+
}
|
|
81
|
+
const method = req.method ?? 'GET';
|
|
82
|
+
const hasBody = method !== 'GET' && method !== 'HEAD';
|
|
83
|
+
return new Request(`http://localhost${req.url ?? '/'}`, {
|
|
84
|
+
method,
|
|
85
|
+
headers,
|
|
86
|
+
body: hasBody ? Readable.toWeb(req) : undefined,
|
|
87
|
+
duplex: 'half'
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
async function respond(bs, req) {
|
|
91
|
+
const path = (req.url ?? '/').split('?')[0];
|
|
92
|
+
const route = Object.hasOwn(routes, path) ? routes[path] : undefined;
|
|
93
|
+
if (!route)
|
|
94
|
+
return Response.json({ error: 'not found' }, { status: 404 });
|
|
95
|
+
const method = req.method ?? 'GET';
|
|
96
|
+
if (!route.methods.includes(method)) {
|
|
97
|
+
return Response.json({ error: 'method not allowed' }, { status: 405, headers: { allow: route.methods.join(', ') } });
|
|
98
|
+
}
|
|
99
|
+
return route.handle(bs, toRequest(req));
|
|
100
|
+
}
|
|
101
|
+
async function send(res, response, head) {
|
|
102
|
+
const headers = { ...SECURITY_HEADERS };
|
|
103
|
+
response.headers.forEach((value, name) => (headers[name] = value));
|
|
104
|
+
const body = Buffer.from(await response.arrayBuffer());
|
|
105
|
+
headers['content-length'] = String(body.length);
|
|
106
|
+
res.writeHead(response.status, headers);
|
|
107
|
+
res.end(head ? undefined : body);
|
|
108
|
+
}
|
|
109
|
+
export function createHttpServer(bs) {
|
|
110
|
+
return createServer((req, res) => {
|
|
111
|
+
respond(bs, req)
|
|
112
|
+
.catch((err) => {
|
|
113
|
+
console.error('[big-spender] request failed:', err);
|
|
114
|
+
return Response.json({ error: 'internal error' }, { status: 500 });
|
|
115
|
+
})
|
|
116
|
+
.then((response) => send(res, response, req.method === 'HEAD'))
|
|
117
|
+
.catch(() => res.destroy());
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
export async function serve(argv) {
|
|
121
|
+
const config = await loadServeConfig(argv);
|
|
122
|
+
const bs = createBigSpender(config);
|
|
123
|
+
const server = createHttpServer(bs);
|
|
124
|
+
if (!config.ingestToken) {
|
|
125
|
+
console.warn('[big-spender] BIG_SPENDER_INGEST_TOKEN is not set: ingest is disabled (503)');
|
|
126
|
+
}
|
|
127
|
+
await new Promise((resolve, reject) => {
|
|
128
|
+
server.once('error', reject);
|
|
129
|
+
server.listen(config.port, config.host, resolve);
|
|
130
|
+
});
|
|
131
|
+
console.log(`big-spender listening on http://${config.host}:${config.port} (data: ${config.dataDir})`);
|
|
132
|
+
const stop = () => {
|
|
133
|
+
server.close(() => process.exit(0));
|
|
134
|
+
server.closeAllConnections();
|
|
135
|
+
};
|
|
136
|
+
process.once('SIGTERM', stop);
|
|
137
|
+
process.once('SIGINT', stop);
|
|
138
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { DeviceConfig } from '../devices.ts';
|
|
2
|
+
import { type UsageSummary } from '../summary.ts';
|
|
3
|
+
export { DEVICE_ID, PROVIDERS, RANGES, usageRowSchema, usageSnapshotSchema, type UsageProvider, type UsageRange, type UsageRow, type UsageSnapshot } from '../schema.ts';
|
|
4
|
+
export { OTHER, PALETTE, resolveDevices, type DeviceConfig, type DeviceInfo } from '../devices.ts';
|
|
5
|
+
export { summarize, type CostByType, type DeviceLine, type ModelLine, type ProviderLine, type RangeSummary, type SeriesPoint, type UsageSummary } from '../summary.ts';
|
|
6
|
+
export type BigSpenderOptions = {
|
|
7
|
+
/** Directory for the per-device snapshot files. Use a persistent volume. */
|
|
8
|
+
dataDir: string;
|
|
9
|
+
/** Bearer token collectors must send. Missing or empty turns ingest off (503). */
|
|
10
|
+
ingestToken: string | undefined;
|
|
11
|
+
devices: DeviceConfig;
|
|
12
|
+
};
|
|
13
|
+
export type BigSpender = {
|
|
14
|
+
/** Handles a collector's `POST`. Wire it to whatever route you serve ingest on. */
|
|
15
|
+
ingest(request: Request): Promise<Response>;
|
|
16
|
+
/** Merged totals for every range, recomputed at most every few minutes or after an ingest. */
|
|
17
|
+
summary(now?: number): Promise<UsageSummary>;
|
|
18
|
+
};
|
|
19
|
+
export declare function createBigSpender({ dataDir, ingestToken, devices }: BigSpenderOptions): BigSpender;
|