dsh-codearts 1.2.13 → 1.3.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.
@@ -1,940 +1,5 @@
1
1
  import { n as __exportAll } from "./rolldown-runtime-B4iAMlE-.mjs";
2
- import { createHash, createHmac, createPrivateKey, createSign, generateKeyPairSync, randomBytes } from "node:crypto";
3
- import { chmod, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
- import { homedir } from "node:os";
5
- import { dirname, join } from "node:path";
6
- import http from "node:http";
7
- import { existsSync } from "node:fs";
8
- //#region src/dpop.ts
9
- /**
10
- * DPoP(RFC 9449)证明 JWT:ES256 + P-256,供 oauth2/tokens 请求头使用。
11
- * 翻译自 codearts2api 的 internal/upstream/dpop.go。
12
- *
13
- * 关键约束:refresh_token 与首次换取时的 DPoP 公钥绑定,刷新时必须复用同一
14
- * 私钥,否则 STS 报 InvalidDPoPHeader。因此该私钥必须随 refresh_token 一起落盘。
15
- *
16
- * @module dsh-codearts/dpop
17
- */
18
- const P256_ORDER = BigInt("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
19
- const P256_HALF = P256_ORDER >> 1n;
20
- /** 生成新的 DPoP 私钥(JWK)。 */
21
- function newDPoPPrivateJWK() {
22
- const { privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
23
- const jwk = privateKey.export({ format: "jwk" });
24
- return {
25
- kty: jwk.kty,
26
- crv: jwk.crv,
27
- x: jwk.x,
28
- y: jwk.y,
29
- d: jwk.d
30
- };
31
- }
32
- function privateKeyFromJWK(jwk) {
33
- return createPrivateKey({
34
- key: jwk,
35
- format: "jwk"
36
- });
37
- }
38
- function b64u(buf) {
39
- return Buffer.from(buf).toString("base64url");
40
- }
41
- /**
42
- * 生成 DPoP proof JWT(htm=POST,htu=token 端点)。
43
- * 低 S 归一化以兼容服务端校验。
44
- */
45
- function signDpopProof(jwk, htu) {
46
- const key = privateKeyFromJWK(jwk);
47
- const header = {
48
- alg: "ES256",
49
- typ: "dpop+jwt",
50
- jwk: {
51
- kty: "EC",
52
- crv: "P-256",
53
- x: jwk.x,
54
- y: jwk.y
55
- }
56
- };
57
- const headerJSON = Buffer.from(JSON.stringify(header));
58
- const payload = {
59
- htm: "POST",
60
- htu,
61
- iat: Math.floor(Date.now() / 1e3),
62
- jti: randomBytes(16).toString("hex")
63
- };
64
- const payloadJSON = Buffer.from(JSON.stringify(payload));
65
- const input = `${b64u(headerJSON)}.${b64u(payloadJSON)}`;
66
- const sig = createSign("SHA256").update(input).sign({
67
- key,
68
- dsaEncoding: "ieee-p1363"
69
- });
70
- let s = sig.subarray(32, 64);
71
- let sBig = BigInt(`0x${s.toString("hex")}`);
72
- if (sBig > P256_HALF) {
73
- sBig = P256_ORDER - sBig;
74
- s = Buffer.from(sBig.toString(16).padStart(64, "0"), "hex");
75
- }
76
- return `${input}.${b64u(Buffer.concat([sig.subarray(0, 32), s]))}`;
77
- }
78
- //#endregion
79
- //#region src/oauth.ts
80
- /**
81
- * CodeArts OAuth2(PKCE)登录 + 刷新,翻译自 codearts2api 的
82
- * internal/server/oauth.go / cmd/login/main.go / internal/upstream/client.go。
83
- *
84
- * 登录:本地起 127.0.0.1 回调服务 → 浏览器跳 codearts.huaweicloud.com/authorize
85
- * → 用户登录 → 华为回调带 code → 用 code + PKCE verifier + DPoP 私钥换
86
- * security_token + 临时 AK/SK + refresh_token。
87
- *
88
- * 刷新:refresh_token 与 client_id、DPoP 私钥三者绑定,刷新时原样复用。
89
- *
90
- * @module dsh-codearts/oauth
91
- */
92
- const CLIENT_ID = "codearts-agent";
93
- const PLUGIN_NAME = "snap_AIIDE";
94
- const PLUGIN_VERSION = "5.2.0";
95
- const SNAP_HOST$1 = "https://snap-access.cn-north-4.myhuaweicloud.com";
96
- const STS_HOST = "https://sts.cn-north-4.myhuaweicloud.com";
97
- const PORTAL = "https://codearts.huaweicloud.com/portal";
98
- const REDIRECT_PATH = "/oauth/callback";
99
- function defaultLoginConfig() {
100
- return {
101
- clientId: CLIENT_ID,
102
- snapHost: SNAP_HOST$1,
103
- stsHost: STS_HOST,
104
- portal: PORTAL
105
- };
106
- }
107
- function randomHex(n) {
108
- return randomBytes(n).toString("hex");
109
- }
110
- function pkce() {
111
- const verifier = base64url(randomBytes(64));
112
- return {
113
- verifier,
114
- challenge: createHash("sha256").update(verifier).digest("base64url"),
115
- method: "S256"
116
- };
117
- }
118
- function base64url(buf) {
119
- return buf.toString("base64url");
120
- }
121
- /** 构造华为授权页 URL(浏览器打开,用户登录后回调本机)。 */
122
- function buildAuthorizeURL(cfg, ticketId, challenge, method, port) {
123
- const q = new URLSearchParams();
124
- q.set("theme", "2");
125
- q.set("locale", "zh-cn");
126
- q.set("uri_scheme", cfg.clientId);
127
- q.set("client_id", cfg.clientId);
128
- q.set("port", String(port));
129
- q.set("code_challenge", challenge);
130
- q.set("code_challenge_method", "SHA-256");
131
- q.set("ticket_id", ticketId);
132
- q.set("plugin-name", PLUGIN_NAME);
133
- q.set("plugin-version", PLUGIN_VERSION);
134
- return `${cfg.portal}/authorize?${q.toString()}`;
135
- }
136
- /** 换 token 请求体:application/x-www-form-urlencoded(与华为 STS 一致)。 */
137
- function buildTokenBody(cfg, params) {
138
- return new URLSearchParams({
139
- client_id: cfg.clientId,
140
- ...params
141
- }).toString();
142
- }
143
- /** 用授权 code 换 token。 */
144
- async function exchangeCode(cfg, code, verifier, port, dpopJWK, abort) {
145
- const htu = `${cfg.stsHost}/v1/oauth2/tokens`;
146
- const dpop = signDpopProof(dpopJWK, htu);
147
- const body = buildTokenBody(cfg, {
148
- code,
149
- code_verifier: verifier,
150
- grant_type: "authorization_code",
151
- redirect_uri: `http://127.0.0.1:${port}${REDIRECT_PATH}`
152
- });
153
- const res = await fetch(`${htu}`, {
154
- method: "POST",
155
- headers: {
156
- "Content-Type": "application/x-www-form-urlencoded",
157
- "DPoP": dpop,
158
- "plugin-name": PLUGIN_NAME,
159
- "plugin-version": PLUGIN_VERSION
160
- },
161
- body,
162
- signal: abort
163
- });
164
- if (!res.ok) {
165
- const text = await res.text();
166
- throw new Error(`exchange code failed: ${res.status} ${text}`);
167
- }
168
- return parseToken(await res.json(), dpopJWK, cfg.clientId);
169
- }
170
- /** 用 refresh_token 续期。 */
171
- async function refreshToken(cfg, prev, abort) {
172
- const htu = `${cfg.stsHost}/v1/oauth2/tokens`;
173
- const dpop = signDpopProof(prev.dpopPrivateKey, htu);
174
- const body = buildTokenBody(cfg, {
175
- grant_type: "refresh_token",
176
- refresh_token: prev.refreshToken
177
- });
178
- const res = await fetch(`${htu}`, {
179
- method: "POST",
180
- headers: {
181
- "Content-Type": "application/x-www-form-urlencoded",
182
- "DPoP": dpop,
183
- "plugin-name": PLUGIN_NAME,
184
- "plugin-version": PLUGIN_VERSION
185
- },
186
- body,
187
- signal: abort
188
- });
189
- if (!res.ok) {
190
- const text = await res.text();
191
- throw new Error(`refresh token failed: ${res.status} ${text}`);
192
- }
193
- return parseToken(await res.json(), prev.dpopPrivateKey, prev.clientId, prev);
194
- }
195
- function parseToken(json, dpopJWK, clientId, prev) {
196
- const cred = json.credentials ?? {};
197
- return {
198
- userId: json.user_id ?? prev?.userId ?? "",
199
- userName: json.user_name ?? prev?.userName ?? "",
200
- domainId: json.domain_id ?? prev?.domainId ?? "",
201
- securityToken: cred.security_token ?? cred.SecurityToken ?? "",
202
- accessKeyId: cred.access_key_id ?? cred.AccessKeyID ?? "",
203
- secretAccessKey: cred.secret_access_key ?? cred.SecretAccessKey ?? "",
204
- expiration: cred.expiration ?? cred.Expiration ?? "",
205
- refreshToken: json.refresh_token ?? json.RefreshToken ?? prev?.refreshToken ?? "",
206
- clientId,
207
- dpopPrivateKey: dpopJWK
208
- };
209
- }
210
- /**
211
- * 华为登录后浏览器落回本机回调的落地页。
212
- *
213
- * 这一页本身没有任何后续逻辑:`code` 在响应发出的同一时刻就已交给等待队列
214
- * (见 startLogin 里的 finish),token 交换完全在服务端做,页面关不关都不影响
215
- * 登录结果。它只是 redirect_uri 必然要渲染的一个落点 —— 华为侧没有「登录成功」
216
- * 页可停留,成功标志就是这一次 302 到 127.0.0.1。
217
- *
218
- * 卡片用 `window.open` 打开授权页,所以这个标签页能自己关掉;用户从卡片的
219
- * 手动链接打开、或浏览器拦脚本关窗时 close 会失败,1.2s 后把提示换成「可关闭」。
220
- */
221
- const CALLBACK_HTML = `<!doctype html>
222
- <html lang="zh-CN">
223
- <head>
224
- <meta charset="utf-8">
225
- <meta name="viewport" content="width=device-width,initial-scale=1">
226
- <title>CodeArts 登录</title>
227
- <style>
228
- html,body{height:100%}
229
- body{margin:0;display:flex;align-items:center;justify-content:center;background:#fff;color:#1f2329;
230
- font:15px/1.6 system-ui,-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
231
- p{margin:0;padding:24px;text-align:center}
232
- </style>
233
- </head>
234
- <body>
235
- <p id="msg">正在返回 DeepSeek Harness…</p>
236
- <script>
237
- setTimeout(function () { try { window.close() } catch (e) {} }, 300)
238
- setTimeout(function () {
239
- var el = document.getElementById('msg')
240
- if (el) el.textContent = 'CodeArts 登录成功,本页可关闭,请回到 DeepSeek Harness。'
241
- }, 1200)
242
- <\/script>
243
- </body>
244
- </html>`;
245
- async function startLogin(cfg = defaultLoginConfig()) {
246
- const ticketId = randomHex(16);
247
- const { verifier, challenge, method } = pkce();
248
- const dpopJWK = newDPoPPrivateJWK();
249
- const codeCh = await new Promise((resolve) => {
250
- const server = http.createServer();
251
- const waiters = [];
252
- server.on("request", (req, res) => {
253
- const u = new URL(req.url ?? "/", "http://127.0.0.1");
254
- if (u.pathname !== REDIRECT_PATH) {
255
- res.writeHead(404).end();
256
- return;
257
- }
258
- const code = u.searchParams.get("code");
259
- const redirect = u.searchParams.get("redirect");
260
- if (!code && redirect) {
261
- res.writeHead(307, { Location: redirect }).end();
262
- return;
263
- }
264
- if (!code) {
265
- let body = "";
266
- req.on("data", (c) => body += c);
267
- req.on("end", () => {
268
- finish(new URLSearchParams(body).get("code"));
269
- });
270
- return;
271
- }
272
- finish(code);
273
- function finish(c) {
274
- res.writeHead(200, {
275
- "Content-Type": "text/html; charset=utf-8",
276
- "Cache-Control": "no-store"
277
- });
278
- res.end(CALLBACK_HTML);
279
- if (c) for (const w of waiters.splice(0)) w(c);
280
- }
281
- });
282
- server.listen(0, "127.0.0.1", () => {
283
- const port = server.address().port;
284
- resolve({
285
- port,
286
- server,
287
- take: () => new Promise((r) => waiters.push(r))
288
- });
289
- });
290
- });
291
- const url = buildAuthorizeURL(cfg, ticketId, challenge, method, codeCh.port);
292
- const promise = (async () => {
293
- const timer = setTimeout(() => codeCh.server.close(), 3e5);
294
- try {
295
- return await exchangeCode(cfg, await codeCh.take(), verifier, codeCh.port, dpopJWK);
296
- } finally {
297
- clearTimeout(timer);
298
- codeCh.server.close();
299
- }
300
- })();
301
- return {
302
- url,
303
- port: codeCh.port,
304
- promise,
305
- close: () => codeCh.server.close()
306
- };
307
- }
308
- //#endregion
309
- //#region src/auth.ts
310
- /**
311
- * CodeArts credential store.
312
- *
313
- * 真实 CodeArts 桌面端聊天需要:STS `security_token` + 临时 AK/SK(HMAC 签名)
314
- * + refresh_token(绑定 DPoP 私钥用于续期)。本模块持久化这全套 OAuth 凭证,
315
- * 并提供自动续期。同时也保留"手动粘贴 security_token"的兜底(但无 AK/SK 时只能
316
- * 作为降级态,聊天会被 APIG 拒)。
317
- *
318
- * @module dsh-codearts/auth
319
- */
320
- /** 福利领取的上限;失败无所谓,卡住登录才是问题。 */
321
- const CLAIM_TIMEOUT_MS = 15e3;
322
- /** 两条凭证里较新的一条(`storedAt` 缺失视为最旧)。 */
323
- function newerCredential(a, b) {
324
- const at = typeof a.storedAt === "number" ? a.storedAt : 0;
325
- return (typeof b.storedAt === "number" ? b.storedAt : 0) > at ? b : a;
326
- }
327
- /** 从 OAuthToken 落库。 */
328
- function credentialFromOAuth(t, label) {
329
- return {
330
- token: t.securityToken,
331
- accessKeyId: t.accessKeyId,
332
- secretAccessKey: t.secretAccessKey,
333
- refreshToken: t.refreshToken,
334
- dpopPrivateKey: t.dpopPrivateKey,
335
- clientId: t.clientId,
336
- expiration: t.expiration,
337
- userId: t.userId,
338
- userName: t.userName,
339
- domainId: t.domainId,
340
- label: label ?? t.userName ?? t.userId,
341
- storedAt: Date.now()
342
- };
343
- }
344
- function codeartsAuthPath(home) {
345
- const base = home ?? process.env.DSH_HOME ?? join(homedir(), ".dsh");
346
- return join(base, ".codearts-auth.json");
347
- }
348
- async function loadCredential(path) {
349
- try {
350
- const raw = await readFile(path, "utf8");
351
- const parsed = JSON.parse(raw);
352
- if (typeof parsed.token !== "string" || parsed.token.length === 0) return void 0;
353
- return {
354
- ...parsed,
355
- token: parsed.token
356
- };
357
- } catch {
358
- return;
359
- }
360
- }
361
- /** 原子写一个 JSON 文件(0600)。 */
362
- async function writeJsonAtomic(path, value) {
363
- await mkdir(dirname(path), { recursive: true });
364
- const body = JSON.stringify(value, null, 2);
365
- const tmp = `${path}.${process.pid}-${Math.random().toString(36).slice(2, 10)}.tmp`;
366
- try {
367
- await writeFile(tmp, body, { mode: 384 });
368
- await chmod(tmp, 384).catch(() => {});
369
- await rename(tmp, path);
370
- } catch {
371
- await unlink(tmp).catch(() => {});
372
- await writeFile(path, body, { mode: 384 });
373
- }
374
- }
375
- async function saveCredential(path, cred) {
376
- await writeJsonAtomic(path, cred);
377
- }
378
- async function clearCredential(path) {
379
- try {
380
- await unlink(path);
381
- } catch {}
382
- }
383
- /**
384
- * 领取限时福利(幂等);无 AK/SK 时静默跳过。
385
- *
386
- * 必须带超时:领取失败不该拖住登录/续期。早先没传 signal,claimBenefit 的
387
- * fetch 就没有任何超时 —— 福利接口一旦不响应,ensureFresh() 永远不返回,
388
- * 跟着卡死的是整个聊天请求。
389
- */
390
- async function claimIfPossible(cred) {
391
- if (!cred.accessKeyId || !cred.secretAccessKey) return;
392
- try {
393
- const { claimBenefit } = await Promise.resolve().then(() => upstream_exports);
394
- await claimBenefit({
395
- token: cred.token,
396
- accessKeyId: cred.accessKeyId,
397
- secretAccessKey: cred.secretAccessKey,
398
- securityToken: cred.token
399
- }, AbortSignal.timeout(CLAIM_TIMEOUT_MS));
400
- } catch {}
401
- }
402
- /** 续期判定:距过期不足 5 分钟就去刷。 */
403
- const REFRESH_SKEW_MS = 3e5;
404
- var CodeArtsCredentialStore = class {
405
- _current;
406
- _path;
407
- /** 正在进行的刷新。并发请求必须共用它,不能各刷一次。 */
408
- _inflight;
409
- /**
410
- * 凭证代际。重登/清除会推进它,让还在飞的刷新发现自己过期,
411
- * 从而不把刷新结果写回去覆盖掉刚拿到的新凭证。
412
- */
413
- _gen = 0;
414
- /** 作废在飞的刷新;任何直接写凭证的路径都要先调它。 */
415
- invalidateInflight() {
416
- this._gen += 1;
417
- this._inflight = void 0;
418
- }
419
- constructor(path) {
420
- this._path = path;
421
- }
422
- setPath(path) {
423
- this.invalidateInflight();
424
- this._current = void 0;
425
- this._path = path;
426
- }
427
- /** 给 shim 用:返回签名所需全套。 */
428
- async resolve() {
429
- const cred = await this.ensureFresh();
430
- if (cred === void 0) return void 0;
431
- return {
432
- token: cred.token,
433
- accessKeyId: cred.accessKeyId,
434
- secretAccessKey: cred.secretAccessKey,
435
- securityToken: cred.token
436
- };
437
- }
438
- async current() {
439
- return this._current ??= await loadCredential(this._path);
440
- }
441
- /** 从 OAuth 登录结果落库。 */
442
- async setFromOAuth(t, label) {
443
- this.invalidateInflight();
444
- const cred = credentialFromOAuth(t, label);
445
- await saveCredential(this._path, cred);
446
- this._current = cred;
447
- await this.claimIfPossible(cred);
448
- }
449
- /** 领取限时福利(幂等);无 AK/SK 时静默跳过。 */
450
- async claimIfPossible(cred) {
451
- await claimIfPossible(cred);
452
- }
453
- /** 手动粘贴 security_token(降级态,无 AK/SK)。 */
454
- async set(token, label) {
455
- this.invalidateInflight();
456
- const cred = {
457
- token: token.trim(),
458
- label,
459
- storedAt: Date.now()
460
- };
461
- await saveCredential(this._path, cred);
462
- this._current = cred;
463
- }
464
- async clear() {
465
- this.invalidateInflight();
466
- this._current = void 0;
467
- await clearCredential(this._path);
468
- }
469
- async hasCredential() {
470
- return await this.current() !== void 0;
471
- }
472
- /**
473
- * 自动续期:若距过期不足 5 分钟且具备 refresh 条件,则刷新并落库。
474
- * 返回当前(可能已刷新)凭证。
475
- */
476
- async ensureFresh() {
477
- const gen = this._gen;
478
- const cred = this._current ?? await loadCredential(this._path);
479
- if (this._gen !== gen) return this._current;
480
- this._current = cred;
481
- if (!cred) return void 0;
482
- if (!cred.refreshToken || !cred.dpopPrivateKey || !cred.clientId) return cred;
483
- const exp = cred.expiration ? Date.parse(cred.expiration) : NaN;
484
- if (!(Number.isNaN(exp) ? false : exp - Date.now() < 3e5)) return cred;
485
- return this._inflight ??= this.refresh(cred, {
486
- refreshToken: cred.refreshToken,
487
- dpopPrivateKey: cred.dpopPrivateKey,
488
- clientId: cred.clientId
489
- }).finally(() => {
490
- this._inflight = void 0;
491
- });
492
- }
493
- /** 真正去刷一次;失败则把凭证标成 stale 落库,让卡片提示重新登录。 */
494
- async refresh(cred, mat) {
495
- const gen = this._gen;
496
- /**
497
- * 这次刷新的结果还能不能往回写。光看代际号不够:重登是异步落库的,可能在
498
- * 本次刷新启动**之后**才把 _current 换掉,那时代际号已经来不及拦。所以还要
499
- * 确认「当前凭证仍然是这次刷新的那一份」。
500
- */
501
- const stillCurrent = () => this._gen === gen && this._current === cred;
502
- try {
503
- const next = credentialFromOAuth(await refreshToken(defaultLoginConfig(), {
504
- userId: cred.userId ?? "",
505
- userName: cred.userName ?? "",
506
- domainId: "",
507
- securityToken: cred.token,
508
- accessKeyId: cred.accessKeyId ?? "",
509
- secretAccessKey: cred.secretAccessKey ?? "",
510
- expiration: cred.expiration ?? "",
511
- refreshToken: mat.refreshToken,
512
- clientId: mat.clientId,
513
- dpopPrivateKey: mat.dpopPrivateKey
514
- }), cred.label);
515
- if (!stillCurrent()) return next;
516
- await saveCredential(this._path, next);
517
- this._current = next;
518
- await this.claimIfPossible(next);
519
- return next;
520
- } catch {
521
- cred.stale = true;
522
- if (!stillCurrent()) return cred;
523
- this._current = cred;
524
- try {
525
- await saveCredential(this._path, cred);
526
- } catch {}
527
- return cred;
528
- }
529
- }
530
- };
531
- /**
532
- * 手工粘贴 token 的降级账号固定用这个 id:再粘一次是**覆盖**,而不是又加一个。
533
- */
534
- const MANUAL_ACCOUNT_ID = "manual";
535
- function codeartsAccountsPath(home) {
536
- const base = home ?? process.env.DSH_HOME ?? join(homedir(), ".dsh");
537
- return join(base, ".codearts-accounts.json");
538
- }
539
- /**
540
- * 账号的自然键,按稳定性依次退让:
541
- *
542
- * 1. `userId` —— 最理想,同一个人永远同一个键。
543
- * 2. `userName`。
544
- * 3. **DPoP 公钥**。实测上游的 token 响应里 `user_id` / `user_name` **都是空串**
545
- * (2026-09-30 用真实账号核对),所以前两级拿不到。DPoP 密钥由每次登录生成、
546
- * 续期时原样复用,因此「同一次登录」内稳定、不同账号必然不同 —— 比拿 token
547
- * 做键好,因为 token 每次续期都会轮换。
548
- * 4. 最后才退回 token 哈希(手工粘贴的降级凭证没有 DPoP 密钥)。
549
- *
550
- * 已知代价:上游不给稳定身份,所以**对同一个账号重新登录**会被当成新账号,
551
- * 旧条目会自己失效(凭据被拒 → 停用)并可在卡片上删掉。
552
- */
553
- function accountIdOf(cred) {
554
- if (typeof cred.userId === "string" && cred.userId !== "") return cred.userId;
555
- if (typeof cred.userName === "string" && cred.userName !== "") return cred.userName;
556
- const jwk = cred.dpopPrivateKey;
557
- if (jwk !== void 0 && typeof jwk.x === "string" && typeof jwk.y === "string") return `k${createHash("sha256").update(`${jwk.x}.${jwk.y}`).digest("hex").slice(0, 15)}`;
558
- return `t${createHash("sha256").update(cred.token).digest("hex").slice(0, 15)}`;
559
- }
560
- function summarizeAccount(id, cred) {
561
- return {
562
- id,
563
- ...cred.label === void 0 ? {} : { label: cred.label },
564
- ...cred.userName === void 0 ? {} : { userName: cred.userName },
565
- ...cred.expiration === void 0 ? {} : { expiration: cred.expiration },
566
- ...cred.storedAt === void 0 ? {} : { storedAt: cred.storedAt },
567
- stale: cred.stale === true,
568
- signable: typeof cred.accessKeyId === "string" && cred.accessKeyId !== "" && typeof cred.secretAccessKey === "string" && cred.secretAccessKey !== "",
569
- paused: cred.paused === true,
570
- pinned: cred.pinned === true
571
- };
572
- }
573
- /**
574
- * 单个账号的内存状态与续期。
575
- *
576
- * 每个账号一份、互不干扰。`refresh_token` 是一次性的,上游在刷新时会轮换它:
577
- * 同一账号内并发刷新会烧掉它、并让失败的那次把 `stale` 盖在成功那次刚拿到的
578
- * 凭证上,登录态就此写死(本机真实踩过一次)。所以这里保留单凭证时代验证过的
579
- * 「单飞 + 代际」两条保护,只是作用域缩到单个账号。
580
- */
581
- var AccountSlot = class {
582
- _cred;
583
- _inflight;
584
- _gen = 0;
585
- persist;
586
- constructor(cred, persist) {
587
- this._cred = cred;
588
- this.persist = persist;
589
- }
590
- get credential() {
591
- return this._cred;
592
- }
593
- /** 账号被替换或删除:作废在飞的刷新,别让它回头写回旧值。 */
594
- invalidate() {
595
- this._gen += 1;
596
- this._inflight = void 0;
597
- }
598
- async ensureFresh() {
599
- const cred = this._cred;
600
- if (cred.stale === true) return cred;
601
- if (!cred.refreshToken || !cred.dpopPrivateKey || !cred.clientId) return cred;
602
- const exp = cred.expiration ? Date.parse(cred.expiration) : NaN;
603
- if (!(Number.isNaN(exp) ? false : exp - Date.now() < REFRESH_SKEW_MS)) return cred;
604
- return this.forceRefresh();
605
- }
606
- /**
607
- * 不管还剩多久,立刻续期一次。
608
- *
609
- * 给上游回 `invalid_iam_token` 时用:token 可能被提前作废(另一个客户端续期、
610
- * 上游轮换),而 `expiration` 还写着几小时之后,`ensureFresh` 根本不会动。
611
- * 仍然走单飞,避免并发请求把一次性的 refresh_token 烧掉。
612
- */
613
- async forceRefresh() {
614
- const cred = this._cred;
615
- if (cred.stale === true) return cred;
616
- if (!cred.refreshToken || !cred.dpopPrivateKey || !cred.clientId) return cred;
617
- return this._inflight ??= this.refresh(cred, {
618
- refreshToken: cred.refreshToken,
619
- dpopPrivateKey: cred.dpopPrivateKey,
620
- clientId: cred.clientId
621
- }).finally(() => {
622
- this._inflight = void 0;
623
- });
624
- }
625
- async refresh(cred, mat) {
626
- const gen = this._gen;
627
- const stillCurrent = () => this._gen === gen && this._cred === cred;
628
- try {
629
- const next = credentialFromOAuth(await refreshToken(defaultLoginConfig(), {
630
- userId: cred.userId ?? "",
631
- userName: cred.userName ?? "",
632
- domainId: "",
633
- securityToken: cred.token,
634
- accessKeyId: cred.accessKeyId ?? "",
635
- secretAccessKey: cred.secretAccessKey ?? "",
636
- expiration: cred.expiration ?? "",
637
- refreshToken: mat.refreshToken,
638
- clientId: mat.clientId,
639
- dpopPrivateKey: mat.dpopPrivateKey
640
- }), cred.label);
641
- if (!stillCurrent()) return next;
642
- await this.persist(next);
643
- this._cred = next;
644
- await claimIfPossible(next);
645
- return next;
646
- } catch {
647
- cred.stale = true;
648
- if (!stillCurrent()) return cred;
649
- this._cred = cred;
650
- try {
651
- await this.persist(cred);
652
- } catch {}
653
- return cred;
654
- }
655
- }
656
- };
657
- async function readAccountDocument(path) {
658
- try {
659
- const parsed = JSON.parse(await readFile(path, "utf8"));
660
- if (typeof parsed !== "object" || parsed === null) return void 0;
661
- const accounts = parsed.accounts ?? {};
662
- const order = Array.isArray(parsed.order) ? parsed.order.filter((id) => typeof id === "string") : [];
663
- for (const id of Object.keys(accounts)) if (!order.includes(id)) order.push(id);
664
- return {
665
- version: 1,
666
- order,
667
- accounts
668
- };
669
- } catch {
670
- return;
671
- }
672
- }
673
- /** 多账号凭证存储:一个账号一份槽位,共用一个文档文件。 */
674
- var CodeArtsAccountStore = class {
675
- _doc;
676
- _slots = /* @__PURE__ */ new Map();
677
- _loading;
678
- /** 落库串行化:多个账号的续期可能同时想写同一个文档。 */
679
- _writeChain = Promise.resolve();
680
- path;
681
- /** 旧版单凭证文件;新文档不存在时把它收编成第一个账号。 */
682
- legacyPath;
683
- constructor(path, legacyPath) {
684
- this.path = path;
685
- this.legacyPath = legacyPath ?? join(dirname(path), ".codearts-auth.json");
686
- }
687
- async loaded() {
688
- this._loading ??= this.load();
689
- return this._loading;
690
- }
691
- async load() {
692
- const doc = await readAccountDocument(this.path);
693
- if (doc !== void 0) {
694
- this.adopt(doc);
695
- return;
696
- }
697
- const legacy = await loadCredential(this.legacyPath);
698
- const fresh = {
699
- version: 1,
700
- order: [],
701
- accounts: {}
702
- };
703
- if (legacy !== void 0) {
704
- const id = accountIdOf(legacy);
705
- fresh.order.push(id);
706
- fresh.accounts[id] = legacy;
707
- }
708
- this.adopt(fresh);
709
- if (legacy !== void 0) await this.persistDoc();
710
- }
711
- adopt(doc) {
712
- this._doc = doc;
713
- this._slots.clear();
714
- for (const [id, cred] of Object.entries(doc.accounts)) this._slots.set(id, new AccountSlot(cred, this.persisterFor(id)));
715
- }
716
- persisterFor(id) {
717
- return async (cred) => {
718
- if (this._doc === void 0) return;
719
- this._doc.accounts[id] = cred;
720
- await this.persistDoc();
721
- };
722
- }
723
- persistDoc() {
724
- const snapshot = this._doc;
725
- const write = async () => {
726
- if (snapshot !== void 0) await writeJsonAtomic(this.path, snapshot);
727
- };
728
- this._writeChain = this._writeChain.then(write, write);
729
- return this._writeChain;
730
- }
731
- /** 按展示顺序返回账号摘要。 */
732
- async list() {
733
- await this.loaded();
734
- const doc = this._doc;
735
- return doc.order.filter((id) => doc.accounts[id] !== void 0).map((id) => summarizeAccount(id, doc.accounts[id]));
736
- }
737
- async ids() {
738
- await this.loaded();
739
- const doc = this._doc;
740
- return doc.order.filter((id) => doc.accounts[id] !== void 0);
741
- }
742
- async credential(id) {
743
- await this.loaded();
744
- return this._doc.accounts[id];
745
- }
746
- /** 首个账号——卡片顶部与 CLI 的「当前」。 */
747
- async current() {
748
- const ids = await this.ids();
749
- return ids.length === 0 ? void 0 : this._doc.accounts[ids[0]];
750
- }
751
- async hasCredential() {
752
- return (await this.ids()).length > 0;
753
- }
754
- /** 新增或更新一个账号,返回它的 id。 */
755
- async upsert(cred, id = accountIdOf(cred)) {
756
- await this.loaded();
757
- const doc = this._doc;
758
- this._slots.get(id)?.invalidate();
759
- doc.accounts[id] = cred;
760
- if (!doc.order.includes(id)) doc.order.push(id);
761
- this._slots.set(id, new AccountSlot(cred, this.persisterFor(id)));
762
- await this.persistDoc();
763
- await claimIfPossible(cred);
764
- return id;
765
- }
766
- /**
767
- * 从一次 OAuth 登录结果新增/更新账号。
768
- *
769
- * 「再登录一次」天然就是「添加账号」:同一账号是更新,别的账号就是新增。
770
- *
771
- * 传了 `identity`(来自 `fetchCallerIdentity` 的稳定 user_id)就用它当账号键 ——
772
- * 这正是「对同一个账号重新登录会被当成新账号」的解药;拿不到身份时退回旧行为
773
- * (DPoP 公钥当键),也就是每次登录各自成一条。
774
- */
775
- async upsertFromOAuth(t, label, identity) {
776
- const cred = credentialFromOAuth(t, label);
777
- if (identity !== void 0) {
778
- cred.userId = identity.userId;
779
- if (identity.userName !== "") cred.userName = identity.userName;
780
- if (identity.domainId !== "") cred.domainId = identity.domainId;
781
- }
782
- return this.upsert(cred);
783
- }
784
- /**
785
- * 把一条已有账号迁移到它的稳定身份键上(同键则合并)。
786
- *
787
- * 用在两处:登录后回填身份(老条目已经存在时合并掉),以及 `dsh-codearts identity --fix`
788
- * 清理历史遗留的重复条目。合并时保留 `storedAt` 较新的一份凭证,位置沿用目标键原有的顺序。
789
- *
790
- * @returns 迁移结果:`merged` 表示并入了已存在的那条,`moved` 表示只换了键,`noop` 表示键没变
791
- */
792
- async adoptIdentity(id, identity) {
793
- await this.loaded();
794
- const doc = this._doc;
795
- const existing = doc.accounts[id];
796
- if (existing === void 0) return "noop";
797
- const targetKey = identity.userId;
798
- if (targetKey === "" || targetKey === id) {
799
- doc.accounts[id] = {
800
- ...existing,
801
- userId: identity.userId === "" ? existing.userId : identity.userId,
802
- ...identity.userName === "" ? {} : { userName: identity.userName },
803
- ...identity.domainId === "" ? {} : { domainId: identity.domainId }
804
- };
805
- this._slots.get(id)?.invalidate();
806
- this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id)));
807
- await this.persistDoc();
808
- return "noop";
809
- }
810
- const target = doc.accounts[targetKey];
811
- const keep = target === void 0 ? existing : newerCredential(target, existing);
812
- doc.accounts[targetKey] = {
813
- ...keep,
814
- userId: identity.userId,
815
- ...identity.userName === "" ? {} : { userName: identity.userName },
816
- ...identity.domainId === "" ? {} : { domainId: identity.domainId }
817
- };
818
- delete doc.accounts[id];
819
- doc.order = doc.order.filter((existingId) => existingId !== id);
820
- if (!doc.order.includes(targetKey)) doc.order.push(targetKey);
821
- this._slots.get(id)?.invalidate();
822
- this._slots.delete(id);
823
- this._slots.get(targetKey)?.invalidate();
824
- this._slots.set(targetKey, new AccountSlot(doc.accounts[targetKey], this.persisterFor(targetKey)));
825
- await this.persistDoc();
826
- return target === void 0 ? "moved" : "merged";
827
- }
828
- /** 手工粘贴 security_token(降级态,无 AK/SK)——固定覆盖同一个「手工」账号。 */
829
- async set(token, label) {
830
- await this.upsert({
831
- token: token.trim(),
832
- label,
833
- storedAt: Date.now()
834
- }, MANUAL_ACCOUNT_ID);
835
- }
836
- async remove(id) {
837
- await this.loaded();
838
- const doc = this._doc;
839
- this._slots.get(id)?.invalidate();
840
- this._slots.delete(id);
841
- delete doc.accounts[id];
842
- doc.order = doc.order.filter((existing) => existing !== id);
843
- await this.persistDoc();
844
- }
845
- /**
846
- * 暂停 / 恢复一个账号。
847
- *
848
- * 只改标记,不碰凭证:恢复时不需要重新登录。重新装配槽位是因为 AccountSlot
849
- * 缓存的 `_cred` 是旧对象,续期回写会把它盖回来 —— 换了对象,续期写到新文档里。
850
- */
851
- async setPaused(id, paused) {
852
- await this.loaded();
853
- const doc = this._doc;
854
- const cred = doc.accounts[id];
855
- if (cred === void 0) return false;
856
- doc.accounts[id] = {
857
- ...cred,
858
- paused
859
- };
860
- this._slots.get(id)?.invalidate();
861
- this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id)));
862
- await this.persistDoc();
863
- return true;
864
- }
865
- /** 置顶 / 取消置顶:只改变轮转先后,不绕过冷却与并发上限。 */
866
- async setPinned(id, pinned) {
867
- await this.loaded();
868
- const doc = this._doc;
869
- const cred = doc.accounts[id];
870
- if (cred === void 0) return false;
871
- doc.accounts[id] = {
872
- ...cred,
873
- pinned
874
- };
875
- this._slots.get(id)?.invalidate();
876
- this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id)));
877
- await this.persistDoc();
878
- return true;
879
- }
880
- /** shim 用:参与轮转的账号 id(排除用户暂停的)。 */
881
- async dispatchIds() {
882
- const paused = new Set(await this.pausedIds());
883
- return (await this.ids()).filter((id) => !paused.has(id));
884
- }
885
- /** 被用户暂停的账号 id(账号池据此保留状态但不派活)。 */
886
- async pausedIds() {
887
- await this.loaded();
888
- const doc = this._doc;
889
- return (await this.ids()).filter((id) => doc.accounts[id]?.paused === true);
890
- }
891
- /** 置顶账号的 id 列表(给账号池排序用)。 */
892
- async pinnedIds() {
893
- await this.loaded();
894
- const doc = this._doc;
895
- return (await this.ids()).filter((id) => doc.accounts[id]?.pinned === true);
896
- }
897
- /** 清空全部账号(整体登出)。 */
898
- async clear() {
899
- await this.loaded();
900
- for (const slot of this._slots.values()) slot.invalidate();
901
- this._slots.clear();
902
- this._doc = {
903
- version: 1,
904
- order: [],
905
- accounts: {}
906
- };
907
- await this.persistDoc();
908
- await clearCredential(this.legacyPath);
909
- }
910
- /** 给 shim 用:解析某账号的签名材料(内部含续期)。 */
911
- async resolve(id) {
912
- await this.loaded();
913
- const slot = this._slots.get(id);
914
- if (slot === void 0) return void 0;
915
- const cred = await slot.ensureFresh();
916
- return {
917
- token: cred.token,
918
- accessKeyId: cred.accessKeyId,
919
- secretAccessKey: cred.secretAccessKey,
920
- securityToken: cred.token
921
- };
922
- }
923
- /**
924
- * 上游报 IAM token 无效时强制续期。
925
- *
926
- * `seenToken` 是这次请求实际用的 token:若别的请求已经换过凭证,就别再刷一次
927
- * (refresh_token 会轮换,白刷一次就多一次失败风险)。
928
- */
929
- async forceRefresh(id, seenToken) {
930
- await this.loaded();
931
- const slot = this._slots.get(id);
932
- if (slot === void 0) return void 0;
933
- if (seenToken !== void 0 && slot.credential.token !== seenToken) return slot.credential;
934
- return slot.forceRefresh();
935
- }
936
- };
937
- //#endregion
2
+ import { createHash, createHmac, randomBytes } from "node:crypto";
938
3
  //#region src/catalog.ts
939
4
  /**
940
5
  * 参数表(不是模型名单):只给**发现到的**模型补 `contextWindow` / `maxTokens` /
@@ -1218,26 +283,39 @@ function mergeModelLists(sets) {
1218
283
  return la === lb ? a.id < b.id ? -1 : 1 : la < lb ? -1 : 1;
1219
284
  });
1220
285
  }
1221
- /** 同一模型两条记录取更全的一条;`benefit` 永远取或。 */
286
+ /**
287
+ * 同一模型两条记录取更全的一条;`benefit` 永远取或。
288
+ *
289
+ * 基底用 `{ ...keep }` 而不是逐字段手抄:以前这里只抄自己想到的几个字段,
290
+ * `contextWindowKnown` 被静默丢掉 —— 多账号时每个 id 都要过一次这条函数,卡片的
291
+ * 「上下文」整列就成了「—」,而上游其实给了值。以后新增可选字段不用再记得改这里。
292
+ */
1222
293
  function richerModel(current, next) {
1223
294
  const benefit = current.benefit === true || next.benefit === true;
1224
295
  const keep = richerThan(next, current) ? next : current;
1225
296
  const drop = keep === next ? current : next;
1226
297
  const ratio = keep.ratio ?? drop.ratio;
1227
298
  const thinking = keep.thinking ?? drop.thinking;
1228
- return {
299
+ const ctxFrom = keep.contextWindow > 0 ? keep : drop;
300
+ const merged = {
301
+ ...keep,
1229
302
  id: keep.id,
1230
303
  name: keep.name || drop.name || keep.id,
1231
- contextWindow: keep.contextWindow > 0 ? keep.contextWindow : drop.contextWindow,
304
+ contextWindow: ctxFrom.contextWindow,
1232
305
  maxTokens: keep.maxTokens > 0 ? keep.maxTokens : drop.maxTokens,
1233
306
  supportsImages: keep.supportsImages || drop.supportsImages,
1234
307
  ...ratio === void 0 ? {} : { ratio },
1235
308
  ...thinking === void 0 ? {} : { thinking },
1236
309
  ...benefit ? { benefit: true } : {}
1237
310
  };
311
+ if (ctxFrom.contextWindowKnown === true) merged.contextWindowKnown = true;
312
+ else delete merged.contextWindowKnown;
313
+ return merged;
1238
314
  }
1239
- /** a 是否比 b 更值得保留:优先带参数,其次保留大小写更「像注册名」的一条。 */
315
+ /** a 是否比 b 更值得保留:先认「上游真给的上下文窗口」,再比参数,最后比大小写。 */
1240
316
  function richerThan(a, b) {
317
+ const aKnown = a.contextWindowKnown === true;
318
+ if (aKnown !== (b.contextWindowKnown === true)) return aKnown;
1241
319
  if (a.contextWindow > 0 !== b.contextWindow > 0) return a.contextWindow > 0;
1242
320
  if (a.maxTokens > 0 !== b.maxTokens > 0) return a.maxTokens > 0;
1243
321
  return a.id !== a.id.toLowerCase() && b.id === b.id.toLowerCase();
@@ -2808,536 +1886,4 @@ async function claimDailyWelfare(credential, signal) {
2808
1886
  };
2809
1887
  }
2810
1888
  //#endregion
2811
- //#region src/discovery.ts
2812
- /**
2813
- * 动态模型发现:把「已登录账号」变成「当前可用模型清单」。
2814
- *
2815
- * 为什么要单独一层:模型目录是**按账号**授予的(限时福利尤其如此:A 账号有、
2816
- * B 账号没有),而插件对外只暴露一份目录。所以这里逐账号发现、取并集,再把
2817
- * 结果提交给全局目录与福利集合。
2818
- *
2819
- * 失败一律不抛出:拉不到就继续用现有目录(冷启动时是种子清单),把失败原因
2820
- * 带回去给 CLI / 日志展示。真正「不可用」的信号是 0 个账号。
2821
- *
2822
- * @module dsh-codearts/discovery
2823
- */
2824
- /**
2825
- * 逐账号发现并合并(不改全局状态)。
2826
- *
2827
- * @param store 账号文档;逐个 `resolve()` 以拿到已续期的签名材料
2828
- * @param signal 取消信号(宿主关停时用)
2829
- */
2830
- async function discoverModels(store, signal) {
2831
- const ids = await store.ids();
2832
- const accounts = [];
2833
- for (const id of ids) {
2834
- if (signal?.aborted === true) break;
2835
- const summary = (await store.list()).find((account) => account.id === id);
2836
- const label = summary?.label ?? summary?.userName;
2837
- const resolved = await store.resolve(id);
2838
- if (resolved === void 0) {
2839
- accounts.push({
2840
- accountId: id,
2841
- ...label === void 0 ? {} : { label },
2842
- ok: false,
2843
- models: [],
2844
- sources: [],
2845
- errors: [{
2846
- source: "agent",
2847
- message: "credential unavailable (sign in again)"
2848
- }]
2849
- });
2850
- continue;
2851
- }
2852
- try {
2853
- const result = await fetchModels(resolved, signal);
2854
- accounts.push({
2855
- accountId: id,
2856
- ...label === void 0 ? {} : { label },
2857
- ok: true,
2858
- models: result.models,
2859
- sources: result.sources,
2860
- errors: result.errors
2861
- });
2862
- } catch (error) {
2863
- accounts.push({
2864
- accountId: id,
2865
- ...label === void 0 ? {} : { label },
2866
- ok: false,
2867
- models: [],
2868
- sources: [],
2869
- errors: [{
2870
- source: "agent",
2871
- message: error instanceof Error ? error.message : String(error)
2872
- }]
2873
- });
2874
- }
2875
- }
2876
- const ok = accounts.filter((account) => account.ok);
2877
- return {
2878
- models: mergeModelLists(ok.map((account) => account.models)),
2879
- accounts,
2880
- anySucceeded: ok.length > 0
2881
- };
2882
- }
2883
- /**
2884
- * 发现并**提交**到全局目录:目录内容 + 福利集合。
2885
- *
2886
- * @returns 提交后的目录;没有任何账号成功时返回 `undefined`(调用方保留原目录)
2887
- */
2888
- async function refreshCatalog(store, catalog, signal) {
2889
- const outcome = await discoverModels(store, signal);
2890
- if (!outcome.anySucceeded || outcome.models.length === 0) return outcome;
2891
- setDiscoveredBenefitModels(outcome.models.filter((model) => model.benefit === true).map((model) => model.id));
2892
- catalog.set(outcome.models.map((model) => {
2893
- const benefit = isBenefitModel(model.id);
2894
- return {
2895
- ...model,
2896
- name: modelDisplayName(model.name, benefit, model.ratio)
2897
- };
2898
- }));
2899
- return outcome;
2900
- }
2901
- //#endregion
2902
- //#region src/usage.ts
2903
- /**
2904
- * 用量账本:把聊天流里的 usage 帧累计成「今天用了多少」。
2905
- *
2906
- * 为什么还要自己记:账号总额度有积分接口了(见 credits.ts,2026-10 从官方 Agent
2907
- * 客户端挖出并实测通过),但**本机经插件发出的请求**仍需自己累计 —— 上游不按
2908
- * 「这台机器」维度给统计。能拿到的真实数据有三样:
2909
- * 1. 每个请求的 token `usage`(上游在流末尾回一帧 `{choices:[],usage:{...}}`);
2910
- * 2. 插件自己知道的账号会话槽位占用(见 account-pool:每账号 3 个并发会话);
2911
- * 3. 账号积分/额度(见 credits.ts)。
2912
- *
2913
- * 所以这里累计的是**本机经插件发出的请求**,与卡片上的积分区块互补 —— 一个是本机
2914
- * 级、一个是账号级。官方额度明细在 `codearts.huaweicloud.com/portal/settings/personal-usage`。
2915
- *
2916
- * 落盘在 `$DSH_HOME/.codearts-usage.json`,按天存,保留最近 `RETENTION_DAYS` 天。
2917
- *
2918
- * @module dsh-codearts/usage
2919
- */
2920
- /** 用量账本路径:与账号文档同一层(`$DSH_HOME` 或 `~/.dsh`)。 */
2921
- function codeartsUsagePath(home) {
2922
- const base = home ?? process.env.DSH_HOME ?? join(homedir(), ".dsh");
2923
- return join(base, ".codearts-usage.json");
2924
- }
2925
- /** 首字延迟分桶的上界(毫秒);落进最后一档表示「超过 30 秒」。 */
2926
- const TTFT_BUCKETS_MS = [
2927
- 200,
2928
- 500,
2929
- 1e3,
2930
- 2e3,
2931
- 3e3,
2932
- 5e3,
2933
- 8e3,
2934
- 12e3,
2935
- 2e4,
2936
- 3e4
2937
- ];
2938
- /** 直方图桶数(含溢出档)。 */
2939
- const TTFT_BUCKET_COUNT = TTFT_BUCKETS_MS.length + 1;
2940
- function emptyTotals() {
2941
- return {
2942
- requests: 0,
2943
- promptTokens: 0,
2944
- completionTokens: 0,
2945
- totalTokens: 0,
2946
- cachedTokens: 0,
2947
- reasoningTokens: 0
2948
- };
2949
- }
2950
- function addTotals(into, add) {
2951
- into.requests += add.requests ?? 0;
2952
- into.promptTokens += add.promptTokens ?? 0;
2953
- into.completionTokens += add.completionTokens ?? 0;
2954
- into.totalTokens += add.totalTokens ?? 0;
2955
- into.cachedTokens += add.cachedTokens ?? 0;
2956
- into.reasoningTokens += add.reasoningTokens ?? 0;
2957
- }
2958
- function mergeTotals(into, from) {
2959
- addTotals(into, from);
2960
- }
2961
- /** 本地日期键 YYYY-MM-DD(不用 toISOString:那是 UTC,会把跨零点的用量算到前一天)。 */
2962
- function localDateKey(at = Date.now()) {
2963
- const d = new Date(at);
2964
- const p = (n) => String(n).padStart(2, "0");
2965
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
2966
- }
2967
- /** 本地小时键 `00`..`23`(同样按本地时间切,跨零点的那一小时不会错位)。 */
2968
- function localHourKey(at = Date.now()) {
2969
- return localHourKeyOfHour(new Date(at).getHours());
2970
- }
2971
- /** 0..23 -> `00`..`23`(小时桶的键)。 */
2972
- function localHourKeyOfHour(hour) {
2973
- return String(hour).padStart(2, "0");
2974
- }
2975
- function positiveInt(value) {
2976
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
2977
- }
2978
- /**
2979
- * 从上游 usage 帧里取缓存命中数。
2980
- *
2981
- * 位置见过两种:OpenAI 的 `prompt_tokens_details.cached_tokens`,以及兼容层直接
2982
- * 平铺在顶层的几种别名。取第一个能读到的。缓存输入必然是输入的子集,所以比
2983
- * `promptTokens` 还大的脏数据直接钳掉 —— 否则界面上会出现 >100% 的命中率。
2984
- */
2985
- function cachedTokensOf(raw, promptTokens) {
2986
- if (promptTokens <= 0) return 0;
2987
- const cached = positiveInt(nestedField(raw.prompt_tokens_details, "cached_tokens") ?? raw.cached_tokens ?? raw.cache_tokens ?? raw.prompt_cache_hit_tokens);
2988
- return Math.min(cached, promptTokens);
2989
- }
2990
- /**
2991
- * 从上游 usage 帧里取思考 token。
2992
- *
2993
- * 口径与 {@link cachedTokensOf} 对称:嵌套 `completion_tokens_details.reasoning_tokens`
2994
- * 优先,顶层 `reasoning_tokens` 兜底,超过输出总量就钳掉(它含在输出里)。
2995
- */
2996
- function reasoningTokensOf(raw, completionTokens) {
2997
- if (completionTokens <= 0) return 0;
2998
- const reasoning = positiveInt(nestedField(raw.completion_tokens_details, "reasoning_tokens") ?? raw.reasoning_tokens);
2999
- return Math.min(reasoning, completionTokens);
3000
- }
3001
- /** 读 `*_tokens_details` 这类嵌套对象里的一个字段;不是对象(或缺字段)给 undefined。 */
3002
- function nestedField(details, key) {
3003
- return typeof details === "object" && details !== null ? details[key] : void 0;
3004
- }
3005
- /** 从上游 usage 帧里取计数(缺哪个算 0,total 缺失时用 prompt+completion 兜底)。 */
3006
- function normalizeUsage(raw) {
3007
- if (raw === void 0) return {
3008
- promptTokens: 0,
3009
- completionTokens: 0,
3010
- totalTokens: 0,
3011
- cachedTokens: 0,
3012
- reasoningTokens: 0
3013
- };
3014
- const promptTokens = positiveInt(raw.prompt_tokens);
3015
- const completionTokens = positiveInt(raw.completion_tokens);
3016
- const total = positiveInt(raw.total_tokens);
3017
- return {
3018
- promptTokens,
3019
- completionTokens,
3020
- totalTokens: total > 0 ? total : promptTokens + completionTokens,
3021
- cachedTokens: cachedTokensOf(raw, promptTokens),
3022
- reasoningTokens: reasoningTokensOf(raw, completionTokens)
3023
- };
3024
- }
3025
- /** 读一项累计值,缺字段(旧账本没有 cachedTokens / reasoningTokens)就按 0 补齐。 */
3026
- function normalizeTotals(raw) {
3027
- return {
3028
- requests: positiveInt(raw?.requests),
3029
- promptTokens: positiveInt(raw?.promptTokens),
3030
- completionTokens: positiveInt(raw?.completionTokens),
3031
- totalTokens: positiveInt(raw?.totalTokens),
3032
- cachedTokens: positiveInt(raw?.cachedTokens),
3033
- reasoningTokens: positiveInt(raw?.reasoningTokens)
3034
- };
3035
- }
3036
- /** 整张「模型/账号 -> 累计」表补齐字段。 */
3037
- function normalizeStore(store) {
3038
- const out = {};
3039
- for (const [key, totals] of Object.entries(store ?? {})) {
3040
- if (typeof totals !== "object" || totals === null) continue;
3041
- out[key] = normalizeTotals(totals);
3042
- }
3043
- return out;
3044
- }
3045
- /** 计数表(失败类别 / 账号失败数)补齐:只留正数,空表给 undefined。 */
3046
- function normalizeCounts(raw) {
3047
- if (typeof raw !== "object" || raw === null) return void 0;
3048
- const out = {};
3049
- for (const [key, value] of Object.entries(raw)) {
3050
- const count = positiveInt(value);
3051
- if (count > 0) out[key] = count;
3052
- }
3053
- return Object.keys(out).length === 0 ? void 0 : out;
3054
- }
3055
- /** 首字延迟直方图补齐到固定桶数;旧账本/脏数组一律按空表。 */
3056
- function normalizeBuckets(raw) {
3057
- if (!Array.isArray(raw)) return void 0;
3058
- const out = Array.from({ length: TTFT_BUCKET_COUNT }, (_, index) => positiveInt(raw[index]));
3059
- return out.some((count) => count > 0) ? out : void 0;
3060
- }
3061
- /**
3062
- * 用量账本。
3063
- *
3064
- * 记账分两步,因为一次请求可能只有其一:
3065
- * - `noteRequest()` 在请求发出时调用(拿不到 usage 的流也要计入请求数);
3066
- * - `noteUsage()` 在收到 usage 帧时调用(补 token 数)。
3067
- */
3068
- var CodeArtsUsageTracker = class {
3069
- days = /* @__PURE__ */ new Map();
3070
- lastAt;
3071
- loaded = false;
3072
- loading;
3073
- saveTimer;
3074
- saving = Promise.resolve();
3075
- path;
3076
- now;
3077
- saveDebounceMs;
3078
- constructor(options = {}) {
3079
- this.path = options.path;
3080
- this.now = options.now ?? (() => Date.now());
3081
- this.saveDebounceMs = options.saveDebounceMs ?? 2e3;
3082
- }
3083
- /** 读账本(懒加载,只读一次)。 */
3084
- async load() {
3085
- this.loading ??= this.readFile();
3086
- return this.loading;
3087
- }
3088
- async readFile() {
3089
- if (this.loaded || this.path === void 0 || !existsSync(this.path)) {
3090
- this.loaded = true;
3091
- return;
3092
- }
3093
- try {
3094
- const raw = await readFile(this.path, "utf8");
3095
- const parsed = JSON.parse(raw);
3096
- if (parsed.version !== 1 || typeof parsed.days !== "object" || parsed.days === null) return;
3097
- for (const [date, day] of Object.entries(parsed.days)) {
3098
- if (typeof day !== "object" || day === null) continue;
3099
- const stored = day;
3100
- const restored = {
3101
- models: normalizeStore(stored.models),
3102
- accounts: normalizeStore(stored.accounts)
3103
- };
3104
- if (stored.hours !== void 0) restored.hours = normalizeStore(stored.hours);
3105
- const failures = normalizeCounts(stored.failures);
3106
- if (failures !== void 0) restored.failures = failures;
3107
- const failuresByAccount = normalizeCounts(stored.failuresByAccount);
3108
- if (failuresByAccount !== void 0) restored.failuresByAccount = failuresByAccount;
3109
- const ttft = normalizeBuckets(stored.ttft);
3110
- if (ttft !== void 0) restored.ttft = ttft;
3111
- this.days.set(date, restored);
3112
- }
3113
- this.prune(this.now());
3114
- } catch {
3115
- this.days.clear();
3116
- } finally {
3117
- this.loaded = true;
3118
- }
3119
- }
3120
- day(dateKey) {
3121
- let day = this.days.get(dateKey);
3122
- if (day === void 0) {
3123
- day = {
3124
- models: {},
3125
- accounts: {}
3126
- };
3127
- this.days.set(dateKey, day);
3128
- }
3129
- return day;
3130
- }
3131
- bucket(store, key) {
3132
- let totals = store[key];
3133
- if (totals === void 0) {
3134
- totals = emptyTotals();
3135
- store[key] = totals;
3136
- }
3137
- return totals;
3138
- }
3139
- /** 记一次请求(不等到 usage 帧)。 */
3140
- noteRequest(accountId, model, at = this.now()) {
3141
- const day = this.day(localDateKey(at));
3142
- addTotals(this.bucket(day.models, model), { requests: 1 });
3143
- addTotals(this.bucket(day.accounts, accountId), { requests: 1 });
3144
- addTotals(this.bucket(this.hoursOf(day), localHourKey(at)), { requests: 1 });
3145
- this.lastAt = at;
3146
- this.prune(at);
3147
- this.scheduleSave();
3148
- }
3149
- /** 记一次 usage 帧。 */
3150
- noteUsage(accountId, model, raw, at = this.now()) {
3151
- const usage = normalizeUsage(raw);
3152
- if (usage.totalTokens === 0 && usage.promptTokens === 0 && usage.completionTokens === 0) return;
3153
- const day = this.day(localDateKey(at));
3154
- addTotals(this.bucket(day.models, model), usage);
3155
- addTotals(this.bucket(day.accounts, accountId), usage);
3156
- addTotals(this.bucket(this.hoursOf(day), localHourKey(at)), usage);
3157
- this.lastAt = at;
3158
- this.prune(at);
3159
- this.scheduleSave();
3160
- }
3161
- /** 一天里的逐小时桶,第一次写的时候才建(老账本没有这个键)。 */
3162
- hoursOf(day) {
3163
- day.hours ??= {};
3164
- return day.hours;
3165
- }
3166
- /**
3167
- * 记一次失败请求。
3168
- *
3169
- * 只在「这次请求最终回给用户一个错误」时调用一次 —— 插件内部换号重试不算失败,
3170
- * 否则一个排队重试就能把失败率刷成好几倍。`kind` 用 shim 的失败出口标识。
3171
- */
3172
- noteFailure(kind, accountId, at = this.now()) {
3173
- if (kind === "") return;
3174
- const day = this.day(localDateKey(at));
3175
- day.failures ??= {};
3176
- day.failures[kind] = (day.failures[kind] ?? 0) + 1;
3177
- if (accountId !== void 0 && accountId !== "") {
3178
- day.failuresByAccount ??= {};
3179
- day.failuresByAccount[accountId] = (day.failuresByAccount[accountId] ?? 0) + 1;
3180
- }
3181
- this.lastAt = at;
3182
- this.prune(at);
3183
- this.scheduleSave();
3184
- }
3185
- /**
3186
- * 记一次首字延迟(毫秒),落进直方图。
3187
- *
3188
- * 从请求进入 shim 算起,到上游第一帧真的写给 DSH 为止 —— 排队和换号的时间都算进去,
3189
- * 因为那正是用户盯着转圈等掉的时长。
3190
- */
3191
- noteLatency(ms, at = this.now()) {
3192
- if (!Number.isFinite(ms) || ms < 0) return;
3193
- const day = this.day(localDateKey(at));
3194
- day.ttft ??= new Array(TTFT_BUCKET_COUNT).fill(0);
3195
- let index = TTFT_BUCKETS_MS.findIndex((limit) => ms <= limit);
3196
- if (index < 0) index = TTFT_BUCKET_COUNT - 1;
3197
- day.ttft[index] += 1;
3198
- this.lastAt = at;
3199
- this.prune(at);
3200
- this.scheduleSave();
3201
- }
3202
- /**
3203
- * 丢弃保留期之外的天(按日期键比较即可,YYYY-MM-DD 是字典序)。
3204
- *
3205
- * 顺带把两天之前的**小时桶**清掉:逐小时数据只有「今天按小时」在画,留着只是
3206
- * 让 60 天的账本多出一个数量级的体积。
3207
- */
3208
- prune(at) {
3209
- if (this.days.size === 0) return;
3210
- const cutoff = localDateKey(at - 5184e6);
3211
- const hourCutoff = localDateKey(at - 1728e5);
3212
- for (const [date, day] of [...this.days.entries()]) if (date < cutoff) this.days.delete(date);
3213
- else if (date < hourCutoff && day.hours !== void 0) delete day.hours;
3214
- }
3215
- /** 当前快照(卡片与 CLI 都读它)。 */
3216
- snapshot(at = this.now()) {
3217
- const todayKey = localDateKey(at);
3218
- const today = this.days.get(todayKey);
3219
- const cutoff = localDateKey(at - 2592e6);
3220
- const allTime = emptyTotals();
3221
- const last30 = emptyTotals();
3222
- for (const [date, day] of this.days) for (const totals of Object.values(day.models)) {
3223
- mergeTotals(allTime, totals);
3224
- if (date >= cutoff) mergeTotals(last30, totals);
3225
- }
3226
- const models = today?.models ?? {};
3227
- const failuresByKind = today?.failures ?? {};
3228
- const ttft = today?.ttft ?? [];
3229
- const p50 = percentileOf(ttft, .5);
3230
- const p95 = percentileOf(ttft, .95);
3231
- return {
3232
- today: {
3233
- ...emptyTotals(),
3234
- ...today === void 0 ? {} : sumOf(models)
3235
- },
3236
- allTime,
3237
- last30,
3238
- failuresToday: {
3239
- total: Object.values(failuresByKind).reduce((sum, count) => sum + count, 0),
3240
- byKind: { ...failuresByKind }
3241
- },
3242
- failuresByAccountToday: { ...today?.failuresByAccount ?? {} },
3243
- latencyToday: {
3244
- samples: ttft.reduce((sum, count) => sum + count, 0),
3245
- ...p50.value === void 0 ? {} : { p50: p50.value },
3246
- ...p95.value === void 0 ? {} : { p95: p95.value },
3247
- overflow: p95.overflow
3248
- },
3249
- byModelToday: Object.entries(models).map(([id, totals]) => ({
3250
- id,
3251
- totals: { ...totals }
3252
- })).sort((a, b) => b.totals.totalTokens - a.totals.totalTokens || (a.id < b.id ? -1 : 1)),
3253
- byAccountToday: Object.fromEntries(Object.entries(today?.accounts ?? {}).map(([id, totals]) => [id, { ...totals }])),
3254
- days: this.days.size,
3255
- recentDays: this.recentDaysOf(at),
3256
- todayByHour: this.todayByHourOf(today, at),
3257
- ...this.lastAt === void 0 ? {} : { lastAt: this.lastAt }
3258
- };
3259
- }
3260
- /** 最近 TREND_DAYS 天的每日合计(按日期升序,缺账目的日子补 0)。 */
3261
- recentDaysOf(at) {
3262
- const out = [];
3263
- for (let back = 34; back >= 0; back -= 1) {
3264
- const date = localDateKey(at - back * 864e5);
3265
- const day = this.days.get(date);
3266
- out.push({
3267
- date,
3268
- totals: day === void 0 ? emptyTotals() : sumOf(day.models)
3269
- });
3270
- }
3271
- return out;
3272
- }
3273
- /** 今天 0 点起的 24 个钟点(还没到的小时补 0,横轴才有固定的 24 格)。 */
3274
- todayByHourOf(today, at) {
3275
- const hours = today?.hours ?? {};
3276
- const currentHour = new Date(at).getHours();
3277
- return Array.from({ length: 24 }, (_, hour) => {
3278
- const totals = hours[localHourKeyOfHour(hour)];
3279
- return {
3280
- hour,
3281
- totals: hour > currentHour || totals === void 0 ? emptyTotals() : { ...totals }
3282
- };
3283
- });
3284
- }
3285
- scheduleSave() {
3286
- if (this.path === void 0) return;
3287
- if (this.saveTimer !== void 0) return;
3288
- this.saveTimer = setTimeout(() => {
3289
- this.saveTimer = void 0;
3290
- this.save();
3291
- }, this.saveDebounceMs);
3292
- this.saveTimer.unref?.();
3293
- }
3294
- /** 立即落盘(关停时调用,别丢最后几秒的账)。 */
3295
- async flush() {
3296
- if (this.saveTimer !== void 0) {
3297
- clearTimeout(this.saveTimer);
3298
- this.saveTimer = void 0;
3299
- }
3300
- await this.save();
3301
- }
3302
- save() {
3303
- if (this.path === void 0) return Promise.resolve();
3304
- const doc = {
3305
- version: 1,
3306
- days: Object.fromEntries(this.days)
3307
- };
3308
- this.saving = this.saving.then(() => writeJsonAtomic(this.path, doc), () => writeJsonAtomic(this.path, doc));
3309
- return this.saving;
3310
- }
3311
- };
3312
- /** 一批桶的合计。 */
3313
- function sumOf(store) {
3314
- const out = emptyTotals();
3315
- for (const totals of Object.values(store)) mergeTotals(out, totals);
3316
- return out;
3317
- }
3318
- /**
3319
- * 直方图分位。
3320
- *
3321
- * 返回的是「落进的那一档的上界」而不是精确毫秒 —— 界面上显示 `≤200ms` 这种口径,
3322
- * 比伪造一个精确值诚实。落进溢出档时 `value` 缺省、`overflow` 为真。
3323
- */
3324
- function percentileOf(buckets, ratio) {
3325
- const total = buckets.reduce((sum, count) => sum + count, 0);
3326
- if (total === 0) return { overflow: false };
3327
- const target = Math.ceil(total * ratio);
3328
- let seen = 0;
3329
- for (let index = 0; index < buckets.length; index += 1) {
3330
- seen += buckets[index] ?? 0;
3331
- if (seen < target) continue;
3332
- return index < TTFT_BUCKETS_MS.length ? {
3333
- value: TTFT_BUCKETS_MS[index],
3334
- overflow: false
3335
- } : { overflow: true };
3336
- }
3337
- return { overflow: true };
3338
- }
3339
- //#endregion
3340
- //#region src/version.ts
3341
- const CODEARTS_VERSION = "1.2.13";
3342
- //#endregion
3343
- export { signedGet as A, markModelUnavailable as B, isTpmLimit as C, pickDailyWelfareCampaign as D, modelUnavailableReasonText as E, creditRatioLabel as F, codeartsAccountsPath as G, CodeArtsAccountStore as H, filterEnabledModels as I, startLogin as J, codeartsAuthPath as K, forgetModelUnavailable as L, CodeArtsCatalog as M, FALLBACK_CODEARTS_MODELS as N, prepareChatBody as O, clearBenefitBlocked as P, isBenefitBlocked as R, isQueueableRate as S, maxTokensCeilingFor as T, CodeArtsCredentialStore as U, modelUnavailableReason as V, MANUAL_ACCOUNT_ID as W, isConcurrencyCap as _, refreshCatalog as a, isNotMultimodal as b, chatStream as c, degradeTokenCeiling as d, fetchCallerIdentity as f, firstFrameError as g, fetchWelfareCampaigns as h, discoverModels as i, upstreamErrorMessage as j, rateLimitFrame as k, claimDailyWelfare as l, fetchQueueStatus as m, CodeArtsUsageTracker as n, SNAP_HOST as o, fetchModels as p, credentialFromOAuth as q, codeartsUsagePath as r, canonicalModel as s, CODEARTS_VERSION as t, clearQueueStatus as u, isIamTokenError as v, isWelfareClaimedStatus as w, isParamInvalidFrame as x, isModelNotAccessible as y, isBenefitModel as z };
1889
+ export { clearBenefitBlocked as A, setDiscoveredBenefitModels as B, prepareChatBody as C, upstream_exports as D, upstreamErrorMessage as E, isBenefitModel as F, markModelUnavailable as I, mergeModelLists as L, filterEnabledModels as M, forgetModelUnavailable as N, CodeArtsCatalog as O, isBenefitBlocked as P, modelDisplayName as R, pickDailyWelfareCampaign as S, signedGet as T, isQueueableRate as _, clearQueueStatus as a, maxTokensCeilingFor as b, fetchModels as c, firstFrameError as d, isConcurrencyCap as f, isParamInvalidFrame as g, isNotMultimodal as h, claimDailyWelfare as i, creditRatioLabel as j, FALLBACK_CODEARTS_MODELS as k, fetchQueueStatus as l, isModelNotAccessible as m, canonicalModel as n, degradeTokenCeiling as o, isIamTokenError as p, chatStream as r, fetchCallerIdentity as s, SNAP_HOST as t, fetchWelfareCampaigns as u, isTpmLimit as v, rateLimitFrame as w, modelUnavailableReasonText as x, isWelfareClaimedStatus as y, modelUnavailableReason as z };