@tea-agent/loop-agent 0.51.0-next.2 → 0.51.0-next.4

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 (92) hide show
  1. package/CHANGELOG.md +31 -3
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/shared/pi-context-pressure/checkpoint.js +201 -74
  4. package/dist/shared/pi-context-pressure/compaction-accounting.js +27 -0
  5. package/dist/shared/pi-context-pressure/compaction-policy.js +5 -1
  6. package/dist/shared/pi-context-pressure/exact-tool-policy.js +93 -0
  7. package/dist/shared/pi-context-pressure/extension.js +59 -6
  8. package/dist/shared/pi-context-pressure/index.js +3 -1
  9. package/dist/shared/pi-context-pressure/sift-bridge.js +53 -3
  10. package/dist/shared/pi-context-pressure/telemetry.js +8 -0
  11. package/dist/shared/pi-context-pressure/tool-result-pruner.js +5 -0
  12. package/dist/worker/console/chat/chat-event-projection.js +6 -0
  13. package/dist/worker/console/chat/chat-event-store.js +7 -0
  14. package/dist/worker/console/chat/compaction-errors.js +1 -1
  15. package/dist/worker/console/chat/context-accounting.js +58 -0
  16. package/dist/worker/console/chat/context-insights.js +95 -35
  17. package/dist/worker/console/chat/context-usage.js +3 -1
  18. package/dist/worker/console/chat/pi-runtime/context-edit.js +11 -3
  19. package/dist/worker/console/chat/pi-runtime.js +45 -3
  20. package/dist/worker/console/chat/routes.js +10 -0
  21. package/dist/worker/console/chat/session-mode.js +1 -0
  22. package/dist/worker/console/chat/terminal-routes.js +15 -1
  23. package/dist/worker/console/chat/terminal-sessions.js +6 -0
  24. package/dist/worker/console/chat/vcp-prompt.js +9 -3
  25. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BDoJuIJc.js → abnfDiagram-N423BO3Z-Cm9fdnXV.js} +1 -1
  26. package/dist/worker/console/static/assets/{arc-BIcO0B1H.js → arc-INXjsn-p.js} +1 -1
  27. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-DbxnPcOI.js → architectureDiagram-T3A2C74G-D37KkILZ.js} +1 -1
  28. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-BG4tXH7C.js → blockDiagram-VBNYF7ZC-KKXC0tnC.js} +1 -1
  29. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BaNxGG9H.js → c4Diagram-5PPSVZJV-CoiYxKG6.js} +1 -1
  30. package/dist/worker/console/static/assets/channel-CjI9LnHL.js +1 -0
  31. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-BYr2qNac.js → chunk-2GRJ4B5K-DUf1X-RG.js} +1 -1
  32. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-D3q2b9W9.js → chunk-2Q5K7J3B-CHCaBxdV.js} +1 -1
  33. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-BFsAsJ8z.js → chunk-5RXB4S5H-BequgbOM.js} +1 -1
  34. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-Bnp6GtE7.js → chunk-5VM5RSS4-BfCaRimU.js} +1 -1
  35. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-CzDChmU1.js → chunk-6Q2QTUOP-D8UjJk_C.js} +1 -1
  36. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-kgZTzZlf.js → chunk-GF5L2VYU-BqVP9DQI.js} +1 -1
  37. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-Vnt5nEN_.js → chunk-JWPE2WC7-DIdHATyu.js} +1 -1
  38. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-CENlGfou.js → chunk-KBJHAD2P-C_lQLU-3.js} +1 -1
  39. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DS1bOotT.js → chunk-RYQCIY6F-Dk7kiAO-.js} +1 -1
  40. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-SkFJspnw.js → chunk-XXDRQBXY-MgUV0HsP.js} +1 -1
  41. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DckutAaL.js +1 -0
  42. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DckutAaL.js +1 -0
  43. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BE1OAnpP.js → cose-bilkent-JH36ORCC-DOLAaAUQ.js} +1 -1
  44. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BaTDZwL-.js → cynefin-VYW2F7L2-CC8nJgvv.js} +1 -1
  45. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-BRrIdbbw.js → cynefinDiagram-MW4NZA55-CWKq9Dot.js} +1 -1
  46. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-B4pDil_r.js → dagre-VZM6K2ZE-DLQrVo6F.js} +1 -1
  47. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DvqFh-9w.js → diagram-7IWD3JNH-4GbuYTRz.js} +1 -1
  48. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-D7me-QwT.js → diagram-B4RE2ZJO-_bsAsFIM.js} +1 -1
  49. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-EahLHu6K.js → diagram-LBJQPF4R-98UkDrJp.js} +1 -1
  50. package/dist/worker/console/static/assets/{diagram-Q27KOJAE--S6g2rQZ.js → diagram-Q27KOJAE-3l4QTjOH.js} +1 -1
  51. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BwqA9gGp.js → diagram-UB23O5K3-CHfpyvkh.js} +1 -1
  52. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-Bdj6kj6x.js → ebnfDiagram-BXEA7PRR-CHaGmmH6.js} +1 -1
  53. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-_Ii2v364.js → erDiagram-JOGREHBK-CGHzLz5D.js} +1 -1
  54. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-LM1yby4D.js → flowDiagram-UKHOOZJN-BuMWtKY4.js} +1 -1
  55. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-_MmByUIz.js → ganttDiagram-PKOTCBZU-C2250UEq.js} +1 -1
  56. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Be4J6q3D.js → gitGraphDiagram-DS77QQ5N-CelgpYyy.js} +1 -1
  57. package/dist/worker/console/static/assets/{index-CpugPRcA.js → index-BlNf823_.js} +159 -147
  58. package/dist/worker/console/static/assets/{index-BVMJjujb.css → index-CzfumEW1.css} +1 -1
  59. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CFRi5O36.js → infoDiagram-6WML65LV-BNjkoLGP.js} +1 -1
  60. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-B2OnsVXe.js → ishikawaDiagram-WSZJBQD7-WsQBCOMy.js} +1 -1
  61. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Dnz8Ge36.js → journeyDiagram-NVQOT4AX-DPMg56VB.js} +1 -1
  62. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-DFPGjB3O.js → kanban-definition-27J2QSJJ-Ces2yNhD.js} +1 -1
  63. package/dist/worker/console/static/assets/{linear-DrKFn9ZE.js → linear-BWDvQlHY.js} +1 -1
  64. package/dist/worker/console/static/assets/{mermaid.core-C4__OfPT.js → mermaid.core-B61abuWa.js} +5 -5
  65. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CMEMeYGS.js → mindmap-definition-FAOFIHXS-D8C0x0Uc.js} +1 -1
  66. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BDNDtN72.js → pegDiagram-VL7TDLO6-CTayvHb1.js} +1 -1
  67. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-DX12wRku.js → pieDiagram-7S7Q4E2Y-BMlgdA3f.js} +1 -1
  68. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-DEzotPpD.js → quadrantDiagram-CIZ2JOQS-CfR-Bjz0.js} +1 -1
  69. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BGbCCVjx.js → railroadDiagram-AXF67PYL-CPZnompR.js} +1 -1
  70. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-eClVYdkl.js → requirementDiagram-LRYGKXZP-ChfgFRf2.js} +1 -1
  71. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-Hyw3eFyF.js → sankeyDiagram-W5VNT64P-wJGtKdSl.js} +1 -1
  72. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DwysyBPq.js → sequenceDiagram-SI44F4Z6-Bvw8kgEK.js} +1 -1
  73. package/dist/worker/console/static/assets/{sheet-workbook-jLtIaGKt.js → sheet-workbook-DIcc5MII.js} +1 -1
  74. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-CsA3-7gH.js → sizeCapture-X5ZJPWSS-CxkQAgp9.js} +1 -1
  75. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-DkUPiKZ8.js → stateDiagram-OKZ733FA-CXxg2h63.js} +1 -1
  76. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BjyIE-uf.js +1 -0
  77. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-qfVo6Xay.js → swimlanes-SLNWSIFB-CW8urXHy.js} +2 -2
  78. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-Dl2sojZu.js +8 -0
  79. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BRTsFNL5.js → timeline-definition-Z64GVDOM-iXcLaMEd.js} +1 -1
  80. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BI-btTm3.js → vennDiagram-T6HMQDX7-qXN9XhmE.js} +1 -1
  81. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BYMVY4Ov.js → wardleyDiagram-T6FBY63Y-CMqSH6Pw.js} +1 -1
  82. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CvK7yNi0.js → xychartDiagram-ELKLHX3M-9DphXHpY.js} +1 -1
  83. package/dist/worker/console/static/index.html +2 -2
  84. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +99 -16
  85. package/dist/worker/console/static-src/operator-chat/useChatThread.js +27 -5
  86. package/dist/worker/console/workspace-context.js +3 -0
  87. package/package.json +6 -3
  88. package/dist/worker/console/static/assets/channel-DigIZ6M1.js +0 -1
  89. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-AY-sL87U.js +0 -1
  90. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-AY-sL87U.js +0 -1
  91. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BiXtsN97.js +0 -1
  92. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-ImoXsndy.js +0 -8
@@ -1,14 +1,19 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { shouldRewriteAssistantTransientProviderError } from "../pi-provider-recovery.js";
3
- import { buildOverflowCheckpoint } from "./checkpoint.js";
3
+ import { buildOverflowCheckpoint, normalizeCompactionPreparation, } 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,
15
+ compactionBoundary: undefined,
16
+ compactionDiagnostics: undefined,
12
17
  counters: emptyContextPressureCounters(),
13
18
  };
14
19
  }
@@ -23,6 +28,10 @@ export function createContextPressureExtension(options) {
23
28
  name: options.name ?? "operator-chat-context-pressure",
24
29
  hidden: true,
25
30
  factory: (api) => {
31
+ // SDK "overflow" also covers length stops and successful responses
32
+ // whose usage exceeds the window. Only an explicit input rejection
33
+ // justifies skipping the model summary request.
34
+ let providerOverflowPending = false;
26
35
  if (l2 || transientRecovery) {
27
36
  api.on("message_end", (event) => {
28
37
  const message = event.message;
@@ -30,6 +39,9 @@ export function createContextPressureExtension(options) {
30
39
  return undefined;
31
40
  const rec = message;
32
41
  if (l2) {
42
+ if (rec.role === "assistant") {
43
+ providerOverflowPending = rec.stopReason === "error" && isContextOverflow(rec.errorMessage);
44
+ }
33
45
  if (typeof rec.errorMessage === "string") {
34
46
  options.controller.lastError = rec.errorMessage;
35
47
  }
@@ -54,8 +66,23 @@ export function createContextPressureExtension(options) {
54
66
  });
55
67
  }
56
68
  if (l2) {
69
+ api.on("session_compact_failed", (event) => {
70
+ options.controller.manualCheckpointFallbackArmed =
71
+ event.reason === "manual" &&
72
+ !event.fromExtension &&
73
+ !event.aborted &&
74
+ isContextOverflow(event.errorMessage);
75
+ return undefined;
76
+ });
57
77
  api.on("session_before_compact", (event) => {
58
78
  const reason = event.reason;
79
+ const providerOverflow = providerOverflowPending;
80
+ providerOverflowPending = false;
81
+ const normalizedPreparation = normalizeCompactionPreparation(event.preparation);
82
+ options.controller.compactionBoundary = normalizedPreparation?.boundary ?? "invalid";
83
+ options.controller.compactionDiagnostics = normalizedPreparation?.diagnostics ?? ["invalid-preparation"];
84
+ options.controller.counters.compactionBoundary = options.controller.compactionBoundary;
85
+ options.controller.counters.compactionDiagnostic = options.controller.compactionDiagnostics.join(",");
59
86
  if (reason === "overflow") {
60
87
  incrementCounter(options.controller.counters, "overflow");
61
88
  if (pruner)
@@ -64,18 +91,24 @@ export function createContextPressureExtension(options) {
64
91
  if (reason === "manual") {
65
92
  incrementCounter(options.controller.counters, "manual");
66
93
  }
67
- const useCheckpoint = options.policy.mode === "strict" &&
68
- (reason === "overflow" ||
69
- (reason === "manual" && options.controller.proactiveCompaction));
94
+ const useCheckpoint = (reason === "overflow" && providerOverflow) ||
95
+ (reason === "manual" &&
96
+ options.controller.manualCheckpointFallbackArmed);
70
97
  if (!useCheckpoint)
71
98
  return undefined;
99
+ if (reason === "manual") {
100
+ options.controller.manualCheckpointFallbackArmed = false;
101
+ }
72
102
  const checkpoint = buildOverflowCheckpoint({
73
103
  preparation: event.preparation,
104
+ customInstructions: event.customInstructions,
74
105
  todos: options.controller.todos,
75
106
  lastError: options.controller.lastError,
76
107
  });
77
108
  if (!checkpoint)
78
109
  return undefined;
110
+ options.controller.compactionBoundary = checkpoint.boundary;
111
+ options.controller.compactionDiagnostics = checkpoint.diagnostics;
79
112
  return {
80
113
  compaction: {
81
114
  summary: checkpoint.summary,
@@ -93,8 +126,12 @@ export function createContextPressureExtension(options) {
93
126
  const messages = Array.isArray(event.messages) ? event.messages : [];
94
127
  try {
95
128
  const result = prunePiToolResultMessages(messages, options.prune);
96
- if (!result.changed)
129
+ if (!result.changed) {
130
+ options.controller.pruneStatus = "armed-but-no-candidate";
131
+ options.controller.pruneDiagnostic = "已达到压缩条件,但没有可清理的工具结果";
97
132
  return undefined;
133
+ }
134
+ let durableCount = 0;
98
135
  const adapter = options.contextEdit?.();
99
136
  if (adapter) {
100
137
  for (const change of result.changes) {
@@ -111,13 +148,29 @@ export function createContextPressureExtension(options) {
111
148
  replacementMessage: change.replacementMessage,
112
149
  charsBefore: change.charsBefore,
113
150
  charsAfter: change.charsAfter,
151
+ accounting: "estimated-chars",
114
152
  });
153
+ durableCount += 1;
115
154
  }
116
155
  catch {
117
156
  // Durable editing is fail-open; keep the in-memory replacement.
118
157
  }
119
158
  }
120
159
  }
160
+ if (durableCount === 0) {
161
+ options.controller.pruneStatus = adapter ? "candidate-but-no-pi-binding" : "in-memory-only";
162
+ options.controller.pruneDiagnostic = adapter
163
+ ? "找到可清理内容,但当前 Pi 会话没有可用的稳定绑定"
164
+ : "已在本次请求中清理,当前 Pi 会话不支持持久化编辑";
165
+ }
166
+ else if (durableCount === result.changes.length) {
167
+ options.controller.pruneStatus = "durable-completed";
168
+ options.controller.pruneDiagnostic = undefined;
169
+ }
170
+ else {
171
+ options.controller.pruneStatus = "durable-pending";
172
+ options.controller.pruneDiagnostic = "部分内容已清理,剩余关系等待恢复";
173
+ }
121
174
  options.controller.counters.toolResultPruned += result.messagesPruned;
122
175
  options.controller.counters.charsPrunedEstimate += result.charsRemoved;
123
176
  return { messages: result.messages };
@@ -1,7 +1,9 @@
1
1
  export { isContextOverflow, CONTEXT_OVERFLOW_PHRASES, OVERFLOW_FIXTURES, NORMALIZED_OVERFLOW_PREFIX, shouldRewriteAssistantOverflow, normalizeOverflowErrorMessage, buildGeneratedOverflowClassifierSource, } from "./overflow.js";
2
2
  export { parseCompactionPolicy, deriveEffectiveWindow, conservativeTokenEstimate, projectPromptPressure, applyProcessCompactionOverride, inMemoryCompactionSettings, PI_DEFAULT_RESERVE_TOKENS, DEFAULT_KEEP_RECENT_TOKENS, } from "./compaction-policy.js";
3
- export { buildOverflowCheckpoint } from "./checkpoint.js";
3
+ export { buildOverflowCheckpoint, normalizeCompactionPreparation, } from "./checkpoint.js";
4
+ export { deriveCompactionAccounting, readCompactionAccounting, } from "./compaction-accounting.js";
4
5
  export { PI_TOOL_RESULT_PRUNE_MARKER, DEFAULT_PI_TOOL_RESULT_PRUNE_CONFIG, resolvePiToolResultPruneConfig, parsePiToolResultPruneConfig, piCodePointLength, prunePiToolResultMessages, } from "./tool-result-pruner.js";
6
+ export { isExactToolName, isExactToolResultMessage, normalizeToolName, collectExactToolCallIds, } from "./exact-tool-policy.js";
5
7
  export { createContextPressureExtension, createCompactionController, } from "./extension.js";
6
8
  export { createSiftBridgeState, parseSiftBridgeConfig, compressProviderPayload, executeSiftRetrieve, housekeepSiftStash, createSiftRetrieveToolDefinition, SIFT_RETRIEVE_TOOL_NAME, SIFT_POLICY_VERSION, } from "./sift-bridge.js";
7
9
  export { isConsoleSiftEnabled, isDagSiftEnabled, readContextPressureMode, parseEnabledFlag, parseContextPressureMode, } from "./env.js";
@@ -3,6 +3,7 @@ import { mkdirSync, readdirSync, rmSync, statSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { parseBoundedNumber, parseEnabledFlag } from "./env.js";
5
5
  import { emptyContextPressureCounters, incrementCounter, } from "./telemetry.js";
6
+ import { collectExactToolCallIds } from "./exact-tool-policy.js";
6
7
  export const SIFT_POLICY_VERSION = "sift-v1-query-undefined";
7
8
  export const SIFT_RETRIEVE_TOOL_NAME = "sift_retrieve";
8
9
  export const SIFT_STASH_KEY_PATTERN = /^[0-9a-f]{24}$/;
@@ -155,6 +156,47 @@ function restoreProtectedToolResults(originalPayload, compressed, protectedIds)
155
156
  restoreInResponsesInput(original, next, protectedIds);
156
157
  return next;
157
158
  }
159
+ function mergeProtectedToolCallIds(payload, retrieveBypassIds) {
160
+ return new Set([
161
+ ...retrieveBypassIds,
162
+ ...collectExactToolCallIds(payload),
163
+ ]);
164
+ }
165
+ function jsonByteLength(value) {
166
+ try {
167
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
168
+ }
169
+ catch {
170
+ return 0;
171
+ }
172
+ }
173
+ function countChangedStringLeaves(original, next) {
174
+ if (typeof original === "string" || typeof next === "string") {
175
+ return original === next ? 0 : 1;
176
+ }
177
+ if (Array.isArray(original) && Array.isArray(next)) {
178
+ const length = Math.max(original.length, next.length);
179
+ let changed = 0;
180
+ for (let index = 0; index < length; index += 1) {
181
+ changed += countChangedStringLeaves(original[index], next[index]);
182
+ }
183
+ return changed;
184
+ }
185
+ if (isRecord(original) && isRecord(next)) {
186
+ const keys = new Set([...Object.keys(original), ...Object.keys(next)]);
187
+ let changed = 0;
188
+ for (const key of keys)
189
+ changed += countChangedStringLeaves(original[key], next[key]);
190
+ return changed;
191
+ }
192
+ return JSON.stringify(original) === JSON.stringify(next) ? 0 : 1;
193
+ }
194
+ /** Sift's estimate is useful only for bytes that remain compressed on the wire. */
195
+ function estimateWireTokensSaved(original, compressed) {
196
+ const before = jsonByteLength(original);
197
+ const after = jsonByteLength(compressed);
198
+ return Math.max(0, Math.floor(((before - after) / 4) * 1.2));
199
+ }
158
200
  function restoreInMessages(original, next, protectedIds) {
159
201
  if (!isRecord(original) || !isRecord(next))
160
202
  return;
@@ -245,9 +287,17 @@ export async function compressProviderPayload(state, payload) {
245
287
  const result = sift.siftRequest(payload, undefined);
246
288
  if (!result || result.changed !== true)
247
289
  return undefined;
248
- const restored = restoreProtectedToolResults(payload, result.body, state.retrieveBypassIds);
249
- state.counters.tokensSavedEstimate += Math.max(0, result.tokensSaved ?? 0);
250
- state.counters.blocksCompressed += Math.max(0, result.blocksCompressed ?? 0);
290
+ const protectedIds = mergeProtectedToolCallIds(payload, state.retrieveBypassIds);
291
+ const restored = restoreProtectedToolResults(payload, result.body, protectedIds);
292
+ if (JSON.stringify(restored) === JSON.stringify(payload))
293
+ return undefined;
294
+ const hasProtectedResults = protectedIds.size > 0;
295
+ state.counters.tokensSavedEstimate += hasProtectedResults
296
+ ? estimateWireTokensSaved(payload, restored)
297
+ : Math.max(0, result.tokensSaved ?? 0);
298
+ state.counters.blocksCompressed += hasProtectedResults
299
+ ? Math.min(Math.max(0, result.blocksCompressed ?? 0), countChangedStringLeaves(payload, restored))
300
+ : Math.max(0, result.blocksCompressed ?? 0);
251
301
  incrementCounter(state.counters, "wire-compression");
252
302
  state.memo.set(key, restored);
253
303
  return restored;
@@ -11,6 +11,10 @@ export function emptyContextPressureCounters() {
11
11
  blocksCompressed: 0,
12
12
  toolResultPruned: 0,
13
13
  charsPrunedEstimate: 0,
14
+ pruneStatus: undefined,
15
+ pruneDiagnostic: undefined,
16
+ compactionBoundary: undefined,
17
+ compactionDiagnostic: undefined,
14
18
  };
15
19
  }
16
20
  export function incrementCounter(counters, reason, amount = 1) {
@@ -51,5 +55,9 @@ export function projectSafeTelemetry(counters) {
51
55
  blocksCompressed: counters.blocksCompressed,
52
56
  toolResultPruned: counters.toolResultPruned,
53
57
  charsPrunedEstimate: counters.charsPrunedEstimate,
58
+ ...(counters.pruneStatus ? { pruneStatus: counters.pruneStatus } : {}),
59
+ ...(counters.pruneDiagnostic ? { pruneDiagnostic: counters.pruneDiagnostic } : {}),
60
+ ...(counters.compactionBoundary ? { compactionBoundary: counters.compactionBoundary } : {}),
61
+ ...(counters.compactionDiagnostic ? { compactionDiagnostic: counters.compactionDiagnostic } : {}),
54
62
  };
55
63
  }
@@ -1,5 +1,6 @@
1
1
  /** Deterministic, model-free pruning of Pi tool-result messages. */
2
2
  import { parseBoundedNumber, parseEnabledFlag } from "./env.js";
3
+ import { collectExactToolCallIds, isExactToolResultMessage, } from "./exact-tool-policy.js";
3
4
  export const PI_TOOL_RESULT_PRUNE_MARKER = "\n\n[... tool result middle pruned ...]\n\n";
4
5
  export const DEFAULT_PI_TOOL_RESULT_PRUNE_CONFIG = Object.freeze({ thresholdChars: 8192, headChars: 4096, tailChars: 1024 });
5
6
  export function parsePiToolResultPruneConfig(env = process.env) {
@@ -71,12 +72,16 @@ function pruneBlocks(input, cfg) {
71
72
  export function prunePiToolResultMessages(messages, config) {
72
73
  const cfg = resolvePiToolResultPruneConfig(config);
73
74
  const output = messages.slice();
75
+ const exactIds = collectExactToolCallIds({ messages });
74
76
  let charsRemoved = 0, messagesPruned = 0;
75
77
  const changes = [];
76
78
  for (let i = 0; i < output.length; i++) {
77
79
  const message = output[i];
78
80
  if (!message || !isToolResult(message))
79
81
  continue;
82
+ const toolCallId = typeof message.toolCallId === "string" ? message.toolCallId : typeof message.tool_call_id === "string" ? message.tool_call_id : typeof message.tool_use_id === "string" ? message.tool_use_id : undefined;
83
+ if (isExactToolResultMessage(message) || (toolCallId !== undefined && exactIds.has(toolCallId)))
84
+ continue;
80
85
  if (typeof message.content === "string") {
81
86
  const r = pruneBlocks([{ type: "text", text: message.content }], cfg);
82
87
  if (r.blocks) {
@@ -379,6 +379,12 @@ 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" || event.accounting === "unknown" ? { accounting: event.accounting } : {}),
386
+ ...(event.shrinkProof === "proved" || event.shrinkProof === "not-proved" || event.shrinkProof === "failed" ? { shrinkProof: event.shrinkProof } : {}),
387
+ ...(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
388
  ...(event.pruneReason === "pressure" || event.pruneReason === "overflow" || event.pruneReason === "manual" ? { pruneReason: event.pruneReason } : {}),
383
389
  };
384
390
  return { kind: event.type, data };
@@ -21,6 +21,7 @@ import { createHash } from "node:crypto";
21
21
  import { existsSync, readFileSync, rmSync } from "node:fs";
22
22
  import path from "node:path";
23
23
  import { ensureSecureDir, writeSecureJsonSync, } from "../../../infrastructure/console/app-data.js";
24
+ import { deriveCompactionAccounting, readCompactionAccounting, } from "../../../shared/pi-context-pressure/compaction-accounting.js";
24
25
  import { isTerminalOperationState, } from "../../../infrastructure/console/operation-store.js";
25
26
  import { projectBrowserTimeline } from "./browser-timeline.js";
26
27
  import { scrubSecrets } from "./explore-tools.js";
@@ -244,6 +245,10 @@ export function projectCompactSnapshot(value) {
244
245
  const details = record.details === undefined
245
246
  ? undefined
246
247
  : boundedRedactedJson(record.details).preview;
248
+ const accounting = readCompactionAccounting(record.accounting) ??
249
+ (tokensBefore !== undefined || estimatedTokensAfter !== undefined
250
+ ? deriveCompactionAccounting(tokensBefore, estimatedTokensAfter)
251
+ : undefined);
247
252
  return {
248
253
  schemaVersion: 1,
249
254
  summary,
@@ -251,6 +256,7 @@ export function projectCompactSnapshot(value) {
251
256
  ...(tokensBefore !== undefined ? { tokensBefore } : {}),
252
257
  ...(estimatedTokensAfter !== undefined ? { estimatedTokensAfter } : {}),
253
258
  ...(details ? { details } : {}),
259
+ ...(accounting ? { accounting } : {}),
254
260
  previewHash: createHash("sha256")
255
261
  .update(JSON.stringify({
256
262
  summary,
@@ -258,6 +264,7 @@ export function projectCompactSnapshot(value) {
258
264
  tokensBefore,
259
265
  estimatedTokensAfter,
260
266
  details,
267
+ accounting,
261
268
  }))
262
269
  .digest("hex"),
263
270
  };
@@ -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
+ }