-
Notifications
You must be signed in to change notification settings - Fork 5
ZH Course 04 Session Store
lloydzhou edited this page Jun 1, 2026
·
2 revisions
Store 层为每个 session 创建一个持久目录:
CONV_FILE="${session_dir}/conversation.jsonl"
SESSION_EVENT_FILE="${session_dir}/events.jsonl"
CONTEXT_SUMMARY_FILE="${session_dir}/summary.txt"
PLAN_FILE="${session_dir}/plan.md"
PLAN_DRAFT_FILE="${session_dir}/plan.draft"
STATS_FILE="${session_dir}/stats.json"这些文件职责不同:
| 文件 | 作用 |
|---|---|
conversation.jsonl |
面向模型的 message history |
events.jsonl |
replay 和 stream-json 的事件日志 |
summary.txt |
长会话压缩后的摘要 |
plan.md |
已确认并进入 prompt 的 plan |
plan.draft |
不触发 prompt cache 失效的草稿 plan |
stats.json |
turn、token、cache token、标题数据 |
conversation.jsonl 面向模型。它保存 user、assistant、tool-result messages,用来构造下一次请求。
events.jsonl 面向运行时观察。它记录 text、thinking、tool call、tool result、usage、error、sub-agent event 和 context update。
这两个文件分开后,runtime 可以直接 replay session,而不需要从模型消息反推出 display 输出。
Replay 读取最近事件,不加载完整 conversation:
store_event_recent_turn_lines() {
local turns="${1:-10}" _match _from_line
[[ -s "${SESSION_EVENT_FILE:-}" ]] || return 0
_match=$(grep -n '"type":"user_input"' "$SESSION_EVENT_FILE" | tail -n "$turns" | head -n 1) || true
_from_line="${_match%%:*}"
[[ -n "$_from_line" && "$_from_line" -ge 1 ]] || _from_line=1
tail -n +"$_from_line" "$SESSION_EVENT_FILE"
}这样进入长 session 时不会因为历史太大而明显占用内存。
Replay 面向 display。它不会重建 conversation.jsonl,而是把最近的 events.jsonl 行重新转换成 display messages:
events.jsonl
-> event_replay.awk
-> RESP-like messages
-> display_stream
这意味着 live execution 和 replay 共享同一个 display renderer。
Usage events 会更新 stats.json:
agent_record_usage() {
local kind="$1" counter_key="$2" write_event="${3:-true}"
store_stats_update ${counter_key}=+1 \
total_input_tokens=+${_in} \
total_output_tokens=+${_out} \
total_cache_read_tokens=+${_cr} \
total_cache_creation_tokens=+${_cc}
}Stats 不只是展示数据。它会驱动:
- current context token estimate
- compaction decision
- cache hit visibility
- terminal title formatting
- runtime parity tests
终端标题也从同一个 stats 文件生成:
store_stats_format_title() {
util_awk_run -v model="$1" -f "$AWK_DIR/term_title.awk" "$STATS_FILE"
}系统提示词构建器 解释稳定 prompt section 如何组装。