dsh-agy-link 0.6.38 → 0.6.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.39 (2026-11-19)
4
+
5
+ ### English
6
+
7
+ - **Fix(quota): a manual pool refresh no longer freezes one account for days or takes a minute (reported live: "the first one refreshed, the second is just stuck, and every refresh is far too slow").** Two independent causes, both fixed:
8
+ - **Stuck row.** An account whose `retrieveUserQuotaSummary` was refused (`403 You do not have a valid license of this product`, with `ECONNRESET` on the daily endpoint) produced no authoritative snapshot — and `buildFamilyQuotas` deliberately keeps the previous complete value, so the card kept rendering yesterday's percentages with **no error anywhere** (three `catch` layers swallowed it and the route had already answered `ok`). The pipeline now records `quotaUnavailable = { reason, since, retryAfter, detail }` on the account (`no_license` / `auth` / `unreachable` / `partial`), the console renders "Quota refresh failed · <reason> · figures last updated <time>", and an authoritative snapshot clears the marker. A `no_license` account also leaves the hourly background sweep for `QUOTA_LICENSE_RETRY_MS` (6h) and skips the doomed summary call entirely, while an explicit click still probes (so a renewed licence recovers immediately).
9
+ - **Slow.** `daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary` resets the connection for every account on this machine (measured 5.3-8.4s) while the sandbox endpoint answers, and every quota call walked the fixed endpoint list from that dead end first — on every account, every refresh, including the background sweep. A per-operation endpoint health memory (`QUOTA_ENDPOINT_DOWN_MS` 10min) now tries recently-failed endpoints last (never skipping them; a total outage still probes), and a user-initiated sweep may run 2 same-egress accounts in parallel with the existing 400-850ms start jitter (`sweep.ts`); the unattended sweep stays strictly serial. One five-account pool that measured ~55s now finishes its per-account work in roughly the time of two cascades.
10
+ - **Fix(ui): refresh progress is real, and a duplicate click says so.** `/status` now exposes `quotaRefreshing` (the host's in-flight account ids) and account cards render "syncing" from it instead of from the click that cleared the moment the route answered; `/pool/refresh-quota` returns `alreadyRunning: true` when the same key is still in flight, so the console says "a refresh is already running" instead of a false "started".
11
+
12
+ ### 中文
13
+
14
+ - **修复(额度):手动刷新账号池不再让某个号「永远卡住」,也不再慢到一分钟(现场反馈:第一个刷出来了、第二个一直卡着、每个都慢得离谱)。** 两个独立根因,都已修复:
15
+ - **卡住**。某账号的 `retrieveUserQuotaSummary` 被拒(`403 You do not have a valid license of this product`,daily 端点还 `ECONNRESET`),拿不到权威快照;而 `buildFamilyQuotas` 的设计是**保留上一份完整数据**(防止部分回退数据覆盖好数据),于是卡片一直渲染前一天的百分比,**任何地方都没有报错**(三层 `catch` 全吞、路由还提前回了 `ok`)。现在管线把 `quotaUnavailable = { reason, since, retryAfter, detail }` 写到账号上(`no_license` / `auth` / `unreachable` / `partial`),控制台渲染「配额刷新失败 · 原因 · 数据停留在 <时间>」,拿到权威快照即清除标记。`no_license` 账号同时退出每小时后台轮询 `QUOTA_LICENSE_RETRY_MS`(6 小时)并跳过注定失败的摘要请求;**用户手动点击仍然必探**(续费后可立即恢复)。
16
+ - **慢**。`daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary` 对本机每个账号都重置连接(实测 5.3~8.4 秒),而 sandbox 端点正常,但每次配额调用都从这条死端点起步——每个账号、每次刷新、包括后台轮询。新增按「操作|端点」的失败记忆(`QUOTA_ENDPOINT_DOWN_MS` 10 分钟),把刚失败的端点排到最后(**绝不跳过**,全部失败时仍按原序探测);用户手动全池刷新允许**同一出口内 2 个账号并发**并保留原有 `400~850ms` 起点抖动(`sweep.ts`),后台轮询仍严格串行。实测 5 号同出口的池子从约 55 秒降到约两个级联的时间。
17
+ - **修复(UI):刷新进度是真的,重复点击也有话讲。** `/status` 新增 `quotaRefreshing`(宿主在途的账号 id),账号卡据此渲染「同步中」,不再依赖「点击后立刻清空」的客户端状态;`/pool/refresh-quota` 在同 key 仍在途时返回 `alreadyRunning: true`,控制台提示「正在刷新中」而不是谎报「已开始刷新」。
18
+
3
19
  ## 0.6.38 (2026-11-19)
4
20
 
5
21
  ### English
@@ -8896,6 +8896,26 @@ var AccountPoolManager = class {
8896
8896
  this.persist();
8897
8897
  }
8898
8898
  /**
8899
+ * Record that the last refresh produced no authoritative snapshot.
8900
+ *
8901
+ * Kept on the account (not just in a log line) because the console has to be
8902
+ * able to say WHY a row is frozen: a failed summary keeps the previous
8903
+ * complete value by design, so the numbers alone can never show staleness.
8904
+ */
8905
+ noteQuotaUnavailable(id, state) {
8906
+ const acc = this.getAccount(id);
8907
+ if (!acc) return;
8908
+ acc.quotaUnavailable = state;
8909
+ this.persist();
8910
+ }
8911
+ /** Clear the marker once an authoritative snapshot arrives. */
8912
+ clearQuotaUnavailable(id) {
8913
+ const acc = this.getAccount(id);
8914
+ if (!acc?.quotaUnavailable) return;
8915
+ delete acc.quotaUnavailable;
8916
+ this.persist();
8917
+ }
8918
+ /**
8899
8919
  * Drop one family's quota row.
8900
8920
  *
8901
8921
  * Used when stored numbers provably cannot be attributed to this account —
package/dist/client.js CHANGED
@@ -77,6 +77,13 @@ window.__ModuleLoader__.load({
77
77
  "quota.refreshStarted": "正在同步额度,稍后自动更新",
78
78
  "quota.windowReset": "已重置 · 可用",
79
79
  "quota.unactivated": "未激活 · 预热启动计时",
80
+ "quota.refreshInProgress": "该账号正在刷新中,请稍候",
81
+ "quota.unavailableTitle": "配额刷新失败",
82
+ "quota.unavailable.no_license": "此账号无有效许可(接口 403)",
83
+ "quota.unavailable.auth": "登录凭据已失效(401)",
84
+ "quota.unavailable.unreachable": "配额接口不可达",
85
+ "quota.unavailable.partial": "只取到模型级数据,5 小时/周额度未更新",
86
+ "quota.unavailableSince": " · 数据停留在 {time}",
80
87
  "quota.paceSurplus": "节奏充裕(富裕 +{pct}%)",
81
88
  "quota.paceFast": "消耗较快(超耗 {pct}%)",
82
89
  "quota.paceOnTrack": "消耗均衡",
@@ -298,6 +305,13 @@ window.__ModuleLoader__.load({
298
305
  "quota.refreshStarted": "Syncing quota — figures update shortly",
299
306
  "quota.windowReset": "Reset · available",
300
307
  "quota.unactivated": "Unactivated · warmup to start",
308
+ "quota.refreshInProgress": "A refresh is already running for this account",
309
+ "quota.unavailableTitle": "Quota refresh failed",
310
+ "quota.unavailable.no_license": "this account has no valid license (HTTP 403)",
311
+ "quota.unavailable.auth": "the login credential is no longer valid (401)",
312
+ "quota.unavailable.unreachable": "the quota endpoints are unreachable",
313
+ "quota.unavailable.partial": "only per-model data arrived; 5-hour/weekly figures are stale",
314
+ "quota.unavailableSince": " · figures last updated {time}",
301
315
  "quota.paceSurplus": "Surplus pace (+{pct}%)",
302
316
  "quota.paceFast": "Burning fast (-{pct}%)",
303
317
  "quota.paceOnTrack": "On pace",
@@ -519,6 +533,13 @@ window.__ModuleLoader__.load({
519
533
  "quota.refreshStarted": "Sincronizando a cota — os números atualizam em breve",
520
534
  "quota.windowReset": "Redefinida · disponível",
521
535
  "quota.unactivated": "Não ativada · aqueça para iniciar",
536
+ "quota.refreshInProgress": "Já existe uma atualização em andamento para esta conta",
537
+ "quota.unavailableTitle": "Falha ao atualizar a cota",
538
+ "quota.unavailable.no_license": "esta conta não tem uma licença válida (HTTP 403)",
539
+ "quota.unavailable.auth": "a credencial de acesso não é mais válida (401)",
540
+ "quota.unavailable.unreachable": "não é possível alcançar os serviços de cota",
541
+ "quota.unavailable.partial": "só chegaram dados por modelo; os números de 5 h/semana estão desatualizados",
542
+ "quota.unavailableSince": " · dados de {time}",
522
543
  "quota.paceSurplus": "Folga de ritmo (+{pct}%)",
523
544
  "quota.paceFast": "Consumo rápido (-{pct}%)",
524
545
  "quota.paceOnTrack": "No ritmo",
@@ -740,6 +761,13 @@ window.__ModuleLoader__.load({
740
761
  "quota.refreshStarted": "Sincronizando la cuota — las cifras se actualizarán en breve",
741
762
  "quota.windowReset": "Reiniciada · disponible",
742
763
  "quota.unactivated": "Sin activar · calentar para iniciar",
764
+ "quota.refreshInProgress": "Ya hay una actualización en curso para esta cuenta",
765
+ "quota.unavailableTitle": "No se pudo actualizar la cuota",
766
+ "quota.unavailable.no_license": "esta cuenta no tiene una licencia válida (HTTP 403)",
767
+ "quota.unavailable.auth": "la credencial de acceso ya no es válida (401)",
768
+ "quota.unavailable.unreachable": "no se puede alcanzar los servicios de cuota",
769
+ "quota.unavailable.partial": "solo llegaron datos por modelo; las cifras de 5 h/semana están desactualizadas",
770
+ "quota.unavailableSince": " · datos del {time}",
743
771
  "quota.paceSurplus": "Margen favorable (+{pct}%)",
744
772
  "quota.paceFast": "Consumo rápido (-{pct}%)",
745
773
  "quota.paceOnTrack": "A buen ritmo",
@@ -7761,6 +7789,10 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
7761
7789
  return;
7762
7790
  }
7763
7791
  await refresh();
7792
+ if (res?.alreadyRunning === true) {
7793
+ showToast(t("quota.refreshInProgress"), "info");
7794
+ return;
7795
+ }
7764
7796
  showToast(res?.pending === true ? t("quota.refreshStarted") : t("quota.refreshed"), res?.pending === true ? "info" : "success");
7765
7797
  } finally {
7766
7798
  setLoadingAction(null);
@@ -8447,12 +8479,55 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8447
8479
  color: "var(--agy-text-primary)"
8448
8480
  } }, brandIcon(FAMILY_BRAND[familyKey], 13), h("span", null, label)), familyKey !== "argon" || has5h ? renderLine(t, t("quota.fiveHour"), pct5h, c5h, note5h, FIVE_H_MS, info?.remainingFraction, info?.resetTime, isRefreshing) : null, renderLine(t, t("quota.weekly"), pctWeekly, cWeekly, noteWeekly, SEVEN_D_MS, info?.weeklyFraction, info?.weeklyResetTime, isRefreshing));
8449
8481
  }
8482
+ /** Short absolute stamp for "this data is from …" notes (past tense). */
8483
+ function formatSnapshotStamp(ms) {
8484
+ const d = new Date(ms);
8485
+ const hh = d.getHours().toString().padStart(2, "0");
8486
+ const mm = d.getMinutes().toString().padStart(2, "0");
8487
+ return `${d.getMonth() + 1}/${d.getDate()} ${hh}:${mm}`;
8488
+ }
8489
+ /**
8490
+ * One-line "quota unavailable" note for an account whose last refresh produced
8491
+ * no authoritative snapshot.
8492
+ *
8493
+ * WHY (live 2026-11-19): `buildFamilyQuotas` deliberately keeps the previous
8494
+ * complete value when the summary failed — a partial fallback must never
8495
+ * overwrite good data — so a refused account renders yesterday's percentages
8496
+ * with nothing to say they are old. The user reported exactly that as "the
8497
+ * second account is stuck". The numbers stay honest; the freshness does not
8498
+ * get to hide.
8499
+ */
8500
+ function renderQuotaUnavailableNote(t, acc) {
8501
+ const state = acc.quotaUnavailable;
8502
+ if (!state) return null;
8503
+ const newest = Math.max(0, ...Object.values(acc.quotas).map((q) => q?.updatedAt ?? 0));
8504
+ const reason = t(`quota.unavailable.${state.reason}`);
8505
+ return h("div", {
8506
+ key: "agy-quota-unavailable",
8507
+ style: {
8508
+ display: "flex",
8509
+ alignItems: "center",
8510
+ gap: "5px",
8511
+ margin: "2px 0 5px 0",
8512
+ padding: "3px 7px",
8513
+ borderRadius: "6px",
8514
+ fontSize: "11px",
8515
+ fontWeight: 600,
8516
+ color: "var(--agy-quota-med-text)",
8517
+ background: "var(--agy-quota-med-bg)",
8518
+ border: "1px solid var(--agy-quota-med-border)"
8519
+ }
8520
+ }, uiIcon("alert", 10, "var(--agy-quota-med-text)"), h("span", null, `${t("quota.unavailableTitle")} · ${reason}`), newest > 0 ? h("span", { style: {
8521
+ fontWeight: 500,
8522
+ opacity: .85
8523
+ } }, t("quota.unavailableSince", { time: formatSnapshotStamp(newest) })) : null);
8524
+ }
8450
8525
  //#endregion
8451
8526
  //#region src/client/sections/AccountsPanel.ts
8452
8527
  function AccountsPanel(props) {
8453
- const { t, pool, accounts, loadingAction, proxyInputs, setProxyInputs, editingProxyId, setEditingProxyId, expandedModels, toggleExpand, optimisticActiveId, handlers } = props;
8528
+ const { t, pool, accounts, loadingAction, quotaRefreshing = [], proxyInputs, setProxyInputs, editingProxyId, setEditingProxyId, expandedModels, toggleExpand, optimisticActiveId, handlers } = props;
8454
8529
  const accountActionBusy = (acc, action) => loadingAction === `${action}:${acc.id}`;
8455
- const renderQuotaBar = (label, familyKey, acc) => renderFamilyQuotaBar(t, label, familyKey, acc, loadingAction === "refresh:all" || loadingAction === `refresh:${acc.id}`);
8530
+ const renderQuotaBar = (label, familyKey, acc) => renderFamilyQuotaBar(t, label, familyKey, acc, loadingAction === "refresh:all" || loadingAction === `refresh:${acc.id}` || quotaRefreshing.includes(acc.id));
8456
8531
  const authoritativeActiveId = pool?.activeAccountId ?? pool?.lastActiveAccountId ?? pool?.activeAccountIds?.google ?? pool?.primaryAccountId;
8457
8532
  const activeAccountId = optimisticActiveId ?? authoritativeActiveId;
8458
8533
  return accounts.map((acc) => {
@@ -8517,7 +8592,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8517
8592
  }), h("div", {
8518
8593
  key: "agy-body",
8519
8594
  style: S.quotaBox
8520
- }, renderQuotaBar("Gemini", "google", acc), acc.quotas.argon ? renderQuotaBar("Argon", "argon", acc) : null, h(Button, {
8595
+ }, renderQuotaUnavailableNote(t, acc), renderQuotaBar("Gemini", "google", acc), acc.quotas.argon ? renderQuotaBar("Argon", "argon", acc) : null, h(Button, {
8521
8596
  variant: "dashed",
8522
8597
  style: {
8523
8598
  color: isExpanded ? "var(--dsw-alias-state-business-primary, #3b82f6)" : "var(--agy-text-secondary)",
@@ -9203,6 +9278,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
9203
9278
  pool,
9204
9279
  accounts,
9205
9280
  loadingAction,
9281
+ quotaRefreshing: status.quotaRefreshing ?? [],
9206
9282
  proxyInputs,
9207
9283
  setProxyInputs,
9208
9284
  editingProxyId,
package/dist/index.js CHANGED
@@ -566,6 +566,20 @@ function modelFamilyOf(modelId) {
566
566
  return "unknown";
567
567
  }
568
568
  /**
569
+ * True when the unattended quota probe must skip this account's summary call.
570
+ *
571
+ * Only a licence refusal suppresses: it is the one verdict the network cannot
572
+ * fix on its own, and re-probing it every hour is pure risk-control exposure.
573
+ * `auth` stays on the existing authRequired lifecycle, and network faults must
574
+ * be retried normally.
575
+ */
576
+ function quotaSummarySuppressed(account, now = Date.now()) {
577
+ const state = account.quotaUnavailable;
578
+ if (state === void 0) return false;
579
+ if (state.reason !== "no_license") return false;
580
+ return state.retryAfter > now;
581
+ }
582
+ /**
569
583
  * Determine whether a managed account has confirmed access to the Gemini 4 Argon family.
570
584
  *
571
585
  * An account qualifies for Argon when:
@@ -641,6 +655,7 @@ function shouldPollAccount(account) {
641
655
  if (!account.enabled) return false;
642
656
  if (account.authRequired) return false;
643
657
  const now = Date.now();
658
+ if (quotaSummarySuppressed(account, now)) return false;
644
659
  for (const cd of Object.values(account.cooldowns ?? {})) if (cd && cd.cooldownUntil > now) return false;
645
660
  return true;
646
661
  }
@@ -3062,6 +3077,23 @@ function longRouteTimeout(jobTimeoutMs) {
3062
3077
  /** How long a manual quota refresh keeps its dedupe entry when work never settles. */
3063
3078
  const QUOTA_REFRESH_DEDUP_MS = 9e4;
3064
3079
  /**
3080
+ * How long an endpoint that just failed keeps its "try me LAST" memory.
3081
+ *
3082
+ * Measured 2026-11-19: retrieveUserQuotaSummary on
3083
+ * daily-cloudcode-pa.googleapis.com resets the connection after 5-8s for every
3084
+ * account, while the sandbox endpoint answers. The endpoint list is walked from
3085
+ * the same end on every refresh, so without this memory each account pays that
3086
+ * timeout first — including the hourly background sweep. Short enough that a
3087
+ * recovered endpoint returns on its own.
3088
+ */
3089
+ const QUOTA_ENDPOINT_DOWN_MS = 6e5;
3090
+ /**
3091
+ * How long a "no valid licence" verdict (403 from the quota summary) keeps the
3092
+ * UNATTENDED probe away from that account. An explicit user refresh ignores it,
3093
+ * so a restored licence is picked up the moment the user asks for it.
3094
+ */
3095
+ const QUOTA_LICENSE_RETRY_MS = 216e5;
3096
+ /**
3065
3097
  * Grace the idle watchdog grants before killing a quiet child. libuv runs the
3066
3098
  * timers phase BEFORE the poll phase: when the DSH host's event loop is blocked
3067
3099
  * (a large parse, many parallel workers), an expired watchdog can fire before
@@ -3877,6 +3909,26 @@ var AccountPoolManager = class {
3877
3909
  this.persist();
3878
3910
  }
3879
3911
  /**
3912
+ * Record that the last refresh produced no authoritative snapshot.
3913
+ *
3914
+ * Kept on the account (not just in a log line) because the console has to be
3915
+ * able to say WHY a row is frozen: a failed summary keeps the previous
3916
+ * complete value by design, so the numbers alone can never show staleness.
3917
+ */
3918
+ noteQuotaUnavailable(id, state) {
3919
+ const acc = this.getAccount(id);
3920
+ if (!acc) return;
3921
+ acc.quotaUnavailable = state;
3922
+ this.persist();
3923
+ }
3924
+ /** Clear the marker once an authoritative snapshot arrives. */
3925
+ clearQuotaUnavailable(id) {
3926
+ const acc = this.getAccount(id);
3927
+ if (!acc?.quotaUnavailable) return;
3928
+ delete acc.quotaUnavailable;
3929
+ this.persist();
3930
+ }
3931
+ /**
3880
3932
  * Drop one family's quota row.
3881
3933
  *
3882
3934
  * Used when stored numbers provably cannot be attributed to this account —
@@ -39448,6 +39500,14 @@ function buildFamilyQuotas(params) {
39448
39500
  }
39449
39501
  //#endregion
39450
39502
  //#region src/features/quota/refresh.ts
39503
+ /** Map the HTTP verdict onto the account-level marker. */
39504
+ function unavailableReason(failure, hasModelData) {
39505
+ if (failure === null) return hasModelData ? "partial" : "unreachable";
39506
+ if (failure.kind === "no_license") return "no_license";
39507
+ if (failure.kind === "auth") return "auth";
39508
+ if (failure.kind === "network") return "unreachable";
39509
+ return hasModelData ? "partial" : "unreachable";
39510
+ }
39451
39511
  /**
39452
39512
  * Fetch and aggregate live quota statistics (both 5-hour limit and weekly limit)
39453
39513
  * for a single account across model families.
@@ -39517,13 +39577,35 @@ async function refreshAccountQuotaPipeline(deps, account, force = false) {
39517
39577
  }
39518
39578
  deps.pool.resetAccountIdentity(account.id, email);
39519
39579
  }
39520
- const [summary, discovered] = await Promise.all([deps.fetchQuotaSummary(accessToken, deps.proxyFor(account)), deps.fetchAvailableModels(accessToken, deps.proxyFor(account))]);
39580
+ const suppressSummary = !force && quotaSummarySuppressed(account, now);
39581
+ let summary = null;
39582
+ let discovered = null;
39583
+ if (suppressSummary) discovered = await deps.fetchAvailableModels(accessToken, deps.proxyFor(account));
39584
+ else {
39585
+ const [fetchedSummary, fetchedModels] = await Promise.all([deps.fetchQuotaSummary(accessToken, deps.proxyFor(account)), deps.fetchAvailableModels(accessToken, deps.proxyFor(account))]);
39586
+ summary = fetchedSummary;
39587
+ discovered = fetchedModels;
39588
+ }
39521
39589
  const userQuota = !Boolean(discovered?.models && Object.values(discovered.models).some((m) => m?.quotaInfo !== void 0)) ? await deps.fetchUserQuota(accessToken, deps.proxyFor(account)).catch(() => null) : null;
39522
39590
  if (!email) {
39523
39591
  const info = await deps.fetchUserInfo(accessToken, deps.proxyFor(account));
39524
39592
  if (info?.email) email = info.email;
39525
39593
  }
39526
39594
  const modelsCatalog = buildModelsCatalog(discovered, userQuota);
39595
+ if (!suppressSummary) {
39596
+ if ((summary?.groups?.length ?? 0) > 0 || (summary?.buckets?.length ?? 0) > 0) deps.pool.clearQuotaUnavailable(account.id);
39597
+ else {
39598
+ const failure = deps.summaryFailure?.() ?? null;
39599
+ const reason = unavailableReason(failure, Object.keys(modelsCatalog).length > 0);
39600
+ const previous = account.quotaUnavailable;
39601
+ deps.pool.noteQuotaUnavailable(account.id, {
39602
+ reason,
39603
+ since: previous?.reason === reason ? previous.since : now,
39604
+ retryAfter: now + QUOTA_LICENSE_RETRY_MS,
39605
+ ...failure?.detail === void 0 ? {} : { detail: failure.detail }
39606
+ });
39607
+ }
39608
+ }
39527
39609
  if (!summary && Object.keys(modelsCatalog).length === 0) return null;
39528
39610
  if (account.authRequired) deps.pool.clearAuthRequired(account.id);
39529
39611
  const { familyQuotas, summaryGroups } = buildFamilyQuotas({
@@ -39550,6 +39632,96 @@ async function refreshAccountQuotaPipeline(deps, account, force = false) {
39550
39632
  return familyQuotas;
39551
39633
  }
39552
39634
  //#endregion
39635
+ //#region src/features/quota/endpoint-health.ts
39636
+ function endpointHealthKey(op, endpoint) {
39637
+ return `${op}|${endpoint}`;
39638
+ }
39639
+ /** TTL-bounded failure memory; a recovered endpoint re-enters on its own. */
39640
+ var EndpointHealth = class {
39641
+ downMs;
39642
+ now;
39643
+ downUntil = /* @__PURE__ */ new Map();
39644
+ constructor(downMs = QUOTA_ENDPOINT_DOWN_MS, now = () => Date.now()) {
39645
+ this.downMs = downMs;
39646
+ this.now = now;
39647
+ }
39648
+ isDown(key) {
39649
+ const until = this.downUntil.get(key);
39650
+ if (until === void 0) return false;
39651
+ if (until <= this.now()) {
39652
+ this.downUntil.delete(key);
39653
+ return false;
39654
+ }
39655
+ return true;
39656
+ }
39657
+ noteFailure(key) {
39658
+ this.downUntil.set(key, this.now() + this.downMs);
39659
+ }
39660
+ noteSuccess(key) {
39661
+ this.downUntil.delete(key);
39662
+ }
39663
+ };
39664
+ /**
39665
+ * Re-order an endpoint list so recently-failed endpoints are tried LAST.
39666
+ *
39667
+ * Never returns an empty list and never drops an endpoint: when everything is
39668
+ * marked down the original order is used, because a total outage must still be
39669
+ * probed (skipping all of them would lock the pool out of a recovered network).
39670
+ */
39671
+ function orderEndpointsByHealth(endpoints, op, health) {
39672
+ if (health === void 0 || endpoints.length < 2) return [...endpoints];
39673
+ const healthy = [];
39674
+ const unhealthy = [];
39675
+ for (const endpoint of endpoints) if (health.isDown(endpointHealthKey(op, endpoint))) unhealthy.push(endpoint);
39676
+ else healthy.push(endpoint);
39677
+ return unhealthy.length === 0 || healthy.length === 0 ? [...endpoints] : [...healthy, ...unhealthy];
39678
+ }
39679
+ //#endregion
39680
+ //#region src/features/quota/sweep.ts
39681
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
39682
+ /** Run `items` with at most `limit` in flight, never starting two within `staggerMs`. */
39683
+ async function runStaggered(items, limit, run, staggerMs) {
39684
+ const queue = [...items];
39685
+ if (queue.length === 0) return;
39686
+ const width = Math.max(1, Math.min(Math.floor(limit), queue.length));
39687
+ let starting = 0;
39688
+ let lastStart = 0;
39689
+ const worker = async () => {
39690
+ for (;;) {
39691
+ const item = queue.shift();
39692
+ if (item === void 0) return;
39693
+ if (starting > 0) {
39694
+ const gap = staggerMs();
39695
+ if (gap > 0) {
39696
+ const wait = lastStart + gap - Date.now();
39697
+ if (wait > 0) await sleep(wait);
39698
+ }
39699
+ }
39700
+ starting++;
39701
+ lastStart = Date.now();
39702
+ await run(item);
39703
+ }
39704
+ };
39705
+ await Promise.all(Array.from({ length: width }, () => worker()));
39706
+ }
39707
+ /**
39708
+ * Sweep accounts grouped by egress.
39709
+ *
39710
+ * Errors never abort the sweep (one broken account must not silence the pool),
39711
+ * matching the previous `.catch(() => null)` semantics at the call site.
39712
+ */
39713
+ async function sweepAccountsByEgress(accounts, options) {
39714
+ const groups = /* @__PURE__ */ new Map();
39715
+ for (const account of accounts) {
39716
+ const egress = options.egressOf(account);
39717
+ const group = groups.get(egress);
39718
+ if (group === void 0) groups.set(egress, [account]);
39719
+ else group.push(account);
39720
+ }
39721
+ const concurrency = Math.max(1, Math.floor(options.concurrency ?? 1));
39722
+ await Promise.allSettled([...groups.values()].map((group) => runStaggered(group, concurrency, options.run, options.staggerMs)));
39723
+ }
39724
+ //#endregion
39553
39725
  //#region src/features/quota/http.ts
39554
39726
  /** Re-order endpoints so the preferred/working endpoint is tried first. */
39555
39727
  function orderedEndpoints(preferredIndex) {
@@ -39558,6 +39730,41 @@ function orderedEndpoints(preferredIndex) {
39558
39730
  for (let i = 0; i < total; i++) ordered.push(AGY_ENDPOINTS[(preferredIndex + i) % total]);
39559
39731
  return ordered;
39560
39732
  }
39733
+ /** The API's own status enum, which is safe to surface (no message body). */
39734
+ function apiErrorStatus(bodyText) {
39735
+ try {
39736
+ const parsed = JSON.parse(bodyText);
39737
+ return typeof parsed.error?.status === "string" ? parsed.error.status : void 0;
39738
+ } catch {
39739
+ return;
39740
+ }
39741
+ }
39742
+ function networkFailureCode(error) {
39743
+ const cause = error?.cause;
39744
+ return typeof cause?.code === "string" ? cause.code : void 0;
39745
+ }
39746
+ /**
39747
+ * Classify a refusal. A 403 that talks about a licence is the one case the
39748
+ * account can never retry its way out of, so it gets its own kind.
39749
+ */
39750
+ function classifySummaryRefusal(status, bodyText = "") {
39751
+ const detail = apiErrorStatus(bodyText);
39752
+ if (status === 401) return {
39753
+ kind: "auth",
39754
+ status,
39755
+ ...detail === void 0 ? {} : { detail }
39756
+ };
39757
+ if (status === 403 && /licen[cs]e/i.test(bodyText)) return {
39758
+ kind: "no_license",
39759
+ status,
39760
+ ...detail === void 0 ? {} : { detail }
39761
+ };
39762
+ return {
39763
+ kind: "http",
39764
+ status,
39765
+ ...detail === void 0 ? {} : { detail }
39766
+ };
39767
+ }
39561
39768
  /**
39562
39769
  * Query live user info (email) from Google OAuth userinfo endpoint.
39563
39770
  */
@@ -39581,13 +39788,16 @@ function requestQuotaSummaryEndpoint(endpoint, accessToken, proxyUrl, agyVersion
39581
39788
  * via v1internal:retrieveUserQuotaSummary.
39582
39789
  */
39583
39790
  async function fetchQuotaSummary(deps, accessToken, proxyUrl) {
39584
- const endpoints = orderedEndpoints(deps.getPreferredEndpointIndex());
39791
+ const endpoints = orderEndpointsByHealth(orderedEndpoints(deps.getPreferredEndpointIndex()), "summary", deps.endpointHealth);
39585
39792
  let partialSummary = null;
39793
+ let refusal = null;
39586
39794
  for (let i = 0; i < endpoints.length; i++) {
39587
39795
  const endpoint = endpoints[i];
39796
+ const healthKey = endpointHealthKey("summary", endpoint);
39588
39797
  try {
39589
39798
  const res = await deps.fetchSummaryEndpoint(endpoint, accessToken, proxyUrl, deps.accountScope);
39590
39799
  if (res.ok) {
39800
+ deps.endpointHealth?.noteSuccess(healthKey);
39591
39801
  const summary = await res.json();
39592
39802
  if (summary?.groups?.some((g) => {
39593
39803
  const name = (g.displayName || "").toLowerCase();
@@ -39603,16 +39813,33 @@ async function fetchQuotaSummary(deps, accessToken, proxyUrl) {
39603
39813
  existingNames.add(name);
39604
39814
  }
39605
39815
  }
39816
+ deps.onSummaryFailure?.(null);
39606
39817
  return partialSummary;
39607
39818
  }
39608
39819
  if (i > 0 && !partialSummary) deps.setPreferredEndpointIndex(AGY_ENDPOINTS.indexOf(endpoint));
39820
+ deps.onSummaryFailure?.(null);
39609
39821
  return summary;
39610
39822
  }
39611
39823
  if (!partialSummary && summary && Array.isArray(summary.groups) && summary.groups.length > 0) partialSummary = summary;
39612
39824
  }
39613
- if (res.status === 401 || res.status === 403) break;
39614
- } catch {}
39825
+ if (res.status === 401 || res.status === 403) {
39826
+ deps.endpointHealth?.noteSuccess(healthKey);
39827
+ refusal = classifySummaryRefusal(res.status, await res.text().catch(() => ""));
39828
+ break;
39829
+ }
39830
+ if (res.status >= 500) deps.endpointHealth?.noteFailure(healthKey);
39831
+ else deps.endpointHealth?.noteSuccess(healthKey);
39832
+ refusal = classifySummaryRefusal(res.status);
39833
+ } catch (error) {
39834
+ deps.endpointHealth?.noteFailure(healthKey);
39835
+ const code = networkFailureCode(error);
39836
+ refusal = {
39837
+ kind: "network",
39838
+ ...code === void 0 ? {} : { detail: code }
39839
+ };
39840
+ }
39615
39841
  }
39842
+ deps.onSummaryFailure?.(partialSummary === null ? refusal : null);
39616
39843
  return partialSummary;
39617
39844
  }
39618
39845
  /** POST /v1internal:retrieveUserQuota for one endpoint. */
@@ -39631,14 +39858,25 @@ function requestUserQuotaEndpoint(endpoint, accessToken, proxyUrl, agyVersion, a
39631
39858
  * Fetch per-model live user quota via v1internal:retrieveUserQuota.
39632
39859
  */
39633
39860
  async function fetchUserQuota(deps, accessToken, proxyUrl) {
39634
- const endpoints = orderedEndpoints(deps.getPreferredEndpointIndex());
39861
+ const endpoints = orderEndpointsByHealth(orderedEndpoints(deps.getPreferredEndpointIndex()), "userQuota", deps.endpointHealth);
39635
39862
  for (let i = 0; i < endpoints.length; i++) {
39636
39863
  const endpoint = endpoints[i];
39864
+ const healthKey = endpointHealthKey("userQuota", endpoint);
39637
39865
  try {
39638
39866
  const res = await deps.fetchUserQuotaEndpoint(endpoint, accessToken, proxyUrl, deps.accountScope);
39639
- if (res.ok) return await res.json();
39640
- if (res.status === 401 || res.status === 403) break;
39641
- } catch {}
39867
+ if (res.ok) {
39868
+ deps.endpointHealth?.noteSuccess(healthKey);
39869
+ return await res.json();
39870
+ }
39871
+ if (res.status === 401 || res.status === 403) {
39872
+ deps.endpointHealth?.noteSuccess(healthKey);
39873
+ break;
39874
+ }
39875
+ if (res.status >= 500) deps.endpointHealth?.noteFailure(healthKey);
39876
+ else deps.endpointHealth?.noteSuccess(healthKey);
39877
+ } catch {
39878
+ deps.endpointHealth?.noteFailure(healthKey);
39879
+ }
39642
39880
  }
39643
39881
  return null;
39644
39882
  }
@@ -39646,9 +39884,10 @@ async function fetchUserQuota(deps, accessToken, proxyUrl) {
39646
39884
  * Fetch available models and model-level quotas via v1internal:fetchAvailableModels.
39647
39885
  */
39648
39886
  async function fetchAvailableModels(deps, accessToken, proxyUrl) {
39649
- const endpoints = orderedEndpoints(deps.getPreferredEndpointIndex());
39887
+ const endpoints = orderEndpointsByHealth(orderedEndpoints(deps.getPreferredEndpointIndex()), "models", deps.endpointHealth);
39650
39888
  for (let i = 0; i < endpoints.length; i++) {
39651
39889
  const endpoint = endpoints[i];
39890
+ const healthKey = endpointHealthKey("models", endpoint);
39652
39891
  try {
39653
39892
  const res = await agyFetch(`${endpoint}/v1internal:fetchAvailableModels`, {
39654
39893
  method: "POST",
@@ -39660,11 +39899,19 @@ async function fetchAvailableModels(deps, accessToken, proxyUrl) {
39660
39899
  body: JSON.stringify({})
39661
39900
  }, proxyUrl, deps.accountScope);
39662
39901
  if (res.ok) {
39902
+ deps.endpointHealth?.noteSuccess(healthKey);
39663
39903
  if (AGY_ENDPOINTS.indexOf(endpoint) === 0) deps.setPreferredEndpointIndex(0);
39664
39904
  return await res.json();
39665
39905
  }
39666
- if (res.status === 401 || res.status === 403) break;
39667
- } catch {}
39906
+ if (res.status === 401 || res.status === 403) {
39907
+ deps.endpointHealth?.noteSuccess(healthKey);
39908
+ break;
39909
+ }
39910
+ if (res.status >= 500) deps.endpointHealth?.noteFailure(healthKey);
39911
+ else deps.endpointHealth?.noteSuccess(healthKey);
39912
+ } catch {
39913
+ deps.endpointHealth?.noteFailure(healthKey);
39914
+ }
39668
39915
  }
39669
39916
  return null;
39670
39917
  }
@@ -40007,6 +40254,15 @@ var QuotaService = class {
40007
40254
  /** accountId -> in-flight getValidAccessToken attempt (dedup). */
40008
40255
  tokenRefreshInFlight = /* @__PURE__ */ new Map();
40009
40256
  /**
40257
+ * Recent per-endpoint failures: a quota call that just reset is tried LAST
40258
+ * instead of first (see features/quota/endpoint-health.ts for the incident).
40259
+ */
40260
+ endpointHealth = new EndpointHealth();
40261
+ /** accountId -> refusal behind the last empty summary (drives quotaUnavailable). */
40262
+ summaryFailures = /* @__PURE__ */ new Map();
40263
+ /** accountIds with a refresh in flight, so the console can show real progress. */
40264
+ refreshingIds = /* @__PURE__ */ new Set();
40265
+ /**
40010
40266
  * @param globalProxy resolves the plugin-wide proxy URL; used when the
40011
40267
  * account has no dedicated proxyUrl. Injected so tests stay network-free.
40012
40268
  */
@@ -40020,7 +40276,13 @@ var QuotaService = class {
40020
40276
  httpDeps(accountScope) {
40021
40277
  return {
40022
40278
  agyVersion: () => this.agyVersion(),
40023
- ...accountScope ? { accountScope } : {},
40279
+ endpointHealth: this.endpointHealth,
40280
+ ...accountScope ? {
40281
+ accountScope,
40282
+ onSummaryFailure: (failure) => {
40283
+ this.summaryFailures.set(accountScope, failure);
40284
+ }
40285
+ } : {},
40024
40286
  getPreferredEndpointIndex: () => this.preferredEndpointIndex,
40025
40287
  setPreferredEndpointIndex: (index) => {
40026
40288
  this.preferredEndpointIndex = index;
@@ -40203,6 +40465,19 @@ var QuotaService = class {
40203
40465
  * public signature and every override point stay unchanged.
40204
40466
  */
40205
40467
  async refreshAccountQuota(account, force = false) {
40468
+ this.refreshingIds.add(account.id);
40469
+ this.summaryFailures.delete(account.id);
40470
+ try {
40471
+ return await this.runQuotaPipeline(account, force);
40472
+ } finally {
40473
+ this.refreshingIds.delete(account.id);
40474
+ }
40475
+ }
40476
+ /** Account ids with a quota refresh in flight (the console renders "同步中" from this). */
40477
+ refreshingAccounts() {
40478
+ return [...this.refreshingIds];
40479
+ }
40480
+ async runQuotaPipeline(account, force) {
40206
40481
  return refreshAccountQuotaPipeline({
40207
40482
  pool: this.pool,
40208
40483
  shouldUseCli: () => this.cliDeps.viaCli?.() !== false,
@@ -40217,7 +40492,8 @@ var QuotaService = class {
40217
40492
  detectEmailFromLogs: (home) => detectEmailFromAgyLogs(home),
40218
40493
  readPrimaryCredential: (baseDir) => readPrimaryCredential(baseDir),
40219
40494
  writePrimaryCredential: (cred, baseDir) => writePrimaryCredential(cred, baseDir),
40220
- credentialFingerprint: (raw) => credentialFingerprint(raw)
40495
+ credentialFingerprint: (raw) => credentialFingerprint(raw),
40496
+ summaryFailure: () => this.summaryFailures.get(account.id) ?? null
40221
40497
  }, account, force);
40222
40498
  }
40223
40499
  /**
@@ -40273,22 +40549,15 @@ var QuotaService = class {
40273
40549
  }
40274
40550
  return;
40275
40551
  }
40276
- const byEgress = /* @__PURE__ */ new Map();
40277
- for (const acc of accounts) {
40278
- const egress = this.proxyFor(acc) || "__direct__";
40279
- const group = byEgress.get(egress) ?? [];
40280
- group.push(acc);
40281
- byEgress.set(egress, group);
40282
- }
40283
- await Promise.allSettled([...byEgress.values()].map(async (group) => {
40284
- for (let i = 0; i < group.length; i++) {
40285
- await this.refreshAccountQuota(group[i], force).catch(() => null);
40286
- if (i < group.length - 1) {
40287
- const gap = nextForceGapMs();
40288
- if (gap > 0) await new Promise((resolve) => setTimeout(resolve, gap));
40289
- }
40290
- }
40291
- }));
40552
+ const concurrency = Math.max(1, Math.floor(this.cliDeps.forceConcurrency?.() ?? 2));
40553
+ await sweepAccountsByEgress(accounts, {
40554
+ egressOf: (acc) => this.proxyFor(acc) || "__direct__",
40555
+ run: async (acc) => {
40556
+ await this.refreshAccountQuota(acc, force).catch(() => null);
40557
+ },
40558
+ staggerMs: nextForceGapMs,
40559
+ concurrency
40560
+ });
40292
40561
  }
40293
40562
  };
40294
40563
  //#endregion
@@ -41348,7 +41617,7 @@ const queryParam = (req, key) => {
41348
41617
  //#endregion
41349
41618
  //#region src/transport/http/routes/status.ts
41350
41619
  function handleStatus(services, req, res) {
41351
- const { getConfig, bin, store, pool, catalog, auth, poolAuth, adapter, translation, lastRun } = services;
41620
+ const { getConfig, bin, store, pool, quota, catalog, auth, poolAuth, adapter, translation, lastRun } = services;
41352
41621
  const { version: versionCache, dormantReason } = services.status;
41353
41622
  runRoute(res, async () => {
41354
41623
  const cfg = getConfig();
@@ -41373,6 +41642,7 @@ function handleStatus(services, req, res) {
41373
41642
  auth: auth.status(),
41374
41643
  poolAuth: poolAuth.status(),
41375
41644
  pool: poolData,
41645
+ quotaRefreshing: typeof quota?.refreshingAccounts === "function" ? quota.refreshingAccounts() : [],
41376
41646
  catalog: {
41377
41647
  source: cat.source,
41378
41648
  count: cat.models.length,
@@ -41642,7 +41912,8 @@ function handlePoolRefreshQuota(services, req, res) {
41642
41912
  const body = await readBody(req);
41643
41913
  const id = typeof body.id === "string" ? body.id : "";
41644
41914
  const key = id || "__all__";
41645
- if (!quotaRefreshInFlight.has(key)) {
41915
+ const alreadyRunning = quotaRefreshInFlight.has(key);
41916
+ if (!alreadyRunning) {
41646
41917
  const work = (async () => {
41647
41918
  if (id) {
41648
41919
  const acc = pool.getAccount(id);
@@ -41664,6 +41935,7 @@ function handlePoolRefreshQuota(services, req, res) {
41664
41935
  sendJson(res, 200, {
41665
41936
  ok: true,
41666
41937
  pending: true,
41938
+ alreadyRunning,
41667
41939
  pool: pool.getPoolData()
41668
41940
  });
41669
41941
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agy-link",
3
- "version": "0.6.38",
3
+ "version": "0.6.39",
4
4
  "description": "Google Antigravity (agy CLI) models for DeepSeek Harness — stream Gemini/Claude/GPT-OSS subscriptions into DSH with thinking, tool activity, token usage and in-GUI Google OAuth login.",
5
5
  "type": "module",
6
6
  "license": "MIT",