dsh-xdpool 3.0.8 → 3.0.9

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/README.md CHANGED
@@ -7,25 +7,9 @@
7
7
  <a href="https://github.com/XDTrees/dsh-xdpool/stargazers"><img src="https://img.shields.io/github/stars/XDTrees/dsh-xdpool?style=flat-square" alt="GitHub stars"></a>
8
8
  </p>
9
9
 
10
- ## 更新公告
11
-
12
- **3.0.8** — 账号昵称与模型列表按渠道读取、优先账号开关、CodeArts 图片输入、登录签到提速。
13
-
14
- - 修复账号池页整页错乱:账号卡回到详情列里,只在选中 WorkBuddy 国内版/国际版时显示
15
- - 修复一键更新「更新了但版本号一直没变」:现在会同步 lockfile 和 node_modules,不再被 DSH 启动时装回旧版
16
- - pi-ai 代际守卫修正宿主路径,mismatch / aligned / unknown 都会写进启动日志,切 xdpool 模型崩溃时不再毫无线索
17
-
18
- **3.0.6** — 账号卡重做。
19
-
20
- - 账号池页的账号卡重画成自包含的卡片:昵称、状态徽章(当前使用 / 已停用 / 冷却中)、令牌到期、积分、以及优先/停用/签到/移出池子一排按钮
21
- - 3.0.4 那一版卡片沿用了旧组件,会挤成一行、互相重叠 —— 已修
22
- - 撤掉右上角的关闭按钮(宿主的设置面板认不出它,点了没反应)
23
-
24
- **3.0.5** — 没登录不再显示模型;写账号表时拒绝「空表覆盖非空表」。
25
-
26
- **3.0.4** — 账号卡回到账号池页、模型选择器不再出现两份、登录通道页算上插件池账号。
27
-
28
- **3.0.3** — 豆包每个模型用自己的思考档位、全关真的会空、积分自动化「立即执行」。
10
+ <p align="center">
11
+ <img src="assets/xdpool-banner.gif" alt="XD Pool 字标扫光动画">
12
+ </p>
29
13
 
30
14
  ## 先加群
31
15
 
@@ -35,7 +19,7 @@
35
19
  <img src="assets/community-qr-qq.jpg" width="240" alt="QQ 群二维码:直接扫码加入 XD 交流群">
36
20
  <br>
37
21
  <b>左:微信(机器人)</b> —— 扫码添加机器人后<b>发送「XD」</b>,它才会拉你进群;只扫码不加不发是不会有反应的。<br>
38
- <b>右:QQ 群</b> —— 直接扫码即可加入,群号 1103463688。
22
+ <b>右:QQ 群</b> —— 直接扫码即可加入(2 群),群号 1139040898;旧群号 1103463688(已满)。
39
23
  <br>
40
24
  <sub>两个群都在,哪个方便用哪个。二维码失效了在 <a href="https://github.com/XDTrees/dsh-xdpool/issues">issues</a> 说一声会换新。</sub>
41
25
  <br>
@@ -43,7 +27,7 @@
43
27
  </p>
44
28
 
45
29
  <p align="center">
46
- <sub>下载量徽章读的是 npm 上 <code>dsh-xdpool</code> 自己的实时统计,不再是改名前的快照。</sub>
30
+ <sub>觉得这个池子有用?<a href="https://afdian.com/a/XDtrees">在爱发电上支持一下</a>。</sub>
47
31
  </p>
48
32
 
49
33
  [English](./README.en.md) | 中文
Binary file
Binary file
Binary file
package/cordis.patch.yml CHANGED
@@ -1,24 +1,24 @@
1
- # Register the XD Pool provider. Discovery is read-only: the plugin reuses the
2
- # WorkBuddy desktop app's own sign-in files and never starts a separate OAuth
3
- # flow. Requests rotate across every discovered account.
4
- - insert:
5
- - id: llm-xdpool
6
- name: dsh-xdpool
7
- #
8
- # billion-context is gone from this plugin, and so is the row that used to sit
9
- # here (`billion-context-xdpool`, kept disabled).
10
- #
11
- # 2.0.0 inserted that row so a profile without the compressor would get one for
12
- # free. Measured against a profile that had ALREADY installed billion-context —
13
- # the normal state for anyone using it, since `bili-native` comes from that
14
- # plugin's own `dsh.bundle.patch.yml` — the host did not disable the duplicate
15
- # and did not resolve it to a no-op: it ran the fiber to `failed`, because the
16
- # plugin registers a cordis service under its own name and a second registration
17
- # is refused outright (`service "…" has been registered at <…>`). Every user who
18
- # had installed it got a permanently failed entry, unexplained, pointing at us.
19
- #
20
- # The follow-up kept the row, disabled, "for addressability". That was the wrong
21
- # trade: it left a name in this file for a feature the plugin no longer has, and
22
- # the page that read it (`billion-context`) is deleted too. Installing the
23
- # compressor is its own decision, made by installing it — which is the
24
- # arrangement that always worked.
1
+ # Register the XD Pool provider. Discovery is read-only: the plugin reuses the
2
+ # WorkBuddy desktop app's own sign-in files and never starts a separate OAuth
3
+ # flow. Requests rotate across every discovered account.
4
+ - insert:
5
+ - id: llm-xdpool
6
+ name: dsh-xdpool
7
+ #
8
+ # billion-context is gone from this plugin, and so is the row that used to sit
9
+ # here (`billion-context-xdpool`, kept disabled).
10
+ #
11
+ # 2.0.0 inserted that row so a profile without the compressor would get one for
12
+ # free. Measured against a profile that had ALREADY installed billion-context —
13
+ # the normal state for anyone using it, since `bili-native` comes from that
14
+ # plugin's own `dsh.bundle.patch.yml` — the host did not disable the duplicate
15
+ # and did not resolve it to a no-op: it ran the fiber to `failed`, because the
16
+ # plugin registers a cordis service under its own name and a second registration
17
+ # is refused outright (`service "…" has been registered at <…>`). Every user who
18
+ # had installed it got a permanently failed entry, unexplained, pointing at us.
19
+ #
20
+ # The follow-up kept the row, disabled, "for addressability". That was the wrong
21
+ # trade: it left a name in this file for a feature the plugin no longer has, and
22
+ # the page that read it (`billion-context`) is deleted too. Installing the
23
+ # compressor is its own decision, made by installing it — which is the
24
+ # arrangement that always worked.
package/lib/bin.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { createDecipheriv, createHash, randomUUID } from "node:crypto";
3
3
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
4
- import { chmod, copyFile, mkdir, readFile, readdir, rename, rm, unlink, writeFile, writeFile as writeFile$1 } from "node:fs/promises";
5
- import { homedir, platform } from "node:os";
4
+ import { chmod, copyFile, mkdir, open, readFile, readdir, rename, rm, unlink, writeFile, writeFile as writeFile$1 } from "node:fs/promises";
5
+ import { homedir, hostname, platform } from "node:os";
6
6
  import { basename, dirname, join, resolve } from "node:path";
7
7
  import { execFile, execFileSync } from "node:child_process";
8
8
  import "@deepseek-ai/dsh-llm";
@@ -2834,6 +2834,59 @@ async function unignoreAccount(accountId, path = ignoredIdsPath()) {
2834
2834
  return next;
2835
2835
  }
2836
2836
  //#endregion
2837
+ //#region src/store-lock.ts
2838
+ /**
2839
+ * Serialize the read-modify-write cycles on a store file.
2840
+ *
2841
+ * WHY THIS IS NEEDED
2842
+ *
2843
+ * Every credential store does the same three steps: load the list, replace one entry, write the
2844
+ * list back. Two of those interleaved lose one entry — the second write starts from a list that
2845
+ * predates the first, so the entry the first added is simply absent from what lands on disk. It
2846
+ * is not a rare race either: signing into two channels of the same family in quick succession is
2847
+ * ordinary use, and a lost credential looks exactly like a sign-in that never worked.
2848
+ *
2849
+ * The atomic `rename` most of these stores already do makes the FILE consistent; it does not
2850
+ * make the READ-MODIFY-WRITE consistent, which is a different guarantee.
2851
+ *
2852
+ * HOW
2853
+ *
2854
+ * One promise chain per file path. Each cycle appends to the chain, so the cycles run one after
2855
+ * another in the order they were requested. A failure does not poison the chain — the next
2856
+ * caller still runs — and the chain is dropped once it drains, so a long-lived process does not
2857
+ * accumulate promises.
2858
+ *
2859
+ * @module dsh-xdpool/store-lock
2860
+ */
2861
+ /** The tail of each path's chain. */
2862
+ const chains = /* @__PURE__ */ new Map();
2863
+ /**
2864
+ * Run `work` once every earlier call for the same key has settled.
2865
+ *
2866
+ * The key is normally the store's absolute path: two stores in different files do not contend,
2867
+ * and two writers of the same file must not interleave.
2868
+ */
2869
+ async function withStoreLock(key, work) {
2870
+ /**
2871
+ * `previous.catch` keeps a rejected earlier cycle from skipping this one: the chain exists to
2872
+ * order writes, not to propagate failures.
2873
+ */
2874
+ const next = (chains.get(key) ?? Promise.resolve()).catch(() => void 0).then(work);
2875
+ const guarded = next.catch(() => void 0);
2876
+ chains.set(key, guarded);
2877
+ try {
2878
+ return await next;
2879
+ } finally {
2880
+ /**
2881
+ * Drop the entry once nothing is queued behind it.
2882
+ *
2883
+ * Without this the map grows with every store the process ever touched — small, but it also
2884
+ * keeps every resolved promise alive for the life of the session.
2885
+ */
2886
+ if (chains.get(key) === guarded) chains.delete(key);
2887
+ }
2888
+ }
2889
+ //#endregion
2837
2890
  //#region src/account-store.ts
2838
2891
  /**
2839
2892
  * Durable copy of the discovered accounts, inside the plugin's data directory.
@@ -2884,43 +2937,205 @@ function isStoredAccount(value) {
2884
2937
  if (typeof value !== "object" || value === null) return false;
2885
2938
  const record = value;
2886
2939
  const credential = record["credential"];
2887
- return typeof record["id"] === "string" && typeof record["label"] === "string" && typeof credential === "object" && credential !== null && typeof credential["accessToken"] === "string" && typeof credential["refreshToken"] === "string";
2940
+ return typeof record["id"] === "string" && typeof record["label"] === "string" && typeof credential === "object" && credential !== null && typeof credential["accessToken"] === "string" && typeof credential["refreshToken"] === "string" && typeof credential["sourcePath"] === "string" && typeof credential["domain"] === "string" && Number.isFinite(credential["expiresAtMs"]);
2888
2941
  }
2889
- /**
2890
- * Read the durable list. Tolerant on purpose: a malformed or half-written file
2891
- * yields `[]` and the pool simply rediscovers from disk, rather than a corrupt
2892
- * store taking the whole pool down.
2893
- */
2894
- async function loadStoredAccounts(path) {
2942
+ async function inspectStore(path) {
2895
2943
  let text;
2896
2944
  try {
2897
2945
  text = await readFile(path, "utf8");
2946
+ } catch (error) {
2947
+ if (error.code === "ENOENT") return {
2948
+ accounts: [],
2949
+ safe: true
2950
+ };
2951
+ throw error;
2952
+ }
2953
+ try {
2954
+ const document = JSON.parse(text);
2955
+ if (document?.version !== 1 || !Array.isArray(document.accounts)) return {
2956
+ text,
2957
+ accounts: [],
2958
+ safe: false
2959
+ };
2960
+ const accounts = [];
2961
+ const seen = /* @__PURE__ */ new Set();
2962
+ let safe = true;
2963
+ for (const entry of document.accounts) {
2964
+ if (!isStoredAccount(entry) || seen.has(entry.id)) {
2965
+ safe = false;
2966
+ continue;
2967
+ }
2968
+ seen.add(entry.id);
2969
+ accounts.push(entry);
2970
+ }
2971
+ return {
2972
+ text,
2973
+ accounts,
2974
+ safe
2975
+ };
2898
2976
  } catch {
2899
- return [];
2977
+ return {
2978
+ text,
2979
+ accounts: [],
2980
+ safe: false
2981
+ };
2900
2982
  }
2901
- let parsed;
2983
+ }
2984
+ /** Keep the old primary present until replacement; every temporary has a unique name. */
2985
+ async function replaceSecret(path, text) {
2986
+ const temporary = `${path}.${randomUUID()}.tmp`;
2902
2987
  try {
2903
- parsed = JSON.parse(text);
2988
+ await writeSecretFile(temporary, text);
2989
+ await rename(temporary, path);
2990
+ } finally {
2991
+ await unlink(temporary).catch((error) => {
2992
+ if (error.code !== "ENOENT") throw error;
2993
+ });
2994
+ }
2995
+ }
2996
+ /**
2997
+ * How long one transaction waits for a live holder before giving up.
2998
+ *
2999
+ * Read per call rather than at import time so a test can shorten the wait; the
3000
+ * default is the production 5 s.
3001
+ */
3002
+ function storeLockWaitMs() {
3003
+ const raw = Number(process.env["DSH_XDPOOL_STORE_LOCK_WAIT_MS"] ?? "");
3004
+ return Number.isSafeInteger(raw) && raw >= 50 ? raw : 5e3;
3005
+ }
3006
+ /** Read the owner record, or undefined when the file cannot prove one. */
3007
+ async function readStoreLockOwner(lockPath) {
3008
+ try {
3009
+ const parsed = JSON.parse(await readFile(lockPath, "utf8"));
3010
+ if (typeof parsed.pid !== "number" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0) return void 0;
3011
+ return {
3012
+ pid: parsed.pid,
3013
+ host: typeof parsed.host === "string" ? parsed.host : "",
3014
+ startedAt: typeof parsed.startedAt === "string" ? parsed.startedAt : ""
3015
+ };
2904
3016
  } catch {
2905
- return [];
3017
+ return;
2906
3018
  }
2907
- const entries = parsed?.["accounts"];
2908
- if (!Array.isArray(entries)) return [];
2909
- const out = [];
2910
- const seen = /* @__PURE__ */ new Set();
2911
- for (const entry of entries) {
2912
- if (!isStoredAccount(entry)) continue;
2913
- if (seen.has(entry.id)) continue;
2914
- seen.add(entry.id);
2915
- out.push(entry);
3019
+ }
3020
+ /**
3021
+ * Whether the recorded owner is provably gone.
3022
+ *
3023
+ * Only a PID from THIS host can be judged; another machine's lock stays
3024
+ * untouchable because its PID numbers mean nothing here. A PID that still
3025
+ * exists counts as alive even when its holder is unrelated (EPERM), and a
3026
+ * reused PID can therefore only ever make us MORE conservative.
3027
+ */
3028
+ function storeLockOwnerIsDead(owner) {
3029
+ if (owner.host !== hostname()) return false;
3030
+ try {
3031
+ process.kill(owner.pid, 0);
3032
+ return false;
3033
+ } catch (error) {
3034
+ return error.code === "ESRCH";
2916
3035
  }
2917
- return out;
2918
3036
  }
2919
3037
  /**
2920
- * Atomically write the durable list: `${path}.tmp` first, then rename. A crash
2921
- * mid-write leaves the previous generation intact.
3038
+ * Serialize the entire scan/read/merge/write, including across cooperating processes.
3039
+ *
3040
+ * A lock whose recorded owner is provably dead is reclaimed once; anything else
3041
+ * fails closed, because a live holder must never have its write interleaved.
3042
+ *
3043
+ * This used to fail closed for EVERY orphan as well, which bricked the store:
3044
+ * a crash between create and release left an empty lock that the plugin then
3045
+ * refused to pass forever — no write, no repair, and no way out short of
3046
+ * deleting the file by hand (found on the real profile, 2026-12-05).
3047
+ */
3048
+ async function withAccountStoreTransaction(path, work) {
3049
+ return withStoreLock(path, async () => {
3050
+ await ensureSecretDir(join(path, ".."));
3051
+ const lockPath = `${path}.lock`;
3052
+ const deadline = Date.now() + storeLockWaitMs();
3053
+ let handle;
3054
+ let reclaimed = false;
3055
+ while (handle === void 0) try {
3056
+ handle = await open(lockPath, "wx", 384);
3057
+ const owner = {
3058
+ pid: process.pid,
3059
+ host: hostname(),
3060
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
3061
+ };
3062
+ await handle.write(JSON.stringify(owner));
3063
+ } catch (error) {
3064
+ if (handle !== void 0) {
3065
+ await handle.close().catch(() => void 0);
3066
+ await unlink(lockPath).catch(() => void 0);
3067
+ handle = void 0;
3068
+ }
3069
+ if (error.code !== "EEXIST") throw error;
3070
+ if (Date.now() >= deadline) {
3071
+ if (!reclaimed) {
3072
+ const owner = await readStoreLockOwner(lockPath);
3073
+ if (owner !== void 0 && storeLockOwnerIsDead(owner)) {
3074
+ await unlink(lockPath).catch(() => void 0);
3075
+ reclaimed = true;
3076
+ continue;
3077
+ }
3078
+ throw new Error(`Account store is locked by ${owner === void 0 ? "an unidentifiable owner (no readable owner record)" : `pid ${owner.pid} on ${owner.host} since ${owner.startedAt}`}; lock file: ${lockPath}. If that process is gone, remove the file or run the plugin's "unlock" command.`);
3079
+ }
3080
+ throw new Error(`Account store stayed locked after reclaiming a dead owner; lock file: ${lockPath}`);
3081
+ }
3082
+ await new Promise((resolve) => setTimeout(resolve, 25));
3083
+ }
3084
+ try {
3085
+ return await work();
3086
+ } finally {
3087
+ await handle.close();
3088
+ await unlink(lockPath);
3089
+ }
3090
+ });
3091
+ }
3092
+ /**
3093
+ * Read valid records with diagnostics. A damaged primary is never rewritten;
3094
+ * a validated previous generation can supply missing records in memory.
3095
+ */
3096
+ async function loadStoredAccounts(path, warn = (message) => process.emitWarning(message)) {
3097
+ const primary = await inspectStore(path);
3098
+ if (primary.safe) return primary.accounts;
3099
+ warn("Account store has invalid entries or structure; preserving the original and blocking replacement");
3100
+ const backup = await inspectStore(`${path}.bak`);
3101
+ if (!backup.safe) throw new Error("Account store and backup are invalid; manual recovery required");
3102
+ const merged = new Map(primary.accounts.map((account) => [account.id, account]));
3103
+ for (const account of backup.accounts) if (!merged.has(account.id)) merged.set(account.id, account);
3104
+ return [...merged.values()];
3105
+ }
3106
+ /**
3107
+ * Back up the validated primary before replacing it with a unique temporary.
3108
+ * The caller must hold the transaction over its entire read/merge/write cycle.
2922
3109
  */
2923
3110
  async function saveStoredAccounts(path, accounts) {
3111
+ const previous = await inspectStore(path);
3112
+ /**
3113
+ * An invalid primary is quarantined rather than written over.
3114
+ *
3115
+ * Refusing outright left the store permanently unwritable: the pool kept
3116
+ * serving from the backup-derived list in memory, but every new sign-in was
3117
+ * lost on the next restart and nothing ever repaired the file. Moving the bad
3118
+ * generation aside keeps it for diagnosis (it is never deleted) while letting
3119
+ * a validated backup become the new baseline.
3120
+ *
3121
+ * The damaged text deliberately does NOT become the new `.bak`: that slot is
3122
+ * the last known-good generation, and overwriting it with garbage would turn
3123
+ * one corrupt file into two. When even the backup is unusable, nothing is
3124
+ * touched and the caller keeps the manual-recovery error.
3125
+ */
3126
+ let quarantined;
3127
+ if (!previous.safe) {
3128
+ const backup = await inspectStore(`${path}.bak`);
3129
+ /**
3130
+ * Rebuilding needs a backup that actually holds something.
3131
+ *
3132
+ * An absent or empty backup would turn "repair" into "replace the user's list with whatever
3133
+ * is in memory", and a damaged file may still be hand-recoverable. Those cases keep refusing.
3134
+ */
3135
+ if (backup.text === void 0 || !backup.safe || backup.accounts.length === 0) throw new Error("Refusing to overwrite an invalid account store; original preserved for recovery");
3136
+ quarantined = `${path}.corrupt-${(/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-").replaceAll(".", "-")}`;
3137
+ await rename(path, quarantined);
3138
+ }
2924
3139
  const stored = accounts.map((account) => ({
2925
3140
  id: account.id,
2926
3141
  label: account.label,
@@ -2932,9 +3147,9 @@ async function saveStoredAccounts(path, accounts) {
2932
3147
  accounts: stored
2933
3148
  }, null, 2) + "\n";
2934
3149
  await ensureSecretDir(join(path, ".."));
2935
- const tmp = `${path}.tmp`;
2936
- await writeSecretFile(tmp, document);
2937
- await rename(tmp, path);
3150
+ if (quarantined === void 0 && previous.text !== void 0) await replaceSecret(`${path}.bak`, previous.text);
3151
+ await replaceSecret(path, document);
3152
+ if (quarantined !== void 0) process.emitWarning(`dsh-xdpool: account store was invalid and has been preserved at ${quarantined}; the list was rebuilt from the last good backup`);
2938
3153
  }
2939
3154
  //#endregion
2940
3155
  //#region src/at-rest.ts
@@ -3771,9 +3986,9 @@ function isChannelPackSource(path) {
3771
3986
  * cleared. The live file stays on top: that is the session the running desktop
3772
3987
  * app is genuinely using right now, and it is newer than anything we mint.
3773
3988
  */
3774
- function compareFreshness(a, b) {
3989
+ function compareFreshness(a, b, liveCredentials) {
3775
3990
  const rankOf = (credential) => {
3776
- if (isLiveAuthFile(credential.sourcePath)) return 2;
3991
+ if (liveCredentials.has(credential)) return 2;
3777
3992
  if (isChannelPackSource(credential.sourcePath)) return 1;
3778
3993
  return 0;
3779
3994
  };
@@ -3786,8 +4001,8 @@ function compareFreshness(a, b) {
3786
4001
  return b.expiresAtMs - a.expiresAtMs;
3787
4002
  }
3788
4003
  /** True when `candidate` should replace `incumbent` for the same account. */
3789
- function isFresher(candidate, incumbent) {
3790
- return compareFreshness(candidate, incumbent) < 0;
4004
+ function isFresher(candidate, incumbent, liveCredentials) {
4005
+ return compareFreshness(candidate, incumbent, liveCredentials) < 0;
3791
4006
  }
3792
4007
  function workbuddyAccountId(credential) {
3793
4008
  const stable = credential.uin ?? credential.uid ?? credential.nickname ?? "unknown";
@@ -4262,6 +4477,8 @@ var WorkBuddyAccountPool = class {
4262
4477
  */
4263
4478
  lastUsedAt = /* @__PURE__ */ new Map();
4264
4479
  refreshInflight = /* @__PURE__ */ new Map();
4480
+ /** Three-way reconciliation anchor: only advanced after a successful store write. */
4481
+ persistedCredentials = /* @__PURE__ */ new Map();
4265
4482
  /**
4266
4483
  * Whether `scan()` seeds from and writes back the durable account store.
4267
4484
  *
@@ -4401,6 +4618,10 @@ var WorkBuddyAccountPool = class {
4401
4618
  }
4402
4619
  /** Rescan the auth directories and merge newly discovered accounts. */
4403
4620
  async scan() {
4621
+ if (this.persistent) return withAccountStoreTransaction(this.storePath, () => this.scanTransaction());
4622
+ return this.scanTransaction();
4623
+ }
4624
+ async scanTransaction() {
4404
4625
  const found = [];
4405
4626
  const skipped = [];
4406
4627
  /**
@@ -4485,13 +4706,36 @@ var WorkBuddyAccountPool = class {
4485
4706
  } catch (error) {
4486
4707
  this.logger?.warn?.("dsh-xdpool: could not read channel-pack accounts; desktop accounts only", error);
4487
4708
  }
4709
+ const liveCredentials = new Set(found.filter((credential) => isLiveAuthFile(credential.sourcePath)));
4488
4710
  const byId = /* @__PURE__ */ new Map();
4489
4711
  for (const account of this.accounts) byId.set(account.id, account);
4490
4712
  if (this.persistent) {
4491
- const stored = await loadStoredAccounts(this.storePath);
4713
+ const stored = await loadStoredAccounts(this.storePath, (message) => {
4714
+ if (this.logger?.warn !== void 0) this.logger.warn(message);
4715
+ else process.emitWarning(message);
4716
+ });
4492
4717
  for (const entry of stored) {
4493
4718
  if (this.ignoredIds.size > 0 && this.ignoredIds.has(entry.id)) continue;
4494
- if (byId.has(entry.id)) continue;
4719
+ const existing = byId.get(entry.id);
4720
+ if (existing !== void 0) {
4721
+ const anchor = this.persistedCredentials.get(entry.id);
4722
+ const memory = JSON.stringify(existing.credential);
4723
+ const disk = JSON.stringify(entry.credential);
4724
+ if (anchor !== void 0 && disk !== anchor && memory !== disk) {
4725
+ if (memory !== anchor) throw new Error(`Account store conflict for ${entry.id}; both versions preserved, no write performed`);
4726
+ byId.set(entry.id, {
4727
+ ...existing,
4728
+ credential: entry.credential,
4729
+ label: entry.label,
4730
+ credentialDeadUntilMs: 0
4731
+ });
4732
+ } else if (anchor === void 0 && isFresher(entry.credential, existing.credential, liveCredentials)) byId.set(entry.id, {
4733
+ ...existing,
4734
+ credential: entry.credential,
4735
+ label: entry.label
4736
+ });
4737
+ continue;
4738
+ }
4495
4739
  byId.set(entry.id, {
4496
4740
  id: entry.id,
4497
4741
  label: entry.label,
@@ -4525,7 +4769,7 @@ var WorkBuddyAccountPool = class {
4525
4769
  });
4526
4770
  continue;
4527
4771
  }
4528
- if (isFresher(credential, existing.credential)) {
4772
+ if (isFresher(credential, existing.credential, liveCredentials)) {
4529
4773
  const signedInAgain = credential.refreshToken !== existing.credential.refreshToken || credential.accessToken !== existing.credential.accessToken;
4530
4774
  byId.set(id, {
4531
4775
  ...existing,
@@ -4536,7 +4780,7 @@ var WorkBuddyAccountPool = class {
4536
4780
  }
4537
4781
  }
4538
4782
  const ordered = [...byId.values()];
4539
- ordered.sort((a, b) => compareFreshness(a.credential, b.credential));
4783
+ ordered.sort((a, b) => compareFreshness(a.credential, b.credential, liveCredentials));
4540
4784
  this.accounts = ordered;
4541
4785
  this.lastScanAtMs = Date.now();
4542
4786
  this.warmExpiryReadings();
@@ -4544,6 +4788,7 @@ var WorkBuddyAccountPool = class {
4544
4788
  const leaving = this.lastPersistedIds === void 0 ? [] : [...this.lastPersistedIds].filter((id) => !this.accounts.some((account) => account.id === id));
4545
4789
  if (leaving.length > 0) this.logger?.warn?.(`dsh-xdpool: ${String(leaving.length)} account(s) are no longer in the pool after a rescan and were removed from the store: ${leaving.join(", ")}. Their credentials are gone unless they are signed in again.`);
4546
4790
  await saveStoredAccounts(this.storePath, this.accounts);
4791
+ this.persistedCredentials = new Map(this.accounts.map((account) => [account.id, JSON.stringify(account.credential)]));
4547
4792
  this.lastPersistedIds = new Set(this.accounts.map((account) => account.id));
4548
4793
  } catch (error) {
4549
4794
  this.logger?.warn?.("dsh-xdpool: could not persist the account store", error);
@@ -4819,6 +5064,13 @@ var WorkBuddyAccountPool = class {
4819
5064
  }
4820
5065
  usable += 1;
4821
5066
  }
5067
+ if (usable > 0) return {
5068
+ total: inRegion.length,
5069
+ cooling,
5070
+ disabled,
5071
+ dead,
5072
+ reason: "none"
5073
+ };
4822
5074
  if (dead > 0) return {
4823
5075
  total: inRegion.length,
4824
5076
  cooling,
@@ -6205,18 +6457,8 @@ var WorkBuddyCatalog = class {
6205
6457
  * is recoverable in one click whereas "nothing" looks like a broken install.
6206
6458
  */
6207
6459
  const allow = enabled === void 0 || enabled.length === 0 ? void 0 : new Set(enabled);
6208
- /**
6209
- * Same reading, and here it is the difference between "images on" and "images off".
6210
- *
6211
- * `enabledModelIds` degrades safely when an empty list is misread — the "everything is
6212
- * enabled" recovery is one click away. `imageModelIds` does not: an empty set overrides
6213
- * every `supportsImages: true` the upstream gateway reported, so a config that never chose
6214
- * (the schema used to write `[]` by default) published the whole pool as text-only and
6215
- * the host refused image attachments. A host that HAS saved a selection still wins — the
6216
- * set is only consulted once something is actually in it.
6217
- */
6218
6460
  const images = this.selection.imageModelIds;
6219
- const imageSet = images === void 0 || images.length === 0 ? void 0 : new Set(images);
6461
+ const imageSet = images === void 0 ? void 0 : new Set(images);
6220
6462
  const budgets = this.selection.contextBudgets;
6221
6463
  return sortFreeFirst(this.models.filter((model) => allow === void 0 || allow.has(model.id)).map((model) => {
6222
6464
  const next = { ...model };
@@ -12322,10 +12564,24 @@ var WorkBuddyScheduler = class {
12322
12564
  * ignored rather than queued: pressing the button twice means hurry up, and
12323
12565
  * the run already under way covers it.
12324
12566
  */
12325
- startRunAll(job = "all", force = false) {
12567
+ startRunAll() {
12568
+ return this.startRun("all");
12569
+ }
12570
+ /**
12571
+ * Start one job — or the whole pass — in the background.
12572
+ *
12573
+ * The card's automation row names a job, and `force` is what a second press
12574
+ * within the same hour means. Both used to be dropped on the floor by the
12575
+ * route wiring, so "run check-in" ran every job and a repeat press inside the
12576
+ * hour silently did nothing. A single-job start goes through the same
12577
+ * in-flight guard as a full pass: overlapping passes would double-spend the
12578
+ * per-account delays and interleave two runs into one status document.
12579
+ */
12580
+ startRun(kind, force = false) {
12326
12581
  if (this.runInFlight) return false;
12582
+ if (!force && kind !== "all" && this.states[kind].lastFiredHour === slotKey(this.now())) return false;
12327
12583
  this.runInFlight = true;
12328
- (job === "all" ? this.runAll() : this.runNow(job, force).then(() => void 0)).catch((error) => {
12584
+ (kind === "all" ? this.runAll() : this.runNow(kind, force).then(() => void 0)).catch((error) => {
12329
12585
  this.logger.warn?.("dsh-xdpool automation run failed:", error);
12330
12586
  }).finally(() => {
12331
12587
  this.runInFlight = false;
@@ -13468,16 +13724,7 @@ z.object({
13468
13724
  disabledAccountIds: asVolatile(z.array(z.string()).default([]).description("Account ids excluded from the pool (empty = every discovered account participates)")),
13469
13725
  creditReserves: asVolatile(z.dict(z.number().step(1).min(0)).default({}).description("Per-account credit floor: stop using an account once its balance reaches this value")),
13470
13726
  enabledModelIds: asVolatile(z.array(z.string()).default([]).description("Legacy shared model-id list; used by a region that has no per-region selection yet")),
13471
- /**
13472
- * No `.default([])` on purpose.
13473
- *
13474
- * A default makes "never chose" and "chose none" the same JSON, and the two are read very
13475
- * differently downstream: absent means "follow the upstream image flag", while an empty list
13476
- * overrides it to "no model accepts images". With the default, every fresh install and every
13477
- * document written before this key existed started out text-only — the host then refused
13478
- * every attachment for models the gateway serves with `supportsImages: true`.
13479
- */
13480
- imageModelIds: asVolatile(z.array(z.string()).description("Legacy shared image-id list; used by a region that has no per-region selection yet (absent = follow the upstream image flag)")),
13727
+ imageModelIds: asVolatile(z.array(z.string()).description("Legacy shared image-id list; used by a region that has no per-region selection yet")),
13481
13728
  contextBudgets: asVolatile(z.dict(z.number().step(1).min(1)).default({}).description("Legacy shared context budgets; used by a region with no per-region selection yet")),
13482
13729
  modelSelectionCn: asVolatile(modelSelectionSchema.description("Model selection for the domestic gateway")),
13483
13730
  modelSelectionGlobal: asVolatile(modelSelectionSchema.description("Model selection for the international gateway")),
@@ -13586,6 +13833,7 @@ function usage() {
13586
13833
  " status Account pool, credits, and shim state (add --credits, --json, --rates)",
13587
13834
  " doctor Diagnose discovery, cooldowns, and upstream reachability",
13588
13835
  " accounts List discovered accounts (add --json)",
13836
+ " unlock Remove a leftover account-store lock after reporting its owner",
13589
13837
  " import <key> Snapshot the current desktop login as <key> (add --force)",
13590
13838
  " remove <key> Delete one imported snapshot",
13591
13839
  " ignore <acct> Drop an account from the pool for good (id or label)",
@@ -13812,6 +14060,54 @@ async function commandDoctor() {
13812
14060
  console.log(lines.join("\n"));
13813
14061
  return healthy ? 0 : 1;
13814
14062
  }
14063
+ /**
14064
+ * Remove a leftover account-store lock.
14065
+ *
14066
+ * The transaction writes its owner (pid, host) into the lock file and reclaims
14067
+ * a provably dead owner on its own. This command covers what that rule cannot:
14068
+ * a lock whose owner record never made it to disk (an older build, or a crash
14069
+ * between create and record), or a lock whose owner belongs to another host.
14070
+ *
14071
+ * It never removes a lock owned by the running process, and it prints what it
14072
+ * found first, so a user pasting the output gives enough to reconstruct what
14073
+ * happened.
14074
+ */
14075
+ async function commandUnlock(args) {
14076
+ const asJson = args.includes("--json");
14077
+ const lockPath = join(accountDir(), `${ACCOUNTS_FILE_NAME}.lock`);
14078
+ let raw;
14079
+ try {
14080
+ raw = await readFile(lockPath, "utf8");
14081
+ } catch (error) {
14082
+ if (error.code === "ENOENT") {
14083
+ console.log(asJson ? JSON.stringify({
14084
+ lock: lockPath,
14085
+ present: false
14086
+ }) : `No account-store lock at ${lockPath}.`);
14087
+ return 0;
14088
+ }
14089
+ throw error;
14090
+ }
14091
+ let owner;
14092
+ try {
14093
+ owner = JSON.parse(raw);
14094
+ } catch {
14095
+ owner = void 0;
14096
+ }
14097
+ if (owner?.pid === process.pid) {
14098
+ console.error(`Refusing to remove ${lockPath}: it is owned by this process (pid ${process.pid}).`);
14099
+ return 1;
14100
+ }
14101
+ await unlink(lockPath);
14102
+ const described = owner?.pid === void 0 ? "no owner record" : `pid ${owner.pid} on ${owner.host} since ${owner.startedAt}`;
14103
+ console.log(asJson ? JSON.stringify({
14104
+ lock: lockPath,
14105
+ removed: true,
14106
+ owner,
14107
+ described
14108
+ }) : `Removed account-store lock ${lockPath} (${described}).`);
14109
+ return 0;
14110
+ }
13815
14111
  async function commandImport(args) {
13816
14112
  const key = args.filter((arg) => !arg.startsWith("--"))[0];
13817
14113
  if (key === void 0) {
@@ -14042,6 +14338,7 @@ async function main(argv) {
14042
14338
  case "status": return commandStatus(rest);
14043
14339
  case "doctor": return commandDoctor();
14044
14340
  case "accounts": return commandAccounts(rest);
14341
+ case "unlock": return commandUnlock(rest);
14045
14342
  case "import": return commandImport(rest);
14046
14343
  case "remove": return commandRemove(rest);
14047
14344
  case "ignore": return commandIgnore(rest, true);