@aispendbook/cli 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +207 -2
- package/dist/bin.js +23 -0
- package/dist/cache-audit.js +162 -0
- package/dist/cli.js +402 -0
- package/dist/compare.js +238 -0
- package/dist/config.js +87 -0
- package/dist/mcp.js +155 -0
- package/dist/node-impl.js +69 -0
- package/dist/prices.json +1743 -0
- package/dist/pricing.js +170 -0
- package/dist/range.js +45 -0
- package/dist/report.js +112 -0
- package/dist/savings.js +83 -0
- package/dist/skill/SKILL.md +76 -0
- package/dist/skill/reference.md +47 -0
- package/dist/sources/claude-code.js +106 -0
- package/dist/sources/claude-prefix.js +111 -0
- package/dist/sources/codex.js +165 -0
- package/dist/sources/gemini.js +141 -0
- package/dist/sources/util.js +53 -0
- package/dist/sync.js +174 -0
- package/dist/types.js +2 -0
- package/package.json +43 -4
package/dist/config.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* All configuration in one place: every default is named here, and every value can be changed by a
|
|
3
|
+
* flag or an environment variable. Nothing else in the package reads process.env.
|
|
4
|
+
*/
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
export const DEFAULTS = {
|
|
7
|
+
apiBase: "https://www.aispendbook.com",
|
|
8
|
+
ingestPath: "/api/v1/ingest/batch",
|
|
9
|
+
/** Server limit is ingest_max_batch_events (services/api/app/core/config.py). */
|
|
10
|
+
batchSize: 500,
|
|
11
|
+
maxRetries: 5,
|
|
12
|
+
/** Upper bound on one wait, whatever Retry-After says. */
|
|
13
|
+
maxRetryWaitMs: 120_000,
|
|
14
|
+
/** The server rejects events older than 400 days; one day of margin. */
|
|
15
|
+
maxEventAgeDays: 399,
|
|
16
|
+
reportSince: "7d",
|
|
17
|
+
/** First sync with no saved state looks back this far. Later syncs start one day before the last one. */
|
|
18
|
+
firstSyncSince: "30d",
|
|
19
|
+
syncOverlapDays: 1,
|
|
20
|
+
stateDirName: ".aispendbook",
|
|
21
|
+
stateFileName: "sync-state.json",
|
|
22
|
+
sdkName: "aispendbook-cli",
|
|
23
|
+
/** Skill install record and comparison markers, next to the sync state. */
|
|
24
|
+
savingsFileName: "savings.json",
|
|
25
|
+
/** The savings skill's folder name under the Claude Code skills directory. */
|
|
26
|
+
skillName: "aispendbook-savings",
|
|
27
|
+
/** Personal skills directory of Claude Code, relative to the home directory. */
|
|
28
|
+
skillsDir: ".claude/skills",
|
|
29
|
+
/** report --compare: days on each side of the split point, and the minimum sessions per side. */
|
|
30
|
+
compareWindowDays: 30,
|
|
31
|
+
compareMinSessions: 20,
|
|
32
|
+
/** Median requests per session differing by more than this share means the work differs in size. */
|
|
33
|
+
compareWorkShift: 0.25,
|
|
34
|
+
savingsPath: "/api/v1/savings-comparisons/ingest",
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Prompt caching facts used by the cache audit, from Anthropic's prompt caching page
|
|
38
|
+
* (read on CACHE_FACTS.observedAt). Prices themselves come from prices.json, per model and date.
|
|
39
|
+
*/
|
|
40
|
+
export const CACHE_FACTS = {
|
|
41
|
+
sourceUrl: "https://platform.claude.com/docs/en/build-with-claude/prompt-caching",
|
|
42
|
+
observedAt: "2026-12-01",
|
|
43
|
+
ttl5mMs: 5 * 60_000,
|
|
44
|
+
ttl1hMs: 60 * 60_000,
|
|
45
|
+
/** Shortest cacheable prompt by model id prefix (longest prefix wins); others use the default. */
|
|
46
|
+
minTokens: {
|
|
47
|
+
"claude-fable-5": 512, "claude-mythos-5": 512, "claude-opus-5": 512, "claude-sonnet-5-5": 512, "claude-haiku-5-5": 512,
|
|
48
|
+
"claude-opus-4-8": 1024, "claude-sonnet-5": 1024, "claude-sonnet-4-6": 1024, "claude-opus-4-1": 1024,
|
|
49
|
+
"claude-opus-4": 1024, "claude-sonnet-4": 1024,
|
|
50
|
+
"claude-mythos-preview": 2048, "claude-opus-4-7": 2048,
|
|
51
|
+
"claude-opus-4-6": 4096, "claude-opus-4-5": 4096, "claude-haiku-4-5": 4096,
|
|
52
|
+
},
|
|
53
|
+
defaultMinTokens: 1024,
|
|
54
|
+
};
|
|
55
|
+
export const ENV = {
|
|
56
|
+
ingestionKey: "AISPENDBOOK_INGESTION_KEY",
|
|
57
|
+
apiBase: "AISPENDBOOK_API",
|
|
58
|
+
home: "AISPENDBOOK_HOME", // directory of the sync state file
|
|
59
|
+
claudeConfigDir: "CLAUDE_CONFIG_DIR", // Claude Code's own variable (comma-separated list allowed)
|
|
60
|
+
codexHome: "CODEX_HOME", // Codex CLI's own variable
|
|
61
|
+
geminiHome: "GEMINI_CLI_HOME", // Gemini CLI's home override (holds .gemini)
|
|
62
|
+
};
|
|
63
|
+
function nonEmpty(v) {
|
|
64
|
+
const s = v?.trim();
|
|
65
|
+
return s ? s : null;
|
|
66
|
+
}
|
|
67
|
+
export function sourcePaths(env, home) {
|
|
68
|
+
const claude = nonEmpty(env[ENV.claudeConfigDir]);
|
|
69
|
+
const claudeDirs = claude
|
|
70
|
+
? claude.split(",").map((s) => s.trim()).filter(Boolean)
|
|
71
|
+
: [join(home, ".claude"), join(home, ".config", "claude")];
|
|
72
|
+
const geminiHome = nonEmpty(env[ENV.geminiHome]) ?? home;
|
|
73
|
+
return {
|
|
74
|
+
claudeDirs,
|
|
75
|
+
codexHome: nonEmpty(env[ENV.codexHome]) ?? join(home, ".codex"),
|
|
76
|
+
// Gemini CLI keeps runtime files under ~/.cache/.gemini when it runs in the macOS sandbox.
|
|
77
|
+
geminiTmpDirs: [join(geminiHome, ".gemini", "tmp"), join(geminiHome, ".cache", ".gemini", "tmp")],
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
export function loadConfig(env, home, flags = {}) {
|
|
81
|
+
return {
|
|
82
|
+
apiBase: (flags.api ?? nonEmpty(env[ENV.apiBase]) ?? DEFAULTS.apiBase).replace(/\/+$/, ""),
|
|
83
|
+
ingestionKey: nonEmpty(flags.key) ?? nonEmpty(env[ENV.ingestionKey]),
|
|
84
|
+
stateDir: nonEmpty(env[ENV.home]) ?? join(home, DEFAULTS.stateDirName),
|
|
85
|
+
sources: sourcePaths(env, home),
|
|
86
|
+
};
|
|
87
|
+
}
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local stdio MCP server: newline-delimited JSON-RPC 2.0 on stdin/stdout. Only protocol messages are
|
|
3
|
+
* ever written to stdout. One read-only tool, my_local_ai_usage, reports usage from local logs.
|
|
4
|
+
*/
|
|
5
|
+
import { createInterface } from "node:readline";
|
|
6
|
+
import { formatUsd } from "./pricing.js";
|
|
7
|
+
import { GROUPINGS, PRICE_BASIS, totalsLine } from "./report.js";
|
|
8
|
+
import { TOOLS } from "./types.js";
|
|
9
|
+
export const PROTOCOL_VERSION = "2025-11-25";
|
|
10
|
+
const SUPPORTED_VERSIONS = [PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05"];
|
|
11
|
+
export const TOOL_NAME = "my_local_ai_usage";
|
|
12
|
+
const MAX_ROWS = 100;
|
|
13
|
+
const ARG_MAX_LEN = 16;
|
|
14
|
+
const TOOL = {
|
|
15
|
+
name: TOOL_NAME,
|
|
16
|
+
title: "My local AI coding usage",
|
|
17
|
+
description: "Token usage and API-equivalent cost of Claude Code, OpenAI Codex CLI and Gemini CLI on this computer, " +
|
|
18
|
+
"read from their local logs. Cost is an estimate at public list prices, not a bill: flat-fee plans such " +
|
|
19
|
+
"as Claude Max are not billed per token. Nothing is uploaded.",
|
|
20
|
+
inputSchema: {
|
|
21
|
+
type: "object",
|
|
22
|
+
properties: {
|
|
23
|
+
since: { type: "string", description: "Start: '7d' (today and the 6 days before) or 'YYYY-MM-DD'. Default 7d.", maxLength: ARG_MAX_LEN },
|
|
24
|
+
until: { type: "string", description: "Last day included, 'YYYY-MM-DD' or 'Nd'. Default today.", maxLength: ARG_MAX_LEN },
|
|
25
|
+
by: { type: "string", enum: [...GROUPINGS], description: "Group rows by day, project, model or tool. Default day." },
|
|
26
|
+
source: { type: "string", enum: [...TOOLS], description: "Only this tool. Default all." },
|
|
27
|
+
},
|
|
28
|
+
additionalProperties: false,
|
|
29
|
+
},
|
|
30
|
+
outputSchema: {
|
|
31
|
+
type: "object",
|
|
32
|
+
properties: {
|
|
33
|
+
by: { type: "string" },
|
|
34
|
+
since: { type: "string" },
|
|
35
|
+
until: { type: ["string", "null"] },
|
|
36
|
+
basis: { type: "string" },
|
|
37
|
+
rows: { type: "array", items: { type: "object" } },
|
|
38
|
+
totals: { type: "object" },
|
|
39
|
+
unpricedModels: { type: "array", items: { type: "string" } },
|
|
40
|
+
},
|
|
41
|
+
required: ["by", "since", "basis", "rows", "totals"],
|
|
42
|
+
},
|
|
43
|
+
annotations: { title: "My local AI coding usage", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
44
|
+
};
|
|
45
|
+
class InvalidParams extends Error {
|
|
46
|
+
}
|
|
47
|
+
function parseArgs(raw, defaultSince) {
|
|
48
|
+
const a = (raw && typeof raw === "object" ? raw : {});
|
|
49
|
+
const s = (k) => {
|
|
50
|
+
const v = a[k];
|
|
51
|
+
if (v === undefined || v === null || v === "")
|
|
52
|
+
return undefined;
|
|
53
|
+
if (typeof v !== "string" || v.length > ARG_MAX_LEN)
|
|
54
|
+
throw new InvalidParams(`${k} must be a short string`);
|
|
55
|
+
return v;
|
|
56
|
+
};
|
|
57
|
+
for (const k of Object.keys(a))
|
|
58
|
+
if (!["since", "until", "by", "source"].includes(k))
|
|
59
|
+
throw new InvalidParams(`unknown argument ${k}`);
|
|
60
|
+
const by = s("by") ?? "day";
|
|
61
|
+
if (!GROUPINGS.includes(by))
|
|
62
|
+
throw new InvalidParams(`by must be one of ${GROUPINGS.join(", ")}`);
|
|
63
|
+
const source = s("source");
|
|
64
|
+
if (source && !TOOLS.includes(source))
|
|
65
|
+
throw new InvalidParams(`source must be one of ${TOOLS.join(", ")}`);
|
|
66
|
+
return { since: s("since") ?? defaultSince, until: s("until"), by: by, source: source ? [source] : null };
|
|
67
|
+
}
|
|
68
|
+
function summary(r) {
|
|
69
|
+
const rows = r.rows.slice(0, MAX_ROWS).map((x) => `${x.key}: ${x.requests} requests, ${x.totalTokens.toLocaleString("en-US")} tokens, ${formatUsd(x.costMicros)}${x.unpricedRequests ? ` (${x.unpricedRequests} unpriced)` : ""}`);
|
|
70
|
+
const more = r.rows.length > MAX_ROWS ? [`(${r.rows.length - MAX_ROWS} more rows in structuredContent)`] : [];
|
|
71
|
+
const unpriced = r.unpricedModels.length ? [`Models without a list price: ${r.unpricedModels.join(", ")}.`] : [];
|
|
72
|
+
return [`${r.since} to ${r.until ?? "now"}, by ${r.by}:`, ...rows, ...more, totalsLine(r), PRICE_BASIS, ...unpriced].join("\n");
|
|
73
|
+
}
|
|
74
|
+
export class McpServer {
|
|
75
|
+
service;
|
|
76
|
+
info;
|
|
77
|
+
defaultSince;
|
|
78
|
+
constructor(service, info, defaultSince) {
|
|
79
|
+
this.service = service;
|
|
80
|
+
this.info = info;
|
|
81
|
+
this.defaultSince = defaultSince;
|
|
82
|
+
}
|
|
83
|
+
/** The reply to one message, or null for a notification (no id) or a response from the client. */
|
|
84
|
+
async handle(msg) {
|
|
85
|
+
if (!msg || typeof msg !== "object" || Array.isArray(msg))
|
|
86
|
+
return this.error(null, -32600, "Invalid Request");
|
|
87
|
+
const m = msg;
|
|
88
|
+
const hasId = "id" in m && (typeof m.id === "string" || typeof m.id === "number");
|
|
89
|
+
if (typeof m.method !== "string")
|
|
90
|
+
return hasId ? this.error(m.id, -32600, "Invalid Request") : null;
|
|
91
|
+
if (!hasId)
|
|
92
|
+
return null; // notifications (initialized, cancelled, ...) get no reply
|
|
93
|
+
const id = m.id;
|
|
94
|
+
const params = (m.params && typeof m.params === "object" ? m.params : {});
|
|
95
|
+
switch (m.method) {
|
|
96
|
+
case "initialize": {
|
|
97
|
+
const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : PROTOCOL_VERSION;
|
|
98
|
+
return this.ok(id, {
|
|
99
|
+
protocolVersion: SUPPORTED_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSION,
|
|
100
|
+
capabilities: { tools: { listChanged: false } },
|
|
101
|
+
serverInfo: { name: this.info.name, title: "AI Spendbook local usage", version: this.info.version },
|
|
102
|
+
instructions: "Use my_local_ai_usage to answer questions about the user's own AI coding tool usage and its API-equivalent cost. It reads local logs only.",
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
case "ping":
|
|
106
|
+
return this.ok(id, {});
|
|
107
|
+
case "tools/list":
|
|
108
|
+
return this.ok(id, { tools: [TOOL] });
|
|
109
|
+
case "tools/call": {
|
|
110
|
+
if (params.name !== TOOL_NAME)
|
|
111
|
+
return this.error(id, -32602, `Unknown tool: ${String(params.name)}`);
|
|
112
|
+
// Argument and date errors are tool results with isError, so the model can correct the call.
|
|
113
|
+
try {
|
|
114
|
+
const report = await this.service.report(parseArgs(params.arguments, this.defaultSince));
|
|
115
|
+
const structured = { by: report.by, since: report.since, until: report.until, basis: report.basis,
|
|
116
|
+
rows: report.rows.slice(0, MAX_ROWS), totals: report.totals, unpricedModels: report.unpricedModels };
|
|
117
|
+
return this.ok(id, { content: [{ type: "text", text: summary(report) }], structuredContent: structured, isError: false });
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
return this.ok(id, { content: [{ type: "text", text: e.message }], isError: true });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
default:
|
|
124
|
+
return this.error(id, -32601, `Method not found: ${m.method}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
ok(id, result) {
|
|
128
|
+
return { jsonrpc: "2.0", id, result };
|
|
129
|
+
}
|
|
130
|
+
error(id, code, message) {
|
|
131
|
+
return { jsonrpc: "2.0", id, error: { code, message } };
|
|
132
|
+
}
|
|
133
|
+
/** Serve until stdin closes. */
|
|
134
|
+
async serve(input, output) {
|
|
135
|
+
const rl = createInterface({ input, crlfDelay: Infinity });
|
|
136
|
+
const pending = [];
|
|
137
|
+
for await (const line of rl) {
|
|
138
|
+
if (!line.trim())
|
|
139
|
+
continue;
|
|
140
|
+
let parsed;
|
|
141
|
+
try {
|
|
142
|
+
parsed = JSON.parse(line);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
output.write(`${JSON.stringify(this.error(null, -32700, "Parse error"))}\n`);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
pending.push(this.handle(parsed).then((reply) => {
|
|
149
|
+
if (reply)
|
|
150
|
+
output.write(`${JSON.stringify(reply)}\n`);
|
|
151
|
+
}));
|
|
152
|
+
}
|
|
153
|
+
await Promise.all(pending);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Node.js implementations of the FileSystem, Clock, Sleeper, HttpClient and Output interfaces. */
|
|
2
|
+
import { promises as fsp } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import * as zlib from "node:zlib";
|
|
5
|
+
export class NodeFileSystem {
|
|
6
|
+
async listFiles(root, accept) {
|
|
7
|
+
const out = [];
|
|
8
|
+
const walk = async (dir) => {
|
|
9
|
+
let entries;
|
|
10
|
+
try {
|
|
11
|
+
entries = await fsp.readdir(dir, { withFileTypes: true });
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return; // missing or unreadable directory
|
|
15
|
+
}
|
|
16
|
+
for (const e of entries) {
|
|
17
|
+
const p = join(dir, e.name);
|
|
18
|
+
if (e.isDirectory())
|
|
19
|
+
await walk(p);
|
|
20
|
+
else if (e.isFile() && accept(e.name)) {
|
|
21
|
+
try {
|
|
22
|
+
out.push({ path: p, mtimeMs: (await fsp.stat(p)).mtimeMs });
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
// vanished between readdir and stat
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
await walk(root);
|
|
31
|
+
return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
32
|
+
}
|
|
33
|
+
readText(path) {
|
|
34
|
+
return fsp.readFile(path, "utf8");
|
|
35
|
+
}
|
|
36
|
+
async readZstdText(path) {
|
|
37
|
+
const decode = zlib.zstdDecompressSync;
|
|
38
|
+
if (typeof decode !== "function")
|
|
39
|
+
return null; // Node.js before 22.15 / 23.8
|
|
40
|
+
return decode(await fsp.readFile(path)).toString("utf8");
|
|
41
|
+
}
|
|
42
|
+
async isDirectory(path) {
|
|
43
|
+
try {
|
|
44
|
+
return (await fsp.stat(path)).isDirectory();
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async writeText(path, text) {
|
|
51
|
+
await fsp.mkdir(dirname(path), { recursive: true });
|
|
52
|
+
const tmp = `${path}.tmp-${process.pid}`;
|
|
53
|
+
await fsp.writeFile(tmp, text, { mode: 0o600 });
|
|
54
|
+
await fsp.rename(tmp, path);
|
|
55
|
+
}
|
|
56
|
+
async removeDir(path) {
|
|
57
|
+
await fsp.rm(path, { recursive: true, force: true });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export const systemClock = { now: () => new Date() };
|
|
61
|
+
export const realSleeper = { sleep: (ms) => new Promise((r) => setTimeout(r, ms)) };
|
|
62
|
+
export const fetchHttp = async (url, init) => {
|
|
63
|
+
const res = await fetch(url, init);
|
|
64
|
+
return { status: res.status, headers: res.headers, text: () => res.text() };
|
|
65
|
+
};
|
|
66
|
+
export const processOutput = {
|
|
67
|
+
out: (t) => process.stdout.write(t.endsWith("\n") ? t : `${t}\n`),
|
|
68
|
+
err: (t) => process.stderr.write(t.endsWith("\n") ? t : `${t}\n`),
|
|
69
|
+
};
|