@tea-agent/loop-agent 0.51.0-next.2 → 0.51.0-next.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.
Files changed (85) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/shared/pi-context-pressure/checkpoint.js +22 -4
  4. package/dist/shared/pi-context-pressure/compaction-policy.js +5 -1
  5. package/dist/shared/pi-context-pressure/extension.js +40 -5
  6. package/dist/shared/pi-context-pressure/telemetry.js +4 -0
  7. package/dist/worker/console/chat/chat-event-projection.js +5 -0
  8. package/dist/worker/console/chat/compaction-errors.js +1 -1
  9. package/dist/worker/console/chat/context-accounting.js +58 -0
  10. package/dist/worker/console/chat/context-insights.js +95 -35
  11. package/dist/worker/console/chat/context-usage.js +3 -1
  12. package/dist/worker/console/chat/pi-runtime/context-edit.js +11 -3
  13. package/dist/worker/console/chat/pi-runtime.js +19 -3
  14. package/dist/worker/console/chat/routes.js +3 -0
  15. package/dist/worker/console/chat/terminal-routes.js +12 -0
  16. package/dist/worker/console/chat/terminal-sessions.js +6 -0
  17. package/dist/worker/console/chat/vcp-prompt.js +9 -3
  18. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BDoJuIJc.js → abnfDiagram-N423BO3Z-GerMJfMU.js} +1 -1
  19. package/dist/worker/console/static/assets/{arc-BIcO0B1H.js → arc-DHRoAcBA.js} +1 -1
  20. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-DbxnPcOI.js → architectureDiagram-T3A2C74G-Bna7kqEi.js} +1 -1
  21. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-BG4tXH7C.js → blockDiagram-VBNYF7ZC-B8yw7WTX.js} +1 -1
  22. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BaNxGG9H.js → c4Diagram-5PPSVZJV-BaUWiyqi.js} +1 -1
  23. package/dist/worker/console/static/assets/channel-CLhtAowh.js +1 -0
  24. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-BYr2qNac.js → chunk-2GRJ4B5K-D4iZ2ZNv.js} +1 -1
  25. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-D3q2b9W9.js → chunk-2Q5K7J3B-BtQpibwB.js} +1 -1
  26. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-BFsAsJ8z.js → chunk-5RXB4S5H-ez-kfSyS.js} +1 -1
  27. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-Bnp6GtE7.js → chunk-5VM5RSS4-6L4-OV-3.js} +1 -1
  28. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-CzDChmU1.js → chunk-6Q2QTUOP-CPUweABC.js} +1 -1
  29. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-kgZTzZlf.js → chunk-GF5L2VYU-6DTw-5Ov.js} +1 -1
  30. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-Vnt5nEN_.js → chunk-JWPE2WC7-DFAS-DH8.js} +1 -1
  31. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-CENlGfou.js → chunk-KBJHAD2P-Du7LoER5.js} +1 -1
  32. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DS1bOotT.js → chunk-RYQCIY6F-D9UugPlg.js} +1 -1
  33. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-SkFJspnw.js → chunk-XXDRQBXY-BLh5yptc.js} +1 -1
  34. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DB7nfjpK.js +1 -0
  35. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DB7nfjpK.js +1 -0
  36. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BE1OAnpP.js → cose-bilkent-JH36ORCC-DjmHXa8h.js} +1 -1
  37. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BaTDZwL-.js → cynefin-VYW2F7L2-D5jbf1gi.js} +1 -1
  38. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-BRrIdbbw.js → cynefinDiagram-MW4NZA55-BudjeLTi.js} +1 -1
  39. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-B4pDil_r.js → dagre-VZM6K2ZE-6YP-wMO0.js} +1 -1
  40. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DvqFh-9w.js → diagram-7IWD3JNH-CA3LtUAB.js} +1 -1
  41. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-D7me-QwT.js → diagram-B4RE2ZJO-BAjJeYaD.js} +1 -1
  42. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-EahLHu6K.js → diagram-LBJQPF4R-Dh4zb-ds.js} +1 -1
  43. package/dist/worker/console/static/assets/{diagram-Q27KOJAE--S6g2rQZ.js → diagram-Q27KOJAE-aMKj_Gkp.js} +1 -1
  44. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BwqA9gGp.js → diagram-UB23O5K3-D_0_rqQ6.js} +1 -1
  45. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-Bdj6kj6x.js → ebnfDiagram-BXEA7PRR--C9HfGgB.js} +1 -1
  46. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-_Ii2v364.js → erDiagram-JOGREHBK-BuqX0vmt.js} +1 -1
  47. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-LM1yby4D.js → flowDiagram-UKHOOZJN-IneEK8zO.js} +1 -1
  48. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-_MmByUIz.js → ganttDiagram-PKOTCBZU-DK2RiNlb.js} +1 -1
  49. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Be4J6q3D.js → gitGraphDiagram-DS77QQ5N-CuN5z0rP.js} +1 -1
  50. package/dist/worker/console/static/assets/{index-BVMJjujb.css → index-CzfumEW1.css} +1 -1
  51. package/dist/worker/console/static/assets/{index-CpugPRcA.js → index-DS6dteCl.js} +159 -147
  52. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CFRi5O36.js → infoDiagram-6WML65LV-B6enpqSl.js} +1 -1
  53. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-B2OnsVXe.js → ishikawaDiagram-WSZJBQD7-DepH_7eq.js} +1 -1
  54. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Dnz8Ge36.js → journeyDiagram-NVQOT4AX-BftlRwcR.js} +1 -1
  55. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-DFPGjB3O.js → kanban-definition-27J2QSJJ-CEIZMo9g.js} +1 -1
  56. package/dist/worker/console/static/assets/{linear-DrKFn9ZE.js → linear-DkgtGbsw.js} +1 -1
  57. package/dist/worker/console/static/assets/{mermaid.core-C4__OfPT.js → mermaid.core-CIMKKPgL.js} +5 -5
  58. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CMEMeYGS.js → mindmap-definition-FAOFIHXS-dzbp1VuW.js} +1 -1
  59. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BDNDtN72.js → pegDiagram-VL7TDLO6-C5b5i7KO.js} +1 -1
  60. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-DX12wRku.js → pieDiagram-7S7Q4E2Y-Ugdko1lm.js} +1 -1
  61. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-DEzotPpD.js → quadrantDiagram-CIZ2JOQS-B2s1OZu8.js} +1 -1
  62. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BGbCCVjx.js → railroadDiagram-AXF67PYL-BVafp-Z6.js} +1 -1
  63. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-eClVYdkl.js → requirementDiagram-LRYGKXZP-BVxBjdbs.js} +1 -1
  64. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-Hyw3eFyF.js → sankeyDiagram-W5VNT64P-CorSImxl.js} +1 -1
  65. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DwysyBPq.js → sequenceDiagram-SI44F4Z6-eVj3geQV.js} +1 -1
  66. package/dist/worker/console/static/assets/{sheet-workbook-jLtIaGKt.js → sheet-workbook-DNnJDCal.js} +1 -1
  67. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-CsA3-7gH.js → sizeCapture-X5ZJPWSS-OQWfzgrL.js} +1 -1
  68. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-DkUPiKZ8.js → stateDiagram-OKZ733FA-DJr_pPmG.js} +1 -1
  69. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cr-50jJB.js +1 -0
  70. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-qfVo6Xay.js → swimlanes-SLNWSIFB-CQG0Q9vK.js} +2 -2
  71. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-kZpEmem6.js +8 -0
  72. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BRTsFNL5.js → timeline-definition-Z64GVDOM-DxWuWIZ5.js} +1 -1
  73. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BI-btTm3.js → vennDiagram-T6HMQDX7-BJt03ecs.js} +1 -1
  74. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BYMVY4Ov.js → wardleyDiagram-T6FBY63Y-BB3rPfNJ.js} +1 -1
  75. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CvK7yNi0.js → xychartDiagram-ELKLHX3M-aVR9TCu0.js} +1 -1
  76. package/dist/worker/console/static/index.html +2 -2
  77. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +99 -16
  78. package/dist/worker/console/static-src/operator-chat/useChatThread.js +27 -5
  79. package/dist/worker/console/workspace-context.js +3 -0
  80. package/package.json +6 -3
  81. package/dist/worker/console/static/assets/channel-DigIZ6M1.js +0 -1
  82. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-AY-sL87U.js +0 -1
  83. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-AY-sL87U.js +0 -1
  84. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BiXtsN97.js +0 -1
  85. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-ImoXsndy.js +0 -8
package/CHANGELOG.md CHANGED
@@ -24,7 +24,7 @@
24
24
  - 初始化更新会保留有效的项目调度配置,不再因此反复要求合并配置文件。
25
25
  - 需求检查失败时保留逐条判定和审核理由,并准确区分未解决条款与背景说明,便于定位阻塞原因。
26
26
 
27
- ## [0.51.0-next.2] - 2026-10-14
27
+ ## [0.51.0-next.3] - 2026-10-15
28
28
 
29
29
  本预发布快照记录构建时已整理的待发布变化,不表示相对上一构建全部新增。
30
30
 
@@ -48,6 +48,24 @@
48
48
  - 初始化更新会保留有效的项目调度配置,不再因此反复要求合并配置文件。
49
49
  - 需求检查失败时保留逐条判定和审核理由,并准确区分未解决条款与背景说明,便于定位阻塞原因。
50
50
 
51
+ ## [0.50.0] - 2026-10-13
52
+
53
+ ### 重点更新
54
+
55
+ - 对话支持按上下文压力整理较长工具结果,压缩后仍保留可追溯的摘要和恢复信息。
56
+ - VCP 视觉卡片减少内置字体资源并修正样式覆盖,加载更轻,卡片排版更稳定。
57
+
58
+ ### 改进
59
+
60
+ - Console 支持在设置中切换代理或直连,新请求立即使用最新选择。
61
+ - 切换对话后会恢复到最近阅读位置,继续查看最新回复更顺畅。
62
+ - 浏览器自动化默认关闭,需要时可通过明确配置启用。
63
+
64
+ ### 修复
65
+
66
+ - 修复浏览器元素引用过期时缺少当前页面快照和恢复线索的问题。
67
+ - 修复切换会话后版本说明、工作区状态和对话滚动位置偶发丢失的问题。
68
+
51
69
  ## [0.49.0] - 2026-10-11
52
70
 
53
71
  ### 重点更新
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "version": "0.51.0-next.2",
4
- "gitSha": "306c6fab335a5962ff2cee5f528bb934b05468d1",
5
- "builtAt": "2026-10-14T05:42:40.679Z"
3
+ "version": "0.51.0-next.3",
4
+ "gitSha": "70fdc60ee57703e2b0c68bb23cf4930d1c158811",
5
+ "builtAt": "2026-10-14T17:25:52.531Z"
6
6
  }
@@ -1,4 +1,21 @@
1
1
  const CHECKPOINT_MAX_BYTES = 12 * 1024;
2
+ function truncateUtf8(value, maxBytes) {
3
+ if (Buffer.byteLength(value, "utf8") <= maxBytes)
4
+ return value;
5
+ const ellipsis = "…";
6
+ const ellipsisBytes = Buffer.byteLength(ellipsis, "utf8");
7
+ const budget = Math.max(0, maxBytes - ellipsisBytes);
8
+ let result = "";
9
+ let used = 0;
10
+ for (const character of Array.from(value)) {
11
+ const bytes = Buffer.byteLength(character, "utf8");
12
+ if (used + bytes > budget)
13
+ break;
14
+ result += character;
15
+ used += bytes;
16
+ }
17
+ return `${result}${ellipsis}`;
18
+ }
2
19
  function boundText(value, maxChars) {
3
20
  if (typeof value !== "string" || !value.trim())
4
21
  return "";
@@ -92,10 +109,13 @@ export function buildOverflowCheckpoint(input) {
92
109
  if (!firstKeptEntryId || tokensBefore === undefined)
93
110
  return undefined;
94
111
  const sections = [
95
- "Deterministic overflow checkpoint (no extra summary request).",
112
+ "Deterministic local compaction checkpoint (no extra summary request).",
96
113
  boundText(preparation?.previousSummary, 2000)
97
114
  ? `Previous summary:\n${boundText(preparation?.previousSummary, 2000)}`
98
115
  : "",
116
+ boundText(input.customInstructions, 800)
117
+ ? `Compaction instructions:\n${boundText(input.customInstructions, 800)}`
118
+ : "",
99
119
  extractLastUserGoal(preparation?.messagesToSummarize)
100
120
  ? `Latest user goal:\n${extractLastUserGoal(preparation?.messagesToSummarize)}`
101
121
  : "",
@@ -109,8 +129,6 @@ export function buildOverflowCheckpoint(input) {
109
129
  "Next step: continue the interrupted turn from the kept recent messages. Do not repeat completed file writes.",
110
130
  ].filter(Boolean);
111
131
  let summary = sections.join("\n\n");
112
- if (Buffer.byteLength(summary, "utf8") > CHECKPOINT_MAX_BYTES) {
113
- summary = `${summary.slice(0, CHECKPOINT_MAX_BYTES - 1)}…`;
114
- }
132
+ summary = truncateUtf8(summary, CHECKPOINT_MAX_BYTES);
115
133
  return { summary, firstKeptEntryId, tokensBefore };
116
134
  }
@@ -118,9 +118,13 @@ export function applyProcessCompactionOverride(manager, input) {
118
118
  ? deriveEffectiveWindow(input.contextWindow, input.policy)
119
119
  : undefined;
120
120
  const compaction = { enabled };
121
+ if (enabled) {
122
+ compaction.keepRecentTokens = Number.isFinite(input.keepRecentTokens)
123
+ ? Math.max(0, Math.floor(input.keepRecentTokens))
124
+ : DEFAULT_KEEP_RECENT_TOKENS;
125
+ }
121
126
  if (window && enabled) {
122
127
  compaction.reserveTokens = window.recommendedReserve;
123
- compaction.keepRecentTokens = DEFAULT_KEEP_RECENT_TOKENS;
124
128
  }
125
129
  manager.applyOverrides({ compaction });
126
130
  return {
@@ -2,13 +2,16 @@ import { randomUUID } from "node:crypto";
2
2
  import { shouldRewriteAssistantTransientProviderError } from "../pi-provider-recovery.js";
3
3
  import { buildOverflowCheckpoint } from "./checkpoint.js";
4
4
  import { prunePiToolResultMessages, } from "./tool-result-pruner.js";
5
- import { shouldRewriteAssistantOverflow } from "./overflow.js";
5
+ import { isContextOverflow, shouldRewriteAssistantOverflow } from "./overflow.js";
6
6
  import { clearRetrieveBypass, compressProviderPayload, createSiftRetrieveToolDefinition, SIFT_RETRIEVE_TOOL_NAME, } from "./sift-bridge.js";
7
7
  import { emptyContextPressureCounters, incrementCounter, } from "./telemetry.js";
8
8
  export function createCompactionController() {
9
9
  return {
10
10
  proactiveCompaction: false,
11
+ manualCheckpointFallbackArmed: false,
11
12
  pruneArmed: false,
13
+ pruneStatus: undefined,
14
+ pruneDiagnostic: undefined,
12
15
  counters: emptyContextPressureCounters(),
13
16
  };
14
17
  }
@@ -54,6 +57,14 @@ export function createContextPressureExtension(options) {
54
57
  });
55
58
  }
56
59
  if (l2) {
60
+ api.on("session_compact_failed", (event) => {
61
+ if (event.reason === "manual" &&
62
+ !event.aborted &&
63
+ isContextOverflow(event.errorMessage)) {
64
+ options.controller.manualCheckpointFallbackArmed = true;
65
+ }
66
+ return undefined;
67
+ });
57
68
  api.on("session_before_compact", (event) => {
58
69
  const reason = event.reason;
59
70
  if (reason === "overflow") {
@@ -64,13 +75,17 @@ export function createContextPressureExtension(options) {
64
75
  if (reason === "manual") {
65
76
  incrementCounter(options.controller.counters, "manual");
66
77
  }
67
- const useCheckpoint = options.policy.mode === "strict" &&
68
- (reason === "overflow" ||
69
- (reason === "manual" && options.controller.proactiveCompaction));
78
+ const useCheckpoint = reason === "overflow" ||
79
+ (reason === "manual" &&
80
+ options.controller.manualCheckpointFallbackArmed);
70
81
  if (!useCheckpoint)
71
82
  return undefined;
83
+ if (reason === "manual") {
84
+ options.controller.manualCheckpointFallbackArmed = false;
85
+ }
72
86
  const checkpoint = buildOverflowCheckpoint({
73
87
  preparation: event.preparation,
88
+ customInstructions: event.customInstructions,
74
89
  todos: options.controller.todos,
75
90
  lastError: options.controller.lastError,
76
91
  });
@@ -93,8 +108,12 @@ export function createContextPressureExtension(options) {
93
108
  const messages = Array.isArray(event.messages) ? event.messages : [];
94
109
  try {
95
110
  const result = prunePiToolResultMessages(messages, options.prune);
96
- if (!result.changed)
111
+ if (!result.changed) {
112
+ options.controller.pruneStatus = "armed-but-no-candidate";
113
+ options.controller.pruneDiagnostic = "已达到压缩条件,但没有可清理的工具结果";
97
114
  return undefined;
115
+ }
116
+ let durableCount = 0;
98
117
  const adapter = options.contextEdit?.();
99
118
  if (adapter) {
100
119
  for (const change of result.changes) {
@@ -111,13 +130,29 @@ export function createContextPressureExtension(options) {
111
130
  replacementMessage: change.replacementMessage,
112
131
  charsBefore: change.charsBefore,
113
132
  charsAfter: change.charsAfter,
133
+ accounting: "estimated-chars",
114
134
  });
135
+ durableCount += 1;
115
136
  }
116
137
  catch {
117
138
  // Durable editing is fail-open; keep the in-memory replacement.
118
139
  }
119
140
  }
120
141
  }
142
+ if (durableCount === 0) {
143
+ options.controller.pruneStatus = adapter ? "candidate-but-no-pi-binding" : "in-memory-only";
144
+ options.controller.pruneDiagnostic = adapter
145
+ ? "找到可清理内容,但当前 Pi 会话没有可用的稳定绑定"
146
+ : "已在本次请求中清理,当前 Pi 会话不支持持久化编辑";
147
+ }
148
+ else if (durableCount === result.changes.length) {
149
+ options.controller.pruneStatus = "durable-completed";
150
+ options.controller.pruneDiagnostic = undefined;
151
+ }
152
+ else {
153
+ options.controller.pruneStatus = "durable-pending";
154
+ options.controller.pruneDiagnostic = "部分内容已清理,剩余关系等待恢复";
155
+ }
121
156
  options.controller.counters.toolResultPruned += result.messagesPruned;
122
157
  options.controller.counters.charsPrunedEstimate += result.charsRemoved;
123
158
  return { messages: result.messages };
@@ -11,6 +11,8 @@ export function emptyContextPressureCounters() {
11
11
  blocksCompressed: 0,
12
12
  toolResultPruned: 0,
13
13
  charsPrunedEstimate: 0,
14
+ pruneStatus: undefined,
15
+ pruneDiagnostic: undefined,
14
16
  };
15
17
  }
16
18
  export function incrementCounter(counters, reason, amount = 1) {
@@ -51,5 +53,7 @@ export function projectSafeTelemetry(counters) {
51
53
  blocksCompressed: counters.blocksCompressed,
52
54
  toolResultPruned: counters.toolResultPruned,
53
55
  charsPrunedEstimate: counters.charsPrunedEstimate,
56
+ ...(counters.pruneStatus ? { pruneStatus: counters.pruneStatus } : {}),
57
+ ...(counters.pruneDiagnostic ? { pruneDiagnostic: counters.pruneDiagnostic } : {}),
54
58
  };
55
59
  }
@@ -379,6 +379,11 @@ export function turnEventToStorePartial(event) {
379
379
  ...(Array.isArray(event.contextEditEntryIds) ? { contextEditEntryIds: event.contextEditEntryIds.filter((id) => typeof id === "string" && id.length > 0) } : {}),
380
380
  ...(typeof event.charsBefore === "number" ? { charsBefore: event.charsBefore } : {}),
381
381
  ...(typeof event.charsAfter === "number" ? { charsAfter: event.charsAfter } : {}),
382
+ ...(typeof event.shadowedTokenCount === "number" ? { shadowedTokenCount: event.shadowedTokenCount } : {}),
383
+ ...(typeof event.replacementTokenCount === "number" ? { replacementTokenCount: event.replacementTokenCount } : {}),
384
+ ...(typeof event.netTokensFreed === "number" ? { netTokensFreed: event.netTokensFreed } : {}),
385
+ ...(event.accounting === "provider" || event.accounting === "meter" || event.accounting === "estimated-chars" ? { accounting: event.accounting } : {}),
386
+ ...(event.pruneStatus === "armed-but-no-candidate" || event.pruneStatus === "candidate-but-no-pi-binding" || event.pruneStatus === "in-memory-only" || event.pruneStatus === "durable-completed" || event.pruneStatus === "durable-pending" || event.pruneStatus === "durable-unresolved" ? { pruneStatus: event.pruneStatus } : {}),
382
387
  ...(event.pruneReason === "pressure" || event.pruneReason === "overflow" || event.pruneReason === "manual" ? { pruneReason: event.pruneReason } : {}),
383
388
  };
384
389
  return { kind: event.type, data };
@@ -24,7 +24,7 @@ export function classifyChatCompactionFailure(error) {
24
24
  return {
25
25
  status: 400,
26
26
  code: "COMPACTION_TOO_SMALL",
27
- message: "会话内容太少,暂无法压缩。多轮对话后再试。",
27
+ message: "当前没有可压缩的历史内容。",
28
28
  raw,
29
29
  };
30
30
  }
@@ -0,0 +1,58 @@
1
+ /** Shared accounting for context prune/compaction projections. */
2
+ function finite(value) {
3
+ return typeof value === "number" && Number.isFinite(value) && value >= 0
4
+ ? value
5
+ : undefined;
6
+ }
7
+ /** Read the durable accounting contract without treating chars as tokens. */
8
+ export function readPruneAccounting(value) {
9
+ const data = value && typeof value === "object"
10
+ ? value
11
+ : {};
12
+ const tokensBefore = finite(data.tokensBefore);
13
+ const tokensAfter = finite(data.estimatedTokensAfter ?? data.tokensAfter);
14
+ const charsBefore = finite(data.charsBefore);
15
+ const charsAfter = finite(data.charsAfter);
16
+ const shadowedTokenCount = finite(data.shadowedTokenCount);
17
+ const replacementTokenCount = finite(data.replacementTokenCount);
18
+ const netTokensFreed = finite(data.netTokensFreed);
19
+ const accounting = data.accounting === "provider" || data.accounting === "meter" || data.accounting === "estimated-chars"
20
+ ? data.accounting
21
+ : undefined;
22
+ return {
23
+ ...(tokensBefore === undefined ? {} : { tokensBefore }),
24
+ ...(tokensAfter === undefined ? {} : { tokensAfter }),
25
+ ...(charsBefore === undefined ? {} : { charsBefore }),
26
+ ...(charsAfter === undefined ? {} : { charsAfter }),
27
+ ...(shadowedTokenCount === undefined ? {} : { shadowedTokenCount }),
28
+ ...(replacementTokenCount === undefined ? {} : { replacementTokenCount }),
29
+ ...(netTokensFreed === undefined ? {} : { netTokensFreed }),
30
+ ...(accounting === undefined ? {} : { accounting }),
31
+ };
32
+ }
33
+ /** Prefer measured/provider tokens, then explicitly marked estimated chars. */
34
+ export function reclaimedAmount(accounting) {
35
+ if (accounting.netTokensFreed !== undefined) {
36
+ return { value: accounting.netTokensFreed, unit: "tokens", mode: accounting.accounting ?? "meter" };
37
+ }
38
+ if (accounting.shadowedTokenCount !== undefined || accounting.replacementTokenCount !== undefined) {
39
+ return {
40
+ value: Math.max(0, (accounting.shadowedTokenCount ?? 0) - (accounting.replacementTokenCount ?? 0)),
41
+ unit: "tokens",
42
+ mode: accounting.accounting ?? "meter",
43
+ };
44
+ }
45
+ if (accounting.tokensBefore !== undefined && accounting.tokensAfter !== undefined) {
46
+ return { value: Math.max(0, accounting.tokensBefore - accounting.tokensAfter), unit: "tokens", mode: accounting.accounting ?? "provider" };
47
+ }
48
+ if (accounting.charsBefore !== undefined && accounting.charsAfter !== undefined) {
49
+ return { value: Math.max(0, accounting.charsBefore - accounting.charsAfter), unit: "chars", mode: "estimated-chars" };
50
+ }
51
+ return { value: null, unit: null, mode: null };
52
+ }
53
+ export function accountingLabel(accounting) {
54
+ const reclaimed = reclaimedAmount(accounting);
55
+ if (reclaimed.value === null)
56
+ return undefined;
57
+ return reclaimed.unit === "chars" ? `${reclaimed.value} 字符(估算)` : `${reclaimed.value} tokens`;
58
+ }
@@ -18,6 +18,7 @@
18
18
  * so it works for idle and restored sessions alike.
19
19
  */
20
20
  import { conservativeTokenEstimate } from "../../../shared/pi-context-pressure/compaction-policy.js";
21
+ import { readPruneAccounting, reclaimedAmount, } from "./context-accounting.js";
21
22
  /** Fixed-density token estimate for preview text (chars → tokens). */
22
23
  export function estimateTokensFromText(text) {
23
24
  if (!text)
@@ -253,12 +254,21 @@ export function deriveContextInsights(events, options = {}) {
253
254
  const browserMessages = [];
254
255
  const browserInjected = [];
255
256
  const browserToolResults = [];
257
+ // Keep an immutable-by-retention history separate from the live surface. A
258
+ // prune removes a node from the next request, but it must remain visible in
259
+ // every historical step that predates the removal (dsh-context's `gone`
260
+ // boundary semantics).
261
+ const historyMessages = [];
262
+ const historyInjected = [];
263
+ const historyToolResults = [];
256
264
  const archivedElements = [];
265
+ const removedAtBySeq = new Map();
257
266
  const liveNodes = [];
258
267
  const pendingShadow = new Map();
268
+ const pruneEventsById = new Map();
259
269
  const seenReplacementIds = new Set();
260
270
  /** Remove the ledger nodes whose seq the removal claims; deduct slices and browser rows. */
261
- function claimNodes(claimed, removedAtSeq) {
271
+ function claimNodes(claimed, removedAtSeq, pruneId, replacementId) {
262
272
  if (claimed.size === 0)
263
273
  return [];
264
274
  const removedIds = [];
@@ -269,9 +279,14 @@ export function deriveContextInsights(events, options = {}) {
269
279
  slice.tokens = Math.max(0, slice.tokens - node.tokens);
270
280
  slice.items = Math.max(0, slice.items - 1);
271
281
  removedIds.push(node.element.id);
272
- archivedElements.push(removedAtSeq === undefined
273
- ? node.element
274
- : { ...node.element, removedAtSeq });
282
+ if (removedAtSeq !== undefined)
283
+ removedAtBySeq.set(node.seq, removedAtSeq);
284
+ archivedElements.push({
285
+ ...node.element,
286
+ ...(removedAtSeq === undefined ? {} : { removedAtSeq }),
287
+ ...(pruneId === undefined ? {} : { pruneId }),
288
+ ...(replacementId === undefined ? {} : { replacementId }),
289
+ });
275
290
  }
276
291
  else {
277
292
  kept.push(node);
@@ -347,6 +362,7 @@ export function deriveContextInsights(events, options = {}) {
347
362
  at: event.at,
348
363
  };
349
364
  browserMessages.push(element);
365
+ historyMessages.push(element);
350
366
  liveNodes.push({ seq: event.seq, tokens, category: "user", element });
351
367
  if (!turnUserBrief.has(event.turnId)) {
352
368
  turnUserBrief.set(event.turnId, text.slice(0, 200));
@@ -381,6 +397,7 @@ export function deriveContextInsights(events, options = {}) {
381
397
  at: event.at,
382
398
  };
383
399
  browserMessages.push(element);
400
+ historyMessages.push(element);
384
401
  liveNodes.push({ seq: event.seq, tokens, category: "assistant", element });
385
402
  }
386
403
  const toolsCalled = stepToolsCalled.get(event.turnId) ?? [];
@@ -451,6 +468,7 @@ export function deriveContextInsights(events, options = {}) {
451
468
  seq: event.seq,
452
469
  at: event.at,
453
470
  });
471
+ historyInjected.push(browserInjected[browserInjected.length - 1]);
454
472
  }
455
473
  if (toolName && atTime > 0) {
456
474
  const toolCallId = typeof data.toolCallId === "string" ? data.toolCallId : "";
@@ -511,13 +529,6 @@ export function deriveContextInsights(events, options = {}) {
511
529
  claimedKey = replacementPruneId;
512
530
  claimed = pendingShadow.get(replacementPruneId);
513
531
  }
514
- else {
515
- const first = pendingShadow.entries().next();
516
- if (!first.done) {
517
- claimedKey = first.value[0];
518
- claimed = first.value[1];
519
- }
520
- }
521
532
  if (claimed) {
522
533
  const sourceSeqs = Array.isArray(data.sourceEventSeqs)
523
534
  ? data.sourceEventSeqs.filter((value) => typeof value === "number" && Number.isInteger(value) && value >= 0)
@@ -529,9 +540,13 @@ export function deriveContextInsights(events, options = {}) {
529
540
  const valid = surfaceOp?.op === "replace" && startSeq !== undefined && endSeq !== undefined &&
530
541
  startSeq === minSeq && endSeq === maxSeq && sourceSeqs.length === claimed.size &&
531
542
  new Set(sourceSeqs).size === claimed.size && sourceSeqs.every((seq) => claimed.has(seq));
532
- pendingShadow.delete(claimedKey);
533
- if (valid)
534
- claimNodes(claimed, event.seq);
543
+ if (valid) {
544
+ pendingShadow.delete(claimedKey);
545
+ claimNodes(claimed, event.seq, claimedKey, replacementId);
546
+ const pruneEvent = pruneEventsById.get(claimedKey);
547
+ if (pruneEvent)
548
+ pruneEvent.pruneStatus = "durable-completed";
549
+ }
535
550
  }
536
551
  const resultPreview = typeof data.resultPreview === "string"
537
552
  ? data.resultPreview
@@ -558,6 +573,7 @@ export function deriveContextInsights(events, options = {}) {
558
573
  at: event.at,
559
574
  };
560
575
  browserToolResults.push(element);
576
+ historyToolResults.push(element);
561
577
  liveNodes.push({ seq: event.seq, tokens, category: "toolResults", element });
562
578
  }
563
579
  break;
@@ -601,9 +617,11 @@ export function deriveContextInsights(events, options = {}) {
601
617
  case "compaction_start":
602
618
  case "compaction_end":
603
619
  case "compact": {
604
- const before = num(data.tokensBefore);
605
- const after = num(data.estimatedTokensAfter);
606
- const reclaimed = before !== undefined && after !== undefined ? before - after : null;
620
+ const accounting = readPruneAccounting(data);
621
+ const before = accounting.tokensBefore;
622
+ const after = accounting.tokensAfter;
623
+ const reclaimedInfo = reclaimedAmount(accounting);
624
+ const reclaimed = reclaimedInfo.unit === "tokens" && reclaimedInfo.value !== null ? reclaimedInfo.value : null;
607
625
  const pruned = data.pruned === true || data.kind === "prune";
608
626
  // Only explicit ring sequence claims can update the live ledger.
609
627
  // Pi firstKeptEntryId values are opaque entry identities, not event
@@ -621,7 +639,7 @@ export function deriveContextInsights(events, options = {}) {
621
639
  if (removedIds.length > 0)
622
640
  removalBasis = "seqs";
623
641
  }
624
- contextEvents.push({
642
+ const contextEvent = {
625
643
  seq: event.seq,
626
644
  at: event.at,
627
645
  turnId: event.turnId,
@@ -637,13 +655,24 @@ export function deriveContextInsights(events, options = {}) {
637
655
  ...(after !== undefined ? { tokensAfter: after } : {}),
638
656
  ...(num(data.charsBefore) !== undefined ? { charsBefore: num(data.charsBefore) } : {}),
639
657
  ...(num(data.charsAfter) !== undefined ? { charsAfter: num(data.charsAfter) } : {}),
658
+ ...(accounting.shadowedTokenCount !== undefined ? { shadowedTokenCount: accounting.shadowedTokenCount } : {}),
659
+ ...(accounting.replacementTokenCount !== undefined ? { replacementTokenCount: accounting.replacementTokenCount } : {}),
660
+ ...(accounting.netTokensFreed !== undefined ? { netTokensFreed: accounting.netTokensFreed } : {}),
661
+ ...(accounting.accounting !== undefined
662
+ ? { accounting: accounting.accounting }
663
+ : accounting.charsBefore !== undefined && accounting.charsAfter !== undefined
664
+ ? { accounting: "estimated-chars" }
665
+ : {}),
640
666
  ...(Array.isArray(data.shadowedSeqs) ? { shadowedItems: data.shadowedSeqs.length } : {}),
641
667
  ...(typeof data.reason === "string" ? { reason: data.reason } : {}),
642
- ...(pruned ? { pruned: true } : {}),
668
+ ...(pruned ? { pruned: true, pruneStatus: "durable-pending" } : {}),
643
669
  ...(removedIds.length > 0 ? { removedIds } : {}),
644
670
  ...(removalBasis !== undefined ? { removalBasis } : {}),
645
671
  detail: boundedText(asRecord(data.details)?.text, 300),
646
- });
672
+ };
673
+ contextEvents.push(contextEvent);
674
+ if (pruned && typeof data.pruneId === "string")
675
+ pruneEventsById.set(data.pruneId, contextEvent);
647
676
  const lastStep = trend.at(-1);
648
677
  if (lastStep && event.kind !== "compaction_start") {
649
678
  lastStep.eventMark = pruned ? "prune" : "compact";
@@ -654,6 +683,15 @@ export function deriveContextInsights(events, options = {}) {
654
683
  break;
655
684
  }
656
685
  }
686
+ for (const [pruneId, pruneEvent] of pruneEventsById) {
687
+ if (pendingShadow.has(pruneId))
688
+ pruneEvent.pruneStatus = "durable-unresolved";
689
+ }
690
+ for (const pruneEvent of contextEvents) {
691
+ if (pruneEvent.kind === "prune" && pruneEvent.pruneStatus === "durable-pending") {
692
+ pruneEvent.pruneStatus = "durable-unresolved";
693
+ }
694
+ }
657
695
  composition.totalTokens = composition.slices.reduce((sum, slice) => sum + slice.tokens, 0);
658
696
  composition.contextWindow = contextWindow;
659
697
  composition.providerTotal = providerTotal;
@@ -697,9 +735,15 @@ export function deriveContextInsights(events, options = {}) {
697
735
  }
698
736
  // --- Browser snapshots: live + one per trend step (rolling elements) ---
699
737
  const browserSteps = [];
700
- const liveMessages = capElements(browserMessages);
701
- const liveInjected = capElements(browserInjected);
702
- const liveToolResults = capElements(browserToolResults);
738
+ const bounded = (elements) => ({
739
+ elements: capElements(elements),
740
+ missing: Math.max(0, elements.length - ELEMENT_LIST_CAP),
741
+ });
742
+ const liveMessages = bounded(browserMessages);
743
+ const liveInjected = bounded(browserInjected);
744
+ const liveToolResults = bounded(browserToolResults);
745
+ const liveArchive = bounded(archivedElements);
746
+ const liveMissing = liveMessages.missing + liveInjected.missing + liveToolResults.missing + liveArchive.missing;
703
747
  const liveCategories = [];
704
748
  const pushCategory = (category, elements) => {
705
749
  if (elements.length === 0)
@@ -721,15 +765,17 @@ export function deriveContextInsights(events, options = {}) {
721
765
  }]
722
766
  : []);
723
767
  pushCategory("tools", browserTools);
724
- pushCategory("messages", liveMessages);
725
- pushCategory("injected", liveInjected);
726
- pushCategory("toolResults", liveToolResults);
768
+ pushCategory("messages", liveMessages.elements);
769
+ pushCategory("injected", liveInjected.elements);
770
+ pushCategory("toolResults", liveToolResults.elements);
727
771
  pushCategory("skills", browserSkills);
728
772
  browserSteps.push({
729
773
  stepId: "live",
730
774
  categories: liveCategories,
731
775
  totalTokens: liveCategories.reduce((sum, c) => sum + c.totalTokens, 0),
732
- archive: capElements(archivedElements),
776
+ archive: liveArchive.elements,
777
+ coverage: liveMissing > 0 ? "approximate" : "complete",
778
+ missingItems: liveMissing,
733
779
  });
734
780
  // Retained steps: rebuild each step's makeup from cumulative snapshots at
735
781
  // that point in the ring (bounded to the most recent steps).
@@ -738,10 +784,20 @@ export function deriveContextInsights(events, options = {}) {
738
784
  for (let i = 0; i < recentTrend.length; i++) {
739
785
  const step = recentTrend[i];
740
786
  const cutoffSeq = step.seq;
741
- const upto = (list) => capElements(list.filter((e) => e.seq <= cutoffSeq));
742
- const messagesAt = upto(browserMessages);
743
- const injectedAt = upto(browserInjected);
744
- const resultsAt = upto(browserToolResults);
787
+ // Historical surfaces are reconstructed from the full ledger. A node is
788
+ // visible before its removal boundary and absent afterwards; using the
789
+ // current live arrays here would incorrectly erase pre-prune history.
790
+ const upto = (list) => bounded(list.filter((e) => {
791
+ if (e.seq > cutoffSeq)
792
+ return false;
793
+ const removedAt = removedAtBySeq.get(e.seq);
794
+ return removedAt === undefined || removedAt > cutoffSeq;
795
+ }));
796
+ const messagesAt = upto(historyMessages);
797
+ const injectedAt = upto(historyInjected);
798
+ const resultsAt = upto(historyToolResults);
799
+ const archiveAt = bounded(archivedElements.filter((element) => element.removedAtSeq === undefined || element.removedAtSeq <= cutoffSeq));
800
+ const missingItems = messagesAt.missing + injectedAt.missing + resultsAt.missing + archiveAt.missing;
745
801
  const categories = [];
746
802
  const push = (category, elements) => {
747
803
  if (elements.length === 0)
@@ -763,9 +819,9 @@ export function deriveContextInsights(events, options = {}) {
763
819
  }]
764
820
  : []);
765
821
  push("tools", browserTools);
766
- push("messages", messagesAt);
767
- push("injected", injectedAt);
768
- push("toolResults", resultsAt);
822
+ push("messages", messagesAt.elements);
823
+ push("injected", injectedAt.elements);
824
+ push("toolResults", resultsAt.elements);
769
825
  push("skills", browserSkills);
770
826
  browserSteps.push({
771
827
  stepId: String(step.index),
@@ -773,7 +829,9 @@ export function deriveContextInsights(events, options = {}) {
773
829
  at: step.at,
774
830
  categories,
775
831
  totalTokens: categories.reduce((sum, c) => sum + c.totalTokens, 0),
776
- archive: capElements(archivedElements.filter((element) => element.removedAtSeq === undefined || element.removedAtSeq <= cutoffSeq)),
832
+ archive: archiveAt.elements,
833
+ coverage: missingItems > 0 ? "approximate" : "complete",
834
+ missingItems,
777
835
  });
778
836
  }
779
837
  return {
@@ -792,6 +850,7 @@ export function deriveContextInsights(events, options = {}) {
792
850
  return a.path.localeCompare(b.path);
793
851
  }),
794
852
  browser: browserSteps,
853
+ browserDroppedSteps: Math.max(0, trend.length - recentTrend.length),
795
854
  usage,
796
855
  timing,
797
856
  systemPromptChars: options.systemPromptChars ?? null,
@@ -802,5 +861,6 @@ export function deriveContextInsights(events, options = {}) {
802
861
  tokens: t.tokens,
803
862
  })),
804
863
  skillInjections: options.skillInjections ?? [],
864
+ ...(options.contextPressure ? { contextPressure: options.contextPressure } : {}),
805
865
  };
806
866
  }
@@ -1,4 +1,5 @@
1
1
  import { parseAssistantContent } from "./assistant-content.js";
2
+ import { readPruneAccounting } from "./context-accounting.js";
2
3
  const tokensForText = (value) => typeof value === "string" ? Math.ceil(value.length / 4) : 0;
3
4
  function finiteCount(value) {
4
5
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
@@ -120,7 +121,8 @@ export function deriveChatContextUsage(events) {
120
121
  else if (event.kind === "compact" || event.kind === "compaction_end") {
121
122
  if (data.status !== undefined && data.status !== "completed")
122
123
  continue;
123
- const after = finiteCount(data.estimatedTokensAfter);
124
+ const accounting = readPruneAccounting(data);
125
+ const after = accounting.tokensAfter;
124
126
  if (after !== undefined) {
125
127
  prompt = after;
126
128
  surface = 0;
@@ -21,6 +21,8 @@ function findToolResultEntry(manager, sourceMessage) {
21
21
  const sourceToolCallId = typeof sourceMessage.toolCallId === "string"
22
22
  ? sourceMessage.toolCallId
23
23
  : undefined;
24
+ const candidates = [];
25
+ const contentMatches = [];
24
26
  for (let index = entries.length - 1; index >= 0; index -= 1) {
25
27
  const entry = entries[index];
26
28
  const id = typeof entry?.id === "string" ? entry.id : undefined;
@@ -28,7 +30,13 @@ function findToolResultEntry(manager, sourceMessage) {
28
30
  if (!id || !message)
29
31
  continue;
30
32
  if (sourceToolCallId && message.toolCallId === sourceToolCallId)
31
- return { id, message };
33
+ candidates.push({ id, message });
34
+ }
35
+ if (candidates.length === 1)
36
+ return candidates[0];
37
+ if (candidates.length > 1) {
38
+ const exact = candidates.filter((candidate) => sameContent(candidate.message, sourceMessage));
39
+ return exact.length === 1 ? exact[0] : undefined;
32
40
  }
33
41
  for (let index = entries.length - 1; index >= 0; index -= 1) {
34
42
  const entry = entries[index];
@@ -37,9 +45,9 @@ function findToolResultEntry(manager, sourceMessage) {
37
45
  if (!id || !message)
38
46
  continue;
39
47
  if (sameContent(message, sourceMessage))
40
- return { id, message };
48
+ contentMatches.push({ id, message });
41
49
  }
42
- return undefined;
50
+ return contentMatches.length === 1 ? contentMatches[0] : undefined;
43
51
  }
44
52
  function replacementContent(message) {
45
53
  if (typeof message.content === "string")