@kenz1117/dsh-ui-usage-billing 1.8.11 → 1.8.13
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 +24 -7
- package/README.md +23 -8
- package/lib/client.js +5 -5
- package/lib/index.js +1449 -381
- package/lib/types/aggregate.d.ts +22 -13
- package/lib/types/balance.d.ts +23 -2
- package/lib/types/client/PeakScheduleEditor.d.ts +9 -0
- package/lib/types/client/api/balance.d.ts +1 -1
- package/lib/types/client/domain/floating-model.d.ts +31 -0
- package/lib/types/client/domain/types.d.ts +10 -1
- package/lib/types/client/live-cost.d.ts +10 -3
- package/lib/types/client/locales.d.ts +2 -1
- 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 +8 -9
- package/lib/types/client/queue-eligibility.d.ts +30 -0
- package/lib/types/client/round-chart.d.ts +1 -0
- package/lib/types/client/scheduled-band.d.ts +23 -0
- package/lib/types/client/task-queue-quick.d.ts +1 -1
- package/lib/types/config.d.ts +2 -0
- 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 +75 -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-shared.d.ts +12 -0
- package/package.json +1 -1
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 折抵扣。
|
|
@@ -617,11 +810,23 @@ function livePriceOf(key) {
|
|
|
617
810
|
};
|
|
618
811
|
}
|
|
619
812
|
/** Lookup a model by its stats key; falls back to the generic `other` entry. */
|
|
620
|
-
function modelOf(key) {
|
|
813
|
+
function modelOf(key, { includeUserPrice = true } = {}) {
|
|
621
814
|
const resolved = resolveCatalogKey(key);
|
|
622
815
|
const found = modelCatalog().find((entry) => entry.key === resolved);
|
|
623
816
|
const extra = extraModelByKey().get(resolved);
|
|
624
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
|
+
};
|
|
625
830
|
const live = livePriceOf(resolved);
|
|
626
831
|
if (live === void 0) return base;
|
|
627
832
|
if (base.price.offPeak !== void 0) return base;
|
|
@@ -775,13 +980,13 @@ function tariffV1At(timeMs) {
|
|
|
775
980
|
* @param peakShare - fallback mix used only when `timeMs` is missing.
|
|
776
981
|
* @returns the estimated cost in CNY(USD 计价模型已按当前汇率折算)。
|
|
777
982
|
*/
|
|
778
|
-
function computeCostAt(entry, buckets, timeMs, peakShare = DEFAULT_PEAK_SHARE) {
|
|
983
|
+
function computeCostAt(entry, buckets, timeMs, peakShare = DEFAULT_PEAK_SHARE, tierOverride) {
|
|
779
984
|
if (timeMs === null || timeMs === void 0 || !Number.isFinite(timeMs)) return computeCost(entry, buckets, peakShare);
|
|
780
985
|
const priced = applyPromo(entry, timeMs);
|
|
781
986
|
const legacy = timeMs < PEAK_ERA_START_MS && entry.userPriced !== true ? LEGACY_DEEPSEEK_BANDS[entry.key] : void 0;
|
|
782
987
|
if (legacy !== void 0) return priceBandCost(legacy, buckets, "CNY");
|
|
783
988
|
const repriced = timeMs < FLASH_REPRICE_MS && entry.userPriced !== true ? FLASH_REPRICED_OFFPEAK[entry.key] : void 0;
|
|
784
|
-
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" ? {
|
|
785
990
|
input: repriced.input * 2,
|
|
786
991
|
cacheHit: repriced.cacheHit * 2,
|
|
787
992
|
output: repriced.output * 2
|
|
@@ -792,7 +997,7 @@ function computeCostAt(entry, buckets, timeMs, peakShare = DEFAULT_PEAK_SHARE) {
|
|
|
792
997
|
const off = priceBandCost(priced.price.offPeak, buckets, priced.price.currency);
|
|
793
998
|
return peak * peakShare + off * (1 - peakShare);
|
|
794
999
|
}
|
|
795
|
-
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);
|
|
796
1001
|
}
|
|
797
1002
|
/**
|
|
798
1003
|
* Format an amount with adaptive precision and the given currency symbol.
|
|
@@ -817,6 +1022,97 @@ function formatTokens(value) {
|
|
|
817
1022
|
return String(value);
|
|
818
1023
|
}
|
|
819
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
|
|
820
1116
|
//#region lib/types/builtin-catalog.js
|
|
821
1117
|
/**
|
|
822
1118
|
* Built-in catalog of current mainstream models as of 2026-10-23, priced from
|
|
@@ -4499,6 +4795,61 @@ const BUILTIN_MODEL_KEY_ALIASES = {
|
|
|
4499
4795
|
"muse-ember-1.0": "muse-ember-1.0"
|
|
4500
4796
|
};
|
|
4501
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"
|
|
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
|
+
}
|
|
4852
|
+
//#endregion
|
|
4502
4853
|
//#region lib/types/aggregate.js
|
|
4503
4854
|
/**
|
|
4504
4855
|
* Real-usage aggregation: folds every persisted session log into the
|
|
@@ -4642,12 +4993,6 @@ function siteRefOf(provider, routes, opts = {}) {
|
|
|
4642
4993
|
provider
|
|
4643
4994
|
};
|
|
4644
4995
|
}
|
|
4645
|
-
/** 站点桶的稳定 key:`site:<origin>` 与 `direct:<provider>` 分开,`unknown` 单一桶。 */
|
|
4646
|
-
function siteBucketKey(ref) {
|
|
4647
|
-
if (ref.kind === "site") return `site:${ref.origin ?? ""}`;
|
|
4648
|
-
if (ref.kind === "direct") return `direct:${ref.provider}`;
|
|
4649
|
-
return "unknown";
|
|
4650
|
-
}
|
|
4651
4996
|
/**
|
|
4652
4997
|
* 站点桶按范围求和(usage_stats 工具的 bySite/relay 口径):bySite 全量累计;
|
|
4653
4998
|
* relay 只计中转站桶(`site:<origin>` 键)——`direct:*` 与 `unknown` 不计入,
|
|
@@ -4659,7 +5004,7 @@ function sumSiteBuckets(bySite, range) {
|
|
|
4659
5004
|
let input = 0;
|
|
4660
5005
|
let output = 0;
|
|
4661
5006
|
for (const [bucket, usage] of Object.entries(bySite)) {
|
|
4662
|
-
if (range === "relay" &&
|
|
5007
|
+
if (range === "relay" && siteKeyParts(bucket).kind !== "site") continue;
|
|
4663
5008
|
cost += usage.cost;
|
|
4664
5009
|
calls += usage.calls;
|
|
4665
5010
|
input += usage.input;
|
|
@@ -4742,23 +5087,42 @@ function foldUsage(acc, usage, key, subscription, timeMs, official = false, pric
|
|
|
4742
5087
|
*/
|
|
4743
5088
|
function foldModelCall(ctx) {
|
|
4744
5089
|
const { fold, usage, modelKey, subscription, official, siteBucket, unverifiedChannel, timeMs, day } = ctx;
|
|
4745
|
-
const
|
|
4746
|
-
|
|
5090
|
+
const catalogPriced = isPriced(modelKey);
|
|
5091
|
+
const priced = !subscription && !unverifiedChannel && catalogPriced;
|
|
5092
|
+
if (!subscription && !catalogPriced) fold.unpricedModels.add(modelKey);
|
|
4747
5093
|
const entry = modelOf(modelKey);
|
|
5094
|
+
const override = priced && !ctx.protectedAccount ? scheduleTier(ctx.schedule, siteBucket, entry, modelKey, timeMs) : void 0;
|
|
4748
5095
|
const thisCost = priced ? computeCostAt(entry, {
|
|
4749
5096
|
input: (usage.cacheReadTokens ?? 0) + usage.inputTokens + (usage.cacheWriteTokens ?? 0),
|
|
4750
5097
|
cacheHit: usage.cacheReadTokens ?? 0,
|
|
4751
5098
|
cacheMiss: usage.inputTokens + (usage.cacheWriteTokens ?? 0),
|
|
4752
5099
|
cacheWrite: usage.cacheWriteTokens ?? 0,
|
|
4753
5100
|
output: usage.outputTokens
|
|
4754
|
-
}, timeMs) : void 0;
|
|
5101
|
+
}, timeMs, void 0, override) : void 0;
|
|
4755
5102
|
foldUsage(fold.total, usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4756
5103
|
foldUsage(usageCell(fold.byModel, modelKey), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4757
5104
|
foldUsage(usageCell(fold.byDay, day), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4758
5105
|
foldUsage(modelDayCell(fold.byDayModels, day, modelKey), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4759
|
-
|
|
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);
|
|
4760
5124
|
foldUsage(usageCell(fold.bySite, siteBucket), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4761
|
-
if (entry.tierSemantics !== "latency") foldUsage(usageCell(fold.byTier, tierAt(timeMs)), 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);
|
|
4762
5126
|
if (subscription) fold.planCalls.set(modelKey, (fold.planCalls.get(modelKey) ?? 0) + 1);
|
|
4763
5127
|
if (subscription) {
|
|
4764
5128
|
const sitePlanKey = planSiteKey(day, modelKey, siteBucket);
|
|
@@ -4770,13 +5134,15 @@ function foldModelCall(ctx) {
|
|
|
4770
5134
|
cacheHit: 0,
|
|
4771
5135
|
cacheMiss: 0,
|
|
4772
5136
|
output: usage.outputTokens
|
|
4773
|
-
}, timeMs);
|
|
5137
|
+
}, timeMs, void 0, override);
|
|
4774
5138
|
fold.roles.outputCost += outputCost;
|
|
4775
5139
|
fold.roles.inputCost += thisCost - outputCost;
|
|
4776
5140
|
}
|
|
4777
5141
|
return {
|
|
4778
5142
|
entry,
|
|
4779
|
-
cost: thisCost
|
|
5143
|
+
cost: thisCost,
|
|
5144
|
+
override,
|
|
5145
|
+
catalogPriced
|
|
4780
5146
|
};
|
|
4781
5147
|
}
|
|
4782
5148
|
/**
|
|
@@ -5198,7 +5564,7 @@ function deserializeFold(fold) {
|
|
|
5198
5564
|
* @param officialProviderIds - 官方直连 provider 名单(决定官方/三方拆分)。
|
|
5199
5565
|
* @returns 归一并补价后的折叠;无需改动时原样返回。
|
|
5200
5566
|
*/
|
|
5201
|
-
function reconcileLedgerFold(fold, officialProviderIds) {
|
|
5567
|
+
function reconcileLedgerFold(fold, officialProviderIds, schedule, fingerprint) {
|
|
5202
5568
|
const rawKeys = /* @__PURE__ */ new Set();
|
|
5203
5569
|
for (const key of fold.byModel.keys()) rawKeys.add(key);
|
|
5204
5570
|
for (const models of fold.byDayModels.values()) for (const key of models.keys()) rawKeys.add(key);
|
|
@@ -5284,20 +5650,30 @@ function reconcileLedgerFold(fold, officialProviderIds) {
|
|
|
5284
5650
|
let addedOfficial = 0;
|
|
5285
5651
|
let addedPeak = 0;
|
|
5286
5652
|
let addedOff = 0;
|
|
5653
|
+
const safeLegacySource = legacyScheduleSource(fingerprint);
|
|
5287
5654
|
for (const [day, models] of fold.byDayModels) for (const [rawKey, cell] of models) {
|
|
5288
5655
|
if (!repriceKeys.has(rawKey)) continue;
|
|
5289
5656
|
const resolved = resolvedKeyOf(rawKey);
|
|
5290
5657
|
const entry = modelOf(resolved);
|
|
5291
|
-
const
|
|
5292
|
-
|
|
5293
|
-
const
|
|
5294
|
-
const dayOutput = repriced.outputCost;
|
|
5295
|
-
const dayPeak = repriced.peakCost;
|
|
5296
|
-
const dayOff = repriced.offCost;
|
|
5658
|
+
const remainder = emptyTokens();
|
|
5659
|
+
addTokens(remainder, cell);
|
|
5660
|
+
const dayPrice = emptyPrice();
|
|
5297
5661
|
let dayOfficial = 0;
|
|
5298
5662
|
const siteCells = fold.byDayModelsSite.get(day)?.get(rawKey);
|
|
5299
|
-
if (siteCells
|
|
5300
|
-
|
|
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);
|
|
5301
5677
|
const official = isOfficialSiteBucket(site, officialProviderIds);
|
|
5302
5678
|
if (official) dayOfficial += siteRepriced.cost;
|
|
5303
5679
|
const siteTarget = byDayModelsSite.get(day)?.get(resolved)?.get(site);
|
|
@@ -5311,6 +5687,8 @@ function reconcileLedgerFold(fold, officialProviderIds) {
|
|
|
5311
5687
|
if (official) siteBucketCell.officialCost += siteRepriced.cost;
|
|
5312
5688
|
}
|
|
5313
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;
|
|
5314
5692
|
const modelCell = byModel.get(resolved);
|
|
5315
5693
|
if (modelCell !== void 0) {
|
|
5316
5694
|
modelCell.cost += dayCost;
|
|
@@ -5333,27 +5711,38 @@ function reconcileLedgerFold(fold, officialProviderIds) {
|
|
|
5333
5711
|
addedPeak += dayPeak;
|
|
5334
5712
|
addedOff += dayOff;
|
|
5335
5713
|
}
|
|
5336
|
-
|
|
5337
|
-
if (
|
|
5338
|
-
const tierOff = byTier.get("offPeak");
|
|
5339
|
-
if (tierOff !== void 0) tierOff.cost += addedOff;
|
|
5714
|
+
if (addedPeak) usageCell(byTier, "peak").cost += addedPeak;
|
|
5715
|
+
if (addedOff) usageCell(byTier, "offPeak").cost += addedOff;
|
|
5340
5716
|
const turns = fold.turns.map((row) => {
|
|
5341
5717
|
const resolved = resolvedKeyOf(row.model);
|
|
5342
5718
|
if (!repriceKeys.has(row.model) || row.cost > 0) return {
|
|
5343
5719
|
...row,
|
|
5344
5720
|
model: resolved
|
|
5345
5721
|
};
|
|
5346
|
-
const
|
|
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, {
|
|
5347
5735
|
input: row.input,
|
|
5348
5736
|
cacheHit: row.cacheHit,
|
|
5349
5737
|
cacheMiss: row.cacheMiss,
|
|
5350
5738
|
cacheWrite: 0,
|
|
5351
5739
|
output: row.output
|
|
5352
|
-
}, row.startedAt);
|
|
5740
|
+
}, row.startedAt, void 0, override);
|
|
5353
5741
|
return {
|
|
5354
5742
|
...row,
|
|
5355
5743
|
model: resolved,
|
|
5356
|
-
cost
|
|
5744
|
+
cost,
|
|
5745
|
+
...override && { scheduleTier: override }
|
|
5357
5746
|
};
|
|
5358
5747
|
});
|
|
5359
5748
|
const roles = {
|
|
@@ -5418,64 +5807,6 @@ function parsePlanSiteKey(key) {
|
|
|
5418
5807
|
return;
|
|
5419
5808
|
}
|
|
5420
5809
|
}
|
|
5421
|
-
/**
|
|
5422
|
-
* 本地自然日(`YYYY-MM-DD`)内、北京时间某小时对应的时刻(epoch ms)。
|
|
5423
|
-
*
|
|
5424
|
-
* 兜底行按日补价时用两个探针时刻分别落峰档与谷档(北京时间 10:00 / 20:00):
|
|
5425
|
-
* 日志已删的会话没有请求级时间戳,只能按日估算(与客户端「目录价预估」同一口径)。
|
|
5426
|
-
*/
|
|
5427
|
-
function dayMomentAtBeijingHour(day, beijingHour) {
|
|
5428
|
-
const parts = day.split("-");
|
|
5429
|
-
const year = Number(parts[0]);
|
|
5430
|
-
const month = Number(parts[1]);
|
|
5431
|
-
const date = Number(parts[2]);
|
|
5432
|
-
if (!Number.isFinite(year) || !Number.isFinite(month) || !Number.isFinite(date)) return Date.now();
|
|
5433
|
-
const base = new Date(year, month - 1, date, 0, 0, 0, 0).getTime();
|
|
5434
|
-
if (!Number.isFinite(base)) return Date.now();
|
|
5435
|
-
return base + (beijingHour - (new Date(base + 288e5).getUTCHours() + 24) % 24 + 24) % 24 * 36e5;
|
|
5436
|
-
}
|
|
5437
|
-
/**
|
|
5438
|
-
* 按自然日给一个 token 桶补价:峰/谷两档各取一个探针时刻后按比例混合。
|
|
5439
|
-
*
|
|
5440
|
-
* 价格时代分段(峰谷时代起点、flash 调价分界)与促销窗口由
|
|
5441
|
-
* {@link computeCostAt} 按该时刻判定——不套现行价重算历史。输出侧费用单独算
|
|
5442
|
-
* 一遍(计价对 token 桶是线性的),供角色归因拆分输入/输出两侧。
|
|
5443
|
-
*/
|
|
5444
|
-
function repriceCellByDay(entry, cell, day) {
|
|
5445
|
-
const buckets = {
|
|
5446
|
-
input: cell.input,
|
|
5447
|
-
cacheHit: cell.cacheHit,
|
|
5448
|
-
cacheMiss: cell.cacheMiss,
|
|
5449
|
-
cacheWrite: cell.cacheWrite ?? 0,
|
|
5450
|
-
output: cell.output
|
|
5451
|
-
};
|
|
5452
|
-
const outputOnly = {
|
|
5453
|
-
input: 0,
|
|
5454
|
-
cacheHit: 0,
|
|
5455
|
-
cacheMiss: 0,
|
|
5456
|
-
cacheWrite: 0,
|
|
5457
|
-
output: cell.output
|
|
5458
|
-
};
|
|
5459
|
-
const tsPeak = dayMomentAtBeijingHour(day, LEDGER_PEAK_PROBE_HOUR);
|
|
5460
|
-
const tsOff = dayMomentAtBeijingHour(day, LEDGER_OFFPEAK_PROBE_HOUR);
|
|
5461
|
-
const peak = computeCostAt(entry, buckets, tsPeak);
|
|
5462
|
-
const off = computeCostAt(entry, buckets, tsOff);
|
|
5463
|
-
const peakOutput = computeCostAt(entry, outputOnly, tsPeak);
|
|
5464
|
-
const offOutput = computeCostAt(entry, outputOnly, tsOff);
|
|
5465
|
-
const cost = peak * DEFAULT_PEAK_SHARE + off * .5;
|
|
5466
|
-
const outputCost = peakOutput * DEFAULT_PEAK_SHARE + offOutput * .5;
|
|
5467
|
-
return {
|
|
5468
|
-
cost,
|
|
5469
|
-
inputCost: cost - outputCost,
|
|
5470
|
-
outputCost,
|
|
5471
|
-
peakCost: peak * DEFAULT_PEAK_SHARE,
|
|
5472
|
-
offCost: off * .5
|
|
5473
|
-
};
|
|
5474
|
-
}
|
|
5475
|
-
/** 兜底行补价时的峰档探针时刻(北京时间小时)。 */
|
|
5476
|
-
const LEDGER_PEAK_PROBE_HOUR = 10;
|
|
5477
|
-
/** 兜底行补价时的谷档探针时刻(北京时间小时)。 */
|
|
5478
|
-
const LEDGER_OFFPEAK_PROBE_HOUR = 20;
|
|
5479
5810
|
/** Runtime boundary for a user-editable/corrupt ledger file. Invalid rows are ignored. */
|
|
5480
5811
|
function ledgerSessionsOf(value) {
|
|
5481
5812
|
if (value === null || typeof value !== "object") return [];
|
|
@@ -5616,7 +5947,8 @@ function freshFold() {
|
|
|
5616
5947
|
* @param routeAliases - 历史路由别名(旧路由名 → 当前路由名),改名/删除路由的
|
|
5617
5948
|
* 历史用量按别名归位,不再落「未知路由」桶。
|
|
5618
5949
|
*/
|
|
5619
|
-
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;
|
|
5620
5952
|
let key = machine.key;
|
|
5621
5953
|
let subscription = machine.subscription;
|
|
5622
5954
|
let official = machine.official;
|
|
@@ -5665,6 +5997,7 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5665
5997
|
if (event.type === "request/header") {
|
|
5666
5998
|
const { model, provider: rawProvider } = event.data.header.config;
|
|
5667
5999
|
const provider = routeAliases[rawProvider] ?? rawProvider;
|
|
6000
|
+
protectedAccount = accountRoute(rawProvider) || accountRoute(provider);
|
|
5668
6001
|
key = resolveCatalogKey(model);
|
|
5669
6002
|
subscription = isSubscriptionCall(subscriptionProviders, provider);
|
|
5670
6003
|
const siteRef = siteRefOf(provider, routes, { subscription });
|
|
@@ -5730,6 +6063,8 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5730
6063
|
const compactionSiteBucket = siteBucketKey(siteRef);
|
|
5731
6064
|
foldModelCall({
|
|
5732
6065
|
fold,
|
|
6066
|
+
protectedAccount: accountRoute(data.provider) || accountRoute(provider),
|
|
6067
|
+
schedule,
|
|
5733
6068
|
usage: compactionUsage,
|
|
5734
6069
|
modelKey,
|
|
5735
6070
|
subscription: compactionSubscription,
|
|
@@ -5747,6 +6082,7 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5747
6082
|
const source = event.data.message?.source;
|
|
5748
6083
|
if (source?.kind === "model" && typeof source.provider === "string" && typeof source.model === "string") {
|
|
5749
6084
|
const provider = routeAliases[source.provider] ?? source.provider;
|
|
6085
|
+
protectedAccount = accountRoute(source.provider) || accountRoute(provider);
|
|
5750
6086
|
key = resolveCatalogKey(source.model);
|
|
5751
6087
|
subscription = isSubscriptionCall(subscriptionProviders, provider);
|
|
5752
6088
|
const siteRef = siteRefOf(provider, routes, { subscription });
|
|
@@ -5755,20 +6091,32 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5755
6091
|
}
|
|
5756
6092
|
const modelKey = key;
|
|
5757
6093
|
const day = dayStamp(event.time);
|
|
5758
|
-
const { entry, cost: thisCost } = foldModelCall({
|
|
6094
|
+
const { entry, cost: thisCost, override, catalogPriced } = foldModelCall({
|
|
5759
6095
|
fold,
|
|
5760
6096
|
usage,
|
|
5761
6097
|
modelKey,
|
|
5762
6098
|
subscription,
|
|
5763
6099
|
official,
|
|
5764
6100
|
siteBucket,
|
|
6101
|
+
schedule,
|
|
6102
|
+
protectedAccount,
|
|
5765
6103
|
unverifiedChannel: siteBucket === "unknown",
|
|
5766
6104
|
timeMs: event.time,
|
|
5767
6105
|
day
|
|
5768
6106
|
});
|
|
5769
6107
|
const turn = event.data.turn ?? -1;
|
|
5770
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;
|
|
5771
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;
|
|
5772
6120
|
state.input += usage.inputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0);
|
|
5773
6121
|
state.output += usage.outputTokens;
|
|
5774
6122
|
state.cacheHit += usage.cacheReadTokens ?? 0;
|
|
@@ -5785,6 +6133,7 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5785
6133
|
}
|
|
5786
6134
|
}
|
|
5787
6135
|
}
|
|
6136
|
+
machine.protectedAccount = protectedAccount;
|
|
5788
6137
|
machine.key = key;
|
|
5789
6138
|
machine.subscription = subscription;
|
|
5790
6139
|
machine.official = official;
|
|
@@ -5796,6 +6145,9 @@ function refreshTurns(fold, machine) {
|
|
|
5796
6145
|
fold.turns = [...machine.turns.values()].filter((state) => state.input > 0 || state.output > 0).sort((a, b) => a.turn - b.turn).map((state) => ({
|
|
5797
6146
|
turn: state.turn,
|
|
5798
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 },
|
|
5799
6151
|
input: state.input,
|
|
5800
6152
|
output: state.output,
|
|
5801
6153
|
cacheHit: state.cacheHit,
|
|
@@ -5970,14 +6322,17 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5970
6322
|
const maxCacheSessions = options.maxCacheSessions ?? 400;
|
|
5971
6323
|
const cache = /* @__PURE__ */ new Map();
|
|
5972
6324
|
const ledger = /* @__PURE__ */ new Map();
|
|
5973
|
-
let
|
|
6325
|
+
let ledgerLoading;
|
|
6326
|
+
let latestFoldedEvent = -1;
|
|
5974
6327
|
let ledgerNeedsSave = false;
|
|
5975
6328
|
let lastLedgerSaveAt = 0;
|
|
5976
6329
|
const unreadable = /* @__PURE__ */ new Map();
|
|
5977
6330
|
const titleHints = /* @__PURE__ */ new Map();
|
|
5978
6331
|
let inflight;
|
|
6332
|
+
let scheduleWrite;
|
|
5979
6333
|
let ledgerAppliedMigrations;
|
|
5980
6334
|
let lastDoc;
|
|
6335
|
+
let lastHistory;
|
|
5981
6336
|
let lastAt = 0;
|
|
5982
6337
|
const deserializedFoldOf = (() => {
|
|
5983
6338
|
const memo = /* @__PURE__ */ new WeakMap();
|
|
@@ -5989,16 +6344,24 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5989
6344
|
return fold;
|
|
5990
6345
|
};
|
|
5991
6346
|
})();
|
|
5992
|
-
|
|
5993
|
-
|
|
5994
|
-
|
|
5995
|
-
|
|
5996
|
-
|
|
5997
|
-
|
|
5998
|
-
|
|
5999
|
-
|
|
6000
|
-
}
|
|
6001
|
-
|
|
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
|
+
}
|
|
6002
6365
|
/** 每次聚合取最新的 provider 路由视图(中转站零配置发现);缺省按空处理(全部未知路由)。
|
|
6003
6366
|
* 叠加已注册 adapter 的通道(issue #91):宿主 llm 注册表里的 provider 合成无 baseURL
|
|
6004
6367
|
* 的空路由视图——siteRefOf 的路由命中分支正是「无 origin 直连」的语义,归位
|
|
@@ -6029,7 +6392,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6029
6392
|
* 价目表变化后未受影响行(无 unpriced 模型)依旧零读取复用。 */
|
|
6030
6393
|
const foldNeedsReprice = (fold) => fold.unpricedModels.some((key) => isPriced(key));
|
|
6031
6394
|
/** 把一份(全量或增量)折叠结果登记进 durable ledger;内容无变化时不落盘。 */
|
|
6032
|
-
const recordLedger = (id, cwd, stamp, fold, subOf) => {
|
|
6395
|
+
const recordLedger = (id, cwd, stamp, fold, subOf, scheduleFingerprint) => {
|
|
6033
6396
|
if (options.ledger === void 0) return;
|
|
6034
6397
|
const entry = {
|
|
6035
6398
|
id,
|
|
@@ -6038,18 +6401,18 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6038
6401
|
...stamp === null ? {} : { stamp },
|
|
6039
6402
|
foldVersion: 24,
|
|
6040
6403
|
fingerprint: foldFingerprint,
|
|
6404
|
+
...scheduleFingerprint === void 0 ? {} : { scheduleFingerprint },
|
|
6041
6405
|
foldedAt: Date.now(),
|
|
6042
6406
|
fold: serializeFold(fold)
|
|
6043
6407
|
};
|
|
6044
6408
|
const row = ledger.get(id);
|
|
6045
|
-
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)) {
|
|
6046
6410
|
ledger.set(id, entry);
|
|
6047
6411
|
ledgerNeedsSave = true;
|
|
6048
6412
|
}
|
|
6049
6413
|
};
|
|
6050
|
-
const
|
|
6051
|
-
if (
|
|
6052
|
-
ledgerLoaded = true;
|
|
6414
|
+
const loadLedger = async () => {
|
|
6415
|
+
if (options.ledger === void 0) return;
|
|
6053
6416
|
try {
|
|
6054
6417
|
const stored = await options.ledger.load();
|
|
6055
6418
|
if (stored !== null && typeof stored === "object" && stored.sessions !== void 0) {
|
|
@@ -6061,11 +6424,15 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6061
6424
|
format: refusal.format === true
|
|
6062
6425
|
});
|
|
6063
6426
|
}
|
|
6064
|
-
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
|
+
}
|
|
6065
6431
|
} catch (error) {
|
|
6066
6432
|
console.warn("[usage-billing] failed to load durable usage ledger; rebuilding from current sessions:", error);
|
|
6067
6433
|
}
|
|
6068
6434
|
};
|
|
6435
|
+
const ensureLedgerLoaded = () => ledgerLoading ??= loadLedger();
|
|
6069
6436
|
/** 失效键:宿主 0.1.3+ 走 adapter 暴露的 revision 令牌;0.1.2 形状退回
|
|
6070
6437
|
* 日志文件 mtime+size(经 locate,拿不到或抛错时返回 null 让调用方重折)。
|
|
6071
6438
|
* locate/stat 调用纳入 try,避免单个会话的异常把整份聚合拖垮。 */
|
|
@@ -6114,11 +6481,12 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6114
6481
|
* 开门后的下一轮即完整折叠)——轻文档的每行折叠反序列化有 WeakMap 记忆,
|
|
6115
6482
|
* 重复构建只付 O(行数) 的汇总合并,冷phase里每个请求都可负担。
|
|
6116
6483
|
*/
|
|
6117
|
-
const aggregateOnce = async (mode) => {
|
|
6484
|
+
const aggregateOnce = async (mode, history, activeSchedule) => {
|
|
6118
6485
|
const now = Date.now();
|
|
6119
6486
|
await ensureLedgerLoaded();
|
|
6120
6487
|
const registeredProviders = options.resolveRegisteredProviders?.() ?? /* @__PURE__ */ new Set();
|
|
6121
6488
|
const roundRoutes = routesOf(registeredProviders);
|
|
6489
|
+
const schedule = useHistory(history);
|
|
6122
6490
|
foldFingerprint = foldFingerprintOf(registeredProviders, roundRoutes);
|
|
6123
6491
|
const seen = /* @__PURE__ */ new Set();
|
|
6124
6492
|
const included = /* @__PURE__ */ new Set();
|
|
@@ -6163,8 +6531,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6163
6531
|
const cwd = meta.cwd;
|
|
6164
6532
|
const subOf = subParentOf(meta);
|
|
6165
6533
|
const ledgerRow = ledger.get(id);
|
|
6166
|
-
if (ledgerRow !== void 0 && ledgerRow.stamp !== void 0 && stamp !== null && ledgerRow.stamp === stamp && (ledgerRow.foldVersion ?? 1) === 24 && ledgerRow.fingerprint === foldFingerprint && !foldNeedsReprice(ledgerRow.fold)) {
|
|
6167
|
-
const fold = reconciledFoldOf(ledgerRow
|
|
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);
|
|
6168
6536
|
folds.push({
|
|
6169
6537
|
id,
|
|
6170
6538
|
...cwd === void 0 ? {} : { cwd },
|
|
@@ -6175,7 +6543,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6175
6543
|
continue;
|
|
6176
6544
|
}
|
|
6177
6545
|
const hit = cache.get(id);
|
|
6178
|
-
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))) {
|
|
6179
6547
|
cache.delete(id);
|
|
6180
6548
|
cache.set(id, hit);
|
|
6181
6549
|
folds.push({
|
|
@@ -6188,7 +6556,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6188
6556
|
continue;
|
|
6189
6557
|
}
|
|
6190
6558
|
const previous = cache.get(id);
|
|
6191
|
-
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))) {
|
|
6192
6560
|
const from = previous.lastSeq + 1;
|
|
6193
6561
|
const { events, inheritedEventCount } = await persistence.readFrom(meta.id, sessionLogOffsetOf(from));
|
|
6194
6562
|
const after = await stampOf(meta);
|
|
@@ -6201,7 +6569,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6201
6569
|
cache.delete(id);
|
|
6202
6570
|
continue;
|
|
6203
6571
|
}
|
|
6204
|
-
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);
|
|
6205
6574
|
refreshTurns(previous.fold, previous.machine);
|
|
6206
6575
|
previous.lastSeq = events[events.length - 1]?.seq ?? previous.lastSeq;
|
|
6207
6576
|
previous.stamp = stamp;
|
|
@@ -6214,7 +6583,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6214
6583
|
fold: previous.fold
|
|
6215
6584
|
});
|
|
6216
6585
|
included.add(id);
|
|
6217
|
-
|
|
6586
|
+
previous.scheduleFingerprint = schedule?.fingerprint(previous.fold.lastActive);
|
|
6587
|
+
recordLedger(id, cwd, stamp, previous.fold, subOf, previous.scheduleFingerprint);
|
|
6218
6588
|
continue;
|
|
6219
6589
|
}
|
|
6220
6590
|
const { events, inheritedEventCount } = await persistence.readFrom(meta.id, sessionLogOffsetOf(0));
|
|
@@ -6223,7 +6593,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6223
6593
|
const fold = freshFold();
|
|
6224
6594
|
const machine = freshMachine();
|
|
6225
6595
|
for (let start = 0; start < events.length; start += FOLD_CHUNK_EVENTS) {
|
|
6226
|
-
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);
|
|
6227
6598
|
if (start + FOLD_CHUNK_EVENTS < events.length && Date.now() - sliceAt >= FOLD_SLICE_MS) {
|
|
6228
6599
|
await new Promise((resolve) => {
|
|
6229
6600
|
setImmediate(resolve);
|
|
@@ -6238,7 +6609,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6238
6609
|
fold,
|
|
6239
6610
|
machine,
|
|
6240
6611
|
...last !== void 0 && typeof last.seq === "number" ? { lastSeq: last.seq } : {},
|
|
6241
|
-
fingerprint: foldFingerprint
|
|
6612
|
+
fingerprint: foldFingerprint,
|
|
6613
|
+
scheduleFingerprint: schedule?.fingerprint(fold.lastActive)
|
|
6242
6614
|
});
|
|
6243
6615
|
folds.push({
|
|
6244
6616
|
id,
|
|
@@ -6247,7 +6619,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6247
6619
|
fold
|
|
6248
6620
|
});
|
|
6249
6621
|
included.add(id);
|
|
6250
|
-
recordLedger(id, cwd, stamp, fold, subOf);
|
|
6622
|
+
recordLedger(id, cwd, stamp, fold, subOf, schedule?.fingerprint(fold.lastActive));
|
|
6251
6623
|
} catch (error) {
|
|
6252
6624
|
skipped.push(id);
|
|
6253
6625
|
const format = isFormatUnsupportedError(error);
|
|
@@ -6293,7 +6665,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6293
6665
|
if (included.has(entry.id)) continue;
|
|
6294
6666
|
try {
|
|
6295
6667
|
const stale = (entry.foldVersion ?? 1) < 24 || entry.fingerprint !== foldFingerprint;
|
|
6296
|
-
const fold = reconciledFoldOf(entry
|
|
6668
|
+
const fold = reconciledFoldOf(entry);
|
|
6297
6669
|
const hint = titleHints.get(entry.id);
|
|
6298
6670
|
folds.push({
|
|
6299
6671
|
id: entry.id,
|
|
@@ -6439,10 +6811,16 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6439
6811
|
};
|
|
6440
6812
|
const toModelDayRecord = (map) => Object.fromEntries([...map].map(([day, models]) => [day, Object.fromEntries(models)]));
|
|
6441
6813
|
const toModelDaySiteRecord = (map) => Object.fromEntries([...map].map(([day, models]) => [day, Object.fromEntries([...models].map(([model, sites]) => [model, Object.fromEntries([...sites].map(([site, cell]) => {
|
|
6442
|
-
|
|
6814
|
+
const count = planSiteCalls.get(planSiteKey(day, model, site)) ?? 0;
|
|
6815
|
+
if (count === cell.calls && count > 0) return [site, {
|
|
6443
6816
|
...cell,
|
|
6444
6817
|
plan: true
|
|
6445
|
-
}
|
|
6818
|
+
}];
|
|
6819
|
+
if (count > 0 && count < cell.calls) return [site, {
|
|
6820
|
+
...cell,
|
|
6821
|
+
planCalls: count
|
|
6822
|
+
}];
|
|
6823
|
+
return [site, cell];
|
|
6446
6824
|
}))]))]));
|
|
6447
6825
|
const modelKeys = /* @__PURE__ */ new Set([...perfModel.keys(), ...perfModelDigest.keys()]);
|
|
6448
6826
|
const hourKeys = /* @__PURE__ */ new Set([...perfHourModel.keys(), ...perfHourDigest.keys()]);
|
|
@@ -6479,6 +6857,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6479
6857
|
...byDayModelsSite.size === 0 ? {} : { byDayModelsSite: toModelDaySiteRecord(byDayModelsSite) },
|
|
6480
6858
|
bySession: sessionRows.slice(0, 100),
|
|
6481
6859
|
bySessionTotal: sessionRows.length,
|
|
6860
|
+
...activeSchedule ? { peakSchedule: activeSchedule } : {},
|
|
6482
6861
|
byTurn: turnRows.slice(0, 200),
|
|
6483
6862
|
byWorkspace: workspaces.slice(0, 100),
|
|
6484
6863
|
...byTier.size === 0 ? {} : { byTier: {
|
|
@@ -6508,20 +6887,37 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6508
6887
|
};
|
|
6509
6888
|
if (mode === "full") {
|
|
6510
6889
|
lastDoc = document;
|
|
6890
|
+
lastHistory = history;
|
|
6511
6891
|
lastAt = now;
|
|
6512
6892
|
}
|
|
6513
6893
|
return document;
|
|
6514
6894
|
};
|
|
6515
6895
|
return {
|
|
6516
6896
|
aggregate() {
|
|
6897
|
+
if (scheduleWrite !== void 0) return scheduleWrite.then(() => this.aggregate(), () => this.aggregate());
|
|
6517
6898
|
const now = Date.now();
|
|
6518
|
-
|
|
6519
|
-
|
|
6520
|
-
|
|
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(() => {
|
|
6521
6905
|
inflight = void 0;
|
|
6522
6906
|
});
|
|
6523
6907
|
return inflight;
|
|
6524
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
|
+
},
|
|
6525
6921
|
async sessionUsageOf(sessionId) {
|
|
6526
6922
|
await this.aggregate();
|
|
6527
6923
|
const hit = cache.get(sessionId);
|
|
@@ -6534,7 +6930,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6534
6930
|
const row = ledger.get(sessionId);
|
|
6535
6931
|
if (row === void 0) return void 0;
|
|
6536
6932
|
try {
|
|
6537
|
-
const fold = reconciledFoldOf(row
|
|
6933
|
+
const fold = reconciledFoldOf(row);
|
|
6538
6934
|
return {
|
|
6539
6935
|
calls: fold.total.calls,
|
|
6540
6936
|
cost: fold.total.cost,
|
|
@@ -6870,6 +7266,12 @@ const customGate = createCooldownGate({
|
|
|
6870
7266
|
});
|
|
6871
7267
|
/** DeepSeek 官方余额接口(官方文档 api-docs.deepseek.com/api/get-user-balance)。 */
|
|
6872
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";
|
|
6873
7275
|
/** Moonshot/Kimi 官方余额接口(platform.kimi.com/docs/api/balance)。 */
|
|
6874
7276
|
const MOONSHOT_BALANCE_URL = "https://api.moonshot.cn/v1/users/me/balance";
|
|
6875
7277
|
/** 阶跃星辰 StepFun 官方账户信息接口(platform.stepfun.com/docs/api-reference/accounts/get)。 */
|
|
@@ -6880,26 +7282,18 @@ const SILICONFLOW_BALANCE_URL = "https://api.siliconflow.cn/v1/user/info";
|
|
|
6880
7282
|
const XAI_CREDITS_URL = "https://api.x.ai/v1/billing/credits";
|
|
6881
7283
|
/** 智谱 GLM(大模型国内域)官方余额接口(open.bigmodel.cn/api/paas/v4/balance)。 */
|
|
6882
7284
|
const ZHIPU_BALANCE_URL = "https://open.bigmodel.cn/api/paas/v4/balance";
|
|
6883
|
-
/** 数字归一化:接口返回的余额是字符串(如 `"110.00"`),统一转 number。 */
|
|
6884
7285
|
/**
|
|
6885
7286
|
* Fetch a Bearer-protected balance endpoint and normalize the HTTP outcome into
|
|
6886
7287
|
* a shared {@link ProviderBalance} row. Each provider supplies its own
|
|
6887
7288
|
* response parser for the success body.
|
|
6888
|
-
* @param ctx - host context carrying the credentials seam.
|
|
6889
7289
|
* @param url - the balance endpoint.
|
|
6890
|
-
* @param
|
|
7290
|
+
* @param key - resolved credential for this query.
|
|
6891
7291
|
* @param provider - the provider id (matches the model-table vendor display name).
|
|
6892
7292
|
* @param displayName - human-readable provider name.
|
|
6893
7293
|
* @param parse - maps a success JSON body to the balance row fields.
|
|
6894
7294
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6895
7295
|
*/
|
|
6896
|
-
async function queryBearerBalance(
|
|
6897
|
-
const hit = await ctx.credentials.resolve(credentialRef(apiKeyEnv));
|
|
6898
|
-
if (hit === void 0) return {
|
|
6899
|
-
provider,
|
|
6900
|
-
displayName,
|
|
6901
|
-
error: "unconfigured"
|
|
6902
|
-
};
|
|
7296
|
+
async function queryBearerBalance(url, key, provider, displayName, parse) {
|
|
6903
7297
|
if (!balanceGate.check(provider)) return {
|
|
6904
7298
|
provider,
|
|
6905
7299
|
displayName,
|
|
@@ -6912,7 +7306,7 @@ async function queryBearerBalance(ctx, url, apiKeyEnv, provider, displayName, pa
|
|
|
6912
7306
|
const response = await fetch(url, {
|
|
6913
7307
|
headers: {
|
|
6914
7308
|
accept: "application/json",
|
|
6915
|
-
authorization: `Bearer ${
|
|
7309
|
+
authorization: `Bearer ${key}`
|
|
6916
7310
|
},
|
|
6917
7311
|
signal: controller.signal
|
|
6918
7312
|
});
|
|
@@ -6956,40 +7350,123 @@ async function queryBearerBalance(ctx, url, apiKeyEnv, provider, displayName, pa
|
|
|
6956
7350
|
};
|
|
6957
7351
|
}
|
|
6958
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
|
+
}
|
|
6959
7371
|
/**
|
|
6960
|
-
*
|
|
6961
|
-
*
|
|
6962
|
-
*
|
|
6963
|
-
* @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)。
|
|
6964
7375
|
*/
|
|
6965
|
-
|
|
6966
|
-
|
|
6967
|
-
|
|
6968
|
-
|
|
6969
|
-
|
|
6970
|
-
|
|
6971
|
-
|
|
6972
|
-
|
|
6973
|
-
|
|
6974
|
-
|
|
6975
|
-
|
|
6976
|
-
|
|
6977
|
-
|
|
6978
|
-
|
|
6979
|
-
|
|
6980
|
-
|
|
6981
|
-
|
|
6982
|
-
|
|
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
|
|
6983
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);
|
|
6984
7462
|
}
|
|
6985
7463
|
/**
|
|
6986
7464
|
* Query the Moonshot/Kimi account balance.
|
|
6987
|
-
* @param
|
|
6988
|
-
* @param apiKeyEnv - credential reference resolving the Moonshot API key.
|
|
7465
|
+
* @param key - resolved credential for this query.
|
|
6989
7466
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6990
7467
|
*/
|
|
6991
|
-
function queryMoonshot(
|
|
6992
|
-
return queryBearerBalance(
|
|
7468
|
+
function queryMoonshot(url, key) {
|
|
7469
|
+
return queryBearerBalance(url, key, "月之暗面", "月之暗面", (data) => {
|
|
6993
7470
|
const doc = data;
|
|
6994
7471
|
const totalBalance = toNumber$1(doc.data?.available_balance);
|
|
6995
7472
|
const grantedBalance = toNumber$1(doc.data?.voucher_balance);
|
|
@@ -7006,12 +7483,11 @@ function queryMoonshot(ctx, apiKeyEnv) {
|
|
|
7006
7483
|
}
|
|
7007
7484
|
/**
|
|
7008
7485
|
* Query the StepFun (阶跃星辰) account balance.
|
|
7009
|
-
* @param
|
|
7010
|
-
* @param apiKeyEnv - credential reference resolving the StepFun API key.
|
|
7486
|
+
* @param key - resolved credential for this query.
|
|
7011
7487
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
7012
7488
|
*/
|
|
7013
|
-
function queryStepFun(
|
|
7014
|
-
return queryBearerBalance(
|
|
7489
|
+
function queryStepFun(url, key) {
|
|
7490
|
+
return queryBearerBalance(url, key, "阶跃星辰", "阶跃星辰", (data) => {
|
|
7015
7491
|
const doc = data;
|
|
7016
7492
|
const totalBalance = toNumber$1(doc.balance);
|
|
7017
7493
|
const toppedUpBalance = toNumber$1(doc.total_cash_balance);
|
|
@@ -7028,12 +7504,11 @@ function queryStepFun(ctx, apiKeyEnv) {
|
|
|
7028
7504
|
}
|
|
7029
7505
|
/**
|
|
7030
7506
|
* Query the SiliconFlow (硅基流动) account balance.
|
|
7031
|
-
* @param
|
|
7032
|
-
* @param apiKeyEnv - credential reference resolving the SiliconFlow API key.
|
|
7507
|
+
* @param key - resolved credential for this query.
|
|
7033
7508
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
7034
7509
|
*/
|
|
7035
|
-
function querySiliconFlow(
|
|
7036
|
-
return queryBearerBalance(
|
|
7510
|
+
function querySiliconFlow(url, key) {
|
|
7511
|
+
return queryBearerBalance(url, key, "硅基流动", "硅基流动", (data) => {
|
|
7037
7512
|
const doc = data;
|
|
7038
7513
|
const inner = doc.data ?? doc;
|
|
7039
7514
|
const totalBalance = toNumber$1(inner.balance ?? inner.balance_cny);
|
|
@@ -7047,12 +7522,11 @@ function querySiliconFlow(ctx, apiKeyEnv) {
|
|
|
7047
7522
|
}
|
|
7048
7523
|
/**
|
|
7049
7524
|
* Query the xAI (Grok) credit balance.
|
|
7050
|
-
* @param
|
|
7051
|
-
* @param apiKeyEnv - credential reference resolving the xAI API key.
|
|
7525
|
+
* @param key - resolved credential for this query.
|
|
7052
7526
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
7053
7527
|
*/
|
|
7054
|
-
function queryXai(
|
|
7055
|
-
return queryBearerBalance(
|
|
7528
|
+
function queryXai(url, key) {
|
|
7529
|
+
return queryBearerBalance(url, key, "xAI", "xAI", (data) => {
|
|
7056
7530
|
const cents = toNumber$1(data.total?.val);
|
|
7057
7531
|
const totalBalance = cents === void 0 ? void 0 : Math.abs(cents) / 100;
|
|
7058
7532
|
return {
|
|
@@ -7085,11 +7559,10 @@ function pickTokenDanceBalanceCny(data) {
|
|
|
7085
7559
|
/**
|
|
7086
7560
|
* 查询 TokenDance Space 钱包余额(issue #26/#27)。`queryBearerBalance` 已覆盖
|
|
7087
7561
|
* 认证失败(401 → unauthorized)与熔断/超时/重试,这里只负责微元 → 元换算。
|
|
7088
|
-
* @param
|
|
7089
|
-
* @param apiKeyEnv - credential reference resolving the TokenDance API key.
|
|
7562
|
+
* @param key - resolved credential for this query.
|
|
7090
7563
|
*/
|
|
7091
|
-
function queryTokenDance(
|
|
7092
|
-
return queryBearerBalance(
|
|
7564
|
+
function queryTokenDance(url, key) {
|
|
7565
|
+
return queryBearerBalance(url, key, "TokenDance", "TokenDance", (data) => {
|
|
7093
7566
|
const cny = pickTokenDanceBalanceCny(data);
|
|
7094
7567
|
return {
|
|
7095
7568
|
provider: "TokenDance",
|
|
@@ -7104,12 +7577,11 @@ function queryTokenDance(ctx, apiKeyEnv) {
|
|
|
7104
7577
|
* 与订阅(zai-coding-cn 的 Coding Plan)互补:一个平台可同时有钱包余额与订阅
|
|
7105
7578
|
* 套餐,两者各读各的(TokenLedger 同款双读姿态)。Z.ai global 域币种为 USD,
|
|
7106
7579
|
* 本函数固定走国内 CNY 域(open.bigmodel.cn),币种不猜,仅覆盖国内域。
|
|
7107
|
-
* @param
|
|
7108
|
-
* @param apiKeyEnv - credential reference resolving the Zhipu API key.
|
|
7580
|
+
* @param key - resolved credential for this query.
|
|
7109
7581
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
7110
7582
|
*/
|
|
7111
|
-
function queryZhipu(
|
|
7112
|
-
return queryBearerBalance(
|
|
7583
|
+
function queryZhipu(url, key) {
|
|
7584
|
+
return queryBearerBalance(url, key, "智谱 AI", "智谱 AI", (data) => {
|
|
7113
7585
|
const doc = data;
|
|
7114
7586
|
const totalBalance = toNumber$1(doc.balance?.available) ?? toNumber$1(doc.balance?.total);
|
|
7115
7587
|
return {
|
|
@@ -7120,71 +7592,51 @@ function queryZhipu(ctx, apiKeyEnv) {
|
|
|
7120
7592
|
};
|
|
7121
7593
|
});
|
|
7122
7594
|
}
|
|
7595
|
+
function bearer(route, displayName, endpoint, query) {
|
|
7596
|
+
return {
|
|
7597
|
+
route,
|
|
7598
|
+
displayName,
|
|
7599
|
+
endpoint,
|
|
7600
|
+
query: (key) => query(endpoint, key)
|
|
7601
|
+
};
|
|
7602
|
+
}
|
|
7123
7603
|
const QUERIERS = [
|
|
7604
|
+
bearer("deepseek", "deepseek", DEEPSEEK_BALANCE_URL, queryDeepSeek),
|
|
7124
7605
|
{
|
|
7125
|
-
route:
|
|
7606
|
+
route: DEEPSEEK_PLATFORM_ROUTE,
|
|
7126
7607
|
displayName: "deepseek",
|
|
7127
|
-
|
|
7128
|
-
|
|
7129
|
-
|
|
7130
|
-
|
|
7131
|
-
|
|
7132
|
-
|
|
7133
|
-
|
|
7134
|
-
|
|
7135
|
-
|
|
7136
|
-
|
|
7137
|
-
|
|
7138
|
-
|
|
7139
|
-
|
|
7140
|
-
route: "siliconflow",
|
|
7141
|
-
displayName: "硅基流动",
|
|
7142
|
-
querier: querySiliconFlow
|
|
7143
|
-
},
|
|
7144
|
-
{
|
|
7145
|
-
route: "xai",
|
|
7146
|
-
displayName: "xAI",
|
|
7147
|
-
querier: queryXai
|
|
7148
|
-
},
|
|
7149
|
-
{
|
|
7150
|
-
route: "zhipu",
|
|
7151
|
-
displayName: "智谱 AI",
|
|
7152
|
-
querier: queryZhipu
|
|
7153
|
-
},
|
|
7154
|
-
{
|
|
7155
|
-
route: "zai-coding-cn",
|
|
7156
|
-
displayName: "智谱 AI",
|
|
7157
|
-
querier: queryZhipu
|
|
7158
|
-
},
|
|
7159
|
-
{
|
|
7160
|
-
route: "tokendance",
|
|
7161
|
-
displayName: "TokenDance",
|
|
7162
|
-
querier: queryTokenDance
|
|
7163
|
-
},
|
|
7164
|
-
{
|
|
7165
|
-
route: "tokendance-space",
|
|
7166
|
-
displayName: "TokenDance",
|
|
7167
|
-
querier: queryTokenDance
|
|
7168
|
-
},
|
|
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),
|
|
7169
7621
|
{
|
|
7170
7622
|
route: "tencent-tokenhub",
|
|
7171
7623
|
displayName: "腾讯云 TokenHub",
|
|
7172
|
-
|
|
7624
|
+
query: queryTencentTokenPlan
|
|
7173
7625
|
},
|
|
7174
7626
|
{
|
|
7175
7627
|
route: "tokenhub",
|
|
7176
7628
|
displayName: "腾讯云 TokenHub",
|
|
7177
|
-
|
|
7629
|
+
query: queryTencentTokenPlan
|
|
7178
7630
|
},
|
|
7179
7631
|
{
|
|
7180
7632
|
route: "tencent",
|
|
7181
7633
|
displayName: "腾讯云 TokenHub",
|
|
7182
|
-
|
|
7634
|
+
query: queryTencentTokenPlan
|
|
7183
7635
|
},
|
|
7184
7636
|
{
|
|
7185
7637
|
route: "tencentcloud",
|
|
7186
7638
|
displayName: "腾讯云 TokenHub",
|
|
7187
|
-
|
|
7639
|
+
query: queryTencentTokenPlan
|
|
7188
7640
|
}
|
|
7189
7641
|
];
|
|
7190
7642
|
/**
|
|
@@ -7195,9 +7647,11 @@ const QUERIERS = [
|
|
|
7195
7647
|
* dashboard shows a stable state instead of dropping the row.
|
|
7196
7648
|
* @param ctx - host context carrying the credentials seam.
|
|
7197
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).
|
|
7198
7652
|
* @returns the balance rows (one per provider).
|
|
7199
7653
|
*/
|
|
7200
|
-
async function queryBalances(ctx, providers) {
|
|
7654
|
+
async function queryBalances(ctx, providers, client, options) {
|
|
7201
7655
|
const resolveRef = async (name) => {
|
|
7202
7656
|
try {
|
|
7203
7657
|
const hit = await ctx.credentials.resolve(credentialRef(name));
|
|
@@ -7206,57 +7660,89 @@ async function queryBalances(ctx, providers) {
|
|
|
7206
7660
|
return;
|
|
7207
7661
|
}
|
|
7208
7662
|
};
|
|
7209
|
-
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;
|
|
7210
7675
|
const env = providers[route]?.apiKeyEnv;
|
|
7211
|
-
const
|
|
7212
|
-
|
|
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;
|
|
7213
7685
|
return {
|
|
7214
|
-
|
|
7215
|
-
|
|
7216
|
-
|
|
7217
|
-
|
|
7686
|
+
...spec,
|
|
7687
|
+
key: hit?.value,
|
|
7688
|
+
expectedOrigin,
|
|
7689
|
+
verified
|
|
7218
7690
|
};
|
|
7219
7691
|
}));
|
|
7220
|
-
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 = [];
|
|
7221
7695
|
for (const item of resolved) {
|
|
7222
|
-
|
|
7223
|
-
|
|
7224
|
-
|
|
7225
|
-
|
|
7226
|
-
|
|
7227
|
-
|
|
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: []
|
|
7228
7702
|
});
|
|
7229
7703
|
}
|
|
7230
|
-
|
|
7231
|
-
|
|
7704
|
+
const apiRows = await Promise.all(targets.map(async ({ route, displayName, query, key, aliases, expectedOrigin, verified }) => {
|
|
7705
|
+
const row = key === void 0 ? {
|
|
7232
7706
|
provider: displayName,
|
|
7233
7707
|
displayName,
|
|
7234
7708
|
error: "unconfigured"
|
|
7235
|
-
});
|
|
7236
|
-
|
|
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;
|
|
7237
7728
|
}));
|
|
7729
|
+
const account = await queryDeepSeekAccount(ctx, client);
|
|
7730
|
+
return [...apiRows, account];
|
|
7238
7731
|
}
|
|
7239
7732
|
/**
|
|
7240
7733
|
* 查询腾讯云 TokenHub Token Plan 套餐余量。凭据值格式 `<SecretId>:<SecretKey>`
|
|
7241
7734
|
* (云 API 密钥,非 TokenHub 推理 key)。链路:套餐列表取 TeamId → 套餐详情读
|
|
7242
7735
|
* 主额度包余量。管控面字段名未完全稳定,解析按语义键防御提取。
|
|
7243
|
-
* @param
|
|
7244
|
-
* @param apiKeyEnv - credential reference resolving the `<SecretId>:<SecretKey>` pair.
|
|
7736
|
+
* @param key - resolved credential for this query.
|
|
7245
7737
|
*/
|
|
7246
|
-
async function queryTencentTokenPlan(
|
|
7738
|
+
async function queryTencentTokenPlan(key) {
|
|
7247
7739
|
const provider = "腾讯云 TokenHub";
|
|
7248
|
-
const hit = await ctx.credentials.resolve(credentialRef(apiKeyEnv));
|
|
7249
|
-
if (hit === void 0) return {
|
|
7250
|
-
provider,
|
|
7251
|
-
displayName: provider,
|
|
7252
|
-
error: "unconfigured"
|
|
7253
|
-
};
|
|
7254
7740
|
if (!balanceGate.check(provider)) return {
|
|
7255
7741
|
provider,
|
|
7256
7742
|
displayName: provider,
|
|
7257
7743
|
error: "unreachable"
|
|
7258
7744
|
};
|
|
7259
|
-
const credential = parseTencentCredential(
|
|
7745
|
+
const credential = parseTencentCredential(key);
|
|
7260
7746
|
if (credential === void 0) return {
|
|
7261
7747
|
provider,
|
|
7262
7748
|
displayName: provider,
|
|
@@ -7485,7 +7971,7 @@ async function queryCustomBalances(ctx, configs) {
|
|
|
7485
7971
|
/** Abort a declared fetch when the upstream hangs beyond this budget. */
|
|
7486
7972
|
const FETCH_TIMEOUT_MS$2 = 8e3;
|
|
7487
7973
|
/** 响应体上限(字节):坏 / 恶意端点不能拖住面板或耗尽内存。 */
|
|
7488
|
-
const MAX_BODY_BYTES = 1e6;
|
|
7974
|
+
const MAX_BODY_BYTES$1 = 1e6;
|
|
7489
7975
|
/** 声明端点查询的熔断门:按(匹配 provider origin + path)独立熔断,各端点互不干扰。 */
|
|
7490
7976
|
const declaredGate = createCooldownGate({
|
|
7491
7977
|
failures: 3,
|
|
@@ -7629,42 +8115,40 @@ async function queryDeclaredEndpoints(ctx, providers, declarations) {
|
|
|
7629
8115
|
return await Promise.all(declarations.map(async (decl) => {
|
|
7630
8116
|
const displayName = typeof decl.displayName === "string" && decl.displayName !== "" ? decl.displayName : "已声明";
|
|
7631
8117
|
const provider = `declared:${displayName}`;
|
|
7632
|
-
const
|
|
7633
|
-
|
|
8118
|
+
const declOrigin = normalizeDeclaredOrigin(decl.origin);
|
|
8119
|
+
const matched = declOrigin === void 0 ? void 0 : byOrigin.get(declOrigin);
|
|
8120
|
+
const identity = {
|
|
7634
8121
|
provider,
|
|
7635
8122
|
displayName,
|
|
7636
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,
|
|
7637
8131
|
error: "invalid",
|
|
7638
8132
|
reason: "path 必须单斜杠绝对路径"
|
|
7639
8133
|
};
|
|
7640
|
-
const declOrigin = normalizeDeclaredOrigin(decl.origin);
|
|
7641
|
-
const matched = declOrigin === void 0 ? void 0 : byOrigin.get(declOrigin);
|
|
7642
8134
|
if (matched === void 0) return {
|
|
7643
|
-
|
|
7644
|
-
displayName,
|
|
7645
|
-
declared: true,
|
|
8135
|
+
...identity,
|
|
7646
8136
|
error: "unconfigured",
|
|
7647
8137
|
reason: "未匹配到同源 provider(需先在 llm-pi-ai 配好 baseURL)"
|
|
7648
8138
|
};
|
|
7649
8139
|
const gateKey = `${declOrigin}${requestPath}`;
|
|
7650
8140
|
if (!declaredGate.check(gateKey)) return {
|
|
7651
|
-
|
|
7652
|
-
displayName,
|
|
7653
|
-
declared: true,
|
|
8141
|
+
...identity,
|
|
7654
8142
|
error: "unreachable"
|
|
7655
8143
|
};
|
|
7656
8144
|
const hit = await firstResolvedRef([...matched.apiKeyEnv !== void 0 ? [matched.apiKeyEnv] : [], ...routeKeyRefCandidates(matched.route)], resolveRef);
|
|
7657
8145
|
if (hit === void 0) return {
|
|
7658
|
-
|
|
7659
|
-
displayName,
|
|
7660
|
-
declared: true,
|
|
8146
|
+
...identity,
|
|
7661
8147
|
error: "unconfigured"
|
|
7662
8148
|
};
|
|
7663
8149
|
const url = new URL(requestPath, declOrigin);
|
|
7664
8150
|
if (url.origin !== declOrigin) return {
|
|
7665
|
-
|
|
7666
|
-
displayName,
|
|
7667
|
-
declared: true,
|
|
8151
|
+
...identity,
|
|
7668
8152
|
error: "invalid",
|
|
7669
8153
|
reason: "跨源路径被拒绝"
|
|
7670
8154
|
};
|
|
@@ -7680,9 +8164,7 @@ async function queryDeclaredEndpoints(ctx, providers, declarations) {
|
|
|
7680
8164
|
declaredGate.success(gateKey);
|
|
7681
8165
|
const nothingResolved = total === void 0 && granted === void 0 && used === void 0 && windows.length === 0;
|
|
7682
8166
|
return {
|
|
7683
|
-
|
|
7684
|
-
displayName,
|
|
7685
|
-
declared: true,
|
|
8167
|
+
...identity,
|
|
7686
8168
|
...total !== void 0 ? { totalBalance: total } : {},
|
|
7687
8169
|
...granted !== void 0 ? { grantedBalance: granted } : {},
|
|
7688
8170
|
...typeof currency === "string" && currency !== "" ? { currency } : {},
|
|
@@ -7696,9 +8178,7 @@ async function queryDeclaredEndpoints(ctx, providers, declarations) {
|
|
|
7696
8178
|
} catch {
|
|
7697
8179
|
declaredGate.fail(gateKey);
|
|
7698
8180
|
return {
|
|
7699
|
-
|
|
7700
|
-
displayName,
|
|
7701
|
-
declared: true,
|
|
8181
|
+
...identity,
|
|
7702
8182
|
error: "unreachable"
|
|
7703
8183
|
};
|
|
7704
8184
|
}
|
|
@@ -7726,7 +8206,7 @@ async function fetchDeclaredBody(url, raw, apiKey) {
|
|
|
7726
8206
|
if (response.status === 401 || response.status === 403) throw new HttpStatusError("unauthorized", response.status);
|
|
7727
8207
|
if (!response.ok) throw new HttpStatusError("http-error", response.status);
|
|
7728
8208
|
const text = await response.text();
|
|
7729
|
-
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);
|
|
7730
8210
|
try {
|
|
7731
8211
|
return JSON.parse(text);
|
|
7732
8212
|
} catch (cause) {
|
|
@@ -7765,6 +8245,30 @@ var HttpStatusError = class extends Error {
|
|
|
7765
8245
|
*
|
|
7766
8246
|
* 纯函数:输入上一基准与本次余额查询结果,输出新基准与对账事件,可独立单测。
|
|
7767
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
|
+
}
|
|
7768
8272
|
/** 余额差对账阈值下限(元):消费低于该值时不值得提示,避免小金额波动刷屏。 */
|
|
7769
8273
|
const MIN_DRIFT_ABS = .3;
|
|
7770
8274
|
/** 余额差相对容忍度:偏差超过较大一方的该比例才判漂移。 */
|
|
@@ -7799,23 +8303,27 @@ function snapOf(ref, balance, nowMs) {
|
|
|
7799
8303
|
* @param todayOfficialCost - 本地账本当日的官方渠道费用(CNY)。
|
|
7800
8304
|
* @param dayKey - 本地日期键(YYYY-MM-DD)。
|
|
7801
8305
|
* @param nowMs - 当前时刻(epoch ms)。
|
|
7802
|
-
* @returns 新基准与对账事件;余额不可用(无 totalBalance)时返回 `{ ref:
|
|
8306
|
+
* @returns 新基准与对账事件;余额不可用(无 totalBalance)时返回 `{ ref: null, event: null }`。
|
|
7803
8307
|
*/
|
|
7804
|
-
function reconcileBalanceDelta(prevRef, balance, todayOfficialCost, dayKey, nowMs) {
|
|
8308
|
+
function reconcileBalanceDelta(prevRef, balance, todayOfficialCost, dayKey, nowMs, source = "deepseek") {
|
|
7805
8309
|
const total = balance.totalBalance;
|
|
7806
8310
|
if (typeof total !== "number" || !Number.isFinite(total)) return {
|
|
7807
|
-
ref:
|
|
8311
|
+
ref: null,
|
|
7808
8312
|
event: null
|
|
7809
8313
|
};
|
|
7810
|
-
const snap =
|
|
7811
|
-
|
|
7812
|
-
|
|
7813
|
-
|
|
7814
|
-
|
|
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 {
|
|
7815
8323
|
ref: snap,
|
|
7816
8324
|
event: { kind: "baseline" }
|
|
7817
8325
|
};
|
|
7818
|
-
if (prevRef.currency !== snap.currency) return {
|
|
8326
|
+
if (prevRef.currency !== snap.currency || todayOfficialCost < prevRef.costAtBaseline || snap.total > prevRef.total + .009) return {
|
|
7819
8327
|
ref: snap,
|
|
7820
8328
|
event: { kind: "structure-reset" }
|
|
7821
8329
|
};
|
|
@@ -7828,7 +8336,7 @@ function reconcileBalanceDelta(prevRef, balance, todayOfficialCost, dayKey, nowM
|
|
|
7828
8336
|
ref: prevRef,
|
|
7829
8337
|
event: { kind: "flat" }
|
|
7830
8338
|
};
|
|
7831
|
-
const cost =
|
|
8339
|
+
const cost = todayOfficialCost - prevRef.costAtBaseline;
|
|
7832
8340
|
if (Math.abs(spent - cost) > Math.max(MIN_DRIFT_ABS, DRIFT_RELATIVE * Math.max(spent, cost))) return {
|
|
7833
8341
|
ref: prevRef,
|
|
7834
8342
|
event: {
|
|
@@ -9671,6 +10179,312 @@ function guardLoopback(req, res, trustedHosts = /* @__PURE__ */ new Set()) {
|
|
|
9671
10179
|
return true;
|
|
9672
10180
|
}
|
|
9673
10181
|
//#endregion
|
|
10182
|
+
//#region lib/types/peak-schedule-store.js
|
|
10183
|
+
const emptyHistory = () => ({
|
|
10184
|
+
version: 3,
|
|
10185
|
+
revisions: []
|
|
10186
|
+
});
|
|
10187
|
+
var ScheduleClockConflict = class extends Error {};
|
|
10188
|
+
function readSaved(path) {
|
|
10189
|
+
let bytes;
|
|
10190
|
+
try {
|
|
10191
|
+
bytes = readFileSync(path);
|
|
10192
|
+
} catch (error) {
|
|
10193
|
+
return {
|
|
10194
|
+
history: emptyHistory(),
|
|
10195
|
+
notices: error.code === "ENOENT" ? [] : [{ code: "unreadableSchedule" }]
|
|
10196
|
+
};
|
|
10197
|
+
}
|
|
10198
|
+
try {
|
|
10199
|
+
return {
|
|
10200
|
+
...readScheduleHistory(JSON.parse(bytes.toString("utf8"))),
|
|
10201
|
+
bytes
|
|
10202
|
+
};
|
|
10203
|
+
} catch {
|
|
10204
|
+
return {
|
|
10205
|
+
history: emptyHistory(),
|
|
10206
|
+
notices: [{ code: "malformedSchedule" }],
|
|
10207
|
+
bytes
|
|
10208
|
+
};
|
|
10209
|
+
}
|
|
10210
|
+
}
|
|
10211
|
+
/** Drop only writes that repeat the immediately preceding state of that key.
|
|
10212
|
+
* A→B→A and deletions after a real override remain distinct historical intervals. */
|
|
10213
|
+
function compact(history) {
|
|
10214
|
+
const state = /* @__PURE__ */ new Map();
|
|
10215
|
+
return {
|
|
10216
|
+
version: 3,
|
|
10217
|
+
revisions: history.revisions.flatMap((row) => {
|
|
10218
|
+
const changes = Object.fromEntries(Object.entries(row.changes).filter(([key, rule]) => {
|
|
10219
|
+
const value = JSON.stringify(rule);
|
|
10220
|
+
if ((state.get(key) ?? "null") === value) return false;
|
|
10221
|
+
state.set(key, value);
|
|
10222
|
+
return true;
|
|
10223
|
+
}));
|
|
10224
|
+
return Object.keys(changes).length ? [{
|
|
10225
|
+
...row,
|
|
10226
|
+
changes
|
|
10227
|
+
}] : [];
|
|
10228
|
+
})
|
|
10229
|
+
};
|
|
10230
|
+
}
|
|
10231
|
+
function openScheduleStore(path, eligible, now = Date.now) {
|
|
10232
|
+
let saved = readSaved(path);
|
|
10233
|
+
function project() {
|
|
10234
|
+
const config = emptySchedule();
|
|
10235
|
+
const skipped = /* @__PURE__ */ new Set();
|
|
10236
|
+
for (const { changes } of saved.history.revisions) for (const [key, rule] of Object.entries(changes)) if (rule === null) {
|
|
10237
|
+
delete config.models[key];
|
|
10238
|
+
skipped.delete(key);
|
|
10239
|
+
} else if (eligible(modelFromScheduleKey(key))) config.models[key] = rule;
|
|
10240
|
+
else skipped.add(key);
|
|
10241
|
+
return {
|
|
10242
|
+
config,
|
|
10243
|
+
notices: [...saved.notices, ...Array.from(skipped, (detail) => ({
|
|
10244
|
+
code: "ineligibleModel",
|
|
10245
|
+
detail
|
|
10246
|
+
}))]
|
|
10247
|
+
};
|
|
10248
|
+
}
|
|
10249
|
+
let active = project();
|
|
10250
|
+
let queue = Promise.resolve();
|
|
10251
|
+
return {
|
|
10252
|
+
current: () => active.config,
|
|
10253
|
+
history: () => saved.history,
|
|
10254
|
+
notices: () => active.notices,
|
|
10255
|
+
save(edit, latestEventTime = -1) {
|
|
10256
|
+
const commit = queue.then(async () => {
|
|
10257
|
+
const { changes } = parseScheduleEdit(edit);
|
|
10258
|
+
mkdirSync(dirname(path), {
|
|
10259
|
+
recursive: true,
|
|
10260
|
+
mode: 448
|
|
10261
|
+
});
|
|
10262
|
+
await withFileLock(path, async () => {
|
|
10263
|
+
const previous = readSaved(path);
|
|
10264
|
+
if (previous.notices.some((n) => n.code === "unreadableSchedule")) throw Error("Schedule unavailable");
|
|
10265
|
+
const revisions = previous.history.revisions;
|
|
10266
|
+
const delta = Object.fromEntries(Object.entries(changes).filter(([key, rule]) => {
|
|
10267
|
+
const latest = revisions.findLast((row) => Object.hasOwn(row.changes, key))?.changes[key] ?? null;
|
|
10268
|
+
return JSON.stringify(latest) !== JSON.stringify(rule);
|
|
10269
|
+
}));
|
|
10270
|
+
if (!Object.keys(delta).length) {
|
|
10271
|
+
if (previous.bytes?.equals(saved.bytes ?? Buffer.alloc(0)) === false) {
|
|
10272
|
+
saved = previous;
|
|
10273
|
+
active = project();
|
|
10274
|
+
}
|
|
10275
|
+
return;
|
|
10276
|
+
}
|
|
10277
|
+
if (previous.bytes !== void 0) {
|
|
10278
|
+
await writeFileAtomic(`${path}.bak`, previous.bytes, {
|
|
10279
|
+
mode: 384,
|
|
10280
|
+
dirMode: 448
|
|
10281
|
+
});
|
|
10282
|
+
if (previous.notices.length) {
|
|
10283
|
+
const hash = createHash("sha256").update(previous.bytes).digest("hex");
|
|
10284
|
+
await writeFileAtomic(`${path}.recovery-${hash}`, previous.bytes, {
|
|
10285
|
+
mode: 384,
|
|
10286
|
+
dirMode: 448
|
|
10287
|
+
});
|
|
10288
|
+
}
|
|
10289
|
+
}
|
|
10290
|
+
const savedAt = now();
|
|
10291
|
+
const lastRevision = revisions.at(-1)?.effectiveFromMs ?? -1;
|
|
10292
|
+
if (savedAt < lastRevision || savedAt <= latestEventTime) throw new ScheduleClockConflict("scheduleClockConflict");
|
|
10293
|
+
const effectiveFromMs = Math.max(savedAt, lastRevision + 1);
|
|
10294
|
+
if (!Number.isSafeInteger(effectiveFromMs) || effectiveFromMs < 0 || effectiveFromMs > 864e13) throw Error("Invalid schedule clock");
|
|
10295
|
+
const history = compact({
|
|
10296
|
+
version: 3,
|
|
10297
|
+
revisions: [...revisions, {
|
|
10298
|
+
effectiveFromMs,
|
|
10299
|
+
changes: delta,
|
|
10300
|
+
audit: {
|
|
10301
|
+
source: "local-api",
|
|
10302
|
+
actor: "unidentified"
|
|
10303
|
+
}
|
|
10304
|
+
}]
|
|
10305
|
+
});
|
|
10306
|
+
const json = JSON.stringify(history);
|
|
10307
|
+
await writeFileAtomic(path, json, {
|
|
10308
|
+
mode: 384,
|
|
10309
|
+
dirMode: 448
|
|
10310
|
+
});
|
|
10311
|
+
saved = {
|
|
10312
|
+
history,
|
|
10313
|
+
notices: [],
|
|
10314
|
+
bytes: Buffer.from(json)
|
|
10315
|
+
};
|
|
10316
|
+
active = project();
|
|
10317
|
+
}, { waitMs: 2e3 });
|
|
10318
|
+
});
|
|
10319
|
+
queue = commit.catch(() => {});
|
|
10320
|
+
return commit;
|
|
10321
|
+
}
|
|
10322
|
+
};
|
|
10323
|
+
}
|
|
10324
|
+
//#endregion
|
|
10325
|
+
//#region lib/types/routes/peak-schedule.js
|
|
10326
|
+
/** Domain validation failures are distinct from storage failures. */
|
|
10327
|
+
var PeakScheduleInputError = class extends Error {};
|
|
10328
|
+
const MAX_BODY_BYTES = 1048576;
|
|
10329
|
+
function reply(res, status, value) {
|
|
10330
|
+
res.writeHead(status, {
|
|
10331
|
+
"content-type": "application/json; charset=utf-8",
|
|
10332
|
+
"cache-control": "no-store"
|
|
10333
|
+
});
|
|
10334
|
+
res.end(JSON.stringify(value));
|
|
10335
|
+
}
|
|
10336
|
+
function registerPeakScheduleRoute(ctx, deps) {
|
|
10337
|
+
ctx.effect(() => ctx.webServer.register({
|
|
10338
|
+
kind: "exact",
|
|
10339
|
+
path: "/api/billing/peak-schedule",
|
|
10340
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
10341
|
+
handler: async (req, res) => {
|
|
10342
|
+
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
10343
|
+
let raw;
|
|
10344
|
+
if (req.method === "POST") {
|
|
10345
|
+
if (!isLoopbackOrigin(req.headers.origin)) return reply(res, 403, {
|
|
10346
|
+
error: "forbidden: loopback only",
|
|
10347
|
+
message: "仅限本机请求"
|
|
10348
|
+
});
|
|
10349
|
+
if (req.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") return reply(res, 415, {
|
|
10350
|
+
error: "unsupported content-type",
|
|
10351
|
+
message: "请使用 application/json"
|
|
10352
|
+
});
|
|
10353
|
+
const chunks = [];
|
|
10354
|
+
let bytes = 0;
|
|
10355
|
+
try {
|
|
10356
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
10357
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
10358
|
+
bytes += buf.length;
|
|
10359
|
+
if (bytes > MAX_BODY_BYTES) {
|
|
10360
|
+
req.resume();
|
|
10361
|
+
return reply(res, 413, {
|
|
10362
|
+
error: "body too large",
|
|
10363
|
+
message: "请求体过大"
|
|
10364
|
+
});
|
|
10365
|
+
}
|
|
10366
|
+
chunks.push(buf);
|
|
10367
|
+
}
|
|
10368
|
+
raw = JSON.parse(Buffer.concat(chunks, bytes).toString("utf8"));
|
|
10369
|
+
} catch {
|
|
10370
|
+
return reply(res, 400, {
|
|
10371
|
+
error: "invalid json body",
|
|
10372
|
+
message: "请求 JSON 无效"
|
|
10373
|
+
});
|
|
10374
|
+
}
|
|
10375
|
+
}
|
|
10376
|
+
let snapshot;
|
|
10377
|
+
try {
|
|
10378
|
+
snapshot = req.method === "POST" ? await deps.save(raw) : await deps.read();
|
|
10379
|
+
} catch (error) {
|
|
10380
|
+
if (req.method === "POST" && error instanceof PeakScheduleInputError) return reply(res, 400, {
|
|
10381
|
+
error: error.message,
|
|
10382
|
+
message: "峰谷设置格式无效 / Invalid schedule format"
|
|
10383
|
+
});
|
|
10384
|
+
if (req.method === "POST" && error instanceof ScheduleClockConflict) return reply(res, 409, {
|
|
10385
|
+
error: "scheduleClockConflict",
|
|
10386
|
+
message: "生效时刻早于已记录的调用或修订 / Schedule clock conflict"
|
|
10387
|
+
});
|
|
10388
|
+
return reply(res, 503, {
|
|
10389
|
+
error: "peak schedule unavailable",
|
|
10390
|
+
message: "峰谷设置暂不可用"
|
|
10391
|
+
});
|
|
10392
|
+
}
|
|
10393
|
+
reply(res, 200, snapshot);
|
|
10394
|
+
}
|
|
10395
|
+
}), "usage-billing: peak-schedule route");
|
|
10396
|
+
}
|
|
10397
|
+
//#endregion
|
|
10398
|
+
//#region lib/types/peak-schedule-models.js
|
|
10399
|
+
async function discover$1(llm, route) {
|
|
10400
|
+
if (!llm?.listModels) throw Error("Model registry unavailable");
|
|
10401
|
+
let timer;
|
|
10402
|
+
try {
|
|
10403
|
+
const models = await Promise.race([llm.listModels(route), new Promise((_, reject) => {
|
|
10404
|
+
timer = setTimeout(() => reject(Error("Model discovery timed out")), 5e3);
|
|
10405
|
+
})]);
|
|
10406
|
+
if (!Array.isArray(models)) throw Error("Invalid model registry response");
|
|
10407
|
+
return models;
|
|
10408
|
+
} finally {
|
|
10409
|
+
clearTimeout(timer);
|
|
10410
|
+
}
|
|
10411
|
+
}
|
|
10412
|
+
function eligibleScheduleModel(key) {
|
|
10413
|
+
const entry = modelOf(key);
|
|
10414
|
+
return key === entry.key && entry.provider === "DeepSeek" && entry.price.offPeak !== void 0 && entry.tierSemantics !== "latency";
|
|
10415
|
+
}
|
|
10416
|
+
/** Cache only remote discovery. Route identity and locally declared models are refreshed every request. */
|
|
10417
|
+
function createScheduleModelDiscovery(now = Date.now, ttlMs = 6e4) {
|
|
10418
|
+
const cache = /* @__PURE__ */ new Map();
|
|
10419
|
+
let service;
|
|
10420
|
+
function listModels(llm, id, baseURL) {
|
|
10421
|
+
const key = JSON.stringify([id, baseURL]);
|
|
10422
|
+
const hit = cache.get(key);
|
|
10423
|
+
if (hit && hit.expires > now()) return hit.result;
|
|
10424
|
+
const entry = {
|
|
10425
|
+
expires: Infinity,
|
|
10426
|
+
result: discover$1(llm, id)
|
|
10427
|
+
};
|
|
10428
|
+
cache.set(key, entry);
|
|
10429
|
+
entry.result.then(() => {
|
|
10430
|
+
entry.expires = now() + ttlMs;
|
|
10431
|
+
}, () => {
|
|
10432
|
+
entry.expires = now() + Math.min(ttlMs, 15e3);
|
|
10433
|
+
});
|
|
10434
|
+
return entry.result;
|
|
10435
|
+
}
|
|
10436
|
+
return async (llm, profiles, aliases) => {
|
|
10437
|
+
if (service !== llm) {
|
|
10438
|
+
cache.clear();
|
|
10439
|
+
service = llm;
|
|
10440
|
+
}
|
|
10441
|
+
const routes = /* @__PURE__ */ new Map();
|
|
10442
|
+
const notices = [];
|
|
10443
|
+
try {
|
|
10444
|
+
if (!llm?.listProviders) throw Error();
|
|
10445
|
+
for (const p of llm.listProviders()) if (typeof p.id === "string") routes.set(p.id, p.name || p.id);
|
|
10446
|
+
} catch {
|
|
10447
|
+
notices.push({ code: "discoveryFailed" });
|
|
10448
|
+
}
|
|
10449
|
+
const views = { ...profiles };
|
|
10450
|
+
for (const id of routes.keys()) if (!Object.hasOwn(views, id)) views[id] = {};
|
|
10451
|
+
for (const [id, profile] of Object.entries(profiles)) if (profile.models) routes.set(id, profile.displayName || id);
|
|
10452
|
+
const liveCacheKeys = new Set([...routes.keys()].map((id) => JSON.stringify([id, profiles[id]?.baseURL])));
|
|
10453
|
+
for (const key of cache.keys()) if (!liveCacheKeys.has(key)) cache.delete(key);
|
|
10454
|
+
const rows = /* @__PURE__ */ new Map();
|
|
10455
|
+
await Promise.all([...routes].map(async ([id, label]) => {
|
|
10456
|
+
const mapped = aliases[id] ?? id;
|
|
10457
|
+
if (accountRoute(id) || accountRoute(mapped)) return;
|
|
10458
|
+
const source = siteBucketKey(siteRefOf(mapped, views));
|
|
10459
|
+
if (!validSource(source)) return;
|
|
10460
|
+
let models;
|
|
10461
|
+
try {
|
|
10462
|
+
models = profiles[id]?.models ?? await listModels(llm, id, profiles[id]?.baseURL);
|
|
10463
|
+
} catch {
|
|
10464
|
+
notices.push({
|
|
10465
|
+
code: "discoveryFailed",
|
|
10466
|
+
detail: id
|
|
10467
|
+
});
|
|
10468
|
+
return;
|
|
10469
|
+
}
|
|
10470
|
+
for (const item of models) {
|
|
10471
|
+
const raw = typeof item === "string" ? item : item?.id;
|
|
10472
|
+
if (typeof raw !== "string") continue;
|
|
10473
|
+
const model = resolveCatalogKey(raw);
|
|
10474
|
+
if (eligibleScheduleModel(model)) rows.set(scheduleKey(source, model), {
|
|
10475
|
+
source,
|
|
10476
|
+
model,
|
|
10477
|
+
label: `${source} / ${modelOf(model).name} (${label})`
|
|
10478
|
+
});
|
|
10479
|
+
}
|
|
10480
|
+
}));
|
|
10481
|
+
return {
|
|
10482
|
+
models: [...rows.values()].sort((a, b) => a.label.localeCompare(b.label)),
|
|
10483
|
+
notices
|
|
10484
|
+
};
|
|
10485
|
+
};
|
|
10486
|
+
}
|
|
10487
|
+
//#endregion
|
|
9674
10488
|
//#region lib/types/routes/notify-claim.js
|
|
9675
10489
|
/**
|
|
9676
10490
|
* 路由:POST /api/billing/notify-claim
|
|
@@ -9754,6 +10568,136 @@ function registerNotifyClaimRoute(ctx, deps) {
|
|
|
9754
10568
|
}), "usage-billing: notify-claim route");
|
|
9755
10569
|
}
|
|
9756
10570
|
//#endregion
|
|
10571
|
+
//#region lib/types/routes/pricing-models.js
|
|
10572
|
+
const JSON_HEADERS$1 = {
|
|
10573
|
+
"content-type": "application/json; charset=utf-8",
|
|
10574
|
+
"cache-control": "no-store"
|
|
10575
|
+
};
|
|
10576
|
+
const MODEL_CACHE_MS = 6e4;
|
|
10577
|
+
const PARTIAL_MODEL_CACHE_MS = 15e3;
|
|
10578
|
+
async function discover(registry, route) {
|
|
10579
|
+
let timer;
|
|
10580
|
+
try {
|
|
10581
|
+
return await Promise.race([registry.listModels(route), new Promise((_, reject) => {
|
|
10582
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error("Model discovery timed out")), 5e3);
|
|
10583
|
+
})]);
|
|
10584
|
+
} finally {
|
|
10585
|
+
clearTimeout(timer);
|
|
10586
|
+
}
|
|
10587
|
+
}
|
|
10588
|
+
/** Static settings remain authoritative even when the registry is unavailable. */
|
|
10589
|
+
async function configuredPricingModels(ctx) {
|
|
10590
|
+
const routes = /* @__PURE__ */ new Map();
|
|
10591
|
+
let partial = false;
|
|
10592
|
+
let registry;
|
|
10593
|
+
const profiles = /* @__PURE__ */ new Map();
|
|
10594
|
+
try {
|
|
10595
|
+
const value = ctx.settings.describe({ redactSecrets: true }).find((item) => item.ns === "llm-pi-ai")?.value;
|
|
10596
|
+
for (const [id, profile] of Object.entries(value?.providers ?? {})) {
|
|
10597
|
+
if (!id.trim() || !profile || typeof profile !== "object" || Array.isArray(profile)) {
|
|
10598
|
+
partial = true;
|
|
10599
|
+
continue;
|
|
10600
|
+
}
|
|
10601
|
+
profiles.set(id, profile);
|
|
10602
|
+
routes.set(id, typeof profile.displayName === "string" && profile.displayName ? profile.displayName : id);
|
|
10603
|
+
}
|
|
10604
|
+
} catch {
|
|
10605
|
+
partial = true;
|
|
10606
|
+
}
|
|
10607
|
+
try {
|
|
10608
|
+
registry = ctx.get("llm");
|
|
10609
|
+
if (!registry) partial = true;
|
|
10610
|
+
for (const p of registry?.listProviders() ?? []) {
|
|
10611
|
+
if (typeof p?.id !== "string" || !p.id.trim()) {
|
|
10612
|
+
partial = true;
|
|
10613
|
+
continue;
|
|
10614
|
+
}
|
|
10615
|
+
const displayName = profiles.get(p.id)?.displayName;
|
|
10616
|
+
const fallback = typeof p.name === "string" && p.name ? p.name : p.id;
|
|
10617
|
+
routes.set(p.id, typeof displayName === "string" && displayName ? displayName : fallback);
|
|
10618
|
+
}
|
|
10619
|
+
} catch {
|
|
10620
|
+
partial = true;
|
|
10621
|
+
}
|
|
10622
|
+
return {
|
|
10623
|
+
models: (await Promise.all([...routes].map(async ([route, channel]) => {
|
|
10624
|
+
if (!route || route === "deepseek-account") return [];
|
|
10625
|
+
const profile = profiles.get(route);
|
|
10626
|
+
let origin = "";
|
|
10627
|
+
if (profile?.baseURL) try {
|
|
10628
|
+
const url = new URL(profile.baseURL);
|
|
10629
|
+
if (["https:", "http:"].includes(url.protocol) && !isOfficialBaseUrl(url.origin)) origin = url.origin;
|
|
10630
|
+
} catch {}
|
|
10631
|
+
function parse(list) {
|
|
10632
|
+
if (!Array.isArray(list)) {
|
|
10633
|
+
partial = true;
|
|
10634
|
+
return [];
|
|
10635
|
+
}
|
|
10636
|
+
const models = [];
|
|
10637
|
+
for (const m of list) {
|
|
10638
|
+
if (typeof m?.id !== "string" || !m.id.trim() || m.name !== void 0 && typeof m.name !== "string") {
|
|
10639
|
+
partial = true;
|
|
10640
|
+
continue;
|
|
10641
|
+
}
|
|
10642
|
+
models.push({
|
|
10643
|
+
key: m.id,
|
|
10644
|
+
name: m.name ?? m.id,
|
|
10645
|
+
route,
|
|
10646
|
+
channel,
|
|
10647
|
+
origin
|
|
10648
|
+
});
|
|
10649
|
+
}
|
|
10650
|
+
return models;
|
|
10651
|
+
}
|
|
10652
|
+
const declared = parse(profile?.models === void 0 ? [] : profile.models);
|
|
10653
|
+
if (declared.length || !registry) return declared;
|
|
10654
|
+
try {
|
|
10655
|
+
return parse(await discover(registry, route));
|
|
10656
|
+
} catch (error) {
|
|
10657
|
+
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;
|
|
10658
|
+
return [];
|
|
10659
|
+
}
|
|
10660
|
+
}))).flat(),
|
|
10661
|
+
partial
|
|
10662
|
+
};
|
|
10663
|
+
}
|
|
10664
|
+
function registerPricingModelsRoute(ctx, trustedHosts) {
|
|
10665
|
+
ctx.effect(() => {
|
|
10666
|
+
let cached;
|
|
10667
|
+
let expiresAt = 0;
|
|
10668
|
+
let inFlight;
|
|
10669
|
+
function load() {
|
|
10670
|
+
if (cached && Date.now() < expiresAt) return Promise.resolve(cached);
|
|
10671
|
+
return inFlight ??= configuredPricingModels(ctx).then((result) => {
|
|
10672
|
+
cached = result;
|
|
10673
|
+
expiresAt = Date.now() + (result.partial ? PARTIAL_MODEL_CACHE_MS : MODEL_CACHE_MS);
|
|
10674
|
+
return result;
|
|
10675
|
+
}).finally(() => {
|
|
10676
|
+
inFlight = void 0;
|
|
10677
|
+
});
|
|
10678
|
+
}
|
|
10679
|
+
return ctx.webServer.register({
|
|
10680
|
+
kind: "exact",
|
|
10681
|
+
path: "/api/billing/pricing-models",
|
|
10682
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
10683
|
+
async handler(req, res) {
|
|
10684
|
+
if (!guardLoopback(req, res, trustedHosts)) return;
|
|
10685
|
+
if (req.method !== "GET") {
|
|
10686
|
+
res.writeHead(405, {
|
|
10687
|
+
...JSON_HEADERS$1,
|
|
10688
|
+
allow: "GET"
|
|
10689
|
+
});
|
|
10690
|
+
res.end(JSON.stringify({ error: "method not allowed" }));
|
|
10691
|
+
return;
|
|
10692
|
+
}
|
|
10693
|
+
const body = await load();
|
|
10694
|
+
res.writeHead(200, JSON_HEADERS$1);
|
|
10695
|
+
res.end(JSON.stringify(body));
|
|
10696
|
+
}
|
|
10697
|
+
});
|
|
10698
|
+
}, "usage-billing: pricing models route");
|
|
10699
|
+
}
|
|
10700
|
+
//#endregion
|
|
9757
10701
|
//#region lib/types/routes/pricing.js
|
|
9758
10702
|
/**
|
|
9759
10703
|
* 路由:GET /api/billing/pricing + POST /api/billing/pricing/refresh
|
|
@@ -9831,6 +10775,20 @@ function registerPricingRoutes(ctx, deps) {
|
|
|
9831
10775
|
* queryDeclaredEndpoints / reconcileBalanceDelta)在装配器里跑,路由只通过
|
|
9832
10776
|
* `cached()` 与 `refreshOnce()` 拿到结果。
|
|
9833
10777
|
*/
|
|
10778
|
+
/** Loopback callers can supply these advisory UI headers. */
|
|
10779
|
+
function readClientMetadata(headers) {
|
|
10780
|
+
const version = headers[BALANCE_CLIENT_HEADERS.version];
|
|
10781
|
+
const locale = headers[BALANCE_CLIENT_HEADERS.locale];
|
|
10782
|
+
const offset = headers[BALANCE_CLIENT_HEADERS.timezone];
|
|
10783
|
+
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;
|
|
10784
|
+
const timezoneOffsetSeconds = Number(offset);
|
|
10785
|
+
if (Math.abs(timezoneOffsetSeconds) > 50400) return void 0;
|
|
10786
|
+
return {
|
|
10787
|
+
version,
|
|
10788
|
+
locale,
|
|
10789
|
+
timezoneOffsetSeconds
|
|
10790
|
+
};
|
|
10791
|
+
}
|
|
9834
10792
|
function registerBalanceRoute(ctx, deps) {
|
|
9835
10793
|
ctx.effect(() => ctx.webServer.register({
|
|
9836
10794
|
kind: "exact",
|
|
@@ -9839,22 +10797,26 @@ function registerBalanceRoute(ctx, deps) {
|
|
|
9839
10797
|
handler: async (req, res) => {
|
|
9840
10798
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
9841
10799
|
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
9842
|
-
|
|
9843
|
-
|
|
10800
|
+
const client = readClientMetadata(req.headers);
|
|
10801
|
+
const cached = deps.cached(client);
|
|
10802
|
+
if (Date.now() - cached.at < deps.cacheMs) {
|
|
10803
|
+
res.end(JSON.stringify(cached.doc));
|
|
9844
10804
|
return;
|
|
9845
10805
|
}
|
|
9846
10806
|
let timedOut = false;
|
|
10807
|
+
let failed = false;
|
|
9847
10808
|
const onFailure = (error) => {
|
|
10809
|
+
failed = true;
|
|
9848
10810
|
console.warn("[usage-billing] refreshBalances failed; serving cached balances:", error);
|
|
9849
10811
|
};
|
|
9850
|
-
await Promise.race([deps.refreshOnce().then(() => void 0, onFailure), new Promise((resolve) => {
|
|
10812
|
+
await Promise.race([deps.refreshOnce(client).then(() => void 0, onFailure), new Promise((resolve) => {
|
|
9851
10813
|
setTimeout(() => {
|
|
9852
10814
|
timedOut = true;
|
|
9853
10815
|
resolve();
|
|
9854
10816
|
}, deps.responseBudgetMs).unref();
|
|
9855
10817
|
})]);
|
|
9856
|
-
const doc = deps.cached().doc;
|
|
9857
|
-
res.end(JSON.stringify(timedOut ? {
|
|
10818
|
+
const doc = deps.cached(client).doc;
|
|
10819
|
+
res.end(JSON.stringify(timedOut || failed ? {
|
|
9858
10820
|
...doc,
|
|
9859
10821
|
stale: true
|
|
9860
10822
|
} : doc));
|
|
@@ -10407,8 +11369,10 @@ var TaskQueueEngine = class {
|
|
|
10407
11369
|
if (!refresh && this.modelCache !== void 0 && this.now() - this.modelCache.at < OPTIONS_CACHE_MS) return this.modelCache;
|
|
10408
11370
|
const catalog = await controller.modelCatalog();
|
|
10409
11371
|
const models = [];
|
|
11372
|
+
let officialRoute = false;
|
|
10410
11373
|
for (const group of catalog.groups) {
|
|
10411
11374
|
if (group.id !== "deepseek-official") continue;
|
|
11375
|
+
officialRoute = true;
|
|
10412
11376
|
for (const model of group.models) {
|
|
10413
11377
|
if (rateChannelOf(model.id, false) !== "deepseek-metered") continue;
|
|
10414
11378
|
models.push({
|
|
@@ -10424,14 +11388,17 @@ var TaskQueueEngine = class {
|
|
|
10424
11388
|
provider: candidate.provider,
|
|
10425
11389
|
model: candidate.model
|
|
10426
11390
|
};
|
|
11391
|
+
const blockedReason = models.length > 0 ? void 0 : officialRoute ? "no-official-model" : "no-official-route";
|
|
10427
11392
|
this.modelCache = {
|
|
10428
11393
|
at: this.now(),
|
|
10429
11394
|
models,
|
|
10430
|
-
defaultModel
|
|
11395
|
+
defaultModel,
|
|
11396
|
+
blockedReason
|
|
10431
11397
|
};
|
|
10432
11398
|
return {
|
|
10433
11399
|
models,
|
|
10434
|
-
defaultModel
|
|
11400
|
+
defaultModel,
|
|
11401
|
+
blockedReason
|
|
10435
11402
|
};
|
|
10436
11403
|
}
|
|
10437
11404
|
async pump() {
|
|
@@ -10945,8 +11912,8 @@ const QUOTA_RESPONSE_BUDGET_MS = 8e3;
|
|
|
10945
11912
|
* 取 5 分钟:与 usage-stats 的 30s 轮询 + 5 分钟快照节流同一量级。
|
|
10946
11913
|
*/
|
|
10947
11914
|
const RECONCILE_BASIS_MAX_AGE_MS = 3e5;
|
|
10948
|
-
/** DeepSeek
|
|
10949
|
-
const DEFAULT_BALANCE_API_KEY_ENV =
|
|
11915
|
+
/** DeepSeek 余额查询的默认凭据引用(与宿主内置平台通道的默认引用一致)。 */
|
|
11916
|
+
const DEFAULT_BALANCE_API_KEY_ENV = DEEPSEEK_PLATFORM_KEY_REF;
|
|
10950
11917
|
/**
|
|
10951
11918
|
* 本插件版本号:从包自身的 package.json 读取(单一来源),随 usage-stats
|
|
10952
11919
|
* 下发,供「设置 → 插件信息卡」展示。发布版 lib/index.js 相对包根解析。
|
|
@@ -11085,6 +12052,18 @@ async function readPiAiProviders(settings) {
|
|
|
11085
12052
|
return {};
|
|
11086
12053
|
}
|
|
11087
12054
|
}
|
|
12055
|
+
/** Site buckets drop the route ID, so a site match needs a unique configured route. */
|
|
12056
|
+
function uniqueSiteOrigins(providers) {
|
|
12057
|
+
const owners = /* @__PURE__ */ new Map();
|
|
12058
|
+
for (const [route, { baseURL }] of Object.entries(providers)) {
|
|
12059
|
+
if (!baseURL) continue;
|
|
12060
|
+
const origin = siteOriginOf(baseURL);
|
|
12061
|
+
owners.set(origin, owners.has(origin) ? void 0 : route);
|
|
12062
|
+
}
|
|
12063
|
+
const origins = /* @__PURE__ */ new Map();
|
|
12064
|
+
for (const [origin, route] of owners) if (route !== void 0) origins.set(route, origin);
|
|
12065
|
+
return origins;
|
|
12066
|
+
}
|
|
11088
12067
|
/** 同步读取 provider 路由的 baseURL 视图(中转站零配置发现来源)。
|
|
11089
12068
|
* `settings.describe` 是同步调用,聚合器每次折叠取最新站点映射,无需缓存/过期。
|
|
11090
12069
|
* 注意:返回**全部可读路由**(baseURL 可选),聚合层据此区分「路由存在但无
|
|
@@ -11093,13 +12072,20 @@ async function readPiAiProviders(settings) {
|
|
|
11093
12072
|
* @returns `<route> → { baseURL? }`;命名空间不可读时返回空。
|
|
11094
12073
|
*/
|
|
11095
12074
|
function readPiAiProviderRoutes(settings) {
|
|
12075
|
+
return Object.fromEntries(Object.entries(readScheduleProfiles(settings)).map(([id, { baseURL }]) => [id, baseURL === void 0 ? {} : { baseURL }]));
|
|
12076
|
+
}
|
|
12077
|
+
function readScheduleProfiles(settings) {
|
|
11096
12078
|
try {
|
|
11097
12079
|
const providers = (settings.describe({ redactSecrets: true }).find((descriptor) => descriptor.ns === "llm-pi-ai")?.value)?.providers;
|
|
11098
|
-
const out =
|
|
12080
|
+
const out = Object.create(null);
|
|
11099
12081
|
for (const [route, entry] of Object.entries(providers ?? {})) {
|
|
11100
12082
|
if (entry === null || typeof entry !== "object") continue;
|
|
11101
12083
|
const baseURL = entry.baseURL;
|
|
11102
|
-
out[route] =
|
|
12084
|
+
out[route] = {
|
|
12085
|
+
...typeof baseURL === "string" && baseURL !== "" ? { baseURL } : {},
|
|
12086
|
+
...typeof entry.displayName === "string" ? { displayName: entry.displayName } : {},
|
|
12087
|
+
...Array.isArray(entry.models) ? { models: entry.models } : {}
|
|
12088
|
+
};
|
|
11103
12089
|
}
|
|
11104
12090
|
return out;
|
|
11105
12091
|
} catch {
|
|
@@ -11360,7 +12346,7 @@ function apply(ctx, config = {}) {
|
|
|
11360
12346
|
const ledgerStore = createFileUsageLedgerStore(config.ledgerPath ?? join(dshHome, ".dsh-usage-ledger.json"));
|
|
11361
12347
|
const reconcilePath = config.reconcilePath ?? join(dshHome, ".dsh-usage-reconcile.json");
|
|
11362
12348
|
let reconcileRef = null;
|
|
11363
|
-
(async () => {
|
|
12349
|
+
const reconcileLoaded = (async () => {
|
|
11364
12350
|
try {
|
|
11365
12351
|
const ref = JSON.parse(await readFile(reconcilePath, "utf8")).ref;
|
|
11366
12352
|
if (ref !== null && typeof ref === "object") {
|
|
@@ -11371,13 +12357,19 @@ function apply(ctx, config = {}) {
|
|
|
11371
12357
|
swallowed("reconcile-ref-missing");
|
|
11372
12358
|
}
|
|
11373
12359
|
})();
|
|
11374
|
-
|
|
11375
|
-
|
|
11376
|
-
|
|
11377
|
-
|
|
11378
|
-
|
|
11379
|
-
|
|
11380
|
-
|
|
12360
|
+
let persistence = Promise.resolve();
|
|
12361
|
+
const setReconcileRef = (next) => {
|
|
12362
|
+
if (next !== reconcileRef) {
|
|
12363
|
+
reconcileRef = next;
|
|
12364
|
+
const payload = JSON.stringify({ ref: next });
|
|
12365
|
+
persistence = persistence.then(() => writeFileAtomic(reconcilePath, payload, {
|
|
12366
|
+
mode: 384,
|
|
12367
|
+
dirMode: 448
|
|
12368
|
+
})).catch(() => {
|
|
12369
|
+
swallowed("reconcile-write-failed");
|
|
12370
|
+
});
|
|
12371
|
+
}
|
|
12372
|
+
return persistence;
|
|
11381
12373
|
};
|
|
11382
12374
|
const workspaceTitleResolver = buildWorkspaceTitleResolver(ctx);
|
|
11383
12375
|
const sessionTitleResolver = buildSessionTitleResolver(ctx);
|
|
@@ -11407,8 +12399,56 @@ function apply(ctx, config = {}) {
|
|
|
11407
12399
|
swallowed("minimax-plan-classify-failed", error);
|
|
11408
12400
|
}
|
|
11409
12401
|
};
|
|
12402
|
+
const schedules = openScheduleStore(config.peakSchedulePath ?? join(dshHome, ".dsh-usage-peak-schedule.json"), eligibleScheduleModel);
|
|
12403
|
+
const discoverScheduleModels = createScheduleModelDiscovery();
|
|
12404
|
+
const configuredScheduleModels = async () => {
|
|
12405
|
+
const llm = ctx.get?.("llm");
|
|
12406
|
+
return discoverScheduleModels(llm, readScheduleProfiles(ctx.settings), config.routeAliases ?? {});
|
|
12407
|
+
};
|
|
12408
|
+
const scheduleSnapshot = (discovery) => {
|
|
12409
|
+
const config = schedules.current();
|
|
12410
|
+
const models = new Map(discovery.models.map((row) => [scheduleKey(row.source, row.model), row]));
|
|
12411
|
+
for (const key of Object.keys(config.models)) {
|
|
12412
|
+
if (models.has(key)) continue;
|
|
12413
|
+
const [source, model] = JSON.parse(key);
|
|
12414
|
+
models.set(key, {
|
|
12415
|
+
source,
|
|
12416
|
+
model,
|
|
12417
|
+
label: `${source} / ${model}`
|
|
12418
|
+
});
|
|
12419
|
+
}
|
|
12420
|
+
const notices = [...schedules.notices(), ...discovery.notices];
|
|
12421
|
+
const effectiveFromMs = schedules.history().revisions.at(-1)?.effectiveFromMs;
|
|
12422
|
+
return {
|
|
12423
|
+
config,
|
|
12424
|
+
...effectiveFromMs !== void 0 && { effectiveFromMs },
|
|
12425
|
+
models: [...models.values()],
|
|
12426
|
+
...notices.length ? { notices } : {}
|
|
12427
|
+
};
|
|
12428
|
+
};
|
|
12429
|
+
registerPeakScheduleRoute(ctx, {
|
|
12430
|
+
trustedHosts,
|
|
12431
|
+
read: async () => scheduleSnapshot(await configuredScheduleModels()),
|
|
12432
|
+
save: async (raw) => {
|
|
12433
|
+
const discovery = await configuredScheduleModels();
|
|
12434
|
+
const allowed = new Set(discovery.models.map((row) => scheduleKey(row.source, row.model)));
|
|
12435
|
+
let batch;
|
|
12436
|
+
try {
|
|
12437
|
+
batch = partitionScheduleEdit(raw, (key, model) => allowed.has(key) && eligibleScheduleModel(model));
|
|
12438
|
+
} catch {
|
|
12439
|
+
throw new PeakScheduleInputError("invalidSchedule");
|
|
12440
|
+
}
|
|
12441
|
+
if (Object.keys(batch.edit.changes).length) await aggregator.withPeakScheduleChange((latestEventTime) => schedules.save(batch.edit, latestEventTime));
|
|
12442
|
+
return {
|
|
12443
|
+
...scheduleSnapshot(discovery),
|
|
12444
|
+
results: batch.results
|
|
12445
|
+
};
|
|
12446
|
+
}
|
|
12447
|
+
});
|
|
11410
12448
|
const replayDelayMs = readReplayDelayMs(config.replayDelayMs);
|
|
11411
12449
|
const aggregator = createUsageAggregator(adaptSessionPersistence(ctx.sessionPersistence), {
|
|
12450
|
+
resolvePeakSchedule: schedules.current,
|
|
12451
|
+
resolvePeakHistory: schedules.history,
|
|
11412
12452
|
subscriptionMatcher: subscriptionRoutes,
|
|
11413
12453
|
...config.routeAliases === void 0 ? {} : { routeAliases: config.routeAliases },
|
|
11414
12454
|
resolveRoutes: () => readPiAiProviderRoutes(ctx.settings),
|
|
@@ -11723,17 +12763,23 @@ function apply(ctx, config = {}) {
|
|
|
11723
12763
|
clearInterval(timer);
|
|
11724
12764
|
};
|
|
11725
12765
|
}, "usage-billing: pricing refresh timer");
|
|
12766
|
+
registerPricingModelsRoute(ctx, trustedHosts);
|
|
11726
12767
|
registerPricingRoutes(ctx, {
|
|
11727
12768
|
trustedHosts,
|
|
11728
12769
|
body: pricingBody,
|
|
11729
12770
|
refresh: refreshPricing
|
|
11730
12771
|
});
|
|
11731
|
-
|
|
12772
|
+
const headless = {
|
|
11732
12773
|
at: 0,
|
|
11733
12774
|
doc: { balances: [] }
|
|
11734
12775
|
};
|
|
11735
|
-
|
|
11736
|
-
|
|
12776
|
+
const ui = {
|
|
12777
|
+
at: 0,
|
|
12778
|
+
doc: { balances: [] }
|
|
12779
|
+
};
|
|
12780
|
+
const balanceSlot = (client) => client === void 0 ? headless : ui;
|
|
12781
|
+
let refreshSequence = 0;
|
|
12782
|
+
const refreshBalance = async (sequence, client) => {
|
|
11737
12783
|
const piProviders = await readPiAiProviders(ctx.settings);
|
|
11738
12784
|
const providers = { ...piProviders };
|
|
11739
12785
|
const deepseekKey = providers["deepseek"]?.apiKeyEnv;
|
|
@@ -11741,7 +12787,7 @@ function apply(ctx, config = {}) {
|
|
|
11741
12787
|
...providers["deepseek"],
|
|
11742
12788
|
apiKeyEnv: config.balanceApiKeyEnv ?? DEFAULT_BALANCE_API_KEY_ENV
|
|
11743
12789
|
};
|
|
11744
|
-
const balances = await queryBalances(ctx, providers);
|
|
12790
|
+
const balances = await queryBalances(ctx, providers, client, config.balanceApiKeyEnv === void 0 ? void 0 : { extraKeyRefs: { [DEEPSEEK_PLATFORM_ROUTE]: [config.balanceApiKeyEnv] } });
|
|
11745
12791
|
const custom = await queryCustomBalances(ctx, config.customBalances ?? []);
|
|
11746
12792
|
const declared = await queryDeclaredEndpoints(ctx, piProviders, config.declaredEndpoints ?? []);
|
|
11747
12793
|
for (const row of [
|
|
@@ -11749,30 +12795,33 @@ function apply(ctx, config = {}) {
|
|
|
11749
12795
|
...custom,
|
|
11750
12796
|
...declared
|
|
11751
12797
|
]) if (row.error === "unauthorized") warnAuthOnce("balance", row.provider, row.displayName);
|
|
11752
|
-
const official = balances.find((row) => row.
|
|
12798
|
+
const official = balances.find((row) => row.sourceRoute === "deepseek" && row.walletKind === "api-key");
|
|
12799
|
+
const account = balances.find((row) => row.walletKind === "account");
|
|
12800
|
+
const now = Date.now();
|
|
12801
|
+
const today = dayStamp(now);
|
|
12802
|
+
const recent = aggregator.lastDocOf();
|
|
11753
12803
|
let reconcile;
|
|
11754
|
-
|
|
11755
|
-
if (
|
|
11756
|
-
const
|
|
11757
|
-
|
|
11758
|
-
|
|
11759
|
-
|
|
11760
|
-
|
|
11761
|
-
|
|
11762
|
-
|
|
11763
|
-
|
|
11764
|
-
|
|
12804
|
+
await reconcileLoaded;
|
|
12805
|
+
if (sequence === refreshSequence) {
|
|
12806
|
+
const fresh = recent !== void 0 && now - recent.updatedAt <= RECONCILE_BASIS_MAX_AGE_MS;
|
|
12807
|
+
if (!fresh) aggregator.aggregate().catch(() => {
|
|
12808
|
+
swallowed("reconcile-basis-stale");
|
|
12809
|
+
});
|
|
12810
|
+
const apiOnly = account?.accountState === "no-service" || account?.accountState === "signed-out";
|
|
12811
|
+
const cost = fresh ? platformSpend(recent, today, piProviders, apiOnly) : void 0;
|
|
12812
|
+
const source = official && apiBalanceSource(official);
|
|
12813
|
+
if (source !== void 0 && official?.error === void 0 && official?.isAvailable !== false && official?.currency === "CNY" && cost !== void 0) {
|
|
12814
|
+
const result = reconcileBalanceDelta(reconcileRef, official, cost, today, now, `${source}:${apiOnly ? "direct" : "site"}`);
|
|
12815
|
+
if (result.event && result.event.kind !== "flat") reconcile = {
|
|
11765
12816
|
...result.event,
|
|
11766
12817
|
provider: official.displayName,
|
|
11767
|
-
|
|
12818
|
+
currency: official.currency
|
|
11768
12819
|
};
|
|
11769
|
-
|
|
11770
|
-
} else
|
|
11771
|
-
aggregator.aggregate().catch(() => {});
|
|
11772
|
-
swallowed("reconcile-basis-stale");
|
|
11773
|
-
}
|
|
12820
|
+
await setReconcileRef(result.ref);
|
|
12821
|
+
} else await setReconcileRef(null);
|
|
11774
12822
|
}
|
|
11775
|
-
const
|
|
12823
|
+
const slot = balanceSlot(client);
|
|
12824
|
+
slot.doc = {
|
|
11776
12825
|
balances: [
|
|
11777
12826
|
...balances,
|
|
11778
12827
|
...custom,
|
|
@@ -11780,20 +12829,25 @@ function apply(ctx, config = {}) {
|
|
|
11780
12829
|
],
|
|
11781
12830
|
...reconcile === void 0 ? {} : { reconcile }
|
|
11782
12831
|
};
|
|
11783
|
-
|
|
11784
|
-
at: Date.now(),
|
|
11785
|
-
doc
|
|
11786
|
-
};
|
|
12832
|
+
slot.at = Date.now();
|
|
11787
12833
|
};
|
|
11788
|
-
const refreshBalanceOnce = () => {
|
|
11789
|
-
|
|
11790
|
-
|
|
11791
|
-
|
|
11792
|
-
|
|
12834
|
+
const refreshBalanceOnce = (client) => {
|
|
12835
|
+
const slot = balanceSlot(client);
|
|
12836
|
+
if (!slot.inflight) {
|
|
12837
|
+
const sequence = ++refreshSequence;
|
|
12838
|
+
slot.inflight = refreshBalance(sequence, client).catch(async (error) => {
|
|
12839
|
+
await reconcileLoaded;
|
|
12840
|
+
if (sequence === refreshSequence) await setReconcileRef(null);
|
|
12841
|
+
throw error;
|
|
12842
|
+
}).finally(() => {
|
|
12843
|
+
delete slot.inflight;
|
|
12844
|
+
});
|
|
12845
|
+
}
|
|
12846
|
+
return slot.inflight;
|
|
11793
12847
|
};
|
|
11794
12848
|
registerBalanceRoute(ctx, {
|
|
11795
12849
|
trustedHosts,
|
|
11796
|
-
cached:
|
|
12850
|
+
cached: balanceSlot,
|
|
11797
12851
|
refreshOnce: refreshBalanceOnce,
|
|
11798
12852
|
cacheMs: BALANCE_CACHE_MS,
|
|
11799
12853
|
responseBudgetMs: BALANCE_RESPONSE_BUDGET_MS
|
|
@@ -11816,29 +12870,38 @@ function apply(ctx, config = {}) {
|
|
|
11816
12870
|
await refreshMiniMaxPlanRoutes();
|
|
11817
12871
|
const { keys, identified } = await resolveSubscriptionKeys(ctx.settings, ctx.credentials);
|
|
11818
12872
|
const piProviders = await readPiAiProviders(ctx.settings);
|
|
11819
|
-
const
|
|
12873
|
+
const queried = await collectSubscriptions(keys, identified.filter((item) => item.adapter).map((item) => {
|
|
11820
12874
|
const baseURL = piProviders[item.provider]?.baseURL;
|
|
11821
12875
|
return {
|
|
11822
12876
|
provider: item.provider,
|
|
11823
12877
|
...item.region === void 0 ? {} : { region: item.region },
|
|
11824
12878
|
...typeof baseURL === "string" && baseURL !== "" ? { baseUrl: baseURL } : {}
|
|
11825
12879
|
};
|
|
11826
|
-
}))
|
|
12880
|
+
}));
|
|
12881
|
+
const origins = uniqueSiteOrigins(piProviders);
|
|
12882
|
+
const rows = [...queried].map((row) => {
|
|
11827
12883
|
const planType = planTypeOf(row.provider);
|
|
11828
12884
|
const subscriptionAmount = subscriptionFeeCnyOf(row.provider, live.rate);
|
|
12885
|
+
const origin = origins.get(row.provider);
|
|
11829
12886
|
return {
|
|
11830
12887
|
...row,
|
|
12888
|
+
...origin === void 0 ? {} : { origin },
|
|
11831
12889
|
planType,
|
|
11832
12890
|
...planType === "code" && subscriptionAmount > 0 ? { subscriptionAmount } : {}
|
|
11833
12891
|
};
|
|
11834
12892
|
});
|
|
11835
|
-
for (const item of identified)
|
|
11836
|
-
|
|
11837
|
-
|
|
11838
|
-
|
|
11839
|
-
|
|
11840
|
-
|
|
11841
|
-
|
|
12893
|
+
for (const item of identified) {
|
|
12894
|
+
if (item.adapter) continue;
|
|
12895
|
+
const origin = origins.get(item.provider);
|
|
12896
|
+
rows.push({
|
|
12897
|
+
provider: item.provider,
|
|
12898
|
+
displayName: item.displayName,
|
|
12899
|
+
status: "ok",
|
|
12900
|
+
windows: [],
|
|
12901
|
+
planType: planTypeOf(item.provider),
|
|
12902
|
+
...origin === void 0 ? {} : { origin }
|
|
12903
|
+
});
|
|
12904
|
+
}
|
|
11842
12905
|
for (const row of rows) if (row.status === "unauthorized") warnAuthOnce("subscription", row.provider, row.displayName);
|
|
11843
12906
|
quotaCache = {
|
|
11844
12907
|
at: Date.now(),
|
|
@@ -11880,9 +12943,14 @@ function apply(ctx, config = {}) {
|
|
|
11880
12943
|
...entry.displayName === void 0 ? {} : { displayName: entry.displayName }
|
|
11881
12944
|
});
|
|
11882
12945
|
}
|
|
12946
|
+
const origins = uniqueSiteOrigins(providers);
|
|
12947
|
+
const quotas = (await queryRelayQuotas(ctx, routes)).map((row) => origins.has(row.route) ? row : {
|
|
12948
|
+
...row,
|
|
12949
|
+
sourceAmbiguous: true
|
|
12950
|
+
});
|
|
11883
12951
|
relayCache = {
|
|
11884
12952
|
at: Date.now(),
|
|
11885
|
-
quotas
|
|
12953
|
+
quotas
|
|
11886
12954
|
};
|
|
11887
12955
|
};
|
|
11888
12956
|
let relayInflight;
|