Skip to content

docs(context): compare compaction across Pi, Codex, Hermes, Grok, Claude, Gemini, and OpenCode #190

Open

Description

@tt-a1i

摘要

这是一次面向 OpenPI 的上下文压缩(context compaction)机制调研,固定比较以下实现:

  • OpenPI 2a69d3f32994da4123f1312b7fa84ef3d6119be1
  • Pi Coding Agent 0.84.3
  • OpenAI Codex CLI da4cf1cdeaf8fb44a18bb75fd8df0094097f90b8
  • Hermes Agent cbd8de8ad64530be01efea23b7764d5c37c634ed
  • xAI Grok Build c2ad97f87aea4303b6000a2c22128bc91ee76c9b
  • Gemini CLI 812f7a2bcf20b6e80e2e50c3c8fa8e26567bc1e8
  • OpenCode 8615731d46153dd29b89e205fb55b2cc16205cb0
  • OpenAI Responses API、xAI Compaction API、Anthropic Messages API/Claude Code 的当前官方文档

调研日期:2026-08-26。

核心结论

  1. OpenPI 当前没有第二套自动压缩器。 普通父 Session 和 child Session 的自动、手动、overflow compaction 都由 Pi 原生生命周期负责。OpenPI 的 context_pivot 是一次显式阶段切换:模型提交自包含 brief,Pi 负责写入 compaction entry。这个 ownership 边界是正确的,应当保留。Pi 0.84.3 的 session append 是同步持久化,但不是带 rollback/fsync 保证的事务性原子提交。
  2. “压缩”不是单一技术。 实际至少分为五类:
    • 删除旧工具结果或 thinking 的 deterministic pruning;
    • 用 LLM 把旧历史替换为可读 summary;
    • 服务端返回 opaque/encrypted compaction item;
    • 保留 recent tail、只压旧前缀;
    • 把 exact 内容外置为 artifact/memory,context 只保留恢复引用。
  3. Pi 的优势是简单、可恢复、生命周期清晰。 它有安全 cut point、split-turn、append-only session tree、手动/阈值/overflow 三条路径和明确 hook。缺点是 anti-thrashing、摘要 provenance/redaction、并发 append race 和“完整阶段丢弃”还不是一等 primitive。
  4. Hermes 的优势是恢复能力最强,但复杂度最高。 它将 pruning、摘要、tail、exact anchors、session search、cooldown、provider fallback 和 race watermark 都纳入压缩系统;这对产品成熟度有价值,但不适合直接复制到 OpenPI。
  5. Codex 与 Grok 的优势是 replacement state 与失败分类更完整。 Codex 同时支持 local/remote compaction;Grok 有 checkpoint/rewind、prefire two-pass 和 sticky suppression。代价是模式和状态机明显复杂。
  6. Gemini 的 70/30 + verification pass 很容易理解。 但字符估算不如 token-aware cut 精确,临时文件恢复边界和失败重试不够清楚。
  7. OpenCode 清楚地区分 prune 与 summary compaction。 durable marker + tail_start_id 很值得参考;当前主要缺口是 prune failure 可观测性不足,不能依据已过时的测试注释把已修复的 output-headroom 路径继续列为缺陷。
  8. 服务端 opaque compaction 与本地可读 summary 是两种产品合同。 OpenAI/xAI 的 opaque item 更能保留供应商内部 reasoning/state,但不可审计、不可跨模型、不可手工修正;Pi/Hermes/Gemini/OpenCode 的可读 summary 更透明、更可移植,但会把正确性押在总结模型和 prompt 上。
  9. Prompt caching 与 compaction 有天然张力。 压缩会改写 conversation prefix,通常导致 conversation cache 重建;正确优化不是拒绝压缩,而是稳定 system/tool prefix、单独设置 cache breakpoint,并只在实际回收量足够时 pruning。
  10. 对 OpenPI 最合理的近期方向不是再造 compressor,而是 upstream Pi hardening: first-class full pivot cut、summary provenance/redaction hook、append-race handling、anti-thrash evidence,以及 exact artifact → bounded projection → recovery pointer。

一、先统一术语

1. Context window

一次模型请求真正可见的输入、输出预留和部分 provider reasoning budget 的总上限。它不是整个 Session 文件大小,也不是累计 token 消费。

2. Compaction / summary compaction

用一段 successor-oriented summary 替换较早历史,同时选择性保留 recent tail。它是有损变换,完整历史是否仍持久化取决于 harness。

3. Pruning / context editing

不生成综合 summary,而是确定性删除或替换特定高体积内容,例如旧 tool result、thinking block、图片或超大参数。它通常更便宜、更可预测,但无法主动提炼跨消息决策。

4. Opaque server-side compaction

服务端返回不可读、不可编辑的 compaction item 或 encrypted blob。客户端把它当成 canonical prefix 原样回传。它可能保留公开 transcript 无法表达的模型内部 reasoning/state,但形成 provider lock-in。

5. Prompt caching

对完全一致的 prompt prefix 复用服务端 KV/cache。缓存不减少逻辑 context 长度,只降低重复计算、成本和 latency。删除、改写或重排旧消息通常会破坏发生改动位置之后的缓存。

6. Durable memory / artifact projection

把 exact 内容保存在 context 之外,通过文件、数据库、artifact 或 search tool 按需恢复。它不是 compaction,但能让 compaction 不必承担“记住所有原文”的不可能目标。

7. Context pivot

显式结束旧阶段,由调用者提供一个面向下一阶段的自包含 brief,再丢弃旧活跃上下文。它与阈值自动压缩不同:触发时机来自模型对任务阶段的判断,而不是 token 数。


二、OpenPI 与 Pi:真实 ownership

2.1 Pi 原生 compaction

Pi 0.84.3 的触发条件是:

contextTokens > contextWindow - reserveTokens

默认:

  • reserveTokens = 16,384
  • keepRecentTokens = 20,000
  • compaction.enabled = true

入口分为三类:

  1. /compact [instructions]:手动压缩,可附 focus;
  2. threshold:每次 assistant run 后检查,超过阈值自动压缩;
  3. overflow recovery:provider 明确返回 context overflow 时,移除失败响应、压缩并重试一次,防止无限循环。

源码/文档:

版本证据来自已安装 npm package @earendil-works/[email protected];其 package.json 将 source repository 标为 earendil-works/pi,对应 tag v0.84.3(commit 4e58f324fae8ebfa98a3d45181fb248072a2afac)。

2.2 Cut point 与 split turn

Pi 从后往前累计 recent token,寻找大约 keepRecentTokens 的保留边界。合法 cut point 是 user、assistant、bash、custom、branch summary 或 compaction summary entry;不会把 tool result 单独从对应 tool call 中切开。

若单个 turn 本身超过 recent budget,Pi 使用 split-turn:

  • 完整旧 turn 进入 history summary;
  • 当前大 turn 的前缀进入 turn-prefix summary;
  • 最新 suffix 保留原文。

这比简单“保留最后 N 条 message”更正确,因为 agent turn 可能包含大量 tool calls/results。

2.3 Summary 与持久化

Pi 使用结构化 continuation summary:Goal、Constraints、Progress、Key Decisions、Next Steps、Critical Context,并累计 <read-files> / <modified-files>。

Session 仍是 append-only JSONL/tree:

  • 旧消息不被物理删除;
  • 新增 compaction entry;
  • entry 记录 summary、firstKeptEntryId、tokensBefore、usage、details、hook provenance;
  • active branch context 从 summary + kept tail 重建;
  • /tree branch summarization 是另一条独立机制。

优势:可回看、可分支、可审计,compaction 不是 destructive rewrite。

2.4 OpenPI 的 context_pivot

OpenPI 没有修改上述自动压缩。extensions/context-pivot/index.ts 提供一个 parent-only 工具:

  • context 少于 30k tokens 时拒绝;
  • 模型提供目标、当前状态、关键决策、阻塞、artifact 路径和下一步;
  • extension 在 session_before_compact 提供该 brief;
  • Pi 仍拥有 compaction lifecycle、持久化和终态事件。

证据:

当前实现为了“旧阶段全部不保留”,给 Pi 一个不存在的 retained entry id,使重建结果成为 brief + pivot 后消息。行为有效,但它依赖非一等合同:更好的长期方向是 Pi 原生支持 retain: none / full-pivot cut。

2.5 OpenPI 不应混淆的三个东西

  • child result projection:为了父 context 有界,对 child final answer 做 head/tail projection,exact result 留 artifact;
  • Workflow handoff:把上游 Agent 结果注入 Report Agent 的有界数据通道;
  • Session compaction:替换父 Session 的旧 conversational context。

三者生命周期、authority 和恢复证据不同,不能用一个“全局压缩层”统一。

2.6 Pi/OpenPI 的优缺点

优势:

  • lifecycle owner 单一;
  • 自动、手动、overflow 行为清楚;
  • tool group 与 split turn 边界正确;
  • append-only history 和 branch semantics 强;
  • extension hook 可以替换 summary,但不能偷走 persistence owner;
  • summary request 使用 fresh routing session,避免一次性总结污染常规 prompt cache writes。

缺点:

  • 没有 first-class full-pivot cut;
  • anti-thrashing 只有简单 one-shot overflow recovery;
  • 没有 Hermes 式 exact anchor/recovery pointer;
  • summary redaction/provenance 策略较弱;
  • 并发消息在 summarization 期间追加时的合同不如 Hermes watermark 明确;
  • operator 看到的是 compaction 是否成功,缺少压缩前后 recall/coverage 指标。

三、Hermes Agent:恢复优先的多层压缩

固定源码:cbd8de8。

关键文件:

3.1 双层触发

Hermes 同时有:

  • Agent compressor:默认约 50% threshold;小于 512k 的模型实际 floor 会抬到至少 75%;特定 Codex route 可为 70%/85%;
  • Gateway hygiene:约 85% 的第二安全网,捕获逃过 Agent compressor 的 Session。

它还支持 per-model threshold、idle resume compaction、manual /compress、server-native Codex Responses compaction,以及 app-server owner 选择。

3.2 四阶段策略

典型流程不是直接总结全部历史:

  1. 先清理重复/旧 tool output、超大 arguments、历史 image 和 replay sidecar;
  2. 保护 system/head 与关键 user anchors;
  3. 生成 rolling summary;
  4. 保留一个 verbatim tail,并清理 orphan tool pairs。

Legacy tail 按 threshold × target_ratio 保留;lean tail 使用约 2.5% × context window,并 clamp 在 10k–25k。

3.3 Lean mode 的关键创新

Lean mode 不试图把大量原文一直塞在 context,而是保留:

  • identifier-preserving chunk digests;
  • regex 机械提取的 PR、SHA、path、error string 等 exact anchors;
  • 最近真实 user messages 原文;
  • session_search recovery pointer;
  • 被裁掉 tool result 的 one-line stub。

这是一种“summary + exact index + on-demand recovery”架构,比单纯写更长 summary 更可扩展。

3.4 Model 与 fallback

Hermes 可单独配置 compression model/provider,先走 auxiliary chain,失败时可 fallback 到 main model。它区分 auth/quota/network 等不可恢复错误与 transient 错误,并有重试、cooldown 和 anti-thrash 计数。

当前源码还包含 deterministic redacted fallback、summary provenance、skill marker reinjection、think-block 清理和 tool-pair sanitation。官方 guide 某些段落仍描述旧的“summary 失败后可能无 summary 丢 middle”行为,因此必须以固定 commit 源码为准,标注文档漂移。

3.5 Persistence 与并发

默认 in-place 模式:

  • 同一个 durable session id;
  • 旧 rows 标记 active=0, compacted=1,仍可搜索;
  • 新压缩 rows 原子替换 active projection;
  • summarization 期间新 append 的消息通过 watermark 保留,避免压缩结果覆盖并发到达内容。

这是本次比较里对 concurrent append race 处理最明确的实现。

3.6 优缺点

优势:

  • exact recovery 和 recall 设计最强;
  • model/provider fallback、cooldown、anti-thrash 完整;
  • redaction、provenance 和 tool pair 清理成熟;
  • 缓存回收价值与 prefix invalidation 被显式考虑;
  • in-place persistence 避免 session rotation 丢状态。

缺点:

  • policy surface 很大,配置、route、tail mode 和 fallback 容易组合爆炸;
  • compressor 已接近第二套 orchestration subsystem;
  • 文档容易追不上实现;
  • 更多总结调用和索引会增加成本;
  • 不适合直接搬入强调 Pi-native ownership 的 OpenPI。

四、OpenAI Codex CLI:local / remote 多模式 replacement

固定源码:da4cf1c。

关键文件:

4.1 Trigger 与模式

Codex 可以选择:

  • local summary compaction;
  • legacy remote compaction;
  • remote v2;
  • token-budget reset/fallback 路径。

自动检查发生在 sampling 后,也会处理 model/context window 下调、auto-compaction hash/window 变化等配置转换。与 Pi 不同,普通 provider overflow 不必然立即走统一 retry-compaction,而可能先作为错误返回;具体取决于 mode/path。

4.2 Local compaction

Local mode 通过普通 Responses stream 生成 summary,再安装 replacement history。它会:

  • 在 summarization request overflow 时继续裁老输入重试;
  • 保留最近真实 user messages,预算上限约 20k tokens;
  • 不把 image/audio 当作本地 summary 文本;
  • 安装 compacted item,并推进 auto-compaction window identity。

4.3 Remote compaction

Remote mode 把 compaction 交给 Codex server protocol:

  • preprocessing 可替换超大 tool outputs、去掉 tool-search payload;
  • remote v2 对 retained history 有更大预算(审计显示约 64k),单 agent message 另有限制;
  • replacement filter 去掉 reasoning、tool call/result 和 wrapper,只保留协议允许的 compacted state;
  • 支持 current/fallback model、stream retry,以及 cached-input/cache-write usage。

4.4 Replacement state

Codex 的 CompactedItem 不只是 summary 字符串,还可携带:

  • replacement history;
  • window ids;
  • MCP resource-origin metadata。

World-state baseline 与 turn context 是 rollout 中的独立 item,不是 CompactedItem 字段。Resume 会组合最新 replacement 与这些独立 runtime items 重建 authoritative context。这比“把 summary 当普通 assistant message”更结构化,但 local/remote/v2 多套路径也提高维护成本。

4.5 优缺点

优势:

  • 本地透明 summary 与服务端 richer state 都支持;
  • model/config transition 也参与触发判断;
  • replacement state 可与 rollout 中独立持久化的 runtime world-state/turn-context items 协同恢复;
  • remote v2 有详细 token/cache accounting;
  • summarization overflow 有输入缩减与 retry。

缺点:

  • 多 mode 产生行为差异;
  • reasoning/tool state 在不同路径的保留规则不一致;
  • remote item 依赖 OpenAI backend;
  • provider overflow 的统一性弱于 Pi;
  • 操作者很难仅从 UI 判断当前用了哪种 compaction owner。

五、OpenAI Responses API:opaque compaction item

官方文档:

5.1 两种入口

  1. Server-side auto compaction:在 /responses 设置:
{
  "context_management": [
    { "type": "compaction", "compact_threshold": 200000 }
  ]
}

当 rendered token count 越过阈值,服务端在同一 response stream 里执行 compaction、发出 encrypted compaction item、裁旧 context 后继续 inference。

  1. Standalone /responses/compact:客户端提交仍能放进 context window 的完整 items,服务端返回 canonical compacted window,下一次请求必须整体原样使用。

5.2 Stateful 与 stateless

  • stateless input-array chaining:把 output(包含 compaction item)append 到下一次 input;可以丢弃最新 compaction item 之前的 items;
  • previous_response_id:只发新 user turn,服务端维护 lineage,不应手工 prune;
  • Conversations API:durable conversation object;
  • store=false:可用于 ZDR-friendly 流程。

5.3 关键合同

  • item opaque,不用于人类阅读;
  • standalone compact output 通常不只一个 compaction item,整个 output 是 canonical next window,不能自行裁剪;
  • 输入在 compaction 前必须仍能装入 model context;
  • reasoning items 和 assistant phase 等 provider-specific state 可以随 output chain 保留;
  • 即使用 previous_response_id,之前 context tokens 仍按 input 计费,compaction 才真正缩短 rendered window。

5.4 优缺点

优势:更可能保留模型内部 reasoning/state;客户端逻辑少;支持 ZDR/stateless;服务端 token accounting 更权威。

缺点:不可审计、不可修改、不可跨 provider/model;离线恢复依赖 blob;质量无法通过 diff summary 直接检查;应用需要把 encrypted item 当敏感 canonical state 保护。


六、xAI Grok Build:checkpoint、prefire 与 suppression

固定源码:c2ad97f。

关键文件:

6.1 Trigger

Grok Build 支持:

  • /compact [context];
  • pre-request threshold;
  • tool-output 后 preflight;
  • overflow recovery;
  • remote-configurable threshold,默认/历史值约 85%。

可选 two-pass prefire 会在 hard threshold 前约 10 个百分点启动后台 pass 1。

6.2 Two-pass prefire

  • pass 1 在后台总结大约 95% prefix,产生 NOTE₁;
  • 到真正 compaction 时,若 model identity、prefix length、content fingerprint 仍匹配,pass 2 复用 NOTE₁;
  • 如果 stale,则放弃 cache,重新走安全路径;
  • telemetry 单独区分 prefire latency、foreground wait、hit/stale、TTFT、stream duration。

这是本次比较里最明确尝试隐藏用户可见 compaction latency 的实现。

6.3 Input ladder 与 failure suppression

Grok 会尝试多级 summarization input:

  1. verbatim;
  2. fitted verbatim;
  3. lossy bounded input。

最多三次 replacement attempt。失败会分类为 auth、credit、size、transient、schema/other,并产生不同作用域的 suppression;manual /compact 不受自动 suppression 限制。取消不重试。

6.4 Persistence / rewind / fork

  • compaction 前写 checkpoint;
  • replacement history 经过 sanitize + validate;
  • /rewind 依赖 checkpoint,缺失或损坏 fail closed;
  • fork session 尽量保留 inherited prefix,只有压缩后仍超过 threshold 才释放;
  • sessions 持久化 prompt、response、tool calls 和 file snapshots。

6.5 Backend 差异

  • Chat Completions 可能把 reasoning 折进 assistant message;
  • Responses 可保留 encrypted reasoning;
  • Messages preparation 可能去掉 reasoning;
  • compaction request 可配置 tool choice,理论上不应执行 tools,但 Auto 比 strict tool-denied surface 更宽。

6.6 优缺点

优势:checkpoint/rewind 最强;failure 分类和 sticky suppression 完整;prefire 可降低前台等待;telemetry 丰富;fork prefix 有明确策略。

缺点:状态机复杂;backend-specific behavior 多;prefire 本身消耗额外 token/请求;staleness 判断需要严格 fingerprint;工具 surface 应进一步收窄。


七、xAI Compaction API:单 opaque blob

官方文档:

7.1 合同

POST /v1/responses/compact 返回一个 response.compaction,其 output 包含单个:

{
  "type": "compaction",
  "encrypted_content": "<opaque blob>"
}

SDK 的 chat.compact() 会把 in-memory messages 原地替换成该 item。官方声明它保留 salient state,包括 system prompts、attached files、prior reasoning 和 compacted turn record,同时删除 verbose tool output/back-and-forth。

7.2 限制

  • 输入在 compact 前必须未超 window;
  • 每次请求最多一次 compaction;
  • encrypted content 不可 parse、编辑、重排或合并;
  • 可对已经 compacted conversation 再 compact;
  • compaction 本身计 input/output/reasoning tokens;
  • 文档建议可选更小/更快 model,但具体兼容性需要按 endpoint 验证。

7.3 Cache 关系

普通 multi-turn cache 要求旧 prefix 完全不变,只 append。compaction 会建立一个新的短 prefix,因此旧 conversation cache continuity 结束,后续请求围绕新 blob 重新缓存。reasoning model 的正常链路必须回传 encrypted reasoning content 或使用 stateful responses。

7.4 与 OpenAI opaque item 的差异

两者都使用 encrypted opaque state,但当前 xAI 文档描述的是单 compaction item,OpenAI standalone compact 明确可能返回“compaction item + retained items”的 canonical window。客户端不能假设两者 output shape 完全一致。


八、Claude Code:先清 tool output,再 summary,并重注入项目上下文

官方文档:

8.1 Trigger 与用户控制

Claude Code 会在接近 window limit 时自动压缩,也支持:

  • /compact [focus];
  • /autocompact <token-count>;
  • /rewind 后选择从某处/到某处 summarize;
  • /clear;
  • /context 查看占用。

若单一大文件/tool output 导致每次 summary 后立即再次爆满,Claude Code 在几次尝试后报告 thrashing error,而不是无限 compaction loop。

8.2 分层处理

官方描述:先清 older tool outputs;仍不足再 summarize conversation。compaction 后并非只剩一段 summary,Claude Code 会重新注入:

  • system prompt/output style;
  • project-root CLAUDE.md 与 unscoped rules;
  • auto memory;
  • plan-mode plan;
  • 最多五个最近修改的已读/已编辑文件(大于 5k token 时只注入 path reference);
  • invoked skill bodies,单 skill 5k、总计 25k,超限 oldest-first drop;
  • SessionStart source=compact hook output。

path-scoped rules 和 nested CLAUDE.md 以后随匹配文件重新加载。

8.3 Cache 设计

Claude Code 把 request 分为稳定 system prompt、project context、conversation 三层。/compact 改写 conversation layer,必然让该层 cache miss;system prompt layer 可以继续复用,project context 从磁盘重载后如果未变也可能复用。

summary request 使用与当前 conversation 相同的 system/tools/history,并在末尾 append summarization instruction。因此 warm cache 下 compaction request 大部分 prefix 可 cache-read;冷 resume 后 compaction 最贵。

8.4 优缺点

优势:对用户解释最清晰;项目规则、memory、skills 和最近文件都有明确 surviving contract;有 thrash stop;支持局部 rewind summary;缓存分层成熟。

缺点:核心 CLI 实现不是完整开源,无法像 Pi/Hermes/Gemini 一样审计 atomicity、cut algorithm 和失败边界;自动重读文件可能重新引入大量 context;早期精确指令仍可能在 summary 中丢失。


九、Anthropic API:compaction 与 context editing 是两条正交路径

官方文档:

9.1 Server-side summary compaction

Beta header:compact-2026-01-12;strategy:compact_20260112。

默认:

  • trigger:150,000 input tokens;
  • 最低可配值:50,000;
  • pause_after_compaction=false;
  • custom instructions 会完全替换 default summary prompt;
  • 同一个 request model 做 summary,不能指定更便宜 model。

触发后:

  1. 生成 summary;
  2. 返回可读 compaction content block;
  3. 同一 request 可继续 main response;
  4. 下一次把 block 回传;API 忽略它之前的 content blocks。

pause_after_compaction=true 可让客户端在 summary 后插入 recent verbatim messages,再继续请求。

9.2 Usage 与 caching

usage.iterations 分开列 compaction iteration 和 message iteration;top-level token 字段不包含 compaction iteration,成本统计必须求和。

compaction block 可独立设置 cache_control。最佳实践是在 system prompt 末尾也设 breakpoint,让 system prefix 在 conversation summary 变化时仍 cache-hit。

已知限制:若 request 定义 tools,内部 summarization 偶尔可能错误调用工具,返回 content: null 的 compaction block。官方建议 custom instructions 明确要求不调用工具。这说明服务端 compaction 仍应被视为可能失败的 model sampling,而不是确定性数据库操作。

9.3 Context editing

Beta header:context-management-2025-06-27。

两种 deterministic server-side edit:

  • clear_tool_uses_20250919
    • 默认 trigger 100k input tokens;
    • 默认保留最近 3 个 tool uses;
    • 默认只清 result,不清 input;
    • 可配 clear_at_least、exclude_tools、clear_tool_inputs;
    • 清除内容用 placeholder 告知模型。
  • clear_thinking_20251015
    • 按 model family 默认保留 all 或 last turn;
    • 可配最近 N thinking turns 或 all。

Context editing 发生在服务端,客户端仍保留完整原始 history。response 的 context_management.applied_edits 报告清除了多少 tool uses/thinking turns/tokens。

9.4 设计价值

Anthropic 最值得借鉴的是把 deterministic deletion 与 semantic summary 明确分开:

  • 旧 tool output 是可按年龄/类型删除的数据;
  • 跨 turn 决策与任务状态才需要 summary;
  • memory tool 在清理前收到提示,把重要信息外置;
  • clear_at_least 用实际回收价值平衡 cache invalidation。

十、Gemini CLI:70/30 split + 双阶段 summary verification

固定源码:812f7a2。

关键文件:

10.1 Trigger 与 split

  • 每个普通 turn 做 compression preflight;
  • 默认 threshold = model token limit 的 50%;
  • local config / remote experiment 可覆盖;
  • forced compression 绕过 threshold;
  • 以 estimated JSON character size 找 split,约 summary 前 70%、保留后 30%;
  • cut 只选没有 functionResponse 的 user boundary,并避免最后留下 dangling functionCall。

10.2 Tool result budget

对 function responses 从后向前预算约 50k estimated tokens。超预算的大结果:

  • 保存到 temporary file;
  • context 中替换为 truncation placeholder/最后若干行;
  • 若 summary 不可用但 truncation 确实缩小了 context,可返回 CONTENT_TRUNCATED。

这是 artifact projection 的雏形,但临时文件生命周期、权限和 resume 后可恢复性应单独审计。

10.3 Summary + verifier

Gemini 先要求模型输出 <state_snapshot>,再进行第二次 verification:检查是否遗漏 technical details、paths、tool results、user constraints;必要时输出改进后的 final snapshot。

这比单次 summary 更重,但把“压缩质量验证”显式化。summary 为空或比原 context 还大时判失败;非 forced 路径可只接受 deterministic truncation。

10.4 优缺点

优势:算法易理解;cut 避免 function pair 断裂;tool outputs 有外置路径;verification pass 提升 recall;status enum 便于观察。

缺点:70/30 基于字符估算,不够 token-precise;第二次调用增加 latency/cost;LLM exception 缺少 compaction-local retry;temp artifact 的 durable/recovery/security 合同不清楚。


十一、OpenCode:prune 与 durable summary marker

固定源码:8615731。

关键文件:

11.1 Trigger

  • 每个 provider step 后检查 token usage;
  • provider structured overflow 也触发 compaction;
  • compaction.auto=false 可禁用;
  • usable capacity 来自 model input limit,或 context limit 减 output reserve。

usable() 在 model 有独立 input limit 时仍会扣除 reserved output headroom;固定 revision 的断言覆盖了这条路径。测试中的旧 BUG 注释已经与实现和断言漂移,不应作为现存缺陷证据。

11.2 Async pruning

若 compaction.prune 开启:

  • 跳过最近两个 user turns;
  • 保护 skills;
  • 保护最新约 40k tool-output tokens;
  • 只有预计至少回收 20k 才持久化 compacted marker;
  • prune failure 当前可被 ignore,诊断较弱。

11.3 Summary compaction

  • compaction agent 默认 tool-denied;
  • 可由 plugin 注入 context 或替换 prompt,plugin trust 成为边界;
  • recent tail 默认使用 usable capacity 的 25%,clamp 在约 2k–15k,并可受 turn limit 控制;
  • durable compaction marker 记录 tail_start_id;
  • summary assistant message 与 retained tail 在 resume 时重建;
  • overflow replay 保留最近 user request,并把被剥离 media 变成明确文本提示。

11.4 优缺点

优势:prune/summary 分工清楚;tool-denied;durable tail boundary;fork 时 remap tail_start_id;overflow media degradation 对用户透明。

缺点:prune failure 静默;plugin 可改变 compaction prompt/context;summary 仍是 plain text,没有结构化验证;provider/model cache 关系文档不足。


十二、跨实现对比

12.1 Trigger 策略

  • Pi:window - reserve,简单并保障 output room。
  • Hermes:模型/route-specific ratio + 双安全网 + cooldown。
  • Codex:token window + mode/hash/model transition。
  • Grok:85% + prefire lead + overflow/preflight。
  • Gemini:默认 50%。
  • OpenCode:usable capacity + provider overflow。
  • OpenAI/xAI API:客户端指定 threshold 或显式 compact。
  • Anthropic API:compaction 默认 150k;tool editing 默认 100k。

结论:固定百分比不是最佳抽象。 正确 threshold 至少要考虑 output reserve、summarization 自身必须 fit、provider reasoning tokens、当前模型变化和是否有 deterministic pruning 可先执行。

12.2 Summary 表达

  • 可读 summary:Pi、Hermes、Gemini、OpenCode、Claude/Anthropic;
  • richer structured replacement:Codex;
  • opaque encrypted item:OpenAI/xAI API;
  • deterministic placeholders:Anthropic context editing、OpenCode prune、Gemini tool truncation。

结论:OpenPI 应保持可读、可审计 summary;如 provider 返回 opaque item,应由 Pi provider/runtime seam 明确拥有,不能让 OpenPI extension 私自混入 portable session format。

12.3 Preserved tail

  • Pi:token-aware backward cut + split turn;
  • Hermes:head anchors + tool-group alignment + legacy/lean tail;
  • Codex:local 20k user memory,remote v2 更大 retained budget;
  • Grok:single-pass replacement + optional 95% prefix two-pass;
  • Gemini:70/30;
  • OpenCode:25% usable capacity,2k–15k + turn limit;
  • Anthropic API:pause_after_compaction 后由客户端重新追加 recent messages。

结论:Pi 的 cut correctness 最值得保留;Hermes 的 exact anchors/recovery pointer 值得以 artifact projection 方式引入,而不是扩大 tail。

12.4 Tool / reasoning / image

  • Tool pair 不应被 cut 拆开;Pi、Hermes、Gemini 都明确处理。
  • 旧 tool result 通常是最大可回收项;Hermes、Anthropic、OpenCode、Gemini 都先 prune/truncate。
  • reasoning 在 provider 之间语义不同:明文、signed、encrypted、不可 replay。不能用通用 JSON summary 假设完整保留。
  • image 通常不适合进入 textual summary:Codex local/Hermes 会去掉,Gemini/OpenCode 改为 attachment notice/artifact。

结论:OpenPI 不应自行解释 provider-specific reasoning item;这是 Pi/provider adapter 的职责。

12.5 Persistence / recovery

  • Pi:append-only tree,历史完整;
  • Hermes:同 session soft archive + search;
  • Codex:atomic replacement item + world state;
  • Grok:checkpoint + rewind;
  • Gemini:recording file 保留,但 crash atomicity 未证实;
  • OpenCode:durable marker + tail id;
  • OpenAI/xAI:opaque item 必须作为 canonical state 持久化;
  • Anthropic:客户端可保留 full history,服务端忽略 compaction block 之前内容。

结论:Pi 已经有最适合 OpenPI 的 source of truth。需要补的是 first-class cut/provenance,而不是另建存储。

12.6 Prompt cache

  • compaction 几乎总会打断 conversation prefix cache;
  • stable system/tool prefix 应单独 cache;
  • warm summary request 可复用旧 prefix;
  • pruning 只有回收足够多 token 才值得 cache miss;
  • provider-native opaque item 建立新的短 prefix;
  • child/fork 是否共享父 cache 取决于 system/tool prefix 是否完全相同。

结论:优化目标应是“压缩后快速形成稳定新 prefix”,不是维持已经过大的旧 prefix。

12.7 Failure / anti-thrashing

  • Pi:bounded one-shot retry,最简单;
  • Hermes:provider fallback + durable cooldown;
  • Grok:错误分类 + sticky suppression;
  • Gemini:验证失败可只接受 truncation,但异常缺少 local retry;
  • OpenCode:overflow terminal,普通错误 retry;
  • Claude Code:多次立即重压后 thrashing error;
  • Anthropic API:tool-aware summary 可能返回 null block。

结论:OpenPI/Pi 最需要的不是更多 retry,而是:

  • 记录每次压缩前后 estimated tokens;
  • 若回收不足,禁止立即重复;
  • 区分 auth/quota/transient/size/invalid-summary;
  • summary 生成成功但 persistence 失败时绝不能继续;
  • cancellation 不自动 retry。

12.8 Security / trust

  • summary prompt 接收整段历史,其中可能含 prompt injection、secret 和 terminal/tool output;
  • summary 本身随后成为高权重 continuation context;
  • provider-native opaque item 不可审计,但仍是敏感 durable state;
  • plugin/hook/custom instructions 可以改变 summary,必须记录 provenance;
  • tool-capable summarizer 可能在压缩时意外执行工具。

结论:正确边界是 tool-denied summarization、terminal/control sanitization、明确 provenance、原子 persistence、可追踪 source span,以及对 secret-bearing artifact 的权限保护。


十三、对 OpenPI 的建议

建议 A:维持当前 ownership(推荐)

  • Pi 继续拥有自动 /compact、overflow、session format、cut point、retry 和 hooks;
  • OpenPI 只保留显式 context_pivot;
  • 不增加 OpenPI token estimator、compaction store、provider stack 或 fallback state machine。

建议 B:向 Pi upstream first-class full pivot

把当前 nonexistent retained-entry id 技巧替换为正式 primitive,例如:

{
  compaction: {
    summary,
    retain: "none"
  }
}

runtime 必须验证:

  • summary 非空且 byte-bounded;
  • 只有 parent/current Session 能发起;
  • compaction entry 原子落盘;
  • 成功、失败、取消、uncertain 有独立终态;
  • branch/fork/reload 后重建一致。

建议 C:增加 anti-thrash evidence,而不是复杂策略

Pi 可以记录:

  • trigger reason;
  • tokens before;
  • estimated tokens after;
  • retained-tail tokens;
  • summary input/output usage;
  • immediate next request 是否再次超阈值;
  • failure class。

如果连续压缩回收率过低,明确停止并报告具体大对象,而不是无限重试。

建议 D:将 exact artifact + bounded projection 限定在 OpenPI 自己拥有的结果通道

对 OpenPI-owned child outputs 与 Workflow evidence:

  1. exact 内容写入安全 artifact;
  2. 父 context 只保留有界 head/tail、identity、hash 和恢复路径;
  3. 模型按需 read;
  4. artifact retention/authority 独立管理。

这复用 OpenPI 已有 result-projection 思路,不改写 Pi conversational history。普通 Pi tool result 的 pruning/projection 属于 Pi 或具体 tool/provider owner,不应由 OpenPI 增加横跨所有工具的 context layer。

建议 E:summary quality eval

建立可复现 compaction benchmark,不以 token reduction 单独判成功。每个 fixture 检查:

  • 用户目标/约束 recall;
  • 文件路径、symbol、SHA、issue/PR id、错误字符串 exact recall;
  • 已完成/未完成区分;
  • failed approach 是否保留;
  • tool call/result pairing;
  • current working tree 与 summary 是否冲突;
  • repeated compaction 后信息衰减;
  • cache read/write、latency、cost;
  • adversarial tool output 是否能劫持 summary;
  • resume/fork/branch correctness。

建议至少包含:单大 turn、100+ tool calls、多次 compaction、provider switch、compaction during pending tool、并发 follow-up、图片/二进制、超大日志和 summary model failure。

建议 F:不要直接复制的机制

  • 不复制 Hermes 的完整 compression policy plane;
  • 不在 OpenPI extension 中接 OpenAI/xAI private compaction protocol;
  • 不按固定关键词自动 pivot;
  • 不把 durable memory、tool pruning、child result projection 和 session compaction 合成一个工具;
  • 不让 summary model 获得普通执行工具;
  • 不以“context 更短”推断“任务状态完整”。

十四、建议的决策顺序

  1. 文档先行: 在 README/architecture docs 明确 OpenPI 不拥有普通 auto-compaction,context_pivot 与 Pi /compact 的差异。
  2. 上游 API: 向 Pi 提议 first-class full-pivot cut,移除 invalid-id 技巧。
  3. 可观测性: 记录压缩回收率、失败分类和 immediate re-overflow。
  4. 安全: 固化 tool-denied summary、provenance 和 adversarial-summary fixtures。
  5. 质量基准: 先测 Pi 当前机制,再决定是否需要 anchor/recovery pointer。
  6. 仅在 benchmark 证明必要时,强化 OpenPI-owned child/Workflow result 的可恢复 artifact projection;不要预先引入第二 compressor,也不要接管普通 Pi tool result。

十五、仍未公开确认的边界

  • Claude Code 的完整 cut-point、atomic persistence 与 summary retry 实现未开源;本文只引用官方行为文档。
  • OpenAI/xAI opaque compaction item 的内部编码、retention、跨模型兼容性不可审计。
  • Codex legacy remote 与 remote v2 的服务端 summary prompt/内部 state 不是完全公开合同。
  • Gemini tool-output 临时文件的 retention、权限、crash cleanup 和跨 resume 恢复需要单独审计。
  • Grok Build 普通 single-pass 是否保留一段 verbatim recent conversational tail,当前源码审计未建立足够明确结论。
  • Pi 0.84.3 的总结模型选择 fallback 需要在 provider/model compatibility 专项中固定更多 runtime receipt。
  • 不同供应商 token usage 对 cached/reasoning/server-tool iteration 的口径不同,不能直接拿百分比横向排名。

十六、文档验收标准

  • README 或独立架构文档明确:Pi 是普通 Session compaction 的 owner;OpenPI 不建立第二控制面。
  • 解释 /compact、auto-compaction、overflow recovery、context_pivot、branch summary、result projection 的区别。
  • 记录 Pi 默认 trigger、reserve、recent-tail、split-turn、持久化和 hook 行为。
  • 对 Hermes、Codex、Grok、Claude、Gemini、OpenCode 的比较均固定源码 commit 或官方文档日期。
  • 明确区分 confirmed source behavior、official documented behavior、inference 和 unknown。
  • 包含 prompt caching、tool/reasoning/image、persistence/replay、failure、security 和 cost 的横向分析。
  • 不把 server-side opaque item 描述为普通文本 summary。
  • 不把 deterministic pruning 描述为 semantic compaction。
  • 给出 OpenPI 的最小推荐方向和明确非目标。
  • 后续任何实现提案必须先提供 compaction quality benchmark,而不是只报告 token reduction。

主要来源

OpenPI / Pi

OpenAI / Codex

Hermes

xAI / Grok

Anthropic / Claude Code

Gemini CLI

OpenCode

Activity

  1. added
    documentation
    on Aug 25, 2026
  2. 627150795 commented on Aug 28, 2026

    @627150795
    Contributor

    Hi! I would like to work on this documentation issue.

    I will publish a focused cross-implementation compaction comparison, keeping the existing OpenPI/Pi ownership boundary explicit and linking to the separate cache and checkpoint contracts rather than duplicating them. The document will distinguish source facts, documented behavior, inference, and unknowns, and will remain documentation-only with no second compressor or runtime changes.

  3. 627150795 commented on Aug 28, 2026

    @627150795
    Contributor

    Update: the fixed-version context-compaction comparison is implemented in PR #253: #253

    Validation completed: git diff --cached --check, bun run lint, and bun run typecheck passed. This is documentation-only; it keeps Pi as the Session compaction owner and does not add a second compressor or provider-private protocol. The PR uses the repository template and will close this issue when merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions