dsh-xdpool 3.0.7 → 3.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -0
- package/README.md +16 -21
- package/assets/community-qr-qq.jpg +0 -0
- package/assets/icon.png +0 -0
- package/assets/xdpool-banner.gif +0 -0
- package/lib/bin.js +1030 -66
- package/lib/client.js +1488 -274
- package/lib/index.d.ts +507 -14
- package/lib/index.js +6158 -641
- package/package.json +1 -2
- package/vendor/channel-pack/pack.js +184 -49
package/lib/bin.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
2
|
import { createDecipheriv, createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
|
|
4
|
-
import { chmod, copyFile, mkdir, readFile, readdir, rename, rm, unlink, writeFile, writeFile as writeFile$1 } from "node:fs/promises";
|
|
5
|
-
import { homedir, platform } from "node:os";
|
|
4
|
+
import { chmod, copyFile, mkdir, open, readFile, readdir, rename, rm, unlink, writeFile, writeFile as writeFile$1 } from "node:fs/promises";
|
|
5
|
+
import { homedir, hostname, platform } from "node:os";
|
|
6
6
|
import { basename, dirname, join, resolve } from "node:path";
|
|
7
7
|
import { execFile, execFileSync } from "node:child_process";
|
|
8
8
|
import "@deepseek-ai/dsh-llm";
|
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
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`, {
|
|
@@ -2436,6 +2834,59 @@ async function unignoreAccount(accountId, path = ignoredIdsPath()) {
|
|
|
2436
2834
|
return next;
|
|
2437
2835
|
}
|
|
2438
2836
|
//#endregion
|
|
2837
|
+
//#region src/store-lock.ts
|
|
2838
|
+
/**
|
|
2839
|
+
* Serialize the read-modify-write cycles on a store file.
|
|
2840
|
+
*
|
|
2841
|
+
* WHY THIS IS NEEDED
|
|
2842
|
+
*
|
|
2843
|
+
* Every credential store does the same three steps: load the list, replace one entry, write the
|
|
2844
|
+
* list back. Two of those interleaved lose one entry — the second write starts from a list that
|
|
2845
|
+
* predates the first, so the entry the first added is simply absent from what lands on disk. It
|
|
2846
|
+
* is not a rare race either: signing into two channels of the same family in quick succession is
|
|
2847
|
+
* ordinary use, and a lost credential looks exactly like a sign-in that never worked.
|
|
2848
|
+
*
|
|
2849
|
+
* The atomic `rename` most of these stores already do makes the FILE consistent; it does not
|
|
2850
|
+
* make the READ-MODIFY-WRITE consistent, which is a different guarantee.
|
|
2851
|
+
*
|
|
2852
|
+
* HOW
|
|
2853
|
+
*
|
|
2854
|
+
* One promise chain per file path. Each cycle appends to the chain, so the cycles run one after
|
|
2855
|
+
* another in the order they were requested. A failure does not poison the chain — the next
|
|
2856
|
+
* caller still runs — and the chain is dropped once it drains, so a long-lived process does not
|
|
2857
|
+
* accumulate promises.
|
|
2858
|
+
*
|
|
2859
|
+
* @module dsh-xdpool/store-lock
|
|
2860
|
+
*/
|
|
2861
|
+
/** The tail of each path's chain. */
|
|
2862
|
+
const chains = /* @__PURE__ */ new Map();
|
|
2863
|
+
/**
|
|
2864
|
+
* Run `work` once every earlier call for the same key has settled.
|
|
2865
|
+
*
|
|
2866
|
+
* The key is normally the store's absolute path: two stores in different files do not contend,
|
|
2867
|
+
* and two writers of the same file must not interleave.
|
|
2868
|
+
*/
|
|
2869
|
+
async function withStoreLock(key, work) {
|
|
2870
|
+
/**
|
|
2871
|
+
* `previous.catch` keeps a rejected earlier cycle from skipping this one: the chain exists to
|
|
2872
|
+
* order writes, not to propagate failures.
|
|
2873
|
+
*/
|
|
2874
|
+
const next = (chains.get(key) ?? Promise.resolve()).catch(() => void 0).then(work);
|
|
2875
|
+
const guarded = next.catch(() => void 0);
|
|
2876
|
+
chains.set(key, guarded);
|
|
2877
|
+
try {
|
|
2878
|
+
return await next;
|
|
2879
|
+
} finally {
|
|
2880
|
+
/**
|
|
2881
|
+
* Drop the entry once nothing is queued behind it.
|
|
2882
|
+
*
|
|
2883
|
+
* Without this the map grows with every store the process ever touched — small, but it also
|
|
2884
|
+
* keeps every resolved promise alive for the life of the session.
|
|
2885
|
+
*/
|
|
2886
|
+
if (chains.get(key) === guarded) chains.delete(key);
|
|
2887
|
+
}
|
|
2888
|
+
}
|
|
2889
|
+
//#endregion
|
|
2439
2890
|
//#region src/account-store.ts
|
|
2440
2891
|
/**
|
|
2441
2892
|
* Durable copy of the discovered accounts, inside the plugin's data directory.
|
|
@@ -2486,43 +2937,205 @@ function isStoredAccount(value) {
|
|
|
2486
2937
|
if (typeof value !== "object" || value === null) return false;
|
|
2487
2938
|
const record = value;
|
|
2488
2939
|
const credential = record["credential"];
|
|
2489
|
-
return typeof record["id"] === "string" && typeof record["label"] === "string" && typeof credential === "object" && credential !== null && typeof credential["accessToken"] === "string" && typeof credential["refreshToken"] === "string";
|
|
2940
|
+
return typeof record["id"] === "string" && typeof record["label"] === "string" && typeof credential === "object" && credential !== null && typeof credential["accessToken"] === "string" && typeof credential["refreshToken"] === "string" && typeof credential["sourcePath"] === "string" && typeof credential["domain"] === "string" && Number.isFinite(credential["expiresAtMs"]);
|
|
2490
2941
|
}
|
|
2491
|
-
|
|
2492
|
-
* Read the durable list. Tolerant on purpose: a malformed or half-written file
|
|
2493
|
-
* yields `[]` and the pool simply rediscovers from disk, rather than a corrupt
|
|
2494
|
-
* store taking the whole pool down.
|
|
2495
|
-
*/
|
|
2496
|
-
async function loadStoredAccounts(path) {
|
|
2942
|
+
async function inspectStore(path) {
|
|
2497
2943
|
let text;
|
|
2498
2944
|
try {
|
|
2499
2945
|
text = await readFile(path, "utf8");
|
|
2946
|
+
} catch (error) {
|
|
2947
|
+
if (error.code === "ENOENT") return {
|
|
2948
|
+
accounts: [],
|
|
2949
|
+
safe: true
|
|
2950
|
+
};
|
|
2951
|
+
throw error;
|
|
2952
|
+
}
|
|
2953
|
+
try {
|
|
2954
|
+
const document = JSON.parse(text);
|
|
2955
|
+
if (document?.version !== 1 || !Array.isArray(document.accounts)) return {
|
|
2956
|
+
text,
|
|
2957
|
+
accounts: [],
|
|
2958
|
+
safe: false
|
|
2959
|
+
};
|
|
2960
|
+
const accounts = [];
|
|
2961
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2962
|
+
let safe = true;
|
|
2963
|
+
for (const entry of document.accounts) {
|
|
2964
|
+
if (!isStoredAccount(entry) || seen.has(entry.id)) {
|
|
2965
|
+
safe = false;
|
|
2966
|
+
continue;
|
|
2967
|
+
}
|
|
2968
|
+
seen.add(entry.id);
|
|
2969
|
+
accounts.push(entry);
|
|
2970
|
+
}
|
|
2971
|
+
return {
|
|
2972
|
+
text,
|
|
2973
|
+
accounts,
|
|
2974
|
+
safe
|
|
2975
|
+
};
|
|
2500
2976
|
} catch {
|
|
2501
|
-
return
|
|
2977
|
+
return {
|
|
2978
|
+
text,
|
|
2979
|
+
accounts: [],
|
|
2980
|
+
safe: false
|
|
2981
|
+
};
|
|
2502
2982
|
}
|
|
2503
|
-
|
|
2983
|
+
}
|
|
2984
|
+
/** Keep the old primary present until replacement; every temporary has a unique name. */
|
|
2985
|
+
async function replaceSecret(path, text) {
|
|
2986
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
2504
2987
|
try {
|
|
2505
|
-
|
|
2988
|
+
await writeSecretFile(temporary, text);
|
|
2989
|
+
await rename(temporary, path);
|
|
2990
|
+
} finally {
|
|
2991
|
+
await unlink(temporary).catch((error) => {
|
|
2992
|
+
if (error.code !== "ENOENT") throw error;
|
|
2993
|
+
});
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
/**
|
|
2997
|
+
* How long one transaction waits for a live holder before giving up.
|
|
2998
|
+
*
|
|
2999
|
+
* Read per call rather than at import time so a test can shorten the wait; the
|
|
3000
|
+
* default is the production 5 s.
|
|
3001
|
+
*/
|
|
3002
|
+
function storeLockWaitMs() {
|
|
3003
|
+
const raw = Number(process.env["DSH_XDPOOL_STORE_LOCK_WAIT_MS"] ?? "");
|
|
3004
|
+
return Number.isSafeInteger(raw) && raw >= 50 ? raw : 5e3;
|
|
3005
|
+
}
|
|
3006
|
+
/** Read the owner record, or undefined when the file cannot prove one. */
|
|
3007
|
+
async function readStoreLockOwner(lockPath) {
|
|
3008
|
+
try {
|
|
3009
|
+
const parsed = JSON.parse(await readFile(lockPath, "utf8"));
|
|
3010
|
+
if (typeof parsed.pid !== "number" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0) return void 0;
|
|
3011
|
+
return {
|
|
3012
|
+
pid: parsed.pid,
|
|
3013
|
+
host: typeof parsed.host === "string" ? parsed.host : "",
|
|
3014
|
+
startedAt: typeof parsed.startedAt === "string" ? parsed.startedAt : ""
|
|
3015
|
+
};
|
|
2506
3016
|
} catch {
|
|
2507
|
-
return
|
|
3017
|
+
return;
|
|
2508
3018
|
}
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
3019
|
+
}
|
|
3020
|
+
/**
|
|
3021
|
+
* Whether the recorded owner is provably gone.
|
|
3022
|
+
*
|
|
3023
|
+
* Only a PID from THIS host can be judged; another machine's lock stays
|
|
3024
|
+
* untouchable because its PID numbers mean nothing here. A PID that still
|
|
3025
|
+
* exists counts as alive even when its holder is unrelated (EPERM), and a
|
|
3026
|
+
* reused PID can therefore only ever make us MORE conservative.
|
|
3027
|
+
*/
|
|
3028
|
+
function storeLockOwnerIsDead(owner) {
|
|
3029
|
+
if (owner.host !== hostname()) return false;
|
|
3030
|
+
try {
|
|
3031
|
+
process.kill(owner.pid, 0);
|
|
3032
|
+
return false;
|
|
3033
|
+
} catch (error) {
|
|
3034
|
+
return error.code === "ESRCH";
|
|
2518
3035
|
}
|
|
2519
|
-
return out;
|
|
2520
3036
|
}
|
|
2521
3037
|
/**
|
|
2522
|
-
*
|
|
2523
|
-
*
|
|
3038
|
+
* Serialize the entire scan/read/merge/write, including across cooperating processes.
|
|
3039
|
+
*
|
|
3040
|
+
* A lock whose recorded owner is provably dead is reclaimed once; anything else
|
|
3041
|
+
* fails closed, because a live holder must never have its write interleaved.
|
|
3042
|
+
*
|
|
3043
|
+
* This used to fail closed for EVERY orphan as well, which bricked the store:
|
|
3044
|
+
* a crash between create and release left an empty lock that the plugin then
|
|
3045
|
+
* refused to pass forever — no write, no repair, and no way out short of
|
|
3046
|
+
* deleting the file by hand (found on the real profile, 2026-12-05).
|
|
3047
|
+
*/
|
|
3048
|
+
async function withAccountStoreTransaction(path, work) {
|
|
3049
|
+
return withStoreLock(path, async () => {
|
|
3050
|
+
await ensureSecretDir(join(path, ".."));
|
|
3051
|
+
const lockPath = `${path}.lock`;
|
|
3052
|
+
const deadline = Date.now() + storeLockWaitMs();
|
|
3053
|
+
let handle;
|
|
3054
|
+
let reclaimed = false;
|
|
3055
|
+
while (handle === void 0) try {
|
|
3056
|
+
handle = await open(lockPath, "wx", 384);
|
|
3057
|
+
const owner = {
|
|
3058
|
+
pid: process.pid,
|
|
3059
|
+
host: hostname(),
|
|
3060
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3061
|
+
};
|
|
3062
|
+
await handle.write(JSON.stringify(owner));
|
|
3063
|
+
} catch (error) {
|
|
3064
|
+
if (handle !== void 0) {
|
|
3065
|
+
await handle.close().catch(() => void 0);
|
|
3066
|
+
await unlink(lockPath).catch(() => void 0);
|
|
3067
|
+
handle = void 0;
|
|
3068
|
+
}
|
|
3069
|
+
if (error.code !== "EEXIST") throw error;
|
|
3070
|
+
if (Date.now() >= deadline) {
|
|
3071
|
+
if (!reclaimed) {
|
|
3072
|
+
const owner = await readStoreLockOwner(lockPath);
|
|
3073
|
+
if (owner !== void 0 && storeLockOwnerIsDead(owner)) {
|
|
3074
|
+
await unlink(lockPath).catch(() => void 0);
|
|
3075
|
+
reclaimed = true;
|
|
3076
|
+
continue;
|
|
3077
|
+
}
|
|
3078
|
+
throw new Error(`Account store is locked by ${owner === void 0 ? "an unidentifiable owner (no readable owner record)" : `pid ${owner.pid} on ${owner.host} since ${owner.startedAt}`}; lock file: ${lockPath}. If that process is gone, remove the file or run the plugin's "unlock" command.`);
|
|
3079
|
+
}
|
|
3080
|
+
throw new Error(`Account store stayed locked after reclaiming a dead owner; lock file: ${lockPath}`);
|
|
3081
|
+
}
|
|
3082
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
3083
|
+
}
|
|
3084
|
+
try {
|
|
3085
|
+
return await work();
|
|
3086
|
+
} finally {
|
|
3087
|
+
await handle.close();
|
|
3088
|
+
await unlink(lockPath);
|
|
3089
|
+
}
|
|
3090
|
+
});
|
|
3091
|
+
}
|
|
3092
|
+
/**
|
|
3093
|
+
* Read valid records with diagnostics. A damaged primary is never rewritten;
|
|
3094
|
+
* a validated previous generation can supply missing records in memory.
|
|
3095
|
+
*/
|
|
3096
|
+
async function loadStoredAccounts(path, warn = (message) => process.emitWarning(message)) {
|
|
3097
|
+
const primary = await inspectStore(path);
|
|
3098
|
+
if (primary.safe) return primary.accounts;
|
|
3099
|
+
warn("Account store has invalid entries or structure; preserving the original and blocking replacement");
|
|
3100
|
+
const backup = await inspectStore(`${path}.bak`);
|
|
3101
|
+
if (!backup.safe) throw new Error("Account store and backup are invalid; manual recovery required");
|
|
3102
|
+
const merged = new Map(primary.accounts.map((account) => [account.id, account]));
|
|
3103
|
+
for (const account of backup.accounts) if (!merged.has(account.id)) merged.set(account.id, account);
|
|
3104
|
+
return [...merged.values()];
|
|
3105
|
+
}
|
|
3106
|
+
/**
|
|
3107
|
+
* Back up the validated primary before replacing it with a unique temporary.
|
|
3108
|
+
* The caller must hold the transaction over its entire read/merge/write cycle.
|
|
2524
3109
|
*/
|
|
2525
3110
|
async function saveStoredAccounts(path, accounts) {
|
|
3111
|
+
const previous = await inspectStore(path);
|
|
3112
|
+
/**
|
|
3113
|
+
* An invalid primary is quarantined rather than written over.
|
|
3114
|
+
*
|
|
3115
|
+
* Refusing outright left the store permanently unwritable: the pool kept
|
|
3116
|
+
* serving from the backup-derived list in memory, but every new sign-in was
|
|
3117
|
+
* lost on the next restart and nothing ever repaired the file. Moving the bad
|
|
3118
|
+
* generation aside keeps it for diagnosis (it is never deleted) while letting
|
|
3119
|
+
* a validated backup become the new baseline.
|
|
3120
|
+
*
|
|
3121
|
+
* The damaged text deliberately does NOT become the new `.bak`: that slot is
|
|
3122
|
+
* the last known-good generation, and overwriting it with garbage would turn
|
|
3123
|
+
* one corrupt file into two. When even the backup is unusable, nothing is
|
|
3124
|
+
* touched and the caller keeps the manual-recovery error.
|
|
3125
|
+
*/
|
|
3126
|
+
let quarantined;
|
|
3127
|
+
if (!previous.safe) {
|
|
3128
|
+
const backup = await inspectStore(`${path}.bak`);
|
|
3129
|
+
/**
|
|
3130
|
+
* Rebuilding needs a backup that actually holds something.
|
|
3131
|
+
*
|
|
3132
|
+
* An absent or empty backup would turn "repair" into "replace the user's list with whatever
|
|
3133
|
+
* is in memory", and a damaged file may still be hand-recoverable. Those cases keep refusing.
|
|
3134
|
+
*/
|
|
3135
|
+
if (backup.text === void 0 || !backup.safe || backup.accounts.length === 0) throw new Error("Refusing to overwrite an invalid account store; original preserved for recovery");
|
|
3136
|
+
quarantined = `${path}.corrupt-${(/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-").replaceAll(".", "-")}`;
|
|
3137
|
+
await rename(path, quarantined);
|
|
3138
|
+
}
|
|
2526
3139
|
const stored = accounts.map((account) => ({
|
|
2527
3140
|
id: account.id,
|
|
2528
3141
|
label: account.label,
|
|
@@ -2534,9 +3147,9 @@ async function saveStoredAccounts(path, accounts) {
|
|
|
2534
3147
|
accounts: stored
|
|
2535
3148
|
}, null, 2) + "\n";
|
|
2536
3149
|
await ensureSecretDir(join(path, ".."));
|
|
2537
|
-
|
|
2538
|
-
await
|
|
2539
|
-
|
|
3150
|
+
if (quarantined === void 0 && previous.text !== void 0) await replaceSecret(`${path}.bak`, previous.text);
|
|
3151
|
+
await replaceSecret(path, document);
|
|
3152
|
+
if (quarantined !== void 0) process.emitWarning(`dsh-xdpool: account store was invalid and has been preserved at ${quarantined}; the list was rebuilt from the last good backup`);
|
|
2540
3153
|
}
|
|
2541
3154
|
//#endregion
|
|
2542
3155
|
//#region src/at-rest.ts
|
|
@@ -3336,7 +3949,7 @@ function parseWorkBuddyAuth(text, sourcePath, decrypt) {
|
|
|
3336
3949
|
* app itself is using.
|
|
3337
3950
|
*/
|
|
3338
3951
|
function isLiveAuthFile(path) {
|
|
3339
|
-
return basename(path) ===
|
|
3952
|
+
return basename(path) === "workbuddy-desktop.info" && existsSync(path);
|
|
3340
3953
|
}
|
|
3341
3954
|
/**
|
|
3342
3955
|
* True for a credential this plugin minted from the channel-pack sign-in flow.
|
|
@@ -3373,9 +3986,9 @@ function isChannelPackSource(path) {
|
|
|
3373
3986
|
* cleared. The live file stays on top: that is the session the running desktop
|
|
3374
3987
|
* app is genuinely using right now, and it is newer than anything we mint.
|
|
3375
3988
|
*/
|
|
3376
|
-
function compareFreshness(a, b) {
|
|
3989
|
+
function compareFreshness(a, b, liveCredentials) {
|
|
3377
3990
|
const rankOf = (credential) => {
|
|
3378
|
-
if (
|
|
3991
|
+
if (liveCredentials.has(credential)) return 2;
|
|
3379
3992
|
if (isChannelPackSource(credential.sourcePath)) return 1;
|
|
3380
3993
|
return 0;
|
|
3381
3994
|
};
|
|
@@ -3388,8 +4001,8 @@ function compareFreshness(a, b) {
|
|
|
3388
4001
|
return b.expiresAtMs - a.expiresAtMs;
|
|
3389
4002
|
}
|
|
3390
4003
|
/** True when `candidate` should replace `incumbent` for the same account. */
|
|
3391
|
-
function isFresher(candidate, incumbent) {
|
|
3392
|
-
return compareFreshness(candidate, incumbent) < 0;
|
|
4004
|
+
function isFresher(candidate, incumbent, liveCredentials) {
|
|
4005
|
+
return compareFreshness(candidate, incumbent, liveCredentials) < 0;
|
|
3393
4006
|
}
|
|
3394
4007
|
function workbuddyAccountId(credential) {
|
|
3395
4008
|
const stable = credential.uin ?? credential.uid ?? credential.nickname ?? "unknown";
|
|
@@ -3789,6 +4402,27 @@ var WorkBuddyAccountPool = class {
|
|
|
3789
4402
|
*/
|
|
3790
4403
|
creditBalances = /* @__PURE__ */ new Map();
|
|
3791
4404
|
/**
|
|
4405
|
+
* Where the last known balances are mirrored, when the host supplies a path.
|
|
4406
|
+
*
|
|
4407
|
+
* The reserve floor is the last line of defence against an account being
|
|
4408
|
+
* drained, and it silently does nothing during the cold-start window when
|
|
4409
|
+
* `creditBalances` is still empty: `available()` keeps an account with no
|
|
4410
|
+
* reading in play, deliberately, so an unprobed pool is not stranded. That
|
|
4411
|
+
* default is right for a pool that has never been measured and wrong for one
|
|
4412
|
+
* measured ten seconds before the process restarted — the pool is then
|
|
4413
|
+
* scheduled straight past the floor the user set.
|
|
4414
|
+
*
|
|
4415
|
+
* Observed 2026-10-30: an account with a 20,000 floor and a real 2,869
|
|
4416
|
+
* balance was picked and drained, because the first request after a restart
|
|
4417
|
+
* arrived before any balance reading existed.
|
|
4418
|
+
*
|
|
4419
|
+
* Mirroring the readings closes that window without changing `available()`'s
|
|
4420
|
+
* semantics: it still sees "known" balances, just ones from the previous run.
|
|
4421
|
+
* The alternative — treating unknown as unusable — would turn a transient
|
|
4422
|
+
* credits-endpoint failure into a full outage.
|
|
4423
|
+
*/
|
|
4424
|
+
creditBalancePath;
|
|
4425
|
+
/**
|
|
3792
4426
|
* Nearest expiry among each account's one-off credit packs, epoch ms.
|
|
3793
4427
|
*
|
|
3794
4428
|
* Credit packs are use-it-or-lose-it, so "which account should serve next"
|
|
@@ -3843,6 +4477,8 @@ var WorkBuddyAccountPool = class {
|
|
|
3843
4477
|
*/
|
|
3844
4478
|
lastUsedAt = /* @__PURE__ */ new Map();
|
|
3845
4479
|
refreshInflight = /* @__PURE__ */ new Map();
|
|
4480
|
+
/** Three-way reconciliation anchor: only advanced after a successful store write. */
|
|
4481
|
+
persistedCredentials = /* @__PURE__ */ new Map();
|
|
3846
4482
|
/**
|
|
3847
4483
|
* Whether `scan()` seeds from and writes back the durable account store.
|
|
3848
4484
|
*
|
|
@@ -3885,6 +4521,8 @@ var WorkBuddyAccountPool = class {
|
|
|
3885
4521
|
this.storePath = accountStorePath();
|
|
3886
4522
|
this.affinityPath = options.affinityPath;
|
|
3887
4523
|
if (this.affinityPath !== void 0) this.loadAffinity();
|
|
4524
|
+
this.creditBalancePath = options.creditBalancePath;
|
|
4525
|
+
if (this.creditBalancePath !== void 0) this.loadCreditBalances();
|
|
3888
4526
|
}
|
|
3889
4527
|
/**
|
|
3890
4528
|
* Re-apply configuration that only affects discovery and cooldown policy,
|
|
@@ -3980,6 +4618,10 @@ var WorkBuddyAccountPool = class {
|
|
|
3980
4618
|
}
|
|
3981
4619
|
/** Rescan the auth directories and merge newly discovered accounts. */
|
|
3982
4620
|
async scan() {
|
|
4621
|
+
if (this.persistent) return withAccountStoreTransaction(this.storePath, () => this.scanTransaction());
|
|
4622
|
+
return this.scanTransaction();
|
|
4623
|
+
}
|
|
4624
|
+
async scanTransaction() {
|
|
3983
4625
|
const found = [];
|
|
3984
4626
|
const skipped = [];
|
|
3985
4627
|
/**
|
|
@@ -4064,13 +4706,36 @@ var WorkBuddyAccountPool = class {
|
|
|
4064
4706
|
} catch (error) {
|
|
4065
4707
|
this.logger?.warn?.("dsh-xdpool: could not read channel-pack accounts; desktop accounts only", error);
|
|
4066
4708
|
}
|
|
4709
|
+
const liveCredentials = new Set(found.filter((credential) => isLiveAuthFile(credential.sourcePath)));
|
|
4067
4710
|
const byId = /* @__PURE__ */ new Map();
|
|
4068
4711
|
for (const account of this.accounts) byId.set(account.id, account);
|
|
4069
4712
|
if (this.persistent) {
|
|
4070
|
-
const stored = await loadStoredAccounts(this.storePath)
|
|
4713
|
+
const stored = await loadStoredAccounts(this.storePath, (message) => {
|
|
4714
|
+
if (this.logger?.warn !== void 0) this.logger.warn(message);
|
|
4715
|
+
else process.emitWarning(message);
|
|
4716
|
+
});
|
|
4071
4717
|
for (const entry of stored) {
|
|
4072
4718
|
if (this.ignoredIds.size > 0 && this.ignoredIds.has(entry.id)) continue;
|
|
4073
|
-
|
|
4719
|
+
const existing = byId.get(entry.id);
|
|
4720
|
+
if (existing !== void 0) {
|
|
4721
|
+
const anchor = this.persistedCredentials.get(entry.id);
|
|
4722
|
+
const memory = JSON.stringify(existing.credential);
|
|
4723
|
+
const disk = JSON.stringify(entry.credential);
|
|
4724
|
+
if (anchor !== void 0 && disk !== anchor && memory !== disk) {
|
|
4725
|
+
if (memory !== anchor) throw new Error(`Account store conflict for ${entry.id}; both versions preserved, no write performed`);
|
|
4726
|
+
byId.set(entry.id, {
|
|
4727
|
+
...existing,
|
|
4728
|
+
credential: entry.credential,
|
|
4729
|
+
label: entry.label,
|
|
4730
|
+
credentialDeadUntilMs: 0
|
|
4731
|
+
});
|
|
4732
|
+
} else if (anchor === void 0 && isFresher(entry.credential, existing.credential, liveCredentials)) byId.set(entry.id, {
|
|
4733
|
+
...existing,
|
|
4734
|
+
credential: entry.credential,
|
|
4735
|
+
label: entry.label
|
|
4736
|
+
});
|
|
4737
|
+
continue;
|
|
4738
|
+
}
|
|
4074
4739
|
byId.set(entry.id, {
|
|
4075
4740
|
id: entry.id,
|
|
4076
4741
|
label: entry.label,
|
|
@@ -4104,7 +4769,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4104
4769
|
});
|
|
4105
4770
|
continue;
|
|
4106
4771
|
}
|
|
4107
|
-
if (isFresher(credential, existing.credential)) {
|
|
4772
|
+
if (isFresher(credential, existing.credential, liveCredentials)) {
|
|
4108
4773
|
const signedInAgain = credential.refreshToken !== existing.credential.refreshToken || credential.accessToken !== existing.credential.accessToken;
|
|
4109
4774
|
byId.set(id, {
|
|
4110
4775
|
...existing,
|
|
@@ -4115,7 +4780,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4115
4780
|
}
|
|
4116
4781
|
}
|
|
4117
4782
|
const ordered = [...byId.values()];
|
|
4118
|
-
ordered.sort((a, b) => compareFreshness(a.credential, b.credential));
|
|
4783
|
+
ordered.sort((a, b) => compareFreshness(a.credential, b.credential, liveCredentials));
|
|
4119
4784
|
this.accounts = ordered;
|
|
4120
4785
|
this.lastScanAtMs = Date.now();
|
|
4121
4786
|
this.warmExpiryReadings();
|
|
@@ -4123,6 +4788,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4123
4788
|
const leaving = this.lastPersistedIds === void 0 ? [] : [...this.lastPersistedIds].filter((id) => !this.accounts.some((account) => account.id === id));
|
|
4124
4789
|
if (leaving.length > 0) this.logger?.warn?.(`dsh-xdpool: ${String(leaving.length)} account(s) are no longer in the pool after a rescan and were removed from the store: ${leaving.join(", ")}. Their credentials are gone unless they are signed in again.`);
|
|
4125
4790
|
await saveStoredAccounts(this.storePath, this.accounts);
|
|
4791
|
+
this.persistedCredentials = new Map(this.accounts.map((account) => [account.id, JSON.stringify(account.credential)]));
|
|
4126
4792
|
this.lastPersistedIds = new Set(this.accounts.map((account) => account.id));
|
|
4127
4793
|
} catch (error) {
|
|
4128
4794
|
this.logger?.warn?.("dsh-xdpool: could not persist the account store", error);
|
|
@@ -4229,6 +4895,23 @@ var WorkBuddyAccountPool = class {
|
|
|
4229
4895
|
});
|
|
4230
4896
|
}
|
|
4231
4897
|
/**
|
|
4898
|
+
* Whether ANY account can serve this model right now.
|
|
4899
|
+
*
|
|
4900
|
+
* Exposed because the retry loop needs this answer *between* attempts, not
|
|
4901
|
+
* only when it starts one: after penalising the account that just returned
|
|
4902
|
+
* 429, the loop must know whether the next attempt has any chance. Without
|
|
4903
|
+
* it, a per-account rate limit walks the whole pool — each attempt is a
|
|
4904
|
+
* guaranteed 429 that also burns that account's quota for the model, so a
|
|
4905
|
+
* single request can leave every account cooling until the next day.
|
|
4906
|
+
*
|
|
4907
|
+
* `available()` already computes exactly this; it stays private because the
|
|
4908
|
+
* account objects it returns are mutable state the pool owns. This reports
|
|
4909
|
+
* the count only, which is all a caller should act on.
|
|
4910
|
+
*/
|
|
4911
|
+
anyAvailable(modelId, region, reserveExempt) {
|
|
4912
|
+
return this.available(Date.now(), modelId, region, reserveExempt).length > 0;
|
|
4913
|
+
}
|
|
4914
|
+
/**
|
|
4232
4915
|
* The pool ordered into three bands, so a resting account is deferred instead of
|
|
4233
4916
|
* discarded.
|
|
4234
4917
|
*
|
|
@@ -4381,6 +5064,13 @@ var WorkBuddyAccountPool = class {
|
|
|
4381
5064
|
}
|
|
4382
5065
|
usable += 1;
|
|
4383
5066
|
}
|
|
5067
|
+
if (usable > 0) return {
|
|
5068
|
+
total: inRegion.length,
|
|
5069
|
+
cooling,
|
|
5070
|
+
disabled,
|
|
5071
|
+
dead,
|
|
5072
|
+
reason: "none"
|
|
5073
|
+
};
|
|
4384
5074
|
if (dead > 0) return {
|
|
4385
5075
|
total: inRegion.length,
|
|
4386
5076
|
cooling,
|
|
@@ -4761,8 +5451,43 @@ var WorkBuddyAccountPool = class {
|
|
|
4761
5451
|
noteCredits(accountId, balance, nearestExpiryMs) {
|
|
4762
5452
|
if (!Number.isFinite(balance)) return;
|
|
4763
5453
|
if (!this.accounts.some((account) => account.id === accountId)) return;
|
|
5454
|
+
const changed = this.creditBalances.get(accountId) !== balance;
|
|
4764
5455
|
this.creditBalances.set(accountId, balance);
|
|
4765
5456
|
this.noteExpiryReading(accountId, nearestExpiryMs);
|
|
5457
|
+
if (changed) this.saveCreditBalances();
|
|
5458
|
+
}
|
|
5459
|
+
/**
|
|
5460
|
+
* Restore the balances mirrored by the previous run.
|
|
5461
|
+
*
|
|
5462
|
+
* Best effort by construction: an unreadable or missing file means "first
|
|
5463
|
+
* run", which is exactly the cold start the mirror exists to narrow rather
|
|
5464
|
+
* than to replace — the pool keeps working either way.
|
|
5465
|
+
*/
|
|
5466
|
+
loadCreditBalances() {
|
|
5467
|
+
if (this.creditBalancePath === void 0) return;
|
|
5468
|
+
try {
|
|
5469
|
+
const balances = JSON.parse(readFileSync(this.creditBalancePath, "utf8")).balances;
|
|
5470
|
+
if (typeof balances !== "object" || balances === null || Array.isArray(balances)) return;
|
|
5471
|
+
for (const [id, value] of Object.entries(balances)) {
|
|
5472
|
+
if (id === "" || typeof value !== "number" || !Number.isFinite(value) || value < 0) continue;
|
|
5473
|
+
this.creditBalances.set(id, value);
|
|
5474
|
+
}
|
|
5475
|
+
} catch {}
|
|
5476
|
+
}
|
|
5477
|
+
/** Mirror every known balance, atomically. Never throws. */
|
|
5478
|
+
saveCreditBalances() {
|
|
5479
|
+
const path = this.creditBalancePath;
|
|
5480
|
+
if (path === void 0) return;
|
|
5481
|
+
try {
|
|
5482
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
5483
|
+
writeFileSync(`${path}.tmp`, `${JSON.stringify({
|
|
5484
|
+
version: 1,
|
|
5485
|
+
at: Date.now(),
|
|
5486
|
+
balances: Object.fromEntries(this.creditBalances)
|
|
5487
|
+
}, null, 2)}
|
|
5488
|
+
`, "utf8");
|
|
5489
|
+
renameSync(`${path}.tmp`, path);
|
|
5490
|
+
} catch {}
|
|
4766
5491
|
}
|
|
4767
5492
|
/**
|
|
4768
5493
|
* Record ONLY the deadline, never the balance.
|
|
@@ -5229,7 +5954,7 @@ const MAGICREW_CN = Object.freeze({
|
|
|
5229
5954
|
displayName: "超级麦吉",
|
|
5230
5955
|
host: "https://i-magic-service.letsmagic.cn",
|
|
5231
5956
|
webOrigin: "https://www.letsmagic.cn",
|
|
5232
|
-
needsOrg:
|
|
5957
|
+
needsOrg: true,
|
|
5233
5958
|
defaultRef: "magicrew"
|
|
5234
5959
|
});
|
|
5235
5960
|
const MAGICREW_INTL = Object.freeze({
|
|
@@ -5735,13 +6460,13 @@ var WorkBuddyCatalog = class {
|
|
|
5735
6460
|
const images = this.selection.imageModelIds;
|
|
5736
6461
|
const imageSet = images === void 0 ? void 0 : new Set(images);
|
|
5737
6462
|
const budgets = this.selection.contextBudgets;
|
|
5738
|
-
return this.models.filter((model) => allow === void 0 || allow.has(model.id)).map((model) => {
|
|
6463
|
+
return sortFreeFirst(this.models.filter((model) => allow === void 0 || allow.has(model.id)).map((model) => {
|
|
5739
6464
|
const next = { ...model };
|
|
5740
6465
|
if (imageSet !== void 0) next.supportsImages = imageSet.has(model.id);
|
|
5741
6466
|
const budget = budgets?.[model.id];
|
|
5742
6467
|
if (budget !== void 0 && budget > 0 && budget < next.contextWindow) next.contextWindow = budget;
|
|
5743
6468
|
return next;
|
|
5744
|
-
});
|
|
6469
|
+
}));
|
|
5745
6470
|
}
|
|
5746
6471
|
/** Replace the catalog and notify the adapter to rebuild its model list. */
|
|
5747
6472
|
update(models) {
|
|
@@ -10818,6 +11543,7 @@ const PROVIDERS = Object.freeze([
|
|
|
10818
11543
|
"baseUrl": "",
|
|
10819
11544
|
"format": "openai-chat",
|
|
10820
11545
|
"models": [],
|
|
11546
|
+
"modelsUrl": "/models",
|
|
10821
11547
|
"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
11548
|
"website": null,
|
|
10823
11549
|
"local": false,
|
|
@@ -10834,6 +11560,54 @@ Object.freeze({
|
|
|
10834
11560
|
"openai-responses": "/responses",
|
|
10835
11561
|
"anthropic-messages": "/messages"
|
|
10836
11562
|
});
|
|
11563
|
+
//#endregion
|
|
11564
|
+
//#region src/group-routing.ts
|
|
11565
|
+
/** 恒等序(ordered / 兜底)。 */
|
|
11566
|
+
function identityOrder(seats) {
|
|
11567
|
+
return seats.map((_, i) => i);
|
|
11568
|
+
}
|
|
11569
|
+
/** smart:额度优先 —— 没用尽的按最早续期/过期排,用尽的沉底。 */
|
|
11570
|
+
function smartOrder(seats) {
|
|
11571
|
+
const idx = seats.map((_, i) => i);
|
|
11572
|
+
const tier = (s) => {
|
|
11573
|
+
if (s.resting === true || s.spent === true || (s.used ?? 0) >= 1) return 2;
|
|
11574
|
+
if ((s.used ?? 0) >= .9) return 1;
|
|
11575
|
+
return 0;
|
|
11576
|
+
};
|
|
11577
|
+
return idx.sort((a, b) => {
|
|
11578
|
+
const ta = tier(seats[a]), tb = tier(seats[b]);
|
|
11579
|
+
if (ta !== tb) return ta - tb;
|
|
11580
|
+
const ra = seats[a].renewsInMs ?? Number.MAX_SAFE_INTEGER;
|
|
11581
|
+
const rb = seats[b].renewsInMs ?? Number.MAX_SAFE_INTEGER;
|
|
11582
|
+
if (ra !== rb) return ra - rb;
|
|
11583
|
+
return (seats[a].used ?? 0) - (seats[b].used ?? 0);
|
|
11584
|
+
});
|
|
11585
|
+
}
|
|
11586
|
+
/** cheapest:价格升序,同价按窗口小的先用。 */
|
|
11587
|
+
function cheapestOrder(seats) {
|
|
11588
|
+
return seats.map((_, i) => i).sort((a, b) => {
|
|
11589
|
+
const ca = seats[a].cost ?? Number.MAX_SAFE_INTEGER;
|
|
11590
|
+
const cb = seats[b].cost ?? Number.MAX_SAFE_INTEGER;
|
|
11591
|
+
if (ca !== cb) return ca - cb;
|
|
11592
|
+
return (seats[a].window ?? Number.MAX_SAFE_INTEGER) - (seats[b].window ?? Number.MAX_SAFE_INTEGER);
|
|
11593
|
+
});
|
|
11594
|
+
}
|
|
11595
|
+
/** free-first:免费且可用的优先,其后按 smart。 */
|
|
11596
|
+
function freeFirstOrder(seats) {
|
|
11597
|
+
return seats.map((_, i) => i).sort((a, b) => {
|
|
11598
|
+
const fa = seats[a].free === true && (seats[a].used ?? 0) < 1 ? 0 : 1;
|
|
11599
|
+
const fb = seats[b].free === true && (seats[b].used ?? 0) < 1 ? 0 : 1;
|
|
11600
|
+
if (fa !== fb) return fa - fb;
|
|
11601
|
+
return smartOrder([seats[a], seats[b]])[0] === 0 ? -1 : 1;
|
|
11602
|
+
});
|
|
11603
|
+
}
|
|
11604
|
+
Object.freeze({
|
|
11605
|
+
smart: { order: smartOrder },
|
|
11606
|
+
ordered: { order: identityOrder },
|
|
11607
|
+
"round-robin": { order: identityOrder },
|
|
11608
|
+
cheapest: { order: cheapestOrder },
|
|
11609
|
+
"free-first": { order: freeFirstOrder }
|
|
11610
|
+
});
|
|
10837
11611
|
Object.freeze({
|
|
10838
11612
|
"openai-chat": "chat",
|
|
10839
11613
|
"openai-responses": "responses",
|
|
@@ -11327,6 +12101,58 @@ function expertChatEvents(expert, conversationId, requestId) {
|
|
|
11327
12101
|
expert_industry_id: ""
|
|
11328
12102
|
} : event);
|
|
11329
12103
|
}
|
|
12104
|
+
//#endregion
|
|
12105
|
+
//#region src/scheduler.ts
|
|
12106
|
+
/**
|
|
12107
|
+
* 自动化节流旋钮(issue #231/#232,PR 232)。
|
|
12108
|
+
*
|
|
12109
|
+
* 固定 800ms 的账号间隔 + 整点触发是一组机器指纹:实测 38 个 domestic 账号在
|
|
12110
|
+
* 三次 800ms 恒定节奏的自动化之后,59 分钟内有 27 个 refresh token 被撤销。
|
|
12111
|
+
* 抖动打散节奏;旋钮都设 0 可精确恢复旧行为,所以这不是悄悄改默认值。
|
|
12112
|
+
*
|
|
12113
|
+
* 旋钮走环境变量而非设置文档:这是缓解措施不是功能,改一个数不该做设置迁移。
|
|
12114
|
+
*/
|
|
12115
|
+
function pacingEnv(name, fallback) {
|
|
12116
|
+
const raw = typeof process === "object" && process !== null ? process.env[name] : void 0;
|
|
12117
|
+
if (typeof raw !== "string" || raw.trim() === "") return fallback;
|
|
12118
|
+
const parsed = Number(raw);
|
|
12119
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
|
|
12120
|
+
}
|
|
12121
|
+
/** 两次上游调用之间的基础间隔(默认 6s)。 */
|
|
12122
|
+
const PACING_ACCOUNT_DELAY_MS = pacingEnv("XDPOOL_ACCOUNT_DELAY_MS", 6e3);
|
|
12123
|
+
/** 叠加在基础间隔上的均匀抖动(默认 0..6s)。 */
|
|
12124
|
+
const PACING_ACCOUNT_DELAY_JITTER_MS = pacingEnv("XDPOOL_ACCOUNT_DELAY_JITTER", 6e3);
|
|
12125
|
+
/** 配置小时内的分散分钟数(默认 0..45)。 */
|
|
12126
|
+
const PACING_SCHEDULE_JITTER_MIN = pacingEnv("XDPOOL_SCHEDULE_JITTER_MIN", 45);
|
|
12127
|
+
/** 带抖动的调用间隔;jitter=0 时精确等于 base。 */
|
|
12128
|
+
function pacedDelay(baseMs) {
|
|
12129
|
+
if (!(baseMs > 0)) return 0;
|
|
12130
|
+
if (!(PACING_ACCOUNT_DELAY_JITTER_MS > 0)) return baseMs;
|
|
12131
|
+
return baseMs + Math.floor(Math.random() * PACING_ACCOUNT_DELAY_JITTER_MS);
|
|
12132
|
+
}
|
|
12133
|
+
/**
|
|
12134
|
+
* 一个 slot 在其配置小时内真正触发的分钟偏移。
|
|
12135
|
+
* 由 slot 字符串确定性哈希得到,不是每次随机 —— 重启/重复 tick 不会提前重跑
|
|
12136
|
+
* 同一个 slot(那会重复消费),也不会把它弄丢。
|
|
12137
|
+
*/
|
|
12138
|
+
function slotMinuteOffset(slot) {
|
|
12139
|
+
/**
|
|
12140
|
+
* 运行时再读一次旋钮,而不是只用模块加载时的快照。
|
|
12141
|
+
*
|
|
12142
|
+
* `PACING_SCHEDULE_JITTER_MIN` 是加载时固化的默认值;但测试要在 import 之后
|
|
12143
|
+
* 用 process.env 关闭抖动来驱动「整点触发」的历史回归,运营也可能在进程内
|
|
12144
|
+
* 改旋钮。实时读取让这两种场景都成立,而正常运行时值不变。
|
|
12145
|
+
*/
|
|
12146
|
+
const live = pacingEnv("XDPOOL_SCHEDULE_JITTER_MIN", PACING_SCHEDULE_JITTER_MIN);
|
|
12147
|
+
const span = Math.min(59, Math.floor(live));
|
|
12148
|
+
if (!(span > 0)) return 0;
|
|
12149
|
+
let hash = 2166136261;
|
|
12150
|
+
for (let i = 0; i < slot.length; i += 1) {
|
|
12151
|
+
hash ^= slot.charCodeAt(i);
|
|
12152
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
12153
|
+
}
|
|
12154
|
+
return hash % (span + 1);
|
|
12155
|
+
}
|
|
11330
12156
|
/**
|
|
11331
12157
|
* The fallback record for the 腾讯轻量云 expert, used when the marketplace
|
|
11332
12158
|
* listing cannot be read. The id is the one the task is scored against.
|
|
@@ -11455,6 +12281,7 @@ function zonedParts(date, timeZone = AUTOMATION_TIME_ZONE) {
|
|
|
11455
12281
|
month: "2-digit",
|
|
11456
12282
|
day: "2-digit",
|
|
11457
12283
|
hour: "2-digit",
|
|
12284
|
+
minute: "2-digit",
|
|
11458
12285
|
hourCycle: "h23"
|
|
11459
12286
|
}).formatToParts(date);
|
|
11460
12287
|
const pick = (type) => parts.find((part) => part.type === type)?.value ?? "00";
|
|
@@ -11462,7 +12289,8 @@ function zonedParts(date, timeZone = AUTOMATION_TIME_ZONE) {
|
|
|
11462
12289
|
year: pick("year"),
|
|
11463
12290
|
month: pick("month"),
|
|
11464
12291
|
day: pick("day"),
|
|
11465
|
-
hour: pick("hour")
|
|
12292
|
+
hour: pick("hour"),
|
|
12293
|
+
minute: pick("minute")
|
|
11466
12294
|
};
|
|
11467
12295
|
}
|
|
11468
12296
|
function dayKey(date, timeZone = AUTOMATION_TIME_ZONE) {
|
|
@@ -11594,7 +12422,7 @@ var WorkBuddyScheduler = class {
|
|
|
11594
12422
|
this.client = client;
|
|
11595
12423
|
this.logger = options.logger ?? {};
|
|
11596
12424
|
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
11597
|
-
this.delayMs = options.accountDelayMs ??
|
|
12425
|
+
this.delayMs = options.accountDelayMs ?? PACING_ACCOUNT_DELAY_MS;
|
|
11598
12426
|
this.eventScoreWaitMs = options.eventScoreWaitMs ?? 9e3;
|
|
11599
12427
|
this.expertGapMs = options.expertGapMs ?? 6e3;
|
|
11600
12428
|
this.loadEarnings = options.loadEarnings;
|
|
@@ -11720,27 +12548,64 @@ var WorkBuddyScheduler = class {
|
|
|
11720
12548
|
* report would have moved. This is what the card's single button calls.
|
|
11721
12549
|
*/
|
|
11722
12550
|
/**
|
|
11723
|
-
* Start a
|
|
12551
|
+
* Start a pass in the background and return immediately.
|
|
11724
12552
|
*
|
|
11725
12553
|
* A pass takes tens of seconds - one upstream round trip per account per job,
|
|
11726
12554
|
* plus the scoring wait - which is far too long to hold the card request open:
|
|
11727
12555
|
* the browser or the host web server would time out, and the user would see
|
|
11728
12556
|
* a hung button for a run that is actually working.
|
|
11729
12557
|
*
|
|
12558
|
+
* `job` names ONE job (the card's per-job button) or `'all'` for the ordered
|
|
12559
|
+
* full pass; anything else is treated as `'all'` by the caller's validation,
|
|
12560
|
+
* not here. `force` bypasses the already-ran-today guard for a single job,
|
|
12561
|
+
* which is what "run it now anyway" means.
|
|
12562
|
+
*
|
|
11730
12563
|
* Returns whether a run started. A second call while one is in flight is
|
|
11731
12564
|
* ignored rather than queued: pressing the button twice means hurry up, and
|
|
11732
12565
|
* the run already under way covers it.
|
|
11733
12566
|
*/
|
|
11734
12567
|
startRunAll() {
|
|
12568
|
+
return this.startRun("all");
|
|
12569
|
+
}
|
|
12570
|
+
/**
|
|
12571
|
+
* Start one job — or the whole pass — in the background.
|
|
12572
|
+
*
|
|
12573
|
+
* The card's automation row names a job, and `force` is what a second press
|
|
12574
|
+
* within the same hour means. Both used to be dropped on the floor by the
|
|
12575
|
+
* route wiring, so "run check-in" ran every job and a repeat press inside the
|
|
12576
|
+
* hour silently did nothing. A single-job start goes through the same
|
|
12577
|
+
* in-flight guard as a full pass: overlapping passes would double-spend the
|
|
12578
|
+
* per-account delays and interleave two runs into one status document.
|
|
12579
|
+
*/
|
|
12580
|
+
startRun(kind, force = false) {
|
|
11735
12581
|
if (this.runInFlight) return false;
|
|
12582
|
+
if (!force && kind !== "all" && this.states[kind].lastFiredHour === slotKey(this.now())) return false;
|
|
11736
12583
|
this.runInFlight = true;
|
|
11737
|
-
this.runAll().catch((error) => {
|
|
12584
|
+
(kind === "all" ? this.runAll() : this.runNow(kind, force).then(() => void 0)).catch((error) => {
|
|
11738
12585
|
this.logger.warn?.("dsh-xdpool automation run failed:", error);
|
|
11739
12586
|
}).finally(() => {
|
|
11740
12587
|
this.runInFlight = false;
|
|
11741
12588
|
});
|
|
11742
12589
|
return true;
|
|
11743
12590
|
}
|
|
12591
|
+
/**
|
|
12592
|
+
* issue #222:启动一个指定 job 的后台运行,供「立即执行」按任务调用。
|
|
12593
|
+
*
|
|
12594
|
+
* 和 `startRunAll` 一样立刻返回(跑一轮要几十秒,不能挂在卡片请求上),
|
|
12595
|
+
* 也复用同一把 `runInFlight` 锁:同时检查 `busy`,避免手动单任务和定时 tick
|
|
12596
|
+
* 并发跑同一批账号(共享 ledger 的 read-modify-write 不是原子的)。
|
|
12597
|
+
* `force` 交给 `runNow`,让它跳过同小时的节流。
|
|
12598
|
+
*/
|
|
12599
|
+
startRunNow(kind, force = false) {
|
|
12600
|
+
if (this.runInFlight || this.busy) return false;
|
|
12601
|
+
this.runInFlight = true;
|
|
12602
|
+
this.runNow(kind, force).catch((error) => {
|
|
12603
|
+
this.logger.warn?.(`dsh-xdpool automation run ${kind} failed:`, error);
|
|
12604
|
+
}).finally(() => {
|
|
12605
|
+
this.runInFlight = false;
|
|
12606
|
+
});
|
|
12607
|
+
return true;
|
|
12608
|
+
}
|
|
11744
12609
|
async runAll() {
|
|
11745
12610
|
const today = dayKey(this.now());
|
|
11746
12611
|
const before = this.earningsSnapshot();
|
|
@@ -11821,13 +12686,17 @@ var WorkBuddyScheduler = class {
|
|
|
11821
12686
|
dueSlot(kind, now) {
|
|
11822
12687
|
const hours = this.hoursOf(kind);
|
|
11823
12688
|
if (hours.length === 0) return void 0;
|
|
11824
|
-
const
|
|
12689
|
+
const parts = zonedParts(now);
|
|
12690
|
+
const current = Number(parts.hour);
|
|
12691
|
+
const currentMinute = Number(parts.minute);
|
|
11825
12692
|
const today = dayKey(now);
|
|
11826
12693
|
const fired = this.firedSlotsOf(kind);
|
|
11827
12694
|
for (const candidate of [...hours].sort((a, b) => a - b)) {
|
|
11828
12695
|
if (candidate > current) break;
|
|
11829
12696
|
const slot = `${today}T${String(candidate).padStart(2, "0")}`;
|
|
11830
|
-
if (
|
|
12697
|
+
if (fired.has(slot)) continue;
|
|
12698
|
+
if (candidate === current && currentMinute < slotMinuteOffset(slot)) break;
|
|
12699
|
+
return slot;
|
|
11831
12700
|
}
|
|
11832
12701
|
}
|
|
11833
12702
|
/** Today's consumed slots for one job, as a set. */
|
|
@@ -11999,18 +12868,52 @@ var WorkBuddyScheduler = class {
|
|
|
11999
12868
|
try {
|
|
12000
12869
|
switch (kind) {
|
|
12001
12870
|
case "checkin": {
|
|
12871
|
+
/**
|
|
12872
|
+
* 定时签到也必须像手动领取一样先用新鲜凭据(issue: 自动签到全挂)。
|
|
12873
|
+
* 手动路由 web-status.ts 已用 freshCredential,但这条定时路径以前
|
|
12874
|
+
* 直接拿池里的旧 token —— 过期后上游 401,整轮静默失败。
|
|
12875
|
+
*/
|
|
12876
|
+
const fresh = await this.pool.freshCredential(account.id);
|
|
12877
|
+
if (fresh === void 0) {
|
|
12878
|
+
detail.push("签到跳过:登录已失效且刷新失败,请重新登录");
|
|
12879
|
+
this.logger.warn?.(`automation checkin ${account.label}: credential could not be refreshed; skipped`);
|
|
12880
|
+
break;
|
|
12881
|
+
}
|
|
12002
12882
|
let alreadyDone = false;
|
|
12883
|
+
let activityClosed = false;
|
|
12884
|
+
let alreadyPaid = 0;
|
|
12003
12885
|
try {
|
|
12004
|
-
|
|
12886
|
+
const status = await this.client.fetchCheckinStatus(fresh);
|
|
12887
|
+
alreadyDone = status.todayCheckedIn === true;
|
|
12888
|
+
activityClosed = status.active === false;
|
|
12889
|
+
/**
|
|
12890
|
+
* issue #221:桌面端通常先签到了,插件 9 点跑到时状态已是已领。
|
|
12891
|
+
* 以前这里直接 break、不记账,ledger 的 checkinCredit 恒 0,
|
|
12892
|
+
* 卡片就显示「今日已领 0/1」——明明已领却像没领到。
|
|
12893
|
+
* `todayCredit` 是上游当天的真实发放额,用它补账;0 不会写入
|
|
12894
|
+
* (recordEarnings 的 empty 短路),与「重复签到不重复加钱」一致。
|
|
12895
|
+
*/
|
|
12896
|
+
alreadyPaid = Math.max(0, status.todayCredit ?? 0);
|
|
12005
12897
|
} catch (error) {
|
|
12006
12898
|
this.logger.warn?.(`automation checkin ${account.label}: status read failed, claiming anyway:`, error);
|
|
12007
12899
|
}
|
|
12008
12900
|
if (alreadyDone) {
|
|
12009
|
-
this.
|
|
12901
|
+
this.recordEarnings(account.id, today, { checkinCredit: alreadyPaid });
|
|
12902
|
+
detail.push(alreadyPaid > 0 ? `签到已领 +${alreadyPaid}` : "签到已在他处完成");
|
|
12903
|
+
this.logger.info?.(`automation checkin ${account.label}: already done today (read, not claimed, paid ${alreadyPaid})`);
|
|
12904
|
+
break;
|
|
12905
|
+
}
|
|
12906
|
+
if (activityClosed) {
|
|
12907
|
+
this.logger.info?.(`automation checkin ${account.label}: no check-in activity on this gateway, skipped`);
|
|
12908
|
+
items.push({
|
|
12909
|
+
title: "每日签到",
|
|
12910
|
+
status: "skipped",
|
|
12911
|
+
note: "this gateway runs no check-in activity"
|
|
12912
|
+
});
|
|
12010
12913
|
break;
|
|
12011
12914
|
}
|
|
12012
12915
|
try {
|
|
12013
|
-
const claim = await this.client.claimDailyCheckin(
|
|
12916
|
+
const claim = await this.client.claimDailyCheckin(fresh);
|
|
12014
12917
|
this.recordEarnings(account.id, today, { checkinCredit: claim.credit });
|
|
12015
12918
|
if (claim.credit > 0) {
|
|
12016
12919
|
detail.push(`签到 +${claim.credit}`);
|
|
@@ -12018,7 +12921,15 @@ var WorkBuddyScheduler = class {
|
|
|
12018
12921
|
}
|
|
12019
12922
|
} catch (error) {
|
|
12020
12923
|
if (!isAlreadyCheckin(error)) throw error;
|
|
12021
|
-
|
|
12924
|
+
/**
|
|
12925
|
+
* 同样补账(#221):状态读取失败但 claim 回「已签到」时,
|
|
12926
|
+
* 回读一次当天实发额;读不到就记 0(等于不写),不再让账本空着。
|
|
12927
|
+
*/
|
|
12928
|
+
const after = await this.client.fetchCheckinStatus(fresh).catch(() => void 0);
|
|
12929
|
+
const paid = Math.max(0, after?.todayCredit ?? 0);
|
|
12930
|
+
this.recordEarnings(account.id, today, { checkinCredit: paid });
|
|
12931
|
+
if (paid > 0) detail.push(`签到已领 +${paid}`);
|
|
12932
|
+
this.logger.info?.(`automation checkin ${account.label}: already done today (paid ${paid})`);
|
|
12022
12933
|
}
|
|
12023
12934
|
break;
|
|
12024
12935
|
}
|
|
@@ -12067,7 +12978,7 @@ var WorkBuddyScheduler = class {
|
|
|
12067
12978
|
failed++;
|
|
12068
12979
|
this.logger.warn?.(`automation ${accountWord} ${account.label} failed:`, error);
|
|
12069
12980
|
}
|
|
12070
|
-
if (index < accounts.length - 1 && this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
|
|
12981
|
+
if (index < accounts.length - 1 && this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
|
|
12071
12982
|
}
|
|
12072
12983
|
const state = this.states[kind];
|
|
12073
12984
|
if (consumedSlot !== void 0) this.consumeSlot(kind, consumedSlot);
|
|
@@ -12160,7 +13071,7 @@ var WorkBuddyScheduler = class {
|
|
|
12160
13071
|
this.logger.warn?.(`automation events ${account.label}: ${task.taskCode} failed:`, error);
|
|
12161
13072
|
break;
|
|
12162
13073
|
}
|
|
12163
|
-
if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
|
|
13074
|
+
if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
|
|
12164
13075
|
}
|
|
12165
13076
|
}
|
|
12166
13077
|
}
|
|
@@ -12285,7 +13196,7 @@ var WorkBuddyScheduler = class {
|
|
|
12285
13196
|
}
|
|
12286
13197
|
const expert = expertFromTask(expertId, task.title);
|
|
12287
13198
|
await this.client.reportDesktopEvents(credential, expertSummonEvents(expert));
|
|
12288
|
-
if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
|
|
13199
|
+
if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
|
|
12289
13200
|
const chat = await this.client.openConversation(credential, expert.expertId);
|
|
12290
13201
|
if (chat === void 0) throw new Error(`${task.taskCode}: no server conversation`);
|
|
12291
13202
|
return [{
|
|
@@ -12311,7 +13222,7 @@ var WorkBuddyScheduler = class {
|
|
|
12311
13222
|
if (this.stopped) break;
|
|
12312
13223
|
try {
|
|
12313
13224
|
await this.client.reportDesktopEvents(credential, expertSummonEvents(expert));
|
|
12314
|
-
if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
|
|
13225
|
+
if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
|
|
12315
13226
|
const chat = await this.client.openConversation(credential, expert.expertId);
|
|
12316
13227
|
if (chat === void 0) continue;
|
|
12317
13228
|
out.push({
|
|
@@ -12342,7 +13253,7 @@ var WorkBuddyScheduler = class {
|
|
|
12342
13253
|
this.logger.warn?.("automation events lighthouse list:", error);
|
|
12343
13254
|
}
|
|
12344
13255
|
await this.client.reportDesktopEvents(credential, expertSummonEvents(expert));
|
|
12345
|
-
if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
|
|
13256
|
+
if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
|
|
12346
13257
|
const chat = await this.client.openConversation(credential, expert.expertId);
|
|
12347
13258
|
if (chat === void 0) throw new Error("Expert_lighthouse: no server conversation");
|
|
12348
13259
|
const use = expertActualUseEvent(expert, chat.conversationId, chat.requestId, "LOCAL");
|
|
@@ -12400,7 +13311,7 @@ var WorkBuddyScheduler = class {
|
|
|
12400
13311
|
});
|
|
12401
13312
|
this.logger.info?.(`automation claim ${account.label}: ${task.taskCode} already claimed`);
|
|
12402
13313
|
}
|
|
12403
|
-
if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
|
|
13314
|
+
if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
|
|
12404
13315
|
}
|
|
12405
13316
|
return {
|
|
12406
13317
|
claimed,
|
|
@@ -12434,7 +13345,7 @@ var WorkBuddyScheduler = class {
|
|
|
12434
13345
|
} catch (error) {
|
|
12435
13346
|
this.logger.warn?.(`automation streak ${account.label}: redeem ${tier.tier} failed:`, error);
|
|
12436
13347
|
}
|
|
12437
|
-
if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
|
|
13348
|
+
if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
|
|
12438
13349
|
}
|
|
12439
13350
|
const chances = await this.client.lotteryChances(credential);
|
|
12440
13351
|
for (let draw = 0; draw < chances; draw += 1) {
|
|
@@ -12446,7 +13357,7 @@ var WorkBuddyScheduler = class {
|
|
|
12446
13357
|
this.logger.warn?.(`automation lottery ${account.label}: draw failed:`, error);
|
|
12447
13358
|
break;
|
|
12448
13359
|
}
|
|
12449
|
-
if (this.delayMs > 0 && !this.stopped) await sleep(this.delayMs);
|
|
13360
|
+
if (this.delayMs > 0 && !this.stopped) await sleep(pacedDelay(this.delayMs));
|
|
12450
13361
|
}
|
|
12451
13362
|
const pendingTier = status.tiers.find((tier) => tier.status === "locked");
|
|
12452
13363
|
if (pendingTier !== void 0) {
|
|
@@ -12608,6 +13519,7 @@ Object.freeze({
|
|
|
12608
13519
|
"Write the briefing only — no preamble, no markdown fence."
|
|
12609
13520
|
].join("\n");
|
|
12610
13521
|
join("channel-pack", "token-ledger.json");
|
|
13522
|
+
join("channel-pack", "token-ledger.json");
|
|
12611
13523
|
//#endregion
|
|
12612
13524
|
//#region src/status.ts
|
|
12613
13525
|
/** Format the per-model credit multipliers. */
|
|
@@ -12619,6 +13531,7 @@ function formatRates(status) {
|
|
|
12619
13531
|
}
|
|
12620
13532
|
return lines.join("\n");
|
|
12621
13533
|
}
|
|
13534
|
+
join(".xdpool", "spend-cache.json");
|
|
12622
13535
|
Object.freeze({
|
|
12623
13536
|
"workbuddy-xdpool": "xdpool",
|
|
12624
13537
|
"workbuddy-xdpool-global": "xdpool-global",
|
|
@@ -12811,7 +13724,7 @@ z.object({
|
|
|
12811
13724
|
disabledAccountIds: asVolatile(z.array(z.string()).default([]).description("Account ids excluded from the pool (empty = every discovered account participates)")),
|
|
12812
13725
|
creditReserves: asVolatile(z.dict(z.number().step(1).min(0)).default({}).description("Per-account credit floor: stop using an account once its balance reaches this value")),
|
|
12813
13726
|
enabledModelIds: asVolatile(z.array(z.string()).default([]).description("Legacy shared model-id list; used by a region that has no per-region selection yet")),
|
|
12814
|
-
imageModelIds: asVolatile(z.array(z.string()).
|
|
13727
|
+
imageModelIds: asVolatile(z.array(z.string()).description("Legacy shared image-id list; used by a region that has no per-region selection yet")),
|
|
12815
13728
|
contextBudgets: asVolatile(z.dict(z.number().step(1).min(1)).default({}).description("Legacy shared context budgets; used by a region with no per-region selection yet")),
|
|
12816
13729
|
modelSelectionCn: asVolatile(modelSelectionSchema.description("Model selection for the domestic gateway")),
|
|
12817
13730
|
modelSelectionGlobal: asVolatile(modelSelectionSchema.description("Model selection for the international gateway")),
|
|
@@ -12855,7 +13768,8 @@ function createCore(logger) {
|
|
|
12855
13768
|
...logger === void 0 ? {} : { logger },
|
|
12856
13769
|
client,
|
|
12857
13770
|
persistent: true,
|
|
12858
|
-
affinityPath: join(pluginDataDir(), "sticky-affinity.json")
|
|
13771
|
+
affinityPath: join(pluginDataDir(), "sticky-affinity.json"),
|
|
13772
|
+
creditBalancePath: join(pluginDataDir(), "credit-balances.json")
|
|
12859
13773
|
});
|
|
12860
13774
|
return {
|
|
12861
13775
|
pool,
|
|
@@ -12919,6 +13833,7 @@ function usage() {
|
|
|
12919
13833
|
" status Account pool, credits, and shim state (add --credits, --json, --rates)",
|
|
12920
13834
|
" doctor Diagnose discovery, cooldowns, and upstream reachability",
|
|
12921
13835
|
" accounts List discovered accounts (add --json)",
|
|
13836
|
+
" unlock Remove a leftover account-store lock after reporting its owner",
|
|
12922
13837
|
" import <key> Snapshot the current desktop login as <key> (add --force)",
|
|
12923
13838
|
" remove <key> Delete one imported snapshot",
|
|
12924
13839
|
" ignore <acct> Drop an account from the pool for good (id or label)",
|
|
@@ -13145,6 +14060,54 @@ async function commandDoctor() {
|
|
|
13145
14060
|
console.log(lines.join("\n"));
|
|
13146
14061
|
return healthy ? 0 : 1;
|
|
13147
14062
|
}
|
|
14063
|
+
/**
|
|
14064
|
+
* Remove a leftover account-store lock.
|
|
14065
|
+
*
|
|
14066
|
+
* The transaction writes its owner (pid, host) into the lock file and reclaims
|
|
14067
|
+
* a provably dead owner on its own. This command covers what that rule cannot:
|
|
14068
|
+
* a lock whose owner record never made it to disk (an older build, or a crash
|
|
14069
|
+
* between create and record), or a lock whose owner belongs to another host.
|
|
14070
|
+
*
|
|
14071
|
+
* It never removes a lock owned by the running process, and it prints what it
|
|
14072
|
+
* found first, so a user pasting the output gives enough to reconstruct what
|
|
14073
|
+
* happened.
|
|
14074
|
+
*/
|
|
14075
|
+
async function commandUnlock(args) {
|
|
14076
|
+
const asJson = args.includes("--json");
|
|
14077
|
+
const lockPath = join(accountDir(), `${ACCOUNTS_FILE_NAME}.lock`);
|
|
14078
|
+
let raw;
|
|
14079
|
+
try {
|
|
14080
|
+
raw = await readFile(lockPath, "utf8");
|
|
14081
|
+
} catch (error) {
|
|
14082
|
+
if (error.code === "ENOENT") {
|
|
14083
|
+
console.log(asJson ? JSON.stringify({
|
|
14084
|
+
lock: lockPath,
|
|
14085
|
+
present: false
|
|
14086
|
+
}) : `No account-store lock at ${lockPath}.`);
|
|
14087
|
+
return 0;
|
|
14088
|
+
}
|
|
14089
|
+
throw error;
|
|
14090
|
+
}
|
|
14091
|
+
let owner;
|
|
14092
|
+
try {
|
|
14093
|
+
owner = JSON.parse(raw);
|
|
14094
|
+
} catch {
|
|
14095
|
+
owner = void 0;
|
|
14096
|
+
}
|
|
14097
|
+
if (owner?.pid === process.pid) {
|
|
14098
|
+
console.error(`Refusing to remove ${lockPath}: it is owned by this process (pid ${process.pid}).`);
|
|
14099
|
+
return 1;
|
|
14100
|
+
}
|
|
14101
|
+
await unlink(lockPath);
|
|
14102
|
+
const described = owner?.pid === void 0 ? "no owner record" : `pid ${owner.pid} on ${owner.host} since ${owner.startedAt}`;
|
|
14103
|
+
console.log(asJson ? JSON.stringify({
|
|
14104
|
+
lock: lockPath,
|
|
14105
|
+
removed: true,
|
|
14106
|
+
owner,
|
|
14107
|
+
described
|
|
14108
|
+
}) : `Removed account-store lock ${lockPath} (${described}).`);
|
|
14109
|
+
return 0;
|
|
14110
|
+
}
|
|
13148
14111
|
async function commandImport(args) {
|
|
13149
14112
|
const key = args.filter((arg) => !arg.startsWith("--"))[0];
|
|
13150
14113
|
if (key === void 0) {
|
|
@@ -13375,6 +14338,7 @@ async function main(argv) {
|
|
|
13375
14338
|
case "status": return commandStatus(rest);
|
|
13376
14339
|
case "doctor": return commandDoctor();
|
|
13377
14340
|
case "accounts": return commandAccounts(rest);
|
|
14341
|
+
case "unlock": return commandUnlock(rest);
|
|
13378
14342
|
case "import": return commandImport(rest);
|
|
13379
14343
|
case "remove": return commandRemove(rest);
|
|
13380
14344
|
case "ignore": return commandIgnore(rest, true);
|