dsh-usage-peak 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/LICENSE +21 -0
- package/README.md +86 -2
- package/assets/sidebar-pill.webp +0 -0
- package/client.js +845 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +6 -0
- package/index.js +501 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +65 -4
package/cordis.patch.yml
ADDED
package/icon.svg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
|
|
2
|
+
<rect x="6" y="34" width="10" height="22" rx="2" fill="#2f9e6a"/>
|
|
3
|
+
<rect x="20" y="22" width="10" height="34" rx="2" fill="#d98b2b"/>
|
|
4
|
+
<rect x="34" y="30" width="10" height="26" rx="2" fill="#2f9e6a"/>
|
|
5
|
+
<rect x="48" y="14" width="10" height="42" rx="2" fill="#d98b2b"/>
|
|
6
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-usage-peak — Host half.
|
|
3
|
+
*
|
|
4
|
+
* Reads the session logs (~/.dsh/sessions/<cwd>/<session>/session.v4.jsonl.zstd),
|
|
5
|
+
* reconstructs every model request from its `assistant/message` usage, prices it
|
|
6
|
+
* with the DeepSeek peak/valley tariff (Beijing time), and serves the result as
|
|
7
|
+
* JSON for the Settings page dashboard implemented in ./client.js.
|
|
8
|
+
*
|
|
9
|
+
* The whale ledger (~/.dsh/.dshw-usage.json) is only used as a cross-check:
|
|
10
|
+
* it knows account-level spend but not the input/cache/output split.
|
|
11
|
+
*/
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import os from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import zlib from 'node:zlib';
|
|
16
|
+
|
|
17
|
+
const NS = 'dsh-usage-peak';
|
|
18
|
+
const ROUTE_BASE = '/plugin/dsh-usage-peak';
|
|
19
|
+
const SNAPSHOT_TTL_MS = 15_000;
|
|
20
|
+
const BJ_OFFSET = 8 * 60 * 60 * 1000;
|
|
21
|
+
const DAYS_SHOWN = 14;
|
|
22
|
+
const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]); // zstd frame magic, little endian
|
|
23
|
+
|
|
24
|
+
/** CNY per million tokens, [valley, peak]. */
|
|
25
|
+
const PRICING = [
|
|
26
|
+
{ id: 'flash', label: 'DeepSeek Flash', match: 'flash', hit: [0.02, 0.04], miss: [1, 2], out: [4, 8] },
|
|
27
|
+
{ id: 'pro', label: 'DeepSeek Pro', match: 'pro', hit: [0.15, 0.3], miss: [4.5, 9], out: [13.5, 27] },
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
function priceFor(model) {
|
|
31
|
+
const name = String(model || '').toLowerCase();
|
|
32
|
+
if (name.includes('pro')) return PRICING[1];
|
|
33
|
+
return PRICING[0];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function bjDate(ts) {
|
|
37
|
+
return new Date(ts + BJ_OFFSET);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function dayKey(ts) {
|
|
41
|
+
return bjDate(ts).toISOString().slice(0, 10);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Peak = Beijing Mon-Fri 09:00-12:00 and 14:00-18:00; everything else is valley (half price). */
|
|
45
|
+
function isPeakAt(ts) {
|
|
46
|
+
const d = bjDate(ts);
|
|
47
|
+
const dow = d.getUTCDay();
|
|
48
|
+
if (dow === 0 || dow === 6) return false;
|
|
49
|
+
const minutes = d.getUTCHours() * 60 + d.getUTCMinutes();
|
|
50
|
+
return (minutes >= 540 && minutes < 720) || (minutes >= 840 && minutes < 1080);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Next tariff switch after `ts`, with the status it switches into. */
|
|
54
|
+
function nextSwitch(ts) {
|
|
55
|
+
const d = bjDate(ts);
|
|
56
|
+
const y = d.getUTCFullYear();
|
|
57
|
+
const mo = d.getUTCMonth();
|
|
58
|
+
const da = d.getUTCDate();
|
|
59
|
+
for (let k = 0; k < 9; k += 1) {
|
|
60
|
+
const probe = new Date(Date.UTC(y, mo, da + k));
|
|
61
|
+
const dow = probe.getUTCDay();
|
|
62
|
+
if (dow === 0 || dow === 6) continue;
|
|
63
|
+
for (const hour of [9, 12, 14, 18]) {
|
|
64
|
+
const at = Date.UTC(probe.getUTCFullYear(), probe.getUTCMonth(), probe.getUTCDate(), hour, 0, 0) - BJ_OFFSET;
|
|
65
|
+
if (at > ts) return { at, status: hour === 9 || hour === 14 ? 'peak' : 'valley' };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return { at: ts + 3600_000, status: 'valley' };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/* ------------------------------------------------------------------ */
|
|
72
|
+
/* Session log decoding */
|
|
73
|
+
/* ------------------------------------------------------------------ */
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Session logs are concatenated zstd frames; Node's zstd entry points stop after
|
|
77
|
+
* the first frame. Split on the frame magic and stitch the frames back together.
|
|
78
|
+
*/
|
|
79
|
+
function decodeSessionFile(file) {
|
|
80
|
+
const buf = fs.readFileSync(file);
|
|
81
|
+
const starts = [];
|
|
82
|
+
let cursor = 0;
|
|
83
|
+
for (;;) {
|
|
84
|
+
const at = buf.indexOf(MAGIC, cursor);
|
|
85
|
+
if (at < 0) break;
|
|
86
|
+
starts.push(at);
|
|
87
|
+
cursor = at + 4;
|
|
88
|
+
}
|
|
89
|
+
if (starts.length === 0) return buf.toString('utf8');
|
|
90
|
+
const chunks = [];
|
|
91
|
+
let index = 0;
|
|
92
|
+
while (index < starts.length) {
|
|
93
|
+
let accepted;
|
|
94
|
+
for (let end = index + 1; end <= starts.length; end += 1) {
|
|
95
|
+
const stop = end < starts.length ? starts[end] : buf.length;
|
|
96
|
+
try {
|
|
97
|
+
accepted = { data: zlib.zstdDecompressSync(buf.subarray(starts[index], stop)), next: end };
|
|
98
|
+
break;
|
|
99
|
+
} catch {
|
|
100
|
+
/* a magic-looking byte inside a frame: keep growing the slice */
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (!accepted) {
|
|
104
|
+
index += 1;
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
chunks.push(accepted.data);
|
|
108
|
+
index = accepted.next;
|
|
109
|
+
}
|
|
110
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** One turn per billed model request: { t, model, input, cache, output }. */
|
|
114
|
+
function parseSessionTurns(text) {
|
|
115
|
+
const turns = [];
|
|
116
|
+
for (const line of text.split('\n')) {
|
|
117
|
+
if (line.length < 2) continue;
|
|
118
|
+
let record;
|
|
119
|
+
try {
|
|
120
|
+
record = JSON.parse(line);
|
|
121
|
+
} catch {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (record.type !== 'assistant/message') continue;
|
|
125
|
+
const usage = record.data && record.data.usage;
|
|
126
|
+
if (!usage) continue;
|
|
127
|
+
const model = (record.data.message && record.data.message.source && record.data.message.source.model) || 'unknown';
|
|
128
|
+
turns.push({
|
|
129
|
+
t: record.time,
|
|
130
|
+
model,
|
|
131
|
+
input: usage.inputTokens || 0,
|
|
132
|
+
cache: usage.cacheReadTokens || 0,
|
|
133
|
+
output: usage.outputTokens || 0,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
return turns;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/* ------------------------------------------------------------------ */
|
|
140
|
+
/* Aggregation */
|
|
141
|
+
/* ------------------------------------------------------------------ */
|
|
142
|
+
|
|
143
|
+
const fileCache = new Map(); // file -> { mtimeMs, size, turns }
|
|
144
|
+
let snapshotCache = null;
|
|
145
|
+
|
|
146
|
+
function collectTurns() {
|
|
147
|
+
const root = path.join(os.homedir(), '.dsh', 'sessions');
|
|
148
|
+
const turns = [];
|
|
149
|
+
let workspaceDirs;
|
|
150
|
+
try {
|
|
151
|
+
workspaceDirs = fs.readdirSync(root, { withFileTypes: true });
|
|
152
|
+
} catch {
|
|
153
|
+
return turns;
|
|
154
|
+
}
|
|
155
|
+
for (const workspace of workspaceDirs) {
|
|
156
|
+
if (!workspace.isDirectory()) continue;
|
|
157
|
+
const workspacePath = path.join(root, workspace.name);
|
|
158
|
+
let sessions;
|
|
159
|
+
try {
|
|
160
|
+
sessions = fs.readdirSync(workspacePath, { withFileTypes: true });
|
|
161
|
+
} catch {
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
for (const session of sessions) {
|
|
165
|
+
if (!session.isDirectory()) continue;
|
|
166
|
+
const dir = path.join(workspacePath, session.name);
|
|
167
|
+
const file = path.join(dir, 'session.v4.jsonl.zstd');
|
|
168
|
+
let stat;
|
|
169
|
+
try {
|
|
170
|
+
stat = fs.statSync(file);
|
|
171
|
+
} catch {
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
let entry = fileCache.get(file);
|
|
175
|
+
if (!entry || entry.mtimeMs !== stat.mtimeMs || entry.size !== stat.size) {
|
|
176
|
+
let parsed = [];
|
|
177
|
+
try {
|
|
178
|
+
parsed = parseSessionTurns(decodeSessionFile(file));
|
|
179
|
+
} catch {
|
|
180
|
+
parsed = [];
|
|
181
|
+
}
|
|
182
|
+
entry = { mtimeMs: stat.mtimeMs, size: stat.size, turns: parsed };
|
|
183
|
+
fileCache.set(file, entry);
|
|
184
|
+
}
|
|
185
|
+
for (const turn of entry.turns) turns.push(turn);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return turns;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function emptyDay(day) {
|
|
192
|
+
const hours = [];
|
|
193
|
+
for (let hour = 0; hour < 24; hour += 1) hours.push({ hour, cost: 0, calls: 0 });
|
|
194
|
+
return {
|
|
195
|
+
day,
|
|
196
|
+
calls: 0,
|
|
197
|
+
inputTokens: 0,
|
|
198
|
+
cacheTokens: 0,
|
|
199
|
+
outputTokens: 0,
|
|
200
|
+
cost: 0,
|
|
201
|
+
costCache: 0,
|
|
202
|
+
costMiss: 0,
|
|
203
|
+
costOut: 0,
|
|
204
|
+
peakCost: 0,
|
|
205
|
+
valleyCost: 0,
|
|
206
|
+
hours,
|
|
207
|
+
models: {},
|
|
208
|
+
firstAt: 0,
|
|
209
|
+
lastAt: 0,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function addTurn(day, turn) {
|
|
214
|
+
const price = priceFor(turn.model);
|
|
215
|
+
const peak = isPeakAt(turn.t);
|
|
216
|
+
const offset = peak ? 1 : 0;
|
|
217
|
+
const costCache = (turn.cache / 1e6) * price.hit[offset];
|
|
218
|
+
const costMiss = (turn.input / 1e6) * price.miss[offset];
|
|
219
|
+
const costOut = (turn.output / 1e6) * price.out[offset];
|
|
220
|
+
const cost = costCache + costMiss + costOut;
|
|
221
|
+
|
|
222
|
+
day.calls += 1;
|
|
223
|
+
day.inputTokens += turn.input;
|
|
224
|
+
day.cacheTokens += turn.cache;
|
|
225
|
+
day.outputTokens += turn.output;
|
|
226
|
+
day.cost += cost;
|
|
227
|
+
day.costCache += costCache;
|
|
228
|
+
day.costMiss += costMiss;
|
|
229
|
+
day.costOut += costOut;
|
|
230
|
+
if (peak) day.peakCost += cost;
|
|
231
|
+
else day.valleyCost += cost;
|
|
232
|
+
if (!day.firstAt || turn.t < day.firstAt) day.firstAt = turn.t;
|
|
233
|
+
if (turn.t > day.lastAt) day.lastAt = turn.t;
|
|
234
|
+
|
|
235
|
+
const hour = bjDate(turn.t).getUTCHours();
|
|
236
|
+
const bucket = day.hours[hour];
|
|
237
|
+
bucket.cost += cost;
|
|
238
|
+
bucket.calls += 1;
|
|
239
|
+
|
|
240
|
+
const modelKey = price.id;
|
|
241
|
+
const slot = day.models[modelKey] || (day.models[modelKey] = { calls: 0, cost: 0, tokens: 0 });
|
|
242
|
+
slot.calls += 1;
|
|
243
|
+
slot.cost += cost;
|
|
244
|
+
slot.tokens += turn.input + turn.cache + turn.output;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function readLedger() {
|
|
248
|
+
const file = path.join(os.homedir(), '.dsh', '.dshw-usage.json');
|
|
249
|
+
try {
|
|
250
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
251
|
+
return {
|
|
252
|
+
file,
|
|
253
|
+
ok: true,
|
|
254
|
+
date: raw.date,
|
|
255
|
+
todayUsage: typeof raw.todayUsage === 'number' ? raw.todayUsage : null,
|
|
256
|
+
balance: typeof raw.lastBalance === 'number' ? raw.lastBalance : null,
|
|
257
|
+
dayStart: typeof raw.dayStart === 'number' ? raw.dayStart : null,
|
|
258
|
+
history: raw.history && typeof raw.history === 'object' ? raw.history : {},
|
|
259
|
+
updatedAt: fs.statSync(file).mtimeMs,
|
|
260
|
+
};
|
|
261
|
+
} catch {
|
|
262
|
+
return { file, ok: false, history: {} };
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function shapeDay(day) {
|
|
267
|
+
const tokens = day.inputTokens + day.cacheTokens + day.outputTokens;
|
|
268
|
+
const billable = Math.max(1, day.cacheTokens + day.inputTokens);
|
|
269
|
+
return {
|
|
270
|
+
day: day.day,
|
|
271
|
+
calls: day.calls,
|
|
272
|
+
tokens,
|
|
273
|
+
inputTokens: day.inputTokens,
|
|
274
|
+
cacheTokens: day.cacheTokens,
|
|
275
|
+
outputTokens: day.outputTokens,
|
|
276
|
+
cost: round(day.cost),
|
|
277
|
+
costCache: round(day.costCache),
|
|
278
|
+
costMiss: round(day.costMiss),
|
|
279
|
+
costOut: round(day.costOut),
|
|
280
|
+
peakCost: round(day.peakCost),
|
|
281
|
+
valleyCost: round(day.valleyCost),
|
|
282
|
+
peakShare: day.cost > 0 ? day.peakCost / day.cost : 0,
|
|
283
|
+
hitRate: (day.cacheTokens + day.inputTokens) > 0 ? day.cacheTokens / billable : 0,
|
|
284
|
+
avgTokens: day.calls > 0 ? Math.round(tokens / day.calls) : 0,
|
|
285
|
+
firstAt: day.firstAt,
|
|
286
|
+
lastAt: day.lastAt,
|
|
287
|
+
models: day.models,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function round(value) {
|
|
292
|
+
return Math.round(value * 10000) / 10000;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function buildSnapshot() {
|
|
296
|
+
const now = Date.now();
|
|
297
|
+
if (snapshotCache && now - snapshotCache.builtAt < SNAPSHOT_TTL_MS) return snapshotCache.payload;
|
|
298
|
+
|
|
299
|
+
const turns = collectTurns();
|
|
300
|
+
const days = new Map();
|
|
301
|
+
let unknownModels = new Set();
|
|
302
|
+
|
|
303
|
+
for (const turn of turns) {
|
|
304
|
+
if (!Number.isFinite(turn.t)) continue;
|
|
305
|
+
const key = dayKey(turn.t);
|
|
306
|
+
let day = days.get(key);
|
|
307
|
+
if (!day) {
|
|
308
|
+
day = emptyDay(key);
|
|
309
|
+
days.set(key, day);
|
|
310
|
+
}
|
|
311
|
+
addTurn(day, turn);
|
|
312
|
+
if (!/flash|pro/i.test(turn.model)) unknownModels.add(turn.model);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const ledger = readLedger();
|
|
316
|
+
|
|
317
|
+
const dayList = [...days.values()].sort((a, b) => a.day.localeCompare(b.day));
|
|
318
|
+
const window = dayList.slice(-DAYS_SHOWN).map((day) => {
|
|
319
|
+
const shaped = shapeDay(day);
|
|
320
|
+
const booked = ledger.history && ledger.history[day.day];
|
|
321
|
+
shaped.ledger = typeof booked === 'number' ? round(booked) : null;
|
|
322
|
+
shaped.hours = day.hours.map((bucket) => ({
|
|
323
|
+
hour: bucket.hour,
|
|
324
|
+
cost: round(bucket.cost),
|
|
325
|
+
calls: bucket.calls,
|
|
326
|
+
peak: isPeakAt(Date.parse(`${day.day}T00:00:00Z`) - BJ_OFFSET + bucket.hour * 3600_000),
|
|
327
|
+
}));
|
|
328
|
+
return shaped;
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
const todayKey = dayKey(now);
|
|
332
|
+
const today = window.find((entry) => entry.day === todayKey) || null;
|
|
333
|
+
const todayHours = today ? today.hours : emptyDay(todayKey).hours.map((bucket) => ({
|
|
334
|
+
hour: bucket.hour,
|
|
335
|
+
cost: 0,
|
|
336
|
+
calls: 0,
|
|
337
|
+
peak: isPeakAt(Date.parse(`${todayKey}T00:00:00Z`) - BJ_OFFSET + bucket.hour * 3600_000),
|
|
338
|
+
}));
|
|
339
|
+
|
|
340
|
+
const last7 = window.slice(-7);
|
|
341
|
+
const week = last7.reduce(
|
|
342
|
+
(acc, entry) => ({
|
|
343
|
+
cost: acc.cost + entry.cost,
|
|
344
|
+
calls: acc.calls + entry.calls,
|
|
345
|
+
tokens: acc.tokens + entry.tokens,
|
|
346
|
+
peakCost: acc.peakCost + entry.peakCost,
|
|
347
|
+
costCache: acc.costCache + entry.costCache,
|
|
348
|
+
costMiss: acc.costMiss + entry.costMiss,
|
|
349
|
+
costOut: acc.costOut + entry.costOut,
|
|
350
|
+
days: acc.days + 1,
|
|
351
|
+
}),
|
|
352
|
+
{ cost: 0, calls: 0, tokens: 0, peakCost: 0, costCache: 0, costMiss: 0, costOut: 0, days: 0 },
|
|
353
|
+
);
|
|
354
|
+
|
|
355
|
+
const switchPoint = nextSwitch(now);
|
|
356
|
+
const peakNow = isPeakAt(now);
|
|
357
|
+
const currentPrice = PRICING[0];
|
|
358
|
+
|
|
359
|
+
const models = PRICING.map((price) => {
|
|
360
|
+
let calls = 0;
|
|
361
|
+
let cost = 0;
|
|
362
|
+
let tokens = 0;
|
|
363
|
+
for (const entry of window) {
|
|
364
|
+
const slot = entry.models[price.id];
|
|
365
|
+
if (!slot) continue;
|
|
366
|
+
calls += slot.calls;
|
|
367
|
+
cost += slot.cost;
|
|
368
|
+
tokens += slot.tokens;
|
|
369
|
+
}
|
|
370
|
+
return { id: price.id, label: price.label, calls, cost: round(cost), tokens };
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
const payload = {
|
|
374
|
+
ok: true,
|
|
375
|
+
generatedAt: now,
|
|
376
|
+
tz: 'Asia/Shanghai',
|
|
377
|
+
now: {
|
|
378
|
+
ts: now,
|
|
379
|
+
day: todayKey,
|
|
380
|
+
peak: peakNow,
|
|
381
|
+
hour: bjDate(now).getUTCHours(),
|
|
382
|
+
minutesIntoHour: bjDate(now).getUTCMinutes(),
|
|
383
|
+
nextAt: switchPoint.at,
|
|
384
|
+
nextStatus: switchPoint.status,
|
|
385
|
+
price: {
|
|
386
|
+
hit: currentPrice.hit[peakNow ? 1 : 0],
|
|
387
|
+
miss: currentPrice.miss[peakNow ? 1 : 0],
|
|
388
|
+
out: currentPrice.out[peakNow ? 1 : 0],
|
|
389
|
+
},
|
|
390
|
+
},
|
|
391
|
+
today,
|
|
392
|
+
hours: todayHours,
|
|
393
|
+
days: window,
|
|
394
|
+
week: {
|
|
395
|
+
cost: round(week.cost),
|
|
396
|
+
calls: week.calls,
|
|
397
|
+
tokens: week.tokens,
|
|
398
|
+
peakCost: round(week.peakCost),
|
|
399
|
+
costCache: round(week.costCache),
|
|
400
|
+
costMiss: round(week.costMiss),
|
|
401
|
+
costOut: round(week.costOut),
|
|
402
|
+
peakShare: week.cost > 0 ? week.peakCost / week.cost : 0,
|
|
403
|
+
avgPerDay: week.days > 0 ? round(week.cost / week.days) : 0,
|
|
404
|
+
avgPerCall: week.calls > 0 ? Math.round(week.tokens / week.calls) : 0,
|
|
405
|
+
},
|
|
406
|
+
models,
|
|
407
|
+
pricing: PRICING.map((price) => ({
|
|
408
|
+
id: price.id,
|
|
409
|
+
label: price.label,
|
|
410
|
+
hit: price.hit,
|
|
411
|
+
miss: price.miss,
|
|
412
|
+
out: price.out,
|
|
413
|
+
})),
|
|
414
|
+
ledger,
|
|
415
|
+
warnings: unknownModels.size > 0 ? [`未识别的模型按 Flash 价计算: ${[...unknownModels].join(', ')}`] : [],
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
snapshotCache = { builtAt: now, payload };
|
|
419
|
+
return payload;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/* ------------------------------------------------------------------ */
|
|
423
|
+
/* HTTP surface */
|
|
424
|
+
/* ------------------------------------------------------------------ */
|
|
425
|
+
|
|
426
|
+
function sendJson(res, status, payload) {
|
|
427
|
+
const body = Buffer.from(JSON.stringify(payload), 'utf8');
|
|
428
|
+
res.writeHead(status, {
|
|
429
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
430
|
+
'Cache-Control': 'no-store',
|
|
431
|
+
'Content-Length': String(body.length),
|
|
432
|
+
});
|
|
433
|
+
res.end(body);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
export const name = NS;
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Wait for the HTTP carrier before applying.
|
|
440
|
+
*
|
|
441
|
+
* Without this the bundle can be applied before `webServer` exists (cold start
|
|
442
|
+
* ordering), the route never gets registered, and the client half sits on a 404
|
|
443
|
+
* until someone reloads the plugin by hand.
|
|
444
|
+
*/
|
|
445
|
+
export const inject = ['webServer'];
|
|
446
|
+
|
|
447
|
+
export function apply(ctx) {
|
|
448
|
+
const webServer = (typeof ctx.get === 'function' && ctx.get('webServer')) || ctx.webServer;
|
|
449
|
+
if (!webServer || typeof webServer.register !== 'function') {
|
|
450
|
+
ctx.logger?.warn?.(`[${NS}] no webServer in this profile; dashboard route skipped`);
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const trustCheck = (req, res) => {
|
|
455
|
+
try {
|
|
456
|
+
const connection = (typeof ctx.get === 'function' && ctx.get('connection')) || ctx.connection;
|
|
457
|
+
if (!connection || typeof connection.requestRejection !== 'function') return false;
|
|
458
|
+
const rejection = connection.requestRejection(req);
|
|
459
|
+
if (rejection === undefined || rejection === null || rejection === false) return false;
|
|
460
|
+
res.statusCode = typeof rejection === 'number' ? rejection : 403;
|
|
461
|
+
res.end();
|
|
462
|
+
return true;
|
|
463
|
+
} catch {
|
|
464
|
+
return false;
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
const register = (route) => {
|
|
469
|
+
try {
|
|
470
|
+
return webServer.register(route);
|
|
471
|
+
} catch (error) {
|
|
472
|
+
// Hot reload can apply the new half before the old one finalises; a
|
|
473
|
+
// duplicate route must not take the whole plugin down.
|
|
474
|
+
ctx.logger?.warn?.(`[${NS}] route ${route.path} not registered: ${String((error && error.message) || error)}`);
|
|
475
|
+
return () => {};
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
const dispose = register({
|
|
480
|
+
kind: 'exact',
|
|
481
|
+
path: `${ROUTE_BASE}/data`,
|
|
482
|
+
handler: async (req, res) => {
|
|
483
|
+
if (trustCheck(req, res)) return;
|
|
484
|
+
if ((req.method || 'GET').toUpperCase() !== 'GET') {
|
|
485
|
+
sendJson(res, 405, { ok: false, error: 'method not allowed' });
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1');
|
|
489
|
+
if (url.searchParams.get('fresh') === '1' || url.searchParams.get('fresh') === 'true') snapshotCache = null;
|
|
490
|
+
try {
|
|
491
|
+
sendJson(res, 200, buildSnapshot());
|
|
492
|
+
} catch (error) {
|
|
493
|
+
sendJson(res, 500, { ok: false, error: String((error && error.stack) || error) });
|
|
494
|
+
}
|
|
495
|
+
},
|
|
496
|
+
});
|
|
497
|
+
|
|
498
|
+
ctx.effect(() => () => {
|
|
499
|
+
dispose();
|
|
500
|
+
}, `${NS}: dashboard route`);
|
|
501
|
+
}
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-usage-peak",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "DeepSeek Harness 用量峰谷仪表盘:峰/谷时段、今日花费与 tokens、24h 与 14 天趋势、缓存命中与花费构成,侧栏常驻胶囊 + 设置页详情。",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./index.js",
|
|
8
|
+
"./client": "./client.js",
|
|
9
|
+
"./locale/*.json": "./locale/*.json",
|
|
10
|
+
"./icon": "./icon.svg"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"index.js",
|
|
14
|
+
"client.js",
|
|
15
|
+
"cordis.patch.yml",
|
|
16
|
+
"locale/*.json",
|
|
17
|
+
"icon.svg",
|
|
18
|
+
"README.md",
|
|
19
|
+
"LICENSE",
|
|
20
|
+
"CHANGELOG.md",
|
|
21
|
+
"assets/*.webp"
|
|
22
|
+
],
|
|
23
|
+
"dsh": {
|
|
24
|
+
"bundle": {
|
|
25
|
+
"patch": "./cordis.patch.yml"
|
|
26
|
+
},
|
|
27
|
+
"client": {
|
|
28
|
+
"platform": "web",
|
|
29
|
+
"immediately": true,
|
|
30
|
+
"inject": []
|
|
31
|
+
},
|
|
32
|
+
"compatibility": {
|
|
33
|
+
"dshReleases": {
|
|
34
|
+
"0.2.1-rc.3": "compatible"
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"license": "MIT",
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=22.15.0"
|
|
41
|
+
},
|
|
42
|
+
"keywords": [
|
|
43
|
+
"dsh",
|
|
44
|
+
"dsh-plugin",
|
|
45
|
+
"deepseek-harness",
|
|
46
|
+
"usage",
|
|
47
|
+
"tokens",
|
|
48
|
+
"cost",
|
|
49
|
+
"deepseek-api",
|
|
50
|
+
"peak-pricing",
|
|
51
|
+
"cordis",
|
|
52
|
+
"react"
|
|
53
|
+
],
|
|
54
|
+
"private": false,
|
|
55
|
+
"author": "mumuhmumu",
|
|
56
|
+
"repository": {
|
|
57
|
+
"type": "git",
|
|
58
|
+
"url": "git+https://github.com/hhse/dsh-usage-peak.git"
|
|
59
|
+
},
|
|
60
|
+
"homepage": "https://github.com/hhse/dsh-usage-peak#readme",
|
|
61
|
+
"bugs": {
|
|
62
|
+
"url": "https://github.com/hhse/dsh-usage-peak/issues"
|
|
63
|
+
},
|
|
64
|
+
"publishConfig": {
|
|
65
|
+
"access": "public"
|
|
66
|
+
}
|
|
67
|
+
}
|