@kenz1117/dsh-ui-usage-billing 1.8.3-alpha.2 → 1.8.3-alpha.21
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/README.en.md +30 -12
- package/README.md +52 -23
- package/lib/client.js +5 -5
- package/lib/index.js +2566 -407
- package/lib/types/aggregate.d.ts +46 -14
- package/lib/types/balance.d.ts +23 -2
- package/lib/types/builtin-catalog.d.ts +5 -0
- package/lib/types/client/PeakScheduleEditor.d.ts +9 -0
- package/lib/types/client/TaskQueuePanel.d.ts +5 -1
- package/lib/types/client/TokenPanel.d.ts +2 -0
- package/lib/types/client/UsageBilling.d.ts +2 -0
- package/lib/types/client/UsageBillingMainPanel.d.ts +7 -0
- package/lib/types/client/UsageBillingPanelIcon.d.ts +5 -0
- package/lib/types/client/api/balance.d.ts +1 -1
- package/lib/types/client/api/task-queue.d.ts +4 -0
- package/lib/types/client/api/usage-stats.d.ts +16 -2
- package/lib/types/client/constants.d.ts +9 -0
- package/lib/types/client/domain/channel-visibility.d.ts +68 -0
- package/lib/types/client/domain/floating-model.d.ts +31 -0
- package/lib/types/client/domain/types.d.ts +37 -1
- package/lib/types/client/footer-lane.d.ts +114 -0
- package/lib/types/client/live-cost.d.ts +10 -3
- package/lib/types/client/locales.d.ts +2 -1
- package/lib/types/client/panel-capability.d.ts +12 -0
- package/lib/types/client/peak-alert.d.ts +2 -1
- package/lib/types/client/peak-schedule-locales.d.ts +48 -0
- package/lib/types/client/price-drafts.d.ts +19 -0
- package/lib/types/client/price-picker.d.ts +17 -0
- package/lib/types/client/pricing.d.ts +22 -12
- package/lib/types/client/provider-display.d.ts +0 -2
- package/lib/types/client/queue-eligibility.d.ts +45 -0
- package/lib/types/client/round-chart.d.ts +5 -1
- package/lib/types/client/scheduled-band.d.ts +23 -0
- package/lib/types/client/task-queue-quick.d.ts +1 -1
- package/lib/types/client/usage-billing-settings.d.ts +62 -9
- package/lib/types/client/usage-command.d.ts +10 -5
- package/lib/types/config.d.ts +2 -0
- package/lib/types/guard.d.ts +30 -3
- package/lib/types/peak-ledger.d.ts +21 -0
- package/lib/types/peak-schedule-history.d.ts +7 -0
- package/lib/types/peak-schedule-models.d.ts +21 -0
- package/lib/types/peak-schedule-store.d.ts +10 -0
- package/lib/types/peak-schedule.d.ts +67 -0
- package/lib/types/pricing-shared.d.ts +81 -1
- package/lib/types/reconcile.d.ts +11 -2
- package/lib/types/routes/balance.d.ts +6 -3
- package/lib/types/routes/peak-schedule.d.ts +12 -0
- package/lib/types/routes/pricing-models.d.ts +11 -0
- package/lib/types/task-queue-band.d.ts +80 -0
- package/lib/types/task-queue-shared.d.ts +57 -0
- package/lib/types/task-queue.d.ts +110 -3
- package/package.json +75 -64
package/lib/index.js
CHANGED
|
@@ -7,8 +7,223 @@ import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
|
|
|
7
7
|
import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
8
8
|
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
9
9
|
import z from "@deepseek-ai/schemastery";
|
|
10
|
-
import * as sessionTypes from "@deepseek-ai/dsh-session/types";
|
|
11
10
|
import { createHash, createHmac, randomUUID } from "node:crypto";
|
|
11
|
+
import * as sessionTypes from "@deepseek-ai/dsh-session/types";
|
|
12
|
+
import { mkdirSync, readFileSync } from "node:fs";
|
|
13
|
+
//#region lib/types/peak-schedule.js
|
|
14
|
+
const emptySchedule = () => ({
|
|
15
|
+
version: 2,
|
|
16
|
+
models: {}
|
|
17
|
+
});
|
|
18
|
+
const scheduleKey = (source, model) => JSON.stringify([source, model]);
|
|
19
|
+
const accountRoute = (id) => id.trim().toLowerCase() === "deepseek-account";
|
|
20
|
+
function validSource(source) {
|
|
21
|
+
if (source.startsWith("direct:")) return /^[a-z\d_.-]+$/i.test(source.slice(7)) && !accountRoute(source.slice(7));
|
|
22
|
+
if (!source.startsWith("site:")) return false;
|
|
23
|
+
try {
|
|
24
|
+
const url = new URL(source.slice(5));
|
|
25
|
+
return /^https?:$/.test(url.protocol) && url.origin === source.slice(5);
|
|
26
|
+
} catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function record(value) {
|
|
31
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
32
|
+
}
|
|
33
|
+
function int(value, min, max) {
|
|
34
|
+
return typeof value === "number" && Number.isInteger(value) && min <= value && value <= max;
|
|
35
|
+
}
|
|
36
|
+
function parseRule(value) {
|
|
37
|
+
if (!record(value) || Object.keys(value).some((k) => ![
|
|
38
|
+
"windows",
|
|
39
|
+
"holidays",
|
|
40
|
+
"weekendOffPeak",
|
|
41
|
+
"utcOffsetMinutes"
|
|
42
|
+
].includes(k))) throw Error("Invalid rule fields");
|
|
43
|
+
const rule = {};
|
|
44
|
+
if ("windows" in value) {
|
|
45
|
+
const w = value.windows;
|
|
46
|
+
if (!Array.isArray(w) || w.length > 48 || w.length % 2 || !w.every((x) => int(x, 0, 1440))) throw Error("Invalid peak windows");
|
|
47
|
+
const pairs = [];
|
|
48
|
+
for (let i = 0; i < w.length; i += 2) pairs.push([w[i], w[i + 1]]);
|
|
49
|
+
pairs.sort((a, b) => a[0] - b[0]);
|
|
50
|
+
if (pairs.some(([a, b], i) => a >= b || i > 0 && pairs[i - 1][1] > a)) throw Error("Overlapping or empty windows");
|
|
51
|
+
rule.windows = pairs.flat();
|
|
52
|
+
}
|
|
53
|
+
if ("holidays" in value) {
|
|
54
|
+
const days = value.holidays;
|
|
55
|
+
if (!Array.isArray(days) || days.length > 366 || !days.every((d) => {
|
|
56
|
+
if (typeof d !== "string" || !/^\d{8}$/.test(d)) return false;
|
|
57
|
+
const iso = `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6)}`;
|
|
58
|
+
const t = Date.parse(iso + "T00:00:00Z");
|
|
59
|
+
return Number.isFinite(t) && new Date(t).toISOString().startsWith(iso);
|
|
60
|
+
})) throw Error("Invalid off-peak dates");
|
|
61
|
+
rule.holidays = [...new Set(days)].sort();
|
|
62
|
+
}
|
|
63
|
+
if ("weekendOffPeak" in value) {
|
|
64
|
+
if (typeof value.weekendOffPeak !== "boolean") throw Error("Invalid weekend setting");
|
|
65
|
+
rule.weekendOffPeak = value.weekendOffPeak;
|
|
66
|
+
}
|
|
67
|
+
if ("utcOffsetMinutes" in value) {
|
|
68
|
+
if (!int(value.utcOffsetMinutes, -720, 840)) throw Error("Invalid UTC offset");
|
|
69
|
+
rule.utcOffsetMinutes = value.utcOffsetMinutes;
|
|
70
|
+
}
|
|
71
|
+
return rule;
|
|
72
|
+
}
|
|
73
|
+
function modelFromScheduleKey(key) {
|
|
74
|
+
const pair = JSON.parse(key);
|
|
75
|
+
if (!Array.isArray(pair) || pair.length !== 2 || typeof pair[0] !== "string" || !validSource(pair[0]) || typeof pair[1] !== "string" || !pair[1] || key !== scheduleKey(pair[0], pair[1])) throw Error("Invalid source/model key");
|
|
76
|
+
return pair[1];
|
|
77
|
+
}
|
|
78
|
+
function partitionScheduleEdit(value, allowed) {
|
|
79
|
+
if (!record(value) || value.version !== 3 || !record(value.changes) || Object.keys(value).some((key) => key !== "version" && key !== "changes")) throw Error("Expected source-scoped schedule edits");
|
|
80
|
+
const changes = {};
|
|
81
|
+
const results = Object.create(null);
|
|
82
|
+
for (const key of Object.keys(value.changes).sort()) try {
|
|
83
|
+
const model = modelFromScheduleKey(key);
|
|
84
|
+
const rule = value.changes[key] === null ? null : parseRule(value.changes[key]);
|
|
85
|
+
if (rule !== null && !allowed(key, model)) results[key] = "unavailableModel";
|
|
86
|
+
else {
|
|
87
|
+
changes[key] = rule;
|
|
88
|
+
results[key] = "accepted";
|
|
89
|
+
}
|
|
90
|
+
} catch {
|
|
91
|
+
results[key] = "invalidRule";
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
edit: {
|
|
95
|
+
version: 3,
|
|
96
|
+
changes
|
|
97
|
+
},
|
|
98
|
+
results
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function parseScheduleEdit(value) {
|
|
102
|
+
const { edit, results } = partitionScheduleEdit(value, () => true);
|
|
103
|
+
if (Object.values(results).some((result) => result !== "accepted")) throw Error("Invalid schedule change");
|
|
104
|
+
return edit;
|
|
105
|
+
}
|
|
106
|
+
function readScheduleHistory(value) {
|
|
107
|
+
const history = {
|
|
108
|
+
version: 3,
|
|
109
|
+
revisions: []
|
|
110
|
+
};
|
|
111
|
+
const notices = [];
|
|
112
|
+
if (record(value) && (value.version === 1 || value.version === 2)) return {
|
|
113
|
+
history,
|
|
114
|
+
notices: [{ code: "legacySchedule" }]
|
|
115
|
+
};
|
|
116
|
+
if (!record(value) || value.version !== 3 || !Array.isArray(value.revisions)) return {
|
|
117
|
+
history,
|
|
118
|
+
notices: [{ code: "malformedSchedule" }]
|
|
119
|
+
};
|
|
120
|
+
let previous = -1;
|
|
121
|
+
for (const [index, row] of value.revisions.entries()) {
|
|
122
|
+
if (!record(row) || !int(row.effectiveFromMs, 0, 864e13) || row.effectiveFromMs <= previous || !record(row.changes)) {
|
|
123
|
+
notices.push({
|
|
124
|
+
code: "malformedRevision",
|
|
125
|
+
detail: String(index + 1)
|
|
126
|
+
});
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const changes = {};
|
|
130
|
+
for (const key of Object.keys(row.changes).sort()) try {
|
|
131
|
+
modelFromScheduleKey(key);
|
|
132
|
+
changes[key] = row.changes[key] === null ? null : parseRule(row.changes[key]);
|
|
133
|
+
} catch {
|
|
134
|
+
notices.push({
|
|
135
|
+
code: "malformedRule",
|
|
136
|
+
detail: key.slice(0, 240)
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
if (Object.keys(changes).length) {
|
|
140
|
+
previous = row.effectiveFromMs;
|
|
141
|
+
const audit = record(row.audit) && row.audit.source === "local-api" && row.audit.actor === "unidentified" ? {
|
|
142
|
+
source: "local-api",
|
|
143
|
+
actor: "unidentified"
|
|
144
|
+
} : void 0;
|
|
145
|
+
history.revisions.push({
|
|
146
|
+
effectiveFromMs: previous,
|
|
147
|
+
changes,
|
|
148
|
+
...audit && { audit }
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
history,
|
|
154
|
+
notices
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
const TIER_BOUNDARY_MINUTES = [
|
|
158
|
+
540,
|
|
159
|
+
720,
|
|
160
|
+
840,
|
|
161
|
+
1080
|
|
162
|
+
];
|
|
163
|
+
const officialHolidays = "20260925 20260926 20260927 20261001 20261002 20261003 20261004 20261005 20261006 20261007";
|
|
164
|
+
function effectiveRule(source, rule) {
|
|
165
|
+
const official = source === "site:https://api.deepseek.com" || /^direct:deepseek(?:-|$)/i.test(source);
|
|
166
|
+
return {
|
|
167
|
+
windows: [...TIER_BOUNDARY_MINUTES],
|
|
168
|
+
holidays: official ? officialHolidays.split(" ") : [],
|
|
169
|
+
weekendOffPeak: true,
|
|
170
|
+
utcOffsetMinutes: 480,
|
|
171
|
+
...rule
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function customTier(time, rule) {
|
|
175
|
+
const local = new Date(time + rule.utcOffsetMinutes * 6e4);
|
|
176
|
+
const weekday = local.getUTCDay();
|
|
177
|
+
if (rule.weekendOffPeak && (weekday === 0 || weekday === 6)) return "offPeak";
|
|
178
|
+
if (rule.holidays.length && rule.holidays.includes(local.toISOString().slice(0, 10).replaceAll("-", ""))) return "offPeak";
|
|
179
|
+
const minute = local.getUTCHours() * 60 + local.getUTCMinutes();
|
|
180
|
+
return rule.windows.some((start, i, w) => i % 2 === 0 && start <= minute && minute < w[i + 1]) ? "peak" : "offPeak";
|
|
181
|
+
}
|
|
182
|
+
//#endregion
|
|
183
|
+
//#region lib/types/peak-schedule-history.js
|
|
184
|
+
function lastAt(rows, time) {
|
|
185
|
+
let lo = 0;
|
|
186
|
+
let hi = rows.length;
|
|
187
|
+
while (lo < hi) {
|
|
188
|
+
const mid = lo + hi >>> 1;
|
|
189
|
+
if (rows[mid].effectiveFromMs <= time) lo = mid + 1;
|
|
190
|
+
else hi = mid;
|
|
191
|
+
}
|
|
192
|
+
return rows[lo - 1];
|
|
193
|
+
}
|
|
194
|
+
/** A future revision does not change the fingerprint of any earlier fold. */
|
|
195
|
+
function indexPeakHistory(history) {
|
|
196
|
+
if (!history?.revisions.length) return void 0;
|
|
197
|
+
const timelines = /* @__PURE__ */ new Map();
|
|
198
|
+
const hash = createHash("sha256");
|
|
199
|
+
const prefixes = history.revisions.map((revision) => {
|
|
200
|
+
for (const [key, rule] of Object.entries(revision.changes)) {
|
|
201
|
+
const [source] = JSON.parse(key);
|
|
202
|
+
const timeline = timelines.get(key) ?? [];
|
|
203
|
+
timeline.push({
|
|
204
|
+
effectiveFromMs: revision.effectiveFromMs,
|
|
205
|
+
rule: rule === null ? void 0 : effectiveRule(source, rule)
|
|
206
|
+
});
|
|
207
|
+
timelines.set(key, timeline);
|
|
208
|
+
}
|
|
209
|
+
hash.update(JSON.stringify({
|
|
210
|
+
effectiveFromMs: revision.effectiveFromMs,
|
|
211
|
+
changes: revision.changes
|
|
212
|
+
}));
|
|
213
|
+
return {
|
|
214
|
+
effectiveFromMs: revision.effectiveFromMs,
|
|
215
|
+
digest: hash.copy().digest("hex")
|
|
216
|
+
};
|
|
217
|
+
});
|
|
218
|
+
return {
|
|
219
|
+
rule(source, model, time) {
|
|
220
|
+
const timeline = timelines.get(scheduleKey(source, model));
|
|
221
|
+
return timeline && lastAt(timeline, time)?.rule;
|
|
222
|
+
},
|
|
223
|
+
fingerprint: (time) => lastAt(prefixes, time)?.digest
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
//#endregion
|
|
12
227
|
//#region lib/types/client/plan-knowledge.js
|
|
13
228
|
/**
|
|
14
229
|
* Plan-knowledge reference (adapted from dsh-spend's `knowledge.js`, MIT):
|
|
@@ -327,36 +542,14 @@ function isBeijingWeekend(timeMs) {
|
|
|
327
542
|
const day = new Date(timeMs + 288e5).getUTCDay();
|
|
328
543
|
return day === 0 || day === 6;
|
|
329
544
|
}
|
|
330
|
-
/**
|
|
331
|
-
* 中国法定节假日 —— **生成块,勿手改**。数据源
|
|
332
|
-
* [NateScarlet/holiday-cn](https://github.com/NateScarlet/holiday-cn)(逐年抓取国务院公告;
|
|
333
|
-
* 2026 年依据 https://www.gov.cn/zhengce/zhengceku/202511/content_7047091.htm)。
|
|
334
|
-
*
|
|
335
|
-
* 只收录峰谷计费起点({@link WEEKEND_OFFPEAK_START_MS},北京时间 2026-08-23 00:00)之后的日期:
|
|
336
|
-
* 更早的调用由 v1 规则定价,不涉及节假日。表中没有的年份退化为「仅周末低谷」,
|
|
337
|
-
* 国务院公布下一年安排后在此追加一条即可。
|
|
338
|
-
*
|
|
339
|
-
* 编码为空格分隔的 `YYYYMMDD` 列表(按年分组、同年日期连续排列,便于逐年追加):
|
|
340
|
-
* 每个键长度固定为 8,故 `includes` 不会跨键误匹配;相比「区间 + 运行时展开」
|
|
341
|
-
* 省掉一段解析代码——client / index 两个 face 都要过本仓自设的体积成本线
|
|
342
|
-
* (sync.sh 的 256/500 KiB;DSH Store 对插件 JS bundle 本身无审查上限)。
|
|
343
|
-
*/
|
|
344
|
-
const CHINA_HOLIDAYS = "20260925 20260926 20260927 20261001 20261002 20261003 20261004 20261005 20261006 20261007";
|
|
345
545
|
/** 北京日期键 YYYYMMDD(与宿主时区无关)。 */
|
|
346
546
|
function beijingDateKey(timeMs) {
|
|
347
547
|
return new Date(timeMs + 288e5).toISOString().slice(0, 10).replace(/-/g, "");
|
|
348
548
|
}
|
|
349
549
|
/** 时刻是否落在北京时间法定节假日(仅覆盖 {@link CHINA_HOLIDAYS} 内已收录的年份)。 */
|
|
350
550
|
function isBeijingHoliday(timeMs) {
|
|
351
|
-
return
|
|
551
|
+
return officialHolidays.includes(beijingDateKey(timeMs));
|
|
352
552
|
}
|
|
353
|
-
/** 峰谷切换边界(北京时间的当日分钟数):09:00 / 12:00 / 14:00 / 18:00。 */
|
|
354
|
-
const TIER_BOUNDARY_MINUTES = [
|
|
355
|
-
540,
|
|
356
|
-
720,
|
|
357
|
-
840,
|
|
358
|
-
1080
|
|
359
|
-
];
|
|
360
553
|
/**
|
|
361
554
|
* 智谱 Coding Plan 的高峰边界(北京时间当日分钟):工作日 14:00–18:00 为高峰,
|
|
362
555
|
* 额度按基础积分全额抵扣;其余时段(含周末全天)按基础积分 5 折抵扣。
|
|
@@ -529,8 +722,16 @@ function extraModelByKey() {
|
|
|
529
722
|
* - 剥离组织前缀(`deepseek/deepseek-v4-flash` → `deepseek-v4-flash`);
|
|
530
723
|
* - 剥离尾部纯数字段(`deepseek-v4-flash-202605` / `-0731` → `deepseek-v4-flash`,
|
|
531
724
|
* 覆盖 TokenHub / 官方按日期滚动的快照 id);
|
|
725
|
+
* - 剥离冒号分段:中转站路由前缀(`cn:deepseek-v4.1-flash` → `deepseek-v4.1-flash`)与
|
|
726
|
+
* 变体后缀(`deepseek-v4.1-flash:fast` → `deepseek-v4.1-flash`)——中转站
|
|
727
|
+
* 常按线路给模型加前缀(cn:/us:),网关常加变体后缀(:free / :1017),
|
|
728
|
+
* 这些形态此前一律落「未收录」记 0(issue #125);
|
|
532
729
|
* - 两者组合派生。目录键本身(如 `mistral-large-2512`、`command-a-03-2025`)
|
|
533
730
|
* 在直接查就已命中,永不进入派生分支,不受剥段影响。
|
|
731
|
+
*
|
|
732
|
+
* 口径纪律:候选必须**原样**命中目录键(精确别名或归一化索引)才算数——剥段
|
|
733
|
+
* 只是找同一模型的另一种写法,不做「相近即认」的模糊猜测;剥完仍未命中就
|
|
734
|
+
* 保持原 id(回退 other,不计费)。
|
|
534
735
|
*/
|
|
535
736
|
function derivedKeyCandidates(id) {
|
|
536
737
|
const out = [];
|
|
@@ -552,6 +753,19 @@ function derivedKeyCandidates(id) {
|
|
|
552
753
|
push(bare);
|
|
553
754
|
stripTrailingDigits(bare);
|
|
554
755
|
}
|
|
756
|
+
const segments = id.split(/[::]/u);
|
|
757
|
+
if (segments.length > 1) {
|
|
758
|
+
for (let i = 1; i < segments.length; i += 1) {
|
|
759
|
+
const tail = segments.slice(i).join(":");
|
|
760
|
+
push(tail);
|
|
761
|
+
stripTrailingDigits(tail);
|
|
762
|
+
}
|
|
763
|
+
for (let i = 0; i < segments.length - 1; i += 1) {
|
|
764
|
+
const head = segments.slice(i, segments.length - 1).join(":");
|
|
765
|
+
push(head);
|
|
766
|
+
stripTrailingDigits(head);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
555
769
|
stripTrailingDigits(id);
|
|
556
770
|
return out;
|
|
557
771
|
}
|
|
@@ -596,21 +810,35 @@ function livePriceOf(key) {
|
|
|
596
810
|
};
|
|
597
811
|
}
|
|
598
812
|
/** Lookup a model by its stats key; falls back to the generic `other` entry. */
|
|
599
|
-
function modelOf(key) {
|
|
813
|
+
function modelOf(key, { includeUserPrice = true } = {}) {
|
|
600
814
|
const resolved = resolveCatalogKey(key);
|
|
601
815
|
const found = modelCatalog().find((entry) => entry.key === resolved);
|
|
602
816
|
const extra = extraModelByKey().get(resolved);
|
|
603
817
|
const base = found ?? (extra !== void 0 ? extraEntryOf(extra) : modelCatalog().find((entry) => entry.key === "other") ?? UNSEEDED_OTHER);
|
|
818
|
+
const user = includeUserPrice ? void 0 : void 0;
|
|
819
|
+
if (user !== void 0) return {
|
|
820
|
+
...base,
|
|
821
|
+
userPriced: true,
|
|
822
|
+
price: {
|
|
823
|
+
currency: user.currency ?? "CNY",
|
|
824
|
+
input: user.input,
|
|
825
|
+
cacheHit: user.cacheHit,
|
|
826
|
+
output: user.output,
|
|
827
|
+
...user.offPeak !== void 0 ? { offPeak: user.offPeak } : {}
|
|
828
|
+
}
|
|
829
|
+
};
|
|
604
830
|
const live = livePriceOf(resolved);
|
|
605
831
|
if (live === void 0) return base;
|
|
606
832
|
if (base.price.offPeak !== void 0) return base;
|
|
833
|
+
const cacheWrite = base.price.cacheWrite !== void 0 && base.price.input > 0 ? live.input * (base.price.cacheWrite / base.price.input) : void 0;
|
|
607
834
|
return {
|
|
608
835
|
...base,
|
|
609
836
|
price: {
|
|
610
837
|
currency: "USD",
|
|
611
838
|
input: live.input,
|
|
612
839
|
cacheHit: live.cacheHit,
|
|
613
|
-
output: live.output
|
|
840
|
+
output: live.output,
|
|
841
|
+
...cacheWrite !== void 0 ? { cacheWrite } : {}
|
|
614
842
|
}
|
|
615
843
|
};
|
|
616
844
|
}
|
|
@@ -625,7 +853,8 @@ function extraEntryOf(extra) {
|
|
|
625
853
|
currency: "USD",
|
|
626
854
|
input: extra.price.input,
|
|
627
855
|
cacheHit: extra.price.cacheHit,
|
|
628
|
-
output: extra.price.output
|
|
856
|
+
output: extra.price.output,
|
|
857
|
+
...extra.price.cacheWrite !== void 0 ? { cacheWrite: extra.price.cacheWrite } : {}
|
|
629
858
|
}
|
|
630
859
|
};
|
|
631
860
|
}
|
|
@@ -671,6 +900,7 @@ function applyPromo(entry, nowMs) {
|
|
|
671
900
|
input: band.input * factorOf("input"),
|
|
672
901
|
cacheHit: band.cacheHit * factorOf("cacheHit"),
|
|
673
902
|
...band.cacheMiss !== void 0 ? { cacheMiss: band.cacheMiss * factorOf("cacheMiss") } : {},
|
|
903
|
+
...band.cacheWrite !== void 0 ? { cacheWrite: band.cacheWrite * factorOf("cacheWrite") } : {},
|
|
674
904
|
output: band.output * factorOf("output")
|
|
675
905
|
});
|
|
676
906
|
return {
|
|
@@ -689,11 +919,18 @@ function applyPromo(entry, nowMs) {
|
|
|
689
919
|
* Providers that report only disjoint buckets carry `cacheMiss` explicitly;
|
|
690
920
|
* otherwise the miss share is derived as `input - cacheHit`. Only USD-priced
|
|
691
921
|
* bands go through the exchange rate.
|
|
922
|
+
*
|
|
923
|
+
* 缓存写入单列(issue #123):`cacheWrite` 是 `cacheMiss` 的子集,厂商对它
|
|
924
|
+
* 单独计价(`band.cacheWrite`,缺省按输入价)。拆分后普通未命中按
|
|
925
|
+
* `band.cacheMiss ?? band.input`、缓存写入按 `band.cacheWrite ?? band.input`
|
|
926
|
+
* ——`cacheWrite` 缺省时两者同价,与旧口径逐字一致。
|
|
692
927
|
*/
|
|
693
928
|
function priceBandCost(band, buckets, currency) {
|
|
694
|
-
const
|
|
929
|
+
const missTotal = buckets.cacheMiss > 0 ? buckets.cacheMiss : Math.max(0, buckets.input - buckets.cacheHit);
|
|
930
|
+
const write = Math.min(buckets.cacheWrite ?? 0, missTotal);
|
|
931
|
+
const miss = missTotal - write;
|
|
695
932
|
const hit = Math.min(buckets.cacheHit, buckets.input);
|
|
696
|
-
const raw = (miss * (band.cacheMiss ?? band.input) + hit * band.cacheHit + buckets.output * band.output) / 1e6;
|
|
933
|
+
const raw = (miss * (band.cacheMiss ?? band.input) + write * (band.cacheWrite ?? band.input) + hit * band.cacheHit + buckets.output * band.output) / 1e6;
|
|
697
934
|
return currency === "USD" ? raw * currentRate() : raw;
|
|
698
935
|
}
|
|
699
936
|
/**
|
|
@@ -743,13 +980,13 @@ function tariffV1At(timeMs) {
|
|
|
743
980
|
* @param peakShare - fallback mix used only when `timeMs` is missing.
|
|
744
981
|
* @returns the estimated cost in CNY(USD 计价模型已按当前汇率折算)。
|
|
745
982
|
*/
|
|
746
|
-
function computeCostAt(entry, buckets, timeMs, peakShare = DEFAULT_PEAK_SHARE) {
|
|
983
|
+
function computeCostAt(entry, buckets, timeMs, peakShare = DEFAULT_PEAK_SHARE, tierOverride) {
|
|
747
984
|
if (timeMs === null || timeMs === void 0 || !Number.isFinite(timeMs)) return computeCost(entry, buckets, peakShare);
|
|
748
985
|
const priced = applyPromo(entry, timeMs);
|
|
749
986
|
const legacy = timeMs < PEAK_ERA_START_MS && entry.userPriced !== true ? LEGACY_DEEPSEEK_BANDS[entry.key] : void 0;
|
|
750
987
|
if (legacy !== void 0) return priceBandCost(legacy, buckets, "CNY");
|
|
751
988
|
const repriced = timeMs < FLASH_REPRICE_MS && entry.userPriced !== true ? FLASH_REPRICED_OFFPEAK[entry.key] : void 0;
|
|
752
|
-
if (repriced !== void 0) return priceBandCost((timeMs < WEEKEND_OFFPEAK_START_MS ? tariffV1At(timeMs) : tierAt(timeMs)) === "peak" ? {
|
|
989
|
+
if (repriced !== void 0) return priceBandCost((tierOverride ?? (timeMs < WEEKEND_OFFPEAK_START_MS ? tariffV1At(timeMs) : tierAt(timeMs))) === "peak" ? {
|
|
753
990
|
input: repriced.input * 2,
|
|
754
991
|
cacheHit: repriced.cacheHit * 2,
|
|
755
992
|
output: repriced.output * 2
|
|
@@ -760,7 +997,7 @@ function computeCostAt(entry, buckets, timeMs, peakShare = DEFAULT_PEAK_SHARE) {
|
|
|
760
997
|
const off = priceBandCost(priced.price.offPeak, buckets, priced.price.currency);
|
|
761
998
|
return peak * peakShare + off * (1 - peakShare);
|
|
762
999
|
}
|
|
763
|
-
return priceBandCost((timeMs < WEEKEND_OFFPEAK_START_MS ? tariffV1At(timeMs) : tierAt(timeMs)) === "peak" ? priced.price : priced.price.offPeak, buckets, priced.price.currency);
|
|
1000
|
+
return priceBandCost((tierOverride ?? (timeMs < WEEKEND_OFFPEAK_START_MS ? tariffV1At(timeMs) : tierAt(timeMs))) === "peak" ? priced.price : priced.price.offPeak, buckets, priced.price.currency);
|
|
764
1001
|
}
|
|
765
1002
|
/**
|
|
766
1003
|
* Format an amount with adaptive precision and the given currency symbol.
|
|
@@ -785,6 +1022,97 @@ function formatTokens(value) {
|
|
|
785
1022
|
return String(value);
|
|
786
1023
|
}
|
|
787
1024
|
//#endregion
|
|
1025
|
+
//#region lib/types/peak-ledger.js
|
|
1026
|
+
function scheduleTier(schedule, source, entry, model, time) {
|
|
1027
|
+
if (!schedule || !source || entry.key !== model || entry.provider !== "DeepSeek" || !entry.price.offPeak || entry.tierSemantics === "latency") return void 0;
|
|
1028
|
+
const rule = schedule.rule(source, model, time);
|
|
1029
|
+
return rule && customTier(time, rule);
|
|
1030
|
+
}
|
|
1031
|
+
/** Old site buckets lack raw provider ids. Only trust the historical routing fingerprint
|
|
1032
|
+
* when its (unescaped) alias/origin fields can be decoded without ambiguity. */
|
|
1033
|
+
function legacyScheduleSource(fingerprint) {
|
|
1034
|
+
const parts = fingerprint?.split("|");
|
|
1035
|
+
if (parts?.length !== 7) return () => false;
|
|
1036
|
+
const accountIds = /* @__PURE__ */ new Set(["deepseek-account"]);
|
|
1037
|
+
const recordedSites = /* @__PURE__ */ new Set();
|
|
1038
|
+
const protectedSites = /* @__PURE__ */ new Set();
|
|
1039
|
+
for (const pair of parts[2].split(",").filter(Boolean)) {
|
|
1040
|
+
const match = /^([\w.-]+)=([\w.-]+)$/.exec(pair);
|
|
1041
|
+
if (!match) return () => false;
|
|
1042
|
+
if (accountRoute(match[1])) accountIds.add(match[2].toLowerCase());
|
|
1043
|
+
}
|
|
1044
|
+
for (const pair of parts[6].split(",").filter(Boolean)) {
|
|
1045
|
+
const match = /^([\w.-]+)=(https?:\/\/[^,|]+)$/i.exec(pair);
|
|
1046
|
+
if (!match) return () => false;
|
|
1047
|
+
try {
|
|
1048
|
+
const origin = new URL(match[2]).origin;
|
|
1049
|
+
recordedSites.add(`site:${origin}`);
|
|
1050
|
+
if (accountIds.has(match[1].toLowerCase())) protectedSites.add(`site:${origin}`);
|
|
1051
|
+
} catch {
|
|
1052
|
+
return () => false;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return (site) => validSource(site) && (site.startsWith("direct:") ? !accountIds.has(site.slice(7).toLowerCase()) : recordedSites.has(site) && !protectedSites.has(site));
|
|
1056
|
+
}
|
|
1057
|
+
const tokenFields = [
|
|
1058
|
+
"input",
|
|
1059
|
+
"output",
|
|
1060
|
+
"cacheHit",
|
|
1061
|
+
"cacheMiss",
|
|
1062
|
+
"cacheWrite"
|
|
1063
|
+
];
|
|
1064
|
+
const emptyTokens = () => ({
|
|
1065
|
+
input: 0,
|
|
1066
|
+
output: 0,
|
|
1067
|
+
cacheHit: 0,
|
|
1068
|
+
cacheMiss: 0,
|
|
1069
|
+
cacheWrite: 0
|
|
1070
|
+
});
|
|
1071
|
+
function addTokens(target, cell, sign = 1) {
|
|
1072
|
+
for (const field of tokenFields) target[field] += sign * (cell[field] ?? 0);
|
|
1073
|
+
}
|
|
1074
|
+
/** Probe a Beijing wall-clock hour within the ledger's *host-local* calendar day. */
|
|
1075
|
+
function dayProbe(day, hour) {
|
|
1076
|
+
const start = (/* @__PURE__ */ new Date(`${day}T00:00:00`)).getTime();
|
|
1077
|
+
const period = 864e5;
|
|
1078
|
+
const phase = (hour - 8) * 36e5;
|
|
1079
|
+
return phase + Math.ceil((start - phase) / period) * period;
|
|
1080
|
+
}
|
|
1081
|
+
const emptyPrice = () => ({
|
|
1082
|
+
cost: 0,
|
|
1083
|
+
inputCost: 0,
|
|
1084
|
+
outputCost: 0,
|
|
1085
|
+
peakCost: 0,
|
|
1086
|
+
offCost: 0
|
|
1087
|
+
});
|
|
1088
|
+
function addPrice(target, price) {
|
|
1089
|
+
target.cost += price.cost;
|
|
1090
|
+
target.inputCost += price.inputCost;
|
|
1091
|
+
target.outputCost += price.outputCost;
|
|
1092
|
+
target.peakCost += price.peakCost;
|
|
1093
|
+
target.offCost += price.offCost;
|
|
1094
|
+
}
|
|
1095
|
+
function priceLedgerTokens(entry, cell, day, schedule, source) {
|
|
1096
|
+
const result = emptyPrice();
|
|
1097
|
+
for (const [hour, share] of [[10, DEFAULT_PEAK_SHARE], [20, .5]]) {
|
|
1098
|
+
const time = dayProbe(day, hour);
|
|
1099
|
+
const override = Number.isFinite(time) ? scheduleTier(schedule, source, entry, entry.key, time) : void 0;
|
|
1100
|
+
const cost = computeCostAt(entry, cell, time, void 0, override) * share;
|
|
1101
|
+
const output = computeCostAt(entry, {
|
|
1102
|
+
...emptyTokens(),
|
|
1103
|
+
output: cell.output
|
|
1104
|
+
}, time, void 0, override) * share;
|
|
1105
|
+
result.cost += cost;
|
|
1106
|
+
result.outputCost += output;
|
|
1107
|
+
result.inputCost += cost - output;
|
|
1108
|
+
if (entry.tierSemantics !== "latency") {
|
|
1109
|
+
if ((override ?? tierAt(time)) === "peak") result.peakCost += cost;
|
|
1110
|
+
else result.offCost += cost;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
return result;
|
|
1114
|
+
}
|
|
1115
|
+
//#endregion
|
|
788
1116
|
//#region lib/types/builtin-catalog.js
|
|
789
1117
|
/**
|
|
790
1118
|
* Built-in catalog of current mainstream models as of 2026-10-23, priced from
|
|
@@ -812,6 +1140,18 @@ function formatTokens(value) {
|
|
|
812
1140
|
* 价源 = 腾讯云 TokenHub「模型价格」页(2026-11-04 更新)的官方 CN 价。
|
|
813
1141
|
* Hy4 preview 条目与其价格一律不动——同 id 不同模型的收录不构成调价。
|
|
814
1142
|
*
|
|
1143
|
+
* 2026-11-16 扩容:补录腾讯混元 TokenHub 新上架的 **Hy4 flash**(官方 id
|
|
1144
|
+
* `hy4-flash`,刊例价 ¥0.5 / ¥0.02(缓存命中)/ ¥2 每百万 token;官方价目页
|
|
1145
|
+
* 2026-11-16 更新)。价源 = 腾讯云 TokenHub「模型价格」页的官方 CN 价
|
|
1146
|
+
* (models.dev 实时目录尚无该模型条目,国内厂商按官方 CN 价优先的价源口径取
|
|
1147
|
+
* 官方价,不做 USD 折算)。官方同期挂出限时折扣:**自该说明发布之日起至
|
|
1148
|
+
* 2026-11-30 12:00:00(北京时间)按目录价格的 50% 结算** —— 刊例价留在 price
|
|
1149
|
+
* 表,折扣按 promo 建模(只在计价/显示出口折算)。折扣起点取官方价目页
|
|
1150
|
+
* 「最近更新时间」2026-11-16 12:15:30(北京时间)——这是本仓能取证的该说明上线
|
|
1151
|
+
* 时刻,官方未给出更早的明确日期,故不向前追溯(promo 起点规则同 Hy4)。
|
|
1152
|
+
* 本批只加新条目:既有 Hy4 / Hy4 preview 条目的价格与折扣窗口一律不动
|
|
1153
|
+
* (本次官方价目页上 Hy4 仍是 ¥6/¥0.3/¥18,与目录现状逐字一致,不构成调价)。
|
|
1154
|
+
*
|
|
815
1155
|
* Time-of-day billing (peak/off-peak) is now real: DeepSeek V4 officially
|
|
816
1156
|
* splits peak (09:00-12:00 / 14:00-18:00 Beijing) at 2x the off-peak rate
|
|
817
1157
|
* from 2026-08-17, and Gemini's Flex tier discounts spare-capacity traffic.
|
|
@@ -819,6 +1159,56 @@ function formatTokens(value) {
|
|
|
819
1159
|
/** DeepSeek 官方高峰时段说明(峰谷分时计费目录条目共用)。 */
|
|
820
1160
|
const DEEPSEEK_PEAK_HOURS = "09:00-12:00 / 14:00-18:00";
|
|
821
1161
|
const GEMINI_PEAK_HOURS = "Standard / Flex";
|
|
1162
|
+
/**
|
|
1163
|
+
* 厂商「缓存写入」加价系数(issue #123):厂商对「把内容写入缓存」按输入价的
|
|
1164
|
+
* 倍数单独计费,models.dev 原生字段 `cache_write` 即该倍率。
|
|
1165
|
+
* 2026-11-14 核对 models.dev 实时目录:OpenAI 11/11 恒为 125%、Anthropic 18/18
|
|
1166
|
+
* 恒为 125%、百炼(阿里通义)约 125%(`qwen3.8-flash` 例外 156%)。
|
|
1167
|
+
* 未列的厂商不落数值 → 缓存写入按输入价计(DeepSeek、月之暗面等本就不单列
|
|
1168
|
+
* 缓存写入费,与旧口径逐字一致;MiniMax 高速档倍率不恒定,故不给规则)。
|
|
1169
|
+
*/
|
|
1170
|
+
const CACHE_WRITE_FACTORS = {
|
|
1171
|
+
"OpenAI": 1.25,
|
|
1172
|
+
"Anthropic": 1.25,
|
|
1173
|
+
"阿里通义": 1.25
|
|
1174
|
+
};
|
|
1175
|
+
/** 条目内官方「显式缓存创建」价(extraRows 行标签)——厂商公布的缓存写入单价。 */
|
|
1176
|
+
const CACHE_WRITE_ROW_LABEL = "显式缓存创建";
|
|
1177
|
+
/** 单价取整到 6 位小数:消除浮点乘法的尾数噪声(0.3 × 1.25 = 0.375 而非 0.37499…)。 */
|
|
1178
|
+
function roundUnitPrice(value) {
|
|
1179
|
+
return Number(value.toFixed(6));
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* 给目录条目补出缓存写入单价(issue #123):条目自带官方「显式缓存创建」价时
|
|
1183
|
+
* 以官方值为准(百炼各档比例不恒定),否则按厂商加价系数从输入价派生;
|
|
1184
|
+
* 两者皆无 → 不落该字段,计价回退按输入价(与旧口径一致)。
|
|
1185
|
+
* 只动主档:分时计价(offPeak)目前只有 DeepSeek,其缓存写入本就按输入价。
|
|
1186
|
+
*/
|
|
1187
|
+
function withCacheWritePrice(entry) {
|
|
1188
|
+
if (entry.price.cacheWrite !== void 0) return entry;
|
|
1189
|
+
const official = entry.extraRows?.find((row) => row.label === CACHE_WRITE_ROW_LABEL)?.input;
|
|
1190
|
+
if (official !== void 0 && official > 0) return {
|
|
1191
|
+
...entry,
|
|
1192
|
+
price: {
|
|
1193
|
+
...entry.price,
|
|
1194
|
+
cacheWrite: official
|
|
1195
|
+
}
|
|
1196
|
+
};
|
|
1197
|
+
const factor = CACHE_WRITE_FACTORS[entry.provider];
|
|
1198
|
+
if (factor === void 0 || !(entry.price.input > 0)) return entry;
|
|
1199
|
+
return {
|
|
1200
|
+
...entry,
|
|
1201
|
+
price: {
|
|
1202
|
+
...entry.price,
|
|
1203
|
+
cacheWrite: roundUnitPrice(entry.price.input * factor)
|
|
1204
|
+
}
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* 内置计费目录(导出态):在原始条目上派生缓存写入单价(issue #123),
|
|
1209
|
+
* 使「缓存写入」成为独立计价维度——厂商对写入缓存单独计价时(OpenAI/
|
|
1210
|
+
* Anthropic/百炼),缓存写入 token 不再按普通输入价估算。
|
|
1211
|
+
*/
|
|
822
1212
|
const BUILTIN_MODEL_CATALOG = [
|
|
823
1213
|
{
|
|
824
1214
|
key: "flash",
|
|
@@ -928,6 +1318,18 @@ const BUILTIN_MODEL_CATALOG = [
|
|
|
928
1318
|
output: 7
|
|
929
1319
|
}
|
|
930
1320
|
},
|
|
1321
|
+
{
|
|
1322
|
+
key: "glm-5.3-flashx-legal",
|
|
1323
|
+
name: "GLM-5.3-FlashX-Legal",
|
|
1324
|
+
provider: "智谱 AI",
|
|
1325
|
+
colorVar: "dsw-static-blue-300",
|
|
1326
|
+
price: {
|
|
1327
|
+
currency: "CNY",
|
|
1328
|
+
input: 2,
|
|
1329
|
+
cacheHit: .57,
|
|
1330
|
+
output: 7
|
|
1331
|
+
}
|
|
1332
|
+
},
|
|
931
1333
|
{
|
|
932
1334
|
key: "glm-4.6",
|
|
933
1335
|
name: "GLM-4.6",
|
|
@@ -1001,6 +1403,18 @@ const BUILTIN_MODEL_CATALOG = [
|
|
|
1001
1403
|
output: 22
|
|
1002
1404
|
}
|
|
1003
1405
|
},
|
|
1406
|
+
{
|
|
1407
|
+
key: "qwen4-max",
|
|
1408
|
+
name: "Qwen4 Max",
|
|
1409
|
+
provider: "阿里通义",
|
|
1410
|
+
colorVar: "dsw-static-blue-600",
|
|
1411
|
+
price: {
|
|
1412
|
+
currency: "CNY",
|
|
1413
|
+
input: 10,
|
|
1414
|
+
cacheHit: .5,
|
|
1415
|
+
output: 30
|
|
1416
|
+
}
|
|
1417
|
+
},
|
|
1004
1418
|
{
|
|
1005
1419
|
key: "qwen-3.8-max",
|
|
1006
1420
|
name: "Qwen3.8 Max",
|
|
@@ -1576,6 +1990,24 @@ const BUILTIN_MODEL_CATALOG = [
|
|
|
1576
1990
|
note: "限时 5 折至 2026-12-31"
|
|
1577
1991
|
}
|
|
1578
1992
|
},
|
|
1993
|
+
{
|
|
1994
|
+
key: "hunyuan-hy4-flash",
|
|
1995
|
+
name: "混元 Hy4 flash",
|
|
1996
|
+
provider: "腾讯混元",
|
|
1997
|
+
colorVar: "dsw-static-amber-400",
|
|
1998
|
+
price: {
|
|
1999
|
+
currency: "CNY",
|
|
2000
|
+
input: .5,
|
|
2001
|
+
cacheHit: .02,
|
|
2002
|
+
output: 2
|
|
2003
|
+
},
|
|
2004
|
+
promo: {
|
|
2005
|
+
factor: .5,
|
|
2006
|
+
startsAtMs: Date.UTC(2026, 10, 16, 4, 15, 30),
|
|
2007
|
+
endsAtMs: Date.UTC(2026, 10, 30, 4, 0, 0),
|
|
2008
|
+
note: "限时 5 折至 2026-11-30 12:00"
|
|
2009
|
+
}
|
|
2010
|
+
},
|
|
1579
2011
|
{
|
|
1580
2012
|
key: "hy-mt2-pro",
|
|
1581
2013
|
name: "混元 MT2-Pro",
|
|
@@ -1770,6 +2202,78 @@ const BUILTIN_MODEL_CATALOG = [
|
|
|
1770
2202
|
output: .5
|
|
1771
2203
|
}
|
|
1772
2204
|
},
|
|
2205
|
+
{
|
|
2206
|
+
key: "gpt-6.2-sol",
|
|
2207
|
+
name: "GPT-6.2 Sol",
|
|
2208
|
+
provider: "OpenAI",
|
|
2209
|
+
colorVar: "ds-green",
|
|
2210
|
+
price: {
|
|
2211
|
+
currency: "USD",
|
|
2212
|
+
input: 2,
|
|
2213
|
+
cacheHit: .1,
|
|
2214
|
+
output: 10
|
|
2215
|
+
}
|
|
2216
|
+
},
|
|
2217
|
+
{
|
|
2218
|
+
key: "gpt-6.2-astra",
|
|
2219
|
+
name: "GPT-6.2 Astra",
|
|
2220
|
+
provider: "OpenAI",
|
|
2221
|
+
colorVar: "ds-green",
|
|
2222
|
+
price: {
|
|
2223
|
+
currency: "USD",
|
|
2224
|
+
input: 8,
|
|
2225
|
+
cacheHit: .4,
|
|
2226
|
+
output: 40
|
|
2227
|
+
}
|
|
2228
|
+
},
|
|
2229
|
+
{
|
|
2230
|
+
key: "gpt-6.2-astra-healthcare",
|
|
2231
|
+
name: "GPT-6.2 Astra Healthcare",
|
|
2232
|
+
provider: "OpenAI",
|
|
2233
|
+
colorVar: "ds-green",
|
|
2234
|
+
price: {
|
|
2235
|
+
currency: "USD",
|
|
2236
|
+
input: 8,
|
|
2237
|
+
cacheHit: .4,
|
|
2238
|
+
output: 40
|
|
2239
|
+
}
|
|
2240
|
+
},
|
|
2241
|
+
{
|
|
2242
|
+
key: "gpt-6-astra-healthcare",
|
|
2243
|
+
name: "GPT-6 Astra Healthcare",
|
|
2244
|
+
provider: "OpenAI",
|
|
2245
|
+
colorVar: "ds-green",
|
|
2246
|
+
price: {
|
|
2247
|
+
currency: "USD",
|
|
2248
|
+
input: 10,
|
|
2249
|
+
cacheHit: 1,
|
|
2250
|
+
output: 50
|
|
2251
|
+
}
|
|
2252
|
+
},
|
|
2253
|
+
{
|
|
2254
|
+
key: "gpt-6.2-sol-healthcare",
|
|
2255
|
+
name: "GPT-6.2 Sol Healthcare",
|
|
2256
|
+
provider: "OpenAI",
|
|
2257
|
+
colorVar: "ds-green",
|
|
2258
|
+
price: {
|
|
2259
|
+
currency: "USD",
|
|
2260
|
+
input: 2,
|
|
2261
|
+
cacheHit: .1,
|
|
2262
|
+
output: 10
|
|
2263
|
+
}
|
|
2264
|
+
},
|
|
2265
|
+
{
|
|
2266
|
+
key: "gpt-6.1-sol-healthcare",
|
|
2267
|
+
name: "GPT-6.1 Sol Healthcare",
|
|
2268
|
+
provider: "OpenAI",
|
|
2269
|
+
colorVar: "ds-green",
|
|
2270
|
+
price: {
|
|
2271
|
+
currency: "USD",
|
|
2272
|
+
input: 2,
|
|
2273
|
+
cacheHit: .1,
|
|
2274
|
+
output: 10
|
|
2275
|
+
}
|
|
2276
|
+
},
|
|
1773
2277
|
{
|
|
1774
2278
|
key: "gpt-5.6-sol",
|
|
1775
2279
|
name: "GPT-5.6 Sol",
|
|
@@ -2431,6 +2935,42 @@ const BUILTIN_MODEL_CATALOG = [
|
|
|
2431
2935
|
output: 10
|
|
2432
2936
|
}
|
|
2433
2937
|
},
|
|
2938
|
+
{
|
|
2939
|
+
key: "gemini-4-neon",
|
|
2940
|
+
name: "Gemini 4 Neon",
|
|
2941
|
+
provider: "Google",
|
|
2942
|
+
colorVar: "dsw-static-blue-600",
|
|
2943
|
+
price: {
|
|
2944
|
+
currency: "USD",
|
|
2945
|
+
input: 3,
|
|
2946
|
+
cacheHit: .15,
|
|
2947
|
+
output: 15
|
|
2948
|
+
}
|
|
2949
|
+
},
|
|
2950
|
+
{
|
|
2951
|
+
key: "gemini-4-hydrogen",
|
|
2952
|
+
name: "Gemini 4 Hydrogen",
|
|
2953
|
+
provider: "Google",
|
|
2954
|
+
colorVar: "dsw-static-blue-600",
|
|
2955
|
+
price: {
|
|
2956
|
+
currency: "USD",
|
|
2957
|
+
input: 1.5,
|
|
2958
|
+
cacheHit: .075,
|
|
2959
|
+
output: 7.5
|
|
2960
|
+
}
|
|
2961
|
+
},
|
|
2962
|
+
{
|
|
2963
|
+
key: "gemini-4-carbon",
|
|
2964
|
+
name: "Gemini 4 Carbon",
|
|
2965
|
+
provider: "Google",
|
|
2966
|
+
colorVar: "dsw-static-blue-600",
|
|
2967
|
+
price: {
|
|
2968
|
+
currency: "USD",
|
|
2969
|
+
input: 2,
|
|
2970
|
+
cacheHit: .1,
|
|
2971
|
+
output: 10
|
|
2972
|
+
}
|
|
2973
|
+
},
|
|
2434
2974
|
{
|
|
2435
2975
|
key: "gemini-flash-latest",
|
|
2436
2976
|
name: "Gemini Flash Latest",
|
|
@@ -2683,6 +3223,18 @@ const BUILTIN_MODEL_CATALOG = [
|
|
|
2683
3223
|
output: 4.25
|
|
2684
3224
|
}
|
|
2685
3225
|
},
|
|
3226
|
+
{
|
|
3227
|
+
key: "muse-ember-1.0",
|
|
3228
|
+
name: "Muse Ember 1.0",
|
|
3229
|
+
provider: "Meta",
|
|
3230
|
+
colorVar: "ds-red",
|
|
3231
|
+
price: {
|
|
3232
|
+
currency: "USD",
|
|
3233
|
+
input: .1,
|
|
3234
|
+
cacheHit: .004,
|
|
3235
|
+
output: .5
|
|
3236
|
+
}
|
|
3237
|
+
},
|
|
2686
3238
|
{
|
|
2687
3239
|
key: "muse-spark-1.2",
|
|
2688
3240
|
name: "Muse Spark 1.2",
|
|
@@ -2839,6 +3391,18 @@ const BUILTIN_MODEL_CATALOG = [
|
|
|
2839
3391
|
output: 50
|
|
2840
3392
|
}
|
|
2841
3393
|
},
|
|
3394
|
+
{
|
|
3395
|
+
key: "claude-fable-5-2",
|
|
3396
|
+
name: "Claude Fable 5.2",
|
|
3397
|
+
provider: "Anthropic",
|
|
3398
|
+
colorVar: "ds-red",
|
|
3399
|
+
price: {
|
|
3400
|
+
currency: "USD",
|
|
3401
|
+
input: 8,
|
|
3402
|
+
cacheHit: .2,
|
|
3403
|
+
output: 40
|
|
3404
|
+
}
|
|
3405
|
+
},
|
|
2842
3406
|
{
|
|
2843
3407
|
key: "claude-fable-5",
|
|
2844
3408
|
name: "Claude Fable 5",
|
|
@@ -4024,7 +4588,7 @@ const BUILTIN_MODEL_CATALOG = [
|
|
|
4024
4588
|
output: 0
|
|
4025
4589
|
}
|
|
4026
4590
|
}
|
|
4027
|
-
];
|
|
4591
|
+
].map(withCacheWritePrice);
|
|
4028
4592
|
/**
|
|
4029
4593
|
* 真实 provider model id → 计费目录键(`MODEL_CATALOG[].key`)的映射。未知 id
|
|
4030
4594
|
* 原样保留并落回 `other`(未知模型不估算费用)。聚合层(aggregate.ts)在折叠时
|
|
@@ -4055,6 +4619,7 @@ const BUILTIN_MODEL_KEY_ALIASES = {
|
|
|
4055
4619
|
"deepseek-v4-flash": "flash",
|
|
4056
4620
|
"deepseek-v4-flash-vision-exp": "flash-vision-exp",
|
|
4057
4621
|
"deepseek-v4.1-flash": "flash",
|
|
4622
|
+
"deepseek-v4.1": "flash",
|
|
4058
4623
|
"deepseek-v4.1-flash-expires-on-0910": "flash",
|
|
4059
4624
|
"deepseek-flash": "flash",
|
|
4060
4625
|
"deepseek-v4.1-flash-1017": "flash",
|
|
@@ -4116,6 +4681,8 @@ const BUILTIN_MODEL_KEY_ALIASES = {
|
|
|
4116
4681
|
"hunyuan-hy4": "hunyuan-hy4",
|
|
4117
4682
|
"hy4-preview": "hunyuan-hy4-preview",
|
|
4118
4683
|
"hunyuan-hy4-preview": "hunyuan-hy4-preview",
|
|
4684
|
+
"hy4-flash": "hunyuan-hy4-flash",
|
|
4685
|
+
"hunyuan-hy4-flash": "hunyuan-hy4-flash",
|
|
4119
4686
|
"longcat-2.0": "longcat-2.0",
|
|
4120
4687
|
"longcat-2": "longcat-2.0",
|
|
4121
4688
|
"minicpm-v-4.5": "minicpm-v-4.5",
|
|
@@ -4212,8 +4779,76 @@ const BUILTIN_MODEL_KEY_ALIASES = {
|
|
|
4212
4779
|
"grok-4-6": "grok",
|
|
4213
4780
|
"gpt-image-2": "gpt-image-2",
|
|
4214
4781
|
"gpt-image-2.5-sunburst": "gpt-image-2.5-sunburst",
|
|
4215
|
-
"gpt-image-2-5-sunburst": "gpt-image-2.5-sunburst"
|
|
4782
|
+
"gpt-image-2-5-sunburst": "gpt-image-2.5-sunburst",
|
|
4783
|
+
"qwen4-max": "qwen4-max",
|
|
4784
|
+
"gpt-6.2-sol": "gpt-6.2-sol",
|
|
4785
|
+
"gpt-6.2-astra": "gpt-6.2-astra",
|
|
4786
|
+
"gpt-6.2-astra-healthcare": "gpt-6.2-astra-healthcare",
|
|
4787
|
+
"gpt-6-astra-healthcare": "gpt-6-astra-healthcare",
|
|
4788
|
+
"gpt-6.2-sol-healthcare": "gpt-6.2-sol-healthcare",
|
|
4789
|
+
"gpt-6.1-sol-healthcare": "gpt-6.1-sol-healthcare",
|
|
4790
|
+
"gemini-4-neon": "gemini-4-neon",
|
|
4791
|
+
"gemini-4-hydrogen": "gemini-4-hydrogen",
|
|
4792
|
+
"gemini-4-carbon": "gemini-4-carbon",
|
|
4793
|
+
"claude-fable-5-2": "claude-fable-5-2",
|
|
4794
|
+
"glm-5.3-flashx-legal": "glm-5.3-flashx-legal",
|
|
4795
|
+
"muse-ember-1.0": "muse-ember-1.0"
|
|
4796
|
+
};
|
|
4797
|
+
//#endregion
|
|
4798
|
+
//#region lib/types/pricing-shared.js
|
|
4799
|
+
/**
|
|
4800
|
+
* Live-pricing wire types shared by the node half (which fetches and caches
|
|
4801
|
+
* once at boot) and the browser half (which applies the overrides on top of
|
|
4802
|
+
* the built-in catalog). An absent field means the built-in value still
|
|
4803
|
+
* applies — the dashboard degrades to the catalog, never to fabricated data.
|
|
4804
|
+
*/
|
|
4805
|
+
const BALANCE_CLIENT_HEADERS = {
|
|
4806
|
+
version: "x-dsh-billing-client-version",
|
|
4807
|
+
locale: "x-dsh-billing-client-locale",
|
|
4808
|
+
timezone: "x-dsh-billing-client-timezone-offset"
|
|
4216
4809
|
};
|
|
4810
|
+
/**
|
|
4811
|
+
* 宿主内置的两条 DeepSeek 通道的路由 id(宿主包 `llm-deepseek-api-key` /
|
|
4812
|
+
* `llm-deepseek-account` 注册,`0.1.2-alpha.1` ~ `0.2.3-alpha.3` 全程稳定):
|
|
4813
|
+
*
|
|
4814
|
+
* - `deepseek-official`:平台 API key 通道,花的是用户自己的 DeepSeek 平台
|
|
4815
|
+
* 账户余额(凭据 ref 默认 `DEEPSEEK_API_KEY`);
|
|
4816
|
+
* - `deepseek-account`:登录账号通道,花的是宿主登录钱包的余额。
|
|
4817
|
+
*
|
|
4818
|
+
* 两条通道都**不在 llm-pi-ai 路由表里**(插件自造的 `deepseek` 路由 id 与它们
|
|
4819
|
+
* 不同)。钱包归属必须按宿主通道 id 认,否则内置通道的用量桶认不到任何钱包
|
|
4820
|
+
* (issue #141:悬浮卡显示「余额不可确认」)。
|
|
4821
|
+
*/
|
|
4822
|
+
const DEEPSEEK_PLATFORM_ROUTE = "deepseek-official";
|
|
4823
|
+
const DEEPSEEK_LOGIN_ROUTE = "deepseek-account";
|
|
4824
|
+
function siteBucketKey(ref) {
|
|
4825
|
+
if (ref.kind === "site" && ref.origin) return `site:${ref.origin}`;
|
|
4826
|
+
if (ref.kind === "direct" && ref.provider) return `direct:${ref.provider}`;
|
|
4827
|
+
return "unknown";
|
|
4828
|
+
}
|
|
4829
|
+
function siteKeyParts(siteKey) {
|
|
4830
|
+
const colon = siteKey.indexOf(":");
|
|
4831
|
+
const value = siteKey.slice(colon + 1);
|
|
4832
|
+
if (colon > 0 && value) {
|
|
4833
|
+
const kind = siteKey.slice(0, colon);
|
|
4834
|
+
if (kind === "site") return {
|
|
4835
|
+
kind,
|
|
4836
|
+
origin: value
|
|
4837
|
+
};
|
|
4838
|
+
if (kind === "direct") return {
|
|
4839
|
+
kind,
|
|
4840
|
+
route: value
|
|
4841
|
+
};
|
|
4842
|
+
}
|
|
4843
|
+
return { kind: "unknown" };
|
|
4844
|
+
}
|
|
4845
|
+
/** New servers declare coverage explicitly, including for errors. Legacy rows need an exact route or alias. */
|
|
4846
|
+
function balanceCoversSite(row, siteKey) {
|
|
4847
|
+
const parts = siteKeyParts(siteKey);
|
|
4848
|
+
if (parts.kind === "site") return row.walletKind !== "account" && row.sourceOrigin === parts.origin;
|
|
4849
|
+
if (parts.kind !== "direct") return false;
|
|
4850
|
+
return row.attributedRoutes?.includes(parts.route) ?? (row.sourceRoute === parts.route || row.sourceRouteAliases?.includes(parts.route) === true);
|
|
4851
|
+
}
|
|
4217
4852
|
//#endregion
|
|
4218
4853
|
//#region lib/types/aggregate.js
|
|
4219
4854
|
/**
|
|
@@ -4358,12 +4993,6 @@ function siteRefOf(provider, routes, opts = {}) {
|
|
|
4358
4993
|
provider
|
|
4359
4994
|
};
|
|
4360
4995
|
}
|
|
4361
|
-
/** 站点桶的稳定 key:`site:<origin>` 与 `direct:<provider>` 分开,`unknown` 单一桶。 */
|
|
4362
|
-
function siteBucketKey(ref) {
|
|
4363
|
-
if (ref.kind === "site") return `site:${ref.origin ?? ""}`;
|
|
4364
|
-
if (ref.kind === "direct") return `direct:${ref.provider}`;
|
|
4365
|
-
return "unknown";
|
|
4366
|
-
}
|
|
4367
4996
|
/**
|
|
4368
4997
|
* 站点桶按范围求和(usage_stats 工具的 bySite/relay 口径):bySite 全量累计;
|
|
4369
4998
|
* relay 只计中转站桶(`site:<origin>` 键)——`direct:*` 与 `unknown` 不计入,
|
|
@@ -4375,7 +5004,7 @@ function sumSiteBuckets(bySite, range) {
|
|
|
4375
5004
|
let input = 0;
|
|
4376
5005
|
let output = 0;
|
|
4377
5006
|
for (const [bucket, usage] of Object.entries(bySite)) {
|
|
4378
|
-
if (range === "relay" &&
|
|
5007
|
+
if (range === "relay" && siteKeyParts(bucket).kind !== "site") continue;
|
|
4379
5008
|
cost += usage.cost;
|
|
4380
5009
|
calls += usage.calls;
|
|
4381
5010
|
input += usage.input;
|
|
@@ -4420,14 +5049,15 @@ function emptyUsage() {
|
|
|
4420
5049
|
*/
|
|
4421
5050
|
function foldUsage(acc, usage, key, subscription, timeMs, official = false, pricedCost, unverifiedChannel = false) {
|
|
4422
5051
|
const cacheHit = usage.cacheReadTokens ?? 0;
|
|
4423
|
-
const
|
|
5052
|
+
const cacheWrite = usage.cacheWriteTokens ?? 0;
|
|
5053
|
+
const cacheMiss = usage.inputTokens + cacheWrite;
|
|
4424
5054
|
acc.calls += 1;
|
|
4425
|
-
acc.input += usage.inputTokens + cacheHit +
|
|
5055
|
+
acc.input += usage.inputTokens + cacheHit + cacheWrite;
|
|
4426
5056
|
acc.output += usage.outputTokens;
|
|
4427
5057
|
acc.reasoning += usage.reasoningTokens ?? 0;
|
|
4428
5058
|
acc.cacheHit += cacheHit;
|
|
4429
5059
|
acc.cacheMiss += cacheMiss;
|
|
4430
|
-
if (
|
|
5060
|
+
if (cacheWrite > 0) acc.cacheWrite = (acc.cacheWrite ?? 0) + cacheWrite;
|
|
4431
5061
|
if (official) acc.officialCalls += 1;
|
|
4432
5062
|
if (pricedCost !== void 0) {
|
|
4433
5063
|
acc.cost += pricedCost;
|
|
@@ -4439,6 +5069,7 @@ function foldUsage(acc, usage, key, subscription, timeMs, official = false, pric
|
|
|
4439
5069
|
input: cacheHit + cacheMiss,
|
|
4440
5070
|
cacheHit,
|
|
4441
5071
|
cacheMiss,
|
|
5072
|
+
cacheWrite,
|
|
4442
5073
|
output: usage.outputTokens
|
|
4443
5074
|
}, timeMs);
|
|
4444
5075
|
acc.cost += thisCost;
|
|
@@ -4446,6 +5077,75 @@ function foldUsage(acc, usage, key, subscription, timeMs, official = false, pric
|
|
|
4446
5077
|
}
|
|
4447
5078
|
}
|
|
4448
5079
|
/**
|
|
5080
|
+
* 折叠一次模型调用:token 分桶 + 计价 + 订阅/官方标记 + 角色归因。
|
|
5081
|
+
*
|
|
5082
|
+
* `assistant/message`(对话主循环)与 `compaction/summary`(上下文压缩摘要,
|
|
5083
|
+
* issue #123)都是真实的模型调用——后者是宿主落盘的压缩摘要事件,自带
|
|
5084
|
+
* `provider`/`model`/`usage`,此前整段被跳过,压缩调用的次数与费用零计入。
|
|
5085
|
+
* 两者共用本函数,保证计费口径逐字一致。
|
|
5086
|
+
* @returns 本次调用的目录条目与费用(未计价时为 undefined)。
|
|
5087
|
+
*/
|
|
5088
|
+
function foldModelCall(ctx) {
|
|
5089
|
+
const { fold, usage, modelKey, subscription, official, siteBucket, unverifiedChannel, timeMs, day } = ctx;
|
|
5090
|
+
const catalogPriced = isPriced(modelKey);
|
|
5091
|
+
const priced = !subscription && !unverifiedChannel && catalogPriced;
|
|
5092
|
+
if (!subscription && !catalogPriced) fold.unpricedModels.add(modelKey);
|
|
5093
|
+
const entry = modelOf(modelKey);
|
|
5094
|
+
const override = priced && !ctx.protectedAccount ? scheduleTier(ctx.schedule, siteBucket, entry, modelKey, timeMs) : void 0;
|
|
5095
|
+
const thisCost = priced ? computeCostAt(entry, {
|
|
5096
|
+
input: (usage.cacheReadTokens ?? 0) + usage.inputTokens + (usage.cacheWriteTokens ?? 0),
|
|
5097
|
+
cacheHit: usage.cacheReadTokens ?? 0,
|
|
5098
|
+
cacheMiss: usage.inputTokens + (usage.cacheWriteTokens ?? 0),
|
|
5099
|
+
cacheWrite: usage.cacheWriteTokens ?? 0,
|
|
5100
|
+
output: usage.outputTokens
|
|
5101
|
+
}, timeMs, void 0, override) : void 0;
|
|
5102
|
+
foldUsage(fold.total, usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
5103
|
+
foldUsage(usageCell(fold.byModel, modelKey), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
5104
|
+
foldUsage(usageCell(fold.byDay, day), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
5105
|
+
foldUsage(modelDayCell(fold.byDayModels, day, modelKey), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
5106
|
+
const siteCell = modelDaySiteCell(fold.byDayModelsSite, day, modelKey, siteBucket);
|
|
5107
|
+
if (!catalogPriced) {
|
|
5108
|
+
const pending = siteCell.pendingPrice ??= {};
|
|
5109
|
+
if (!subscription && !unverifiedChannel) {
|
|
5110
|
+
const tokens = pending[ctx.protectedAccount ? "native" : "scheduled"] ??= emptyTokens();
|
|
5111
|
+
const hit = usage.cacheReadTokens ?? 0;
|
|
5112
|
+
const write = usage.cacheWriteTokens ?? 0;
|
|
5113
|
+
const miss = usage.inputTokens + write;
|
|
5114
|
+
addTokens(tokens, {
|
|
5115
|
+
input: hit + miss,
|
|
5116
|
+
output: usage.outputTokens,
|
|
5117
|
+
cacheHit: hit,
|
|
5118
|
+
cacheMiss: miss,
|
|
5119
|
+
cacheWrite: write
|
|
5120
|
+
});
|
|
5121
|
+
}
|
|
5122
|
+
}
|
|
5123
|
+
foldUsage(siteCell, usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
5124
|
+
foldUsage(usageCell(fold.bySite, siteBucket), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
5125
|
+
if (entry.tierSemantics !== "latency") foldUsage(usageCell(fold.byTier, override ?? tierAt(timeMs)), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
5126
|
+
if (subscription) fold.planCalls.set(modelKey, (fold.planCalls.get(modelKey) ?? 0) + 1);
|
|
5127
|
+
if (subscription) {
|
|
5128
|
+
const sitePlanKey = planSiteKey(day, modelKey, siteBucket);
|
|
5129
|
+
fold.planSiteCalls.set(sitePlanKey, (fold.planSiteCalls.get(sitePlanKey) ?? 0) + 1);
|
|
5130
|
+
}
|
|
5131
|
+
if (thisCost !== void 0 && entry !== void 0) {
|
|
5132
|
+
const outputCost = computeCostAt(entry, {
|
|
5133
|
+
input: 0,
|
|
5134
|
+
cacheHit: 0,
|
|
5135
|
+
cacheMiss: 0,
|
|
5136
|
+
output: usage.outputTokens
|
|
5137
|
+
}, timeMs, void 0, override);
|
|
5138
|
+
fold.roles.outputCost += outputCost;
|
|
5139
|
+
fold.roles.inputCost += thisCost - outputCost;
|
|
5140
|
+
}
|
|
5141
|
+
return {
|
|
5142
|
+
entry,
|
|
5143
|
+
cost: thisCost,
|
|
5144
|
+
override,
|
|
5145
|
+
catalogPriced
|
|
5146
|
+
};
|
|
5147
|
+
}
|
|
5148
|
+
/**
|
|
4449
5149
|
* Fold one auxiliary web-search LLM request (issue #15) into an accumulator.
|
|
4450
5150
|
* 这类调用绕过对话通道直连官方端点,日志只记请求(无响应/用量事件),token
|
|
4451
5151
|
* 不可知:按「每次估值」计入费用并单独累计 `searchCalls`,不产生 token 维度。
|
|
@@ -4836,6 +5536,277 @@ function deserializeFold(fold) {
|
|
|
4836
5536
|
...fold.title !== void 0 ? { title: fold.title } : {}
|
|
4837
5537
|
};
|
|
4838
5538
|
}
|
|
5539
|
+
/**
|
|
5540
|
+
* 兜底账本行的模型键归一与按日补价(issue #127)。
|
|
5541
|
+
*
|
|
5542
|
+
* 日志已删的会话只剩账本行:行内各模型桶的键是**落盘当时的原始 model id**
|
|
5543
|
+
* (如 `cn:deepseek-v4.1-flash`),此前既不归一化(与已归一的 `flash` 分成两行
|
|
5544
|
+
* 同名模型),也不重新计价(落盘时未收录的模型恒记 0 费 → 概览仍弹「未收录
|
|
5545
|
+
* 计价」、账单少算这笔钱)。报告者实测:同一中转通道下两行同名
|
|
5546
|
+
* DeepSeek V4.1 Flash,token 数完全一致——同一批数据被拆成两个 byModel 键。
|
|
5547
|
+
*
|
|
5548
|
+
* 本函数做两件事:
|
|
5549
|
+
*
|
|
5550
|
+
* 1. **键归一**:按 {@link resolveCatalogKey} 把各模型桶的键归到目录键,同键合并
|
|
5551
|
+
* (含模型×日、模型×日×通道、订阅计数与性能摘要各桶)。归一后账单只剩一行,
|
|
5552
|
+
* 客户端 {@link modelOf} 的显示名也不会再撞车。
|
|
5553
|
+
* 2. **按日补价**:落盘时未收录、而当前目录已收录的模型,用账本里现成的 token
|
|
5554
|
+
* 桶按目录价补算费用——日志已删就没有请求级时间戳,只能按自然日取峰/谷两个
|
|
5555
|
+
* 探针时刻后按 {@link DEFAULT_PEAK_SHARE} 混合(与客户端「目录价预估」同一
|
|
5556
|
+
* 口径);价格时代分段(峰谷时代 / flash 调价分界)与促销窗口仍按该时刻判定,
|
|
5557
|
+
* 不套现行价重算历史。
|
|
5558
|
+
*
|
|
5559
|
+
* 只补「落盘时未收录」的那部分:落盘时已计价的用量其费用原样保留(历史事件按
|
|
5560
|
+
* 事件发生时刻的官方规则计价,不能被按日估算覆盖);订阅通道的调用恒免费,
|
|
5561
|
+
* 不在未收录集合里,因此不会被补价。
|
|
5562
|
+
*
|
|
5563
|
+
* @param fold - 从账本行反序列化出的折叠(不得原地修改)。
|
|
5564
|
+
* @param officialProviderIds - 官方直连 provider 名单(决定官方/三方拆分)。
|
|
5565
|
+
* @returns 归一并补价后的折叠;无需改动时原样返回。
|
|
5566
|
+
*/
|
|
5567
|
+
function reconcileLedgerFold(fold, officialProviderIds, schedule, fingerprint) {
|
|
5568
|
+
const rawKeys = /* @__PURE__ */ new Set();
|
|
5569
|
+
for (const key of fold.byModel.keys()) rawKeys.add(key);
|
|
5570
|
+
for (const models of fold.byDayModels.values()) for (const key of models.keys()) rawKeys.add(key);
|
|
5571
|
+
for (const models of fold.byDayModelsSite.values()) for (const key of models.keys()) rawKeys.add(key);
|
|
5572
|
+
for (const key of fold.unpricedModels) rawKeys.add(key);
|
|
5573
|
+
const resolvedOf = /* @__PURE__ */ new Map();
|
|
5574
|
+
let rekey = false;
|
|
5575
|
+
for (const key of rawKeys) {
|
|
5576
|
+
const resolved = resolveCatalogKey(key);
|
|
5577
|
+
resolvedOf.set(key, resolved);
|
|
5578
|
+
if (resolved !== key) rekey = true;
|
|
5579
|
+
}
|
|
5580
|
+
const resolvedKeyOf = (key) => resolvedOf.get(key) ?? resolveCatalogKey(key);
|
|
5581
|
+
const repriceKeys = /* @__PURE__ */ new Set();
|
|
5582
|
+
for (const key of fold.unpricedModels) if (isPriced(resolvedKeyOf(key))) repriceKeys.add(key);
|
|
5583
|
+
if (!rekey && repriceKeys.size === 0) return fold;
|
|
5584
|
+
const byModel = /* @__PURE__ */ new Map();
|
|
5585
|
+
const byDay = /* @__PURE__ */ new Map();
|
|
5586
|
+
const byDayModels = /* @__PURE__ */ new Map();
|
|
5587
|
+
const byDayModelsSite = /* @__PURE__ */ new Map();
|
|
5588
|
+
const bySite = /* @__PURE__ */ new Map();
|
|
5589
|
+
const byTier = /* @__PURE__ */ new Map();
|
|
5590
|
+
const unpricedModels = /* @__PURE__ */ new Set();
|
|
5591
|
+
const planCalls = /* @__PURE__ */ new Map();
|
|
5592
|
+
const planSiteCalls = /* @__PURE__ */ new Map();
|
|
5593
|
+
const perfDigest = /* @__PURE__ */ new Map();
|
|
5594
|
+
const perfHourDigest = /* @__PURE__ */ new Map();
|
|
5595
|
+
for (const [key, cell] of fold.byModel) mergeUsageInto(usageCell(byModel, resolvedKeyOf(key)), cell);
|
|
5596
|
+
for (const [day, cell] of fold.byDay) byDay.set(day, { ...cell });
|
|
5597
|
+
for (const [day, models] of fold.byDayModels) {
|
|
5598
|
+
const target = /* @__PURE__ */ new Map();
|
|
5599
|
+
for (const [key, cell] of models) mergeUsageInto(usageCell(target, resolvedKeyOf(key)), cell);
|
|
5600
|
+
byDayModels.set(day, target);
|
|
5601
|
+
}
|
|
5602
|
+
for (const [day, models] of fold.byDayModelsSite) {
|
|
5603
|
+
const target = /* @__PURE__ */ new Map();
|
|
5604
|
+
for (const [key, sites] of models) {
|
|
5605
|
+
const siteTarget = /* @__PURE__ */ new Map();
|
|
5606
|
+
for (const [site, cell] of sites) mergeUsageInto(usageCell(siteTarget, site), cell);
|
|
5607
|
+
const resolved = resolvedKeyOf(key);
|
|
5608
|
+
const existing = target.get(resolved);
|
|
5609
|
+
if (existing === void 0) target.set(resolved, siteTarget);
|
|
5610
|
+
else for (const [site, cell] of siteTarget) mergeUsageInto(usageCell(existing, site), cell);
|
|
5611
|
+
}
|
|
5612
|
+
byDayModelsSite.set(day, target);
|
|
5613
|
+
}
|
|
5614
|
+
for (const [site, cell] of fold.bySite) bySite.set(site, { ...cell });
|
|
5615
|
+
for (const [tier, cell] of fold.byTier) byTier.set(tier, { ...cell });
|
|
5616
|
+
for (const key of fold.unpricedModels) {
|
|
5617
|
+
const resolved = resolvedKeyOf(key);
|
|
5618
|
+
if (!isPriced(resolved)) unpricedModels.add(resolved);
|
|
5619
|
+
}
|
|
5620
|
+
for (const [key, count] of fold.planCalls) {
|
|
5621
|
+
const resolved = resolvedKeyOf(key);
|
|
5622
|
+
planCalls.set(resolved, (planCalls.get(resolved) ?? 0) + count);
|
|
5623
|
+
}
|
|
5624
|
+
for (const [key, count] of fold.planSiteCalls) {
|
|
5625
|
+
const parsed = parsePlanSiteKey(key);
|
|
5626
|
+
if (parsed === void 0) {
|
|
5627
|
+
planSiteCalls.set(key, count);
|
|
5628
|
+
continue;
|
|
5629
|
+
}
|
|
5630
|
+
const next = planSiteKey(parsed.day, resolvedKeyOf(parsed.model), parsed.site);
|
|
5631
|
+
planSiteCalls.set(next, (planSiteCalls.get(next) ?? 0) + count);
|
|
5632
|
+
}
|
|
5633
|
+
for (const [key, digest] of fold.perfDigest) {
|
|
5634
|
+
const resolved = resolvedKeyOf(key);
|
|
5635
|
+
const existing = perfDigest.get(resolved);
|
|
5636
|
+
perfDigest.set(resolved, existing === void 0 ? digest : mergeModelDigest(existing, digest));
|
|
5637
|
+
}
|
|
5638
|
+
for (const [hour, models] of fold.perfHourDigest) {
|
|
5639
|
+
const target = /* @__PURE__ */ new Map();
|
|
5640
|
+
for (const [key, digest] of models) {
|
|
5641
|
+
const resolved = resolvedKeyOf(key);
|
|
5642
|
+
const existing = target.get(resolved);
|
|
5643
|
+
target.set(resolved, existing === void 0 ? digest : mergeHourDigest(existing, digest));
|
|
5644
|
+
}
|
|
5645
|
+
perfHourDigest.set(hour, target);
|
|
5646
|
+
}
|
|
5647
|
+
let addedCost = 0;
|
|
5648
|
+
let addedInput = 0;
|
|
5649
|
+
let addedOutput = 0;
|
|
5650
|
+
let addedOfficial = 0;
|
|
5651
|
+
let addedPeak = 0;
|
|
5652
|
+
let addedOff = 0;
|
|
5653
|
+
const safeLegacySource = legacyScheduleSource(fingerprint);
|
|
5654
|
+
for (const [day, models] of fold.byDayModels) for (const [rawKey, cell] of models) {
|
|
5655
|
+
if (!repriceKeys.has(rawKey)) continue;
|
|
5656
|
+
const resolved = resolvedKeyOf(rawKey);
|
|
5657
|
+
const entry = modelOf(resolved);
|
|
5658
|
+
const remainder = emptyTokens();
|
|
5659
|
+
addTokens(remainder, cell);
|
|
5660
|
+
const dayPrice = emptyPrice();
|
|
5661
|
+
let dayOfficial = 0;
|
|
5662
|
+
const siteCells = fold.byDayModelsSite.get(day)?.get(rawKey);
|
|
5663
|
+
if (siteCells) for (const siteCell of siteCells.values()) addTokens(remainder, siteCell, -1);
|
|
5664
|
+
const consistent = tokenFields.every((f) => remainder[f] >= 0);
|
|
5665
|
+
if (!consistent) {
|
|
5666
|
+
Object.assign(remainder, emptyTokens());
|
|
5667
|
+
addTokens(remainder, cell);
|
|
5668
|
+
}
|
|
5669
|
+
if (consistent && siteCells) for (const [site, siteCell] of siteCells) {
|
|
5670
|
+
const siteRepriced = emptyPrice();
|
|
5671
|
+
if (siteCell.pendingPrice) {
|
|
5672
|
+
const { scheduled, native } = siteCell.pendingPrice;
|
|
5673
|
+
if (scheduled) addPrice(siteRepriced, priceLedgerTokens(entry, scheduled, day, schedule, site));
|
|
5674
|
+
if (native) addPrice(siteRepriced, priceLedgerTokens(entry, native, day));
|
|
5675
|
+
} else if (site !== "unknown" && !siteCell.cost && !siteCell.plan && !(fold.planSiteCalls.get(planSiteKey(day, rawKey, site)) ?? (fold.planSiteCalls.size === 0 ? fold.planCalls.get(rawKey) : 0))) addPrice(siteRepriced, priceLedgerTokens(entry, siteCell, day, schedule, safeLegacySource(site) ? site : void 0));
|
|
5676
|
+
addPrice(dayPrice, siteRepriced);
|
|
5677
|
+
const official = isOfficialSiteBucket(site, officialProviderIds);
|
|
5678
|
+
if (official) dayOfficial += siteRepriced.cost;
|
|
5679
|
+
const siteTarget = byDayModelsSite.get(day)?.get(resolved)?.get(site);
|
|
5680
|
+
if (siteTarget !== void 0) {
|
|
5681
|
+
siteTarget.cost += siteRepriced.cost;
|
|
5682
|
+
if (official) siteTarget.officialCost += siteRepriced.cost;
|
|
5683
|
+
}
|
|
5684
|
+
const siteBucketCell = bySite.get(site);
|
|
5685
|
+
if (siteBucketCell !== void 0) {
|
|
5686
|
+
siteBucketCell.cost += siteRepriced.cost;
|
|
5687
|
+
if (official) siteBucketCell.officialCost += siteRepriced.cost;
|
|
5688
|
+
}
|
|
5689
|
+
}
|
|
5690
|
+
if (!cell.cost && !fold.planCalls.get(rawKey) && tokenFields.every((f) => remainder[f] >= 0) && tokenFields.some((f) => remainder[f] > 0)) addPrice(dayPrice, priceLedgerTokens(entry, remainder, day));
|
|
5691
|
+
const { cost: dayCost, inputCost: dayInput, outputCost: dayOutput, peakCost: dayPeak, offCost: dayOff } = dayPrice;
|
|
5692
|
+
const modelCell = byModel.get(resolved);
|
|
5693
|
+
if (modelCell !== void 0) {
|
|
5694
|
+
modelCell.cost += dayCost;
|
|
5695
|
+
modelCell.officialCost += dayOfficial;
|
|
5696
|
+
}
|
|
5697
|
+
const dayCell = byDay.get(day);
|
|
5698
|
+
if (dayCell !== void 0) {
|
|
5699
|
+
dayCell.cost += dayCost;
|
|
5700
|
+
dayCell.officialCost += dayOfficial;
|
|
5701
|
+
}
|
|
5702
|
+
const dayModelCell = byDayModels.get(day)?.get(resolved);
|
|
5703
|
+
if (dayModelCell !== void 0) {
|
|
5704
|
+
dayModelCell.cost += dayCost;
|
|
5705
|
+
dayModelCell.officialCost += dayOfficial;
|
|
5706
|
+
}
|
|
5707
|
+
addedCost += dayCost;
|
|
5708
|
+
addedInput += dayInput;
|
|
5709
|
+
addedOutput += dayOutput;
|
|
5710
|
+
addedOfficial += dayOfficial;
|
|
5711
|
+
addedPeak += dayPeak;
|
|
5712
|
+
addedOff += dayOff;
|
|
5713
|
+
}
|
|
5714
|
+
if (addedPeak) usageCell(byTier, "peak").cost += addedPeak;
|
|
5715
|
+
if (addedOff) usageCell(byTier, "offPeak").cost += addedOff;
|
|
5716
|
+
const turns = fold.turns.map((row) => {
|
|
5717
|
+
const resolved = resolvedKeyOf(row.model);
|
|
5718
|
+
if (!repriceKeys.has(row.model) || row.cost > 0) return {
|
|
5719
|
+
...row,
|
|
5720
|
+
model: resolved
|
|
5721
|
+
};
|
|
5722
|
+
const day = dayStamp(row.startedAt);
|
|
5723
|
+
const sites = fold.byDayModelsSite.get(day)?.get(row.model);
|
|
5724
|
+
const onlySite = sites?.size === 1 ? sites.keys().next().value : void 0;
|
|
5725
|
+
const dayCell = fold.byDayModels.get(day)?.get(row.model);
|
|
5726
|
+
const homogeneous = onlySite && sites?.get(onlySite)?.calls === dayCell?.calls;
|
|
5727
|
+
const source = row.unpricedSource ?? (homogeneous && safeLegacySource(onlySite) ? onlySite : void 0);
|
|
5728
|
+
if (row.unpricedSource === null || !row.unpricedSource && (fold.planCalls.get(row.model) || onlySite === "unknown")) return {
|
|
5729
|
+
...row,
|
|
5730
|
+
model: resolved
|
|
5731
|
+
};
|
|
5732
|
+
const entry = modelOf(resolved);
|
|
5733
|
+
const override = scheduleTier(schedule, source, entry, resolved, row.startedAt);
|
|
5734
|
+
const cost = computeCostAt(entry, {
|
|
5735
|
+
input: row.input,
|
|
5736
|
+
cacheHit: row.cacheHit,
|
|
5737
|
+
cacheMiss: row.cacheMiss,
|
|
5738
|
+
cacheWrite: 0,
|
|
5739
|
+
output: row.output
|
|
5740
|
+
}, row.startedAt, void 0, override);
|
|
5741
|
+
return {
|
|
5742
|
+
...row,
|
|
5743
|
+
model: resolved,
|
|
5744
|
+
cost,
|
|
5745
|
+
...override && { scheduleTier: override }
|
|
5746
|
+
};
|
|
5747
|
+
});
|
|
5748
|
+
const roles = {
|
|
5749
|
+
...fold.roles,
|
|
5750
|
+
inputCost: fold.roles.inputCost + addedInput,
|
|
5751
|
+
outputCost: fold.roles.outputCost + addedOutput
|
|
5752
|
+
};
|
|
5753
|
+
const total = {
|
|
5754
|
+
...fold.total,
|
|
5755
|
+
cost: fold.total.cost + addedCost,
|
|
5756
|
+
officialCost: fold.total.officialCost + addedOfficial
|
|
5757
|
+
};
|
|
5758
|
+
return {
|
|
5759
|
+
...fold,
|
|
5760
|
+
total,
|
|
5761
|
+
byModel,
|
|
5762
|
+
byDay,
|
|
5763
|
+
byDayModels,
|
|
5764
|
+
byDayModelsSite,
|
|
5765
|
+
bySite,
|
|
5766
|
+
byTier,
|
|
5767
|
+
unpricedModels,
|
|
5768
|
+
planCalls,
|
|
5769
|
+
planSiteCalls,
|
|
5770
|
+
perfDigest,
|
|
5771
|
+
perfHourDigest,
|
|
5772
|
+
turns,
|
|
5773
|
+
roles
|
|
5774
|
+
};
|
|
5775
|
+
}
|
|
5776
|
+
/**
|
|
5777
|
+
* 站点桶键能否还原官方直连(官方/三方费用拆分用)。
|
|
5778
|
+
*
|
|
5779
|
+
* 与 {@link officialChannelOf} 的通道判定同口径:配置了 officialProviderIds 时
|
|
5780
|
+
* 以名单为准(站点桶还原不出 provider,保守按三方计);未配置时
|
|
5781
|
+
* `direct:<provider>` 看 provider 是否官方、`site:<origin>` 看 origin 是否官方。
|
|
5782
|
+
*/
|
|
5783
|
+
function isOfficialSiteBucket(siteKey, officialProviderIds) {
|
|
5784
|
+
if (siteKey.startsWith("direct:")) {
|
|
5785
|
+
const provider = siteKey.slice(7);
|
|
5786
|
+
return officialProviderIds !== void 0 ? officialProviderIds.has(provider) : isOfficialProvider(provider);
|
|
5787
|
+
}
|
|
5788
|
+
if (siteKey.startsWith("site:")) {
|
|
5789
|
+
if (officialProviderIds !== void 0) return false;
|
|
5790
|
+
return siteKey.slice(5) === OFFICIAL_DEEPSEEK_ORIGIN;
|
|
5791
|
+
}
|
|
5792
|
+
return false;
|
|
5793
|
+
}
|
|
5794
|
+
/** 解析 {@link planSiteKey} 的 JSON 数组键;形状不符时返回 undefined。 */
|
|
5795
|
+
function parsePlanSiteKey(key) {
|
|
5796
|
+
try {
|
|
5797
|
+
const parsed = JSON.parse(key);
|
|
5798
|
+
if (!Array.isArray(parsed) || parsed.length !== 3) return void 0;
|
|
5799
|
+
const [day, model, site] = parsed;
|
|
5800
|
+
if (typeof day !== "string" || typeof model !== "string" || typeof site !== "string") return void 0;
|
|
5801
|
+
return {
|
|
5802
|
+
day,
|
|
5803
|
+
model,
|
|
5804
|
+
site
|
|
5805
|
+
};
|
|
5806
|
+
} catch {
|
|
5807
|
+
return;
|
|
5808
|
+
}
|
|
5809
|
+
}
|
|
4839
5810
|
/** Runtime boundary for a user-editable/corrupt ledger file. Invalid rows are ignored. */
|
|
4840
5811
|
function ledgerSessionsOf(value) {
|
|
4841
5812
|
if (value === null || typeof value !== "object") return [];
|
|
@@ -4976,7 +5947,8 @@ function freshFold() {
|
|
|
4976
5947
|
* @param routeAliases - 历史路由别名(旧路由名 → 当前路由名),改名/删除路由的
|
|
4977
5948
|
* 历史用量按别名归位,不再落「未知路由」桶。
|
|
4978
5949
|
*/
|
|
4979
|
-
function foldInto(fold, machine, events, subscriptionProviders, officialProviderIds, routes, searchCallEstimateCny, seedLength, routeAliases = {}) {
|
|
5950
|
+
function foldInto(fold, machine, events, subscriptionProviders, officialProviderIds, routes, searchCallEstimateCny, seedLength, routeAliases = {}, schedule) {
|
|
5951
|
+
let protectedAccount = machine.protectedAccount ?? false;
|
|
4980
5952
|
let key = machine.key;
|
|
4981
5953
|
let subscription = machine.subscription;
|
|
4982
5954
|
let official = machine.official;
|
|
@@ -5025,6 +5997,7 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5025
5997
|
if (event.type === "request/header") {
|
|
5026
5998
|
const { model, provider: rawProvider } = event.data.header.config;
|
|
5027
5999
|
const provider = routeAliases[rawProvider] ?? rawProvider;
|
|
6000
|
+
protectedAccount = accountRoute(rawProvider) || accountRoute(provider);
|
|
5028
6001
|
key = resolveCatalogKey(model);
|
|
5029
6002
|
subscription = isSubscriptionCall(subscriptionProviders, provider);
|
|
5030
6003
|
const siteRef = siteRefOf(provider, routes, { subscription });
|
|
@@ -5077,12 +6050,39 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5077
6050
|
}
|
|
5078
6051
|
continue;
|
|
5079
6052
|
}
|
|
6053
|
+
if (event.type === "compaction/summary") {
|
|
6054
|
+
const data = event.data;
|
|
6055
|
+
const compactionUsage = data.usage;
|
|
6056
|
+
if (compactionUsage === void 0) continue;
|
|
6057
|
+
if (typeof data.provider !== "string" || typeof data.model !== "string") continue;
|
|
6058
|
+
const provider = routeAliases[data.provider] ?? data.provider;
|
|
6059
|
+
const modelKey = resolveCatalogKey(data.model);
|
|
6060
|
+
const compactionSubscription = isSubscriptionCall(subscriptionProviders, provider);
|
|
6061
|
+
const siteRef = siteRefOf(provider, routes, { subscription: compactionSubscription });
|
|
6062
|
+
const compactionOfficial = officialChannelOf(provider, siteRef, officialProviderIds);
|
|
6063
|
+
const compactionSiteBucket = siteBucketKey(siteRef);
|
|
6064
|
+
foldModelCall({
|
|
6065
|
+
fold,
|
|
6066
|
+
protectedAccount: accountRoute(data.provider) || accountRoute(provider),
|
|
6067
|
+
schedule,
|
|
6068
|
+
usage: compactionUsage,
|
|
6069
|
+
modelKey,
|
|
6070
|
+
subscription: compactionSubscription,
|
|
6071
|
+
official: compactionOfficial,
|
|
6072
|
+
siteBucket: compactionSiteBucket,
|
|
6073
|
+
unverifiedChannel: compactionSiteBucket === "unknown",
|
|
6074
|
+
timeMs: event.time,
|
|
6075
|
+
day: dayStamp(event.time)
|
|
6076
|
+
});
|
|
6077
|
+
continue;
|
|
6078
|
+
}
|
|
5080
6079
|
if (event.type !== "assistant/message") continue;
|
|
5081
6080
|
const usage = event.data.usage;
|
|
5082
6081
|
if (usage === void 0) continue;
|
|
5083
6082
|
const source = event.data.message?.source;
|
|
5084
6083
|
if (source?.kind === "model" && typeof source.provider === "string" && typeof source.model === "string") {
|
|
5085
6084
|
const provider = routeAliases[source.provider] ?? source.provider;
|
|
6085
|
+
protectedAccount = accountRoute(source.provider) || accountRoute(provider);
|
|
5086
6086
|
key = resolveCatalogKey(source.model);
|
|
5087
6087
|
subscription = isSubscriptionCall(subscriptionProviders, provider);
|
|
5088
6088
|
const siteRef = siteRefOf(provider, routes, { subscription });
|
|
@@ -5091,46 +6091,37 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5091
6091
|
}
|
|
5092
6092
|
const modelKey = key;
|
|
5093
6093
|
const day = dayStamp(event.time);
|
|
5094
|
-
const
|
|
5095
|
-
|
|
5096
|
-
|
|
5097
|
-
|
|
5098
|
-
|
|
5099
|
-
|
|
5100
|
-
|
|
5101
|
-
|
|
5102
|
-
|
|
5103
|
-
|
|
5104
|
-
|
|
5105
|
-
|
|
5106
|
-
|
|
5107
|
-
foldUsage(modelDayCell(fold.byDayModels, day, modelKey), usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
|
|
5108
|
-
foldUsage(modelDaySiteCell(fold.byDayModelsSite, day, modelKey, siteBucket), usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
|
|
5109
|
-
foldUsage(usageCell(fold.bySite, siteBucket), usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
|
|
5110
|
-
if (entry.tierSemantics !== "latency") foldUsage(usageCell(fold.byTier, tierAt(event.time)), usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
|
|
5111
|
-
if (subscription) fold.planCalls.set(modelKey, (fold.planCalls.get(modelKey) ?? 0) + 1);
|
|
5112
|
-
if (subscription) {
|
|
5113
|
-
const sitePlanKey = planSiteKey(day, modelKey, siteBucket);
|
|
5114
|
-
fold.planSiteCalls.set(sitePlanKey, (fold.planSiteCalls.get(sitePlanKey) ?? 0) + 1);
|
|
5115
|
-
}
|
|
6094
|
+
const { entry, cost: thisCost, override, catalogPriced } = foldModelCall({
|
|
6095
|
+
fold,
|
|
6096
|
+
usage,
|
|
6097
|
+
modelKey,
|
|
6098
|
+
subscription,
|
|
6099
|
+
official,
|
|
6100
|
+
siteBucket,
|
|
6101
|
+
schedule,
|
|
6102
|
+
protectedAccount,
|
|
6103
|
+
unverifiedChannel: siteBucket === "unknown",
|
|
6104
|
+
timeMs: event.time,
|
|
6105
|
+
day
|
|
6106
|
+
});
|
|
5116
6107
|
const turn = event.data.turn ?? -1;
|
|
5117
6108
|
const state = turnState(turns, turn);
|
|
6109
|
+
if (!catalogPriced) {
|
|
6110
|
+
const source = subscription || siteBucket === "unknown" ? null : protectedAccount ? "native" : siteBucket;
|
|
6111
|
+
if (state.input || state.output) {
|
|
6112
|
+
if (state.unpricedSource !== source || state.model !== modelKey) state.unpricedSource = null;
|
|
6113
|
+
} else state.unpricedSource = source;
|
|
6114
|
+
} else if (state.unpricedSource !== void 0) state.unpricedSource = null;
|
|
5118
6115
|
state.model = modelKey;
|
|
6116
|
+
if (protectedAccount || subscription || siteBucket === "unknown") delete state.scheduleSource;
|
|
6117
|
+
else state.scheduleSource = siteBucket;
|
|
6118
|
+
if (override === void 0) delete state.scheduleTier;
|
|
6119
|
+
else state.scheduleTier = override;
|
|
5119
6120
|
state.input += usage.inputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0);
|
|
5120
6121
|
state.output += usage.outputTokens;
|
|
5121
6122
|
state.cacheHit += usage.cacheReadTokens ?? 0;
|
|
5122
6123
|
state.cacheMiss += usage.inputTokens + (usage.cacheWriteTokens ?? 0);
|
|
5123
|
-
if (thisCost !== void 0 && entry !== void 0)
|
|
5124
|
-
state.cost += thisCost;
|
|
5125
|
-
const outputCost = computeCostAt(entry, {
|
|
5126
|
-
input: 0,
|
|
5127
|
-
cacheHit: 0,
|
|
5128
|
-
cacheMiss: 0,
|
|
5129
|
-
output: usage.outputTokens
|
|
5130
|
-
}, event.time);
|
|
5131
|
-
fold.roles.outputCost += outputCost;
|
|
5132
|
-
fold.roles.inputCost += thisCost - outputCost;
|
|
5133
|
-
}
|
|
6124
|
+
if (thisCost !== void 0 && entry !== void 0) state.cost += thisCost;
|
|
5134
6125
|
if (state.startedAt === Number.MAX_SAFE_INTEGER) state.startedAt = event.time;
|
|
5135
6126
|
const stepNum = event.data.step;
|
|
5136
6127
|
if (typeof stepNum === "number") {
|
|
@@ -5142,6 +6133,7 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5142
6133
|
}
|
|
5143
6134
|
}
|
|
5144
6135
|
}
|
|
6136
|
+
machine.protectedAccount = protectedAccount;
|
|
5145
6137
|
machine.key = key;
|
|
5146
6138
|
machine.subscription = subscription;
|
|
5147
6139
|
machine.official = official;
|
|
@@ -5153,6 +6145,9 @@ function refreshTurns(fold, machine) {
|
|
|
5153
6145
|
fold.turns = [...machine.turns.values()].filter((state) => state.input > 0 || state.output > 0).sort((a, b) => a.turn - b.turn).map((state) => ({
|
|
5154
6146
|
turn: state.turn,
|
|
5155
6147
|
model: state.model,
|
|
6148
|
+
...state.unpricedSource === void 0 ? {} : { unpricedSource: state.unpricedSource },
|
|
6149
|
+
...state.scheduleSource === void 0 ? {} : { scheduleSource: state.scheduleSource },
|
|
6150
|
+
...state.scheduleTier === void 0 ? {} : { scheduleTier: state.scheduleTier },
|
|
5156
6151
|
input: state.input,
|
|
5157
6152
|
output: state.output,
|
|
5158
6153
|
cacheHit: state.cacheHit,
|
|
@@ -5285,6 +6280,28 @@ function configFingerprint(subscriptionMatcher, officialProviderIds, routeAliase
|
|
|
5285
6280
|
origins
|
|
5286
6281
|
].join("|");
|
|
5287
6282
|
}
|
|
6283
|
+
/** 失败原因摘要:给文档与日志用的短文本(截断,避免超长路径撑爆响应体)。
|
|
6284
|
+
* Error 取 message;非 Error 取字符串化值。截断上限与 task-queue 路由一致(300)。 */
|
|
6285
|
+
function reasonOf(error) {
|
|
6286
|
+
const trimmed = (error instanceof Error ? error.message : String(error)).trim();
|
|
6287
|
+
return trimmed.length > 300 ? `${trimmed.slice(0, 300)}…` : trimmed;
|
|
6288
|
+
}
|
|
6289
|
+
/**
|
|
6290
|
+
* 会话列表整体读不到(issue #119):宿主持久化后端整体故障,或会话目录里有
|
|
6291
|
+
* 读不了/对不上的日志。聚合无法枚举会话,只能降级到持久账本或磁盘快照——
|
|
6292
|
+
* 但「降级」必须让用户看得见,否则新装用户看到的是一片 ¥0(分不清没花钱
|
|
6293
|
+
* 还是没读到)。携带原因随文档下发,客户端据此显示「读取失败」。
|
|
6294
|
+
*/
|
|
6295
|
+
var SessionListUnavailableError = class extends Error {
|
|
6296
|
+
/** 失败原因摘要(面向用户的中文/英文提示语,由调用方决定措辞)。 */
|
|
6297
|
+
reason;
|
|
6298
|
+
constructor(reason, cause) {
|
|
6299
|
+
super(`session list unavailable: ${reason}`);
|
|
6300
|
+
this.name = "SessionListUnavailableError";
|
|
6301
|
+
this.reason = reason;
|
|
6302
|
+
if (cause !== void 0) this.cause = cause;
|
|
6303
|
+
}
|
|
6304
|
+
};
|
|
5288
6305
|
/** 会话格式拒读(宿主 SessionFormatUnsupportedError):日志完好,仅本构建读不了。
|
|
5289
6306
|
* 宿主错误类显式落 error.name;经包装/重建的路径只在 message 里保留类名,两处都认。
|
|
5290
6307
|
* 据此把「格式不受支持」与「损坏/其他读取失败」分开计数,供面板按原因归因(issue #84)。 */
|
|
@@ -5305,14 +6322,17 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5305
6322
|
const maxCacheSessions = options.maxCacheSessions ?? 400;
|
|
5306
6323
|
const cache = /* @__PURE__ */ new Map();
|
|
5307
6324
|
const ledger = /* @__PURE__ */ new Map();
|
|
5308
|
-
let
|
|
6325
|
+
let ledgerLoading;
|
|
6326
|
+
let latestFoldedEvent = -1;
|
|
5309
6327
|
let ledgerNeedsSave = false;
|
|
5310
6328
|
let lastLedgerSaveAt = 0;
|
|
5311
6329
|
const unreadable = /* @__PURE__ */ new Map();
|
|
5312
6330
|
const titleHints = /* @__PURE__ */ new Map();
|
|
5313
6331
|
let inflight;
|
|
6332
|
+
let scheduleWrite;
|
|
5314
6333
|
let ledgerAppliedMigrations;
|
|
5315
6334
|
let lastDoc;
|
|
6335
|
+
let lastHistory;
|
|
5316
6336
|
let lastAt = 0;
|
|
5317
6337
|
const deserializedFoldOf = (() => {
|
|
5318
6338
|
const memo = /* @__PURE__ */ new WeakMap();
|
|
@@ -5324,6 +6344,24 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5324
6344
|
return fold;
|
|
5325
6345
|
};
|
|
5326
6346
|
})();
|
|
6347
|
+
let indexedHistory;
|
|
6348
|
+
let indexedSchedule;
|
|
6349
|
+
let reconciled = /* @__PURE__ */ new WeakMap();
|
|
6350
|
+
function useHistory(history) {
|
|
6351
|
+
if (indexedHistory !== history) {
|
|
6352
|
+
indexedHistory = history;
|
|
6353
|
+
indexedSchedule = indexPeakHistory(history);
|
|
6354
|
+
reconciled = /* @__PURE__ */ new WeakMap();
|
|
6355
|
+
}
|
|
6356
|
+
return indexedSchedule;
|
|
6357
|
+
}
|
|
6358
|
+
function reconciledFoldOf(row) {
|
|
6359
|
+
const hit = reconciled.get(row);
|
|
6360
|
+
if (hit) return hit;
|
|
6361
|
+
const fold = reconcileLedgerFold(deserializedFoldOf(row.fold), officialProviderIds, indexedSchedule, row.fingerprint);
|
|
6362
|
+
reconciled.set(row, fold);
|
|
6363
|
+
return fold;
|
|
6364
|
+
}
|
|
5327
6365
|
/** 每次聚合取最新的 provider 路由视图(中转站零配置发现);缺省按空处理(全部未知路由)。
|
|
5328
6366
|
* 叠加已注册 adapter 的通道(issue #91):宿主 llm 注册表里的 provider 合成无 baseURL
|
|
5329
6367
|
* 的空路由视图——siteRefOf 的路由命中分支正是「无 origin 直连」的语义,归位
|
|
@@ -5354,27 +6392,27 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5354
6392
|
* 价目表变化后未受影响行(无 unpriced 模型)依旧零读取复用。 */
|
|
5355
6393
|
const foldNeedsReprice = (fold) => fold.unpricedModels.some((key) => isPriced(key));
|
|
5356
6394
|
/** 把一份(全量或增量)折叠结果登记进 durable ledger;内容无变化时不落盘。 */
|
|
5357
|
-
const recordLedger = (id, cwd, stamp, fold, subOf) => {
|
|
6395
|
+
const recordLedger = (id, cwd, stamp, fold, subOf, scheduleFingerprint) => {
|
|
5358
6396
|
if (options.ledger === void 0) return;
|
|
5359
6397
|
const entry = {
|
|
5360
6398
|
id,
|
|
5361
6399
|
...cwd === void 0 ? {} : { cwd },
|
|
5362
6400
|
...subOf === void 0 ? {} : { subOf },
|
|
5363
6401
|
...stamp === null ? {} : { stamp },
|
|
5364
|
-
foldVersion:
|
|
6402
|
+
foldVersion: 24,
|
|
5365
6403
|
fingerprint: foldFingerprint,
|
|
6404
|
+
...scheduleFingerprint === void 0 ? {} : { scheduleFingerprint },
|
|
5366
6405
|
foldedAt: Date.now(),
|
|
5367
6406
|
fold: serializeFold(fold)
|
|
5368
6407
|
};
|
|
5369
6408
|
const row = ledger.get(id);
|
|
5370
|
-
if (row === void 0 || row.stamp !== entry.stamp || row.cwd !== entry.cwd || row.subOf !== entry.subOf || row.foldVersion !== entry.foldVersion || row.fingerprint !== entry.fingerprint || stamp === null && JSON.stringify(row.fold) !== JSON.stringify(entry.fold) || stamp !== null && foldNeedsReprice(row.fold)) {
|
|
6409
|
+
if (row === void 0 || row.stamp !== entry.stamp || row.cwd !== entry.cwd || row.subOf !== entry.subOf || row.foldVersion !== entry.foldVersion || row.fingerprint !== entry.fingerprint || row.scheduleFingerprint !== entry.scheduleFingerprint || stamp === null && JSON.stringify(row.fold) !== JSON.stringify(entry.fold) || stamp !== null && foldNeedsReprice(row.fold)) {
|
|
5371
6410
|
ledger.set(id, entry);
|
|
5372
6411
|
ledgerNeedsSave = true;
|
|
5373
6412
|
}
|
|
5374
6413
|
};
|
|
5375
|
-
const
|
|
5376
|
-
if (
|
|
5377
|
-
ledgerLoaded = true;
|
|
6414
|
+
const loadLedger = async () => {
|
|
6415
|
+
if (options.ledger === void 0) return;
|
|
5378
6416
|
try {
|
|
5379
6417
|
const stored = await options.ledger.load();
|
|
5380
6418
|
if (stored !== null && typeof stored === "object" && stored.sessions !== void 0) {
|
|
@@ -5386,11 +6424,15 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5386
6424
|
format: refusal.format === true
|
|
5387
6425
|
});
|
|
5388
6426
|
}
|
|
5389
|
-
for (const entry of ledgerSessionsOf(stored))
|
|
6427
|
+
for (const entry of ledgerSessionsOf(stored)) {
|
|
6428
|
+
ledger.set(entry.id, entry);
|
|
6429
|
+
if (Number.isFinite(entry.fold.lastActive)) latestFoldedEvent = Math.max(latestFoldedEvent, entry.fold.lastActive);
|
|
6430
|
+
}
|
|
5390
6431
|
} catch (error) {
|
|
5391
6432
|
console.warn("[usage-billing] failed to load durable usage ledger; rebuilding from current sessions:", error);
|
|
5392
6433
|
}
|
|
5393
6434
|
};
|
|
6435
|
+
const ensureLedgerLoaded = () => ledgerLoading ??= loadLedger();
|
|
5394
6436
|
/** 失效键:宿主 0.1.3+ 走 adapter 暴露的 revision 令牌;0.1.2 形状退回
|
|
5395
6437
|
* 日志文件 mtime+size(经 locate,拿不到或抛错时返回 null 让调用方重折)。
|
|
5396
6438
|
* locate/stat 调用纳入 try,避免单个会话的异常把整份聚合拖垮。 */
|
|
@@ -5439,11 +6481,12 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5439
6481
|
* 开门后的下一轮即完整折叠)——轻文档的每行折叠反序列化有 WeakMap 记忆,
|
|
5440
6482
|
* 重复构建只付 O(行数) 的汇总合并,冷phase里每个请求都可负担。
|
|
5441
6483
|
*/
|
|
5442
|
-
const aggregateOnce = async (mode) => {
|
|
6484
|
+
const aggregateOnce = async (mode, history, activeSchedule) => {
|
|
5443
6485
|
const now = Date.now();
|
|
5444
6486
|
await ensureLedgerLoaded();
|
|
5445
6487
|
const registeredProviders = options.resolveRegisteredProviders?.() ?? /* @__PURE__ */ new Set();
|
|
5446
6488
|
const roundRoutes = routesOf(registeredProviders);
|
|
6489
|
+
const schedule = useHistory(history);
|
|
5447
6490
|
foldFingerprint = foldFingerprintOf(registeredProviders, roundRoutes);
|
|
5448
6491
|
const seen = /* @__PURE__ */ new Set();
|
|
5449
6492
|
const included = /* @__PURE__ */ new Set();
|
|
@@ -5454,13 +6497,16 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5454
6497
|
let formatUnreadable = 0;
|
|
5455
6498
|
let noLedgerUnreadable = 0;
|
|
5456
6499
|
let staleLedgerSessions = 0;
|
|
6500
|
+
let sessionListError;
|
|
5457
6501
|
if (mode === "full") {
|
|
5458
6502
|
let metas;
|
|
5459
6503
|
try {
|
|
5460
6504
|
metas = await persistence.list();
|
|
5461
6505
|
} catch (error) {
|
|
5462
|
-
|
|
6506
|
+
const reason = reasonOf(error);
|
|
6507
|
+
sessionListError = reason;
|
|
5463
6508
|
console.warn("[usage-billing] session list unavailable; serving durable usage ledger:", error);
|
|
6509
|
+
if (options.ledger === void 0 || ledger.size === 0) throw new SessionListUnavailableError(reason, error);
|
|
5464
6510
|
metas = [];
|
|
5465
6511
|
}
|
|
5466
6512
|
let sliceAt = Date.now();
|
|
@@ -5485,8 +6531,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5485
6531
|
const cwd = meta.cwd;
|
|
5486
6532
|
const subOf = subParentOf(meta);
|
|
5487
6533
|
const ledgerRow = ledger.get(id);
|
|
5488
|
-
if (ledgerRow !== void 0 && ledgerRow.stamp !== void 0 && stamp !== null && ledgerRow.stamp === stamp && (ledgerRow.foldVersion ?? 1) ===
|
|
5489
|
-
const fold =
|
|
6534
|
+
if (ledgerRow !== void 0 && ledgerRow.stamp !== void 0 && stamp !== null && ledgerRow.stamp === stamp && (ledgerRow.foldVersion ?? 1) === 24 && ledgerRow.fingerprint === foldFingerprint && ledgerRow.scheduleFingerprint === schedule?.fingerprint(ledgerRow.fold.lastActive) && !foldNeedsReprice(ledgerRow.fold)) {
|
|
6535
|
+
const fold = reconciledFoldOf(ledgerRow);
|
|
5490
6536
|
folds.push({
|
|
5491
6537
|
id,
|
|
5492
6538
|
...cwd === void 0 ? {} : { cwd },
|
|
@@ -5497,7 +6543,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5497
6543
|
continue;
|
|
5498
6544
|
}
|
|
5499
6545
|
const hit = cache.get(id);
|
|
5500
|
-
if (hit !== void 0 && stamp !== null && hit.stamp === stamp && hit.fingerprint === foldFingerprint && ![...hit.fold.unpricedModels].some((key) => isPriced(key))) {
|
|
6546
|
+
if (hit !== void 0 && stamp !== null && hit.stamp === stamp && hit.fingerprint === foldFingerprint && hit.scheduleFingerprint === schedule?.fingerprint(hit.fold.lastActive) && ![...hit.fold.unpricedModels].some((key) => isPriced(key))) {
|
|
5501
6547
|
cache.delete(id);
|
|
5502
6548
|
cache.set(id, hit);
|
|
5503
6549
|
folds.push({
|
|
@@ -5510,7 +6556,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5510
6556
|
continue;
|
|
5511
6557
|
}
|
|
5512
6558
|
const previous = cache.get(id);
|
|
5513
|
-
if (previous?.machine !== void 0 && previous.lastSeq !== void 0 && previous.fingerprint === foldFingerprint && ![...previous.fold.unpricedModels].some((key) => isPriced(key))) {
|
|
6559
|
+
if (previous?.machine !== void 0 && previous.lastSeq !== void 0 && previous.fingerprint === foldFingerprint && previous.scheduleFingerprint === schedule?.fingerprint(previous.fold.lastActive) && ![...previous.fold.unpricedModels].some((key) => isPriced(key))) {
|
|
5514
6560
|
const from = previous.lastSeq + 1;
|
|
5515
6561
|
const { events, inheritedEventCount } = await persistence.readFrom(meta.id, sessionLogOffsetOf(from));
|
|
5516
6562
|
const after = await stampOf(meta);
|
|
@@ -5523,7 +6569,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5523
6569
|
cache.delete(id);
|
|
5524
6570
|
continue;
|
|
5525
6571
|
}
|
|
5526
|
-
foldInto(previous.fold, previous.machine, events, subscriptionMatcher, officialProviderIds, roundRoutes, searchEstimate, inheritedEventCount, routeAliases);
|
|
6572
|
+
foldInto(previous.fold, previous.machine, events, subscriptionMatcher, officialProviderIds, roundRoutes, searchEstimate, inheritedEventCount, routeAliases, schedule);
|
|
6573
|
+
if (Number.isFinite(previous.fold.lastActive)) latestFoldedEvent = Math.max(latestFoldedEvent, previous.fold.lastActive);
|
|
5527
6574
|
refreshTurns(previous.fold, previous.machine);
|
|
5528
6575
|
previous.lastSeq = events[events.length - 1]?.seq ?? previous.lastSeq;
|
|
5529
6576
|
previous.stamp = stamp;
|
|
@@ -5536,7 +6583,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5536
6583
|
fold: previous.fold
|
|
5537
6584
|
});
|
|
5538
6585
|
included.add(id);
|
|
5539
|
-
|
|
6586
|
+
previous.scheduleFingerprint = schedule?.fingerprint(previous.fold.lastActive);
|
|
6587
|
+
recordLedger(id, cwd, stamp, previous.fold, subOf, previous.scheduleFingerprint);
|
|
5540
6588
|
continue;
|
|
5541
6589
|
}
|
|
5542
6590
|
const { events, inheritedEventCount } = await persistence.readFrom(meta.id, sessionLogOffsetOf(0));
|
|
@@ -5545,7 +6593,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5545
6593
|
const fold = freshFold();
|
|
5546
6594
|
const machine = freshMachine();
|
|
5547
6595
|
for (let start = 0; start < events.length; start += FOLD_CHUNK_EVENTS) {
|
|
5548
|
-
foldInto(fold, machine, events.slice(start, start + FOLD_CHUNK_EVENTS), subscriptionMatcher, officialProviderIds, roundRoutes, searchEstimate, inheritedEventCount, routeAliases);
|
|
6596
|
+
foldInto(fold, machine, events.slice(start, start + FOLD_CHUNK_EVENTS), subscriptionMatcher, officialProviderIds, roundRoutes, searchEstimate, inheritedEventCount, routeAliases, schedule);
|
|
6597
|
+
if (Number.isFinite(fold.lastActive)) latestFoldedEvent = Math.max(latestFoldedEvent, fold.lastActive);
|
|
5549
6598
|
if (start + FOLD_CHUNK_EVENTS < events.length && Date.now() - sliceAt >= FOLD_SLICE_MS) {
|
|
5550
6599
|
await new Promise((resolve) => {
|
|
5551
6600
|
setImmediate(resolve);
|
|
@@ -5560,7 +6609,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5560
6609
|
fold,
|
|
5561
6610
|
machine,
|
|
5562
6611
|
...last !== void 0 && typeof last.seq === "number" ? { lastSeq: last.seq } : {},
|
|
5563
|
-
fingerprint: foldFingerprint
|
|
6612
|
+
fingerprint: foldFingerprint,
|
|
6613
|
+
scheduleFingerprint: schedule?.fingerprint(fold.lastActive)
|
|
5564
6614
|
});
|
|
5565
6615
|
folds.push({
|
|
5566
6616
|
id,
|
|
@@ -5569,7 +6619,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5569
6619
|
fold
|
|
5570
6620
|
});
|
|
5571
6621
|
included.add(id);
|
|
5572
|
-
recordLedger(id, cwd, stamp, fold, subOf);
|
|
6622
|
+
recordLedger(id, cwd, stamp, fold, subOf, schedule?.fingerprint(fold.lastActive));
|
|
5573
6623
|
} catch (error) {
|
|
5574
6624
|
skipped.push(id);
|
|
5575
6625
|
const format = isFormatUnsupportedError(error);
|
|
@@ -5614,8 +6664,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5614
6664
|
}
|
|
5615
6665
|
if (included.has(entry.id)) continue;
|
|
5616
6666
|
try {
|
|
5617
|
-
const stale = (entry.foldVersion ?? 1) <
|
|
5618
|
-
const fold =
|
|
6667
|
+
const stale = (entry.foldVersion ?? 1) < 24 || entry.fingerprint !== foldFingerprint;
|
|
6668
|
+
const fold = reconciledFoldOf(entry);
|
|
5619
6669
|
const hint = titleHints.get(entry.id);
|
|
5620
6670
|
folds.push({
|
|
5621
6671
|
id: entry.id,
|
|
@@ -5761,10 +6811,16 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5761
6811
|
};
|
|
5762
6812
|
const toModelDayRecord = (map) => Object.fromEntries([...map].map(([day, models]) => [day, Object.fromEntries(models)]));
|
|
5763
6813
|
const toModelDaySiteRecord = (map) => Object.fromEntries([...map].map(([day, models]) => [day, Object.fromEntries([...models].map(([model, sites]) => [model, Object.fromEntries([...sites].map(([site, cell]) => {
|
|
5764
|
-
|
|
6814
|
+
const count = planSiteCalls.get(planSiteKey(day, model, site)) ?? 0;
|
|
6815
|
+
if (count === cell.calls && count > 0) return [site, {
|
|
5765
6816
|
...cell,
|
|
5766
6817
|
plan: true
|
|
5767
|
-
}
|
|
6818
|
+
}];
|
|
6819
|
+
if (count > 0 && count < cell.calls) return [site, {
|
|
6820
|
+
...cell,
|
|
6821
|
+
planCalls: count
|
|
6822
|
+
}];
|
|
6823
|
+
return [site, cell];
|
|
5768
6824
|
}))]))]));
|
|
5769
6825
|
const modelKeys = /* @__PURE__ */ new Set([...perfModel.keys(), ...perfModelDigest.keys()]);
|
|
5770
6826
|
const hourKeys = /* @__PURE__ */ new Set([...perfHourModel.keys(), ...perfHourDigest.keys()]);
|
|
@@ -5800,6 +6856,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5800
6856
|
byDayModels: toModelDayRecord(byDayModels),
|
|
5801
6857
|
...byDayModelsSite.size === 0 ? {} : { byDayModelsSite: toModelDaySiteRecord(byDayModelsSite) },
|
|
5802
6858
|
bySession: sessionRows.slice(0, 100),
|
|
6859
|
+
bySessionTotal: sessionRows.length,
|
|
6860
|
+
...activeSchedule ? { peakSchedule: activeSchedule } : {},
|
|
5803
6861
|
byTurn: turnRows.slice(0, 200),
|
|
5804
6862
|
byWorkspace: workspaces.slice(0, 100),
|
|
5805
6863
|
...byTier.size === 0 ? {} : { byTier: {
|
|
@@ -5824,24 +6882,42 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5824
6882
|
tool: roles.inputCost * (1 - userShare)
|
|
5825
6883
|
};
|
|
5826
6884
|
})(),
|
|
5827
|
-
...mode === "ledger-only" ? { staleSnapshot: true } : {}
|
|
6885
|
+
...mode === "ledger-only" ? { staleSnapshot: true } : {},
|
|
6886
|
+
...sessionListError === void 0 ? {} : { sessionListError }
|
|
5828
6887
|
};
|
|
5829
6888
|
if (mode === "full") {
|
|
5830
6889
|
lastDoc = document;
|
|
6890
|
+
lastHistory = history;
|
|
5831
6891
|
lastAt = now;
|
|
5832
6892
|
}
|
|
5833
6893
|
return document;
|
|
5834
6894
|
};
|
|
5835
6895
|
return {
|
|
5836
6896
|
aggregate() {
|
|
6897
|
+
if (scheduleWrite !== void 0) return scheduleWrite.then(() => this.aggregate(), () => this.aggregate());
|
|
5837
6898
|
const now = Date.now();
|
|
5838
|
-
|
|
5839
|
-
|
|
5840
|
-
|
|
6899
|
+
const currentSchedule = options.resolvePeakSchedule?.();
|
|
6900
|
+
const activeSchedule = currentSchedule && Object.keys(currentSchedule.models).length ? currentSchedule : void 0;
|
|
6901
|
+
const history = options.resolvePeakHistory?.();
|
|
6902
|
+
if (lastDoc !== void 0 && lastHistory === history && lastDoc.peakSchedule === activeSchedule && now - lastAt < 5e3) return Promise.resolve(lastDoc);
|
|
6903
|
+
if (now < foldAllowedAt) return inflight ?? aggregateOnce("ledger-only", history, activeSchedule);
|
|
6904
|
+
inflight ??= aggregateOnce("full", history, activeSchedule).finally(() => {
|
|
5841
6905
|
inflight = void 0;
|
|
5842
6906
|
});
|
|
5843
6907
|
return inflight;
|
|
5844
6908
|
},
|
|
6909
|
+
withPeakScheduleChange(save) {
|
|
6910
|
+
const previous = scheduleWrite ?? inflight;
|
|
6911
|
+
const commit = (async () => {
|
|
6912
|
+
if (previous !== void 0) await previous.catch(() => void 0);
|
|
6913
|
+
await ensureLedgerLoaded();
|
|
6914
|
+
return save(latestFoldedEvent);
|
|
6915
|
+
})().finally(() => {
|
|
6916
|
+
if (scheduleWrite === commit) scheduleWrite = void 0;
|
|
6917
|
+
});
|
|
6918
|
+
scheduleWrite = commit;
|
|
6919
|
+
return commit;
|
|
6920
|
+
},
|
|
5845
6921
|
async sessionUsageOf(sessionId) {
|
|
5846
6922
|
await this.aggregate();
|
|
5847
6923
|
const hit = cache.get(sessionId);
|
|
@@ -5854,7 +6930,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5854
6930
|
const row = ledger.get(sessionId);
|
|
5855
6931
|
if (row === void 0) return void 0;
|
|
5856
6932
|
try {
|
|
5857
|
-
const fold =
|
|
6933
|
+
const fold = reconciledFoldOf(row);
|
|
5858
6934
|
return {
|
|
5859
6935
|
calls: fold.total.calls,
|
|
5860
6936
|
cost: fold.total.cost,
|
|
@@ -6190,6 +7266,12 @@ const customGate = createCooldownGate({
|
|
|
6190
7266
|
});
|
|
6191
7267
|
/** DeepSeek 官方余额接口(官方文档 api-docs.deepseek.com/api/get-user-balance)。 */
|
|
6192
7268
|
const DEEPSEEK_BALANCE_URL = "https://api.deepseek.com/user/balance";
|
|
7269
|
+
/**
|
|
7270
|
+
* 宿主内置平台通道(路由 id `deepseek-official`)的默认凭据 ref——宿主包
|
|
7271
|
+
* `llm-deepseek-api-key` 的 `apiKeyEnv` 默认值(`0.1.2-alpha.1` ~ `0.2.3-alpha.3`)。
|
|
7272
|
+
* 内置通道不在 llm-pi-ai 路由表里,只能按这个约定 ref 找回它的 key。
|
|
7273
|
+
*/
|
|
7274
|
+
const DEEPSEEK_PLATFORM_KEY_REF = "DEEPSEEK_API_KEY";
|
|
6193
7275
|
/** Moonshot/Kimi 官方余额接口(platform.kimi.com/docs/api/balance)。 */
|
|
6194
7276
|
const MOONSHOT_BALANCE_URL = "https://api.moonshot.cn/v1/users/me/balance";
|
|
6195
7277
|
/** 阶跃星辰 StepFun 官方账户信息接口(platform.stepfun.com/docs/api-reference/accounts/get)。 */
|
|
@@ -6200,26 +7282,18 @@ const SILICONFLOW_BALANCE_URL = "https://api.siliconflow.cn/v1/user/info";
|
|
|
6200
7282
|
const XAI_CREDITS_URL = "https://api.x.ai/v1/billing/credits";
|
|
6201
7283
|
/** 智谱 GLM(大模型国内域)官方余额接口(open.bigmodel.cn/api/paas/v4/balance)。 */
|
|
6202
7284
|
const ZHIPU_BALANCE_URL = "https://open.bigmodel.cn/api/paas/v4/balance";
|
|
6203
|
-
/** 数字归一化:接口返回的余额是字符串(如 `"110.00"`),统一转 number。 */
|
|
6204
7285
|
/**
|
|
6205
7286
|
* Fetch a Bearer-protected balance endpoint and normalize the HTTP outcome into
|
|
6206
7287
|
* a shared {@link ProviderBalance} row. Each provider supplies its own
|
|
6207
7288
|
* response parser for the success body.
|
|
6208
|
-
* @param ctx - host context carrying the credentials seam.
|
|
6209
7289
|
* @param url - the balance endpoint.
|
|
6210
|
-
* @param
|
|
7290
|
+
* @param key - resolved credential for this query.
|
|
6211
7291
|
* @param provider - the provider id (matches the model-table vendor display name).
|
|
6212
7292
|
* @param displayName - human-readable provider name.
|
|
6213
7293
|
* @param parse - maps a success JSON body to the balance row fields.
|
|
6214
7294
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6215
7295
|
*/
|
|
6216
|
-
async function queryBearerBalance(
|
|
6217
|
-
const hit = await ctx.credentials.resolve(credentialRef(apiKeyEnv));
|
|
6218
|
-
if (hit === void 0) return {
|
|
6219
|
-
provider,
|
|
6220
|
-
displayName,
|
|
6221
|
-
error: "unconfigured"
|
|
6222
|
-
};
|
|
7296
|
+
async function queryBearerBalance(url, key, provider, displayName, parse) {
|
|
6223
7297
|
if (!balanceGate.check(provider)) return {
|
|
6224
7298
|
provider,
|
|
6225
7299
|
displayName,
|
|
@@ -6232,7 +7306,7 @@ async function queryBearerBalance(ctx, url, apiKeyEnv, provider, displayName, pa
|
|
|
6232
7306
|
const response = await fetch(url, {
|
|
6233
7307
|
headers: {
|
|
6234
7308
|
accept: "application/json",
|
|
6235
|
-
authorization: `Bearer ${
|
|
7309
|
+
authorization: `Bearer ${key}`
|
|
6236
7310
|
},
|
|
6237
7311
|
signal: controller.signal
|
|
6238
7312
|
});
|
|
@@ -6276,40 +7350,123 @@ async function queryBearerBalance(ctx, url, apiKeyEnv, provider, displayName, pa
|
|
|
6276
7350
|
};
|
|
6277
7351
|
}
|
|
6278
7352
|
}
|
|
7353
|
+
function parseDeepSeekBalance(data) {
|
|
7354
|
+
const doc = data;
|
|
7355
|
+
const info = (Array.isArray(doc.balance_infos) ? doc.balance_infos : [])[0];
|
|
7356
|
+
const currency = typeof info?.currency === "string" ? info.currency : void 0;
|
|
7357
|
+
const totalBalance = toNumber$1(info?.total_balance);
|
|
7358
|
+
const grantedBalance = toNumber$1(info?.granted_balance);
|
|
7359
|
+
const toppedUpBalance = toNumber$1(info?.topped_up_balance);
|
|
7360
|
+
const isAvailable = typeof doc.is_available === "boolean" ? doc.is_available : void 0;
|
|
7361
|
+
return {
|
|
7362
|
+
provider: "deepseek",
|
|
7363
|
+
displayName: "DeepSeek",
|
|
7364
|
+
...currency !== void 0 ? { currency } : {},
|
|
7365
|
+
...totalBalance !== void 0 ? { totalBalance } : {},
|
|
7366
|
+
...grantedBalance !== void 0 ? { grantedBalance } : {},
|
|
7367
|
+
...toppedUpBalance !== void 0 ? { toppedUpBalance } : {},
|
|
7368
|
+
...isAvailable !== void 0 ? { isAvailable } : {}
|
|
7369
|
+
};
|
|
7370
|
+
}
|
|
6279
7371
|
/**
|
|
6280
|
-
*
|
|
6281
|
-
*
|
|
6282
|
-
*
|
|
6283
|
-
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
7372
|
+
* 登录钱包(宿主 DeepSeek 账号通道):归属宿主内置的登录通道路由 id
|
|
7373
|
+
* `deepseek-account`(宿主包 `llm-deepseek-account` 注册)——它供的是登录通道,
|
|
7374
|
+
* 不是 API key 路由,两只钱包不能共认一条路由(issue #141)。
|
|
6284
7375
|
*/
|
|
6285
|
-
|
|
6286
|
-
|
|
6287
|
-
|
|
6288
|
-
|
|
6289
|
-
|
|
6290
|
-
|
|
6291
|
-
|
|
6292
|
-
|
|
6293
|
-
|
|
6294
|
-
|
|
6295
|
-
|
|
6296
|
-
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
|
|
6301
|
-
|
|
6302
|
-
|
|
7376
|
+
const ACCOUNT_WALLET = {
|
|
7377
|
+
provider: "deepseek",
|
|
7378
|
+
displayName: "DeepSeek",
|
|
7379
|
+
sourceRoute: "deepseek",
|
|
7380
|
+
attributedRoutes: [DEEPSEEK_LOGIN_ROUTE],
|
|
7381
|
+
walletKind: "account"
|
|
7382
|
+
};
|
|
7383
|
+
const warnedAccountFailures = /* @__PURE__ */ new Set();
|
|
7384
|
+
const apiSources = /* @__PURE__ */ new WeakMap();
|
|
7385
|
+
function apiBalanceSource(row) {
|
|
7386
|
+
return apiSources.get(row);
|
|
7387
|
+
}
|
|
7388
|
+
function accountBalanceRow(details) {
|
|
7389
|
+
const doc = details;
|
|
7390
|
+
if (doc?.status !== "ready") return void 0;
|
|
7391
|
+
const sumsByCurrency = (items) => {
|
|
7392
|
+
const sums = /* @__PURE__ */ new Map();
|
|
7393
|
+
if (!Array.isArray(items)) return sums;
|
|
7394
|
+
for (const item of items) {
|
|
7395
|
+
const currency = item?.currency;
|
|
7396
|
+
const value = toNumber$1(item?.balance);
|
|
7397
|
+
if ((currency === "CNY" || currency === "USD") && value !== void 0) sums.set(currency, (sums.get(currency) ?? 0) + value);
|
|
7398
|
+
}
|
|
7399
|
+
return sums;
|
|
7400
|
+
};
|
|
7401
|
+
const toppedUp = sumsByCurrency(doc.value);
|
|
7402
|
+
const granted = sumsByCurrency(doc.bonusWallets);
|
|
7403
|
+
const has = (currency) => toppedUp.has(currency) || granted.has(currency);
|
|
7404
|
+
const currency = has("CNY") ? "CNY" : has("USD") ? "USD" : void 0;
|
|
7405
|
+
if (currency === void 0) return void 0;
|
|
7406
|
+
const toppedUpBalance = toppedUp.get(currency);
|
|
7407
|
+
const grantedBalance = granted.get(currency);
|
|
7408
|
+
return {
|
|
7409
|
+
...ACCOUNT_WALLET,
|
|
7410
|
+
...has("CNY") && has("USD") ? { otherBalances: [{
|
|
7411
|
+
currency: "USD",
|
|
7412
|
+
totalBalance: (toppedUp.get("USD") ?? 0) + (granted.get("USD") ?? 0)
|
|
7413
|
+
}] } : {},
|
|
7414
|
+
currency,
|
|
7415
|
+
totalBalance: (toppedUpBalance ?? 0) + (grantedBalance ?? 0),
|
|
7416
|
+
...toppedUpBalance !== void 0 ? { toppedUpBalance } : {},
|
|
7417
|
+
...grantedBalance !== void 0 ? { grantedBalance } : {},
|
|
7418
|
+
isAvailable: true
|
|
7419
|
+
};
|
|
7420
|
+
}
|
|
7421
|
+
function accountWalletFailure(reason, error = "unreachable") {
|
|
7422
|
+
if (!warnedAccountFailures.has(reason)) {
|
|
7423
|
+
warnedAccountFailures.add(reason);
|
|
7424
|
+
console.warn(`[usage-billing] DeepSeek sign-in wallet: ${reason}`);
|
|
7425
|
+
}
|
|
7426
|
+
return {
|
|
7427
|
+
...ACCOUNT_WALLET,
|
|
7428
|
+
error
|
|
7429
|
+
};
|
|
7430
|
+
}
|
|
7431
|
+
async function queryDeepSeekAccount(ctx, client) {
|
|
7432
|
+
const unavailable = (accountState) => ({
|
|
7433
|
+
...ACCOUNT_WALLET,
|
|
7434
|
+
attributedRoutes: [],
|
|
7435
|
+
error: "unconfigured",
|
|
7436
|
+
accountState
|
|
6303
7437
|
});
|
|
7438
|
+
let account;
|
|
7439
|
+
try {
|
|
7440
|
+
account = ctx.get?.("deepseekAccount");
|
|
7441
|
+
} catch {
|
|
7442
|
+
return accountWalletFailure("host service lookup threw");
|
|
7443
|
+
}
|
|
7444
|
+
if (typeof account?.getBalance !== "function") return unavailable("no-service");
|
|
7445
|
+
if (client === void 0) return unavailable("no-metadata");
|
|
7446
|
+
try {
|
|
7447
|
+
const details = await account.getBalance(client);
|
|
7448
|
+
if (details === null) return unavailable("signed-out");
|
|
7449
|
+
if (details?.status === "failed") return accountWalletFailure("host returned failed");
|
|
7450
|
+
return accountBalanceRow(details) ?? accountWalletFailure("unusable balance response", "invalid");
|
|
7451
|
+
} catch {
|
|
7452
|
+
return accountWalletFailure("balance query threw");
|
|
7453
|
+
}
|
|
7454
|
+
}
|
|
7455
|
+
/**
|
|
7456
|
+
* Query the DeepSeek Platform wallet independently of the sign-in service.
|
|
7457
|
+
* @param key - resolved credential for this query.
|
|
7458
|
+
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
7459
|
+
*/
|
|
7460
|
+
function queryDeepSeek(url, key) {
|
|
7461
|
+
return queryBearerBalance(url, key, "deepseek", "DeepSeek", parseDeepSeekBalance);
|
|
6304
7462
|
}
|
|
6305
7463
|
/**
|
|
6306
7464
|
* Query the Moonshot/Kimi account balance.
|
|
6307
|
-
* @param
|
|
6308
|
-
* @param apiKeyEnv - credential reference resolving the Moonshot API key.
|
|
7465
|
+
* @param key - resolved credential for this query.
|
|
6309
7466
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6310
7467
|
*/
|
|
6311
|
-
function queryMoonshot(
|
|
6312
|
-
return queryBearerBalance(
|
|
7468
|
+
function queryMoonshot(url, key) {
|
|
7469
|
+
return queryBearerBalance(url, key, "月之暗面", "月之暗面", (data) => {
|
|
6313
7470
|
const doc = data;
|
|
6314
7471
|
const totalBalance = toNumber$1(doc.data?.available_balance);
|
|
6315
7472
|
const grantedBalance = toNumber$1(doc.data?.voucher_balance);
|
|
@@ -6326,12 +7483,11 @@ function queryMoonshot(ctx, apiKeyEnv) {
|
|
|
6326
7483
|
}
|
|
6327
7484
|
/**
|
|
6328
7485
|
* Query the StepFun (阶跃星辰) account balance.
|
|
6329
|
-
* @param
|
|
6330
|
-
* @param apiKeyEnv - credential reference resolving the StepFun API key.
|
|
7486
|
+
* @param key - resolved credential for this query.
|
|
6331
7487
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6332
7488
|
*/
|
|
6333
|
-
function queryStepFun(
|
|
6334
|
-
return queryBearerBalance(
|
|
7489
|
+
function queryStepFun(url, key) {
|
|
7490
|
+
return queryBearerBalance(url, key, "阶跃星辰", "阶跃星辰", (data) => {
|
|
6335
7491
|
const doc = data;
|
|
6336
7492
|
const totalBalance = toNumber$1(doc.balance);
|
|
6337
7493
|
const toppedUpBalance = toNumber$1(doc.total_cash_balance);
|
|
@@ -6348,12 +7504,11 @@ function queryStepFun(ctx, apiKeyEnv) {
|
|
|
6348
7504
|
}
|
|
6349
7505
|
/**
|
|
6350
7506
|
* Query the SiliconFlow (硅基流动) account balance.
|
|
6351
|
-
* @param
|
|
6352
|
-
* @param apiKeyEnv - credential reference resolving the SiliconFlow API key.
|
|
7507
|
+
* @param key - resolved credential for this query.
|
|
6353
7508
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6354
7509
|
*/
|
|
6355
|
-
function querySiliconFlow(
|
|
6356
|
-
return queryBearerBalance(
|
|
7510
|
+
function querySiliconFlow(url, key) {
|
|
7511
|
+
return queryBearerBalance(url, key, "硅基流动", "硅基流动", (data) => {
|
|
6357
7512
|
const doc = data;
|
|
6358
7513
|
const inner = doc.data ?? doc;
|
|
6359
7514
|
const totalBalance = toNumber$1(inner.balance ?? inner.balance_cny);
|
|
@@ -6367,12 +7522,11 @@ function querySiliconFlow(ctx, apiKeyEnv) {
|
|
|
6367
7522
|
}
|
|
6368
7523
|
/**
|
|
6369
7524
|
* Query the xAI (Grok) credit balance.
|
|
6370
|
-
* @param
|
|
6371
|
-
* @param apiKeyEnv - credential reference resolving the xAI API key.
|
|
7525
|
+
* @param key - resolved credential for this query.
|
|
6372
7526
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6373
7527
|
*/
|
|
6374
|
-
function queryXai(
|
|
6375
|
-
return queryBearerBalance(
|
|
7528
|
+
function queryXai(url, key) {
|
|
7529
|
+
return queryBearerBalance(url, key, "xAI", "xAI", (data) => {
|
|
6376
7530
|
const cents = toNumber$1(data.total?.val);
|
|
6377
7531
|
const totalBalance = cents === void 0 ? void 0 : Math.abs(cents) / 100;
|
|
6378
7532
|
return {
|
|
@@ -6405,11 +7559,10 @@ function pickTokenDanceBalanceCny(data) {
|
|
|
6405
7559
|
/**
|
|
6406
7560
|
* 查询 TokenDance Space 钱包余额(issue #26/#27)。`queryBearerBalance` 已覆盖
|
|
6407
7561
|
* 认证失败(401 → unauthorized)与熔断/超时/重试,这里只负责微元 → 元换算。
|
|
6408
|
-
* @param
|
|
6409
|
-
* @param apiKeyEnv - credential reference resolving the TokenDance API key.
|
|
7562
|
+
* @param key - resolved credential for this query.
|
|
6410
7563
|
*/
|
|
6411
|
-
function queryTokenDance(
|
|
6412
|
-
return queryBearerBalance(
|
|
7564
|
+
function queryTokenDance(url, key) {
|
|
7565
|
+
return queryBearerBalance(url, key, "TokenDance", "TokenDance", (data) => {
|
|
6413
7566
|
const cny = pickTokenDanceBalanceCny(data);
|
|
6414
7567
|
return {
|
|
6415
7568
|
provider: "TokenDance",
|
|
@@ -6424,12 +7577,11 @@ function queryTokenDance(ctx, apiKeyEnv) {
|
|
|
6424
7577
|
* 与订阅(zai-coding-cn 的 Coding Plan)互补:一个平台可同时有钱包余额与订阅
|
|
6425
7578
|
* 套餐,两者各读各的(TokenLedger 同款双读姿态)。Z.ai global 域币种为 USD,
|
|
6426
7579
|
* 本函数固定走国内 CNY 域(open.bigmodel.cn),币种不猜,仅覆盖国内域。
|
|
6427
|
-
* @param
|
|
6428
|
-
* @param apiKeyEnv - credential reference resolving the Zhipu API key.
|
|
7580
|
+
* @param key - resolved credential for this query.
|
|
6429
7581
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6430
7582
|
*/
|
|
6431
|
-
function queryZhipu(
|
|
6432
|
-
return queryBearerBalance(
|
|
7583
|
+
function queryZhipu(url, key) {
|
|
7584
|
+
return queryBearerBalance(url, key, "智谱 AI", "智谱 AI", (data) => {
|
|
6433
7585
|
const doc = data;
|
|
6434
7586
|
const totalBalance = toNumber$1(doc.balance?.available) ?? toNumber$1(doc.balance?.total);
|
|
6435
7587
|
return {
|
|
@@ -6440,71 +7592,51 @@ function queryZhipu(ctx, apiKeyEnv) {
|
|
|
6440
7592
|
};
|
|
6441
7593
|
});
|
|
6442
7594
|
}
|
|
7595
|
+
function bearer(route, displayName, endpoint, query) {
|
|
7596
|
+
return {
|
|
7597
|
+
route,
|
|
7598
|
+
displayName,
|
|
7599
|
+
endpoint,
|
|
7600
|
+
query: (key) => query(endpoint, key)
|
|
7601
|
+
};
|
|
7602
|
+
}
|
|
6443
7603
|
const QUERIERS = [
|
|
7604
|
+
bearer("deepseek", "deepseek", DEEPSEEK_BALANCE_URL, queryDeepSeek),
|
|
6444
7605
|
{
|
|
6445
|
-
route:
|
|
7606
|
+
route: DEEPSEEK_PLATFORM_ROUTE,
|
|
6446
7607
|
displayName: "deepseek",
|
|
6447
|
-
|
|
6448
|
-
|
|
6449
|
-
|
|
6450
|
-
|
|
6451
|
-
|
|
6452
|
-
|
|
6453
|
-
|
|
6454
|
-
|
|
6455
|
-
|
|
6456
|
-
|
|
6457
|
-
|
|
6458
|
-
|
|
6459
|
-
|
|
6460
|
-
route: "siliconflow",
|
|
6461
|
-
displayName: "硅基流动",
|
|
6462
|
-
querier: querySiliconFlow
|
|
6463
|
-
},
|
|
6464
|
-
{
|
|
6465
|
-
route: "xai",
|
|
6466
|
-
displayName: "xAI",
|
|
6467
|
-
querier: queryXai
|
|
6468
|
-
},
|
|
6469
|
-
{
|
|
6470
|
-
route: "zhipu",
|
|
6471
|
-
displayName: "智谱 AI",
|
|
6472
|
-
querier: queryZhipu
|
|
6473
|
-
},
|
|
6474
|
-
{
|
|
6475
|
-
route: "zai-coding-cn",
|
|
6476
|
-
displayName: "智谱 AI",
|
|
6477
|
-
querier: queryZhipu
|
|
6478
|
-
},
|
|
6479
|
-
{
|
|
6480
|
-
route: "tokendance",
|
|
6481
|
-
displayName: "TokenDance",
|
|
6482
|
-
querier: queryTokenDance
|
|
6483
|
-
},
|
|
6484
|
-
{
|
|
6485
|
-
route: "tokendance-space",
|
|
6486
|
-
displayName: "TokenDance",
|
|
6487
|
-
querier: queryTokenDance
|
|
6488
|
-
},
|
|
7608
|
+
endpoint: DEEPSEEK_BALANCE_URL,
|
|
7609
|
+
keyRefs: [DEEPSEEK_PLATFORM_KEY_REF],
|
|
7610
|
+
keyOnly: true,
|
|
7611
|
+
query: (key) => queryDeepSeek(DEEPSEEK_BALANCE_URL, key)
|
|
7612
|
+
},
|
|
7613
|
+
bearer("moonshot", "月之暗面", MOONSHOT_BALANCE_URL, queryMoonshot),
|
|
7614
|
+
bearer("stepfun", "阶跃星辰", STEPFUN_BALANCE_URL, queryStepFun),
|
|
7615
|
+
bearer("siliconflow", "硅基流动", SILICONFLOW_BALANCE_URL, querySiliconFlow),
|
|
7616
|
+
bearer("xai", "xAI", XAI_CREDITS_URL, queryXai),
|
|
7617
|
+
bearer("zhipu", "智谱 AI", ZHIPU_BALANCE_URL, queryZhipu),
|
|
7618
|
+
bearer("zai-coding-cn", "智谱 AI", ZHIPU_BALANCE_URL, queryZhipu),
|
|
7619
|
+
bearer("tokendance", "TokenDance", TOKENDANCE_BALANCE_URL, queryTokenDance),
|
|
7620
|
+
bearer("tokendance-space", "TokenDance", TOKENDANCE_BALANCE_URL, queryTokenDance),
|
|
6489
7621
|
{
|
|
6490
7622
|
route: "tencent-tokenhub",
|
|
6491
7623
|
displayName: "腾讯云 TokenHub",
|
|
6492
|
-
|
|
7624
|
+
query: queryTencentTokenPlan
|
|
6493
7625
|
},
|
|
6494
7626
|
{
|
|
6495
7627
|
route: "tokenhub",
|
|
6496
7628
|
displayName: "腾讯云 TokenHub",
|
|
6497
|
-
|
|
7629
|
+
query: queryTencentTokenPlan
|
|
6498
7630
|
},
|
|
6499
7631
|
{
|
|
6500
7632
|
route: "tencent",
|
|
6501
7633
|
displayName: "腾讯云 TokenHub",
|
|
6502
|
-
|
|
7634
|
+
query: queryTencentTokenPlan
|
|
6503
7635
|
},
|
|
6504
7636
|
{
|
|
6505
7637
|
route: "tencentcloud",
|
|
6506
7638
|
displayName: "腾讯云 TokenHub",
|
|
6507
|
-
|
|
7639
|
+
query: queryTencentTokenPlan
|
|
6508
7640
|
}
|
|
6509
7641
|
];
|
|
6510
7642
|
/**
|
|
@@ -6515,9 +7647,11 @@ const QUERIERS = [
|
|
|
6515
7647
|
* dashboard shows a stable state instead of dropping the row.
|
|
6516
7648
|
* @param ctx - host context carrying the credentials seam.
|
|
6517
7649
|
* @param providers - the llm-pi-ai providers dict (`<route> → { apiKeyEnv? }`).
|
|
7650
|
+
* @param client - UI metadata for the host login wallet service.
|
|
7651
|
+
* @param options - extra credential candidates per route (plugin config).
|
|
6518
7652
|
* @returns the balance rows (one per provider).
|
|
6519
7653
|
*/
|
|
6520
|
-
async function queryBalances(ctx, providers) {
|
|
7654
|
+
async function queryBalances(ctx, providers, client, options) {
|
|
6521
7655
|
const resolveRef = async (name) => {
|
|
6522
7656
|
try {
|
|
6523
7657
|
const hit = await ctx.credentials.resolve(credentialRef(name));
|
|
@@ -6526,57 +7660,89 @@ async function queryBalances(ctx, providers) {
|
|
|
6526
7660
|
return;
|
|
6527
7661
|
}
|
|
6528
7662
|
};
|
|
6529
|
-
const
|
|
7663
|
+
const originOwners = /* @__PURE__ */ new Map();
|
|
7664
|
+
const origins = /* @__PURE__ */ new Map();
|
|
7665
|
+
for (const [route, { baseURL }] of Object.entries(providers)) {
|
|
7666
|
+
if (baseURL === void 0) continue;
|
|
7667
|
+
const origin = URL.parse(baseURL)?.origin ?? "";
|
|
7668
|
+
origins.set(route, origin);
|
|
7669
|
+
const owners = originOwners.get(origin) ?? [];
|
|
7670
|
+
owners.push(route);
|
|
7671
|
+
originOwners.set(origin, owners);
|
|
7672
|
+
}
|
|
7673
|
+
const resolved = await Promise.all(QUERIERS.map(async (spec) => {
|
|
7674
|
+
const { route, endpoint } = spec;
|
|
6530
7675
|
const env = providers[route]?.apiKeyEnv;
|
|
6531
|
-
const
|
|
6532
|
-
|
|
7676
|
+
const hit = await firstResolvedRef([
|
|
7677
|
+
...env ? [env] : [],
|
|
7678
|
+
...spec.keyRefs ?? [],
|
|
7679
|
+
...options?.extraKeyRefs?.[route] ?? [],
|
|
7680
|
+
...routeKeyRefCandidates(route)
|
|
7681
|
+
], resolveRef);
|
|
7682
|
+
const expectedOrigin = endpoint && new URL(endpoint).origin;
|
|
7683
|
+
const configuredOrigin = origins.get(route);
|
|
7684
|
+
const verified = configuredOrigin === void 0 || expectedOrigin !== void 0 && configuredOrigin === expectedOrigin;
|
|
6533
7685
|
return {
|
|
6534
|
-
|
|
6535
|
-
|
|
6536
|
-
|
|
6537
|
-
|
|
7686
|
+
...spec,
|
|
7687
|
+
key: hit?.value,
|
|
7688
|
+
expectedOrigin,
|
|
7689
|
+
verified
|
|
6538
7690
|
};
|
|
6539
7691
|
}));
|
|
6540
|
-
const
|
|
7692
|
+
const present = (item) => item.key !== void 0 || !item.keyOnly && Object.hasOwn(providers, item.route);
|
|
7693
|
+
const presentVendors = new Set(resolved.filter(present).map((item) => item.displayName));
|
|
7694
|
+
const targets = [];
|
|
6541
7695
|
for (const item of resolved) {
|
|
6542
|
-
|
|
6543
|
-
|
|
6544
|
-
|
|
6545
|
-
|
|
6546
|
-
|
|
6547
|
-
|
|
7696
|
+
if (!present(item) && (presentVendors.has(item.displayName) || targets.some((other) => other.displayName === item.displayName))) continue;
|
|
7697
|
+
const shared = item.key !== void 0 && item.verified && targets.find((other) => other.verified && other.key === item.key && (item.endpoint !== void 0 ? other.endpoint === item.endpoint : other.query === item.query));
|
|
7698
|
+
if (shared) shared.aliases.push(item.route);
|
|
7699
|
+
else targets.push({
|
|
7700
|
+
...item,
|
|
7701
|
+
aliases: []
|
|
6548
7702
|
});
|
|
6549
7703
|
}
|
|
6550
|
-
|
|
6551
|
-
|
|
7704
|
+
const apiRows = await Promise.all(targets.map(async ({ route, displayName, query, key, aliases, expectedOrigin, verified }) => {
|
|
7705
|
+
const row = key === void 0 ? {
|
|
6552
7706
|
provider: displayName,
|
|
6553
7707
|
displayName,
|
|
6554
7708
|
error: "unconfigured"
|
|
6555
|
-
});
|
|
6556
|
-
|
|
7709
|
+
} : await query(key);
|
|
7710
|
+
const sourceRoute = row.sourceRoute ?? route;
|
|
7711
|
+
const attributed = {
|
|
7712
|
+
...row,
|
|
7713
|
+
sourceRoute,
|
|
7714
|
+
walletKind: row.walletKind ?? "api-key",
|
|
7715
|
+
attributedRoutes: row.attributedRoutes ?? (route === "deepseek" && key === void 0 ? [] : verified ? [sourceRoute, ...aliases] : []),
|
|
7716
|
+
...aliases.length > 0 ? { sourceRouteAliases: aliases } : {}
|
|
7717
|
+
};
|
|
7718
|
+
if (route === "deepseek" && key !== void 0) apiSources.set(attributed, createHash("sha256").update(key).digest("hex"));
|
|
7719
|
+
const owners = expectedOrigin && originOwners.get(expectedOrigin);
|
|
7720
|
+
if (attributed.walletKind === "api-key" && owners && owners.every((provider) => balanceCoversSite(attributed, siteBucketKey({
|
|
7721
|
+
kind: "direct",
|
|
7722
|
+
provider
|
|
7723
|
+
})))) return {
|
|
7724
|
+
...attributed,
|
|
7725
|
+
sourceOrigin: expectedOrigin
|
|
7726
|
+
};
|
|
7727
|
+
return attributed;
|
|
6557
7728
|
}));
|
|
7729
|
+
const account = await queryDeepSeekAccount(ctx, client);
|
|
7730
|
+
return [...apiRows, account];
|
|
6558
7731
|
}
|
|
6559
7732
|
/**
|
|
6560
7733
|
* 查询腾讯云 TokenHub Token Plan 套餐余量。凭据值格式 `<SecretId>:<SecretKey>`
|
|
6561
7734
|
* (云 API 密钥,非 TokenHub 推理 key)。链路:套餐列表取 TeamId → 套餐详情读
|
|
6562
7735
|
* 主额度包余量。管控面字段名未完全稳定,解析按语义键防御提取。
|
|
6563
|
-
* @param
|
|
6564
|
-
* @param apiKeyEnv - credential reference resolving the `<SecretId>:<SecretKey>` pair.
|
|
7736
|
+
* @param key - resolved credential for this query.
|
|
6565
7737
|
*/
|
|
6566
|
-
async function queryTencentTokenPlan(
|
|
7738
|
+
async function queryTencentTokenPlan(key) {
|
|
6567
7739
|
const provider = "腾讯云 TokenHub";
|
|
6568
|
-
const hit = await ctx.credentials.resolve(credentialRef(apiKeyEnv));
|
|
6569
|
-
if (hit === void 0) return {
|
|
6570
|
-
provider,
|
|
6571
|
-
displayName: provider,
|
|
6572
|
-
error: "unconfigured"
|
|
6573
|
-
};
|
|
6574
7740
|
if (!balanceGate.check(provider)) return {
|
|
6575
7741
|
provider,
|
|
6576
7742
|
displayName: provider,
|
|
6577
7743
|
error: "unreachable"
|
|
6578
7744
|
};
|
|
6579
|
-
const credential = parseTencentCredential(
|
|
7745
|
+
const credential = parseTencentCredential(key);
|
|
6580
7746
|
if (credential === void 0) return {
|
|
6581
7747
|
provider,
|
|
6582
7748
|
displayName: provider,
|
|
@@ -6805,7 +7971,7 @@ async function queryCustomBalances(ctx, configs) {
|
|
|
6805
7971
|
/** Abort a declared fetch when the upstream hangs beyond this budget. */
|
|
6806
7972
|
const FETCH_TIMEOUT_MS$2 = 8e3;
|
|
6807
7973
|
/** 响应体上限(字节):坏 / 恶意端点不能拖住面板或耗尽内存。 */
|
|
6808
|
-
const MAX_BODY_BYTES = 1e6;
|
|
7974
|
+
const MAX_BODY_BYTES$1 = 1e6;
|
|
6809
7975
|
/** 声明端点查询的熔断门:按(匹配 provider origin + path)独立熔断,各端点互不干扰。 */
|
|
6810
7976
|
const declaredGate = createCooldownGate({
|
|
6811
7977
|
failures: 3,
|
|
@@ -6949,42 +8115,40 @@ async function queryDeclaredEndpoints(ctx, providers, declarations) {
|
|
|
6949
8115
|
return await Promise.all(declarations.map(async (decl) => {
|
|
6950
8116
|
const displayName = typeof decl.displayName === "string" && decl.displayName !== "" ? decl.displayName : "已声明";
|
|
6951
8117
|
const provider = `declared:${displayName}`;
|
|
6952
|
-
const
|
|
6953
|
-
|
|
8118
|
+
const declOrigin = normalizeDeclaredOrigin(decl.origin);
|
|
8119
|
+
const matched = declOrigin === void 0 ? void 0 : byOrigin.get(declOrigin);
|
|
8120
|
+
const identity = {
|
|
6954
8121
|
provider,
|
|
6955
8122
|
displayName,
|
|
6956
8123
|
declared: true,
|
|
8124
|
+
walletKind: "relay",
|
|
8125
|
+
sourceRoute: matched?.route ?? provider,
|
|
8126
|
+
attributedRoutes: matched ? [matched.route] : []
|
|
8127
|
+
};
|
|
8128
|
+
const requestPath = compileDeclaredEndpoint(decl);
|
|
8129
|
+
if (requestPath === void 0) return {
|
|
8130
|
+
...identity,
|
|
6957
8131
|
error: "invalid",
|
|
6958
8132
|
reason: "path 必须单斜杠绝对路径"
|
|
6959
8133
|
};
|
|
6960
|
-
const declOrigin = normalizeDeclaredOrigin(decl.origin);
|
|
6961
|
-
const matched = declOrigin === void 0 ? void 0 : byOrigin.get(declOrigin);
|
|
6962
8134
|
if (matched === void 0) return {
|
|
6963
|
-
|
|
6964
|
-
displayName,
|
|
6965
|
-
declared: true,
|
|
8135
|
+
...identity,
|
|
6966
8136
|
error: "unconfigured",
|
|
6967
8137
|
reason: "未匹配到同源 provider(需先在 llm-pi-ai 配好 baseURL)"
|
|
6968
8138
|
};
|
|
6969
8139
|
const gateKey = `${declOrigin}${requestPath}`;
|
|
6970
8140
|
if (!declaredGate.check(gateKey)) return {
|
|
6971
|
-
|
|
6972
|
-
displayName,
|
|
6973
|
-
declared: true,
|
|
8141
|
+
...identity,
|
|
6974
8142
|
error: "unreachable"
|
|
6975
8143
|
};
|
|
6976
8144
|
const hit = await firstResolvedRef([...matched.apiKeyEnv !== void 0 ? [matched.apiKeyEnv] : [], ...routeKeyRefCandidates(matched.route)], resolveRef);
|
|
6977
8145
|
if (hit === void 0) return {
|
|
6978
|
-
|
|
6979
|
-
displayName,
|
|
6980
|
-
declared: true,
|
|
8146
|
+
...identity,
|
|
6981
8147
|
error: "unconfigured"
|
|
6982
8148
|
};
|
|
6983
8149
|
const url = new URL(requestPath, declOrigin);
|
|
6984
8150
|
if (url.origin !== declOrigin) return {
|
|
6985
|
-
|
|
6986
|
-
displayName,
|
|
6987
|
-
declared: true,
|
|
8151
|
+
...identity,
|
|
6988
8152
|
error: "invalid",
|
|
6989
8153
|
reason: "跨源路径被拒绝"
|
|
6990
8154
|
};
|
|
@@ -7000,9 +8164,7 @@ async function queryDeclaredEndpoints(ctx, providers, declarations) {
|
|
|
7000
8164
|
declaredGate.success(gateKey);
|
|
7001
8165
|
const nothingResolved = total === void 0 && granted === void 0 && used === void 0 && windows.length === 0;
|
|
7002
8166
|
return {
|
|
7003
|
-
|
|
7004
|
-
displayName,
|
|
7005
|
-
declared: true,
|
|
8167
|
+
...identity,
|
|
7006
8168
|
...total !== void 0 ? { totalBalance: total } : {},
|
|
7007
8169
|
...granted !== void 0 ? { grantedBalance: granted } : {},
|
|
7008
8170
|
...typeof currency === "string" && currency !== "" ? { currency } : {},
|
|
@@ -7016,9 +8178,7 @@ async function queryDeclaredEndpoints(ctx, providers, declarations) {
|
|
|
7016
8178
|
} catch {
|
|
7017
8179
|
declaredGate.fail(gateKey);
|
|
7018
8180
|
return {
|
|
7019
|
-
|
|
7020
|
-
displayName,
|
|
7021
|
-
declared: true,
|
|
8181
|
+
...identity,
|
|
7022
8182
|
error: "unreachable"
|
|
7023
8183
|
};
|
|
7024
8184
|
}
|
|
@@ -7046,7 +8206,7 @@ async function fetchDeclaredBody(url, raw, apiKey) {
|
|
|
7046
8206
|
if (response.status === 401 || response.status === 403) throw new HttpStatusError("unauthorized", response.status);
|
|
7047
8207
|
if (!response.ok) throw new HttpStatusError("http-error", response.status);
|
|
7048
8208
|
const text = await response.text();
|
|
7049
|
-
if (text.length > MAX_BODY_BYTES) throw new HttpStatusError("body-too-large", 413);
|
|
8209
|
+
if (text.length > MAX_BODY_BYTES$1) throw new HttpStatusError("body-too-large", 413);
|
|
7050
8210
|
try {
|
|
7051
8211
|
return JSON.parse(text);
|
|
7052
8212
|
} catch (cause) {
|
|
@@ -7085,6 +8245,30 @@ var HttpStatusError = class extends Error {
|
|
|
7085
8245
|
*
|
|
7086
8246
|
* 纯函数:输入上一基准与本次余额查询结果,输出新基准与对账事件,可独立单测。
|
|
7087
8247
|
*/
|
|
8248
|
+
/** The daily official aggregate also includes other deepseek-* routes, the official
|
|
8249
|
+
* origin (possibly shared), and web search (estimated cost, separate credentials).
|
|
8250
|
+
* Require complete site coverage and exclude unrelated routes before comparing. */
|
|
8251
|
+
function platformSpend(doc, day, providers, allowDirect = true) {
|
|
8252
|
+
if (doc.staleSnapshot || doc.sessionListError !== void 0 || doc.unreadableSessions) return void 0;
|
|
8253
|
+
const owners = Object.entries(providers).filter(([, p]) => p.baseURL !== void 0 && siteOriginOf(p.baseURL) === "https://api.deepseek.com");
|
|
8254
|
+
const uniqueOrigin = owners.length === 1 && owners[0]?.[0] === "deepseek";
|
|
8255
|
+
if (!allowDirect && !uniqueOrigin) return void 0;
|
|
8256
|
+
const daily = doc.byDay[day];
|
|
8257
|
+
if (daily === void 0) return 0;
|
|
8258
|
+
const models = doc.byDayModelsSite?.[day];
|
|
8259
|
+
if (models === void 0) return void 0;
|
|
8260
|
+
let coveredCalls = 0, coveredCost = 0, cost = 0;
|
|
8261
|
+
for (const sites of Object.values(models)) for (const [site, cell] of Object.entries(sites)) {
|
|
8262
|
+
coveredCalls += cell.officialCalls;
|
|
8263
|
+
coveredCost += cell.officialCost;
|
|
8264
|
+
if (site === "direct:deepseek" && !allowDirect) return void 0;
|
|
8265
|
+
if (site === `site:https://api.deepseek.com` && !uniqueOrigin) return void 0;
|
|
8266
|
+
if (site !== "direct:deepseek" && site !== `site:https://api.deepseek.com`) continue;
|
|
8267
|
+
if (cell.searchCalls || cell.officialCalls !== cell.calls || cell.calls && cell.officialCost <= 0) return void 0;
|
|
8268
|
+
cost += cell.officialCost;
|
|
8269
|
+
}
|
|
8270
|
+
return coveredCalls === daily.officialCalls && Math.abs(coveredCost - daily.officialCost) < 1e-6 ? cost : void 0;
|
|
8271
|
+
}
|
|
7088
8272
|
/** 余额差对账阈值下限(元):消费低于该值时不值得提示,避免小金额波动刷屏。 */
|
|
7089
8273
|
const MIN_DRIFT_ABS = .3;
|
|
7090
8274
|
/** 余额差相对容忍度:偏差超过较大一方的该比例才判漂移。 */
|
|
@@ -7119,23 +8303,27 @@ function snapOf(ref, balance, nowMs) {
|
|
|
7119
8303
|
* @param todayOfficialCost - 本地账本当日的官方渠道费用(CNY)。
|
|
7120
8304
|
* @param dayKey - 本地日期键(YYYY-MM-DD)。
|
|
7121
8305
|
* @param nowMs - 当前时刻(epoch ms)。
|
|
7122
|
-
* @returns 新基准与对账事件;余额不可用(无 totalBalance)时返回 `{ ref:
|
|
8306
|
+
* @returns 新基准与对账事件;余额不可用(无 totalBalance)时返回 `{ ref: null, event: null }`。
|
|
7123
8307
|
*/
|
|
7124
|
-
function reconcileBalanceDelta(prevRef, balance, todayOfficialCost, dayKey, nowMs) {
|
|
8308
|
+
function reconcileBalanceDelta(prevRef, balance, todayOfficialCost, dayKey, nowMs, source = "deepseek") {
|
|
7125
8309
|
const total = balance.totalBalance;
|
|
7126
8310
|
if (typeof total !== "number" || !Number.isFinite(total)) return {
|
|
7127
|
-
ref:
|
|
8311
|
+
ref: null,
|
|
7128
8312
|
event: null
|
|
7129
8313
|
};
|
|
7130
|
-
const snap =
|
|
7131
|
-
|
|
7132
|
-
|
|
7133
|
-
|
|
7134
|
-
|
|
8314
|
+
const snap = {
|
|
8315
|
+
...snapOf({
|
|
8316
|
+
date: dayKey,
|
|
8317
|
+
currency: ""
|
|
8318
|
+
}, balance, nowMs),
|
|
8319
|
+
source,
|
|
8320
|
+
costAtBaseline: todayOfficialCost
|
|
8321
|
+
};
|
|
8322
|
+
if (prevRef === null || prevRef.date !== dayKey || prevRef.source !== source || !Number.isFinite(prevRef.costAtBaseline)) return {
|
|
7135
8323
|
ref: snap,
|
|
7136
8324
|
event: { kind: "baseline" }
|
|
7137
8325
|
};
|
|
7138
|
-
if (prevRef.currency !== snap.currency) return {
|
|
8326
|
+
if (prevRef.currency !== snap.currency || todayOfficialCost < prevRef.costAtBaseline || snap.total > prevRef.total + .009) return {
|
|
7139
8327
|
ref: snap,
|
|
7140
8328
|
event: { kind: "structure-reset" }
|
|
7141
8329
|
};
|
|
@@ -7148,7 +8336,7 @@ function reconcileBalanceDelta(prevRef, balance, todayOfficialCost, dayKey, nowM
|
|
|
7148
8336
|
ref: prevRef,
|
|
7149
8337
|
event: { kind: "flat" }
|
|
7150
8338
|
};
|
|
7151
|
-
const cost =
|
|
8339
|
+
const cost = todayOfficialCost - prevRef.costAtBaseline;
|
|
7152
8340
|
if (Math.abs(spent - cost) > Math.max(MIN_DRIFT_ABS, DRIFT_RELATIVE * Math.max(spent, cost))) return {
|
|
7153
8341
|
ref: prevRef,
|
|
7154
8342
|
event: {
|
|
@@ -7186,27 +8374,40 @@ const pricingGate = createCooldownGate({
|
|
|
7186
8374
|
cooldownMs: 6e4
|
|
7187
8375
|
});
|
|
7188
8376
|
/**
|
|
7189
|
-
*
|
|
7190
|
-
*
|
|
7191
|
-
*
|
|
8377
|
+
* 解析 `{ rates: { CNY: number } }` 结构的汇率 JSON(open.er-api.com 与 AllRatesToday 通用)。
|
|
8378
|
+
* @param text - 响应正文。
|
|
8379
|
+
* @returns CNY 汇率;结构不符或非正数时 undefined。
|
|
7192
8380
|
*/
|
|
7193
|
-
|
|
7194
|
-
|
|
7195
|
-
|
|
7196
|
-
|
|
7197
|
-
|
|
8381
|
+
function parseRatesJsonCny(text) {
|
|
8382
|
+
try {
|
|
8383
|
+
const cny = JSON.parse(text).rates?.CNY;
|
|
8384
|
+
return typeof cny === "number" && Number.isFinite(cny) && cny > 0 ? cny : void 0;
|
|
8385
|
+
} catch {
|
|
8386
|
+
return;
|
|
7198
8387
|
}
|
|
7199
|
-
}
|
|
7200
|
-
|
|
7201
|
-
|
|
7202
|
-
|
|
7203
|
-
|
|
7204
|
-
|
|
7205
|
-
|
|
7206
|
-
|
|
8388
|
+
}
|
|
8389
|
+
/**
|
|
8390
|
+
* USD → CNY 汇率源,按顺序尝试:国内可达的腾讯财经行情(免 key、`~` 分隔
|
|
8391
|
+
* 第 4 个字段为价格)优先,国外 open.er-api.com 兜底,再退到 AllRatesToday
|
|
8392
|
+
* 免 key 端点(同结构)。任一源失败自动落到下一个;全部失败由调用方降级内置汇率。
|
|
8393
|
+
*/
|
|
8394
|
+
const RATE_SOURCES = [
|
|
8395
|
+
{
|
|
8396
|
+
url: "https://qt.gtimg.cn/q=whUSDCNY",
|
|
8397
|
+
parse: (text) => {
|
|
8398
|
+
const price = /"([^"]*)"/.exec(text)?.[1]?.split("~")[3];
|
|
8399
|
+
return price !== void 0 && price !== "" ? Number(price) : void 0;
|
|
7207
8400
|
}
|
|
8401
|
+
},
|
|
8402
|
+
{
|
|
8403
|
+
url: "https://open.er-api.com/v6/latest/USD",
|
|
8404
|
+
parse: parseRatesJsonCny
|
|
8405
|
+
},
|
|
8406
|
+
{
|
|
8407
|
+
url: "https://allratestoday.com/api/open/latest/USD",
|
|
8408
|
+
parse: parseRatesJsonCny
|
|
7208
8409
|
}
|
|
7209
|
-
|
|
8410
|
+
];
|
|
7210
8411
|
/** OpenRouter's public model list: per-token USD prices, no key needed. */
|
|
7211
8412
|
const ROUTER_URL = "https://openrouter.ai/api/v1/models";
|
|
7212
8413
|
/** models.dev 公开目录:pi-ai 预制提供方的上游数据源(USD / 1M tokens)。
|
|
@@ -7311,25 +8512,25 @@ async function fetchJson(url) {
|
|
|
7311
8512
|
/** Latest USD → CNY rate from the first working source, or undefined when none respond. */
|
|
7312
8513
|
/**
|
|
7313
8514
|
* EUR → CNY 汇率源。与 USD 同一套降级约定:腾讯行情优先(免 key、国内可达),
|
|
7314
|
-
* open.er-api.com
|
|
8515
|
+
* open.er-api.com 兑底,AllRatesToday 再兜底;全部失败由调用方降级内置汇率,不阻塞其他价格拉取。
|
|
7315
8516
|
*/
|
|
7316
|
-
const EUR_RATE_SOURCES = [
|
|
7317
|
-
|
|
7318
|
-
|
|
7319
|
-
|
|
7320
|
-
|
|
7321
|
-
|
|
7322
|
-
}, {
|
|
7323
|
-
url: "https://open.er-api.com/v6/latest/EUR",
|
|
7324
|
-
parse: (text) => {
|
|
7325
|
-
try {
|
|
7326
|
-
const cny = JSON.parse(text).rates?.CNY;
|
|
7327
|
-
return typeof cny === "number" && Number.isFinite(cny) && cny > 0 ? cny : void 0;
|
|
7328
|
-
} catch {
|
|
7329
|
-
return;
|
|
8517
|
+
const EUR_RATE_SOURCES = [
|
|
8518
|
+
{
|
|
8519
|
+
url: "https://qt.gtimg.cn/q=whEURCNY",
|
|
8520
|
+
parse: (text) => {
|
|
8521
|
+
const price = /"([^"]*)"/.exec(text)?.[1]?.split("~")[3];
|
|
8522
|
+
return price !== void 0 && price !== "" ? Number(price) : void 0;
|
|
7330
8523
|
}
|
|
8524
|
+
},
|
|
8525
|
+
{
|
|
8526
|
+
url: "https://open.er-api.com/v6/latest/EUR",
|
|
8527
|
+
parse: parseRatesJsonCny
|
|
8528
|
+
},
|
|
8529
|
+
{
|
|
8530
|
+
url: "https://allratestoday.com/api/open/latest/EUR",
|
|
8531
|
+
parse: parseRatesJsonCny
|
|
7331
8532
|
}
|
|
7332
|
-
|
|
8533
|
+
];
|
|
7333
8534
|
/**
|
|
7334
8535
|
* 按顺序尝试汇率源,返回第一个合法正数。
|
|
7335
8536
|
* @param sources - 待尝试的汇率源。
|
|
@@ -7453,6 +8654,7 @@ function buildExtraModels(data) {
|
|
|
7453
8654
|
if (input === void 0 || output === void 0) continue;
|
|
7454
8655
|
const declaredCacheRead = asPrice(cost.cache_read);
|
|
7455
8656
|
const cacheRead = declaredCacheRead ?? input * .1;
|
|
8657
|
+
const declaredCacheWrite = asPrice(cost.cache_write);
|
|
7456
8658
|
const name = modelDoc.name;
|
|
7457
8659
|
const familyValue = modelDoc.family;
|
|
7458
8660
|
const family = typeof familyValue === "string" && familyValue !== "" ? familyValue : void 0;
|
|
@@ -7480,7 +8682,8 @@ function buildExtraModels(data) {
|
|
|
7480
8682
|
price: {
|
|
7481
8683
|
input,
|
|
7482
8684
|
cacheHit: cacheRead,
|
|
7483
|
-
output
|
|
8685
|
+
output,
|
|
8686
|
+
...declaredCacheWrite !== void 0 ? { cacheWrite: declaredCacheWrite } : {}
|
|
7484
8687
|
}
|
|
7485
8688
|
},
|
|
7486
8689
|
input,
|
|
@@ -8927,20 +10130,46 @@ function isLoopbackHost(req, trustedHosts = /* @__PURE__ */ new Set()) {
|
|
|
8927
10130
|
if (name === "localhost" || name === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(name)) return true;
|
|
8928
10131
|
return name !== "" && trustedHosts.has(name);
|
|
8929
10132
|
}
|
|
8930
|
-
/** 校验 Origin
|
|
10133
|
+
/** 校验 Origin 头是否可信(写操作用,防止跨站表单/fetch 改写设置)。Origin 缺失
|
|
8931
10134
|
* (curl 或同源 fetch 不带)视为放行,交给下方的 Content-Type 校验兜底;Origin 存在
|
|
8932
|
-
*
|
|
8933
|
-
|
|
10135
|
+
* 但主机既非回环、也不在 trustedHosts 里则拒绝——跨站脚本发起的写请求必带攻击者
|
|
10136
|
+
* 域名的 Origin。
|
|
10137
|
+
*
|
|
10138
|
+
* 反向代理场景:浏览器把页面自身的地址写进 Origin(`https://dash.example.com`)。
|
|
10139
|
+
* Host 头因为同一域名被 trustedHosts 放行,Origin 却是同一个非回环域名——只认回环
|
|
10140
|
+
* 字面量会让「已显式信任的主机」在写操作上必然 403(读操作正常),表现为面板能
|
|
10141
|
+
* 打开、点任何保存/入队都报 `forbidden: loopback only`。因此 Origin 与 Host 共用
|
|
10142
|
+
* 同一份 trustedHosts:用户显式信任某个主机,就等于接受该主机的同源写请求。
|
|
10143
|
+
* @param origin - 原始 Origin 头(可能缺失)。
|
|
10144
|
+
* @param trustedHosts - 已归一化的可信主机名集合,与 {@link isLoopbackHost} 同口径。
|
|
10145
|
+
*/
|
|
10146
|
+
function isLoopbackOrigin(origin, trustedHosts = /* @__PURE__ */ new Set()) {
|
|
8934
10147
|
if (origin === void 0 || origin === "") return true;
|
|
8935
10148
|
try {
|
|
8936
10149
|
const raw = new URL(origin).hostname;
|
|
8937
10150
|
const host = raw.startsWith("[") && raw.endsWith("]") ? raw.slice(1, -1) : raw;
|
|
8938
|
-
|
|
10151
|
+
if (host === "localhost" || host === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host)) return true;
|
|
10152
|
+
return host !== "" && trustedHosts.has(host.toLowerCase());
|
|
8939
10153
|
} catch {
|
|
8940
10154
|
return false;
|
|
8941
10155
|
}
|
|
8942
10156
|
}
|
|
8943
10157
|
/**
|
|
10158
|
+
* 路由准入声明(宿主 0.2.3-alpha.1 起必需)。
|
|
10159
|
+
*
|
|
10160
|
+
* 宿主把 Web 路由的 `auth` 默认值从「无鉴权」改成了 `'required'`:未通过宿主
|
|
10161
|
+
* 连接层鉴权的请求在进入 handler **之前**就被拒(401/503),插件自带的守卫
|
|
10162
|
+
* 根本没机会执行——面板会静默变成一片 0。本插件的端点只服务本机浏览器,安全
|
|
10163
|
+
* 边界是 {@link guardLoopback}(peer 回环 socket + Host 头精确字面量 +
|
|
10164
|
+
* trustedHosts 白名单 + Origin 校验),因此显式声明匿名准入。
|
|
10165
|
+
*
|
|
10166
|
+
* 宿主的可信主机栅栏仍然生效(Host 必须是回环/可信主机、Origin 必须同源),
|
|
10167
|
+
* 这里只放宽「需要 peer 凭据」这一层,不放宽来源校验。
|
|
10168
|
+
*
|
|
10169
|
+
* 老宿主(≤0.2.2-rc.5)没有 `auth` 字段,多余字段被忽略,行为与从前一致。
|
|
10170
|
+
*/
|
|
10171
|
+
const ANONYMOUS_ROUTE_AUTH = { auth: "anonymous" };
|
|
10172
|
+
/**
|
|
8944
10173
|
* 回环防护守卫:仅接受回环 GET 请求(peer socket 地址 + Host 头同时校验)。
|
|
8945
10174
|
* 不满足时返回 403 并结束响应;调用方在 handler 顶部调用,返回 false 即已拒绝。
|
|
8946
10175
|
* @param req - 当前请求。
|
|
@@ -8961,6 +10190,312 @@ function guardLoopback(req, res, trustedHosts = /* @__PURE__ */ new Set()) {
|
|
|
8961
10190
|
return true;
|
|
8962
10191
|
}
|
|
8963
10192
|
//#endregion
|
|
10193
|
+
//#region lib/types/peak-schedule-store.js
|
|
10194
|
+
const emptyHistory = () => ({
|
|
10195
|
+
version: 3,
|
|
10196
|
+
revisions: []
|
|
10197
|
+
});
|
|
10198
|
+
var ScheduleClockConflict = class extends Error {};
|
|
10199
|
+
function readSaved(path) {
|
|
10200
|
+
let bytes;
|
|
10201
|
+
try {
|
|
10202
|
+
bytes = readFileSync(path);
|
|
10203
|
+
} catch (error) {
|
|
10204
|
+
return {
|
|
10205
|
+
history: emptyHistory(),
|
|
10206
|
+
notices: error.code === "ENOENT" ? [] : [{ code: "unreadableSchedule" }]
|
|
10207
|
+
};
|
|
10208
|
+
}
|
|
10209
|
+
try {
|
|
10210
|
+
return {
|
|
10211
|
+
...readScheduleHistory(JSON.parse(bytes.toString("utf8"))),
|
|
10212
|
+
bytes
|
|
10213
|
+
};
|
|
10214
|
+
} catch {
|
|
10215
|
+
return {
|
|
10216
|
+
history: emptyHistory(),
|
|
10217
|
+
notices: [{ code: "malformedSchedule" }],
|
|
10218
|
+
bytes
|
|
10219
|
+
};
|
|
10220
|
+
}
|
|
10221
|
+
}
|
|
10222
|
+
/** Drop only writes that repeat the immediately preceding state of that key.
|
|
10223
|
+
* A→B→A and deletions after a real override remain distinct historical intervals. */
|
|
10224
|
+
function compact(history) {
|
|
10225
|
+
const state = /* @__PURE__ */ new Map();
|
|
10226
|
+
return {
|
|
10227
|
+
version: 3,
|
|
10228
|
+
revisions: history.revisions.flatMap((row) => {
|
|
10229
|
+
const changes = Object.fromEntries(Object.entries(row.changes).filter(([key, rule]) => {
|
|
10230
|
+
const value = JSON.stringify(rule);
|
|
10231
|
+
if ((state.get(key) ?? "null") === value) return false;
|
|
10232
|
+
state.set(key, value);
|
|
10233
|
+
return true;
|
|
10234
|
+
}));
|
|
10235
|
+
return Object.keys(changes).length ? [{
|
|
10236
|
+
...row,
|
|
10237
|
+
changes
|
|
10238
|
+
}] : [];
|
|
10239
|
+
})
|
|
10240
|
+
};
|
|
10241
|
+
}
|
|
10242
|
+
function openScheduleStore(path, eligible, now = Date.now) {
|
|
10243
|
+
let saved = readSaved(path);
|
|
10244
|
+
function project() {
|
|
10245
|
+
const config = emptySchedule();
|
|
10246
|
+
const skipped = /* @__PURE__ */ new Set();
|
|
10247
|
+
for (const { changes } of saved.history.revisions) for (const [key, rule] of Object.entries(changes)) if (rule === null) {
|
|
10248
|
+
delete config.models[key];
|
|
10249
|
+
skipped.delete(key);
|
|
10250
|
+
} else if (eligible(modelFromScheduleKey(key))) config.models[key] = rule;
|
|
10251
|
+
else skipped.add(key);
|
|
10252
|
+
return {
|
|
10253
|
+
config,
|
|
10254
|
+
notices: [...saved.notices, ...Array.from(skipped, (detail) => ({
|
|
10255
|
+
code: "ineligibleModel",
|
|
10256
|
+
detail
|
|
10257
|
+
}))]
|
|
10258
|
+
};
|
|
10259
|
+
}
|
|
10260
|
+
let active = project();
|
|
10261
|
+
let queue = Promise.resolve();
|
|
10262
|
+
return {
|
|
10263
|
+
current: () => active.config,
|
|
10264
|
+
history: () => saved.history,
|
|
10265
|
+
notices: () => active.notices,
|
|
10266
|
+
save(edit, latestEventTime = -1) {
|
|
10267
|
+
const commit = queue.then(async () => {
|
|
10268
|
+
const { changes } = parseScheduleEdit(edit);
|
|
10269
|
+
mkdirSync(dirname(path), {
|
|
10270
|
+
recursive: true,
|
|
10271
|
+
mode: 448
|
|
10272
|
+
});
|
|
10273
|
+
await withFileLock(path, async () => {
|
|
10274
|
+
const previous = readSaved(path);
|
|
10275
|
+
if (previous.notices.some((n) => n.code === "unreadableSchedule")) throw Error("Schedule unavailable");
|
|
10276
|
+
const revisions = previous.history.revisions;
|
|
10277
|
+
const delta = Object.fromEntries(Object.entries(changes).filter(([key, rule]) => {
|
|
10278
|
+
const latest = revisions.findLast((row) => Object.hasOwn(row.changes, key))?.changes[key] ?? null;
|
|
10279
|
+
return JSON.stringify(latest) !== JSON.stringify(rule);
|
|
10280
|
+
}));
|
|
10281
|
+
if (!Object.keys(delta).length) {
|
|
10282
|
+
if (previous.bytes?.equals(saved.bytes ?? Buffer.alloc(0)) === false) {
|
|
10283
|
+
saved = previous;
|
|
10284
|
+
active = project();
|
|
10285
|
+
}
|
|
10286
|
+
return;
|
|
10287
|
+
}
|
|
10288
|
+
if (previous.bytes !== void 0) {
|
|
10289
|
+
await writeFileAtomic(`${path}.bak`, previous.bytes, {
|
|
10290
|
+
mode: 384,
|
|
10291
|
+
dirMode: 448
|
|
10292
|
+
});
|
|
10293
|
+
if (previous.notices.length) {
|
|
10294
|
+
const hash = createHash("sha256").update(previous.bytes).digest("hex");
|
|
10295
|
+
await writeFileAtomic(`${path}.recovery-${hash}`, previous.bytes, {
|
|
10296
|
+
mode: 384,
|
|
10297
|
+
dirMode: 448
|
|
10298
|
+
});
|
|
10299
|
+
}
|
|
10300
|
+
}
|
|
10301
|
+
const savedAt = now();
|
|
10302
|
+
const lastRevision = revisions.at(-1)?.effectiveFromMs ?? -1;
|
|
10303
|
+
if (savedAt < lastRevision || savedAt <= latestEventTime) throw new ScheduleClockConflict("scheduleClockConflict");
|
|
10304
|
+
const effectiveFromMs = Math.max(savedAt, lastRevision + 1);
|
|
10305
|
+
if (!Number.isSafeInteger(effectiveFromMs) || effectiveFromMs < 0 || effectiveFromMs > 864e13) throw Error("Invalid schedule clock");
|
|
10306
|
+
const history = compact({
|
|
10307
|
+
version: 3,
|
|
10308
|
+
revisions: [...revisions, {
|
|
10309
|
+
effectiveFromMs,
|
|
10310
|
+
changes: delta,
|
|
10311
|
+
audit: {
|
|
10312
|
+
source: "local-api",
|
|
10313
|
+
actor: "unidentified"
|
|
10314
|
+
}
|
|
10315
|
+
}]
|
|
10316
|
+
});
|
|
10317
|
+
const json = JSON.stringify(history);
|
|
10318
|
+
await writeFileAtomic(path, json, {
|
|
10319
|
+
mode: 384,
|
|
10320
|
+
dirMode: 448
|
|
10321
|
+
});
|
|
10322
|
+
saved = {
|
|
10323
|
+
history,
|
|
10324
|
+
notices: [],
|
|
10325
|
+
bytes: Buffer.from(json)
|
|
10326
|
+
};
|
|
10327
|
+
active = project();
|
|
10328
|
+
}, { waitMs: 2e3 });
|
|
10329
|
+
});
|
|
10330
|
+
queue = commit.catch(() => {});
|
|
10331
|
+
return commit;
|
|
10332
|
+
}
|
|
10333
|
+
};
|
|
10334
|
+
}
|
|
10335
|
+
//#endregion
|
|
10336
|
+
//#region lib/types/routes/peak-schedule.js
|
|
10337
|
+
/** Domain validation failures are distinct from storage failures. */
|
|
10338
|
+
var PeakScheduleInputError = class extends Error {};
|
|
10339
|
+
const MAX_BODY_BYTES = 1048576;
|
|
10340
|
+
function reply(res, status, value) {
|
|
10341
|
+
res.writeHead(status, {
|
|
10342
|
+
"content-type": "application/json; charset=utf-8",
|
|
10343
|
+
"cache-control": "no-store"
|
|
10344
|
+
});
|
|
10345
|
+
res.end(JSON.stringify(value));
|
|
10346
|
+
}
|
|
10347
|
+
function registerPeakScheduleRoute(ctx, deps) {
|
|
10348
|
+
ctx.effect(() => ctx.webServer.register({
|
|
10349
|
+
kind: "exact",
|
|
10350
|
+
path: "/api/billing/peak-schedule",
|
|
10351
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
10352
|
+
handler: async (req, res) => {
|
|
10353
|
+
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
10354
|
+
let raw;
|
|
10355
|
+
if (req.method === "POST") {
|
|
10356
|
+
if (!isLoopbackOrigin(req.headers.origin, deps.trustedHosts)) return reply(res, 403, {
|
|
10357
|
+
error: "forbidden: loopback only",
|
|
10358
|
+
message: "仅限本机请求"
|
|
10359
|
+
});
|
|
10360
|
+
if (req.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") return reply(res, 415, {
|
|
10361
|
+
error: "unsupported content-type",
|
|
10362
|
+
message: "请使用 application/json"
|
|
10363
|
+
});
|
|
10364
|
+
const chunks = [];
|
|
10365
|
+
let bytes = 0;
|
|
10366
|
+
try {
|
|
10367
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
10368
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
10369
|
+
bytes += buf.length;
|
|
10370
|
+
if (bytes > MAX_BODY_BYTES) {
|
|
10371
|
+
req.resume();
|
|
10372
|
+
return reply(res, 413, {
|
|
10373
|
+
error: "body too large",
|
|
10374
|
+
message: "请求体过大"
|
|
10375
|
+
});
|
|
10376
|
+
}
|
|
10377
|
+
chunks.push(buf);
|
|
10378
|
+
}
|
|
10379
|
+
raw = JSON.parse(Buffer.concat(chunks, bytes).toString("utf8"));
|
|
10380
|
+
} catch {
|
|
10381
|
+
return reply(res, 400, {
|
|
10382
|
+
error: "invalid json body",
|
|
10383
|
+
message: "请求 JSON 无效"
|
|
10384
|
+
});
|
|
10385
|
+
}
|
|
10386
|
+
}
|
|
10387
|
+
let snapshot;
|
|
10388
|
+
try {
|
|
10389
|
+
snapshot = req.method === "POST" ? await deps.save(raw) : await deps.read();
|
|
10390
|
+
} catch (error) {
|
|
10391
|
+
if (req.method === "POST" && error instanceof PeakScheduleInputError) return reply(res, 400, {
|
|
10392
|
+
error: error.message,
|
|
10393
|
+
message: "峰谷设置格式无效 / Invalid schedule format"
|
|
10394
|
+
});
|
|
10395
|
+
if (req.method === "POST" && error instanceof ScheduleClockConflict) return reply(res, 409, {
|
|
10396
|
+
error: "scheduleClockConflict",
|
|
10397
|
+
message: "生效时刻早于已记录的调用或修订 / Schedule clock conflict"
|
|
10398
|
+
});
|
|
10399
|
+
return reply(res, 503, {
|
|
10400
|
+
error: "peak schedule unavailable",
|
|
10401
|
+
message: "峰谷设置暂不可用"
|
|
10402
|
+
});
|
|
10403
|
+
}
|
|
10404
|
+
reply(res, 200, snapshot);
|
|
10405
|
+
}
|
|
10406
|
+
}), "usage-billing: peak-schedule route");
|
|
10407
|
+
}
|
|
10408
|
+
//#endregion
|
|
10409
|
+
//#region lib/types/peak-schedule-models.js
|
|
10410
|
+
async function discover$1(llm, route) {
|
|
10411
|
+
if (!llm?.listModels) throw Error("Model registry unavailable");
|
|
10412
|
+
let timer;
|
|
10413
|
+
try {
|
|
10414
|
+
const models = await Promise.race([llm.listModels(route), new Promise((_, reject) => {
|
|
10415
|
+
timer = setTimeout(() => reject(Error("Model discovery timed out")), 5e3);
|
|
10416
|
+
})]);
|
|
10417
|
+
if (!Array.isArray(models)) throw Error("Invalid model registry response");
|
|
10418
|
+
return models;
|
|
10419
|
+
} finally {
|
|
10420
|
+
clearTimeout(timer);
|
|
10421
|
+
}
|
|
10422
|
+
}
|
|
10423
|
+
function eligibleScheduleModel(key) {
|
|
10424
|
+
const entry = modelOf(key);
|
|
10425
|
+
return key === entry.key && entry.provider === "DeepSeek" && entry.price.offPeak !== void 0 && entry.tierSemantics !== "latency";
|
|
10426
|
+
}
|
|
10427
|
+
/** Cache only remote discovery. Route identity and locally declared models are refreshed every request. */
|
|
10428
|
+
function createScheduleModelDiscovery(now = Date.now, ttlMs = 6e4) {
|
|
10429
|
+
const cache = /* @__PURE__ */ new Map();
|
|
10430
|
+
let service;
|
|
10431
|
+
function listModels(llm, id, baseURL) {
|
|
10432
|
+
const key = JSON.stringify([id, baseURL]);
|
|
10433
|
+
const hit = cache.get(key);
|
|
10434
|
+
if (hit && hit.expires > now()) return hit.result;
|
|
10435
|
+
const entry = {
|
|
10436
|
+
expires: Infinity,
|
|
10437
|
+
result: discover$1(llm, id)
|
|
10438
|
+
};
|
|
10439
|
+
cache.set(key, entry);
|
|
10440
|
+
entry.result.then(() => {
|
|
10441
|
+
entry.expires = now() + ttlMs;
|
|
10442
|
+
}, () => {
|
|
10443
|
+
entry.expires = now() + Math.min(ttlMs, 15e3);
|
|
10444
|
+
});
|
|
10445
|
+
return entry.result;
|
|
10446
|
+
}
|
|
10447
|
+
return async (llm, profiles, aliases) => {
|
|
10448
|
+
if (service !== llm) {
|
|
10449
|
+
cache.clear();
|
|
10450
|
+
service = llm;
|
|
10451
|
+
}
|
|
10452
|
+
const routes = /* @__PURE__ */ new Map();
|
|
10453
|
+
const notices = [];
|
|
10454
|
+
try {
|
|
10455
|
+
if (!llm?.listProviders) throw Error();
|
|
10456
|
+
for (const p of llm.listProviders()) if (typeof p.id === "string") routes.set(p.id, p.name || p.id);
|
|
10457
|
+
} catch {
|
|
10458
|
+
notices.push({ code: "discoveryFailed" });
|
|
10459
|
+
}
|
|
10460
|
+
const views = { ...profiles };
|
|
10461
|
+
for (const id of routes.keys()) if (!Object.hasOwn(views, id)) views[id] = {};
|
|
10462
|
+
for (const [id, profile] of Object.entries(profiles)) if (profile.models) routes.set(id, profile.displayName || id);
|
|
10463
|
+
const liveCacheKeys = new Set([...routes.keys()].map((id) => JSON.stringify([id, profiles[id]?.baseURL])));
|
|
10464
|
+
for (const key of cache.keys()) if (!liveCacheKeys.has(key)) cache.delete(key);
|
|
10465
|
+
const rows = /* @__PURE__ */ new Map();
|
|
10466
|
+
await Promise.all([...routes].map(async ([id, label]) => {
|
|
10467
|
+
const mapped = aliases[id] ?? id;
|
|
10468
|
+
if (accountRoute(id) || accountRoute(mapped)) return;
|
|
10469
|
+
const source = siteBucketKey(siteRefOf(mapped, views));
|
|
10470
|
+
if (!validSource(source)) return;
|
|
10471
|
+
let models;
|
|
10472
|
+
try {
|
|
10473
|
+
models = profiles[id]?.models ?? await listModels(llm, id, profiles[id]?.baseURL);
|
|
10474
|
+
} catch {
|
|
10475
|
+
notices.push({
|
|
10476
|
+
code: "discoveryFailed",
|
|
10477
|
+
detail: id
|
|
10478
|
+
});
|
|
10479
|
+
return;
|
|
10480
|
+
}
|
|
10481
|
+
for (const item of models) {
|
|
10482
|
+
const raw = typeof item === "string" ? item : item?.id;
|
|
10483
|
+
if (typeof raw !== "string") continue;
|
|
10484
|
+
const model = resolveCatalogKey(raw);
|
|
10485
|
+
if (eligibleScheduleModel(model)) rows.set(scheduleKey(source, model), {
|
|
10486
|
+
source,
|
|
10487
|
+
model,
|
|
10488
|
+
label: `${source} / ${modelOf(model).name} (${label})`
|
|
10489
|
+
});
|
|
10490
|
+
}
|
|
10491
|
+
}));
|
|
10492
|
+
return {
|
|
10493
|
+
models: [...rows.values()].sort((a, b) => a.label.localeCompare(b.label)),
|
|
10494
|
+
notices
|
|
10495
|
+
};
|
|
10496
|
+
};
|
|
10497
|
+
}
|
|
10498
|
+
//#endregion
|
|
8964
10499
|
//#region lib/types/routes/notify-claim.js
|
|
8965
10500
|
/**
|
|
8966
10501
|
* 路由:POST /api/billing/notify-claim
|
|
@@ -8985,6 +10520,7 @@ function registerNotifyClaimRoute(ctx, deps) {
|
|
|
8985
10520
|
ctx.effect(() => ctx.webServer.register({
|
|
8986
10521
|
kind: "exact",
|
|
8987
10522
|
path: "/api/billing/notify-claim",
|
|
10523
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
8988
10524
|
handler: async (req, res) => {
|
|
8989
10525
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
8990
10526
|
if (req.method !== "POST") {
|
|
@@ -8992,7 +10528,7 @@ function registerNotifyClaimRoute(ctx, deps) {
|
|
|
8992
10528
|
res.end(JSON.stringify({ error: "method not allowed" }));
|
|
8993
10529
|
return;
|
|
8994
10530
|
}
|
|
8995
|
-
if (!isLoopbackOrigin(req.headers.origin) || !(req.headers["content-type"] ?? "").toLowerCase().includes("application/json")) {
|
|
10531
|
+
if (!isLoopbackOrigin(req.headers.origin, deps.trustedHosts) || !(req.headers["content-type"] ?? "").toLowerCase().includes("application/json")) {
|
|
8996
10532
|
res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
|
|
8997
10533
|
res.end(JSON.stringify({ error: "forbidden: loopback only" }));
|
|
8998
10534
|
return;
|
|
@@ -9043,6 +10579,136 @@ function registerNotifyClaimRoute(ctx, deps) {
|
|
|
9043
10579
|
}), "usage-billing: notify-claim route");
|
|
9044
10580
|
}
|
|
9045
10581
|
//#endregion
|
|
10582
|
+
//#region lib/types/routes/pricing-models.js
|
|
10583
|
+
const JSON_HEADERS$1 = {
|
|
10584
|
+
"content-type": "application/json; charset=utf-8",
|
|
10585
|
+
"cache-control": "no-store"
|
|
10586
|
+
};
|
|
10587
|
+
const MODEL_CACHE_MS = 6e4;
|
|
10588
|
+
const PARTIAL_MODEL_CACHE_MS = 15e3;
|
|
10589
|
+
async function discover(registry, route) {
|
|
10590
|
+
let timer;
|
|
10591
|
+
try {
|
|
10592
|
+
return await Promise.race([registry.listModels(route), new Promise((_, reject) => {
|
|
10593
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error("Model discovery timed out")), 5e3);
|
|
10594
|
+
})]);
|
|
10595
|
+
} finally {
|
|
10596
|
+
clearTimeout(timer);
|
|
10597
|
+
}
|
|
10598
|
+
}
|
|
10599
|
+
/** Static settings remain authoritative even when the registry is unavailable. */
|
|
10600
|
+
async function configuredPricingModels(ctx) {
|
|
10601
|
+
const routes = /* @__PURE__ */ new Map();
|
|
10602
|
+
let partial = false;
|
|
10603
|
+
let registry;
|
|
10604
|
+
const profiles = /* @__PURE__ */ new Map();
|
|
10605
|
+
try {
|
|
10606
|
+
const value = ctx.settings.describe({ redactSecrets: true }).find((item) => item.ns === "llm-pi-ai")?.value;
|
|
10607
|
+
for (const [id, profile] of Object.entries(value?.providers ?? {})) {
|
|
10608
|
+
if (!id.trim() || !profile || typeof profile !== "object" || Array.isArray(profile)) {
|
|
10609
|
+
partial = true;
|
|
10610
|
+
continue;
|
|
10611
|
+
}
|
|
10612
|
+
profiles.set(id, profile);
|
|
10613
|
+
routes.set(id, typeof profile.displayName === "string" && profile.displayName ? profile.displayName : id);
|
|
10614
|
+
}
|
|
10615
|
+
} catch {
|
|
10616
|
+
partial = true;
|
|
10617
|
+
}
|
|
10618
|
+
try {
|
|
10619
|
+
registry = ctx.get("llm");
|
|
10620
|
+
if (!registry) partial = true;
|
|
10621
|
+
for (const p of registry?.listProviders() ?? []) {
|
|
10622
|
+
if (typeof p?.id !== "string" || !p.id.trim()) {
|
|
10623
|
+
partial = true;
|
|
10624
|
+
continue;
|
|
10625
|
+
}
|
|
10626
|
+
const displayName = profiles.get(p.id)?.displayName;
|
|
10627
|
+
const fallback = typeof p.name === "string" && p.name ? p.name : p.id;
|
|
10628
|
+
routes.set(p.id, typeof displayName === "string" && displayName ? displayName : fallback);
|
|
10629
|
+
}
|
|
10630
|
+
} catch {
|
|
10631
|
+
partial = true;
|
|
10632
|
+
}
|
|
10633
|
+
return {
|
|
10634
|
+
models: (await Promise.all([...routes].map(async ([route, channel]) => {
|
|
10635
|
+
if (!route || route === "deepseek-account") return [];
|
|
10636
|
+
const profile = profiles.get(route);
|
|
10637
|
+
let origin = "";
|
|
10638
|
+
if (profile?.baseURL) try {
|
|
10639
|
+
const url = new URL(profile.baseURL);
|
|
10640
|
+
if (["https:", "http:"].includes(url.protocol) && !isOfficialBaseUrl(url.origin)) origin = url.origin;
|
|
10641
|
+
} catch {}
|
|
10642
|
+
function parse(list) {
|
|
10643
|
+
if (!Array.isArray(list)) {
|
|
10644
|
+
partial = true;
|
|
10645
|
+
return [];
|
|
10646
|
+
}
|
|
10647
|
+
const models = [];
|
|
10648
|
+
for (const m of list) {
|
|
10649
|
+
if (typeof m?.id !== "string" || !m.id.trim() || m.name !== void 0 && typeof m.name !== "string") {
|
|
10650
|
+
partial = true;
|
|
10651
|
+
continue;
|
|
10652
|
+
}
|
|
10653
|
+
models.push({
|
|
10654
|
+
key: m.id,
|
|
10655
|
+
name: m.name ?? m.id,
|
|
10656
|
+
route,
|
|
10657
|
+
channel,
|
|
10658
|
+
origin
|
|
10659
|
+
});
|
|
10660
|
+
}
|
|
10661
|
+
return models;
|
|
10662
|
+
}
|
|
10663
|
+
const declared = parse(profile?.models === void 0 ? [] : profile.models);
|
|
10664
|
+
if (declared.length || !registry) return declared;
|
|
10665
|
+
try {
|
|
10666
|
+
return parse(await discover(registry, route));
|
|
10667
|
+
} catch (error) {
|
|
10668
|
+
if (!(error && typeof error === "object" && "code" in error && error.code === "NO_ADAPTER") && !(error instanceof Error && error.message === `no adapter registered for provider "${route}"`)) partial = true;
|
|
10669
|
+
return [];
|
|
10670
|
+
}
|
|
10671
|
+
}))).flat(),
|
|
10672
|
+
partial
|
|
10673
|
+
};
|
|
10674
|
+
}
|
|
10675
|
+
function registerPricingModelsRoute(ctx, trustedHosts) {
|
|
10676
|
+
ctx.effect(() => {
|
|
10677
|
+
let cached;
|
|
10678
|
+
let expiresAt = 0;
|
|
10679
|
+
let inFlight;
|
|
10680
|
+
function load() {
|
|
10681
|
+
if (cached && Date.now() < expiresAt) return Promise.resolve(cached);
|
|
10682
|
+
return inFlight ??= configuredPricingModels(ctx).then((result) => {
|
|
10683
|
+
cached = result;
|
|
10684
|
+
expiresAt = Date.now() + (result.partial ? PARTIAL_MODEL_CACHE_MS : MODEL_CACHE_MS);
|
|
10685
|
+
return result;
|
|
10686
|
+
}).finally(() => {
|
|
10687
|
+
inFlight = void 0;
|
|
10688
|
+
});
|
|
10689
|
+
}
|
|
10690
|
+
return ctx.webServer.register({
|
|
10691
|
+
kind: "exact",
|
|
10692
|
+
path: "/api/billing/pricing-models",
|
|
10693
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
10694
|
+
async handler(req, res) {
|
|
10695
|
+
if (!guardLoopback(req, res, trustedHosts)) return;
|
|
10696
|
+
if (req.method !== "GET") {
|
|
10697
|
+
res.writeHead(405, {
|
|
10698
|
+
...JSON_HEADERS$1,
|
|
10699
|
+
allow: "GET"
|
|
10700
|
+
});
|
|
10701
|
+
res.end(JSON.stringify({ error: "method not allowed" }));
|
|
10702
|
+
return;
|
|
10703
|
+
}
|
|
10704
|
+
const body = await load();
|
|
10705
|
+
res.writeHead(200, JSON_HEADERS$1);
|
|
10706
|
+
res.end(JSON.stringify(body));
|
|
10707
|
+
}
|
|
10708
|
+
});
|
|
10709
|
+
}, "usage-billing: pricing models route");
|
|
10710
|
+
}
|
|
10711
|
+
//#endregion
|
|
9046
10712
|
//#region lib/types/routes/pricing.js
|
|
9047
10713
|
/**
|
|
9048
10714
|
* 路由:GET /api/billing/pricing + POST /api/billing/pricing/refresh
|
|
@@ -9063,6 +10729,7 @@ function registerGetRoute(ctx, deps) {
|
|
|
9063
10729
|
ctx.effect(() => ctx.webServer.register({
|
|
9064
10730
|
kind: "exact",
|
|
9065
10731
|
path: "/api/billing/pricing",
|
|
10732
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
9066
10733
|
handler: async (req, res) => {
|
|
9067
10734
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
9068
10735
|
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
@@ -9075,6 +10742,7 @@ function registerRefreshRoute(ctx, deps) {
|
|
|
9075
10742
|
ctx.effect(() => ctx.webServer.register({
|
|
9076
10743
|
kind: "exact",
|
|
9077
10744
|
path: "/api/billing/pricing/refresh",
|
|
10745
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
9078
10746
|
handler: async (req, res) => {
|
|
9079
10747
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
9080
10748
|
if (req.method !== "POST") {
|
|
@@ -9082,7 +10750,7 @@ function registerRefreshRoute(ctx, deps) {
|
|
|
9082
10750
|
res.end(JSON.stringify({ error: "method not allowed" }));
|
|
9083
10751
|
return;
|
|
9084
10752
|
}
|
|
9085
|
-
if (!isLoopbackOrigin(req.headers.origin)) {
|
|
10753
|
+
if (!isLoopbackOrigin(req.headers.origin, deps.trustedHosts)) {
|
|
9086
10754
|
res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
|
|
9087
10755
|
res.end(JSON.stringify({ error: "forbidden: loopback only" }));
|
|
9088
10756
|
return;
|
|
@@ -9118,29 +10786,48 @@ function registerPricingRoutes(ctx, deps) {
|
|
|
9118
10786
|
* queryDeclaredEndpoints / reconcileBalanceDelta)在装配器里跑,路由只通过
|
|
9119
10787
|
* `cached()` 与 `refreshOnce()` 拿到结果。
|
|
9120
10788
|
*/
|
|
10789
|
+
/** Loopback callers can supply these advisory UI headers. */
|
|
10790
|
+
function readClientMetadata(headers) {
|
|
10791
|
+
const version = headers[BALANCE_CLIENT_HEADERS.version];
|
|
10792
|
+
const locale = headers[BALANCE_CLIENT_HEADERS.locale];
|
|
10793
|
+
const offset = headers[BALANCE_CLIENT_HEADERS.timezone];
|
|
10794
|
+
if (typeof version !== "string" || !/^[\w.+-]{1,64}$/.test(version) || typeof locale !== "string" || !/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8}){0,8}$/.test(locale) || typeof offset !== "string" || !/^-?\d{1,5}$/.test(offset)) return void 0;
|
|
10795
|
+
const timezoneOffsetSeconds = Number(offset);
|
|
10796
|
+
if (Math.abs(timezoneOffsetSeconds) > 50400) return void 0;
|
|
10797
|
+
return {
|
|
10798
|
+
version,
|
|
10799
|
+
locale,
|
|
10800
|
+
timezoneOffsetSeconds
|
|
10801
|
+
};
|
|
10802
|
+
}
|
|
9121
10803
|
function registerBalanceRoute(ctx, deps) {
|
|
9122
10804
|
ctx.effect(() => ctx.webServer.register({
|
|
9123
10805
|
kind: "exact",
|
|
9124
10806
|
path: "/api/billing/balance",
|
|
10807
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
9125
10808
|
handler: async (req, res) => {
|
|
9126
10809
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
9127
10810
|
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
9128
|
-
|
|
9129
|
-
|
|
10811
|
+
const client = readClientMetadata(req.headers);
|
|
10812
|
+
const cached = deps.cached(client);
|
|
10813
|
+
if (Date.now() - cached.at < deps.cacheMs) {
|
|
10814
|
+
res.end(JSON.stringify(cached.doc));
|
|
9130
10815
|
return;
|
|
9131
10816
|
}
|
|
9132
10817
|
let timedOut = false;
|
|
10818
|
+
let failed = false;
|
|
9133
10819
|
const onFailure = (error) => {
|
|
10820
|
+
failed = true;
|
|
9134
10821
|
console.warn("[usage-billing] refreshBalances failed; serving cached balances:", error);
|
|
9135
10822
|
};
|
|
9136
|
-
await Promise.race([deps.refreshOnce().then(() => void 0, onFailure), new Promise((resolve) => {
|
|
10823
|
+
await Promise.race([deps.refreshOnce(client).then(() => void 0, onFailure), new Promise((resolve) => {
|
|
9137
10824
|
setTimeout(() => {
|
|
9138
10825
|
timedOut = true;
|
|
9139
10826
|
resolve();
|
|
9140
10827
|
}, deps.responseBudgetMs).unref();
|
|
9141
10828
|
})]);
|
|
9142
|
-
const doc = deps.cached().doc;
|
|
9143
|
-
res.end(JSON.stringify(timedOut ? {
|
|
10829
|
+
const doc = deps.cached(client).doc;
|
|
10830
|
+
res.end(JSON.stringify(timedOut || failed ? {
|
|
9144
10831
|
...doc,
|
|
9145
10832
|
stale: true
|
|
9146
10833
|
} : doc));
|
|
@@ -9169,6 +10856,7 @@ function registerUsageToolRoute(ctx, deps) {
|
|
|
9169
10856
|
ctx.effect(() => ctx.webServer.register({
|
|
9170
10857
|
kind: "exact",
|
|
9171
10858
|
path: "/api/billing/usage-tool",
|
|
10859
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
9172
10860
|
handler: async (req, res) => {
|
|
9173
10861
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
9174
10862
|
if (req.method !== "GET" && req.method !== "POST") {
|
|
@@ -9177,7 +10865,7 @@ function registerUsageToolRoute(ctx, deps) {
|
|
|
9177
10865
|
return;
|
|
9178
10866
|
}
|
|
9179
10867
|
if (req.method === "POST") {
|
|
9180
|
-
if (!isLoopbackOrigin(req.headers.origin)) {
|
|
10868
|
+
if (!isLoopbackOrigin(req.headers.origin, deps.trustedHosts)) {
|
|
9181
10869
|
res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
|
|
9182
10870
|
res.end(JSON.stringify({ error: "forbidden: loopback only" }));
|
|
9183
10871
|
return;
|
|
@@ -9245,6 +10933,7 @@ function registerSubscriptionsRoute(ctx, deps) {
|
|
|
9245
10933
|
ctx.effect(() => ctx.webServer.register({
|
|
9246
10934
|
kind: "exact",
|
|
9247
10935
|
path: "/api/billing/subscriptions",
|
|
10936
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
9248
10937
|
handler: async (req, res) => {
|
|
9249
10938
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
9250
10939
|
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
@@ -9280,6 +10969,7 @@ function registerRelayQuotasRoute(ctx, deps) {
|
|
|
9280
10969
|
ctx.effect(() => ctx.webServer.register({
|
|
9281
10970
|
kind: "exact",
|
|
9282
10971
|
path: "/api/billing/relay-quotas",
|
|
10972
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
9283
10973
|
handler: async (req, res) => {
|
|
9284
10974
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
9285
10975
|
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
@@ -9413,6 +11103,7 @@ function registerUsageStatsRoute(ctx, deps) {
|
|
|
9413
11103
|
ctx.effect(() => ctx.webServer.register({
|
|
9414
11104
|
kind: "exact",
|
|
9415
11105
|
path: "/api/billing/usage-stats",
|
|
11106
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
9416
11107
|
handler: async (req, res) => {
|
|
9417
11108
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
9418
11109
|
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
@@ -9442,6 +11133,7 @@ function registerUsageStatsRoute(ctx, deps) {
|
|
|
9442
11133
|
deps.persistSnapshot(decorate(stats));
|
|
9443
11134
|
}, () => {});
|
|
9444
11135
|
let fresh;
|
|
11136
|
+
let sessionListError;
|
|
9445
11137
|
try {
|
|
9446
11138
|
fresh = await Promise.race([aggregating.then((stats) => stats), new Promise((resolve) => {
|
|
9447
11139
|
setTimeout(() => {
|
|
@@ -9450,16 +11142,19 @@ function registerUsageStatsRoute(ctx, deps) {
|
|
|
9450
11142
|
})]);
|
|
9451
11143
|
} catch (error) {
|
|
9452
11144
|
console.error("[usage-billing] usage-stats aggregate failed, falling back to snapshot:", error);
|
|
11145
|
+
if (error instanceof SessionListUnavailableError) sessionListError = error.reason;
|
|
9453
11146
|
}
|
|
9454
11147
|
if (fresh !== void 0) {
|
|
9455
11148
|
res.end(statsBodyOf(fresh));
|
|
9456
11149
|
return;
|
|
9457
11150
|
}
|
|
11151
|
+
const degraded = sessionListError === void 0 ? {} : { sessionListError };
|
|
9458
11152
|
const recent = deps.lastDoc?.();
|
|
9459
11153
|
if (recent !== void 0) {
|
|
9460
11154
|
res.end(JSON.stringify({
|
|
9461
11155
|
...decorate(recent),
|
|
9462
|
-
staleSnapshot: true
|
|
11156
|
+
staleSnapshot: true,
|
|
11157
|
+
...degraded
|
|
9463
11158
|
}));
|
|
9464
11159
|
return;
|
|
9465
11160
|
}
|
|
@@ -9468,15 +11163,141 @@ function registerUsageStatsRoute(ctx, deps) {
|
|
|
9468
11163
|
if (doc === null) continue;
|
|
9469
11164
|
res.end(JSON.stringify({
|
|
9470
11165
|
...decorate(doc),
|
|
9471
|
-
staleSnapshot: true
|
|
11166
|
+
staleSnapshot: true,
|
|
11167
|
+
...degraded
|
|
9472
11168
|
}));
|
|
9473
11169
|
return;
|
|
9474
11170
|
}
|
|
9475
|
-
res.end(JSON.stringify({
|
|
11171
|
+
res.end(JSON.stringify({
|
|
11172
|
+
error: "usage stats unavailable",
|
|
11173
|
+
...degraded
|
|
11174
|
+
}));
|
|
9476
11175
|
}
|
|
9477
11176
|
}), "usage-billing: usage-stats route");
|
|
9478
11177
|
}
|
|
9479
11178
|
//#endregion
|
|
11179
|
+
//#region lib/types/client/scheduled-band.js
|
|
11180
|
+
const MINUTE = 6e4;
|
|
11181
|
+
const DAY = 1440 * MINUTE;
|
|
11182
|
+
/** Only wall-clock boundaries can change a band. Infinity means no future transition. */
|
|
11183
|
+
function scheduledCountdown(now, channel, rule) {
|
|
11184
|
+
if (!rule || channel !== "deepseek-metered") return channelCountdown(now, channel);
|
|
11185
|
+
const tier = customTier(now, rule);
|
|
11186
|
+
const offset = rule.utcOffsetMinutes * MINUTE;
|
|
11187
|
+
const midnight = Math.floor((now + offset) / DAY) * DAY - offset;
|
|
11188
|
+
const boundaries = [.../* @__PURE__ */ new Set([0, ...rule.windows.filter((m) => m < 1440)])];
|
|
11189
|
+
const days = /* @__PURE__ */ new Set([
|
|
11190
|
+
0,
|
|
11191
|
+
1,
|
|
11192
|
+
2,
|
|
11193
|
+
3,
|
|
11194
|
+
4,
|
|
11195
|
+
5,
|
|
11196
|
+
6,
|
|
11197
|
+
7
|
|
11198
|
+
]);
|
|
11199
|
+
for (const date of rule.holidays) {
|
|
11200
|
+
const day = (Date.parse(`${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6)}T00:00Z`) - offset - midnight) / DAY;
|
|
11201
|
+
if (day < 0) continue;
|
|
11202
|
+
for (let i = 0; i <= 7; i++) days.add(day + i);
|
|
11203
|
+
}
|
|
11204
|
+
for (const day of [...days].sort((a, b) => a - b)) for (const m of boundaries) {
|
|
11205
|
+
const at = midnight + day * DAY + m * MINUTE;
|
|
11206
|
+
if (at > now && customTier(at, rule) !== tier) return {
|
|
11207
|
+
tier,
|
|
11208
|
+
nextSwitchInMs: at - now
|
|
11209
|
+
};
|
|
11210
|
+
}
|
|
11211
|
+
return {
|
|
11212
|
+
tier,
|
|
11213
|
+
nextSwitchInMs: Infinity
|
|
11214
|
+
};
|
|
11215
|
+
}
|
|
11216
|
+
//#endregion
|
|
11217
|
+
//#region lib/types/task-queue-band.js
|
|
11218
|
+
/**
|
|
11219
|
+
* 低谷队列的**按来源判档**(issue #143)。
|
|
11220
|
+
*
|
|
11221
|
+
* 背景:报告者实测发现两件事——①订阅通道(如 `dsh-opencode-go`)确实有峰谷
|
|
11222
|
+
* 倍率(其模型目录里 `deepseek-v4.1-flash` / `deepseek-v4-pro` 在 UTC 周一至
|
|
11223
|
+
* 周五 01:00–04:00 / 06:00–10:00 时 `factor: 2`,其余为 1,即北京时间
|
|
11224
|
+
* 09:00–12:00 / 14:00–18:00 倍率 2);②插件的「按模型配峰谷时段」已经能让
|
|
11225
|
+
* 订阅通道的模型进入配置(`eligibleScheduleModel` 只要求目录里有 offPeak 价),
|
|
11226
|
+
* 但低谷队列此前**硬过滤官方路由**且用全局 `tierAt` 判档——用户配了、计费认了、
|
|
11227
|
+
* 队列不认。
|
|
11228
|
+
*
|
|
11229
|
+
* 本模块把「某个来源 × 某个模型此刻处于哪一档」收敛成一处判定,供队列的
|
|
11230
|
+
* 候选筛选、启动闸门与展示共用(**同一件事不许两处各写一套**)。
|
|
11231
|
+
*
|
|
11232
|
+
* 两条纪律:
|
|
11233
|
+
* 1. **来源桶与聚合层同源**——`site:` / `direct:` 的映射由调用方注入(用
|
|
11234
|
+
* `siteRefOf` + `siteBucketKey`),本模块不自己猜,避免队列与计费对同一
|
|
11235
|
+
* 条路由得出两个来源桶。
|
|
11236
|
+
* 2. **窗口语义分列**——官方按量通道的谷档省**现金**,订阅通道的谷段省**套餐
|
|
11237
|
+
* 额度**(倍率 2→1)。两者窗口数值可能相同,但省的东西不同;界面必须分开
|
|
11238
|
+
* 表述,混说就是假声明。
|
|
11239
|
+
*/
|
|
11240
|
+
/**
|
|
11241
|
+
* 官方按量通道的来源桶前缀。宿主内置的 DeepSeek API Key 通道
|
|
11242
|
+
* (路由 id `deepseek-official`)不在 llm-pi-ai 路由表里,按直连归位。
|
|
11243
|
+
*/
|
|
11244
|
+
const OFFICIAL_SOURCE_RE = /^direct:deepseek(?:-|$)|^site:https:\/\/api\.deepseek\.com$/i;
|
|
11245
|
+
/**
|
|
11246
|
+
* 用户为该来源 × 模型配置的规则(未配置则 undefined)。
|
|
11247
|
+
*
|
|
11248
|
+
* @param facts - 判档事实。
|
|
11249
|
+
* @returns 命中的规则,未命中时 undefined。
|
|
11250
|
+
*/
|
|
11251
|
+
function ruleOf(facts) {
|
|
11252
|
+
if (facts.channel === void 0 || facts.schedule === void 0) return void 0;
|
|
11253
|
+
return facts.schedule.models[scheduleKey(facts.channel.source, facts.catalogKey)];
|
|
11254
|
+
}
|
|
11255
|
+
/**
|
|
11256
|
+
* 某来源 × 某模型此刻处于哪一档。
|
|
11257
|
+
*
|
|
11258
|
+
* 判定顺序:
|
|
11259
|
+
* 1. 用户配了该来源 × 模型的时段 → 用它(`effectiveRule` 补齐该来源的缺省:
|
|
11260
|
+
* 窗口、周末、时区;官方来源另补中国法定节假日);
|
|
11261
|
+
* 2. 未配 → 官方来源走全局 `tierAt`(含节假日),订阅来源走**同一组官方窗口
|
|
11262
|
+
* 但不含中国节假日**——订阅厂商的倍率表里没有中国节假日这一项,套上去会
|
|
11263
|
+
* 把本该计倍率的时段误判成低谷。
|
|
11264
|
+
*
|
|
11265
|
+
* @param facts - 判档事实。
|
|
11266
|
+
* @param at - 判定时刻(epoch ms)。
|
|
11267
|
+
* @returns `peak` / `offPeak`。
|
|
11268
|
+
*/
|
|
11269
|
+
function tierOf(facts, at) {
|
|
11270
|
+
const channel = facts.channel;
|
|
11271
|
+
if (channel === void 0) return tierAt(at);
|
|
11272
|
+
const rule = ruleOf(facts);
|
|
11273
|
+
if (rule !== void 0) return customTier(at, effectiveRule(channel.source, rule));
|
|
11274
|
+
if (OFFICIAL_SOURCE_RE.test(channel.source)) return tierAt(at);
|
|
11275
|
+
return customTier(at, effectiveRule(channel.source, {}));
|
|
11276
|
+
}
|
|
11277
|
+
/**
|
|
11278
|
+
* 该来源 × 模型距离下一次档位切换还有多久(毫秒)。
|
|
11279
|
+
*
|
|
11280
|
+
* 复用客户端同源的倒计时实现(`scheduledCountdown`)——它已按「自定义规则」
|
|
11281
|
+
* 算切换点(含周末与节假日例外),与面板里显示的倒计时是同一份逻辑,不会
|
|
11282
|
+
* 出现「面板说还有 5 分钟、队列说还有 1 小时」的分裂。
|
|
11283
|
+
*
|
|
11284
|
+
* @param facts - 判档事实。
|
|
11285
|
+
* @param at - 判定时刻(epoch ms)。
|
|
11286
|
+
* @returns 距下次切换的毫秒数;无未来切换点时为 `Infinity`。
|
|
11287
|
+
*/
|
|
11288
|
+
function nextSwitchMsOf(facts, at) {
|
|
11289
|
+
const channel = facts.channel;
|
|
11290
|
+
if (channel === void 0) return switchMsOf(scheduledCountdown(at, "deepseek-metered"));
|
|
11291
|
+
const rule = ruleOf(facts);
|
|
11292
|
+
if (rule !== void 0) return switchMsOf(scheduledCountdown(at, "deepseek-metered", effectiveRule(channel.source, rule)));
|
|
11293
|
+
if (OFFICIAL_SOURCE_RE.test(channel.source)) return switchMsOf(scheduledCountdown(at, "deepseek-metered"));
|
|
11294
|
+
return switchMsOf(scheduledCountdown(at, "deepseek-metered", effectiveRule(channel.source, {})));
|
|
11295
|
+
}
|
|
11296
|
+
/** 倒计时可能缺席(通道无窗口)——缺席时按「无切换点」处理(Infinity)。 */
|
|
11297
|
+
function switchMsOf(countdown) {
|
|
11298
|
+
return countdown?.nextSwitchInMs ?? Infinity;
|
|
11299
|
+
}
|
|
11300
|
+
//#endregion
|
|
9480
11301
|
//#region lib/types/task-queue.js
|
|
9481
11302
|
/**
|
|
9482
11303
|
* Durable off-peak FIFO task queue (issue #106, new-host capability preview).
|
|
@@ -9490,6 +11311,15 @@ const QUEUE_VERSION = 1;
|
|
|
9490
11311
|
const MAX_TASKS = 100;
|
|
9491
11312
|
const MAX_QUEUED = 50;
|
|
9492
11313
|
const MAX_PROMPT_LENGTH = 32e3;
|
|
11314
|
+
/** 会话 id 长度上限(宿主的 id 是 uuid;超长的入参一律当作没有来源会话)。 */
|
|
11315
|
+
const MAX_SESSION_ID_LENGTH = 200;
|
|
11316
|
+
/** 会话列表读面的超时(毫秒):拿不到就降级新建会话,不让队列卡住。 */
|
|
11317
|
+
const SESSION_LIST_TIMEOUT_MS = 1e4;
|
|
11318
|
+
/** 目录是否落在某个项目内(相等或为其子目录)。 */
|
|
11319
|
+
function isInsideDirectory(cwd, project) {
|
|
11320
|
+
if (project === "") return false;
|
|
11321
|
+
return cwd === project || cwd.startsWith(`${project}/`);
|
|
11322
|
+
}
|
|
9493
11323
|
const LOCK_WAIT_MS = 5e3;
|
|
9494
11324
|
const LEASE_MS = 45e3;
|
|
9495
11325
|
const HEARTBEAT_MS = 15e3;
|
|
@@ -9517,7 +11347,7 @@ function validStoredTask(value) {
|
|
|
9517
11347
|
"running",
|
|
9518
11348
|
"completed",
|
|
9519
11349
|
"failed"
|
|
9520
|
-
].includes(task.status ?? "") && (task.sessionId === void 0 || typeof task.sessionId === "string") && (task.owner === void 0 || typeof task.owner === "string") && (task.leaseUntil === void 0 || typeof task.leaseUntil === "number");
|
|
11350
|
+
].includes(task.status ?? "") && (task.sessionId === void 0 || typeof task.sessionId === "string") && (task.sourceSessionId === void 0 || typeof task.sourceSessionId === "string") && (task.reuseSource === void 0 || typeof task.reuseSource === "boolean") && (task.fallbackReason === void 0 || typeof task.fallbackReason === "string") && (task.owner === void 0 || typeof task.owner === "string") && (task.leaseUntil === void 0 || typeof task.leaseUntil === "number");
|
|
9521
11351
|
}
|
|
9522
11352
|
function publicTask(task) {
|
|
9523
11353
|
const { owner: _owner, leaseUntil: _leaseUntil, ...pub } = task;
|
|
@@ -9545,6 +11375,12 @@ var TaskQueueEngine = class {
|
|
|
9545
11375
|
taskAbort;
|
|
9546
11376
|
stopped = true;
|
|
9547
11377
|
pumping = false;
|
|
11378
|
+
/**
|
|
11379
|
+
* 模型目录缓存(issue #143)。
|
|
11380
|
+
*
|
|
11381
|
+
* 只缓存**目录事实**(候选清单与根因),**不缓存档位**——档位随时间变化,
|
|
11382
|
+
* 缓存 60 秒会让面板显示过期的「距高峰还有 N 分钟」。每次快照现算档位。
|
|
11383
|
+
*/
|
|
9548
11384
|
modelCache;
|
|
9549
11385
|
constructor(options) {
|
|
9550
11386
|
this.options = options;
|
|
@@ -9571,42 +11407,70 @@ var TaskQueueEngine = class {
|
|
|
9571
11407
|
this.taskAbort?.abort();
|
|
9572
11408
|
}
|
|
9573
11409
|
async snapshot(refreshModels = false) {
|
|
9574
|
-
const countdown = channelCountdown(this.now(), "deepseek-metered");
|
|
9575
11410
|
const controller = usableController(this.options.getController());
|
|
9576
11411
|
const base = {
|
|
9577
11412
|
supported: controller !== void 0,
|
|
9578
|
-
tier: tierAt(this.now()),
|
|
9579
|
-
nextSwitchInMs: countdown?.nextSwitchInMs ?? 0,
|
|
9580
11413
|
tasks: (await this.readDocument()).tasks.map(publicTask),
|
|
9581
11414
|
workspaces: this.options.getWorkspaces()
|
|
9582
11415
|
};
|
|
9583
11416
|
if (controller === void 0) return {
|
|
9584
11417
|
...base,
|
|
11418
|
+
...this.officialBand(),
|
|
9585
11419
|
models: []
|
|
9586
11420
|
};
|
|
9587
11421
|
try {
|
|
11422
|
+
const options = await this.modelOptions(controller, refreshModels);
|
|
9588
11423
|
return {
|
|
9589
11424
|
...base,
|
|
9590
|
-
...
|
|
11425
|
+
...this.bandOf(options),
|
|
11426
|
+
...options
|
|
9591
11427
|
};
|
|
9592
11428
|
} catch (error) {
|
|
9593
11429
|
return {
|
|
9594
11430
|
...base,
|
|
11431
|
+
...this.officialBand(),
|
|
9595
11432
|
models: [],
|
|
9596
11433
|
optionsError: messageOf(error)
|
|
9597
11434
|
};
|
|
9598
11435
|
}
|
|
9599
11436
|
}
|
|
9600
11437
|
async summary() {
|
|
9601
|
-
const countdown = channelCountdown(this.now(), "deepseek-metered");
|
|
9602
11438
|
const document = await this.readDocument();
|
|
9603
11439
|
return {
|
|
9604
11440
|
supported: usableController(this.options.getController()) !== void 0,
|
|
9605
|
-
|
|
9606
|
-
nextSwitchInMs: countdown?.nextSwitchInMs ?? 0,
|
|
11441
|
+
...this.bandOf(this.modelCache === void 0 ? void 0 : this.modelOptionsOf(this.modelCache)),
|
|
9607
11442
|
queuedCount: document.tasks.filter((task) => task.status === "queued").length
|
|
9608
11443
|
};
|
|
9609
11444
|
}
|
|
11445
|
+
/** 官方全局档位(无候选时的兜底口径,与旧行为逐字一致)。 */
|
|
11446
|
+
officialBand() {
|
|
11447
|
+
const countdown = channelCountdown(this.now(), "deepseek-metered");
|
|
11448
|
+
return {
|
|
11449
|
+
tier: tierAt(this.now()),
|
|
11450
|
+
nextSwitchInMs: countdown?.nextSwitchInMs ?? 0
|
|
11451
|
+
};
|
|
11452
|
+
}
|
|
11453
|
+
/**
|
|
11454
|
+
* 档位按**默认候选模型**判定(issue #143)。
|
|
11455
|
+
*
|
|
11456
|
+
* 候选为空 → 回落到官方全局档位(没有可判的来源);默认模型不在候选内
|
|
11457
|
+
* (宿主默认路由未配峰谷价)→ 用第一个候选。摘要接口不探测模型目录,
|
|
11458
|
+
* 因此复用已缓存的候选;缓存为空时同样回落到官方全局档位。
|
|
11459
|
+
*/
|
|
11460
|
+
bandOf(options) {
|
|
11461
|
+
const models = options?.models ?? [];
|
|
11462
|
+
if (models.length === 0) return this.officialBand();
|
|
11463
|
+
const defaultModel = options?.defaultModel;
|
|
11464
|
+
const selected = defaultModel !== void 0 && models.some((model) => model.provider === defaultModel.provider && model.id === defaultModel.model) ? defaultModel : {
|
|
11465
|
+
provider: models[0].provider,
|
|
11466
|
+
model: models[0].id
|
|
11467
|
+
};
|
|
11468
|
+
const now = this.now();
|
|
11469
|
+
return {
|
|
11470
|
+
tier: this.tierOfTask(selected.provider, selected.model, now),
|
|
11471
|
+
nextSwitchInMs: this.nextSwitchMsOfTask(selected.provider, selected.model, now)
|
|
11472
|
+
};
|
|
11473
|
+
}
|
|
9610
11474
|
async enqueue(input) {
|
|
9611
11475
|
await this.enqueueMany([input]);
|
|
9612
11476
|
}
|
|
@@ -9628,11 +11492,14 @@ var TaskQueueEngine = class {
|
|
|
9628
11492
|
if (!workspaces.some((workspace) => workspace.path === cwd)) throw new TaskQueueError("workspace is no longer available", 409);
|
|
9629
11493
|
if (typeof provider !== "string" || typeof model !== "string") throw new TaskQueueError("model is required");
|
|
9630
11494
|
if (!models.some((candidate) => candidate.provider === provider && candidate.id === model)) throw new TaskQueueError("select an available DeepSeek time-of-day model", 409);
|
|
11495
|
+
const sourceSessionId = typeof input.sourceSessionId === "string" && input.sourceSessionId.trim() !== "" && input.sourceSessionId.length <= MAX_SESSION_ID_LENGTH ? input.sourceSessionId : void 0;
|
|
9631
11496
|
return {
|
|
9632
11497
|
prompt,
|
|
9633
11498
|
cwd,
|
|
9634
11499
|
provider,
|
|
9635
|
-
model
|
|
11500
|
+
model,
|
|
11501
|
+
sourceSessionId,
|
|
11502
|
+
reuseSource: input.reuseSource === true && sourceSessionId !== void 0
|
|
9636
11503
|
};
|
|
9637
11504
|
} catch (error) {
|
|
9638
11505
|
if (inputs.length > 1 && error instanceof TaskQueueError) throw new TaskQueueError(`task ${String(index + 1)}: ${error.message}`, error.status);
|
|
@@ -9666,21 +11533,30 @@ var TaskQueueEngine = class {
|
|
|
9666
11533
|
});
|
|
9667
11534
|
}
|
|
9668
11535
|
async modelOptions(controller, refresh = false) {
|
|
9669
|
-
if (!refresh && this.modelCache !== void 0 && this.now() - this.modelCache.at < OPTIONS_CACHE_MS) return this.modelCache;
|
|
11536
|
+
if (!refresh && this.modelCache !== void 0 && this.now() - this.modelCache.at < OPTIONS_CACHE_MS) return this.modelOptionsOf(this.modelCache);
|
|
9670
11537
|
const catalog = await controller.modelCatalog();
|
|
9671
|
-
const
|
|
11538
|
+
const candidates = [];
|
|
11539
|
+
let officialRoute = false;
|
|
11540
|
+
let otherRouteWithPeakModel = false;
|
|
9672
11541
|
for (const group of catalog.groups) {
|
|
9673
|
-
|
|
11542
|
+
const channel = this.options.resolveRouteChannel?.(group.id);
|
|
11543
|
+
const official = group.id === DEEPSEEK_PLATFORM_ROUTE;
|
|
11544
|
+
if (official) officialRoute = true;
|
|
11545
|
+
if (!official && channel === void 0) continue;
|
|
9674
11546
|
for (const model of group.models) {
|
|
9675
11547
|
if (rateChannelOf(model.id, false) !== "deepseek-metered") continue;
|
|
9676
|
-
|
|
11548
|
+
if (!official) otherRouteWithPeakModel = true;
|
|
11549
|
+
if (!official && !this.hasPeakRule(channel.source, resolveCatalogKey(model.id))) continue;
|
|
11550
|
+
candidates.push({
|
|
9677
11551
|
provider: group.id,
|
|
9678
11552
|
providerName: group.name,
|
|
9679
11553
|
id: model.id,
|
|
9680
|
-
name: model.name
|
|
11554
|
+
name: model.name,
|
|
11555
|
+
saving: official ? "cash" : channel.saving
|
|
9681
11556
|
});
|
|
9682
11557
|
}
|
|
9683
11558
|
}
|
|
11559
|
+
const blockedReason = candidates.length > 0 ? void 0 : officialRoute && !otherRouteWithPeakModel ? "no-official-model" : otherRouteWithPeakModel ? "no-scheduled-model" : "no-official-route";
|
|
9684
11560
|
const candidate = catalog.default;
|
|
9685
11561
|
const defaultModel = candidate === void 0 ? void 0 : {
|
|
9686
11562
|
provider: candidate.provider,
|
|
@@ -9688,20 +11564,78 @@ var TaskQueueEngine = class {
|
|
|
9688
11564
|
};
|
|
9689
11565
|
this.modelCache = {
|
|
9690
11566
|
at: this.now(),
|
|
9691
|
-
|
|
9692
|
-
defaultModel
|
|
11567
|
+
candidates,
|
|
11568
|
+
defaultModel,
|
|
11569
|
+
blockedReason
|
|
9693
11570
|
};
|
|
11571
|
+
return this.modelOptionsOf(this.modelCache);
|
|
11572
|
+
}
|
|
11573
|
+
/** 缓存的目录事实 + 现算的档位 → 快照用的候选清单。 */
|
|
11574
|
+
modelOptionsOf(cache) {
|
|
9694
11575
|
return {
|
|
9695
|
-
models,
|
|
9696
|
-
defaultModel
|
|
11576
|
+
models: cache.candidates.map((entry) => this.decorateModel(entry)),
|
|
11577
|
+
defaultModel: cache.defaultModel,
|
|
11578
|
+
blockedReason: cache.blockedReason
|
|
9697
11579
|
};
|
|
9698
11580
|
}
|
|
11581
|
+
/**
|
|
11582
|
+
* 候选模型 + 它当前所处的档位(issue #143)。
|
|
11583
|
+
*
|
|
11584
|
+
* 档位按**该候选自己的来源**判定——不同来源可能同一时刻处于不同档位,
|
|
11585
|
+
* 逐候选给出,界面才能对所选模型说准话。
|
|
11586
|
+
*/
|
|
11587
|
+
decorateModel(entry) {
|
|
11588
|
+
const now = this.now();
|
|
11589
|
+
return {
|
|
11590
|
+
...entry,
|
|
11591
|
+
tier: this.tierOfTask(entry.provider, entry.id, now),
|
|
11592
|
+
nextSwitchInMs: this.nextSwitchMsOfTask(entry.provider, entry.id, now)
|
|
11593
|
+
};
|
|
11594
|
+
}
|
|
11595
|
+
/**
|
|
11596
|
+
* 用户是否为该来源 × 模型配了峰谷时段(issue #143)。
|
|
11597
|
+
*
|
|
11598
|
+
* 这是**用户显式声明「这个来源有峰谷分时」**的信号——与峰谷设置页同一份
|
|
11599
|
+
* 数据。订阅通道(如 `dsh-opencode-go`)的倍率表在厂商侧,插件无从探测;
|
|
11600
|
+
* 用户配了时段就说明他知道这个通道的分时规则,队列据此放行并按它排程。
|
|
11601
|
+
*
|
|
11602
|
+
* 注意判定键与峰谷设置页一致:`scheduleKey(source, 目录键)`——用**目录键**
|
|
11603
|
+
* (`resolveCatalogKey` 归一后)而非宿主原始模型 id,否则同一个模型在两处
|
|
11604
|
+
* 会对不上(#125 的同类坑)。
|
|
11605
|
+
*/
|
|
11606
|
+
hasPeakRule(source, catalogKey) {
|
|
11607
|
+
const schedule = this.options.resolvePeakSchedule?.();
|
|
11608
|
+
if (schedule === void 0) return false;
|
|
11609
|
+
return schedule.models[scheduleKey(source, catalogKey)] !== void 0;
|
|
11610
|
+
}
|
|
11611
|
+
/**
|
|
11612
|
+
* 某条路由 × 某个模型此刻处于哪一档(issue #143:按来源判档)。
|
|
11613
|
+
*
|
|
11614
|
+
* 用户为该来源 × 模型配了时段就用它;没配时官方来源走全局窗口(含中国
|
|
11615
|
+
* 节假日),订阅来源走厂商倍率窗口(不含中国节假日——订阅厂商的倍率表里
|
|
11616
|
+
* 没有这一项)。
|
|
11617
|
+
*/
|
|
11618
|
+
tierOfTask(provider, model, at) {
|
|
11619
|
+
return tierOf({
|
|
11620
|
+
channel: this.options.resolveRouteChannel?.(provider),
|
|
11621
|
+
schedule: this.options.resolvePeakSchedule?.(),
|
|
11622
|
+
catalogKey: resolveCatalogKey(model)
|
|
11623
|
+
}, at);
|
|
11624
|
+
}
|
|
11625
|
+
/** 某条路由 × 某个模型距下一次档位切换还有多久。 */
|
|
11626
|
+
nextSwitchMsOfTask(provider, model, at) {
|
|
11627
|
+
return nextSwitchMsOf({
|
|
11628
|
+
channel: this.options.resolveRouteChannel?.(provider),
|
|
11629
|
+
schedule: this.options.resolvePeakSchedule?.(),
|
|
11630
|
+
catalogKey: resolveCatalogKey(model)
|
|
11631
|
+
}, at);
|
|
11632
|
+
}
|
|
9699
11633
|
async pump() {
|
|
9700
11634
|
if (this.stopped || this.pumping) return;
|
|
9701
11635
|
this.pumping = true;
|
|
9702
11636
|
try {
|
|
9703
11637
|
await this.recoverExpired();
|
|
9704
|
-
if (this.stopped
|
|
11638
|
+
if (this.stopped) return;
|
|
9705
11639
|
if (usableController(this.options.getController()) === void 0) return;
|
|
9706
11640
|
const task = await this.claimNext();
|
|
9707
11641
|
if (task !== void 0) await this.execute(task);
|
|
@@ -9711,10 +11645,20 @@ var TaskQueueEngine = class {
|
|
|
9711
11645
|
this.pumping = false;
|
|
9712
11646
|
}
|
|
9713
11647
|
}
|
|
11648
|
+
/**
|
|
11649
|
+
* 领取下一个可执行的任务(issue #143:按来源判档)。
|
|
11650
|
+
*
|
|
11651
|
+
* 档位闸门落在**任务自己**的来源 × 模型上,而不是全局单一窗口——不同来源
|
|
11652
|
+
* 可能同一时刻处于不同档位(订阅通道的倍率窗口与官方窗口不一定重合),
|
|
11653
|
+
* 逐任务判定才能让「现在能跑的那一路」先跑。全局闸门会让所有任务一起等。
|
|
11654
|
+
*
|
|
11655
|
+
* FIFO 语义保持不变:按入队顺序找**第一个**当前处于低谷的任务。
|
|
11656
|
+
*/
|
|
9714
11657
|
async claimNext() {
|
|
9715
11658
|
let claimed;
|
|
11659
|
+
const now = this.now();
|
|
9716
11660
|
await this.update((tasks) => {
|
|
9717
|
-
const task = tasks.find((candidate) => candidate.status === "queued");
|
|
11661
|
+
const task = tasks.find((candidate) => candidate.status === "queued" && this.tierOfTask(candidate.provider, candidate.model, now) === "offPeak");
|
|
9718
11662
|
if (task === void 0) return;
|
|
9719
11663
|
const next = {
|
|
9720
11664
|
...task,
|
|
@@ -9763,20 +11707,30 @@ var TaskQueueEngine = class {
|
|
|
9763
11707
|
this.heartbeat = heartbeat;
|
|
9764
11708
|
try {
|
|
9765
11709
|
if (!this.options.getWorkspaces().some((workspace) => workspace.path === claimed.cwd)) throw new TaskQueueError("workspace is no longer available", 409);
|
|
9766
|
-
if (
|
|
11710
|
+
if (this.tierOfTask(claimed.provider, claimed.model, this.now()) !== "offPeak") {
|
|
9767
11711
|
await this.requeue(claimed.id);
|
|
9768
11712
|
return;
|
|
9769
11713
|
}
|
|
9770
|
-
const
|
|
9771
|
-
|
|
9772
|
-
|
|
9773
|
-
|
|
9774
|
-
|
|
11714
|
+
const reuse = await this.resolveSourceSession(claimed, controller);
|
|
11715
|
+
let sessionId;
|
|
11716
|
+
if (reuse.ok) sessionId = reuse.sessionId;
|
|
11717
|
+
else {
|
|
11718
|
+
if (reuse.reason !== void 0) {
|
|
11719
|
+
if (!await this.patch(claimed.id, { fallbackReason: reuse.reason })) return;
|
|
11720
|
+
}
|
|
11721
|
+
const { models: availableModels } = await this.modelOptions(controller, true);
|
|
11722
|
+
if (!availableModels.some((model) => model.provider === claimed.provider && model.id === claimed.model)) throw new TaskQueueError("the selected DeepSeek model is no longer available", 409);
|
|
11723
|
+
sessionId = (await this.createGroupedSession(controller, claimed.cwd)).sessionId;
|
|
11724
|
+
}
|
|
11725
|
+
const sessionPatch = { sessionId };
|
|
11726
|
+
if (reuse.ok) sessionPatch.fallbackReason = void 0;
|
|
11727
|
+
if (!await this.patch(claimed.id, sessionPatch)) return;
|
|
11728
|
+
if (!reuse.ok) await controller.selectModel({
|
|
9775
11729
|
sessionId,
|
|
9776
11730
|
provider: claimed.provider,
|
|
9777
11731
|
model: claimed.model
|
|
9778
11732
|
});
|
|
9779
|
-
if (
|
|
11733
|
+
if (this.tierOfTask(claimed.provider, claimed.model, this.now()) !== "offPeak") {
|
|
9780
11734
|
await this.requeue(claimed.id);
|
|
9781
11735
|
return;
|
|
9782
11736
|
}
|
|
@@ -9810,6 +11764,74 @@ var TaskQueueEngine = class {
|
|
|
9810
11764
|
this.taskAbort = void 0;
|
|
9811
11765
|
}
|
|
9812
11766
|
}
|
|
11767
|
+
/**
|
|
11768
|
+
* issue #118:判断来源会话能否续跑。不能就给出降级原因(写进卡片)。
|
|
11769
|
+
*
|
|
11770
|
+
* 判据来自 issue 的安全边界:来源会话已删除 / 正在跑别的轮次 / 工作区变了时,
|
|
11771
|
+
* 回退为新建会话,不要往用户正在使用的会话里硬塞一轮。另外子智能体会话与
|
|
11772
|
+
* 归档会话也不能复用——前者归属子智能体路由,后者轮次会以 blocked 结束、
|
|
11773
|
+
* 看起来跑了其实没跑。
|
|
11774
|
+
*/
|
|
11775
|
+
async resolveSourceSession(claimed, controller) {
|
|
11776
|
+
if (claimed.reuseSource !== true) return { ok: false };
|
|
11777
|
+
const sourceSessionId = claimed.sourceSessionId;
|
|
11778
|
+
if (sourceSessionId === void 0) return { ok: false };
|
|
11779
|
+
const list = controller.list;
|
|
11780
|
+
if (typeof list !== "function") return {
|
|
11781
|
+
ok: false,
|
|
11782
|
+
reason: "this host cannot inspect Sessions"
|
|
11783
|
+
};
|
|
11784
|
+
let items;
|
|
11785
|
+
try {
|
|
11786
|
+
items = (await list.call(controller, {}, AbortSignal.timeout(SESSION_LIST_TIMEOUT_MS)))?.items ?? [];
|
|
11787
|
+
} catch (error) {
|
|
11788
|
+
return {
|
|
11789
|
+
ok: false,
|
|
11790
|
+
reason: `source session lookup failed: ${messageOf(error)}`
|
|
11791
|
+
};
|
|
11792
|
+
}
|
|
11793
|
+
const summary = items.find((item) => item.sessionId === sourceSessionId);
|
|
11794
|
+
if (summary === void 0) return {
|
|
11795
|
+
ok: false,
|
|
11796
|
+
reason: "source session no longer exists"
|
|
11797
|
+
};
|
|
11798
|
+
if (summary.origin === "subagent") return {
|
|
11799
|
+
ok: false,
|
|
11800
|
+
reason: "source session belongs to a subagent"
|
|
11801
|
+
};
|
|
11802
|
+
const archived = this.options.getWorkspaceContext?.()?.archivedSessionIds;
|
|
11803
|
+
if (archived !== void 0 && archived.includes(sourceSessionId)) return {
|
|
11804
|
+
ok: false,
|
|
11805
|
+
reason: "source session is archived"
|
|
11806
|
+
};
|
|
11807
|
+
if (summary.running === true) return {
|
|
11808
|
+
ok: false,
|
|
11809
|
+
reason: "source session is busy"
|
|
11810
|
+
};
|
|
11811
|
+
const project = typeof summary.cwd === "string" ? summary.cwd : void 0;
|
|
11812
|
+
if (project !== void 0 && !isInsideDirectory(claimed.cwd, project)) return {
|
|
11813
|
+
ok: false,
|
|
11814
|
+
reason: "source session working directory changed"
|
|
11815
|
+
};
|
|
11816
|
+
return {
|
|
11817
|
+
ok: true,
|
|
11818
|
+
sessionId: sourceSessionId
|
|
11819
|
+
};
|
|
11820
|
+
}
|
|
11821
|
+
/**
|
|
11822
|
+
* 新建会话:cwd 恰好等于某个工作区时用 create({ workspaceId }),让宿主把会话挂进
|
|
11823
|
+
* 该工作区——create({ cwd }) 从不归组,这正是队列会话在侧栏里没有分组的原因。
|
|
11824
|
+
* 两者互斥:带 workspaceId 时不能再带 cwd。
|
|
11825
|
+
*/
|
|
11826
|
+
async createGroupedSession(controller, cwd) {
|
|
11827
|
+
const workspaceId = this.options.getWorkspaceContext?.()?.workspaceIdOfPath(cwd);
|
|
11828
|
+
if (workspaceId !== void 0) try {
|
|
11829
|
+
return await controller.create({ workspaceId });
|
|
11830
|
+
} catch (error) {
|
|
11831
|
+
console.warn("[usage-billing] task queue workspace Session creation failed:", error);
|
|
11832
|
+
}
|
|
11833
|
+
return await controller.create({ cwd });
|
|
11834
|
+
}
|
|
9813
11835
|
async watch(frames, requestId) {
|
|
9814
11836
|
let admitted = false;
|
|
9815
11837
|
for await (const raw of frames) {
|
|
@@ -9847,7 +11869,8 @@ var TaskQueueEngine = class {
|
|
|
9847
11869
|
owner: void 0,
|
|
9848
11870
|
leaseUntil: void 0,
|
|
9849
11871
|
startedAt: void 0,
|
|
9850
|
-
sessionId: void 0
|
|
11872
|
+
sessionId: void 0,
|
|
11873
|
+
fallbackReason: void 0
|
|
9851
11874
|
});
|
|
9852
11875
|
}
|
|
9853
11876
|
async finish(id, status, error) {
|
|
@@ -9946,6 +11969,7 @@ function registerTaskQueueRoute(ctx, deps) {
|
|
|
9946
11969
|
ctx.effect(() => ctx.webServer.register({
|
|
9947
11970
|
kind: "exact",
|
|
9948
11971
|
path: "/api/billing/task-queue",
|
|
11972
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
9949
11973
|
handler: async (req, res) => {
|
|
9950
11974
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
9951
11975
|
if (req.method !== "GET" && req.method !== "POST") {
|
|
@@ -9953,7 +11977,7 @@ function registerTaskQueueRoute(ctx, deps) {
|
|
|
9953
11977
|
return;
|
|
9954
11978
|
}
|
|
9955
11979
|
if (req.method === "POST") {
|
|
9956
|
-
if (!isLoopbackOrigin(req.headers.origin)) {
|
|
11980
|
+
if (!isLoopbackOrigin(req.headers.origin, deps.trustedHosts)) {
|
|
9957
11981
|
send(res, 403, { error: "forbidden: loopback only" });
|
|
9958
11982
|
return;
|
|
9959
11983
|
}
|
|
@@ -10018,6 +12042,7 @@ function registerTaskQueueRoute(ctx, deps) {
|
|
|
10018
12042
|
ctx.effect(() => ctx.webServer.register({
|
|
10019
12043
|
kind: "exact",
|
|
10020
12044
|
path: "/api/billing/task-queue-summary",
|
|
12045
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
10021
12046
|
handler: async (req, res) => {
|
|
10022
12047
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
10023
12048
|
if (req.method !== "GET") {
|
|
@@ -10126,8 +12151,8 @@ const QUOTA_RESPONSE_BUDGET_MS = 8e3;
|
|
|
10126
12151
|
* 取 5 分钟:与 usage-stats 的 30s 轮询 + 5 分钟快照节流同一量级。
|
|
10127
12152
|
*/
|
|
10128
12153
|
const RECONCILE_BASIS_MAX_AGE_MS = 3e5;
|
|
10129
|
-
/** DeepSeek
|
|
10130
|
-
const DEFAULT_BALANCE_API_KEY_ENV =
|
|
12154
|
+
/** DeepSeek 余额查询的默认凭据引用(与宿主内置平台通道的默认引用一致)。 */
|
|
12155
|
+
const DEFAULT_BALANCE_API_KEY_ENV = DEEPSEEK_PLATFORM_KEY_REF;
|
|
10131
12156
|
/**
|
|
10132
12157
|
* 本插件版本号:从包自身的 package.json 读取(单一来源),随 usage-stats
|
|
10133
12158
|
* 下发,供「设置 → 插件信息卡」展示。发布版 lib/index.js 相对包根解析。
|
|
@@ -10266,6 +12291,18 @@ async function readPiAiProviders(settings) {
|
|
|
10266
12291
|
return {};
|
|
10267
12292
|
}
|
|
10268
12293
|
}
|
|
12294
|
+
/** Site buckets drop the route ID, so a site match needs a unique configured route. */
|
|
12295
|
+
function uniqueSiteOrigins(providers) {
|
|
12296
|
+
const owners = /* @__PURE__ */ new Map();
|
|
12297
|
+
for (const [route, { baseURL }] of Object.entries(providers)) {
|
|
12298
|
+
if (!baseURL) continue;
|
|
12299
|
+
const origin = siteOriginOf(baseURL);
|
|
12300
|
+
owners.set(origin, owners.has(origin) ? void 0 : route);
|
|
12301
|
+
}
|
|
12302
|
+
const origins = /* @__PURE__ */ new Map();
|
|
12303
|
+
for (const [origin, route] of owners) if (route !== void 0) origins.set(route, origin);
|
|
12304
|
+
return origins;
|
|
12305
|
+
}
|
|
10269
12306
|
/** 同步读取 provider 路由的 baseURL 视图(中转站零配置发现来源)。
|
|
10270
12307
|
* `settings.describe` 是同步调用,聚合器每次折叠取最新站点映射,无需缓存/过期。
|
|
10271
12308
|
* 注意:返回**全部可读路由**(baseURL 可选),聚合层据此区分「路由存在但无
|
|
@@ -10274,13 +12311,20 @@ async function readPiAiProviders(settings) {
|
|
|
10274
12311
|
* @returns `<route> → { baseURL? }`;命名空间不可读时返回空。
|
|
10275
12312
|
*/
|
|
10276
12313
|
function readPiAiProviderRoutes(settings) {
|
|
12314
|
+
return Object.fromEntries(Object.entries(readScheduleProfiles(settings)).map(([id, { baseURL }]) => [id, baseURL === void 0 ? {} : { baseURL }]));
|
|
12315
|
+
}
|
|
12316
|
+
function readScheduleProfiles(settings) {
|
|
10277
12317
|
try {
|
|
10278
12318
|
const providers = (settings.describe({ redactSecrets: true }).find((descriptor) => descriptor.ns === "llm-pi-ai")?.value)?.providers;
|
|
10279
|
-
const out =
|
|
12319
|
+
const out = Object.create(null);
|
|
10280
12320
|
for (const [route, entry] of Object.entries(providers ?? {})) {
|
|
10281
12321
|
if (entry === null || typeof entry !== "object") continue;
|
|
10282
12322
|
const baseURL = entry.baseURL;
|
|
10283
|
-
out[route] =
|
|
12323
|
+
out[route] = {
|
|
12324
|
+
...typeof baseURL === "string" && baseURL !== "" ? { baseURL } : {},
|
|
12325
|
+
...typeof entry.displayName === "string" ? { displayName: entry.displayName } : {},
|
|
12326
|
+
...Array.isArray(entry.models) ? { models: entry.models } : {}
|
|
12327
|
+
};
|
|
10284
12328
|
}
|
|
10285
12329
|
return out;
|
|
10286
12330
|
} catch {
|
|
@@ -10541,7 +12585,7 @@ function apply(ctx, config = {}) {
|
|
|
10541
12585
|
const ledgerStore = createFileUsageLedgerStore(config.ledgerPath ?? join(dshHome, ".dsh-usage-ledger.json"));
|
|
10542
12586
|
const reconcilePath = config.reconcilePath ?? join(dshHome, ".dsh-usage-reconcile.json");
|
|
10543
12587
|
let reconcileRef = null;
|
|
10544
|
-
(async () => {
|
|
12588
|
+
const reconcileLoaded = (async () => {
|
|
10545
12589
|
try {
|
|
10546
12590
|
const ref = JSON.parse(await readFile(reconcilePath, "utf8")).ref;
|
|
10547
12591
|
if (ref !== null && typeof ref === "object") {
|
|
@@ -10552,13 +12596,19 @@ function apply(ctx, config = {}) {
|
|
|
10552
12596
|
swallowed("reconcile-ref-missing");
|
|
10553
12597
|
}
|
|
10554
12598
|
})();
|
|
10555
|
-
|
|
10556
|
-
|
|
10557
|
-
|
|
10558
|
-
|
|
10559
|
-
|
|
10560
|
-
|
|
10561
|
-
|
|
12599
|
+
let persistence = Promise.resolve();
|
|
12600
|
+
const setReconcileRef = (next) => {
|
|
12601
|
+
if (next !== reconcileRef) {
|
|
12602
|
+
reconcileRef = next;
|
|
12603
|
+
const payload = JSON.stringify({ ref: next });
|
|
12604
|
+
persistence = persistence.then(() => writeFileAtomic(reconcilePath, payload, {
|
|
12605
|
+
mode: 384,
|
|
12606
|
+
dirMode: 448
|
|
12607
|
+
})).catch(() => {
|
|
12608
|
+
swallowed("reconcile-write-failed");
|
|
12609
|
+
});
|
|
12610
|
+
}
|
|
12611
|
+
return persistence;
|
|
10562
12612
|
};
|
|
10563
12613
|
const workspaceTitleResolver = buildWorkspaceTitleResolver(ctx);
|
|
10564
12614
|
const sessionTitleResolver = buildSessionTitleResolver(ctx);
|
|
@@ -10588,8 +12638,56 @@ function apply(ctx, config = {}) {
|
|
|
10588
12638
|
swallowed("minimax-plan-classify-failed", error);
|
|
10589
12639
|
}
|
|
10590
12640
|
};
|
|
12641
|
+
const schedules = openScheduleStore(config.peakSchedulePath ?? join(dshHome, ".dsh-usage-peak-schedule.json"), eligibleScheduleModel);
|
|
12642
|
+
const discoverScheduleModels = createScheduleModelDiscovery();
|
|
12643
|
+
const configuredScheduleModels = async () => {
|
|
12644
|
+
const llm = ctx.get?.("llm");
|
|
12645
|
+
return discoverScheduleModels(llm, readScheduleProfiles(ctx.settings), config.routeAliases ?? {});
|
|
12646
|
+
};
|
|
12647
|
+
const scheduleSnapshot = (discovery) => {
|
|
12648
|
+
const config = schedules.current();
|
|
12649
|
+
const models = new Map(discovery.models.map((row) => [scheduleKey(row.source, row.model), row]));
|
|
12650
|
+
for (const key of Object.keys(config.models)) {
|
|
12651
|
+
if (models.has(key)) continue;
|
|
12652
|
+
const [source, model] = JSON.parse(key);
|
|
12653
|
+
models.set(key, {
|
|
12654
|
+
source,
|
|
12655
|
+
model,
|
|
12656
|
+
label: `${source} / ${model}`
|
|
12657
|
+
});
|
|
12658
|
+
}
|
|
12659
|
+
const notices = [...schedules.notices(), ...discovery.notices];
|
|
12660
|
+
const effectiveFromMs = schedules.history().revisions.at(-1)?.effectiveFromMs;
|
|
12661
|
+
return {
|
|
12662
|
+
config,
|
|
12663
|
+
...effectiveFromMs !== void 0 && { effectiveFromMs },
|
|
12664
|
+
models: [...models.values()],
|
|
12665
|
+
...notices.length ? { notices } : {}
|
|
12666
|
+
};
|
|
12667
|
+
};
|
|
12668
|
+
registerPeakScheduleRoute(ctx, {
|
|
12669
|
+
trustedHosts,
|
|
12670
|
+
read: async () => scheduleSnapshot(await configuredScheduleModels()),
|
|
12671
|
+
save: async (raw) => {
|
|
12672
|
+
const discovery = await configuredScheduleModels();
|
|
12673
|
+
const allowed = new Set(discovery.models.map((row) => scheduleKey(row.source, row.model)));
|
|
12674
|
+
let batch;
|
|
12675
|
+
try {
|
|
12676
|
+
batch = partitionScheduleEdit(raw, (key, model) => allowed.has(key) && eligibleScheduleModel(model));
|
|
12677
|
+
} catch {
|
|
12678
|
+
throw new PeakScheduleInputError("invalidSchedule");
|
|
12679
|
+
}
|
|
12680
|
+
if (Object.keys(batch.edit.changes).length) await aggregator.withPeakScheduleChange((latestEventTime) => schedules.save(batch.edit, latestEventTime));
|
|
12681
|
+
return {
|
|
12682
|
+
...scheduleSnapshot(discovery),
|
|
12683
|
+
results: batch.results
|
|
12684
|
+
};
|
|
12685
|
+
}
|
|
12686
|
+
});
|
|
10591
12687
|
const replayDelayMs = readReplayDelayMs(config.replayDelayMs);
|
|
10592
12688
|
const aggregator = createUsageAggregator(adaptSessionPersistence(ctx.sessionPersistence), {
|
|
12689
|
+
resolvePeakSchedule: schedules.current,
|
|
12690
|
+
resolvePeakHistory: schedules.history,
|
|
10593
12691
|
subscriptionMatcher: subscriptionRoutes,
|
|
10594
12692
|
...config.routeAliases === void 0 ? {} : { routeAliases: config.routeAliases },
|
|
10595
12693
|
resolveRoutes: () => readPiAiProviderRoutes(ctx.settings),
|
|
@@ -10627,7 +12725,8 @@ function apply(ctx, config = {}) {
|
|
|
10627
12725
|
const now = Date.now();
|
|
10628
12726
|
if (now - lastSnapshotAt < SNAPSHOT_INTERVAL_MS) return;
|
|
10629
12727
|
lastSnapshotAt = now;
|
|
10630
|
-
const
|
|
12728
|
+
const { sessionListError: _liveError, ...data } = doc;
|
|
12729
|
+
const payload = JSON.stringify(data);
|
|
10631
12730
|
(async () => {
|
|
10632
12731
|
try {
|
|
10633
12732
|
const existing = await readFile(snapshotPath, "utf8");
|
|
@@ -10663,6 +12762,24 @@ function apply(ctx, config = {}) {
|
|
|
10663
12762
|
});
|
|
10664
12763
|
const taskQueue = new TaskQueueEngine({
|
|
10665
12764
|
filePath: config.taskQueuePath ?? join(dshHome, ".dsh-usage-task-queue.json"),
|
|
12765
|
+
resolveRouteChannel: (route) => {
|
|
12766
|
+
if (route === "deepseek-official") return {
|
|
12767
|
+
source: `direct:${route}`,
|
|
12768
|
+
saving: "cash"
|
|
12769
|
+
};
|
|
12770
|
+
const subscription = subscriptionRoutes.has(route);
|
|
12771
|
+
const source = siteBucketKey(siteRefOf(route, readPiAiProviderRoutes(ctx.settings), { subscription }));
|
|
12772
|
+
if (source === "unknown") return void 0;
|
|
12773
|
+
if (subscription) return {
|
|
12774
|
+
source,
|
|
12775
|
+
saving: "quota"
|
|
12776
|
+
};
|
|
12777
|
+
return {
|
|
12778
|
+
source,
|
|
12779
|
+
saving: source.startsWith("site:") ? "cash" : "schedule"
|
|
12780
|
+
};
|
|
12781
|
+
},
|
|
12782
|
+
resolvePeakSchedule: schedules.current,
|
|
10666
12783
|
getController: () => {
|
|
10667
12784
|
try {
|
|
10668
12785
|
return ctx.get("sessionController");
|
|
@@ -10679,6 +12796,20 @@ function apply(ctx, config = {}) {
|
|
|
10679
12796
|
} catch {
|
|
10680
12797
|
return [];
|
|
10681
12798
|
}
|
|
12799
|
+
},
|
|
12800
|
+
getWorkspaceContext: () => {
|
|
12801
|
+
try {
|
|
12802
|
+
const registry = ctx.get("workspaceRegistry");
|
|
12803
|
+
if (registry === void 0) return void 0;
|
|
12804
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
12805
|
+
for (const workspace of registry.list?.() ?? []) if (typeof workspace.path === "string" && workspace.path !== "" && typeof workspace.id === "string") byPath.set(workspace.path, workspace.id);
|
|
12806
|
+
return {
|
|
12807
|
+
archivedSessionIds: registry.archivedSessionIds ?? [],
|
|
12808
|
+
workspaceIdOfPath: (path) => byPath.get(path)
|
|
12809
|
+
};
|
|
12810
|
+
} catch {
|
|
12811
|
+
return;
|
|
12812
|
+
}
|
|
10682
12813
|
}
|
|
10683
12814
|
});
|
|
10684
12815
|
registerTaskQueueRoute(ctx, {
|
|
@@ -10889,17 +13020,23 @@ function apply(ctx, config = {}) {
|
|
|
10889
13020
|
clearInterval(timer);
|
|
10890
13021
|
};
|
|
10891
13022
|
}, "usage-billing: pricing refresh timer");
|
|
13023
|
+
registerPricingModelsRoute(ctx, trustedHosts);
|
|
10892
13024
|
registerPricingRoutes(ctx, {
|
|
10893
13025
|
trustedHosts,
|
|
10894
13026
|
body: pricingBody,
|
|
10895
13027
|
refresh: refreshPricing
|
|
10896
13028
|
});
|
|
10897
|
-
|
|
13029
|
+
const headless = {
|
|
10898
13030
|
at: 0,
|
|
10899
13031
|
doc: { balances: [] }
|
|
10900
13032
|
};
|
|
10901
|
-
|
|
10902
|
-
|
|
13033
|
+
const ui = {
|
|
13034
|
+
at: 0,
|
|
13035
|
+
doc: { balances: [] }
|
|
13036
|
+
};
|
|
13037
|
+
const balanceSlot = (client) => client === void 0 ? headless : ui;
|
|
13038
|
+
let refreshSequence = 0;
|
|
13039
|
+
const refreshBalance = async (sequence, client) => {
|
|
10903
13040
|
const piProviders = await readPiAiProviders(ctx.settings);
|
|
10904
13041
|
const providers = { ...piProviders };
|
|
10905
13042
|
const deepseekKey = providers["deepseek"]?.apiKeyEnv;
|
|
@@ -10907,7 +13044,7 @@ function apply(ctx, config = {}) {
|
|
|
10907
13044
|
...providers["deepseek"],
|
|
10908
13045
|
apiKeyEnv: config.balanceApiKeyEnv ?? DEFAULT_BALANCE_API_KEY_ENV
|
|
10909
13046
|
};
|
|
10910
|
-
const balances = await queryBalances(ctx, providers);
|
|
13047
|
+
const balances = await queryBalances(ctx, providers, client, config.balanceApiKeyEnv === void 0 ? void 0 : { extraKeyRefs: { [DEEPSEEK_PLATFORM_ROUTE]: [config.balanceApiKeyEnv] } });
|
|
10911
13048
|
const custom = await queryCustomBalances(ctx, config.customBalances ?? []);
|
|
10912
13049
|
const declared = await queryDeclaredEndpoints(ctx, piProviders, config.declaredEndpoints ?? []);
|
|
10913
13050
|
for (const row of [
|
|
@@ -10915,30 +13052,33 @@ function apply(ctx, config = {}) {
|
|
|
10915
13052
|
...custom,
|
|
10916
13053
|
...declared
|
|
10917
13054
|
]) if (row.error === "unauthorized") warnAuthOnce("balance", row.provider, row.displayName);
|
|
10918
|
-
const official = balances.find((row) => row.
|
|
13055
|
+
const official = balances.find((row) => row.sourceRoute === "deepseek" && row.walletKind === "api-key");
|
|
13056
|
+
const account = balances.find((row) => row.walletKind === "account");
|
|
13057
|
+
const now = Date.now();
|
|
13058
|
+
const today = dayStamp(now);
|
|
13059
|
+
const recent = aggregator.lastDocOf();
|
|
10919
13060
|
let reconcile;
|
|
10920
|
-
|
|
10921
|
-
if (
|
|
10922
|
-
const
|
|
10923
|
-
|
|
10924
|
-
|
|
10925
|
-
|
|
10926
|
-
|
|
10927
|
-
|
|
10928
|
-
|
|
10929
|
-
|
|
10930
|
-
|
|
13061
|
+
await reconcileLoaded;
|
|
13062
|
+
if (sequence === refreshSequence) {
|
|
13063
|
+
const fresh = recent !== void 0 && now - recent.updatedAt <= RECONCILE_BASIS_MAX_AGE_MS;
|
|
13064
|
+
if (!fresh) aggregator.aggregate().catch(() => {
|
|
13065
|
+
swallowed("reconcile-basis-stale");
|
|
13066
|
+
});
|
|
13067
|
+
const apiOnly = account?.accountState === "no-service" || account?.accountState === "signed-out";
|
|
13068
|
+
const cost = fresh ? platformSpend(recent, today, piProviders, apiOnly) : void 0;
|
|
13069
|
+
const source = official && apiBalanceSource(official);
|
|
13070
|
+
if (source !== void 0 && official?.error === void 0 && official?.isAvailable !== false && official?.currency === "CNY" && cost !== void 0) {
|
|
13071
|
+
const result = reconcileBalanceDelta(reconcileRef, official, cost, today, now, `${source}:${apiOnly ? "direct" : "site"}`);
|
|
13072
|
+
if (result.event && result.event.kind !== "flat") reconcile = {
|
|
10931
13073
|
...result.event,
|
|
10932
13074
|
provider: official.displayName,
|
|
10933
|
-
|
|
13075
|
+
currency: official.currency
|
|
10934
13076
|
};
|
|
10935
|
-
|
|
10936
|
-
} else
|
|
10937
|
-
aggregator.aggregate().catch(() => {});
|
|
10938
|
-
swallowed("reconcile-basis-stale");
|
|
10939
|
-
}
|
|
13077
|
+
await setReconcileRef(result.ref);
|
|
13078
|
+
} else await setReconcileRef(null);
|
|
10940
13079
|
}
|
|
10941
|
-
const
|
|
13080
|
+
const slot = balanceSlot(client);
|
|
13081
|
+
slot.doc = {
|
|
10942
13082
|
balances: [
|
|
10943
13083
|
...balances,
|
|
10944
13084
|
...custom,
|
|
@@ -10946,20 +13086,25 @@ function apply(ctx, config = {}) {
|
|
|
10946
13086
|
],
|
|
10947
13087
|
...reconcile === void 0 ? {} : { reconcile }
|
|
10948
13088
|
};
|
|
10949
|
-
|
|
10950
|
-
at: Date.now(),
|
|
10951
|
-
doc
|
|
10952
|
-
};
|
|
13089
|
+
slot.at = Date.now();
|
|
10953
13090
|
};
|
|
10954
|
-
const refreshBalanceOnce = () => {
|
|
10955
|
-
|
|
10956
|
-
|
|
10957
|
-
|
|
10958
|
-
|
|
13091
|
+
const refreshBalanceOnce = (client) => {
|
|
13092
|
+
const slot = balanceSlot(client);
|
|
13093
|
+
if (!slot.inflight) {
|
|
13094
|
+
const sequence = ++refreshSequence;
|
|
13095
|
+
slot.inflight = refreshBalance(sequence, client).catch(async (error) => {
|
|
13096
|
+
await reconcileLoaded;
|
|
13097
|
+
if (sequence === refreshSequence) await setReconcileRef(null);
|
|
13098
|
+
throw error;
|
|
13099
|
+
}).finally(() => {
|
|
13100
|
+
delete slot.inflight;
|
|
13101
|
+
});
|
|
13102
|
+
}
|
|
13103
|
+
return slot.inflight;
|
|
10959
13104
|
};
|
|
10960
13105
|
registerBalanceRoute(ctx, {
|
|
10961
13106
|
trustedHosts,
|
|
10962
|
-
cached:
|
|
13107
|
+
cached: balanceSlot,
|
|
10963
13108
|
refreshOnce: refreshBalanceOnce,
|
|
10964
13109
|
cacheMs: BALANCE_CACHE_MS,
|
|
10965
13110
|
responseBudgetMs: BALANCE_RESPONSE_BUDGET_MS
|
|
@@ -10982,29 +13127,38 @@ function apply(ctx, config = {}) {
|
|
|
10982
13127
|
await refreshMiniMaxPlanRoutes();
|
|
10983
13128
|
const { keys, identified } = await resolveSubscriptionKeys(ctx.settings, ctx.credentials);
|
|
10984
13129
|
const piProviders = await readPiAiProviders(ctx.settings);
|
|
10985
|
-
const
|
|
13130
|
+
const queried = await collectSubscriptions(keys, identified.filter((item) => item.adapter).map((item) => {
|
|
10986
13131
|
const baseURL = piProviders[item.provider]?.baseURL;
|
|
10987
13132
|
return {
|
|
10988
13133
|
provider: item.provider,
|
|
10989
13134
|
...item.region === void 0 ? {} : { region: item.region },
|
|
10990
13135
|
...typeof baseURL === "string" && baseURL !== "" ? { baseUrl: baseURL } : {}
|
|
10991
13136
|
};
|
|
10992
|
-
}))
|
|
13137
|
+
}));
|
|
13138
|
+
const origins = uniqueSiteOrigins(piProviders);
|
|
13139
|
+
const rows = [...queried].map((row) => {
|
|
10993
13140
|
const planType = planTypeOf(row.provider);
|
|
10994
13141
|
const subscriptionAmount = subscriptionFeeCnyOf(row.provider, live.rate);
|
|
13142
|
+
const origin = origins.get(row.provider);
|
|
10995
13143
|
return {
|
|
10996
13144
|
...row,
|
|
13145
|
+
...origin === void 0 ? {} : { origin },
|
|
10997
13146
|
planType,
|
|
10998
13147
|
...planType === "code" && subscriptionAmount > 0 ? { subscriptionAmount } : {}
|
|
10999
13148
|
};
|
|
11000
13149
|
});
|
|
11001
|
-
for (const item of identified)
|
|
11002
|
-
|
|
11003
|
-
|
|
11004
|
-
|
|
11005
|
-
|
|
11006
|
-
|
|
11007
|
-
|
|
13150
|
+
for (const item of identified) {
|
|
13151
|
+
if (item.adapter) continue;
|
|
13152
|
+
const origin = origins.get(item.provider);
|
|
13153
|
+
rows.push({
|
|
13154
|
+
provider: item.provider,
|
|
13155
|
+
displayName: item.displayName,
|
|
13156
|
+
status: "ok",
|
|
13157
|
+
windows: [],
|
|
13158
|
+
planType: planTypeOf(item.provider),
|
|
13159
|
+
...origin === void 0 ? {} : { origin }
|
|
13160
|
+
});
|
|
13161
|
+
}
|
|
11008
13162
|
for (const row of rows) if (row.status === "unauthorized") warnAuthOnce("subscription", row.provider, row.displayName);
|
|
11009
13163
|
quotaCache = {
|
|
11010
13164
|
at: Date.now(),
|
|
@@ -11046,9 +13200,14 @@ function apply(ctx, config = {}) {
|
|
|
11046
13200
|
...entry.displayName === void 0 ? {} : { displayName: entry.displayName }
|
|
11047
13201
|
});
|
|
11048
13202
|
}
|
|
13203
|
+
const origins = uniqueSiteOrigins(providers);
|
|
13204
|
+
const quotas = (await queryRelayQuotas(ctx, routes)).map((row) => origins.has(row.route) ? row : {
|
|
13205
|
+
...row,
|
|
13206
|
+
sourceAmbiguous: true
|
|
13207
|
+
});
|
|
11049
13208
|
relayCache = {
|
|
11050
13209
|
at: Date.now(),
|
|
11051
|
-
quotas
|
|
13210
|
+
quotas
|
|
11052
13211
|
};
|
|
11053
13212
|
};
|
|
11054
13213
|
let relayInflight;
|