dsh-wtq-pool 1.1.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/README.en.md +21 -17
- package/README.md +21 -17
- package/lib/client.js +1 -2
- package/lib/index.d.ts +0 -2
- package/lib/index.js +1291 -556
- package/package.json +1 -1
- package/renderer/index.html +2 -15
- package/renderer/panel.css +1 -1
- package/renderer/panel.js +189 -134
package/lib/index.js
CHANGED
|
@@ -12,9 +12,9 @@ import { resolveImageAttachmentAccess, resolveRetryPolicy } from "@deepseek-ai/d
|
|
|
12
12
|
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
|
-
import * as net from "node:net";
|
|
16
|
-
import { isIP } from "node:net";
|
|
17
15
|
import { constants, createCipheriv, createDecipheriv, createHash, publicEncrypt, randomBytes, randomUUID } from "node:crypto";
|
|
16
|
+
import * as net from "node:net";
|
|
17
|
+
import { BlockList, isIP } from "node:net";
|
|
18
18
|
import * as fs$1 from "node:fs";
|
|
19
19
|
import { statSync } from "node:fs";
|
|
20
20
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -29,6 +29,17 @@ import { execFile, execFileSync, spawn } from "node:child_process";
|
|
|
29
29
|
* these lines agree.
|
|
30
30
|
*/
|
|
31
31
|
const LOG_PREFIX = "wtq-pool";
|
|
32
|
+
/**
|
|
33
|
+
* A stable, non-identifying tag for one account in a log line.
|
|
34
|
+
*
|
|
35
|
+
* The panel shows the label because the user needs to tell accounts apart. A
|
|
36
|
+
* log is copied into bug reports far more often than the panel is, and an email
|
|
37
|
+
* address or nickname there is personal data; a short digest still lets two
|
|
38
|
+
* lines about the same account be correlated without carrying the label.
|
|
39
|
+
*/
|
|
40
|
+
function accountLogTag(label) {
|
|
41
|
+
return "acct-" + createHash("sha256").update(String(label ?? "")).digest("hex").slice(0, 8);
|
|
42
|
+
}
|
|
32
43
|
//#endregion
|
|
33
44
|
//#region src/loopback.ts
|
|
34
45
|
const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
|
|
@@ -164,6 +175,7 @@ const REDACTIONS = [
|
|
|
164
175
|
[/\b(qoder-oauth-token-)[A-Za-z0-9_+/.=-]+/g, "$1[redacted]"],
|
|
165
176
|
[/\b(rt_)[A-Za-z0-9_+/.=-]+/g, "$1[redacted]"],
|
|
166
177
|
[/((?:\\{0,2}["']?)(?:access_?token|refresh_?token|id_?token|auth_?token|oauth_?token|api_?key|secret|token)(?:\\{0,2}["']?\s*[:=]\s*\\{0,2}["']?))(?=[A-Za-z0-9_+/.=-]{6,})(?=[A-Za-z0-9_+/.=-]*[A-Za-z_-])[A-Za-z0-9_+/.=-]+/gi, "$1[redacted]"],
|
|
178
|
+
[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, "[account]"],
|
|
167
179
|
[/\b[A-Za-z]:[\\/][^\r\n"'<>|]*/g, "[redacted path]"],
|
|
168
180
|
[/\\\\[^\r\n"'<>|]+/g, "[redacted path]"],
|
|
169
181
|
[/(['"])(\/(?!\/)[^'"\r\n]+)\1/g, "$1[redacted path]$1"],
|
|
@@ -183,18 +195,22 @@ function redactSecrets(text) {
|
|
|
183
195
|
/**
|
|
184
196
|
* The vendor's channel check, answered as what it is.
|
|
185
197
|
*
|
|
186
|
-
* WorkBuddy's upstream
|
|
187
|
-
*
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
*
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
*
|
|
198
|
+
* WorkBuddy's upstream inspects the system and assistant turns for wording that
|
|
199
|
+
* belongs to a client it does not serve, and answers business code 11128. The
|
|
200
|
+
* plugin already moves the system prompt into the first user turn and retries
|
|
201
|
+
* once (`chatStream`); a second refusal means the blocked wording is somewhere
|
|
202
|
+
* that move does not reach, or the host changed its screen again. Every account
|
|
203
|
+
* of that region answers the same way, so rotation cannot clear it, and the
|
|
204
|
+
* vendor body is a wall of mixed Chinese and English tips that names no cause a
|
|
205
|
+
* user can act on. The sentence below says what happened and what does work.
|
|
194
206
|
*/
|
|
195
207
|
function unapprovedChannelRefusal(text) {
|
|
196
|
-
if (!/"code"\s*:\s*11128\b
|
|
197
|
-
return
|
|
208
|
+
if (!/"code"\s*:\s*"?11128\b/u.test(text) && !/\bcode 11128\b/u.test(text)) return void 0;
|
|
209
|
+
return channelCheckRefusal();
|
|
210
|
+
}
|
|
211
|
+
/** The sentence a refused prompt is answered with, whatever shape the body has. */
|
|
212
|
+
function channelCheckRefusal() {
|
|
213
|
+
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
214
|
}
|
|
199
215
|
/**
|
|
200
216
|
* The `finish_reason` one turn is reported with.
|
|
@@ -473,19 +489,8 @@ async function pumpToResponse(source, res) {
|
|
|
473
489
|
for (;;) {
|
|
474
490
|
const next = await reader.read();
|
|
475
491
|
if (next.done) break;
|
|
492
|
+
await writeChunk(res, next.value);
|
|
476
493
|
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
494
|
}
|
|
490
495
|
} finally {
|
|
491
496
|
res.off("close", cancel);
|
|
@@ -592,7 +597,7 @@ function createLoopbackServer(options) {
|
|
|
592
597
|
});
|
|
593
598
|
server.listen(options.port ?? 0, "127.0.0.1");
|
|
594
599
|
server.on("error", (error) => {
|
|
595
|
-
options.logger?.warn?.("wtq-pool: " + options.label + " server error", error);
|
|
600
|
+
options.logger?.warn?.("wtq-pool: " + options.label + " server error", safeMessage(error));
|
|
596
601
|
});
|
|
597
602
|
return {
|
|
598
603
|
ready,
|
|
@@ -793,7 +798,6 @@ const CHANNELS = /* @__PURE__ */ new Set([
|
|
|
793
798
|
"xd.distribution",
|
|
794
799
|
"xd.setAutoCheckin",
|
|
795
800
|
"xd.setComposerPoints",
|
|
796
|
-
"xd.setRewriteClientName",
|
|
797
801
|
"xd.setCreditReserve",
|
|
798
802
|
"xd.setRegionEnabled",
|
|
799
803
|
"xd.setSource",
|
|
@@ -831,63 +835,18 @@ const PANEL_CSP = [
|
|
|
831
835
|
"base-uri 'none'",
|
|
832
836
|
"form-action 'none'"
|
|
833
837
|
].join("; ");
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
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
|
-
*/
|
|
838
|
+
const LOOPBACK = new BlockList();
|
|
839
|
+
LOOPBACK.addSubnet("127.0.0.0", 8, "ipv4");
|
|
840
|
+
LOOPBACK.addAddress("::1", "ipv6");
|
|
841
|
+
LOOPBACK.addSubnet("::ffff:127.0.0.0", 104, "ipv6");
|
|
842
|
+
/** Whether the request's peer is this machine. */
|
|
882
843
|
function peerIsLoopback(req) {
|
|
883
844
|
const address = req.socket.remoteAddress;
|
|
884
845
|
if (address === void 0) return false;
|
|
885
|
-
|
|
886
|
-
if (
|
|
887
|
-
|
|
888
|
-
|
|
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;
|
|
846
|
+
const family = isIP(address);
|
|
847
|
+
if (family === 4) return LOOPBACK.check(address, "ipv4");
|
|
848
|
+
if (family === 6) return LOOPBACK.check(address, "ipv6");
|
|
849
|
+
return false;
|
|
891
850
|
}
|
|
892
851
|
/**
|
|
893
852
|
* Whether the request's own headers say the page asking is this origin.
|
|
@@ -1039,7 +998,7 @@ function registerPanelRoutes(ctx, deps) {
|
|
|
1039
998
|
for (const dispose of disposers) try {
|
|
1040
999
|
dispose();
|
|
1041
1000
|
} catch (error) {
|
|
1042
|
-
deps.logger.warn("dsh-wtq-pool: a panel route did not release cleanly", error);
|
|
1001
|
+
deps.logger.warn("dsh-wtq-pool: a panel route did not release cleanly", safeMessage(error));
|
|
1043
1002
|
}
|
|
1044
1003
|
};
|
|
1045
1004
|
const mount = (route) => {
|
|
@@ -1100,7 +1059,7 @@ function registerPanelRoutes(ctx, deps) {
|
|
|
1100
1059
|
return release;
|
|
1101
1060
|
});
|
|
1102
1061
|
} catch (error) {
|
|
1103
|
-
deps.logger.warn("dsh-wtq-pool: the panel routes could not be mounted", error);
|
|
1062
|
+
deps.logger.warn("dsh-wtq-pool: the panel routes could not be mounted", safeMessage(error));
|
|
1104
1063
|
}
|
|
1105
1064
|
}
|
|
1106
1065
|
//#endregion
|
|
@@ -1230,29 +1189,33 @@ const CN_BILLING_BASE = "https://www.codebuddy.cn";
|
|
|
1230
1189
|
/** Global base for `workbuddy.ai` logins. */
|
|
1231
1190
|
const GLOBAL_BASE$1 = "https://www.workbuddy.ai";
|
|
1232
1191
|
/**
|
|
1233
|
-
*
|
|
1192
|
+
* Client versions the two gateways see, and the headers that carry them.
|
|
1234
1193
|
*
|
|
1235
|
-
*
|
|
1236
|
-
*
|
|
1237
|
-
*
|
|
1238
|
-
*
|
|
1239
|
-
* global config (verified 2026-10-26), so every call reads from here.
|
|
1194
|
+
* CN desktop 5.9.3 (2026-10-27) sends `X-Agent-Runtime: local-agent` and the
|
|
1195
|
+
* same `X-Stainless-*` family as the bundled CLI. The international desktop is
|
|
1196
|
+
* still 5.8.4. Keeping one literal for both was one version behind on CN and
|
|
1197
|
+
* produced a combination no installed client sends.
|
|
1240
1198
|
*/
|
|
1241
|
-
const
|
|
1242
|
-
const
|
|
1199
|
+
const CN_CLIENT_VERSION = "5.9.3";
|
|
1200
|
+
const CN_CLI_VERSION = "2.165.0";
|
|
1201
|
+
const GLOBAL_CLIENT_VERSION = "5.8.4";
|
|
1202
|
+
const GLOBAL_CLI_VERSION = "2.161.0";
|
|
1243
1203
|
/** CN chat UA: the desktop client's three-segment spelling. */
|
|
1244
|
-
const
|
|
1204
|
+
const CN_CHAT_UA = `WorkBuddy/${CN_CLIENT_VERSION} WorkBuddy/${CN_CLIENT_VERSION} CLI/${CN_CLI_VERSION}`;
|
|
1205
|
+
/** CN desktop UA, used by the endpoints the desktop process calls directly. */
|
|
1206
|
+
const CN_DESKTOP_UA = `WorkBuddy/${CN_CLIENT_VERSION}`;
|
|
1245
1207
|
/**
|
|
1246
|
-
* The international desktop client's
|
|
1247
|
-
*
|
|
1208
|
+
* The international desktop client's UA. The `workbuddy-ai/` segment only
|
|
1209
|
+
* exists on that gateway, and the CN spelling gets the CLI roster there.
|
|
1248
1210
|
*/
|
|
1249
|
-
const GLOBAL_CHAT_UA = `WorkBuddy/${
|
|
1211
|
+
const GLOBAL_CHAT_UA = `WorkBuddy/${GLOBAL_CLIENT_VERSION} workbuddy-ai/${GLOBAL_CLIENT_VERSION} CLI/${GLOBAL_CLI_VERSION}`;
|
|
1250
1212
|
/**
|
|
1251
|
-
* Desktop app UA
|
|
1252
|
-
* client channel: the CLI UA gets a truncated roster (or an HTTP 500),
|
|
1253
|
-
* is why the international catalog must be read with the desktop
|
|
1213
|
+
* Desktop app UA for the global gateway. It serves its product config only to
|
|
1214
|
+
* this client channel: the CLI UA gets a truncated roster (or an HTTP 500),
|
|
1215
|
+
* which is why the international catalog must be read with the desktop
|
|
1216
|
+
* spelling.
|
|
1254
1217
|
*/
|
|
1255
|
-
const
|
|
1218
|
+
const GLOBAL_DESKTOP_UA = `WorkBuddy/${GLOBAL_CLIENT_VERSION}`;
|
|
1256
1219
|
/** CN model catalog. */
|
|
1257
1220
|
const MODELS_CATALOG_PATH = "/v2/enterprises/personal/models";
|
|
1258
1221
|
/** Global product config, which carries the international model roster. */
|
|
@@ -1462,6 +1425,15 @@ const SESSION_DEAD_PATTERN = /Offline user session not found|"code"\s*:\s*"?1215
|
|
|
1462
1425
|
*/
|
|
1463
1426
|
const MODEL_TIER_PATTERN = /"code"\s*:\s*"?11158\b/u;
|
|
1464
1427
|
/**
|
|
1428
|
+
* The prompt-screen refusal: `11128`.
|
|
1429
|
+
*
|
|
1430
|
+
* The host returns it for a system or assistant turn whose wording belongs to a
|
|
1431
|
+
* client it does not serve. It is a property of the request body, not the
|
|
1432
|
+
* account, so the rotation must not spend another sign-in on it; `chatStream`
|
|
1433
|
+
* moves the system prompt into the first user turn and retries once instead.
|
|
1434
|
+
*/
|
|
1435
|
+
const CHANNEL_CHECK_PATTERN = /"code"\s*:\s*"?11128\b/u;
|
|
1436
|
+
/**
|
|
1465
1437
|
* The vendor's account-level restriction: `11140`, "request illegal".
|
|
1466
1438
|
*
|
|
1467
1439
|
* The body names the account ("your account has been restricted due to unusual
|
|
@@ -1471,6 +1443,15 @@ const MODEL_TIER_PATTERN = /"code"\s*:\s*"?11158\b/u;
|
|
|
1471
1443
|
*/
|
|
1472
1444
|
const ACCOUNT_RESTRICTED_PATTERN = /"code"\s*:\s*"?11140\b/u;
|
|
1473
1445
|
/**
|
|
1446
|
+
* The upstream's rate-limit marker.
|
|
1447
|
+
*
|
|
1448
|
+
* The same envelope is returned with HTTP 200 by JSON endpoints and by the
|
|
1449
|
+
* chat screen, so the status alone cannot decide it. The code is matched as an
|
|
1450
|
+
* envelope value rather than as a bare number for the reason above; the text
|
|
1451
|
+
* forms cover the older deployments that answer with prose only.
|
|
1452
|
+
*/
|
|
1453
|
+
const SOFT_RATE_PATTERN = /"code"\s*:\s*"?6004\b|soft_rate|频率限制/u;
|
|
1454
|
+
/**
|
|
1474
1455
|
* Hosts the international product answers on, once each has been stripped of a
|
|
1475
1456
|
* leading label. The WorkBuddy AI desktop app signs in at `workbuddy.ai` (and
|
|
1476
1457
|
* the desktop client itself lists `workbuddy.cc` alongside it); the CodeBuddy
|
|
@@ -1490,6 +1471,35 @@ function regionOf(domain) {
|
|
|
1490
1471
|
for (const host of GLOBAL_HOSTS) if (lowered === host || lowered.endsWith(`.${host}`)) return "global";
|
|
1491
1472
|
return "cn";
|
|
1492
1473
|
}
|
|
1474
|
+
/** The client version that gateway expects in `X-IDE-Version`. */
|
|
1475
|
+
function clientVersion(region) {
|
|
1476
|
+
return region === "global" ? GLOBAL_CLIENT_VERSION : CN_CLIENT_VERSION;
|
|
1477
|
+
}
|
|
1478
|
+
/** The full chat UA for the credential's gateway. */
|
|
1479
|
+
function chatUa(region) {
|
|
1480
|
+
return region === "global" ? GLOBAL_CHAT_UA : CN_CHAT_UA;
|
|
1481
|
+
}
|
|
1482
|
+
/** The desktop-process UA for endpoints outside the chat path. */
|
|
1483
|
+
function desktopUa(region) {
|
|
1484
|
+
return region === "global" ? GLOBAL_DESKTOP_UA : CN_DESKTOP_UA;
|
|
1485
|
+
}
|
|
1486
|
+
/**
|
|
1487
|
+
* The OpenAI Node SDK's fingerprint headers, as the current desktop client sends
|
|
1488
|
+
* them. OS, architecture and runtime version follow the host so a macOS or Linux
|
|
1489
|
+
* install does not claim to be a Windows client; the rest mirror the bundled CLI.
|
|
1490
|
+
*/
|
|
1491
|
+
function stainlessHeaders() {
|
|
1492
|
+
return {
|
|
1493
|
+
"x-stainless-lang": "js",
|
|
1494
|
+
"x-stainless-package-version": "6.25.0",
|
|
1495
|
+
"x-stainless-os": process.platform === "win32" ? "Windows" : process.platform === "darwin" ? "MacOS" : "Linux",
|
|
1496
|
+
"x-stainless-arch": process.arch,
|
|
1497
|
+
"x-stainless-runtime": "node",
|
|
1498
|
+
"x-stainless-runtime-version": process.version,
|
|
1499
|
+
"x-stainless-retry-count": "0",
|
|
1500
|
+
"x-stainless-timeout": "1200"
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1493
1503
|
/**
|
|
1494
1504
|
* Gateway for a global credential.
|
|
1495
1505
|
*
|
|
@@ -1516,7 +1526,7 @@ function commonHeaders(credential) {
|
|
|
1516
1526
|
"X-Requested-With": "XMLHttpRequest",
|
|
1517
1527
|
"Origin": billingBase(credential),
|
|
1518
1528
|
"Referer": `${billingBase(credential)}/`,
|
|
1519
|
-
"User-Agent":
|
|
1529
|
+
"User-Agent": desktopUa(regionOf(credential.domain)),
|
|
1520
1530
|
"X-CodeBuddy-Request": "1",
|
|
1521
1531
|
"Connection": "close"
|
|
1522
1532
|
};
|
|
@@ -1542,7 +1552,7 @@ function commonHeaders(credential) {
|
|
|
1542
1552
|
* one - so there is nothing to gain from deriving it, and a stable value would
|
|
1543
1553
|
* be one more thing for the channel check to notice.
|
|
1544
1554
|
*/
|
|
1545
|
-
function conversationHeaders() {
|
|
1555
|
+
function conversationHeaders(region) {
|
|
1546
1556
|
const turn = randomUUID().replace(/-/g, "");
|
|
1547
1557
|
const message = randomUUID().replace(/-/g, "");
|
|
1548
1558
|
const traceId = randomUUID().replace(/-/g, "");
|
|
@@ -1556,7 +1566,7 @@ function conversationHeaders() {
|
|
|
1556
1566
|
"X-Agent-Intent": "craft",
|
|
1557
1567
|
"X-Agent-Purpose": "conversation",
|
|
1558
1568
|
"X-Agent-Type": "main",
|
|
1559
|
-
"X-IDE-Version":
|
|
1569
|
+
"X-IDE-Version": clientVersion(region),
|
|
1560
1570
|
"X-Private-Data": "true",
|
|
1561
1571
|
"X-Trace-ID": traceId,
|
|
1562
1572
|
"traceparent": `00-${traceId}-${spanId}-01`,
|
|
@@ -1568,16 +1578,19 @@ function conversationHeaders() {
|
|
|
1568
1578
|
}
|
|
1569
1579
|
/** Chat request headers, including the X-No-* conventions the official CLI uses. */
|
|
1570
1580
|
function chatHeaders(credential) {
|
|
1581
|
+
const region = regionOf(credential.domain);
|
|
1571
1582
|
return {
|
|
1572
1583
|
...commonHeaders(credential),
|
|
1573
|
-
...conversationHeaders(),
|
|
1584
|
+
...conversationHeaders(region),
|
|
1585
|
+
...stainlessHeaders(),
|
|
1574
1586
|
"Content-Type": "application/json",
|
|
1575
1587
|
"Authorization": `Bearer ${credential.accessToken}`,
|
|
1576
1588
|
...credential.uid === "" || credential.uid === void 0 ? { "X-No-User-Id": "1" } : { "X-User-Id": credential.uid },
|
|
1577
1589
|
...credential.enterpriseId === void 0 || credential.enterpriseId === "" ? { "X-No-Enterprise-Id": "1" } : { "X-Enterprise-Id": credential.enterpriseId },
|
|
1578
1590
|
...credential.domain === "" ? { "X-No-Department-Info": "1" } : { "X-Domain": credential.domain },
|
|
1579
1591
|
"X-Product": "SaaS",
|
|
1580
|
-
...
|
|
1592
|
+
...region === "cn" ? { "X-Agent-Runtime": "local-agent" } : {},
|
|
1593
|
+
"User-Agent": chatUa(region)
|
|
1581
1594
|
};
|
|
1582
1595
|
}
|
|
1583
1596
|
/** Refresh-endpoint headers; X-Refresh-Token appears here and nowhere else. */
|
|
@@ -1597,7 +1610,7 @@ function billingHeaders(credential) {
|
|
|
1597
1610
|
"Accept": "application/json",
|
|
1598
1611
|
"Content-Type": "application/json",
|
|
1599
1612
|
"X-CodeBuddy-Request": "1",
|
|
1600
|
-
"User-Agent":
|
|
1613
|
+
"User-Agent": desktopUa(regionOf(credential.domain)),
|
|
1601
1614
|
"Connection": "close"
|
|
1602
1615
|
};
|
|
1603
1616
|
if (credential.uid !== "" && credential.uid !== void 0) headers["X-User-Id"] = credential.uid;
|
|
@@ -1700,8 +1713,9 @@ async function readEnvelope(response) {
|
|
|
1700
1713
|
}
|
|
1701
1714
|
if (typeof parsed !== "object" || parsed === null) throw new Error(`workbuddy upstream returned an unexpected document (http ${response.status})`);
|
|
1702
1715
|
const document = parsed;
|
|
1716
|
+
const rawCode = document["code"];
|
|
1703
1717
|
return {
|
|
1704
|
-
code: typeof
|
|
1718
|
+
code: typeof rawCode === "number" && Number.isFinite(rawCode) ? rawCode : typeof rawCode === "string" && /^-?\d+$/u.test(rawCode.trim()) ? Number(rawCode.trim()) : 0,
|
|
1705
1719
|
msg: typeof document["msg"] === "string" ? document["msg"] : "",
|
|
1706
1720
|
data: "data" in document ? document["data"] : void 0
|
|
1707
1721
|
};
|
|
@@ -1737,15 +1751,23 @@ function upstreamErrorKind(error) {
|
|
|
1737
1751
|
* fires on any other status, or a rate limit whose text happens to carry
|
|
1738
1752
|
* the code would rotate without cooling the account.
|
|
1739
1753
|
*
|
|
1740
|
-
* The credit markers are read
|
|
1741
|
-
* "this account cannot pay": 402
|
|
1742
|
-
* REQUEST, and its body routinely quotes the
|
|
1743
|
-
* matching there turned a malformed body into a
|
|
1744
|
-
* 402 that named the wrong problem.
|
|
1754
|
+
* The credit markers are read on the statuses the upstream itself uses for
|
|
1755
|
+
* "this account cannot pay": 402, 403, and an HTTP 200 business envelope. A
|
|
1756
|
+
* 400 or 422 is a verdict on the REQUEST, and its body routinely quotes the
|
|
1757
|
+
* quota it measured against, so matching there turned a malformed body into a
|
|
1758
|
+
* whole-pool rotation and a 402 that named the wrong problem.
|
|
1745
1759
|
*/
|
|
1746
1760
|
function classifyUpstreamError(status, body) {
|
|
1747
1761
|
if (status === 402) return "hard_credit";
|
|
1748
1762
|
if (status === 429) return "soft_rate";
|
|
1763
|
+
if (status === 200) {
|
|
1764
|
+
if (ACCOUNT_RESTRICTED_PATTERN.test(body)) return "account_restricted";
|
|
1765
|
+
if (MODEL_TIER_PATTERN.test(body)) return "model_tier";
|
|
1766
|
+
if (SESSION_DEAD_PATTERN.test(body)) return "session_dead";
|
|
1767
|
+
if (SOFT_RATE_PATTERN.test(body)) return "soft_rate";
|
|
1768
|
+
if (isHardCreditText(body)) return "hard_credit";
|
|
1769
|
+
return "client";
|
|
1770
|
+
}
|
|
1749
1771
|
if ((status === 400 || status === 403 || status === 422) && ACCOUNT_RESTRICTED_PATTERN.test(body)) return "account_restricted";
|
|
1750
1772
|
if ((status === 400 || status === 403 || status === 422) && MODEL_TIER_PATTERN.test(body)) return "model_tier";
|
|
1751
1773
|
if ((status === 401 || status === 403) && SESSION_DEAD_PATTERN.test(body)) return "session_dead";
|
|
@@ -1753,8 +1775,8 @@ function classifyUpstreamError(status, body) {
|
|
|
1753
1775
|
if (status === 403) {
|
|
1754
1776
|
if (isHardCreditText(body)) return "hard_credit";
|
|
1755
1777
|
}
|
|
1756
|
-
if (status === 503 &&
|
|
1757
|
-
if (status === 403 &&
|
|
1778
|
+
if (status === 503 && SOFT_RATE_PATTERN.test(body)) return "soft_rate";
|
|
1779
|
+
if (status === 403 && !/"code"\s*:|"msg"\s*:/.test(body)) return "waf_block";
|
|
1758
1780
|
if (status === 404) return "not_found";
|
|
1759
1781
|
if (status >= 500) return "server";
|
|
1760
1782
|
return "client";
|
|
@@ -1928,6 +1950,158 @@ function withLeadingSystemPrompt(prepared) {
|
|
|
1928
1950
|
}, ...messages];
|
|
1929
1951
|
return JSON.stringify(obj);
|
|
1930
1952
|
}
|
|
1953
|
+
/**
|
|
1954
|
+
* System prompts the host has already refused at its channel check.
|
|
1955
|
+
*
|
|
1956
|
+
* WorkBuddy's prompt screen reads system and assistant roles, not user turns, and
|
|
1957
|
+
* it matches more than one client's wording: the DSH opening line, the DSH GUI
|
|
1958
|
+
* pair, and several lines shared with other agent harnesses. A fixed rewrite list
|
|
1959
|
+
* is therefore always one upstream change behind. The first turn that is refused
|
|
1960
|
+
* pays one 400, its system prompt is folded into the first user message, and the
|
|
1961
|
+
* same prompt is folded before sending from then on. Bounded so a process that
|
|
1962
|
+
* sees many one-off prompts keeps only recent ones.
|
|
1963
|
+
*/
|
|
1964
|
+
const FOLDED_PROMPTS_MAX = 32;
|
|
1965
|
+
const foldedPrompts = /* @__PURE__ */ new Set();
|
|
1966
|
+
/** The fingerprint of every system message in a prepared body, if it has one. */
|
|
1967
|
+
function systemPromptFingerprint(prepared) {
|
|
1968
|
+
let body;
|
|
1969
|
+
try {
|
|
1970
|
+
body = JSON.parse(prepared);
|
|
1971
|
+
} catch {
|
|
1972
|
+
return;
|
|
1973
|
+
}
|
|
1974
|
+
const messages = body?.messages;
|
|
1975
|
+
if (!Array.isArray(messages)) return void 0;
|
|
1976
|
+
const texts = [];
|
|
1977
|
+
for (const value of messages) {
|
|
1978
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
|
|
1979
|
+
const message = value;
|
|
1980
|
+
if (message["role"] !== "system" && message["role"] !== "developer") continue;
|
|
1981
|
+
texts.push(contentText(message["content"]));
|
|
1982
|
+
}
|
|
1983
|
+
if (texts.length === 0) return void 0;
|
|
1984
|
+
return createHash("sha256").update(texts.join("\0")).digest("hex");
|
|
1985
|
+
}
|
|
1986
|
+
/** The text parts of a message content value, joined for the fingerprint and fold. */
|
|
1987
|
+
function contentText(content) {
|
|
1988
|
+
if (typeof content === "string") return content;
|
|
1989
|
+
if (!Array.isArray(content)) return "";
|
|
1990
|
+
const parts = [];
|
|
1991
|
+
for (const part of content) if (typeof part === "string") parts.push(part);
|
|
1992
|
+
else if (typeof part === "object" && part !== null && typeof part["text"] === "string") parts.push(part["text"]);
|
|
1993
|
+
return parts.join("\n");
|
|
1994
|
+
}
|
|
1995
|
+
/**
|
|
1996
|
+
* Move every system message into the first user message, and take the client
|
|
1997
|
+
* name out of assistant turns.
|
|
1998
|
+
*
|
|
1999
|
+
* The host accepts the same instructions in a user turn; a system turn is what
|
|
2000
|
+
* its channel check inspects. Assistant turns are inspected too, so a reply that
|
|
2001
|
+
* quoted the client name would fail the next request; that copy is renamed. A
|
|
2002
|
+
* neutral system message stays first so a gateway that insists on one still sees
|
|
2003
|
+
* it. Returns undefined when there is nothing to move or rename, which is also
|
|
2004
|
+
* what keeps an empty system message from looping.
|
|
2005
|
+
*/
|
|
2006
|
+
function foldSystemIntoUser(prepared) {
|
|
2007
|
+
let body;
|
|
2008
|
+
try {
|
|
2009
|
+
body = JSON.parse(prepared);
|
|
2010
|
+
} catch {
|
|
2011
|
+
return;
|
|
2012
|
+
}
|
|
2013
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) return void 0;
|
|
2014
|
+
const obj = body;
|
|
2015
|
+
const messages = obj["messages"];
|
|
2016
|
+
if (!Array.isArray(messages)) return void 0;
|
|
2017
|
+
const prompts = [];
|
|
2018
|
+
const rest = [];
|
|
2019
|
+
let renamed = false;
|
|
2020
|
+
for (const value of messages) {
|
|
2021
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
2022
|
+
const message = value;
|
|
2023
|
+
if (message["role"] === "system" || message["role"] === "developer") {
|
|
2024
|
+
const text = contentText(message["content"]);
|
|
2025
|
+
if (text.trim() !== "") prompts.push(text);
|
|
2026
|
+
continue;
|
|
2027
|
+
}
|
|
2028
|
+
if (message["role"] === "assistant" && "content" in message) {
|
|
2029
|
+
const content = renameInContent(message["content"]);
|
|
2030
|
+
if (content !== message["content"]) {
|
|
2031
|
+
renamed = true;
|
|
2032
|
+
rest.push({
|
|
2033
|
+
...message,
|
|
2034
|
+
content
|
|
2035
|
+
});
|
|
2036
|
+
continue;
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
rest.push(value);
|
|
2041
|
+
}
|
|
2042
|
+
if (prompts.length === 0 && !renamed) return void 0;
|
|
2043
|
+
if (prompts.length === 0) {
|
|
2044
|
+
obj["messages"] = rest;
|
|
2045
|
+
return JSON.stringify(obj);
|
|
2046
|
+
}
|
|
2047
|
+
const instructions = prompts.join("\n\n");
|
|
2048
|
+
const firstUser = rest.findIndex((value) => typeof value === "object" && value !== null && !Array.isArray(value) && value["role"] === "user");
|
|
2049
|
+
if (firstUser === -1) rest.unshift({
|
|
2050
|
+
role: "user",
|
|
2051
|
+
content: instructions
|
|
2052
|
+
});
|
|
2053
|
+
else {
|
|
2054
|
+
const message = rest[firstUser];
|
|
2055
|
+
const content = message["content"];
|
|
2056
|
+
rest[firstUser] = {
|
|
2057
|
+
...message,
|
|
2058
|
+
content: typeof content === "string" ? `${instructions}\n\n${content}` : [{
|
|
2059
|
+
type: "text",
|
|
2060
|
+
text: instructions
|
|
2061
|
+
}, ...Array.isArray(content) ? content : []]
|
|
2062
|
+
};
|
|
2063
|
+
}
|
|
2064
|
+
obj["messages"] = [{
|
|
2065
|
+
role: "system",
|
|
2066
|
+
content: ""
|
|
2067
|
+
}, ...rest];
|
|
2068
|
+
return JSON.stringify(obj);
|
|
2069
|
+
}
|
|
2070
|
+
/**
|
|
2071
|
+
* Rename the client in one message content, preserving every other field.
|
|
2072
|
+
*
|
|
2073
|
+
* Matched case-insensitively because the host's screen is, and only the product
|
|
2074
|
+
* name is replaced: the rest of the sentence still reads naturally, and the
|
|
2075
|
+
* model sees the same instructions.
|
|
2076
|
+
*/
|
|
2077
|
+
function renameInContent(content) {
|
|
2078
|
+
const rename = (text) => text.replace(/DeepSeek Harness/gi, "DeepSeek");
|
|
2079
|
+
if (typeof content === "string") return rename(content);
|
|
2080
|
+
if (!Array.isArray(content)) return content;
|
|
2081
|
+
return content.map((part) => {
|
|
2082
|
+
if (typeof part === "string") return rename(part);
|
|
2083
|
+
if (typeof part !== "object" || part === null || Array.isArray(part)) return part;
|
|
2084
|
+
const record = part;
|
|
2085
|
+
if (typeof record["text"] !== "string") return part;
|
|
2086
|
+
const text = rename(record["text"]);
|
|
2087
|
+
return text === record["text"] ? part : {
|
|
2088
|
+
...record,
|
|
2089
|
+
text
|
|
2090
|
+
};
|
|
2091
|
+
});
|
|
2092
|
+
}
|
|
2093
|
+
function rememberFoldedPrompt(fingerprint) {
|
|
2094
|
+
if (foldedPrompts.has(fingerprint)) return;
|
|
2095
|
+
if (foldedPrompts.size >= FOLDED_PROMPTS_MAX) {
|
|
2096
|
+
const oldest = foldedPrompts.values().next().value;
|
|
2097
|
+
if (oldest !== void 0) foldedPrompts.delete(oldest);
|
|
2098
|
+
}
|
|
2099
|
+
foldedPrompts.add(fingerprint);
|
|
2100
|
+
}
|
|
2101
|
+
/** Whether a 400 body is the host's prompt screen rather than a bad request. */
|
|
2102
|
+
function isChannelCheckText(text) {
|
|
2103
|
+
return CHANNEL_CHECK_PATTERN.test(text);
|
|
2104
|
+
}
|
|
1931
2105
|
var WorkBuddyUpstreamClient = class {
|
|
1932
2106
|
fetchImpl;
|
|
1933
2107
|
constructor(options = {}) {
|
|
@@ -1954,6 +2128,10 @@ var WorkBuddyUpstreamClient = class {
|
|
|
1954
2128
|
if (typeof value !== "object" || value === null || Array.isArray(value)) continue;
|
|
1955
2129
|
const message = value;
|
|
1956
2130
|
if (message["role"] === "developer") message["role"] = "system";
|
|
2131
|
+
if (message["role"] === "assistant" && "content" in message) {
|
|
2132
|
+
const content = renameInContent(message["content"]);
|
|
2133
|
+
if (content !== message["content"]) message["content"] = content;
|
|
2134
|
+
}
|
|
1957
2135
|
}
|
|
1958
2136
|
const choice = obj["tool_choice"];
|
|
1959
2137
|
if (typeof choice === "string") {
|
|
@@ -1981,58 +2159,104 @@ var WorkBuddyUpstreamClient = class {
|
|
|
1981
2159
|
}
|
|
1982
2160
|
/** Forward one chat completion. Never throws for upstream failures. */
|
|
1983
2161
|
async chatStream(credential, prepared, signal, timeouts) {
|
|
1984
|
-
|
|
1985
|
-
const
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
}
|
|
2162
|
+
const fingerprint = systemPromptFingerprint(prepared);
|
|
2163
|
+
const region = regionOf(credential.domain);
|
|
2164
|
+
let body = region === "global" ? withLeadingSystemPrompt(prepared) : prepared;
|
|
2165
|
+
const cacheKey = fingerprint === void 0 ? void 0 : `${region}:${fingerprint}`;
|
|
2166
|
+
if (cacheKey !== void 0 && foldedPrompts.has(cacheKey)) body = foldSystemIntoUser(body) ?? body;
|
|
2167
|
+
let rememberOnSuccess;
|
|
2168
|
+
for (let attempt = 0;; attempt++) {
|
|
2169
|
+
let response;
|
|
2170
|
+
const deadline = headersDeadline(signal, timeouts?.headersMs ?? STREAM_HEADERS_TIMEOUT_MS);
|
|
2171
|
+
try {
|
|
2172
|
+
response = await this.fetchImpl(`${chatBase(credential)}/v2/chat/completions`, {
|
|
2173
|
+
redirect: "error",
|
|
2174
|
+
method: "POST",
|
|
2175
|
+
headers: chatHeaders(credential),
|
|
2176
|
+
body,
|
|
2177
|
+
signal: deadline.signal
|
|
2178
|
+
});
|
|
2179
|
+
} catch (error) {
|
|
2180
|
+
if (signal?.aborted === true) return {
|
|
2181
|
+
ok: false,
|
|
2182
|
+
kind: "aborted",
|
|
2183
|
+
status: 0,
|
|
2184
|
+
message: "cancelled by the caller"
|
|
2185
|
+
};
|
|
2186
|
+
return {
|
|
2187
|
+
ok: false,
|
|
2188
|
+
kind: "transport",
|
|
2189
|
+
status: 0,
|
|
2190
|
+
message: `transport error: ${String(error)}`
|
|
2191
|
+
};
|
|
2192
|
+
} finally {
|
|
2193
|
+
deadline.arrived();
|
|
2194
|
+
}
|
|
2195
|
+
if (response.ok) {
|
|
2196
|
+
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
|
|
2197
|
+
const declaredLength = Number(response.headers.get("content-length") ?? "");
|
|
2198
|
+
const smallDeclaredBody = Number.isFinite(declaredLength) && declaredLength > 0 && declaredLength <= ERROR_BODY_LIMIT;
|
|
2199
|
+
if (contentType.includes("application/json") || smallDeclaredBody && !contentType.includes("text/event-stream")) {
|
|
2200
|
+
const text = await readErrorBody(response, ERROR_BODY_LIMIT, signal);
|
|
2201
|
+
if (attempt === 0 && isChannelCheckText(text)) {
|
|
2202
|
+
const folded = foldSystemIntoUser(body);
|
|
2203
|
+
if (folded !== void 0) {
|
|
2204
|
+
rememberOnSuccess = cacheKey;
|
|
2205
|
+
body = folded;
|
|
2206
|
+
continue;
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
if (rememberOnSuccess !== void 0 && !isChannelCheckText(text)) rememberFoldedPrompt(rememberOnSuccess);
|
|
2210
|
+
const envelopeResponse = new Response(text, {
|
|
2211
|
+
status: response.status,
|
|
2212
|
+
headers: response.headers
|
|
2213
|
+
});
|
|
2214
|
+
const envelopeBody = envelopeResponse.body;
|
|
2215
|
+
if (envelopeBody === null) return {
|
|
2216
|
+
ok: false,
|
|
2217
|
+
kind: "server",
|
|
2218
|
+
status: 502,
|
|
2219
|
+
message: "upstream returned 200 without a body"
|
|
2220
|
+
};
|
|
2221
|
+
return {
|
|
2222
|
+
ok: true,
|
|
2223
|
+
response: withRelayStream(envelopeResponse, envelopeBody)
|
|
2224
|
+
};
|
|
2225
|
+
}
|
|
2226
|
+
if (rememberOnSuccess !== void 0) rememberFoldedPrompt(rememberOnSuccess);
|
|
2227
|
+
if (response.body === null) return {
|
|
2228
|
+
ok: false,
|
|
2229
|
+
kind: "server",
|
|
2230
|
+
status: 502,
|
|
2231
|
+
message: "upstream returned 200 without a stream"
|
|
2232
|
+
};
|
|
2233
|
+
const relayed = withIdleWatchdog(response.body, timeouts?.idleMs, signal);
|
|
2234
|
+
return {
|
|
2235
|
+
ok: true,
|
|
2236
|
+
response: withRelayStream(new Response(relayed, {
|
|
2237
|
+
status: response.status,
|
|
2238
|
+
headers: response.headers
|
|
2239
|
+
}), relayed)
|
|
2240
|
+
};
|
|
2241
|
+
}
|
|
2242
|
+
const text = await readErrorBody(response, ERROR_BODY_LIMIT, signal);
|
|
2243
|
+
const retryAfter = retryAfterSeconds(response.headers);
|
|
2244
|
+
if (attempt === 0 && response.status === 400 && isChannelCheckText(text)) {
|
|
2245
|
+
const folded = foldSystemIntoUser(body);
|
|
2246
|
+
if (folded !== void 0) {
|
|
2247
|
+
rememberOnSuccess = cacheKey;
|
|
2248
|
+
body = folded;
|
|
2249
|
+
continue;
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2002
2252
|
return {
|
|
2003
2253
|
ok: false,
|
|
2004
|
-
kind:
|
|
2005
|
-
status:
|
|
2006
|
-
message:
|
|
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)
|
|
2254
|
+
kind: classifyUpstreamError(response.status, text),
|
|
2255
|
+
status: response.status,
|
|
2256
|
+
message: isGatewayHtmlRejection(response.status, text) ? gatewayRejectionText(response.status) : text,
|
|
2257
|
+
...retryAfter === void 0 ? {} : { retryAfter }
|
|
2025
2258
|
};
|
|
2026
2259
|
}
|
|
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
2260
|
}
|
|
2037
2261
|
/** POST the token-refresh endpoint; the caller merges the outcome. */
|
|
2038
2262
|
async refreshToken(credential) {
|
|
@@ -2058,8 +2282,9 @@ var WorkBuddyUpstreamClient = class {
|
|
|
2058
2282
|
*
|
|
2059
2283
|
* The two gateways are read differently, because they answer differently:
|
|
2060
2284
|
*
|
|
2061
|
-
* - **CN** serves the roster at `/v2/enterprises/personal/models
|
|
2062
|
-
* the
|
|
2285
|
+
* - **CN** serves the roster at `/v2/enterprises/personal/models`. Like the
|
|
2286
|
+
* desktop process that calls it directly, it expects the desktop client
|
|
2287
|
+
* spelling; this is not the chat endpoint's three-segment UA.
|
|
2063
2288
|
* - **Global** serves it as part of the product config at `/v3/config`, and
|
|
2064
2289
|
* only to the DESKTOP client channel. Asking the global host with the CLI UA
|
|
2065
2290
|
* yields a truncated roster, and the CN path answers HTTP 500 there — which
|
|
@@ -2080,7 +2305,7 @@ var WorkBuddyUpstreamClient = class {
|
|
|
2080
2305
|
"X-Requested-With": "XMLHttpRequest",
|
|
2081
2306
|
"X-CodeBuddy-Request": "1",
|
|
2082
2307
|
"Connection": "close",
|
|
2083
|
-
"User-Agent":
|
|
2308
|
+
"User-Agent": GLOBAL_DESKTOP_UA
|
|
2084
2309
|
} : {
|
|
2085
2310
|
...commonHeaders(credential),
|
|
2086
2311
|
"Authorization": `Bearer ${credential.accessToken}`,
|
|
@@ -2609,6 +2834,18 @@ function openEncryptedField(field, key) {
|
|
|
2609
2834
|
function cleanIconPath(raw) {
|
|
2610
2835
|
return raw.replace(/^"/u, "").replace(/",-?\d+$/u, "").replace(/,-?\d+$/u, "").trim();
|
|
2611
2836
|
}
|
|
2837
|
+
/**
|
|
2838
|
+
* Whether a Windows path names a local file rather than a network share.
|
|
2839
|
+
*
|
|
2840
|
+
* The registry scan reads values any process running as the user can write. A
|
|
2841
|
+
* `DisplayIcon` naming `\\host\share\x.exe` would make PowerShell's own path
|
|
2842
|
+
* check authenticate to that host before any signature was read, leaking the
|
|
2843
|
+
* user's NTLM response. Only absolute drive paths are considered, and every
|
|
2844
|
+
* stat and spawn goes through the same filter.
|
|
2845
|
+
*/
|
|
2846
|
+
function localWindowsPath(candidate) {
|
|
2847
|
+
return /^[A-Za-z]:[\\/]/u.test(candidate);
|
|
2848
|
+
}
|
|
2612
2849
|
function windowsRegistryAppPaths() {
|
|
2613
2850
|
if (process.platform !== "win32") return [];
|
|
2614
2851
|
const cached = registryAppPaths;
|
|
@@ -2679,21 +2916,20 @@ function scanInterpreter(env) {
|
|
|
2679
2916
|
return join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
2680
2917
|
}
|
|
2681
2918
|
/**
|
|
2682
|
-
* Every path an uninstall key names for a WorkBuddy-family install
|
|
2683
|
-
* the signature PowerShell found on it.
|
|
2919
|
+
* Every path an uninstall key names for a WorkBuddy-family install.
|
|
2684
2920
|
*
|
|
2685
2921
|
* The scan reads `DisplayName`, `DisplayIcon` and `InstallLocation` out of the
|
|
2686
2922
|
* user's own uninstall keys, which means any process running as the user can add
|
|
2687
|
-
* one.
|
|
2688
|
-
*
|
|
2689
|
-
*
|
|
2690
|
-
*
|
|
2923
|
+
* one. It only enumerates here: a path is filtered to a local drive, stat'ed,
|
|
2924
|
+
* and signature-checked in Node before anything is spawned. Doing the stat or
|
|
2925
|
+
* signature read in PowerShell would touch a planted UNC path first and leak an
|
|
2926
|
+
* NTLM response to the host it names.
|
|
2691
2927
|
*
|
|
2692
|
-
* PowerShell does the part only it can do: enumerate
|
|
2693
|
-
* and quotes off `DisplayIcon
|
|
2694
|
-
*
|
|
2695
|
-
*
|
|
2696
|
-
*
|
|
2928
|
+
* PowerShell does the part only it can do: enumerate the keys and clean the
|
|
2929
|
+
* resource index and quotes off `DisplayIcon`. The decision is
|
|
2930
|
+
* {@link signatureAccepts}'s, in Node, because that is where it can be tested
|
|
2931
|
+
* without a registry to plant a key in, and it is handed a module path 5.1 can
|
|
2932
|
+
* actually load, because the host's is not always one.
|
|
2697
2933
|
*/
|
|
2698
2934
|
function readRegistryAppPaths() {
|
|
2699
2935
|
const script = [
|
|
@@ -2708,23 +2944,19 @@ function readRegistryAppPaths() {
|
|
|
2708
2944
|
" return $v",
|
|
2709
2945
|
"}",
|
|
2710
2946
|
"$roots=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*')",
|
|
2711
|
-
"foreach($r in $roots){",
|
|
2947
|
+
"$out = foreach($r in $roots){",
|
|
2712
2948
|
" Get-ItemProperty -Path $r | ForEach-Object {",
|
|
2713
2949
|
" $dn=[string]$_.DisplayName; $di=[string]$_.DisplayIcon; $il=[string]$_.InstallLocation",
|
|
2714
2950
|
" if($dn -match 'WorkBuddy|CodeBuddy' -or $di -match 'WorkBuddy|CodeBuddy'){",
|
|
2715
2951
|
" foreach($raw in @($di,$il)){",
|
|
2716
2952
|
" $p = Clean $raw",
|
|
2717
2953
|
" if($p -eq ''){ continue }",
|
|
2718
|
-
"
|
|
2719
|
-
" $s = $null",
|
|
2720
|
-
" try { $s = Get-AuthenticodeSignature -LiteralPath $p } catch { $s = $null }",
|
|
2721
|
-
" $st = if($s -ne $null){ [string]$s.Status } else { \"\" }",
|
|
2722
|
-
" $sj = if($s -ne $null -and $s.SignerCertificate -ne $null){ [string]$s.SignerCertificate.Subject } else { \"\" }",
|
|
2723
|
-
" Write-Output ($p + [char]9 + $st + [char]9 + $sj)",
|
|
2954
|
+
" Write-Output $p",
|
|
2724
2955
|
" }",
|
|
2725
2956
|
" }",
|
|
2726
2957
|
" }",
|
|
2727
|
-
"}"
|
|
2958
|
+
"}",
|
|
2959
|
+
"ConvertTo-Json -InputObject @($out) -Compress"
|
|
2728
2960
|
].join("\n");
|
|
2729
2961
|
let stdout;
|
|
2730
2962
|
const interpreter = scanInterpreter(process.env);
|
|
@@ -2747,12 +2979,18 @@ function readRegistryAppPaths() {
|
|
|
2747
2979
|
} catch {
|
|
2748
2980
|
return [];
|
|
2749
2981
|
}
|
|
2982
|
+
let parsed;
|
|
2983
|
+
try {
|
|
2984
|
+
parsed = JSON.parse(stdout);
|
|
2985
|
+
} catch {
|
|
2986
|
+
return [];
|
|
2987
|
+
}
|
|
2988
|
+
const entries = Array.isArray(parsed) ? parsed : [parsed];
|
|
2750
2989
|
const out = [];
|
|
2751
|
-
for (const
|
|
2752
|
-
|
|
2753
|
-
const cleaned =
|
|
2754
|
-
if (cleaned === "") continue;
|
|
2755
|
-
if (!signatureAccepts(status, signer)) continue;
|
|
2990
|
+
for (const entry of entries) {
|
|
2991
|
+
if (typeof entry !== "string") continue;
|
|
2992
|
+
const cleaned = cleanIconPath(entry);
|
|
2993
|
+
if (cleaned === "" || !localWindowsPath(cleaned)) continue;
|
|
2756
2994
|
out.push(cleaned);
|
|
2757
2995
|
}
|
|
2758
2996
|
return out;
|
|
@@ -2764,11 +3002,12 @@ function readRegistryAppPaths() {
|
|
|
2764
3002
|
* PowerShell half is not unit-testable, and this half is where the decision
|
|
2765
3003
|
* actually lives.
|
|
2766
3004
|
*
|
|
2767
|
-
* `Valid` means the chain resolved to a trusted root
|
|
2768
|
-
* the
|
|
2769
|
-
*
|
|
2770
|
-
*
|
|
2771
|
-
*
|
|
3005
|
+
* `Valid` means the chain resolved to a trusted root. A user process cannot
|
|
3006
|
+
* forge the vendor's signature, but it can trust a certificate of its own in the
|
|
3007
|
+
* current user's root store without elevation, so this check raises the bar
|
|
3008
|
+
* rather than proving the file is the vendor's. It still rejects an unsigned
|
|
3009
|
+
* planted executable, and every cached registry path is checked again before it
|
|
3010
|
+
* is run.
|
|
2772
3011
|
*
|
|
2773
3012
|
* The publisher is deliberately not pinned. The plugin is a third-party build and
|
|
2774
3013
|
* the vendor can change its signing certificate; a pinned name would turn that
|
|
@@ -2782,17 +3021,100 @@ function readRegistryAppPaths() {
|
|
|
2782
3021
|
function signatureAccepts(status, signer) {
|
|
2783
3022
|
return status === "Valid" && signer !== void 0 && signer.trim() !== "";
|
|
2784
3023
|
}
|
|
3024
|
+
/** Why the last signature scan could not produce an answer, if it could not. */
|
|
3025
|
+
let signatureScanFailure = "";
|
|
3026
|
+
/**
|
|
3027
|
+
* The candidates whose Authenticode signature is valid.
|
|
3028
|
+
*
|
|
3029
|
+
* The standard install roots and the environment override were trusted by path
|
|
3030
|
+
* alone, while only the registry fallback checked a signature. A process running
|
|
3031
|
+
* as the user can write `%LOCALAPPDATA%\\Programs\\WorkBuddy\\WorkBuddy.exe`; when
|
|
3032
|
+
* the host runs elevated, spawning that file would hand it the plugin's whole
|
|
3033
|
+
* environment and every WorkBuddy token. Every path is checked here, and the
|
|
3034
|
+
* registry result is passed through the same check before it is spawned.
|
|
3035
|
+
*/
|
|
3036
|
+
async function signedExecutables(candidates) {
|
|
3037
|
+
if (process.platform !== "win32" || candidates.length === 0) return candidates;
|
|
3038
|
+
signatureScanFailure = "";
|
|
3039
|
+
const interpreter = scanInterpreter(process.env);
|
|
3040
|
+
if (interpreter === void 0) {
|
|
3041
|
+
signatureScanFailure = "the signature check could not run: Windows PowerShell was not found";
|
|
3042
|
+
return [];
|
|
3043
|
+
}
|
|
3044
|
+
const script = [
|
|
3045
|
+
"$ErrorActionPreference='SilentlyContinue'",
|
|
3046
|
+
"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}",
|
|
3047
|
+
`$paths = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(JSON.stringify(candidates), "utf8").toString("base64")}')) | ConvertFrom-Json`,
|
|
3048
|
+
"$out = foreach ($p in @($paths)) {",
|
|
3049
|
+
" if ([string]::IsNullOrWhiteSpace([string]$p)) { continue }",
|
|
3050
|
+
" $s = $null",
|
|
3051
|
+
" try { $s = Get-AuthenticodeSignature -LiteralPath ([string]$p) } catch { $s = $null }",
|
|
3052
|
+
" [pscustomobject]@{",
|
|
3053
|
+
" path = [string]$p",
|
|
3054
|
+
" status = if ($s -ne $null) { [string]$s.Status } else { \"\" }",
|
|
3055
|
+
" signer = if ($s -ne $null -and $s.SignerCertificate -ne $null) { [string]$s.SignerCertificate.Subject } else { \"\" }",
|
|
3056
|
+
" }",
|
|
3057
|
+
"}",
|
|
3058
|
+
"ConvertTo-Json -InputObject @($out) -Compress"
|
|
3059
|
+
].join("\n");
|
|
3060
|
+
let stdout;
|
|
3061
|
+
try {
|
|
3062
|
+
stdout = await new Promise((resolve, reject) => {
|
|
3063
|
+
execFile(interpreter, [
|
|
3064
|
+
"-NoProfile",
|
|
3065
|
+
"-NonInteractive",
|
|
3066
|
+
"-ExecutionPolicy",
|
|
3067
|
+
"Bypass",
|
|
3068
|
+
"-Command",
|
|
3069
|
+
script
|
|
3070
|
+
], {
|
|
3071
|
+
encoding: "utf8",
|
|
3072
|
+
timeout: 2e4,
|
|
3073
|
+
windowsHide: true,
|
|
3074
|
+
maxBuffer: 8388608,
|
|
3075
|
+
env: signatureScanEnv()
|
|
3076
|
+
}, (error, output) => {
|
|
3077
|
+
if (error !== null) reject(error);
|
|
3078
|
+
else resolve(output);
|
|
3079
|
+
});
|
|
3080
|
+
});
|
|
3081
|
+
} catch {
|
|
3082
|
+
signatureScanFailure = "the signature check could not run";
|
|
3083
|
+
return [];
|
|
3084
|
+
}
|
|
3085
|
+
let parsed;
|
|
3086
|
+
try {
|
|
3087
|
+
parsed = JSON.parse(stdout);
|
|
3088
|
+
} catch {
|
|
3089
|
+
signatureScanFailure = "the signature check returned no readable answer";
|
|
3090
|
+
return [];
|
|
3091
|
+
}
|
|
3092
|
+
const entries = Array.isArray(parsed) ? parsed : [parsed];
|
|
3093
|
+
const accepted = [];
|
|
3094
|
+
for (const entry of entries) {
|
|
3095
|
+
if (entry === null || typeof entry !== "object") continue;
|
|
3096
|
+
const record = entry;
|
|
3097
|
+
const file = record["path"];
|
|
3098
|
+
const status = record["status"];
|
|
3099
|
+
const signer = record["signer"];
|
|
3100
|
+
if (typeof file !== "string" || file === "") continue;
|
|
3101
|
+
if (!signatureAccepts(typeof status === "string" ? status : void 0, typeof signer === "string" ? signer : void 0)) continue;
|
|
3102
|
+
accepted.push(file);
|
|
3103
|
+
}
|
|
3104
|
+
return accepted;
|
|
3105
|
+
}
|
|
2785
3106
|
function statExecutables(candidates) {
|
|
2786
3107
|
const files = [];
|
|
2787
3108
|
for (const candidate of candidates) {
|
|
2788
3109
|
if (candidate === "") continue;
|
|
3110
|
+
if (process.platform === "win32" && !localWindowsPath(candidate)) continue;
|
|
2789
3111
|
try {
|
|
2790
3112
|
if (statSync(candidate, { throwIfNoEntry: false })?.isFile() === true) files.push(candidate);
|
|
2791
3113
|
} catch {}
|
|
2792
3114
|
}
|
|
2793
3115
|
return files;
|
|
2794
3116
|
}
|
|
2795
|
-
function executableCandidates(env = process.env) {
|
|
3117
|
+
async function executableCandidates(env = process.env) {
|
|
2796
3118
|
const override = env[WORKBUDDY_APP_EXECUTABLE_ENV]?.trim();
|
|
2797
3119
|
const known = override === void 0 ? [] : [override];
|
|
2798
3120
|
if (process.platform === "win32") {
|
|
@@ -2813,9 +3135,9 @@ function executableCandidates(env = process.env) {
|
|
|
2813
3135
|
const home = homedir();
|
|
2814
3136
|
for (const bundle of ["WorkBuddy.app", "WorkBuddy AI.app"]) for (const base of ["/Applications", join(home, "Applications")]) known.push(join(base, bundle, "Contents", "MacOS", "Electron"));
|
|
2815
3137
|
}
|
|
2816
|
-
const standard = statExecutables(known);
|
|
3138
|
+
const standard = await signedExecutables(statExecutables(known));
|
|
2817
3139
|
if (standard.length > 0 || process.platform !== "win32") return standard;
|
|
2818
|
-
return statExecutables(windowsRegistryAppPaths());
|
|
3140
|
+
return signedExecutables(statExecutables(windowsRegistryAppPaths()));
|
|
2819
3141
|
}
|
|
2820
3142
|
function fetchAtRestKeyPayload(executable) {
|
|
2821
3143
|
return new Promise((resolve, reject) => {
|
|
@@ -2874,10 +3196,10 @@ function ensureAtRestKeys() {
|
|
|
2874
3196
|
if (atRestKeyById.size > 0) return Promise.resolve();
|
|
2875
3197
|
if (Date.now() - lastKeyFailureAtMs < KEY_FAILURE_BACKOFF_MS) return Promise.resolve();
|
|
2876
3198
|
inflightKeys ??= (async () => {
|
|
2877
|
-
const candidates = executableCandidates();
|
|
3199
|
+
const candidates = await executableCandidates();
|
|
2878
3200
|
if (candidates.length === 0) {
|
|
2879
3201
|
lastKeyFailureAtMs = Date.now();
|
|
2880
|
-
lastKeyFailure = "no WorkBuddy executable found in the standard install roots";
|
|
3202
|
+
lastKeyFailure = process.platform === "win32" ? signatureScanFailure !== "" ? signatureScanFailure : "no WorkBuddy executable with a valid signature was found" : "no WorkBuddy executable found in the standard install roots";
|
|
2881
3203
|
return;
|
|
2882
3204
|
}
|
|
2883
3205
|
let anySuccess = false;
|
|
@@ -3643,16 +3965,17 @@ async function readArchivedCredentials(file) {
|
|
|
3643
3965
|
const record = entry;
|
|
3644
3966
|
if (typeof record["id"] !== "string" || record["id"] === "") continue;
|
|
3645
3967
|
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;
|
|
3968
|
+
const expiresAt = typeof record["expiresAtMs"] === "number" ? expiryToMs(record["expiresAtMs"]) : 0;
|
|
3969
|
+
const refreshExpiresAt = typeof record["refreshExpiresAtMs"] === "number" ? expiryToMs(record["refreshExpiresAtMs"]) : 0;
|
|
3970
|
+
const lastRefreshAt = typeof record["lastRefreshAtMs"] === "number" ? expiryToMs(record["lastRefreshAtMs"]) : 0;
|
|
3648
3971
|
const lastUsable = Math.max(expiresAt, refreshExpiresAt);
|
|
3649
3972
|
if (lastUsable > 0 && lastUsable < horizon) continue;
|
|
3650
3973
|
stored.set(record["id"], {
|
|
3651
3974
|
accessToken: record["accessToken"],
|
|
3652
3975
|
refreshToken: typeof record["refreshToken"] === "string" ? record["refreshToken"] : "",
|
|
3653
|
-
expiresAtMs:
|
|
3654
|
-
...
|
|
3655
|
-
...
|
|
3976
|
+
expiresAtMs: expiresAt,
|
|
3977
|
+
...refreshExpiresAt === 0 ? {} : { refreshExpiresAtMs: refreshExpiresAt },
|
|
3978
|
+
...lastRefreshAt === 0 ? {} : { lastRefreshAtMs: lastRefreshAt },
|
|
3656
3979
|
...typeof record["nickname"] !== "string" || record["nickname"] === "" ? {} : { nickname: record["nickname"] },
|
|
3657
3980
|
...typeof record["uin"] !== "string" || record["uin"] === "" ? {} : { uin: record["uin"] },
|
|
3658
3981
|
...typeof record["uid"] !== "string" || record["uid"] === "" ? {} : { uid: record["uid"] },
|
|
@@ -3880,7 +4203,7 @@ var WorkBuddyAccountPool = class {
|
|
|
3880
4203
|
if (hold.reason !== "spent" || total <= 0) return;
|
|
3881
4204
|
this.heldIds.delete(accountId);
|
|
3882
4205
|
if (account.cooldownUntilMs > Date.now() && account.cooldownUntilMs <= hold.until) account.cooldownUntilMs = 0;
|
|
3883
|
-
this.logger?.info?.(`${LOG_PREFIX}: ${account.label} has credits again; releasing the hold`);
|
|
4206
|
+
this.logger?.info?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} has credits again; releasing the hold`);
|
|
3884
4207
|
}
|
|
3885
4208
|
/** True when a known balance has reached the floor set for this account. */
|
|
3886
4209
|
reserveHolds(accountId) {
|
|
@@ -4128,7 +4451,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4128
4451
|
lastRefreshAtMs: credential.lastRefreshAtMs ?? 0
|
|
4129
4452
|
});
|
|
4130
4453
|
} catch (error) {
|
|
4131
|
-
this.logger?.warn?.(`${LOG_PREFIX}: could not take over ${accountLabel(credential)}: ${String(error)}`);
|
|
4454
|
+
this.logger?.warn?.(`${LOG_PREFIX}: could not take over ${accountLogTag(accountLabel(credential))}: ${String(error)}`);
|
|
4132
4455
|
continue;
|
|
4133
4456
|
}
|
|
4134
4457
|
ownedIds.add(id);
|
|
@@ -4151,7 +4474,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4151
4474
|
try {
|
|
4152
4475
|
await renewOwnSignInFile(credential.sourcePath, credential);
|
|
4153
4476
|
} catch (error) {
|
|
4154
|
-
this.logger?.warn?.(`${LOG_PREFIX}: could not write the renewed token back for ${credential.nickname ?? credential.uid}: ${String(error)}`);
|
|
4477
|
+
this.logger?.warn?.(`${LOG_PREFIX}: could not write the renewed token back for ${accountLogTag(credential.nickname ?? credential.uid)}: ${String(error)}`);
|
|
4155
4478
|
}
|
|
4156
4479
|
return;
|
|
4157
4480
|
}
|
|
@@ -4160,7 +4483,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4160
4483
|
try {
|
|
4161
4484
|
credential.sourcePath = await writeOwnSignIn(directory, ownSignInOf(credential));
|
|
4162
4485
|
} catch (error) {
|
|
4163
|
-
this.logger?.warn?.(`${LOG_PREFIX}: could not keep the renewed token for ${credential.nickname ?? credential.uid}: ${String(error)}`);
|
|
4486
|
+
this.logger?.warn?.(`${LOG_PREFIX}: could not keep the renewed token for ${accountLogTag(credential.nickname ?? credential.uid)}: ${String(error)}`);
|
|
4164
4487
|
}
|
|
4165
4488
|
}
|
|
4166
4489
|
/**
|
|
@@ -4356,7 +4679,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4356
4679
|
if (this.signInRefused(id, account.credential.accessToken)) continue;
|
|
4357
4680
|
this.heldIds.delete(id);
|
|
4358
4681
|
if (account.cooldownUntilMs > 0 && account.cooldownUntilMs <= hold.until) account.cooldownUntilMs = 0;
|
|
4359
|
-
this.logger?.info?.(`${LOG_PREFIX}: ${account.label} has a sign-in the upstream did not refuse; releasing the hold`);
|
|
4682
|
+
this.logger?.info?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} has a sign-in the upstream did not refuse; releasing the hold`);
|
|
4360
4683
|
}
|
|
4361
4684
|
const foundIds = new Set(found.map((credential) => workbuddyAccountId(credential)));
|
|
4362
4685
|
for (const [id, refused] of this.refusedSignIns) {
|
|
@@ -4487,19 +4810,23 @@ var WorkBuddyAccountPool = class {
|
|
|
4487
4810
|
* Scans on first use, and rescans when every known account is cooling down: a
|
|
4488
4811
|
* fresh desktop login is the usual way out of an exhausted pool.
|
|
4489
4812
|
*/
|
|
4490
|
-
async acquire(modelId, region, conversationKey) {
|
|
4813
|
+
async acquire(modelId, region, conversationKey, excludeIds) {
|
|
4814
|
+
const eligibleNow = () => {
|
|
4815
|
+
const list = this.available(Date.now(), modelId, region);
|
|
4816
|
+
return excludeIds === void 0 ? list : list.filter((item) => !excludeIds.has(item.id));
|
|
4817
|
+
};
|
|
4491
4818
|
if (this.accounts.length === 0) await this.scan();
|
|
4492
|
-
let pool =
|
|
4819
|
+
let pool = eligibleNow();
|
|
4493
4820
|
if (pool.length === 0) {
|
|
4494
4821
|
await this.scan();
|
|
4495
|
-
pool =
|
|
4822
|
+
pool = eligibleNow();
|
|
4496
4823
|
}
|
|
4497
4824
|
if (pool.length === 0) return void 0;
|
|
4498
4825
|
const preferredId = this.preferredIds.get(region);
|
|
4499
4826
|
const account = pool.find((item) => item.id === preferredId) ?? this.pick(pool, conversationKey);
|
|
4500
4827
|
if (account === void 0) return void 0;
|
|
4501
4828
|
await this.ensureFresh(account);
|
|
4502
|
-
const eligible =
|
|
4829
|
+
const eligible = eligibleNow();
|
|
4503
4830
|
if (eligible.includes(account)) return account;
|
|
4504
4831
|
const next = eligible.find((item) => item.id === preferredId) ?? this.pick(eligible, conversationKey);
|
|
4505
4832
|
if (next === void 0) return void 0;
|
|
@@ -4548,7 +4875,17 @@ var WorkBuddyAccountPool = class {
|
|
|
4548
4875
|
* token is unchanged, so the caller stops retrying the same dead token.
|
|
4549
4876
|
*/
|
|
4550
4877
|
async refreshAccount(accountId) {
|
|
4551
|
-
return await this.
|
|
4878
|
+
return await this.refreshAccountOutcome(accountId) === "refreshed";
|
|
4879
|
+
}
|
|
4880
|
+
/**
|
|
4881
|
+
* The same refresh, keeping a refusal apart from a failure.
|
|
4882
|
+
*
|
|
4883
|
+
* The caller needs the difference: only the upstream turning the sign-in down
|
|
4884
|
+
* justifies a six-hour hold, while a timeout or an unreachable host says
|
|
4885
|
+
* nothing about the token and must leave the account in rotation.
|
|
4886
|
+
*/
|
|
4887
|
+
async refreshAccountOutcome(accountId) {
|
|
4888
|
+
return await this.refreshForRetry(accountId);
|
|
4552
4889
|
}
|
|
4553
4890
|
/**
|
|
4554
4891
|
* Refresh after a session-dead answer, keeping a refusal apart from a failure.
|
|
@@ -4565,7 +4902,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4565
4902
|
if (account.credential.refreshToken === "") return "refused";
|
|
4566
4903
|
const outcome = await this.ensureFresh(account, true);
|
|
4567
4904
|
if (account.credential.accessToken !== previous) return "refreshed";
|
|
4568
|
-
return outcome === "
|
|
4905
|
+
return outcome === "failed" ? "failed" : "refused";
|
|
4569
4906
|
}
|
|
4570
4907
|
/**
|
|
4571
4908
|
* Hold an account whose sign-in the upstream refuses.
|
|
@@ -4642,7 +4979,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4642
4979
|
if (credential.expiresAtMs > Date.now() + 3e4) return "fresh";
|
|
4643
4980
|
if (!this.noRefreshWarned.has(account.id)) {
|
|
4644
4981
|
this.noRefreshWarned.add(account.id);
|
|
4645
|
-
this.logger?.warn(`${LOG_PREFIX}: ${account.label} token expired with no refresh token; sign in again`);
|
|
4982
|
+
this.logger?.warn(`${LOG_PREFIX}: ${accountLogTag(account.label)} token expired with no refresh token; sign in again`);
|
|
4646
4983
|
}
|
|
4647
4984
|
return "noToken";
|
|
4648
4985
|
}
|
|
@@ -4664,13 +5001,13 @@ var WorkBuddyAccountPool = class {
|
|
|
4664
5001
|
if (sessionHold !== void 0 && sessionHold.reason === "session") {
|
|
4665
5002
|
this.heldIds.delete(account.id);
|
|
4666
5003
|
if (account.cooldownUntilMs > Date.now() && account.cooldownUntilMs <= sessionHold.until) account.cooldownUntilMs = 0;
|
|
4667
|
-
this.logger?.info?.(`${LOG_PREFIX}: ${account.label} refreshed again; releasing the refused sign-in hold`);
|
|
5004
|
+
this.logger?.info?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} refreshed again; releasing the refused sign-in hold`);
|
|
4668
5005
|
}
|
|
4669
|
-
this.logger?.info?.(`${LOG_PREFIX}: refreshed token for ${account.label}`);
|
|
5006
|
+
this.logger?.info?.(`${LOG_PREFIX}: refreshed token for ${accountLogTag(account.label)}`);
|
|
4670
5007
|
return "refreshed";
|
|
4671
5008
|
} catch (error) {
|
|
4672
|
-
if (credential.expiresAtMs > Date.now() + 3e4) this.logger?.warn?.(`${LOG_PREFIX}: token refresh failed but token still valid for ${account.label}`, error);
|
|
4673
|
-
else this.logger?.error?.(`${LOG_PREFIX}: token refresh failed and token expired for ${account.label}`, error);
|
|
5009
|
+
if (credential.expiresAtMs > Date.now() + 3e4) this.logger?.warn?.(`${LOG_PREFIX}: token refresh failed but token still valid for ${accountLogTag(account.label)}`, error);
|
|
5010
|
+
else this.logger?.error?.(`${LOG_PREFIX}: token refresh failed and token expired for ${accountLogTag(account.label)}`, error);
|
|
4674
5011
|
return upstreamErrorKind(error) === "session_dead" ? "refused" : "failed";
|
|
4675
5012
|
}
|
|
4676
5013
|
})();
|
|
@@ -4698,7 +5035,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4698
5035
|
penalize(accountId, resetAtMs, modelId, hold = false) {
|
|
4699
5036
|
const account = this.accounts.find((item) => item.id === accountId);
|
|
4700
5037
|
if (account === void 0) return;
|
|
4701
|
-
account.rateLimitHits += 1;
|
|
5038
|
+
if (hold === false) account.rateLimitHits += 1;
|
|
4702
5039
|
const now = Date.now();
|
|
4703
5040
|
const stated = resetAtMs !== void 0 && resetAtMs > now;
|
|
4704
5041
|
if (hold === false && !stated) {
|
|
@@ -4713,7 +5050,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4713
5050
|
if (modelId !== void 0 && modelId !== "") {
|
|
4714
5051
|
pruneModelCooldowns(account, now);
|
|
4715
5052
|
account.modelCooldowns[modelId] = Math.max(account.modelCooldowns[modelId] ?? 0, until);
|
|
4716
|
-
this.logger?.warn(`${LOG_PREFIX}: ${account.label} rate-limited on model ${modelId}; cooling that model until ${new Date(until).toISOString()}`);
|
|
5053
|
+
this.logger?.warn(`${LOG_PREFIX}: ${accountLogTag(account.label)} rate-limited on model ${modelId}; cooling that model until ${new Date(until).toISOString()}`);
|
|
4717
5054
|
return;
|
|
4718
5055
|
}
|
|
4719
5056
|
account.cooldownUntilMs = Math.max(account.cooldownUntilMs, until);
|
|
@@ -4728,7 +5065,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4728
5065
|
heldSignIns
|
|
4729
5066
|
});
|
|
4730
5067
|
}
|
|
4731
|
-
this.logger?.warn(holdReason !== void 0 ? `${LOG_PREFIX}: account ${account.label} held (${holdReason}); held until ${new Date(until).toISOString()}` : `${LOG_PREFIX}: account ${account.label} rate-limited; cooling until ${new Date(until).toISOString()}`);
|
|
5068
|
+
this.logger?.warn(holdReason !== void 0 ? `${LOG_PREFIX}: account ${accountLogTag(account.label)} held (${holdReason}); held until ${new Date(until).toISOString()}` : `${LOG_PREFIX}: account ${accountLogTag(account.label)} rate-limited; cooling until ${new Date(until).toISOString()}`);
|
|
4732
5069
|
}
|
|
4733
5070
|
/**
|
|
4734
5071
|
* Keep one model out of one account's rotation for a stated window.
|
|
@@ -5142,7 +5479,7 @@ const KIND_STATUS = {
|
|
|
5142
5479
|
soft_rate: 429,
|
|
5143
5480
|
session_dead: 401,
|
|
5144
5481
|
waf_block: 502,
|
|
5145
|
-
not_found:
|
|
5482
|
+
not_found: 404,
|
|
5146
5483
|
server: 502,
|
|
5147
5484
|
client: 400,
|
|
5148
5485
|
model_tier: 400,
|
|
@@ -5160,6 +5497,16 @@ const KIND_STATUS = {
|
|
|
5160
5497
|
*/
|
|
5161
5498
|
const MODEL_TIER_HOLD_MS = 864e5;
|
|
5162
5499
|
/**
|
|
5500
|
+
* How many accounts one request may lose to a transport failure.
|
|
5501
|
+
*
|
|
5502
|
+
* Rotation is still worth one retry: a global pool can hold sign-ins served by
|
|
5503
|
+
* different gateways, so one unreachable host says nothing about the next
|
|
5504
|
+
* account. A host-wide outage, however, would otherwise cost one headers
|
|
5505
|
+
* timeout per sign-in before the client saw an answer, so the second failure
|
|
5506
|
+
* ends the turn.
|
|
5507
|
+
*/
|
|
5508
|
+
const MAX_TRANSPORT_ATTEMPTS = 2;
|
|
5509
|
+
/**
|
|
5163
5510
|
* The business code an account-level 200 envelope carries.
|
|
5164
5511
|
*
|
|
5165
5512
|
* `classifyUpstreamError` only reads codes on the statuses the upstream uses
|
|
@@ -5173,6 +5520,8 @@ function classifyEnvelopeCode(code, text) {
|
|
|
5173
5520
|
if (code === "11140") return "account_restricted";
|
|
5174
5521
|
if (code === "12153") return "session_dead";
|
|
5175
5522
|
if (isHardCreditText(text)) return "hard_credit";
|
|
5523
|
+
const kind = classifyUpstreamError(200, text);
|
|
5524
|
+
return kind === "client" ? void 0 : kind;
|
|
5176
5525
|
}
|
|
5177
5526
|
/** Stable key for one conversation: a hash of its first user message. */
|
|
5178
5527
|
function conversationKeyOf(raw) {
|
|
@@ -5190,6 +5539,7 @@ function conversationKeyOf(raw) {
|
|
|
5190
5539
|
return;
|
|
5191
5540
|
}
|
|
5192
5541
|
}
|
|
5542
|
+
const EMPTY_STREAM_REFUSAL = "workbuddy returned an empty answer stream";
|
|
5193
5543
|
/**
|
|
5194
5544
|
* Read enough of a 200 body to tell an SSE stream from a refusal wearing a 200.
|
|
5195
5545
|
*
|
|
@@ -5230,7 +5580,7 @@ async function peekAnswerHead(reader) {
|
|
|
5230
5580
|
if (trimmed === "" && ended) return {
|
|
5231
5581
|
head,
|
|
5232
5582
|
ended,
|
|
5233
|
-
refusal:
|
|
5583
|
+
refusal: EMPTY_STREAM_REFUSAL
|
|
5234
5584
|
};
|
|
5235
5585
|
if (!jsonLooking) return {
|
|
5236
5586
|
head,
|
|
@@ -5246,6 +5596,7 @@ async function peekAnswerHead(reader) {
|
|
|
5246
5596
|
return {
|
|
5247
5597
|
head,
|
|
5248
5598
|
ended,
|
|
5599
|
+
body: trimmed,
|
|
5249
5600
|
refusal: sentence === "" ? "workbuddy answered 200 with a JSON body where a stream was expected" : `workbuddy answered 200 with ${sentence}`,
|
|
5250
5601
|
...named === "" ? {} : { code: String(code) }
|
|
5251
5602
|
};
|
|
@@ -5253,6 +5604,7 @@ async function peekAnswerHead(reader) {
|
|
|
5253
5604
|
return {
|
|
5254
5605
|
head,
|
|
5255
5606
|
ended,
|
|
5607
|
+
body: trimmed,
|
|
5256
5608
|
refusal: `workbuddy answered 200 with a body that is neither a stream nor an envelope: ${safeMessage(trimmed.slice(0, 200))}`
|
|
5257
5609
|
};
|
|
5258
5610
|
}
|
|
@@ -5389,7 +5741,6 @@ function createWorkBuddyShim(options) {
|
|
|
5389
5741
|
const { pool, client, catalog } = options;
|
|
5390
5742
|
const region = options.region;
|
|
5391
5743
|
const logger = options.logger;
|
|
5392
|
-
const maxAttempts = 8;
|
|
5393
5744
|
const server = createLoopbackServer({
|
|
5394
5745
|
port: options.port,
|
|
5395
5746
|
label: "workbuddy shim",
|
|
@@ -5456,26 +5807,34 @@ function createWorkBuddyShim(options) {
|
|
|
5456
5807
|
writeOpenAIError(res, 400, "invalid_request_error", "model is required");
|
|
5457
5808
|
return;
|
|
5458
5809
|
}
|
|
5459
|
-
|
|
5810
|
+
let tried = 0;
|
|
5811
|
+
const skipped = /* @__PURE__ */ new Set();
|
|
5460
5812
|
let last;
|
|
5461
5813
|
let exhaustedByRateLimit = false;
|
|
5814
|
+
let transportAttempts = 0;
|
|
5462
5815
|
let effortFallback;
|
|
5463
5816
|
let effortFallbackBuilt = false;
|
|
5817
|
+
const maxAttempts = Math.max(8, pool.list(region).length + 2);
|
|
5464
5818
|
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
5465
5819
|
if (controller.signal.aborted) return;
|
|
5466
|
-
const account = await pool.acquire(modelId, region, conversationKey);
|
|
5820
|
+
const account = await pool.acquire(modelId, region, conversationKey, skipped);
|
|
5467
5821
|
if (account === void 0) {
|
|
5468
5822
|
if (exhaustedByRateLimit && last !== void 0) {
|
|
5469
5823
|
const model = ` for model ${modelId}`;
|
|
5470
5824
|
const subject = last.kind === "waf_block" ? "every WorkBuddy account was blocked by the upstream gateway (WAF)" : last.kind === "hard_credit" ? `every WorkBuddy account is out of credits${model}` : last.kind === "session_dead" ? `every WorkBuddy sign-in is no longer accepted${model}` : last.kind === "model_tier" ? `no WorkBuddy account can use model ${modelId}` : last.kind === "account_restricted" ? "every WorkBuddy account was restricted by the upstream" : last.kind === "transport" ? `the upstream host could not be reached on any account${model}` : `every account is rate-limited${model}`;
|
|
5471
|
-
const advice = last.kind === "soft_rate" ? "resets at the upstream window" : last.kind === "model_tier" ? "pick another model, or add an account whose plan includes it" : last.kind === "account_restricted" ? "appeal the restriction in the WorkBuddy console, or add another account" : last.kind === "transport" ? "check the connection to the upstream host" : "sign in again in the desktop app";
|
|
5472
|
-
|
|
5825
|
+
const advice = last.kind === "soft_rate" ? "resets at the upstream window" : last.kind === "model_tier" ? "pick another model, or add an account whose plan includes it" : last.kind === "account_restricted" ? "appeal the restriction in the WorkBuddy console, or add another account" : last.kind === "waf_block" ? "wait for the upstream gateway block to clear, or change network" : last.kind === "transport" ? "check the connection to the upstream host" : last.kind === "hard_credit" ? "top up the account, or add another account" : "sign in again in the desktop app";
|
|
5826
|
+
if (last.kind === "soft_rate") {
|
|
5827
|
+
const live = pool.list(region).filter((candidate) => !pool.isDisabled(candidate.id));
|
|
5828
|
+
const wait = unavailableAnswer(pool, live, Date.now(), modelId).retryAfterSeconds;
|
|
5829
|
+
if (wait !== void 0) res.setHeader("Retry-After", String(wait));
|
|
5830
|
+
}
|
|
5831
|
+
writeOpenAIError(res, KIND_STATUS[last.kind], last.kind, `${subject} (tried ${tried} account(s)); ${advice} — ${last.message.slice(0, 200)}`);
|
|
5473
5832
|
return;
|
|
5474
5833
|
}
|
|
5475
5834
|
const regionAccounts = pool.list(region);
|
|
5476
5835
|
const switchedOff = regionAccounts.filter((account) => pool.isDisabled(account.id));
|
|
5477
5836
|
if (regionAccounts.length > 0 && switchedOff.length === regionAccounts.length) {
|
|
5478
|
-
writeOpenAIError(res, 403, "accounts_switched_off", `every account for this gateway is switched off in the plugin panel
|
|
5837
|
+
writeOpenAIError(res, 403, "accounts_switched_off", `every account for this gateway is switched off in the plugin panel; switch one back on`);
|
|
5479
5838
|
return;
|
|
5480
5839
|
}
|
|
5481
5840
|
if (regionAccounts.length > 0) {
|
|
@@ -5489,9 +5848,25 @@ function createWorkBuddyShim(options) {
|
|
|
5489
5848
|
writeOpenAIError(res, 401, "not_signed_in", "no WorkBuddy credential found; sign in on the desktop app (or set WORKBUDDY_AUTH_FILE)");
|
|
5490
5849
|
return;
|
|
5491
5850
|
}
|
|
5492
|
-
tried
|
|
5851
|
+
tried += 1;
|
|
5493
5852
|
let result = await client.chatStream(account.credential, prepared, controller.signal);
|
|
5494
|
-
|
|
5853
|
+
let refreshOutcome;
|
|
5854
|
+
if (!result.ok && result.kind === "session_dead") {
|
|
5855
|
+
const failure = result;
|
|
5856
|
+
refreshOutcome = await pool.refreshAccountOutcome(account.id);
|
|
5857
|
+
if (refreshOutcome === "failed") {
|
|
5858
|
+
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} could not refresh its sign-in; trying the next account without holding it`);
|
|
5859
|
+
skipped.add(account.id);
|
|
5860
|
+
last = {
|
|
5861
|
+
kind: "transport",
|
|
5862
|
+
status: 502,
|
|
5863
|
+
message: `could not refresh the sign-in: ${failure.message}`
|
|
5864
|
+
};
|
|
5865
|
+
exhaustedByRateLimit = true;
|
|
5866
|
+
continue;
|
|
5867
|
+
}
|
|
5868
|
+
}
|
|
5869
|
+
if (refreshOutcome === "refreshed") {
|
|
5495
5870
|
if (controller.signal.aborted) return;
|
|
5496
5871
|
result = await client.chatStream(account.credential, prepared, controller.signal);
|
|
5497
5872
|
}
|
|
@@ -5511,6 +5886,7 @@ function createWorkBuddyShim(options) {
|
|
|
5511
5886
|
let sawDone = false;
|
|
5512
5887
|
let sawFinish = false;
|
|
5513
5888
|
let envelopeFailure;
|
|
5889
|
+
let headFailure;
|
|
5514
5890
|
const decoder = new TextDecoder();
|
|
5515
5891
|
const sse = new SseDecoder();
|
|
5516
5892
|
const startStream = () => {
|
|
@@ -5569,7 +5945,16 @@ function createWorkBuddyShim(options) {
|
|
|
5569
5945
|
ended = peeked.ended;
|
|
5570
5946
|
if (peeked.refusal !== void 0) {
|
|
5571
5947
|
await reader.cancel().catch(() => {});
|
|
5572
|
-
|
|
5948
|
+
if (peeked.ended && peeked.refusal === EMPTY_STREAM_REFUSAL) {
|
|
5949
|
+
headFailure = peeked.refusal;
|
|
5950
|
+
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} answered 200 with an empty stream; rotating`);
|
|
5951
|
+
return;
|
|
5952
|
+
}
|
|
5953
|
+
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} answered 200 with no stream: ${peeked.refusal}`);
|
|
5954
|
+
if (peeked.code === "11128" || unapprovedChannelRefusal(peeked.refusal) !== void 0) {
|
|
5955
|
+
writeOpenAIError(res, 400, "upstream_channel_check", channelCheckRefusal());
|
|
5956
|
+
return;
|
|
5957
|
+
}
|
|
5573
5958
|
const envelopeKind = classifyEnvelopeCode(peeked.code, peeked.refusal);
|
|
5574
5959
|
if (envelopeKind === "soft_rate" || envelopeKind === "hard_credit" || envelopeKind === "session_dead" || envelopeKind === "account_restricted" || envelopeKind === "model_tier") {
|
|
5575
5960
|
last = {
|
|
@@ -5579,20 +5964,36 @@ function createWorkBuddyShim(options) {
|
|
|
5579
5964
|
};
|
|
5580
5965
|
exhaustedByRateLimit = true;
|
|
5581
5966
|
envelopeFailure = envelopeKind;
|
|
5582
|
-
if (envelopeKind === "soft_rate")
|
|
5583
|
-
|
|
5584
|
-
|
|
5967
|
+
if (envelopeKind === "soft_rate") {
|
|
5968
|
+
const bodyReset = parseRateLimitReset(peeked.body ?? peeked.refusal);
|
|
5969
|
+
const headerReset = resetFromRetryAfter(retryAfterSeconds(result.response.headers));
|
|
5970
|
+
const resetAtMs = bodyReset !== void 0 && bodyReset > Date.now() ? headerReset === void 0 ? bodyReset : Math.max(bodyReset, headerReset) : headerReset;
|
|
5971
|
+
pool.penalize(account.id, resetAtMs, modelId);
|
|
5972
|
+
} else if (envelopeKind === "model_tier") pool.blockModel(account.id, modelId, Date.now() + MODEL_TIER_HOLD_MS);
|
|
5973
|
+
else if (envelopeKind === "session_dead") {
|
|
5974
|
+
const refreshOutcome = await pool.refreshAccountOutcome(account.id);
|
|
5975
|
+
if (refreshOutcome === "refused") pool.penalize(account.id, holdUntil(), void 0, "session");
|
|
5976
|
+
else if (refreshOutcome === "failed") {
|
|
5977
|
+
skipped.add(account.id);
|
|
5978
|
+
last = {
|
|
5979
|
+
kind: "transport",
|
|
5980
|
+
status: 502,
|
|
5981
|
+
message: `could not refresh the sign-in: ${peeked.refusal.slice(0, 200)}`
|
|
5982
|
+
};
|
|
5983
|
+
}
|
|
5984
|
+
} else pool.penalize(account.id, holdUntil(), void 0, envelopeKind === "hard_credit" ? "spent" : "restricted");
|
|
5585
5985
|
return;
|
|
5586
5986
|
}
|
|
5587
5987
|
writeOpenAIError(res, 502, "upstream_error", peeked.refusal);
|
|
5588
5988
|
return;
|
|
5589
5989
|
}
|
|
5590
5990
|
} catch (error) {
|
|
5591
|
-
|
|
5592
|
-
|
|
5991
|
+
await reader.cancel().catch(() => {});
|
|
5992
|
+
headFailure = safeMessage(error);
|
|
5993
|
+
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} failed before its first byte; rotating`);
|
|
5593
5994
|
return;
|
|
5594
5995
|
}
|
|
5595
|
-
logger?.info?.(`${LOG_PREFIX}: served by ${account.label}`);
|
|
5996
|
+
logger?.info?.(`${LOG_PREFIX}: served by ${accountLogTag(account.label)}`);
|
|
5596
5997
|
startStream();
|
|
5597
5998
|
let headIndex = 0;
|
|
5598
5999
|
try {
|
|
@@ -5643,6 +6044,18 @@ function createWorkBuddyShim(options) {
|
|
|
5643
6044
|
} catch {}
|
|
5644
6045
|
}
|
|
5645
6046
|
})();
|
|
6047
|
+
if (headFailure !== void 0) {
|
|
6048
|
+
last = {
|
|
6049
|
+
kind: "transport",
|
|
6050
|
+
status: 502,
|
|
6051
|
+
message: headFailure
|
|
6052
|
+
};
|
|
6053
|
+
exhaustedByRateLimit = true;
|
|
6054
|
+
skipped.add(account.id);
|
|
6055
|
+
transportAttempts += 1;
|
|
6056
|
+
if (transportAttempts >= MAX_TRANSPORT_ATTEMPTS) break;
|
|
6057
|
+
continue;
|
|
6058
|
+
}
|
|
5646
6059
|
if (envelopeFailure === void 0) return;
|
|
5647
6060
|
continue;
|
|
5648
6061
|
}
|
|
@@ -5671,10 +6084,13 @@ function createWorkBuddyShim(options) {
|
|
|
5671
6084
|
* configured window rather than a hold that would park a healthy account
|
|
5672
6085
|
* for hours over a transient block.
|
|
5673
6086
|
*
|
|
5674
|
-
* A `transport` failure is the network path's
|
|
5675
|
-
*
|
|
5676
|
-
*
|
|
5677
|
-
*
|
|
6087
|
+
* A `transport` failure is the network path's. A global pool need not
|
|
6088
|
+
* share a host: `codebuddy.ai` and `workbuddy.ai` logins can be served by
|
|
6089
|
+
* different gateways, so one unreachable host says nothing about the next
|
|
6090
|
+
* account. It is skipped for this request and rotation continues, up to
|
|
6091
|
+
* `MAX_TRANSPORT_ATTEMPTS`: past that the host itself is down, and one
|
|
6092
|
+
* headers timeout per sign-in is not a better answer.
|
|
6093
|
+
* An `aborted` turn is the client's own doing and stops the loop.
|
|
5678
6094
|
*/
|
|
5679
6095
|
if (result.kind === "aborted") break;
|
|
5680
6096
|
if (result.kind === "transport") {
|
|
@@ -5684,19 +6100,24 @@ function createWorkBuddyShim(options) {
|
|
|
5684
6100
|
message: result.message
|
|
5685
6101
|
};
|
|
5686
6102
|
exhaustedByRateLimit = true;
|
|
5687
|
-
|
|
6103
|
+
skipped.add(account.id);
|
|
6104
|
+
transportAttempts += 1;
|
|
6105
|
+
if (transportAttempts >= MAX_TRANSPORT_ATTEMPTS) break;
|
|
6106
|
+
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} transport failure; rotating`);
|
|
6107
|
+
continue;
|
|
5688
6108
|
}
|
|
5689
6109
|
if (result.kind !== "soft_rate" && result.kind !== "waf_block" && result.kind !== "hard_credit" && result.kind !== "session_dead" && result.kind !== "model_tier" && result.kind !== "account_restricted") break;
|
|
5690
6110
|
exhaustedByRateLimit = true;
|
|
5691
6111
|
if (result.kind === "soft_rate") {
|
|
5692
6112
|
const bodyReset = parseRateLimitReset(result.message);
|
|
5693
|
-
const
|
|
6113
|
+
const headerReset = resetFromRetryAfter(result.retryAfter);
|
|
6114
|
+
const resetAtMs = bodyReset !== void 0 && bodyReset > Date.now() ? headerReset === void 0 ? bodyReset : Math.max(bodyReset, headerReset) : headerReset;
|
|
5694
6115
|
pool.penalize(account.id, resetAtMs, modelId);
|
|
5695
6116
|
} else if (result.kind === "model_tier") pool.blockModel(account.id, modelId, Date.now() + MODEL_TIER_HOLD_MS);
|
|
5696
6117
|
else if (result.kind === "account_restricted") pool.penalize(account.id, holdUntil(), void 0, "restricted");
|
|
5697
6118
|
else if (result.kind === "hard_credit" || result.kind === "session_dead") pool.penalize(account.id, holdUntil(), void 0, result.kind === "hard_credit" ? "spent" : "session");
|
|
5698
6119
|
else pool.penalize(account.id);
|
|
5699
|
-
logger?.warn(`${LOG_PREFIX}: ${account.label} ${result.kind} on ${modelId} (attempt ${attempt + 1}/${maxAttempts}); rotating`);
|
|
6120
|
+
logger?.warn(`${LOG_PREFIX}: ${accountLogTag(account.label)} ${result.kind} on ${modelId} (attempt ${attempt + 1}/${maxAttempts}); rotating`);
|
|
5700
6121
|
}
|
|
5701
6122
|
if (last === void 0) {
|
|
5702
6123
|
writeOpenAIError(res, 500, "internal", "chat request exhausted without a result");
|
|
@@ -5711,7 +6132,7 @@ function createWorkBuddyShim(options) {
|
|
|
5711
6132
|
writeOpenAIError(res, 400, "upstream_channel_check", unapproved);
|
|
5712
6133
|
return;
|
|
5713
6134
|
}
|
|
5714
|
-
writeOpenAIError(res, KIND_STATUS[last.kind], last.kind, `workbuddy upstream ${last.kind} (http ${last.status}) after ${tried
|
|
6135
|
+
writeOpenAIError(res, KIND_STATUS[last.kind], last.kind, `workbuddy upstream ${last.kind} (http ${last.status}) after ${tried} account(s): ${last.message.slice(0, 400)}`);
|
|
5715
6136
|
}
|
|
5716
6137
|
return {
|
|
5717
6138
|
ready,
|
|
@@ -5720,75 +6141,6 @@ function createWorkBuddyShim(options) {
|
|
|
5720
6141
|
close: server.close
|
|
5721
6142
|
};
|
|
5722
6143
|
}
|
|
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
6144
|
//#endregion
|
|
5793
6145
|
//#region src/promo.ts
|
|
5794
6146
|
/**
|
|
@@ -7174,7 +7526,7 @@ var TraeSoloUpstreamClient = class {
|
|
|
7174
7526
|
async fetchModels(signal) {
|
|
7175
7527
|
const [credential, identity] = await Promise.all([this.options.credential(), this.options.identity()]);
|
|
7176
7528
|
const region = traeRegionOfCredential(credential);
|
|
7177
|
-
const base =
|
|
7529
|
+
const base = REGION_GATEWAYS[region].chat;
|
|
7178
7530
|
const headers = {
|
|
7179
7531
|
...buildTraeHeaders(credential, identity),
|
|
7180
7532
|
Accept: "application/json"
|
|
@@ -7309,7 +7661,7 @@ var TraeSoloUpstreamClient = class {
|
|
|
7309
7661
|
const [credential, identity] = await Promise.all([this.options.credential(), this.options.identity()]);
|
|
7310
7662
|
const region = traeRegionOfCredential(credential);
|
|
7311
7663
|
if (region !== "ai") throw new Error("Trae pay status exists on the international region only");
|
|
7312
|
-
const response = await this.fetchImpl(traeEndpoint(
|
|
7664
|
+
const response = await this.fetchImpl(traeEndpoint(REGION_GATEWAYS[region].pay, TRAE_PAY_STATUS_PATH), {
|
|
7313
7665
|
redirect: "error",
|
|
7314
7666
|
method: "POST",
|
|
7315
7667
|
headers: traeCheckinHeaders(credential, identity, region),
|
|
@@ -7379,7 +7731,7 @@ var TraeSoloUpstreamClient = class {
|
|
|
7379
7731
|
};
|
|
7380
7732
|
}
|
|
7381
7733
|
const headers = buildTraeHeaders(credential, identity);
|
|
7382
|
-
const base =
|
|
7734
|
+
const base = REGION_GATEWAYS[traeRegionOfCredential(credential)].chat;
|
|
7383
7735
|
let response;
|
|
7384
7736
|
const deadline = headersDeadline(signal, timeouts?.headersMs ?? TRAE_HEADERS_TIMEOUT_MS);
|
|
7385
7737
|
try {
|
|
@@ -7702,7 +8054,11 @@ function bridgeTraeStream(source, model, options = {}) {
|
|
|
7702
8054
|
const decoded = decodeTraeEvent(event);
|
|
7703
8055
|
if (decoded.type === "done" || event.event === "done") upstreamDone = true;
|
|
7704
8056
|
const failure = traeFailureOf(decoded);
|
|
7705
|
-
if (failure !== void 0)
|
|
8057
|
+
if (failure !== void 0) {
|
|
8058
|
+
const refusal = new Error(describeTraeFailure(failure));
|
|
8059
|
+
refusal.traeFailure = failure;
|
|
8060
|
+
throw refusal;
|
|
8061
|
+
}
|
|
7706
8062
|
if (decoded.type === "unknown") {
|
|
7707
8063
|
keepalive(controller);
|
|
7708
8064
|
return;
|
|
@@ -8097,10 +8453,13 @@ function createTraeGateway(options) {
|
|
|
8097
8453
|
try {
|
|
8098
8454
|
relayed = await openTraeResponse(result.response, model, { onFailure: (error) => {
|
|
8099
8455
|
logger?.warn?.("wtq-pool: trae relay stream failed mid-flight", error);
|
|
8100
|
-
if (!(error instanceof Error && error.name === "AbortError") && !watcher.signal.aborted)
|
|
8101
|
-
|
|
8102
|
-
|
|
8103
|
-
|
|
8456
|
+
if (!(error instanceof Error && error.name === "AbortError") && !watcher.signal.aborted) {
|
|
8457
|
+
const failure = error.traeFailure;
|
|
8458
|
+
if (failure !== void 0) {
|
|
8459
|
+
const classified = classifyTraeFailure(failure);
|
|
8460
|
+
options.onAttemptFailure?.(credential, { ...classified.retryAfterSeconds === void 0 ? {} : { retryAfter: String(classified.retryAfterSeconds) } });
|
|
8461
|
+
} else options.onAttemptFailure?.(credential, {});
|
|
8462
|
+
}
|
|
8104
8463
|
} });
|
|
8105
8464
|
} catch (error) {
|
|
8106
8465
|
if (watcher.signal.aborted || error instanceof Error && error.name === "AbortError") return {
|
|
@@ -8159,11 +8518,7 @@ function createTraeGateway(options) {
|
|
|
8159
8518
|
}
|
|
8160
8519
|
opened = attempt;
|
|
8161
8520
|
if (!rotates(attempt.status, attempt.kind)) break;
|
|
8162
|
-
options.onAttemptFailure?.(credential, {
|
|
8163
|
-
status: attempt.status,
|
|
8164
|
-
...attempt.kind === void 0 ? {} : { kind: attempt.kind },
|
|
8165
|
-
...attempt.retryAfter === void 0 ? {} : { retryAfter: attempt.retryAfter }
|
|
8166
|
-
});
|
|
8521
|
+
options.onAttemptFailure?.(credential, { ...attempt.retryAfter === void 0 ? {} : { retryAfter: attempt.retryAfter } });
|
|
8167
8522
|
if (index < credentials.length - 1) logger?.warn?.(`${LOG_PREFIX}: trae sign-in failed on ${model} (http ${attempt.status}); rotating`);
|
|
8168
8523
|
}
|
|
8169
8524
|
if (opened === void 0 || !opened.ok) {
|
|
@@ -9213,13 +9568,16 @@ function qoderWindowOpenAt(campaign, nowMs) {
|
|
|
9213
9568
|
function qoderClaimableCampaignOf(payload, nowMs) {
|
|
9214
9569
|
const list = payload?.campaigns;
|
|
9215
9570
|
if (!Array.isArray(list)) return void 0;
|
|
9571
|
+
let collected;
|
|
9216
9572
|
for (const entry of list) {
|
|
9217
9573
|
if (entry === null || typeof entry !== "object") continue;
|
|
9218
9574
|
const campaign = entry;
|
|
9219
9575
|
if (campaign["actionType"] !== QODER_CLAIM_BENEFIT_ACTION) continue;
|
|
9220
9576
|
if (!qoderWindowOpenAt(campaign, nowMs)) continue;
|
|
9221
|
-
return campaign;
|
|
9577
|
+
if (campaign["claimStatus"] !== QODER_CLAIMED_STATUS) return campaign;
|
|
9578
|
+
if (collected === void 0) collected = campaign;
|
|
9222
9579
|
}
|
|
9580
|
+
return collected;
|
|
9223
9581
|
}
|
|
9224
9582
|
/**
|
|
9225
9583
|
* Id of today's round when it can be claimed right now, else undefined. Kept
|
|
@@ -9739,36 +10097,42 @@ var QoderUpstreamClient = class {
|
|
|
9739
10097
|
if (!response.ok) throw new Error(`Qoder usage failed: HTTP ${response.status} ${await readErrorBody(response, 300, signal)}`);
|
|
9740
10098
|
return await response.json();
|
|
9741
10099
|
};
|
|
9742
|
-
|
|
9743
|
-
|
|
10100
|
+
/**
|
|
10101
|
+
* Turn one route's document into the panel shape.
|
|
10102
|
+
*
|
|
10103
|
+
* Validation is part of parsing, not a key-presence check before it: a
|
|
10104
|
+
* document carrying only `expiresAt`, or an empty quota object, used to pass
|
|
10105
|
+
* `usable()` and then throw after the fallback had already been skipped.
|
|
10106
|
+
*/
|
|
10107
|
+
const parse = (value, source) => {
|
|
10108
|
+
const envelope = value === null || typeof value !== "object" ? {} : value;
|
|
10109
|
+
const usage = envelope["qoderUsage"] ?? envelope["data"] ?? value;
|
|
10110
|
+
if (usage === null || typeof usage !== "object") throw new Error("Qoder usage answered no usable document");
|
|
10111
|
+
const record = usage;
|
|
10112
|
+
const userQuota = qoderQuotaBucket(record["user_quota"] ?? record["userQuota"]);
|
|
10113
|
+
const addOnQuota = qoderQuotaBucket(record["add_on_quota"] ?? record["addOnQuota"]);
|
|
10114
|
+
const rawExpiry = record["expiresAt"] ?? record["expires_at"];
|
|
10115
|
+
const expiresAtMs = qoderEpochMs(rawExpiry);
|
|
10116
|
+
const neverExpires = expiresAtMs === void 0 && rawExpiry !== void 0 && rawExpiry !== null && rawExpiry !== "";
|
|
10117
|
+
const rawPackages = record["dedicated_resource_packages"] ?? record["dedicatedResourcePackages"];
|
|
10118
|
+
const now = Date.now();
|
|
10119
|
+
const dedicatedPackages = Array.isArray(rawPackages) ? rawPackages.map(qoderDedicatedPackage).filter((entry) => entry !== void 0).filter((entry) => entry.expiresAtMs === void 0 || entry.expiresAtMs > now) : [];
|
|
10120
|
+
if (userQuota === void 0 && addOnQuota === void 0 && dedicatedPackages.length === 0) throw new Error("Qoder usage contained no usable quota");
|
|
10121
|
+
return {
|
|
10122
|
+
...userQuota === void 0 ? {} : { userQuota },
|
|
10123
|
+
...addOnQuota === void 0 ? {} : { addOnQuota },
|
|
10124
|
+
dedicatedPackages,
|
|
10125
|
+
...expiresAtMs === void 0 ? {} : { expiresAtMs },
|
|
10126
|
+
...neverExpires ? { neverExpires: true } : {},
|
|
10127
|
+
source
|
|
10128
|
+
};
|
|
10129
|
+
};
|
|
9744
10130
|
try {
|
|
9745
|
-
|
|
10131
|
+
return parse(await read(QODER_USAGE_PRESENTATION_PATH), "presentation");
|
|
9746
10132
|
} catch (error) {
|
|
9747
10133
|
if (signal?.aborted) throw error;
|
|
9748
|
-
|
|
9749
|
-
|
|
9750
|
-
}
|
|
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
|
-
};
|
|
10134
|
+
return parse(await read(QODER_USAGE_PATH), "quota");
|
|
10135
|
+
}
|
|
9772
10136
|
}
|
|
9773
10137
|
/**
|
|
9774
10138
|
* Read the raw campaigns payload once. One round trip answers both the
|
|
@@ -9928,6 +10292,7 @@ function isAcknowledgementCode(value) {
|
|
|
9928
10292
|
function unwrapFailure(frame) {
|
|
9929
10293
|
let code = "";
|
|
9930
10294
|
let detail = "";
|
|
10295
|
+
const signals = [];
|
|
9931
10296
|
let node = frame;
|
|
9932
10297
|
let descended = false;
|
|
9933
10298
|
let codeFromPlainKey = false;
|
|
@@ -9950,8 +10315,10 @@ function unwrapFailure(frame) {
|
|
|
9950
10315
|
}
|
|
9951
10316
|
}
|
|
9952
10317
|
const message = node["message"] ?? node["errorMessage"];
|
|
9953
|
-
if (typeof message === "string" && message.
|
|
10318
|
+
if (typeof message === "string" && message.trim() !== "" && !signals.includes(message)) signals.push(message);
|
|
10319
|
+
if ((detail === "" || tryJsonObject(detail) !== void 0) && typeof message === "string" && message.length > 0) detail = message;
|
|
9954
10320
|
const flat = typeof node["error"] === "string" ? node["error"] : typeof node["details"] === "string" ? node["details"] : void 0;
|
|
10321
|
+
if (flat !== void 0 && flat.trim() !== "" && !signals.includes(flat)) signals.push(flat);
|
|
9955
10322
|
if (detail === "" && flat !== void 0 && flat.length > 0) detail = flat;
|
|
9956
10323
|
const nested = isPlainObject(node["details"]) ? node["details"] : isPlainObject(node["error"]) ? node["error"] : void 0;
|
|
9957
10324
|
const next = nested ?? (typeof message === "string" ? tryJsonObject(message) : void 0);
|
|
@@ -9964,25 +10331,32 @@ function unwrapFailure(frame) {
|
|
|
9964
10331
|
if (codeFromPlainKey && isAcknowledgementCode(code)) code = "";
|
|
9965
10332
|
return {
|
|
9966
10333
|
code,
|
|
9967
|
-
detail
|
|
10334
|
+
detail,
|
|
10335
|
+
signals: signals.join("\n")
|
|
9968
10336
|
};
|
|
9969
10337
|
}
|
|
9970
10338
|
/**
|
|
9971
10339
|
* The gateway's retry hint, when the frame carries one.
|
|
9972
10340
|
*
|
|
9973
|
-
* A carried `0` is the decoder's "no hint" placeholder, not a real wait
|
|
9974
|
-
*
|
|
9975
|
-
*
|
|
9976
|
-
*
|
|
10341
|
+
* A carried `0` is the decoder's "no hint" placeholder, not a real wait. The
|
|
10342
|
+
* hint may sit on the envelope, in a nested container, or inside a message that
|
|
10343
|
+
* is itself a JSON document; the walk reads all three so a queue descriptor is
|
|
10344
|
+
* not lost when the outer sentence is the one worth showing.
|
|
9977
10345
|
*/
|
|
9978
10346
|
function retryAfterSecondsOf(frame) {
|
|
9979
|
-
|
|
9980
|
-
|
|
9981
|
-
|
|
9982
|
-
|
|
9983
|
-
|
|
9984
|
-
|
|
9985
|
-
|
|
10347
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10348
|
+
let node = frame;
|
|
10349
|
+
for (let depth = 0; depth < 8; depth++) {
|
|
10350
|
+
if (!isPlainObject(node) || seen.has(node)) break;
|
|
10351
|
+
seen.add(node);
|
|
10352
|
+
const direct = node["retryAfterSeconds"];
|
|
10353
|
+
if (typeof direct === "number" && Number.isFinite(direct) && direct > 0) return direct;
|
|
10354
|
+
const message = node["message"] ?? node["errorMessage"];
|
|
10355
|
+
const next = (isPlainObject(node["details"]) ? node["details"] : isPlainObject(node["error"]) ? node["error"] : void 0) ?? (typeof message === "string" ? tryJsonObject(message) : void 0);
|
|
10356
|
+
if (next === void 0) break;
|
|
10357
|
+
node = next;
|
|
10358
|
+
}
|
|
10359
|
+
return 0;
|
|
9986
10360
|
}
|
|
9987
10361
|
/**
|
|
9988
10362
|
* The inner chunk of one data payload: the envelope's `body` when it is a JSON
|
|
@@ -10020,7 +10394,7 @@ function decodeQoderFrame(payload) {
|
|
|
10020
10394
|
type: "chunk",
|
|
10021
10395
|
chunk
|
|
10022
10396
|
};
|
|
10023
|
-
const { code, detail } = unwrapFailure(chunk);
|
|
10397
|
+
const { code, detail, signals } = unwrapFailure(chunk);
|
|
10024
10398
|
if (code === "" && detail === "") return {
|
|
10025
10399
|
type: "unknown",
|
|
10026
10400
|
reason: "unnamed",
|
|
@@ -10030,6 +10404,7 @@ function decodeQoderFrame(payload) {
|
|
|
10030
10404
|
type: "failure",
|
|
10031
10405
|
code,
|
|
10032
10406
|
detail,
|
|
10407
|
+
signals,
|
|
10033
10408
|
retryAfterSeconds: retryAfterSecondsOf(chunk)
|
|
10034
10409
|
};
|
|
10035
10410
|
}
|
|
@@ -10109,6 +10484,16 @@ var QoderFrameDecoder = class {
|
|
|
10109
10484
|
* frame. A vendor that does close its stream wins this race and pays nothing.
|
|
10110
10485
|
*/
|
|
10111
10486
|
const TAIL_GRACE_MS = 1e3;
|
|
10487
|
+
/**
|
|
10488
|
+
* How long a peek that has seen a frame carrying no output waits for a refusal
|
|
10489
|
+
* that may follow it.
|
|
10490
|
+
*
|
|
10491
|
+
* Qoder opens a turn with a role-only delta. Committing on that frame hid a
|
|
10492
|
+
* refusal in the very next one; waiting for output instead kept the 200 from the
|
|
10493
|
+
* client for the whole thinking phase. The grace is enough for a refusal that
|
|
10494
|
+
* arrives promptly, and short enough that a slow model still gets its headers.
|
|
10495
|
+
*/
|
|
10496
|
+
const PEEK_OUTPUT_GRACE_MS = 1e3;
|
|
10112
10497
|
/** Retryable queue wait the gateway answers with 429 + Retry-After. */
|
|
10113
10498
|
var QoderQueueRejection = class extends Error {
|
|
10114
10499
|
retryAfterSeconds;
|
|
@@ -10188,14 +10573,16 @@ function queueSeconds(frame) {
|
|
|
10188
10573
|
*/
|
|
10189
10574
|
function classifyQoderFailure(failure) {
|
|
10190
10575
|
const code = failure.code.trim();
|
|
10191
|
-
const text = `${code} ${failure.message}`;
|
|
10576
|
+
const text = `${code} ${failure.message} ${failure.signals ?? ""}`;
|
|
10577
|
+
const frame = {
|
|
10578
|
+
type: "failure",
|
|
10579
|
+
code,
|
|
10580
|
+
detail: failure.message,
|
|
10581
|
+
signals: failure.signals ?? "",
|
|
10582
|
+
retryAfterSeconds: failure.retryAfterSeconds ?? 0
|
|
10583
|
+
};
|
|
10192
10584
|
if (code === "110" || /daily.*(limit|quota)|quota.*daily|allowance.*spent/i.test(text)) {
|
|
10193
|
-
const retryAfter = queueSeconds(
|
|
10194
|
-
type: "failure",
|
|
10195
|
-
code,
|
|
10196
|
-
detail: failure.message,
|
|
10197
|
-
retryAfterSeconds: failure.retryAfterSeconds ?? 0
|
|
10198
|
-
});
|
|
10585
|
+
const retryAfter = queueSeconds(frame);
|
|
10199
10586
|
return {
|
|
10200
10587
|
status: 429,
|
|
10201
10588
|
kind: "hard_credit",
|
|
@@ -10205,12 +10592,7 @@ function classifyQoderFailure(failure) {
|
|
|
10205
10592
|
if (code === "10605") return {
|
|
10206
10593
|
status: 429,
|
|
10207
10594
|
kind: "soft_rate",
|
|
10208
|
-
error: new QoderQueueRejection(queueSeconds(
|
|
10209
|
-
type: "failure",
|
|
10210
|
-
code,
|
|
10211
|
-
detail: failure.message,
|
|
10212
|
-
retryAfterSeconds: failure.retryAfterSeconds ?? 0
|
|
10213
|
-
}), failure.message)
|
|
10595
|
+
error: new QoderQueueRejection(queueSeconds(frame), failure.message)
|
|
10214
10596
|
};
|
|
10215
10597
|
if (/Login expired|TOKEN_EXPIRE|token is not active/i.test(text) || code === "105") return {
|
|
10216
10598
|
status: 401,
|
|
@@ -10222,15 +10604,10 @@ function classifyQoderFailure(failure) {
|
|
|
10222
10604
|
kind: "client",
|
|
10223
10605
|
error: new Error(failure.message)
|
|
10224
10606
|
};
|
|
10225
|
-
if (queueMarkerCount(
|
|
10607
|
+
if (queueMarkerCount(text) >= 2) return {
|
|
10226
10608
|
status: 429,
|
|
10227
10609
|
kind: "soft_rate",
|
|
10228
|
-
error: new QoderQueueRejection(queueSeconds(
|
|
10229
|
-
type: "failure",
|
|
10230
|
-
code,
|
|
10231
|
-
detail: failure.message,
|
|
10232
|
-
retryAfterSeconds: failure.retryAfterSeconds ?? 0
|
|
10233
|
-
}), failure.message)
|
|
10610
|
+
error: new QoderQueueRejection(queueSeconds(frame), failure.message)
|
|
10234
10611
|
};
|
|
10235
10612
|
if (code === "429") return {
|
|
10236
10613
|
status: 429,
|
|
@@ -10385,6 +10762,7 @@ function bridgeQoderStream(source, model, options = {}) {
|
|
|
10385
10762
|
const { error } = classifyQoderFailure({
|
|
10386
10763
|
code: decoded.code,
|
|
10387
10764
|
message: decoded.detail,
|
|
10765
|
+
signals: decoded.signals,
|
|
10388
10766
|
retryAfterSeconds: decoded.retryAfterSeconds
|
|
10389
10767
|
});
|
|
10390
10768
|
throw error;
|
|
@@ -10547,6 +10925,45 @@ function bridgeQoderStream(source, model, options = {}) {
|
|
|
10547
10925
|
});
|
|
10548
10926
|
}
|
|
10549
10927
|
/**
|
|
10928
|
+
* Whether a Qoder chunk carries output a client would actually see.
|
|
10929
|
+
*
|
|
10930
|
+
* A role-only delta and a usage-only frame both have `choices`, but neither is
|
|
10931
|
+
* output: a refusal that follows them can still become a real status code and
|
|
10932
|
+
* let the next account try. Counting any non-empty `choices` as output committed
|
|
10933
|
+
* the stream at 200 and skipped failover.
|
|
10934
|
+
*/
|
|
10935
|
+
function qoderChunkHasOutput(chunk) {
|
|
10936
|
+
const choices = chunk["choices"];
|
|
10937
|
+
if (!Array.isArray(choices)) return false;
|
|
10938
|
+
for (const raw of choices) {
|
|
10939
|
+
if (raw === null || typeof raw !== "object") continue;
|
|
10940
|
+
const delta = raw["delta"];
|
|
10941
|
+
if (delta === null || typeof delta !== "object") continue;
|
|
10942
|
+
const fields = delta;
|
|
10943
|
+
if (typeof fields["content"] === "string" && fields["content"] !== "") return true;
|
|
10944
|
+
if (typeof fields["reasoning_content"] === "string" && fields["reasoning_content"] !== "") return true;
|
|
10945
|
+
const calls = fields["tool_calls"];
|
|
10946
|
+
if (Array.isArray(calls) && calls.length > 0) return true;
|
|
10947
|
+
}
|
|
10948
|
+
return false;
|
|
10949
|
+
}
|
|
10950
|
+
/**
|
|
10951
|
+
* Whether a Qoder chunk closes the turn, even if the socket stays open.
|
|
10952
|
+
*
|
|
10953
|
+
* Qoder reports a completed turn with a `finish_reason` and often a trailing
|
|
10954
|
+
* usage frame, then leaves the connection open. The peek must stop there or it
|
|
10955
|
+
* waits for the upstream idle watchdog on a turn that has already finished.
|
|
10956
|
+
*/
|
|
10957
|
+
function qoderChunkIsTerminal(chunk) {
|
|
10958
|
+
const choices = chunk["choices"];
|
|
10959
|
+
if (Array.isArray(choices)) for (const raw of choices) {
|
|
10960
|
+
if (raw === null || typeof raw !== "object") continue;
|
|
10961
|
+
const finish = raw["finish_reason"];
|
|
10962
|
+
if (finish !== void 0 && finish !== null) return true;
|
|
10963
|
+
}
|
|
10964
|
+
return chunk["usage"] !== void 0 && chunk["usage"] !== null;
|
|
10965
|
+
}
|
|
10966
|
+
/**
|
|
10550
10967
|
* Turn one gateway response into something an OpenAI client can consume.
|
|
10551
10968
|
*
|
|
10552
10969
|
* A non-2xx answer becomes a JSON error, and so does a 2xx with no body at all.
|
|
@@ -10557,7 +10974,7 @@ function bridgeQoderStream(source, model, options = {}) {
|
|
|
10557
10974
|
*/
|
|
10558
10975
|
async function openQoderResponse(response, model, options = {}) {
|
|
10559
10976
|
if (!response.ok) {
|
|
10560
|
-
const detail =
|
|
10977
|
+
const detail = await readErrorBody(response, 1024);
|
|
10561
10978
|
return Response.json({ error: {
|
|
10562
10979
|
message: detail === "" ? `Qoder returned HTTP ${response.status}` : detail,
|
|
10563
10980
|
type: "upstream_error",
|
|
@@ -10575,26 +10992,52 @@ async function openQoderResponse(response, model, options = {}) {
|
|
|
10575
10992
|
const buffered = [];
|
|
10576
10993
|
let bufferedBytes = 0;
|
|
10577
10994
|
let sawOutput = false;
|
|
10995
|
+
let sawTerminal = false;
|
|
10996
|
+
let sawQuiet = false;
|
|
10997
|
+
let graceDeadline = 0;
|
|
10998
|
+
let pendingRead;
|
|
10578
10999
|
let failure;
|
|
10579
11000
|
let ended = false;
|
|
10580
11001
|
const inspect = (payloads) => {
|
|
10581
11002
|
for (const payload of payloads) {
|
|
10582
11003
|
const decoded = decodeQoderFrame(payload);
|
|
10583
11004
|
if (decoded.type === "chunk") {
|
|
10584
|
-
const
|
|
10585
|
-
if (
|
|
10586
|
-
|
|
11005
|
+
const chunk = decoded.chunk;
|
|
11006
|
+
if (qoderChunkHasOutput(chunk)) sawOutput = true;
|
|
11007
|
+
if (qoderChunkIsTerminal(chunk)) sawTerminal = true;
|
|
11008
|
+
if (!sawOutput && !sawTerminal && Array.isArray(chunk["choices"]) && chunk["choices"].length > 0) sawQuiet = true;
|
|
10587
11009
|
} else if (decoded.type === "failure") failure ??= {
|
|
10588
11010
|
code: decoded.code,
|
|
10589
11011
|
message: decoded.detail,
|
|
11012
|
+
signals: decoded.signals,
|
|
10590
11013
|
retryAfterSeconds: decoded.retryAfterSeconds
|
|
10591
11014
|
};
|
|
10592
|
-
if (sawOutput || failure !== void 0) break;
|
|
11015
|
+
if (sawOutput || sawTerminal || failure !== void 0) break;
|
|
10593
11016
|
}
|
|
10594
11017
|
};
|
|
10595
11018
|
try {
|
|
10596
11019
|
while (buffered.length < 64 && bufferedBytes < 262144) {
|
|
10597
|
-
|
|
11020
|
+
let next;
|
|
11021
|
+
if (graceDeadline === 0) next = await reader.read();
|
|
11022
|
+
else {
|
|
11023
|
+
const read = reader.read();
|
|
11024
|
+
pendingRead = read;
|
|
11025
|
+
read.catch(() => {});
|
|
11026
|
+
const remaining = Math.max(0, graceDeadline - Date.now());
|
|
11027
|
+
let timer;
|
|
11028
|
+
const timedOut = new Promise((resolve) => {
|
|
11029
|
+
timer = setTimeout(() => resolve(void 0), remaining);
|
|
11030
|
+
});
|
|
11031
|
+
let winner;
|
|
11032
|
+
try {
|
|
11033
|
+
winner = await Promise.race([read.then((result) => ({ result })), timedOut]);
|
|
11034
|
+
} finally {
|
|
11035
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
11036
|
+
}
|
|
11037
|
+
if (winner === void 0) break;
|
|
11038
|
+
next = winner.result;
|
|
11039
|
+
pendingRead = void 0;
|
|
11040
|
+
}
|
|
10598
11041
|
if (next.done) {
|
|
10599
11042
|
ended = true;
|
|
10600
11043
|
const rest = decoder.decode();
|
|
@@ -10604,9 +11047,11 @@ async function openQoderResponse(response, model, options = {}) {
|
|
|
10604
11047
|
buffered.push(next.value);
|
|
10605
11048
|
bufferedBytes += next.value.byteLength;
|
|
10606
11049
|
inspect(frames.push(decoder.decode(next.value, { stream: true })));
|
|
10607
|
-
if (sawOutput || failure !== void 0 || frames.ended) break;
|
|
11050
|
+
if (sawOutput || sawTerminal || failure !== void 0 || frames.ended) break;
|
|
11051
|
+
if (sawQuiet && graceDeadline === 0) graceDeadline = Date.now() + PEEK_OUTPUT_GRACE_MS;
|
|
10608
11052
|
}
|
|
10609
11053
|
} catch (error) {
|
|
11054
|
+
pendingRead = void 0;
|
|
10610
11055
|
await reader.cancel().catch(() => {});
|
|
10611
11056
|
throw error;
|
|
10612
11057
|
}
|
|
@@ -10625,7 +11070,19 @@ async function openQoderResponse(response, model, options = {}) {
|
|
|
10625
11070
|
...wait === void 0 ? {} : { headers: { "Retry-After": wait } }
|
|
10626
11071
|
});
|
|
10627
11072
|
}
|
|
10628
|
-
const relay = bridgeQoderStream(replaySource(buffered,
|
|
11073
|
+
const relay = bridgeQoderStream(replaySource(buffered, {
|
|
11074
|
+
async read() {
|
|
11075
|
+
const queued = pendingRead;
|
|
11076
|
+
if (queued !== void 0) {
|
|
11077
|
+
pendingRead = void 0;
|
|
11078
|
+
return queued;
|
|
11079
|
+
}
|
|
11080
|
+
return reader.read();
|
|
11081
|
+
},
|
|
11082
|
+
cancel(reason) {
|
|
11083
|
+
return reader.cancel(reason);
|
|
11084
|
+
}
|
|
11085
|
+
}, ended), model, options);
|
|
10629
11086
|
return withRelayStream(new Response(relay, {
|
|
10630
11087
|
status: 200,
|
|
10631
11088
|
headers: { "Content-Type": "text/event-stream" }
|
|
@@ -10777,10 +11234,10 @@ function createQoderGateway(options) {
|
|
|
10777
11234
|
try {
|
|
10778
11235
|
relayed = await openQoderResponse(result.response, model, { onFailure: (error) => {
|
|
10779
11236
|
logger?.warn?.("wtq-pool: qoder relay stream failed mid-flight", error);
|
|
10780
|
-
if (!(error instanceof Error && error.name === "AbortError") && !watcher.signal.aborted)
|
|
10781
|
-
|
|
10782
|
-
|
|
10783
|
-
}
|
|
11237
|
+
if (!(error instanceof Error && error.name === "AbortError") && !watcher.signal.aborted) {
|
|
11238
|
+
const seconds = error.retryAfterSeconds;
|
|
11239
|
+
options.onAttemptFailure?.(credential, { ...typeof seconds === "number" && seconds > 0 ? { retryAfter: String(seconds) } : {} });
|
|
11240
|
+
}
|
|
10784
11241
|
} });
|
|
10785
11242
|
} catch (error) {
|
|
10786
11243
|
if (watcher.signal.aborted || error instanceof Error && error.name === "AbortError") return {
|
|
@@ -10833,11 +11290,7 @@ function createQoderGateway(options) {
|
|
|
10833
11290
|
}
|
|
10834
11291
|
opened = attempt;
|
|
10835
11292
|
if (!rotates(attempt.status, attempt.kind)) break;
|
|
10836
|
-
options.onAttemptFailure?.(credential, {
|
|
10837
|
-
status: attempt.status,
|
|
10838
|
-
...attempt.kind === void 0 ? {} : { kind: attempt.kind },
|
|
10839
|
-
...attempt.retryAfter === void 0 ? {} : { retryAfter: attempt.retryAfter }
|
|
10840
|
-
});
|
|
11293
|
+
options.onAttemptFailure?.(credential, { ...attempt.retryAfter === void 0 ? {} : { retryAfter: attempt.retryAfter } });
|
|
10841
11294
|
if (index < credentials.length - 1) logger?.warn?.(`${LOG_PREFIX}: qoder sign-in failed on ${model} (http ${attempt.status}); rotating`);
|
|
10842
11295
|
}
|
|
10843
11296
|
if (opened === void 0 || !opened.ok) {
|
|
@@ -10964,6 +11417,23 @@ function baseFor(realm) {
|
|
|
10964
11417
|
function originFor(realm) {
|
|
10965
11418
|
return realm === "global" ? GLOBAL_ORIGIN : CN_ORIGIN;
|
|
10966
11419
|
}
|
|
11420
|
+
/**
|
|
11421
|
+
* The browser URL a login start hands the panel.
|
|
11422
|
+
*
|
|
11423
|
+
* The panel opens it without inspecting it, so the scheme is checked here: an
|
|
11424
|
+
* upstream answer that named `javascript:` or `file:` would otherwise be handed
|
|
11425
|
+
* straight to the desktop shell.
|
|
11426
|
+
*/
|
|
11427
|
+
function checkedAuthUrl(value) {
|
|
11428
|
+
let parsed;
|
|
11429
|
+
try {
|
|
11430
|
+
parsed = new URL(value);
|
|
11431
|
+
} catch {
|
|
11432
|
+
throw new Error("workbuddy login start returned an invalid url");
|
|
11433
|
+
}
|
|
11434
|
+
if (parsed.protocol !== "https:") throw new Error("workbuddy login start returned a non-https url");
|
|
11435
|
+
return value;
|
|
11436
|
+
}
|
|
10967
11437
|
/** Browser-shaped headers; `Origin` is the one the endpoints check. */
|
|
10968
11438
|
function loginHeaders(origin) {
|
|
10969
11439
|
return {
|
|
@@ -11018,7 +11488,7 @@ async function startDeviceLogin(realm, fetchImpl = fetch) {
|
|
|
11018
11488
|
if (state === "" || authUrl === "") throw new Error(`workbuddy login start gave no state or url: ${envelope.msg}`);
|
|
11019
11489
|
return {
|
|
11020
11490
|
state,
|
|
11021
|
-
authUrl
|
|
11491
|
+
authUrl: checkedAuthUrl(authUrl)
|
|
11022
11492
|
};
|
|
11023
11493
|
}
|
|
11024
11494
|
/**
|
|
@@ -11185,13 +11655,14 @@ function createSourcePool(host) {
|
|
|
11185
11655
|
return healthy.concat(held, rest);
|
|
11186
11656
|
}
|
|
11187
11657
|
const live = ordered.filter((credential) => !sourceCredentialExpired(credential, now));
|
|
11188
|
-
|
|
11658
|
+
const peek = rotate === "peek";
|
|
11659
|
+
if (rotate !== true && !peek || preferred !== "" || live.length < 2 || host.sourceDistribution(source) !== "round-robin") return ordered;
|
|
11189
11660
|
const healthy = live.filter((credential) => !sourceFailureActive(source, region, labelOf(credential), now));
|
|
11190
11661
|
const held = live.filter((credential) => sourceFailureActive(source, region, labelOf(credential), now));
|
|
11191
11662
|
if (healthy.length < 2) return ordered;
|
|
11192
11663
|
const key = host.sourceRegionKey(source, region);
|
|
11193
11664
|
const step = (sourceRotation.get(key) ?? 0) % healthy.length;
|
|
11194
|
-
sourceRotation.set(key, step + 1);
|
|
11665
|
+
if (!peek) sourceRotation.set(key, step + 1);
|
|
11195
11666
|
const rest = ordered.filter((credential) => sourceCredentialExpired(credential, now));
|
|
11196
11667
|
return healthy.slice(step).concat(healthy.slice(0, step), held, rest);
|
|
11197
11668
|
}
|
|
@@ -11234,8 +11705,8 @@ const SERVICE_ID = "provider-host";
|
|
|
11234
11705
|
/** The two gateways, matching the provider ids this plugin registers. */
|
|
11235
11706
|
const REGIONS = ["cn", "global"];
|
|
11236
11707
|
const PROVIDER_ID_BY_REGION = {
|
|
11237
|
-
cn: "
|
|
11238
|
-
global: "
|
|
11708
|
+
cn: "wtqpool-cn",
|
|
11709
|
+
global: "wtqpool-global"
|
|
11239
11710
|
};
|
|
11240
11711
|
const PROVIDER_NAME_BY_REGION = {
|
|
11241
11712
|
cn: "WTQ Pool (CN)",
|
|
@@ -11296,8 +11767,8 @@ const REGION_PORTS = {
|
|
|
11296
11767
|
*/
|
|
11297
11768
|
const TRAE_REGIONS = ["cn", "ai"];
|
|
11298
11769
|
const TRAE_PROVIDER_ID_BY_REGION = {
|
|
11299
|
-
cn: "
|
|
11300
|
-
ai: "
|
|
11770
|
+
cn: "wtqpool-trae-cn",
|
|
11771
|
+
ai: "wtqpool-trae-ai"
|
|
11301
11772
|
};
|
|
11302
11773
|
const TRAE_PROVIDER_NAME_BY_REGION = {
|
|
11303
11774
|
cn: "WTQ Pool Trae (CN)",
|
|
@@ -11322,8 +11793,8 @@ function activeTraeRegions() {
|
|
|
11322
11793
|
*/
|
|
11323
11794
|
const QODER_REGIONS = ["cn", "global"];
|
|
11324
11795
|
const QODER_PROVIDER_ID_BY_REGION = {
|
|
11325
|
-
cn: "
|
|
11326
|
-
global: "
|
|
11796
|
+
cn: "wtqpool-qoder-cn",
|
|
11797
|
+
global: "wtqpool-qoder-global"
|
|
11327
11798
|
};
|
|
11328
11799
|
const QODER_PROVIDER_NAME_BY_REGION = {
|
|
11329
11800
|
cn: "WTQ Pool Qoder (CN)",
|
|
@@ -11478,6 +11949,14 @@ let settings = {};
|
|
|
11478
11949
|
* a switch the user just flipped.
|
|
11479
11950
|
*/
|
|
11480
11951
|
let settingsRevision = 0;
|
|
11952
|
+
/**
|
|
11953
|
+
* Bumped only by writes this process made, never by a document the host pushed.
|
|
11954
|
+
*
|
|
11955
|
+
* A host announcement that was already in flight when a local save landed is
|
|
11956
|
+
* older than that save. `onHostSettingsChanged` captures this counter before it
|
|
11957
|
+
* queues, and drops the document when a local write overtook it.
|
|
11958
|
+
*/
|
|
11959
|
+
let localSettingsRevision = 0;
|
|
11481
11960
|
let dataPath = "";
|
|
11482
11961
|
/** One runtime per gateway: its shim and catalog. */
|
|
11483
11962
|
const runtimes = /* @__PURE__ */ new Map();
|
|
@@ -11523,6 +12002,8 @@ const gatewayStartFailures = /* @__PURE__ */ new Map();
|
|
|
11523
12002
|
* failed one.
|
|
11524
12003
|
*/
|
|
11525
12004
|
const sourceStartFailures = /* @__PURE__ */ new Map();
|
|
12005
|
+
/** One in-flight source-gateway start per region, shared by overlapping passes. */
|
|
12006
|
+
const sourceGatewayStarts = /* @__PURE__ */ new Map();
|
|
11526
12007
|
/** Provider ids the host has confirmed it is serving, this process's lifetime. */
|
|
11527
12008
|
let publishedIds = /* @__PURE__ */ new Set();
|
|
11528
12009
|
/**
|
|
@@ -11694,7 +12175,8 @@ const STREAK_REPORT_READ_GAP_MS = 1200;
|
|
|
11694
12175
|
const travelAdoptTried = /* @__PURE__ */ new Map();
|
|
11695
12176
|
function log(level, message) {
|
|
11696
12177
|
try {
|
|
11697
|
-
|
|
12178
|
+
const text = redactSecrets(String(message));
|
|
12179
|
+
console.log("[wtq-pool] " + level + ": " + text);
|
|
11698
12180
|
} catch {}
|
|
11699
12181
|
}
|
|
11700
12182
|
/**
|
|
@@ -11767,6 +12249,7 @@ async function saveSettings(patch) {
|
|
|
11767
12249
|
...patch
|
|
11768
12250
|
};
|
|
11769
12251
|
settingsRevision += 1;
|
|
12252
|
+
localSettingsRevision += 1;
|
|
11770
12253
|
return true;
|
|
11771
12254
|
} catch (error) {
|
|
11772
12255
|
log("warn", "could not save settings: " + safeMessage(error));
|
|
@@ -11815,6 +12298,7 @@ async function mutateSettings(key, mutate) {
|
|
|
11815
12298
|
[key]: next
|
|
11816
12299
|
};
|
|
11817
12300
|
settingsRevision += 1;
|
|
12301
|
+
localSettingsRevision += 1;
|
|
11818
12302
|
return true;
|
|
11819
12303
|
} catch (error) {
|
|
11820
12304
|
log("warn", "could not save settings: " + safeMessage(error));
|
|
@@ -11846,15 +12330,34 @@ function resetDiscoveryCaches() {
|
|
|
11846
12330
|
* reach the picker or the user still sees the models they just disabled.
|
|
11847
12331
|
*/
|
|
11848
12332
|
async function onHostSettingsChanged(next) {
|
|
11849
|
-
if (serviceStopped) return;
|
|
11850
12333
|
if (next === null || typeof next !== "object" || Array.isArray(next)) return false;
|
|
11851
|
-
const
|
|
11852
|
-
|
|
11853
|
-
|
|
11854
|
-
|
|
11855
|
-
|
|
11856
|
-
|
|
11857
|
-
|
|
12334
|
+
const localRevision = localSettingsRevision;
|
|
12335
|
+
return enqueueWrite(async () => {
|
|
12336
|
+
if (serviceStopped) return false;
|
|
12337
|
+
const before = settings;
|
|
12338
|
+
if (localSettingsRevision !== localRevision) {
|
|
12339
|
+
if (!await adoptHostSettings()) {
|
|
12340
|
+
scheduleRefresh("settings");
|
|
12341
|
+
return false;
|
|
12342
|
+
}
|
|
12343
|
+
} else {
|
|
12344
|
+
settings = next;
|
|
12345
|
+
settingsRevision += 1;
|
|
12346
|
+
}
|
|
12347
|
+
const toggled = Object.values(SOURCE_SETTING_KEYS).some((key) => Object.hasOwn(settings, key) && before[key] !== settings[key]);
|
|
12348
|
+
if (toggled) resetDiscoveryCaches();
|
|
12349
|
+
await applySettingsEverywhere(toggled);
|
|
12350
|
+
return true;
|
|
12351
|
+
});
|
|
12352
|
+
}
|
|
12353
|
+
/**
|
|
12354
|
+
* Apply the settings document already in `settings` to everything downstream.
|
|
12355
|
+
*
|
|
12356
|
+
* Shared by the host-driven change above and the panel's own switches, which
|
|
12357
|
+
* write the key first and then ask for the same reconciliation with no new
|
|
12358
|
+
* document to merge.
|
|
12359
|
+
*/
|
|
12360
|
+
async function applySettingsEverywhere(toggled) {
|
|
11858
12361
|
applySettingsToCore();
|
|
11859
12362
|
traeAccountRows = traeAccountRows.filter((row) => regionEnabled("trae", row.region));
|
|
11860
12363
|
qoderAccountRows = qoderAccountRows.filter((row) => regionEnabled("qoder", row.region));
|
|
@@ -11929,6 +12432,10 @@ function autoCheckinEnabled() {
|
|
|
11929
12432
|
* restart after the morning hour forgot every slot and re-ran the whole pass.
|
|
11930
12433
|
* The file holds one array per campaign day, the same shape the desktop twin
|
|
11931
12434
|
* writes, so the two engines cannot disagree about what a day's record is.
|
|
12435
|
+
* `_qoderRetryAt` is metadata beside those arrays: Qoder's deferred round can
|
|
12436
|
+
* open hours after the pass that scheduled it, and a reload before then used to
|
|
12437
|
+
* lose the day's Qoder credits. A key that is not an array is ignored by the
|
|
12438
|
+
* day reader, so the file stays compatible with the twin.
|
|
11932
12439
|
*/
|
|
11933
12440
|
const CHECKIN_SLOTS_FILE = "checkin-slots.json";
|
|
11934
12441
|
/**
|
|
@@ -11942,6 +12449,7 @@ const CHECKIN_SLOTS_FILE = "checkin-slots.json";
|
|
|
11942
12449
|
*/
|
|
11943
12450
|
function loadCheckinSlots() {
|
|
11944
12451
|
autoCheckinSlots.clear();
|
|
12452
|
+
qoderRetryAt = 0;
|
|
11945
12453
|
if (dataPath === "") return;
|
|
11946
12454
|
try {
|
|
11947
12455
|
const parsed = JSON.parse(fs$1.readFileSync(path.join(dataPath, CHECKIN_SLOTS_FILE), "utf8"));
|
|
@@ -11950,6 +12458,9 @@ function loadCheckinSlots() {
|
|
|
11950
12458
|
if (!Array.isArray(slots)) continue;
|
|
11951
12459
|
for (const slot of slots) if (typeof slot === "string" && slot !== "") autoCheckinSlots.add(slot);
|
|
11952
12460
|
}
|
|
12461
|
+
const retry = parsed._qoderRetryAt;
|
|
12462
|
+
const now = Date.now();
|
|
12463
|
+
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
12464
|
} catch {}
|
|
11954
12465
|
}
|
|
11955
12466
|
/**
|
|
@@ -11970,6 +12481,7 @@ function saveCheckinSlots() {
|
|
|
11970
12481
|
}
|
|
11971
12482
|
const keep = Object.keys(byDay).sort().slice(-3);
|
|
11972
12483
|
for (const day of Object.keys(byDay)) if (!keep.includes(day)) delete byDay[day];
|
|
12484
|
+
if (qoderRetryAt > 0) byDay._qoderRetryAt = qoderRetryAt;
|
|
11973
12485
|
const target = path.join(dataPath, CHECKIN_SLOTS_FILE);
|
|
11974
12486
|
const staging = target + ".tmp";
|
|
11975
12487
|
try {
|
|
@@ -12586,15 +13098,18 @@ function warmingGatewayIds() {
|
|
|
12586
13098
|
if (gatewayStartFailures.has(region)) continue;
|
|
12587
13099
|
if (runtime === void 0 || runtime.connecting !== null) ids.add(PROVIDER_ID_BY_REGION[region]);
|
|
12588
13100
|
}
|
|
12589
|
-
for (const [gateways, regions, idByRegion] of [[
|
|
13101
|
+
for (const [source, gateways, regions, idByRegion] of [[
|
|
13102
|
+
"trae",
|
|
12590
13103
|
traeGateways,
|
|
12591
13104
|
activeTraeRegions(),
|
|
12592
13105
|
TRAE_PROVIDER_ID_BY_REGION
|
|
12593
13106
|
], [
|
|
13107
|
+
"qoder",
|
|
12594
13108
|
qoderGateways,
|
|
12595
13109
|
activeQoderRegions(),
|
|
12596
13110
|
QODER_PROVIDER_ID_BY_REGION
|
|
12597
13111
|
]]) for (const region of regions) {
|
|
13112
|
+
if (sourceStartFailures.has(source + ":" + region)) continue;
|
|
12598
13113
|
const entry = gateways.get(region);
|
|
12599
13114
|
if (entry === void 0 || entry.gateway.models().length === 0 && entry.lastError === "") ids.add(idByRegion[region]);
|
|
12600
13115
|
}
|
|
@@ -12620,6 +13135,7 @@ async function warmSourceDirectory(entry, signal) {
|
|
|
12620
13135
|
entry.lastError = entry.gateway.models().length > 0 ? "" : "directory unavailable: " + safeMessage(error);
|
|
12621
13136
|
if (entry.lastError !== "") log("warn", "[" + entry.source + ":" + entry.region + "] " + entry.lastError);
|
|
12622
13137
|
}
|
|
13138
|
+
entry.warmSettled = true;
|
|
12623
13139
|
if (entry.lastError === "" && entry.gateway.models().length > 0) syncDeclaration();
|
|
12624
13140
|
return entry.lastError === "";
|
|
12625
13141
|
}
|
|
@@ -12721,7 +13237,8 @@ async function createTraeRuntime(region) {
|
|
|
12721
13237
|
portFallback: bound !== preferred,
|
|
12722
13238
|
preferredPort: preferred,
|
|
12723
13239
|
lastError: "",
|
|
12724
|
-
source: "trae"
|
|
13240
|
+
source: "trae",
|
|
13241
|
+
warmSettled: false
|
|
12725
13242
|
};
|
|
12726
13243
|
if (entry.portFallback) log("warn", "[trae:" + region + "] preferred port " + preferred + " is held by another process; serving this session on port " + gateway.port());
|
|
12727
13244
|
warmSourceDirectoryAtStartup(entry, warmAbort.signal).catch((error) => log("warn", "[trae:" + region + "] directory warm-up failed: " + safeMessage(error)));
|
|
@@ -12733,6 +13250,7 @@ async function reconcileTraeGateways() {
|
|
|
12733
13250
|
if (!stillLoaded(generation) || serviceStopped) return;
|
|
12734
13251
|
const active = activeTraeRegions();
|
|
12735
13252
|
for (const [region, entry] of Array.from(traeGateways)) {
|
|
13253
|
+
if (!stillLoaded(generation) || serviceStopped) return;
|
|
12736
13254
|
if (active.includes(region)) continue;
|
|
12737
13255
|
traeGateways.delete(region);
|
|
12738
13256
|
sourceStartFailures.delete("trae:" + region);
|
|
@@ -12743,17 +13261,30 @@ async function reconcileTraeGateways() {
|
|
|
12743
13261
|
}
|
|
12744
13262
|
}
|
|
12745
13263
|
for (const region of active) {
|
|
13264
|
+
if (!stillLoaded(generation) || serviceStopped) return;
|
|
12746
13265
|
if (traeGateways.has(region)) continue;
|
|
13266
|
+
const key = "trae:" + region;
|
|
13267
|
+
const pending = sourceGatewayStarts.get(key);
|
|
13268
|
+
if (pending !== void 0) {
|
|
13269
|
+
await pending.catch(() => {});
|
|
13270
|
+
continue;
|
|
13271
|
+
}
|
|
13272
|
+
const starting = createTraeRuntime(region);
|
|
13273
|
+
sourceGatewayStarts.set(key, starting);
|
|
12747
13274
|
try {
|
|
12748
|
-
const entry = await
|
|
13275
|
+
const entry = await starting;
|
|
12749
13276
|
if (!stillLoaded(generation) || !activeTraeRegions().includes(region) || traeGateways.has(region)) await entry.gateway.close();
|
|
12750
13277
|
else {
|
|
12751
13278
|
traeGateways.set(region, entry);
|
|
12752
|
-
sourceStartFailures.delete(
|
|
13279
|
+
sourceStartFailures.delete(key);
|
|
12753
13280
|
}
|
|
12754
13281
|
} catch (error) {
|
|
12755
|
-
|
|
12756
|
-
|
|
13282
|
+
if (stillLoaded(generation)) {
|
|
13283
|
+
sourceStartFailures.set(key, safeMessage(error));
|
|
13284
|
+
log("warn", "[trae:" + region + "] gateway could not start: " + safeMessage(error));
|
|
13285
|
+
}
|
|
13286
|
+
} finally {
|
|
13287
|
+
if (sourceGatewayStarts.get(key) === starting) sourceGatewayStarts.delete(key);
|
|
12757
13288
|
}
|
|
12758
13289
|
}
|
|
12759
13290
|
}
|
|
@@ -12862,7 +13393,8 @@ async function createQoderRuntime(region) {
|
|
|
12862
13393
|
portFallback: bound !== preferred,
|
|
12863
13394
|
preferredPort: preferred,
|
|
12864
13395
|
lastError: "",
|
|
12865
|
-
source: "qoder"
|
|
13396
|
+
source: "qoder",
|
|
13397
|
+
warmSettled: false
|
|
12866
13398
|
};
|
|
12867
13399
|
if (entry.portFallback) log("warn", "[qoder:" + region + "] preferred port " + preferred + " is held by another process; serving this session on port " + gateway.port());
|
|
12868
13400
|
warmSourceDirectoryAtStartup(entry, warmAbort.signal).catch((error) => log("warn", "[qoder:" + region + "] directory warm-up failed: " + safeMessage(error)));
|
|
@@ -12874,6 +13406,7 @@ async function reconcileQoderGateways() {
|
|
|
12874
13406
|
if (!stillLoaded(generation) || serviceStopped) return;
|
|
12875
13407
|
const active = activeQoderRegions();
|
|
12876
13408
|
for (const [region, entry] of Array.from(qoderGateways)) {
|
|
13409
|
+
if (!stillLoaded(generation) || serviceStopped) return;
|
|
12877
13410
|
if (active.includes(region)) continue;
|
|
12878
13411
|
qoderGateways.delete(region);
|
|
12879
13412
|
sourceStartFailures.delete("qoder:" + region);
|
|
@@ -12884,17 +13417,30 @@ async function reconcileQoderGateways() {
|
|
|
12884
13417
|
}
|
|
12885
13418
|
}
|
|
12886
13419
|
for (const region of active) {
|
|
13420
|
+
if (!stillLoaded(generation) || serviceStopped) return;
|
|
12887
13421
|
if (qoderGateways.has(region)) continue;
|
|
13422
|
+
const key = "qoder:" + region;
|
|
13423
|
+
const pending = sourceGatewayStarts.get(key);
|
|
13424
|
+
if (pending !== void 0) {
|
|
13425
|
+
await pending.catch(() => {});
|
|
13426
|
+
continue;
|
|
13427
|
+
}
|
|
13428
|
+
const starting = createQoderRuntime(region);
|
|
13429
|
+
sourceGatewayStarts.set(key, starting);
|
|
12888
13430
|
try {
|
|
12889
|
-
const entry = await
|
|
13431
|
+
const entry = await starting;
|
|
12890
13432
|
if (!stillLoaded(generation) || !activeQoderRegions().includes(region) || qoderGateways.has(region)) await entry.gateway.close();
|
|
12891
13433
|
else {
|
|
12892
13434
|
qoderGateways.set(region, entry);
|
|
12893
|
-
sourceStartFailures.delete(
|
|
13435
|
+
sourceStartFailures.delete(key);
|
|
12894
13436
|
}
|
|
12895
13437
|
} catch (error) {
|
|
12896
|
-
|
|
12897
|
-
|
|
13438
|
+
if (stillLoaded(generation)) {
|
|
13439
|
+
sourceStartFailures.set(key, safeMessage(error));
|
|
13440
|
+
log("warn", "[qoder:" + region + "] gateway could not start: " + safeMessage(error));
|
|
13441
|
+
}
|
|
13442
|
+
} finally {
|
|
13443
|
+
if (sourceGatewayStarts.get(key) === starting) sourceGatewayStarts.delete(key);
|
|
12898
13444
|
}
|
|
12899
13445
|
}
|
|
12900
13446
|
}
|
|
@@ -13038,8 +13584,9 @@ function startRuntimeOnce(region) {
|
|
|
13038
13584
|
* is every later pass's only re-entry test, so a stopped entry there would take
|
|
13039
13585
|
* the region out until the next teardown.
|
|
13040
13586
|
*
|
|
13041
|
-
* This host's `onLoad` clears both maps, so it never shares a bind across a
|
|
13042
|
-
* PI-Desktop
|
|
13587
|
+
* This host's `onLoad` clears both maps, so it never shares a bind across a
|
|
13588
|
+
* reload; PI-Desktop clears them too and relies on this same ordering within one
|
|
13589
|
+
* activation.
|
|
13043
13590
|
*/
|
|
13044
13591
|
async function settleStartedRuntime(region, runtime, unwanted) {
|
|
13045
13592
|
const held = runtimes.get(region);
|
|
@@ -13072,8 +13619,10 @@ async function startRuntimes() {
|
|
|
13072
13619
|
try {
|
|
13073
13620
|
await settleStartedRuntime(region, await startRuntimeOnce(region), !stillLoaded(generation) || !activeRegions().includes(region));
|
|
13074
13621
|
} catch (error) {
|
|
13075
|
-
|
|
13076
|
-
|
|
13622
|
+
if (stillLoaded(generation)) {
|
|
13623
|
+
gatewayStartFailures.set(region, safeMessage(error));
|
|
13624
|
+
log("warn", "[workbuddy:" + region + "] gateway could not start: " + safeMessage(error));
|
|
13625
|
+
}
|
|
13077
13626
|
}
|
|
13078
13627
|
}));
|
|
13079
13628
|
}
|
|
@@ -13187,7 +13736,11 @@ function refreshNeeded() {
|
|
|
13187
13736
|
*/
|
|
13188
13737
|
function cooldownPending() {
|
|
13189
13738
|
const now = Date.now();
|
|
13190
|
-
for (const account of core.pool.list())
|
|
13739
|
+
for (const account of core.pool.list()) {
|
|
13740
|
+
if (account.cooldownUntilMs <= now) continue;
|
|
13741
|
+
if (core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
|
|
13742
|
+
return true;
|
|
13743
|
+
}
|
|
13191
13744
|
return false;
|
|
13192
13745
|
}
|
|
13193
13746
|
/** True while any pool account's cached billing answers are missing or old. */
|
|
@@ -13197,6 +13750,7 @@ function probesStale() {
|
|
|
13197
13750
|
if (account.cooldownUntilMs > now || core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
|
|
13198
13751
|
const cached = probeCache.get(account.id);
|
|
13199
13752
|
if (cached === void 0 || now - cached.atMs >= PROBE_TTL_MS) return true;
|
|
13753
|
+
if (cached.checkinOnly === true) return true;
|
|
13200
13754
|
}
|
|
13201
13755
|
return false;
|
|
13202
13756
|
}
|
|
@@ -13676,7 +14230,9 @@ function applyProbe(row, probe) {
|
|
|
13676
14230
|
async function accountProbe(account, allowNetwork, checkinOnly = false) {
|
|
13677
14231
|
const cached = probeCache.get(account.id);
|
|
13678
14232
|
if (allowNetwork !== true) return cached === void 0 ? { pending: true } : cached.value;
|
|
13679
|
-
|
|
14233
|
+
const cachedFresh = cached !== void 0 && Date.now() - cached.atMs < PROBE_TTL_MS;
|
|
14234
|
+
const cachedHasCredits = cached !== void 0 && (cached.value.credits !== void 0 || cached.value.creditsError !== void 0);
|
|
14235
|
+
if (cachedFresh && (checkinOnly || cached.checkinOnly !== true && cachedHasCredits)) return cached.value;
|
|
13680
14236
|
if (signInRefused(account)) return {};
|
|
13681
14237
|
const value = {};
|
|
13682
14238
|
if (!checkinOnly) {
|
|
@@ -13700,6 +14256,7 @@ async function accountProbe(account, allowNetwork, checkinOnly = false) {
|
|
|
13700
14256
|
}
|
|
13701
14257
|
if (value.credits !== void 0 && typeof value.credits.total === "number") core.pool.setCreditBalance(account.id, value.credits.total, value.credits.nearestExpiryMs);
|
|
13702
14258
|
}
|
|
14259
|
+
const checkinStartedAt = Date.now();
|
|
13703
14260
|
try {
|
|
13704
14261
|
const checkin = await core.pool.readAfterRefresh(account.id, (credential) => core.client.fetchCheckinStatus(credential));
|
|
13705
14262
|
value.checkin = {
|
|
@@ -13715,15 +14272,54 @@ async function accountProbe(account, allowNetwork, checkinOnly = false) {
|
|
|
13715
14272
|
} catch (error) {
|
|
13716
14273
|
value.checkinError = safeMessage(error);
|
|
13717
14274
|
}
|
|
14275
|
+
const latest = probeCache.get(account.id);
|
|
14276
|
+
if (latest !== cached) {
|
|
14277
|
+
if (latest === void 0) return { pending: true };
|
|
14278
|
+
if (!checkinOnly && latest.checkinOnly === true && (value.credits !== void 0 || value.creditsError !== void 0)) {
|
|
14279
|
+
const merged = { ...latest.value };
|
|
14280
|
+
if (value.credits !== void 0) {
|
|
14281
|
+
merged.credits = value.credits;
|
|
14282
|
+
delete merged.creditsError;
|
|
14283
|
+
}
|
|
14284
|
+
if (value.creditsError !== void 0) {
|
|
14285
|
+
merged.creditsError = value.creditsError;
|
|
14286
|
+
delete merged.credits;
|
|
14287
|
+
}
|
|
14288
|
+
if (latest.atMs <= checkinStartedAt) {
|
|
14289
|
+
if (value.checkin !== void 0) {
|
|
14290
|
+
merged.checkin = value.checkin;
|
|
14291
|
+
delete merged.checkinError;
|
|
14292
|
+
}
|
|
14293
|
+
if (value.checkinError !== void 0) {
|
|
14294
|
+
merged.checkinError = value.checkinError;
|
|
14295
|
+
delete merged.checkin;
|
|
14296
|
+
}
|
|
14297
|
+
}
|
|
14298
|
+
probeCache.set(account.id, {
|
|
14299
|
+
atMs: Date.now(),
|
|
14300
|
+
value: merged,
|
|
14301
|
+
checkinOnly: false
|
|
14302
|
+
});
|
|
14303
|
+
return merged;
|
|
14304
|
+
}
|
|
14305
|
+
return latest.value;
|
|
14306
|
+
}
|
|
14307
|
+
const stored = checkinOnly && cached !== void 0 ? {
|
|
14308
|
+
...cached.value,
|
|
14309
|
+
...value
|
|
14310
|
+
} : value;
|
|
14311
|
+
if (value.checkin !== void 0) delete stored.checkinError;
|
|
14312
|
+
if (value.checkinError !== void 0) delete stored.checkin;
|
|
13718
14313
|
probeCache.set(account.id, {
|
|
13719
14314
|
atMs: Date.now(),
|
|
13720
|
-
value
|
|
14315
|
+
value: stored,
|
|
14316
|
+
checkinOnly
|
|
13721
14317
|
});
|
|
13722
14318
|
if (probeCache.size > core.pool.list().length) {
|
|
13723
14319
|
const live = new Set(core.pool.list().map((item) => item.id));
|
|
13724
14320
|
for (const id of Array.from(probeCache.keys())) if (!live.has(id)) probeCache.delete(id);
|
|
13725
14321
|
}
|
|
13726
|
-
return
|
|
14322
|
+
return stored;
|
|
13727
14323
|
}
|
|
13728
14324
|
/**
|
|
13729
14325
|
* Per-gateway roster warnings, for gateways that have one right now.
|
|
@@ -13892,7 +14488,6 @@ async function statusDocument(options) {
|
|
|
13892
14488
|
modelCap: MAX_MODELS,
|
|
13893
14489
|
distribution: distributionSetting(),
|
|
13894
14490
|
showComposerPoints: settings.showComposerPoints === true,
|
|
13895
|
-
replacedClientName: replacedClientName() ?? null,
|
|
13896
14491
|
autoCheckin: {
|
|
13897
14492
|
enabled: autoCheckinEnabled(),
|
|
13898
14493
|
hours: checkinHours(),
|
|
@@ -13982,9 +14577,10 @@ function samePublishedAddress(a, b) {
|
|
|
13982
14577
|
/**
|
|
13983
14578
|
* True when the address that was published is not the address this run bound.
|
|
13984
14579
|
*
|
|
13985
|
-
*
|
|
13986
|
-
*
|
|
13987
|
-
*
|
|
14580
|
+
* The declaration is republished after a port fallback, so the published address
|
|
14581
|
+
* is the test: a row that follows the actual port is healthy, while one that
|
|
14582
|
+
* still names the preferred port is drift. Checking `portFallback` itself marked
|
|
14583
|
+
* a correctly republished row as broken.
|
|
13988
14584
|
*
|
|
13989
14585
|
* A gateway whose start failed counts as drift too, and for the same reason: it
|
|
13990
14586
|
* has no shim at all, so the address the host registered is refused. Skipping
|
|
@@ -13996,7 +14592,6 @@ function samePublishedAddress(a, b) {
|
|
|
13996
14592
|
*/
|
|
13997
14593
|
function addressDrift() {
|
|
13998
14594
|
for (const region of activeRegions()) {
|
|
13999
|
-
if (runtimes.get(region)?.portFallback === true) return true;
|
|
14000
14595
|
const published = declaredBaseUrl(region);
|
|
14001
14596
|
const bound = shimInfo(region).baseUrl;
|
|
14002
14597
|
if (bound === void 0) {
|
|
@@ -14006,12 +14601,10 @@ function addressDrift() {
|
|
|
14006
14601
|
if (published !== void 0 && published !== bound) return true;
|
|
14007
14602
|
}
|
|
14008
14603
|
for (const entry of Array.from(traeGateways.values())) {
|
|
14009
|
-
if (entry.portFallback === true) return true;
|
|
14010
14604
|
const published = declaredSourceBaseUrl(entry, TRAE_PROVIDER_ID_BY_REGION);
|
|
14011
14605
|
if (published !== void 0 && !samePublishedAddress(published, entry.baseUrl)) return true;
|
|
14012
14606
|
}
|
|
14013
14607
|
for (const entry of Array.from(qoderGateways.values())) {
|
|
14014
|
-
if (entry.portFallback === true) return true;
|
|
14015
14608
|
const published = declaredSourceBaseUrl(entry, QODER_PROVIDER_ID_BY_REGION);
|
|
14016
14609
|
if (published !== void 0 && !samePublishedAddress(published, entry.baseUrl)) return true;
|
|
14017
14610
|
}
|
|
@@ -14050,10 +14643,19 @@ async function traeDoctorDetail() {
|
|
|
14050
14643
|
}
|
|
14051
14644
|
const parts = Object.entries(byRegion).map(([region, count]) => `${region} x${count}`).join(", ");
|
|
14052
14645
|
const failures = found.failures.length > 0 ? `; ${found.failures.length} unreadable file(s)` : "";
|
|
14053
|
-
const
|
|
14646
|
+
const servedRegions = activeTraeRegions();
|
|
14647
|
+
const served = servedRegions.map((region) => `${region}: ${traeDeclarationModels(region).length} model(s)`).join(", ");
|
|
14648
|
+
const stillReading = [];
|
|
14649
|
+
const problems = [];
|
|
14650
|
+
for (const region of servedRegions) {
|
|
14651
|
+
const entry = traeGateways.get(region);
|
|
14652
|
+
if (entry === void 0 && !byRegion[region]) problems.push(`${region}: no sign-in for this region`);
|
|
14653
|
+
else if (entry === void 0 || entry.warmSettled !== true) stillReading.push(region);
|
|
14654
|
+
else if (traeDeclarationModels(region).length === 0) problems.push(entry.lastError !== "" ? `${region}: ${entry.lastError}` : `${region}: no models selected`);
|
|
14655
|
+
}
|
|
14054
14656
|
return {
|
|
14055
|
-
ok:
|
|
14056
|
-
detail: `on; ${found.credentials.length} account(s) (${parts})${failures}; serving ${served}`
|
|
14657
|
+
ok: problems.length === 0,
|
|
14658
|
+
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
14659
|
};
|
|
14058
14660
|
} catch (error) {
|
|
14059
14661
|
return {
|
|
@@ -14078,10 +14680,19 @@ async function qoderDoctorDetail() {
|
|
|
14078
14680
|
for (const credential of found.credentials) byRegion[credential.region] = (byRegion[credential.region] || 0) + 1;
|
|
14079
14681
|
const parts = Object.entries(byRegion).map(([region, count]) => `${region} x${count}`).join(", ");
|
|
14080
14682
|
const failures = found.failures.length > 0 ? `; ${found.failures.length} unreadable app dir(s)` : "";
|
|
14081
|
-
const
|
|
14683
|
+
const servedRegions = activeQoderRegions();
|
|
14684
|
+
const served = servedRegions.map((region) => `${region}: ${qoderDeclarationModels(region).length} model(s)`).join(", ");
|
|
14685
|
+
const stillReading = [];
|
|
14686
|
+
const problems = [];
|
|
14687
|
+
for (const region of servedRegions) {
|
|
14688
|
+
const entry = qoderGateways.get(region);
|
|
14689
|
+
if (entry === void 0 && !byRegion[region]) problems.push(`${region}: no sign-in for this region`);
|
|
14690
|
+
else if (entry === void 0 || entry.warmSettled !== true) stillReading.push(region);
|
|
14691
|
+
else if (qoderDeclarationModels(region).length === 0) problems.push(entry.lastError !== "" ? `${region}: ${entry.lastError}` : `${region}: no models selected`);
|
|
14692
|
+
}
|
|
14082
14693
|
return {
|
|
14083
|
-
ok:
|
|
14084
|
-
detail: `on; ${found.credentials.length} account(s) (${parts})${failures}; serving ${served}`
|
|
14694
|
+
ok: problems.length === 0,
|
|
14695
|
+
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
14696
|
};
|
|
14086
14697
|
} catch (error) {
|
|
14087
14698
|
return {
|
|
@@ -14134,36 +14745,56 @@ async function doctorReport() {
|
|
|
14134
14745
|
push(label + ": models", regionModels.length > 0, regionModels.length + " model(s) in the catalog");
|
|
14135
14746
|
push(label + ": declared", declared, declared ? "registered with the running host" : runtime?.lastError || runtime?.lastWarning || "this gateway is not published yet");
|
|
14136
14747
|
}
|
|
14137
|
-
for (const [gateways, idByRegion, nameByRegion, ports] of [
|
|
14748
|
+
for (const [gateways, idByRegion, nameByRegion, ports, modelsOf] of [
|
|
14138
14749
|
[
|
|
14139
14750
|
runtimes,
|
|
14140
14751
|
PROVIDER_ID_BY_REGION,
|
|
14141
14752
|
PROVIDER_NAME_BY_REGION,
|
|
14142
|
-
REGION_PORTS
|
|
14753
|
+
REGION_PORTS,
|
|
14754
|
+
declarationModels
|
|
14143
14755
|
],
|
|
14144
14756
|
[
|
|
14145
14757
|
traeGateways,
|
|
14146
14758
|
TRAE_PROVIDER_ID_BY_REGION,
|
|
14147
14759
|
TRAE_PROVIDER_NAME_BY_REGION,
|
|
14148
|
-
TRAE_PORTS
|
|
14760
|
+
TRAE_PORTS,
|
|
14761
|
+
traeDeclarationModels
|
|
14149
14762
|
],
|
|
14150
14763
|
[
|
|
14151
14764
|
qoderGateways,
|
|
14152
14765
|
QODER_PROVIDER_ID_BY_REGION,
|
|
14153
14766
|
QODER_PROVIDER_NAME_BY_REGION,
|
|
14154
|
-
QODER_PORTS
|
|
14767
|
+
QODER_PORTS,
|
|
14768
|
+
qoderDeclarationModels
|
|
14155
14769
|
]
|
|
14156
14770
|
]) for (const entry of Array.from(gateways.values())) {
|
|
14157
14771
|
const published = declaredSourceBaseUrl(entry, idByRegion);
|
|
14158
14772
|
const bound = entry.baseUrl;
|
|
14159
14773
|
const label = nameByRegion[entry.region];
|
|
14160
|
-
if (
|
|
14774
|
+
if (bound === void 0) continue;
|
|
14775
|
+
if (published === void 0) {
|
|
14776
|
+
if (entry.warmSettled !== void 0 ? entry.warmSettled !== true : warmingGatewayIds().has(idByRegion[entry.region])) {
|
|
14777
|
+
push(label + ": published address", true, "still reading its model roster");
|
|
14778
|
+
continue;
|
|
14779
|
+
}
|
|
14780
|
+
if (entry.lastError) {
|
|
14781
|
+
push(label + ": published address", false, entry.lastError);
|
|
14782
|
+
continue;
|
|
14783
|
+
}
|
|
14784
|
+
if (modelsOf(entry.region).length === 0) {
|
|
14785
|
+
push(label + ": published address", true, "no callable models selected; nothing to publish");
|
|
14786
|
+
continue;
|
|
14787
|
+
}
|
|
14788
|
+
push(label + ": published address", false, "this gateway is running but its provider row is not published in this run's declaration - restart the plugin");
|
|
14789
|
+
continue;
|
|
14790
|
+
}
|
|
14161
14791
|
const fallback = entry.portFallback === true;
|
|
14162
|
-
if (samePublishedAddress(published, bound)
|
|
14163
|
-
|
|
14792
|
+
if (samePublishedAddress(published, bound)) {
|
|
14793
|
+
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 + ")";
|
|
14794
|
+
push(label + ": published address", true, detail);
|
|
14164
14795
|
continue;
|
|
14165
14796
|
}
|
|
14166
|
-
const detail =
|
|
14797
|
+
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
14798
|
push(label + ": published address", false, detail);
|
|
14168
14799
|
}
|
|
14169
14800
|
for (const [source, nameByRegion, regions] of [[
|
|
@@ -14289,6 +14920,41 @@ function parseSelection(body) {
|
|
|
14289
14920
|
return out;
|
|
14290
14921
|
}
|
|
14291
14922
|
/**
|
|
14923
|
+
* The model ids one save's page could display, or undefined for an older panel.
|
|
14924
|
+
*
|
|
14925
|
+
* Only used to tell "the page did not show this id" from "the user removed it",
|
|
14926
|
+
* so junk entries are skipped rather than failing the save.
|
|
14927
|
+
*/
|
|
14928
|
+
function parseKnownModelIds(value) {
|
|
14929
|
+
if (!Array.isArray(value)) return void 0;
|
|
14930
|
+
const ids = /* @__PURE__ */ new Set();
|
|
14931
|
+
for (const entry of value) if (typeof entry === "string" && entry !== "" && entry.length <= MAX_MODEL_ID_LENGTH) ids.add(entry);
|
|
14932
|
+
return ids;
|
|
14933
|
+
}
|
|
14934
|
+
/**
|
|
14935
|
+
* Keep the stored selection of models the saving page could not display.
|
|
14936
|
+
*
|
|
14937
|
+
* A roster read can be partial: the static fallback stands until the live list
|
|
14938
|
+
* arrives, and a source directory can answer with fewer rows than it will carry
|
|
14939
|
+
* later. Saving such a page used to replace the whole selection, so every model
|
|
14940
|
+
* outside the snapshot lost its tick and its per-model edits. Ids the page did
|
|
14941
|
+
* show are authoritative - an absent override there means the user cleared it -
|
|
14942
|
+
* while ids it never showed keep what was stored.
|
|
14943
|
+
*/
|
|
14944
|
+
function mergeSelectionForPartialRoster(selection, prior, known) {
|
|
14945
|
+
if (known === void 0) return selection;
|
|
14946
|
+
const carriedEnabled = (Array.isArray(prior.enabledModelIds) ? prior.enabledModelIds : []).filter((id) => !known.has(id));
|
|
14947
|
+
const priorOverrides = prior.overrides !== null && typeof prior.overrides === "object" ? prior.overrides : {};
|
|
14948
|
+
const overrides = Object.create(null);
|
|
14949
|
+
for (const [id, entry] of Object.entries(priorOverrides)) if (!known.has(id)) overrides[id] = { ...entry };
|
|
14950
|
+
const merged = { ...selection };
|
|
14951
|
+
if (Array.isArray(selection.enabledModelIds)) merged.enabledModelIds = [.../* @__PURE__ */ new Set([...selection.enabledModelIds, ...carriedEnabled])].slice(0, MAX_STORED_MODEL_IDS);
|
|
14952
|
+
if (selection.overrides !== void 0) for (const [id, entry] of Object.entries(selection.overrides)) overrides[id] = entry;
|
|
14953
|
+
if (Object.keys(overrides).length > 0) merged.overrides = overrides;
|
|
14954
|
+
else delete merged.overrides;
|
|
14955
|
+
return merged;
|
|
14956
|
+
}
|
|
14957
|
+
/**
|
|
14292
14958
|
* Validate one model's override.
|
|
14293
14959
|
*
|
|
14294
14960
|
* Every field is optional, and a value that is present must be usable: the host
|
|
@@ -14351,9 +15017,11 @@ async function onPanelInvoke(channel, payload) {
|
|
|
14351
15017
|
refreshing: false,
|
|
14352
15018
|
stale: true
|
|
14353
15019
|
};
|
|
15020
|
+
const stillNeeded = refreshNeeded();
|
|
15021
|
+
if (stillNeeded) scheduleRefresh("panel");
|
|
14354
15022
|
return {
|
|
14355
15023
|
...refreshed,
|
|
14356
|
-
refreshing:
|
|
15024
|
+
refreshing: stillNeeded
|
|
14357
15025
|
};
|
|
14358
15026
|
}
|
|
14359
15027
|
const document = await statusDocument({ allowNetwork: false });
|
|
@@ -14401,12 +15069,21 @@ async function onPanelInvoke(channel, payload) {
|
|
|
14401
15069
|
if (activeRegions().length > 0) await settle(core.pool.scan());
|
|
14402
15070
|
await settle(startRuntimes());
|
|
14403
15071
|
await settle(refreshSourceAccounts());
|
|
15072
|
+
await settle(reconcileTraeGateways());
|
|
15073
|
+
await settle(reconcileQoderGateways());
|
|
15074
|
+
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
15075
|
await settle(Promise.all(Array.from(runtimes.values()).map((runtime) => refreshRuntime(runtime, "rescan", true))));
|
|
14405
15076
|
syncDeclaration();
|
|
14406
|
-
|
|
15077
|
+
const document = await statusDocument({
|
|
14407
15078
|
allowNetwork: true,
|
|
14408
15079
|
budgetMs: left()
|
|
14409
15080
|
});
|
|
15081
|
+
const refreshing = refreshNeeded();
|
|
15082
|
+
if (refreshing) scheduleRefresh("panel");
|
|
15083
|
+
return {
|
|
15084
|
+
...document,
|
|
15085
|
+
refreshing
|
|
15086
|
+
};
|
|
14410
15087
|
}
|
|
14411
15088
|
case "xd.resetCooldowns":
|
|
14412
15089
|
core.pool.resetCooldowns();
|
|
@@ -14448,9 +15125,9 @@ async function onPanelInvoke(channel, payload) {
|
|
|
14448
15125
|
result: claim
|
|
14449
15126
|
};
|
|
14450
15127
|
};
|
|
14451
|
-
const answered = await settleWithin(work()
|
|
15128
|
+
const answered = await settleWithin(work().finally(() => {
|
|
14452
15129
|
if (token === checkinPassToken) checkinPassRunning = false;
|
|
14453
|
-
});
|
|
15130
|
+
}), PANEL_STEP_BUDGET_MS);
|
|
14454
15131
|
if (answered === void 0) throw panelError("the check-in did not finish in time; try again", "TIMEOUT");
|
|
14455
15132
|
return answered;
|
|
14456
15133
|
}
|
|
@@ -14467,9 +15144,10 @@ async function onPanelInvoke(channel, payload) {
|
|
|
14467
15144
|
if (!/^(cn|global|trae:cn|trae:ai|qoder:cn|qoder:global)$/.test(requested)) throw panelError("unknown gateway", "INVALID");
|
|
14468
15145
|
const selection = parseSelection(payload?.selection);
|
|
14469
15146
|
if (selection === void 0) throw panelError("invalid selection payload", "INVALID");
|
|
15147
|
+
const known = parseKnownModelIds(payload?.knownModelIds);
|
|
14470
15148
|
if (await mutateSettings("modelSelection", (current) => {
|
|
14471
15149
|
const all = { ...current && typeof current === "object" && !Array.isArray(current) ? current : {} };
|
|
14472
|
-
all[requested] = selection;
|
|
15150
|
+
all[requested] = mergeSelectionForPartialRoster(selection, normalizeSelection(all[requested]), known);
|
|
14473
15151
|
return all;
|
|
14474
15152
|
}) !== true) throw panelError("the selection could not be written to the plugin settings file", "SAVE_FAILED");
|
|
14475
15153
|
if (requested === "cn" || requested === "global") applyEffectiveSelection(requested);
|
|
@@ -14645,6 +15323,7 @@ async function onPanelInvoke(channel, payload) {
|
|
|
14645
15323
|
checkinPassRunning = true;
|
|
14646
15324
|
const answered = await settleWithin((async () => {
|
|
14647
15325
|
const outcome = source === "trae" ? await traeClaimOne(label, region) : await qoderClaimOne(label, region);
|
|
15326
|
+
markSourceCheckinRow(source, label, region, outcome);
|
|
14648
15327
|
return {
|
|
14649
15328
|
state: await statusDocument({
|
|
14650
15329
|
allowNetwork: true,
|
|
@@ -14652,9 +15331,9 @@ async function onPanelInvoke(channel, payload) {
|
|
|
14652
15331
|
}),
|
|
14653
15332
|
result: outcome
|
|
14654
15333
|
};
|
|
14655
|
-
})()
|
|
15334
|
+
})().finally(() => {
|
|
14656
15335
|
if (token === checkinPassToken) checkinPassRunning = false;
|
|
14657
|
-
});
|
|
15336
|
+
}), PANEL_STEP_BUDGET_MS);
|
|
14658
15337
|
if (answered === void 0) throw panelError("the check-in did not finish in time; try again", "TIMEOUT");
|
|
14659
15338
|
return answered;
|
|
14660
15339
|
}
|
|
@@ -14753,15 +15432,6 @@ async function onPanelInvoke(channel, payload) {
|
|
|
14753
15432
|
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
15433
|
return await statusDocument({ allowNetwork: false });
|
|
14755
15434
|
/**
|
|
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
15435
|
* Park or unpark one edition of one source (国内版 / 国际版).
|
|
14766
15436
|
*
|
|
14767
15437
|
* Same shape as the source switch above: a parked region keeps no gateway,
|
|
@@ -14779,7 +15449,7 @@ async function onPanelInvoke(channel, payload) {
|
|
|
14779
15449
|
if (payload?.enabled !== true) parked.push(key);
|
|
14780
15450
|
return parked;
|
|
14781
15451
|
}) !== true) throw panelError("the region switch could not be written to the plugin settings file", "SAVE_FAILED");
|
|
14782
|
-
await
|
|
15452
|
+
await applySettingsEverywhere(false);
|
|
14783
15453
|
if (payload?.enabled === true) await refreshAll("region-on", true);
|
|
14784
15454
|
else syncDeclaration();
|
|
14785
15455
|
if (source === "workbuddy") {
|
|
@@ -14801,7 +15471,7 @@ async function onPanelInvoke(channel, payload) {
|
|
|
14801
15471
|
if (key === void 0) throw panelError("unknown source", "UNSUPPORTED");
|
|
14802
15472
|
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
15473
|
resetDiscoveryCaches();
|
|
14804
|
-
await
|
|
15474
|
+
await applySettingsEverywhere(false);
|
|
14805
15475
|
if (payload?.enabled === true) await refreshAll("source-on", true);
|
|
14806
15476
|
else syncDeclaration();
|
|
14807
15477
|
if (payload?.source === "workbuddy") {
|
|
@@ -15033,6 +15703,7 @@ async function runCheckinPass(options) {
|
|
|
15033
15703
|
slot,
|
|
15034
15704
|
claimed: 0,
|
|
15035
15705
|
pending: true,
|
|
15706
|
+
workbuddy: want("workbuddy"),
|
|
15036
15707
|
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
15037
15708
|
...manual ? { manual: true } : {}
|
|
15038
15709
|
};
|
|
@@ -15076,25 +15747,30 @@ async function runCheckinPass(options) {
|
|
|
15076
15747
|
adopted: 0
|
|
15077
15748
|
}, "travel") : void 0;
|
|
15078
15749
|
if (!stillLoaded(generation)) return started;
|
|
15079
|
-
|
|
15750
|
+
if (want("qoder")) {
|
|
15751
|
+
const now = Date.now();
|
|
15752
|
+
const opening = typeof qoder?.opensAt === "number" && qoder.opensAt > now ? qoder.opensAt : 0;
|
|
15753
|
+
const backoff = Number(qoder?.failed) > 0 && (typeof qoder?.reason === "string" || qoder?.retry === true) ? now + QODER_RETRY_BACKOFF_MS : 0;
|
|
15754
|
+
qoderRetryAt = opening === 0 ? backoff : backoff === 0 ? opening : Math.min(opening, backoff);
|
|
15755
|
+
}
|
|
15080
15756
|
Object.assign(started, {
|
|
15081
15757
|
claimed: pool.claimed,
|
|
15082
15758
|
skipped: pool.skipped,
|
|
15083
15759
|
failed: pool.failed,
|
|
15084
15760
|
...pool.reason === void 0 ? {} : { reason: pool.reason },
|
|
15085
15761
|
travel,
|
|
15086
|
-
qoder,
|
|
15087
|
-
trae
|
|
15762
|
+
...want("qoder") ? { qoder } : {},
|
|
15763
|
+
...want("trae") ? { trae } : {}
|
|
15088
15764
|
});
|
|
15089
15765
|
await checkinDelay(GROWTH_AFTER_CHECKIN_MS);
|
|
15090
15766
|
if (!stillLoaded(generation)) return started;
|
|
15091
15767
|
started.growth = want("workbuddy") ? await claimAllGrowth() : void 0;
|
|
15092
15768
|
log((manual ? "manual" : "automatic") + " check-in collected " + pool.claimed + " account(s) for " + slot);
|
|
15093
|
-
if (spendsSlot && stillLoaded(generation)) saveCheckinSlots();
|
|
15769
|
+
if ((spendsSlot || want("qoder")) && stillLoaded(generation)) saveCheckinSlots();
|
|
15094
15770
|
} catch (error) {
|
|
15095
15771
|
started.error = safeMessage(error);
|
|
15096
15772
|
log("warn", (manual ? "manual" : "automatic") + " check-in failed for " + slot + ": " + started.error);
|
|
15097
|
-
if (spendsSlot && stillLoaded(generation)) saveCheckinSlots();
|
|
15773
|
+
if ((spendsSlot || want("qoder")) && stillLoaded(generation)) saveCheckinSlots();
|
|
15098
15774
|
} finally {
|
|
15099
15775
|
if (token === checkinPassToken) checkinPassRunning = false;
|
|
15100
15776
|
delete started.pending;
|
|
@@ -15175,17 +15851,17 @@ async function redeemAccountStreak(account) {
|
|
|
15175
15851
|
const yesterday = zonedDay(-1);
|
|
15176
15852
|
await core.client.useMakeupCard(account.credential, yesterday);
|
|
15177
15853
|
detail.makeup += 1;
|
|
15178
|
-
log("info", "streak " + account.label + ": make-up card spent on " + yesterday);
|
|
15854
|
+
log("info", "streak " + accountLogTag(account.label) + ": make-up card spent on " + yesterday);
|
|
15179
15855
|
}
|
|
15180
15856
|
} catch (error) {
|
|
15181
15857
|
detail.failed += 1;
|
|
15182
|
-
log("warn", "streak " + account.label + ": make-up: " + safeMessage(error));
|
|
15858
|
+
log("warn", "streak " + accountLogTag(account.label) + ": make-up: " + safeMessage(error));
|
|
15183
15859
|
}
|
|
15184
15860
|
for (const [label, collect] of [["gift", () => core.client.claimGift(account.credential)], ["compensation", () => core.client.claimCompensation(account.credential)]]) try {
|
|
15185
15861
|
const paid = await collect();
|
|
15186
15862
|
if (paid > 0) {
|
|
15187
15863
|
detail[label] += paid;
|
|
15188
|
-
log("info", "streak " + account.label + ": " + label + " +" + paid + "c");
|
|
15864
|
+
log("info", "streak " + accountLogTag(account.label) + ": " + label + " +" + paid + "c");
|
|
15189
15865
|
}
|
|
15190
15866
|
} catch {}
|
|
15191
15867
|
try {
|
|
@@ -15193,7 +15869,7 @@ async function redeemAccountStreak(account) {
|
|
|
15193
15869
|
detail.activity += 1;
|
|
15194
15870
|
} catch (error) {
|
|
15195
15871
|
detail.failed += 1;
|
|
15196
|
-
log("warn", "streak " + account.label + ": activity report failed: " + safeMessage(error));
|
|
15872
|
+
log("warn", "streak " + accountLogTag(account.label) + ": activity report failed: " + safeMessage(error));
|
|
15197
15873
|
}
|
|
15198
15874
|
await checkinDelay(STREAK_REPORT_READ_GAP_MS);
|
|
15199
15875
|
const status = await core.client.growthStreakFull(account.credential);
|
|
@@ -15208,10 +15884,10 @@ async function redeemAccountStreak(account) {
|
|
|
15208
15884
|
credit += tier.credit;
|
|
15209
15885
|
energy += tier.energy;
|
|
15210
15886
|
detail.streak += 1;
|
|
15211
|
-
log("info", "streak " + account.label + ": redeemed " + tier.tier + " (+" + tier.credit + "c +" + tier.energy + "e)");
|
|
15887
|
+
log("info", "streak " + accountLogTag(account.label) + ": redeemed " + tier.tier + " (+" + tier.credit + "c +" + tier.energy + "e)");
|
|
15212
15888
|
} catch (error) {
|
|
15213
15889
|
detail.failed += 1;
|
|
15214
|
-
log("warn", "streak " + account.label + ": redeem " + tier.tier + " failed: " + safeMessage(error));
|
|
15890
|
+
log("warn", "streak " + accountLogTag(account.label) + ": redeem " + tier.tier + " failed: " + safeMessage(error));
|
|
15215
15891
|
}
|
|
15216
15892
|
}
|
|
15217
15893
|
try {
|
|
@@ -15219,11 +15895,11 @@ async function redeemAccountStreak(account) {
|
|
|
15219
15895
|
for (let draw = 0; draw < chances; draw += 1) {
|
|
15220
15896
|
const prize = await core.client.drawLottery(account.credential);
|
|
15221
15897
|
detail.lottery += 1;
|
|
15222
|
-
log("info", "streak " + account.label + ": draw " + (draw + 1) + "/" + chances + " " + JSON.stringify(prize).slice(0, 160));
|
|
15898
|
+
log("info", "streak " + accountLogTag(account.label) + ": draw " + (draw + 1) + "/" + chances + " " + JSON.stringify(prize).slice(0, 160));
|
|
15223
15899
|
}
|
|
15224
15900
|
} catch (error) {
|
|
15225
15901
|
detail.failed += 1;
|
|
15226
|
-
log("warn", "streak " + account.label + ": lottery: " + safeMessage(error));
|
|
15902
|
+
log("warn", "streak " + accountLogTag(account.label) + ": lottery: " + safeMessage(error));
|
|
15227
15903
|
}
|
|
15228
15904
|
return {
|
|
15229
15905
|
claimed,
|
|
@@ -15264,7 +15940,7 @@ async function claimAllGrowth() {
|
|
|
15264
15940
|
} catch (error) {
|
|
15265
15941
|
counts.failed += 1;
|
|
15266
15942
|
counts.detail.failed += 1;
|
|
15267
|
-
log("warn", "streak failed for " + account.label + ": " + safeMessage(error));
|
|
15943
|
+
log("warn", "streak failed for " + accountLogTag(account.label) + ": " + safeMessage(error));
|
|
15268
15944
|
}
|
|
15269
15945
|
if (collected) probeCache.delete(account.id);
|
|
15270
15946
|
}
|
|
@@ -15317,7 +15993,7 @@ async function readGrowthState() {
|
|
|
15317
15993
|
chances
|
|
15318
15994
|
};
|
|
15319
15995
|
} catch (error) {
|
|
15320
|
-
log("warn", "growth state failed for " + account.label + ": " + safeMessage(error));
|
|
15996
|
+
log("warn", "growth state failed for " + accountLogTag(account.label) + ": " + safeMessage(error));
|
|
15321
15997
|
return {
|
|
15322
15998
|
account,
|
|
15323
15999
|
error
|
|
@@ -15400,7 +16076,7 @@ async function claimAllCheckins() {
|
|
|
15400
16076
|
continue;
|
|
15401
16077
|
}
|
|
15402
16078
|
counts.failed += 1;
|
|
15403
|
-
log("warn", "check-in failed for " + account.label + ": " + safeMessage(error));
|
|
16079
|
+
log("warn", "check-in failed for " + accountLogTag(account.label) + ": " + safeMessage(error));
|
|
15404
16080
|
}
|
|
15405
16081
|
}
|
|
15406
16082
|
return counts;
|
|
@@ -15427,13 +16103,13 @@ async function travelAdopt(account) {
|
|
|
15427
16103
|
try {
|
|
15428
16104
|
await core.client.reportChatActivity(account.credential, conversationId);
|
|
15429
16105
|
} catch (error) {
|
|
15430
|
-
log("warn", "travel " + account.label + ": adopt preflight report: " + safeMessage(error));
|
|
16106
|
+
log("warn", "travel " + accountLogTag(account.label) + ": adopt preflight report: " + safeMessage(error));
|
|
15431
16107
|
}
|
|
15432
16108
|
await checkinDelay(TRAVEL_ADOPT_GAP_MS);
|
|
15433
16109
|
try {
|
|
15434
16110
|
await core.client.agreeBuddy(account.credential);
|
|
15435
16111
|
} catch (error) {
|
|
15436
|
-
log("warn", "travel " + account.label + ": agreement: " + safeMessage(error));
|
|
16112
|
+
log("warn", "travel " + accountLogTag(account.label) + ": agreement: " + safeMessage(error));
|
|
15437
16113
|
return "failed";
|
|
15438
16114
|
}
|
|
15439
16115
|
try {
|
|
@@ -15441,13 +16117,13 @@ async function travelAdopt(account) {
|
|
|
15441
16117
|
} catch (error) {
|
|
15442
16118
|
if (isBuddyThresholdIncomplete(safeMessage(error))) {
|
|
15443
16119
|
travelAdoptTried.set(account.id, day);
|
|
15444
|
-
log("info", "travel " + account.label + ": adopt skipped (conversation threshold not reached, retry tomorrow)");
|
|
16120
|
+
log("info", "travel " + accountLogTag(account.label) + ": adopt skipped (conversation threshold not reached, retry tomorrow)");
|
|
15445
16121
|
return "skipped";
|
|
15446
16122
|
}
|
|
15447
|
-
log("warn", "travel " + account.label + ": adopt: " + safeMessage(error));
|
|
16123
|
+
log("warn", "travel " + accountLogTag(account.label) + ": adopt: " + safeMessage(error));
|
|
15448
16124
|
return "failed";
|
|
15449
16125
|
}
|
|
15450
|
-
log("info", "travel " + account.label + ": adopt ok");
|
|
16126
|
+
log("info", "travel " + accountLogTag(account.label) + ": adopt ok");
|
|
15451
16127
|
return "adopted";
|
|
15452
16128
|
}
|
|
15453
16129
|
/**
|
|
@@ -15461,7 +16137,7 @@ async function travelOne(account) {
|
|
|
15461
16137
|
try {
|
|
15462
16138
|
buddy = await core.client.fetchBuddyInfo(account.credential);
|
|
15463
16139
|
} catch (error) {
|
|
15464
|
-
log("warn", "travel " + account.label + ": buddy-info: " + safeMessage(error));
|
|
16140
|
+
log("warn", "travel " + accountLogTag(account.label) + ": buddy-info: " + safeMessage(error));
|
|
15465
16141
|
return "failed";
|
|
15466
16142
|
}
|
|
15467
16143
|
if (buddy === null) return await travelAdopt(account);
|
|
@@ -15469,42 +16145,42 @@ async function travelOne(account) {
|
|
|
15469
16145
|
try {
|
|
15470
16146
|
status = await core.client.fetchTravelStatus(account.credential);
|
|
15471
16147
|
} catch (error) {
|
|
15472
|
-
log("warn", "travel " + account.label + ": status: " + safeMessage(error));
|
|
16148
|
+
log("warn", "travel " + accountLogTag(account.label) + ": status: " + safeMessage(error));
|
|
15473
16149
|
return "failed";
|
|
15474
16150
|
}
|
|
15475
16151
|
if (status.state === "arrived") {
|
|
15476
16152
|
if (status.recordId === 0) {
|
|
15477
|
-
log("info", "travel " + account.label + ": claim skipped (arrived but no record_id)");
|
|
16153
|
+
log("info", "travel " + accountLogTag(account.label) + ": claim skipped (arrived but no record_id)");
|
|
15478
16154
|
return "skipped";
|
|
15479
16155
|
}
|
|
15480
16156
|
try {
|
|
15481
16157
|
const reward = await core.client.claimTravelReward(account.credential, status.recordId);
|
|
15482
|
-
log("info", "travel " + account.label + ": claim ok record=" + status.recordId + " reward=" + reward);
|
|
16158
|
+
log("info", "travel " + accountLogTag(account.label) + ": claim ok record=" + status.recordId + " reward=" + reward);
|
|
15483
16159
|
return "claimed";
|
|
15484
16160
|
} catch (error) {
|
|
15485
|
-
log("warn", "travel " + account.label + ": claim record=" + status.recordId + ": " + safeMessage(error));
|
|
16161
|
+
log("warn", "travel " + accountLogTag(account.label) + ": claim record=" + status.recordId + ": " + safeMessage(error));
|
|
15486
16162
|
return "failed";
|
|
15487
16163
|
}
|
|
15488
16164
|
}
|
|
15489
16165
|
if (status.state === "idle") {
|
|
15490
16166
|
if (status.dailyLimitReached) {
|
|
15491
|
-
log("info", "travel " + account.label + ": skip (daily limit reached)");
|
|
16167
|
+
log("info", "travel " + accountLogTag(account.label) + ": skip (daily limit reached)");
|
|
15492
16168
|
return "skipped";
|
|
15493
16169
|
}
|
|
15494
16170
|
try {
|
|
15495
16171
|
await core.client.departTravel(account.credential, 4);
|
|
15496
|
-
log("info", "travel " + account.label + ": depart ok location=4");
|
|
16172
|
+
log("info", "travel " + accountLogTag(account.label) + ": depart ok location=4");
|
|
15497
16173
|
return "departed";
|
|
15498
16174
|
} catch (error) {
|
|
15499
|
-
log("warn", "travel " + account.label + ": depart: " + safeMessage(error));
|
|
16175
|
+
log("warn", "travel " + accountLogTag(account.label) + ": depart: " + safeMessage(error));
|
|
15500
16176
|
return "failed";
|
|
15501
16177
|
}
|
|
15502
16178
|
}
|
|
15503
16179
|
if (status.state === "traveling") {
|
|
15504
|
-
log("info", "travel " + account.label + ": skip (traveling record=" + status.recordId + ")");
|
|
16180
|
+
log("info", "travel " + accountLogTag(account.label) + ": skip (traveling record=" + status.recordId + ")");
|
|
15505
16181
|
return "skipped";
|
|
15506
16182
|
}
|
|
15507
|
-
log("info", "travel " + account.label + ": skip (unknown state " + JSON.stringify(status.state) + ")");
|
|
16183
|
+
log("info", "travel " + accountLogTag(account.label) + ": skip (unknown state " + JSON.stringify(status.state) + ")");
|
|
15508
16184
|
return "skipped";
|
|
15509
16185
|
}
|
|
15510
16186
|
/**
|
|
@@ -15536,7 +16212,7 @@ async function travelAllAccounts() {
|
|
|
15536
16212
|
} else if (outcome === "failed") counts.failed += 1;
|
|
15537
16213
|
} catch (error) {
|
|
15538
16214
|
counts.failed += 1;
|
|
15539
|
-
log("warn", "travel failed for " + account.label + ": " + safeMessage(error));
|
|
16215
|
+
log("warn", "travel failed for " + accountLogTag(account.label) + ": " + safeMessage(error));
|
|
15540
16216
|
}
|
|
15541
16217
|
}
|
|
15542
16218
|
return counts;
|
|
@@ -15551,7 +16227,8 @@ async function qoderCheckinAll() {
|
|
|
15551
16227
|
const counts = {
|
|
15552
16228
|
claimed: 0,
|
|
15553
16229
|
skipped: 0,
|
|
15554
|
-
failed: 0
|
|
16230
|
+
failed: 0,
|
|
16231
|
+
retry: false
|
|
15555
16232
|
};
|
|
15556
16233
|
const regions = activeQoderRegions();
|
|
15557
16234
|
if (regions.length === 0) return counts;
|
|
@@ -15567,6 +16244,10 @@ async function qoderCheckinAll() {
|
|
|
15567
16244
|
reason
|
|
15568
16245
|
};
|
|
15569
16246
|
}
|
|
16247
|
+
if (found.failures.length > 0) {
|
|
16248
|
+
counts.failed += 1;
|
|
16249
|
+
counts.retry = true;
|
|
16250
|
+
}
|
|
15570
16251
|
let seen = 0;
|
|
15571
16252
|
for (const credential of found.credentials) {
|
|
15572
16253
|
if (!regions.includes(credential.region)) continue;
|
|
@@ -15575,6 +16256,8 @@ async function qoderCheckinAll() {
|
|
|
15575
16256
|
seen += 1;
|
|
15576
16257
|
const result = await qoderClaimFor(credential);
|
|
15577
16258
|
counts[result.outcome] += 1;
|
|
16259
|
+
markSourceCheckinRow("qoder", qoderRowLabel(credential), credential.region, result);
|
|
16260
|
+
if (result.retry === true) counts.retry = true;
|
|
15578
16261
|
if (result.opensAt !== void 0 && (counts.opensAt === void 0 || result.opensAt < counts.opensAt)) counts.opensAt = result.opensAt;
|
|
15579
16262
|
}
|
|
15580
16263
|
return counts;
|
|
@@ -15586,6 +16269,14 @@ async function qoderCheckinAll() {
|
|
|
15586
16269
|
* that already collected) costs a single GET and no mutation.
|
|
15587
16270
|
*/
|
|
15588
16271
|
async function qoderClaimFor(credential) {
|
|
16272
|
+
if (sourceCredentialExpired(credential, Date.now())) {
|
|
16273
|
+
const reason = "token expired (open Qoder to refresh it)";
|
|
16274
|
+
log("warn", "[qoder:" + credential.region + "] check-in skipped for " + accountLogTag(qoderRowLabel(credential)) + ": token expired (open Qoder to refresh it)");
|
|
16275
|
+
return {
|
|
16276
|
+
outcome: "skipped",
|
|
16277
|
+
reason
|
|
16278
|
+
};
|
|
16279
|
+
}
|
|
15589
16280
|
const client = new QoderUpstreamClient({
|
|
15590
16281
|
region: credential.region,
|
|
15591
16282
|
credential: async () => qoderClientCredential(credential)
|
|
@@ -15597,27 +16288,36 @@ async function qoderClaimFor(credential) {
|
|
|
15597
16288
|
const state = qoderCheckinStateFrom(campaigns);
|
|
15598
16289
|
return {
|
|
15599
16290
|
outcome: "skipped",
|
|
16291
|
+
...state.todayCheckedIn === true ? { todayCheckedIn: true } : {},
|
|
15600
16292
|
...state.opensAt === void 0 ? {} : { opensAt: state.opensAt }
|
|
15601
16293
|
};
|
|
15602
16294
|
}
|
|
15603
16295
|
const result = qoderNormalizeClaimResult(await client.claimCampaign(id));
|
|
15604
16296
|
if (result.reason !== void 0) {
|
|
15605
|
-
log("warn", "[qoder:" + credential.region + "] check-in refused for " + qoderRowLabel(credential) + ": " + result.reason);
|
|
16297
|
+
log("warn", "[qoder:" + credential.region + "] check-in refused for " + accountLogTag(qoderRowLabel(credential)) + ": " + result.reason);
|
|
15606
16298
|
return {
|
|
15607
16299
|
outcome: "failed",
|
|
15608
|
-
reason: result.reason
|
|
16300
|
+
reason: result.reason,
|
|
16301
|
+
retry: false
|
|
15609
16302
|
};
|
|
15610
16303
|
}
|
|
15611
|
-
return { outcome: result.claimed
|
|
16304
|
+
return { outcome: result.claimed ? "claimed" : "skipped" };
|
|
15612
16305
|
} catch (error) {
|
|
15613
16306
|
const reason = safeMessage(error);
|
|
15614
|
-
log("warn", "[qoder:" + credential.region + "] check-in failed for " + qoderRowLabel(credential) + ": " + reason);
|
|
16307
|
+
log("warn", "[qoder:" + credential.region + "] check-in failed for " + accountLogTag(qoderRowLabel(credential)) + ": " + reason);
|
|
15615
16308
|
return {
|
|
15616
16309
|
outcome: "failed",
|
|
15617
|
-
reason
|
|
16310
|
+
reason,
|
|
16311
|
+
retry: qoderFailureRetryable(error)
|
|
15618
16312
|
};
|
|
15619
16313
|
}
|
|
15620
16314
|
}
|
|
16315
|
+
/** A transport/5xx failure is worth another tick; a 4xx verdict is not. */
|
|
16316
|
+
function qoderFailureRetryable(error) {
|
|
16317
|
+
const status = Number(/\bHTTP\s+(\d{3})\b/iu.exec(safeMessage(error))?.[1] ?? 0);
|
|
16318
|
+
if (status === 0) return true;
|
|
16319
|
+
return status === 408 || status === 429 || status >= 500;
|
|
16320
|
+
}
|
|
15621
16321
|
/**
|
|
15622
16322
|
* Claim today's Trae credits for every signed-in CN Trae account. Each account
|
|
15623
16323
|
* is read first: one already checked in costs a single status call and no
|
|
@@ -15646,16 +16346,24 @@ async function traeCheckinAll() {
|
|
|
15646
16346
|
};
|
|
15647
16347
|
}
|
|
15648
16348
|
const cnCredentials = found.credentials.filter((credential) => traeRegionOfCredential(credential) === "cn");
|
|
16349
|
+
const spentEditions = /* @__PURE__ */ new Set();
|
|
15649
16350
|
let index = 0;
|
|
15650
16351
|
for (; index < cnCredentials.length; index += 1) {
|
|
15651
16352
|
if (currentCheckinSignal().aborted) break;
|
|
16353
|
+
const credential = cnCredentials[index];
|
|
16354
|
+
if (spentEditions.has(credential.edition)) {
|
|
16355
|
+
markSourceCheckinRow("trae", traeRowLabel(credential), "cn", {
|
|
16356
|
+
outcome: "skipped",
|
|
16357
|
+
deviceCheckedIn: true
|
|
16358
|
+
});
|
|
16359
|
+
counts.skipped += 1;
|
|
16360
|
+
continue;
|
|
16361
|
+
}
|
|
15652
16362
|
if (index > 0) await checkinDelay(Math.max(1e3, TRAE_ACCOUNT_DELAY_MS + Math.round((Math.random() * 2 - 1) * TRAE_ACCOUNT_JITTER_MS)));
|
|
15653
|
-
const result = await traeClaimFor(
|
|
16363
|
+
const result = await traeClaimFor(credential, desktopCandidates);
|
|
15654
16364
|
counts[result.outcome] += 1;
|
|
15655
|
-
|
|
15656
|
-
|
|
15657
|
-
break;
|
|
15658
|
-
}
|
|
16365
|
+
markSourceCheckinRow("trae", traeRowLabel(credential), "cn", result);
|
|
16366
|
+
if (result.deviceCheckedIn === true) spentEditions.add(credential.edition);
|
|
15659
16367
|
}
|
|
15660
16368
|
return counts;
|
|
15661
16369
|
}
|
|
@@ -15712,7 +16420,7 @@ async function traeClaimFor(credential, desktopCandidates) {
|
|
|
15712
16420
|
const label = traeRowLabel(credential);
|
|
15713
16421
|
if (sourceCredentialExpired(credential, Date.now())) {
|
|
15714
16422
|
const reason = "token expired (open Trae to refresh it)";
|
|
15715
|
-
log("warn", "[trae:cn] check-in skipped for " + label + ": token expired (open Trae to refresh it)");
|
|
16423
|
+
log("warn", "[trae:cn] check-in skipped for " + accountLogTag(label) + ": token expired (open Trae to refresh it)");
|
|
15716
16424
|
return {
|
|
15717
16425
|
outcome: "skipped",
|
|
15718
16426
|
reason
|
|
@@ -15725,7 +16433,10 @@ async function traeClaimFor(credential, desktopCandidates) {
|
|
|
15725
16433
|
try {
|
|
15726
16434
|
const status = await client.fetchCheckinStatus();
|
|
15727
16435
|
if (status.code === 0 && status.enable === false) return { outcome: "skipped" };
|
|
15728
|
-
if (status.code === 0 && status.checkedIn) return {
|
|
16436
|
+
if (status.code === 0 && status.checkedIn) return {
|
|
16437
|
+
outcome: "skipped",
|
|
16438
|
+
todayCheckedIn: true
|
|
16439
|
+
};
|
|
15729
16440
|
if (status.code === 0 && status.didCheckedIn) return {
|
|
15730
16441
|
outcome: "skipped",
|
|
15731
16442
|
deviceCheckedIn: true
|
|
@@ -15733,27 +16444,45 @@ async function traeClaimFor(credential, desktopCandidates) {
|
|
|
15733
16444
|
const claim = status.code === 0 ? await client.claimCheckin() : status;
|
|
15734
16445
|
if (claim.code === 0) return { outcome: "claimed" };
|
|
15735
16446
|
if (claim.code === 9095) {
|
|
15736
|
-
log("info", "[trae:cn] check-in already used by this device for " + label + ": " + safeMessage(claim.message ?? ""));
|
|
16447
|
+
log("info", "[trae:cn] check-in already used by this device for " + accountLogTag(label) + ": " + safeMessage(claim.message ?? ""));
|
|
15737
16448
|
return {
|
|
15738
16449
|
outcome: "skipped",
|
|
15739
16450
|
deviceCheckedIn: true
|
|
15740
16451
|
};
|
|
15741
16452
|
}
|
|
15742
16453
|
const reason = await traeCheckinReason("code " + claim.code + (claim.message === void 0 ? "" : " " + safeMessage(claim.message)), credential, desktopCandidates);
|
|
15743
|
-
log("warn", "[trae:cn] check-in refused for " + label + ": " + reason);
|
|
16454
|
+
log("warn", "[trae:cn] check-in refused for " + accountLogTag(label) + ": " + reason);
|
|
15744
16455
|
return {
|
|
15745
16456
|
outcome: "failed",
|
|
15746
16457
|
reason
|
|
15747
16458
|
};
|
|
15748
16459
|
} catch (error) {
|
|
15749
16460
|
const reason = await traeCheckinReason(safeMessage(error), credential, desktopCandidates);
|
|
15750
|
-
log("warn", "[trae:cn] check-in failed for " + label + ": " + reason);
|
|
16461
|
+
log("warn", "[trae:cn] check-in failed for " + accountLogTag(label) + ": " + reason);
|
|
15751
16462
|
return {
|
|
15752
16463
|
outcome: "failed",
|
|
15753
16464
|
reason
|
|
15754
16465
|
};
|
|
15755
16466
|
}
|
|
15756
16467
|
}
|
|
16468
|
+
/** Record a single claim in the cached source row the panel reads back. */
|
|
16469
|
+
function markSourceCheckinRow(source, label, region, outcome) {
|
|
16470
|
+
const checkedToday = outcome?.outcome === "claimed" || outcome?.todayCheckedIn === true;
|
|
16471
|
+
if (!checkedToday && outcome?.deviceCheckedIn !== true) return;
|
|
16472
|
+
const row = (source === "trae" ? traeAccountRows : qoderAccountRows).find((entry) => entry.label === label && entry.region === region);
|
|
16473
|
+
if (row === void 0) return;
|
|
16474
|
+
row.checkin = {
|
|
16475
|
+
...row.checkin ?? {
|
|
16476
|
+
active: true,
|
|
16477
|
+
todayCheckedIn: false
|
|
16478
|
+
},
|
|
16479
|
+
...checkedToday ? {
|
|
16480
|
+
active: true,
|
|
16481
|
+
todayCheckedIn: true
|
|
16482
|
+
} : {},
|
|
16483
|
+
...outcome.deviceCheckedIn === true ? { deviceCheckedIn: true } : {}
|
|
16484
|
+
};
|
|
16485
|
+
}
|
|
15757
16486
|
/** The one Trae account a panel row names, or a refusal that says why. */
|
|
15758
16487
|
async function traeClaimOne(label, region) {
|
|
15759
16488
|
if (region !== "cn") throw panelError("Trae check-in is CN-only", "INVALID");
|
|
@@ -15792,20 +16521,27 @@ async function autoCheckinTick(now) {
|
|
|
15792
16521
|
checkinAbort.abort();
|
|
15793
16522
|
checkinAbort = new AbortController();
|
|
15794
16523
|
checkinScope.enterWith(checkinAbort.signal);
|
|
16524
|
+
const retrySlot = autoCheckinLast?.slot ?? checkinSlotId(zonedDayHour(/* @__PURE__ */ new Date()).day, zonedDayHour(/* @__PURE__ */ new Date()).hour);
|
|
15795
16525
|
try {
|
|
15796
16526
|
qoderRetryAt = 0;
|
|
15797
16527
|
const retry = await qoderCheckinAll();
|
|
15798
16528
|
if (!stillLoaded(retryGeneration)) return autoCheckinLast;
|
|
15799
|
-
|
|
16529
|
+
const now = Date.now();
|
|
16530
|
+
const opening = typeof retry.opensAt === "number" && retry.opensAt > now ? retry.opensAt : 0;
|
|
16531
|
+
const backoff = Number(retry.failed) > 0 && (typeof retry.reason === "string" || retry.retry === true) ? now + QODER_RETRY_BACKOFF_MS : 0;
|
|
16532
|
+
qoderRetryAt = opening === 0 ? backoff : backoff === 0 ? opening : Math.min(opening, backoff);
|
|
15800
16533
|
const claimedBefore = Number(autoCheckinLast?.qoder?.claimed) || 0;
|
|
15801
16534
|
autoCheckinLast = {
|
|
15802
16535
|
...autoCheckinLast,
|
|
16536
|
+
slot: retrySlot,
|
|
16537
|
+
...autoCheckinLast === null ? { workbuddy: false } : {},
|
|
15803
16538
|
qoder: {
|
|
15804
16539
|
...retry,
|
|
15805
16540
|
claimed: claimedBefore + (Number(retry.claimed) || 0)
|
|
15806
16541
|
},
|
|
15807
16542
|
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
15808
16543
|
};
|
|
16544
|
+
saveCheckinSlots();
|
|
15809
16545
|
log("info", "deferred Qoder check-in: " + JSON.stringify(retry));
|
|
15810
16546
|
} catch (error) {
|
|
15811
16547
|
if (stillLoaded(retryGeneration)) {
|
|
@@ -15813,6 +16549,7 @@ async function autoCheckinTick(now) {
|
|
|
15813
16549
|
const claimedBefore = Number(autoCheckinLast?.qoder?.claimed) || 0;
|
|
15814
16550
|
autoCheckinLast = {
|
|
15815
16551
|
...autoCheckinLast,
|
|
16552
|
+
slot: retrySlot,
|
|
15816
16553
|
qoder: {
|
|
15817
16554
|
claimed: claimedBefore,
|
|
15818
16555
|
skipped: 0,
|
|
@@ -15821,6 +16558,7 @@ async function autoCheckinTick(now) {
|
|
|
15821
16558
|
},
|
|
15822
16559
|
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
15823
16560
|
};
|
|
16561
|
+
saveCheckinSlots();
|
|
15824
16562
|
log("warn", "deferred Qoder check-in failed: " + safeMessage(error));
|
|
15825
16563
|
}
|
|
15826
16564
|
} finally {
|
|
@@ -15968,10 +16706,13 @@ async function publishDeclarationEarly() {
|
|
|
15968
16706
|
else if (written.changed === true) log("info", "declaration updated at load time; " + written.providerCount + " provider(s)");
|
|
15969
16707
|
}
|
|
15970
16708
|
async function onServiceStart() {
|
|
16709
|
+
const generation = loadGeneration;
|
|
15971
16710
|
serviceStopped = false;
|
|
15972
16711
|
if (warmAbort.signal.aborted) warmAbort = new AbortController();
|
|
15973
16712
|
await adoptHostSettings();
|
|
16713
|
+
if (!stillLoaded(generation)) return;
|
|
15974
16714
|
if (settings.enabled === false) {
|
|
16715
|
+
syncDeclaration();
|
|
15975
16716
|
log("info", "plugin disabled in settings; the provider host stays down");
|
|
15976
16717
|
return;
|
|
15977
16718
|
}
|
|
@@ -15980,9 +16721,13 @@ async function onServiceStart() {
|
|
|
15980
16721
|
startAccountWatch();
|
|
15981
16722
|
const { left: bootstrapLeft } = budget(SERVICE_BOOTSTRAP_BUDGET_MS);
|
|
15982
16723
|
await settleWithin(reconcileTraeGateways(), bootstrapLeft());
|
|
16724
|
+
if (!stillLoaded(generation)) return;
|
|
15983
16725
|
await settleWithin(reconcileQoderGateways(), bootstrapLeft());
|
|
16726
|
+
if (!stillLoaded(generation)) return;
|
|
15984
16727
|
if (activeRegions().length > 0) await settleWithin(core.pool.scan(), bootstrapLeft());
|
|
16728
|
+
if (!stillLoaded(generation)) return;
|
|
15985
16729
|
await settleWithin(startRuntimes(), bootstrapLeft());
|
|
16730
|
+
if (!stillLoaded(generation)) return;
|
|
15986
16731
|
await settleWithin(Promise.all(Array.from(runtimes.values()).map(async (runtime) => {
|
|
15987
16732
|
try {
|
|
15988
16733
|
await connect(runtime, !catalogFresh(runtime));
|
|
@@ -15991,6 +16736,7 @@ async function onServiceStart() {
|
|
|
15991
16736
|
log("warn", runtime.region + " failed to start: " + runtime.lastError);
|
|
15992
16737
|
}
|
|
15993
16738
|
})), SERVICE_ROSTER_BUDGET_MS);
|
|
16739
|
+
if (!stillLoaded(generation)) return;
|
|
15994
16740
|
syncDeclaration();
|
|
15995
16741
|
scheduleRefresh("service-start");
|
|
15996
16742
|
}
|
|
@@ -16017,6 +16763,7 @@ async function onServiceStop() {
|
|
|
16017
16763
|
qoderGateways.clear();
|
|
16018
16764
|
gatewayStartFailures.clear();
|
|
16019
16765
|
sourceStartFailures.clear();
|
|
16766
|
+
sourceGatewayStarts.clear();
|
|
16020
16767
|
await Promise.all(closing);
|
|
16021
16768
|
}
|
|
16022
16769
|
async function onLoad() {
|
|
@@ -16037,11 +16784,7 @@ async function onLoad() {
|
|
|
16037
16784
|
for (const runtime of runtimes.values()) pendingRuntimeStops.push(stopRuntime(runtime));
|
|
16038
16785
|
runtimes.clear();
|
|
16039
16786
|
runtimeStarts.clear();
|
|
16040
|
-
|
|
16041
|
-
log("warn", "[" + entry.source + ":" + entry.region + "] gateway did not close cleanly: " + safeMessage(error));
|
|
16042
|
-
}));
|
|
16043
|
-
traeGateways.clear();
|
|
16044
|
-
qoderGateways.clear();
|
|
16787
|
+
sourceGatewayStarts.clear();
|
|
16045
16788
|
checkinPassRunning = false;
|
|
16046
16789
|
autoCheckinSlots.clear();
|
|
16047
16790
|
autoCheckinLast = null;
|
|
@@ -16049,7 +16792,7 @@ async function onLoad() {
|
|
|
16049
16792
|
growthLast = null;
|
|
16050
16793
|
keepAliveLast = null;
|
|
16051
16794
|
qoderRetryAt = 0;
|
|
16052
|
-
core.client = new WorkBuddyUpstreamClient({
|
|
16795
|
+
core.client = new WorkBuddyUpstreamClient({});
|
|
16053
16796
|
core.pool = new WorkBuddyAccountPool({
|
|
16054
16797
|
client: core.client,
|
|
16055
16798
|
cooldownMs: cooldownMs(),
|
|
@@ -16063,7 +16806,6 @@ async function onLoad() {
|
|
|
16063
16806
|
});
|
|
16064
16807
|
await adoptHostSettings();
|
|
16065
16808
|
if (serviceStopped) return;
|
|
16066
|
-
declarationIndex = /* @__PURE__ */ new Map();
|
|
16067
16809
|
publishedIds = /* @__PURE__ */ new Set();
|
|
16068
16810
|
try {
|
|
16069
16811
|
dataPath = await pi.plugin.getDataPath();
|
|
@@ -16100,6 +16842,7 @@ async function onUnload() {
|
|
|
16100
16842
|
traeIdentityBlockers.clear();
|
|
16101
16843
|
gatewayStartFailures.clear();
|
|
16102
16844
|
sourceStartFailures.clear();
|
|
16845
|
+
sourceGatewayStarts.clear();
|
|
16103
16846
|
deviceLogins.clear();
|
|
16104
16847
|
unsubscribeFromHostSettings();
|
|
16105
16848
|
}
|
|
@@ -16107,19 +16850,6 @@ function composerPointsEnabled() {
|
|
|
16107
16850
|
return settings.showComposerPoints === true;
|
|
16108
16851
|
}
|
|
16109
16852
|
/**
|
|
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
16853
|
* The source and region one selected provider route belongs to.
|
|
16124
16854
|
*
|
|
16125
16855
|
* The composer readout is handed the session's selection straight from the
|
|
@@ -16212,7 +16942,7 @@ function workbuddyComposerAccounts(region, modelId) {
|
|
|
16212
16942
|
function sourceComposerAccounts(source, region) {
|
|
16213
16943
|
const rows = (source === "trae" ? traeAccountRows : qoderAccountRows).filter((row) => row.region === region);
|
|
16214
16944
|
const live = rows.filter((row) => row.expired !== true);
|
|
16215
|
-
const active = orderSourceCredentials(source, region, live, (row) => row.label,
|
|
16945
|
+
const active = orderSourceCredentials(source, region, live, (row) => row.label, "peek")[0];
|
|
16216
16946
|
return rows.map((row) => {
|
|
16217
16947
|
const credits = row.usage?.credits;
|
|
16218
16948
|
return {
|
|
@@ -16298,9 +17028,12 @@ async function composerPrefer(args) {
|
|
|
16298
17028
|
else next[sourceRegionKey(source, region)] = accountLabel;
|
|
16299
17029
|
return next;
|
|
16300
17030
|
}) !== true) throw panelError("the account choice could not be saved", "SAVE_FAILED");
|
|
17031
|
+
const activeLabel = sourceComposerAccounts(source, region).find((row) => row.active === true)?.label ?? "";
|
|
17032
|
+
const servable = accountLabel === "" || activeLabel === accountLabel;
|
|
16301
17033
|
return {
|
|
16302
17034
|
...composerPoints(args),
|
|
16303
|
-
saved: true
|
|
17035
|
+
saved: true,
|
|
17036
|
+
...servable ? {} : { unavailable: true }
|
|
16304
17037
|
};
|
|
16305
17038
|
}
|
|
16306
17039
|
//#endregion
|
|
@@ -16444,7 +17177,6 @@ const Config = z.object({
|
|
|
16444
17177
|
preferredSourceAccounts: asVolatile(z.any().description("Picked Trae/Qoder account per region")),
|
|
16445
17178
|
removedAccounts: asVolatile(z.any().description("Accounts removed from the pool for good")),
|
|
16446
17179
|
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
17180
|
sourceDistributions: asVolatile(z.any().description("How each Trae/Qoder region spreads requests"))
|
|
16449
17181
|
});
|
|
16450
17182
|
/** Peel one volatile reference, if the running line wrapped it. */
|
|
@@ -16719,13 +17451,16 @@ function apply(ctx, config = {}) {
|
|
|
16719
17451
|
if (mutate === void 0) throw new Error("this host exposes no settings mutate()");
|
|
16720
17452
|
writesStarted += 1;
|
|
16721
17453
|
writesInFlight += 1;
|
|
17454
|
+
let echoed = false;
|
|
16722
17455
|
try {
|
|
16723
17456
|
await mutate.call(settingsService, settingsNamespace, Object.entries(patch).map(([key, value]) => ({
|
|
16724
17457
|
op: "set",
|
|
16725
17458
|
path: [key],
|
|
16726
17459
|
value
|
|
16727
17460
|
})));
|
|
17461
|
+
echoed = true;
|
|
16728
17462
|
} finally {
|
|
17463
|
+
if (!echoed) writesStarted -= 1;
|
|
16729
17464
|
writesInFlight -= 1;
|
|
16730
17465
|
if (writesInFlight === 0) {
|
|
16731
17466
|
if (droppedPushes > writesStarted) {
|
|
@@ -16836,7 +17571,7 @@ function apply(ctx, config = {}) {
|
|
|
16836
17571
|
try {
|
|
16837
17572
|
if (typeof settingsService?.configure === "function") ctx.effect(() => settingsService.configure?.({ auto: true }, ctx.fiber) ?? (() => {}));
|
|
16838
17573
|
} catch (error) {
|
|
16839
|
-
ctx.logger.warn?.("dsh-wtq-pool: settings section unavailable", error);
|
|
17574
|
+
ctx.logger.warn?.("dsh-wtq-pool: settings section unavailable", safeMessage(error));
|
|
16840
17575
|
}
|
|
16841
17576
|
ctx.effect(() => {
|
|
16842
17577
|
disposeDiscovery?.();
|