MAESTRO

Programme Notes

Note VI · Engineering

Balancing a fleet of agents across several accounts

When several subscriptions feed one fleet, which agent should spend which account changes by the hour. A Cue pipeline that wakes every six hours, measures which agents actually burn tokens, and moves them to the account with room. Our worked example is Claude Max; the per-agent account switch works the same way for Codex.

You run a fleet of agents on more than one subscription. Maybe it is two plans with one provider, maybe three. Which agent should spend which account?

The naive answer is to split them evenly and forget about it. That works for about a week. Then one account sits at 92% of its weekly window while another sits at 0%. The agents you live in this month are not the ones you lived in last month, and nothing rebalanced. You get locked out of your main tool on a Tuesday while a third of what you pay for goes unspent.

This post is the pattern we use to fix that: one scheduled Cue pipeline that wakes every six hours, asks each account how much of its week is gone, works out which agents are actually burning tokens, and moves those agents to an account with room. Maestro supplies the parts: a per-agent environment that selects the account, usage dashboards that show each account’s quota, maestro-cli to read stats and move agents, and Cue to run it on a clock.

Our worked example is three Claude Max subscriptions running Claude Code agents. The numbers below come from that setup. Near the end we cover what changes for Codex and the other providers Maestro runs.

The setup this builds on

One agent runs as one account. The account is chosen by an environment variable on the agent, and every provider spells that variable differently. The Multiple Accounts guide covers the full setup per provider.

In our example, each Claude account gets its own config directory that holds only its credentials. Everything else in that directory symlinks back to one shared ~/.claude. Each Maestro agent carries a CLAUDE_CONFIG_DIR variable that names the account it bills to.

Standing the accounts up is the easy part. The hard part comes after: which agent belongs on which account is not a static decision. Treat it as one and you get locked out.

Balancing by headcount does nothing

The first instinct is arithmetic. Thirty-two agents on the hot account, so move sixteen.

We measured before doing that. Over seven days, of the thirty-two agents on the hot account:

  • One agent accounted for about 72% of all active time.
  • Ten agents ran at least one query.
  • Twenty-two ran zero queries.

Move sixteen agents at random and you will probably move sixteen agents that were doing nothing. The percentage does not change. You have reorganized and changed no behavior. That is the common failure of any automation that counts things instead of measuring them.

So the unit is not agents. The unit is recency-weighted active seconds. Each query’s duration gets a weight of w = 0.5 ^ (age / 12h): a twelve hour half-life over a seventy-two hour lookback. Work from an hour ago counts about sixteen times as much as work from two days ago. The operator asked for “especially the ones I’m working on,” and that decay curve is the reading of it that behaves differently from a coin flip.

The data comes from Maestro’s stats database, which records queries for every provider. Each row carries the agent’s id (session_id), its provider (agent_type), a start time, and a duration, both in milliseconds. maestro-cli stats-query runs read-only SQL against it:

maestro-cli stats-query \
  "SELECT session_id, start_time, duration FROM query_events WHERE start_time > ?" \
  --param "$(( ($(date +%s) - 72*3600) * 1000 ))" --json

Apply the weight per row, then sum per agent.

Why moving an agent costs nothing

In the Claude example, one of the shared symlinks is what makes this pattern safe:

$ ls -la ~/.claude-*/ | grep projects
projects -> ../.claude/projects
projects -> ../.claude/projects
projects -> ../.claude/projects

plugins and skills are symlinked too. There is one transcript tree on the machine and three billing identities pointed at it. An agent moved between accounts keeps its history, its resumable sessions, and its skills. Only the invoice changes.

That turns an account switch from a migration into a variable assignment. Verify it on your own setup, and note that it does not hold for every provider (see other providers below). The same fact has a sharp edge, covered next.

Two dead ends

We tried three ways to attribute load to accounts. The two failures teach more than the success.

A token usage cache. A file on disk held real per-session token counts and costs, keyed by account. It had exactly the schema we needed. On this machine, every entry resolved to one of three keys, and none of them were the accounts in question. A file can have the right schema and none of the data.

Transcript volume. Measure the bytes written under each config directory in the last week, and rank by that. We wrote the script and got numbers that were byte-identical across all three accounts.

Of course they were. One transcript tree. The symlink that makes a move free also makes per-account attribution by transcript impossible. The two properties are the same property seen from opposite ends. (The Usage Dashboard’s Tokens tab hits the same limit: accounts that share one transcript directory by symlink are counted once.)

A config directory being distinct does not mean the data under it is distinct. One ls -la would have killed the transcript approach before any code was written.

What worked was the stats database above: real query events, timestamped, per agent.

The trigger has two halves

A naive version reads each account’s percentage and reacts when it crosses a line. Reacting at 80% is reacting late. An account at 55% with two heavy agents and five days left in its window is already on track to run out. The cheapest moment to move that work is before the crossing.

So the rebalancer sheds load when either condition holds:

HalfFires whenWhy
ReactiveCurrent week % is at or above 80Already in trouble
ForwardProjected week % at reset is at or above 95On pace to blow the window

The projection needs a cost model. We did not invent a constant. The tool derives one from the accounts:

points per second = week percent consumed / active seconds this window

It takes the median across every measurable account, so one odd account cannot skew it. If no account has enough load to calibrate, the tool says so in plain language and falls back to choosing on headroom alone. A model that cannot admit it lacks data is worse than no model.

The report prints both numbers side by side. The gap between them is the signal:

account      week   proj   sess   resets in  agents active   wtd sec
acct-a        93%    93%     5%         68h       4      0         0
acct-b         9%    35%    17%        124h      57     12      8475
acct-c         1%    24%     7%        155h      17      3      7840

Account A is at 93% and staying there, because nothing on it is running. Account B is at 9% and on pace for 35%. Read only the first column and you pick the wrong account as the one under pressure.

Fig. 1 · Two numbers per account

Read only the first and you pick wrong

xychart-beta
  x-axis [acct-a, acct-b, acct-c]
  y-axis "% of weekly window" 0 --> 100
  bar [93, 9, 1]
  line [93, 35, 24]
Bars: week used now. Line: projected at reset. Account A sits at 93% with nothing running; account B is at 9% and on pace for 35%.

The first real run moved nothing, correctly

Most of the load had already been moved off the hot account by hand. Four agents remained. Three carried their own API key. The fourth ran a different provider.

The API-keyed agents bill an API, not a plan, so moving them changes nothing. The fourth reads a different provider’s account variable, so changing its Claude config directory does nothing. The tool moved zero agents and said why:

acct-a is hot (at 93%) but nothing there can move: 3 carries ANTHROPIC_API_KEY; 1 not claude-code. That percentage is already-spent burn, not future load.

Spent burn cannot be un-spent by moving agents. Making the tool say so took real effort, and it was worth it. A no-op that cannot explain itself looks the same as a broken job. A scheduled job you cannot tell from a broken one gets ignored, including on the day it actually breaks.

Two environment traps that blame the wrong component

Cue jobs run in the desktop app’s environment, which never sources your shell profile. To see what that breaks, we ran the tool under env -i with almost nothing set. It failed twice, and both error messages named the wrong component.

First trap. Neither maestro-p (the helper that reads Claude Code’s /usage panel) nor the claude binary was on PATH. The error was:

maestro-p: claude TUI exited before /usage panel could render

That reads like a rendering timeout. It is a missing file.

Second trap. With USER unset, the probe exited 1 with:

maestro-p: failed to parse /usage output

The message names the parser. The parser was fine. We bisected one variable at a time: TERM, LANG, SHELL, LOGNAME, and TMPDIR made no difference. Setting USER alone fixed it. An identity variable, reported as a parse failure. (Newer builds retry an unparsed panel before giving up, so the message now ends with the number of attempts.)

The fix is not clever. Set USER, HOME, TERM, and PATH explicitly. Call every binary by its absolute path. Never inherit anything you can state. That holds for any provider’s CLI a scheduled job calls.

Built from the CLI

The rebalancer does not reach into Maestro’s files. It calls the same CLI the interface uses, and an agent in a Maestro tab can do the same. The whole pipeline was built by asking an agent for it in a sentence: it wrote the script, registered the schedule, triggered a test run, and later edited the thresholds.

Moving an agent is one command. Pass whichever account variable the agent’s provider reads:

maestro-cli update-agent <agent-id> --env CLAUDE_CONFIG_DIR="$HOME/.claude-b" --json

The tool reads the JSON back, checks that the value landed, and never records a move it did not confirm.

Telling you goes through the same notification system as the rest of the app:

maestro-cli notify toast "Agents rebalanced" "2 agents moved from acct-b to acct-c" \
  --source-agent "Account Rebalance"

Scheduling is a Cue subscription: a time.heartbeat every 360 minutes that runs a shell command, defined in cue.yaml next to the code it runs:

subscriptions:
  - name: account-rebalance
    label: Account Rebalance
    event: time.heartbeat
    interval_minutes: 360
    action: command
    command:
      mode: shell
      shell: /usr/bin/python3 "$HOME/bin/account_rebalance.py" --apply --quiet

No daemon, and it appears in the same pipeline view as everything else. Before trusting the clock, trigger it once by hand and confirm it runs end to end:

maestro-cli cue trigger account-rebalance

Watching it comes free. The Cue Pipeline List derives a health badge for every pipeline from its recent runs: Failing when the last run failed or timed out, No recent runs when nothing has fired in the activity window. Watch the heartbeat, not the moves. This pipeline correctly does nothing on most runs, so “did it run” is the honest question to ask of it. The tool also appends every decision to a ledger, and runs as a dry run unless you pass --apply.

Why every six hours

The window being watched is one week: 168 hours. Six hours is 3.6% of it. In the worst case you learn about a problem after about one twenty-eighth of the budget has gone.

Faster buys little. Each run probes three accounts at about five seconds each, so the cost is trivial, but the decisions would not improve. Activity is measured over a 72 hour lookback with a 12 hour half-life, so the ranking barely moves inside an hour.

Slower risks the thing the pipeline exists to prevent. Miss one run and you are twelve hours behind. On a heavy day that is enough to take an account from comfortable to locked out.

Six hours also fits the two guards. Each run moves at most six agents, and a moved agent cannot move again for twelve hours. That is a deliberate two-to-one ratio: an agent moves at most once per two wakeups, however the numbers swing between them.

Other providers

The pattern is provider agnostic: measure recent work per agent, read each account’s quota, change one variable on the agent. How much of it carries over depends on whether the provider has a per-agent account switch at all. This is what the Multiple Accounts guide documents today:

ProviderAccount variableMaestro names the accountA move keeps history
Claude CodeCLAUDE_CONFIG_DIRYesYes, with symlinks
CodexCODEX_HOMEYesNo
OpenCodeXDG_DATA_HOMENoNo
Copilot CLINone: one login per machinePer home, not per loginn/a
Local modelsNone: no account, no quotan/an/a

Codex is the closest fit. Give each account its own CODEX_HOME, and Maestro attributes agents to it, shows its bars on the OpenAI Usage tab, and splits its spend on the Tokens tab. Three things change in the pipeline:

  • The variable. Pass --env CODEX_HOME=... instead of CLAUDE_CONFIG_DIR, and select Codex agents with agent_type in the stats query.
  • The quota probe. Ours reads Claude Code’s /usage panel through maestro-p. Maestro samples each Codex home’s windows for the OpenAI Usage tab, but maestro-cli does not print those readings today, so the script needs its own way to read each account’s percentage.
  • The cost of a move. Codex keeps sessions, memories, and history in SQLite databases inside each home, and those must not be symlinked between accounts. A moved Codex agent starts a fresh conversation. Moves stop being free, so a longer cooldown, or moving only agents that are between tasks, makes sense.

Codex also has an option Claude lacks: an agent can spend a reset credit when its quota runs out (maestro-cli update-agent <agent-id> --codex-auto-reset true, off by default). That reopens a window; it does not replace balancing.

OpenCode can run each agent under its own login through XDG_DATA_HOME, but Maestro shows every OpenCode agent as one profile, so neither the dashboards nor a script built on them can tell the accounts apart. Copilot CLI keeps one login per machine, so there is nothing to balance per agent. Local models have no account and no quota.

Dashboards as parked tabs

The rebalancer’s report is one of several standalone HTML dashboards that Cue jobs write on a schedule. Each is a single file with its data baked in. maestro-cli open-file <file> --background opens one as a preview tab without changing what you are looking at, and it stays parked there.

Three details make them useful:

  • Match the host theme’s intent, not its hex codes. Theme accents are tuned for syntax highlighting on a dark background. Several of them blur together as adjacent chart fills under color vision deficiency simulation. Keep each hue and move it into a lightness band that passes the check.
  • Never steal focus from a timer. A scheduled job that pulls the window forward mid-keystroke is a bug. Focus belongs to a request you made just now.
  • Turn chart animation off. Animated charts paint on animation frames, and background tabs do not fire them. An animated build renders blank canvases in exactly the tab you parked to glance at.

A dashboard that you must decide to open gets opened when something already feels wrong. A dashboard in a tab you pass a dozen times a day gets read at a glance.

What native pooling will need

The script is about 850 lines of Python with a dry run by default, an append-only ledger, and a health check on its heartbeat. It took an afternoon, and most of that afternoon was measurement. Building it produced a list of requirements that any native version has to meet:

  • Balance on measured recent work, never on agent counts.
  • Trigger forward as well as reactively, or you are always late.
  • Derive the cost model from observed data, and say so when there is not enough data.
  • Never move an agent that bills an API, runs on a remote host, or belongs to an account that is not yours to spend.
  • Treat an unreadable account as neither a source nor a destination. Unknown is not empty.
  • Guard against oscillation. Weekly windows reset at different hours and their rankings cross. Without a cooldown, an agent walks back and forth across every crossover and gains nothing.

If you run more than one account per provider across a fleet, take the pattern rather than the code. Measure recent work, trigger forward as well as reactively, guard against oscillation, and make the no-op explain itself.

Balancing keeps any one account from hitting its limit. It does not spend what the others leave behind. Once accounts are balanced, the next question is the quota still unspent before the weekly reset. Waste no tokens covers a Cue pipeline that spends it on Auto Run playbooks you forgot you had.

Tagged cue maestro-cli usage-dashboard multiple-accounts scheduling