為什麼 sessions_send 回來一次,Claude CLI 就突然變貴了?
我最近在調一條很長的 Claude CLI workflow,發現一個很怪的 cache 問題。流程本身沒有改,模型也沒有換,但只要中間用 sessions_send 傳回結果,下一輪的 prompt cache 就像被重置一樣。短對話不容易察覺,長對話就很痛,因為每一輪都重新吃一大段 system prompt。
我一開始以為是 session history 被重播,後來把每一輪送出的內容拆開看,才發現真正的差異在 system prompt。sessions_send 的處理指示被塞進 extraSystemPrompt,這代表該輪的 system prompt hash 會改變。下一輪指示消失後,hash 又切回去。對模型來說只是多一段文字,對 prompt cache 來說卻是整個前綴不一樣。
我的做法是把「這一輪要怎麼處理回傳結果」從穩定的 system prompt 移出去,改放在 runtimeContextFragments。概念可以簡化成這樣:
const currentTurnInstructions = buildCurrentTurnInstructions({
sessionSendResult,
toolResults,
});
return {
systemPrompt: stableSystemPrompt,
runtimeContextFragments: [currentTurnInstructions],
};
重點不是換一個欄位而已,而是要把 stable context 和 current turn context 分層。前者只放角色、規則、長期不變的工具說明,後者才放這一輪的 delivery 狀態、暫時指示和工具結果。只要把短命資料混進 system prompt,cache 就會一直抖。
我還補了兩種測試。第一種是連續跑六輪,確認每輪 stable system prompt 的 hash 都相同。第二種是 replay 同一個 turn,確認 runtime context 不會被重複拼接,否則修好 cache 又會製造重播污染。這個測試很值得加在自己寫的 skill 裡,尤其是會呼叫 sessions_send、spawn 子任務,或把結果送回長對話的 workflow。
實測差異很誇張,delivery turn 的 cache write token 從 18,475 降到 883,長對話大約 89k token 時尤其明顯。我的判斷是,做 Skill 時不要只看功能有沒有完成,也要看每個 runtime instruction 被放在哪個生命週期。會變動的東西放在 turn context,穩定的東西才留在 system prompt。
這個原則也適用在其他 runner。Copilot 和 Muse 我會先做 outgoing input test,再補 live proof,因為不同 runner 對 context replay 的行為不一定一樣。先把邊界測清楚,再談共用 builder,workflow 這樣設才不會只在自己的環境裡看起來正常。
作者:Jesse