@tea-agent/loop-agent 0.51.0-next.3 → 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 (80) hide show
  1. package/CHANGELOG.md +13 -3
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/shared/pi-context-pressure/checkpoint.js +186 -77
  4. package/dist/shared/pi-context-pressure/compaction-accounting.js +27 -0
  5. package/dist/shared/pi-context-pressure/exact-tool-policy.js +93 -0
  6. package/dist/shared/pi-context-pressure/extension.js +25 -7
  7. package/dist/shared/pi-context-pressure/index.js +3 -1
  8. package/dist/shared/pi-context-pressure/sift-bridge.js +53 -3
  9. package/dist/shared/pi-context-pressure/telemetry.js +4 -0
  10. package/dist/shared/pi-context-pressure/tool-result-pruner.js +5 -0
  11. package/dist/worker/console/chat/chat-event-projection.js +2 -1
  12. package/dist/worker/console/chat/chat-event-store.js +7 -0
  13. package/dist/worker/console/chat/pi-runtime.js +37 -11
  14. package/dist/worker/console/chat/routes.js +7 -0
  15. package/dist/worker/console/chat/session-mode.js +1 -0
  16. package/dist/worker/console/chat/terminal-routes.js +3 -1
  17. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-GerMJfMU.js → abnfDiagram-N423BO3Z-Cm9fdnXV.js} +1 -1
  18. package/dist/worker/console/static/assets/{arc-DHRoAcBA.js → arc-INXjsn-p.js} +1 -1
  19. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-Bna7kqEi.js → architectureDiagram-T3A2C74G-D37KkILZ.js} +1 -1
  20. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-B8yw7WTX.js → blockDiagram-VBNYF7ZC-KKXC0tnC.js} +1 -1
  21. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BaUWiyqi.js → c4Diagram-5PPSVZJV-CoiYxKG6.js} +1 -1
  22. package/dist/worker/console/static/assets/channel-CjI9LnHL.js +1 -0
  23. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-D4iZ2ZNv.js → chunk-2GRJ4B5K-DUf1X-RG.js} +1 -1
  24. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-BtQpibwB.js → chunk-2Q5K7J3B-CHCaBxdV.js} +1 -1
  25. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-ez-kfSyS.js → chunk-5RXB4S5H-BequgbOM.js} +1 -1
  26. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-6L4-OV-3.js → chunk-5VM5RSS4-BfCaRimU.js} +1 -1
  27. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-CPUweABC.js → chunk-6Q2QTUOP-D8UjJk_C.js} +1 -1
  28. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-6DTw-5Ov.js → chunk-GF5L2VYU-BqVP9DQI.js} +1 -1
  29. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-DFAS-DH8.js → chunk-JWPE2WC7-DIdHATyu.js} +1 -1
  30. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Du7LoER5.js → chunk-KBJHAD2P-C_lQLU-3.js} +1 -1
  31. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-D9UugPlg.js → chunk-RYQCIY6F-Dk7kiAO-.js} +1 -1
  32. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-BLh5yptc.js → chunk-XXDRQBXY-MgUV0HsP.js} +1 -1
  33. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DckutAaL.js +1 -0
  34. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DckutAaL.js +1 -0
  35. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-DjmHXa8h.js → cose-bilkent-JH36ORCC-DOLAaAUQ.js} +1 -1
  36. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-D5jbf1gi.js → cynefin-VYW2F7L2-CC8nJgvv.js} +1 -1
  37. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-BudjeLTi.js → cynefinDiagram-MW4NZA55-CWKq9Dot.js} +1 -1
  38. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-6YP-wMO0.js → dagre-VZM6K2ZE-DLQrVo6F.js} +1 -1
  39. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-CA3LtUAB.js → diagram-7IWD3JNH-4GbuYTRz.js} +1 -1
  40. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BAjJeYaD.js → diagram-B4RE2ZJO-_bsAsFIM.js} +1 -1
  41. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-Dh4zb-ds.js → diagram-LBJQPF4R-98UkDrJp.js} +1 -1
  42. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-aMKj_Gkp.js → diagram-Q27KOJAE-3l4QTjOH.js} +1 -1
  43. package/dist/worker/console/static/assets/{diagram-UB23O5K3-D_0_rqQ6.js → diagram-UB23O5K3-CHfpyvkh.js} +1 -1
  44. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR--C9HfGgB.js → ebnfDiagram-BXEA7PRR-CHaGmmH6.js} +1 -1
  45. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-BuqX0vmt.js → erDiagram-JOGREHBK-CGHzLz5D.js} +1 -1
  46. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-IneEK8zO.js → flowDiagram-UKHOOZJN-BuMWtKY4.js} +1 -1
  47. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-DK2RiNlb.js → ganttDiagram-PKOTCBZU-C2250UEq.js} +1 -1
  48. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-CuN5z0rP.js → gitGraphDiagram-DS77QQ5N-CelgpYyy.js} +1 -1
  49. package/dist/worker/console/static/assets/{index-DS6dteCl.js → index-BlNf823_.js} +3 -3
  50. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-B6enpqSl.js → infoDiagram-6WML65LV-BNjkoLGP.js} +1 -1
  51. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-DepH_7eq.js → ishikawaDiagram-WSZJBQD7-WsQBCOMy.js} +1 -1
  52. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BftlRwcR.js → journeyDiagram-NVQOT4AX-DPMg56VB.js} +1 -1
  53. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-CEIZMo9g.js → kanban-definition-27J2QSJJ-Ces2yNhD.js} +1 -1
  54. package/dist/worker/console/static/assets/{linear-DkgtGbsw.js → linear-BWDvQlHY.js} +1 -1
  55. package/dist/worker/console/static/assets/{mermaid.core-CIMKKPgL.js → mermaid.core-B61abuWa.js} +5 -5
  56. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-dzbp1VuW.js → mindmap-definition-FAOFIHXS-D8C0x0Uc.js} +1 -1
  57. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-C5b5i7KO.js → pegDiagram-VL7TDLO6-CTayvHb1.js} +1 -1
  58. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-Ugdko1lm.js → pieDiagram-7S7Q4E2Y-BMlgdA3f.js} +1 -1
  59. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-B2s1OZu8.js → quadrantDiagram-CIZ2JOQS-CfR-Bjz0.js} +1 -1
  60. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BVafp-Z6.js → railroadDiagram-AXF67PYL-CPZnompR.js} +1 -1
  61. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BVxBjdbs.js → requirementDiagram-LRYGKXZP-ChfgFRf2.js} +1 -1
  62. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-CorSImxl.js → sankeyDiagram-W5VNT64P-wJGtKdSl.js} +1 -1
  63. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-eVj3geQV.js → sequenceDiagram-SI44F4Z6-Bvw8kgEK.js} +1 -1
  64. package/dist/worker/console/static/assets/{sheet-workbook-DNnJDCal.js → sheet-workbook-DIcc5MII.js} +1 -1
  65. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-OQWfzgrL.js → sizeCapture-X5ZJPWSS-CxkQAgp9.js} +1 -1
  66. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-DJr_pPmG.js → stateDiagram-OKZ733FA-CXxg2h63.js} +1 -1
  67. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BjyIE-uf.js +1 -0
  68. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-CQG0Q9vK.js → swimlanes-SLNWSIFB-CW8urXHy.js} +2 -2
  69. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-Dl2sojZu.js +8 -0
  70. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-DxWuWIZ5.js → timeline-definition-Z64GVDOM-iXcLaMEd.js} +1 -1
  71. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BJt03ecs.js → vennDiagram-T6HMQDX7-qXN9XhmE.js} +1 -1
  72. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BB3rPfNJ.js → wardleyDiagram-T6FBY63Y-CMqSH6Pw.js} +1 -1
  73. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-aVR9TCu0.js → xychartDiagram-ELKLHX3M-9DphXHpY.js} +1 -1
  74. package/dist/worker/console/static/index.html +1 -1
  75. package/package.json +3 -3
  76. package/dist/worker/console/static/assets/channel-CLhtAowh.js +0 -1
  77. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DB7nfjpK.js +0 -1
  78. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DB7nfjpK.js +0 -1
  79. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cr-50jJB.js +0 -1
  80. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-kZpEmem6.js +0 -8
package/CHANGELOG.md CHANGED
@@ -12,10 +12,15 @@
12
12
  - 普通安全节点续跑可继承剩余硬预算;预算缺失、超限或不一致时会说明原因并停止。前端专用恢复仍使用原恢复入口。
13
13
  - 正式版本的更新说明以「上一正式版本」为对比起点,说明这次升级带来的变化。
14
14
  - 版本页缺少本版本说明时仍可查看历史;新发布版本可直接读取说明,较大的已发布包有更充足的查询时间,失败时会区分超时和内容缺失。预发布版本会保留该构建的待发布变化快照。
15
+ - 详情栏新增终端工作台,可复用终端会话;轨迹视图补充更完整的工具调用和结果信息。
16
+ - 切换已打开过的对话会优先恢复最近内容,并减少重复读取上下文,多个会话之间切换更快。
17
+ - 上下文洞察会展示工具结果整理和上下文占用变化,长对话更容易判断哪些内容已被压缩或保留。
15
18
 
16
19
  ### 修复
17
20
 
18
- - 修复读取较长工具结果时内容反复被压缩、导致任务耗尽请求额度的问题。
21
+ - 修复较长文件读取和搜索结果在上下文整理后丢失原文的问题;普通日志仍可压缩,精确文件修改会保留必要源码。
22
+ - 修复 provider 拒绝过大上下文时重复发送完整摘要请求的问题;现在优先使用 provider 摘要,超限时改用本地 checkpoint 继续恢复。
23
+ - 手动压缩不再因为保留窗口过大而拒绝已有少量历史的会话。
19
24
 
20
25
  - 修复切换对话后停在顶部或回复中间的问题,默认显示最新助手回复末尾;主动上翻后,调整窗口宽度仍保留阅读位置。
21
26
  - 修复浏览器工具在元素引用过期时未提供恢复线索的问题;现在会返回当前可用快照与具体失效原因,避免调用方盲目重试。
@@ -24,7 +29,7 @@
24
29
  - 初始化更新会保留有效的项目调度配置,不再因此反复要求合并配置文件。
25
30
  - 需求检查失败时保留逐条判定和审核理由,并准确区分未解决条款与背景说明,便于定位阻塞原因。
26
31
 
27
- ## [0.51.0-next.3] - 2026-10-15
32
+ ## [0.51.0-next.4] - 2026-10-16
28
33
 
29
34
  本预发布快照记录构建时已整理的待发布变化,不表示相对上一构建全部新增。
30
35
 
@@ -36,10 +41,15 @@
36
41
  - 普通安全节点续跑可继承剩余硬预算;预算缺失、超限或不一致时会说明原因并停止。前端专用恢复仍使用原恢复入口。
37
42
  - 正式版本的更新说明以「上一正式版本」为对比起点,说明这次升级带来的变化。
38
43
  - 版本页缺少本版本说明时仍可查看历史;新发布版本可直接读取说明,较大的已发布包有更充足的查询时间,失败时会区分超时和内容缺失。预发布版本会保留该构建的待发布变化快照。
44
+ - 详情栏新增终端工作台,可复用终端会话;轨迹视图补充更完整的工具调用和结果信息。
45
+ - 切换已打开过的对话会优先恢复最近内容,并减少重复读取上下文,多个会话之间切换更快。
46
+ - 上下文洞察会展示工具结果整理和上下文占用变化,长对话更容易判断哪些内容已被压缩或保留。
39
47
 
40
48
  ### 修复
41
49
 
42
- - 修复读取较长工具结果时内容反复被压缩、导致任务耗尽请求额度的问题。
50
+ - 修复较长文件读取和搜索结果在上下文整理后丢失原文的问题;普通日志仍可压缩,精确文件修改会保留必要源码。
51
+ - 修复 provider 拒绝过大上下文时重复发送完整摘要请求的问题;现在优先使用 provider 摘要,超限时改用本地 checkpoint 继续恢复。
52
+ - 手动压缩不再因为保留窗口过大而拒绝已有少量历史的会话。
43
53
 
44
54
  - 修复切换对话后停在顶部或回复中间的问题,默认显示最新助手回复末尾;主动上翻后,调整窗口宽度仍保留阅读位置。
45
55
  - 修复浏览器工具在元素引用过期时未提供恢复线索的问题;现在会返回当前可用快照与具体失效原因,避免调用方盲目重试。
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "version": "0.51.0-next.3",
4
- "gitSha": "70fdc60ee57703e2b0c68bb23cf4930d1c158811",
5
- "builtAt": "2026-10-14T17:25:52.531Z"
3
+ "version": "0.51.0-next.4",
4
+ "gitSha": "008f2b7e3bf11695d5e5834574923354e5afb8ed",
5
+ "builtAt": "2026-10-16T01:59:41.560Z"
6
6
  }
@@ -1,10 +1,11 @@
1
1
  const CHECKPOINT_MAX_BYTES = 12 * 1024;
2
2
  function truncateUtf8(value, maxBytes) {
3
+ if (maxBytes <= 0)
4
+ return "";
3
5
  if (Buffer.byteLength(value, "utf8") <= maxBytes)
4
6
  return value;
5
7
  const ellipsis = "…";
6
- const ellipsisBytes = Buffer.byteLength(ellipsis, "utf8");
7
- const budget = Math.max(0, maxBytes - ellipsisBytes);
8
+ const budget = Math.max(0, maxBytes - Buffer.byteLength(ellipsis, "utf8"));
8
9
  let result = "";
9
10
  let used = 0;
10
11
  for (const character of Array.from(value)) {
@@ -19,116 +20,224 @@ function truncateUtf8(value, maxBytes) {
19
20
  function boundText(value, maxChars) {
20
21
  if (typeof value !== "string" || !value.trim())
21
22
  return "";
22
- return value.length <= maxChars ? value : `${value.slice(0, maxChars - 1)}…`;
23
+ return value.length <= maxChars ? value : `${value.slice(0, Math.max(0, maxChars - 1))}…`;
23
24
  }
24
25
  function asRecord(value) {
25
26
  return value !== null && typeof value === "object" && !Array.isArray(value)
26
27
  ? value
27
28
  : undefined;
28
29
  }
30
+ function asMessages(value) {
31
+ return Array.isArray(value) ? value : [];
32
+ }
33
+ function normalizePathSet(value) {
34
+ const values = [];
35
+ if (value instanceof Set) {
36
+ for (const item of value)
37
+ if (typeof item === "string" && item.trim())
38
+ values.push(item.trim());
39
+ }
40
+ else if (Array.isArray(value)) {
41
+ for (const item of value)
42
+ if (typeof item === "string" && item.trim())
43
+ values.push(item.trim());
44
+ }
45
+ else if (typeof value === "string" && value.trim()) {
46
+ values.push(value.trim());
47
+ }
48
+ return [...new Set(values)].sort((left, right) => left < right ? -1 : left > right ? 1 : 0);
49
+ }
50
+ function messageToolCallIds(message) {
51
+ const record = asRecord(message);
52
+ const content = record?.content;
53
+ if (!Array.isArray(content))
54
+ return [];
55
+ const ids = [];
56
+ for (const block of content) {
57
+ const item = asRecord(block);
58
+ if (!item)
59
+ continue;
60
+ if (item.type !== "toolCall" && item.type !== "tool_use" && item.type !== "tool-call")
61
+ continue;
62
+ const id = item.id ?? item.toolCallId ?? item.tool_use_id;
63
+ if (typeof id === "string" && id)
64
+ ids.push(id);
65
+ }
66
+ return ids;
67
+ }
68
+ function messageToolResultId(message) {
69
+ const record = asRecord(message);
70
+ if (!record || (record.role !== "toolResult" && record.role !== "tool" && record.role !== "tool_result"))
71
+ return undefined;
72
+ const id = record.toolCallId ?? record.tool_call_id ?? record.tool_use_id ?? record.id;
73
+ return typeof id === "string" && id ? id : undefined;
74
+ }
75
+ /** Normalize Pi's preparation without changing the data sent to its provider. */
76
+ export function normalizeCompactionPreparation(input) {
77
+ const preparation = asRecord(input);
78
+ if (!preparation)
79
+ return undefined;
80
+ const firstKeptEntryId = typeof preparation.firstKeptEntryId === "string" && preparation.firstKeptEntryId ? preparation.firstKeptEntryId : undefined;
81
+ const tokensBefore = typeof preparation.tokensBefore === "number" && Number.isFinite(preparation.tokensBefore) && preparation.tokensBefore >= 0 ? preparation.tokensBefore : undefined;
82
+ if (!firstKeptEntryId || tokensBefore === undefined)
83
+ return undefined;
84
+ const messagesToSummarize = asMessages(preparation.messagesToSummarize);
85
+ const turnPrefixMessages = asMessages(preparation.turnPrefixMessages);
86
+ const allMessages = [...messagesToSummarize, ...turnPrefixMessages];
87
+ const diagnostics = [];
88
+ const openCalls = new Set();
89
+ let boundary = "proved";
90
+ for (const message of allMessages) {
91
+ for (const id of messageToolCallIds(message))
92
+ openCalls.add(id);
93
+ const resultId = messageToolResultId(message);
94
+ if (resultId !== undefined) {
95
+ if (!openCalls.has(resultId)) {
96
+ boundary = "unknown";
97
+ diagnostics.push("orphan-tool-result");
98
+ }
99
+ else
100
+ openCalls.delete(resultId);
101
+ }
102
+ }
103
+ if (allMessages.length > 0 && messageToolResultId(allMessages.at(-1)) !== undefined && boundary !== "unknown") {
104
+ boundary = "unknown";
105
+ diagnostics.push("tool-result-boundary-unknown");
106
+ }
107
+ if (openCalls.size > 0) {
108
+ boundary = "unknown";
109
+ diagnostics.push("unpaired-tool-call");
110
+ }
111
+ const fileOps = asRecord(preparation.fileOps);
112
+ const read = normalizePathSet(fileOps?.read ?? fileOps?.readFiles ?? preparation.readFiles);
113
+ const written = normalizePathSet(fileOps?.written);
114
+ const edited = normalizePathSet(fileOps?.edited);
115
+ if (fileOps && !("read" in fileOps || "written" in fileOps || "edited" in fileOps || "readFiles" in fileOps || "modifiedFiles" in fileOps))
116
+ diagnostics.push("file-ops-shape-unknown");
117
+ const modifiedFiles = normalizePathSet(fileOps?.modifiedFiles ?? preparation.modifiedFiles);
118
+ for (const file of modifiedFiles)
119
+ if (!edited.includes(file) && !written.includes(file))
120
+ written.push(file);
121
+ return {
122
+ firstKeptEntryId,
123
+ tokensBefore,
124
+ ...(typeof preparation.previousSummary === "string" && preparation.previousSummary.trim() ? { previousSummary: preparation.previousSummary } : {}),
125
+ messagesToSummarize,
126
+ turnPrefixMessages,
127
+ fileOps: {
128
+ read: [...new Set(read)].sort((left, right) => left < right ? -1 : left > right ? 1 : 0),
129
+ written: [...new Set(written)].sort((left, right) => left < right ? -1 : left > right ? 1 : 0),
130
+ edited: [...new Set(edited)].sort((left, right) => left < right ? -1 : left > right ? 1 : 0),
131
+ },
132
+ boundary,
133
+ diagnostics: [...new Set(diagnostics)],
134
+ };
135
+ }
29
136
  function extractLastUserGoal(messages) {
30
- if (!Array.isArray(messages))
31
- return "";
32
137
  for (let index = messages.length - 1; index >= 0; index -= 1) {
33
138
  const message = asRecord(messages[index]);
34
139
  if (!message || message.role !== "user")
35
140
  continue;
36
141
  const content = message.content;
37
142
  if (typeof content === "string")
38
- return boundText(content, 800);
143
+ return boundText(content, 900);
39
144
  if (Array.isArray(content)) {
40
- const texts = content
41
- .map((block) => {
145
+ const texts = content.map((block) => {
42
146
  const rec = asRecord(block);
43
147
  return typeof rec?.text === "string" ? rec.text : "";
44
- })
45
- .filter(Boolean);
148
+ }).filter(Boolean);
46
149
  if (texts.length > 0)
47
- return boundText(texts.join("\n"), 800);
150
+ return boundText(texts.join("\n"), 900);
48
151
  }
49
152
  }
50
153
  return "";
51
154
  }
155
+ function extractVisibleProgress(messages) {
156
+ const lines = [];
157
+ for (const message of messages.slice(-8)) {
158
+ const record = asRecord(message);
159
+ if (!record || (record.role !== "assistant" && record.role !== "user"))
160
+ continue;
161
+ const content = record.content;
162
+ if (typeof content === "string" && content.trim())
163
+ lines.push(`${String(record.role)}: ${content.trim()}`);
164
+ else if (Array.isArray(content)) {
165
+ const text = content.map((block) => {
166
+ const rec = asRecord(block);
167
+ return typeof rec?.text === "string" ? rec.text : "";
168
+ }).filter(Boolean).join(" ");
169
+ if (text)
170
+ lines.push(`${String(record.role)}: ${text}`);
171
+ }
172
+ }
173
+ return boundText(lines.join("\n"), 1800);
174
+ }
52
175
  function extractTodos(details) {
53
176
  const record = asRecord(details);
54
177
  const todos = record?.todos ?? record?.items;
55
178
  if (!Array.isArray(todos))
56
179
  return "";
57
- const lines = todos
58
- .slice(0, 24)
59
- .map((item) => {
180
+ return boundText(todos.slice(0, 24).map((item) => {
60
181
  const rec = asRecord(item);
61
182
  const status = typeof rec?.status === "string" ? rec.status : "pending";
62
- const content = typeof rec?.content === "string"
63
- ? rec.content
64
- : typeof rec?.title === "string"
65
- ? rec.title
66
- : "";
183
+ const content = typeof rec?.content === "string" ? rec.content : typeof rec?.title === "string" ? rec.title : "";
67
184
  return content ? `- [${status}] ${content}` : "";
68
- })
69
- .filter(Boolean);
70
- return boundText(lines.join("\n"), 1200);
185
+ }).filter(Boolean).join("\n"), 1800);
71
186
  }
72
187
  function extractFileOps(fileOps) {
73
- const record = asRecord(fileOps);
74
- if (!record)
75
- return "";
76
188
  const parts = [];
77
- for (const key of ["edited", "written", "read", "deleted", "ops"]) {
78
- const value = record[key];
79
- if (Array.isArray(value)) {
80
- parts.push(`${key}: ${value
81
- .slice(0, 20)
82
- .map((item) => (typeof item === "string" ? item : JSON.stringify(item)))
83
- .join(", ")}`);
84
- }
85
- else if (typeof value === "string" && value) {
86
- parts.push(`${key}: ${value}`);
87
- }
189
+ for (const [key, values] of [["edited", fileOps.edited], ["written", fileOps.written], ["read", fileOps.read]]) {
190
+ if (values.length > 0)
191
+ parts.push(`${key}: ${values.slice(0, 40).join(", ")}`);
88
192
  }
89
- if (parts.length === 0) {
90
- try {
91
- return boundText(JSON.stringify(fileOps), 800);
92
- }
93
- catch {
94
- return "";
95
- }
193
+ return boundText(parts.join("\n"), 2200);
194
+ }
195
+ function section(title, body) {
196
+ return body ? `## ${title}\n${body}` : `## ${title}`;
197
+ }
198
+ function fitSections(sections, tail) {
199
+ const fixedBytes = Buffer.byteLength(tail, "utf8");
200
+ const available = Math.max(0, CHECKPOINT_MAX_BYTES - fixedBytes - 2 * (sections.length - 1));
201
+ const texts = sections.map(({ text, budget }) => truncateUtf8(text, budget));
202
+ let used = texts.reduce((sum, text) => sum + Buffer.byteLength(text, "utf8"), 0);
203
+ for (let index = 0; used > available && index < texts.length; index += 1) {
204
+ const current = texts[index];
205
+ const next = truncateUtf8(current, Math.max(0, Buffer.byteLength(current, "utf8") - (used - available)));
206
+ used -= Buffer.byteLength(current, "utf8") - Buffer.byteLength(next, "utf8");
207
+ texts[index] = next;
96
208
  }
97
- return boundText(parts.join("\n"), 800);
209
+ return [...texts, tail].join("\n\n");
98
210
  }
99
211
  export function buildOverflowCheckpoint(input) {
100
- const preparation = input.preparation;
101
- const firstKeptEntryId = typeof preparation?.firstKeptEntryId === "string" &&
102
- preparation.firstKeptEntryId
103
- ? preparation.firstKeptEntryId
104
- : undefined;
105
- const tokensBefore = typeof preparation?.tokensBefore === "number" &&
106
- Number.isFinite(preparation.tokensBefore)
107
- ? preparation.tokensBefore
108
- : undefined;
109
- if (!firstKeptEntryId || tokensBefore === undefined)
212
+ const preparation = normalizeCompactionPreparation(input.preparation);
213
+ if (!preparation)
110
214
  return undefined;
111
- const sections = [
112
- "Deterministic local compaction checkpoint (no extra summary request).",
113
- boundText(preparation?.previousSummary, 2000)
114
- ? `Previous summary:\n${boundText(preparation?.previousSummary, 2000)}`
115
- : "",
116
- boundText(input.customInstructions, 800)
117
- ? `Compaction instructions:\n${boundText(input.customInstructions, 800)}`
118
- : "",
119
- extractLastUserGoal(preparation?.messagesToSummarize)
120
- ? `Latest user goal:\n${extractLastUserGoal(preparation?.messagesToSummarize)}`
121
- : "",
122
- extractTodos(input.todos) ? `Open todos:\n${extractTodos(input.todos)}` : "",
123
- extractFileOps(preparation?.fileOps)
124
- ? `File ops:\n${extractFileOps(preparation?.fileOps)}`
125
- : "",
126
- typeof input.lastError === "string" && input.lastError
127
- ? `Latest error:\n${boundText(input.lastError, 400)}`
128
- : "",
129
- "Next step: continue the interrupted turn from the kept recent messages. Do not repeat completed file writes.",
130
- ].filter(Boolean);
131
- let summary = sections.join("\n\n");
132
- summary = truncateUtf8(summary, CHECKPOINT_MAX_BYTES);
133
- return { summary, firstKeptEntryId, tokensBefore };
215
+ const messages = [...preparation.messagesToSummarize, ...preparation.turnPrefixMessages];
216
+ const goal = extractLastUserGoal(messages);
217
+ const progress = extractVisibleProgress(messages);
218
+ const todos = extractTodos(input.todos);
219
+ const files = extractFileOps(preparation.fileOps);
220
+ const error = typeof input.lastError === "string" && input.lastError ? boundText(input.lastError, 1000) : "";
221
+ const customInstructions = boundText(input.customInstructions, 1000);
222
+ const previousSummary = boundText(preparation.previousSummary, 2400);
223
+ const tail = [
224
+ section("Pending Jobs", `Open todos:\n${todos || "No structured pending jobs recorded."}`),
225
+ section("Next Steps", "Next step: continue the interrupted turn from the kept recent messages. Do not repeat completed file writes."),
226
+ section("Critical Context", customInstructions ? `Compaction instructions:\n${customInstructions}` : "The Pi provider summary was unavailable; use the kept recent messages as the source of truth."),
227
+ section("Recovery Note", "This deterministic checkpoint was created without a model summary request. Details not restated here remain in the kept recent messages."),
228
+ ].join("\n\n");
229
+ const summary = fitSections([
230
+ { text: "Deterministic local compaction checkpoint (no extra summary request).", budget: 900 },
231
+ { text: section("Goal", `Latest user goal:\n${goal || "No recent user goal was available."}`), budget: 1800 },
232
+ { text: section("Progress", [previousSummary ? `Previous summary:\n${previousSummary}` : "", progress].filter(Boolean).join("\n")), budget: 3200 },
233
+ { text: section("Files and Code", `File ops:\n${files || "No file operations were recorded."}`), budget: 2400 },
234
+ { text: section("Errors and Fixes", error ? `Latest error:\n${error}` : "No recent provider error was recorded."), budget: 1400 },
235
+ ], tail);
236
+ return {
237
+ summary: truncateUtf8(summary, CHECKPOINT_MAX_BYTES),
238
+ firstKeptEntryId: preparation.firstKeptEntryId,
239
+ tokensBefore: preparation.tokensBefore,
240
+ boundary: preparation.boundary,
241
+ diagnostics: preparation.diagnostics,
242
+ };
134
243
  }
@@ -0,0 +1,27 @@
1
+ function finiteNonNegative(value) {
2
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : undefined;
3
+ }
4
+ /** Derive a proof only when both values use the same Pi context meter. */
5
+ export function deriveCompactionAccounting(tokensBefore, estimatedTokensAfter) {
6
+ const before = finiteNonNegative(tokensBefore);
7
+ const after = finiteNonNegative(estimatedTokensAfter);
8
+ if (before === undefined || after === undefined)
9
+ return { accounting: "unknown", shrinkProof: "not-proved" };
10
+ if (after >= before)
11
+ return { shadowedTokenCount: before, replacementTokenCount: after, accounting: "meter", shrinkProof: "failed" };
12
+ return { shadowedTokenCount: before, replacementTokenCount: after, netTokensFreed: before - after, accounting: "meter", shrinkProof: "proved" };
13
+ }
14
+ export function readCompactionAccounting(value) {
15
+ if (!value || typeof value !== "object")
16
+ return undefined;
17
+ const record = value;
18
+ const accounting = record.accounting === "provider" || record.accounting === "meter" || record.accounting === "estimated-chars" || record.accounting === "unknown" ? record.accounting : undefined;
19
+ const shrinkProof = record.shrinkProof === "proved" || record.shrinkProof === "not-proved" || record.shrinkProof === "failed" ? record.shrinkProof : undefined;
20
+ if (!accounting && !shrinkProof)
21
+ return undefined;
22
+ const tokenAccounting = accounting === "provider" || accounting === "meter";
23
+ const shadowedTokenCount = tokenAccounting ? finiteNonNegative(record.shadowedTokenCount) : undefined;
24
+ const replacementTokenCount = tokenAccounting ? finiteNonNegative(record.replacementTokenCount) : undefined;
25
+ const netTokensFreed = tokenAccounting ? finiteNonNegative(record.netTokensFreed) : undefined;
26
+ return { accounting: accounting ?? "unknown", shrinkProof: shrinkProof ?? "not-proved", ...(shadowedTokenCount === undefined ? {} : { shadowedTokenCount }), ...(replacementTokenCount === undefined ? {} : { replacementTokenCount }), ...(netTokensFreed === undefined ? {} : { netTokensFreed }) };
27
+ }
@@ -0,0 +1,93 @@
1
+ /** Tools whose results are source material for exact inspection or editing. */
2
+ const EXACT_TOOL_NAMES = new Set([
3
+ "read",
4
+ "grep",
5
+ "edit",
6
+ "write",
7
+ "replace",
8
+ "safe-read",
9
+ "safe-grep",
10
+ ]);
11
+ function asRecord(value) {
12
+ return value !== null && typeof value === "object" && !Array.isArray(value)
13
+ ? value
14
+ : undefined;
15
+ }
16
+ function stringField(record, ...keys) {
17
+ if (!record)
18
+ return undefined;
19
+ for (const key of keys) {
20
+ const value = record[key];
21
+ if (typeof value === "string" && value.trim())
22
+ return value;
23
+ }
24
+ return undefined;
25
+ }
26
+ export function normalizeToolName(value) {
27
+ if (typeof value !== "string")
28
+ return undefined;
29
+ const normalized = value.trim().toLowerCase();
30
+ return normalized || undefined;
31
+ }
32
+ export function isExactToolName(value) {
33
+ const normalized = normalizeToolName(value);
34
+ return normalized !== undefined && EXACT_TOOL_NAMES.has(normalized);
35
+ }
36
+ function addExactId(ids, id, name) {
37
+ if (typeof id !== "string" || !id || !isExactToolName(name))
38
+ return;
39
+ ids.add(id);
40
+ }
41
+ function collectMessageIds(messages, ids) {
42
+ for (const value of messages) {
43
+ const message = asRecord(value);
44
+ if (!message)
45
+ continue;
46
+ addExactId(ids, stringField(message, "toolCallId", "tool_call_id", "tool_use_id", "call_id"), stringField(message, "toolName", "tool_name", "name"));
47
+ const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
48
+ for (const callValue of toolCalls) {
49
+ const call = asRecord(callValue);
50
+ const functionValue = asRecord(call?.function);
51
+ addExactId(ids, stringField(call, "id", "call_id"), stringField(functionValue, "name") ?? stringField(call, "name", "toolName", "tool_name"));
52
+ }
53
+ const content = Array.isArray(message.content) ? message.content : [];
54
+ for (const blockValue of content) {
55
+ const block = asRecord(blockValue);
56
+ if (!block)
57
+ continue;
58
+ const type = normalizeToolName(block.type);
59
+ if (type === "tool_use" || type === "toolcall" || type === "tool_call") {
60
+ addExactId(ids, stringField(block, "id", "tool_use_id", "tool_call_id", "call_id"), stringField(block, "name", "toolName", "tool_name"));
61
+ }
62
+ }
63
+ }
64
+ }
65
+ /**
66
+ * Returns call IDs whose tool result must remain lossless in a provider payload.
67
+ * The scan understands OpenAI Chat, Responses, Anthropic, and Pi-shaped fields.
68
+ */
69
+ export function collectExactToolCallIds(payload) {
70
+ const root = asRecord(payload);
71
+ const ids = new Set();
72
+ if (!root)
73
+ return ids;
74
+ if (Array.isArray(root.messages))
75
+ collectMessageIds(root.messages, ids);
76
+ if (Array.isArray(root.input)) {
77
+ for (const value of root.input) {
78
+ const item = asRecord(value);
79
+ if (!item)
80
+ continue;
81
+ const type = normalizeToolName(item.type);
82
+ if (type === "function_call") {
83
+ addExactId(ids, stringField(item, "call_id", "id"), stringField(item, "name", "toolName", "tool_name"));
84
+ }
85
+ addExactId(ids, stringField(item, "tool_call_id", "tool_use_id", "call_id"), stringField(item, "toolName", "tool_name", "name"));
86
+ }
87
+ }
88
+ return ids;
89
+ }
90
+ export function isExactToolResultMessage(message) {
91
+ const record = asRecord(message);
92
+ return isExactToolName(stringField(record, "toolName", "tool_name", "name"));
93
+ }
@@ -1,6 +1,6 @@
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
5
  import { isContextOverflow, shouldRewriteAssistantOverflow } from "./overflow.js";
6
6
  import { clearRetrieveBypass, compressProviderPayload, createSiftRetrieveToolDefinition, SIFT_RETRIEVE_TOOL_NAME, } from "./sift-bridge.js";
@@ -12,6 +12,8 @@ export function createCompactionController() {
12
12
  pruneArmed: false,
13
13
  pruneStatus: undefined,
14
14
  pruneDiagnostic: undefined,
15
+ compactionBoundary: undefined,
16
+ compactionDiagnostics: undefined,
15
17
  counters: emptyContextPressureCounters(),
16
18
  };
17
19
  }
@@ -26,6 +28,10 @@ export function createContextPressureExtension(options) {
26
28
  name: options.name ?? "operator-chat-context-pressure",
27
29
  hidden: true,
28
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;
29
35
  if (l2 || transientRecovery) {
30
36
  api.on("message_end", (event) => {
31
37
  const message = event.message;
@@ -33,6 +39,9 @@ export function createContextPressureExtension(options) {
33
39
  return undefined;
34
40
  const rec = message;
35
41
  if (l2) {
42
+ if (rec.role === "assistant") {
43
+ providerOverflowPending = rec.stopReason === "error" && isContextOverflow(rec.errorMessage);
44
+ }
36
45
  if (typeof rec.errorMessage === "string") {
37
46
  options.controller.lastError = rec.errorMessage;
38
47
  }
@@ -58,15 +67,22 @@ export function createContextPressureExtension(options) {
58
67
  }
59
68
  if (l2) {
60
69
  api.on("session_compact_failed", (event) => {
61
- if (event.reason === "manual" &&
62
- !event.aborted &&
63
- isContextOverflow(event.errorMessage)) {
64
- options.controller.manualCheckpointFallbackArmed = true;
65
- }
70
+ options.controller.manualCheckpointFallbackArmed =
71
+ event.reason === "manual" &&
72
+ !event.fromExtension &&
73
+ !event.aborted &&
74
+ isContextOverflow(event.errorMessage);
66
75
  return undefined;
67
76
  });
68
77
  api.on("session_before_compact", (event) => {
69
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(",");
70
86
  if (reason === "overflow") {
71
87
  incrementCounter(options.controller.counters, "overflow");
72
88
  if (pruner)
@@ -75,7 +91,7 @@ export function createContextPressureExtension(options) {
75
91
  if (reason === "manual") {
76
92
  incrementCounter(options.controller.counters, "manual");
77
93
  }
78
- const useCheckpoint = reason === "overflow" ||
94
+ const useCheckpoint = (reason === "overflow" && providerOverflow) ||
79
95
  (reason === "manual" &&
80
96
  options.controller.manualCheckpointFallbackArmed);
81
97
  if (!useCheckpoint)
@@ -91,6 +107,8 @@ export function createContextPressureExtension(options) {
91
107
  });
92
108
  if (!checkpoint)
93
109
  return undefined;
110
+ options.controller.compactionBoundary = checkpoint.boundary;
111
+ options.controller.compactionDiagnostics = checkpoint.diagnostics;
94
112
  return {
95
113
  compaction: {
96
114
  summary: checkpoint.summary,
@@ -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";