dsh-codearts 1.4.4 → 1.4.6

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 CHANGED
@@ -3,6 +3,54 @@
3
3
  本文件记录本插件的重要改动。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
4
4
  版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
5
5
 
6
+ ## [1.4.6] - 2026-11-18
7
+
8
+ ### 新增
9
+
10
+ - **企业租户的第三方模型清单**:企业内部专业版由管理员注册的自定义模型,现在也会
11
+ 进入模型目录。发现链路新增一路 `GET /v1/third-party-model/model/list`,先用
12
+ `GET /v1/llm/tenant/settings` 判断租户是否启用第三方模型:未启用的账号不请求清单、
13
+ 也不记错误;只有明确启用后清单失败才上报。与 agent-center 清单重复的模型按现有
14
+ 合并规则去重,输出上限同样兼容 `output_context_window`。
15
+
16
+ ### 修复
17
+
18
+ - **守护进程空窗期不再让凭证裸奔**:插件以前只要看到 keeper 心跳新鲜就完全不
19
+ 自己刷,而 keeper 两轮 tick 之间有 20 分钟空窗 —— 万一下一轮撞上锁忙跳过了,
20
+ 两边就一起不刷,凭证一路走到过期(11-18 凌晨缺 4 轮 tick 那次就是这样)。
21
+ 现在改成「keeper 活着 **且** 下一轮 tick 已经临近」才让路,其余时间插件自己刷,
22
+ 跨进程锁照旧把两边串起来。
23
+
24
+ ## [1.4.5] - 2026-11-18
25
+
26
+ ### 修复
27
+
28
+ - **企业版自定义模型的输出上限不再被压到 8000**(#11):企业内部专业版的模型由
29
+ 管理侧注册为自定义模型,上游把输出上限放在 `model_parameters.output_context_window`、
30
+ 而 `max_tokens` 留 0。插件以前只读 `max_tokens`,这类模型的 `maxTokens` 全部落到
31
+ 8000 兜底,长回答在 8K token 处被截断。现在 `max_tokens` 为 0 时退回读
32
+ `output_context_window`,随后仍按该模型的实测上限钳制(声明 100000 会被钳到
33
+ 65536);内置模型与福利模型的取值不变。
34
+ - **续期不再把两个账号同时刷死**:插件的保活循环和守护进程 keeper 会各自拿同一份
35
+ `refresh_token` 去换新令牌,而 CodeArts 的 refresh_token 是一次性的 —— 谁后到
36
+ 谁收到 `HTTP 400 STS5.1806 invalid refresh token: 'the refresh token has been used'`,
37
+ 两个令牌一起作废,所有账号掉到需要重新登录。现在跨进程用 `.codearts-refresh.lock`
38
+ (PID + 心跳,60ms 轮询抢锁、20s 重申、90s 判僵尸)串行化刷新,拿不到锁的一方
39
+ 直接跳过本轮,等对端写完再读盘。
40
+ - **「refresh token 已用过」不再当场判死**:这条错误以前被当成永久失败,直接把账号
41
+ 标成 `stale` 停在登录页。现在按瞬态处理:先重读磁盘看对端是否已换上新令牌,没换
42
+ 就连续 3 轮(插件侧 3 次独立刷新)才真正判死,期间保持可重试。
43
+ - **PID 探活不再误杀进程**:Windows 上 `process.kill(pid, 0)` 会真的把目标进程
44
+ 干掉(Node 不看信号值,直接 TerminateProcess)。锁文件的僵尸判定与 keeper 的
45
+ `keeperStats()` 探活都踩了这一条 —— 后者每探一次就可能杀掉守护进程,keeper 一死
46
+ 插件就整段时间不再自己续期。现在 Windows 分支改用 `tasklist /FI "PID eq N"` 判定,
47
+ 探活失败按「活着」处理,宁可等心跳超时也不误删。
48
+ - **机器睡眠后 keeper 立即补一轮**:Windows 睡眠会让 20 分钟一次的 `setTimeout`
49
+ 停摆(11-18 凌晨实测有 4 轮 tick 全空,而进程一直活着),期间没有续期。现在加了
50
+ 30 秒看门狗,发现距上次 tick 超过 25 分钟就重排定时器并立刻补跑一轮。
51
+ - **旧版本误标的 `stale` 账号自动复活**:1.3.0 及以前任何一次续期失败(含网络抖动)
52
+ 都会永久落 `stale`;现在重新登录前会先用一次续期复验,成功就直接恢复,不必手动重登。
53
+
6
54
  ## [1.4.4] - 2026-11-17
7
55
 
8
56
  ### 调整
@@ -1,8 +1,9 @@
1
1
  import { createHash, createPrivateKey, createSign, generateKeyPairSync, randomBytes } from "node:crypto";
2
- import { chmod, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
+ import { chmod, mkdir, open, readFile, rename, unlink, utimes, writeFile } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import http from "node:http";
6
+ import { execFileSync } from "node:child_process";
6
7
  //#region src/dpop.ts
7
8
  /**
8
9
  * DPoP(RFC 9449)证明 JWT:ES256 + P-256,供 oauth2/tokens 请求头使用。
@@ -343,6 +344,161 @@ async function startLogin(cfg = defaultLoginConfig()) {
343
344
  close: () => codeCh.server.close()
344
345
  };
345
346
  }
347
+ /** Windows 上探活要起一次 tasklist:超时按毫秒给足,卡住就按「活着」处理。 */
348
+ const PID_PROBE_TIMEOUT_MS = 5e3;
349
+ /** 抢锁的轮询间隔(带上少量抖动,避免两个进程同拍重试)。 */
350
+ const POLL_MS = 60;
351
+ /** 持锁期间的重申间隔:一次续期里超过这个时长没重申,别人就可以认定我们死了。 */
352
+ const RENEW_MS = 2e4;
353
+ /** 锁文件路径:与账号文档同目录,保证同一份凭证只有一个锁。 */
354
+ function refreshLockPath(home) {
355
+ return join(home, ".codearts-refresh.lock");
356
+ }
357
+ const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
358
+ /**
359
+ * 判断某个 pid 是否还活着。
360
+ *
361
+ * **绝不能用 `process.kill(pid, 0)`**:这个技巧只在 POSIX 上成立。Windows 上 Node 的
362
+ * 实现不看信号值,直接用 `TerminateProcess` —— `kill(pid, 0)` 会把那个进程**直接杀掉**
363
+ * (实测:同步执行的两段代码互相探活,持锁那一段被当场干掉,锁一直留到 90 秒超时)。
364
+ * 续期锁要探的正是插件自己或守护进程,杀掉它们就是杀掉登录态本身。
365
+ *
366
+ * 这里改用 Windows 自带的 tasklist 查表;POSIX 上继续用 `kill(pid, 0)`。
367
+ */
368
+ function pidAlive(pid) {
369
+ if (!Number.isInteger(pid) || pid <= 0) return false;
370
+ if (process.platform !== "win32") try {
371
+ process.kill(pid, 0);
372
+ return true;
373
+ } catch (error) {
374
+ return error?.code === "EPERM";
375
+ }
376
+ if (pid === process.pid) return true;
377
+ try {
378
+ const out = execFileSync("tasklist", [
379
+ "/FI",
380
+ `PID eq ${pid}`,
381
+ "/NH"
382
+ ], {
383
+ encoding: "utf8",
384
+ stdio: [
385
+ "ignore",
386
+ "pipe",
387
+ "ignore"
388
+ ],
389
+ timeout: PID_PROBE_TIMEOUT_MS,
390
+ windowsHide: true
391
+ });
392
+ return /\b\d+/.test(out) && out.includes(String(pid));
393
+ } catch {
394
+ return true;
395
+ }
396
+ }
397
+ /** 读锁文件;读不到/内容坏掉都返回 undefined(坏锁当成「可以清掉」)。 */
398
+ async function readLock(path) {
399
+ try {
400
+ const parsed = JSON.parse(await readFile(path, "utf8"));
401
+ if (typeof parsed.pid === "number" && typeof parsed.at === "number") return {
402
+ pid: parsed.pid,
403
+ at: parsed.at
404
+ };
405
+ } catch {}
406
+ }
407
+ /**
408
+ * 这个锁还能不能算数。
409
+ *
410
+ * pid 复用是 Windows 上的真实风险:被 kill 的进程留下的 pid 很快会分给新进程,
411
+ * 只看 `pidAlive` 会把死锁当成活锁,永远抢不到。所以「pid 还活着」也要配上
412
+ * `at` 在合理范围内才算活着。
413
+ */
414
+ function isStale(lock, now) {
415
+ if (now - lock.at > 9e4) return true;
416
+ return !pidAlive(lock.pid);
417
+ }
418
+ /**
419
+ * 清掉一个陈旧锁。
420
+ *
421
+ * 删之前重读一次内容、和刚才判定时逐字段比对:中间可能有人刚抢到新锁,
422
+ * 那就不许删(删了会让两个进程同时持锁,比不加锁更糟)。
423
+ */
424
+ async function breakStale(path, seen) {
425
+ const now = await readLock(path);
426
+ if (now !== void 0 && seen !== void 0 && (now.pid !== seen.pid || now.at !== seen.at)) return;
427
+ try {
428
+ await unlink(path);
429
+ } catch {}
430
+ }
431
+ /**
432
+ * 抢锁。拿到了返回释放函数,等不到返回 undefined。
433
+ *
434
+ * 调用方**必须**在 `finally` 里释放(或依赖它自己超时 —— 不释放只是让别人多等
435
+ * 一个 `REFRESH_LOCK_STALE_MS`,不会把锁永久卡死)。
436
+ */
437
+ async function acquireRefreshLock(path, options = {}) {
438
+ const now = options.now ?? Date.now;
439
+ const deadline = now() + (options.waitMs ?? 2e4);
440
+ for (;;) {
441
+ const payload = {
442
+ pid: process.pid,
443
+ at: now()
444
+ };
445
+ let handle;
446
+ try {
447
+ handle = await open(path, "wx", 384);
448
+ await handle.writeFile(JSON.stringify(payload));
449
+ await handle.close();
450
+ handle = void 0;
451
+ return releaser(path, payload);
452
+ } catch (error) {
453
+ await handle?.close().catch(() => {});
454
+ if (error?.code !== "EEXIST") return;
455
+ }
456
+ const held = await readLock(path);
457
+ if (held === void 0 || isStale(held, now())) {
458
+ await breakStale(path, held);
459
+ continue;
460
+ }
461
+ if (now() >= deadline) return void 0;
462
+ await sleep$1(POLL_MS + Math.floor(Math.random() * POLL_MS));
463
+ }
464
+ }
465
+ function releaser(path, payload) {
466
+ let released = false;
467
+ const renew = setInterval(() => {
468
+ if (released) return;
469
+ payload.at = Date.now();
470
+ writeFile(path, JSON.stringify(payload), { mode: 384 }).then(() => utimes(path, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date())).catch(() => {});
471
+ }, RENEW_MS);
472
+ renew.unref?.();
473
+ return async () => {
474
+ if (released) return;
475
+ released = true;
476
+ clearInterval(renew);
477
+ const now_ = await readLock(path);
478
+ if (now_ !== void 0 && now_.pid !== payload.pid) return;
479
+ try {
480
+ await unlink(path);
481
+ } catch {}
482
+ };
483
+ }
484
+ /**
485
+ * 拿着锁做一件事。
486
+ *
487
+ * 拿不到锁返回 `undefined` —— 调用方据此知道「这一轮没轮到我们,什么都不用做」,
488
+ * 而不是把「没刷成」当成「刷新失败」(后者会误判 stale)。
489
+ */
490
+ async function withRefreshLock(path, fn, options = {}) {
491
+ const release = await acquireRefreshLock(path, options);
492
+ if (release === void 0) {
493
+ options.onBusy?.();
494
+ return;
495
+ }
496
+ try {
497
+ return await fn();
498
+ } finally {
499
+ await release();
500
+ }
501
+ }
346
502
  //#endregion
347
503
  //#region src/auth.ts
348
504
  /**
@@ -428,7 +584,7 @@ async function clearCredential(path) {
428
584
  async function claimIfPossible(cred) {
429
585
  if (!cred.accessKeyId || !cred.secretAccessKey) return;
430
586
  try {
431
- const { claimBenefit } = await import("./upstream-BV4XWB4l.mjs").then((n) => n.P);
587
+ const { claimBenefit } = await import("./upstream-COqsw56c.mjs").then((n) => n.P);
432
588
  await claimBenefit({
433
589
  token: cred.token,
434
590
  accessKeyId: cred.accessKeyId,
@@ -467,6 +623,15 @@ const REFRESH_RETRY_BASE_MS = 250;
467
623
  * 一次性 refresh_token 反复烧掉,把「暂时失败」放大成「真的失效」。
468
624
  */
469
625
  const REFRESH_TRANSIENT_BLOCK_MS = 6e4;
626
+ /**
627
+ * `STS5.1806`(refresh_token 已被用掉)连续撞上几次才判死。
628
+ *
629
+ * 这个码本身**不能**证明凭证坏了:另一个写入方(守护进程)恰好先用掉了同一个令牌,
630
+ * 撞上的这一方手里拿的就是旧值。绝大多数情况下下一轮重读磁盘就能拿到新令牌。
631
+ * 连续 3 次、每次之间隔一个瞬时冷却还都是这个结果,才算真的没救了 ——
632
+ * 早先一次就判死,2026-11-18 00:06 两个号同时被误杀(见 `refresh-lock.ts` 的说明)。
633
+ */
634
+ const REFRESH_USED_MAX_STREAK = 3;
470
635
  /** 失败是不是「凭证真的没了」;只有这一类才允许写 `stale`。 */
471
636
  function isPermanentRefreshFailure(error) {
472
637
  return error instanceof OAuthTokenError && error.permanent;
@@ -722,14 +887,19 @@ var AccountSlot = class {
722
887
  _gen = 0;
723
888
  persist;
724
889
  log;
890
+ /** 跨进程续期锁的路径(由 store 注入;单凭证时代用默认目录)。 */
891
+ lockPath;
725
892
  /** 瞬时失败后的冷却:这之前不再拿 refresh_token 去撞上游。 */
726
893
  _refreshBlockedUntil = 0;
727
894
  /** 最近一次续期失败的类型,供 store 判断要不要「重读磁盘再试一次」。 */
728
895
  _lastFailure;
729
- constructor(cred, persist, log) {
896
+ /** `STS5.1806` 连续撞了几次(成功一次就清零);见 `REFRESH_USED_MAX_STREAK`。 */
897
+ _usedStreak = 0;
898
+ constructor(cred, persist, log, lockPath) {
730
899
  this._cred = cred;
731
900
  this.persist = persist;
732
901
  this.log = log;
902
+ this.lockPath = lockPath ?? refreshLockPath(dirname(codeartsAccountsPath()));
733
903
  }
734
904
  get credential() {
735
905
  return this._cred;
@@ -738,6 +908,17 @@ var AccountSlot = class {
738
908
  get lastFailure() {
739
909
  return this._lastFailure;
740
910
  }
911
+ /**
912
+ * 这一份凭证是不是真的完了。
913
+ *
914
+ * `_lastFailure === 'used'` 只代表「这一趟撞上了已用过的令牌」,还要看连续撞了几次:
915
+ * 一两次是并发轮换的正常现象,重读磁盘就能恢复。
916
+ */
917
+ get exhausted() {
918
+ if (this._cred.stale === true) return true;
919
+ if (this._lastFailure === "permanent") return true;
920
+ return this._lastFailure === "used" && this._usedStreak >= REFRESH_USED_MAX_STREAK;
921
+ }
741
922
  /** 把这份凭证标成 stale 并落库(store 在「令牌被别人用掉且磁盘也没有更新」时调)。 */
742
923
  async markStale() {
743
924
  if (this._cred.stale === true) return;
@@ -791,20 +972,57 @@ var AccountSlot = class {
791
972
  */
792
973
  async verifyStale() {
793
974
  const cred = this._cred;
794
- if (cred.stale !== true) return true;
975
+ if (this._cred.stale === true) {
976
+ if (!cred.refreshToken || !cred.dpopPrivateKey || !cred.clientId) return false;
977
+ if (Date.now() < this._refreshBlockedUntil) return false;
978
+ const outcome = await this.refresh(cred, {
979
+ refreshToken: cred.refreshToken,
980
+ dpopPrivateKey: cred.dpopPrivateKey,
981
+ clientId: cred.clientId
982
+ });
983
+ if (outcome.ok) this._cred = outcome.cred;
984
+ return outcome.ok;
985
+ }
795
986
  if (!cred.refreshToken || !cred.dpopPrivateKey || !cred.clientId) return false;
796
987
  if (Date.now() < this._refreshBlockedUntil) return false;
797
- return (await this.runRefresh(cred)).ok;
988
+ const outcome = await this.refresh(cred, {
989
+ refreshToken: cred.refreshToken,
990
+ dpopPrivateKey: cred.dpopPrivateKey,
991
+ clientId: cred.clientId
992
+ });
993
+ if (outcome.ok) this._cred = outcome.cred;
994
+ return outcome.ok;
798
995
  }
799
- /** 单飞执行一次续期。 */
996
+ /**
997
+ * 单飞执行一次续期,**并在跨进程文件锁里做**。
998
+ *
999
+ * 单飞只挡得住同一进程内的并发;守护进程(`keeper-main.ts`)是另一个进程,
1000
+ * 它和我们各持一份同一个账号的 refresh_token,同时刷必然有一方撞上 `STS5.1806`。
1001
+ * 锁保证「同一时刻只有一个进程拿 refresh_token 去撞上游」。拿不到锁(对方正在刷)
1002
+ * 就当这一轮没轮到我们:不写 stale,只冷却一会儿等下一轮重读磁盘拿它写回的新令牌。
1003
+ */
800
1004
  async runRefresh(cred) {
801
- return this._inflight ??= this.refresh(cred, {
1005
+ return this._inflight ??= this.refreshLocked(cred).finally(() => {
1006
+ this._inflight = void 0;
1007
+ });
1008
+ }
1009
+ async refreshLocked(cred) {
1010
+ const outcome = await withRefreshLock(this.lockPath, () => this.refresh(cred, {
802
1011
  refreshToken: cred.refreshToken ?? "",
803
1012
  dpopPrivateKey: cred.dpopPrivateKey,
804
1013
  clientId: cred.clientId ?? ""
805
- }).finally(() => {
806
- this._inflight = void 0;
807
- });
1014
+ }), { onBusy: () => {
1015
+ this._refreshBlockedUntil = Date.now() + REFRESH_TRANSIENT_BLOCK_MS;
1016
+ this.log?.(`[dsh-codearts] refresh ${cred.label ?? "account"} skipped: another process holds the refresh lock, will reload from disk`);
1017
+ } });
1018
+ if (outcome !== void 0) return outcome;
1019
+ this._refreshBlockedUntil = Date.now() + REFRESH_TRANSIENT_BLOCK_MS;
1020
+ return {
1021
+ ok: false,
1022
+ cred: this._cred,
1023
+ permanent: false,
1024
+ reason: "refresh lock busy"
1025
+ };
808
1026
  }
809
1027
  async refresh(cred, mat) {
810
1028
  const gen = this._gen;
@@ -825,6 +1043,7 @@ var AccountSlot = class {
825
1043
  }), cred.label);
826
1044
  this._refreshBlockedUntil = 0;
827
1045
  this._lastFailure = void 0;
1046
+ this._usedStreak = 0;
828
1047
  if (!stillCurrent()) return {
829
1048
  ok: true,
830
1049
  cred: next
@@ -838,15 +1057,34 @@ var AccountSlot = class {
838
1057
  };
839
1058
  } catch (error) {
840
1059
  lastError = error;
841
- if (isPermanentRefreshFailure(error)) break;
1060
+ if (isPermanentRefreshFailure(error) || isRefreshTokenUsed(error)) break;
842
1061
  this.log?.(`[dsh-codearts] refresh ${cred.label ?? "account"} attempt ${attempt}/${REFRESH_MAX_ATTEMPTS} failed (transient): ${describeRefreshFailure(error)}`);
843
1062
  if (attempt < REFRESH_MAX_ATTEMPTS) await sleep(REFRESH_RETRY_BASE_MS * 2 ** (attempt - 1));
844
1063
  }
845
1064
  const used = isRefreshTokenUsed(lastError);
846
1065
  const permanent = !used && isPermanentRefreshFailure(lastError);
847
1066
  const reason = describeRefreshFailure(lastError);
848
- if (used) this._lastFailure = "used";
849
- else if (permanent) {
1067
+ if (used) {
1068
+ this._usedStreak += 1;
1069
+ this._lastFailure = "used";
1070
+ this._refreshBlockedUntil = Date.now() + REFRESH_TRANSIENT_BLOCK_MS;
1071
+ this.log?.(`[dsh-codearts] refresh ${cred.label ?? "account"} hit a used refresh token (${this._usedStreak}/${REFRESH_USED_MAX_STREAK}), reloading from disk`);
1072
+ if (!stillCurrent()) return {
1073
+ ok: false,
1074
+ cred: this._cred,
1075
+ permanent: false,
1076
+ reason
1077
+ };
1078
+ this._cred = cred;
1079
+ return {
1080
+ ok: false,
1081
+ cred,
1082
+ permanent: false,
1083
+ reason
1084
+ };
1085
+ }
1086
+ this._usedStreak = 0;
1087
+ if (permanent) {
850
1088
  this._lastFailure = "permanent";
851
1089
  cred.stale = true;
852
1090
  } else {
@@ -911,6 +1149,16 @@ var CodeArtsAccountStore = class {
911
1149
  this.legacyPath = legacyPath ?? join(dirname(path), ".codearts-auth.json");
912
1150
  this.log = options.log;
913
1151
  }
1152
+ /**
1153
+ * 所有槽位共用的跨进程续期锁(与守护进程同一个文件)。
1154
+ *
1155
+ * 注意是**整个文档一把锁**,不是每个账号一把:`AccountSlot` 是先刷后整份写回的,
1156
+ * 两个账号同时在刷会让后写的那次把前一个刚轮换出来的 refresh_token 覆盖掉。
1157
+ * 一把锁的代价只是多账号时串行几秒,换来的是不可能互相踩。
1158
+ */
1159
+ slotLockPath() {
1160
+ return refreshLockPath(dirname(this.path));
1161
+ }
914
1162
  async loaded() {
915
1163
  this._loading ??= this.load();
916
1164
  return this._loading;
@@ -938,7 +1186,8 @@ var CodeArtsAccountStore = class {
938
1186
  adopt(doc) {
939
1187
  this._doc = doc;
940
1188
  this._slots.clear();
941
- for (const [id, cred] of Object.entries(doc.accounts)) this._slots.set(id, new AccountSlot(cred, this.persisterFor(id), this.log));
1189
+ const lockPath = this.slotLockPath();
1190
+ for (const [id, cred] of Object.entries(doc.accounts)) this._slots.set(id, new AccountSlot(cred, this.persisterFor(id), this.log, lockPath));
942
1191
  }
943
1192
  persisterFor(id) {
944
1193
  return async (cred) => {
@@ -985,7 +1234,7 @@ var CodeArtsAccountStore = class {
985
1234
  this._slots.get(id)?.invalidate();
986
1235
  doc.accounts[id] = cred;
987
1236
  if (!doc.order.includes(id)) doc.order.push(id);
988
- this._slots.set(id, new AccountSlot(cred, this.persisterFor(id), this.log));
1237
+ this._slots.set(id, new AccountSlot(cred, this.persisterFor(id), this.log, this.slotLockPath()));
989
1238
  await this.persistDoc();
990
1239
  await claimIfPossible(cred);
991
1240
  return id;
@@ -1030,7 +1279,7 @@ var CodeArtsAccountStore = class {
1030
1279
  ...identity.domainId === "" ? {} : { domainId: identity.domainId }
1031
1280
  };
1032
1281
  this._slots.get(id)?.invalidate();
1033
- this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id), this.log));
1282
+ this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id), this.log, this.slotLockPath()));
1034
1283
  await this.persistDoc();
1035
1284
  return "noop";
1036
1285
  }
@@ -1048,7 +1297,7 @@ var CodeArtsAccountStore = class {
1048
1297
  this._slots.get(id)?.invalidate();
1049
1298
  this._slots.delete(id);
1050
1299
  this._slots.get(targetKey)?.invalidate();
1051
- this._slots.set(targetKey, new AccountSlot(doc.accounts[targetKey], this.persisterFor(targetKey), this.log));
1300
+ this._slots.set(targetKey, new AccountSlot(doc.accounts[targetKey], this.persisterFor(targetKey), this.log, this.slotLockPath()));
1052
1301
  await this.persistDoc();
1053
1302
  return target === void 0 ? "moved" : "merged";
1054
1303
  }
@@ -1085,7 +1334,7 @@ var CodeArtsAccountStore = class {
1085
1334
  paused
1086
1335
  };
1087
1336
  this._slots.get(id)?.invalidate();
1088
- this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id), this.log));
1337
+ this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id), this.log, this.slotLockPath()));
1089
1338
  await this.persistDoc();
1090
1339
  return true;
1091
1340
  }
@@ -1100,7 +1349,7 @@ var CodeArtsAccountStore = class {
1100
1349
  pinned
1101
1350
  };
1102
1351
  this._slots.get(id)?.invalidate();
1103
- this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id), this.log));
1352
+ this._slots.set(id, new AccountSlot(doc.accounts[id], this.persisterFor(id), this.log, this.slotLockPath()));
1104
1353
  await this.persistDoc();
1105
1354
  return true;
1106
1355
  }
@@ -1144,11 +1393,8 @@ var CodeArtsAccountStore = class {
1144
1393
  if (await this.reloadIfPeerAdvanced(id)) {
1145
1394
  const retry = this._slots.get(id);
1146
1395
  if (retry !== void 0) cred = await retry.ensureFresh();
1147
- if (retry?.lastFailure === "used") {
1148
- await this.markStale(id);
1149
- cred = this._slots.get(id)?.credential ?? cred;
1150
- }
1151
- } else {
1396
+ }
1397
+ if (this._slots.get(id)?.exhausted === true) {
1152
1398
  await this.markStale(id);
1153
1399
  cred = this._slots.get(id)?.credential ?? cred;
1154
1400
  }
@@ -1177,7 +1423,7 @@ var CodeArtsAccountStore = class {
1177
1423
  slot = this._slots.get(id);
1178
1424
  next = slot === void 0 ? void 0 : await slot.forceRefresh();
1179
1425
  }
1180
- if (next === void 0) await this.markStale(id);
1426
+ if (next === void 0 && this._slots.get(id)?.exhausted === true) await this.markStale(id);
1181
1427
  }
1182
1428
  return next;
1183
1429
  }
@@ -1284,4 +1530,4 @@ var CodeArtsAccountStore = class {
1284
1530
  }
1285
1531
  };
1286
1532
  //#endregion
1287
- export { codeartsAuthPath as a, credentialFromOAuth as c, OAuthTokenError as d, defaultLoginConfig as f, codeartsAccountsPath as i, readAccountDocument as l, startLogin as m, CodeArtsCredentialStore as n, codeartsDebugLogPath as o, refreshToken as p, MANUAL_ACCOUNT_ID as r, codeartsRefreshLogPath as s, CodeArtsAccountStore as t, writeJsonAtomic as u };
1533
+ export { codeartsAuthPath as a, credentialFromOAuth as c, refreshLockPath as d, withRefreshLock as f, startLogin as g, refreshToken as h, codeartsAccountsPath as i, readAccountDocument as l, defaultLoginConfig as m, CodeArtsCredentialStore as n, codeartsDebugLogPath as o, OAuthTokenError as p, MANUAL_ACCOUNT_ID as r, codeartsRefreshLogPath as s, CodeArtsAccountStore as t, writeJsonAtomic as u };
package/lib/bin.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { i as codeartsAccountsPath, t as CodeArtsAccountStore } from "./auth-Cd2SvQIy.mjs";
3
- import { H as isBenefitModel, l as fetchCallerIdentity } from "./upstream-BV4XWB4l.mjs";
4
- import { i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-CHCdx9qJ.mjs";
2
+ import { i as codeartsAccountsPath, t as CodeArtsAccountStore } from "./auth-q6MY-TXM.mjs";
3
+ import { H as isBenefitModel, l as fetchCallerIdentity } from "./upstream-COqsw56c.mjs";
4
+ import { i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-BZuhJ6R9.mjs";
5
5
  import { existsSync, statSync } from "node:fs";
6
6
  //#region src/bin.ts
7
7
  /**
@@ -156,123 +156,123 @@ if (typeof document !== "undefined" && document.querySelector("style[data-plugin
156
156
  document.head.appendChild(tag);
157
157
  }
158
158
  var CodeArtsPluginCard_module_css_default = {
159
- "balanceMeta": "xoziZG_balanceMeta",
160
- "section": "xoziZG_section",
161
- "statCard": "xoziZG_statCard",
162
- "skeleton": "xoziZG_skeleton",
163
- "windowPopoverValue": "xoziZG_windowPopoverValue",
164
- "heatHourCell": "xoziZG_heatHourCell",
159
+ "accountName": "xoziZG_accountName",
160
+ "windowHint": "xoziZG_windowHint",
161
+ "creditRows": "xoziZG_creditRows",
162
+ "windowButton": "xoziZG_windowButton",
163
+ "creditFooter": "xoziZG_creditFooter",
164
+ "skeletonBreath": "xoziZG_skeletonBreath",
165
+ "accountInfo": "xoziZG_accountInfo",
165
166
  "heatLegendChip": "xoziZG_heatLegendChip",
166
- "sectionHead": "xoziZG_sectionHead",
167
- "creditLink": "xoziZG_creditLink",
168
- "groupLabel": "xoziZG_groupLabel",
169
- "usageTipName": "xoziZG_usageTipName",
170
- "accountMenu": "xoziZG_accountMenu",
171
- "expiryRow": "xoziZG_expiryRow",
172
- "accountMenuItem": "xoziZG_accountMenuItem",
173
- "tabPanel": "xoziZG_tabPanel",
174
- "header": "xoziZG_header",
175
- "accountGrid": "xoziZG_accountGrid",
167
+ "area": "xoziZG_area",
168
+ "usageTipRow": "xoziZG_usageTipRow",
169
+ "groupHead": "xoziZG_groupHead",
170
+ "windowAnchor": "xoziZG_windowAnchor",
171
+ "modelTrack": "xoziZG_modelTrack",
172
+ "windowUnit": "xoziZG_windowUnit",
173
+ "heatGrid": "xoziZG_heatGrid",
174
+ "sectionLabel": "xoziZG_sectionLabel",
175
+ "modelMeta": "xoziZG_modelMeta",
176
176
  "creditHint": "xoziZG_creditHint",
177
- "statSub": "xoziZG_statSub",
178
- "heatAxis": "xoziZG_heatAxis",
179
- "windowCaret": "xoziZG_windowCaret",
180
- "windowButtonOpen": "xoziZG_windowButtonOpen",
181
- "windowPopoverRow": "xoziZG_windowPopoverRow",
182
- "choiceTail": "xoziZG_choiceTail",
183
- "accountClearHint": "xoziZG_accountClearHint",
184
177
  "name": "xoziZG_name",
178
+ "usageTip": "xoziZG_usageTip",
179
+ "count": "xoziZG_count",
180
+ "windowRange": "xoziZG_windowRange",
181
+ "sectionHead": "xoziZG_sectionHead",
182
+ "card": "xoziZG_card",
183
+ "choiceTail": "xoziZG_choiceTail",
184
+ "statSub": "xoziZG_statSub",
185
+ "heatLegend": "xoziZG_heatLegend",
186
+ "accountHint": "xoziZG_accountHint",
187
+ "statValue": "xoziZG_statValue",
188
+ "heatHourCell": "xoziZG_heatHourCell",
189
+ "modelCheck": "xoziZG_modelCheck",
185
190
  "usageFill": "xoziZG_usageFill",
186
- "barFill": "xoziZG_barFill",
187
- "windowAnchor": "xoziZG_windowAnchor",
191
+ "windowPopoverHead": "xoziZG_windowPopoverHead",
192
+ "meta": "xoziZG_meta",
193
+ "accountClearHint": "xoziZG_accountClearHint",
194
+ "avatar": "xoziZG_avatar",
195
+ "windowButtonSet": "xoziZG_windowButtonSet",
196
+ "desc": "xoziZG_desc",
197
+ "updated": "xoziZG_updated",
198
+ "windowPopover": "xoziZG_windowPopover",
199
+ "windowInput": "xoziZG_windowInput",
200
+ "modelSpec": "xoziZG_modelSpec",
201
+ "danger": "xoziZG_danger",
202
+ "modelName": "xoziZG_modelName",
203
+ "heatAxisSlot": "xoziZG_heatAxisSlot",
204
+ "check": "xoziZG_check",
205
+ "tabs": "xoziZG_tabs",
206
+ "header": "xoziZG_header",
207
+ "doctorRow": "xoziZG_doctorRow",
208
+ "balanceMeta": "xoziZG_balanceMeta",
209
+ "error": "xoziZG_error",
210
+ "manualSummary": "xoziZG_manualSummary",
211
+ "claimAllRow": "xoziZG_claimAllRow",
212
+ "expiryRow": "xoziZG_expiryRow",
188
213
  "modelRequests": "xoziZG_modelRequests",
214
+ "statusLine": "xoziZG_statusLine",
215
+ "manualForm": "xoziZG_manualForm",
216
+ "accountCard": "xoziZG_accountCard",
217
+ "skeletonRow": "xoziZG_skeletonRow",
218
+ "accountRow": "xoziZG_accountRow",
189
219
  "hint": "xoziZG_hint",
190
- "accountHint": "xoziZG_accountHint",
191
- "modelMeta": "xoziZG_modelMeta",
192
- "accountName": "xoziZG_accountName",
193
- "doctorList": "xoziZG_doctorList",
194
- "tabs": "xoziZG_tabs",
195
- "sectionLabel": "xoziZG_sectionLabel",
196
- "modelTokens": "xoziZG_modelTokens",
197
- "heatGrid": "xoziZG_heatGrid",
198
- "accountRowActions": "xoziZG_accountRowActions",
199
- "creditRow": "xoziZG_creditRow",
220
+ "creditBlock": "xoziZG_creditBlock",
221
+ "usageBar": "xoziZG_usageBar",
222
+ "usageTipSep": "xoziZG_usageTipSep",
223
+ "trendTip": "xoziZG_trendTip",
200
224
  "balanceRow": "xoziZG_balanceRow",
225
+ "balanceUnit": "xoziZG_balanceUnit",
201
226
  "accountMenuAnchor": "xoziZG_accountMenuAnchor",
202
- "statLabel": "xoziZG_statLabel",
203
- "creditRows": "xoziZG_creditRows",
204
- "creditFooter": "xoziZG_creditFooter",
205
- "danger": "xoziZG_danger",
206
- "doctorName": "xoziZG_doctorName",
207
- "fieldLabel": "xoziZG_fieldLabel",
208
- "choiceRow": "xoziZG_choiceRow",
209
- "desc": "xoziZG_desc",
227
+ "accountMenuItem": "xoziZG_accountMenuItem",
210
228
  "modelRow": "xoziZG_modelRow",
211
- "usageTipRow": "xoziZG_usageTipRow",
212
- "windowUnit": "xoziZG_windowUnit",
213
- "error": "xoziZG_error",
214
- "doctorRow": "xoziZG_doctorRow",
215
- "accountClear": "xoziZG_accountClear",
216
229
  "accountToolbar": "xoziZG_accountToolbar",
217
- "heatWeekday": "xoziZG_heatWeekday",
218
- "windowInput": "xoziZG_windowInput",
230
+ "heatAxis": "xoziZG_heatAxis",
231
+ "creditRow": "xoziZG_creditRow",
232
+ "statCard": "xoziZG_statCard",
233
+ "windowButtonOpen": "xoziZG_windowButtonOpen",
219
234
  "modelShare": "xoziZG_modelShare",
220
- "manual": "xoziZG_manual",
221
- "link": "xoziZG_link",
222
- "groupHeadFirst": "xoziZG_groupHeadFirst",
235
+ "statLabel": "xoziZG_statLabel",
223
236
  "modelChart": "xoziZG_modelChart",
224
- "modelCheck": "xoziZG_modelCheck",
225
- "headText": "xoziZG_headText",
226
- "balance": "xoziZG_balance",
227
- "windowPopover": "xoziZG_windowPopover",
228
- "heatCell": "xoziZG_heatCell",
229
- "windowButton": "xoziZG_windowButton",
230
- "count": "xoziZG_count",
231
- "usageTip": "xoziZG_usageTip",
232
- "body": "xoziZG_body",
233
- "modelSpec": "xoziZG_modelSpec",
234
- "statValue": "xoziZG_statValue",
235
- "modelTrack": "xoziZG_modelTrack",
236
237
  "accountEntry": "xoziZG_accountEntry",
237
- "meta": "xoziZG_meta",
238
- "groupHead": "xoziZG_groupHead",
239
- "avatar": "xoziZG_avatar",
240
- "statGrid": "xoziZG_statGrid",
241
- "trendTip": "xoziZG_trendTip",
242
- "heatAxisSlot": "xoziZG_heatAxisSlot",
243
- "accountInfo": "xoziZG_accountInfo",
244
- "usageTipSep": "xoziZG_usageTipSep",
238
+ "heatHours": "xoziZG_heatHours",
239
+ "creditLink": "xoziZG_creditLink",
240
+ "fieldLabel": "xoziZG_fieldLabel",
241
+ "groupLabel": "xoziZG_groupLabel",
242
+ "bar": "xoziZG_bar",
243
+ "body": "xoziZG_body",
244
+ "tabPanel": "xoziZG_tabPanel",
245
+ "accountRowActions": "xoziZG_accountRowActions",
246
+ "windowPopoverRow": "xoziZG_windowPopoverRow",
247
+ "manual": "xoziZG_manual",
248
+ "accountNameRow": "xoziZG_accountNameRow",
249
+ "accountClear": "xoziZG_accountClear",
250
+ "balance": "xoziZG_balance",
251
+ "barFill": "xoziZG_barFill",
252
+ "link": "xoziZG_link",
245
253
  "modelFill": "xoziZG_modelFill",
246
- "statusLine": "xoziZG_statusLine",
247
- "updated": "xoziZG_updated",
248
- "windowButtonSet": "xoziZG_windowButtonSet",
249
- "choices": "xoziZG_choices",
254
+ "accountGrid": "xoziZG_accountGrid",
255
+ "accountMenu": "xoziZG_accountMenu",
256
+ "heatWeekday": "xoziZG_heatWeekday",
257
+ "actions": "xoziZG_actions",
258
+ "modelTokens": "xoziZG_modelTokens",
259
+ "heatCell": "xoziZG_heatCell",
260
+ "section": "xoziZG_section",
250
261
  "windowInputSet": "xoziZG_windowInputSet",
251
- "creditBlock": "xoziZG_creditBlock",
252
- "accountToggle": "xoziZG_accountToggle",
262
+ "choices": "xoziZG_choices",
263
+ "windowPopoverValue": "xoziZG_windowPopoverValue",
264
+ "windowCaret": "xoziZG_windowCaret",
253
265
  "field": "xoziZG_field",
266
+ "doctorName": "xoziZG_doctorName",
267
+ "choiceRow": "xoziZG_choiceRow",
268
+ "headText": "xoziZG_headText",
269
+ "usageTipName": "xoziZG_usageTipName",
270
+ "doctorList": "xoziZG_doctorList",
271
+ "statGrid": "xoziZG_statGrid",
272
+ "accountToggle": "xoziZG_accountToggle",
254
273
  "expiryLabel": "xoziZG_expiryLabel",
255
- "skeletonBreath": "xoziZG_skeletonBreath",
256
- "accountNameRow": "xoziZG_accountNameRow",
257
- "manualSummary": "xoziZG_manualSummary",
258
- "usageBar": "xoziZG_usageBar",
259
- "heatLegend": "xoziZG_heatLegend",
260
- "windowRange": "xoziZG_windowRange",
261
- "accountCard": "xoziZG_accountCard",
262
- "card": "xoziZG_card",
263
- "area": "xoziZG_area",
264
- "heatHours": "xoziZG_heatHours",
265
- "manualForm": "xoziZG_manualForm",
266
- "claimAllRow": "xoziZG_claimAllRow",
267
- "accountRow": "xoziZG_accountRow",
268
- "check": "xoziZG_check",
269
- "balanceUnit": "xoziZG_balanceUnit",
270
- "bar": "xoziZG_bar",
271
- "actions": "xoziZG_actions",
272
- "windowPopoverHead": "xoziZG_windowPopoverHead",
273
- "windowHint": "xoziZG_windowHint",
274
- "modelName": "xoziZG_modelName",
275
- "skeletonRow": "xoziZG_skeletonRow"
274
+ "groupHeadFirst": "xoziZG_groupHeadFirst",
275
+ "skeleton": "xoziZG_skeleton"
276
276
  };
277
277
  //#endregion
278
278
  //#region src/client/CodeArtsPluginCard.tsx
@@ -3289,14 +3289,14 @@ if (typeof document !== "undefined" && document.querySelector("style[data-plugin
3289
3289
  document.head.appendChild(tag);
3290
3290
  }
3291
3291
  var CodeArtsPanel_module_css_default = {
3292
- "title": "Z66cgG_title",
3293
3292
  "back": "Z66cgG_back",
3294
- "head": "Z66cgG_head",
3293
+ "title": "Z66cgG_title",
3295
3294
  "body": "Z66cgG_body",
3296
- "desc": "Z66cgG_desc",
3297
3295
  "page": "Z66cgG_page",
3298
- "backCaret": "Z66cgG_backCaret",
3299
- "icon": "Z66cgG_icon"
3296
+ "icon": "Z66cgG_icon",
3297
+ "desc": "Z66cgG_desc",
3298
+ "head": "Z66cgG_head",
3299
+ "backCaret": "Z66cgG_backCaret"
3300
3300
  };
3301
3301
  //#endregion
3302
3302
  //#region src/client/CodeArtsPanel.tsx
package/lib/index.d.mts CHANGED
@@ -977,7 +977,7 @@ interface CallerIdentity {
977
977
  * 模型清单的来源。前三路是目录本身(任一路失败都不阻断,只有三路全失败才算失败),
978
978
  * `thinking` 只是目录之上的可选增强:它失败时模型照常可用,只是没有思考档位选择器。
979
979
  */
980
- type ModelSource = 'builtin' | 'benefit' | 'agent' | 'thinking';
980
+ type ModelSource = 'builtin' | 'benefit' | 'agent' | 'thirdparty' | 'thinking';
981
981
  interface ModelDiscoveryResult {
982
982
  /** 合并后的清单(已去重、已排序)。 */
983
983
  models: readonly CodeArtsModelInfo[];
@@ -997,10 +997,11 @@ interface CodeArtsQueueStatus {
997
997
  message: string;
998
998
  }
999
999
  /**
1000
- * 动态发现当前账号可用的模型清单(三路合并)。
1000
+ * 动态发现当前账号可用的模型清单(四路合并)。
1001
1001
  *
1002
- * 与 codearts2api 的 `Client.FetchModels` 等价:内置、限时福利、agent-center 三路
1003
- * 各自独立,任一路失败只记进 `errors` 不阻断 —— 福利网关抖动时仍能拿到内置模型。
1002
+ * 内置、限时福利、agent-center、企业第三方模型四路各自独立,任一路失败只记进
1003
+ * `errors` 不阻断 —— 福利网关抖动时仍能拿到内置模型。第三方模型那一路有门禁:
1004
+ * 租户未启用时返回空且不算来源(见 `fetchThirdPartyModels`)。
1004
1005
  *
1005
1006
  * 上标的两个「实测 vs 标称」处理(很重要,别照搬标称值):
1006
1007
  * - **maxTokens 钳到该模型的实测上限**(`MEASURED_MAX_TOKENS`)。上游
@@ -1011,7 +1012,7 @@ interface CodeArtsQueueStatus {
1011
1012
  * 用户配置的按模型覆盖值与进程内学到的真实上界在这里压过发现值(issue #9)。
1012
1013
  *
1013
1014
  * @param contextWindowOverrides 按模型 id 覆盖 contextWindow(大小写不敏感)
1014
- * @throws 三路全失败,或合并结果为空。
1015
+ * @throws 所有来源全失败,或合并结果为空。
1015
1016
  */
1016
1017
  declare function fetchModels(credential: CodeArtsResolved, signal?: AbortSignal, contextWindowOverrides?: Readonly<Record<string, number>>): Promise<ModelDiscoveryResult>;
1017
1018
  //#endregion
@@ -1127,6 +1128,14 @@ declare class CodeArtsAccountStore {
1127
1128
  constructor(path: string, legacyPath?: string, options?: {
1128
1129
  log?: (message: string) => void;
1129
1130
  });
1131
+ /**
1132
+ * 所有槽位共用的跨进程续期锁(与守护进程同一个文件)。
1133
+ *
1134
+ * 注意是**整个文档一把锁**,不是每个账号一把:`AccountSlot` 是先刷后整份写回的,
1135
+ * 两个账号同时在刷会让后写的那次把前一个刚轮换出来的 refresh_token 覆盖掉。
1136
+ * 一把锁的代价只是多账号时串行几秒,换来的是不可能互相踩。
1137
+ */
1138
+ private slotLockPath;
1130
1139
  private loaded;
1131
1140
  private load;
1132
1141
  private adopt;
package/lib/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { a as codeartsAuthPath, c as credentialFromOAuth, i as codeartsAccountsPath, m as startLogin, n as CodeArtsCredentialStore, o as codeartsDebugLogPath, r as MANUAL_ACCOUNT_ID, s as codeartsRefreshLogPath, t as CodeArtsAccountStore } from "./auth-Cd2SvQIy.mjs";
2
- import { A as queueFrame, B as forgetModelUnavailable, C as isWelfareClaimedStatus, D as modelUnavailableReasonText, E as maxTokensCeilingFor, F as CodeArtsCatalog, H as isBenefitModel, I as FALLBACK_CODEARTS_MODELS, K as modelUnavailableReason, L as clearBenefitBlocked, M as signedGet, N as upstreamErrorMessage, O as pickDailyWelfareCampaign, R as creditRatioLabel, S as isTpmLimit, T as learnedContextWindowFor, U as markModelUnavailable, V as isBenefitBlocked, _ as isNotMultimodal, a as claimDailyWelfare, b as isQueueRejectText, c as degradeTokenCeiling, d as fetchQueueStatus, f as fetchWelfareCampaigns, g as isModelNotAccessible, h as isIamTokenError, i as chatStream, j as rateLimitFrame, k as prepareChatBody, l as fetchCallerIdentity, m as isConcurrencyCap, n as SNAP_HOST, o as clearQueueStatus, p as firstFrameError, r as canonicalModel, s as contextWindowOverrideFor, t as MAX_TOKENS_FLOOR, u as fetchModels, v as isParamInvalidFrame, w as learnContextWindow, x as isQueueableRate, y as isQueueReject, z as filterEnabledModels } from "./upstream-BV4XWB4l.mjs";
3
- import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-CHCdx9qJ.mjs";
1
+ import { a as codeartsAuthPath, c as credentialFromOAuth, g as startLogin, i as codeartsAccountsPath, n as CodeArtsCredentialStore, o as codeartsDebugLogPath, r as MANUAL_ACCOUNT_ID, s as codeartsRefreshLogPath, t as CodeArtsAccountStore } from "./auth-q6MY-TXM.mjs";
2
+ import { A as queueFrame, B as forgetModelUnavailable, C as isWelfareClaimedStatus, D as modelUnavailableReasonText, E as maxTokensCeilingFor, F as CodeArtsCatalog, H as isBenefitModel, I as FALLBACK_CODEARTS_MODELS, K as modelUnavailableReason, L as clearBenefitBlocked, M as signedGet, N as upstreamErrorMessage, O as pickDailyWelfareCampaign, R as creditRatioLabel, S as isTpmLimit, T as learnedContextWindowFor, U as markModelUnavailable, V as isBenefitBlocked, _ as isNotMultimodal, a as claimDailyWelfare, b as isQueueRejectText, c as degradeTokenCeiling, d as fetchQueueStatus, f as fetchWelfareCampaigns, g as isModelNotAccessible, h as isIamTokenError, i as chatStream, j as rateLimitFrame, k as prepareChatBody, l as fetchCallerIdentity, m as isConcurrencyCap, n as SNAP_HOST, o as clearQueueStatus, p as firstFrameError, r as canonicalModel, s as contextWindowOverrideFor, t as MAX_TOKENS_FLOOR, u as fetchModels, v as isParamInvalidFrame, w as learnContextWindow, x as isQueueableRate, y as isQueueReject, z as filterEnabledModels } from "./upstream-COqsw56c.mjs";
3
+ import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-BZuhJ6R9.mjs";
4
4
  import { i as lazyApi, r as createProvider } from "./models-CgKCibpk.mjs";
5
- import { c as keeperLogPath, d as keeperStats, f as spawnKeeper, i as clearKeeperHandoff, l as keeperScriptPath, n as KEEPER_STALE_MS, p as stopKeeper, s as keeperHandoffRecent } from "./keeper-DJLwIiR4.mjs";
5
+ import { c as keeperLogPath, f as keeperStats, i as clearKeeperHandoff, l as keeperNextPassAt, m as stopKeeper, n as KEEPER_STALE_MS, p as spawnKeeper, s as keeperHandoffRecent, u as keeperScriptPath } from "./keeper-BWHQDFAh.mjs";
6
6
  import { appendFileSync, statSync, writeFileSync } from "node:fs";
7
7
  import z from "@deepseek-ai/schemastery";
8
8
  import { randomBytes, timingSafeEqual } from "node:crypto";
@@ -3592,9 +3592,26 @@ function apply(ctx, rawConfig) {
3592
3592
  */
3593
3593
  const KEEP_ALIVE_INTERVAL_MS = 12e5;
3594
3594
  let keepAliveTimer;
3595
+ /**
3596
+ * 这一轮该不该把续期让给守护进程。
3597
+ *
3598
+ * 原来只看 `keeperRunning()`(心跳新鲜 + pid 活着)。问题是那个条件在 keeper 的
3599
+ * **两轮 tick 之间(20 分钟空窗)同样成立**,于是插件整段时间完全不刷;万一 keeper
3600
+ * 那一轮撞上锁忙跳过了,两边就一起不刷,凭证一路裸奔到过期(2026-11-18 凌晨
3601
+ * 06:46–08:06 缺 4 轮 tick 时就是这样,见 `keeper-main.ts` 的睡眠补偿注释)。
3602
+ *
3603
+ * 现在改成「keeper 活着 **且** 它马上要来」才让路:只有当下一轮 tick 已到最后
3604
+ * 一个心跳周期的窗口里(或者已经过点了),才把续期权交给它。其余时间插件自己刷,
3605
+ * 反正跨进程锁会把两边串起来。
3606
+ */
3607
+ const shouldDeferToKeeper = () => {
3608
+ const stats = keeperStats();
3609
+ if (!stats.alive) return false;
3610
+ return Date.now() >= keeperNextPassAt(stats.state) - KEEPER_STALE_MS;
3611
+ };
3595
3612
  const keepAliveLoop = async () => {
3596
3613
  if (stopped) return;
3597
- if (keeperRunning()) await store.reloadFromDisk().catch(() => {});
3614
+ if (shouldDeferToKeeper()) await store.reloadFromDisk().catch(() => {});
3598
3615
  else try {
3599
3616
  const outcome = await store.keepAlive();
3600
3617
  if (outcome.refreshed > 0) ctx.logger.debug(`dsh-codearts: refreshed ${outcome.refreshed} credential(s) in the background`);
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { basename, dirname, join } from "node:path";
4
- import { spawn } from "node:child_process";
4
+ import { execFileSync, spawn } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
6
6
  //#region src/keeper.ts
7
7
  /**
@@ -41,6 +41,8 @@ import { fileURLToPath } from "node:url";
41
41
  */
42
42
  /** 心跳超过这么久没更新,就认为守护进程已经不在(它每 30 秒写一次)。 */
43
43
  const KEEPER_STALE_MS = 9e4;
44
+ /** Windows 上探活要起一次 tasklist:给足超时,卡住就按「活着」处理。 */
45
+ const PID_PROBE_TIMEOUT_MS = 5e3;
44
46
  /** 心跳写入间隔。 */
45
47
  const KEEPER_HEARTBEAT_MS = 3e4;
46
48
  /** 守护进程的续期节奏:每 20 分钟过一遍,与插件里的 `KEEP_ALIVE_INTERVAL_MS` 对齐。 */
@@ -79,14 +81,42 @@ function writeKeeperState(state, home) {
79
81
  } catch {}
80
82
  }
81
83
  /** 进程还在吗。信号 0 只探活,不真的发信号(Windows 上同样适用)。 */
84
+ /**
85
+ * 某个 pid 是否还活着。
86
+ *
87
+ * **不能用 `process.kill(pid, 0)`**:那个「发信号 0 只是探活」的约定只在 POSIX 上
88
+ * 成立。Windows 上 Node 的实现不看信号值,直接 `TerminateProcess` —— 探活会把目标
89
+ * 进程**当场杀掉**。这里的调用方是 `keeperStats()`,探的正是守护进程本身,用错实现
90
+ * 就成了「插件每查一次状态就杀一次 keeper」,而 keeper 一死插件就再也不自己续期。
91
+ */
82
92
  function pidAlive(pid) {
83
93
  if (!Number.isInteger(pid) || pid <= 0) return false;
84
- try {
94
+ if (pid === process.pid) return true;
95
+ if (process.platform !== "win32") try {
85
96
  process.kill(pid, 0);
86
97
  return true;
87
98
  } catch (error) {
88
99
  return error?.code === "EPERM";
89
100
  }
101
+ try {
102
+ const out = execFileSync("tasklist", [
103
+ "/FI",
104
+ `PID eq ${pid}`,
105
+ "/NH"
106
+ ], {
107
+ encoding: "utf8",
108
+ stdio: [
109
+ "ignore",
110
+ "pipe",
111
+ "ignore"
112
+ ],
113
+ timeout: PID_PROBE_TIMEOUT_MS,
114
+ windowsHide: true
115
+ });
116
+ return new RegExp(`\\b${pid}\\b`).test(out);
117
+ } catch {
118
+ return true;
119
+ }
90
120
  }
91
121
  /** 状态文件的 mtime(用来判断账号文档是不是被守护进程改过)。 */
92
122
  function keeperStats(home) {
@@ -97,6 +127,20 @@ function keeperStats(home) {
97
127
  state
98
128
  };
99
129
  }
130
+ /**
131
+ * 下一个 tick 最晚会在什么时候发生。
132
+ *
133
+ * 守护进程每 `KEEPER_TICK_MS` 跑一轮,但那一刻没在跑不代表它死了 —— 两轮之间就是
134
+ * 20 分钟的空窗。插件要判断「这一轮的续期该由谁来负责」,必须看这个时间点,而不是
135
+ * 只看 `alive`。
136
+ *
137
+ * 补了一点余量(`KEEPER_STALE_MS`):tick 本身要读文档、逐号发请求,慢的时候能拖上
138
+ * 几十秒,卡在边界上会让插件抢在 keeper 落库前就把号刷了 —— 那正是要避免的双刷。
139
+ */
140
+ function keeperNextPassAt(state) {
141
+ if (state === void 0) return 0;
142
+ return (state.lastPass?.at ?? state.startedAt) + KEEPER_TICK_MS + KEEPER_STALE_MS;
143
+ }
100
144
  /** 守护进程的脚本路径:和当前 bundle 同目录的 `keeper-main.mjs`(tsdown 入口名)。 */
101
145
  function keeperScriptPath() {
102
146
  return fileURLToPath(new URL("./keeper-main.mjs", import.meta.url));
@@ -287,4 +331,4 @@ function stopRequested(home) {
287
331
  return existsSync(join(home ?? dshHome(), ".codearts-keeper.stop"));
288
332
  }
289
333
  //#endregion
290
- export { clearKeeperState as a, keeperLogPath as c, keeperStats as d, spawnKeeper as f, writeKeeperState as g, writeKeeperHandoff as h, clearKeeperHandoff as i, keeperScriptPath as l, stopRequested as m, KEEPER_STALE_MS as n, isDshInstallerTempDir as o, stopKeeper as p, KEEPER_TICK_MS as r, keeperHandoffRecent as s, KEEPER_HEARTBEAT_MS as t, keeperStatePath as u };
334
+ export { writeKeeperState as _, clearKeeperState as a, keeperLogPath as c, keeperStatePath as d, keeperStats as f, writeKeeperHandoff as g, stopRequested as h, clearKeeperHandoff as i, keeperNextPassAt as l, stopKeeper as m, KEEPER_STALE_MS as n, isDshInstallerTempDir as o, spawnKeeper as p, KEEPER_TICK_MS as r, keeperHandoffRecent as s, KEEPER_HEARTBEAT_MS as t, keeperScriptPath as u };
@@ -1,7 +1,7 @@
1
- import { d as OAuthTokenError, f as defaultLoginConfig, i as codeartsAccountsPath, l as readAccountDocument, p as refreshToken, u as writeJsonAtomic } from "./auth-Cd2SvQIy.mjs";
2
- import { a as clearKeeperState, c as keeperLogPath, d as keeperStats, g as writeKeeperState, h as writeKeeperHandoff, i as clearKeeperHandoff, m as stopRequested, o as isDshInstallerTempDir, r as KEEPER_TICK_MS, t as KEEPER_HEARTBEAT_MS, u as keeperStatePath } from "./keeper-DJLwIiR4.mjs";
1
+ import { d as refreshLockPath, f as withRefreshLock, h as refreshToken, i as codeartsAccountsPath, l as readAccountDocument, m as defaultLoginConfig, p as OAuthTokenError, u as writeJsonAtomic } from "./auth-q6MY-TXM.mjs";
2
+ import { _ as writeKeeperState, a as clearKeeperState, c as keeperLogPath, d as keeperStatePath, f as keeperStats, g as writeKeeperHandoff, h as stopRequested, i as clearKeeperHandoff, o as isDshInstallerTempDir, r as KEEPER_TICK_MS, t as KEEPER_HEARTBEAT_MS } from "./keeper-BWHQDFAh.mjs";
3
3
  import { appendFileSync, existsSync, unlinkSync, watch } from "node:fs";
4
- import { join } from "node:path";
4
+ import { dirname, join } from "node:path";
5
5
  //#region src/keeper-main.ts
6
6
  /**
7
7
  * dsh-codearts 凭证守护进程(独立入口,由 DSH 用 `ELECTRON_RUN_AS_NODE=1` 拉起)。
@@ -23,6 +23,16 @@ import { join } from "node:path";
23
23
  */
24
24
  /** 距过期不足这么久就续(与服务端插件保持一致)。 */
25
25
  const REFRESH_SKEW_MS = 18e5;
26
+ /**
27
+ * `STS5.1806` 连续撞上几次才判死(与 `auth.ts` 的 `REFRESH_USED_MAX_STREAK` 对齐)。
28
+ *
29
+ * 这个码只说明「这个 refresh_token 已经被用掉了」,最常见的原因是插件刚刚先刷了
30
+ * 一次。磁盘上若已经有新令牌,重读就行;磁盘还没更新(对方正在写)时也会撞上,
31
+ * 那更不能判死 —— 下一轮就恢复正常了。
32
+ */
33
+ const USED_MAX_STREAK = 3;
34
+ /** 睡眠看门狗的检查间隔:机器醒过来最多 30 秒就会补跑一轮。 */
35
+ const SLEEP_WATCHDOG_MS = 3e4;
26
36
  function parseHomeArg(argv) {
27
37
  const at = argv.indexOf("--home");
28
38
  if (at >= 0 && at + 1 < argv.length) return argv[at + 1];
@@ -58,6 +68,8 @@ function alreadyRunning() {
58
68
  * 凭证,守护进程必须看见这些变化,否则会把一份过期的内存快照写回去,把刚登录的
59
69
  * 号覆盖掉。
60
70
  */
71
+ /** 每个账号连续撞上「令牌已被用掉」的次数;成功续上一次就清零。 */
72
+ const usedStreak = /* @__PURE__ */ new Map();
61
73
  async function tick(state) {
62
74
  const accountsPath = codeartsAccountsPath(home);
63
75
  const doc = await readAccountDocument(accountsPath);
@@ -86,19 +98,26 @@ async function tick(state) {
86
98
  if (Number.isNaN(exp)) continue;
87
99
  if (exp - Date.now() >= REFRESH_SKEW_MS) continue;
88
100
  checked += 1;
101
+ const refreshTokenValue = cred.refreshToken;
102
+ const clientIdValue = cred.clientId;
103
+ const dpopPrivateKeyValue = cred.dpopPrivateKey;
104
+ if (refreshTokenValue === void 0 || clientIdValue === void 0 || dpopPrivateKeyValue === void 0) continue;
105
+ const locked = await withRefreshLock(refreshLockPath(dirname(accountsPath)), () => refreshToken(defaultLoginConfig(), {
106
+ userId: cred.userId ?? "",
107
+ userName: cred.userName ?? "",
108
+ domainId: "",
109
+ securityToken: cred.token,
110
+ accessKeyId: cred.accessKeyId ?? "",
111
+ secretAccessKey: cred.secretAccessKey ?? "",
112
+ expiration: cred.expiration ?? "",
113
+ refreshToken: refreshTokenValue,
114
+ clientId: clientIdValue,
115
+ dpopPrivateKey: dpopPrivateKeyValue
116
+ }), { onBusy: () => log(`refresh SKIPPED ${id.slice(0, 12)} (plugin holds the refresh lock)`) });
117
+ if (locked === void 0) continue;
89
118
  try {
90
- const next = await refreshToken(defaultLoginConfig(), {
91
- userId: cred.userId ?? "",
92
- userName: cred.userName ?? "",
93
- domainId: "",
94
- securityToken: cred.token,
95
- accessKeyId: cred.accessKeyId ?? "",
96
- secretAccessKey: cred.secretAccessKey ?? "",
97
- expiration: cred.expiration ?? "",
98
- refreshToken: cred.refreshToken,
99
- clientId: cred.clientId,
100
- dpopPrivateKey: cred.dpopPrivateKey
101
- });
119
+ const next = locked;
120
+ usedStreak.delete(id);
102
121
  doc.accounts[id] = {
103
122
  ...cred,
104
123
  token: next.securityToken,
@@ -116,14 +135,19 @@ async function tick(state) {
116
135
  log(`refreshed ${id.slice(0, 12)} → expires ${next.expiration}`);
117
136
  } catch (error) {
118
137
  const used = error instanceof OAuthTokenError && error.refreshTokenUsed;
138
+ let markStale = false;
119
139
  if (used) {
120
140
  const fresh = await readAccountDocument(accountsPath);
121
141
  const advanced = fresh !== void 0 && fresh.accounts[id]?.refreshToken !== void 0 && fresh.accounts[id]?.refreshToken !== cred.refreshToken;
122
- log(`refresh SKIPPED ${id.slice(0, 12)} (refresh token already used${advanced ? ", newer token on disk" : ""})`);
123
- if (advanced) continue;
142
+ const streak = (usedStreak.get(id) ?? 0) + 1;
143
+ usedStreak.set(id, streak);
144
+ markStale = !advanced && streak >= USED_MAX_STREAK;
145
+ log(`refresh SKIPPED ${id.slice(0, 12)} (refresh token already used${advanced ? ", newer token on disk" : ""}, streak ${streak}/${USED_MAX_STREAK})`);
146
+ } else {
147
+ usedStreak.delete(id);
148
+ markStale = error instanceof OAuthTokenError && error.permanent;
124
149
  }
125
- const permanent = !used && error instanceof OAuthTokenError && error.permanent;
126
- if (permanent) {
150
+ if (markStale) {
127
151
  doc.accounts[id] = {
128
152
  ...cred,
129
153
  stale: true
@@ -132,7 +156,7 @@ async function tick(state) {
132
156
  needsLogin.push(id);
133
157
  }
134
158
  const reason = error instanceof OAuthTokenError ? `HTTP ${error.status} ${error.body.slice(0, 200)}` : error instanceof Error ? error.message : String(error);
135
- log(`refresh FAILED ${id.slice(0, 12)} (${permanent ? "permanent, marked stale" : "transient, retry next pass"}): ${reason}`);
159
+ log(`refresh FAILED ${id.slice(0, 12)} (${markStale ? "permanent, marked stale" : "transient, retry next pass"}): ${reason}`);
136
160
  }
137
161
  }
138
162
  if (dirty) await writeJsonAtomic(accountsPath, doc);
@@ -231,6 +255,8 @@ async function main() {
231
255
  writeKeeperState(state, home);
232
256
  if (stopRequested(home)) shutdown("stop requested by plugin");
233
257
  }, KEEPER_HEARTBEAT_MS);
258
+ let timer;
259
+ let lastPassAt = 0;
234
260
  const loop = async () => {
235
261
  if (stopped) return;
236
262
  if (stopRequested(home)) {
@@ -242,11 +268,29 @@ async function main() {
242
268
  } catch (error) {
243
269
  log(`pass failed: ${error instanceof Error ? error.message : String(error)}`);
244
270
  }
245
- state.heartbeatAt = Date.now();
271
+ lastPassAt = Date.now();
272
+ state.heartbeatAt = lastPassAt;
246
273
  writeKeeperState(state, home);
247
274
  if (stopped) return;
248
- setTimeout(() => void loop(), KEEPER_TICK_MS);
275
+ timer = setTimeout(() => void loop(), KEEPER_TICK_MS);
249
276
  };
277
+ /**
278
+ * 睡眠/休眠补偿:setTimeout 只保证「不早于」,机器睡过去的那段时间它是停摆的。
279
+ *
280
+ * 2026-11-18 的现场:守护进程 pid 全程活着,日志却在 06:46–08:06 之间缺了 4 轮
281
+ * tick —— 机器睡了,定时器跟着停。而插件那边看到心跳文件在、pid 也活,就按
282
+ * `keeperRunning()` 让路,于是两边一起不刷,等醒过来凭证已经过期。
283
+ *
284
+ * 这里每 30 秒对一次表:超过一个 tick 周期没跑过一轮就立刻补一轮。补跑会重排
285
+ * 定时器,所以睡醒后不会连撞两次。
286
+ */
287
+ setInterval(() => {
288
+ if (stopped || timer === void 0) return;
289
+ if (Date.now() - lastPassAt < 15e5) return;
290
+ clearTimeout(timer);
291
+ log(`wake-from-sleep: no pass for ${Math.round((Date.now() - lastPassAt) / 1e3)}s, running one now`);
292
+ loop();
293
+ }, SLEEP_WATCHDOG_MS);
250
294
  loop();
251
295
  }
252
296
  main().catch((error) => {
@@ -505,6 +505,13 @@ const EP_BENEFIT_CONFIG = "/api/v1/gateway/config";
505
505
  const EP_AGENT_LIST = "/v1/agent-center/agents/useragents";
506
506
  const EP_AGENT_DETAIL = "/v1/agent-center/agents/detail";
507
507
  /**
508
+ * 企业租户设置与第三方模型清单(26.11 客户端)。官方客户端先按套餐门禁
509
+ * (`is_credit_package && spec_code 含 enterprise`,或白名单)判断后才请求,
510
+ * 普通账号不会走到。见 `fetchThirdPartyModels`。
511
+ */
512
+ const EP_TENANT_SETTINGS = "/v1/llm/tenant/settings";
513
+ const EP_THIRD_PARTY_MODELS = "/v1/third-party-model/model/list";
514
+ /**
508
515
  * 模型的思考强度清单(26.10.0 新增)。**必须带 `Agent-Type: PromptCenter`**:
509
516
  * 不带头时上游回 `TM.00001001 请求头Agent-Type为空`(实测)。
510
517
  */
@@ -1586,13 +1593,77 @@ async function fetchAgentModels(credential, signal) {
1586
1593
  name: firstString(model.model_name, model.model_alias, id),
1587
1594
  contextWindow,
1588
1595
  ...contextWindow > 0 ? { contextWindowKnown: true } : {},
1589
- maxTokens: positive(params.max_tokens),
1596
+ maxTokens: positive(params.max_tokens) || positive(params.output_context_window),
1590
1597
  supportsImages: model.supports_images === true,
1591
1598
  ...ratio === void 0 ? {} : { ratio }
1592
1599
  });
1593
1600
  }
1594
1601
  return out;
1595
1602
  }
1603
+ /** 租户是否启用了第三方模型;读不到明确值时返回 undefined(交给调用方决定)。 */
1604
+ function thirdPartyModelsEnabled(value) {
1605
+ const body = asRecord(value);
1606
+ for (const candidate of [
1607
+ body.third_party_model_enabled,
1608
+ asRecord(body.data).third_party_model_enabled,
1609
+ asRecord(body.settings).third_party_model_enabled
1610
+ ]) {
1611
+ if (candidate === true) return true;
1612
+ if (candidate === false) return false;
1613
+ }
1614
+ }
1615
+ /**
1616
+ * 企业租户的第三方模型清单:先 `GET /v1/llm/tenant/settings` 拿门禁,再
1617
+ * `GET /v1/third-party-model/model/list`(分页,官方客户端一页取 100 条)。
1618
+ *
1619
+ * 这类模型是企业管理员注册的 MaaS 通道(企业内部专业版的主力),与 agent-center
1620
+ * 的 `gpts.models` 同源但不完全重合:没挂到 CodeAgent 上的模型只在清单里出现。
1621
+ *
1622
+ * 门禁失败或未启用时返回空数组且不记 errors —— 官方客户端对普通账号根本不会
1623
+ * 请求这两条接口,我们照做,免得每个个人账号每轮刷新都多两条噪音。只有租户明确
1624
+ * 启用后清单仍失败,才把失败带回去(那说明企业账号的发现链路真断了)。
1625
+ *
1626
+ * 条目形状以 `model_parameters` 为准,也兼容参数摊平在顶层的写法(官方客户端两处
1627
+ * 都兼容)。输出上限同样可能放在 `output_context_window`(#11)。
1628
+ */
1629
+ async function fetchThirdPartyModels(credential, signal) {
1630
+ const settingsResp = await signedGet(`${SNAP_HOST}${EP_TENANT_SETTINGS}`, credential, "PromptCenter", signal);
1631
+ if (!settingsResp.ok) return [];
1632
+ const enabled = thirdPartyModelsEnabled(parseJson(settingsResp.text));
1633
+ if (enabled === false) return [];
1634
+ const listResp = await signedGet(`${SNAP_HOST}${EP_THIRD_PARTY_MODELS}?page_num=1&page_size=100`, credential, "PromptCenter", signal);
1635
+ if (!listResp.ok) {
1636
+ if (enabled === true) throw new Error(`third-party model list HTTP ${listResp.status} ${listResp.message}`);
1637
+ return [];
1638
+ }
1639
+ const body = asRecord(parseJson(listResp.text));
1640
+ const error = body.error ?? asRecord(body.data).error;
1641
+ if (error !== void 0) {
1642
+ if (enabled === true) throw new Error(`third-party model list error: ${JSON.stringify(error).slice(0, 200)}`);
1643
+ return [];
1644
+ }
1645
+ const out = [];
1646
+ for (const raw of asArray(body.list ?? asRecord(body.data).list)) {
1647
+ const item = asRecord(raw);
1648
+ const params = asRecord(item.model_parameters);
1649
+ const flat = Object.keys(params).length > 0 ? params : item;
1650
+ if (item.enable === false || item.display_enabled === false) continue;
1651
+ const id = firstString(flat.model_id, item.model_id, item.model_alias, flat.service_name, flat.third_party_model);
1652
+ if (id === "") continue;
1653
+ const ratio = creditRatioOf(item) ?? creditRatioOf(flat);
1654
+ const contextWindow = positive(flat.context_window);
1655
+ out.push({
1656
+ id,
1657
+ name: firstString(item.model_name, item.model_alias, flat.model_name, id),
1658
+ contextWindow,
1659
+ ...contextWindow > 0 ? { contextWindowKnown: true } : {},
1660
+ maxTokens: positive(flat.max_tokens) || positive(flat.output_context_window),
1661
+ supportsImages: item.supports_images === true || flat.supports_images === true,
1662
+ ...ratio === void 0 ? {} : { ratio }
1663
+ });
1664
+ }
1665
+ return out;
1666
+ }
1596
1667
  /**
1597
1668
  * 思考强度清单:`POST /v1/model/thinking-variants`,body `{ model_names }`。
1598
1669
  *
@@ -1716,10 +1787,11 @@ async function clearQueueStatus(credential, chatId, model, signal) {
1716
1787
  }
1717
1788
  }
1718
1789
  /**
1719
- * 动态发现当前账号可用的模型清单(三路合并)。
1790
+ * 动态发现当前账号可用的模型清单(四路合并)。
1720
1791
  *
1721
- * 与 codearts2api 的 `Client.FetchModels` 等价:内置、限时福利、agent-center 三路
1722
- * 各自独立,任一路失败只记进 `errors` 不阻断 —— 福利网关抖动时仍能拿到内置模型。
1792
+ * 内置、限时福利、agent-center、企业第三方模型四路各自独立,任一路失败只记进
1793
+ * `errors` 不阻断 —— 福利网关抖动时仍能拿到内置模型。第三方模型那一路有门禁:
1794
+ * 租户未启用时返回空且不算来源(见 `fetchThirdPartyModels`)。
1723
1795
  *
1724
1796
  * 上标的两个「实测 vs 标称」处理(很重要,别照搬标称值):
1725
1797
  * - **maxTokens 钳到该模型的实测上限**(`MEASURED_MAX_TOKENS`)。上游
@@ -1730,7 +1802,7 @@ async function clearQueueStatus(credential, chatId, model, signal) {
1730
1802
  * 用户配置的按模型覆盖值与进程内学到的真实上界在这里压过发现值(issue #9)。
1731
1803
  *
1732
1804
  * @param contextWindowOverrides 按模型 id 覆盖 contextWindow(大小写不敏感)
1733
- * @throws 三路全失败,或合并结果为空。
1805
+ * @throws 所有来源全失败,或合并结果为空。
1734
1806
  */
1735
1807
  async function fetchModels(credential, signal, contextWindowOverrides = {}) {
1736
1808
  const settled = await Promise.all([
@@ -1754,6 +1826,13 @@ async function fetchModels(credential, signal, contextWindowOverrides = {}) {
1754
1826
  }), (error) => ({
1755
1827
  source: "agent",
1756
1828
  error
1829
+ })),
1830
+ fetchThirdPartyModels(credential, signal).then((models) => ({
1831
+ source: "thirdparty",
1832
+ models
1833
+ }), (error) => ({
1834
+ source: "thirdparty",
1835
+ error
1757
1836
  }))
1758
1837
  ]);
1759
1838
  const sources = [];
@@ -1763,6 +1842,7 @@ async function fetchModels(credential, signal, contextWindowOverrides = {}) {
1763
1842
  source: item.source,
1764
1843
  message: item.error.message
1765
1844
  });
1845
+ else if (item.source === "thirdparty" && item.models.length === 0) continue;
1766
1846
  else {
1767
1847
  sources.push(item.source);
1768
1848
  discovered.push(item.models);
@@ -1,5 +1,5 @@
1
- import { u as writeJsonAtomic } from "./auth-Cd2SvQIy.mjs";
2
- import { G as modelDisplayName, H as isBenefitModel, W as mergeModelLists, q as setDiscoveredBenefitModels, u as fetchModels } from "./upstream-BV4XWB4l.mjs";
1
+ import { u as writeJsonAtomic } from "./auth-q6MY-TXM.mjs";
2
+ import { G as modelDisplayName, H as isBenefitModel, W as mergeModelLists, q as setDiscoveredBenefitModels, u as fetchModels } from "./upstream-COqsw56c.mjs";
3
3
  import { existsSync } from "node:fs";
4
4
  import { readFile } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
@@ -535,6 +535,6 @@ function percentileOf(buckets, ratio) {
535
535
  }
536
536
  //#endregion
537
537
  //#region src/version.ts
538
- const CODEARTS_VERSION = "1.4.4";
538
+ const CODEARTS_VERSION = "1.4.6";
539
539
  //#endregion
540
540
  export { refreshCatalog as a, discoverModels as i, CodeArtsUsageTracker as n, codeartsUsagePath as r, CODEARTS_VERSION as t };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-codearts",
3
3
  "displayName": "DSH CodeArts Connect",
4
4
  "description": "把华为云 CodeArts 接入 DeepSeek Harness —— 内置 OAuth2 登录(PKCE + DPoP),登录后即可在 DSH 对话窗口使用 CodeArts 的模型。",
5
- "version": "1.4.4",
5
+ "version": "1.4.6",
6
6
  "packageManager": "pnpm@11.24.0",
7
7
  "author": "elegant01",
8
8
  "keywords": [