dsh-codearts 1.4.3 → 1.4.5

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/lib/index.d.mts CHANGED
@@ -1127,6 +1127,14 @@ declare class CodeArtsAccountStore {
1127
1127
  constructor(path: string, legacyPath?: string, options?: {
1128
1128
  log?: (message: string) => void;
1129
1129
  });
1130
+ /**
1131
+ * 所有槽位共用的跨进程续期锁(与守护进程同一个文件)。
1132
+ *
1133
+ * 注意是**整个文档一把锁**,不是每个账号一把:`AccountSlot` 是先刷后整份写回的,
1134
+ * 两个账号同时在刷会让后写的那次把前一个刚轮换出来的 refresh_token 覆盖掉。
1135
+ * 一把锁的代价只是多账号时串行几秒,换来的是不可能互相踩。
1136
+ */
1137
+ private slotLockPath;
1130
1138
  private loaded;
1131
1139
  private load;
1132
1140
  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-DqzkoxeU.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-B5PDMG7r.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-B_KAbdPy.mjs";
3
+ import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-DZ47veC-.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, 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-CA6PKtcv.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";
@@ -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) {
@@ -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-B5PDMG7r.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-CA6PKtcv.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) => {
@@ -1586,7 +1586,7 @@ async function fetchAgentModels(credential, signal) {
1586
1586
  name: firstString(model.model_name, model.model_alias, id),
1587
1587
  contextWindow,
1588
1588
  ...contextWindow > 0 ? { contextWindowKnown: true } : {},
1589
- maxTokens: positive(params.max_tokens),
1589
+ maxTokens: positive(params.max_tokens) || positive(params.output_context_window),
1590
1590
  supportsImages: model.supports_images === true,
1591
1591
  ...ratio === void 0 ? {} : { ratio }
1592
1592
  });
@@ -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-B5PDMG7r.mjs";
2
+ import { G as modelDisplayName, H as isBenefitModel, W as mergeModelLists, q as setDiscoveredBenefitModels, u as fetchModels } from "./upstream-B_KAbdPy.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.3";
538
+ const CODEARTS_VERSION = "1.4.5";
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.3",
5
+ "version": "1.4.5",
6
6
  "packageManager": "pnpm@11.24.0",
7
7
  "author": "elegant01",
8
8
  "keywords": [