claude-rpc 1.5.2 → 1.6.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 +72 -62
- package/SECURITY.md +99 -20
- package/package.json +2 -1
- package/src/atomic-rename.js +45 -2
- package/src/badge.js +3 -4
- package/src/card.js +1 -22
- package/src/cli-path.js +286 -0
- package/src/cli.js +430 -459
- package/src/commands.js +245 -0
- package/src/community.js +101 -60
- package/src/completion.js +196 -0
- package/src/config.js +4 -1
- package/src/daemon.js +45 -47
- package/src/default-config.js +4 -3
- package/src/discord-ipc.js +24 -13
- package/src/doctor.js +64 -38
- package/src/ensure-daemon.js +11 -4
- package/src/fmt.js +8 -6
- package/src/format.js +8 -13
- package/src/gist.js +8 -18
- package/src/git.js +4 -1
- package/src/help.js +117 -0
- package/src/hook.js +27 -32
- package/src/insights.js +3 -4
- package/src/install.js +100 -79
- package/src/leaderboard.js +3 -2
- package/src/mcp.js +2 -8
- package/src/nudge.js +10 -5
- package/src/png.js +135 -0
- package/src/pricing.js +25 -3
- package/src/privacy.js +22 -7
- package/src/profile.js +0 -6
- package/src/recap.js +4 -17
- package/src/scanner.js +103 -71
- package/src/select.js +60 -0
- package/src/server/api.js +64 -36
- package/src/server/assets/dashboard.client.js +75 -44
- package/src/server/assets/dashboard.css +18 -18
- package/src/server/assets/dashboard.html +13 -15
- package/src/server/assets/wrapped.client.js +26 -11
- package/src/server/assets/wrapped.css +2 -2
- package/src/server/index.js +43 -32
- package/src/server/page.js +6 -3
- package/src/server/sse.js +90 -34
- package/src/session-card.js +3 -1
- package/src/statcards.js +278 -0
- package/src/state.js +14 -24
- package/src/tui.js +3 -12
- package/src/ui.js +7 -5
- package/src/verify.js +3 -7
- package/src/version.js +1 -1
- package/src/week.js +4 -4
package/src/commands.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// The one table of CLI commands. `help`, `help <command>`, tab completion
|
|
2
|
+
// (`__complete`) and the "did you mean" hint all read it, so a command, flag
|
|
3
|
+
// or sub-command added here shows up in all four at once. Dispatch itself
|
|
4
|
+
// stays in cli.js's switch; test/commands.test.js fails when the two drift.
|
|
5
|
+
//
|
|
6
|
+
// Shape of an entry:
|
|
7
|
+
// name what you type
|
|
8
|
+
// group help section (GROUPS order); omitted → hidden from help + completion
|
|
9
|
+
// summary one line for the list
|
|
10
|
+
// usage argument synopsis after the name ('' when none)
|
|
11
|
+
// subs [name, summary] positional choices for the first argument
|
|
12
|
+
// flags [flag, summary, values?] — values: an array, 'file', 'project' or
|
|
13
|
+
// 'any' (takes a free-form value); no values → boolean switch
|
|
14
|
+
// aliases older names that still work (stable per VERSIONING.md), not listed
|
|
15
|
+
// examples shown by `help <command>`
|
|
16
|
+
//
|
|
17
|
+
// Pure data + pure helpers: no fs, no imports from the core graph — the
|
|
18
|
+
// completion path loads this on every <Tab>.
|
|
19
|
+
|
|
20
|
+
export const GROUPS = [
|
|
21
|
+
['start', 'Get started'],
|
|
22
|
+
['stats', 'Your stats'],
|
|
23
|
+
['share', 'Share'],
|
|
24
|
+
['privacy', 'Privacy'],
|
|
25
|
+
['online', 'Online'],
|
|
26
|
+
['daemon', 'Daemon'],
|
|
27
|
+
['fix', 'Troubleshoot'],
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
const METRICS = ['hours', 'tokens', 'streak', 'sessions'];
|
|
31
|
+
const RANGES = ['week', 'month', 'year', 'all'];
|
|
32
|
+
export const SHELLS = ['bash', 'zsh', 'fish', 'powershell'];
|
|
33
|
+
|
|
34
|
+
export const COMMANDS = [
|
|
35
|
+
// ── Get started ──
|
|
36
|
+
{ name: 'setup', group: 'start', summary: 'Hook into Claude Code and start the card — run once',
|
|
37
|
+
flags: [['--link', 'Also verify this machine with a claude-rpc.com code', 'any'],
|
|
38
|
+
['--wrapped', 'With --link: publish your year-in-review too']],
|
|
39
|
+
aliases: ['install'],
|
|
40
|
+
examples: ['claude-rpc setup', 'claude-rpc setup --link ABCD-1234 --wrapped'] },
|
|
41
|
+
{ name: 'completion', group: 'start', summary: 'Tab completion for your shell', usage: '[install|uninstall|<shell>]',
|
|
42
|
+
subs: [['install', 'Turn it on for your shell (asks nothing else)'], ['uninstall', 'Turn it off'],
|
|
43
|
+
...SHELLS.map((s) => [s, `Print the ${s} script`])],
|
|
44
|
+
examples: ['claude-rpc completion install', 'claude-rpc completion zsh > ~/.zfunc/_claude-rpc'] },
|
|
45
|
+
{ name: 'uninstall', group: 'start', summary: 'Undo setup (keeps your config and stats)' },
|
|
46
|
+
|
|
47
|
+
// ── Your stats ──
|
|
48
|
+
{ name: 'status', group: 'stats', summary: 'Live stats dashboard in the terminal',
|
|
49
|
+
flags: [['--dump', 'Print once as plain text (also when piped)']], aliases: ['dump'] },
|
|
50
|
+
{ name: 'today', group: 'stats', summary: 'Today, plus when in the day you code' },
|
|
51
|
+
{ name: 'week', group: 'stats', summary: 'This week day by day',
|
|
52
|
+
flags: [['--compare', 'Side by side with last week']], aliases: ['compare'],
|
|
53
|
+
examples: ['claude-rpc week', 'claude-rpc week --compare'] },
|
|
54
|
+
{ name: 'projects', group: 'stats', summary: 'Projects ranked by time — or one project in detail', usage: '[name]',
|
|
55
|
+
args: 'project', flags: [['--limit', 'How many to list (default 12)', 'any']], aliases: ['project'],
|
|
56
|
+
examples: ['claude-rpc projects', 'claude-rpc projects claude-rpc'] },
|
|
57
|
+
{ name: 'usage', group: 'stats', summary: 'Plan limits: session and weekly % used' },
|
|
58
|
+
{ name: 'recap', group: 'stats', summary: 'Standup summary (yesterday by default)', usage: '[today|yesterday|week|YYYY-MM-DD]',
|
|
59
|
+
subs: [['yesterday', 'Default — Monday covers Friday'], ['today', 'So far today'], ['week', 'This week']],
|
|
60
|
+
flags: [['--md', 'Paste-ready markdown'], ['--json', 'Raw numbers']],
|
|
61
|
+
examples: ['claude-rpc recap', 'claude-rpc recap week --md'] },
|
|
62
|
+
{ name: 'insights', group: 'stats', summary: 'Patterns spotted in your history' },
|
|
63
|
+
{ name: 'wrapped', group: 'stats', summary: 'Your animated year in review',
|
|
64
|
+
flags: [['--publish', 'Put it on claude-rpc.com/wrapped/<handle>'], ['--year', 'Which year', 'any'], ['--yes', 'Skip the confirm']] },
|
|
65
|
+
{ name: 'serve', group: 'stats', summary: 'Open the live web dashboard' },
|
|
66
|
+
{ name: 'export', group: 'stats', summary: 'Everything as JSON, or daily rows as CSV',
|
|
67
|
+
flags: [['--csv', 'Daily rows as CSV'], ['--out', 'Write to a file', 'file']] },
|
|
68
|
+
|
|
69
|
+
// ── Share ──
|
|
70
|
+
{ name: 'statcards', group: 'share', summary: 'Cards and badges as a live link, PNG or SVG', usage: '[card]',
|
|
71
|
+
subs: [['stats', 'Stats + year heatmap'], ['profile', 'Profile card'], ['badge', 'Small badge'],
|
|
72
|
+
['heatmap', 'Year heatmap'], ['poster', 'Poster summary'], ['session', 'This session'],
|
|
73
|
+
['wrapped', 'Year-in-review card'], ['list', 'What each card is and where it can go']],
|
|
74
|
+
flags: [['--link', 'Live, self-updating URL (needs a public profile)'], ['--png', 'Save a PNG (optional path)', 'file'],
|
|
75
|
+
['--svg', 'Save an SVG (optional path)', 'file'], ['--md', 'With --link: print Markdown'],
|
|
76
|
+
['--html', 'With --link: print an <img> tag'], ['--metric', 'What a badge/heatmap counts', METRICS],
|
|
77
|
+
['--range', 'Window for badge/poster', RANGES], ['--copy', 'Copy the snippet to the clipboard']],
|
|
78
|
+
aliases: ['badge', 'card', 'github-stat', 'calendar', 'session-card', 'readme'],
|
|
79
|
+
examples: ['claude-rpc statcards', 'claude-rpc statcards stats --link --md', 'claude-rpc statcards poster --png', 'claude-rpc statcards badge --metric streak --svg streak.svg'] },
|
|
80
|
+
{ name: 'statusline', group: 'share', summary: 'One-line status for tmux and shell prompts',
|
|
81
|
+
flags: [['--template', 'Template using any `claude-rpc vars` name', 'any']] },
|
|
82
|
+
{ name: 'mcp', group: 'share', summary: 'Let Claude read your stats (MCP server)', usage: '[install|uninstall]',
|
|
83
|
+
subs: [['install', 'Wire it into Claude Code'], ['uninstall', 'Remove it']] },
|
|
84
|
+
|
|
85
|
+
// ── Privacy ──
|
|
86
|
+
{ name: 'private', group: 'privacy', summary: 'Hide this folder from Discord — or show it again', usage: '[on|off|status]',
|
|
87
|
+
subs: [['on', 'Hide this folder (default)'], ['off', 'Show it again'], ['status', 'What Discord sees for this folder']],
|
|
88
|
+
aliases: ['public', 'privacy'],
|
|
89
|
+
examples: ['claude-rpc private', 'claude-rpc private off', 'claude-rpc private status'] },
|
|
90
|
+
{ name: 'pause', group: 'privacy', summary: 'Hide the card everywhere for a while (default 1h)', usage: '[30m|2h|off|status]',
|
|
91
|
+
subs: [['30m', '30 minutes'], ['1h', 'An hour'], ['2h', 'Two hours'], ['off', 'Show the card again'], ['status', 'Paused?']],
|
|
92
|
+
aliases: ['resume', 'unpause'],
|
|
93
|
+
examples: ['claude-rpc pause 2h', 'claude-rpc pause off'] },
|
|
94
|
+
|
|
95
|
+
// ── Online ──
|
|
96
|
+
{ name: 'profile', group: 'online', summary: 'Your public leaderboard profile', usage: '[status|set|on|off|publish|verify]',
|
|
97
|
+
subs: [['status', 'Show it'], ['set', 'Change handle / name / github'], ['on', 'Go public'], ['off', 'Go private'],
|
|
98
|
+
['publish', 'Push your numbers now'], ['verify', 'Prove the GitHub account is yours']],
|
|
99
|
+
flags: [['--handle', 'With set: your handle', 'any'], ['--name', 'With set: display name', 'any'], ['--github', 'With set: GitHub login', 'any']] },
|
|
100
|
+
{ name: 'squad', group: 'online', summary: 'Private leaderboards with friends', usage: '[status|create|join|leave]',
|
|
101
|
+
subs: [['status', 'Your squads'], ['create', 'Start one'], ['join', 'Join with a code'], ['leave', 'Leave one']] },
|
|
102
|
+
{ name: 'link', group: 'online', summary: 'Join machines into one profile', usage: '[code]' },
|
|
103
|
+
{ name: 'community', group: 'online', summary: 'Anonymous community totals', usage: '[status|on|off|report]',
|
|
104
|
+
subs: [['status', 'Show it'], ['on', 'Opt in'], ['off', 'Opt out'], ['report', 'Send now']] },
|
|
105
|
+
|
|
106
|
+
// ── Daemon ──
|
|
107
|
+
{ name: 'start', group: 'daemon', summary: 'Start the Discord daemon' },
|
|
108
|
+
{ name: 'stop', group: 'daemon', summary: 'Stop it' },
|
|
109
|
+
{ name: 'restart', group: 'daemon', summary: 'Restart it and wait until it is up' },
|
|
110
|
+
{ name: 'logs', group: 'daemon', summary: 'Follow the daemon log', aliases: ['tail', 'log'] },
|
|
111
|
+
|
|
112
|
+
// ── Troubleshoot ──
|
|
113
|
+
{ name: 'doctor', group: 'fix', summary: 'Check everything; --fix repairs what it can',
|
|
114
|
+
flags: [['--fix', 'Apply the repairs']] },
|
|
115
|
+
{ name: 'scan', group: 'fix', summary: 'Re-count your history from transcripts',
|
|
116
|
+
flags: [['--force', 'Re-parse everything, ignore the cache']], aliases: ['rescan'] },
|
|
117
|
+
{ name: 'backfill', group: 'fix', summary: 'Import transcripts from a backup or another machine', usage: '<dir>', args: 'file' },
|
|
118
|
+
{ name: 'preview', group: 'fix', summary: 'How every card frame renders right now' },
|
|
119
|
+
{ name: 'vars', group: 'fix', summary: 'Every template variable and its live value (JSON)' },
|
|
120
|
+
{ name: 'upgrade-config', summary: 'Re-run config migrations' },
|
|
121
|
+
{ name: 'daemon', summary: 'Run the daemon in the foreground (debug)' },
|
|
122
|
+
{ name: 'help', summary: 'This screen, or one command in detail', usage: '[command]', args: 'command' },
|
|
123
|
+
];
|
|
124
|
+
|
|
125
|
+
// Internal entry points the dispatcher knows but nobody types.
|
|
126
|
+
export const INTERNAL = ['hook', 'scan-worker', '__complete', '--version', '-V', '-v', '--help', '-h'];
|
|
127
|
+
|
|
128
|
+
const BY_NAME = new Map();
|
|
129
|
+
for (const cmd of COMMANDS) {
|
|
130
|
+
BY_NAME.set(cmd.name, cmd);
|
|
131
|
+
for (const a of cmd.aliases || []) BY_NAME.set(a, cmd);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// The command entry for a name or any alias, or null.
|
|
135
|
+
export function findCommand(name) {
|
|
136
|
+
return BY_NAME.get(name) || null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Every name the dispatcher must accept: commands, aliases, internals.
|
|
140
|
+
export function allNames() {
|
|
141
|
+
return [...BY_NAME.keys(), ...INTERNAL];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function visibleCommands() {
|
|
145
|
+
return COMMANDS.filter((c) => c.group);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Damerau-free Levenshtein, small strings only.
|
|
149
|
+
function distance(a, b) {
|
|
150
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
151
|
+
for (let i = 1; i <= a.length; i++) {
|
|
152
|
+
let prev = row[0];
|
|
153
|
+
row[0] = i;
|
|
154
|
+
for (let j = 1; j <= b.length; j++) {
|
|
155
|
+
const tmp = row[j];
|
|
156
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
157
|
+
prev = tmp;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return row[b.length];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// What each older name now spells, for `help <old>` and typo hints.
|
|
164
|
+
export const ALIAS_HINT = {
|
|
165
|
+
install: 'setup', dump: 'status --dump', compare: 'week --compare', project: 'projects <name>',
|
|
166
|
+
rescan: 'scan --force', resume: 'pause off', unpause: 'pause off', public: 'private off',
|
|
167
|
+
privacy: 'private status', tail: 'logs', log: 'logs', badge: 'statcards badge', card: 'statcards poster',
|
|
168
|
+
'github-stat': 'statcards profile', calendar: 'statcards heatmap', 'session-card': 'statcards session',
|
|
169
|
+
readme: 'statcards stats --link',
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
// "did you mean" for an unknown command: a unique prefix match first
|
|
173
|
+
// (`stat` is ambiguous, `statc` → statcards), else the closest name within 2
|
|
174
|
+
// edits. Older names count too, so muscle memory still gets a hint — the hint
|
|
175
|
+
// is the name that matched, which still works.
|
|
176
|
+
export function suggestCommand(input) {
|
|
177
|
+
const s = String(input || '').toLowerCase();
|
|
178
|
+
if (!s) return null;
|
|
179
|
+
const names = [...BY_NAME.keys()];
|
|
180
|
+
const prefixed = names.filter((n) => n.startsWith(s));
|
|
181
|
+
if (prefixed.length && new Set(prefixed.map((n) => BY_NAME.get(n).name)).size === 1) {
|
|
182
|
+
return prefixed.sort((a, b) => a.length - b.length)[0];
|
|
183
|
+
}
|
|
184
|
+
let best = null;
|
|
185
|
+
let bestD = 3;
|
|
186
|
+
for (const n of names) {
|
|
187
|
+
const d = distance(s, n);
|
|
188
|
+
if (d < bestD) { bestD = d; best = n; }
|
|
189
|
+
}
|
|
190
|
+
return best;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ── completion ───────────────────────────────────────────────────────────
|
|
194
|
+
//
|
|
195
|
+
// complete(words, ctx) → candidate lines, each "value" or "value\tdescription".
|
|
196
|
+
// `words` are the args after `claude-rpc`, the last one being the word under
|
|
197
|
+
// the cursor (possibly ''). A lone '__files__' line asks the shell to fall back
|
|
198
|
+
// to file-name completion. ctx.projects() lazily supplies project names.
|
|
199
|
+
|
|
200
|
+
export const FILES = '__files__';
|
|
201
|
+
|
|
202
|
+
function matching(pairs, cur) {
|
|
203
|
+
return pairs.filter(([v]) => v.startsWith(cur)).map(([v, d]) => (d ? `${v}\t${d}` : v));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function valueCandidates(kind, cur, ctx) {
|
|
207
|
+
if (kind === 'file') return [FILES];
|
|
208
|
+
if (kind === 'project') return matching((ctx.projects?.() || []).map((p) => [p, '']), cur);
|
|
209
|
+
if (kind === 'command') return matching(visibleCommands().map((c) => [c.name, c.summary]), cur);
|
|
210
|
+
if (Array.isArray(kind)) return matching(kind.map((v) => [v, '']), cur);
|
|
211
|
+
return [];
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function complete(words, ctx = {}) {
|
|
215
|
+
const w = words.length ? words : [''];
|
|
216
|
+
const cur = w[w.length - 1];
|
|
217
|
+
if (w.length === 1) return matching(visibleCommands().map((c) => [c.name, c.summary]), cur);
|
|
218
|
+
|
|
219
|
+
const cmd = findCommand(w[0]);
|
|
220
|
+
if (!cmd) return [];
|
|
221
|
+
const flags = cmd.flags || [];
|
|
222
|
+
const prev = w[w.length - 2];
|
|
223
|
+
|
|
224
|
+
// Value for the flag just typed (`--metric <Tab>`).
|
|
225
|
+
const flag = flags.find(([f]) => f === prev);
|
|
226
|
+
if (flag && flag[2] && !cur.startsWith('-')) return valueCandidates(flag[2], cur, ctx);
|
|
227
|
+
|
|
228
|
+
if (cur.startsWith('-')) {
|
|
229
|
+
const used = new Set(w.slice(1, -1));
|
|
230
|
+
return matching(flags.filter(([f]) => !used.has(f)).map(([f, d]) => [f, d]), cur);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// First positional → the command's sub-commands or argument values.
|
|
234
|
+
const positionals = w.slice(1, -1).filter((x, i, arr) => {
|
|
235
|
+
if (x.startsWith('-')) return false;
|
|
236
|
+
const before = i > 0 ? arr[i - 1] : w[0];
|
|
237
|
+
const f = flags.find(([name]) => name === before);
|
|
238
|
+
return !(f && f[2]);
|
|
239
|
+
});
|
|
240
|
+
if (positionals.length === 0) {
|
|
241
|
+
if (cmd.subs) return matching(cmd.subs, cur);
|
|
242
|
+
if (cmd.args) return valueCandidates(cmd.args, cur, ctx);
|
|
243
|
+
}
|
|
244
|
+
return [];
|
|
245
|
+
}
|
package/src/community.js
CHANGED
|
@@ -3,33 +3,48 @@
|
|
|
3
3
|
// pre-v0.7 config keep the explicit-opt-in flow via `claude-rpc community
|
|
4
4
|
// on`. Reads aggregate.json + a small cursor file to compute counter
|
|
5
5
|
// DELTAs (not absolute values — the cursor moves forward as we report),
|
|
6
|
-
// then POSTs to the configured worker endpoint.
|
|
6
|
+
// then POSTs to the configured worker endpoint. Also builds and sends the
|
|
7
|
+
// opt-in leaderboard profile (/profile) and the one-shot Claude Wrapped
|
|
8
|
+
// (/wrapped) payloads.
|
|
7
9
|
//
|
|
8
10
|
// Three guarantees this module owes the rest of the codebase:
|
|
9
11
|
//
|
|
10
12
|
// 1. Never throws. The daemon calls this from a setInterval and must
|
|
11
13
|
// not crash on a network burp or a malformed response. All failure
|
|
12
14
|
// modes resolve to `{ ok: false, reason }` and move on.
|
|
13
|
-
// 2. Never sends anything beyond the documented
|
|
14
|
-
//
|
|
15
|
-
//
|
|
15
|
+
// 2. Never sends anything beyond the documented payloads. Each build*Payload
|
|
16
|
+
// function is the complete schema for its endpoint, mirrored by the
|
|
17
|
+
// worker's validators. The anonymous /report carries only counter
|
|
18
|
+
// deltas, version and OS family. The opt-in /profile adds the chosen
|
|
19
|
+
// identity, lifetime totals and a per-day token/active-time series.
|
|
20
|
+
// /wrapped (sent only by `wrapped --publish`, after showing the user the
|
|
21
|
+
// payload) adds that year's stats, including privacy-filtered project
|
|
22
|
+
// names, the model mix, languages and the top file's basename. Never
|
|
23
|
+
// file paths, prompts or cwd.
|
|
16
24
|
// 3. Never advances the cursor on a failed flush. A 5xx today + a
|
|
17
25
|
// successful flush tomorrow still reports today's deltas.
|
|
18
26
|
//
|
|
19
27
|
// See worker/src/index.js for the receiving end.
|
|
20
28
|
|
|
21
|
-
import { readFileSync,
|
|
22
|
-
import { join
|
|
29
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
30
|
+
import { join } from 'node:path';
|
|
23
31
|
import { platform } from 'node:os';
|
|
24
|
-
import { AGGREGATE_PATH, STATE_DIR } from './paths.js';
|
|
32
|
+
import { AGGREGATE_PATH, DATA_DIR, STATE_DIR } from './paths.js';
|
|
25
33
|
import { VERSION } from './version.js';
|
|
26
34
|
import { profileIsPublishable } from './leaderboard.js';
|
|
27
35
|
import { projectNameIsPrivate } from './privacy.js';
|
|
28
36
|
import { cleanProjectName, dayKey } from './scanner.js';
|
|
29
37
|
import { HEATMAP_DAYS } from './heatmap.js';
|
|
30
38
|
import { humanModel } from './format.js';
|
|
39
|
+
import { adoptLegacyFile, writeFileAtomic } from './atomic-rename.js';
|
|
31
40
|
|
|
32
|
-
|
|
41
|
+
// How much of this install's lifetime has already been reported. It must
|
|
42
|
+
// survive reboots: the worker adds every delta blindly, so a lost cursor
|
|
43
|
+
// re-sends the whole lifetime and inflates the public counter. Through v1.5.2
|
|
44
|
+
// it lived in os.tmpdir() (LEGACY_CURSOR_PATH), which a reboot or temp purge
|
|
45
|
+
// wipes; ensureCursor / markCursorFresh move it here once.
|
|
46
|
+
export const CURSOR_PATH = join(DATA_DIR, 'community-cursor.json');
|
|
47
|
+
export const LEGACY_CURSOR_PATH = join(STATE_DIR, 'community-cursor.json');
|
|
33
48
|
|
|
34
49
|
export function readCursor(path = CURSOR_PATH) {
|
|
35
50
|
if (!existsSync(path)) return { sessions: 0, tokens: 0, ts: 0 };
|
|
@@ -39,8 +54,7 @@ export function readCursor(path = CURSOR_PATH) {
|
|
|
39
54
|
|
|
40
55
|
export function writeCursor(c, path = CURSOR_PATH) {
|
|
41
56
|
try {
|
|
42
|
-
|
|
43
|
-
writeFileSync(path, JSON.stringify(c, null, 2));
|
|
57
|
+
writeFileAtomic(path, JSON.stringify(c, null, 2));
|
|
44
58
|
} catch {
|
|
45
59
|
// Cursor write failure is recoverable — the next flush will resend
|
|
46
60
|
// the same delta, which the worker accepts (we accumulate at the
|
|
@@ -48,6 +62,45 @@ export function writeCursor(c, path = CURSOR_PATH) {
|
|
|
48
62
|
}
|
|
49
63
|
}
|
|
50
64
|
|
|
65
|
+
// A parsed cursor file, or null when it's missing or unreadable.
|
|
66
|
+
function loadCursorFile(path) {
|
|
67
|
+
try {
|
|
68
|
+
const c = JSON.parse(readFileSync(path, 'utf8'));
|
|
69
|
+
return c && typeof c === 'object' ? { sessions: 0, tokens: 0, ts: 0, ...c } : null;
|
|
70
|
+
} catch { return null; }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// A new identity has reported nothing yet: write an explicit zero cursor so
|
|
74
|
+
// its first flush sends the install's whole history. Called wherever an
|
|
75
|
+
// instanceId is minted (setup's seeded config, `community on`, `profile on`).
|
|
76
|
+
// Leaves an existing cursor alone (adopting a legacy one), so a reused machine
|
|
77
|
+
// only ever reports new growth. Returns true when it wrote the zero cursor.
|
|
78
|
+
export function markCursorFresh({ path = CURSOR_PATH, legacyPath = LEGACY_CURSOR_PATH } = {}) {
|
|
79
|
+
adoptLegacyFile(path, legacyPath);
|
|
80
|
+
if (existsSync(path)) return false;
|
|
81
|
+
writeCursor({ sessions: 0, tokens: 0, ts: 0 }, path);
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// The cursor flushCommunity diffs against, in order:
|
|
86
|
+
// 1. the cursor at `path` (the normal case);
|
|
87
|
+
// 2. the legacy tmpdir cursor, moved into `path` (first flush after upgrade);
|
|
88
|
+
// 3. neither (or an unreadable file): seed it from the current aggregate, so
|
|
89
|
+
// only growth from now on is reported. A missing cursor does NOT mean
|
|
90
|
+
// "never reported" — a new identity gets an explicit zero cursor from
|
|
91
|
+
// markCursorFresh — so landing here means an install from before the move
|
|
92
|
+
// whose tmp cursor was wiped. Re-sending its lifetime would double-count
|
|
93
|
+
// it on the public counter; seeding at worst skips history it never got
|
|
94
|
+
// to report, the much smaller error.
|
|
95
|
+
export function ensureCursor(aggregate, { path = CURSOR_PATH, legacyPath = LEGACY_CURSOR_PATH, now = Date.now() } = {}) {
|
|
96
|
+
adoptLegacyFile(path, legacyPath);
|
|
97
|
+
const existing = loadCursorFile(path);
|
|
98
|
+
if (existing) return existing;
|
|
99
|
+
const seeded = { sessions: aggregate?.sessions || 0, tokens: totalTokens(aggregate), ts: now, seeded: true };
|
|
100
|
+
writeCursor(seeded, path);
|
|
101
|
+
return seeded;
|
|
102
|
+
}
|
|
103
|
+
|
|
51
104
|
export function osFamily() {
|
|
52
105
|
const p = platform();
|
|
53
106
|
if (p === 'win32') return 'win32';
|
|
@@ -71,10 +124,7 @@ const MAX_REPORT_TOKENS = 5_000_000_000;
|
|
|
71
124
|
// here, add it there too.
|
|
72
125
|
export function buildPayload(aggregate, cursor, { instanceId, now = Date.now() }) {
|
|
73
126
|
const sessions = aggregate?.sessions || 0;
|
|
74
|
-
const tokens = (aggregate
|
|
75
|
-
+ (aggregate?.outputTokens || 0)
|
|
76
|
-
+ (aggregate?.cacheReadTokens || 0)
|
|
77
|
-
+ (aggregate?.cacheWriteTokens || 0);
|
|
127
|
+
const tokens = totalTokens(aggregate);
|
|
78
128
|
return {
|
|
79
129
|
instanceId,
|
|
80
130
|
sessionsDelta: Math.min(MAX_REPORT_SESSIONS, Math.max(0, sessions - (cursor.sessions || 0))),
|
|
@@ -85,13 +135,6 @@ export function buildPayload(aggregate, cursor, { instanceId, now = Date.now() }
|
|
|
85
135
|
};
|
|
86
136
|
}
|
|
87
137
|
|
|
88
|
-
// ── leaderboard profile flush ──────────────────────────────────────────
|
|
89
|
-
// Publishes the opt-in public profile (identity + lifetime totals) to the
|
|
90
|
-
// worker's /profile endpoint. Reuses the anonymous community instanceId as the
|
|
91
|
-
// profile's row key. Unlike flushCommunity this is cursor-free and idempotent —
|
|
92
|
-
// it POSTs absolute totals, so the worker SETs (never accumulates) and a resend
|
|
93
|
-
// is a no-op. Same safety guarantees: never throws, sends only documented fields.
|
|
94
|
-
|
|
95
138
|
function totalTokens(aggregate) {
|
|
96
139
|
return (aggregate?.inputTokens || 0)
|
|
97
140
|
+ (aggregate?.outputTokens || 0)
|
|
@@ -99,11 +142,13 @@ function totalTokens(aggregate) {
|
|
|
99
142
|
+ (aggregate?.cacheWriteTokens || 0);
|
|
100
143
|
}
|
|
101
144
|
|
|
102
|
-
//
|
|
103
|
-
//
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
//
|
|
145
|
+
// ── leaderboard profile flush ──────────────────────────────────────────
|
|
146
|
+
// Publishes the opt-in public profile (identity + lifetime totals) to the
|
|
147
|
+
// worker's /profile endpoint. Reuses the anonymous community instanceId as the
|
|
148
|
+
// profile's row key. Unlike flushCommunity this is cursor-free and idempotent —
|
|
149
|
+
// it POSTs absolute totals, so the worker SETs (never accumulates) and a resend
|
|
150
|
+
// is a no-op. Same safety guarantees: never throws, sends only documented fields.
|
|
151
|
+
|
|
107
152
|
// The last year of per-day tokens + active minutes, for the live heatmap
|
|
108
153
|
// (/heatmap/<h>.svg, /stats/<h>.svg). Keyed by LOCAL date like aggregate.byDay;
|
|
109
154
|
// oldest → newest with leading empty days trimmed. Only day totals — nothing
|
|
@@ -126,6 +171,11 @@ export function buildDailySeries(aggregate, now = Date.now(), days = HEATMAP_DAY
|
|
|
126
171
|
return { end, tokens: tokens.slice(first), activeMin: activeMin.slice(first) };
|
|
127
172
|
}
|
|
128
173
|
|
|
174
|
+
// A profile reports ABSOLUTE lifetime totals (not deltas). It's per-user and
|
|
175
|
+
// keyed by the instanceId, so the server just stores the latest value — no
|
|
176
|
+
// cursor, no double-count risk, and the board matches your real aggregate
|
|
177
|
+
// exactly. (Deltas were wrong here: the first publish carried the entire
|
|
178
|
+
// lifetime total, which blew past the per-report caps for any established user.)
|
|
129
179
|
export function buildProfilePayload(aggregate, profileCfg, { instanceId, now = Date.now() }) {
|
|
130
180
|
return {
|
|
131
181
|
instanceId,
|
|
@@ -264,23 +314,31 @@ export function buildWrappedPayload(aggregate, config, { instanceId, year, now =
|
|
|
264
314
|
};
|
|
265
315
|
}
|
|
266
316
|
|
|
267
|
-
//
|
|
268
|
-
//
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
const url = community.endpoint.replace(/\/+$/, '') + '/wrapped';
|
|
273
|
-
let res;
|
|
317
|
+
// POST a JSON payload to `<endpoint><route>`. Resolves { res }, or { fail }:
|
|
318
|
+
// the { ok:false, reason:'network' } result callers return as-is. Bare fetch
|
|
319
|
+
// never times out; a hung peer would wedge the 30-min flush loop.
|
|
320
|
+
async function postJson(fetchImpl, endpoint, route, payload) {
|
|
321
|
+
const url = endpoint.replace(/\/+$/, '') + route;
|
|
274
322
|
try {
|
|
275
|
-
res = await fetchImpl(url, {
|
|
323
|
+
const res = await fetchImpl(url, {
|
|
276
324
|
method: 'POST',
|
|
277
325
|
headers: { 'Content-Type': 'application/json' },
|
|
278
326
|
body: JSON.stringify(payload),
|
|
279
327
|
signal: AbortSignal.timeout(10_000),
|
|
280
328
|
});
|
|
329
|
+
return { res };
|
|
281
330
|
} catch (e) {
|
|
282
|
-
return { ok: false, reason: 'network', error: e.message };
|
|
331
|
+
return { fail: { ok: false, reason: 'network', error: e.message } };
|
|
283
332
|
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// One-shot POST of a built wrapped payload. Mirrors flushProfile's error
|
|
336
|
+
// contract: never throws, returns { ok, reason?, url? }.
|
|
337
|
+
export async function publishWrapped(cfg, payload, { fetchImpl = globalThis.fetch } = {}) {
|
|
338
|
+
const community = cfg?.community || {};
|
|
339
|
+
if (!community.endpoint) return { ok: false, reason: 'no-endpoint' };
|
|
340
|
+
const { res, fail } = await postJson(fetchImpl, community.endpoint, '/wrapped', payload);
|
|
341
|
+
if (fail) return fail;
|
|
284
342
|
let body = null;
|
|
285
343
|
try { body = await res.json(); } catch { /* non-JSON error body */ }
|
|
286
344
|
if (!res.ok) {
|
|
@@ -308,18 +366,8 @@ export async function flushProfile(cfg, {
|
|
|
308
366
|
catch { return { ok: false, reason: 'unreadable-aggregate' }; }
|
|
309
367
|
|
|
310
368
|
const payload = buildProfilePayload(aggregate, profile, { instanceId });
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
try {
|
|
314
|
-
res = await fetchImpl(url, {
|
|
315
|
-
method: 'POST',
|
|
316
|
-
headers: { 'Content-Type': 'application/json' },
|
|
317
|
-
body: JSON.stringify(payload),
|
|
318
|
-
signal: AbortSignal.timeout(10_000), // bare fetch never times out; a hung peer would wedge the 30-min flush loop
|
|
319
|
-
});
|
|
320
|
-
} catch (e) {
|
|
321
|
-
return { ok: false, reason: 'network', error: e.message };
|
|
322
|
-
}
|
|
369
|
+
const { res, fail } = await postJson(fetchImpl, community.endpoint, '/profile', payload);
|
|
370
|
+
if (fail) return fail;
|
|
323
371
|
if (!res.ok) {
|
|
324
372
|
if (res.status === 429) return { ok: false, reason: 'rate-limited' };
|
|
325
373
|
return { ok: false, reason: `http-${res.status}` };
|
|
@@ -333,6 +381,9 @@ export async function flushProfile(cfg, {
|
|
|
333
381
|
export async function flushCommunity(cfg, {
|
|
334
382
|
aggregatePath = AGGREGATE_PATH,
|
|
335
383
|
cursorPath = CURSOR_PATH,
|
|
384
|
+
// Only the real cursor migrates from its old tmpdir home; a caller-supplied
|
|
385
|
+
// path (tests) never touches it.
|
|
386
|
+
legacyCursorPath = cursorPath === CURSOR_PATH ? LEGACY_CURSOR_PATH : null,
|
|
336
387
|
fetchImpl = globalThis.fetch,
|
|
337
388
|
} = {}) {
|
|
338
389
|
const community = cfg?.community || {};
|
|
@@ -345,24 +396,14 @@ export async function flushCommunity(cfg, {
|
|
|
345
396
|
try { aggregate = JSON.parse(readFileSync(aggregatePath, 'utf8')); }
|
|
346
397
|
catch { return { ok: false, reason: 'unreadable-aggregate' }; }
|
|
347
398
|
|
|
348
|
-
const cursor =
|
|
399
|
+
const cursor = ensureCursor(aggregate, { path: cursorPath, legacyPath: legacyCursorPath });
|
|
349
400
|
const payload = buildPayload(aggregate, cursor, { instanceId: community.instanceId });
|
|
350
401
|
if (payload.sessionsDelta === 0 && payload.tokensDelta === 0) {
|
|
351
402
|
return { ok: true, reason: 'no-delta' };
|
|
352
403
|
}
|
|
353
404
|
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
try {
|
|
357
|
-
res = await fetchImpl(url, {
|
|
358
|
-
method: 'POST',
|
|
359
|
-
headers: { 'Content-Type': 'application/json' },
|
|
360
|
-
body: JSON.stringify(payload),
|
|
361
|
-
signal: AbortSignal.timeout(10_000), // bare fetch never times out; a hung peer would wedge the 30-min flush loop
|
|
362
|
-
});
|
|
363
|
-
} catch (e) {
|
|
364
|
-
return { ok: false, reason: 'network', error: e.message };
|
|
365
|
-
}
|
|
405
|
+
const { res, fail } = await postJson(fetchImpl, community.endpoint, '/report', payload);
|
|
406
|
+
if (fail) return fail;
|
|
366
407
|
if (!res.ok) {
|
|
367
408
|
// 429 is rate-limit — not actually a failure, just "come back later".
|
|
368
409
|
if (res.status === 429) return { ok: false, reason: 'rate-limited' };
|