前言¶
智能體開發中,上下文窗口填滿後的處理是一個常見痛點。傳統的摘要壓縮往往是有損的,會導致模型遺忘細節,且質量會隨壓縮次數衰減。Codex 在 0.153.0 版本後引入了新的上下文窗口管理模型:不再頻繁壓縮,而是在接近閾值時,通過“換窗”丟棄整個舊窗口,只裝回一份全新的初始上下文,依靠 notes 和 searchable history 保留細節。
dsh-context-window 是一個 DSH 插件,由 CooperZhuang 維護,旨在復刻這套機制。它包含三個核心組件:token 預算提示、模型可調用的 new_context 工具,以及預算記賬與閾值節流。
核心功能¶
該插件提供兩種換窗模式(resetMode):
resetMode: handoff(推薦):無摘要換窗。換窗時直接寫入交接檢查點(包含目標、待辦、筆記、最後請求),不產生 compaction 事件,模型知道舊內容在哪。resetMode: seam-region:委託ctx.compaction.compactRegion執行整面替換。這會走傳統的摘要壓縮路徑,需要將行掛進 agent preset 的compactionrealm。
安裝與啓用¶
安裝時使用官方命令,插件默認 enabled: false,裝上不會改變當前行爲。
dsh plugin --profile web add dsh-context-window
配置時在 profile 的 cordis.patch.yml 或掛載行寫入以下內容:
- id: context-window
name: 'dsh-context-window'
config:
enabled: true
resetMode: handoff
noticeThresholds: [25, 50, 75]
effectiveContextWindowPercent: 95
autoCompactTokenLimitRatio: 0.9
fallbackBufferTokens: 8000
reminderThresholdTokens: 16000
bodyAfterPrefix: true
toolEnabled: true
toolName: new_context
notesToolEnabled: true
notesToolName: notes
模型交互¶
模型會接收到窗口提示和換窗工具。
1. 窗口提示
開窗時注入提示,包含當前窗口 ID 和剩餘 token 數。
2. 換窗工具
模型調用 new_context 工具時,返回如下文本:
A new context window will start without summarizing conversation history.
3. 筆記工具
模型調用 notes 工具時,返回如下文本:
Noted (1/8 notes retained for the next window).
4. 交接檢查點
在 resetMode: handoff 模式下,換窗後新窗口的第一條消息是 context_handoff:
<context_handoff>
Context window 1 (id 0199…) ended; this is context window 2 (id 0199…).
The messages of the previous window are gone. The state below was carried over verbatim.
<objective phase="active">
修復換窗後沒有任務狀態的問題
</objective>
<remaining_work>
- [~] 補 history 工具
- [ ] 真機掛載冒煙
</remaining_work>
<notes>
- seam 禁止不平衡切點,換窗只能落在 step 邊界
</notes>
<last_human_request>
繼續之前的工作
</last_human_request>
</context_handoff>
已知限制¶
使用時需注意以下幾點:
- 掛載約束:
ctx.compaction是按 realm 隔離的。seam-region模式需要將行掛進 agent preset 的compactionrealm;handoff模式不需要後端,在 host 平面即可工作。 - 邊界限制:換窗只能落在 step 邊界。DSH 的壓縮 seam 強制 tool-pairing 平衡,不允許切穿還在飛的工具調用。
- 計量啓發式:
token meter是啓發式的(4 字符/token),CJK 與 JSON schema 會被低估,閾值會偏晚觸發。 - UI 不可見:
handoff模式不產生compaction/*事件,在 UI 的壓縮統計中不可見,只在日誌中記錄。 - 基線不持久:
baselinePrefillTokens只在內存中,進程重啓後body_after_prefix會退化爲total。
總結¶
dsh-context-window 提供了一種顯式重啓的上下文管理方式,通過 handoff 模式將交接內容顯式寫入新窗口,避免了隱式摘要壓縮的信息丟失。這是一個 MIT 許可證的開源項目,適合需要在複雜長對話場景中保持上下文連續性的開發者。