dsh-wtq-pool 1.3.1 → 1.3.6

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,7 +12,7 @@ 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
+ import { constants, createCipheriv, createDecipheriv, createHash, pbkdf2Sync, publicEncrypt, randomBytes, randomUUID } from "node:crypto";
16
16
  import * as net from "node:net";
17
17
  import { BlockList, isIP } from "node:net";
18
18
  import * as fs$1 from "node:fs";
@@ -1425,7 +1425,7 @@ function retryAfterSeconds(headers) {
1425
1425
  * read as a clean end, which the relay would otherwise report as a finished
1426
1426
  * turn with a truncated reply.
1427
1427
  */
1428
- function withIdleWatchdog(body, idleMs = STREAM_IDLE_TIMEOUT_MS$1, signal) {
1428
+ function withIdleWatchdog(body, idleMs = STREAM_IDLE_TIMEOUT_MS$1, signal, abortTransport) {
1429
1429
  const reader = body.getReader();
1430
1430
  let timer;
1431
1431
  let idle;
@@ -1446,6 +1446,7 @@ function withIdleWatchdog(body, idleMs = STREAM_IDLE_TIMEOUT_MS$1, signal) {
1446
1446
  const stop = (reason) => {
1447
1447
  if (idle !== void 0) return;
1448
1448
  idle = reason;
1449
+ abortTransport?.(reason);
1449
1450
  reader.cancel(reason).catch(() => {});
1450
1451
  disarm();
1451
1452
  detach();
@@ -1495,6 +1496,7 @@ function withIdleWatchdog(body, idleMs = STREAM_IDLE_TIMEOUT_MS$1, signal) {
1495
1496
  },
1496
1497
  cancel(reason) {
1497
1498
  finish();
1499
+ abortTransport?.(reason);
1498
1500
  return reader.cancel(reason);
1499
1501
  }
1500
1502
  });
@@ -1528,6 +1530,7 @@ function headersDeadline(caller, ms) {
1528
1530
  timer.unref?.();
1529
1531
  return {
1530
1532
  signal: controller.signal,
1533
+ abort: (reason) => controller.abort(reason),
1531
1534
  arrived: () => {
1532
1535
  clearTimeout(timer);
1533
1536
  caller?.removeEventListener("abort", onCallerAbort);
@@ -2387,7 +2390,7 @@ var WorkBuddyUpstreamClient = class {
2387
2390
  status: 502,
2388
2391
  message: "upstream returned 200 without a stream"
2389
2392
  };
2390
- const relayed = withIdleWatchdog(response.body, timeouts?.idleMs, signal);
2393
+ const relayed = withIdleWatchdog(response.body, timeouts?.idleMs, signal, deadline.abort);
2391
2394
  return {
2392
2395
  ok: true,
2393
2396
  response: withRelayStream(new Response(relayed, {
@@ -2397,6 +2400,7 @@ var WorkBuddyUpstreamClient = class {
2397
2400
  };
2398
2401
  }
2399
2402
  const text = await readErrorBody(response, ERROR_BODY_LIMIT, signal);
2403
+ deadline.abort();
2400
2404
  const retryAfter = retryAfterSeconds(response.headers);
2401
2405
  if (attempt === 0 && response.status === 400 && isChannelCheckText(text)) {
2402
2406
  const folded = foldSystemIntoUser(body);
@@ -3485,33 +3489,32 @@ async function encryptedFieldOpener() {
3485
3489
  }
3486
3490
  //#endregion
3487
3491
  //#region src/trusted-process.ts
3488
- /** Resolve the OS directory without trusting inherited Windows environment variables. */
3489
- function trustedSystemRootOf(env) {
3490
- if (process.platform === "win32") try {
3492
+ /** Resolve the OS directory from the kernel, never from an inherited variable. */
3493
+ function trustedSystemRootOf() {
3494
+ if (process.platform !== "win32") return void 0;
3495
+ try {
3491
3496
  return realpathSync.native("\\\\?\\GLOBALROOT\\SystemRoot");
3492
3497
  } catch {
3493
3498
  return;
3494
3499
  }
3495
- const value = env["SystemRoot"]?.trim() || env["windir"]?.trim();
3496
- return value === void 0 || value === "" ? void 0 : value;
3497
3500
  }
3498
- function trustedWindowsPowerShell(env) {
3499
- const systemRoot = trustedSystemRootOf(env);
3501
+ function trustedWindowsPowerShell() {
3502
+ const systemRoot = trustedSystemRootOf();
3500
3503
  if (systemRoot === void 0) return void 0;
3501
3504
  return join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
3502
3505
  }
3503
3506
  /** Build a PowerShell environment with fixed executable and module search paths. */
3504
- function trustedWindowsChildEnv(env, options = {}) {
3505
- const systemRoot = trustedSystemRootOf(env);
3507
+ function trustedWindowsChildEnv(env) {
3508
+ const systemRoot = trustedSystemRootOf();
3506
3509
  if (systemRoot === void 0) return {};
3507
3510
  const result = {};
3508
- if (options.inheritTemp === true) for (const name of ["TEMP", "TMP"]) {
3511
+ for (const name of ["TEMP", "TMP"]) {
3509
3512
  const value = env[name];
3510
3513
  if (value !== void 0 && value !== "") result[name] = value;
3511
3514
  }
3512
3515
  result.SystemRoot = systemRoot;
3513
3516
  result.windir = systemRoot;
3514
- if (options.includeSystemDrive === true && /^[A-Za-z]:\\/.test(systemRoot)) result.SystemDrive = systemRoot.slice(0, 2);
3517
+ if (/^[A-Za-z]:\\/.test(systemRoot)) result.SystemDrive = systemRoot.slice(0, 2);
3515
3518
  result.PATH = join(systemRoot, "System32");
3516
3519
  result.PSModulePath = join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "Modules");
3517
3520
  return result;
@@ -3635,8 +3638,8 @@ function processOutput(command, args, env, cwd, timeoutMs) {
3635
3638
  async function processStartedAt(pid, timeoutMs = 2e3) {
3636
3639
  if (pid === process.pid) return PROCESS_STARTED_AT_MS;
3637
3640
  if (process.platform === "win32") {
3638
- const systemRoot = trustedSystemRootOf(process.env);
3639
- const powershell = trustedWindowsPowerShell(process.env);
3641
+ const systemRoot = trustedSystemRootOf();
3642
+ const powershell = trustedWindowsPowerShell();
3640
3643
  if (systemRoot === void 0 || powershell === void 0) return void 0;
3641
3644
  const match = (await processOutput(powershell, [
3642
3645
  "-NoLogo",
@@ -3644,10 +3647,7 @@ async function processStartedAt(pid, timeoutMs = 2e3) {
3644
3647
  "-NonInteractive",
3645
3648
  "-Command",
3646
3649
  `$env:PSModulePath=[IO.Path]::Combine($env:SystemRoot,'System32\\WindowsPowerShell\\v1.0\\Modules'); $d=(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime(); ([DateTimeOffset]$d).ToUnixTimeMilliseconds()`
3647
- ], trustedWindowsChildEnv(process.env, {
3648
- inheritTemp: true,
3649
- includeSystemDrive: true
3650
- }), join(systemRoot, "System32"), timeoutMs))?.match(/\d{10,}/);
3650
+ ], trustedWindowsChildEnv(process.env), join(systemRoot, "System32"), timeoutMs))?.match(/\d{10,}/);
3651
3651
  return match === void 0 || match === null ? void 0 : Number(match[0]);
3652
3652
  }
3653
3653
  const ps = ["/usr/bin/ps", "/bin/ps"].find(existsSync);
@@ -4971,12 +4971,16 @@ function sameDirs(a, b) {
4971
4971
  * over every sign-in it still holds.
4972
4972
  */
4973
4973
  async function readArchivedCredentials(file) {
4974
- const stored = /* @__PURE__ */ new Map();
4974
+ const result = {
4975
+ stored: /* @__PURE__ */ new Map(),
4976
+ pruned: false
4977
+ };
4978
+ const { stored } = result;
4975
4979
  let text;
4976
4980
  try {
4977
4981
  text = await readFile(file, "utf8");
4978
4982
  } catch (error) {
4979
- if (error.code === "ENOENT") return stored;
4983
+ if (error.code === "ENOENT") return result;
4980
4984
  throw error;
4981
4985
  }
4982
4986
  let parsed;
@@ -4985,9 +4989,9 @@ async function readArchivedCredentials(file) {
4985
4989
  } catch {
4986
4990
  throw new Error("credential archive is not valid JSON");
4987
4991
  }
4988
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return stored;
4992
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return result;
4989
4993
  const entries = parsed.entries;
4990
- if (!Array.isArray(entries)) return stored;
4994
+ if (!Array.isArray(entries)) return result;
4991
4995
  const horizon = Date.now() - ARCHIVE_RETENTION_MS;
4992
4996
  for (const entry of entries) {
4993
4997
  if (typeof entry !== "object" || entry === null) continue;
@@ -4998,7 +5002,10 @@ async function readArchivedCredentials(file) {
4998
5002
  const refreshExpiresAt = typeof record["refreshExpiresAtMs"] === "number" ? expiryToMs(record["refreshExpiresAtMs"]) : 0;
4999
5003
  const lastRefreshAt = typeof record["lastRefreshAtMs"] === "number" ? expiryToMs(record["lastRefreshAtMs"]) : 0;
5000
5004
  const lastUsable = Math.max(expiresAt, refreshExpiresAt);
5001
- if (lastUsable > 0 && lastUsable < horizon) continue;
5005
+ if (lastUsable > 0 && lastUsable < horizon) {
5006
+ result.pruned = true;
5007
+ continue;
5008
+ }
5002
5009
  stored.set(record["id"], {
5003
5010
  accessToken: record["accessToken"],
5004
5011
  refreshToken: typeof record["refreshToken"] === "string" ? record["refreshToken"] : "",
@@ -5013,7 +5020,7 @@ async function readArchivedCredentials(file) {
5013
5020
  sourcePath: typeof record["sourcePath"] === "string" ? record["sourcePath"] : ""
5014
5021
  });
5015
5022
  }
5016
- return stored;
5023
+ return result;
5017
5024
  }
5018
5025
  /** How old a leftover write temp must be before another writer removes it. */
5019
5026
  const ABANDONED_TEMP_MAX_AGE_MS = 6e5;
@@ -5453,30 +5460,34 @@ var WorkBuddyAccountPool = class {
5453
5460
  current: true
5454
5461
  }, deletingCredential);
5455
5462
  }
5456
- const onDisk = await readCredential(ownedPath);
5457
- if (!replaced) replaced = onDisk.kind === "sealed" || onDisk.kind === "unreadable" || onDisk.kind === "credential" && (workbuddyAccountId(onDisk.credential) !== account.id || !sameCredential(onDisk.credential));
5458
- if (replaced) {
5459
- await fail();
5460
- return false;
5461
- }
5462
5463
  try {
5463
- const tombstoneFile = this.deletedSignInsFile();
5464
- if (tombstoneFile === void 0) await unlink(ownedPath);
5465
- else await withFileLock(`${tombstoneFile}.lock`, async () => {
5466
- await unlink(ownedPath);
5464
+ await withSignInWriteLock(ownedPath, async () => {
5465
+ const onDisk = await readCredential(ownedPath);
5466
+ if (!replaced) replaced = onDisk.kind === "sealed" || onDisk.kind === "unreadable" || onDisk.kind === "credential" && (workbuddyAccountId(onDisk.credential) !== account.id || !sameCredential(onDisk.credential));
5467
+ if (replaced) return;
5468
+ try {
5469
+ const tombstoneFile = this.deletedSignInsFile();
5470
+ if (tombstoneFile === void 0) await unlink(ownedPath);
5471
+ else await withFileLock(`${tombstoneFile}.lock`, async () => {
5472
+ await unlink(ownedPath);
5473
+ });
5474
+ } catch (error) {
5475
+ if (!(error instanceof FileLockReleaseError) && error.code !== "ENOENT") throw error;
5476
+ }
5477
+ await removeAbandonedTemps(ownedPath, 0);
5467
5478
  });
5468
5479
  } catch (error) {
5469
- const code = error.code;
5470
- if (!(error instanceof FileLockReleaseError) && code !== "ENOENT") {
5471
- await fail();
5472
- this.rosterRevision += 1;
5473
- await this.rescan().catch((rescanError) => {
5474
- this.logger?.warn?.(`${LOG_PREFIX}: could not restore the roster after a failed delete: ${String(rescanError)}`);
5475
- });
5476
- throw error;
5477
- }
5480
+ await fail();
5481
+ this.rosterRevision += 1;
5482
+ await this.rescan().catch((rescanError) => {
5483
+ this.logger?.warn?.(`${LOG_PREFIX}: could not restore the roster after a failed delete: ${String(rescanError)}`);
5484
+ });
5485
+ throw error;
5486
+ }
5487
+ if (replaced) {
5488
+ await fail();
5489
+ return false;
5478
5490
  }
5479
- await removeAbandonedTemps(ownedPath, 0);
5480
5491
  this.rosterRevision += 1;
5481
5492
  const archivedIds = this.storedIds(account.id);
5482
5493
  if (!settled) running.catch(() => {}).then(() => this.forgetArchived(archivedIds));
@@ -5784,8 +5795,8 @@ var WorkBuddyAccountPool = class {
5784
5795
  if (file === void 0) return;
5785
5796
  const run = this.archiveQueue.then(async () => {
5786
5797
  await withFileLock(`${file}.lock`, async () => {
5787
- const stored = await readArchivedCredentials(file);
5788
- let dropped = false;
5798
+ const { stored, pruned } = await readArchivedCredentials(file);
5799
+ let dropped = pruned;
5789
5800
  for (const id of ids) dropped = stored.delete(id) || dropped;
5790
5801
  if (!dropped) return;
5791
5802
  await writeArchivedCredentials(file, stored);
@@ -5863,11 +5874,11 @@ var WorkBuddyAccountPool = class {
5863
5874
  const run = this.archiveQueue.then(async () => {
5864
5875
  await withFileLock(`${file}.lock`, async () => {
5865
5876
  if (signal?.aborted) return;
5866
- const stored = await readArchivedCredentials(file);
5877
+ const { stored, pruned } = await readArchivedCredentials(file);
5867
5878
  if (signal?.aborted) return;
5868
5879
  const tombstones = await this.loadDeletedSignIns(signal);
5869
5880
  if (tombstones === void 0) return;
5870
- let changed = false;
5881
+ let changed = pruned;
5871
5882
  for (const credential of credentials) {
5872
5883
  const id = workbuddyAccountId(credential);
5873
5884
  const entry = tombstoneOf(tombstones, credential, id);
@@ -5895,20 +5906,22 @@ var WorkBuddyAccountPool = class {
5895
5906
  }
5896
5907
  }
5897
5908
  /** Credentials the archive kept for a directory this walk can read. */
5898
- async archivedCredentials(homes) {
5909
+ async archivedCredentials(homes, signal) {
5899
5910
  const file = this.archiveFile();
5900
5911
  if (file === void 0) return [];
5912
+ let stored = /* @__PURE__ */ new Map();
5901
5913
  try {
5902
- let stored = /* @__PURE__ */ new Map();
5903
5914
  await withFileLock(`${file}.lock`, async () => {
5915
+ if (signal?.aborted) return;
5904
5916
  await removeAbandonedTemps(file);
5905
- stored = await readArchivedCredentials(file);
5917
+ const archive = await readArchivedCredentials(file);
5918
+ stored = archive.stored;
5919
+ if (archive.pruned) await writeArchivedCredentials(file, stored, signal);
5906
5920
  });
5907
- return [...stored.values()].filter((credential) => homes.has(this.homeOf(credential)));
5908
5921
  } catch (error) {
5909
- this.logger?.warn?.(`${LOG_PREFIX}: could not read the credential archive: ${String(error)}`);
5910
- return [];
5922
+ if (!signal?.aborted) this.logger?.warn?.(`${LOG_PREFIX}: could not read or prune the credential archive: ${String(error)}`);
5911
5923
  }
5924
+ return [...stored.values()].filter((credential) => homes.has(this.homeOf(credential)));
5912
5925
  }
5913
5926
  /** The auth directory a credential was read from. */
5914
5927
  homeOf(credential) {
@@ -6038,7 +6051,7 @@ var WorkBuddyAccountPool = class {
6038
6051
  const refreshBlockedIds = /* @__PURE__ */ new Set();
6039
6052
  for (const [file, id] of appHeld) if (sealedFiles.has(file) || unreadableFiles.has(file) || unavailableDirs.has(resolve(dirname(file)))) refreshBlockedIds.add(id);
6040
6053
  for (const account of this.accounts) if (sealedFiles.has(resolve(account.credential.sourcePath)) || unreadableFiles.has(resolve(account.credential.sourcePath)) || unavailableDirs.has(this.homeOf(account.credential))) refreshBlockedIds.add(account.id);
6041
- const archived = await this.archivedCredentials(readableDirs);
6054
+ const archived = await this.archivedCredentials(readableDirs, signal);
6042
6055
  if (signal.aborted || rosterRevision !== this.rosterRevision) return this.accounts;
6043
6056
  for (const credential of archived) {
6044
6057
  const id = workbuddyAccountId(credential);
@@ -6913,8 +6926,6 @@ var SseDecoder = class {
6913
6926
  onFrame;
6914
6927
  buffer = "";
6915
6928
  event;
6916
- id;
6917
- retry;
6918
6929
  data = [];
6919
6930
  dataChars = 0;
6920
6931
  rawFrame = "";
@@ -6985,23 +6996,18 @@ var SseDecoder = class {
6985
6996
  else if (field === "data") {
6986
6997
  this.data.push(value);
6987
6998
  this.dataChars += value.length + 1;
6988
- } else if (field === "id" && !value.includes("\0")) this.id = value;
6989
- else if (field === "retry" && /^\d+$/.test(value)) this.retry = Number(value);
6999
+ }
6990
7000
  }
6991
7001
  dispatch() {
6992
7002
  if (this.data.length === 0) {
6993
7003
  this.event = void 0;
6994
- this.retry = void 0;
6995
7004
  return;
6996
7005
  }
6997
7006
  const result = {
6998
7007
  ...this.event === void 0 || this.event === "" ? {} : { event: this.event },
6999
- data: this.data.join("\n"),
7000
- ...this.id === void 0 ? {} : { id: this.id },
7001
- ...this.retry === void 0 ? {} : { retry: this.retry }
7008
+ data: this.data.join("\n")
7002
7009
  };
7003
7010
  this.event = void 0;
7004
- this.retry = void 0;
7005
7011
  this.data = [];
7006
7012
  this.dataChars = 0;
7007
7013
  return result;
@@ -7663,7 +7669,7 @@ function createWorkBuddyShim(options) {
7663
7669
  */
7664
7670
  const failInBand = (error) => {
7665
7671
  if (controller.signal.aborted || !res.writable) return;
7666
- logger?.warn?.("wtq-pool: upstream stream failed mid-flight", safeMessage(error));
7672
+ logger?.warn?.("wtq-pool: upstream stream failed mid-flight", error instanceof Error ? error.name : "unknown error");
7667
7673
  try {
7668
7674
  res.write(`data: ${JSON.stringify({ error: {
7669
7675
  message: safeMessage(error),
@@ -7720,14 +7726,14 @@ function createWorkBuddyShim(options) {
7720
7726
  head = peeked.head;
7721
7727
  ended = peeked.ended;
7722
7728
  if (peeked.refusal !== void 0) {
7723
- await reader.cancel().catch(() => {});
7729
+ reader.cancel().catch(() => {});
7724
7730
  if (peeked.ended && peeked.refusal === EMPTY_STREAM_REFUSAL) {
7725
7731
  headFailure = peeked.refusal;
7726
7732
  headIsEmptyStream = true;
7727
7733
  logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} answered 200 with an empty stream; rotating`);
7728
7734
  return;
7729
7735
  }
7730
- logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} answered 200 with no stream: ${safeMessage(peeked.refusal)}`);
7736
+ logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} answered 200 with no stream`);
7731
7737
  if (peeked.code === "11128" || unapprovedChannelRefusal(peeked.refusal) !== void 0) {
7732
7738
  writeOpenAIError(res, 400, "upstream_channel_check", channelCheckRefusal());
7733
7739
  return;
@@ -8837,10 +8843,6 @@ function traeIdentityHeaders(identity) {
8837
8843
  "x-app-version": identity.appVersion,
8838
8844
  "x-ide-version": identity.appVersion
8839
8845
  },
8840
- ...identity.buildVersion === void 0 ? {} : {
8841
- "x-app-version-code": identity.buildVersion,
8842
- "x-ide-version-code": identity.buildVersion
8843
- },
8844
8846
  "x-ide-version-type": "stable"
8845
8847
  };
8846
8848
  }
@@ -8848,15 +8850,15 @@ function traeIdentityHeaders(identity) {
8848
8850
  * Headers shared by every Trae edition. The same shape is accepted by both
8849
8851
  * gateways (identical `x-app-id`, identity headers, and `Cloud-IDE-JWT` auth).
8850
8852
  */
8851
- function buildTraeHeaders(credential, identity, options = {}) {
8852
- const requestId = options.requestId ?? randomUUID();
8853
+ function buildTraeHeaders(credential, identity) {
8854
+ const requestId = randomUUID();
8853
8855
  const traceId = requestId.replaceAll("-", "").slice(0, 32);
8854
8856
  return {
8855
8857
  "Authorization": `Cloud-IDE-JWT ${credential.accessToken}`,
8856
8858
  "X-Ide-Token": credential.accessToken,
8857
8859
  "x-plugin-channel": "icube-ai",
8858
8860
  "User-Agent": `Trae/${identity.appVersion ?? identity.buildVersion ?? "unknown"}`,
8859
- "x-app-id": options.appId ?? "6eefa01c-1036-4c7e-9ca5-d891f63bfcd8",
8861
+ "x-app-id": "6eefa01c-1036-4c7e-9ca5-d891f63bfcd8",
8860
8862
  ...traeIdentityHeaders(identity),
8861
8863
  "x-app-version-code": normalizeTraeVersionCode(identity.buildVersion),
8862
8864
  "x-ide-version-code": normalizeTraeVersionCode(identity.buildVersion),
@@ -9535,12 +9537,13 @@ var TraeSoloUpstreamClient = class {
9535
9537
  }
9536
9538
  if (response.ok) return {
9537
9539
  ok: true,
9538
- response: response.body === null ? response : new Response(withIdleWatchdog(response.body, timeouts?.idleMs, signal), {
9540
+ response: response.body === null ? response : new Response(withIdleWatchdog(response.body, timeouts?.idleMs, signal, deadline.abort), {
9539
9541
  status: response.status,
9540
9542
  headers: response.headers
9541
9543
  })
9542
9544
  };
9543
9545
  const text = await readErrorBody(response, 1024, signal);
9546
+ deadline.abort();
9544
9547
  return {
9545
9548
  ok: false,
9546
9549
  status: response.status,
@@ -10040,7 +10043,7 @@ async function openTraeResponse(response, model, options = {}) {
10040
10043
  throw error;
10041
10044
  }
10042
10045
  if (failure !== void 0 && !sawOutput) {
10043
- await reader.cancel().catch(() => {});
10046
+ reader.cancel().catch(() => {});
10044
10047
  const { status, kind, retryAfterSeconds } = classifyTraeFailure(failure);
10045
10048
  const wait = retryAfterHeader(retryAfterSeconds);
10046
10049
  return Response.json({ error: {
@@ -10249,7 +10252,8 @@ function createTraeGateway(options) {
10249
10252
  * a subscription gate), which is what the next sign-in is for.
10250
10253
  */
10251
10254
  const attemptOnce = async (credential, functionName) => {
10252
- const result = await clientFor(credential).chatStream(raw, watcher.signal, functionName, capabilities.get(model), void 0, published !== void 0 && serving !== void 0 && serving.contextWindow !== void 0 && published > serving.contextWindow);
10255
+ const variant = entry?.variants?.find((row) => row.function === functionName) ?? serving;
10256
+ const result = await clientFor(credential).chatStream(raw, watcher.signal, functionName, capabilities.get(model), void 0, published !== void 0 && variant?.contextWindow !== void 0 && published > variant.contextWindow);
10253
10257
  if (!result.ok) return {
10254
10258
  ok: false,
10255
10259
  status: result.status,
@@ -10260,7 +10264,8 @@ function createTraeGateway(options) {
10260
10264
  let relayed;
10261
10265
  try {
10262
10266
  relayed = await openTraeResponse(result.response, model, { onFailure: (error) => {
10263
- logger?.warn?.("wtq-pool: trae relay stream failed mid-flight", error);
10267
+ const failure = error.traeFailure;
10268
+ logger?.warn?.("wtq-pool: trae relay stream failed mid-flight", failure?.code === void 0 ? error instanceof Error ? error.name : "unknown error" : `code ${failure.code}`);
10264
10269
  if (!(error instanceof Error && error.name === "AbortError") && !watcher.signal.aborted) {
10265
10270
  const failure = error.traeFailure;
10266
10271
  if (failure !== void 0) {
@@ -10341,10 +10346,6 @@ function createTraeGateway(options) {
10341
10346
  return;
10342
10347
  }
10343
10348
  const relayed = opened.relayed;
10344
- if (relayed.body === null) {
10345
- writeOpenAIError(res, 502, "upstream_error", "Trae SOLO returned no stream");
10346
- return;
10347
- }
10348
10349
  if (watcher.signal.aborted) {
10349
10350
  relayStreamOf(relayed).cancel().catch(() => {});
10350
10351
  return;
@@ -10357,7 +10358,7 @@ function createTraeGateway(options) {
10357
10358
  });
10358
10359
  res.flushHeaders();
10359
10360
  pumpToResponse(relayStreamOf(relayed), res).catch((error) => {
10360
- if (!(watcher.signal.aborted || error instanceof Error && error.name === "AbortError")) logger?.warn?.("wtq-pool: trae relay stream failed mid-flight", error);
10361
+ if (!(watcher.signal.aborted || error instanceof Error && error.name === "AbortError")) logger?.warn?.("wtq-pool: trae relay stream failed mid-flight", error instanceof Error ? error.name : "unknown error");
10361
10362
  if (res.writable) res.end();
10362
10363
  });
10363
10364
  }
@@ -10442,10 +10443,23 @@ function osVersionOf(platform) {
10442
10443
  function deviceCpuOf() {
10443
10444
  return nonEmpty(cpus()[0]?.model.split(" ")[0]);
10444
10445
  }
10445
- /** `x-device-id` when exactly one device-center id is persisted. */
10446
+ /**
10447
+ * `x-device-id`: the device-center number the official clients send.
10448
+ *
10449
+ * That value is the numeric suffix of `iCubeAuthInfo://icube-dc:<id>`. The app
10450
+ * also leaves entries of another shape behind — for example an `aha-…` key it
10451
+ * writes when it migrates its device id — and those are not device numbers, so
10452
+ * they are never what this header wants. One numeric id beside such leftovers
10453
+ * is still the machine's own and must be used; two numeric ids are two sign-ins
10454
+ * with no way to tell which one this account owns, so the caller still has to
10455
+ * fall back. Keeping the single-entry case shape-blind preserves installs that
10456
+ * persist no numeric id at all.
10457
+ */
10446
10458
  function traeDeviceCenterId(storage) {
10447
10459
  const ids = Object.keys(storage).filter((key) => key.startsWith(TRAE_DEVICE_CENTER_PREFIX)).map((key) => key.slice(25)).filter(Boolean);
10448
- return ids.length === 1 ? ids[0] : void 0;
10460
+ const numeric = ids.filter((id) => /^\d+$/.test(id));
10461
+ if (numeric.length === 1) return numeric[0];
10462
+ if (numeric.length === 0 && ids.length === 1) return ids[0];
10449
10463
  }
10450
10464
  async function readJsonFile(path) {
10451
10465
  try {
@@ -10720,6 +10734,19 @@ function decryptQoderOscrypt(blob, key) {
10720
10734
  return;
10721
10735
  }
10722
10736
  }
10737
+ /** Chromium's macOS OSCrypt uses a fixed IV of sixteen ASCII spaces. */
10738
+ const MAC_OSCRYPT_IV = Buffer.alloc(16, 32);
10739
+ /** A macOS `v10` blob stores the prefix followed by AES-CBC ciphertext. */
10740
+ function decryptQoderOscryptMac(blob, key) {
10741
+ if (blob.length < 19) return void 0;
10742
+ if (blob.subarray(0, 3).toString("latin1") !== "v10") return void 0;
10743
+ try {
10744
+ const decipher = createDecipheriv("aes-128-cbc", key, MAC_OSCRYPT_IV);
10745
+ return Buffer.concat([decipher.update(blob.subarray(3)), decipher.final()]).toString("utf8");
10746
+ } catch {
10747
+ return;
10748
+ }
10749
+ }
10723
10750
  //#endregion
10724
10751
  //#region src/qoder-credentials.ts
10725
10752
  /**
@@ -10818,7 +10845,7 @@ async function unwrapQoderOscryptKey(localStatePath, options = {}) {
10818
10845
  } catch {}
10819
10846
  const cached = oscryptKeyCache.get(localStatePath);
10820
10847
  if (cached !== void 0 && cached.mtimeMs === mtimeMs) return Buffer.from(cached.key);
10821
- const exe = trustedWindowsPowerShell(env);
10848
+ const exe = trustedWindowsPowerShell();
10822
10849
  if (exe === void 0) throw new QoderKeyError("unavailable", "SystemRoot is not set, cannot locate PowerShell");
10823
10850
  const stdout = await new Promise((resolve, reject) => {
10824
10851
  const child = spawn(exe, [
@@ -10827,12 +10854,9 @@ async function unwrapQoderOscryptKey(localStatePath, options = {}) {
10827
10854
  "-Command",
10828
10855
  DPAPI_SCRIPT
10829
10856
  ], {
10830
- env: trustedWindowsChildEnv(env, {
10831
- inheritTemp: true,
10832
- includeSystemDrive: true
10833
- }),
10857
+ env: trustedWindowsChildEnv(env),
10834
10858
  cwd: (() => {
10835
- const root = trustedSystemRootOf(env);
10859
+ const root = trustedSystemRootOf();
10836
10860
  return root === void 0 ? void 0 : join(root, "System32");
10837
10861
  })(),
10838
10862
  windowsHide: true,
@@ -10930,16 +10954,82 @@ async function firstAuthBlob(paths) {
10930
10954
  return await readFile(path);
10931
10955
  } catch {}
10932
10956
  }
10957
+ /** Keychain service names for the current and older Qoder builds. */
10958
+ const QODER_KEYCHAIN_SERVICES = {
10959
+ cn: [
10960
+ "Qoder CN App Safe Storage",
10961
+ "Qoder CN Safe Storage",
10962
+ "QoderWork CN Safe Storage"
10963
+ ],
10964
+ global: [
10965
+ "Qoder App Safe Storage",
10966
+ "Qoder Safe Storage",
10967
+ "QoderWork Safe Storage"
10968
+ ]
10969
+ };
10970
+ /**
10971
+ * PBKDF2 parameters Chromium's macOS OSCrypt uses to turn the Keychain
10972
+ * password into the 16-byte AES-128 key. Fixed by Chromium, not secret.
10973
+ */
10974
+ const MAC_OSCRYPT_SALT = "saltysalt";
10975
+ const MAC_OSCRYPT_ITERATIONS = 1003;
10976
+ /** Derived macOS keys, keyed on the Keychain service they came from. */
10977
+ const darwinKeyCache = /* @__PURE__ */ new Map();
10978
+ /** Pin the system helper and bound the wait for a Keychain prompt. */
10979
+ function darwinKeychainPassword(service) {
10980
+ return new Promise((resolve) => {
10981
+ execFile("/usr/bin/security", [
10982
+ "find-generic-password",
10983
+ "-s",
10984
+ service,
10985
+ "-w"
10986
+ ], { timeout: 8e3 }, (error, stdout) => {
10987
+ resolve(error ? void 0 : stdout.trim() || void 0);
10988
+ });
10989
+ });
10990
+ }
10991
+ /** One app directory's credential on macOS, or the reason there is none. */
10992
+ async function readQoderCredentialMac(authBlob, region, appDir) {
10993
+ const base = { region };
10994
+ let decrypted = false;
10995
+ for (const service of QODER_KEYCHAIN_SERVICES[region]) {
10996
+ let key = darwinKeyCache.get(service);
10997
+ if (key === void 0) {
10998
+ const password = await darwinKeychainPassword(service);
10999
+ if (password === void 0) continue;
11000
+ key = pbkdf2Sync(password, MAC_OSCRYPT_SALT, MAC_OSCRYPT_ITERATIONS, 16, "sha1");
11001
+ darwinKeyCache.set(service, key);
11002
+ }
11003
+ const plain = decryptQoderOscryptMac(authBlob, key);
11004
+ if (plain === void 0) continue;
11005
+ decrypted = true;
11006
+ const session = parseQoderAuthSession(plain);
11007
+ if (session === void 0) continue;
11008
+ const machineID = await machineIdOf(appDir);
11009
+ return { credential: {
11010
+ ...base,
11011
+ ...session,
11012
+ ...machineID === void 0 ? {} : { machineID }
11013
+ } };
11014
+ }
11015
+ return { failure: {
11016
+ ...base,
11017
+ reason: decrypted ? "invalid" : "no-key",
11018
+ ...decrypted ? {} : { message: "no macOS Keychain key opened the sign-in (sign in to the Qoder app, then allow the Keychain prompt and rescan)" }
11019
+ } };
11020
+ }
10933
11021
  /** Read one app directory's credential, or the reason there is none. */
10934
11022
  async function readQoderCredential(candidates, options = {}) {
10935
11023
  const byKind = (kind) => candidates.filter((candidate) => candidate.kind === kind).map((candidate) => candidate.path);
10936
11024
  const appDir = candidates[0]?.appDir ?? "";
10937
- const base = { region: candidates[0]?.region ?? "cn" };
11025
+ const region = candidates[0]?.region ?? "cn";
11026
+ const base = { region };
10938
11027
  const authBlob = await firstAuthBlob(byKind("auth-v1"));
10939
11028
  if (authBlob === void 0) return { failure: {
10940
11029
  ...base,
10941
11030
  reason: "no-auth"
10942
11031
  } };
11032
+ if ((options.platform ?? process.platform) === "darwin") return readQoderCredentialMac(authBlob, region, appDir);
10943
11033
  let key;
10944
11034
  try {
10945
11035
  const localState = byKind("local-state")[0];
@@ -10985,9 +11075,16 @@ async function readQoderCredential(candidates, options = {}) {
10985
11075
  */
10986
11076
  const DISCOVERY_TTL_MS = 3e4;
10987
11077
  let discoveryCache;
10988
- /** Drop the cached discovery answer, e.g. when the user asks for a rescan. */
11078
+ /**
11079
+ * Drop the cached discovery answer, e.g. when the user asks for a rescan.
11080
+ *
11081
+ * The macOS Keychain keys go with it: a desktop re-login can rotate the stored
11082
+ * password, and a rescan is exactly when a rotated key has to be re-read
11083
+ * instead of failing every decrypt with the stale copy.
11084
+ */
10989
11085
  function resetQoderCredentialCache() {
10990
11086
  discoveryCache = void 0;
11087
+ darwinKeyCache.clear();
10991
11088
  }
10992
11089
  /**
10993
11090
  * Every Qoder sign-in on this machine. One app directory that is missing or
@@ -12283,6 +12380,7 @@ var QoderUpstreamClient = class {
12283
12380
  }
12284
12381
  if (!response.ok) {
12285
12382
  const text = await readErrorBody(response, 300, options.signal);
12383
+ deadline.abort();
12286
12384
  return {
12287
12385
  ok: false,
12288
12386
  status: response.status,
@@ -12293,7 +12391,7 @@ var QoderUpstreamClient = class {
12293
12391
  }
12294
12392
  return {
12295
12393
  ok: true,
12296
- response: response.body === null ? response : new Response(withIdleWatchdog(response.body, options.timeouts?.idleMs, options.signal), {
12394
+ response: response.body === null ? response : new Response(withIdleWatchdog(response.body, options.timeouts?.idleMs, options.signal, deadline.abort), {
12297
12395
  status: response.status,
12298
12396
  headers: response.headers
12299
12397
  })
@@ -12479,19 +12577,16 @@ function classifyQoderFailure(failure) {
12479
12577
  * caller states it (a fabricated `false` is refused with 1210 on models that
12480
12578
  * always think).
12481
12579
  */
12482
- function qoderRequestBody(openAiBody, model, entry, options = {}) {
12580
+ function qoderRequestBody(openAiBody, model, entry) {
12483
12581
  const requested = readReasoningEffort(openAiBody);
12484
12582
  const off = requested === "off" || requested === "none";
12485
12583
  const wire = requested === void 0 || off ? void 0 : qoderWireEffort(requested, entry);
12486
12584
  return {
12487
12585
  body: openAiBody,
12488
12586
  model,
12489
- options: {
12490
- ...options,
12491
- ...requested === void 0 ? {} : {
12492
- enableThinking: !off,
12493
- ...wire === void 0 ? {} : { reasoningEffort: wire }
12494
- }
12587
+ options: requested === void 0 ? {} : {
12588
+ enableThinking: !off,
12589
+ ...wire === void 0 ? {} : { reasoningEffort: wire }
12495
12590
  }
12496
12591
  };
12497
12592
  }
@@ -12901,7 +12996,7 @@ async function openQoderResponse(response, model, options = {}) {
12901
12996
  throw error;
12902
12997
  }
12903
12998
  if (failure !== void 0 && !sawOutput) {
12904
- await reader.cancel().catch(() => {});
12999
+ reader.cancel().catch(() => {});
12905
13000
  const { status, kind, error } = classifyQoderFailure(failure);
12906
13001
  const retryAfter = error instanceof QoderQueueRejection || error instanceof QoderDailyLimitRejection ? error.retryAfterSeconds : void 0;
12907
13002
  const wait = retryAfter === void 0 ? void 0 : retryAfterHeader(retryAfter);
@@ -13047,7 +13142,6 @@ function createQoderGateway(options) {
13047
13142
  return cachedModels;
13048
13143
  });
13049
13144
  if (watcher.signal.aborted) return;
13050
- if (roster.length === 0) roster = cachedModels;
13051
13145
  if (roster.length === 0) {
13052
13146
  writeOpenAIError(res, 503, "upstream_unavailable", reason);
13053
13147
  return;
@@ -13097,7 +13191,7 @@ function createQoderGateway(options) {
13097
13191
  let relayed;
13098
13192
  try {
13099
13193
  relayed = await openQoderResponse(result.response, model, { onFailure: (error) => {
13100
- logger?.warn?.("wtq-pool: qoder relay stream failed mid-flight", error);
13194
+ logger?.warn?.("wtq-pool: qoder relay stream failed mid-flight", error instanceof Error ? error.name : "unknown error");
13101
13195
  if (!(error instanceof Error && error.name === "AbortError") && !watcher.signal.aborted) {
13102
13196
  const seconds = error.retryAfterSeconds;
13103
13197
  options.onAttemptFailure?.(credential, { ...typeof seconds === "number" && seconds > 0 ? { retryAfter: String(seconds) } : {} });
@@ -13169,10 +13263,6 @@ function createQoderGateway(options) {
13169
13263
  return;
13170
13264
  }
13171
13265
  const relayed = opened.relayed;
13172
- if (relayed.body === null) {
13173
- writeOpenAIError(res, 502, "upstream_error", "Qoder returned no stream");
13174
- return;
13175
- }
13176
13266
  if (watcher.signal.aborted) {
13177
13267
  relayStreamOf(relayed).cancel().catch(() => {});
13178
13268
  return;
@@ -13185,7 +13275,7 @@ function createQoderGateway(options) {
13185
13275
  });
13186
13276
  res.flushHeaders();
13187
13277
  pumpToResponse(relayStreamOf(relayed), res).catch((error) => {
13188
- if (!(watcher.signal.aborted || error instanceof Error && error.name === "AbortError")) logger?.warn?.("wtq-pool: qoder relay stream failed mid-flight", error);
13278
+ if (!(watcher.signal.aborted || error instanceof Error && error.name === "AbortError")) logger?.warn?.("wtq-pool: qoder relay stream failed mid-flight", error instanceof Error ? error.name : "unknown error");
13189
13279
  if (res.writable) res.end();
13190
13280
  });
13191
13281
  }
@@ -13566,7 +13656,6 @@ function createSourcePool(host) {
13566
13656
  sourceCredentialExpired,
13567
13657
  accountStateKey,
13568
13658
  noteSourceFailure,
13569
- packUrgency,
13570
13659
  orderSourceCredentials
13571
13660
  };
13572
13661
  }
@@ -14416,8 +14505,14 @@ function saveCheckinSlots() {
14416
14505
  const target = path.join(dataPath, CHECKIN_SLOTS_FILE);
14417
14506
  const staging = target + ".tmp";
14418
14507
  try {
14419
- fs$1.mkdirSync(dataPath, { recursive: true });
14420
- fs$1.writeFileSync(staging, JSON.stringify(byDay), "utf8");
14508
+ fs$1.mkdirSync(dataPath, {
14509
+ recursive: true,
14510
+ mode: 448
14511
+ });
14512
+ fs$1.writeFileSync(staging, JSON.stringify(byDay), {
14513
+ encoding: "utf8",
14514
+ mode: 384
14515
+ });
14421
14516
  fs$1.renameSync(staging, target);
14422
14517
  } catch (error) {
14423
14518
  try {
@@ -16600,6 +16695,28 @@ async function statusDocument(options) {
16600
16695
  row.active = nextUpNow.get(row.region) === row.id;
16601
16696
  }
16602
16697
  }
16698
+ const sourceDocument = (source) => {
16699
+ const sourceRegions = source === "trae" ? activeTraeRegions : activeQoderRegions;
16700
+ const accounts = source === "trae" ? traeAccountRows : qoderAccountRows;
16701
+ const gateways = source === "trae" ? traeGateways : qoderGateways;
16702
+ const declarationModels = source === "trae" ? traeDeclarationModels : qoderDeclarationModels;
16703
+ const nativeOf = source === "trae" ? traeNativeOf : qoderNativeOf;
16704
+ return {
16705
+ regions: sourceRegions(),
16706
+ distribution: sourceDistribution(source),
16707
+ accounts,
16708
+ preferred: sourcePreferredMap(source),
16709
+ gateways: Array.from(gateways.values()).map((entry) => ({
16710
+ region: entry.region,
16711
+ port: entry.gateway.port(),
16712
+ models: declarationModels(entry.region).length,
16713
+ portFallback: entry.portFallback,
16714
+ preferredPort: entry.preferredPort,
16715
+ lastError: entry.lastError,
16716
+ ...sourcePublishedModels(source + ":" + entry.region, entry.gateway.models(), nativeOf)
16717
+ }))
16718
+ };
16719
+ };
16603
16720
  return {
16604
16721
  regions: activeRegions(),
16605
16722
  sources: {
@@ -16608,36 +16725,8 @@ async function statusDocument(options) {
16608
16725
  qoder: sourceEnabled("qoder")
16609
16726
  },
16610
16727
  disabledRegions: disabledRegionKeys(),
16611
- trae: {
16612
- regions: activeTraeRegions(),
16613
- distribution: sourceDistribution("trae"),
16614
- accounts: traeAccountRows,
16615
- preferred: sourcePreferredMap("trae"),
16616
- gateways: Array.from(traeGateways.values()).map((entry) => ({
16617
- region: entry.region,
16618
- port: entry.gateway.port(),
16619
- models: traeDeclarationModels(entry.region).length,
16620
- portFallback: entry.portFallback,
16621
- preferredPort: entry.preferredPort,
16622
- lastError: entry.lastError,
16623
- ...sourcePublishedModels("trae:" + entry.region, entry.gateway.models(), traeNativeOf)
16624
- }))
16625
- },
16626
- qoder: {
16627
- regions: activeQoderRegions(),
16628
- distribution: sourceDistribution("qoder"),
16629
- accounts: qoderAccountRows,
16630
- preferred: sourcePreferredMap("qoder"),
16631
- gateways: Array.from(qoderGateways.values()).map((entry) => ({
16632
- region: entry.region,
16633
- port: entry.gateway.port(),
16634
- models: qoderDeclarationModels(entry.region).length,
16635
- portFallback: entry.portFallback,
16636
- preferredPort: entry.preferredPort,
16637
- lastError: entry.lastError,
16638
- ...sourcePublishedModels("qoder:" + entry.region, entry.gateway.models(), qoderNativeOf)
16639
- }))
16640
- },
16728
+ trae: sourceDocument("trae"),
16729
+ qoder: sourceDocument("qoder"),
16641
16730
  enabled: settings.enabled !== false,
16642
16731
  unpublishedDeclarations: unpublishedDeclarations(),
16643
16732
  modelCap: MAX_MODELS,
@@ -16774,39 +16863,38 @@ function addressDrift() {
16774
16863
  return false;
16775
16864
  }
16776
16865
  /**
16777
- * Trae discovery for the doctor: count only, never token material.
16866
+ * Discovery detail shared by Trae and Qoder.
16778
16867
  *
16779
- * Answers `{ok, detail}` so the finding can carry the verdict instead of
16780
- * hard-coding `true`: a source that could not be read, or that holds no
16781
- * sign-in at all, is a failed check, and the report used to pass it.
16868
+ * Counts and served-model figures only: the report is copyable out of the panel,
16869
+ * so no token material or filesystem path reaches it.
16782
16870
  */
16783
- async function traeDoctorDetail() {
16784
- if (!sourceEnabled("trae")) return {
16871
+ async function sourceDoctorDetail(spec) {
16872
+ if (!sourceEnabled(spec.source)) return {
16785
16873
  ok: true,
16786
16874
  detail: "switched off in plugin settings (deliberate; not a failure)"
16787
16875
  };
16788
16876
  try {
16789
- const found = await discoverTraeCredentials();
16877
+ const found = await spec.discover();
16878
+ const failures = found.failures.length > 0 ? `; ${found.failures.length} ${spec.unreadable}` : "";
16790
16879
  if (found.credentials.length === 0) return {
16791
16880
  ok: false,
16792
- detail: "on; no Trae sign-in found (sign in to Trae CN / TRAE SOLO CN, then run the check again)"
16881
+ detail: `on; no ${spec.label} sign-in found (${spec.hint})${failures}`
16793
16882
  };
16794
16883
  const byRegion = {};
16795
16884
  for (const credential of found.credentials) {
16796
- const region = traeRegionOfCredential(credential);
16885
+ const region = spec.regionOf(credential);
16797
16886
  byRegion[region] = (byRegion[region] || 0) + 1;
16798
16887
  }
16799
16888
  const parts = Object.entries(byRegion).map(([region, count]) => `${region} x${count}`).join(", ");
16800
- const failures = found.failures.length > 0 ? `; ${found.failures.length} unreadable file(s)` : "";
16801
- const servedRegions = activeTraeRegions();
16802
- const served = servedRegions.map((region) => `${region}: ${traeDeclarationModels(region).length} model(s)`).join(", ");
16889
+ const servedRegions = spec.activeRegions();
16890
+ const served = servedRegions.map((region) => `${region}: ${spec.declarationModels(region).length} model(s)`).join(", ");
16803
16891
  const stillReading = [];
16804
16892
  const problems = [];
16805
16893
  for (const region of servedRegions) {
16806
- const entry = traeGateways.get(region);
16894
+ const entry = spec.gateways.get(region);
16807
16895
  if (entry === void 0 && !byRegion[region]) problems.push(`${region}: no sign-in for this region`);
16808
16896
  else if (entry === void 0 || entry.warmSettled !== true) stillReading.push(region);
16809
- else if (traeDeclarationModels(region).length === 0) problems.push(entry.lastError !== "" ? `${region}: ${entry.lastError}` : `${region}: no models selected`);
16897
+ else if (spec.declarationModels(region).length === 0) problems.push(entry.lastError !== "" ? `${region}: ${entry.lastError}` : `${region}: no models selected`);
16810
16898
  }
16811
16899
  return {
16812
16900
  ok: problems.length === 0,
@@ -16819,42 +16907,33 @@ async function traeDoctorDetail() {
16819
16907
  };
16820
16908
  }
16821
16909
  }
16822
- /** Qoder credentials for the doctor: count only, never token material. */
16823
- async function qoderDoctorDetail() {
16824
- if (!sourceEnabled("qoder")) return {
16825
- ok: true,
16826
- detail: "switched off in plugin settings (deliberate; not a failure)"
16827
- };
16828
- try {
16829
- const found = await discoverQoderCredentials();
16830
- if (found.credentials.length === 0) return {
16831
- ok: false,
16832
- detail: `on; no Qoder sign-in found (sign in to Qoder, then run the check again)${found.failures.length > 0 ? `; ${found.failures.length} unreadable app dir(s)` : ""}`
16833
- };
16834
- const byRegion = {};
16835
- for (const credential of found.credentials) byRegion[credential.region] = (byRegion[credential.region] || 0) + 1;
16836
- const parts = Object.entries(byRegion).map(([region, count]) => `${region} x${count}`).join(", ");
16837
- const failures = found.failures.length > 0 ? `; ${found.failures.length} unreadable app dir(s)` : "";
16838
- const servedRegions = activeQoderRegions();
16839
- const served = servedRegions.map((region) => `${region}: ${qoderDeclarationModels(region).length} model(s)`).join(", ");
16840
- const stillReading = [];
16841
- const problems = [];
16842
- for (const region of servedRegions) {
16843
- const entry = qoderGateways.get(region);
16844
- if (entry === void 0 && !byRegion[region]) problems.push(`${region}: no sign-in for this region`);
16845
- else if (entry === void 0 || entry.warmSettled !== true) stillReading.push(region);
16846
- else if (qoderDeclarationModels(region).length === 0) problems.push(entry.lastError !== "" ? `${region}: ${entry.lastError}` : `${region}: no models selected`);
16847
- }
16848
- return {
16849
- ok: problems.length === 0,
16850
- 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("; ")}` : "")
16851
- };
16852
- } catch (error) {
16853
- return {
16854
- ok: false,
16855
- detail: `on; discovery failed (${errorCodeOf(error)})`
16856
- };
16857
- }
16910
+ /** Trae discovery for the doctor. */
16911
+ function traeDoctorDetail() {
16912
+ return sourceDoctorDetail({
16913
+ source: "trae",
16914
+ label: "Trae",
16915
+ hint: "sign in to Trae CN / TRAE SOLO CN, then run the check again",
16916
+ unreadable: "unreadable file(s)",
16917
+ discover: discoverTraeCredentials,
16918
+ regionOf: traeRegionOfCredential,
16919
+ activeRegions: activeTraeRegions,
16920
+ declarationModels: traeDeclarationModels,
16921
+ gateways: traeGateways
16922
+ });
16923
+ }
16924
+ /** Qoder discovery for the doctor. */
16925
+ function qoderDoctorDetail() {
16926
+ return sourceDoctorDetail({
16927
+ source: "qoder",
16928
+ label: "Qoder",
16929
+ hint: "sign in to Qoder, then run the check again",
16930
+ unreadable: "unreadable app dir(s)",
16931
+ discover: discoverQoderCredentials,
16932
+ regionOf: (credential) => credential.region,
16933
+ activeRegions: activeQoderRegions,
16934
+ declarationModels: qoderDeclarationModels,
16935
+ gateways: qoderGateways
16936
+ });
16858
16937
  }
16859
16938
  /** A readable report of everything that has to hold for a chat to reach upstream. */
16860
16939
  async function doctorReport() {
@@ -17786,31 +17865,7 @@ async function onPanelInvoke(channel, payload) {
17786
17865
  */
17787
17866
  case "xd.composerRefresh": {
17788
17867
  const hit = matchComposerModel(payload);
17789
- if (hit === void 0) return composerPoints(payload);
17790
- const { left, settle } = budget(COMPOSER_REFRESH_BUDGET_MS);
17791
- if (hit.source === "workbuddy") {
17792
- for (const account of core.pool.list(hit.region)) probeCache.delete(account.id);
17793
- await settle(statusDocument({
17794
- allowNetwork: true,
17795
- budgetMs: COMPOSER_REFRESH_BUDGET_MS
17796
- }));
17797
- } else {
17798
- const rows = hit.source === "trae" ? traeAccountRows : qoderAccountRows;
17799
- const found = hit.source === "trae" ? await discoverTraeCredentials() : await discoverQoderCredentials();
17800
- for (const row of rows) {
17801
- if (row.region !== hit.region) continue;
17802
- if (left() === 0) break;
17803
- const credential = found.credentials.find((item) => {
17804
- const itemLabel = hit.source === "trae" ? traeRowLabel(item) : qoderRowLabel(item);
17805
- const itemRegion = hit.source === "trae" ? traeRegionOfCredential(item) : item.region;
17806
- return itemLabel === row.label && itemRegion === row.region;
17807
- });
17808
- if (credential === void 0) continue;
17809
- const probe = hit.source === "trae" ? await traeRowProbe(credential, row) : await qoderRowProbe(credential, row);
17810
- if (probe?.usage) row.usage = probe.usage;
17811
- if (probe?.checkin) row.checkin = probe.checkin;
17812
- }
17813
- }
17868
+ if (hit !== void 0) await settleWithin(composerRefreshWork(hit), COMPOSER_REFRESH_BUDGET_MS);
17814
17869
  return composerPoints(payload);
17815
17870
  }
17816
17871
  default: throw panelError("unsupported panel channel: " + String(channel), "UNSUPPORTED");
@@ -17977,6 +18032,32 @@ const GROWTH_BUDGET_MS = 9e4;
17977
18032
  * credentials read from turning the click into a client-side timeout.
17978
18033
  */
17979
18034
  const COMPOSER_REFRESH_BUDGET_MS = 15e3;
18035
+ async function composerRefreshWork(hit) {
18036
+ if (hit.source === "workbuddy") {
18037
+ for (const account of core.pool.list(hit.region)) probeCache.delete(account.id);
18038
+ await statusDocument({
18039
+ allowNetwork: true,
18040
+ budgetMs: COMPOSER_REFRESH_BUDGET_MS
18041
+ });
18042
+ return;
18043
+ }
18044
+ const { left } = budget(COMPOSER_REFRESH_BUDGET_MS);
18045
+ const rows = hit.source === "trae" ? traeAccountRows : qoderAccountRows;
18046
+ const found = hit.source === "trae" ? await discoverTraeCredentials() : await discoverQoderCredentials();
18047
+ for (const row of rows) {
18048
+ if (row.region !== hit.region) continue;
18049
+ if (left() === 0) break;
18050
+ const credential = found.credentials.find((item) => {
18051
+ const itemLabel = hit.source === "trae" ? traeRowLabel(item) : qoderRowLabel(item);
18052
+ const itemRegion = hit.source === "trae" ? traeRegionOfCredential(item) : item.region;
18053
+ return itemLabel === row.label && itemRegion === row.region;
18054
+ });
18055
+ if (credential === void 0) continue;
18056
+ const probe = hit.source === "trae" ? await traeRowProbe(credential, row) : await qoderRowProbe(credential, row);
18057
+ if (probe?.usage) row.usage = probe.usage;
18058
+ if (probe?.checkin) row.checkin = probe.checkin;
18059
+ }
18060
+ }
17980
18061
  /**
17981
18062
  * Light one account's growth streak, then redeem every tier it opened.
17982
18063
  *