Usage, Cost & Context Compaction
Tuse tracks token usage and USD cost across main turns and llm() calls, and automatically compacts older tool output when a session's context grows past its compaction threshold.
Usage accounting
Token extraction
When an API response includes a usage object, Tuse records:
input(prompt_tokens) — total input tokens, including cached reads and cache writes.output(completion_tokens) — completion tokens generated.cache_read(prompt_tokens_details.cached_tokens) — cached prompt tokens read.cache_write—max(prompt_tokens_details.cache_write_tokens, prompt_tokens_details.cached_creation_tokens).
Main turn steps persist a main usage record (llm = false) and update the session's live context size to input + output. Lua llm() calls persist a usage record marked llm = true (and emit usage) only when the reply supplies usage, counting toward cumulative totals and spend without changing the session's context.
Cost calculation
For each usage record whose model matches a configured entry with prices:
plain_input = max(0, input - (cache_read + cache_write))
cost_usd = (plain_input * prices.input
+ cache_read * prices.cache_read
+ cache_write * prices.cache_write
+ output * prices.output) / 1,000,000
session().usage.costis the cumulative total across main turns andllm()calls;session().usage.llm_costis thellm()portion alone.- Cost is
nil/(unknown)(and omitted from the TUI model bar) until at least one usage record matches a model with configuredprices. - Updating
models[].pricesand running/reloadrecomputes cumulative costs across all records in the session immediately.
Token formatting and display
Token counts format compactly:
< 1,000: exact integer (999)1,000–999,999:kwith up to 1 decimal, dropping.0(5.2k,200k)>= 1,000,000:mwith up to 1 decimal, dropping.0(1m,1.5m)
Where usage appears:
- TUI bottom status bar:
<display> · <effort> [· <used>/<window>] [· $<cost>]. The context segment is omitted completely when both<used>and<window>are0; when<window>is0and<used> > 0, it shows<used>/?. Cost renders to 2 decimal places when priced (omitted otherwise);<used>is coloredaccent. /sessionpanel:Context(<used> / <window> (<pct>%), compacts at <threshold>),Turnsandsteps,Usage(in,cache read,cache write,out), andCost($<total>to 4 decimal places plus($<main> + $<llm> llm)).- Lua / JSON-RPC:
session().ctx,session().ctx_size,session().usage,session().steps,session().turns, andsession.stats/session.snapshot.
Context compaction (50/25/25)
Compaction reduces what is sent to the model on future steps without altering or deleting any saved records in SQLite or /trace.
Compaction threshold
After tool execution finishes at the end of a tool-using step, Tuse resolves the compaction threshold (compact_at):
- Active model's
models[].compact_atif set. This takes precedence oversettings.compact_atin both directions: a positive per-model threshold overrides a globalsettings.compact_at = 0, and a per-modelcompact_at = 0disables compaction for that model even ifsettings.compact_atis positive. - Otherwise
settings.compact_atif set (0disables compaction globally unless overridden per model). - Otherwise
floor(model.window * 6 / 10)(60% of the configuredwindow), or0(disabled) whenwindowis unknown (0).
If threshold > 0 and the latest context >= threshold, compaction runs.
Token estimation and three-zone algorithm
Tuse walks backward from the newest record, estimating tokens per message as:
- Non-multipart messages (string
content, or assistant messages withtool_calls):floor(serialized_message_json_bytes / 4). - Multipart messages (
contentis a JSON array, such as user messages with attached images): sum acrosscontentparts—eachimage_urlpart counts as1,000tokens, and every other part counts asfloor(serialized_part_json_bytes / 4).
Using these estimates, Tuse computes monotonic record index bounds (drop, prune):
- Fresh zone (newest ~25% of
threshold,index >= prune): Sent in full—user text with hidden context and images, assistant text and tool calls, full tool outputs, and images returned byread(). - Pruned middle zone (from ~25% to ~50% of
threshold,drop <= index < prune): Keeps user messages, hidden context, assistant messages, and tool-call structure, omits images from tool results, and shortens each tool result output to its first line (up to 200 characters) plus\n[tool output pruned]whenever the output is multiline or longer than 200 characters. - Dropped old zone (older than ~50% of
threshold,index < drop): Anchored at auserornotificationrecord boundary so assistanttool_callsand their matchingtoolresults are never split. Keeps only plain conversation text: usertext(without hiddencontextorimages),notificationtext, and non-empty assistanttext. All tool calls and tool results in this zone are omitted.
Bounds only advance forward (max with previous bounds). If neither drop nor prune advances, nothing changes.
Effects of compaction and resume
When bounds advance:
- Appends a
compactionrecord (prune,drop) to the session log (restored automatically on resume). - Subsequent API requests append a note to the system prompt when
drop > 0: "Earlier parts of this conversation were compacted to save context: old tool calls and their outputs were removed and some later outputs were cut to their first line." - Updates the live session's
contextcounter in memory to the estimated token count of the compacted message list. - Appends and emits a notice:
Context compacted at <threshold> tokens; now about <estimated>.
On resume, Tuse restores the compaction bounds from compaction records, while context is restored from the last non-llm usage record (input + output), not from the temporary post-compaction estimate.