# bash tool output truncation is bypassed by binary output: the 30,000 budget is measured in display columns, so tool results can reach tens of MB
Description
Suggested issue title (for GitHub):
bashtool output truncation is bypassed by binary output — the 30,000 budget is display width, not bytes, so a single tool result reached 26 MB / ~2 M tokens
Summary
bash tool output is supposed to be capped at 30,000 (internal/agent/tools/bash.go:55,
MaxOutputLength). For binary / NUL-heavy output that cap does not bound the result size
at all, because the budget and both slice offsets are computed in display columns
(ansi.StringWidth / ansi.Truncate / ansi.TruncateLeft), while NUL and control bytes
contribute 0 columns:
- Output whose total display width stays ≤ 30,000 columns is returned completely
untouched, no matter how many bytes it is (26 MB of
\0= 0 columns). - When truncation does trigger, the kept head and tail are sized in columns too, so the retained byte count is unbounded (observed: 1,087,328 chars of head + 1,057,542 chars of tail retained in one call).
- The dropped-middle marker reports lines, and binary content has no newlines, so it
proudly reports
... [0 lines truncated, ...] ...while ~26 MB was dropped.
In one observed incident this produced a single bash tool result of 2,144,870
characters ≈ 2 M tokens in the session history. The next provider request was
2,064,479 (messages) + 300,000 (completion) = 2,364,479 tokens against a 1,048,576-token
window and was rejected with HTTP 400. Because the oversized message is persisted, the
session is permanently unusable: including the auto-summarize path, which re-sends the same
history (see Impact).
Environment
| Crush | v0.96.1 (crush --version) |
| OS | Linux (x86_64) |
| Provider | OpenAI-compatible HTTP endpoint enforcing a 1,048,576-token window as input + requested completion (any endpoint that enforces a total window behaves the same) |
| Relevant code | internal/agent/tools/bash.go:55, 395-396, 428-446; github.com/charmbracelet/x/ansi v0.11.8 |
Steps to reproduce
Minimal (no repo needed) — any single tool result whose display width ≤ 30,000 columns yet whose byte size is huge is passed through verbatim:
mkdir -p /tmp/blob && head -c 26M /dev/zero > /tmp/blob/big.binThen have the agent (or a crush run) read it:
bash: { "command": "cat /tmp/blob/big.bin" }Real-world variant seen in practice: dumping a directory that contains a SQLite database, i.e. Crush's own session store:
find .crush -type f -exec echo "== {} ==" \; -exec cat {} \;The spilled full output is written to .crush/shell-output/output-<id>.log as intended, so
the data is not lost — it is only the model-facing copy that is not bounded.
Library-level reproduction, if you prefer a unit test (uses the exported
tools.TruncateOutput, so it is trivially testable):
func TestTruncateOutputBinaryBypass(t *testing.T) {
// 1 MiB of NULs has display width 5 -> returned unchanged today.
bin := strings.Repeat("\x00", 1<<20) + "hello"
require.LessOrEqual(t, len(TruncateOutput(bin, t.TempDir())), 4*MaxOutputLength)
}Expected
A tool result handed to the model is bounded by a byte (or rune) budget, e.g. ≤ ~32 KB, independent of content type, with the full output available in the spill file.
Actual
Measured on Crush v0.96.1 by calling tools.TruncateOutput directly:
| input | bytes | ansi.StringWidth |
TruncateOutput result |
|---|---|---|---|
1 MiB NULs + "hello" |
1,048,581 | 5 | 1,048,581 bytes — unchanged, no marker |
26 MiB NULs |
27,262,976 | 0 | 27,262,976 bytes — unchanged, no marker |
| incident sample (the already-truncated 2.14 MB result, re-truncated) | 2,175,988 | 213,563 | 202,291 bytes (marker at offset 154,970) |
Incident details (from the persisted session message and Crush's debug log):
- one
bashtool call returned 2,144,870 characters, marker placed at offset 1,087,328 → head 1,087,328 chars + tail 1,057,542 chars were kept. Both retained chunks are ~95 % NUL bytes (965,718 and 944,231 NULs respectively), i.e. they cost almost nothing in columns:... [0 lines truncated, full output: <session-dir>/.crush/shell-output/output-<id>.log] ... - the resulting request failed with:
This model's maximum context length is 1048576 tokens. However, you requested 2364479 tokens (2064479 in the messages, 300000 in the completion).
Root cause
// internal/agent/tools/bash.go:55
MaxOutputLength = 30000
// internal/agent/tools/bash.go:431
func TruncateOutput(content, spillDir string) string {
if ansi.StringWidth(content) <= MaxOutputLength { // (1)
return content // binary blob: width ~0 -> returned as-is
}
halfLength := MaxOutputLength / 2
start := ansi.Truncate(content, halfLength, "") // (2) columns, not bytes
end := ansi.TruncateLeft(content, ansi.StringWidth(content)-halfLength, "") // (2) columns, not bytes
truncatedLinesCount := max(strings.Count(content, "\n")-strings.Count(start, "\n")-strings.Count(end, "\n"), 0)
marker := fmt.Sprintf("... [%d lines truncated] ...", truncatedLinesCount) // (3) lines, not bytes
...
}- The guard compares display width with the budget, so any content that renders as few columns (NULs, control bytes, and generally binary data) is never truncated at all.
- When the guard fires, the head/tail are sliced by column offsets, so the number of bytes retained is unrelated to the budget: it is whatever the first/last 15,000 columns happen to span.
- The marker counts newlines, which binary output does not contain, so the "truncated" message can claim that nothing was dropped.
Impact
- One unlucky
bashcall (e.g.cating a binary/SQLite file,find … -exec cat, dumping a pty log) can exceed any context window by an order of magnitude and hard-fail the turn with a provider 400. - The oversized tool result is persisted in the session, so the session cannot be
recovered:
/summarizeand the automatic summarizer send the same history (internal/agent/agent.go:1335— the large model with the full message list, no trimming), which reproduces the same 400. The only escape iscrush session delete <id>. - Costs are also affected: a spurious ~2 M-token request is billed at input rates (a slightly smaller dump would have been accepted instead of rejected).
Suggested fix
Bound by bytes/runes, not display columns. Keep the ANSI-aware slicing for cosmetics, but enforce a byte cap on the result, e.g.
const ( maxOutputBytes = 48 << 10 // hard cap on what reaches the model maxOutputLines = 500 )and slice on byte boundaries (UTF-8-safe), or compute the column budget from the byte budget instead of the other way round.
Remove the early-return bypass: the
ansi.StringWidth(content) <= MaxOutputLengthshortcut must not skip the byte cap (it is the path that let a 26 MB blob through untouched).Make the marker honest: report dropped bytes (and lines when known) and never emit
[0 lines truncated]when content was actually dropped, e.g.... [10.4 MB omitted, full output: <path>] ....Defense in depth: cap the persisted tool-result size in the message store (e.g. 256 KB) so no tool —
bash,view, MCP tools,download— can render a session unrecoverable.
Workaround
A PreToolUse hook that refuses the unbounded-dump patterns before they run (it only
inspects CRUSH_TOOL_INPUT_COMMAND, so no JSON parsing is needed):
#!/usr/bin/env bash
set -u
cmd="${CRUSH_TOOL_INPUT_COMMAND:-}"
[ -z "$cmd" ] && exit 0
deny() { printf '{"decision":"deny","reason":"%s"}\n' "$1"; exit 0; }
printf '%s\n' "$cmd" | grep -Eq '(^|[[:space:];&|(])cat[[:space:]]+[^[:space:]]*(crush\.db|\.db-wal|\.db-shm)' \
&& deny 'Refusing to read the SQLite session store into context; use sqlite3 / python3 instead.'
printf '%s\n' "$cmd" | grep -Eq '(^|[[:space:];&|(])cat([[:space:]]+-[[:alnum:]]+)*[[:space:]]+[^[:space:]]*\.crush/' \
&& deny 'Refusing to cat files under .crush/ (unbounded size); use grep/view/crush logs.'
printf '%s\n' "$cmd" | grep -Eq -- '(-exec[[:space:]]+cat([[:space:]]|$)|[|][[:space:]]*xargs[[:space:]]+(-[[:alnum:]]+[[:space:]]+)*cat([[:space:]]|$))' \
&& deny 'Refusing unbounded dumps (find -exec cat / xargs cat); filter by name/size first.'
exit 0hook add PreToolUse --matcher "^bash$" --name deny-binary-dump \
--command "$HOME/.config/crush/hooks/deny-binary-dump.sh"Related observation (probably a separate issue)
The auto-summarize trigger does not reserve the completion budget. For
context_window > 200,000 the threshold is a fixed 20,000 tokens
(internal/agent/agent.go:1049-1054), so summarization only starts once
prompt_tokens + completion_tokens ≥ context_window − 20,000. With
context_window set to the model's full window and a non-trivial max_tokens, the request
issued just below that threshold is guaranteed to exceed a input + completion ≤ window
limit. Users must therefore set context_window ≤ window − max_tokens − 20,000, which is
not obvious. (Happy to file this separately if you prefer.)
Version
No response
Environment
No response
Source: charmbracelet/crush