dsh-codearts 1.2.14 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs CHANGED
@@ -1,5 +1,9 @@
1
- import { A as signedGet, B as markModelUnavailable, C as isTpmLimit, D as pickDailyWelfareCampaign, E as modelUnavailableReasonText, F as creditRatioLabel, G as codeartsAccountsPath, H as CodeArtsAccountStore, I as filterEnabledModels, J as startLogin, K as codeartsAuthPath, L as forgetModelUnavailable, M as CodeArtsCatalog, N as FALLBACK_CODEARTS_MODELS, O as prepareChatBody, P as clearBenefitBlocked, R as isBenefitBlocked, S as isQueueableRate, T as maxTokensCeilingFor, U as CodeArtsCredentialStore, V as modelUnavailableReason, W as MANUAL_ACCOUNT_ID, _ as isConcurrencyCap, a as refreshCatalog, b as isNotMultimodal, c as chatStream, d as degradeTokenCeiling, f as fetchCallerIdentity, g as firstFrameError, h as fetchWelfareCampaigns, i as discoverModels, j as upstreamErrorMessage, k as rateLimitFrame, l as claimDailyWelfare, m as fetchQueueStatus, n as CodeArtsUsageTracker, o as SNAP_HOST, p as fetchModels, q as credentialFromOAuth, r as codeartsUsagePath, s as canonicalModel, t as CODEARTS_VERSION, u as clearQueueStatus, v as isIamTokenError, w as isWelfareClaimedStatus, x as isParamInvalidFrame, y as isModelNotAccessible, z as isBenefitModel } from "./version-Msk-1m2n.mjs";
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-Ch0vYSAo.mjs";
2
+ import { A as clearBenefitBlocked, C as prepareChatBody, E as upstreamErrorMessage, F as isBenefitModel, I as markModelUnavailable, M as filterEnabledModels, N as forgetModelUnavailable, O as CodeArtsCatalog, P as isBenefitBlocked, S as pickDailyWelfareCampaign, T as signedGet, _ as isQueueableRate, a as clearQueueStatus, b as maxTokensCeilingFor, c as fetchModels, d as firstFrameError, f as isConcurrencyCap, g as isParamInvalidFrame, h as isNotMultimodal, i as claimDailyWelfare, j as creditRatioLabel, k as FALLBACK_CODEARTS_MODELS, l as fetchQueueStatus, m as isModelNotAccessible, n as canonicalModel, o as degradeTokenCeiling, p as isIamTokenError, r as chatStream, s as fetchCallerIdentity, t as SNAP_HOST, u as fetchWelfareCampaigns, v as isTpmLimit, w as rateLimitFrame, x as modelUnavailableReasonText, y as isWelfareClaimedStatus, z as modelUnavailableReason } from "./upstream-CVtspzAv.mjs";
3
+ import { a as refreshCatalog, i as discoverModels, n as CodeArtsUsageTracker, r as codeartsUsagePath, t as CODEARTS_VERSION } from "./version-BjBwEMks.mjs";
2
4
  import { i as lazyApi, r as createProvider } from "./models-CgKCibpk.mjs";
5
+ import { a as keeperLogPath, c as keeperStats, d as stopKeeper, n as KEEPER_STALE_MS, o as keeperScriptPath, u as spawnKeeper } from "./keeper-MHeAp_eV.mjs";
6
+ import { appendFileSync, statSync, writeFileSync } from "node:fs";
3
7
  import z from "@deepseek-ai/schemastery";
4
8
  import { randomBytes, timingSafeEqual } from "node:crypto";
5
9
  import { createServer } from "node:http";
@@ -49,6 +53,8 @@ var CodeArtsAccountPool = class {
49
53
  preferred = /* @__PURE__ */ new Set();
50
54
  maxConcurrent;
51
55
  now;
56
+ /** 等槽位的唤醒器:槽位释放 / 池里新增账号 / 账号复活时逐个唤醒。 */
57
+ waiters = /* @__PURE__ */ new Set();
52
58
  constructor(ids, options = {}) {
53
59
  this.maxConcurrent = options.maxConcurrent ?? 2;
54
60
  this.now = options.now ?? (() => Date.now());
@@ -57,6 +63,7 @@ var CodeArtsAccountPool = class {
57
63
  /** 让池与账号文档对齐:新增的进来,删掉的出去。已有账号的运行时状态保留。 */
58
64
  sync(ids) {
59
65
  const wanted = new Set(ids);
66
+ const before = this.accounts.size;
60
67
  for (const id of [...this.accounts.keys()]) if (!wanted.has(id)) this.accounts.delete(id);
61
68
  for (const id of ids) {
62
69
  if (this.accounts.has(id)) continue;
@@ -73,6 +80,7 @@ var CodeArtsAccountPool = class {
73
80
  errorCount: 0
74
81
  });
75
82
  }
83
+ if (this.accounts.size !== before) this.notifyWaiters();
76
84
  }
77
85
  list() {
78
86
  return [...this.accounts.values()];
@@ -98,6 +106,11 @@ var CodeArtsAccountPool = class {
98
106
  setPaused(ids) {
99
107
  this.paused.clear();
100
108
  for (const id of ids) this.paused.add(id);
109
+ this.notifyWaiters();
110
+ }
111
+ /** 当前被用户暂停的账号 id(报错文案要把「暂停」与「槽位满」分开说)。 */
112
+ pausedIds() {
113
+ return [...this.paused];
101
114
  }
102
115
  /** 设置置顶集合(账号 id)。置顶只在「同时可用」时改变先后,不会绕过冷却/上限。 */
103
116
  setPreferred(ids) {
@@ -131,6 +144,58 @@ var CodeArtsAccountPool = class {
131
144
  const account = this.accounts.get(id);
132
145
  if (account === void 0) return;
133
146
  if (account.activeConcurrent > 0) account.activeConcurrent -= 1;
147
+ this.notifyWaiters();
148
+ }
149
+ notifyWaiters() {
150
+ for (const waiter of [...this.waiters]) try {
151
+ waiter();
152
+ } catch {}
153
+ }
154
+ /** 现在是否有一个真正能接活的空槽位(禁用/暂停/冷却中的号不算)。 */
155
+ hasFreeSlot() {
156
+ const now = this.now();
157
+ return this.list().some((a) => !a.disabled && !this.paused.has(a.id) && now >= a.coolUntil && a.activeConcurrent < a.maxConcurrent);
158
+ }
159
+ /**
160
+ * 有没有「健康、但本地槽位被占满」的号。
161
+ *
162
+ * 只有这一种情况值得等一会儿:禁用要重新登录、暂停是用户自己停的、冷却有明确
163
+ * 截止时间 —— 等它们都不会在预算内自己好。
164
+ */
165
+ hasBusyWaitable() {
166
+ const now = this.now();
167
+ return this.list().some((a) => !a.disabled && !this.paused.has(a.id) && now >= a.coolUntil && a.activeConcurrent >= a.maxConcurrent);
168
+ }
169
+ /**
170
+ * 等一个本地槽位空出来,最多 `maxWaitMs`。
171
+ *
172
+ * 返回 true = 等到了;false = 超时、被中止,或者池里根本没有「等一会儿就会空」的号。
173
+ * issue #8:本地槽位满以前是立刻回 429「没有可用账号」,并发场景下(一次派 5 个
174
+ * subagent)必然误伤;现在与上游排队对齐 —— 先短时等待,等不到再报错。
175
+ */
176
+ waitForFreeSlot(maxWaitMs, signal) {
177
+ if (this.hasFreeSlot()) return Promise.resolve(true);
178
+ if (!this.hasBusyWaitable() || maxWaitMs <= 0) return Promise.resolve(false);
179
+ if (signal?.aborted === true) return Promise.resolve(false);
180
+ return new Promise((resolve) => {
181
+ let settled = false;
182
+ const finish = (value) => {
183
+ if (settled) return;
184
+ settled = true;
185
+ this.waiters.delete(check);
186
+ clearTimeout(timer);
187
+ signal?.removeEventListener("abort", onAbort);
188
+ resolve(value);
189
+ };
190
+ const check = () => {
191
+ if (this.hasFreeSlot()) finish(true);
192
+ };
193
+ const onAbort = () => finish(false);
194
+ const timer = setTimeout(() => finish(false), maxWaitMs);
195
+ timer.unref?.();
196
+ this.waiters.add(check);
197
+ signal?.addEventListener("abort", onAbort, { once: true });
198
+ });
134
199
  }
135
200
  /**
136
201
  * 撞到上游并发上限。
@@ -185,6 +250,7 @@ var CodeArtsAccountPool = class {
185
250
  account.lastCapAt = 0;
186
251
  account.errorCount = 0;
187
252
  account.lastError = void 0;
253
+ this.notifyWaiters();
188
254
  }
189
255
  /** 上游 5xx / 软限流:短时冷却。 */
190
256
  cooldown(id, ms, reason) {
@@ -960,11 +1026,13 @@ function queuedMessage(model, gate) {
960
1026
  * 全部被禁用时回 401(宿主只自动重试 429,401 一次就把「去重新登录」说清);
961
1027
  * 只要还有会自己恢复的(冷却/槽位满)就回 429,宿主重试有概率直接救回来。
962
1028
  */
963
- function noAccountError(accounts) {
1029
+ function noAccountError(accounts, pausedIds = []) {
964
1030
  const now = Date.now();
1031
+ const paused = new Set(pausedIds);
965
1032
  const disabled = accounts.filter((a) => a.disabled);
966
1033
  const cooling = accounts.filter((a) => !a.disabled && now < a.coolUntil);
967
- const busy = accounts.filter((a) => !a.disabled && now >= a.coolUntil);
1034
+ const idleButPaused = accounts.filter((a) => !a.disabled && now >= a.coolUntil && paused.has(a.id));
1035
+ const busy = accounts.filter((a) => !a.disabled && now >= a.coolUntil && !paused.has(a.id));
968
1036
  const parts = [];
969
1037
  if (disabled.length > 0) {
970
1038
  const reasons = disabled.map((a) => a.lastError === void 0 ? a.id : `${a.id}(${a.lastError.slice(0, 120)})`).join("、");
@@ -974,8 +1042,9 @@ function noAccountError(accounts) {
974
1042
  const secs = Math.max(1, Math.ceil((Math.min(...cooling.map((a) => a.coolUntil)) - now) / 1e3));
975
1043
  parts.push(`${cooling.length} 个在短时冷却中(约 ${secs} 秒后恢复)`);
976
1044
  }
977
- if (busy.length > 0) parts.push(`${busy.length} 个的本地并发槽位已满(每账号最多 ${busy[0]?.maxConcurrent ?? 2} 个在飞请求),等几秒再发`);
978
- const message = `codearts 当前没有可用账号:${parts.join(";")}`;
1045
+ if (idleButPaused.length > 0) parts.push(`${idleButPaused.length} 个已被暂停(在卡片上取消暂停即可恢复)`);
1046
+ if (busy.length > 0) parts.push(`${busy.length} 个的本地并发槽位已满(每账号最多 ${busy[0]?.maxConcurrent ?? 2} 个在飞请求)`);
1047
+ const message = disabled.length === 0 && cooling.length === 0 && idleButPaused.length === 0 && busy.length > 0 ? `codearts 账号忙:${parts.join(";")},已等待仍没有空位,请稍后重试` : `codearts 当前没有可用账号:${parts.join(";")}`;
979
1048
  return disabled.length === accounts.length ? {
980
1049
  status: 401,
981
1050
  kind: "session_dead",
@@ -1080,6 +1149,8 @@ function createCodeArtsShim(options) {
1080
1149
  const logger = options.logger;
1081
1150
  const usage = options.usage;
1082
1151
  const queue = options.queue;
1152
+ const debug = options.debug;
1153
+ const localSlotWaitBudgetMs = options.localSlotWaitMs ?? 3e4;
1083
1154
  const pool = options.pool ?? new CodeArtsAccountPool([]);
1084
1155
  const SHARED_SECRET = randomBytes(32).toString("base64url");
1085
1156
  function bearerOk(req) {
@@ -1331,91 +1402,117 @@ function createCodeArtsShim(options) {
1331
1402
  let cappedAccount;
1332
1403
  let tpmAccount;
1333
1404
  let queueWaitedMs = 0;
1405
+ let localSlotWaitedMs = 0;
1334
1406
  let lastKind;
1335
1407
  let lastAccountId;
1336
1408
  let lastStatus = 0;
1337
1409
  let lastMessage = "";
1338
1410
  const rotateDeadline = Date.now() + CAP_WAIT_LIMIT;
1339
1411
  const attempts = Math.min(Math.max(ids.length, ROTATE_MIN_ATTEMPTS), ROTATE_MAX_ATTEMPTS);
1340
- for (let attempt = 0; attempt < attempts; attempt += 1) {
1341
- if (Date.now() + ATTEMPT_RESERVE_MS > rotateDeadline) break;
1342
- const id = pool.pick(tried);
1343
- if (id === void 0) break;
1344
- tried.add(id);
1345
- if (!pool.acquire(id)) continue;
1346
- try {
1347
- const credential = await store.resolve(id);
1348
- if (credential === void 0) {
1349
- pool.disable(id, "no credential");
1412
+ /** 日志里区分并发请求;没开调试时不生成。 */
1413
+ const requestTag = debug === void 0 ? "" : randomBytes(3).toString("hex");
1414
+ /**
1415
+ * 两轮:第一轮按账号轮换;如果全被「本地槽位满」挡住,就等一个槽位空出来
1416
+ * 再跑第二轮。以前这里直接落到「没有可用账号」的 429,并发派发(一次 5 个
1417
+ * subagent)必然误伤(issue #8)。
1418
+ */
1419
+ for (let round = 0; round < 2; round += 1) {
1420
+ tried.clear();
1421
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
1422
+ if (Date.now() + ATTEMPT_RESERVE_MS > rotateDeadline) break;
1423
+ const id = pool.pick(tried);
1424
+ if (id === void 0) break;
1425
+ tried.add(id);
1426
+ if (!pool.acquire(id)) {
1427
+ debug?.(`acquire miss req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
1350
1428
  continue;
1351
1429
  }
1352
- if (queue !== void 0) {
1353
- const gate = await queue.wait(credential, checked.chatId, checked.model, controller.signal);
1354
- if (controller.signal.aborted) return;
1355
- if (gate.kind === "queued") {
1356
- usage?.noteFailure("queued", id);
1357
- writeOpenAIError(res, 400, "queued", queuedMessage(checked.model, gate));
1430
+ debug?.(`acquire ok req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
1431
+ try {
1432
+ const credential = await store.resolve(id);
1433
+ if (credential === void 0) {
1434
+ pool.disable(id, "no credential");
1435
+ continue;
1436
+ }
1437
+ if (queue !== void 0) {
1438
+ const gate = await queue.wait(credential, checked.chatId, checked.model, controller.signal);
1439
+ if (controller.signal.aborted) return;
1440
+ if (gate.kind === "queued") {
1441
+ usage?.noteFailure("queued", id);
1442
+ writeOpenAIError(res, 400, "queued", queuedMessage(checked.model, gate));
1443
+ return;
1444
+ }
1445
+ if (gate.kind === "queue_full" || gate.kind === "error") {
1446
+ usage?.noteFailure(gate.kind, id);
1447
+ writeOpenAIError(res, gate.kind === "queue_full" ? 429 : 502, gate.kind, gate.message);
1448
+ return;
1449
+ }
1450
+ }
1451
+ const opened = await openWithCeilingHeal(credential, raw, contextWindow, controller.signal);
1452
+ const { prepared, result } = opened;
1453
+ if (controller.signal.aborted) {
1454
+ if (result.ok) await result.stream.cancel().catch(() => {});
1358
1455
  return;
1359
1456
  }
1360
- if (gate.kind === "queue_full" || gate.kind === "error") {
1361
- usage?.noteFailure(gate.kind, id);
1362
- writeOpenAIError(res, gate.kind === "queue_full" ? 429 : 502, gate.kind, gate.message);
1457
+ if (result.ok) {
1458
+ pool.noteSuccess(id);
1459
+ await pipeToResponse(res, result.stream, controller.signal, {
1460
+ accountId: id,
1461
+ model: prepared.model,
1462
+ startedAt: requestStartedAt
1463
+ }, opened.head);
1363
1464
  return;
1364
1465
  }
1365
- }
1366
- const opened = await openWithCeilingHeal(credential, raw, contextWindow, controller.signal);
1367
- const { prepared, result } = opened;
1368
- if (controller.signal.aborted) {
1369
- if (result.ok) await result.stream.cancel().catch(() => {});
1370
- return;
1371
- }
1372
- if (result.ok) {
1373
- pool.noteSuccess(id);
1374
- await pipeToResponse(res, result.stream, controller.signal, {
1375
- accountId: id,
1376
- model: prepared.model,
1377
- startedAt: requestStartedAt
1378
- }, opened.head);
1379
- return;
1380
- }
1381
- lastKind = result.kind;
1382
- lastAccountId = id;
1383
- lastStatus = result.status;
1384
- lastMessage = result.message;
1385
- if (isConcurrencyCap(result)) {
1386
- pool.noteConcurrencyCap(id);
1387
- cappedAccount = id;
1388
- continue;
1389
- }
1390
- if (isTpmLimit(result)) {
1391
- tpmAccount = id;
1392
- break;
1393
- }
1394
- if (result.kind === "iam_stale") {
1395
- if (!refreshed.has(id)) {
1396
- refreshed.add(id);
1397
- logger?.warn(`dsh-codearts: ${id} 的 IAM token 被判失效,强制续期后重试`);
1398
- if (await store.forceRefresh(id, credential.token) !== void 0) {
1399
- tried.delete(id);
1400
- continue;
1466
+ lastKind = result.kind;
1467
+ lastAccountId = id;
1468
+ lastStatus = result.status;
1469
+ lastMessage = result.message;
1470
+ if (isConcurrencyCap(result)) {
1471
+ pool.noteConcurrencyCap(id);
1472
+ cappedAccount = id;
1473
+ continue;
1474
+ }
1475
+ if (isTpmLimit(result)) {
1476
+ tpmAccount = id;
1477
+ break;
1478
+ }
1479
+ if (result.kind === "iam_stale") {
1480
+ if (!refreshed.has(id)) {
1481
+ refreshed.add(id);
1482
+ logger?.warn(`dsh-codearts: ${id} 的 IAM token 被判失效,强制续期后重试`);
1483
+ if (await store.forceRefresh(id, credential.token) !== void 0) {
1484
+ tried.delete(id);
1485
+ continue;
1486
+ }
1401
1487
  }
1488
+ pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
1489
+ continue;
1402
1490
  }
1403
- pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
1404
- continue;
1405
- }
1406
- if (result.kind === "session_dead") {
1407
- pool.disable(id, result.message);
1408
- continue;
1409
- }
1410
- if (result.kind === "server" || result.kind === "soft_rate") {
1411
- pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
1491
+ if (result.kind === "session_dead") {
1492
+ pool.disable(id, result.message);
1493
+ continue;
1494
+ }
1495
+ if (result.kind === "server" || result.kind === "soft_rate") {
1496
+ pool.cooldown(id, SERVER_COOLDOWN_MS, result.message);
1497
+ break;
1498
+ }
1499
+ pool.noteError(id, 3, ERROR_COOLDOWN_MS, result.message);
1412
1500
  break;
1501
+ } finally {
1502
+ pool.release(id);
1503
+ debug?.(`release req=${requestTag} ${id} active=${pool.get(id)?.activeConcurrent ?? "?"}/${pool.get(id)?.maxConcurrent ?? "?"}`);
1413
1504
  }
1414
- pool.noteError(id, 3, ERROR_COOLDOWN_MS, result.message);
1415
- break;
1416
- } finally {
1417
- pool.release(id);
1418
1505
  }
1506
+ if (lastKind !== void 0 || controller.signal.aborted) break;
1507
+ if (!pool.hasBusyWaitable()) break;
1508
+ const waitBudget = Math.min(localSlotWaitBudgetMs, rotateDeadline - ATTEMPT_RESERVE_MS - Date.now());
1509
+ if (waitBudget <= 0) break;
1510
+ const waitingSince = Date.now();
1511
+ debug?.(`slot wait start req=${requestTag} budget=${waitBudget}ms pool=${pool.list().map((a) => `${a.id}:${a.activeConcurrent}/${a.maxConcurrent}`).join(",")}`);
1512
+ const got = await pool.waitForFreeSlot(waitBudget, controller.signal);
1513
+ localSlotWaitedMs += Date.now() - waitingSince;
1514
+ debug?.(`slot wait ${got ? "done" : "timeout"} req=${requestTag} waited=${Date.now() - waitingSince}ms`);
1515
+ if (!got) break;
1419
1516
  }
1420
1517
  if (controller.signal.aborted) return;
1421
1518
  const queueAccount = cappedAccount ?? tpmAccount;
@@ -1450,13 +1547,16 @@ function createCodeArtsShim(options) {
1450
1547
  }
1451
1548
  }
1452
1549
  if (lastKind === void 0) {
1453
- const none = noAccountError(pool.list());
1550
+ const none = noAccountError(pool.list(), pool.pausedIds());
1454
1551
  usage?.noteFailure(none.kind);
1455
1552
  writeOpenAIError(res, none.status, none.kind, none.message);
1456
1553
  return;
1457
1554
  }
1458
1555
  const explanation = upstreamErrorMessage(lastMessage, lastStatus);
1459
- const waited = queueWaitedMs >= 1e3 ? `(本地已排队重试 ${Math.round(queueWaitedMs / 1e3)} 秒)` : "";
1556
+ const waits = [];
1557
+ if (queueWaitedMs >= 1e3) waits.push(`排队重试 ${Math.round(queueWaitedMs / 1e3)} 秒`);
1558
+ if (localSlotWaitedMs >= 1e3) waits.push(`等本地槽位 ${Math.round(localSlotWaitedMs / 1e3)} 秒`);
1559
+ const waited = waits.length > 0 ? `(本地已${waits.join("、")})` : "";
1460
1560
  usage?.noteFailure(lastKind, lastAccountId);
1461
1561
  writeOpenAIError(res, KIND_STATUS[lastKind], lastKind, `${explanation}${waited}`);
1462
1562
  }
@@ -1584,6 +1684,15 @@ const CODEARTS_QUEUE_PATH = "/api/codearts/queue";
1584
1684
  * GET 给当前值与 writable,POST 收 `{credits?, queue?}` 写进 settings。
1585
1685
  */
1586
1686
  const CODEARTS_DOCK_PATH = "/api/codearts/dock";
1687
+ /**
1688
+ * POST /api/codearts/keeper/stop — 结束常驻守护进程,并把开关**同时**关掉。
1689
+ *
1690
+ * 为什么必须在服务端把开关一起关:进程被 kill 之后,「开关开着但没进程」是个自相
1691
+ * 矛盾的状态。若只杀进程不改开关,用户下次打开 DSH 会看到开关还是开的、PID 却是空
1692
+ * 的,以为功能坏了;而且插件会按「开关是开的」去重起它 —— 用户刚 kill 掉的东西自己
1693
+ * 又回来了。所以这两件事必须原子地一起做。
1694
+ */
1695
+ const CODEARTS_KEEPER_STOP_PATH = "/api/codearts/keeper/stop";
1587
1696
  /** 最近出站请求的**形状**摘要(只有 role 名与计数,不含内容),排障用。 */
1588
1697
  const CODEARTS_DEBUG_PATH = "/api/codearts/debug";
1589
1698
  /**
@@ -1657,11 +1766,16 @@ function modelBadgesOf(models) {
1657
1766
  /**
1658
1767
  * 开关的默认值:没有 settings provider(或老配置没这两个键)时保持原有行为 ——
1659
1768
  * 底部两行都显示;侧边栏相反,缺省不开(那一格是所有插件共用的全局座位)。
1769
+ * `modelDetail` 缺省开(保持老版本的样子),`autoClaim` 缺省关。
1660
1770
  */
1661
1771
  const DEFAULT_DOCK_FLAGS = {
1662
1772
  credits: true,
1663
1773
  queue: true,
1664
- sidebar: false
1774
+ sidebar: false,
1775
+ settingsEntry: true,
1776
+ modelDetail: true,
1777
+ autoClaim: false,
1778
+ keepAliveDaemon: false
1665
1779
  };
1666
1780
  /**
1667
1781
  * 把逐账号的领取结果汇总成一条:HTTP 层只看 ok,卡片看 results 逐号展示。
@@ -1874,6 +1988,7 @@ async function buildStatus(deps, force = false) {
1874
1988
  const cred = await deps.store.current();
1875
1989
  const usage = usageOf(deps);
1876
1990
  const dock = deps.dock === void 0 ? {} : { dock: deps.dock() };
1991
+ const keeperView = deps.keeper === void 0 ? {} : { keeper: await deps.keeper() };
1877
1992
  const piAi = await probePiAiCompat();
1878
1993
  const compat = piAi === void 0 ? {} : { piAiError: piAi };
1879
1994
  if (accounts.length === 0 || cred === void 0) return {
@@ -1882,6 +1997,7 @@ async function buildStatus(deps, force = false) {
1882
1997
  accounts,
1883
1998
  usage,
1884
1999
  ...dock,
2000
+ ...keeperView,
1885
2001
  ...compat
1886
2002
  };
1887
2003
  const usable = accounts.some(accountUsable);
@@ -1891,7 +2007,8 @@ async function buildStatus(deps, force = false) {
1891
2007
  models,
1892
2008
  accounts,
1893
2009
  usage,
1894
- ...dock
2010
+ ...dock,
2011
+ ...keeperView
1895
2012
  };
1896
2013
  if (!usable) return {
1897
2014
  status: "expired",
@@ -2041,10 +2158,14 @@ function dockHandler(deps) {
2041
2158
  const touched = [
2042
2159
  "credits",
2043
2160
  "queue",
2044
- "sidebar"
2161
+ "sidebar",
2162
+ "settingsEntry",
2163
+ "modelDetail",
2164
+ "autoClaim",
2165
+ "keepAliveDaemon"
2045
2166
  ].filter((key) => body[key] !== void 0);
2046
2167
  if (touched.length === 0 || touched.some((key) => typeof body[key] !== "boolean")) {
2047
- json(res, 400, { error: "expected {\"credits\"?: boolean, \"queue\"?: boolean, \"sidebar\"?: boolean}" });
2168
+ json(res, 400, { error: "expected {\"credits\"?: boolean, \"queue\"?: boolean, \"sidebar\"?: boolean, \"settingsEntry\"?: boolean, \"modelDetail\"?: boolean, \"autoClaim\"?: boolean, \"keepAliveDaemon\"?: boolean}" });
2048
2169
  return;
2049
2170
  }
2050
2171
  if (!await deps.setDock(Object.fromEntries(touched.map((key) => [key, body[key]])))) {
@@ -2063,6 +2184,42 @@ function dockHandler(deps) {
2063
2184
  json(res, 405, { error: "method not allowed" });
2064
2185
  };
2065
2186
  }
2187
+ /**
2188
+ * POST /api/codearts/keeper/stop — 结束守护进程,并把开关一起关掉。
2189
+ *
2190
+ * 顺序不能反:先杀进程、再写开关。反过来的话,写开关的那一瞬间如果正好触发了插件的
2191
+ * 重排(`armKeepAliveDaemon`),它会按「开关是开的」再起一个 —— 用户点一次结束,
2192
+ * 结果又冒出来一个新 pid。杀完再写,重排看到的是 false,自然什么都不做。
2193
+ */
2194
+ function keeperStopHandler(deps) {
2195
+ return async (req, res) => {
2196
+ if (!loopbackRequest(req)) {
2197
+ json(res, 403, { error: "request-not-trusted" });
2198
+ return;
2199
+ }
2200
+ if (req.method !== "POST") {
2201
+ json(res, 405, { error: "method not allowed" });
2202
+ return;
2203
+ }
2204
+ if (deps.stopKeeper === void 0) {
2205
+ json(res, 503, { error: "keeper-control-unavailable" });
2206
+ return;
2207
+ }
2208
+ try {
2209
+ const outcome = await deps.stopKeeper();
2210
+ const writable = deps.setDock === void 0 ? false : await deps.setDock({ keepAliveDaemon: false }).catch(() => false);
2211
+ json(res, outcome.ok ? 200 : 500, {
2212
+ ok: outcome.ok,
2213
+ ...outcome.pid === void 0 ? {} : { pid: outcome.pid },
2214
+ ...outcome.reason === void 0 ? {} : { reason: outcome.reason },
2215
+ writable,
2216
+ dock: deps.dock?.() ?? DEFAULT_DOCK_FLAGS
2217
+ });
2218
+ } catch (error) {
2219
+ json(res, 500, { error: safeMessage(error) });
2220
+ }
2221
+ };
2222
+ }
2066
2223
  /** GET /api/codearts/models — currently offered model ids (honours allowlist). */
2067
2224
  function modelsHandler(deps) {
2068
2225
  return async (req, res) => {
@@ -2538,6 +2695,11 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2538
2695
  path: CODEARTS_DOCK_PATH,
2539
2696
  handler: dockHandler(deps)
2540
2697
  });
2698
+ const disposeKeeperStop = ctx.webServer.register({
2699
+ kind: "exact",
2700
+ path: CODEARTS_KEEPER_STOP_PATH,
2701
+ handler: keeperStopHandler(deps)
2702
+ });
2541
2703
  const disposeDebug = ctx.webServer.register({
2542
2704
  kind: "exact",
2543
2705
  path: CODEARTS_DEBUG_PATH,
@@ -2561,6 +2723,7 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2561
2723
  disposeTestModel();
2562
2724
  disposeQueue();
2563
2725
  disposeDock();
2726
+ disposeKeeperStop();
2564
2727
  disposeDebug();
2565
2728
  disposeDoctor();
2566
2729
  for (const s of activeLogins.values()) s.close();
@@ -2740,7 +2903,11 @@ const Config = z.object({
2740
2903
  enabledModels: z.array(z.string()).description("Model ids offered in the model pickers (empty means every model)").volatile(),
2741
2904
  showCreditDock: z.boolean().default(true).description("Show the remaining-credits line under the chat input box").volatile(),
2742
2905
  showQueueDock: z.boolean().default(true).description("Show the upstream queue position under the chat input box").volatile(),
2743
- showSidebarPanel: z.boolean().default(false).description("Show a CodeArts icon in the DSH sidebar icon column, opening this page in the middle column").volatile()
2906
+ showSidebarPanel: z.boolean().default(false).description("Show a CodeArts icon in the DSH sidebar icon column, opening this page in the middle column").volatile(),
2907
+ showSettingsEntry: z.boolean().default(true).description("Show a CodeArts entry in the left navigation of DSH Settings (default: shown)").volatile(),
2908
+ showModelDetailDock: z.boolean().default(true).description("Show \"Model … · x ratio\" on the line under the chat input box (Provider CodeArts always shows)").volatile(),
2909
+ autoClaim: z.boolean().default(false).description("Automatically claim the daily sign-in credits for every signed-in account").volatile(),
2910
+ keepAliveDaemon: z.boolean().default(false).description("Keep a detached background process that refreshes the OAuth credential while DSH is closed").volatile()
2744
2911
  });
2745
2912
  function settingsCompatNamespace(ctx) {
2746
2913
  return resolveSettingsNamespaceCompat(ctx, ctx.get("settings"), CODEARTS_SETTINGS_NS);
@@ -2748,7 +2915,23 @@ function settingsCompatNamespace(ctx) {
2748
2915
  function apply(ctx, rawConfig) {
2749
2916
  const config = unwrapConfig(rawConfig);
2750
2917
  const accountsPath = codeartsAccountsPath();
2751
- const store = new CodeArtsAccountStore(accountsPath);
2918
+ /**
2919
+ * 续期失败日志。
2920
+ *
2921
+ * 宿主对插件的 `info`/`debug` 没有任何出口,`warn` 会变成系统通知 —— 一次网络抖动
2922
+ * 就弹一次窗口显然不行。所以失败原因写插件自己的文件(issue #8 里 03:22 那次续期
2923
+ * 失败就是因为零日志而永远无法取证)。1MB 截断重来,避免长期运行无限增长。
2924
+ */
2925
+ const appendRefreshLog = (message) => {
2926
+ try {
2927
+ const path = codeartsRefreshLogPath();
2928
+ try {
2929
+ if (statSync(path).size > 1e6) writeFileSync(path, "");
2930
+ } catch {}
2931
+ appendFileSync(path, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`, { mode: 384 });
2932
+ } catch {}
2933
+ };
2934
+ const store = new CodeArtsAccountStore(accountsPath, void 0, { log: appendRefreshLog });
2752
2935
  const pool = new CodeArtsAccountPool([]);
2753
2936
  const catalog = new CodeArtsCatalog();
2754
2937
  const usage = new CodeArtsUsageTracker({ path: codeartsUsagePath() });
@@ -2757,6 +2940,11 @@ function apply(ctx, rawConfig) {
2757
2940
  /** /status 是卡片与对话底部都会轮询的接口,积分慢请求不能把它拖成转圈。 */
2758
2941
  const CREDIT_TIMEOUT_MS = 8e3;
2759
2942
  /**
2943
+ * 领取签到积分的单号预算。福利中心偶尔很慢(要拉活动列表再认领),给足 20 秒,
2944
+ * 但必须有个上限:自动领取是在后台跑的,卡死的请求会把这个号的后续重试全堵住。
2945
+ */
2946
+ const CLAIM_TIMEOUT_MS = 2e4;
2947
+ /**
2760
2948
  * 拉一次积分(每个账号各自一份)。
2761
2949
  *
2762
2950
  * 积分是**账号级**属性:多账号下每个号的余额、到期、签到状态都不同,所以逐号
@@ -2816,7 +3004,11 @@ function apply(ctx, rawConfig) {
2816
3004
  const dock = () => ({
2817
3005
  credits: current().showCreditDock !== false,
2818
3006
  queue: current().showQueueDock !== false,
2819
- sidebar: current().showSidebarPanel === true
3007
+ sidebar: current().showSidebarPanel === true,
3008
+ settingsEntry: current().showSettingsEntry !== false,
3009
+ modelDetail: current().showModelDetailDock !== false,
3010
+ autoClaim: current().autoClaim === true,
3011
+ keepAliveDaemon: current().keepAliveDaemon === true
2820
3012
  });
2821
3013
  const setDock = async (patch) => {
2822
3014
  const settings = ctx.get("settings");
@@ -2824,12 +3016,202 @@ function apply(ctx, rawConfig) {
2824
3016
  await settings.update(settingsCompatNamespace(ctx), {
2825
3017
  ...patch.credits === void 0 ? {} : { showCreditDock: patch.credits },
2826
3018
  ...patch.queue === void 0 ? {} : { showQueueDock: patch.queue },
2827
- ...patch.sidebar === void 0 ? {} : { showSidebarPanel: patch.sidebar }
3019
+ ...patch.sidebar === void 0 ? {} : { showSidebarPanel: patch.sidebar },
3020
+ ...patch.settingsEntry === void 0 ? {} : { showSettingsEntry: patch.settingsEntry },
3021
+ ...patch.modelDetail === void 0 ? {} : { showModelDetailDock: patch.modelDetail },
3022
+ ...patch.autoClaim === void 0 ? {} : { autoClaim: patch.autoClaim },
3023
+ ...patch.keepAliveDaemon === void 0 ? {} : { keepAliveDaemon: patch.keepAliveDaemon }
2828
3024
  });
2829
3025
  return true;
2830
3026
  };
2831
3027
  /** 手动「刷新模型列表」的预算:三路来源各打一次,比每小时的后台刷新更该给足时间。 */
2832
3028
  const MANUAL_REFRESH_MS = 6e4;
3029
+ /**
3030
+ * 守护进程:当前活着吗。
3031
+ *
3032
+ * 「活着」= 状态文件里心跳新鲜 **且** 那个 pid 真能探到(`keeper.ts` 里两个条件都查)。
3033
+ * 只看心跳会把刚被 kill 的进程当成活的 —— 心跳是它死前 30 秒内写的,不会自己消失。
3034
+ */
3035
+ const keeperRunning = () => keeperStats().alive;
3036
+ /**
3037
+ * 刚点开开关、守护进程还没写出状态文件的那段时间。
3038
+ *
3039
+ * 秒级的进程启动 + 首次 `writeKeeperState` 之间确实有一段「探不到活」的窗口。
3040
+ * 不区分的话,卡片刚被勾上就会因为「没探到进程」而自己把开关关掉 —— 用户看到的是
3041
+ * 勾了一下马上弹回去。这段时间里 `alive` 仍是 false(它确实还没活),但带 `starting`。
3042
+ */
3043
+ const KEEPER_START_GRACE_MS = KEEPER_STALE_MS;
3044
+ const keeperView = async () => {
3045
+ const logPath = keeperLogPath();
3046
+ const stats = keeperStats();
3047
+ if (stats.alive && stats.state !== void 0) {
3048
+ keeperLastError = void 0;
3049
+ return {
3050
+ alive: true,
3051
+ pid: stats.state.pid,
3052
+ startedAt: stats.state.startedAt,
3053
+ heartbeatAt: stats.state.heartbeatAt,
3054
+ ...stats.state.lastPass === void 0 ? {} : { lastPass: stats.state.lastPass },
3055
+ logPath
3056
+ };
3057
+ }
3058
+ if (!(current().keepAliveDaemon === true)) return {
3059
+ alive: false,
3060
+ logPath
3061
+ };
3062
+ if (Date.now() - keeperSpawnedAt < KEEPER_START_GRACE_MS) return {
3063
+ alive: false,
3064
+ starting: true,
3065
+ ...keeperLastError === void 0 ? {} : { error: keeperLastError },
3066
+ logPath
3067
+ };
3068
+ try {
3069
+ await setDock({ keepAliveDaemon: false });
3070
+ } catch {}
3071
+ return {
3072
+ alive: false,
3073
+ error: keeperLastError ?? "守护进程已退出,已自动关闭保活开关",
3074
+ logPath
3075
+ };
3076
+ };
3077
+ /**
3078
+ * 常驻守护进程:在 DSH 之外续 refresh_token。
3079
+ *
3080
+ * 与上面 `keepAliveLoop` 的分工:那个只在 DSH 活着时有用,关掉 DSH 就没了;这个起的是
3081
+ * 一个 detached 进程,DSH 退出后它还在,20 分钟续一次,把 30 天有效期的 refresh_token
3082
+ * 一直续下去 —— 这才是「十几天不用重新登录」的正解。
3083
+ *
3084
+ * refresh_token 是一次性的:两边同时刷会让后刷的一方拿着作废的 token 失败。所以开关
3085
+ * 打开时 `keepAliveLoop` 会主动让路(只从磁盘重读),刷新权独占在守护进程手里。
3086
+ */
3087
+ const KEEPER_ENSURE_MS = 6e4;
3088
+ let keeperSpawnedAt = 0;
3089
+ let keeperLastError;
3090
+ let keeperTimer;
3091
+ /**
3092
+ * 按开关状态把守护进程拉起来。
3093
+ *
3094
+ * 只在「开关刚被打开」时调用(`armKeepAliveDaemon`)。**不做定时重起**:用户明确要求
3095
+ * 「被 kill 了开关就关掉」,而不是「被 kill 了自己又冒出来」—— 后者正是用户按了结束
3096
+ * 却看到进程又活了的那种体验。
3097
+ */
3098
+ const ensureKeeper = () => {
3099
+ if (stopped) return;
3100
+ if (current().keepAliveDaemon !== true) return;
3101
+ if (keeperRunning()) return;
3102
+ const outcome = spawnKeeper({
3103
+ scriptPath: keeperScriptPath(),
3104
+ pluginVersion: CODEARTS_VERSION
3105
+ });
3106
+ keeperSpawnedAt = Date.now();
3107
+ if (outcome.ok) {
3108
+ keeperLastError = void 0;
3109
+ ctx.logger.debug(`dsh-codearts: credential keeper running (pid ${outcome.pid ?? "?"})`);
3110
+ } else {
3111
+ keeperLastError = outcome.reason ?? "spawn failed";
3112
+ ctx.logger.debug(`dsh-codearts: credential keeper failed to start: ${keeperLastError}`);
3113
+ }
3114
+ };
3115
+ /**
3116
+ * 守护巡检:只在旁边看着,不重起。
3117
+ *
3118
+ * 三种结局:开关被关掉 → 收工;进程还活着 → 继续看;进程没了(超出启动宽限期)→
3119
+ * 把开关关掉并收工。判死必须在服务端做,不能只靠卡片轮询 —— 卡片没打开时也得让
3120
+ * 那个「开着却空转」的开关自己消失。
3121
+ */
3122
+ const keeperLoop = async () => {
3123
+ if (stopped) return;
3124
+ if (current().keepAliveDaemon !== true) {
3125
+ keeperTimer = void 0;
3126
+ return;
3127
+ }
3128
+ if (!keeperRunning() && Date.now() - keeperSpawnedAt >= KEEPER_START_GRACE_MS) {
3129
+ keeperTimer = void 0;
3130
+ keeperSpawnedAt = 0;
3131
+ await setDock({ keepAliveDaemon: false }).catch(() => false);
3132
+ return;
3133
+ }
3134
+ keeperTimer = setTimeout(() => void keeperLoop(), KEEPER_ENSURE_MS);
3135
+ keeperTimer.unref?.();
3136
+ };
3137
+ /** 开关变化时立刻响应:打开就马上起,关掉就撤掉巡检(进程本身留给「结束」按钮)。 */
3138
+ const armKeepAliveDaemon = () => {
3139
+ if (stopped) return;
3140
+ if (current().keepAliveDaemon !== true) {
3141
+ if (keeperTimer !== void 0) clearTimeout(keeperTimer);
3142
+ keeperTimer = void 0;
3143
+ keeperSpawnedAt = 0;
3144
+ return;
3145
+ }
3146
+ if (keeperTimer !== void 0) return;
3147
+ ensureKeeper();
3148
+ keeperTimer = setTimeout(() => void keeperLoop(), KEEPER_ENSURE_MS);
3149
+ keeperTimer.unref?.();
3150
+ };
3151
+ /**
3152
+ * 逐号领取每日签到积分。
3153
+ *
3154
+ * 手动「领取」按钮和后台自动领取走的是**同一条**路径,只是入口不同:领的是什么、
3155
+ * 失败怎么归类、什么时候作废缓存,两处必须完全一致,否则「手动能领到、自动领不到」
3156
+ * 这种差异排查起来极其费劲。
3157
+ */
3158
+ const claimAll = async (accountId) => {
3159
+ const ids = accountId === void 0 ? await store.ids() : [accountId];
3160
+ if (ids.length === 0) return {
3161
+ ok: false,
3162
+ claimed: false,
3163
+ state: "failed",
3164
+ amount: 0,
3165
+ message: "no usable credential"
3166
+ };
3167
+ const results = [];
3168
+ for (const id of ids) try {
3169
+ const stored = await store.credential(id);
3170
+ if (stored === void 0 || stored.stale === true) {
3171
+ results.push({
3172
+ id,
3173
+ ok: false,
3174
+ claimed: false,
3175
+ state: "failed",
3176
+ amount: 0,
3177
+ message: stored === void 0 ? "account not found" : "account needs sign-in"
3178
+ });
3179
+ continue;
3180
+ }
3181
+ const resolved = await store.resolve(id);
3182
+ if (resolved === void 0) {
3183
+ results.push({
3184
+ id,
3185
+ ok: false,
3186
+ claimed: false,
3187
+ state: "failed",
3188
+ amount: 0,
3189
+ message: "no usable credential"
3190
+ });
3191
+ continue;
3192
+ }
3193
+ const outcome = await claimDailyWelfare(resolved, AbortSignal.timeout(CLAIM_TIMEOUT_MS));
3194
+ if (outcome.state === "claimed") credits.invalidate(id);
3195
+ results.push({
3196
+ id,
3197
+ ok: outcome.state !== "failed",
3198
+ claimed: outcome.state === "claimed",
3199
+ state: outcome.state,
3200
+ amount: outcome.amount,
3201
+ message: outcome.message
3202
+ });
3203
+ } catch (error) {
3204
+ results.push({
3205
+ id,
3206
+ ok: false,
3207
+ claimed: false,
3208
+ state: "failed",
3209
+ amount: 0,
3210
+ message: error instanceof Error ? error.message : String(error)
3211
+ });
3212
+ }
3213
+ return summarizeClaims(results);
3214
+ };
2833
3215
  ctx.inject(["webServer"], (webCtx) => registerCodeArtsStatusRoute(webCtx, {
2834
3216
  store,
2835
3217
  models: () => catalog.current(),
@@ -2848,62 +3230,17 @@ function apply(ctx, rawConfig) {
2848
3230
  },
2849
3231
  dock,
2850
3232
  setDock,
2851
- claim: async (accountId) => {
2852
- const ids = accountId === void 0 ? await store.ids() : [accountId];
2853
- if (ids.length === 0) return {
2854
- ok: false,
2855
- claimed: false,
2856
- state: "failed",
2857
- amount: 0,
2858
- message: "no usable credential"
2859
- };
2860
- const results = [];
2861
- for (const id of ids) try {
2862
- const stored = await store.credential(id);
2863
- if (stored === void 0 || stored.stale === true) {
2864
- results.push({
2865
- id,
2866
- ok: false,
2867
- claimed: false,
2868
- state: "failed",
2869
- amount: 0,
2870
- message: stored === void 0 ? "account not found" : "account needs sign-in"
2871
- });
2872
- continue;
2873
- }
2874
- const resolved = await store.resolve(id);
2875
- if (resolved === void 0) {
2876
- results.push({
2877
- id,
2878
- ok: false,
2879
- claimed: false,
2880
- state: "failed",
2881
- amount: 0,
2882
- message: "no usable credential"
2883
- });
2884
- continue;
2885
- }
2886
- const outcome = await claimDailyWelfare(resolved, AbortSignal.timeout(2e4));
2887
- if (outcome.state === "claimed") credits.invalidate(id);
2888
- results.push({
2889
- id,
2890
- ok: outcome.state !== "failed",
2891
- claimed: outcome.state === "claimed",
2892
- state: outcome.state,
2893
- amount: outcome.amount,
2894
- message: outcome.message
2895
- });
2896
- } catch (error) {
2897
- results.push({
2898
- id,
2899
- ok: false,
2900
- claimed: false,
2901
- state: "failed",
2902
- amount: 0,
2903
- message: error instanceof Error ? error.message : String(error)
2904
- });
2905
- }
2906
- return summarizeClaims(results);
3233
+ keeper: keeperView,
3234
+ stopKeeper: async () => {
3235
+ const outcome = await stopKeeper();
3236
+ keeperSpawnedAt = 0;
3237
+ return outcome;
3238
+ },
3239
+ claim: claimAll,
3240
+ autoClaim: async () => {
3241
+ const outcome = await claimAll();
3242
+ outcome.claimed, outcome.state, outcome.amount, outcome.message;
3243
+ return outcome;
2907
3244
  },
2908
3245
  refreshModels: async () => {
2909
3246
  const outcome = await refreshCatalog(store, catalog, AbortSignal.timeout(MANUAL_REFRESH_MS));
@@ -2918,8 +3255,13 @@ function apply(ctx, rawConfig) {
2918
3255
  installSettingsSectionCompat(ctx, CODEARTS_SETTINGS_NS, Config, config, {
2919
3256
  setSource(source) {
2920
3257
  current = () => unwrapConfig(source());
3258
+ armAutoClaim();
3259
+ armKeepAliveDaemon();
2921
3260
  },
2922
- onChange() {}
3261
+ onChange() {
3262
+ armAutoClaim();
3263
+ armKeepAliveDaemon();
3264
+ }
2923
3265
  });
2924
3266
  let stopped = false;
2925
3267
  ctx.effect(() => () => {
@@ -2967,18 +3309,126 @@ function apply(ctx, rawConfig) {
2967
3309
  abort.abort();
2968
3310
  if (discoveryTimer !== void 0) clearTimeout(discoveryTimer);
2969
3311
  });
3312
+ /**
3313
+ * 凭证保活:每 20 分钟把所有「快过期」的账号提前续掉。
3314
+ *
3315
+ * 为什么必须有这个循环:上游签发的 token 有效期是固定的 2 小时(实测,见
3316
+ * `auth.ts` 的 `REFRESH_SKEW_MS` 注释),而 `ensureFresh` 只在「有请求进来」时才被
3317
+ * 触发。用户开着 DSH 却不聊天时没有任何请求,凭证就一路裸奔到过期 —— 表现就是
3318
+ * 「隔天就要重新登录」。有了这个循环,只要 DSH 活着,凭证就不会真的到期。
3319
+ *
3320
+ * 间隔 20 分钟 + 续期阈值 30 分钟 = 剩 30 分钟以内一定会被扫到至少一次。
3321
+ * 关掉 DSH 就无从保活(插件不在进程里),那部分只能靠下次启动时重新登录,
3322
+ * 这是纯客户端方案的硬边界,卡片文案里必须讲明白。
3323
+ */
3324
+ const KEEP_ALIVE_INTERVAL_MS = 12e5;
3325
+ let keepAliveTimer;
3326
+ const keepAliveLoop = async () => {
3327
+ if (stopped) return;
3328
+ if (keeperRunning()) await store.reloadFromDisk().catch(() => {});
3329
+ else try {
3330
+ const outcome = await store.keepAlive();
3331
+ if (outcome.refreshed > 0) ctx.logger.debug(`dsh-codearts: refreshed ${outcome.refreshed} credential(s) in the background`);
3332
+ if (outcome.needsLogin.length > 0) ctx.logger.debug(`dsh-codearts: ${outcome.needsLogin.length} account(s) need a fresh sign-in`);
3333
+ } catch (error) {
3334
+ ctx.logger.debug("dsh-codearts: credential keep-alive failed; will retry", error);
3335
+ }
3336
+ if (stopped) return;
3337
+ keepAliveTimer = setTimeout(() => void keepAliveLoop(), KEEP_ALIVE_INTERVAL_MS);
3338
+ keepAliveTimer.unref?.();
3339
+ };
3340
+ /**
3341
+ * 自动领取每日签到积分。
3342
+ *
3343
+ * 节奏的取舍:上游按天去重(重复领返回 40001 → already),所以多领不会出事;
3344
+ * 但也正因为幂等,**没必要**高频轮询 —— 单号一天只值 200 分,每 10 秒刷一次的
3345
+ * 上行成本和风控风险都远大于收益。取「启动后 30 秒试一次 + 失败才退避重试
3346
+ * (30 分钟一次、最多 3 次)」:装了就领到,领不到也不无限缠着上游。
3347
+ *
3348
+ * 终止条件:任意一轮里「有号真领到」或「所有号都是 already/unavailable」就停。
3349
+ * 只有 genuinely 失败(网络、凭据异常)才值得再试。
3350
+ */
3351
+ const AUTO_CLAIM_FIRST_DELAY_MS = 3e4;
3352
+ const AUTO_CLAIM_RETRY_MS = 18e5;
3353
+ const AUTO_CLAIM_MAX_TRIES = 3;
3354
+ let autoClaimTimer;
3355
+ let autoClaimTries = 0;
3356
+ /** 自我重排的自动领取循环;开关关掉时直接不排下一轮,下次打开才重新开始。 */
3357
+ const autoClaimLoop = async () => {
3358
+ if (stopped) return;
3359
+ if (!dock().autoClaim) {
3360
+ autoClaimTimer = void 0;
3361
+ return;
3362
+ }
3363
+ autoClaimTries += 1;
3364
+ let retry = false;
3365
+ try {
3366
+ const outcome = await claimAll();
3367
+ outcome.claimed, outcome.state, outcome.amount, outcome.message;
3368
+ if (outcome.claimed) ctx.logger.debug(`dsh-codearts: auto-claimed daily credits (${outcome.amount})`);
3369
+ else if (outcome.state === "failed") retry = true;
3370
+ } catch (error) {
3371
+ retry = true;
3372
+ ctx.logger.debug("dsh-codearts: auto-claim failed; will retry", error);
3373
+ }
3374
+ if (stopped) return;
3375
+ if (!retry || autoClaimTries >= AUTO_CLAIM_MAX_TRIES) {
3376
+ autoClaimTimer = void 0;
3377
+ return;
3378
+ }
3379
+ autoClaimTimer = setTimeout(() => void autoClaimLoop(), AUTO_CLAIM_RETRY_MS);
3380
+ autoClaimTimer.unref?.();
3381
+ };
3382
+ /** 按当前开关状态(重新)拉起自动领取;开关关掉时把在等的定时器撤掉。 */
3383
+ const armAutoClaim = () => {
3384
+ if (stopped) return;
3385
+ if (!dock().autoClaim) {
3386
+ if (autoClaimTimer !== void 0) clearTimeout(autoClaimTimer);
3387
+ autoClaimTimer = void 0;
3388
+ autoClaimTries = 0;
3389
+ return;
3390
+ }
3391
+ if (autoClaimTimer !== void 0) return;
3392
+ autoClaimTries = 0;
3393
+ autoClaimTimer = setTimeout(() => void autoClaimLoop(), AUTO_CLAIM_FIRST_DELAY_MS);
3394
+ autoClaimTimer.unref?.();
3395
+ };
3396
+ ctx.effect(() => () => {
3397
+ if (keepAliveTimer !== void 0) clearTimeout(keepAliveTimer);
3398
+ if (autoClaimTimer !== void 0) clearTimeout(autoClaimTimer);
3399
+ if (keeperTimer !== void 0) clearTimeout(keeperTimer);
3400
+ });
3401
+ /**
3402
+ * 槽位取证日志:acquire/release 的时间点与在飞计数。
3403
+ *
3404
+ * 默认关闭(只有 `DSH_CODEARTS_DEBUG=1` 时写)。issue #8 里「只剩一个在飞请求,
3405
+ * 但所有 acquire 都失败」的怀疑,只能靠这份日志证实或排除。
3406
+ */
3407
+ const writeDebugLog = process.env.DSH_CODEARTS_DEBUG === "1" ? (message) => {
3408
+ try {
3409
+ const path = codeartsDebugLogPath();
3410
+ try {
3411
+ if (statSync(path).size > 2e6) writeFileSync(path, "");
3412
+ } catch {}
3413
+ appendFileSync(path, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`, { mode: 384 });
3414
+ } catch {}
3415
+ } : void 0;
2970
3416
  const shim = createCodeArtsShim({
2971
3417
  store,
2972
3418
  catalog,
2973
3419
  pool,
2974
3420
  usage,
2975
3421
  queue,
2976
- logger: ctx.logger
3422
+ logger: ctx.logger,
3423
+ debug: writeDebugLog
2977
3424
  });
2978
3425
  usage.load().catch(() => {});
2979
3426
  shim.ready.then(async () => {
2980
3427
  if (stopped) return;
2981
3428
  discoverLoop();
3429
+ keepAliveLoop();
3430
+ armAutoClaim();
3431
+ armKeepAliveDaemon();
2982
3432
  const incompatible = await probePiAiCompat();
2983
3433
  if (incompatible !== void 0) ctx.logger.error(`dsh-codearts: ${incompatible}`);
2984
3434
  const codearts = createCodeArtsAdapter({