Running Persistent Multi-Bot Fleets (Orca + OpenCode + SOUL.md) at 70% Lower Token Spend
A practical engineering guide to orchestrating a Manager + Subordinate coding and growth fleet using open-source Orca, OpenCode CLI, plain-text SOUL.md memory, and CostLean LeanRouter—cutting per-dispatch spend from 30 to 9 LeanCredits.
- Why Naive Multi-Bot Fleets Burn Cash: Pointing multiple autonomous bots at the same working directory on flagship reasoning models causes git merge collisions, 30,000-token context re-reads, and overnight cron retry storms.
- The Golden Triangle Stack: Combining open-source Orca (isolated git worktrees + hierarchy), OpenCode CLI (@ai-sdk/openai-compatible), and CostLean LeanRouter cuts multi-step fleet dispatches by 70.0% (9 vs. 30 LeanCredits).
- Plain-Text Governance via SOUL.md and MEMORY.md: Replacing opaque vector chat histories with compact <=120-line Markdown ledgers shrinks baseline prompt noise by over 50% across sessions.
- Four Non-Negotiable Cron Circuit-Breakers: Zero-diff local pre-checks, scoped $0.50/day cron keys, max-step retry caps, and read-only branch gates eliminate unattended billing shocks.
📑 Table of Contents (5 sections)
- 1. The Three Disasters of Unmanaged Multi-Bot Fleets
- 2. Architecture: The Orca + OpenCode + LeanRouter Golden Triangle
- 3. Step-by-Step: Wiring opencode.json to CostLean LeanRouter
- 4. Designing the 1 Manager + 4 Subordinates Hierarchy & SOUL.md Contracts
- 5. Four Hard Circuit-Breakers for Unattended Cron Jobs
1. The Three Disasters of Unmanaged Multi-Bot Fleets
Running a persistent team of AI agents—one writing SEO/GEO content, one auditing backlinks, one refactoring frontend components, and one triaging cloud alerts—sounds like a superpower for lean startups and engineering squads. In practice, teams who wire four or five autonomous bots directly to flagship API keys quickly hit three expensive failure modes:
- Shared Working-Tree Collisions: Two bots edit
astro.config.mjsorpackage.jsonsimultaneously in the same directory, overwriting each other’s diffs and triggering endless lint-fix retry loops. - Unbounded Session Context Bloat: Without structured state handoffs, every subordinate bot re-ingests
25,000–60,000tokens of raw chat logs and terminal output on every turn just to figure out what happened yesterday. - Overnight Cron Bill Shocks: An unattended hourly scheduled job hits a
502 Bad Gatewayor anti-bot challenge at 2:00 AM, enters an autonomous reflection-and-retry loop on a frontier model, and burns$400before anyone wakes up.
You do not need to abandon multi-agent automation to fix this. By pairing open-source Orca (MIT-licensed desktop orchestrator), OpenCode CLI (deterministic local execution engine), and CostLean LeanRouter (tiered smart gateway), our engineering teams run 5-bot fleets daily at 70.0% lower compute spend with zero git collisions.
2. Architecture: The Orca + OpenCode + LeanRouter Golden Triangle
Each layer in this stack owns a strict engineering and financial boundary:
| Stack Layer | Component | Core Technical Responsibility | Cost & Reliability Gain |
|---|---|---|---|
| 1. Desktop Orchestration & Isolation | Orca (stablyai/orca, MIT) | Enforces Manager -> Subordinate org hierarchy, dedicated Git Worktrees per bot, plain-text SOUL.md / MEMORY.md, and scheduled triggers | Eliminates file-edit collisions; shrinks cross-session prompt context by 50%+ |
| 2. Local Execution & Pre-Filtering | OpenCode CLI (:4096 daemon / CLI) | Native @ai-sdk/openai-compatible client; runs local AST grep, regex log filtering, and build checks before calling any LLM | Local scripts filter 10,000-line logs at $0.00 token cost before sending compact summaries |
| 3. Tiered Routing & Budget Control | CostLean LeanRouter (api.costlean.com/v1) | Executes prefix/semantic caching, complexity routing (claude-sonnet-lean vs. deepseek-v3-lean), and hard TCC credit caps | Cuts blended fleet dispatch cost from 30 to 9 LeanCredits (-70.0%) |
3. Step-by-Step: Wiring opencode.json to CostLean LeanRouter
OpenCode natively reads a project-scoped ./opencode.json file (or a global path pointed to by OPENCODE_CONFIG). Instead of hardcoding a single expensive model across every task, configure three explicit routing tiers backed by your sk-lean-* gateway key from https://app.costlean.com:
{
"$schema": "https://opencode.ai/config.json",
"model": "costlean/leanrouter-auto",
"small_model": "costlean/deepseek-v3-lean",
"provider": {
"costlean": {
"npm": "@ai-sdk/openai-compatible",
"name": "CostLean LeanRouter Smart Gateway",
"options": {
"baseURL": "https://api.costlean.com/v1",
"apiKey": "{env:COSTLEAN_API_KEY}",
"headers": {
"X-CostLean-Policy": "balanced",
"X-CostLean-Client": "orca-opencode-fleet"
}
},
"models": {
"leanrouter-auto": {
"name": "LeanRouter Auto (Semantic Cache + Tiered Routing · Default -68%)",
"limit": {
"context": 128000,
"output": 8192
}
},
"deepseek-v3-lean": {
"name": "DeepSeek-V3 Lean (High-Frequency Subordinate Execution Tier)",
"limit": {
"context": 64000,
"output": 8192
}
},
"claude-sonnet-lean": {
"name": "Claude Sonnet Lean (Manager Decomposition & Final Gate Tier)",
"limit": {
"context": 200000,
"output": 8192
}
}
}
}
}
}
Never commit raw secret keys to Git: export COSTLEAN_API_KEY="sk-lean-pro-..." in your shell profile, and every OpenCode process spawned by Orca automatically inherits authenticated access—returning standard OpenAI completion payloads enriched with costlean_meta real-time savings telemetry.
4. Designing the 1 Manager + 4 Subordinates Hierarchy & SOUL.md Contracts
Inside Orca, create one top-level Chief Cost Manager (Reports to: None, bound to costlean/claude-sonnet-lean) and four specialized Subordinate Bots (Reports to: Chief Cost Manager, each isolated in its own Git Worktree and bound to deepseek-v3-lean or leanrouter-auto):
👑 Chief Manager(manager): Receives high-level objectives from the human operator, decomposes work into<= 5atomic tickets, verifies exit codes (exit 0), and merges clean branches.🔍 SEO & GEO Dripper(seo-dripper): Auditsrobots.txt/ WAF403blocks onOAI-SearchBotandPerplexityBot, mines low-difficulty keywords, and scaffolds structured MDX drafts (deepseek-v3-lean).✍️ Technical Writer(content-writer): Produces benchmark tables, anonymized case studies, and distribution threads (leanrouter-auto).🔗 Backlink Auditor(backlink-auditor): Runs logged-out HTML checks on directory listings to flagnoindextags or dead redirects (deepseek-v3-lean).💻 Frontend Builder(frontend-dev): Builds interactive calculators in an isolated worktree and validatesnpm run build(leanrouter-auto).
The secret to keeping token consumption tiny across weeks of continuous operation is replacing sprawling chat histories with a strict SOUL.md constitution and a rolling <= 120-line MEMORY.md ledger in each bot’s workspace:
# SOUL.md — Subordinate Execution Bot (Reports to: Chief Manager)
## 1. Workspace Isolation & Scope
- Operate strictly inside your assigned Git Worktree and owned file paths.
- Never modify global billing configs or sibling bot branches.
## 2. Deterministic Pre-Filtering & Token Caps
1. Local Script First: For any CSV, JSONL, or source file over 200 lines, run local grep/Python filtering first. Never dump raw multi-megabyte files into the LLM prompt.
2. Hard Execution Cap: Keep input context `<= 4,000 tokens` and `Max Tool Steps <= 6`. If the same command fails twice consecutively, halt immediately and report the exact stderr trace to Chief Manager.
## 3. Compact 4-Line Handoff Format
Reply to Chief Manager using only:
- [STATUS]: DONE or BLOCKED
- [ARTIFACTS]: Relative file paths changed
- [VERIFICATION]: Exact build/test exit code summary
- [MEMORY_DELTA]: One-sentence fact to append to MEMORY.md
When you send a single prompt to 👑 Chief Manager—for example, “Verify AI crawler HTTP 200 access on /scanner/ and publish a comparison table on AWS NAT Gateway alternatives”—only the Manager’s compact decomposition (~1,100 tokens) and final verification touch the premium tier. Ninety percent of tool execution runs on deepseek-v3-lean or hits prefix cache, dropping a full multi-bot workflow from 30 LeanCredits ($0.30) down to 9 LeanCredits ($0.09).
5. Four Hard Circuit-Breakers for Unattended Cron Jobs
Before enabling scheduled Cron triggers in Orca (or inside CostLean’s cloud workbench), enforce all four circuit-breakers below so an unattended job can never burn your monthly budget:
| Rule # | Circuit-Breaker Name | Concrete Engineering Standard | Failure Mode Eliminated |
|---|---|---|---|
| Rule 1 | Zero-Diff Local Pre-Check | Start every Cron command with a $0 shell check (git rev-parse HEAD or log SHA-256 diff). If nothing changed since the last run, exit 0 before invoking OpenCode or any LLM API. | Eliminates 95% of empty hourly “wake up and check if anything happened” token burn. |
| Rule 2 | Low-Frequency Window + Scoped Daily Key | Ban sub-hour schedules (*/5 * * * *); use off-peak daily windows (30 7 * * *) with a dedicated sk-lean-cron-* key capped at 50 LeanCredits/day ($0.50/day) returning HTTP 429 on breach. | Mathematically caps worst-case daily runaway exposure at $0.50 even if local scripts misbehave. |
| Rule 3 | Max-Steps & Zero-Retry Storm Guard | Lock Max Steps <= 5, max_tokens <= 2048, and process timeout 60s. On upstream 403 / 429 / 5xx errors, execute 0 blind retries—log status to MEMORY.md and park. | Stops exponential reflection retry storms when external sites rate-limit or go offline. |
| Rule 4 | Read-Only Unattended Mode & Morning HITL | Disable git push origin main, billing mutations, and public social posting during Cron runs. Output diffs to a staging branch for a 30-second human review each morning. | Prevents late-night model drift from breaking production or triggering platform account flags. |
Want this exact Manager + Subordinate + SOUL.md architecture without maintaining local daemons? On https://app.costlean.com, you can compile and provision a hosted /w/<slug> multi-bot workspace in 3 seconds—or export its offline Skill Pack directly into your local Orca desktop client.