dsh-agy-link 0.6.47 → 0.6.49

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,47 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.49 (2026-11-20)
4
+
5
+ ### English
6
+
7
+ - **Fix(accounts/UI): one source of truth for quota admission, so the console never disagrees with the scheduler.** A Pro account at `0%` on the 5-hour window (e.g. `god`) was rotated out by `isQuotaBenched()` while every client surface still painted it eligible: the dot stayed green, no badge appeared, "Set as in use" was offered, and `/agy pool` printed `Ready`. Clicking it reported success and then silently retreated, because `setActiveAccount()` never consulted eligibility.
8
+ - New `src/common/quota-bench.ts` holds the pure predicates (`is5hQuotaBenched`, `isWeeklyQuotaBenched`, `isQuotaBenched`, `accountHasActiveCooldown`, `accountHasQuotaBench`, `isAccountCriticalAuth`). `domain/accounts/selection.ts` re-exports them, so scheduling and rendering share one implementation instead of two drifting copies.
9
+ - `AccountsPanel` now derives the dot, the `rate-limited` badge, the banner (with its clear action) and the visibility of "Set as in use" from those predicates; a quota-benched account is no longer advertised as usable. `VALIDATION_REQUIRED` / `TOS_VIOLATION` render as `Verification required` / `Suspended (ToS)` with the verification link, taken from `quotaUnavailable` when `authError` carries no URL.
10
+ - `QuotaPanel` marks the 5-hour and weekly rows `· rate-limited` when they are what benched the account. `SessionStatus` includes quota benches in both the active-account and all-accounts-drained checks, so the header dot turns amber too.
11
+ - `setActiveAccount()` validates with `isAccountEligible()`, so a rejected pin returns `false` up front instead of a false success. `/agy pool` reports `Quota-limited (auto-rotated until reset)` instead of `Ready`.
12
+ - **Fix(quota): the "data frozen at" stamp names the oldest frozen window.** `renderQuotaUnavailableNote` used `Math.max` across families, so a partial refresh that only touched `argon` dated the whole row to *now* (14:05) while the failing `google` snapshot was hours old (11:27). It now takes the oldest non-zero `updatedAt`, which is what "the data is stuck at" actually means.
13
+ - **Fix(quota): verification and ToS refusals quarantine the account immediately.** A `403` carrying `VALIDATION_REQUIRED` or `TOS_VIOLATION` recorded `quotaUnavailable` but left `authRequired` unset, so selection kept routing to an account Google had just refused. Both reasons now stamp `authRequired` (with the verification URL) and clear again once a later summary succeeds.
14
+ - Four locales updated (en/es/ptBR/zh). Regression suite added: `test/status-consistency.test.ts` (5 cases covering the benched-card render, the header dot, `setActiveAccount` agreement, the frozen-stamp choice, and the verification heals-on-success path).
15
+
16
+ ### 中文
17
+
18
+ - **修复(账号/UI):配额可用性判定收敛为单一真源,控制台不再与调度器打架。** 一个 5 小时额度 `0%` 的 Pro 账号(如 `god`)已被 `isQuotaBenched()` 轮转掉,但所有前端面仍把它画成可用:圆点还是绿的、没有任何标签、「设为当前使用」照常出现、`/agy pool` 也打印 `Ready`。点下去还会提示成功然后悄悄退回,因为 `setActiveAccount()` 从未校验可用性。
19
+ - 新增 `src/common/quota-bench.ts` 承载纯谓词(`is5hQuotaBenched`、`isWeeklyQuotaBenched`、`isQuotaBenched`、`accountHasActiveCooldown`、`accountHasQuotaBench`、`isAccountCriticalAuth`)。`domain/accounts/selection.ts` 复用它并再导出,调度与渲染共用一份实现,而不是两份逐渐分叉的副本。
20
+ - `AccountsPanel` 的圆点、`限流中` 标签、提示条(含清除动作)以及「设为当前使用」的可见性,全部由这些谓词推导;被配额限流的账号不再被宣称为可用。`VALIDATION_REQUIRED` / `TOS_VIOLATION` 显示为 `需安全验证` / `已封禁 (ToS)` 并附验证链接——当 `authError` 里没有 URL 时从 `quotaUnavailable` 取。
21
+ - `QuotaPanel` 在 5 小时或周额度正是限流原因时,于对应行标注 `· 限流中`。`SessionStatus` 把配额限流也纳入「当前账号」与「全部账号耗尽」的判定,顶部圆点同步变琥珀色。
22
+ - `setActiveAccount()` 改用 `isAccountEligible()` 校验,被拒绝的固定会当场返回 `false`,而不是假成功。`/agy pool` 输出 `Quota-limited (auto-rotated until reset)`,不再是 `Ready`。
23
+ - **修复(额度):冻结时间戳改取最早冻结的那个窗口。** `renderQuotaUnavailableNote` 原先取各族的 `Math.max`,于是一次只刷新了 `argon` 的部分刷新会把整行标成「数据停留在」当下(14:05),而真正失败的 `google` 快照已经是几小时前(11:27)。现改取最早的非零 `updatedAt`——这才是「数据卡在什么时候」的本意。
24
+ - **修复(额度):需验证与被封禁会被立即隔离。** 携带 `VALIDATION_REQUIRED` 或 `TOS_VIOLATION` 的 `403` 只记录了 `quotaUnavailable`,却没设 `authRequired`,于是选号仍在往 Google 刚拒绝过的账号上派活。现在这两种原因都会打上 `authRequired`(含验证链接),并在后续 summary 成功时自动解除。
25
+ - 四语言词条同步(en/es/ptBR/zh)。新增回归套件 `test/status-consistency.test.ts`(5 条用例,覆盖限流卡片渲染、顶部圆点、`setActiveAccount` 一致性、冻结时间戳选取,以及验证通过后自动恢复)。
26
+
27
+ ## 0.6.48 (2026-11-20)
28
+
29
+ ### English
30
+
31
+ - **Fix(idle-grace): three linked causes of `INVALID_OUTPUT: agy stream ended without a result event` (merges PR #147).** Follow-up to #144/#146, from a report that the failure could still replay three times within milliseconds on continuation retries:
32
+ - **`waiting up to <duration> for N background task(s)`** is a second wording agy emits (e.g. `waiting up to 240m0s for 1 background task(s)`). `backgroundTasksFrom()` only matched `waiting for N`, so this variant returned `null` and the reaper was still armed for a positive count. The regex now accepts the optional `up to <duration>` segment.
33
+ - **An empty error result no longer hides the recoverable reply.** On SIGTERM agy can flush `{ ok: false, response: '' }`; `hasResult` counted that envelope, so the `idleGraceTerminated` recovery was skipped while `EventMapper` ignored the empty result without finishing. The guard is now `hasConsumableResult` (ok, or non-empty response), so a usable reply or the explicit notice is always appended.
34
+ - **A settled recording with no finishable event stops replaying.** When a continuation had no consumable result and no cuttable tool step after its resume point, every DSH retry re-drove the same dead recording (~20 ms each) until retries were exhausted. `hasFinishableEventFrom()` makes the adapter forget such a recording and spawn a fresh attempt instead. **This is the part that goes beyond what shipped in v0.6.47**, which only checked the result dimension — a recording cut mid-tool-step now resumes instead of re-running the work.
35
+ - Note: v0.6.47 independently landed the first two items and the `recording` helpers; this merge keeps that structure and takes the wider adapter predicate plus PR #147's regression suite (4 new tests, 347 lines).
36
+
37
+ ### 中文
38
+
39
+ - **修复(idle-grace):`INVALID_OUTPUT: agy stream ended without a result event` 的三条关联成因(合并 PR #147)。** 是 #144/#146 的后续,源于「该失败在续接重试时仍会在毫秒级重复三次」的报告:
40
+ - **`waiting up to <duration> for N background task(s)`** 是 agy 的第二种措辞(例如 `waiting up to 240m0s for 1 background task(s)`)。`backgroundTasksFrom()` 只匹配 `waiting for N`,该变体返回 `null`,于是正数计数下收割器仍会被武装。正则现在接受可选的 `up to <duration>` 片段。
41
+ - **空的错误 result 不再掩盖可恢复的回复。** SIGTERM 时 agy 可能刷出 `{ ok: false, response: '' }`;`hasResult` 把这个信封算作结果,导致 `idleGraceTerminated` 的恢复逻辑被跳过,而 `EventMapper` 又忽略空结果、不置 finished。判据改为 `hasConsumableResult`(ok 或非空 response),因此总会补上可用回复或明确提示。
42
+ - **没有可完成事件的 settled recording 不再被重放。** 续接点在可消费 result 与可切割工具步骤之后都没有事件时,DSH 每次重试都会重驱同一份死 recording(每次约 20ms)直到重试耗尽。`hasFinishableEventFrom()` 让适配器遗忘这种 recording 并新起一次尝试。**这部分超出 v0.6.47 已发布的内容**——它只检查 result 维度;在工具步骤中途被切断的 recording 现在会续接,而不是重跑已有工作。
43
+ - 说明:v0.6.47 已独立落地前两项与 `recording` 辅助方法;本次合并保留其结构,吸收更宽的适配器判据与 PR #147 的回归测试(4 条新用例,347 行)。
44
+
3
45
  ## 0.6.47 (2026-11-20)
4
46
 
5
47
  ### English
@@ -2497,6 +2497,27 @@ var RunRecording = class {
2497
2497
  get hasResult() {
2498
2498
  return this.events.some((e) => e.kind === "result");
2499
2499
  }
2500
+ /** Whether a result event that EventMapper will finish on (ok, or non-empty error response) was recorded. */
2501
+ get hasConsumableResult() {
2502
+ const r = this.getResultEvent();
2503
+ return r !== null && (r.ok || r.response !== "");
2504
+ }
2505
+ /**
2506
+ * Whether any recorded event at or after `from` can finish a span cleanly
2507
+ * (a consumable result envelope, or a completed tool step when `cutOnTool`
2508
+ * is enabled). A settled recording with `failureInfo === null` and no such
2509
+ * event would otherwise replay `INVALID_OUTPUT: agy stream ended without a
2510
+ * result event` on every continuation retry.
2511
+ */
2512
+ hasFinishableEventFrom(from, cutOnTool = true) {
2513
+ for (let i = Math.max(0, from); i < this.events.length; i++) {
2514
+ const ev = this.events[i];
2515
+ if (ev === void 0) continue;
2516
+ if (ev.kind === "result" && (ev.ok || ev.response !== "")) return true;
2517
+ if (cutOnTool && ev.kind === "step" && ev.stepKind === "tool" && ev.tool !== void 0 && (ev.state === "DONE" || ev.state === "ERROR" || ev.state === "RUNNING" || ev.state === void 0 && (ev.tool.output !== void 0 || ev.tool.error !== void 0))) return true;
2518
+ }
2519
+ return false;
2520
+ }
2500
2521
  /** The last result envelope's finish-relevant projection, when one arrived. */
2501
2522
  getResultEvent() {
2502
2523
  for (let i = this.events.length - 1; i >= 0; i--) {
@@ -5333,7 +5354,7 @@ function preemptAgyAutoUpdate(env = process.env, now = Date.now()) {
5333
5354
  * boundary cut the line), which keeps the conservative "arm the grace" path.
5334
5355
  */
5335
5356
  function backgroundTasksFrom(text) {
5336
- const match = /root agent idle;\s*waiting\s+for\s+(\d+)\s+background/i.exec(text);
5357
+ const match = /root agent idle;\s*waiting(?:\s+up\s+to\s+\S+)?\s+for\s+(\d+)\s+background/i.exec(text);
5337
5358
  if (match === null) return null;
5338
5359
  const count = Number(match[1]);
5339
5360
  return Number.isSafeInteger(count) && count >= 0 ? count : null;
@@ -7558,6 +7579,51 @@ function defaultPoolDir(home) {
7558
7579
  return join(effectiveHome, ".dsh", "agy-accounts");
7559
7580
  }
7560
7581
  //#endregion
7582
+ //#region src/common/quota-bench.ts
7583
+ /** Proactive rotation thresholds: bench accounts at or below these remaining fractions until reset. */
7584
+ const LOW_QUOTA_5H = .1;
7585
+ const LOW_QUOTA_WEEKLY = .05;
7586
+ function isWindowBenched(fraction, resetTime, threshold, now) {
7587
+ if (typeof fraction !== "number" || fraction > threshold) return false;
7588
+ if (!resetTime) return true;
7589
+ const resetMs = Date.parse(resetTime);
7590
+ return Number.isNaN(resetMs) || resetMs > now;
7591
+ }
7592
+ /** True when a family's 5-hour quota window is at or below the proactive bench threshold and not yet reset. */
7593
+ function is5hQuotaBenched(quota, clearedAt, now) {
7594
+ if (!quota) return false;
7595
+ if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) return false;
7596
+ return isWindowBenched(quota.remainingFraction, quota.resetTime, LOW_QUOTA_5H, now);
7597
+ }
7598
+ /** True when a family's weekly quota window is at or below the proactive bench threshold and not yet reset. */
7599
+ function isWeeklyQuotaBenched(quota, clearedAt, now) {
7600
+ if (!quota) return false;
7601
+ if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) return false;
7602
+ return isWindowBenched(quota.weeklyFraction, quota.weeklyResetTime, LOW_QUOTA_WEEKLY, now);
7603
+ }
7604
+ /**
7605
+ * True when a family's cached quota snapshot benches the account.
7606
+ *
7607
+ * A user-visible `clearCooldown(..., includeQuotaBench = true)` records the
7608
+ * `updatedAt` of the snapshot it overrode; the gate stays off only while the
7609
+ * cached row is no newer than that stamp, so a fresh poll always re-arms it.
7610
+ */
7611
+ function isQuotaBenched(acc, family, now) {
7612
+ const quota = acc.quotas?.[family] ?? (family === "argon" ? acc.quotas?.google : void 0);
7613
+ if (!quota) return false;
7614
+ const clearedAt = acc.quotaGateClearedAt?.[family];
7615
+ return is5hQuotaBenched(quota, clearedAt, now) || isWeeklyQuotaBenched(quota, clearedAt, now);
7616
+ }
7617
+ /**
7618
+ * True when the account cannot operate due to auth expiration, web verification
7619
+ * (`VALIDATION_REQUIRED`), or ToS suspension (`TOS_VIOLATION`).
7620
+ */
7621
+ function isAccountCriticalAuth(acc) {
7622
+ if (acc.authRequired === true) return true;
7623
+ const reason = acc.quotaUnavailable?.reason;
7624
+ return reason === "validation_required" || reason === "tos_violation";
7625
+ }
7626
+ //#endregion
7561
7627
  //#region src/common/quota-pacing.ts
7562
7628
  const FIVE_HOUR_WINDOW_MS = 18e6;
7563
7629
  const WEEKLY_WINDOW_MS = 6048e5;
@@ -7617,32 +7683,8 @@ function computeQuotaPacing(remainingFraction, resetTimeIso, windowMs, now = Dat
7617
7683
  burnMultiplier
7618
7684
  };
7619
7685
  }
7620
- /**
7621
- * True when a family's cached quota snapshot benches the account.
7622
- *
7623
- * A user-visible `clearCooldown(..., includeQuotaBench = true)` records the
7624
- * `updatedAt` of the snapshot it overrode; the gate stays off only while the
7625
- * cached row is no newer than that stamp, so a fresh poll always re-arms it.
7626
- */
7627
- function isQuotaBenched(acc, family, now) {
7628
- const quota = acc.quotas?.[family] ?? (family === "argon" ? acc.quotas?.google : void 0);
7629
- if (!quota) return false;
7630
- const clearedAt = acc.quotaGateClearedAt?.[family];
7631
- if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) return false;
7632
- if (typeof quota.remainingFraction === "number" && quota.remainingFraction <= .1) {
7633
- if (quota.resetTime) {
7634
- const resetMs = Date.parse(quota.resetTime);
7635
- if (Number.isNaN(resetMs) || resetMs > now) return true;
7636
- } else return true;
7637
- }
7638
- if (typeof quota.weeklyFraction === "number" && quota.weeklyFraction <= .05) {
7639
- if (quota.weeklyResetTime) {
7640
- const resetMs = Date.parse(quota.weeklyResetTime);
7641
- if (Number.isNaN(resetMs) || resetMs > now) return true;
7642
- } else return true;
7643
- }
7644
- return false;
7645
- }
7686
+ //#endregion
7687
+ //#region src/domain/accounts/selection.ts
7646
7688
  /**
7647
7689
  * Why this account cannot serve `family` right now, or null when it can.
7648
7690
  *
@@ -7652,7 +7694,7 @@ function isQuotaBenched(acc, family, now) {
7652
7694
  */
7653
7695
  function explainIneligibility(acc, family, now, pool, model) {
7654
7696
  if (!acc.enabled) return "disabled";
7655
- if (acc.authRequired) return "auth";
7697
+ if (isAccountCriticalAuth(acc)) return "auth";
7656
7698
  if (family === "argon" && !accountHasArgon(acc, pool)) return "unsupported";
7657
7699
  if (model && pool?.isModelSupported && !pool.isModelSupported(acc, model)) return "model-unsupported";
7658
7700
  const cd = acc.cooldowns?.[family];
@@ -7909,7 +7951,7 @@ var PoolAdmin = class {
7909
7951
  setActiveAccount(id, family = "google") {
7910
7952
  const data = this.deps.getData();
7911
7953
  const acc = this.account(id);
7912
- if (!acc || !acc.enabled || acc.authRequired) return false;
7954
+ if (!acc || !isAccountEligible(acc, family, Date.now(), this.deps.pool)) return false;
7913
7955
  if (!data.activeAccountIds) data.activeAccountIds = {};
7914
7956
  data.activeAccountIds[family] = id;
7915
7957
  data.lastActiveAccountId = id;
@@ -34825,8 +34867,7 @@ async function handleAttemptOutcome(deps, input, ctx) {
34825
34867
  deps.clearInFlightPrompt(sessionKey, spawn.prompt);
34826
34868
  recorder.drain(input.agyOnEvent);
34827
34869
  const conversationId = recorder.conversationId();
34828
- const existingRes = rec.getResultEvent();
34829
- if (!(existingRes !== null && (existingRes.ok || existingRes.response !== "")) && outcome.idleGraceTerminated) {
34870
+ if (!rec.hasConsumableResult && outcome.idleGraceTerminated) {
34830
34871
  const recovered = conversationId === null ? "" : recoverFinalReply(conversationId, rec.accountHome);
34831
34872
  const synthResult = {
34832
34873
  kind: "result",
@@ -34887,7 +34928,7 @@ async function handleAttemptOutcome(deps, input, ctx) {
34887
34928
  * queue notices; the outcome closure runs detached exactly as before.
34888
34929
  */
34889
34930
  async function* runAgyAttempt(deps, input) {
34890
- const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId, !input.isAux);
34931
+ const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId);
34891
34932
  const spawn = buildSpawnArgs(input, recorder.printTimeoutMinutes, deps.log);
34892
34933
  const slot = yield* dispatchCredentialSlot(deps, {
34893
34934
  ...input,
@@ -35132,14 +35173,14 @@ var AgyAdapter = class extends LlmAdapter {
35132
35173
  if (continuation !== null) {
35133
35174
  const rec = this.deps.runs.get(continuation.runId);
35134
35175
  const deadFailure = rec !== void 0 && rec.isSettled ? rec.failureInfo : null;
35135
- const deadMissingResult = rec !== void 0 && rec.isSettled && deadFailure === null && !rec.hasConsumableResultFrom(continuation.eventIndex + 1);
35136
- if (rec !== void 0 && !deadMissingResult && !(deadFailure !== null && this.claimFailover(sessionKey, deadFailure.code))) {
35176
+ const deadNoResult = rec !== void 0 && rec.isSettled && deadFailure === null && !rec.hasFinishableEventFrom(continuation.eventIndex + 1, hasToolSupport);
35177
+ if (rec !== void 0 && !deadNoResult && !(deadFailure !== null && this.claimFailover(sessionKey, deadFailure.code))) {
35137
35178
  yield* driveSpan(this.deps, rec, continuation.eventIndex + 1, hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal);
35138
35179
  return;
35139
35180
  }
35140
35181
  if (rec !== void 0) {
35141
35182
  this.deps.runs.forget(continuation.runId);
35142
- this.warnOnce("dead-continuation:" + continuation.runId, deadMissingResult ? "agy run " + continuation.runId + " settled without a consumable result — retrying this step instead of replaying an empty stream" : "agy run " + continuation.runId + " settled in " + (deadFailure?.code ?? "") + " — retrying this step instead of replaying it" + (deadFailure?.code === Err.NETWORK && this.sharesSingleEgress() ? " on the same account (shared egress)" : " on another account"));
35183
+ this.warnOnce("dead-continuation:" + continuation.runId, deadNoResult ? "agy run " + continuation.runId + " settled without a consumable result — retrying this step instead of replaying it" : "agy run " + continuation.runId + " settled in " + (deadFailure?.code ?? "") + " — retrying this step instead of replaying it" + (deadFailure?.code === Err.NETWORK && this.sharesSingleEgress() ? " on the same account (shared egress)" : " on another account"));
35143
35184
  } else this.warnOnce("stale-continuation:" + continuation.runId, "agy run " + continuation.runId + " is no longer available in memory (server restarted?) — falling back to fresh turn prompt assembly");
35144
35185
  }
35145
35186
  const catalog = this.deps.catalog.get();
@@ -35324,7 +35365,7 @@ var AgyAdapter = class extends LlmAdapter {
35324
35365
  signal: options.signal,
35325
35366
  agyOnEvent: options.agyOnEvent
35326
35367
  });
35327
- yield* driveSpan(this.deps, rec, 0, policy.mirrorTools && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice, isAux && !isImage);
35368
+ yield* driveSpan(this.deps, rec, 0, policy.mirrorTools && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice);
35328
35369
  }
35329
35370
  };
35330
35371
  //#endregion
package/dist/client.js CHANGED
@@ -37,12 +37,13 @@ window.__ModuleLoader__.load({
37
37
  "status.loading": "正在加载 Antigravity 状态...",
38
38
  "status.authRequired": "需重新登录",
39
39
  "status.cooldown": "冷却中",
40
+ "status.quotaLimited": "限流中",
40
41
  "status.tosBanned": "已封禁 (ToS)",
41
42
  "status.validationRequired": "需安全验证",
42
43
  "account.setActive": "设为当前使用",
43
44
  "account.settingActive": "切换中",
44
45
  "account.activeSet": "已切换当前使用账号",
45
- "account.activeSetFailed": "该账号当前不可用(冷却或需重新登录)",
46
+ "account.activeSetFailed": "该账号当前不可用(冷却、限流或需重新登录)",
46
47
  "account.reauth": "重新登录",
47
48
  "account.reauthing": "重登中",
48
49
  "account.reauthTitle": "原位重新登录此账号(保留别名、代理与优先级)",
@@ -70,6 +71,7 @@ window.__ModuleLoader__.load({
70
71
  "account.cooldown": "部分模型限流中,已自动切换账号",
71
72
  "account.clearCooldown": "清除冷却",
72
73
  "account.localCooldown": " · 本地冷却中",
74
+ "account.quotaLimitedNote": " · 限流中",
73
75
  "account.removed": "已移除账号:{alias}",
74
76
  "quota.fiveHour": "5 小时额度",
75
77
  "quota.weekly": "周额度",
@@ -269,12 +271,13 @@ window.__ModuleLoader__.load({
269
271
  "status.loading": "Loading Antigravity status...",
270
272
  "status.authRequired": "Sign in again required",
271
273
  "status.cooldown": "Cooldown",
274
+ "status.quotaLimited": "Rate limited",
272
275
  "status.tosBanned": "Suspended (ToS)",
273
276
  "status.validationRequired": "Verification required",
274
277
  "account.setActive": "Set as in use",
275
278
  "account.settingActive": "Switching...",
276
279
  "account.activeSet": "Active account switched",
277
- "account.activeSetFailed": "Account not currently eligible (cooldown or auth required)",
280
+ "account.activeSetFailed": "Account not currently eligible (cooldown, quota-limited, or auth required)",
278
281
  "account.reauth": "Sign in again",
279
282
  "account.reauthing": "Signing in...",
280
283
  "account.reauthTitle": "Re-authenticate this account in place (keeps alias, proxy and priority)",
@@ -302,6 +305,7 @@ window.__ModuleLoader__.load({
302
305
  "account.cooldown": "Some models are rate-limited; the account was switched automatically",
303
306
  "account.clearCooldown": "Clear cooldown",
304
307
  "account.localCooldown": " · local cooldown active",
308
+ "account.quotaLimitedNote": " · rate-limited",
305
309
  "account.removed": "Account removed: {alias}",
306
310
  "quota.fiveHour": "5-hour quota",
307
311
  "quota.weekly": "Weekly quota",
@@ -501,12 +505,13 @@ window.__ModuleLoader__.load({
501
505
  "status.loading": "Carregando o status do Antigravity...",
502
506
  "status.authRequired": "É necessário entrar novamente",
503
507
  "status.cooldown": "Em espera",
508
+ "status.quotaLimited": "Limitado",
504
509
  "status.tosBanned": "Suspensa (ToS)",
505
510
  "status.validationRequired": "Verificação necessária",
506
511
  "account.setActive": "Definir como em uso",
507
512
  "account.settingActive": "Alternando...",
508
513
  "account.activeSet": "Conta em uso alterada",
509
- "account.activeSetFailed": "Conta não elegível no momento (cooldown ou login necessário)",
514
+ "account.activeSetFailed": "Conta não elegível no momento (cooldown, cota limitada ou login necessário)",
510
515
  "account.reauth": "Entrar novamente",
511
516
  "account.reauthing": "Entrando...",
512
517
  "account.reauthTitle": "Reautenticar esta conta no lugar (mantém apelido, proxy e prioridade)",
@@ -534,6 +539,7 @@ window.__ModuleLoader__.load({
534
539
  "account.cooldown": "Alguns modelos estão limitados; a conta foi alternada automaticamente",
535
540
  "account.clearCooldown": "Limpar espera",
536
541
  "account.localCooldown": " · espera local ativa",
542
+ "account.quotaLimitedNote": " · limitado",
537
543
  "account.removed": "Conta removida: {alias}",
538
544
  "quota.fiveHour": "Cota de 5 horas",
539
545
  "quota.weekly": "Cota semanal",
@@ -733,12 +739,13 @@ window.__ModuleLoader__.load({
733
739
  "status.loading": "Cargando el estado de Antigravity...",
734
740
  "status.authRequired": "Debe iniciar sesión de nuevo",
735
741
  "status.cooldown": "En espera",
742
+ "status.quotaLimited": "Limitado",
736
743
  "status.tosBanned": "Suspendida (ToS)",
737
744
  "status.validationRequired": "Verificación requerida",
738
745
  "account.setActive": "Establecer como en uso",
739
746
  "account.settingActive": "Cambiando...",
740
747
  "account.activeSet": "Cuenta en uso cambiada",
741
- "account.activeSetFailed": "Cuenta no elegible ahora (enfriamiento o requiere login)",
748
+ "account.activeSetFailed": "Cuenta no elegible ahora (enfriamiento, límite de cuota o requiere login)",
742
749
  "account.reauth": "Iniciar sesión de nuevo",
743
750
  "account.reauthing": "Iniciando...",
744
751
  "account.reauthTitle": "Reautenticar esta cuenta en su sitio (conserva alias, proxy y prioridad)",
@@ -766,6 +773,7 @@ window.__ModuleLoader__.load({
766
773
  "account.cooldown": "Algunos modelos tienen límite de uso; la cuenta se cambió automáticamente",
767
774
  "account.clearCooldown": "Borrar espera",
768
775
  "account.localCooldown": " · espera local activa",
776
+ "account.quotaLimitedNote": " · limitado",
769
777
  "account.removed": "Cuenta eliminada: {alias}",
770
778
  "quota.fiveHour": "Cuota de 5 horas",
771
779
  "quota.weekly": "Cuota semanal",
@@ -8348,7 +8356,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8348
8356
  openai: "OpenAI",
8349
8357
  unknown: "Other"
8350
8358
  };
8351
- const QUOTA_FAMILIES = [
8359
+ const QUOTA_FAMILIES$1 = [
8352
8360
  "google",
8353
8361
  "argon",
8354
8362
  "anthropic",
@@ -8393,7 +8401,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8393
8401
  }
8394
8402
  function collectAccountQuotaModels(acc) {
8395
8403
  const out = [];
8396
- for (const fam of QUOTA_FAMILIES) {
8404
+ for (const fam of QUOTA_FAMILIES$1) {
8397
8405
  const models = acc.quotas?.[fam]?.models;
8398
8406
  if (!Array.isArray(models)) continue;
8399
8407
  for (const model of models) if (model && typeof model.modelId === "string" && model.modelId.trim() !== "") out.push({
@@ -8512,6 +8520,70 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8512
8520
  return projectFromQuotaFallback(acc);
8513
8521
  }
8514
8522
  //#endregion
8523
+ //#region src/common/quota-bench.ts
8524
+ /** Proactive rotation thresholds: bench accounts at or below these remaining fractions until reset. */
8525
+ const LOW_QUOTA_5H = .1;
8526
+ const LOW_QUOTA_WEEKLY = .05;
8527
+ /** Ordered quota families tracked on an account card. */
8528
+ const QUOTA_FAMILIES = [
8529
+ "google",
8530
+ "argon",
8531
+ "anthropic",
8532
+ "openai"
8533
+ ];
8534
+ function isWindowBenched(fraction, resetTime, threshold, now) {
8535
+ if (typeof fraction !== "number" || fraction > threshold) return false;
8536
+ if (!resetTime) return true;
8537
+ const resetMs = Date.parse(resetTime);
8538
+ return Number.isNaN(resetMs) || resetMs > now;
8539
+ }
8540
+ /** True when a family's 5-hour quota window is at or below the proactive bench threshold and not yet reset. */
8541
+ function is5hQuotaBenched(quota, clearedAt, now) {
8542
+ if (!quota) return false;
8543
+ if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) return false;
8544
+ return isWindowBenched(quota.remainingFraction, quota.resetTime, LOW_QUOTA_5H, now);
8545
+ }
8546
+ /** True when a family's weekly quota window is at or below the proactive bench threshold and not yet reset. */
8547
+ function isWeeklyQuotaBenched(quota, clearedAt, now) {
8548
+ if (!quota) return false;
8549
+ if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) return false;
8550
+ return isWindowBenched(quota.weeklyFraction, quota.weeklyResetTime, LOW_QUOTA_WEEKLY, now);
8551
+ }
8552
+ /**
8553
+ * True when a family's cached quota snapshot benches the account.
8554
+ *
8555
+ * A user-visible `clearCooldown(..., includeQuotaBench = true)` records the
8556
+ * `updatedAt` of the snapshot it overrode; the gate stays off only while the
8557
+ * cached row is no newer than that stamp, so a fresh poll always re-arms it.
8558
+ */
8559
+ function isQuotaBenched(acc, family, now) {
8560
+ const quota = acc.quotas?.[family] ?? (family === "argon" ? acc.quotas?.google : void 0);
8561
+ if (!quota) return false;
8562
+ const clearedAt = acc.quotaGateClearedAt?.[family];
8563
+ return is5hQuotaBenched(quota, clearedAt, now) || isWeeklyQuotaBenched(quota, clearedAt, now);
8564
+ }
8565
+ /** True when any family on the account has an active local 429 cooldown timer. */
8566
+ function accountHasActiveCooldown(acc, now) {
8567
+ return Object.values(acc.cooldowns ?? {}).some((cd) => Boolean(cd && cd.cooldownUntil > now));
8568
+ }
8569
+ /**
8570
+ * True when any family reported on the account is benched by its quota snapshot.
8571
+ * Skips the synthesized `argon -> google` fallback when the account has no dedicated
8572
+ * `quotas.argon` row, since `google` itself already reflects that shared bucket.
8573
+ */
8574
+ function accountHasQuotaBench(acc, now) {
8575
+ return QUOTA_FAMILIES.some((fam) => (fam !== "argon" || acc.quotas?.argon !== void 0) && isQuotaBenched(acc, fam, now));
8576
+ }
8577
+ /**
8578
+ * True when the account cannot operate due to auth expiration, web verification
8579
+ * (`VALIDATION_REQUIRED`), or ToS suspension (`TOS_VIOLATION`).
8580
+ */
8581
+ function isAccountCriticalAuth(acc) {
8582
+ if (acc.authRequired === true) return true;
8583
+ const reason = acc.quotaUnavailable?.reason;
8584
+ return reason === "validation_required" || reason === "tos_violation";
8585
+ }
8586
+ //#endregion
8515
8587
  //#region src/common/quota-pacing.ts
8516
8588
  /**
8517
8589
  * Compare remaining quota fraction against remaining reset window fraction.
@@ -8734,20 +8806,25 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8734
8806
  function renderFamilyQuotaBar(t, label, familyKey, acc, isRefreshing = false) {
8735
8807
  const info = acc.quotas[familyKey];
8736
8808
  const cd = acc.cooldowns[familyKey];
8737
- const inCooldown = cd && cd.cooldownUntil > Date.now();
8809
+ const now = Date.now();
8810
+ const inCooldown = Boolean(cd && cd.cooldownUntil > now);
8811
+ const clearedAt = acc.quotaGateClearedAt?.[familyKey];
8812
+ const benched5h = !inCooldown && is5hQuotaBenched(info, clearedAt, now);
8813
+ const benchedWeekly = !inCooldown && isWeeklyQuotaBenched(info, clearedAt, now);
8738
8814
  const has5h = typeof info?.remainingFraction === "number" && Number.isFinite(info.remainingFraction);
8739
8815
  const pct5h = has5h ? Math.max(0, Math.min(100, Math.round(info.remainingFraction * 100))) : -1;
8740
- const cdNote = inCooldown ? t("account.localCooldown") : "";
8816
+ const cdNote5h = inCooldown ? t("account.localCooldown") : benched5h ? t("account.quotaLimitedNote") : "";
8741
8817
  const w5h = formatQuotaWindow(t, info?.resetTime);
8742
8818
  const expiredFull5h = w5h.expired && has5h && pct5h >= 100;
8743
8819
  const hasWeekly = typeof info?.weeklyFraction === "number" && Number.isFinite(info.weeklyFraction);
8744
8820
  const pctWeekly = hasWeekly ? Math.max(0, Math.min(100, Math.round(info.weeklyFraction * 100))) : -1;
8821
+ const cdNoteWeekly = benchedWeekly ? t("account.quotaLimitedNote") : "";
8745
8822
  const wWeekly = formatQuotaWindow(t, info?.weeklyResetTime);
8746
8823
  const expiredFullWeekly = wWeekly.expired && hasWeekly && pctWeekly >= 100;
8747
8824
  const c5h = getQuotaColors(pct5h);
8748
8825
  const cWeekly = getQuotaColors(pctWeekly);
8749
- const note5h = w5h.resetText ? w5h.resetText + cdNote : expiredFull5h ? t("quota.windowReset") + cdNote : cdNote.replace(/^ · /, "");
8750
- const noteWeekly = wWeekly.resetText ? wWeekly.resetText : expiredFullWeekly ? t("quota.windowReset") : "";
8826
+ const note5h = w5h.resetText ? w5h.resetText + cdNote5h : expiredFull5h ? t("quota.windowReset") + cdNote5h : cdNote5h.replace(/^ · /, "");
8827
+ const noteWeekly = wWeekly.resetText ? wWeekly.resetText + cdNoteWeekly : expiredFullWeekly ? t("quota.windowReset") + cdNoteWeekly : cdNoteWeekly.replace(/^ · /, "");
8751
8828
  return h("div", { style: {
8752
8829
  margin: "4px 0",
8753
8830
  padding: "5px 8px",
@@ -8785,7 +8862,8 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8785
8862
  function renderQuotaUnavailableNote(t, acc) {
8786
8863
  const state = acc.quotaUnavailable;
8787
8864
  if (!state) return null;
8788
- const newest = Math.max(0, ...Object.values(acc.quotas).map((q) => q?.updatedAt ?? 0));
8865
+ const stamps = Object.values(acc.quotas).map((q) => q?.updatedAt ?? 0).filter((ts) => ts > 0);
8866
+ const oldest = stamps.length > 0 ? Math.min(...stamps) : 0;
8789
8867
  const reason = t(`quota.unavailable.${state.reason}`);
8790
8868
  const isCritical = state.reason === "validation_required" || state.reason === "tos_violation";
8791
8869
  const toneText = isCritical ? "var(--agy-quota-low-text)" : "var(--agy-quota-med-text)";
@@ -8817,10 +8895,10 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8817
8895
  textDecoration: "underline",
8818
8896
  fontWeight: 700
8819
8897
  }
8820
- }, t("quota.verifyNow")) : null, newest > 0 ? h("span", { style: {
8898
+ }, t("quota.verifyNow")) : null, oldest > 0 ? h("span", { style: {
8821
8899
  fontWeight: 500,
8822
8900
  opacity: .85
8823
- } }, t("quota.unavailableSince", { time: formatSnapshotStamp(newest) })) : null);
8901
+ } }, t("quota.unavailableSince", { time: formatSnapshotStamp(oldest) })) : null);
8824
8902
  }
8825
8903
  //#endregion
8826
8904
  //#region src/client/sections/AccountsPanel.ts
@@ -8830,12 +8908,17 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8830
8908
  const renderQuotaBar = (label, familyKey, acc) => renderFamilyQuotaBar(t, label, familyKey, acc, loadingAction === "refresh:all" || loadingAction === `refresh:${acc.id}` || quotaRefreshing.includes(acc.id));
8831
8909
  const authoritativeActiveId = pool?.activeAccountId ?? pool?.lastActiveAccountId ?? pool?.activeAccountIds?.google ?? pool?.primaryAccountId;
8832
8910
  const activeAccountId = optimisticActiveId ?? authoritativeActiveId;
8911
+ const now = Date.now();
8833
8912
  return accounts.map((acc) => {
8834
8913
  const isPrimary = acc.id === pool?.primaryAccountId;
8835
- const hasCooldown = Object.entries(acc.cooldowns).some(([, cd]) => cd && cd.cooldownUntil > Date.now());
8836
- const isAuthRequired = acc.authRequired === true;
8914
+ const hasCooldown = accountHasActiveCooldown(acc, now);
8915
+ const hasQuotaBench = accountHasQuotaBench(acc, now);
8916
+ const isRateLimited = hasCooldown || hasQuotaBench;
8917
+ const isAuthRequired = isAccountCriticalAuth(acc);
8918
+ const isGoogleCooldown = Boolean(acc.cooldowns?.google && acc.cooldowns.google.cooldownUntil > now);
8919
+ const isGoogleEligible = acc.enabled && !isAuthRequired && !isGoogleCooldown && !isQuotaBenched(acc, "google", now);
8837
8920
  const isInUse = Boolean(acc.enabled && !isAuthRequired && activeAccountId !== void 0 && activeAccountId === acc.id);
8838
- const dotColor = !acc.enabled ? "#64748b" : isAuthRequired ? "#ef4444" : hasCooldown ? "#f59e0b" : "#10b981";
8921
+ const dotColor = !acc.enabled ? "#64748b" : isAuthRequired ? "#ef4444" : isRateLimited ? "#f59e0b" : "#10b981";
8839
8922
  const isEditingProxy = editingProxyId === acc.id;
8840
8923
  const isExpanded = expandedModels[acc.id] ?? false;
8841
8924
  const accIndex = accounts.indexOf(acc);
@@ -8861,6 +8944,8 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8861
8944
  isPrimary,
8862
8945
  isAuthRequired,
8863
8946
  hasCooldown,
8947
+ hasQuotaBench,
8948
+ isGoogleEligible,
8864
8949
  isInUse,
8865
8950
  dotColor,
8866
8951
  isEditingProxy,
@@ -8884,7 +8969,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8884
8969
  margin: "4px 0 2px 0"
8885
8970
  },
8886
8971
  onClick: () => toggleExpand(acc.id)
8887
- }, uiIcon(isExpanded ? "chevronUp" : "chevronDown", 10), h("span", null, isExpanded ? t("account.collapseOthers") : t("account.expandOthers"))), isExpanded ? h("div", { key: "expanded-details" }, renderQuotaBar("Claude", "anthropic", acc), renderQuotaBar("GPT-OSS", "openai", acc), childModels.length > 0 ? renderChildModels(t, childModels) : null) : null), hasCooldown ? renderCooldownBanner(t, acc, loadingAction, accountActionBusy, handlers) : null, isEditingProxy ? renderProxyEditor(t, acc, pool, proxyInputs, setProxyInputs, setEditingProxyId, loadingAction, accountActionBusy, handlers) : null);
8972
+ }, uiIcon(isExpanded ? "chevronUp" : "chevronDown", 10), h("span", null, isExpanded ? t("account.collapseOthers") : t("account.expandOthers"))), isExpanded ? h("div", { key: "expanded-details" }, renderQuotaBar("Claude", "anthropic", acc), renderQuotaBar("GPT-OSS", "openai", acc), childModels.length > 0 ? renderChildModels(t, childModels) : null) : null), isRateLimited ? renderCooldownBanner(t, acc, loadingAction, accountActionBusy, handlers) : null, isEditingProxy ? renderProxyEditor(t, acc, pool, proxyInputs, setProxyInputs, setEditingProxyId, loadingAction, accountActionBusy, handlers) : null);
8888
8973
  });
8889
8974
  }
8890
8975
  function extractActionUrl(text) {
@@ -8893,11 +8978,12 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8893
8978
  return m ? m[0] : void 0;
8894
8979
  }
8895
8980
  function renderStatusBadges(t, acc, ctx) {
8896
- const { isAuthRequired, hasCooldown, isInUse, pool } = ctx;
8897
- const isTos = isAuthRequired && /\bTOS_VIOLATION\b|violation of Terms of Service/i.test(acc.authError ?? "");
8898
- const isValidation = isAuthRequired && !isTos && /\bVALIDATION_REQUIRED\b/i.test(acc.authError ?? "");
8981
+ const { isAuthRequired, hasCooldown, hasQuotaBench, isInUse, pool } = ctx;
8982
+ const unavailReason = acc.quotaUnavailable?.reason;
8983
+ const isTos = isAuthRequired && (unavailReason === "tos_violation" || /\bTOS_VIOLATION\b|violation of Terms of Service/i.test(acc.authError ?? ""));
8984
+ const isValidation = isAuthRequired && !isTos && (unavailReason === "validation_required" || /\bVALIDATION_REQUIRED\b/i.test(acc.authError ?? ""));
8899
8985
  const authLabel = isTos ? t("status.tosBanned") : isValidation ? t("status.validationRequired") : t("status.authRequired");
8900
- const actionUrl = isAuthRequired ? extractActionUrl(acc.authError) : void 0;
8986
+ const actionUrl = isAuthRequired ? extractActionUrl(acc.authError) ?? (typeof acc.quotaUnavailable?.actionUrl === "string" && acc.quotaUnavailable.actionUrl.startsWith("https://") ? acc.quotaUnavailable.actionUrl : void 0) : void 0;
8901
8987
  return [
8902
8988
  acc.email ? h("span", {
8903
8989
  style: {
@@ -8963,7 +9049,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8963
9049
  textDecoration: actionUrl ? "underline" : "none"
8964
9050
  }
8965
9051
  }, uiIcon("alert", 10, "#ef4444"), authLabel) : null,
8966
- hasCooldown ? h("span", { style: {
9052
+ hasCooldown || hasQuotaBench ? h("span", { style: {
8967
9053
  ...S.badgeTag,
8968
9054
  background: "rgba(245, 158, 11, 0.15)",
8969
9055
  color: "#f59e0b",
@@ -8974,7 +9060,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
8974
9060
  fontWeight: 700,
8975
9061
  whiteSpace: "nowrap",
8976
9062
  flexShrink: 0
8977
- } }, uiIcon("alert", 10, "#f59e0b"), t("status.cooldown")) : null,
9063
+ } }, uiIcon("alert", 10, "#f59e0b"), hasCooldown ? t("status.cooldown") : t("status.quotaLimited")) : null,
8978
9064
  !acc.enabled ? h("span", {
8979
9065
  style: {
8980
9066
  ...S.badgeTag,
@@ -9081,7 +9167,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
9081
9167
  }, ...badges);
9082
9168
  }
9083
9169
  function renderCardHeader(t, acc, ctx) {
9084
- const { isEditingProxy, isInUse, displayAlias, accounts, loadingAction, accountActionBusy, handlers, setEditingProxyId } = ctx;
9170
+ const { isEditingProxy, isAuthRequired, isInUse, isGoogleEligible, displayAlias, accounts, loadingAction, accountActionBusy, handlers, setEditingProxyId } = ctx;
9085
9171
  return h("div", {
9086
9172
  className: "agy-card-header",
9087
9173
  style: {
@@ -9102,7 +9188,9 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
9102
9188
  }
9103
9189
  }, renderHeaderBadges(t, acc, ctx), renderActionButtons(t, acc, {
9104
9190
  isEditingProxy,
9191
+ isAuthRequired,
9105
9192
  isInUse,
9193
+ isGoogleEligible,
9106
9194
  displayAlias,
9107
9195
  showRemove: accounts.length > 1,
9108
9196
  loadingAction,
@@ -9112,7 +9200,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
9112
9200
  })), renderMetaRow(t, acc, ctx));
9113
9201
  }
9114
9202
  function renderActionButtons(t, acc, ctx) {
9115
- const { isEditingProxy, isInUse, displayAlias, showRemove, loadingAction, accountActionBusy, handlers, setEditingProxyId } = ctx;
9203
+ const { isEditingProxy, isAuthRequired, isInUse, isGoogleEligible, displayAlias, showRemove, loadingAction, accountActionBusy, handlers, setEditingProxyId } = ctx;
9116
9204
  return h("div", {
9117
9205
  className: "agy-card-actions",
9118
9206
  style: {
@@ -9148,7 +9236,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
9148
9236
  title: t("account.syncTitle"),
9149
9237
  disabled: accountActionBusy(acc, "refresh"),
9150
9238
  onClick: () => void handlers.refreshQuota(acc.id)
9151
- }, ...loadingAction === `refresh:${acc.id}` ? [Spinner(), t("account.syncing")] : [uiIcon("refresh", 10), ` ${t("account.sync")}`]), acc.authRequired && handlers.beginReauth ? h(Button, {
9239
+ }, ...loadingAction === `refresh:${acc.id}` ? [Spinner(), t("account.syncing")] : [uiIcon("refresh", 10), ` ${t("account.sync")}`]), isAuthRequired && handlers.beginReauth ? h(Button, {
9152
9240
  variant: "primary",
9153
9241
  size: "sm",
9154
9242
  className: "agy-btn",
@@ -9161,7 +9249,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
9161
9249
  title: t("account.reauthTitle"),
9162
9250
  disabled: accountActionBusy(acc, "reauth"),
9163
9251
  onClick: () => void handlers.beginReauth(acc)
9164
- }, ...loadingAction === `reauth:${acc.id}` ? [Spinner(), t("account.reauthing")] : [uiIcon("externalLink", 10, "#ffffff"), ` ${t("account.reauth")}`]) : null, acc.enabled && !acc.authRequired ? h(Button, {
9252
+ }, ...loadingAction === `reauth:${acc.id}` ? [Spinner(), t("account.reauthing")] : [uiIcon("externalLink", 10, "#ffffff"), ` ${t("account.reauth")}`]) : null, acc.enabled && !isAuthRequired ? h(Button, {
9165
9253
  variant: "default",
9166
9254
  size: "sm",
9167
9255
  className: "agy-btn",
@@ -9175,7 +9263,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
9175
9263
  title: t("account.warmupTitle"),
9176
9264
  disabled: accountActionBusy(acc, "warmup"),
9177
9265
  onClick: () => void handlers.warmupAccount(acc.id)
9178
- }, ...loadingAction === `warmup:${acc.id}` ? [Spinner(), t("account.warmingUp")] : [uiIcon("flame", 10, "#f97316"), ` ${t("account.warmup")}`]) : null, acc.enabled && !acc.authRequired && !isInUse ? h(Button, {
9266
+ }, ...loadingAction === `warmup:${acc.id}` ? [Spinner(), t("account.warmingUp")] : [uiIcon("flame", 10, "#f97316"), ` ${t("account.warmup")}`]) : null, isGoogleEligible && !isInUse ? h(Button, {
9179
9267
  variant: "default",
9180
9268
  size: "sm",
9181
9269
  className: "agy-btn",
@@ -10101,16 +10189,17 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
10101
10189
  const accounts = pool?.accounts ?? [];
10102
10190
  const rawActiveId = pool?.activeAccountId ?? pool?.lastActiveAccountId ?? pool?.activeAccountIds?.google ?? pool?.primaryAccountId;
10103
10191
  const activeAcc = rawActiveId !== void 0 ? accounts.find((a) => a.id === rawActiveId) : void 0;
10104
- const activeAuthRequired = activeAcc?.authRequired === true;
10105
- const activeHasCooldown = activeAcc ? Object.entries(activeAcc.cooldowns ?? {}).some(([, cd]) => cd && cd.cooldownUntil > Date.now()) : false;
10106
- const allInCooldown = accounts.length > 0 && accounts.every((a) => !a.enabled || a.authRequired || Object.entries(a.cooldowns ?? {}).some(([, cd]) => cd && cd.cooldownUntil > Date.now()));
10192
+ const now = Date.now();
10193
+ const activeAuthRequired = activeAcc ? isAccountCriticalAuth(activeAcc) : false;
10194
+ const activeHasCooldown = activeAcc ? accountHasActiveCooldown(activeAcc, now) || accountHasQuotaBench(activeAcc, now) : false;
10195
+ const allInCooldown = accounts.length > 0 && accounts.every((a) => !a.enabled || isAccountCriticalAuth(a) || accountHasActiveCooldown(a, now) || accountHasQuotaBench(a, now));
10107
10196
  const isAuthed = status?.auth?.phase === "ok" || accounts.length > 0;
10108
10197
  const color = status === null ? "#64748b" : status.dormantReason ? "#f59e0b" : allInCooldown ? "#f59e0b" : activeAuthRequired ? "#ef4444" : activeHasCooldown ? "#f59e0b" : isAuthed ? "#10b981" : "#f59e0b";
10109
10198
  const legacyDefault = activeAcc && activeAcc.defaultAlias === void 0 && activeAcc.systemHome && activeAcc.alias === "主账号 (系统登录)";
10110
10199
  const displayAlias = activeAcc ? activeAcc.defaultAlias || legacyDefault ? activeAcc.systemHome ? t("account.defaultAlias") : t("account.aliasDefault", { number: accounts.indexOf(activeAcc) + 1 }) : activeAcc.alias : "";
10111
10200
  const gFrac = activeAcc?.quotas?.google?.remainingFraction;
10112
10201
  const activePct = typeof gFrac === "number" && Number.isFinite(gFrac) ? Math.max(0, Math.min(100, Math.round(gFrac * 100))) : null;
10113
- const activeEligible = activeAcc !== void 0 && activeAcc.enabled && !activeAcc.authRequired;
10202
+ const activeEligible = activeAcc !== void 0 && activeAcc.enabled && !activeAuthRequired;
10114
10203
  const activeDetail = activeAcc !== void 0 && activeEligible ? ` · ${t("status.inUse")}: ${displayAlias}${activeAcc.email ? ` (${activeAcc.email})` : ""}${activePct !== null ? ` · ${activePct}%` : ""}` : "";
10115
10204
  const badgeTitle = status === null ? t("header.badgeLoading") : `${t("header.badgeTitle", { count: accounts.length })}${activeDetail}`;
10116
10205
  const buttonLabel = status === null ? "AGY" : displayAlias ? `AGY · ${displayAlias}` : `AGY (${accounts.length})`;
package/dist/index.js CHANGED
@@ -1411,6 +1411,66 @@ function defaultPoolDir(home) {
1411
1411
  return join(effectiveHome, ".dsh", "agy-accounts");
1412
1412
  }
1413
1413
  //#endregion
1414
+ //#region src/common/quota-bench.ts
1415
+ /** Proactive rotation thresholds: bench accounts at or below these remaining fractions until reset. */
1416
+ const LOW_QUOTA_5H = .1;
1417
+ const LOW_QUOTA_WEEKLY = .05;
1418
+ /** Ordered quota families tracked on an account card. */
1419
+ const QUOTA_FAMILIES = [
1420
+ "google",
1421
+ "argon",
1422
+ "anthropic",
1423
+ "openai"
1424
+ ];
1425
+ function isWindowBenched(fraction, resetTime, threshold, now) {
1426
+ if (typeof fraction !== "number" || fraction > threshold) return false;
1427
+ if (!resetTime) return true;
1428
+ const resetMs = Date.parse(resetTime);
1429
+ return Number.isNaN(resetMs) || resetMs > now;
1430
+ }
1431
+ /** True when a family's 5-hour quota window is at or below the proactive bench threshold and not yet reset. */
1432
+ function is5hQuotaBenched(quota, clearedAt, now) {
1433
+ if (!quota) return false;
1434
+ if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) return false;
1435
+ return isWindowBenched(quota.remainingFraction, quota.resetTime, LOW_QUOTA_5H, now);
1436
+ }
1437
+ /** True when a family's weekly quota window is at or below the proactive bench threshold and not yet reset. */
1438
+ function isWeeklyQuotaBenched(quota, clearedAt, now) {
1439
+ if (!quota) return false;
1440
+ if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) return false;
1441
+ return isWindowBenched(quota.weeklyFraction, quota.weeklyResetTime, LOW_QUOTA_WEEKLY, now);
1442
+ }
1443
+ /**
1444
+ * True when a family's cached quota snapshot benches the account.
1445
+ *
1446
+ * A user-visible `clearCooldown(..., includeQuotaBench = true)` records the
1447
+ * `updatedAt` of the snapshot it overrode; the gate stays off only while the
1448
+ * cached row is no newer than that stamp, so a fresh poll always re-arms it.
1449
+ */
1450
+ function isQuotaBenched(acc, family, now) {
1451
+ const quota = acc.quotas?.[family] ?? (family === "argon" ? acc.quotas?.google : void 0);
1452
+ if (!quota) return false;
1453
+ const clearedAt = acc.quotaGateClearedAt?.[family];
1454
+ return is5hQuotaBenched(quota, clearedAt, now) || isWeeklyQuotaBenched(quota, clearedAt, now);
1455
+ }
1456
+ /**
1457
+ * True when any family reported on the account is benched by its quota snapshot.
1458
+ * Skips the synthesized `argon -> google` fallback when the account has no dedicated
1459
+ * `quotas.argon` row, since `google` itself already reflects that shared bucket.
1460
+ */
1461
+ function accountHasQuotaBench(acc, now) {
1462
+ return QUOTA_FAMILIES.some((fam) => (fam !== "argon" || acc.quotas?.argon !== void 0) && isQuotaBenched(acc, fam, now));
1463
+ }
1464
+ /**
1465
+ * True when the account cannot operate due to auth expiration, web verification
1466
+ * (`VALIDATION_REQUIRED`), or ToS suspension (`TOS_VIOLATION`).
1467
+ */
1468
+ function isAccountCriticalAuth(acc) {
1469
+ if (acc.authRequired === true) return true;
1470
+ const reason = acc.quotaUnavailable?.reason;
1471
+ return reason === "validation_required" || reason === "tos_violation";
1472
+ }
1473
+ //#endregion
1414
1474
  //#region src/common/quota-pacing.ts
1415
1475
  const FIVE_HOUR_WINDOW_MS = 18e6;
1416
1476
  const WEEKLY_WINDOW_MS = 6048e5;
@@ -1470,32 +1530,8 @@ function computeQuotaPacing(remainingFraction, resetTimeIso, windowMs, now = Dat
1470
1530
  burnMultiplier
1471
1531
  };
1472
1532
  }
1473
- /**
1474
- * True when a family's cached quota snapshot benches the account.
1475
- *
1476
- * A user-visible `clearCooldown(..., includeQuotaBench = true)` records the
1477
- * `updatedAt` of the snapshot it overrode; the gate stays off only while the
1478
- * cached row is no newer than that stamp, so a fresh poll always re-arms it.
1479
- */
1480
- function isQuotaBenched(acc, family, now) {
1481
- const quota = acc.quotas?.[family] ?? (family === "argon" ? acc.quotas?.google : void 0);
1482
- if (!quota) return false;
1483
- const clearedAt = acc.quotaGateClearedAt?.[family];
1484
- if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) return false;
1485
- if (typeof quota.remainingFraction === "number" && quota.remainingFraction <= .1) {
1486
- if (quota.resetTime) {
1487
- const resetMs = Date.parse(quota.resetTime);
1488
- if (Number.isNaN(resetMs) || resetMs > now) return true;
1489
- } else return true;
1490
- }
1491
- if (typeof quota.weeklyFraction === "number" && quota.weeklyFraction <= .05) {
1492
- if (quota.weeklyResetTime) {
1493
- const resetMs = Date.parse(quota.weeklyResetTime);
1494
- if (Number.isNaN(resetMs) || resetMs > now) return true;
1495
- } else return true;
1496
- }
1497
- return false;
1498
- }
1533
+ //#endregion
1534
+ //#region src/domain/accounts/selection.ts
1499
1535
  /**
1500
1536
  * Why this account cannot serve `family` right now, or null when it can.
1501
1537
  *
@@ -1505,7 +1541,7 @@ function isQuotaBenched(acc, family, now) {
1505
1541
  */
1506
1542
  function explainIneligibility(acc, family, now, pool, model) {
1507
1543
  if (!acc.enabled) return "disabled";
1508
- if (acc.authRequired) return "auth";
1544
+ if (isAccountCriticalAuth(acc)) return "auth";
1509
1545
  if (family === "argon" && !accountHasArgon(acc, pool)) return "unsupported";
1510
1546
  if (model && pool?.isModelSupported && !pool.isModelSupported(acc, model)) return "model-unsupported";
1511
1547
  const cd = acc.cooldowns?.[family];
@@ -1762,7 +1798,7 @@ var PoolAdmin = class {
1762
1798
  setActiveAccount(id, family = "google") {
1763
1799
  const data = this.deps.getData();
1764
1800
  const acc = this.account(id);
1765
- if (!acc || !acc.enabled || acc.authRequired) return false;
1801
+ if (!acc || !isAccountEligible(acc, family, Date.now(), this.deps.pool)) return false;
1766
1802
  if (!data.activeAccountIds) data.activeAccountIds = {};
1767
1803
  data.activeAccountIds[family] = id;
1768
1804
  data.lastActiveAccountId = id;
@@ -3243,7 +3279,7 @@ function describeAgyAutoUpdate(env = process.env, now = Date.now()) {
3243
3279
  * boundary cut the line), which keeps the conservative "arm the grace" path.
3244
3280
  */
3245
3281
  function backgroundTasksFrom(text) {
3246
- const match = /root agent idle;\s*waiting\s+for\s+(\d+)\s+background/i.exec(text);
3282
+ const match = /root agent idle;\s*waiting(?:\s+up\s+to\s+\S+)?\s+for\s+(\d+)\s+background/i.exec(text);
3247
3283
  if (match === null) return null;
3248
3284
  const count = Number(match[1]);
3249
3285
  return Number.isSafeInteger(count) && count >= 0 ? count : null;
@@ -30934,6 +30970,27 @@ var RunRecording = class {
30934
30970
  get hasResult() {
30935
30971
  return this.events.some((e) => e.kind === "result");
30936
30972
  }
30973
+ /** Whether a result event that EventMapper will finish on (ok, or non-empty error response) was recorded. */
30974
+ get hasConsumableResult() {
30975
+ const r = this.getResultEvent();
30976
+ return r !== null && (r.ok || r.response !== "");
30977
+ }
30978
+ /**
30979
+ * Whether any recorded event at or after `from` can finish a span cleanly
30980
+ * (a consumable result envelope, or a completed tool step when `cutOnTool`
30981
+ * is enabled). A settled recording with `failureInfo === null` and no such
30982
+ * event would otherwise replay `INVALID_OUTPUT: agy stream ended without a
30983
+ * result event` on every continuation retry.
30984
+ */
30985
+ hasFinishableEventFrom(from, cutOnTool = true) {
30986
+ for (let i = Math.max(0, from); i < this.events.length; i++) {
30987
+ const ev = this.events[i];
30988
+ if (ev === void 0) continue;
30989
+ if (ev.kind === "result" && (ev.ok || ev.response !== "")) return true;
30990
+ if (cutOnTool && ev.kind === "step" && ev.stepKind === "tool" && ev.tool !== void 0 && (ev.state === "DONE" || ev.state === "ERROR" || ev.state === "RUNNING" || ev.state === void 0 && (ev.tool.output !== void 0 || ev.tool.error !== void 0))) return true;
30991
+ }
30992
+ return false;
30993
+ }
30937
30994
  /** The last result envelope's finish-relevant projection, when one arrived. */
30938
30995
  getResultEvent() {
30939
30996
  for (let i = this.events.length - 1; i >= 0; i--) {
@@ -35617,8 +35674,7 @@ async function handleAttemptOutcome(deps, input, ctx) {
35617
35674
  deps.clearInFlightPrompt(sessionKey, spawn.prompt);
35618
35675
  recorder.drain(input.agyOnEvent);
35619
35676
  const conversationId = recorder.conversationId();
35620
- const existingRes = rec.getResultEvent();
35621
- if (!(existingRes !== null && (existingRes.ok || existingRes.response !== "")) && outcome.idleGraceTerminated) {
35677
+ if (!rec.hasConsumableResult && outcome.idleGraceTerminated) {
35622
35678
  const recovered = conversationId === null ? "" : recoverFinalReply(conversationId, rec.accountHome);
35623
35679
  const synthResult = {
35624
35680
  kind: "result",
@@ -35679,7 +35735,7 @@ async function handleAttemptOutcome(deps, input, ctx) {
35679
35735
  * queue notices; the outcome closure runs detached exactly as before.
35680
35736
  */
35681
35737
  async function* runAgyAttempt(deps, input) {
35682
- const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId, !input.isAux);
35738
+ const recorder = createAttemptRecorder(deps, input.cfg, input.account, input.binding?.conversationId);
35683
35739
  const spawn = buildSpawnArgs(input, recorder.printTimeoutMinutes, deps.log);
35684
35740
  const slot = yield* dispatchCredentialSlot(deps, {
35685
35741
  ...input,
@@ -35924,14 +35980,14 @@ var AgyAdapter = class extends LlmAdapter {
35924
35980
  if (continuation !== null) {
35925
35981
  const rec = this.deps.runs.get(continuation.runId);
35926
35982
  const deadFailure = rec !== void 0 && rec.isSettled ? rec.failureInfo : null;
35927
- const deadMissingResult = rec !== void 0 && rec.isSettled && deadFailure === null && !rec.hasConsumableResultFrom(continuation.eventIndex + 1);
35928
- if (rec !== void 0 && !deadMissingResult && !(deadFailure !== null && this.claimFailover(sessionKey, deadFailure.code))) {
35983
+ const deadNoResult = rec !== void 0 && rec.isSettled && deadFailure === null && !rec.hasFinishableEventFrom(continuation.eventIndex + 1, hasToolSupport);
35984
+ if (rec !== void 0 && !deadNoResult && !(deadFailure !== null && this.claimFailover(sessionKey, deadFailure.code))) {
35929
35985
  yield* driveSpan(this.deps, rec, continuation.eventIndex + 1, hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal);
35930
35986
  return;
35931
35987
  }
35932
35988
  if (rec !== void 0) {
35933
35989
  this.deps.runs.forget(continuation.runId);
35934
- this.warnOnce("dead-continuation:" + continuation.runId, deadMissingResult ? "agy run " + continuation.runId + " settled without a consumable result — retrying this step instead of replaying an empty stream" : "agy run " + continuation.runId + " settled in " + (deadFailure?.code ?? "") + " — retrying this step instead of replaying it" + (deadFailure?.code === Err.NETWORK && this.sharesSingleEgress() ? " on the same account (shared egress)" : " on another account"));
35990
+ this.warnOnce("dead-continuation:" + continuation.runId, deadNoResult ? "agy run " + continuation.runId + " settled without a consumable result — retrying this step instead of replaying it" : "agy run " + continuation.runId + " settled in " + (deadFailure?.code ?? "") + " — retrying this step instead of replaying it" + (deadFailure?.code === Err.NETWORK && this.sharesSingleEgress() ? " on the same account (shared egress)" : " on another account"));
35935
35991
  } else this.warnOnce("stale-continuation:" + continuation.runId, "agy run " + continuation.runId + " is no longer available in memory (server restarted?) — falling back to fresh turn prompt assembly");
35936
35992
  }
35937
35993
  const catalog = this.deps.catalog.get();
@@ -36116,7 +36172,7 @@ var AgyAdapter = class extends LlmAdapter {
36116
36172
  signal: options.signal,
36117
36173
  agyOnEvent: options.agyOnEvent
36118
36174
  });
36119
- yield* driveSpan(this.deps, rec, 0, policy.mirrorTools && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice, isAux && !isImage);
36175
+ yield* driveSpan(this.deps, rec, 0, policy.mirrorTools && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice);
36120
36176
  }
36121
36177
  };
36122
36178
  //#endregion
@@ -36473,15 +36529,17 @@ function renderPool(deps) {
36473
36529
  const qO = a.quotas.openai?.remainingFraction !== void 0 ? `${Math.round(a.quotas.openai.remainingFraction * 100)}%` : "unknown";
36474
36530
  const qA = a.quotas.argon?.weeklyFraction ?? a.quotas.argon?.remainingFraction;
36475
36531
  const quotaLine = ` - Quota: Gemini ${qG} | Claude ${qC} | GPT-OSS ${qO}` + (qA !== void 0 ? ` | Argon ${Math.round(qA * 100)}%` : "");
36532
+ const now = Date.now();
36476
36533
  const cds = [];
36477
- for (const [fam, cd] of Object.entries(a.cooldowns)) if (cd && cd.cooldownUntil > Date.now()) {
36478
- const sec = Math.ceil((cd.cooldownUntil - Date.now()) / 1e3);
36534
+ for (const [fam, cd] of Object.entries(a.cooldowns)) if (cd && cd.cooldownUntil > now) {
36535
+ const sec = Math.ceil((cd.cooldownUntil - now) / 1e3);
36479
36536
  cds.push(`${fam} cooldown: ${sec}s left (${cd.reason})`);
36480
36537
  }
36481
36538
  let statusText = " - Status: 🟢 Ready";
36482
36539
  if (!a.enabled) statusText = " - Status: ⏸️ Disabled";
36483
- else if (a.authRequired) statusText = ` - Status: 🔴 Auth required (${a.authError || "sign in again"})`;
36540
+ else if (isAccountCriticalAuth(a)) statusText = ` - Status: 🔴 Auth required (${a.authError || a.quotaUnavailable?.reason || "sign in again"})`;
36484
36541
  else if (cds.length > 0) statusText = ` - ⚠️ ${cds.join("; ")}`;
36542
+ else if (accountHasQuotaBench(a, now)) statusText = " - ⚠️ Quota-limited (auto-rotated until reset)";
36485
36543
  lines.push(`${i + 1}. **${a.alias}** (${a.email || "email unknown"}; id: \`${a.id}\`)${isPrimary ? " ⭐ primary" : ""}`, ` - Proxy: ${a.proxyUrl ? redactProxyUrl(a.proxyUrl) : deps.cfg().proxyUrl ? redactProxyUrl(deps.cfg().proxyUrl) : "system default"}`, quotaLine, statusText);
36486
36544
  }
36487
36545
  return ok$1(lines.join("\n"));
@@ -36494,7 +36552,7 @@ async function handlePool(deps, ctx) {
36494
36552
  const pool = deps.pool?.();
36495
36553
  if (!pool) return err$1("Account pool not available");
36496
36554
  const prev = pool.getActiveAccountId("google");
36497
- if (!pool.setActiveAccount(arg)) return err$1(`Account ${arg} not found or not eligible (disabled / auth required)`);
36555
+ if (!pool.setActiveAccount(arg)) return err$1(`Account ${arg} not found or not eligible (disabled / cooldown / quota-limited / auth required)`);
36498
36556
  if (arg === prev) deps.notifyPicker?.();
36499
36557
  return ok$1(`Active account set to **${arg}** — model picker synced.`);
36500
36558
  }
@@ -40260,6 +40318,11 @@ async function refreshAccountQuotaPipeline(deps, account, force = false) {
40260
40318
  ...failure?.detail === void 0 ? {} : { detail: failure.detail },
40261
40319
  ...failure?.actionUrl === void 0 ? {} : { actionUrl: failure.actionUrl }
40262
40320
  });
40321
+ if ((reason === "validation_required" || reason === "tos_violation") && !account.authRequired) {
40322
+ const tag = reason === "tos_violation" ? "TOS_VIOLATION" : "VALIDATION_REQUIRED";
40323
+ const suffix = failure?.actionUrl ? ` (${failure.actionUrl})` : "";
40324
+ deps.pool.markAuthRequired(account.id, `${tag}${suffix}`);
40325
+ }
40263
40326
  }
40264
40327
  }
40265
40328
  if (!summary && Object.keys(modelsCatalog).length === 0) return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agy-link",
3
- "version": "0.6.47",
3
+ "version": "0.6.49",
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",