savemytokens 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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +164 -0
  3. package/dist/adapters/claude-code/index.js +130 -0
  4. package/dist/adapters/claude-code/merge.js +90 -0
  5. package/dist/adapters/claude-code/parse.js +642 -0
  6. package/dist/adapters/claude-code/provider.js +105 -0
  7. package/dist/adapters/codex/index.js +74 -0
  8. package/dist/adapters/codex/parse.js +389 -0
  9. package/dist/adapters/codex/provider.js +171 -0
  10. package/dist/adapters/index.js +10 -0
  11. package/dist/adapters/pending.js +29 -0
  12. package/dist/adapters/types.js +1 -0
  13. package/dist/analyze/aggregate.js +180 -0
  14. package/dist/analyze/combine.js +11 -0
  15. package/dist/analyze/detectors.js +244 -0
  16. package/dist/analyze/index.js +29 -0
  17. package/dist/analyze/score.js +20 -0
  18. package/dist/cli-options.js +149 -0
  19. package/dist/cli.js +141 -0
  20. package/dist/collect.js +62 -0
  21. package/dist/commands/audit.js +74 -0
  22. package/dist/commands/control.js +654 -0
  23. package/dist/commands/hud.js +71 -0
  24. package/dist/commands/install.js +369 -0
  25. package/dist/commands/policy.js +93 -0
  26. package/dist/commands/privacy.js +28 -0
  27. package/dist/commands/set.js +83 -0
  28. package/dist/commands/theme.js +136 -0
  29. package/dist/commands/watch.js +135 -0
  30. package/dist/core/cost.js +24 -0
  31. package/dist/core/hash.js +0 -0
  32. package/dist/core/pricing.js +63 -0
  33. package/dist/core/resource.js +1 -0
  34. package/dist/core/tokens.js +32 -0
  35. package/dist/core/types.js +1 -0
  36. package/dist/hooks/nudge.js +111 -0
  37. package/dist/hooks/rules.js +14 -0
  38. package/dist/privacy/payload.js +22 -0
  39. package/dist/report/graph.js +162 -0
  40. package/dist/report/graphs.js +61 -0
  41. package/dist/report/render.js +183 -0
  42. package/dist/report/schedule.js +143 -0
  43. package/dist/report/settings.js +237 -0
  44. package/dist/report/views.js +418 -0
  45. package/dist/runtime/hook.mjs +234 -0
  46. package/dist/runtime/kernel.mjs +1472 -0
  47. package/dist/runtime/statusline.mjs +243 -0
  48. package/dist/scheduler/keys.js +112 -0
  49. package/dist/scheduler/plan.js +287 -0
  50. package/dist/storage/cache.js +38 -0
  51. package/dist/storage/paths.js +29 -0
  52. package/dist/storage/store.js +48 -0
  53. package/dist/util/ansi.js +35 -0
  54. package/dist/util/fmt.js +76 -0
  55. package/package.json +51 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Offbeatport
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,164 @@
1
+ <div align="center">
2
+
3
+ <img src="https://raw.githubusercontent.com/offbeatport/savemytokens/main/assets/logo.svg" alt="" width="64" height="64">
4
+
5
+ # SaveMyTokens
6
+
7
+ ### Decide which project gets your Claude allowance.
8
+
9
+ <a href="https://www.npmjs.com/package/savemytokens"><img src="https://img.shields.io/npm/v/savemytokens?style=flat-square&color=1a7f37&label=npm" alt="npm version"></a>
10
+ <img src="https://img.shields.io/badge/dependencies-0-1a7f37?style=flat-square" alt="zero dependencies">
11
+ <img src="https://img.shields.io/badge/node-%E2%89%A5%2018.17-2b7489?style=flat-square" alt="node 18.17+">
12
+ <img src="https://img.shields.io/badge/local%20only-no%20network%20call-6e40c9?style=flat-square" alt="local only">
13
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-24292f?style=flat-square" alt="MIT"></a>
14
+
15
+ <br><br>
16
+
17
+ <img src="https://raw.githubusercontent.com/offbeatport/savemytokens/main/assets/screenshot.svg" alt="The SaveMyTokens control centre: three live projects sharing one 5-hour window, each row showing its allocation, how much of that allocation it has spent, its priority and its last prompt." width="880">
18
+
19
+ <br>
20
+
21
+ <img src="https://raw.githubusercontent.com/offbeatport/savemytokens/main/assets/statusline.svg" alt="A Claude Code status line: a braille bar, then 21%/50%, 5h 42%, in 3h52." width="520">
22
+
23
+ </div>
24
+
25
+ <br>
26
+
27
+ ## Get started
28
+
29
+ ```sh
30
+ npx savemytokens
31
+ ```
32
+
33
+ That is the whole install. It opens the control centre and, on the first run, offers to add four
34
+ hooks and a status line to Claude Code's `settings.json`, backing the file up first. Prefer it
35
+ installed once rather than fetched each time? `npm i -g savemytokens`, then the command is just
36
+ `savemytokens`.
37
+
38
+ **Say yes.** The status line is the only place Anthropic publishes your 5h and weekly usage, and it
39
+ is what proves a session is still open, so nothing is live without it. Changed your mind?
40
+ `npx savemytokens uninstall` takes every entry back out.
41
+
42
+ <br>
43
+
44
+ | | |
45
+ | :-- | :-- |
46
+ | **The real numbers** | Your 5-hour and weekly usage exactly as Anthropic publishes it. Never an invented *"% remaining"*. |
47
+ | **Two lists you control** | **ACTIVE** is what shares your window; **RECENT** is everything else it has seen. A project joins ACTIVE on its own when you open Claude Code there and stays after you close it, so a target survives the session. `a` moves one up, `x` sends it back. |
48
+ | **Claude working to it** | As a session eats into its slice it is told to narrow scope and finish, and to write down whatever it drops. That comes back the next time you work on the project. |
49
+ | **Unused capacity returned** | A project with nothing running lends its share to the rest and takes it back when you return. Mark one done and what it did not spend goes to the others immediately. |
50
+ | **In your status line** | `21%/50% · 5h 42% · in 3h52`. How much of your share you have spent, where the window is, when it comes back. Pick a shape, or arrange the pieces yourself. |
51
+
52
+ <br>
53
+
54
+ ## Commands
55
+
56
+ | | |
57
+ | :-- | :-- |
58
+ | `npx savemytokens` | the control centre |
59
+ | `npx savemytokens status` | one plain-text snapshot · `--json` for a script |
60
+ | `npx savemytokens share buydiff 40` | pin a project's allocation |
61
+ | `npx savemytokens priority buydiff high` | who gets spare capacity first |
62
+ | `npx savemytokens release buydiff` | hand its unused share back |
63
+ | `npx savemytokens policy strict` | wind down earlier when it gets tight |
64
+ | `npx savemytokens hud` | pick a status line, previewed on your numbers |
65
+ | `npx savemytokens theme` | eighteen themes, or write your own |
66
+ | `npx savemytokens defer` | work a session pushed to next time |
67
+ | `npx savemytokens audit` | what your last 7 days wasted |
68
+ | `npx savemytokens uninstall` | remove every trace · `--purge` drops the data too |
69
+
70
+ Inside the control centre, `?` lists every key. The ones worth knowing: `←→` moves an allocation,
71
+ `space` moves a project up a level and `x` moves it down, so a project you never want to see goes
72
+ ACTIVE to RECENT to hidden. `p` cycles priority, `⏎` opens a project's sessions, `s` opens settings.
73
+
74
+ ## Where the numbers come from
75
+
76
+ Three different kinds of number sit on that screen, and it matters which is which.
77
+
78
+ | | |
79
+ | :-- | :-- |
80
+ | **5h and 7d** | Anthropic's own figures. Claude Code publishes them to the status line, so SaveMyTokens installs one, reads them, and stores each reading with its timestamp. Nothing is estimated. |
81
+ | **share** | Measured from the transcripts already on your disk, token by token, including subagents. Exact, and independent of anything Anthropic reports. |
82
+ | **used, allocation** | Anthropic's percentage, split by that measured share. The total is theirs. The division between projects is ours, and it is the only inferred number on the screen. |
83
+
84
+ Usage from another machine, or from claude.ai, is invisible to a local tool. When the window moves
85
+ while none of your projects had a turn, that is reported on its own line rather than folded silently
86
+ into a project's figure.
87
+
88
+ ## How it works
89
+
90
+ `install` writes three scripts to `~/.savemytokens/hooks`, adds four hook entries and a status line
91
+ to Claude Code's `settings.json`, and backs that file up first. There is no daemon. The hooks meter
92
+ their own session as it runs, the status line captures the published window every ten seconds, and
93
+ the control centre reads what they leave behind. Transcripts are read incrementally, from a stored
94
+ byte offset per file, so a prompt costs milliseconds however long the session has run.
95
+
96
+ Nothing outside `~/.savemytokens` and Claude Code's own settings is touched. `uninstall` puts it
97
+ back, and restores a status line of your own if it wrapped one.
98
+
99
+ ## Requirements
100
+
101
+ Node 18.17 or newer, and Claude Code 2.1 or newer. The published 5h and 7d figures come with a Claude
102
+ subscription. On an API key or through the Console, Anthropic reports no window; SaveMyTokens says so
103
+ rather than guessing, and allocation and advice still work from measured usage alone.
104
+
105
+ <details>
106
+ <summary><b>Writing your own theme</b></summary>
107
+
108
+ <br>
109
+
110
+ ```sh
111
+ npx savemytokens theme new mine nord # copy one to start from
112
+ npx savemytokens theme check mine # is it readable?
113
+ npx savemytokens theme tui mine # use it
114
+ ```
115
+
116
+ `~/.savemytokens/themes/mine.json`. Everything you leave out is inherited:
117
+
118
+ ```json
119
+ {
120
+ "colors": { "fg": "#eceff4", "dim": "#7b88a1", "accent": "#88c0d0",
121
+ "ok": "#a3be8c", "warn": "#ebcb8b", "danger": "#e0707c", "track": "#434c5e" },
122
+ "tui": { "cursor": "❯", "pin": "★", "active": "●", "done": "✓",
123
+ "fill": "▰", "empty": "▱", "over": "▶", "meter": "▰", "track": "▱" },
124
+ "glyphs": { "sep": "·" }
125
+ }
126
+ ```
127
+
128
+ `theme check` measures every colour against the terminal and fails anything unreadable, against the same
129
+ bar the built-in themes have to clear.
130
+
131
+ </details>
132
+
133
+ <details>
134
+ <summary><b>What the hooks read and write</b></summary>
135
+
136
+ <br>
137
+
138
+ | | |
139
+ | :-- | :-- |
140
+ | **reads** | `~/.claude/projects/**/*.jsonl`, the transcripts Claude Code already writes, from a stored byte offset, and the status line payload Claude Code hands it on stdin. |
141
+ | **writes** | `~/.savemytokens` only: meter offsets, per-project settings, quota readings, deferred notes. |
142
+ | **injects** | A line of context on `SessionStart` and `UserPromptSubmit` when a project is over its share. Nothing else. |
143
+ | **never** | Makes a network call, blocks a prompt, or exits non-zero. |
144
+
145
+ </details>
146
+
147
+ ## What it will not do
148
+
149
+ - **It advises; it does not enforce.** The hooks inject text, and a model does not hold a budget the
150
+ way a scheduler holds a lock. A session that ignores the advice keeps running. Hard caps are the
151
+ next step, and will ship only after a period of logging what *would* have been blocked.
152
+ - **It does not predict a lockout.** Anthropic publishes a percentage and a reset time. Anything
153
+ beyond those two facts would be a guess dressed up as a number.
154
+ - **It cannot see usage it did not measure.** Another machine, claude.ai, or work done before you
155
+ installed it shows up as unattributed window, labelled as such.
156
+ - **It makes no network call.** No account, no telemetry, no daemon. `savemytokens privacy` prints
157
+ every file it reads and writes.
158
+
159
+ <div align="center">
160
+ <br>
161
+ <sub>No daemon · no account · nothing leaves your machine · MIT</sub>
162
+ <br>
163
+ <sub>Built by <a href="https://offbeatport.com">Offbeatport</a> · questions and bugs: <a href="mailto:hello@offbeatport.com">hello@offbeatport.com</a></sub>
164
+ </div>
@@ -0,0 +1,130 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { mergeSidechain } from "./merge.js";
5
+ import { parseClaudeSession } from "./parse.js";
6
+ const CLAUDE_HOME = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
7
+ const DATA_DIR = path.join(CLAUDE_HOME, "projects");
8
+ const MAX_SUBAGENT_DEPTH = 4;
9
+ export function encodeProject(dir) {
10
+ return dir.replace(/[^a-zA-Z0-9]/g, "-");
11
+ }
12
+ function collectNested(dir, depth, out) {
13
+ if (depth > MAX_SUBAGENT_DEPTH)
14
+ return;
15
+ let entries;
16
+ try {
17
+ entries = fs.readdirSync(dir, { withFileTypes: true });
18
+ }
19
+ catch {
20
+ return;
21
+ }
22
+ for (const entry of entries) {
23
+ const full = path.join(dir, entry.name);
24
+ if (entry.isDirectory())
25
+ collectNested(full, depth + 1, out);
26
+ else if (entry.name.endsWith(".jsonl"))
27
+ out.push(full);
28
+ }
29
+ }
30
+ function scanProject(projectDir, projectKey, options, out) {
31
+ let entries;
32
+ try {
33
+ entries = fs.readdirSync(projectDir, { withFileTypes: true });
34
+ }
35
+ catch {
36
+ return;
37
+ }
38
+ const directories = new Set(entries.filter((e) => e.isDirectory()).map((e) => e.name));
39
+ for (const entry of entries) {
40
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl"))
41
+ continue;
42
+ const main = path.join(projectDir, entry.name);
43
+ let stat;
44
+ try {
45
+ stat = fs.statSync(main);
46
+ }
47
+ catch {
48
+ continue;
49
+ }
50
+ if (stat.size === 0)
51
+ continue;
52
+ const sessionId = entry.name.slice(0, -".jsonl".length);
53
+ const extras = [];
54
+ if (directories.has(sessionId))
55
+ collectNested(path.join(projectDir, sessionId), 1, extras);
56
+ let size = stat.size;
57
+ let mtimeMs = stat.mtimeMs;
58
+ for (const extra of extras) {
59
+ try {
60
+ const extraStat = fs.statSync(extra);
61
+ size += extraStat.size;
62
+ if (extraStat.mtimeMs > mtimeMs)
63
+ mtimeMs = extraStat.mtimeMs;
64
+ }
65
+ catch {
66
+ continue;
67
+ }
68
+ }
69
+ if (mtimeMs < options.since)
70
+ continue;
71
+ out.push({ adapter: "claude-code", file: main, size, mtimeMs, projectKey, extraFiles: extras });
72
+ }
73
+ }
74
+ export const claudeCodeAdapter = {
75
+ id: "claude-code",
76
+ label: "Claude Code",
77
+ supported: true,
78
+ dataDir: DATA_DIR,
79
+ detect() {
80
+ try {
81
+ return fs.statSync(DATA_DIR).isDirectory();
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ },
87
+ discover(options) {
88
+ const refs = [];
89
+ let projects;
90
+ try {
91
+ projects = fs.readdirSync(DATA_DIR, { withFileTypes: true });
92
+ }
93
+ catch {
94
+ return refs;
95
+ }
96
+ const wanted = options.project ? encodeProject(options.project) : null;
97
+ for (const project of projects) {
98
+ if (!project.isDirectory())
99
+ continue;
100
+ if (wanted && project.name !== wanted)
101
+ continue;
102
+ scanProject(path.join(DATA_DIR, project.name), project.name, options, refs);
103
+ }
104
+ return refs;
105
+ },
106
+ async parse(ref) {
107
+ let evidence = null;
108
+ try {
109
+ evidence = await parseClaudeSession(ref.file, fs.statSync(ref.file));
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ if (!evidence)
115
+ return null;
116
+ for (const extra of ref.extraFiles ?? []) {
117
+ try {
118
+ const sub = await parseClaudeSession(extra, fs.statSync(extra));
119
+ if (sub)
120
+ mergeSidechain(evidence, sub);
121
+ }
122
+ catch {
123
+ continue;
124
+ }
125
+ }
126
+ evidence.sourceSize = ref.size;
127
+ evidence.sourceMtimeMs = ref.mtimeMs;
128
+ return evidence;
129
+ },
130
+ };
@@ -0,0 +1,90 @@
1
+ import { WEIGHTS, addUsage, estimateTokens } from "../../core/tokens.js";
2
+ const MAX_BUCKETS = 24;
3
+ function mergeBuckets(base, extra, keyOf, combine, weightOf) {
4
+ const map = new Map();
5
+ for (const item of [...base, ...extra]) {
6
+ const key = keyOf(item);
7
+ const existing = map.get(key);
8
+ map.set(key, existing ? combine(existing, item) : item);
9
+ }
10
+ return [...map.values()].sort((a, b) => weightOf(b) - weightOf(a)).slice(0, MAX_BUCKETS);
11
+ }
12
+ export function mergeSidechain(base, extra) {
13
+ addUsage(base.usage, extra.usage);
14
+ base.weighted += extra.weighted;
15
+ base.turns += extra.turns;
16
+ base.toolCalls += extra.toolCalls;
17
+ base.toolErrors += extra.toolErrors;
18
+ base.apiErrors += extra.apiErrors;
19
+ base.interruptions += extra.interruptions;
20
+ base.searchChars += extra.searchChars;
21
+ base.bloatTurns += extra.bloatTurns;
22
+ base.bloatTokens += extra.bloatTokens;
23
+ base.bloatWeighted += extra.bloatWeighted;
24
+ base.compactions += extra.compactions;
25
+ base.sidechainTurns += extra.turns;
26
+ base.sidechainWeighted += extra.weighted;
27
+ base.sourceSize += extra.sourceSize;
28
+ if (extra.sourceMtimeMs > base.sourceMtimeMs)
29
+ base.sourceMtimeMs = extra.sourceMtimeMs;
30
+ if (extra.peakContext > base.peakContext)
31
+ base.peakContext = extra.peakContext;
32
+ if (extra.startedAt && (!base.startedAt || extra.startedAt < base.startedAt))
33
+ base.startedAt = extra.startedAt;
34
+ if (extra.endedAt > base.endedAt)
35
+ base.endedAt = extra.endedAt;
36
+ for (const model of extra.models) {
37
+ const existing = base.models.find((m) => m.model === model.model);
38
+ if (!existing) {
39
+ base.models.push(model);
40
+ continue;
41
+ }
42
+ existing.turns += model.turns;
43
+ addUsage(existing.usage, model.usage);
44
+ existing.weighted += model.weighted;
45
+ existing.trivialTurns += model.trivialTurns;
46
+ existing.trivialWeighted += model.trivialWeighted;
47
+ }
48
+ base.reads = mergeBuckets(base.reads, extra.reads, (r) => r.path, (a, b) => {
49
+ const sameContent = a.signature !== "" && a.signature === b.signature;
50
+ const firstCopyChars = b.chars - b.redundantChars;
51
+ return {
52
+ path: a.path,
53
+ signature: a.signature,
54
+ reads: a.reads + b.reads,
55
+ chars: a.chars + b.chars,
56
+ redundantReads: a.redundantReads + b.redundantReads + (sameContent ? b.reads - b.redundantReads : 0),
57
+ redundantChars: a.redundantChars + b.redundantChars + (sameContent ? firstCopyChars : 0),
58
+ redundantWeighted: a.redundantWeighted +
59
+ b.redundantWeighted +
60
+ (sameContent ? estimateTokens(firstCopyChars) * WEIGHTS.cacheWrite : 0),
61
+ };
62
+ }, (r) => r.redundantWeighted);
63
+ base.outputs = mergeBuckets(base.outputs, extra.outputs, (o) => o.label, (a, b) => ({
64
+ label: a.label,
65
+ tool: a.tool,
66
+ calls: a.calls + b.calls,
67
+ chars: a.chars + b.chars,
68
+ maxChars: Math.max(a.maxChars, b.maxChars),
69
+ excessChars: a.excessChars + b.excessChars,
70
+ excessWeighted: a.excessWeighted + b.excessWeighted,
71
+ }), (o) => o.excessWeighted);
72
+ base.hooks = mergeBuckets(base.hooks, extra.hooks, (h) => h.name, (a, b) => ({
73
+ name: a.name,
74
+ events: a.events + b.events,
75
+ chars: a.chars + b.chars,
76
+ weighted: a.weighted + b.weighted,
77
+ sample: a.sample || b.sample,
78
+ command: a.command || b.command,
79
+ }), (h) => h.weighted);
80
+ base.writes = mergeBuckets(base.writes, extra.writes, (w) => w.path, (a, b) => ({
81
+ path: a.path,
82
+ writes: a.writes + b.writes,
83
+ edits: a.edits + b.edits,
84
+ rewrittenChars: a.rewrittenChars + b.rewrittenChars,
85
+ rewrittenWeighted: a.rewrittenWeighted + b.rewrittenWeighted,
86
+ }), (w) => w.rewrittenWeighted);
87
+ base.failures = mergeBuckets(base.failures, extra.failures, (f) => f.label, (a, b) => ({ label: a.label, tool: a.tool, failures: a.failures + b.failures, chars: a.chars + b.chars, weighted: a.weighted + b.weighted }), (f) => f.weighted);
88
+ base.attachments = mergeBuckets(base.attachments, extra.attachments, (a) => a.type, (a, b) => ({ type: a.type, events: a.events + b.events, chars: a.chars + b.chars }), (a) => a.chars);
89
+ return base;
90
+ }