dsh-xdpool 3.0.7 → 3.0.8

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/bin.js CHANGED
@@ -44,8 +44,221 @@ import "@deepseek-ai/dsh-llm-pi-ai";
44
44
  */
45
45
  /** Prefix the CN gateway uses for a promotion badge inside `tags`. */
46
46
  const BADGE_TAG_PREFIX = "badge:";
47
+ /**
48
+ * The one badge label that means "free right now".
49
+ *
50
+ * A name check rather than a position check, so a gateway that reorders or adds
51
+ * other badges keeps working.
52
+ */
53
+ const BADGE_FREE_LABEL = "限时免费";
54
+ /** A `#`-prefixed hex colour of 3–8 digits, which is what CSS accepts. */
55
+ const COLOR_TAIL = /^[0-9A-Fa-f]{3,8}$/;
56
+ /**
57
+ * Split the `badge:<label>:#RRGGBB` entries the CN gateway puts in `tags`.
58
+ *
59
+ * `#` may legitimately occur inside a label, so the split happens on the LAST
60
+ * one and the tail is only accepted as a colour when it actually looks like
61
+ * one — otherwise a label such as `C#` would silently lose its last character.
62
+ *
63
+ * Returns an empty array for `undefined` so callers can iterate unconditionally.
64
+ */
65
+ function parseBadgeTags(tags) {
66
+ const out = [];
67
+ for (const tag of tags ?? []) {
68
+ if (!tag.startsWith("badge:")) continue;
69
+ const rest = tag.slice(6);
70
+ const hash = rest.lastIndexOf("#");
71
+ const tail = hash === -1 ? "" : rest.slice(hash + 1);
72
+ const isColor = hash !== -1 && COLOR_TAIL.test(tail);
73
+ const cut = (hash === -1 ? rest : rest.slice(0, hash)).trim();
74
+ const label = isColor ? cut.replace(/:$/, "").trim() : cut;
75
+ if (label === "") continue;
76
+ out.push(isColor ? {
77
+ label,
78
+ color: tail
79
+ } : { label });
80
+ }
81
+ return out;
82
+ }
83
+ /**
84
+ * Whether any badge declares the model free right now.
85
+ *
86
+ * Distinct from the multiplier check in `isFreeModel`: this is the upstream
87
+ * volunteering the fact, which is what lets the card show "限时免费" for a model
88
+ * whose `credits` string never said zero.
89
+ */
90
+ function hasFreeBadge(tags) {
91
+ return parseBadgeTags(tags).some((badge) => badge.label === BADGE_FREE_LABEL);
92
+ }
93
+ /**
94
+ * Which free presentation wins for one row: the gateway's own badge, or the
95
+ * generic `免费`.
96
+ *
97
+ * The badge branch is gated on the FREE badge, not on "has any badge": the CN
98
+ * roster also writes `badge:夜间折扣` on `glm-5.2`, which is priced at `x0.79`
99
+ * and still costs credits. Reporting a discount row as free would change what
100
+ * the user spends, which is the one thing this plugin must never get wrong.
101
+ * Callers that want to SHOW a non-free badge ask `badgeLabels` separately.
102
+ *
103
+ * Ordered so the free badge wins over the generic label, because `限时免费`
104
+ * ("free, for a limited time") names the part that expires, which the generic
105
+ * label cannot. `undefined` means the row is not free at all and the caller
106
+ * should fall through to its other tag rules.
107
+ *
108
+ * A separately-sorted "is it free right now" question is answered by
109
+ * `isFreeNow` in `promo.ts`, which reads the same badge. Keeping the two apart
110
+ * is why this returns a presentation rather than a boolean.
111
+ */
112
+ function freeBadgeKind(model) {
113
+ if (hasFreeBadge(model.tags)) return "badge";
114
+ if (model.multiplier === 0 || (model.tags ?? []).includes("free")) return "generic";
115
+ /**
116
+ * An id ending in `-free` is the vendor's own way of saying so.
117
+ *
118
+ * `hy4flash-free` carries no `free` tag and no zero multiplier in the static table — the free
119
+ * fact lives in the ID. Without this the row that shares its name with a paid twin had no badge
120
+ * at all, so the免费 twin and the paid one looked identical.
121
+ */
122
+ if (typeof model.id === "string" && /-free$/u.test(model.id)) return "generic";
123
+ }
124
+ /**
125
+ * 免费优先的稳定排序(模型列表 / 选择器):免费的排前面,组内保留原顺序。
126
+ *
127
+ * 只改展示顺序,不改 id 映射或 enabledModelIds 集合语义。显式带上原 index 兜底,
128
+ * 避免不同 JS 引擎的 Array.sort 稳定性差异导致同组顺序漂移。
129
+ */
130
+ function sortFreeFirst(rows) {
131
+ return rows.map((row, index) => ({
132
+ row,
133
+ index
134
+ })).sort((a, b) => {
135
+ const fa = freeBadgeKind(a.row) !== void 0;
136
+ if (fa !== (freeBadgeKind(b.row) !== void 0)) return fa ? -1 : 1;
137
+ return a.index - b.index;
138
+ }).map((entry) => entry.row);
139
+ }
47
140
  //#endregion
48
141
  //#region src/upstream.ts
142
+ /** The meter's stamp format, in LOCAL time: `YYYY-MM-DD HH:MM:SS`. */
143
+ function formatMeterStamp(ms) {
144
+ const date = new Date(ms);
145
+ const pad = (value) => String(value).padStart(2, "0");
146
+ return `${String(date.getFullYear())}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
147
+ }
148
+ /**
149
+ * Parse a meter stamp, or undefined when it is not one.
150
+ *
151
+ * The meter answers local wall-clock time with no zone, so it is read as local —
152
+ * the same reading `formatMeterStamp` writes. Treating it as UTC would shift
153
+ * every row by the machine's offset and move charges across day boundaries,
154
+ * which is exactly the arithmetic the dashboard is built on. Empty strings are
155
+ * legitimate here (`CycleStartTime` is `""` for a one-off package) and must come
156
+ * back as undefined rather than as the epoch.
157
+ */
158
+ function parseMeterStamp(value) {
159
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
160
+ if (typeof value !== "string") return void 0;
161
+ const trimmed = value.trim();
162
+ if (trimmed === "") return void 0;
163
+ const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})$/u.exec(trimmed);
164
+ if (match === null) return void 0;
165
+ const [, year, month, day, hour, minute, second] = match;
166
+ const parsed = new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), Number(second)).getTime();
167
+ return Number.isFinite(parsed) ? parsed : void 0;
168
+ }
169
+ /** Spread a possibly-absent number into an optional field, under exactOptionalPropertyTypes. */
170
+ function optionalMs(key, value) {
171
+ return value === void 0 ? {} : { [key]: value };
172
+ }
173
+ /**
174
+ * Cut the prompt fields out of a usage page's JSON TEXT, before it is parsed.
175
+ *
176
+ * WHY
177
+ *
178
+ * The meter attaches each request's prompt to its row (`input`, and a truncated
179
+ * copy in `inputTrunc`). Nothing in the request changes that — measured across
180
+ * `fields`, `exclude`, `columns`, `needPrompt`, `withPrompt`, `showInput`, `simple`,
181
+ * `lite`, `detail`, four `User-Agent` variants and three `Accept` spellings, all of
182
+ * which it ignores — and a wider `Accept-Encoding` is answered with `identity`, so
183
+ * there is no compressed form to lean on either. On a real six-day page those two
184
+ * fields were **81.8%** of the body.
185
+ *
186
+ * `JSON.parse` on the untouched body therefore builds an object per prompt so that
187
+ * this module can keep four small fields and drop the rest. Removing the values
188
+ * first means the parser never materialises them at all, and the string that gets
189
+ * parsed is a fraction of its original size. With ten pages in flight that is the
190
+ * difference between holding tens of megabytes of the user's own prompts and
191
+ * holding almost none.
192
+ *
193
+ * HOW, AND WHY NOT A STREAMING PARSER
194
+ *
195
+ * Both fields are always JSON STRINGS, so each occurrence is `"input": "…"` (or
196
+ * `"inputTrunc": "…"`). The scanner finds those keys and skips the string literal
197
+ * that follows with correct escape handling, so a prompt containing `\"` or a
198
+ * newline cannot desynchronise it. It is textual because a second, hand-rolled JSON
199
+ * reader is a second parser to get wrong; a string-literal skipper is small enough
200
+ * that its one job is provable, and anything it does not recognise is returned
201
+ * untouched — so an upstream shape change degrades to the previous behaviour rather
202
+ * than to "no data".
203
+ *
204
+ * Exported for its own tests: it is the one piece here whose failure would be
205
+ * silent (a dropped row reads as a missing charge).
206
+ */
207
+ function stripUsagePrompts(text) {
208
+ if (!text.includes("\"input")) return text;
209
+ const out = [];
210
+ let copied = 0;
211
+ let index = 0;
212
+ while (index < text.length) {
213
+ if (text.charCodeAt(index) !== 34) {
214
+ index += 1;
215
+ continue;
216
+ }
217
+ const keyEnd = scanString(text, index);
218
+ if (keyEnd === -1) break;
219
+ const key = text.slice(index + 1, keyEnd - 1);
220
+ if (key !== "input" && key !== "inputTrunc") {
221
+ index = keyEnd;
222
+ continue;
223
+ }
224
+ let cursor = keyEnd;
225
+ while (cursor < text.length && (text[cursor] === ":" || text[cursor] === " " || text[cursor] === " ")) cursor += 1;
226
+ if (text[cursor] !== "\"") {
227
+ index = keyEnd;
228
+ continue;
229
+ }
230
+ const valueEnd = scanString(text, cursor);
231
+ if (valueEnd === -1) break;
232
+ out.push(text.slice(copied, index));
233
+ out.push(`"${key}":""`);
234
+ copied = valueEnd;
235
+ index = valueEnd;
236
+ }
237
+ if (out.length === 0) return text;
238
+ out.push(text.slice(copied));
239
+ return out.join("");
240
+ }
241
+ /**
242
+ * Index just past the string literal starting at `start` (which must be a quote).
243
+ *
244
+ * Returns -1 when the literal never closes, so the caller can bail out and leave the
245
+ * document alone rather than truncate it. Escape handling is the whole point: a
246
+ * prompt containing `\"` would otherwise end the literal early and misalign every
247
+ * key after it.
248
+ */
249
+ function scanString(text, start) {
250
+ let index = start + 1;
251
+ while (index < text.length) {
252
+ const char = text.charCodeAt(index);
253
+ if (char === 92) {
254
+ index += 2;
255
+ continue;
256
+ }
257
+ if (char === 34) return index + 1;
258
+ index += 1;
259
+ }
260
+ return -1;
261
+ }
49
262
  /**
50
263
  * Backoff between catalog-fetch attempts.
51
264
  *
@@ -189,7 +402,36 @@ const SESSION_DEAD_MARKERS = [
189
402
  * reward for today is already collected. Matched against the message, since
190
403
  * the code varies by realm.
191
404
  */
192
- const ALREADY_CHECKIN_MARKERS = ["已签到", "already"];
405
+ /**
406
+ * 「今日已领」必须整句锚定,不能用子串。
407
+ *
408
+ * 对照组用真实 13 条报文证明:`已签到` 这一子串会出现在
409
+ * 「今日已签到记录写入失败」「账号已被限制,今日已签到次数异常」「当前账号已签出,请重新登录」
410
+ * 「领取名额已签满」里 —— 用子串匹配会把这些失败翻成成功并写入账本,导致当天不再补领。
411
+ * 这里只认「整句就是已签到」的几种固定措辞,以及明确带「今日已领取/已签」且不含失败词的短句。
412
+ */
413
+ const ALREADY_CHECKIN_EXACT = /* @__PURE__ */ new Set([
414
+ "已签到",
415
+ "今日已签到",
416
+ "今天已签到",
417
+ "already checked in",
418
+ "already checked-in",
419
+ "already claimed",
420
+ "今日已领取",
421
+ "今日已领",
422
+ "已经签到"
423
+ ]);
424
+ const CHECKIN_FAILURE_MARKERS = [
425
+ "失败",
426
+ "异常",
427
+ "限制",
428
+ "签出",
429
+ "名额已签满",
430
+ "重新登录",
431
+ "过期",
432
+ "refused",
433
+ "error"
434
+ ];
193
435
  /**
194
436
  * 签到相关的业务码。
195
437
  *
@@ -647,8 +889,14 @@ async function readEnvelope(response) {
647
889
  }
648
890
  if (typeof parsed !== "object" || parsed === null) throw new Error(`workbuddy upstream returned an unexpected document (http ${response.status})`);
649
891
  const document = parsed;
892
+ /**
893
+ * 业务码可能是 number 也可能是字符串(上游会下发 `"41000"` / `"0"`)。
894
+ * 只认 number 会把新登记码全判失败,全天反复重试(对照 hub credits.ts:719)。
895
+ */
896
+ const rawCode = document["code"];
897
+ const parsedCode = typeof rawCode === "string" && rawCode.trim() !== "" ? Number(rawCode) : rawCode;
650
898
  return {
651
- code: typeof document["code"] === "number" ? document["code"] : 0,
899
+ code: typeof parsedCode === "number" && Number.isFinite(parsedCode) ? parsedCode : 0,
652
900
  msg: typeof document["msg"] === "string" ? document["msg"] : "",
653
901
  data: "data" in document ? document["data"] : void 0
654
902
  };
@@ -736,6 +984,7 @@ function contentOfFrame(frame) {
736
984
  const RISK_BLOCK_CODES = ["11140", "11141"];
737
985
  function classifyUpstreamError(status, body) {
738
986
  if (status === 402) return "hard_credit";
987
+ if (status === 429) return "soft_rate";
739
988
  /**
740
989
  * Risk control first, and only for a 403.
741
990
  *
@@ -747,12 +996,11 @@ function classifyUpstreamError(status, body) {
747
996
  for (const code of RISK_BLOCK_CODES) if (body.includes(`"code":${code}`) || body.includes(`"code": ${code}`) || body.includes(`"code":"${code}"`)) return "risk_blocked";
748
997
  }
749
998
  if (status === 401 || status === 403) return "session_dead";
999
+ if (body.includes("soft_rate") || body.includes("\"code\":6004") || body.includes("\"code\": 6004") || body.includes("频率限制")) return "soft_rate";
750
1000
  const lower = body.toLowerCase();
751
1001
  for (const code of HARD_CREDIT_CODES) if (body.includes(`"code":${code}`) || body.includes(`"code": ${code}`) || body.includes(`"code":"${code}"`)) return "hard_credit";
752
1002
  for (const marker of HARD_CREDIT_MARKERS) if (lower.includes(marker.toLowerCase()) || body.includes(marker)) return "hard_credit";
753
1003
  for (const marker of SESSION_DEAD_MARKERS) if (body.includes(marker)) return "session_dead";
754
- if (status === 429) return "soft_rate";
755
- if (body.includes("soft_rate") || body.includes("\"code\":6004") || body.includes("频率限制")) return "soft_rate";
756
1004
  if (status === 404) return "not_found";
757
1005
  if (status >= 500) return "server";
758
1006
  return "client";
@@ -765,8 +1013,10 @@ function classifyUpstreamError(status, body) {
765
1013
  * account behind a false negative.
766
1014
  */
767
1015
  function isAlreadyCheckin(error) {
768
- const message = error instanceof Error ? error.message : String(error);
769
- return ALREADY_CHECKIN_MARKERS.some((marker) => message.includes(marker));
1016
+ const message = (error instanceof Error ? error.message : String(error)).trim().toLowerCase();
1017
+ if (CHECKIN_FAILURE_MARKERS.some((marker) => message.includes(marker.toLowerCase()))) return false;
1018
+ if (ALREADY_CHECKIN_EXACT.has(message)) return true;
1019
+ return /^(?:今日|今天|already )?(?:已签到|已领取|已签|已领)[。.!!]?$/u.test(message);
770
1020
  }
771
1021
  /**
772
1022
  * Whether an error means "no compensation offer is running for this account".
@@ -1485,6 +1735,154 @@ var WorkBuddyUpstreamClient = class {
1485
1735
  ...nearestExpiryMs === void 0 ? {} : { nearestExpiryMs }
1486
1736
  };
1487
1737
  }
1738
+ /**
1739
+ * One page of the per-request billing meter.
1740
+ *
1741
+ * WHY THIS IS A RAW READ
1742
+ *
1743
+ * {@link fetchCredits} answers "how much is left", which is a single number and
1744
+ * can be normalised on the spot. This answers "what was each request charged",
1745
+ * and the dashboard above it needs the rows themselves: it sums them per day,
1746
+ * per account and per model, and reconciles the result against the packages.
1747
+ * Normalising here would push that arithmetic into the caller's document
1748
+ * builder, where a missing field has no way to say so.
1749
+ *
1750
+ * THREE MEASURED UPSTREAM BEHAVIOURS, all of which the caller must survive:
1751
+ *
1752
+ * - the rows come back NEWEST FIRST, so a second page with the same window
1753
+ * answers empty (the meter has no offset — see {@link WorkBuddyUsageQuery.endMs});
1754
+ * - `data.total` is CLAMPED AT 3000, so it cannot be used to decide "done";
1755
+ * - a single day CAN exceed 3000 requests, in which case a page boundary
1756
+ * silently drops the rest unless the caller slides the window.
1757
+ *
1758
+ * Excess concurrency is refused upstream with `429 Too Many Requests` as plain
1759
+ * text (not a JSON envelope), so it is reported as a retryable failure rather
1760
+ * than thrown as a malformed document.
1761
+ */
1762
+ async fetchUsageEntries(credential, query, signal) {
1763
+ const timeout = AbortSignal.timeout(JSON_TIMEOUT_MS);
1764
+ const response = await this.fetchImpl(`${billingBase(credential)}/billing/meter/get-user-request-usage`, {
1765
+ method: "POST",
1766
+ headers: billingHeaders(credential),
1767
+ body: JSON.stringify({
1768
+ startTime: formatMeterStamp(query.startMs),
1769
+ endTime: formatMeterStamp(query.endMs),
1770
+ pageNum: 1,
1771
+ pageSize: query.pageSize
1772
+ }),
1773
+ signal: signal === void 0 ? timeout : AbortSignal.any([timeout, signal])
1774
+ });
1775
+ if (response.status === 429) return {
1776
+ ok: false,
1777
+ retryable: true,
1778
+ reason: "rate-limited"
1779
+ };
1780
+ const text = await response.text();
1781
+ let parsed;
1782
+ try {
1783
+ parsed = JSON.parse(stripUsagePrompts(text));
1784
+ } catch {
1785
+ return {
1786
+ ok: false,
1787
+ retryable: response.status >= 500,
1788
+ reason: `non-JSON (http ${response.status}): ${text.slice(0, 120)}`
1789
+ };
1790
+ }
1791
+ if (typeof parsed !== "object" || parsed === null) return {
1792
+ ok: false,
1793
+ retryable: false,
1794
+ reason: `unexpected document (http ${response.status})`
1795
+ };
1796
+ const document = parsed;
1797
+ const code = typeof document["code"] === "number" ? document["code"] : 0;
1798
+ if (code !== 0) return {
1799
+ ok: false,
1800
+ retryable: false,
1801
+ reason: `code ${String(code)} ${String(document["msg"] ?? "")}`.trim()
1802
+ };
1803
+ const data = typeof document["data"] === "object" && document["data"] !== null ? document["data"] : {};
1804
+ const rows = Array.isArray(data["data"]) ? data["data"] : [];
1805
+ const entries = [];
1806
+ for (const raw of rows) {
1807
+ if (typeof raw !== "object" || raw === null) continue;
1808
+ const row = raw;
1809
+ const at = parseMeterStamp(row["requestTime"] ?? row["request_time"]);
1810
+ if (at === void 0) continue;
1811
+ const requestId = typeof row["requestId"] === "string" ? row["requestId"] : `${String(row["requestTime"] ?? "")}|${String(row["model"] ?? "")}|${String(at)}`;
1812
+ entries.push({
1813
+ requestId,
1814
+ credit: typeof row["credit"] === "number" && Number.isFinite(row["credit"]) ? row["credit"] : 0,
1815
+ model: typeof row["model"] === "string" && row["model"] !== "" ? row["model"] : "(unknown)",
1816
+ at
1817
+ });
1818
+ }
1819
+ return {
1820
+ ok: true,
1821
+ entries,
1822
+ count: rows.length
1823
+ };
1824
+ }
1825
+ /**
1826
+ * Every billing package this credential holds, raw.
1827
+ *
1828
+ * The window is deliberately wide on both sides. `fetchCredits` asks for
1829
+ * packages ending in the FUTURE, because a balance only counts what can still
1830
+ * be spent; a dashboard asking "what did I gain this month" needs the ones that
1831
+ * already ended too, or the first day of the window reads as zero income. The
1832
+ * upstream caps this list at `PageSize`, so it is asked for once at 300 and the
1833
+ * caller treats a full page as "there may be more" rather than as the truth.
1834
+ */
1835
+ async fetchResourceRows(credential, range, signal) {
1836
+ const timeout = AbortSignal.timeout(JSON_TIMEOUT_MS);
1837
+ const response = await this.fetchImpl(`${billingBase(credential)}/v2/billing/meter/get-user-resource`, {
1838
+ method: "POST",
1839
+ headers: billingHeaders(credential),
1840
+ body: JSON.stringify({
1841
+ PageNumber: 1,
1842
+ PageSize: 300,
1843
+ ProductCode: "p_tcaca",
1844
+ Status: [0, 3],
1845
+ PackageEndTimeRangeBegin: formatMeterStamp(range.beginMs),
1846
+ PackageEndTimeRangeEnd: formatMeterStamp(range.endMs)
1847
+ }),
1848
+ signal: signal === void 0 ? timeout : AbortSignal.any([timeout, signal])
1849
+ });
1850
+ const envelope = await readEnvelope(response);
1851
+ if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1852
+ const wrapper = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1853
+ const inner = typeof wrapper["Response"] === "object" && wrapper["Response"] !== null ? wrapper["Response"]["Data"] : void 0;
1854
+ const accounts = typeof inner === "object" && inner !== null ? inner["Accounts"] : void 0;
1855
+ const list = Array.isArray(accounts) ? accounts : [];
1856
+ const rows = [];
1857
+ for (const raw of list) {
1858
+ if (typeof raw !== "object" || raw === null) continue;
1859
+ const row = raw;
1860
+ const number = (key) => typeof row[key] === "number" && Number.isFinite(row[key]) ? row[key] : 0;
1861
+ const precise = (key) => {
1862
+ const value = row[`${key}Precise`];
1863
+ return typeof value === "number" && Number.isFinite(value) ? value : number(key);
1864
+ };
1865
+ rows.push({
1866
+ packageName: typeof row["PackageName"] === "string" && row["PackageName"] !== "" ? row["PackageName"] : typeof row["SubPackageName"] === "string" && row["SubPackageName"] !== "" ? row["SubPackageName"] : "积分包",
1867
+ capacityType: number("CapacityType"),
1868
+ createMs: number("CreateTime"),
1869
+ cycleSize: precise("CycleCapacitySize"),
1870
+ cycleRemain: precise("CycleCapacityRemain"),
1871
+ totalSize: precise("CapacitySize"),
1872
+ totalRemain: precise("CapacityRemain"),
1873
+ ...optionalMs("cycleStartMs", parseMeterStamp(row["CycleStartTime"])),
1874
+ ...optionalMs("cycleEndMs", parseMeterStamp(row["CycleEndTime"])),
1875
+ status: number("Status"),
1876
+ ...optionalMs("deductionEndMs", number("DeductionEndTime") > 0 ? number("DeductionEndTime") : void 0),
1877
+ ...optionalMs("expiredMs", parseMeterStamp(row["ExpiredTime"]))
1878
+ });
1879
+ }
1880
+ return {
1881
+ ok: true,
1882
+ rows,
1883
+ truncated: list.length >= 300
1884
+ };
1885
+ }
1488
1886
  /** Query today's check-in status without changing account state. */
1489
1887
  async fetchCheckinStatus(credential) {
1490
1888
  const response = await this.fetchImpl(`${billingBase(credential)}/v2/billing/meter/checkin-activity-status`, {
@@ -3336,7 +3734,7 @@ function parseWorkBuddyAuth(text, sourcePath, decrypt) {
3336
3734
  * app itself is using.
3337
3735
  */
3338
3736
  function isLiveAuthFile(path) {
3339
- return basename(path) === WORKBUDDY_LIVE_FILENAME;
3737
+ return basename(path) === "workbuddy-desktop.info" && existsSync(path);
3340
3738
  }
3341
3739
  /**
3342
3740
  * True for a credential this plugin minted from the channel-pack sign-in flow.
@@ -3789,6 +4187,27 @@ var WorkBuddyAccountPool = class {
3789
4187
  */
3790
4188
  creditBalances = /* @__PURE__ */ new Map();
3791
4189
  /**
4190
+ * Where the last known balances are mirrored, when the host supplies a path.
4191
+ *
4192
+ * The reserve floor is the last line of defence against an account being
4193
+ * drained, and it silently does nothing during the cold-start window when
4194
+ * `creditBalances` is still empty: `available()` keeps an account with no
4195
+ * reading in play, deliberately, so an unprobed pool is not stranded. That
4196
+ * default is right for a pool that has never been measured and wrong for one
4197
+ * measured ten seconds before the process restarted — the pool is then
4198
+ * scheduled straight past the floor the user set.
4199
+ *
4200
+ * Observed 2026-10-30: an account with a 20,000 floor and a real 2,869
4201
+ * balance was picked and drained, because the first request after a restart
4202
+ * arrived before any balance reading existed.
4203
+ *
4204
+ * Mirroring the readings closes that window without changing `available()`'s
4205
+ * semantics: it still sees "known" balances, just ones from the previous run.
4206
+ * The alternative — treating unknown as unusable — would turn a transient
4207
+ * credits-endpoint failure into a full outage.
4208
+ */
4209
+ creditBalancePath;
4210
+ /**
3792
4211
  * Nearest expiry among each account's one-off credit packs, epoch ms.
3793
4212
  *
3794
4213
  * Credit packs are use-it-or-lose-it, so "which account should serve next"
@@ -3885,6 +4304,8 @@ var WorkBuddyAccountPool = class {
3885
4304
  this.storePath = accountStorePath();
3886
4305
  this.affinityPath = options.affinityPath;
3887
4306
  if (this.affinityPath !== void 0) this.loadAffinity();
4307
+ this.creditBalancePath = options.creditBalancePath;
4308
+ if (this.creditBalancePath !== void 0) this.loadCreditBalances();
3888
4309
  }
3889
4310
  /**
3890
4311
  * Re-apply configuration that only affects discovery and cooldown policy,
@@ -4229,6 +4650,23 @@ var WorkBuddyAccountPool = class {
4229
4650
  });
4230
4651
  }
4231
4652
  /**
4653
+ * Whether ANY account can serve this model right now.
4654
+ *
4655
+ * Exposed because the retry loop needs this answer *between* attempts, not
4656
+ * only when it starts one: after penalising the account that just returned
4657
+ * 429, the loop must know whether the next attempt has any chance. Without
4658
+ * it, a per-account rate limit walks the whole pool — each attempt is a
4659
+ * guaranteed 429 that also burns that account's quota for the model, so a
4660
+ * single request can leave every account cooling until the next day.
4661
+ *
4662
+ * `available()` already computes exactly this; it stays private because the
4663
+ * account objects it returns are mutable state the pool owns. This reports
4664
+ * the count only, which is all a caller should act on.
4665
+ */
4666
+ anyAvailable(modelId, region, reserveExempt) {
4667
+ return this.available(Date.now(), modelId, region, reserveExempt).length > 0;
4668
+ }
4669
+ /**
4232
4670
  * The pool ordered into three bands, so a resting account is deferred instead of
4233
4671
  * discarded.
4234
4672
  *
@@ -4761,8 +5199,43 @@ var WorkBuddyAccountPool = class {
4761
5199
  noteCredits(accountId, balance, nearestExpiryMs) {
4762
5200
  if (!Number.isFinite(balance)) return;
4763
5201
  if (!this.accounts.some((account) => account.id === accountId)) return;
5202
+ const changed = this.creditBalances.get(accountId) !== balance;
4764
5203
  this.creditBalances.set(accountId, balance);
4765
5204
  this.noteExpiryReading(accountId, nearestExpiryMs);
5205
+ if (changed) this.saveCreditBalances();
5206
+ }
5207
+ /**
5208
+ * Restore the balances mirrored by the previous run.
5209
+ *
5210
+ * Best effort by construction: an unreadable or missing file means "first
5211
+ * run", which is exactly the cold start the mirror exists to narrow rather
5212
+ * than to replace — the pool keeps working either way.
5213
+ */
5214
+ loadCreditBalances() {
5215
+ if (this.creditBalancePath === void 0) return;
5216
+ try {
5217
+ const balances = JSON.parse(readFileSync(this.creditBalancePath, "utf8")).balances;
5218
+ if (typeof balances !== "object" || balances === null || Array.isArray(balances)) return;
5219
+ for (const [id, value] of Object.entries(balances)) {
5220
+ if (id === "" || typeof value !== "number" || !Number.isFinite(value) || value < 0) continue;
5221
+ this.creditBalances.set(id, value);
5222
+ }
5223
+ } catch {}
5224
+ }
5225
+ /** Mirror every known balance, atomically. Never throws. */
5226
+ saveCreditBalances() {
5227
+ const path = this.creditBalancePath;
5228
+ if (path === void 0) return;
5229
+ try {
5230
+ mkdirSync(dirname(path), { recursive: true });
5231
+ writeFileSync(`${path}.tmp`, `${JSON.stringify({
5232
+ version: 1,
5233
+ at: Date.now(),
5234
+ balances: Object.fromEntries(this.creditBalances)
5235
+ }, null, 2)}
5236
+ `, "utf8");
5237
+ renameSync(`${path}.tmp`, path);
5238
+ } catch {}
4766
5239
  }
4767
5240
  /**
4768
5241
  * Record ONLY the deadline, never the balance.
@@ -5229,7 +5702,7 @@ const MAGICREW_CN = Object.freeze({
5229
5702
  displayName: "超级麦吉",
5230
5703
  host: "https://i-magic-service.letsmagic.cn",
5231
5704
  webOrigin: "https://www.letsmagic.cn",
5232
- needsOrg: false,
5705
+ needsOrg: true,
5233
5706
  defaultRef: "magicrew"
5234
5707
  });
5235
5708
  const MAGICREW_INTL = Object.freeze({
@@ -5732,16 +6205,26 @@ var WorkBuddyCatalog = class {
5732
6205
  * is recoverable in one click whereas "nothing" looks like a broken install.
5733
6206
  */
5734
6207
  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
+ */
5735
6218
  const images = this.selection.imageModelIds;
5736
- const imageSet = images === void 0 ? void 0 : new Set(images);
6219
+ const imageSet = images === void 0 || images.length === 0 ? void 0 : new Set(images);
5737
6220
  const budgets = this.selection.contextBudgets;
5738
- return this.models.filter((model) => allow === void 0 || allow.has(model.id)).map((model) => {
6221
+ return sortFreeFirst(this.models.filter((model) => allow === void 0 || allow.has(model.id)).map((model) => {
5739
6222
  const next = { ...model };
5740
6223
  if (imageSet !== void 0) next.supportsImages = imageSet.has(model.id);
5741
6224
  const budget = budgets?.[model.id];
5742
6225
  if (budget !== void 0 && budget > 0 && budget < next.contextWindow) next.contextWindow = budget;
5743
6226
  return next;
5744
- });
6227
+ }));
5745
6228
  }
5746
6229
  /** Replace the catalog and notify the adapter to rebuild its model list. */
5747
6230
  update(models) {
@@ -10818,6 +11301,7 @@ const PROVIDERS = Object.freeze([
10818
11301
  "baseUrl": "",
10819
11302
  "format": "openai-chat",
10820
11303
  "models": [],
11304
+ "modelsUrl": "/models",
10821
11305
  "notes": "Any OpenAI-compatible endpoint — vLLM, LiteLLM, one-api, LM Studio, a self-hosted gateway. Paste the base URL (ending in /v1) and the key on this card, then press Fetch models.",
10822
11306
  "website": null,
10823
11307
  "local": false,
@@ -10834,6 +11318,54 @@ Object.freeze({
10834
11318
  "openai-responses": "/responses",
10835
11319
  "anthropic-messages": "/messages"
10836
11320
  });
11321
+ //#endregion
11322
+ //#region src/group-routing.ts
11323
+ /** 恒等序(ordered / 兜底)。 */
11324
+ function identityOrder(seats) {
11325
+ return seats.map((_, i) => i);
11326
+ }
11327
+ /** smart:额度优先 —— 没用尽的按最早续期/过期排,用尽的沉底。 */
11328
+ function smartOrder(seats) {
11329
+ const idx = seats.map((_, i) => i);
11330
+ const tier = (s) => {
11331
+ if (s.resting === true || s.spent === true || (s.used ?? 0) >= 1) return 2;
11332
+ if ((s.used ?? 0) >= .9) return 1;
11333
+ return 0;
11334
+ };
11335
+ return idx.sort((a, b) => {
11336
+ const ta = tier(seats[a]), tb = tier(seats[b]);
11337
+ if (ta !== tb) return ta - tb;
11338
+ const ra = seats[a].renewsInMs ?? Number.MAX_SAFE_INTEGER;
11339
+ const rb = seats[b].renewsInMs ?? Number.MAX_SAFE_INTEGER;
11340
+ if (ra !== rb) return ra - rb;
11341
+ return (seats[a].used ?? 0) - (seats[b].used ?? 0);
11342
+ });
11343
+ }
11344
+ /** cheapest:价格升序,同价按窗口小的先用。 */
11345
+ function cheapestOrder(seats) {
11346
+ return seats.map((_, i) => i).sort((a, b) => {
11347
+ const ca = seats[a].cost ?? Number.MAX_SAFE_INTEGER;
11348
+ const cb = seats[b].cost ?? Number.MAX_SAFE_INTEGER;
11349
+ if (ca !== cb) return ca - cb;
11350
+ return (seats[a].window ?? Number.MAX_SAFE_INTEGER) - (seats[b].window ?? Number.MAX_SAFE_INTEGER);
11351
+ });
11352
+ }
11353
+ /** free-first:免费且可用的优先,其后按 smart。 */
11354
+ function freeFirstOrder(seats) {
11355
+ return seats.map((_, i) => i).sort((a, b) => {
11356
+ const fa = seats[a].free === true && (seats[a].used ?? 0) < 1 ? 0 : 1;
11357
+ const fb = seats[b].free === true && (seats[b].used ?? 0) < 1 ? 0 : 1;
11358
+ if (fa !== fb) return fa - fb;
11359
+ return smartOrder([seats[a], seats[b]])[0] === 0 ? -1 : 1;
11360
+ });
11361
+ }
11362
+ Object.freeze({
11363
+ smart: { order: smartOrder },
11364
+ ordered: { order: identityOrder },
11365
+ "round-robin": { order: identityOrder },
11366
+ cheapest: { order: cheapestOrder },
11367
+ "free-first": { order: freeFirstOrder }
11368
+ });
10837
11369
  Object.freeze({
10838
11370
  "openai-chat": "chat",
10839
11371
  "openai-responses": "responses",
@@ -11327,6 +11859,58 @@ function expertChatEvents(expert, conversationId, requestId) {
11327
11859
  expert_industry_id: ""
11328
11860
  } : event);
11329
11861
  }
11862
+ //#endregion
11863
+ //#region src/scheduler.ts
11864
+ /**
11865
+ * 自动化节流旋钮(issue #231/#232,PR 232)。
11866
+ *
11867
+ * 固定 800ms 的账号间隔 + 整点触发是一组机器指纹:实测 38 个 domestic 账号在
11868
+ * 三次 800ms 恒定节奏的自动化之后,59 分钟内有 27 个 refresh token 被撤销。
11869
+ * 抖动打散节奏;旋钮都设 0 可精确恢复旧行为,所以这不是悄悄改默认值。
11870
+ *
11871
+ * 旋钮走环境变量而非设置文档:这是缓解措施不是功能,改一个数不该做设置迁移。
11872
+ */
11873
+ function pacingEnv(name, fallback) {
11874
+ const raw = typeof process === "object" && process !== null ? process.env[name] : void 0;
11875
+ if (typeof raw !== "string" || raw.trim() === "") return fallback;
11876
+ const parsed = Number(raw);
11877
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
11878
+ }
11879
+ /** 两次上游调用之间的基础间隔(默认 6s)。 */
11880
+ const PACING_ACCOUNT_DELAY_MS = pacingEnv("XDPOOL_ACCOUNT_DELAY_MS", 6e3);
11881
+ /** 叠加在基础间隔上的均匀抖动(默认 0..6s)。 */
11882
+ const PACING_ACCOUNT_DELAY_JITTER_MS = pacingEnv("XDPOOL_ACCOUNT_DELAY_JITTER", 6e3);
11883
+ /** 配置小时内的分散分钟数(默认 0..45)。 */
11884
+ const PACING_SCHEDULE_JITTER_MIN = pacingEnv("XDPOOL_SCHEDULE_JITTER_MIN", 45);
11885
+ /** 带抖动的调用间隔;jitter=0 时精确等于 base。 */
11886
+ function pacedDelay(baseMs) {
11887
+ if (!(baseMs > 0)) return 0;
11888
+ if (!(PACING_ACCOUNT_DELAY_JITTER_MS > 0)) return baseMs;
11889
+ return baseMs + Math.floor(Math.random() * PACING_ACCOUNT_DELAY_JITTER_MS);
11890
+ }
11891
+ /**
11892
+ * 一个 slot 在其配置小时内真正触发的分钟偏移。
11893
+ * 由 slot 字符串确定性哈希得到,不是每次随机 —— 重启/重复 tick 不会提前重跑
11894
+ * 同一个 slot(那会重复消费),也不会把它弄丢。
11895
+ */
11896
+ function slotMinuteOffset(slot) {
11897
+ /**
11898
+ * 运行时再读一次旋钮,而不是只用模块加载时的快照。
11899
+ *
11900
+ * `PACING_SCHEDULE_JITTER_MIN` 是加载时固化的默认值;但测试要在 import 之后
11901
+ * 用 process.env 关闭抖动来驱动「整点触发」的历史回归,运营也可能在进程内
11902
+ * 改旋钮。实时读取让这两种场景都成立,而正常运行时值不变。
11903
+ */
11904
+ const live = pacingEnv("XDPOOL_SCHEDULE_JITTER_MIN", PACING_SCHEDULE_JITTER_MIN);
11905
+ const span = Math.min(59, Math.floor(live));
11906
+ if (!(span > 0)) return 0;
11907
+ let hash = 2166136261;
11908
+ for (let i = 0; i < slot.length; i += 1) {
11909
+ hash ^= slot.charCodeAt(i);
11910
+ hash = Math.imul(hash, 16777619) >>> 0;
11911
+ }
11912
+ return hash % (span + 1);
11913
+ }
11330
11914
  /**
11331
11915
  * The fallback record for the 腾讯轻量云 expert, used when the marketplace
11332
11916
  * listing cannot be read. The id is the one the task is scored against.
@@ -11455,6 +12039,7 @@ function zonedParts(date, timeZone = AUTOMATION_TIME_ZONE) {
11455
12039
  month: "2-digit",
11456
12040
  day: "2-digit",
11457
12041
  hour: "2-digit",
12042
+ minute: "2-digit",
11458
12043
  hourCycle: "h23"
11459
12044
  }).formatToParts(date);
11460
12045
  const pick = (type) => parts.find((part) => part.type === type)?.value ?? "00";
@@ -11462,7 +12047,8 @@ function zonedParts(date, timeZone = AUTOMATION_TIME_ZONE) {
11462
12047
  year: pick("year"),
11463
12048
  month: pick("month"),
11464
12049
  day: pick("day"),
11465
- hour: pick("hour")
12050
+ hour: pick("hour"),
12051
+ minute: pick("minute")
11466
12052
  };
11467
12053
  }
11468
12054
  function dayKey(date, timeZone = AUTOMATION_TIME_ZONE) {
@@ -11594,7 +12180,7 @@ var WorkBuddyScheduler = class {
11594
12180
  this.client = client;
11595
12181
  this.logger = options.logger ?? {};
11596
12182
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
11597
- this.delayMs = options.accountDelayMs ?? 800;
12183
+ this.delayMs = options.accountDelayMs ?? PACING_ACCOUNT_DELAY_MS;
11598
12184
  this.eventScoreWaitMs = options.eventScoreWaitMs ?? 9e3;
11599
12185
  this.expertGapMs = options.expertGapMs ?? 6e3;
11600
12186
  this.loadEarnings = options.loadEarnings;
@@ -11720,27 +12306,50 @@ var WorkBuddyScheduler = class {
11720
12306
  * report would have moved. This is what the card's single button calls.
11721
12307
  */
11722
12308
  /**
11723
- * Start a full pass in the background and return immediately.
12309
+ * Start a pass in the background and return immediately.
11724
12310
  *
11725
12311
  * A pass takes tens of seconds - one upstream round trip per account per job,
11726
12312
  * plus the scoring wait - which is far too long to hold the card request open:
11727
12313
  * the browser or the host web server would time out, and the user would see
11728
12314
  * a hung button for a run that is actually working.
11729
12315
  *
12316
+ * `job` names ONE job (the card's per-job button) or `'all'` for the ordered
12317
+ * full pass; anything else is treated as `'all'` by the caller's validation,
12318
+ * not here. `force` bypasses the already-ran-today guard for a single job,
12319
+ * which is what "run it now anyway" means.
12320
+ *
11730
12321
  * Returns whether a run started. A second call while one is in flight is
11731
12322
  * ignored rather than queued: pressing the button twice means hurry up, and
11732
12323
  * the run already under way covers it.
11733
12324
  */
11734
- startRunAll() {
12325
+ startRunAll(job = "all", force = false) {
11735
12326
  if (this.runInFlight) return false;
11736
12327
  this.runInFlight = true;
11737
- this.runAll().catch((error) => {
12328
+ (job === "all" ? this.runAll() : this.runNow(job, force).then(() => void 0)).catch((error) => {
11738
12329
  this.logger.warn?.("dsh-xdpool automation run failed:", error);
11739
12330
  }).finally(() => {
11740
12331
  this.runInFlight = false;
11741
12332
  });
11742
12333
  return true;
11743
12334
  }
12335
+ /**
12336
+ * issue #222:启动一个指定 job 的后台运行,供「立即执行」按任务调用。
12337
+ *
12338
+ * 和 `startRunAll` 一样立刻返回(跑一轮要几十秒,不能挂在卡片请求上),
12339
+ * 也复用同一把 `runInFlight` 锁:同时检查 `busy`,避免手动单任务和定时 tick
12340
+ * 并发跑同一批账号(共享 ledger 的 read-modify-write 不是原子的)。
12341
+ * `force` 交给 `runNow`,让它跳过同小时的节流。
12342
+ */
12343
+ startRunNow(kind, force = false) {
12344
+ if (this.runInFlight || this.busy) return false;
12345
+ this.runInFlight = true;
12346
+ this.runNow(kind, force).catch((error) => {
12347
+ this.logger.warn?.(`dsh-xdpool automation run ${kind} failed:`, error);
12348
+ }).finally(() => {
12349
+ this.runInFlight = false;
12350
+ });
12351
+ return true;
12352
+ }
11744
12353
  async runAll() {
11745
12354
  const today = dayKey(this.now());
11746
12355
  const before = this.earningsSnapshot();
@@ -11821,13 +12430,17 @@ var WorkBuddyScheduler = class {
11821
12430
  dueSlot(kind, now) {
11822
12431
  const hours = this.hoursOf(kind);
11823
12432
  if (hours.length === 0) return void 0;
11824
- const current = Number(zonedParts(now).hour);
12433
+ const parts = zonedParts(now);
12434
+ const current = Number(parts.hour);
12435
+ const currentMinute = Number(parts.minute);
11825
12436
  const today = dayKey(now);
11826
12437
  const fired = this.firedSlotsOf(kind);
11827
12438
  for (const candidate of [...hours].sort((a, b) => a - b)) {
11828
12439
  if (candidate > current) break;
11829
12440
  const slot = `${today}T${String(candidate).padStart(2, "0")}`;
11830
- if (!fired.has(slot)) return slot;
12441
+ if (fired.has(slot)) continue;
12442
+ if (candidate === current && currentMinute < slotMinuteOffset(slot)) break;
12443
+ return slot;
11831
12444
  }
11832
12445
  }
11833
12446
  /** Today's consumed slots for one job, as a set. */
@@ -11999,18 +12612,52 @@ var WorkBuddyScheduler = class {
11999
12612
  try {
12000
12613
  switch (kind) {
12001
12614
  case "checkin": {
12615
+ /**
12616
+ * 定时签到也必须像手动领取一样先用新鲜凭据(issue: 自动签到全挂)。
12617
+ * 手动路由 web-status.ts 已用 freshCredential,但这条定时路径以前
12618
+ * 直接拿池里的旧 token —— 过期后上游 401,整轮静默失败。
12619
+ */
12620
+ const fresh = await this.pool.freshCredential(account.id);
12621
+ if (fresh === void 0) {
12622
+ detail.push("签到跳过:登录已失效且刷新失败,请重新登录");
12623
+ this.logger.warn?.(`automation checkin ${account.label}: credential could not be refreshed; skipped`);
12624
+ break;
12625
+ }
12002
12626
  let alreadyDone = false;
12627
+ let activityClosed = false;
12628
+ let alreadyPaid = 0;
12003
12629
  try {
12004
- alreadyDone = (await this.client.fetchCheckinStatus(account.credential)).todayCheckedIn === true;
12630
+ const status = await this.client.fetchCheckinStatus(fresh);
12631
+ alreadyDone = status.todayCheckedIn === true;
12632
+ activityClosed = status.active === false;
12633
+ /**
12634
+ * issue #221:桌面端通常先签到了,插件 9 点跑到时状态已是已领。
12635
+ * 以前这里直接 break、不记账,ledger 的 checkinCredit 恒 0,
12636
+ * 卡片就显示「今日已领 0/1」——明明已领却像没领到。
12637
+ * `todayCredit` 是上游当天的真实发放额,用它补账;0 不会写入
12638
+ * (recordEarnings 的 empty 短路),与「重复签到不重复加钱」一致。
12639
+ */
12640
+ alreadyPaid = Math.max(0, status.todayCredit ?? 0);
12005
12641
  } catch (error) {
12006
12642
  this.logger.warn?.(`automation checkin ${account.label}: status read failed, claiming anyway:`, error);
12007
12643
  }
12008
12644
  if (alreadyDone) {
12009
- this.logger.info?.(`automation checkin ${account.label}: already done today (read, not claimed)`);
12645
+ this.recordEarnings(account.id, today, { checkinCredit: alreadyPaid });
12646
+ detail.push(alreadyPaid > 0 ? `签到已领 +${alreadyPaid}` : "签到已在他处完成");
12647
+ this.logger.info?.(`automation checkin ${account.label}: already done today (read, not claimed, paid ${alreadyPaid})`);
12648
+ break;
12649
+ }
12650
+ if (activityClosed) {
12651
+ this.logger.info?.(`automation checkin ${account.label}: no check-in activity on this gateway, skipped`);
12652
+ items.push({
12653
+ title: "每日签到",
12654
+ status: "skipped",
12655
+ note: "this gateway runs no check-in activity"
12656
+ });
12010
12657
  break;
12011
12658
  }
12012
12659
  try {
12013
- const claim = await this.client.claimDailyCheckin(account.credential);
12660
+ const claim = await this.client.claimDailyCheckin(fresh);
12014
12661
  this.recordEarnings(account.id, today, { checkinCredit: claim.credit });
12015
12662
  if (claim.credit > 0) {
12016
12663
  detail.push(`签到 +${claim.credit}`);
@@ -12018,7 +12665,15 @@ var WorkBuddyScheduler = class {
12018
12665
  }
12019
12666
  } catch (error) {
12020
12667
  if (!isAlreadyCheckin(error)) throw error;
12021
- this.logger.info?.(`automation checkin ${account.label}: already done today`);
12668
+ /**
12669
+ * 同样补账(#221):状态读取失败但 claim 回「已签到」时,
12670
+ * 回读一次当天实发额;读不到就记 0(等于不写),不再让账本空着。
12671
+ */
12672
+ const after = await this.client.fetchCheckinStatus(fresh).catch(() => void 0);
12673
+ const paid = Math.max(0, after?.todayCredit ?? 0);
12674
+ this.recordEarnings(account.id, today, { checkinCredit: paid });
12675
+ if (paid > 0) detail.push(`签到已领 +${paid}`);
12676
+ this.logger.info?.(`automation checkin ${account.label}: already done today (paid ${paid})`);
12022
12677
  }
12023
12678
  break;
12024
12679
  }
@@ -12067,7 +12722,7 @@ var WorkBuddyScheduler = class {
12067
12722
  failed++;
12068
12723
  this.logger.warn?.(`automation ${accountWord} ${account.label} failed:`, error);
12069
12724
  }
12070
- if (index < accounts.length - 1 && this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
12725
+ if (index < accounts.length - 1 && this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12071
12726
  }
12072
12727
  const state = this.states[kind];
12073
12728
  if (consumedSlot !== void 0) this.consumeSlot(kind, consumedSlot);
@@ -12160,7 +12815,7 @@ var WorkBuddyScheduler = class {
12160
12815
  this.logger.warn?.(`automation events ${account.label}: ${task.taskCode} failed:`, error);
12161
12816
  break;
12162
12817
  }
12163
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
12818
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12164
12819
  }
12165
12820
  }
12166
12821
  }
@@ -12285,7 +12940,7 @@ var WorkBuddyScheduler = class {
12285
12940
  }
12286
12941
  const expert = expertFromTask(expertId, task.title);
12287
12942
  await this.client.reportDesktopEvents(credential, expertSummonEvents(expert));
12288
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
12943
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12289
12944
  const chat = await this.client.openConversation(credential, expert.expertId);
12290
12945
  if (chat === void 0) throw new Error(`${task.taskCode}: no server conversation`);
12291
12946
  return [{
@@ -12311,7 +12966,7 @@ var WorkBuddyScheduler = class {
12311
12966
  if (this.stopped) break;
12312
12967
  try {
12313
12968
  await this.client.reportDesktopEvents(credential, expertSummonEvents(expert));
12314
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
12969
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12315
12970
  const chat = await this.client.openConversation(credential, expert.expertId);
12316
12971
  if (chat === void 0) continue;
12317
12972
  out.push({
@@ -12342,7 +12997,7 @@ var WorkBuddyScheduler = class {
12342
12997
  this.logger.warn?.("automation events lighthouse list:", error);
12343
12998
  }
12344
12999
  await this.client.reportDesktopEvents(credential, expertSummonEvents(expert));
12345
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
13000
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12346
13001
  const chat = await this.client.openConversation(credential, expert.expertId);
12347
13002
  if (chat === void 0) throw new Error("Expert_lighthouse: no server conversation");
12348
13003
  const use = expertActualUseEvent(expert, chat.conversationId, chat.requestId, "LOCAL");
@@ -12400,7 +13055,7 @@ var WorkBuddyScheduler = class {
12400
13055
  });
12401
13056
  this.logger.info?.(`automation claim ${account.label}: ${task.taskCode} already claimed`);
12402
13057
  }
12403
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
13058
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12404
13059
  }
12405
13060
  return {
12406
13061
  claimed,
@@ -12434,7 +13089,7 @@ var WorkBuddyScheduler = class {
12434
13089
  } catch (error) {
12435
13090
  this.logger.warn?.(`automation streak ${account.label}: redeem ${tier.tier} failed:`, error);
12436
13091
  }
12437
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
13092
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12438
13093
  }
12439
13094
  const chances = await this.client.lotteryChances(credential);
12440
13095
  for (let draw = 0; draw < chances; draw += 1) {
@@ -12446,7 +13101,7 @@ var WorkBuddyScheduler = class {
12446
13101
  this.logger.warn?.(`automation lottery ${account.label}: draw failed:`, error);
12447
13102
  break;
12448
13103
  }
12449
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
13104
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12450
13105
  }
12451
13106
  const pendingTier = status.tiers.find((tier) => tier.status === "locked");
12452
13107
  if (pendingTier !== void 0) {
@@ -12608,6 +13263,7 @@ Object.freeze({
12608
13263
  "Write the briefing only — no preamble, no markdown fence."
12609
13264
  ].join("\n");
12610
13265
  join("channel-pack", "token-ledger.json");
13266
+ join("channel-pack", "token-ledger.json");
12611
13267
  //#endregion
12612
13268
  //#region src/status.ts
12613
13269
  /** Format the per-model credit multipliers. */
@@ -12619,6 +13275,7 @@ function formatRates(status) {
12619
13275
  }
12620
13276
  return lines.join("\n");
12621
13277
  }
13278
+ join(".xdpool", "spend-cache.json");
12622
13279
  Object.freeze({
12623
13280
  "workbuddy-xdpool": "xdpool",
12624
13281
  "workbuddy-xdpool-global": "xdpool-global",
@@ -12811,7 +13468,16 @@ z.object({
12811
13468
  disabledAccountIds: asVolatile(z.array(z.string()).default([]).description("Account ids excluded from the pool (empty = every discovered account participates)")),
12812
13469
  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")),
12813
13470
  enabledModelIds: asVolatile(z.array(z.string()).default([]).description("Legacy shared model-id list; used by a region that has no per-region selection yet")),
12814
- imageModelIds: asVolatile(z.array(z.string()).default([]).description("Legacy shared image-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)")),
12815
13481
  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")),
12816
13482
  modelSelectionCn: asVolatile(modelSelectionSchema.description("Model selection for the domestic gateway")),
12817
13483
  modelSelectionGlobal: asVolatile(modelSelectionSchema.description("Model selection for the international gateway")),
@@ -12855,7 +13521,8 @@ function createCore(logger) {
12855
13521
  ...logger === void 0 ? {} : { logger },
12856
13522
  client,
12857
13523
  persistent: true,
12858
- affinityPath: join(pluginDataDir(), "sticky-affinity.json")
13524
+ affinityPath: join(pluginDataDir(), "sticky-affinity.json"),
13525
+ creditBalancePath: join(pluginDataDir(), "credit-balances.json")
12859
13526
  });
12860
13527
  return {
12861
13528
  pool,