@frugalhq/frugal 0.0.0 → 0.1.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/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +227 -4
- package/SECURITY.md +37 -0
- package/dist/cache.js +69 -0
- package/dist/cli.js +132 -0
- package/dist/compress.js +149 -0
- package/dist/config.js +166 -0
- package/dist/doctor.js +148 -0
- package/dist/handoff.js +51 -0
- package/dist/hooks/bashOutput.js +166 -0
- package/dist/hooks/prompt.js +115 -0
- package/dist/hooks/toolOutput.js +168 -0
- package/dist/html.js +62 -0
- package/dist/init.js +43 -0
- package/dist/io.js +60 -0
- package/dist/mcpServer.js +91 -0
- package/dist/metrics.js +54 -0
- package/dist/net.js +39 -0
- package/dist/ollama.js +100 -0
- package/dist/paths.js +143 -0
- package/dist/redact.js +45 -0
- package/dist/report.js +52 -0
- package/dist/spend.js +52 -0
- package/dist/statusline.js +122 -0
- package/dist/transcript.js +251 -0
- package/dist/version.js +1 -0
- package/package.json +50 -4
package/dist/paths.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// XDG paths, strict permissions (0700 dirs / 0600 files) and symlink refusal (S4).
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as os from "node:os";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
export const DIR_MODE = 0o700;
|
|
7
|
+
export const FILE_MODE = 0o600;
|
|
8
|
+
export function dataDir() {
|
|
9
|
+
const base = process.env.XDG_DATA_HOME || path.join(os.homedir(), ".local", "share");
|
|
10
|
+
return path.join(base, "frugal");
|
|
11
|
+
}
|
|
12
|
+
export function configDir() {
|
|
13
|
+
const base = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
|
|
14
|
+
return path.join(base, "frugal");
|
|
15
|
+
}
|
|
16
|
+
export function configPath() {
|
|
17
|
+
return path.join(configDir(), "config.json");
|
|
18
|
+
}
|
|
19
|
+
/** Claude Code's config root. Wrappers may move it with CLAUDE_CONFIG_DIR. */
|
|
20
|
+
export function claudeConfigDir() {
|
|
21
|
+
return process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
|
|
22
|
+
}
|
|
23
|
+
export class UnsafePathError extends Error {
|
|
24
|
+
}
|
|
25
|
+
function refuseSymlink(p) {
|
|
26
|
+
let st;
|
|
27
|
+
try {
|
|
28
|
+
st = fs.lstatSync(p);
|
|
29
|
+
}
|
|
30
|
+
catch (e) {
|
|
31
|
+
if (e.code === "ENOENT")
|
|
32
|
+
return undefined;
|
|
33
|
+
throw e;
|
|
34
|
+
}
|
|
35
|
+
if (st.isSymbolicLink())
|
|
36
|
+
throw new UnsafePathError(`refusing symlink: ${p}`);
|
|
37
|
+
return st;
|
|
38
|
+
}
|
|
39
|
+
/** Create (if needed) a private directory inside the data dir. Refuses symlinks, tightens perms. */
|
|
40
|
+
export function ensurePrivateDir(dir) {
|
|
41
|
+
const root = dataDir();
|
|
42
|
+
const rel = path.relative(root, dir);
|
|
43
|
+
if (rel.startsWith("..") || path.isAbsolute(rel))
|
|
44
|
+
throw new UnsafePathError(`outside data dir: ${dir}`);
|
|
45
|
+
const parts = [root, ...rel.split(path.sep).filter(Boolean).map((_, i, a) => path.join(root, ...a.slice(0, i + 1)))];
|
|
46
|
+
for (const p of parts) {
|
|
47
|
+
const st = refuseSymlink(p);
|
|
48
|
+
if (!st) {
|
|
49
|
+
fs.mkdirSync(p, { recursive: true, mode: DIR_MODE });
|
|
50
|
+
fs.chmodSync(p, DIR_MODE);
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
if (!st.isDirectory())
|
|
54
|
+
throw new UnsafePathError(`not a directory: ${p}`);
|
|
55
|
+
if ((st.mode & 0o777) !== DIR_MODE)
|
|
56
|
+
fs.chmodSync(p, DIR_MODE);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return dir;
|
|
60
|
+
}
|
|
61
|
+
export function dataPath(...segs) {
|
|
62
|
+
return path.join(dataDir(), ...segs);
|
|
63
|
+
}
|
|
64
|
+
const O_NOFOLLOW = fs.constants.O_NOFOLLOW ?? 0;
|
|
65
|
+
/** Atomic private write: temp file (O_EXCL|O_NOFOLLOW, 0600) then rename. */
|
|
66
|
+
export function writePrivateFile(file, data) {
|
|
67
|
+
ensurePrivateDir(path.dirname(file));
|
|
68
|
+
refuseSymlink(file);
|
|
69
|
+
const tmp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
70
|
+
const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | O_NOFOLLOW, FILE_MODE);
|
|
71
|
+
try {
|
|
72
|
+
fs.writeSync(fd, typeof data === "string" ? Buffer.from(data, "utf8") : data);
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
fs.closeSync(fd);
|
|
76
|
+
}
|
|
77
|
+
fs.renameSync(tmp, file);
|
|
78
|
+
}
|
|
79
|
+
export function appendPrivateFile(file, data) {
|
|
80
|
+
ensurePrivateDir(path.dirname(file));
|
|
81
|
+
refuseSymlink(file);
|
|
82
|
+
const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_APPEND | O_NOFOLLOW, FILE_MODE);
|
|
83
|
+
try {
|
|
84
|
+
fs.fchmodSync(fd, FILE_MODE);
|
|
85
|
+
fs.writeSync(fd, data);
|
|
86
|
+
}
|
|
87
|
+
finally {
|
|
88
|
+
fs.closeSync(fd);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** Read a file from the data dir; returns undefined if missing. Refuses symlinks. */
|
|
92
|
+
export function readPrivateFile(file) {
|
|
93
|
+
if (!refuseSymlink(file))
|
|
94
|
+
return undefined;
|
|
95
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | O_NOFOLLOW);
|
|
96
|
+
try {
|
|
97
|
+
return fs.readFileSync(fd, "utf8");
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
fs.closeSync(fd);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
export function readPrivateJson(file) {
|
|
104
|
+
const s = readPrivateFile(file);
|
|
105
|
+
if (s === undefined)
|
|
106
|
+
return undefined;
|
|
107
|
+
try {
|
|
108
|
+
return JSON.parse(s);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** Report perms problems for doctor. */
|
|
115
|
+
export function checkPerms() {
|
|
116
|
+
const issues = [];
|
|
117
|
+
const root = dataDir();
|
|
118
|
+
const walk = (p) => {
|
|
119
|
+
let st;
|
|
120
|
+
try {
|
|
121
|
+
st = fs.lstatSync(p);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (st.isSymbolicLink()) {
|
|
127
|
+
issues.push(`symlink in data dir: ${p}`);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
const mode = st.mode & 0o777;
|
|
131
|
+
if (st.isDirectory()) {
|
|
132
|
+
if (mode !== DIR_MODE)
|
|
133
|
+
issues.push(`dir ${p} has mode ${mode.toString(8)}, want 700`);
|
|
134
|
+
for (const n of fs.readdirSync(p))
|
|
135
|
+
walk(path.join(p, n));
|
|
136
|
+
}
|
|
137
|
+
else if (mode !== FILE_MODE) {
|
|
138
|
+
issues.push(`file ${p} has mode ${mode.toString(8)}, want 600`);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
walk(root);
|
|
142
|
+
return issues;
|
|
143
|
+
}
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// S2: secret redaction before anything is cached, logged or sent to Ollama.
|
|
2
|
+
const RULES = [
|
|
3
|
+
{ name: "private-key", re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g },
|
|
4
|
+
{ name: "aws-access-key", re: /\b(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\b/g },
|
|
5
|
+
{
|
|
6
|
+
name: "aws-secret",
|
|
7
|
+
re: /(aws_secret_access_key|aws_session_token)(["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,
|
|
8
|
+
replace: (_m, k, sep) => `${k}${sep}[REDACTED:aws-secret]`
|
|
9
|
+
},
|
|
10
|
+
{ name: "github-token", re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}\b/g },
|
|
11
|
+
{ name: "github-pat", re: /\bgithub_pat_[A-Za-z0-9_]{22,}\b/g },
|
|
12
|
+
{ name: "gitlab-token", re: /\bgl(?:pat|dt|rt|ptt|cbt|oas)-[A-Za-z0-9_-]{20,}\b/g },
|
|
13
|
+
{ name: "slack-token", re: /\bxox[abposr]-[A-Za-z0-9-]{10,}\b/g },
|
|
14
|
+
{ name: "slack-app-token", re: /\bxapp-\d-[A-Za-z0-9-]{10,}\b/g },
|
|
15
|
+
{ name: "slack-webhook", re: /hooks\.slack\.com\/services\/[A-Za-z0-9/]+/g },
|
|
16
|
+
{ name: "google-api-key", re: /\bAIza[0-9A-Za-z_-]{35}\b/g },
|
|
17
|
+
{ name: "jwt", re: /\beyJ[A-Za-z0-9_-]{5,}\.eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}/g },
|
|
18
|
+
{
|
|
19
|
+
name: "bearer",
|
|
20
|
+
re: /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/g,
|
|
21
|
+
replace: (_m, kind) => `${kind} [REDACTED:auth]`
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
name: "password",
|
|
25
|
+
re: /\b(password|passwd|pwd|secret|client_secret|api[_-]?key|apikey|access[_-]?token|auth[_-]?token)(["']?\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|[^\s,;&"'}]+)/gi,
|
|
26
|
+
replace: (_m, k, sep, v) => {
|
|
27
|
+
const q = v.startsWith('"') ? '"' : v.startsWith("'") ? "'" : "";
|
|
28
|
+
return `${k}${sep}${q}[REDACTED:secret]${q}`;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
];
|
|
32
|
+
export function redact(text) {
|
|
33
|
+
let out = text;
|
|
34
|
+
for (const r of RULES) {
|
|
35
|
+
out = r.replace
|
|
36
|
+
? out.replace(r.re, r.replace)
|
|
37
|
+
: out.replace(r.re, `[REDACTED:${r.name}]`);
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
export function redactionCount(before, after) {
|
|
42
|
+
if (before === after)
|
|
43
|
+
return 0;
|
|
44
|
+
return (after.match(/\[REDACTED:/g) ?? []).length - (before.match(/\[REDACTED:/g) ?? []).length;
|
|
45
|
+
}
|
package/dist/report.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { readMetrics } from "./metrics.js";
|
|
2
|
+
import { dayKey, loadLedger } from "./spend.js";
|
|
3
|
+
import { money } from "./statusline.js";
|
|
4
|
+
import { fmtKB } from "./compress.js";
|
|
5
|
+
function table(rows) {
|
|
6
|
+
const w = rows[0].map((_, i) => Math.max(...rows.map((r) => (r[i] ?? "").length)));
|
|
7
|
+
return rows.map((r) => r.map((c, i) => (i === 0 ? c.padEnd(w[i]) : c.padStart(w[i]))).join(" ")).join("\n");
|
|
8
|
+
}
|
|
9
|
+
export function report(cfg, days, now = Date.now()) {
|
|
10
|
+
const out = [];
|
|
11
|
+
const ledger = loadLedger();
|
|
12
|
+
const rows = [["day", "spend"]];
|
|
13
|
+
let total = 0;
|
|
14
|
+
for (let i = days - 1; i >= 0; i--) {
|
|
15
|
+
const k = dayKey(now - i * 86400_000);
|
|
16
|
+
const v = ledger.days[k];
|
|
17
|
+
if (v === undefined)
|
|
18
|
+
continue;
|
|
19
|
+
total += v;
|
|
20
|
+
rows.push([k, money(v)]);
|
|
21
|
+
}
|
|
22
|
+
out.push(`Spend, last ${days} days (${cfg.currency})`);
|
|
23
|
+
out.push(rows.length > 1 ? table([...rows, ["total", money(total)]]) : "(no spend recorded yet)");
|
|
24
|
+
const since = now - days * 86400_000;
|
|
25
|
+
const per = new Map();
|
|
26
|
+
for (const e of readMetrics(since)) {
|
|
27
|
+
if (e.kind !== "compress" || !e.tool)
|
|
28
|
+
continue;
|
|
29
|
+
const t = per.get(e.tool) ?? { calls: 0, inB: 0, outB: 0 };
|
|
30
|
+
t.calls++;
|
|
31
|
+
t.inB += e.bytesIn ?? 0;
|
|
32
|
+
t.outB += e.bytesOut ?? 0;
|
|
33
|
+
per.set(e.tool, t);
|
|
34
|
+
}
|
|
35
|
+
out.push("", "MCP output compression");
|
|
36
|
+
if (per.size === 0)
|
|
37
|
+
out.push("(no compressed tool calls yet)");
|
|
38
|
+
else {
|
|
39
|
+
const r = [["tool", "calls", "in", "out", "saved"]];
|
|
40
|
+
let ti = 0;
|
|
41
|
+
let to = 0;
|
|
42
|
+
for (const [tool, t] of [...per.entries()].sort((a, b) => b[1].inB - b[1].outB - (a[1].inB - a[1].outB))) {
|
|
43
|
+
ti += t.inB;
|
|
44
|
+
to += t.outB;
|
|
45
|
+
r.push([tool, String(t.calls), fmtKB(t.inB), fmtKB(t.outB), `${Math.round((1 - t.outB / t.inB) * 100)}%`]);
|
|
46
|
+
}
|
|
47
|
+
r.push(["total", "", fmtKB(ti), fmtKB(to), `${Math.round((1 - to / ti) * 100)}%`]);
|
|
48
|
+
out.push(table(r));
|
|
49
|
+
out.push(`≈ ${Math.round((ti - to) / 4).toLocaleString("en-US")} tokens kept out of context (bytes/4 estimate)`);
|
|
50
|
+
}
|
|
51
|
+
return out.join("\n");
|
|
52
|
+
}
|
package/dist/spend.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Spend ledger. Claude Code reports a *cumulative* per-session cost on every
|
|
2
|
+
// status line refresh, so we store the last value per session and add only deltas.
|
|
3
|
+
import { dataPath, readPrivateJson, writePrivateFile } from "./paths.js";
|
|
4
|
+
import { record } from "./metrics.js";
|
|
5
|
+
const KEEP_SESSION_MS = 45 * 24 * 3600_000;
|
|
6
|
+
export function ledgerFile() {
|
|
7
|
+
return dataPath("spend.json");
|
|
8
|
+
}
|
|
9
|
+
export function loadLedger() {
|
|
10
|
+
const l = readPrivateJson(ledgerFile());
|
|
11
|
+
if (!l || l.v !== 1 || typeof l.sessions !== "object" || typeof l.days !== "object")
|
|
12
|
+
return { v: 1, sessions: {}, days: {} };
|
|
13
|
+
return l;
|
|
14
|
+
}
|
|
15
|
+
export function saveLedger(l, now = Date.now()) {
|
|
16
|
+
for (const [id, s] of Object.entries(l.sessions))
|
|
17
|
+
if (now - s.updated > KEEP_SESSION_MS)
|
|
18
|
+
delete l.sessions[id];
|
|
19
|
+
writePrivateFile(ledgerFile(), JSON.stringify(l));
|
|
20
|
+
}
|
|
21
|
+
export function dayKey(ts) {
|
|
22
|
+
const d = new Date(ts);
|
|
23
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
24
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
|
|
25
|
+
}
|
|
26
|
+
/** Apply a new cumulative session total. Returns the delta added (>= 0). */
|
|
27
|
+
export function applySessionTotal(l, session, totalUsd, now = Date.now(), tokens) {
|
|
28
|
+
const prev = l.sessions[session];
|
|
29
|
+
const before = prev?.usd ?? 0;
|
|
30
|
+
const delta = totalUsd - before;
|
|
31
|
+
l.sessions[session] = { ...(prev ?? {}), usd: Math.max(totalUsd, 0), updated: now };
|
|
32
|
+
if (delta <= 0 || !Number.isFinite(delta))
|
|
33
|
+
return 0;
|
|
34
|
+
const k = dayKey(now);
|
|
35
|
+
l.days[k] = (l.days[k] ?? 0) + delta;
|
|
36
|
+
try {
|
|
37
|
+
record({ ts: now, kind: "cost", session, costUsd: delta, tokens });
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// best-effort
|
|
41
|
+
}
|
|
42
|
+
return delta;
|
|
43
|
+
}
|
|
44
|
+
export function totals(l, now = Date.now()) {
|
|
45
|
+
const today = dayKey(now);
|
|
46
|
+
const month = today.slice(0, 7);
|
|
47
|
+
let m = 0;
|
|
48
|
+
for (const [k, v] of Object.entries(l.days))
|
|
49
|
+
if (k.startsWith(month))
|
|
50
|
+
m += v;
|
|
51
|
+
return { today: l.days[today] ?? 0, month: m };
|
|
52
|
+
}
|
|
@@ -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
|
+
}
|
package/dist/version.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = "0.1.0";
|