delegate-to-opencode — run sidecar work on OpenCode or OpenRouter models
The opencode CLI reaches an active OpenCode Go ($10/mo subscription), hosted free (opencode Zen), and OpenRouter tiers. Use only hosted providers. Never invoke an ollama/* model or another local inference runtime because local inference can crash the user’s computer. That ban covers models run on the machine, and it covers every ollama/* id run through the opencode CLI. A curl call to Ollama Cloud’s API (api.ollama.com) runs the model on Ollama’s servers. This skill reads the ban’s crash-risk reason as not reaching that call (inferred; the user has not ruled on Ollama Cloud). “Ollama Cloud when Go is exhausted” below says when to use it.
Claude stays the orchestrator. It writes the prompt, runs the delegate, validates what comes back, and does the synthesis. This skill is the mechanism. The budget preference it plugs into lives in memories/delegation.md.
Why this is a shell-out and not a subagent
The Agent tool’s model parameter is an enum of Claude aliases, and .claude/agents/*.md frontmatter takes the same aliases or inherit. There is no per-agent hook for a third-party endpoint, so the only route to opencode is Bash — the same shape delegate-to-codex uses.
When this fires
- “delegate to opencode”, “use opencode”, “run this on opencode”, “use a free model”, “dto”
- Proactively, before any mechanical, bounded read/extract/reformat pass — a grep-and-summarize sweep, a bulk reformat, a first-pass triage of many files — that would otherwise spend a metered budget.
- Do not use this skill when data must not leave the machine. Keep that work in the authoring session and use deterministic tools instead of model delegation.
When NOT to delegate
- The task needs strong reasoning, judgment, or long-context synthesis — unless explicitly routed to a frontier model. Free models hosted via Zen are small, unbenchmarked ids where a wrong answer costs more to detect than the quota saved. When delegating judgment-bearing work, route explicitly to OpenRouter stealth/frontier models or capable OpenCode Go tiers.
- The critical-path edit the rest of the work waits on. Do it inline, in this session, so progress does not block on a round-trip.
- The result must conform to a schema and you have no cheap validator.
opencode runhas no schema flag, so conformance is asked for in the prompt and checked on the way back rather than enforced at the boundary. - The destination tier is unavailable or exhausted. OpenCode Go operates on dollar caps rather than request counts. As of 2026-10-15 each model has its own monthly dollar limit. Its 5-hour limit is 20% of that and its weekly limit 50% (vendor docs, https://opencode.ai/docs/go, fetched 2026-10-15). DeepSeek V4.1 Flash is $80 per month on Go and $160 on Go Plus; DeepSeek V4 Pro and Kimi K3 are $15 on Go. The vendor’s page lists the other models’ limits. Exhaustion shows as HTTP 429
GoUsageLimitErrorwithlimitNameweekly,5-hourormonthly. On 2026-10-15 every model returned the weekly error at once, so the documented per-model limits did not isolate one model’s exhaustion from another’s. The response carries no reset time. When exhausted, fall back to Codex or OpenRouter per the ladder. In a cloud session, where neither is reachable, follow “Ollama Cloud when Go is exhausted” below. Zen free tier rate-limiting is an availability state rather than window exhaustion.
The first two transfer from delegate-to-codex, but for a reason that skill does not have. There, work shape and model capability were independent. Here they point the same way: authoring and judgment work is exactly what the free tier is worst at.
Hosted-only routing rule
delegate-to-codex’s “Data sensitivity is a second trigger” section says a repo can route work to codex because of what the work reads, that this trigger overrides the shape exceptions, and that when codex is busy the work waits rather than falling back.
opencode/* (hosted Zen gateway) and opencode-go/* (OpenCode Go subscription) are hosted destinations. The payload leaves the machine exactly as it does for any other hosted model. Free or subscription-covered pricing is a billing fact and says nothing about where bytes go. OpenRouter is hosted too. Ollama Cloud (api.ollama.com) is hosted too. A data trigger therefore forbids all OpenCode, OpenRouter and Ollama Cloud model dispatch unless the consuming repository explicitly approves that hosted destination.
The discriminator is the provider prefix, not the -free suffix. opencode models on 2026-08-19 listed opencode/big-pickle alongside six ids ending in -free, all under the same hosted provider. The suffix answers a pricing question. The prefix answers which hosted tier a job goes to, which is the routing question.
That answers where bytes go, not what a given account can actually call. Measured 2026-09-04: on an account with no payment method on file, every non--free opencode/* id returned Error: No payment method. immediately, before doing any work, while an opencode/*-free id and an opencode-go/* id both ran normally. So the prefix/suffix split above is right about routing and silent about reachability — check which ids actually run (a smoke test, per the Procedure below) before picking one for real work, rather than assuming every listed opencode/* id is callable.
As in the codex skill, do not infer a data trigger from a repo merely holding sensitive data. It applies where the consuming repo has written the rule down, and that repo owns the path list.
- Do: keep data-triggered work in the authoring session and use deterministic tools when no hosted destination is approved.
- Don’t: start or invoke a model on the machine: local Ollama, LM Studio, llama.cpp, or another local runtime.
- Don’t: send data-triggered work to Ollama Cloud. Being allowed past the local-inference ban does not make it local, and the payload leaves the machine as it does for OpenCode.
- Don’t: read a
-freesuffix, or its absence, as evidence about where the payload goes.
A third destination: OpenRouter, for models neither tier carries
OpenRouter bills pay-as-you-go from a prepaid balance, so under the subscriptions-only rule in memories/delegation.md (Ezra, 2026-10-13) dispatch only to models priced 0/0, such as the stealth previews below, and never spend the balance.
opencode reaches OpenRouter as an ordinary provider, and one class of model makes that worth configuring: OpenRouter’s stealth previews — anonymized frontier models trialled under codenames, free while they last. stealth/ox-alpha (“Ox Alpha”, a reasoning model for coding and agentic work, 1,048,576-token context, pricing 0/0) was the roster’s one entry on 2026-08-23.
The provider is carried by the models.dev registry opencode resolves models from — stealth ids included — but it stays inactive until the config or the auth store references it, which is why a machine with no openrouter entry lists no openrouter/* ids at all. Any reference activates it: adding the entry below to the existing provider block of opencode.jsonc took this machine’s opencode models from zero openrouter/* ids to 360 — the full registry roster, including stealth/ox-alpha (which the registry already carried) and 359 ids the entry never named (measured 2026-08-23 on opencode 1.18.21). An empty "openrouter": {} therefore activates the same roster; a models entry earns its lines only by setting a display name, or by reaching an id the registry does not carry yet:
// Insert inside the existing "provider" object in ~/.config/opencode/opencode.jsonc
// (add a comma after the preceding sibling entry):
"openrouter": {
"models": {
"stealth/ox-alpha": { "name": "Ox Alpha (stealth, 1M context)" }
}
}
The unauthenticated smoke test failed cleanly with OpenRouter API key is missing (same measurement). Auth is the OPENROUTER_API_KEY environment variable, and the key is the user’s to enter, never the agent’s. The interactive route is broken as of 1.18.21: opencode auth login <provider> failed with Failed to load auth provider metadata ... fetch() URL is invalid for every provider tried, with or without a config entry. Measured 2026-08-23, tracked in ai-config#2058 — so have the user set the env var (setx OPENROUTER_API_KEY <key> on Windows) instead. A rejected key answers User not found, and one measured cause (2026-08-23) is a paste that doubles the sk-or-v1- prefix — the shape check that catches the paste error without exposing the value is length, 82 characters against a real key’s 73 (sk-or-v1- is 9 characters plus 64 hex, matching OpenRouter’s current key format). The current stealth roster is one query, no key needed:
curl -s https://openrouter.ai/api/v1/models \
| python3 -c "import json,sys; [print(m['id'], '|', m['name'], '| ctx:', m['context_length']) for m in json.load(sys.stdin)['data'] if m['id'].startswith('stealth/')]"Two routing consequences:
The data-sensitivity rule extends to OpenRouter and Go on the split’s own terms. A hosted destination’s payload leaves the machine, so a data trigger forbids
openrouter/*,opencode-go/*,opencode/*, and Ollama Cloud alike — and a stealth preview is the worse case, since the lab behind it is unnamed by construction.A stealth model inverts the capability caveat rather than sharing it — the consequence the split cannot supply. The hosted-free ids are unbenchmarked small models, so the “no judgment work” exception binds them. A stealth id is an unbenchmarked frontier preview, so it can plausibly carry judgment-bearing work the free tier cannot — but “plausibly” is the operative word: validate its output like any other delegate’s, and timestamp any claim about a specific id. First probe rather than a benchmark: on 2026-08-23
stealth/ox-alphascored 4/4 on a known-answer crash-diagnosis task with strict-JSON output, including a byte-level UTF-8 detail (0x9d as the tail of U+201D) — one task, so it licenses trying such work, not trusting it unvalidated.Do: activate the provider with a config entry, and route to a stealth model as
openrouter/<model-id>.Do: re-derive the stealth roster from the API on each use — the ids expire without notice.
Don’t: read an empty
openrouter/*listing as OpenRouter being unreachable — an unreferenced provider is inactive, and one config entry activates the whole roster.Don’t: send data-triggered work to
openrouter/*,opencode-go/*,opencode/*, or Ollama Cloud — free or subscription pricing is a billing fact, and bytes still leave the machine.
Cloud sessions: OpenCode Go over HTTP, keyless where the proxy holds the key
A claude.ai cloud session has no opencode CLI preinstalled (npm i -g opencode-ai installs one), but its agent proxy injects the OpenCode credential for opencode.ai, so curl to the chat endpoint works without a key (verified 2026-10-09). That holds only in an environment that allows opencode.ai and has the credential saved; on 2026-11-17 the Default environment had neither, as the note on the key below records. A GitHub Actions review job reported 401 Missing API key on the same call and no proxy variable (PR review run 37907648792, 2026-10-09), so do not assume it holds there. Use the Go endpoint https://opencode.ai/zen/go/v1, which both Go and Go Plus plans serve. Do not use the pay-as-you-go path /zen/v1, which has no funds and returns 402 (“Insufficient account funds” on 2026-11-05).
/chat/completions:glm-5.3,glm-5.3-flash,kimi-k3,deepseek-v4-pro, and others. Use this endpoint in a cloud session.qwen3.8-maxis documented under/messages, yet it returned a normal reply here on 2026-10-09, so it is usable on this endpoint./messages(claude-haiku-5-5,minimax-m3) returned 401Missing API keythrough the proxy on 2026-10-09, so it is not usable there./responsesand/modelsalso exist;/modelslists every id.Send a stable
x-opencode-sessionUUID header for each conversation, or the request fails with 400MissingSessionID.Models seen on
/modelson 2026-10-15 includedeepseek-v4.1-flash(the vendor estimates about 87,000 requests per week on Go at 410 input, 71,300 cached and 310 output tokens per request, with input at $0.15 per million tokens off-peak; a review that returns a longer answer gets fewer requests, and several smaller models list lower prices) andgemini-4-argon-contributor(the Argon model, 2x usage for a limited time). Treat/modelsas the authority, since the vendor says the list changes as models are added.cat-jam-freeandlongcat-2.5-preview-freeanswered through the proxy on 2026-10-15 while the Go quota was exhausted. On 2026-11-09 both returned “Upstream request failed: Model is unavailable”. Those two ids were free for a limited time and reasoning models (a 16-token request returned only reasoning). Give any free reasoning id a generousmax_tokens. On 2026-11-09/modelslisted the free idsbeam-free,iceman-contributor-freeandlongcat-2.5-freeinstead. On 2026-11-11 every paid Go model returned the weeklyGoUsageLimitError, and all three free ids answered a one-word probe. On PR-diff reviews that day (ai-config#5397, #5423, #5426), their record was mixed:beam-freeusually gave verdicts with quoted findings.iceman-contributor-freegave a bare verdict on one review, and a reasoned one on another whose brief asked for reasons.longcat-2.5-free’s one streamed review produced only reasoning and no answer.
Later on 2026-11-11, reviewing #5472 and #5486,
beam-freereturned empty content both streamed and not, which counts as no verdict.iceman-contributor-free, not streamed, returned a bareVERDICT: CLEANwith no reasons. One HTTP 502 from it cleared on retry. The PR comments recording those merges (#5472, #5486) relied on it only beside a reasoned Flash read and a clean Claude review.On 2026-11-12 the diff size decided whether
beam-freeanswered (gha#1944). A streamed review of the whole 611-line diff spent the 32768 reasoning-token cap and returned no verdict twice. A review of only the newest commit’s diff returned a reasoned verdict (comment). Without a system message saying the reviewer has no tools, it tried to call tools and stopped with no verdict. So send the newest commit’s diff when the whole diff is large, and say in the system message that no tools exist.On 2026-11-16 a non-streamed review of a 190-line or 360-line diff (ai-config#5716, #5717) returned
upstream request failedor timed out after 280 s, on bothdeepseek-v4.1-flashandglm-5.3. Streaming fixed it fordeepseek-v4.1-flash: send"stream": truewithcurl -N,"reasoning_effort": "low"and"max_tokens": 60000, and read the answer from the SSEdelta.contentfields. With 24000 tokens the model spent the whole budget on reasoning and stopped withfinish_reason: length. Streaming did not fix it forglm-5.3, which streams its reasoning underdelta.reasoning: on one 190-line review it was still reasoning when a 570 s--max-timeran out, so preferdeepseek-v4.1-flash.Check
/modelsfor the current free ids and try them before relying on this route.Make the request with
curlitself if it is to satisfy the merge gate.hooks/warn-merge-without-cross-harness-review.pycounts a Bash command whose command word iscurl, with a data flag (-d,--data-binary,--jsonand the like) and a literalhttps://opencode.ai/zen/go/v1/chat/completionsURL, that exits without error after the last push. It never reads the response, and it does not see a request made from a script. In a command that also runsgit push, acurlcounts only when every push in that command runs before it, at the same level: both on the top-level command line, or both inside onebash -cstring. A push in that same command at another level, such asbash -c 'git push'; curl ..., makes the review stale whichever runs first, because the hook cannot order the two. In the session that merged #5486 (author’s own observation, not recorded on the PR), the hook refused the merge after a review sent from a Python script and allowed it once the same request was sent withcurl.A review through
cat-jam-freeandlongcat-2.5-preview-freeworked on 2026-10-16, while every Go model returned the weeklyGoUsageLimitError(ai-config#4581). Stream with"stream": trueandmax_tokens30000, and assembledelta.content; the text comes only after 40,000 to 70,000 characters ofreasoning_content, about five minutes. On ai-config#4572,longcat-2.5-preview-freefound three real defects in the first push and then returned no text on the fix commit in two attempts, whilecat-jam-freereturned a clean verdict on both heads. Run both, treat an empty answer as no verdict rather than clean, and address, rebut or defer every defect in a list as for any review. The user accepted a clean verdict from one of these free models as the non-Claude gate while Go is exhausted (relayed by the coordinator session, 2026-10-16), with the other model’s empty answer counted as no verdict.The free ids change, so read them from
/modelseach time rather than reusing the names above. On 2026-11-13, with Go at its weekly limit,/modelslistedbeam-free,iceman-contributor-freeandlongcat-2.5-free, andcat-jam-freeandlongcat-2.5-preview-freereturnedUpstream request failed: Model is unavailable. All three listed ids answered the same streamed review request.longcat-2.5-freereturned no text, so it gives no verdict (ai-config#5603).In a cloud session on 2026-10-16 these other routes did not work, so use the streamed Go-endpoint recipe above instead. The free ids on the pay-as-you-go path
https://opencode.ai/zen/v1(not the Go path) returnFreeTierErrorwith the message that the free tier can only be used from within OpenCode, whereas the paid ids on that path return the 402 above. With the CLI installed bynpm i -g opencode-aiand the opencode API-key environment variable set to any non-empty value (the proxy supplies the real key),opencode run -m opencode/<free id>printed only its banner and hit a 280 to 420 second timeout. That held fordeepseek-v4.1-flash-freeandnemotron-3-ultra-free, each with the brief passed as the argument and with the brief attached by-f. A message placed after-fis read as a file name, because-ftakes several files, so put the message before-f.codexandagyare not installed in a cloud session, no OpenRouter, Databricks or Gemini key is set, andopenrouter.aiandapi.openai.comare refused by the network policy.On 2026-10-15 the Argon model was blocked by the same weekly limit as every other Go model. Route the review to
agyon a device, permemories/delegation.md, when the session can reach one. Otherwise use Ollama Cloud below.
A non-streaming call works for short prompts (such as a smoke test):
curl -s https://opencode.ai/zen/go/v1/chat/completions \
-H "Content-Type: application/json" \
-H "x-opencode-session: $(python3 -c 'import uuid; print(uuid.uuid4())')" \
-d '{"model": "glm-5.3", "messages": [{"role": "user", "content": "Reply with exactly the word: PONG"}]}'Non-streaming requests fail for review-sized or substantial prompts. Measured in a claude.ai cloud session on 2026-10-12, a non-streaming request with a ~22 KB diff failed: glm-5.3 returned HTTP 502 after about 30 seconds, and deepseek-v4-pro returned an empty body with upstream request failed (while a PONG smoke test on the same endpoint returned 200 in 1.8 seconds). The roughly 30-second gateway cutoff requires streaming for anything longer than a trivial prompt. A 2026-11-17 measurement (below) saw a non-streaming request complete after more than 120 seconds, so the cutoff is not constant, but streaming stays the default.
Always stream review-sized prompts and assemble delta.content chunks. Add "stream": true to the payload, pass a generous --max-time (e.g. 600 or 900 seconds), and pipe into scripts/parse-sse.py (or an inline Python extractor):
curl -N -s --max-time 900 https://opencode.ai/zen/go/v1/chat/completions \
-H "Content-Type: application/json" \
-H "x-opencode-session: $(python3 -c 'import uuid; print(uuid.uuid4())')" \
-d '{"model": "deepseek-v4-pro", "stream": true, "messages": [{"role": "user", "content": "Review this diff:\n..."}]}' \
| python3 skills/delegate-to-opencode/scripts/parse-sse.pyInline extractor alternative if running without the helper script:
python3 -c '
import json, sys
for line in sys.stdin:
line = line.strip()
if line.startswith("data:"):
chunk = line[5:].strip()
if chunk == "[DONE]":
break
try:
d = json.loads(chunk)
c = d.get("choices", [{}])[0].get("delta", {}).get("content", "")
if c:
sys.stdout.write(c)
sys.stdout.flush()
except json.JSONDecodeError:
pass
'Model reliability for large prompts in cloud sessions: - deepseek-v4-pro: Verified reliable on 2026-10-12 with "stream": true on review-sized prompts, returning complete reviews over several minutes. On 2026-11-17 a streamed ~25 KB prompt combining five PRs returned no delta.content (see below). - glm-5.3: Unreliable on large prompts even when streaming. In testing, it sent ~4.8 MB of deltas in 290 seconds with no delta.content before timing out, or returned upstream request failed. Prefer deepseek-v4-pro for review-sized or multi-KB prompts, but see the 2026-11-17 measurement below, where kimi-k3 succeeded more often.
From a 2026-11-17 measurement in a claude.ai cloud session, the recommendation is to send one payload per PR, one at a time, through the model fallback loop, and to retry later when every model fails. This measurement qualifies the deepseek-v4-pro preference above: on that day no model handled the combined prompt, and only kimi-k3 and deepseek-v4-pro are recorded handling a per-PR prompt, and each only some of the time. The attempts, in order:
- A streamed ~25 KB review prompt (five PRs’ diffs in one payload) returned no
delta.contentfromdeepseek-v4-pro,kimi-k3,qwen3.8-maxorglm-5.3, and a non-streamingkimi-k3retry of the same payload returned the bare bodyupstream request failed. - One PR’s payload (0.7 KB) sent alone, non-streaming, got a full
kimi-k3review after more than 120 seconds, so the roughly 30-second gateway cutoff in “Non-streaming requests fail” above did not stop it. - The other four per-PR payloads (1.6 to 12 KB), sent non-streaming in parallel, returned one review (its model was not recorded) and three empty bodies.
- Those three, re-sent one at a time through a non-streaming version of the model fallback loop below, returned two reviews (
deepseek-v4-pro, thenkimi-k3). The third failed on every model, then succeeded onkimi-k3about 20 minutes later.
No per-PR payload was sent streamed that day, so these attempts do not show which mode suits per-PR prompts better. Until that is measured, keep streaming as the first try for a per-PR payload, and fall back to a non-streaming send when the stream returns no delta.content.
Python urllib returns 403 Forbidden; always use curl. In a claude.ai cloud session (as observed on 2026-10-13), HTTP requests made via Python’s urllib (or requests) to https://opencode.ai/zen/go/v1/chat/completions fail with 403 Forbidden from the cloud agent proxy, while curl with the identical body and headers returns 200 OK. Always invoke curl in shell commands rather than Python HTTP libraries when calling the OpenCode Go API in cloud sessions.
The Default cloud environment carries a proxy-injected OpenCode Go key (since 2026-11-18). At about 04:50Z on 2026-11-18 a key was saved as a network secret for opencode.ai on Default, and a streamed curl to https://opencode.ai/zen/go/v1/chat/completions with kimi-k3 returned a full review of #5795 at 06:41Z, after that PR had merged (ai-config#5795 comment). So the keyless curl route above has run from a Default cloud session since then (as observed on 2026-11-18), and the cross-model waiver applies there only when that route fails at run time. Earlier on 2026-11-18, before the key was saved, every attempt that reached the API returned authentication_error: OpenCode Go requires an API key, and six merges between 01:05Z and 04:44Z that day ran under the waiver (#5757, #5781, #5782, #5788, #5791, #5795). Earlier still (as observed on 2026-11-17), the proxy refused opencode.ai until the user added it to Default’s allowed hosts: curl printed CONNECT tunnel failed, response 403, and the proxy’s failure note said connect_rejected.
- Do: probe with one
curltoopencode.aibefore planning a cross-model review in a cloud session, and read the “no key needed” claim as holding only where the proxy injects the credential. - Do: run the cross-model review itself through that
curlroute, on the final head, before everymwcmerge from a Default cloud session; a connectivity probe alone does not count. - Don’t: count on that claim in an environment where you have not seen the probe succeed, or apply the waiver from this section’s history alone.
Per-model 502 upstream errors and fallback loop: Both glm-5.3 and deepseek-v4-pro can intermittently return 502 upstream request failed (as observed on 2026-10-13) even on short diffs (e.g. 1 KB), while kimi-k3 answers. When dispatching a review in a cloud session, implement a fallback loop over candidate models (deepseek-v4-pro, kimi-k3, qwen3.8-max, glm-5.3) so a single model’s transient 502 does not block the review:
set -o pipefail 2>/dev/null || true
PAYLOAD_FILE=$(mktemp)
trap 'rm -f "$PAYLOAD_FILE"' EXIT
for model in deepseek-v4-pro kimi-k3 qwen3.8-max glm-5.3; do
echo "Attempting review with $model..."
# Build payload into a file to avoid Linux MAX_ARG_STRLEN (128 KiB) limits on large diffs
python3 -c "import json, sys; json.dump({'model': sys.argv[1], 'stream': True, 'messages': [{'role': 'user', 'content': 'Review this diff:\n' + sys.stdin.read()}]}, open(sys.argv[2], 'w'))" "$model" "$PAYLOAD_FILE" < diff.patch
if curl -N -s --max-time 900 https://opencode.ai/zen/go/v1/chat/completions \
-H "Content-Type: application/json" \
-H "x-opencode-session: $(python3 -c 'import uuid; print(uuid.uuid4())')" \
--data-binary "@$PAYLOAD_FILE" \
| python3 skills/delegate-to-opencode/scripts/parse-sse.py > review.txt && [ -s review.txt ]; then
break
fi
done
rm -f "$PAYLOAD_FILE"
[ -s review.txt ] || { echo "Error: all candidate models failed" >&2; false; }- Do: send
"stream": trueand assembledelta.contentchunks for review-sized prompts. - Do: run streaming requests with a generous
--max-time(e.g.--max-time 900) in the background. - Do: prefer
deepseek-v4-prooverglm-5.3for large prompts or reviews in cloud sessions. - Do: use
curlrather than Pythonurllibin cloud sessions; the cloud agent proxy returns 403 Forbidden tourllib. - Do: loop over candidate models (
deepseek-v4-pro,kimi-k3,qwen3.8-max,glm-5.3) on 502 upstream failures. - Don’t: use Python
urllibto call the OpenCode Go API in cloud sessions. - Don’t: send non-streaming requests for anything longer than a short prompt; the roughly 30-second gateway cutoff returns 502 or upstream request failure.
- Don’t: rely on
glm-5.3for large prompts; it can stream megabytes of empty deltas or fail upstream.
Measured in a claude.ai cloud session on 2026-11-12, while merging ai-config#5482: - hooks/warn-merge-without-cross-harness-review.py did not recognise an OpenCode Go review whose curl ran inside a Python wrapper script. The merge went through only after curl -sS -N --max-time 1500 https://opencode.ai/zen/go/v1/chat/completions ... --data-binary @req.json -o out.sse ran directly in a Bash call. - The same hook counts only a cross-harness review run in the merging session’s own transcript, so a Gemini Flash read that another session posted on the PR did not satisfy it. - The merge gate that requires a check-pr-fully-clean.py pass did not accept a run whose output was filtered through grep, and accepted it once the output was unpiped. - With every Go model at its weekly GoUsageLimitError, iceman-contributor-free returned a bare VERDICT: CLEAN, beam-free returned no text, and longcat-2.5-free spent all 30,000 max_tokens on reasoning with no text. Treat the bare verdict as weak evidence and the empty answers as no verdict.
- Do: run the OpenCode
curldirectly in Bash, and runcheck-pr-fully-clean.pyunpiped, before a merge. - Don’t: wrap the
curlin a script, or count another session’s posted read, as the merge hook’s cross-harness review.
Reuse one UUID across the turns of a conversation. Prefer Go models for bulk and mechanical work while Claude quota is low. The data rules above still apply: no student data (FERPA records) and no PHI to any hosted model. Review work must also meet the model-and-harness independence rule in adversarial-self-review. When posting an OpenCode review result to a PR comment under a user login (e.g. from local or Remote Control sessions), wrap the output in a standardized envelope:
## Cross-harness review (OpenCode <model>) of <HEAD_SHA>
Reviewed-Commit: <HEAD_SHA>
<verbatim review output>
### Verdict
Verdict: <Clean or Needs more work>
_Posted by <Agent Name> (AI agent) --- not written by a human._This ensures check-pr-fully-clean.py admits the review by construction and allows a clean verdict to supersede any earlier standing not-clean comments (#4425). The “by construction” claim holds only for a review with no findings section of its own (ai-config#5802). Post the full envelope from the first relay, and see the Do/Don’t pair in adversarial-self-review for the re-review a findings section requires. Never use Codex for this routing.
Ollama Cloud when Go is exhausted
Ollama Cloud is a hosted route for a cross-model review in a cloud session (ai-config#5197). Try the routes in this order:
- Smoke-test a Go model. On 2026-11-05 every Go model returned
GoUsageLimitErrorwithlimitNamemonthly. By 2026-11-09kimi-k3answered on Go again. No cause for that recovery was measured, so test Go each time rather than assume it is still capped. - Try the current free ids on the Go endpoint, as described above.
- Use
agyon a device if the session can reach one. - Use Ollama Cloud.
Each fact below was measured in a claude.ai cloud session on the date given, so re-check it before relying on it.
- The proxy injects the Ollama credential for
https://api.ollama.com/api/chat, so the request carries no key (2026-11-05). A request toollama.comitself failed at CONNECT with 403 (2026-11-05). - On this account’s free plan only
gpt-oss:120bandgemma4:31b-cloudanswered (2026-11-09)./api/tagslistsgemma4:31b, but the id that answered wasgemma4:31b-cloud. No review fromgemma4:31b-cloudis recorded here, so the quality of its reviews has not been measured.kimi-k3,glm-5.3anddeepseek-v4-pro:0813were refused as “not included in your free usage” (2026-11-09). On 2026-11-14 every model tried,gpt-oss:120bandgemma4:31b-cloudincluded, was refused with “Add usage credits or subscribe”, so the free allowance can run out too (gha#2004). Try both free-plan ids before recording Ollama as unavailable in a waiver. - Send
"stream": falseand readmessage.content. A non-streaming request with a diff of about 30 KB returned a full review on 2026-11-05. The Go gateway’s 30-second cutoff above did not apply. gpt-oss:120braised confident false positives in every first pass on Morrison-Lab/swc#11, #13 and #14 (2026-11-05 to 2026-11-09). It reported a “missing import” and an “undefined” function that were both present in unchanged context. It also said “Python 3.13 is not available on hosted runners”. Verify every finding against the code before acting on it, as for any review. For each false positive, write a rebuttal that cites the evidence you checked yourself, such as the file and line that defines the name. Then re-run with the rebuttals in the prompt and count only the re-run’s verdict. This is the same bar as persuading any reviewer with evidence, and the rebuttals must be facts you verified, not assertions. On those three PRs it accepted the rebuttals and returned CLEAN.- The reviewer differs from Claude in model and harness, so it meets the independence rule in
adversarial-self-review. The data rules apply here as to any hosted model, so use it only for work no data trigger covers. - When posting the result, use the envelope above with
(Ollama Cloud <model>)in the heading. hooks/warn-merge-without-cross-harness-review.pycounts acurlPOST tohttps://api.ollama.com/api/chatas a cross-harness review call (ai-config#4849).
Write the brief and the diff to files in the scratchpad first, and set BRIEF and DIFF to their paths. The brief must ask the model to end with one line, VERDICT: CLEAN or VERDICT: NOT_CLEAN. The loop tries each model and stops at the first reply that holds a VERDICT: line.
set -o pipefail
PAYLOAD=$(mktemp); REVIEW=$(mktemp); trap 'rm -f "$PAYLOAD"' EXIT
for model in gpt-oss:120b gemma4:31b-cloud; do
python3 -I -c 'import json, sys; m, b, d, o = sys.argv[1:5]; json.dump({"model": m, "stream": False, "messages": [{"role": "user", "content": open(b).read() + chr(10) * 2 + open(d).read()}]}, open(o, "w"))' \
"$model" "$BRIEF" "$DIFF" "$PAYLOAD" || break
curl -sS --max-time 600 https://api.ollama.com/api/chat \
-H "Content-Type: application/json" --data-binary "@$PAYLOAD" \
| python3 -I -c 'import json, sys; r = json.load(sys.stdin); c = r.get("message", {}).get("content", ""); print(c) if c.strip() else sys.exit("no content: " + str(r)[:500])' \
> "$REVIEW" && grep -q 'VERDICT:' "$REVIEW" && { echo "MODEL: $model (Ollama Cloud)" >> "$REVIEW"; break; }
: > "$REVIEW"
done
[ -s "$REVIEW" ] || { echo "Error: no Ollama Cloud verdict" >&2; false; }Any non-zero exit, an empty $REVIEW, or a reply without a VERDICT: line counts as no verdict. The trap keeps $REVIEW so you can read it; delete it once the verdict is recorded.
OpenCode 2.0
OpenCode 2.0 was first seen on 2026-10-15 (https://opencode.ai/v2/docs, https://opencode.ai/v2/docs/migrate-v1/). Nothing in this skill was measured on it. Every opencode measurement above is from 1.18.x.
- V2 reads the same config files as V1, including
~/.config/opencode/opencode.json(c),<project>/opencode.json(c)and.opencode/. Existing agent, command and skill definitions are documented to keep working. - V1 plugin implementations do not run in V2.
docs/opencode-hook-mapping.mddepends on the oh-my-openagent plugin, so a V2 session would lose the hook bridge. Either stay on V1 until that plugin has a V2 port, or move to V2 and accept that the guards then run only under Claude Code. - The V2 install commands are
curl -fsSL https://opencode.ai/v2/install | bashandnpm install -g @opencode/cli. The docs saymise use -g opencodeinstalls V1 on amiseolder than 2026.10.9. The migration guide says the V2 curl installer replaces the V1 binary, and says to remove a package-managed V1 install first. That is vendor-documented and untested here, so checkopencode --versionafter any install. V1 and V2 share the config locations, so keep a copy of the V1 config before converting it.
Where opencode sits in the budget ladder
memories/delegation.md’s “Delegate heavy work to another CLI first” section holds the order across codex, agy, opencode, and openrouter — including where OpenCode’s hosted cost tiers (free Zen, the opencode-go/* subscription, and OpenRouter’s prepaid balance) sit relative to codex and agy’s usage windows. Read it there rather than re-deriving it here.
Procedure
1. Confirm opencode is available and pick a tier
opencode --version
opencode modelsOn Windows, the OpenCode desktop app does not provide the CLI, so “installed” and “available” diverge. Measured 2026-08-23: @opencode-aidesktop was present under AppData\Local\Programs while opencode resolved in neither Git Bash nor PowerShell, and %APPDATA%\npm was absent from the User Path. How this file’s 2026-08-19 measurements ran on the same machine is unrecorded — an install surface since removed is one explanation — so treat CLI availability as a per-session check rather than a machine property. The recovery is two steps, both durable: npm install -g opencode-ai (landed 1.18.21), then add %APPDATA%\npm to the User Path if absent. A User Path edit reaches new shells only, so the session that made it still prefixes the directory onto its own PATH (or calls the binary by full path) — retrying the bare name in the same session reproduces the exact symptom the fix just cured.
- Do: treat
command not foundas an install-surface gap and run the npm install, even when the desktop app is visibly present. - Do: export the npm directory onto the current session’s
PATHafter the UserPathedit, before retrying. - Don’t: read the desktop app’s presence as the CLI being installed — they are separate artifacts with separate install routes.
opencode models prints ids as provider/model, which is the routing signal from the section above. A malformed config fails here rather than mid-run — see Troubleshooting. Smoke-test the exact hosted tier you intend to use:
opencode run -m opencode/deepseek-v4-flash-free "Reply with exactly the word: PONG"
opencode run -m opencode-go/deepseek-v4-pro "Reply with exactly the word: PONG"Measured 2026-08-19 on opencode 1.18.15, the hosted-free smoke test returned PONG in 7.9s. The OpenCode Go subscription’s activation was verified 2026-08-25; that check confirmed the subscription is active, not that the smoke test above ran — the opencode-go/* line is the recipe for that test, and its output was not observed in this session.
That gap is closed as of 2026-09-04. opencode run -m opencode-go/gpt-5.6-luna "Reply with exactly the word: PONG" returned PONG, and a subsequent real dispatch (an adversarial prose review of a small diff) to the same id completed and returned a usable verdict. So opencode-go/* is a confirmed-working route for judgment-bearing sidecar work, not only an active-subscription claim — prefer it there over a bare opencode/* id, per the reachability caveat in the section above. That result did not reproduce on another machine on 2026-10-22, where opencode models listed no opencode-go/* ids, so run opencode models before choosing the tier.
2. Prepare the prompt
As of 2026-08-19, opencode run takes the message as positional arguments, and -f/--file attaches files. Use --dir to point the run at a repo, and --variant for a provider-specific reasoning effort. Fetch anything from the network yourself and embed it in the prompt.
There is no schema flag. opencode run --help on 2026-08-19 offered --format json, which emits the raw event stream rather than a schema-constrained final message, and nothing equivalent to codex’s --output-schema. So ask for the structure in the prompt and validate it on return. Expect that validation to fail sometimes, because emitting strict JSON is one of the things small models are worst at.
Name every target file’s literal path — do not hand the delegate a glob and expect it to resolve one. Measured 2026-08-28 on opencode CLI 1.18.15 (macOS), during a Morrison-Lab/gha#682 delegated multi-file R refactor: under opencode/nemotron-3-ultra-free, the agent’s Glob tool returned zero matches for globs anchored under dot-prefixed directories — **/test-description-version.R and .github/workflows/scripts/tests/*.R both came back empty even though the files existed. The model recovered only because the brief also carried the literal file paths, which it then reached via find and a direct Read instead. A brief that described the file set only by pattern, with no literal fallback, would have had nothing to recover with.
- Do: enumerate every file the delegate must read or edit as a literal path in the brief, especially anything under
.github/or another dot-prefixed directory. - Do: treat a zero-match Glob under a dotted path as an expected gap on this model rather than a bug to debug mid-dispatch.
- Don’t: describe a target file set to an opencode delegate by glob pattern alone and assume it will resolve — a real, existing file under
.github/workflows/scripts/tests/returned no matches on this model.
3. Run it
--agent plan is now inert; the stall it was meant to work around still reproduces. Measured 2026-09-04: opencode run --agent plan -m <id> "<prompt>" prints agent "plan" is a subagent, not a primary agent. Falling back to default agent and runs the default agent anyway — the exact remedy the paragraph below once prescribed no longer selects an agent at all, and the warning is easy to miss in a tail-trimmed transcript. The underlying stall reproduced the same day on a fresh default-agent run: a ~250-word review prompt produced zero output across a 300s foreground timeout and had still written nothing when backgrounded and checked later. So treat the section below as a historical account of a workaround that stopped working, not as a live instruction — there is currently no known opencode run flag that avoids the stall, and a stalled dispatch should be killed and retried rather than trusted to eventually finish.
opencode run defaults to the build agent, which runs with tools enabled. Measured 2026-08-23 on 1.18.21 with openrouter/stealth/ox-alpha: a ~350-word diagnosis prompt (a Python traceback plus a function body, JSON-only output requested) produced zero streamed output across two default-agent runs — one killed at a 5-minute timeout, the other left running in the background and never observed to finish — while --agent plan completed the identical prompt in 36 seconds, and the default agent answered trivial and medium prompts in 13-15 seconds throughout. A candidate explanation is the prompt’s file paths inducing tool use that goes nowhere headless, but that mechanism is unconfirmed. The measurements above are what this section asserts, over the version where --agent plan still worked.
- Do: treat a silent, multi-minute
opencode runas a stall to kill and retry —--agent planno longer selects an agent as of 2026-09-04, so it is not an escape from the stall. When the stalled run passed a long prompt as a positional argument, try the 2026-10-22 prompt-in-file recipe, since a change of model alone did not help in those runs. - Don’t: rely on
--agent planto avoid the default-agent stall. It now falls back to the default agent it was meant to replace.
A recipe that returned output where long positional prompts did not, measured 2026-10-22 (Linux desktop, opencode 1.18.34). Whether this is the same default-agent stall described above is not established. A long review prompt (~6.7 KB) passed as one positional argument to opencode run -m opencode/<id> hit a 600 s timeout with 0 bytes of output, not even the > build · banner. That happened four times, on deepseek-v4.1-flash-free, nemotron-3-ultra-free and glm-5.3-flash-free, from the repo root and from a scratchpad directory, with and without file paths in the prompt. A trivial prompt (cd /tmp && opencode run -m opencode/glm-5.3-flash-free "Reply with exactly the word: PONG") returned in about 3 s. Putting the prompt in a file (7.6 KB), passing a short positional message before -f <file>, and running from /tmp completed with a full, usable review four times in a row, each within a few minutes, all on glm-5.3-flash-free:
cd /tmp && opencode run -m opencode/glm-5.3-flash-free \
"Follow the instructions at the top of the attached file and review the two diffs it contains. Do not use any tools." \
-f <prompt-file>Several things changed at once between the failing and working runs:
- the prompt moved from the positional argument into an attached file;
- the positional message became short;
- the cwd became
/tmp; - the prompt size differed (about 6.7 KB against 7.6 KB);
- every working run used
glm-5.3-flash-free, which had also stalled with a long positional prompt.
No run varied one of these alone, so which change mattered is unknown.
- Do: when a long positional prompt stalls, retry with the full recipe above (prompt in a file, short positional message before
-f <file>, cwd/tmp), since that combination is the one measured to work. - Do: write the
-f <prompt-file>attachment directly under/tmp/(for example,/tmp/opencode-review-<id>.txt), keep it at or below 20 KB (<=20 KB) onopencode/glm-5.3-flash-free, and wrapopencode runintimeout 90(ortimeout 120):opencode’s file resolver skips paths inside dot-prefixed directories (such as~/.gemini/or worktrees nested under it), andglm-5.3-flash-freestreamed 0 bytes after> build · glm-5.3-flash-freeon a 34 KB attachment while completing in ~42–55 s on 7–13 KB attachments in the same session (measured 2026-10-27 and 2026-10-28, Antigravity, ai-config#4798). - Don’t: credit any single part of the recipe with the fix, or treat the recipe as proven on models other than
glm-5.3-flash-free.
On that machine and date, opencode models listed no opencode-go/* ids, so opencode-go/deepseek-v4-pro returned “Model not found”. Step 1’s “confirmed-working” result for opencode-go/* (2026-09-04) did not reproduce there; the cause (account, configuration, or version) was not determined. The alternative delegation CLIs were also unusable there: agy returned HTTP 429 “Individual quota reached”, and gemini and cursor-agent were unauthenticated (ai-config#4688).
On the lab’s Linux workstation on 2026-11-16 (Remote Control session, opencode 1.18.34), opencode was not on the shell’s PATH. The npm global install put it at ~/.npm-global/bin/opencode, so prefix that directory onto PATH before reading command not found as no install. opencode models again listed no opencode-go/* ids, only eleven opencode/*-free ids. The recipe above, on glm-5.3-flash-free with a 19,996-byte attachment under timeout 300, returned a reasoned review of gha#2065 with a VERDICT: line. Two of its six findings were false positives, disproved by running the claimed-missing command in the image.
opencode run has no sandbox flag. opencode run --help on 2026-08-19 listed none, and permissions come from the permission block in the opencode config. --auto auto-approves everything not explicitly denied, and its own help calls it dangerous, so scope the config rather than reaching for that flag. The root opencode.json in this repo is intentionally unscoped (permission: allow for all tools, opencode.json:23-37) to avoid interactive prompts for routine gh/sh pipelines. This is the config-scoped equivalent of --auto and is documented as deliberate here. Prefer this repo-level allow over per-invocation --auto.
For a long or multi-item run, borrow the background-runner-plus-DONE-marker shape from delegate-to-codex step 3 rather than making a foreground call that the tool timeout will kill. Borrow the shape and not the body. Four things in that skill’s run_one() do not transfer, and the fourth fails silently rather than erroring:
-o <file>, which opencode has no equivalent of, so there is no per-item JSON file to write.--output-schema, which it has no equivalent of either.- stdin
-, which is not how a prompt is passed here.opencode runtook the message as positional arguments as of 2026-08-19, so a literal-becomes the prompt text. - The
bytes=0success gate, which reads the-ofile that was never written. It therefore reportsbytes=0for every item, misclassifying a run that fully succeeded as one that entirely failed.
Capture stdout and gate on the exit status instead, per step 4.
MAXPAR is the fifth, and it needs a provider-aware bound. Hosted providers enforce their own rate and concurrency limits. Start with the provider’s documented limit and reduce parallelism when responses report throttling.
A local bound sits below the provider’s. On a Linux desktop whose home directory is on NFS, on 2026-11-17 (opencode 1.18.34), three opencode run processes started together under one user left two failing at once with Error: Unexpected error and database is locked, exit 1. The third ran on. opencode keeps its session state in the SQLite file ~/.local/share/opencode/opencode.db, with -wal and -shm files beside it. There the file sat on that NFS home. So treat runs under one user’s home as serial unless measured otherwise.
- Do: run one
opencode runat a time per user, looping over models one after another. - Don’t: read
database is lockedas a model or provider failure. It is a local collision, and the same run alone is the retry.
The same day, a review prompt of about 18 KB (brief plus a whole PR diff, gha#2074) got no answer from any free model. glm-5.3-flash-free, deepseek-v4.1-flash-free, beam-free and iceman-free each ran to its timeout of 300 to 600 s with no events, even under --format json. nemotron-3.5-lightning-free ended with step_finish reason length, 32,000 reasoning tokens and no output. A 20 KB prompt for another PR had worked on glm-5.3-flash-free the day before, so size alone does not predict it. Cutting the diff to the action and its scripts (about 10 KB, tests and docs left out) got glm-5.3-flash-free to return a reasoned verdict in about 6 minutes.
- Do: when every free model stalls on a whole diff, send the core files alone and say in the review which files were left out.
- Don’t: retry the same whole-diff prompt on another free model after a timeout, or read the silence as a model failure.
4. Detect failure
With no -o capture file, key on the exit status and on empty stdout. Then check something codex’s step 4 does not have to: a small model’s usual failure is a fluent wrong answer rather than an error, so output validation matters more here than exhaustion detection does. Re-run only the items that actually failed.
5. Collect, validate, synthesize
Read the results, re-derive every count and citation, and integrate. Claude owns this step.
Troubleshooting
Every invocation fails with a config error when a model declares limit.context without limit.output. Reported 2026-08-19 in ai-config#1693: ~/.config/opencode/opencode.jsonc had gemma4:12b and granite4:7b-a1b-h each carrying limit.context alone, and every opencode call failed until both were given an output value. The schema wants the pair.
Two things make it a plausible first-run trap. The failure is total rather than scoped to the offending model, so it looks like a broken install rather than a config typo. And it fires on opencode models too, so the command you would reach for to diagnose it fails the same way.
The fix is to give every model that declares limit.context a limit.output, or to drop the limit block entirely — as of 2026-08-19 the models in that file carrying no limit at all were unaffected.
A total, immediate hosted-free-tier failure is per-model availability, not a tier-wide outage — retry the identical prompt on a different opencode/*-free id before escalating. Measured 2026-08-28 on opencode CLI 1.18.15 (macOS), during a Morrison-Lab/gha#682 delegated multi-file R refactor: opencode/deepseek-v4-flash-free failed a dispatch with UnknownError: "Unexpected server error. Check server logs for details." (carrying an err_... reference), exit 1, before doing any work — zero edits. Retrying the exact same prompt on opencode/nemotron-3-ultra-free, a different id on the same hosted-free tier, completed the task.
This is a different failure from the config error above: it happens mid-dispatch on an otherwise-working config, and the fix is a same-tier model swap rather than an edit to opencode.jsonc. This is a same-tier, cross-model retry among hosted providers.
- Do: on a total, immediate
UnknownErrorfrom oneopencode/*-freemodel, retry the identical prompt on a different free-tier model id before falling back to a metered CLI. - Do: treat a per-model server error as availability noise for that model, not as proof the hosted-free tier itself is down.
- Don’t: read one free-tier model’s
UnknownErroras exhausting the hosted-free tier — a sibling free model completed the identical prompt immediately afterward. - Don’t: use this retry rule for restricted data unless the repository explicitly approves the hosted destination.
Relationship to other skills
delegate-to-codex— the same shell-out shape aimed at a metered frontier CLI. Read its steps 2 to 5 for the background runner and DONE-marker poll rather than duplicating them here. What does not carry over is its data-sensitivity trigger, which splits into the routing rule above.select-model— picks which Claude model runs a task. This skill decides whether the task runs on Claude at all.agent-builder— an opencode model is a different model family from both Claude and codex, so it is a cheap cross-family second reader for that skill’s “paranoid reviewer” role. How much its agreement is worth is governed byself-review-fallback’s cross-vendor section.ums— record new opencode mechanics here as they are measured, since the model list and the version above will go stale.
Anti-patterns
- ❌ Sending data-triggered work to an
opencode/*,opencode-go/*, oropenrouter/*model because it is free or subscription-covered — billing facts say nothing about data leaving the machine. - ❌ Passing
--autoto widen a delegate’s permissions instead of scoping the config (repo rootopencode.jsonuses a blanket-allow config intentionally as the scoped equivalent — see above — prefer that over--autoper-run). - ❌ Quoting a count, a line number, or a citation a free model returned without re-deriving it.
- ❌ Skipping OpenCode’s hosted-free tier for small mechanical work because Codex is stronger — Codex has a window to conserve while OpenCode Zen consumes no quota.
- ❌ Handing a free hosted model the authoring or judgment task that needed Claude’s own context.