dsh-wtq-pool 1.0.4 → 1.0.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import * as path from "node:path";
2
- import { basename, dirname, join, resolve } from "node:path";
2
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
3
3
  import * as os from "node:os";
4
4
  import { cpus, homedir, hostname, release } from "node:os";
5
5
  import * as fs from "node:fs/promises";
6
- import { readFile, readdir, stat } from "node:fs/promises";
6
+ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
7
7
  import { fileURLToPath } from "node:url";
8
- import { AsyncLocalStorage } from "node:async_hooks";
9
8
  import * as piAi from "@earendil-works/pi-ai";
10
9
  import { createProvider } from "@earendil-works/pi-ai";
11
10
  import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
@@ -18,16 +17,17 @@ import { isIP } from "node:net";
18
17
  import { constants, createCipheriv, createDecipheriv, createHash, publicEncrypt, randomBytes, randomUUID } from "node:crypto";
19
18
  import * as fs$1 from "node:fs";
20
19
  import { statSync } from "node:fs";
20
+ import { AsyncLocalStorage } from "node:async_hooks";
21
21
  import { execFile, execFileSync, spawn } from "node:child_process";
22
- import { Readable } from "node:stream";
23
22
  //#region src/log.ts
24
23
  /**
25
24
  * The prefix the shared modules' log lines and warnings carry.
26
25
  *
27
26
  * One constant rather than a literal per call site, because those modules are
28
27
  * synced byte for byte between the two builds and a literal is what a sync
29
- * overwrites. The two host entries are not synced, so they spell their own
30
- * prefix out; the value is the same either way.
28
+ * overwrites. The value differs per build on purpose: a log line should name the
29
+ * plugin that wrote it. This file is therefore the one shared module the two
30
+ * builds do not copy.
31
31
  */
32
32
  const LOG_PREFIX = "dsh-wtq-pool";
33
33
  //#endregion
@@ -167,6 +167,38 @@ function redactSecrets(text) {
167
167
  return out;
168
168
  }
169
169
  /**
170
+ * The vendor's channel check, answered as what it is.
171
+ *
172
+ * WorkBuddy's upstream refuses a request whose prompt names DeepSeek Harness as
173
+ * the client, with code 11128 and "Illegal API invocation from an unapproved
174
+ * channel". The refusal is about the caller's identity rather than the account:
175
+ * every account of that region answers it the same way, so rotating cannot clear
176
+ * it, and the body is a wall of mixed Chinese and English tips that names no
177
+ * cause a user can act on. The sentence below says what happened and what does
178
+ * work. Verified 2026-10-21 on the domestic host: the same prompt is served by
179
+ * the international WorkBuddy accounts, by Trae and by Qoder.
180
+ */
181
+ function unapprovedChannelRefusal(text) {
182
+ if (!/"code"\s*:\s*11128\b/.test(text)) return void 0;
183
+ return "the domestic WorkBuddy host refuses requests that name DeepSeek Harness as the client (channel check 11128), on every account of that region. Use a model served by the international WorkBuddy accounts, Trae or Qoder here.";
184
+ }
185
+ /**
186
+ * The `finish_reason` one turn is reported with.
187
+ *
188
+ * A turn that emitted tool calls says `tool_calls`, because that is what an
189
+ * OpenAI client looks for before it acts on them. It must not say that *over*
190
+ * what the upstream reported: `length` and `content_filter` describe how the
191
+ * turn ended, and a tool call cut off by the output budget is exactly the case
192
+ * where acting on its arguments spends a request on half a JSON body. So only
193
+ * the verdict that carries nothing of its own - `stop`, or nothing at all - is
194
+ * replaced.
195
+ */
196
+ function openAIFinishReason(upstream, sawToolCalls) {
197
+ const stated = upstream === void 0 || upstream === "" || upstream === "null" ? void 0 : upstream;
198
+ if (stated !== void 0 && stated !== "stop") return stated;
199
+ return sawToolCalls ? "tool_calls" : "stop";
200
+ }
201
+ /**
170
202
  * Models a discovery answer may name.
171
203
  *
172
204
  * The host rebuilds the picker from `GET /v1/models`, so these ids are the
@@ -611,26 +643,6 @@ const pi = {
611
643
  absent();
612
644
  }
613
645
  },
614
- commands: {
615
- register: async (spec) => {
616
- if (bridge.registerCommand === void 0) absent();
617
- await bridge.registerCommand(spec);
618
- },
619
- unregister: async (id) => {
620
- if (bridge.unregisterCommand === void 0) absent();
621
- await bridge.unregisterCommand(id);
622
- }
623
- },
624
- ui: {
625
- showToast: async (text, kind) => {
626
- if (bridge.notify === void 0) absent();
627
- await bridge.notify(text, kind === "warn" ? "warn" : "info");
628
- },
629
- openPanel: async () => {
630
- if (bridge.openPanel === void 0) absent();
631
- await bridge.openPanel();
632
- }
633
- },
634
646
  services: {
635
647
  /**
636
648
  * The background services the core registers, whose `start` brings every
@@ -746,11 +758,17 @@ const CHANNELS = /* @__PURE__ */ new Set([
746
758
  "xd.distribution",
747
759
  "xd.setAutoCheckin",
748
760
  "xd.setComposerPoints",
761
+ "xd.setRewriteClientName",
749
762
  "xd.setCreditReserve",
750
763
  "xd.setRegionEnabled",
751
764
  "xd.setSource",
752
765
  "xd.sourceCheckin",
753
- "xd.sourceDistribution"
766
+ "xd.sourceDistribution",
767
+ "xd.startLogin",
768
+ "xd.pollLogin",
769
+ "xd.growthState",
770
+ "xd.growthRun",
771
+ "xd.keepAlive"
754
772
  ]);
755
773
  /** Largest panel request body accepted, so a hung or oversized body cannot pin memory. */
756
774
  const MAX_BODY_BYTES = 65536;
@@ -976,7 +994,7 @@ window.pluginBridge = {
976
994
  on: function () { return function () {}; }
977
995
  };
978
996
  <\/script>`;
979
- return fs$1.readFileSync(file, "utf8").replace(/\s*<meta name="pi-plugin-chrome"[^>]*>/i, "").replace(/\s*<meta\b[^>]*\bhttp-equiv\s*=\s*["']?content-security-policy["']?[^>]*>/i, "").replace("</head>", `${bridge}\n</head>`);
997
+ return fs$1.readFileSync(file, "utf8").replace(/\s*<meta\b[^>]*\bhttp-equiv\s*=\s*["']?content-security-policy["']?[^>]*>/i, "").replace("</head>", `${bridge}\n</head>`);
980
998
  }
981
999
  function registerPanelRoutes(ctx, deps) {
982
1000
  try {
@@ -1061,6 +1079,93 @@ function registerPanelRoutes(ctx, deps) {
1061
1079
  */
1062
1080
  const ROW_ID = "llm-dsh-xdpool";
1063
1081
  //#endregion
1082
+ //#region src/checkin-time.ts
1083
+ /**
1084
+ * When the daily check-in is due, decided in one time zone.
1085
+ *
1086
+ * The reward windows are defined in Beijing time, so an hour has to mean the
1087
+ * same instant on every machine: reading the host's local hour would make "9
1088
+ * o'clock" slip by a day on a laptop set to another zone. Everything here is a
1089
+ * pure function of its arguments, which is what lets a check drive the whole
1090
+ * decision - the configured hours, the slot id, what is due right now - without
1091
+ * a clock to fake or a settings file to write.
1092
+ *
1093
+ * The cap on the configured hours is defensive rather than load-bearing - the
1094
+ * filter below already leaves at most 24 distinct values in 0..23 - but a host
1095
+ * entry that skipped it would disagree with this one about which hours are in
1096
+ * force, so the rule lives in one place.
1097
+ *
1098
+ * @module dsh-wtq-pool/checkin-time
1099
+ */
1100
+ /** The zone the daily check-in hours are read in. */
1101
+ const CHECKIN_TIME_ZONE = "Asia/Shanghai";
1102
+ /** Collected at 09:00 local campaign time unless the user says otherwise. */
1103
+ const DEFAULT_CHECKIN_HOURS = [9];
1104
+ /** How often the timer looks for a due slot. A minute is far below one hour. */
1105
+ const CHECKIN_POLL_MS = 6e4;
1106
+ /** Calendar day and hour of `date` in the check-in zone, as zero-padded strings. */
1107
+ function zonedDayHour(date) {
1108
+ const parts = new Intl.DateTimeFormat("en-CA", {
1109
+ timeZone: CHECKIN_TIME_ZONE,
1110
+ year: "numeric",
1111
+ month: "2-digit",
1112
+ day: "2-digit",
1113
+ hour: "2-digit",
1114
+ hourCycle: "h23"
1115
+ }).formatToParts(date);
1116
+ const pick = (type) => {
1117
+ const found = parts.find((part) => part.type === type);
1118
+ return found === void 0 ? "00" : found.value;
1119
+ };
1120
+ return {
1121
+ day: pick("year") + "-" + pick("month") + "-" + pick("day"),
1122
+ hour: Number(pick("hour"))
1123
+ };
1124
+ }
1125
+ /**
1126
+ * Calendar day `offset` days from today in the check-in zone, as `YYYY-MM-DD`.
1127
+ *
1128
+ * Same zone as {@link zonedDayHour}, so a make-up target and a scheduled pass
1129
+ * can never disagree about which day they mean. The offset is applied to the
1130
+ * zone's own midnight rather than to the caller's clock: adding 24-hour steps
1131
+ * across a DST boundary in some other zone lands on the wrong date.
1132
+ */
1133
+ function zonedDay(offset = 0) {
1134
+ const today = zonedDayHour(/* @__PURE__ */ new Date()).day;
1135
+ if (offset === 0) return today;
1136
+ const [year, month, day] = today.split("-");
1137
+ return new Date(Date.UTC(Number(year), Number(month) - 1, Number(day) + offset)).toISOString().slice(0, 10);
1138
+ }
1139
+ /**
1140
+ * Whole hours only, in order. Anything unreadable is dropped rather than
1141
+ * guessed at, and an empty list falls back to the default hour: a switch that
1142
+ * is on but never fires would be worse than one that picks a sane time.
1143
+ */
1144
+ function normaliseCheckinHours(raw) {
1145
+ const hours = [...new Set(raw.filter((value) => typeof value === "number" || typeof value === "string" && value.trim() !== "").map((value) => Math.floor(Number(value))))].filter((hour) => Number.isInteger(hour) && hour >= 0 && hour <= 23).sort((a, b) => a - b);
1146
+ return hours.length === 0 ? [...DEFAULT_CHECKIN_HOURS] : hours;
1147
+ }
1148
+ /** A slot's id: `YYYY-MM-DDTHH` in the check-in zone. */
1149
+ function checkinSlotId(day, hour) {
1150
+ return day + "T" + String(hour).padStart(2, "0");
1151
+ }
1152
+ /**
1153
+ * The slot to collect right now, or undefined when nothing is due.
1154
+ *
1155
+ * An hour is due once its time has passed - catch-up, deliberately: a machine
1156
+ * that slept through 09:00 still collects when it wakes instead of waiting for
1157
+ * tomorrow. The earliest unconsumed hour wins, so two configured hours still
1158
+ * give two passes a day.
1159
+ */
1160
+ function dueCheckinSlot(now, hours, fired) {
1161
+ const { day, hour } = zonedDayHour(now);
1162
+ for (const candidate of [...hours].sort((a, b) => a - b)) {
1163
+ if (candidate > hour) continue;
1164
+ const slot = checkinSlotId(day, candidate);
1165
+ if (!fired.has(slot)) return slot;
1166
+ }
1167
+ }
1168
+ //#endregion
1064
1169
  //#region src/upstream.ts
1065
1170
  /**
1066
1171
  * WorkBuddy (CodeBuddy / copilot.tencent.com) upstream client.
@@ -1088,7 +1193,7 @@ const CN_CHAT_BASE = "https://copilot.tencent.com";
1088
1193
  /** Billing/console base — `www.codebuddy.cn` is the billing origin. */
1089
1194
  const CN_BILLING_BASE = "https://www.codebuddy.cn";
1090
1195
  /** Global base for `workbuddy.ai` logins. */
1091
- const GLOBAL_BASE = "https://www.workbuddy.ai";
1196
+ const GLOBAL_BASE$1 = "https://www.workbuddy.ai";
1092
1197
  /** Chat UA: the official desktop client's three-segment spelling. */
1093
1198
  const CLIENT_UA = "WorkBuddy/5.5.4 WorkBuddy/5.5.4 CLI/2.137.1";
1094
1199
  /**
@@ -1117,6 +1222,35 @@ const STREAM_HEADERS_TIMEOUT_MS = 6e4;
1117
1222
  /** Longest a relayed chat stream may go without a single byte. */
1118
1223
  const STREAM_IDLE_TIMEOUT_MS$1 = 3e5;
1119
1224
  /**
1225
+ * Lifetime assumed for a token whose answer carries no `expiresIn`.
1226
+ *
1227
+ * It must exceed the refresh margin, or a refreshed credential would read as
1228
+ * already-expiring and every request would refresh again. An hour is
1229
+ * comfortably past that margin and far short of any cap, so a token with a
1230
+ * real lifetime always replaces it in time.
1231
+ */
1232
+ const ASSUMED_TOKEN_LIFETIME_MS = 36e5;
1233
+ /** Longest expiry `Date` can represent; anything past it is not a date. */
1234
+ const MAX_EXPIRY_MS$1 = 41024448e5;
1235
+ /**
1236
+ * Absolute expiry for a token the vendor issued, from its `expiresIn`.
1237
+ *
1238
+ * The figure comes from the vendor's own answer, so it is bounded here rather
1239
+ * than trusted: a garbled one (1e300, Infinity) would otherwise store a
1240
+ * timestamp past `Date`'s range, and the panel's `toISOString()` for that row
1241
+ * then threw, failing the whole document rather than the one field. A value
1242
+ * this function refuses falls back to the assumed lifetime, not to 0: 0 means
1243
+ * "never expires", which would leave a token that really was not fresh being
1244
+ * served as if it were.
1245
+ */
1246
+ function tokenExpiryMs(expiresInSec) {
1247
+ const assumed = () => Date.now() + ASSUMED_TOKEN_LIFETIME_MS;
1248
+ if (typeof expiresInSec !== "number" || !Number.isFinite(expiresInSec) || expiresInSec <= 0) return assumed();
1249
+ const at = Date.now() + expiresInSec * 1e3;
1250
+ if (!Number.isFinite(at) || at > MAX_EXPIRY_MS$1) return assumed();
1251
+ return at;
1252
+ }
1253
+ /**
1120
1254
  * A response's `Retry-After`, in whole seconds, bounded.
1121
1255
  *
1122
1256
  * The header is the upstream's own answer to "how long", and it is the only
@@ -1301,7 +1435,7 @@ function regionOf(domain) {
1301
1435
  function globalBase(credential) {
1302
1436
  const lowered = credential.domain.trim().toLowerCase();
1303
1437
  if (lowered === "codebuddy.ai" || lowered.endsWith(".codebuddy.ai")) return "https://www.codebuddy.ai";
1304
- return GLOBAL_BASE;
1438
+ return GLOBAL_BASE$1;
1305
1439
  }
1306
1440
  function chatBase(credential) {
1307
1441
  return regionOf(credential.domain) === "global" ? globalBase(credential) : CN_CHAT_BASE;
@@ -1428,7 +1562,7 @@ function isGatewayHtmlRejection(status, text) {
1428
1562
  * otherwise reach the client as the error text.
1429
1563
  */
1430
1564
  function gatewayRejectionText(status) {
1431
- return `the WorkBuddy gateway rejected this credential (http ${status}). This usually means the account is using a stale sign-in the upstream no longer accepts: sign in again in the WorkBuddy desktop app, then pick the account on the plugin card. Run the WTQ Pool connection check (the command palette entry, or the panel's connection tab) to list every credential found.`;
1565
+ return `the WorkBuddy gateway rejected this credential (http ${status}). This usually means the account is using a stale sign-in the upstream no longer accepts: sign in again in the WorkBuddy desktop app, then pick the account on the plugin card. Run the WTQ Pool connection check (the panel's connection tab) to list every credential found.`;
1432
1566
  }
1433
1567
  /**
1434
1568
  * Read a failed response's body, bounded in both time and size.
@@ -1653,43 +1787,6 @@ function numberField(record, key) {
1653
1787
  function asRecord(value) {
1654
1788
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
1655
1789
  }
1656
- /**
1657
- * Flatten one upstream task entry.
1658
- *
1659
- * Progress is reported two ways depending on the task: flat `current`/`target`
1660
- * fields, or a nested `progress: {current, target}`. The nested form wins when
1661
- * it carries anything, because a task that reports both puts the live counter
1662
- * there. Entries without a usable `task_code` are dropped — without one the
1663
- * claim path cannot be built.
1664
- */
1665
- function parseTask(value) {
1666
- const raw = asRecord(value);
1667
- const taskCode = typeof raw["task_code"] === "string" ? raw["task_code"] : "";
1668
- if (taskCode === "") return void 0;
1669
- let current = numberField(raw, "current");
1670
- let target = numberField(raw, "target");
1671
- const nested = asRecord(raw["progress"]);
1672
- const nestedCurrent = numberField(nested, "current");
1673
- const nestedTarget = numberField(nested, "target");
1674
- if (nestedTarget > 0 || nestedCurrent > 0) {
1675
- current = nestedCurrent;
1676
- target = nestedTarget;
1677
- }
1678
- const acceptStatus = typeof raw["accept_status"] === "string" ? raw["accept_status"] : "";
1679
- const claimed = acceptStatus === "claimed";
1680
- return {
1681
- taskCode,
1682
- title: typeof raw["title"] === "string" && raw["title"] !== "" ? raw["title"] : taskCode,
1683
- credit: numberField(raw, "reward_credit"),
1684
- energy: numberField(raw, "reward_energy"),
1685
- target,
1686
- current,
1687
- acceptStatus,
1688
- claimable: !claimed && (target <= 0 || current >= target),
1689
- claimed,
1690
- locked: raw["locked"] === true
1691
- };
1692
- }
1693
1790
  /** Parse one catalog entry; entries without usable token limits are dropped. */
1694
1791
  function parseUpstreamModel(value) {
1695
1792
  if (typeof value !== "object" || value === null) return void 0;
@@ -1823,13 +1920,20 @@ var WorkBuddyUpstreamClient = class {
1823
1920
  } finally {
1824
1921
  deadline.arrived();
1825
1922
  }
1826
- if (response.ok) return {
1827
- ok: true,
1828
- response: response.body === null ? response : new Response(withIdleWatchdog(response.body, timeouts?.idleMs, signal), {
1829
- status: response.status,
1830
- headers: response.headers
1831
- })
1832
- };
1923
+ if (response.ok) {
1924
+ if (response.body === null) return {
1925
+ ok: true,
1926
+ response
1927
+ };
1928
+ const relayed = withIdleWatchdog(response.body, timeouts?.idleMs, signal);
1929
+ return {
1930
+ ok: true,
1931
+ response: withRelayStream(new Response(relayed, {
1932
+ status: response.status,
1933
+ headers: response.headers
1934
+ }), relayed)
1935
+ };
1936
+ }
1833
1937
  const text = await readErrorBody(response, ERROR_BODY_LIMIT, signal);
1834
1938
  const retryAfter = retryAfterSeconds(response.headers);
1835
1939
  return {
@@ -1953,7 +2057,7 @@ var WorkBuddyUpstreamClient = class {
1953
2057
  let nearestExpiryMs;
1954
2058
  const SOON_MS = 2592e5;
1955
2059
  const parseDate = (raw) => {
1956
- if (typeof raw === "number" && raw > 0xe8d4a51000) return raw;
2060
+ if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) return raw > 0xe8d4a51000 ? raw : raw > 1e9 ? raw * 1e3 : void 0;
1957
2061
  if (typeof raw === "string" && raw !== "") {
1958
2062
  const parsed = Date.parse(raw);
1959
2063
  if (!Number.isNaN(parsed)) return parsed;
@@ -2240,6 +2344,7 @@ var WorkBuddyUpstreamClient = class {
2240
2344
  days: numberField(streak, "days"),
2241
2345
  nextTier: typeof streak["next_tier"] === "string" ? streak["next_tier"] : "",
2242
2346
  nextTierRemaining: numberField(streak, "next_tier_remaining"),
2347
+ makeupCards: numberField(asRecord(data["makeup_cards"]), "balance"),
2243
2348
  tiers
2244
2349
  };
2245
2350
  }
@@ -2258,110 +2363,69 @@ var WorkBuddyUpstreamClient = class {
2258
2363
  });
2259
2364
  }
2260
2365
  /**
2261
- * Fetch the growth task list for one account.
2366
+ * Call a billing-domain endpoint and return its unwrapped `data`.
2262
2367
  *
2263
- * The upstream answers `data.tasks[]`, and `claimable` is derived locally —
2264
- * the upstream does not mark it. The task list is the one growth endpoint
2265
- * that DOES carry the `/v2` prefix.
2368
+ * Counterpart of {@link growthJson}: same envelope, but these paths carry the
2369
+ * `/v2/billing/meter` prefix and the billing host. Kept separate because the
2370
+ * prefix is part of the path, not something the caller should remember.
2266
2371
  */
2267
- async listTasks(credential) {
2268
- const response = await this.fetchImpl(`${chatBase(credential)}/v2/activity/growth/tasks`, {
2372
+ async billingJson(credential, path, body) {
2373
+ const response = await this.fetchImpl(`${billingBase(credential)}${path}`, {
2269
2374
  redirect: "error",
2270
- headers: chatHeaders(credential),
2375
+ method: "POST",
2376
+ headers: billingHeaders(credential),
2377
+ body: body === void 0 ? "{}" : JSON.stringify(body),
2271
2378
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
2272
2379
  });
2273
2380
  const envelope = await readEnvelope(response);
2274
2381
  if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
2275
- const raw = Array.isArray(asRecord(envelope.data)["tasks"]) ? asRecord(envelope.data)["tasks"] : [];
2276
- const out = [];
2277
- for (const entry of raw) {
2278
- const parsed = parseTask(entry);
2279
- if (parsed !== void 0) out.push(parsed);
2280
- }
2281
- return out;
2382
+ return asRecord(envelope.data);
2282
2383
  }
2283
2384
  /**
2284
- * Accept (enrol in) tasks by code.
2385
+ * The one-off starter gift. Once per account; a second claim is a business
2386
+ * error, which the caller treats as "nothing to collect".
2285
2387
  *
2286
- * Accepting is the "sign up" half: it produces no progress by itself, and the
2287
- * upstream answers success for an already-accepted task, so replaying this is
2288
- * safe. Progress is lit by real activity (a chat, an activity report).
2289
- *
2290
- * Returns the codes the upstream refused. One retired or renamed code makes
2291
- * the whole batch fail, which used to cost the account every reward of the
2292
- * pass, because the caller's second list read never ran. The batch is
2293
- * therefore retried code by code when it fails as a whole: a code the
2294
- * upstream will not take is reported instead of thrown, and the rest still
2295
- * lands.
2388
+ * No `/v2` prefix: that form answers a 404 route miss, while the bare path is
2389
+ * the one the console itself posts to.
2296
2390
  */
2297
- async acceptTasks(credential, taskCodes) {
2298
- if (taskCodes.length === 0) return [];
2299
- const post = async (codes) => {
2300
- const response = await this.fetchImpl(`${chatBase(credential)}/v2/activity/growth/tasks/accept`, {
2301
- redirect: "error",
2302
- method: "POST",
2303
- headers: chatHeaders(credential),
2304
- body: JSON.stringify({ task_codes: [...codes] }),
2305
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
2306
- });
2307
- const envelope = await readEnvelope(response);
2308
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
2309
- };
2310
- try {
2311
- await post(taskCodes);
2312
- return [];
2313
- } catch (error) {
2314
- if (taskCodes.length === 1) throw error;
2315
- const refused = [];
2316
- for (const code of taskCodes) try {
2317
- await post([code]);
2318
- } catch {
2319
- refused.push(code);
2320
- }
2321
- if (refused.length === taskCodes.length) throw error;
2322
- return refused;
2323
- }
2391
+ async claimGift(credential) {
2392
+ return numberField(await this.billingJson(credential, "/billing/meter/claim-gift"), "credit");
2393
+ }
2394
+ /** Campaign compensation, when the account has any waiting. */
2395
+ async claimCompensation(credential) {
2396
+ return numberField(await this.billingJson(credential, "/billing/meter/claim-compensation"), "credit");
2324
2397
  }
2325
2398
  /**
2326
- * Claim one task's reward.
2399
+ * Whether yesterday is still empty on the streak heatmap.
2327
2400
  *
2328
- * Two details differ from list/accept and are load-bearing:
2329
- *
2330
- * - The task code rides the PATH, not the body.
2331
- * - It is served by the web origin, not the chat host, and only when the
2332
- * request carries the growth-centre Origin/Referer plus
2333
- * `x-client-platform: web`. The chat host's `/reward/claim` path does not
2334
- * exist and answers 400 "task not completed".
2335
- *
2336
- * A repeat claim answers `already_claimed` with zero credit, which is treated
2337
- * as success so the caller can stay idempotent.
2401
+ * A missed day breaks the run, and the run is what unlocks the 7/14/28-day
2402
+ * tiers, so this is read before deciding to spend a make-up card on it.
2338
2403
  */
2339
- async claimTaskReward(credential, taskCode) {
2340
- const headers = {
2341
- ...billingHeaders(credential),
2342
- "Accept": "application/json, text/plain, */*",
2343
- "Origin": "https://www.workbuddy.cn",
2344
- "Referer": "https://www.workbuddy.cn/profile/growth-center",
2345
- "x-client-platform": "web",
2346
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
2347
- };
2348
- const response = await this.fetchImpl(`https://www.workbuddy.cn/activity/growth/tasks/${encodeURIComponent(taskCode)}/claim`, {
2349
- method: "POST",
2350
- redirect: "error",
2351
- headers,
2352
- signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
2353
- });
2354
- const envelope = await readEnvelope(response);
2355
- if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
2356
- const data = asRecord(envelope.data);
2357
- if (data["already_claimed"] === true) return {
2358
- credit: 0,
2359
- energy: 0
2360
- };
2361
- return {
2362
- credit: numberField(data, "credit"),
2363
- energy: numberField(data, "energy")
2364
- };
2404
+ async missedYesterday(credential) {
2405
+ const data = await this.growthJson(credential, "GET", "/activity/growth/heatmap");
2406
+ const cells = Array.isArray(data["cells"]) ? data["cells"] : [];
2407
+ const yesterday = zonedDay(-1);
2408
+ for (const entry of cells) {
2409
+ const cell = asRecord(entry);
2410
+ if ((typeof cell["date"] === "string" ? cell["date"].slice(0, 10) : "") === yesterday) return numberField(cell, "score") === 0;
2411
+ }
2412
+ return false;
2413
+ }
2414
+ /** Spend one make-up card on a past day (`YYYY-MM-DD`). */
2415
+ async useMakeupCard(credential, date) {
2416
+ await this.growthJson(credential, "POST", "/activity/growth/makeup-cards/use", { target_date: date });
2417
+ }
2418
+ /** Make-up cards in hand; the streak is only repairable while this is above zero. */
2419
+ async makeupCards(credential) {
2420
+ return numberField(asRecord((await this.growthJson(credential, "GET", "/activity/growth/streak"))["makeup_cards"]), "balance");
2421
+ }
2422
+ /** Draws available from redeemed streak tiers. */
2423
+ async lotteryChances(credential) {
2424
+ return numberField(await this.growthJson(credential, "GET", "/activity/growth/lottery/summary"), "chances");
2425
+ }
2426
+ /** Spend one draw; the prize payload is passed through as-is. */
2427
+ async drawLottery(credential) {
2428
+ return await this.growthJson(credential, "POST", "/activity/growth/lottery/draw", { client_token: randomUUID() });
2365
2429
  }
2366
2430
  };
2367
2431
  //#endregion
@@ -2468,6 +2532,64 @@ function windowsRegistryAppPaths() {
2468
2532
  return registryAppPaths;
2469
2533
  }
2470
2534
  /**
2535
+ * The Windows directory, whichever of the two variables holds it.
2536
+ *
2537
+ * Both are read here rather than only in `scanInterpreter`, because the module
2538
+ * path and the interpreter have to come from the same place: pinning the
2539
+ * absolute path from `windir` while the 5.1 module directory was skipped for a
2540
+ * missing `SystemRoot` left `Get-AuthenticodeSignature` unable to load for every
2541
+ * candidate, which is the failure this pair exists to avoid.
2542
+ */
2543
+ function systemRootOf(env) {
2544
+ const value = env["SystemRoot"]?.trim() || env["windir"]?.trim();
2545
+ return value === void 0 || value === "" ? void 0 : value;
2546
+ }
2547
+ /**
2548
+ * The environment the signature scan runs in.
2549
+ *
2550
+ * `powershell` is Windows PowerShell 5.1, and it resolves
2551
+ * `Microsoft.PowerShell.Security` by walking `PSModulePath` in order. Any machine
2552
+ * with a Store-installed PowerShell 7 carries that build's Modules directory
2553
+ * ahead of the system one, because the Store install prepends it to the variable
2554
+ * the desktop host inherited. 5.1 then binds the 7 build's copy of the module
2555
+ * first and the import dies on a type-data conflict, so
2556
+ * `Get-AuthenticodeSignature` throws for every candidate. The scan's own catch
2557
+ * swallows that, the policy function is handed an empty status, and the at-rest
2558
+ * key reads as "no WorkBuddy executable found" on a machine holding two signed
2559
+ * installs. Putting the 5.1 directory first makes the right copy win.
2560
+ *
2561
+ * The directory is derived from `SystemRoot` rather than written out, and the
2562
+ * rest of the ambient path is left alone so a user's own modules still resolve.
2563
+ * Applying it twice is a no-op, so the answer stays one directory long however
2564
+ * often it is built.
2565
+ */
2566
+ function signatureScanEnv(env = process.env) {
2567
+ const systemRoot = systemRootOf(env);
2568
+ const ambient = env["PSModulePath"];
2569
+ const modules = systemRoot === void 0 ? void 0 : join(systemRoot, "system32", "WindowsPowerShell", "v1.0", "Modules");
2570
+ if (modules === void 0) return { ...env };
2571
+ if (ambient === modules || ambient?.startsWith(`${modules};`) === true) return { ...env };
2572
+ return {
2573
+ ...env,
2574
+ PSModulePath: ambient === void 0 || ambient === "" ? modules : `${modules};${ambient}`
2575
+ };
2576
+ }
2577
+ /**
2578
+ * The interpreter to run the scan with, by absolute path.
2579
+ *
2580
+ * Resolved from `SystemRoot` rather than through `PATH`, for the same reason the
2581
+ * scan exists at all: a user-level directory is on the default `PATH`
2582
+ * (`%LOCALAPPDATA%\Microsoft\WindowsApps`), so a bare `powershell` would let
2583
+ * whatever sits there be spawned inside a process holding every WorkBuddy token.
2584
+ * Neither variable set answers `undefined`, and the caller treats that as "no
2585
+ * scan" rather than guessing a path.
2586
+ */
2587
+ function scanInterpreter(env) {
2588
+ const systemRoot = systemRootOf(env);
2589
+ if (systemRoot === void 0) return void 0;
2590
+ return join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
2591
+ }
2592
+ /**
2471
2593
  * Every path an uninstall key names for a WorkBuddy-family install, paired with
2472
2594
  * the signature PowerShell found on it.
2473
2595
  *
@@ -2481,7 +2603,8 @@ function windowsRegistryAppPaths() {
2481
2603
  * PowerShell does the part only it can do: enumerate, clean the resource index
2482
2604
  * and quotes off `DisplayIcon`, stat the file, and read its signature. The
2483
2605
  * decision is {@link signatureAccepts}'s, in Node, because that is where it can
2484
- * be tested without a registry to plant a key in.
2606
+ * be tested without a registry to plant a key in, and it is handed a module path
2607
+ * 5.1 can actually load, because the host's is not always one.
2485
2608
  */
2486
2609
  function readRegistryAppPaths() {
2487
2610
  const script = [
@@ -2515,8 +2638,10 @@ function readRegistryAppPaths() {
2515
2638
  "}"
2516
2639
  ].join("\n");
2517
2640
  let stdout;
2641
+ const interpreter = scanInterpreter(process.env);
2642
+ if (interpreter === void 0) return [];
2518
2643
  try {
2519
- stdout = execFileSync("powershell", [
2644
+ stdout = execFileSync(interpreter, [
2520
2645
  "-NoProfile",
2521
2646
  "-NonInteractive",
2522
2647
  "-ExecutionPolicy",
@@ -2527,7 +2652,8 @@ function readRegistryAppPaths() {
2527
2652
  encoding: "utf8",
2528
2653
  timeout: 2e4,
2529
2654
  windowsHide: true,
2530
- maxBuffer: 8388608
2655
+ maxBuffer: 8388608,
2656
+ env: signatureScanEnv()
2531
2657
  });
2532
2658
  } catch {
2533
2659
  return [];
@@ -2715,6 +2841,37 @@ async function encryptedFieldOpener() {
2715
2841
  const WORKBUDDY_LIVE_FILENAME = "workbuddy-desktop.info";
2716
2842
  /** Env override for the auth file or its directory. */
2717
2843
  const WORKBUDDY_AUTH_FILE_ENV = "WORKBUDDY_AUTH_FILE";
2844
+ /**
2845
+ * File the pool keeps beside its own settings: every credential it has seen.
2846
+ *
2847
+ * The CN client writes a timestamped snapshot beside its live sign-in, so a
2848
+ * re-login leaves the previous account's file behind. The global client writes
2849
+ * one live file and nothing else, and switching accounts overwrites it — which
2850
+ * is why the global pool saw a single account no matter how many had signed in.
2851
+ */
2852
+ const ARCHIVE_FILENAME = "credentials-archive.json";
2853
+ /** Subdirectory of the plugin's own data root that holds the sign-ins it wrote. */
2854
+ const OWN_SIGN_IN_DIRNAME = "signins";
2855
+ /** File-name prefix that marks one of those sign-ins as the plugin's own. */
2856
+ const OWN_SIGN_IN_PREFIX = "workbuddy-panel-";
2857
+ /**
2858
+ * How long a delete waits for a scan that is already running.
2859
+ *
2860
+ * The wait is for ordering, not for the walk itself: a normal scan is a handful
2861
+ * of milliseconds, and the host answers a panel call in thirty seconds. A cold
2862
+ * scan stuck in the at-rest key fetch would otherwise burn that whole budget and
2863
+ * report the delete as failed after it had already happened.
2864
+ */
2865
+ const DELETE_SCAN_WAIT_MS = 5e3;
2866
+ /**
2867
+ * How long an archived credential is kept after the last token it can still be
2868
+ * renewed with would have expired.
2869
+ *
2870
+ * Measured against the credential's own dates rather than the file's write time:
2871
+ * an account switched away from today is worth keeping for as long as its
2872
+ * refresh token lives, and the global access token alone is valid for a year.
2873
+ */
2874
+ const ARCHIVE_RETENTION_MS = 2592e6;
2718
2875
  function nonEmptyEnv(value) {
2719
2876
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
2720
2877
  }
@@ -2751,32 +2908,33 @@ const MAX_EXPIRY_MS = 41024448e5;
2751
2908
  *
2752
2909
  * Anything past {@link MAX_EXPIRY_MS} is unusable input, not a date, so it
2753
2910
  * reads as "no expiry" (0) - the same answer a sign-in without an `expiresAt`
2754
- * gives. The caller must not treat that as "fresh": see {@link refreshExpiryMs}.
2911
+ * gives. The caller must not treat that as "fresh": see {@link tokenExpiryMs}.
2755
2912
  */
2756
2913
  function expiryToMs(value) {
2757
2914
  if (!Number.isFinite(value) || value <= 0) return 0;
2758
2915
  const ms = value > 0xe8d4a51000 ? value : value * 1e3;
2759
2916
  return ms > MAX_EXPIRY_MS ? 0 : ms;
2760
2917
  }
2918
+ function optionalString$1(value) {
2919
+ return typeof value === "string" && value !== "" ? value : void 0;
2920
+ }
2761
2921
  /**
2762
- * Absolute expiry for a refreshed token.
2922
+ * Whether `work` finished inside `budgetMs`.
2763
2923
  *
2764
- * `expiresIn` comes from the vendor's own answer, so it is bounded here rather
2765
- * than trusted: a garbled one (Infinity, 1e300) would otherwise store a
2766
- * timestamp past `Date`'s range, and the panel's `toISOString()` for that row
2767
- * then threw, failing the whole document rather than the one field. A value
2768
- * this function refuses falls back to the assumed lifetime, not to 0: 0 means
2769
- * "never expires", which would leave a token that really was not fresh being
2770
- * served as if it were.
2924
+ * A timeout here is not a cancellation: the caller is told to stop waiting, and
2925
+ * whatever it started keeps running. The timer is cleared on the fast path so a
2926
+ * short wait does not hold the process open for the whole budget.
2771
2927
  */
2772
- function refreshExpiryMs(expiresInSec) {
2773
- const assumed = () => Date.now() + ASSUMED_TOKEN_LIFETIME_MS;
2774
- if (typeof expiresInSec !== "number" || !Number.isFinite(expiresInSec) || expiresInSec <= 0) return assumed();
2775
- const at = expiryToMs(Date.now() + expiresInSec * 1e3);
2776
- return at === 0 ? assumed() : at;
2777
- }
2778
- function optionalString$1(value) {
2779
- return typeof value === "string" && value !== "" ? value : void 0;
2928
+ async function raceWithTimeout(work, budgetMs) {
2929
+ let timer;
2930
+ const timeout = new Promise((resolve) => {
2931
+ timer = setTimeout(() => resolve(false), budgetMs);
2932
+ });
2933
+ try {
2934
+ return await Promise.race([work.then(() => true), timeout]);
2935
+ } finally {
2936
+ if (timer !== void 0) clearTimeout(timer);
2937
+ }
2780
2938
  }
2781
2939
  /**
2782
2940
  * Parse a WorkBuddy auth document. Accepts the nested desktop shape
@@ -2981,6 +3139,34 @@ const POOL_HOLD_CAP_MS = 864e5;
2981
3139
  * sprays distinct ids could otherwise grow one map per account forever.
2982
3140
  */
2983
3141
  const MAX_MODEL_COOLDOWN_KEYS = 128;
3142
+ /**
3143
+ * How far a repeated limit may stretch the configured window, and how many times
3144
+ * it may double first.
3145
+ *
3146
+ * One `usage exceeds frequency limit` is the commonest answer the upstream
3147
+ * sends, and returning the account after the configured minute put it straight
3148
+ * back into the same wall for as long as the window lasted: every attempt spent
3149
+ * an upstream call to learn nothing. Doubling from the user's own window keeps
3150
+ * their setting in charge of the first retry and only stretches the ones that
3151
+ * keep failing, which is the escalation the reference proxy settled on after the
3152
+ * same incident.
3153
+ */
3154
+ const RATE_LIMIT_STREAK_CAP = 9e5;
3155
+ const RATE_LIMIT_STREAK_STEPS = 4;
3156
+ /**
3157
+ * How close two failures have to be to count as consecutive.
3158
+ *
3159
+ * Without this the count is a lifetime total: one failure hours ago plus another
3160
+ * today would sit at the cap forever, and every future one would open at the
3161
+ * longest window. The reference proxy names that exact shape as the bug that made
3162
+ * a working credential look broken.
3163
+ *
3164
+ * It has to outlast `RATE_LIMIT_STREAK_CAP`, or the top of the ladder cancels
3165
+ * itself: the account cannot be tried again until that window has passed, so it
3166
+ * would always come back to a count of one and the cap would apply once per
3167
+ * cycle instead of holding a persistently limited account back.
3168
+ */
3169
+ const RATE_LIMIT_STREAK_WINDOW_MS = RATE_LIMIT_STREAK_CAP * 2;
2984
3170
  /** Drop expired per-model cooldowns, then cap what is left, soonest first. */
2985
3171
  function pruneModelCooldowns(account, now) {
2986
3172
  for (const [modelId, until] of Object.entries(account.modelCooldowns)) if (until <= now) delete account.modelCooldowns[modelId];
@@ -2990,15 +3176,58 @@ function pruneModelCooldowns(account, now) {
2990
3176
  for (const key of keys.slice(0, keys.length - MAX_MODEL_COOLDOWN_KEYS)) delete account.modelCooldowns[key];
2991
3177
  }
2992
3178
  /**
2993
- * Lifetime assumed for a refreshed token whose answer carries no `expiresIn`.
3179
+ * Directory the plugin writes its own sign-ins into.
2994
3180
  *
2995
- * It must exceed {@link REFRESH_MARGIN_MS}, or the refreshed
2996
- * credential would read as already-expiring and every request would refresh
2997
- * again. An hour is comfortably past the five-minute margin and far short of the
2998
- * two-hour cap, so a token with a real lifetime always replaces it in time.
3181
+ * A login the panel starts lands here rather than in the desktop app's auth
3182
+ * directory: the app owns that directory and indexes the files it wrote, so a
3183
+ * foreign `.info` beside them is a file nothing maintains. This one is scanned
3184
+ * on the same terms as the vendor's, so an account added from the panel is an
3185
+ * ordinary pool account, and it disappears only when the user removes it.
3186
+ */
3187
+ function ownSignInDir(dataPath) {
3188
+ return dataPath === "" ? "" : join(dataPath, OWN_SIGN_IN_DIRNAME);
3189
+ }
3190
+ /**
3191
+ * Write one panel-added sign-in as a `.info` file the scan reads back.
3192
+ *
3193
+ * The shape is the desktop app's own, so `parseWorkBuddyAuth` opens it with no
3194
+ * special case. The file name carries the billing identity: re-adding the same
3195
+ * account rewrites its own file instead of leaving a second copy behind, and
3196
+ * two accounts never collide on a name.
3197
+ */
3198
+ async function writeOwnSignIn(directory, signIn) {
3199
+ const stable = signIn.uin === "" ? signIn.uid : signIn.uin;
3200
+ const suffix = stable === "" ? randomUUID() : stable.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 32);
3201
+ const file = join(directory, `${OWN_SIGN_IN_PREFIX}${suffix === "" ? randomUUID() : suffix}.info`);
3202
+ await mkdir(directory, { recursive: true });
3203
+ await writeFile(file, JSON.stringify({
3204
+ auth: {
3205
+ accessToken: signIn.accessToken,
3206
+ refreshToken: signIn.refreshToken,
3207
+ expiresAt: signIn.expiresAtMs,
3208
+ domain: signIn.domain,
3209
+ lastRefreshTime: Date.now()
3210
+ },
3211
+ account: {
3212
+ ...signIn.uid === "" ? {} : { uid: signIn.uid },
3213
+ ...signIn.uin === "" ? {} : { uin: signIn.uin },
3214
+ ...signIn.enterpriseId === "" ? {} : { enterpriseId: signIn.enterpriseId },
3215
+ ...signIn.nickname === "" ? {} : { nickname: signIn.nickname }
3216
+ }
3217
+ }, null, 2), { mode: 384 });
3218
+ return file;
3219
+ }
3220
+ /**
3221
+ * Soonest future one-off expiry. Missing or past sorts last. None left -> list head.
3222
+ *
3223
+ * Strict soonest-first, not a weighted spread: this mode exists so a pack about to
3224
+ * lapse is the one that gets spent, and a pool of two or three accounts has
3225
+ * nothing to spread. The burst this could cause is bounded by `available`, which
3226
+ * drops an account the moment the upstream limits it, so the next request already
3227
+ * goes elsewhere. The reference proxy weights the share instead, because it runs
3228
+ * enough accounts that one of them would otherwise absorb every request; adopting
3229
+ * that here would trade away the guarantee the user picked the mode for.
2999
3230
  */
3000
- const ASSUMED_TOKEN_LIFETIME_MS = 36e5;
3001
- /** Soonest future one-off expiry. Missing or past sorts last. None left → list head. */
3002
3231
  function pickSoonestExpiry(pool, expiryMs, now) {
3003
3232
  let best;
3004
3233
  let bestAt = Infinity;
@@ -3030,6 +3259,95 @@ function sameDirs(a, b) {
3030
3259
  return a.every((dir) => b.includes(dir));
3031
3260
  }
3032
3261
  /**
3262
+ * Read the credential archive: id → credential.
3263
+ *
3264
+ * A missing file is an empty archive. A read error or a damaged document
3265
+ * throws, so the writer leaves the file alone instead of saving an empty one
3266
+ * over every sign-in it still holds.
3267
+ */
3268
+ async function readArchivedCredentials(file) {
3269
+ const stored = /* @__PURE__ */ new Map();
3270
+ let text;
3271
+ try {
3272
+ text = await readFile(file, "utf8");
3273
+ } catch (error) {
3274
+ if (error.code === "ENOENT") return stored;
3275
+ throw error;
3276
+ }
3277
+ let parsed;
3278
+ try {
3279
+ parsed = JSON.parse(text);
3280
+ } catch {
3281
+ throw new Error("credential archive is not valid JSON");
3282
+ }
3283
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return stored;
3284
+ const entries = parsed.entries;
3285
+ if (!Array.isArray(entries)) return stored;
3286
+ const horizon = Date.now() - ARCHIVE_RETENTION_MS;
3287
+ for (const entry of entries) {
3288
+ if (typeof entry !== "object" || entry === null) continue;
3289
+ const record = entry;
3290
+ if (typeof record["id"] !== "string" || record["id"] === "") continue;
3291
+ if (typeof record["accessToken"] !== "string" || record["accessToken"] === "") continue;
3292
+ const expiresAt = typeof record["expiresAtMs"] === "number" ? record["expiresAtMs"] : 0;
3293
+ const refreshExpiresAt = typeof record["refreshExpiresAtMs"] === "number" ? record["refreshExpiresAtMs"] : 0;
3294
+ const lastUsable = Math.max(expiresAt, refreshExpiresAt);
3295
+ if (lastUsable > 0 && lastUsable < horizon) continue;
3296
+ stored.set(record["id"], {
3297
+ accessToken: record["accessToken"],
3298
+ refreshToken: typeof record["refreshToken"] === "string" ? record["refreshToken"] : "",
3299
+ expiresAtMs: typeof record["expiresAtMs"] === "number" ? record["expiresAtMs"] : 0,
3300
+ ...typeof record["refreshExpiresAtMs"] !== "number" ? {} : { refreshExpiresAtMs: record["refreshExpiresAtMs"] },
3301
+ ...typeof record["lastRefreshAtMs"] !== "number" ? {} : { lastRefreshAtMs: record["lastRefreshAtMs"] },
3302
+ ...typeof record["nickname"] !== "string" || record["nickname"] === "" ? {} : { nickname: record["nickname"] },
3303
+ ...typeof record["uin"] !== "string" || record["uin"] === "" ? {} : { uin: record["uin"] },
3304
+ ...typeof record["uid"] !== "string" || record["uid"] === "" ? {} : { uid: record["uid"] },
3305
+ ...typeof record["enterpriseId"] !== "string" || record["enterpriseId"] === "" ? {} : { enterpriseId: record["enterpriseId"] },
3306
+ domain: typeof record["domain"] === "string" ? record["domain"] : "",
3307
+ sourcePath: typeof record["sourcePath"] === "string" ? record["sourcePath"] : ""
3308
+ });
3309
+ }
3310
+ return stored;
3311
+ }
3312
+ /**
3313
+ * Write the archive, replacing the previous file only once the new one is whole.
3314
+ *
3315
+ * The write is what keeps an overwritten sign-in recoverable, so it must not
3316
+ * leave a truncated file behind if it is interrupted: temp file, then rename.
3317
+ * Only the archived credential is stored, not the raw sign-in document.
3318
+ */
3319
+ async function writeArchivedCredentials(file, entries) {
3320
+ await mkdir(dirname(file), { recursive: true });
3321
+ const body = JSON.stringify({
3322
+ version: 1,
3323
+ entries: [...entries].map(([id, credential]) => ({
3324
+ id,
3325
+ accessToken: credential.accessToken,
3326
+ refreshToken: credential.refreshToken,
3327
+ expiresAtMs: credential.expiresAtMs,
3328
+ ...credential.refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs: credential.refreshExpiresAtMs },
3329
+ ...credential.lastRefreshAtMs === void 0 ? {} : { lastRefreshAtMs: credential.lastRefreshAtMs },
3330
+ ...credential.nickname === void 0 ? {} : { nickname: credential.nickname },
3331
+ ...credential.uin === void 0 ? {} : { uin: credential.uin },
3332
+ ...credential.uid === void 0 ? {} : { uid: credential.uid },
3333
+ ...credential.enterpriseId === void 0 ? {} : { enterpriseId: credential.enterpriseId },
3334
+ domain: credential.domain,
3335
+ sourcePath: credential.sourcePath
3336
+ }))
3337
+ });
3338
+ const temporary = `${file}.${randomUUID()}.tmp`;
3339
+ try {
3340
+ await writeFile(temporary, body, {
3341
+ encoding: "utf8",
3342
+ mode: 384
3343
+ });
3344
+ await rename(temporary, file);
3345
+ } catch (error) {
3346
+ await unlink(temporary).catch(() => {});
3347
+ throw error;
3348
+ }
3349
+ }
3350
+ /**
3033
3351
  * Read-only pool of every discovered WorkBuddy account, with rate-limit
3034
3352
  * cooldown and round-robin failover.
3035
3353
  */
@@ -3080,9 +3398,13 @@ var WorkBuddyAccountPool = class {
3080
3398
  * would strand a healthy pool, and the first 402 still cools it as before.
3081
3399
  */
3082
3400
  creditBalances = /* @__PURE__ */ new Map();
3401
+ /** Supplies the archive directory; asked on each scan, not at construction. */
3402
+ dataPath;
3083
3403
  /** Soonest remaining one-off pack, ms. Cleared when that pack is spent or past. */
3084
3404
  creditExpiries = /* @__PURE__ */ new Map();
3085
3405
  refreshInflight = /* @__PURE__ */ new Map();
3406
+ /** Tail of the archive's write chain; every archive write waits on it. */
3407
+ archiveQueue = Promise.resolve();
3086
3408
  /** The one scan in progress; concurrent callers await it instead of duplicating it. */
3087
3409
  scanInflight;
3088
3410
  /** The directories the in-flight scan is reading, so a repoint supersedes it. */
@@ -3095,20 +3417,42 @@ var WorkBuddyAccountPool = class {
3095
3417
  */
3096
3418
  noRefreshWarned = /* @__PURE__ */ new Set();
3097
3419
  /**
3098
- * Accounts a hold the pool itself decided is keeping out of rotation.
3420
+ * Accounts a hold the pool itself decided is keeping out of rotation, and why.
3099
3421
  *
3100
3422
  * Separate from `cooldownUntilMs` because the two are released by different
3101
3423
  * things: an upstream's rate-limit window expires on its own, while a hold
3102
- * ends when the condition behind it changes. A balance read that finds credits
3103
- * again is that signal for a spent account, and it has to be able to tell a
3104
- * hold from a rate limit to release the right one.
3424
+ * ends when the condition behind it changes. The reason is recorded because
3425
+ * the two conditions are not the same signal: a balance read finding credits
3426
+ * again says a spent account was topped up, and it says nothing about a
3427
+ * sign-in the upstream refuses. Releasing both on a balance meant a 401'ing
3428
+ * account went back to the head of the queue on every probe cycle.
3105
3429
  */
3106
- heldIds = /* @__PURE__ */ new Set();
3107
- constructor(options = {}) {
3108
- this.logger = options.logger;
3109
- this.authDirs = options.authDirs ?? candidateAuthDirs();
3110
- this.cooldownMs = options.cooldownMs ?? 6e4;
3111
- this.client = options.client;
3430
+ heldIds = /* @__PURE__ */ new Map();
3431
+ /**
3432
+ * The sign-ins each account's own files hold, as of the last scan.
3433
+ *
3434
+ * Only the files the client and the panel write, not the archive: the archive
3435
+ * is rewritten whenever this process refreshes a token, so counting it would
3436
+ * turn every refresh into a "the user signed in again".
3437
+ */
3438
+ signInTokens = /* @__PURE__ */ new Map();
3439
+ /**
3440
+ * Sign-ins the upstream refused, per account.
3441
+ *
3442
+ * `compareFreshness` ranks a live desktop file above every panel sign-in
3443
+ * whatever their issue times, so a token that was refused would win that ranking
3444
+ * again on the very next scan and the account would go on sending it - the hold
3445
+ * would look released while the requests kept failing. Kept across scans, and
3446
+ * dropped once the sign-in is no longer on disk or the cooldowns are reset.
3447
+ */
3448
+ refusedSignIns = /* @__PURE__ */ new Map();
3449
+ constructor(options = {}) {
3450
+ this.logger = options.logger;
3451
+ this.authDirs = options.authDirs ?? candidateAuthDirs();
3452
+ this.dataPath = options.dataPath;
3453
+ this.cooldownMs = options.cooldownMs ?? 6e4;
3454
+ if (!Number.isFinite(this.cooldownMs) || this.cooldownMs <= 0) this.cooldownMs = 6e4;
3455
+ this.client = options.client;
3112
3456
  this.distribution = options.distribution ?? "priority";
3113
3457
  }
3114
3458
  /**
@@ -3150,10 +3494,17 @@ var WorkBuddyAccountPool = class {
3150
3494
  if (typeof nearestExpiryMs === "number" && Number.isFinite(nearestExpiryMs) && nearestExpiryMs > Date.now()) this.creditExpiries.set(accountId, nearestExpiryMs);
3151
3495
  else this.creditExpiries.delete(accountId);
3152
3496
  const account = this.accounts.find((item) => item.id === accountId);
3153
- if (account !== void 0 && total > 0 && this.heldIds.delete(accountId) && account.cooldownUntilMs > Date.now()) {
3154
- account.cooldownUntilMs = 0;
3155
- this.logger?.info?.(`${LOG_PREFIX}: ${account.label} has credits again; releasing the hold`);
3497
+ if (account === void 0) return;
3498
+ const hold = this.heldIds.get(accountId);
3499
+ if (hold === void 0) return;
3500
+ if (hold.until <= Date.now()) {
3501
+ this.heldIds.delete(accountId);
3502
+ return;
3156
3503
  }
3504
+ if (hold.reason !== "spent" || total <= 0) return;
3505
+ this.heldIds.delete(accountId);
3506
+ if (account.cooldownUntilMs > Date.now() && account.cooldownUntilMs <= hold.until) account.cooldownUntilMs = 0;
3507
+ this.logger?.info?.(`${LOG_PREFIX}: ${account.label} has credits again; releasing the hold`);
3157
3508
  }
3158
3509
  /** True when a known balance has reached the floor set for this account. */
3159
3510
  reserveHolds(accountId) {
@@ -3176,6 +3527,71 @@ var WorkBuddyAccountPool = class {
3176
3527
  applyRemoved(ids) {
3177
3528
  this.removedIds = new Set(ids);
3178
3529
  }
3530
+ /**
3531
+ * True when this account's sign-in is one the plugin wrote, so it may be
3532
+ * deleted. The panel asks before it offers the button: deleting a desktop
3533
+ * app's own sign-in would sign the user out of that app.
3534
+ */
3535
+ ownsSignIn(accountId) {
3536
+ const account = this.accounts.find((item) => item.id === accountId);
3537
+ return account !== void 0 && this.isOwnSignInPath(account.credential.sourcePath);
3538
+ }
3539
+ /**
3540
+ * Delete one account's sign-in, and its archive entry with it.
3541
+ *
3542
+ * Two things have to go, not one: the archive keeps a copy of every
3543
+ * credential a walk has seen and reads it back for every directory the walk
3544
+ * can still read, which includes the plugin's own. Deleting only the file
3545
+ * would bring the account straight back on the next scan.
3546
+ *
3547
+ * Only a sign-in this plugin wrote is removable. The desktop app owns its own
3548
+ * directory, and a file deleted there takes the user's session in that app
3549
+ * down with it, so anything outside the plugin's own directory is refused
3550
+ * rather than attempted. Answers false for an unknown account too, so the
3551
+ * caller reports a refusal instead of treating it as done.
3552
+ */
3553
+ async removeOwnSignIn(accountId) {
3554
+ const account = this.accounts.find((item) => item.id === accountId);
3555
+ if (account === void 0) return false;
3556
+ if (!this.isOwnSignInPath(account.credential.sourcePath)) return false;
3557
+ const running = this.scanInflight;
3558
+ if (running !== void 0) {
3559
+ if (!await raceWithTimeout(running.catch(() => {}), DELETE_SCAN_WAIT_MS)) running.catch(() => {}).then(() => this.forgetArchived(account.id));
3560
+ }
3561
+ await unlink(account.credential.sourcePath).catch((error) => {
3562
+ if (error.code !== "ENOENT") throw error;
3563
+ });
3564
+ await this.forgetArchived(account.id);
3565
+ return true;
3566
+ }
3567
+ /** Whether `sourcePath` sits inside the directory the plugin writes into. */ isOwnSignInPath(sourcePath) {
3568
+ const own = ownSignInDir(this.dataPath?.() ?? "");
3569
+ if (own === "" || sourcePath === "") return false;
3570
+ const walked = relative(resolve(own), resolve(sourcePath));
3571
+ return walked !== "" && !walked.startsWith("..") && !isAbsolute(walked);
3572
+ }
3573
+ /**
3574
+ * Drop one account from the credential archive.
3575
+ *
3576
+ * On the same queue as every other archive write: this is a read-modify-write
3577
+ * of one document, and a delete that raced a scan's write would otherwise be
3578
+ * overwritten by it.
3579
+ */
3580
+ async forgetArchived(id) {
3581
+ const file = this.archiveFile();
3582
+ if (file === void 0) return;
3583
+ const run = this.archiveQueue.then(async () => {
3584
+ const stored = await readArchivedCredentials(file);
3585
+ if (!stored.delete(id)) return;
3586
+ await writeArchivedCredentials(file, stored);
3587
+ });
3588
+ this.archiveQueue = run.catch(() => {});
3589
+ try {
3590
+ await run;
3591
+ } catch (error) {
3592
+ this.logger?.warn?.(`${LOG_PREFIX}: could not drop ${id} from the credential archive: ${String(error)}`);
3593
+ }
3594
+ }
3179
3595
  /** Drop every account, e.g. when the source is switched off. A later `scan()` rebuilds from disk. */
3180
3596
  clear() {
3181
3597
  this.accounts = [];
@@ -3194,6 +3610,53 @@ var WorkBuddyAccountPool = class {
3194
3610
  this.scanInflight = inflight;
3195
3611
  return inflight;
3196
3612
  }
3613
+ /**
3614
+ * Keep the credentials this walk saw, so an account whose only file the client
3615
+ * overwrites on the next sign-in still has a copy to be read back from.
3616
+ *
3617
+ * Best effort by design: a failed write costs the archive, never the scan.
3618
+ */
3619
+ async archiveCredentials(credentials) {
3620
+ const file = this.archiveFile();
3621
+ if (file === void 0 || credentials.length === 0) return;
3622
+ const run = this.archiveQueue.then(async () => {
3623
+ const stored = await readArchivedCredentials(file);
3624
+ let changed = false;
3625
+ for (const credential of credentials) {
3626
+ const id = workbuddyAccountId(credential);
3627
+ const previous = stored.get(id);
3628
+ if (previous !== void 0 && !isFresher(credential, previous)) continue;
3629
+ stored.set(id, credential);
3630
+ changed = true;
3631
+ }
3632
+ if (changed) await writeArchivedCredentials(file, stored);
3633
+ });
3634
+ this.archiveQueue = run.catch(() => {});
3635
+ try {
3636
+ await run;
3637
+ } catch (error) {
3638
+ this.logger?.warn?.(`${LOG_PREFIX}: could not update the credential archive: ${String(error)}`);
3639
+ }
3640
+ }
3641
+ /** Credentials the archive kept for a directory this walk can read. */
3642
+ async archivedCredentials(homes) {
3643
+ const file = this.archiveFile();
3644
+ if (file === void 0) return [];
3645
+ try {
3646
+ return [...(await readArchivedCredentials(file)).values()].filter((credential) => homes.has(this.homeOf(credential)));
3647
+ } catch (error) {
3648
+ this.logger?.warn?.(`${LOG_PREFIX}: could not read the credential archive: ${String(error)}`);
3649
+ return [];
3650
+ }
3651
+ }
3652
+ /** The auth directory a credential was read from. */
3653
+ homeOf(credential) {
3654
+ return resolve(dirname(credential.sourcePath));
3655
+ }
3656
+ archiveFile() {
3657
+ const directory = this.dataPath?.();
3658
+ return directory === void 0 || directory === "" ? void 0 : join(directory, ARCHIVE_FILENAME);
3659
+ }
3197
3660
  async scanOnce(dirs) {
3198
3661
  const found = [];
3199
3662
  const readableDirs = /* @__PURE__ */ new Set();
@@ -3208,6 +3671,19 @@ var WorkBuddyAccountPool = class {
3208
3671
  else if (read.kind === "sealed") sealedDirs.add(resolve(dir));
3209
3672
  }
3210
3673
  }
3674
+ await this.archiveCredentials(found);
3675
+ const signInTokens = /* @__PURE__ */ new Map();
3676
+ for (const credential of found) {
3677
+ const id = workbuddyAccountId(credential);
3678
+ const held = signInTokens.get(id);
3679
+ if (held === void 0) signInTokens.set(id, [credential]);
3680
+ else held.push(credential);
3681
+ }
3682
+ const liveIds = new Set(found.map((credential) => workbuddyAccountId(credential)));
3683
+ for (const credential of await this.archivedCredentials(readableDirs)) {
3684
+ if (liveIds.has(workbuddyAccountId(credential))) continue;
3685
+ found.push(credential);
3686
+ }
3211
3687
  const byId = /* @__PURE__ */ new Map();
3212
3688
  for (const account of this.accounts) byId.set(account.id, account);
3213
3689
  for (const credential of found) {
@@ -3224,9 +3700,27 @@ var WorkBuddyAccountPool = class {
3224
3700
  });
3225
3701
  continue;
3226
3702
  }
3227
- if (isFresher(credential, existing.credential)) existing.credential = credential;
3703
+ const hold = this.heldIds.get(id);
3704
+ const heldSignIns = hold?.reason === "session" ? hold.heldSignIns : void 0;
3705
+ const replaced = heldSignIns === void 0 ? void 0 : signInTokens.get(id)?.find((entry) => !heldSignIns.includes(entry.accessToken));
3706
+ if (replaced !== void 0 && hold !== void 0 && heldSignIns !== void 0) {
3707
+ this.heldIds.delete(id);
3708
+ if (existing.cooldownUntilMs <= hold.until) existing.cooldownUntilMs = 0;
3709
+ existing.credential = replaced;
3710
+ this.refusedSignIns.set(id, heldSignIns);
3711
+ }
3712
+ const refused = this.refusedSignIns.get(id);
3713
+ if (isFresher(credential, existing.credential) && !(refused?.includes(credential.accessToken) ?? false)) existing.credential = credential;
3228
3714
  }
3229
3715
  const foundIds = new Set(found.map((credential) => workbuddyAccountId(credential)));
3716
+ for (const [id, refused] of this.refusedSignIns) {
3717
+ if (!foundIds.has(id)) {
3718
+ this.refusedSignIns.delete(id);
3719
+ continue;
3720
+ }
3721
+ const onDisk = signInTokens.get(id);
3722
+ if (onDisk !== void 0 && !refused.some((token) => onDisk.some((entry) => entry.accessToken === token))) this.refusedSignIns.delete(id);
3723
+ }
3230
3724
  const scanNow = Date.now();
3231
3725
  for (const account of byId.values()) pruneModelCooldowns(account, scanNow);
3232
3726
  for (const [id, account] of byId) {
@@ -3238,14 +3732,21 @@ var WorkBuddyAccountPool = class {
3238
3732
  this.creditBalances.delete(id);
3239
3733
  this.creditExpiries.delete(id);
3240
3734
  this.heldIds.delete(id);
3735
+ this.signInTokens.delete(id);
3736
+ this.refusedSignIns.delete(id);
3241
3737
  }
3242
3738
  }
3243
3739
  const ordered = [...byId.values()];
3244
3740
  ordered.sort((a, b) => compareFreshness(a.credential, b.credential));
3245
- for (const account of ordered) account.label = accountLabel(account.credential);
3741
+ for (const account of ordered) {
3742
+ account.label = accountLabel(account.credential);
3743
+ if (liveIds.has(account.id)) delete account.archived;
3744
+ else account.archived = true;
3745
+ }
3246
3746
  disambiguateLabels(ordered);
3247
3747
  if (!sameDirs(this.authDirs, dirs)) return this.accounts;
3248
3748
  this.accounts = ordered;
3749
+ this.signInTokens = signInTokens;
3249
3750
  this.lastScanAtMs = Date.now();
3250
3751
  return this.accounts;
3251
3752
  }
@@ -3280,21 +3781,42 @@ var WorkBuddyAccountPool = class {
3280
3781
  });
3281
3782
  }
3282
3783
  /**
3784
+ * Why this account is not being served right now, for a caller that has to
3785
+ * explain an empty pool. Returns null when the account is eligible.
3786
+ *
3787
+ * One place for the answer: the gateway used to infer a cause from cooldown
3788
+ * timestamps alone, so an expired sign-in was reported as a credit-reserve
3789
+ * setting the user never touched.
3790
+ */
3791
+ unavailableReason(accountId, now, modelId) {
3792
+ const account = this.accounts.find((item) => item.id === accountId);
3793
+ if (account === void 0) return null;
3794
+ if (this.removedIds.has(account.id)) return "removed";
3795
+ if (this.disabledIds.has(account.id)) return "switched off";
3796
+ if (this.reserveHolds(account.id)) return "under its credit reserve";
3797
+ if (credentialUnusable(account.credential, now)) return "sign-in expired";
3798
+ if (account.cooldownUntilMs > now) return this.heldIds.get(account.id)?.reason === "session" ? "sign-in refused" : "on hold";
3799
+ if (modelId !== void 0 && (account.modelCooldowns[modelId] ?? 0) > now) return "rate-limited";
3800
+ return null;
3801
+ }
3802
+ /**
3283
3803
  * Pick the account to serve a request.
3284
3804
  *
3285
- * Two distributions, chosen by the `distribution` setting:
3805
+ * The `distribution` setting chooses how:
3286
3806
  *
3287
- * - **priority** (default, and what the card ships with): one account serves
3288
- * every request until it is rate-limited, then the next in order takes over.
3289
- * Credits drain one account at a time, and a cooling account returns to the
3290
- * head of the queue the moment its window resets — it was never consumed, so
3291
- * it resumes straight away.
3807
+ * - **priority** (default): one account serves every request until it is
3808
+ * rate-limited, then the next in order takes over. Credits drain one account
3809
+ * at a time, and a cooling account returns to the head of the queue the moment
3810
+ * its window resets - it was never consumed, so it resumes straight away.
3292
3811
  * - **round-robin**: consecutive requests rotate through the pool so spend
3293
3812
  * spreads evenly across every account.
3813
+ * - **expiry**: the account whose credit pack expires soonest goes first, so
3814
+ * nothing is wasted on the day it lapses.
3815
+ * - **sticky**: one account per conversation, for as long as it keeps working.
3294
3816
  *
3295
- * In both modes an explicit user selection (`prefer`) heads the list, a
3296
- * cooling account is skipped for that model only, and an unrecognised setting
3297
- * falls back to priority.
3817
+ * In every mode an explicit user selection (`prefer`) heads the list, a cooling
3818
+ * account is skipped for that model only, and an unrecognised setting falls back
3819
+ * to priority.
3298
3820
  *
3299
3821
  * Scans on first use, and rescans when every known account is cooling down: a
3300
3822
  * fresh desktop login is the usual way out of an exhausted pool.
@@ -3371,46 +3893,54 @@ var WorkBuddyAccountPool = class {
3371
3893
  * expired), in-flight de-duped per account. A failed refresh keeps the
3372
3894
  * existing token when it has not yet expired, so an unreachable refresh
3373
3895
  * endpoint never takes down a working session.
3896
+ *
3897
+ * Reports what it did, so a caller walking the pool for keep-alive can tell a
3898
+ * pass that refreshed something from one that had nothing to do. The answer
3899
+ * describes this call, not the account: an in-flight refresh another call
3900
+ * started is reported as `fresh` because this one spent no upstream call.
3374
3901
  */
3375
3902
  async ensureFresh(account, forced = false) {
3376
- if (this.client === void 0) return;
3903
+ if (this.client === void 0) return "fresh";
3377
3904
  const credential = account.credential;
3378
- if (!(forced || credential.expiresAtMs <= 0 || credential.expiresAtMs <= Date.now() + REFRESH_MARGIN_MS)) return;
3905
+ if (!(forced || credential.expiresAtMs <= 0 || credential.expiresAtMs <= Date.now() + REFRESH_MARGIN_MS)) return "fresh";
3379
3906
  const existing = this.refreshInflight.get(account.id);
3380
3907
  if (existing !== void 0) {
3381
3908
  await existing;
3382
- return;
3909
+ return "fresh";
3383
3910
  }
3384
3911
  const run = (async () => {
3385
3912
  if (credential.refreshToken === "") {
3386
- if (credential.expiresAtMs > Date.now() + 3e4) return;
3913
+ if (credential.expiresAtMs > Date.now() + 3e4) return "fresh";
3387
3914
  if (!this.noRefreshWarned.has(account.id)) {
3388
3915
  this.noRefreshWarned.add(account.id);
3389
3916
  this.logger?.warn(`${LOG_PREFIX}: ${account.label} token expired with no refresh token; sign in again`);
3390
3917
  }
3391
- return;
3918
+ return "noToken";
3392
3919
  }
3393
3920
  try {
3394
3921
  const outcome = await this.client.refreshToken(credential);
3395
- if (account.credential !== credential) return;
3922
+ if (account.credential !== credential) return "fresh";
3396
3923
  account.credential = {
3397
3924
  ...credential,
3398
3925
  accessToken: outcome.accessToken,
3399
3926
  ...outcome.refreshToken === void 0 ? {} : { refreshToken: outcome.refreshToken },
3400
- expiresAtMs: refreshExpiryMs(outcome.expiresInSec),
3927
+ expiresAtMs: tokenExpiryMs(outcome.expiresInSec),
3401
3928
  ...outcome.domain === void 0 || outcome.domain === "" ? {} : { domain: outcome.domain },
3402
3929
  lastRefreshAtMs: Date.now()
3403
3930
  };
3404
3931
  this.noRefreshWarned.delete(account.id);
3405
3932
  this.logger?.info?.(`${LOG_PREFIX}: refreshed token for ${account.label}`);
3933
+ await this.archiveCredentials([account.credential]);
3934
+ return "refreshed";
3406
3935
  } catch (error) {
3407
3936
  if (credential.expiresAtMs > Date.now() + 3e4) this.logger?.warn?.(`${LOG_PREFIX}: token refresh failed but token still valid for ${account.label}`, error);
3408
3937
  else this.logger?.error?.(`${LOG_PREFIX}: token refresh failed and token expired for ${account.label}`, error);
3938
+ return "failed";
3409
3939
  }
3410
3940
  })();
3411
3941
  this.refreshInflight.set(account.id, run);
3412
3942
  try {
3413
- await run;
3943
+ return await run;
3414
3944
  } finally {
3415
3945
  this.refreshInflight.delete(account.id);
3416
3946
  }
@@ -3434,7 +3964,16 @@ var WorkBuddyAccountPool = class {
3434
3964
  if (account === void 0) return;
3435
3965
  account.rateLimitHits += 1;
3436
3966
  const now = Date.now();
3437
- const until = resetAtMs !== void 0 && resetAtMs > now ? Math.min(resetAtMs, now + (hold ? POOL_HOLD_CAP_MS : PENALIZE_CAP_MS)) : now + this.cooldownMs;
3967
+ const stated = resetAtMs !== void 0 && resetAtMs > now;
3968
+ if (hold === false && !stated) {
3969
+ account.rateLimitStreak = now - (account.rateLimitStreakAtMs ?? 0) > RATE_LIMIT_STREAK_WINDOW_MS ? 1 : (account.rateLimitStreak ?? 0) + 1;
3970
+ account.rateLimitStreakAtMs = now;
3971
+ }
3972
+ const holdReason = hold === false ? void 0 : hold === true ? "spent" : hold;
3973
+ const cap = holdReason !== void 0 ? POOL_HOLD_CAP_MS : PENALIZE_CAP_MS;
3974
+ const streak = Math.min(Math.max((account.rateLimitStreak ?? 1) - 1, 0), RATE_LIMIT_STREAK_STEPS);
3975
+ const backoff = Math.min(this.cooldownMs * 2 ** streak, Math.max(this.cooldownMs, RATE_LIMIT_STREAK_CAP));
3976
+ const until = stated ? Math.min(resetAtMs, now + cap) : holdReason !== void 0 ? now + cap : now + backoff;
3438
3977
  if (modelId !== void 0 && modelId !== "") {
3439
3978
  pruneModelCooldowns(account, now);
3440
3979
  account.modelCooldowns[modelId] = Math.max(account.modelCooldowns[modelId] ?? 0, until);
@@ -3442,7 +3981,17 @@ var WorkBuddyAccountPool = class {
3442
3981
  return;
3443
3982
  }
3444
3983
  account.cooldownUntilMs = Math.max(account.cooldownUntilMs, until);
3445
- if (hold) this.heldIds.add(accountId);
3984
+ if (holdReason !== void 0) {
3985
+ const prior = this.heldIds.get(accountId);
3986
+ const carried = prior !== void 0 && prior.until > now && prior.reason === "session" ? prior : void 0;
3987
+ const reason = carried?.reason ?? holdReason;
3988
+ const heldSignIns = carried !== void 0 ? carried.heldSignIns : (this.signInTokens.get(accountId) ?? []).map((entry) => entry.accessToken);
3989
+ this.heldIds.set(accountId, {
3990
+ reason,
3991
+ until: Math.max(until, carried?.until ?? 0),
3992
+ heldSignIns
3993
+ });
3994
+ }
3446
3995
  this.logger?.warn(`${LOG_PREFIX}: account ${account.label} rate-limited; cooling until ${new Date(until).toISOString()}`);
3447
3996
  }
3448
3997
  /** Clear all cooldowns (account-wide and per-model), e.g. from a reset command. */
@@ -3451,8 +4000,11 @@ var WorkBuddyAccountPool = class {
3451
4000
  account.cooldownUntilMs = 0;
3452
4001
  account.modelCooldowns = {};
3453
4002
  account.rateLimitHits = 0;
4003
+ account.rateLimitStreak = 0;
4004
+ account.rateLimitStreakAtMs = 0;
3454
4005
  }
3455
4006
  this.heldIds.clear();
4007
+ this.refusedSignIns.clear();
3456
4008
  }
3457
4009
  /** Diagnostics snapshot. Account-wide cooling count (per-model cooling excluded:
3458
4010
  * the account as a whole stays usable when only one model is limited). */
@@ -3573,7 +4125,8 @@ var WorkBuddyCatalog = class {
3573
4125
  const enabled = this.selection.enabledModelIds;
3574
4126
  const allow = enabled === void 0 ? void 0 : new Set(enabled);
3575
4127
  const overrides = this.selection.overrides ?? {};
3576
- return this.models.filter((model) => allow === void 0 || allow.has(model.id)).map((model) => applyOverride(model, overrides[model.id]));
4128
+ const bounded = this.live;
4129
+ return this.models.filter((model) => allow === void 0 || allow.has(model.id)).map((model) => applyOverride(model, overrides[model.id], bounded));
3577
4130
  }
3578
4131
  /**
3579
4132
  * Replace the catalog with the upstream's own list.
@@ -3598,8 +4151,18 @@ var WorkBuddyCatalog = class {
3598
4151
  *
3599
4152
  * A non-positive window or ceiling is ignored rather than stored: the host
3600
4153
  * rejects a zero value, so writing one would drop the row's number entirely.
3601
- */
3602
- function applyOverride(model, override) {
4154
+ *
4155
+ * `bounded` is the catalog's own provenance: when the roster in force came from
4156
+ * the upstream, an override may lower a limit but never raise it above what the
4157
+ * vendor advertises. The host trusts the declared figure to size its context
4158
+ * budget and its compaction threshold, so a window larger than the model really
4159
+ * accepts made the host believe it had room the upstream does not have, and the
4160
+ * reply was truncated or compacted well before the declared window was full.
4161
+ * When the static fallback is still standing the figures are this plugin's own
4162
+ * guess, and clamping to them would overwrite a correct saved value with a
4163
+ * smaller invented one.
4164
+ */
4165
+ function applyOverride(model, override, bounded = false) {
3603
4166
  const next = { ...model };
3604
4167
  if (override === void 0) return next;
3605
4168
  if (override.alias !== void 0) {
@@ -3607,8 +4170,8 @@ function applyOverride(model, override) {
3607
4170
  if (alias === "") delete next.alias;
3608
4171
  else next.alias = alias;
3609
4172
  }
3610
- if (override.contextWindow !== void 0 && override.contextWindow > 0) next.contextWindow = override.contextWindow;
3611
- if (override.maxOutputTokens !== void 0 && override.maxOutputTokens > 0) next.maxOutputTokens = override.maxOutputTokens;
4173
+ if (override.contextWindow !== void 0 && override.contextWindow > 0) next.contextWindow = bounded ? Math.min(override.contextWindow, model.contextWindow) : override.contextWindow;
4174
+ if (override.maxOutputTokens !== void 0 && override.maxOutputTokens > 0) next.maxOutputTokens = bounded ? Math.min(override.maxOutputTokens, model.maxOutputTokens) : override.maxOutputTokens;
3612
4175
  if (override.supportsImages !== void 0) next.supportsImages = override.supportsImages;
3613
4176
  if (override.thinkingLevels !== void 0 && override.thinkingLevels.length > 0) next.supportedEfforts = override.thinkingLevels;
3614
4177
  if (override.defaultThinkingLevel !== void 0) next.defaultThinkingLevel = override.defaultThinkingLevel;
@@ -3839,6 +4402,63 @@ function conversationKeyOf(raw) {
3839
4402
  return;
3840
4403
  }
3841
4404
  }
4405
+ /**
4406
+ * The effort to put back on a request that carries none.
4407
+ *
4408
+ * Some providers treat the field as mandatory and reject the whole request
4409
+ * without it (`glm-5.1` answers HTTP 400 / 11133 "the request parameters were
4410
+ * rejected by the model provider", although the same request with `off` or any
4411
+ * rung of its ladder is served). The model's own declared default is what a
4412
+ * client that expresses no preference should get.
4413
+ *
4414
+ * A default outside the model's own ladder is not sent: answering the refusal
4415
+ * with a level the upstream also refuses would spend a second call to produce
4416
+ * the same error.
4417
+ */
4418
+ function declaredEffortOf(catalog, modelId) {
4419
+ const model = rosterFor(catalog).find((entry) => entry.id === modelId);
4420
+ const effort = model?.defaultThinkingLevel;
4421
+ if (effort === void 0 || effort === "") return void 0;
4422
+ const supported = model?.supportedEfforts;
4423
+ if (supported !== void 0 && supported.length > 0 && !supported.includes(effort)) return void 0;
4424
+ return effort;
4425
+ }
4426
+ /**
4427
+ * The roster a request may target: the user's selection, else the whole catalog.
4428
+ *
4429
+ * A switch that turned every model off leaves `visible()` empty while the models
4430
+ * are still callable, so the full roster is the fallback. Read through `typeof`
4431
+ * rather than calling directly: this runs inside a live request, and a catalog
4432
+ * object that cannot answer must not turn a chat completion into a 500.
4433
+ */
4434
+ function rosterFor(catalog) {
4435
+ const visible = typeof catalog.visible === "function" ? catalog.visible() : [];
4436
+ if (visible.length > 0) return visible;
4437
+ return typeof catalog.current === "function" ? catalog.current() : [];
4438
+ }
4439
+ /** The same body with `reasoning_effort` filled in, when it names no effort yet. */
4440
+ function withReasoningEffort(prepared, effort) {
4441
+ let body;
4442
+ try {
4443
+ body = JSON.parse(prepared);
4444
+ } catch {
4445
+ return;
4446
+ }
4447
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
4448
+ const request = body;
4449
+ const named = request["reasoning_effort"];
4450
+ if (typeof named === "string" && named !== "") return void 0;
4451
+ request["reasoning_effort"] = effort;
4452
+ return JSON.stringify(request);
4453
+ }
4454
+ /**
4455
+ * The upstream's code for "the request parameters were rejected by the model
4456
+ * provider": the refusal `glm-5.1` answers a request that carries no effort
4457
+ * with. It is a general invalid-parameter code, not an effort-specific one, so
4458
+ * the retry it triggers is gated on the request having named no effort at all -
4459
+ * that is the one parameter this plugin can tell is missing.
4460
+ */
4461
+ const PARAMETER_REJECTION = /"code"\s*:\s*"?11133\b/;
3842
4462
  /** True when an upstream failure body means the request overran the model's
3843
4463
  * context window (OpenAI `context_length_exceeded`, WorkBuddy code 11115 /
3844
4464
  * "input length too long"). Surfaced as a friendly hint, never auto-truncated. */
@@ -3874,6 +4494,42 @@ function resetFromRetryAfter(seconds) {
3874
4494
  if (seconds === void 0) return void 0;
3875
4495
  return Date.now() + seconds * 1e3;
3876
4496
  }
4497
+ /**
4498
+ * The answer for a gateway whose every account is present but none is usable.
4499
+ *
4500
+ * The status follows the reason, not the timestamps. A `session` hold also
4501
+ * writes a cooldown, so answering 429 whenever every reset sat in the future
4502
+ * told the user to wait out a rate limit when the remedy was to sign in again,
4503
+ * and put every other remedy below it out of reach.
4504
+ *
4505
+ * The remedy is the message: every reason here needs a different one, so the
4506
+ * answer names the reason that applies rather than sending the user to a
4507
+ * setting that was never the problem.
4508
+ *
4509
+ * A deadline travels with any answer that contains a rate-limited account, not
4510
+ * only with the 429: the host keeps `Retry-After` on a 5xx too, and a mixed pool is
4511
+ * the one case where waiting is part of the remedy for a request that will
4512
+ * otherwise succeed a minute later. Each host then clamps that wait to its own
4513
+ * retry budget, so a long deadline shortens rather than being ignored.
4514
+ */
4515
+ function unavailableAnswer(pool, live, now, modelId) {
4516
+ const reasons = live.map((account) => pool.unavailableReason(account.id, now, modelId));
4517
+ const only = new Set(reasons).size === 1 ? reasons[0] : null;
4518
+ const limited = live.filter((_, index) => reasons[index] === "rate-limited");
4519
+ const retryAfterSeconds = limited.length === 0 ? void 0 : boundedRetryAfterSeconds(Math.ceil((Math.min(...limited.map((account) => Math.max(account.cooldownUntilMs, account.modelCooldowns[modelId] ?? 0))) - now) / 1e3));
4520
+ if (only === "rate-limited") return {
4521
+ status: 429,
4522
+ code: "soft_rate",
4523
+ detail: `every account is rate-limited for model ${modelId}`,
4524
+ retryAfterSeconds
4525
+ };
4526
+ return {
4527
+ status: 503,
4528
+ code: "accounts_unavailable",
4529
+ detail: only === "sign-in expired" ? "every WorkBuddy sign-in for this gateway has expired; sign in again in the desktop app" : only === "sign-in refused" ? "every WorkBuddy sign-in was refused by the upstream; sign in again in the desktop app" : only === "on hold" ? `every WorkBuddy account is out of credits or otherwise on hold for model ${modelId}` : only === "under its credit reserve" ? "no account is available within its configured credit reserve" : `no WorkBuddy account is available for model ${modelId}`,
4530
+ retryAfterSeconds
4531
+ };
4532
+ }
3877
4533
  function createWorkBuddyShim(options) {
3878
4534
  const { pool, client, catalog } = options;
3879
4535
  const region = options.region;
@@ -3948,6 +4604,10 @@ function createWorkBuddyShim(options) {
3948
4604
  const tried = [];
3949
4605
  let last;
3950
4606
  let exhaustedByRateLimit = false;
4607
+ const effortFallback = (() => {
4608
+ const effort = declaredEffortOf(catalog, modelId);
4609
+ return effort === void 0 ? void 0 : withReasoningEffort(prepared, effort);
4610
+ })();
3951
4611
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
3952
4612
  if (controller.signal.aborted) return;
3953
4613
  const account = await pool.acquire(modelId, region, conversationKey);
@@ -3967,11 +4627,10 @@ function createWorkBuddyShim(options) {
3967
4627
  }
3968
4628
  if (regionAccounts.length > 0) {
3969
4629
  const now = Date.now();
3970
- const resets = regionAccounts.filter((account) => !pool.isDisabled(account.id)).map((account) => Math.max(account.cooldownUntilMs, account.modelCooldowns[modelId] ?? 0));
3971
- if (resets.every((until) => until > now)) {
3972
- res.setHeader("Retry-After", String(Math.max(1, Math.ceil((Math.min(...resets) - now) / 1e3))));
3973
- writeOpenAIError(res, 429, "soft_rate", `every account is rate-limited for model ${modelId}`);
3974
- } else writeOpenAIError(res, 503, "accounts_unavailable", "no account is available within its configured credit reserve");
4630
+ const live = regionAccounts.filter((account) => !pool.isDisabled(account.id));
4631
+ const answer = unavailableAnswer(pool, live, now, modelId);
4632
+ if (answer.retryAfterSeconds !== void 0) res.setHeader("Retry-After", String(answer.retryAfterSeconds));
4633
+ writeOpenAIError(res, answer.status, answer.code, answer.detail);
3975
4634
  return;
3976
4635
  }
3977
4636
  writeOpenAIError(res, 401, "not_signed_in", "no WorkBuddy credential found; sign in on the desktop app (or set WORKBUDDY_AUTH_FILE)");
@@ -3983,6 +4642,10 @@ function createWorkBuddyShim(options) {
3983
4642
  if (controller.signal.aborted) return;
3984
4643
  result = await client.chatStream(account.credential, prepared, controller.signal);
3985
4644
  }
4645
+ if (!result.ok && result.kind === "client" && effortFallback !== void 0 && PARAMETER_REJECTION.test(result.message) && !controller.signal.aborted) {
4646
+ logger?.info?.(`${LOG_PREFIX}: ${modelId} refused a request that named no effort; retrying with the model's declared default`);
4647
+ result = await client.chatStream(account.credential, effortFallback, controller.signal);
4648
+ }
3986
4649
  if (result.ok) {
3987
4650
  if (result.response.body === null) {
3988
4651
  writeOpenAIError(res, 502, "upstream_error", "workbuddy returned no stream");
@@ -3999,7 +4662,7 @@ function createWorkBuddyShim(options) {
3999
4662
  let sawDone = false;
4000
4663
  const decoder = new TextDecoder();
4001
4664
  const sse = new SseDecoder();
4002
- const body = Readable.fromWeb(result.response.body);
4665
+ const reader = relayStreamOf(result.response).getReader();
4003
4666
  /**
4004
4667
  * End the relayed stream in a shape the client can finish on.
4005
4668
  *
@@ -4019,38 +4682,50 @@ function createWorkBuddyShim(options) {
4019
4682
  message: safeMessage(error),
4020
4683
  type: "upstream_error"
4021
4684
  } })}\n\n`);
4685
+ res.write(`data: ${JSON.stringify({ choices: [{
4686
+ index: 0,
4687
+ delta: {},
4688
+ finish_reason: "stop"
4689
+ }] })}\n\n`);
4022
4690
  res.end("data: [DONE]\n\n");
4023
4691
  } catch {}
4024
4692
  };
4025
- body.on("error", (error) => {
4026
- failInBand(error);
4027
- });
4028
- body.on("end", () => {
4029
- try {
4030
- const rest = decoder.decode();
4031
- if ((rest === "" ? sse.finish() : [...sse.push(rest), ...sse.finish()]).some((event) => event.data === "[DONE]")) sawDone = true;
4032
- } catch {}
4033
- closeWithoutDone();
4034
- });
4035
4693
  /** End the response with `[DONE]` unless the upstream already sent it. */
4036
4694
  function closeWithoutDone() {
4037
4695
  if (sawDone || !res.writable) return;
4038
4696
  logger?.warn?.(LOG_PREFIX + ": upstream stream ended without [DONE]");
4039
4697
  res.end("data: [DONE]\n\n");
4040
4698
  }
4041
- body.pipe(res);
4042
- body.on("data", (chunk) => {
4699
+ return await (async () => {
4043
4700
  try {
4044
- if (!sse.push(decoder.decode(chunk, { stream: true })).some((event) => event.data === "[DONE]")) return;
4045
- sawDone = true;
4046
- body.unpipe(res);
4047
- res.end();
4048
- body.destroy();
4701
+ for (;;) {
4702
+ const { done, value } = await reader.read();
4703
+ if (done) break;
4704
+ if (!res.writable) return;
4705
+ res.write(value);
4706
+ try {
4707
+ const decoded = decoder.decode(value, { stream: true });
4708
+ if (sse.push(decoded).some((event) => event.data === "[DONE]")) {
4709
+ sawDone = true;
4710
+ if (res.writable) res.end();
4711
+ await reader.cancel().catch(() => {});
4712
+ return;
4713
+ }
4714
+ } catch {}
4715
+ }
4716
+ if (!sawDone) try {
4717
+ const rest = decoder.decode();
4718
+ if ((rest === "" ? sse.finish() : [...sse.push(rest), ...sse.finish()]).some((event) => event.data === "[DONE]")) sawDone = true;
4719
+ } catch {}
4720
+ closeWithoutDone();
4049
4721
  } catch (error) {
4050
- body.destroy(error instanceof Error ? error : new Error(String(error)));
4722
+ failInBand(error);
4723
+ } finally {
4724
+ try {
4725
+ reader.releaseLock();
4726
+ } catch {}
4051
4727
  }
4052
- });
4053
- return;
4728
+ })();
4054
4729
  }
4055
4730
  last = {
4056
4731
  kind: result.kind,
@@ -4088,7 +4763,7 @@ function createWorkBuddyShim(options) {
4088
4763
  const bodyReset = parseRateLimitReset(result.message);
4089
4764
  const resetAtMs = bodyReset !== void 0 && bodyReset > Date.now() ? bodyReset : resetFromRetryAfter(result.retryAfter);
4090
4765
  pool.penalize(account.id, resetAtMs, modelId);
4091
- } else if (result.kind === "hard_credit" || result.kind === "session_dead") pool.penalize(account.id, spentAccountHoldUntil(), void 0, true);
4766
+ } else if (result.kind === "hard_credit" || result.kind === "session_dead") pool.penalize(account.id, spentAccountHoldUntil(), void 0, result.kind === "hard_credit" ? "spent" : "session");
4092
4767
  else pool.penalize(account.id);
4093
4768
  logger?.warn(`${LOG_PREFIX}: ${account.label} ${result.kind} on ${modelId} (attempt ${attempt + 1}/${maxAttempts}); rotating`);
4094
4769
  }
@@ -4100,6 +4775,11 @@ function createWorkBuddyShim(options) {
4100
4775
  writeOpenAIError(res, 400, "context_length_exceeded", `${`the conversation exceeds ${modelId}'s context window`}. Shorten the conversation, start a new chat, or pick a model with a larger window (e.g. hy4-preview).`);
4101
4776
  return;
4102
4777
  }
4778
+ const unapproved = unapprovedChannelRefusal(last.message);
4779
+ if (unapproved !== void 0) {
4780
+ writeOpenAIError(res, 400, "upstream_channel_check", unapproved);
4781
+ return;
4782
+ }
4103
4783
  writeOpenAIError(res, KIND_STATUS[last.kind], last.kind, `workbuddy upstream ${last.kind} (http ${last.status}) after ${tried.length} account(s) [${tried.join(" → ")}]: ${last.message.slice(0, 400)}`);
4104
4784
  }
4105
4785
  return {
@@ -4109,79 +4789,74 @@ function createWorkBuddyShim(options) {
4109
4789
  close: server.close
4110
4790
  };
4111
4791
  }
4112
- //#endregion
4113
- //#region src/checkin-time.ts
4114
4792
  /**
4115
- * When the daily check-in is due, decided in one time zone.
4116
- *
4117
- * The reward windows are defined in Beijing time, so an hour has to mean the
4118
- * same instant on every machine: reading the host's local hour would make "9
4119
- * o'clock" slip by a day on a laptop set to another zone. Everything here is a
4120
- * pure function of its arguments, which is what lets a check drive the whole
4121
- * decision - the configured hours, the slot id, what is due right now - without
4122
- * a clock to fake or a settings file to write.
4123
- *
4124
- * The two host entries carried their own copy of this, and they had already
4125
- * drifted: one capped the configured hours and the other did not. The cap is
4126
- * defensive rather than load-bearing - the filter below already leaves at most
4127
- * 24 distinct values in 0..23 - but two copies of a rule is two chances to
4128
- * disagree about it, so there is one copy now.
4129
- *
4130
- * @module dsh-wtq-pool/checkin-time
4793
+ * Matched case-insensitively: the host's check is, and a lowercase spelling in a
4794
+ * user message tripped it just the same when probed.
4131
4795
  */
4132
- /** The zone the daily check-in hours are read in. */
4133
- const CHECKIN_TIME_ZONE = "Asia/Shanghai";
4134
- /** Collected at 09:00 local campaign time unless the user says otherwise. */
4135
- const DEFAULT_CHECKIN_HOURS = [9];
4136
- /** How often the timer looks for a due slot. A minute is far below one hour. */
4137
- const CHECKIN_POLL_MS = 6e4;
4138
- /** Calendar day and hour of `date` in the check-in zone, as zero-padded strings. */
4139
- function zonedDayHour(date) {
4140
- const parts = new Intl.DateTimeFormat("en-CA", {
4141
- timeZone: CHECKIN_TIME_ZONE,
4142
- year: "numeric",
4143
- month: "2-digit",
4144
- day: "2-digit",
4145
- hour: "2-digit",
4146
- hourCycle: "h23"
4147
- }).formatToParts(date);
4148
- const pick = (type) => {
4149
- const found = parts.find((part) => part.type === type);
4150
- return found === void 0 ? "00" : found.value;
4151
- };
4152
- return {
4153
- day: pick("year") + "-" + pick("month") + "-" + pick("day"),
4154
- hour: Number(pick("hour"))
4155
- };
4156
- }
4796
+ const CLIENT_NAME = /DeepSeek Harness/gi;
4157
4797
  /**
4158
- * Whole hours only, in order. Anything unreadable is dropped rather than
4159
- * guessed at, and an empty list falls back to the default hour: a switch that
4160
- * is on but never fires would be worse than one that picks a sane time.
4798
+ * Replace the client name in every message's text, leaving everything else be.
4799
+ *
4800
+ * Only text can carry it: `tool_calls`, `tool_call_id`, tool names and ids are
4801
+ * the client's own vocabulary for the call it is making, and rewriting those
4802
+ * would break the pairing.
4161
4803
  */
4162
- function normaliseCheckinHours(raw) {
4163
- const hours = [...new Set(raw.filter((value) => typeof value === "number" || typeof value === "string" && value.trim() !== "").map((value) => Math.floor(Number(value))))].filter((hour) => Number.isInteger(hour) && hour >= 0 && hour <= 23).sort((a, b) => a - b);
4164
- return hours.length === 0 ? [...DEFAULT_CHECKIN_HOURS] : hours;
4165
- }
4166
- /** A slot's id: `YYYY-MM-DDTHH` in the check-in zone. */
4167
- function checkinSlotId(day, hour) {
4168
- return day + "T" + String(hour).padStart(2, "0");
4804
+ function renameClientInMessages(messages, replacement) {
4805
+ const rename = (text) => text.replace(CLIENT_NAME, replacement);
4806
+ const inContent = (content) => {
4807
+ if (typeof content === "string") return rename(content);
4808
+ if (!Array.isArray(content)) return content;
4809
+ return content.map((part) => {
4810
+ if (typeof part === "string") return rename(part);
4811
+ if (typeof part !== "object" || part === null || Array.isArray(part)) return part;
4812
+ const record = part;
4813
+ if (typeof record["text"] !== "string") return part;
4814
+ return {
4815
+ ...record,
4816
+ text: rename(record["text"])
4817
+ };
4818
+ });
4819
+ };
4820
+ return messages.map((message) => {
4821
+ if (typeof message !== "object" || message === null || Array.isArray(message)) return message;
4822
+ const record = message;
4823
+ if (!("content" in record)) return message;
4824
+ const content = inContent(record["content"]);
4825
+ return content === record["content"] ? message : {
4826
+ ...record,
4827
+ content
4828
+ };
4829
+ });
4169
4830
  }
4170
4831
  /**
4171
- * The slot to collect right now, or undefined when nothing is due.
4832
+ * Wrap `fetch` so chat requests to the domestic host carry the replacement name.
4172
4833
  *
4173
- * An hour is due once its time has passed - catch-up, deliberately: a machine
4174
- * that slept through 09:00 still collects when it wakes instead of waiting for
4175
- * tomorrow. The earliest unconsumed hour wins, so two configured hours still
4176
- * give two passes a day.
4834
+ * The name is read per request, so the panel's switch takes effect on the next
4835
+ * turn; a reader that returns nothing leaves the body exactly as the host wrote
4836
+ * it. Only the chat endpoint is touched. The billing and check-in calls carry no
4837
+ * prompt, and the international host does not check for this.
4177
4838
  */
4178
- function dueCheckinSlot(now, hours, fired) {
4179
- const { day, hour } = zonedDayHour(now);
4180
- for (const candidate of [...hours].sort((a, b) => a - b)) {
4181
- if (candidate > hour) continue;
4182
- const slot = checkinSlotId(day, candidate);
4183
- if (!fired.has(slot)) return slot;
4184
- }
4839
+ function clientNameRewritingFetch(replacement, inner = globalThis.fetch) {
4840
+ const rewrite = (url, init) => {
4841
+ if (!url.includes("copilot.tencent.com") || typeof init?.body !== "string") return init;
4842
+ const name = replacement()?.trim();
4843
+ if (name === void 0 || name === "") return init;
4844
+ let parsed;
4845
+ try {
4846
+ parsed = JSON.parse(init.body);
4847
+ } catch {
4848
+ return init;
4849
+ }
4850
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return init;
4851
+ const body = parsed;
4852
+ if (!Array.isArray(body["messages"])) return init;
4853
+ body["messages"] = renameClientInMessages(body["messages"], name);
4854
+ return {
4855
+ ...init,
4856
+ body: JSON.stringify(body)
4857
+ };
4858
+ };
4859
+ return ((input, init) => inner(input, rewrite(String(input), init)));
4185
4860
  }
4186
4861
  //#endregion
4187
4862
  //#region src/promo.ts
@@ -4963,6 +5638,23 @@ const TRAE_DIRECTORY_FUNCTIONS = {
4963
5638
  };
4964
5639
  const TRAE_SOLO_CHAT_PATH = "/api/agent/v3/llm_utils_chat";
4965
5640
  const TRAE_SOLO_MODELS_PATH = "/api/ide/v1/get_detail_param";
5641
+ /**
5642
+ * The window the upstream accepts once Max mode is on.
5643
+ *
5644
+ * `context_window_tokens.dev` in the directory is the plan's default, not the
5645
+ * ceiling: it reads 200000 for models that then serve far more. Measured against
5646
+ * the live chat endpoint in Max mode, a 1005020-token prompt was answered to
5647
+ * `finish_reason: stop` on both glm-5.3-flash and deepseek-v4.1-flash, and a
5648
+ * 1350030-token prompt was refused with `4022 your prompt tokens have exceeded the
5649
+ * maximum limit`.
5650
+ *
5651
+ * A row that states a larger tier of its own keeps that figure - the directory is
5652
+ * the upstream speaking about its own model - and only a row that states none gets
5653
+ * this measured ceiling. Publishing a ceiling at all is what lets a caller use the
5654
+ * room: the gateway asks for Max mode only when the window in force is above the
5655
+ * answer's default, so a model left on its default behaves exactly as before.
5656
+ */
5657
+ const TRAE_MAX_CONTEXT_WINDOW = 1e6;
4966
5658
  const TRAE_REASONING_EFFORTS = [
4967
5659
  "minimal",
4968
5660
  "low",
@@ -5126,7 +5818,7 @@ function buildTraeHeaders(credential, identity, options = {}) {
5126
5818
  * OpenAI-compatible, so only its own fields are sent: optional Pi/OpenAI
5127
5819
  * fields (temperature, max_tokens, tool_choice, …) would fail validation.
5128
5820
  */
5129
- function prepareSoloBody(source, defaultModel = "glm-5.2", functionName, capability) {
5821
+ function prepareSoloBody(source, defaultModel = "glm-5.2", functionName, capability, maxMode = false) {
5130
5822
  const input = JSON.parse(source);
5131
5823
  const model = typeof input["model"] === "string" && input["model"].trim() !== "" ? input["model"].trim() : defaultModel;
5132
5824
  const wireEffort = typeof input["reasoning_effort"] === "string" ? traeWireEffort(input["reasoning_effort"], capability) : void 0;
@@ -5137,7 +5829,8 @@ function prepareSoloBody(source, defaultModel = "glm-5.2", functionName, capabil
5137
5829
  function: functionName ?? TRAE_SOLO_FUNCTION,
5138
5830
  stream: true,
5139
5831
  ...Array.isArray(input["tools"]) ? { tools: input["tools"] } : {},
5140
- ...wireEffort === void 0 ? {} : { reasoning_effort: wireEffort }
5832
+ ...wireEffort === void 0 ? {} : { reasoning_effort: wireEffort },
5833
+ ...maxMode ? { extra_info: { v2_max_mode_enabled: true } } : {}
5141
5834
  };
5142
5835
  if (Array.isArray(body["messages"])) for (const raw of body["messages"]) {
5143
5836
  if (typeof raw !== "object" || raw === null) continue;
@@ -5204,10 +5897,95 @@ function wireCreditMultiplier(config) {
5204
5897
  if (typeof data !== "object" || data === null) return void 0;
5205
5898
  return finitePositive(data["rate"]);
5206
5899
  }
5900
+ /** The widest window one answer can serve, Max tier included. */
5901
+ function variantReach(variant) {
5902
+ return Math.max(variant.contextWindow ?? 0, variant.maxContextWindow ?? 0);
5903
+ }
5904
+ /**
5905
+ * The answer that should serve a request for `window`.
5906
+ *
5907
+ * Candidates are answers that serve the window on their OWN default tier. An
5908
+ * answer that only reaches it with Max mode on is not a candidate at that size:
5909
+ * picking it would put a default-window request on the larger tier's terms, and
5910
+ * Max mode is billed that way. Only when nothing serves the window on its own
5911
+ * tier - which is exactly a request above every default, i.e. a real Max
5912
+ * request - do the Max-capable answers become candidates.
5913
+ *
5914
+ * Among equals the largest output budget wins: a user who keeps the default
5915
+ * window then gets the function that grants the most room to answer. Equal
5916
+ * budgets prefer the tighter ceiling, so nothing is declared wider than it
5917
+ * needs to be.
5918
+ *
5919
+ * The last resort - a window no answer can reach - is ranked the other way round.
5920
+ * There the tightest ceiling would be the answer that takes the LEAST of the
5921
+ * request, so the widest wins instead, and Max mode is asked for it: that is the
5922
+ * only combination that can serve a window the directory has since narrowed away
5923
+ * from.
5924
+ */
5925
+ function traeVariantFor(model, window) {
5926
+ const variants = model.variants ?? [];
5927
+ if (variants.length === 0) return void 0;
5928
+ const wanted = window !== void 0 && window > 0 ? window : model.contextWindow ?? 0;
5929
+ const own = variants.filter((variant) => (variant.contextWindow ?? 0) >= wanted);
5930
+ const reaching = own.length > 0 ? own : variants.filter((variant) => variantReach(variant) >= wanted);
5931
+ const exhausted = reaching.length === 0;
5932
+ const pool = exhausted ? variants : reaching;
5933
+ let best;
5934
+ for (const variant of pool) {
5935
+ if (best === void 0) {
5936
+ best = variant;
5937
+ continue;
5938
+ }
5939
+ const out = variant.maxTokens ?? 0;
5940
+ const bestOut = best.maxTokens ?? 0;
5941
+ if (exhausted) {
5942
+ const tier = variant.contextWindow ?? 0;
5943
+ const bestTier = best.contextWindow ?? 0;
5944
+ if (tier > bestTier) best = variant;
5945
+ else if (tier === bestTier && out > bestOut) best = variant;
5946
+ continue;
5947
+ }
5948
+ if (out > bestOut) best = variant;
5949
+ else if (out === bestOut && variantReach(variant) < variantReach(best)) best = variant;
5950
+ }
5951
+ return best;
5952
+ }
5953
+ /**
5954
+ * The published figures, derived from every answer about a model.
5955
+ *
5956
+ * The default window is the widest any function serves and the output budget
5957
+ * belongs to the answer that serves it - the same answer a request at that window
5958
+ * uses. The ceiling is the widest tier any function states, or the measured one
5959
+ * when none states a tier above the default.
5960
+ *
5961
+ * A tier equal to the widest default is not published as one: most rows state a
5962
+ * `max` that merely repeats their own window (the `__max` checkpoint naming the
5963
+ * same size), and offering that as a second tier would put a Max switch on the
5964
+ * model that changes nothing.
5965
+ */
5966
+ function figuresFrom(variants) {
5967
+ const windows = variants.map((v) => v.contextWindow ?? 0);
5968
+ const defaultWindow = Math.max(0, ...windows);
5969
+ const declaredCeiling = Math.max(0, ...variants.map(variantReach));
5970
+ const ceiling = defaultWindow <= 0 ? declaredCeiling : declaredCeiling > defaultWindow ? declaredCeiling : TRAE_MAX_CONTEXT_WINDOW;
5971
+ const serving = traeVariantFor({
5972
+ id: "",
5973
+ name: "",
5974
+ variants
5975
+ }, defaultWindow);
5976
+ return {
5977
+ contextWindow: defaultWindow > 0 ? defaultWindow : void 0,
5978
+ maxContextWindow: ceiling > defaultWindow ? ceiling : void 0,
5979
+ maxTokens: serving?.maxTokens,
5980
+ function: serving?.function
5981
+ };
5982
+ }
5207
5983
  /**
5208
- * Merge one directory function's config list into the shared catalogue.
5209
- * First function to list a `config_name` owns it, so precedence follows
5210
- * `TRAE_DIRECTORY_FUNCTIONS` order. Pure: no network, no token logging.
5984
+ * Merge one directory answer into the roster.
5985
+ *
5986
+ * Exported because the merge rule is the whole point: the answers disagree, and
5987
+ * which one is kept used to depend on the order the gateway happened to answer in.
5988
+ * Every answer is kept as a variant, so nothing one function states is lost.
5211
5989
  */
5212
5990
  function collectTraeSoloModels(list, directoryFunction, byId) {
5213
5991
  for (const raw of list) {
@@ -5218,7 +5996,9 @@ function collectTraeSoloModels(list, directoryFunction, byId) {
5218
5996
  const display = typeof config["display_config"] === "object" && config["display_config"] !== null ? config["display_config"] : {};
5219
5997
  const details = Array.isArray(config["model_detail_list"]) ? config["model_detail_list"] : [];
5220
5998
  const detail = typeof details[0] === "object" && details[0] !== null ? details[0] : {};
5221
- const contextWindow = finitePositive((typeof config["context_window_tokens"] === "object" && config["context_window_tokens"] !== null ? config["context_window_tokens"] : {})["dev"]) ?? finitePositive(detail["prompt_max_tokens"]);
5999
+ const contextTokens = typeof config["context_window_tokens"] === "object" && config["context_window_tokens"] !== null ? config["context_window_tokens"] : {};
6000
+ const contextWindow = finitePositive(contextTokens["dev"]) ?? finitePositive(detail["prompt_max_tokens"]);
6001
+ const maxContextWindow = finitePositive(contextTokens["max"]);
5222
6002
  const maxTokens = finitePositive(detail["max_tokens"]);
5223
6003
  const reasoning = parseTraeReasoningCapability({
5224
6004
  ...config,
@@ -5226,18 +6006,73 @@ function collectTraeSoloModels(list, directoryFunction, byId) {
5226
6006
  });
5227
6007
  const creditMultiplier = wireCreditMultiplier(config);
5228
6008
  const multimodal = display["multimodal"];
5229
- if (byId.has(id)) continue;
6009
+ const variant = {
6010
+ function: directoryFunction,
6011
+ ...contextWindow === void 0 ? {} : { contextWindow },
6012
+ ...maxContextWindow === void 0 ? {} : { maxContextWindow },
6013
+ ...maxTokens === void 0 ? {} : { maxTokens }
6014
+ };
6015
+ const existing = byId.get(id);
6016
+ const variants = [...existing?.variants ?? []];
6017
+ const known = variants.findIndex((entry) => entry.function === directoryFunction);
6018
+ const previous = known === -1 ? void 0 : variants[known];
6019
+ if (previous === void 0) variants.push(variant);
6020
+ else if (variantReach(variant) > variantReach(previous) || (variant.maxTokens ?? 0) > (previous.maxTokens ?? 0)) variants[known] = variant;
6021
+ if (existing !== void 0) {
6022
+ byId.set(id, {
6023
+ ...existing,
6024
+ ...figuresFrom(variants),
6025
+ variants
6026
+ });
6027
+ continue;
6028
+ }
5230
6029
  byId.set(id, {
5231
6030
  id,
5232
6031
  name: typeof display["display_name"] === "string" && display["display_name"] !== "" ? display["display_name"] : id,
5233
- ...contextWindow === void 0 ? {} : { contextWindow },
5234
- ...maxTokens === void 0 ? {} : { maxTokens },
5235
6032
  ...reasoning === void 0 ? {} : { reasoning },
5236
6033
  ...creditMultiplier === void 0 ? {} : { creditMultiplier },
5237
6034
  ...typeof multimodal === "boolean" ? { supportsImages: multimodal } : {},
5238
- function: directoryFunction
6035
+ ...figuresFrom(variants),
6036
+ variants
6037
+ });
6038
+ }
6039
+ }
6040
+ /**
6041
+ * Fold a partial directory read into the roster already held.
6042
+ *
6043
+ * A function that failed lists models the answer does not mention, so two facts
6044
+ * have to be kept apart: an id only the earlier read knows stays callable, and
6045
+ * an id both reads know keeps the variants of both. The failed function may be
6046
+ * the only one that stated a Max tier or a wider window, and dropping its answer
6047
+ * would re-publish the model at the smaller figures - the same silent narrowing
6048
+ * the variant system exists to prevent.
6049
+ *
6050
+ * A complete read is never merged: it is the directory's current word, and a
6051
+ * model it no longer lists is one that is gone.
6052
+ *
6053
+ * A variant carried over from a failed function is still chosen by
6054
+ * `traeVariantFor` when it is the one that reaches the window, and the request is
6055
+ * then sent to a function that may have stopped answering entirely. That is the
6056
+ * right call while the failure was a timeout - the chat path is a different
6057
+ * endpoint - and the gateway retries once with another answer when the chosen one
6058
+ * turns out to be gone.
6059
+ */
6060
+ function mergeTraeDirectory(previous, next) {
6061
+ const merged = new Map(next.map((model) => [model.id, model]));
6062
+ for (const model of next) {
6063
+ const before = previous.find((entry) => entry.id === model.id);
6064
+ if (before === void 0) continue;
6065
+ const variants = [...model.variants ?? []];
6066
+ for (const variant of before.variants ?? []) if (!variants.some((entry) => entry.function === variant.function)) variants.push(variant);
6067
+ if (variants.length === (model.variants ?? []).length) continue;
6068
+ merged.set(model.id, {
6069
+ ...model,
6070
+ ...figuresFrom(variants),
6071
+ variants
5239
6072
  });
5240
6073
  }
6074
+ for (const model of previous) if (!merged.has(model.id)) merged.set(model.id, model);
6075
+ return [...merged.values()];
5241
6076
  }
5242
6077
  /** Daily check-in endpoints on the CN pay host (`REGION_GATEWAYS.cn.pay`). */
5243
6078
  const TRAE_CHECKIN_STATUS_PATH = "/trae/api/v2/ug/checkin_credits/status";
@@ -5398,6 +6233,12 @@ var TraeSoloUpstreamClient = class {
5398
6233
  * Read the callable roster for this credential's region. Every function in
5399
6234
  * `TRAE_DIRECTORY_FUNCTIONS` is asked in order and their answers unioned;
5400
6235
  * one function failing never hides the others' rosters.
6236
+ *
6237
+ * The answer says whether it is `partial`: a function that failed is one that
6238
+ * would have listed models, and the ones only it lists are missing from what
6239
+ * came back. That has to travel with the read, because the roster replaces the
6240
+ * cached one - and a roster that lost models makes the gateway refuse them as
6241
+ * `not_found`, for as long as the read stays fresh.
5401
6242
  */
5402
6243
  async fetchModels(signal) {
5403
6244
  const [credential, identity] = await Promise.all([this.options.credential(), this.options.identity()]);
@@ -5409,8 +6250,9 @@ var TraeSoloUpstreamClient = class {
5409
6250
  };
5410
6251
  const byId = /* @__PURE__ */ new Map();
5411
6252
  const failures = [];
5412
- for (const directoryFunction of TRAE_DIRECTORY_FUNCTIONS[region]) {
5413
- let list;
6253
+ /** The functions whose answer this read could not use, by name only. */
6254
+ const failedFunctions = [];
6255
+ const answers = await Promise.all(TRAE_DIRECTORY_FUNCTIONS[region].map(async (directoryFunction) => {
5414
6256
  try {
5415
6257
  const response = await this.fetchImpl(traeEndpoint(base, TRAE_SOLO_MODELS_PATH), {
5416
6258
  redirect: "error",
@@ -5429,12 +6271,29 @@ var TraeSoloUpstreamClient = class {
5429
6271
  });
5430
6272
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
5431
6273
  const document = await response.json();
5432
- list = Array.isArray(document["config_info_list"]) ? document["config_info_list"] : [];
6274
+ if (!Array.isArray(document["config_info_list"])) {
6275
+ const code = typeof document["code"] === "number" ? document["code"] : void 0;
6276
+ const message = typeof document["message"] === "string" ? document["message"].slice(0, 60) : "";
6277
+ throw new Error(code === void 0 ? "no config_info_list" : `code ${code}${message === "" ? "" : ": " + message}`);
6278
+ }
6279
+ return {
6280
+ directoryFunction,
6281
+ list: document["config_info_list"]
6282
+ };
5433
6283
  } catch (error) {
5434
- failures.push(`${directoryFunction}: ${String(error).slice(0, 80)}`);
6284
+ failedFunctions.push(directoryFunction);
6285
+ return {
6286
+ directoryFunction,
6287
+ failure: `${directoryFunction}: ${String(error).slice(0, 80)}`
6288
+ };
6289
+ }
6290
+ }));
6291
+ for (const answer of answers) {
6292
+ if (answer.failure !== void 0) {
6293
+ failures.push(answer.failure);
5435
6294
  continue;
5436
6295
  }
5437
- collectTraeSoloModels(list, directoryFunction, byId);
6296
+ collectTraeSoloModels(answer.list, answer.directoryFunction, byId);
5438
6297
  }
5439
6298
  const models = [...byId.values()];
5440
6299
  if (models.length === 0) throw new Error(`Trae SOLO models response contained no models (${failures.join("; ") || "empty directory"})`);
@@ -5444,7 +6303,11 @@ var TraeSoloUpstreamClient = class {
5444
6303
  const found = reasoning.get(model.id);
5445
6304
  if (found !== void 0) model.reasoning = found;
5446
6305
  }
5447
- return models;
6306
+ return {
6307
+ models,
6308
+ partial: failures.length > 0,
6309
+ failedFunctions
6310
+ };
5448
6311
  }
5449
6312
  /**
5450
6313
  * Reasoning tables live on the remote model directory, not on
@@ -5560,16 +6423,16 @@ var TraeSoloUpstreamClient = class {
5560
6423
  return traeCheckinStatusOf(payload);
5561
6424
  }
5562
6425
  /** Send one chat body through the credential's regional gateway. */
5563
- async chatStream(bodyJson, signal, functionName, capability, timeouts) {
6426
+ async chatStream(bodyJson, signal, functionName, capability, timeouts, maxMode) {
5564
6427
  let prepared;
5565
6428
  try {
5566
- prepared = prepareSoloBody(bodyJson, void 0, functionName, capability);
5567
- } catch {
6429
+ prepared = prepareSoloBody(bodyJson, void 0, functionName, capability, maxMode === true);
6430
+ } catch (error) {
5568
6431
  return {
5569
6432
  ok: false,
5570
6433
  status: 400,
5571
6434
  kind: "client",
5572
- message: "invalid JSON request"
6435
+ message: error instanceof Error && error.message !== "" ? error.message : "invalid JSON request"
5573
6436
  };
5574
6437
  }
5575
6438
  let credential;
@@ -5935,7 +6798,7 @@ function bridgeTraeStream(source, model, options = {}) {
5935
6798
  if (decoded.type !== "done" && decoded.type !== "delta") return;
5936
6799
  if (emittedFinishReason) return;
5937
6800
  emittedFinishReason = true;
5938
- controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : decoded.finishReason || "stop"));
6801
+ controller.enqueue(chunk({}, openAIFinishReason(decoded.finishReason, sawToolCalls)));
5939
6802
  };
5940
6803
  let released = false;
5941
6804
  /**
@@ -5980,7 +6843,7 @@ function bridgeTraeStream(source, model, options = {}) {
5980
6843
  for (const event of events) consume(event, controller);
5981
6844
  if (!emittedFinishReason) {
5982
6845
  emittedFinishReason = true;
5983
- controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : "stop"));
6846
+ controller.enqueue(chunk({}, openAIFinishReason(void 0, sawToolCalls)));
5984
6847
  }
5985
6848
  controller.enqueue(encoder.encode("data: [DONE]\n\n"));
5986
6849
  controller.close();
@@ -6005,7 +6868,7 @@ function bridgeTraeStream(source, model, options = {}) {
6005
6868
  })}\n\n`));
6006
6869
  if (!emittedFinishReason) {
6007
6870
  emittedFinishReason = true;
6008
- controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : "stop"));
6871
+ controller.enqueue(chunk({}, openAIFinishReason(void 0, sawToolCalls)));
6009
6872
  }
6010
6873
  controller.enqueue(encoder.encode("data: [DONE]\n\n"));
6011
6874
  controller.close();
@@ -6126,6 +6989,17 @@ function capabilityMapOf(models) {
6126
6989
  for (const model of models) map.set(model.id, model.reasoning ?? { supported: [] });
6127
6990
  return map;
6128
6991
  }
6992
+ /**
6993
+ * Whether a failure says this model is not served by the function that was asked.
6994
+ *
6995
+ * Trae answers `4001` in its own envelope when the chosen function does not know
6996
+ * the `config_name`, which is a fact about the function rather than about the
6997
+ * request. Every other 4xx is the request's own and is passed through untouched.
6998
+ */
6999
+ function functionGone(status, kind, message) {
7000
+ if (kind === "not_found") return true;
7001
+ return status === 400 && /"code"\s*:\s*"?4001\b/.test(message);
7002
+ }
6129
7003
  function createTraeGateway(options) {
6130
7004
  const logger = options.logger;
6131
7005
  let cachedModels = [];
@@ -6167,10 +7041,10 @@ function createTraeGateway(options) {
6167
7041
  let lastError;
6168
7042
  for (const credential of candidates) try {
6169
7043
  const read = await clientFor(credential).fetchModels();
6170
- cachedModels = read;
7044
+ cachedModels = read.partial ? mergeTraeDirectory(cachedModels, read.models) : read.models;
6171
7045
  catalogAt = Date.now();
6172
7046
  catalogFailedAt = 0;
6173
- return read;
7047
+ return cachedModels;
6174
7048
  } catch (error) {
6175
7049
  lastError = error;
6176
7050
  }
@@ -6209,18 +7083,45 @@ function createTraeGateway(options) {
6209
7083
  let functions = functionMapOf(directory);
6210
7084
  if (functions.size === 0) functions = functionMapOf(cachedModels);
6211
7085
  if (functions.size === 0) {
6212
- writeOpenAIError(res, 503, "upstream_unavailable", "Trae model directory is not available yet");
7086
+ writeOpenAIError(res, 503, "upstream_unavailable", catalogErrorText !== "" ? catalogErrorText : "Trae model directory is not available yet");
6213
7087
  return;
6214
7088
  }
6215
7089
  if (!directory.some((entry) => entry.id === model) && !cachedModels.some((entry) => entry.id === model)) {
6216
7090
  writeOpenAIError(res, 404, "not_found", `model not in the Trae directory: ${model}`);
6217
7091
  return;
6218
7092
  }
6219
- let credentials;
6220
- try {
6221
- credentials = (await options.credentials("chat")).filter((credential) => credential.accessToken !== "");
6222
- } catch (error) {
6223
- writeOpenAIError(res, 503, "upstream_unavailable", String(error instanceof Error ? error.message : error));
7093
+ const published = options.publishedWindowOf?.(model);
7094
+ const entry = directory.find((row) => row.id === model) ?? cachedModels.find((row) => row.id === model);
7095
+ const serving = entry === void 0 ? void 0 : traeVariantFor(entry, published);
7096
+ /**
7097
+ * Which functions to try for this model, in order.
7098
+ *
7099
+ * The published answer leads. A partial directory read still carries the answer
7100
+ * of a function that has just failed, so the leader can be a function the
7101
+ * upstream no longer serves - and then every request for the model fails while
7102
+ * an answer that did arrive this time sits unused. The rest of the answers are
7103
+ * the fallback, one attempt each, taken only for a refusal that says this model
7104
+ * is not there.
7105
+ */
7106
+ const functionOrder = [];
7107
+ const pushFunction = (name) => {
7108
+ if (name !== void 0 && name !== "" && !functionOrder.includes(name)) functionOrder.push(name);
7109
+ };
7110
+ pushFunction(serving?.function ?? functions.get(model));
7111
+ const target = published ?? entry?.contextWindow;
7112
+ if (entry !== void 0 && target !== void 0) {
7113
+ const reach = (row) => Math.max(row.contextWindow ?? 0, row.maxContextWindow ?? 0);
7114
+ const answering = [...entry.variants ?? []].sort((a, b) => {
7115
+ const fits = (row) => reach(row) >= target ? 1 : 0;
7116
+ return fits(b) - fits(a) || reach(b) - reach(a) || (b.maxTokens ?? 0) - (a.maxTokens ?? 0);
7117
+ });
7118
+ for (const row of answering) pushFunction(row.function);
7119
+ }
7120
+ let credentials;
7121
+ try {
7122
+ credentials = (await options.credentials("chat")).filter((credential) => credential.accessToken !== "");
7123
+ } catch (error) {
7124
+ writeOpenAIError(res, 503, "upstream_unavailable", String(error instanceof Error ? error.message : error));
6224
7125
  return;
6225
7126
  }
6226
7127
  if (credentials.length === 0) {
@@ -6228,15 +7129,15 @@ function createTraeGateway(options) {
6228
7129
  return;
6229
7130
  }
6230
7131
  if (watcher.signal.aborted) return;
6231
- const capabilities = capabilityMapOf(directory);
7132
+ const capabilities = capabilityMapOf([...cachedModels, ...directory]);
6232
7133
  /**
6233
7134
  * One sign-in's attempt: the chat call plus the peek that turns a refusal
6234
7135
  * hidden in the stream into a real status. The peek is inside the attempt
6235
7136
  * because a refusal is usually a property of the sign-in (an expired login,
6236
7137
  * a subscription gate), which is what the next sign-in is for.
6237
7138
  */
6238
- const attemptOnce = async (credential) => {
6239
- const result = await clientFor(credential).chatStream(raw, watcher.signal, functions.get(model), capabilities.get(model));
7139
+ const attemptOnce = async (credential, functionName) => {
7140
+ const result = await clientFor(credential).chatStream(raw, watcher.signal, functionName, capabilities.get(model), void 0, published !== void 0 && serving !== void 0 && serving.contextWindow !== void 0 && published > serving.contextWindow);
6240
7141
  if (!result.ok) return {
6241
7142
  ok: false,
6242
7143
  status: result.status,
@@ -6297,7 +7198,13 @@ function createTraeGateway(options) {
6297
7198
  if (watcher.signal.aborted) return;
6298
7199
  const credential = credentials[index];
6299
7200
  if (credential === void 0) continue;
6300
- const attempt = await attemptOnce(credential);
7201
+ let attempt = await attemptOnce(credential, functionOrder[0]);
7202
+ for (let candidate = 1; candidate < functionOrder.length; candidate += 1) {
7203
+ if (attempt.ok) break;
7204
+ if (!functionGone(attempt.status, attempt.kind, attempt.message)) break;
7205
+ logger?.warn?.(`${LOG_PREFIX}: ${model} is refused by ${functionOrder[candidate - 1]} (http ${attempt.status}); trying ${functionOrder[candidate]}`);
7206
+ attempt = await attemptOnce(credential, functionOrder[candidate]);
7207
+ }
6301
7208
  if (attempt.ok) {
6302
7209
  opened = attempt;
6303
7210
  break;
@@ -7743,11 +8650,30 @@ function qoderContextWindowOf(record) {
7743
8650
  const sizes = Object.values(config).map(tokenCountOf).filter((value) => value !== void 0);
7744
8651
  return sizes.length === 0 ? void 0 : Math.max(...sizes);
7745
8652
  }
8653
+ /**
8654
+ * The routes Qoder lists beside its models without naming them.
8655
+ *
8656
+ * The global directory returns four entries whose display names are Qoder's own
8657
+ * codenames — Ultimate, Efficient, Sonus, Cantus — and nothing in the payload
8658
+ * marks them as different from a named model: same `source`, same `format`, same
8659
+ * `is_editable`, and one of them even carries a promotion. Offered in the picker
8660
+ * they read as four opaque names between Auto and Qwen3.8-Max. The keys are what
8661
+ * Qoder's API has returned for them across versions, so they are matched by key
8662
+ * on whichever directory lists them. The `auto` route stays: it is a model choice
8663
+ * a user recognises, and it is the row the directory marks `is_default`.
8664
+ */
8665
+ const QODER_UNNAMED_ROUTES = /* @__PURE__ */ new Set([
8666
+ "ultimate",
8667
+ "efficient",
8668
+ "smodel",
8669
+ "cmodel"
8670
+ ]);
7746
8671
  /** One directory row → one callable model, or undefined when unusable. */
7747
8672
  function qoderModelOf(entry) {
7748
8673
  if (entry === null || typeof entry !== "object") return void 0;
7749
8674
  const record = entry;
7750
8675
  if (typeof record["key"] !== "string" || record["key"].length === 0) return void 0;
8676
+ if (QODER_UNNAMED_ROUTES.has(record["key"])) return void 0;
7751
8677
  if (record["enable"] === false) return void 0;
7752
8678
  if (typeof record["display_name"] !== "string" || record["display_name"].length === 0) return void 0;
7753
8679
  const config = record["thinking_config"];
@@ -8495,7 +9421,7 @@ function bridgeQoderStream(source, model, options = {}) {
8495
9421
  if (typeof finish === "string" && finish !== "" && finish !== "null") {
8496
9422
  if (!emittedFinishReason) {
8497
9423
  emittedFinishReason = true;
8498
- controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : finish));
9424
+ controller.enqueue(chunk({}, openAIFinishReason(finish, sawToolCalls)));
8499
9425
  endSoon();
8500
9426
  }
8501
9427
  }
@@ -8588,7 +9514,7 @@ function bridgeQoderStream(source, model, options = {}) {
8588
9514
  if (!finished) {
8589
9515
  if (!emittedFinishReason) {
8590
9516
  emittedFinishReason = true;
8591
- controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : "stop"));
9517
+ controller.enqueue(chunk({}, openAIFinishReason(void 0, sawToolCalls)));
8592
9518
  }
8593
9519
  finalize();
8594
9520
  }
@@ -8613,7 +9539,7 @@ function bridgeQoderStream(source, model, options = {}) {
8613
9539
  })}\n\n`));
8614
9540
  if (!emittedFinishReason) {
8615
9541
  emittedFinishReason = true;
8616
- controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : "stop"));
9542
+ controller.enqueue(chunk({}, openAIFinishReason(void 0, sawToolCalls)));
8617
9543
  }
8618
9544
  finalize();
8619
9545
  }
@@ -9016,6 +9942,157 @@ function createQoderGateway(options) {
9016
9942
  };
9017
9943
  }
9018
9944
  //#endregion
9945
+ //#region src/login.ts
9946
+ /** The domestic gateway, which serves the domestic login page. */
9947
+ const CN_BASE = "https://copilot.tencent.com";
9948
+ /** The international gateway. */
9949
+ const GLOBAL_BASE = "https://www.workbuddy.ai";
9950
+ /** Billing origin the domestic login page is served from. */
9951
+ const CN_ORIGIN = "https://www.codebuddy.cn";
9952
+ /** The international login page is same-origin with its gateway. */
9953
+ const GLOBAL_ORIGIN = "https://www.workbuddy.ai";
9954
+ /**
9955
+ * The CLI's own user agent.
9956
+ *
9957
+ * The endpoints answer this spelling and turn the plugin's other ones away,
9958
+ * and the page it opens belongs to the same client channel — a different
9959
+ * spelling there is answered as an unknown platform.
9960
+ */
9961
+ const LOGIN_UA = "CLI/2.63.2 CodeBuddy/2.63.2";
9962
+ const REQUEST_TIMEOUT_MS = 3e4;
9963
+ /**
9964
+ * Domain stamped on a sign-in whose answer carried none.
9965
+ *
9966
+ * `regionOf` reads an empty domain as CN, so a global login that arrives
9967
+ * without one would be filed under the domestic gateway, which refuses its
9968
+ * token at the openresty layer with an HTML 401 instead of a business error.
9969
+ */
9970
+ const DEFAULT_DOMAIN = {
9971
+ cn: "www.codebuddy.cn",
9972
+ global: "www.workbuddy.ai"
9973
+ };
9974
+ function baseFor(realm) {
9975
+ return realm === "global" ? GLOBAL_BASE : CN_BASE;
9976
+ }
9977
+ function originFor(realm) {
9978
+ return realm === "global" ? GLOBAL_ORIGIN : CN_ORIGIN;
9979
+ }
9980
+ /** Browser-shaped headers; `Origin` is the one the endpoints check. */
9981
+ function loginHeaders(origin) {
9982
+ return {
9983
+ "Accept": "application/json, text/plain, */*",
9984
+ "Content-Type": "application/json",
9985
+ "Origin": origin,
9986
+ "Referer": `${origin}/`,
9987
+ "User-Agent": LOGIN_UA,
9988
+ "X-Requested-With": "XMLHttpRequest"
9989
+ };
9990
+ }
9991
+ async function callLogin(url, headers, fetchImpl, body) {
9992
+ const response = await fetchImpl(url, {
9993
+ redirect: "error",
9994
+ method: body === void 0 ? "GET" : "POST",
9995
+ headers,
9996
+ ...body === void 0 ? {} : { body },
9997
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
9998
+ });
9999
+ const text = await response.text();
10000
+ if (!response.ok) throw new Error(`workbuddy login endpoint answered ${response.status}`);
10001
+ let parsed;
10002
+ try {
10003
+ parsed = JSON.parse(text);
10004
+ } catch {
10005
+ throw new Error("workbuddy login endpoint did not answer JSON");
10006
+ }
10007
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("workbuddy login endpoint did not answer an object");
10008
+ const document = parsed;
10009
+ const data = typeof document["data"] === "object" && document["data"] !== null ? document["data"] : {};
10010
+ return {
10011
+ code: typeof document["code"] === "number" ? document["code"] : -1,
10012
+ msg: typeof document["msg"] === "string" ? document["msg"] : "",
10013
+ data
10014
+ };
10015
+ }
10016
+ function stringField(data, key) {
10017
+ const value = data[key];
10018
+ return typeof value === "string" ? value : "";
10019
+ }
10020
+ /**
10021
+ * Start a login and answer the URL to open.
10022
+ *
10023
+ * The state is the only thing that ties the browser half to this one, so the
10024
+ * caller keeps it for as long as it polls and drops it afterwards.
10025
+ */
10026
+ async function startDeviceLogin(realm, fetchImpl = fetch) {
10027
+ const envelope = await callLogin(`${baseFor(realm)}/v2/plugin/auth/state?platform=CLI`, loginHeaders(originFor(realm)), fetchImpl, "{}");
10028
+ const state = stringField(envelope.data, "state");
10029
+ const authUrl = stringField(envelope.data, "authUrl");
10030
+ if (state === "" || authUrl === "") throw new Error(`workbuddy login start gave no state or url: ${envelope.msg}`);
10031
+ return {
10032
+ state,
10033
+ authUrl
10034
+ };
10035
+ }
10036
+ /**
10037
+ * Read the account a fresh token belongs to.
10038
+ *
10039
+ * Best effort by design: the token is already good, so an identity that cannot
10040
+ * be read costs the panel a name and the archive a stable key, not the sign-in.
10041
+ */
10042
+ async function readLoginAccount(base, headers, state, accessToken, fetchImpl) {
10043
+ const empty = {
10044
+ uid: "",
10045
+ uin: "",
10046
+ enterpriseId: "",
10047
+ nickname: ""
10048
+ };
10049
+ let envelope;
10050
+ try {
10051
+ envelope = await callLogin(`${base}/v2/plugin/login/account?state=${encodeURIComponent(state)}`, {
10052
+ ...headers,
10053
+ "Authorization": `Bearer ${accessToken}`
10054
+ }, fetchImpl);
10055
+ } catch {
10056
+ return empty;
10057
+ }
10058
+ if (envelope.code !== 0) return empty;
10059
+ return {
10060
+ uid: stringField(envelope.data, "uid"),
10061
+ uin: stringField(envelope.data, "uin"),
10062
+ enterpriseId: stringField(envelope.data, "enterpriseId"),
10063
+ nickname: stringField(envelope.data, "nickname")
10064
+ };
10065
+ }
10066
+ /**
10067
+ * Poll a started login once.
10068
+ *
10069
+ * The token endpoint is the authority on whether the browser has finished: it
10070
+ * answers `code: 0` with the token bundle once it has, and a business error
10071
+ * for as long as it has not. A non-2xx or an unreadable answer throws, because
10072
+ * neither means "keep waiting".
10073
+ */
10074
+ async function pollDeviceLogin(realm, state, fetchImpl = fetch) {
10075
+ const base = baseFor(realm);
10076
+ const headers = loginHeaders(originFor(realm));
10077
+ const token = await callLogin(`${base}/v2/plugin/auth/token?state=${encodeURIComponent(state)}`, headers, fetchImpl);
10078
+ const accessToken = stringField(token.data, "accessToken");
10079
+ if (token.code !== 0 || accessToken === "") return { status: "pending" };
10080
+ const domain = stringField(token.data, "domain");
10081
+ const identity = await readLoginAccount(base, headers, state, accessToken, fetchImpl);
10082
+ const stamped = domain === "" ? DEFAULT_DOMAIN[realm] : domain;
10083
+ return {
10084
+ status: "ok",
10085
+ signIn: {
10086
+ region: regionOf(stamped),
10087
+ accessToken,
10088
+ refreshToken: stringField(token.data, "refreshToken"),
10089
+ expiresAtMs: tokenExpiryMs(typeof token.data["expiresIn"] === "number" ? token.data["expiresIn"] : void 0),
10090
+ domain: stamped,
10091
+ ...identity
10092
+ }
10093
+ };
10094
+ }
10095
+ //#endregion
9019
10096
  //#region src/source-pool.ts
9020
10097
  /**
9021
10098
  * The account pool the Trae and Qoder gateways share.
@@ -9036,11 +10113,22 @@ function createQoderGateway(options) {
9036
10113
  */
9037
10114
  /** Build the pool the Trae and Qoder gateways share, wired to the host's readers. */
9038
10115
  function createSourcePool(host) {
10116
+ /**
10117
+ * The key one account's state is stored under.
10118
+ *
10119
+ * The region belongs in it: one label can name a copy in each region (the
10120
+ * scanner keys its rows by label *and* region for exactly that reason), so a
10121
+ * key without it hands one region's hold and pack expiry to the other region's
10122
+ * account.
10123
+ */
10124
+ function accountStateKey(source, region, label) {
10125
+ return host.sourceRegionKey(source, region) + "\n" + label;
10126
+ }
9039
10127
  /** account key -> the timestamp that account's soonest one-off pack runs out at. */
9040
10128
  const sourceCreditExpiry = /* @__PURE__ */ new Map();
9041
10129
  /** Unknown expiry sorts last, so it never beats a real deadline. */
9042
- function packUrgency(source, label, now) {
9043
- const at = sourceCreditExpiry.get(source + "\n" + label);
10130
+ function packUrgency(source, region, label, now) {
10131
+ const at = sourceCreditExpiry.get(accountStateKey(source, region, label));
9044
10132
  return typeof at === "number" && at > now ? at : Infinity;
9045
10133
  }
9046
10134
  /** Where each source region's rotation stands. Advanced once per chat, never by a directory or health read. */
@@ -9050,17 +10138,18 @@ function createSourcePool(host) {
9050
10138
  * keyed the way `sourceCreditExpiry` is.
9051
10139
  */
9052
10140
  const sourceFailureHold = /* @__PURE__ */ new Map();
9053
- function noteSourceFailure(source, label, retryAfter) {
10141
+ function noteSourceFailure(source, region, label, retryAfter) {
9054
10142
  const stated = retryAfterHeader(retryAfter);
9055
10143
  const waitMs = stated === void 0 ? host.cooldownMs() : Number(stated) * 1e3;
9056
- sourceFailureHold.set(source + "\n" + label, Date.now() + waitMs);
10144
+ sourceFailureHold.set(accountStateKey(source, region, label), Date.now() + waitMs);
9057
10145
  }
9058
10146
  /** Whether one sign-in is inside the hold a failure put on it. */
9059
- function sourceFailureActive(source, label, now) {
9060
- const until = sourceFailureHold.get(source + "\n" + label);
10147
+ function sourceFailureActive(source, region, label, now) {
10148
+ const key = accountStateKey(source, region, label);
10149
+ const until = sourceFailureHold.get(key);
9061
10150
  if (until === void 0) return false;
9062
10151
  if (until <= now) {
9063
- sourceFailureHold.delete(source + "\n" + label);
10152
+ sourceFailureHold.delete(key);
9064
10153
  return false;
9065
10154
  }
9066
10155
  return true;
@@ -9092,7 +10181,7 @@ function createSourcePool(host) {
9092
10181
  const preferred = stored !== "" && credentials.some((credential) => labelOf(credential) === stored) ? stored : "";
9093
10182
  const rank = (credential) => {
9094
10183
  const expired = sourceCredentialExpired(credential, now) ? 1 : 0;
9095
- const held = expired === 0 && sourceFailureActive(source, labelOf(credential), now) ? 1 : 0;
10184
+ const held = expired === 0 && sourceFailureActive(source, region, labelOf(credential), now) ? 1 : 0;
9096
10185
  const wanted = preferred !== "" && labelOf(credential) === preferred ? 0 : 1;
9097
10186
  return expired * 4 + held * 2 + wanted;
9098
10187
  };
@@ -9100,24 +10189,31 @@ function createSourcePool(host) {
9100
10189
  if (preferred === "" && host.sourceDistribution(source) === "expiry") {
9101
10190
  const live = ordered.filter((credential) => !sourceCredentialExpired(credential, now));
9102
10191
  const rest = ordered.filter((credential) => sourceCredentialExpired(credential, now));
9103
- live.sort((left, right) => packUrgency(source, labelOf(left), now) - packUrgency(source, labelOf(right), now));
9104
- return live.concat(rest);
10192
+ const healthy = live.filter((credential) => !sourceFailureActive(source, region, labelOf(credential), now));
10193
+ const held = live.filter((credential) => sourceFailureActive(source, region, labelOf(credential), now));
10194
+ const byUrgency = (left, right) => packUrgency(source, region, labelOf(left), now) - packUrgency(source, region, labelOf(right), now);
10195
+ healthy.sort(byUrgency);
10196
+ held.sort(byUrgency);
10197
+ return healthy.concat(held, rest);
9105
10198
  }
9106
10199
  const live = ordered.filter((credential) => !sourceCredentialExpired(credential, now));
9107
10200
  if (rotate !== true || preferred !== "" || live.length < 2 || host.sourceDistribution(source) !== "round-robin") return ordered;
10201
+ const healthy = live.filter((credential) => !sourceFailureActive(source, region, labelOf(credential), now));
10202
+ const held = live.filter((credential) => sourceFailureActive(source, region, labelOf(credential), now));
10203
+ if (healthy.length < 2) return ordered;
9108
10204
  const key = host.sourceRegionKey(source, region);
9109
- const step = (sourceRotation.get(key) ?? 0) % live.length;
10205
+ const step = (sourceRotation.get(key) ?? 0) % healthy.length;
9110
10206
  sourceRotation.set(key, step + 1);
9111
10207
  const rest = ordered.filter((credential) => sourceCredentialExpired(credential, now));
9112
- return live.slice(step).concat(live.slice(0, step), rest);
10208
+ return healthy.slice(step).concat(healthy.slice(0, step), held, rest);
9113
10209
  }
9114
10210
  return {
9115
10211
  sourceCreditExpiry,
9116
10212
  sourceRotation,
9117
10213
  sourceFailureHold,
9118
10214
  sourceCredentialExpired,
10215
+ accountStateKey,
9119
10216
  noteSourceFailure,
9120
- sourceFailureActive,
9121
10217
  packUrgency,
9122
10218
  orderSourceCredentials
9123
10219
  };
@@ -9148,11 +10244,6 @@ function createSourcePool(host) {
9148
10244
  /** Read from the package, so this can never drift behind the version it reports. */
9149
10245
  /** The one background service this plugin registers. */
9150
10246
  const SERVICE_ID = "provider-host";
9151
- const COMMAND_OPEN = "xdpool.open";
9152
- const COMMAND_RESCAN = "xdpool.rescan";
9153
- const COMMAND_RESET = "xdpool.resetCooldowns";
9154
- const COMMAND_DOCTOR = "xdpool.doctor";
9155
- const COMMAND_CHECKIN = "xdpool.checkin";
9156
10247
  /** The two gateways, matching the provider ids this plugin registers. */
9157
10248
  const REGIONS = ["cn", "global"];
9158
10249
  const PROVIDER_ID_BY_REGION = {
@@ -9307,7 +10398,7 @@ const CATALOG_TTL_MS = 18e5;
9307
10398
  /**
9308
10399
  * How long a failed roster read waits before the next attempt.
9309
10400
  *
9310
- * A failed read used to be stamped as freshly read, which parked the static
10401
+ * A failed read must not be stamped as freshly read: that parks the static
9311
10402
  * fallback - and with it the wrong model list, for the gateways and for the
9312
10403
  * host's picker - for the whole TTL after one slow start.
9313
10404
  */
@@ -9323,6 +10414,8 @@ const PLACEHOLDER_BASE_URL = "http://127.0.0.1:1/v1";
9323
10414
  * paint, so opening it never waits on a billing call per account.
9324
10415
  */
9325
10416
  const PROBE_TTL_MS = 6e4;
10417
+ /** How often the desktop sign-ins are re-read while the service runs. */
10418
+ const ACCOUNT_WATCH_MS = 6e4;
9326
10419
  /**
9327
10420
  * Bound on one model-catalog request, so a stalled host cannot stall a load.
9328
10421
  *
@@ -9362,6 +10455,32 @@ const SERVICE_BOOTSTRAP_BUDGET_MS = 1500;
9362
10455
  * few seconds at worst when another process holds the preferred ports.
9363
10456
  */
9364
10457
  const REFRESH_PASS_BUDGET_MS = 18e3;
10458
+ /**
10459
+ * How often the token keep-alive walks the pool.
10460
+ *
10461
+ * Half of the lifetime the pool assumes for a token that reports none, so a
10462
+ * sign-in nobody has used is renewed while it still works rather than at the
10463
+ * moment a request needs it.
10464
+ */
10465
+ /**
10466
+ * How long a started panel login stays pollable.
10467
+ *
10468
+ * The browser half is the user's to finish, so it is measured in minutes
10469
+ * rather than the seconds a network call gets. Past it the state is dropped and
10470
+ * the panel asks the user to start again: the upstream keeps answering
10471
+ * `login ing...` for a state that will never complete, so a poll with no
10472
+ * deadline would look alive forever.
10473
+ */
10474
+ const DEVICE_LOGIN_TTL_MS = 9e5;
10475
+ /**
10476
+ * One account-directory walk, on its own clock.
10477
+ *
10478
+ * A walk reads every `.info` in every auth directory and, on a cold key, asks
10479
+ * the OS for the at-rest key, which is the slow part. The host allows a panel
10480
+ * call 30 s and the pass that follows has 18 s of its own, so this is sized to
10481
+ * leave the walk the larger share and let the pass take what is left.
10482
+ */
10483
+ const POOL_SCAN_BUDGET_MS = 8e3;
9365
10484
  let settings = {};
9366
10485
  /**
9367
10486
  * Bumped by every local mutation of `settings`.
@@ -9376,6 +10495,16 @@ let dataPath = "";
9376
10495
  /** One runtime per gateway: its shim and catalog. */
9377
10496
  const runtimes = /* @__PURE__ */ new Map();
9378
10497
  /**
10498
+ * Binds in flight, by region.
10499
+ *
10500
+ * A rescan and a refresh pass can reach the same region at the same moment, and
10501
+ * two binds for one region mean the second loses the preferred port it had just
10502
+ * reserved and logs a warning about its own process. The map is what makes the
10503
+ * second caller the first one's answer; entries are dropped once the promise
10504
+ * settles, so the next pass starts fresh.
10505
+ */
10506
+ const runtimeStarts = /* @__PURE__ */ new Map();
10507
+ /**
9379
10508
  * Gateway closes `reconcileRuntimes` started but could not wait for.
9380
10509
  *
9381
10510
  * That function runs synchronously inside settings application, yet a source
@@ -9442,6 +10571,13 @@ let settingsChangedHandler = null;
9442
10571
  /** The daily check-in timer, and what it has already collected. */
9443
10572
  let autoCheckinTimer = null;
9444
10573
  /**
10574
+ * Timer that re-reads the desktop sign-ins while the service runs.
10575
+ *
10576
+ * Once a minute because a switch in the client overwrites the global sign-in
10577
+ * file in place: the pool only has the account if it read the file before that.
10578
+ */
10579
+ let accountWatchTimer = null;
10580
+ /**
9445
10581
  * True while a check-in pass is running, whichever entry point started it.
9446
10582
  *
9447
10583
  * One flag for all three — the scheduled tick, the host command and the panel's
@@ -9451,10 +10587,45 @@ let autoCheckinTimer = null;
9451
10587
  let checkinPassRunning = false;
9452
10588
  /** Which pass owns the running flag; see `runCheckinPass`. */
9453
10589
  let checkinPassToken = 0;
10590
+ /**
10591
+ * True while the growth centre runs on its own, from the panel's card.
10592
+ *
10593
+ * Separate from `checkinPassRunning` because the two are different passes over
10594
+ * the same accounts: a growth run started beside a check-in pass would stack
10595
+ * two unpaced request clusters on one account, which is what the upstream
10596
+ * reads as a burst. The card refuses while either is running.
10597
+ */
10598
+ let growthPassRunning = false;
10599
+ /** Which run owns `growthPassRunning`, on the same rule as `checkinPassToken`. */
10600
+ let growthPassToken = 0;
10601
+ /**
10602
+ * The last standalone growth run, in the shape the scheduled pass records its
10603
+ * own growth half in. In memory only: after a restart the card falls back to
10604
+ * the growth half of the last scheduled pass, which is persisted with it.
10605
+ */
10606
+ let growthLast = null;
10607
+ /**
10608
+ * The growth centre's last successful read.
10609
+ *
10610
+ * Published with the status document so a repaint or a fresh panel paints it
10611
+ * instead of asking the user to read again; the panel refreshes it when it is old.
10612
+ */
10613
+ let growthRead = null;
10614
+ /**
10615
+ * Which read the answer in flight belongs to.
10616
+ *
10617
+ * A read walks several accounts and can take seconds, so a user can park a region
10618
+ * or drop an account while it runs. Comparing this counter around the await is
10619
+ * what stops that answer - computed against the pool as it was - from being
10620
+ * written back over the drop that just happened.
10621
+ */
10622
+ let growthReadEpoch = 0;
9454
10623
  /** Slots this process has collected, as `YYYY-MM-DDTHH` in the campaign's zone. */
9455
10624
  const autoCheckinSlots = /* @__PURE__ */ new Set();
9456
10625
  /** The last automatic pass, for the panel's status line. */
9457
10626
  let autoCheckinLast = null;
10627
+ /** The last keep-alive pass, for the panel's status line. In memory only. */
10628
+ let keepAliveLast = null;
9458
10629
  /**
9459
10630
  * When a deferred pass is owed, in ms; 0 = nothing pending.
9460
10631
  *
@@ -9483,6 +10654,10 @@ const QODER_RETRY_BACKOFF_MS = 6e5;
9483
10654
  * retired the pass that was running then, not the ones still to come.
9484
10655
  */
9485
10656
  let checkinAbort = new AbortController();
10657
+ const checkinScope = new AsyncLocalStorage();
10658
+ function currentCheckinSignal() {
10659
+ return checkinScope.getStore() ?? checkinAbort.signal;
10660
+ }
9486
10661
  /**
9487
10662
  * Cat-travel pacing: one pass per account, same throttle as the upstream's own
9488
10663
  * scheduler. A single `travelOne` already fans out to several RPCs, so a tight
@@ -9519,18 +10694,6 @@ const GROWTH_ACCOUNT_DELAY_MS = 400;
9519
10694
  const STREAK_REPORT_READ_GAP_MS = 1200;
9520
10695
  /** Account ids that hit the adopt conversation threshold today (CST day). */
9521
10696
  const travelAdoptTried = /* @__PURE__ */ new Map();
9522
- /**
9523
- * An error's text with token-shaped content already redacted.
9524
- *
9525
- * Every caller gets this form — log lines, the panel and the doctor report all
9526
- * read the same string — so a credential that reaches an error message cannot
9527
- * end up somewhere it should not, whichever call site forgot to ask for the
9528
- * panel's stricter copy. The one implementation lives beside the other
9529
- * redaction rules in `loopback.ts`; this is the name the rest of the file uses.
9530
- */
9531
- function messageOf(error) {
9532
- return safeMessage(error);
9533
- }
9534
10697
  function log(level, message) {
9535
10698
  try {
9536
10699
  console.log("[xdpool] " + level + ": " + message);
@@ -9545,7 +10708,7 @@ function log(level, message) {
9545
10708
  * error text gets, so nothing unredacted reaches the log through it.
9546
10709
  */
9547
10710
  function gatewayLogLine(prefix, args) {
9548
- return prefix + args.map(messageOf).join(" ");
10711
+ return prefix + args.map(safeMessage).join(" ");
9549
10712
  }
9550
10713
  function regionOfKey(value) {
9551
10714
  return value === "global" ? "global" : "cn";
@@ -9608,7 +10771,7 @@ async function saveSettings(patch) {
9608
10771
  settingsRevision += 1;
9609
10772
  return true;
9610
10773
  } catch (error) {
9611
- log("warn", "could not save settings: " + messageOf(error));
10774
+ log("warn", "could not save settings: " + safeMessage(error));
9612
10775
  return false;
9613
10776
  }
9614
10777
  });
@@ -9656,7 +10819,7 @@ async function mutateSettings(key, mutate) {
9656
10819
  settingsRevision += 1;
9657
10820
  return true;
9658
10821
  } catch (error) {
9659
- log("warn", "could not save settings: " + messageOf(error));
10822
+ log("warn", "could not save settings: " + safeMessage(error));
9660
10823
  return false;
9661
10824
  }
9662
10825
  });
@@ -9701,6 +10864,10 @@ async function onHostSettingsChanged(next) {
9701
10864
  await reconcileQoderGateways();
9702
10865
  syncDeclaration();
9703
10866
  if (toggled) probeCache.clear();
10867
+ if (toggled) {
10868
+ growthRead = null;
10869
+ growthReadEpoch += 1;
10870
+ }
9704
10871
  scheduleRefresh("settings");
9705
10872
  return true;
9706
10873
  }
@@ -9709,7 +10876,7 @@ function subscribeToHostSettings() {
9709
10876
  settingsChangedHandler = (next) => {
9710
10877
  onHostSettingsChanged(next).then((applied) => {
9711
10878
  if (applied) log("info", "settings changed in the host UI; selection re-applied");
9712
- }).catch((error) => log("warn", "applying host settings failed: " + messageOf(error)));
10879
+ }).catch((error) => log("warn", "applying host settings failed: " + safeMessage(error)));
9713
10880
  };
9714
10881
  try {
9715
10882
  if (pi.events && typeof pi.events.on === "function") {
@@ -9717,7 +10884,7 @@ function subscribeToHostSettings() {
9717
10884
  return true;
9718
10885
  }
9719
10886
  } catch (error) {
9720
- log("warn", "could not subscribe to settings changes: " + messageOf(error));
10887
+ log("warn", "could not subscribe to settings changes: " + safeMessage(error));
9721
10888
  }
9722
10889
  settingsChangedHandler = null;
9723
10890
  return false;
@@ -9727,7 +10894,7 @@ function cooldownMs() {
9727
10894
  if (!Number.isFinite(value) || value <= 0) return 6e4;
9728
10895
  return Math.max(1e3, Math.min(864e5, Math.round(value * 1e3)));
9729
10896
  }
9730
- /** `priority` drains one account. An old `balanced` value reads as priority. */
10897
+ /** The modes other than `priority`, which is what an unrecognised or absent value means. */
9731
10898
  const WORKBUDDY_DISTRIBUTIONS = [
9732
10899
  "round-robin",
9733
10900
  "expiry",
@@ -9803,7 +10970,7 @@ function saveCheckinSlots() {
9803
10970
  try {
9804
10971
  fs$1.rmSync(staging, { force: true });
9805
10972
  } catch {}
9806
- log("warn", "could not record the collected check-in slots: " + messageOf(error));
10973
+ log("warn", "could not record the collected check-in slots: " + safeMessage(error));
9807
10974
  }
9808
10975
  }
9809
10976
  function preferredAccountId(region) {
@@ -9868,15 +11035,15 @@ function nearestPackExpiry(packages) {
9868
11035
  }
9869
11036
  return best;
9870
11037
  }
9871
- const { sourceCreditExpiry, sourceRotation, sourceFailureHold, sourceCredentialExpired, noteSourceFailure, sourceFailureActive, packUrgency, orderSourceCredentials } = createSourcePool({
11038
+ const { sourceCreditExpiry, sourceRotation, sourceFailureHold, sourceCredentialExpired, accountStateKey, noteSourceFailure, orderSourceCredentials } = createSourcePool({
9872
11039
  cooldownMs,
9873
11040
  preferredSourceAccount,
9874
11041
  sourceDistribution,
9875
11042
  sourceRegionKey
9876
11043
  });
9877
- function noteSourceExpiry(source, label, packages) {
11044
+ function noteSourceExpiry(source, region, label, packages) {
9878
11045
  const at = nearestPackExpiry(packages);
9879
- const key = source + "\n" + label;
11046
+ const key = accountStateKey(source, region, label);
9880
11047
  if (at === void 0) sourceCreditExpiry.delete(key);
9881
11048
  else sourceCreditExpiry.set(key, at);
9882
11049
  }
@@ -9935,6 +11102,25 @@ function gatewayEnabledIds(key, catalogIds) {
9935
11102
  const kept = enabled.filter((id) => known.has(id));
9936
11103
  return kept.length > 0 ? new Set(kept) : null;
9937
11104
  }
11105
+ /**
11106
+ * The selection as the gateway really publishes it, for the panel to render.
11107
+ *
11108
+ * The declaration normalizes a stored selection whose every id has been renamed
11109
+ * away back to "everything on", and the panel has to show that same answer. It
11110
+ * used to read the raw stored value, so a catalog rename showed every model
11111
+ * unticked while the gateway published all of them, with no way back: ticking
11112
+ * them produced the same normalized selection again.
11113
+ */
11114
+ function publishedSelectionFor(key, catalogIds) {
11115
+ const stored = gatewaySelectionFor(key);
11116
+ const enabled = gatewayEnabledIds(key, catalogIds);
11117
+ if (enabled !== null) return {
11118
+ ...stored,
11119
+ enabledModelIds: [...enabled]
11120
+ };
11121
+ const { enabledModelIds, ...rest } = stored;
11122
+ return rest;
11123
+ }
9938
11124
  /** Stored per-model overrides for one gateway key ("trae:cn", ...), by model id. */
9939
11125
  function gatewayOverrides(key) {
9940
11126
  const overrides = gatewaySelectionFor(key).overrides;
@@ -9951,15 +11137,20 @@ function sourceModelView(key, model, native) {
9951
11137
  const override = gatewayOverrides(key)[id] ?? {};
9952
11138
  const nativeName = typeof model.name === "string" && model.name !== "" ? model.name : id;
9953
11139
  const alias = typeof override.alias === "string" && override.alias.trim() !== "" ? override.alias.trim() : void 0;
11140
+ const nativeCeiling = Math.max(positiveInteger(native.contextWindow, CONSERVATIVE_CONTEXT_WINDOW), positiveInteger(native.maxContextWindow, 0));
11141
+ const declaredWindow = Math.min(positiveInteger(Number.isFinite(override.contextWindow) ? override.contextWindow : native.contextWindow, CONSERVATIVE_CONTEXT_WINDOW), nativeCeiling);
11142
+ const outputCeiling = positiveInteger(declaredWindow > positiveInteger(native.contextWindow, 128e3) ? native.maxTokensAtCeiling : native.maxTokens, positiveInteger(native.maxTokens, DEFAULT_MAX_TOKENS));
9954
11143
  return {
9955
11144
  id,
9956
11145
  name: alias ?? nativeName,
9957
11146
  ...alias === void 0 ? {} : { alias },
9958
11147
  nativeName,
9959
- contextWindow: positiveInteger(Number.isFinite(override.contextWindow) ? override.contextWindow : native.contextWindow, CONSERVATIVE_CONTEXT_WINDOW),
9960
- maxOutputTokens: positiveInteger(Number.isFinite(override.maxOutputTokens) ? override.maxOutputTokens : native.maxTokens, DEFAULT_MAX_TOKENS),
11148
+ contextWindow: declaredWindow,
11149
+ maxOutputTokens: Math.min(positiveInteger(Number.isFinite(override.maxOutputTokens) ? override.maxOutputTokens : outputCeiling, DEFAULT_MAX_TOKENS), outputCeiling),
9961
11150
  nativeContextWindow: native.contextWindow,
9962
- nativeMaxOutputTokens: native.maxTokens,
11151
+ ...nativeCeiling > positiveInteger(native.contextWindow, 128e3) ? { maxContextWindow: nativeCeiling } : {},
11152
+ nativeMaxOutputTokens: positiveInteger(native.maxTokens, DEFAULT_MAX_TOKENS),
11153
+ ...native.maxTokensAtCeiling === void 0 ? {} : { maxOutputAtCeiling: positiveInteger(native.maxTokensAtCeiling, outputCeiling) },
9963
11154
  supportsImages: typeof override.supportsImages === "boolean" ? override.supportsImages : native.supportsImages,
9964
11155
  nativeSupportsImages: native.supportsImages,
9965
11156
  ...Array.isArray(native.thinkingLevels) && native.thinkingLevels.length > 0 ? { nativeThinkingLevels: [...native.thinkingLevels] } : {},
@@ -9974,6 +11165,20 @@ function sourceRosterFor(key, models, nativeOf) {
9974
11165
  return models.filter((model) => String(model.id || "").trim() !== "").map((model) => sourceModelView(key, model, nativeOf(model))).filter((view) => isSelectableSourceModel(source, view));
9975
11166
  }
9976
11167
  /**
11168
+ * A source gateway's roster plus the selection that gateway really publishes.
11169
+ * One roster pass answers both, so the panel ticks exactly what the declaration
11170
+ * emits: a stored selection whose every id has been renamed away normalizes to
11171
+ * "publish everything" instead of every model showing unticked while the
11172
+ * gateway serves them all.
11173
+ */
11174
+ function sourcePublishedModels(key, models, nativeOf) {
11175
+ const roster = sourceRosterFor(key, models, nativeOf);
11176
+ return {
11177
+ roster,
11178
+ selection: publishedSelectionFor(key, roster.map((view) => view.id))
11179
+ };
11180
+ }
11181
+ /**
9977
11182
  * Trae's internal slots, by the names the IDE gives them.
9978
11183
  *
9979
11184
  * They are the IDE's own, stable across versions, and are what distinguishes a
@@ -10105,7 +11310,8 @@ function delay(ms) {
10105
11310
  * collects one.
10106
11311
  */
10107
11312
  function checkinDelay(ms) {
10108
- if (checkinAbort.signal.aborted) return Promise.resolve();
11313
+ const signal = currentCheckinSignal();
11314
+ if (signal.aborted) return Promise.resolve();
10109
11315
  return new Promise((resolve) => {
10110
11316
  let timer = null;
10111
11317
  const onAbort = () => {
@@ -10113,11 +11319,11 @@ function checkinDelay(ms) {
10113
11319
  resolve();
10114
11320
  };
10115
11321
  timer = setTimeout(() => {
10116
- checkinAbort.signal.removeEventListener("abort", onAbort);
11322
+ signal.removeEventListener("abort", onAbort);
10117
11323
  resolve();
10118
11324
  }, ms);
10119
11325
  if (typeof timer.unref === "function") timer.unref();
10120
- checkinAbort.signal.addEventListener("abort", onAbort, { once: true });
11326
+ signal.addEventListener("abort", onAbort, { once: true });
10121
11327
  });
10122
11328
  }
10123
11329
  /**
@@ -10249,7 +11455,7 @@ function declarationModels(region) {
10249
11455
  const seen = /* @__PURE__ */ new Set();
10250
11456
  for (const model of catalog.visible()) {
10251
11457
  const id = String(model.id || "").trim();
10252
- if (id === "" || id.length > 256 || seen.has(id)) continue;
11458
+ if (id === "" || id.length > MAX_MODEL_ID_LENGTH || seen.has(id)) continue;
10253
11459
  seen.add(id);
10254
11460
  const thinkingLevels = thinkingLevelsFor(model);
10255
11461
  const entry = {
@@ -10404,6 +11610,7 @@ async function warmSourceDirectory(entry, signal) {
10404
11610
  entry.lastError = entry.gateway.models().length > 0 ? "" : "directory unavailable: " + safeMessage(error);
10405
11611
  if (entry.lastError !== "") log("warn", "[" + entry.source + ":" + entry.region + "] " + entry.lastError);
10406
11612
  }
11613
+ if (entry.lastError === "" && entry.gateway.models().length > 0) syncDeclaration();
10407
11614
  return entry.lastError === "";
10408
11615
  }
10409
11616
  /**
@@ -10482,8 +11689,12 @@ async function createTraeRuntime(region) {
10482
11689
  credentials: async (purpose) => orderSourceCredentials("trae", region, (await discoverTraeCredentials()).credentials.filter((credential) => traeRegionOfCredential(credential) === region), traeRowLabel, purpose === "chat"),
10483
11690
  identity: (credential) => resolveTraeIdentity(desktopCandidates, credential.edition),
10484
11691
  listedIds: () => traeDeclarationModels(region).map((model) => model.id),
11692
+ publishedWindowOf: (modelId) => {
11693
+ const declared = traeDeclarationModels(region).find((model) => model.id === modelId);
11694
+ return declared === void 0 ? void 0 : declared.contextWindow;
11695
+ },
10485
11696
  onAttemptFailure: (credential, outcome) => {
10486
- noteSourceFailure("trae", traeRowLabel(credential), outcome.retryAfter);
11697
+ noteSourceFailure("trae", region, traeRowLabel(credential), outcome.retryAfter);
10487
11698
  },
10488
11699
  port: bound,
10489
11700
  logger: {
@@ -10498,11 +11709,12 @@ async function createTraeRuntime(region) {
10498
11709
  gateway,
10499
11710
  baseUrl: gateway.baseUrl(),
10500
11711
  portFallback: bound !== preferred,
11712
+ preferredPort: preferred,
10501
11713
  lastError: "",
10502
11714
  source: "trae"
10503
11715
  };
10504
11716
  if (entry.portFallback) log("warn", "[trae:" + region + "] preferred port " + preferred + " is held by another process; serving this session on port " + gateway.port());
10505
- warmSourceDirectoryAtStartup(entry, warmAbort.signal).catch((error) => log("warn", "[trae:" + region + "] directory warm-up failed: " + messageOf(error)));
11717
+ warmSourceDirectoryAtStartup(entry, warmAbort.signal).catch((error) => log("warn", "[trae:" + region + "] directory warm-up failed: " + safeMessage(error)));
10506
11718
  return entry;
10507
11719
  }
10508
11720
  /** Start and stop Trae gateways so the map matches the source switch exactly. */
@@ -10516,7 +11728,7 @@ async function reconcileTraeGateways() {
10516
11728
  try {
10517
11729
  await entry.gateway.close();
10518
11730
  } catch (error) {
10519
- log("warn", "[trae:" + region + "] gateway did not close cleanly: " + messageOf(error));
11731
+ log("warn", "[trae:" + region + "] gateway did not close cleanly: " + safeMessage(error));
10520
11732
  }
10521
11733
  }
10522
11734
  for (const region of active) {
@@ -10526,15 +11738,20 @@ async function reconcileTraeGateways() {
10526
11738
  if (!stillLoaded(generation) || !activeTraeRegions().includes(region) || traeGateways.has(region)) await entry.gateway.close();
10527
11739
  else traeGateways.set(region, entry);
10528
11740
  } catch (error) {
10529
- log("warn", "[trae:" + region + "] gateway could not start: " + messageOf(error));
11741
+ log("warn", "[trae:" + region + "] gateway could not start: " + safeMessage(error));
10530
11742
  }
10531
11743
  }
10532
11744
  }
10533
11745
  /** What a Trae gateway itself reported for one model. */
10534
11746
  function traeNativeOf(model) {
11747
+ const devWindow = positiveInteger(model.contextWindow, CONSERVATIVE_CONTEXT_WINDOW);
11748
+ const maxWindow = positiveInteger(model.maxContextWindow, 0);
11749
+ const ceiling = Math.max(devWindow, maxWindow);
10535
11750
  return {
10536
- contextWindow: positiveInteger(model.contextWindow, CONSERVATIVE_CONTEXT_WINDOW),
11751
+ contextWindow: devWindow,
10537
11752
  maxTokens: positiveInteger(model.maxTokens, DEFAULT_MAX_TOKENS),
11753
+ ...maxWindow > devWindow ? { maxTokensAtCeiling: positiveInteger(traeVariantFor(model, ceiling)?.maxTokens, positiveInteger(model.maxTokens, DEFAULT_MAX_TOKENS)) } : {},
11754
+ ...maxWindow > devWindow ? { maxContextWindow: maxWindow } : {},
10538
11755
  supportsImages: model.supportsImages === true,
10539
11756
  thinkingLevels: (model.reasoning ? model.reasoning.supported : []).filter((level) => HOST_THINKING_LEVELS.includes(level)),
10540
11757
  ...Number.isFinite(model.creditMultiplier) ? { multiplier: model.creditMultiplier } : {}
@@ -10549,7 +11766,7 @@ function traeDeclarationModels(region) {
10549
11766
  const enabled = gatewayEnabledIds("trae:" + region, roster);
10550
11767
  for (const model of gateway.models()) {
10551
11768
  const id = String(model.id || "").trim();
10552
- if (id === "" || id.length > 256 || seen.has(id)) continue;
11769
+ if (id === "" || id.length > MAX_MODEL_ID_LENGTH || seen.has(id)) continue;
10553
11770
  if (enabled !== null && !enabled.has(id)) continue;
10554
11771
  seen.add(id);
10555
11772
  const native = traeNativeOf(model);
@@ -10613,7 +11830,7 @@ async function createQoderRuntime(region) {
10613
11830
  listedIds: () => qoderDeclarationModels(region).map((model) => model.id),
10614
11831
  onAttemptFailure: (credential, outcome) => {
10615
11832
  const label = typeof credential.name === "string" && credential.name !== "" ? credential.name : credential.userID;
10616
- noteSourceFailure("qoder", label, outcome.retryAfter);
11833
+ noteSourceFailure("qoder", region, label, outcome.retryAfter);
10617
11834
  },
10618
11835
  port: bound,
10619
11836
  logger: {
@@ -10628,11 +11845,12 @@ async function createQoderRuntime(region) {
10628
11845
  gateway,
10629
11846
  baseUrl: gateway.baseUrl(),
10630
11847
  portFallback: bound !== preferred,
11848
+ preferredPort: preferred,
10631
11849
  lastError: "",
10632
11850
  source: "qoder"
10633
11851
  };
10634
11852
  if (entry.portFallback) log("warn", "[qoder:" + region + "] preferred port " + preferred + " is held by another process; serving this session on port " + gateway.port());
10635
- warmSourceDirectoryAtStartup(entry, warmAbort.signal).catch((error) => log("warn", "[qoder:" + region + "] directory warm-up failed: " + messageOf(error)));
11853
+ warmSourceDirectoryAtStartup(entry, warmAbort.signal).catch((error) => log("warn", "[qoder:" + region + "] directory warm-up failed: " + safeMessage(error)));
10636
11854
  return entry;
10637
11855
  }
10638
11856
  /** Start and stop Qoder gateways so the map matches the source switch exactly. */
@@ -10646,7 +11864,7 @@ async function reconcileQoderGateways() {
10646
11864
  try {
10647
11865
  await entry.gateway.close();
10648
11866
  } catch (error) {
10649
- log("warn", "[qoder:" + region + "] gateway did not close cleanly: " + messageOf(error));
11867
+ log("warn", "[qoder:" + region + "] gateway did not close cleanly: " + safeMessage(error));
10650
11868
  }
10651
11869
  }
10652
11870
  for (const region of active) {
@@ -10656,7 +11874,7 @@ async function reconcileQoderGateways() {
10656
11874
  if (!stillLoaded(generation) || !activeQoderRegions().includes(region) || qoderGateways.has(region)) await entry.gateway.close();
10657
11875
  else qoderGateways.set(region, entry);
10658
11876
  } catch (error) {
10659
- log("warn", "[qoder:" + region + "] gateway could not start: " + messageOf(error));
11877
+ log("warn", "[qoder:" + region + "] gateway could not start: " + safeMessage(error));
10660
11878
  }
10661
11879
  }
10662
11880
  }
@@ -10693,7 +11911,7 @@ function qoderDeclarationModels(region) {
10693
11911
  const enabled = gatewayEnabledIds("qoder:" + region, roster);
10694
11912
  for (const model of gateway.models()) {
10695
11913
  const id = String(model.id || "").trim();
10696
- if (id === "" || id.length > 256 || seen.has(id)) continue;
11914
+ if (id === "" || id.length > MAX_MODEL_ID_LENGTH || seen.has(id)) continue;
10697
11915
  if (enabled !== null && !enabled.has(id)) continue;
10698
11916
  seen.add(id);
10699
11917
  const native = qoderNativeOf(model);
@@ -10763,6 +11981,59 @@ async function createRuntime(region) {
10763
11981
  return runtime;
10764
11982
  }
10765
11983
  /**
11984
+ * One bind per region, whoever asks first.
11985
+ *
11986
+ * A rescan and the refresh pass can both reach a region with no runtime at the
11987
+ * same moment. Each used to reserve the preferred port and bind its own shim, so
11988
+ * one of them lost the bind and logged "the preferred port is held by another
11989
+ * process" - about this very process, whose first bind had not finished. Sharing
11990
+ * the in-flight promise makes the second caller the first one's answer.
11991
+ */
11992
+ function startRuntimeOnce(region) {
11993
+ const existing = runtimeStarts.get(region);
11994
+ if (existing !== void 0) return existing;
11995
+ const started = createRuntime(region).finally(() => {
11996
+ if (runtimeStarts.get(region) === started) runtimeStarts.delete(region);
11997
+ });
11998
+ runtimeStarts.set(region, started);
11999
+ return started;
12000
+ }
12001
+ /**
12002
+ * Take ownership of a runtime that has finished binding, or release it.
12003
+ *
12004
+ * Both callers of `startRuntimeOnce` land here with the same object, so
12005
+ * "somebody already put a runtime in the map" cannot be read as "mine is not
12006
+ * wanted": the other caller's entry is this very runtime. Releasing on that
12007
+ * reading closed a gateway that was serving and left a stopped object in the map
12008
+ * no later pass would rebuild.
12009
+ *
12010
+ * `unwanted` covers the reasons nobody is waiting for a gateway at all: the
12011
+ * activation it was started for is gone, the service stopped, or the region was
12012
+ * switched off while the shim was binding.
12013
+ *
12014
+ * A runtime already in the map outranks `unwanted`: the two callers of one
12015
+ * activation (`startRuntimes` and the refresh pass) share one bind, so a runtime
12016
+ * that one of them has already registered must not be closed by the other, whose
12017
+ * `unwanted` is about a generation or a region switch of its own. `runtimes.has`
12018
+ * is every later pass's only re-entry test, so a stopped entry there would take
12019
+ * the region out until the next teardown.
12020
+ *
12021
+ * This host's `onLoad` clears both maps, so it never shares a bind across a reload;
12022
+ * PI-Desktop's keeps its gateways and relies on this same ordering for that case.
12023
+ */
12024
+ async function settleStartedRuntime(region, runtime, unwanted) {
12025
+ const held = runtimes.get(region);
12026
+ if (held === runtime) return true;
12027
+ if (runtime.retired === true) return false;
12028
+ if (unwanted || held !== void 0) {
12029
+ await stopRuntime(runtime);
12030
+ return false;
12031
+ }
12032
+ runtimes.set(region, runtime);
12033
+ gatewayStartFailures.delete(region);
12034
+ return true;
12035
+ }
12036
+ /**
10766
12037
  * Start every active WorkBuddy gateway that is not running yet.
10767
12038
  *
10768
12039
  * One gateway's failure is logged and left out, on the same terms as the Trae
@@ -10779,43 +12050,47 @@ async function startRuntimes() {
10779
12050
  await Promise.all(activeRegions().map(async (region) => {
10780
12051
  if (runtimes.has(region)) return;
10781
12052
  try {
10782
- const runtime = await createRuntime(region);
10783
- if (!stillLoaded(generation) || !activeRegions().includes(region) || runtimes.has(region)) await stopRuntime(runtime);
10784
- else {
10785
- runtimes.set(region, runtime);
10786
- gatewayStartFailures.delete(region);
10787
- }
12053
+ await settleStartedRuntime(region, await startRuntimeOnce(region), !stillLoaded(generation) || !activeRegions().includes(region));
10788
12054
  } catch (error) {
10789
12055
  gatewayStartFailures.set(region, safeMessage(error));
10790
- log("warn", "[workbuddy:" + region + "] gateway could not start: " + messageOf(error));
12056
+ log("warn", "[workbuddy:" + region + "] gateway could not start: " + safeMessage(error));
10791
12057
  }
10792
12058
  }));
10793
12059
  }
10794
12060
  async function stopRuntime(runtime) {
12061
+ if (runtime.retired === true) return;
10795
12062
  runtime.retired = true;
10796
12063
  runtime.signedIn = false;
10797
12064
  gatewayStartFailures.delete(runtime.region);
10798
12065
  if (runtime.shim) await runtime.shim.close().catch((error) => {
10799
- log("warn", "[workbuddy:" + runtime.region + "] gateway did not close cleanly: " + messageOf(error));
12066
+ log("warn", "[workbuddy:" + runtime.region + "] gateway did not close cleanly: " + safeMessage(error));
10800
12067
  });
10801
12068
  }
10802
12069
  /**
10803
12070
  * Come back for a roster that could not be read.
10804
12071
  *
10805
- * A failed read - or one that found no sign-in because the load-time account
10806
- * scan had not finished - used to be stamped as freshly read, which parked the
10807
- * static fallback, and with it the wrong model list for the gateways and for
10808
- * the host's picker, for the whole TTL after one slow start. The retries are
10809
- * cheap: a gateway with no account answers without a request, and one whose
10810
- * read succeeded skips it on the freshness check.
12072
+ * Retries are cheap: a gateway with no account answers without a request, and
12073
+ * one whose read succeeded skips it on the freshness check.
12074
+ *
12075
+ * The handles are tracked so a stop or an unload can clear them: a retry that
12076
+ * outlived its activation fired into the next one and triggered a full refresh
12077
+ * pass nobody asked for.
10811
12078
  */
12079
+ const modelRetryTimers = /* @__PURE__ */ new Set();
10812
12080
  function scheduleModelRetries(attempt = 1) {
10813
12081
  if (serviceStopped) return;
10814
12082
  const timer = setTimeout(() => {
12083
+ modelRetryTimers.delete(timer);
10815
12084
  scheduleRefresh("model-list-retry");
10816
12085
  if (attempt < MODEL_RETRY_ATTEMPTS) scheduleModelRetries(attempt + 1);
10817
12086
  }, CATALOG_RETRY_MS);
10818
12087
  if (typeof timer.unref === "function") timer.unref();
12088
+ modelRetryTimers.add(timer);
12089
+ }
12090
+ /** Drop every pending roster retry. */
12091
+ function clearModelRetries() {
12092
+ for (const timer of modelRetryTimers) clearTimeout(timer);
12093
+ modelRetryTimers.clear();
10819
12094
  }
10820
12095
  /**
10821
12096
  * Bring one gateway online: seed its catalog from that gateway's own account.
@@ -10917,7 +12192,7 @@ function scheduleRefresh(reason) {
10917
12192
  if (refreshTimer !== null || refreshInflight !== null) return;
10918
12193
  refreshTimer = setTimeout(() => {
10919
12194
  refreshTimer = null;
10920
- refreshAll(reason, false).catch((error) => log("warn", "background refresh failed: " + messageOf(error)));
12195
+ refreshAll(reason, false).catch((error) => log("warn", "background refresh failed: " + safeMessage(error)));
10921
12196
  }, 0);
10922
12197
  if (typeof refreshTimer.unref === "function") refreshTimer.unref();
10923
12198
  }
@@ -10992,29 +12267,22 @@ async function refreshAll(reason, force) {
10992
12267
  if (!stillLoaded(generation)) return stalePass();
10993
12268
  }
10994
12269
  if (runtimes.has(region)) continue;
10995
- const starting = createRuntime(region);
12270
+ const starting = startRuntimeOnce(region);
10996
12271
  let runtime;
10997
12272
  try {
10998
12273
  runtime = await settle(starting);
10999
12274
  } catch (error) {
11000
12275
  gatewayStartFailures.set(region, safeMessage(error));
11001
- log("warn", "[" + region + "] gateway could not start: " + messageOf(error));
12276
+ log("warn", "[" + region + "] gateway could not start: " + safeMessage(error));
11002
12277
  continue;
11003
12278
  }
11004
12279
  if (runtime === void 0) {
11005
- starting.then((late) => stopRuntime(late)).catch(() => {});
12280
+ starting.then((late) => {
12281
+ if (runtimes.get(region) !== late) return stopRuntime(late);
12282
+ }).catch(() => {});
11006
12283
  continue;
11007
12284
  }
11008
- if (!stillLoaded(generation)) {
11009
- await stopRuntime(runtime);
11010
- return stalePass();
11011
- }
11012
- if (!stillLoaded(generation) || !activeRegions().includes(region) || runtimes.has(region)) {
11013
- await stopRuntime(runtime);
11014
- continue;
11015
- }
11016
- runtimes.set(region, runtime);
11017
- gatewayStartFailures.delete(region);
12285
+ await settleStartedRuntime(region, runtime, !stillLoaded(generation) || !activeRegions().includes(region));
11018
12286
  }
11019
12287
  await settle(reconcileTraeGateways());
11020
12288
  if (!stillLoaded(generation)) return stalePass();
@@ -11061,7 +12329,7 @@ let qoderAccountRows = [];
11061
12329
  /**
11062
12330
  * The name one Trae account is listed and claimed under.
11063
12331
  *
11064
- * A Trae-generated `username` can read as a stranger (`zhi c cheng`), so the
12332
+ * A Trae-generated `username` can read as a stranger (`zhang san xyz`), so the
11065
12333
  * email is what the panel shows next to it; the label itself stays the app's
11066
12334
  * own name so it matches what the desktop app displays.
11067
12335
  */
@@ -11223,7 +12491,7 @@ async function refreshSourceAccounts() {
11223
12491
  const label = traeRowLabel(credential);
11224
12492
  const region = traeRegionOfCredential(credential);
11225
12493
  const probe = await traeRowProbe(credential, traeAccountRows.find((row) => row.label === label && row.region === region));
11226
- noteSourceExpiry("trae", label, probe?.usage?.credits?.packages);
12494
+ noteSourceExpiry("trae", region, label, probe?.usage?.credits?.packages);
11227
12495
  return {
11228
12496
  label,
11229
12497
  region,
@@ -11237,7 +12505,7 @@ async function refreshSourceAccounts() {
11237
12505
  }))).filter((row) => regionEnabled("trae", row.region));
11238
12506
  } else traeAccountRows = [];
11239
12507
  } catch (error) {
11240
- log("warn", "listing Trae sign-ins failed: " + messageOf(error));
12508
+ log("warn", "listing Trae sign-ins failed: " + safeMessage(error));
11241
12509
  }
11242
12510
  try {
11243
12511
  const regions = activeQoderRegions();
@@ -11253,7 +12521,7 @@ async function refreshSourceAccounts() {
11253
12521
  const label = qoderRowLabel(credential);
11254
12522
  const previous = qoderAccountRows.find((row) => row.label === label && row.region === credential.region);
11255
12523
  const probe = left() > 0 ? await qoderRowProbe(credential, previous) : previous;
11256
- noteSourceExpiry("qoder", label, probe?.usage?.credits?.packages);
12524
+ noteSourceExpiry("qoder", credential.region, label, probe?.usage?.credits?.packages);
11257
12525
  rows.push({
11258
12526
  label,
11259
12527
  region: credential.region,
@@ -11266,7 +12534,7 @@ async function refreshSourceAccounts() {
11266
12534
  qoderAccountRows = rows.filter((row) => regionEnabled("qoder", row.region));
11267
12535
  } else qoderAccountRows = [];
11268
12536
  } catch (error) {
11269
- log("warn", "listing Qoder sign-ins failed: " + messageOf(error));
12537
+ log("warn", "listing Qoder sign-ins failed: " + safeMessage(error));
11270
12538
  }
11271
12539
  pruneSourceState();
11272
12540
  }
@@ -11281,16 +12549,33 @@ async function refreshSourceAccounts() {
11281
12549
  */
11282
12550
  function pruneSourceState() {
11283
12551
  const live = /* @__PURE__ */ new Set();
11284
- for (const row of traeAccountRows) live.add("trae\n" + row.label);
11285
- for (const row of qoderAccountRows) live.add("qoder\n" + row.label);
12552
+ for (const row of traeAccountRows) live.add(accountStateKey("trae", row.region, row.label));
12553
+ for (const row of qoderAccountRows) live.add(accountStateKey("qoder", row.region, row.label));
11286
12554
  for (const key of [...sourceFailureHold.keys()]) if (!live.has(key)) sourceFailureHold.delete(key);
11287
12555
  for (const key of [...sourceCreditExpiry.keys()]) if (!live.has(key)) sourceCreditExpiry.delete(key);
11288
12556
  }
12557
+ /**
12558
+ * Directories the WorkBuddy pool reads, in order.
12559
+ *
12560
+ * The desktop app's own directories come first, so its live sign-in wins over
12561
+ * anything the plugin wrote. The plugin's own directory is appended rather than
12562
+ * substituted: an account added from the panel is read on exactly the same
12563
+ * terms as a desktop sign-in, and removing it is a file deletion the user can
12564
+ * see. A repointed `authFile` narrows the walk to that one directory, as
12565
+ * before — the user asked for a specific file.
12566
+ */
12567
+ function poolAuthDirs(authFile) {
12568
+ if (authFile !== "") return [path.dirname(authFile)];
12569
+ const own = ownSignInDir(dataPath);
12570
+ const dirs = candidateAuthDirs();
12571
+ if (own === "" || dirs.includes(own)) return dirs;
12572
+ return [...dirs, own];
12573
+ }
11289
12574
  /** Push the settings that affect discovery, cooldown and the picker. */
11290
12575
  function applySettingsToCore() {
11291
12576
  const authFile = typeof settings.authFile === "string" ? settings.authFile.trim() : "";
11292
12577
  const emptied = core.pool.applyConfig({
11293
- authDirs: authFile === "" ? candidateAuthDirs() : [path.dirname(authFile)],
12578
+ authDirs: poolAuthDirs(authFile),
11294
12579
  cooldownMs: cooldownMs(),
11295
12580
  distribution: distributionSetting(),
11296
12581
  disabledAccountIds: disabledAccountIds(),
@@ -11366,30 +12651,32 @@ function applyProbe(row, probe) {
11366
12651
  * `pending` so the panel can say it is still reading, and the caller refreshes
11367
12652
  * behind the first paint.
11368
12653
  */
11369
- async function accountProbe(account, allowNetwork) {
12654
+ async function accountProbe(account, allowNetwork, checkinOnly = false) {
11370
12655
  const cached = probeCache.get(account.id);
11371
12656
  if (allowNetwork !== true) return cached === void 0 ? { pending: true } : cached.value;
11372
12657
  if (cached !== void 0 && Date.now() - cached.atMs < PROBE_TTL_MS) return cached.value;
11373
12658
  const value = {};
11374
- try {
11375
- const credits = await core.client.fetchCredits(account.credential);
11376
- value.credits = {
11377
- ...credits.total === void 0 ? {} : { total: credits.total },
11378
- packages: (credits.packages || []).map((pack) => ({
11379
- packageName: pack.packageName,
11380
- ...pack.remain === void 0 ? {} : { remain: pack.remain },
11381
- ...pack.size === void 0 ? {} : { size: pack.size },
11382
- ...pack.monthly === void 0 ? {} : { monthly: pack.monthly },
11383
- ...pack.refreshAtMs === void 0 ? {} : { refreshAtMs: pack.refreshAtMs },
11384
- ...pack.expiresAtMs === void 0 ? {} : { expiresAtMs: pack.expiresAtMs }
11385
- })),
11386
- ...credits.expiringSoon === void 0 ? {} : { expiringSoon: credits.expiringSoon },
11387
- ...credits.nearestExpiryMs === void 0 ? {} : { nearestExpiryMs: credits.nearestExpiryMs }
11388
- };
11389
- } catch (error) {
11390
- value.creditsError = safeMessage(error);
12659
+ if (!checkinOnly) {
12660
+ try {
12661
+ const credits = await core.client.fetchCredits(account.credential);
12662
+ value.credits = {
12663
+ ...credits.total === void 0 ? {} : { total: credits.total },
12664
+ packages: (credits.packages || []).map((pack) => ({
12665
+ packageName: pack.packageName,
12666
+ ...pack.remain === void 0 ? {} : { remain: pack.remain },
12667
+ ...pack.size === void 0 ? {} : { size: pack.size },
12668
+ ...pack.monthly === void 0 ? {} : { monthly: pack.monthly },
12669
+ ...pack.refreshAtMs === void 0 ? {} : { refreshAtMs: pack.refreshAtMs },
12670
+ ...pack.expiresAtMs === void 0 ? {} : { expiresAtMs: pack.expiresAtMs }
12671
+ })),
12672
+ ...credits.expiringSoon === void 0 ? {} : { expiringSoon: credits.expiringSoon },
12673
+ ...credits.nearestExpiryMs === void 0 ? {} : { nearestExpiryMs: credits.nearestExpiryMs }
12674
+ };
12675
+ } catch (error) {
12676
+ value.creditsError = safeMessage(error);
12677
+ }
12678
+ if (value.credits !== void 0 && typeof value.credits.total === "number") core.pool.setCreditBalance(account.id, value.credits.total, value.credits.nearestExpiryMs);
11391
12679
  }
11392
- if (value.credits !== void 0 && typeof value.credits.total === "number") core.pool.setCreditBalance(account.id, value.credits.total, value.credits.nearestExpiryMs);
11393
12680
  try {
11394
12681
  const checkin = await core.client.fetchCheckinStatus(account.credential);
11395
12682
  value.checkin = {
@@ -11451,9 +12738,7 @@ async function statusDocument(options) {
11451
12738
  selectionByRegion[region] = effectiveSelectionFor(region, runtimes.get(region)?.catalog);
11452
12739
  if (selectionStale(region, runtimes.get(region)?.catalog)) staleSelectionRegions.push(region);
11453
12740
  const available = core.pool.available(now, void 0, region);
11454
- const preferred = available.find((account) => account.id === preferredAccountIds[region]);
11455
- const namesNext = distributionSetting() === "priority" || distributionSetting() === "expiry";
11456
- const nextUp = preferred ?? (namesNext ? core.pool.preview(available) : void 0);
12741
+ const nextUp = available.find((account) => account.id === preferredAccountIds[region]) ?? core.pool.preview(available);
11457
12742
  runtimeNextUpId.set(region, nextUp === void 0 ? void 0 : nextUp.id);
11458
12743
  for (const account of core.pool.list(region)) {
11459
12744
  const cooling = account.cooldownUntilMs > now;
@@ -11473,21 +12758,26 @@ async function statusDocument(options) {
11473
12758
  active: runtimeNextUpId.get(region) === account.id,
11474
12759
  preferred: preferredAccountIds[region] === account.id,
11475
12760
  disabled: core.pool.isDisabled(account.id),
12761
+ ...account.archived === true ? { archived: true } : {},
12762
+ ...core.pool.ownsSignIn(account.id) ? { own: true } : {},
11476
12763
  ...reserves[account.id] === void 0 ? {} : { creditReserve: reserves[account.id] }
11477
12764
  };
11478
- if (!cooling && !core.pool.isDisabled(account.id)) pendingProbes.push(accountProbe(account, allowNetwork).then((probe) => {
11479
- applyProbe(row, probe);
11480
- }));
12765
+ if (!core.pool.isDisabled(account.id)) {
12766
+ const checkinOnly = cooling;
12767
+ pendingProbes.push(accountProbe(account, allowNetwork, checkinOnly).then((probe) => {
12768
+ applyProbe(row, probe);
12769
+ }));
12770
+ }
11481
12771
  accounts.push(row);
11482
12772
  }
11483
12773
  const catalog = runtimes.get(region)?.catalog;
11484
12774
  if (catalog) {
11485
- const selection = effectiveSelectionFor(region, catalog);
12775
+ const selection = selectionByRegion[region];
11486
12776
  const enabled = selection.enabledModelIds;
11487
12777
  const overrides = selection.overrides || {};
11488
12778
  for (const model of catalog.current()) {
11489
12779
  const override = overrides[model.id];
11490
- const effective = applyOverride(model, override);
12780
+ const effective = applyOverride(model, override, catalog.hasLiveRoster());
11491
12781
  const levels = thinkingLevelsFor(effective);
11492
12782
  const promo = promoStatusFor(model, campaignClock, region);
11493
12783
  models.push({
@@ -11531,9 +12821,9 @@ async function statusDocument(options) {
11531
12821
  port: entry.gateway.port(),
11532
12822
  models: traeDeclarationModels(entry.region).length,
11533
12823
  portFallback: entry.portFallback,
12824
+ preferredPort: entry.preferredPort,
11534
12825
  lastError: entry.lastError,
11535
- roster: sourceRosterFor("trae:" + entry.region, entry.gateway.models(), traeNativeOf),
11536
- selection: gatewaySelectionFor("trae:" + entry.region)
12826
+ ...sourcePublishedModels("trae:" + entry.region, entry.gateway.models(), traeNativeOf)
11537
12827
  }))
11538
12828
  },
11539
12829
  qoder: {
@@ -11546,9 +12836,9 @@ async function statusDocument(options) {
11546
12836
  port: entry.gateway.port(),
11547
12837
  models: qoderDeclarationModels(entry.region).length,
11548
12838
  portFallback: entry.portFallback,
12839
+ preferredPort: entry.preferredPort,
11549
12840
  lastError: entry.lastError,
11550
- roster: sourceRosterFor("qoder:" + entry.region, entry.gateway.models(), qoderNativeOf),
11551
- selection: gatewaySelectionFor("qoder:" + entry.region)
12841
+ ...sourcePublishedModels("qoder:" + entry.region, entry.gateway.models(), qoderNativeOf)
11552
12842
  }))
11553
12843
  },
11554
12844
  enabled: settings.enabled !== false,
@@ -11556,11 +12846,18 @@ async function statusDocument(options) {
11556
12846
  modelCap: MAX_MODELS,
11557
12847
  distribution: distributionSetting(),
11558
12848
  showComposerPoints: settings.showComposerPoints === true,
12849
+ replacedClientName: replacedClientName() ?? null,
11559
12850
  autoCheckin: {
11560
12851
  enabled: autoCheckinEnabled(),
11561
12852
  hours: checkinHours(),
11562
12853
  ...autoCheckinLast === null ? {} : { last: autoCheckinLast }
11563
12854
  },
12855
+ growth: {
12856
+ running: growthPassRunning || checkinPassRunning,
12857
+ ...growthLast === null ? {} : { last: growthLast },
12858
+ read: growthRead
12859
+ },
12860
+ keepAlive: keepAliveLast === null ? null : { ...keepAliveLast },
11564
12861
  preferredAccountIds,
11565
12862
  removedAccounts: removedAccounts().map((entry) => ({
11566
12863
  id: entry.id,
@@ -11766,7 +13063,7 @@ async function doctorReport() {
11766
13063
  push("source-trae", traeDetail?.ok ?? false, traeDetail?.detail ?? "on; still reading this source's sign-ins");
11767
13064
  const qoderDetail = await settle(qoderDoctorDetail());
11768
13065
  push("source-qoder", qoderDetail?.ok ?? false, qoderDetail?.detail ?? "on; still reading this source's sign-ins");
11769
- push("accounts", status.sources.workbuddy !== true || status.accounts.length > 0, status.sources.workbuddy !== true ? "WorkBuddy source is switched off; nothing is scanned or served" : status.accounts.length === 0 ? "no WorkBuddy sign-in found; sign in to the desktop app, then detect accounts again" : status.accounts.length + " account(s): " + status.accounts.map((account) => account.label).join(", "));
13066
+ push("accounts", status.sources.workbuddy !== true || status.accounts.length > 0, status.sources.workbuddy !== true ? "WorkBuddy source is switched off; nothing is scanned or served" : status.accounts.length === 0 ? "no WorkBuddy sign-in found; sign in to the desktop app, then detect accounts again" : status.accounts.length + " account(s)");
11770
13067
  const healthy = status.accounts.filter((account) => !account.cooling).length;
11771
13068
  push("rotation", status.sources.workbuddy !== true || healthy > 0, status.sources.workbuddy !== true ? "switched off; nothing to rotate" : healthy + " of " + status.accounts.length + " account(s) can serve a request now");
11772
13069
  const atRestKeyReason = status.sources.workbuddy === true ? atRestKeyFailure() : "";
@@ -11869,6 +13166,15 @@ async function doctor() {
11869
13166
  };
11870
13167
  }
11871
13168
  }
13169
+ /**
13170
+ * Logins the panel has started and not finished, keyed by realm.
13171
+ *
13172
+ * One per realm on purpose: a second start for the same realm replaces the
13173
+ * first, and the replaced state is dead — a browser is sitting on a URL nobody
13174
+ * polls. Memory only, so a restart drops them and the panel simply starts over
13175
+ * rather than answering a poll for a state this process never issued.
13176
+ */
13177
+ const deviceLogins = /* @__PURE__ */ new Map();
11872
13178
  function panelError(message, code) {
11873
13179
  const error = new Error(message);
11874
13180
  error.code = code;
@@ -12004,7 +13310,10 @@ async function onPanelInvoke(channel, payload) {
12004
13310
  }
12005
13311
  })), LOAD_ROSTER_BUDGET_MS);
12006
13312
  syncDeclaration();
12007
- return await statusDocument({ allowNetwork: false });
13313
+ return {
13314
+ ...await statusDocument({ allowNetwork: false }),
13315
+ refreshing: refreshNeeded()
13316
+ };
12008
13317
  /**
12009
13318
  * "Detect accounts again": a deliberate, user-invoked re-read, so every
12010
13319
  * gateway's roster is refetched even inside its refresh window.
@@ -12012,6 +13321,8 @@ async function onPanelInvoke(channel, payload) {
12012
13321
  case "xd.rescan": {
12013
13322
  const { left, settle } = budget(RESCAN_BUDGET_MS);
12014
13323
  resetDiscoveryCaches();
13324
+ growthRead = null;
13325
+ growthReadEpoch += 1;
12015
13326
  if (activeRegions().length > 0) await settle(core.pool.scan());
12016
13327
  await settle(startRuntimes());
12017
13328
  await settle(refreshSourceAccounts());
@@ -12032,7 +13343,9 @@ async function onPanelInvoke(channel, payload) {
12032
13343
  const account = core.pool.list().find((item) => item.id === accountId);
12033
13344
  if (account === void 0) throw panelError("unknown account", "NOT_FOUND");
12034
13345
  if (!regionEnabled("workbuddy", regionOf(account.credential.domain))) throw panelError("this source region is disabled", "INACTIVE");
12035
- if (checkinPassRunning) throw panelError("a check-in pass is already running; wait for it to finish", "BUSY");
13346
+ if (checkinPassRunning || growthPassRunning) throw panelError("a check-in or growth pass is already running; wait for it to finish", "BUSY");
13347
+ const token = ++checkinPassToken;
13348
+ checkinPassRunning = true;
12036
13349
  const work = async () => {
12037
13350
  const before = await core.client.fetchCheckinStatus(account.credential);
12038
13351
  if (before.todayCheckedIn) {
@@ -12060,7 +13373,9 @@ async function onPanelInvoke(channel, payload) {
12060
13373
  result: claim
12061
13374
  };
12062
13375
  };
12063
- const answered = await settleWithin(work(), PANEL_STEP_BUDGET_MS);
13376
+ const answered = await settleWithin(work(), PANEL_STEP_BUDGET_MS).finally(() => {
13377
+ if (token === checkinPassToken) checkinPassRunning = false;
13378
+ });
12064
13379
  if (answered === void 0) throw panelError("the check-in did not finish in time; try again", "TIMEOUT");
12065
13380
  return answered;
12066
13381
  }
@@ -12117,11 +13432,40 @@ async function onPanelInvoke(channel, payload) {
12117
13432
  "enabled",
12118
13433
  "disabled",
12119
13434
  "removed",
12120
- "restored"
13435
+ "restored",
13436
+ "deleted"
12121
13437
  ].includes(state)) throw panelError("region, accountId and a known state are required", "INVALID");
12122
13438
  const account = core.pool.list(region).find((item) => item.id === accountId);
12123
13439
  const stored = removedAccounts().find((entry) => entry.id === accountId);
12124
13440
  if (state !== "restored" && account === void 0 && stored === void 0) throw panelError("account does not belong to this gateway", "NOT_FOUND");
13441
+ if (state === "deleted") {
13442
+ if (!core.pool.ownsSignIn(accountId)) throw panelError("only an account added from this panel can be deleted", "NOT_OWN");
13443
+ if (await core.pool.removeOwnSignIn(accountId) !== true) throw panelError("the sign-in file could not be removed", "DELETE_FAILED");
13444
+ await settleWithin(core.pool.scan(), POOL_SCAN_BUDGET_MS);
13445
+ if (await mutateSettings("disabledAccountIds", (current) => {
13446
+ return (Array.isArray(current) ? current.filter((id) => typeof id === "string") : []).filter((id) => id !== accountId);
13447
+ }) !== true) log("warn", "could not clear the disabled state for " + accountId);
13448
+ if (await mutateSettings("creditReserves", (current) => {
13449
+ const next = { ...current && typeof current === "object" && !Array.isArray(current) ? current : {} };
13450
+ delete next[accountId];
13451
+ return next;
13452
+ }) !== true) log("warn", "could not clear the credit reserve for " + accountId);
13453
+ core.pool.applyConfig({
13454
+ disabledAccountIds: disabledAccountIds(),
13455
+ creditReserves: creditReserves()
13456
+ });
13457
+ if (preferredAccountId(region) === accountId) {
13458
+ if (await mutateSettings("preferredAccountIds", (current) => {
13459
+ const next = { ...current && typeof current === "object" && !Array.isArray(current) ? current : {} };
13460
+ delete next[region];
13461
+ return next;
13462
+ }) !== true) log("warn", "could not clear the preferred account for " + region);
13463
+ core.pool.prefer(void 0, region);
13464
+ }
13465
+ growthRead = null;
13466
+ growthReadEpoch += 1;
13467
+ return await statusDocument({ allowNetwork: false });
13468
+ }
12125
13469
  if (await mutateSettings("disabledAccountIds", (current) => {
12126
13470
  const kept = (Array.isArray(current) ? current.filter((id) => typeof id === "string") : []).filter((id) => id !== accountId);
12127
13471
  if (state === "disabled") kept.push(accountId);
@@ -12148,6 +13492,8 @@ async function onPanelInvoke(channel, payload) {
12148
13492
  }) !== true) log("warn", "could not clear the preferred account for " + region);
12149
13493
  core.pool.prefer(void 0, region);
12150
13494
  }
13495
+ growthRead = null;
13496
+ growthReadEpoch += 1;
12151
13497
  return await statusDocument({ allowNetwork: false });
12152
13498
  }
12153
13499
  /** The credits to keep back on one account: 0 clears the floor. */
@@ -12167,67 +13513,36 @@ async function onPanelInvoke(channel, payload) {
12167
13513
  core.pool.applyConfig({ creditReserves: creditReserves() });
12168
13514
  return await statusDocument({ allowNetwork: false });
12169
13515
  }
12170
- /** One click for every account's daily reward, as the command palette does.
13516
+ /** One click for every account's daily reward.
12171
13517
  * With `source`, only that source's pool runs — each source has its own
12172
13518
  * check-in pool in the panel, so one button must not sweep the others. */
12173
13519
  case "xd.checkinAll": {
12174
13520
  const source = typeof payload?.source === "string" ? payload.source : "";
12175
- const want = (name) => source === "" || source === name;
12176
- if (checkinPassRunning) return {
13521
+ if (![
13522
+ "",
13523
+ "workbuddy",
13524
+ "trae",
13525
+ "qoder"
13526
+ ].includes(source)) throw panelError("source must be workbuddy, trae or qoder", "INVALID");
13527
+ const counts = await settleWithin(runCheckinPass({
13528
+ manual: true,
13529
+ only: source
13530
+ }), CHECKIN_BUDGET_MS);
13531
+ if (counts === void 0) return {
12177
13532
  state: await statusDocument({
12178
13533
  allowNetwork: true,
12179
13534
  budgetMs: DOCUMENT_BUDGET_MS
12180
13535
  }),
12181
13536
  running: true
12182
13537
  };
12183
- if (serviceStopped) return {
12184
- state: await statusDocument({ allowNetwork: false }),
12185
- running: true
12186
- };
12187
- checkinPassRunning = true;
12188
- const token = ++checkinPassToken;
12189
- checkinAbort = new AbortController();
12190
- const passHour = zonedDayHour(/* @__PURE__ */ new Date());
12191
- autoCheckinSlots.add(dueCheckinSlot(/* @__PURE__ */ new Date(), checkinHours(), autoCheckinSlots) ?? checkinSlotId(passHour.day, passHour.hour));
12192
- saveCheckinSlots();
12193
- const failed = { failed: true };
12194
- const counts = await settleWithin((async () => {
12195
- try {
12196
- const [pool, qoder, trae] = await Promise.all([
12197
- want("workbuddy") ? isolatedCheckinWorker(claimAllCheckins(), {
12198
- claimed: 0,
12199
- skipped: 0,
12200
- failed: 0
12201
- }, "workbuddy") : Promise.resolve({
12202
- claimed: 0,
12203
- skipped: 0,
12204
- failed: 0
12205
- }),
12206
- want("qoder") ? isolatedCheckinWorker(qoderCheckinAll(), void 0, "qoder") : Promise.resolve(void 0),
12207
- want("trae") ? isolatedCheckinWorker(traeCheckinAll(), void 0, "trae") : Promise.resolve(void 0)
12208
- ]);
12209
- const travel = want("workbuddy") ? await isolatedCheckinWorker(travelAllAccounts(), void 0, "travel") : void 0;
12210
- return {
12211
- ...pool,
12212
- travel,
12213
- qoder,
12214
- trae
12215
- };
12216
- } finally {
12217
- if (token === checkinPassToken) checkinPassRunning = false;
12218
- }
12219
- })().catch((error) => {
12220
- log("warn", "check-in pass failed: " + messageOf(error));
12221
- return failed;
12222
- }), CHECKIN_BUDGET_MS);
12223
- if (counts === void 0) return {
13538
+ if (counts.running === true || counts.stale === true) return {
12224
13539
  state: await statusDocument({
12225
13540
  allowNetwork: true,
12226
13541
  budgetMs: DOCUMENT_BUDGET_MS
12227
13542
  }),
12228
13543
  running: true
12229
13544
  };
12230
- if (counts === failed) throw panelError("the check-in pass failed; the reason is in the plugin log", "UPSTREAM");
13545
+ if (counts.error !== void 0) throw panelError(counts.error, "UPSTREAM");
12231
13546
  return {
12232
13547
  state: await statusDocument({
12233
13548
  allowNetwork: true,
@@ -12250,7 +13565,9 @@ async function onPanelInvoke(channel, payload) {
12250
13565
  if (source !== "trae" && source !== "qoder") throw panelError("source must be trae or qoder", "INVALID");
12251
13566
  if (label === "" || region === "") throw panelError("label and region are required", "INVALID");
12252
13567
  if (!regionEnabled(source, region)) throw panelError("this source region is disabled", "INACTIVE");
12253
- if (checkinPassRunning) throw panelError("a check-in pass is already running; wait for it to finish", "BUSY");
13568
+ if (checkinPassRunning || growthPassRunning) throw panelError("a check-in or growth pass is already running; wait for it to finish", "BUSY");
13569
+ const token = ++checkinPassToken;
13570
+ checkinPassRunning = true;
12254
13571
  const answered = await settleWithin((async () => {
12255
13572
  const outcome = source === "trae" ? await traeClaimOne(label, region) : await qoderClaimOne(label, region);
12256
13573
  return {
@@ -12260,7 +13577,9 @@ async function onPanelInvoke(channel, payload) {
12260
13577
  }),
12261
13578
  result: outcome
12262
13579
  };
12263
- })(), PANEL_STEP_BUDGET_MS);
13580
+ })(), PANEL_STEP_BUDGET_MS).finally(() => {
13581
+ if (token === checkinPassToken) checkinPassRunning = false;
13582
+ });
12264
13583
  if (answered === void 0) throw panelError("the check-in did not finish in time; try again", "TIMEOUT");
12265
13584
  return answered;
12266
13585
  }
@@ -12320,6 +13639,23 @@ async function onPanelInvoke(channel, payload) {
12320
13639
  return await statusDocument({ allowNetwork: false });
12321
13640
  }
12322
13641
  /**
13642
+ * Refresh every eligible account's token, by hand.
13643
+ *
13644
+ * There is no schedule behind this: the panel's button is the only thing
13645
+ * that runs it, which is what the user asked for. The pass itself is the
13646
+ * same one the check-in card's other controls use — `ensureFresh` decides
13647
+ * per account whether an upstream call is needed — so a token that still
13648
+ * has hours on it costs nothing and an international token that lives a
13649
+ * year is never touched.
13650
+ *
13651
+ * Bounded like every other network pass here: Trae alone spaces its
13652
+ * accounts, and a pass that outruns the budget records itself in the
13653
+ * document instead of leaving the button spinning.
13654
+ */
13655
+ case "xd.keepAlive":
13656
+ await settleWithin(runKeepAlivePass(), REFRESH_PASS_BUDGET_MS);
13657
+ return await statusDocument({ allowNetwork: false });
13658
+ /**
12323
13659
  * Run the daily pass now, by hand.
12324
13660
  *
12325
13661
  * The scheduled pass is silent by nature: it fires at an hour nobody is
@@ -12342,6 +13678,15 @@ async function onPanelInvoke(channel, payload) {
12342
13678
  if (await saveSettings({ showComposerPoints: payload?.enabled === true }) !== true) throw panelError("the composer credits setting could not be written to the plugin settings file", "SAVE_FAILED");
12343
13679
  return await statusDocument({ allowNetwork: false });
12344
13680
  /**
13681
+ * Rewrite the client name the domestic host's channel check refuses.
13682
+ *
13683
+ * Off by default: it changes what the prompt says about the client, which is
13684
+ * a decision for the user rather than something the plugin does behind them.
13685
+ */
13686
+ case "xd.setRewriteClientName":
13687
+ if (await saveSettings({ rewriteClientName: payload?.enabled === true }) !== true) throw panelError("the client-name setting could not be written to the plugin settings file", "SAVE_FAILED");
13688
+ return await statusDocument({ allowNetwork: false });
13689
+ /**
12345
13690
  * Park or unpark one edition of one source (国内版 / 国际版).
12346
13691
  *
12347
13692
  * Same shape as the source switch above: a parked region keeps no gateway,
@@ -12362,6 +13707,10 @@ async function onPanelInvoke(channel, payload) {
12362
13707
  await onHostSettingsChanged({});
12363
13708
  if (payload?.enabled === true) await refreshAll("region-on", true);
12364
13709
  else syncDeclaration();
13710
+ if (source === "workbuddy") {
13711
+ growthRead = null;
13712
+ growthReadEpoch += 1;
13713
+ }
12365
13714
  return await statusDocument({ allowNetwork: false });
12366
13715
  }
12367
13716
  /**
@@ -12380,8 +13729,135 @@ async function onPanelInvoke(channel, payload) {
12380
13729
  await onHostSettingsChanged({});
12381
13730
  if (payload?.enabled === true) await refreshAll("source-on", true);
12382
13731
  else syncDeclaration();
13732
+ if (payload?.source === "workbuddy") {
13733
+ growthRead = null;
13734
+ growthReadEpoch += 1;
13735
+ }
12383
13736
  return await statusDocument({ allowNetwork: false });
12384
13737
  }
13738
+ /**
13739
+ * Start a panel login and answer the URL to open.
13740
+ *
13741
+ * The URL is handed back rather than opened from here: the panel owns the
13742
+ * click, and this host's page is a real browser tab, so it opens the link
13743
+ * itself the same way its footer links do.
13744
+ */
13745
+ case "xd.startLogin": {
13746
+ const realm = payload?.realm === "global" ? "global" : "cn";
13747
+ const start = await startDeviceLogin(realm);
13748
+ deviceLogins.set(realm, {
13749
+ state: start.state,
13750
+ at: Date.now()
13751
+ });
13752
+ return {
13753
+ realm,
13754
+ authUrl: start.authUrl
13755
+ };
13756
+ }
13757
+ /**
13758
+ * Poll the login the panel started on this realm.
13759
+ *
13760
+ * A finished login is written as one of the plugin's own `.info` files and
13761
+ * the pool is rescanned, so the account appears in the panel and the
13762
+ * provider row without a reload. The second sign-in for an account already
13763
+ * present lands in a directory the pool already reads, so the directory set
13764
+ * does not change and `applyConfig` would not notice it: the scan is
13765
+ * explicit for that reason.
13766
+ */
13767
+ case "xd.pollLogin": {
13768
+ const realm = payload?.realm === "global" ? "global" : "cn";
13769
+ const pending = deviceLogins.get(realm);
13770
+ if (pending === void 0) throw panelError("no login is waiting on this realm", "NO_LOGIN");
13771
+ if (Date.now() - pending.at > DEVICE_LOGIN_TTL_MS) {
13772
+ deviceLogins.delete(realm);
13773
+ throw panelError("the login link has expired; start again", "LOGIN_EXPIRED");
13774
+ }
13775
+ const answer = await pollDeviceLogin(realm, pending.state);
13776
+ if (answer.status !== "ok") return { status: "pending" };
13777
+ deviceLogins.delete(realm);
13778
+ const directory = ownSignInDir(dataPath);
13779
+ if (directory === "") throw panelError("no plugin data directory to write the sign-in into", "NO_DATA_DIR");
13780
+ await writeOwnSignIn(directory, answer.signIn);
13781
+ growthRead = null;
13782
+ growthReadEpoch += 1;
13783
+ await settleWithin(core.pool.scan(), POOL_SCAN_BUDGET_MS);
13784
+ await refreshAll("panel-login", false);
13785
+ return {
13786
+ status: "ok",
13787
+ nickname: answer.signIn.nickname,
13788
+ region: answer.signIn.region,
13789
+ state: await statusDocument({ allowNetwork: false })
13790
+ };
13791
+ }
13792
+ /**
13793
+ * What the growth centre holds, claiming nothing.
13794
+ *
13795
+ * Read-only because two of the four steps are not idempotent: a make-up
13796
+ * card and a lottery draw are spent by running them. Showing the state
13797
+ * first is what lets the panel say "2 cards, yesterday missed" before the
13798
+ * user decides, rather than spending one and reporting it afterwards.
13799
+ */
13800
+ case "xd.growthState": {
13801
+ const epoch = growthReadEpoch;
13802
+ const answered = await settleWithin(readGrowthState(), PANEL_STEP_BUDGET_MS);
13803
+ if (answered === void 0) throw panelError("the growth state did not finish in time; try again", "TIMEOUT");
13804
+ if (epoch !== growthReadEpoch) return { growth: {
13805
+ ...answered,
13806
+ readAt: Date.now()
13807
+ } };
13808
+ growthRead = {
13809
+ ...answered,
13810
+ readAt: Date.now()
13811
+ };
13812
+ return { growth: growthRead };
13813
+ }
13814
+ /**
13815
+ * Run the growth centre on its own, without the daily check-in.
13816
+ *
13817
+ * The scheduled pass runs it as its third stage, so this is the same code
13818
+ * with the same pacing and the same abort signal - not a second, smaller
13819
+ * copy of it. Refused beside a check-in pass rather than queued: both walk
13820
+ * the same accounts, and two unpaced clusters on one account is what the
13821
+ * upstream reads as a burst.
13822
+ */
13823
+ case "xd.growthRun": {
13824
+ if (serviceStopped) return {
13825
+ state: await statusDocument({ allowNetwork: false }),
13826
+ running: true
13827
+ };
13828
+ if (growthPassRunning || checkinPassRunning) return {
13829
+ state: await statusDocument({ allowNetwork: false }),
13830
+ running: true
13831
+ };
13832
+ growthPassRunning = true;
13833
+ const token = ++growthPassToken;
13834
+ checkinAbort.abort();
13835
+ checkinAbort = new AbortController();
13836
+ checkinScope.enterWith(checkinAbort.signal);
13837
+ const generation = loadGeneration;
13838
+ const counts = await settleWithin((async () => {
13839
+ try {
13840
+ return await claimAllGrowth();
13841
+ } finally {
13842
+ if (token === growthPassToken) growthPassRunning = false;
13843
+ }
13844
+ })(), GROWTH_BUDGET_MS);
13845
+ if (counts === void 0) return {
13846
+ state: await statusDocument({ allowNetwork: false }),
13847
+ running: true
13848
+ };
13849
+ if (stillLoaded(generation)) {
13850
+ growthLast = {
13851
+ at: (/* @__PURE__ */ new Date()).toISOString(),
13852
+ ...counts
13853
+ };
13854
+ scheduleRefresh("growth");
13855
+ }
13856
+ return {
13857
+ state: await statusDocument({ allowNetwork: false }),
13858
+ growth: counts
13859
+ };
13860
+ }
12385
13861
  case "xd.doctor": return await doctor();
12386
13862
  /**
12387
13863
  * The composer readout.
@@ -12433,70 +13909,6 @@ async function onPanelInvoke(channel, payload) {
12433
13909
  default: throw panelError("unsupported panel channel: " + String(channel), "UNSUPPORTED");
12434
13910
  }
12435
13911
  }
12436
- async function registerCommands() {
12437
- const register = async (id, title, keywords, run) => {
12438
- try {
12439
- await pi.commands.register({
12440
- id,
12441
- title,
12442
- category: "Productivity",
12443
- keywords,
12444
- run
12445
- });
12446
- } catch (error) {
12447
- log("warn", "could not register command " + id + ": " + messageOf(error));
12448
- }
12449
- };
12450
- await register(COMMAND_OPEN, "WTQ Pool: Open Panel", [
12451
- "workbuddy",
12452
- "pool",
12453
- "池",
12454
- "模型"
12455
- ], async () => {
12456
- await pi.ui.openPanel();
12457
- });
12458
- await register(COMMAND_RESCAN, "WTQ Pool: Detect Accounts Again", [
12459
- "workbuddy",
12460
- "rescan",
12461
- "重新检测"
12462
- ], async () => {
12463
- const state = await onPanelInvoke("xd.rescan", {});
12464
- await pi.ui.showToast("WTQ Pool - " + state.accounts.length + " account(s) in the pool", "info");
12465
- });
12466
- await register(COMMAND_RESET, "WTQ Pool: Clear All Cooldowns", [
12467
- "workbuddy",
12468
- "cooldown",
12469
- "清除冷却"
12470
- ], async () => {
12471
- core.pool.resetCooldowns();
12472
- sourceFailureHold.clear();
12473
- await pi.ui.showToast("WTQ Pool - all cooldowns cleared", "info");
12474
- });
12475
- await register(COMMAND_DOCTOR, "WTQ Pool: Run Connection Check", [
12476
- "workbuddy",
12477
- "doctor",
12478
- "诊断"
12479
- ], async () => {
12480
- const result = await doctor();
12481
- await pi.ui.showToast(result.ok ? "WTQ Pool check passed" : "WTQ Pool check found problems - see the panel", result.ok ? "info" : "warn");
12482
- });
12483
- await register(COMMAND_CHECKIN, "WTQ Pool: Daily Check-in (All Accounts)", [
12484
- "workbuddy",
12485
- "trae",
12486
- "qoder",
12487
- "checkin",
12488
- "签到"
12489
- ], async () => {
12490
- const finished = runCheckinPass().then((result) => checkinSummaryText(result));
12491
- const summary = await settleWithin(finished, CHECKIN_BUDGET_MS);
12492
- if (summary !== void 0) {
12493
- await pi.ui.showToast(summary, "info");
12494
- return;
12495
- }
12496
- await pi.ui.showToast("dsh-wtq-pool - check-in running in the background", "info");
12497
- finished.then((late) => pi.ui.showToast(late, "info")).catch((error) => log("warn", "background check-in failed: " + messageOf(error)));
12498
- });
12499
- }
12500
13912
  /**
12501
13913
  * One check-in worker, isolated from the others in the same fan-out.
12502
13914
  *
@@ -12506,7 +13918,7 @@ async function registerCommands() {
12506
13918
  */
12507
13919
  function isolatedCheckinWorker(work, fallback, name) {
12508
13920
  return work.catch((error) => {
12509
- log("warn", name + " check-in failed: " + messageOf(error));
13921
+ log("warn", name + " check-in failed: " + safeMessage(error));
12510
13922
  return {
12511
13923
  ...fallback,
12512
13924
  failed: 1,
@@ -12528,12 +13940,17 @@ function isolatedCheckinWorker(work, fallback, name) {
12528
13940
  */
12529
13941
  async function runCheckinPass(options) {
12530
13942
  const manual = options?.manual === true;
13943
+ const only = typeof options?.only === "string" ? options.only : "";
13944
+ const want = (name) => only === "" || only === name;
12531
13945
  const generation = loadGeneration;
12532
13946
  if (checkinPassRunning) return { running: true };
12533
13947
  if (serviceStopped) return { stale: true };
13948
+ if (growthPassRunning) return { running: true };
12534
13949
  checkinPassRunning = true;
12535
13950
  const token = ++checkinPassToken;
13951
+ checkinAbort.abort();
12536
13952
  checkinAbort = new AbortController();
13953
+ checkinScope.enterWith(checkinAbort.signal);
12537
13954
  const zoned = zonedDayHour(/* @__PURE__ */ new Date());
12538
13955
  const slot = typeof options?.slot === "string" && options.slot !== "" ? options.slot : dueCheckinSlot(/* @__PURE__ */ new Date(), checkinHours(), autoCheckinSlots) ?? checkinSlotId(zoned.day, zoned.hour);
12539
13956
  const started = {
@@ -12544,42 +13961,64 @@ async function runCheckinPass(options) {
12544
13961
  ...manual ? { manual: true } : {}
12545
13962
  };
12546
13963
  autoCheckinLast = started;
12547
- autoCheckinSlots.add(slot);
13964
+ const spendsSlot = want("workbuddy");
13965
+ if (spendsSlot) autoCheckinSlots.add(slot);
12548
13966
  scheduleRefresh(manual ? "manual-checkin" : "auto-checkin");
12549
13967
  try {
12550
13968
  const [pool, qoder, trae] = await Promise.all([
12551
- isolatedCheckinWorker(claimAllCheckins(), {
13969
+ want("workbuddy") ? isolatedCheckinWorker(claimAllCheckins(), {
13970
+ claimed: 0,
13971
+ skipped: 0,
13972
+ failed: 0
13973
+ }, "workbuddy") : Promise.resolve({
13974
+ claimed: 0,
13975
+ skipped: 0,
13976
+ failed: 0
13977
+ }),
13978
+ want("qoder") ? isolatedCheckinWorker(qoderCheckinAll(), {
13979
+ claimed: 0,
13980
+ skipped: 0,
13981
+ failed: 0
13982
+ }, "qoder") : Promise.resolve({
13983
+ claimed: 0,
13984
+ skipped: 0,
13985
+ failed: 0
13986
+ }),
13987
+ want("trae") ? isolatedCheckinWorker(traeCheckinAll(), {
12552
13988
  claimed: 0,
12553
13989
  skipped: 0,
12554
13990
  failed: 0
12555
- }, "workbuddy"),
12556
- isolatedCheckinWorker(qoderCheckinAll(), void 0, "qoder"),
12557
- isolatedCheckinWorker(traeCheckinAll(), void 0, "trae")
13991
+ }, "trae") : Promise.resolve({
13992
+ claimed: 0,
13993
+ skipped: 0,
13994
+ failed: 0
13995
+ })
12558
13996
  ]);
12559
- const travel = await isolatedCheckinWorker(travelAllAccounts(), {
13997
+ const travel = want("workbuddy") ? await isolatedCheckinWorker(travelAllAccounts(), {
12560
13998
  departed: 0,
12561
13999
  claimed: 0,
12562
14000
  adopted: 0
12563
- }, "travel");
14001
+ }, "travel") : void 0;
12564
14002
  if (!stillLoaded(generation)) return started;
12565
- qoderRetryAt = typeof qoder.opensAt === "number" && qoder.opensAt > Date.now() ? qoder.opensAt : 0;
14003
+ qoderRetryAt = typeof qoder?.opensAt === "number" && qoder.opensAt > Date.now() ? qoder.opensAt : 0;
12566
14004
  Object.assign(started, {
12567
14005
  claimed: pool.claimed,
12568
14006
  skipped: pool.skipped,
12569
14007
  failed: pool.failed,
14008
+ ...pool.reason === void 0 ? {} : { reason: pool.reason },
12570
14009
  travel,
12571
14010
  qoder,
12572
14011
  trae
12573
14012
  });
12574
14013
  await checkinDelay(GROWTH_AFTER_CHECKIN_MS);
12575
14014
  if (!stillLoaded(generation)) return started;
12576
- started.growth = await claimAllGrowth();
14015
+ started.growth = want("workbuddy") ? await claimAllGrowth() : void 0;
12577
14016
  log((manual ? "manual" : "automatic") + " check-in collected " + pool.claimed + " account(s) for " + slot);
12578
- if (stillLoaded(generation)) saveCheckinSlots();
14017
+ if (spendsSlot && stillLoaded(generation)) saveCheckinSlots();
12579
14018
  } catch (error) {
12580
14019
  started.error = safeMessage(error);
12581
14020
  log("warn", (manual ? "manual" : "automatic") + " check-in failed for " + slot + ": " + started.error);
12582
- if (stillLoaded(generation)) saveCheckinSlots();
14021
+ if (spendsSlot && stillLoaded(generation)) saveCheckinSlots();
12583
14022
  } finally {
12584
14023
  if (token === checkinPassToken) checkinPassRunning = false;
12585
14024
  delete started.pending;
@@ -12610,6 +14049,12 @@ const PANEL_STEP_BUDGET_MS = 2e4;
12610
14049
  */
12611
14050
  const DOCUMENT_BUDGET_MS = 4e3;
12612
14051
  /**
14052
+ * A standalone growth run. Wider than the check-in budget it is carved out of,
14053
+ * because growth walks the same accounts with a pause and a report gap between
14054
+ * the steps, and several sign-ins make that minutes rather than seconds.
14055
+ */
14056
+ const GROWTH_BUDGET_MS = 9e4;
14057
+ /**
12613
14058
  * What the composer popup's refresh may spend before it answers.
12614
14059
  *
12615
14060
  * The readout's own call deadline is 20 s (`INVOKE_TIMEOUT_MS`), and the route
@@ -12619,15 +14064,6 @@ const DOCUMENT_BUDGET_MS = 4e3;
12619
14064
  * credentials read from turning the click into a client-side timeout.
12620
14065
  */
12621
14066
  const COMPOSER_REFRESH_BUDGET_MS = 15e3;
12622
- /** The one line a check-in pass reports, whichever way it finished. */
12623
- function checkinSummaryText(result) {
12624
- if (result == null || result.running === true) return "WTQ Pool - a check-in pass is already running";
12625
- if (result.stale === true) return "WTQ Pool - the check-in pass was interrupted by a reload; run it again";
12626
- const growth = result.growth;
12627
- const growthText = growth === void 0 ? "" : ", streak " + (Number(growth.streak) || 0) + " tier(s), tasks " + (Number(growth.tasks) || 0) + " (+" + (Number(growth.credit) || 0) + " credits)";
12628
- const row = (value, label) => value === void 0 ? "" : ", " + label + " " + JSON.stringify(value);
12629
- return "WTQ Pool - checked in " + ((Number(result.claimed) || 0) + (Number(result.qoder?.claimed) || 0) + (Number(result.trae?.claimed) || 0)) + " account(s)" + row(result.travel, "travel") + growthText + row(result.qoder, "Qoder") + row(result.trae, "Trae");
12630
- }
12631
14067
  /**
12632
14068
  * Light one account's growth streak, then redeem every tier it opened.
12633
14069
  *
@@ -12648,11 +14084,40 @@ function checkinSummaryText(result) {
12648
14084
  * redeemed and what they paid, so the panel can say so.
12649
14085
  */
12650
14086
  async function redeemAccountStreak(account) {
14087
+ const detail = {
14088
+ makeup: 0,
14089
+ gift: 0,
14090
+ compensation: 0,
14091
+ activity: 0,
14092
+ streak: 0,
14093
+ lottery: 0,
14094
+ failed: 0
14095
+ };
12651
14096
  const conversationId = "wb2api-streak-" + Date.now();
14097
+ try {
14098
+ if (await core.client.makeupCards(account.credential) > 0 && await core.client.missedYesterday(account.credential)) {
14099
+ const yesterday = zonedDay(-1);
14100
+ await core.client.useMakeupCard(account.credential, yesterday);
14101
+ detail.makeup += 1;
14102
+ log("info", "streak " + account.label + ": make-up card spent on " + yesterday);
14103
+ }
14104
+ } catch (error) {
14105
+ detail.failed += 1;
14106
+ log("warn", "streak " + account.label + ": make-up: " + safeMessage(error));
14107
+ }
14108
+ for (const [label, collect] of [["gift", () => core.client.claimGift(account.credential)], ["compensation", () => core.client.claimCompensation(account.credential)]]) try {
14109
+ const paid = await collect();
14110
+ if (paid > 0) {
14111
+ detail[label] += paid;
14112
+ log("info", "streak " + account.label + ": " + label + " +" + paid + "c");
14113
+ }
14114
+ } catch {}
12652
14115
  try {
12653
14116
  await core.client.reportChatActivity(account.credential, conversationId);
14117
+ detail.activity += 1;
12654
14118
  } catch (error) {
12655
- log("warn", "streak " + account.label + ": activity report failed: " + messageOf(error));
14119
+ detail.failed += 1;
14120
+ log("warn", "streak " + account.label + ": activity report failed: " + safeMessage(error));
12656
14121
  }
12657
14122
  await checkinDelay(STREAK_REPORT_READ_GAP_MS);
12658
14123
  const status = await core.client.growthStreakFull(account.credential);
@@ -12666,114 +14131,164 @@ async function redeemAccountStreak(account) {
12666
14131
  claimed += 1;
12667
14132
  credit += tier.credit;
12668
14133
  energy += tier.energy;
14134
+ detail.streak += 1;
12669
14135
  log("info", "streak " + account.label + ": redeemed " + tier.tier + " (+" + tier.credit + "c +" + tier.energy + "e)");
12670
14136
  } catch (error) {
12671
- log("warn", "streak " + account.label + ": redeem " + tier.tier + " failed: " + messageOf(error));
14137
+ detail.failed += 1;
14138
+ log("warn", "streak " + account.label + ": redeem " + tier.tier + " failed: " + safeMessage(error));
12672
14139
  }
12673
14140
  }
12674
- return {
12675
- claimed,
12676
- credit,
12677
- energy
12678
- };
12679
- }
12680
- /**
12681
- * Collect every claimable task reward of one account.
12682
- *
12683
- * Enrolment comes first: a task that was never accepted cannot be claimed, and
12684
- * accepting an already-accepted task succeeds, so replaying the pass is safe.
12685
- * The list is read again afterwards, because accepting can change what is
12686
- * claimable. A repeat claim answers `already_claimed` and pays nothing.
12687
- */
12688
- async function claimAccountTasks(account) {
12689
- const credential = account.credential;
12690
- const open = (await core.client.listTasks(credential)).filter((task) => task.acceptStatus === "not_accepted" && !task.locked).map((task) => task.taskCode);
12691
- if (open.length > 0) {
12692
- const refused = await core.client.acceptTasks(credential, open);
12693
- if (refused.length > 0) log("warn", "task " + account.label + ": the upstream refused " + refused.join(", "));
12694
- }
12695
- const tasks = await core.client.listTasks(credential);
12696
- let claimed = 0;
12697
- let credit = 0;
12698
- let energy = 0;
12699
- let failed = 0;
12700
- for (const task of tasks) {
12701
- if (!task.claimable || task.locked) continue;
12702
- try {
12703
- const reward = await core.client.claimTaskReward(credential, task.taskCode);
12704
- if (reward.credit > 0 || reward.energy > 0) {
12705
- claimed += 1;
12706
- credit += reward.credit;
12707
- energy += reward.energy;
12708
- log("info", "task " + account.label + ": " + task.title + " +" + reward.credit + "c +" + reward.energy + "e");
12709
- }
12710
- } catch (error) {
12711
- failed += 1;
12712
- log("warn", "task " + account.label + ": " + task.taskCode + " failed: " + messageOf(error));
14141
+ try {
14142
+ const chances = await core.client.lotteryChances(account.credential);
14143
+ for (let draw = 0; draw < chances; draw += 1) {
14144
+ const prize = await core.client.drawLottery(account.credential);
14145
+ detail.lottery += 1;
14146
+ log("info", "streak " + account.label + ": draw " + (draw + 1) + "/" + chances + " " + JSON.stringify(prize).slice(0, 160));
12713
14147
  }
14148
+ } catch (error) {
14149
+ detail.failed += 1;
14150
+ log("warn", "streak " + account.label + ": lottery: " + safeMessage(error));
12714
14151
  }
12715
- if (claimed === 0 && failed > 0) throw panelError("the task rewards could not be claimed", "UPSTREAM");
12716
14152
  return {
12717
14153
  claimed,
12718
14154
  credit,
12719
- energy
14155
+ energy,
14156
+ detail
12720
14157
  };
12721
14158
  }
12722
14159
  /**
12723
- * Collect the streak bonus and the task rewards of every domestic account.
14160
+ * Collect the streak bonus of every account.
12724
14161
  *
12725
- * Both are idempotent, so a pass that finds nothing to collect costs the reads
12726
- * and no mutation, and running it on the daily schedule cannot double-pay. One
12727
- * account failing never stops the rest. International accounts have no growth
12728
- * centre, so they are skipped without a call.
14162
+ * Idempotent, so a pass that finds nothing to collect costs the reads and no
14163
+ * mutation, and running it on the daily schedule cannot double-pay. One account
14164
+ * failing never stops the rest.
12729
14165
  */
12730
14166
  async function claimAllGrowth() {
12731
14167
  const counts = {
12732
14168
  streak: 0,
12733
- tasks: 0,
12734
14169
  credit: 0,
12735
- failed: 0
14170
+ failed: 0,
14171
+ detail: emptyGrowthDetail()
12736
14172
  };
12737
14173
  let seen = 0;
12738
14174
  for (const account of core.pool.list()) {
14175
+ if (currentCheckinSignal().aborted) break;
12739
14176
  if (core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
12740
- if (regionOf(account.credential.domain) !== "cn") continue;
12741
- if (checkinAbort.signal.aborted) break;
12742
14177
  if (seen > 0) await checkinDelay(GROWTH_ACCOUNT_DELAY_MS);
12743
14178
  seen += 1;
14179
+ counts.detail.accounts += 1;
12744
14180
  let collected = false;
12745
14181
  try {
12746
14182
  const streak = await redeemAccountStreak(account);
12747
14183
  counts.streak += streak.claimed;
12748
14184
  counts.credit += streak.credit;
12749
14185
  if (streak.claimed > 0) collected = true;
14186
+ mergeGrowthDetail(counts.detail, streak.detail);
12750
14187
  } catch (error) {
12751
14188
  counts.failed += 1;
12752
- log("warn", "streak failed for " + account.label + ": " + messageOf(error));
14189
+ counts.detail.failed += 1;
14190
+ log("warn", "streak failed for " + account.label + ": " + safeMessage(error));
12753
14191
  }
14192
+ if (collected) probeCache.delete(account.id);
14193
+ }
14194
+ return counts;
14195
+ }
14196
+ /** A growth breakdown with everything at zero, for a pass that found nothing. */
14197
+ function emptyGrowthDetail() {
14198
+ return {
14199
+ accounts: 0,
14200
+ makeup: 0,
14201
+ gift: 0,
14202
+ compensation: 0,
14203
+ activity: 0,
14204
+ streak: 0,
14205
+ lottery: 0,
14206
+ failed: 0
14207
+ };
14208
+ }
14209
+ /** Add one account's step counts into the pass total. */
14210
+ function mergeGrowthDetail(total, part) {
14211
+ for (const key of Object.keys(total)) if (typeof part[key] === "number") total[key] += part[key];
14212
+ }
14213
+ /**
14214
+ * What the growth centre holds right now, without claiming anything.
14215
+ *
14216
+ * Read-only, so the panel can show the state before the user decides to spend
14217
+ * a make-up card or a draw: those two are the only steps of the pass that are
14218
+ * not idempotent, and a blind \"run\" would spend them without saying so.
14219
+ *
14220
+ * One row per account rather than one merged total. The streak, the tier it is
14221
+ * walking towards and the cards it holds are facts about one account, and a
14222
+ * total across them names no account: with two sign-ins the old merged line
14223
+ * showed whichever account was read last. The panel expands a row for the
14224
+ * tier detail behind it.
14225
+ *
14226
+ * One account's two reads run together and the accounts run together too,
14227
+ * like the credit probe: this is on demand, one button, and a serial pass over
14228
+ * several sign-ins would make the panel feel broken.
14229
+ */
14230
+ async function readGrowthState() {
14231
+ const rows = [];
14232
+ let failed = 0;
14233
+ const wanted = core.pool.list().filter((account) => !core.pool.isDisabled(account.id) && regionEnabled("workbuddy", regionOf(account.credential.domain)));
14234
+ const reads = await Promise.all(wanted.map(async (account) => {
12754
14235
  try {
12755
- const tasks = await claimAccountTasks(account);
12756
- counts.tasks += tasks.claimed;
12757
- counts.credit += tasks.credit;
12758
- if (tasks.claimed > 0) collected = true;
14236
+ const [streak, chances] = await Promise.all([core.client.growthStreakFull(account.credential), core.client.lotteryChances(account.credential)]);
14237
+ return {
14238
+ account,
14239
+ streak,
14240
+ chances
14241
+ };
12759
14242
  } catch (error) {
12760
- counts.failed += 1;
12761
- log("warn", "tasks failed for " + account.label + ": " + messageOf(error));
14243
+ log("warn", "growth state failed for " + account.label + ": " + safeMessage(error));
14244
+ return {
14245
+ account,
14246
+ error
14247
+ };
12762
14248
  }
12763
- if (collected) probeCache.delete(account.id);
14249
+ }));
14250
+ for (const read of reads) {
14251
+ const region = regionOf(read.account.credential.domain);
14252
+ if (read.error !== void 0) {
14253
+ failed += 1;
14254
+ rows.push({
14255
+ id: read.account.id,
14256
+ label: read.account.label,
14257
+ region,
14258
+ failed: true
14259
+ });
14260
+ continue;
14261
+ }
14262
+ const streak = read.streak;
14263
+ rows.push({
14264
+ id: read.account.id,
14265
+ label: read.account.label,
14266
+ region,
14267
+ days: streak.days,
14268
+ nextTier: streak.nextTier,
14269
+ nextTierRemaining: streak.nextTierRemaining,
14270
+ tiers: streak.tiers.filter((tier) => tier.status === "unlocked").length,
14271
+ tierList: streak.tiers,
14272
+ makeupCards: streak.makeupCards,
14273
+ lottery: read.chances
14274
+ });
12764
14275
  }
12765
- return counts;
14276
+ return {
14277
+ accounts: rows.length,
14278
+ failed,
14279
+ rows
14280
+ };
12766
14281
  }
12767
14282
  /**
12768
14283
  * Whether an upstream refusal means "the day was already collected".
12769
14284
  *
12770
- * Matched on the whole sentence, not on the bare word: a refusal whose text
12771
- * merely contains "already" (a token or account refusal often does) used to be
12772
- * counted as a benign skip, which hid a real breakage from the last-run line
12773
- * and from the check-in summary the user reads.
14285
+ * Matched on the whole sentence, not on the bare word: a token or account
14286
+ * refusal often merely contains "already", and counting that as a benign skip
14287
+ * hides a real breakage from the last-run line and from the check-in summary
14288
+ * the user reads.
12774
14289
  */
12775
14290
  function isAlreadyCheckin(error) {
12776
- const message = messageOf(error).toLowerCase();
14291
+ const message = safeMessage(error).toLowerCase();
12777
14292
  return message.includes("已签到") || message.includes("已经签到") || message.includes("already checked in") || message.includes("already signed in") || message.includes("already claimed") || message.includes("already received");
12778
14293
  }
12779
14294
  async function claimAllCheckins() {
@@ -12785,7 +14300,7 @@ async function claimAllCheckins() {
12785
14300
  let seen = 0;
12786
14301
  for (const account of core.pool.list()) {
12787
14302
  if (core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
12788
- if (checkinAbort.signal.aborted) break;
14303
+ if (currentCheckinSignal().aborted) break;
12789
14304
  if (seen > 0) await checkinDelay(CHECKIN_ACCOUNT_DELAY_MS);
12790
14305
  seen += 1;
12791
14306
  try {
@@ -12804,7 +14319,7 @@ async function claimAllCheckins() {
12804
14319
  continue;
12805
14320
  }
12806
14321
  counts.failed += 1;
12807
- log("warn", "check-in failed for " + account.label + ": " + messageOf(error));
14322
+ log("warn", "check-in failed for " + account.label + ": " + safeMessage(error));
12808
14323
  }
12809
14324
  }
12810
14325
  return counts;
@@ -12831,24 +14346,24 @@ async function travelAdopt(account) {
12831
14346
  try {
12832
14347
  await core.client.reportChatActivity(account.credential, conversationId);
12833
14348
  } catch (error) {
12834
- log("warn", "travel " + account.label + ": adopt preflight report: " + messageOf(error));
14349
+ log("warn", "travel " + account.label + ": adopt preflight report: " + safeMessage(error));
12835
14350
  }
12836
14351
  await checkinDelay(TRAVEL_ADOPT_GAP_MS);
12837
14352
  try {
12838
14353
  await core.client.agreeBuddy(account.credential);
12839
14354
  } catch (error) {
12840
- log("warn", "travel " + account.label + ": agreement: " + messageOf(error));
14355
+ log("warn", "travel " + account.label + ": agreement: " + safeMessage(error));
12841
14356
  return "failed";
12842
14357
  }
12843
14358
  try {
12844
14359
  await core.client.adoptBuddy(account.credential);
12845
14360
  } catch (error) {
12846
- if (isBuddyThresholdIncomplete(messageOf(error))) {
14361
+ if (isBuddyThresholdIncomplete(safeMessage(error))) {
12847
14362
  travelAdoptTried.set(account.id, day);
12848
14363
  log("info", "travel " + account.label + ": adopt skipped (conversation threshold not reached, retry tomorrow)");
12849
14364
  return "skipped";
12850
14365
  }
12851
- log("warn", "travel " + account.label + ": adopt: " + messageOf(error));
14366
+ log("warn", "travel " + account.label + ": adopt: " + safeMessage(error));
12852
14367
  return "failed";
12853
14368
  }
12854
14369
  log("info", "travel " + account.label + ": adopt ok");
@@ -12865,7 +14380,7 @@ async function travelOne(account) {
12865
14380
  try {
12866
14381
  buddy = await core.client.fetchBuddyInfo(account.credential);
12867
14382
  } catch (error) {
12868
- log("warn", "travel " + account.label + ": buddy-info: " + messageOf(error));
14383
+ log("warn", "travel " + account.label + ": buddy-info: " + safeMessage(error));
12869
14384
  return "failed";
12870
14385
  }
12871
14386
  if (buddy === null) return await travelAdopt(account);
@@ -12873,7 +14388,7 @@ async function travelOne(account) {
12873
14388
  try {
12874
14389
  status = await core.client.fetchTravelStatus(account.credential);
12875
14390
  } catch (error) {
12876
- log("warn", "travel " + account.label + ": status: " + messageOf(error));
14391
+ log("warn", "travel " + account.label + ": status: " + safeMessage(error));
12877
14392
  return "failed";
12878
14393
  }
12879
14394
  if (status.state === "arrived") {
@@ -12886,7 +14401,7 @@ async function travelOne(account) {
12886
14401
  log("info", "travel " + account.label + ": claim ok record=" + status.recordId + " reward=" + reward);
12887
14402
  return "claimed";
12888
14403
  } catch (error) {
12889
- log("warn", "travel " + account.label + ": claim record=" + status.recordId + ": " + messageOf(error));
14404
+ log("warn", "travel " + account.label + ": claim record=" + status.recordId + ": " + safeMessage(error));
12890
14405
  return "failed";
12891
14406
  }
12892
14407
  }
@@ -12900,7 +14415,7 @@ async function travelOne(account) {
12900
14415
  log("info", "travel " + account.label + ": depart ok location=4");
12901
14416
  return "departed";
12902
14417
  } catch (error) {
12903
- log("warn", "travel " + account.label + ": depart: " + messageOf(error));
14418
+ log("warn", "travel " + account.label + ": depart: " + safeMessage(error));
12904
14419
  return "failed";
12905
14420
  }
12906
14421
  }
@@ -12928,7 +14443,7 @@ async function travelAllAccounts() {
12928
14443
  if (core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
12929
14444
  if (regionOf(account.credential.domain) !== "cn") continue;
12930
14445
  if (!account.credential.refreshToken) continue;
12931
- if (checkinAbort.signal.aborted) break;
14446
+ if (currentCheckinSignal().aborted) break;
12932
14447
  if (seen > 0) await checkinDelay(TRAVEL_ACCOUNT_DELAY_MS);
12933
14448
  seen += 1;
12934
14449
  try {
@@ -12936,10 +14451,10 @@ async function travelAllAccounts() {
12936
14451
  if (outcome === "departed" || outcome === "claimed" || outcome === "adopted") {
12937
14452
  counts[outcome === "departed" ? "departed" : outcome === "claimed" ? "claimed" : "adopted"] += 1;
12938
14453
  probeCache.delete(account.id);
12939
- }
14454
+ } else if (outcome === "failed") counts.failed += 1;
12940
14455
  } catch (error) {
12941
14456
  counts.failed += 1;
12942
- log("warn", "travel failed for " + account.label + ": " + messageOf(error));
14457
+ log("warn", "travel failed for " + account.label + ": " + safeMessage(error));
12943
14458
  }
12944
14459
  }
12945
14460
  return counts;
@@ -12973,7 +14488,7 @@ async function qoderCheckinAll() {
12973
14488
  let seen = 0;
12974
14489
  for (const credential of found.credentials) {
12975
14490
  if (!regions.includes(credential.region)) continue;
12976
- if (checkinAbort.signal.aborted) break;
14491
+ if (currentCheckinSignal().aborted) break;
12977
14492
  if (seen > 0) await checkinDelay(QODER_ACCOUNT_DELAY_MS);
12978
14493
  seen += 1;
12979
14494
  const result = await qoderClaimFor(credential);
@@ -13051,7 +14566,7 @@ async function traeCheckinAll() {
13051
14566
  const cnCredentials = found.credentials.filter((credential) => traeRegionOfCredential(credential) === "cn");
13052
14567
  let index = 0;
13053
14568
  for (; index < cnCredentials.length; index += 1) {
13054
- if (checkinAbort.signal.aborted) break;
14569
+ if (currentCheckinSignal().aborted) break;
13055
14570
  if (index > 0) await checkinDelay(Math.max(1e3, TRAE_ACCOUNT_DELAY_MS + Math.round((Math.random() * 2 - 1) * TRAE_ACCOUNT_JITTER_MS)));
13056
14571
  const result = await traeClaimFor(cnCredentials[index], desktopCandidates);
13057
14572
  counts[result.outcome] += 1;
@@ -13185,19 +14700,21 @@ async function autoCheckinTick(now) {
13185
14700
  if (!autoCheckinEnabled()) return void 0;
13186
14701
  const when = now === void 0 ? /* @__PURE__ */ new Date() : now;
13187
14702
  if (qoderRetryAt !== 0 && when.getTime() >= qoderRetryAt && activeQoderRegions().length > 0) {
13188
- if (checkinPassRunning) {
14703
+ if (checkinPassRunning || growthPassRunning) {
13189
14704
  log("info", "deferred Qoder check-in deferred: a pass is already running");
13190
14705
  return autoCheckinLast;
13191
14706
  }
13192
14707
  const retryGeneration = loadGeneration;
13193
14708
  checkinPassRunning = true;
13194
14709
  const token = ++checkinPassToken;
14710
+ checkinAbort.abort();
13195
14711
  checkinAbort = new AbortController();
14712
+ checkinScope.enterWith(checkinAbort.signal);
13196
14713
  try {
13197
14714
  qoderRetryAt = 0;
13198
14715
  const retry = await qoderCheckinAll();
13199
14716
  if (!stillLoaded(retryGeneration)) return autoCheckinLast;
13200
- qoderRetryAt = typeof retry.opensAt === "number" && retry.opensAt > Date.now() ? retry.opensAt : 0;
14717
+ qoderRetryAt = typeof retry.opensAt === "number" && retry.opensAt > Date.now() ? retry.opensAt : Number(retry.failed) > 0 && Number(retry.claimed) === 0 ? Date.now() + QODER_RETRY_BACKOFF_MS : 0;
13201
14718
  const claimedBefore = Number(autoCheckinLast?.qoder?.claimed) || 0;
13202
14719
  autoCheckinLast = {
13203
14720
  ...autoCheckinLast,
@@ -13222,7 +14739,7 @@ async function autoCheckinTick(now) {
13222
14739
  },
13223
14740
  at: (/* @__PURE__ */ new Date()).toISOString()
13224
14741
  };
13225
- log("warn", "deferred Qoder check-in failed: " + messageOf(error));
14742
+ log("warn", "deferred Qoder check-in failed: " + safeMessage(error));
13226
14743
  }
13227
14744
  } finally {
13228
14745
  if (token === checkinPassToken) checkinPassRunning = false;
@@ -13243,7 +14760,7 @@ function startAutoCheckin() {
13243
14760
  if (autoCheckinTimer !== null) return;
13244
14761
  if (serviceStopped) return;
13245
14762
  autoCheckinTimer = setInterval(() => {
13246
- autoCheckinTick().catch((error) => log("warn", "scheduled check-in failed: " + messageOf(error)));
14763
+ autoCheckinTick().catch((error) => log("warn", "scheduled check-in failed: " + safeMessage(error)));
13247
14764
  }, CHECKIN_POLL_MS);
13248
14765
  if (typeof autoCheckinTimer.unref === "function") autoCheckinTimer.unref();
13249
14766
  }
@@ -13258,6 +14775,78 @@ function applyAutoCheckin() {
13258
14775
  else stopAutoCheckin();
13259
14776
  }
13260
14777
  /**
14778
+ * Refresh every eligible account's token, by hand.
14779
+ *
14780
+ * `ensureFresh` decides per account whether an upstream call is needed, so an
14781
+ * account whose token still has hours on it costs nothing and an international
14782
+ * token that lives a year is never touched. What the pass buys is the account
14783
+ * nobody has used since its token expired: without it that account is refreshed
14784
+ * by the first request that arrives, which pays the round trip on the user's
14785
+ * own turn and, when the refresh token is dead too, fails that turn instead of
14786
+ * this one.
14787
+ *
14788
+ * Disabled and switched-off-region accounts stay out, matching every other
14789
+ * pass: a parked account is parked on purpose.
14790
+ */
14791
+ async function keepAliveTokens() {
14792
+ const counts = {
14793
+ refreshed: 0,
14794
+ fresh: 0,
14795
+ failed: 0,
14796
+ noToken: 0
14797
+ };
14798
+ for (const account of core.pool.list()) {
14799
+ if (serviceStopped) break;
14800
+ if (core.pool.isDisabled(account.id)) continue;
14801
+ if (!regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
14802
+ const outcome = await core.pool.ensureFresh(account);
14803
+ counts[outcome] = (counts[outcome] ?? 0) + 1;
14804
+ }
14805
+ return counts;
14806
+ }
14807
+ /** Run one keep-alive pass and record it for the panel. */
14808
+ async function runKeepAlivePass() {
14809
+ if (serviceStopped) return null;
14810
+ const generation = loadGeneration;
14811
+ const counts = await keepAliveTokens();
14812
+ if (stillLoaded(generation)) {
14813
+ keepAliveLast = {
14814
+ at: (/* @__PURE__ */ new Date()).toISOString(),
14815
+ ...counts
14816
+ };
14817
+ scheduleRefresh("keep-alive");
14818
+ }
14819
+ return counts;
14820
+ }
14821
+ /**
14822
+ * Re-read the sign-ins on a timer while the service runs.
14823
+ *
14824
+ * The pool scans at load, when the panel opens and when it runs dry. None of
14825
+ * those happens between two account switches in the desktop client, and the
14826
+ * global client keeps one live file: the sign-in that was overwritten in that
14827
+ * gap was never read, so it could not be archived either. A read this often is
14828
+ * what turns "the account I had before" into one the pool still holds.
14829
+ *
14830
+ * Chained rather than an interval, so a slow walk is followed by one pause
14831
+ * instead of a queue of walks on top of each other.
14832
+ */
14833
+ function startAccountWatch() {
14834
+ if (accountWatchTimer !== null || serviceStopped) return;
14835
+ const read = () => {
14836
+ accountWatchTimer = null;
14837
+ if (serviceStopped) return;
14838
+ if (activeRegions().length > 0) core.pool.scan().catch((error) => log("warn", "account re-read failed: " + safeMessage(error)));
14839
+ startAccountWatch();
14840
+ };
14841
+ accountWatchTimer = setTimeout(read, ACCOUNT_WATCH_MS);
14842
+ if (typeof accountWatchTimer.unref === "function") accountWatchTimer.unref();
14843
+ }
14844
+ function stopAccountWatch() {
14845
+ if (accountWatchTimer === null) return;
14846
+ clearTimeout(accountWatchTimer);
14847
+ accountWatchTimer = null;
14848
+ }
14849
+ /**
13261
14850
  * Bring the declaration up to date BEFORE the host can act on it.
13262
14851
  *
13263
14852
  * Registration is a runtime call and the host serves whatever the last
@@ -13304,6 +14893,7 @@ async function onServiceStart() {
13304
14893
  }
13305
14894
  applySettingsToCore();
13306
14895
  reconcileRuntimes();
14896
+ startAccountWatch();
13307
14897
  const { left: bootstrapLeft } = budget(SERVICE_BOOTSTRAP_BUDGET_MS);
13308
14898
  await settleWithin(reconcileTraeGateways(), bootstrapLeft());
13309
14899
  await settleWithin(reconcileQoderGateways(), bootstrapLeft());
@@ -13329,12 +14919,15 @@ async function onServiceStop() {
13329
14919
  }
13330
14920
  refreshInflight = null;
13331
14921
  stopAutoCheckin();
14922
+ stopAccountWatch();
13332
14923
  abortWarmups();
14924
+ clearModelRetries();
13333
14925
  checkinAbort.abort();
13334
14926
  const closing = Array.from(runtimes.values()).map(stopRuntime);
13335
14927
  runtimes.clear();
14928
+ runtimeStarts.clear();
13336
14929
  for (const entry of [...traeGateways.values(), ...qoderGateways.values()]) closing.push(entry.gateway.close().catch((error) => {
13337
- log("warn", "[" + entry.source + ":" + entry.region + "] gateway did not close cleanly: " + messageOf(error));
14930
+ log("warn", "[" + entry.source + ":" + entry.region + "] gateway did not close cleanly: " + safeMessage(error));
13338
14931
  }));
13339
14932
  traeGateways.clear();
13340
14933
  qoderGateways.clear();
@@ -13343,17 +14936,39 @@ async function onServiceStop() {
13343
14936
  async function onLoad() {
13344
14937
  serviceStopped = false;
13345
14938
  loadGeneration += 1;
14939
+ abortWarmups();
13346
14940
  warmAbort = new AbortController();
14941
+ checkinAbort.abort();
13347
14942
  checkinAbort = new AbortController();
14943
+ stopAutoCheckin();
14944
+ stopAccountWatch();
14945
+ clearModelRetries();
14946
+ if (refreshTimer !== null) {
14947
+ clearTimeout(refreshTimer);
14948
+ refreshTimer = null;
14949
+ }
14950
+ refreshInflight = null;
14951
+ for (const runtime of runtimes.values()) pendingRuntimeStops.push(stopRuntime(runtime));
14952
+ runtimes.clear();
14953
+ runtimeStarts.clear();
14954
+ for (const entry of [...traeGateways.values(), ...qoderGateways.values()]) pendingRuntimeStops.push(entry.gateway.close().catch((error) => {
14955
+ log("warn", "[" + entry.source + ":" + entry.region + "] gateway did not close cleanly: " + safeMessage(error));
14956
+ }));
14957
+ traeGateways.clear();
14958
+ qoderGateways.clear();
13348
14959
  checkinPassRunning = false;
13349
14960
  autoCheckinSlots.clear();
13350
14961
  autoCheckinLast = null;
14962
+ growthPassRunning = false;
14963
+ growthLast = null;
14964
+ keepAliveLast = null;
13351
14965
  qoderRetryAt = 0;
13352
- core.client = new WorkBuddyUpstreamClient();
14966
+ core.client = new WorkBuddyUpstreamClient({ fetchImpl: clientNameRewritingFetch(replacedClientName) });
13353
14967
  core.pool = new WorkBuddyAccountPool({
13354
14968
  client: core.client,
13355
14969
  cooldownMs: cooldownMs(),
13356
14970
  distribution: distributionSetting(),
14971
+ dataPath: () => dataPath,
13357
14972
  logger: {
13358
14973
  info: (...args) => log("info", gatewayLogLine("", args)),
13359
14974
  warn: (...args) => log("warn", gatewayLogLine("", args)),
@@ -13368,12 +14983,10 @@ async function onLoad() {
13368
14983
  dataPath = await pi.plugin.getDataPath();
13369
14984
  } catch (error) {
13370
14985
  dataPath = "";
13371
- log("warn", "no plugin data path: " + messageOf(error));
14986
+ log("warn", "no plugin data path: " + safeMessage(error));
13372
14987
  }
13373
14988
  loadCheckinSlots();
13374
14989
  if (serviceStopped) return;
13375
- await registerCommands();
13376
- if (serviceStopped) return;
13377
14990
  pi.services.register({
13378
14991
  id: SERVICE_ID,
13379
14992
  start: onServiceStart,
@@ -13389,6 +15002,8 @@ async function onUnload() {
13389
15002
  refreshTimer = null;
13390
15003
  }
13391
15004
  stopAutoCheckin();
15005
+ stopAccountWatch();
15006
+ clearModelRetries();
13392
15007
  abortWarmups();
13393
15008
  await onServiceStop();
13394
15009
  probeCache.clear();
@@ -13401,23 +15016,27 @@ async function onUnload() {
13401
15016
  try {
13402
15017
  if (pi.events && typeof pi.events.off === "function" && settingsChangedHandler !== null) pi.events.off("plugin:settingsChanged", settingsChangedHandler);
13403
15018
  } catch (error) {
13404
- log("warn", "could not unsubscribe from settings changes: " + messageOf(error));
15019
+ log("warn", "could not unsubscribe from settings changes: " + safeMessage(error));
13405
15020
  }
13406
15021
  settingsChangedHandler = null;
13407
- try {
13408
- await pi.commands.unregister(COMMAND_OPEN);
13409
- await pi.commands.unregister(COMMAND_RESCAN);
13410
- await pi.commands.unregister(COMMAND_RESET);
13411
- await pi.commands.unregister(COMMAND_DOCTOR);
13412
- await pi.commands.unregister(COMMAND_CHECKIN);
13413
- } catch (error) {
13414
- log("warn", "unregistering commands failed: " + messageOf(error));
13415
- }
13416
15022
  }
13417
15023
  function composerPointsEnabled() {
13418
15024
  return settings.showComposerPoints === true;
13419
15025
  }
13420
15026
  /**
15027
+ * The name this plugin sends as the client when the user turns the rewrite on.
15028
+ *
15029
+ * WorkBuddy's domestic host refuses a request whose prompt names DeepSeek
15030
+ * Harness (`11128`, channel check) on every account of that region, so the panel
15031
+ * offers a switch that renames the client in the outgoing prompt. "DeepSeek" is
15032
+ * the vendor that actually serves the model, so the sentences stay true, and it
15033
+ * was verified against the live host: the two prompts it refuses are accepted
15034
+ * with the product name replaced.
15035
+ */
15036
+ function replacedClientName() {
15037
+ return settings.rewriteClientName === true ? "DeepSeek" : void 0;
15038
+ }
15039
+ /**
13421
15040
  * The source and region one selected provider route belongs to.
13422
15041
  *
13423
15042
  * The composer readout is handed the session's selection straight from the
@@ -13495,9 +15114,7 @@ function workbuddyComposerAccounts(region, modelId) {
13495
15114
  const list = core.pool.list(region);
13496
15115
  const available = core.pool.available(now, modelId, region);
13497
15116
  const preferredId = preferredAccountId(region);
13498
- const preferred = available.find((account) => account.id === preferredId);
13499
- const namesNext = distributionSetting() === "priority" || distributionSetting() === "expiry";
13500
- const next = preferred ?? (namesNext ? core.pool.preview(available) : void 0);
15117
+ const next = available.find((account) => account.id === preferredId) ?? core.pool.preview(available);
13501
15118
  return list.map((account) => {
13502
15119
  const cached = probeCache.get(account.id)?.value?.credits;
13503
15120
  return {
@@ -13512,15 +15129,7 @@ function workbuddyComposerAccounts(region, modelId) {
13512
15129
  function sourceComposerAccounts(source, region) {
13513
15130
  const rows = (source === "trae" ? traeAccountRows : qoderAccountRows).filter((row) => row.region === region);
13514
15131
  const live = rows.filter((row) => row.expired !== true);
13515
- const preferred = preferredSourceAccount(source, region);
13516
- let active = preferred === "" ? void 0 : live.find((row) => row.label === preferred);
13517
- if (active === void 0) {
13518
- const mode = sourceDistribution(source);
13519
- if (mode === "expiry") {
13520
- const now = Date.now();
13521
- active = live.slice().sort((left, right) => packUrgency(source, left.label, now) - packUrgency(source, right.label, now))[0];
13522
- } else if (mode !== "round-robin") active = live[0];
13523
- }
15132
+ const active = orderSourceCredentials(source, region, live, (row) => row.label, false)[0];
13524
15133
  return rows.map((row) => {
13525
15134
  const credits = row.usage?.credits;
13526
15135
  return {
@@ -13752,6 +15361,7 @@ const Config = z.object({
13752
15361
  preferredSourceAccounts: asVolatile(z.any().description("Picked Trae/Qoder account per region")),
13753
15362
  removedAccounts: asVolatile(z.any().description("Accounts removed from the pool for good")),
13754
15363
  showComposerPoints: asVolatile(z.boolean().default(false).description("Show the active account credits beside the composer")),
15364
+ rewriteClientName: asVolatile(z.boolean().default(false).description("Rename the client in the prompt WorkBuddy receives (domestic channel check 11128)")),
13755
15365
  sourceDistributions: asVolatile(z.any().description("How each Trae/Qoder region spreads requests"))
13756
15366
  });
13757
15367
  /** Peel one volatile reference, if the running line wrapped it. */
@@ -13988,8 +15598,6 @@ function registrationFingerprint(descriptors) {
13988
15598
  function apply(ctx, config = {}) {
13989
15599
  const current = () => unwrapVolatileDeep(config);
13990
15600
  const settingsNamespace = settingsNamespaceOf(ctx);
13991
- const commandNotes = new AsyncLocalStorage();
13992
- const commands = /* @__PURE__ */ new Map();
13993
15601
  const settingsListeners = /* @__PURE__ */ new Map();
13994
15602
  const settingsHandlers = /* @__PURE__ */ new Set();
13995
15603
  const token = activationToken += 1;
@@ -14074,46 +15682,6 @@ function apply(ctx, config = {}) {
14074
15682
  settingsListeners.get(handler)?.();
14075
15683
  settingsListeners.delete(handler);
14076
15684
  },
14077
- notify: (text, kind) => {
14078
- commandNotes.getStore()?.push(text);
14079
- const line = `dsh-wtq-pool: ${text}`;
14080
- if (kind === "warn") ctx.logger.warn?.(line);
14081
- else ctx.logger.info?.(line);
14082
- },
14083
- openPanel: () => {
14084
- commandNotes.getStore()?.push("面板在 插件页 → 「账号池」卡片");
14085
- },
14086
- registerCommand: async (spec) => {
14087
- const service = ctx.get("commands");
14088
- if (service === void 0) return;
14089
- const commandName = spec.id.replace(/[^a-z0-9_-]+/gi, "-").toLowerCase();
14090
- const dispose = service.register({
14091
- name: commandName,
14092
- description: spec.title,
14093
- handler: async () => {
14094
- const notes = [];
14095
- return commandNotes.run(notes, async () => {
14096
- try {
14097
- await spec.run();
14098
- return {
14099
- kind: "success",
14100
- text: notes.join("\n") || spec.title
14101
- };
14102
- } catch (error) {
14103
- return {
14104
- kind: "error",
14105
- text: safeMessage(error)
14106
- };
14107
- }
14108
- });
14109
- }
14110
- });
14111
- if (typeof dispose === "function") commands.set(spec.id, dispose);
14112
- },
14113
- unregisterCommand: async (id) => {
14114
- commands.get(id)?.();
14115
- commands.delete(id);
14116
- },
14117
15685
  /**
14118
15686
  * Publish the provider rows.
14119
15687
  *
@@ -14226,8 +15794,6 @@ function apply(ctx, config = {}) {
14226
15794
  ctx.effect(() => async () => {
14227
15795
  stopped = true;
14228
15796
  lastRows = [];
14229
- for (const dispose of commands.values()) dispose();
14230
- commands.clear();
14231
15797
  for (const dispose of settingsListeners.values()) dispose();
14232
15798
  settingsListeners.clear();
14233
15799
  disposeRegistration?.();