@laoyuehanni/dsh-token-usage 0.3.7
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 +178 -0
- package/README.zh.md +182 -0
- package/cordis.patch.yml +7 -0
- package/lib/client/CostDeltaFlyLabel.d.ts +8 -0
- package/lib/client/CostDeltaFlyLabel.d.ts.map +1 -0
- package/lib/client/CostDeltaFlyLabel.js +24 -0
- package/lib/client/CostDeltaFlyLabel.js.map +1 -0
- package/lib/client/HitRateText.d.ts +21 -0
- package/lib/client/HitRateText.d.ts.map +1 -0
- package/lib/client/HitRateText.js +16 -0
- package/lib/client/HitRateText.js.map +1 -0
- package/lib/client/QuotaButton.d.ts +70 -0
- package/lib/client/QuotaButton.d.ts.map +1 -0
- package/lib/client/QuotaButton.js +346 -0
- package/lib/client/QuotaButton.js.map +1 -0
- package/lib/client/SessionStatsChip.d.ts +47 -0
- package/lib/client/SessionStatsChip.d.ts.map +1 -0
- package/lib/client/SessionStatsChip.js +141 -0
- package/lib/client/SessionStatsChip.js.map +1 -0
- package/lib/client/StatCard.d.ts +26 -0
- package/lib/client/StatCard.d.ts.map +1 -0
- package/lib/client/StatCard.js +10 -0
- package/lib/client/StatCard.js.map +1 -0
- package/lib/client/TokenUsageCard.d.ts +41 -0
- package/lib/client/TokenUsageCard.d.ts.map +1 -0
- package/lib/client/TokenUsageCard.js +164 -0
- package/lib/client/TokenUsageCard.js.map +1 -0
- package/lib/client/TokenUsageSection.d.ts +32 -0
- package/lib/client/TokenUsageSection.d.ts.map +1 -0
- package/lib/client/TokenUsageSection.js +266 -0
- package/lib/client/TokenUsageSection.js.map +1 -0
- package/lib/client/TrendChart.d.ts +53 -0
- package/lib/client/TrendChart.d.ts.map +1 -0
- package/lib/client/TrendChart.js +141 -0
- package/lib/client/TrendChart.js.map +1 -0
- package/lib/client/UsageView.d.ts +42 -0
- package/lib/client/UsageView.d.ts.map +1 -0
- package/lib/client/UsageView.js +158 -0
- package/lib/client/UsageView.js.map +1 -0
- package/lib/client/async-resource.d.ts +54 -0
- package/lib/client/async-resource.d.ts.map +1 -0
- package/lib/client/async-resource.js +90 -0
- package/lib/client/async-resource.js.map +1 -0
- package/lib/client/card-form.d.ts +171 -0
- package/lib/client/card-form.d.ts.map +1 -0
- package/lib/client/card-form.js +300 -0
- package/lib/client/card-form.js.map +1 -0
- package/lib/client/cost-inflate-motion.d.ts +17 -0
- package/lib/client/cost-inflate-motion.d.ts.map +1 -0
- package/lib/client/cost-inflate-motion.js +61 -0
- package/lib/client/cost-inflate-motion.js.map +1 -0
- package/lib/client/cost-inflate.d.ts +28 -0
- package/lib/client/cost-inflate.d.ts.map +1 -0
- package/lib/client/cost-inflate.js +49 -0
- package/lib/client/cost-inflate.js.map +1 -0
- package/lib/client/day.d.ts +49 -0
- package/lib/client/day.d.ts.map +1 -0
- package/lib/client/day.js +84 -0
- package/lib/client/day.js.map +1 -0
- package/lib/client/format.d.ts +120 -0
- package/lib/client/format.d.ts.map +1 -0
- package/lib/client/format.js +163 -0
- package/lib/client/format.js.map +1 -0
- package/lib/client/index.d.ts +26 -0
- package/lib/client/index.d.ts.map +1 -0
- package/lib/client/index.js +131 -0
- package/lib/client/index.js.map +1 -0
- package/lib/client/locales.d.ts +131 -0
- package/lib/client/locales.d.ts.map +1 -0
- package/lib/client/locales.js +230 -0
- package/lib/client/locales.js.map +1 -0
- package/lib/client/quota-format.d.ts +69 -0
- package/lib/client/quota-format.d.ts.map +1 -0
- package/lib/client/quota-format.js +147 -0
- package/lib/client/quota-format.js.map +1 -0
- package/lib/client/session-stats.d.ts +105 -0
- package/lib/client/session-stats.d.ts.map +1 -0
- package/lib/client/session-stats.js +142 -0
- package/lib/client/session-stats.js.map +1 -0
- package/lib/client/trend-chart/axis.d.ts +21 -0
- package/lib/client/trend-chart/axis.d.ts.map +1 -0
- package/lib/client/trend-chart/axis.js +33 -0
- package/lib/client/trend-chart/axis.js.map +1 -0
- package/lib/client/trend-chart/bucket.d.ts +24 -0
- package/lib/client/trend-chart/bucket.d.ts.map +1 -0
- package/lib/client/trend-chart/bucket.js +28 -0
- package/lib/client/trend-chart/bucket.js.map +1 -0
- package/lib/client/trend-chart/index.d.ts +12 -0
- package/lib/client/trend-chart/index.d.ts.map +1 -0
- package/lib/client/trend-chart/index.js +9 -0
- package/lib/client/trend-chart/index.js.map +1 -0
- package/lib/client/trend-chart/points.d.ts +46 -0
- package/lib/client/trend-chart/points.d.ts.map +1 -0
- package/lib/client/trend-chart/points.js +82 -0
- package/lib/client/trend-chart/points.js.map +1 -0
- package/lib/client/trend-chart/scale.d.ts +47 -0
- package/lib/client/trend-chart/scale.d.ts.map +1 -0
- package/lib/client/trend-chart/scale.js +75 -0
- package/lib/client/trend-chart/scale.js.map +1 -0
- package/lib/client/use-color-scheme.d.ts +18 -0
- package/lib/client/use-color-scheme.d.ts.map +1 -0
- package/lib/client/use-color-scheme.js +37 -0
- package/lib/client/use-color-scheme.js.map +1 -0
- package/lib/client/use-cost-inflate.d.ts +33 -0
- package/lib/client/use-cost-inflate.d.ts.map +1 -0
- package/lib/client/use-cost-inflate.js +108 -0
- package/lib/client/use-cost-inflate.js.map +1 -0
- package/lib/client.js +3892 -0
- package/lib/client.js.map +1 -0
- package/lib/index.d.ts +132 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +599 -0
- package/lib/index.js.map +1 -0
- package/lib/migrate.d.ts +60 -0
- package/lib/migrate.d.ts.map +1 -0
- package/lib/migrate.js +126 -0
- package/lib/migrate.js.map +1 -0
- package/lib/pricing.d.ts +212 -0
- package/lib/pricing.d.ts.map +1 -0
- package/lib/pricing.js +492 -0
- package/lib/pricing.js.map +1 -0
- package/lib/quota/adapters/deepseek-balance.d.ts +18 -0
- package/lib/quota/adapters/deepseek-balance.d.ts.map +1 -0
- package/lib/quota/adapters/deepseek-balance.js +76 -0
- package/lib/quota/adapters/deepseek-balance.js.map +1 -0
- package/lib/quota/adapters/kimi.d.ts +26 -0
- package/lib/quota/adapters/kimi.d.ts.map +1 -0
- package/lib/quota/adapters/kimi.js +91 -0
- package/lib/quota/adapters/kimi.js.map +1 -0
- package/lib/quota/adapters/minimax.d.ts +24 -0
- package/lib/quota/adapters/minimax.d.ts.map +1 -0
- package/lib/quota/adapters/minimax.js +136 -0
- package/lib/quota/adapters/minimax.js.map +1 -0
- package/lib/quota/adapters/opencode-go.d.ts +25 -0
- package/lib/quota/adapters/opencode-go.d.ts.map +1 -0
- package/lib/quota/adapters/opencode-go.js +105 -0
- package/lib/quota/adapters/opencode-go.js.map +1 -0
- package/lib/quota/adapters/openrouter.d.ts +15 -0
- package/lib/quota/adapters/openrouter.d.ts.map +1 -0
- package/lib/quota/adapters/openrouter.js +54 -0
- package/lib/quota/adapters/openrouter.js.map +1 -0
- package/lib/quota/adapters/zhipu.d.ts +38 -0
- package/lib/quota/adapters/zhipu.d.ts.map +1 -0
- package/lib/quota/adapters/zhipu.js +246 -0
- package/lib/quota/adapters/zhipu.js.map +1 -0
- package/lib/quota/credentials.d.ts +79 -0
- package/lib/quota/credentials.d.ts.map +1 -0
- package/lib/quota/credentials.js +130 -0
- package/lib/quota/credentials.js.map +1 -0
- package/lib/quota/http.d.ts +49 -0
- package/lib/quota/http.d.ts.map +1 -0
- package/lib/quota/http.js +114 -0
- package/lib/quota/http.js.map +1 -0
- package/lib/quota/provider-tracking.d.ts +45 -0
- package/lib/quota/provider-tracking.d.ts.map +1 -0
- package/lib/quota/provider-tracking.js +52 -0
- package/lib/quota/provider-tracking.js.map +1 -0
- package/lib/quota/quota-route.d.ts +22 -0
- package/lib/quota/quota-route.d.ts.map +1 -0
- package/lib/quota/quota-route.js +57 -0
- package/lib/quota/quota-route.js.map +1 -0
- package/lib/quota/quota-service.d.ts +54 -0
- package/lib/quota/quota-service.d.ts.map +1 -0
- package/lib/quota/quota-service.js +171 -0
- package/lib/quota/quota-service.js.map +1 -0
- package/lib/quota/registry.d.ts +24 -0
- package/lib/quota/registry.d.ts.map +1 -0
- package/lib/quota/registry.js +38 -0
- package/lib/quota/registry.js.map +1 -0
- package/lib/quota/types.d.ts +79 -0
- package/lib/quota/types.d.ts.map +1 -0
- package/lib/quota/types.js +24 -0
- package/lib/quota/types.js.map +1 -0
- package/lib/record-cache.d.ts +38 -0
- package/lib/record-cache.d.ts.map +1 -0
- package/lib/record-cache.js +143 -0
- package/lib/record-cache.js.map +1 -0
- package/lib/rollup.d.ts +52 -0
- package/lib/rollup.d.ts.map +1 -0
- package/lib/rollup.js +117 -0
- package/lib/rollup.js.map +1 -0
- package/lib/stats-route.d.ts +88 -0
- package/lib/stats-route.d.ts.map +1 -0
- package/lib/stats-route.js +313 -0
- package/lib/stats-route.js.map +1 -0
- package/lib/stats.d.ts +158 -0
- package/lib/stats.d.ts.map +1 -0
- package/lib/stats.js +426 -0
- package/lib/stats.js.map +1 -0
- package/lib/sync-state.d.ts +27 -0
- package/lib/sync-state.d.ts.map +1 -0
- package/lib/sync-state.js +56 -0
- package/lib/sync-state.js.map +1 -0
- package/lib/sync.d.ts +74 -0
- package/lib/sync.d.ts.map +1 -0
- package/lib/sync.js +64 -0
- package/lib/sync.js.map +1 -0
- package/lib/trend-bucket.d.ts +48 -0
- package/lib/trend-bucket.d.ts.map +1 -0
- package/lib/trend-bucket.js +87 -0
- package/lib/trend-bucket.js.map +1 -0
- package/lib/usage-log.d.ts +64 -0
- package/lib/usage-log.d.ts.map +1 -0
- package/lib/usage-log.js +144 -0
- package/lib/usage-log.js.map +1 -0
- package/lib/usage-record.d.ts +59 -0
- package/lib/usage-record.d.ts.map +1 -0
- package/lib/usage-record.js +115 -0
- package/lib/usage-record.js.map +1 -0
- package/lib/wire.d.ts +452 -0
- package/lib/wire.d.ts.map +1 -0
- package/lib/wire.js +144 -0
- package/lib/wire.js.map +1 -0
- package/package.json +100 -0
package/lib/stats.js
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stats computation of the token-usage plugin: read the day files and fold
|
|
3
|
+
* the records into totals, per-day rows, per-model rows, and a bounded recent
|
|
4
|
+
* window — keeping one row per (day, model, rate identity) so every record
|
|
5
|
+
* is billed at the rate its own timestamp resolved through (see
|
|
6
|
+
* pricing.resolveRate). Frozen (pre-today) day files are served from the
|
|
7
|
+
* on-disk rollup (see rollup.ts); only today's file is read on every call.
|
|
8
|
+
* Pure aggregation lives apart from the file walk so the web route and tests
|
|
9
|
+
* share one implementation.
|
|
10
|
+
*
|
|
11
|
+
* @module token-usage/stats
|
|
12
|
+
*/
|
|
13
|
+
import { costOf, ratesForKey } from "./pricing.js";
|
|
14
|
+
import { fileDay, listDayFiles, readDayFile } from "./record-cache.js";
|
|
15
|
+
import { readRollup, writeRollup } from "./rollup.js";
|
|
16
|
+
import { UNPRICED_KEY } from "./wire.js";
|
|
17
|
+
/** Bounded recent window length: only the newest records cross the wire. */
|
|
18
|
+
export const RECENT_LIMIT = 20;
|
|
19
|
+
/** Empty rollup used as the merge base when no rollup exists on disk yet. */
|
|
20
|
+
function emptyRollup() {
|
|
21
|
+
return { upto: '', total: emptyTotals(), byDay: [], byHour: [], byModel: [], rateRows: [], recent: [] };
|
|
22
|
+
}
|
|
23
|
+
/** Zeroed totals; requests counts rows, the token buckets sum reported usage. */
|
|
24
|
+
export function emptyTotals() {
|
|
25
|
+
return {
|
|
26
|
+
requests: 0,
|
|
27
|
+
inputTokens: 0,
|
|
28
|
+
outputTokens: 0,
|
|
29
|
+
cacheReadTokens: 0,
|
|
30
|
+
cacheWriteTokens: 0,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** Add one totals row into another, field by field. */
|
|
34
|
+
function addTotals(target, source) {
|
|
35
|
+
target.requests += source.requests;
|
|
36
|
+
target.inputTokens += source.inputTokens;
|
|
37
|
+
target.outputTokens += source.outputTokens;
|
|
38
|
+
target.cacheReadTokens += source.cacheReadTokens;
|
|
39
|
+
target.cacheWriteTokens += source.cacheWriteTokens;
|
|
40
|
+
}
|
|
41
|
+
/** Sort a day row map ascending by day, matching {@link summarizeRecords}. */
|
|
42
|
+
function dayRows(days) {
|
|
43
|
+
return [...days.entries()]
|
|
44
|
+
.map(([day, totals]) => ({ day, totals }))
|
|
45
|
+
.sort((left, right) => left.day < right.day ? -1 : 1);
|
|
46
|
+
}
|
|
47
|
+
/** Sort a model row map by requests descending then model name, matching {@link summarizeRecords}. */
|
|
48
|
+
function modelRows(models) {
|
|
49
|
+
return [...models.entries()]
|
|
50
|
+
.map(([model, totals]) => ({ model, totals }))
|
|
51
|
+
.sort((left, right) => right.totals.requests - left.totals.requests || left.model.localeCompare(right.model));
|
|
52
|
+
}
|
|
53
|
+
/** Deterministic rate-identity order: rule window, tier, slot. */
|
|
54
|
+
function compareKeys(left, right) {
|
|
55
|
+
return left.ruleStart - right.ruleStart || left.ruleEnd - right.ruleEnd
|
|
56
|
+
|| left.tier - right.tier || left.slot - right.slot;
|
|
57
|
+
}
|
|
58
|
+
/** Sort rate rows day ascending, then model name, then rate identity. */
|
|
59
|
+
function rateRowsSorted(rows) {
|
|
60
|
+
return [...rows].sort((left, right) => left.day < right.day ? -1 : left.day > right.day ? 1
|
|
61
|
+
: left.model < right.model ? -1 : left.model > right.model ? 1
|
|
62
|
+
: compareKeys(left.rate, right.rate));
|
|
63
|
+
}
|
|
64
|
+
/** Map key of one (day, model, rate) cell. */
|
|
65
|
+
function rateRowKey(day, model, rate) {
|
|
66
|
+
return `${day}\n${model}\n${rate.ruleStart}-${rate.ruleEnd}-${rate.tier}-${rate.slot}`;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Fold one record into totals; a record without provider usage still counts a request. */
|
|
70
|
+
function addUsage(totals, usage) {
|
|
71
|
+
totals.requests += 1;
|
|
72
|
+
if (usage === undefined)
|
|
73
|
+
return;
|
|
74
|
+
totals.inputTokens += usage.inputTokens;
|
|
75
|
+
totals.outputTokens += usage.outputTokens;
|
|
76
|
+
if (usage.cacheReadTokens !== undefined)
|
|
77
|
+
totals.cacheReadTokens += usage.cacheReadTokens;
|
|
78
|
+
if (usage.cacheWriteTokens !== undefined)
|
|
79
|
+
totals.cacheWriteTokens += usage.cacheWriteTokens;
|
|
80
|
+
}
|
|
81
|
+
/** Local date key of a record time, matching the day-file naming convention. */
|
|
82
|
+
function dayKey(time) {
|
|
83
|
+
const date = new Date(time);
|
|
84
|
+
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
85
|
+
const day = String(date.getDate()).padStart(2, '0');
|
|
86
|
+
return `${date.getFullYear()}-${month}-${day}`;
|
|
87
|
+
}
|
|
88
|
+
/** Local `YYYY-MM-DDTHH` key of a record time, the byHour row key. */
|
|
89
|
+
function hourKey(time) {
|
|
90
|
+
const date = new Date(time);
|
|
91
|
+
const hour = String(date.getHours()).padStart(2, '0');
|
|
92
|
+
return `${dayKey(time)}T${hour}`;
|
|
93
|
+
}
|
|
94
|
+
/** Map key of one (hour, model) cell. */
|
|
95
|
+
function hourRowKey(hour, model) {
|
|
96
|
+
return `${hour}\n${model}`;
|
|
97
|
+
}
|
|
98
|
+
/** Sort an hour row map by hour ascending then model name, matching {@link summarizeRecords}. */
|
|
99
|
+
function hourRows(hours) {
|
|
100
|
+
return [...hours.entries()]
|
|
101
|
+
.map(([key, totals]) => {
|
|
102
|
+
const separator = key.indexOf('\n');
|
|
103
|
+
return { hour: key.slice(0, separator), model: key.slice(separator + 1), totals };
|
|
104
|
+
})
|
|
105
|
+
.sort((left, right) => left.hour < right.hour ? -1 : left.hour > right.hour ? 1
|
|
106
|
+
: left.model < right.model ? -1 : left.model > right.model ? 1
|
|
107
|
+
: 0);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Fold records into the token summary shape, one rate row per (day, model,
|
|
111
|
+
* rate identity) the resolver assigns. The recent window keeps the last
|
|
112
|
+
* {@link RECENT_LIMIT} records in input order (day files are chronological)
|
|
113
|
+
* and then sorts them by time descending.
|
|
114
|
+
* @param records - parsed records in day-file order.
|
|
115
|
+
* @param resolve - the rate resolver; defaults to leaving every record unpriced.
|
|
116
|
+
* @returns totals, day rows, model rows, rate rows, and the recent window.
|
|
117
|
+
*/
|
|
118
|
+
export function summarizeRecords(records, resolve = () => UNPRICED_KEY) {
|
|
119
|
+
const total = emptyTotals();
|
|
120
|
+
const days = new Map();
|
|
121
|
+
const hours = new Map();
|
|
122
|
+
const models = new Map();
|
|
123
|
+
const rated = new Map();
|
|
124
|
+
const recent = [];
|
|
125
|
+
for (const record of records) {
|
|
126
|
+
addUsage(total, record.usage);
|
|
127
|
+
const day = dayKey(record.time);
|
|
128
|
+
const dayTotals = days.get(day) ?? emptyTotals();
|
|
129
|
+
addUsage(dayTotals, record.usage);
|
|
130
|
+
days.set(day, dayTotals);
|
|
131
|
+
const hour = hourKey(record.time);
|
|
132
|
+
const hourTotals = hours.get(hourRowKey(hour, record.model)) ?? emptyTotals();
|
|
133
|
+
addUsage(hourTotals, record.usage);
|
|
134
|
+
hours.set(hourRowKey(hour, record.model), hourTotals);
|
|
135
|
+
const modelTotals = models.get(record.model) ?? emptyTotals();
|
|
136
|
+
addUsage(modelTotals, record.usage);
|
|
137
|
+
models.set(record.model, modelTotals);
|
|
138
|
+
const rate = resolve(record);
|
|
139
|
+
const rowKey = rateRowKey(day, record.model, rate);
|
|
140
|
+
const cell = rated.get(rowKey)
|
|
141
|
+
?? { day, model: record.model, rate, totals: emptyTotals() };
|
|
142
|
+
addUsage(cell.totals, record.usage);
|
|
143
|
+
rated.set(rowKey, cell);
|
|
144
|
+
if (recent.length === RECENT_LIMIT)
|
|
145
|
+
recent.shift();
|
|
146
|
+
recent.push(record);
|
|
147
|
+
}
|
|
148
|
+
const byDay = dayRows(days);
|
|
149
|
+
const byHour = hourRows(hours);
|
|
150
|
+
const byModel = modelRows(models);
|
|
151
|
+
recent.sort((left, right) => right.time - left.time);
|
|
152
|
+
return { total, byDay, byHour, byModel, rateRows: rateRowsSorted(rated.values()), recent };
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Keep only the records owned by one of the listed sessions. The rollup
|
|
156
|
+
* carries no session dimension (its rows are (day, model, rate) cells), so a
|
|
157
|
+
* session-scoped read cannot reuse it and must fold the filtered raw records
|
|
158
|
+
* instead — cheap in practice (the JSONL day files are a few hundred KB) and
|
|
159
|
+
* only triggered by per-session fetches (view switches), never the settings
|
|
160
|
+
* page's whole-log read.
|
|
161
|
+
* @param records - parsed records in day-file order.
|
|
162
|
+
* @param sessionIds - the sessions whose requests stay; [] yields no records.
|
|
163
|
+
* @returns the records owned by those sessions, in the original order.
|
|
164
|
+
*/
|
|
165
|
+
export function filterRecordsBySessions(records, sessionIds) {
|
|
166
|
+
const wanted = new Set(sessionIds);
|
|
167
|
+
return records.filter(record => wanted.has(record.sessionId));
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Derive the half-open day-range bounds from optional `YYYY-MM-DD` keys. A
|
|
171
|
+
* missing key leaves that side unbounded; the upper bound inherits the day's
|
|
172
|
+
* full millisecond span (the day-key convention used everywhere else).
|
|
173
|
+
* @param from - first day key (`YYYY-MM-DD`), inclusive; '' ignores both ends.
|
|
174
|
+
* @param to - last day key (`YYYY-MM-DD`), inclusive.
|
|
175
|
+
* @param model - exact model id; undefined matches any model.
|
|
176
|
+
* @returns the bounds (every field may be undefined).
|
|
177
|
+
*/
|
|
178
|
+
export function dayRangeFilter(from, to, model) {
|
|
179
|
+
const filter = {};
|
|
180
|
+
if (from !== undefined && from !== '')
|
|
181
|
+
filter.start = dayStart(from);
|
|
182
|
+
if (to !== undefined && to !== '')
|
|
183
|
+
filter.end = dayStart(to) + 86_399_999;
|
|
184
|
+
if (model !== undefined && model !== '')
|
|
185
|
+
filter.model = model;
|
|
186
|
+
return filter;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Combine a day-range filter with a session-id filter. The session ids are
|
|
190
|
+
* applied first (cheap, preroll), the day-range second (per-record); the
|
|
191
|
+
* model id, if any, is per-record too. Returns the records passing both.
|
|
192
|
+
* @param records - parsed records in chronological order.
|
|
193
|
+
* @param sessions - the session ids whose records stay; undefined skips that
|
|
194
|
+
* dimension.
|
|
195
|
+
* @param range - the day-range + model filter; undefined skips every dimension.
|
|
196
|
+
*/
|
|
197
|
+
export function filterRecordsByRange(records, sessions, range = {}) {
|
|
198
|
+
const wanted = sessions !== undefined ? new Set(sessions) : undefined;
|
|
199
|
+
const { start, end, model } = range;
|
|
200
|
+
return records.filter(record => (wanted === undefined || wanted.has(record.sessionId))
|
|
201
|
+
&& (start === undefined || record.time >= start)
|
|
202
|
+
&& (end === undefined || record.time <= end)
|
|
203
|
+
&& (model === undefined || record.model === model));
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* The per-request token series of a record set, in time order — one point
|
|
207
|
+
* per request, so a 55-request session plots 55 points. The conversation
|
|
208
|
+
* view tab draws this at request granularity; the settings page's hourly
|
|
209
|
+
* aggregation is unchanged (this field is session-scope only).
|
|
210
|
+
* @param records - the scoped records (day-file order is chronological).
|
|
211
|
+
* @param from - optional inclusive day key; the series keeps those requests.
|
|
212
|
+
* @param to - optional inclusive day key.
|
|
213
|
+
* @param model - optional exact model id.
|
|
214
|
+
* @returns one point per kept request, in the original time order.
|
|
215
|
+
*/
|
|
216
|
+
export function requestSeriesOf(records, from, to, model) {
|
|
217
|
+
return filterRecordsByRange(records, undefined, dayRangeFilter(from, to, model))
|
|
218
|
+
.map(record => ({
|
|
219
|
+
time: record.time,
|
|
220
|
+
tokens: record.usage === undefined ? 0
|
|
221
|
+
: record.usage.inputTokens + record.usage.outputTokens
|
|
222
|
+
+ (record.usage.cacheReadTokens ?? 0) + (record.usage.cacheWriteTokens ?? 0),
|
|
223
|
+
}));
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Merge two summaries into one: totals and model rows add up, day rows fold
|
|
227
|
+
* by day key (a same-day record set landing in a later file must join the
|
|
228
|
+
* earlier bucket, never replace it), rate rows fold by their (day, model,
|
|
229
|
+
* rate) key, and the recent window keeps the newest {@link RECENT_LIMIT}
|
|
230
|
+
* records across both sides. Order-independent and associative: merging
|
|
231
|
+
* partial summaries equals summarizing the concatenated records.
|
|
232
|
+
* @param left - one partial summary.
|
|
233
|
+
* @param right - the other partial summary.
|
|
234
|
+
* @returns the folded summary.
|
|
235
|
+
*/
|
|
236
|
+
export function mergeSummaries(left, right) {
|
|
237
|
+
const total = emptyTotals();
|
|
238
|
+
addTotals(total, left.total);
|
|
239
|
+
addTotals(total, right.total);
|
|
240
|
+
const days = new Map();
|
|
241
|
+
const hours = new Map();
|
|
242
|
+
const models = new Map();
|
|
243
|
+
const rated = new Map();
|
|
244
|
+
for (const row of [...left.byDay, ...right.byDay]) {
|
|
245
|
+
const day = days.get(row.day) ?? emptyTotals();
|
|
246
|
+
addTotals(day, row.totals);
|
|
247
|
+
days.set(row.day, day);
|
|
248
|
+
}
|
|
249
|
+
for (const row of [...left.byHour, ...right.byHour]) {
|
|
250
|
+
const key = hourRowKey(row.hour, row.model);
|
|
251
|
+
const cell = hours.get(key) ?? emptyTotals();
|
|
252
|
+
addTotals(cell, row.totals);
|
|
253
|
+
hours.set(key, cell);
|
|
254
|
+
}
|
|
255
|
+
for (const row of [...left.byModel, ...right.byModel]) {
|
|
256
|
+
const model = models.get(row.model) ?? emptyTotals();
|
|
257
|
+
addTotals(model, row.totals);
|
|
258
|
+
models.set(row.model, model);
|
|
259
|
+
}
|
|
260
|
+
for (const row of [...left.rateRows, ...right.rateRows]) {
|
|
261
|
+
const key = rateRowKey(row.day, row.model, row.rate);
|
|
262
|
+
const cell = rated.get(key)
|
|
263
|
+
?? { day: row.day, model: row.model, rate: row.rate, totals: emptyTotals() };
|
|
264
|
+
addTotals(cell.totals, row.totals);
|
|
265
|
+
rated.set(key, cell);
|
|
266
|
+
}
|
|
267
|
+
const recent = [...left.recent, ...right.recent]
|
|
268
|
+
.sort((a, b) => b.time - a.time)
|
|
269
|
+
.slice(0, RECENT_LIMIT);
|
|
270
|
+
return {
|
|
271
|
+
total,
|
|
272
|
+
byDay: dayRows(days),
|
|
273
|
+
byHour: hourRows(hours),
|
|
274
|
+
byModel: modelRows(models),
|
|
275
|
+
rateRows: rateRowsSorted(rated.values()),
|
|
276
|
+
recent,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
/** Local-midnight epoch of a day key, matching the day-file convention. */
|
|
280
|
+
function dayStart(day) {
|
|
281
|
+
const [year, month, date] = day.split('-').map(Number);
|
|
282
|
+
return new Date(year, month - 1, date).getTime();
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Re-aggregate a summary under an optional inclusive day range and model
|
|
286
|
+
* filter, drawing every dimension from the rate rows so no file is reread.
|
|
287
|
+
* The recent window filters on its record timestamps
|
|
288
|
+
* ([from 00:00, to 23:59:59.999] local). No filters returns the input as-is.
|
|
289
|
+
* @param summary - the unfiltered summary.
|
|
290
|
+
* @param from - first day key (`YYYY-MM-DD`), inclusive.
|
|
291
|
+
* @param to - last day key (`YYYY-MM-DD`), inclusive.
|
|
292
|
+
* @param model - exact model id.
|
|
293
|
+
* @returns the filtered summary.
|
|
294
|
+
*/
|
|
295
|
+
export function filterSummary(summary, from, to, model) {
|
|
296
|
+
if (from === undefined && to === undefined && model === undefined)
|
|
297
|
+
return summary;
|
|
298
|
+
const rows = summary.rateRows.filter(row => (from === undefined || row.day >= from)
|
|
299
|
+
&& (to === undefined || row.day <= to)
|
|
300
|
+
&& (model === undefined || row.model === model));
|
|
301
|
+
// Hour rows filter on their day prefix (the `YYYY-MM-DD` part of the key).
|
|
302
|
+
const byHour = summary.byHour.filter(row => (from === undefined || row.hour.slice(0, 10) >= from)
|
|
303
|
+
&& (to === undefined || row.hour.slice(0, 10) <= to)
|
|
304
|
+
&& (model === undefined || row.model === model));
|
|
305
|
+
const total = emptyTotals();
|
|
306
|
+
const days = new Map();
|
|
307
|
+
const models = new Map();
|
|
308
|
+
for (const row of rows) {
|
|
309
|
+
addTotals(total, row.totals);
|
|
310
|
+
const day = days.get(row.day) ?? emptyTotals();
|
|
311
|
+
addTotals(day, row.totals);
|
|
312
|
+
days.set(row.day, day);
|
|
313
|
+
const perModel = models.get(row.model) ?? emptyTotals();
|
|
314
|
+
addTotals(perModel, row.totals);
|
|
315
|
+
models.set(row.model, perModel);
|
|
316
|
+
}
|
|
317
|
+
const recent = filterRecordsByRange(summary.recent, undefined, dayRangeFilter(from, to, model));
|
|
318
|
+
return { dataDir: summary.dataDir, total, byDay: dayRows(days), byHour, byModel: modelRows(models), rateRows: rateRowsSorted(rows), recent };
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Attach the cost layer to a token-only summary: each rate row is priced at
|
|
322
|
+
* the prices its rate identity resolves to under the current table, folded
|
|
323
|
+
* into per-model costs, the total, the unpriced model list, and the table
|
|
324
|
+
* itself. Purely additive — totals, day rows, and the recent window are
|
|
325
|
+
* returned untouched, so the token aggregation (and the rollup format)
|
|
326
|
+
* never carries currency, and an updated table re-prices history for free.
|
|
327
|
+
* @param summary - the aggregated summary (build or filtered).
|
|
328
|
+
* @param pricing - the active pricing table.
|
|
329
|
+
* @returns the same summary plus the cost fields.
|
|
330
|
+
*/
|
|
331
|
+
export function attachCosts(summary, pricing) {
|
|
332
|
+
const costs = new Map();
|
|
333
|
+
let totalCost = 0;
|
|
334
|
+
for (const row of summary.rateRows) {
|
|
335
|
+
const rules = pricing[row.model];
|
|
336
|
+
if (rules === undefined)
|
|
337
|
+
continue;
|
|
338
|
+
const cost = costOf(row.totals, ratesForKey(rules, row.rate));
|
|
339
|
+
costs.set(row.model, (costs.get(row.model) ?? 0) + cost);
|
|
340
|
+
totalCost += cost;
|
|
341
|
+
}
|
|
342
|
+
const byModel = summary.byModel.map(row => ({
|
|
343
|
+
model: row.model,
|
|
344
|
+
totals: row.totals,
|
|
345
|
+
cost: costs.get(row.model) ?? 0,
|
|
346
|
+
}));
|
|
347
|
+
const unpricedModels = summary.byModel
|
|
348
|
+
.filter(row => pricing[row.model] === undefined)
|
|
349
|
+
.map(row => row.model);
|
|
350
|
+
return {
|
|
351
|
+
dataDir: summary.dataDir,
|
|
352
|
+
total: summary.total,
|
|
353
|
+
totalCost,
|
|
354
|
+
unpricedModels,
|
|
355
|
+
pricing,
|
|
356
|
+
byDay: summary.byDay,
|
|
357
|
+
byHour: summary.byHour,
|
|
358
|
+
byModel,
|
|
359
|
+
rateRows: summary.rateRows,
|
|
360
|
+
recent: summary.recent,
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Read every day file into records, in day-file order. An absent data
|
|
365
|
+
* directory (nothing written yet) yields an empty list. Uncached — the
|
|
366
|
+
* session-scoped route uses `readCachedRecords` so repeated chip /
|
|
367
|
+
* usage-tab polls do not re-parse frozen files.
|
|
368
|
+
* @param dir - the plugin's data directory.
|
|
369
|
+
* @returns parsed records, or [] when the directory does not exist.
|
|
370
|
+
*/
|
|
371
|
+
export async function readAllRecords(dir) {
|
|
372
|
+
const records = [];
|
|
373
|
+
for (const name of await listDayFiles(dir)) {
|
|
374
|
+
records.push(...await readDayFile(dir, name));
|
|
375
|
+
}
|
|
376
|
+
return records;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Build the full stats payload for one data directory: the rollup over every
|
|
380
|
+
* frozen day file (advanced lazily and rewritten atomically when unabsorbed
|
|
381
|
+
* frozen files appear) merged with a fresh read of today's file. Day files
|
|
382
|
+
* named at or after today but already absorbed by a later rollup `upto` are
|
|
383
|
+
* skipped, so a clock stepping back cannot count an absorbed file twice.
|
|
384
|
+
* A failed rollup write logs and does not block the response — the next read
|
|
385
|
+
* retries the absorption. The resolver prices each record as it is absorbed,
|
|
386
|
+
* so the rollup carries rate identities (never prices) and a table update
|
|
387
|
+
* re-prices history without rebuilding anything.
|
|
388
|
+
* @param dir - the plugin's data directory.
|
|
389
|
+
* @param now - clock source for the frozen/today boundary (test seam).
|
|
390
|
+
* @param resolve - the rate resolver (see {@link RateResolver}).
|
|
391
|
+
* @returns the summary served to the web settings page.
|
|
392
|
+
*/
|
|
393
|
+
export async function buildSummary(dir, now = () => new Date(), resolve = () => UNPRICED_KEY) {
|
|
394
|
+
const today = dayKey(now().getTime());
|
|
395
|
+
const rollup = (await readRollup(dir)) ?? emptyRollup();
|
|
396
|
+
const cold = [];
|
|
397
|
+
const hot = [];
|
|
398
|
+
for (const name of await listDayFiles(dir)) {
|
|
399
|
+
const day = fileDay(name);
|
|
400
|
+
if (day <= rollup.upto)
|
|
401
|
+
continue;
|
|
402
|
+
if (day < today)
|
|
403
|
+
cold.push(name);
|
|
404
|
+
else
|
|
405
|
+
hot.push(name);
|
|
406
|
+
}
|
|
407
|
+
let absorbed = rollup;
|
|
408
|
+
if (cold.length > 0) {
|
|
409
|
+
// names are date-ascending, so the last cold file carries the new upto
|
|
410
|
+
const records = [];
|
|
411
|
+
for (const name of cold)
|
|
412
|
+
records.push(...await readDayFile(dir, name));
|
|
413
|
+
absorbed = {
|
|
414
|
+
upto: fileDay(cold[cold.length - 1]),
|
|
415
|
+
...mergeSummaries(rollup, summarizeRecords(records, resolve)),
|
|
416
|
+
};
|
|
417
|
+
await writeRollup(dir, absorbed).catch((error) => {
|
|
418
|
+
console.error('[token-usage] cannot write rollup:', error);
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
const fresh = [];
|
|
422
|
+
for (const name of hot)
|
|
423
|
+
fresh.push(...await readDayFile(dir, name));
|
|
424
|
+
return { dataDir: dir, ...mergeSummaries(absorbed, summarizeRecords(fresh, resolve)) };
|
|
425
|
+
}
|
|
426
|
+
//# sourceMappingURL=stats.js.map
|
package/lib/stats.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stats.js","sourceRoot":"","sources":["../src/stats.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAClD,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM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,MAAM,GAAG,CAAC,CAAE,CAAE;YACtC,GAAG,cAAc,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;SAC9D,CAAA;QACD,MAAM,WAAW,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACxD,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,KAAK,CAAC,CAAA;QAC5D,CAAC,CAAC,CAAA;IACJ,CAAC;IACD,MAAM,KAAK,GAAkB,EAAE,CAAA;IAC/B,KAAK,MAAM,IAAI,IAAI,GAAG;QAAE,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAA;IACnE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,cAAc,CAAC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,EAAE,CAAA;AACxF,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-shot initialization marker: whether the plugin ever completed a history
|
|
3
|
+
* sync. The marker exists only to gate the FIRST automatic sync; every later
|
|
4
|
+
* sync is the user's decision (the manual command).
|
|
5
|
+
*
|
|
6
|
+
* @module token-usage/sync-state
|
|
7
|
+
*/
|
|
8
|
+
/** Contents of the initialized marker. */
|
|
9
|
+
export interface SyncState {
|
|
10
|
+
/** Epoch milliseconds when the first automatic sync completed. */
|
|
11
|
+
initializedAt: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Whether the first automatic sync already completed. A missing or malformed
|
|
15
|
+
* marker reads as uninitialized: the next startup re-runs the sync, whose
|
|
16
|
+
* dedupe makes the repetition a no-op.
|
|
17
|
+
* @param dir - the data directory holding the marker.
|
|
18
|
+
*/
|
|
19
|
+
export declare function isInitialized(dir: string): Promise<boolean>;
|
|
20
|
+
/**
|
|
21
|
+
* Persist the initialized marker atomically (temp file + rename), so a crash
|
|
22
|
+
* mid-write never leaves a torn marker that would misread as initialized.
|
|
23
|
+
* @param dir - the data directory holding the marker.
|
|
24
|
+
* @param now - clock source (test seam).
|
|
25
|
+
*/
|
|
26
|
+
export declare function markInitialized(dir: string, now?: () => Date): Promise<void>;
|
|
27
|
+
//# sourceMappingURL=sync-state.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sync-state.d.ts","sourceRoot":"","sources":["../src/sync-state.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAQH,0CAA0C;AAC1C,MAAM,WAAW,SAAS;IACxB,kEAAkE;IAClE,aAAa,EAAE,MAAM,CAAA;CACtB;AAQD;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAiBjE;AAED;;;;;GAKG;AACH,wBAAsB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,MAAM,IAAuB,GAAG,OAAO,CAAC,IAAI,CAAC,CAKpG"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-shot initialization marker: whether the plugin ever completed a history
|
|
3
|
+
* sync. The marker exists only to gate the FIRST automatic sync; every later
|
|
4
|
+
* sync is the user's decision (the manual command).
|
|
5
|
+
*
|
|
6
|
+
* @module token-usage/sync-state
|
|
7
|
+
*/
|
|
8
|
+
import { readFile, rename, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
const STATE_FILE = 'state.json';
|
|
11
|
+
const TMP_FILE = 'state.json.tmp';
|
|
12
|
+
function isSyncState(value) {
|
|
13
|
+
return typeof value === 'object' && value !== null
|
|
14
|
+
&& typeof value.initializedAt === 'number'
|
|
15
|
+
&& Number.isFinite(value.initializedAt);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Whether the first automatic sync already completed. A missing or malformed
|
|
19
|
+
* marker reads as uninitialized: the next startup re-runs the sync, whose
|
|
20
|
+
* dedupe makes the repetition a no-op.
|
|
21
|
+
* @param dir - the data directory holding the marker.
|
|
22
|
+
*/
|
|
23
|
+
export async function isInitialized(dir) {
|
|
24
|
+
let text;
|
|
25
|
+
try {
|
|
26
|
+
text = await readFile(join(dir, STATE_FILE), 'utf8');
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (error.code === 'ENOENT')
|
|
30
|
+
return false;
|
|
31
|
+
console.error('[token-usage] cannot read state:', error);
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
let value;
|
|
35
|
+
try {
|
|
36
|
+
value = JSON.parse(text);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// Malformed marker: treat as uninitialized (the sync re-runs idempotently).
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
return isSyncState(value);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Persist the initialized marker atomically (temp file + rename), so a crash
|
|
46
|
+
* mid-write never leaves a torn marker that would misread as initialized.
|
|
47
|
+
* @param dir - the data directory holding the marker.
|
|
48
|
+
* @param now - clock source (test seam).
|
|
49
|
+
*/
|
|
50
|
+
export async function markInitialized(dir, now = () => new Date()) {
|
|
51
|
+
const target = join(dir, STATE_FILE);
|
|
52
|
+
const tmp = join(dir, TMP_FILE);
|
|
53
|
+
await writeFile(tmp, JSON.stringify({ initializedAt: now().getTime() }), 'utf8');
|
|
54
|
+
await rename(tmp, target);
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=sync-state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sync-state.js","sourceRoot":"","sources":["../src/sync-state.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAC9D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CA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C,SAAS,CAAC,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,EAAE,MAAM,CAAC,CAAA;IAChF,MAAM,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,CAAA;AAC3B,CAAC"}
|
package/lib/sync.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* History sync: replay every persisted session log and append the request
|
|
3
|
+
* rows the log does not already hold, deduped by request id. The sync runs
|
|
4
|
+
* automatically ONCE, on the first startup after installation (gated by the
|
|
5
|
+
* initialized marker).
|
|
6
|
+
*
|
|
7
|
+
* @module token-usage/sync
|
|
8
|
+
*/
|
|
9
|
+
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session';
|
|
10
|
+
import type { UsageLog } from './usage-log.ts';
|
|
11
|
+
/** Outcome of one sync run. */
|
|
12
|
+
export interface SyncResult {
|
|
13
|
+
/** Rows appended to the log. */
|
|
14
|
+
added: number;
|
|
15
|
+
/** Requests already present in the log (deduped). */
|
|
16
|
+
skipped: number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* One progress tick of a long sync: the host forwards these to the card so the
|
|
20
|
+
* user can see how far the manual scan has gotten. The first tick is emitted
|
|
21
|
+
* before the first session is read (so the bar shows `0/total` immediately),
|
|
22
|
+
* and one tick follows each completed session. `total` is the session count
|
|
23
|
+
* seen at the start of the run; a session that appears mid-run does not
|
|
24
|
+
* change it.
|
|
25
|
+
*/
|
|
26
|
+
export interface SyncProgressTick {
|
|
27
|
+
/** Sessions fully processed so far. */
|
|
28
|
+
processed: number;
|
|
29
|
+
/** Total sessions this run intends to walk (frozen at the start). */
|
|
30
|
+
total: number;
|
|
31
|
+
/** Rows appended to the log so far. */
|
|
32
|
+
added: number;
|
|
33
|
+
/** Rows skipped by dedupe so far. */
|
|
34
|
+
skipped: number;
|
|
35
|
+
}
|
|
36
|
+
/** The persistence surface the sync needs (duck-typed for tests). */
|
|
37
|
+
export interface SyncPersistence {
|
|
38
|
+
/** Every materialized session, in arbitrary order. */
|
|
39
|
+
list(signal?: AbortSignal): Promise<{
|
|
40
|
+
id: SessionId;
|
|
41
|
+
}[]>;
|
|
42
|
+
/** Immutable logical event log of one session. */
|
|
43
|
+
inspect(id: SessionId, signal?: AbortSignal): Promise<{
|
|
44
|
+
events: readonly SessionEvent[];
|
|
45
|
+
}>;
|
|
46
|
+
}
|
|
47
|
+
/** Dependencies of one sync run. */
|
|
48
|
+
export interface SyncDeps {
|
|
49
|
+
persistence: SyncPersistence;
|
|
50
|
+
log: UsageLog;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Append every missing request row. The log's dedupe set is rebuilt from the
|
|
54
|
+
* data files first, so a second run is a no-op and rows recorded live in a
|
|
55
|
+
* previous process are not duplicated.
|
|
56
|
+
* @param deps - persistence and the shared log.
|
|
57
|
+
* @param onTick - optional progress callback; fires once before the first
|
|
58
|
+
* session (with `processed: 0` and the final `total`), then once per session
|
|
59
|
+
* as it finishes. The card passes this to drive its progress bar; the
|
|
60
|
+
* one-shot startup sync omits it.
|
|
61
|
+
* @param signal - cancellation; an aborted run throws `AbortError`.
|
|
62
|
+
*/
|
|
63
|
+
export declare function syncHistory(deps: SyncDeps, onTick?: (tick: SyncProgressTick) => void, signal?: AbortSignal): Promise<SyncResult>;
|
|
64
|
+
/**
|
|
65
|
+
* Run the one-shot automatic sync when the initialized marker is absent, then
|
|
66
|
+
* persist the marker. A crash between the sync and the marker write leaves
|
|
67
|
+
* the marker absent, so the next startup re-runs the sync — a no-op thanks to
|
|
68
|
+
* dedupe.
|
|
69
|
+
* @param deps - persistence and the shared log.
|
|
70
|
+
* @param dir - the data directory holding the marker.
|
|
71
|
+
* @returns the sync outcome, or null when the marker was already present.
|
|
72
|
+
*/
|
|
73
|
+
export declare function autoSyncIfNeeded(deps: SyncDeps, dir: string): Promise<SyncResult | null>;
|
|
74
|
+
//# sourceMappingURL=sync.d.ts.map
|
|
@@ -0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