dsh-agy-link 0.5.7 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0 (2026-11-05)
4
+
5
+ ### English
6
+
7
+ - **Feat(client): DeepSeek-parity context-compaction card with token-delta metrics.** (thanks @Ronnoc, #74)
8
+ - Compaction was invisible: ADR-013 cleared stale bindings and re-seeded agy with a digest, but the conversation showed nothing. `renderCompactionMarker()` now emits a markdown-safe marker at the first compacted turn carrying `beforeTokens/afterTokens/items` plus a percent-encoded digest, and `scanAndEnhanceCompactionCards()` upgrades it to a native-style collapsible card (`上下文已压缩 · 128.5k → 14.2k tokens (-89%)`). Token accounting is persisted per session (`lastInputTokens`) so the "before" figure is the real pre-compaction occupancy. In plain markdown/headless it degrades to a blockquote.
9
+ - Hardening on merge: the digest is only decoded behind a `try/catch` (a mangled percent-encoding now degrades to "no digest" instead of aborting the marker scan), and the digest text reaches the DOM via `textContent` only.
10
+
11
+ ### 中文
12
+
13
+ - **新增(client):对齐 DeepSeek 原生的「上下文已压缩」卡片,附 token 变化指标。**(感谢 @Ronnoc,#74)
14
+ - 此前压缩过程不可见:ADR-013 会清理旧绑定并用摘要重播种 agy,但会话里没有任何提示。`renderCompactionMarker()` 现在在首个压缩回合注入 markdown 安全的标记(含压缩前/后 token、条目数、百分号编码的摘要),`scanAndEnhanceCompactionCards()` 将其升级为原生风格可折叠卡片(`上下文已压缩 · 128.5k → 14.2k tokens (-89%)`)。会话内持久化 `lastInputTokens` 使「压缩前」是真实占用值;纯 markdown/无头环境降级为引用块。
15
+ - 合并时加固:摘要解码置于 `try/catch`(畸形百分号编码降级为「无摘要」而非中断扫描),摘要正文仅通过 `textContent` 进入 DOM。
16
+
17
+ **Full Changelog**: https://github.com/amlyczz/dsh-agy-link/compare/v0.5.7...v0.6.0
18
+
3
19
  ## 0.5.7 (2026-11-05)
4
20
 
5
21
  ### English
package/dist/client.js CHANGED
@@ -981,7 +981,7 @@ window.__ModuleLoader__.load({
981
981
  white-space: nowrap;
982
982
  }
983
983
  `;
984
- function injectStyles$4() {
984
+ function injectStyles$5() {
985
985
  if (typeof document === "undefined") return;
986
986
  const styleId = "dsh-agy-link-decisions-css";
987
987
  if (document.getElementById(styleId) === null) {
@@ -1142,7 +1142,7 @@ window.__ModuleLoader__.load({
1142
1142
  function installDecisionChips() {
1143
1143
  if (typeof window === "undefined" || typeof document === "undefined") return () => {};
1144
1144
  decisionChipsDispose?.();
1145
- injectStyles$4();
1145
+ injectStyles$5();
1146
1146
  const observer = new MutationObserver(() => {
1147
1147
  scheduleDecisionScan();
1148
1148
  });
@@ -1367,7 +1367,7 @@ window.__ModuleLoader__.load({
1367
1367
  pointer-events: none;
1368
1368
  }
1369
1369
  `;
1370
- function injectStyles$3() {
1370
+ function injectStyles$4() {
1371
1371
  if (typeof document === "undefined") return;
1372
1372
  const styleId = "dsh-agy-link-images-css";
1373
1373
  if (document.getElementById(styleId) === null) {
@@ -1391,7 +1391,7 @@ window.__ModuleLoader__.load({
1391
1391
  */
1392
1392
  function openLightbox(src, title = "Image Preview", rawPath) {
1393
1393
  if (typeof document === "undefined") return;
1394
- injectStyles$3();
1394
+ injectStyles$4();
1395
1395
  if (lightboxOverlay) {
1396
1396
  lightboxOverlay.remove();
1397
1397
  lightboxOverlay = null;
@@ -1646,7 +1646,7 @@ window.__ModuleLoader__.load({
1646
1646
  function installImageEnhancer() {
1647
1647
  if (typeof window === "undefined" || typeof document === "undefined") return () => {};
1648
1648
  imageEnhancerDispose?.();
1649
- injectStyles$3();
1649
+ injectStyles$4();
1650
1650
  const observer = new MutationObserver(() => {
1651
1651
  scheduleImageScan();
1652
1652
  });
@@ -3419,7 +3419,7 @@ body > [id^="iagy-mmd"] .error-icon {
3419
3419
  let loadFailedAt = 0;
3420
3420
  const LOAD_RETRY_MS = 6e4;
3421
3421
  let renderSeq = 0;
3422
- function injectStyles$2() {
3422
+ function injectStyles$3() {
3423
3423
  if (typeof document === "undefined") return;
3424
3424
  if (document.getElementById("agy-mermaid-css")) return;
3425
3425
  const st = document.createElement("style");
@@ -3779,7 +3779,7 @@ body > [id^="iagy-mmd"] .error-icon {
3779
3779
  function installMermaidRendering() {
3780
3780
  if (typeof window === "undefined" || typeof document === "undefined") return () => {};
3781
3781
  disposeMermaidRendering();
3782
- injectStyles$2();
3782
+ injectStyles$3();
3783
3783
  cleanupTempElements();
3784
3784
  const observer = new MutationObserver(() => {
3785
3785
  scheduleScan$1();
@@ -3868,7 +3868,7 @@ div[data-variant="think"] [class*="thinkBody"] {
3868
3868
  font-family: inherit;
3869
3869
  }
3870
3870
  `;
3871
- function injectStyles$1() {
3871
+ function injectStyles$2() {
3872
3872
  if (typeof document === "undefined") return;
3873
3873
  const styleId = "dsh-agy-link-reasoning-css";
3874
3874
  if (document.getElementById(styleId) === null) {
@@ -3958,7 +3958,7 @@ div[data-variant="think"] [class*="thinkBody"] {
3958
3958
  function installAutoExpandReasoning() {
3959
3959
  if (typeof window === "undefined" || typeof document === "undefined") return () => {};
3960
3960
  disposeAutoExpandReasoning();
3961
- injectStyles$1();
3961
+ injectStyles$2();
3962
3962
  const observer = new MutationObserver(() => {
3963
3963
  scheduleScan();
3964
3964
  });
@@ -4146,7 +4146,7 @@ body.dark .agy-tsl-card,
4146
4146
  .agy-tsl-tip { animation: none; }
4147
4147
  }
4148
4148
  `;
4149
- function injectStyles() {
4149
+ function injectStyles$1() {
4150
4150
  if (typeof document === "undefined") return;
4151
4151
  const doc = win$1.document;
4152
4152
  if (doc === null || doc === void 0) return;
@@ -4699,7 +4699,7 @@ body.dark .agy-tsl-card,
4699
4699
  }
4700
4700
  /** Mount the card renderer, the event Definition and both affordances. */
4701
4701
  function installTranslationUi(ctx, localeNs) {
4702
- injectStyles();
4702
+ injectStyles$1();
4703
4703
  const disposers = [];
4704
4704
  const conversation = service(ctx, "uiConversation");
4705
4705
  if (conversation?.events !== void 0 && typeof conversation.events.register === "function") try {
@@ -4739,6 +4739,311 @@ body.dark .agy-tsl-card,
4739
4739
  };
4740
4740
  }
4741
4741
  //#endregion
4742
+ //#region src/common/compaction.ts
4743
+ /** Format a raw token count into human-friendly string like 128.5k, 14.2k, 1.2M, 500. */
4744
+ function formatTokenCount(tokens) {
4745
+ if (typeof tokens !== "number" || !Number.isFinite(tokens) || tokens <= 0) return "0";
4746
+ if (tokens >= 1e6) return `${(tokens / 1e6).toFixed(1).replace(/\.0$/, "")}M`;
4747
+ if (tokens >= 1e3) return `${(tokens / 1e3).toFixed(1).replace(/\.0$/, "")}k`;
4748
+ return String(Math.round(tokens));
4749
+ }
4750
+ /** Calculate percentage reduction, e.g. "-89%". */
4751
+ function calcTokenReduction(before, after) {
4752
+ if (before <= 0 || after >= before) return "-0%";
4753
+ return `-${Math.round((before - after) / before * 100)}%`;
4754
+ }
4755
+ /** Format the summary string, e.g. "128.5k → 14.2k tokens (-89%)". */
4756
+ function formatCompactionSummary(before, after) {
4757
+ return `${formatTokenCount(before)} → ${formatTokenCount(after)} tokens (${calcTokenReduction(before, after)})`;
4758
+ }
4759
+ //#endregion
4760
+ //#region src/client/compaction.ts
4761
+ const COMPACTION_CSS = `
4762
+ .agy-compaction-row {
4763
+ --dsh-compaction-header-height: calc(24px + var(--dsh-content-font-delta, 0px));
4764
+ padding: 2px 0;
4765
+ margin: 6px 0;
4766
+ font-family: inherit;
4767
+ }
4768
+
4769
+ .agy-compaction-button {
4770
+ width: 100%;
4771
+ height: var(--dsh-compaction-header-height);
4772
+ border-radius: var(--dsw-radius-sm, 4px);
4773
+ min-width: 0;
4774
+ color: var(--dsw-alias-label-tertiary, #888);
4775
+ font: inherit;
4776
+ font-size: var(--dsh-content-font-size-secondary, 12px);
4777
+ text-align: left;
4778
+ background: transparent;
4779
+ border: none;
4780
+ align-items: center;
4781
+ padding: 0 4px;
4782
+ transition: color 0.1s ease, background 0.1s ease;
4783
+ display: flex;
4784
+ cursor: pointer;
4785
+ box-sizing: border-box;
4786
+ }
4787
+
4788
+ .agy-compaction-button:hover {
4789
+ color: var(--dsw-alias-label-secondary, #ccc);
4790
+ background: var(--dsw-alias-interactive-bg-hover, rgba(127, 127, 127, 0.08));
4791
+ }
4792
+
4793
+ .agy-compaction-row[data-state="expanded"] .agy-compaction-button {
4794
+ position: sticky;
4795
+ top: 0;
4796
+ z-index: 7;
4797
+ background: var(--dsw-alias-bg-base, #1e1e1e);
4798
+ border-radius: 0;
4799
+ }
4800
+
4801
+ .agy-compaction-leading {
4802
+ width: calc(16px + var(--dsh-content-font-delta, 0px));
4803
+ height: calc(16px + var(--dsh-content-font-delta, 0px));
4804
+ color: inherit;
4805
+ flex: none;
4806
+ place-items: center;
4807
+ margin-right: 6px;
4808
+ display: inline-grid;
4809
+ }
4810
+
4811
+ .agy-compaction-leading svg {
4812
+ width: calc(14px + var(--dsh-content-font-delta, 0px));
4813
+ height: calc(14px + var(--dsh-content-font-delta, 0px));
4814
+ }
4815
+
4816
+ .agy-compaction-icon-context,
4817
+ .agy-compaction-icon-chevron {
4818
+ grid-area: 1/1;
4819
+ justify-content: center;
4820
+ align-items: center;
4821
+ display: inline-flex;
4822
+ transition: opacity 0.12s ease, transform 0.12s ease;
4823
+ }
4824
+
4825
+ .agy-compaction-icon-chevron {
4826
+ opacity: 0;
4827
+ }
4828
+
4829
+ .agy-compaction-button:hover .agy-compaction-icon-context {
4830
+ opacity: 0;
4831
+ }
4832
+
4833
+ .agy-compaction-button:hover .agy-compaction-icon-chevron {
4834
+ opacity: 1;
4835
+ }
4836
+
4837
+ .agy-compaction-row[data-state="expanded"] .agy-compaction-icon-context {
4838
+ opacity: 0;
4839
+ }
4840
+
4841
+ .agy-compaction-row[data-state="expanded"] .agy-compaction-icon-chevron {
4842
+ opacity: 1;
4843
+ transform: rotate(90deg);
4844
+ }
4845
+
4846
+ .agy-compaction-title {
4847
+ font-weight: 500;
4848
+ color: var(--dsw-alias-label-secondary, #aaa);
4849
+ }
4850
+
4851
+ .agy-compaction-sep {
4852
+ margin: 0 6px;
4853
+ color: var(--dsw-alias-label-tertiary, #666);
4854
+ }
4855
+
4856
+ .agy-compaction-summary {
4857
+ color: var(--dsw-alias-label-tertiary, #888);
4858
+ font-size: var(--dsh-content-font-size-secondary, 12px);
4859
+ overflow: hidden;
4860
+ text-overflow: ellipsis;
4861
+ white-space: nowrap;
4862
+ }
4863
+
4864
+ .agy-compaction-body {
4865
+ padding: 10px 14px;
4866
+ margin-top: 4px;
4867
+ border-radius: var(--dsw-radius-sm, 6px);
4868
+ background: var(--dsw-alias-bg-l1, rgba(127, 127, 127, 0.05));
4869
+ border: 1px solid var(--dsw-alias-border-l1, rgba(127, 127, 127, 0.15));
4870
+ color: var(--dsw-alias-label-secondary, #ccc);
4871
+ font-size: 13px;
4872
+ line-height: 1.6;
4873
+ }
4874
+
4875
+ .agy-compaction-metrics-bar {
4876
+ display: flex;
4877
+ align-items: center;
4878
+ gap: 8px;
4879
+ padding-bottom: 8px;
4880
+ margin-bottom: 8px;
4881
+ border-bottom: 1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.15));
4882
+ font-size: 12px;
4883
+ }
4884
+
4885
+ .agy-metric-item {
4886
+ color: var(--dsw-alias-label-secondary, #bbb);
4887
+ }
4888
+
4889
+ .agy-metric-arrow {
4890
+ color: var(--dsw-alias-label-tertiary, #666);
4891
+ font-weight: 600;
4892
+ }
4893
+
4894
+ .agy-metric-badge {
4895
+ background: rgba(16, 185, 129, 0.15);
4896
+ color: #10b981;
4897
+ font-weight: 600;
4898
+ padding: 1px 6px;
4899
+ border-radius: 4px;
4900
+ font-size: 11px;
4901
+ }
4902
+
4903
+ .agy-compaction-summary-text {
4904
+ white-space: pre-wrap;
4905
+ word-break: break-word;
4906
+ }
4907
+ `;
4908
+ function injectStyles() {
4909
+ if (typeof document === "undefined") return;
4910
+ const styleId = "dsh-agy-link-compaction-css";
4911
+ if (document.getElementById(styleId) === null) {
4912
+ const st = document.createElement("style");
4913
+ st.id = styleId;
4914
+ st.textContent = COMPACTION_CSS;
4915
+ const host = document.head ?? document.documentElement;
4916
+ if (host) host.appendChild(st);
4917
+ }
4918
+ }
4919
+ /** Check if document language is Chinese or English. */
4920
+ function getCompactionTitle() {
4921
+ if (typeof document !== "undefined") {
4922
+ if ((document.documentElement.lang || "").startsWith("en")) return "Context compacted";
4923
+ }
4924
+ return "上下文已压缩";
4925
+ }
4926
+ /**
4927
+ * Scan DOM for `.agy-compaction-card` markers and transform them into
4928
+ * the interactive DeepSeek-like Compaction Card.
4929
+ */
4930
+ function scanAndEnhanceCompactionCards(root = document) {
4931
+ if (typeof document === "undefined") return;
4932
+ if (isInteractionLocked()) return;
4933
+ const cards = root.querySelectorAll(".agy-compaction-card:not([data-agy-compaction-rendered=\"true\"])");
4934
+ for (const card of Array.from(cards)) {
4935
+ card.setAttribute("data-agy-compaction-rendered", "true");
4936
+ const beforeTokens = parseInt(card.dataset.before || "0", 10);
4937
+ const afterTokens = parseInt(card.dataset.after || "0", 10);
4938
+ let summary = "";
4939
+ if (card.dataset.summary) try {
4940
+ summary = decodeURIComponent(card.dataset.summary);
4941
+ } catch {
4942
+ summary = "";
4943
+ }
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";
4995
+ });
4996
+ card.replaceChildren(row);
4997
+ row.appendChild(button);
4998
+ row.appendChild(body);
4999
+ }
5000
+ }
5001
+ let compactionDispose = null;
5002
+ let compactionScanTimer = null;
5003
+ let unbindCompactionSettle = null;
5004
+ function scheduleCompactionScan() {
5005
+ if (isInteractionLocked()) return;
5006
+ if (compactionScanTimer !== null) return;
5007
+ compactionScanTimer = setTimeout(() => {
5008
+ compactionScanTimer = null;
5009
+ if (isInteractionLocked()) return;
5010
+ scanAndEnhanceCompactionCards();
5011
+ }, 100);
5012
+ }
5013
+ function installCompactionCard() {
5014
+ if (typeof window === "undefined" || typeof document === "undefined") return () => {};
5015
+ compactionDispose?.();
5016
+ injectStyles();
5017
+ const observer = new MutationObserver(() => {
5018
+ scheduleCompactionScan();
5019
+ });
5020
+ unbindCompactionSettle = onScrollSettle(() => {
5021
+ scheduleCompactionScan();
5022
+ });
5023
+ const setup = () => {
5024
+ if (document.body) {
5025
+ observer.observe(document.body, {
5026
+ childList: true,
5027
+ subtree: true
5028
+ });
5029
+ scanAndEnhanceCompactionCards();
5030
+ }
5031
+ };
5032
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", setup, { once: true });
5033
+ else setup();
5034
+ const dispose = () => {
5035
+ if (compactionScanTimer !== null) {
5036
+ clearTimeout(compactionScanTimer);
5037
+ compactionScanTimer = null;
5038
+ }
5039
+ observer.disconnect();
5040
+ unbindCompactionSettle?.();
5041
+ unbindCompactionSettle = null;
5042
+ };
5043
+ compactionDispose = dispose;
5044
+ return dispose;
5045
+ }
5046
+ //#endregion
4742
5047
  //#region src/client/index.ts
4743
5048
  const { createElement: h, useState, useEffect, useRef } = require("react");
4744
5049
  const reactDom = require("react-dom");
@@ -7524,6 +7829,7 @@ body[data-ds-dark-theme] select.agy-select { color-scheme: dark; }
7524
7829
  ctx.effect(() => installMermaidRendering());
7525
7830
  ctx.effect(() => installImageEnhancer());
7526
7831
  ctx.effect(() => installDecisionChips());
7832
+ ctx.effect(() => installCompactionCard());
7527
7833
  ctx.effect(() => {
7528
7834
  try {
7529
7835
  return installTranslationUi(ctx, NS);
package/dist/index.js CHANGED
@@ -910,6 +910,9 @@ var RunRecording = class {
910
910
  noteStepUsage(raw) {
911
911
  this.lastStepUsageRaw = raw;
912
912
  }
913
+ get lastUsage() {
914
+ return this.lastStepUsageRaw;
915
+ }
913
916
  /** The usage to report for the result envelope: last per-call step sample. */
914
917
  finalUsage(resultRaw) {
915
918
  return this.lastStepUsageRaw ?? resultRaw;
@@ -1892,6 +1895,35 @@ function buildPlanExitToolCallBlock(planMarkdown, blockIdx) {
1892
1895
  }];
1893
1896
  }
1894
1897
  //#endregion
1898
+ //#region src/common/compaction.ts
1899
+ /** Format a raw token count into human-friendly string like 128.5k, 14.2k, 1.2M, 500. */
1900
+ function formatTokenCount(tokens) {
1901
+ if (typeof tokens !== "number" || !Number.isFinite(tokens) || tokens <= 0) return "0";
1902
+ if (tokens >= 1e6) return `${(tokens / 1e6).toFixed(1).replace(/\.0$/, "")}M`;
1903
+ if (tokens >= 1e3) return `${(tokens / 1e3).toFixed(1).replace(/\.0$/, "")}k`;
1904
+ return String(Math.round(tokens));
1905
+ }
1906
+ /** Calculate percentage reduction, e.g. "-89%". */
1907
+ function calcTokenReduction(before, after) {
1908
+ if (before <= 0 || after >= before) return "-0%";
1909
+ return `-${Math.round((before - after) / before * 100)}%`;
1910
+ }
1911
+ /** Format the summary string, e.g. "128.5k → 14.2k tokens (-89%)". */
1912
+ function formatCompactionSummary(before, after) {
1913
+ return `${formatTokenCount(before)} → ${formatTokenCount(after)} tokens (${calcTokenReduction(before, after)})`;
1914
+ }
1915
+ /**
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%)
1919
+ * In browser DSH, the client enhancer transforms it into the interactive native Compaction Card.
1920
+ */
1921
+ function renderCompactionMarker(notice) {
1922
+ 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`;
1925
+ }
1926
+ //#endregion
1895
1927
  //#region src/host/mapper.ts
1896
1928
  const toToolCallId = dshLlm.ToolCallId ?? dshLlm.CallId ?? ((id) => id);
1897
1929
  /**
@@ -1962,6 +1994,7 @@ var EventMapper = class {
1962
1994
  finished = false;
1963
1995
  totalTextOutput = "";
1964
1996
  toolCallStates = /* @__PURE__ */ new Map();
1997
+ emittedCompactionNotice = false;
1965
1998
  constructor(opts) {
1966
1999
  this.opts = opts;
1967
2000
  this.sawTextStep = opts.initialSawText === true;
@@ -2062,10 +2095,22 @@ var EventMapper = class {
2062
2095
  }
2063
2096
  }
2064
2097
  }
2098
+ *emitCompactionNoticeIfPending() {
2099
+ if (this.opts.compactionNotice && !this.emittedCompactionNotice) {
2100
+ this.emittedCompactionNotice = true;
2101
+ yield* this.ensureBlock("text");
2102
+ const marker = renderCompactionMarker(this.opts.compactionNotice);
2103
+ const d = this.appendDelta(marker);
2104
+ if (d) yield d;
2105
+ const close = this.closeOpen();
2106
+ if (close) yield close;
2107
+ }
2108
+ }
2065
2109
  *map(ev, absIndex) {
2066
2110
  if (this.finished) return;
2067
2111
  if (ev.kind === "init") return;
2068
2112
  if (ev.kind === "garbage") return;
2113
+ yield* this.emitCompactionNoticeIfPending();
2069
2114
  yield* this.flushBannerOnlyThoughts();
2070
2115
  if (ev.kind === "step") {
2071
2116
  if (ev.usage) this.opts.usage?.noteStepUsage(ev.usage);
@@ -31414,7 +31459,27 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31414
31459
  binding = void 0;
31415
31460
  }
31416
31461
  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);
31462
+ let compactionNotice = void 0;
31417
31463
  if (persistBinding && binding !== void 0 && isCompacted) {
31464
+ const beforeTokens = typeof binding.lastInputTokens === "number" && binding.lastInputTokens > 0 ? binding.lastInputTokens : Math.round(binding.lastMessageCount * 750);
31465
+ const items = Math.max(1, binding.lastMessageCount - messages.length);
31466
+ let extractedSummary = void 0;
31467
+ for (let i = messages.length - 1; i >= 0; i--) {
31468
+ const msg = messages[i];
31469
+ if (!msg) continue;
31470
+ const txt = textOf(msg);
31471
+ const m = /<compacted-summary>([\s\S]*?)<\/compacted-summary>/i.exec(txt);
31472
+ if (m && m[1]) {
31473
+ extractedSummary = m[1].trim();
31474
+ break;
31475
+ }
31476
+ }
31477
+ compactionNotice = {
31478
+ beforeTokens,
31479
+ afterTokens: 0,
31480
+ items,
31481
+ ...extractedSummary ? { summary: extractedSummary } : {}
31482
+ };
31418
31483
  if (sessionAccountKey !== "") this.deps.store.delete(sessionAccountKey);
31419
31484
  binding = void 0;
31420
31485
  } else if (binding !== void 0 && messages.length < binding.lastMessageCount) {
@@ -31506,6 +31571,7 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31506
31571
  }
31507
31572
  if (prompt.trim() === "") throw new LlmError("request carries no user text or images to forward to agy", Err.AGY_ERROR);
31508
31573
  } else if (prompt.trim() === "") throw new LlmError("request carries no user text to forward to agy", Err.AGY_ERROR);
31574
+ if (compactionNotice && compactionNotice.afterTokens <= 0) compactionNotice.afterTokens = Math.max(100, Math.round(prompt.length / 3.5));
31509
31575
  if (!isAux && sessionKey !== "") {
31510
31576
  const now = Date.now();
31511
31577
  if (this.activeSessionPrompts.size > 100) {
@@ -31983,13 +32049,18 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
31983
32049
  this.clearNetworkStreak(sessionKey);
31984
32050
  if (persistBinding && sessionAccountKey !== "" && !superseded) {
31985
32051
  const finalId = binding !== void 0 ? binding.conversationId : conversationId;
31986
- if (finalId) this.deps.store.set(sessionAccountKey, {
31987
- conversationId: finalId,
31988
- lastMessageCount: messages.length,
31989
- updatedAt: Date.now(),
31990
- model: activeModel,
31991
- sentImageIds: mergeSentImageIds(binding?.sentImageIds, newlySentImageIds)
31992
- });
32052
+ if (finalId) {
32053
+ const finalUsage = rec.lastUsage ?? rec.finalUsage({});
32054
+ const inputTokens = typeof finalUsage?.input_tokens === "number" && finalUsage.input_tokens > 0 ? finalUsage.input_tokens : binding?.lastInputTokens;
32055
+ this.deps.store.set(sessionAccountKey, {
32056
+ conversationId: finalId,
32057
+ lastMessageCount: messages.length,
32058
+ updatedAt: Date.now(),
32059
+ model: activeModel,
32060
+ sentImageIds: mergeSentImageIds(binding?.sentImageIds, newlySentImageIds),
32061
+ ...typeof inputTokens === "number" && inputTokens > 0 ? { lastInputTokens: inputTokens } : {}
32062
+ });
32063
+ }
31993
32064
  }
31994
32065
  } else {
31995
32066
  if (account && !outcome.aborted && looksLikeHardRateLimit(rawErrText)) this.deps.pool?.recordFailure(account.id, family, failure.message);
@@ -32007,14 +32078,19 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
32007
32078
  if (persistBinding && sessionAccountKey !== "" && staleConversation) this.deps.store.delete(sessionAccountKey);
32008
32079
  else if (persistBinding && sessionAccountKey !== "" && !superseded) {
32009
32080
  const finalId = binding !== void 0 ? binding.conversationId : conversationId;
32010
- if (finalId) this.deps.store.set(sessionAccountKey, {
32011
- conversationId: finalId,
32012
- lastMessageCount: messages.length,
32013
- updatedAt: Date.now(),
32014
- model: activeModel,
32015
- sentImageIds: mergeSentImageIds(binding?.sentImageIds, []),
32016
- ...interruptedTurn || binding?.interrupted === true ? { interrupted: true } : {}
32017
- });
32081
+ if (finalId) {
32082
+ const finalUsage = rec.lastUsage ?? rec.finalUsage({});
32083
+ const inputTokens = typeof finalUsage?.input_tokens === "number" && finalUsage.input_tokens > 0 ? finalUsage.input_tokens : binding?.lastInputTokens;
32084
+ this.deps.store.set(sessionAccountKey, {
32085
+ conversationId: finalId,
32086
+ lastMessageCount: messages.length,
32087
+ updatedAt: Date.now(),
32088
+ model: activeModel,
32089
+ sentImageIds: mergeSentImageIds(binding?.sentImageIds, []),
32090
+ ...interruptedTurn || binding?.interrupted === true ? { interrupted: true } : {},
32091
+ ...typeof inputTokens === "number" && inputTokens > 0 ? { lastInputTokens: inputTokens } : {}
32092
+ });
32093
+ }
32018
32094
  }
32019
32095
  }
32020
32096
  this.deps.onRun?.({
@@ -32033,7 +32109,7 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
32033
32109
  message: "internal error: " + brief(String(err))
32034
32110
  });
32035
32111
  });
32036
- yield* this.driveSpan(rec, 0, !isAux && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal);
32112
+ yield* this.driveSpan(rec, 0, !isAux && hasToolSupport, isCodeMode, goalContext, supportsGoalUpdate, supportsPlanExit, options.signal, compactionNotice);
32037
32113
  }
32038
32114
  /**
32039
32115
  * Stream one span of a recording: map events from `from` until the mapper
@@ -32042,7 +32118,7 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
32042
32118
  * as this span's terminal chunk — the turn ends exactly like a native
32043
32119
  * provider error.
32044
32120
  */
32045
- async *driveSpan(rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal) {
32121
+ async *driveSpan(rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice) {
32046
32122
  if (signal?.aborted) {
32047
32123
  rec.requestAbort?.();
32048
32124
  yield {
@@ -32060,14 +32136,14 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
32060
32136
  this.deps.runs.remember(rec);
32061
32137
  this.deps.runs.pin(rec.runId);
32062
32138
  try {
32063
- yield* this.driveSpanBody(rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal);
32139
+ yield* this.driveSpanBody(rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice);
32064
32140
  } finally {
32065
32141
  this.deps.runs.unpin(rec.runId);
32066
32142
  this.deps.runs.remember(rec);
32067
32143
  }
32068
32144
  }
32069
32145
  /** Body of {@link driveSpan}: map recorded events until the span finishes. */
32070
- async *driveSpanBody(rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal) {
32146
+ async *driveSpanBody(rec, from, cutOnTool, useCodeWrapper, goalContext, supportsGoalUpdate, supportsPlanExit, signal, compactionNotice) {
32071
32147
  const queue = new ChunkQueue();
32072
32148
  let abortedLocally = false;
32073
32149
  const onAbort = () => {
@@ -32101,7 +32177,8 @@ var AgyAdapter = class AgyAdapter extends LlmAdapter {
32101
32177
  mediaBaseUrl: this.deps.getMediaBaseUrl?.() ?? void 0,
32102
32178
  goalContext,
32103
32179
  supportsGoalUpdate,
32104
- supportsPlanExit
32180
+ supportsPlanExit,
32181
+ compactionNotice: from === 0 ? compactionNotice : void 0
32105
32182
  });
32106
32183
  let i = from;
32107
32184
  const pendingThoughtSteps = /* @__PURE__ */ new Map();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agy-link",
3
- "version": "0.5.7",
3
+ "version": "0.6.0",
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",