@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
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.2] - 2026-10-14
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
  - 修复浏览器工具在元素引用过期时未提供恢复线索的问题;现在会返回当前可用快照与具体失效原因,避免调用方盲目重试。
@@ -48,6 +58,24 @@
48
58
  - 初始化更新会保留有效的项目调度配置,不再因此反复要求合并配置文件。
49
59
  - 需求检查失败时保留逐条判定和审核理由,并准确区分未解决条款与背景说明,便于定位阻塞原因。
50
60
 
61
+ ## [0.50.0] - 2026-10-13
62
+
63
+ ### 重点更新
64
+
65
+ - 对话支持按上下文压力整理较长工具结果,压缩后仍保留可追溯的摘要和恢复信息。
66
+ - VCP 视觉卡片减少内置字体资源并修正样式覆盖,加载更轻,卡片排版更稳定。
67
+
68
+ ### 改进
69
+
70
+ - Console 支持在设置中切换代理或直连,新请求立即使用最新选择。
71
+ - 切换对话后会恢复到最近阅读位置,继续查看最新回复更顺畅。
72
+ - 浏览器自动化默认关闭,需要时可通过明确配置启用。
73
+
74
+ ### 修复
75
+
76
+ - 修复浏览器元素引用过期时缺少当前页面快照和恢复线索的问题。
77
+ - 修复切换会话后版本说明、工作区状态和对话滚动位置偶发丢失的问题。
78
+
51
79
  ## [0.49.0] - 2026-10-11
52
80
 
53
81
  ### 重点更新
@@ -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.4",
4
+ "gitSha": "008f2b7e3bf11695d5e5834574923354e5afb8ed",
5
+ "builtAt": "2026-10-16T01:59:41.560Z"
6
6
  }
@@ -1,116 +1,243 @@
1
1
  const CHECKPOINT_MAX_BYTES = 12 * 1024;
2
+ function truncateUtf8(value, maxBytes) {
3
+ if (maxBytes <= 0)
4
+ return "";
5
+ if (Buffer.byteLength(value, "utf8") <= maxBytes)
6
+ return value;
7
+ const ellipsis = "…";
8
+ const budget = Math.max(0, maxBytes - Buffer.byteLength(ellipsis, "utf8"));
9
+ let result = "";
10
+ let used = 0;
11
+ for (const character of Array.from(value)) {
12
+ const bytes = Buffer.byteLength(character, "utf8");
13
+ if (used + bytes > budget)
14
+ break;
15
+ result += character;
16
+ used += bytes;
17
+ }
18
+ return `${result}${ellipsis}`;
19
+ }
2
20
  function boundText(value, maxChars) {
3
21
  if (typeof value !== "string" || !value.trim())
4
22
  return "";
5
- return value.length <= maxChars ? value : `${value.slice(0, maxChars - 1)}…`;
23
+ return value.length <= maxChars ? value : `${value.slice(0, Math.max(0, maxChars - 1))}…`;
6
24
  }
7
25
  function asRecord(value) {
8
26
  return value !== null && typeof value === "object" && !Array.isArray(value)
9
27
  ? value
10
28
  : undefined;
11
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
+ }
12
136
  function extractLastUserGoal(messages) {
13
- if (!Array.isArray(messages))
14
- return "";
15
137
  for (let index = messages.length - 1; index >= 0; index -= 1) {
16
138
  const message = asRecord(messages[index]);
17
139
  if (!message || message.role !== "user")
18
140
  continue;
19
141
  const content = message.content;
20
142
  if (typeof content === "string")
21
- return boundText(content, 800);
143
+ return boundText(content, 900);
22
144
  if (Array.isArray(content)) {
23
- const texts = content
24
- .map((block) => {
145
+ const texts = content.map((block) => {
25
146
  const rec = asRecord(block);
26
147
  return typeof rec?.text === "string" ? rec.text : "";
27
- })
28
- .filter(Boolean);
148
+ }).filter(Boolean);
29
149
  if (texts.length > 0)
30
- return boundText(texts.join("\n"), 800);
150
+ return boundText(texts.join("\n"), 900);
31
151
  }
32
152
  }
33
153
  return "";
34
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
+ }
35
175
  function extractTodos(details) {
36
176
  const record = asRecord(details);
37
177
  const todos = record?.todos ?? record?.items;
38
178
  if (!Array.isArray(todos))
39
179
  return "";
40
- const lines = todos
41
- .slice(0, 24)
42
- .map((item) => {
180
+ return boundText(todos.slice(0, 24).map((item) => {
43
181
  const rec = asRecord(item);
44
182
  const status = typeof rec?.status === "string" ? rec.status : "pending";
45
- const content = typeof rec?.content === "string"
46
- ? rec.content
47
- : typeof rec?.title === "string"
48
- ? rec.title
49
- : "";
183
+ const content = typeof rec?.content === "string" ? rec.content : typeof rec?.title === "string" ? rec.title : "";
50
184
  return content ? `- [${status}] ${content}` : "";
51
- })
52
- .filter(Boolean);
53
- return boundText(lines.join("\n"), 1200);
185
+ }).filter(Boolean).join("\n"), 1800);
54
186
  }
55
187
  function extractFileOps(fileOps) {
56
- const record = asRecord(fileOps);
57
- if (!record)
58
- return "";
59
188
  const parts = [];
60
- for (const key of ["edited", "written", "read", "deleted", "ops"]) {
61
- const value = record[key];
62
- if (Array.isArray(value)) {
63
- parts.push(`${key}: ${value
64
- .slice(0, 20)
65
- .map((item) => (typeof item === "string" ? item : JSON.stringify(item)))
66
- .join(", ")}`);
67
- }
68
- else if (typeof value === "string" && value) {
69
- parts.push(`${key}: ${value}`);
70
- }
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(", ")}`);
71
192
  }
72
- if (parts.length === 0) {
73
- try {
74
- return boundText(JSON.stringify(fileOps), 800);
75
- }
76
- catch {
77
- return "";
78
- }
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;
79
208
  }
80
- return boundText(parts.join("\n"), 800);
209
+ return [...texts, tail].join("\n\n");
81
210
  }
82
211
  export function buildOverflowCheckpoint(input) {
83
- const preparation = input.preparation;
84
- const firstKeptEntryId = typeof preparation?.firstKeptEntryId === "string" &&
85
- preparation.firstKeptEntryId
86
- ? preparation.firstKeptEntryId
87
- : undefined;
88
- const tokensBefore = typeof preparation?.tokensBefore === "number" &&
89
- Number.isFinite(preparation.tokensBefore)
90
- ? preparation.tokensBefore
91
- : undefined;
92
- if (!firstKeptEntryId || tokensBefore === undefined)
212
+ const preparation = normalizeCompactionPreparation(input.preparation);
213
+ if (!preparation)
93
214
  return undefined;
94
- const sections = [
95
- "Deterministic overflow checkpoint (no extra summary request).",
96
- boundText(preparation?.previousSummary, 2000)
97
- ? `Previous summary:\n${boundText(preparation?.previousSummary, 2000)}`
98
- : "",
99
- extractLastUserGoal(preparation?.messagesToSummarize)
100
- ? `Latest user goal:\n${extractLastUserGoal(preparation?.messagesToSummarize)}`
101
- : "",
102
- extractTodos(input.todos) ? `Open todos:\n${extractTodos(input.todos)}` : "",
103
- extractFileOps(preparation?.fileOps)
104
- ? `File ops:\n${extractFileOps(preparation?.fileOps)}`
105
- : "",
106
- typeof input.lastError === "string" && input.lastError
107
- ? `Latest error:\n${boundText(input.lastError, 400)}`
108
- : "",
109
- "Next step: continue the interrupted turn from the kept recent messages. Do not repeat completed file writes.",
110
- ].filter(Boolean);
111
- 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
- }
115
- 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
+ };
116
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
+ }
@@ -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 {
@@ -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
+ }