文档导航

文档

本页目录

压缩(Compaction)参考手册

本参考文档介绍了自动压缩、分支总结、持久化条目以及扩展钩子(extension hooks)。关于用户操作流程,请参阅会话与上下文。

源码文件(pig):

概述

#

pig 拥有两种总结机制:

机制触发时机目的
压缩(Compaction)上下文超出阈值,或执行 /compact总结旧消息以释放上下文空间
分支总结(Branch summarization)/tree 导航切换分支时切换分支时保留上下文信息

两者都使用紧密相关的结构化格式,并以累加方式追踪文件操作。总结请求会禁用 prompt-cache 写入,因为这些一次性的 Prompt 极不可能被复用。

压缩

#

触发时机

#

自动压缩在满足以下条件时触发:

contextTokens > contextWindow - reserveTokens

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

在多轮 Agent 运行期间,pig 会在工具执行完毕且结果已追加之后、下一次 Assistant 响应开始之前,检查规范的预测上下文大小。如果超出阈值,pig 会在 prepareNextTurn 阶段执行压缩,然后在 turn_start 之前执行现有的追赶转向轮询(catch-up steering poll)。当已完成的工具批次终止了运行,且没有排队的消息需要进一步响应时,它会跳过此轮间检查。pig 还会在线的 User Prompt 之前进行检查,并在底层运行结束后执行最终尝试溢出恢复(final-attempt overflow recovery)。

模型提供商返回的上下文溢出错误或提前触发的最终 stopReason: "length" 状态,可以选择发起一次“压缩并重试”(compact-and-retry)的恢复尝试。包含工具调用的 length 响应会保留其合成的失败工具结果,并遵循常规的工具/队列调度程序处理,而不会强制结束运行。

你也可以使用 /compact [instructions] 手动触发,其中可选的 instructions 用于聚焦总结的重点。

工作原理

#
  1. 确定截断点(Cut point):反向遍历已确定的会话投影,累加预估 Token 数,直到达到 keepRecentTokens(默认为 20k,可在 ~/.pig/agent/settings.json 或 <project-dir>/.pig/settings.json 中配置)
  2. 提取消息:收集从上一个保留边界(或会话起始点)到截断点之间的预测消息
  3. 生成总结:调用 LLM 使用结构化格式进行总结;如果存在先前的总结,则将其作为迭代上下文传入
  4. 追加条目:保存包含总结内容和 firstKeptEntryId 的 CompactionEntry
  5. 重建上下文:会话为下一次请求重建上下文,使用总结 + 从 firstKeptEntryId 开始的消息
压缩前:

  条目:   0     1     2     3      4     5     6      7      8     9
        ┌─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬─────┐
        │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│
        └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┘
                └────────┬───────┘ └──────────────┬──────────────┘
               messagesToSummarize            保留的消息
                                   ↑
                          firstKeptEntryId (entry 4)

压缩后(追加新条目):

  条目:   0     1     2     3      4     5     6      7      8     9     10
        ┌─────┬─────┬─────┬──────┬─────┬─────┬──────┬──────┬─────┬─────┬─────┐
        │ hdr │ usr │ ass │ tool │ usr │ ass │ tool │ tool │ ass │ tool│ cmp │
        └─────┴─────┴─────┴──────┴─────┴─────┴──────┴──────┴─────┴─────┴─────┘
               └──────────┬──────┘ └──────────────────────┬───────────────────┘
                 不发送给 LLM                        发送给 LLM
                                                         ↑
                                              从 firstKeptEntryId 开始

LLM 看到的内容:

  ┌────────┬─────────┬─────┬─────┬──────┬──────┬─────┬──────┐
  │ system │ summary │ usr │ ass │ tool │ tool │ ass │ tool │
  └────────┴─────────┴─────┴─────┴──────┴──────┴─────┴──────┘
       ↑         ↑      └─────────────────┬────────────────┘
    prompt   来自 cmp          来自 firstKeptEntryId 的消息

在连续多次压缩时,总结的范围始于上一次压缩的保留边界(firstKeptEntryId),而不是压缩条目本身;如果在路径中找不到该保留条目,则回退到上一次压缩之后的条目。完全不保留(retain-none)的压缩会将其自身的 ID 记录为 firstKeptEntryId;后续压缩从该条目之后开始。这样可以通过将先前压缩中保留下来的消息再次包含在下一轮总结传递中,从而保留这些消息。pig 还会在写入新的 CompactionEntry 之前,从重建且经上下文编辑的会话投影中重新计算 tokensBefore,以使 Token 计数反映被替换的实际压缩前上下文。被忽略的原始条目仍会被存储,但不会影响截断点选择、总结、检查点或 Token 估算。

溢出与 Length 恢复顺序

#

恢复过程保留了现有的生命周期和队列顺序。已完成的尝试对 turn_end 和 agent_end 仍然可见;运行后的恢复流程会在全新重试前修复持久化的模型上下文:

持久化最终 assistant 响应
→ 扩展/公共 turn_end
→ 扩展/公共 agent_end
→ 为选定的尝试追加 context_edit 省略标记
→ 针对 overflow/length:运行 session_before_compact 并在成功时追加压缩条目
→ 作为全新的运行启动重试

如果恢复压缩失败或被取消,pig 会保留省略编辑,不追加任何压缩条目,也不安排内部重试。现有的排队任务仍受常规转向和跟进规则的管理。agent_before_settle 在恢复处理后看到的是修复后的投影。原始副本历史记录、导出、账单总计以及历史搜索扩展仍可检查被省略的尝试。

拆分 User 消息跨度(Split user-message spans)

#

一个 User 消息跨度以一条 User 消息开始,并包含直到下一条 User 消息之间的所有轮次。通常情况下,压缩会在 User 消息边界处进行截断。

当单个 User 消息跨度超过 keepRecentTokens 时,截断点会落入该跨度内的某条 Assistant 消息处。这就是拆分 User 消息跨度:

拆分 User 消息跨度(单个跨度超出预算):

  条目:   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) ───────┘
                                                      └── 保留 (7-8)

  isSplitTurn = true
  messagesToSummarize = []  (没有更早的 User 消息跨度)
  turnPrefixMessages = [usr, ass, tool, ass, tool, tool]

对于拆分 User 消息跨度,pig 会生成两份总结并将它们合并:

  1. 历史总结:先前的上下文(若有)
  2. User 消息跨度前缀总结:拆分 User 消息跨度的前半部分

截断点规则

#

有效的截断点包括:

  • User 消息
  • Assistant 消息
  • BashExecution 消息
  • 自定义消息(custom_message、branch_summary)

绝不能在工具结果(Tool result)处截断(它们必须与其工具调用保持在一起)。

仅当上下文不可见的后缀包含被省略的 Assistant 尝试且不包含未省略的产出上下文的条目时,准备阶段才会将保留边界推入该后缀。恢复时的 context_edit 省略标记满足此规则;本质上上下文不可见的元数据可以与它们共存。仅有元数据和新追加的自定义消息不会移动截断点。影响候选输入或被总结前缀的替换编辑也会阻止边界推进,因为被省略的 Assistant 响应的是编辑前的输入;对最终被省略的后缀条目的替换仍是安全的。这允许在保留使被放弃尝试保持省略状态的编辑的同时,总结超出预算的已恢复输入,而无需通过记账变更来决定新模型输入是否逐字保留。

CompactionEntry 结构

#

一次压缩是会话文件中的一行 compaction,读取后成为一个 CompactionEntry:

{
  "type": "compaction",
  "id": "…",
  "parentId": "…",
  "timestamp": "…",
  "summary": "## Goal\n…",
  "firstKeptEntryId": "…",
  "tokensBefore": 123456,
  "usage": { "…": "LLM usage that generated the summary" },
  "fromHook": false,
  "details": { "readFiles": ["src/A.php"], "modifiedFiles": ["src/B.php"] }
}

当总结由扩展提供时,fromHook 为 true(遗留字段名)。与上游 pi 不同,pig 只在 details 中保存文件列表,不把它们放进 summary;<read-files> 和 <modified-files> 标签会在向模型展示总结时添加(CompactionEntry::toText())。details 只保存 readFiles 和 modifiedFiles:扩展返回的其他键不会被存储。生成的总结和扩展提供的总结在可用时都会存储其 LLM usage,以便会话总计包含总结所消耗的用量。

实现详情请参阅 Compaction::prepareCompaction() 和 Compaction::compact()。如需以编程方式直接生成总结,Compaction::generateSummary() 返回总结文本,generateSummaryWithUsage() 返回文本及其用量。

分支总结

#

触发时机

#

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

工作原理

#
  1. 寻找共同祖先:旧位置和新位置所共享的最深节点
  2. 收集条目:从旧叶子节点回溯到共同祖先
  3. 按预算准备:在 Token 预算范围内纳入消息(最新的优先)
  4. 生成总结:使用结构化格式调用 LLM
  5. 追加条目:在导航点保存 BranchSummaryEntryEntry
导航前的树:

         ┌─ B ─ C ─ D (旧叶子节点,将被离开)
    A ───┤
         └─ E ─ F (目标)

共同祖先:A
待总结条目:B, C, D

带总结导航后:

         ┌─ B ─ C ─ D
    A ───┤
         └─ E ─ F ─ [B,C,D 的总结] (新叶子节点)

累加式文件追踪

#

默认压缩和分支总结均采用累加方式追踪文件。两者都会从被总结消息中的工具调用提取文件操作。压缩还会继承上一次由 pig 生成的压缩中的文件列表。分支总结则会从其总结条目中包含的由 pig 生成的分支总结中继承文件列表。

因此,文件追踪会在默认压缩和嵌套的默认分支总结之间累加。对于 fromHook 字段为 true 的扩展生成总结,pig 不会自动继承其文件列表;扩展需自行管理其 details 格式。

BranchSummaryEntryEntry 结构

#

一次分支总结是一行 branch_summary,读取后成为一个 BranchSummaryEntry:

{
  "type": "branch_summary",
  "id": "…",
  "parentId": "…",
  "timestamp": "…",
  "summary": "…",
  "fromId": "… (the entry navigated from)",
  "usage": { "…": "LLM usage that generated the summary" },
  "fromHook": false,
  "details": { "readFiles": [], "modifiedFiles": [] }
}

与压缩相同,details 只保存 readFiles 和 modifiedFiles。

实现详情请参阅 collectEntriesForBranchSummaryEntry()、prepareBranchEntries() 和 generateBranchSummaryEntry()。

总结格式

#

两种格式均包含目标(Goal)、约束与偏好(Constraints & Preferences)、进展(Progress)、关键决策(Key Decisions)以及后续步骤(Next Steps)。压缩总结还包含关键上下文(Critical Context)。分支总结在后续步骤之后结束。向模型展示总结时,pig 会以标签形式追加文件列表;存储的 summary 文本中不含这些标签。

模型看到的压缩总结采用以下格式:

## 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.php
path/to/file2.php
</read-files>

<modified-files>
path/to/changed.php
</modified-files>

消息序列化

#

在总结之前,消息会通过 CodingAgent::toLlm() 转换为 LLM 消息,再通过 Compaction::serializeConversation() 序列化为文本。Hook 消息、! 命令输出以及先前的总结会以 [User]: 行的形式交给总结模型:

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

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

在序列化期间,工具结果会被截断至 2000 个字符(Compaction::TOOL_RESULT_MAX_CHARS)。超出该限制的内容将被替换为一个标记,指示截断了多少个字符。这可以使总结请求保持在合理的 Token 预算之内,因为工具结果(尤其是来自 read 和 bash 的结果)通常是导致上下文体积增大的最大因素。

通过扩展自定义总结

#

扩展可以拦截并自定义压缩和分支总结。事件类位于 Extensions/Events/,结果类位于 Extensions/Results/。对于 session_before_* 事件,第一个取消操作的处理器生效;否则采用最后一个处理器的返回结果。

session_before_compact

#

在手动、阈值和溢出压缩执行前触发。可以取消操作或提供自定义总结。参见 SessionBeforeCompactEvent 和 CompactionPreparation。

use Pig\CodingAgent\Extensions\Events\SessionBeforeCompactEvent;
use Pig\CodingAgent\Extensions\ExtensionContext;
use Pig\CodingAgent\Extensions\Results\SessionBeforeCompactResult;
use Pig\CodingAgent\Session\CompactionResult;

$pig->on('session_before_compact', function (SessionBeforeCompactEvent $event, ExtensionContext $ctx) {
    $preparation = $event->preparation;

    // $preparation->messagesToSummarize - messages to summarize
    // $preparation->turnPrefixMessages  - user-message-span prefix (if $preparation->isSplitTurn)
    // $preparation->previousSummary     - previous compaction summary
    // $preparation->fileOps             - extracted file operations (FileOperations)
    // $preparation->tokensBefore        - context tokens before compaction
    // $preparation->firstKeptEntryId    - where kept messages start
    // $preparation->settings            - effective CompactionSettings after model overrides

    // $event->branchEntries      - all entries on the current branch (for custom state)
    // $event->customInstructions - the text after /compact, or null
    // $event->reason             - 'manual' (/compact), 'threshold', or 'overflow'
    // $event->willRetry          - whether the aborted turn is retried after compaction (overflow recovery)
    // $event->signal             - AbortSignal (pass to LLM calls)

    // Cancel (the compaction fails with "Compaction cancelled"):
    return new SessionBeforeCompactResult(cancel: true);

    // Custom summary:
    return new SessionBeforeCompactResult(compaction: new CompactionResult(
        summary: 'Your summary...',
        firstKeptEntryId: $preparation->firstKeptEntryId,
        tokensBefore: $preparation->tokensBefore,
        // usage: $usage, // optional; included in session totals
        details: ['readFiles' => [], 'modifiedFiles' => []],
    ));
});

pig 会按处理器返回的原样写入 firstKeptEntryId 和 tokensBefore。

将消息转换为文本

#

若要使用你自己的模型生成总结,可使用 Compaction::serializeConversation() 将消息转换为文本:

use Pig\CodingAgent\CodingAgent;
use Pig\CodingAgent\Session\Compaction;

$pig->on('session_before_compact', function (SessionBeforeCompactEvent $event, ExtensionContext $ctx) {
    $preparation = $event->preparation;

    // Convert session messages to LLM messages, then serialize to text
    $conversationText = Compaction::serializeConversation(
        CodingAgent::toLlm($preparation->messagesToSummarize),
    );
    // [User]: message text
    // [Assistant thinking]: thinking content
    // [Assistant]: response text
    // [Assistant tool calls]: read(path="..."); bash(command="...")
    // [Tool result]: output text

    // Ask the session's model (or pass another Model) for the summary
    $summary = $ctx->complete("Summarize this coding session:\n\n{$conversationText}", maxTokens: 4000);

    if ($summary === null) {
        return null; // fall back to pig's own summary
    }

    return new SessionBeforeCompactResult(compaction: new CompactionResult(
        summary: $summary,
        firstKeptEntryId: $preparation->firstKeptEntryId,
        tokensBefore: $preparation->tokensBefore,
    ));
});

若要保留 pig 的提示词但更换模型,请调用 Compaction::compact($preparation, $model, $apiKey, signal: $event->signal) 并返回其 CompactionResult。

session_compact

#

在写入压缩条目之后触发。SessionCompactEvent 携带 compactionEntry(即 CompactionEntry)、fromExtension、reason 和 willRetry。

session_compact_failed

#

在手动或自动压缩失败或中止时触发。对于需要将 session_before_compact 尝试与最终结果关联起来的遥测扩展非常有用。

use Pig\CodingAgent\Extensions\Events\SessionCompactFailedEvent;

$pig->on('session_compact_failed', function (SessionCompactFailedEvent $event, ExtensionContext $ctx): void {
    // $event->reason        - 'manual' (/compact), 'threshold', or 'overflow'
    // $event->errorMessage  - present for non-abort failures, prefixed "Compaction failed: ",
    //                         "Auto-compaction failed: ", or "Context overflow recovery failed: "
    // $event->aborted       - true for cancelled/aborted compactions
    // $event->willRetry     - always false: a turn whose recovery failed is not sent again
    // $event->fromExtension - whether extension-provided compaction content was being used
});

session_before_tree

#

在 /tree 导航前触发。无论用户是否选择总结,都会始终触发。可以取消导航或提供自定义总结。

use Pig\CodingAgent\Extensions\Events\SessionBeforeTreeEvent;
use Pig\CodingAgent\Extensions\Results\SessionBeforeTreeResult;

$pig->on('session_before_tree', function (SessionBeforeTreeEvent $event, ExtensionContext $ctx) {
    $preparation = $event->preparation;

    // $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
    // $preparation->customInstructions, ->replaceInstructions, ->label

    // Cancel navigation entirely:
    return new SessionBeforeTreeResult(cancel: true);

    // Provide a custom summary (only used if userWantsSummary is true):
    if ($preparation->userWantsSummary) {
        return new SessionBeforeTreeResult(summary: [
            'summary' => 'Your summary...',
            // 'usage' => $usage, // optional; included in session totals
            'details' => ['readFiles' => [], 'modifiedFiles' => []],
        ]);
    }

    return null;
});

返回结果还可以为 pig 自身的总结器覆盖 customInstructions、replaceInstructions 和 label。参见 SessionBeforeTreeEvent、TreePreparation 和 SessionBeforeTreeResult。导航完成后,session_tree(SessionTreeEvent)会携带 newLeafId、oldLeafId、summaryEntry 和 fromExtension。

设置

#

在 ~/.pig/agent/settings.json 或 <project-dir>/.pig/settings.json 中配置压缩:

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

通过 "enabled": false 禁用自动压缩。你仍然可以使用 /compact 进行手动压缩。

按模型覆盖(Per-model overrides)

#

使用 compaction.modelOverrides 为不同的模型微调 Token 预算:

{
  "compaction": {
    "reserveTokens": 16384,
    "keepRecentTokens": 20000,
    "modelOverrides": {
      "some-provider/big-model": {
        "reserveTokens": 400000
      }
    }
  }
}

对于具有 1M 上下文窗口的模型,此覆盖配置会在超过 600K Token 时触发压缩,并保留常规的 20000 个近期 Token。其他模型仍保留常规的 16384 Token 预留。reserveTokens 还会影响总结输出的上限(受模型最大输出 Token 限制);它不仅仅是一个触发阈值。

键名是精确且区分大小写的 provider/modelId 值,包含模型 ID 内的任何斜杠。每个 reserveTokens 和 keepRecentTokens 值都会独立回退:模型覆盖 -> 普通设置 -> 内置默认值。值必须为非负安全整数。在匹配的模型覆盖中若存在无效值,读取时将报错;只有省略的字段才会回退到普通设置。模型覆盖项必须是对象。普通 Token 设置若无效,读取时也会报错,即使当前活动模型具有有效的覆盖配置也是如此。只有省略的普通值才会使用内置默认值。enabled 始终是全局设置,不支持按模型配置。

这些解析后的值将用于手动压缩、所有自动阈值检查、溢出恢复以及扩展可见的 preparation.settings。切换模型会影响后续的检查和压缩,而不会更改普通设置。已经在进行中的压缩将使用为该操作捕获的模型和设置。分支总结设置不受影响。

覆盖配置在全局设置和项目设置中均有效。设置只合并一层:compaction 下的直接键会合并,但项目中的 compaction.modelOverrides 对象会整体替换全局对象,因此只要项目设置了任何模型覆盖,就必须重复写出它想保留的全局条目。详情请参阅设置。