Skip to content

Latest commit

 

History

History
97 lines (69 loc) · 10.7 KB

budgets.md

File metadata and controls

97 lines (69 loc) · 10.7 KB
title Budgets and caps
description A dollar cap on a conversation, per-agent turn and spend caps, a ceiling on background subagents, and a keepalive for an idle conversation's prompt cache.
sidebar
order
9

Nothing else bounds what an opencode conversation spends through this plugin. Claude Code's own --max-turns and --max-budget-usd are per claude invocation, opencode's per-agent steps counts opencode steps (and the tools Claude runs itself never end a step, so a CLI-native tool loop is invisible to it), and background subagents fan out with no ceiling. The plugin is the one layer that sees every result the CLI reports, across respawns, accounts and the subagents a conversation starts, so the caps live here. All of them are off unless set.

{
  "provider": {
    "claude-code": {
      "options": {
        "maxBudgetUsd": 5,
        "budgetWarnAt": [50, 80],
        "maxBackgroundSubagents": 3,
        "cacheKeepalive": true,
        "defaultSubagentMaxTurns": 40,
        "defaultSubagentMaxBudgetUsd": 1
      }
    }
  }
}

A dollar cap per conversation: maxBudgetUsd

maxBudgetUsd caps one opencode conversation: its own turns plus every subagent it started, and every subagent those started. The amount is what Claude Code itself reports as total_cost_usd on each turn, which is list price: on a subscription it is a measure of how much of your usage the conversation took, not money charged.

  • Warnings. At each percentage in budgetWarnAt (default [50, 80]) the turn that crossed it ends with one ▌ **budget:** note naming what was spent and the cap. Each threshold is written once per conversation; a turn that jumps past two writes only the higher. [] turns the warnings off and keeps the stop. The turn that reaches the cap says the next message will not start.
  • The stop. Once the conversation has spent the cap, the next message ends before anything is spawned or sent to Claude, with one ▌ **budget:** note naming the amount, the cap and what to do, and finishes as an error (budget_exceeded). A turn that answers a tool call Claude is still waiting on (a foreground subagent's result, say) is never stopped, because ending it there would strand the call; the stop lands on the next new message.
  • The way out. Raise maxBudgetUsd and relaunch opencode (plugin options are read once, at startup), or start a new session.
  • Subagents. A child session's spend counts toward the conversation that started it. A child never writes a budget note, because its text can become the parent's task result; a child stopped at the cap ends with an error instead, so the parent's task result says why.
  • Compaction is exempt. A /compact turn always runs, so a summary is always possible, and its spend still counts.
  • doGenerate turns (opencode does not use them today) get the error finish and no note, since their text is a return value.

What is not kept. The ledger is in memory: an opencode restart starts every conversation again from zero. A conversation whose Claude session is resumed after a restart picks its earlier spend back up on its first turn, because Claude Code restores that session's running total; one that is replayed as text does not. /claude-code-doctor lists every conversation with recorded spend.

Per-agent caps: maxTurns and maxBudgetUsd on an agent

An agent can carry Claude Code's own two caps, passed to its claude process as --max-turns and --max-budget-usd:

---
description: Reads the codebase and reports back
mode: subagent
maxTurns: 30
maxBudgetUsd: 0.5
---

defaultSubagentMaxTurns and defaultSubagentMaxBudgetUsd in the provider options give every discovered mode: subagent agent that declares none a value, the way defaultSubagentCacheTtl does. The agent's own value wins. Both are part of the session key, so an agent with different caps gets its own process.

What the two count was measured on Claude Code 2.1.293, and they differ in the way that decides who may have them:

  • --max-turns counts API round trips per user message, not over the process's life. A process capped at 3 answered three two-call messages in a row, and a message that hit a cap of 1 ended with error_max_turns while the same process answered the next message normally. So it is safe on any agent, a long-lived main conversation included. A turn that hits it ends as an error naming the cap.
  • --max-budget-usd counts over the whole process's life, and starts again on every --resume. At $0.02 the second message ended error_max_budget_usd (that call still ran and billed) and every later message was refused at once with no API call. On a reused main conversation that would end every message once spent, and reset whenever the process did. So it is honoured for discovered mode: subagent agents only, whose dispatch gets a process of its own; a main agent declaring it is refused with one warning. Use maxBudgetUsd in the provider options for the conversation-wide cap.

Both are --print flags, so the interactive transport cannot carry them and says so once. --max-turns needs Claude Code 2.1.280 or newer; --max-budget-usd is checked against claude --help. A CLI that cannot take one gets a warning and spawns without it. A value that is not a positive number (a whole one for maxTurns) is refused with a warning.

A ceiling on background subagents: maxBackgroundSubagents

maxBackgroundSubagents caps how many background subagents run at once. A background: true task, or a task_batch with background tasks, that would put more to work than the cap allows is refused before it reaches opencode, with a tool result naming the cap and how many are running, and telling Claude to run the work in the foreground or later. A task_batch is refused whole, foreground tasks included, so a batch is never half-started. Foreground dispatch is never capped.

The running count is the one the doctor and the Background subagents running now line use: background dispatches Claude made through this opencode process, asked about with the same test task_status uses. When opencode cannot say whether one of them is still running within 2 seconds, the dispatch is refused rather than guessed, because a count that is too low is the harmful direction.

Keeping an idle conversation's cache warm: cacheKeepalive

Claude Code caches a conversation's prompt for an hour on a subscription login, and refreshes that hour every time a request reads the cache. When a conversation sits idle for longer, the next message rewrites the whole context at the cache-write price. On the maintainer's machine over 30 days that was 253 calls with a median context of 307,773 tokens, about $709 at API prices, and Claude Code does nothing about it for a headless claude (its own idle compaction runs only in its TUI).

{ "cacheKeepalive": true }

With it on, after a turn finishes the plugin sends one side_question to that conversation's live claude process at 54 minutes (0.9 of the one-hour TTL), counted from the turn's last API call. A side question reads the whole cached conversation and adds nothing to it: nothing is written to the transcript, nothing is spawned, and the next message continues exactly where the turn left off, with its cache still warm. Each ping restarts the clock, up to a cap per idle stretch: true is 2 pings (warm for up to about 2 hours 48 minutes of idle), a whole number from 1 to 4 is that many, a larger number is used as 4 with a warning, and false or unset is off.

Why 2: a ping costs about what a warm turn on the same context costs, roughly 5% of the rewrite it avoids, but a ping for a conversation you never come back to is pure cost. Replaying the 30 days above, 2 pings per stretch came out best (at most $166 saved), and more than about 6 cost more than they saved.

The keepalive never pings:

  • a process that is busy: a turn running, a proxied tool call Claude is waiting on, or a plan-mode question; the turn's own end plans the next stretch;
  • once the cache has already expired: a ping that fires late (the Mac slept through its time) and finds less than a minute left, or none, is skipped, because it would rewrite the whole context, which is the cost it exists to avoid;
  • a subagent's conversation, a /compact turn's process, or a turn with no opencode session;
  • an account the plugin knows is limited;
  • a conversation whose last call wrote a 5-minute cache (an API-key login, say): it would need a ping every four and a half minutes, and nothing measured says that pays;
  • the interactive transport, which has no control channel for a side question (its TUI has an idle compaction of its own for a large context).

A new message, the process exiting or being evicted, a deleted session, an account switch, a live model or effort switch, a respawn and a compaction each cancel the stretch; the next finished turn plans a new one. A ping needs the live process, so an idleProcessTimeoutMs shorter than the stretch ends the keepalive along with the process.

With opencode 2's own warming. opencode 2's warming setting (off unless you set it) sends its own keep-alive as a session.generate request, which the plugin already answers with the same side question (see opencode 2). Each one it answers counts as a keepalive ping and restarts the clock, so the two never ping twice. opencode's warming picks its interval from the model's settings.cache.ttl: with none it pings every 4 minutes for 30 minutes, and a declared one-hour TTL makes it refuse to warm at all, because 54 minutes is longer than its 30-minute window. The real TTL depends on the account (one hour on a subscription, five minutes on an API key by default), which is why the plugin reads it off what each call wrote instead.

What it costs and how it is counted. A side question's answer carries no usage, but Claude Code adds its cost to the session's running total, so the next turn's total_cost_usd includes every ping since the turn before. maxBudgetUsd counts it there, and that turn's turnStats footer includes it. In the 5-hour window, as far as can be measured, a ping weighs what a warm turn of the same context weighs. Each ping writes one INFO line to the plugin log (sent a cache keepalive ping, with the context's token count and never any text), and /claude-code-doctor has a Cache keepalive section: on or off, the pings sent, the pings skipped by reason, and when each conversation's next ping is due. No note is written into the conversation.

Not in this release

A gate on the account's remaining usage (stop starting turns below N% of the 5-hour window) needs the account-usage readings another change is adding, and is a follow-up.