dsh-wtq-pool 1.1.0 → 1.2.0

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
@@ -13,7 +13,7 @@ import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
13
13
  import z from "@deepseek-ai/schemastery";
14
14
  import { createServer } from "node:http";
15
15
  import * as net from "node:net";
16
- import { isIP } from "node:net";
16
+ import { BlockList, isIP } from "node:net";
17
17
  import { constants, createCipheriv, createDecipheriv, createHash, publicEncrypt, randomBytes, randomUUID } from "node:crypto";
18
18
  import * as fs$1 from "node:fs";
19
19
  import { statSync } from "node:fs";
@@ -183,18 +183,22 @@ function redactSecrets(text) {
183
183
  /**
184
184
  * The vendor's channel check, answered as what it is.
185
185
  *
186
- * WorkBuddy's upstream refuses a request whose prompt names DeepSeek Harness as
187
- * the client, with code 11128 and "Illegal API invocation from an unapproved
188
- * channel". The refusal is about the caller's identity rather than the account:
189
- * every account of that region answers it the same way, so rotating cannot clear
190
- * it, and the body is a wall of mixed Chinese and English tips that names no
191
- * cause a user can act on. The sentence below says what happened and what does
192
- * work. Verified 2026-10-21 on the domestic host: the same prompt is served by
193
- * the international WorkBuddy accounts, by Trae and by Qoder.
186
+ * WorkBuddy's upstream inspects the system and assistant turns for wording that
187
+ * belongs to a client it does not serve, and answers business code 11128. The
188
+ * plugin already moves the system prompt into the first user turn and retries
189
+ * once (`chatStream`); a second refusal means the blocked wording is somewhere
190
+ * that move does not reach, or the host changed its screen again. Every account
191
+ * of that region answers the same way, so rotation cannot clear it, and the
192
+ * vendor body is a wall of mixed Chinese and English tips that names no cause a
193
+ * user can act on. The sentence below says what happened and what does work.
194
194
  */
195
195
  function unapprovedChannelRefusal(text) {
196
- if (!/"code"\s*:\s*11128\b/.test(text)) return void 0;
197
- 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.";
196
+ if (!/"code"\s*:\s*"?11128\b/u.test(text) && !/\bcode 11128\b/u.test(text)) return void 0;
197
+ return channelCheckRefusal();
198
+ }
199
+ /** The sentence a refused prompt is answered with, whatever shape the body has. */
200
+ function channelCheckRefusal() {
201
+ return "the WorkBuddy host refused this conversation at its client check (11128). That screen reads system and assistant turns for wording that belongs to a client it does not serve, so remove client-identifying text from the conversation, start a new one, or use Trae or Qoder for this prompt.";
198
202
  }
199
203
  /**
200
204
  * The `finish_reason` one turn is reported with.
@@ -473,19 +477,8 @@ async function pumpToResponse(source, res) {
473
477
  for (;;) {
474
478
  const next = await reader.read();
475
479
  if (next.done) break;
480
+ await writeChunk(res, next.value);
476
481
  if (res.destroyed || res.writableEnded) break;
477
- if (!res.write(Buffer.from(next.value))) {
478
- if (res.destroyed) break;
479
- await new Promise((resolve) => {
480
- const wake = () => {
481
- res.off("drain", wake);
482
- res.off("close", wake);
483
- resolve();
484
- };
485
- res.once("drain", wake);
486
- res.once("close", wake);
487
- });
488
- }
489
482
  }
490
483
  } finally {
491
484
  res.off("close", cancel);
@@ -793,7 +786,6 @@ const CHANNELS = /* @__PURE__ */ new Set([
793
786
  "xd.distribution",
794
787
  "xd.setAutoCheckin",
795
788
  "xd.setComposerPoints",
796
- "xd.setRewriteClientName",
797
789
  "xd.setCreditReserve",
798
790
  "xd.setRegionEnabled",
799
791
  "xd.setSource",
@@ -831,63 +823,18 @@ const PANEL_CSP = [
831
823
  "base-uri 'none'",
832
824
  "form-action 'none'"
833
825
  ].join("; ");
834
- /**
835
- * The eight 16-bit groups of an IPv6 address, in any spelling.
836
- *
837
- * Handles the compressed (`::1`), expanded (`0:0:0:0:0:0:0:1`) and dotted-quad
838
- * (`::ffff:127.0.0.1`) forms, because a peer address arrives in whichever of
839
- * them the client's stack printed. Returns undefined for anything malformed.
840
- */
841
- function ipv6Groups(address) {
842
- const halves = address.toLowerCase().split("::");
843
- if (halves.length > 2) return void 0;
844
- const expand = (side) => {
845
- if (side === void 0 || side === "") return [];
846
- const groups = side.split(":");
847
- const last = groups[groups.length - 1] ?? "";
848
- if (!last.includes(".")) return groups;
849
- const octets = last.split(".");
850
- if (octets.length !== 4) return void 0;
851
- if (!octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255)) return void 0;
852
- const high = (Number(octets[0]) << 8) + Number(octets[1]);
853
- const low = (Number(octets[2]) << 8) + Number(octets[3]);
854
- return [
855
- ...groups.slice(0, -1),
856
- high.toString(16),
857
- low.toString(16)
858
- ];
859
- };
860
- const head = expand(halves[0]);
861
- const tail = halves.length === 2 ? expand(halves[1]) : [];
862
- if (head === void 0 || tail === void 0) return void 0;
863
- const missing = 8 - head.length - tail.length;
864
- if (missing < 0) return void 0;
865
- const values = [
866
- ...head,
867
- ...Array(missing).fill("0"),
868
- ...tail
869
- ].map((group) => Number.parseInt(group, 16));
870
- return values.length === 8 && values.every((value) => Number.isInteger(value)) ? values : void 0;
871
- }
872
- /**
873
- * Whether the request's peer is this machine.
874
- *
875
- * Read off the address's own groups rather than off Node's serialised form of
876
- * it: the regex this replaces matched `[::ffff:7f00:1]`, which is what the
877
- * current Node prints for `::ffff:127.0.0.1`, and a check that depends on a
878
- * serialisation detail is one Node release away from refusing a legitimate
879
- * peer. Every address in 127/8, `::1`, and the `::ffff:127/8` mapping of that
880
- * range is this machine; nothing else is.
881
- */
826
+ const LOOPBACK = new BlockList();
827
+ LOOPBACK.addSubnet("127.0.0.0", 8, "ipv4");
828
+ LOOPBACK.addAddress("::1", "ipv6");
829
+ LOOPBACK.addSubnet("::ffff:127.0.0.0", 104, "ipv6");
830
+ /** Whether the request's peer is this machine. */
882
831
  function peerIsLoopback(req) {
883
832
  const address = req.socket.remoteAddress;
884
833
  if (address === void 0) return false;
885
- if (isIP(address) === 4) return address.startsWith("127.");
886
- if (isIP(address) !== 6) return false;
887
- const groups = ipv6Groups(address);
888
- if (groups === void 0) return false;
889
- if (groups.slice(0, 6).every((value) => value === 0) && groups[6] === 0 && groups[7] === 1) return true;
890
- return groups.slice(0, 5).every((value) => value === 0) && groups[5] === 65535 && (groups[6] ?? 0) >> 8 === 127;
834
+ const family = isIP(address);
835
+ if (family === 4) return LOOPBACK.check(address, "ipv4");
836
+ if (family === 6) return LOOPBACK.check(address, "ipv6");
837
+ return false;
891
838
  }
892
839
  /**
893
840
  * Whether the request's own headers say the page asking is this origin.
@@ -1230,29 +1177,33 @@ const CN_BILLING_BASE = "https://www.codebuddy.cn";
1230
1177
  /** Global base for `workbuddy.ai` logins. */
1231
1178
  const GLOBAL_BASE$1 = "https://www.workbuddy.ai";
1232
1179
  /**
1233
- * One client version for every WorkBuddy call.
1180
+ * Client versions the two gateways see, and the headers that carry them.
1234
1181
  *
1235
- * The version appears twice in a request: `X-IDE-Version` and the version
1236
- * segment of the UA. They were three literals (5.8.4 in the header, 5.5.4 in the
1237
- * CN UA, 5.5.2 for the roster), which is a combination no real client produces.
1238
- * The 5.8.4 desktop spelling still returns the full 28-model roster from the
1239
- * global config (verified 2026-10-26), so every call reads from here.
1182
+ * CN desktop 5.9.3 (2026-10-27) sends `X-Agent-Runtime: local-agent` and the
1183
+ * same `X-Stainless-*` family as the bundled CLI. The international desktop is
1184
+ * still 5.8.4. Keeping one literal for both was one version behind on CN and
1185
+ * produced a combination no installed client sends.
1240
1186
  */
1241
- const CLIENT_VERSION = "5.8.4";
1242
- const CLI_VERSION = "2.161.0";
1187
+ const CN_CLIENT_VERSION = "5.9.3";
1188
+ const CN_CLI_VERSION = "2.165.0";
1189
+ const GLOBAL_CLIENT_VERSION = "5.8.4";
1190
+ const GLOBAL_CLI_VERSION = "2.161.0";
1243
1191
  /** CN chat UA: the desktop client's three-segment spelling. */
1244
- const CLIENT_UA = `WorkBuddy/${CLIENT_VERSION} WorkBuddy/${CLIENT_VERSION} CLI/${CLI_VERSION}`;
1192
+ const CN_CHAT_UA = `WorkBuddy/${CN_CLIENT_VERSION} WorkBuddy/${CN_CLIENT_VERSION} CLI/${CN_CLI_VERSION}`;
1193
+ /** CN desktop UA, used by the endpoints the desktop process calls directly. */
1194
+ const CN_DESKTOP_UA = `WorkBuddy/${CN_CLIENT_VERSION}`;
1245
1195
  /**
1246
- * The international desktop client's own chat UA: the `workbuddy-ai/` segment
1247
- * only exists on that gateway, and the CN spelling gets the CLI roster there.
1196
+ * The international desktop client's UA. The `workbuddy-ai/` segment only
1197
+ * exists on that gateway, and the CN spelling gets the CLI roster there.
1248
1198
  */
1249
- const GLOBAL_CHAT_UA = `WorkBuddy/${CLIENT_VERSION} workbuddy-ai/${CLIENT_VERSION} CLI/${CLI_VERSION}`;
1199
+ const GLOBAL_CHAT_UA = `WorkBuddy/${GLOBAL_CLIENT_VERSION} workbuddy-ai/${GLOBAL_CLIENT_VERSION} CLI/${GLOBAL_CLI_VERSION}`;
1250
1200
  /**
1251
- * Desktop app UA. The global gateway serves its product config only to this
1252
- * client channel: the CLI UA gets a truncated roster (or an HTTP 500), which
1253
- * is why the international catalog must be read with the desktop spelling.
1201
+ * Desktop app UA for the global gateway. It serves its product config only to
1202
+ * this client channel: the CLI UA gets a truncated roster (or an HTTP 500),
1203
+ * which is why the international catalog must be read with the desktop
1204
+ * spelling.
1254
1205
  */
1255
- const DESKTOP_UA = `WorkBuddy/${CLIENT_VERSION}`;
1206
+ const GLOBAL_DESKTOP_UA = `WorkBuddy/${GLOBAL_CLIENT_VERSION}`;
1256
1207
  /** CN model catalog. */
1257
1208
  const MODELS_CATALOG_PATH = "/v2/enterprises/personal/models";
1258
1209
  /** Global product config, which carries the international model roster. */
@@ -1462,6 +1413,15 @@ const SESSION_DEAD_PATTERN = /Offline user session not found|"code"\s*:\s*"?1215
1462
1413
  */
1463
1414
  const MODEL_TIER_PATTERN = /"code"\s*:\s*"?11158\b/u;
1464
1415
  /**
1416
+ * The prompt-screen refusal: `11128`.
1417
+ *
1418
+ * The host returns it for a system or assistant turn whose wording belongs to a
1419
+ * client it does not serve. It is a property of the request body, not the
1420
+ * account, so the rotation must not spend another sign-in on it; `chatStream`
1421
+ * moves the system prompt into the first user turn and retries once instead.
1422
+ */
1423
+ const CHANNEL_CHECK_PATTERN = /"code"\s*:\s*"?11128\b/u;
1424
+ /**
1465
1425
  * The vendor's account-level restriction: `11140`, "request illegal".
1466
1426
  *
1467
1427
  * The body names the account ("your account has been restricted due to unusual
@@ -1471,6 +1431,15 @@ const MODEL_TIER_PATTERN = /"code"\s*:\s*"?11158\b/u;
1471
1431
  */
1472
1432
  const ACCOUNT_RESTRICTED_PATTERN = /"code"\s*:\s*"?11140\b/u;
1473
1433
  /**
1434
+ * The upstream's rate-limit marker.
1435
+ *
1436
+ * The same envelope is returned with HTTP 200 by JSON endpoints and by the
1437
+ * chat screen, so the status alone cannot decide it. The code is matched as an
1438
+ * envelope value rather than as a bare number for the reason above; the text
1439
+ * forms cover the older deployments that answer with prose only.
1440
+ */
1441
+ const SOFT_RATE_PATTERN = /"code"\s*:\s*"?6004\b|soft_rate|频率限制/u;
1442
+ /**
1474
1443
  * Hosts the international product answers on, once each has been stripped of a
1475
1444
  * leading label. The WorkBuddy AI desktop app signs in at `workbuddy.ai` (and
1476
1445
  * the desktop client itself lists `workbuddy.cc` alongside it); the CodeBuddy
@@ -1490,6 +1459,35 @@ function regionOf(domain) {
1490
1459
  for (const host of GLOBAL_HOSTS) if (lowered === host || lowered.endsWith(`.${host}`)) return "global";
1491
1460
  return "cn";
1492
1461
  }
1462
+ /** The client version that gateway expects in `X-IDE-Version`. */
1463
+ function clientVersion(region) {
1464
+ return region === "global" ? GLOBAL_CLIENT_VERSION : CN_CLIENT_VERSION;
1465
+ }
1466
+ /** The full chat UA for the credential's gateway. */
1467
+ function chatUa(region) {
1468
+ return region === "global" ? GLOBAL_CHAT_UA : CN_CHAT_UA;
1469
+ }
1470
+ /** The desktop-process UA for endpoints outside the chat path. */
1471
+ function desktopUa(region) {
1472
+ return region === "global" ? GLOBAL_DESKTOP_UA : CN_DESKTOP_UA;
1473
+ }
1474
+ /**
1475
+ * The OpenAI Node SDK's fingerprint headers, as the current desktop client sends
1476
+ * them. OS, architecture and runtime version follow the host so a macOS or Linux
1477
+ * install does not claim to be a Windows client; the rest mirror the bundled CLI.
1478
+ */
1479
+ function stainlessHeaders() {
1480
+ return {
1481
+ "x-stainless-lang": "js",
1482
+ "x-stainless-package-version": "6.25.0",
1483
+ "x-stainless-os": process.platform === "win32" ? "Windows" : process.platform === "darwin" ? "MacOS" : "Linux",
1484
+ "x-stainless-arch": process.arch,
1485
+ "x-stainless-runtime": "node",
1486
+ "x-stainless-runtime-version": process.version,
1487
+ "x-stainless-retry-count": "0",
1488
+ "x-stainless-timeout": "1200"
1489
+ };
1490
+ }
1493
1491
  /**
1494
1492
  * Gateway for a global credential.
1495
1493
  *
@@ -1516,7 +1514,7 @@ function commonHeaders(credential) {
1516
1514
  "X-Requested-With": "XMLHttpRequest",
1517
1515
  "Origin": billingBase(credential),
1518
1516
  "Referer": `${billingBase(credential)}/`,
1519
- "User-Agent": CLIENT_UA,
1517
+ "User-Agent": desktopUa(regionOf(credential.domain)),
1520
1518
  "X-CodeBuddy-Request": "1",
1521
1519
  "Connection": "close"
1522
1520
  };
@@ -1542,7 +1540,7 @@ function commonHeaders(credential) {
1542
1540
  * one - so there is nothing to gain from deriving it, and a stable value would
1543
1541
  * be one more thing for the channel check to notice.
1544
1542
  */
1545
- function conversationHeaders() {
1543
+ function conversationHeaders(region) {
1546
1544
  const turn = randomUUID().replace(/-/g, "");
1547
1545
  const message = randomUUID().replace(/-/g, "");
1548
1546
  const traceId = randomUUID().replace(/-/g, "");
@@ -1556,7 +1554,7 @@ function conversationHeaders() {
1556
1554
  "X-Agent-Intent": "craft",
1557
1555
  "X-Agent-Purpose": "conversation",
1558
1556
  "X-Agent-Type": "main",
1559
- "X-IDE-Version": CLIENT_VERSION,
1557
+ "X-IDE-Version": clientVersion(region),
1560
1558
  "X-Private-Data": "true",
1561
1559
  "X-Trace-ID": traceId,
1562
1560
  "traceparent": `00-${traceId}-${spanId}-01`,
@@ -1568,16 +1566,19 @@ function conversationHeaders() {
1568
1566
  }
1569
1567
  /** Chat request headers, including the X-No-* conventions the official CLI uses. */
1570
1568
  function chatHeaders(credential) {
1569
+ const region = regionOf(credential.domain);
1571
1570
  return {
1572
1571
  ...commonHeaders(credential),
1573
- ...conversationHeaders(),
1572
+ ...conversationHeaders(region),
1573
+ ...stainlessHeaders(),
1574
1574
  "Content-Type": "application/json",
1575
1575
  "Authorization": `Bearer ${credential.accessToken}`,
1576
1576
  ...credential.uid === "" || credential.uid === void 0 ? { "X-No-User-Id": "1" } : { "X-User-Id": credential.uid },
1577
1577
  ...credential.enterpriseId === void 0 || credential.enterpriseId === "" ? { "X-No-Enterprise-Id": "1" } : { "X-Enterprise-Id": credential.enterpriseId },
1578
1578
  ...credential.domain === "" ? { "X-No-Department-Info": "1" } : { "X-Domain": credential.domain },
1579
1579
  "X-Product": "SaaS",
1580
- ...regionOf(credential.domain) === "global" ? { "User-Agent": GLOBAL_CHAT_UA } : {}
1580
+ ...region === "cn" ? { "X-Agent-Runtime": "local-agent" } : {},
1581
+ "User-Agent": chatUa(region)
1581
1582
  };
1582
1583
  }
1583
1584
  /** Refresh-endpoint headers; X-Refresh-Token appears here and nowhere else. */
@@ -1597,7 +1598,7 @@ function billingHeaders(credential) {
1597
1598
  "Accept": "application/json",
1598
1599
  "Content-Type": "application/json",
1599
1600
  "X-CodeBuddy-Request": "1",
1600
- "User-Agent": CLIENT_UA,
1601
+ "User-Agent": desktopUa(regionOf(credential.domain)),
1601
1602
  "Connection": "close"
1602
1603
  };
1603
1604
  if (credential.uid !== "" && credential.uid !== void 0) headers["X-User-Id"] = credential.uid;
@@ -1700,8 +1701,9 @@ async function readEnvelope(response) {
1700
1701
  }
1701
1702
  if (typeof parsed !== "object" || parsed === null) throw new Error(`workbuddy upstream returned an unexpected document (http ${response.status})`);
1702
1703
  const document = parsed;
1704
+ const rawCode = document["code"];
1703
1705
  return {
1704
- code: typeof document["code"] === "number" ? document["code"] : 0,
1706
+ code: typeof rawCode === "number" && Number.isFinite(rawCode) ? rawCode : typeof rawCode === "string" && /^-?\d+$/u.test(rawCode.trim()) ? Number(rawCode.trim()) : 0,
1705
1707
  msg: typeof document["msg"] === "string" ? document["msg"] : "",
1706
1708
  data: "data" in document ? document["data"] : void 0
1707
1709
  };
@@ -1737,15 +1739,23 @@ function upstreamErrorKind(error) {
1737
1739
  * fires on any other status, or a rate limit whose text happens to carry
1738
1740
  * the code would rotate without cooling the account.
1739
1741
  *
1740
- * The credit markers are read only on statuses the upstream itself uses for
1741
- * "this account cannot pay": 402 and 403. A 400 or 422 is a verdict on the
1742
- * REQUEST, and its body routinely quotes the quota it measured against, so
1743
- * matching there turned a malformed body into a whole-pool rotation and a
1744
- * 402 that named the wrong problem.
1742
+ * The credit markers are read on the statuses the upstream itself uses for
1743
+ * "this account cannot pay": 402, 403, and an HTTP 200 business envelope. A
1744
+ * 400 or 422 is a verdict on the REQUEST, and its body routinely quotes the
1745
+ * quota it measured against, so matching there turned a malformed body into a
1746
+ * whole-pool rotation and a 402 that named the wrong problem.
1745
1747
  */
1746
1748
  function classifyUpstreamError(status, body) {
1747
1749
  if (status === 402) return "hard_credit";
1748
1750
  if (status === 429) return "soft_rate";
1751
+ if (status === 200) {
1752
+ if (ACCOUNT_RESTRICTED_PATTERN.test(body)) return "account_restricted";
1753
+ if (MODEL_TIER_PATTERN.test(body)) return "model_tier";
1754
+ if (SESSION_DEAD_PATTERN.test(body)) return "session_dead";
1755
+ if (SOFT_RATE_PATTERN.test(body)) return "soft_rate";
1756
+ if (isHardCreditText(body)) return "hard_credit";
1757
+ return "client";
1758
+ }
1749
1759
  if ((status === 400 || status === 403 || status === 422) && ACCOUNT_RESTRICTED_PATTERN.test(body)) return "account_restricted";
1750
1760
  if ((status === 400 || status === 403 || status === 422) && MODEL_TIER_PATTERN.test(body)) return "model_tier";
1751
1761
  if ((status === 401 || status === 403) && SESSION_DEAD_PATTERN.test(body)) return "session_dead";
@@ -1753,7 +1763,7 @@ function classifyUpstreamError(status, body) {
1753
1763
  if (status === 403) {
1754
1764
  if (isHardCreditText(body)) return "hard_credit";
1755
1765
  }
1756
- if (status === 503 && (body.includes("soft_rate") || body.includes("\"code\":6004") || body.includes("频率限制"))) return "soft_rate";
1766
+ if (status === 503 && SOFT_RATE_PATTERN.test(body)) return "soft_rate";
1757
1767
  if (status === 403 && !body.includes("\"code\":") && !body.includes("\"msg\":")) return "waf_block";
1758
1768
  if (status === 404) return "not_found";
1759
1769
  if (status >= 500) return "server";
@@ -1928,6 +1938,158 @@ function withLeadingSystemPrompt(prepared) {
1928
1938
  }, ...messages];
1929
1939
  return JSON.stringify(obj);
1930
1940
  }
1941
+ /**
1942
+ * System prompts the host has already refused at its channel check.
1943
+ *
1944
+ * WorkBuddy's prompt screen reads system and assistant roles, not user turns, and
1945
+ * it matches more than one client's wording: the DSH opening line, the DSH GUI
1946
+ * pair, and several lines shared with other agent harnesses. A fixed rewrite list
1947
+ * is therefore always one upstream change behind. The first turn that is refused
1948
+ * pays one 400, its system prompt is folded into the first user message, and the
1949
+ * same prompt is folded before sending from then on. Bounded so a process that
1950
+ * sees many one-off prompts keeps only recent ones.
1951
+ */
1952
+ const FOLDED_PROMPTS_MAX = 32;
1953
+ const foldedPrompts = /* @__PURE__ */ new Set();
1954
+ /** The fingerprint of every system message in a prepared body, if it has one. */
1955
+ function systemPromptFingerprint(prepared) {
1956
+ let body;
1957
+ try {
1958
+ body = JSON.parse(prepared);
1959
+ } catch {
1960
+ return;
1961
+ }
1962
+ const messages = body?.messages;
1963
+ if (!Array.isArray(messages)) return void 0;
1964
+ const texts = [];
1965
+ for (const value of messages) {
1966
+ if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
1967
+ const message = value;
1968
+ if (message["role"] !== "system" && message["role"] !== "developer") continue;
1969
+ texts.push(contentText(message["content"]));
1970
+ }
1971
+ if (texts.length === 0) return void 0;
1972
+ return createHash("sha256").update(texts.join("\0")).digest("hex");
1973
+ }
1974
+ /** The text parts of a message content value, joined for the fingerprint and fold. */
1975
+ function contentText(content) {
1976
+ if (typeof content === "string") return content;
1977
+ if (!Array.isArray(content)) return "";
1978
+ const parts = [];
1979
+ for (const part of content) if (typeof part === "string") parts.push(part);
1980
+ else if (typeof part === "object" && part !== null && typeof part["text"] === "string") parts.push(part["text"]);
1981
+ return parts.join("\n");
1982
+ }
1983
+ /**
1984
+ * Move every system message into the first user message, and take the client
1985
+ * name out of assistant turns.
1986
+ *
1987
+ * The host accepts the same instructions in a user turn; a system turn is what
1988
+ * its channel check inspects. Assistant turns are inspected too, so a reply that
1989
+ * quoted the client name would fail the next request; that copy is renamed. A
1990
+ * neutral system message stays first so a gateway that insists on one still sees
1991
+ * it. Returns undefined when there is nothing to move or rename, which is also
1992
+ * what keeps an empty system message from looping.
1993
+ */
1994
+ function foldSystemIntoUser(prepared) {
1995
+ let body;
1996
+ try {
1997
+ body = JSON.parse(prepared);
1998
+ } catch {
1999
+ return;
2000
+ }
2001
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
2002
+ const obj = body;
2003
+ const messages = obj["messages"];
2004
+ if (!Array.isArray(messages)) return void 0;
2005
+ const prompts = [];
2006
+ const rest = [];
2007
+ let renamed = false;
2008
+ for (const value of messages) {
2009
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
2010
+ const message = value;
2011
+ if (message["role"] === "system" || message["role"] === "developer") {
2012
+ const text = contentText(message["content"]);
2013
+ if (text.trim() !== "") prompts.push(text);
2014
+ continue;
2015
+ }
2016
+ if (message["role"] === "assistant" && "content" in message) {
2017
+ const content = renameInContent(message["content"]);
2018
+ if (content !== message["content"]) {
2019
+ renamed = true;
2020
+ rest.push({
2021
+ ...message,
2022
+ content
2023
+ });
2024
+ continue;
2025
+ }
2026
+ }
2027
+ }
2028
+ rest.push(value);
2029
+ }
2030
+ if (prompts.length === 0 && !renamed) return void 0;
2031
+ if (prompts.length === 0) {
2032
+ obj["messages"] = rest;
2033
+ return JSON.stringify(obj);
2034
+ }
2035
+ const instructions = prompts.join("\n\n");
2036
+ const firstUser = rest.findIndex((value) => typeof value === "object" && value !== null && !Array.isArray(value) && value["role"] === "user");
2037
+ if (firstUser === -1) rest.unshift({
2038
+ role: "user",
2039
+ content: instructions
2040
+ });
2041
+ else {
2042
+ const message = rest[firstUser];
2043
+ const content = message["content"];
2044
+ rest[firstUser] = {
2045
+ ...message,
2046
+ content: typeof content === "string" ? `${instructions}\n\n${content}` : [{
2047
+ type: "text",
2048
+ text: instructions
2049
+ }, ...Array.isArray(content) ? content : []]
2050
+ };
2051
+ }
2052
+ obj["messages"] = [{
2053
+ role: "system",
2054
+ content: ""
2055
+ }, ...rest];
2056
+ return JSON.stringify(obj);
2057
+ }
2058
+ /**
2059
+ * Rename the client in one message content, preserving every other field.
2060
+ *
2061
+ * Matched case-insensitively because the host's screen is, and only the product
2062
+ * name is replaced: the rest of the sentence still reads naturally, and the
2063
+ * model sees the same instructions.
2064
+ */
2065
+ function renameInContent(content) {
2066
+ const rename = (text) => text.replace(/DeepSeek Harness/gi, "DeepSeek");
2067
+ if (typeof content === "string") return rename(content);
2068
+ if (!Array.isArray(content)) return content;
2069
+ return content.map((part) => {
2070
+ if (typeof part === "string") return rename(part);
2071
+ if (typeof part !== "object" || part === null || Array.isArray(part)) return part;
2072
+ const record = part;
2073
+ if (typeof record["text"] !== "string") return part;
2074
+ const text = rename(record["text"]);
2075
+ return text === record["text"] ? part : {
2076
+ ...record,
2077
+ text
2078
+ };
2079
+ });
2080
+ }
2081
+ function rememberFoldedPrompt(fingerprint) {
2082
+ if (foldedPrompts.has(fingerprint)) return;
2083
+ if (foldedPrompts.size >= FOLDED_PROMPTS_MAX) {
2084
+ const oldest = foldedPrompts.values().next().value;
2085
+ if (oldest !== void 0) foldedPrompts.delete(oldest);
2086
+ }
2087
+ foldedPrompts.add(fingerprint);
2088
+ }
2089
+ /** Whether a 400 body is the host's prompt screen rather than a bad request. */
2090
+ function isChannelCheckText(text) {
2091
+ return CHANNEL_CHECK_PATTERN.test(text);
2092
+ }
1931
2093
  var WorkBuddyUpstreamClient = class {
1932
2094
  fetchImpl;
1933
2095
  constructor(options = {}) {
@@ -1954,6 +2116,10 @@ var WorkBuddyUpstreamClient = class {
1954
2116
  if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
1955
2117
  const message = value;
1956
2118
  if (message["role"] === "developer") message["role"] = "system";
2119
+ if (message["role"] === "assistant" && "content" in message) {
2120
+ const content = renameInContent(message["content"]);
2121
+ if (content !== message["content"]) message["content"] = content;
2122
+ }
1957
2123
  }
1958
2124
  const choice = obj["tool_choice"];
1959
2125
  if (typeof choice === "string") {
@@ -1981,58 +2147,104 @@ var WorkBuddyUpstreamClient = class {
1981
2147
  }
1982
2148
  /** Forward one chat completion. Never throws for upstream failures. */
1983
2149
  async chatStream(credential, prepared, signal, timeouts) {
1984
- let response;
1985
- const deadline = headersDeadline(signal, timeouts?.headersMs ?? STREAM_HEADERS_TIMEOUT_MS);
1986
- const body = regionOf(credential.domain) === "global" ? withLeadingSystemPrompt(prepared) : prepared;
1987
- try {
1988
- response = await this.fetchImpl(`${chatBase(credential)}/v2/chat/completions`, {
1989
- redirect: "error",
1990
- method: "POST",
1991
- headers: chatHeaders(credential),
1992
- body,
1993
- signal: deadline.signal
1994
- });
1995
- } catch (error) {
1996
- if (signal?.aborted === true) return {
1997
- ok: false,
1998
- kind: "aborted",
1999
- status: 0,
2000
- message: "cancelled by the caller"
2001
- };
2150
+ const fingerprint = systemPromptFingerprint(prepared);
2151
+ const region = regionOf(credential.domain);
2152
+ let body = region === "global" ? withLeadingSystemPrompt(prepared) : prepared;
2153
+ const cacheKey = fingerprint === void 0 ? void 0 : `${region}:${fingerprint}`;
2154
+ if (cacheKey !== void 0 && foldedPrompts.has(cacheKey)) body = foldSystemIntoUser(body) ?? body;
2155
+ let rememberOnSuccess;
2156
+ for (let attempt = 0;; attempt++) {
2157
+ let response;
2158
+ const deadline = headersDeadline(signal, timeouts?.headersMs ?? STREAM_HEADERS_TIMEOUT_MS);
2159
+ try {
2160
+ response = await this.fetchImpl(`${chatBase(credential)}/v2/chat/completions`, {
2161
+ redirect: "error",
2162
+ method: "POST",
2163
+ headers: chatHeaders(credential),
2164
+ body,
2165
+ signal: deadline.signal
2166
+ });
2167
+ } catch (error) {
2168
+ if (signal?.aborted === true) return {
2169
+ ok: false,
2170
+ kind: "aborted",
2171
+ status: 0,
2172
+ message: "cancelled by the caller"
2173
+ };
2174
+ return {
2175
+ ok: false,
2176
+ kind: "transport",
2177
+ status: 0,
2178
+ message: `transport error: ${String(error)}`
2179
+ };
2180
+ } finally {
2181
+ deadline.arrived();
2182
+ }
2183
+ if (response.ok) {
2184
+ const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
2185
+ const declaredLength = Number(response.headers.get("content-length") ?? "");
2186
+ const smallDeclaredBody = Number.isFinite(declaredLength) && declaredLength > 0 && declaredLength <= ERROR_BODY_LIMIT;
2187
+ if (contentType.includes("application/json") || smallDeclaredBody && !contentType.includes("text/event-stream")) {
2188
+ const text = await readErrorBody(response, ERROR_BODY_LIMIT, signal);
2189
+ if (attempt === 0 && isChannelCheckText(text)) {
2190
+ const folded = foldSystemIntoUser(body);
2191
+ if (folded !== void 0) {
2192
+ rememberOnSuccess = cacheKey;
2193
+ body = folded;
2194
+ continue;
2195
+ }
2196
+ }
2197
+ if (rememberOnSuccess !== void 0 && !isChannelCheckText(text)) rememberFoldedPrompt(rememberOnSuccess);
2198
+ const envelopeResponse = new Response(text, {
2199
+ status: response.status,
2200
+ headers: response.headers
2201
+ });
2202
+ const envelopeBody = envelopeResponse.body;
2203
+ if (envelopeBody === null) return {
2204
+ ok: false,
2205
+ kind: "server",
2206
+ status: 502,
2207
+ message: "upstream returned 200 without a body"
2208
+ };
2209
+ return {
2210
+ ok: true,
2211
+ response: withRelayStream(envelopeResponse, envelopeBody)
2212
+ };
2213
+ }
2214
+ if (rememberOnSuccess !== void 0) rememberFoldedPrompt(rememberOnSuccess);
2215
+ if (response.body === null) return {
2216
+ ok: false,
2217
+ kind: "server",
2218
+ status: 502,
2219
+ message: "upstream returned 200 without a stream"
2220
+ };
2221
+ const relayed = withIdleWatchdog(response.body, timeouts?.idleMs, signal);
2222
+ return {
2223
+ ok: true,
2224
+ response: withRelayStream(new Response(relayed, {
2225
+ status: response.status,
2226
+ headers: response.headers
2227
+ }), relayed)
2228
+ };
2229
+ }
2230
+ const text = await readErrorBody(response, ERROR_BODY_LIMIT, signal);
2231
+ const retryAfter = retryAfterSeconds(response.headers);
2232
+ if (attempt === 0 && response.status === 400 && isChannelCheckText(text)) {
2233
+ const folded = foldSystemIntoUser(body);
2234
+ if (folded !== void 0) {
2235
+ rememberOnSuccess = cacheKey;
2236
+ body = folded;
2237
+ continue;
2238
+ }
2239
+ }
2002
2240
  return {
2003
2241
  ok: false,
2004
- kind: "transport",
2005
- status: 0,
2006
- message: `transport error: ${String(error)}`
2007
- };
2008
- } finally {
2009
- deadline.arrived();
2010
- }
2011
- if (response.ok) {
2012
- if (response.body === null) return {
2013
- ok: false,
2014
- kind: "server",
2015
- status: 502,
2016
- message: "upstream returned 200 without a stream"
2017
- };
2018
- const relayed = withIdleWatchdog(response.body, timeouts?.idleMs, signal);
2019
- return {
2020
- ok: true,
2021
- response: withRelayStream(new Response(relayed, {
2022
- status: response.status,
2023
- headers: response.headers
2024
- }), relayed)
2242
+ kind: classifyUpstreamError(response.status, text),
2243
+ status: response.status,
2244
+ message: isGatewayHtmlRejection(response.status, text) ? gatewayRejectionText(response.status) : text,
2245
+ ...retryAfter === void 0 ? {} : { retryAfter }
2025
2246
  };
2026
2247
  }
2027
- const text = await readErrorBody(response, ERROR_BODY_LIMIT, signal);
2028
- const retryAfter = retryAfterSeconds(response.headers);
2029
- return {
2030
- ok: false,
2031
- kind: classifyUpstreamError(response.status, text),
2032
- status: response.status,
2033
- message: isGatewayHtmlRejection(response.status, text) ? gatewayRejectionText(response.status) : text,
2034
- ...retryAfter === void 0 ? {} : { retryAfter }
2035
- };
2036
2248
  }
2037
2249
  /** POST the token-refresh endpoint; the caller merges the outcome. */
2038
2250
  async refreshToken(credential) {
@@ -2058,8 +2270,9 @@ var WorkBuddyUpstreamClient = class {
2058
2270
  *
2059
2271
  * The two gateways are read differently, because they answer differently:
2060
2272
  *
2061
- * - **CN** serves the roster at `/v2/enterprises/personal/models` and expects
2062
- * the CLI client spelling.
2273
+ * - **CN** serves the roster at `/v2/enterprises/personal/models`. Like the
2274
+ * desktop process that calls it directly, it expects the desktop client
2275
+ * spelling; this is not the chat endpoint's three-segment UA.
2063
2276
  * - **Global** serves it as part of the product config at `/v3/config`, and
2064
2277
  * only to the DESKTOP client channel. Asking the global host with the CLI UA
2065
2278
  * yields a truncated roster, and the CN path answers HTTP 500 there — which
@@ -2080,7 +2293,7 @@ var WorkBuddyUpstreamClient = class {
2080
2293
  "X-Requested-With": "XMLHttpRequest",
2081
2294
  "X-CodeBuddy-Request": "1",
2082
2295
  "Connection": "close",
2083
- "User-Agent": DESKTOP_UA
2296
+ "User-Agent": GLOBAL_DESKTOP_UA
2084
2297
  } : {
2085
2298
  ...commonHeaders(credential),
2086
2299
  "Authorization": `Bearer ${credential.accessToken}`,
@@ -3643,16 +3856,17 @@ async function readArchivedCredentials(file) {
3643
3856
  const record = entry;
3644
3857
  if (typeof record["id"] !== "string" || record["id"] === "") continue;
3645
3858
  if (typeof record["accessToken"] !== "string" || record["accessToken"] === "") continue;
3646
- const expiresAt = typeof record["expiresAtMs"] === "number" ? record["expiresAtMs"] : 0;
3647
- const refreshExpiresAt = typeof record["refreshExpiresAtMs"] === "number" ? record["refreshExpiresAtMs"] : 0;
3859
+ const expiresAt = typeof record["expiresAtMs"] === "number" ? expiryToMs(record["expiresAtMs"]) : 0;
3860
+ const refreshExpiresAt = typeof record["refreshExpiresAtMs"] === "number" ? expiryToMs(record["refreshExpiresAtMs"]) : 0;
3861
+ const lastRefreshAt = typeof record["lastRefreshAtMs"] === "number" ? expiryToMs(record["lastRefreshAtMs"]) : 0;
3648
3862
  const lastUsable = Math.max(expiresAt, refreshExpiresAt);
3649
3863
  if (lastUsable > 0 && lastUsable < horizon) continue;
3650
3864
  stored.set(record["id"], {
3651
3865
  accessToken: record["accessToken"],
3652
3866
  refreshToken: typeof record["refreshToken"] === "string" ? record["refreshToken"] : "",
3653
- expiresAtMs: typeof record["expiresAtMs"] === "number" ? record["expiresAtMs"] : 0,
3654
- ...typeof record["refreshExpiresAtMs"] !== "number" ? {} : { refreshExpiresAtMs: record["refreshExpiresAtMs"] },
3655
- ...typeof record["lastRefreshAtMs"] !== "number" ? {} : { lastRefreshAtMs: record["lastRefreshAtMs"] },
3867
+ expiresAtMs: expiresAt,
3868
+ ...refreshExpiresAt === 0 ? {} : { refreshExpiresAtMs: refreshExpiresAt },
3869
+ ...lastRefreshAt === 0 ? {} : { lastRefreshAtMs: lastRefreshAt },
3656
3870
  ...typeof record["nickname"] !== "string" || record["nickname"] === "" ? {} : { nickname: record["nickname"] },
3657
3871
  ...typeof record["uin"] !== "string" || record["uin"] === "" ? {} : { uin: record["uin"] },
3658
3872
  ...typeof record["uid"] !== "string" || record["uid"] === "" ? {} : { uid: record["uid"] },
@@ -4487,19 +4701,23 @@ var WorkBuddyAccountPool = class {
4487
4701
  * Scans on first use, and rescans when every known account is cooling down: a
4488
4702
  * fresh desktop login is the usual way out of an exhausted pool.
4489
4703
  */
4490
- async acquire(modelId, region, conversationKey) {
4704
+ async acquire(modelId, region, conversationKey, excludeIds) {
4705
+ const eligibleNow = () => {
4706
+ const list = this.available(Date.now(), modelId, region);
4707
+ return excludeIds === void 0 ? list : list.filter((item) => !excludeIds.has(item.id));
4708
+ };
4491
4709
  if (this.accounts.length === 0) await this.scan();
4492
- let pool = this.available(Date.now(), modelId, region);
4710
+ let pool = eligibleNow();
4493
4711
  if (pool.length === 0) {
4494
4712
  await this.scan();
4495
- pool = this.available(Date.now(), modelId, region);
4713
+ pool = eligibleNow();
4496
4714
  }
4497
4715
  if (pool.length === 0) return void 0;
4498
4716
  const preferredId = this.preferredIds.get(region);
4499
4717
  const account = pool.find((item) => item.id === preferredId) ?? this.pick(pool, conversationKey);
4500
4718
  if (account === void 0) return void 0;
4501
4719
  await this.ensureFresh(account);
4502
- const eligible = this.available(Date.now(), modelId, region);
4720
+ const eligible = eligibleNow();
4503
4721
  if (eligible.includes(account)) return account;
4504
4722
  const next = eligible.find((item) => item.id === preferredId) ?? this.pick(eligible, conversationKey);
4505
4723
  if (next === void 0) return void 0;
@@ -4548,7 +4766,17 @@ var WorkBuddyAccountPool = class {
4548
4766
  * token is unchanged, so the caller stops retrying the same dead token.
4549
4767
  */
4550
4768
  async refreshAccount(accountId) {
4551
- return await this.refreshForRetry(accountId) === "refreshed";
4769
+ return await this.refreshAccountOutcome(accountId) === "refreshed";
4770
+ }
4771
+ /**
4772
+ * The same refresh, keeping a refusal apart from a failure.
4773
+ *
4774
+ * The caller needs the difference: only the upstream turning the sign-in down
4775
+ * justifies a six-hour hold, while a timeout or an unreachable host says
4776
+ * nothing about the token and must leave the account in rotation.
4777
+ */
4778
+ async refreshAccountOutcome(accountId) {
4779
+ return await this.refreshForRetry(accountId);
4552
4780
  }
4553
4781
  /**
4554
4782
  * Refresh after a session-dead answer, keeping a refusal apart from a failure.
@@ -4565,7 +4793,7 @@ var WorkBuddyAccountPool = class {
4565
4793
  if (account.credential.refreshToken === "") return "refused";
4566
4794
  const outcome = await this.ensureFresh(account, true);
4567
4795
  if (account.credential.accessToken !== previous) return "refreshed";
4568
- return outcome === "refused" ? "refused" : "failed";
4796
+ return outcome === "failed" ? "failed" : "refused";
4569
4797
  }
4570
4798
  /**
4571
4799
  * Hold an account whose sign-in the upstream refuses.
@@ -4698,7 +4926,7 @@ var WorkBuddyAccountPool = class {
4698
4926
  penalize(accountId, resetAtMs, modelId, hold = false) {
4699
4927
  const account = this.accounts.find((item) => item.id === accountId);
4700
4928
  if (account === void 0) return;
4701
- account.rateLimitHits += 1;
4929
+ if (hold === false) account.rateLimitHits += 1;
4702
4930
  const now = Date.now();
4703
4931
  const stated = resetAtMs !== void 0 && resetAtMs > now;
4704
4932
  if (hold === false && !stated) {
@@ -5142,7 +5370,7 @@ const KIND_STATUS = {
5142
5370
  soft_rate: 429,
5143
5371
  session_dead: 401,
5144
5372
  waf_block: 502,
5145
- not_found: 502,
5373
+ not_found: 404,
5146
5374
  server: 502,
5147
5375
  client: 400,
5148
5376
  model_tier: 400,
@@ -5173,6 +5401,8 @@ function classifyEnvelopeCode(code, text) {
5173
5401
  if (code === "11140") return "account_restricted";
5174
5402
  if (code === "12153") return "session_dead";
5175
5403
  if (isHardCreditText(text)) return "hard_credit";
5404
+ const kind = classifyUpstreamError(200, text);
5405
+ return kind === "client" ? void 0 : kind;
5176
5406
  }
5177
5407
  /** Stable key for one conversation: a hash of its first user message. */
5178
5408
  function conversationKeyOf(raw) {
@@ -5246,6 +5476,7 @@ async function peekAnswerHead(reader) {
5246
5476
  return {
5247
5477
  head,
5248
5478
  ended,
5479
+ body: trimmed,
5249
5480
  refusal: sentence === "" ? "workbuddy answered 200 with a JSON body where a stream was expected" : `workbuddy answered 200 with ${sentence}`,
5250
5481
  ...named === "" ? {} : { code: String(code) }
5251
5482
  };
@@ -5253,6 +5484,7 @@ async function peekAnswerHead(reader) {
5253
5484
  return {
5254
5485
  head,
5255
5486
  ended,
5487
+ body: trimmed,
5256
5488
  refusal: `workbuddy answered 200 with a body that is neither a stream nor an envelope: ${safeMessage(trimmed.slice(0, 200))}`
5257
5489
  };
5258
5490
  }
@@ -5457,13 +5689,14 @@ function createWorkBuddyShim(options) {
5457
5689
  return;
5458
5690
  }
5459
5691
  const tried = [];
5692
+ const skipped = /* @__PURE__ */ new Set();
5460
5693
  let last;
5461
5694
  let exhaustedByRateLimit = false;
5462
5695
  let effortFallback;
5463
5696
  let effortFallbackBuilt = false;
5464
5697
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
5465
5698
  if (controller.signal.aborted) return;
5466
- const account = await pool.acquire(modelId, region, conversationKey);
5699
+ const account = await pool.acquire(modelId, region, conversationKey, skipped);
5467
5700
  if (account === void 0) {
5468
5701
  if (exhaustedByRateLimit && last !== void 0) {
5469
5702
  const model = ` for model ${modelId}`;
@@ -5491,7 +5724,23 @@ function createWorkBuddyShim(options) {
5491
5724
  }
5492
5725
  tried.push(account.label);
5493
5726
  let result = await client.chatStream(account.credential, prepared, controller.signal);
5494
- if (!result.ok && result.kind === "session_dead" && await pool.refreshAccount(account.id)) {
5727
+ let refreshOutcome;
5728
+ if (!result.ok && result.kind === "session_dead") {
5729
+ const failure = result;
5730
+ refreshOutcome = await pool.refreshAccountOutcome(account.id);
5731
+ if (refreshOutcome === "failed") {
5732
+ logger?.warn?.(`${LOG_PREFIX}: ${account.label} could not refresh its sign-in; trying the next account without holding it`);
5733
+ skipped.add(account.id);
5734
+ last = {
5735
+ kind: "transport",
5736
+ status: 502,
5737
+ message: `could not refresh the sign-in: ${failure.message}`
5738
+ };
5739
+ exhaustedByRateLimit = true;
5740
+ continue;
5741
+ }
5742
+ }
5743
+ if (refreshOutcome === "refreshed") {
5495
5744
  if (controller.signal.aborted) return;
5496
5745
  result = await client.chatStream(account.credential, prepared, controller.signal);
5497
5746
  }
@@ -5570,6 +5819,10 @@ function createWorkBuddyShim(options) {
5570
5819
  if (peeked.refusal !== void 0) {
5571
5820
  await reader.cancel().catch(() => {});
5572
5821
  logger?.warn?.(`${LOG_PREFIX}: ${account.label} answered 200 with no stream: ${peeked.refusal}`);
5822
+ if (peeked.code === "11128" || unapprovedChannelRefusal(peeked.refusal) !== void 0) {
5823
+ writeOpenAIError(res, 400, "upstream_channel_check", channelCheckRefusal());
5824
+ return;
5825
+ }
5573
5826
  const envelopeKind = classifyEnvelopeCode(peeked.code, peeked.refusal);
5574
5827
  if (envelopeKind === "soft_rate" || envelopeKind === "hard_credit" || envelopeKind === "session_dead" || envelopeKind === "account_restricted" || envelopeKind === "model_tier") {
5575
5828
  last = {
@@ -5579,9 +5832,24 @@ function createWorkBuddyShim(options) {
5579
5832
  };
5580
5833
  exhaustedByRateLimit = true;
5581
5834
  envelopeFailure = envelopeKind;
5582
- if (envelopeKind === "soft_rate") pool.penalize(account.id, void 0, modelId);
5583
- else if (envelopeKind === "model_tier") pool.blockModel(account.id, modelId, Date.now() + MODEL_TIER_HOLD_MS);
5584
- else if (envelopeKind === "session_dead" && await pool.refreshAccount(account.id)) {} else pool.penalize(account.id, holdUntil(), void 0, envelopeKind === "hard_credit" ? "spent" : envelopeKind === "session_dead" ? "session" : "restricted");
5835
+ if (envelopeKind === "soft_rate") {
5836
+ const bodyReset = parseRateLimitReset(peeked.body ?? peeked.refusal);
5837
+ const headerReset = resetFromRetryAfter(retryAfterSeconds(result.response.headers));
5838
+ const resetAtMs = bodyReset !== void 0 && bodyReset > Date.now() ? headerReset === void 0 ? bodyReset : Math.max(bodyReset, headerReset) : headerReset;
5839
+ pool.penalize(account.id, resetAtMs, modelId);
5840
+ } else if (envelopeKind === "model_tier") pool.blockModel(account.id, modelId, Date.now() + MODEL_TIER_HOLD_MS);
5841
+ else if (envelopeKind === "session_dead") {
5842
+ const refreshOutcome = await pool.refreshAccountOutcome(account.id);
5843
+ if (refreshOutcome === "refused") pool.penalize(account.id, holdUntil(), void 0, "session");
5844
+ else if (refreshOutcome === "failed") {
5845
+ skipped.add(account.id);
5846
+ last = {
5847
+ kind: "transport",
5848
+ status: 502,
5849
+ message: `could not refresh the sign-in: ${peeked.refusal.slice(0, 200)}`
5850
+ };
5851
+ }
5852
+ } else pool.penalize(account.id, holdUntil(), void 0, envelopeKind === "hard_credit" ? "spent" : "restricted");
5585
5853
  return;
5586
5854
  }
5587
5855
  writeOpenAIError(res, 502, "upstream_error", peeked.refusal);
@@ -5690,7 +5958,8 @@ function createWorkBuddyShim(options) {
5690
5958
  exhaustedByRateLimit = true;
5691
5959
  if (result.kind === "soft_rate") {
5692
5960
  const bodyReset = parseRateLimitReset(result.message);
5693
- const resetAtMs = bodyReset !== void 0 && bodyReset > Date.now() ? bodyReset : resetFromRetryAfter(result.retryAfter);
5961
+ const headerReset = resetFromRetryAfter(result.retryAfter);
5962
+ const resetAtMs = bodyReset !== void 0 && bodyReset > Date.now() ? headerReset === void 0 ? bodyReset : Math.max(bodyReset, headerReset) : headerReset;
5694
5963
  pool.penalize(account.id, resetAtMs, modelId);
5695
5964
  } else if (result.kind === "model_tier") pool.blockModel(account.id, modelId, Date.now() + MODEL_TIER_HOLD_MS);
5696
5965
  else if (result.kind === "account_restricted") pool.penalize(account.id, holdUntil(), void 0, "restricted");
@@ -5720,75 +5989,6 @@ function createWorkBuddyShim(options) {
5720
5989
  close: server.close
5721
5990
  };
5722
5991
  }
5723
- /**
5724
- * Matched case-insensitively: the host's check is, and a lowercase spelling in a
5725
- * user message tripped it just the same when probed.
5726
- */
5727
- const CLIENT_NAME = /DeepSeek Harness/gi;
5728
- /**
5729
- * Replace the client name in every message's text, leaving everything else be.
5730
- *
5731
- * Only text can carry it: `tool_calls`, `tool_call_id`, tool names and ids are
5732
- * the client's own vocabulary for the call it is making, and rewriting those
5733
- * would break the pairing.
5734
- */
5735
- function renameClientInMessages(messages, replacement) {
5736
- const rename = (text) => text.replace(CLIENT_NAME, replacement);
5737
- const inContent = (content) => {
5738
- if (typeof content === "string") return rename(content);
5739
- if (!Array.isArray(content)) return content;
5740
- return content.map((part) => {
5741
- if (typeof part === "string") return rename(part);
5742
- if (typeof part !== "object" || part === null || Array.isArray(part)) return part;
5743
- const record = part;
5744
- if (typeof record["text"] !== "string") return part;
5745
- return {
5746
- ...record,
5747
- text: rename(record["text"])
5748
- };
5749
- });
5750
- };
5751
- return messages.map((message) => {
5752
- if (typeof message !== "object" || message === null || Array.isArray(message)) return message;
5753
- const record = message;
5754
- if (!("content" in record)) return message;
5755
- const content = inContent(record["content"]);
5756
- return content === record["content"] ? message : {
5757
- ...record,
5758
- content
5759
- };
5760
- });
5761
- }
5762
- /**
5763
- * Wrap `fetch` so chat requests to the domestic host carry the replacement name.
5764
- *
5765
- * The name is read per request, so the panel's switch takes effect on the next
5766
- * turn; a reader that returns nothing leaves the body exactly as the host wrote
5767
- * it. Only the chat endpoint is touched. The billing and check-in calls carry no
5768
- * prompt, and the international host does not check for this.
5769
- */
5770
- function clientNameRewritingFetch(replacement, inner = globalThis.fetch) {
5771
- const rewrite = (url, init) => {
5772
- if (!url.includes("copilot.tencent.com") || typeof init?.body !== "string") return init;
5773
- const name = replacement()?.trim();
5774
- if (name === void 0 || name === "") return init;
5775
- let parsed;
5776
- try {
5777
- parsed = JSON.parse(init.body);
5778
- } catch {
5779
- return init;
5780
- }
5781
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return init;
5782
- const body = parsed;
5783
- if (!Array.isArray(body["messages"])) return init;
5784
- body["messages"] = renameClientInMessages(body["messages"], name);
5785
- return {
5786
- ...init,
5787
- body: JSON.stringify(body)
5788
- };
5789
- };
5790
- return ((input, init) => inner(input, rewrite(String(input), init)));
5791
- }
5792
5992
  //#endregion
5793
5993
  //#region src/promo.ts
5794
5994
  /**
@@ -7174,7 +7374,7 @@ var TraeSoloUpstreamClient = class {
7174
7374
  async fetchModels(signal) {
7175
7375
  const [credential, identity] = await Promise.all([this.options.credential(), this.options.identity()]);
7176
7376
  const region = traeRegionOfCredential(credential);
7177
- const base = this.options.baseUrl ?? REGION_GATEWAYS[region].chat;
7377
+ const base = REGION_GATEWAYS[region].chat;
7178
7378
  const headers = {
7179
7379
  ...buildTraeHeaders(credential, identity),
7180
7380
  Accept: "application/json"
@@ -7309,7 +7509,7 @@ var TraeSoloUpstreamClient = class {
7309
7509
  const [credential, identity] = await Promise.all([this.options.credential(), this.options.identity()]);
7310
7510
  const region = traeRegionOfCredential(credential);
7311
7511
  if (region !== "ai") throw new Error("Trae pay status exists on the international region only");
7312
- const response = await this.fetchImpl(traeEndpoint(this.options.baseUrl ?? REGION_GATEWAYS[region].pay, TRAE_PAY_STATUS_PATH), {
7512
+ const response = await this.fetchImpl(traeEndpoint(REGION_GATEWAYS[region].pay, TRAE_PAY_STATUS_PATH), {
7313
7513
  redirect: "error",
7314
7514
  method: "POST",
7315
7515
  headers: traeCheckinHeaders(credential, identity, region),
@@ -7379,7 +7579,7 @@ var TraeSoloUpstreamClient = class {
7379
7579
  };
7380
7580
  }
7381
7581
  const headers = buildTraeHeaders(credential, identity);
7382
- const base = this.options.baseUrl ?? REGION_GATEWAYS[traeRegionOfCredential(credential)].chat;
7582
+ const base = REGION_GATEWAYS[traeRegionOfCredential(credential)].chat;
7383
7583
  let response;
7384
7584
  const deadline = headersDeadline(signal, timeouts?.headersMs ?? TRAE_HEADERS_TIMEOUT_MS);
7385
7585
  try {
@@ -9739,36 +9939,42 @@ var QoderUpstreamClient = class {
9739
9939
  if (!response.ok) throw new Error(`Qoder usage failed: HTTP ${response.status} ${await readErrorBody(response, 300, signal)}`);
9740
9940
  return await response.json();
9741
9941
  };
9742
- let payload;
9743
- let source = "presentation";
9942
+ /**
9943
+ * Turn one route's document into the panel shape.
9944
+ *
9945
+ * Validation is part of parsing, not a key-presence check before it: a
9946
+ * document carrying only `expiresAt`, or an empty quota object, used to pass
9947
+ * `usable()` and then throw after the fallback had already been skipped.
9948
+ */
9949
+ const parse = (value, source) => {
9950
+ const envelope = value === null || typeof value !== "object" ? {} : value;
9951
+ const usage = envelope["qoderUsage"] ?? envelope["data"] ?? value;
9952
+ if (usage === null || typeof usage !== "object") throw new Error("Qoder usage answered no usable document");
9953
+ const record = usage;
9954
+ const userQuota = qoderQuotaBucket(record["user_quota"] ?? record["userQuota"]);
9955
+ const addOnQuota = qoderQuotaBucket(record["add_on_quota"] ?? record["addOnQuota"]);
9956
+ const rawExpiry = record["expiresAt"] ?? record["expires_at"];
9957
+ const expiresAtMs = qoderEpochMs(rawExpiry);
9958
+ const neverExpires = expiresAtMs === void 0 && rawExpiry !== void 0 && rawExpiry !== null && rawExpiry !== "";
9959
+ const rawPackages = record["dedicated_resource_packages"] ?? record["dedicatedResourcePackages"];
9960
+ const now = Date.now();
9961
+ const dedicatedPackages = Array.isArray(rawPackages) ? rawPackages.map(qoderDedicatedPackage).filter((entry) => entry !== void 0).filter((entry) => entry.expiresAtMs === void 0 || entry.expiresAtMs > now) : [];
9962
+ if (userQuota === void 0 && addOnQuota === void 0 && dedicatedPackages.length === 0) throw new Error("Qoder usage contained no usable quota");
9963
+ return {
9964
+ ...userQuota === void 0 ? {} : { userQuota },
9965
+ ...addOnQuota === void 0 ? {} : { addOnQuota },
9966
+ dedicatedPackages,
9967
+ ...expiresAtMs === void 0 ? {} : { expiresAtMs },
9968
+ ...neverExpires ? { neverExpires: true } : {},
9969
+ source
9970
+ };
9971
+ };
9744
9972
  try {
9745
- payload = await read(QODER_USAGE_PRESENTATION_PATH);
9973
+ return parse(await read(QODER_USAGE_PRESENTATION_PATH), "presentation");
9746
9974
  } catch (error) {
9747
9975
  if (signal?.aborted) throw error;
9748
- source = "quota";
9749
- payload = await read(QODER_USAGE_PATH);
9976
+ return parse(await read(QODER_USAGE_PATH), "quota");
9750
9977
  }
9751
- const envelope = payload === null || typeof payload !== "object" ? {} : payload;
9752
- const usage = envelope["qoderUsage"] ?? envelope["data"] ?? payload;
9753
- if (usage === null || typeof usage !== "object") throw new Error("Qoder usage answered no usable document");
9754
- const record = usage;
9755
- const userQuota = qoderQuotaBucket(record["user_quota"] ?? record["userQuota"]);
9756
- const addOnQuota = qoderQuotaBucket(record["add_on_quota"] ?? record["addOnQuota"]);
9757
- const rawExpiry = record["expiresAt"] ?? record["expires_at"];
9758
- const expiresAtMs = qoderEpochMs(rawExpiry);
9759
- const neverExpires = expiresAtMs === void 0 && rawExpiry !== void 0 && rawExpiry !== null && rawExpiry !== "";
9760
- const rawPackages = record["dedicated_resource_packages"] ?? record["dedicatedResourcePackages"];
9761
- const now = Date.now();
9762
- const dedicatedPackages = Array.isArray(rawPackages) ? rawPackages.map(qoderDedicatedPackage).filter((entry) => entry !== void 0).filter((entry) => entry.expiresAtMs === void 0 || entry.expiresAtMs > now) : [];
9763
- if (userQuota === void 0 && addOnQuota === void 0 && dedicatedPackages.length === 0) throw new Error("Qoder usage contained no usable quota");
9764
- return {
9765
- ...userQuota === void 0 ? {} : { userQuota },
9766
- ...addOnQuota === void 0 ? {} : { addOnQuota },
9767
- dedicatedPackages,
9768
- ...expiresAtMs === void 0 ? {} : { expiresAtMs },
9769
- ...neverExpires ? { neverExpires: true } : {},
9770
- source
9771
- };
9772
9978
  }
9773
9979
  /**
9774
9980
  * Read the raw campaigns payload once. One round trip answers both the
@@ -11185,13 +11391,14 @@ function createSourcePool(host) {
11185
11391
  return healthy.concat(held, rest);
11186
11392
  }
11187
11393
  const live = ordered.filter((credential) => !sourceCredentialExpired(credential, now));
11188
- if (rotate !== true || preferred !== "" || live.length < 2 || host.sourceDistribution(source) !== "round-robin") return ordered;
11394
+ const peek = rotate === "peek";
11395
+ if (rotate !== true && !peek || preferred !== "" || live.length < 2 || host.sourceDistribution(source) !== "round-robin") return ordered;
11189
11396
  const healthy = live.filter((credential) => !sourceFailureActive(source, region, labelOf(credential), now));
11190
11397
  const held = live.filter((credential) => sourceFailureActive(source, region, labelOf(credential), now));
11191
11398
  if (healthy.length < 2) return ordered;
11192
11399
  const key = host.sourceRegionKey(source, region);
11193
11400
  const step = (sourceRotation.get(key) ?? 0) % healthy.length;
11194
- sourceRotation.set(key, step + 1);
11401
+ if (!peek) sourceRotation.set(key, step + 1);
11195
11402
  const rest = ordered.filter((credential) => sourceCredentialExpired(credential, now));
11196
11403
  return healthy.slice(step).concat(healthy.slice(0, step), held, rest);
11197
11404
  }
@@ -11234,8 +11441,8 @@ const SERVICE_ID = "provider-host";
11234
11441
  /** The two gateways, matching the provider ids this plugin registers. */
11235
11442
  const REGIONS = ["cn", "global"];
11236
11443
  const PROVIDER_ID_BY_REGION = {
11237
- cn: "xdpool-cn",
11238
- global: "xdpool-global"
11444
+ cn: "wtqpool-cn",
11445
+ global: "wtqpool-global"
11239
11446
  };
11240
11447
  const PROVIDER_NAME_BY_REGION = {
11241
11448
  cn: "WTQ Pool (CN)",
@@ -11296,8 +11503,8 @@ const REGION_PORTS = {
11296
11503
  */
11297
11504
  const TRAE_REGIONS = ["cn", "ai"];
11298
11505
  const TRAE_PROVIDER_ID_BY_REGION = {
11299
- cn: "xdpool-trae-cn",
11300
- ai: "xdpool-trae-ai"
11506
+ cn: "wtqpool-trae-cn",
11507
+ ai: "wtqpool-trae-ai"
11301
11508
  };
11302
11509
  const TRAE_PROVIDER_NAME_BY_REGION = {
11303
11510
  cn: "WTQ Pool Trae (CN)",
@@ -11322,8 +11529,8 @@ function activeTraeRegions() {
11322
11529
  */
11323
11530
  const QODER_REGIONS = ["cn", "global"];
11324
11531
  const QODER_PROVIDER_ID_BY_REGION = {
11325
- cn: "xdpool-qoder-cn",
11326
- global: "xdpool-qoder-global"
11532
+ cn: "wtqpool-qoder-cn",
11533
+ global: "wtqpool-qoder-global"
11327
11534
  };
11328
11535
  const QODER_PROVIDER_NAME_BY_REGION = {
11329
11536
  cn: "WTQ Pool Qoder (CN)",
@@ -11478,6 +11685,14 @@ let settings = {};
11478
11685
  * a switch the user just flipped.
11479
11686
  */
11480
11687
  let settingsRevision = 0;
11688
+ /**
11689
+ * Bumped only by writes this process made, never by a document the host pushed.
11690
+ *
11691
+ * A host announcement that was already in flight when a local save landed is
11692
+ * older than that save. `onHostSettingsChanged` captures this counter before it
11693
+ * queues, and drops the document when a local write overtook it.
11694
+ */
11695
+ let localSettingsRevision = 0;
11481
11696
  let dataPath = "";
11482
11697
  /** One runtime per gateway: its shim and catalog. */
11483
11698
  const runtimes = /* @__PURE__ */ new Map();
@@ -11523,6 +11738,8 @@ const gatewayStartFailures = /* @__PURE__ */ new Map();
11523
11738
  * failed one.
11524
11739
  */
11525
11740
  const sourceStartFailures = /* @__PURE__ */ new Map();
11741
+ /** One in-flight source-gateway start per region, shared by overlapping passes. */
11742
+ const sourceGatewayStarts = /* @__PURE__ */ new Map();
11526
11743
  /** Provider ids the host has confirmed it is serving, this process's lifetime. */
11527
11744
  let publishedIds = /* @__PURE__ */ new Set();
11528
11745
  /**
@@ -11767,6 +11984,7 @@ async function saveSettings(patch) {
11767
11984
  ...patch
11768
11985
  };
11769
11986
  settingsRevision += 1;
11987
+ localSettingsRevision += 1;
11770
11988
  return true;
11771
11989
  } catch (error) {
11772
11990
  log("warn", "could not save settings: " + safeMessage(error));
@@ -11815,6 +12033,7 @@ async function mutateSettings(key, mutate) {
11815
12033
  [key]: next
11816
12034
  };
11817
12035
  settingsRevision += 1;
12036
+ localSettingsRevision += 1;
11818
12037
  return true;
11819
12038
  } catch (error) {
11820
12039
  log("warn", "could not save settings: " + safeMessage(error));
@@ -11846,15 +12065,34 @@ function resetDiscoveryCaches() {
11846
12065
  * reach the picker or the user still sees the models they just disabled.
11847
12066
  */
11848
12067
  async function onHostSettingsChanged(next) {
11849
- if (serviceStopped) return;
11850
12068
  if (next === null || typeof next !== "object" || Array.isArray(next)) return false;
11851
- const toggled = Object.values(SOURCE_SETTING_KEYS).some((key) => Object.hasOwn(next, key) && settings[key] !== next[key]);
11852
- settings = {
11853
- ...settings,
11854
- ...next
11855
- };
11856
- settingsRevision += 1;
11857
- if (toggled) resetDiscoveryCaches();
12069
+ const localRevision = localSettingsRevision;
12070
+ return enqueueWrite(async () => {
12071
+ if (serviceStopped) return false;
12072
+ const before = settings;
12073
+ if (localSettingsRevision !== localRevision) {
12074
+ if (!await adoptHostSettings()) {
12075
+ scheduleRefresh("settings");
12076
+ return false;
12077
+ }
12078
+ } else {
12079
+ settings = next;
12080
+ settingsRevision += 1;
12081
+ }
12082
+ const toggled = Object.values(SOURCE_SETTING_KEYS).some((key) => Object.hasOwn(settings, key) && before[key] !== settings[key]);
12083
+ if (toggled) resetDiscoveryCaches();
12084
+ await applySettingsEverywhere(toggled);
12085
+ return true;
12086
+ });
12087
+ }
12088
+ /**
12089
+ * Apply the settings document already in `settings` to everything downstream.
12090
+ *
12091
+ * Shared by the host-driven change above and the panel's own switches, which
12092
+ * write the key first and then ask for the same reconciliation with no new
12093
+ * document to merge.
12094
+ */
12095
+ async function applySettingsEverywhere(toggled) {
11858
12096
  applySettingsToCore();
11859
12097
  traeAccountRows = traeAccountRows.filter((row) => regionEnabled("trae", row.region));
11860
12098
  qoderAccountRows = qoderAccountRows.filter((row) => regionEnabled("qoder", row.region));
@@ -11929,6 +12167,10 @@ function autoCheckinEnabled() {
11929
12167
  * restart after the morning hour forgot every slot and re-ran the whole pass.
11930
12168
  * The file holds one array per campaign day, the same shape the desktop twin
11931
12169
  * writes, so the two engines cannot disagree about what a day's record is.
12170
+ * `_qoderRetryAt` is metadata beside those arrays: Qoder's deferred round can
12171
+ * open hours after the pass that scheduled it, and a reload before then used to
12172
+ * lose the day's Qoder credits. A key that is not an array is ignored by the
12173
+ * day reader, so the file stays compatible with the twin.
11932
12174
  */
11933
12175
  const CHECKIN_SLOTS_FILE = "checkin-slots.json";
11934
12176
  /**
@@ -11942,6 +12184,7 @@ const CHECKIN_SLOTS_FILE = "checkin-slots.json";
11942
12184
  */
11943
12185
  function loadCheckinSlots() {
11944
12186
  autoCheckinSlots.clear();
12187
+ qoderRetryAt = 0;
11945
12188
  if (dataPath === "") return;
11946
12189
  try {
11947
12190
  const parsed = JSON.parse(fs$1.readFileSync(path.join(dataPath, CHECKIN_SLOTS_FILE), "utf8"));
@@ -11950,6 +12193,9 @@ function loadCheckinSlots() {
11950
12193
  if (!Array.isArray(slots)) continue;
11951
12194
  for (const slot of slots) if (typeof slot === "string" && slot !== "") autoCheckinSlots.add(slot);
11952
12195
  }
12196
+ const retry = parsed._qoderRetryAt;
12197
+ const now = Date.now();
12198
+ if (typeof retry === "number" && Number.isFinite(retry) && retry > 0 && (zonedDayHour(new Date(retry)).day === zonedDayHour(new Date(now)).day || retry > now - 72e5 && retry <= now + 864e5)) qoderRetryAt = retry;
11953
12199
  } catch {}
11954
12200
  }
11955
12201
  /**
@@ -11970,6 +12216,7 @@ function saveCheckinSlots() {
11970
12216
  }
11971
12217
  const keep = Object.keys(byDay).sort().slice(-3);
11972
12218
  for (const day of Object.keys(byDay)) if (!keep.includes(day)) delete byDay[day];
12219
+ if (qoderRetryAt > 0) byDay._qoderRetryAt = qoderRetryAt;
11973
12220
  const target = path.join(dataPath, CHECKIN_SLOTS_FILE);
11974
12221
  const staging = target + ".tmp";
11975
12222
  try {
@@ -12586,15 +12833,18 @@ function warmingGatewayIds() {
12586
12833
  if (gatewayStartFailures.has(region)) continue;
12587
12834
  if (runtime === void 0 || runtime.connecting !== null) ids.add(PROVIDER_ID_BY_REGION[region]);
12588
12835
  }
12589
- for (const [gateways, regions, idByRegion] of [[
12836
+ for (const [source, gateways, regions, idByRegion] of [[
12837
+ "trae",
12590
12838
  traeGateways,
12591
12839
  activeTraeRegions(),
12592
12840
  TRAE_PROVIDER_ID_BY_REGION
12593
12841
  ], [
12842
+ "qoder",
12594
12843
  qoderGateways,
12595
12844
  activeQoderRegions(),
12596
12845
  QODER_PROVIDER_ID_BY_REGION
12597
12846
  ]]) for (const region of regions) {
12847
+ if (sourceStartFailures.has(source + ":" + region)) continue;
12598
12848
  const entry = gateways.get(region);
12599
12849
  if (entry === void 0 || entry.gateway.models().length === 0 && entry.lastError === "") ids.add(idByRegion[region]);
12600
12850
  }
@@ -12620,6 +12870,7 @@ async function warmSourceDirectory(entry, signal) {
12620
12870
  entry.lastError = entry.gateway.models().length > 0 ? "" : "directory unavailable: " + safeMessage(error);
12621
12871
  if (entry.lastError !== "") log("warn", "[" + entry.source + ":" + entry.region + "] " + entry.lastError);
12622
12872
  }
12873
+ entry.warmSettled = true;
12623
12874
  if (entry.lastError === "" && entry.gateway.models().length > 0) syncDeclaration();
12624
12875
  return entry.lastError === "";
12625
12876
  }
@@ -12721,7 +12972,8 @@ async function createTraeRuntime(region) {
12721
12972
  portFallback: bound !== preferred,
12722
12973
  preferredPort: preferred,
12723
12974
  lastError: "",
12724
- source: "trae"
12975
+ source: "trae",
12976
+ warmSettled: false
12725
12977
  };
12726
12978
  if (entry.portFallback) log("warn", "[trae:" + region + "] preferred port " + preferred + " is held by another process; serving this session on port " + gateway.port());
12727
12979
  warmSourceDirectoryAtStartup(entry, warmAbort.signal).catch((error) => log("warn", "[trae:" + region + "] directory warm-up failed: " + safeMessage(error)));
@@ -12733,6 +12985,7 @@ async function reconcileTraeGateways() {
12733
12985
  if (!stillLoaded(generation) || serviceStopped) return;
12734
12986
  const active = activeTraeRegions();
12735
12987
  for (const [region, entry] of Array.from(traeGateways)) {
12988
+ if (!stillLoaded(generation) || serviceStopped) return;
12736
12989
  if (active.includes(region)) continue;
12737
12990
  traeGateways.delete(region);
12738
12991
  sourceStartFailures.delete("trae:" + region);
@@ -12743,17 +12996,30 @@ async function reconcileTraeGateways() {
12743
12996
  }
12744
12997
  }
12745
12998
  for (const region of active) {
12999
+ if (!stillLoaded(generation) || serviceStopped) return;
12746
13000
  if (traeGateways.has(region)) continue;
13001
+ const key = "trae:" + region;
13002
+ const pending = sourceGatewayStarts.get(key);
13003
+ if (pending !== void 0) {
13004
+ await pending.catch(() => {});
13005
+ continue;
13006
+ }
13007
+ const starting = createTraeRuntime(region);
13008
+ sourceGatewayStarts.set(key, starting);
12747
13009
  try {
12748
- const entry = await createTraeRuntime(region);
13010
+ const entry = await starting;
12749
13011
  if (!stillLoaded(generation) || !activeTraeRegions().includes(region) || traeGateways.has(region)) await entry.gateway.close();
12750
13012
  else {
12751
13013
  traeGateways.set(region, entry);
12752
- sourceStartFailures.delete("trae:" + region);
13014
+ sourceStartFailures.delete(key);
12753
13015
  }
12754
13016
  } catch (error) {
12755
- sourceStartFailures.set("trae:" + region, safeMessage(error));
12756
- log("warn", "[trae:" + region + "] gateway could not start: " + safeMessage(error));
13017
+ if (stillLoaded(generation)) {
13018
+ sourceStartFailures.set(key, safeMessage(error));
13019
+ log("warn", "[trae:" + region + "] gateway could not start: " + safeMessage(error));
13020
+ }
13021
+ } finally {
13022
+ if (sourceGatewayStarts.get(key) === starting) sourceGatewayStarts.delete(key);
12757
13023
  }
12758
13024
  }
12759
13025
  }
@@ -12862,7 +13128,8 @@ async function createQoderRuntime(region) {
12862
13128
  portFallback: bound !== preferred,
12863
13129
  preferredPort: preferred,
12864
13130
  lastError: "",
12865
- source: "qoder"
13131
+ source: "qoder",
13132
+ warmSettled: false
12866
13133
  };
12867
13134
  if (entry.portFallback) log("warn", "[qoder:" + region + "] preferred port " + preferred + " is held by another process; serving this session on port " + gateway.port());
12868
13135
  warmSourceDirectoryAtStartup(entry, warmAbort.signal).catch((error) => log("warn", "[qoder:" + region + "] directory warm-up failed: " + safeMessage(error)));
@@ -12874,6 +13141,7 @@ async function reconcileQoderGateways() {
12874
13141
  if (!stillLoaded(generation) || serviceStopped) return;
12875
13142
  const active = activeQoderRegions();
12876
13143
  for (const [region, entry] of Array.from(qoderGateways)) {
13144
+ if (!stillLoaded(generation) || serviceStopped) return;
12877
13145
  if (active.includes(region)) continue;
12878
13146
  qoderGateways.delete(region);
12879
13147
  sourceStartFailures.delete("qoder:" + region);
@@ -12884,17 +13152,30 @@ async function reconcileQoderGateways() {
12884
13152
  }
12885
13153
  }
12886
13154
  for (const region of active) {
13155
+ if (!stillLoaded(generation) || serviceStopped) return;
12887
13156
  if (qoderGateways.has(region)) continue;
13157
+ const key = "qoder:" + region;
13158
+ const pending = sourceGatewayStarts.get(key);
13159
+ if (pending !== void 0) {
13160
+ await pending.catch(() => {});
13161
+ continue;
13162
+ }
13163
+ const starting = createQoderRuntime(region);
13164
+ sourceGatewayStarts.set(key, starting);
12888
13165
  try {
12889
- const entry = await createQoderRuntime(region);
13166
+ const entry = await starting;
12890
13167
  if (!stillLoaded(generation) || !activeQoderRegions().includes(region) || qoderGateways.has(region)) await entry.gateway.close();
12891
13168
  else {
12892
13169
  qoderGateways.set(region, entry);
12893
- sourceStartFailures.delete("qoder:" + region);
13170
+ sourceStartFailures.delete(key);
12894
13171
  }
12895
13172
  } catch (error) {
12896
- sourceStartFailures.set("qoder:" + region, safeMessage(error));
12897
- log("warn", "[qoder:" + region + "] gateway could not start: " + safeMessage(error));
13173
+ if (stillLoaded(generation)) {
13174
+ sourceStartFailures.set(key, safeMessage(error));
13175
+ log("warn", "[qoder:" + region + "] gateway could not start: " + safeMessage(error));
13176
+ }
13177
+ } finally {
13178
+ if (sourceGatewayStarts.get(key) === starting) sourceGatewayStarts.delete(key);
12898
13179
  }
12899
13180
  }
12900
13181
  }
@@ -13038,8 +13319,9 @@ function startRuntimeOnce(region) {
13038
13319
  * is every later pass's only re-entry test, so a stopped entry there would take
13039
13320
  * the region out until the next teardown.
13040
13321
  *
13041
- * This host's `onLoad` clears both maps, so it never shares a bind across a reload;
13042
- * PI-Desktop's keeps its gateways and relies on this same ordering for that case.
13322
+ * This host's `onLoad` clears both maps, so it never shares a bind across a
13323
+ * reload; PI-Desktop clears them too and relies on this same ordering within one
13324
+ * activation.
13043
13325
  */
13044
13326
  async function settleStartedRuntime(region, runtime, unwanted) {
13045
13327
  const held = runtimes.get(region);
@@ -13072,8 +13354,10 @@ async function startRuntimes() {
13072
13354
  try {
13073
13355
  await settleStartedRuntime(region, await startRuntimeOnce(region), !stillLoaded(generation) || !activeRegions().includes(region));
13074
13356
  } catch (error) {
13075
- gatewayStartFailures.set(region, safeMessage(error));
13076
- log("warn", "[workbuddy:" + region + "] gateway could not start: " + safeMessage(error));
13357
+ if (stillLoaded(generation)) {
13358
+ gatewayStartFailures.set(region, safeMessage(error));
13359
+ log("warn", "[workbuddy:" + region + "] gateway could not start: " + safeMessage(error));
13360
+ }
13077
13361
  }
13078
13362
  }));
13079
13363
  }
@@ -13197,6 +13481,7 @@ function probesStale() {
13197
13481
  if (account.cooldownUntilMs > now || core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
13198
13482
  const cached = probeCache.get(account.id);
13199
13483
  if (cached === void 0 || now - cached.atMs >= PROBE_TTL_MS) return true;
13484
+ if (cached.checkinOnly === true) return true;
13200
13485
  }
13201
13486
  return false;
13202
13487
  }
@@ -13676,7 +13961,9 @@ function applyProbe(row, probe) {
13676
13961
  async function accountProbe(account, allowNetwork, checkinOnly = false) {
13677
13962
  const cached = probeCache.get(account.id);
13678
13963
  if (allowNetwork !== true) return cached === void 0 ? { pending: true } : cached.value;
13679
- if (cached !== void 0 && Date.now() - cached.atMs < PROBE_TTL_MS) return cached.value;
13964
+ const cachedFresh = cached !== void 0 && Date.now() - cached.atMs < PROBE_TTL_MS;
13965
+ const cachedHasCredits = cached !== void 0 && (cached.value.credits !== void 0 || cached.value.creditsError !== void 0);
13966
+ if (cachedFresh && (checkinOnly || cached.checkinOnly !== true && cachedHasCredits)) return cached.value;
13680
13967
  if (signInRefused(account)) return {};
13681
13968
  const value = {};
13682
13969
  if (!checkinOnly) {
@@ -13700,6 +13987,7 @@ async function accountProbe(account, allowNetwork, checkinOnly = false) {
13700
13987
  }
13701
13988
  if (value.credits !== void 0 && typeof value.credits.total === "number") core.pool.setCreditBalance(account.id, value.credits.total, value.credits.nearestExpiryMs);
13702
13989
  }
13990
+ const checkinStartedAt = Date.now();
13703
13991
  try {
13704
13992
  const checkin = await core.pool.readAfterRefresh(account.id, (credential) => core.client.fetchCheckinStatus(credential));
13705
13993
  value.checkin = {
@@ -13715,15 +14003,54 @@ async function accountProbe(account, allowNetwork, checkinOnly = false) {
13715
14003
  } catch (error) {
13716
14004
  value.checkinError = safeMessage(error);
13717
14005
  }
14006
+ const latest = probeCache.get(account.id);
14007
+ if (latest !== cached) {
14008
+ if (latest === void 0) return { pending: true };
14009
+ if (!checkinOnly && latest.checkinOnly === true && (value.credits !== void 0 || value.creditsError !== void 0)) {
14010
+ const merged = { ...latest.value };
14011
+ if (value.credits !== void 0) {
14012
+ merged.credits = value.credits;
14013
+ delete merged.creditsError;
14014
+ }
14015
+ if (value.creditsError !== void 0) {
14016
+ merged.creditsError = value.creditsError;
14017
+ delete merged.credits;
14018
+ }
14019
+ if (latest.atMs <= checkinStartedAt) {
14020
+ if (value.checkin !== void 0) {
14021
+ merged.checkin = value.checkin;
14022
+ delete merged.checkinError;
14023
+ }
14024
+ if (value.checkinError !== void 0) {
14025
+ merged.checkinError = value.checkinError;
14026
+ delete merged.checkin;
14027
+ }
14028
+ }
14029
+ probeCache.set(account.id, {
14030
+ atMs: Date.now(),
14031
+ value: merged,
14032
+ checkinOnly: false
14033
+ });
14034
+ return merged;
14035
+ }
14036
+ return latest.value;
14037
+ }
14038
+ const stored = checkinOnly && cached !== void 0 ? {
14039
+ ...cached.value,
14040
+ ...value
14041
+ } : value;
14042
+ if (value.checkin !== void 0) delete stored.checkinError;
14043
+ if (value.checkinError !== void 0) delete stored.checkin;
13718
14044
  probeCache.set(account.id, {
13719
14045
  atMs: Date.now(),
13720
- value
14046
+ value: stored,
14047
+ checkinOnly
13721
14048
  });
13722
14049
  if (probeCache.size > core.pool.list().length) {
13723
14050
  const live = new Set(core.pool.list().map((item) => item.id));
13724
14051
  for (const id of Array.from(probeCache.keys())) if (!live.has(id)) probeCache.delete(id);
13725
14052
  }
13726
- return value;
14053
+ return stored;
13727
14054
  }
13728
14055
  /**
13729
14056
  * Per-gateway roster warnings, for gateways that have one right now.
@@ -13892,7 +14219,6 @@ async function statusDocument(options) {
13892
14219
  modelCap: MAX_MODELS,
13893
14220
  distribution: distributionSetting(),
13894
14221
  showComposerPoints: settings.showComposerPoints === true,
13895
- replacedClientName: replacedClientName() ?? null,
13896
14222
  autoCheckin: {
13897
14223
  enabled: autoCheckinEnabled(),
13898
14224
  hours: checkinHours(),
@@ -13982,9 +14308,10 @@ function samePublishedAddress(a, b) {
13982
14308
  /**
13983
14309
  * True when the address that was published is not the address this run bound.
13984
14310
  *
13985
- * A run that fell back to an ephemeral port counts as drift: the declaration
13986
- * names the port this run bound, and until the plugin is reloaded nothing
13987
- * answers on the address the host registered before the fallback.
14311
+ * The declaration is republished after a port fallback, so the published address
14312
+ * is the test: a row that follows the actual port is healthy, while one that
14313
+ * still names the preferred port is drift. Checking `portFallback` itself marked
14314
+ * a correctly republished row as broken.
13988
14315
  *
13989
14316
  * A gateway whose start failed counts as drift too, and for the same reason: it
13990
14317
  * has no shim at all, so the address the host registered is refused. Skipping
@@ -13996,7 +14323,6 @@ function samePublishedAddress(a, b) {
13996
14323
  */
13997
14324
  function addressDrift() {
13998
14325
  for (const region of activeRegions()) {
13999
- if (runtimes.get(region)?.portFallback === true) return true;
14000
14326
  const published = declaredBaseUrl(region);
14001
14327
  const bound = shimInfo(region).baseUrl;
14002
14328
  if (bound === void 0) {
@@ -14006,12 +14332,10 @@ function addressDrift() {
14006
14332
  if (published !== void 0 && published !== bound) return true;
14007
14333
  }
14008
14334
  for (const entry of Array.from(traeGateways.values())) {
14009
- if (entry.portFallback === true) return true;
14010
14335
  const published = declaredSourceBaseUrl(entry, TRAE_PROVIDER_ID_BY_REGION);
14011
14336
  if (published !== void 0 && !samePublishedAddress(published, entry.baseUrl)) return true;
14012
14337
  }
14013
14338
  for (const entry of Array.from(qoderGateways.values())) {
14014
- if (entry.portFallback === true) return true;
14015
14339
  const published = declaredSourceBaseUrl(entry, QODER_PROVIDER_ID_BY_REGION);
14016
14340
  if (published !== void 0 && !samePublishedAddress(published, entry.baseUrl)) return true;
14017
14341
  }
@@ -14050,10 +14374,19 @@ async function traeDoctorDetail() {
14050
14374
  }
14051
14375
  const parts = Object.entries(byRegion).map(([region, count]) => `${region} x${count}`).join(", ");
14052
14376
  const failures = found.failures.length > 0 ? `; ${found.failures.length} unreadable file(s)` : "";
14053
- const served = activeTraeRegions().map((region) => `${region}: ${traeDeclarationModels(region).length} model(s)`).join(", ");
14377
+ const servedRegions = activeTraeRegions();
14378
+ const served = servedRegions.map((region) => `${region}: ${traeDeclarationModels(region).length} model(s)`).join(", ");
14379
+ const stillReading = [];
14380
+ const problems = [];
14381
+ for (const region of servedRegions) {
14382
+ const entry = traeGateways.get(region);
14383
+ if (entry === void 0 && !byRegion[region]) problems.push(`${region}: no sign-in for this region`);
14384
+ else if (entry === void 0 || entry.warmSettled !== true) stillReading.push(region);
14385
+ else if (traeDeclarationModels(region).length === 0) problems.push(entry.lastError !== "" ? `${region}: ${entry.lastError}` : `${region}: no models selected`);
14386
+ }
14054
14387
  return {
14055
- ok: true,
14056
- detail: `on; ${found.credentials.length} account(s) (${parts})${failures}; serving ${served}`
14388
+ ok: problems.length === 0,
14389
+ detail: `on; ${found.credentials.length} account(s) (${parts})${failures}; serving ${served}` + (stillReading.length > 0 ? `; still reading models for ${stillReading.join(", ")}` : "") + (problems.length > 0 ? `; ${problems.join("; ")}` : "")
14057
14390
  };
14058
14391
  } catch (error) {
14059
14392
  return {
@@ -14078,10 +14411,19 @@ async function qoderDoctorDetail() {
14078
14411
  for (const credential of found.credentials) byRegion[credential.region] = (byRegion[credential.region] || 0) + 1;
14079
14412
  const parts = Object.entries(byRegion).map(([region, count]) => `${region} x${count}`).join(", ");
14080
14413
  const failures = found.failures.length > 0 ? `; ${found.failures.length} unreadable app dir(s)` : "";
14081
- const served = activeQoderRegions().map((region) => `${region}: ${qoderDeclarationModels(region).length} model(s)`).join(", ");
14414
+ const servedRegions = activeQoderRegions();
14415
+ const served = servedRegions.map((region) => `${region}: ${qoderDeclarationModels(region).length} model(s)`).join(", ");
14416
+ const stillReading = [];
14417
+ const problems = [];
14418
+ for (const region of servedRegions) {
14419
+ const entry = qoderGateways.get(region);
14420
+ if (entry === void 0 && !byRegion[region]) problems.push(`${region}: no sign-in for this region`);
14421
+ else if (entry === void 0 || entry.warmSettled !== true) stillReading.push(region);
14422
+ else if (qoderDeclarationModels(region).length === 0) problems.push(entry.lastError !== "" ? `${region}: ${entry.lastError}` : `${region}: no models selected`);
14423
+ }
14082
14424
  return {
14083
- ok: true,
14084
- detail: `on; ${found.credentials.length} account(s) (${parts})${failures}; serving ${served}`
14425
+ ok: problems.length === 0,
14426
+ detail: `on; ${found.credentials.length} account(s) (${parts})${failures}; serving ${served}` + (stillReading.length > 0 ? `; still reading models for ${stillReading.join(", ")}` : "") + (problems.length > 0 ? `; ${problems.join("; ")}` : "")
14085
14427
  };
14086
14428
  } catch (error) {
14087
14429
  return {
@@ -14134,36 +14476,56 @@ async function doctorReport() {
14134
14476
  push(label + ": models", regionModels.length > 0, regionModels.length + " model(s) in the catalog");
14135
14477
  push(label + ": declared", declared, declared ? "registered with the running host" : runtime?.lastError || runtime?.lastWarning || "this gateway is not published yet");
14136
14478
  }
14137
- for (const [gateways, idByRegion, nameByRegion, ports] of [
14479
+ for (const [gateways, idByRegion, nameByRegion, ports, modelsOf] of [
14138
14480
  [
14139
14481
  runtimes,
14140
14482
  PROVIDER_ID_BY_REGION,
14141
14483
  PROVIDER_NAME_BY_REGION,
14142
- REGION_PORTS
14484
+ REGION_PORTS,
14485
+ declarationModels
14143
14486
  ],
14144
14487
  [
14145
14488
  traeGateways,
14146
14489
  TRAE_PROVIDER_ID_BY_REGION,
14147
14490
  TRAE_PROVIDER_NAME_BY_REGION,
14148
- TRAE_PORTS
14491
+ TRAE_PORTS,
14492
+ traeDeclarationModels
14149
14493
  ],
14150
14494
  [
14151
14495
  qoderGateways,
14152
14496
  QODER_PROVIDER_ID_BY_REGION,
14153
14497
  QODER_PROVIDER_NAME_BY_REGION,
14154
- QODER_PORTS
14498
+ QODER_PORTS,
14499
+ qoderDeclarationModels
14155
14500
  ]
14156
14501
  ]) for (const entry of Array.from(gateways.values())) {
14157
14502
  const published = declaredSourceBaseUrl(entry, idByRegion);
14158
14503
  const bound = entry.baseUrl;
14159
14504
  const label = nameByRegion[entry.region];
14160
- if (published === void 0 || bound === void 0) continue;
14505
+ if (bound === void 0) continue;
14506
+ if (published === void 0) {
14507
+ if (entry.warmSettled !== void 0 ? entry.warmSettled !== true : warmingGatewayIds().has(idByRegion[entry.region])) {
14508
+ push(label + ": published address", true, "still reading its model roster");
14509
+ continue;
14510
+ }
14511
+ if (entry.lastError) {
14512
+ push(label + ": published address", false, entry.lastError);
14513
+ continue;
14514
+ }
14515
+ if (modelsOf(entry.region).length === 0) {
14516
+ push(label + ": published address", true, "no callable models selected; nothing to publish");
14517
+ continue;
14518
+ }
14519
+ push(label + ": published address", false, "this gateway is running but its provider row is not published in this run's declaration - restart the plugin");
14520
+ continue;
14521
+ }
14161
14522
  const fallback = entry.portFallback === true;
14162
- if (samePublishedAddress(published, bound) && !fallback) {
14163
- push(label + ": published address", true, "matches the endpoint this gateway bound (" + bound + ")");
14523
+ if (samePublishedAddress(published, bound)) {
14524
+ const detail = fallback ? "matches the endpoint this gateway bound (" + bound + "); preferred port " + ports[entry.region] + " is held, so this session serves the fallback" : "matches the endpoint this gateway bound (" + bound + ")";
14525
+ push(label + ": published address", true, detail);
14164
14526
  continue;
14165
14527
  }
14166
- const detail = fallback ? "port " + ports[entry.region] + " is held by another process, so this session serves " + bound + " - free that port (usually a leftover plugin process), then reload the plugin" : "the published address is " + published + " but this gateway is on " + bound + " - reload the plugin so the host picks the new address up";
14528
+ const detail = "the published address is " + published + " but this gateway is on " + bound + " - reload the plugin so the host picks the new address up";
14167
14529
  push(label + ": published address", false, detail);
14168
14530
  }
14169
14531
  for (const [source, nameByRegion, regions] of [[
@@ -14289,6 +14651,41 @@ function parseSelection(body) {
14289
14651
  return out;
14290
14652
  }
14291
14653
  /**
14654
+ * The model ids one save's page could display, or undefined for an older panel.
14655
+ *
14656
+ * Only used to tell "the page did not show this id" from "the user removed it",
14657
+ * so junk entries are skipped rather than failing the save.
14658
+ */
14659
+ function parseKnownModelIds(value) {
14660
+ if (!Array.isArray(value)) return void 0;
14661
+ const ids = /* @__PURE__ */ new Set();
14662
+ for (const entry of value) if (typeof entry === "string" && entry !== "" && entry.length <= MAX_MODEL_ID_LENGTH) ids.add(entry);
14663
+ return ids;
14664
+ }
14665
+ /**
14666
+ * Keep the stored selection of models the saving page could not display.
14667
+ *
14668
+ * A roster read can be partial: the static fallback stands until the live list
14669
+ * arrives, and a source directory can answer with fewer rows than it will carry
14670
+ * later. Saving such a page used to replace the whole selection, so every model
14671
+ * outside the snapshot lost its tick and its per-model edits. Ids the page did
14672
+ * show are authoritative - an absent override there means the user cleared it -
14673
+ * while ids it never showed keep what was stored.
14674
+ */
14675
+ function mergeSelectionForPartialRoster(selection, prior, known) {
14676
+ if (known === void 0) return selection;
14677
+ const carriedEnabled = (Array.isArray(prior.enabledModelIds) ? prior.enabledModelIds : []).filter((id) => !known.has(id));
14678
+ const priorOverrides = prior.overrides !== null && typeof prior.overrides === "object" ? prior.overrides : {};
14679
+ const overrides = Object.create(null);
14680
+ for (const [id, entry] of Object.entries(priorOverrides)) if (!known.has(id)) overrides[id] = { ...entry };
14681
+ const merged = { ...selection };
14682
+ if (Array.isArray(selection.enabledModelIds)) merged.enabledModelIds = [.../* @__PURE__ */ new Set([...selection.enabledModelIds, ...carriedEnabled])].slice(0, MAX_STORED_MODEL_IDS);
14683
+ if (selection.overrides !== void 0) for (const [id, entry] of Object.entries(selection.overrides)) overrides[id] = entry;
14684
+ if (Object.keys(overrides).length > 0) merged.overrides = overrides;
14685
+ else delete merged.overrides;
14686
+ return merged;
14687
+ }
14688
+ /**
14292
14689
  * Validate one model's override.
14293
14690
  *
14294
14691
  * Every field is optional, and a value that is present must be usable: the host
@@ -14351,9 +14748,11 @@ async function onPanelInvoke(channel, payload) {
14351
14748
  refreshing: false,
14352
14749
  stale: true
14353
14750
  };
14751
+ const stillNeeded = refreshNeeded();
14752
+ if (stillNeeded) scheduleRefresh("panel");
14354
14753
  return {
14355
14754
  ...refreshed,
14356
- refreshing: false
14755
+ refreshing: stillNeeded
14357
14756
  };
14358
14757
  }
14359
14758
  const document = await statusDocument({ allowNetwork: false });
@@ -14401,12 +14800,21 @@ async function onPanelInvoke(channel, payload) {
14401
14800
  if (activeRegions().length > 0) await settle(core.pool.scan());
14402
14801
  await settle(startRuntimes());
14403
14802
  await settle(refreshSourceAccounts());
14803
+ await settle(reconcileTraeGateways());
14804
+ await settle(reconcileQoderGateways());
14805
+ await settle(Promise.all([...Array.from(traeGateways.values()), ...Array.from(qoderGateways.values())].filter((entry) => entry.lastError !== "" || entry.gateway.models().length === 0).map((entry) => warmSourceDirectory(entry))));
14404
14806
  await settle(Promise.all(Array.from(runtimes.values()).map((runtime) => refreshRuntime(runtime, "rescan", true))));
14405
14807
  syncDeclaration();
14406
- return await statusDocument({
14808
+ const document = await statusDocument({
14407
14809
  allowNetwork: true,
14408
14810
  budgetMs: left()
14409
14811
  });
14812
+ const refreshing = refreshNeeded();
14813
+ if (refreshing) scheduleRefresh("panel");
14814
+ return {
14815
+ ...document,
14816
+ refreshing
14817
+ };
14410
14818
  }
14411
14819
  case "xd.resetCooldowns":
14412
14820
  core.pool.resetCooldowns();
@@ -14448,9 +14856,9 @@ async function onPanelInvoke(channel, payload) {
14448
14856
  result: claim
14449
14857
  };
14450
14858
  };
14451
- const answered = await settleWithin(work(), PANEL_STEP_BUDGET_MS).finally(() => {
14859
+ const answered = await settleWithin(work().finally(() => {
14452
14860
  if (token === checkinPassToken) checkinPassRunning = false;
14453
- });
14861
+ }), PANEL_STEP_BUDGET_MS);
14454
14862
  if (answered === void 0) throw panelError("the check-in did not finish in time; try again", "TIMEOUT");
14455
14863
  return answered;
14456
14864
  }
@@ -14467,9 +14875,10 @@ async function onPanelInvoke(channel, payload) {
14467
14875
  if (!/^(cn|global|trae:cn|trae:ai|qoder:cn|qoder:global)$/.test(requested)) throw panelError("unknown gateway", "INVALID");
14468
14876
  const selection = parseSelection(payload?.selection);
14469
14877
  if (selection === void 0) throw panelError("invalid selection payload", "INVALID");
14878
+ const known = parseKnownModelIds(payload?.knownModelIds);
14470
14879
  if (await mutateSettings("modelSelection", (current) => {
14471
14880
  const all = { ...current && typeof current === "object" && !Array.isArray(current) ? current : {} };
14472
- all[requested] = selection;
14881
+ all[requested] = mergeSelectionForPartialRoster(selection, normalizeSelection(all[requested]), known);
14473
14882
  return all;
14474
14883
  }) !== true) throw panelError("the selection could not be written to the plugin settings file", "SAVE_FAILED");
14475
14884
  if (requested === "cn" || requested === "global") applyEffectiveSelection(requested);
@@ -14652,9 +15061,9 @@ async function onPanelInvoke(channel, payload) {
14652
15061
  }),
14653
15062
  result: outcome
14654
15063
  };
14655
- })(), PANEL_STEP_BUDGET_MS).finally(() => {
15064
+ })().finally(() => {
14656
15065
  if (token === checkinPassToken) checkinPassRunning = false;
14657
- });
15066
+ }), PANEL_STEP_BUDGET_MS);
14658
15067
  if (answered === void 0) throw panelError("the check-in did not finish in time; try again", "TIMEOUT");
14659
15068
  return answered;
14660
15069
  }
@@ -14753,15 +15162,6 @@ async function onPanelInvoke(channel, payload) {
14753
15162
  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");
14754
15163
  return await statusDocument({ allowNetwork: false });
14755
15164
  /**
14756
- * Rewrite the client name the domestic host's channel check refuses.
14757
- *
14758
- * Off by default: it changes what the prompt says about the client, which is
14759
- * a decision for the user rather than something the plugin does behind them.
14760
- */
14761
- case "xd.setRewriteClientName":
14762
- 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");
14763
- return await statusDocument({ allowNetwork: false });
14764
- /**
14765
15165
  * Park or unpark one edition of one source (国内版 / 国际版).
14766
15166
  *
14767
15167
  * Same shape as the source switch above: a parked region keeps no gateway,
@@ -14779,7 +15179,7 @@ async function onPanelInvoke(channel, payload) {
14779
15179
  if (payload?.enabled !== true) parked.push(key);
14780
15180
  return parked;
14781
15181
  }) !== true) throw panelError("the region switch could not be written to the plugin settings file", "SAVE_FAILED");
14782
- await onHostSettingsChanged({});
15182
+ await applySettingsEverywhere(false);
14783
15183
  if (payload?.enabled === true) await refreshAll("region-on", true);
14784
15184
  else syncDeclaration();
14785
15185
  if (source === "workbuddy") {
@@ -14801,7 +15201,7 @@ async function onPanelInvoke(channel, payload) {
14801
15201
  if (key === void 0) throw panelError("unknown source", "UNSUPPORTED");
14802
15202
  if (await saveSettings({ [key]: payload?.enabled === true }) !== true) throw panelError("the source switch could not be written to the plugin settings file", "SAVE_FAILED");
14803
15203
  resetDiscoveryCaches();
14804
- await onHostSettingsChanged({});
15204
+ await applySettingsEverywhere(false);
14805
15205
  if (payload?.enabled === true) await refreshAll("source-on", true);
14806
15206
  else syncDeclaration();
14807
15207
  if (payload?.source === "workbuddy") {
@@ -15033,6 +15433,7 @@ async function runCheckinPass(options) {
15033
15433
  slot,
15034
15434
  claimed: 0,
15035
15435
  pending: true,
15436
+ workbuddy: want("workbuddy"),
15036
15437
  at: (/* @__PURE__ */ new Date()).toISOString(),
15037
15438
  ...manual ? { manual: true } : {}
15038
15439
  };
@@ -15076,25 +15477,30 @@ async function runCheckinPass(options) {
15076
15477
  adopted: 0
15077
15478
  }, "travel") : void 0;
15078
15479
  if (!stillLoaded(generation)) return started;
15079
- qoderRetryAt = typeof qoder?.opensAt === "number" && qoder.opensAt > Date.now() ? qoder.opensAt : 0;
15480
+ if (want("qoder")) {
15481
+ const now = Date.now();
15482
+ const opening = typeof qoder?.opensAt === "number" && qoder.opensAt > now ? qoder.opensAt : 0;
15483
+ const backoff = Number(qoder?.failed) > 0 && (typeof qoder?.reason === "string" || qoder?.retry === true) ? now + QODER_RETRY_BACKOFF_MS : 0;
15484
+ qoderRetryAt = opening === 0 ? backoff : backoff === 0 ? opening : Math.min(opening, backoff);
15485
+ }
15080
15486
  Object.assign(started, {
15081
15487
  claimed: pool.claimed,
15082
15488
  skipped: pool.skipped,
15083
15489
  failed: pool.failed,
15084
15490
  ...pool.reason === void 0 ? {} : { reason: pool.reason },
15085
15491
  travel,
15086
- qoder,
15087
- trae
15492
+ ...want("qoder") ? { qoder } : {},
15493
+ ...want("trae") ? { trae } : {}
15088
15494
  });
15089
15495
  await checkinDelay(GROWTH_AFTER_CHECKIN_MS);
15090
15496
  if (!stillLoaded(generation)) return started;
15091
15497
  started.growth = want("workbuddy") ? await claimAllGrowth() : void 0;
15092
15498
  log((manual ? "manual" : "automatic") + " check-in collected " + pool.claimed + " account(s) for " + slot);
15093
- if (spendsSlot && stillLoaded(generation)) saveCheckinSlots();
15499
+ if ((spendsSlot || want("qoder")) && stillLoaded(generation)) saveCheckinSlots();
15094
15500
  } catch (error) {
15095
15501
  started.error = safeMessage(error);
15096
15502
  log("warn", (manual ? "manual" : "automatic") + " check-in failed for " + slot + ": " + started.error);
15097
- if (spendsSlot && stillLoaded(generation)) saveCheckinSlots();
15503
+ if ((spendsSlot || want("qoder")) && stillLoaded(generation)) saveCheckinSlots();
15098
15504
  } finally {
15099
15505
  if (token === checkinPassToken) checkinPassRunning = false;
15100
15506
  delete started.pending;
@@ -15551,7 +15957,8 @@ async function qoderCheckinAll() {
15551
15957
  const counts = {
15552
15958
  claimed: 0,
15553
15959
  skipped: 0,
15554
- failed: 0
15960
+ failed: 0,
15961
+ retry: false
15555
15962
  };
15556
15963
  const regions = activeQoderRegions();
15557
15964
  if (regions.length === 0) return counts;
@@ -15567,6 +15974,10 @@ async function qoderCheckinAll() {
15567
15974
  reason
15568
15975
  };
15569
15976
  }
15977
+ if (found.failures.length > 0) {
15978
+ counts.failed += 1;
15979
+ counts.retry = true;
15980
+ }
15570
15981
  let seen = 0;
15571
15982
  for (const credential of found.credentials) {
15572
15983
  if (!regions.includes(credential.region)) continue;
@@ -15575,6 +15986,7 @@ async function qoderCheckinAll() {
15575
15986
  seen += 1;
15576
15987
  const result = await qoderClaimFor(credential);
15577
15988
  counts[result.outcome] += 1;
15989
+ if (result.retry === true) counts.retry = true;
15578
15990
  if (result.opensAt !== void 0 && (counts.opensAt === void 0 || result.opensAt < counts.opensAt)) counts.opensAt = result.opensAt;
15579
15991
  }
15580
15992
  return counts;
@@ -15605,7 +16017,8 @@ async function qoderClaimFor(credential) {
15605
16017
  log("warn", "[qoder:" + credential.region + "] check-in refused for " + qoderRowLabel(credential) + ": " + result.reason);
15606
16018
  return {
15607
16019
  outcome: "failed",
15608
- reason: result.reason
16020
+ reason: result.reason,
16021
+ retry: false
15609
16022
  };
15610
16023
  }
15611
16024
  return { outcome: result.claimed && !result.replayed ? "claimed" : "skipped" };
@@ -15614,10 +16027,17 @@ async function qoderClaimFor(credential) {
15614
16027
  log("warn", "[qoder:" + credential.region + "] check-in failed for " + qoderRowLabel(credential) + ": " + reason);
15615
16028
  return {
15616
16029
  outcome: "failed",
15617
- reason
16030
+ reason,
16031
+ retry: qoderFailureRetryable(error)
15618
16032
  };
15619
16033
  }
15620
16034
  }
16035
+ /** A transport/5xx failure is worth another tick; a 4xx verdict is not. */
16036
+ function qoderFailureRetryable(error) {
16037
+ const status = Number(/\bHTTP\s+(\d{3})\b/iu.exec(safeMessage(error))?.[1] ?? 0);
16038
+ if (status === 0) return true;
16039
+ return status === 408 || status === 429 || status >= 500;
16040
+ }
15621
16041
  /**
15622
16042
  * Claim today's Trae credits for every signed-in CN Trae account. Each account
15623
16043
  * is read first: one already checked in costs a single status call and no
@@ -15792,20 +16212,27 @@ async function autoCheckinTick(now) {
15792
16212
  checkinAbort.abort();
15793
16213
  checkinAbort = new AbortController();
15794
16214
  checkinScope.enterWith(checkinAbort.signal);
16215
+ const retrySlot = autoCheckinLast?.slot ?? checkinSlotId(zonedDayHour(/* @__PURE__ */ new Date()).day, zonedDayHour(/* @__PURE__ */ new Date()).hour);
15795
16216
  try {
15796
16217
  qoderRetryAt = 0;
15797
16218
  const retry = await qoderCheckinAll();
15798
16219
  if (!stillLoaded(retryGeneration)) return autoCheckinLast;
15799
- 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;
16220
+ const now = Date.now();
16221
+ const opening = typeof retry.opensAt === "number" && retry.opensAt > now ? retry.opensAt : 0;
16222
+ const backoff = Number(retry.failed) > 0 && (typeof retry.reason === "string" || retry.retry === true) ? now + QODER_RETRY_BACKOFF_MS : 0;
16223
+ qoderRetryAt = opening === 0 ? backoff : backoff === 0 ? opening : Math.min(opening, backoff);
15800
16224
  const claimedBefore = Number(autoCheckinLast?.qoder?.claimed) || 0;
15801
16225
  autoCheckinLast = {
15802
16226
  ...autoCheckinLast,
16227
+ slot: retrySlot,
16228
+ ...autoCheckinLast === null ? { workbuddy: false } : {},
15803
16229
  qoder: {
15804
16230
  ...retry,
15805
16231
  claimed: claimedBefore + (Number(retry.claimed) || 0)
15806
16232
  },
15807
16233
  at: (/* @__PURE__ */ new Date()).toISOString()
15808
16234
  };
16235
+ saveCheckinSlots();
15809
16236
  log("info", "deferred Qoder check-in: " + JSON.stringify(retry));
15810
16237
  } catch (error) {
15811
16238
  if (stillLoaded(retryGeneration)) {
@@ -15813,6 +16240,7 @@ async function autoCheckinTick(now) {
15813
16240
  const claimedBefore = Number(autoCheckinLast?.qoder?.claimed) || 0;
15814
16241
  autoCheckinLast = {
15815
16242
  ...autoCheckinLast,
16243
+ slot: retrySlot,
15816
16244
  qoder: {
15817
16245
  claimed: claimedBefore,
15818
16246
  skipped: 0,
@@ -15821,6 +16249,7 @@ async function autoCheckinTick(now) {
15821
16249
  },
15822
16250
  at: (/* @__PURE__ */ new Date()).toISOString()
15823
16251
  };
16252
+ saveCheckinSlots();
15824
16253
  log("warn", "deferred Qoder check-in failed: " + safeMessage(error));
15825
16254
  }
15826
16255
  } finally {
@@ -15968,10 +16397,13 @@ async function publishDeclarationEarly() {
15968
16397
  else if (written.changed === true) log("info", "declaration updated at load time; " + written.providerCount + " provider(s)");
15969
16398
  }
15970
16399
  async function onServiceStart() {
16400
+ const generation = loadGeneration;
15971
16401
  serviceStopped = false;
15972
16402
  if (warmAbort.signal.aborted) warmAbort = new AbortController();
15973
16403
  await adoptHostSettings();
16404
+ if (!stillLoaded(generation)) return;
15974
16405
  if (settings.enabled === false) {
16406
+ syncDeclaration();
15975
16407
  log("info", "plugin disabled in settings; the provider host stays down");
15976
16408
  return;
15977
16409
  }
@@ -15980,9 +16412,13 @@ async function onServiceStart() {
15980
16412
  startAccountWatch();
15981
16413
  const { left: bootstrapLeft } = budget(SERVICE_BOOTSTRAP_BUDGET_MS);
15982
16414
  await settleWithin(reconcileTraeGateways(), bootstrapLeft());
16415
+ if (!stillLoaded(generation)) return;
15983
16416
  await settleWithin(reconcileQoderGateways(), bootstrapLeft());
16417
+ if (!stillLoaded(generation)) return;
15984
16418
  if (activeRegions().length > 0) await settleWithin(core.pool.scan(), bootstrapLeft());
16419
+ if (!stillLoaded(generation)) return;
15985
16420
  await settleWithin(startRuntimes(), bootstrapLeft());
16421
+ if (!stillLoaded(generation)) return;
15986
16422
  await settleWithin(Promise.all(Array.from(runtimes.values()).map(async (runtime) => {
15987
16423
  try {
15988
16424
  await connect(runtime, !catalogFresh(runtime));
@@ -15991,6 +16427,7 @@ async function onServiceStart() {
15991
16427
  log("warn", runtime.region + " failed to start: " + runtime.lastError);
15992
16428
  }
15993
16429
  })), SERVICE_ROSTER_BUDGET_MS);
16430
+ if (!stillLoaded(generation)) return;
15994
16431
  syncDeclaration();
15995
16432
  scheduleRefresh("service-start");
15996
16433
  }
@@ -16017,6 +16454,7 @@ async function onServiceStop() {
16017
16454
  qoderGateways.clear();
16018
16455
  gatewayStartFailures.clear();
16019
16456
  sourceStartFailures.clear();
16457
+ sourceGatewayStarts.clear();
16020
16458
  await Promise.all(closing);
16021
16459
  }
16022
16460
  async function onLoad() {
@@ -16037,11 +16475,7 @@ async function onLoad() {
16037
16475
  for (const runtime of runtimes.values()) pendingRuntimeStops.push(stopRuntime(runtime));
16038
16476
  runtimes.clear();
16039
16477
  runtimeStarts.clear();
16040
- for (const entry of [...traeGateways.values(), ...qoderGateways.values()]) pendingRuntimeStops.push(entry.gateway.close().catch((error) => {
16041
- log("warn", "[" + entry.source + ":" + entry.region + "] gateway did not close cleanly: " + safeMessage(error));
16042
- }));
16043
- traeGateways.clear();
16044
- qoderGateways.clear();
16478
+ sourceGatewayStarts.clear();
16045
16479
  checkinPassRunning = false;
16046
16480
  autoCheckinSlots.clear();
16047
16481
  autoCheckinLast = null;
@@ -16049,7 +16483,7 @@ async function onLoad() {
16049
16483
  growthLast = null;
16050
16484
  keepAliveLast = null;
16051
16485
  qoderRetryAt = 0;
16052
- core.client = new WorkBuddyUpstreamClient({ fetchImpl: clientNameRewritingFetch(replacedClientName) });
16486
+ core.client = new WorkBuddyUpstreamClient({});
16053
16487
  core.pool = new WorkBuddyAccountPool({
16054
16488
  client: core.client,
16055
16489
  cooldownMs: cooldownMs(),
@@ -16063,7 +16497,6 @@ async function onLoad() {
16063
16497
  });
16064
16498
  await adoptHostSettings();
16065
16499
  if (serviceStopped) return;
16066
- declarationIndex = /* @__PURE__ */ new Map();
16067
16500
  publishedIds = /* @__PURE__ */ new Set();
16068
16501
  try {
16069
16502
  dataPath = await pi.plugin.getDataPath();
@@ -16100,6 +16533,7 @@ async function onUnload() {
16100
16533
  traeIdentityBlockers.clear();
16101
16534
  gatewayStartFailures.clear();
16102
16535
  sourceStartFailures.clear();
16536
+ sourceGatewayStarts.clear();
16103
16537
  deviceLogins.clear();
16104
16538
  unsubscribeFromHostSettings();
16105
16539
  }
@@ -16107,19 +16541,6 @@ function composerPointsEnabled() {
16107
16541
  return settings.showComposerPoints === true;
16108
16542
  }
16109
16543
  /**
16110
- * The name this plugin sends as the client when the user turns the rewrite on.
16111
- *
16112
- * WorkBuddy's domestic host refuses a request whose prompt names DeepSeek
16113
- * Harness (`11128`, channel check) on every account of that region, so the panel
16114
- * offers a switch that renames the client in the outgoing prompt. "DeepSeek" is
16115
- * the vendor that actually serves the model, so the sentences stay true, and it
16116
- * was verified against the live host: the two prompts it refuses are accepted
16117
- * with the product name replaced.
16118
- */
16119
- function replacedClientName() {
16120
- return settings.rewriteClientName === true ? "DeepSeek" : void 0;
16121
- }
16122
- /**
16123
16544
  * The source and region one selected provider route belongs to.
16124
16545
  *
16125
16546
  * The composer readout is handed the session's selection straight from the
@@ -16212,7 +16633,7 @@ function workbuddyComposerAccounts(region, modelId) {
16212
16633
  function sourceComposerAccounts(source, region) {
16213
16634
  const rows = (source === "trae" ? traeAccountRows : qoderAccountRows).filter((row) => row.region === region);
16214
16635
  const live = rows.filter((row) => row.expired !== true);
16215
- const active = orderSourceCredentials(source, region, live, (row) => row.label, false)[0];
16636
+ const active = orderSourceCredentials(source, region, live, (row) => row.label, "peek")[0];
16216
16637
  return rows.map((row) => {
16217
16638
  const credits = row.usage?.credits;
16218
16639
  return {
@@ -16298,9 +16719,12 @@ async function composerPrefer(args) {
16298
16719
  else next[sourceRegionKey(source, region)] = accountLabel;
16299
16720
  return next;
16300
16721
  }) !== true) throw panelError("the account choice could not be saved", "SAVE_FAILED");
16722
+ const activeLabel = sourceComposerAccounts(source, region).find((row) => row.active === true)?.label ?? "";
16723
+ const servable = accountLabel === "" || activeLabel === accountLabel;
16301
16724
  return {
16302
16725
  ...composerPoints(args),
16303
- saved: true
16726
+ saved: true,
16727
+ ...servable ? {} : { unavailable: true }
16304
16728
  };
16305
16729
  }
16306
16730
  //#endregion
@@ -16444,7 +16868,6 @@ const Config = z.object({
16444
16868
  preferredSourceAccounts: asVolatile(z.any().description("Picked Trae/Qoder account per region")),
16445
16869
  removedAccounts: asVolatile(z.any().description("Accounts removed from the pool for good")),
16446
16870
  showComposerPoints: asVolatile(z.boolean().default(false).description("Show the active account credits beside the composer")),
16447
- rewriteClientName: asVolatile(z.boolean().default(false).description("Rename the client in the prompt WorkBuddy receives (domestic channel check 11128)")),
16448
16871
  sourceDistributions: asVolatile(z.any().description("How each Trae/Qoder region spreads requests"))
16449
16872
  });
16450
16873
  /** Peel one volatile reference, if the running line wrapped it. */
@@ -16719,13 +17142,16 @@ function apply(ctx, config = {}) {
16719
17142
  if (mutate === void 0) throw new Error("this host exposes no settings mutate()");
16720
17143
  writesStarted += 1;
16721
17144
  writesInFlight += 1;
17145
+ let echoed = false;
16722
17146
  try {
16723
17147
  await mutate.call(settingsService, settingsNamespace, Object.entries(patch).map(([key, value]) => ({
16724
17148
  op: "set",
16725
17149
  path: [key],
16726
17150
  value
16727
17151
  })));
17152
+ echoed = true;
16728
17153
  } finally {
17154
+ if (!echoed) writesStarted -= 1;
16729
17155
  writesInFlight -= 1;
16730
17156
  if (writesInFlight === 0) {
16731
17157
  if (droppedPushes > writesStarted) {