limitcast 0.0.0-stage → 0.6.1
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 +95 -0
- package/README.md +73 -2
- package/bin/limitcast.mjs +256 -0
- package/package.json +14 -4
- package/src/forecast.mjs +89 -0
- package/src/formats.mjs +115 -0
- package/src/guard.mjs +65 -0
- package/src/install.mjs +241 -0
- package/src/license.mjs +71 -0
- package/src/overhead.mjs +101 -0
- package/src/polar.mjs +169 -0
- package/src/report.mjs +111 -0
- package/src/sources.mjs +95 -0
- package/src/startup.mjs +184 -0
- package/src/store.mjs +70 -0
- package/src/trim.mjs +312 -0
- package/src/usage.mjs +233 -0
package/src/report.mjs
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { total } from './usage.mjs';
|
|
4
|
+
|
|
5
|
+
/** @typedef {import('./usage.mjs').Usage} Usage */
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Weekly burn report as Markdown: totals, per day, per project, per model, top sessions, subagent share.
|
|
9
|
+
* @param {Usage[]} usage
|
|
10
|
+
* @param {{since:number, now:number}} range
|
|
11
|
+
*/
|
|
12
|
+
export function burnReport(usage, { since, now }) {
|
|
13
|
+
const sum = (/** @type {Usage[]} */ xs) => xs.reduce((a, u) => a + total(u), 0);
|
|
14
|
+
const all = sum(usage);
|
|
15
|
+
const lines = [`# limitcast burn report`, '', `${day(since)} to ${day(now)} · ${fmt(all)} tokens`, ''];
|
|
16
|
+
if (!usage.length) return [...lines, 'No Claude Code or Codex usage in this period.'].join('\n');
|
|
17
|
+
|
|
18
|
+
const byTool = group(usage, (u) => u.src);
|
|
19
|
+
lines.push('| tool | tokens | output | cache reads | share |', '|---|---:|---:|---:|---:|');
|
|
20
|
+
for (const [k, xs] of byTool) {
|
|
21
|
+
lines.push(
|
|
22
|
+
`| ${k} | ${fmt(sum(xs))} | ${fmt(xs.reduce((a, u) => a + u.output, 0))} | ${fmt(xs.reduce((a, u) => a + u.cacheRead, 0))} | ${pct(sum(xs), all)} |`,
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const claude = usage.filter((u) => u.src === 'claude');
|
|
27
|
+
if (claude.length) {
|
|
28
|
+
const side = sum(claude.filter((u) => u.sidechain));
|
|
29
|
+
lines.push('', `Subagents used **${pct(side, sum(claude))}** of Claude tokens.`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
table(
|
|
33
|
+
lines,
|
|
34
|
+
'By day',
|
|
35
|
+
group(usage, (u) => day(u.t)),
|
|
36
|
+
sum,
|
|
37
|
+
all,
|
|
38
|
+
false,
|
|
39
|
+
);
|
|
40
|
+
table(
|
|
41
|
+
lines,
|
|
42
|
+
'Top projects',
|
|
43
|
+
group(usage, (u) => short(u.project) || '(unknown)'),
|
|
44
|
+
sum,
|
|
45
|
+
all,
|
|
46
|
+
true,
|
|
47
|
+
8,
|
|
48
|
+
);
|
|
49
|
+
table(
|
|
50
|
+
lines,
|
|
51
|
+
'By model',
|
|
52
|
+
group(usage, (u) => u.model || '(unknown)'),
|
|
53
|
+
sum,
|
|
54
|
+
all,
|
|
55
|
+
true,
|
|
56
|
+
6,
|
|
57
|
+
);
|
|
58
|
+
table(
|
|
59
|
+
lines,
|
|
60
|
+
'Heaviest sessions',
|
|
61
|
+
group(usage, (u) => `${u.src} ${u.session.slice(0, 8)} · ${short(u.project)}`),
|
|
62
|
+
sum,
|
|
63
|
+
all,
|
|
64
|
+
true,
|
|
65
|
+
5,
|
|
66
|
+
);
|
|
67
|
+
lines.push('', `_Generated by limitcast. Token counts come from your local Claude Code and Codex logs._`);
|
|
68
|
+
return lines.join('\n');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @param {string[]} lines
|
|
73
|
+
* @param {string} title
|
|
74
|
+
* @param {Map<string, Usage[]>} groups
|
|
75
|
+
* @param {(xs:Usage[])=>number} sum
|
|
76
|
+
* @param {number} all
|
|
77
|
+
* @param {boolean} sortBySize
|
|
78
|
+
* @param {number} [limit]
|
|
79
|
+
*/
|
|
80
|
+
function table(lines, title, groups, sum, all, sortBySize, limit = Infinity) {
|
|
81
|
+
let rows = [...groups].map(([k, xs]) => /** @type {[string, number]} */ ([k, sum(xs)]));
|
|
82
|
+
rows = sortBySize ? rows.sort((a, b) => b[1] - a[1]) : rows.sort((a, b) => a[0].localeCompare(b[0]));
|
|
83
|
+
lines.push('', `## ${title}`, '', '| | tokens | share |', '|---|---:|---:|');
|
|
84
|
+
for (const [k, n] of rows.slice(0, limit)) lines.push(`| ${k} | ${fmt(n)} | ${pct(n, all)} |`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* @template T
|
|
89
|
+
* @param {T[]} xs
|
|
90
|
+
* @param {(x:T)=>string} key
|
|
91
|
+
*/
|
|
92
|
+
function group(xs, key) {
|
|
93
|
+
/** @type {Map<string, T[]>} */
|
|
94
|
+
const m = new Map();
|
|
95
|
+
for (const x of xs) {
|
|
96
|
+
const k = key(x);
|
|
97
|
+
if (!m.has(k)) m.set(k, []);
|
|
98
|
+
m.get(k)?.push(x);
|
|
99
|
+
}
|
|
100
|
+
return m;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** @param {number} n */
|
|
104
|
+
export const fmt = (n) =>
|
|
105
|
+
n >= 1e9 ? `${(n / 1e9).toFixed(2)}B` : n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : `${n}`;
|
|
106
|
+
/** @param {number} n @param {number} d */
|
|
107
|
+
const pct = (n, d) => (d ? `${Math.round((n / d) * 100)}%` : '-');
|
|
108
|
+
/** @param {number} t */
|
|
109
|
+
const day = (t) => new Date(t).toLocaleDateString('sv-SE'); // local YYYY-MM-DD
|
|
110
|
+
/** @param {string} p */
|
|
111
|
+
const short = (p) => p.replace(homedir(), '~');
|
package/src/sources.mjs
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { createReadStream, existsSync, readdirSync, statSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline';
|
|
6
|
+
import { windowName } from './forecast.mjs';
|
|
7
|
+
|
|
8
|
+
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Samples from the JSON Claude Code pipes to its status line.
|
|
12
|
+
* @param {any} input parsed status-line JSON
|
|
13
|
+
* @param {number} now epoch ms
|
|
14
|
+
* @returns {Sample[]}
|
|
15
|
+
*/
|
|
16
|
+
export function claudeSamples(input, now) {
|
|
17
|
+
const rl = input?.rate_limits;
|
|
18
|
+
if (!rl || typeof rl !== 'object') return [];
|
|
19
|
+
/** @type {Sample[]} */
|
|
20
|
+
const out = [];
|
|
21
|
+
for (const [key, win] of [
|
|
22
|
+
['five_hour', '5h'],
|
|
23
|
+
['seven_day', '7d'],
|
|
24
|
+
]) {
|
|
25
|
+
const w = rl[key];
|
|
26
|
+
const pct = Number(w?.used_percentage);
|
|
27
|
+
const reset = Number(w?.resets_at);
|
|
28
|
+
if (Number.isFinite(pct) && Number.isFinite(reset) && reset > 0) {
|
|
29
|
+
out.push({ t: now, src: 'claude', win, pct, reset, ...(input.session_id ? { sid: String(input.session_id) } : {}) });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Samples from one Codex rollout JSONL line, or [] if it carries no rate limits.
|
|
37
|
+
* @param {string} line
|
|
38
|
+
* @returns {Sample[]}
|
|
39
|
+
*/
|
|
40
|
+
export function codexSamples(line) {
|
|
41
|
+
if (!line.includes('"rate_limits"')) return [];
|
|
42
|
+
let ev;
|
|
43
|
+
try {
|
|
44
|
+
ev = JSON.parse(line);
|
|
45
|
+
} catch {
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
const rl = ev?.payload?.rate_limits;
|
|
49
|
+
const t = Date.parse(ev?.timestamp);
|
|
50
|
+
if (!rl || !Number.isFinite(t)) return [];
|
|
51
|
+
/** @type {Sample[]} */
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const w of [rl.primary, rl.secondary]) {
|
|
54
|
+
const pct = Number(w?.used_percent);
|
|
55
|
+
const reset = Number(w?.resets_at);
|
|
56
|
+
const mins = Number(w?.window_minutes);
|
|
57
|
+
if (Number.isFinite(pct) && Number.isFinite(reset) && reset > 0 && mins > 0) {
|
|
58
|
+
out.push({ t, src: 'codex', win: windowName(mins), pct, reset });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* All Codex samples from rollout files modified since `since`.
|
|
66
|
+
* @param {number} since epoch ms
|
|
67
|
+
* @param {string} [root]
|
|
68
|
+
* @returns {Promise<Sample[]>}
|
|
69
|
+
*/
|
|
70
|
+
export async function readCodex(since, root = join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'sessions')) {
|
|
71
|
+
if (!existsSync(root)) return [];
|
|
72
|
+
/** @type {Sample[]} */
|
|
73
|
+
const out = [];
|
|
74
|
+
for (const file of rolloutFiles(root, since)) {
|
|
75
|
+
const rl = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
|
|
76
|
+
for await (const line of rl) for (const s of codexSamples(line)) if (s.t >= since) out.push(s);
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* @param {string} dir
|
|
83
|
+
* @param {number} since
|
|
84
|
+
* @returns {string[]}
|
|
85
|
+
*/
|
|
86
|
+
function rolloutFiles(dir, since) {
|
|
87
|
+
/** @type {string[]} */
|
|
88
|
+
const out = [];
|
|
89
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
90
|
+
const p = join(dir, e.name);
|
|
91
|
+
if (e.isDirectory()) out.push(...rolloutFiles(p, since));
|
|
92
|
+
else if (e.name.startsWith('rollout-') && e.name.endsWith('.jsonl') && statSync(p).mtimeMs >= since) out.push(p);
|
|
93
|
+
}
|
|
94
|
+
return out;
|
|
95
|
+
}
|
package/src/startup.mjs
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { createReadStream, readdirSync, statSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One piece of the context Claude Code loads before your first message, measured from the transcript.
|
|
8
|
+
* @typedef {{group:string, name:string, chars:number}} Piece
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Break a session's starting context into pieces: SessionStart hook output, MCP server instructions and
|
|
13
|
+
* tool names, the agent list, the skill listing (per skill), instruction files and the output style.
|
|
14
|
+
* Reads the transcript only up to the first model response.
|
|
15
|
+
* @param {string} file transcript .jsonl
|
|
16
|
+
* @returns {Promise<{pieces:Piece[], at:number, entry:string}>}
|
|
17
|
+
*/
|
|
18
|
+
export async function startupBreakdown(file) {
|
|
19
|
+
/** @type {Piece[]} */
|
|
20
|
+
const pieces = [];
|
|
21
|
+
let at = 0;
|
|
22
|
+
let entry = '';
|
|
23
|
+
const rl = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
|
|
24
|
+
for await (const line of rl) {
|
|
25
|
+
if (line.includes('"type":"assistant"')) {
|
|
26
|
+
try {
|
|
27
|
+
const ev = JSON.parse(line);
|
|
28
|
+
at = Date.parse(ev.timestamp) || 0;
|
|
29
|
+
entry = ev.entrypoint ?? '';
|
|
30
|
+
} catch {
|
|
31
|
+
/* torn line: keep what we have */
|
|
32
|
+
}
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
if (!line.includes('"type":"attachment"')) continue;
|
|
36
|
+
let a;
|
|
37
|
+
try {
|
|
38
|
+
a = JSON.parse(line).attachment;
|
|
39
|
+
} catch {
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
pieces.push(...attachmentPieces(a));
|
|
43
|
+
}
|
|
44
|
+
rl.close();
|
|
45
|
+
return { pieces, at, entry };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* @param {any} a transcript attachment
|
|
50
|
+
* @returns {Piece[]}
|
|
51
|
+
*/
|
|
52
|
+
export function attachmentPieces(a) {
|
|
53
|
+
switch (a?.type) {
|
|
54
|
+
case 'hook_success': {
|
|
55
|
+
if (a.hookEvent !== 'SessionStart') return [];
|
|
56
|
+
// Plain-text output arrives as `content`; JSON output's additionalContext is inside `stdout`.
|
|
57
|
+
let chars = typeof a.content === 'string' ? a.content.length : 0;
|
|
58
|
+
if (!chars && typeof a.stdout === 'string') {
|
|
59
|
+
try {
|
|
60
|
+
chars = String(JSON.parse(a.stdout)?.hookSpecificOutput?.additionalContext ?? '').length;
|
|
61
|
+
} catch {
|
|
62
|
+
chars = 0;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return chars ? [{ group: 'SessionStart hooks', name: hookLabel(String(a.command ?? '')), chars }] : [];
|
|
66
|
+
}
|
|
67
|
+
case 'mcp_instructions_delta':
|
|
68
|
+
return (a.addedNames ?? []).map((/** @type {string} */ n, /** @type {number} */ i) => ({
|
|
69
|
+
group: 'MCP server instructions',
|
|
70
|
+
name: n,
|
|
71
|
+
chars: text(a.addedBlocks?.[i]).length,
|
|
72
|
+
}));
|
|
73
|
+
case 'deferred_tools_delta': {
|
|
74
|
+
// One line per tool name; group MCP tools by server.
|
|
75
|
+
/** @type {Map<string, number>} */
|
|
76
|
+
const by = new Map();
|
|
77
|
+
(a.addedLines ?? []).forEach((/** @type {string} */ l, /** @type {number} */ i) => {
|
|
78
|
+
const name = String(a.addedNames?.[i] ?? l);
|
|
79
|
+
const key = name.startsWith('mcp__') ? name.split('__')[1] : '(built-in)';
|
|
80
|
+
by.set(key, (by.get(key) ?? 0) + String(l).length + 1);
|
|
81
|
+
});
|
|
82
|
+
return [...by].map(([name, chars]) => ({ group: 'Tool names', name, chars }));
|
|
83
|
+
}
|
|
84
|
+
case 'agent_listing_delta':
|
|
85
|
+
return [{ group: 'Agent list', name: `${(a.addedLines ?? []).length} agents`, chars: (a.addedLines ?? []).join('\n').length }];
|
|
86
|
+
case 'skill_listing':
|
|
87
|
+
return skillPieces(String(a.content ?? ''));
|
|
88
|
+
case 'instructions':
|
|
89
|
+
return (a.files ?? []).map((/** @type {any} */ f) => ({
|
|
90
|
+
group: 'Instruction files',
|
|
91
|
+
name: String(f.path ?? ''),
|
|
92
|
+
chars: String(f.content ?? '').length,
|
|
93
|
+
}));
|
|
94
|
+
case 'output_style_instructions':
|
|
95
|
+
return [{ group: 'Output style', name: 'output style', chars: text(a.style).length }];
|
|
96
|
+
default:
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The skill listing is "- name: description" entries; size each one.
|
|
103
|
+
* @param {string} content
|
|
104
|
+
* @returns {Piece[]}
|
|
105
|
+
*/
|
|
106
|
+
export function skillPieces(content) {
|
|
107
|
+
return content
|
|
108
|
+
.split(/\n(?=- )/)
|
|
109
|
+
.filter((e) => e.startsWith('- '))
|
|
110
|
+
.map((e) => {
|
|
111
|
+
// Names can contain ':' (plugin:skill); the description starts after the first ': '.
|
|
112
|
+
const body = e.slice(2);
|
|
113
|
+
const i = body.indexOf(': ');
|
|
114
|
+
return { group: 'Skill listing', name: (i >= 0 ? body.slice(0, i) : body).split('\n')[0].trim(), chars: e.length };
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** @param {unknown} v */
|
|
119
|
+
const text = (v) => (typeof v === 'string' ? v : v == null ? '' : JSON.stringify(v));
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* A readable label for a hook command: the plugin or script name rather than the whole command line.
|
|
123
|
+
* @param {string} cmd
|
|
124
|
+
*/
|
|
125
|
+
export function hookLabel(cmd) {
|
|
126
|
+
const plugin = cmd.match(/plugins\/(?:cache\/)?[^/]+\/([^/]+)/)?.[1];
|
|
127
|
+
if (plugin) return plugin;
|
|
128
|
+
// Plugin hooks often hide behind ${CLAUDE_PLUGIN_ROOT}; the file they run or print is the best name.
|
|
129
|
+
const script = cmd.match(/([\w.-]+\.(?:md|txt|py|sh|js|mjs|cjs|cmd|ts|rb))\b/)?.[1];
|
|
130
|
+
return script ?? cmd.slice(0, 50);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The most recently active interactive (launched from the CLI, not a subagent or SDK run) transcript.
|
|
135
|
+
* @param {string} root ~/.claude/projects
|
|
136
|
+
* @param {number} [scan] how many recent transcripts to check
|
|
137
|
+
*/
|
|
138
|
+
export async function latestInteractiveTranscript(root, scan = 40) {
|
|
139
|
+
/** @type {{p:string, m:number}[]} */
|
|
140
|
+
const files = [];
|
|
141
|
+
try {
|
|
142
|
+
for (const proj of readdirSync(root, { withFileTypes: true })) {
|
|
143
|
+
if (!proj.isDirectory()) continue;
|
|
144
|
+
for (const f of readdirSync(join(root, proj.name), { withFileTypes: true })) {
|
|
145
|
+
if (f.isFile() && f.name.endsWith('.jsonl')) {
|
|
146
|
+
const p = join(root, proj.name, f.name);
|
|
147
|
+
files.push({ p, m: statSync(p).mtimeMs });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
} catch {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
for (const { p } of files.sort((a, b) => b.m - a.m).slice(0, scan)) {
|
|
155
|
+
const b = await startupBreakdown(p);
|
|
156
|
+
if (b.entry === 'cli' && b.pieces.length) return { file: p, ...b };
|
|
157
|
+
}
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Interactive (CLI-launched) Claude Code sessions started since `since`, read from transcript heads.
|
|
163
|
+
* @param {string} root ~/.claude/projects
|
|
164
|
+
* @param {number} since epoch ms
|
|
165
|
+
*/
|
|
166
|
+
export async function countInteractiveSince(root, since) {
|
|
167
|
+
let n = 0;
|
|
168
|
+
try {
|
|
169
|
+
for (const proj of readdirSync(root, { withFileTypes: true })) {
|
|
170
|
+
if (!proj.isDirectory()) continue;
|
|
171
|
+
for (const f of readdirSync(join(root, proj.name), { withFileTypes: true })) {
|
|
172
|
+
if (!f.isFile() || !f.name.endsWith('.jsonl')) continue;
|
|
173
|
+
const p = join(root, proj.name, f.name);
|
|
174
|
+
const st = statSync(p);
|
|
175
|
+
if ((st.birthtimeMs || st.mtimeMs) < since) continue;
|
|
176
|
+
const b = await startupBreakdown(p);
|
|
177
|
+
if (b.entry === 'cli' && b.at >= since) n++;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
} catch {
|
|
181
|
+
/* unreadable root: count what we have */
|
|
182
|
+
}
|
|
183
|
+
return n;
|
|
184
|
+
}
|
package/src/store.mjs
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
/** @typedef {import('./forecast.mjs').Sample} Sample */
|
|
7
|
+
|
|
8
|
+
export const KEEP_MS = 8 * 24 * 3600_000;
|
|
9
|
+
const PRUNE_BYTES = 1_000_000;
|
|
10
|
+
|
|
11
|
+
export function stateDir() {
|
|
12
|
+
return process.env.LIMITCAST_STATE ?? join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), 'limitcast');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Append samples whose pct or reset changed since the last one for the same series.
|
|
17
|
+
* The status line fires on every message, so unchanged readings are skipped.
|
|
18
|
+
* @param {Sample[]} samples
|
|
19
|
+
*/
|
|
20
|
+
export function record(samples) {
|
|
21
|
+
if (!samples.length) return;
|
|
22
|
+
const dir = stateDir();
|
|
23
|
+
mkdirSync(dir, { recursive: true });
|
|
24
|
+
const lastPath = join(dir, 'last.json');
|
|
25
|
+
/** @type {Record<string, {pct:number, reset:number}>} */
|
|
26
|
+
let last = {};
|
|
27
|
+
try {
|
|
28
|
+
last = JSON.parse(readFileSync(lastPath, 'utf8'));
|
|
29
|
+
} catch {
|
|
30
|
+
/* first run or corrupt: start fresh */
|
|
31
|
+
}
|
|
32
|
+
const key = (/** @type {Sample} */ s) => `${s.src}:${s.win}:${s.sid ?? ''}`;
|
|
33
|
+
const fresh = samples.filter((s) => {
|
|
34
|
+
const prev = last[key(s)];
|
|
35
|
+
return !prev || prev.pct !== s.pct || prev.reset !== s.reset;
|
|
36
|
+
});
|
|
37
|
+
if (!fresh.length) return;
|
|
38
|
+
const file = join(dir, 'samples.jsonl');
|
|
39
|
+
appendFileSync(file, `${fresh.map((s) => JSON.stringify(s)).join('\n')}\n`);
|
|
40
|
+
for (const s of fresh) last[key(s)] = { pct: s.pct, reset: s.reset };
|
|
41
|
+
writeFileSync(lastPath, JSON.stringify(last));
|
|
42
|
+
if (statSync(file).size > PRUNE_BYTES)
|
|
43
|
+
writeFileSync(
|
|
44
|
+
file,
|
|
45
|
+
load(Date.now() - KEEP_MS)
|
|
46
|
+
.map((s) => `${JSON.stringify(s)}\n`)
|
|
47
|
+
.join(''),
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {number} since epoch ms
|
|
53
|
+
* @returns {Sample[]}
|
|
54
|
+
*/
|
|
55
|
+
export function load(since) {
|
|
56
|
+
const file = join(stateDir(), 'samples.jsonl');
|
|
57
|
+
if (!existsSync(file)) return [];
|
|
58
|
+
/** @type {Sample[]} */
|
|
59
|
+
const out = [];
|
|
60
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
61
|
+
if (!line) continue;
|
|
62
|
+
try {
|
|
63
|
+
const s = JSON.parse(line);
|
|
64
|
+
if (s.t >= since) out.push(s);
|
|
65
|
+
} catch {
|
|
66
|
+
/* skip a torn line from a concurrent write */
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|