# What does one AI coding agent task cost? A per-task method

URL: https://infro.io/blog/what-does-one-ai-coding-agent-task-cost-a-per-task-method
Author: INFRO Editorial (https://infro.io/blog/editorial)
Publisher: INFRO
Published: 2026-11-30
Last modified: 2026-11-30
Last reviewed: 2026-11-30 (next review due 2026-12-30)
Topic: Evaluation and models
Format: Methodology

> Cost per task is the priced token spend of every request that shares a task id, retries and abandoned attempts included. Cost per merged pull request is that total divided by accepted outcomes only. Tag the task, price four token classes, record the outcome, then report median and p90.

Key takeaways:
- A task is the unit: give every agent launch a task id and send it on every model request so spend can be grouped by task, not by day or seat.
- Price four token classes separately (uncached input, cache write, cache read, output); in a long agent loop cache reads dominate the token count but not always the dollars.
- Count retries as their own lines (provider retry, agent self-retry, CI-fix loop, human re-prompt) so you can see which kind inflates cost.
- Cost per merged pull request divides all spend, abandoned attempts included, by accepted outcomes only; it is always above the mean cost per task.
- Report median and 90th percentile per task, and flag runs whose cost is partial or unpriced instead of averaging them in.

## Why the monthly bill cannot answer this

A provider invoice or a seat report says how much the team spent. It cannot say what a merged pull request cost, because the unit that matters (one task, from ticket to merge or abandonment) is not a column in any billing export. Two engineers can spend the same amount in a week, one landing nine small PRs and the other landing one after four abandoned attempts.

This method builds the missing column. It has four parts: give every agent launch a task id, meter the requests under that id, price them at your own rates, and divide by accepted outcomes. The team-level view is in [coding agent costs for teams](https://infro.io/blog/coding-agent-costs-for-teams), and the general metric is in [cost per successful task](https://infro.io/blog/cost-per-successful-task). This post covers what those do not: the loop inside one agent task, where a single prompt becomes dozens of model calls.

## Define the task and the accepted outcome first

Decide two things before you measure anything, because changing them later makes old numbers incomparable.

- **Task:** one unit of work handed to an agent, usually one ticket or one prompt that is expected to produce one branch. A human re-prompt after a failure is *inside* the same task; a new ticket is a new task.
- **Accepted outcome:** the event that makes the spend worth it. For a coding agent this is typically "pull request merged, CI green, not reverted within N days". Pick N once (seven is common) and write it down.

Everything else is bookkeeping around those two definitions. A task that ends without an accepted outcome is not excluded; its cost stays in the numerator. That is the whole point of the metric.

## What to meter per task

An agent loop reads files, calls tools, runs tests, reads the output and calls the model again. Each model call re-sends a growing context. Record these per task:

| Measure | Why it matters | Where it comes from |
| --- | --- | --- |
| Uncached input tokens | Billed at the full input rate | Provider usage on each request |
| Cache write tokens | Billed above the input rate | Provider usage |
| Cache read tokens | Most of a long loop's volume, at a small fraction of the input rate | Provider usage |
| Output tokens (including reasoning) | Highest rate per token | Provider usage |
| Model calls | Loop length; the multiplier on context re-sends | Count of requests under the task id |
| Tool calls | Time and, for server-side tools, separate charges | Agent logs or an MCP/tool gateway log |
| Retries, by kind | Spend that bought nothing | See the next section |
| Model used per call | Rates differ by model and by prompt size | Request record |
| Outcome | The divisor | Your VCS and CI |

Token classes must be kept apart. Anthropic's published API rates show why: for Sonnet 5.5 the listed rates are $2 per million input tokens, $2.50 to write cache, $0.10 to read cache and $10 for output[1]. A task that re-reads a large cached context forty times is mostly cache reads by volume, but a single uncached rewrite of that context costs far more than all the reads that follow it.

Two rate quirks matter in loops. Haiku 5.5 is listed at a higher input and output rate for prompts above 100K tokens than at or below it[1], and context grows as a loop proceeds, so a task can cross that line mid-run. Fast mode for Opus 5.5 and Fable 5.2 is listed at 2x standard pricing, and US-only inference at 1.1x[1]. Record the mode per request, or your price table will quietly be wrong.

For span-level instrumentation, OpenTelemetry has GenAI semantic conventions for model and agent spans, but its site now says they have moved to a separate repository and are no longer maintained on that page[2]. Check the current attribute names there rather than copying them from an older blog post, and add your own task id attribute alongside them.

## Separate the four kinds of retry

"Retries" hides four different costs with four different fixes. Tag each one so the task record can show which dominates.

1. **Transport retry or failover:** a request that failed before any answer and was re-sent. Usually cheap, since a failed request often bills little or nothing, but check your provider's rules for partial streams.
2. **Agent self-retry:** the agent runs the tests, they fail, it edits and runs again. This is the normal loop and the largest controllable cost.
3. **CI-fix loop:** the PR is opened, CI fails, the agent is relaunched to repair it. Same task id, new loop.
4. **Human re-prompt:** a reviewer rejects the diff and asks again. Count it in the task; it often doubles the context.

A practical rule: if the second, third and fourth kinds do not share a task id with the first attempt, your cost per merged PR will be understated by exactly the rework you wanted to see.

## Price it: the formula and a worked example

Cost per task is a sum over requests, using the rates your own provider account bills. List rates are a starting point; if you hold a negotiated rate, use it instead.

```text
task_cost = Σ over requests r in task:
    uncached_input(r) × input_rate(model(r), size(r))
  + cache_write(r)    × write_rate(model(r), size(r))
  + cache_read(r)     × read_rate(model(r), size(r))
  + output(r)         × output_rate(model(r), size(r))

cost_per_merged_pr = Σ task_cost over ALL tasks in the window
                     ÷ count(tasks with an accepted outcome)
```

> **Example: Illustrative numbers, not measurements**
> One task on Sonnet 5.5 at the list rates above[1]: 40 model calls, totalling 300,000 uncached input tokens, 150,000 cache-write tokens, 2,400,000 cache-read tokens and 60,000 output tokens.
> 
> - Uncached input: 0.3 M × $2 = $0.60
> - Cache write: 0.15 M × $2.50 = $0.375
> - Cache read: 2.4 M × $0.10 = $0.24
> - Output: 0.06 M × $10 = $0.60
> - Task cost: $1.815
> 
> Now a week of 50 tasks costing $140 in total, of which 31 ended in a merged PR. The mean cost per task is $2.80. The cost per merged PR is $140 ÷ 31 = $4.52, because 19 tasks produced nothing but still billed. The gap between those two figures is your waste ratio.

Notice that output tokens are 4% of the token volume in this example but a third of the cost. That is the usual shape, and it is why a rule such as "cheap model for exploration, strong model for the final edit" can be tested per task rather than argued about.

## Tag the task at the source

The measuring is only as good as the task id. The simplest reliable place to set it is the harness that launches the agent, not the agent itself, because the harness knows the ticket and later learns the outcome.

With a gateway in the path, the id rides as a header on every request the agent makes. INFRO groups requests that share a trace id into one run per workflow, and accepts the id as `metadata.trace_id` or the `X-INFRO-Trace-Id` header, alongside `metadata.workflow`[3]. Claude Code can be pointed at INFRO by changing the base URL and key, and extra headers can be set through `ANTHROPIC_CUSTOM_HEADERS`[4]. Because that variable is per process, a wrapper can give each task its own value:

```python
import os, subprocess, uuid, requests

BASE = "https://api.infro.io"
KEY = os.environ["INFRO_API_KEY"]  # a gateway key with its own spend limit

def run_task(ticket_id: str, prompt: str) -> str:
    trace_id = f"task_{ticket_id}_{uuid.uuid4().hex[:8]}"
    env = dict(
        os.environ,
        ANTHROPIC_BASE_URL=BASE,
        ANTHROPIC_AUTH_TOKEN=KEY,
        ANTHROPIC_CUSTOM_HEADERS=(
            f"X-INFRO-Trace-Id: {trace_id}\n"
            "X-INFRO-Workflow: coding-agent"
        ),
    )
    subprocess.run(["claude", "-p", prompt], env=env, check=False)
    return trace_id  # store it on the ticket for the CI-fix and re-prompt loops

def record_outcome(trace_id: str, merged: bool) -> None:
    requests.post(
        f"{BASE}/v1/scores",
        headers={"Authorization": f"Bearer {KEY}"},
        json={"scores": [
            {"trace_id": trace_id, "name": "merged", "value": merged},
            {"trace_id": trace_id, "name": "accepted", "value": 1 if merged else 0},
        ]},
    )
```

Reuse the same `trace_id` when the CI-fix loop or a human re-prompt relaunches the agent on that ticket. Other clients and other gateways can do the same with their own header; the requirement is only that every model request carries one stable id.

## Join cost to outcome and read the distribution

Once requests share an id and the outcome is a score on that id, the join is a query. INFRO's runs list returns one row per run with request count, error count, duration, models and estimated provider cost, and can be sorted by cost or filtered by minimum cost and by errors[3]. Scores can be posted on a run from your code, as a number, a boolean or a category[5].

```bash
# Costliest coding-agent runs in the window, with their scores
curl "https://api.infro.io/v1/runs?workflow=coding-agent&sort=costliest&limit=100" \
  -H "Authorization: Bearer $INFRO_API_KEY"

# Runs whose mean numeric score is below 1: tasks that were not accepted
curl "https://api.infro.io/v1/runs?workflow=coding-agent&score_below=1" \
  -H "Authorization: Bearer $INFRO_API_KEY"
```

The `score_below` filter works on numeric scores only and leaves out runs with none[3], which is why the example above posts a 1 or 0 `accepted` score next to the boolean. A single run window is limited to 31 days[3], so export weekly into your own warehouse if you want quarter-on-quarter trends.

From the joined table, report five figures per period and per model:

- Median cost per task and 90th-percentile cost per task.
- Acceptance rate (accepted tasks ÷ all tasks).
- Cost per merged PR (all spend ÷ accepted tasks).
- Waste ratio: spend on non-accepted tasks ÷ total spend.
- Model calls per task, median and 90th percentile.

Cost is skewed. A mean hides the handful of runaway loops; the 90th percentile exposes them, and the costliest-first list tells you which tasks to read.

## Traps that distort the number

- **Partial pricing.** A run that includes a request with no known rate is understated. INFRO's run rows carry `cost_is_partial` and `unpriced_requests` fields[3]; exclude or flag those runs rather than averaging them in.
- **Estimate versus invoice.** A per-request cost computed from usage and a rate table is an estimate. Compare it with what the provider actually billed on a schedule, and apply your contract rates where they differ from list. A persistent gap means the rate table is wrong, not that the method is.
- **Seat usage is not metered per task.** Plan seats carry usage limits rather than a per-token bill[1]. Use API-key or gateway traffic to get task figures, or run a fixed task set through an API key as a proxy.
- **Survivorship.** If only merged tasks get a task id and abandoned ones are untagged, the metric looks excellent and means nothing. Assign the id at launch.
- **Task mix.** A one-line fix and a cross-module refactor are not the same unit. Segment by size label or repository before comparing models or teams.
- **Idle loops.** Cost can accrue after a task is effectively dead. Bound steps, time and spend per task; see [bounding agent loops](https://infro.io/blog/bound-ai-agent-loops).

## Where a gateway helps, and where it does not

Everything above can be built from provider usage exports plus your own harness. A gateway shortens the join: with INFRO, requests from Claude Code or Codex pass through your own provider connections, each is logged with its model, token counts and estimated provider cost, and a run groups them by trace id[6]. A gateway key can carry its own spend limit, so a runaway task is refused before the provider is called[4]. Your provider still invoices you directly at your own rates, and INFRO's figure is an estimate that daily reconciliation compares against the provider's reported cost. INFRO sees request metadata, not whether a diff was any good; the merged-or-not outcome has to come from your VCS and CI, as in the code above.

For tracing the steps inside a task, see [tracing an agent run](https://infro.io/blog/trace-ai-agent-runs).

## A one-week rollout

- [ ] Write the task and accepted-outcome definitions, including the revert window.
- [ ] Wrap agent launches so every task gets an id at launch, not at merge.
- [ ] Reuse the id for CI-fix loops and human re-prompts on the same ticket.
- [ ] Load your contracted rates, falling back to list rates only where you have none.
- [ ] Post the outcome as a score or column when the PR merges, closes or ages out.
- [ ] Publish median, p90, acceptance rate, cost per merged PR and waste ratio, by model and repo.
- [ ] Read the ten costliest tasks each week before changing any model or limit.

## Questions

### Does a Claude Code or Codex seat price tell me the cost per task?

No. A seat is a flat monthly charge with usage limits, so it carries no per-task meter. Anthropic's Enterprise plan is listed as a seat price plus usage at API rates [1]; that usage part is what you can price per task. For seat-only users, estimate by running the same task set through an API key and use that as a proxy.

### How many tasks do I need before the number is stable?

There is no fixed threshold. Watch the median and the 90th percentile as the sample grows and stop when a week of added tasks no longer moves them. Task cost is skewed, so the 90th percentile settles slowest; a handful of runaway loops can dominate a small sample.

### Should reviewer time count toward the cost of a merged pull request?

Keep it as a separate column. Token spend is a provider-billed cost you can meter exactly; reviewer and rework time is a salary estimate. Adding them into one figure hides which lever (model choice, loop bounds, prompt quality) moved.

## Sources

1. Plans & pricing (API rates, prompt caching, fast mode, US-only inference) — Anthropic. https://claude.com/pricing (accessed 2026-11-30)
2. Generative AI semantic conventions (moved notice) — OpenTelemetry. https://opentelemetry.io/docs/specs/semconv/gen-ai/ (accessed 2026-11-30)
3. Runs — INFRO Docs. https://infro.io/docs/observability/runs (accessed 2026-11-30)
4. Claude Code & Codex — INFRO Docs. https://infro.io/docs/coding-agents (accessed 2026-11-30)
5. Scores and feedback — INFRO Docs. https://infro.io/docs/observability/scores (accessed 2026-11-30)
6. INFRO documentation overview — INFRO Docs. https://infro.io/docs (accessed 2026-11-30)
