JINLOOPEST. 2026
浏览文档
PI DOCUMENTATION更新于

压缩与分支摘要

LLM 的上下文窗口有限。当对话过长时,Pi 使用压缩来总结较早的内容,同时保留近期工作。本页涵盖自动压缩和分支摘要。

源文件 (π-单):

有关项目中的 TypeScript 定义,请检查 node_modules/@earendil-works/pi-coding-agent/dist/.

概述

Pi 有两种摘要机制:

机制触发条件目的
压缩上下文超过阈值,或 /compact总结旧消息以释放上下文
分支摘要/tree 导航切换分支时保留上下文

两者使用相同的结构化摘要格式,并累积跟踪文件操作。压缩和分支摘要请求使用新的路由会话 ID,并且在提供商支持的情况下,禁用提示缓存写入,因为这些一次性提示不太可能被重用。

压缩

触发时机

自动压缩在以下情况触发:

contextTokens > contextWindow - reserveTokens

默认情况下, reserveTokens 为 16384 个令牌(可在 ~/.pi/agent/settings.json<project-dir>/.pi/settings.json中配置)。这为 LLM 的响应留出了空间。

你也可以通过 /compact [instructions]手动触发,其中可选指令用于聚焦摘要。

工作原理

  1. 找到切割点: 从最新消息向后遍历,累积令牌估计值,直到达到 keepRecentTokens (默认 20k,可在 ~/.pi/agent/settings.json<project-dir>/.pi/settings.json中配置)
  2. 提取消息: 收集从上一个保留边界(或会话开始)到切割点的消息
  3. 生成摘要: 调用 LLM 以结构化格式进行摘要,如果存在上一个摘要,则将其作为迭代上下文传递
  4. 追加条目: 保存带有摘要和 CompactionEntryfirstKeptEntryId
  5. 重建上下文: 会话为下一个请求重建上下文,使用摘要和从 firstKeptEntryId 开始的消息
Before compaction:

  entry:  0     1     2     3      4     5     6      7      8     9
        ┌─────┬─────┬─────┬─────┬──────┬─────┬──── ─┬──────┬─────┬─────┐
        │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│
        └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┘
                └────────┬───────┘ └──────────────┬──────────────┘
               messagesToSummarize            kept messages
                                   ↑
                          firstKeptEntryId (entry 4)

After compaction (new entry appended):

  entry:  0     1     2     3      4     5     6      7      8     9     10
        ┌─────┬─────┬─────┬─────┬──────┬─────┬──── ─┬──────┬─────┬─────┬─────┐
        │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│ cmp │
        └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┴─────┘
               └──────────┬──────┘ └──────────────────────┬───────────────────┘
                 not sent to LLM                    sent to LLM
                                                         ↑
                                              starts from firstKeptEntryId

What the LLM sees:

  ┌────────┬─────────┬─────┬─────┬──────┬──────┬─────┬──────┐
  │ system │ summary │ usr │ ass │ tool │ tool │ ass │ tool │
  └────────┴─────────┴─────┴─────┴──────┴──────┴─────┴──────┘
       ↑         ↑      └─────────────────┬────────────────┘
    prompt   from cmp          messages from firstKeptEntryId

在重复压缩时,摘要范围从上一次压缩的保留边界(firstKeptEntryId)开始,而不是从压缩条目本身开始,如果在路径中找不到该保留条目,则回退到上一次压缩后的条目。这通过将那些在早期压缩中幸存的消息也包含在下一次摘要过程中来保留它们。Pi 还会在写入新的 tokensBefore 之前,从重建的会话上下文中重新计算 CompactionEntry,因此令牌计数反映了被替换的实际预压缩上下文。

分割轮次

一个“轮次”以用户消息开始,包含所有助手响应和工具调用,直到下一条用户消息。通常,压缩会在轮次边界处进行切割。

当单个轮次超过 keepRecentTokens时,切割点会落在轮次中间的某条助手消息上。这称为“分割轮次”:

Split turn (one huge turn exceeds budget):

  entry:  0     1     2      3     4      5      6     7      8
        ┌─────┬─────┬─────┬──────┬─────┬──────┬──────┬─────┬──────┐
        │ hdr │ usr │ ass │ tool │ ass │ tool │ tool │ ass │ tool │
        └─────┴─────┴─────┴──────┴─────┴──────┴──────┴─────┴──────┘
                ↑                                     ↑
         turnStartIndex = 1                  firstKeptEntryId = 7
                │                                     │
                └──── turnPrefixMessages (1-6) ───────┘
                                                      └── kept (7-8)

  isSplitTurn = true
  messagesToSummarize = []  (no complete turns before)
  turnPrefixMessages = [usr, ass, tool, ass, tool, tool]

对于分割轮次,Pi 会生成两个摘要并合并它们:

  1. 历史摘要:之前的上下文(如果有)
  2. 轮次前缀摘要:分割轮次的前半部分

切割点规则

有效的切割点包括:

  • 用户消息
  • 助手消息
  • BashExecution 消息
  • 自定义消息(custom_message、branch_summary)

绝不在工具结果处切割(它们必须与其工具调用保持在一起)。

CompactionEntry 结构

定义在 session-manager.ts:

interface CompactionEntry<T = unknown> {
  type: "compaction";
  id: string;
  parentId: string;
  timestamp: number;
  summary: string;
  firstKeptEntryId: string;
  tokensBefore: number;
  usage?: Usage;       // LLM usage that generated the summary
  fromHook?: boolean;  // true if provided by extension (legacy field name)
  details?: T;         // implementation-specific data
}
 
// Default compaction uses this for details (from compaction.ts):
interface CompactionDetails {
  readFiles: string[];
  modifiedFiles: string[];
}

扩展可以在 details中存储任何 JSON 可序列化的数据。默认压缩会跟踪文件操作,但自定义扩展实现可以使用自己的结构。生成的摘要和扩展提供的摘要会在可用时存储其 LLM usage ,以便会话总数包含摘要工作。

参见 prepareCompaction()compact() 了解实现。对于直接编程式摘要, generateSummary() 返回摘要文本,而 generateSummaryWithUsage() 返回 { text, usage }.

分支摘要

触发时机

当你使用 /tree 导航到不同分支时,Pi 会提示你总结即将离开的工作。这会将左侧分支的上下文注入到新分支中。

工作原理

  1. 查找共同祖先:新旧位置共享的最深节点
  2. 收集条目:从旧叶子节点回溯到共同祖先
  3. 预算准备:包含消息直到达到令牌预算(最新的优先)
  4. 生成摘要:使用结构化格式调用 LLM
  5. 追加条目:在导航点保存 BranchSummaryEntry 累积文件跟踪
Tree before navigation:

         ┌─ B ─ C ─ D (old leaf, being abandoned)
    A ───┤
         └─ E ─ F (target)

Common ancestor: A
Entries to summarize: B, C, D

After navigation with summary:

         ┌─ B ─ C ─ D
    A ───┤
         └─ E ─ F ─ [summary of B,C,D] (new leaf)

压缩和分支摘要都会累积跟踪文件。生成摘要时,pi 从以下来源提取文件操作:

正在摘要的消息中的工具调用

  • 之前的压缩或分支摘要
  • (如果有) details 这意味着文件跟踪会跨多次压缩或嵌套分支摘要累积,保留读取和修改文件的完整历史。

BranchSummaryEntry 结构

定义在

与压缩相同,扩展可以在 session-manager.ts:

interface BranchSummaryEntry<T = unknown> {
  type: "branch_summary";
  id: string;
  parentId: string;
  timestamp: number;
  summary: string;
  fromId: string;      // Entry we navigated from
  usage?: Usage;       // LLM usage that generated the summary
  fromHook?: boolean;  // true if provided by extension (legacy field name)
  details?: T;         // implementation-specific data
}
 
// Default branch summarization uses this for details (from branch-summarization.ts):
interface BranchSummaryDetails {
  readFiles: string[];
  modifiedFiles: string[];
}

中存储自定义数据 details.

参见 collectEntriesForBranchSummary(), prepareBranchEntries()generateBranchSummary() 了解实现。

摘要格式

压缩和分支摘要都使用相同的结构化格式:

## Goal
[What the user is trying to accomplish]
 
## Constraints & Preferences
- [Requirements mentioned by user]
 
## Progress
### Done
- [x] [Completed tasks]
 
### In Progress
- [ ] [Current work]
 
### Blocked
- [Issues, if any]
 
## Key Decisions
- **[Decision]**: [Rationale]
 
## Next Steps
1. [What should happen next]
 
## Critical Context
- [Data needed to continue]
 
<read-files>
path/to/file1.ts
path/to/file2.ts
</read-files>
 
<modified-files>
path/to/changed.ts
</modified-files>

消息序列化

在摘要生成之前,消息会通过序列化为文本 serializeConversation():

[User]: What they said
[Assistant thinking]: Internal reasoning
[Assistant]: Response text
[Assistant tool calls]: read(path="foo.ts"); edit(path="bar.ts", ...)
[Tool result]: Output from tool

这可以防止模型将其视为要继续的对话。

在序列化过程中,工具结果会被截断为 2000 个字符。超出该限制的内容会被替换为一个标记,指示被截断的字符数。这使摘要请求保持在合理的 token 预算内,因为工具结果(尤其是来自 readbash)通常是上下文大小的最大贡献者。

通过扩展进行自定义摘要

扩展可以拦截并自定义压缩和分支摘要。有关事件类型定义,请参阅 extensions/types.ts 用于事件类型定义。

压缩前的会话

在自动压缩或 /compact之前触发。可以取消或提供自定义摘要。请参阅类型文件中的 SessionBeforeCompactEventCompactionPreparation 在类型文件中。

pi.on("session_before_compact", async (event, ctx) => {
  const { preparation, branchEntries, customInstructions, reason, willRetry, signal } = event;
 
  // preparation.messagesToSummarize - messages to summarize
  // preparation.turnPrefixMessages - split turn prefix (if isSplitTurn)
  // preparation.previousSummary - previous compaction summary
  // preparation.fileOps - extracted file operations
  // preparation.tokensBefore - context tokens before compaction
  // preparation.firstKeptEntryId - where kept messages start
  // preparation.settings - compaction settings
 
  // branchEntries - all entries on current branch (for custom state)
  // reason - "manual" (/compact), "threshold", or "overflow"
  // willRetry - whether the aborted turn is retried after compaction (overflow recovery)
  // signal - AbortSignal (pass to LLM calls)
 
  // Cancel:
  return { cancel: true };
 
  // Custom summary:
  return {
    compaction: {
      summary: "Your summary...",
      firstKeptEntryId: preparation.firstKeptEntryId,
      tokensBefore: preparation.tokensBefore,
      // usage: summaryResponse.usage, // Optional; included in session totals
      details: { /* custom data */ },
    }
  };
});

将消息转换为文本

要使用自己的模型生成摘要,请使用以下方法将消息转换为文本: serializeConversation:

import { convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent";
 
pi.on("session_before_compact", async (event, ctx) => {
  const { preparation } = event;
  
  // Convert AgentMessage[] to Message[], then serialize to text
  const conversationText = serializeConversation(
    convertToLlm(preparation.messagesToSummarize)
  );
  // Returns:
  // [User]: message text
  // [Assistant thinking]: thinking content
  // [Assistant]: response text
  // [Assistant tool calls]: read(path="..."); bash(command="...")
  // [Tool result]: output text
 
  // Now send to your model for summarization
  const { summary, usage } = await myModel.summarize(conversationText);
  
  return {
    compaction: {
      summary,
      firstKeptEntryId: preparation.firstKeptEntryId,
      tokensBefore: preparation.tokensBefore,
      usage,
    }
  };
});

请参阅 custom-compaction.ts 以获取使用不同模型的完整示例。

会话前树

/tree 导航之前触发。无论用户是否选择摘要,始终触发。可以取消导航或提供自定义摘要。

pi.on("session_before_tree", async (event, ctx) => {
  const { preparation, signal } = event;
 
  // preparation.targetId - where we're navigating to
  // preparation.oldLeafId - current position (being abandoned)
  // preparation.commonAncestorId - shared ancestor
  // preparation.entriesToSummarize - entries that would be summarized
  // preparation.userWantsSummary - whether user chose to summarize
 
  // Cancel navigation entirely:
  return { cancel: true };
 
  // Provide custom summary (only used if userWantsSummary is true):
  if (preparation.userWantsSummary) {
    return {
      summary: {
        summary: "Your summary...",
        // usage: summaryResponse.usage, // Optional; included in session totals
        details: { /* custom data */ },
      }
    };
  }
});

请参阅类型文件中的 SessionBeforeTreeEventTreePreparation 在类型文件中。

设置

在以下位置配置压缩: ~/.pi/agent/settings.json<project-dir>/.pi/settings.json:

{
  "compaction": {
    "enabled": true,
    "reserveTokens": 16384,
    "keepRecentTokens": 20000
  }
}
设置默认值描述
enabledtrue启用自动压缩
reserveTokens16384为 LLM 响应保留的 token 数
keepRecentTokens20000保留的最近 token 数(不进行摘要)

使用以下命令禁用自动压缩: "enabled": false。您仍然可以使用以下命令手动压缩: /compact.

本文档内容同步自 PI 官方 GitHub 仓库。

查看源文件