sprag-cli 3.100.0 → 3.101.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/bin/cli.js +8 -1
- package/package.json +1 -1
- package/src/claude-price.js +63 -7
- package/src/cost.js +2 -2
- package/src/gateway-price-history.js +128 -0
- package/src/litellm-models.js +13 -5
- package/src/model-share.js +2 -2
- package/src/month-spend.js +43 -11
- package/src/net-saving.js +47 -0
- package/src/openai-prices.js +7 -3
- package/src/parser.js +40 -4
- package/src/route-scan.js +34 -12
- package/src/savings-ledger.js +118 -6
- package/src/session-cache.js +8 -1
- package/src/team-sync.js +2 -2
- package/src/usage-ledger.js +118 -0
package/bin/cli.js
CHANGED
|
@@ -934,10 +934,17 @@ async function main() {
|
|
|
934
934
|
: await parseAllSessions({ days: Math.max(1, Math.ceil(daysNeeded)), projectFilter, sinceMs: since });
|
|
935
935
|
// 월 경계에 걸친 세션은 월초 이후 요청만 남긴다. 그러지 않으면 1일 자정을
|
|
936
936
|
// 넘긴 세션의 전월분이 이번 달 지출에 그대로 들어온다.
|
|
937
|
-
monthSpendInfo = monthSpend(await sessionsSince(monthSessions, since));
|
|
937
|
+
monthSpendInfo = monthSpend(await sessionsSince(monthSessions, since), new Date(), { ledger: !projectFilter });
|
|
938
938
|
} catch (e) {
|
|
939
939
|
debug('month-spend', e);
|
|
940
940
|
}
|
|
941
|
+
// 사용량 장부: Claude Code 가 transcript 를 지운 뒤에도 월 지출이 줄지 않도록
|
|
942
|
+
// 토큰을 일자별로 남긴다(#15). 실패해도 통계선은 그대로 그린다.
|
|
943
|
+
try {
|
|
944
|
+
if (monthSessions) (await import('../src/usage-ledger.js')).recordUsage(monthSessions);
|
|
945
|
+
} catch (e) {
|
|
946
|
+
debug('usage-ledger', e);
|
|
947
|
+
}
|
|
941
948
|
}
|
|
942
949
|
|
|
943
950
|
// 모델별 사용 비중: `sprag saved` 와 같은 기간(라우팅 초기화 기록, 없으면 월초)의
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.101.0",
|
|
4
4
|
"description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/claude-price.js
CHANGED
|
@@ -10,17 +10,54 @@ import { estimateCost, estimateCostAcross } from './cost.js';
|
|
|
10
10
|
import { gatewayPriceFor } from './litellm-models.js';
|
|
11
11
|
import { gatewayBase } from './gateway-auth.js';
|
|
12
12
|
|
|
13
|
-
// `at` is when the tokens were spent; list prices
|
|
13
|
+
// `at` is when the tokens were spent; list prices and gateway prices (from the
|
|
14
|
+
// gateway's dated price history) are looked up for that time.
|
|
14
15
|
export function sessionCost(totals, model, { env = process.env, now, at } = {}) {
|
|
15
16
|
if (!gatewayBase(env)) return estimateCost(totals, model, { at });
|
|
16
|
-
const price = gatewayPriceFor(model, env, now);
|
|
17
|
+
const price = gatewayPriceFor(model, env, now, at);
|
|
17
18
|
return price ? estimateCost(totals, model, { price }) : null;
|
|
18
19
|
}
|
|
19
20
|
|
|
20
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* Several totals folded into one, `long` included. Returns the entry itself
|
|
23
|
+
* for a list of one.
|
|
24
|
+
*/
|
|
25
|
+
export function sumTotals(list) {
|
|
26
|
+
if (list.length === 1) return list[0];
|
|
27
|
+
const out = {};
|
|
28
|
+
for (const t of list) {
|
|
29
|
+
for (const [k, v] of Object.entries(t)) {
|
|
30
|
+
if (k === 'long') {
|
|
31
|
+
out.long = out.long || {};
|
|
32
|
+
for (const [lk, lv] of Object.entries(v)) out.long[lk] = (out.long[lk] || 0) + lv;
|
|
33
|
+
} else out[k] = (out[k] || 0) + v;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* One priced part per model that spent tokens, or the whole at its one model.
|
|
41
|
+
* `at` is when the tokens were spent (the start of the session or run) and
|
|
42
|
+
* `byDay` holds that model's totals per UTC day, present only when the
|
|
43
|
+
* session or run crossed a UTC midnight. Price rows change at UTC midnight,
|
|
44
|
+
* so partCost prices each day at its own row instead of one row for all (#15).
|
|
45
|
+
*/
|
|
21
46
|
function partsByModel(x) {
|
|
22
|
-
|
|
23
|
-
|
|
47
|
+
const t = x.startTime || x.endTime;
|
|
48
|
+
const at = t ? new Date(t).getTime() : undefined;
|
|
49
|
+
const dayTotals = x.dayTotals;
|
|
50
|
+
const dayParts = (model, only) => {
|
|
51
|
+
if (!dayTotals) return {};
|
|
52
|
+
const byDay = {};
|
|
53
|
+
for (const [day, models] of Object.entries(dayTotals)) {
|
|
54
|
+
const hit = only ? models[model] : sumTotals(Object.values(models));
|
|
55
|
+
if (hit) byDay[day] = hit;
|
|
56
|
+
}
|
|
57
|
+
return Object.keys(byDay).length ? { byDay } : {};
|
|
58
|
+
};
|
|
59
|
+
if (!x.modelTotals) return [{ totals: x.totals, model: x.model, at, ...dayParts(x.model, false) }];
|
|
60
|
+
return Object.entries(x.modelTotals).map(([model, totals]) => ({ totals, model, at, ...dayParts(model, true) }));
|
|
24
61
|
}
|
|
25
62
|
|
|
26
63
|
/**
|
|
@@ -38,11 +75,30 @@ export function pricedParts(session) {
|
|
|
38
75
|
];
|
|
39
76
|
}
|
|
40
77
|
|
|
78
|
+
/**
|
|
79
|
+
* Cost of one priced part. A part that crossed UTC midnights is priced day by
|
|
80
|
+
* day, each day at the price row in effect then; the figures are summed. One
|
|
81
|
+
* unpriced day makes the whole part unpriced (null), as for a single price.
|
|
82
|
+
* Without `byDay` the part is priced at its start time.
|
|
83
|
+
*/
|
|
84
|
+
export function partCost(part, { env = process.env, now } = {}) {
|
|
85
|
+
if (!part.byDay) return sessionCost(part.totals, part.model, { env, now, at: part.at });
|
|
86
|
+
const acc = { actual: 0, noCacheCost: 0, savings: 0, scenario5mCost: 0, extraCostIf5m: 0, extraCostIf5mApplicable: false, tier: null };
|
|
87
|
+
for (const day of Object.keys(part.byDay).sort()) {
|
|
88
|
+
const c = sessionCost(part.byDay[day], part.model, { env, now, at: `${day}T12:00:00Z` });
|
|
89
|
+
if (!c) return null;
|
|
90
|
+
for (const k of ['actual', 'noCacheCost', 'savings', 'scenario5mCost', 'extraCostIf5m']) acc[k] += c[k];
|
|
91
|
+
acc.extraCostIf5mApplicable = acc.extraCostIf5mApplicable || c.extraCostIf5mApplicable;
|
|
92
|
+
acc.tier = c.tier;
|
|
93
|
+
}
|
|
94
|
+
return { ...acc, savingsRate: acc.noCacheCost > 0 ? acc.savings / acc.noCacheCost : 0 };
|
|
95
|
+
}
|
|
96
|
+
|
|
41
97
|
/** Like estimateCostAcross, plus how many priced parts (a session, a subagent run, or one model's share of either) had no price and were left out. */
|
|
42
98
|
export function sessionCostAcross(sessions, opts = {}) {
|
|
43
99
|
let unpriced = 0;
|
|
44
|
-
const total = estimateCostAcross((sessions || []).flatMap(pricedParts), (totals, model) => {
|
|
45
|
-
const c =
|
|
100
|
+
const total = estimateCostAcross((sessions || []).flatMap(pricedParts), (totals, model, part) => {
|
|
101
|
+
const c = partCost(part, opts);
|
|
46
102
|
if (!c) unpriced++;
|
|
47
103
|
return c;
|
|
48
104
|
});
|
package/src/cost.js
CHANGED
|
@@ -566,13 +566,13 @@ function estimateCostAtPrice(totals, price) {
|
|
|
566
566
|
* Sessions whose model has no known rate are skipped, as month-spend does.
|
|
567
567
|
* `estimate` lets a caller price by path (see claude-price.js); null skips a session.
|
|
568
568
|
*/
|
|
569
|
-
export function estimateCostAcross(sessions, estimate = estimateCost) {
|
|
569
|
+
export function estimateCostAcross(sessions, estimate = (totals, model) => estimateCost(totals, model)) {
|
|
570
570
|
const acc = { actual: 0, noCacheCost: 0, scenario5mCost: 0, extraCostIf5mApplicable: false };
|
|
571
571
|
const tiers = new Map();
|
|
572
572
|
for (const s of sessions || []) {
|
|
573
573
|
if (!s?.totals) continue;
|
|
574
574
|
let c;
|
|
575
|
-
try { c = estimate(s.totals, s.model); } catch { continue; }
|
|
575
|
+
try { c = estimate(s.totals, s.model, s); } catch { continue; }
|
|
576
576
|
if (!c) continue;
|
|
577
577
|
acc.actual += c.actual;
|
|
578
578
|
acc.noCacheCost += c.noCacheCost;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* gateway-price-history: dated copies of a LiteLLM gateway's price table (#15).
|
|
3
|
+
*
|
|
4
|
+
* `/model/info` only reports today's prices, so a figure for past usage priced
|
|
5
|
+
* from the current table drifts whenever the gateway changes a price. Every
|
|
6
|
+
* successful refresh is recorded here instead, and a call is priced with the
|
|
7
|
+
* table in effect when it happened.
|
|
8
|
+
*
|
|
9
|
+
* File: <userDataDir>/gateway-price-history.json
|
|
10
|
+
* { "version": 1,
|
|
11
|
+
* "gateways": { "<base>": { "checkedAt": <ms of the latest successful fetch>,
|
|
12
|
+
* "rows": [ { "from": "YYYY-MM-DD", "prices": {...} } ] } } }
|
|
13
|
+
* Rows are oldest first; `from` is the UTC day of the fetch that first showed
|
|
14
|
+
* those prices. A row is appended only when the prices changed, and a fetch on
|
|
15
|
+
* the day of the last row replaces it.
|
|
16
|
+
*
|
|
17
|
+
* Same principle as the rest of the gateway path: only the gateway's own
|
|
18
|
+
* numbers are used and a model its table lacks stays unpriced (null). Prices
|
|
19
|
+
* for a time later than `checkedAt + PRICE_MAX_AGE_MS` are unknown, the same
|
|
20
|
+
* freshness rule the current table follows.
|
|
21
|
+
*
|
|
22
|
+
* An install that refreshed before this file existed has its table in
|
|
23
|
+
* profile-map.json (`gateway.prices`). That table stands in as a single row
|
|
24
|
+
* from its `fetchedAt` day until the history has an entry for the gateway.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
28
|
+
import { join } from 'node:path';
|
|
29
|
+
import { userDataDir } from './paths.js';
|
|
30
|
+
import { writeStateFile } from './state-file.js';
|
|
31
|
+
import { PRICE_MAX_AGE_MS } from './gateway-prices.js';
|
|
32
|
+
import { loadProfileMap } from './model-alias.js';
|
|
33
|
+
import { normalizeCandidate } from './litellm-models.js';
|
|
34
|
+
|
|
35
|
+
export const HISTORY_VERSION = 1;
|
|
36
|
+
|
|
37
|
+
export function priceHistoryPath() {
|
|
38
|
+
return join(userDataDir(), 'gateway-price-history.json');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const dayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
42
|
+
|
|
43
|
+
// Sorted keys at every level, so equal tables compare equal whatever order the gateway listed them in.
|
|
44
|
+
function canonical(value) {
|
|
45
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
|
46
|
+
if (value && typeof value === 'object') {
|
|
47
|
+
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`;
|
|
48
|
+
}
|
|
49
|
+
return JSON.stringify(value) ?? 'null';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let cache = null; // { path, mtimeMs, size, data }
|
|
53
|
+
|
|
54
|
+
function readHistory() {
|
|
55
|
+
const path = priceHistoryPath();
|
|
56
|
+
try {
|
|
57
|
+
const st = statSync(path);
|
|
58
|
+
if (cache && cache.path === path && cache.mtimeMs === st.mtimeMs && cache.size === st.size) return cache.data;
|
|
59
|
+
const data = JSON.parse(readFileSync(path, 'utf8'));
|
|
60
|
+
const ok = data && data.version === HISTORY_VERSION && data.gateways && typeof data.gateways === 'object';
|
|
61
|
+
const out = ok ? data : { version: HISTORY_VERSION, gateways: {} };
|
|
62
|
+
cache = { path, mtimeMs: st.mtimeMs, size: st.size, data: out };
|
|
63
|
+
return out;
|
|
64
|
+
} catch {
|
|
65
|
+
return { version: HISTORY_VERSION, gateways: {} };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The table profile-map.json holds for `base`, as a one-row history, or null. */
|
|
70
|
+
function seedEntry(base) {
|
|
71
|
+
try {
|
|
72
|
+
const gw = loadProfileMap()?.gateway;
|
|
73
|
+
if (!gw || gw.base !== base || !gw.prices || typeof gw.prices !== 'object') return null;
|
|
74
|
+
const fetchedAt = Date.parse(gw.fetchedAt);
|
|
75
|
+
if (!Number.isFinite(fetchedAt)) return null;
|
|
76
|
+
return { checkedAt: fetchedAt, rows: [{ from: dayOf(fetchedAt), prices: gw.prices }] };
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Record a successful fetch of `base`'s table. Appends a row only when the
|
|
84
|
+
* prices differ from the last row; on the same UTC day as the last row the row
|
|
85
|
+
* is replaced instead. Call it before the profile-map section is overwritten:
|
|
86
|
+
* for a gateway the history has not seen yet, the table still stored there is
|
|
87
|
+
* kept as the first row, so the prices known before this fetch are not lost.
|
|
88
|
+
*/
|
|
89
|
+
export function recordGatewayPrices(base, prices, fetchedAtMs = Date.now()) {
|
|
90
|
+
if (!base || !prices || typeof prices !== 'object' || !Number.isFinite(fetchedAtMs)) return;
|
|
91
|
+
const data = readHistory();
|
|
92
|
+
const gateways = { ...data.gateways };
|
|
93
|
+
const prev = gateways[base] && Array.isArray(gateways[base].rows) ? gateways[base] : seedEntry(base);
|
|
94
|
+
const rows = prev ? prev.rows.map((r) => ({ from: r.from, prices: r.prices })) : [];
|
|
95
|
+
const from = dayOf(fetchedAtMs);
|
|
96
|
+
const last = rows[rows.length - 1];
|
|
97
|
+
if (!last || canonical(last.prices) !== canonical(prices)) {
|
|
98
|
+
if (last && last.from === from) rows[rows.length - 1] = { from, prices };
|
|
99
|
+
else rows.push({ from, prices });
|
|
100
|
+
}
|
|
101
|
+
gateways[base] = { checkedAt: fetchedAtMs, rows };
|
|
102
|
+
writeStateFile(priceHistoryPath(), JSON.stringify({ version: HISTORY_VERSION, gateways }) + '\n');
|
|
103
|
+
cache = null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Price of `model` on `base` at time `at` (ms or ISO string): the newest row
|
|
108
|
+
* whose day is not after the UTC day of `at`, or the first row for an earlier
|
|
109
|
+
* time. null when the gateway has no history, `at` is later than the freshness
|
|
110
|
+
* limit, or that row lacks the model (or lists it as ambiguous).
|
|
111
|
+
*/
|
|
112
|
+
export function gatewayPriceAt(model, base, at) {
|
|
113
|
+
if (!base || typeof model !== 'string' || !model) return null;
|
|
114
|
+
const t = typeof at === 'number' ? at : Date.parse(at);
|
|
115
|
+
if (!Number.isFinite(t)) return null;
|
|
116
|
+
const entry = readHistory().gateways[base] ?? seedEntry(base);
|
|
117
|
+
if (!entry || !Array.isArray(entry.rows) || entry.rows.length === 0) return null;
|
|
118
|
+
if (!Number.isFinite(entry.checkedAt) || t > entry.checkedAt + PRICE_MAX_AGE_MS) return null;
|
|
119
|
+
const day = dayOf(t);
|
|
120
|
+
let row = entry.rows[0];
|
|
121
|
+
for (const r of entry.rows) if (r.from <= day) row = r;
|
|
122
|
+
const prices = row?.prices;
|
|
123
|
+
if (!prices || typeof prices !== 'object') return null;
|
|
124
|
+
for (const key of [model, normalizeCandidate(model)]) {
|
|
125
|
+
if (key && Object.hasOwn(prices, key)) return prices[key] || null;
|
|
126
|
+
}
|
|
127
|
+
return null;
|
|
128
|
+
}
|
package/src/litellm-models.js
CHANGED
|
@@ -29,6 +29,7 @@ import { loadProfileMap, updateProfileMap, resetModelAliasCache, profileIdFrom,
|
|
|
29
29
|
import { isRecognizedModelId } from './cost.js';
|
|
30
30
|
import { deploymentPrice, mergePrices, PRICE_MAX_AGE_MS } from './gateway-prices.js';
|
|
31
31
|
import { debug } from './debug.js';
|
|
32
|
+
import { recordGatewayPrices, gatewayPriceAt } from './gateway-price-history.js';
|
|
32
33
|
|
|
33
34
|
/** 게이트웨이 모델 맵의 신선도 기준. 배포 구성은 하루에 여러 번 바뀌지 않습니다. */
|
|
34
35
|
export const MODEL_MAP_TTL_MS = 24 * 60 * 60 * 1000;
|
|
@@ -58,7 +59,7 @@ const PROVIDER_PREFIXES = ['bedrock/converse/', 'bedrock/', 'openai/', 'vertex_a
|
|
|
58
59
|
* 줄이지 않으면 isRecognizedModelId()가 계열명을 품은 ARN 전체를 "인식됨"으로
|
|
59
60
|
* 판정해(cost.js의 정규식 한 줄이므로) 계정 ID가 값 쪽으로도 새어 나갑니다.
|
|
60
61
|
*/
|
|
61
|
-
function normalizeCandidate(id) {
|
|
62
|
+
export function normalizeCandidate(id) {
|
|
62
63
|
if (typeof id !== 'string' || !id) return '';
|
|
63
64
|
let s = id;
|
|
64
65
|
if (isGatewayModelId(s)) return profileIdFrom(s) || '';
|
|
@@ -180,9 +181,12 @@ export function deriveGatewayPrices(payload) {
|
|
|
180
181
|
/**
|
|
181
182
|
* LiteLLM 경로로 나간 호출의 모델 가격(토큰당 USD). 게이트웨이 표에 없거나,
|
|
182
183
|
* 표가 PRICE_MAX_AGE_MS보다 오래됐거나, 키가 모호하면 null입니다. 정가표로
|
|
183
|
-
* 대신 채우지 않습니다. 호출이 실제로 지난 경로의 가격만 씁니다.
|
|
184
|
+
* 대신 채우지 않습니다. 호출이 실제로 지난 경로의 가격만 씁니다. `at`(호출 시각)이
|
|
185
|
+
* 있으면 그 시각에 적용되던 표를 gateway-price-history.js에서 찾습니다.
|
|
184
186
|
*/
|
|
185
|
-
export function gatewayPriceFor(model, env = process.env, now = Date.now()) {
|
|
187
|
+
export function gatewayPriceFor(model, env = process.env, now = Date.now(), at) {
|
|
188
|
+
// With `at`, the price is the one in effect then, from the dated history (#15).
|
|
189
|
+
if (at !== undefined && at !== null) return gatewayPriceAt(model, gatewayBase(env), at);
|
|
186
190
|
const gateway = readGatewayModelMap(env);
|
|
187
191
|
if (!gateway?.prices || typeof gateway.prices !== 'object') return null;
|
|
188
192
|
const fetchedAt = Date.parse(gateway.fetchedAt);
|
|
@@ -295,12 +299,16 @@ export async function refreshGatewayModelMap({ base, key, fetchImpl = fetch } =
|
|
|
295
299
|
// gateway 절만 갱신합니다. updateProfileMap이 쓰기 직전에 파일을 다시 읽어
|
|
296
300
|
// 병합하므로, 이 네트워크 호출이 오가는 동안 route-scan의 학습 경로가
|
|
297
301
|
// learned를 기록했더라도 그 결과를 지우지 않습니다. 반대 방향도 같습니다.
|
|
302
|
+
const fetchedAt = Date.now();
|
|
303
|
+
const prices = deriveGatewayPrices(payload);
|
|
304
|
+
// 날짜별 가격 이력에 먼저 남깁니다(옛 표가 아직 profile-map에 있을 때). 이력은 부가 기록이라 실패해도 갱신은 계속합니다.
|
|
305
|
+
try { recordGatewayPrices(base, prices, fetchedAt); } catch (e) { debug('litellm-models:price-history', e); }
|
|
298
306
|
updateProfileMap({
|
|
299
307
|
gateway: {
|
|
300
308
|
base,
|
|
301
|
-
fetchedAt: new Date().toISOString(),
|
|
309
|
+
fetchedAt: new Date(fetchedAt).toISOString(),
|
|
302
310
|
aliases: result.aliases,
|
|
303
|
-
prices
|
|
311
|
+
prices,
|
|
304
312
|
skipped: result.skipped,
|
|
305
313
|
count: result.count,
|
|
306
314
|
},
|
package/src/model-share.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* "Same period" as `sprag saved`: the routing reset mark, or the start of the
|
|
6
6
|
* calendar month when nothing was ever reset, capped at 90 days of parsing.
|
|
7
7
|
*/
|
|
8
|
-
import { pricedParts,
|
|
8
|
+
import { pricedParts, partCost } from './claude-price.js';
|
|
9
9
|
import { modelFamily } from './savings-ledger.js';
|
|
10
10
|
import { readResetMarks } from './saved-reset.cjs';
|
|
11
11
|
import { RESET, RED, GREEN, YELLOW, CYAN, MAGENTA, GRAY } from './formatters/statusline.js';
|
|
@@ -84,7 +84,7 @@ export function computeModelShare(sessions, { env = process.env } = {}) {
|
|
|
84
84
|
for (const part of pricedParts(s)) {
|
|
85
85
|
if (!part || !part.totals) continue;
|
|
86
86
|
let cost = null;
|
|
87
|
-
try { cost =
|
|
87
|
+
try { cost = partCost(part, { env }); } catch { cost = null; }
|
|
88
88
|
if (!cost || !Number.isFinite(cost.actual)) { unpriced++; continue; }
|
|
89
89
|
const family = modelFamily(part.model);
|
|
90
90
|
all.set(family, (all.get(family) || 0) + cost.actual);
|
package/src/month-spend.js
CHANGED
|
@@ -7,9 +7,12 @@
|
|
|
7
7
|
* 다르므로 세션별로 호출 경로에 맞는 가격(sessionCost)을 적용해 합산합니다.
|
|
8
8
|
* LiteLLM 게이트웨이 세션은 게이트웨이 가격표로만 계산하고, 표에 없는 모델은
|
|
9
9
|
* 합계에서 빼고 unpriced 로 셉니다. 정가표로 대신 채우지 않습니다.
|
|
10
|
+
* 가격은 토큰을 쓴 날 기준입니다. 가격표는 UTC 자정에 바뀌므로 오늘 단가로
|
|
11
|
+
* 계산하면 가격이 바뀔 때 지난 지출까지 달라집니다(#15).
|
|
10
12
|
*/
|
|
11
13
|
|
|
12
|
-
import {
|
|
14
|
+
import { partCost, pricedParts } from './claude-price.js';
|
|
15
|
+
import { usageSince } from './usage-ledger.js';
|
|
13
16
|
|
|
14
17
|
/** 이번 달 1일 00:00(로컬)의 epoch ms. */
|
|
15
18
|
export function monthStartMs(now = new Date()) {
|
|
@@ -27,32 +30,61 @@ export function monthLabel(now = new Date()) {
|
|
|
27
30
|
* 호출하는 쪽이 parser.js 의 sessionsSince 로 월초 이후 요청만 남겨서
|
|
28
31
|
* 넘겨야 합니다. 그대로 넘기면 세션 전체가 이번 달 지출로 계산됩니다.
|
|
29
32
|
*
|
|
33
|
+
* Claude Code 가 transcript 를 지운 세션은 sessions 에 없으므로 사용량 장부
|
|
34
|
+
* (usage-ledger.js)에서 월초 이후 일자분을 더합니다. sessions 에 있는 세션과
|
|
35
|
+
* 그 서브에이전트 실행은 장부에서 빼서 두 번 세지 않습니다. 장부는 UTC 일자 단위라
|
|
36
|
+
* 월초가 UTC 날짜와 어긋나면 장부 전용 세션은 최대 하루치를 더 셀 수 있습니다.
|
|
37
|
+
* `ledger: false` 는 일부 프로젝트만 넘기는 호출처가 다른 프로젝트의 장부분을
|
|
38
|
+
* 섞지 않으려고 씁니다.
|
|
39
|
+
*
|
|
30
40
|
* @param {Array} sessions parseAllSessions 결과
|
|
31
41
|
* @param {Date} [now]
|
|
42
|
+
* @param {{ledger?: boolean}} [opts]
|
|
32
43
|
* @returns {{usd:number, sessions:number, unpriced:number, sinceMs:number, label:string}}
|
|
33
44
|
*/
|
|
34
|
-
export function monthSpend(sessions, now = new Date()) {
|
|
45
|
+
export function monthSpend(sessions, now = new Date(), { ledger = true } = {}) {
|
|
35
46
|
const since = monthStartMs(now);
|
|
36
47
|
let usd = 0;
|
|
37
48
|
let count = 0;
|
|
38
49
|
let unpriced = 0;
|
|
50
|
+
const price = (part) => {
|
|
51
|
+
try {
|
|
52
|
+
const c = partCost(part);
|
|
53
|
+
if (!c) { unpriced += 1; return false; }
|
|
54
|
+
usd += c.actual;
|
|
55
|
+
return true;
|
|
56
|
+
} catch {
|
|
57
|
+
// 단가를 모르는 모델은 합계에서 빠집니다. 통계선에서는 침묵이 낫습니다.
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const seen = new Set();
|
|
39
62
|
for (const s of sessions || []) {
|
|
63
|
+
if (s && s.sessionId) {
|
|
64
|
+
seen.add(s.sessionId);
|
|
65
|
+
for (const r of s.subagentRuns || []) if (r.agent) seen.add(`${s.sessionId}/${r.agent}`);
|
|
66
|
+
}
|
|
40
67
|
if (!s || !s.endTime || s.endTime.getTime() < since) continue;
|
|
41
68
|
if (!s.totals) continue;
|
|
42
|
-
// 세션이 띄운 서브에이전트 실행도 같은 청구서에
|
|
69
|
+
// 세션이 띄운 서브에이전트 실행도 같은 청구서에 들어가므로 실행마다 그 모델의
|
|
43
70
|
// 단가로 계산해 더합니다. 세션 수에는 넣지 않습니다.
|
|
44
71
|
let priced = false;
|
|
45
72
|
for (const part of pricedParts(s)) {
|
|
46
|
-
|
|
47
|
-
const c = sessionCost(part.totals, part.model);
|
|
48
|
-
if (!c) { unpriced += 1; continue; }
|
|
49
|
-
usd += c.actual;
|
|
50
|
-
if (part.own) priced = true;
|
|
51
|
-
} catch {
|
|
52
|
-
// 단가를 모르는 모델은 합계에서 빠집니다. 통계선에서는 침묵이 낫습니다.
|
|
53
|
-
}
|
|
73
|
+
if (price(part) && part.own) priced = true;
|
|
54
74
|
}
|
|
55
75
|
if (priced) count += 1;
|
|
56
76
|
}
|
|
77
|
+
if (ledger) {
|
|
78
|
+
try {
|
|
79
|
+
// 모델이 둘 이상인 장부 세션도 한 번만 세려고 id 로 모읍니다.
|
|
80
|
+
const ids = new Set();
|
|
81
|
+
for (const part of usageSince(since, { exclude: seen })) {
|
|
82
|
+
if (price(part) && part.own) ids.add(part.id);
|
|
83
|
+
}
|
|
84
|
+
count += ids.size;
|
|
85
|
+
} catch {
|
|
86
|
+
// 장부를 못 읽어도 transcript 기준 합계는 그대로 냅니다.
|
|
87
|
+
}
|
|
88
|
+
}
|
|
57
89
|
return { usd, sessions: count, unpriced, sinceMs: since, label: monthLabel(now) };
|
|
58
90
|
}
|
package/src/net-saving.js
CHANGED
|
@@ -131,3 +131,50 @@ export function netSavingV3({ calls, mainCtx, followUps, promptTokens, resultTok
|
|
|
131
131
|
// input and output. Split out so the savings page can show each term.
|
|
132
132
|
return { usd: cfWork + cfCarry - actual, cfWork, cfReread, cfCarry, overhead, actual, subActual };
|
|
133
133
|
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The v3 saving is linear in the main model's three rates, so a run can be
|
|
137
|
+
* stored as three token quantities and priced later at whatever rates applied
|
|
138
|
+
* when it ran (#15). With G = grow_last + the run's output and N = followUps:
|
|
139
|
+
* cacheRead = sum(mainCtx + grow_i) + G * N - R * N
|
|
140
|
+
* write = sum(newIn_i) (the first call's left out under skipFirstWrite) - R
|
|
141
|
+
* output = sum(out_i) - P
|
|
142
|
+
* and usd = cacheRead * rates.cacheRead + write * rates.write
|
|
143
|
+
* + output * rates.output - subActual (see savingFromQuantities).
|
|
144
|
+
* Same inputs and validation as netSavingV3, minus rates and subActual.
|
|
145
|
+
*
|
|
146
|
+
* @returns {{cacheRead:number,write:number,output:number}|null}
|
|
147
|
+
*/
|
|
148
|
+
export function netSavingQuantities({ calls, mainCtx, followUps, promptTokens, resultTokens, skipFirstWrite = false }) {
|
|
149
|
+
if (!Array.isArray(calls) || calls.length === 0) return null;
|
|
150
|
+
if (!calls.every((c) => c && isNum(c.ctx) && isNum(c.newIn) && isNum(c.out))) return null;
|
|
151
|
+
if (!isNum(mainCtx) || mainCtx <= 0) return null;
|
|
152
|
+
if (!isNum(followUps) || followUps < 0) return null;
|
|
153
|
+
if (!isNum(promptTokens) || promptTokens < 0) return null;
|
|
154
|
+
if (!isNum(resultTokens) || resultTokens < 0) return null;
|
|
155
|
+
|
|
156
|
+
const ctx1 = calls[0].ctx;
|
|
157
|
+
const grow = (c) => Math.max(0, c.ctx - ctx1);
|
|
158
|
+
let reread = 0;
|
|
159
|
+
let newIn = 0;
|
|
160
|
+
let totalOut = 0;
|
|
161
|
+
calls.forEach((c, i) => {
|
|
162
|
+
reread += mainCtx + grow(c);
|
|
163
|
+
if (!(skipFirstWrite && i === 0)) newIn += c.newIn;
|
|
164
|
+
totalOut += c.out;
|
|
165
|
+
});
|
|
166
|
+
const G = grow(calls[calls.length - 1]) + totalOut;
|
|
167
|
+
return {
|
|
168
|
+
cacheRead: reread + G * followUps - resultTokens * followUps,
|
|
169
|
+
write: newIn - resultTokens,
|
|
170
|
+
output: totalOut - promptTokens,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The v3 saving in USD from stored quantities; null when any input is not finite. */
|
|
175
|
+
export function savingFromQuantities(q, rates, subActual) {
|
|
176
|
+
if (!q || !isNum(q.cacheRead) || !isNum(q.write) || !isNum(q.output)) return null;
|
|
177
|
+
if (!rates || !isNum(rates.cacheRead) || !isNum(rates.write) || !isNum(rates.output)) return null;
|
|
178
|
+
if (!isNum(subActual)) return null;
|
|
179
|
+
return q.cacheRead * rates.cacheRead + q.write * rates.write + q.output * rates.output - subActual;
|
|
180
|
+
}
|
package/src/openai-prices.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
// OpenAI list prices for Codex calls that go straight to OpenAI (ChatGPT/OpenAI login).
|
|
2
2
|
// Source: https://developers.openai.com/api/docs/pricing , "Standard" tier, short-context
|
|
3
|
-
// rates, checked 2026-
|
|
3
|
+
// rates, checked 2026-11-07. Long-context surcharges are not modeled, so requests past the
|
|
4
4
|
// long-context threshold are under-priced. Calls through a LiteLLM gateway never use this table.
|
|
5
|
-
export const OPENAI_PRICES_CHECKED_AT = Date.parse('2026-
|
|
5
|
+
export const OPENAI_PRICES_CHECKED_AT = Date.parse('2026-11-07T00:00:00Z');
|
|
6
6
|
|
|
7
7
|
// Per-1M-token numbers as listed on the page; null where the page shows "-".
|
|
8
|
-
const PER_MILLION = {
|
|
8
|
+
export const PER_MILLION = {
|
|
9
9
|
'gpt-6-astra': [10, 1, 12.5, 50],
|
|
10
10
|
'gpt-6.1-sol': [2, 0.1, 2.5, 10],
|
|
11
|
+
'gpt-6.1-terra': [1, 0.05, 1.25, 5],
|
|
11
12
|
'gpt-6-luna': [0.1, 0.01, 0.125, 0.5],
|
|
12
13
|
'gpt-6-sol': [2, 0.2, 2.5, 10],
|
|
13
14
|
'gpt-5.6-sol': [4, 0.4, 5, 20],
|
|
@@ -23,6 +24,9 @@ const PER_MILLION = {
|
|
|
23
24
|
'gpt-5.2-pro': [21, null, null, 168],
|
|
24
25
|
'gpt-5.1': [1.25, 0.125, null, 10],
|
|
25
26
|
'gpt-5': [1.25, 0.125, null, 10],
|
|
27
|
+
'gpt-5-mini': [0.25, 0.025, null, 2],
|
|
28
|
+
'gpt-5-nano': [0.05, 0.005, null, 0.4],
|
|
29
|
+
'gpt-5-pro': [15, null, null, 120],
|
|
26
30
|
};
|
|
27
31
|
|
|
28
32
|
// Parse "<n>e-6" instead of dividing so 0.1 per 1M is exactly 1e-7, without float noise.
|
package/src/parser.js
CHANGED
|
@@ -105,7 +105,7 @@ export async function parseSessionFile(filePath) {
|
|
|
105
105
|
if (n > best) { best = n; model = m; }
|
|
106
106
|
}
|
|
107
107
|
if (best === 0 && reqs.length > 0) model = reqs[0].model || 'unknown';
|
|
108
|
-
const { totals, maxContextPerRequest, modelTotals } = sumRequests(reqs);
|
|
108
|
+
const { totals, maxContextPerRequest, modelTotals, dayTotals } = sumRequests(reqs);
|
|
109
109
|
|
|
110
110
|
return {
|
|
111
111
|
sessionId,
|
|
@@ -118,6 +118,7 @@ export async function parseSessionFile(filePath) {
|
|
|
118
118
|
maxContextPerRequest,
|
|
119
119
|
model,
|
|
120
120
|
...(modelTotals ? { modelTotals } : {}),
|
|
121
|
+
...(dayTotals ? { dayTotals } : {}),
|
|
121
122
|
gatewayObserved,
|
|
122
123
|
};
|
|
123
124
|
}
|
|
@@ -147,6 +148,8 @@ function addRequest(acc, r) {
|
|
|
147
148
|
}
|
|
148
149
|
}
|
|
149
150
|
|
|
151
|
+
const utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
152
|
+
|
|
150
153
|
/**
|
|
151
154
|
* Totals of a set of requests, plus the same totals split by model when more
|
|
152
155
|
* than one model spent tokens.
|
|
@@ -156,10 +159,20 @@ function addRequest(acc, r) {
|
|
|
156
159
|
* model's rate billed a Haiku stretch at the Fable rate, or the reverse. The
|
|
157
160
|
* split lets the cost side price each model's tokens at its own rate. It is
|
|
158
161
|
* left out for the usual single-model session, so those keep their old shape.
|
|
162
|
+
*
|
|
163
|
+
* `dayTotals` is the same split by UTC day and then model:
|
|
164
|
+
* `{ 'YYYY-MM-DD': { [model]: totals } }`. Price rows change at UTC midnight,
|
|
165
|
+
* so a session that runs across one must be priced day by day or a price
|
|
166
|
+
* change rewrites the part spent before it (#15). Like `modelTotals` it is
|
|
167
|
+
* left out for the usual case, here a set of requests inside one UTC day. A
|
|
168
|
+
* request without a timestamp is put on the earliest day known; with no
|
|
169
|
+
* timestamp anywhere there is no day to name and `dayTotals` is left out.
|
|
159
170
|
*/
|
|
160
171
|
function sumRequests(reqs) {
|
|
161
172
|
const totals = emptyTotals();
|
|
162
173
|
const byModel = new Map();
|
|
174
|
+
const timed = [];
|
|
175
|
+
const untimed = [];
|
|
163
176
|
let maxContextPerRequest = 0;
|
|
164
177
|
for (const r of reqs) {
|
|
165
178
|
addRequest(totals, r);
|
|
@@ -169,8 +182,26 @@ function sumRequests(reqs) {
|
|
|
169
182
|
const key = r.model || 'unknown';
|
|
170
183
|
if (!byModel.has(key)) byModel.set(key, emptyTotals());
|
|
171
184
|
addRequest(byModel.get(key), r);
|
|
185
|
+
(r.ts == null ? untimed : timed).push(r);
|
|
186
|
+
}
|
|
187
|
+
let dayTotals = null;
|
|
188
|
+
if (timed.length) {
|
|
189
|
+
const days = new Map();
|
|
190
|
+
const firstDay = utcDay(timed.reduce((m, r) => Math.min(m, r.ts), Infinity));
|
|
191
|
+
for (const r of [...timed, ...untimed]) {
|
|
192
|
+
const day = r.ts == null ? firstDay : utcDay(r.ts);
|
|
193
|
+
if (!days.has(day)) days.set(day, new Map());
|
|
194
|
+
const models = days.get(day);
|
|
195
|
+
const key = r.model || 'unknown';
|
|
196
|
+
if (!models.has(key)) models.set(key, emptyTotals());
|
|
197
|
+
addRequest(models.get(key), r);
|
|
198
|
+
}
|
|
199
|
+
if (days.size > 1) {
|
|
200
|
+
dayTotals = {};
|
|
201
|
+
for (const day of [...days.keys()].sort()) dayTotals[day] = Object.fromEntries(days.get(day));
|
|
202
|
+
}
|
|
172
203
|
}
|
|
173
|
-
return { totals, maxContextPerRequest, modelTotals: byModel.size > 1 ? Object.fromEntries(byModel) : null };
|
|
204
|
+
return { totals, maxContextPerRequest, modelTotals: byModel.size > 1 ? Object.fromEntries(byModel) : null, dayTotals };
|
|
174
205
|
}
|
|
175
206
|
|
|
176
207
|
/**
|
|
@@ -429,7 +460,7 @@ function trimToCutoff(session, cutoffMs) {
|
|
|
429
460
|
if (firstTs === null || r.ts < firstTs) firstTs = r.ts;
|
|
430
461
|
if (lastTs === null || r.ts > lastTs) lastTs = r.ts;
|
|
431
462
|
}
|
|
432
|
-
const { totals, maxContextPerRequest, modelTotals } = sumRequests(reqs);
|
|
463
|
+
const { totals, maxContextPerRequest, modelTotals, dayTotals } = sumRequests(reqs);
|
|
433
464
|
return {
|
|
434
465
|
sessionId: session.sessionId,
|
|
435
466
|
filePath: session.filePath,
|
|
@@ -441,6 +472,7 @@ function trimToCutoff(session, cutoffMs) {
|
|
|
441
472
|
maxContextPerRequest,
|
|
442
473
|
model: session.model,
|
|
443
474
|
...(modelTotals ? { modelTotals } : {}),
|
|
475
|
+
...(dayTotals ? { dayTotals } : {}),
|
|
444
476
|
gatewayObserved: session.gatewayObserved,
|
|
445
477
|
};
|
|
446
478
|
}
|
|
@@ -520,8 +552,12 @@ export async function parseAllSessions(options = {}) {
|
|
|
520
552
|
}
|
|
521
553
|
}
|
|
522
554
|
if (!run.requestCount || !run.endTime || run.endTime.getTime() < cutoffMs) continue;
|
|
555
|
+
// `agent` names the run for the usage ledger; `startTime` and `dayTotals`
|
|
556
|
+
// let the cost side price it at the rates of the days it ran (#15).
|
|
523
557
|
runs.push({ model: run.model, totals: run.totals, requestCount: run.requestCount, endTime: run.endTime,
|
|
524
|
-
|
|
558
|
+
agent: basename(a.path, '.jsonl'), startTime: run.startTime,
|
|
559
|
+
...(run.modelTotals ? { modelTotals: run.modelTotals } : {}),
|
|
560
|
+
...(run.dayTotals ? { dayTotals: run.dayTotals } : {}) });
|
|
525
561
|
} catch {
|
|
526
562
|
continue;
|
|
527
563
|
}
|
package/src/route-scan.js
CHANGED
|
@@ -22,12 +22,13 @@ import { join } from 'node:path';
|
|
|
22
22
|
import { userDataDir } from './paths.js';
|
|
23
23
|
import { discoverSessionFiles } from './parser.js';
|
|
24
24
|
import { collectSessionRecords, delegationContexts } from './session-records.js';
|
|
25
|
-
import { netSavingV3, unitRates, exactCost, priceSource } from './net-saving.js';
|
|
25
|
+
import { netSavingV3, netSavingQuantities, unitRates, exactCost, priceSource } from './net-saving.js';
|
|
26
26
|
import {
|
|
27
27
|
collectSubagentRuns, indexRuns, exactRunsForEpisode, fallbackRunsForEpisode,
|
|
28
28
|
} from './subagent-records.js';
|
|
29
29
|
import { modelRank, isRecognizedModelId, TIER_TARGET_RANK, tierForRank } from './cost.js';
|
|
30
30
|
import { sessionCost } from './claude-price.js';
|
|
31
|
+
import { gatewayBase } from './gateway-auth.js';
|
|
31
32
|
import { learnProfileMapping, resetModelAliasCache } from './model-alias.js';
|
|
32
33
|
import { modelRuleBaseText } from './model-rules.js';
|
|
33
34
|
import { RULE_CATEGORY_LABELS } from './rule-categories.js';
|
|
@@ -378,7 +379,7 @@ export function worthDelegating(tier, rank) {
|
|
|
378
379
|
* table lacks the model), which is unpriced, not zero.
|
|
379
380
|
*/
|
|
380
381
|
/** When a run spent its tokens, for the dated price lookup; undefined means now. */
|
|
381
|
-
const runTime = (run) => (Number.isFinite(run?.startedAt) ? run.startedAt : Number.isFinite(run?.endedAt) ? run.endedAt : undefined);
|
|
382
|
+
export const runTime = (run) => (Number.isFinite(run?.startedAt) ? run.startedAt : Number.isFinite(run?.endedAt) ? run.endedAt : undefined);
|
|
382
383
|
|
|
383
384
|
export function runSaving(run, mainModel, { env = process.env } = {}) {
|
|
384
385
|
if (!run.model || !mainModel) return null;
|
|
@@ -402,7 +403,10 @@ export function runSaving(run, mainModel, { env = process.env } = {}) {
|
|
|
402
403
|
* no price on either side) sends the run to the v2 formula instead, tagged
|
|
403
404
|
* basis 'v2', so the figure is never invented. null still means unpriced.
|
|
404
405
|
*
|
|
405
|
-
*
|
|
406
|
+
* On v3 the result also carries `main`, the main model's token quantities the
|
|
407
|
+
* saving is linear in (netSavingQuantities), which the ledger stores.
|
|
408
|
+
*
|
|
409
|
+
* @returns {{usd:number, basis:'v3'|'v2', main?:object, cfWork?:number, cfCarry?:number, overhead?:number}|null}
|
|
406
410
|
*/
|
|
407
411
|
export function runSavingDetail(run, mainModel, info, { env = process.env } = {}) {
|
|
408
412
|
if (!run.model || !mainModel) return null;
|
|
@@ -416,15 +420,16 @@ export function runSavingDetail(run, mainModel, info, { env = process.env } = {}
|
|
|
416
420
|
// A background launch returns only an acknowledgement; the report that
|
|
417
421
|
// follows is the run's final message.
|
|
418
422
|
const chars = info.resultChars + (info.async ? (run.finalChars || 0) : 0);
|
|
419
|
-
|
|
423
|
+
const inputs = {
|
|
420
424
|
calls: run.perCall,
|
|
421
425
|
mainCtx: info.C,
|
|
422
426
|
followUps: info.N,
|
|
423
427
|
promptTokens: info.P,
|
|
424
428
|
resultTokens: chars / 4,
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
429
|
+
};
|
|
430
|
+
const result = netSavingV3({ ...inputs, rates, subActual });
|
|
431
|
+
if (!result) return null;
|
|
432
|
+
return { ...result, main: netSavingQuantities(inputs) };
|
|
428
433
|
})();
|
|
429
434
|
if (v3) return { basis: 'v3', ...v3 };
|
|
430
435
|
const v2 = runSaving(run, mainModel, { env });
|
|
@@ -442,7 +447,7 @@ export function runCost(run) {
|
|
|
442
447
|
return actual ? actual.actual : null;
|
|
443
448
|
}
|
|
444
449
|
|
|
445
|
-
function runTotals(run) {
|
|
450
|
+
export function runTotals(run) {
|
|
446
451
|
return {
|
|
447
452
|
input: run.input,
|
|
448
453
|
cacheCreation: run.cacheCreation,
|
|
@@ -926,7 +931,7 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
|
|
|
926
931
|
// to show up: the first wrote the new baseline but billed against the old
|
|
927
932
|
// one, and the totals only settled on the second.
|
|
928
933
|
try {
|
|
929
|
-
const { recordDelegationEvents } = await import('./savings-ledger.js');
|
|
934
|
+
const { recordDelegationEvents, repriceDelegationLedger, priceLedgerEvent } = await import('./savings-ledger.js');
|
|
930
935
|
const { loadModelRules } = await import('./model-rules.js');
|
|
931
936
|
const fresh = loadModelRules().rules;
|
|
932
937
|
const priced = [];
|
|
@@ -947,9 +952,10 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
|
|
|
947
952
|
const detail = runSavingDetail(e.run, baseline, e.info);
|
|
948
953
|
// A loss is recorded too; only an unpriced run (null) has nothing to record.
|
|
949
954
|
if (!detail || !Number.isFinite(detail.usd)) continue;
|
|
950
|
-
|
|
955
|
+
const ts = e.run.endedAt ?? e.run.startedAt ?? Date.now();
|
|
956
|
+
const event = {
|
|
951
957
|
key: e.run.path,
|
|
952
|
-
ts
|
|
958
|
+
ts,
|
|
953
959
|
usd: detail.usd,
|
|
954
960
|
cost: runCost(e.run),
|
|
955
961
|
rule: rule.signature,
|
|
@@ -958,7 +964,22 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
|
|
|
958
964
|
basis: detail.basis,
|
|
959
965
|
priceSource: priceSource(),
|
|
960
966
|
baselineSource: fromEpisode ? 'episode' : 'rule',
|
|
961
|
-
}
|
|
967
|
+
};
|
|
968
|
+
// Every run is stored as token quantities, and its dollars come from
|
|
969
|
+
// them through the one function every reader uses (#15): a list run from
|
|
970
|
+
// the list table, a gateway run from that gateway's price history, with
|
|
971
|
+
// the gateway recorded so a later shell cannot change the path.
|
|
972
|
+
if (event.priceSource === 'gateway') event.gw = gatewayBase();
|
|
973
|
+
event.q = {
|
|
974
|
+
at: runTime(e.run) ?? ts,
|
|
975
|
+
sub: runTotals(e.run),
|
|
976
|
+
...(detail.basis === 'v3' && detail.main ? { main: detail.main } : {}),
|
|
977
|
+
};
|
|
978
|
+
const p = priceLedgerEvent(event);
|
|
979
|
+
if (!p) continue;
|
|
980
|
+
event.usd = p.usd;
|
|
981
|
+
event.cost = p.cost;
|
|
982
|
+
priced.push(event);
|
|
962
983
|
if (Array.isArray(trace)) {
|
|
963
984
|
trace.push({
|
|
964
985
|
key: e.run.path,
|
|
@@ -982,6 +1003,7 @@ export async function runRouteScan({ days = 14, trace = null } = {}) {
|
|
|
982
1003
|
}
|
|
983
1004
|
}
|
|
984
1005
|
recordDelegationEvents(priced);
|
|
1006
|
+
repriceDelegationLedger();
|
|
985
1007
|
} catch {
|
|
986
1008
|
// ledger write failure only delays the statusline totals, never the scan
|
|
987
1009
|
}
|
package/src/savings-ledger.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* File: <userDataDir>/delegation-ledger.json
|
|
12
12
|
* { "version": 3,
|
|
13
13
|
* "events": { "<run path>": { "ts", "usd", "cost", "rule", "from", "to",
|
|
14
|
-
* "basis", "priceSource", "baselineSource" } } }
|
|
14
|
+
* "basis", "priceSource", "baselineSource", "gw", "q" } } }
|
|
15
15
|
*
|
|
16
16
|
* Version 3 prices a run on the net-saving basis (src/net-saving.js), and each
|
|
17
17
|
* event says how it was priced: `basis` 'v3' (cache re-reads and carried
|
|
@@ -22,6 +22,20 @@
|
|
|
22
22
|
* their value and read as basis v2; a rescan reprices those still inside the
|
|
23
23
|
* scan window as v3 and leaves the older ones alone.
|
|
24
24
|
*
|
|
25
|
+
* `q` holds the token quantities a run was priced from (#15):
|
|
26
|
+
* `at` (when the run spent its tokens), `sub` (the run's own token totals) and,
|
|
27
|
+
* on the v3 basis, `main` (cacheRead, write and output tokens of the main model,
|
|
28
|
+
* from src/net-saving.js). The dollars of such an event are computed from `q`
|
|
29
|
+
* every time the ledger is read, with the price in effect at `q.at`, so a
|
|
30
|
+
* corrected price table fixes the past; `usd` and `cost` stored beside it are
|
|
31
|
+
* only a cache of that figure. `q` is optional and the ledger stays version 3,
|
|
32
|
+
* so older sprag versions ignore it. A gateway event (`priceSource` 'gateway')
|
|
33
|
+
* also carries `gw`, the gateway address it went through, and is priced from
|
|
34
|
+
* that gateway's own price history (src/gateway-price-history.js) at `q.at`,
|
|
35
|
+
* never from the list table (stage 3 of #15). Events without `q` (written
|
|
36
|
+
* before it existed and outside the scan window), and gateway events without
|
|
37
|
+
* `gw`, keep their stored figure.
|
|
38
|
+
*
|
|
25
39
|
* `from`/`to` are the models the routing decision moved between, and `usd` is
|
|
26
40
|
* the price difference between them for this run's tokens. `cost` is what the
|
|
27
41
|
* run itself cost on the model it ran on, so the statusline can show what the
|
|
@@ -41,6 +55,8 @@ import { join } from 'node:path';
|
|
|
41
55
|
import { userDataDir } from './paths.js';
|
|
42
56
|
import { writeStateFile } from './state-file.js';
|
|
43
57
|
import { readResetMarks, isBeforeReset } from './saved-reset.cjs';
|
|
58
|
+
import { exactCost, unitRates, savingFromQuantities } from './net-saving.js';
|
|
59
|
+
import { gatewayBase } from './gateway-auth.js';
|
|
44
60
|
|
|
45
61
|
const WEEK_MS = 7 * 24 * 3600 * 1000;
|
|
46
62
|
const MONTH_MS = 30 * 24 * 3600 * 1000;
|
|
@@ -69,7 +85,52 @@ export function runIdentity(key) {
|
|
|
69
85
|
return i > 0 ? parts.slice(i - 1).join('/') : String(key);
|
|
70
86
|
}
|
|
71
87
|
|
|
72
|
-
|
|
88
|
+
/**
|
|
89
|
+
* What an event is worth, computed from its stored quantities `q` with the
|
|
90
|
+
* list price in effect at `q.at` (#15). { usd, cost } rounded like stored
|
|
91
|
+
* figures, or null when the event cannot be priced from quantities: no `q`, a
|
|
92
|
+
* gateway price, a missing model, or a model with no price. The empty env keeps
|
|
93
|
+
* a gateway set in the current shell from leaking into the list table.
|
|
94
|
+
*/
|
|
95
|
+
export function priceLedgerEvent(e) {
|
|
96
|
+
try {
|
|
97
|
+
const q = e?.q;
|
|
98
|
+
if (!q || typeof q !== 'object' || !q.sub || typeof q.sub !== 'object') return null;
|
|
99
|
+
if (!e.from || !e.to) return null;
|
|
100
|
+
// A list event is priced with an empty env so a gateway set in the current
|
|
101
|
+
// shell cannot leak in. A gateway event names its gateway (`gw`) and is
|
|
102
|
+
// priced from that gateway's price history only; without `gw` it keeps its
|
|
103
|
+
// stored dollars.
|
|
104
|
+
let env;
|
|
105
|
+
if (e.priceSource === 'list') env = {};
|
|
106
|
+
else if (e.priceSource === 'gateway' && typeof e.gw === 'string' && e.gw) env = { ANTHROPIC_BASE_URL: e.gw };
|
|
107
|
+
else return null;
|
|
108
|
+
if (e.priceSource === 'gateway' && !gatewayBase(env)) return null; // gw is the official endpoint, not a gateway
|
|
109
|
+
const at = Number.isFinite(q.at) ? q.at : Number.isFinite(e.ts) ? e.ts : undefined;
|
|
110
|
+
if (e.priceSource === 'gateway' && at === undefined) return null;
|
|
111
|
+
const cost = exactCost(q.sub, e.to, { env, at });
|
|
112
|
+
if (!Number.isFinite(cost)) return null;
|
|
113
|
+
let usd;
|
|
114
|
+
if (q.main) {
|
|
115
|
+
const rates = unitRates(e.from, { env, at });
|
|
116
|
+
usd = rates ? savingFromQuantities(q.main, rates, cost) : null;
|
|
117
|
+
} else {
|
|
118
|
+
const base = exactCost(q.sub, e.from, { env, at });
|
|
119
|
+
usd = Number.isFinite(base) ? base - cost : null;
|
|
120
|
+
}
|
|
121
|
+
if (!Number.isFinite(usd)) return null;
|
|
122
|
+
return { usd: roundUsd(usd), cost: roundUsd(cost) };
|
|
123
|
+
} catch {
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* `priced: false` returns the stored figures untouched; the writers use it so
|
|
130
|
+
* a write does not turn the read-time figures into stored ones (that is
|
|
131
|
+
* repriceDelegationLedger's job, which also marks the change for the team sync).
|
|
132
|
+
*/
|
|
133
|
+
export function loadLedger({ priced = true } = {}) {
|
|
73
134
|
try {
|
|
74
135
|
const data = JSON.parse(readFileSync(ledgerPath(), 'utf8'));
|
|
75
136
|
if (!data || typeof data.events !== 'object' || data.events === null) {
|
|
@@ -90,6 +151,14 @@ export function loadLedger() {
|
|
|
90
151
|
if (seen.has(id)) delete data.events[key];
|
|
91
152
|
else seen.add(id);
|
|
92
153
|
}
|
|
154
|
+
// Dollars come from the stored quantities at the price in effect when each
|
|
155
|
+
// run happened, so every reader sees the current price table's figure.
|
|
156
|
+
if (priced) {
|
|
157
|
+
for (const e of Object.values(data.events)) {
|
|
158
|
+
const p = e && priceLedgerEvent(e);
|
|
159
|
+
if (p) { e.usd = p.usd; e.cost = p.cost; }
|
|
160
|
+
}
|
|
161
|
+
}
|
|
93
162
|
return data;
|
|
94
163
|
} catch {
|
|
95
164
|
return { version: LEDGER_VERSION, events: {} };
|
|
@@ -98,7 +167,7 @@ export function loadLedger() {
|
|
|
98
167
|
|
|
99
168
|
/**
|
|
100
169
|
* Upsert saving events. `events` is an array of
|
|
101
|
-
* { key, ts, usd, cost, rule, from, to, basis, priceSource, baselineSource } where `key` is the run's transcript
|
|
170
|
+
* { key, ts, usd, cost, rule, from, to, basis, priceSource, baselineSource, gw, q } where `key` is the run's transcript
|
|
102
171
|
* path (unique per subagent run) and `from`/`to` name the models the routing
|
|
103
172
|
* decision moved between. `usd` is signed: a run on a pricier model is a loss
|
|
104
173
|
* and is recorded as a negative amount so it reduces the totals. Only
|
|
@@ -107,7 +176,7 @@ export function loadLedger() {
|
|
|
107
176
|
*/
|
|
108
177
|
export function recordDelegationEvents(events) {
|
|
109
178
|
if (!Array.isArray(events) || events.length === 0) return;
|
|
110
|
-
const data = loadLedger();
|
|
179
|
+
const data = loadLedger({ priced: false });
|
|
111
180
|
data.version = LEDGER_VERSION;
|
|
112
181
|
let changed = false;
|
|
113
182
|
// Earliest moment whose figures this call changed. A rescan that reprices or
|
|
@@ -129,7 +198,9 @@ export function recordDelegationEvents(events) {
|
|
|
129
198
|
// The same goes for the basis fields: a v2 event rescanned as v3 differs.
|
|
130
199
|
if (prev && prev.ts === e.ts && prev.usd === usd && prev.cost === cost
|
|
131
200
|
&& prev.basis === (e.basis || undefined) && prev.priceSource === (e.priceSource || undefined)
|
|
132
|
-
&& prev.baselineSource === (e.baselineSource || undefined)
|
|
201
|
+
&& prev.baselineSource === (e.baselineSource || undefined)
|
|
202
|
+
&& prev.gw === (e.gw || undefined)
|
|
203
|
+
&& JSON.stringify(prev.q) === JSON.stringify(e.q || undefined)) continue;
|
|
133
204
|
earliest = Math.min(earliest, e.ts, Number.isFinite(prev?.ts) ? prev.ts : Infinity);
|
|
134
205
|
if (prevKey !== e.key) delete data.events[prevKey];
|
|
135
206
|
keyOf.set(id, e.key);
|
|
@@ -143,6 +214,8 @@ export function recordDelegationEvents(events) {
|
|
|
143
214
|
...(e.basis ? { basis: e.basis } : {}),
|
|
144
215
|
...(e.priceSource ? { priceSource: e.priceSource } : {}),
|
|
145
216
|
...(e.baselineSource ? { baselineSource: e.baselineSource } : {}),
|
|
217
|
+
...(e.gw ? { gw: e.gw } : {}),
|
|
218
|
+
...(e.q ? { q: e.q } : {}),
|
|
146
219
|
};
|
|
147
220
|
changed = true;
|
|
148
221
|
}
|
|
@@ -158,6 +231,45 @@ export function recordDelegationEvents(events) {
|
|
|
158
231
|
}
|
|
159
232
|
}
|
|
160
233
|
|
|
234
|
+
/**
|
|
235
|
+
* Store the figures computed from quantities where they differ from the stored
|
|
236
|
+
* ones, and mark the change for the team sync. A price correction changes days
|
|
237
|
+
* the sync already uploaded, and nothing else would tell it to reach back that
|
|
238
|
+
* far. Reads the file as stored (not loadLedger's computed view), so it sees
|
|
239
|
+
* what was uploaded. Returns the number of events changed.
|
|
240
|
+
*/
|
|
241
|
+
export function repriceDelegationLedger() {
|
|
242
|
+
let data;
|
|
243
|
+
try {
|
|
244
|
+
data = JSON.parse(readFileSync(ledgerPath(), 'utf8'));
|
|
245
|
+
} catch {
|
|
246
|
+
return 0;
|
|
247
|
+
}
|
|
248
|
+
if (!data || typeof data.events !== 'object' || data.events === null || !READABLE_VERSIONS.has(data.version)) return 0;
|
|
249
|
+
let n = 0;
|
|
250
|
+
let earliest = Infinity;
|
|
251
|
+
for (const e of Object.values(data.events)) {
|
|
252
|
+
const p = e && priceLedgerEvent(e);
|
|
253
|
+
if (!p || (e.usd === p.usd && e.cost === p.cost)) continue;
|
|
254
|
+
e.usd = p.usd;
|
|
255
|
+
e.cost = p.cost;
|
|
256
|
+
n += 1;
|
|
257
|
+
if (Number.isFinite(e.ts)) earliest = Math.min(earliest, e.ts);
|
|
258
|
+
}
|
|
259
|
+
if (n === 0) return 0;
|
|
260
|
+
data.version = LEDGER_VERSION;
|
|
261
|
+
if (Number.isFinite(earliest)) {
|
|
262
|
+
data.changedSince = Math.min(Number.isFinite(data.changedSince) ? data.changedSince : Infinity, earliest);
|
|
263
|
+
data.changeSeq = (Number(data.changeSeq) || 0) + 1;
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
writeStateFile(ledgerPath(), JSON.stringify(data) + '\n');
|
|
267
|
+
} catch {
|
|
268
|
+
return 0;
|
|
269
|
+
}
|
|
270
|
+
return n;
|
|
271
|
+
}
|
|
272
|
+
|
|
161
273
|
/**
|
|
162
274
|
* The ledger's pending change mark, for the team sync: `since` is the earliest
|
|
163
275
|
* event time a recordDelegationEvents call changed after the last upload, and
|
|
@@ -183,7 +295,7 @@ export function changedSinceForSync() {
|
|
|
183
295
|
* then kept, so the next sync covers that change too.
|
|
184
296
|
*/
|
|
185
297
|
export function clearChangedSince(seq) {
|
|
186
|
-
const data = loadLedger();
|
|
298
|
+
const data = loadLedger({ priced: false });
|
|
187
299
|
if ((Number(data.changeSeq) || 0) !== seq) return false;
|
|
188
300
|
if (!Number.isFinite(data.changedSince) && data.changeTracking === 1) return false;
|
|
189
301
|
delete data.changedSince;
|
package/src/session-cache.js
CHANGED
|
@@ -40,7 +40,11 @@ const CACHE_PATH = join(userDataDir(), 'session-cache.json');
|
|
|
40
40
|
// tokens from requests whose prompt exceeds 100k, which Haiku 5.5 prices at a
|
|
41
41
|
// higher rate. A v4 entry lacks it, so a Haiku 5.5 session cached before the
|
|
42
42
|
// bump would keep being priced at the short rate until its transcript changed.
|
|
43
|
-
|
|
43
|
+
// 6: sessions spanning more than one UTC day carry `dayTotals` (totals per UTC
|
|
44
|
+
// day and model), so cost can use each day's price row (#15). A v5 entry lacks
|
|
45
|
+
// it, so a session crossing a price change would be priced at one day's rate
|
|
46
|
+
// until its transcript changed.
|
|
47
|
+
const CACHE_VERSION = 6;
|
|
44
48
|
// Entries for transcripts this old are pruned on write. Keeps the file
|
|
45
49
|
// bounded without an existence check per entry (which would cost the syscalls
|
|
46
50
|
// the cache exists to avoid).
|
|
@@ -57,6 +61,7 @@ const PRUNE_AFTER_MS = 90 * 24 * 60 * 60 * 1000;
|
|
|
57
61
|
* @property {number} maxContextPerRequest
|
|
58
62
|
* @property {string} model
|
|
59
63
|
* @property {Record<string, object>} [modelTotals] totals per model, present only when more than one model spent tokens
|
|
64
|
+
* @property {Record<string, Record<string, object>>} [dayTotals] totals per UTC day and model, present only when the requests span more than one UTC day
|
|
60
65
|
* @property {string} [projectDir]
|
|
61
66
|
*/
|
|
62
67
|
|
|
@@ -71,6 +76,7 @@ function serialize(session) {
|
|
|
71
76
|
maxContextPerRequest: session.maxContextPerRequest,
|
|
72
77
|
model: session.model,
|
|
73
78
|
...(session.modelTotals ? { modelTotals: session.modelTotals } : {}),
|
|
79
|
+
...(session.dayTotals ? { dayTotals: session.dayTotals } : {}),
|
|
74
80
|
gatewayObserved: !!session.gatewayObserved,
|
|
75
81
|
};
|
|
76
82
|
}
|
|
@@ -87,6 +93,7 @@ function deserialize(stored, filePath, projectDir) {
|
|
|
87
93
|
maxContextPerRequest: stored.maxContextPerRequest || 0,
|
|
88
94
|
model: stored.model || 'unknown',
|
|
89
95
|
...(stored.modelTotals && typeof stored.modelTotals === 'object' ? { modelTotals: stored.modelTotals } : {}),
|
|
96
|
+
...(stored.dayTotals && typeof stored.dayTotals === 'object' ? { dayTotals: stored.dayTotals } : {}),
|
|
90
97
|
gatewayObserved: !!stored.gatewayObserved,
|
|
91
98
|
};
|
|
92
99
|
}
|
package/src/team-sync.js
CHANGED
|
@@ -47,7 +47,7 @@ import { userLanguage } from './config.js';
|
|
|
47
47
|
import { debug } from './debug.js';
|
|
48
48
|
import { trustSystemCA } from './system-ca.js';
|
|
49
49
|
import { loadLedger, modelFamily, roundUsd, changedSinceForSync, clearChangedSince } from './savings-ledger.js';
|
|
50
|
-
import {
|
|
50
|
+
import { partCost, pricedParts } from './claude-price.js';
|
|
51
51
|
import { uploadPrompts, dropOffsets, promptOffsetsExist } from './team-prompts.js';
|
|
52
52
|
import { ruleStatsSummary } from './team-rule-stats.js';
|
|
53
53
|
import { rulesPullDue, syncTeamRatchet, ensureTeamImport } from './team-ratchet.js';
|
|
@@ -476,7 +476,7 @@ export async function aggregateDaily({
|
|
|
476
476
|
const d = get(dayKey(t));
|
|
477
477
|
for (const part of pricedParts(s)) {
|
|
478
478
|
try {
|
|
479
|
-
const c =
|
|
479
|
+
const c = partCost(part, { env });
|
|
480
480
|
if (!c) { d.unpriced += 1; continue; }
|
|
481
481
|
d.spent += c.actual;
|
|
482
482
|
if (!part.own) d.subagent += c.actual;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* usage-ledger: token usage per session, UTC day and model, kept after Claude
|
|
3
|
+
* Code deletes the transcript (#15).
|
|
4
|
+
*
|
|
5
|
+
* Month spend is computed from transcripts, and Claude Code removes old ones.
|
|
6
|
+
* A deleted session would drop out of the month's total and the figure would
|
|
7
|
+
* shrink for no reason. This file keeps the tokens (never dollars), so cost is
|
|
8
|
+
* still priced when it is read, at the price row of each day, and a later
|
|
9
|
+
* price correction applies to the history too.
|
|
10
|
+
*
|
|
11
|
+
* Shape: `{ version: 1, writtenAt, sessions: { [id]: { days: { 'YYYY-MM-DD':
|
|
12
|
+
* { [model]: totals } }, updatedAt } } }`. A subagent run is keyed
|
|
13
|
+
* `<session id>/<agent file>`. Days are UTC days, because price rows change at
|
|
14
|
+
* UTC midnight.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { readFileSync } from 'node:fs';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
import { userDataDir } from './paths.js';
|
|
20
|
+
import { writeStateFile } from './state-file.js';
|
|
21
|
+
import { sumTotals } from './claude-price.js';
|
|
22
|
+
import { debug } from './debug.js';
|
|
23
|
+
|
|
24
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
25
|
+
// Entries whose newest day is older than this are dropped on write.
|
|
26
|
+
const KEEP_DAYS = 400;
|
|
27
|
+
// The statusline calls this on every refresh; hourly is plenty for a history.
|
|
28
|
+
const THROTTLE_MS = 60 * 60 * 1000;
|
|
29
|
+
|
|
30
|
+
const ledgerPath = () => join(userDataDir(), 'usage-ledger.json');
|
|
31
|
+
const utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
32
|
+
|
|
33
|
+
function load() {
|
|
34
|
+
try {
|
|
35
|
+
const data = JSON.parse(readFileSync(ledgerPath(), 'utf8'));
|
|
36
|
+
if (data && data.version === 1 && data.sessions && typeof data.sessions === 'object') return data;
|
|
37
|
+
} catch (e) {
|
|
38
|
+
if (e && e.code !== 'ENOENT') debug('usage-ledger:load', e);
|
|
39
|
+
}
|
|
40
|
+
return { version: 1, sessions: {} };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** `{ day: { model: totals } }` of a parsed session or subagent run, or null when it has no usable time. */
|
|
44
|
+
function daysOf(x) {
|
|
45
|
+
if (!x) return null;
|
|
46
|
+
if (x.dayTotals) return x.dayTotals;
|
|
47
|
+
const t = x.startTime || x.endTime;
|
|
48
|
+
const ms = t ? new Date(t).getTime() : NaN;
|
|
49
|
+
if (!Number.isFinite(ms)) return null;
|
|
50
|
+
const models = x.modelTotals || (x.totals ? { [x.model || 'unknown']: x.totals } : null);
|
|
51
|
+
return models ? { [utcDay(ms)]: models } : null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Upsert the usage of the given sessions (and their subagent runs). Safe to
|
|
56
|
+
* repeat: an entry is replaced by what the transcript says now, day by day, so
|
|
57
|
+
* days only an earlier, wider parse knew about are kept. Skipped entirely when
|
|
58
|
+
* the file was written less than an hour ago. Returns true when it wrote.
|
|
59
|
+
*/
|
|
60
|
+
export function recordUsage(sessions, { now = Date.now() } = {}) {
|
|
61
|
+
const ledger = load();
|
|
62
|
+
const age = now - (ledger.writtenAt || 0);
|
|
63
|
+
if (ledger.writtenAt && age >= 0 && age < THROTTLE_MS) return false;
|
|
64
|
+
|
|
65
|
+
const upsert = (id, days) => {
|
|
66
|
+
if (!id || !days) return;
|
|
67
|
+
const old = ledger.sessions[id];
|
|
68
|
+
const merged = { ...(old ? old.days : {}), ...days };
|
|
69
|
+
if (old && JSON.stringify(old.days) === JSON.stringify(merged)) return;
|
|
70
|
+
ledger.sessions[id] = { days: merged, updatedAt: now };
|
|
71
|
+
};
|
|
72
|
+
for (const s of sessions || []) {
|
|
73
|
+
if (!s) continue;
|
|
74
|
+
upsert(s.sessionId, daysOf(s));
|
|
75
|
+
for (const r of s.subagentRuns || []) if (s.sessionId && r.agent) upsert(`${s.sessionId}/${r.agent}`, daysOf(r));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const oldest = utcDay(now - KEEP_DAYS * DAY_MS);
|
|
79
|
+
for (const [id, e] of Object.entries(ledger.sessions)) {
|
|
80
|
+
const newest = Object.keys(e.days || {}).sort().pop();
|
|
81
|
+
if (!newest || newest < oldest) delete ledger.sessions[id];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
ledger.writtenAt = now;
|
|
85
|
+
writeStateFile(ledgerPath(), JSON.stringify(ledger) + '\n');
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Ledger usage from the UTC day of `sinceMs` on, as parts that partCost can
|
|
91
|
+
* price (one per session and model). Entries named in `exclude` are skipped:
|
|
92
|
+
* the caller already has those from a live transcript. `own` is false for a
|
|
93
|
+
* subagent run, as for the parts pricedParts builds.
|
|
94
|
+
*/
|
|
95
|
+
export function usageSince(sinceMs, { exclude = new Set() } = {}) {
|
|
96
|
+
const sinceDay = utcDay(sinceMs);
|
|
97
|
+
const parts = [];
|
|
98
|
+
for (const [id, e] of Object.entries(load().sessions)) {
|
|
99
|
+
if (exclude.has(id)) continue;
|
|
100
|
+
const byModel = {};
|
|
101
|
+
for (const [day, models] of Object.entries(e.days || {})) {
|
|
102
|
+
if (day < sinceDay) continue;
|
|
103
|
+
for (const [model, totals] of Object.entries(models)) (byModel[model] ||= {})[day] = totals;
|
|
104
|
+
}
|
|
105
|
+
for (const [model, byDay] of Object.entries(byModel)) {
|
|
106
|
+
const days = Object.keys(byDay).sort();
|
|
107
|
+
parts.push({
|
|
108
|
+
id,
|
|
109
|
+
model,
|
|
110
|
+
totals: sumTotals(days.map((d) => byDay[d])),
|
|
111
|
+
at: Date.parse(`${days[0]}T12:00:00Z`),
|
|
112
|
+
byDay,
|
|
113
|
+
own: !id.includes('/'),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return parts;
|
|
118
|
+
}
|