@tea-agent/loop-agent 0.52.0-next.5 → 0.52.0-next.6

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 (75) hide show
  1. package/CHANGELOG.md +3 -1
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/shared/pi-context-pressure/checkpoint.js +94 -24
  4. package/dist/shared/pi-context-pressure/compaction-policy.js +104 -11
  5. package/dist/shared/pi-context-pressure/extension.js +25 -8
  6. package/dist/shared/pi-context-pressure/telemetry.js +5 -0
  7. package/dist/worker/console/chat/chat-event-projection.js +4 -0
  8. package/dist/worker/console/chat/pi-runtime.js +109 -14
  9. package/dist/worker/console/pi-compaction-settings.js +182 -0
  10. package/dist/worker/console/server.js +59 -1
  11. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-q8Zn-JlS.js → abnfDiagram-N423BO3Z-BiFM8_eW.js} +1 -1
  12. package/dist/worker/console/static/assets/{arc-CqXYi6Cq.js → arc-Ci4EnVJs.js} +1 -1
  13. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-BfrVQFaO.js → architectureDiagram-T3A2C74G-C9Hnq824.js} +1 -1
  14. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DFl6xIeQ.js → blockDiagram-VBNYF7ZC-Erza3vCj.js} +1 -1
  15. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BkeCachn.js → c4Diagram-5PPSVZJV-DhiEJ_zn.js} +1 -1
  16. package/dist/worker/console/static/assets/channel-o866H8CG.js +1 -0
  17. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DKbA7wvS.js → chunk-2GRJ4B5K-Jwoe5Hha.js} +1 -1
  18. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-COeFrK0l.js → chunk-2Q5K7J3B-B2p-ASWD.js} +1 -1
  19. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-DN50xlDZ.js → chunk-5RXB4S5H-CinVrkm9.js} +1 -1
  20. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-Cds3bTQr.js → chunk-5VM5RSS4-DPEKo8K0.js} +1 -1
  21. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-GnSZ3Q_F.js → chunk-6Q2QTUOP-BWkVY9W5.js} +1 -1
  22. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-C6UwY9nR.js → chunk-GF5L2VYU-CMFm2SFJ.js} +1 -1
  23. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BuYYcpOE.js → chunk-JWPE2WC7-Du_X-MSA.js} +1 -1
  24. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-BksBBron.js → chunk-KBJHAD2P-cTlf6fnC.js} +1 -1
  25. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-lATCww1u.js → chunk-RYQCIY6F-C5ve9fxF.js} +1 -1
  26. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-w1pNKtr7.js → chunk-XXDRQBXY-CRxS8vXT.js} +1 -1
  27. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-iDhRZSeN.js +1 -0
  28. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-iDhRZSeN.js +1 -0
  29. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-C-M-DjUn.js → cose-bilkent-JH36ORCC-BEnyQAzp.js} +1 -1
  30. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-zh47XBGY.js → cynefinDiagram-MW4NZA55-DvPiK5od.js} +1 -1
  31. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-DmBrLR56.js → dagre-VZM6K2ZE-DxigWx8E.js} +1 -1
  32. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-_aQq1Uwl.js → diagram-7IWD3JNH-D50wvAbw.js} +1 -1
  33. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-rD-1FbDW.js → diagram-B4RE2ZJO-B6PmMJzk.js} +1 -1
  34. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-BIOtuSUO.js → diagram-LBJQPF4R-BbT1ZLia.js} +1 -1
  35. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-COYOUs-A.js → diagram-Q27KOJAE-CizMPXm7.js} +1 -1
  36. package/dist/worker/console/static/assets/{diagram-UB23O5K3-DHBljm5_.js → diagram-UB23O5K3-DjxNSFmF.js} +1 -1
  37. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-B2aPoFUL.js → ebnfDiagram-BXEA7PRR-Bwg25Xpv.js} +1 -1
  38. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-S3jGp2gH.js → erDiagram-JOGREHBK-aHHIkVbd.js} +1 -1
  39. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-4PZPJme4.js → flowDiagram-UKHOOZJN-CBQFor5-.js} +1 -1
  40. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-hY9AqGVo.js → ganttDiagram-PKOTCBZU-Bhv0b_Ay.js} +1 -1
  41. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DBNB0wWX.js → gitGraphDiagram-DS77QQ5N-CcTjAWTv.js} +1 -1
  42. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-Cej8plCh.js → infoDiagram-6WML65LV-Bwt6_MRI.js} +1 -1
  43. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BmeNegTv.js → ishikawaDiagram-WSZJBQD7-JcDN-oJ0.js} +1 -1
  44. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BlL2uW1B.js → journeyDiagram-NVQOT4AX-C7YA3mW8.js} +1 -1
  45. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BUQ6cZg2.js → kanban-definition-27J2QSJJ-CfgSiedW.js} +1 -1
  46. package/dist/worker/console/static/assets/{linear-XcBbsyGj.js → linear-Dy5YZwCe.js} +1 -1
  47. package/dist/worker/console/static/assets/{main-C9HyHMYb.css → main-C537vZah.css} +1 -1
  48. package/dist/worker/console/static/assets/{main-BtQuxoWS.js → main-D39kbkZI.js} +124 -124
  49. package/dist/worker/console/static/assets/{mermaid.core-CIj0Ef-_.js → mermaid.core-CWATftfi.js} +4 -4
  50. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-J2HWWWHK.js → mindmap-definition-FAOFIHXS-DXcCCbEa.js} +1 -1
  51. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-Bi4Txdnd.js → pegDiagram-VL7TDLO6-CoS0ZgLy.js} +1 -1
  52. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-C_Ir9kQa.js → pieDiagram-7S7Q4E2Y-DotRKEI5.js} +1 -1
  53. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-Wmzc16HI.js → quadrantDiagram-CIZ2JOQS-DMdkO7Rz.js} +1 -1
  54. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BBlE2mdV.js → railroadDiagram-AXF67PYL-rj-Qc0fo.js} +1 -1
  55. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-10tJvPpg.js → requirementDiagram-LRYGKXZP-DDBta62g.js} +1 -1
  56. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-CMyZUusG.js → sankeyDiagram-W5VNT64P-DWqZxqI8.js} +1 -1
  57. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BAMpiKB0.js → sequenceDiagram-SI44F4Z6-C0fVeYqG.js} +1 -1
  58. package/dist/worker/console/static/assets/{sheet-workbook-C-2fz9qI.js → sheet-workbook-CNv6AzfM.js} +1 -1
  59. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-f5t9RbJB.js → sizeCapture-X5ZJPWSS-DOvvHUh-.js} +1 -1
  60. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-EMnmXMw9.js → stateDiagram-OKZ733FA-DgqVm117.js} +1 -1
  61. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-8zVknfpQ.js +1 -0
  62. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BosIuNEF.js → swimlanes-SLNWSIFB-C6H8hfVq.js} +2 -2
  63. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BTTCojly.js +8 -0
  64. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-dhqGUSL1.js → timeline-definition-Z64GVDOM-DyUP-YKn.js} +1 -1
  65. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-Buj6-SnQ.js → vennDiagram-T6HMQDX7-CwY3bnAh.js} +1 -1
  66. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BdmO-2xt.js → wardleyDiagram-T6FBY63Y-DE1T6Hko.js} +1 -1
  67. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-dbO2MqJN.js → xychartDiagram-ELKLHX3M-C0h8BPyy.js} +1 -1
  68. package/dist/worker/console/static/index.html +2 -2
  69. package/dist/worker/console/static-src/operator-chat/compaction-message.js +4 -0
  70. package/package.json +3 -3
  71. package/dist/worker/console/static/assets/channel-bnnK2hoC.js +0 -1
  72. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CRSYuU2u.js +0 -1
  73. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CRSYuU2u.js +0 -1
  74. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-pqCJTCQK.js +0 -1
  75. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-6P0fI_e1.js +0 -8
package/CHANGELOG.md CHANGED
@@ -41,7 +41,7 @@
41
41
  - 修复任务管理把已收起的子代理仍然画在图上,导致聚合卡片和成员卡片同时出现、连线交叉杂乱的问题。
42
42
  - 修复点击子代理详情后跳到仓库文件页而不是子代理内容的问题。
43
43
 
44
- ## [0.52.0-next.5] - 2026-10-20
44
+ ## [0.52.0-next.6] - 2026-10-21
45
45
 
46
46
  本预发布快照记录构建时已整理的待发布变化,不表示相对上一构建全部新增。
47
47
 
@@ -98,6 +98,8 @@
98
98
 
99
99
  ### 修复
100
100
 
101
+ - 修复自建网关在模型声明的上下文窗口之下就拒绝请求时,压缩始终不触发、每段长对话都只能退回到信息量很少的本地摘要的问题。在「模型与认证」里填上网关实际接受的输入上限后,压缩会在被拒绝之前开始,并正常请求模型摘要。
102
+ - 无法请求模型摘要时的本地兜底摘要保留更多内容:范围更大的近期对话、更长的上一轮摘要,待办列表不再挤占目标与文件清单的空间;中文对话拿到的篇幅与英文一致。
101
103
  - 修复较长文件读取和搜索结果在上下文整理后丢失原文的问题;普通日志仍可压缩,精确文件修改会保留必要源码。
102
104
  - 修复 provider 拒绝过大上下文时重复发送完整摘要请求的问题;现在优先使用 provider 摘要,超限时改用本地 checkpoint 继续恢复。
103
105
  - 手动压缩不再因为保留窗口过大而拒绝已有少量历史的会话。
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "version": "0.52.0-next.5",
4
- "gitSha": "00048f89d5f8b3db9d1ff7e0051feaf7a48e8a97",
5
- "builtAt": "2026-10-20T12:22:24.568Z"
3
+ "version": "0.52.0-next.6",
4
+ "gitSha": "e1881b3b681c5af2e87f2541f709dbcd87636343",
5
+ "builtAt": "2026-10-20T17:00:00.683Z"
6
6
  }
@@ -1,4 +1,25 @@
1
- const CHECKPOINT_MAX_BYTES = 12 * 1024;
1
+ const CHECKPOINT_MAX_BYTES = 16 * 1024;
2
+ /*
3
+ * Per-section BYTE budgets.
4
+ *
5
+ * The checkpoint limit is a byte limit (`truncateUtf8` counts UTF-8 bytes), so
6
+ * every budget here is bytes too. Naming them as characters and feeding them to
7
+ * a byte-level truncator silently gave CJK content a third of its intended
8
+ * room, which is how a Chinese-language session ended up with a summary that
9
+ * looked far emptier than the English one for the same input.
10
+ *
11
+ * The sum deliberately exceeds the total budget: sections are fitted to the
12
+ * real limit afterwards, sacrificing the lowest priority first.
13
+ */
14
+ const GOAL_MAX_BYTES = 2_400;
15
+ const PROGRESS_MAX_BYTES = 5_000;
16
+ /** How far back the Progress section looks for visible text. */
17
+ const PROGRESS_MAX_MESSAGES = 24;
18
+ const FILES_MAX_BYTES = 2_400;
19
+ const ERROR_MAX_BYTES = 1_400;
20
+ const TODOS_MAX_BYTES = 1_600;
21
+ const PREVIOUS_SUMMARY_MAX_BYTES = 4_000;
22
+ const CUSTOM_INSTRUCTIONS_MAX_BYTES = 1_200;
2
23
  function truncateUtf8(value, maxBytes) {
3
24
  if (maxBytes <= 0)
4
25
  return "";
@@ -17,10 +38,20 @@ function truncateUtf8(value, maxBytes) {
17
38
  }
18
39
  return `${result}${ellipsis}`;
19
40
  }
20
- function boundText(value, maxChars) {
41
+ /**
42
+ * Bound a string to a BYTE budget, keeping whole characters.
43
+ *
44
+ * Section budgets are bytes because the checkpoint limit is bytes. Cutting on
45
+ * `String.length` counts UTF-16 code units, so the same budget admitted three
46
+ * times as much Chinese as English and the sections never lined up with the
47
+ * real limit.
48
+ */
49
+ function boundText(value, maxBytes) {
21
50
  if (typeof value !== "string" || !value.trim())
22
51
  return "";
23
- return value.length <= maxChars ? value : `${value.slice(0, Math.max(0, maxChars - 1))}…`;
52
+ if (Buffer.byteLength(value, "utf8") <= maxBytes)
53
+ return value;
54
+ return truncateUtf8(value, maxBytes);
24
55
  }
25
56
  function asRecord(value) {
26
57
  return value !== null && typeof value === "object" && !Array.isArray(value)
@@ -140,21 +171,30 @@ function extractLastUserGoal(messages) {
140
171
  continue;
141
172
  const content = message.content;
142
173
  if (typeof content === "string")
143
- return boundText(content, 900);
174
+ return boundText(content, GOAL_MAX_BYTES);
144
175
  if (Array.isArray(content)) {
145
176
  const texts = content.map((block) => {
146
177
  const rec = asRecord(block);
147
178
  return typeof rec?.text === "string" ? rec.text : "";
148
179
  }).filter(Boolean);
149
180
  if (texts.length > 0)
150
- return boundText(texts.join("\n"), 900);
181
+ return boundText(texts.join("\n"), GOAL_MAX_BYTES);
151
182
  }
152
183
  }
153
184
  return "";
154
185
  }
186
+ /**
187
+ * Visible assistant/user text for the Progress section.
188
+ *
189
+ * The checkpoint used to keep only the last 8 messages, which drops an entire
190
+ * analysis chain the moment a long turn compacts: the model restarts without
191
+ * the reasoning it just produced and redoes the work. Widening the window and
192
+ * keeping the NEWEST entries first means the tail of the analysis survives even
193
+ * when the section is later truncated.
194
+ */
155
195
  function extractVisibleProgress(messages) {
156
196
  const lines = [];
157
- for (const message of messages.slice(-8)) {
197
+ for (const message of messages.slice(-PROGRESS_MAX_MESSAGES)) {
158
198
  const record = asRecord(message);
159
199
  if (!record || (record.role !== "assistant" && record.role !== "user"))
160
200
  continue;
@@ -170,7 +210,7 @@ function extractVisibleProgress(messages) {
170
210
  lines.push(`${String(record.role)}: ${text}`);
171
211
  }
172
212
  }
173
- return boundText(lines.join("\n"), 1800);
213
+ return boundText(lines.join("\n"), PROGRESS_MAX_BYTES);
174
214
  }
175
215
  function extractTodos(details) {
176
216
  const record = asRecord(details);
@@ -182,7 +222,7 @@ function extractTodos(details) {
182
222
  const status = typeof rec?.status === "string" ? rec.status : "pending";
183
223
  const content = typeof rec?.content === "string" ? rec.content : typeof rec?.title === "string" ? rec.title : "";
184
224
  return content ? `- [${status}] ${content}` : "";
185
- }).filter(Boolean).join("\n"), 1800);
225
+ }).filter(Boolean).join("\n"), TODOS_MAX_BYTES);
186
226
  }
187
227
  function extractFileOps(fileOps) {
188
228
  const parts = [];
@@ -195,18 +235,43 @@ function extractFileOps(fileOps) {
195
235
  function section(title, body) {
196
236
  return body ? `## ${title}\n${body}` : `## ${title}`;
197
237
  }
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));
238
+ /**
239
+ * Fit the sections into the byte limit, sacrificing low-priority content first.
240
+ *
241
+ * Two bugs drove this rewrite:
242
+ *
243
+ * 1. Truncation started at index 0, so an oversized section at the top ate the
244
+ * budget and the goal/error sections were the first to be cut.
245
+ * 2. `Pending Jobs` lived in the untouchable tail. Its bytes were counted as
246
+ * fixed overhead but it was never shrunk, so a long todo list could consume
247
+ * most of the checkpoint while the goal and file list were squeezed to a
248
+ * few dozen bytes.
249
+ *
250
+ * Now every section competes for the same budget and only the genuinely fixed
251
+ * closing lines are exempt.
252
+ */
253
+ function fitSections(sections, fixedTail) {
254
+ const separatorBytes = 2 * Math.max(0, sections.length);
255
+ const fixedBytes = Buffer.byteLength(fixedTail, "utf8") + separatorBytes;
256
+ const available = Math.max(0, CHECKPOINT_MAX_BYTES - fixedBytes);
201
257
  const texts = sections.map(({ text, budget }) => truncateUtf8(text, budget));
202
258
  let used = texts.reduce((sum, text) => sum + Buffer.byteLength(text, "utf8"), 0);
203
- for (let index = 0; used > available && index < texts.length; index += 1) {
259
+ if (used <= available) {
260
+ return [...texts, fixedTail].join("\n\n");
261
+ }
262
+ // Drop from the least important section until the overage is covered.
263
+ const order = sections
264
+ .map((entry, index) => ({ index, priority: entry.priority }))
265
+ .sort((left, right) => left.priority - right.priority);
266
+ for (const { index } of order) {
267
+ if (used <= available)
268
+ break;
204
269
  const current = texts[index];
205
270
  const next = truncateUtf8(current, Math.max(0, Buffer.byteLength(current, "utf8") - (used - available)));
206
271
  used -= Buffer.byteLength(current, "utf8") - Buffer.byteLength(next, "utf8");
207
272
  texts[index] = next;
208
273
  }
209
- return [...texts, tail].join("\n\n");
274
+ return [...texts, fixedTail].join("\n\n");
210
275
  }
211
276
  export function buildOverflowCheckpoint(input) {
212
277
  const preparation = normalizeCompactionPreparation(input.preparation);
@@ -217,22 +282,27 @@ export function buildOverflowCheckpoint(input) {
217
282
  const progress = extractVisibleProgress(messages);
218
283
  const todos = extractTodos(input.todos);
219
284
  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."}`),
285
+ const error = typeof input.lastError === "string" && input.lastError ? boundText(input.lastError, ERROR_MAX_BYTES) : "";
286
+ const customInstructions = boundText(input.customInstructions, CUSTOM_INSTRUCTIONS_MAX_BYTES);
287
+ const previousSummary = boundText(preparation.previousSummary, PREVIOUS_SUMMARY_MAX_BYTES);
288
+ /*
289
+ * Only the closing instructions are exempt from the budget: they are what
290
+ * tells the model how to resume, and losing them is what makes a checkpoint
291
+ * useless. Everything else — including the todo list — competes for space.
292
+ */
293
+ const fixedTail = [
225
294
  section("Next Steps", "Next step: continue the interrupted turn from the kept recent messages. Do not repeat completed file writes."),
226
295
  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
296
  section("Recovery Note", "This deterministic checkpoint was created without a model summary request. Details not restated here remain in the kept recent messages."),
228
297
  ].join("\n\n");
229
298
  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);
299
+ { text: "Deterministic local compaction checkpoint (no extra summary request).", budget: 900, priority: 6 },
300
+ { text: section("Goal", `Latest user goal:\n${goal || "No recent user goal was available."}`), budget: GOAL_MAX_BYTES, priority: 5 },
301
+ { text: section("Progress", [previousSummary ? `Previous summary:\n${previousSummary}` : "", progress].filter(Boolean).join("\n")), budget: PROGRESS_MAX_BYTES, priority: 1 },
302
+ { text: section("Files and Code", `File ops:\n${files || "No file operations were recorded."}`), budget: FILES_MAX_BYTES, priority: 3 },
303
+ { text: section("Errors and Fixes", error ? `Latest error:\n${error}` : "No recent provider error was recorded."), budget: ERROR_MAX_BYTES, priority: 2 },
304
+ { text: section("Pending Jobs", `Open todos:\n${todos || "No structured pending jobs recorded."}`), budget: TODOS_MAX_BYTES, priority: 4 },
305
+ ], fixedTail);
236
306
  return {
237
307
  summary: truncateUtf8(summary, CHECKPOINT_MAX_BYTES),
238
308
  firstKeptEntryId: preparation.firstKeptEntryId,
@@ -4,6 +4,19 @@ export const DEFAULT_TRAILING_BUDGET_TOKENS = 8_192;
4
4
  export const DEFAULT_SAFETY_MARGIN_TOKENS = 4_096;
5
5
  export const DEFAULT_MINIMUM_WORKING_SET = 32_768;
6
6
  export const DEFAULT_KEEP_RECENT_TOKENS = 20_000;
7
+ /**
8
+ * Convert a trigger line into the reserve Pi needs to compute that same line.
9
+ *
10
+ * `declared - triggerTokens` is positive whenever the trigger is below the
11
+ * declared window, which `deriveEffectiveWindow` already guarantees. A
12
+ * non-positive trigger means the window was unusable, so the plain reserve is
13
+ * kept rather than asking Pi to compact on every request.
14
+ */
15
+ function piReserveFor(declared, triggerTokens, plainReserve) {
16
+ if (triggerTokens <= 0)
17
+ return plainReserve;
18
+ return Math.min(Math.max(1, declared - triggerTokens), Math.max(1, declared - 1));
19
+ }
7
20
  export function parseCompactionPolicy(env = process.env) {
8
21
  const diagnostics = [];
9
22
  const modeResult = readContextPressureMode(env);
@@ -24,6 +37,25 @@ export function parseCompactionPolicy(env = process.env) {
24
37
  : parseBoundedNumber(explicit, PI_DEFAULT_RESERVE_TOKENS, 1_024, 1_000_000);
25
38
  if (explicitReserve?.diagnostic)
26
39
  diagnostics.push(explicitReserve.diagnostic);
40
+ // A gateway limit that is absent means "no separate cap", which is the
41
+ // common case for direct provider access; only a positive value constrains
42
+ // the trigger. Parsing happens only when the value can mean something, since
43
+ // `parseBoundedNumber` clamps 0 up to the minimum instead of rejecting it.
44
+ const gatewayLimitRaw = env.HARNESS_GATEWAY_INPUT_LIMIT_TOKENS?.trim();
45
+ const gatewayLimit = gatewayLimitRaw === undefined ||
46
+ gatewayLimitRaw === "" ||
47
+ !/^\d+$/.test(gatewayLimitRaw) ||
48
+ Number(gatewayLimitRaw) <= 0
49
+ ? undefined
50
+ : parseBoundedNumber(gatewayLimitRaw, 0, 1_024, 10_000_000);
51
+ if (gatewayLimit?.diagnostic)
52
+ diagnostics.push(gatewayLimit.diagnostic);
53
+ const keepRecentRaw = env.HARNESS_COMPACTION_KEEP_RECENT_TOKENS;
54
+ const keepRecent = keepRecentRaw === undefined || keepRecentRaw.trim() === ""
55
+ ? undefined
56
+ : parseBoundedNumber(keepRecentRaw, 0, 0, 1_000_000);
57
+ if (keepRecent?.diagnostic)
58
+ diagnostics.push(keepRecent.diagnostic);
27
59
  return {
28
60
  mode: modeResult.mode,
29
61
  k: k.value,
@@ -31,23 +63,41 @@ export function parseCompactionPolicy(env = process.env) {
31
63
  safetyMarginTokens: safety.value,
32
64
  minimumWorkingSet: DEFAULT_MINIMUM_WORKING_SET,
33
65
  ...(explicitReserve ? { explicitReserveTokens: explicitReserve.value } : {}),
66
+ ...(gatewayLimit && gatewayLimit.value > 0
67
+ ? { gatewayInputLimitTokens: gatewayLimit.value }
68
+ : {}),
69
+ ...(keepRecent ? { keepRecentTokens: keepRecent.value } : {}),
34
70
  diagnostics,
35
71
  };
36
72
  }
37
73
  export function deriveEffectiveWindow(contextWindow, policy) {
38
- const W = Math.floor(contextWindow);
39
- if (!Number.isFinite(W) || W <= 0) {
74
+ const declared = Math.floor(contextWindow);
75
+ if (!Number.isFinite(declared) || declared <= 0) {
40
76
  return {
41
77
  recommendedReserve: PI_DEFAULT_RESERVE_TOKENS,
42
78
  triggerTokens: 0,
79
+ piReserveTokens: PI_DEFAULT_RESERVE_TOKENS,
43
80
  fallback: true,
44
81
  };
45
82
  }
83
+ /*
84
+ * The trigger must fire before the gateway refuses the request, so it is
85
+ * bounded by the smaller of what the model declares and what the gateway
86
+ * accepts. Shrinking only the trigger keeps `contextWindow` itself truthful
87
+ * (it still describes the model) and leaves `maxTokens` accounting alone.
88
+ */
89
+ const W = policy.gatewayInputLimitTokens !== undefined &&
90
+ policy.gatewayInputLimitTokens > 0 &&
91
+ policy.gatewayInputLimitTokens < declared
92
+ ? Math.floor(policy.gatewayInputLimitTokens)
93
+ : declared;
46
94
  if (policy.explicitReserveTokens !== undefined) {
47
95
  const recommendedReserve = Math.min(Math.max(policy.explicitReserveTokens, 1), Math.max(1, W - 1));
96
+ const triggerTokens = Math.max(0, W - recommendedReserve);
48
97
  return {
49
98
  recommendedReserve,
50
- triggerTokens: Math.max(0, W - recommendedReserve),
99
+ triggerTokens,
100
+ piReserveTokens: piReserveFor(declared, triggerTokens, recommendedReserve),
51
101
  fallback: false,
52
102
  };
53
103
  }
@@ -60,16 +110,20 @@ export function deriveEffectiveWindow(contextWindow, policy) {
60
110
  !Number.isFinite(rawReserve) ||
61
111
  maxReserve < PI_DEFAULT_RESERVE_TOKENS) {
62
112
  const recommendedReserve = Math.min(PI_DEFAULT_RESERVE_TOKENS, Math.max(1, W - 1));
113
+ const triggerTokens = Math.max(0, W - recommendedReserve);
63
114
  return {
64
115
  recommendedReserve,
65
- triggerTokens: Math.max(0, W - recommendedReserve),
116
+ triggerTokens,
117
+ piReserveTokens: piReserveFor(declared, triggerTokens, recommendedReserve),
66
118
  fallback: true,
67
119
  };
68
120
  }
69
121
  const recommendedReserve = Math.min(Math.max(PI_DEFAULT_RESERVE_TOKENS, rawReserve), maxReserve);
122
+ const triggerTokens = Math.max(0, W - recommendedReserve);
70
123
  return {
71
124
  recommendedReserve,
72
- triggerTokens: Math.max(0, W - recommendedReserve),
125
+ triggerTokens,
126
+ piReserveTokens: piReserveFor(declared, triggerTokens, recommendedReserve),
73
127
  fallback: false,
74
128
  };
75
129
  }
@@ -108,23 +162,61 @@ function isExplicitlyDisabled(manager) {
108
162
  const global = manager.getGlobalSettings?.()?.compaction?.enabled;
109
163
  return project === false || (project === undefined && global === false);
110
164
  }
165
+ /**
166
+ * How much history to keep verbatim after a compaction.
167
+ *
168
+ * `keepRecentTokens: 0` looks attractive — it lets any session compact — but it
169
+ * puts the ENTIRE branch into `messagesToSummarize`. The summary request then
170
+ * carries the same oversized history the provider just rejected, so it fails
171
+ * too, and recovery falls through to the local checkpoint. That is exactly the
172
+ * regression that made provider summaries disappear in favour of the
173
+ * deterministic checkpoint.
174
+ *
175
+ * The retained tail must therefore be small enough that the summary request
176
+ * itself fits: a fraction of the trigger line, capped so long sessions keep
177
+ * useful recent context and floored so Pi still has something to summarize.
178
+ */
179
+ export const KEEP_RECENT_TRIGGER_RATIO = 0.15;
180
+ export const KEEP_RECENT_MAX_TOKENS = 30_000;
181
+ export const KEEP_RECENT_MIN_TOKENS = 2_000;
182
+ export function resolveKeepRecentTokens(input) {
183
+ if (Number.isFinite(input.explicit)) {
184
+ return Math.max(0, Math.floor(input.explicit));
185
+ }
186
+ if (input.policy.keepRecentTokens !== undefined) {
187
+ return Math.max(0, Math.floor(input.policy.keepRecentTokens));
188
+ }
189
+ if (typeof input.triggerTokens === "number" &&
190
+ Number.isFinite(input.triggerTokens) &&
191
+ input.triggerTokens > 0) {
192
+ const scaled = Math.floor(input.triggerTokens * KEEP_RECENT_TRIGGER_RATIO);
193
+ return Math.min(Math.max(scaled, KEEP_RECENT_MIN_TOKENS), KEEP_RECENT_MAX_TOKENS);
194
+ }
195
+ return DEFAULT_KEEP_RECENT_TOKENS;
196
+ }
111
197
  export function applyProcessCompactionOverride(manager, input) {
112
198
  if (!manager?.applyOverrides || input.policy.mode === "off") {
113
199
  return { applied: false };
114
200
  }
115
201
  const explicitOff = input.policy.mode === "safe" && isExplicitlyDisabled(manager);
116
202
  const enabled = input.policy.mode === "strict" ? true : explicitOff ? false : true;
117
- const window = typeof input.contextWindow === "number" && input.contextWindow > 0
118
- ? deriveEffectiveWindow(input.contextWindow, input.policy)
203
+ const declaredWindow = typeof input.declaredContextWindow === "number" &&
204
+ input.declaredContextWindow > 0
205
+ ? input.declaredContextWindow
206
+ : input.contextWindow;
207
+ const window = typeof declaredWindow === "number" && declaredWindow > 0
208
+ ? deriveEffectiveWindow(declaredWindow, input.policy)
119
209
  : undefined;
120
210
  const compaction = { enabled };
121
211
  if (enabled) {
122
- compaction.keepRecentTokens = Number.isFinite(input.keepRecentTokens)
123
- ? Math.max(0, Math.floor(input.keepRecentTokens))
124
- : DEFAULT_KEEP_RECENT_TOKENS;
212
+ compaction.keepRecentTokens = resolveKeepRecentTokens({
213
+ policy: input.policy,
214
+ explicit: input.keepRecentTokens,
215
+ triggerTokens: window?.triggerTokens,
216
+ });
125
217
  }
126
218
  if (window && enabled) {
127
- compaction.reserveTokens = window.recommendedReserve;
219
+ compaction.reserveTokens = window.piReserveTokens;
128
220
  }
129
221
  manager.applyOverrides({ compaction });
130
222
  return {
@@ -133,6 +225,7 @@ export function applyProcessCompactionOverride(manager, input) {
133
225
  ...(typeof compaction.reserveTokens === "number"
134
226
  ? { reserveTokens: compaction.reserveTokens }
135
227
  : {}),
228
+ ...(window ? { triggerTokens: window.triggerTokens } : {}),
136
229
  ...(typeof compaction.keepRecentTokens === "number"
137
230
  ? { keepRecentTokens: compaction.keepRecentTokens }
138
231
  : {}),
@@ -9,6 +9,7 @@ export function createCompactionController() {
9
9
  return {
10
10
  proactiveCompaction: false,
11
11
  manualCheckpointFallbackArmed: false,
12
+ summaryRetryPending: undefined,
12
13
  pruneArmed: false,
13
14
  pruneStatus: undefined,
14
15
  pruneDiagnostic: undefined,
@@ -67,9 +68,12 @@ export function createContextPressureExtension(options) {
67
68
  }
68
69
  if (l2) {
69
70
  api.on("session_compact_failed", (event) => {
71
+ // A provider summary that itself hit the context ceiling is the
72
+ // signal to stop asking the model and fall back locally. This
73
+ // covers both entry points: an automatic overflow retry and a
74
+ // manual compaction whose summary request was rejected.
70
75
  options.controller.manualCheckpointFallbackArmed =
71
- event.reason === "manual" &&
72
- !event.fromExtension &&
76
+ !event.fromExtension &&
73
77
  !event.aborted &&
74
78
  isContextOverflow(event.errorMessage);
75
79
  return undefined;
@@ -91,14 +95,27 @@ export function createContextPressureExtension(options) {
91
95
  if (reason === "manual") {
92
96
  incrementCounter(options.controller.counters, "manual");
93
97
  }
94
- const useCheckpoint = (reason === "overflow" && providerOverflow) ||
95
- (reason === "manual" &&
96
- options.controller.manualCheckpointFallbackArmed);
97
- if (!useCheckpoint)
98
+ /*
99
+ * The provider summary is tried FIRST, even after the gateway
100
+ * rejected the previous request.
101
+ *
102
+ * Taking over on the first overflow is what made every session
103
+ * end on the deterministic checkpoint: one 400 from the gateway
104
+ * permanently downgraded the summary quality for that compaction,
105
+ * with no chance to see whether a smaller request would have
106
+ * worked. Only a FAILED summary request arms the local fallback
107
+ * (see session_compact_failed above), so reaching this branch
108
+ * means the model already declined.
109
+ */
110
+ const useCheckpoint = options.controller.manualCheckpointFallbackArmed;
111
+ if (!useCheckpoint) {
112
+ if (reason === "overflow" && providerOverflow) {
113
+ incrementCounter(options.controller.counters, "overflow-summary-retry");
114
+ options.controller.summaryRetryPending = true;
115
+ }
98
116
  return undefined;
99
- if (reason === "manual") {
100
- options.controller.manualCheckpointFallbackArmed = false;
101
117
  }
118
+ options.controller.manualCheckpointFallbackArmed = false;
102
119
  const checkpoint = buildOverflowCheckpoint({
103
120
  preparation: event.preparation,
104
121
  customInstructions: event.customInstructions,
@@ -2,6 +2,7 @@ export function emptyContextPressureCounters() {
2
2
  return {
3
3
  prePromptThreshold: 0,
4
4
  overflow: 0,
5
+ overflowSummaryRetry: 0,
5
6
  manual: 0,
6
7
  wireCompression: 0,
7
8
  failOpen: 0,
@@ -25,6 +26,9 @@ export function incrementCounter(counters, reason, amount = 1) {
25
26
  case "overflow":
26
27
  counters.overflow += amount;
27
28
  break;
29
+ case "overflow-summary-retry":
30
+ counters.overflowSummaryRetry += amount;
31
+ break;
28
32
  case "manual":
29
33
  counters.manual += amount;
30
34
  break;
@@ -48,6 +52,7 @@ export function projectSafeTelemetry(counters) {
48
52
  return {
49
53
  prePromptThreshold: counters.prePromptThreshold,
50
54
  overflow: counters.overflow,
55
+ overflowSummaryRetry: counters.overflowSummaryRetry,
51
56
  manual: counters.manual,
52
57
  wireCompression: counters.wireCompression,
53
58
  failOpen: counters.failOpen,
@@ -370,6 +370,10 @@ export function turnEventToStorePartial(event) {
370
370
  ? { estimatedTokensAfter: event.estimatedTokensAfter }
371
371
  : {}),
372
372
  willRetry: Boolean(event.willRetry),
373
+ ...(event.localFallback === true ? { localFallback: true } : {}),
374
+ ...(typeof event.localFallbackReason === "string"
375
+ ? { localFallbackReason: event.localFallbackReason }
376
+ : {}),
373
377
  ...(typeof event.errorMessage === "string"
374
378
  ? { errorMessage: event.errorMessage }
375
379
  : {}),