Kimi CLI 上下文加载机制分析
Kimi CLI 上下文加载机制分析
1. 存储结构
会话存储在 ~/.kimi/sessions/
context.jsonl —— 实际加载到 LLM 的对话历史
wire.jsonl —— 完整 wire 协议记录(TurnBegin、StepBegin、think、ToolCall 等)
state.json —— 会话状态(approval、plan_mode、todos、archived 等)
元数据索引:~/.kimi/kimi.json 记录每个工作目录的 last_session_id
2. –continue 加载流程
CLI 检测到 –continue → Session.continue_(work_dir) → 读取 kimi.json 的 last_session_id → Session.find() 定位目录 → Context.restore() 加载 context.jsonl → KimiSoul(agent, context=context)
3. context.restore() 核心逻辑
逐行读取 context.jsonl,按 role 分类:
_system_prompt:提取系统提示,覆盖 agent 默认 prompt
_usage:更新 token 计数,清空 pending 队列
_checkpoint:记录检查点 ID,支持 revert
user / assistant / tool:解析为 Message 对象,追加到 _history
4. wire.jsonl 与 context.jsonl 的区别
context.jsonl 是精简版,只保留 LLM 需要看到的对话内容。
wire.jsonl 是完整版,记录 TurnBegin、StepBegin、think、工具调用、token 消耗等,用于标题生成、Web UI 回放、调试。
5. 当前会话实际情况
工作目录:/opt/vibecoding/coding_com/sandbox/kimi-chat
会话 ID:bff7d946-8903-4260-ab29-30fa141be85b
存储路径:~/.kimi/sessions/8f5110e2ed8d8aeaf51a86d9cc4509b7/bff7d946-8903-4260-ab29-30fa141be85b/
当前 context.jsonl 包含从”怎么说”开始的完整对话历史,实时追加写入。