🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
ADR 508: the cost ladder feeds gateway budgets
Status: Accepted (implemented in PR #4592, 2026-10-29)
Issue: #4581 follow-up 2. Builds on: ADR-404 (the mod's cost ladder), the ruflo-cost-tracker plugin, the meta-llm gateway.
1. Context
ruflo-mods' cost ladder (costBudgetUsd, costHardStop) watches the session's live cost through session.measure. It announces the 50, 75, 90 and 100% rungs once each. At 100%, it can refuse new subagent spawns. It cannot stop the model call that pushes spend past the line, and it knows nothing about other sessions or other machines.
Gateways can enforce budgets for real. LiteLLM, for example, can be put in front of Claude Code through ANTHROPIC_BASE_URL and then:
- enforce
max_budgetover a rollingbudget_duration(24h, 7d or 30d); - stack several windows through
budget_limits; - fall back to a cheaper model when a per-model budget runs out (
model_max_budgetplusbudget_fallbacks, on virtual keys, from v1.92).
The meta-llm gateway that ruflo users run behind cognitum-* models has its own allowance tiers. A gateway sees every request. It cannot see which tool or subagent caused the spend.
2. Decision
Keep attribution in the mod. Put enforcement in the gateway, and connect the two with a file.
2.1 One budget file, read by both
.claude-flow/cost/budget.json (version 1) holds the budget:
{ "version": 1, "windows": [ { "usd": 10, "period": "24h" }, { "usd": 100, "period": "30d" } ], "hardStop": true, "fallbackModel": "haiku" }
- The mod reads it when
costBudgetUsdis 0. It uses the smallest window'susdfor the per-session ladder, and announces which window is closest to its limit. ruflo cost budget set --daily 10 --monthly 100writes the file.
2.2 Export to a gateway
ruflo cost budget export --gateway litellm prints the LiteLLM key settings for the current budget (budget_limits, model_max_budget, budget_fallbacks) as YAML or as a /key/generate JSON body. --apply --url <proxy> --key-env LITELLM_MASTER_KEY posts it.
- The master key is read from the environment variable named by
--key-env(or from auserConfigsensitive option, ADR-506). It is never taken from argv. --gateway meta-llmis accepted only once meta-llm documents a budget API. Until then it fails with a pointer to this ADR. ruflo never guesses an endpoint.
2.3 Attribution stays in the mod
The mod keeps a per-session breakdown of session.measure cost deltas, by subagent type (from agent.spawn) and by the tool that ran just before each delta. At session end it writes the breakdown to the cost-tracker's ledger, so ruflo cost report can say which agents and tools spent the money. This is the part the gateway cannot see.
2.4 When the gateway refuses
When a model call fails with a budget error, ruflo-mods toasts once: budget: the gateway refused the request (<window> spent). It records the event. It does not retry or change models itself; that is the gateway's fallback configuration.
3. Security
- No gateway credential is stored in the budget file.
--applysends only the budget fields, to the URL given, over HTTPS unless the host is loopback.
4. Verification
- Unit tests:
- budget file validation, including hostile files: negative values, unknown periods, oversized arrays;
- the ladder reads the file;
- the LiteLLM export output matches LiteLLM's documented schema field by field;
--applyrefuses plain HTTP to a non-loopback host, and a URL path that would move the request to another host.
- Attribution is tested in the mods harness with scripted
session.measureandagent.spawnevents.
5. Implementation notes
What shipped, and where it differs from the sketch above.
Option. One new ruflo-mods option,
costLedger(default on), covers the mod side: the budget-file fallback, attribution and the refusal toast. It does nothing outside a ruflo project (no.claude-flow/). With it off andcostBudgetUsdat 0 the mod hooks no cost events, as before.Budget file.
periodfollows LiteLLM'sbudget_durationgrammar (^[1-9][0-9]{0,3}[smhd]$), so24h,7dand30dpass and1mo,weekor-1ddo not. A file is rejected whole if it has more than 8 windows, ausdoutside (0, 1 000 000], a repeated period, a non-booleanhardStop, or afallbackModeloutside a plain model-name charset. A rejected file means no budget, never a zero budget. Unknown fields are dropped. The validator lives twice, inplugins/ruflo-mods/hooks/cost/file.ts(the mod may not import outside its folder) and inv3/@claude-flow/cli/src/cost/budget-file.ts.__tests__/cost-budget-gateway.test.tsruns both over the same hostile corpus and requires identical answers.Ladder. When
costBudgetUsdis 0, the ladder uses the window with the smallestusdand names it in the toast, for example(24h window). The mod sees only one session's spend, so that window is always the one nearest its limit; the longer windows are the gateway's job. The file'shardStopacts ascostHardStop. As before,session.measurereports after each turn, so the hard stop applies from the turn after the one that crossed 100%. A single long-pturn is not stopped part way through.Attribution. It is written to
.claude-flow/cost/attribution.jsonl(one line per session, newest 500 kept), not to the cost-tracker's memory namespace. The mod may not spawn the CLI, and_ledger.mjsis a read-only aggregator of provider logs. The newruflo cost reportreads this file. A subagent's tool calls are charged to the type itsagent.spawngave; an id it never saw is charged tosubagent. Names are limited to 64 per session, and the rest are charged toother.Attribution granularity (differs from §2.3). Claude Code measures cost after each main-thread turn (and on rate-limit moves), not per tool call (
session.measure, 2.1.289 types). A foreground subagent runs inside the main loop's Agent tool call, so its tool calls all complete before that turn's single measurement, and the main Agent call completes last. Charging "the tool that ran just before" each delta, as first shipped, therefore put a foreground subagent's spend onmain/Agent. Instead, each measured delta is split across every tool call completed since the previous measurement, one equal share per call. A subagent's calls are charged to its type, and the main loop's Agent/Task call that wrapped it counts as onemainshare. A delta with no tool calls in it (a plain answer) goes tomainand(model). A measurement with no cost change (a rate-limit move) keeps the pending calls for the next delta. This is an estimate by call count, not a per-request price. Exact per-request cost would needturn.step(which carriesusageandagentId) plus a price table.turn.stepis a request-rewriting event, so hooking it would widen the mod's trust surface (hooks/trust.ts) and smoke step 5's event list. That is left out.ruflo cost reportprints the estimate rule above its tables. The harness testhost order: a foreground subagent runs inside the main Agent call …drives events in the host's order: main tool, spawn, subagent tools, main Agent call, then one measurement. It fails on the last-tool rule.--applyURL (review fix). The first version built the target asnew URL(${path}key/generate, origin). A base path starting with//(or/\, which WHATWG normalises to//) then reads as a protocol-relative URL, and its first segment becomes the host.http://localhost//evil.example/went tohttp://evil.example/key/generatewith the master key. Now a path starting with//is refused. The path is set on a copy of the parsed URL, and the result must keep the given scheme and host.Refusal detection (§2.4).
turn.completecarries no API error kind, andturn.stephas no error field either. Live on Claude Code 2.1.289, a turn that dies on a LiteLLM budget error hasreason: 'error'andanswer: ''. The error text is the transcript's last message: a synthetic assistant message,API Error: 400 … ExceededTokenBudget …. So, only for a main-loop turn whose reason iserror, the mod reads that one message through$.session.messages(), and only when it starts withAPI Error. It matches LiteLLM'sbudget_exceeded,ExceededTokenBudgetand "budget has been exceeded" wording. A model's own answer is never read. No new event was needed; smoke step 5 is unchanged.Export.
budget_limitsgets one{ budget_duration, max_budget }per window.model_max_budget({ budget_limit, time_period }from the ladder window) andbudget_fallbacks({ model: [fallbackModel] }) are emitted only with--model <gateway model>. The budget file names no primary model, and ruflo does not invent a gateway model name. Field names were checked against docs.litellm.ai (/docs/proxy/users,/docs/proxy/budget_fallbacks;budget_fallbacksneeds LiteLLM v1.92.0 or later). The format option is the CLI's global--format:jsonprints the/key/generatebody, anything else prints YAML. A command-local--format yamlcollided with the global choices (text|json|table), which the live run caught.--apply. It POSTs to<url>/key/generate. The rules are:- HTTPS only, or plain HTTP to
localhost,127.0.0.1or[::1]; - no credentials, query or fragment in the URL;
redirect: 'error', so a redirect cannot leave HTTPS or loopback;- a 15 s timeout;
- only the budget fields go in the body;
- the master key comes only from the variable
--key-envnames (an upper-case variable name; a pasted key is refused).
The generated virtual key is printed masked unless
--print-keyis given. TheuserConfigsensitive-option source (ADR-506) is not wired yet.- HTTPS only, or plain HTTP to
meta-llm.
--gateway meta-llmexits 2 with a pointer to this ADR and sends nothing.Open: the budget file is project-writable. The model can edit or delete
.claude-flow/cost/budget.jsonmid-session, for example with the Edit tool. Doing so lowers the ladder and lifts the file'shardStop.costBudgetUsdandcostHardStop, which live in user settings, cannot be changed this way. No ruflo-mods guard protects.claude-flow/control files today. Whether to add a tighten-onlytool.checkdeny for writes to this file is left to the integration owner.Default on.
costLedgerdefaults totrue, by analogy withlearningLoop(ADR-502). The cost is onestatpersession.measure, one append per session, and the transcript read on error turns. Default-on versus opt-in is left to the integration owner.Command home. There was no
ruflo costCLI command; the cost-tracker plugin's/ruflo-costis a prompt command over scripts.costis a new top-level CLI command (v3/@claude-flow/cli/src/commands/cost.ts, listed inRUFLO_CLI_COMMANDS).plugins/ruflo-cost-tracker/commands/ruflo-cost.mdpoints to it.
Live validation (Claude Code 2.1.289, CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1, --plugin-dir plugins/ruflo-mods)
- Fake LiteLLM on loopback, no model spend. Every request got LiteLLM's documented
budget_exceeded400.claude -pprintedAPI Error: 400 Authentication Error, ExceededTokenBudget: …. The mod wrote{"totalUsd":0,…,"refusals":1,"budget":{"usd":10,"period":"24h"}}. - One haiku run (under the first, last-tool attribution rule, since replaced; see "Attribution granularity"). The model ran Bash, then spawned a
general-purposesubagent. The mod wrote{"totalUsd":0.196703,"byAgent":{"main":0.159246,"general-purpose":0.037457},"byTool":{"Bash":0.141942,"Agent":0.054761},…}.ruflo cost reportshowed the same split. - The CLI against the fake gateway.
cost budget set --daily 10 --monthly 100 --fallback-model haikuwrote the file.export --gateway litellm --model claude-opus-4-5printedbudget_limits,model_max_budgetandbudget_fallbacks.--apply --url http://127.0.0.1:47508 --key-env …posted onlybudget_limits, with a bearer header.--apply --url http://example.com:4000was refused before any request.--gateway meta-llmexited 2. - One haiku run after the review fix (per-call split). Same setup. The model ran
lswith Bash, then spawned ageneral-purposesubagent that used Read and Bash. The mod wrote{"totalUsd":0.264993,"byAgent":{"main":0.166775,"general-purpose":0.098219},"byTool":{"(model)":0.149061,"Bash":0.057966,"Read":0.049109,"Agent":0.008857},…}. The subagent's Read and Bash calls now carry its spend, and the wrappingAgentcall carries only one share. The(model)row shows that this run had a cost measurement with no tool call completed before it. In practice a measurement can fall inside a turn, so the split is per measurement window.