06 — 上下文管理、Token 与 Compact
ContextManager:线程历史 transcript
codex-rs/core/src/context_manager/history.rs 中 ContextManager 持有:
- 按时间顺序的
ResponseItem向量; TokenUsageInfo;reference_context_item:用于 diff 设置 与 向模型注入上下文更新 的基线。
32:48:codex-rs/core/src/context_manager/history.rs
/// Transcript of thread history
#[derive(Debug, Clone, Default)]
pub(crate) struct ContextManager {
/// The oldest items are at the beginning of the vector.
items: Vec<ResponseItem>,
token_info: Option<TokenUsageInfo>,
/// Reference context snapshot used for diffing and producing model-visible
/// settings update items.
///
/// This is the baseline for the next regular model turn, and may already
/// match the current turn after context updates are persisted.
///
/// When this is `None`, settings diffing treats the next turn as having no
/// baseline and emits a full reinjection of context state. Rollback may
/// also clear this when it trims a mixed initial-context developer bundle
/// whose non-diff fragments no longer exist in the surviving history.
reference_context_item: Option<TurnContextItem>,
}设计原因:
- 全量重注 vs diff:若每轮都把 cwd、沙箱、模型配置全文塞进 developer message,会浪费 token。维护
reference_context_item可只发 增量。 - 回滚一致性:注释说明 rollback 可能清空 baseline,避免 历史与注入片段不对齐 导致模型看到自相矛盾的系统状态。
截断与估算
同模块使用 codex_utils_output_truncation:对函数输出等做 可配置截断,并用近似 token/字节估算辅助 Compaction 决策。这与前端「列表虚拟化 + 可见区域估算」类似,但目标是 API 成本与上下文窗口。
Compact:本地与远程
codex.rs 引入 compact、compact_remote 等模块;should_use_remote_compact_task 等分支体现 压缩/摘要可在本机或上游服务完成。可简述为:
- 动机:对话过长时必须在 不丢失任务关键信息 的前提下缩短。
- 权衡:远程 compact 可能更准但更依赖网络与隐私策略;本地 compact 更可控但算法要维护。
(具体触发条件与策略以源码 compact*.rs 为准,阅读时注意 feature flag 与 model 能力。)
Session 与 State DB
docs/config.md 说明 SQLite state DB 位置(sqlite_home / CODEX_SQLITE_HOME)。持久化与 ContextManager 内存态配合,支撑 resume thread、崩溃恢复与 rollout 文件。
延伸阅读
- 07 ModelClient(token 与 turn 元数据上报)
- 03 Op