dsh-wtq-pool 1.2.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/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 { constants, createCipheriv, createDecipheriv, createHash, publicEncrypt, randomBytes, randomUUID } from "node:crypto";
15
16
  import * as net from "node:net";
16
17
  import { BlockList, isIP } from "node:net";
17
- import { constants, createCipheriv, createDecipheriv, createHash, publicEncrypt, randomBytes, randomUUID } from "node:crypto";
18
18
  import * as fs$1 from "node:fs";
19
19
  import { statSync } from "node:fs";
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"],
@@ -585,7 +597,7 @@ function createLoopbackServer(options) {
585
597
  });
586
598
  server.listen(options.port ?? 0, "127.0.0.1");
587
599
  server.on("error", (error) => {
588
- options.logger?.warn?.("wtq-pool: " + options.label + " server error", error);
600
+ options.logger?.warn?.("wtq-pool: " + options.label + " server error", safeMessage(error));
589
601
  });
590
602
  return {
591
603
  ready,
@@ -986,7 +998,7 @@ function registerPanelRoutes(ctx, deps) {
986
998
  for (const dispose of disposers) try {
987
999
  dispose();
988
1000
  } catch (error) {
989
- 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));
990
1002
  }
991
1003
  };
992
1004
  const mount = (route) => {
@@ -1047,7 +1059,7 @@ function registerPanelRoutes(ctx, deps) {
1047
1059
  return release;
1048
1060
  });
1049
1061
  } catch (error) {
1050
- 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));
1051
1063
  }
1052
1064
  }
1053
1065
  //#endregion
@@ -1764,7 +1776,7 @@ function classifyUpstreamError(status, body) {
1764
1776
  if (isHardCreditText(body)) return "hard_credit";
1765
1777
  }
1766
1778
  if (status === 503 && SOFT_RATE_PATTERN.test(body)) return "soft_rate";
1767
- if (status === 403 && !body.includes("\"code\":") && !body.includes("\"msg\":")) return "waf_block";
1779
+ if (status === 403 && !/"code"\s*:|"msg"\s*:/.test(body)) return "waf_block";
1768
1780
  if (status === 404) return "not_found";
1769
1781
  if (status >= 500) return "server";
1770
1782
  return "client";
@@ -2822,6 +2834,18 @@ function openEncryptedField(field, key) {
2822
2834
  function cleanIconPath(raw) {
2823
2835
  return raw.replace(/^"/u, "").replace(/",-?\d+$/u, "").replace(/,-?\d+$/u, "").trim();
2824
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
+ }
2825
2849
  function windowsRegistryAppPaths() {
2826
2850
  if (process.platform !== "win32") return [];
2827
2851
  const cached = registryAppPaths;
@@ -2892,21 +2916,20 @@ function scanInterpreter(env) {
2892
2916
  return join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
2893
2917
  }
2894
2918
  /**
2895
- * Every path an uninstall key names for a WorkBuddy-family install, paired with
2896
- * the signature PowerShell found on it.
2919
+ * Every path an uninstall key names for a WorkBuddy-family install.
2897
2920
  *
2898
2921
  * The scan reads `DisplayName`, `DisplayIcon` and `InstallLocation` out of the
2899
2922
  * user's own uninstall keys, which means any process running as the user can add
2900
- * one. Before the signature check, a key naming an arbitrary executable was
2901
- * enough to have this plugin spawn it with the plugin's whole environment, inside
2902
- * a process holding every WorkBuddy token - so the check is what makes the scan
2903
- * safe to run at all, not an extra.
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.
2904
2927
  *
2905
- * PowerShell does the part only it can do: enumerate, clean the resource index
2906
- * and quotes off `DisplayIcon`, stat the file, and read its signature. The
2907
- * decision is {@link signatureAccepts}'s, in Node, because that is where it can
2908
- * be tested without a registry to plant a key in, and it is handed a module path
2909
- * 5.1 can actually load, because the host's is not always one.
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.
2910
2933
  */
2911
2934
  function readRegistryAppPaths() {
2912
2935
  const script = [
@@ -2921,23 +2944,19 @@ function readRegistryAppPaths() {
2921
2944
  " return $v",
2922
2945
  "}",
2923
2946
  "$roots=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*')",
2924
- "foreach($r in $roots){",
2947
+ "$out = foreach($r in $roots){",
2925
2948
  " Get-ItemProperty -Path $r | ForEach-Object {",
2926
2949
  " $dn=[string]$_.DisplayName; $di=[string]$_.DisplayIcon; $il=[string]$_.InstallLocation",
2927
2950
  " if($dn -match 'WorkBuddy|CodeBuddy' -or $di -match 'WorkBuddy|CodeBuddy'){",
2928
2951
  " foreach($raw in @($di,$il)){",
2929
2952
  " $p = Clean $raw",
2930
2953
  " if($p -eq ''){ continue }",
2931
- " if(-not (Test-Path -LiteralPath $p -PathType Leaf)){ continue }",
2932
- " $s = $null",
2933
- " try { $s = Get-AuthenticodeSignature -LiteralPath $p } catch { $s = $null }",
2934
- " $st = if($s -ne $null){ [string]$s.Status } else { \"\" }",
2935
- " $sj = if($s -ne $null -and $s.SignerCertificate -ne $null){ [string]$s.SignerCertificate.Subject } else { \"\" }",
2936
- " Write-Output ($p + [char]9 + $st + [char]9 + $sj)",
2954
+ " Write-Output $p",
2937
2955
  " }",
2938
2956
  " }",
2939
2957
  " }",
2940
- "}"
2958
+ "}",
2959
+ "ConvertTo-Json -InputObject @($out) -Compress"
2941
2960
  ].join("\n");
2942
2961
  let stdout;
2943
2962
  const interpreter = scanInterpreter(process.env);
@@ -2960,12 +2979,18 @@ function readRegistryAppPaths() {
2960
2979
  } catch {
2961
2980
  return [];
2962
2981
  }
2982
+ let parsed;
2983
+ try {
2984
+ parsed = JSON.parse(stdout);
2985
+ } catch {
2986
+ return [];
2987
+ }
2988
+ const entries = Array.isArray(parsed) ? parsed : [parsed];
2963
2989
  const out = [];
2964
- for (const line of stdout.split(/\r?\n/u)) {
2965
- const [rawPath, status, signer] = line.trim().split(" ");
2966
- const cleaned = rawPath === void 0 ? "" : cleanIconPath(rawPath);
2967
- if (cleaned === "") continue;
2968
- 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;
2969
2994
  out.push(cleaned);
2970
2995
  }
2971
2996
  return out;
@@ -2977,11 +3002,12 @@ function readRegistryAppPaths() {
2977
3002
  * PowerShell half is not unit-testable, and this half is where the decision
2978
3003
  * actually lives.
2979
3004
  *
2980
- * `Valid` means the chain resolved to a trusted root, which a process running as
2981
- * the user cannot produce for a file it wrote - it would need either a
2982
- * certificate issued to it or administrative access to install a root. That is
2983
- * the whole defence: an uninstall key is user-writable, so "the key names it" is
2984
- * not evidence of anything, while a valid signature is.
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.
2985
3011
  *
2986
3012
  * The publisher is deliberately not pinned. The plugin is a third-party build and
2987
3013
  * the vendor can change its signing certificate; a pinned name would turn that
@@ -2995,17 +3021,100 @@ function readRegistryAppPaths() {
2995
3021
  function signatureAccepts(status, signer) {
2996
3022
  return status === "Valid" && signer !== void 0 && signer.trim() !== "";
2997
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
+ }
2998
3106
  function statExecutables(candidates) {
2999
3107
  const files = [];
3000
3108
  for (const candidate of candidates) {
3001
3109
  if (candidate === "") continue;
3110
+ if (process.platform === "win32" && !localWindowsPath(candidate)) continue;
3002
3111
  try {
3003
3112
  if (statSync(candidate, { throwIfNoEntry: false })?.isFile() === true) files.push(candidate);
3004
3113
  } catch {}
3005
3114
  }
3006
3115
  return files;
3007
3116
  }
3008
- function executableCandidates(env = process.env) {
3117
+ async function executableCandidates(env = process.env) {
3009
3118
  const override = env[WORKBUDDY_APP_EXECUTABLE_ENV]?.trim();
3010
3119
  const known = override === void 0 ? [] : [override];
3011
3120
  if (process.platform === "win32") {
@@ -3026,9 +3135,9 @@ function executableCandidates(env = process.env) {
3026
3135
  const home = homedir();
3027
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"));
3028
3137
  }
3029
- const standard = statExecutables(known);
3138
+ const standard = await signedExecutables(statExecutables(known));
3030
3139
  if (standard.length > 0 || process.platform !== "win32") return standard;
3031
- return statExecutables(windowsRegistryAppPaths());
3140
+ return signedExecutables(statExecutables(windowsRegistryAppPaths()));
3032
3141
  }
3033
3142
  function fetchAtRestKeyPayload(executable) {
3034
3143
  return new Promise((resolve, reject) => {
@@ -3087,10 +3196,10 @@ function ensureAtRestKeys() {
3087
3196
  if (atRestKeyById.size > 0) return Promise.resolve();
3088
3197
  if (Date.now() - lastKeyFailureAtMs < KEY_FAILURE_BACKOFF_MS) return Promise.resolve();
3089
3198
  inflightKeys ??= (async () => {
3090
- const candidates = executableCandidates();
3199
+ const candidates = await executableCandidates();
3091
3200
  if (candidates.length === 0) {
3092
3201
  lastKeyFailureAtMs = Date.now();
3093
- 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";
3094
3203
  return;
3095
3204
  }
3096
3205
  let anySuccess = false;
@@ -4094,7 +4203,7 @@ var WorkBuddyAccountPool = class {
4094
4203
  if (hold.reason !== "spent" || total <= 0) return;
4095
4204
  this.heldIds.delete(accountId);
4096
4205
  if (account.cooldownUntilMs > Date.now() && account.cooldownUntilMs <= hold.until) account.cooldownUntilMs = 0;
4097
- 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`);
4098
4207
  }
4099
4208
  /** True when a known balance has reached the floor set for this account. */
4100
4209
  reserveHolds(accountId) {
@@ -4342,7 +4451,7 @@ var WorkBuddyAccountPool = class {
4342
4451
  lastRefreshAtMs: credential.lastRefreshAtMs ?? 0
4343
4452
  });
4344
4453
  } catch (error) {
4345
- 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)}`);
4346
4455
  continue;
4347
4456
  }
4348
4457
  ownedIds.add(id);
@@ -4365,7 +4474,7 @@ var WorkBuddyAccountPool = class {
4365
4474
  try {
4366
4475
  await renewOwnSignInFile(credential.sourcePath, credential);
4367
4476
  } catch (error) {
4368
- 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)}`);
4369
4478
  }
4370
4479
  return;
4371
4480
  }
@@ -4374,7 +4483,7 @@ var WorkBuddyAccountPool = class {
4374
4483
  try {
4375
4484
  credential.sourcePath = await writeOwnSignIn(directory, ownSignInOf(credential));
4376
4485
  } catch (error) {
4377
- 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)}`);
4378
4487
  }
4379
4488
  }
4380
4489
  /**
@@ -4570,7 +4679,7 @@ var WorkBuddyAccountPool = class {
4570
4679
  if (this.signInRefused(id, account.credential.accessToken)) continue;
4571
4680
  this.heldIds.delete(id);
4572
4681
  if (account.cooldownUntilMs > 0 && account.cooldownUntilMs <= hold.until) account.cooldownUntilMs = 0;
4573
- 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`);
4574
4683
  }
4575
4684
  const foundIds = new Set(found.map((credential) => workbuddyAccountId(credential)));
4576
4685
  for (const [id, refused] of this.refusedSignIns) {
@@ -4870,7 +4979,7 @@ var WorkBuddyAccountPool = class {
4870
4979
  if (credential.expiresAtMs > Date.now() + 3e4) return "fresh";
4871
4980
  if (!this.noRefreshWarned.has(account.id)) {
4872
4981
  this.noRefreshWarned.add(account.id);
4873
- 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`);
4874
4983
  }
4875
4984
  return "noToken";
4876
4985
  }
@@ -4892,13 +5001,13 @@ var WorkBuddyAccountPool = class {
4892
5001
  if (sessionHold !== void 0 && sessionHold.reason === "session") {
4893
5002
  this.heldIds.delete(account.id);
4894
5003
  if (account.cooldownUntilMs > Date.now() && account.cooldownUntilMs <= sessionHold.until) account.cooldownUntilMs = 0;
4895
- 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`);
4896
5005
  }
4897
- this.logger?.info?.(`${LOG_PREFIX}: refreshed token for ${account.label}`);
5006
+ this.logger?.info?.(`${LOG_PREFIX}: refreshed token for ${accountLogTag(account.label)}`);
4898
5007
  return "refreshed";
4899
5008
  } catch (error) {
4900
- if (credential.expiresAtMs > Date.now() + 3e4) this.logger?.warn?.(`${LOG_PREFIX}: token refresh failed but token still valid for ${account.label}`, error);
4901
- 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);
4902
5011
  return upstreamErrorKind(error) === "session_dead" ? "refused" : "failed";
4903
5012
  }
4904
5013
  })();
@@ -4941,7 +5050,7 @@ var WorkBuddyAccountPool = class {
4941
5050
  if (modelId !== void 0 && modelId !== "") {
4942
5051
  pruneModelCooldowns(account, now);
4943
5052
  account.modelCooldowns[modelId] = Math.max(account.modelCooldowns[modelId] ?? 0, until);
4944
- 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()}`);
4945
5054
  return;
4946
5055
  }
4947
5056
  account.cooldownUntilMs = Math.max(account.cooldownUntilMs, until);
@@ -4956,7 +5065,7 @@ var WorkBuddyAccountPool = class {
4956
5065
  heldSignIns
4957
5066
  });
4958
5067
  }
4959
- 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()}`);
4960
5069
  }
4961
5070
  /**
4962
5071
  * Keep one model out of one account's rotation for a stated window.
@@ -5388,6 +5497,16 @@ const KIND_STATUS = {
5388
5497
  */
5389
5498
  const MODEL_TIER_HOLD_MS = 864e5;
5390
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
+ /**
5391
5510
  * The business code an account-level 200 envelope carries.
5392
5511
  *
5393
5512
  * `classifyUpstreamError` only reads codes on the statuses the upstream uses
@@ -5420,6 +5539,7 @@ function conversationKeyOf(raw) {
5420
5539
  return;
5421
5540
  }
5422
5541
  }
5542
+ const EMPTY_STREAM_REFUSAL = "workbuddy returned an empty answer stream";
5423
5543
  /**
5424
5544
  * Read enough of a 200 body to tell an SSE stream from a refusal wearing a 200.
5425
5545
  *
@@ -5460,7 +5580,7 @@ async function peekAnswerHead(reader) {
5460
5580
  if (trimmed === "" && ended) return {
5461
5581
  head,
5462
5582
  ended,
5463
- refusal: "workbuddy returned an empty answer stream"
5583
+ refusal: EMPTY_STREAM_REFUSAL
5464
5584
  };
5465
5585
  if (!jsonLooking) return {
5466
5586
  head,
@@ -5621,7 +5741,6 @@ function createWorkBuddyShim(options) {
5621
5741
  const { pool, client, catalog } = options;
5622
5742
  const region = options.region;
5623
5743
  const logger = options.logger;
5624
- const maxAttempts = 8;
5625
5744
  const server = createLoopbackServer({
5626
5745
  port: options.port,
5627
5746
  label: "workbuddy shim",
@@ -5688,12 +5807,14 @@ function createWorkBuddyShim(options) {
5688
5807
  writeOpenAIError(res, 400, "invalid_request_error", "model is required");
5689
5808
  return;
5690
5809
  }
5691
- const tried = [];
5810
+ let tried = 0;
5692
5811
  const skipped = /* @__PURE__ */ new Set();
5693
5812
  let last;
5694
5813
  let exhaustedByRateLimit = false;
5814
+ let transportAttempts = 0;
5695
5815
  let effortFallback;
5696
5816
  let effortFallbackBuilt = false;
5817
+ const maxAttempts = Math.max(8, pool.list(region).length + 2);
5697
5818
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
5698
5819
  if (controller.signal.aborted) return;
5699
5820
  const account = await pool.acquire(modelId, region, conversationKey, skipped);
@@ -5701,14 +5822,19 @@ function createWorkBuddyShim(options) {
5701
5822
  if (exhaustedByRateLimit && last !== void 0) {
5702
5823
  const model = ` for model ${modelId}`;
5703
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}`;
5704
- 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";
5705
- writeOpenAIError(res, KIND_STATUS[last.kind], last.kind, `${subject} (tried ${tried.length}: ${tried.join(", ")}); ${advice} — ${last.message.slice(0, 200)}`);
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)}`);
5706
5832
  return;
5707
5833
  }
5708
5834
  const regionAccounts = pool.list(region);
5709
5835
  const switchedOff = regionAccounts.filter((account) => pool.isDisabled(account.id));
5710
5836
  if (regionAccounts.length > 0 && switchedOff.length === regionAccounts.length) {
5711
- writeOpenAIError(res, 403, "accounts_switched_off", `every account for this gateway is switched off in the plugin panel (${switchedOff.map((account) => account.label).join(", ")}); switch one back on`);
5837
+ writeOpenAIError(res, 403, "accounts_switched_off", `every account for this gateway is switched off in the plugin panel; switch one back on`);
5712
5838
  return;
5713
5839
  }
5714
5840
  if (regionAccounts.length > 0) {
@@ -5722,14 +5848,14 @@ function createWorkBuddyShim(options) {
5722
5848
  writeOpenAIError(res, 401, "not_signed_in", "no WorkBuddy credential found; sign in on the desktop app (or set WORKBUDDY_AUTH_FILE)");
5723
5849
  return;
5724
5850
  }
5725
- tried.push(account.label);
5851
+ tried += 1;
5726
5852
  let result = await client.chatStream(account.credential, prepared, controller.signal);
5727
5853
  let refreshOutcome;
5728
5854
  if (!result.ok && result.kind === "session_dead") {
5729
5855
  const failure = result;
5730
5856
  refreshOutcome = await pool.refreshAccountOutcome(account.id);
5731
5857
  if (refreshOutcome === "failed") {
5732
- logger?.warn?.(`${LOG_PREFIX}: ${account.label} could not refresh its sign-in; trying the next account without holding it`);
5858
+ logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} could not refresh its sign-in; trying the next account without holding it`);
5733
5859
  skipped.add(account.id);
5734
5860
  last = {
5735
5861
  kind: "transport",
@@ -5760,6 +5886,7 @@ function createWorkBuddyShim(options) {
5760
5886
  let sawDone = false;
5761
5887
  let sawFinish = false;
5762
5888
  let envelopeFailure;
5889
+ let headFailure;
5763
5890
  const decoder = new TextDecoder();
5764
5891
  const sse = new SseDecoder();
5765
5892
  const startStream = () => {
@@ -5818,7 +5945,12 @@ function createWorkBuddyShim(options) {
5818
5945
  ended = peeked.ended;
5819
5946
  if (peeked.refusal !== void 0) {
5820
5947
  await reader.cancel().catch(() => {});
5821
- logger?.warn?.(`${LOG_PREFIX}: ${account.label} answered 200 with no stream: ${peeked.refusal}`);
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}`);
5822
5954
  if (peeked.code === "11128" || unapprovedChannelRefusal(peeked.refusal) !== void 0) {
5823
5955
  writeOpenAIError(res, 400, "upstream_channel_check", channelCheckRefusal());
5824
5956
  return;
@@ -5856,11 +5988,12 @@ function createWorkBuddyShim(options) {
5856
5988
  return;
5857
5989
  }
5858
5990
  } catch (error) {
5859
- startStream();
5860
- failInBand(error);
5991
+ await reader.cancel().catch(() => {});
5992
+ headFailure = safeMessage(error);
5993
+ logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} failed before its first byte; rotating`);
5861
5994
  return;
5862
5995
  }
5863
- logger?.info?.(`${LOG_PREFIX}: served by ${account.label}`);
5996
+ logger?.info?.(`${LOG_PREFIX}: served by ${accountLogTag(account.label)}`);
5864
5997
  startStream();
5865
5998
  let headIndex = 0;
5866
5999
  try {
@@ -5911,6 +6044,18 @@ function createWorkBuddyShim(options) {
5911
6044
  } catch {}
5912
6045
  }
5913
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
+ }
5914
6059
  if (envelopeFailure === void 0) return;
5915
6060
  continue;
5916
6061
  }
@@ -5939,10 +6084,13 @@ function createWorkBuddyShim(options) {
5939
6084
  * configured window rather than a hold that would park a healthy account
5940
6085
  * for hours over a transient block.
5941
6086
  *
5942
- * A `transport` failure is the network path's, not the account's, so the
5943
- * rotation stops: every account here reaches the same host, and trying
5944
- * each one just spends another header timeout before answering. An
5945
- * `aborted` turn is the client's own doing and stops the loop too.
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.
5946
6094
  */
5947
6095
  if (result.kind === "aborted") break;
5948
6096
  if (result.kind === "transport") {
@@ -5952,7 +6100,11 @@ function createWorkBuddyShim(options) {
5952
6100
  message: result.message
5953
6101
  };
5954
6102
  exhaustedByRateLimit = true;
5955
- break;
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;
5956
6108
  }
5957
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;
5958
6110
  exhaustedByRateLimit = true;
@@ -5965,7 +6117,7 @@ function createWorkBuddyShim(options) {
5965
6117
  else if (result.kind === "account_restricted") pool.penalize(account.id, holdUntil(), void 0, "restricted");
5966
6118
  else if (result.kind === "hard_credit" || result.kind === "session_dead") pool.penalize(account.id, holdUntil(), void 0, result.kind === "hard_credit" ? "spent" : "session");
5967
6119
  else pool.penalize(account.id);
5968
- 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`);
5969
6121
  }
5970
6122
  if (last === void 0) {
5971
6123
  writeOpenAIError(res, 500, "internal", "chat request exhausted without a result");
@@ -5980,7 +6132,7 @@ function createWorkBuddyShim(options) {
5980
6132
  writeOpenAIError(res, 400, "upstream_channel_check", unapproved);
5981
6133
  return;
5982
6134
  }
5983
- writeOpenAIError(res, KIND_STATUS[last.kind], last.kind, `workbuddy upstream ${last.kind} (http ${last.status}) after ${tried.length} account(s) [${tried.join(" → ")}]: ${last.message.slice(0, 400)}`);
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)}`);
5984
6136
  }
5985
6137
  return {
5986
6138
  ready,
@@ -7902,7 +8054,11 @@ function bridgeTraeStream(source, model, options = {}) {
7902
8054
  const decoded = decodeTraeEvent(event);
7903
8055
  if (decoded.type === "done" || event.event === "done") upstreamDone = true;
7904
8056
  const failure = traeFailureOf(decoded);
7905
- if (failure !== void 0) throw new Error(describeTraeFailure(failure));
8057
+ if (failure !== void 0) {
8058
+ const refusal = new Error(describeTraeFailure(failure));
8059
+ refusal.traeFailure = failure;
8060
+ throw refusal;
8061
+ }
7906
8062
  if (decoded.type === "unknown") {
7907
8063
  keepalive(controller);
7908
8064
  return;
@@ -8297,10 +8453,13 @@ function createTraeGateway(options) {
8297
8453
  try {
8298
8454
  relayed = await openTraeResponse(result.response, model, { onFailure: (error) => {
8299
8455
  logger?.warn?.("wtq-pool: trae relay stream failed mid-flight", error);
8300
- if (!(error instanceof Error && error.name === "AbortError") && !watcher.signal.aborted) options.onAttemptFailure?.(credential, {
8301
- status: 0,
8302
- kind: "server"
8303
- });
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
+ }
8304
8463
  } });
8305
8464
  } catch (error) {
8306
8465
  if (watcher.signal.aborted || error instanceof Error && error.name === "AbortError") return {
@@ -8359,11 +8518,7 @@ function createTraeGateway(options) {
8359
8518
  }
8360
8519
  opened = attempt;
8361
8520
  if (!rotates(attempt.status, attempt.kind)) break;
8362
- options.onAttemptFailure?.(credential, {
8363
- status: attempt.status,
8364
- ...attempt.kind === void 0 ? {} : { kind: attempt.kind },
8365
- ...attempt.retryAfter === void 0 ? {} : { retryAfter: attempt.retryAfter }
8366
- });
8521
+ options.onAttemptFailure?.(credential, { ...attempt.retryAfter === void 0 ? {} : { retryAfter: attempt.retryAfter } });
8367
8522
  if (index < credentials.length - 1) logger?.warn?.(`${LOG_PREFIX}: trae sign-in failed on ${model} (http ${attempt.status}); rotating`);
8368
8523
  }
8369
8524
  if (opened === void 0 || !opened.ok) {
@@ -9413,13 +9568,16 @@ function qoderWindowOpenAt(campaign, nowMs) {
9413
9568
  function qoderClaimableCampaignOf(payload, nowMs) {
9414
9569
  const list = payload?.campaigns;
9415
9570
  if (!Array.isArray(list)) return void 0;
9571
+ let collected;
9416
9572
  for (const entry of list) {
9417
9573
  if (entry === null || typeof entry !== "object") continue;
9418
9574
  const campaign = entry;
9419
9575
  if (campaign["actionType"] !== QODER_CLAIM_BENEFIT_ACTION) continue;
9420
9576
  if (!qoderWindowOpenAt(campaign, nowMs)) continue;
9421
- return campaign;
9577
+ if (campaign["claimStatus"] !== QODER_CLAIMED_STATUS) return campaign;
9578
+ if (collected === void 0) collected = campaign;
9422
9579
  }
9580
+ return collected;
9423
9581
  }
9424
9582
  /**
9425
9583
  * Id of today's round when it can be claimed right now, else undefined. Kept
@@ -10134,6 +10292,7 @@ function isAcknowledgementCode(value) {
10134
10292
  function unwrapFailure(frame) {
10135
10293
  let code = "";
10136
10294
  let detail = "";
10295
+ const signals = [];
10137
10296
  let node = frame;
10138
10297
  let descended = false;
10139
10298
  let codeFromPlainKey = false;
@@ -10156,8 +10315,10 @@ function unwrapFailure(frame) {
10156
10315
  }
10157
10316
  }
10158
10317
  const message = node["message"] ?? node["errorMessage"];
10159
- if (typeof message === "string" && message.length > 0) detail = 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;
10160
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);
10161
10322
  if (detail === "" && flat !== void 0 && flat.length > 0) detail = flat;
10162
10323
  const nested = isPlainObject(node["details"]) ? node["details"] : isPlainObject(node["error"]) ? node["error"] : void 0;
10163
10324
  const next = nested ?? (typeof message === "string" ? tryJsonObject(message) : void 0);
@@ -10170,25 +10331,32 @@ function unwrapFailure(frame) {
10170
10331
  if (codeFromPlainKey && isAcknowledgementCode(code)) code = "";
10171
10332
  return {
10172
10333
  code,
10173
- detail
10334
+ detail,
10335
+ signals: signals.join("\n")
10174
10336
  };
10175
10337
  }
10176
10338
  /**
10177
10339
  * The gateway's retry hint, when the frame carries one.
10178
10340
  *
10179
- * A carried `0` is the decoder's "no hint" placeholder, not a real wait, so it
10180
- * falls through to the nested value the same way `queueSeconds` does. Treating it
10181
- * as a real answer returned 0 and threw away the actual wait the queue frame
10182
- * carried in its message text.
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.
10183
10345
  */
10184
10346
  function retryAfterSecondsOf(frame) {
10185
- if (!isPlainObject(frame)) return 0;
10186
- const direct = frame["retryAfterSeconds"];
10187
- if (typeof direct === "number" && Number.isFinite(direct) && direct > 0) return direct;
10188
- const { detail } = unwrapFailure(frame);
10189
- if (detail === "") return 0;
10190
- const nested = tryJsonObject(detail)?.["retryAfterSeconds"];
10191
- return typeof nested === "number" && Number.isFinite(nested) && nested > 0 ? nested : 0;
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;
10192
10360
  }
10193
10361
  /**
10194
10362
  * The inner chunk of one data payload: the envelope's `body` when it is a JSON
@@ -10226,7 +10394,7 @@ function decodeQoderFrame(payload) {
10226
10394
  type: "chunk",
10227
10395
  chunk
10228
10396
  };
10229
- const { code, detail } = unwrapFailure(chunk);
10397
+ const { code, detail, signals } = unwrapFailure(chunk);
10230
10398
  if (code === "" && detail === "") return {
10231
10399
  type: "unknown",
10232
10400
  reason: "unnamed",
@@ -10236,6 +10404,7 @@ function decodeQoderFrame(payload) {
10236
10404
  type: "failure",
10237
10405
  code,
10238
10406
  detail,
10407
+ signals,
10239
10408
  retryAfterSeconds: retryAfterSecondsOf(chunk)
10240
10409
  };
10241
10410
  }
@@ -10315,6 +10484,16 @@ var QoderFrameDecoder = class {
10315
10484
  * frame. A vendor that does close its stream wins this race and pays nothing.
10316
10485
  */
10317
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;
10318
10497
  /** Retryable queue wait the gateway answers with 429 + Retry-After. */
10319
10498
  var QoderQueueRejection = class extends Error {
10320
10499
  retryAfterSeconds;
@@ -10394,14 +10573,16 @@ function queueSeconds(frame) {
10394
10573
  */
10395
10574
  function classifyQoderFailure(failure) {
10396
10575
  const code = failure.code.trim();
10397
- 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
+ };
10398
10584
  if (code === "110" || /daily.*(limit|quota)|quota.*daily|allowance.*spent/i.test(text)) {
10399
- const retryAfter = queueSeconds({
10400
- type: "failure",
10401
- code,
10402
- detail: failure.message,
10403
- retryAfterSeconds: failure.retryAfterSeconds ?? 0
10404
- });
10585
+ const retryAfter = queueSeconds(frame);
10405
10586
  return {
10406
10587
  status: 429,
10407
10588
  kind: "hard_credit",
@@ -10411,12 +10592,7 @@ function classifyQoderFailure(failure) {
10411
10592
  if (code === "10605") return {
10412
10593
  status: 429,
10413
10594
  kind: "soft_rate",
10414
- error: new QoderQueueRejection(queueSeconds({
10415
- type: "failure",
10416
- code,
10417
- detail: failure.message,
10418
- retryAfterSeconds: failure.retryAfterSeconds ?? 0
10419
- }), failure.message)
10595
+ error: new QoderQueueRejection(queueSeconds(frame), failure.message)
10420
10596
  };
10421
10597
  if (/Login expired|TOKEN_EXPIRE|token is not active/i.test(text) || code === "105") return {
10422
10598
  status: 401,
@@ -10428,15 +10604,10 @@ function classifyQoderFailure(failure) {
10428
10604
  kind: "client",
10429
10605
  error: new Error(failure.message)
10430
10606
  };
10431
- if (queueMarkerCount(failure.message) >= 2) return {
10607
+ if (queueMarkerCount(text) >= 2) return {
10432
10608
  status: 429,
10433
10609
  kind: "soft_rate",
10434
- error: new QoderQueueRejection(queueSeconds({
10435
- type: "failure",
10436
- code,
10437
- detail: failure.message,
10438
- retryAfterSeconds: failure.retryAfterSeconds ?? 0
10439
- }), failure.message)
10610
+ error: new QoderQueueRejection(queueSeconds(frame), failure.message)
10440
10611
  };
10441
10612
  if (code === "429") return {
10442
10613
  status: 429,
@@ -10591,6 +10762,7 @@ function bridgeQoderStream(source, model, options = {}) {
10591
10762
  const { error } = classifyQoderFailure({
10592
10763
  code: decoded.code,
10593
10764
  message: decoded.detail,
10765
+ signals: decoded.signals,
10594
10766
  retryAfterSeconds: decoded.retryAfterSeconds
10595
10767
  });
10596
10768
  throw error;
@@ -10753,6 +10925,45 @@ function bridgeQoderStream(source, model, options = {}) {
10753
10925
  });
10754
10926
  }
10755
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
+ /**
10756
10967
  * Turn one gateway response into something an OpenAI client can consume.
10757
10968
  *
10758
10969
  * A non-2xx answer becomes a JSON error, and so does a 2xx with no body at all.
@@ -10763,7 +10974,7 @@ function bridgeQoderStream(source, model, options = {}) {
10763
10974
  */
10764
10975
  async function openQoderResponse(response, model, options = {}) {
10765
10976
  if (!response.ok) {
10766
- const detail = (await response.text().catch(() => "")).slice(0, 1024);
10977
+ const detail = await readErrorBody(response, 1024);
10767
10978
  return Response.json({ error: {
10768
10979
  message: detail === "" ? `Qoder returned HTTP ${response.status}` : detail,
10769
10980
  type: "upstream_error",
@@ -10781,26 +10992,52 @@ async function openQoderResponse(response, model, options = {}) {
10781
10992
  const buffered = [];
10782
10993
  let bufferedBytes = 0;
10783
10994
  let sawOutput = false;
10995
+ let sawTerminal = false;
10996
+ let sawQuiet = false;
10997
+ let graceDeadline = 0;
10998
+ let pendingRead;
10784
10999
  let failure;
10785
11000
  let ended = false;
10786
11001
  const inspect = (payloads) => {
10787
11002
  for (const payload of payloads) {
10788
11003
  const decoded = decodeQoderFrame(payload);
10789
11004
  if (decoded.type === "chunk") {
10790
- const choices = decoded.chunk["choices"];
10791
- if (Array.isArray(choices) && choices.length > 0) sawOutput = true;
10792
- else if (decoded.chunk["usage"] !== void 0) sawOutput = true;
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;
10793
11009
  } else if (decoded.type === "failure") failure ??= {
10794
11010
  code: decoded.code,
10795
11011
  message: decoded.detail,
11012
+ signals: decoded.signals,
10796
11013
  retryAfterSeconds: decoded.retryAfterSeconds
10797
11014
  };
10798
- if (sawOutput || failure !== void 0) break;
11015
+ if (sawOutput || sawTerminal || failure !== void 0) break;
10799
11016
  }
10800
11017
  };
10801
11018
  try {
10802
11019
  while (buffered.length < 64 && bufferedBytes < 262144) {
10803
- const next = await reader.read();
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
+ }
10804
11041
  if (next.done) {
10805
11042
  ended = true;
10806
11043
  const rest = decoder.decode();
@@ -10810,9 +11047,11 @@ async function openQoderResponse(response, model, options = {}) {
10810
11047
  buffered.push(next.value);
10811
11048
  bufferedBytes += next.value.byteLength;
10812
11049
  inspect(frames.push(decoder.decode(next.value, { stream: true })));
10813
- 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;
10814
11052
  }
10815
11053
  } catch (error) {
11054
+ pendingRead = void 0;
10816
11055
  await reader.cancel().catch(() => {});
10817
11056
  throw error;
10818
11057
  }
@@ -10831,7 +11070,19 @@ async function openQoderResponse(response, model, options = {}) {
10831
11070
  ...wait === void 0 ? {} : { headers: { "Retry-After": wait } }
10832
11071
  });
10833
11072
  }
10834
- const relay = bridgeQoderStream(replaySource(buffered, reader, ended), model, options);
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);
10835
11086
  return withRelayStream(new Response(relay, {
10836
11087
  status: 200,
10837
11088
  headers: { "Content-Type": "text/event-stream" }
@@ -10983,10 +11234,10 @@ function createQoderGateway(options) {
10983
11234
  try {
10984
11235
  relayed = await openQoderResponse(result.response, model, { onFailure: (error) => {
10985
11236
  logger?.warn?.("wtq-pool: qoder relay stream failed mid-flight", error);
10986
- if (!(error instanceof Error && error.name === "AbortError") && !watcher.signal.aborted) options.onAttemptFailure?.(credential, {
10987
- status: 0,
10988
- kind: "server"
10989
- });
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
+ }
10990
11241
  } });
10991
11242
  } catch (error) {
10992
11243
  if (watcher.signal.aborted || error instanceof Error && error.name === "AbortError") return {
@@ -11039,11 +11290,7 @@ function createQoderGateway(options) {
11039
11290
  }
11040
11291
  opened = attempt;
11041
11292
  if (!rotates(attempt.status, attempt.kind)) break;
11042
- options.onAttemptFailure?.(credential, {
11043
- status: attempt.status,
11044
- ...attempt.kind === void 0 ? {} : { kind: attempt.kind },
11045
- ...attempt.retryAfter === void 0 ? {} : { retryAfter: attempt.retryAfter }
11046
- });
11293
+ options.onAttemptFailure?.(credential, { ...attempt.retryAfter === void 0 ? {} : { retryAfter: attempt.retryAfter } });
11047
11294
  if (index < credentials.length - 1) logger?.warn?.(`${LOG_PREFIX}: qoder sign-in failed on ${model} (http ${attempt.status}); rotating`);
11048
11295
  }
11049
11296
  if (opened === void 0 || !opened.ok) {
@@ -11170,6 +11417,23 @@ function baseFor(realm) {
11170
11417
  function originFor(realm) {
11171
11418
  return realm === "global" ? GLOBAL_ORIGIN : CN_ORIGIN;
11172
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
+ }
11173
11437
  /** Browser-shaped headers; `Origin` is the one the endpoints check. */
11174
11438
  function loginHeaders(origin) {
11175
11439
  return {
@@ -11224,7 +11488,7 @@ async function startDeviceLogin(realm, fetchImpl = fetch) {
11224
11488
  if (state === "" || authUrl === "") throw new Error(`workbuddy login start gave no state or url: ${envelope.msg}`);
11225
11489
  return {
11226
11490
  state,
11227
- authUrl
11491
+ authUrl: checkedAuthUrl(authUrl)
11228
11492
  };
11229
11493
  }
11230
11494
  /**
@@ -11911,7 +12175,8 @@ const STREAK_REPORT_READ_GAP_MS = 1200;
11911
12175
  const travelAdoptTried = /* @__PURE__ */ new Map();
11912
12176
  function log(level, message) {
11913
12177
  try {
11914
- console.log("[wtq-pool] " + level + ": " + message);
12178
+ const text = redactSecrets(String(message));
12179
+ console.log("[wtq-pool] " + level + ": " + text);
11915
12180
  } catch {}
11916
12181
  }
11917
12182
  /**
@@ -13471,7 +13736,11 @@ function refreshNeeded() {
13471
13736
  */
13472
13737
  function cooldownPending() {
13473
13738
  const now = Date.now();
13474
- for (const account of core.pool.list()) if (account.cooldownUntilMs > now) return true;
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
+ }
13475
13744
  return false;
13476
13745
  }
13477
13746
  /** True while any pool account's cached billing answers are missing or old. */
@@ -15054,6 +15323,7 @@ async function onPanelInvoke(channel, payload) {
15054
15323
  checkinPassRunning = true;
15055
15324
  const answered = await settleWithin((async () => {
15056
15325
  const outcome = source === "trae" ? await traeClaimOne(label, region) : await qoderClaimOne(label, region);
15326
+ markSourceCheckinRow(source, label, region, outcome);
15057
15327
  return {
15058
15328
  state: await statusDocument({
15059
15329
  allowNetwork: true,
@@ -15581,17 +15851,17 @@ async function redeemAccountStreak(account) {
15581
15851
  const yesterday = zonedDay(-1);
15582
15852
  await core.client.useMakeupCard(account.credential, yesterday);
15583
15853
  detail.makeup += 1;
15584
- log("info", "streak " + account.label + ": make-up card spent on " + yesterday);
15854
+ log("info", "streak " + accountLogTag(account.label) + ": make-up card spent on " + yesterday);
15585
15855
  }
15586
15856
  } catch (error) {
15587
15857
  detail.failed += 1;
15588
- log("warn", "streak " + account.label + ": make-up: " + safeMessage(error));
15858
+ log("warn", "streak " + accountLogTag(account.label) + ": make-up: " + safeMessage(error));
15589
15859
  }
15590
15860
  for (const [label, collect] of [["gift", () => core.client.claimGift(account.credential)], ["compensation", () => core.client.claimCompensation(account.credential)]]) try {
15591
15861
  const paid = await collect();
15592
15862
  if (paid > 0) {
15593
15863
  detail[label] += paid;
15594
- log("info", "streak " + account.label + ": " + label + " +" + paid + "c");
15864
+ log("info", "streak " + accountLogTag(account.label) + ": " + label + " +" + paid + "c");
15595
15865
  }
15596
15866
  } catch {}
15597
15867
  try {
@@ -15599,7 +15869,7 @@ async function redeemAccountStreak(account) {
15599
15869
  detail.activity += 1;
15600
15870
  } catch (error) {
15601
15871
  detail.failed += 1;
15602
- log("warn", "streak " + account.label + ": activity report failed: " + safeMessage(error));
15872
+ log("warn", "streak " + accountLogTag(account.label) + ": activity report failed: " + safeMessage(error));
15603
15873
  }
15604
15874
  await checkinDelay(STREAK_REPORT_READ_GAP_MS);
15605
15875
  const status = await core.client.growthStreakFull(account.credential);
@@ -15614,10 +15884,10 @@ async function redeemAccountStreak(account) {
15614
15884
  credit += tier.credit;
15615
15885
  energy += tier.energy;
15616
15886
  detail.streak += 1;
15617
- 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)");
15618
15888
  } catch (error) {
15619
15889
  detail.failed += 1;
15620
- log("warn", "streak " + account.label + ": redeem " + tier.tier + " failed: " + safeMessage(error));
15890
+ log("warn", "streak " + accountLogTag(account.label) + ": redeem " + tier.tier + " failed: " + safeMessage(error));
15621
15891
  }
15622
15892
  }
15623
15893
  try {
@@ -15625,11 +15895,11 @@ async function redeemAccountStreak(account) {
15625
15895
  for (let draw = 0; draw < chances; draw += 1) {
15626
15896
  const prize = await core.client.drawLottery(account.credential);
15627
15897
  detail.lottery += 1;
15628
- 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));
15629
15899
  }
15630
15900
  } catch (error) {
15631
15901
  detail.failed += 1;
15632
- log("warn", "streak " + account.label + ": lottery: " + safeMessage(error));
15902
+ log("warn", "streak " + accountLogTag(account.label) + ": lottery: " + safeMessage(error));
15633
15903
  }
15634
15904
  return {
15635
15905
  claimed,
@@ -15670,7 +15940,7 @@ async function claimAllGrowth() {
15670
15940
  } catch (error) {
15671
15941
  counts.failed += 1;
15672
15942
  counts.detail.failed += 1;
15673
- log("warn", "streak failed for " + account.label + ": " + safeMessage(error));
15943
+ log("warn", "streak failed for " + accountLogTag(account.label) + ": " + safeMessage(error));
15674
15944
  }
15675
15945
  if (collected) probeCache.delete(account.id);
15676
15946
  }
@@ -15723,7 +15993,7 @@ async function readGrowthState() {
15723
15993
  chances
15724
15994
  };
15725
15995
  } catch (error) {
15726
- log("warn", "growth state failed for " + account.label + ": " + safeMessage(error));
15996
+ log("warn", "growth state failed for " + accountLogTag(account.label) + ": " + safeMessage(error));
15727
15997
  return {
15728
15998
  account,
15729
15999
  error
@@ -15806,7 +16076,7 @@ async function claimAllCheckins() {
15806
16076
  continue;
15807
16077
  }
15808
16078
  counts.failed += 1;
15809
- log("warn", "check-in failed for " + account.label + ": " + safeMessage(error));
16079
+ log("warn", "check-in failed for " + accountLogTag(account.label) + ": " + safeMessage(error));
15810
16080
  }
15811
16081
  }
15812
16082
  return counts;
@@ -15833,13 +16103,13 @@ async function travelAdopt(account) {
15833
16103
  try {
15834
16104
  await core.client.reportChatActivity(account.credential, conversationId);
15835
16105
  } catch (error) {
15836
- log("warn", "travel " + account.label + ": adopt preflight report: " + safeMessage(error));
16106
+ log("warn", "travel " + accountLogTag(account.label) + ": adopt preflight report: " + safeMessage(error));
15837
16107
  }
15838
16108
  await checkinDelay(TRAVEL_ADOPT_GAP_MS);
15839
16109
  try {
15840
16110
  await core.client.agreeBuddy(account.credential);
15841
16111
  } catch (error) {
15842
- log("warn", "travel " + account.label + ": agreement: " + safeMessage(error));
16112
+ log("warn", "travel " + accountLogTag(account.label) + ": agreement: " + safeMessage(error));
15843
16113
  return "failed";
15844
16114
  }
15845
16115
  try {
@@ -15847,13 +16117,13 @@ async function travelAdopt(account) {
15847
16117
  } catch (error) {
15848
16118
  if (isBuddyThresholdIncomplete(safeMessage(error))) {
15849
16119
  travelAdoptTried.set(account.id, day);
15850
- 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)");
15851
16121
  return "skipped";
15852
16122
  }
15853
- log("warn", "travel " + account.label + ": adopt: " + safeMessage(error));
16123
+ log("warn", "travel " + accountLogTag(account.label) + ": adopt: " + safeMessage(error));
15854
16124
  return "failed";
15855
16125
  }
15856
- log("info", "travel " + account.label + ": adopt ok");
16126
+ log("info", "travel " + accountLogTag(account.label) + ": adopt ok");
15857
16127
  return "adopted";
15858
16128
  }
15859
16129
  /**
@@ -15867,7 +16137,7 @@ async function travelOne(account) {
15867
16137
  try {
15868
16138
  buddy = await core.client.fetchBuddyInfo(account.credential);
15869
16139
  } catch (error) {
15870
- log("warn", "travel " + account.label + ": buddy-info: " + safeMessage(error));
16140
+ log("warn", "travel " + accountLogTag(account.label) + ": buddy-info: " + safeMessage(error));
15871
16141
  return "failed";
15872
16142
  }
15873
16143
  if (buddy === null) return await travelAdopt(account);
@@ -15875,42 +16145,42 @@ async function travelOne(account) {
15875
16145
  try {
15876
16146
  status = await core.client.fetchTravelStatus(account.credential);
15877
16147
  } catch (error) {
15878
- log("warn", "travel " + account.label + ": status: " + safeMessage(error));
16148
+ log("warn", "travel " + accountLogTag(account.label) + ": status: " + safeMessage(error));
15879
16149
  return "failed";
15880
16150
  }
15881
16151
  if (status.state === "arrived") {
15882
16152
  if (status.recordId === 0) {
15883
- 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)");
15884
16154
  return "skipped";
15885
16155
  }
15886
16156
  try {
15887
16157
  const reward = await core.client.claimTravelReward(account.credential, status.recordId);
15888
- 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);
15889
16159
  return "claimed";
15890
16160
  } catch (error) {
15891
- log("warn", "travel " + account.label + ": claim record=" + status.recordId + ": " + safeMessage(error));
16161
+ log("warn", "travel " + accountLogTag(account.label) + ": claim record=" + status.recordId + ": " + safeMessage(error));
15892
16162
  return "failed";
15893
16163
  }
15894
16164
  }
15895
16165
  if (status.state === "idle") {
15896
16166
  if (status.dailyLimitReached) {
15897
- log("info", "travel " + account.label + ": skip (daily limit reached)");
16167
+ log("info", "travel " + accountLogTag(account.label) + ": skip (daily limit reached)");
15898
16168
  return "skipped";
15899
16169
  }
15900
16170
  try {
15901
16171
  await core.client.departTravel(account.credential, 4);
15902
- log("info", "travel " + account.label + ": depart ok location=4");
16172
+ log("info", "travel " + accountLogTag(account.label) + ": depart ok location=4");
15903
16173
  return "departed";
15904
16174
  } catch (error) {
15905
- log("warn", "travel " + account.label + ": depart: " + safeMessage(error));
16175
+ log("warn", "travel " + accountLogTag(account.label) + ": depart: " + safeMessage(error));
15906
16176
  return "failed";
15907
16177
  }
15908
16178
  }
15909
16179
  if (status.state === "traveling") {
15910
- log("info", "travel " + account.label + ": skip (traveling record=" + status.recordId + ")");
16180
+ log("info", "travel " + accountLogTag(account.label) + ": skip (traveling record=" + status.recordId + ")");
15911
16181
  return "skipped";
15912
16182
  }
15913
- 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) + ")");
15914
16184
  return "skipped";
15915
16185
  }
15916
16186
  /**
@@ -15942,7 +16212,7 @@ async function travelAllAccounts() {
15942
16212
  } else if (outcome === "failed") counts.failed += 1;
15943
16213
  } catch (error) {
15944
16214
  counts.failed += 1;
15945
- log("warn", "travel failed for " + account.label + ": " + safeMessage(error));
16215
+ log("warn", "travel failed for " + accountLogTag(account.label) + ": " + safeMessage(error));
15946
16216
  }
15947
16217
  }
15948
16218
  return counts;
@@ -15986,6 +16256,7 @@ async function qoderCheckinAll() {
15986
16256
  seen += 1;
15987
16257
  const result = await qoderClaimFor(credential);
15988
16258
  counts[result.outcome] += 1;
16259
+ markSourceCheckinRow("qoder", qoderRowLabel(credential), credential.region, result);
15989
16260
  if (result.retry === true) counts.retry = true;
15990
16261
  if (result.opensAt !== void 0 && (counts.opensAt === void 0 || result.opensAt < counts.opensAt)) counts.opensAt = result.opensAt;
15991
16262
  }
@@ -15998,6 +16269,14 @@ async function qoderCheckinAll() {
15998
16269
  * that already collected) costs a single GET and no mutation.
15999
16270
  */
16000
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
+ }
16001
16280
  const client = new QoderUpstreamClient({
16002
16281
  region: credential.region,
16003
16282
  credential: async () => qoderClientCredential(credential)
@@ -16009,22 +16288,23 @@ async function qoderClaimFor(credential) {
16009
16288
  const state = qoderCheckinStateFrom(campaigns);
16010
16289
  return {
16011
16290
  outcome: "skipped",
16291
+ ...state.todayCheckedIn === true ? { todayCheckedIn: true } : {},
16012
16292
  ...state.opensAt === void 0 ? {} : { opensAt: state.opensAt }
16013
16293
  };
16014
16294
  }
16015
16295
  const result = qoderNormalizeClaimResult(await client.claimCampaign(id));
16016
16296
  if (result.reason !== void 0) {
16017
- 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);
16018
16298
  return {
16019
16299
  outcome: "failed",
16020
16300
  reason: result.reason,
16021
16301
  retry: false
16022
16302
  };
16023
16303
  }
16024
- return { outcome: result.claimed && !result.replayed ? "claimed" : "skipped" };
16304
+ return { outcome: result.claimed ? "claimed" : "skipped" };
16025
16305
  } catch (error) {
16026
16306
  const reason = safeMessage(error);
16027
- 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);
16028
16308
  return {
16029
16309
  outcome: "failed",
16030
16310
  reason,
@@ -16066,16 +16346,24 @@ async function traeCheckinAll() {
16066
16346
  };
16067
16347
  }
16068
16348
  const cnCredentials = found.credentials.filter((credential) => traeRegionOfCredential(credential) === "cn");
16349
+ const spentEditions = /* @__PURE__ */ new Set();
16069
16350
  let index = 0;
16070
16351
  for (; index < cnCredentials.length; index += 1) {
16071
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
+ }
16072
16362
  if (index > 0) await checkinDelay(Math.max(1e3, TRAE_ACCOUNT_DELAY_MS + Math.round((Math.random() * 2 - 1) * TRAE_ACCOUNT_JITTER_MS)));
16073
- const result = await traeClaimFor(cnCredentials[index], desktopCandidates);
16363
+ const result = await traeClaimFor(credential, desktopCandidates);
16074
16364
  counts[result.outcome] += 1;
16075
- if (result.deviceCheckedIn === true) {
16076
- counts.skipped += cnCredentials.length - index - 1;
16077
- break;
16078
- }
16365
+ markSourceCheckinRow("trae", traeRowLabel(credential), "cn", result);
16366
+ if (result.deviceCheckedIn === true) spentEditions.add(credential.edition);
16079
16367
  }
16080
16368
  return counts;
16081
16369
  }
@@ -16132,7 +16420,7 @@ async function traeClaimFor(credential, desktopCandidates) {
16132
16420
  const label = traeRowLabel(credential);
16133
16421
  if (sourceCredentialExpired(credential, Date.now())) {
16134
16422
  const reason = "token expired (open Trae to refresh it)";
16135
- 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)");
16136
16424
  return {
16137
16425
  outcome: "skipped",
16138
16426
  reason
@@ -16145,7 +16433,10 @@ async function traeClaimFor(credential, desktopCandidates) {
16145
16433
  try {
16146
16434
  const status = await client.fetchCheckinStatus();
16147
16435
  if (status.code === 0 && status.enable === false) return { outcome: "skipped" };
16148
- if (status.code === 0 && status.checkedIn) return { outcome: "skipped" };
16436
+ if (status.code === 0 && status.checkedIn) return {
16437
+ outcome: "skipped",
16438
+ todayCheckedIn: true
16439
+ };
16149
16440
  if (status.code === 0 && status.didCheckedIn) return {
16150
16441
  outcome: "skipped",
16151
16442
  deviceCheckedIn: true
@@ -16153,27 +16444,45 @@ async function traeClaimFor(credential, desktopCandidates) {
16153
16444
  const claim = status.code === 0 ? await client.claimCheckin() : status;
16154
16445
  if (claim.code === 0) return { outcome: "claimed" };
16155
16446
  if (claim.code === 9095) {
16156
- 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 ?? ""));
16157
16448
  return {
16158
16449
  outcome: "skipped",
16159
16450
  deviceCheckedIn: true
16160
16451
  };
16161
16452
  }
16162
16453
  const reason = await traeCheckinReason("code " + claim.code + (claim.message === void 0 ? "" : " " + safeMessage(claim.message)), credential, desktopCandidates);
16163
- log("warn", "[trae:cn] check-in refused for " + label + ": " + reason);
16454
+ log("warn", "[trae:cn] check-in refused for " + accountLogTag(label) + ": " + reason);
16164
16455
  return {
16165
16456
  outcome: "failed",
16166
16457
  reason
16167
16458
  };
16168
16459
  } catch (error) {
16169
16460
  const reason = await traeCheckinReason(safeMessage(error), credential, desktopCandidates);
16170
- log("warn", "[trae:cn] check-in failed for " + label + ": " + reason);
16461
+ log("warn", "[trae:cn] check-in failed for " + accountLogTag(label) + ": " + reason);
16171
16462
  return {
16172
16463
  outcome: "failed",
16173
16464
  reason
16174
16465
  };
16175
16466
  }
16176
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
+ }
16177
16486
  /** The one Trae account a panel row names, or a refusal that says why. */
16178
16487
  async function traeClaimOne(label, region) {
16179
16488
  if (region !== "cn") throw panelError("Trae check-in is CN-only", "INVALID");
@@ -17262,7 +17571,7 @@ function apply(ctx, config = {}) {
17262
17571
  try {
17263
17572
  if (typeof settingsService?.configure === "function") ctx.effect(() => settingsService.configure?.({ auto: true }, ctx.fiber) ?? (() => {}));
17264
17573
  } catch (error) {
17265
- ctx.logger.warn?.("dsh-wtq-pool: settings section unavailable", error);
17574
+ ctx.logger.warn?.("dsh-wtq-pool: settings section unavailable", safeMessage(error));
17266
17575
  }
17267
17576
  ctx.effect(() => {
17268
17577
  disposeDiscovery?.();