harma-kit 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/src/usage.mjs ADDED
@@ -0,0 +1,127 @@
1
+ // Token usage from the CLIs' own session logs, and an API-list-price estimate.
2
+ // Claude Code: ~/.claude/projects/<slug>/<session-id>.jsonl, assistant
3
+ // entries carry message.usage and message.model.
4
+ // Codex: ~/.codex/sessions/YYYY/MM/DD/rollout-*-<session-id>.jsonl,
5
+ // session_meta.payload.id, turn_context.payload.model/effort,
6
+ // event_msg token_count payload.info.total_token_usage (cumulative).
7
+ // For subscriptions this is what the tokens would cost at API list price,
8
+ // not what is billed.
9
+ import { readdirSync, statSync, existsSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+ import { homedir } from 'node:os';
12
+ import { readJsonl } from './util.mjs';
13
+
14
+ // Multipliers on the input price. Anthropic publishes these (cache write
15
+ // 1.25x for 5 min, 2x for 1 h, read 0.1x). For OpenAI the cached-input ratio
16
+ // is not in the catalog: 0.1x is an assumption and is reported as one.
17
+ export const PRICE_RULES = {
18
+ anthropic: { cacheWrite5m: 1.25, cacheWrite1h: 2, cacheRead: 0.1, assumed: false },
19
+ openai: { cacheRead: 0.1, assumed: true },
20
+ };
21
+
22
+ function files(dir, { suffix = '.jsonl', sinceMs = 0, match } = {}) {
23
+ if (!existsSync(dir)) return [];
24
+ let names;
25
+ try { names = readdirSync(dir, { recursive: true }); } catch { return []; }
26
+ const out = [];
27
+ for (const n of names) {
28
+ const name = String(n);
29
+ if (!name.endsWith(suffix)) continue;
30
+ if (match && !match(name)) continue;
31
+ const p = join(dir, name);
32
+ try { if (statSync(p).mtimeMs >= sinceMs) out.push(p); } catch { /* gone */ }
33
+ }
34
+ return out;
35
+ }
36
+
37
+ const home = (env) => env.HOME || homedir();
38
+
39
+ export function claudeUsage({ env = process.env, sessionIds, sinceMs = 0 } = {}) {
40
+ const dir = join(home(env), '.claude', 'projects');
41
+ const ids = sessionIds ? new Set(sessionIds) : null;
42
+ const paths = files(dir, { sinceMs, match: ids ? (n) => ids.has(n.split('/').pop().replace(/\.jsonl$/, '')) : undefined });
43
+ const bySession = {};
44
+ for (const p of paths) {
45
+ for (const e of readJsonl(p)) {
46
+ const u = e?.message?.usage;
47
+ if (e.type !== 'assistant' || !u) continue;
48
+ if (Date.parse(e.timestamp ?? 0) < sinceMs) continue;
49
+ const sid = e.sessionId ?? p.split('/').pop().replace(/\.jsonl$/, '');
50
+ if (ids && !ids.has(sid)) continue;
51
+ const s = (bySession[sid] ??= { harness: 'claude', session_id: sid, model: null, cwd: e.cwd ?? null, input: 0, cache_write_5m: 0, cache_write_1h: 0, cache_read: 0, output: 0 });
52
+ s.model = e.message.model ?? s.model;
53
+ s.input += u.input_tokens ?? 0;
54
+ const cc = u.cache_creation ?? {};
55
+ const w1h = cc.ephemeral_1h_input_tokens ?? 0;
56
+ s.cache_write_1h += w1h;
57
+ s.cache_write_5m += (u.cache_creation_input_tokens ?? 0) - w1h;
58
+ s.cache_read += u.cache_read_input_tokens ?? 0;
59
+ s.output += u.output_tokens ?? 0;
60
+ }
61
+ }
62
+ return Object.values(bySession);
63
+ }
64
+
65
+ export function codexUsage({ env = process.env, sessionIds, sinceMs = 0 } = {}) {
66
+ const dir = join(home(env), '.codex', 'sessions');
67
+ const ids = sessionIds ? new Set(sessionIds) : null;
68
+ const paths = files(dir, { sinceMs, match: (n) => /rollout-.*\.jsonl$/.test(n) && (!ids || [...ids].some((id) => n.endsWith(`${id}.jsonl`))) });
69
+ const out = [];
70
+ for (const p of paths) {
71
+ let s = null;
72
+ for (const e of readJsonl(p)) {
73
+ const pl = e.payload ?? {};
74
+ if (e.type === 'session_meta') {
75
+ s = { harness: 'codex', session_id: pl.id, model: null, effort: null, cwd: pl.cwd ?? null, started_at: pl.timestamp ?? e.timestamp, input: 0, cache_read: 0, output: 0, reasoning: 0 };
76
+ } else if (s && e.type === 'turn_context') {
77
+ s.model = pl.model ?? s.model;
78
+ s.effort = pl.effort ?? s.effort;
79
+ } else if (s && pl.type === 'token_count' && pl.info?.total_token_usage) {
80
+ const t = pl.info.total_token_usage; // cumulative: last one wins
81
+ s.input = (t.input_tokens ?? 0) - (t.cached_input_tokens ?? 0);
82
+ s.cache_read = t.cached_input_tokens ?? 0;
83
+ s.output = t.output_tokens ?? 0;
84
+ s.reasoning = t.reasoning_output_tokens ?? 0;
85
+ }
86
+ }
87
+ if (s && (!ids || ids.has(s.session_id))) out.push(s);
88
+ }
89
+ return out;
90
+ }
91
+
92
+ /** Codex session started in <cwd> at or after <sinceMs> (the first one). */
93
+ export function findCodexSession({ env = process.env, cwd, sinceMs }) {
94
+ const sessions = codexUsage({ env, sinceMs: sinceMs - 60_000 })
95
+ .filter((s) => s.cwd === cwd && Date.parse(s.started_at ?? 0) >= sinceMs - 5_000)
96
+ .sort((a, b) => Date.parse(a.started_at) - Date.parse(b.started_at));
97
+ return sessions[0]?.session_id ?? null;
98
+ }
99
+
100
+ /** Estimated USD at API list price; null when the model has no price. */
101
+ export function estimateCost(session, catalog) {
102
+ const model = catalog.models?.[session.model] ?? catalog.models?.[normalizeModel(session.model, catalog)];
103
+ const price = model?.pricing;
104
+ if (!price) return { usd: null, note: `prezzo sconosciuto per ${session.model ?? 'modello ignoto'}` };
105
+ const rules = PRICE_RULES[model.provider] ?? { cacheRead: 1, assumed: true };
106
+ const inP = price.input / 1e6;
107
+ const outP = price.output / 1e6;
108
+ let usd = (session.input ?? 0) * inP + (session.output ?? 0) * outP + (session.cache_read ?? 0) * inP * (rules.cacheRead ?? 1);
109
+ usd += (session.cache_write_5m ?? 0) * inP * (rules.cacheWrite5m ?? 1);
110
+ usd += (session.cache_write_1h ?? 0) * inP * (rules.cacheWrite1h ?? 1);
111
+ return {
112
+ usd: Math.round(usd * 100) / 100,
113
+ note: `listino ${price.source} ${price.verified_on}${rules.assumed ? '; input in cache a 0.1× (ipotesi)' : ''}`,
114
+ };
115
+ }
116
+
117
+ function normalizeModel(name, catalog) {
118
+ if (!name) return null;
119
+ // "claude-opus-5-5-20261001" or "claude-opus-5-5[1m]" -> catalog id
120
+ return Object.keys(catalog.models ?? {}).find((id) => name.startsWith(id)) ?? null;
121
+ }
122
+
123
+ export function usageFor(harness, opts) {
124
+ if (harness === 'claude') return claudeUsage(opts);
125
+ if (harness === 'codex') return codexUsage(opts);
126
+ return [];
127
+ }
package/src/util.mjs ADDED
@@ -0,0 +1,90 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { readFileSync, existsSync, accessSync, constants } from 'node:fs';
3
+ import { delimiter, join } from 'node:path';
4
+
5
+ export const now = () => new Date().toISOString();
6
+
7
+ /** Run a program without a shell. Never throws: returns {ok, code, stdout, stderr}. */
8
+ export function run(cmd, args = [], { timeout = 60_000, env, cwd, input } = {}) {
9
+ return new Promise((resolve) => {
10
+ const child = execFile(cmd, args, {
11
+ timeout, env: env ?? process.env, cwd, maxBuffer: 64 * 1024 * 1024,
12
+ }, (err, stdout, stderr) => {
13
+ resolve({
14
+ ok: !err,
15
+ code: err ? (typeof err.code === 'number' ? err.code : 1) : 0,
16
+ stdout: String(stdout ?? ''), stderr: String(stderr ?? ''),
17
+ error: err && typeof err.code === 'string' ? err.code : undefined,
18
+ });
19
+ });
20
+ if (input !== undefined) child.stdin.end(input);
21
+ });
22
+ }
23
+
24
+ /** Absolute path of a program on PATH, or null. */
25
+ export function which(bin, env = process.env) {
26
+ for (const dir of (env.PATH ?? '').split(delimiter)) {
27
+ if (!dir) continue;
28
+ const p = join(dir, bin);
29
+ try { accessSync(p, constants.X_OK); return p; } catch { /* next */ }
30
+ }
31
+ return null;
32
+ }
33
+
34
+ export function readJson(path, fallback = null) {
35
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return fallback; }
36
+ }
37
+
38
+ export function parseJson(text) {
39
+ try { return JSON.parse(text); } catch { return null; }
40
+ }
41
+
42
+ /** Read a JSONL file into an array of objects, skipping bad lines. */
43
+ export function readJsonl(path) {
44
+ if (!existsSync(path)) return [];
45
+ const out = [];
46
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
47
+ if (!line.trim()) continue;
48
+ try { out.push(JSON.parse(line)); } catch { /* skip */ }
49
+ }
50
+ return out;
51
+ }
52
+
53
+ /** Minimal fixed-width table for terminal output. */
54
+ export function table(rows, columns) {
55
+ if (!rows.length) return '(nessuna riga)';
56
+ const cols = columns ?? Object.keys(rows[0]);
57
+ const cell = (v) => (v === null || v === undefined ? '—' : String(v));
58
+ const widths = cols.map((c) => Math.max(c.length, ...rows.map((r) => cell(r[c]).length)));
59
+ const line = (vals) => vals.map((v, i) => v.padEnd(widths[i])).join(' ').trimEnd();
60
+ return [line(cols), line(widths.map((w) => '-'.repeat(w))), ...rows.map((r) => line(cols.map((c) => cell(r[c]))))].join('\n');
61
+ }
62
+
63
+ export const EFFORT_ORDER = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
64
+
65
+ /** Keys that identify a person or account; stripped from anything harma stores or prints. */
66
+ const IDENTITY_KEYS = new Set([
67
+ 'accountEmail', 'signedInEmail', 'email', 'accountID', 'accountId', 'identity',
68
+ 'userId', 'user_id', 'organizationId', 'orgId', 'apiKey', 'api_key', 'token', 'cookie',
69
+ ]);
70
+
71
+ export function stripIdentity(value) {
72
+ if (Array.isArray(value)) return value.map(stripIdentity);
73
+ if (value && typeof value === 'object') {
74
+ const out = {};
75
+ for (const [k, v] of Object.entries(value)) {
76
+ if (IDENTITY_KEYS.has(k)) continue;
77
+ out[k] = stripIdentity(v);
78
+ }
79
+ return out;
80
+ }
81
+ return value;
82
+ }
83
+
84
+ export class HarmaError extends Error {
85
+ constructor(message, { exitCode = 1, hint } = {}) {
86
+ super(message);
87
+ this.exitCode = exitCode;
88
+ this.hint = hint;
89
+ }
90
+ }