dsh-xdpool 3.0.6 → 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
@@ -1,3 +1,4 @@
1
+ import { createRequire } from "node:module";
1
2
  import { createDecipheriv, createHash, randomUUID } from "node:crypto";
2
3
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
3
4
  import { chmod, copyFile, mkdir, readFile, readdir, rename, rm, unlink, writeFile, writeFile as writeFile$1 } from "node:fs/promises";
@@ -43,8 +44,221 @@ import "@deepseek-ai/dsh-llm-pi-ai";
43
44
  */
44
45
  /** Prefix the CN gateway uses for a promotion badge inside `tags`. */
45
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
+ }
46
140
  //#endregion
47
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
+ }
48
262
  /**
49
263
  * Backoff between catalog-fetch attempts.
50
264
  *
@@ -188,7 +402,53 @@ const SESSION_DEAD_MARKERS = [
188
402
  * reward for today is already collected. Matched against the message, since
189
403
  * the code varies by realm.
190
404
  */
191
- 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
+ ];
435
+ /**
436
+ * 签到相关的业务码。
437
+ *
438
+ * 上游用 `code` 区分三种「不是成功也不是故障」的结果,而我们此前一律当失败抛出:
439
+ * 今天已经领过(1001/10001)会在每次自动领取时记一条失败;活动未开放(1002/1003/
440
+ * 40901/41000)也会,而且永远重试不到结果。它们必须分开对待:
441
+ *
442
+ * 已领 → 幂等成功(今天的分就在账上,不是错)
443
+ * 未开放 → inactive(等下一次,不报错、不重试)
444
+ */
445
+ const CHECKIN_ALREADY_CODES = /* @__PURE__ */ new Set([1001, 10001]);
446
+ const CHECKIN_INACTIVE_CODES = /* @__PURE__ */ new Set([
447
+ 1002,
448
+ 1003,
449
+ 40901,
450
+ 41e3
451
+ ]);
192
452
  /**
193
453
  * Markers for "there is no compensation offer to collect".
194
454
  *
@@ -575,7 +835,17 @@ function billingHeaders(credential) {
575
835
  const headers = {
576
836
  "Authorization": `Bearer ${credential.accessToken}`,
577
837
  "Accept": "application/json",
578
- "Content-Type": "application/json"
838
+ "Content-Type": "application/json",
839
+ /**
840
+ * 产品身份头 —— 缺了它们,计费/签到端点会把请求当成「不是客户端发的」。
841
+ *
842
+ * 这三个头一直在客户端那边发(网页/IDE 的每个 billing 请求都带),我们只发了
843
+ * Authorization + X-Domain + X-User-Id。上游收紧校验之后,签到就只剩一个笼统的
844
+ * 失败,看不出原因。UA 用本插件已经在别处使用的桌面版本号,不再另造一个。
845
+ */
846
+ "X-Product": "SaaS",
847
+ "X-Product-Code": "workbuddy",
848
+ "User-Agent": DESKTOP_UA
579
849
  };
580
850
  if (credential.uid !== "" && credential.uid !== void 0) headers["X-User-Id"] = credential.uid;
581
851
  if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") {
@@ -619,8 +889,14 @@ async function readEnvelope(response) {
619
889
  }
620
890
  if (typeof parsed !== "object" || parsed === null) throw new Error(`workbuddy upstream returned an unexpected document (http ${response.status})`);
621
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;
622
898
  return {
623
- code: typeof document["code"] === "number" ? document["code"] : 0,
899
+ code: typeof parsedCode === "number" && Number.isFinite(parsedCode) ? parsedCode : 0,
624
900
  msg: typeof document["msg"] === "string" ? document["msg"] : "",
625
901
  data: "data" in document ? document["data"] : void 0
626
902
  };
@@ -708,6 +984,7 @@ function contentOfFrame(frame) {
708
984
  const RISK_BLOCK_CODES = ["11140", "11141"];
709
985
  function classifyUpstreamError(status, body) {
710
986
  if (status === 402) return "hard_credit";
987
+ if (status === 429) return "soft_rate";
711
988
  /**
712
989
  * Risk control first, and only for a 403.
713
990
  *
@@ -719,12 +996,11 @@ function classifyUpstreamError(status, body) {
719
996
  for (const code of RISK_BLOCK_CODES) if (body.includes(`"code":${code}`) || body.includes(`"code": ${code}`) || body.includes(`"code":"${code}"`)) return "risk_blocked";
720
997
  }
721
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";
722
1000
  const lower = body.toLowerCase();
723
1001
  for (const code of HARD_CREDIT_CODES) if (body.includes(`"code":${code}`) || body.includes(`"code": ${code}`) || body.includes(`"code":"${code}"`)) return "hard_credit";
724
1002
  for (const marker of HARD_CREDIT_MARKERS) if (lower.includes(marker.toLowerCase()) || body.includes(marker)) return "hard_credit";
725
1003
  for (const marker of SESSION_DEAD_MARKERS) if (body.includes(marker)) return "session_dead";
726
- if (status === 429) return "soft_rate";
727
- if (body.includes("soft_rate") || body.includes("\"code\":6004") || body.includes("频率限制")) return "soft_rate";
728
1004
  if (status === 404) return "not_found";
729
1005
  if (status >= 500) return "server";
730
1006
  return "client";
@@ -737,8 +1013,10 @@ function classifyUpstreamError(status, body) {
737
1013
  * account behind a false negative.
738
1014
  */
739
1015
  function isAlreadyCheckin(error) {
740
- const message = error instanceof Error ? error.message : String(error);
741
- 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);
742
1020
  }
743
1021
  /**
744
1022
  * Whether an error means "no compensation offer is running for this account".
@@ -1457,6 +1735,154 @@ var WorkBuddyUpstreamClient = class {
1457
1735
  ...nearestExpiryMs === void 0 ? {} : { nearestExpiryMs }
1458
1736
  };
1459
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
+ }
1460
1886
  /** Query today's check-in status without changing account state. */
1461
1887
  async fetchCheckinStatus(credential) {
1462
1888
  const response = await this.fetchImpl(`${billingBase(credential)}/v2/billing/meter/checkin-activity-status`, {
@@ -1466,6 +1892,17 @@ var WorkBuddyUpstreamClient = class {
1466
1892
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1467
1893
  });
1468
1894
  const envelope = await readEnvelope(response);
1895
+ if (response.ok && CHECKIN_INACTIVE_CODES.has(envelope.code)) return {
1896
+ active: false,
1897
+ todayCheckedIn: false,
1898
+ streakDays: 0,
1899
+ dailyCredit: 0,
1900
+ todayCredit: 0,
1901
+ isStreakDay: false,
1902
+ nextStreakDay: 0,
1903
+ streakBonusDays: 0,
1904
+ streakBonusCredit: 0
1905
+ };
1469
1906
  if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1470
1907
  const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1471
1908
  const num = (key) => typeof data[key] === "number" ? data[key] : 0;
@@ -1491,8 +1928,22 @@ var WorkBuddyUpstreamClient = class {
1491
1928
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
1492
1929
  });
1493
1930
  const envelope = await readEnvelope(response);
1931
+ const neutral = (data_) => ({
1932
+ credit: 0,
1933
+ streakDays: typeof data_["streak_days"] === "number" ? data_["streak_days"] : 0,
1934
+ isStreakDay: false
1935
+ });
1936
+ const payload = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1937
+ /**
1938
+ * 已领过(1001/10001)就是成功:今天的分在账上,重复领取不该被记成失败 ——
1939
+ * 自动化每小时跑一次,记成失败会刷出一整片红字。
1940
+ *
1941
+ * 未开放(1002/1003/40901/41000)同样是「今天没有可领的」,不是故障;
1942
+ * 抛错会让调度器一直重试一个永远不会成功的结果。
1943
+ */
1944
+ if (response.ok && (CHECKIN_ALREADY_CODES.has(envelope.code) || CHECKIN_INACTIVE_CODES.has(envelope.code))) return neutral(payload);
1494
1945
  if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
1495
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
1946
+ const data = payload;
1496
1947
  const numberField = (key) => typeof data[key] === "number" ? data[key] : 0;
1497
1948
  return {
1498
1949
  credit: numberField("credit"),
@@ -3283,7 +3734,7 @@ function parseWorkBuddyAuth(text, sourcePath, decrypt) {
3283
3734
  * app itself is using.
3284
3735
  */
3285
3736
  function isLiveAuthFile(path) {
3286
- return basename(path) === WORKBUDDY_LIVE_FILENAME;
3737
+ return basename(path) === "workbuddy-desktop.info" && existsSync(path);
3287
3738
  }
3288
3739
  /**
3289
3740
  * True for a credential this plugin minted from the channel-pack sign-in flow.
@@ -3736,6 +4187,27 @@ var WorkBuddyAccountPool = class {
3736
4187
  */
3737
4188
  creditBalances = /* @__PURE__ */ new Map();
3738
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
+ /**
3739
4211
  * Nearest expiry among each account's one-off credit packs, epoch ms.
3740
4212
  *
3741
4213
  * Credit packs are use-it-or-lose-it, so "which account should serve next"
@@ -3832,6 +4304,8 @@ var WorkBuddyAccountPool = class {
3832
4304
  this.storePath = accountStorePath();
3833
4305
  this.affinityPath = options.affinityPath;
3834
4306
  if (this.affinityPath !== void 0) this.loadAffinity();
4307
+ this.creditBalancePath = options.creditBalancePath;
4308
+ if (this.creditBalancePath !== void 0) this.loadCreditBalances();
3835
4309
  }
3836
4310
  /**
3837
4311
  * Re-apply configuration that only affects discovery and cooldown policy,
@@ -4176,6 +4650,23 @@ var WorkBuddyAccountPool = class {
4176
4650
  });
4177
4651
  }
4178
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
+ /**
4179
4670
  * The pool ordered into three bands, so a resting account is deferred instead of
4180
4671
  * discarded.
4181
4672
  *
@@ -4708,8 +5199,43 @@ var WorkBuddyAccountPool = class {
4708
5199
  noteCredits(accountId, balance, nearestExpiryMs) {
4709
5200
  if (!Number.isFinite(balance)) return;
4710
5201
  if (!this.accounts.some((account) => account.id === accountId)) return;
5202
+ const changed = this.creditBalances.get(accountId) !== balance;
4711
5203
  this.creditBalances.set(accountId, balance);
4712
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 {}
4713
5239
  }
4714
5240
  /**
4715
5241
  * Record ONLY the deadline, never the balance.
@@ -4931,6 +5457,22 @@ var WorkBuddyAccountPool = class {
4931
5457
  * Returns true when the token is known good afterwards (refreshed, or still
4932
5458
  * valid), false when the credential was proven dead.
4933
5459
  */
5460
+ /**
5461
+ * 取一个账号「可以用来发一次请求」的凭据:过期就先刷新。
5462
+ *
5463
+ * 签到 / 积分这些端点走的是「按 id 直接找账号」的路径,和选号路径不同 ——
5464
+ * 以前它们直接拿池里的 `account.credential`,凭据过期时上游回 401,界面只能
5465
+ * 说「领取失败」,而同一时刻对话却正常(对话走 `getAvailableAccount`,那里会
5466
+ * 先 `ensureFresh`)。用户反馈的「积分领取全部失败」就是这一处。
5467
+ *
5468
+ * 返回 undefined 表示「刷新失败」:调用方应当直接告诉用户重新登录,
5469
+ * 而不是拿旧 token 再去撞一次 401。
5470
+ */
5471
+ async freshCredential(id) {
5472
+ const account = this.accounts.find((item) => item.id === id);
5473
+ if (account === void 0) return void 0;
5474
+ return await this.ensureFresh(account) ? account.credential : void 0;
5475
+ }
4934
5476
  async ensureFresh(account, force = false) {
4935
5477
  if (this.client === void 0) return true;
4936
5478
  const credential = account.credential;
@@ -5160,7 +5702,7 @@ const MAGICREW_CN = Object.freeze({
5160
5702
  displayName: "超级麦吉",
5161
5703
  host: "https://i-magic-service.letsmagic.cn",
5162
5704
  webOrigin: "https://www.letsmagic.cn",
5163
- needsOrg: false,
5705
+ needsOrg: true,
5164
5706
  defaultRef: "magicrew"
5165
5707
  });
5166
5708
  const MAGICREW_INTL = Object.freeze({
@@ -5663,16 +6205,26 @@ var WorkBuddyCatalog = class {
5663
6205
  * is recoverable in one click whereas "nothing" looks like a broken install.
5664
6206
  */
5665
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
+ */
5666
6218
  const images = this.selection.imageModelIds;
5667
- const imageSet = images === void 0 ? void 0 : new Set(images);
6219
+ const imageSet = images === void 0 || images.length === 0 ? void 0 : new Set(images);
5668
6220
  const budgets = this.selection.contextBudgets;
5669
- 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) => {
5670
6222
  const next = { ...model };
5671
6223
  if (imageSet !== void 0) next.supportsImages = imageSet.has(model.id);
5672
6224
  const budget = budgets?.[model.id];
5673
6225
  if (budget !== void 0 && budget > 0 && budget < next.contextWindow) next.contextWindow = budget;
5674
6226
  return next;
5675
- });
6227
+ }));
5676
6228
  }
5677
6229
  /** Replace the catalog and notify the adapter to rebuild its model list. */
5678
6230
  update(models) {
@@ -10749,6 +11301,7 @@ const PROVIDERS = Object.freeze([
10749
11301
  "baseUrl": "",
10750
11302
  "format": "openai-chat",
10751
11303
  "models": [],
11304
+ "modelsUrl": "/models",
10752
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.",
10753
11306
  "website": null,
10754
11307
  "local": false,
@@ -10765,6 +11318,54 @@ Object.freeze({
10765
11318
  "openai-responses": "/responses",
10766
11319
  "anthropic-messages": "/messages"
10767
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
+ });
10768
11369
  Object.freeze({
10769
11370
  "openai-chat": "chat",
10770
11371
  "openai-responses": "responses",
@@ -11258,6 +11859,58 @@ function expertChatEvents(expert, conversationId, requestId) {
11258
11859
  expert_industry_id: ""
11259
11860
  } : event);
11260
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
+ }
11261
11914
  /**
11262
11915
  * The fallback record for the 腾讯轻量云 expert, used when the marketplace
11263
11916
  * listing cannot be read. The id is the one the task is scored against.
@@ -11386,6 +12039,7 @@ function zonedParts(date, timeZone = AUTOMATION_TIME_ZONE) {
11386
12039
  month: "2-digit",
11387
12040
  day: "2-digit",
11388
12041
  hour: "2-digit",
12042
+ minute: "2-digit",
11389
12043
  hourCycle: "h23"
11390
12044
  }).formatToParts(date);
11391
12045
  const pick = (type) => parts.find((part) => part.type === type)?.value ?? "00";
@@ -11393,7 +12047,8 @@ function zonedParts(date, timeZone = AUTOMATION_TIME_ZONE) {
11393
12047
  year: pick("year"),
11394
12048
  month: pick("month"),
11395
12049
  day: pick("day"),
11396
- hour: pick("hour")
12050
+ hour: pick("hour"),
12051
+ minute: pick("minute")
11397
12052
  };
11398
12053
  }
11399
12054
  function dayKey(date, timeZone = AUTOMATION_TIME_ZONE) {
@@ -11525,7 +12180,7 @@ var WorkBuddyScheduler = class {
11525
12180
  this.client = client;
11526
12181
  this.logger = options.logger ?? {};
11527
12182
  this.now = options.now ?? (() => /* @__PURE__ */ new Date());
11528
- this.delayMs = options.accountDelayMs ?? 800;
12183
+ this.delayMs = options.accountDelayMs ?? PACING_ACCOUNT_DELAY_MS;
11529
12184
  this.eventScoreWaitMs = options.eventScoreWaitMs ?? 9e3;
11530
12185
  this.expertGapMs = options.expertGapMs ?? 6e3;
11531
12186
  this.loadEarnings = options.loadEarnings;
@@ -11651,27 +12306,50 @@ var WorkBuddyScheduler = class {
11651
12306
  * report would have moved. This is what the card's single button calls.
11652
12307
  */
11653
12308
  /**
11654
- * Start a full pass in the background and return immediately.
12309
+ * Start a pass in the background and return immediately.
11655
12310
  *
11656
12311
  * A pass takes tens of seconds - one upstream round trip per account per job,
11657
12312
  * plus the scoring wait - which is far too long to hold the card request open:
11658
12313
  * the browser or the host web server would time out, and the user would see
11659
12314
  * a hung button for a run that is actually working.
11660
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
+ *
11661
12321
  * Returns whether a run started. A second call while one is in flight is
11662
12322
  * ignored rather than queued: pressing the button twice means hurry up, and
11663
12323
  * the run already under way covers it.
11664
12324
  */
11665
- startRunAll() {
12325
+ startRunAll(job = "all", force = false) {
11666
12326
  if (this.runInFlight) return false;
11667
12327
  this.runInFlight = true;
11668
- this.runAll().catch((error) => {
12328
+ (job === "all" ? this.runAll() : this.runNow(job, force).then(() => void 0)).catch((error) => {
11669
12329
  this.logger.warn?.("dsh-xdpool automation run failed:", error);
11670
12330
  }).finally(() => {
11671
12331
  this.runInFlight = false;
11672
12332
  });
11673
12333
  return true;
11674
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
+ }
11675
12353
  async runAll() {
11676
12354
  const today = dayKey(this.now());
11677
12355
  const before = this.earningsSnapshot();
@@ -11752,13 +12430,17 @@ var WorkBuddyScheduler = class {
11752
12430
  dueSlot(kind, now) {
11753
12431
  const hours = this.hoursOf(kind);
11754
12432
  if (hours.length === 0) return void 0;
11755
- const current = Number(zonedParts(now).hour);
12433
+ const parts = zonedParts(now);
12434
+ const current = Number(parts.hour);
12435
+ const currentMinute = Number(parts.minute);
11756
12436
  const today = dayKey(now);
11757
12437
  const fired = this.firedSlotsOf(kind);
11758
12438
  for (const candidate of [...hours].sort((a, b) => a - b)) {
11759
12439
  if (candidate > current) break;
11760
12440
  const slot = `${today}T${String(candidate).padStart(2, "0")}`;
11761
- if (!fired.has(slot)) return slot;
12441
+ if (fired.has(slot)) continue;
12442
+ if (candidate === current && currentMinute < slotMinuteOffset(slot)) break;
12443
+ return slot;
11762
12444
  }
11763
12445
  }
11764
12446
  /** Today's consumed slots for one job, as a set. */
@@ -11930,18 +12612,52 @@ var WorkBuddyScheduler = class {
11930
12612
  try {
11931
12613
  switch (kind) {
11932
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
+ }
11933
12626
  let alreadyDone = false;
12627
+ let activityClosed = false;
12628
+ let alreadyPaid = 0;
11934
12629
  try {
11935
- 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);
11936
12641
  } catch (error) {
11937
12642
  this.logger.warn?.(`automation checkin ${account.label}: status read failed, claiming anyway:`, error);
11938
12643
  }
11939
12644
  if (alreadyDone) {
11940
- 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
+ });
11941
12657
  break;
11942
12658
  }
11943
12659
  try {
11944
- const claim = await this.client.claimDailyCheckin(account.credential);
12660
+ const claim = await this.client.claimDailyCheckin(fresh);
11945
12661
  this.recordEarnings(account.id, today, { checkinCredit: claim.credit });
11946
12662
  if (claim.credit > 0) {
11947
12663
  detail.push(`签到 +${claim.credit}`);
@@ -11949,7 +12665,15 @@ var WorkBuddyScheduler = class {
11949
12665
  }
11950
12666
  } catch (error) {
11951
12667
  if (!isAlreadyCheckin(error)) throw error;
11952
- 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})`);
11953
12677
  }
11954
12678
  break;
11955
12679
  }
@@ -11998,7 +12722,7 @@ var WorkBuddyScheduler = class {
11998
12722
  failed++;
11999
12723
  this.logger.warn?.(`automation ${accountWord} ${account.label} failed:`, error);
12000
12724
  }
12001
- 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));
12002
12726
  }
12003
12727
  const state = this.states[kind];
12004
12728
  if (consumedSlot !== void 0) this.consumeSlot(kind, consumedSlot);
@@ -12091,7 +12815,7 @@ var WorkBuddyScheduler = class {
12091
12815
  this.logger.warn?.(`automation events ${account.label}: ${task.taskCode} failed:`, error);
12092
12816
  break;
12093
12817
  }
12094
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
12818
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12095
12819
  }
12096
12820
  }
12097
12821
  }
@@ -12216,7 +12940,7 @@ var WorkBuddyScheduler = class {
12216
12940
  }
12217
12941
  const expert = expertFromTask(expertId, task.title);
12218
12942
  await this.client.reportDesktopEvents(credential, expertSummonEvents(expert));
12219
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
12943
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12220
12944
  const chat = await this.client.openConversation(credential, expert.expertId);
12221
12945
  if (chat === void 0) throw new Error(`${task.taskCode}: no server conversation`);
12222
12946
  return [{
@@ -12242,7 +12966,7 @@ var WorkBuddyScheduler = class {
12242
12966
  if (this.stopped) break;
12243
12967
  try {
12244
12968
  await this.client.reportDesktopEvents(credential, expertSummonEvents(expert));
12245
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
12969
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12246
12970
  const chat = await this.client.openConversation(credential, expert.expertId);
12247
12971
  if (chat === void 0) continue;
12248
12972
  out.push({
@@ -12273,7 +12997,7 @@ var WorkBuddyScheduler = class {
12273
12997
  this.logger.warn?.("automation events lighthouse list:", error);
12274
12998
  }
12275
12999
  await this.client.reportDesktopEvents(credential, expertSummonEvents(expert));
12276
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
13000
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12277
13001
  const chat = await this.client.openConversation(credential, expert.expertId);
12278
13002
  if (chat === void 0) throw new Error("Expert_lighthouse: no server conversation");
12279
13003
  const use = expertActualUseEvent(expert, chat.conversationId, chat.requestId, "LOCAL");
@@ -12331,7 +13055,7 @@ var WorkBuddyScheduler = class {
12331
13055
  });
12332
13056
  this.logger.info?.(`automation claim ${account.label}: ${task.taskCode} already claimed`);
12333
13057
  }
12334
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
13058
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12335
13059
  }
12336
13060
  return {
12337
13061
  claimed,
@@ -12365,7 +13089,7 @@ var WorkBuddyScheduler = class {
12365
13089
  } catch (error) {
12366
13090
  this.logger.warn?.(`automation streak ${account.label}: redeem ${tier.tier} failed:`, error);
12367
13091
  }
12368
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
13092
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12369
13093
  }
12370
13094
  const chances = await this.client.lotteryChances(credential);
12371
13095
  for (let draw = 0; draw < chances; draw += 1) {
@@ -12377,7 +13101,7 @@ var WorkBuddyScheduler = class {
12377
13101
  this.logger.warn?.(`automation lottery ${account.label}: draw failed:`, error);
12378
13102
  break;
12379
13103
  }
12380
- if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
13104
+ if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
12381
13105
  }
12382
13106
  const pendingTier = status.tiers.find((tier) => tier.status === "locked");
12383
13107
  if (pendingTier !== void 0) {
@@ -12539,6 +13263,7 @@ Object.freeze({
12539
13263
  "Write the briefing only — no preamble, no markdown fence."
12540
13264
  ].join("\n");
12541
13265
  join("channel-pack", "token-ledger.json");
13266
+ join("channel-pack", "token-ledger.json");
12542
13267
  //#endregion
12543
13268
  //#region src/status.ts
12544
13269
  /** Format the per-model credit multipliers. */
@@ -12550,6 +13275,7 @@ function formatRates(status) {
12550
13275
  }
12551
13276
  return lines.join("\n");
12552
13277
  }
13278
+ join(".xdpool", "spend-cache.json");
12553
13279
  Object.freeze({
12554
13280
  "workbuddy-xdpool": "xdpool",
12555
13281
  "workbuddy-xdpool-global": "xdpool-global",
@@ -12643,10 +13369,25 @@ async function writePreferredId(accountId, path = preferredIdPath()) {
12643
13369
  }
12644
13370
  fileURLToPath(new URL("..", import.meta.url));
12645
13371
  (() => {
13372
+ /**
13373
+ * issue #208:原来用 `../../node_modules/@deepseek-ai/dsh-llm-pi-ai/`:
13374
+ * `import.meta.url` 是 `<profile>/node_modules/dsh-xdpool/lib/index.js`,`../../`
13375
+ * 已经落到 `<profile>/node_modules/`,再拼 `node_modules/...` 就成了
13376
+ * `<profile>/node_modules/node_modules/...` —— 多一层,永远解析不到,守卫因此
13377
+ * 长期返回 unknown、日志里一个字都不写,而真正的 0.82 / 1.5 代际错配照样崩。
13378
+ *
13379
+ * 现在优先用 createRequire 从插件自身解析宿主包(pnpm / hoisted / 全局安装都
13380
+ * 能覆盖),再退回少一层的相对路径。createRequire 在 ESM bundle 里也可用。
13381
+ */
12646
13382
  try {
12647
- return fileURLToPath(new URL("../../node_modules/@deepseek-ai/dsh-llm-pi-ai/", import.meta.url));
13383
+ const require_ = createRequire(import.meta.url);
13384
+ return dirname(require_.resolve("@deepseek-ai/dsh-llm-pi-ai/package.json"));
12648
13385
  } catch {
12649
- return "";
13386
+ try {
13387
+ return fileURLToPath(new URL("../node_modules/@deepseek-ai/dsh-llm-pi-ai/", import.meta.url));
13388
+ } catch {
13389
+ return "";
13390
+ }
12650
13391
  }
12651
13392
  })();
12652
13393
  /**
@@ -12727,7 +13468,16 @@ z.object({
12727
13468
  disabledAccountIds: asVolatile(z.array(z.string()).default([]).description("Account ids excluded from the pool (empty = every discovered account participates)")),
12728
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")),
12729
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")),
12730
- 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)")),
12731
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")),
12732
13482
  modelSelectionCn: asVolatile(modelSelectionSchema.description("Model selection for the domestic gateway")),
12733
13483
  modelSelectionGlobal: asVolatile(modelSelectionSchema.description("Model selection for the international gateway")),
@@ -12771,7 +13521,8 @@ function createCore(logger) {
12771
13521
  ...logger === void 0 ? {} : { logger },
12772
13522
  client,
12773
13523
  persistent: true,
12774
- affinityPath: join(pluginDataDir(), "sticky-affinity.json")
13524
+ affinityPath: join(pluginDataDir(), "sticky-affinity.json"),
13525
+ creditBalancePath: join(pluginDataDir(), "credit-balances.json")
12775
13526
  });
12776
13527
  return {
12777
13528
  pool,