amelnagdy/delegate-skillsVérifier avant exécution
SKILL DETAIL
opencode-delegate
amelnagdy/delegate-skills/opencode-delegate
>-
Installations · 106Voir la source
Installation
npx skills add https://github.com/amelnagdy/delegate-skills --skill opencode-delegate
Fichiers du skill
SKILL.md
Dernière synchronisation · 30 août 2026
references/dispatch-and-poll.md›
# Dispatch and poll
`scripts/relay.mjs` is the dispatch layer. It wraps `opencode run`, runs the brief under the chosen
agent, captures everything, and writes a structured `result.json`. Your job collapses to: run one
command, then read one file. Everything OpenCode-specific lives in the helper, which is what keeps the
loop portable across orchestrators.
## Before the first run: check the binary
Two gotchas, both worth 30 seconds:
```bash
command -v opencode # the active binary on PATH
opencode --version # the relay records this in result.json too
opencode auth list # at least one provider credential must be present
```
## Dispatching
```bash
node "<skill-dir>/scripts/relay.mjs" --brief brief.txt --model <provider/model> --cd /path/to/repo
```
(`<skill-dir>` is wherever this skill is installed — the folder containing its `SKILL.md`. On Claude
Code it's the printed "Base directory for this skill"; on other orchestrators substitute that install
path. See [`SKILL.md`](../SKILL.md) if you need to locate it.)
Options:
| Flag | Effect |
| --- | --- |
| `--brief <file>` | The brief. Omit it to read the brief from stdin (`node relay.mjs … < brief.txt`). |
| `--cd <dir>` | Working root for OpenCode (default: current directory). |
| `--lane <name>` | Fleet lane from `delegate-setup` config. Applies that lane's dials; fails if the lane's `implementer` is not this relay. Explicit dial flags win. |
| `--model <name>` | Model as `provider/model`. **Required on a fresh run** — OpenCode has no safe default (a bare `opencode run` errors); a resumed run inherits its session's model. |
| `--agent <name>` | OpenCode agent (default: `build`, write-capable). |
| `--read-only` | Shortcut for `--agent plan` — review/diagnosis with no edits. |
| `--variant <name>` | Provider reasoning effort (e.g. `high`, `max`, `minimal`). |
| `--no-auto` | The relay passes `opencode`'s `--auto` (auto-approve permissions) **by default** so a headless run doesn't hang on a prompt; `--no-auto` drops it and honors the agent's own permission config instead. A `--read-only`/`plan` run never gets `--auto`, so it can't be auto-approved into edits. |
| `--resume-last` | Continue the most recent OpenCode session; send only the delta brief (see review-and-land). |
| `--session <id>` | Continue a specific session id (`ses_…`); send only the delta brief. |
| `--pure` | Run OpenCode without external plugins (cleaner event stream). |
| `--timeout <dur>` | Relay-side watchdog (e.g. `30m`, `2h`); on expiry the child is killed and `result.json` gets `status: "timeout"`. Off by default. |
| `--out-dir <dir>` | Where artifacts go (default: a fresh dir under the system temp dir). |
Artifacts default to the system temp dir on purpose: the repo under review stays clean, so the
touched-files report shows only OpenCode's edits and nothing of the helper's own.
## The result
`<out-dir>/result.json` is the contract. Fields:
- `schema` — the result-format version (currently `delegate-relay.result.v1`)
- `tool` — `opencode`
- `status` — `completed` | `failed` | `timeout` | `aborted` | `opencode_unavailable`
- `exitCode` — mirrors OpenCode's exit code; `128` plus the signal number if the child was killed; `127` if `opencode` isn't on PATH; on a `timeout` the relay forces a non-zero code even when the child exited `0` after the watchdog's SIGTERM
- `signal` — the signal that killed the child, otherwise `null`
- `opencodeVersion` — the binary that actually ran
- `agent` — the agent selected for this dispatch (`build`, `plan`, …)
- `sessionId` — feed this to a later `--session <id>` (or use `--resume-last`)
- `finalMessage` — OpenCode's assembled final text (the `<structured_output_contract>` you asked for).
Empty if OpenCode stopped without emitting a closing summary — ask for the report explicitly
- `touchedFiles` — `git status --porcelain` lines in the working root: your review starting point.
`null` (not `[]`) when git can't report — `git` missing, or a non-repo run; `[]` means git ran and
the tree is clean
- `cost` — total run cost in USD, summed from the step events (`null` if none were reported)
- `briefPath` / `eventsPath` / `finalPath` — the exact brief relay sent, the raw JSON event stream, and
the final-message file
- `workdir`, `model`, `auto`, `resumed`, `resumeLast`, `startedAt`, `finishedAt`
- `stderrTail` — last ~20 stderr lines; present on every run that did not complete (`failed`, `timeout`, `aborted`), absent on `completed`,
`opencode_unavailable`, and launch failures
- `error` — present on a launch failure, and on `timeout` and `aborted` runs
The helper also prints a summary to stdout and exits with OpenCode's exit code, so a wrapping script can
branch on success/failure directly.
## Waiting for completion
The helper blocks until OpenCode finishes. Back it with whatever your orchestrator offers:
- **Claude Code:** run the `Bash` call with `run_in_background: true`; you're notified on completion,
then read `result.json`.
- **Plain shell / other agents:** foreground for short tasks, or background and poll — `node relay.mjs
… &` in bash/zsh (including Git Bash/WSL), or your shell's equivalent (`Start-Job` in PowerShell,
`start /b` in cmd). A run is done when `result.json` exists with a `status`. **But** a pre-run usage
error (bad args, empty brief) exits with code 2 *before* writing any file — so check the exit code
too, don't only watch for the file. (A missing `opencode` binary exits 127 but *does* write a
`result.json` with status `opencode_unavailable`.)
Trust the working tree and the process state over any progress display. A run is finished when the
process has exited and `result.json` is written — not when a status line says so.
## When a run misbehaves
- **`status: opencode_unavailable` (exit 127):** `opencode` isn't on PATH or isn't found. Install
(`npm i -g opencode-ai`) and `opencode auth login`, then re-dispatch.
- **an `error` mentioning `version preflight` (`failed`, or `timeout` at exit 124):** the bounded
`opencode --version` probe exited non-zero or hung past its cap (10s, or `--timeout` when shorter),
so opencode was never dispatched; only the relay's own artifacts may already exist under
`--out-dir`. Check the install by running `opencode --version` yourself.
- **`status: failed`:** read `result.json`'s `stderrTail` and the tail of `eventsPath` for the cause.
Common causes: an auth lapse, an unknown `--model` or `--agent`, or a permission the run needed but
the agent didn't grant. Fix the cause and re-dispatch; don't paper over it by doing the work yourself
unless that's what the user wants.
- **`status: timeout`:** the `--timeout` watchdog killed the run. The working tree may hold a
half-applied change — inspect it before deciding between a longer `--timeout`, a smaller brief,
or a resume.
- **`status: aborted`:** the relay itself was killed (its parent's timeout, a stopped task, a
closed terminal) and forwarded the kill to opencode. The result is written before the relay exits;
inspect the working tree before re-dispatching. On native Windows a hard kill of the relay is
uncatchable (Node supports no `SIGTERM` handler there), so this status may never get written -
a relay process that is gone without a `result.json` is an aborted run; inspect the working
tree and `events.jsonl` directly.
- **`status: failed` with `signal: "SIGKILL"`:** the host ended the child — commonly the OOM killer
or a supervisor timeout, not an implementer error. Free up host memory or split the task into
smaller briefs, then re-dispatch.
- **Empty `finalMessage`:** OpenCode finished without emitting a closing text summary (common when it
completes purely through tool calls). The edits may still be correct — check `touchedFiles` and the
diff. To get a report next time, add a `<structured_output_contract>` block (see
[writing-the-brief.md](writing-the-brief.md)).
- **A run hangs:** an agent with an `ask` permission can block waiting for approval that never comes in
headless mode. Runs pass `--auto` by default precisely to avoid this — so a hang almost always means
you passed `--no-auto`. Either drop it, or set the agent's permissions to *allow* (not ask) the
actions the task needs.
## Recovering lost work
`events.jsonl` in the run directory records every event the implementer streamed. If finished
work is lost — the run killed late, or the working tree damaged afterward — read the event log
before re-dispatching: it identifies which files and tool commands were involved, which scopes
what needs redoing. Whether it also carries the edit contents depends on what the CLI streams,
so treat any reconstruction as unverified until it matches a working-tree diff — when the tree
still holds the work, preserve the tree rather than replaying the log.
## What the helper is doing (and the alternatives)
Under the hood the helper runs roughly:
```bash
opencode run --format json --agent build -m provider/model < brief.txt # fresh run (model required)
opencode run --format json --continue --agent build < delta-brief.txt # resume most recent (inherits model)
opencode run --format json --session ses_… --agent build < delta-brief.txt # resume a specific session
```
The brief is fed on **stdin**, never as an argument — which is why a multi-line, XML-tagged brief needs
no quoting. The `--format json` stream is newline-delimited JSON events; the relay assembles
`finalMessage` from the `text` events and pulls `sessionId` from the event stream. OpenCode selects an
agent for each prompt, so the helper passes the requested agent on fresh and resumed runs.
If you ever want it, raw `opencode run` is fine for one-offs — you just give up the captured
`result.json`, touched-files summary, and session-id extraction the helper does for you.
## The commit boundary
The helper never commits — by design, not omission. The robust contract is: OpenCode edits the working
tree, the orchestrator reviews and commits. See [review-and-land.md](review-and-land.md).
references/multi-task-queues.md›
# Multi-task queues
The single-task loop scales to a queue, and that's where delegation pays off most — a removal split
across layers, a migration touching many files, a refactor sweep. The discipline that makes a queue
trustworthy is sequencing and bookkeeping, not parallelism.
## Run sequentially, one commit per task
Resist the urge to fan out the whole queue at once. Run tasks **one at a time, in dependency order**,
landing each (review + gates + commit) before dispatching the next. Three reasons:
- **Later tasks assume earlier ones landed.** Task 3's brief can say "the X added in the previous step
exists" only if the previous step actually committed.
- **One commit per task** keeps the history reviewable and any single step revertible.
- **Each review is honest.** A clean working tree before each dispatch means the next task's
`touchedFiles` shows only *its* changes, not a pile-up from earlier tasks.
Parallelism is occasionally worth it for genuinely independent tasks on separate files, but it
sacrifices the clean-tree-per-task property and makes review harder. Default to sequential. (Each fresh
`relay.mjs` dispatch starts a new OpenCode session, so independent tasks don't share context — fold any
shared constraint into each brief, see below.)
## Carry decided constraints forward
Implementation surfaces facts the original plan didn't have: a helper got named, a fixture lives in a
specific place, an interface was chosen. When a later task depends on one of those, **fold it into that
task's brief** as an explicit line. A fresh OpenCode session has no memory of the earlier run, so a
constraint that emerged in task 2 must be restated in task 5's brief or it won't hold. This is the queue
equivalent of keeping briefs self-contained.
## Keep a progress file
For anything longer than two or three tasks — especially a run the human steps away from — maintain a
single progress file alongside the work. It's the durable record that survives your own context limits
and lets the human catch up at a glance. A shape that works:
- **Status table** — each task: queued / at-implementer / reviewed+committed (with the commit hash).
- **Per-task review notes** — what landed, what you verified, the gate outcome. One short paragraph.
- **"Needs your eyes"** — design decisions OpenCode made, non-blocking nitpicks, anything you want the
human to overrule or confirm. This is the section they read first.
- **End-of-run checklist** — what happens after the last task (push, open/update the PR, manual checks
the human should do).
Update it as each task lands, not in a batch at the end — if the run is interrupted, the file is still
accurate.
## Close with a coherence check
Per-task review proves each step in isolation; it doesn't prove the steps cohere. After the last task,
verify the whole:
- Run the full test/build once more on the final tree — not just the last task's slice.
- Do a repo-wide check for the thing the queue was about (e.g. after a removal, grep the entire tree
for any surviving reference; after a rename, confirm no stragglers).
- For schema work, replay all the new migrations from a clean state and check for drift.
- Then push and open or update the PR, with a description that reflects what actually shipped.
## When to stop and ask
Proceed without asking on anything that follows from the agreed plan — that's the point of the human
opting into the queue. Stop and surface when:
- A task can't be completed correctly within its brief's scope (a scope change is the human's call).
- A review finds something that calls the *plan* into question, not just the implementation.
- The gates reveal a problem that affects tasks already "done."
Then report where you are, what's committed, and what the open question is — and wait. A queue that
quietly works around a broken assumption produces a lot of commits in the wrong direction.
references/review-and-land.md›
# Review and land
OpenCode did the typing; you own the judgment. This is where delegation earns its keep or quietly ships
a mistake. The discipline is simple to state and easy to skip under time pressure: **verify against
reality, never against the self-report — and read the diff as generated code, which fails in ways a
green gate can't see.**
## Check the tests before trusting the gates
If the diff touches existing tests, review those edits *first* — before the gate re-run means anything.
A weakened assertion, an added skip, or a deleted test makes the gate measure less than it did before
the run; green is only meaningful if the yardstick wasn't shortened.
- **Unbriefed edits to existing tests are a contract change, not part of the fix.** The brief asked for
an implementation; nothing in it authorized moving the goalposts. Flag them, don't absorb them.
- **Skipped, disabled, or commented-out tests added in this diff:** treat the underlying test as failing
until proven otherwise, whatever the annotation's comment claims.
- **Loosened assertions** (exact match relaxed to contains/truthy, error-type checks broadened, tolerance
widened): same treatment.
## Re-run the gates yourself
`result.json` carries OpenCode's own claim that the gates passed. Treat that as a claim, not evidence —
re-run the project's actual test/lint/build commands in the working tree and read the output. And keep
the result in proportion: **passing is necessary, not sufficient.** An implementer can *game* a gate,
not just misreport it — that is what the test check above and the sweep below exist to catch.
For changes with their own verification shape, go further:
- **Migrations / schema:** round-trip them (apply, reverse, re-apply on a scratch target) and check for
drift, rather than trusting that "the migration is reversible."
- **Removals / renames:** grep the codebase for dangling references to whatever was removed.
- **Anything stateful:** exercise the actual behavior, don't just confirm it compiles.
## Read the diff against the brief
Open the diff (`touchedFiles` in the result is your starting list) and hold it against what you asked
for:
- **Scope creep** — did OpenCode change things the brief said to leave untouched? Unasked refactors,
renames, "while I was here" edits. These are the most common quality problem in delegated work.
- **Scope shortfall** — did it do the whole task, including the edge cases and cleanup, or stop at the
first plausible version?
- **Quiet judgment calls** — sometimes OpenCode makes a defensible decision the brief didn't anticipate.
Don't just accept it because it looks reasonable; understand it and decide.
## The implementer sweep
Generated code fails in systematic ways that gates are structurally blind to — each of these can sit in
a diff whose tests are all green. Walk them against every diff before you commit:
- **Hardcoded success or fixture data** on a path the brief says does real work — a canned
`{status: "ok"}` or default return passes tests *by design*. If OpenCode couldn't implement something,
the diff should fail loudly, not pretend.
- **Catch-all error handling that returns a default** instead of propagating — the suppressed failure is
exactly what the gate would have caught. A broad catch is only acceptable with a recovery path the
contract documents.
- **Unverified imports and API calls** — confirm every new dependency, method, and signature exists in
the *installed* version (read the lockfile or the package, don't trust plausibility).
- **Dead weight** — unused imports, helpers nothing calls, unreachable branches, "Step 1/Step 2"
comment scaffolding, comments that restate the line below them.
- **A second way to do what the file already does** — a new HTTP client, error idiom, or logging style
introduced beside the existing one instead of reusing it.
- **New tests that assert internals** — asserting that an internal helper was called, or mocking the
project's own functions to isolate a "unit." Green, brittle, and worthless as regression cover.
- **Near-duplicate test bodies** differing by one value — fold into one data-driven test or drop the
copies; bloat reads as coverage but isn't.
- **Speculative surface** — optional parameters, config flags, or abstractions with no caller in this
diff or the repo. Delegated work gets the concrete behavior the brief asked for, nothing extra.
- **Guards for impossible cases** — null/type checks for values the code's own contract already
excludes. Noise that buries the validation that matters at real trust boundaries.
Anything the sweep catches goes back to OpenCode as a delta brief (below) or gets fixed in the tree
before commit — and either way is reported to the user (see "Surface, don't absorb").
If the `guard-skills` package is installed, run the relevant guard on the diff for the full treatment —
`clean-code-guard` on production code, `test-guard` on tests, `docs-guard` on documentation. The sweep
above is the built-in floor; the guards go deeper.
## The commit boundary
When the gates pass and the diff holds, **you commit** — the orchestrator, never the implementer. The
`build` agent *can* write the working tree, but committing should be the act of the party that verified
the work, not the one that produced it. Write a clear message describing what landed. If your project
attributes co-authorship, that's the place for it.
From dispatch until that commit, the uncommitted working tree is the authoritative copy of the
implementer's work — the only one you can commit from, and often the only copy at all. Never run `git checkout`, `reset`, `clean`, or a branch switch in the
workspace between those two points — however messy an interrupted run looks, inspect it first:
`git status`, `git diff`, `git diff --cached` for anything the implementer staged (plain
`git diff` is blind to the index), and open any untracked files (`??` in `git status`) directly —
they are the implementer's new files, and no diff shows their contents. The tree is evidence,
not clutter. After that inspection the
verdict can legitimately be to discard — work built on a premise you have since corrected, for
example — and then `git checkout`/`clean` is the right tool. The ban is on reflexive cleanup
before anyone has looked.
## Reworking: send the delta, not the whole task
If the review turns up problems, don't restate the entire brief. Continue the same OpenCode session with
just the correction:
```bash
echo "The fix is right, but the test mocks the DB session - use the real migrated fixture instead, and
drop the now-unused import." | node "<skill-dir>/scripts/relay.mjs" --resume-last --cd /path/to/repo
```
(`<skill-dir>` is this skill's install directory — see [dispatch-and-poll.md](dispatch-and-poll.md).)
`--resume-last` keeps OpenCode's session context from the first run (and its model), so a short delta is
enough. Then review again — rework gets the same gate-rerun, test check, diff-read, and sweep as the
original, no shortcuts. Repeat until it's right, then commit.
## Surface, don't absorb
The human opted into delegation, so committing verified, gate-passing work is the agreed contract.
But keep them in the loop on anything that changes the shape of the work:
- **Report design decisions** OpenCode made, and any defensible-but-unrequested turns it took.
- **Note non-blocking nitpicks** you chose not to block on, so the human can overrule you.
- **Stop and ask** if correct completion requires going beyond the brief — don't expand the mandate on
your own. A scope change is the human's call, not yours or OpenCode's.
For a multi-task run, capture these in the progress file rather than letting them scroll past — see
[multi-task-queues.md](multi-task-queues.md).
references/writing-the-brief.md›
# Writing the brief
A brief is the entire task as OpenCode will see it. OpenCode runs in a fresh session with **no memory of
your conversation, no access to your prior notes, and no shared context** — only the text you send and
whatever it can read from the working tree (including the repo's own `AGENTS.md`, which it picks up
automatically). If a constraint isn't in the brief or discoverable in the repo, it doesn't exist for
OpenCode. The single most common failure is a brief that assumes context OpenCode doesn't have.
## Match the model to the brief
OpenCode has no default model, so every fresh dispatch names one with `--model provider/model`. Which
model is a two-owner decision: the **human** owns which models are allowed to run; **you, the
orchestrator**, pick one of them to fit the task in front of you.
- **The allowed set is the human's to state.** `opencode models` lists a few hundred models, but most
bill per token (OpenRouter and the like) and the CLI does not mark which are the human's
subscriptions. So they name their usable models — ideally once, in the target repo's `AGENTS.md` or
their `CLAUDE.md` (e.g. `opencode-go/…`, `zai-coding-plan/…`, `minimax-coding-plan/…`). If they
haven't, ask before dispatching rather than guessing a model and risking a metered bill.
- **Read the task's difficulty off the brief you just wrote, and match within that set.** A mechanical,
well-bounded brief — a rename sweep, a `moment`→`date-fns` migration, a dead-code removal — is safe on
a cheap, fast model. A brief whose risk lives in judgment — a concurrency fix, a money or auth path,
an ambiguous spec — wants a strong one, because the sweep's failure modes (plausible-but-wrong logic,
swallowed errors) are exactly what a weaker model produces more of.
- **A resumed run keeps the first run's model.** `--resume-last` / `--session` don't take `--model`; the
session already has one. Send only the delta brief.
## The shape that works
OpenCode responds well to compact, block-structured prompts with XML tags rather than long prose. State
the task, what "done" looks like, how to behave by default, and the few constraints that actually
matter. Add a block only when the task needs it — don't ship empty ceremony.
```xml
<task>
One or two sentences: the concrete job and where it lives. Then the specifics — current state, what to
change, and explicitly what to leave untouched. The "leave untouched" list is what keeps OpenCode from
wandering into unrelated refactors.
</task>
<verification_loop>
Run these before finishing and fix anything they surface, don't just report it:
<the project's real test command>
<the project's real lint/format command>
<the project's real build/typecheck command>
Confirm the working tree shows only the intended changes afterward.
</verification_loop>
<action_safety>
Keep changes scoped to the task. No unrelated refactors, renames, or cleanup unless required for
correctness. Do NOT run git add or git commit — the orchestrator commits after reviewing. Leave the
work uncommitted in the working tree.
</action_safety>
<structured_output_contract>
End with a report in this exact shape:
1. What changed and why
2. Files touched
3. Gate outcomes (paste the test/lint counts)
4. Anything you deviated on, left open, or want a decision on
</structured_output_contract>
```
That four-block skeleton covers most implementation tasks. Reach for the extra blocks when the task
profile calls for them:
- **Debugging / open-ended fixes** — add `<completeness_contract>` (resolve fully, don't stop at the
first plausible fix) and `<missing_context_gating>` (don't guess missing repo facts; find them or
state what's unknown).
- **Review / diagnosis (read-only)** — add `<grounding_rules>` (ground every claim in evidence; label
inferences) and dispatch with `--read-only` so OpenCode runs as the `plan` agent and can't edit.
- **Research / recommendations** — add `<research_mode>` (separate observed facts, inferences, open
questions).
## Always ask for the report explicitly
The relay assembles OpenCode's final message from the text it emits when it stops. If the agent finishes
a task purely through tool calls and stops without a closing summary, `finalMessage` comes back empty —
not a relay defect, just nothing said. The `<structured_output_contract>` block is what guarantees a
report you can read: it tells OpenCode to end with a written summary, so the result file carries one.
## Discover the real gates — don't hardcode
`<verification_loop>` is only useful if it names the project's *actual* commands. Read the repo's
`AGENTS.md` / `CLAUDE.md` / `Makefile` / `package.json` first and copy the real ones in (`make test`,
`npm run lint`, `cargo test`, `pytest -q`, whatever it is). A brief that says "run the tests" without
naming them gets you an OpenCode that guesses — or skips.
## Honor the repo's conventions
OpenCode reads the repo's `AGENTS.md` automatically, so house rules there (style, forbidden patterns,
commit conventions) already apply. If the project forbids certain things in code — say, spec/ticket IDs
in comments, process language like "MVP"/"for now"/"phase N", or specific test conventions, whatever the
repo's own conventions ban — restate the load-bearing ones in the brief too, because OpenCode's
compliance is only as reliable as what's in front of it.
## One task per brief
Keep each brief to a single, bounded job. "Review this, fix what you find, update the docs, and suggest
a roadmap" produces a muddled run; split it into separate dispatches. One brief → one OpenCode run →
one commit keeps review and rollback clean, and lets a later task assume the earlier one landed.
## Premises freeze at dispatch
The implementer starts from the brief's facts and there is no steering channel mid-run. Audit the
fact block before sending — ownership, target branch, constraints, anything a judgment call rests
on. If a premise turns out wrong while the run is live, stop the run and re-dispatch a corrected
brief rather than discounting the output afterward; for a write-capable run, inspect the working
tree and reconcile any partial or premise-contaminated edits — keep or revert them — before the
re-dispatch.
## A worked example
```xml
<task>
In the payments service at services/billing/, the refund path double-charges when a refund is retried
after a network timeout (the idempotency key isn't checked before re-submitting). Make the refund
submission idempotent: check for an existing refund by idempotency key before creating a new one.
Touch only services/billing/refund.py and its tests. Leave the charge path, the API routes, and the
data models untouched.
</task>
<verification_loop>
Run and make green before finishing:
pytest tests/billing/ -q
ruff check services/billing/
Confirm git status shows only refund.py and its test file changed.
</verification_loop>
<action_safety>
Scope strictly to the refund idempotency fix. No unrelated refactors. Do NOT git add or commit; leave
changes in the working tree for review.
</action_safety>
<structured_output_contract>
Report: (1) the root cause and your fix, (2) files touched, (3) pytest + ruff outcomes with counts,
(4) anything you left open or want decided.
</structured_output_contract>
```
Send this with `relay.mjs` (see [dispatch-and-poll.md](dispatch-and-poll.md)); review the result and
commit it yourself (see [review-and-land.md](review-and-land.md)).
scripts/relay.mjs›
#!/usr/bin/env node
/**
* delegate-skills · opencode-delegate · relay.mjs
*
* Dispatch a self-contained brief to the OpenCode CLI (`opencode run`),
* capture the run, and write a structured result the orchestrating agent can
* review. The orchestrator runs this one command and reads the result JSON —
* every OpenCode-specific mechanic lives in here, which keeps the skill
* orchestrator-agnostic. Verified against opencode CLI v1.17.13.
*
* Trust posture: relay.mjs itself makes no network calls, reads or writes no
* credentials, and sends no telemetry; it has no dependencies (Node built-ins
* only). It shells out only to `opencode` and `git`. The `opencode` process it
* launches does authenticate — exactly as you do at the terminal. Read this
* file before you run it.
*
* It deliberately does NOT commit. Committing is always the orchestrator's job —
* after it reviews the diff and re-runs the project gates.
*
* OpenCode autonomy is governed by the chosen agent, not a sandbox enum:
* build (default) — write-capable; edits files in the working dir headlessly.
* plan — read-only; reviews/diagnoses without touching the tree.
* A build run passes `--auto` by default so OpenCode never blocks on a permission
* prompt no one can answer in headless mode; the orchestrator's diff review is the
* safety net. Pass --no-auto to instead honor the agent's own permission config.
* A plan (read-only) run never gets --auto, so it can't be auto-approved into edits.
*
* Usage:
* node relay.mjs --brief <file> [options]
* cat brief.txt | node relay.mjs [options]
*
* Options:
* --brief <file> Path to the brief. If omitted, the brief is read from stdin.
* --cd <dir> Working root for OpenCode (default: current directory).
* --lane <name> Fleet lane from delegate-setup config (dials apply; explicit flags win).
* --model <name> Model as provider/model. REQUIRED for a fresh run — OpenCode has no
* safe default; a resumed run inherits its session's model.
* --agent <name> OpenCode agent (default: build). Use plan for read-only review.
* --read-only Shortcut for --agent plan (review/diagnosis, no edits).
* --variant <name> Provider reasoning effort (e.g. high, max, minimal).
* --no-auto Don't pass --auto; honor the agent's own permission config (a headless
* run may then hang if the agent is set to ask for a permission).
* --resume-last Continue the most recent OpenCode session; send only the delta brief.
* --session <id> Continue a specific session id (ses_...); send only the delta brief.
* --pure Run OpenCode without external plugins (cleaner event stream).
* --timeout <dur> Relay-side watchdog (default: off). Durations use h/m/s
* strings like 30m or 2h. On expiry the opencode child is
* killed and result.json gets status "timeout".
* --out-dir <dir> Where to write run artifacts (default: a fresh dir under
* the system temp dir, so the repo under review stays clean).
* -h, --help Show this help.
*
* Result: written to <out-dir>/result.json and summarized on stdout —
* status, exitCode, signal, opencodeVersion, sessionId (for a later resume), finalMessage
* (OpenCode's own report), touchedFiles (git porcelain, null if git can't report), and the
* paths to events.jsonl and final.txt.
*
* Exit codes: a pre-run usage error (bad/missing args, empty brief) exits 2
* before any run and writes no result file; a missing `opencode` binary exits 127;
* otherwise the exit code mirrors OpenCode's own (0 success, non-zero failure).
* If the child dies on a signal, the exit code is 128 plus the signal number and
* `result.json` records the signal.
* Once the brief validates, `result.json` is written on every outcome —
* completed, failed, timeout (the --timeout watchdog fired), aborted (the relay
* itself was killed and forwarded the kill to opencode), or
* opencode_unavailable. An orchestrator that polls for the
* file must therefore also treat a non-zero exit with no file as a usage error.
*/
import {spawn, execFileSync, spawnSync } from "node:child_process";
import { mkdirSync, writeFileSync, renameSync, readFileSync, existsSync, appendFileSync } from "node:fs";
import {join, resolve, basename, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { constants, tmpdir } from "node:os";
import { StringDecoder } from "node:string_decoder";
const MAX_BUFFERED_CHARS = 1_048_576;
const VERSION_PROBE_TIMEOUT_MS = 10_000;
const MAX_TIMER_MS = 2_147_483_647;
// model/variant reach cmd.exe on win32 (shell:true for the opencode.cmd shim).
// Keep in lockstep with delegate-setup MODEL_TOKEN.shellSafe.
const SAFE_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
const IMPLEMENTER_KEY = "opencode";
function makeEventScanner(onObject) {
let buf = "";
let index = 0;
let depth = 0;
let start = -1;
let inString = false;
let escaped = false;
return (chunk) => {
if (!chunk) return;
buf += chunk;
for (;;) {
while (index < buf.length) {
const ch = buf[index];
// Only track strings inside an object (depth > 0). At depth 0 we are
// skipping a junk prefix, and an unmatched `"` there must not swallow the
// real `{...}` that follows in the same chunk.
if (inString) {
if (escaped) escaped = false;
else if (ch === "\\") escaped = true;
else if (ch === '"') inString = false;
} else if (ch === '"') {
if (depth > 0) inString = true;
} else if (ch === "{") {
if (depth === 0) start = index;
depth += 1;
} else if (ch === "}") {
if (depth > 0) {
depth -= 1;
if (depth === 0 && start !== -1) {
const slice = buf.slice(start, index + 1);
try { onObject(JSON.parse(slice)); } catch { /* skip malformed */ }
start = -1;
}
}
}
index += 1;
}
if (depth === 0 || start === -1 || buf.length - start <= MAX_BUFFERED_CHARS) break;
// A complete object may exceed the retained-input cap within this chunk.
// Drop only an oversized partial, then rescan its suffix so a later
// concatenated event is not lost.
buf = buf.slice(start + MAX_BUFFERED_CHARS);
index = 0;
start = -1;
depth = 0;
inString = false;
escaped = false;
}
if (depth > 0 && start !== -1) {
if (start > 0) {
buf = buf.slice(start);
index -= start;
start = 0;
}
} else {
buf = "";
index = 0;
start = -1;
}
};
}
function applyFleetLane(opts, flagged) {
if (!opts.lane) return;
const script = join(dirname(fileURLToPath(import.meta.url)), "../../delegate-setup/scripts/lane.mjs");
if (!existsSync(script)) {
fail("--lane requires the delegate-setup skill installed beside this relay");
}
const r = spawnSync(
process.execPath,
[script, "resolve", "--cwd", opts.cd, "--lane", opts.lane, "--implementer", IMPLEMENTER_KEY],
{ encoding: "utf8", env: process.env },
);
if (r.error) fail(`lane resolve failed: ${r.error.message}`);
if (r.status !== 0) {
fail((r.stderr || "lane resolve failed").trim().replace(/^lane\.mjs:\s*/, ""));
}
let resolved;
try {
const lines = (r.stdout || "").trim().split("\n").filter(Boolean);
resolved = JSON.parse(lines[lines.length - 1]);
} catch {
fail("lane resolve returned invalid JSON");
}
opts.laneSource = resolved.source;
for (const [field, value] of Object.entries(resolved.dials || {})) {
if (flagged.has(field)) continue;
if (field === "autonomy" && (flagged.has("autonomy") || flagged.has("sandbox") || flagged.has("readOnly"))) continue;
if (field === "agent" && (flagged.has("agent") || flagged.has("readOnly"))) continue;
if (field === "sandbox" && (flagged.has("sandbox") || flagged.has("readOnly"))) continue;
if (field === "permissionMode" && (flagged.has("permissionMode") || flagged.has("readOnly"))) continue;
if (field === "planOnly" && (flagged.has("planOnly") || flagged.has("readOnly"))) continue;
if (field === "readOnly" && flagged.has("readOnly")) continue;
if (field === "force" && flagged.has("force")) continue;
opts[field] = value;
}
}
function fail(message, code = 2) {
process.stderr.write(`relay: ${message}\n`);
process.exit(code);
}
function parseArgs(argv) {
const flagged = new Set();
const opts = {
lane: null,
laneSource: null,
brief: null,
cd: process.cwd(),
model: null,
agent: "build",
variant: null,
auto: true,
resumeLast: false,
session: null,
pure: false,
timeout: null,
outDir: null,
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
const next = () => {
const value = argv[i + 1];
if (value === undefined) fail(`${arg} requires a value`);
i += 1;
return value;
};
switch (arg) {
case "-h":
case "--help":
process.stdout.write(headerComment());
process.exit(0);
break;
case "--brief": opts.brief = next(); break;
case "--cd": opts.cd = resolve(next()); break;
case "--lane": opts.lane = next(); break;
case "--model": opts.model = next(); flagged.add("model"); break;
case "--agent": opts.agent = next(); flagged.add("agent"); break;
case "--read-only": opts.agent = "plan"; flagged.add("agent"); flagged.add("readOnly"); break;
case "--variant": opts.variant = next(); flagged.add("variant"); break;
case "--auto": opts.auto = true; break;
case "--no-auto": opts.auto = false; break;
case "--resume-last": opts.resumeLast = true; break;
case "--session": opts.session = next(); break;
case "--pure": opts.pure = true; break;
case "--timeout": opts.timeout = next(); flagged.add("timeout"); break;
case "--out-dir": opts.outDir = resolve(next()); break;
default:
fail(`unknown option: ${arg}`);
}
}
applyFleetLane(opts, flagged);
if (opts.model !== null && !SAFE_TOKEN.test(opts.model)) {
fail("--model contains unsupported characters (allowed: letters, digits, . _ : / -)");
}
if (opts.variant !== null && !SAFE_TOKEN.test(opts.variant)) {
fail("--variant contains unsupported characters (allowed: letters, digits, . _ : / -)");
}
// The watchdog is relay-only (the opencode launch has no timeout flag), so a malformed
// --timeout must fail loudly here - a silent no-watchdog fallback would be wrong.
if (opts.timeout !== null && parseDuration(opts.timeout) === null) {
fail(`--timeout "${opts.timeout}" is invalid or too long; use a positive h/m/s duration no longer than about 24 days`);
}
return opts;
}
function parseDuration(duration) {
const match = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(duration);
if (!match || (!match[1] && !match[2] && !match[3])) return null;
try {
const seconds =
BigInt(match[1] || 0) * 3600n +
BigInt(match[2] || 0) * 60n +
BigInt(match[3] || 0);
const milliseconds = seconds * 1000n;
if (milliseconds <= 0n || milliseconds > BigInt(MAX_TIMER_MS)) return null;
return Number(milliseconds);
} catch {
return null;
}
}
function killChild(child, signal = "SIGTERM") {
if (!child || !child.pid) return;
if (process.platform === "win32") {
if (signal !== "SIGTERM") return;
try {
execFileSync("taskkill", ["/pid", String(child.pid), "/t", "/f"], {
stdio: ["ignore", "ignore", "inherit"],
});
} catch {
// The process tree already exited.
}
return;
}
try {
process.kill(-child.pid, signal);
} catch {
try {
child.kill(signal);
} catch {
// The process group already exited.
}
}
}
function headerComment() {
// The leading block comment doubles as --help text.
const src = readFileSync(new URL(import.meta.url), "utf8");
const match = src.match(/\/\*\*([\s\S]*?)\*\//);
if (!match) return "relay.mjs — dispatch a brief to opencode run\n";
return match[1].replace(/^\s*\* ?/gm, "").trim() + "\n";
}
function readBrief(opts) {
if (opts.brief) {
if (!existsSync(opts.brief)) fail(`brief file not found: ${opts.brief}`);
return readFileSync(opts.brief, "utf8");
}
// No --brief: read from stdin (fd 0). Empty stdin is an error.
if (process.stdin.isTTY) {
fail("no --brief given and stdin is a TTY; pass --brief <file> or pipe the brief on stdin");
}
let stdin = "";
try {
stdin = readFileSync(0, "utf8");
} catch {
stdin = "";
}
return stdin;
}
function versionProbeTimeout(opts) {
// The watchdog is only armed once opencode is running, so the preflight needs a bound of
// its own: an `opencode --version` that never returns would wedge the relay here, before
// any result.json exists, and --timeout could not reach it.
const timeoutMs = opts.timeout === null ? null : parseDuration(opts.timeout);
return timeoutMs === null ? VERSION_PROBE_TIMEOUT_MS : Math.min(timeoutMs, VERSION_PROBE_TIMEOUT_MS);
}
function opencodeVersion(probeTimeoutMs) {
try {
// On Windows, npm installs `opencode` as a .cmd shim; Node's CreateProcess only
// auto-appends .exe, never .cmd, so launching it needs shell:true there or it
// ENOENTs on a working install. POSIX is unaffected. (git installs a real
// git.exe and must NOT get this flag — see gitTouchedFiles.)
const version = execFileSync("opencode", ["--version"], {
encoding: "utf8",
shell: process.platform === "win32",
timeout: probeTimeoutMs,
killSignal: "SIGKILL",
}).trim();
return { version: version || "unknown", error: null };
} catch (error) {
if (error?.code === "ENOENT") return { version: null, error: null };
// shell:true routes a missing binary through cmd.exe, which reports it as a non-zero
// exit rather than ENOENT; that is still "not installed", not a broken install.
if (process.platform === "win32" &&
/not recognized as an internal or external command/i.test(String(error?.stderr || ""))) {
return { version: null, error: null };
}
// Anything else — a hung probe we killed, or a real non-zero exit — means opencode is
// installed but not usable. Reporting that as "unavailable" would send the caller
// off to reinstall a binary that is already there.
return { version: null, error };
}
}
function gitTouchedFiles(cwd) {
try {
const output = execFileSync("git", ["status", "--porcelain"], {
cwd,
encoding: "utf8",
timeout: 10_000,
killSignal: "SIGKILL",
stdio: ["ignore", "pipe", "ignore"],
maxBuffer: 64 * 1024 * 1024,
});
return output.split("\n").map((line) => line.trimEnd()).filter(Boolean);
} catch {
return null;
}
}
function timestamp() {
// Local script (not a workflow): Date is available and fine here.
return new Date().toISOString().replace(/[:.]/g, "-");
}
function buildArgv(opts) {
const argv = ["run", "--format", "json"];
if (opts.pure) argv.push("--pure");
// Resume continues an existing session; --session pins a specific id, otherwise
// --continue picks up the most recent one. OpenCode selects the agent for each
// prompt, so preserve the relay's requested autonomy on resumed turns too.
if (opts.session) {
argv.push("--session", opts.session);
} else if (opts.resumeLast) {
argv.push("--continue");
}
argv.push("--agent", opts.agent);
if (opts.model) argv.push("--model", opts.model);
if (opts.variant) argv.push("--variant", opts.variant);
// --auto (on by default) auto-approves permissions so a headless build run doesn't
// block on a prompt no one can answer; --no-auto honors the agent's own config.
// Never on a plan (read-only) run: --auto would approve the plan agent's ask-gated
// edit/bash permissions and let a "read-only" review modify the tree. A plan run
// only reads, so it doesn't need auto-approval anyway.
if (opts.auto && opts.agent !== "plan") argv.push("--auto");
// No message argument: the brief is piped on stdin (see dispatchToOpenCode),
// which avoids all argv-quoting issues with multi-line, XML-tagged briefs.
return argv;
}
function prepareRunDir(opts, brief) {
const startedAt = new Date().toISOString();
// Default the run dir to system temp so the repo under review stays pristine —
// the touched-files report must show only OpenCode's edits, not relay's artifacts.
const outDir = opts.outDir || join(tmpdir(), "delegate-relay", `${basename(opts.cd) || "repo"}-${timestamp()}`);
mkdirSync(outDir, { recursive: true });
const run = {
startedAt,
eventsPath: join(outDir, "events.jsonl"),
finalPath: join(outDir, "final.txt"),
briefPath: join(outDir, "brief.txt"),
resultPath: join(outDir, "result.json"),
};
writeFileSync(run.briefPath, brief, "utf8");
writeFileSync(run.eventsPath, "", "utf8");
return run;
}
function makeResultWriter(opts, version, run) {
// Returns writeResult(extra): merges the per-outcome fields onto the run's
// standing metadata, persists result.json, and returns the object it just
// wrote so the caller can hand it straight to printSummary.
return (extra) => {
const resuming = Boolean(opts.session || opts.resumeLast);
const result = {
schema: "delegate-relay.result.v1",
lane: opts.lane,
laneSource: opts.laneSource,
tool: "opencode",
workdir: opts.cd,
agent: opts.agent,
model: opts.model,
variant: opts.variant,
auto: opts.auto,
resumed: resuming,
resumeLast: opts.resumeLast,
opencodeVersion: version,
startedAt: run.startedAt,
finishedAt: new Date().toISOString(),
briefPath: run.briefPath,
eventsPath: run.eventsPath,
finalPath: existsSync(run.finalPath) ? run.finalPath : null,
...extra,
};
// Publish atomically so a polling orchestrator never reads a half-written file
// (same idiom as claude-delegate's writeJsonAtomic and qoder-delegate).
const temporary = `${run.resultPath}.${process.pid}.tmp`;
writeFileSync(temporary, `${JSON.stringify(result, null, 2)}\n`, "utf8");
renameSync(temporary, run.resultPath);
return result;
};
}
function reportUnavailable(writeResult, resultPath) {
const result = writeResult({ status: "opencode_unavailable", exitCode: 127, signal: null, sessionId: null, finalMessage: "", touchedFiles: null, cost: null });
printSummary(result, resultPath);
process.stderr.write("relay: `opencode` not found on PATH. Install it (npm i -g opencode-ai) and run `opencode auth login`.\n");
process.exit(127);
}
function reportVersionFailure(opts, writeResult, run, error, probeTimeoutMs) {
const timedOut = error?.code === "ETIMEDOUT";
const stderr = String(error?.stderr || "").trim();
const message = timedOut
? `opencode --version preflight timed out after ${probeTimeoutMs}ms; OpenCode was not dispatched`
: `opencode --version preflight failed${Number.isInteger(error?.status) ? ` with exit ${error.status}` : ""}; OpenCode was not dispatched`;
const result = writeResult({
status: timedOut ? "timeout" : "failed",
exitCode: timedOut ? 124 : Number.isInteger(error?.status) ? error.status : 1,
signal: null,
sessionId: null,
finalMessage: "",
touchedFiles: gitTouchedFiles(opts.cd),
cost: null,
stderrTail: stderr ? stderr.split("\n").slice(-20) : [],
error: message,
});
printSummary(result, run.resultPath);
process.stderr.write(`relay: ${message}\n`);
process.exit(result.exitCode);
}
function dispatchToOpenCode(opts, brief, run, writeResult) {
const argv = buildArgv(opts);
// Pin the working root two ways: `cwd` sets the child's real directory, and PWD
// is set explicitly because OpenCode can resolve its project root from the
// inherited PWD env — which spawn does NOT rewrite — so without it a run could
// operate on the orchestrator's directory instead of opts.cd (and, with --auto
// on, edit it unattended). Passing the path via env, not argv, keeps it clear of
// shell quoting.
// shell:true on Windows so the opencode.cmd shim resolves (see opencodeVersion).
// Safe: the brief is fed via child.stdin below — never argv — and argv holds only
// flag names, an agent enum, a model string, and a session id, with no shell
// metacharacters or spaceable paths.
const child = spawn("opencode", argv, {
cwd: opts.cd,
env: { ...process.env, PWD: opts.cd },
stdio: ["pipe", "pipe", "pipe"],
shell: process.platform === "win32",
detached: process.platform !== "win32", // POSIX: lead a new process group so killChild can fell the whole tree
});
let sessionId = opts.session || null;
let totalCost = 0;
let sawCost = false;
const textParts = new Map(); // part.id -> latest text
const textOrder = []; // part.ids in first-seen order
const stderrTail = [];
const scan = makeEventScanner((event) => {
// Session id: real events carry `sessionID` (camelCase); plugin notify objects
// carry `session_id` (snake_case). Accept either.
const sid = event.sessionID || event.session_id;
if (sid) sessionId = sid;
// Assistant text lives in `type:"text"` events under part.text. Key by part.id
// so streamed updates to the same part replace rather than duplicate; preserve
// first-seen order so multi-segment messages assemble correctly.
if (event.type === "text" && event.part && event.part.type === "text") {
const id = event.part.id || `anon-${textOrder.length}`;
if (!textParts.has(id)) textOrder.push(id);
textParts.set(id, event.part.text ?? "");
}
if (event.type === "step_finish" && event.part && typeof event.part.cost === "number") {
totalCost += event.part.cost;
sawCost = true;
}
});
// Decode across chunk boundaries: a multibyte UTF-8 character split between
// two data events would otherwise decode as U+FFFD and corrupt the report.
const stdoutDecoder = new StringDecoder("utf8");
const stderrDecoder = new StringDecoder("utf8");
child.stdout.on("data", (chunk) => {
appendFileSync(run.eventsPath, chunk); // faithful raw record of the event stream
scan(stdoutDecoder.write(chunk));
});
child.stderr.on("data", (chunk) => {
process.stderr.write(chunk); // surface OpenCode progress live for the orchestrator
const text = stderrDecoder.write(chunk);
for (const line of text.split("\n")) {
if (line.trim()) stderrTail.push(line.trimEnd());
}
while (stderrTail.length > 20) stderrTail.shift();
});
const assembleFinal = () => {
const message = textOrder.map((id) => textParts.get(id)).join("").trim();
if (message) writeFileSync(run.finalPath, message, "utf8");
return message;
};
let settled = false;
let watchdogFired = false;
let watchdogTimer = null;
let sigkillTimer = null;
const timeoutMs = opts.timeout === null ? null : parseDuration(opts.timeout);
if (timeoutMs !== null) {
watchdogTimer = setTimeout(() => {
watchdogFired = true;
child.once("exit", () => {
child.stdout.destroy();
child.stderr.destroy();
});
killChild(child);
sigkillTimer = setTimeout(() => {
if (!settled) killChild(child, "SIGKILL");
}, 10_000);
}, timeoutMs);
}
const clearWatchdog = () => {
if (watchdogTimer) clearTimeout(watchdogTimer);
if (sigkillTimer) clearTimeout(sigkillTimer);
};
// The relay's own death must still produce a result: without this, a kill from the
// orchestrator's side (its command timeout, a stopped task, a closed terminal) writes
// no result.json and leaves the opencode child running or dying mid-edit with nothing
// recording why. SIGTERM/SIGHUP registration is a no-op on Windows; SIGINT works there.
for (const sig of ["SIGTERM", "SIGINT", "SIGHUP"]) {
process.on(sig, () => {
if (settled) return;
settled = true;
clearWatchdog();
const abortedFields = {
status: "aborted",
exitCode: 128 + (constants.signals[sig] || 15),
signal: sig,
sessionId,
finalMessage: assembleFinal(),
touchedFiles: gitTouchedFiles(opts.cd),
cost: sawCost ? Number(totalCost.toFixed(6)) : null,
stderrTail: stderrTail.slice(-20),
error: `the relay was killed by ${sig}; opencode was terminated with it — inspect the working tree before re-dispatching`,
};
const result = writeResult(abortedFields);
printSummary(result, run.resultPath);
killChild(child);
setTimeout(() => {
killChild(child, "SIGKILL");
// the child may flush files during the grace window; refresh the snapshot so the
// artifact matches the tree the orchestrator will actually find
writeResult({ ...abortedFields, touchedFiles: gitTouchedFiles(opts.cd) });
process.exit(result.exitCode);
}, 2000);
});
}
child.on("error", (err) => {
if (settled) return;
settled = true;
clearWatchdog();
const result = writeResult({ status: "failed", exitCode: 1, signal: null, sessionId, finalMessage: assembleFinal(), touchedFiles: gitTouchedFiles(opts.cd), cost: sawCost ? totalCost : null, error: String(err && err.message ? err.message : err) });
printSummary(result, run.resultPath);
process.exit(1);
});
child.on("close", (code, signal) => {
if (settled) return;
settled = true;
clearWatchdog();
// a descendant that ignored SIGTERM must not outlive the timeout report: once the
// parent is down, sweep the group (no-op where taskkill already felled the tree)
if (watchdogFired) killChild(child, "SIGKILL");
const finalMessage = assembleFinal();
// A timed-out run is never a success even if opencode handles SIGTERM by exiting 0 -
// orchestrators key off status and the relay exit code.
const succeeded = code === 0 && !watchdogFired;
const mapped = code ?? (constants.signals[signal] ? 128 + constants.signals[signal] : 1);
const result = writeResult({
status: succeeded ? "completed" : watchdogFired ? "timeout" : "failed",
exitCode: succeeded ? 0 : mapped === 0 ? 1 : mapped,
signal: signal ?? null,
sessionId,
finalMessage,
touchedFiles: gitTouchedFiles(opts.cd),
cost: sawCost ? Number(totalCost.toFixed(6)) : null,
...(succeeded ? {} : { stderrTail: stderrTail.slice(-20) }),
...(watchdogFired ? { error: `opencode did not finish within --timeout ${opts.timeout}; killed by the relay watchdog` } : {}),
});
printSummary(result, run.resultPath);
process.exit(result.exitCode);
});
// If the child failed to launch, writing to its stdin can emit a stray 'error'
// on the pipe; the 'error' handler above owns that outcome, so swallow it here.
child.stdin.on("error", () => {});
child.stdin.write(brief);
child.stdin.end();
}
function main() {
const opts = parseArgs(process.argv.slice(2));
const brief = readBrief(opts);
if (!brief.trim()) fail("empty brief (pass --brief <file> or pipe the brief on stdin)");
// --session pins a specific session and --resume-last picks the most recent; passing both is a
// contradiction, and buildArgv would silently prefer --session. Reject it rather than guess.
if (opts.session && opts.resumeLast) {
fail("--session and --resume-last are mutually exclusive; pass only one");
}
// OpenCode has no safe default model (a bare `opencode run` errors), so a fresh run must name one.
// A resumed run inherits its session's model, so --model is optional there.
if (!opts.model && !opts.resumeLast && !opts.session) {
fail("no model given: pass --model provider/model — opencode has no safe default (e.g. a plan you're subscribed to, like opencode-go/kimi-k2.7-code)");
}
// Prepare the run dir before probing, so a preflight that times out or fails still has
// somewhere to publish result.json rather than exiting silently.
const run = prepareRunDir(opts, brief);
const probeTimeoutMs = versionProbeTimeout(opts);
const probe = opencodeVersion(probeTimeoutMs);
const writeResult = makeResultWriter(opts, probe.version, run);
if (!probe.version && !probe.error) {
reportUnavailable(writeResult, run.resultPath);
return;
}
if (probe.error) {
reportVersionFailure(opts, writeResult, run, probe.error, probeTimeoutMs);
return;
}
dispatchToOpenCode(opts, brief, run, writeResult);
}
function printSummary(result, resultPath) {
const lines = [];
lines.push("");
lines.push(`relay: ${result.status} (exit ${result.exitCode}${result.signal ? `, killed by ${result.signal}` : ""}) · opencode ${result.opencodeVersion ?? "?"}`);
if (result.signal === "SIGKILL" && result.status === "failed") lines.push("hint: the host killed the process (commonly the OOM killer or a supervisor timeout) — this is not an opencode error; check host memory and re-dispatch, or split the task into smaller briefs.");
if (result.signal === "SIGTERM" && result.status === "failed") lines.push("hint: something outside the relay terminated opencode (a supervisor, the session ending, or a manual kill) — when the relay itself does the killing it reports status \"timeout\" or \"aborted\" instead; inspect the working tree before re-dispatching.");
if (result.resumed) lines.push("mode: resumed existing session");
if (result.sessionId) lines.push(`session id (resume with: --session ${result.sessionId}): ${result.sessionId}`);
if (typeof result.cost === "number") lines.push(`cost: $${result.cost}`);
const touched = result.touchedFiles;
if (touched === null) {
lines.push("touched files: git unavailable — inspect the working tree directly");
} else {
lines.push(`touched files: ${touched.length}`);
for (const file of touched.slice(0, 40)) lines.push(` ${file}`);
if (touched.length > 40) lines.push(` … and ${touched.length - 40} more`);
}
if (result.stderrTail && result.stderrTail.length) {
lines.push("last stderr:");
for (const line of result.stderrTail.slice(-8)) lines.push(` ${line}`);
}
lines.push("");
lines.push("--- opencode final report ---");
lines.push(result.finalMessage || "(no final message captured)");
lines.push("--- end report ---");
lines.push("");
lines.push(`result: ${resultPath}`);
lines.push("relay does not commit. Review the diff, re-run the project gates yourself, then commit from the orchestrator.");
process.stdout.write(`${lines.join("\n")}\n`);
}
main();
SKILL.md›
---
name: opencode-delegate
description: >-
Delegate a coding task to the OpenCode CLI as a background implementer, then review its diff and
land it yourself. Use this whenever the user wants to hand implementation work to OpenCode — phrasings
like "have OpenCode do X", "delegate this to OpenCode", "run it through OpenCode", or "use OpenCode to
implement/fix/refactor" — or wants to run a queue of coding tasks through OpenCode while staying the
reviewer. Prefer it when the user will review the diff and commit it themselves. DO NOT USE for tasks
small enough to do inline, or when the user wants the code written directly without delegating.
license: MIT
compatibility: Requires the `opencode` CLI installed and authenticated, Node 18+, and git. The orchestrating agent must be able to run shell commands and read files. Shell examples assume bash/zsh (macOS/Linux, or Git Bash/WSL on Windows).
metadata:
version: 0.5.0
---
# OpenCode Delegate
You are the **orchestrator**. This skill lets you hand a bounded coding task to a separate
**implementer** — the OpenCode CLI — then review what it produced and land it yourself. You write
the brief and own the judgment; OpenCode does the typing in its own session; you verify and commit.
Nothing here is specific to one orchestrating agent. The loop needs only the ability to run a shell
command and read a file, so any agent with those two capabilities — Claude Code, OpenCode driving a
sibling session, or a comparable one — can drive it. (It is designed for and run on Claude Code; treat
other orchestrators as designed-for, not yet proven.)
## When NOT to use this
- The task is small enough to just do inline — delegation overhead is not worth it.
- The `opencode` CLI is not installed or not authenticated (run `opencode auth login`).
- You want to write the code yourself, or you only need a review (use the `plan` agent via `--read-only`).
## Prerequisites (check once)
1. `opencode --version` succeeds. If not, install (`npm i -g opencode-ai`, or the native installer from
opencode.ai) and `opencode auth login`.
2. **Confirm which `opencode` is on PATH.** `command -v opencode` shows the active binary and
`opencode --version` its version. The relay records the version it ran into `result.json`, so a stale
binary is visible after the fact.
3. A model provider is authenticated — `opencode auth list` shows at least one credential.
4. You are in (or will point `--cd` at) the target git repository.
## Choose the implementer model
OpenCode has **no safe default** — a bare `opencode run` errors — so a fresh run needs a model via
`--model` or a fleet `--lane` that sets one (a resumed run inherits its session's model). Naming the
model is the one decision a single-model backend like codex-delegate never had, and it has two owners:
- **The human owns which models are allowed.** `opencode models` lists hundreds of entries, most billed
per token (OpenRouter and the like); only the human knows which are their flat-rate subscriptions, and
the CLI can't tell them apart. So the usable set is theirs — ideally stated once in the repo's
`AGENTS.md` or their `CLAUDE.md` (e.g. "delegate mechanical work to `opencode-go/…`, hard logic to
`…`").
- **You, the orchestrator, pick per task — from that set.** Match the model to the brief: a cheap, fast
model for a mechanical sweep (rename, migration, removal); a strong one for a subtle bug or a
money/security path.
- **If no usable set is stated, ask — don't guess.** Guessing from the catalog risks a metered model and
a surprise bill. Name the constraint to the human and let them choose.
More depth: [references/writing-the-brief.md](references/writing-the-brief.md).
## The loop
Run these five steps per task. Steps 1, 4, and 5 are your judgment; 2 and 3 are mechanical.
### 1. Write the brief
OpenCode sees **only** the text you send plus what it can read from the working tree — no chat history,
no shared context. Everything the task needs goes in the brief: the goal, the current state, what to
change, what to leave untouched, the project's **actual** gate commands (discover them from the repo's
AGENTS.md/CLAUDE.md/Makefile — do not assume), and a report contract. Tell OpenCode it will **not**
commit (you will). Keep one task per brief. Full guidance and a template:
[references/writing-the-brief.md](references/writing-the-brief.md).
### 2. Dispatch
Send the brief to OpenCode with the bundled helper. It wraps `opencode run`, captures the run, and
writes a structured `result.json` — so your only job is "run a command, read a file." (`<skill-dir>`
below is this skill's installed directory — the folder containing this `SKILL.md`. Claude Code prints
it as "Base directory for this skill" when the skill loads; on other orchestrators use that same
directory — if unsure where it landed, run `find ~ -name relay.mjs -path '*opencode-delegate*'` and
substitute the directory above it.)
```bash
node "<skill-dir>/scripts/relay.mjs" --brief brief.txt --model <provider/model> --cd /path/to/repo
# --model (or a --lane that sets model) is required on a fresh run
# fleet lane from delegate-setup: add --lane <name> (dials apply; flags still win)
# read-only (review/diagnosis, no edits): add --read-only (uses the plan agent)
# continue the previous OpenCode session: add --resume-last (delta brief only; keeps the model)
# hard time limit (watchdog): add --timeout 2h (default: off; implementation runs routinely need 1-2h)
# see all options: node .../relay.mjs --help
```
The helper defaults to the write-capable `build` agent and writes its artifacts to a temp dir, so the
repo under review stays clean. It **never commits** — see step 5. Mechanics, flags, and the
`result.json` shape: [references/dispatch-and-poll.md](references/dispatch-and-poll.md).
### 3. Wait for completion
The helper blocks until OpenCode finishes, so back it with whatever your orchestrator offers and resume
when it returns:
- **Claude Code:** run the Bash call with `run_in_background: true`; you are notified on completion.
- **Plain shell / other agents:** run it in the foreground for short tasks, or background it and poll
the result file — `… &` in bash/zsh (including Git Bash/WSL), or your shell's equivalent (`Start-Job`
in PowerShell, `start /b` in cmd). The run is done when `result.json` exists with a `status`. (A
pre-run usage error — bad args or an empty brief — instead exits with code 2 and writes no result
file, so check the exit code too. A missing `opencode` binary exits 127 but *does* write a
`result.json` with status `opencode_unavailable`.)
Do not trust progress trackers over reality: a run is finished when `result.json` is written and the
process has exited. Read the working tree, not a status line. The implementer's full report is
the `finalMessage` field in `result.json` (also printed in full on stdout between the report markers).
### 4. Review — do not trust the self-report
OpenCode's `result.json` includes its own final message and any gate claims. **Re-verify, don't accept:**
- **Re-run the project's gates yourself** (the test/lint/build commands from step 1). Never take
"gates passed" on faith.
- **Read the diff** against the brief: did OpenCode do what was asked, nothing more (scope creep) and
nothing less? `touchedFiles` in the result is your starting point.
- **Run the relevant guard skills** on the diff if you have them installed (clean-code-guard,
test-guard, etc. from `guard-skills`) — this skill produces the work; those skills judge it.
- For schema/migration changes, round-trip them; for removals, grep for dangling references.
Full checklist: [references/review-and-land.md](references/review-and-land.md).
### 5. Land it
The implementer edits the working tree; **the orchestrator commits.** Committing should be the act of
the party that verified the work. Only after the gates pass and the diff holds:
- Commit the verified work yourself, with a clear message.
- If it needs changes, send a delta brief with `--resume-last` (don't restate the whole task) and
review again.
## Autonomy model
OpenCode's autonomy is governed by the **agent**, not a sandbox enum:
- **`build`** (the relay default) — write-capable; edits files in the working dir headlessly. The
equivalent of "let it implement."
- **`plan`** (via `--read-only`) — read-only; reviews and diagnoses without touching the tree. The
equivalent of "let it look but not edit."
Permissions **auto-approve by default**: the relay passes `--auto` so a headless run never blocks on a
prompt no one can answer. That is the point of unattended delegation — the orchestrator's diff review
and the implementer sweep (step 4) are the safety net, not a per-action prompt. Pass `--no-auto` to
honor the agent's own permission config instead (allow/ask/deny per action); pair it with an agent whose
in-workspace permissions are set to *allow*, or a headless run can hang waiting on an `ask`.
**Read-only (`plan`) runs never get `--auto`** — auto-approving would let the plan agent's ask-gated
edit/bash permissions through and defeat "read-only," so a review can't be tricked into touching the tree.
## Authorization model
Delegation is something the human opts into. Once they have ("run this queue", "proceed"), committing
verified, gate-passing work is the agreed contract — that is the whole point. Two limits on that
mandate: **surface, don't absorb** (report OpenCode's design decisions, defensible-but-unasked turns,
and non-blocking nitpicks rather than silently keeping them) and **stop for scope changes** (if correct
completion needs going beyond the brief, ask — don't expand the mandate yourself). The full treatment
is in [references/review-and-land.md](references/review-and-land.md).
## References
- [references/writing-the-brief.md](references/writing-the-brief.md) — how to write a brief OpenCode can
execute blind: structure, XML blocks, the report contract, embedding the real gate commands.
- [references/dispatch-and-poll.md](references/dispatch-and-poll.md) — `relay.mjs` flags, the
`result.json` contract, backgrounding per orchestrator, and recovery when a run misbehaves.
- [references/review-and-land.md](references/review-and-land.md) — the review checklist, the commit
boundary, and the rework cycle via `--resume-last`.
- [references/multi-task-queues.md](references/multi-task-queues.md) — running a sequential queue:
carrying constraints forward, progress tracking, and the end-of-run coherence check.