dsh-codearts 1.2.14 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs CHANGED
@@ -1,5 +1,8 @@
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, d as startLogin, i as codeartsAccountsPath, n as CodeArtsCredentialStore, o as credentialFromOAuth, r as MANUAL_ACCOUNT_ID, t as CodeArtsAccountStore } from "./auth-CF9XHMX-.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-CJTTrulR.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-P4FkDUEd.mjs";
3
6
  import z from "@deepseek-ai/schemastery";
4
7
  import { randomBytes, timingSafeEqual } from "node:crypto";
5
8
  import { createServer } from "node:http";
@@ -1584,6 +1587,15 @@ const CODEARTS_QUEUE_PATH = "/api/codearts/queue";
1584
1587
  * GET 给当前值与 writable,POST 收 `{credits?, queue?}` 写进 settings。
1585
1588
  */
1586
1589
  const CODEARTS_DOCK_PATH = "/api/codearts/dock";
1590
+ /**
1591
+ * POST /api/codearts/keeper/stop — 结束常驻守护进程,并把开关**同时**关掉。
1592
+ *
1593
+ * 为什么必须在服务端把开关一起关:进程被 kill 之后,「开关开着但没进程」是个自相
1594
+ * 矛盾的状态。若只杀进程不改开关,用户下次打开 DSH 会看到开关还是开的、PID 却是空
1595
+ * 的,以为功能坏了;而且插件会按「开关是开的」去重起它 —— 用户刚 kill 掉的东西自己
1596
+ * 又回来了。所以这两件事必须原子地一起做。
1597
+ */
1598
+ const CODEARTS_KEEPER_STOP_PATH = "/api/codearts/keeper/stop";
1587
1599
  /** 最近出站请求的**形状**摘要(只有 role 名与计数,不含内容),排障用。 */
1588
1600
  const CODEARTS_DEBUG_PATH = "/api/codearts/debug";
1589
1601
  /**
@@ -1657,11 +1669,15 @@ function modelBadgesOf(models) {
1657
1669
  /**
1658
1670
  * 开关的默认值:没有 settings provider(或老配置没这两个键)时保持原有行为 ——
1659
1671
  * 底部两行都显示;侧边栏相反,缺省不开(那一格是所有插件共用的全局座位)。
1672
+ * `modelDetail` 缺省开(保持老版本的样子),`autoClaim` 缺省关。
1660
1673
  */
1661
1674
  const DEFAULT_DOCK_FLAGS = {
1662
1675
  credits: true,
1663
1676
  queue: true,
1664
- sidebar: false
1677
+ sidebar: false,
1678
+ modelDetail: true,
1679
+ autoClaim: false,
1680
+ keepAliveDaemon: false
1665
1681
  };
1666
1682
  /**
1667
1683
  * 把逐账号的领取结果汇总成一条:HTTP 层只看 ok,卡片看 results 逐号展示。
@@ -1874,6 +1890,7 @@ async function buildStatus(deps, force = false) {
1874
1890
  const cred = await deps.store.current();
1875
1891
  const usage = usageOf(deps);
1876
1892
  const dock = deps.dock === void 0 ? {} : { dock: deps.dock() };
1893
+ const keeperView = deps.keeper === void 0 ? {} : { keeper: await deps.keeper() };
1877
1894
  const piAi = await probePiAiCompat();
1878
1895
  const compat = piAi === void 0 ? {} : { piAiError: piAi };
1879
1896
  if (accounts.length === 0 || cred === void 0) return {
@@ -1882,6 +1899,7 @@ async function buildStatus(deps, force = false) {
1882
1899
  accounts,
1883
1900
  usage,
1884
1901
  ...dock,
1902
+ ...keeperView,
1885
1903
  ...compat
1886
1904
  };
1887
1905
  const usable = accounts.some(accountUsable);
@@ -1891,7 +1909,8 @@ async function buildStatus(deps, force = false) {
1891
1909
  models,
1892
1910
  accounts,
1893
1911
  usage,
1894
- ...dock
1912
+ ...dock,
1913
+ ...keeperView
1895
1914
  };
1896
1915
  if (!usable) return {
1897
1916
  status: "expired",
@@ -2041,10 +2060,13 @@ function dockHandler(deps) {
2041
2060
  const touched = [
2042
2061
  "credits",
2043
2062
  "queue",
2044
- "sidebar"
2063
+ "sidebar",
2064
+ "modelDetail",
2065
+ "autoClaim",
2066
+ "keepAliveDaemon"
2045
2067
  ].filter((key) => body[key] !== void 0);
2046
2068
  if (touched.length === 0 || touched.some((key) => typeof body[key] !== "boolean")) {
2047
- json(res, 400, { error: "expected {\"credits\"?: boolean, \"queue\"?: boolean, \"sidebar\"?: boolean}" });
2069
+ json(res, 400, { error: "expected {\"credits\"?: boolean, \"queue\"?: boolean, \"sidebar\"?: boolean, \"modelDetail\"?: boolean, \"autoClaim\"?: boolean, \"keepAliveDaemon\"?: boolean}" });
2048
2070
  return;
2049
2071
  }
2050
2072
  if (!await deps.setDock(Object.fromEntries(touched.map((key) => [key, body[key]])))) {
@@ -2063,6 +2085,42 @@ function dockHandler(deps) {
2063
2085
  json(res, 405, { error: "method not allowed" });
2064
2086
  };
2065
2087
  }
2088
+ /**
2089
+ * POST /api/codearts/keeper/stop — 结束守护进程,并把开关一起关掉。
2090
+ *
2091
+ * 顺序不能反:先杀进程、再写开关。反过来的话,写开关的那一瞬间如果正好触发了插件的
2092
+ * 重排(`armKeepAliveDaemon`),它会按「开关是开的」再起一个 —— 用户点一次结束,
2093
+ * 结果又冒出来一个新 pid。杀完再写,重排看到的是 false,自然什么都不做。
2094
+ */
2095
+ function keeperStopHandler(deps) {
2096
+ return async (req, res) => {
2097
+ if (!loopbackRequest(req)) {
2098
+ json(res, 403, { error: "request-not-trusted" });
2099
+ return;
2100
+ }
2101
+ if (req.method !== "POST") {
2102
+ json(res, 405, { error: "method not allowed" });
2103
+ return;
2104
+ }
2105
+ if (deps.stopKeeper === void 0) {
2106
+ json(res, 503, { error: "keeper-control-unavailable" });
2107
+ return;
2108
+ }
2109
+ try {
2110
+ const outcome = await deps.stopKeeper();
2111
+ const writable = deps.setDock === void 0 ? false : await deps.setDock({ keepAliveDaemon: false }).catch(() => false);
2112
+ json(res, outcome.ok ? 200 : 500, {
2113
+ ok: outcome.ok,
2114
+ ...outcome.pid === void 0 ? {} : { pid: outcome.pid },
2115
+ ...outcome.reason === void 0 ? {} : { reason: outcome.reason },
2116
+ writable,
2117
+ dock: deps.dock?.() ?? DEFAULT_DOCK_FLAGS
2118
+ });
2119
+ } catch (error) {
2120
+ json(res, 500, { error: safeMessage(error) });
2121
+ }
2122
+ };
2123
+ }
2066
2124
  /** GET /api/codearts/models — currently offered model ids (honours allowlist). */
2067
2125
  function modelsHandler(deps) {
2068
2126
  return async (req, res) => {
@@ -2538,6 +2596,11 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2538
2596
  path: CODEARTS_DOCK_PATH,
2539
2597
  handler: dockHandler(deps)
2540
2598
  });
2599
+ const disposeKeeperStop = ctx.webServer.register({
2600
+ kind: "exact",
2601
+ path: CODEARTS_KEEPER_STOP_PATH,
2602
+ handler: keeperStopHandler(deps)
2603
+ });
2541
2604
  const disposeDebug = ctx.webServer.register({
2542
2605
  kind: "exact",
2543
2606
  path: CODEARTS_DEBUG_PATH,
@@ -2561,6 +2624,7 @@ function registerCodeArtsStatusRoute(ctx, deps) {
2561
2624
  disposeTestModel();
2562
2625
  disposeQueue();
2563
2626
  disposeDock();
2627
+ disposeKeeperStop();
2564
2628
  disposeDebug();
2565
2629
  disposeDoctor();
2566
2630
  for (const s of activeLogins.values()) s.close();
@@ -2740,7 +2804,10 @@ const Config = z.object({
2740
2804
  enabledModels: z.array(z.string()).description("Model ids offered in the model pickers (empty means every model)").volatile(),
2741
2805
  showCreditDock: z.boolean().default(true).description("Show the remaining-credits line under the chat input box").volatile(),
2742
2806
  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()
2807
+ showSidebarPanel: z.boolean().default(false).description("Show a CodeArts icon in the DSH sidebar icon column, opening this page in the middle column").volatile(),
2808
+ showModelDetailDock: z.boolean().default(true).description("Show \"Model … · x ratio\" on the line under the chat input box (Provider CodeArts always shows)").volatile(),
2809
+ autoClaim: z.boolean().default(false).description("Automatically claim the daily sign-in credits for every signed-in account").volatile(),
2810
+ keepAliveDaemon: z.boolean().default(false).description("Keep a detached background process that refreshes the OAuth credential while DSH is closed").volatile()
2744
2811
  });
2745
2812
  function settingsCompatNamespace(ctx) {
2746
2813
  return resolveSettingsNamespaceCompat(ctx, ctx.get("settings"), CODEARTS_SETTINGS_NS);
@@ -2757,6 +2824,11 @@ function apply(ctx, rawConfig) {
2757
2824
  /** /status 是卡片与对话底部都会轮询的接口,积分慢请求不能把它拖成转圈。 */
2758
2825
  const CREDIT_TIMEOUT_MS = 8e3;
2759
2826
  /**
2827
+ * 领取签到积分的单号预算。福利中心偶尔很慢(要拉活动列表再认领),给足 20 秒,
2828
+ * 但必须有个上限:自动领取是在后台跑的,卡死的请求会把这个号的后续重试全堵住。
2829
+ */
2830
+ const CLAIM_TIMEOUT_MS = 2e4;
2831
+ /**
2760
2832
  * 拉一次积分(每个账号各自一份)。
2761
2833
  *
2762
2834
  * 积分是**账号级**属性:多账号下每个号的余额、到期、签到状态都不同,所以逐号
@@ -2816,7 +2888,10 @@ function apply(ctx, rawConfig) {
2816
2888
  const dock = () => ({
2817
2889
  credits: current().showCreditDock !== false,
2818
2890
  queue: current().showQueueDock !== false,
2819
- sidebar: current().showSidebarPanel === true
2891
+ sidebar: current().showSidebarPanel === true,
2892
+ modelDetail: current().showModelDetailDock !== false,
2893
+ autoClaim: current().autoClaim === true,
2894
+ keepAliveDaemon: current().keepAliveDaemon === true
2820
2895
  });
2821
2896
  const setDock = async (patch) => {
2822
2897
  const settings = ctx.get("settings");
@@ -2824,12 +2899,201 @@ function apply(ctx, rawConfig) {
2824
2899
  await settings.update(settingsCompatNamespace(ctx), {
2825
2900
  ...patch.credits === void 0 ? {} : { showCreditDock: patch.credits },
2826
2901
  ...patch.queue === void 0 ? {} : { showQueueDock: patch.queue },
2827
- ...patch.sidebar === void 0 ? {} : { showSidebarPanel: patch.sidebar }
2902
+ ...patch.sidebar === void 0 ? {} : { showSidebarPanel: patch.sidebar },
2903
+ ...patch.modelDetail === void 0 ? {} : { showModelDetailDock: patch.modelDetail },
2904
+ ...patch.autoClaim === void 0 ? {} : { autoClaim: patch.autoClaim },
2905
+ ...patch.keepAliveDaemon === void 0 ? {} : { keepAliveDaemon: patch.keepAliveDaemon }
2828
2906
  });
2829
2907
  return true;
2830
2908
  };
2831
2909
  /** 手动「刷新模型列表」的预算:三路来源各打一次,比每小时的后台刷新更该给足时间。 */
2832
2910
  const MANUAL_REFRESH_MS = 6e4;
2911
+ /**
2912
+ * 守护进程:当前活着吗。
2913
+ *
2914
+ * 「活着」= 状态文件里心跳新鲜 **且** 那个 pid 真能探到(`keeper.ts` 里两个条件都查)。
2915
+ * 只看心跳会把刚被 kill 的进程当成活的 —— 心跳是它死前 30 秒内写的,不会自己消失。
2916
+ */
2917
+ const keeperRunning = () => keeperStats().alive;
2918
+ /**
2919
+ * 刚点开开关、守护进程还没写出状态文件的那段时间。
2920
+ *
2921
+ * 秒级的进程启动 + 首次 `writeKeeperState` 之间确实有一段「探不到活」的窗口。
2922
+ * 不区分的话,卡片刚被勾上就会因为「没探到进程」而自己把开关关掉 —— 用户看到的是
2923
+ * 勾了一下马上弹回去。这段时间里 `alive` 仍是 false(它确实还没活),但带 `starting`。
2924
+ */
2925
+ const KEEPER_START_GRACE_MS = KEEPER_STALE_MS;
2926
+ const keeperView = async () => {
2927
+ const logPath = keeperLogPath();
2928
+ const stats = keeperStats();
2929
+ if (stats.alive && stats.state !== void 0) {
2930
+ keeperLastError = void 0;
2931
+ return {
2932
+ alive: true,
2933
+ pid: stats.state.pid,
2934
+ startedAt: stats.state.startedAt,
2935
+ heartbeatAt: stats.state.heartbeatAt,
2936
+ ...stats.state.lastPass === void 0 ? {} : { lastPass: stats.state.lastPass },
2937
+ logPath
2938
+ };
2939
+ }
2940
+ if (!(current().keepAliveDaemon === true)) return {
2941
+ alive: false,
2942
+ logPath
2943
+ };
2944
+ if (Date.now() - keeperSpawnedAt < KEEPER_START_GRACE_MS) return {
2945
+ alive: false,
2946
+ starting: true,
2947
+ ...keeperLastError === void 0 ? {} : { error: keeperLastError },
2948
+ logPath
2949
+ };
2950
+ try {
2951
+ await setDock({ keepAliveDaemon: false });
2952
+ } catch {}
2953
+ return {
2954
+ alive: false,
2955
+ error: keeperLastError ?? "守护进程已退出,已自动关闭保活开关",
2956
+ logPath
2957
+ };
2958
+ };
2959
+ /**
2960
+ * 常驻守护进程:在 DSH 之外续 refresh_token。
2961
+ *
2962
+ * 与上面 `keepAliveLoop` 的分工:那个只在 DSH 活着时有用,关掉 DSH 就没了;这个起的是
2963
+ * 一个 detached 进程,DSH 退出后它还在,20 分钟续一次,把 30 天有效期的 refresh_token
2964
+ * 一直续下去 —— 这才是「十几天不用重新登录」的正解。
2965
+ *
2966
+ * refresh_token 是一次性的:两边同时刷会让后刷的一方拿着作废的 token 失败。所以开关
2967
+ * 打开时 `keepAliveLoop` 会主动让路(只从磁盘重读),刷新权独占在守护进程手里。
2968
+ */
2969
+ const KEEPER_ENSURE_MS = 6e4;
2970
+ let keeperSpawnedAt = 0;
2971
+ let keeperLastError;
2972
+ let keeperTimer;
2973
+ /**
2974
+ * 按开关状态把守护进程拉起来。
2975
+ *
2976
+ * 只在「开关刚被打开」时调用(`armKeepAliveDaemon`)。**不做定时重起**:用户明确要求
2977
+ * 「被 kill 了开关就关掉」,而不是「被 kill 了自己又冒出来」—— 后者正是用户按了结束
2978
+ * 却看到进程又活了的那种体验。
2979
+ */
2980
+ const ensureKeeper = () => {
2981
+ if (stopped) return;
2982
+ if (current().keepAliveDaemon !== true) return;
2983
+ if (keeperRunning()) return;
2984
+ const outcome = spawnKeeper({
2985
+ scriptPath: keeperScriptPath(),
2986
+ pluginVersion: CODEARTS_VERSION
2987
+ });
2988
+ keeperSpawnedAt = Date.now();
2989
+ if (outcome.ok) {
2990
+ keeperLastError = void 0;
2991
+ ctx.logger.debug(`dsh-codearts: credential keeper running (pid ${outcome.pid ?? "?"})`);
2992
+ } else {
2993
+ keeperLastError = outcome.reason ?? "spawn failed";
2994
+ ctx.logger.debug(`dsh-codearts: credential keeper failed to start: ${keeperLastError}`);
2995
+ }
2996
+ };
2997
+ /**
2998
+ * 守护巡检:只在旁边看着,不重起。
2999
+ *
3000
+ * 三种结局:开关被关掉 → 收工;进程还活着 → 继续看;进程没了(超出启动宽限期)→
3001
+ * 把开关关掉并收工。判死必须在服务端做,不能只靠卡片轮询 —— 卡片没打开时也得让
3002
+ * 那个「开着却空转」的开关自己消失。
3003
+ */
3004
+ const keeperLoop = async () => {
3005
+ if (stopped) return;
3006
+ if (current().keepAliveDaemon !== true) {
3007
+ keeperTimer = void 0;
3008
+ return;
3009
+ }
3010
+ if (!keeperRunning() && Date.now() - keeperSpawnedAt >= KEEPER_START_GRACE_MS) {
3011
+ keeperTimer = void 0;
3012
+ keeperSpawnedAt = 0;
3013
+ await setDock({ keepAliveDaemon: false }).catch(() => false);
3014
+ return;
3015
+ }
3016
+ keeperTimer = setTimeout(() => void keeperLoop(), KEEPER_ENSURE_MS);
3017
+ keeperTimer.unref?.();
3018
+ };
3019
+ /** 开关变化时立刻响应:打开就马上起,关掉就撤掉巡检(进程本身留给「结束」按钮)。 */
3020
+ const armKeepAliveDaemon = () => {
3021
+ if (stopped) return;
3022
+ if (current().keepAliveDaemon !== true) {
3023
+ if (keeperTimer !== void 0) clearTimeout(keeperTimer);
3024
+ keeperTimer = void 0;
3025
+ keeperSpawnedAt = 0;
3026
+ return;
3027
+ }
3028
+ if (keeperTimer !== void 0) return;
3029
+ ensureKeeper();
3030
+ keeperTimer = setTimeout(() => void keeperLoop(), KEEPER_ENSURE_MS);
3031
+ keeperTimer.unref?.();
3032
+ };
3033
+ /**
3034
+ * 逐号领取每日签到积分。
3035
+ *
3036
+ * 手动「领取」按钮和后台自动领取走的是**同一条**路径,只是入口不同:领的是什么、
3037
+ * 失败怎么归类、什么时候作废缓存,两处必须完全一致,否则「手动能领到、自动领不到」
3038
+ * 这种差异排查起来极其费劲。
3039
+ */
3040
+ const claimAll = async (accountId) => {
3041
+ const ids = accountId === void 0 ? await store.ids() : [accountId];
3042
+ if (ids.length === 0) return {
3043
+ ok: false,
3044
+ claimed: false,
3045
+ state: "failed",
3046
+ amount: 0,
3047
+ message: "no usable credential"
3048
+ };
3049
+ const results = [];
3050
+ for (const id of ids) try {
3051
+ const stored = await store.credential(id);
3052
+ if (stored === void 0 || stored.stale === true) {
3053
+ results.push({
3054
+ id,
3055
+ ok: false,
3056
+ claimed: false,
3057
+ state: "failed",
3058
+ amount: 0,
3059
+ message: stored === void 0 ? "account not found" : "account needs sign-in"
3060
+ });
3061
+ continue;
3062
+ }
3063
+ const resolved = await store.resolve(id);
3064
+ if (resolved === void 0) {
3065
+ results.push({
3066
+ id,
3067
+ ok: false,
3068
+ claimed: false,
3069
+ state: "failed",
3070
+ amount: 0,
3071
+ message: "no usable credential"
3072
+ });
3073
+ continue;
3074
+ }
3075
+ const outcome = await claimDailyWelfare(resolved, AbortSignal.timeout(CLAIM_TIMEOUT_MS));
3076
+ if (outcome.state === "claimed") credits.invalidate(id);
3077
+ results.push({
3078
+ id,
3079
+ ok: outcome.state !== "failed",
3080
+ claimed: outcome.state === "claimed",
3081
+ state: outcome.state,
3082
+ amount: outcome.amount,
3083
+ message: outcome.message
3084
+ });
3085
+ } catch (error) {
3086
+ results.push({
3087
+ id,
3088
+ ok: false,
3089
+ claimed: false,
3090
+ state: "failed",
3091
+ amount: 0,
3092
+ message: error instanceof Error ? error.message : String(error)
3093
+ });
3094
+ }
3095
+ return summarizeClaims(results);
3096
+ };
2833
3097
  ctx.inject(["webServer"], (webCtx) => registerCodeArtsStatusRoute(webCtx, {
2834
3098
  store,
2835
3099
  models: () => catalog.current(),
@@ -2848,62 +3112,17 @@ function apply(ctx, rawConfig) {
2848
3112
  },
2849
3113
  dock,
2850
3114
  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);
3115
+ keeper: keeperView,
3116
+ stopKeeper: async () => {
3117
+ const outcome = await stopKeeper();
3118
+ keeperSpawnedAt = 0;
3119
+ return outcome;
3120
+ },
3121
+ claim: claimAll,
3122
+ autoClaim: async () => {
3123
+ const outcome = await claimAll();
3124
+ outcome.claimed, outcome.state, outcome.amount, outcome.message;
3125
+ return outcome;
2907
3126
  },
2908
3127
  refreshModels: async () => {
2909
3128
  const outcome = await refreshCatalog(store, catalog, AbortSignal.timeout(MANUAL_REFRESH_MS));
@@ -2918,8 +3137,13 @@ function apply(ctx, rawConfig) {
2918
3137
  installSettingsSectionCompat(ctx, CODEARTS_SETTINGS_NS, Config, config, {
2919
3138
  setSource(source) {
2920
3139
  current = () => unwrapConfig(source());
3140
+ armAutoClaim();
3141
+ armKeepAliveDaemon();
2921
3142
  },
2922
- onChange() {}
3143
+ onChange() {
3144
+ armAutoClaim();
3145
+ armKeepAliveDaemon();
3146
+ }
2923
3147
  });
2924
3148
  let stopped = false;
2925
3149
  ctx.effect(() => () => {
@@ -2967,6 +3191,95 @@ function apply(ctx, rawConfig) {
2967
3191
  abort.abort();
2968
3192
  if (discoveryTimer !== void 0) clearTimeout(discoveryTimer);
2969
3193
  });
3194
+ /**
3195
+ * 凭证保活:每 20 分钟把所有「快过期」的账号提前续掉。
3196
+ *
3197
+ * 为什么必须有这个循环:上游签发的 token 有效期是固定的 2 小时(实测,见
3198
+ * `auth.ts` 的 `REFRESH_SKEW_MS` 注释),而 `ensureFresh` 只在「有请求进来」时才被
3199
+ * 触发。用户开着 DSH 却不聊天时没有任何请求,凭证就一路裸奔到过期 —— 表现就是
3200
+ * 「隔天就要重新登录」。有了这个循环,只要 DSH 活着,凭证就不会真的到期。
3201
+ *
3202
+ * 间隔 20 分钟 + 续期阈值 30 分钟 = 剩 30 分钟以内一定会被扫到至少一次。
3203
+ * 关掉 DSH 就无从保活(插件不在进程里),那部分只能靠下次启动时重新登录,
3204
+ * 这是纯客户端方案的硬边界,卡片文案里必须讲明白。
3205
+ */
3206
+ const KEEP_ALIVE_INTERVAL_MS = 12e5;
3207
+ let keepAliveTimer;
3208
+ const keepAliveLoop = async () => {
3209
+ if (stopped) return;
3210
+ if (keeperRunning()) await store.reloadFromDisk().catch(() => {});
3211
+ else try {
3212
+ const outcome = await store.keepAlive();
3213
+ if (outcome.refreshed > 0) ctx.logger.debug(`dsh-codearts: refreshed ${outcome.refreshed} credential(s) in the background`);
3214
+ if (outcome.needsLogin.length > 0) ctx.logger.debug(`dsh-codearts: ${outcome.needsLogin.length} account(s) need a fresh sign-in`);
3215
+ } catch (error) {
3216
+ ctx.logger.debug("dsh-codearts: credential keep-alive failed; will retry", error);
3217
+ }
3218
+ if (stopped) return;
3219
+ keepAliveTimer = setTimeout(() => void keepAliveLoop(), KEEP_ALIVE_INTERVAL_MS);
3220
+ keepAliveTimer.unref?.();
3221
+ };
3222
+ /**
3223
+ * 自动领取每日签到积分。
3224
+ *
3225
+ * 节奏的取舍:上游按天去重(重复领返回 40001 → already),所以多领不会出事;
3226
+ * 但也正因为幂等,**没必要**高频轮询 —— 单号一天只值 200 分,每 10 秒刷一次的
3227
+ * 上行成本和风控风险都远大于收益。取「启动后 30 秒试一次 + 失败才退避重试
3228
+ * (30 分钟一次、最多 3 次)」:装了就领到,领不到也不无限缠着上游。
3229
+ *
3230
+ * 终止条件:任意一轮里「有号真领到」或「所有号都是 already/unavailable」就停。
3231
+ * 只有 genuinely 失败(网络、凭据异常)才值得再试。
3232
+ */
3233
+ const AUTO_CLAIM_FIRST_DELAY_MS = 3e4;
3234
+ const AUTO_CLAIM_RETRY_MS = 18e5;
3235
+ const AUTO_CLAIM_MAX_TRIES = 3;
3236
+ let autoClaimTimer;
3237
+ let autoClaimTries = 0;
3238
+ /** 自我重排的自动领取循环;开关关掉时直接不排下一轮,下次打开才重新开始。 */
3239
+ const autoClaimLoop = async () => {
3240
+ if (stopped) return;
3241
+ if (!dock().autoClaim) {
3242
+ autoClaimTimer = void 0;
3243
+ return;
3244
+ }
3245
+ autoClaimTries += 1;
3246
+ let retry = false;
3247
+ try {
3248
+ const outcome = await claimAll();
3249
+ outcome.claimed, outcome.state, outcome.amount, outcome.message;
3250
+ if (outcome.claimed) ctx.logger.debug(`dsh-codearts: auto-claimed daily credits (${outcome.amount})`);
3251
+ else if (outcome.state === "failed") retry = true;
3252
+ } catch (error) {
3253
+ retry = true;
3254
+ ctx.logger.debug("dsh-codearts: auto-claim failed; will retry", error);
3255
+ }
3256
+ if (stopped) return;
3257
+ if (!retry || autoClaimTries >= AUTO_CLAIM_MAX_TRIES) {
3258
+ autoClaimTimer = void 0;
3259
+ return;
3260
+ }
3261
+ autoClaimTimer = setTimeout(() => void autoClaimLoop(), AUTO_CLAIM_RETRY_MS);
3262
+ autoClaimTimer.unref?.();
3263
+ };
3264
+ /** 按当前开关状态(重新)拉起自动领取;开关关掉时把在等的定时器撤掉。 */
3265
+ const armAutoClaim = () => {
3266
+ if (stopped) return;
3267
+ if (!dock().autoClaim) {
3268
+ if (autoClaimTimer !== void 0) clearTimeout(autoClaimTimer);
3269
+ autoClaimTimer = void 0;
3270
+ autoClaimTries = 0;
3271
+ return;
3272
+ }
3273
+ if (autoClaimTimer !== void 0) return;
3274
+ autoClaimTries = 0;
3275
+ autoClaimTimer = setTimeout(() => void autoClaimLoop(), AUTO_CLAIM_FIRST_DELAY_MS);
3276
+ autoClaimTimer.unref?.();
3277
+ };
3278
+ ctx.effect(() => () => {
3279
+ if (keepAliveTimer !== void 0) clearTimeout(keepAliveTimer);
3280
+ if (autoClaimTimer !== void 0) clearTimeout(autoClaimTimer);
3281
+ if (keeperTimer !== void 0) clearTimeout(keeperTimer);
3282
+ });
2970
3283
  const shim = createCodeArtsShim({
2971
3284
  store,
2972
3285
  catalog,
@@ -2979,6 +3292,9 @@ function apply(ctx, rawConfig) {
2979
3292
  shim.ready.then(async () => {
2980
3293
  if (stopped) return;
2981
3294
  discoverLoop();
3295
+ keepAliveLoop();
3296
+ armAutoClaim();
3297
+ armKeepAliveDaemon();
2982
3298
  const incompatible = await probePiAiCompat();
2983
3299
  if (incompatible !== void 0) ctx.logger.error(`dsh-codearts: ${incompatible}`);
2984
3300
  const codearts = createCodeArtsAdapter({