OpenCode CLI Orchestrator - Full-Runtime Cross-AI Dispatch
CRITICAL: SELF-INVOCATION PROHIBITED
If you run this skill inside OpenCode (TUI / acp / serve / run modes; detection signals in §8), you MUST refuse to load it and return the documented error message instead of dispatching.
This skill dispatches to the OpenCode CLI binary (opencode; an opencode2 installed by the v2 package is also accepted).
Only an explicit "parallel detached" request is exempt. It must intentionally spawn a SEPARATE session with its own session id and state directory.
A running CLI skill never dispatches itself. The cli-X skills are for cross-AI delegation only, never self-invocation.
Orchestrate OpenCode 2's opencode run (OpenCode 1's opencode run as the fallback) from external AI assistants (Claude Code, OpenCode, raw shell) AND from inside an existing OpenCode session for parallel detached workers. Three documented use cases keep the cycle risk explicit and give every dispatch path a copy-paste invocation shape.
Core Principle: The calling AI stays the conductor. Delegate to OpenCode for what it does best: the full plugin, skill, and MCP runtime in a one-shot dispatch. Validate and integrate the output.
1. WHEN TO USE
Activation Triggers
- Full plugin / skill / MCP runtime (use case 1): calling AI is Claude Code / OpenCode / Copilot / raw shell AND the task needs the project's spec folders and continuity docs, or every plugin/skill/MCP tool in a one-shot dispatch. Includes
@deep-research / @deep-review agent loops with externalized state under .opencode/specs/.
- Parallel detached session (use case 2): operator already inside OpenCode (TUI / web / serve / acp) AND wants a SEPARATE session with its own session id and state directory for ablation, worker farm, or parallel research. Prompt explicitly mentions "parallel detached", "ablation suite", "worker farm", "parallel research", "spawn detached", or "share URL".
- Agent dispatch: Use this when a task matches a specialized OpenCode agent.
- Primary agents (directly invokable via
--agent): general, plan (built-in), orchestrate.
- The orchestrate primary fully dispatches generic subagents:
context, review, write, debug, ai-council.
- Their parent
/deep:* command owns the loop executors end-to-end: deep-research, deep-review, prompt-improver.
orchestrate may make exactly one bounded hand-off to a recognized loop request, but never manages the loop.
- See §3 for the full contract.
- Cross-repo dispatch: On OpenCode 2, a session in repo A dispatches into repo B's plugin/skill/MCP runtime via
--server <url> and a start-in-directory cd.
- OpenCode 1 remains supported for now as a fallback for users who have not updated. Use
--dir <path> or a remote OpenCode server via --attach <url> (see references/install-and-versions.md).
When NOT to Use
- You ARE OpenCode already. If your runtime is OpenCode (detection signals in §8), this skill refuses to load.
- Self-invocation creates a circular dispatch loop and burns tokens for no value. The cli-X family is exclusively for cross-AI delegation.
- Only an explicit "parallel detached" request is exempt; it must intentionally spawn a SEPARATE session id and state directory (use case 2).
- Without that qualifier, the smart router refuses per ADR-001.
- Simple, quick tasks where
opencode run overhead is not worth it.
- Tasks that only need a raw model dispatch. Use a sibling cli-* skill.
- Tasks requiring interactive TUI or web UI (use
opencode directly instead of opencode run).
- Context already loaded and understood by the calling AI.
- Tasks where the OpenCode binary is not installed at the expected path.
2. SMART ROUTING
The cli-external-orchestration hub routes an OpenCode dispatch here: the request names OpenCode, opencode run, a parallel detached session or a full plugin runtime, and the hub's cli-opencode mode signal selects this packet.
A session already inside OpenCode is refused unless the request asks for a parallel detached session.
The hub ROUTER.md names the two leaves an OpenCode dispatch starts from.
Three use cases route here: external dispatch, parallel detached session and cross-AI handback.
Inside this packet the ALWAYS tier loads first: references/cli-reference.md and assets/prompt-quality-card.md.
A request that maps to no use case returns UNKNOWN_FALLBACK with a disambiguation checklist rather than a silent default.
Read ROUTER.md before selecting skill-local resources; open only the matched files.
3. HOW IT WORKS
Execution Ownership
This packet owns user-facing routing, the OpenCode binary probe, prompt construction and the self-invocation guard.
For research and review lineages, the shared deep-loop runtime at ../../system-deep-loop/runtime/scripts/fanout-run.cjs owns process construction and execution, using executor kind cli-opencode.
That runner accepts only the research and review loop types, so a single build or doc dispatch uses the child dispatch envelope in providers-and-models.md §5.
Do not add a packet-local wrapper, spawn path or command builder. Direct opencode run snippets below are operator reference and manual-testing examples.
Prerequisites
Verified versions. This skill was verified against OpenCode 2.3.0 and OpenCode 1.19.4 on 2026-11-14.
Flag and provider observations naming 2.0.32 or 1.19.3 were read on those releases, not re-read on 2.3.0 or 1.19.4.
Two subcommands moved in 2.3.0: credentials are under opencode auth, and agents are listed by opencode debug agents.
OpenCode 2 is expected and recommended; OpenCode 1 remains supported for now as a fallback for users who have not updated.
The skill loads and runs on both, with a documented capability delta. Later versions are unsupported until re-verified.
The delta is in references/install-and-versions.md.
The resolver takes the first opencode2 on PATH, falling back to the first opencode only if no opencode2 exists. OPENCODE_BIN overrides both.
The recommended side-by-side layout has no opencode2; there, the resolver's opencode is OpenCode 2. OpenCode 1 answers only to opencode1.
This skill's OpenCode 1 command lines name opencode, which is right on a v1-only machine. For side by side, run them as opencode1 or set OPENCODE_BIN=opencode1.
# Binary pick and version check: references/install-and-versions.md §4-5.
OC=${OPENCODE_BIN:-}; if [ -z "$OC" ]; then OC=$(command -v opencode2 2>/dev/null); [ -z "$OC" ] && OC=$(command -v opencode 2>/dev/null); fi
"$OC" --version # `opencode v2.3.0` = OpenCode 2 (expected), `1.19.4` = OpenCode 1 (fallback); either major passes
# Self-invocation guard. OPENCODE_API_KEY is a provider key an operator exports, not a session marker.
env | grep -v '^OPENCODE_API_KEY=' | grep -q '^OPENCODE_' && echo "ERROR: Already inside OpenCode session"
# Authentication. OpenCode 1 lists them with `opencode providers list`.
opencode auth list
Authentication options: opencode auth login <provider> on OpenCode 2, because 2.3.0 has no providers subcommand, and opencode providers login <provider> on OpenCode 1. A subscription plan uses opencode auth login with no provider and an interactive pick. Full per-provider login shapes: references/cli-reference.md §4.
Provider Auth Pre-Flight (Smart Fallback)
MANDATORY before any first dispatch in a session. The default provider may not be logged in, and a silent 401 mid-dispatch wastes a round-trip. Run the pre-flight once per session, cache the result, and re-run only on an auth failure.
The one-shot pre-flight bash, the decision trees and the error-recovery contract live in references/cli-reference.md §4. Never substitute a model the user didn't approve. ASK when the default is unavailable.
Default Invocation (Skill Default)
Default model, variant and format: Both OpenCode versions use llmgateway/deepseek-v4.1-flash-1017 at the max variant with --format json.
OpenCode 2 (the expected version) starts in the repo root, adds --standalone and puts effort on the model id (-m llmgateway/deepseek-v4.1-flash-1017#max).
OpenCode 1 (the supported fallback) uses this canonical dispatch: opencode run --model llmgateway/deepseek-v4.1-flash-1017 --variant max --format json --dir <repo-root> "<prompt>".
Full v2 argv and the per-version provider check: references/cli-reference.md §4.
Fan-out fallback: a deep-loop lineage that pins no model runs DeepSeek V4.1 Flash. The family is named here without a version or an effort tier on purpose, so this line does not go stale when the family ships a point release. The runner resolves the current id, and a drift test keeps the two in the same family.
The --agent flag (read this): Do NOT pass --agent on a top-level opencode run.
The default agent is correct for almost every dispatch; it applies when you omit --agent.
To target a specific agent profile, describe the role in the prompt body (e.g. "Act as a code-review agent: …").
Pass --agent <name> only after opencode run --help confirms acceptance.
On OpenCode 2.0.32, --agent <slug> runs the session as that agent, including general. An unknown slug exits 1; an "As @review" body stays with the default agent.
On OpenCode 1 (fallback), named agents like general are rejected at the top level.
Full roster and top-level rules: references/agent-delegation.md.
Honor explicit user model, port, and handback phrasing verbatim. Otherwise use the default invocation above.
Core Invocation Pattern
Core flags on OpenCode 2:
- Effort goes in
-m provider/model#<level>; --dir becomes a start-in-directory cd.
--standalone, --server and the log flags are global, and run accepts them on its command line.
run also takes --worktree and --archived, neither of which this skill passes.
--share, --port and --pure are absent on run.
OpenCode 1 fallback supports:
--model, --agent, --variant, --format json, --dir, session/fork flags, --port for detached sessions, --file, --thinking, --pure, --title, --command, --attach (with -p/-u), -i, --auto and log flags (see references/install-and-versions.md).
Non-interactive invocation stdin: always append </dev/null to any non-interactive opencode run invocation, on both versions, because the hang is observed on OpenCode 1 and unverified on OpenCode 2 (see references/integration-patterns.md §6).
Always pin the model with -m <provider/model>: a run that inherits an out-of-quota default provider retries the 429 forever and prints nothing, which looks like a deadlock. It is the most common cause of a "hung" opencode run. Diagnose with --print-logs --log-level DEBUG and look for stream error … Error 429, then pin a provider/model with live quota.
Registered command dispatch (--command, OpenCode 1 only): slash-command text inside a run message is NOT expanded. OpenCode 2 has no run flag for a registered command. On OpenCode 1 (fallback), use opencode run --command <family>/<name> [flags] "<args>". Full semantics: references/cli-reference.md §4.
Model Selection
On OpenCode 2, run opencode models --standalone filtered for the <provider>/ prefix (2.0.32's models takes no provider argument). On OpenCode 1 (fallback), run opencode providers list to confirm credentials and opencode models <provider> for live choices. Defaults live in §3 Default Invocation, and the roster is references/providers-and-models.md.
Five providers are reachable (opencode-go, openai, llmgateway (DevPass), minimax, mistral), with llmgateway/deepseek-v4.1-flash-1017 the single default on both OpenCode 2 and OpenCode 1, and the full roster and per-provider caveats in references/providers-and-models.md.
One cross-provider footgun is worth carrying here: id shape differs per provider, and copying a form between providers returns a 400 (see references/providers-and-models.md §2).
Closed roster: only models catalogued in that reference may be dispatched. Any model outside it is FORBIDDEN for cli-opencode (a hard discipline rule, since cli-opencode has no code-enforced allowlist).
OpenCode Agent Delegation
The calling AI is the conductor. OpenCode distinguishes primary agents (invokable via --agent <slug>) from subagents (Task-dispatched from a primary).
Primary agents, directly invokable via --agent
OpenCode lists plan and the repo's orchestrate as primary agents, and general as a subagent, on 2.0.32 and 1.19.3.
Never pass --agent general; the default agent covers that case on both versions, and OpenCode 1 rejects it at the top level.
Pin --agent plan|orchestrate only when the task needs that profile and opencode run --help confirms top-level acceptance. Otherwise, state the role in the prompt body.
Subagents, dispatched as Task subagents from a primary
These subagents live at .opencode/agents/<slug>.md with mode: subagent. They are NOT directly invokable via opencode run --agent.
Route generic subagents (context, review, write, debug) through --agent orchestrate. Route ai-council through /speckit:ai-council or orchestrate.
The parent /deep:* commands own the loop executors deep-research, deep-review and prompt-improver. Never dispatch them by raw --agent <slug>.
orchestrate may make one bounded hand-off but MUST NOT re-implement the loop.
See agent-delegation.md for the full roster and dispatch patterns.
Essential Commands
On OpenCode 2, those flags are gone from run. Cross-repo dispatch starts in the target directory.
--agent orchestrate runs the session as orchestrate; how it then routes subagents is untested.
On OpenCode 1 (fallback), --port <N> serves explicit detached sessions and --dir serves cross-repo dispatch.
--agent orchestrate routes generic subagents (see references/install-and-versions.md).
Error Handling
- Install missing binaries.
- Refuse ambiguous self-invocation.
- Run provider pre-flight for model/auth errors.
- Check version drift for unknown flags.
- Force
--format json for empty streams.
- Add
</dev/null for background loops.
- Never pass
--share.
- Use
--pure only for plugin crashes; it is absent from OpenCode 2 run and available on OpenCode 1 only (see references/install-and-versions.md).
- Inspect state logs for stuck sessions.
4. RULES
✅ ALWAYS
- Verify OpenCode CLI is installed before first invocation. Confirm the version baseline for OpenCode 2 (2.3.0, the expected version) or OpenCode 1 (1.19.4, supported for now as a fallback), with drift handling per
references/cli-reference.md §9.
- Run the self-invocation guard before dispatch (ADR-001): Layer 1 env-var lookup for any
OPENCODE_* other than OPENCODE_API_KEY, Layer 2 process-ancestry probe for opencode parent, Layer 3 ~/.opencode/state/<id>/lock probe. Trip on ANY positive. Refuse unless the prompt has explicit parallel-session keywords.
- Pin model, variant, format and dir explicitly.
- OpenCode 2 default:
-m llmgateway/deepseek-v4.1-flash-1017#max --format json with a start-in-directory cd.
- OpenCode 1 fallback:
--model llmgateway/deepseek-v4.1-flash-1017 --variant max --format json --dir <repo-root> (see references/cli-reference.md §4).
- No
--agent: the Default Invocation note says top-level --agent general is rejected. Put agent-profile requests in the prompt body.
- Honor user overrides verbatim. Check the id against the roster in references/providers-and-models.md rather than memory; each provider allows a specific set and a specific id shape.
- Pass
--format json unless the calling AI explicitly wants formatted output. The JSON event stream is what external runtimes parse incrementally.
- Append
</dev/null to every non-interactive opencode run invocation when it redirects stdout and/or stderr to files or runs inside while read loops.
- Without a closed stdin,
opencode run hangs at 0% CPU.
- Place it after the prompt positional argument and before the
> stdout 2> stderr redirects.
- DO NOT auto-kill external operator-owned opencode sessions when sweeping orphans. Exclude
opencode run from pkill.
- Hang mechanics and failure patterns:
references/integration-patterns.md §6.
- Pass the spec folder to the dispatched session in the prompt: if the calling AI has an active Gate-3 spec folder, include
Spec folder: <path> (pre-approved, skip Gate 3). If none, ASK the user before delegating: the dispatched session cannot answer Gate 3 interactively in non-interactive run mode.
- Prompt construction & model-craft (cli- family precedence).* Compose every dispatch prompt via the 2-tier rule canonical in
../../sk-prompt/assets/cli-prompt-quality-card.md:
- Fast path (default). Build from the local
assets/prompt-quality-card.md, which delegates the framework table + CLEAR check to the canonical card. Framework selection uses the canonical card's cross-model defaults, with no per-model prompt-craft profiles.
- Deep path (escalation). Dispatch
@prompt-improver via the Task tool (never load full sk-prompt inline) when any canonical Tier 2 trigger applies. The Tier 2 trigger list lives in ../../sk-prompt/assets/cli-prompt-quality-card.md. Do not re-enumerate it here.
- Validate dispatched session output: parse JSON events incrementally (tool calls, partial messages, final summary), run syntax checks if code generated, and cross-reference against project standards via
sk-code surface detection plus its code-review mode for findings-first review (see ALWAYS rule 12).
- Capture stderr (
2>&1) to catch tool errors and warnings.
- Classify the use case (1 / 2 / 3) before dispatching. The smart router refuses dispatches that do not map to one of the three.
- Run the Provider Auth Pre-Flight once per session (see §3 Provider Auth Pre-Flight). Cache the configured-providers list. If the default provider is missing (
llmgateway on both versions), ASK the user. Never silently substitute the model. If a later dispatch returns an auth error, invalidate the cache and rerun the pre-flight before retrying.
- Code Standards Loading (surface-aware contract): For code review or generation, instruct the session to:
- (1) Load
sk-code.
- (2) Let
sk-code emit a surface tag matching the detected stack.
- (3) Load selected surface resources and run its verification commands.
- (4) Load
sk-code's code-review mode only for formal findings-first review output.
- If the surface cannot be determined confidently, ask for the runtime surface and verification command set.
- NEVER hardcode obsolete sibling code skills in dispatch prompts.
- Design Standards Loading (measured-reference contract): For design or UI work, instruct the session to:
- (1) Load
sk-design-md-generator.
- (2) Extract a measured Style Reference DESIGN.md (named color tokens, type scale, components, Quick-Start CSS/Tailwind) from the live source before building UI.
- (3) Build against those measured tokens and run the extraction's validate step to confirm hex/section fidelity.
- If no live source can be measured, ask for the reference URL or exact tokens.
- NEVER treat
mcp-figma or sk-design-md-generator as a taste or critique authority. The extraction measures real CSS; it does not judge design.
Pass the design reference manifest to the dispatched session: For design or UI work, inline a DESIGN_DISPATCH_MANIFEST v1 block in the prompt.
- The child cannot resolve skill paths; the manifest must travel in the payload, not by reference.
- Include
styleReferenceExtracted true, the measured live source, measured design tokens / type scale / components, loadedFiles and proofDemandBack.
- If you lack a Style Reference or a live source, ask before launching; do not start a silent dispatch.
- The child returns the demanded proof. The parent reconciles it on return.
Destructive-scope-violation prevention (RM-8) for deep-loop dispatches.
- The permissions-matrix gate (
permissions-gate.ts) has no production caller. A --permissions-matrix <path> config is not enforced and bypasses nothing (wiring status: references/permissions-matrix.md).
- For non-interactive
opencode run with --dangerously-skip-permissions against a populated worktree, you MUST apply the four-layer mitigation, the only active protection:
- (L1) The rendered prompt contains literal
BANNED OPERATIONS and ALLOWED WRITE PATHS.
- (L2) The working directory points to a fresh
git worktree (OpenCode 2: start-in-directory cd; OpenCode 1: --dir <path>).
- OpenCode 2 takes the model's working directory from
PWD, not from the process directory, and names the repository's first checkout as the workspace root. A dispatch from Node spawn() with cwd must also set PWD to that directory, and the prompt carries the REPOSITORY ROOT line from the child-dispatch preamble.
scripts/probe-worktree-confinement.cjs shows whether a dispatch shape stays inside: exit 1 means a tool path left the worktree.
- (L3) Commit the target's own in-flight changes by explicit path. Leave other sessions' changes alone and record the recovery-baseline commit hash.
- (L4) For multi-phase / phase-parent targets, prefer
cli-copilot + gpt-6-sol --reasoning-effort high over the DeepSeek V4 Flash default, after confirming that model on the Copilot surface.
- The 2026-05-04 incident deleted 44 files. See
references/destructive-scope-violations.md for its root cause and checklist.
Single-dispatch discipline (operator-gated, session-scoped).
- Launch ONE cli-* dispatch at a time. Wait for it to return and verify its outputs.
- Then SIGKILL only the dispatch this skill started, using its captured PID and that PID's own children. Never use a blanket
pkill -9 -f "opencode run" (see Rule 5).
- Deep-flow sessions chain iterations back-to-back with kill-between. Explicitly authorized parallel dispatches are each killed by their own PID.
- Full procedure:
references/integration-patterns.md §8.
Set AI_SESSION_CHILD=1 in the dispatched session's env AND state the exemption in the prompt.
- A model cannot see an environment variable. Given only the variable, a session still asks the documentation-scope question and writes nothing at exit code zero.
- Copy the preamble from
shared/references/child-dispatch-preamble.md to the top of every non-interactive prompt.
- The variable also tells the per-session worktree wrapper (
.skilled/bin/worktree-session.sh) that dispatched opencode run is an orchestrated sub-session sharing the parent's worktree rather than allocating its own.
- The wrapper checks
AI_SESSION_CHILD plus a git --git-common-dir backstop, then execs in place when set.
- Pattern:
AI_SESSION_CHILD=1 opencode run ... </dev/null. Harmless when the wrapper is not in use.
- See
.skilled/bin/README.md → "Worktree session isolation".
- Prepend
SYSTEM_SPEC_GATE_ENFORCE=0 next to it so the child never inherits an enforced spec-gate from the parent shell: SYSTEM_SPEC_GATE_ENFORCE=0 AI_SESSION_CHILD=1 opencode run ... </dev/null.
Agent-persona injection (attach identity, not just the task). Every dispatch composes {resolved agent persona + task prompt}, never a bare task.
- Resolve the persona from the ACTIVE runtime's agent directory per AGENTS.md §9 (
.opencode/agents/<name>.md, .claude/agents/<name>.md, etc.). Never hardcode one runtime.
- Map each subtask to the RIGHT agent, not one default:
code→code, review→review, design→design, research→deep-research, docs→markdown.
- OpenCode reaches personas via a primary: route
--agent orchestrate (or another primary) so the resolved persona runs as a Task subagent. Top-level --agent rejects mode: subagent personas (see references/agent-delegation.md).
- On a bare
opencode run that names no subagent, INLINE the persona block into the payload using the same in-payload pattern as the DESIGN_DISPATCH_MANIFEST (Rule 14); the child cannot resolve agent paths by reference.
- A persona-less dispatch runs the leaf as a generic assistant, silently dropping its tool-scope, verification gates and output contract.
- Canonical contract:
../../sk-prompt/assets/cli-prompt-quality-card.md "Persona Injection". Native precedent: orchestrate.md "Agent Loading Protocol".
- Declare rare exceptions at the dispatch site: native surface used, focused summary for a small-context model, or pure-mechanical command.
⛔ NEVER
- Invoke this skill from within OpenCode itself for a self-dispatch. Refuse with the documented error message and use a sibling cli-* / fresh shell / parallel-session keywords.
- Pass
--share. OpenCode 2 run has no such flag, and on OpenCode 1.19.3 (fallback) it is a hidden, deprecated flag that only prints "Session sharing has been discontinued" (see references/install-and-versions.md).
- Trust dispatched session output blindly for security-sensitive code, send sensitive data (API keys, passwords, credentials) in prompts, or hammer the API with rapid sequential calls.
- Use
--pure outside of plugin debugging (absent from OpenCode 2 run, OpenCode 1 only, see references/install-and-versions.md). Disabling plugins removes the entire point of cli-opencode dispatch.
- Nest
opencode run inside a dispatched session's tool calls. Use OpenCode's native Task tool for sub-agent dispatch.
⚠️ ESCALATE IF
- OpenCode CLI is not installed and user has not acknowledged (provide
brew install opencode or curl -fsSL https://opencode.ai/install | bash).
- Operator asks for a share URL. OpenCode 2
run has no share flag, and OpenCode 1.19.3 discontinued session sharing, so say there is no URL to publish.
- Binary version differs from the OpenCode 2 (2.3.0, expected) or OpenCode 1 (1.19.4, fallback) baseline. Run
opencode --version (opencode1 --version for the side-by-side OpenCode 1) and run --help, then surface drift and fall back or require approval.
- Smart router cannot map the prompt to one of the three use cases. Surface the disambiguation checklist from UNKNOWN_FALLBACK.
- Self-invocation guard trips AND the prompt is ambiguous. Surface the refusal with three remediation options (sibling cli-* / fresh shell / parallel-session keywords).
Memory Handback Protocol
When you need to preserve session context from an OpenCode CLI delegation, run the canonical procedure: extract MEMORY_HANDBACK, scrub secrets, and invoke generate-context.js via --stdin/--json/temp-file.
The continuity writer is the last step; nothing is handed to an index.
Full procedure and caveats: system-spec-kit/references/cli/memory-handback.md.
OpenCode-specific Memory Epilogue template: see assets/prompt-templates.md §14.
Example invocation:
printf '%s' "$JSON_PAYLOAD" | node .skilled/skills/system-spec-kit/runtime/cli/dist/continuity/generate-context.js --stdin [spec-folder]
5. SUCCESS CRITERIA
Task Completion
- OpenCode CLI invoked with the correct subcommand, flags, model, agent, variant, format, and dir.
- Self-invocation guard checked before dispatch and refused when appropriate.
- Use case (1 / 2 / 3) classified explicitly before invocation.
- JSON event stream captured, parsed incrementally, validated, integrated.
- No security vulnerabilities introduced from generated code.
- No dispatch passes
--share (absent from OpenCode 2 run, discontinued on OpenCode 1 1.19.3).
- Background dispatches in
while read loops include </dev/null redirect.
- Memory Handback extracted and saved through
generate-context.js when applicable.
Skill Quality
- All numbered sections present and correctly ordered.
- Smart routing covers all intent signals with UNKNOWN_FALLBACK.
- Reference files provide deep-dive content without duplication.
- Self-invocation guard detail in
ROUTER.md mirrors ADR-001.
6. INTEGRATION POINTS
Framework Integration
This skill operates within the behavioral framework defined in AGENTS.md.
Key integrations:
- Gate 2: Skill routing via the Skill Advisor Hook (or
skill_advisor.py fallback)
- Tool Routing: Per AGENTS.md Section 5 decision tree
- Continuity: Context preserved by
/speckit:save, which writes through generate-context.js
- Validation:
bash .skilled/skills/system-spec-kit/runtime/cli/spec/validate.sh for spec-folder workflows
Tool roles: Bash dispatches the CLI. Read/Glob/Grep validate output and probe ~/.opencode/state/ for session locks.
7. REFERENCES AND RELATED RESOURCES
Core References
- cli-reference.md - Full subcommand/flag reference, provider auth pre-flight, models, version drift
- integration-patterns.md - 3 use cases, decision tree, silent stdin
- self-invocation-guard.md - ADR-001 layered bash + python detection contract
- opencode-tools.md - Unique value props vs sibling cli-* skills
- agent-delegation.md - Agent routing matrix, leaf-agent constraints
- destructive-scope-violations.md - RM-8 incident, root cause, four-layer prevention playbook
- install-and-versions.md - Install recipes, side-by-side layout, version detection and the capability delta
- providers-and-models.md - The provider, model and variant-effort roster
- permissions-matrix.md - Matrix schema, resolution semantics and RM-8 replay reasoning
- context-budget.md - Model context windows and the truncation marker for bounded prompts
Templates and Assets
Shared (cli-* family)
External
Reference Loading Notes
- Smart Routing (Section 2) is the summary.
ROUTER.md is the single routing authority.
- The router discovers reference, asset, and script docs dynamically: resources from
references/, templates from assets/, automation from scripts/ when present.
Related Skills
cli-claude-code and cli-opencode for sibling cross-AI dispatch, system-spec-kit for handback, sk-code plus the selected overlay for generated code, system-deep-loop for loop execution (its research and review modes), and mcp-code-mode for MCP-backed tools.
1---2name: cli-opencode3description: "OpenCode CLI orchestrator: external dispatch, in-OpenCode parallel sessions, cross-AI handback with full runtime context."4allowed-tools: [Bash, Read, Glob, Grep]5version: 1.5.12.06metadata:7 source: https://skillmd.com/skills/michelkerkmeester/cli-opencode8---910# OpenCode CLI Orchestrator - Full-Runtime Cross-AI Dispatch1112> **CRITICAL: SELF-INVOCATION PROHIBITED**13>14> If you run this skill inside OpenCode (TUI / acp / serve / run modes; detection signals in §8), you MUST refuse to load it and return the documented error message instead of dispatching.15> This skill dispatches to the OpenCode CLI binary (`opencode`; an `opencode2` installed by the v2 package is also accepted).16> Only an explicit "parallel detached" request is exempt. It must intentionally spawn a SEPARATE session with its own session id and state directory.17>18> A running CLI skill never dispatches itself. The cli-X skills are for **cross-AI delegation only**, never self-invocation.1920Orchestrate OpenCode 2's `opencode run` (OpenCode 1's `opencode run` as the fallback) from external AI assistants (Claude Code, OpenCode, raw shell) AND from inside an existing OpenCode session for parallel detached workers. Three documented use cases keep the cycle risk explicit and give every dispatch path a copy-paste invocation shape.2122**Core Principle**: The calling AI stays the conductor. Delegate to OpenCode for what it does best: the full plugin, skill, and MCP runtime in a one-shot dispatch. Validate and integrate the output.2324---2526## 1. WHEN TO USE2728### Activation Triggers2930- **Full plugin / skill / MCP runtime** (use case 1): calling AI is Claude Code / OpenCode / Copilot / raw shell AND the task needs the project's spec folders and continuity docs, or every plugin/skill/MCP tool in a one-shot dispatch. Includes `@deep-research` / `@deep-review` agent loops with externalized state under `.opencode/specs/`.31- **Parallel detached session** (use case 2): operator already inside OpenCode (TUI / web / serve / acp) AND wants a SEPARATE session with its own session id and state directory for ablation, worker farm, or parallel research. Prompt explicitly mentions "parallel detached", "ablation suite", "worker farm", "parallel research", "spawn detached", or "share URL".32- **Agent dispatch**: Use this when a task matches a specialized OpenCode agent.33 - Primary agents (directly invokable via `--agent`): `general`, `plan` (built-in), `orchestrate`.34 - The orchestrate primary fully dispatches generic subagents: `context`, `review`, `write`, `debug`, `ai-council`.35 - Their parent `/deep:*` command owns the loop executors end-to-end: `deep-research`, `deep-review`, `prompt-improver`.36 - `orchestrate` may make exactly one bounded hand-off to a recognized loop request, but never manages the loop.37 - See §3 for the full contract.38- **Cross-repo dispatch**: On OpenCode 2, a session in repo A dispatches into repo B's plugin/skill/MCP runtime via `--server <url>` and a start-in-directory `cd`.39 - OpenCode 1 remains supported for now as a fallback for users who have not updated. Use `--dir <path>` or a remote OpenCode server via `--attach <url>` (see [`references/install-and-versions.md`](./references/install-and-versions.md)).4041### When NOT to Use4243- **You ARE OpenCode already.** If your runtime is OpenCode (detection signals in §8), this skill refuses to load.44- Self-invocation creates a circular dispatch loop and burns tokens for no value. The cli-X family is exclusively for cross-AI delegation.45- Only an explicit "parallel detached" request is exempt; it must intentionally spawn a SEPARATE session id and state directory (use case 2).46- Without that qualifier, the smart router refuses per ADR-001.47- Simple, quick tasks where `opencode run` overhead is not worth it.48- Tasks that only need a raw model dispatch. Use a sibling cli-* skill.49- Tasks requiring interactive TUI or web UI (use `opencode` directly instead of `opencode run`).50- Context already loaded and understood by the calling AI.51- Tasks where the OpenCode binary is not installed at the expected path.5253---5455## 2. SMART ROUTING5657The `cli-external-orchestration` hub routes an OpenCode dispatch here: the request names OpenCode, `opencode run`, a parallel detached session or a full plugin runtime, and the hub's `cli-opencode` mode signal selects this packet.58A session already inside OpenCode is refused unless the request asks for a parallel detached session.5960The hub [`ROUTER.md`](../ROUTER.md) names the two leaves an OpenCode dispatch starts from.61Three use cases route here: external dispatch, parallel detached session and cross-AI handback.62Inside this packet the `ALWAYS` tier loads first: `references/cli-reference.md` and `assets/prompt-quality-card.md`.6364A request that maps to no use case returns `UNKNOWN_FALLBACK` with a disambiguation checklist rather than a silent default.65Read [`ROUTER.md`](./ROUTER.md) before selecting skill-local resources; open only the matched files.6667---6869## 3. HOW IT WORKS7071### Execution Ownership7273This packet owns user-facing routing, the OpenCode binary probe, prompt construction and the self-invocation guard.74For research and review lineages, the shared deep-loop runtime at `../../system-deep-loop/runtime/scripts/fanout-run.cjs` owns process construction and execution, using executor kind `cli-opencode`.75That runner accepts only the `research` and `review` loop types, so a single build or doc dispatch uses the child dispatch envelope in [providers-and-models.md](./references/providers-and-models.md) §5.76Do not add a packet-local wrapper, spawn path or command builder. Direct `opencode run` snippets below are operator reference and manual-testing examples.7778### Prerequisites7980**Verified versions.** This skill was verified against OpenCode 2.3.0 and OpenCode 1.19.4 on 2026-11-14.81Flag and provider observations naming 2.0.32 or 1.19.3 were read on those releases, not re-read on 2.3.0 or 1.19.4.82Two subcommands moved in 2.3.0: credentials are under `opencode auth`, and agents are listed by `opencode debug agents`.83OpenCode 2 is expected and recommended; OpenCode 1 remains supported for now as a fallback for users who have not updated.84The skill loads and runs on both, with a documented capability delta. Later versions are unsupported until re-verified.85The delta is in [`references/install-and-versions.md`](./references/install-and-versions.md).8687The resolver takes the first `opencode2` on `PATH`, falling back to the first `opencode` only if no `opencode2` exists. `OPENCODE_BIN` overrides both.88The recommended side-by-side layout has no `opencode2`; there, the resolver's `opencode` is OpenCode 2. OpenCode 1 answers only to `opencode1`.89This skill's OpenCode 1 command lines name `opencode`, which is right on a v1-only machine. For side by side, run them as `opencode1` or set `OPENCODE_BIN=opencode1`.9091```bash92# Binary pick and version check: references/install-and-versions.md §4-5.93OC=${OPENCODE_BIN:-}; if [ -z "$OC" ]; then OC=$(command -v opencode2 2>/dev/null); [ -z "$OC" ] && OC=$(command -v opencode 2>/dev/null); fi94"$OC" --version # `opencode v2.3.0` = OpenCode 2 (expected), `1.19.4` = OpenCode 1 (fallback); either major passes9596# Self-invocation guard. OPENCODE_API_KEY is a provider key an operator exports, not a session marker.97env | grep -v '^OPENCODE_API_KEY=' | grep -q '^OPENCODE_' && echo "ERROR: Already inside OpenCode session"9899# Authentication. OpenCode 1 lists them with `opencode providers list`.100opencode auth list101```102103**Authentication options**: `opencode auth login <provider>` on OpenCode 2, because 2.3.0 has no `providers` subcommand, and `opencode providers login <provider>` on OpenCode 1. A subscription plan uses `opencode auth login` with no provider and an interactive pick. Full per-provider login shapes: `references/cli-reference.md` §4.104105### Provider Auth Pre-Flight (Smart Fallback)106107**MANDATORY before any first dispatch in a session.** The default provider may not be logged in, and a silent `401` mid-dispatch wastes a round-trip. Run the pre-flight once per session, cache the result, and re-run only on an auth failure.108109The one-shot pre-flight bash, the decision trees and the error-recovery contract live in [`references/cli-reference.md`](./references/cli-reference.md) §4. Never substitute a model the user didn't approve. ASK when the default is unavailable.110111### Default Invocation (Skill Default)112113**Default model, variant and format**: Both OpenCode versions use `llmgateway/deepseek-v4.1-flash-1017` at the `max` variant with `--format json`.114OpenCode 2 (the expected version) starts in the repo root, adds `--standalone` and puts effort on the model id (`-m llmgateway/deepseek-v4.1-flash-1017#max`).115OpenCode 1 (the supported fallback) uses this canonical dispatch: `opencode run --model llmgateway/deepseek-v4.1-flash-1017 --variant max --format json --dir <repo-root> "<prompt>"`.116Full v2 argv and the per-version provider check: [`references/cli-reference.md`](./references/cli-reference.md) §4.117118> **Fan-out fallback:** a deep-loop lineage that pins no model runs **DeepSeek V4.1 Flash**. The family is named here without a version or an effort tier on purpose, so this line does not go stale when the family ships a point release. The runner resolves the current id, and a drift test keeps the two in the same family.119120> **The `--agent` flag (read this):** Do NOT pass `--agent` on a top-level `opencode run`.121> The default agent is correct for almost every dispatch; it applies when you omit `--agent`.122> To target a specific agent profile, describe the role in the prompt body (e.g. "Act as a code-review agent: …").123> Pass `--agent <name>` only after `opencode run --help` confirms acceptance.124> On OpenCode 2.0.32, `--agent <slug>` runs the session as that agent, including `general`. An unknown slug exits 1; an "As @review" body stays with the default agent.125> On OpenCode 1 (fallback), named agents like `general` are rejected at the top level.126> Full roster and top-level rules: [`references/agent-delegation.md`](./references/agent-delegation.md).127128Honor explicit user model, port, and handback phrasing verbatim. Otherwise use the default invocation above.129130### Core Invocation Pattern131132Core flags on OpenCode 2:133- Effort goes in `-m provider/model#<level>`; `--dir` becomes a start-in-directory `cd`.134- `--standalone`, `--server` and the log flags are global, and `run` accepts them on its command line.135- `run` also takes `--worktree` and `--archived`, neither of which this skill passes.136- `--share`, `--port` and `--pure` are absent on `run`.137138OpenCode 1 fallback supports:139- `--model`, `--agent`, `--variant`, `--format json`, `--dir`, session/fork flags, `--port` for detached sessions, `--file`, `--thinking`, `--pure`, `--title`, `--command`, `--attach` (with `-p`/`-u`), `-i`, `--auto` and log flags (see [`references/install-and-versions.md`](./references/install-and-versions.md)).140141> **Non-interactive invocation stdin**: always append `</dev/null` to any non-interactive `opencode run` invocation, on both versions, because the hang is observed on OpenCode 1 and unverified on OpenCode 2 (see `references/integration-patterns.md` §6).142143> **Always pin the model with `-m <provider/model>`**: a run that inherits an out-of-quota default provider retries the `429` forever and prints nothing, which looks like a deadlock. It is the most common cause of a "hung" `opencode run`. Diagnose with `--print-logs --log-level DEBUG` and look for `stream error … Error 429`, then pin a provider/model with live quota.144145> **Registered command dispatch (`--command`, OpenCode 1 only)**: slash-command text inside a `run` message is NOT expanded. OpenCode 2 has no `run` flag for a registered command. On OpenCode 1 (fallback), use `opencode run --command <family>/<name> [flags] "<args>"`. Full semantics: `references/cli-reference.md` §4.146147### Model Selection148149On OpenCode 2, run `opencode models --standalone` filtered for the `<provider>/` prefix (2.0.32's `models` takes no provider argument). On OpenCode 1 (fallback), run `opencode providers list` to confirm credentials and `opencode models <provider>` for live choices. Defaults live in §3 Default Invocation, and the roster is [references/providers-and-models.md](references/providers-and-models.md).150151**Five providers are reachable** (`opencode-go`, `openai`, `llmgateway` (**DevPass**), `minimax`, `mistral`), with `llmgateway/deepseek-v4.1-flash-1017` the single default on both OpenCode 2 and OpenCode 1, and the full roster and per-provider caveats in [references/providers-and-models.md](references/providers-and-models.md).152One cross-provider footgun is worth carrying here: **id shape differs per provider**, and copying a form between providers returns a 400 (see [references/providers-and-models.md](references/providers-and-models.md) §2).153154**Closed roster: only models catalogued in that reference may be dispatched. Any model outside it is FORBIDDEN for cli-opencode** (a hard discipline rule, since cli-opencode has no code-enforced allowlist).155156### OpenCode Agent Delegation157158The calling AI is the conductor. OpenCode distinguishes **primary agents** (invokable via `--agent <slug>`) from **subagents** (Task-dispatched from a primary).159160#### Primary agents, directly invokable via `--agent`161162OpenCode lists `plan` and the repo's `orchestrate` as primary agents, and `general` as a subagent, on 2.0.32 and 1.19.3.163**Never pass `--agent general`**; the default agent covers that case on both versions, and OpenCode 1 rejects it at the top level.164Pin `--agent plan|orchestrate` only when the task needs that profile and `opencode run --help` confirms top-level acceptance. Otherwise, state the role in the prompt body.165166#### Subagents, dispatched as Task subagents from a primary167168These subagents live at `.opencode/agents/<slug>.md` with `mode: subagent`. They are NOT directly invokable via `opencode run --agent`.169Route generic subagents (`context`, `review`, `write`, `debug`) through `--agent orchestrate`. Route `ai-council` through `/speckit:ai-council` or `orchestrate`.170The parent `/deep:*` commands own the loop executors `deep-research`, `deep-review` and `prompt-improver`. Never dispatch them by raw `--agent <slug>`.171`orchestrate` may make one bounded hand-off but MUST NOT re-implement the loop.172173See [agent-delegation.md](./references/agent-delegation.md) for the full roster and dispatch patterns.174175### Essential Commands176177On OpenCode 2, those flags are gone from `run`. Cross-repo dispatch starts in the target directory.178`--agent orchestrate` runs the session as `orchestrate`; how it then routes subagents is untested.179On OpenCode 1 (fallback), `--port <N>` serves explicit detached sessions and `--dir` serves cross-repo dispatch.180`--agent orchestrate` routes generic subagents (see [`references/install-and-versions.md`](./references/install-and-versions.md)).181182### Error Handling183184- Install missing binaries.185- Refuse ambiguous self-invocation.186- Run provider pre-flight for model/auth errors.187- Check version drift for unknown flags.188- Force `--format json` for empty streams.189- Add `</dev/null` for background loops.190- Never pass `--share`.191- Use `--pure` only for plugin crashes; it is absent from OpenCode 2 `run` and available on OpenCode 1 only (see [`references/install-and-versions.md`](./references/install-and-versions.md)).192- Inspect state logs for stuck sessions.193194---195196## 4. RULES197198### ✅ ALWAYS1992001. Verify OpenCode CLI is installed before first invocation. Confirm the version baseline for OpenCode 2 (2.3.0, the expected version) or OpenCode 1 (1.19.4, supported for now as a fallback), with drift handling per `references/cli-reference.md` §9.2012. **Run the self-invocation guard before dispatch** (ADR-001): Layer 1 env-var lookup for any `OPENCODE_*` other than `OPENCODE_API_KEY`, Layer 2 process-ancestry probe for `opencode` parent, Layer 3 `~/.opencode/state/<id>/lock` probe. Trip on ANY positive. Refuse unless the prompt has explicit parallel-session keywords.2023. Pin model, variant, format and dir explicitly.203 - OpenCode 2 default: `-m llmgateway/deepseek-v4.1-flash-1017#max --format json` with a start-in-directory `cd`.204 - OpenCode 1 fallback: `--model llmgateway/deepseek-v4.1-flash-1017 --variant max --format json --dir <repo-root>` (see [`references/cli-reference.md`](./references/cli-reference.md) §4).205 - **No `--agent`**: the Default Invocation note says top-level `--agent general` is rejected. Put agent-profile requests in the prompt body.206 - Honor user overrides verbatim. Check the id against the roster in [references/providers-and-models.md](references/providers-and-models.md) rather than memory; each provider allows a specific set and a specific id shape.2074. Pass `--format json` unless the calling AI explicitly wants formatted output. The JSON event stream is what external runtimes parse incrementally.2085. **Append `</dev/null` to every non-interactive `opencode run` invocation** when it redirects stdout and/or stderr to files or runs inside `while read` loops.209 - Without a closed stdin, `opencode run` hangs at 0% CPU.210 - Place it after the prompt positional argument and before the `> stdout 2> stderr` redirects.211 - **DO NOT auto-kill external operator-owned opencode sessions** when sweeping orphans. Exclude `opencode run` from pkill.212 - Hang mechanics and failure patterns: [`references/integration-patterns.md`](./references/integration-patterns.md) §6.2136. **Pass the spec folder to the dispatched session** in the prompt: if the calling AI has an active Gate-3 spec folder, include `Spec folder: <path> (pre-approved, skip Gate 3)`. If none, ASK the user before delegating: the dispatched session cannot answer Gate 3 interactively in non-interactive `run` mode.2147. **Prompt construction & model-craft (cli-* family precedence).** Compose every dispatch prompt via the 2-tier rule canonical in `../../sk-prompt/assets/cli-prompt-quality-card.md`:215 1. **Fast path (default).** Build from the local `assets/prompt-quality-card.md`, which delegates the framework table + CLEAR check to the canonical card. Framework selection uses the canonical card's cross-model defaults, with no per-model prompt-craft profiles.216 2. **Deep path (escalation).** Dispatch `@prompt-improver` via the Task tool (never load full `sk-prompt` inline) when any canonical **Tier 2** trigger applies. The Tier 2 trigger list lives in `../../sk-prompt/assets/cli-prompt-quality-card.md`. Do not re-enumerate it here.2178. Validate dispatched session output: parse JSON events incrementally (tool calls, partial messages, final summary), run syntax checks if code generated, and cross-reference against project standards via `sk-code` surface detection plus its code-review mode for findings-first review (see ALWAYS rule 12).2189. Capture stderr (`2>&1`) to catch tool errors and warnings.21910. Classify the use case (1 / 2 / 3) before dispatching. The smart router refuses dispatches that do not map to one of the three.22011. **Run the Provider Auth Pre-Flight once per session** (see §3 Provider Auth Pre-Flight). Cache the configured-providers list. If the default provider is missing (`llmgateway` on both versions), ASK the user. Never silently substitute the model. If a later dispatch returns an auth error, invalidate the cache and rerun the pre-flight before retrying.22112. **Code Standards Loading (surface-aware contract):** For code review or generation, instruct the session to:222 - (1) Load `sk-code`.223 - (2) Let `sk-code` emit a surface tag matching the detected stack.224 - (3) Load selected surface resources and run its verification commands.225 - (4) Load `sk-code`'s code-review mode only for formal findings-first review output.226 - If the surface cannot be determined confidently, ask for the runtime surface and verification command set.227 - NEVER hardcode obsolete sibling code skills in dispatch prompts.22813. **Design Standards Loading (measured-reference contract):** For design or UI work, instruct the session to:229 - (1) Load `sk-design-md-generator`.230 - (2) Extract a measured Style Reference DESIGN.md (named color tokens, type scale, components, Quick-Start CSS/Tailwind) from the live source before building UI.231 - (3) Build against those measured tokens and run the extraction's validate step to confirm hex/section fidelity.232 - If no live source can be measured, ask for the reference URL or exact tokens.233 - NEVER treat `mcp-figma` or `sk-design-md-generator` as a taste or critique authority. The extraction measures real CSS; it does not judge design.23414. **Pass the design reference manifest to the dispatched session:** For design or UI work, inline a `DESIGN_DISPATCH_MANIFEST v1` block in the prompt.235 - The child cannot resolve skill paths; the manifest must travel in the payload, not by reference.236 - Include `styleReferenceExtracted` true, the measured live `source`, measured design tokens / type scale / components, `loadedFiles` and `proofDemandBack`.237 - If you lack a Style Reference or a live source, ask before launching; do not start a silent dispatch.238 - The child returns the demanded proof. The parent reconciles it on return.23915. **Destructive-scope-violation prevention (RM-8) for deep-loop dispatches.**240 - The permissions-matrix gate (`permissions-gate.ts`) has no production caller. A `--permissions-matrix <path>` config is not enforced and bypasses nothing (wiring status: `references/permissions-matrix.md`).241 - For non-interactive `opencode run` with `--dangerously-skip-permissions` against a populated worktree, you MUST apply the four-layer mitigation, the only active protection:242 - (L1) The rendered prompt contains literal `BANNED OPERATIONS` and `ALLOWED WRITE PATHS`.243 - (L2) The working directory points to a fresh `git worktree` (OpenCode 2: start-in-directory `cd`; OpenCode 1: `--dir <path>`).244 - OpenCode 2 takes the model's working directory from `PWD`, not from the process directory, and names the repository's first checkout as the workspace root. A dispatch from Node `spawn()` with `cwd` must also set `PWD` to that directory, and the prompt carries the `REPOSITORY ROOT` line from the child-dispatch preamble.245 - `scripts/probe-worktree-confinement.cjs` shows whether a dispatch shape stays inside: exit 1 means a tool path left the worktree.246 - (L3) Commit the target's own in-flight changes by explicit path. Leave other sessions' changes alone and record the recovery-baseline commit hash.247 - (L4) For multi-phase / phase-parent targets, prefer `cli-copilot` + `gpt-6-sol --reasoning-effort high` over the DeepSeek V4 Flash default, after confirming that model on the Copilot surface.248 - The 2026-05-04 incident deleted 44 files. See `references/destructive-scope-violations.md` for its root cause and checklist.24916. **Single-dispatch discipline (operator-gated, session-scoped).**250 - Launch ONE cli-* dispatch at a time. Wait for it to return and verify its outputs.251 - Then SIGKILL only the dispatch this skill started, using its captured PID and that PID's own children. Never use a blanket `pkill -9 -f "opencode run"` (see Rule 5).252 - Deep-flow sessions chain iterations back-to-back with kill-between. Explicitly authorized parallel dispatches are each killed by their own PID.253 - Full procedure: [`references/integration-patterns.md`](./references/integration-patterns.md) §8.25417. **Set `AI_SESSION_CHILD=1` in the dispatched session's env AND state the exemption in the prompt.**255 - A model cannot see an environment variable. Given only the variable, a session still asks the documentation-scope question and writes nothing at exit code zero.256 - Copy the preamble from [`shared/references/child-dispatch-preamble.md`](../shared/references/child-dispatch-preamble.md) to the top of every non-interactive prompt.257 - The variable also tells the per-session worktree wrapper (`.skilled/bin/worktree-session.sh`) that dispatched `opencode run` is an orchestrated sub-session sharing the parent's worktree rather than allocating its own.258 - The wrapper checks `AI_SESSION_CHILD` plus a `git --git-common-dir` backstop, then execs in place when set.259 - Pattern: `AI_SESSION_CHILD=1 opencode run ... </dev/null`. Harmless when the wrapper is not in use.260 - See `.skilled/bin/README.md` → "Worktree session isolation".261 - Prepend `SYSTEM_SPEC_GATE_ENFORCE=0` next to it so the child never inherits an enforced spec-gate from the parent shell: `SYSTEM_SPEC_GATE_ENFORCE=0 AI_SESSION_CHILD=1 opencode run ... </dev/null`.26226318. **Agent-persona injection (attach identity, not just the task).** Every dispatch composes `{resolved agent persona + task prompt}`, never a bare task.264 - Resolve the persona from the ACTIVE runtime's agent directory per AGENTS.md §9 (`.opencode/agents/<name>.md`, `.claude/agents/<name>.md`, etc.). Never hardcode one runtime.265 - Map each subtask to the RIGHT agent, not one default: `code`→code, `review`→review, `design`→design, research→`deep-research`, docs→`markdown`.266 - **OpenCode reaches personas via a primary:** route `--agent orchestrate` (or another primary) so the resolved persona runs as a Task subagent. Top-level `--agent` rejects `mode: subagent` personas (see [`references/agent-delegation.md`](./references/agent-delegation.md)).267 - On a bare `opencode run` that names no subagent, **INLINE** the persona block into the payload using the same in-payload pattern as the `DESIGN_DISPATCH_MANIFEST` (Rule 14); the child cannot resolve agent paths by reference.268 - A persona-less dispatch runs the leaf as a generic assistant, silently dropping its tool-scope, verification gates and output contract.269 - Canonical contract: `../../sk-prompt/assets/cli-prompt-quality-card.md` "Persona Injection". Native precedent: `orchestrate.md` "Agent Loading Protocol".270 - Declare rare exceptions at the dispatch site: native surface used, focused summary for a small-context model, or pure-mechanical command.271272### ⛔ NEVER2732741. Invoke this skill from within OpenCode itself for a self-dispatch. Refuse with the documented error message and use a sibling cli-* / fresh shell / parallel-session keywords.2752. Pass `--share`. OpenCode 2 `run` has no such flag, and on OpenCode 1.19.3 (fallback) it is a hidden, deprecated flag that only prints "Session sharing has been discontinued" (see [`references/install-and-versions.md`](./references/install-and-versions.md)).2763. Trust dispatched session output blindly for security-sensitive code, send sensitive data (API keys, passwords, credentials) in prompts, or hammer the API with rapid sequential calls.2774. Use `--pure` outside of plugin debugging (absent from OpenCode 2 `run`, OpenCode 1 only, see [`references/install-and-versions.md`](./references/install-and-versions.md)). Disabling plugins removes the entire point of cli-opencode dispatch.2785. Nest `opencode run` inside a dispatched session's tool calls. Use OpenCode's native Task tool for sub-agent dispatch.279280### ⚠️ ESCALATE IF2812821. OpenCode CLI is not installed and user has not acknowledged (provide `brew install opencode` or `curl -fsSL https://opencode.ai/install | bash`).2832. Operator asks for a share URL. OpenCode 2 `run` has no share flag, and OpenCode 1.19.3 discontinued session sharing, so say there is no URL to publish.2843. Binary version differs from the OpenCode 2 (2.3.0, expected) or OpenCode 1 (1.19.4, fallback) baseline. Run `opencode --version` (`opencode1 --version` for the side-by-side OpenCode 1) and `run --help`, then surface drift and fall back or require approval.2854. Smart router cannot map the prompt to one of the three use cases. Surface the disambiguation checklist from UNKNOWN_FALLBACK.2865. Self-invocation guard trips AND the prompt is ambiguous. Surface the refusal with three remediation options (sibling cli-* / fresh shell / parallel-session keywords).287288### Memory Handback Protocol289290When you need to preserve session context from an OpenCode CLI delegation, run the canonical procedure: extract `MEMORY_HANDBACK`, scrub secrets, and invoke `generate-context.js` via `--stdin`/`--json`/temp-file.291The continuity writer is the last step; nothing is handed to an index.292Full procedure and caveats: [`system-spec-kit/references/cli/memory-handback.md`](../../system-spec-kit/references/cli/memory-handback.md).293294295OpenCode-specific Memory Epilogue template: see [assets/prompt-templates.md](./assets/prompt-templates.md) §14.296297Example invocation:298```bash299printf '%s' "$JSON_PAYLOAD" | node .skilled/skills/system-spec-kit/runtime/cli/dist/continuity/generate-context.js --stdin [spec-folder]300```301302---303304## 5. SUCCESS CRITERIA305306### Task Completion307308- OpenCode CLI invoked with the correct subcommand, flags, model, agent, variant, format, and dir.309- Self-invocation guard checked before dispatch and refused when appropriate.310- Use case (1 / 2 / 3) classified explicitly before invocation.311- JSON event stream captured, parsed incrementally, validated, integrated.312- No security vulnerabilities introduced from generated code.313- No dispatch passes `--share` (absent from OpenCode 2 `run`, discontinued on OpenCode 1 1.19.3).314- Background dispatches in `while read` loops include `</dev/null` redirect.315- Memory Handback extracted and saved through `generate-context.js` when applicable.316317### Skill Quality318319- All numbered sections present and correctly ordered.320- Smart routing covers all intent signals with UNKNOWN_FALLBACK.321- Reference files provide deep-dive content without duplication.322- Self-invocation guard detail in [`ROUTER.md`](./ROUTER.md) mirrors ADR-001.323324---325326## 6. INTEGRATION POINTS327328### Framework Integration329330This skill operates within the behavioral framework defined in [AGENTS.md](../../../../AGENTS.md).331332Key integrations:333- **Gate 2**: Skill routing via the Skill Advisor Hook (or `skill_advisor.py` fallback)334- **Tool Routing**: Per AGENTS.md Section 5 decision tree335- **Continuity**: Context preserved by `/speckit:save`, which writes through `generate-context.js`336- **Validation**: `bash .skilled/skills/system-spec-kit/runtime/cli/spec/validate.sh` for spec-folder workflows337338**Tool roles**: Bash dispatches the CLI. Read/Glob/Grep validate output and probe `~/.opencode/state/` for session locks.339340---341342## 7. REFERENCES AND RELATED RESOURCES343344### Core References345346- [cli-reference.md](./references/cli-reference.md) - Full subcommand/flag reference, provider auth pre-flight, models, version drift347- [integration-patterns.md](./references/integration-patterns.md) - 3 use cases, decision tree, silent stdin348- [self-invocation-guard.md](./references/self-invocation-guard.md) - ADR-001 layered bash + python detection contract349- [opencode-tools.md](./references/opencode-tools.md) - Unique value props vs sibling cli-* skills350- [agent-delegation.md](./references/agent-delegation.md) - Agent routing matrix, leaf-agent constraints351- [destructive-scope-violations.md](./references/destructive-scope-violations.md) - RM-8 incident, root cause, four-layer prevention playbook352- [install-and-versions.md](./references/install-and-versions.md) - Install recipes, side-by-side layout, version detection and the capability delta353- [providers-and-models.md](./references/providers-and-models.md) - The provider, model and variant-effort roster354- [permissions-matrix.md](./references/permissions-matrix.md) - Matrix schema, resolution semantics and RM-8 replay reasoning355- [context-budget.md](./references/context-budget.md) - Model context windows and the truncation marker for bounded prompts356357### Templates and Assets358359- [prompt-templates.md](./assets/prompt-templates.md) - Copy-paste templates per use case + agent + handback360- [prompt-quality-card.md](./assets/prompt-quality-card.md) - Executor-specific model overrides, delegating the framework/CLEAR check to the canonical card361362### Shared (cli-* family)363- [shared-smart-router.md](../../system-spec-kit/references/cli/shared-smart-router.md) - Helper-function bodies for the smart router.364- [memory-handback.md](../../system-spec-kit/references/cli/memory-handback.md) - Canonical 7-step Memory Handback procedure.365366### External367- [OpenCode GitHub](https://github.com/sst/opencode) - Official repository368- [OpenCode Install](https://opencode.ai/install) - Standalone installer entry point369- [OpenCode Documentation](https://opencode.ai/docs) - Official docs370371### Reference Loading Notes372373- Smart Routing (Section 2) is the summary. [`ROUTER.md`](./ROUTER.md) is the single routing authority.374- The router discovers reference, asset, and script docs dynamically: resources from `references/`, templates from `assets/`, automation from `scripts/` when present.375376### Related Skills377378`cli-claude-code` and `cli-opencode` for sibling cross-AI dispatch, `system-spec-kit` for handback, `sk-code` plus the selected overlay for generated code, `system-deep-loop` for loop execution (its `research` and `review` modes), and `mcp-code-mode` for MCP-backed tools.