@kenz1117/dsh-ui-usage-billing 1.8.11 → 1.8.12
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 +17 -3
- package/README.md +15 -3
- package/lib/client.js +5 -5
- package/lib/index.js +1402 -379
- package/lib/types/aggregate.d.ts +22 -13
- package/lib/types/balance.d.ts +4 -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/round-chart.d.ts +1 -0
- package/lib/types/client/scheduled-band.d.ts +23 -0
- 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 +61 -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/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,47 @@ 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
|
+
function siteBucketKey(ref) {
|
|
4811
|
+
if (ref.kind === "site" && ref.origin) return `site:${ref.origin}`;
|
|
4812
|
+
if (ref.kind === "direct" && ref.provider) return `direct:${ref.provider}`;
|
|
4813
|
+
return "unknown";
|
|
4814
|
+
}
|
|
4815
|
+
function siteKeyParts(siteKey) {
|
|
4816
|
+
const colon = siteKey.indexOf(":");
|
|
4817
|
+
const value = siteKey.slice(colon + 1);
|
|
4818
|
+
if (colon > 0 && value) {
|
|
4819
|
+
const kind = siteKey.slice(0, colon);
|
|
4820
|
+
if (kind === "site") return {
|
|
4821
|
+
kind,
|
|
4822
|
+
origin: value
|
|
4823
|
+
};
|
|
4824
|
+
if (kind === "direct") return {
|
|
4825
|
+
kind,
|
|
4826
|
+
route: value
|
|
4827
|
+
};
|
|
4828
|
+
}
|
|
4829
|
+
return { kind: "unknown" };
|
|
4830
|
+
}
|
|
4831
|
+
/** New servers declare coverage explicitly, including for errors. Legacy rows need an exact route or alias. */
|
|
4832
|
+
function balanceCoversSite(row, siteKey) {
|
|
4833
|
+
const parts = siteKeyParts(siteKey);
|
|
4834
|
+
if (parts.kind === "site") return row.walletKind !== "account" && row.sourceOrigin === parts.origin;
|
|
4835
|
+
if (parts.kind !== "direct") return false;
|
|
4836
|
+
return row.attributedRoutes?.includes(parts.route) ?? (row.sourceRoute === parts.route || row.sourceRouteAliases?.includes(parts.route) === true);
|
|
4837
|
+
}
|
|
4838
|
+
//#endregion
|
|
4502
4839
|
//#region lib/types/aggregate.js
|
|
4503
4840
|
/**
|
|
4504
4841
|
* Real-usage aggregation: folds every persisted session log into the
|
|
@@ -4642,12 +4979,6 @@ function siteRefOf(provider, routes, opts = {}) {
|
|
|
4642
4979
|
provider
|
|
4643
4980
|
};
|
|
4644
4981
|
}
|
|
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
4982
|
/**
|
|
4652
4983
|
* 站点桶按范围求和(usage_stats 工具的 bySite/relay 口径):bySite 全量累计;
|
|
4653
4984
|
* relay 只计中转站桶(`site:<origin>` 键)——`direct:*` 与 `unknown` 不计入,
|
|
@@ -4659,7 +4990,7 @@ function sumSiteBuckets(bySite, range) {
|
|
|
4659
4990
|
let input = 0;
|
|
4660
4991
|
let output = 0;
|
|
4661
4992
|
for (const [bucket, usage] of Object.entries(bySite)) {
|
|
4662
|
-
if (range === "relay" &&
|
|
4993
|
+
if (range === "relay" && siteKeyParts(bucket).kind !== "site") continue;
|
|
4663
4994
|
cost += usage.cost;
|
|
4664
4995
|
calls += usage.calls;
|
|
4665
4996
|
input += usage.input;
|
|
@@ -4742,23 +5073,42 @@ function foldUsage(acc, usage, key, subscription, timeMs, official = false, pric
|
|
|
4742
5073
|
*/
|
|
4743
5074
|
function foldModelCall(ctx) {
|
|
4744
5075
|
const { fold, usage, modelKey, subscription, official, siteBucket, unverifiedChannel, timeMs, day } = ctx;
|
|
4745
|
-
const
|
|
4746
|
-
|
|
5076
|
+
const catalogPriced = isPriced(modelKey);
|
|
5077
|
+
const priced = !subscription && !unverifiedChannel && catalogPriced;
|
|
5078
|
+
if (!subscription && !catalogPriced) fold.unpricedModels.add(modelKey);
|
|
4747
5079
|
const entry = modelOf(modelKey);
|
|
5080
|
+
const override = priced && !ctx.protectedAccount ? scheduleTier(ctx.schedule, siteBucket, entry, modelKey, timeMs) : void 0;
|
|
4748
5081
|
const thisCost = priced ? computeCostAt(entry, {
|
|
4749
5082
|
input: (usage.cacheReadTokens ?? 0) + usage.inputTokens + (usage.cacheWriteTokens ?? 0),
|
|
4750
5083
|
cacheHit: usage.cacheReadTokens ?? 0,
|
|
4751
5084
|
cacheMiss: usage.inputTokens + (usage.cacheWriteTokens ?? 0),
|
|
4752
5085
|
cacheWrite: usage.cacheWriteTokens ?? 0,
|
|
4753
5086
|
output: usage.outputTokens
|
|
4754
|
-
}, timeMs) : void 0;
|
|
5087
|
+
}, timeMs, void 0, override) : void 0;
|
|
4755
5088
|
foldUsage(fold.total, usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4756
5089
|
foldUsage(usageCell(fold.byModel, modelKey), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4757
5090
|
foldUsage(usageCell(fold.byDay, day), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4758
5091
|
foldUsage(modelDayCell(fold.byDayModels, day, modelKey), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4759
|
-
|
|
5092
|
+
const siteCell = modelDaySiteCell(fold.byDayModelsSite, day, modelKey, siteBucket);
|
|
5093
|
+
if (!catalogPriced) {
|
|
5094
|
+
const pending = siteCell.pendingPrice ??= {};
|
|
5095
|
+
if (!subscription && !unverifiedChannel) {
|
|
5096
|
+
const tokens = pending[ctx.protectedAccount ? "native" : "scheduled"] ??= emptyTokens();
|
|
5097
|
+
const hit = usage.cacheReadTokens ?? 0;
|
|
5098
|
+
const write = usage.cacheWriteTokens ?? 0;
|
|
5099
|
+
const miss = usage.inputTokens + write;
|
|
5100
|
+
addTokens(tokens, {
|
|
5101
|
+
input: hit + miss,
|
|
5102
|
+
output: usage.outputTokens,
|
|
5103
|
+
cacheHit: hit,
|
|
5104
|
+
cacheMiss: miss,
|
|
5105
|
+
cacheWrite: write
|
|
5106
|
+
});
|
|
5107
|
+
}
|
|
5108
|
+
}
|
|
5109
|
+
foldUsage(siteCell, usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4760
5110
|
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);
|
|
5111
|
+
if (entry.tierSemantics !== "latency") foldUsage(usageCell(fold.byTier, override ?? tierAt(timeMs)), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
|
|
4762
5112
|
if (subscription) fold.planCalls.set(modelKey, (fold.planCalls.get(modelKey) ?? 0) + 1);
|
|
4763
5113
|
if (subscription) {
|
|
4764
5114
|
const sitePlanKey = planSiteKey(day, modelKey, siteBucket);
|
|
@@ -4770,13 +5120,15 @@ function foldModelCall(ctx) {
|
|
|
4770
5120
|
cacheHit: 0,
|
|
4771
5121
|
cacheMiss: 0,
|
|
4772
5122
|
output: usage.outputTokens
|
|
4773
|
-
}, timeMs);
|
|
5123
|
+
}, timeMs, void 0, override);
|
|
4774
5124
|
fold.roles.outputCost += outputCost;
|
|
4775
5125
|
fold.roles.inputCost += thisCost - outputCost;
|
|
4776
5126
|
}
|
|
4777
5127
|
return {
|
|
4778
5128
|
entry,
|
|
4779
|
-
cost: thisCost
|
|
5129
|
+
cost: thisCost,
|
|
5130
|
+
override,
|
|
5131
|
+
catalogPriced
|
|
4780
5132
|
};
|
|
4781
5133
|
}
|
|
4782
5134
|
/**
|
|
@@ -5198,7 +5550,7 @@ function deserializeFold(fold) {
|
|
|
5198
5550
|
* @param officialProviderIds - 官方直连 provider 名单(决定官方/三方拆分)。
|
|
5199
5551
|
* @returns 归一并补价后的折叠;无需改动时原样返回。
|
|
5200
5552
|
*/
|
|
5201
|
-
function reconcileLedgerFold(fold, officialProviderIds) {
|
|
5553
|
+
function reconcileLedgerFold(fold, officialProviderIds, schedule, fingerprint) {
|
|
5202
5554
|
const rawKeys = /* @__PURE__ */ new Set();
|
|
5203
5555
|
for (const key of fold.byModel.keys()) rawKeys.add(key);
|
|
5204
5556
|
for (const models of fold.byDayModels.values()) for (const key of models.keys()) rawKeys.add(key);
|
|
@@ -5284,20 +5636,30 @@ function reconcileLedgerFold(fold, officialProviderIds) {
|
|
|
5284
5636
|
let addedOfficial = 0;
|
|
5285
5637
|
let addedPeak = 0;
|
|
5286
5638
|
let addedOff = 0;
|
|
5639
|
+
const safeLegacySource = legacyScheduleSource(fingerprint);
|
|
5287
5640
|
for (const [day, models] of fold.byDayModels) for (const [rawKey, cell] of models) {
|
|
5288
5641
|
if (!repriceKeys.has(rawKey)) continue;
|
|
5289
5642
|
const resolved = resolvedKeyOf(rawKey);
|
|
5290
5643
|
const entry = modelOf(resolved);
|
|
5291
|
-
const
|
|
5292
|
-
|
|
5293
|
-
const
|
|
5294
|
-
const dayOutput = repriced.outputCost;
|
|
5295
|
-
const dayPeak = repriced.peakCost;
|
|
5296
|
-
const dayOff = repriced.offCost;
|
|
5644
|
+
const remainder = emptyTokens();
|
|
5645
|
+
addTokens(remainder, cell);
|
|
5646
|
+
const dayPrice = emptyPrice();
|
|
5297
5647
|
let dayOfficial = 0;
|
|
5298
5648
|
const siteCells = fold.byDayModelsSite.get(day)?.get(rawKey);
|
|
5299
|
-
if (siteCells
|
|
5300
|
-
|
|
5649
|
+
if (siteCells) for (const siteCell of siteCells.values()) addTokens(remainder, siteCell, -1);
|
|
5650
|
+
const consistent = tokenFields.every((f) => remainder[f] >= 0);
|
|
5651
|
+
if (!consistent) {
|
|
5652
|
+
Object.assign(remainder, emptyTokens());
|
|
5653
|
+
addTokens(remainder, cell);
|
|
5654
|
+
}
|
|
5655
|
+
if (consistent && siteCells) for (const [site, siteCell] of siteCells) {
|
|
5656
|
+
const siteRepriced = emptyPrice();
|
|
5657
|
+
if (siteCell.pendingPrice) {
|
|
5658
|
+
const { scheduled, native } = siteCell.pendingPrice;
|
|
5659
|
+
if (scheduled) addPrice(siteRepriced, priceLedgerTokens(entry, scheduled, day, schedule, site));
|
|
5660
|
+
if (native) addPrice(siteRepriced, priceLedgerTokens(entry, native, day));
|
|
5661
|
+
} 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));
|
|
5662
|
+
addPrice(dayPrice, siteRepriced);
|
|
5301
5663
|
const official = isOfficialSiteBucket(site, officialProviderIds);
|
|
5302
5664
|
if (official) dayOfficial += siteRepriced.cost;
|
|
5303
5665
|
const siteTarget = byDayModelsSite.get(day)?.get(resolved)?.get(site);
|
|
@@ -5311,6 +5673,8 @@ function reconcileLedgerFold(fold, officialProviderIds) {
|
|
|
5311
5673
|
if (official) siteBucketCell.officialCost += siteRepriced.cost;
|
|
5312
5674
|
}
|
|
5313
5675
|
}
|
|
5676
|
+
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));
|
|
5677
|
+
const { cost: dayCost, inputCost: dayInput, outputCost: dayOutput, peakCost: dayPeak, offCost: dayOff } = dayPrice;
|
|
5314
5678
|
const modelCell = byModel.get(resolved);
|
|
5315
5679
|
if (modelCell !== void 0) {
|
|
5316
5680
|
modelCell.cost += dayCost;
|
|
@@ -5333,27 +5697,38 @@ function reconcileLedgerFold(fold, officialProviderIds) {
|
|
|
5333
5697
|
addedPeak += dayPeak;
|
|
5334
5698
|
addedOff += dayOff;
|
|
5335
5699
|
}
|
|
5336
|
-
|
|
5337
|
-
if (
|
|
5338
|
-
const tierOff = byTier.get("offPeak");
|
|
5339
|
-
if (tierOff !== void 0) tierOff.cost += addedOff;
|
|
5700
|
+
if (addedPeak) usageCell(byTier, "peak").cost += addedPeak;
|
|
5701
|
+
if (addedOff) usageCell(byTier, "offPeak").cost += addedOff;
|
|
5340
5702
|
const turns = fold.turns.map((row) => {
|
|
5341
5703
|
const resolved = resolvedKeyOf(row.model);
|
|
5342
5704
|
if (!repriceKeys.has(row.model) || row.cost > 0) return {
|
|
5343
5705
|
...row,
|
|
5344
5706
|
model: resolved
|
|
5345
5707
|
};
|
|
5346
|
-
const
|
|
5708
|
+
const day = dayStamp(row.startedAt);
|
|
5709
|
+
const sites = fold.byDayModelsSite.get(day)?.get(row.model);
|
|
5710
|
+
const onlySite = sites?.size === 1 ? sites.keys().next().value : void 0;
|
|
5711
|
+
const dayCell = fold.byDayModels.get(day)?.get(row.model);
|
|
5712
|
+
const homogeneous = onlySite && sites?.get(onlySite)?.calls === dayCell?.calls;
|
|
5713
|
+
const source = row.unpricedSource ?? (homogeneous && safeLegacySource(onlySite) ? onlySite : void 0);
|
|
5714
|
+
if (row.unpricedSource === null || !row.unpricedSource && (fold.planCalls.get(row.model) || onlySite === "unknown")) return {
|
|
5715
|
+
...row,
|
|
5716
|
+
model: resolved
|
|
5717
|
+
};
|
|
5718
|
+
const entry = modelOf(resolved);
|
|
5719
|
+
const override = scheduleTier(schedule, source, entry, resolved, row.startedAt);
|
|
5720
|
+
const cost = computeCostAt(entry, {
|
|
5347
5721
|
input: row.input,
|
|
5348
5722
|
cacheHit: row.cacheHit,
|
|
5349
5723
|
cacheMiss: row.cacheMiss,
|
|
5350
5724
|
cacheWrite: 0,
|
|
5351
5725
|
output: row.output
|
|
5352
|
-
}, row.startedAt);
|
|
5726
|
+
}, row.startedAt, void 0, override);
|
|
5353
5727
|
return {
|
|
5354
5728
|
...row,
|
|
5355
5729
|
model: resolved,
|
|
5356
|
-
cost
|
|
5730
|
+
cost,
|
|
5731
|
+
...override && { scheduleTier: override }
|
|
5357
5732
|
};
|
|
5358
5733
|
});
|
|
5359
5734
|
const roles = {
|
|
@@ -5418,64 +5793,6 @@ function parsePlanSiteKey(key) {
|
|
|
5418
5793
|
return;
|
|
5419
5794
|
}
|
|
5420
5795
|
}
|
|
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
5796
|
/** Runtime boundary for a user-editable/corrupt ledger file. Invalid rows are ignored. */
|
|
5480
5797
|
function ledgerSessionsOf(value) {
|
|
5481
5798
|
if (value === null || typeof value !== "object") return [];
|
|
@@ -5616,7 +5933,8 @@ function freshFold() {
|
|
|
5616
5933
|
* @param routeAliases - 历史路由别名(旧路由名 → 当前路由名),改名/删除路由的
|
|
5617
5934
|
* 历史用量按别名归位,不再落「未知路由」桶。
|
|
5618
5935
|
*/
|
|
5619
|
-
function foldInto(fold, machine, events, subscriptionProviders, officialProviderIds, routes, searchCallEstimateCny, seedLength, routeAliases = {}) {
|
|
5936
|
+
function foldInto(fold, machine, events, subscriptionProviders, officialProviderIds, routes, searchCallEstimateCny, seedLength, routeAliases = {}, schedule) {
|
|
5937
|
+
let protectedAccount = machine.protectedAccount ?? false;
|
|
5620
5938
|
let key = machine.key;
|
|
5621
5939
|
let subscription = machine.subscription;
|
|
5622
5940
|
let official = machine.official;
|
|
@@ -5665,6 +5983,7 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5665
5983
|
if (event.type === "request/header") {
|
|
5666
5984
|
const { model, provider: rawProvider } = event.data.header.config;
|
|
5667
5985
|
const provider = routeAliases[rawProvider] ?? rawProvider;
|
|
5986
|
+
protectedAccount = accountRoute(rawProvider) || accountRoute(provider);
|
|
5668
5987
|
key = resolveCatalogKey(model);
|
|
5669
5988
|
subscription = isSubscriptionCall(subscriptionProviders, provider);
|
|
5670
5989
|
const siteRef = siteRefOf(provider, routes, { subscription });
|
|
@@ -5730,6 +6049,8 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5730
6049
|
const compactionSiteBucket = siteBucketKey(siteRef);
|
|
5731
6050
|
foldModelCall({
|
|
5732
6051
|
fold,
|
|
6052
|
+
protectedAccount: accountRoute(data.provider) || accountRoute(provider),
|
|
6053
|
+
schedule,
|
|
5733
6054
|
usage: compactionUsage,
|
|
5734
6055
|
modelKey,
|
|
5735
6056
|
subscription: compactionSubscription,
|
|
@@ -5747,6 +6068,7 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5747
6068
|
const source = event.data.message?.source;
|
|
5748
6069
|
if (source?.kind === "model" && typeof source.provider === "string" && typeof source.model === "string") {
|
|
5749
6070
|
const provider = routeAliases[source.provider] ?? source.provider;
|
|
6071
|
+
protectedAccount = accountRoute(source.provider) || accountRoute(provider);
|
|
5750
6072
|
key = resolveCatalogKey(source.model);
|
|
5751
6073
|
subscription = isSubscriptionCall(subscriptionProviders, provider);
|
|
5752
6074
|
const siteRef = siteRefOf(provider, routes, { subscription });
|
|
@@ -5755,20 +6077,32 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5755
6077
|
}
|
|
5756
6078
|
const modelKey = key;
|
|
5757
6079
|
const day = dayStamp(event.time);
|
|
5758
|
-
const { entry, cost: thisCost } = foldModelCall({
|
|
6080
|
+
const { entry, cost: thisCost, override, catalogPriced } = foldModelCall({
|
|
5759
6081
|
fold,
|
|
5760
6082
|
usage,
|
|
5761
6083
|
modelKey,
|
|
5762
6084
|
subscription,
|
|
5763
6085
|
official,
|
|
5764
6086
|
siteBucket,
|
|
6087
|
+
schedule,
|
|
6088
|
+
protectedAccount,
|
|
5765
6089
|
unverifiedChannel: siteBucket === "unknown",
|
|
5766
6090
|
timeMs: event.time,
|
|
5767
6091
|
day
|
|
5768
6092
|
});
|
|
5769
6093
|
const turn = event.data.turn ?? -1;
|
|
5770
6094
|
const state = turnState(turns, turn);
|
|
6095
|
+
if (!catalogPriced) {
|
|
6096
|
+
const source = subscription || siteBucket === "unknown" ? null : protectedAccount ? "native" : siteBucket;
|
|
6097
|
+
if (state.input || state.output) {
|
|
6098
|
+
if (state.unpricedSource !== source || state.model !== modelKey) state.unpricedSource = null;
|
|
6099
|
+
} else state.unpricedSource = source;
|
|
6100
|
+
} else if (state.unpricedSource !== void 0) state.unpricedSource = null;
|
|
5771
6101
|
state.model = modelKey;
|
|
6102
|
+
if (protectedAccount || subscription || siteBucket === "unknown") delete state.scheduleSource;
|
|
6103
|
+
else state.scheduleSource = siteBucket;
|
|
6104
|
+
if (override === void 0) delete state.scheduleTier;
|
|
6105
|
+
else state.scheduleTier = override;
|
|
5772
6106
|
state.input += usage.inputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0);
|
|
5773
6107
|
state.output += usage.outputTokens;
|
|
5774
6108
|
state.cacheHit += usage.cacheReadTokens ?? 0;
|
|
@@ -5785,6 +6119,7 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
|
|
|
5785
6119
|
}
|
|
5786
6120
|
}
|
|
5787
6121
|
}
|
|
6122
|
+
machine.protectedAccount = protectedAccount;
|
|
5788
6123
|
machine.key = key;
|
|
5789
6124
|
machine.subscription = subscription;
|
|
5790
6125
|
machine.official = official;
|
|
@@ -5796,6 +6131,9 @@ function refreshTurns(fold, machine) {
|
|
|
5796
6131
|
fold.turns = [...machine.turns.values()].filter((state) => state.input > 0 || state.output > 0).sort((a, b) => a.turn - b.turn).map((state) => ({
|
|
5797
6132
|
turn: state.turn,
|
|
5798
6133
|
model: state.model,
|
|
6134
|
+
...state.unpricedSource === void 0 ? {} : { unpricedSource: state.unpricedSource },
|
|
6135
|
+
...state.scheduleSource === void 0 ? {} : { scheduleSource: state.scheduleSource },
|
|
6136
|
+
...state.scheduleTier === void 0 ? {} : { scheduleTier: state.scheduleTier },
|
|
5799
6137
|
input: state.input,
|
|
5800
6138
|
output: state.output,
|
|
5801
6139
|
cacheHit: state.cacheHit,
|
|
@@ -5970,14 +6308,17 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5970
6308
|
const maxCacheSessions = options.maxCacheSessions ?? 400;
|
|
5971
6309
|
const cache = /* @__PURE__ */ new Map();
|
|
5972
6310
|
const ledger = /* @__PURE__ */ new Map();
|
|
5973
|
-
let
|
|
6311
|
+
let ledgerLoading;
|
|
6312
|
+
let latestFoldedEvent = -1;
|
|
5974
6313
|
let ledgerNeedsSave = false;
|
|
5975
6314
|
let lastLedgerSaveAt = 0;
|
|
5976
6315
|
const unreadable = /* @__PURE__ */ new Map();
|
|
5977
6316
|
const titleHints = /* @__PURE__ */ new Map();
|
|
5978
6317
|
let inflight;
|
|
6318
|
+
let scheduleWrite;
|
|
5979
6319
|
let ledgerAppliedMigrations;
|
|
5980
6320
|
let lastDoc;
|
|
6321
|
+
let lastHistory;
|
|
5981
6322
|
let lastAt = 0;
|
|
5982
6323
|
const deserializedFoldOf = (() => {
|
|
5983
6324
|
const memo = /* @__PURE__ */ new WeakMap();
|
|
@@ -5989,16 +6330,24 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
5989
6330
|
return fold;
|
|
5990
6331
|
};
|
|
5991
6332
|
})();
|
|
5992
|
-
|
|
5993
|
-
|
|
5994
|
-
|
|
5995
|
-
|
|
5996
|
-
|
|
5997
|
-
|
|
5998
|
-
|
|
5999
|
-
|
|
6000
|
-
}
|
|
6001
|
-
|
|
6333
|
+
let indexedHistory;
|
|
6334
|
+
let indexedSchedule;
|
|
6335
|
+
let reconciled = /* @__PURE__ */ new WeakMap();
|
|
6336
|
+
function useHistory(history) {
|
|
6337
|
+
if (indexedHistory !== history) {
|
|
6338
|
+
indexedHistory = history;
|
|
6339
|
+
indexedSchedule = indexPeakHistory(history);
|
|
6340
|
+
reconciled = /* @__PURE__ */ new WeakMap();
|
|
6341
|
+
}
|
|
6342
|
+
return indexedSchedule;
|
|
6343
|
+
}
|
|
6344
|
+
function reconciledFoldOf(row) {
|
|
6345
|
+
const hit = reconciled.get(row);
|
|
6346
|
+
if (hit) return hit;
|
|
6347
|
+
const fold = reconcileLedgerFold(deserializedFoldOf(row.fold), officialProviderIds, indexedSchedule, row.fingerprint);
|
|
6348
|
+
reconciled.set(row, fold);
|
|
6349
|
+
return fold;
|
|
6350
|
+
}
|
|
6002
6351
|
/** 每次聚合取最新的 provider 路由视图(中转站零配置发现);缺省按空处理(全部未知路由)。
|
|
6003
6352
|
* 叠加已注册 adapter 的通道(issue #91):宿主 llm 注册表里的 provider 合成无 baseURL
|
|
6004
6353
|
* 的空路由视图——siteRefOf 的路由命中分支正是「无 origin 直连」的语义,归位
|
|
@@ -6029,7 +6378,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6029
6378
|
* 价目表变化后未受影响行(无 unpriced 模型)依旧零读取复用。 */
|
|
6030
6379
|
const foldNeedsReprice = (fold) => fold.unpricedModels.some((key) => isPriced(key));
|
|
6031
6380
|
/** 把一份(全量或增量)折叠结果登记进 durable ledger;内容无变化时不落盘。 */
|
|
6032
|
-
const recordLedger = (id, cwd, stamp, fold, subOf) => {
|
|
6381
|
+
const recordLedger = (id, cwd, stamp, fold, subOf, scheduleFingerprint) => {
|
|
6033
6382
|
if (options.ledger === void 0) return;
|
|
6034
6383
|
const entry = {
|
|
6035
6384
|
id,
|
|
@@ -6038,18 +6387,18 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6038
6387
|
...stamp === null ? {} : { stamp },
|
|
6039
6388
|
foldVersion: 24,
|
|
6040
6389
|
fingerprint: foldFingerprint,
|
|
6390
|
+
...scheduleFingerprint === void 0 ? {} : { scheduleFingerprint },
|
|
6041
6391
|
foldedAt: Date.now(),
|
|
6042
6392
|
fold: serializeFold(fold)
|
|
6043
6393
|
};
|
|
6044
6394
|
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)) {
|
|
6395
|
+
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
6396
|
ledger.set(id, entry);
|
|
6047
6397
|
ledgerNeedsSave = true;
|
|
6048
6398
|
}
|
|
6049
6399
|
};
|
|
6050
|
-
const
|
|
6051
|
-
if (
|
|
6052
|
-
ledgerLoaded = true;
|
|
6400
|
+
const loadLedger = async () => {
|
|
6401
|
+
if (options.ledger === void 0) return;
|
|
6053
6402
|
try {
|
|
6054
6403
|
const stored = await options.ledger.load();
|
|
6055
6404
|
if (stored !== null && typeof stored === "object" && stored.sessions !== void 0) {
|
|
@@ -6061,11 +6410,15 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6061
6410
|
format: refusal.format === true
|
|
6062
6411
|
});
|
|
6063
6412
|
}
|
|
6064
|
-
for (const entry of ledgerSessionsOf(stored))
|
|
6413
|
+
for (const entry of ledgerSessionsOf(stored)) {
|
|
6414
|
+
ledger.set(entry.id, entry);
|
|
6415
|
+
if (Number.isFinite(entry.fold.lastActive)) latestFoldedEvent = Math.max(latestFoldedEvent, entry.fold.lastActive);
|
|
6416
|
+
}
|
|
6065
6417
|
} catch (error) {
|
|
6066
6418
|
console.warn("[usage-billing] failed to load durable usage ledger; rebuilding from current sessions:", error);
|
|
6067
6419
|
}
|
|
6068
6420
|
};
|
|
6421
|
+
const ensureLedgerLoaded = () => ledgerLoading ??= loadLedger();
|
|
6069
6422
|
/** 失效键:宿主 0.1.3+ 走 adapter 暴露的 revision 令牌;0.1.2 形状退回
|
|
6070
6423
|
* 日志文件 mtime+size(经 locate,拿不到或抛错时返回 null 让调用方重折)。
|
|
6071
6424
|
* locate/stat 调用纳入 try,避免单个会话的异常把整份聚合拖垮。 */
|
|
@@ -6114,11 +6467,12 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6114
6467
|
* 开门后的下一轮即完整折叠)——轻文档的每行折叠反序列化有 WeakMap 记忆,
|
|
6115
6468
|
* 重复构建只付 O(行数) 的汇总合并,冷phase里每个请求都可负担。
|
|
6116
6469
|
*/
|
|
6117
|
-
const aggregateOnce = async (mode) => {
|
|
6470
|
+
const aggregateOnce = async (mode, history, activeSchedule) => {
|
|
6118
6471
|
const now = Date.now();
|
|
6119
6472
|
await ensureLedgerLoaded();
|
|
6120
6473
|
const registeredProviders = options.resolveRegisteredProviders?.() ?? /* @__PURE__ */ new Set();
|
|
6121
6474
|
const roundRoutes = routesOf(registeredProviders);
|
|
6475
|
+
const schedule = useHistory(history);
|
|
6122
6476
|
foldFingerprint = foldFingerprintOf(registeredProviders, roundRoutes);
|
|
6123
6477
|
const seen = /* @__PURE__ */ new Set();
|
|
6124
6478
|
const included = /* @__PURE__ */ new Set();
|
|
@@ -6163,8 +6517,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6163
6517
|
const cwd = meta.cwd;
|
|
6164
6518
|
const subOf = subParentOf(meta);
|
|
6165
6519
|
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
|
|
6520
|
+
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)) {
|
|
6521
|
+
const fold = reconciledFoldOf(ledgerRow);
|
|
6168
6522
|
folds.push({
|
|
6169
6523
|
id,
|
|
6170
6524
|
...cwd === void 0 ? {} : { cwd },
|
|
@@ -6175,7 +6529,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6175
6529
|
continue;
|
|
6176
6530
|
}
|
|
6177
6531
|
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))) {
|
|
6532
|
+
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
6533
|
cache.delete(id);
|
|
6180
6534
|
cache.set(id, hit);
|
|
6181
6535
|
folds.push({
|
|
@@ -6188,7 +6542,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6188
6542
|
continue;
|
|
6189
6543
|
}
|
|
6190
6544
|
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))) {
|
|
6545
|
+
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
6546
|
const from = previous.lastSeq + 1;
|
|
6193
6547
|
const { events, inheritedEventCount } = await persistence.readFrom(meta.id, sessionLogOffsetOf(from));
|
|
6194
6548
|
const after = await stampOf(meta);
|
|
@@ -6201,7 +6555,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6201
6555
|
cache.delete(id);
|
|
6202
6556
|
continue;
|
|
6203
6557
|
}
|
|
6204
|
-
foldInto(previous.fold, previous.machine, events, subscriptionMatcher, officialProviderIds, roundRoutes, searchEstimate, inheritedEventCount, routeAliases);
|
|
6558
|
+
foldInto(previous.fold, previous.machine, events, subscriptionMatcher, officialProviderIds, roundRoutes, searchEstimate, inheritedEventCount, routeAliases, schedule);
|
|
6559
|
+
if (Number.isFinite(previous.fold.lastActive)) latestFoldedEvent = Math.max(latestFoldedEvent, previous.fold.lastActive);
|
|
6205
6560
|
refreshTurns(previous.fold, previous.machine);
|
|
6206
6561
|
previous.lastSeq = events[events.length - 1]?.seq ?? previous.lastSeq;
|
|
6207
6562
|
previous.stamp = stamp;
|
|
@@ -6214,7 +6569,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6214
6569
|
fold: previous.fold
|
|
6215
6570
|
});
|
|
6216
6571
|
included.add(id);
|
|
6217
|
-
|
|
6572
|
+
previous.scheduleFingerprint = schedule?.fingerprint(previous.fold.lastActive);
|
|
6573
|
+
recordLedger(id, cwd, stamp, previous.fold, subOf, previous.scheduleFingerprint);
|
|
6218
6574
|
continue;
|
|
6219
6575
|
}
|
|
6220
6576
|
const { events, inheritedEventCount } = await persistence.readFrom(meta.id, sessionLogOffsetOf(0));
|
|
@@ -6223,7 +6579,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6223
6579
|
const fold = freshFold();
|
|
6224
6580
|
const machine = freshMachine();
|
|
6225
6581
|
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);
|
|
6582
|
+
foldInto(fold, machine, events.slice(start, start + FOLD_CHUNK_EVENTS), subscriptionMatcher, officialProviderIds, roundRoutes, searchEstimate, inheritedEventCount, routeAliases, schedule);
|
|
6583
|
+
if (Number.isFinite(fold.lastActive)) latestFoldedEvent = Math.max(latestFoldedEvent, fold.lastActive);
|
|
6227
6584
|
if (start + FOLD_CHUNK_EVENTS < events.length && Date.now() - sliceAt >= FOLD_SLICE_MS) {
|
|
6228
6585
|
await new Promise((resolve) => {
|
|
6229
6586
|
setImmediate(resolve);
|
|
@@ -6238,7 +6595,8 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6238
6595
|
fold,
|
|
6239
6596
|
machine,
|
|
6240
6597
|
...last !== void 0 && typeof last.seq === "number" ? { lastSeq: last.seq } : {},
|
|
6241
|
-
fingerprint: foldFingerprint
|
|
6598
|
+
fingerprint: foldFingerprint,
|
|
6599
|
+
scheduleFingerprint: schedule?.fingerprint(fold.lastActive)
|
|
6242
6600
|
});
|
|
6243
6601
|
folds.push({
|
|
6244
6602
|
id,
|
|
@@ -6247,7 +6605,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6247
6605
|
fold
|
|
6248
6606
|
});
|
|
6249
6607
|
included.add(id);
|
|
6250
|
-
recordLedger(id, cwd, stamp, fold, subOf);
|
|
6608
|
+
recordLedger(id, cwd, stamp, fold, subOf, schedule?.fingerprint(fold.lastActive));
|
|
6251
6609
|
} catch (error) {
|
|
6252
6610
|
skipped.push(id);
|
|
6253
6611
|
const format = isFormatUnsupportedError(error);
|
|
@@ -6293,7 +6651,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6293
6651
|
if (included.has(entry.id)) continue;
|
|
6294
6652
|
try {
|
|
6295
6653
|
const stale = (entry.foldVersion ?? 1) < 24 || entry.fingerprint !== foldFingerprint;
|
|
6296
|
-
const fold = reconciledFoldOf(entry
|
|
6654
|
+
const fold = reconciledFoldOf(entry);
|
|
6297
6655
|
const hint = titleHints.get(entry.id);
|
|
6298
6656
|
folds.push({
|
|
6299
6657
|
id: entry.id,
|
|
@@ -6439,10 +6797,16 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6439
6797
|
};
|
|
6440
6798
|
const toModelDayRecord = (map) => Object.fromEntries([...map].map(([day, models]) => [day, Object.fromEntries(models)]));
|
|
6441
6799
|
const toModelDaySiteRecord = (map) => Object.fromEntries([...map].map(([day, models]) => [day, Object.fromEntries([...models].map(([model, sites]) => [model, Object.fromEntries([...sites].map(([site, cell]) => {
|
|
6442
|
-
|
|
6800
|
+
const count = planSiteCalls.get(planSiteKey(day, model, site)) ?? 0;
|
|
6801
|
+
if (count === cell.calls && count > 0) return [site, {
|
|
6443
6802
|
...cell,
|
|
6444
6803
|
plan: true
|
|
6445
|
-
}
|
|
6804
|
+
}];
|
|
6805
|
+
if (count > 0 && count < cell.calls) return [site, {
|
|
6806
|
+
...cell,
|
|
6807
|
+
planCalls: count
|
|
6808
|
+
}];
|
|
6809
|
+
return [site, cell];
|
|
6446
6810
|
}))]))]));
|
|
6447
6811
|
const modelKeys = /* @__PURE__ */ new Set([...perfModel.keys(), ...perfModelDigest.keys()]);
|
|
6448
6812
|
const hourKeys = /* @__PURE__ */ new Set([...perfHourModel.keys(), ...perfHourDigest.keys()]);
|
|
@@ -6479,6 +6843,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6479
6843
|
...byDayModelsSite.size === 0 ? {} : { byDayModelsSite: toModelDaySiteRecord(byDayModelsSite) },
|
|
6480
6844
|
bySession: sessionRows.slice(0, 100),
|
|
6481
6845
|
bySessionTotal: sessionRows.length,
|
|
6846
|
+
...activeSchedule ? { peakSchedule: activeSchedule } : {},
|
|
6482
6847
|
byTurn: turnRows.slice(0, 200),
|
|
6483
6848
|
byWorkspace: workspaces.slice(0, 100),
|
|
6484
6849
|
...byTier.size === 0 ? {} : { byTier: {
|
|
@@ -6508,20 +6873,37 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6508
6873
|
};
|
|
6509
6874
|
if (mode === "full") {
|
|
6510
6875
|
lastDoc = document;
|
|
6876
|
+
lastHistory = history;
|
|
6511
6877
|
lastAt = now;
|
|
6512
6878
|
}
|
|
6513
6879
|
return document;
|
|
6514
6880
|
};
|
|
6515
6881
|
return {
|
|
6516
6882
|
aggregate() {
|
|
6883
|
+
if (scheduleWrite !== void 0) return scheduleWrite.then(() => this.aggregate(), () => this.aggregate());
|
|
6517
6884
|
const now = Date.now();
|
|
6518
|
-
|
|
6519
|
-
|
|
6520
|
-
|
|
6885
|
+
const currentSchedule = options.resolvePeakSchedule?.();
|
|
6886
|
+
const activeSchedule = currentSchedule && Object.keys(currentSchedule.models).length ? currentSchedule : void 0;
|
|
6887
|
+
const history = options.resolvePeakHistory?.();
|
|
6888
|
+
if (lastDoc !== void 0 && lastHistory === history && lastDoc.peakSchedule === activeSchedule && now - lastAt < 5e3) return Promise.resolve(lastDoc);
|
|
6889
|
+
if (now < foldAllowedAt) return inflight ?? aggregateOnce("ledger-only", history, activeSchedule);
|
|
6890
|
+
inflight ??= aggregateOnce("full", history, activeSchedule).finally(() => {
|
|
6521
6891
|
inflight = void 0;
|
|
6522
6892
|
});
|
|
6523
6893
|
return inflight;
|
|
6524
6894
|
},
|
|
6895
|
+
withPeakScheduleChange(save) {
|
|
6896
|
+
const previous = scheduleWrite ?? inflight;
|
|
6897
|
+
const commit = (async () => {
|
|
6898
|
+
if (previous !== void 0) await previous.catch(() => void 0);
|
|
6899
|
+
await ensureLedgerLoaded();
|
|
6900
|
+
return save(latestFoldedEvent);
|
|
6901
|
+
})().finally(() => {
|
|
6902
|
+
if (scheduleWrite === commit) scheduleWrite = void 0;
|
|
6903
|
+
});
|
|
6904
|
+
scheduleWrite = commit;
|
|
6905
|
+
return commit;
|
|
6906
|
+
},
|
|
6525
6907
|
async sessionUsageOf(sessionId) {
|
|
6526
6908
|
await this.aggregate();
|
|
6527
6909
|
const hit = cache.get(sessionId);
|
|
@@ -6534,7 +6916,7 @@ function createUsageAggregator(persistence, options = {}) {
|
|
|
6534
6916
|
const row = ledger.get(sessionId);
|
|
6535
6917
|
if (row === void 0) return void 0;
|
|
6536
6918
|
try {
|
|
6537
|
-
const fold = reconciledFoldOf(row
|
|
6919
|
+
const fold = reconciledFoldOf(row);
|
|
6538
6920
|
return {
|
|
6539
6921
|
calls: fold.total.calls,
|
|
6540
6922
|
cost: fold.total.cost,
|
|
@@ -6880,26 +7262,18 @@ const SILICONFLOW_BALANCE_URL = "https://api.siliconflow.cn/v1/user/info";
|
|
|
6880
7262
|
const XAI_CREDITS_URL = "https://api.x.ai/v1/billing/credits";
|
|
6881
7263
|
/** 智谱 GLM(大模型国内域)官方余额接口(open.bigmodel.cn/api/paas/v4/balance)。 */
|
|
6882
7264
|
const ZHIPU_BALANCE_URL = "https://open.bigmodel.cn/api/paas/v4/balance";
|
|
6883
|
-
/** 数字归一化:接口返回的余额是字符串(如 `"110.00"`),统一转 number。 */
|
|
6884
7265
|
/**
|
|
6885
7266
|
* Fetch a Bearer-protected balance endpoint and normalize the HTTP outcome into
|
|
6886
7267
|
* a shared {@link ProviderBalance} row. Each provider supplies its own
|
|
6887
7268
|
* response parser for the success body.
|
|
6888
|
-
* @param ctx - host context carrying the credentials seam.
|
|
6889
7269
|
* @param url - the balance endpoint.
|
|
6890
|
-
* @param
|
|
7270
|
+
* @param key - resolved credential for this query.
|
|
6891
7271
|
* @param provider - the provider id (matches the model-table vendor display name).
|
|
6892
7272
|
* @param displayName - human-readable provider name.
|
|
6893
7273
|
* @param parse - maps a success JSON body to the balance row fields.
|
|
6894
7274
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6895
7275
|
*/
|
|
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
|
-
};
|
|
7276
|
+
async function queryBearerBalance(url, key, provider, displayName, parse) {
|
|
6903
7277
|
if (!balanceGate.check(provider)) return {
|
|
6904
7278
|
provider,
|
|
6905
7279
|
displayName,
|
|
@@ -6912,7 +7286,7 @@ async function queryBearerBalance(ctx, url, apiKeyEnv, provider, displayName, pa
|
|
|
6912
7286
|
const response = await fetch(url, {
|
|
6913
7287
|
headers: {
|
|
6914
7288
|
accept: "application/json",
|
|
6915
|
-
authorization: `Bearer ${
|
|
7289
|
+
authorization: `Bearer ${key}`
|
|
6916
7290
|
},
|
|
6917
7291
|
signal: controller.signal
|
|
6918
7292
|
});
|
|
@@ -6956,40 +7330,118 @@ async function queryBearerBalance(ctx, url, apiKeyEnv, provider, displayName, pa
|
|
|
6956
7330
|
};
|
|
6957
7331
|
}
|
|
6958
7332
|
}
|
|
7333
|
+
function parseDeepSeekBalance(data) {
|
|
7334
|
+
const doc = data;
|
|
7335
|
+
const info = (Array.isArray(doc.balance_infos) ? doc.balance_infos : [])[0];
|
|
7336
|
+
const currency = typeof info?.currency === "string" ? info.currency : void 0;
|
|
7337
|
+
const totalBalance = toNumber$1(info?.total_balance);
|
|
7338
|
+
const grantedBalance = toNumber$1(info?.granted_balance);
|
|
7339
|
+
const toppedUpBalance = toNumber$1(info?.topped_up_balance);
|
|
7340
|
+
const isAvailable = typeof doc.is_available === "boolean" ? doc.is_available : void 0;
|
|
7341
|
+
return {
|
|
7342
|
+
provider: "deepseek",
|
|
7343
|
+
displayName: "DeepSeek",
|
|
7344
|
+
...currency !== void 0 ? { currency } : {},
|
|
7345
|
+
...totalBalance !== void 0 ? { totalBalance } : {},
|
|
7346
|
+
...grantedBalance !== void 0 ? { grantedBalance } : {},
|
|
7347
|
+
...toppedUpBalance !== void 0 ? { toppedUpBalance } : {},
|
|
7348
|
+
...isAvailable !== void 0 ? { isAvailable } : {}
|
|
7349
|
+
};
|
|
7350
|
+
}
|
|
7351
|
+
const ACCOUNT_WALLET = {
|
|
7352
|
+
provider: "deepseek",
|
|
7353
|
+
displayName: "DeepSeek",
|
|
7354
|
+
sourceRoute: "deepseek",
|
|
7355
|
+
attributedRoutes: ["deepseek"],
|
|
7356
|
+
walletKind: "account"
|
|
7357
|
+
};
|
|
7358
|
+
const warnedAccountFailures = /* @__PURE__ */ new Set();
|
|
7359
|
+
const apiSources = /* @__PURE__ */ new WeakMap();
|
|
7360
|
+
function apiBalanceSource(row) {
|
|
7361
|
+
return apiSources.get(row);
|
|
7362
|
+
}
|
|
7363
|
+
function accountBalanceRow(details) {
|
|
7364
|
+
const doc = details;
|
|
7365
|
+
if (doc?.status !== "ready") return void 0;
|
|
7366
|
+
const sumsByCurrency = (items) => {
|
|
7367
|
+
const sums = /* @__PURE__ */ new Map();
|
|
7368
|
+
if (!Array.isArray(items)) return sums;
|
|
7369
|
+
for (const item of items) {
|
|
7370
|
+
const currency = item?.currency;
|
|
7371
|
+
const value = toNumber$1(item?.balance);
|
|
7372
|
+
if ((currency === "CNY" || currency === "USD") && value !== void 0) sums.set(currency, (sums.get(currency) ?? 0) + value);
|
|
7373
|
+
}
|
|
7374
|
+
return sums;
|
|
7375
|
+
};
|
|
7376
|
+
const toppedUp = sumsByCurrency(doc.value);
|
|
7377
|
+
const granted = sumsByCurrency(doc.bonusWallets);
|
|
7378
|
+
const has = (currency) => toppedUp.has(currency) || granted.has(currency);
|
|
7379
|
+
const currency = has("CNY") ? "CNY" : has("USD") ? "USD" : void 0;
|
|
7380
|
+
if (currency === void 0) return void 0;
|
|
7381
|
+
const toppedUpBalance = toppedUp.get(currency);
|
|
7382
|
+
const grantedBalance = granted.get(currency);
|
|
7383
|
+
return {
|
|
7384
|
+
...ACCOUNT_WALLET,
|
|
7385
|
+
...has("CNY") && has("USD") ? { otherBalances: [{
|
|
7386
|
+
currency: "USD",
|
|
7387
|
+
totalBalance: (toppedUp.get("USD") ?? 0) + (granted.get("USD") ?? 0)
|
|
7388
|
+
}] } : {},
|
|
7389
|
+
currency,
|
|
7390
|
+
totalBalance: (toppedUpBalance ?? 0) + (grantedBalance ?? 0),
|
|
7391
|
+
...toppedUpBalance !== void 0 ? { toppedUpBalance } : {},
|
|
7392
|
+
...grantedBalance !== void 0 ? { grantedBalance } : {},
|
|
7393
|
+
isAvailable: true
|
|
7394
|
+
};
|
|
7395
|
+
}
|
|
7396
|
+
function accountWalletFailure(reason, error = "unreachable") {
|
|
7397
|
+
if (!warnedAccountFailures.has(reason)) {
|
|
7398
|
+
warnedAccountFailures.add(reason);
|
|
7399
|
+
console.warn(`[usage-billing] DeepSeek sign-in wallet: ${reason}`);
|
|
7400
|
+
}
|
|
7401
|
+
return {
|
|
7402
|
+
...ACCOUNT_WALLET,
|
|
7403
|
+
error
|
|
7404
|
+
};
|
|
7405
|
+
}
|
|
7406
|
+
async function queryDeepSeekAccount(ctx, client) {
|
|
7407
|
+
const unavailable = (accountState) => ({
|
|
7408
|
+
...ACCOUNT_WALLET,
|
|
7409
|
+
attributedRoutes: [],
|
|
7410
|
+
error: "unconfigured",
|
|
7411
|
+
accountState
|
|
7412
|
+
});
|
|
7413
|
+
let account;
|
|
7414
|
+
try {
|
|
7415
|
+
account = ctx.get?.("deepseekAccount");
|
|
7416
|
+
} catch {
|
|
7417
|
+
return accountWalletFailure("host service lookup threw");
|
|
7418
|
+
}
|
|
7419
|
+
if (typeof account?.getBalance !== "function") return unavailable("no-service");
|
|
7420
|
+
if (client === void 0) return unavailable("no-metadata");
|
|
7421
|
+
try {
|
|
7422
|
+
const details = await account.getBalance(client);
|
|
7423
|
+
if (details === null) return unavailable("signed-out");
|
|
7424
|
+
if (details?.status === "failed") return accountWalletFailure("host returned failed");
|
|
7425
|
+
return accountBalanceRow(details) ?? accountWalletFailure("unusable balance response", "invalid");
|
|
7426
|
+
} catch {
|
|
7427
|
+
return accountWalletFailure("balance query threw");
|
|
7428
|
+
}
|
|
7429
|
+
}
|
|
6959
7430
|
/**
|
|
6960
|
-
* Query the DeepSeek
|
|
6961
|
-
* @param
|
|
6962
|
-
* @param apiKeyEnv - credential reference resolving the DeepSeek API key.
|
|
7431
|
+
* Query the DeepSeek Platform wallet independently of the sign-in service.
|
|
7432
|
+
* @param key - resolved credential for this query.
|
|
6963
7433
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6964
7434
|
*/
|
|
6965
|
-
function queryDeepSeek(
|
|
6966
|
-
return queryBearerBalance(
|
|
6967
|
-
const doc = data;
|
|
6968
|
-
const info = (Array.isArray(doc.balance_infos) ? doc.balance_infos : [])[0];
|
|
6969
|
-
const currency = typeof info?.currency === "string" ? info.currency : void 0;
|
|
6970
|
-
const totalBalance = toNumber$1(info?.total_balance);
|
|
6971
|
-
const grantedBalance = toNumber$1(info?.granted_balance);
|
|
6972
|
-
const toppedUpBalance = toNumber$1(info?.topped_up_balance);
|
|
6973
|
-
const isAvailable = typeof doc.is_available === "boolean" ? doc.is_available : void 0;
|
|
6974
|
-
return {
|
|
6975
|
-
provider: "deepseek",
|
|
6976
|
-
displayName: "DeepSeek",
|
|
6977
|
-
...currency !== void 0 ? { currency } : {},
|
|
6978
|
-
...totalBalance !== void 0 ? { totalBalance } : {},
|
|
6979
|
-
...grantedBalance !== void 0 ? { grantedBalance } : {},
|
|
6980
|
-
...toppedUpBalance !== void 0 ? { toppedUpBalance } : {},
|
|
6981
|
-
...isAvailable !== void 0 ? { isAvailable } : {}
|
|
6982
|
-
};
|
|
6983
|
-
});
|
|
7435
|
+
function queryDeepSeek(url, key) {
|
|
7436
|
+
return queryBearerBalance(url, key, "deepseek", "DeepSeek", parseDeepSeekBalance);
|
|
6984
7437
|
}
|
|
6985
7438
|
/**
|
|
6986
7439
|
* Query the Moonshot/Kimi account balance.
|
|
6987
|
-
* @param
|
|
6988
|
-
* @param apiKeyEnv - credential reference resolving the Moonshot API key.
|
|
7440
|
+
* @param key - resolved credential for this query.
|
|
6989
7441
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
6990
7442
|
*/
|
|
6991
|
-
function queryMoonshot(
|
|
6992
|
-
return queryBearerBalance(
|
|
7443
|
+
function queryMoonshot(url, key) {
|
|
7444
|
+
return queryBearerBalance(url, key, "月之暗面", "月之暗面", (data) => {
|
|
6993
7445
|
const doc = data;
|
|
6994
7446
|
const totalBalance = toNumber$1(doc.data?.available_balance);
|
|
6995
7447
|
const grantedBalance = toNumber$1(doc.data?.voucher_balance);
|
|
@@ -7006,12 +7458,11 @@ function queryMoonshot(ctx, apiKeyEnv) {
|
|
|
7006
7458
|
}
|
|
7007
7459
|
/**
|
|
7008
7460
|
* Query the StepFun (阶跃星辰) account balance.
|
|
7009
|
-
* @param
|
|
7010
|
-
* @param apiKeyEnv - credential reference resolving the StepFun API key.
|
|
7461
|
+
* @param key - resolved credential for this query.
|
|
7011
7462
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
7012
7463
|
*/
|
|
7013
|
-
function queryStepFun(
|
|
7014
|
-
return queryBearerBalance(
|
|
7464
|
+
function queryStepFun(url, key) {
|
|
7465
|
+
return queryBearerBalance(url, key, "阶跃星辰", "阶跃星辰", (data) => {
|
|
7015
7466
|
const doc = data;
|
|
7016
7467
|
const totalBalance = toNumber$1(doc.balance);
|
|
7017
7468
|
const toppedUpBalance = toNumber$1(doc.total_cash_balance);
|
|
@@ -7028,12 +7479,11 @@ function queryStepFun(ctx, apiKeyEnv) {
|
|
|
7028
7479
|
}
|
|
7029
7480
|
/**
|
|
7030
7481
|
* Query the SiliconFlow (硅基流动) account balance.
|
|
7031
|
-
* @param
|
|
7032
|
-
* @param apiKeyEnv - credential reference resolving the SiliconFlow API key.
|
|
7482
|
+
* @param key - resolved credential for this query.
|
|
7033
7483
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
7034
7484
|
*/
|
|
7035
|
-
function querySiliconFlow(
|
|
7036
|
-
return queryBearerBalance(
|
|
7485
|
+
function querySiliconFlow(url, key) {
|
|
7486
|
+
return queryBearerBalance(url, key, "硅基流动", "硅基流动", (data) => {
|
|
7037
7487
|
const doc = data;
|
|
7038
7488
|
const inner = doc.data ?? doc;
|
|
7039
7489
|
const totalBalance = toNumber$1(inner.balance ?? inner.balance_cny);
|
|
@@ -7047,12 +7497,11 @@ function querySiliconFlow(ctx, apiKeyEnv) {
|
|
|
7047
7497
|
}
|
|
7048
7498
|
/**
|
|
7049
7499
|
* Query the xAI (Grok) credit balance.
|
|
7050
|
-
* @param
|
|
7051
|
-
* @param apiKeyEnv - credential reference resolving the xAI API key.
|
|
7500
|
+
* @param key - resolved credential for this query.
|
|
7052
7501
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
7053
7502
|
*/
|
|
7054
|
-
function queryXai(
|
|
7055
|
-
return queryBearerBalance(
|
|
7503
|
+
function queryXai(url, key) {
|
|
7504
|
+
return queryBearerBalance(url, key, "xAI", "xAI", (data) => {
|
|
7056
7505
|
const cents = toNumber$1(data.total?.val);
|
|
7057
7506
|
const totalBalance = cents === void 0 ? void 0 : Math.abs(cents) / 100;
|
|
7058
7507
|
return {
|
|
@@ -7085,11 +7534,10 @@ function pickTokenDanceBalanceCny(data) {
|
|
|
7085
7534
|
/**
|
|
7086
7535
|
* 查询 TokenDance Space 钱包余额(issue #26/#27)。`queryBearerBalance` 已覆盖
|
|
7087
7536
|
* 认证失败(401 → unauthorized)与熔断/超时/重试,这里只负责微元 → 元换算。
|
|
7088
|
-
* @param
|
|
7089
|
-
* @param apiKeyEnv - credential reference resolving the TokenDance API key.
|
|
7537
|
+
* @param key - resolved credential for this query.
|
|
7090
7538
|
*/
|
|
7091
|
-
function queryTokenDance(
|
|
7092
|
-
return queryBearerBalance(
|
|
7539
|
+
function queryTokenDance(url, key) {
|
|
7540
|
+
return queryBearerBalance(url, key, "TokenDance", "TokenDance", (data) => {
|
|
7093
7541
|
const cny = pickTokenDanceBalanceCny(data);
|
|
7094
7542
|
return {
|
|
7095
7543
|
provider: "TokenDance",
|
|
@@ -7104,12 +7552,11 @@ function queryTokenDance(ctx, apiKeyEnv) {
|
|
|
7104
7552
|
* 与订阅(zai-coding-cn 的 Coding Plan)互补:一个平台可同时有钱包余额与订阅
|
|
7105
7553
|
* 套餐,两者各读各的(TokenLedger 同款双读姿态)。Z.ai global 域币种为 USD,
|
|
7106
7554
|
* 本函数固定走国内 CNY 域(open.bigmodel.cn),币种不猜,仅覆盖国内域。
|
|
7107
|
-
* @param
|
|
7108
|
-
* @param apiKeyEnv - credential reference resolving the Zhipu API key.
|
|
7555
|
+
* @param key - resolved credential for this query.
|
|
7109
7556
|
* @returns the balance row, or an error row when the key/endpoint misbehaves.
|
|
7110
7557
|
*/
|
|
7111
|
-
function queryZhipu(
|
|
7112
|
-
return queryBearerBalance(
|
|
7558
|
+
function queryZhipu(url, key) {
|
|
7559
|
+
return queryBearerBalance(url, key, "智谱 AI", "智谱 AI", (data) => {
|
|
7113
7560
|
const doc = data;
|
|
7114
7561
|
const totalBalance = toNumber$1(doc.balance?.available) ?? toNumber$1(doc.balance?.total);
|
|
7115
7562
|
return {
|
|
@@ -7120,71 +7567,43 @@ function queryZhipu(ctx, apiKeyEnv) {
|
|
|
7120
7567
|
};
|
|
7121
7568
|
});
|
|
7122
7569
|
}
|
|
7570
|
+
function bearer(route, displayName, endpoint, query) {
|
|
7571
|
+
return {
|
|
7572
|
+
route,
|
|
7573
|
+
displayName,
|
|
7574
|
+
endpoint,
|
|
7575
|
+
query: (key) => query(endpoint, key)
|
|
7576
|
+
};
|
|
7577
|
+
}
|
|
7123
7578
|
const QUERIERS = [
|
|
7124
|
-
|
|
7125
|
-
|
|
7126
|
-
|
|
7127
|
-
|
|
7128
|
-
|
|
7129
|
-
|
|
7130
|
-
|
|
7131
|
-
|
|
7132
|
-
|
|
7133
|
-
},
|
|
7134
|
-
{
|
|
7135
|
-
route: "stepfun",
|
|
7136
|
-
displayName: "阶跃星辰",
|
|
7137
|
-
querier: queryStepFun
|
|
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
|
-
},
|
|
7579
|
+
bearer("deepseek", "deepseek", DEEPSEEK_BALANCE_URL, queryDeepSeek),
|
|
7580
|
+
bearer("moonshot", "月之暗面", MOONSHOT_BALANCE_URL, queryMoonshot),
|
|
7581
|
+
bearer("stepfun", "阶跃星辰", STEPFUN_BALANCE_URL, queryStepFun),
|
|
7582
|
+
bearer("siliconflow", "硅基流动", SILICONFLOW_BALANCE_URL, querySiliconFlow),
|
|
7583
|
+
bearer("xai", "xAI", XAI_CREDITS_URL, queryXai),
|
|
7584
|
+
bearer("zhipu", "智谱 AI", ZHIPU_BALANCE_URL, queryZhipu),
|
|
7585
|
+
bearer("zai-coding-cn", "智谱 AI", ZHIPU_BALANCE_URL, queryZhipu),
|
|
7586
|
+
bearer("tokendance", "TokenDance", TOKENDANCE_BALANCE_URL, queryTokenDance),
|
|
7587
|
+
bearer("tokendance-space", "TokenDance", TOKENDANCE_BALANCE_URL, queryTokenDance),
|
|
7169
7588
|
{
|
|
7170
7589
|
route: "tencent-tokenhub",
|
|
7171
7590
|
displayName: "腾讯云 TokenHub",
|
|
7172
|
-
|
|
7591
|
+
query: queryTencentTokenPlan
|
|
7173
7592
|
},
|
|
7174
7593
|
{
|
|
7175
7594
|
route: "tokenhub",
|
|
7176
7595
|
displayName: "腾讯云 TokenHub",
|
|
7177
|
-
|
|
7596
|
+
query: queryTencentTokenPlan
|
|
7178
7597
|
},
|
|
7179
7598
|
{
|
|
7180
7599
|
route: "tencent",
|
|
7181
7600
|
displayName: "腾讯云 TokenHub",
|
|
7182
|
-
|
|
7601
|
+
query: queryTencentTokenPlan
|
|
7183
7602
|
},
|
|
7184
7603
|
{
|
|
7185
7604
|
route: "tencentcloud",
|
|
7186
7605
|
displayName: "腾讯云 TokenHub",
|
|
7187
|
-
|
|
7606
|
+
query: queryTencentTokenPlan
|
|
7188
7607
|
}
|
|
7189
7608
|
];
|
|
7190
7609
|
/**
|
|
@@ -7197,7 +7616,7 @@ const QUERIERS = [
|
|
|
7197
7616
|
* @param providers - the llm-pi-ai providers dict (`<route> → { apiKeyEnv? }`).
|
|
7198
7617
|
* @returns the balance rows (one per provider).
|
|
7199
7618
|
*/
|
|
7200
|
-
async function queryBalances(ctx, providers) {
|
|
7619
|
+
async function queryBalances(ctx, providers, client) {
|
|
7201
7620
|
const resolveRef = async (name) => {
|
|
7202
7621
|
try {
|
|
7203
7622
|
const hit = await ctx.credentials.resolve(credentialRef(name));
|
|
@@ -7206,57 +7625,84 @@ async function queryBalances(ctx, providers) {
|
|
|
7206
7625
|
return;
|
|
7207
7626
|
}
|
|
7208
7627
|
};
|
|
7209
|
-
const
|
|
7628
|
+
const originOwners = /* @__PURE__ */ new Map();
|
|
7629
|
+
const origins = /* @__PURE__ */ new Map();
|
|
7630
|
+
for (const [route, { baseURL }] of Object.entries(providers)) {
|
|
7631
|
+
if (baseURL === void 0) continue;
|
|
7632
|
+
const origin = URL.parse(baseURL)?.origin ?? "";
|
|
7633
|
+
origins.set(route, origin);
|
|
7634
|
+
const owners = originOwners.get(origin) ?? [];
|
|
7635
|
+
owners.push(route);
|
|
7636
|
+
originOwners.set(origin, owners);
|
|
7637
|
+
}
|
|
7638
|
+
const resolved = await Promise.all(QUERIERS.map(async (spec) => {
|
|
7639
|
+
const { route, endpoint } = spec;
|
|
7210
7640
|
const env = providers[route]?.apiKeyEnv;
|
|
7211
|
-
const
|
|
7212
|
-
const
|
|
7641
|
+
const hit = await firstResolvedRef([...env ? [env] : [], ...routeKeyRefCandidates(route)], resolveRef);
|
|
7642
|
+
const expectedOrigin = endpoint && new URL(endpoint).origin;
|
|
7643
|
+
const configuredOrigin = origins.get(route);
|
|
7644
|
+
const verified = configuredOrigin === void 0 || expectedOrigin !== void 0 && configuredOrigin === expectedOrigin;
|
|
7213
7645
|
return {
|
|
7214
|
-
|
|
7215
|
-
|
|
7216
|
-
|
|
7217
|
-
|
|
7646
|
+
...spec,
|
|
7647
|
+
key: hit?.value,
|
|
7648
|
+
expectedOrigin,
|
|
7649
|
+
verified
|
|
7218
7650
|
};
|
|
7219
7651
|
}));
|
|
7220
|
-
const
|
|
7652
|
+
const present = (item) => item.key !== void 0 || Object.hasOwn(providers, item.route);
|
|
7653
|
+
const presentVendors = new Set(resolved.filter(present).map((item) => item.displayName));
|
|
7654
|
+
const targets = [];
|
|
7221
7655
|
for (const item of resolved) {
|
|
7222
|
-
|
|
7223
|
-
|
|
7224
|
-
|
|
7225
|
-
|
|
7226
|
-
|
|
7227
|
-
|
|
7656
|
+
if (!present(item) && (presentVendors.has(item.displayName) || targets.some((other) => other.displayName === item.displayName))) continue;
|
|
7657
|
+
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));
|
|
7658
|
+
if (shared) shared.aliases.push(item.route);
|
|
7659
|
+
else targets.push({
|
|
7660
|
+
...item,
|
|
7661
|
+
aliases: []
|
|
7228
7662
|
});
|
|
7229
7663
|
}
|
|
7230
|
-
|
|
7231
|
-
|
|
7664
|
+
const apiRows = await Promise.all(targets.map(async ({ route, displayName, query, key, aliases, expectedOrigin, verified }) => {
|
|
7665
|
+
const row = key === void 0 ? {
|
|
7232
7666
|
provider: displayName,
|
|
7233
7667
|
displayName,
|
|
7234
7668
|
error: "unconfigured"
|
|
7235
|
-
});
|
|
7236
|
-
|
|
7669
|
+
} : await query(key);
|
|
7670
|
+
const sourceRoute = row.sourceRoute ?? route;
|
|
7671
|
+
const attributed = {
|
|
7672
|
+
...row,
|
|
7673
|
+
sourceRoute,
|
|
7674
|
+
walletKind: row.walletKind ?? "api-key",
|
|
7675
|
+
attributedRoutes: row.attributedRoutes ?? (route === "deepseek" && key === void 0 ? [] : verified ? [sourceRoute, ...aliases] : []),
|
|
7676
|
+
...aliases.length > 0 ? { sourceRouteAliases: aliases } : {}
|
|
7677
|
+
};
|
|
7678
|
+
if (route === "deepseek" && key !== void 0) apiSources.set(attributed, createHash("sha256").update(key).digest("hex"));
|
|
7679
|
+
const owners = expectedOrigin && originOwners.get(expectedOrigin);
|
|
7680
|
+
if (attributed.walletKind === "api-key" && owners && owners.every((provider) => balanceCoversSite(attributed, siteBucketKey({
|
|
7681
|
+
kind: "direct",
|
|
7682
|
+
provider
|
|
7683
|
+
})))) return {
|
|
7684
|
+
...attributed,
|
|
7685
|
+
sourceOrigin: expectedOrigin
|
|
7686
|
+
};
|
|
7687
|
+
return attributed;
|
|
7237
7688
|
}));
|
|
7689
|
+
const account = await queryDeepSeekAccount(ctx, client);
|
|
7690
|
+
return [...apiRows, account];
|
|
7238
7691
|
}
|
|
7239
7692
|
/**
|
|
7240
7693
|
* 查询腾讯云 TokenHub Token Plan 套餐余量。凭据值格式 `<SecretId>:<SecretKey>`
|
|
7241
7694
|
* (云 API 密钥,非 TokenHub 推理 key)。链路:套餐列表取 TeamId → 套餐详情读
|
|
7242
7695
|
* 主额度包余量。管控面字段名未完全稳定,解析按语义键防御提取。
|
|
7243
|
-
* @param
|
|
7244
|
-
* @param apiKeyEnv - credential reference resolving the `<SecretId>:<SecretKey>` pair.
|
|
7696
|
+
* @param key - resolved credential for this query.
|
|
7245
7697
|
*/
|
|
7246
|
-
async function queryTencentTokenPlan(
|
|
7698
|
+
async function queryTencentTokenPlan(key) {
|
|
7247
7699
|
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
7700
|
if (!balanceGate.check(provider)) return {
|
|
7255
7701
|
provider,
|
|
7256
7702
|
displayName: provider,
|
|
7257
7703
|
error: "unreachable"
|
|
7258
7704
|
};
|
|
7259
|
-
const credential = parseTencentCredential(
|
|
7705
|
+
const credential = parseTencentCredential(key);
|
|
7260
7706
|
if (credential === void 0) return {
|
|
7261
7707
|
provider,
|
|
7262
7708
|
displayName: provider,
|
|
@@ -7485,7 +7931,7 @@ async function queryCustomBalances(ctx, configs) {
|
|
|
7485
7931
|
/** Abort a declared fetch when the upstream hangs beyond this budget. */
|
|
7486
7932
|
const FETCH_TIMEOUT_MS$2 = 8e3;
|
|
7487
7933
|
/** 响应体上限(字节):坏 / 恶意端点不能拖住面板或耗尽内存。 */
|
|
7488
|
-
const MAX_BODY_BYTES = 1e6;
|
|
7934
|
+
const MAX_BODY_BYTES$1 = 1e6;
|
|
7489
7935
|
/** 声明端点查询的熔断门:按(匹配 provider origin + path)独立熔断,各端点互不干扰。 */
|
|
7490
7936
|
const declaredGate = createCooldownGate({
|
|
7491
7937
|
failures: 3,
|
|
@@ -7629,42 +8075,40 @@ async function queryDeclaredEndpoints(ctx, providers, declarations) {
|
|
|
7629
8075
|
return await Promise.all(declarations.map(async (decl) => {
|
|
7630
8076
|
const displayName = typeof decl.displayName === "string" && decl.displayName !== "" ? decl.displayName : "已声明";
|
|
7631
8077
|
const provider = `declared:${displayName}`;
|
|
7632
|
-
const
|
|
7633
|
-
|
|
8078
|
+
const declOrigin = normalizeDeclaredOrigin(decl.origin);
|
|
8079
|
+
const matched = declOrigin === void 0 ? void 0 : byOrigin.get(declOrigin);
|
|
8080
|
+
const identity = {
|
|
7634
8081
|
provider,
|
|
7635
8082
|
displayName,
|
|
7636
8083
|
declared: true,
|
|
8084
|
+
walletKind: "relay",
|
|
8085
|
+
sourceRoute: matched?.route ?? provider,
|
|
8086
|
+
attributedRoutes: matched ? [matched.route] : []
|
|
8087
|
+
};
|
|
8088
|
+
const requestPath = compileDeclaredEndpoint(decl);
|
|
8089
|
+
if (requestPath === void 0) return {
|
|
8090
|
+
...identity,
|
|
7637
8091
|
error: "invalid",
|
|
7638
8092
|
reason: "path 必须单斜杠绝对路径"
|
|
7639
8093
|
};
|
|
7640
|
-
const declOrigin = normalizeDeclaredOrigin(decl.origin);
|
|
7641
|
-
const matched = declOrigin === void 0 ? void 0 : byOrigin.get(declOrigin);
|
|
7642
8094
|
if (matched === void 0) return {
|
|
7643
|
-
|
|
7644
|
-
displayName,
|
|
7645
|
-
declared: true,
|
|
8095
|
+
...identity,
|
|
7646
8096
|
error: "unconfigured",
|
|
7647
8097
|
reason: "未匹配到同源 provider(需先在 llm-pi-ai 配好 baseURL)"
|
|
7648
8098
|
};
|
|
7649
8099
|
const gateKey = `${declOrigin}${requestPath}`;
|
|
7650
8100
|
if (!declaredGate.check(gateKey)) return {
|
|
7651
|
-
|
|
7652
|
-
displayName,
|
|
7653
|
-
declared: true,
|
|
8101
|
+
...identity,
|
|
7654
8102
|
error: "unreachable"
|
|
7655
8103
|
};
|
|
7656
8104
|
const hit = await firstResolvedRef([...matched.apiKeyEnv !== void 0 ? [matched.apiKeyEnv] : [], ...routeKeyRefCandidates(matched.route)], resolveRef);
|
|
7657
8105
|
if (hit === void 0) return {
|
|
7658
|
-
|
|
7659
|
-
displayName,
|
|
7660
|
-
declared: true,
|
|
8106
|
+
...identity,
|
|
7661
8107
|
error: "unconfigured"
|
|
7662
8108
|
};
|
|
7663
8109
|
const url = new URL(requestPath, declOrigin);
|
|
7664
8110
|
if (url.origin !== declOrigin) return {
|
|
7665
|
-
|
|
7666
|
-
displayName,
|
|
7667
|
-
declared: true,
|
|
8111
|
+
...identity,
|
|
7668
8112
|
error: "invalid",
|
|
7669
8113
|
reason: "跨源路径被拒绝"
|
|
7670
8114
|
};
|
|
@@ -7680,9 +8124,7 @@ async function queryDeclaredEndpoints(ctx, providers, declarations) {
|
|
|
7680
8124
|
declaredGate.success(gateKey);
|
|
7681
8125
|
const nothingResolved = total === void 0 && granted === void 0 && used === void 0 && windows.length === 0;
|
|
7682
8126
|
return {
|
|
7683
|
-
|
|
7684
|
-
displayName,
|
|
7685
|
-
declared: true,
|
|
8127
|
+
...identity,
|
|
7686
8128
|
...total !== void 0 ? { totalBalance: total } : {},
|
|
7687
8129
|
...granted !== void 0 ? { grantedBalance: granted } : {},
|
|
7688
8130
|
...typeof currency === "string" && currency !== "" ? { currency } : {},
|
|
@@ -7696,9 +8138,7 @@ async function queryDeclaredEndpoints(ctx, providers, declarations) {
|
|
|
7696
8138
|
} catch {
|
|
7697
8139
|
declaredGate.fail(gateKey);
|
|
7698
8140
|
return {
|
|
7699
|
-
|
|
7700
|
-
displayName,
|
|
7701
|
-
declared: true,
|
|
8141
|
+
...identity,
|
|
7702
8142
|
error: "unreachable"
|
|
7703
8143
|
};
|
|
7704
8144
|
}
|
|
@@ -7726,7 +8166,7 @@ async function fetchDeclaredBody(url, raw, apiKey) {
|
|
|
7726
8166
|
if (response.status === 401 || response.status === 403) throw new HttpStatusError("unauthorized", response.status);
|
|
7727
8167
|
if (!response.ok) throw new HttpStatusError("http-error", response.status);
|
|
7728
8168
|
const text = await response.text();
|
|
7729
|
-
if (text.length > MAX_BODY_BYTES) throw new HttpStatusError("body-too-large", 413);
|
|
8169
|
+
if (text.length > MAX_BODY_BYTES$1) throw new HttpStatusError("body-too-large", 413);
|
|
7730
8170
|
try {
|
|
7731
8171
|
return JSON.parse(text);
|
|
7732
8172
|
} catch (cause) {
|
|
@@ -7765,6 +8205,30 @@ var HttpStatusError = class extends Error {
|
|
|
7765
8205
|
*
|
|
7766
8206
|
* 纯函数:输入上一基准与本次余额查询结果,输出新基准与对账事件,可独立单测。
|
|
7767
8207
|
*/
|
|
8208
|
+
/** The daily official aggregate also includes other deepseek-* routes, the official
|
|
8209
|
+
* origin (possibly shared), and web search (estimated cost, separate credentials).
|
|
8210
|
+
* Require complete site coverage and exclude unrelated routes before comparing. */
|
|
8211
|
+
function platformSpend(doc, day, providers, allowDirect = true) {
|
|
8212
|
+
if (doc.staleSnapshot || doc.sessionListError !== void 0 || doc.unreadableSessions) return void 0;
|
|
8213
|
+
const owners = Object.entries(providers).filter(([, p]) => p.baseURL !== void 0 && siteOriginOf(p.baseURL) === "https://api.deepseek.com");
|
|
8214
|
+
const uniqueOrigin = owners.length === 1 && owners[0]?.[0] === "deepseek";
|
|
8215
|
+
if (!allowDirect && !uniqueOrigin) return void 0;
|
|
8216
|
+
const daily = doc.byDay[day];
|
|
8217
|
+
if (daily === void 0) return 0;
|
|
8218
|
+
const models = doc.byDayModelsSite?.[day];
|
|
8219
|
+
if (models === void 0) return void 0;
|
|
8220
|
+
let coveredCalls = 0, coveredCost = 0, cost = 0;
|
|
8221
|
+
for (const sites of Object.values(models)) for (const [site, cell] of Object.entries(sites)) {
|
|
8222
|
+
coveredCalls += cell.officialCalls;
|
|
8223
|
+
coveredCost += cell.officialCost;
|
|
8224
|
+
if (site === "direct:deepseek" && !allowDirect) return void 0;
|
|
8225
|
+
if (site === `site:https://api.deepseek.com` && !uniqueOrigin) return void 0;
|
|
8226
|
+
if (site !== "direct:deepseek" && site !== `site:https://api.deepseek.com`) continue;
|
|
8227
|
+
if (cell.searchCalls || cell.officialCalls !== cell.calls || cell.calls && cell.officialCost <= 0) return void 0;
|
|
8228
|
+
cost += cell.officialCost;
|
|
8229
|
+
}
|
|
8230
|
+
return coveredCalls === daily.officialCalls && Math.abs(coveredCost - daily.officialCost) < 1e-6 ? cost : void 0;
|
|
8231
|
+
}
|
|
7768
8232
|
/** 余额差对账阈值下限(元):消费低于该值时不值得提示,避免小金额波动刷屏。 */
|
|
7769
8233
|
const MIN_DRIFT_ABS = .3;
|
|
7770
8234
|
/** 余额差相对容忍度:偏差超过较大一方的该比例才判漂移。 */
|
|
@@ -7799,23 +8263,27 @@ function snapOf(ref, balance, nowMs) {
|
|
|
7799
8263
|
* @param todayOfficialCost - 本地账本当日的官方渠道费用(CNY)。
|
|
7800
8264
|
* @param dayKey - 本地日期键(YYYY-MM-DD)。
|
|
7801
8265
|
* @param nowMs - 当前时刻(epoch ms)。
|
|
7802
|
-
* @returns 新基准与对账事件;余额不可用(无 totalBalance)时返回 `{ ref:
|
|
8266
|
+
* @returns 新基准与对账事件;余额不可用(无 totalBalance)时返回 `{ ref: null, event: null }`。
|
|
7803
8267
|
*/
|
|
7804
|
-
function reconcileBalanceDelta(prevRef, balance, todayOfficialCost, dayKey, nowMs) {
|
|
8268
|
+
function reconcileBalanceDelta(prevRef, balance, todayOfficialCost, dayKey, nowMs, source = "deepseek") {
|
|
7805
8269
|
const total = balance.totalBalance;
|
|
7806
8270
|
if (typeof total !== "number" || !Number.isFinite(total)) return {
|
|
7807
|
-
ref:
|
|
8271
|
+
ref: null,
|
|
7808
8272
|
event: null
|
|
7809
8273
|
};
|
|
7810
|
-
const snap =
|
|
7811
|
-
|
|
7812
|
-
|
|
7813
|
-
|
|
7814
|
-
|
|
8274
|
+
const snap = {
|
|
8275
|
+
...snapOf({
|
|
8276
|
+
date: dayKey,
|
|
8277
|
+
currency: ""
|
|
8278
|
+
}, balance, nowMs),
|
|
8279
|
+
source,
|
|
8280
|
+
costAtBaseline: todayOfficialCost
|
|
8281
|
+
};
|
|
8282
|
+
if (prevRef === null || prevRef.date !== dayKey || prevRef.source !== source || !Number.isFinite(prevRef.costAtBaseline)) return {
|
|
7815
8283
|
ref: snap,
|
|
7816
8284
|
event: { kind: "baseline" }
|
|
7817
8285
|
};
|
|
7818
|
-
if (prevRef.currency !== snap.currency) return {
|
|
8286
|
+
if (prevRef.currency !== snap.currency || todayOfficialCost < prevRef.costAtBaseline || snap.total > prevRef.total + .009) return {
|
|
7819
8287
|
ref: snap,
|
|
7820
8288
|
event: { kind: "structure-reset" }
|
|
7821
8289
|
};
|
|
@@ -7828,7 +8296,7 @@ function reconcileBalanceDelta(prevRef, balance, todayOfficialCost, dayKey, nowM
|
|
|
7828
8296
|
ref: prevRef,
|
|
7829
8297
|
event: { kind: "flat" }
|
|
7830
8298
|
};
|
|
7831
|
-
const cost =
|
|
8299
|
+
const cost = todayOfficialCost - prevRef.costAtBaseline;
|
|
7832
8300
|
if (Math.abs(spent - cost) > Math.max(MIN_DRIFT_ABS, DRIFT_RELATIVE * Math.max(spent, cost))) return {
|
|
7833
8301
|
ref: prevRef,
|
|
7834
8302
|
event: {
|
|
@@ -9671,6 +10139,312 @@ function guardLoopback(req, res, trustedHosts = /* @__PURE__ */ new Set()) {
|
|
|
9671
10139
|
return true;
|
|
9672
10140
|
}
|
|
9673
10141
|
//#endregion
|
|
10142
|
+
//#region lib/types/peak-schedule-store.js
|
|
10143
|
+
const emptyHistory = () => ({
|
|
10144
|
+
version: 3,
|
|
10145
|
+
revisions: []
|
|
10146
|
+
});
|
|
10147
|
+
var ScheduleClockConflict = class extends Error {};
|
|
10148
|
+
function readSaved(path) {
|
|
10149
|
+
let bytes;
|
|
10150
|
+
try {
|
|
10151
|
+
bytes = readFileSync(path);
|
|
10152
|
+
} catch (error) {
|
|
10153
|
+
return {
|
|
10154
|
+
history: emptyHistory(),
|
|
10155
|
+
notices: error.code === "ENOENT" ? [] : [{ code: "unreadableSchedule" }]
|
|
10156
|
+
};
|
|
10157
|
+
}
|
|
10158
|
+
try {
|
|
10159
|
+
return {
|
|
10160
|
+
...readScheduleHistory(JSON.parse(bytes.toString("utf8"))),
|
|
10161
|
+
bytes
|
|
10162
|
+
};
|
|
10163
|
+
} catch {
|
|
10164
|
+
return {
|
|
10165
|
+
history: emptyHistory(),
|
|
10166
|
+
notices: [{ code: "malformedSchedule" }],
|
|
10167
|
+
bytes
|
|
10168
|
+
};
|
|
10169
|
+
}
|
|
10170
|
+
}
|
|
10171
|
+
/** Drop only writes that repeat the immediately preceding state of that key.
|
|
10172
|
+
* A→B→A and deletions after a real override remain distinct historical intervals. */
|
|
10173
|
+
function compact(history) {
|
|
10174
|
+
const state = /* @__PURE__ */ new Map();
|
|
10175
|
+
return {
|
|
10176
|
+
version: 3,
|
|
10177
|
+
revisions: history.revisions.flatMap((row) => {
|
|
10178
|
+
const changes = Object.fromEntries(Object.entries(row.changes).filter(([key, rule]) => {
|
|
10179
|
+
const value = JSON.stringify(rule);
|
|
10180
|
+
if ((state.get(key) ?? "null") === value) return false;
|
|
10181
|
+
state.set(key, value);
|
|
10182
|
+
return true;
|
|
10183
|
+
}));
|
|
10184
|
+
return Object.keys(changes).length ? [{
|
|
10185
|
+
...row,
|
|
10186
|
+
changes
|
|
10187
|
+
}] : [];
|
|
10188
|
+
})
|
|
10189
|
+
};
|
|
10190
|
+
}
|
|
10191
|
+
function openScheduleStore(path, eligible, now = Date.now) {
|
|
10192
|
+
let saved = readSaved(path);
|
|
10193
|
+
function project() {
|
|
10194
|
+
const config = emptySchedule();
|
|
10195
|
+
const skipped = /* @__PURE__ */ new Set();
|
|
10196
|
+
for (const { changes } of saved.history.revisions) for (const [key, rule] of Object.entries(changes)) if (rule === null) {
|
|
10197
|
+
delete config.models[key];
|
|
10198
|
+
skipped.delete(key);
|
|
10199
|
+
} else if (eligible(modelFromScheduleKey(key))) config.models[key] = rule;
|
|
10200
|
+
else skipped.add(key);
|
|
10201
|
+
return {
|
|
10202
|
+
config,
|
|
10203
|
+
notices: [...saved.notices, ...Array.from(skipped, (detail) => ({
|
|
10204
|
+
code: "ineligibleModel",
|
|
10205
|
+
detail
|
|
10206
|
+
}))]
|
|
10207
|
+
};
|
|
10208
|
+
}
|
|
10209
|
+
let active = project();
|
|
10210
|
+
let queue = Promise.resolve();
|
|
10211
|
+
return {
|
|
10212
|
+
current: () => active.config,
|
|
10213
|
+
history: () => saved.history,
|
|
10214
|
+
notices: () => active.notices,
|
|
10215
|
+
save(edit, latestEventTime = -1) {
|
|
10216
|
+
const commit = queue.then(async () => {
|
|
10217
|
+
const { changes } = parseScheduleEdit(edit);
|
|
10218
|
+
mkdirSync(dirname(path), {
|
|
10219
|
+
recursive: true,
|
|
10220
|
+
mode: 448
|
|
10221
|
+
});
|
|
10222
|
+
await withFileLock(path, async () => {
|
|
10223
|
+
const previous = readSaved(path);
|
|
10224
|
+
if (previous.notices.some((n) => n.code === "unreadableSchedule")) throw Error("Schedule unavailable");
|
|
10225
|
+
const revisions = previous.history.revisions;
|
|
10226
|
+
const delta = Object.fromEntries(Object.entries(changes).filter(([key, rule]) => {
|
|
10227
|
+
const latest = revisions.findLast((row) => Object.hasOwn(row.changes, key))?.changes[key] ?? null;
|
|
10228
|
+
return JSON.stringify(latest) !== JSON.stringify(rule);
|
|
10229
|
+
}));
|
|
10230
|
+
if (!Object.keys(delta).length) {
|
|
10231
|
+
if (previous.bytes?.equals(saved.bytes ?? Buffer.alloc(0)) === false) {
|
|
10232
|
+
saved = previous;
|
|
10233
|
+
active = project();
|
|
10234
|
+
}
|
|
10235
|
+
return;
|
|
10236
|
+
}
|
|
10237
|
+
if (previous.bytes !== void 0) {
|
|
10238
|
+
await writeFileAtomic(`${path}.bak`, previous.bytes, {
|
|
10239
|
+
mode: 384,
|
|
10240
|
+
dirMode: 448
|
|
10241
|
+
});
|
|
10242
|
+
if (previous.notices.length) {
|
|
10243
|
+
const hash = createHash("sha256").update(previous.bytes).digest("hex");
|
|
10244
|
+
await writeFileAtomic(`${path}.recovery-${hash}`, previous.bytes, {
|
|
10245
|
+
mode: 384,
|
|
10246
|
+
dirMode: 448
|
|
10247
|
+
});
|
|
10248
|
+
}
|
|
10249
|
+
}
|
|
10250
|
+
const savedAt = now();
|
|
10251
|
+
const lastRevision = revisions.at(-1)?.effectiveFromMs ?? -1;
|
|
10252
|
+
if (savedAt < lastRevision || savedAt <= latestEventTime) throw new ScheduleClockConflict("scheduleClockConflict");
|
|
10253
|
+
const effectiveFromMs = Math.max(savedAt, lastRevision + 1);
|
|
10254
|
+
if (!Number.isSafeInteger(effectiveFromMs) || effectiveFromMs < 0 || effectiveFromMs > 864e13) throw Error("Invalid schedule clock");
|
|
10255
|
+
const history = compact({
|
|
10256
|
+
version: 3,
|
|
10257
|
+
revisions: [...revisions, {
|
|
10258
|
+
effectiveFromMs,
|
|
10259
|
+
changes: delta,
|
|
10260
|
+
audit: {
|
|
10261
|
+
source: "local-api",
|
|
10262
|
+
actor: "unidentified"
|
|
10263
|
+
}
|
|
10264
|
+
}]
|
|
10265
|
+
});
|
|
10266
|
+
const json = JSON.stringify(history);
|
|
10267
|
+
await writeFileAtomic(path, json, {
|
|
10268
|
+
mode: 384,
|
|
10269
|
+
dirMode: 448
|
|
10270
|
+
});
|
|
10271
|
+
saved = {
|
|
10272
|
+
history,
|
|
10273
|
+
notices: [],
|
|
10274
|
+
bytes: Buffer.from(json)
|
|
10275
|
+
};
|
|
10276
|
+
active = project();
|
|
10277
|
+
}, { waitMs: 2e3 });
|
|
10278
|
+
});
|
|
10279
|
+
queue = commit.catch(() => {});
|
|
10280
|
+
return commit;
|
|
10281
|
+
}
|
|
10282
|
+
};
|
|
10283
|
+
}
|
|
10284
|
+
//#endregion
|
|
10285
|
+
//#region lib/types/routes/peak-schedule.js
|
|
10286
|
+
/** Domain validation failures are distinct from storage failures. */
|
|
10287
|
+
var PeakScheduleInputError = class extends Error {};
|
|
10288
|
+
const MAX_BODY_BYTES = 1048576;
|
|
10289
|
+
function reply(res, status, value) {
|
|
10290
|
+
res.writeHead(status, {
|
|
10291
|
+
"content-type": "application/json; charset=utf-8",
|
|
10292
|
+
"cache-control": "no-store"
|
|
10293
|
+
});
|
|
10294
|
+
res.end(JSON.stringify(value));
|
|
10295
|
+
}
|
|
10296
|
+
function registerPeakScheduleRoute(ctx, deps) {
|
|
10297
|
+
ctx.effect(() => ctx.webServer.register({
|
|
10298
|
+
kind: "exact",
|
|
10299
|
+
path: "/api/billing/peak-schedule",
|
|
10300
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
10301
|
+
handler: async (req, res) => {
|
|
10302
|
+
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
10303
|
+
let raw;
|
|
10304
|
+
if (req.method === "POST") {
|
|
10305
|
+
if (!isLoopbackOrigin(req.headers.origin)) return reply(res, 403, {
|
|
10306
|
+
error: "forbidden: loopback only",
|
|
10307
|
+
message: "仅限本机请求"
|
|
10308
|
+
});
|
|
10309
|
+
if (req.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") return reply(res, 415, {
|
|
10310
|
+
error: "unsupported content-type",
|
|
10311
|
+
message: "请使用 application/json"
|
|
10312
|
+
});
|
|
10313
|
+
const chunks = [];
|
|
10314
|
+
let bytes = 0;
|
|
10315
|
+
try {
|
|
10316
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
10317
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
10318
|
+
bytes += buf.length;
|
|
10319
|
+
if (bytes > MAX_BODY_BYTES) {
|
|
10320
|
+
req.resume();
|
|
10321
|
+
return reply(res, 413, {
|
|
10322
|
+
error: "body too large",
|
|
10323
|
+
message: "请求体过大"
|
|
10324
|
+
});
|
|
10325
|
+
}
|
|
10326
|
+
chunks.push(buf);
|
|
10327
|
+
}
|
|
10328
|
+
raw = JSON.parse(Buffer.concat(chunks, bytes).toString("utf8"));
|
|
10329
|
+
} catch {
|
|
10330
|
+
return reply(res, 400, {
|
|
10331
|
+
error: "invalid json body",
|
|
10332
|
+
message: "请求 JSON 无效"
|
|
10333
|
+
});
|
|
10334
|
+
}
|
|
10335
|
+
}
|
|
10336
|
+
let snapshot;
|
|
10337
|
+
try {
|
|
10338
|
+
snapshot = req.method === "POST" ? await deps.save(raw) : await deps.read();
|
|
10339
|
+
} catch (error) {
|
|
10340
|
+
if (req.method === "POST" && error instanceof PeakScheduleInputError) return reply(res, 400, {
|
|
10341
|
+
error: error.message,
|
|
10342
|
+
message: "峰谷设置格式无效 / Invalid schedule format"
|
|
10343
|
+
});
|
|
10344
|
+
if (req.method === "POST" && error instanceof ScheduleClockConflict) return reply(res, 409, {
|
|
10345
|
+
error: "scheduleClockConflict",
|
|
10346
|
+
message: "生效时刻早于已记录的调用或修订 / Schedule clock conflict"
|
|
10347
|
+
});
|
|
10348
|
+
return reply(res, 503, {
|
|
10349
|
+
error: "peak schedule unavailable",
|
|
10350
|
+
message: "峰谷设置暂不可用"
|
|
10351
|
+
});
|
|
10352
|
+
}
|
|
10353
|
+
reply(res, 200, snapshot);
|
|
10354
|
+
}
|
|
10355
|
+
}), "usage-billing: peak-schedule route");
|
|
10356
|
+
}
|
|
10357
|
+
//#endregion
|
|
10358
|
+
//#region lib/types/peak-schedule-models.js
|
|
10359
|
+
async function discover$1(llm, route) {
|
|
10360
|
+
if (!llm?.listModels) throw Error("Model registry unavailable");
|
|
10361
|
+
let timer;
|
|
10362
|
+
try {
|
|
10363
|
+
const models = await Promise.race([llm.listModels(route), new Promise((_, reject) => {
|
|
10364
|
+
timer = setTimeout(() => reject(Error("Model discovery timed out")), 5e3);
|
|
10365
|
+
})]);
|
|
10366
|
+
if (!Array.isArray(models)) throw Error("Invalid model registry response");
|
|
10367
|
+
return models;
|
|
10368
|
+
} finally {
|
|
10369
|
+
clearTimeout(timer);
|
|
10370
|
+
}
|
|
10371
|
+
}
|
|
10372
|
+
function eligibleScheduleModel(key) {
|
|
10373
|
+
const entry = modelOf(key);
|
|
10374
|
+
return key === entry.key && entry.provider === "DeepSeek" && entry.price.offPeak !== void 0 && entry.tierSemantics !== "latency";
|
|
10375
|
+
}
|
|
10376
|
+
/** Cache only remote discovery. Route identity and locally declared models are refreshed every request. */
|
|
10377
|
+
function createScheduleModelDiscovery(now = Date.now, ttlMs = 6e4) {
|
|
10378
|
+
const cache = /* @__PURE__ */ new Map();
|
|
10379
|
+
let service;
|
|
10380
|
+
function listModels(llm, id, baseURL) {
|
|
10381
|
+
const key = JSON.stringify([id, baseURL]);
|
|
10382
|
+
const hit = cache.get(key);
|
|
10383
|
+
if (hit && hit.expires > now()) return hit.result;
|
|
10384
|
+
const entry = {
|
|
10385
|
+
expires: Infinity,
|
|
10386
|
+
result: discover$1(llm, id)
|
|
10387
|
+
};
|
|
10388
|
+
cache.set(key, entry);
|
|
10389
|
+
entry.result.then(() => {
|
|
10390
|
+
entry.expires = now() + ttlMs;
|
|
10391
|
+
}, () => {
|
|
10392
|
+
entry.expires = now() + Math.min(ttlMs, 15e3);
|
|
10393
|
+
});
|
|
10394
|
+
return entry.result;
|
|
10395
|
+
}
|
|
10396
|
+
return async (llm, profiles, aliases) => {
|
|
10397
|
+
if (service !== llm) {
|
|
10398
|
+
cache.clear();
|
|
10399
|
+
service = llm;
|
|
10400
|
+
}
|
|
10401
|
+
const routes = /* @__PURE__ */ new Map();
|
|
10402
|
+
const notices = [];
|
|
10403
|
+
try {
|
|
10404
|
+
if (!llm?.listProviders) throw Error();
|
|
10405
|
+
for (const p of llm.listProviders()) if (typeof p.id === "string") routes.set(p.id, p.name || p.id);
|
|
10406
|
+
} catch {
|
|
10407
|
+
notices.push({ code: "discoveryFailed" });
|
|
10408
|
+
}
|
|
10409
|
+
const views = { ...profiles };
|
|
10410
|
+
for (const id of routes.keys()) if (!Object.hasOwn(views, id)) views[id] = {};
|
|
10411
|
+
for (const [id, profile] of Object.entries(profiles)) if (profile.models) routes.set(id, profile.displayName || id);
|
|
10412
|
+
const liveCacheKeys = new Set([...routes.keys()].map((id) => JSON.stringify([id, profiles[id]?.baseURL])));
|
|
10413
|
+
for (const key of cache.keys()) if (!liveCacheKeys.has(key)) cache.delete(key);
|
|
10414
|
+
const rows = /* @__PURE__ */ new Map();
|
|
10415
|
+
await Promise.all([...routes].map(async ([id, label]) => {
|
|
10416
|
+
const mapped = aliases[id] ?? id;
|
|
10417
|
+
if (accountRoute(id) || accountRoute(mapped)) return;
|
|
10418
|
+
const source = siteBucketKey(siteRefOf(mapped, views));
|
|
10419
|
+
if (!validSource(source)) return;
|
|
10420
|
+
let models;
|
|
10421
|
+
try {
|
|
10422
|
+
models = profiles[id]?.models ?? await listModels(llm, id, profiles[id]?.baseURL);
|
|
10423
|
+
} catch {
|
|
10424
|
+
notices.push({
|
|
10425
|
+
code: "discoveryFailed",
|
|
10426
|
+
detail: id
|
|
10427
|
+
});
|
|
10428
|
+
return;
|
|
10429
|
+
}
|
|
10430
|
+
for (const item of models) {
|
|
10431
|
+
const raw = typeof item === "string" ? item : item?.id;
|
|
10432
|
+
if (typeof raw !== "string") continue;
|
|
10433
|
+
const model = resolveCatalogKey(raw);
|
|
10434
|
+
if (eligibleScheduleModel(model)) rows.set(scheduleKey(source, model), {
|
|
10435
|
+
source,
|
|
10436
|
+
model,
|
|
10437
|
+
label: `${source} / ${modelOf(model).name} (${label})`
|
|
10438
|
+
});
|
|
10439
|
+
}
|
|
10440
|
+
}));
|
|
10441
|
+
return {
|
|
10442
|
+
models: [...rows.values()].sort((a, b) => a.label.localeCompare(b.label)),
|
|
10443
|
+
notices
|
|
10444
|
+
};
|
|
10445
|
+
};
|
|
10446
|
+
}
|
|
10447
|
+
//#endregion
|
|
9674
10448
|
//#region lib/types/routes/notify-claim.js
|
|
9675
10449
|
/**
|
|
9676
10450
|
* 路由:POST /api/billing/notify-claim
|
|
@@ -9754,6 +10528,136 @@ function registerNotifyClaimRoute(ctx, deps) {
|
|
|
9754
10528
|
}), "usage-billing: notify-claim route");
|
|
9755
10529
|
}
|
|
9756
10530
|
//#endregion
|
|
10531
|
+
//#region lib/types/routes/pricing-models.js
|
|
10532
|
+
const JSON_HEADERS$1 = {
|
|
10533
|
+
"content-type": "application/json; charset=utf-8",
|
|
10534
|
+
"cache-control": "no-store"
|
|
10535
|
+
};
|
|
10536
|
+
const MODEL_CACHE_MS = 6e4;
|
|
10537
|
+
const PARTIAL_MODEL_CACHE_MS = 15e3;
|
|
10538
|
+
async function discover(registry, route) {
|
|
10539
|
+
let timer;
|
|
10540
|
+
try {
|
|
10541
|
+
return await Promise.race([registry.listModels(route), new Promise((_, reject) => {
|
|
10542
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error("Model discovery timed out")), 5e3);
|
|
10543
|
+
})]);
|
|
10544
|
+
} finally {
|
|
10545
|
+
clearTimeout(timer);
|
|
10546
|
+
}
|
|
10547
|
+
}
|
|
10548
|
+
/** Static settings remain authoritative even when the registry is unavailable. */
|
|
10549
|
+
async function configuredPricingModels(ctx) {
|
|
10550
|
+
const routes = /* @__PURE__ */ new Map();
|
|
10551
|
+
let partial = false;
|
|
10552
|
+
let registry;
|
|
10553
|
+
const profiles = /* @__PURE__ */ new Map();
|
|
10554
|
+
try {
|
|
10555
|
+
const value = ctx.settings.describe({ redactSecrets: true }).find((item) => item.ns === "llm-pi-ai")?.value;
|
|
10556
|
+
for (const [id, profile] of Object.entries(value?.providers ?? {})) {
|
|
10557
|
+
if (!id.trim() || !profile || typeof profile !== "object" || Array.isArray(profile)) {
|
|
10558
|
+
partial = true;
|
|
10559
|
+
continue;
|
|
10560
|
+
}
|
|
10561
|
+
profiles.set(id, profile);
|
|
10562
|
+
routes.set(id, typeof profile.displayName === "string" && profile.displayName ? profile.displayName : id);
|
|
10563
|
+
}
|
|
10564
|
+
} catch {
|
|
10565
|
+
partial = true;
|
|
10566
|
+
}
|
|
10567
|
+
try {
|
|
10568
|
+
registry = ctx.get("llm");
|
|
10569
|
+
if (!registry) partial = true;
|
|
10570
|
+
for (const p of registry?.listProviders() ?? []) {
|
|
10571
|
+
if (typeof p?.id !== "string" || !p.id.trim()) {
|
|
10572
|
+
partial = true;
|
|
10573
|
+
continue;
|
|
10574
|
+
}
|
|
10575
|
+
const displayName = profiles.get(p.id)?.displayName;
|
|
10576
|
+
const fallback = typeof p.name === "string" && p.name ? p.name : p.id;
|
|
10577
|
+
routes.set(p.id, typeof displayName === "string" && displayName ? displayName : fallback);
|
|
10578
|
+
}
|
|
10579
|
+
} catch {
|
|
10580
|
+
partial = true;
|
|
10581
|
+
}
|
|
10582
|
+
return {
|
|
10583
|
+
models: (await Promise.all([...routes].map(async ([route, channel]) => {
|
|
10584
|
+
if (!route || route === "deepseek-account") return [];
|
|
10585
|
+
const profile = profiles.get(route);
|
|
10586
|
+
let origin = "";
|
|
10587
|
+
if (profile?.baseURL) try {
|
|
10588
|
+
const url = new URL(profile.baseURL);
|
|
10589
|
+
if (["https:", "http:"].includes(url.protocol) && !isOfficialBaseUrl(url.origin)) origin = url.origin;
|
|
10590
|
+
} catch {}
|
|
10591
|
+
function parse(list) {
|
|
10592
|
+
if (!Array.isArray(list)) {
|
|
10593
|
+
partial = true;
|
|
10594
|
+
return [];
|
|
10595
|
+
}
|
|
10596
|
+
const models = [];
|
|
10597
|
+
for (const m of list) {
|
|
10598
|
+
if (typeof m?.id !== "string" || !m.id.trim() || m.name !== void 0 && typeof m.name !== "string") {
|
|
10599
|
+
partial = true;
|
|
10600
|
+
continue;
|
|
10601
|
+
}
|
|
10602
|
+
models.push({
|
|
10603
|
+
key: m.id,
|
|
10604
|
+
name: m.name ?? m.id,
|
|
10605
|
+
route,
|
|
10606
|
+
channel,
|
|
10607
|
+
origin
|
|
10608
|
+
});
|
|
10609
|
+
}
|
|
10610
|
+
return models;
|
|
10611
|
+
}
|
|
10612
|
+
const declared = parse(profile?.models === void 0 ? [] : profile.models);
|
|
10613
|
+
if (declared.length || !registry) return declared;
|
|
10614
|
+
try {
|
|
10615
|
+
return parse(await discover(registry, route));
|
|
10616
|
+
} catch (error) {
|
|
10617
|
+
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;
|
|
10618
|
+
return [];
|
|
10619
|
+
}
|
|
10620
|
+
}))).flat(),
|
|
10621
|
+
partial
|
|
10622
|
+
};
|
|
10623
|
+
}
|
|
10624
|
+
function registerPricingModelsRoute(ctx, trustedHosts) {
|
|
10625
|
+
ctx.effect(() => {
|
|
10626
|
+
let cached;
|
|
10627
|
+
let expiresAt = 0;
|
|
10628
|
+
let inFlight;
|
|
10629
|
+
function load() {
|
|
10630
|
+
if (cached && Date.now() < expiresAt) return Promise.resolve(cached);
|
|
10631
|
+
return inFlight ??= configuredPricingModels(ctx).then((result) => {
|
|
10632
|
+
cached = result;
|
|
10633
|
+
expiresAt = Date.now() + (result.partial ? PARTIAL_MODEL_CACHE_MS : MODEL_CACHE_MS);
|
|
10634
|
+
return result;
|
|
10635
|
+
}).finally(() => {
|
|
10636
|
+
inFlight = void 0;
|
|
10637
|
+
});
|
|
10638
|
+
}
|
|
10639
|
+
return ctx.webServer.register({
|
|
10640
|
+
kind: "exact",
|
|
10641
|
+
path: "/api/billing/pricing-models",
|
|
10642
|
+
...ANONYMOUS_ROUTE_AUTH,
|
|
10643
|
+
async handler(req, res) {
|
|
10644
|
+
if (!guardLoopback(req, res, trustedHosts)) return;
|
|
10645
|
+
if (req.method !== "GET") {
|
|
10646
|
+
res.writeHead(405, {
|
|
10647
|
+
...JSON_HEADERS$1,
|
|
10648
|
+
allow: "GET"
|
|
10649
|
+
});
|
|
10650
|
+
res.end(JSON.stringify({ error: "method not allowed" }));
|
|
10651
|
+
return;
|
|
10652
|
+
}
|
|
10653
|
+
const body = await load();
|
|
10654
|
+
res.writeHead(200, JSON_HEADERS$1);
|
|
10655
|
+
res.end(JSON.stringify(body));
|
|
10656
|
+
}
|
|
10657
|
+
});
|
|
10658
|
+
}, "usage-billing: pricing models route");
|
|
10659
|
+
}
|
|
10660
|
+
//#endregion
|
|
9757
10661
|
//#region lib/types/routes/pricing.js
|
|
9758
10662
|
/**
|
|
9759
10663
|
* 路由:GET /api/billing/pricing + POST /api/billing/pricing/refresh
|
|
@@ -9831,6 +10735,20 @@ function registerPricingRoutes(ctx, deps) {
|
|
|
9831
10735
|
* queryDeclaredEndpoints / reconcileBalanceDelta)在装配器里跑,路由只通过
|
|
9832
10736
|
* `cached()` 与 `refreshOnce()` 拿到结果。
|
|
9833
10737
|
*/
|
|
10738
|
+
/** Loopback callers can supply these advisory UI headers. */
|
|
10739
|
+
function readClientMetadata(headers) {
|
|
10740
|
+
const version = headers[BALANCE_CLIENT_HEADERS.version];
|
|
10741
|
+
const locale = headers[BALANCE_CLIENT_HEADERS.locale];
|
|
10742
|
+
const offset = headers[BALANCE_CLIENT_HEADERS.timezone];
|
|
10743
|
+
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;
|
|
10744
|
+
const timezoneOffsetSeconds = Number(offset);
|
|
10745
|
+
if (Math.abs(timezoneOffsetSeconds) > 50400) return void 0;
|
|
10746
|
+
return {
|
|
10747
|
+
version,
|
|
10748
|
+
locale,
|
|
10749
|
+
timezoneOffsetSeconds
|
|
10750
|
+
};
|
|
10751
|
+
}
|
|
9834
10752
|
function registerBalanceRoute(ctx, deps) {
|
|
9835
10753
|
ctx.effect(() => ctx.webServer.register({
|
|
9836
10754
|
kind: "exact",
|
|
@@ -9839,22 +10757,26 @@ function registerBalanceRoute(ctx, deps) {
|
|
|
9839
10757
|
handler: async (req, res) => {
|
|
9840
10758
|
if (!guardLoopback(req, res, deps.trustedHosts)) return;
|
|
9841
10759
|
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
9842
|
-
|
|
9843
|
-
|
|
10760
|
+
const client = readClientMetadata(req.headers);
|
|
10761
|
+
const cached = deps.cached(client);
|
|
10762
|
+
if (Date.now() - cached.at < deps.cacheMs) {
|
|
10763
|
+
res.end(JSON.stringify(cached.doc));
|
|
9844
10764
|
return;
|
|
9845
10765
|
}
|
|
9846
10766
|
let timedOut = false;
|
|
10767
|
+
let failed = false;
|
|
9847
10768
|
const onFailure = (error) => {
|
|
10769
|
+
failed = true;
|
|
9848
10770
|
console.warn("[usage-billing] refreshBalances failed; serving cached balances:", error);
|
|
9849
10771
|
};
|
|
9850
|
-
await Promise.race([deps.refreshOnce().then(() => void 0, onFailure), new Promise((resolve) => {
|
|
10772
|
+
await Promise.race([deps.refreshOnce(client).then(() => void 0, onFailure), new Promise((resolve) => {
|
|
9851
10773
|
setTimeout(() => {
|
|
9852
10774
|
timedOut = true;
|
|
9853
10775
|
resolve();
|
|
9854
10776
|
}, deps.responseBudgetMs).unref();
|
|
9855
10777
|
})]);
|
|
9856
|
-
const doc = deps.cached().doc;
|
|
9857
|
-
res.end(JSON.stringify(timedOut ? {
|
|
10778
|
+
const doc = deps.cached(client).doc;
|
|
10779
|
+
res.end(JSON.stringify(timedOut || failed ? {
|
|
9858
10780
|
...doc,
|
|
9859
10781
|
stale: true
|
|
9860
10782
|
} : doc));
|
|
@@ -11085,6 +12007,18 @@ async function readPiAiProviders(settings) {
|
|
|
11085
12007
|
return {};
|
|
11086
12008
|
}
|
|
11087
12009
|
}
|
|
12010
|
+
/** Site buckets drop the route ID, so a site match needs a unique configured route. */
|
|
12011
|
+
function uniqueSiteOrigins(providers) {
|
|
12012
|
+
const owners = /* @__PURE__ */ new Map();
|
|
12013
|
+
for (const [route, { baseURL }] of Object.entries(providers)) {
|
|
12014
|
+
if (!baseURL) continue;
|
|
12015
|
+
const origin = siteOriginOf(baseURL);
|
|
12016
|
+
owners.set(origin, owners.has(origin) ? void 0 : route);
|
|
12017
|
+
}
|
|
12018
|
+
const origins = /* @__PURE__ */ new Map();
|
|
12019
|
+
for (const [origin, route] of owners) if (route !== void 0) origins.set(route, origin);
|
|
12020
|
+
return origins;
|
|
12021
|
+
}
|
|
11088
12022
|
/** 同步读取 provider 路由的 baseURL 视图(中转站零配置发现来源)。
|
|
11089
12023
|
* `settings.describe` 是同步调用,聚合器每次折叠取最新站点映射,无需缓存/过期。
|
|
11090
12024
|
* 注意:返回**全部可读路由**(baseURL 可选),聚合层据此区分「路由存在但无
|
|
@@ -11093,13 +12027,20 @@ async function readPiAiProviders(settings) {
|
|
|
11093
12027
|
* @returns `<route> → { baseURL? }`;命名空间不可读时返回空。
|
|
11094
12028
|
*/
|
|
11095
12029
|
function readPiAiProviderRoutes(settings) {
|
|
12030
|
+
return Object.fromEntries(Object.entries(readScheduleProfiles(settings)).map(([id, { baseURL }]) => [id, baseURL === void 0 ? {} : { baseURL }]));
|
|
12031
|
+
}
|
|
12032
|
+
function readScheduleProfiles(settings) {
|
|
11096
12033
|
try {
|
|
11097
12034
|
const providers = (settings.describe({ redactSecrets: true }).find((descriptor) => descriptor.ns === "llm-pi-ai")?.value)?.providers;
|
|
11098
|
-
const out =
|
|
12035
|
+
const out = Object.create(null);
|
|
11099
12036
|
for (const [route, entry] of Object.entries(providers ?? {})) {
|
|
11100
12037
|
if (entry === null || typeof entry !== "object") continue;
|
|
11101
12038
|
const baseURL = entry.baseURL;
|
|
11102
|
-
out[route] =
|
|
12039
|
+
out[route] = {
|
|
12040
|
+
...typeof baseURL === "string" && baseURL !== "" ? { baseURL } : {},
|
|
12041
|
+
...typeof entry.displayName === "string" ? { displayName: entry.displayName } : {},
|
|
12042
|
+
...Array.isArray(entry.models) ? { models: entry.models } : {}
|
|
12043
|
+
};
|
|
11103
12044
|
}
|
|
11104
12045
|
return out;
|
|
11105
12046
|
} catch {
|
|
@@ -11360,7 +12301,7 @@ function apply(ctx, config = {}) {
|
|
|
11360
12301
|
const ledgerStore = createFileUsageLedgerStore(config.ledgerPath ?? join(dshHome, ".dsh-usage-ledger.json"));
|
|
11361
12302
|
const reconcilePath = config.reconcilePath ?? join(dshHome, ".dsh-usage-reconcile.json");
|
|
11362
12303
|
let reconcileRef = null;
|
|
11363
|
-
(async () => {
|
|
12304
|
+
const reconcileLoaded = (async () => {
|
|
11364
12305
|
try {
|
|
11365
12306
|
const ref = JSON.parse(await readFile(reconcilePath, "utf8")).ref;
|
|
11366
12307
|
if (ref !== null && typeof ref === "object") {
|
|
@@ -11371,13 +12312,19 @@ function apply(ctx, config = {}) {
|
|
|
11371
12312
|
swallowed("reconcile-ref-missing");
|
|
11372
12313
|
}
|
|
11373
12314
|
})();
|
|
11374
|
-
|
|
11375
|
-
|
|
11376
|
-
|
|
11377
|
-
|
|
11378
|
-
|
|
11379
|
-
|
|
11380
|
-
|
|
12315
|
+
let persistence = Promise.resolve();
|
|
12316
|
+
const setReconcileRef = (next) => {
|
|
12317
|
+
if (next !== reconcileRef) {
|
|
12318
|
+
reconcileRef = next;
|
|
12319
|
+
const payload = JSON.stringify({ ref: next });
|
|
12320
|
+
persistence = persistence.then(() => writeFileAtomic(reconcilePath, payload, {
|
|
12321
|
+
mode: 384,
|
|
12322
|
+
dirMode: 448
|
|
12323
|
+
})).catch(() => {
|
|
12324
|
+
swallowed("reconcile-write-failed");
|
|
12325
|
+
});
|
|
12326
|
+
}
|
|
12327
|
+
return persistence;
|
|
11381
12328
|
};
|
|
11382
12329
|
const workspaceTitleResolver = buildWorkspaceTitleResolver(ctx);
|
|
11383
12330
|
const sessionTitleResolver = buildSessionTitleResolver(ctx);
|
|
@@ -11407,8 +12354,56 @@ function apply(ctx, config = {}) {
|
|
|
11407
12354
|
swallowed("minimax-plan-classify-failed", error);
|
|
11408
12355
|
}
|
|
11409
12356
|
};
|
|
12357
|
+
const schedules = openScheduleStore(config.peakSchedulePath ?? join(dshHome, ".dsh-usage-peak-schedule.json"), eligibleScheduleModel);
|
|
12358
|
+
const discoverScheduleModels = createScheduleModelDiscovery();
|
|
12359
|
+
const configuredScheduleModels = async () => {
|
|
12360
|
+
const llm = ctx.get?.("llm");
|
|
12361
|
+
return discoverScheduleModels(llm, readScheduleProfiles(ctx.settings), config.routeAliases ?? {});
|
|
12362
|
+
};
|
|
12363
|
+
const scheduleSnapshot = (discovery) => {
|
|
12364
|
+
const config = schedules.current();
|
|
12365
|
+
const models = new Map(discovery.models.map((row) => [scheduleKey(row.source, row.model), row]));
|
|
12366
|
+
for (const key of Object.keys(config.models)) {
|
|
12367
|
+
if (models.has(key)) continue;
|
|
12368
|
+
const [source, model] = JSON.parse(key);
|
|
12369
|
+
models.set(key, {
|
|
12370
|
+
source,
|
|
12371
|
+
model,
|
|
12372
|
+
label: `${source} / ${model}`
|
|
12373
|
+
});
|
|
12374
|
+
}
|
|
12375
|
+
const notices = [...schedules.notices(), ...discovery.notices];
|
|
12376
|
+
const effectiveFromMs = schedules.history().revisions.at(-1)?.effectiveFromMs;
|
|
12377
|
+
return {
|
|
12378
|
+
config,
|
|
12379
|
+
...effectiveFromMs !== void 0 && { effectiveFromMs },
|
|
12380
|
+
models: [...models.values()],
|
|
12381
|
+
...notices.length ? { notices } : {}
|
|
12382
|
+
};
|
|
12383
|
+
};
|
|
12384
|
+
registerPeakScheduleRoute(ctx, {
|
|
12385
|
+
trustedHosts,
|
|
12386
|
+
read: async () => scheduleSnapshot(await configuredScheduleModels()),
|
|
12387
|
+
save: async (raw) => {
|
|
12388
|
+
const discovery = await configuredScheduleModels();
|
|
12389
|
+
const allowed = new Set(discovery.models.map((row) => scheduleKey(row.source, row.model)));
|
|
12390
|
+
let batch;
|
|
12391
|
+
try {
|
|
12392
|
+
batch = partitionScheduleEdit(raw, (key, model) => allowed.has(key) && eligibleScheduleModel(model));
|
|
12393
|
+
} catch {
|
|
12394
|
+
throw new PeakScheduleInputError("invalidSchedule");
|
|
12395
|
+
}
|
|
12396
|
+
if (Object.keys(batch.edit.changes).length) await aggregator.withPeakScheduleChange((latestEventTime) => schedules.save(batch.edit, latestEventTime));
|
|
12397
|
+
return {
|
|
12398
|
+
...scheduleSnapshot(discovery),
|
|
12399
|
+
results: batch.results
|
|
12400
|
+
};
|
|
12401
|
+
}
|
|
12402
|
+
});
|
|
11410
12403
|
const replayDelayMs = readReplayDelayMs(config.replayDelayMs);
|
|
11411
12404
|
const aggregator = createUsageAggregator(adaptSessionPersistence(ctx.sessionPersistence), {
|
|
12405
|
+
resolvePeakSchedule: schedules.current,
|
|
12406
|
+
resolvePeakHistory: schedules.history,
|
|
11412
12407
|
subscriptionMatcher: subscriptionRoutes,
|
|
11413
12408
|
...config.routeAliases === void 0 ? {} : { routeAliases: config.routeAliases },
|
|
11414
12409
|
resolveRoutes: () => readPiAiProviderRoutes(ctx.settings),
|
|
@@ -11723,17 +12718,23 @@ function apply(ctx, config = {}) {
|
|
|
11723
12718
|
clearInterval(timer);
|
|
11724
12719
|
};
|
|
11725
12720
|
}, "usage-billing: pricing refresh timer");
|
|
12721
|
+
registerPricingModelsRoute(ctx, trustedHosts);
|
|
11726
12722
|
registerPricingRoutes(ctx, {
|
|
11727
12723
|
trustedHosts,
|
|
11728
12724
|
body: pricingBody,
|
|
11729
12725
|
refresh: refreshPricing
|
|
11730
12726
|
});
|
|
11731
|
-
|
|
12727
|
+
const headless = {
|
|
11732
12728
|
at: 0,
|
|
11733
12729
|
doc: { balances: [] }
|
|
11734
12730
|
};
|
|
11735
|
-
|
|
11736
|
-
|
|
12731
|
+
const ui = {
|
|
12732
|
+
at: 0,
|
|
12733
|
+
doc: { balances: [] }
|
|
12734
|
+
};
|
|
12735
|
+
const balanceSlot = (client) => client === void 0 ? headless : ui;
|
|
12736
|
+
let refreshSequence = 0;
|
|
12737
|
+
const refreshBalance = async (sequence, client) => {
|
|
11737
12738
|
const piProviders = await readPiAiProviders(ctx.settings);
|
|
11738
12739
|
const providers = { ...piProviders };
|
|
11739
12740
|
const deepseekKey = providers["deepseek"]?.apiKeyEnv;
|
|
@@ -11741,7 +12742,7 @@ function apply(ctx, config = {}) {
|
|
|
11741
12742
|
...providers["deepseek"],
|
|
11742
12743
|
apiKeyEnv: config.balanceApiKeyEnv ?? DEFAULT_BALANCE_API_KEY_ENV
|
|
11743
12744
|
};
|
|
11744
|
-
const balances = await queryBalances(ctx, providers);
|
|
12745
|
+
const balances = await queryBalances(ctx, providers, client);
|
|
11745
12746
|
const custom = await queryCustomBalances(ctx, config.customBalances ?? []);
|
|
11746
12747
|
const declared = await queryDeclaredEndpoints(ctx, piProviders, config.declaredEndpoints ?? []);
|
|
11747
12748
|
for (const row of [
|
|
@@ -11749,30 +12750,33 @@ function apply(ctx, config = {}) {
|
|
|
11749
12750
|
...custom,
|
|
11750
12751
|
...declared
|
|
11751
12752
|
]) if (row.error === "unauthorized") warnAuthOnce("balance", row.provider, row.displayName);
|
|
11752
|
-
const official = balances.find((row) => row.
|
|
12753
|
+
const official = balances.find((row) => row.sourceRoute === "deepseek" && row.walletKind === "api-key");
|
|
12754
|
+
const account = balances.find((row) => row.walletKind === "account");
|
|
12755
|
+
const now = Date.now();
|
|
12756
|
+
const today = dayStamp(now);
|
|
12757
|
+
const recent = aggregator.lastDocOf();
|
|
11753
12758
|
let reconcile;
|
|
11754
|
-
|
|
11755
|
-
if (
|
|
11756
|
-
const
|
|
11757
|
-
|
|
11758
|
-
|
|
11759
|
-
|
|
11760
|
-
|
|
11761
|
-
|
|
11762
|
-
|
|
11763
|
-
|
|
11764
|
-
|
|
12759
|
+
await reconcileLoaded;
|
|
12760
|
+
if (sequence === refreshSequence) {
|
|
12761
|
+
const fresh = recent !== void 0 && now - recent.updatedAt <= RECONCILE_BASIS_MAX_AGE_MS;
|
|
12762
|
+
if (!fresh) aggregator.aggregate().catch(() => {
|
|
12763
|
+
swallowed("reconcile-basis-stale");
|
|
12764
|
+
});
|
|
12765
|
+
const apiOnly = account?.accountState === "no-service" || account?.accountState === "signed-out";
|
|
12766
|
+
const cost = fresh ? platformSpend(recent, today, piProviders, apiOnly) : void 0;
|
|
12767
|
+
const source = official && apiBalanceSource(official);
|
|
12768
|
+
if (source !== void 0 && official?.error === void 0 && official?.isAvailable !== false && official?.currency === "CNY" && cost !== void 0) {
|
|
12769
|
+
const result = reconcileBalanceDelta(reconcileRef, official, cost, today, now, `${source}:${apiOnly ? "direct" : "site"}`);
|
|
12770
|
+
if (result.event && result.event.kind !== "flat") reconcile = {
|
|
11765
12771
|
...result.event,
|
|
11766
12772
|
provider: official.displayName,
|
|
11767
|
-
|
|
12773
|
+
currency: official.currency
|
|
11768
12774
|
};
|
|
11769
|
-
|
|
11770
|
-
} else
|
|
11771
|
-
aggregator.aggregate().catch(() => {});
|
|
11772
|
-
swallowed("reconcile-basis-stale");
|
|
11773
|
-
}
|
|
12775
|
+
await setReconcileRef(result.ref);
|
|
12776
|
+
} else await setReconcileRef(null);
|
|
11774
12777
|
}
|
|
11775
|
-
const
|
|
12778
|
+
const slot = balanceSlot(client);
|
|
12779
|
+
slot.doc = {
|
|
11776
12780
|
balances: [
|
|
11777
12781
|
...balances,
|
|
11778
12782
|
...custom,
|
|
@@ -11780,20 +12784,25 @@ function apply(ctx, config = {}) {
|
|
|
11780
12784
|
],
|
|
11781
12785
|
...reconcile === void 0 ? {} : { reconcile }
|
|
11782
12786
|
};
|
|
11783
|
-
|
|
11784
|
-
at: Date.now(),
|
|
11785
|
-
doc
|
|
11786
|
-
};
|
|
12787
|
+
slot.at = Date.now();
|
|
11787
12788
|
};
|
|
11788
|
-
const refreshBalanceOnce = () => {
|
|
11789
|
-
|
|
11790
|
-
|
|
11791
|
-
|
|
11792
|
-
|
|
12789
|
+
const refreshBalanceOnce = (client) => {
|
|
12790
|
+
const slot = balanceSlot(client);
|
|
12791
|
+
if (!slot.inflight) {
|
|
12792
|
+
const sequence = ++refreshSequence;
|
|
12793
|
+
slot.inflight = refreshBalance(sequence, client).catch(async (error) => {
|
|
12794
|
+
await reconcileLoaded;
|
|
12795
|
+
if (sequence === refreshSequence) await setReconcileRef(null);
|
|
12796
|
+
throw error;
|
|
12797
|
+
}).finally(() => {
|
|
12798
|
+
delete slot.inflight;
|
|
12799
|
+
});
|
|
12800
|
+
}
|
|
12801
|
+
return slot.inflight;
|
|
11793
12802
|
};
|
|
11794
12803
|
registerBalanceRoute(ctx, {
|
|
11795
12804
|
trustedHosts,
|
|
11796
|
-
cached:
|
|
12805
|
+
cached: balanceSlot,
|
|
11797
12806
|
refreshOnce: refreshBalanceOnce,
|
|
11798
12807
|
cacheMs: BALANCE_CACHE_MS,
|
|
11799
12808
|
responseBudgetMs: BALANCE_RESPONSE_BUDGET_MS
|
|
@@ -11816,29 +12825,38 @@ function apply(ctx, config = {}) {
|
|
|
11816
12825
|
await refreshMiniMaxPlanRoutes();
|
|
11817
12826
|
const { keys, identified } = await resolveSubscriptionKeys(ctx.settings, ctx.credentials);
|
|
11818
12827
|
const piProviders = await readPiAiProviders(ctx.settings);
|
|
11819
|
-
const
|
|
12828
|
+
const queried = await collectSubscriptions(keys, identified.filter((item) => item.adapter).map((item) => {
|
|
11820
12829
|
const baseURL = piProviders[item.provider]?.baseURL;
|
|
11821
12830
|
return {
|
|
11822
12831
|
provider: item.provider,
|
|
11823
12832
|
...item.region === void 0 ? {} : { region: item.region },
|
|
11824
12833
|
...typeof baseURL === "string" && baseURL !== "" ? { baseUrl: baseURL } : {}
|
|
11825
12834
|
};
|
|
11826
|
-
}))
|
|
12835
|
+
}));
|
|
12836
|
+
const origins = uniqueSiteOrigins(piProviders);
|
|
12837
|
+
const rows = [...queried].map((row) => {
|
|
11827
12838
|
const planType = planTypeOf(row.provider);
|
|
11828
12839
|
const subscriptionAmount = subscriptionFeeCnyOf(row.provider, live.rate);
|
|
12840
|
+
const origin = origins.get(row.provider);
|
|
11829
12841
|
return {
|
|
11830
12842
|
...row,
|
|
12843
|
+
...origin === void 0 ? {} : { origin },
|
|
11831
12844
|
planType,
|
|
11832
12845
|
...planType === "code" && subscriptionAmount > 0 ? { subscriptionAmount } : {}
|
|
11833
12846
|
};
|
|
11834
12847
|
});
|
|
11835
|
-
for (const item of identified)
|
|
11836
|
-
|
|
11837
|
-
|
|
11838
|
-
|
|
11839
|
-
|
|
11840
|
-
|
|
11841
|
-
|
|
12848
|
+
for (const item of identified) {
|
|
12849
|
+
if (item.adapter) continue;
|
|
12850
|
+
const origin = origins.get(item.provider);
|
|
12851
|
+
rows.push({
|
|
12852
|
+
provider: item.provider,
|
|
12853
|
+
displayName: item.displayName,
|
|
12854
|
+
status: "ok",
|
|
12855
|
+
windows: [],
|
|
12856
|
+
planType: planTypeOf(item.provider),
|
|
12857
|
+
...origin === void 0 ? {} : { origin }
|
|
12858
|
+
});
|
|
12859
|
+
}
|
|
11842
12860
|
for (const row of rows) if (row.status === "unauthorized") warnAuthOnce("subscription", row.provider, row.displayName);
|
|
11843
12861
|
quotaCache = {
|
|
11844
12862
|
at: Date.now(),
|
|
@@ -11880,9 +12898,14 @@ function apply(ctx, config = {}) {
|
|
|
11880
12898
|
...entry.displayName === void 0 ? {} : { displayName: entry.displayName }
|
|
11881
12899
|
});
|
|
11882
12900
|
}
|
|
12901
|
+
const origins = uniqueSiteOrigins(providers);
|
|
12902
|
+
const quotas = (await queryRelayQuotas(ctx, routes)).map((row) => origins.has(row.route) ? row : {
|
|
12903
|
+
...row,
|
|
12904
|
+
sourceAmbiguous: true
|
|
12905
|
+
});
|
|
11883
12906
|
relayCache = {
|
|
11884
12907
|
at: Date.now(),
|
|
11885
|
-
quotas
|
|
12908
|
+
quotas
|
|
11886
12909
|
};
|
|
11887
12910
|
};
|
|
11888
12911
|
let relayInflight;
|