Coding agents spend most of their tokens on mechanical work: reading files, grepping symbols, and running test suites. Keeping a heavy 5x model like GLM-5.2 on every single turn wastes both API budget and wall-clock time. Switching to a smaller operator saves money until the agent gets stuck in a retry loop or misses a cross-file edge case.
The goal of this guide is practical: test whether splitting an OpenCode V2 session into three specialized roles (a fast operator, a sub-second Clef-Flash decision gate, and an on-demand orchestrator) actually improves developer workflows on real benchmarks, or whether it just adds latency and complexity.
Where does a three-tier OpenCode loop deliver a statistically proven win, and where does a single fast model still hold its own?
We ran 130 isolated OpenCode v2.4.1 sessions on our European API across two separate benchmarks: a 30-task pre-registered sample from Aider Polyglot (Python, JavaScript, and Rust) and an 8-task multi-file calibration suite with hidden holdout tests. Below you will find the exact benchmark design, how to install the drop-in OpenCode V2 plugin, the measured results with p-values, and the three concrete rules for deciding when to use this pattern.
19-second visual walkthrough: how the three-tier OpenCode V2 loop catches drift in ~420 ms with Clef-Flash and cuts cost per solved task by 83.2% vs standalone GLM-5.2 on Aider Polyglot (N = 30).
Routine reads, edits, and test runs stay on a fast operator model. Clef-Flash checks trajectory alignment via /v1/systemone with zero output tokens and wakes the orchestrator only when the operator stalls, loops, or breaks constraints.
What we tested: two benchmarks and 130 isolated runs
Small custom benchmarks are easy to overfit, so we separated calibration from evaluation and froze the plugin code before touching public tasks. Every session ran headlessly via opencode run --standalone --archived --auto --format json on a fresh workspace copy with a 180-second timeout per task.
- Calibration suite (euroledger, N = 8, 40 runs): An 8-module EU billing, VAT, and SEPA reconciliation service with visible tests plus unseen holdout tests. We used it to test both model pairings (Qwen3.8-27B + DeepSeek V4.1 Flash and DeepSeek V4.1 Flash + GLM-5.2) and fix a gate-prompt bug before freezing the plugin.
- Public statistical benchmark (Aider Polyglot, N = 30, 90 runs): A deterministic stratified draw (seed
20261128) of 10 Python, 10 JavaScript, and 10 Rust exercises fromAider-AI/polyglot-benchmark, comparing standalonedeepseek-v4.1-flash, standaloneglm5.2, and the three-tier loop (deepseek-v4.1-flash+clef-flash+glm5.2). - Anti-cheating and paired statistics: We stripped
.meta/reference solutions and hints, activated all skippedxtestand#[ignore]tests, restored original test files before final grading (0/90 tamper attempts), and ran pre-registered exact McNemar and paired Wilcoxon signed-rank tests.
All models ran on our European inference catalog at published PAYG rates (clef-flash at $0.15/1M input and $0 output, deepseek-v4.1-flash at $0.45/$1.80, and glm5.2 at $2.30/$6.90) as well as our flat Core pool multipliers (2.0x Qwen3.8-27B, 3.0x DeepSeek V4.1 Flash, 5.0x GLM-5.2). For single-model context, see our DeepSeek V4.1 Flash evaluation and our Clef-Flash sub-second decision guide.
Sovereign AI inference, OpenAI-compatible, EU-hosted. Benchmarks, new models (Mistral, Qwen, GLM), and cost insights. One email, no spam.
Please check your inbox to confirm your subscription.
100% European infrastructure · Zero spam · Unsubscribe anytime.
How to install and use the plugin in OpenCode V2
Clone the full 160-line trajectory-guard plugin, opencode.jsonc configuration, environment template, and raw Aider Polyglot (N = 30) results with our McNemar and Wilcoxon reproduction script.
The entire supervision loop is completely transparent to the developer: you do not switch commands, manage subagents manually, or change how you prompt OpenCode. OpenCode V2 loads local server plugins directly from .opencode/plugins/ (see the official OpenCode V2 server plugin reference or our integrations hub). Drop the configuration and one ESM plugin file into your repository:

Project layout and runtime hook lifecycle for the OpenCode V2 trajectory-guard plugin. Routine turns never touch the orchestrator, and optional JSONL logging tracks every gate and steering call.
First, point opencode.jsonc at our OpenAI-compatible endpoint and pick your default operator model (the same pattern we used in our Qwen3.8-27B harness engineering guide):
{
"$schema": "https://opencode.ai/config.json",
"model": "regolo/deepseek-v4.1-flash",
"providers": {
"regolo": {
"name": "Regolo",
"package": "@opencode/ai/providers/openai-compatible",
"settings": {
"baseURL": "https://api.regolo.ai/v1",
"apiKey": "{env:REGOLO_API_KEY}"
},
"models": {
"qwen3.8-27b": { "name": "Qwen3.8-27B", "modelID": "qwen3.8-27b", "limit": { "context": 131072, "output": 16384 } },
"deepseek-v4.1-flash": { "name": "DeepSeek V4.1 Flash", "modelID": "deepseek-v4.1-flash", "limit": { "context": 131072, "output": 16384 } },
"glm5.2": { "name": "GLM-5.2", "modelID": "glm5.2", "limit": { "context": 131072, "output": 16384 } }
}
}
}
}Code language: JSON / JSON with Comments (json)
Inside .opencode/plugins/trajectory-guard/index.js, the decision gate calls our /v1/systemone endpoint instead of a chat completion. Below is the exact Clef-Flash payload excerpt that scores both the four-way trajectory state and the binary escalation probability with zero output tokens:
// Excerpt from .opencode/plugins/trajectory-guard/index.js
async function callClefFlash(apiKey, statePayload) {
const res = await fetch("https://api.regolo.ai/v1/systemone", {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({
model: "clef-flash",
state: statePayload,
questions: {
trajectory: {
type: "choice",
instructions:
"Initial exploration (1 to 3 reads or running tests once before editing) is ON_TRACK. " +
"Stalling for 4+ tool calls with 0 edits, failing tests after edits, or editing unrelated files is OFF_TRACK.",
criteria: {
on_track: "Early exploration (<=3 tool calls) or clean edits advancing the stated goal.",
drifting: "Edited the wrong file, broke a constraint, or still fails tests after editing.",
looping: "Stalled in repetitive reads (4+ tool calls with 0 edits) or repeating failed edits.",
scope_creep: "Modifies unrelated modules, tests, or public signatures outside the goal."
}
},
needs_orchestrator: {
type: "noul",
instructions:
"Answer YES if trajectory is drifting, looping (including 4+ tool calls with 0 edits), or scope_creep. Answer NO if on_track."
}
}
}),
signal: AbortSignal.timeout(8000)
});
return res.json();
}Code language: JavaScript (javascript)
Three native OpenCode V2 hooks wire the loop together without modifying persisted chat history. Setting TRAJECTORY_AGENT lets you scope the guard to a single custom agent (for example a dedicated guarded mode switched with Tab), while TRAJECTORY_GUARD_LOG writes a compact JSONL audit trail of every decision, token count, and latency:
// Excerpt: three OpenCode V2 server hooks (optional TRAJECTORY_AGENT scoping + JSONL logging)
await ctx.session.hook("prompt", (event) => {
const st = getState(event.sessionID);
if (!st.goal && event?.prompt?.text) st.goal = event.prompt.text.slice(0, 1500);
});
await ctx.tool.hook("execute.after", (event) => {
const st = getState(event.sessionID);
st.totalToolCalls += 1;
st.stepsSinceCheck += 1;
if (event.tool === "edit" || event.tool === "write") st.editsMade += 1;
if (isFailure(event) && st.editsMade > 0) st.stepsSinceCheck = CHECK_EVERY;
st.actions.push(`[${event.tool}] ${summarize(event)}`);
});
await ctx.session.hook("context", async (event) => {
if (ONLY_AGENT && event.agent !== ONLY_AGENT) return;
const st = getState(event.sessionID);
if (!st.goal || st.stepsSinceCheck < CHECK_EVERY || st.interventions >= MAX_INTERVENTIONS) return;
st.stepsSinceCheck = 0;
const decision = await callClefFlash(process.env.REGOLO_API_KEY, buildState(st));
if (decision.trajectory !== "on_track" && decision.needs_orchestrator >= THRESHOLD) {
st.interventions += 1;
const guidance = await callOrchestrator(process.env.REGOLO_API_KEY, st.goal, decision, st);
event.system[0].text += `\n\n[ORCHESTRATOR STEERING]\n${guidance}\n[END ORCHESTRATOR STEERING]`;
}
});Code language: JavaScript (javascript)
Here is a real trace from our Aider Polyglot run on py_rest-api. After the operator edited rest_api.py and hit two failing assertions, Clef-Flash flagged drifting in 412 ms, GLM-5.2 returned two concrete steering bullets, and the operator finished in 5 total steps ($0.088) instead of the 12 steps ($0.207) standalone DeepSeek spent on the same exercise:

Real OpenCode v2.4.1 trace on Aider Polyglot py_rest-api: one Clef-Flash check (412 ms) and one GLM-5.2 steering call cut the session from 12 steps ($0.207) down to 5 steps ($0.088).
Benchmark results: Aider Polyglot (N = 30) and euroledger (N = 8)
Across all 90 Aider Polyglot sessions, total API spend for the entire experiment was $17.72 ($2.93 for standalone DeepSeek, $12.04 for standalone GLM-5.2, and $2.75 for the three-tier loop). Every comparison below uses paired tests across the exact same 30 exercises.
10 Python + 10 JavaScript + 10 Rust exercises (seed 20261128), 180s timeout, .meta/ stripped, original tests restored before grading (Nov 2026)
| Metric | DeepSeek V4.1Standalone (3.0x) | GLM-5.2Standalone (5.0x) | 3-Tier LoopDeepSeek + Clef + GLM-5.2 | 3-Tier vs GLM-5.2Paired test (N=30) | 3-Tier vs DeepSeekPaired test (N=30) |
|---|---|---|---|---|---|
| Full pass ratePy / JS / Rust split | 30/30 (100%)10 / 10 / 10 | 22/30 (73.3%)6 / 7 / 9 (17 timeouts) | 30/30 (100%)10 / 10 / 10 (0 timeouts) | +26.7 ptMcNemar p = 0.0078 | +0.0 ptMcNemar p = 1.0 |
| PAYG API costTotal & $ per solved task | $2.93$0.0978 / solved | $12.04$0.5474 / solved | $2.75$0.0917 / solved | -77.2% total-83.2% $/solved (p = 2e-6) | -6.3%Wilcoxon p = 0.50 |
| Weighted Core tokens3.0x DS / 5.0x GLM-5.2 | 18.90M6.30M raw billed | 25.67M5.13M raw billed | 17.45M5.97M raw billed | -32.0%Wilcoxon p = 0.00051 | -7.6%Wilcoxon p = 0.93 |
| Median / p90 durationEnd-to-end wall clock | 25.4 sp90: 56.1 s | 180.0 sp90: 180.0 s | 26.1 sp90: 57.5 s | 6.9x fasterZero timeout cutoff | +0.7 s medianNear-zero overhead |
| Agent steps & gateTotal turns & escalations | 177 steps0 gate / 0 orch | 153 stepsCapped by timeouts | 163 steps71 gate / 3 orch (27/30 silent) | 3/3 recoveriespy_rest-api: 12 → 5 steps | -7.9% stepsWilcoxon p = 0.56 |
Cost per solved task: 83.2% lower than GLM-5.2 (p = 2e-6)
Dividing total spend by solved tasks penalizes wasted tokens on failed or timed-out runs. On Aider Polyglot, standalone GLM-5.2 cost $0.547 per solved task because every file read and test retry paid 5x rates. Moving routine execution to DeepSeek V4.1 Flash and waking GLM-5.2 only three times across 30 exercises cut cost per solved task to $0.092 (Wilcoxon p = 2e-6) and reduced weighted Core pool tokens by 32.0% (p = 0.00051).
API cost per solved task (USD, lower is better)
Total PAYG spend divided by solved tasks across 30 exercises (10 Python, 10 JS, 10 Rust; Wilcoxon p = 2e-6 vs GLM-5.2)
90 isolated OpenCode v2.4.1 runs at official Regolo PAYG rates (DeepSeek $0.45/$1.80, GLM-5.2 $2.30/$6.90, Clef-Flash $0.15/$0). 3-Tier cuts $/solved by 83.2% vs GLM-5.2. Source: live OpenCode v2.4.1 benchmark on api.regolo.ai/v1, November 2026.
Pass rate and median speed: +26.7 points and 6.9x faster than GLM-5.2
Standalone GLM-5.2 hit the 180-second ceiling on 17 of 30 exercises and failed 8 of them (22/30, 73.3%), not because the model lacked coding ability, but because burning heavy decode time on routine tool turns left too little budget to finish edits. The three-tier loop hit 30/30 across Python, JavaScript, and Rust (McNemar exact p = 0.0078 vs GLM-5.2) with a 26.1-second median duration.
Full pass rate on Aider Polyglot (30 tasks)
Higher is better: 10 Python, 10 JavaScript, and 10 Rust tasks within 180s (McNemar exact p = 0.0078 vs GLM-5.2)
Original test files restored before grading (0/90 tamper attempts). 3-Tier and DeepSeek both hit 30/30; GLM-5.2 hit 17 timeouts at 180s and finished 22/30. Source: live OpenCode v2.4.1 benchmark on api.regolo.ai/v1, November 2026.
Comparing the three-tier loop against standalone DeepSeek V4.1 Flash reveals an equally useful finding: both scored 30/30 (p = 1.0), and Clef-Flash stayed silent on 27 of 30 tasks (90% silent pass rate). Adding the guard layer cost just +0.7 seconds at the median (26.1s vs 25.4s) and finished slightly lower in raw spend ($2.75 vs $2.93, p = 0.50), meaning the safety net carries virtually zero overhead when the operator stays on track.
Median session duration per task (p50 seconds)
Lower is better: end-to-end OpenCode runtime including Clef-Flash checks (27/30 tasks ran silently with 0 orchestrator calls)
3-Tier adds only +0.7s median overhead over standalone DeepSeek (26.1s vs 25.4s, p > 0.49) while running 6.9x faster than standalone GLM-5.2 (180.0s median). Source: live OpenCode v2.4.1 benchmark on api.regolo.ai/v1, November 2026.
What happens with a smaller 2x operator (euroledger calibration, N = 8)
Because DeepSeek V4.1 Flash already hit a 100% ceiling on Aider Polyglot, our 8-task euroledger suite (with hidden holdout tests) illustrates what happens when the operator itself is a smaller 2x model like Qwen3.8-27B. Standalone Qwen3.8-27B passed all visible tests but missed a quarterly credit-note edge case in the unseen holdout (7/8). Pairing it with Clef-Flash and DeepSeek V4.1 Flash lifted holdout completion to 8/8 while cutting weighted pool tokens by 17.3% vs Qwen alone (4.46M vs 5.40M) and 50.9% vs standalone DeepSeek (9.10M).
Weighted Core pool tokens with Qwen3.8-27B operator
Lower is better: 8 multi-file euroledger tasks with hidden holdouts (Qwen3.8 2x, DeepSeek 3x, GLM-5.2 5x)
On a smaller 2x operator, 3-Tier lifted holdout pass rate from 7/8 to 8/8 while cutting weighted pool tokens by 17.3% vs Qwen alone and 50.9% vs DeepSeek alone. Source: live OpenCode v2.4.1 benchmark on api.regolo.ai/v1, November 2026.
One calibration detail from that suite is worth keeping in mind if you tune Clef-Flash yourself. In our first run, we told needs_orchestrator to answer NO whenever edits_made == 0 so early reads would not trigger false alarms. On task 3, Qwen3.8-27B stalled for 13 consecutive read calls without editing anything: Clef-Flash accurately flagged looping five times in a row, yet obeyed our literal rule and returned 0.0. Replacing that rule with an explicit threshold (1 to 3 reads is normal exploration; 4 or more calls with 0 edits is a read stall) resolved the issue completely before we froze the plugin for Aider Polyglot.
Sovereign AI inference, OpenAI-compatible, EU-hosted. Benchmarks, new models (Mistral, Qwen, GLM), and cost insights. One email, no spam.
Please check your inbox to confirm your subscription.
100% European infrastructure · Zero spam · Unsubscribe anytime.
When to use the three-tier loop (and when not to)
Taken together, our 130 runs do not claim that three models always beat one model. They point to three concrete operating rules you can apply to your own team immediately:
1. You currently run a heavy 5x model on every turn
This is where the three-tier loop delivers an unambiguous, statistically proven win (Aider Polyglot, N = 30). Offloading reads, greps, and test runs to a fast operator while reserving GLM-5.2 for rare drift events cut cost per solved task by 83.2% (p = 2e-6), reduced weighted Core tokens by 32.0% (p = 0.00051), raised pass rate by +26.7 points (p = 0.0078), and ran 6.9x faster at the median.
2. You run a compact 2x operator that occasionally drifts
If your team runs a fast 27B or local operator to stay inside a tight token budget, the three-tier loop works as a targeted accuracy recovery layer. On our euroledger holdout suite (N = 8), calling DeepSeek V4.1 Flash only on drift closed the remaining edge-case gap (7/8 to 8/8) and cut wasted retry turns from 72 down to 61, making the guarded loop both cheaper and faster than running Qwen3.8-27B alone. Because this pairing was measured on our 8-task calibration set rather than N = 30, treat the accuracy lift as directional rather than statistically confirmed.
3. You already run DeepSeek V4.1 Flash alone on medium-complexity tasks
Be realistic here: on Aider Polyglot (N = 30), the three-tier loop did not beat standalone DeepSeek V4.1 Flash on accuracy (both hit 30/30, p = 1.0) or produce a statistically significant cost drop (-6.3%, p = 0.50). The real benefit in this case is an almost free insurance policy: Clef-Flash stayed silent on 27 of 30 tasks (+0.7 seconds median overhead) and stepped in cleanly on the three sessions that wandered, recovering 3/3 and cutting py_rest-api from 12 steps down to 5.
Pick the row that matches how you run coding sessions today.
Every model in this workflow runs on our Zero Data Retention European infrastructure under transparent Regolo pricing, so source code, stack traces, and JSONL telemetry stay inside Europe without touching third-party training logs. If you want to try the loop in your own repository, drop the plugin into .opencode/plugins/trajectory-guard/, point TRAJECTORY_GUARD_LOG at a local file to inspect your real escalation rate, and keep the orchestrator on standby only for the turns that actually need it.
Sovereign AI inference, OpenAI-compatible, EU-hosted. Benchmarks, new models (Mistral, Qwen, GLM), and cost insights. One email, no spam.
Please check your inbox to confirm your subscription.
100% European infrastructure · Zero spam · Unsubscribe anytime.
Frequently asked questions
Does the three-tier OpenCode loop beat DeepSeek V4.1 Flash alone on accuracy?
Not on Aider Polyglot (N=30), where both standalone DeepSeek V4.1 Flash and the three-tier loop scored 30/30 (McNemar p = 1.0). The statistically proven gain on that benchmark is against running GLM-5.2 alone (+26.7 percentage points pass rate, p = 0.0078, and 83.2% lower cost per solved task, p = 2e-6), while adding the plugin on top of DeepSeek carried near-zero overhead (+0.7 seconds median, 27/30 silent passes).
When does the three-tier loop actually improve pass rate over a standalone operator?
It improves pass rate in two measured situations: when replacing a slow 5x model like GLM-5.2 that times out on routine tool calls (22/30 to 30/30 on Aider Polyglot), and when supervising a smaller 2x operator like Qwen3.8-27B that misses cross-file edge cases (7/8 to 8/8 on our euroledger holdout suite).
How does Clef-Flash check trajectory without slowing down every turn?
Clef-Flash runs on our /v1/systemone decision endpoint instead of /v1/chat/completions. It scores structured choice and yes/no probability questions with zero output tokens in roughly 420 ms, and the plugin only calls it every two tool calls or immediately after a post-edit test failure.
Do I have to change my OpenCode workflow or chat history to use the plugin?
No. You drop one JavaScript file into .opencode/plugins/trajectory-guard/index.js and run OpenCode normally. Steering bullets are injected into the outgoing system instructions only when drift is detected, leaving persisted chat history clean, and optional JSONL logging tracks every gate and orchestrator call.
How is this plugin different from Brick semantic routing on Regolo?
Our open-source Brick router (brick-v1-beta) selects the right model for an incoming prompt before a turn starts. The OpenCode trajectory-guard plugin supervises an active multi-step coding session: it monitors real tool results with Clef-Flash and calls an orchestrator only when the operator stalls, loops, or breaks constraints.
You have the architecture and the open-source workflow. Now give it a sovereign European inference layer built for production: fast access to GLM-5.2, Qwen3.8-27B, Qwen3.5-122B, Gemma 4, Mistral Small 4, and Brick (brick-v1-beta) with zero data retention and no new SDK to learn.
Build, test, and deploy with no infrastructure to maintain. Core plans from €11.70/mo (70% off first 3 months).
Get the full implementation, configuration scripts, evaluation benchmarks, and ready-to-run templates.
Meet engineers building with coding agents, private RAG, local LLMs, and production open-weight models.
Scaling beyond a proof of concept or running regulated EU workloads? Get a tailored architecture and commercial plan.