@frugalhq/frugal 0.0.0 → 0.1.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.
@@ -0,0 +1,122 @@
1
+ import { priceFor } from "./config.js";
2
+ import { applySessionTotal, loadLedger, saveLedger, totals } from "./spend.js";
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ import { accumulateCost, contextTokens, emptyCostState, lastContextTokens } from "./transcript.js";
6
+ /** The session transcript plus any subagent transcripts Claude Code wrote next to it. */
7
+ export function transcriptFiles(transcript, session) {
8
+ const files = [transcript];
9
+ const subDir = path.join(path.dirname(transcript), session, "subagents");
10
+ try {
11
+ for (const n of fs.readdirSync(subDir))
12
+ if (n.endsWith(".jsonl"))
13
+ files.push(path.join(subDir, n));
14
+ }
15
+ catch {
16
+ // no subagents
17
+ }
18
+ return files;
19
+ }
20
+ import { faultPoint, num, obj, str } from "./io.js";
21
+ const SESSION_RE = /^[A-Za-z0-9_-]{1,128}$/;
22
+ export function money(n) {
23
+ if (n >= 100)
24
+ return `$${Math.round(n)}`;
25
+ return `$${n.toFixed(2)}`;
26
+ }
27
+ export function ktok(n) {
28
+ if (n >= 1_000_000)
29
+ return `${(n / 1_000_000).toFixed(1)}M`;
30
+ if (n >= 1000)
31
+ return `${Math.round(n / 1000)}k`;
32
+ return String(n);
33
+ }
34
+ function color(pct, s, useColor) {
35
+ if (!useColor)
36
+ return s;
37
+ if (pct >= 90)
38
+ return `\u001b[31m${s}\u001b[0m`;
39
+ if (pct >= 70)
40
+ return `\u001b[33m${s}\u001b[0m`;
41
+ return s;
42
+ }
43
+ export function contextFromInput(input) {
44
+ const cw = obj(input.context_window);
45
+ const cu = obj(cw?.current_usage);
46
+ if (cu) {
47
+ const u = {
48
+ input: num(cu.input_tokens) ?? 0,
49
+ output: 0,
50
+ cacheRead: num(cu.cache_read_input_tokens) ?? 0,
51
+ cacheWrite: num(cu.cache_creation_input_tokens) ?? 0
52
+ };
53
+ const t = contextTokens(u);
54
+ if (t > 0)
55
+ return t;
56
+ }
57
+ const pct = num(cw?.used_percentage);
58
+ const size = num(cw?.context_window_size);
59
+ if (pct !== undefined && size)
60
+ return Math.round((pct / 100) * size);
61
+ return undefined;
62
+ }
63
+ export function priceUsage(cfg) {
64
+ return (model, u) => {
65
+ const p = priceFor(cfg, model);
66
+ return ((u.input * p.inputPerMTok + u.output * p.outputPerMTok + u.cacheRead * p.cacheReadPerMTok + u.cacheWrite * p.cacheWritePerMTok) /
67
+ 1_000_000);
68
+ };
69
+ }
70
+ export function renderStatus(input, cfg, now = Date.now(), useColor = true) {
71
+ faultPoint("statusline");
72
+ const session = str(input.session_id);
73
+ const transcript = str(input.transcript_path);
74
+ const ledger = loadLedger();
75
+ let costKnown = false;
76
+ if (session && SESSION_RE.test(session)) {
77
+ const costField = num(obj(input.cost)?.total_cost_usd);
78
+ if (costField !== undefined && cfg.costSource !== "transcript") {
79
+ applySessionTotal(ledger, session, costField, now);
80
+ costKnown = true;
81
+ }
82
+ else if (transcript && cfg.costSource !== "statusline") {
83
+ // Main transcript plus subagent transcripts (<session>/subagents/*.jsonl): subagents cost money too.
84
+ const prevStates = ledger.sessions[session]?.transcripts ?? {};
85
+ const nextStates = {};
86
+ let total = 0;
87
+ let tokenDelta = 0;
88
+ for (const f of transcriptFiles(transcript, session)) {
89
+ const key = path.basename(f);
90
+ const prev = prevStates[key] ?? emptyCostState();
91
+ const next = accumulateCost(f, prev, priceUsage(cfg));
92
+ nextStates[key] = next;
93
+ total += next.total;
94
+ tokenDelta += next.tokens - prev.tokens;
95
+ }
96
+ applySessionTotal(ledger, session, total, now, tokenDelta);
97
+ ledger.sessions[session].transcripts = nextStates;
98
+ costKnown = total > 0;
99
+ }
100
+ saveLedger(ledger, now);
101
+ }
102
+ const t = totals(ledger, now);
103
+ const parts = [];
104
+ if (costKnown || t.month > 0) {
105
+ parts.push(`${money(t.today)} today`);
106
+ if (cfg.monthlyCap > 0) {
107
+ const pct = Math.round((t.month / cfg.monthlyCap) * 100);
108
+ parts.push(color(pct, `${money(t.month)}/${money(cfg.monthlyCap)} month (${pct}%)`, useColor));
109
+ }
110
+ else {
111
+ parts.push(`${money(t.month)} month`);
112
+ }
113
+ }
114
+ const ctx = contextFromInput(input) ?? (transcript ? lastContextTokens(transcript) : undefined);
115
+ if (ctx !== undefined) {
116
+ const s = `ctx ${ktok(ctx)}`;
117
+ parts.push(ctx >= cfg.contextWarnTokens ? color(95, s, useColor) : s);
118
+ }
119
+ if (parts.length === 0)
120
+ return "frugal ▸ waiting for usage";
121
+ return `frugal ▸ ${parts.join(" · ")}`;
122
+ }
@@ -0,0 +1,251 @@
1
+ // Defensive parser for Claude Code session transcripts (JSONL).
2
+ // The format is internal to Claude Code and changes between versions, so every
3
+ // field is optional here and unknown lines are skipped. Shapes observed on 2.1.x:
4
+ // {type:"assistant", message:{id, model, usage:{input_tokens, output_tokens,
5
+ // cache_creation_input_tokens, cache_read_input_tokens}, content:[...]}, isSidechain}
6
+ // {type:"user", message:{role:"user", content: string | [{type:"text"|"tool_result",...}]}}
7
+ // One API message can span several lines (one per content block) sharing message.id.
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+ import { obj, num, str } from "./io.js";
11
+ import { claudeConfigDir } from "./paths.js";
12
+ export function parseLine(line) {
13
+ if (!line || line[0] !== "{")
14
+ return undefined;
15
+ try {
16
+ return obj(JSON.parse(line));
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ export function usageOf(entry) {
23
+ if (entry.type !== "assistant")
24
+ return undefined;
25
+ const msg = obj(entry.message);
26
+ const u = obj(msg?.usage);
27
+ if (!msg || !u)
28
+ return undefined;
29
+ const usage = {
30
+ input: num(u.input_tokens) ?? 0,
31
+ output: num(u.output_tokens) ?? 0,
32
+ cacheRead: num(u.cache_read_input_tokens) ?? 0,
33
+ cacheWrite: num(u.cache_creation_input_tokens) ?? 0
34
+ };
35
+ if (!usage.input && !usage.output && !usage.cacheRead && !usage.cacheWrite)
36
+ return undefined;
37
+ return { id: str(msg.id) ?? str(entry.requestId), model: str(msg.model), usage };
38
+ }
39
+ export function contextTokens(u) {
40
+ return u.input + u.cacheRead + u.cacheWrite;
41
+ }
42
+ /** Context size from the last main-thread assistant message, reading only the tail of the file. */
43
+ export function lastContextTokens(file, tailBytes = 1024 * 1024) {
44
+ let fd;
45
+ try {
46
+ fd = fs.openSync(file, "r");
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ try {
52
+ const size = fs.fstatSync(fd).size;
53
+ const start = Math.max(0, size - tailBytes);
54
+ const buf = Buffer.alloc(size - start);
55
+ fs.readSync(fd, buf, 0, buf.length, start);
56
+ const lines = buf.toString("utf8").split("\n");
57
+ for (let i = lines.length - 1; i >= 0; i--) {
58
+ const e = parseLine(lines[i]);
59
+ if (!e || e.isSidechain === true)
60
+ continue;
61
+ const u = usageOf(e);
62
+ if (u)
63
+ return contextTokens(u.usage);
64
+ }
65
+ return undefined;
66
+ }
67
+ finally {
68
+ fs.closeSync(fd);
69
+ }
70
+ }
71
+ export function emptyCostState() {
72
+ return { offset: 0, total: 0, lastCost: 0, tokens: 0, lastTokens: 0 };
73
+ }
74
+ /**
75
+ * Incrementally accumulate cost from new transcript bytes. `price` maps a model id
76
+ * and usage to USD. Lines sharing a message id replace (not add to) the previous one.
77
+ */
78
+ export function accumulateCost(file, state, price, maxBytes = 64 * 1024 * 1024) {
79
+ const s = { ...state };
80
+ let fd;
81
+ try {
82
+ fd = fs.openSync(file, "r");
83
+ }
84
+ catch {
85
+ return s;
86
+ }
87
+ try {
88
+ const size = fs.fstatSync(fd).size;
89
+ if (size < s.offset)
90
+ Object.assign(s, emptyCostState()); // file replaced/truncated
91
+ const len = Math.min(size - s.offset, maxBytes);
92
+ if (len <= 0)
93
+ return s;
94
+ const buf = Buffer.alloc(len);
95
+ fs.readSync(fd, buf, 0, len, s.offset);
96
+ const lastNl = buf.lastIndexOf(0x0a);
97
+ if (lastNl < 0)
98
+ return s; // no complete line yet
99
+ const text = buf.subarray(0, lastNl + 1).toString("utf8");
100
+ s.offset += lastNl + 1;
101
+ for (const line of text.split("\n")) {
102
+ const e = parseLine(line);
103
+ if (!e)
104
+ continue;
105
+ const u = usageOf(e);
106
+ if (!u)
107
+ continue;
108
+ const c = price(u.model, u.usage);
109
+ const t = u.usage.input + u.usage.output + u.usage.cacheRead + u.usage.cacheWrite;
110
+ if (u.id && u.id === s.lastId) {
111
+ s.total += c - s.lastCost;
112
+ s.tokens += t - s.lastTokens;
113
+ }
114
+ else {
115
+ s.total += c;
116
+ s.tokens += t;
117
+ }
118
+ s.lastId = u.id;
119
+ s.lastCost = c;
120
+ s.lastTokens = t;
121
+ }
122
+ return s;
123
+ }
124
+ finally {
125
+ fs.closeSync(fd);
126
+ }
127
+ }
128
+ function textOfContent(c) {
129
+ if (typeof c === "string")
130
+ return c;
131
+ if (Array.isArray(c)) {
132
+ const t = c
133
+ .map((b) => obj(b))
134
+ .filter((b) => b?.type === "text" && typeof b.text === "string")
135
+ .map((b) => b.text);
136
+ return t.length ? t.join("\n") : undefined;
137
+ }
138
+ return undefined;
139
+ }
140
+ function isRealPrompt(t) {
141
+ const s = t.trim();
142
+ return s.length > 0 && !s.startsWith("<") && !s.startsWith("Caveat:") && !s.startsWith("[Request interrupted");
143
+ }
144
+ const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
145
+ export function extractFacts(file) {
146
+ const facts = { prompts: 0, filesTouched: [], openTodos: [], recentNotes: [] };
147
+ const text = fs.readFileSync(file, "utf8");
148
+ const files = new Set();
149
+ const notes = [];
150
+ for (const line of text.split("\n")) {
151
+ const e = parseLine(line);
152
+ if (!e || e.isSidechain === true)
153
+ continue;
154
+ if (!facts.cwd && typeof e.cwd === "string")
155
+ facts.cwd = e.cwd;
156
+ const msg = obj(e.message);
157
+ if (!msg)
158
+ continue;
159
+ if (e.type === "user") {
160
+ const t = textOfContent(msg.content);
161
+ if (t && isRealPrompt(t) && e.isMeta !== true) {
162
+ facts.prompts++;
163
+ if (!facts.goal)
164
+ facts.goal = t.trim();
165
+ facts.lastPrompt = t.trim();
166
+ }
167
+ if (Array.isArray(msg.content)) {
168
+ for (const b of msg.content) {
169
+ const o = obj(b);
170
+ if (o?.type === "tool_result" && o.is_error === true) {
171
+ const et = textOfContent(o.content) ?? "";
172
+ if (et.trim())
173
+ facts.lastError = et.trim();
174
+ }
175
+ }
176
+ }
177
+ }
178
+ else if (e.type === "assistant" && Array.isArray(msg.content)) {
179
+ for (const b of msg.content) {
180
+ const o = obj(b);
181
+ if (!o)
182
+ continue;
183
+ if (o.type === "text" && typeof o.text === "string" && o.text.trim())
184
+ notes.push(o.text.trim());
185
+ if (o.type === "tool_use") {
186
+ const name = str(o.name) ?? "";
187
+ const input = obj(o.input) ?? {};
188
+ if (EDIT_TOOLS.has(name)) {
189
+ const p = str(input.file_path) ?? str(input.notebook_path);
190
+ if (p)
191
+ files.add(p);
192
+ }
193
+ if (name === "TodoWrite" && Array.isArray(input.todos)) {
194
+ facts.openTodos = input.todos
195
+ .map((t) => obj(t))
196
+ .filter((t) => t && t.status !== "completed" && typeof t.content === "string")
197
+ .map((t) => `${t.content}${t.status === "in_progress" ? " (in progress)" : ""}`);
198
+ }
199
+ }
200
+ }
201
+ }
202
+ }
203
+ const cwd = facts.cwd;
204
+ facts.filesTouched = [...files].map((f) => (cwd && f.startsWith(cwd + path.sep) ? path.relative(cwd, f) : f));
205
+ facts.recentNotes = notes.slice(-3);
206
+ return facts;
207
+ }
208
+ /** Claude Code's projects dir naming: non-alphanumerics become "-". */
209
+ export function projectDirFor(cwd) {
210
+ return path.join(claudeConfigDir(), "projects", cwd.replace(/[^A-Za-z0-9]/g, "-"));
211
+ }
212
+ const SESSION_RE = /^[A-Za-z0-9_-]{1,128}$/;
213
+ export function findTranscript(opts) {
214
+ const root = path.join(claudeConfigDir(), "projects");
215
+ if (opts.session) {
216
+ if (!SESSION_RE.test(opts.session))
217
+ return undefined;
218
+ const direct = path.join(projectDirFor(opts.cwd), `${opts.session}.jsonl`);
219
+ if (fs.existsSync(direct))
220
+ return direct;
221
+ let dirs;
222
+ try {
223
+ dirs = fs.readdirSync(root);
224
+ }
225
+ catch {
226
+ return undefined;
227
+ }
228
+ for (const d of dirs) {
229
+ const p = path.join(root, d, `${opts.session}.jsonl`);
230
+ if (fs.existsSync(p))
231
+ return p;
232
+ }
233
+ return undefined;
234
+ }
235
+ const dir = projectDirFor(opts.cwd);
236
+ let names;
237
+ try {
238
+ names = fs.readdirSync(dir).filter((n) => n.endsWith(".jsonl"));
239
+ }
240
+ catch {
241
+ return undefined;
242
+ }
243
+ let best;
244
+ for (const n of names) {
245
+ const p = path.join(dir, n);
246
+ const m = fs.statSync(p).mtimeMs;
247
+ if (!best || m > best.m)
248
+ best = { p, m };
249
+ }
250
+ return best?.p;
251
+ }
@@ -0,0 +1 @@
1
+ export const VERSION = "0.1.1";
package/package.json CHANGED
@@ -1,8 +1,54 @@
1
1
  {
2
2
  "name": "@frugalhq/frugal",
3
- "version": "0.0.0",
4
- "description": "Placeholder to enable npm trusted publishing. Install >= 0.1.0.",
3
+ "version": "0.1.1",
4
+ "description": "Local-only copilot for Claude Code: shrinks MCP tool output, shows spend, flags topic drift. No data leaves your machine.",
5
5
  "license": "MIT",
6
- "repository": { "type": "git", "url": "git+https://github.com/rushi209/frugal.git" },
7
- "files": ["README.md"]
6
+ "type": "module",
7
+ "bin": {
8
+ "frugal": "dist/cli.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md",
13
+ "SECURITY.md",
14
+ "LICENSE",
15
+ "CHANGELOG.md"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
20
+ "scripts": {
21
+ "build": "tsc -p tsconfig.build.json",
22
+ "typecheck": "tsc -p tsconfig.json --noEmit",
23
+ "lint": "eslint . && npm run typecheck && node scripts/check-urls.mjs",
24
+ "test": "npm run build && vitest run",
25
+ "prepublishOnly": "npm run build"
26
+ },
27
+ "keywords": [
28
+ "claude-code",
29
+ "mcp",
30
+ "cost",
31
+ "statusline"
32
+ ],
33
+ "devDependencies": {
34
+ "@eslint/js": "10.0.1",
35
+ "@modelcontextprotocol/sdk": "1.32.2",
36
+ "@types/node": "22.20.7",
37
+ "eslint": "10.16.0",
38
+ "typescript": "6.0.3",
39
+ "typescript-eslint": "8.74.0",
40
+ "vitest": "5.1.2"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/rushi209/frugal.git"
45
+ },
46
+ "homepage": "https://github.com/rushi209/frugal",
47
+ "bugs": {
48
+ "url": "https://github.com/rushi209/frugal/issues"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public",
52
+ "provenance": true
53
+ }
8
54
  }