ContextManager 对 History 只有少数受控变换:record_items 追加 API 可用项,remove_first_item 从最旧端删除并同步配对项,replace 整体重写并提升版本,rollback 按用户 Turn 边界裁剪。不同操作对 baseline 的影响不相同。
追加先过滤,再截断大型输出
record_items 忽略不应进入模型 API 的内部项目。Function/Custom Tool output 根据 TruncationPolicy 处理,并预留约 20% 序列化开销;普通消息、调用和 reasoning 保持类型结构。
def record_items(history, incoming, policy):
for item in incoming:
if not is_api_message(item):
continue
history.items.append(process_large_output(item, policy * 1.2))
删除必须保住调用对
remove_first_item 删除 index 0 后,如果该项是 call 或 output,会调用 remove_corresponding_for 再删另一端。否则紧接着的 Prompt 规范化虽能修复结构,却会把已经无意义的半对继续占在原始历史里。
replace(items) 用新 Arc 替换向量,history_version 饱和加一并清空 World State baseline。压缩、回滚和新窗口安装都使用这一语义。
def replace(history, new_items):
history.items = tuple(new_items)
history.history_version = min(MAX_U64, history.history_version + 1)
history.world_state_baseline = None
Rollback 按“指令 Turn”裁剪
回滚边界包括普通 user message 和结构化的 inter-agent instruction。超过已有 Turn 数时,保留首个用户输入前的前缀;裁剪若切到混合 Developer bundle,还会清空 reference context item,因为幸存文本不足以证明旧基线完整。
错误实现是按固定 item 数裁剪:一个 Turn 可能含多个 calls/outputs,会轻易切断配对和上下文边界。
源码与测试锚点
codex-rs/core/src/context_manager/history.rs:四类变换。codex-rs/core/src/context_manager/normalize.rs::remove_corresponding_for。codex-rs/core/src/context_manager/history_tests.rs:rollback 与 pair 保持。
评论
登录后即可评论