Sessions & Workflows Intermediate
Multi-Turn Cost Tracking
Track cumulative cost across session turns by extracting total_cost_usd from each response
Command
$ RESULT=$("color:#7C5CFC">claude -p "Step 1" "color:#d97757">--output-format json) SESSION=$("color:#7C5CFC">echo "$RESULT" | "color:#7C5CFC">jq -r '.session_id') COST1=$("color:#7C5CFC">echo "$RESULT" | "color:#7C5CFC">jq -r '.total_cost_usd') RESULT2=$("color:#7C5CFC">claude -p "Step 2" "color:#d97757">--resume "$SESSION" "color:#d97757">--output-format json) COST2=$("color:#7C5CFC">echo "$RESULT2" | "color:#7C5CFC">jq -r '.total_cost_usd') "color:#7C5CFC">echo "Total: $(">echo "$COST1 + $COST2" | bc)"
Response
{
"total_cost_usd": 0.045,
"usage": {
"input_tokens": 156,
"cache_read_input_tokens": 14253,
"output_tokens": 87
}
} Parsing Code
059669">">let totalCost = 0; 059669">">for (059669">">const prompt 059669">">of prompts) { 059669">">const data = JSON.parse(execFileSync(059669059669">">'claude', [ 059669059669">">'-p', prompt, 059669059669">">'--resume', sessionId, 059669059669">">'--output-format', 059669059669">">'json' ], opts)); totalCost += data.total_cost_usd; console.log(059669">`Turn cost: $${data.total_cost_usd}, Running: $${totalCost}`); }
Gotchas
! total_cost_usd is for the CURRENT call only, not the cumulative session total
! Track costs in your own database for billing and auditing