dsh-wtq-pool 1.0.4 → 1.0.5

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;
@@ -8495,7 +9402,7 @@ function bridgeQoderStream(source, model, options = {}) {
8495
9402
  if (typeof finish === "string" && finish !== "" && finish !== "null") {
8496
9403
  if (!emittedFinishReason) {
8497
9404
  emittedFinishReason = true;
8498
- controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : finish));
9405
+ controller.enqueue(chunk({}, openAIFinishReason(finish, sawToolCalls)));
8499
9406
  endSoon();
8500
9407
  }
8501
9408
  }
@@ -8588,7 +9495,7 @@ function bridgeQoderStream(source, model, options = {}) {
8588
9495
  if (!finished) {
8589
9496
  if (!emittedFinishReason) {
8590
9497
  emittedFinishReason = true;
8591
- controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : "stop"));
9498
+ controller.enqueue(chunk({}, openAIFinishReason(void 0, sawToolCalls)));
8592
9499
  }
8593
9500
  finalize();
8594
9501
  }
@@ -8613,7 +9520,7 @@ function bridgeQoderStream(source, model, options = {}) {
8613
9520
  })}\n\n`));
8614
9521
  if (!emittedFinishReason) {
8615
9522
  emittedFinishReason = true;
8616
- controller.enqueue(chunk({}, sawToolCalls ? "tool_calls" : "stop"));
9523
+ controller.enqueue(chunk({}, openAIFinishReason(void 0, sawToolCalls)));
8617
9524
  }
8618
9525
  finalize();
8619
9526
  }
@@ -9016,6 +9923,157 @@ function createQoderGateway(options) {
9016
9923
  };
9017
9924
  }
9018
9925
  //#endregion
9926
+ //#region src/login.ts
9927
+ /** The domestic gateway, which serves the domestic login page. */
9928
+ const CN_BASE = "https://copilot.tencent.com";
9929
+ /** The international gateway. */
9930
+ const GLOBAL_BASE = "https://www.workbuddy.ai";
9931
+ /** Billing origin the domestic login page is served from. */
9932
+ const CN_ORIGIN = "https://www.codebuddy.cn";
9933
+ /** The international login page is same-origin with its gateway. */
9934
+ const GLOBAL_ORIGIN = "https://www.workbuddy.ai";
9935
+ /**
9936
+ * The CLI's own user agent.
9937
+ *
9938
+ * The endpoints answer this spelling and turn the plugin's other ones away,
9939
+ * and the page it opens belongs to the same client channel — a different
9940
+ * spelling there is answered as an unknown platform.
9941
+ */
9942
+ const LOGIN_UA = "CLI/2.63.2 CodeBuddy/2.63.2";
9943
+ const REQUEST_TIMEOUT_MS = 3e4;
9944
+ /**
9945
+ * Domain stamped on a sign-in whose answer carried none.
9946
+ *
9947
+ * `regionOf` reads an empty domain as CN, so a global login that arrives
9948
+ * without one would be filed under the domestic gateway, which refuses its
9949
+ * token at the openresty layer with an HTML 401 instead of a business error.
9950
+ */
9951
+ const DEFAULT_DOMAIN = {
9952
+ cn: "www.codebuddy.cn",
9953
+ global: "www.workbuddy.ai"
9954
+ };
9955
+ function baseFor(realm) {
9956
+ return realm === "global" ? GLOBAL_BASE : CN_BASE;
9957
+ }
9958
+ function originFor(realm) {
9959
+ return realm === "global" ? GLOBAL_ORIGIN : CN_ORIGIN;
9960
+ }
9961
+ /** Browser-shaped headers; `Origin` is the one the endpoints check. */
9962
+ function loginHeaders(origin) {
9963
+ return {
9964
+ "Accept": "application/json, text/plain, */*",
9965
+ "Content-Type": "application/json",
9966
+ "Origin": origin,
9967
+ "Referer": `${origin}/`,
9968
+ "User-Agent": LOGIN_UA,
9969
+ "X-Requested-With": "XMLHttpRequest"
9970
+ };
9971
+ }
9972
+ async function callLogin(url, headers, fetchImpl, body) {
9973
+ const response = await fetchImpl(url, {
9974
+ redirect: "error",
9975
+ method: body === void 0 ? "GET" : "POST",
9976
+ headers,
9977
+ ...body === void 0 ? {} : { body },
9978
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
9979
+ });
9980
+ const text = await response.text();
9981
+ if (!response.ok) throw new Error(`workbuddy login endpoint answered ${response.status}`);
9982
+ let parsed;
9983
+ try {
9984
+ parsed = JSON.parse(text);
9985
+ } catch {
9986
+ throw new Error("workbuddy login endpoint did not answer JSON");
9987
+ }
9988
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("workbuddy login endpoint did not answer an object");
9989
+ const document = parsed;
9990
+ const data = typeof document["data"] === "object" && document["data"] !== null ? document["data"] : {};
9991
+ return {
9992
+ code: typeof document["code"] === "number" ? document["code"] : -1,
9993
+ msg: typeof document["msg"] === "string" ? document["msg"] : "",
9994
+ data
9995
+ };
9996
+ }
9997
+ function stringField(data, key) {
9998
+ const value = data[key];
9999
+ return typeof value === "string" ? value : "";
10000
+ }
10001
+ /**
10002
+ * Start a login and answer the URL to open.
10003
+ *
10004
+ * The state is the only thing that ties the browser half to this one, so the
10005
+ * caller keeps it for as long as it polls and drops it afterwards.
10006
+ */
10007
+ async function startDeviceLogin(realm, fetchImpl = fetch) {
10008
+ const envelope = await callLogin(`${baseFor(realm)}/v2/plugin/auth/state?platform=CLI`, loginHeaders(originFor(realm)), fetchImpl, "{}");
10009
+ const state = stringField(envelope.data, "state");
10010
+ const authUrl = stringField(envelope.data, "authUrl");
10011
+ if (state === "" || authUrl === "") throw new Error(`workbuddy login start gave no state or url: ${envelope.msg}`);
10012
+ return {
10013
+ state,
10014
+ authUrl
10015
+ };
10016
+ }
10017
+ /**
10018
+ * Read the account a fresh token belongs to.
10019
+ *
10020
+ * Best effort by design: the token is already good, so an identity that cannot
10021
+ * be read costs the panel a name and the archive a stable key, not the sign-in.
10022
+ */
10023
+ async function readLoginAccount(base, headers, state, accessToken, fetchImpl) {
10024
+ const empty = {
10025
+ uid: "",
10026
+ uin: "",
10027
+ enterpriseId: "",
10028
+ nickname: ""
10029
+ };
10030
+ let envelope;
10031
+ try {
10032
+ envelope = await callLogin(`${base}/v2/plugin/login/account?state=${encodeURIComponent(state)}`, {
10033
+ ...headers,
10034
+ "Authorization": `Bearer ${accessToken}`
10035
+ }, fetchImpl);
10036
+ } catch {
10037
+ return empty;
10038
+ }
10039
+ if (envelope.code !== 0) return empty;
10040
+ return {
10041
+ uid: stringField(envelope.data, "uid"),
10042
+ uin: stringField(envelope.data, "uin"),
10043
+ enterpriseId: stringField(envelope.data, "enterpriseId"),
10044
+ nickname: stringField(envelope.data, "nickname")
10045
+ };
10046
+ }
10047
+ /**
10048
+ * Poll a started login once.
10049
+ *
10050
+ * The token endpoint is the authority on whether the browser has finished: it
10051
+ * answers `code: 0` with the token bundle once it has, and a business error
10052
+ * for as long as it has not. A non-2xx or an unreadable answer throws, because
10053
+ * neither means "keep waiting".
10054
+ */
10055
+ async function pollDeviceLogin(realm, state, fetchImpl = fetch) {
10056
+ const base = baseFor(realm);
10057
+ const headers = loginHeaders(originFor(realm));
10058
+ const token = await callLogin(`${base}/v2/plugin/auth/token?state=${encodeURIComponent(state)}`, headers, fetchImpl);
10059
+ const accessToken = stringField(token.data, "accessToken");
10060
+ if (token.code !== 0 || accessToken === "") return { status: "pending" };
10061
+ const domain = stringField(token.data, "domain");
10062
+ const identity = await readLoginAccount(base, headers, state, accessToken, fetchImpl);
10063
+ const stamped = domain === "" ? DEFAULT_DOMAIN[realm] : domain;
10064
+ return {
10065
+ status: "ok",
10066
+ signIn: {
10067
+ region: regionOf(stamped),
10068
+ accessToken,
10069
+ refreshToken: stringField(token.data, "refreshToken"),
10070
+ expiresAtMs: tokenExpiryMs(typeof token.data["expiresIn"] === "number" ? token.data["expiresIn"] : void 0),
10071
+ domain: stamped,
10072
+ ...identity
10073
+ }
10074
+ };
10075
+ }
10076
+ //#endregion
9019
10077
  //#region src/source-pool.ts
9020
10078
  /**
9021
10079
  * The account pool the Trae and Qoder gateways share.
@@ -9036,11 +10094,22 @@ function createQoderGateway(options) {
9036
10094
  */
9037
10095
  /** Build the pool the Trae and Qoder gateways share, wired to the host's readers. */
9038
10096
  function createSourcePool(host) {
10097
+ /**
10098
+ * The key one account's state is stored under.
10099
+ *
10100
+ * The region belongs in it: one label can name a copy in each region (the
10101
+ * scanner keys its rows by label *and* region for exactly that reason), so a
10102
+ * key without it hands one region's hold and pack expiry to the other region's
10103
+ * account.
10104
+ */
10105
+ function accountStateKey(source, region, label) {
10106
+ return host.sourceRegionKey(source, region) + "\n" + label;
10107
+ }
9039
10108
  /** account key -> the timestamp that account's soonest one-off pack runs out at. */
9040
10109
  const sourceCreditExpiry = /* @__PURE__ */ new Map();
9041
10110
  /** 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);
10111
+ function packUrgency(source, region, label, now) {
10112
+ const at = sourceCreditExpiry.get(accountStateKey(source, region, label));
9044
10113
  return typeof at === "number" && at > now ? at : Infinity;
9045
10114
  }
9046
10115
  /** Where each source region's rotation stands. Advanced once per chat, never by a directory or health read. */
@@ -9050,17 +10119,18 @@ function createSourcePool(host) {
9050
10119
  * keyed the way `sourceCreditExpiry` is.
9051
10120
  */
9052
10121
  const sourceFailureHold = /* @__PURE__ */ new Map();
9053
- function noteSourceFailure(source, label, retryAfter) {
10122
+ function noteSourceFailure(source, region, label, retryAfter) {
9054
10123
  const stated = retryAfterHeader(retryAfter);
9055
10124
  const waitMs = stated === void 0 ? host.cooldownMs() : Number(stated) * 1e3;
9056
- sourceFailureHold.set(source + "\n" + label, Date.now() + waitMs);
10125
+ sourceFailureHold.set(accountStateKey(source, region, label), Date.now() + waitMs);
9057
10126
  }
9058
10127
  /** 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);
10128
+ function sourceFailureActive(source, region, label, now) {
10129
+ const key = accountStateKey(source, region, label);
10130
+ const until = sourceFailureHold.get(key);
9061
10131
  if (until === void 0) return false;
9062
10132
  if (until <= now) {
9063
- sourceFailureHold.delete(source + "\n" + label);
10133
+ sourceFailureHold.delete(key);
9064
10134
  return false;
9065
10135
  }
9066
10136
  return true;
@@ -9092,7 +10162,7 @@ function createSourcePool(host) {
9092
10162
  const preferred = stored !== "" && credentials.some((credential) => labelOf(credential) === stored) ? stored : "";
9093
10163
  const rank = (credential) => {
9094
10164
  const expired = sourceCredentialExpired(credential, now) ? 1 : 0;
9095
- const held = expired === 0 && sourceFailureActive(source, labelOf(credential), now) ? 1 : 0;
10165
+ const held = expired === 0 && sourceFailureActive(source, region, labelOf(credential), now) ? 1 : 0;
9096
10166
  const wanted = preferred !== "" && labelOf(credential) === preferred ? 0 : 1;
9097
10167
  return expired * 4 + held * 2 + wanted;
9098
10168
  };
@@ -9100,24 +10170,31 @@ function createSourcePool(host) {
9100
10170
  if (preferred === "" && host.sourceDistribution(source) === "expiry") {
9101
10171
  const live = ordered.filter((credential) => !sourceCredentialExpired(credential, now));
9102
10172
  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);
10173
+ const healthy = live.filter((credential) => !sourceFailureActive(source, region, labelOf(credential), now));
10174
+ const held = live.filter((credential) => sourceFailureActive(source, region, labelOf(credential), now));
10175
+ const byUrgency = (left, right) => packUrgency(source, region, labelOf(left), now) - packUrgency(source, region, labelOf(right), now);
10176
+ healthy.sort(byUrgency);
10177
+ held.sort(byUrgency);
10178
+ return healthy.concat(held, rest);
9105
10179
  }
9106
10180
  const live = ordered.filter((credential) => !sourceCredentialExpired(credential, now));
9107
10181
  if (rotate !== true || preferred !== "" || live.length < 2 || host.sourceDistribution(source) !== "round-robin") return ordered;
10182
+ const healthy = live.filter((credential) => !sourceFailureActive(source, region, labelOf(credential), now));
10183
+ const held = live.filter((credential) => sourceFailureActive(source, region, labelOf(credential), now));
10184
+ if (healthy.length < 2) return ordered;
9108
10185
  const key = host.sourceRegionKey(source, region);
9109
- const step = (sourceRotation.get(key) ?? 0) % live.length;
10186
+ const step = (sourceRotation.get(key) ?? 0) % healthy.length;
9110
10187
  sourceRotation.set(key, step + 1);
9111
10188
  const rest = ordered.filter((credential) => sourceCredentialExpired(credential, now));
9112
- return live.slice(step).concat(live.slice(0, step), rest);
10189
+ return healthy.slice(step).concat(healthy.slice(0, step), held, rest);
9113
10190
  }
9114
10191
  return {
9115
10192
  sourceCreditExpiry,
9116
10193
  sourceRotation,
9117
10194
  sourceFailureHold,
9118
10195
  sourceCredentialExpired,
10196
+ accountStateKey,
9119
10197
  noteSourceFailure,
9120
- sourceFailureActive,
9121
10198
  packUrgency,
9122
10199
  orderSourceCredentials
9123
10200
  };
@@ -9148,11 +10225,6 @@ function createSourcePool(host) {
9148
10225
  /** Read from the package, so this can never drift behind the version it reports. */
9149
10226
  /** The one background service this plugin registers. */
9150
10227
  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
10228
  /** The two gateways, matching the provider ids this plugin registers. */
9157
10229
  const REGIONS = ["cn", "global"];
9158
10230
  const PROVIDER_ID_BY_REGION = {
@@ -9307,7 +10379,7 @@ const CATALOG_TTL_MS = 18e5;
9307
10379
  /**
9308
10380
  * How long a failed roster read waits before the next attempt.
9309
10381
  *
9310
- * A failed read used to be stamped as freshly read, which parked the static
10382
+ * A failed read must not be stamped as freshly read: that parks the static
9311
10383
  * fallback - and with it the wrong model list, for the gateways and for the
9312
10384
  * host's picker - for the whole TTL after one slow start.
9313
10385
  */
@@ -9323,6 +10395,8 @@ const PLACEHOLDER_BASE_URL = "http://127.0.0.1:1/v1";
9323
10395
  * paint, so opening it never waits on a billing call per account.
9324
10396
  */
9325
10397
  const PROBE_TTL_MS = 6e4;
10398
+ /** How often the desktop sign-ins are re-read while the service runs. */
10399
+ const ACCOUNT_WATCH_MS = 6e4;
9326
10400
  /**
9327
10401
  * Bound on one model-catalog request, so a stalled host cannot stall a load.
9328
10402
  *
@@ -9362,6 +10436,32 @@ const SERVICE_BOOTSTRAP_BUDGET_MS = 1500;
9362
10436
  * few seconds at worst when another process holds the preferred ports.
9363
10437
  */
9364
10438
  const REFRESH_PASS_BUDGET_MS = 18e3;
10439
+ /**
10440
+ * How often the token keep-alive walks the pool.
10441
+ *
10442
+ * Half of the lifetime the pool assumes for a token that reports none, so a
10443
+ * sign-in nobody has used is renewed while it still works rather than at the
10444
+ * moment a request needs it.
10445
+ */
10446
+ /**
10447
+ * How long a started panel login stays pollable.
10448
+ *
10449
+ * The browser half is the user's to finish, so it is measured in minutes
10450
+ * rather than the seconds a network call gets. Past it the state is dropped and
10451
+ * the panel asks the user to start again: the upstream keeps answering
10452
+ * `login ing...` for a state that will never complete, so a poll with no
10453
+ * deadline would look alive forever.
10454
+ */
10455
+ const DEVICE_LOGIN_TTL_MS = 9e5;
10456
+ /**
10457
+ * One account-directory walk, on its own clock.
10458
+ *
10459
+ * A walk reads every `.info` in every auth directory and, on a cold key, asks
10460
+ * the OS for the at-rest key, which is the slow part. The host allows a panel
10461
+ * call 30 s and the pass that follows has 18 s of its own, so this is sized to
10462
+ * leave the walk the larger share and let the pass take what is left.
10463
+ */
10464
+ const POOL_SCAN_BUDGET_MS = 8e3;
9365
10465
  let settings = {};
9366
10466
  /**
9367
10467
  * Bumped by every local mutation of `settings`.
@@ -9376,6 +10476,16 @@ let dataPath = "";
9376
10476
  /** One runtime per gateway: its shim and catalog. */
9377
10477
  const runtimes = /* @__PURE__ */ new Map();
9378
10478
  /**
10479
+ * Binds in flight, by region.
10480
+ *
10481
+ * A rescan and a refresh pass can reach the same region at the same moment, and
10482
+ * two binds for one region mean the second loses the preferred port it had just
10483
+ * reserved and logs a warning about its own process. The map is what makes the
10484
+ * second caller the first one's answer; entries are dropped once the promise
10485
+ * settles, so the next pass starts fresh.
10486
+ */
10487
+ const runtimeStarts = /* @__PURE__ */ new Map();
10488
+ /**
9379
10489
  * Gateway closes `reconcileRuntimes` started but could not wait for.
9380
10490
  *
9381
10491
  * That function runs synchronously inside settings application, yet a source
@@ -9442,6 +10552,13 @@ let settingsChangedHandler = null;
9442
10552
  /** The daily check-in timer, and what it has already collected. */
9443
10553
  let autoCheckinTimer = null;
9444
10554
  /**
10555
+ * Timer that re-reads the desktop sign-ins while the service runs.
10556
+ *
10557
+ * Once a minute because a switch in the client overwrites the global sign-in
10558
+ * file in place: the pool only has the account if it read the file before that.
10559
+ */
10560
+ let accountWatchTimer = null;
10561
+ /**
9445
10562
  * True while a check-in pass is running, whichever entry point started it.
9446
10563
  *
9447
10564
  * One flag for all three — the scheduled tick, the host command and the panel's
@@ -9451,10 +10568,45 @@ let autoCheckinTimer = null;
9451
10568
  let checkinPassRunning = false;
9452
10569
  /** Which pass owns the running flag; see `runCheckinPass`. */
9453
10570
  let checkinPassToken = 0;
10571
+ /**
10572
+ * True while the growth centre runs on its own, from the panel's card.
10573
+ *
10574
+ * Separate from `checkinPassRunning` because the two are different passes over
10575
+ * the same accounts: a growth run started beside a check-in pass would stack
10576
+ * two unpaced request clusters on one account, which is what the upstream
10577
+ * reads as a burst. The card refuses while either is running.
10578
+ */
10579
+ let growthPassRunning = false;
10580
+ /** Which run owns `growthPassRunning`, on the same rule as `checkinPassToken`. */
10581
+ let growthPassToken = 0;
10582
+ /**
10583
+ * The last standalone growth run, in the shape the scheduled pass records its
10584
+ * own growth half in. In memory only: after a restart the card falls back to
10585
+ * the growth half of the last scheduled pass, which is persisted with it.
10586
+ */
10587
+ let growthLast = null;
10588
+ /**
10589
+ * The growth centre's last successful read.
10590
+ *
10591
+ * Published with the status document so a repaint or a fresh panel paints it
10592
+ * instead of asking the user to read again; the panel refreshes it when it is old.
10593
+ */
10594
+ let growthRead = null;
10595
+ /**
10596
+ * Which read the answer in flight belongs to.
10597
+ *
10598
+ * A read walks several accounts and can take seconds, so a user can park a region
10599
+ * or drop an account while it runs. Comparing this counter around the await is
10600
+ * what stops that answer - computed against the pool as it was - from being
10601
+ * written back over the drop that just happened.
10602
+ */
10603
+ let growthReadEpoch = 0;
9454
10604
  /** Slots this process has collected, as `YYYY-MM-DDTHH` in the campaign's zone. */
9455
10605
  const autoCheckinSlots = /* @__PURE__ */ new Set();
9456
10606
  /** The last automatic pass, for the panel's status line. */
9457
10607
  let autoCheckinLast = null;
10608
+ /** The last keep-alive pass, for the panel's status line. In memory only. */
10609
+ let keepAliveLast = null;
9458
10610
  /**
9459
10611
  * When a deferred pass is owed, in ms; 0 = nothing pending.
9460
10612
  *
@@ -9483,6 +10635,10 @@ const QODER_RETRY_BACKOFF_MS = 6e5;
9483
10635
  * retired the pass that was running then, not the ones still to come.
9484
10636
  */
9485
10637
  let checkinAbort = new AbortController();
10638
+ const checkinScope = new AsyncLocalStorage();
10639
+ function currentCheckinSignal() {
10640
+ return checkinScope.getStore() ?? checkinAbort.signal;
10641
+ }
9486
10642
  /**
9487
10643
  * Cat-travel pacing: one pass per account, same throttle as the upstream's own
9488
10644
  * scheduler. A single `travelOne` already fans out to several RPCs, so a tight
@@ -9519,18 +10675,6 @@ const GROWTH_ACCOUNT_DELAY_MS = 400;
9519
10675
  const STREAK_REPORT_READ_GAP_MS = 1200;
9520
10676
  /** Account ids that hit the adopt conversation threshold today (CST day). */
9521
10677
  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
10678
  function log(level, message) {
9535
10679
  try {
9536
10680
  console.log("[xdpool] " + level + ": " + message);
@@ -9545,7 +10689,7 @@ function log(level, message) {
9545
10689
  * error text gets, so nothing unredacted reaches the log through it.
9546
10690
  */
9547
10691
  function gatewayLogLine(prefix, args) {
9548
- return prefix + args.map(messageOf).join(" ");
10692
+ return prefix + args.map(safeMessage).join(" ");
9549
10693
  }
9550
10694
  function regionOfKey(value) {
9551
10695
  return value === "global" ? "global" : "cn";
@@ -9608,7 +10752,7 @@ async function saveSettings(patch) {
9608
10752
  settingsRevision += 1;
9609
10753
  return true;
9610
10754
  } catch (error) {
9611
- log("warn", "could not save settings: " + messageOf(error));
10755
+ log("warn", "could not save settings: " + safeMessage(error));
9612
10756
  return false;
9613
10757
  }
9614
10758
  });
@@ -9656,7 +10800,7 @@ async function mutateSettings(key, mutate) {
9656
10800
  settingsRevision += 1;
9657
10801
  return true;
9658
10802
  } catch (error) {
9659
- log("warn", "could not save settings: " + messageOf(error));
10803
+ log("warn", "could not save settings: " + safeMessage(error));
9660
10804
  return false;
9661
10805
  }
9662
10806
  });
@@ -9701,6 +10845,10 @@ async function onHostSettingsChanged(next) {
9701
10845
  await reconcileQoderGateways();
9702
10846
  syncDeclaration();
9703
10847
  if (toggled) probeCache.clear();
10848
+ if (toggled) {
10849
+ growthRead = null;
10850
+ growthReadEpoch += 1;
10851
+ }
9704
10852
  scheduleRefresh("settings");
9705
10853
  return true;
9706
10854
  }
@@ -9709,7 +10857,7 @@ function subscribeToHostSettings() {
9709
10857
  settingsChangedHandler = (next) => {
9710
10858
  onHostSettingsChanged(next).then((applied) => {
9711
10859
  if (applied) log("info", "settings changed in the host UI; selection re-applied");
9712
- }).catch((error) => log("warn", "applying host settings failed: " + messageOf(error)));
10860
+ }).catch((error) => log("warn", "applying host settings failed: " + safeMessage(error)));
9713
10861
  };
9714
10862
  try {
9715
10863
  if (pi.events && typeof pi.events.on === "function") {
@@ -9717,7 +10865,7 @@ function subscribeToHostSettings() {
9717
10865
  return true;
9718
10866
  }
9719
10867
  } catch (error) {
9720
- log("warn", "could not subscribe to settings changes: " + messageOf(error));
10868
+ log("warn", "could not subscribe to settings changes: " + safeMessage(error));
9721
10869
  }
9722
10870
  settingsChangedHandler = null;
9723
10871
  return false;
@@ -9727,7 +10875,7 @@ function cooldownMs() {
9727
10875
  if (!Number.isFinite(value) || value <= 0) return 6e4;
9728
10876
  return Math.max(1e3, Math.min(864e5, Math.round(value * 1e3)));
9729
10877
  }
9730
- /** `priority` drains one account. An old `balanced` value reads as priority. */
10878
+ /** The modes other than `priority`, which is what an unrecognised or absent value means. */
9731
10879
  const WORKBUDDY_DISTRIBUTIONS = [
9732
10880
  "round-robin",
9733
10881
  "expiry",
@@ -9803,7 +10951,7 @@ function saveCheckinSlots() {
9803
10951
  try {
9804
10952
  fs$1.rmSync(staging, { force: true });
9805
10953
  } catch {}
9806
- log("warn", "could not record the collected check-in slots: " + messageOf(error));
10954
+ log("warn", "could not record the collected check-in slots: " + safeMessage(error));
9807
10955
  }
9808
10956
  }
9809
10957
  function preferredAccountId(region) {
@@ -9868,15 +11016,15 @@ function nearestPackExpiry(packages) {
9868
11016
  }
9869
11017
  return best;
9870
11018
  }
9871
- const { sourceCreditExpiry, sourceRotation, sourceFailureHold, sourceCredentialExpired, noteSourceFailure, sourceFailureActive, packUrgency, orderSourceCredentials } = createSourcePool({
11019
+ const { sourceCreditExpiry, sourceRotation, sourceFailureHold, sourceCredentialExpired, accountStateKey, noteSourceFailure, orderSourceCredentials } = createSourcePool({
9872
11020
  cooldownMs,
9873
11021
  preferredSourceAccount,
9874
11022
  sourceDistribution,
9875
11023
  sourceRegionKey
9876
11024
  });
9877
- function noteSourceExpiry(source, label, packages) {
11025
+ function noteSourceExpiry(source, region, label, packages) {
9878
11026
  const at = nearestPackExpiry(packages);
9879
- const key = source + "\n" + label;
11027
+ const key = accountStateKey(source, region, label);
9880
11028
  if (at === void 0) sourceCreditExpiry.delete(key);
9881
11029
  else sourceCreditExpiry.set(key, at);
9882
11030
  }
@@ -9935,6 +11083,25 @@ function gatewayEnabledIds(key, catalogIds) {
9935
11083
  const kept = enabled.filter((id) => known.has(id));
9936
11084
  return kept.length > 0 ? new Set(kept) : null;
9937
11085
  }
11086
+ /**
11087
+ * The selection as the gateway really publishes it, for the panel to render.
11088
+ *
11089
+ * The declaration normalizes a stored selection whose every id has been renamed
11090
+ * away back to "everything on", and the panel has to show that same answer. It
11091
+ * used to read the raw stored value, so a catalog rename showed every model
11092
+ * unticked while the gateway published all of them, with no way back: ticking
11093
+ * them produced the same normalized selection again.
11094
+ */
11095
+ function publishedSelectionFor(key, catalogIds) {
11096
+ const stored = gatewaySelectionFor(key);
11097
+ const enabled = gatewayEnabledIds(key, catalogIds);
11098
+ if (enabled !== null) return {
11099
+ ...stored,
11100
+ enabledModelIds: [...enabled]
11101
+ };
11102
+ const { enabledModelIds, ...rest } = stored;
11103
+ return rest;
11104
+ }
9938
11105
  /** Stored per-model overrides for one gateway key ("trae:cn", ...), by model id. */
9939
11106
  function gatewayOverrides(key) {
9940
11107
  const overrides = gatewaySelectionFor(key).overrides;
@@ -9951,15 +11118,20 @@ function sourceModelView(key, model, native) {
9951
11118
  const override = gatewayOverrides(key)[id] ?? {};
9952
11119
  const nativeName = typeof model.name === "string" && model.name !== "" ? model.name : id;
9953
11120
  const alias = typeof override.alias === "string" && override.alias.trim() !== "" ? override.alias.trim() : void 0;
11121
+ const nativeCeiling = Math.max(positiveInteger(native.contextWindow, CONSERVATIVE_CONTEXT_WINDOW), positiveInteger(native.maxContextWindow, 0));
11122
+ const declaredWindow = Math.min(positiveInteger(Number.isFinite(override.contextWindow) ? override.contextWindow : native.contextWindow, CONSERVATIVE_CONTEXT_WINDOW), nativeCeiling);
11123
+ const outputCeiling = positiveInteger(declaredWindow > positiveInteger(native.contextWindow, 128e3) ? native.maxTokensAtCeiling : native.maxTokens, positiveInteger(native.maxTokens, DEFAULT_MAX_TOKENS));
9954
11124
  return {
9955
11125
  id,
9956
11126
  name: alias ?? nativeName,
9957
11127
  ...alias === void 0 ? {} : { alias },
9958
11128
  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),
11129
+ contextWindow: declaredWindow,
11130
+ maxOutputTokens: Math.min(positiveInteger(Number.isFinite(override.maxOutputTokens) ? override.maxOutputTokens : outputCeiling, DEFAULT_MAX_TOKENS), outputCeiling),
9961
11131
  nativeContextWindow: native.contextWindow,
9962
- nativeMaxOutputTokens: native.maxTokens,
11132
+ ...nativeCeiling > positiveInteger(native.contextWindow, 128e3) ? { maxContextWindow: nativeCeiling } : {},
11133
+ nativeMaxOutputTokens: positiveInteger(native.maxTokens, DEFAULT_MAX_TOKENS),
11134
+ ...native.maxTokensAtCeiling === void 0 ? {} : { maxOutputAtCeiling: positiveInteger(native.maxTokensAtCeiling, outputCeiling) },
9963
11135
  supportsImages: typeof override.supportsImages === "boolean" ? override.supportsImages : native.supportsImages,
9964
11136
  nativeSupportsImages: native.supportsImages,
9965
11137
  ...Array.isArray(native.thinkingLevels) && native.thinkingLevels.length > 0 ? { nativeThinkingLevels: [...native.thinkingLevels] } : {},
@@ -9974,6 +11146,20 @@ function sourceRosterFor(key, models, nativeOf) {
9974
11146
  return models.filter((model) => String(model.id || "").trim() !== "").map((model) => sourceModelView(key, model, nativeOf(model))).filter((view) => isSelectableSourceModel(source, view));
9975
11147
  }
9976
11148
  /**
11149
+ * A source gateway's roster plus the selection that gateway really publishes.
11150
+ * One roster pass answers both, so the panel ticks exactly what the declaration
11151
+ * emits: a stored selection whose every id has been renamed away normalizes to
11152
+ * "publish everything" instead of every model showing unticked while the
11153
+ * gateway serves them all.
11154
+ */
11155
+ function sourcePublishedModels(key, models, nativeOf) {
11156
+ const roster = sourceRosterFor(key, models, nativeOf);
11157
+ return {
11158
+ roster,
11159
+ selection: publishedSelectionFor(key, roster.map((view) => view.id))
11160
+ };
11161
+ }
11162
+ /**
9977
11163
  * Trae's internal slots, by the names the IDE gives them.
9978
11164
  *
9979
11165
  * They are the IDE's own, stable across versions, and are what distinguishes a
@@ -10105,7 +11291,8 @@ function delay(ms) {
10105
11291
  * collects one.
10106
11292
  */
10107
11293
  function checkinDelay(ms) {
10108
- if (checkinAbort.signal.aborted) return Promise.resolve();
11294
+ const signal = currentCheckinSignal();
11295
+ if (signal.aborted) return Promise.resolve();
10109
11296
  return new Promise((resolve) => {
10110
11297
  let timer = null;
10111
11298
  const onAbort = () => {
@@ -10113,11 +11300,11 @@ function checkinDelay(ms) {
10113
11300
  resolve();
10114
11301
  };
10115
11302
  timer = setTimeout(() => {
10116
- checkinAbort.signal.removeEventListener("abort", onAbort);
11303
+ signal.removeEventListener("abort", onAbort);
10117
11304
  resolve();
10118
11305
  }, ms);
10119
11306
  if (typeof timer.unref === "function") timer.unref();
10120
- checkinAbort.signal.addEventListener("abort", onAbort, { once: true });
11307
+ signal.addEventListener("abort", onAbort, { once: true });
10121
11308
  });
10122
11309
  }
10123
11310
  /**
@@ -10249,7 +11436,7 @@ function declarationModels(region) {
10249
11436
  const seen = /* @__PURE__ */ new Set();
10250
11437
  for (const model of catalog.visible()) {
10251
11438
  const id = String(model.id || "").trim();
10252
- if (id === "" || id.length > 256 || seen.has(id)) continue;
11439
+ if (id === "" || id.length > MAX_MODEL_ID_LENGTH || seen.has(id)) continue;
10253
11440
  seen.add(id);
10254
11441
  const thinkingLevels = thinkingLevelsFor(model);
10255
11442
  const entry = {
@@ -10404,6 +11591,7 @@ async function warmSourceDirectory(entry, signal) {
10404
11591
  entry.lastError = entry.gateway.models().length > 0 ? "" : "directory unavailable: " + safeMessage(error);
10405
11592
  if (entry.lastError !== "") log("warn", "[" + entry.source + ":" + entry.region + "] " + entry.lastError);
10406
11593
  }
11594
+ if (entry.lastError === "" && entry.gateway.models().length > 0) syncDeclaration();
10407
11595
  return entry.lastError === "";
10408
11596
  }
10409
11597
  /**
@@ -10482,8 +11670,12 @@ async function createTraeRuntime(region) {
10482
11670
  credentials: async (purpose) => orderSourceCredentials("trae", region, (await discoverTraeCredentials()).credentials.filter((credential) => traeRegionOfCredential(credential) === region), traeRowLabel, purpose === "chat"),
10483
11671
  identity: (credential) => resolveTraeIdentity(desktopCandidates, credential.edition),
10484
11672
  listedIds: () => traeDeclarationModels(region).map((model) => model.id),
11673
+ publishedWindowOf: (modelId) => {
11674
+ const declared = traeDeclarationModels(region).find((model) => model.id === modelId);
11675
+ return declared === void 0 ? void 0 : declared.contextWindow;
11676
+ },
10485
11677
  onAttemptFailure: (credential, outcome) => {
10486
- noteSourceFailure("trae", traeRowLabel(credential), outcome.retryAfter);
11678
+ noteSourceFailure("trae", region, traeRowLabel(credential), outcome.retryAfter);
10487
11679
  },
10488
11680
  port: bound,
10489
11681
  logger: {
@@ -10498,11 +11690,12 @@ async function createTraeRuntime(region) {
10498
11690
  gateway,
10499
11691
  baseUrl: gateway.baseUrl(),
10500
11692
  portFallback: bound !== preferred,
11693
+ preferredPort: preferred,
10501
11694
  lastError: "",
10502
11695
  source: "trae"
10503
11696
  };
10504
11697
  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)));
11698
+ warmSourceDirectoryAtStartup(entry, warmAbort.signal).catch((error) => log("warn", "[trae:" + region + "] directory warm-up failed: " + safeMessage(error)));
10506
11699
  return entry;
10507
11700
  }
10508
11701
  /** Start and stop Trae gateways so the map matches the source switch exactly. */
@@ -10516,7 +11709,7 @@ async function reconcileTraeGateways() {
10516
11709
  try {
10517
11710
  await entry.gateway.close();
10518
11711
  } catch (error) {
10519
- log("warn", "[trae:" + region + "] gateway did not close cleanly: " + messageOf(error));
11712
+ log("warn", "[trae:" + region + "] gateway did not close cleanly: " + safeMessage(error));
10520
11713
  }
10521
11714
  }
10522
11715
  for (const region of active) {
@@ -10526,15 +11719,20 @@ async function reconcileTraeGateways() {
10526
11719
  if (!stillLoaded(generation) || !activeTraeRegions().includes(region) || traeGateways.has(region)) await entry.gateway.close();
10527
11720
  else traeGateways.set(region, entry);
10528
11721
  } catch (error) {
10529
- log("warn", "[trae:" + region + "] gateway could not start: " + messageOf(error));
11722
+ log("warn", "[trae:" + region + "] gateway could not start: " + safeMessage(error));
10530
11723
  }
10531
11724
  }
10532
11725
  }
10533
11726
  /** What a Trae gateway itself reported for one model. */
10534
11727
  function traeNativeOf(model) {
11728
+ const devWindow = positiveInteger(model.contextWindow, CONSERVATIVE_CONTEXT_WINDOW);
11729
+ const maxWindow = positiveInteger(model.maxContextWindow, 0);
11730
+ const ceiling = Math.max(devWindow, maxWindow);
10535
11731
  return {
10536
- contextWindow: positiveInteger(model.contextWindow, CONSERVATIVE_CONTEXT_WINDOW),
11732
+ contextWindow: devWindow,
10537
11733
  maxTokens: positiveInteger(model.maxTokens, DEFAULT_MAX_TOKENS),
11734
+ ...maxWindow > devWindow ? { maxTokensAtCeiling: positiveInteger(traeVariantFor(model, ceiling)?.maxTokens, positiveInteger(model.maxTokens, DEFAULT_MAX_TOKENS)) } : {},
11735
+ ...maxWindow > devWindow ? { maxContextWindow: maxWindow } : {},
10538
11736
  supportsImages: model.supportsImages === true,
10539
11737
  thinkingLevels: (model.reasoning ? model.reasoning.supported : []).filter((level) => HOST_THINKING_LEVELS.includes(level)),
10540
11738
  ...Number.isFinite(model.creditMultiplier) ? { multiplier: model.creditMultiplier } : {}
@@ -10549,7 +11747,7 @@ function traeDeclarationModels(region) {
10549
11747
  const enabled = gatewayEnabledIds("trae:" + region, roster);
10550
11748
  for (const model of gateway.models()) {
10551
11749
  const id = String(model.id || "").trim();
10552
- if (id === "" || id.length > 256 || seen.has(id)) continue;
11750
+ if (id === "" || id.length > MAX_MODEL_ID_LENGTH || seen.has(id)) continue;
10553
11751
  if (enabled !== null && !enabled.has(id)) continue;
10554
11752
  seen.add(id);
10555
11753
  const native = traeNativeOf(model);
@@ -10613,7 +11811,7 @@ async function createQoderRuntime(region) {
10613
11811
  listedIds: () => qoderDeclarationModels(region).map((model) => model.id),
10614
11812
  onAttemptFailure: (credential, outcome) => {
10615
11813
  const label = typeof credential.name === "string" && credential.name !== "" ? credential.name : credential.userID;
10616
- noteSourceFailure("qoder", label, outcome.retryAfter);
11814
+ noteSourceFailure("qoder", region, label, outcome.retryAfter);
10617
11815
  },
10618
11816
  port: bound,
10619
11817
  logger: {
@@ -10628,11 +11826,12 @@ async function createQoderRuntime(region) {
10628
11826
  gateway,
10629
11827
  baseUrl: gateway.baseUrl(),
10630
11828
  portFallback: bound !== preferred,
11829
+ preferredPort: preferred,
10631
11830
  lastError: "",
10632
11831
  source: "qoder"
10633
11832
  };
10634
11833
  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)));
11834
+ warmSourceDirectoryAtStartup(entry, warmAbort.signal).catch((error) => log("warn", "[qoder:" + region + "] directory warm-up failed: " + safeMessage(error)));
10636
11835
  return entry;
10637
11836
  }
10638
11837
  /** Start and stop Qoder gateways so the map matches the source switch exactly. */
@@ -10646,7 +11845,7 @@ async function reconcileQoderGateways() {
10646
11845
  try {
10647
11846
  await entry.gateway.close();
10648
11847
  } catch (error) {
10649
- log("warn", "[qoder:" + region + "] gateway did not close cleanly: " + messageOf(error));
11848
+ log("warn", "[qoder:" + region + "] gateway did not close cleanly: " + safeMessage(error));
10650
11849
  }
10651
11850
  }
10652
11851
  for (const region of active) {
@@ -10656,7 +11855,7 @@ async function reconcileQoderGateways() {
10656
11855
  if (!stillLoaded(generation) || !activeQoderRegions().includes(region) || qoderGateways.has(region)) await entry.gateway.close();
10657
11856
  else qoderGateways.set(region, entry);
10658
11857
  } catch (error) {
10659
- log("warn", "[qoder:" + region + "] gateway could not start: " + messageOf(error));
11858
+ log("warn", "[qoder:" + region + "] gateway could not start: " + safeMessage(error));
10660
11859
  }
10661
11860
  }
10662
11861
  }
@@ -10693,7 +11892,7 @@ function qoderDeclarationModels(region) {
10693
11892
  const enabled = gatewayEnabledIds("qoder:" + region, roster);
10694
11893
  for (const model of gateway.models()) {
10695
11894
  const id = String(model.id || "").trim();
10696
- if (id === "" || id.length > 256 || seen.has(id)) continue;
11895
+ if (id === "" || id.length > MAX_MODEL_ID_LENGTH || seen.has(id)) continue;
10697
11896
  if (enabled !== null && !enabled.has(id)) continue;
10698
11897
  seen.add(id);
10699
11898
  const native = qoderNativeOf(model);
@@ -10763,6 +11962,59 @@ async function createRuntime(region) {
10763
11962
  return runtime;
10764
11963
  }
10765
11964
  /**
11965
+ * One bind per region, whoever asks first.
11966
+ *
11967
+ * A rescan and the refresh pass can both reach a region with no runtime at the
11968
+ * same moment. Each used to reserve the preferred port and bind its own shim, so
11969
+ * one of them lost the bind and logged "the preferred port is held by another
11970
+ * process" - about this very process, whose first bind had not finished. Sharing
11971
+ * the in-flight promise makes the second caller the first one's answer.
11972
+ */
11973
+ function startRuntimeOnce(region) {
11974
+ const existing = runtimeStarts.get(region);
11975
+ if (existing !== void 0) return existing;
11976
+ const started = createRuntime(region).finally(() => {
11977
+ if (runtimeStarts.get(region) === started) runtimeStarts.delete(region);
11978
+ });
11979
+ runtimeStarts.set(region, started);
11980
+ return started;
11981
+ }
11982
+ /**
11983
+ * Take ownership of a runtime that has finished binding, or release it.
11984
+ *
11985
+ * Both callers of `startRuntimeOnce` land here with the same object, so
11986
+ * "somebody already put a runtime in the map" cannot be read as "mine is not
11987
+ * wanted": the other caller's entry is this very runtime. Releasing on that
11988
+ * reading closed a gateway that was serving and left a stopped object in the map
11989
+ * no later pass would rebuild.
11990
+ *
11991
+ * `unwanted` covers the reasons nobody is waiting for a gateway at all: the
11992
+ * activation it was started for is gone, the service stopped, or the region was
11993
+ * switched off while the shim was binding.
11994
+ *
11995
+ * A runtime already in the map outranks `unwanted`: the two callers of one
11996
+ * activation (`startRuntimes` and the refresh pass) share one bind, so a runtime
11997
+ * that one of them has already registered must not be closed by the other, whose
11998
+ * `unwanted` is about a generation or a region switch of its own. `runtimes.has`
11999
+ * is every later pass's only re-entry test, so a stopped entry there would take
12000
+ * the region out until the next teardown.
12001
+ *
12002
+ * This host's `onLoad` clears both maps, so it never shares a bind across a reload;
12003
+ * PI-Desktop's keeps its gateways and relies on this same ordering for that case.
12004
+ */
12005
+ async function settleStartedRuntime(region, runtime, unwanted) {
12006
+ const held = runtimes.get(region);
12007
+ if (held === runtime) return true;
12008
+ if (runtime.retired === true) return false;
12009
+ if (unwanted || held !== void 0) {
12010
+ await stopRuntime(runtime);
12011
+ return false;
12012
+ }
12013
+ runtimes.set(region, runtime);
12014
+ gatewayStartFailures.delete(region);
12015
+ return true;
12016
+ }
12017
+ /**
10766
12018
  * Start every active WorkBuddy gateway that is not running yet.
10767
12019
  *
10768
12020
  * One gateway's failure is logged and left out, on the same terms as the Trae
@@ -10779,43 +12031,47 @@ async function startRuntimes() {
10779
12031
  await Promise.all(activeRegions().map(async (region) => {
10780
12032
  if (runtimes.has(region)) return;
10781
12033
  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
- }
12034
+ await settleStartedRuntime(region, await startRuntimeOnce(region), !stillLoaded(generation) || !activeRegions().includes(region));
10788
12035
  } catch (error) {
10789
12036
  gatewayStartFailures.set(region, safeMessage(error));
10790
- log("warn", "[workbuddy:" + region + "] gateway could not start: " + messageOf(error));
12037
+ log("warn", "[workbuddy:" + region + "] gateway could not start: " + safeMessage(error));
10791
12038
  }
10792
12039
  }));
10793
12040
  }
10794
12041
  async function stopRuntime(runtime) {
12042
+ if (runtime.retired === true) return;
10795
12043
  runtime.retired = true;
10796
12044
  runtime.signedIn = false;
10797
12045
  gatewayStartFailures.delete(runtime.region);
10798
12046
  if (runtime.shim) await runtime.shim.close().catch((error) => {
10799
- log("warn", "[workbuddy:" + runtime.region + "] gateway did not close cleanly: " + messageOf(error));
12047
+ log("warn", "[workbuddy:" + runtime.region + "] gateway did not close cleanly: " + safeMessage(error));
10800
12048
  });
10801
12049
  }
10802
12050
  /**
10803
12051
  * Come back for a roster that could not be read.
10804
12052
  *
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.
12053
+ * Retries are cheap: a gateway with no account answers without a request, and
12054
+ * one whose read succeeded skips it on the freshness check.
12055
+ *
12056
+ * The handles are tracked so a stop or an unload can clear them: a retry that
12057
+ * outlived its activation fired into the next one and triggered a full refresh
12058
+ * pass nobody asked for.
10811
12059
  */
12060
+ const modelRetryTimers = /* @__PURE__ */ new Set();
10812
12061
  function scheduleModelRetries(attempt = 1) {
10813
12062
  if (serviceStopped) return;
10814
12063
  const timer = setTimeout(() => {
12064
+ modelRetryTimers.delete(timer);
10815
12065
  scheduleRefresh("model-list-retry");
10816
12066
  if (attempt < MODEL_RETRY_ATTEMPTS) scheduleModelRetries(attempt + 1);
10817
12067
  }, CATALOG_RETRY_MS);
10818
12068
  if (typeof timer.unref === "function") timer.unref();
12069
+ modelRetryTimers.add(timer);
12070
+ }
12071
+ /** Drop every pending roster retry. */
12072
+ function clearModelRetries() {
12073
+ for (const timer of modelRetryTimers) clearTimeout(timer);
12074
+ modelRetryTimers.clear();
10819
12075
  }
10820
12076
  /**
10821
12077
  * Bring one gateway online: seed its catalog from that gateway's own account.
@@ -10917,7 +12173,7 @@ function scheduleRefresh(reason) {
10917
12173
  if (refreshTimer !== null || refreshInflight !== null) return;
10918
12174
  refreshTimer = setTimeout(() => {
10919
12175
  refreshTimer = null;
10920
- refreshAll(reason, false).catch((error) => log("warn", "background refresh failed: " + messageOf(error)));
12176
+ refreshAll(reason, false).catch((error) => log("warn", "background refresh failed: " + safeMessage(error)));
10921
12177
  }, 0);
10922
12178
  if (typeof refreshTimer.unref === "function") refreshTimer.unref();
10923
12179
  }
@@ -10992,29 +12248,22 @@ async function refreshAll(reason, force) {
10992
12248
  if (!stillLoaded(generation)) return stalePass();
10993
12249
  }
10994
12250
  if (runtimes.has(region)) continue;
10995
- const starting = createRuntime(region);
12251
+ const starting = startRuntimeOnce(region);
10996
12252
  let runtime;
10997
12253
  try {
10998
12254
  runtime = await settle(starting);
10999
12255
  } catch (error) {
11000
12256
  gatewayStartFailures.set(region, safeMessage(error));
11001
- log("warn", "[" + region + "] gateway could not start: " + messageOf(error));
12257
+ log("warn", "[" + region + "] gateway could not start: " + safeMessage(error));
11002
12258
  continue;
11003
12259
  }
11004
12260
  if (runtime === void 0) {
11005
- starting.then((late) => stopRuntime(late)).catch(() => {});
11006
- continue;
11007
- }
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);
12261
+ starting.then((late) => {
12262
+ if (runtimes.get(region) !== late) return stopRuntime(late);
12263
+ }).catch(() => {});
11014
12264
  continue;
11015
12265
  }
11016
- runtimes.set(region, runtime);
11017
- gatewayStartFailures.delete(region);
12266
+ await settleStartedRuntime(region, runtime, !stillLoaded(generation) || !activeRegions().includes(region));
11018
12267
  }
11019
12268
  await settle(reconcileTraeGateways());
11020
12269
  if (!stillLoaded(generation)) return stalePass();
@@ -11061,7 +12310,7 @@ let qoderAccountRows = [];
11061
12310
  /**
11062
12311
  * The name one Trae account is listed and claimed under.
11063
12312
  *
11064
- * A Trae-generated `username` can read as a stranger (`zhi c cheng`), so the
12313
+ * A Trae-generated `username` can read as a stranger (`zhang san xyz`), so the
11065
12314
  * email is what the panel shows next to it; the label itself stays the app's
11066
12315
  * own name so it matches what the desktop app displays.
11067
12316
  */
@@ -11223,7 +12472,7 @@ async function refreshSourceAccounts() {
11223
12472
  const label = traeRowLabel(credential);
11224
12473
  const region = traeRegionOfCredential(credential);
11225
12474
  const probe = await traeRowProbe(credential, traeAccountRows.find((row) => row.label === label && row.region === region));
11226
- noteSourceExpiry("trae", label, probe?.usage?.credits?.packages);
12475
+ noteSourceExpiry("trae", region, label, probe?.usage?.credits?.packages);
11227
12476
  return {
11228
12477
  label,
11229
12478
  region,
@@ -11237,7 +12486,7 @@ async function refreshSourceAccounts() {
11237
12486
  }))).filter((row) => regionEnabled("trae", row.region));
11238
12487
  } else traeAccountRows = [];
11239
12488
  } catch (error) {
11240
- log("warn", "listing Trae sign-ins failed: " + messageOf(error));
12489
+ log("warn", "listing Trae sign-ins failed: " + safeMessage(error));
11241
12490
  }
11242
12491
  try {
11243
12492
  const regions = activeQoderRegions();
@@ -11253,7 +12502,7 @@ async function refreshSourceAccounts() {
11253
12502
  const label = qoderRowLabel(credential);
11254
12503
  const previous = qoderAccountRows.find((row) => row.label === label && row.region === credential.region);
11255
12504
  const probe = left() > 0 ? await qoderRowProbe(credential, previous) : previous;
11256
- noteSourceExpiry("qoder", label, probe?.usage?.credits?.packages);
12505
+ noteSourceExpiry("qoder", credential.region, label, probe?.usage?.credits?.packages);
11257
12506
  rows.push({
11258
12507
  label,
11259
12508
  region: credential.region,
@@ -11266,7 +12515,7 @@ async function refreshSourceAccounts() {
11266
12515
  qoderAccountRows = rows.filter((row) => regionEnabled("qoder", row.region));
11267
12516
  } else qoderAccountRows = [];
11268
12517
  } catch (error) {
11269
- log("warn", "listing Qoder sign-ins failed: " + messageOf(error));
12518
+ log("warn", "listing Qoder sign-ins failed: " + safeMessage(error));
11270
12519
  }
11271
12520
  pruneSourceState();
11272
12521
  }
@@ -11281,16 +12530,33 @@ async function refreshSourceAccounts() {
11281
12530
  */
11282
12531
  function pruneSourceState() {
11283
12532
  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);
12533
+ for (const row of traeAccountRows) live.add(accountStateKey("trae", row.region, row.label));
12534
+ for (const row of qoderAccountRows) live.add(accountStateKey("qoder", row.region, row.label));
11286
12535
  for (const key of [...sourceFailureHold.keys()]) if (!live.has(key)) sourceFailureHold.delete(key);
11287
12536
  for (const key of [...sourceCreditExpiry.keys()]) if (!live.has(key)) sourceCreditExpiry.delete(key);
11288
12537
  }
12538
+ /**
12539
+ * Directories the WorkBuddy pool reads, in order.
12540
+ *
12541
+ * The desktop app's own directories come first, so its live sign-in wins over
12542
+ * anything the plugin wrote. The plugin's own directory is appended rather than
12543
+ * substituted: an account added from the panel is read on exactly the same
12544
+ * terms as a desktop sign-in, and removing it is a file deletion the user can
12545
+ * see. A repointed `authFile` narrows the walk to that one directory, as
12546
+ * before — the user asked for a specific file.
12547
+ */
12548
+ function poolAuthDirs(authFile) {
12549
+ if (authFile !== "") return [path.dirname(authFile)];
12550
+ const own = ownSignInDir(dataPath);
12551
+ const dirs = candidateAuthDirs();
12552
+ if (own === "" || dirs.includes(own)) return dirs;
12553
+ return [...dirs, own];
12554
+ }
11289
12555
  /** Push the settings that affect discovery, cooldown and the picker. */
11290
12556
  function applySettingsToCore() {
11291
12557
  const authFile = typeof settings.authFile === "string" ? settings.authFile.trim() : "";
11292
12558
  const emptied = core.pool.applyConfig({
11293
- authDirs: authFile === "" ? candidateAuthDirs() : [path.dirname(authFile)],
12559
+ authDirs: poolAuthDirs(authFile),
11294
12560
  cooldownMs: cooldownMs(),
11295
12561
  distribution: distributionSetting(),
11296
12562
  disabledAccountIds: disabledAccountIds(),
@@ -11366,30 +12632,32 @@ function applyProbe(row, probe) {
11366
12632
  * `pending` so the panel can say it is still reading, and the caller refreshes
11367
12633
  * behind the first paint.
11368
12634
  */
11369
- async function accountProbe(account, allowNetwork) {
12635
+ async function accountProbe(account, allowNetwork, checkinOnly = false) {
11370
12636
  const cached = probeCache.get(account.id);
11371
12637
  if (allowNetwork !== true) return cached === void 0 ? { pending: true } : cached.value;
11372
12638
  if (cached !== void 0 && Date.now() - cached.atMs < PROBE_TTL_MS) return cached.value;
11373
12639
  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);
12640
+ if (!checkinOnly) {
12641
+ try {
12642
+ const credits = await core.client.fetchCredits(account.credential);
12643
+ value.credits = {
12644
+ ...credits.total === void 0 ? {} : { total: credits.total },
12645
+ packages: (credits.packages || []).map((pack) => ({
12646
+ packageName: pack.packageName,
12647
+ ...pack.remain === void 0 ? {} : { remain: pack.remain },
12648
+ ...pack.size === void 0 ? {} : { size: pack.size },
12649
+ ...pack.monthly === void 0 ? {} : { monthly: pack.monthly },
12650
+ ...pack.refreshAtMs === void 0 ? {} : { refreshAtMs: pack.refreshAtMs },
12651
+ ...pack.expiresAtMs === void 0 ? {} : { expiresAtMs: pack.expiresAtMs }
12652
+ })),
12653
+ ...credits.expiringSoon === void 0 ? {} : { expiringSoon: credits.expiringSoon },
12654
+ ...credits.nearestExpiryMs === void 0 ? {} : { nearestExpiryMs: credits.nearestExpiryMs }
12655
+ };
12656
+ } catch (error) {
12657
+ value.creditsError = safeMessage(error);
12658
+ }
12659
+ if (value.credits !== void 0 && typeof value.credits.total === "number") core.pool.setCreditBalance(account.id, value.credits.total, value.credits.nearestExpiryMs);
11391
12660
  }
11392
- if (value.credits !== void 0 && typeof value.credits.total === "number") core.pool.setCreditBalance(account.id, value.credits.total, value.credits.nearestExpiryMs);
11393
12661
  try {
11394
12662
  const checkin = await core.client.fetchCheckinStatus(account.credential);
11395
12663
  value.checkin = {
@@ -11451,9 +12719,7 @@ async function statusDocument(options) {
11451
12719
  selectionByRegion[region] = effectiveSelectionFor(region, runtimes.get(region)?.catalog);
11452
12720
  if (selectionStale(region, runtimes.get(region)?.catalog)) staleSelectionRegions.push(region);
11453
12721
  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);
12722
+ const nextUp = available.find((account) => account.id === preferredAccountIds[region]) ?? core.pool.preview(available);
11457
12723
  runtimeNextUpId.set(region, nextUp === void 0 ? void 0 : nextUp.id);
11458
12724
  for (const account of core.pool.list(region)) {
11459
12725
  const cooling = account.cooldownUntilMs > now;
@@ -11473,21 +12739,26 @@ async function statusDocument(options) {
11473
12739
  active: runtimeNextUpId.get(region) === account.id,
11474
12740
  preferred: preferredAccountIds[region] === account.id,
11475
12741
  disabled: core.pool.isDisabled(account.id),
12742
+ ...account.archived === true ? { archived: true } : {},
12743
+ ...core.pool.ownsSignIn(account.id) ? { own: true } : {},
11476
12744
  ...reserves[account.id] === void 0 ? {} : { creditReserve: reserves[account.id] }
11477
12745
  };
11478
- if (!cooling && !core.pool.isDisabled(account.id)) pendingProbes.push(accountProbe(account, allowNetwork).then((probe) => {
11479
- applyProbe(row, probe);
11480
- }));
12746
+ if (!core.pool.isDisabled(account.id)) {
12747
+ const checkinOnly = cooling;
12748
+ pendingProbes.push(accountProbe(account, allowNetwork, checkinOnly).then((probe) => {
12749
+ applyProbe(row, probe);
12750
+ }));
12751
+ }
11481
12752
  accounts.push(row);
11482
12753
  }
11483
12754
  const catalog = runtimes.get(region)?.catalog;
11484
12755
  if (catalog) {
11485
- const selection = effectiveSelectionFor(region, catalog);
12756
+ const selection = selectionByRegion[region];
11486
12757
  const enabled = selection.enabledModelIds;
11487
12758
  const overrides = selection.overrides || {};
11488
12759
  for (const model of catalog.current()) {
11489
12760
  const override = overrides[model.id];
11490
- const effective = applyOverride(model, override);
12761
+ const effective = applyOverride(model, override, catalog.hasLiveRoster());
11491
12762
  const levels = thinkingLevelsFor(effective);
11492
12763
  const promo = promoStatusFor(model, campaignClock, region);
11493
12764
  models.push({
@@ -11531,9 +12802,9 @@ async function statusDocument(options) {
11531
12802
  port: entry.gateway.port(),
11532
12803
  models: traeDeclarationModels(entry.region).length,
11533
12804
  portFallback: entry.portFallback,
12805
+ preferredPort: entry.preferredPort,
11534
12806
  lastError: entry.lastError,
11535
- roster: sourceRosterFor("trae:" + entry.region, entry.gateway.models(), traeNativeOf),
11536
- selection: gatewaySelectionFor("trae:" + entry.region)
12807
+ ...sourcePublishedModels("trae:" + entry.region, entry.gateway.models(), traeNativeOf)
11537
12808
  }))
11538
12809
  },
11539
12810
  qoder: {
@@ -11546,9 +12817,9 @@ async function statusDocument(options) {
11546
12817
  port: entry.gateway.port(),
11547
12818
  models: qoderDeclarationModels(entry.region).length,
11548
12819
  portFallback: entry.portFallback,
12820
+ preferredPort: entry.preferredPort,
11549
12821
  lastError: entry.lastError,
11550
- roster: sourceRosterFor("qoder:" + entry.region, entry.gateway.models(), qoderNativeOf),
11551
- selection: gatewaySelectionFor("qoder:" + entry.region)
12822
+ ...sourcePublishedModels("qoder:" + entry.region, entry.gateway.models(), qoderNativeOf)
11552
12823
  }))
11553
12824
  },
11554
12825
  enabled: settings.enabled !== false,
@@ -11556,11 +12827,18 @@ async function statusDocument(options) {
11556
12827
  modelCap: MAX_MODELS,
11557
12828
  distribution: distributionSetting(),
11558
12829
  showComposerPoints: settings.showComposerPoints === true,
12830
+ replacedClientName: replacedClientName() ?? null,
11559
12831
  autoCheckin: {
11560
12832
  enabled: autoCheckinEnabled(),
11561
12833
  hours: checkinHours(),
11562
12834
  ...autoCheckinLast === null ? {} : { last: autoCheckinLast }
11563
12835
  },
12836
+ growth: {
12837
+ running: growthPassRunning || checkinPassRunning,
12838
+ ...growthLast === null ? {} : { last: growthLast },
12839
+ read: growthRead
12840
+ },
12841
+ keepAlive: keepAliveLast === null ? null : { ...keepAliveLast },
11564
12842
  preferredAccountIds,
11565
12843
  removedAccounts: removedAccounts().map((entry) => ({
11566
12844
  id: entry.id,
@@ -11766,7 +13044,7 @@ async function doctorReport() {
11766
13044
  push("source-trae", traeDetail?.ok ?? false, traeDetail?.detail ?? "on; still reading this source's sign-ins");
11767
13045
  const qoderDetail = await settle(qoderDoctorDetail());
11768
13046
  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(", "));
13047
+ 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
13048
  const healthy = status.accounts.filter((account) => !account.cooling).length;
11771
13049
  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
13050
  const atRestKeyReason = status.sources.workbuddy === true ? atRestKeyFailure() : "";
@@ -11869,6 +13147,15 @@ async function doctor() {
11869
13147
  };
11870
13148
  }
11871
13149
  }
13150
+ /**
13151
+ * Logins the panel has started and not finished, keyed by realm.
13152
+ *
13153
+ * One per realm on purpose: a second start for the same realm replaces the
13154
+ * first, and the replaced state is dead — a browser is sitting on a URL nobody
13155
+ * polls. Memory only, so a restart drops them and the panel simply starts over
13156
+ * rather than answering a poll for a state this process never issued.
13157
+ */
13158
+ const deviceLogins = /* @__PURE__ */ new Map();
11872
13159
  function panelError(message, code) {
11873
13160
  const error = new Error(message);
11874
13161
  error.code = code;
@@ -12004,7 +13291,10 @@ async function onPanelInvoke(channel, payload) {
12004
13291
  }
12005
13292
  })), LOAD_ROSTER_BUDGET_MS);
12006
13293
  syncDeclaration();
12007
- return await statusDocument({ allowNetwork: false });
13294
+ return {
13295
+ ...await statusDocument({ allowNetwork: false }),
13296
+ refreshing: refreshNeeded()
13297
+ };
12008
13298
  /**
12009
13299
  * "Detect accounts again": a deliberate, user-invoked re-read, so every
12010
13300
  * gateway's roster is refetched even inside its refresh window.
@@ -12012,6 +13302,8 @@ async function onPanelInvoke(channel, payload) {
12012
13302
  case "xd.rescan": {
12013
13303
  const { left, settle } = budget(RESCAN_BUDGET_MS);
12014
13304
  resetDiscoveryCaches();
13305
+ growthRead = null;
13306
+ growthReadEpoch += 1;
12015
13307
  if (activeRegions().length > 0) await settle(core.pool.scan());
12016
13308
  await settle(startRuntimes());
12017
13309
  await settle(refreshSourceAccounts());
@@ -12032,7 +13324,9 @@ async function onPanelInvoke(channel, payload) {
12032
13324
  const account = core.pool.list().find((item) => item.id === accountId);
12033
13325
  if (account === void 0) throw panelError("unknown account", "NOT_FOUND");
12034
13326
  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");
13327
+ if (checkinPassRunning || growthPassRunning) throw panelError("a check-in or growth pass is already running; wait for it to finish", "BUSY");
13328
+ const token = ++checkinPassToken;
13329
+ checkinPassRunning = true;
12036
13330
  const work = async () => {
12037
13331
  const before = await core.client.fetchCheckinStatus(account.credential);
12038
13332
  if (before.todayCheckedIn) {
@@ -12060,7 +13354,9 @@ async function onPanelInvoke(channel, payload) {
12060
13354
  result: claim
12061
13355
  };
12062
13356
  };
12063
- const answered = await settleWithin(work(), PANEL_STEP_BUDGET_MS);
13357
+ const answered = await settleWithin(work(), PANEL_STEP_BUDGET_MS).finally(() => {
13358
+ if (token === checkinPassToken) checkinPassRunning = false;
13359
+ });
12064
13360
  if (answered === void 0) throw panelError("the check-in did not finish in time; try again", "TIMEOUT");
12065
13361
  return answered;
12066
13362
  }
@@ -12117,11 +13413,40 @@ async function onPanelInvoke(channel, payload) {
12117
13413
  "enabled",
12118
13414
  "disabled",
12119
13415
  "removed",
12120
- "restored"
13416
+ "restored",
13417
+ "deleted"
12121
13418
  ].includes(state)) throw panelError("region, accountId and a known state are required", "INVALID");
12122
13419
  const account = core.pool.list(region).find((item) => item.id === accountId);
12123
13420
  const stored = removedAccounts().find((entry) => entry.id === accountId);
12124
13421
  if (state !== "restored" && account === void 0 && stored === void 0) throw panelError("account does not belong to this gateway", "NOT_FOUND");
13422
+ if (state === "deleted") {
13423
+ if (!core.pool.ownsSignIn(accountId)) throw panelError("only an account added from this panel can be deleted", "NOT_OWN");
13424
+ if (await core.pool.removeOwnSignIn(accountId) !== true) throw panelError("the sign-in file could not be removed", "DELETE_FAILED");
13425
+ await settleWithin(core.pool.scan(), POOL_SCAN_BUDGET_MS);
13426
+ if (await mutateSettings("disabledAccountIds", (current) => {
13427
+ return (Array.isArray(current) ? current.filter((id) => typeof id === "string") : []).filter((id) => id !== accountId);
13428
+ }) !== true) log("warn", "could not clear the disabled state for " + accountId);
13429
+ if (await mutateSettings("creditReserves", (current) => {
13430
+ const next = { ...current && typeof current === "object" && !Array.isArray(current) ? current : {} };
13431
+ delete next[accountId];
13432
+ return next;
13433
+ }) !== true) log("warn", "could not clear the credit reserve for " + accountId);
13434
+ core.pool.applyConfig({
13435
+ disabledAccountIds: disabledAccountIds(),
13436
+ creditReserves: creditReserves()
13437
+ });
13438
+ if (preferredAccountId(region) === accountId) {
13439
+ if (await mutateSettings("preferredAccountIds", (current) => {
13440
+ const next = { ...current && typeof current === "object" && !Array.isArray(current) ? current : {} };
13441
+ delete next[region];
13442
+ return next;
13443
+ }) !== true) log("warn", "could not clear the preferred account for " + region);
13444
+ core.pool.prefer(void 0, region);
13445
+ }
13446
+ growthRead = null;
13447
+ growthReadEpoch += 1;
13448
+ return await statusDocument({ allowNetwork: false });
13449
+ }
12125
13450
  if (await mutateSettings("disabledAccountIds", (current) => {
12126
13451
  const kept = (Array.isArray(current) ? current.filter((id) => typeof id === "string") : []).filter((id) => id !== accountId);
12127
13452
  if (state === "disabled") kept.push(accountId);
@@ -12148,6 +13473,8 @@ async function onPanelInvoke(channel, payload) {
12148
13473
  }) !== true) log("warn", "could not clear the preferred account for " + region);
12149
13474
  core.pool.prefer(void 0, region);
12150
13475
  }
13476
+ growthRead = null;
13477
+ growthReadEpoch += 1;
12151
13478
  return await statusDocument({ allowNetwork: false });
12152
13479
  }
12153
13480
  /** The credits to keep back on one account: 0 clears the floor. */
@@ -12167,67 +13494,36 @@ async function onPanelInvoke(channel, payload) {
12167
13494
  core.pool.applyConfig({ creditReserves: creditReserves() });
12168
13495
  return await statusDocument({ allowNetwork: false });
12169
13496
  }
12170
- /** One click for every account's daily reward, as the command palette does.
13497
+ /** One click for every account's daily reward.
12171
13498
  * With `source`, only that source's pool runs — each source has its own
12172
13499
  * check-in pool in the panel, so one button must not sweep the others. */
12173
13500
  case "xd.checkinAll": {
12174
13501
  const source = typeof payload?.source === "string" ? payload.source : "";
12175
- const want = (name) => source === "" || source === name;
12176
- if (checkinPassRunning) return {
13502
+ if (![
13503
+ "",
13504
+ "workbuddy",
13505
+ "trae",
13506
+ "qoder"
13507
+ ].includes(source)) throw panelError("source must be workbuddy, trae or qoder", "INVALID");
13508
+ const counts = await settleWithin(runCheckinPass({
13509
+ manual: true,
13510
+ only: source
13511
+ }), CHECKIN_BUDGET_MS);
13512
+ if (counts === void 0) return {
12177
13513
  state: await statusDocument({
12178
13514
  allowNetwork: true,
12179
13515
  budgetMs: DOCUMENT_BUDGET_MS
12180
13516
  }),
12181
13517
  running: true
12182
13518
  };
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 {
13519
+ if (counts.running === true || counts.stale === true) return {
12224
13520
  state: await statusDocument({
12225
13521
  allowNetwork: true,
12226
13522
  budgetMs: DOCUMENT_BUDGET_MS
12227
13523
  }),
12228
13524
  running: true
12229
13525
  };
12230
- if (counts === failed) throw panelError("the check-in pass failed; the reason is in the plugin log", "UPSTREAM");
13526
+ if (counts.error !== void 0) throw panelError(counts.error, "UPSTREAM");
12231
13527
  return {
12232
13528
  state: await statusDocument({
12233
13529
  allowNetwork: true,
@@ -12250,7 +13546,9 @@ async function onPanelInvoke(channel, payload) {
12250
13546
  if (source !== "trae" && source !== "qoder") throw panelError("source must be trae or qoder", "INVALID");
12251
13547
  if (label === "" || region === "") throw panelError("label and region are required", "INVALID");
12252
13548
  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");
13549
+ if (checkinPassRunning || growthPassRunning) throw panelError("a check-in or growth pass is already running; wait for it to finish", "BUSY");
13550
+ const token = ++checkinPassToken;
13551
+ checkinPassRunning = true;
12254
13552
  const answered = await settleWithin((async () => {
12255
13553
  const outcome = source === "trae" ? await traeClaimOne(label, region) : await qoderClaimOne(label, region);
12256
13554
  return {
@@ -12260,7 +13558,9 @@ async function onPanelInvoke(channel, payload) {
12260
13558
  }),
12261
13559
  result: outcome
12262
13560
  };
12263
- })(), PANEL_STEP_BUDGET_MS);
13561
+ })(), PANEL_STEP_BUDGET_MS).finally(() => {
13562
+ if (token === checkinPassToken) checkinPassRunning = false;
13563
+ });
12264
13564
  if (answered === void 0) throw panelError("the check-in did not finish in time; try again", "TIMEOUT");
12265
13565
  return answered;
12266
13566
  }
@@ -12320,6 +13620,23 @@ async function onPanelInvoke(channel, payload) {
12320
13620
  return await statusDocument({ allowNetwork: false });
12321
13621
  }
12322
13622
  /**
13623
+ * Refresh every eligible account's token, by hand.
13624
+ *
13625
+ * There is no schedule behind this: the panel's button is the only thing
13626
+ * that runs it, which is what the user asked for. The pass itself is the
13627
+ * same one the check-in card's other controls use — `ensureFresh` decides
13628
+ * per account whether an upstream call is needed — so a token that still
13629
+ * has hours on it costs nothing and an international token that lives a
13630
+ * year is never touched.
13631
+ *
13632
+ * Bounded like every other network pass here: Trae alone spaces its
13633
+ * accounts, and a pass that outruns the budget records itself in the
13634
+ * document instead of leaving the button spinning.
13635
+ */
13636
+ case "xd.keepAlive":
13637
+ await settleWithin(runKeepAlivePass(), REFRESH_PASS_BUDGET_MS);
13638
+ return await statusDocument({ allowNetwork: false });
13639
+ /**
12323
13640
  * Run the daily pass now, by hand.
12324
13641
  *
12325
13642
  * The scheduled pass is silent by nature: it fires at an hour nobody is
@@ -12342,6 +13659,15 @@ async function onPanelInvoke(channel, payload) {
12342
13659
  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
13660
  return await statusDocument({ allowNetwork: false });
12344
13661
  /**
13662
+ * Rewrite the client name the domestic host's channel check refuses.
13663
+ *
13664
+ * Off by default: it changes what the prompt says about the client, which is
13665
+ * a decision for the user rather than something the plugin does behind them.
13666
+ */
13667
+ case "xd.setRewriteClientName":
13668
+ 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");
13669
+ return await statusDocument({ allowNetwork: false });
13670
+ /**
12345
13671
  * Park or unpark one edition of one source (国内版 / 国际版).
12346
13672
  *
12347
13673
  * Same shape as the source switch above: a parked region keeps no gateway,
@@ -12362,6 +13688,10 @@ async function onPanelInvoke(channel, payload) {
12362
13688
  await onHostSettingsChanged({});
12363
13689
  if (payload?.enabled === true) await refreshAll("region-on", true);
12364
13690
  else syncDeclaration();
13691
+ if (source === "workbuddy") {
13692
+ growthRead = null;
13693
+ growthReadEpoch += 1;
13694
+ }
12365
13695
  return await statusDocument({ allowNetwork: false });
12366
13696
  }
12367
13697
  /**
@@ -12380,8 +13710,135 @@ async function onPanelInvoke(channel, payload) {
12380
13710
  await onHostSettingsChanged({});
12381
13711
  if (payload?.enabled === true) await refreshAll("source-on", true);
12382
13712
  else syncDeclaration();
13713
+ if (payload?.source === "workbuddy") {
13714
+ growthRead = null;
13715
+ growthReadEpoch += 1;
13716
+ }
12383
13717
  return await statusDocument({ allowNetwork: false });
12384
13718
  }
13719
+ /**
13720
+ * Start a panel login and answer the URL to open.
13721
+ *
13722
+ * The URL is handed back rather than opened from here: the panel owns the
13723
+ * click, and this host's page is a real browser tab, so it opens the link
13724
+ * itself the same way its footer links do.
13725
+ */
13726
+ case "xd.startLogin": {
13727
+ const realm = payload?.realm === "global" ? "global" : "cn";
13728
+ const start = await startDeviceLogin(realm);
13729
+ deviceLogins.set(realm, {
13730
+ state: start.state,
13731
+ at: Date.now()
13732
+ });
13733
+ return {
13734
+ realm,
13735
+ authUrl: start.authUrl
13736
+ };
13737
+ }
13738
+ /**
13739
+ * Poll the login the panel started on this realm.
13740
+ *
13741
+ * A finished login is written as one of the plugin's own `.info` files and
13742
+ * the pool is rescanned, so the account appears in the panel and the
13743
+ * provider row without a reload. The second sign-in for an account already
13744
+ * present lands in a directory the pool already reads, so the directory set
13745
+ * does not change and `applyConfig` would not notice it: the scan is
13746
+ * explicit for that reason.
13747
+ */
13748
+ case "xd.pollLogin": {
13749
+ const realm = payload?.realm === "global" ? "global" : "cn";
13750
+ const pending = deviceLogins.get(realm);
13751
+ if (pending === void 0) throw panelError("no login is waiting on this realm", "NO_LOGIN");
13752
+ if (Date.now() - pending.at > DEVICE_LOGIN_TTL_MS) {
13753
+ deviceLogins.delete(realm);
13754
+ throw panelError("the login link has expired; start again", "LOGIN_EXPIRED");
13755
+ }
13756
+ const answer = await pollDeviceLogin(realm, pending.state);
13757
+ if (answer.status !== "ok") return { status: "pending" };
13758
+ deviceLogins.delete(realm);
13759
+ const directory = ownSignInDir(dataPath);
13760
+ if (directory === "") throw panelError("no plugin data directory to write the sign-in into", "NO_DATA_DIR");
13761
+ await writeOwnSignIn(directory, answer.signIn);
13762
+ growthRead = null;
13763
+ growthReadEpoch += 1;
13764
+ await settleWithin(core.pool.scan(), POOL_SCAN_BUDGET_MS);
13765
+ await refreshAll("panel-login", false);
13766
+ return {
13767
+ status: "ok",
13768
+ nickname: answer.signIn.nickname,
13769
+ region: answer.signIn.region,
13770
+ state: await statusDocument({ allowNetwork: false })
13771
+ };
13772
+ }
13773
+ /**
13774
+ * What the growth centre holds, claiming nothing.
13775
+ *
13776
+ * Read-only because two of the four steps are not idempotent: a make-up
13777
+ * card and a lottery draw are spent by running them. Showing the state
13778
+ * first is what lets the panel say "2 cards, yesterday missed" before the
13779
+ * user decides, rather than spending one and reporting it afterwards.
13780
+ */
13781
+ case "xd.growthState": {
13782
+ const epoch = growthReadEpoch;
13783
+ const answered = await settleWithin(readGrowthState(), PANEL_STEP_BUDGET_MS);
13784
+ if (answered === void 0) throw panelError("the growth state did not finish in time; try again", "TIMEOUT");
13785
+ if (epoch !== growthReadEpoch) return { growth: {
13786
+ ...answered,
13787
+ readAt: Date.now()
13788
+ } };
13789
+ growthRead = {
13790
+ ...answered,
13791
+ readAt: Date.now()
13792
+ };
13793
+ return { growth: growthRead };
13794
+ }
13795
+ /**
13796
+ * Run the growth centre on its own, without the daily check-in.
13797
+ *
13798
+ * The scheduled pass runs it as its third stage, so this is the same code
13799
+ * with the same pacing and the same abort signal - not a second, smaller
13800
+ * copy of it. Refused beside a check-in pass rather than queued: both walk
13801
+ * the same accounts, and two unpaced clusters on one account is what the
13802
+ * upstream reads as a burst.
13803
+ */
13804
+ case "xd.growthRun": {
13805
+ if (serviceStopped) return {
13806
+ state: await statusDocument({ allowNetwork: false }),
13807
+ running: true
13808
+ };
13809
+ if (growthPassRunning || checkinPassRunning) return {
13810
+ state: await statusDocument({ allowNetwork: false }),
13811
+ running: true
13812
+ };
13813
+ growthPassRunning = true;
13814
+ const token = ++growthPassToken;
13815
+ checkinAbort.abort();
13816
+ checkinAbort = new AbortController();
13817
+ checkinScope.enterWith(checkinAbort.signal);
13818
+ const generation = loadGeneration;
13819
+ const counts = await settleWithin((async () => {
13820
+ try {
13821
+ return await claimAllGrowth();
13822
+ } finally {
13823
+ if (token === growthPassToken) growthPassRunning = false;
13824
+ }
13825
+ })(), GROWTH_BUDGET_MS);
13826
+ if (counts === void 0) return {
13827
+ state: await statusDocument({ allowNetwork: false }),
13828
+ running: true
13829
+ };
13830
+ if (stillLoaded(generation)) {
13831
+ growthLast = {
13832
+ at: (/* @__PURE__ */ new Date()).toISOString(),
13833
+ ...counts
13834
+ };
13835
+ scheduleRefresh("growth");
13836
+ }
13837
+ return {
13838
+ state: await statusDocument({ allowNetwork: false }),
13839
+ growth: counts
13840
+ };
13841
+ }
12385
13842
  case "xd.doctor": return await doctor();
12386
13843
  /**
12387
13844
  * The composer readout.
@@ -12433,70 +13890,6 @@ async function onPanelInvoke(channel, payload) {
12433
13890
  default: throw panelError("unsupported panel channel: " + String(channel), "UNSUPPORTED");
12434
13891
  }
12435
13892
  }
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
13893
  /**
12501
13894
  * One check-in worker, isolated from the others in the same fan-out.
12502
13895
  *
@@ -12506,7 +13899,7 @@ async function registerCommands() {
12506
13899
  */
12507
13900
  function isolatedCheckinWorker(work, fallback, name) {
12508
13901
  return work.catch((error) => {
12509
- log("warn", name + " check-in failed: " + messageOf(error));
13902
+ log("warn", name + " check-in failed: " + safeMessage(error));
12510
13903
  return {
12511
13904
  ...fallback,
12512
13905
  failed: 1,
@@ -12528,12 +13921,17 @@ function isolatedCheckinWorker(work, fallback, name) {
12528
13921
  */
12529
13922
  async function runCheckinPass(options) {
12530
13923
  const manual = options?.manual === true;
13924
+ const only = typeof options?.only === "string" ? options.only : "";
13925
+ const want = (name) => only === "" || only === name;
12531
13926
  const generation = loadGeneration;
12532
13927
  if (checkinPassRunning) return { running: true };
12533
13928
  if (serviceStopped) return { stale: true };
13929
+ if (growthPassRunning) return { running: true };
12534
13930
  checkinPassRunning = true;
12535
13931
  const token = ++checkinPassToken;
13932
+ checkinAbort.abort();
12536
13933
  checkinAbort = new AbortController();
13934
+ checkinScope.enterWith(checkinAbort.signal);
12537
13935
  const zoned = zonedDayHour(/* @__PURE__ */ new Date());
12538
13936
  const slot = typeof options?.slot === "string" && options.slot !== "" ? options.slot : dueCheckinSlot(/* @__PURE__ */ new Date(), checkinHours(), autoCheckinSlots) ?? checkinSlotId(zoned.day, zoned.hour);
12539
13937
  const started = {
@@ -12544,42 +13942,64 @@ async function runCheckinPass(options) {
12544
13942
  ...manual ? { manual: true } : {}
12545
13943
  };
12546
13944
  autoCheckinLast = started;
12547
- autoCheckinSlots.add(slot);
13945
+ const spendsSlot = want("workbuddy");
13946
+ if (spendsSlot) autoCheckinSlots.add(slot);
12548
13947
  scheduleRefresh(manual ? "manual-checkin" : "auto-checkin");
12549
13948
  try {
12550
13949
  const [pool, qoder, trae] = await Promise.all([
12551
- isolatedCheckinWorker(claimAllCheckins(), {
13950
+ want("workbuddy") ? isolatedCheckinWorker(claimAllCheckins(), {
13951
+ claimed: 0,
13952
+ skipped: 0,
13953
+ failed: 0
13954
+ }, "workbuddy") : Promise.resolve({
12552
13955
  claimed: 0,
12553
13956
  skipped: 0,
12554
13957
  failed: 0
12555
- }, "workbuddy"),
12556
- isolatedCheckinWorker(qoderCheckinAll(), void 0, "qoder"),
12557
- isolatedCheckinWorker(traeCheckinAll(), void 0, "trae")
13958
+ }),
13959
+ want("qoder") ? isolatedCheckinWorker(qoderCheckinAll(), {
13960
+ claimed: 0,
13961
+ skipped: 0,
13962
+ failed: 0
13963
+ }, "qoder") : Promise.resolve({
13964
+ claimed: 0,
13965
+ skipped: 0,
13966
+ failed: 0
13967
+ }),
13968
+ want("trae") ? isolatedCheckinWorker(traeCheckinAll(), {
13969
+ claimed: 0,
13970
+ skipped: 0,
13971
+ failed: 0
13972
+ }, "trae") : Promise.resolve({
13973
+ claimed: 0,
13974
+ skipped: 0,
13975
+ failed: 0
13976
+ })
12558
13977
  ]);
12559
- const travel = await isolatedCheckinWorker(travelAllAccounts(), {
13978
+ const travel = want("workbuddy") ? await isolatedCheckinWorker(travelAllAccounts(), {
12560
13979
  departed: 0,
12561
13980
  claimed: 0,
12562
13981
  adopted: 0
12563
- }, "travel");
13982
+ }, "travel") : void 0;
12564
13983
  if (!stillLoaded(generation)) return started;
12565
- qoderRetryAt = typeof qoder.opensAt === "number" && qoder.opensAt > Date.now() ? qoder.opensAt : 0;
13984
+ qoderRetryAt = typeof qoder?.opensAt === "number" && qoder.opensAt > Date.now() ? qoder.opensAt : 0;
12566
13985
  Object.assign(started, {
12567
13986
  claimed: pool.claimed,
12568
13987
  skipped: pool.skipped,
12569
13988
  failed: pool.failed,
13989
+ ...pool.reason === void 0 ? {} : { reason: pool.reason },
12570
13990
  travel,
12571
13991
  qoder,
12572
13992
  trae
12573
13993
  });
12574
13994
  await checkinDelay(GROWTH_AFTER_CHECKIN_MS);
12575
13995
  if (!stillLoaded(generation)) return started;
12576
- started.growth = await claimAllGrowth();
13996
+ started.growth = want("workbuddy") ? await claimAllGrowth() : void 0;
12577
13997
  log((manual ? "manual" : "automatic") + " check-in collected " + pool.claimed + " account(s) for " + slot);
12578
- if (stillLoaded(generation)) saveCheckinSlots();
13998
+ if (spendsSlot && stillLoaded(generation)) saveCheckinSlots();
12579
13999
  } catch (error) {
12580
14000
  started.error = safeMessage(error);
12581
14001
  log("warn", (manual ? "manual" : "automatic") + " check-in failed for " + slot + ": " + started.error);
12582
- if (stillLoaded(generation)) saveCheckinSlots();
14002
+ if (spendsSlot && stillLoaded(generation)) saveCheckinSlots();
12583
14003
  } finally {
12584
14004
  if (token === checkinPassToken) checkinPassRunning = false;
12585
14005
  delete started.pending;
@@ -12610,6 +14030,12 @@ const PANEL_STEP_BUDGET_MS = 2e4;
12610
14030
  */
12611
14031
  const DOCUMENT_BUDGET_MS = 4e3;
12612
14032
  /**
14033
+ * A standalone growth run. Wider than the check-in budget it is carved out of,
14034
+ * because growth walks the same accounts with a pause and a report gap between
14035
+ * the steps, and several sign-ins make that minutes rather than seconds.
14036
+ */
14037
+ const GROWTH_BUDGET_MS = 9e4;
14038
+ /**
12613
14039
  * What the composer popup's refresh may spend before it answers.
12614
14040
  *
12615
14041
  * The readout's own call deadline is 20 s (`INVOKE_TIMEOUT_MS`), and the route
@@ -12619,15 +14045,6 @@ const DOCUMENT_BUDGET_MS = 4e3;
12619
14045
  * credentials read from turning the click into a client-side timeout.
12620
14046
  */
12621
14047
  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
14048
  /**
12632
14049
  * Light one account's growth streak, then redeem every tier it opened.
12633
14050
  *
@@ -12648,11 +14065,40 @@ function checkinSummaryText(result) {
12648
14065
  * redeemed and what they paid, so the panel can say so.
12649
14066
  */
12650
14067
  async function redeemAccountStreak(account) {
14068
+ const detail = {
14069
+ makeup: 0,
14070
+ gift: 0,
14071
+ compensation: 0,
14072
+ activity: 0,
14073
+ streak: 0,
14074
+ lottery: 0,
14075
+ failed: 0
14076
+ };
12651
14077
  const conversationId = "wb2api-streak-" + Date.now();
14078
+ try {
14079
+ if (await core.client.makeupCards(account.credential) > 0 && await core.client.missedYesterday(account.credential)) {
14080
+ const yesterday = zonedDay(-1);
14081
+ await core.client.useMakeupCard(account.credential, yesterday);
14082
+ detail.makeup += 1;
14083
+ log("info", "streak " + account.label + ": make-up card spent on " + yesterday);
14084
+ }
14085
+ } catch (error) {
14086
+ detail.failed += 1;
14087
+ log("warn", "streak " + account.label + ": make-up: " + safeMessage(error));
14088
+ }
14089
+ for (const [label, collect] of [["gift", () => core.client.claimGift(account.credential)], ["compensation", () => core.client.claimCompensation(account.credential)]]) try {
14090
+ const paid = await collect();
14091
+ if (paid > 0) {
14092
+ detail[label] += paid;
14093
+ log("info", "streak " + account.label + ": " + label + " +" + paid + "c");
14094
+ }
14095
+ } catch {}
12652
14096
  try {
12653
14097
  await core.client.reportChatActivity(account.credential, conversationId);
14098
+ detail.activity += 1;
12654
14099
  } catch (error) {
12655
- log("warn", "streak " + account.label + ": activity report failed: " + messageOf(error));
14100
+ detail.failed += 1;
14101
+ log("warn", "streak " + account.label + ": activity report failed: " + safeMessage(error));
12656
14102
  }
12657
14103
  await checkinDelay(STREAK_REPORT_READ_GAP_MS);
12658
14104
  const status = await core.client.growthStreakFull(account.credential);
@@ -12666,114 +14112,164 @@ async function redeemAccountStreak(account) {
12666
14112
  claimed += 1;
12667
14113
  credit += tier.credit;
12668
14114
  energy += tier.energy;
14115
+ detail.streak += 1;
12669
14116
  log("info", "streak " + account.label + ": redeemed " + tier.tier + " (+" + tier.credit + "c +" + tier.energy + "e)");
12670
14117
  } catch (error) {
12671
- log("warn", "streak " + account.label + ": redeem " + tier.tier + " failed: " + messageOf(error));
14118
+ detail.failed += 1;
14119
+ log("warn", "streak " + account.label + ": redeem " + tier.tier + " failed: " + safeMessage(error));
12672
14120
  }
12673
14121
  }
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));
14122
+ try {
14123
+ const chances = await core.client.lotteryChances(account.credential);
14124
+ for (let draw = 0; draw < chances; draw += 1) {
14125
+ const prize = await core.client.drawLottery(account.credential);
14126
+ detail.lottery += 1;
14127
+ log("info", "streak " + account.label + ": draw " + (draw + 1) + "/" + chances + " " + JSON.stringify(prize).slice(0, 160));
12713
14128
  }
14129
+ } catch (error) {
14130
+ detail.failed += 1;
14131
+ log("warn", "streak " + account.label + ": lottery: " + safeMessage(error));
12714
14132
  }
12715
- if (claimed === 0 && failed > 0) throw panelError("the task rewards could not be claimed", "UPSTREAM");
12716
14133
  return {
12717
14134
  claimed,
12718
14135
  credit,
12719
- energy
14136
+ energy,
14137
+ detail
12720
14138
  };
12721
14139
  }
12722
14140
  /**
12723
- * Collect the streak bonus and the task rewards of every domestic account.
14141
+ * Collect the streak bonus of every account.
12724
14142
  *
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.
14143
+ * Idempotent, so a pass that finds nothing to collect costs the reads and no
14144
+ * mutation, and running it on the daily schedule cannot double-pay. One account
14145
+ * failing never stops the rest.
12729
14146
  */
12730
14147
  async function claimAllGrowth() {
12731
14148
  const counts = {
12732
14149
  streak: 0,
12733
- tasks: 0,
12734
14150
  credit: 0,
12735
- failed: 0
14151
+ failed: 0,
14152
+ detail: emptyGrowthDetail()
12736
14153
  };
12737
14154
  let seen = 0;
12738
14155
  for (const account of core.pool.list()) {
14156
+ if (currentCheckinSignal().aborted) break;
12739
14157
  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
14158
  if (seen > 0) await checkinDelay(GROWTH_ACCOUNT_DELAY_MS);
12743
14159
  seen += 1;
14160
+ counts.detail.accounts += 1;
12744
14161
  let collected = false;
12745
14162
  try {
12746
14163
  const streak = await redeemAccountStreak(account);
12747
14164
  counts.streak += streak.claimed;
12748
14165
  counts.credit += streak.credit;
12749
14166
  if (streak.claimed > 0) collected = true;
14167
+ mergeGrowthDetail(counts.detail, streak.detail);
12750
14168
  } catch (error) {
12751
14169
  counts.failed += 1;
12752
- log("warn", "streak failed for " + account.label + ": " + messageOf(error));
14170
+ counts.detail.failed += 1;
14171
+ log("warn", "streak failed for " + account.label + ": " + safeMessage(error));
12753
14172
  }
14173
+ if (collected) probeCache.delete(account.id);
14174
+ }
14175
+ return counts;
14176
+ }
14177
+ /** A growth breakdown with everything at zero, for a pass that found nothing. */
14178
+ function emptyGrowthDetail() {
14179
+ return {
14180
+ accounts: 0,
14181
+ makeup: 0,
14182
+ gift: 0,
14183
+ compensation: 0,
14184
+ activity: 0,
14185
+ streak: 0,
14186
+ lottery: 0,
14187
+ failed: 0
14188
+ };
14189
+ }
14190
+ /** Add one account's step counts into the pass total. */
14191
+ function mergeGrowthDetail(total, part) {
14192
+ for (const key of Object.keys(total)) if (typeof part[key] === "number") total[key] += part[key];
14193
+ }
14194
+ /**
14195
+ * What the growth centre holds right now, without claiming anything.
14196
+ *
14197
+ * Read-only, so the panel can show the state before the user decides to spend
14198
+ * a make-up card or a draw: those two are the only steps of the pass that are
14199
+ * not idempotent, and a blind \"run\" would spend them without saying so.
14200
+ *
14201
+ * One row per account rather than one merged total. The streak, the tier it is
14202
+ * walking towards and the cards it holds are facts about one account, and a
14203
+ * total across them names no account: with two sign-ins the old merged line
14204
+ * showed whichever account was read last. The panel expands a row for the
14205
+ * tier detail behind it.
14206
+ *
14207
+ * One account's two reads run together and the accounts run together too,
14208
+ * like the credit probe: this is on demand, one button, and a serial pass over
14209
+ * several sign-ins would make the panel feel broken.
14210
+ */
14211
+ async function readGrowthState() {
14212
+ const rows = [];
14213
+ let failed = 0;
14214
+ const wanted = core.pool.list().filter((account) => !core.pool.isDisabled(account.id) && regionEnabled("workbuddy", regionOf(account.credential.domain)));
14215
+ const reads = await Promise.all(wanted.map(async (account) => {
12754
14216
  try {
12755
- const tasks = await claimAccountTasks(account);
12756
- counts.tasks += tasks.claimed;
12757
- counts.credit += tasks.credit;
12758
- if (tasks.claimed > 0) collected = true;
14217
+ const [streak, chances] = await Promise.all([core.client.growthStreakFull(account.credential), core.client.lotteryChances(account.credential)]);
14218
+ return {
14219
+ account,
14220
+ streak,
14221
+ chances
14222
+ };
12759
14223
  } catch (error) {
12760
- counts.failed += 1;
12761
- log("warn", "tasks failed for " + account.label + ": " + messageOf(error));
14224
+ log("warn", "growth state failed for " + account.label + ": " + safeMessage(error));
14225
+ return {
14226
+ account,
14227
+ error
14228
+ };
12762
14229
  }
12763
- if (collected) probeCache.delete(account.id);
14230
+ }));
14231
+ for (const read of reads) {
14232
+ const region = regionOf(read.account.credential.domain);
14233
+ if (read.error !== void 0) {
14234
+ failed += 1;
14235
+ rows.push({
14236
+ id: read.account.id,
14237
+ label: read.account.label,
14238
+ region,
14239
+ failed: true
14240
+ });
14241
+ continue;
14242
+ }
14243
+ const streak = read.streak;
14244
+ rows.push({
14245
+ id: read.account.id,
14246
+ label: read.account.label,
14247
+ region,
14248
+ days: streak.days,
14249
+ nextTier: streak.nextTier,
14250
+ nextTierRemaining: streak.nextTierRemaining,
14251
+ tiers: streak.tiers.filter((tier) => tier.status === "unlocked").length,
14252
+ tierList: streak.tiers,
14253
+ makeupCards: streak.makeupCards,
14254
+ lottery: read.chances
14255
+ });
12764
14256
  }
12765
- return counts;
14257
+ return {
14258
+ accounts: rows.length,
14259
+ failed,
14260
+ rows
14261
+ };
12766
14262
  }
12767
14263
  /**
12768
14264
  * Whether an upstream refusal means "the day was already collected".
12769
14265
  *
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.
14266
+ * Matched on the whole sentence, not on the bare word: a token or account
14267
+ * refusal often merely contains "already", and counting that as a benign skip
14268
+ * hides a real breakage from the last-run line and from the check-in summary
14269
+ * the user reads.
12774
14270
  */
12775
14271
  function isAlreadyCheckin(error) {
12776
- const message = messageOf(error).toLowerCase();
14272
+ const message = safeMessage(error).toLowerCase();
12777
14273
  return message.includes("已签到") || message.includes("已经签到") || message.includes("already checked in") || message.includes("already signed in") || message.includes("already claimed") || message.includes("already received");
12778
14274
  }
12779
14275
  async function claimAllCheckins() {
@@ -12785,7 +14281,7 @@ async function claimAllCheckins() {
12785
14281
  let seen = 0;
12786
14282
  for (const account of core.pool.list()) {
12787
14283
  if (core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
12788
- if (checkinAbort.signal.aborted) break;
14284
+ if (currentCheckinSignal().aborted) break;
12789
14285
  if (seen > 0) await checkinDelay(CHECKIN_ACCOUNT_DELAY_MS);
12790
14286
  seen += 1;
12791
14287
  try {
@@ -12804,7 +14300,7 @@ async function claimAllCheckins() {
12804
14300
  continue;
12805
14301
  }
12806
14302
  counts.failed += 1;
12807
- log("warn", "check-in failed for " + account.label + ": " + messageOf(error));
14303
+ log("warn", "check-in failed for " + account.label + ": " + safeMessage(error));
12808
14304
  }
12809
14305
  }
12810
14306
  return counts;
@@ -12831,24 +14327,24 @@ async function travelAdopt(account) {
12831
14327
  try {
12832
14328
  await core.client.reportChatActivity(account.credential, conversationId);
12833
14329
  } catch (error) {
12834
- log("warn", "travel " + account.label + ": adopt preflight report: " + messageOf(error));
14330
+ log("warn", "travel " + account.label + ": adopt preflight report: " + safeMessage(error));
12835
14331
  }
12836
14332
  await checkinDelay(TRAVEL_ADOPT_GAP_MS);
12837
14333
  try {
12838
14334
  await core.client.agreeBuddy(account.credential);
12839
14335
  } catch (error) {
12840
- log("warn", "travel " + account.label + ": agreement: " + messageOf(error));
14336
+ log("warn", "travel " + account.label + ": agreement: " + safeMessage(error));
12841
14337
  return "failed";
12842
14338
  }
12843
14339
  try {
12844
14340
  await core.client.adoptBuddy(account.credential);
12845
14341
  } catch (error) {
12846
- if (isBuddyThresholdIncomplete(messageOf(error))) {
14342
+ if (isBuddyThresholdIncomplete(safeMessage(error))) {
12847
14343
  travelAdoptTried.set(account.id, day);
12848
14344
  log("info", "travel " + account.label + ": adopt skipped (conversation threshold not reached, retry tomorrow)");
12849
14345
  return "skipped";
12850
14346
  }
12851
- log("warn", "travel " + account.label + ": adopt: " + messageOf(error));
14347
+ log("warn", "travel " + account.label + ": adopt: " + safeMessage(error));
12852
14348
  return "failed";
12853
14349
  }
12854
14350
  log("info", "travel " + account.label + ": adopt ok");
@@ -12865,7 +14361,7 @@ async function travelOne(account) {
12865
14361
  try {
12866
14362
  buddy = await core.client.fetchBuddyInfo(account.credential);
12867
14363
  } catch (error) {
12868
- log("warn", "travel " + account.label + ": buddy-info: " + messageOf(error));
14364
+ log("warn", "travel " + account.label + ": buddy-info: " + safeMessage(error));
12869
14365
  return "failed";
12870
14366
  }
12871
14367
  if (buddy === null) return await travelAdopt(account);
@@ -12873,7 +14369,7 @@ async function travelOne(account) {
12873
14369
  try {
12874
14370
  status = await core.client.fetchTravelStatus(account.credential);
12875
14371
  } catch (error) {
12876
- log("warn", "travel " + account.label + ": status: " + messageOf(error));
14372
+ log("warn", "travel " + account.label + ": status: " + safeMessage(error));
12877
14373
  return "failed";
12878
14374
  }
12879
14375
  if (status.state === "arrived") {
@@ -12886,7 +14382,7 @@ async function travelOne(account) {
12886
14382
  log("info", "travel " + account.label + ": claim ok record=" + status.recordId + " reward=" + reward);
12887
14383
  return "claimed";
12888
14384
  } catch (error) {
12889
- log("warn", "travel " + account.label + ": claim record=" + status.recordId + ": " + messageOf(error));
14385
+ log("warn", "travel " + account.label + ": claim record=" + status.recordId + ": " + safeMessage(error));
12890
14386
  return "failed";
12891
14387
  }
12892
14388
  }
@@ -12900,7 +14396,7 @@ async function travelOne(account) {
12900
14396
  log("info", "travel " + account.label + ": depart ok location=4");
12901
14397
  return "departed";
12902
14398
  } catch (error) {
12903
- log("warn", "travel " + account.label + ": depart: " + messageOf(error));
14399
+ log("warn", "travel " + account.label + ": depart: " + safeMessage(error));
12904
14400
  return "failed";
12905
14401
  }
12906
14402
  }
@@ -12928,7 +14424,7 @@ async function travelAllAccounts() {
12928
14424
  if (core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
12929
14425
  if (regionOf(account.credential.domain) !== "cn") continue;
12930
14426
  if (!account.credential.refreshToken) continue;
12931
- if (checkinAbort.signal.aborted) break;
14427
+ if (currentCheckinSignal().aborted) break;
12932
14428
  if (seen > 0) await checkinDelay(TRAVEL_ACCOUNT_DELAY_MS);
12933
14429
  seen += 1;
12934
14430
  try {
@@ -12936,10 +14432,10 @@ async function travelAllAccounts() {
12936
14432
  if (outcome === "departed" || outcome === "claimed" || outcome === "adopted") {
12937
14433
  counts[outcome === "departed" ? "departed" : outcome === "claimed" ? "claimed" : "adopted"] += 1;
12938
14434
  probeCache.delete(account.id);
12939
- }
14435
+ } else if (outcome === "failed") counts.failed += 1;
12940
14436
  } catch (error) {
12941
14437
  counts.failed += 1;
12942
- log("warn", "travel failed for " + account.label + ": " + messageOf(error));
14438
+ log("warn", "travel failed for " + account.label + ": " + safeMessage(error));
12943
14439
  }
12944
14440
  }
12945
14441
  return counts;
@@ -12973,7 +14469,7 @@ async function qoderCheckinAll() {
12973
14469
  let seen = 0;
12974
14470
  for (const credential of found.credentials) {
12975
14471
  if (!regions.includes(credential.region)) continue;
12976
- if (checkinAbort.signal.aborted) break;
14472
+ if (currentCheckinSignal().aborted) break;
12977
14473
  if (seen > 0) await checkinDelay(QODER_ACCOUNT_DELAY_MS);
12978
14474
  seen += 1;
12979
14475
  const result = await qoderClaimFor(credential);
@@ -13051,7 +14547,7 @@ async function traeCheckinAll() {
13051
14547
  const cnCredentials = found.credentials.filter((credential) => traeRegionOfCredential(credential) === "cn");
13052
14548
  let index = 0;
13053
14549
  for (; index < cnCredentials.length; index += 1) {
13054
- if (checkinAbort.signal.aborted) break;
14550
+ if (currentCheckinSignal().aborted) break;
13055
14551
  if (index > 0) await checkinDelay(Math.max(1e3, TRAE_ACCOUNT_DELAY_MS + Math.round((Math.random() * 2 - 1) * TRAE_ACCOUNT_JITTER_MS)));
13056
14552
  const result = await traeClaimFor(cnCredentials[index], desktopCandidates);
13057
14553
  counts[result.outcome] += 1;
@@ -13185,19 +14681,21 @@ async function autoCheckinTick(now) {
13185
14681
  if (!autoCheckinEnabled()) return void 0;
13186
14682
  const when = now === void 0 ? /* @__PURE__ */ new Date() : now;
13187
14683
  if (qoderRetryAt !== 0 && when.getTime() >= qoderRetryAt && activeQoderRegions().length > 0) {
13188
- if (checkinPassRunning) {
14684
+ if (checkinPassRunning || growthPassRunning) {
13189
14685
  log("info", "deferred Qoder check-in deferred: a pass is already running");
13190
14686
  return autoCheckinLast;
13191
14687
  }
13192
14688
  const retryGeneration = loadGeneration;
13193
14689
  checkinPassRunning = true;
13194
14690
  const token = ++checkinPassToken;
14691
+ checkinAbort.abort();
13195
14692
  checkinAbort = new AbortController();
14693
+ checkinScope.enterWith(checkinAbort.signal);
13196
14694
  try {
13197
14695
  qoderRetryAt = 0;
13198
14696
  const retry = await qoderCheckinAll();
13199
14697
  if (!stillLoaded(retryGeneration)) return autoCheckinLast;
13200
- qoderRetryAt = typeof retry.opensAt === "number" && retry.opensAt > Date.now() ? retry.opensAt : 0;
14698
+ 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
14699
  const claimedBefore = Number(autoCheckinLast?.qoder?.claimed) || 0;
13202
14700
  autoCheckinLast = {
13203
14701
  ...autoCheckinLast,
@@ -13222,7 +14720,7 @@ async function autoCheckinTick(now) {
13222
14720
  },
13223
14721
  at: (/* @__PURE__ */ new Date()).toISOString()
13224
14722
  };
13225
- log("warn", "deferred Qoder check-in failed: " + messageOf(error));
14723
+ log("warn", "deferred Qoder check-in failed: " + safeMessage(error));
13226
14724
  }
13227
14725
  } finally {
13228
14726
  if (token === checkinPassToken) checkinPassRunning = false;
@@ -13243,7 +14741,7 @@ function startAutoCheckin() {
13243
14741
  if (autoCheckinTimer !== null) return;
13244
14742
  if (serviceStopped) return;
13245
14743
  autoCheckinTimer = setInterval(() => {
13246
- autoCheckinTick().catch((error) => log("warn", "scheduled check-in failed: " + messageOf(error)));
14744
+ autoCheckinTick().catch((error) => log("warn", "scheduled check-in failed: " + safeMessage(error)));
13247
14745
  }, CHECKIN_POLL_MS);
13248
14746
  if (typeof autoCheckinTimer.unref === "function") autoCheckinTimer.unref();
13249
14747
  }
@@ -13258,6 +14756,78 @@ function applyAutoCheckin() {
13258
14756
  else stopAutoCheckin();
13259
14757
  }
13260
14758
  /**
14759
+ * Refresh every eligible account's token, by hand.
14760
+ *
14761
+ * `ensureFresh` decides per account whether an upstream call is needed, so an
14762
+ * account whose token still has hours on it costs nothing and an international
14763
+ * token that lives a year is never touched. What the pass buys is the account
14764
+ * nobody has used since its token expired: without it that account is refreshed
14765
+ * by the first request that arrives, which pays the round trip on the user's
14766
+ * own turn and, when the refresh token is dead too, fails that turn instead of
14767
+ * this one.
14768
+ *
14769
+ * Disabled and switched-off-region accounts stay out, matching every other
14770
+ * pass: a parked account is parked on purpose.
14771
+ */
14772
+ async function keepAliveTokens() {
14773
+ const counts = {
14774
+ refreshed: 0,
14775
+ fresh: 0,
14776
+ failed: 0,
14777
+ noToken: 0
14778
+ };
14779
+ for (const account of core.pool.list()) {
14780
+ if (serviceStopped) break;
14781
+ if (core.pool.isDisabled(account.id)) continue;
14782
+ if (!regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
14783
+ const outcome = await core.pool.ensureFresh(account);
14784
+ counts[outcome] = (counts[outcome] ?? 0) + 1;
14785
+ }
14786
+ return counts;
14787
+ }
14788
+ /** Run one keep-alive pass and record it for the panel. */
14789
+ async function runKeepAlivePass() {
14790
+ if (serviceStopped) return null;
14791
+ const generation = loadGeneration;
14792
+ const counts = await keepAliveTokens();
14793
+ if (stillLoaded(generation)) {
14794
+ keepAliveLast = {
14795
+ at: (/* @__PURE__ */ new Date()).toISOString(),
14796
+ ...counts
14797
+ };
14798
+ scheduleRefresh("keep-alive");
14799
+ }
14800
+ return counts;
14801
+ }
14802
+ /**
14803
+ * Re-read the sign-ins on a timer while the service runs.
14804
+ *
14805
+ * The pool scans at load, when the panel opens and when it runs dry. None of
14806
+ * those happens between two account switches in the desktop client, and the
14807
+ * global client keeps one live file: the sign-in that was overwritten in that
14808
+ * gap was never read, so it could not be archived either. A read this often is
14809
+ * what turns "the account I had before" into one the pool still holds.
14810
+ *
14811
+ * Chained rather than an interval, so a slow walk is followed by one pause
14812
+ * instead of a queue of walks on top of each other.
14813
+ */
14814
+ function startAccountWatch() {
14815
+ if (accountWatchTimer !== null || serviceStopped) return;
14816
+ const read = () => {
14817
+ accountWatchTimer = null;
14818
+ if (serviceStopped) return;
14819
+ if (activeRegions().length > 0) core.pool.scan().catch((error) => log("warn", "account re-read failed: " + safeMessage(error)));
14820
+ startAccountWatch();
14821
+ };
14822
+ accountWatchTimer = setTimeout(read, ACCOUNT_WATCH_MS);
14823
+ if (typeof accountWatchTimer.unref === "function") accountWatchTimer.unref();
14824
+ }
14825
+ function stopAccountWatch() {
14826
+ if (accountWatchTimer === null) return;
14827
+ clearTimeout(accountWatchTimer);
14828
+ accountWatchTimer = null;
14829
+ }
14830
+ /**
13261
14831
  * Bring the declaration up to date BEFORE the host can act on it.
13262
14832
  *
13263
14833
  * Registration is a runtime call and the host serves whatever the last
@@ -13304,6 +14874,7 @@ async function onServiceStart() {
13304
14874
  }
13305
14875
  applySettingsToCore();
13306
14876
  reconcileRuntimes();
14877
+ startAccountWatch();
13307
14878
  const { left: bootstrapLeft } = budget(SERVICE_BOOTSTRAP_BUDGET_MS);
13308
14879
  await settleWithin(reconcileTraeGateways(), bootstrapLeft());
13309
14880
  await settleWithin(reconcileQoderGateways(), bootstrapLeft());
@@ -13329,12 +14900,15 @@ async function onServiceStop() {
13329
14900
  }
13330
14901
  refreshInflight = null;
13331
14902
  stopAutoCheckin();
14903
+ stopAccountWatch();
13332
14904
  abortWarmups();
14905
+ clearModelRetries();
13333
14906
  checkinAbort.abort();
13334
14907
  const closing = Array.from(runtimes.values()).map(stopRuntime);
13335
14908
  runtimes.clear();
14909
+ runtimeStarts.clear();
13336
14910
  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));
14911
+ log("warn", "[" + entry.source + ":" + entry.region + "] gateway did not close cleanly: " + safeMessage(error));
13338
14912
  }));
13339
14913
  traeGateways.clear();
13340
14914
  qoderGateways.clear();
@@ -13343,17 +14917,39 @@ async function onServiceStop() {
13343
14917
  async function onLoad() {
13344
14918
  serviceStopped = false;
13345
14919
  loadGeneration += 1;
14920
+ abortWarmups();
13346
14921
  warmAbort = new AbortController();
14922
+ checkinAbort.abort();
13347
14923
  checkinAbort = new AbortController();
14924
+ stopAutoCheckin();
14925
+ stopAccountWatch();
14926
+ clearModelRetries();
14927
+ if (refreshTimer !== null) {
14928
+ clearTimeout(refreshTimer);
14929
+ refreshTimer = null;
14930
+ }
14931
+ refreshInflight = null;
14932
+ for (const runtime of runtimes.values()) pendingRuntimeStops.push(stopRuntime(runtime));
14933
+ runtimes.clear();
14934
+ runtimeStarts.clear();
14935
+ for (const entry of [...traeGateways.values(), ...qoderGateways.values()]) pendingRuntimeStops.push(entry.gateway.close().catch((error) => {
14936
+ log("warn", "[" + entry.source + ":" + entry.region + "] gateway did not close cleanly: " + safeMessage(error));
14937
+ }));
14938
+ traeGateways.clear();
14939
+ qoderGateways.clear();
13348
14940
  checkinPassRunning = false;
13349
14941
  autoCheckinSlots.clear();
13350
14942
  autoCheckinLast = null;
14943
+ growthPassRunning = false;
14944
+ growthLast = null;
14945
+ keepAliveLast = null;
13351
14946
  qoderRetryAt = 0;
13352
- core.client = new WorkBuddyUpstreamClient();
14947
+ core.client = new WorkBuddyUpstreamClient({ fetchImpl: clientNameRewritingFetch(replacedClientName) });
13353
14948
  core.pool = new WorkBuddyAccountPool({
13354
14949
  client: core.client,
13355
14950
  cooldownMs: cooldownMs(),
13356
14951
  distribution: distributionSetting(),
14952
+ dataPath: () => dataPath,
13357
14953
  logger: {
13358
14954
  info: (...args) => log("info", gatewayLogLine("", args)),
13359
14955
  warn: (...args) => log("warn", gatewayLogLine("", args)),
@@ -13368,12 +14964,10 @@ async function onLoad() {
13368
14964
  dataPath = await pi.plugin.getDataPath();
13369
14965
  } catch (error) {
13370
14966
  dataPath = "";
13371
- log("warn", "no plugin data path: " + messageOf(error));
14967
+ log("warn", "no plugin data path: " + safeMessage(error));
13372
14968
  }
13373
14969
  loadCheckinSlots();
13374
14970
  if (serviceStopped) return;
13375
- await registerCommands();
13376
- if (serviceStopped) return;
13377
14971
  pi.services.register({
13378
14972
  id: SERVICE_ID,
13379
14973
  start: onServiceStart,
@@ -13389,6 +14983,8 @@ async function onUnload() {
13389
14983
  refreshTimer = null;
13390
14984
  }
13391
14985
  stopAutoCheckin();
14986
+ stopAccountWatch();
14987
+ clearModelRetries();
13392
14988
  abortWarmups();
13393
14989
  await onServiceStop();
13394
14990
  probeCache.clear();
@@ -13401,23 +14997,27 @@ async function onUnload() {
13401
14997
  try {
13402
14998
  if (pi.events && typeof pi.events.off === "function" && settingsChangedHandler !== null) pi.events.off("plugin:settingsChanged", settingsChangedHandler);
13403
14999
  } catch (error) {
13404
- log("warn", "could not unsubscribe from settings changes: " + messageOf(error));
15000
+ log("warn", "could not unsubscribe from settings changes: " + safeMessage(error));
13405
15001
  }
13406
15002
  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
15003
  }
13417
15004
  function composerPointsEnabled() {
13418
15005
  return settings.showComposerPoints === true;
13419
15006
  }
13420
15007
  /**
15008
+ * The name this plugin sends as the client when the user turns the rewrite on.
15009
+ *
15010
+ * WorkBuddy's domestic host refuses a request whose prompt names DeepSeek
15011
+ * Harness (`11128`, channel check) on every account of that region, so the panel
15012
+ * offers a switch that renames the client in the outgoing prompt. "DeepSeek" is
15013
+ * the vendor that actually serves the model, so the sentences stay true, and it
15014
+ * was verified against the live host: the two prompts it refuses are accepted
15015
+ * with the product name replaced.
15016
+ */
15017
+ function replacedClientName() {
15018
+ return settings.rewriteClientName === true ? "DeepSeek" : void 0;
15019
+ }
15020
+ /**
13421
15021
  * The source and region one selected provider route belongs to.
13422
15022
  *
13423
15023
  * The composer readout is handed the session's selection straight from the
@@ -13495,9 +15095,7 @@ function workbuddyComposerAccounts(region, modelId) {
13495
15095
  const list = core.pool.list(region);
13496
15096
  const available = core.pool.available(now, modelId, region);
13497
15097
  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);
15098
+ const next = available.find((account) => account.id === preferredId) ?? core.pool.preview(available);
13501
15099
  return list.map((account) => {
13502
15100
  const cached = probeCache.get(account.id)?.value?.credits;
13503
15101
  return {
@@ -13512,15 +15110,7 @@ function workbuddyComposerAccounts(region, modelId) {
13512
15110
  function sourceComposerAccounts(source, region) {
13513
15111
  const rows = (source === "trae" ? traeAccountRows : qoderAccountRows).filter((row) => row.region === region);
13514
15112
  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
- }
15113
+ const active = orderSourceCredentials(source, region, live, (row) => row.label, false)[0];
13524
15114
  return rows.map((row) => {
13525
15115
  const credits = row.usage?.credits;
13526
15116
  return {
@@ -13752,6 +15342,7 @@ const Config = z.object({
13752
15342
  preferredSourceAccounts: asVolatile(z.any().description("Picked Trae/Qoder account per region")),
13753
15343
  removedAccounts: asVolatile(z.any().description("Accounts removed from the pool for good")),
13754
15344
  showComposerPoints: asVolatile(z.boolean().default(false).description("Show the active account credits beside the composer")),
15345
+ rewriteClientName: asVolatile(z.boolean().default(false).description("Rename the client in the prompt WorkBuddy receives (domestic channel check 11128)")),
13755
15346
  sourceDistributions: asVolatile(z.any().description("How each Trae/Qoder region spreads requests"))
13756
15347
  });
13757
15348
  /** Peel one volatile reference, if the running line wrapped it. */
@@ -13988,8 +15579,6 @@ function registrationFingerprint(descriptors) {
13988
15579
  function apply(ctx, config = {}) {
13989
15580
  const current = () => unwrapVolatileDeep(config);
13990
15581
  const settingsNamespace = settingsNamespaceOf(ctx);
13991
- const commandNotes = new AsyncLocalStorage();
13992
- const commands = /* @__PURE__ */ new Map();
13993
15582
  const settingsListeners = /* @__PURE__ */ new Map();
13994
15583
  const settingsHandlers = /* @__PURE__ */ new Set();
13995
15584
  const token = activationToken += 1;
@@ -14074,46 +15663,6 @@ function apply(ctx, config = {}) {
14074
15663
  settingsListeners.get(handler)?.();
14075
15664
  settingsListeners.delete(handler);
14076
15665
  },
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
15666
  /**
14118
15667
  * Publish the provider rows.
14119
15668
  *
@@ -14226,8 +15775,6 @@ function apply(ctx, config = {}) {
14226
15775
  ctx.effect(() => async () => {
14227
15776
  stopped = true;
14228
15777
  lastRows = [];
14229
- for (const dispose of commands.values()) dispose();
14230
- commands.clear();
14231
15778
  for (const dispose of settingsListeners.values()) dispose();
14232
15779
  settingsListeners.clear();
14233
15780
  disposeRegistration?.();