@refeain/dsh-xdpool 3.0.6 → 3.0.8

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
@@ -2839,12 +2839,7 @@ function createDoubaoLlm(options) {
2839
2839
  * The reasoning level.
2840
2840
  *
2841
2841
  * The picker sends an opaque branded string; Doubao's levels are named. An unknown
2842
- * value falls back to DEFAULT_REASONING_LEVEL_ID, the level every model in the
2843
- * family accepts.
2844
- *
2845
- * 兜底值必须是 `DOUBAO_REASONING_LEVELS` 里真实存在的 id —— 否则上面的 some()
2846
- * 永远匹配不到它,请求会带着一个上游不认的档位发出去。这里以前写 `medium`:
2847
- * 那是 `LEVEL_NAMES` 的旧拼法(catalog 与 adapter 都叫 `mid`),不在档位表里。
2842
+ * value falls back to the middle level, which every model in the family accepts.
2848
2843
  */
2849
2844
  const requested = streamOptions["reasoningEffort"];
2850
2845
  const levelName = DOUBAO_REASONING_LEVELS.some((entry) => entry.id === requested) ? String(requested) : DEFAULT_REASONING_LEVEL_ID;
@@ -13501,6 +13496,23 @@ const SESSION_DEAD_MARKERS = [
13501
13496
  */
13502
13497
  const ALREADY_CHECKIN_MARKERS = ["已签到", "already"];
13503
13498
  /**
13499
+ * 签到相关的业务码。
13500
+ *
13501
+ * 上游用 `code` 区分三种「不是成功也不是故障」的结果,而我们此前一律当失败抛出:
13502
+ * 今天已经领过(1001/10001)会在每次自动领取时记一条失败;活动未开放(1002/1003/
13503
+ * 40901/41000)也会,而且永远重试不到结果。它们必须分开对待:
13504
+ *
13505
+ * 已领 → 幂等成功(今天的分就在账上,不是错)
13506
+ * 未开放 → inactive(等下一次,不报错、不重试)
13507
+ */
13508
+ const CHECKIN_ALREADY_CODES = /* @__PURE__ */ new Set([1001, 10001]);
13509
+ const CHECKIN_INACTIVE_CODES = /* @__PURE__ */ new Set([
13510
+ 1002,
13511
+ 1003,
13512
+ 40901,
13513
+ 41e3
13514
+ ]);
13515
+ /**
13504
13516
  * Markers for "there is no compensation offer to collect".
13505
13517
  *
13506
13518
  * The offer is seasonal — an outage announcement opens one, and it closes on a
@@ -13886,7 +13898,17 @@ function billingHeaders(credential) {
13886
13898
  const headers = {
13887
13899
  "Authorization": `Bearer ${credential.accessToken}`,
13888
13900
  "Accept": "application/json",
13889
- "Content-Type": "application/json"
13901
+ "Content-Type": "application/json",
13902
+ /**
13903
+ * 产品身份头 —— 缺了它们,计费/签到端点会把请求当成「不是客户端发的」。
13904
+ *
13905
+ * 这三个头一直在客户端那边发(网页/IDE 的每个 billing 请求都带),我们只发了
13906
+ * Authorization + X-Domain + X-User-Id。上游收紧校验之后,签到就只剩一个笼统的
13907
+ * 失败,看不出原因。UA 用本插件已经在别处使用的桌面版本号,不再另造一个。
13908
+ */
13909
+ "X-Product": "SaaS",
13910
+ "X-Product-Code": "workbuddy",
13911
+ "User-Agent": DESKTOP_UA
13890
13912
  };
13891
13913
  if (credential.uid !== "" && credential.uid !== void 0) headers["X-User-Id"] = credential.uid;
13892
13914
  if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") {
@@ -14886,6 +14908,17 @@ var WorkBuddyUpstreamClient = class {
14886
14908
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
14887
14909
  });
14888
14910
  const envelope = await readEnvelope(response);
14911
+ if (response.ok && CHECKIN_INACTIVE_CODES.has(envelope.code)) return {
14912
+ active: false,
14913
+ todayCheckedIn: false,
14914
+ streakDays: 0,
14915
+ dailyCredit: 0,
14916
+ todayCredit: 0,
14917
+ isStreakDay: false,
14918
+ nextStreakDay: 0,
14919
+ streakBonusDays: 0,
14920
+ streakBonusCredit: 0
14921
+ };
14889
14922
  if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
14890
14923
  const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
14891
14924
  const num = (key) => typeof data[key] === "number" ? data[key] : 0;
@@ -14911,8 +14944,22 @@ var WorkBuddyUpstreamClient = class {
14911
14944
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
14912
14945
  });
14913
14946
  const envelope = await readEnvelope(response);
14947
+ const neutral = (data_) => ({
14948
+ credit: 0,
14949
+ streakDays: typeof data_["streak_days"] === "number" ? data_["streak_days"] : 0,
14950
+ isStreakDay: false
14951
+ });
14952
+ const payload = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
14953
+ /**
14954
+ * 已领过(1001/10001)就是成功:今天的分在账上,重复领取不该被记成失败 ——
14955
+ * 自动化每小时跑一次,记成失败会刷出一整片红字。
14956
+ *
14957
+ * 未开放(1002/1003/40901/41000)同样是「今天没有可领的」,不是故障;
14958
+ * 抛错会让调度器一直重试一个永远不会成功的结果。
14959
+ */
14960
+ if (response.ok && (CHECKIN_ALREADY_CODES.has(envelope.code) || CHECKIN_INACTIVE_CODES.has(envelope.code))) return neutral(payload);
14914
14961
  if (!response.ok || envelope.code !== 0) throw envelopeError(response.status, envelope);
14915
- const data = typeof envelope.data === "object" && envelope.data !== null ? envelope.data : {};
14962
+ const data = payload;
14916
14963
  const numberField = (key) => typeof data[key] === "number" ? data[key] : 0;
14917
14964
  return {
14918
14965
  credit: numberField("credit"),
@@ -18134,6 +18181,22 @@ var WorkBuddyAccountPool = class {
18134
18181
  * Returns true when the token is known good afterwards (refreshed, or still
18135
18182
  * valid), false when the credential was proven dead.
18136
18183
  */
18184
+ /**
18185
+ * 取一个账号「可以用来发一次请求」的凭据:过期就先刷新。
18186
+ *
18187
+ * 签到 / 积分这些端点走的是「按 id 直接找账号」的路径,和选号路径不同 ——
18188
+ * 以前它们直接拿池里的 `account.credential`,凭据过期时上游回 401,界面只能
18189
+ * 说「领取失败」,而同一时刻对话却正常(对话走 `getAvailableAccount`,那里会
18190
+ * 先 `ensureFresh`)。用户反馈的「积分领取全部失败」就是这一处。
18191
+ *
18192
+ * 返回 undefined 表示「刷新失败」:调用方应当直接告诉用户重新登录,
18193
+ * 而不是拿旧 token 再去撞一次 401。
18194
+ */
18195
+ async freshCredential(id) {
18196
+ const account = this.accounts.find((item) => item.id === id);
18197
+ if (account === void 0) return void 0;
18198
+ return await this.ensureFresh(account) ? account.credential : void 0;
18199
+ }
18137
18200
  async ensureFresh(account, force = false) {
18138
18201
  if (this.client === void 0) return true;
18139
18202
  const credential = account.credential;
@@ -29317,7 +29380,7 @@ function parseBody(body) {
29317
29380
  *
29318
29381
  * @module dsh-xdpool/version
29319
29382
  */
29320
- const POOL_VERSION = "3.0.6";
29383
+ const POOL_VERSION = "3.0.8";
29321
29384
  //#endregion
29322
29385
  //#region src/update-check.ts
29323
29386
  /**
@@ -31755,6 +31818,66 @@ function profileDir() {
31755
31818
  if (existsSync(join(candidate, "package.json"))) return candidate;
31756
31819
  }
31757
31820
  }
31821
+ let syncImplementation = syncWithPnpm;
31822
+ /**
31823
+ * 写完 package.json 后用 pnpm 同步 lockfile 与 node_modules。
31824
+ *
31825
+ * 这是「更新了却一直没生效」的真正原因:以前只改 profile 的 package.json,没碰
31826
+ * pnpm-lock.yaml。DSH 下次启动按 lockfile 装回旧版本 —— 用户看到的就是
31827
+ * 「一键更新从没成功过」。现在交给 pnpm 把 package.json / lockfile / node_modules
31828
+ * 三处一次对齐。失败时调用方会回滚 manifest:半更新的 profile 会让宿主 repair。
31829
+ */
31830
+ async function syncWithPnpm(profile) {
31831
+ return await new Promise((resolve) => {
31832
+ const command = process.platform === "win32" ? "pnpm.cmd" : "pnpm";
31833
+ let child;
31834
+ try {
31835
+ child = spawn(command, [
31836
+ "install",
31837
+ "--config.auto-install-peers=false",
31838
+ "--ignore-scripts"
31839
+ ], {
31840
+ cwd: profile,
31841
+ env: process.env,
31842
+ stdio: [
31843
+ "ignore",
31844
+ "pipe",
31845
+ "pipe"
31846
+ ],
31847
+ shell: process.platform === "win32"
31848
+ });
31849
+ } catch (error) {
31850
+ resolve({
31851
+ ok: false,
31852
+ detail: error instanceof Error ? error.message : String(error)
31853
+ });
31854
+ return;
31855
+ }
31856
+ let output = "";
31857
+ child.stdout?.on("data", (chunk) => {
31858
+ output += chunk.toString();
31859
+ });
31860
+ child.stderr?.on("data", (chunk) => {
31861
+ output += chunk.toString();
31862
+ });
31863
+ child.on("error", (error) => {
31864
+ resolve({
31865
+ ok: false,
31866
+ detail: error.message
31867
+ });
31868
+ });
31869
+ child.on("close", (code) => {
31870
+ if (code === 0) resolve({
31871
+ ok: true,
31872
+ detail: "pnpm install ok"
31873
+ });
31874
+ else resolve({
31875
+ ok: false,
31876
+ detail: output.slice(-400) || `pnpm exit ${String(code)}`
31877
+ });
31878
+ });
31879
+ });
31880
+ }
31758
31881
  /** 把下载 / 读写文件时的错误翻成一句中文(前端直接展示)。 */
31759
31882
  function chineseFailure(prefix, error) {
31760
31883
  const message = error instanceof Error ? error.message : String(error);
@@ -31881,6 +32004,7 @@ async function installVersion(version) {
31881
32004
  */
31882
32005
  const newSpec = version;
31883
32006
  const pkgPath = join(profile, "package.json");
32007
+ const originalManifest = readFileSync(pkgPath, "utf8");
31884
32008
  const read = readProfilePackage(pkgPath);
31885
32009
  if ("error" in read) {
31886
32010
  steps.push({
@@ -31942,6 +32066,30 @@ async function installVersion(version) {
31942
32066
  id: "write",
31943
32067
  ok: true
31944
32068
  });
32069
+ /**
32070
+ * 关键:让 pnpm 同步 lockfile 与 node_modules。
32071
+ * 以前只到上一行就返回成功,DSH 下次启动按旧 lockfile 装回旧版,版本号从不变化。
32072
+ * 同步失败就回滚,宁可这次没更新,也不留下会触发宿主 repair 的半更新 profile。
32073
+ */
32074
+ const synced = await syncImplementation(profile);
32075
+ if (!synced.ok) {
32076
+ writeFileSync(`${pkgPath}.tmp`, originalManifest, "utf8");
32077
+ renameSync(`${pkgPath}.tmp`, pkgPath);
32078
+ steps.push({
32079
+ id: "write",
32080
+ ok: false,
32081
+ detail: `pnpm 同步失败,已回滚:${synced.detail}`
32082
+ });
32083
+ return failed(`安装依赖失败,已回滚,插件和数据都没有改动:${synced.detail}`, {
32084
+ path: target,
32085
+ backupPath
32086
+ });
32087
+ }
32088
+ steps.push({
32089
+ id: "sync",
32090
+ ok: true,
32091
+ detail: synced.detail
32092
+ });
31945
32093
  return {
31946
32094
  ok: true,
31947
32095
  version,
@@ -32412,7 +32560,17 @@ function toWebAccount(account, disabled, preferred, reserve, reserved) {
32412
32560
  const now = Date.now();
32413
32561
  const cooling = account.cooldownUntilMs > now;
32414
32562
  const deadUntil = account.credentialDeadUntilMs ?? 0;
32415
- const credentialDead = deadUntil > now;
32563
+ /**
32564
+ * 凭据本身已经过期、且 refresh 也过期 —— 这种情况不必等用户点一次失败才知道。
32565
+ *
32566
+ * 实测:一个 access 过期 9 天、refresh 过期 7 天的账号,点领取只会得到上游 401,
32567
+ * 而卡片上什么标记都没有,用户唯一的线索是「领取失败」。现在这种账号直接标成
32568
+ * 「登录失效」,卡片上就能看到,点它也会得到一句能照做的中文提示。
32569
+ */
32570
+ const credential = account.credential;
32571
+ const refreshExpired = credential.refreshExpiresAtMs === void 0 || credential.refreshExpiresAtMs <= now;
32572
+ const expiredBeyondRepair = credential.expiresAtMs > 0 && credential.expiresAtMs <= now && refreshExpired;
32573
+ const credentialDead = deadUntil > now || expiredBeyondRepair;
32416
32574
  const modelCooldowns = Object.entries(account.modelCooldowns).filter(([, until]) => until > now).sort((a, b) => a[1] - b[1]).map(([modelId, until]) => ({
32417
32575
  modelId,
32418
32576
  until: new Date(until).toISOString()
@@ -32695,7 +32853,15 @@ function registerPoolStatusRoute(ctx, deps) {
32695
32853
  if (accountId === "") return json(res, 400, { error: "accountId is required" });
32696
32854
  const account = deps.pool.list().find((item) => item.id === accountId);
32697
32855
  if (account === void 0) return json(res, 404, { error: "unknown account" });
32698
- const before = await deps.client.fetchCheckinStatus(account.credential);
32856
+ /**
32857
+ * 先拿一份「能用」的凭据再发请求。
32858
+ *
32859
+ * 以前这里直接用 `account.credential`:凭据过期时上游回 401,用户看到
32860
+ * 的只有「领取失败」,而同一时刻对话正常(对话路径会先 ensureFresh)。
32861
+ */
32862
+ const credential = deps.pool.freshCredential === void 0 ? account.credential : await deps.pool.freshCredential(accountId);
32863
+ if (credential === void 0) return json(res, 409, { error: "this account's sign-in has expired and could not be renewed; sign in again in the WorkBuddy desktop app, then retry" });
32864
+ const before = await deps.client.fetchCheckinStatus(credential);
32699
32865
  if (!before.active) return json(res, 409, { error: "check-in activity is not active" });
32700
32866
  if (before.todayCheckedIn) return json(res, 200, {
32701
32867
  ok: true,
@@ -32708,10 +32874,19 @@ function registerPoolStatusRoute(ctx, deps) {
32708
32874
  });
32709
32875
  json(res, 200, {
32710
32876
  ok: true,
32711
- claim: await deps.client.claimDailyCheckin(account.credential)
32877
+ claim: await deps.client.claimDailyCheckin(credential)
32712
32878
  });
32713
32879
  } catch (error) {
32714
- json(res, 500, { error: safeMessage(error) });
32880
+ const message = safeMessage(error);
32881
+ /**
32882
+ * 401 说清楚该做什么。
32883
+ *
32884
+ * 「领取失败」没有信息量:它可能是活动没有、可能今天已经领过、也可能是
32885
+ * 登录态彻底过期(refresh token 也过了)。实测这一类占失败的大多数,
32886
+ * 而用户能做的动作只有一个 —— 回 WorkBuddy 桌面端重新登录这个账号。
32887
+ */
32888
+ if (/401|rejected this credential/i.test(message)) return json(res, 409, { error: "这个账号的登录已失效(上游返回 401),refresh token 也过期了。请在 WorkBuddy 桌面端重新登录这个账号,然后在卡片上重新检测账号后再领取。" });
32889
+ json(res, 500, { error: message });
32715
32890
  }
32716
32891
  }
32717
32892
  });
@@ -37735,10 +37910,25 @@ const PLUGIN_ROOT = fileURLToPath(new URL("..", import.meta.url));
37735
37910
  * other side; comparing one tree with itself would always agree.
37736
37911
  */
37737
37912
  const HOST_MODULE_ROOT = (() => {
37913
+ /**
37914
+ * issue #208:原来用 `../../node_modules/@deepseek-ai/dsh-llm-pi-ai/`:
37915
+ * `import.meta.url` 是 `<profile>/node_modules/dsh-xdpool/lib/index.js`,`../../`
37916
+ * 已经落到 `<profile>/node_modules/`,再拼 `node_modules/...` 就成了
37917
+ * `<profile>/node_modules/node_modules/...` —— 多一层,永远解析不到,守卫因此
37918
+ * 长期返回 unknown、日志里一个字都不写,而真正的 0.82 / 1.5 代际错配照样崩。
37919
+ *
37920
+ * 现在优先用 createRequire 从插件自身解析宿主包(pnpm / hoisted / 全局安装都
37921
+ * 能覆盖),再退回少一层的相对路径。createRequire 在 ESM bundle 里也可用。
37922
+ */
37738
37923
  try {
37739
- return fileURLToPath(new URL("../../node_modules/@deepseek-ai/dsh-llm-pi-ai/", import.meta.url));
37924
+ const require_ = createRequire(import.meta.url);
37925
+ return dirname(require_.resolve("@deepseek-ai/dsh-llm-pi-ai/package.json"));
37740
37926
  } catch {
37741
- return "";
37927
+ try {
37928
+ return fileURLToPath(new URL("../node_modules/@deepseek-ai/dsh-llm-pi-ai/", import.meta.url));
37929
+ } catch {
37930
+ return "";
37931
+ }
37742
37932
  }
37743
37933
  })();
37744
37934
  /** Stable Cordis plugin name. */
@@ -37995,9 +38185,19 @@ function createCore(logger) {
37995
38185
  */
37996
38186
  function warnOnPiAiGenerationMismatch(ctx) {
37997
38187
  try {
37998
- const message = piAiMismatchMessage(checkPiAiGeneration(PLUGIN_ROOT, HOST_MODULE_ROOT));
38188
+ const check = checkPiAiGeneration(PLUGIN_ROOT, HOST_MODULE_ROOT);
38189
+ const message = piAiMismatchMessage(check);
37999
38190
  if (message !== void 0) ctx.logger.warn(message);
38000
- } catch {}
38191
+ /**
38192
+ * issue #208:`unknown` 曾经和「对齐」在日志上完全一样,用户撞上代际错配时
38193
+ * 没有任何线索。现在至少留一行,说明是「读不到某一侧」还是「两侧对齐」。
38194
+ * 这一行不是警告 —— 单侧可见(比如宿主把 pi-ai 打进 bundle)是合法安装。
38195
+ */
38196
+ if (check.kind === "unknown") recordStartupNote("pi-ai generation: unknown (one or both resolutions unavailable)");
38197
+ else if (check.kind === "aligned") recordStartupNote(`pi-ai generation: aligned at ${check.generation}`);
38198
+ } catch (error) {
38199
+ recordStartupNote(`pi-ai generation check skipped: ${describeError(error)}`);
38200
+ }
38001
38201
  }
38002
38202
  /**
38003
38203
  * Late-bound switch for the 免密 lane, set once the catalog exists.
@@ -38623,30 +38823,52 @@ function apply(ctx, config = {}) {
38623
38823
  adopted: () => {},
38624
38824
  trustedHosts
38625
38825
  });
38626
- registerDoubaoRoutes(webCtx, {
38627
- session: () => doubaoSession,
38628
- trustedHosts,
38629
- save: (session) => {
38630
- adoptDoubaoSession(session);
38631
- writeStoredSession(session);
38632
- },
38633
- clear: () => {
38634
- adoptDoubaoSession(void 0);
38635
- removeStoredSession();
38636
- },
38637
- automation: () => doubaoAutomation,
38638
- /**
38639
- * Persist the card's disable-list — issue #196.
38640
- *
38641
- * `setSetting` re-reads and throws when the document did not change, so a
38642
- * refused write reaches the card as a 500 instead of looking saved.
38643
- */
38644
- saveDoubaoSelection: async (ids, hideAll) => {
38645
- const payload = [...ids];
38646
- await setSetting("doubaoDisabledModels", payload, payload);
38647
- await setSetting("doubaoHideAllModels", hideAll === true, hideAll === true);
38648
- }
38649
- });
38826
+ /**
38827
+ * 探针:确认 webServer 这条注入真的进来了。
38828
+ *
38829
+ * 插件有两层注册 —— `ctx.inject(['webServer'])` 里的 HTTP 路由,和
38830
+ * `ctx.inject(['llm'])` 里的 provider。前者若整段没执行(服务没注入、或回调里
38831
+ * 某条注册抛错),界面就只剩 `HTTP 404`,而 provider 层照常工作、日志里也有
38832
+ * `providers registered`。所以这一条 note 是判断「路由层到底有没有起来」的分界线。
38833
+ */
38834
+ recordStartupNote("routes: webCtx callback entered");
38835
+ /**
38836
+ * 每一层路由各自兜住自己的失败。
38837
+ *
38838
+ * 以前这里是三段落顺序执行的裸调用:任何一段抛错(重复路由、依赖没就位),
38839
+ * 后面的注册就再也不执行 —— 界面上表现为「模型能用、点任何按钮都是 HTTP 404」,
38840
+ * 而且日志里只剩一条 `providers registered`,看不出断在哪。
38841
+ * 现在每段独立 try/catch,失败写进 startup.log,其余照常注册。
38842
+ */
38843
+ try {
38844
+ registerDoubaoRoutes(webCtx, {
38845
+ session: () => doubaoSession,
38846
+ trustedHosts,
38847
+ save: (session) => {
38848
+ adoptDoubaoSession(session);
38849
+ writeStoredSession(session);
38850
+ },
38851
+ clear: () => {
38852
+ adoptDoubaoSession(void 0);
38853
+ removeStoredSession();
38854
+ },
38855
+ automation: () => doubaoAutomation,
38856
+ /**
38857
+ * Persist the card's disable-list — issue #196.
38858
+ *
38859
+ * `setSetting` re-reads and throws when the document did not change, so a
38860
+ * refused write reaches the card as a 500 instead of looking saved.
38861
+ */
38862
+ saveDoubaoSelection: async (ids, hideAll) => {
38863
+ const payload = [...ids];
38864
+ await setSetting("doubaoDisabledModels", payload, payload);
38865
+ await setSetting("doubaoHideAllModels", hideAll === true, hideAll === true);
38866
+ }
38867
+ });
38868
+ recordStartupNote("routes: doubao ok");
38869
+ } catch (error) {
38870
+ recordStartupNote(`routes: doubao FAILED: ${describeError(error)}`);
38871
+ }
38650
38872
  /**
38651
38873
  * The 「账号使用方式」 route — the one 3.0.0 forgot to register.
38652
38874
  *
@@ -38656,266 +38878,278 @@ function apply(ctx, config = {}) {
38656
38878
  * Registering it here is the whole fix — the read, the atomic write and the
38657
38879
  * publish to the pack were already written and tested.
38658
38880
  */
38659
- registerChannelUsageRoute(webCtx, {
38660
- pool: () => current().distribution ?? "priority",
38661
- trustedHosts
38662
- });
38663
- return registerPoolStatusRoute(webCtx, {
38664
- pool: core.pool,
38665
- trustedHosts,
38666
- /**
38667
- * The usage order each channel actually uses.
38668
- *
38669
- * A channel with an override reports it; one without reports the pool-wide value, because
38670
- * that IS what it uses — the card shows the effective decision, not just the stored one.
38671
- */
38672
- /**
38673
- * The usage order each channel actually uses.
38674
- *
38675
- * The per-channel overrides live in the plugin's own state file rather than in the host's
38676
- * settings document: the host's write path for a plugin's section accepts only its own
38677
- * `{auto}` toggle, so a settings write from here would need a service this build may not
38678
- * publish. A file the plugin already owns is the same mechanism `accounts.json` uses, and
38679
- * the effective value is computed the same way either way.
38680
- */
38681
- channelUsage: () => ({
38682
- pool: config.distribution ?? "priority",
38683
- channels: readChannelUsage()
38684
- }),
38685
- setChannelUsage: async (channel, strategy) => {
38686
- writeChannelUsage(channel, isUsageStrategy(strategy) ? strategy : void 0);
38687
- },
38688
- catalogs: core.catalogs,
38689
- client: core.client,
38690
- usage: () => usageRecorder.summary(),
38691
- shim: () => shimInfo("cn"),
38692
- scheduler: () => core.scheduler.status(),
38693
- runAutomation: (_job, _force) => core.scheduler.startRunAll(),
38694
- saveSelection: async (region, selection) => {
38695
- const payload = {
38696
- ...selection.enabledModelIds === void 0 ? {} : { enabledModelIds: [...selection.enabledModelIds] },
38697
- ...selection.imageModelIds === void 0 ? {} : { imageModelIds: [...selection.imageModelIds] },
38698
- ...selection.contextBudgets === void 0 ? {} : { contextBudgets: { ...selection.contextBudgets } }
38699
- };
38700
- await setSetting(modelSelectionKeyFor(region), payload, payload);
38701
- },
38702
- setAccountDisabled: async (accountId, disabled) => {
38703
- const currentIds = current().disabledAccountIds ?? [];
38704
- const next = disabled ? currentIds.includes(accountId) ? currentIds : [...currentIds, accountId] : currentIds.filter((id) => id !== accountId);
38705
- await setSetting("disabledAccountIds", next, next);
38706
- },
38707
- setCreditReserve: async (accountId, reserve) => {
38708
- const next = creditReservesWith(current().creditReserves, accountId, reserve);
38709
- await setSetting("creditReserves", next, next);
38710
- },
38711
- setAccountIgnored: async (accountId, ignored) => {
38712
- if (ignored) {
38713
- const known = core.pool.list().find((account) => account.id === accountId);
38714
- await ignoreAccount({
38715
- id: accountId,
38716
- ...known === void 0 ? {} : { label: known.label }
38717
- }, ignoredPath);
38718
- } else await unignoreAccount(accountId, ignoredPath);
38719
- refreshIgnored();
38720
- if (!ignored) await core.pool.scan();
38721
- },
38722
- ignoredAccounts: () => ignoredAccounts,
38723
- setPreferredAccount: async (accountId) => {
38724
- await writePreferredId(accountId ?? void 0, preferredPath);
38725
- applyPreferred(accountId ?? void 0);
38726
- },
38727
- refreshCatalog: async () => {
38728
- const result = await seedCatalog();
38729
- invalidateCatalog();
38730
- return result;
38731
- },
38732
- aggregateDocument: () => aggregateStatusOf(readAggregateSettingsSync(), aggregateCatalog.providerRows().map(toWebAggregateModel)),
38733
- saveAggregate: async (patch) => {
38734
- if (patch.kind === "lane") await setAggregateEnabled(patch.enabled);
38735
- else if (patch.kind === "clear") await clearProviderSetting(patch.providerId);
38736
- else await updateProviderSetting(patch.providerId, {
38737
- ...patch.enabled === void 0 ? {} : { enabled: patch.enabled },
38738
- ...patch.apiKey === void 0 ? {} : { apiKey: patch.apiKey },
38739
- ...patch.apiKeys === void 0 ? {} : { apiKeys: patch.apiKeys },
38740
- ...patch.appendApiKey === void 0 ? {} : { appendApiKey: patch.appendApiKey },
38741
- ...patch.distribution === void 0 ? {} : { distribution: patch.distribution },
38742
- ...patch.baseUrl === void 0 ? {} : { baseUrl: patch.baseUrl },
38743
- ...patch.models === void 0 ? {} : { models: patch.models }
38744
- });
38745
- await aggregateCatalog.refresh();
38746
- return aggregateStatusOf(readAggregateSettingsSync(), aggregateCatalog.providerRows().map(toWebAggregateModel));
38747
- },
38748
- probeAggregate: async (providerId) => {
38749
- const probe = await probeAggregateProvider(readAggregateSettingsSync(), providerId);
38750
- return {
38751
- ok: probe.ok,
38752
- status: probe.status,
38753
- message: probe.message,
38754
- ...probe.modelCount === void 0 ? {} : { modelCount: probe.modelCount },
38755
- ...probe.modelIds === void 0 ? {} : { modelIds: probe.modelIds }
38756
- };
38757
- },
38758
- /**
38759
- * One real streaming call, for the card's per-model "test connection" button.
38760
- *
38761
- * Routed through `ctx.llm.stream` rather than through any of this plugin's
38762
- * own lanes, and that is the whole point: `ctx.llm` is the host's adapter
38763
- * registry, so it resolves the provider/model pair to whichever credential
38764
- * and endpoint actually serve it — including lanes this plugin knows nothing
38765
- * about. Asking our own shims instead would make the button report on the
38766
- * plumbing rather than on the model the user clicked.
38767
- *
38768
- * Never throws (see {@link probeModelConnectivity}): the measurement is the
38769
- * answer, and a rejection here would show as a bare route failure that reads
38770
- * like a wrong key.
38771
- */
38772
- probeModel: async (provider, model, signal) => {
38773
- return probeModelConnectivity(ctx.llm, provider, model, { signal });
38774
- },
38775
- /**
38776
- * What each login channel contributes, read from the host's own catalogue.
38777
- *
38778
- * Not from the pack, on purpose. The pack's `model.list` keeps the id, the
38779
- * name and two flags and drops the rest, and the rest is exactly what the
38780
- * login page is asked to show. The host's `listModels` is also the same
38781
- * catalogue the model picker builds from, so a row's window here is the
38782
- * window the picker will enforce.
38783
- *
38784
- * `listModels` is a LISTING, though: the host's own answer carries only the
38785
- * id, the name, a description and the input modalities, and the host drops
38786
- * the context window out of it on the way out (its listing mapper keeps
38787
- * four fields). The window lives one call deeper, on
38788
- * `resolveModelInfo(provider, model)` — which is where the model picker and
38789
- * the compaction planner read it from — so a second pass over each row is
38790
- * the only way to show a context size that matches what will actually be
38791
- * enforced.
38792
- *
38793
- * That second pass is bounded and per-row isolated: adapters resolve a model
38794
- * from their own cache in the common case, a row that cannot be resolved
38795
- * simply prints no window, and a channel's answer is never held up by one
38796
- * model it could not describe.
38797
- *
38798
- * A provider with no adapter registered under it is left out of the record
38799
- * instead of being reported empty: "not signed in" and "signed in with
38800
- * nothing to offer" would otherwise be drawn identically, and the user has
38801
- * no way to tell which one they are looking at.
38802
- */
38803
- channelModels: async (providers, hints) => {
38804
- const models = {};
38805
- const resolveConcurrency = 6;
38806
- for (const provider of providers) try {
38807
- const hinted = hints?.[provider];
38808
- const rows = hinted !== void 0 && hinted.length > 0 ? hinted.map((id) => ({
38809
- id,
38810
- name: id
38811
- })) : await ctx.llm.listModels(provider);
38812
- const resolved = /* @__PURE__ */ new Map();
38813
- let next = 0;
38814
- const workers = Array.from({ length: Math.min(resolveConcurrency, rows.length) }, async () => {
38815
- while (next < rows.length) {
38816
- const row = rows[next++];
38817
- if (row === void 0) continue;
38818
- let extra = {};
38819
- try {
38820
- const info = await ctx.llm.resolveModelInfo(provider, row.id);
38821
- extra = {
38822
- ...info.context?.contextWindow === void 0 ? {} : { contextWindow: info.context.contextWindow },
38823
- ...info.defaultMaxTokens === void 0 ? {} : { maxTokens: info.defaultMaxTokens },
38824
- ...info.inputModalities === void 0 ? {} : { inputModalities: info.inputModalities }
38825
- };
38826
- } catch (cause) {}
38827
- resolved.set(row.id, {
38828
- id: row.id,
38829
- name: row.name,
38830
- ...row.description === void 0 ? {} : { description: row.description },
38831
- ...row.inputModalities === void 0 ? {} : { inputModalities: row.inputModalities },
38832
- ...extra
38833
- });
38834
- }
38881
+ try {
38882
+ registerChannelUsageRoute(webCtx, {
38883
+ pool: () => current().distribution ?? "priority",
38884
+ trustedHosts
38885
+ });
38886
+ recordStartupNote("routes: channel-usage ok");
38887
+ } catch (error) {
38888
+ recordStartupNote(`routes: channel-usage FAILED: ${describeError(error)}`);
38889
+ }
38890
+ recordStartupNote("routes: doubao + channel-usage registered; registering the rest");
38891
+ recordStartupNote("routes: status + checkin + models routes registering");
38892
+ try {
38893
+ registerPoolStatusRoute(webCtx, {
38894
+ pool: core.pool,
38895
+ trustedHosts,
38896
+ /**
38897
+ * The usage order each channel actually uses.
38898
+ *
38899
+ * A channel with an override reports it; one without reports the pool-wide value, because
38900
+ * that IS what it uses — the card shows the effective decision, not just the stored one.
38901
+ */
38902
+ /**
38903
+ * The usage order each channel actually uses.
38904
+ *
38905
+ * The per-channel overrides live in the plugin's own state file rather than in the host's
38906
+ * settings document: the host's write path for a plugin's section accepts only its own
38907
+ * `{auto}` toggle, so a settings write from here would need a service this build may not
38908
+ * publish. A file the plugin already owns is the same mechanism `accounts.json` uses, and
38909
+ * the effective value is computed the same way either way.
38910
+ */
38911
+ channelUsage: () => ({
38912
+ pool: config.distribution ?? "priority",
38913
+ channels: readChannelUsage()
38914
+ }),
38915
+ setChannelUsage: async (channel, strategy) => {
38916
+ writeChannelUsage(channel, isUsageStrategy(strategy) ? strategy : void 0);
38917
+ },
38918
+ catalogs: core.catalogs,
38919
+ client: core.client,
38920
+ usage: () => usageRecorder.summary(),
38921
+ shim: () => shimInfo("cn"),
38922
+ scheduler: () => core.scheduler.status(),
38923
+ runAutomation: (_job, _force) => core.scheduler.startRunAll(),
38924
+ saveSelection: async (region, selection) => {
38925
+ const payload = {
38926
+ ...selection.enabledModelIds === void 0 ? {} : { enabledModelIds: [...selection.enabledModelIds] },
38927
+ ...selection.imageModelIds === void 0 ? {} : { imageModelIds: [...selection.imageModelIds] },
38928
+ ...selection.contextBudgets === void 0 ? {} : { contextBudgets: { ...selection.contextBudgets } }
38929
+ };
38930
+ await setSetting(modelSelectionKeyFor(region), payload, payload);
38931
+ },
38932
+ setAccountDisabled: async (accountId, disabled) => {
38933
+ const currentIds = current().disabledAccountIds ?? [];
38934
+ const next = disabled ? currentIds.includes(accountId) ? currentIds : [...currentIds, accountId] : currentIds.filter((id) => id !== accountId);
38935
+ await setSetting("disabledAccountIds", next, next);
38936
+ },
38937
+ setCreditReserve: async (accountId, reserve) => {
38938
+ const next = creditReservesWith(current().creditReserves, accountId, reserve);
38939
+ await setSetting("creditReserves", next, next);
38940
+ },
38941
+ setAccountIgnored: async (accountId, ignored) => {
38942
+ if (ignored) {
38943
+ const known = core.pool.list().find((account) => account.id === accountId);
38944
+ await ignoreAccount({
38945
+ id: accountId,
38946
+ ...known === void 0 ? {} : { label: known.label }
38947
+ }, ignoredPath);
38948
+ } else await unignoreAccount(accountId, ignoredPath);
38949
+ refreshIgnored();
38950
+ if (!ignored) await core.pool.scan();
38951
+ },
38952
+ ignoredAccounts: () => ignoredAccounts,
38953
+ setPreferredAccount: async (accountId) => {
38954
+ await writePreferredId(accountId ?? void 0, preferredPath);
38955
+ applyPreferred(accountId ?? void 0);
38956
+ },
38957
+ refreshCatalog: async () => {
38958
+ const result = await seedCatalog();
38959
+ invalidateCatalog();
38960
+ return result;
38961
+ },
38962
+ aggregateDocument: () => aggregateStatusOf(readAggregateSettingsSync(), aggregateCatalog.providerRows().map(toWebAggregateModel)),
38963
+ saveAggregate: async (patch) => {
38964
+ if (patch.kind === "lane") await setAggregateEnabled(patch.enabled);
38965
+ else if (patch.kind === "clear") await clearProviderSetting(patch.providerId);
38966
+ else await updateProviderSetting(patch.providerId, {
38967
+ ...patch.enabled === void 0 ? {} : { enabled: patch.enabled },
38968
+ ...patch.apiKey === void 0 ? {} : { apiKey: patch.apiKey },
38969
+ ...patch.apiKeys === void 0 ? {} : { apiKeys: patch.apiKeys },
38970
+ ...patch.appendApiKey === void 0 ? {} : { appendApiKey: patch.appendApiKey },
38971
+ ...patch.distribution === void 0 ? {} : { distribution: patch.distribution },
38972
+ ...patch.baseUrl === void 0 ? {} : { baseUrl: patch.baseUrl },
38973
+ ...patch.models === void 0 ? {} : { models: patch.models }
38835
38974
  });
38836
- await Promise.all(workers);
38837
- models[provider] = rows.map((row) => resolved.get(row.id)).filter((row) => row !== void 0);
38838
- } catch {}
38839
- return models;
38840
- },
38841
- discoverAggregate: async (providerId) => {
38842
- const probe = await probeAggregateProvider(readAggregateSettingsSync(), providerId);
38843
- if (!probe.ok || probe.modelIds === void 0) return {
38844
- ok: probe.ok,
38845
- status: probe.status,
38846
- message: probe.message,
38847
- ...probe.modelCount === void 0 ? {} : { modelCount: probe.modelCount }
38848
- };
38849
- await updateProviderSetting(providerId, { discovered: probe.modelIds });
38850
- await aggregateCatalog.refresh();
38851
- return {
38852
- ok: true,
38853
- status: probe.status,
38854
- message: probe.message,
38855
- ...probe.modelCount === void 0 ? {} : { modelCount: probe.modelCount },
38856
- modelIds: probe.modelIds,
38857
- committed: probe.modelIds.length
38858
- };
38859
- },
38860
- channelsDocument: () => {
38861
- const state = channels.state();
38862
- return {
38863
- state: state.state,
38864
- ...state.state === "unavailable" ? { reason: state.reason } : {},
38865
- channels: REGISTERED_CHANNELS.map((channel) => ({
38866
- id: channel.id,
38867
- name: channel.name,
38868
- org: channel.org,
38869
- ...channel.domain === void 0 ? {} : { domain: channel.domain },
38870
- accent: channel.accent,
38871
- note: channel.note,
38872
- loginKind: channel.login,
38873
- ownedByPool: POOL_OWNED_CHANNELS.has(channel.id),
38874
- ...channel.smsHint === true ? { smsHint: true } : {},
38875
- ...channel.credits === void 0 ? {} : { credits: channel.credits }
38876
- }))
38877
- };
38878
- },
38879
- combosDocument: async () => combosStatusOf(readAggregateSettingsSync(), aggregateCatalog, core.catalogs.cn.current(), await hostRoster()),
38880
- saveCombos: async (raw) => {
38881
- await saveCombos(raw);
38882
- await aggregateCatalog.refresh();
38883
- return combosStatusOf(readAggregateSettingsSync(), aggregateCatalog, core.catalogs.cn.current(), await hostRoster());
38884
- },
38885
- /** Estimated credit spend per channel, for the composer strip. */
38886
- creditsSpend: async (days) => await creditSpend(days),
38887
- /**
38888
- * Relay state plus the gateway's model picker.
38889
- *
38890
- * The candidates come from the shim's own roster rather than a parallel
38891
- * assembly here, so the card cannot offer a model the gateway would then
38892
- * refuse — the exact drift the picker exists to prevent.
38893
- */
38894
- relayDocument,
38895
- /**
38896
- * Apply one patch from the card and answer with the fresh document.
38897
- *
38898
- * The write path mints a key when the card asks for a rotation and the user
38899
- * has never had one: an enabled relay with no key would have to either refuse
38900
- * everyone (so the switch silently does nothing) or accept everyone. Minting
38901
- * one keeps "enabled" honest, and the card shows it so it can be pasted into
38902
- * the other device.
38903
- */
38904
- saveRelay: async (patch) => {
38905
- const before = readAggregateSettingsSync().relay ?? {};
38906
- const key = patch.key === "" ? newRelayKey() : patch.key;
38907
- await updateRelaySetting({
38908
- ...patch.enabled === void 0 ? {} : { enabled: patch.enabled },
38909
- ...patch.host === void 0 ? {} : { host: patch.host },
38910
- ...patch.port === void 0 ? {} : { port: patch.port },
38911
- key: key ?? before.key ?? newRelayKey(),
38912
- ...patch.models === void 0 ? {} : { models: patch.models },
38913
- ...patch.modelsMode === void 0 ? {} : { modelsMode: patch.modelsMode }
38914
- });
38915
- await relay.sync();
38916
- return relayDocument();
38917
- }
38918
- });
38975
+ await aggregateCatalog.refresh();
38976
+ return aggregateStatusOf(readAggregateSettingsSync(), aggregateCatalog.providerRows().map(toWebAggregateModel));
38977
+ },
38978
+ probeAggregate: async (providerId) => {
38979
+ const probe = await probeAggregateProvider(readAggregateSettingsSync(), providerId);
38980
+ return {
38981
+ ok: probe.ok,
38982
+ status: probe.status,
38983
+ message: probe.message,
38984
+ ...probe.modelCount === void 0 ? {} : { modelCount: probe.modelCount },
38985
+ ...probe.modelIds === void 0 ? {} : { modelIds: probe.modelIds }
38986
+ };
38987
+ },
38988
+ /**
38989
+ * One real streaming call, for the card's per-model "test connection" button.
38990
+ *
38991
+ * Routed through `ctx.llm.stream` rather than through any of this plugin's
38992
+ * own lanes, and that is the whole point: `ctx.llm` is the host's adapter
38993
+ * registry, so it resolves the provider/model pair to whichever credential
38994
+ * and endpoint actually serve it — including lanes this plugin knows nothing
38995
+ * about. Asking our own shims instead would make the button report on the
38996
+ * plumbing rather than on the model the user clicked.
38997
+ *
38998
+ * Never throws (see {@link probeModelConnectivity}): the measurement is the
38999
+ * answer, and a rejection here would show as a bare route failure that reads
39000
+ * like a wrong key.
39001
+ */
39002
+ probeModel: async (provider, model, signal) => {
39003
+ return probeModelConnectivity(ctx.llm, provider, model, { signal });
39004
+ },
39005
+ /**
39006
+ * What each login channel contributes, read from the host's own catalogue.
39007
+ *
39008
+ * Not from the pack, on purpose. The pack's `model.list` keeps the id, the
39009
+ * name and two flags and drops the rest, and the rest is exactly what the
39010
+ * login page is asked to show. The host's `listModels` is also the same
39011
+ * catalogue the model picker builds from, so a row's window here is the
39012
+ * window the picker will enforce.
39013
+ *
39014
+ * `listModels` is a LISTING, though: the host's own answer carries only the
39015
+ * id, the name, a description and the input modalities, and the host drops
39016
+ * the context window out of it on the way out (its listing mapper keeps
39017
+ * four fields). The window lives one call deeper, on
39018
+ * `resolveModelInfo(provider, model)` — which is where the model picker and
39019
+ * the compaction planner read it from — so a second pass over each row is
39020
+ * the only way to show a context size that matches what will actually be
39021
+ * enforced.
39022
+ *
39023
+ * That second pass is bounded and per-row isolated: adapters resolve a model
39024
+ * from their own cache in the common case, a row that cannot be resolved
39025
+ * simply prints no window, and a channel's answer is never held up by one
39026
+ * model it could not describe.
39027
+ *
39028
+ * A provider with no adapter registered under it is left out of the record
39029
+ * instead of being reported empty: "not signed in" and "signed in with
39030
+ * nothing to offer" would otherwise be drawn identically, and the user has
39031
+ * no way to tell which one they are looking at.
39032
+ */
39033
+ channelModels: async (providers, hints) => {
39034
+ const models = {};
39035
+ const resolveConcurrency = 6;
39036
+ for (const provider of providers) try {
39037
+ const hinted = hints?.[provider];
39038
+ const rows = hinted !== void 0 && hinted.length > 0 ? hinted.map((id) => ({
39039
+ id,
39040
+ name: id
39041
+ })) : await ctx.llm.listModels(provider);
39042
+ const resolved = /* @__PURE__ */ new Map();
39043
+ let next = 0;
39044
+ const workers = Array.from({ length: Math.min(resolveConcurrency, rows.length) }, async () => {
39045
+ while (next < rows.length) {
39046
+ const row = rows[next++];
39047
+ if (row === void 0) continue;
39048
+ let extra = {};
39049
+ try {
39050
+ const info = await ctx.llm.resolveModelInfo(provider, row.id);
39051
+ extra = {
39052
+ ...info.context?.contextWindow === void 0 ? {} : { contextWindow: info.context.contextWindow },
39053
+ ...info.defaultMaxTokens === void 0 ? {} : { maxTokens: info.defaultMaxTokens },
39054
+ ...info.inputModalities === void 0 ? {} : { inputModalities: info.inputModalities }
39055
+ };
39056
+ } catch (cause) {}
39057
+ resolved.set(row.id, {
39058
+ id: row.id,
39059
+ name: row.name,
39060
+ ...row.description === void 0 ? {} : { description: row.description },
39061
+ ...row.inputModalities === void 0 ? {} : { inputModalities: row.inputModalities },
39062
+ ...extra
39063
+ });
39064
+ }
39065
+ });
39066
+ await Promise.all(workers);
39067
+ models[provider] = rows.map((row) => resolved.get(row.id)).filter((row) => row !== void 0);
39068
+ } catch {}
39069
+ return models;
39070
+ },
39071
+ discoverAggregate: async (providerId) => {
39072
+ const probe = await probeAggregateProvider(readAggregateSettingsSync(), providerId);
39073
+ if (!probe.ok || probe.modelIds === void 0) return {
39074
+ ok: probe.ok,
39075
+ status: probe.status,
39076
+ message: probe.message,
39077
+ ...probe.modelCount === void 0 ? {} : { modelCount: probe.modelCount }
39078
+ };
39079
+ await updateProviderSetting(providerId, { discovered: probe.modelIds });
39080
+ await aggregateCatalog.refresh();
39081
+ return {
39082
+ ok: true,
39083
+ status: probe.status,
39084
+ message: probe.message,
39085
+ ...probe.modelCount === void 0 ? {} : { modelCount: probe.modelCount },
39086
+ modelIds: probe.modelIds,
39087
+ committed: probe.modelIds.length
39088
+ };
39089
+ },
39090
+ channelsDocument: () => {
39091
+ const state = channels.state();
39092
+ return {
39093
+ state: state.state,
39094
+ ...state.state === "unavailable" ? { reason: state.reason } : {},
39095
+ channels: REGISTERED_CHANNELS.map((channel) => ({
39096
+ id: channel.id,
39097
+ name: channel.name,
39098
+ org: channel.org,
39099
+ ...channel.domain === void 0 ? {} : { domain: channel.domain },
39100
+ accent: channel.accent,
39101
+ note: channel.note,
39102
+ loginKind: channel.login,
39103
+ ownedByPool: POOL_OWNED_CHANNELS.has(channel.id),
39104
+ ...channel.smsHint === true ? { smsHint: true } : {},
39105
+ ...channel.credits === void 0 ? {} : { credits: channel.credits }
39106
+ }))
39107
+ };
39108
+ },
39109
+ combosDocument: async () => combosStatusOf(readAggregateSettingsSync(), aggregateCatalog, core.catalogs.cn.current(), await hostRoster()),
39110
+ saveCombos: async (raw) => {
39111
+ await saveCombos(raw);
39112
+ await aggregateCatalog.refresh();
39113
+ return combosStatusOf(readAggregateSettingsSync(), aggregateCatalog, core.catalogs.cn.current(), await hostRoster());
39114
+ },
39115
+ /** Estimated credit spend per channel, for the composer strip. */
39116
+ creditsSpend: async (days) => await creditSpend(days),
39117
+ /**
39118
+ * Relay state plus the gateway's model picker.
39119
+ *
39120
+ * The candidates come from the shim's own roster rather than a parallel
39121
+ * assembly here, so the card cannot offer a model the gateway would then
39122
+ * refuse — the exact drift the picker exists to prevent.
39123
+ */
39124
+ relayDocument,
39125
+ /**
39126
+ * Apply one patch from the card and answer with the fresh document.
39127
+ *
39128
+ * The write path mints a key when the card asks for a rotation and the user
39129
+ * has never had one: an enabled relay with no key would have to either refuse
39130
+ * everyone (so the switch silently does nothing) or accept everyone. Minting
39131
+ * one keeps "enabled" honest, and the card shows it so it can be pasted into
39132
+ * the other device.
39133
+ */
39134
+ saveRelay: async (patch) => {
39135
+ const before = readAggregateSettingsSync().relay ?? {};
39136
+ const key = patch.key === "" ? newRelayKey() : patch.key;
39137
+ await updateRelaySetting({
39138
+ ...patch.enabled === void 0 ? {} : { enabled: patch.enabled },
39139
+ ...patch.host === void 0 ? {} : { host: patch.host },
39140
+ ...patch.port === void 0 ? {} : { port: patch.port },
39141
+ key: key ?? before.key ?? newRelayKey(),
39142
+ ...patch.models === void 0 ? {} : { models: patch.models },
39143
+ ...patch.modelsMode === void 0 ? {} : { modelsMode: patch.modelsMode }
39144
+ });
39145
+ await relay.sync();
39146
+ return relayDocument();
39147
+ }
39148
+ });
39149
+ recordStartupNote("routes: status family ok");
39150
+ } catch (error) {
39151
+ recordStartupNote(`routes: status family FAILED: ${describeError(error)}`);
39152
+ }
38919
39153
  });
38920
39154
  api = {
38921
39155
  ...core,