dsh-codearts 1.2.14 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +598 -515
- package/lib/auth-Ch0vYSAo.mjs +1287 -0
- package/lib/bin.mjs +3 -1
- package/lib/client/index.d.cts +30 -0
- package/lib/client/index.js +632 -178
- package/lib/index.d.mts +122 -4
- package/lib/index.mjs +591 -141
- package/lib/keeper-MHeAp_eV.mjs +215 -0
- package/lib/keeper-main.d.mts +1 -0
- package/lib/keeper-main.mjs +210 -0
- package/lib/{version-Msk-1m2n.mjs → upstream-CVtspzAv.mjs} +2 -1469
- package/lib/version-BjBwEMks.mjs +539 -0
- package/package.json +125 -125
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
import { u as writeJsonAtomic } from "./auth-Ch0vYSAo.mjs";
|
|
2
|
+
import { B as setDiscoveredBenefitModels, F as isBenefitModel, L as mergeModelLists, R as modelDisplayName, c as fetchModels } from "./upstream-CVtspzAv.mjs";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
//#region src/discovery.ts
|
|
8
|
+
/**
|
|
9
|
+
* 动态模型发现:把「已登录账号」变成「当前可用模型清单」。
|
|
10
|
+
*
|
|
11
|
+
* 为什么要单独一层:模型目录是**按账号**授予的(限时福利尤其如此:A 账号有、
|
|
12
|
+
* B 账号没有),而插件对外只暴露一份目录。所以这里逐账号发现、取并集,再把
|
|
13
|
+
* 结果提交给全局目录与福利集合。
|
|
14
|
+
*
|
|
15
|
+
* 失败一律不抛出:拉不到就继续用现有目录(冷启动时是种子清单),把失败原因
|
|
16
|
+
* 带回去给 CLI / 日志展示。真正「不可用」的信号是 0 个账号。
|
|
17
|
+
*
|
|
18
|
+
* @module dsh-codearts/discovery
|
|
19
|
+
*/
|
|
20
|
+
/**
|
|
21
|
+
* 逐账号发现并合并(不改全局状态)。
|
|
22
|
+
*
|
|
23
|
+
* @param store 账号文档;逐个 `resolve()` 以拿到已续期的签名材料
|
|
24
|
+
* @param signal 取消信号(宿主关停时用)
|
|
25
|
+
*/
|
|
26
|
+
async function discoverModels(store, signal) {
|
|
27
|
+
const ids = await store.ids();
|
|
28
|
+
const accounts = [];
|
|
29
|
+
for (const id of ids) {
|
|
30
|
+
if (signal?.aborted === true) break;
|
|
31
|
+
const summary = (await store.list()).find((account) => account.id === id);
|
|
32
|
+
const label = summary?.label ?? summary?.userName;
|
|
33
|
+
const resolved = await store.resolve(id);
|
|
34
|
+
if (resolved === void 0) {
|
|
35
|
+
accounts.push({
|
|
36
|
+
accountId: id,
|
|
37
|
+
...label === void 0 ? {} : { label },
|
|
38
|
+
ok: false,
|
|
39
|
+
models: [],
|
|
40
|
+
sources: [],
|
|
41
|
+
errors: [{
|
|
42
|
+
source: "agent",
|
|
43
|
+
message: "credential unavailable (sign in again)"
|
|
44
|
+
}]
|
|
45
|
+
});
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
const result = await fetchModels(resolved, signal);
|
|
50
|
+
accounts.push({
|
|
51
|
+
accountId: id,
|
|
52
|
+
...label === void 0 ? {} : { label },
|
|
53
|
+
ok: true,
|
|
54
|
+
models: result.models,
|
|
55
|
+
sources: result.sources,
|
|
56
|
+
errors: result.errors
|
|
57
|
+
});
|
|
58
|
+
} catch (error) {
|
|
59
|
+
accounts.push({
|
|
60
|
+
accountId: id,
|
|
61
|
+
...label === void 0 ? {} : { label },
|
|
62
|
+
ok: false,
|
|
63
|
+
models: [],
|
|
64
|
+
sources: [],
|
|
65
|
+
errors: [{
|
|
66
|
+
source: "agent",
|
|
67
|
+
message: error instanceof Error ? error.message : String(error)
|
|
68
|
+
}]
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const ok = accounts.filter((account) => account.ok);
|
|
73
|
+
return {
|
|
74
|
+
models: mergeModelLists(ok.map((account) => account.models)),
|
|
75
|
+
accounts,
|
|
76
|
+
anySucceeded: ok.length > 0
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* 发现并**提交**到全局目录:目录内容 + 福利集合。
|
|
81
|
+
*
|
|
82
|
+
* @returns 提交后的目录;没有任何账号成功时返回 `undefined`(调用方保留原目录)
|
|
83
|
+
*/
|
|
84
|
+
async function refreshCatalog(store, catalog, signal) {
|
|
85
|
+
const outcome = await discoverModels(store, signal);
|
|
86
|
+
if (!outcome.anySucceeded || outcome.models.length === 0) return outcome;
|
|
87
|
+
setDiscoveredBenefitModels(outcome.models.filter((model) => model.benefit === true).map((model) => model.id));
|
|
88
|
+
catalog.set(outcome.models.map((model) => {
|
|
89
|
+
const benefit = isBenefitModel(model.id);
|
|
90
|
+
return {
|
|
91
|
+
...model,
|
|
92
|
+
name: modelDisplayName(model.name, benefit, model.ratio)
|
|
93
|
+
};
|
|
94
|
+
}));
|
|
95
|
+
return outcome;
|
|
96
|
+
}
|
|
97
|
+
//#endregion
|
|
98
|
+
//#region src/usage.ts
|
|
99
|
+
/**
|
|
100
|
+
* 用量账本:把聊天流里的 usage 帧累计成「今天用了多少」。
|
|
101
|
+
*
|
|
102
|
+
* 为什么还要自己记:账号总额度有积分接口了(见 credits.ts,2026-10 从官方 Agent
|
|
103
|
+
* 客户端挖出并实测通过),但**本机经插件发出的请求**仍需自己累计 —— 上游不按
|
|
104
|
+
* 「这台机器」维度给统计。能拿到的真实数据有三样:
|
|
105
|
+
* 1. 每个请求的 token `usage`(上游在流末尾回一帧 `{choices:[],usage:{...}}`);
|
|
106
|
+
* 2. 插件自己知道的账号会话槽位占用(见 account-pool:每账号 3 个并发会话);
|
|
107
|
+
* 3. 账号积分/额度(见 credits.ts)。
|
|
108
|
+
*
|
|
109
|
+
* 所以这里累计的是**本机经插件发出的请求**,与卡片上的积分区块互补 —— 一个是本机
|
|
110
|
+
* 级、一个是账号级。官方额度明细在 `codearts.huaweicloud.com/portal/settings/personal-usage`。
|
|
111
|
+
*
|
|
112
|
+
* 落盘在 `$DSH_HOME/.codearts-usage.json`,按天存,保留最近 `RETENTION_DAYS` 天。
|
|
113
|
+
*
|
|
114
|
+
* @module dsh-codearts/usage
|
|
115
|
+
*/
|
|
116
|
+
/** 用量账本路径:与账号文档同一层(`$DSH_HOME` 或 `~/.dsh`)。 */
|
|
117
|
+
function codeartsUsagePath(home) {
|
|
118
|
+
const base = home ?? process.env.DSH_HOME ?? join(homedir(), ".dsh");
|
|
119
|
+
return join(base, ".codearts-usage.json");
|
|
120
|
+
}
|
|
121
|
+
/** 首字延迟分桶的上界(毫秒);落进最后一档表示「超过 30 秒」。 */
|
|
122
|
+
const TTFT_BUCKETS_MS = [
|
|
123
|
+
200,
|
|
124
|
+
500,
|
|
125
|
+
1e3,
|
|
126
|
+
2e3,
|
|
127
|
+
3e3,
|
|
128
|
+
5e3,
|
|
129
|
+
8e3,
|
|
130
|
+
12e3,
|
|
131
|
+
2e4,
|
|
132
|
+
3e4
|
|
133
|
+
];
|
|
134
|
+
/** 直方图桶数(含溢出档)。 */
|
|
135
|
+
const TTFT_BUCKET_COUNT = TTFT_BUCKETS_MS.length + 1;
|
|
136
|
+
function emptyTotals() {
|
|
137
|
+
return {
|
|
138
|
+
requests: 0,
|
|
139
|
+
promptTokens: 0,
|
|
140
|
+
completionTokens: 0,
|
|
141
|
+
totalTokens: 0,
|
|
142
|
+
cachedTokens: 0,
|
|
143
|
+
reasoningTokens: 0
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function addTotals(into, add) {
|
|
147
|
+
into.requests += add.requests ?? 0;
|
|
148
|
+
into.promptTokens += add.promptTokens ?? 0;
|
|
149
|
+
into.completionTokens += add.completionTokens ?? 0;
|
|
150
|
+
into.totalTokens += add.totalTokens ?? 0;
|
|
151
|
+
into.cachedTokens += add.cachedTokens ?? 0;
|
|
152
|
+
into.reasoningTokens += add.reasoningTokens ?? 0;
|
|
153
|
+
}
|
|
154
|
+
function mergeTotals(into, from) {
|
|
155
|
+
addTotals(into, from);
|
|
156
|
+
}
|
|
157
|
+
/** 本地日期键 YYYY-MM-DD(不用 toISOString:那是 UTC,会把跨零点的用量算到前一天)。 */
|
|
158
|
+
function localDateKey(at = Date.now()) {
|
|
159
|
+
const d = new Date(at);
|
|
160
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
161
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
|
|
162
|
+
}
|
|
163
|
+
/** 本地小时键 `00`..`23`(同样按本地时间切,跨零点的那一小时不会错位)。 */
|
|
164
|
+
function localHourKey(at = Date.now()) {
|
|
165
|
+
return localHourKeyOfHour(new Date(at).getHours());
|
|
166
|
+
}
|
|
167
|
+
/** 0..23 -> `00`..`23`(小时桶的键)。 */
|
|
168
|
+
function localHourKeyOfHour(hour) {
|
|
169
|
+
return String(hour).padStart(2, "0");
|
|
170
|
+
}
|
|
171
|
+
function positiveInt(value) {
|
|
172
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* 从上游 usage 帧里取缓存命中数。
|
|
176
|
+
*
|
|
177
|
+
* 位置见过两种:OpenAI 的 `prompt_tokens_details.cached_tokens`,以及兼容层直接
|
|
178
|
+
* 平铺在顶层的几种别名。取第一个能读到的。缓存输入必然是输入的子集,所以比
|
|
179
|
+
* `promptTokens` 还大的脏数据直接钳掉 —— 否则界面上会出现 >100% 的命中率。
|
|
180
|
+
*/
|
|
181
|
+
function cachedTokensOf(raw, promptTokens) {
|
|
182
|
+
if (promptTokens <= 0) return 0;
|
|
183
|
+
const cached = positiveInt(nestedField(raw.prompt_tokens_details, "cached_tokens") ?? raw.cached_tokens ?? raw.cache_tokens ?? raw.prompt_cache_hit_tokens);
|
|
184
|
+
return Math.min(cached, promptTokens);
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* 从上游 usage 帧里取思考 token。
|
|
188
|
+
*
|
|
189
|
+
* 口径与 {@link cachedTokensOf} 对称:嵌套 `completion_tokens_details.reasoning_tokens`
|
|
190
|
+
* 优先,顶层 `reasoning_tokens` 兜底,超过输出总量就钳掉(它含在输出里)。
|
|
191
|
+
*/
|
|
192
|
+
function reasoningTokensOf(raw, completionTokens) {
|
|
193
|
+
if (completionTokens <= 0) return 0;
|
|
194
|
+
const reasoning = positiveInt(nestedField(raw.completion_tokens_details, "reasoning_tokens") ?? raw.reasoning_tokens);
|
|
195
|
+
return Math.min(reasoning, completionTokens);
|
|
196
|
+
}
|
|
197
|
+
/** 读 `*_tokens_details` 这类嵌套对象里的一个字段;不是对象(或缺字段)给 undefined。 */
|
|
198
|
+
function nestedField(details, key) {
|
|
199
|
+
return typeof details === "object" && details !== null ? details[key] : void 0;
|
|
200
|
+
}
|
|
201
|
+
/** 从上游 usage 帧里取计数(缺哪个算 0,total 缺失时用 prompt+completion 兜底)。 */
|
|
202
|
+
function normalizeUsage(raw) {
|
|
203
|
+
if (raw === void 0) return {
|
|
204
|
+
promptTokens: 0,
|
|
205
|
+
completionTokens: 0,
|
|
206
|
+
totalTokens: 0,
|
|
207
|
+
cachedTokens: 0,
|
|
208
|
+
reasoningTokens: 0
|
|
209
|
+
};
|
|
210
|
+
const promptTokens = positiveInt(raw.prompt_tokens);
|
|
211
|
+
const completionTokens = positiveInt(raw.completion_tokens);
|
|
212
|
+
const total = positiveInt(raw.total_tokens);
|
|
213
|
+
return {
|
|
214
|
+
promptTokens,
|
|
215
|
+
completionTokens,
|
|
216
|
+
totalTokens: total > 0 ? total : promptTokens + completionTokens,
|
|
217
|
+
cachedTokens: cachedTokensOf(raw, promptTokens),
|
|
218
|
+
reasoningTokens: reasoningTokensOf(raw, completionTokens)
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
/** 读一项累计值,缺字段(旧账本没有 cachedTokens / reasoningTokens)就按 0 补齐。 */
|
|
222
|
+
function normalizeTotals(raw) {
|
|
223
|
+
return {
|
|
224
|
+
requests: positiveInt(raw?.requests),
|
|
225
|
+
promptTokens: positiveInt(raw?.promptTokens),
|
|
226
|
+
completionTokens: positiveInt(raw?.completionTokens),
|
|
227
|
+
totalTokens: positiveInt(raw?.totalTokens),
|
|
228
|
+
cachedTokens: positiveInt(raw?.cachedTokens),
|
|
229
|
+
reasoningTokens: positiveInt(raw?.reasoningTokens)
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/** 整张「模型/账号 -> 累计」表补齐字段。 */
|
|
233
|
+
function normalizeStore(store) {
|
|
234
|
+
const out = {};
|
|
235
|
+
for (const [key, totals] of Object.entries(store ?? {})) {
|
|
236
|
+
if (typeof totals !== "object" || totals === null) continue;
|
|
237
|
+
out[key] = normalizeTotals(totals);
|
|
238
|
+
}
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
/** 计数表(失败类别 / 账号失败数)补齐:只留正数,空表给 undefined。 */
|
|
242
|
+
function normalizeCounts(raw) {
|
|
243
|
+
if (typeof raw !== "object" || raw === null) return void 0;
|
|
244
|
+
const out = {};
|
|
245
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
246
|
+
const count = positiveInt(value);
|
|
247
|
+
if (count > 0) out[key] = count;
|
|
248
|
+
}
|
|
249
|
+
return Object.keys(out).length === 0 ? void 0 : out;
|
|
250
|
+
}
|
|
251
|
+
/** 首字延迟直方图补齐到固定桶数;旧账本/脏数组一律按空表。 */
|
|
252
|
+
function normalizeBuckets(raw) {
|
|
253
|
+
if (!Array.isArray(raw)) return void 0;
|
|
254
|
+
const out = Array.from({ length: TTFT_BUCKET_COUNT }, (_, index) => positiveInt(raw[index]));
|
|
255
|
+
return out.some((count) => count > 0) ? out : void 0;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* 用量账本。
|
|
259
|
+
*
|
|
260
|
+
* 记账分两步,因为一次请求可能只有其一:
|
|
261
|
+
* - `noteRequest()` 在请求发出时调用(拿不到 usage 的流也要计入请求数);
|
|
262
|
+
* - `noteUsage()` 在收到 usage 帧时调用(补 token 数)。
|
|
263
|
+
*/
|
|
264
|
+
var CodeArtsUsageTracker = class {
|
|
265
|
+
days = /* @__PURE__ */ new Map();
|
|
266
|
+
lastAt;
|
|
267
|
+
loaded = false;
|
|
268
|
+
loading;
|
|
269
|
+
saveTimer;
|
|
270
|
+
saving = Promise.resolve();
|
|
271
|
+
path;
|
|
272
|
+
now;
|
|
273
|
+
saveDebounceMs;
|
|
274
|
+
constructor(options = {}) {
|
|
275
|
+
this.path = options.path;
|
|
276
|
+
this.now = options.now ?? (() => Date.now());
|
|
277
|
+
this.saveDebounceMs = options.saveDebounceMs ?? 2e3;
|
|
278
|
+
}
|
|
279
|
+
/** 读账本(懒加载,只读一次)。 */
|
|
280
|
+
async load() {
|
|
281
|
+
this.loading ??= this.readFile();
|
|
282
|
+
return this.loading;
|
|
283
|
+
}
|
|
284
|
+
async readFile() {
|
|
285
|
+
if (this.loaded || this.path === void 0 || !existsSync(this.path)) {
|
|
286
|
+
this.loaded = true;
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
try {
|
|
290
|
+
const raw = await readFile(this.path, "utf8");
|
|
291
|
+
const parsed = JSON.parse(raw);
|
|
292
|
+
if (parsed.version !== 1 || typeof parsed.days !== "object" || parsed.days === null) return;
|
|
293
|
+
for (const [date, day] of Object.entries(parsed.days)) {
|
|
294
|
+
if (typeof day !== "object" || day === null) continue;
|
|
295
|
+
const stored = day;
|
|
296
|
+
const restored = {
|
|
297
|
+
models: normalizeStore(stored.models),
|
|
298
|
+
accounts: normalizeStore(stored.accounts)
|
|
299
|
+
};
|
|
300
|
+
if (stored.hours !== void 0) restored.hours = normalizeStore(stored.hours);
|
|
301
|
+
const failures = normalizeCounts(stored.failures);
|
|
302
|
+
if (failures !== void 0) restored.failures = failures;
|
|
303
|
+
const failuresByAccount = normalizeCounts(stored.failuresByAccount);
|
|
304
|
+
if (failuresByAccount !== void 0) restored.failuresByAccount = failuresByAccount;
|
|
305
|
+
const ttft = normalizeBuckets(stored.ttft);
|
|
306
|
+
if (ttft !== void 0) restored.ttft = ttft;
|
|
307
|
+
this.days.set(date, restored);
|
|
308
|
+
}
|
|
309
|
+
this.prune(this.now());
|
|
310
|
+
} catch {
|
|
311
|
+
this.days.clear();
|
|
312
|
+
} finally {
|
|
313
|
+
this.loaded = true;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
day(dateKey) {
|
|
317
|
+
let day = this.days.get(dateKey);
|
|
318
|
+
if (day === void 0) {
|
|
319
|
+
day = {
|
|
320
|
+
models: {},
|
|
321
|
+
accounts: {}
|
|
322
|
+
};
|
|
323
|
+
this.days.set(dateKey, day);
|
|
324
|
+
}
|
|
325
|
+
return day;
|
|
326
|
+
}
|
|
327
|
+
bucket(store, key) {
|
|
328
|
+
let totals = store[key];
|
|
329
|
+
if (totals === void 0) {
|
|
330
|
+
totals = emptyTotals();
|
|
331
|
+
store[key] = totals;
|
|
332
|
+
}
|
|
333
|
+
return totals;
|
|
334
|
+
}
|
|
335
|
+
/** 记一次请求(不等到 usage 帧)。 */
|
|
336
|
+
noteRequest(accountId, model, at = this.now()) {
|
|
337
|
+
const day = this.day(localDateKey(at));
|
|
338
|
+
addTotals(this.bucket(day.models, model), { requests: 1 });
|
|
339
|
+
addTotals(this.bucket(day.accounts, accountId), { requests: 1 });
|
|
340
|
+
addTotals(this.bucket(this.hoursOf(day), localHourKey(at)), { requests: 1 });
|
|
341
|
+
this.lastAt = at;
|
|
342
|
+
this.prune(at);
|
|
343
|
+
this.scheduleSave();
|
|
344
|
+
}
|
|
345
|
+
/** 记一次 usage 帧。 */
|
|
346
|
+
noteUsage(accountId, model, raw, at = this.now()) {
|
|
347
|
+
const usage = normalizeUsage(raw);
|
|
348
|
+
if (usage.totalTokens === 0 && usage.promptTokens === 0 && usage.completionTokens === 0) return;
|
|
349
|
+
const day = this.day(localDateKey(at));
|
|
350
|
+
addTotals(this.bucket(day.models, model), usage);
|
|
351
|
+
addTotals(this.bucket(day.accounts, accountId), usage);
|
|
352
|
+
addTotals(this.bucket(this.hoursOf(day), localHourKey(at)), usage);
|
|
353
|
+
this.lastAt = at;
|
|
354
|
+
this.prune(at);
|
|
355
|
+
this.scheduleSave();
|
|
356
|
+
}
|
|
357
|
+
/** 一天里的逐小时桶,第一次写的时候才建(老账本没有这个键)。 */
|
|
358
|
+
hoursOf(day) {
|
|
359
|
+
day.hours ??= {};
|
|
360
|
+
return day.hours;
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* 记一次失败请求。
|
|
364
|
+
*
|
|
365
|
+
* 只在「这次请求最终回给用户一个错误」时调用一次 —— 插件内部换号重试不算失败,
|
|
366
|
+
* 否则一个排队重试就能把失败率刷成好几倍。`kind` 用 shim 的失败出口标识。
|
|
367
|
+
*/
|
|
368
|
+
noteFailure(kind, accountId, at = this.now()) {
|
|
369
|
+
if (kind === "") return;
|
|
370
|
+
const day = this.day(localDateKey(at));
|
|
371
|
+
day.failures ??= {};
|
|
372
|
+
day.failures[kind] = (day.failures[kind] ?? 0) + 1;
|
|
373
|
+
if (accountId !== void 0 && accountId !== "") {
|
|
374
|
+
day.failuresByAccount ??= {};
|
|
375
|
+
day.failuresByAccount[accountId] = (day.failuresByAccount[accountId] ?? 0) + 1;
|
|
376
|
+
}
|
|
377
|
+
this.lastAt = at;
|
|
378
|
+
this.prune(at);
|
|
379
|
+
this.scheduleSave();
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* 记一次首字延迟(毫秒),落进直方图。
|
|
383
|
+
*
|
|
384
|
+
* 从请求进入 shim 算起,到上游第一帧真的写给 DSH 为止 —— 排队和换号的时间都算进去,
|
|
385
|
+
* 因为那正是用户盯着转圈等掉的时长。
|
|
386
|
+
*/
|
|
387
|
+
noteLatency(ms, at = this.now()) {
|
|
388
|
+
if (!Number.isFinite(ms) || ms < 0) return;
|
|
389
|
+
const day = this.day(localDateKey(at));
|
|
390
|
+
day.ttft ??= new Array(TTFT_BUCKET_COUNT).fill(0);
|
|
391
|
+
let index = TTFT_BUCKETS_MS.findIndex((limit) => ms <= limit);
|
|
392
|
+
if (index < 0) index = TTFT_BUCKET_COUNT - 1;
|
|
393
|
+
day.ttft[index] += 1;
|
|
394
|
+
this.lastAt = at;
|
|
395
|
+
this.prune(at);
|
|
396
|
+
this.scheduleSave();
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* 丢弃保留期之外的天(按日期键比较即可,YYYY-MM-DD 是字典序)。
|
|
400
|
+
*
|
|
401
|
+
* 顺带把两天之前的**小时桶**清掉:逐小时数据只有「今天按小时」在画,留着只是
|
|
402
|
+
* 让 60 天的账本多出一个数量级的体积。
|
|
403
|
+
*/
|
|
404
|
+
prune(at) {
|
|
405
|
+
if (this.days.size === 0) return;
|
|
406
|
+
const cutoff = localDateKey(at - 5184e6);
|
|
407
|
+
const hourCutoff = localDateKey(at - 1728e5);
|
|
408
|
+
for (const [date, day] of [...this.days.entries()]) if (date < cutoff) this.days.delete(date);
|
|
409
|
+
else if (date < hourCutoff && day.hours !== void 0) delete day.hours;
|
|
410
|
+
}
|
|
411
|
+
/** 当前快照(卡片与 CLI 都读它)。 */
|
|
412
|
+
snapshot(at = this.now()) {
|
|
413
|
+
const todayKey = localDateKey(at);
|
|
414
|
+
const today = this.days.get(todayKey);
|
|
415
|
+
const cutoff = localDateKey(at - 2592e6);
|
|
416
|
+
const allTime = emptyTotals();
|
|
417
|
+
const last30 = emptyTotals();
|
|
418
|
+
for (const [date, day] of this.days) for (const totals of Object.values(day.models)) {
|
|
419
|
+
mergeTotals(allTime, totals);
|
|
420
|
+
if (date >= cutoff) mergeTotals(last30, totals);
|
|
421
|
+
}
|
|
422
|
+
const models = today?.models ?? {};
|
|
423
|
+
const failuresByKind = today?.failures ?? {};
|
|
424
|
+
const ttft = today?.ttft ?? [];
|
|
425
|
+
const p50 = percentileOf(ttft, .5);
|
|
426
|
+
const p95 = percentileOf(ttft, .95);
|
|
427
|
+
return {
|
|
428
|
+
today: {
|
|
429
|
+
...emptyTotals(),
|
|
430
|
+
...today === void 0 ? {} : sumOf(models)
|
|
431
|
+
},
|
|
432
|
+
allTime,
|
|
433
|
+
last30,
|
|
434
|
+
failuresToday: {
|
|
435
|
+
total: Object.values(failuresByKind).reduce((sum, count) => sum + count, 0),
|
|
436
|
+
byKind: { ...failuresByKind }
|
|
437
|
+
},
|
|
438
|
+
failuresByAccountToday: { ...today?.failuresByAccount ?? {} },
|
|
439
|
+
latencyToday: {
|
|
440
|
+
samples: ttft.reduce((sum, count) => sum + count, 0),
|
|
441
|
+
...p50.value === void 0 ? {} : { p50: p50.value },
|
|
442
|
+
...p95.value === void 0 ? {} : { p95: p95.value },
|
|
443
|
+
overflow: p95.overflow
|
|
444
|
+
},
|
|
445
|
+
byModelToday: Object.entries(models).map(([id, totals]) => ({
|
|
446
|
+
id,
|
|
447
|
+
totals: { ...totals }
|
|
448
|
+
})).sort((a, b) => b.totals.totalTokens - a.totals.totalTokens || (a.id < b.id ? -1 : 1)),
|
|
449
|
+
byAccountToday: Object.fromEntries(Object.entries(today?.accounts ?? {}).map(([id, totals]) => [id, { ...totals }])),
|
|
450
|
+
days: this.days.size,
|
|
451
|
+
recentDays: this.recentDaysOf(at),
|
|
452
|
+
todayByHour: this.todayByHourOf(today, at),
|
|
453
|
+
...this.lastAt === void 0 ? {} : { lastAt: this.lastAt }
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
/** 最近 TREND_DAYS 天的每日合计(按日期升序,缺账目的日子补 0)。 */
|
|
457
|
+
recentDaysOf(at) {
|
|
458
|
+
const out = [];
|
|
459
|
+
for (let back = 34; back >= 0; back -= 1) {
|
|
460
|
+
const date = localDateKey(at - back * 864e5);
|
|
461
|
+
const day = this.days.get(date);
|
|
462
|
+
out.push({
|
|
463
|
+
date,
|
|
464
|
+
totals: day === void 0 ? emptyTotals() : sumOf(day.models)
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
return out;
|
|
468
|
+
}
|
|
469
|
+
/** 今天 0 点起的 24 个钟点(还没到的小时补 0,横轴才有固定的 24 格)。 */
|
|
470
|
+
todayByHourOf(today, at) {
|
|
471
|
+
const hours = today?.hours ?? {};
|
|
472
|
+
const currentHour = new Date(at).getHours();
|
|
473
|
+
return Array.from({ length: 24 }, (_, hour) => {
|
|
474
|
+
const totals = hours[localHourKeyOfHour(hour)];
|
|
475
|
+
return {
|
|
476
|
+
hour,
|
|
477
|
+
totals: hour > currentHour || totals === void 0 ? emptyTotals() : { ...totals }
|
|
478
|
+
};
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
scheduleSave() {
|
|
482
|
+
if (this.path === void 0) return;
|
|
483
|
+
if (this.saveTimer !== void 0) return;
|
|
484
|
+
this.saveTimer = setTimeout(() => {
|
|
485
|
+
this.saveTimer = void 0;
|
|
486
|
+
this.save();
|
|
487
|
+
}, this.saveDebounceMs);
|
|
488
|
+
this.saveTimer.unref?.();
|
|
489
|
+
}
|
|
490
|
+
/** 立即落盘(关停时调用,别丢最后几秒的账)。 */
|
|
491
|
+
async flush() {
|
|
492
|
+
if (this.saveTimer !== void 0) {
|
|
493
|
+
clearTimeout(this.saveTimer);
|
|
494
|
+
this.saveTimer = void 0;
|
|
495
|
+
}
|
|
496
|
+
await this.save();
|
|
497
|
+
}
|
|
498
|
+
save() {
|
|
499
|
+
if (this.path === void 0) return Promise.resolve();
|
|
500
|
+
const doc = {
|
|
501
|
+
version: 1,
|
|
502
|
+
days: Object.fromEntries(this.days)
|
|
503
|
+
};
|
|
504
|
+
this.saving = this.saving.then(() => writeJsonAtomic(this.path, doc), () => writeJsonAtomic(this.path, doc));
|
|
505
|
+
return this.saving;
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
/** 一批桶的合计。 */
|
|
509
|
+
function sumOf(store) {
|
|
510
|
+
const out = emptyTotals();
|
|
511
|
+
for (const totals of Object.values(store)) mergeTotals(out, totals);
|
|
512
|
+
return out;
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* 直方图分位。
|
|
516
|
+
*
|
|
517
|
+
* 返回的是「落进的那一档的上界」而不是精确毫秒 —— 界面上显示 `≤200ms` 这种口径,
|
|
518
|
+
* 比伪造一个精确值诚实。落进溢出档时 `value` 缺省、`overflow` 为真。
|
|
519
|
+
*/
|
|
520
|
+
function percentileOf(buckets, ratio) {
|
|
521
|
+
const total = buckets.reduce((sum, count) => sum + count, 0);
|
|
522
|
+
if (total === 0) return { overflow: false };
|
|
523
|
+
const target = Math.ceil(total * ratio);
|
|
524
|
+
let seen = 0;
|
|
525
|
+
for (let index = 0; index < buckets.length; index += 1) {
|
|
526
|
+
seen += buckets[index] ?? 0;
|
|
527
|
+
if (seen < target) continue;
|
|
528
|
+
return index < TTFT_BUCKETS_MS.length ? {
|
|
529
|
+
value: TTFT_BUCKETS_MS[index],
|
|
530
|
+
overflow: false
|
|
531
|
+
} : { overflow: true };
|
|
532
|
+
}
|
|
533
|
+
return { overflow: true };
|
|
534
|
+
}
|
|
535
|
+
//#endregion
|
|
536
|
+
//#region src/version.ts
|
|
537
|
+
const CODEARTS_VERSION = "1.4.0";
|
|
538
|
+
//#endregion
|
|
539
|
+
export { refreshCatalog as a, discoverModels as i, CodeArtsUsageTracker as n, codeartsUsagePath as r, CODEARTS_VERSION as t };
|