dsh-agy-link 0.6.1 → 0.6.3

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,43 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.3 (2026-11-06)
4
+
5
+ ### English
6
+
7
+ - **Fix(compaction): the compaction card now actually renders in DSH, reports real token deltas, and no longer duplicates across accounts.** (thanks @Ronnoc, #79)
8
+ - DSH's markdown renderer uses `allowDangerousHtml: false`, so the previous raw `<div class="agy-compaction-card">` marker was escaped into visible text. The marker is now a standard blockquote **link** (`> [✂️ 上下文已压缩 · 128.5k → 14.2k tokens (-89%)](#agy-compaction-card?…)`) that the client enhancer upgrades to the native card — and legacy raw/escaped markers still upgrade.
9
+ - Token accounting summed only `input_tokens` (the uncached delta), so cards fired at tiny counts like `4.6k → 205`; `calcPromptTokens()` now adds `cache_read_tokens` + `cache_write_tokens` for the real prompt size.
10
+ - Multi-account compaction cleared only the active account's binding, so rotating steps re-triggered duplicate cards; compaction now invalidates every binding for the session across accounts and debounces repeated notices.
11
+ - Hardening on merge: marker query values now percent-encode `( ) ' !` too, so a digest containing parentheses can't terminate the markdown link early.
12
+
13
+ ### 中文
14
+
15
+ - **修复(compaction):压缩卡片现在能在 DSH 里真正渲染、显示真实 token 变化,且不再跨账号重复。**(感谢 @Ronnoc,#79)
16
+ - DSH 的 markdown 渲染器 `allowDangerousHtml: false`,旧的原始 `<div class="agy-compaction-card">` 标记会被转义成可见文本。现改为标准引用块**链接**(`> [✂️ 上下文已压缩 · 128.5k → 14.2k tokens (-89%)](#agy-compaction-card?…)`),由客户端增强器升级为原生卡片;旧的原始/转义标记仍可升级。
17
+ - token 记账只加 `input_tokens`(未缓存增量),导致卡片在 `4.6k → 205` 这种小值就触发;`calcPromptTokens()` 现加上 `cache_read_tokens` + `cache_write_tokens` 得到真实 prompt 规模。
18
+ - 多账号下压缩只清当前账号的绑定,切换账号的后续步骤会重复触发卡片;现按会话清空所有账号的绑定并对重复提示去抖。
19
+ - 合并时加固:标记的查询值额外百分号编码 `( ) ' !`,避免含括号的摘要把 markdown 链接提前截断。
20
+
21
+ **Full Changelog**: https://github.com/amlyczz/dsh-agy-link/compare/v0.6.2...v0.6.3
22
+
23
+ ## 0.6.2 (2026-11-06)
24
+
25
+ ### English
26
+
27
+ - **Fix(quota): Argon is weekly-only when the backend folds it into the Gemini bucket, and `/agy clear-cooldown` can now lift a quota bench (issue #77).** (thanks @hjwsm1989, #78)
28
+ - The model-level fallback filed Argon's **weekly** `quotaInfo` under `remainingFraction` (the 5-hour slot), so the 10% 5h floor benched accounts whose weekly quota was still above the 5% weekly floor — the `5% < weekly ≤ 10%` dead band. Argon without a backend 5-hour window is now written to `weeklyFraction/weeklyResetTime` only (an existing mis-filled row is healed on the next poll).
29
+ - The "no account can serve" error now reports the real reason via `pool.explainIneligibility()` (`disabled` / `auth` / `cooldown` / `quota`) and suggests a remedy that works; `/agy clear-cooldown` also lifts the proactive low-quota bench for the cached snapshot (`quotaGateClearedAt`), re-arming as soon as a poll writes fresher data.
30
+ - Retired Argon groups release their cooldown again: the dedicated-group decision uses the summary alone, not the synthesized model row that made the `else` branch unreachable.
31
+
32
+ ### 中文
33
+
34
+ - **修复(quota):后端把 Argon 折进 Gemini 桶时按「仅周额度」处理,且 `/agy clear-cooldown` 现在能解除配额停摆(issue #77)。**(感谢 @hjwsm1989,#78)
35
+ - 模型级回退把 Argon 的**周** `quotaInfo` 写进 `remainingFraction`(5 小时槽),于是 10% 的 5h 下限会误伤周额度仍高于 5% 下限的账号(`5% < weekly ≤ 10%` 死区)。现在没有后端 5 小时窗口的 Argon 只写 `weeklyFraction/weeklyResetTime`,并在下次轮询时修复已被误填的行。
36
+ - 「无可用账号」错误改用 `pool.explainIneligibility()` 报告真实原因(`disabled`/`auth`/`cooldown`/`quota`)并给出有效建议;`/agy clear-cooldown` 会同时解除针对当前缓存快照的主动低配额停摆(`quotaGateClearedAt`),一旦轮询写入更新数据即自动重新生效。
37
+ - 退役的 Argon 组重新能释放冷却:专用组判定只看 summary,不再被模型回退合成出来的行挡住。
38
+
39
+ **Full Changelog**: https://github.com/amlyczz/dsh-agy-link/compare/v0.6.1...v0.6.2
40
+
3
41
  ## 0.6.1 (2026-11-06)
4
42
 
5
43
  ### English
package/dist/client.js CHANGED
@@ -4923,79 +4923,165 @@ body.dark .agy-tsl-card,
4923
4923
  }
4924
4924
  return "上下文已压缩";
4925
4925
  }
4926
+ function buildCompactionRow(notice) {
4927
+ const { beforeTokens, afterTokens, summary = "" } = notice;
4928
+ const summaryLabel = formatCompactionSummary(beforeTokens, afterTokens);
4929
+ const reductionLabel = calcTokenReduction(beforeTokens, afterTokens);
4930
+ const titleText = getCompactionTitle();
4931
+ const row = document.createElement("div");
4932
+ row.className = "agy-compaction-row";
4933
+ row.setAttribute("data-state", "collapsed");
4934
+ const button = document.createElement("button");
4935
+ button.type = "button";
4936
+ button.className = "agy-compaction-button";
4937
+ button.setAttribute("aria-expanded", "false");
4938
+ button.innerHTML = `
4939
+ <span class="agy-compaction-leading" aria-hidden="true">
4940
+ <svg class="agy-compaction-icon-context" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4941
+ <rect x="3" y="4" width="18" height="16" rx="2"></rect>
4942
+ <line x1="7" y1="8" x2="17" y2="8"></line>
4943
+ <line x1="7" y1="12" x2="13" y2="12"></line>
4944
+ <line x1="7" y1="16" x2="11" y2="16"></line>
4945
+ </svg>
4946
+ <svg class="agy-compaction-icon-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4947
+ <path d="M9 5l7 7-7 7"></path>
4948
+ </svg>
4949
+ </span>
4950
+ <span class="agy-compaction-title">${titleText}</span>
4951
+ <span class="agy-compaction-sep" aria-hidden="true">·</span>
4952
+ <span class="agy-compaction-summary">${summaryLabel}</span>
4953
+ `;
4954
+ const body = document.createElement("div");
4955
+ body.className = "agy-compaction-body";
4956
+ body.style.display = "none";
4957
+ const metricsBar = document.createElement("div");
4958
+ metricsBar.className = "agy-compaction-metrics-bar";
4959
+ metricsBar.innerHTML = `
4960
+ <span class="agy-metric-item"><strong>压缩前:</strong> ${formatTokenCount(beforeTokens)} tokens</span>
4961
+ <span class="agy-metric-arrow">→</span>
4962
+ <span class="agy-metric-item"><strong>压缩后:</strong> ${formatTokenCount(afterTokens)} tokens</span>
4963
+ <span class="agy-metric-badge">${reductionLabel}</span>
4964
+ `;
4965
+ body.appendChild(metricsBar);
4966
+ if (summary.trim() !== "") {
4967
+ const summaryContent = document.createElement("div");
4968
+ summaryContent.className = "agy-compaction-summary-text";
4969
+ summaryContent.textContent = summary;
4970
+ body.appendChild(summaryContent);
4971
+ }
4972
+ button.addEventListener("click", (e) => {
4973
+ e.stopPropagation();
4974
+ const isExpanded = row.getAttribute("data-state") === "expanded";
4975
+ const nextState = isExpanded ? "collapsed" : "expanded";
4976
+ row.setAttribute("data-state", nextState);
4977
+ button.setAttribute("aria-expanded", String(!isExpanded));
4978
+ body.style.display = isExpanded ? "none" : "block";
4979
+ });
4980
+ row.appendChild(button);
4981
+ row.appendChild(body);
4982
+ return row;
4983
+ }
4926
4984
  /**
4927
- * Scan DOM for `.agy-compaction-card` markers and transform them into
4985
+ * Scan DOM for compaction markers and transform them into
4928
4986
  * the interactive DeepSeek-like Compaction Card.
4929
4987
  */
4930
4988
  function scanAndEnhanceCompactionCards(root = document) {
4931
4989
  if (typeof document === "undefined") return;
4932
4990
  if (isInteractionLocked()) return;
4991
+ const anchors = root.querySelectorAll("a[href*=\"#agy-compaction\"]:not([data-agy-compaction-rendered=\"true\"])");
4992
+ for (const anchor of Array.from(anchors)) {
4993
+ anchor.setAttribute("data-agy-compaction-rendered", "true");
4994
+ const href = anchor.getAttribute("href") || "";
4995
+ const qIdx = href.indexOf("?");
4996
+ const queryStr = qIdx >= 0 ? href.slice(qIdx + 1) : "";
4997
+ const params = new URLSearchParams(queryStr);
4998
+ const beforeTokens = parseInt(params.get("before") || "0", 10);
4999
+ const afterTokens = parseInt(params.get("after") || "0", 10);
5000
+ const items = parseInt(params.get("items") || "0", 10);
5001
+ let summary = "";
5002
+ const rawSummary = params.get("summary");
5003
+ if (rawSummary) try {
5004
+ summary = decodeURIComponent(rawSummary);
5005
+ } catch {
5006
+ summary = "";
5007
+ }
5008
+ const container = document.createElement("div");
5009
+ container.className = "agy-compaction-card";
5010
+ container.setAttribute("data-agy-compaction-rendered", "true");
5011
+ const row = buildCompactionRow({
5012
+ beforeTokens,
5013
+ afterTokens,
5014
+ items,
5015
+ summary
5016
+ });
5017
+ container.appendChild(row);
5018
+ let targetNode = anchor;
5019
+ if (targetNode.parentElement && targetNode.parentElement.tagName.toLowerCase() === "p") targetNode = targetNode.parentElement;
5020
+ if (targetNode.parentElement && targetNode.parentElement.tagName.toLowerCase() === "blockquote") targetNode = targetNode.parentElement;
5021
+ if (typeof targetNode.replaceWith === "function") targetNode.replaceWith(container);
5022
+ else if (targetNode.parentNode) targetNode.parentNode.replaceChild(container, targetNode);
5023
+ }
4933
5024
  const cards = root.querySelectorAll(".agy-compaction-card:not([data-agy-compaction-rendered=\"true\"])");
4934
5025
  for (const card of Array.from(cards)) {
4935
5026
  card.setAttribute("data-agy-compaction-rendered", "true");
4936
5027
  const beforeTokens = parseInt(card.dataset.before || "0", 10);
4937
5028
  const afterTokens = parseInt(card.dataset.after || "0", 10);
5029
+ const items = parseInt(card.dataset.items || "0", 10);
4938
5030
  let summary = "";
4939
5031
  if (card.dataset.summary) try {
4940
5032
  summary = decodeURIComponent(card.dataset.summary);
4941
5033
  } catch {
4942
5034
  summary = "";
4943
5035
  }
4944
- const summaryLabel = formatCompactionSummary(beforeTokens, afterTokens);
4945
- const reductionLabel = calcTokenReduction(beforeTokens, afterTokens);
4946
- const titleText = getCompactionTitle();
4947
- const row = document.createElement("div");
4948
- row.className = "agy-compaction-row";
4949
- row.setAttribute("data-state", "collapsed");
4950
- const button = document.createElement("button");
4951
- button.type = "button";
4952
- button.className = "agy-compaction-button";
4953
- button.setAttribute("aria-expanded", "false");
4954
- button.innerHTML = `
4955
- <span class="agy-compaction-leading" aria-hidden="true">
4956
- <svg class="agy-compaction-icon-context" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4957
- <rect x="3" y="4" width="18" height="16" rx="2"></rect>
4958
- <line x1="7" y1="8" x2="17" y2="8"></line>
4959
- <line x1="7" y1="12" x2="13" y2="12"></line>
4960
- <line x1="7" y1="16" x2="11" y2="16"></line>
4961
- </svg>
4962
- <svg class="agy-compaction-icon-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
4963
- <path d="M9 5l7 7-7 7"></path>
4964
- </svg>
4965
- </span>
4966
- <span class="agy-compaction-title">${titleText}</span>
4967
- <span class="agy-compaction-sep" aria-hidden="true">·</span>
4968
- <span class="agy-compaction-summary">${summaryLabel}</span>
4969
- `;
4970
- const body = document.createElement("div");
4971
- body.className = "agy-compaction-body";
4972
- body.style.display = "none";
4973
- const metricsBar = document.createElement("div");
4974
- metricsBar.className = "agy-compaction-metrics-bar";
4975
- metricsBar.innerHTML = `
4976
- <span class="agy-metric-item"><strong>压缩前:</strong> ${formatTokenCount(beforeTokens)} tokens</span>
4977
- <span class="agy-metric-arrow">→</span>
4978
- <span class="agy-metric-item"><strong>压缩后:</strong> ${formatTokenCount(afterTokens)} tokens</span>
4979
- <span class="agy-metric-badge">${reductionLabel}</span>
4980
- `;
4981
- body.appendChild(metricsBar);
4982
- if (summary.trim() !== "") {
4983
- const summaryContent = document.createElement("div");
4984
- summaryContent.className = "agy-compaction-summary-text";
4985
- summaryContent.textContent = summary;
4986
- body.appendChild(summaryContent);
4987
- }
4988
- button.addEventListener("click", (e) => {
4989
- e.stopPropagation();
4990
- const isExpanded = row.getAttribute("data-state") === "expanded";
4991
- const nextState = isExpanded ? "collapsed" : "expanded";
4992
- row.setAttribute("data-state", nextState);
4993
- button.setAttribute("aria-expanded", String(!isExpanded));
4994
- body.style.display = isExpanded ? "none" : "block";
5036
+ const row = buildCompactionRow({
5037
+ beforeTokens,
5038
+ afterTokens,
5039
+ items,
5040
+ summary
4995
5041
  });
4996
5042
  card.replaceChildren(row);
4997
- row.appendChild(button);
4998
- row.appendChild(body);
5043
+ }
5044
+ const paragraphs = root.querySelectorAll("p:not([data-agy-compaction-rendered=\"true\"])");
5045
+ for (const p of Array.from(paragraphs)) {
5046
+ const text = p.textContent || "";
5047
+ if (!text.includes("class=\"agy-compaction-card\"") && !text.includes("agy-compaction-card")) continue;
5048
+ p.setAttribute("data-agy-compaction-rendered", "true");
5049
+ const beforeMatch = /data-before="(\d+)"/.exec(text);
5050
+ const afterMatch = /data-after="(\d+)"/.exec(text);
5051
+ const itemsMatch = /data-items="(\d+)"/.exec(text);
5052
+ const summaryMatch = /data-summary="([^"]*)"/.exec(text);
5053
+ const beforeTokens = beforeMatch ? parseInt(beforeMatch[1] || "0", 10) : 0;
5054
+ const afterTokens = afterMatch ? parseInt(afterMatch[1] || "0", 10) : 0;
5055
+ const items = itemsMatch ? parseInt(itemsMatch[1] || "0", 10) : 0;
5056
+ let summary = "";
5057
+ if (summaryMatch && summaryMatch[1]) try {
5058
+ summary = decodeURIComponent(summaryMatch[1]);
5059
+ } catch {
5060
+ summary = "";
5061
+ }
5062
+ const container = document.createElement("div");
5063
+ container.className = "agy-compaction-card";
5064
+ container.setAttribute("data-agy-compaction-rendered", "true");
5065
+ const row = buildCompactionRow({
5066
+ beforeTokens,
5067
+ afterTokens,
5068
+ items,
5069
+ summary
5070
+ });
5071
+ container.appendChild(row);
5072
+ let next = p.nextElementSibling;
5073
+ while (next) {
5074
+ const sib = next;
5075
+ const sibTag = sib.tagName ? sib.tagName.toLowerCase() : "";
5076
+ const sibText = (sib.textContent || "").trim();
5077
+ if (sibTag === "blockquote" || sibTag === "p" && (sibText === "</div>" || sibText === "")) {
5078
+ next = sib.nextElementSibling;
5079
+ if (typeof sib.remove === "function") sib.remove();
5080
+ else if (sib.parentNode) sib.parentNode.removeChild(sib);
5081
+ } else break;
5082
+ }
5083
+ if (typeof p.replaceWith === "function") p.replaceWith(container);
5084
+ else if (p.parentNode) p.parentNode.replaceChild(container, p);
4999
5085
  }
5000
5086
  }
5001
5087
  let compactionDispose = null;
package/dist/index.js CHANGED
@@ -1914,14 +1914,20 @@ function formatCompactionSummary(before, after) {
1914
1914
  }
1915
1915
  /**
1916
1916
  * Render standard compaction marker for the stream.
1917
- * In raw markdown, this surfaces as an elegant blockquote:
1918
- * > ✂️ **上下文已压缩** · 128.5k → 14.2k tokens (-89%)
1917
+ * In raw markdown (and DSH markdown which escapes raw HTML), this surfaces as an elegant blockquote:
1918
+ * > [✂️ **上下文已压缩** · 128.5k → 14.2k tokens (-89%)](#agy-compaction-card?before=128500&after=14200&items=18&summary=...)
1919
1919
  * In browser DSH, the client enhancer transforms it into the interactive native Compaction Card.
1920
1920
  */
1921
+ /** Percent-encode a value for use inside a markdown link destination.
1922
+ * encodeURIComponent leaves ( ) ' ! alone, but a raw ')' in a query value would
1923
+ * terminate the `](...)` link early and break the marker. */
1924
+ function encodeForMarkdownUrl(value) {
1925
+ return encodeURIComponent(value).replace(/[()'!]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
1926
+ }
1921
1927
  function renderCompactionMarker(notice) {
1922
1928
  const summaryText = formatCompactionSummary(notice.beforeTokens, notice.afterTokens);
1923
- const encodedSummary = notice.summary ? encodeURIComponent(notice.summary) : "";
1924
- return `<div class="agy-compaction-card" data-before="${notice.beforeTokens}" data-after="${notice.afterTokens}" data-items="${notice.items}" data-summary="${encodedSummary}">\n\n> ✂️ **上下文已压缩** · ${summaryText}\n\n</div>\n\n`;
1929
+ const encodedSummary = notice.summary ? encodeForMarkdownUrl(notice.summary) : "";
1930
+ return `> [✂️ **上下文已压缩** · ${summaryText}](#agy-compaction-card?before=${notice.beforeTokens}&after=${notice.afterTokens}&items=${notice.items}&summary=${encodedSummary})\n\n`;
1925
1931
  }
1926
1932
  //#endregion
1927
1933
  //#region src/host/mapper.ts
@@ -4359,6 +4365,7 @@ var AccountPoolManager = class {
4359
4365
  if (acc.cooldowns === void 0 || acc.cooldowns === null) acc.cooldowns = {};
4360
4366
  if (acc.quotas === void 0 || acc.quotas === null) acc.quotas = {};
4361
4367
  if (acc.enabled === void 0) acc.enabled = true;
4368
+ if (acc.quotaGateClearedAt !== void 0 && (typeof acc.quotaGateClearedAt !== "object" || acc.quotaGateClearedAt === null)) acc.quotaGateClearedAt = void 0;
4362
4369
  for (const [fam, cd] of Object.entries(acc.cooldowns)) if (cd && cd.reason === "agy run aborted by caller") delete acc.cooldowns[fam];
4363
4370
  }
4364
4371
  return {
@@ -4786,26 +4793,51 @@ var AccountPoolManager = class {
4786
4793
  this.persist();
4787
4794
  }
4788
4795
  /**
4789
- * Check whether an account is eligible to serve requests for the given family.
4796
+ * True when a family's cached quota snapshot benches the account.
4797
+ *
4798
+ * A user-visible `clearCooldown(..., includeQuotaBench = true)` records the
4799
+ * `updatedAt` of the snapshot it overrode; the gate stays off only while the
4800
+ * cached row is no newer than that stamp, so a fresh poll always re-arms it.
4790
4801
  */
4791
- isAccountEligible(acc, family, now = Date.now()) {
4792
- if (!acc.enabled || acc.authRequired) return false;
4793
- const cd = acc.cooldowns?.[family];
4794
- if (cd && cd.cooldownUntil > now) return false;
4802
+ isQuotaBenched(acc, family, now) {
4795
4803
  const quota = acc.quotas?.[family];
4796
- if (quota && typeof quota.remainingFraction === "number" && quota.remainingFraction <= .1) {
4804
+ if (!quota) return false;
4805
+ const clearedAt = acc.quotaGateClearedAt?.[family];
4806
+ if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) return false;
4807
+ if (typeof quota.remainingFraction === "number" && quota.remainingFraction <= .1) {
4797
4808
  if (quota.resetTime) {
4798
4809
  const resetMs = Date.parse(quota.resetTime);
4799
- if (Number.isNaN(resetMs) || resetMs > now) return false;
4800
- } else return false;
4810
+ if (Number.isNaN(resetMs) || resetMs > now) return true;
4811
+ } else return true;
4801
4812
  }
4802
- if (quota && typeof quota.weeklyFraction === "number" && quota.weeklyFraction <= .05) {
4813
+ if (typeof quota.weeklyFraction === "number" && quota.weeklyFraction <= .05) {
4803
4814
  if (quota.weeklyResetTime) {
4804
4815
  const resetMs = Date.parse(quota.weeklyResetTime);
4805
- if (Number.isNaN(resetMs) || resetMs > now) return false;
4806
- } else return false;
4816
+ if (Number.isNaN(resetMs) || resetMs > now) return true;
4817
+ } else return true;
4807
4818
  }
4808
- return true;
4819
+ return false;
4820
+ }
4821
+ /**
4822
+ * Why this account cannot serve `family` right now, or null when it can.
4823
+ *
4824
+ * Exists so callers can report the ACTUAL blocker: quota rotation used to be
4825
+ * folded into "in cooldown", which pointed users at `/agy clear-cooldown` for
4826
+ * a state that command did not touch.
4827
+ */
4828
+ explainIneligibility(acc, family, now = Date.now()) {
4829
+ if (!acc.enabled) return "disabled";
4830
+ if (acc.authRequired) return "auth";
4831
+ const cd = acc.cooldowns?.[family];
4832
+ if (cd && cd.cooldownUntil > now) return "cooldown";
4833
+ if (this.isQuotaBenched(acc, family, now)) return "quota";
4834
+ return null;
4835
+ }
4836
+ /**
4837
+ * Check whether an account is eligible to serve requests for the given family.
4838
+ */
4839
+ isAccountEligible(acc, family, now = Date.now()) {
4840
+ return this.explainIneligibility(acc, family, now) === null;
4809
4841
  }
4810
4842
  /**
4811
4843
  * Returns the currently active and healthy account ID.
@@ -4908,7 +4940,8 @@ var AccountPoolManager = class {
4908
4940
  const isExhausted5h = typeof info.remainingFraction === "number" && info.remainingFraction <= .1 && (!info.resetTime || Number.isNaN(Date.parse(info.resetTime)) || Date.parse(info.resetTime) > now);
4909
4941
  const isExhaustedWeekly = typeof info.weeklyFraction === "number" && info.weeklyFraction <= .05 && (!info.weeklyResetTime || Number.isNaN(Date.parse(info.weeklyResetTime)) || Date.parse(info.weeklyResetTime) > now);
4910
4942
  if (isExhausted5h || isExhaustedWeekly) {
4911
- if (this.data.activeAccountIds?.[famKey] === id || this.data.lastActiveAccountId === id) this.advanceAccount(id, famKey);
4943
+ const clearedAt = acc.quotaGateClearedAt?.[famKey];
4944
+ if (!(clearedAt !== void 0 && (info.updatedAt ?? 0) <= clearedAt) && (this.data.activeAccountIds?.[famKey] === id || this.data.lastActiveAccountId === id)) this.advanceAccount(id, famKey);
4912
4945
  }
4913
4946
  }
4914
4947
  this.persist();
@@ -4988,18 +5021,36 @@ var AccountPoolManager = class {
4988
5021
  acc.dedicatedGroups = acc.dedicatedGroups.filter((f) => f !== family);
4989
5022
  this.persist();
4990
5023
  }
4991
- clearCooldown(id, family) {
4992
- if (id) {
4993
- const acc = this.getAccount(id);
4994
- if (!acc) return;
4995
- acc.cooldowns ??= {};
4996
- if (family) delete acc.cooldowns[family];
4997
- else acc.cooldowns = {};
4998
- } else for (const acc of this.data.accounts) {
5024
+ /**
5025
+ * Reset cooldown timers.
5026
+ *
5027
+ * `includeQuotaBench` (set by the user-facing `/agy clear-cooldown` command
5028
+ * and its HTTP twin) ALSO lifts the proactive low-quota rotation for the
5029
+ * cached snapshot. The override records that snapshot's `updatedAt`, so the
5030
+ * safety gate re-arms as soon as a poll produces fresher data. Internal
5031
+ * callers (orphan release, CLI quota cleanup) leave it off: they only mean to
5032
+ * drop a 429 timer.
5033
+ */
5034
+ clearCooldown(id, family, includeQuotaBench = false) {
5035
+ const now = Date.now();
5036
+ const clearOne = (acc) => {
4999
5037
  acc.cooldowns ??= {};
5000
5038
  if (family) delete acc.cooldowns[family];
5001
5039
  else acc.cooldowns = {};
5002
- }
5040
+ if (!includeQuotaBench) return;
5041
+ const families = family ? [family] : Object.keys(acc.quotas ?? {});
5042
+ if (families.length === 0) return;
5043
+ acc.quotaGateClearedAt ??= {};
5044
+ for (const fam of families) {
5045
+ const updatedAt = acc.quotas?.[fam]?.updatedAt;
5046
+ acc.quotaGateClearedAt[fam] = Math.max(now, updatedAt ?? 0);
5047
+ }
5048
+ };
5049
+ if (id) {
5050
+ const acc = this.getAccount(id);
5051
+ if (!acc) return;
5052
+ clearOne(acc);
5053
+ } else for (const acc of this.data.accounts) clearOne(acc);
5003
5054
  this.persist();
5004
5055
  }
5005
5056
  /**
@@ -5077,6 +5128,8 @@ var AccountPoolManager = class {
5077
5128
  if (cd && cd.cooldownUntil > now) bump(cd.cooldownUntil);
5078
5129
  const quota = acc.quotas?.[family];
5079
5130
  if (quota === void 0) continue;
5131
+ const clearedAt = acc.quotaGateClearedAt?.[family];
5132
+ if (clearedAt !== void 0 && (quota.updatedAt ?? 0) <= clearedAt) continue;
5080
5133
  const drained5h = typeof quota.remainingFraction === "number" && quota.remainingFraction <= .1 && typeof quota.resetTime === "string" && Date.parse(quota.resetTime) > now;
5081
5134
  const drainedWeekly = typeof quota.weeklyFraction === "number" && quota.weeklyFraction <= .05 && typeof quota.weeklyResetTime === "string" && Date.parse(quota.weeklyResetTime) > now;
5082
5135
  if (drained5h || drainedWeekly) bump(this.nextQuotaResetAt(acc, family));
@@ -30855,8 +30908,17 @@ async function waitForRunSettle(run, timeoutMs) {
30855
30908
  }
30856
30909
  return run.isSettled;
30857
30910
  }
30911
+ function calcPromptTokens(usage) {
30912
+ if (!usage) return void 0;
30913
+ const input = typeof usage.input_tokens === "number" && usage.input_tokens > 0 ? usage.input_tokens : 0;
30914
+ const cacheRead = typeof usage.cache_read_tokens === "number" && usage.cache_read_tokens > 0 ? usage.cache_read_tokens : 0;
30915
+ const cacheWrite = typeof usage.cache_write_tokens === "number" && usage.cache_write_tokens > 0 ? usage.cache_write_tokens : 0;
30916
+ const totalPrompt = input + cacheRead + cacheWrite;
30917
+ return totalPrompt > 0 ? totalPrompt : void 0;
30918
+ }
30858
30919
  var AgyAdapter = class AgyAdapter extends LlmAdapter {
30859
30920
  deps;
30921
+ recentlyCompactedSessions = /* @__PURE__ */ new Map();
30860
30922
  /**
30861
30923
  * Models agy has refused `--effort` for (issue #67). Seeded from the host's
30862
30924
  * persisted list on first use, then grown by each refusal. Effort support is
@@ -31406,7 +31468,9 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31406
31468
  const allAccounts = pool.getAccounts();
31407
31469
  const accounts = allAccounts.filter((a) => a.enabled);
31408
31470
  const disabled = allAccounts.length - accounts.length;
31409
- const cooling = accounts.filter((a) => pool.isAccountEligible(a, family) === false && !a.authRequired).length;
31471
+ const reasons = accounts.map((a) => typeof pool.explainIneligibility === "function" ? pool.explainIneligibility(a, family) : pool.isAccountEligible(a, family) ? null : "cooldown");
31472
+ const cooling = reasons.filter((r) => r === "cooldown").length;
31473
+ const quotaBlocked = reasons.filter((r) => r === "quota").length;
31410
31474
  const signedOut = accounts.filter((a) => a.authRequired === true).length;
31411
31475
  const countdown = pool.getEarliestAvailableCountdown?.(family) ?? pool.getEarliestResetCountdown(family);
31412
31476
  if (countdown !== null && countdown > 0 && countdown <= 2e4) {
@@ -31420,13 +31484,14 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31420
31484
  else {
31421
31485
  const details = [];
31422
31486
  if (cooling > 0) details.push(`${cooling} in cooldown`);
31487
+ if (quotaBlocked > 0) details.push(`${quotaBlocked} quota-exhausted`);
31423
31488
  if (signedOut > 0) details.push(`${signedOut} signed out`);
31424
31489
  if (disabled > 0) details.push(`${disabled} disabled`);
31425
31490
  const detailStr = details.length > 0 ? ` (${details.join(", ")})` : "";
31426
31491
  why = `no account can serve ${family} right now${detailStr}`;
31427
31492
  }
31428
31493
  const waitStr = countdown !== null && countdown > 0 ? ` (earliest reset in ${Math.ceil(countdown / 1e3)}s)` : "";
31429
- throw new LlmError(`All Antigravity accounts are unavailable: ${why}${waitStr}. Add an account, wait for reset, or run /agy clear-cooldown.`, Err.AGY_ERROR);
31494
+ throw new LlmError(`All Antigravity accounts are unavailable: ${why}${waitStr}. ${quotaBlocked > 0 && cooling === 0 ? "Add an account, wait for the quota reset, or run /agy clear-cooldown to override the current quota snapshot." : "Add an account, wait for reset, or run /agy clear-cooldown."}`, Err.AGY_ERROR);
31430
31495
  }
31431
31496
  }
31432
31497
  }
@@ -31459,7 +31524,9 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31459
31524
  if (sessionAccountKey !== "") this.deps.store.delete(sessionAccountKey);
31460
31525
  binding = void 0;
31461
31526
  }
31462
- const isCompacted = binding !== void 0 && (messages.length <= 4 && binding.lastMessageCount >= 5 || binding.lastMessageCount > 10 && messages.length < Math.floor(binding.lastMessageCount * .8) || binding.lastMessageCount <= 10 && messages.length < binding.lastMessageCount - 2);
31527
+ const lastCompactedAt = sessionKey ? this.recentlyCompactedSessions.get(sessionKey) : void 0;
31528
+ const now = Date.now();
31529
+ const isCompacted = binding !== void 0 && (!lastCompactedAt || now - lastCompactedAt > 6e4) && (messages.length <= 4 && binding.lastMessageCount >= 5 || binding.lastMessageCount > 10 && messages.length < Math.floor(binding.lastMessageCount * .8) || binding.lastMessageCount <= 10 && messages.length < binding.lastMessageCount - 2);
31463
31530
  let compactionNotice = void 0;
31464
31531
  if (persistBinding && binding !== void 0 && isCompacted) {
31465
31532
  const beforeTokens = typeof binding.lastInputTokens === "number" && binding.lastInputTokens > 0 ? binding.lastInputTokens : Math.round(binding.lastMessageCount * 750);
@@ -31481,7 +31548,13 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31481
31548
  items,
31482
31549
  ...extractedSummary ? { summary: extractedSummary } : {}
31483
31550
  };
31484
- if (sessionAccountKey !== "") this.deps.store.delete(sessionAccountKey);
31551
+ if (sessionKey) {
31552
+ this.recentlyCompactedSessions.set(sessionKey, now);
31553
+ if (this.recentlyCompactedSessions.size > 200) {
31554
+ for (const [k, t] of this.recentlyCompactedSessions) if (now - t > 12e4) this.recentlyCompactedSessions.delete(k);
31555
+ }
31556
+ for (const k of Object.keys(this.deps.store.all())) if (k === sessionKey || k.startsWith(sessionKey + ":")) this.deps.store.delete(k);
31557
+ } else if (sessionAccountKey !== "") this.deps.store.delete(sessionAccountKey);
31485
31558
  binding = void 0;
31486
31559
  } else if (binding !== void 0 && messages.length < binding.lastMessageCount) {
31487
31560
  binding.lastMessageCount = messages.length;
@@ -32052,7 +32125,7 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
32052
32125
  const finalId = binding !== void 0 ? binding.conversationId : conversationId;
32053
32126
  if (finalId) {
32054
32127
  const finalUsage = rec.lastUsage ?? rec.finalUsage({});
32055
- const inputTokens = typeof finalUsage?.input_tokens === "number" && finalUsage.input_tokens > 0 ? finalUsage.input_tokens : binding?.lastInputTokens;
32128
+ const inputTokens = calcPromptTokens(finalUsage) ?? (typeof finalUsage?.input_tokens === "number" && finalUsage.input_tokens > 0 ? finalUsage.input_tokens : binding?.lastInputTokens);
32056
32129
  this.deps.store.set(sessionAccountKey, {
32057
32130
  conversationId: finalId,
32058
32131
  lastMessageCount: messages.length,
@@ -32081,7 +32154,7 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
32081
32154
  const finalId = binding !== void 0 ? binding.conversationId : conversationId;
32082
32155
  if (finalId) {
32083
32156
  const finalUsage = rec.lastUsage ?? rec.finalUsage({});
32084
- const inputTokens = typeof finalUsage?.input_tokens === "number" && finalUsage.input_tokens > 0 ? finalUsage.input_tokens : binding?.lastInputTokens;
32157
+ const inputTokens = calcPromptTokens(finalUsage) ?? (typeof finalUsage?.input_tokens === "number" && finalUsage.input_tokens > 0 ? finalUsage.input_tokens : binding?.lastInputTokens);
32085
32158
  this.deps.store.set(sessionAccountKey, {
32086
32159
  conversationId: finalId,
32087
32160
  lastMessageCount: messages.length,
@@ -33001,7 +33074,7 @@ const HELP$1 = [
33001
33074
  "- `/agy enable-account <id>` — enable an account slot",
33002
33075
  "- `/agy disable-account <id>` — disable an account slot (skips in rotation)",
33003
33076
  "- `/agy refresh-quota` — query Google backend for fresh quota %",
33004
- "- `/agy clear-cooldown` — reset cooldown timers across all accounts",
33077
+ "- `/agy clear-cooldown` — reset cooldown timers (and any active low-quota bench)",
33005
33078
  "- `/agy remove-account <id>` — delete an account slot",
33006
33079
  "- `/agy auth` — Google login for the primary account (opens the browser)",
33007
33080
  "- `/agy auth-code <code>` — finish login by pasting the code (fallback)",
@@ -33088,8 +33161,8 @@ async function handle$1(deps, raw, invocation) {
33088
33161
  if (sub === "clear-cooldown") {
33089
33162
  const pool = deps.pool?.();
33090
33163
  if (!pool) return err$1("Account pool not available");
33091
- pool.clearCooldown(arg || void 0);
33092
- return ok$1("Cleared cooldown timers.");
33164
+ pool.clearCooldown(arg || void 0, void 0, true);
33165
+ return ok$1("Cleared cooldown timers and any active low-quota bench (until the next quota refresh).");
33093
33166
  }
33094
33167
  if (sub === "remove-account") {
33095
33168
  if (!arg) return err$1("usage: /agy remove-account <id>");
@@ -35588,18 +35661,22 @@ var QuotaService = class {
35588
35661
  });
35589
35662
  const isStale = stale5hFamilies.has(fam);
35590
35663
  if (!familyQuotas[fam]) {
35591
- familyQuotas[fam] = pickFamilyQuota(account.quotas[fam], {
35664
+ if (fam === "argon") familyQuotas.argon = {
35665
+ ...account.quotas.argon ?? {},
35666
+ remainingFraction: void 0,
35667
+ resetTime: void 0,
35668
+ weeklyFraction: remaining,
35669
+ weeklyResetTime: resetTime,
35670
+ updatedAt: now
35671
+ };
35672
+ else familyQuotas[fam] = pickFamilyQuota(account.quotas[fam], {
35592
35673
  remainingFraction: remaining,
35593
35674
  resetTime,
35594
35675
  updatedAt: now
35595
35676
  }, summaryGroups.length > 0);
35596
- if (fam === "argon" && familyQuotas[fam].weeklyFraction === void 0) {
35597
- familyQuotas[fam].weeklyFraction = remaining;
35598
- familyQuotas[fam].weeklyResetTime = resetTime;
35599
- }
35600
35677
  } else {
35601
35678
  const familyQuota = familyQuotas[fam];
35602
- if (sameQuotaWindow(resetTime, familyQuota.weeklyResetTime) && !sameQuotaWindow(resetTime, familyQuota.resetTime)) {
35679
+ if (fam === "argon" && familyQuota.resetTime === void 0 || sameQuotaWindow(resetTime, familyQuota.weeklyResetTime) && !sameQuotaWindow(resetTime, familyQuota.resetTime)) {
35603
35680
  if (remaining < (familyQuota.weeklyFraction ?? 1)) {
35604
35681
  familyQuota.weeklyFraction = remaining;
35605
35682
  familyQuota.weeklyResetTime = resetTime;
@@ -35622,18 +35699,17 @@ var QuotaService = class {
35622
35699
  if (familyQuotas[fam]) familyQuotas[fam].models = list;
35623
35700
  }
35624
35701
  if (summaryGroups.length > 0) {
35625
- if (summaryHasArgonGroup(summaryGroups) || familyQuotas.argon) this.pool.noteDedicatedGroup(account.id, "argon");
35702
+ if (summaryHasArgonGroup(summaryGroups)) this.pool.noteDedicatedGroup(account.id, "argon");
35626
35703
  else {
35627
- this.pool.clearQuotaFamily(account.id, "argon");
35704
+ const groupSeenBefore = this.pool.hasDedicatedGroup(account.id, "argon");
35705
+ if (familyQuotas.argon === void 0) this.pool.clearQuotaFamily(account.id, "argon");
35628
35706
  if (shouldReleaseOrphanedCooldown({
35629
35707
  summaryAuthoritative: true,
35630
35708
  groupPresent: false,
35631
- groupSeenBefore: this.pool.hasDedicatedGroup(account.id, "argon"),
35709
+ groupSeenBefore,
35632
35710
  hasCooldown: account.cooldowns?.argon !== void 0
35633
- })) {
35634
- this.pool.forgetDedicatedGroup(account.id, "argon");
35635
- this.pool.clearCooldown(account.id, "argon");
35636
- }
35711
+ })) this.pool.clearCooldown(account.id, "argon");
35712
+ this.pool.forgetDedicatedGroup(account.id, "argon");
35637
35713
  }
35638
35714
  }
35639
35715
  this.pool.updateAccountQuotas(account.id, familyQuotas, email);
@@ -37708,7 +37784,7 @@ function apply(ctx, entryConfig = {}) {
37708
37784
  const body = await readBody(req);
37709
37785
  const id = typeof body.id === "string" ? body.id : void 0;
37710
37786
  const family = typeof body.family === "string" ? body.family : void 0;
37711
- pool.clearCooldown(id, family);
37787
+ pool.clearCooldown(id, family, true);
37712
37788
  sendJson(res, 200, {
37713
37789
  ok: true,
37714
37790
  pool: pool.getPoolData()
@@ -226,4 +226,4 @@ All host routes are namespaced under `/plugins/agy-link/`:
226
226
  - `/agy add-account [alias]`: Start terminal-guided OAuth login for a new account slot.
227
227
  - `/agy refresh-quota [id]`: Fetch fresh quota percentages from Google backend.
228
228
  - `/agy remove-account <id>`: Delete an account slot.
229
- - `/agy clear-cooldown [id]`: Manually reset cooldown timers for accounts.
229
+ - `/agy clear-cooldown [id]`: Manually reset cooldown timers for accounts. It also lifts the proactive low-quota bench for the cached quota snapshot; the bench re-arms as soon as a quota refresh writes newer data.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agy-link",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
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",