{"slug": "show-hn-costcatch-a-cli-tool-for-agent-cost-tracking-and-debugging", "title": "Show HN: Costcatch – A CLI tool for Agent cost tracking and Debugging", "summary": "Developer Ronak Rahane released costcatch v0.2.0, an open-source npm CLI tool that records every LLM API call an AI agent makes by wrapping the agent's launch command, requiring no SDK changes or code edits and keeping all data on the local machine. The tool reports per-call model, token and cost figures, tool-result sizes, HTTP status and provider error messages for failed steps, plus warnings for loops, retries, duplicate calls and max_tokens cut-offs, and supports diff, --compare-last and CI gates on cost, calls and errors. costcatch requires Node.js 20.19 or later and Python 3.8 or later for tracing Python agents, and users must run `costcatch init` once to download current model prices.", "body_md": "**Put `costcatch` in front of the command that runs your agent.\nNothing to add to your code, nothing to sign up for, and nothing leaves your machine.**\n\n```\ncostcatch python my_agent.py\n```\n\nAn AI agent is a loop. Every turn it sends the whole conversation to a model, runs the tools the model asks for, adds their results, and goes again. Both the cost and the bugs hide in that loop:\n\n- **Costs add up quietly.** The history is sent again on every turn, so one big\ntool result is paid for on every call after it. A silent retry, or an agent\nstuck repeating itself, multiplies the bill.\n- **Failures hide.** The SDK retries a rate limit without telling you. A tool\nfails and the model works around it. An answer gets cut off at`max_tokens` .\nThe run still \"finishes\", and all you see is the final answer.\n- **Your provider's dashboard can't help.** It shows a daily total per model. It\ncan't tell you which step of which run, which tool, or why.\n- **Most tracing tools need setup first.** You wrap your client in their SDK,\nsend your traffic through their proxy, or upload your prompts to their cloud.\n\ncostcatch runs your agent and records every LLM API call it makes, from outside your code. While the agent runs, each call shows up live in your terminal. When it ends, you get the whole run step by step: the model, tokens and cost of each call, the tools the model asked for and how big their results were, what failed and why, and warnings that point at what to fix.\n\n| Question | Where costcatch answers it | \n|---|---|\n| Which step failed, and why? | ✗ rows with the HTTP status and the provider's message, and failed tools with their error | \n| Which step costs the most? | The cost of every step, with a bar, and a warning when one step costs more than the rest together | \n| Which tool result is bloating every prompt? | The size of every tool result, and a warning for big results sent again and again | \n| Did the agent loop, retry, or get cut off? | Loop, retry, duplicate and cut-off warnings | \n| Where did the time go? | Time in LLM calls against time in your own code and tools | \n| Did my change make it worse? | `diff` ,`--compare-last` , and CI gates on cost, calls and errors | \n\nHow it compares:\n\n| Approach | Examples | What it asks of you | \n|---|---|---|\n| SDK-based tracing | LangSmith, Langfuse, Braintrust | Add their SDK to your code and send traces to their server | \n| Proxies and gateways | Helicone, LiteLLM Proxy | Point your API base URL at the proxy | \n| OpenTelemetry | OpenLLMetry, APM vendors | Add instrumentation and run a collector | \n| **costcatch** |  | **Put `costcatch` in front of your command** | \n\ncostcatch is a tool for the machine you're developing on. It isn't production monitoring, and it works fine next to any of the tools above.\n\nThe published npm package, v0.2.0, requires Node.js 20.19 or later. To trace\nPython agents you also need Python 3.8 or later; there's nothing to `pip install`.\n\n```\nnpm install -g costcatch\ncostcatch init        # once: downloads current prices for every model\n```\n\nOr run it without installing: `npx costcatch python my_agent.py`.\n\nTo build it from source:\n\n```\ngit clone https://github.com/RonakRahane/costcatch.git\ncd costcatch\nnpm ci\nnpm run build\nnpm link              # puts the costcatch command on your PATH\ncostcatch init                  # first, once: download current prices for every model\ncostcatch python my_agent.py    # trace a Python agent\ncostcatch node my_agent.js      # trace a Node.js agent\n```\n\nRun `costcatch init` before your first trace, and again now and then to pick up\nnew prices. Without it, costcatch only knows a small bundled price list, so\nnewer models show `$?.??`, and costcatch reminds you to run it.\n\nThis is the full terminal screen from `costcatch init`. It was captured on\nNovember 18, 2026; the fetched model count changes as the public price lists are\nupdated.\n\n```\n ██████╗ ██████╗ ███████╗████████╗ ██████╗ █████╗ ████████╗ ██████╗██╗  ██╗\n██╔════╝██╔═══██╗██╔════╝╚══██╔══╝██╔════╝██╔══██╗╚══██╔══╝██╔════╝██║  ██║\n██║     ██║   ██║███████╗   ██║   ██║     ███████║   ██║   ██║     ███████║\n██║     ██║   ██║╚════██║   ██║   ██║     ██╔══██║   ██║   ██║     ██╔══██║\n╚██████╗╚██████╔╝███████║   ██║   ╚██████╗██║  ██║   ██║   ╚██████╗██║  ██║\n ╚═════╝ ╚═════╝ ╚══════╝   ╚═╝    ╚═════╝╚═╝  ╚═╝   ╚═╝    ╚═════╝╚═╝  ╚═╝\n\n┌────────────────────────────────┬────── v0.2.0 ───────────────────────────────────────┐\n│                                │                                                     │\n│ About                          │ Commands                                            │\n│ Zero-instrumentation LLM       │   run          trace a script (default)             │\n│ agent tracer & cost tracker.   │   estimate     estimate prompt token cost           │\n│ Like `time`, for AI agents.    │   show         inspect conversation content         │\n│                                │   diff         compare two saved traces             │\n│ Features                       │   stats        aggregated analytics                 │\n│ · live trace in the terminal   │   replay       re-display a saved trace             │\n│ · per-call cost tracking       │   watch        run, always saved                    │\n│ · prompt cost estimation       │   clean        prune old saved traces               │\n│ · auto-diff between runs       │   init         setup & fetch pricing                │\n│ · CI assertion gates           │                                                     │\n│ · secret & PII redaction       │ Quick Start                                         │\n│                                │ $ costcatch python3 agent.py                        │\n│                                │ $ costcatch node agent.mjs                          │\n│                                │                                                     │\n└────────────────────────────────┴─────────────────────────────────────────────────────┘\n\n- fetching latest model pricing…\n\n┌──────────────────────────────────────────────────────────────────────────────────────────────┐\n│ costcatch                                                                               init │\n│                                                                                              │\n│ ✓ created .costcatch/ (~/oncall-agent/.costcatch)                                            │\n│ ✓ added .costcatch/ to .gitignore                                                            │\n│ ✓ fetched latest pricing (5,831 models)                                                      │\n│                                                                                              │\n│ ready · run `costcatch --help` to see all commands                                           │\n└──────────────────────────────────────────────────────────────────────────────────────────────┘\n```\n\nYour program runs as usual and keeps its own output and exit code. costcatch draws a live view of the calls under that output, and prints the full trace when the program exits.\n\nThe repository has a small demo agent that answers its own API calls from a\nmock server in the same process. It needs no key and calls no real API, and\ncostcatch prices its calls as if they went to `gpt-4o`. From the repository root:\n\n```\ncostcatch node demo_scripts/demo_agent.mjs\n\ncostcatch --save node demo_scripts/demo_agent.mjs      # save a run\ncostcatch --save node demo_scripts/demo_agent_v2.mjs   # save a cheaper version of the same agent\ncostcatch diff                                         # compare the two saved runs\ncostcatch --save python my_agent.py                 # keep the trace in .costcatch/\ncostcatch show --step 3                             # read exactly what step 3 sent and got back\ncostcatch --save --compare-last python my_agent.py  # what changed since the last run\ncostcatch stats                                     # spend and tools across all saved runs\ncostcatch --max-cost 0.10 --max-errors 0 python my_agent.py   # fail if it costs too much or errors\n```\n\n**costcatch's own flags go first.** Like `time` and `env`, everything from\nyour program's name onward belongs to your program. `costcatch --save python agent.py` saves the trace; `costcatch python agent.py --save` passes `--save`\nto your agent. costcatch warns you when one of its flags ends up in your\ncommand.\n\ncostcatch isn't limited to scripts. Start your backend under costcatch, use your\napp the way you normally would (a browser, your frontend, `curl`), and every LLM\ncall any request makes shows up in the live view. Press Ctrl+C to stop the\nserver, and costcatch prints the trace of the whole session. Add `--save` to\nkeep it.\n\n``` php\nflowchart LR\n    client([\"Browser, frontend<br/>or curl\"]) -->|\"requests\"| server\n    subgraph session[\"Started under costcatch\"]\n        server[\"Your backend<br/>FastAPI · Express · …\"]\n    end\n    server -->|\"LLM calls, recorded\"| api[\"LLM API\"]\n    session -->|\"Ctrl+C\"| trace[\"One trace for the session<br/>every call, its cost, every warning\"]\n```\n\n**Node.js.** Express, Fastify or a plain `http` server all work the same way:\n\n```\ncostcatch node server.js                   # start the server under costcatch\ncostcatch --save node --watch server.js    # restarts on file changes stay in one trace\ncostcatch --save npx tsx src/server.ts     # a TypeScript server, through tsx\n```\n\ncostcatch needs to see `node`, `npx`, `tsx` or `ts-node` in the command, so\n`costcatch npm run dev` stops with \"Could not detect runtime\". Use the command\nfrom your `dev` script instead, for example `costcatch node --watch src/server.js`.\n\n**FastAPI.** Start uvicorn or the FastAPI CLI through `python -m`:\n\n```\ncostcatch python -m uvicorn main:app --reload        # also works with --workers\ncostcatch python -m fastapi dev main.py              # the FastAPI CLI\ncostcatch -- uv run python -m uvicorn main:app       # in a uv project\n```\n\n`costcatch uvicorn main:app` doesn't work, because costcatch needs to see\n`python` in the command. `python -m uvicorn` starts the same server. Reloads and\nworker processes land in the same trace.\n\nA few things to know about a session trace:\n\n- Calls are numbered in the order they started, across every request.\n- Warnings that compare calls treat the session as one run. Two requests that send the same prompt show as a retry.\n- `costcatch show --grep \"<text>\"` finds the calls one request made.\n- `--budget 1.00` stops the server once the session has spent $1.00.\n- A long session can hit the capture limit (64 MiB). Raise\n`COSTCATCH_MAX_TRACE_BYTES` to record more.\n\n``` php\nflowchart LR\n    cmd([\"costcatch python agent.py\"]) --> program\n\n    subgraph program[\"Your program, unchanged\"]\n        direction TB\n        code[\"Agent code\"] --> client[\"LLM SDK / HTTP client<br/>patched in memory\"]\n    end\n\n    client <-->|\"HTTPS, untouched\"| api[\"LLM API<br/>OpenAI · Anthropic · Gemini · …\"]\n    client -.->|\"a copy of each call\"| file[(\"Capture file<br/>local, temporary\")]\n    file --> live[\"Live view<br/>while it runs\"]\n    file --> build[\"Trace<br/>parsed · priced · redacted<br/>checked for problems\"]\n```\n\n1. **costcatch starts your program with a small interceptor loaded.** For\nNode.js it patches`http` ,`https` and`fetch` , and it also reaches programs\nstarted through`npx` or`tsx` and any Node workers your program starts. For\nPython it patches`httpx` ,`httpx2` and`urllib3` , which covers`requests` ,\nthe OpenAI, Anthropic and Mistral SDKs, LangChain, LiteLLM and CrewAI.\n2. **The interceptor copies each LLM call** (the URL, the request, the response,\nthe status and the timing) into a temporary file on your machine. Streamed\nresponses are put back together from their events.\n3. **costcatch reads that file while the program runs** to draw the live view.\nWhen the program exits, it builds the trace: each call is read, priced,\nredacted, linked to its tool results, and checked for problems.\n\nThe interceptor only watches. If something inside costcatch fails, it records nothing; it never breaks your agent. Your program reads its responses as usual, errors stay yours, and memory use is capped (2 MiB per response and 64 MiB per run by default). Request headers are never read, so your API keys never end up in a trace.\n\n**How it knows about your tools.** costcatch only sees HTTP traffic, but every\ntool result has to go back to the model inside the next request, tagged with the\nid of the call it answers. costcatch matches the two by that id. That's how it\nknows how big each result was, which tools failed, and which results were sent\nagain on every later call. It never guesses: a tool counts as failed only when\nthe API itself marks the result as an error.\n\nThe examples below are real costcatch output from a demo research agent run\nagainst a local mock API. The run hits most of what goes wrong in practice: a\nbig file read, a tool that keeps failing, a rate limit, an answer cut off at\n`max_tokens`, and a crash before a tool result went back to the model.\n\nA live box sits under your program's own output and redraws in place. Calls in flight show a spinner and a timer. Finished calls settle in with their tokens and cost, and a failed tool turns ✗ as soon as the next call reports it.\n\n```\n┌──────────────────────────────────────────────────────────────────────────────────────────────┐\n│ ▸ costcatch                                                                     10.4s  $0.03 │\n│                                                                                              │\n│ ✓ Step 1 claude-sonnet-4-20250514    1.2s     43 tok in → 60 tok out  $0.00103               │\n│    ├─ ▸ read_file(path=\"big.log\")  → ~4.3k tok                                               │\n│    └─ ✗ get_weather(city=\"Atlantis\")                                                         │\n│         failed: WeatherAPIError: city 'Atlantis' not found                                   │\n│ ✓ Step 2 claude-sonnet-4-20250514    2.4s  4,142 tok in → 60 tok out     $0.01               │\n│    └─ ✗ get_weather(city=\"Atlantis\")                                                         │\n│         failed: WeatherAPIError: city 'Atlantis' not found                                   │\n│ ✗ Step 3 claude-sonnet-4-20250514   312ms  HTTP 429                                          │\n│    └─ rate_limit_error Number of request tokens has exceeded your per-minute rate limit      │\n│ ✓ Step 4 claude-sonnet-4-20250514    2.1s  4,213 tok in → 60 tok out     $0.01               │\n│    └─ ▸ get_weather(city=\"Atlantis\")                                                         │\n│ ▖ ··     claude-sonnet-4-20250514    2.5s  thinking..                                        │\n│                                                                                              │\n│ 5 calls · 8.4k tok in → 180 tok out · $0.03 · 3 errors                                       │\n└──────────────────────────────────────────────────────────────────────────────────────────────┘\n```\n\nThe box fits your window and keeps working when you resize it, including inside task runners such as turborepo. When it fills the window, the oldest steps move up into your scrollback and one row at the top adds them up, so no step is ever lost. If another process writes to the same terminal, costcatch prints one line per call instead and tells you which process it is.\n\nThe live box is replaced by the full trace: every step, a summary, and the warnings, worst first.\n\n```\n┌──────────────────────────────────────────────────────────────────────────────────────────────┐\n│ costcatch                                          claude-sonnet-4-20250514  ·  17.2s  $0.10 │\n│                                                                                              │\n│ ✓ Step 1   1.2s    400 tok in → 60 tok out  $0.00210  ▒░░░░                                  │\n│    ├─ ▸ read_file(path=\"big.log\")  → ~5.4k tok                                               │\n│    └─ ✗ get_weather(city=\"Atlantis\")                                                         │\n│         failed: WeatherAPIError: city 'Atlantis' not found                                   │\n│                                                                                              │\n│ ✓ Step 2   2.4s  7,500 tok in → 60 tok out     $0.02  ████▓                                  │\n│    └─ ✗ get_weather(city=\"Atlantis\")                                                         │\n│         failed: WeatherAPIError: city 'Atlantis' not found                                   │\n│    ∆ context grew 18.8× (400 → 7,500 input tok)                                              │\n│                                                                                              │\n│ ✗ Step 3  305ms  HTTP 429                                                                    │\n│    └─ rate_limit_error Number of request tokens has exceeded your per-minute rate limit      │\n│                                                                                              │\n│ ✓ Step 4   2.1s  7,700 tok in → 60 tok out     $0.02  ████▓                                  │\n│    →→ retry of step 3                                                                        │\n│    └─ ✗ get_weather(city=\"Atlantis\")                                                         │\n│         failed: WeatherAPIError: city 'Atlantis' not found                                   │\n│                                                                                              │\n│ ∆ Step 5   3.8s  7,900 tok in → 60 tok out     $0.02  █████                                  │\n│    ∆ output cut off (max_tokens): the answer is incomplete                                   │\n│                                                                                              │\n│ ✓ Step 6   1.6s  8,100 tok in → 60 tok out     $0.03  █████                                  │\n│    └─ ▸ submit(answer=\"unknown\")  → no result                                                │\n│                                                                                              │\n│ ── summary                                                                                   │\n│ 6 LLM calls  ·  5 tool calls  ·  17.2s  ·  $0.10                                             │\n│ ✗ 1 failed LLM call · 3 failed tool calls                                                    │\n│ 11.5s in LLM calls  ·  5.7s between calls (your code and tools)                              │\n│ 1 repeated prompt                                                                            │\n│ 32k tok in → 300 tok out                                                                     │\n│ at 1 run/day = $2.98/mo  ·  at 100 runs/day = $297.90/mo  ·  at 1000 runs/day = $2,979.00/mo │\n│                                                                                              │\n│ ── warnings                                                                                  │\n│ ● Step 3 failed: HTTP 429 rate_limit_error: Number of request tokens has exceeded your per-… │\n│ ● get_weather() was called 3 times with the same arguments (steps 1, 2 and 4); all 3 failed… │\n│ ● Context grew 20× across calls (400 → 8,100 tokens)                                         │\n│ ● Step 6 asked for submit(); the program exited with code 1 before sending its result back … │\n│ ● Step 5 was cut off (max_tokens): the answer is incomplete                                  │\n│ ● Step 1: read_file() returned ~5.4k tokens, 72% of step 2's prompt, sent 5 times            │\n│ ● Step 4 retried step 3 (which failed), same prompt re-sent                                  │\n│ ● Context grew 18.8× between steps 1 and 2 (400 → 7,500)                                     │\n│ ● 5.6s passed after step 1 before the next LLM call (other gaps: 32ms); step 1 asked for re… │\n│ run 2026-10-10T10-03-06                                                                      │\n└──────────────────────────────────────────────────────────────────────────────────────────────┘\n```\n\nOne screen tells you that the weather tool never worked and the agent kept\ntrying it, that one file read is sent again with every call, that a rate limit\nwas retried, that the final answer was cut off, and that the program crashed\nbefore its `submit` result went back to the model.\n\nWith `--no-color`, in CI, or when the output goes to a file, the same trace\nprints as plain lines that are safe for logs:\n\n```\n  6 LLM calls · 5 tool calls · 17.2s · $0.10\n  1 failed LLM call · 3 failed tool calls\n  11.5s in LLM calls · 5.7s between calls (your code and tools)\n  1 repeated prompt\n  warnings:\n    - [critical] Step 3 failed: HTTP 429 rate_limit_error: Number of request tokens has exceeded your per-minute rate limit\n    - [critical] get_weather() was called 3 times with the same arguments (steps 1, 2 and 4); all 3 failed: WeatherAPIError: city 'Atlantis' not found\n    - [critical] Context grew 20× across calls (400 → 8,100 tokens)\n    - [warn] Step 6 asked for submit(); the program exited with code 1 before sending its result back to the model\n    …\n```\n\nThe same run, input tokens per call:\n\n```\nStep 1     400  ██\nStep 2   7,500  █████████████████████████████████████   ← read_file's ~5.4k-token result joins the history\nStep 3       —                                          (HTTP 429, nothing billed)\nStep 4   7,700  ██████████████████████████████████████\nStep 5   7,900  ███████████████████████████████████████\nStep 6   8,100  ████████████████████████████████████████\n```\n\nChat APIs send the whole history on every call, so a result that enters the conversation once is paid for again on every call after it. costcatch counts those resends (\"sent 5 times\") and flags a result that's both large and a big part of the prompt. Trimming that one tool's output is often the cheapest fix in an agent.\n\ncostcatch works out what happened from the traffic alone. Each warning has a\nstable `code` in the `--json` output.\n\n| Warning | Code | Severity | What it means | \n|---|---|---|---|\n| Failed calls | `http_error` | critical | A call failed: a 429 rate limit, a 5xx, a 401, a dropped connection, an error inside a 200 response, or no response before the run ended | \n| Failed tool calls | `tool_error` | warn | A tool result went back to the model marked as an error (Anthropic's `is_error` ) | \n| Tool loops | `tool_loop` | warn, critical | The same tool with the same arguments in three or more steps; critical when every call failed | \n| Unanswered tool calls | `unanswered_tool_call` | warn | The program crashed, or `--budget` stopped it, after a step asked for a tool and before its result went back | \n| Cut-off output | `truncated_output` | warn | The output hit a token limit ( `length` ,`max_tokens` , …), so the answer or the tool arguments are incomplete | \n| Blocked output | `blocked_output` | warn | The output was blocked by a filter or refused ( `content_filter` ,`refusal` , Gemini safety stops) | \n| Invalid tool call | `invalid_tool_call` | warn | The model wrote a broken tool call, such as arguments that aren't valid JSON | \n| Cancelled call | `cancelled_call` | info | Your program stopped reading a response before it finished, so its output and cost are unknown | \n| Large tool results | `large_tool_result` | warn | A result of about 1,000 tokens or more that is at least 25% of the prompt carrying it, with how often it was resent | \n| Retries | `retry` | warn, info | The same prompt sent again: after a failure (an SDK retry), or as a redundant call | \n| Context growth | `context_growth` | warn, critical | Input tokens growing 3× or more over a conversation; critical from 10× | \n| Context spike | `context_spike` | warn | Input tokens growing 4× or more between two calls | \n| Duplicate tool calls | `duplicate_tool_call` | warn, info | The same call made twice, or the same request in slightly different words | \n| Cost concentration | `cost_concentration` | warn | One step costs more than half the run | \n| Latency spikes | `latency_spike` | info | A call far slower than the run's others, or slower than `--threshold` | \n| Slow gaps | `slow_gap` | info | A long wait between a step's response and the next call: a slow tool, or slow code of your own | \n\n| Command | What it does | \n|---|---|\n| `costcatch <your command>` | Trace a Python or Node.js program. Same as `costcatch run <your command>` | \n| `costcatch watch <your command>` | Trace a program and always save the trace | \n| `costcatch show [trace]` | Print what each step sent and got back | \n| `costcatch replay [trace]` | Draw a saved trace again | \n| `costcatch diff [before] [after]` | Compare two saved traces | \n| `costcatch stats` | Spend, tokens and tools across all saved traces | \n| `costcatch estimate [file]` | Price a prompt before you send it | \n| `costcatch init` | Create `.costcatch/` and download current prices | \n| `costcatch clean` | Delete old saved traces | \n\nCommands that read a saved trace use the newest one in `.costcatch/` when you\ndon't name a file. Every command takes `--no-color` and `--help`.\n\n```\ncostcatch python my_agent.py\ncostcatch run node my_agent.js     # the same thing\n```\n\n| Flag | What it does | \n|---|---|\n| `--save` | Save the trace to `.costcatch/` | \n| `--save-as <name>` | Save under a name you choose (overwrites it) | \n| `--inspect` | After the run, show the full conversation of every step | \n| `--compare-last` | Compare with the last saved trace of this script (also saves) | \n| `--max-cost <usd>` | Exit 1 if the run cost more than this | \n| `--max-calls <n>` | Exit 1 if there were more LLM calls than this | \n| `--max-errors <n>` | Exit 1 if failed LLM calls plus failed tool calls are more than this | \n| `--budget <usd>` | Stop the program as soon as spend passes this, or a call can't be priced | \n| `--threshold <ms>` | Flag calls slower than this | \n| `--filter <provider>` | Trace only one provider, for example `--filter anthropic` | \n| `--no-cost` | Hide cost figures | \n| `--no-redact` | Keep personal data in captured content (secrets are always removed) | \n| `--json` | Print the trace as JSON | \n| `--no-color` | Plain output with no color or cursor movement ( `NO_COLOR` works too) | \n| `--quiet` | Print a one-line summary only | \n\nThe live view only appears in an interactive, colored terminal. In CI, when the\noutput is piped, or with `--no-color`, costcatch prints one plain line per call\nas the run goes, then the trace. With `--json`, your program's own output goes\nto stderr so stdout holds only the JSON.\n\n**Passing your own flags.** Your program's flags stay yours. If your program\nuses a flag that costcatch also has, put `--` before your command:\n\n```\ncostcatch --save python agent.py --verbose    # --verbose goes to agent.py\ncostcatch --save -- python agent.py --save    # the second --save goes to agent.py\n```\n\n**Launchers.** The runtime doesn't have to come first. costcatch looks past a\nlauncher to the `python` or `node` it starts:\n\n```\ncostcatch --save -- poetry run python agent.py\ncostcatch -- uv run --with openai python agent.py\ncostcatch -- env OPENAI_BASE_URL=http://localhost:4000 node agent.js\n```\n\nName the interpreter (`uv run python agent.py`, not `uv run agent.py`), and use\n`--` when the launcher has flags of its own. costcatch recognises `python`,\n`python3`, `python3.x`, `py`, `node`, `nodejs`, `npx`, `tsx` and `ts-node`. A\nlauncher that clears the environment, as `sudo` does by default, also removes\nthe interceptor; costcatch tells you when that happens.\n\nThe same as `run --save`, with the live view on. It takes the same flags as\n`run`, except `--save`, `--json` and `--quiet`.\n\nAgent bugs are rarely about what it called and usually about what was in the\nprompt that made it do that. `show` prints each step's system prompt, messages,\noutput, tool calls with their result sizes, and any error. It also prints the\nprovider's own usage numbers exactly as sent, including the ones the summary\nleaves out, such as one-hour cache writes, web searches or the service tier.\n\n```\ncostcatch show                                  # the latest saved trace\ncostcatch show trace.json --step 3              # one step\ncostcatch show trace.json --grep \"not found\"    # steps that mention a word, tool errors included\ncostcatch replay                     # draw the latest saved trace again\ncostcatch replay trace.json --json   # a saved trace as JSON\n\ncostcatch diff                       # compare the last two saved runs\ncostcatch diff before.json after.json\n```\n\n`diff` compares the totals (steps, calls, tool calls, time, cost and the largest\nprompt), the tools added or removed, and each step's tokens and cost. It pairs\nsteps by model and tool names, not by position.\n\n```\ncostcatch stats                      # spend by script and model, tokens, slowest runs\ncostcatch stats --week --script my_agent.py\ncostcatch stats --model gpt-4o --json\n```\n\n`--today` and `--week` limit it to recent runs, `--script` and `--model` filter\nby name. `stats` reads up to 2,000 saved traces. It also ranks your tools by how\nmany tokens their results put into prompts, resends included:\n\n```\n  ── tools, by result tokens sent\n      ~27k tok  read_file  (1 call · avg ~5.4k tok)\n      ~132 tok  get_weather  (3 calls · 3 failed · avg ~12 tok · 32ms after)\n             —  submit  (1 call · 1 unanswered)\ncostcatch estimate prompt.txt --model gpt-4o\ncat prompt.md | costcatch estimate --model gpt-4o,claude-sonnet-4   # compare models\ncostcatch estimate --text \"Summarize this ticket\" --model gpt-4o\ncostcatch estimate prompt.txt --breakdown          # tokens per section\ncostcatch estimate prompt.txt --max-cost 0.05      # exit 1 if it would cost more\n```\n\nThe prompt comes from `--text`, a file, or standard input, up to 10 MB. Without\n`--model`, costcatch reads the model from `LLM_MODEL` (or `MODEL`,\n`OPENROUTER_MODEL`, `OPENAI_MODEL`, `GEMINI_MODEL`) in a `.env` file in the\ncurrent folder.\n\nAn estimate is not an exact count, and costcatch says how far off it can be: about ±10% on English text for Claude and OpenAI models, more for code, other languages, and models whose tokenizer hasn't been measured. Traced runs never estimate; they use the counts the API reports.\n\n```\ncostcatch init                          # create .costcatch/, add it to .gitignore, fetch current prices\ncostcatch init --offline                # the same, with the bundled prices only\n\ncostcatch clean --keep 50               # keep the 50 newest saved traces\ncostcatch clean --older-than 30         # delete traces older than 30 days\ncostcatch clean --older-than 30 --dry-run\n```\n\n`clean` needs `--keep`, `--older-than`, or both. With both, a trace is deleted\nonly when it's outside the newest `--keep` and older than `--older-than` days.\n`--dry-run` lists what would go and deletes nothing.\n\nRun your agent with gates. Each one fails the job when the agent gets more expensive, makes more calls, or starts failing:\n\n```\ncostcatch --no-color --max-cost 0.10 --max-calls 8 --max-errors 0 python agent.py\n```\n\nA complete GitHub Actions job that also keeps the trace:\n\n```\nname: Agent check\n\non: [pull_request]\n\njobs:\n  agent:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n\n      - uses: actions/setup-node@v4\n        with:\n          node-version: \"22\"\n\n      - uses: actions/setup-python@v5\n        with:\n          python-version: \"3.12\"\n\n      - run: pip install -r requirements.txt\n\n      - name: Run the agent under costcatch\n        run: npx costcatch --no-color --save-as ci-run --max-cost 0.10 --max-calls 8 --max-errors 0 python agent.py\n        env:\n          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}\n\n      - name: Keep the trace\n        if: always()\n        uses: actions/upload-artifact@v4\n        with:\n          name: costcatch-trace\n          path: .costcatch/ci-run.json\n```\n\nThe trace is saved before the gates are checked, so a failed job still leaves\nits trace for `costcatch show`. A failed gate says what went wrong:\n\n```\n┌──────────────────────────────────────────────────────────────────────────────────────────────┐\n│ ✗ CI GATE: 4 errors (1 failed LLM call · 3 failed tool calls) exceeds --max-errors 0         │\n└──────────────────────────────────────────────────────────────────────────────────────────────┘\n```\n\nA gate that can't be judged fails instead of passing: a model costcatch can't price, a stream that reported no usage, or a run cut short by the capture limit.\n\n**Stop a runaway agent.** `--max-cost` judges the run after it ends. `--budget`\nwatches spend as calls land and stops the program once it passes the limit. It\nsends SIGTERM first so the program can clean up, then SIGKILL after five\nseconds. It counts calls as they finish, so calls already on their way still\ncomplete and are billed, and spend can end up above the limit. Like the gates,\nit fails closed: a call costcatch can't price stops the program too, because\nits cost can't be counted. Local Ollama calls cost $0, and a call the provider\nrefused (like a 429) costs nothing, so neither stops it.\n\n```\ncostcatch --budget 1.00 python my_agent.py\n```\n\nFor anything else, use the JSON:\n\n```\ncostcatch --json python agent.py | jq '.summary'\ncostcatch --json python agent.py | jq '[.warnings[] | select(.severity == \"critical\")]'\n```\n\n| Code | Meaning | \n|---|---|\n| `0` | Success, and your program exited 0 | \n| `1` | A `--max-cost` ,`--max-calls` ,`--max-errors` or`--budget` limit was passed | \n| `2` | Bad command: unknown runtime, missing arguments, unreadable input | \n| `70` | costcatch itself failed | \n| `127` | Your program could not be started | \n| other | Your program's own exit code (128+N for a signal) | \n\n| Provider | Detected by | Notes | \n|---|---|---|\n| **OpenAI** | `api.openai.com` | Chat Completions, the Responses API and embeddings, with streaming and tools | \n| **Azure OpenAI** | `*.openai.azure.com` | Read like OpenAI | \n| **Anthropic** | `api.anthropic.com` | Tool use, cache reads and writes, web search | \n| **Google Gemini** | `generativelanguage.googleapis.com` ,`aiplatform.googleapis.com` | The model is read from the URL | \n| **Claude on Vertex AI** | `aiplatform.googleapis.com/…/publishers/anthropic/…` | Read like Anthropic; run `costcatch init` to price its`@` -dated model names | \n| **OpenRouter** | `openrouter.ai` | Uses the cost OpenRouter reports when it sends one | \n| **Groq** | `api.groq.com` | OpenAI-compatible | \n| **Mistral** | `api.mistral.ai` | OpenAI-compatible | \n| **Cohere** | `api.cohere.com` ,`api.cohere.ai` | Chat, tool calls and embeddings | \n| **Ollama** | port `11434` | Local models, priced at zero | \n| **Anything else** | URLs with `/chat/completions` ,`/v1/responses` or`/v1/messages` , and paths ending in`/embeddings` | vLLM, Together, Fireworks, LiteLLM and other compatible servers | \n\nAWS Bedrock isn't supported: it signs every request and streams in a binary format.\n\n**Streams and token counts.** Anthropic streams always include usage. OpenAI\nChat Completions streams only include it when the request asks for it\n(`stream_options: { include_usage: true }`). Without it, the call is still\ntraced, its tokens show as `tokens ?`, and costcatch tells you how to turn usage\non.\n\nMissing a provider? [Open a provider request](https://github.com/RonakRahane/costcatch/issues/new?template=provider_request.yml).\n\n|  | Comes from | Exact? | \n|---|---|---|\n| Token counts | The `usage` the API returned | Yes. Never guessed: a call without usage shows `tokens ?` | \n| Status, errors, tool calls, timings | The recorded traffic | Yes | \n| Cost | Token counts times public prices from LiteLLM and OpenRouter (5,831 models in the November 18, 2026 capture; 44 are bundled), at the rate for what the response reports: long prompts, cache writes and their lifetime, flex or priority processing, US-only inference, fast mode, web searches | As exact as the price data. A model or billing condition costcatch can't price with confidence shows `$?.??` , never a guess | \n| Prompt-cache cost | The model's own cache prices | Yes when the price data has them. Otherwise reads cost 0.5× input, and Anthropic's writes 1.25× (2× for one-hour writes). OpenAI charges for writes on some models only, so an OpenAI write without a listed price shows `$?.??` ; its 12-hour writes cost 2.5× input | \n| Tool result sizes | The result's text, measured for the model's tokenizer | Estimated, marked `~` | \n| `costcatch estimate` | The same measurement | Estimated, with its margin | \n\nFailures are never guessed from text. A tool counts as failed only when the API marks its result as an error, and a call counts as having no result only when costcatch could read every request after it.\n\nEverything stays on your machine. costcatch writes in these places only:\n\n| Data | Where | Kept until | \n|---|---|---|\n| Calls recorded during a run | A private temporary folder ( `costcatch-*` ) | The run ends | \n| Saved traces | `.costcatch/<run-id>-<script>.json` in the folder you run costcatch from | You delete them, or `costcatch clean` does | \n| Downloaded prices | `~/.costcatch/pricing.json` (or under`$COSTCATCH_HOME` ) | The next `costcatch init` | \n\n- A trace is saved only when you ask: `--save` ,`--save-as` ,`--compare-last` or`watch` .\n- Two runs saved in the same second get numbered copies instead of overwriting each other. Files are written in one go, so an interrupted run never leaves half a file, and only you can read them.\n- `costcatch init` adds`.costcatch/` to`.gitignore` . Traces hold your prompts,\nso keep them out of version control.\n\nA saved trace is the same JSON that `--json` prints:\n\n| Field | What it holds | \n|---|---|\n| `runId` ,`startedAt` ,`durationMs` | When the run started and how long it took | \n| `script` ,`runtime` ,`command` | What was traced. `command` is redacted, since arguments can carry keys | \n| `exitCode` | Your program's exit code | \n| `totalCostUsd` | The cost of every priced call. `0` when the provider rejected every call, since a rejected call costs nothing;`null` when nothing could be priced | \n| `summary` | Totals: `llmCalls` ,`toolCalls` ,`totalInputTokens` ,`totalOutputTokens` ,`retries` ,`wastedCostUsd` ,`unpricedCalls` and more | \n| `steps` | One entry per LLM call: `provider` ,`model` , tokens,`costUsd` ,`providerUsage` (the provider's own usage numbers),`statusCode` ,`error` ,`finishReason` ,`toolCalls` with their results, and the captured`content` | \n| `warnings` | Each warning's `severity` ,`code` ,`message` and the`stepIds` it is about | \n\nThe full type is in [src/types/trace.ts](https://github.com/RonakRahane/costcatch/blob/main/src/types/trace.ts). The format may\nstill change before 1.0; a newer costcatch still opens traces saved by an\nolder one.\n\n```\nnpm uninstall -g costcatch\nrm -rf .costcatch            # this project's saved traces\nrm -rf ~/.costcatch          # the downloaded prices\n```\n\n- **Local only.** There's no telemetry. The only network request costcatch makes\non its own is`costcatch init` downloading public price lists.\n- **No API keys.** Request headers, where API keys live, are never read.\n- **Secrets are always removed** from everything recorded, before it's stored\nor printed: OpenAI, Anthropic, Google, AWS, Groq, Replicate, GitHub, Slack,\nStripe, SendGrid, Hugging Face and OpenRouter keys, webhook signing secrets,\nJWTs,`Bearer` tokens, labelled`api_key: value` pairs, passwords in\nconnection URLs, Azure account keys, Slack webhook URLs, private keys (PEM and\nJWK), and the credentials in Docker,`.netrc` and kubeconfig files.\n- **Personal data is removed by default:** emails, formatted phone numbers and\ncard numbers. Turn this off with`--no-redact` .\n- **Terminal tricks are stripped.** Model output can carry escape sequences that\nwould rewrite your screen; costcatch removes them.\n- **Saved traces are checked when loaded** , since they get shared: every field is\nvalidated before anything is drawn.\n\nRedaction catches the formats listed above, not every possible secret. Look over a trace before you share it.\n\n**Found a security issue?** Please report it privately through\n[GitHub security advisories](https://github.com/RonakRahane/costcatch/security/advisories/new),\nnot in a public issue.\n\ncostcatch needs no config file. These environment variables change how it behaves:\n\n| Variable | Effect | \n|---|---|\n| `NO_COLOR` | Turn off color, the same as `--no-color` | \n| `CI` | Print plain lines instead of the live view (also when output is piped, or `TERM=dumb` ) | \n| `COLUMNS` ,`LINES` | The terminal size to draw for. Set both to keep the live view behind a task runner that hides the real size | \n| `COSTCATCH_MAX_BODY_BYTES` | Largest response body recorded (default 2 MiB) | \n| `COSTCATCH_MAX_TRACE_BYTES` | Most data recorded per run (default 64 MiB). A run that hits it says so, and its gates fail | \n| `COSTCATCH_HOME` | Where the downloaded prices live (default: your home folder) | \n| `COSTCATCH_DEBUG=1` | Print stack traces for internal errors | \n\n**\"No LLM API calls detected during this run\"**\n\nThe program ran, but costcatch saw no call it recognises. Usually one of these:\n\n- The agent uses a transport costcatch doesn't patch, such as Python's\n`aiohttp` or gRPC.\n- The API's address isn't one costcatch recognises (see\n[Supported providers](#supported-providers) ). Ollama is only recognised on its\ndefault port, 11434.\n- A launcher cleared the environment, as `sudo` does by default.\n- `--filter` hid the calls. Run again without it.\n\n**\"Could not detect runtime\"**\n\nThe command has to name `python` or `node`, directly or after a launcher. Write\n`uv run python agent.py`, not `uv run agent.py`, and `python -m uvicorn main:app`, not `uvicorn main:app`. bun and deno aren't supported; run the script\nwith `node` instead.\n\n`failed to start \"python\": not found on PATH`\n\nmacOS and many Linux systems call it `python3`. Run `costcatch python3 my_agent.py`.\n\n**Tokens show as `tokens ?`**\n\nThe call was a stream that reported no usage. For OpenAI Chat Completions\nstreams, add `stream_options: { include_usage: true }` to the request.\n\n**Cost shows as `$?.??`**\n\ncostcatch has no reliable price for that model. Run `costcatch init` to download\ncurrent prices. Until the model has a price, a `--max-cost` gate fails rather\nthan guess, and so does `--budget`.\n\nA bare model name that hosts sell at different prices also shows `$?.??`. For\nexample, Azure AI, watsonx and OpenRouter each list a `mistral-large` at their\nown price. A call to Mistral, Groq, DeepSeek, xAI, Together, Fireworks,\nCerebras, Gemini or Vertex AI is priced at that host's own rate. With\n`costcatch estimate`, name the host, as in `azure_ai/mistral-large`.\n\n**\"live view off: costcatch cannot see this terminal's size behind the task runner\"**\n\nSet `COLUMNS` and `LINES` in the task's environment to turn the live view back on.\n\n**\"live view off: pid … writes to this terminal too\"**\n\nAnother process writes to the same terminal, so the box would draw over its output. costcatch prints one line per call instead. To keep the box, run that process in a terminal of its own.\n\n**\"Capture limit reached\"**\n\nThe run hit the capture limit (64 MiB by default), so later calls weren't\nrecorded. Its costs and counts are a lower bound, and its gates fail. Raise\n`COSTCATCH_MAX_TRACE_BYTES` to record more.\n\n**costcatch itself failed (exit code 70)**\n\nRun it again with `COSTCATCH_DEBUG=1` to see the stack trace, and\n[open a bug report](https://github.com/RonakRahane/costcatch/issues/new?template=bug_report.yml).\n\ncostcatch works at the HTTP level, from outside your code. That's what makes it zero-setup, and it also sets its limits:\n\n- **It sees calls, not the inside of your tools.** A tool's own exception isn't\nin the traffic. costcatch reports that the tool failed (when the API marks it)\nor that the program stopped before the result went back; the traceback is in\nyour program's output.\n- **Tool failures are only marked where the API has a flag for it** , which today\nis Anthropic's`is_error` .\n- **Some transports and runtimes aren't supported:** gRPC, Python's`aiohttp` ,\nbun and deno.\n- **Very large requests.** The Node.js interceptor reads up to 2 MiB of each\nrequest. Past that it can't see the tool results inside, so it makes no claims\nabout them. Raise`COSTCATCH_MAX_BODY_BYTES` to read more.\n- **Prices come from public price lists.** A model, or a billing condition, that\nthe list has no price for shows`$?.??` instead of a guess.`costcatch init` fetches the latest lists.\n- **Some streams carry no token counts:** Ollama's native stream and Gemini\nstreams without`alt=sse` show`tokens ?` .\n- **Calls made in parallel** are numbered by start time. HTTP alone can't tell\nwhich part of your code made which call.\n- **Stored conversation text is capped** at 8 million characters per run. Every\nnumber is still kept, and the steps say their text was cut.\n- **One machine.** costcatch sees the programs it starts. It's a development\ntool, not production monitoring.\n\n- **Found a bug?** Open a[bug report](https://github.com/RonakRahane/costcatch/issues/new?template=bug_report.yml) .\n- **Missing a provider or model?** Open a[provider request](https://github.com/RonakRahane/costcatch/issues/new?template=provider_request.yml) .\n- **A question or an idea?** Start a[discussion](https://github.com/RonakRahane/costcatch/discussions) .\n\nPull requests are welcome. Run `npm run verify` before you open one, and add a\nline to [CHANGELOG.md](https://github.com/RonakRahane/costcatch/blob/main/CHANGELOG.md) for anything users will notice. Changes to\nthe interceptors must leave the traced program behaving exactly as before.\n\nReleases are published to npm by the maintainer.\n\nMIT. See [LICENSE](https://github.com/RonakRahane/costcatch/blob/main/LICENSE).\n\nBuilt by [Ronak Rahane](https://github.com/ronakrahane)", "url": "https://wpnews.pro/news/show-hn-costcatch-a-cli-tool-for-agent-cost-tracking-and-debugging", "canonical_source": "https://github.com/RonakRahane/costcatch", "published_at": "2026-11-24 13:30:26+00:00", "updated_at": "2026-11-24 13:41:51.561602+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "mlops"], "entities": ["costcatch", "Ronak Rahane", "Node.js", "Python", "LangSmith", "Langfuse", "Braintrust", "Helicone"], "also_reported_by": [], "takeaway": "Wrapping an agent's launch command with costcatch v0.2.0 records each LLM call's model, tokens, cost and tool-result size from outside the code, flagging loops, retries and max_tokens cut-offs, with diff and --compare-last for regression checks.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/show-hn-costcatch-a-cli-tool-for-agent-cost-tracking-and-debugging", "markdown": "https://wpnews.pro/news/show-hn-costcatch-a-cli-tool-for-agent-cost-tracking-and-debugging.md", "text": "https://wpnews.pro/news/show-hn-costcatch-a-cli-tool-for-agent-cost-tracking-and-debugging.txt", "jsonld": "https://wpnews.pro/news/show-hn-costcatch-a-cli-tool-for-agent-cost-tracking-and-debugging.jsonld"}}