Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(providers): add opencode CLI provider (#436)

baked frosty7ee5fd40039d
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 119dddd6b..95692ae12 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -90,6 +90,27 @@ repowise/
- Keep functions small and focused
- Write docstrings for public APIs
+### Adding a new LLM provider
+
+1. **Create `packages/core/src/repowise/core/providers/llm/<name>.py`**
+ - Subclass `BaseProvider` and implement `generate()`, `provider_name`, `model_name`
+ - For local CLI providers, use `asyncio.create_subprocess_exec` (never `shell=True`), validate user-supplied model names against a safe character set, and resolve paths with `Path.resolve()`
+ - See `opencode.py` for a clean reference implementation
+
+2. **Register** in `registry.py` — add to `_BUILTIN_PROVIDERS` and the `_missing` package map
+
+3. **Wire up configuration** in these files:
+ - `rate_limiter.py` — add `RateLimitConfig` to `PROVIDER_DEFAULTS`
+ - `provider_config.py` — add entry to `PROVIDER_CATALOG`
+ - `provider_selection.py` — add to `_PROVIDER_DEFAULTS`, `_PROVIDER_ENV`, `_PROVIDER_SIGNUP`, and detection
+ - `helpers.py` — add validation in `validate_provider_config()`
+
+4. **Update the web UI** — add to `PROVIDERS`, `MODEL_PLACEHOLDERS`, and `PROVIDER_ENV_VARS` in `provider-section.tsx` and `run-config-form.tsx`
+
+5. **Add tests** in `tests/unit/test_providers/` — mock the subprocess, test success/error/timeout paths (see `test_codex_cli_provider.py` for the pattern)
+
+6. **Write docs** — `docs/<NAME>.md` and `website/<name>.md`, following `docs/CODEX.md` and `docs/OPENCODE.md`.
+
Adding a new language or LLM provider has a dedicated recipe — see
[docs/LANGUAGE_SUPPORT.md](../docs/LANGUAGE_SUPPORT.md).
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 4579cf797..6382f493b 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -9,6 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
---
+## [Unreleased]
+
+### Added
+- **OpenCode CLI provider.** A new local OpenCode LLM provider runs documentation generation through the local OpenCode CLI via `opencode run --format json`. Uses `asyncio.create_subprocess_exec` (no shell), parses JSONL output, validates model names against a safe character set, and treats `opencode/*` cost as `$0.00`. No API keys are stored — OpenCode manages its own auth and model selection through its provider system. Interactive selection detects the OpenCode CLI on `PATH` and shows helpful install/setup instructions when it's missing.
+
+---
+
## [0.18.0] — 2026-06-08
### Added
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
index 9b5e73940..fbcfc935e 100644
--- a/docs/CLI_REFERENCE.md
+++ b/docs/CLI_REFERENCE.md
@@ -50,7 +50,7 @@ In workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (
| Flag | Description |
|------|-------------|
-| `--provider` | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `codex_cli`, `mock` |
+| `--provider` | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `codex_cli`, `opencode`, `mock` |
| `--model` | Model name override (e.g., `claude-sonnet-4-6`) |
| `--embedder` | Embedder for semantic search: `gemini`, `openai`, `mock` |
| `--index-only` | Skip LLM generation. Only parse, build graph, and index git. Free. |
@@ -79,6 +79,7 @@ In workspace mode, adds: repo scanning, per-repo indexing, cross-repo analysis (
repowise init # interactive
repowise init --provider anthropic --yes # automated
repowise init --provider codex_cli --codex --yes # use authenticated Codex CLI
+repowise init --provider opencode --yes # use local OpenCode CLI
repowise init --index-only # free, no LLM
repowise init --dry-run # preview cost
repowise init --test-run # quick test (10 files)
diff --git a/docs/OPENCODE.md b/docs/OPENCODE.md
new file mode 100644
index 000000000..ff35ab710
--- /dev/null
+++ b/docs/OPENCODE.md
@@ -0,0 +1,117 @@
+# OpenCode Integration
+
+Repowise supports OpenCode via the `opencode` LLM provider, which runs
+documentation generation through your local OpenCode CLI installation.
+No API keys are managed by repowise — OpenCode handles all authentication
+and model selection through its own provider system.
+
+## Prerequisites
+
+Install OpenCode:
+
+```bash
+curl -fsSL https://opencode.ai/install | bash
+```
+
+Then run `opencode` once to set up your model provider and authentication:
+
+```bash
+opencode
+```
+
+Verify the CLI is available:
+
+```bash
+opencode --version
+```
+
+Repowise detects OpenCode automatically: when `opencode` is in `PATH`,
+the interactive provider selection shows it as "available" and it can
+be used immediately.
+
+## `opencode` Provider
+
+Use `opencode` when you want Repowise page generation to run through
+your local OpenCode CLI instead of an API key:
+
+```bash
+repowise init --provider opencode --yes
+```
+
+You can also persist it:
+
+```bash
+REPOWISE_PROVIDER=opencode repowise update
+```
+
+The provider runs:
+
+```bash
+opencode run --format json --dangerously-skip-permissions --dir /absolute/path/to/repo
+```
+
+Repowise sends the combined system + user prompt on **stdin**, parses
+OpenCode's **JSONL** output (extracting text from `text` events and
+token usage from `step_finish` events), and treats `opencode/*` cost
+as `$0.00` because billing is handled by OpenCode's own subscription/auth.
+
+### Default model
+
+`opencode/default` uses OpenCode's configured default model — no
+`--model` flag is passed. To use a specific model:
+
+```bash
+repowise init --provider opencode --model opencode/deepseek-v4-pro
+```
+
+Or use a bare model slug (the `opencode/` prefix is optional):
+
+```bash
+repowise init --provider opencode --model deepseek-v4-pro
+```
+
+### Listing available models
+
+```bash
+opencode models # all available models
+opencode models opencode # models from the opencode provider
+```
+
+### Reasoning
+
+The opencode provider does not pass reasoning effort flags. OpenCode
+handles reasoning internally through its own model/agent configuration.
+
+## Security
+
+The provider enforces several safety measures:
+
+- Uses `asyncio.create_subprocess_exec` (no shell), so every argument
+ is passed as a distinct list element — shell injection is impossible.
+- Model names are validated against a safe character set
+ (`[a-zA-Z0-9][a-zA-Z0-9._/\-]*`), rejecting shell metacharacters
+ before anything reaches the subprocess.
+- All paths are resolved with `Path.resolve()` before being passed to
+ `--dir`.
+- Subprocess execution is serialized via `asyncio.Semaphore(1)`.
+- A 600-second hard timeout with process kill prevents runaway calls.
+
+## Comparison with Codex CLI
+
+| Aspect | `opencode` | `codex_cli` |
+|--------|-----------|-------------|
+| CLI command | `opencode run` | `codex exec` |
+| Auth | OpenCode providers | `codex login` |
+| Output format | JSONL via `--format json` | JSONL via `--json` |
+| Reasoning modes | Not passed (OpenCode manages it) | `model_reasoning_effort` mapping |
+| Sandbox | OpenCode manages its own | `--sandbox read-only` |
+| Model discovery | `opencode models` | `codex debug models --bundled` |
+| Editor integration | None | `.codex/config.toml`, hooks, plugin |
+| API keys stored | No | No |
+
+## Official OpenCode Docs
+
+- [OpenCode](https://opencode.ai)
+- [OpenCode GitHub](https://github.com/anomalyco/opencode)
+- [OpenCode Docs](https://opencode.ai/docs)
+- [OpenCode Download](https://opencode.ai/download)
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md
index 9012bfdf2..7970cbda8 100644
--- a/docs/architecture/ARCHITECTURE.md
+++ b/docs/architecture/ARCHITECTURE.md
@@ -1618,7 +1618,7 @@ Key files:
Full configuration with defaults (`.repowise/config.yaml`):
```yaml
-provider: anthropic # anthropic | openai | openrouter | gemini | deepseek | ollama | litellm | mock
+provider: anthropic # anthropic | openai | openrouter | gemini | deepseek | ollama | litellm | codex_cli | opencode | mock
model: claude-sonnet-4-5 # passed through to the provider
embedding_provider: anthropic
embedding_model: voyage-3
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
index 7cee2402c..fc9e30036 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py
@@ -207,7 +207,7 @@ def _run_generation_phase(
default=None,
help=(
"LLM provider name (anthropic, openai, openrouter, gemini, "
- "deepseek, ollama, litellm, codex_cli, mock)."
+ "deepseek, ollama, litellm, codex_cli, opencode, mock)."
),
)
@click.option("--model", default=None, help="Model identifier override.")
diff --git a/packages/cli/src/repowise/cli/cost_estimator/pricing.py b/packages/cli/src/repowise/cli/cost_estimator/pricing.py
index d26ffeed3..7ef07508b 100644
--- a/packages/cli/src/repowise/cli/cost_estimator/pricing.py
+++ b/packages/cli/src/repowise/cli/cost_estimator/pricing.py
@@ -36,6 +36,7 @@ _COST_TABLE_PREFIX: dict[str, tuple[float, float]] = {
"llama": (0.0, 0.0),
"mock": (0.0, 0.0),
"codex_cli/": (0.0, 0.0),
+ "opencode/": (0.0, 0.0),
}
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index d82c84fe2..10d18953a 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -706,6 +706,8 @@ def resolve_provider(
kwargs["base_url"] = base_url
if provider_name == "codex_cli" and repo_path is not None:
kwargs["repo_path"] = repo_path
+ if provider_name == "opencode" and repo_path is not None:
+ kwargs["repo_path"] = repo_path
# Pass API key from environment if available
if provider_name == "anthropic" and os.environ.get("ANTHROPIC_API_KEY"):
@@ -787,7 +789,7 @@ def resolve_provider(
"or set ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / "
"OLLAMA_BASE_URL / GEMINI_API_KEY / GOOGLE_API_KEY / DEEPSEEK_API_KEY / "
"LITELLM_API_KEY. Use REPOWISE_PROVIDER=codex_cli to use an authenticated "
- "Codex CLI subscription."
+ "Codex CLI subscription, or REPOWISE_PROVIDER=opencode to use opencode."
)
@@ -837,6 +839,19 @@ def validate_provider_config(provider_name: str | None = None) -> list[str]:
)
return warnings
+ if provider_name == "opencode":
+ import shutil
+ if not shutil.which("opencode"):
+ warnings.append(
+ "Provider 'opencode' requires the opencode CLI.\n"
+ " Install: curl -fsSL https://opencode.ai/install | bash\n"
+ " Setup: run 'opencode' once to configure your provider\n"
+ " Models: opencode models (list available models)\n"
+ " More: https://opencode.ai\n"
+ " Usage: repowise init --provider opencode --model opencode/openai/gpt-5"
+ )
+ return warnings
+
# Validate specific provider
if provider_name not in provider_env_vars:
warnings.append(f"Unknown provider '{provider_name}' - cannot validate configuration")
diff --git a/packages/cli/src/repowise/cli/ui/provider_selection.py b/packages/cli/src/repowise/cli/ui/provider_selection.py
index d63ca765e..2a2886d78 100644
--- a/packages/cli/src/repowise/cli/ui/provider_selection.py
+++ b/packages/cli/src/repowise/cli/ui/provider_selection.py
@@ -26,6 +26,7 @@ _PROVIDER_DEFAULTS: dict[str, str] = {
"anthropic": "claude-sonnet-4-6",
"deepseek": "deepseek-v4-flash",
"codex_cli": "codex_cli/default",
+ "opencode": "opencode/default",
"ollama": "llama3.2",
"openrouter": "anthropic/claude-sonnet-4.6",
"litellm": "groq/llama-3.1-70b-versatile",
@@ -37,6 +38,7 @@ _PROVIDER_ENV: dict[str, str] = {
"anthropic": "ANTHROPIC_API_KEY",
"deepseek": "DEEPSEEK_API_KEY",
"codex_cli": "__CODEX_CLI__",
+ "opencode": "__OPENCODE_CLI__",
"ollama": "OLLAMA_BASE_URL",
"openrouter": "OPENROUTER_API_KEY",
}
@@ -47,6 +49,7 @@ _PROVIDER_SIGNUP: dict[str, str] = {
"anthropic": "https://console.anthropic.com/settings/keys",
"deepseek": "https://platform.deepseek.com/api_keys",
"codex_cli": "https://developers.openai.com/codex/cli",
+ "opencode": "https://opencode.ai",
"ollama": "https://ollama.com/download",
"openrouter": "https://openrouter.ai/keys",
}
@@ -69,6 +72,13 @@ def _detect_codex_cli_status() -> tuple[bool, bool]:
return installed, is_codex_logged_in() if installed else False
+def _detect_opencode_status() -> bool:
+ """Return ``True`` if the opencode CLI is installed on PATH."""
+ import shutil
+
+ return shutil.which("opencode") is not None
+
+
def _detect_provider_status() -> dict[str, str]:
"""Return {provider: env_var_name} for providers whose key is set."""
status: dict[str, str] = {}
@@ -80,6 +90,9 @@ def _detect_provider_status() -> dict[str, str]:
installed, logged_in = _detect_codex_cli_status()
if installed and logged_in:
status[prov] = "codex CLI"
+ elif prov == "opencode":
+ if _detect_opencode_status():
+ status[prov] = "opencode CLI"
elif os.environ.get(env_var):
status[prov] = env_var
return status
@@ -120,6 +133,11 @@ def _interactive_provider_name(
status_text = "[yellow]✗ codex login required[/yellow]"
else:
status_text = "[dim]✗ codex CLI not found[/dim]"
+ elif prov == "opencode":
+ if _detect_opencode_status():
+ status_text = f"[{OK}]✓ opencode CLI available[/]"
+ else:
+ status_text = "[dim]✗ opencode CLI not found[/dim]"
else:
status_text = f"[{OK}]✓ API key set[/]" if prov in detected else "[dim]✗ no key[/dim]"
default_model = _PROVIDER_DEFAULTS.get(prov, "")
@@ -129,6 +147,8 @@ def _interactive_provider_name(
label = f"{prov} [dim](recommended)[/dim]"
elif prov == "codex_cli":
label = f"{prov} [dim](uses Codex CLI auth)[/dim]"
+ elif prov == "opencode":
+ label = f"{prov} [dim](uses opencode CLI auth)[/dim]"
table.add_row(f"[{idx}]", label, status_text, default_model)
console.print()
@@ -175,6 +195,28 @@ def _interactive_provider_name(
"or select another provider.[/]"
)
return _interactive_provider_name(console, model_flag, repo_path=repo_path)
+ if chosen == "opencode":
+ console.print()
+ console.print(
+ " [bold]opencode[/bold] is a local AI coding CLI that manages its own "
+ "models and authentication."
+ )
+ console.print()
+ console.print(f" Install: [{BRAND}]curl -fsSL https://opencode.ai/install | bash[/]")
+ console.print(f" Setup: [{BRAND}]opencode[/] (first run sets up your provider)")
+ console.print(f" Models: [{BRAND}]opencode models[/] (list available models)")
+ console.print(f" More info: [{BRAND}]https://opencode.ai[/]")
+ console.print()
+ console.print(
+ f" To use a specific model: [{BRAND}]repowise init --provider opencode "
+ "--model opencode/deepseek/deepseek-v4-pro[/]"
+ )
+ console.print()
+ console.print(
+ f" [{WARN}]opencode CLI not detected. Install it and retry, "
+ "or select another provider.[/]"
+ )
+ return _interactive_provider_name(console, model_flag, repo_path=repo_path)
env_var = _PROVIDER_ENV[chosen]
signup_url = _PROVIDER_SIGNUP.get(chosen, "")
console.print()
diff --git a/packages/core/src/repowise/core/generation/cost_tracker.py b/packages/core/src/repowise/core/generation/cost_tracker.py
index 4994de761..5f5f344d6 100644
--- a/packages/core/src/repowise/core/generation/cost_tracker.py
+++ b/packages/core/src/repowise/core/generation/cost_tracker.py
@@ -65,6 +65,8 @@ def _get_pricing(model: str) -> dict[str, float]:
"""Return pricing for *model*, falling back and warning if unknown."""
if model.startswith("codex_cli/"):
return {"input": 0.0, "output": 0.0}
+ if model.startswith("opencode/"):
+ return {"input": 0.0, "output": 0.0}
if model in _PRICING:
return _PRICING[model]
if model not in _warned_models:
diff --git a/packages/core/src/repowise/core/providers/llm/__init__.py b/packages/core/src/repowise/core/providers/llm/__init__.py
index 650e07041..b44ee36f8 100644
--- a/packages/core/src/repowise/core/providers/llm/__init__.py
+++ b/packages/core/src/repowise/core/providers/llm/__init__.py
@@ -17,6 +17,7 @@ Built-in providers:
ollama — local inference (llama3.2, codellama, etc.)
litellm — 100+ providers via LiteLLM proxy
codex_cli — local authenticated Codex CLI via codex exec
+ opencode — local opencode CLI via opencode run
mock — deterministic test provider
"""
diff --git a/packages/core/src/repowise/core/providers/llm/opencode.py b/packages/core/src/repowise/core/providers/llm/opencode.py
new file mode 100644
index 000000000..0a39f17b2
--- /dev/null
+++ b/packages/core/src/repowise/core/providers/llm/opencode.py
@@ -0,0 +1,431 @@
+"""OpenCode CLI provider for repowise.
+
+This provider delegates generation to the local OpenCode CLI via ``opencode run``.
+It uses the user's existing OpenCode installation and authentication (``opencode providers``)
+without requiring a separate API key.
+
+Security: uses ``asyncio.create_subprocess_exec`` (no shell), validates model names
+against a safe character set, resolves all paths before passing them to the
+subprocess, and enforces a read-only permission profile via ``OPENCODE_CONFIG_CONTENT``
+(highest-precedence config that a project-local ``opencode.json`` cannot loosen).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import json
+import os
+import re
+import shutil
+import subprocess
+from functools import lru_cache
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+from repowise.core.providers.llm.base import (
+ BaseProvider,
+ CacheHint,
+ GeneratedResponse,
+ ProviderError,
+ ProviderModelOption,
+)
+from repowise.core.rate_limiter import RateLimiter
+from repowise.core.reasoning import ReasoningMode
+
+log = structlog.get_logger(__name__)
+
+_DEFAULT_MODEL_LABEL = "opencode/default"
+_EXEC_TIMEOUT_SECONDS = 600
+_CATALOG_TIMEOUT_SECONDS = 10
+_MAX_STDERR_CHARS = 1_000
+
+_MODEL_NAME_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._/\-]*$")
+
+_OPENCODE_READONLY_CONFIG = json.dumps(
+ {"permission": {k: "deny" for k in
+ ("edit", "bash", "webfetch", "websearch", "external_directory", "doom_loop", "task")}}
+)
+
+
+def _resolve_opencode_executable() -> str | None:
+ return shutil.which("opencode")
+
+
+def _validate_model_name(model: str) -> None:
+ if not _MODEL_NAME_RE.match(model):
+ raise ProviderError(
+ "opencode",
+ f"Invalid model name {model!r}. Model names may only contain "
+ "alphanumeric characters, dots, hyphens, underscores, and forward slashes.",
+ )
+
+
+def _normalize_model(model: str | None) -> str | None:
+ if not model:
+ return None
+ if model == _DEFAULT_MODEL_LABEL:
+ return None
+ if model.startswith("opencode/"):
+ suffix = model.removeprefix("opencode/")
+ return suffix or None
+ return model
+
+
+def _model_label(model: str | None) -> str:
+ native = _normalize_model(model)
+ return f"opencode/{native}" if native else _DEFAULT_MODEL_LABEL
+
+
+def _combine_prompt(system_prompt: str, user_prompt: str) -> str:
+ return (
+ "System instructions for this task:\n\n"
+ f"{system_prompt.strip()}\n\n"
+ "---\n\n"
+ "User request and context:\n\n"
+ f"{user_prompt.strip()}"
+ )
+
+
+def _parse_jsonl(stdout: str) -> tuple[str, dict[str, Any]]:
+ content_parts: list[str] = []
+ usage: dict[str, Any] = {}
+
+ for raw_line in stdout.splitlines():
+ line = raw_line.strip()
+ if not line:
+ continue
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+
+ event_type = event.get("type")
+ if event_type == "text":
+ part = event.get("part") or {}
+ text = part.get("text")
+ if isinstance(text, str) and text:
+ content_parts.append(text)
+ elif event_type == "step_finish":
+ part = event.get("part") or {}
+ tokens = part.get("tokens")
+ if isinstance(tokens, dict):
+ for key, value in tokens.items():
+ if isinstance(value, dict):
+ existing = usage.get(key, {})
+ if not isinstance(existing, dict):
+ existing = {}
+ for sub_key, sub_value in value.items():
+ if isinstance(sub_value, (int, float)):
+ existing[sub_key] = existing.get(sub_key, 0) + int(sub_value)
+ usage[key] = existing
+ elif isinstance(value, (int, float)):
+ usage[key] = usage.get(key, 0) + int(value)
+
+ return "\n".join(content_parts), usage
+
+
+def _tail(text: str, max_chars: int = _MAX_STDERR_CHARS) -> str:
+ text = text.strip()
+ if len(text) <= max_chars:
+ return text
+ return text[-max_chars:]
+
+
+def _error_message(stderr: str, stdout: str, returncode: int) -> str:
+ for candidate in (_tail(stderr), _tail(stdout)):
+ if not candidate:
+ continue
+ if candidate.lstrip().startswith(("{", "[")):
+ continue
+ return candidate
+
+ try:
+ for raw_line in stdout.splitlines():
+ line = raw_line.strip()
+ if not line:
+ continue
+ event = json.loads(line)
+ if event.get("type") == "error":
+ err = event.get("error") or {}
+ msg = err.get("data", {}).get("message") or err.get("name", "")
+ if msg:
+ return str(msg)
+ except Exception:
+ pass
+
+ return f"opencode run exited with {returncode}"
+
+
+_MODEL_LINE_RE = re.compile(
+ r"^\s*([a-zA-Z0-9][a-zA-Z0-9._\-]*)/([a-zA-Z0-9][a-zA-Z0-9._/\-]*)\s*$"
+)
+
+
+def _parse_models_output(output: str) -> list[str]:
+ models: list[str] = []
+ for raw_line in output.splitlines():
+ line = raw_line.strip()
+ if not line:
+ continue
+ match = _MODEL_LINE_RE.match(line)
+ if match:
+ provider, model = match.group(1), match.group(2)
+ models.append(f"{provider}/{model}")
+ return models
+
+
+@lru_cache(maxsize=4)
+def _load_opencode_model_catalog(opencode_cmd: str) -> list[str] | None:
+ try:
+ completed = subprocess.run(
+ [opencode_cmd, "models"],
+ capture_output=True,
+ check=False,
+ text=True,
+ timeout=_CATALOG_TIMEOUT_SECONDS,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+
+ if completed.returncode != 0:
+ return None
+
+ return _parse_models_output(completed.stdout) or None
+
+
+def _opencode_model_options(
+ opencode_cmd: str,
+) -> tuple[ProviderModelOption, ...]:
+ catalog = _load_opencode_model_catalog(opencode_cmd)
+ if catalog is None:
+ return (
+ ProviderModelOption(
+ model=_DEFAULT_MODEL_LABEL,
+ label="OpenCode default",
+ reasoning_modes=("auto",),
+ recommended=True,
+ source="fallback",
+ notes="uses opencode config",
+ ),
+ )
+
+ options: list[ProviderModelOption] = [
+ ProviderModelOption(
+ model=_DEFAULT_MODEL_LABEL,
+ label="OpenCode default",
+ reasoning_modes=("auto",),
+ recommended=True,
+ source="local",
+ notes="uses opencode config",
+ )
+ ]
+ for model in sorted(catalog):
+ options.append(
+ ProviderModelOption(
+ model=_model_label(model),
+ label=model,
+ reasoning_modes=("auto",),
+ recommended=False,
+ source="local",
+ notes="",
+ )
+ )
+ return tuple(options)
+
+
+class OpenCodeProvider(BaseProvider):
+ """LLM provider backed by ``opencode run``.
+
+ Uses the local opencode CLI for generation. Does not require an API key —
+ opencode manages its own authentication via ``opencode providers``.
+
+ Args:
+ model: Optional model identifier in ``provider/model`` format
+ (e.g. ``deepseek/deepseek-v4-pro``). If omitted or
+ ``opencode/default``, opencode uses its configured default.
+ repo_path: Working directory passed to opencode via ``--dir``.
+ rate_limiter: Serializes subprocess calls by default.
+ """
+
+ def __init__(
+ self,
+ model: str | None = None,
+ repo_path: str | Path | None = None,
+ rate_limiter: RateLimiter | None = None,
+ ) -> None:
+ opencode_cmd = _resolve_opencode_executable()
+ if not opencode_cmd:
+ raise ProviderError(
+ "opencode",
+ "OpenCode CLI is not installed.\n\n"
+ "Installation:\n"
+ " curl -fsSL https://opencode.ai/install | bash\n\n"
+ "After installing, run 'opencode' once to set up your model provider "
+ "and authenticate. No API keys are managed by repowise — opencode "
+ "handles all authentication.\n\n"
+ "To choose a model:\n"
+ " opencode models # list available models\n"
+ " repowise init --provider opencode --model opencode/deepseek/deepseek-v4-pro\n\n"
+ "More info: https://opencode.ai",
+ )
+ self._opencode_cmd = opencode_cmd
+ native = _normalize_model(model)
+ if native is not None:
+ _validate_model_name(native)
+ self._model = native
+ self._repo_path = (
+ Path(repo_path).resolve() if repo_path is not None else Path.cwd().resolve()
+ )
+ self._rate_limiter = rate_limiter
+ self._subprocess_semaphore: asyncio.Semaphore | None = None
+ self._semaphore_loop: asyncio.AbstractEventLoop | None = None
+
+ @property
+ def provider_name(self) -> str:
+ return "opencode"
+
+ @property
+ def model_name(self) -> str:
+ return _model_label(self._model)
+
+ def supported_reasoning_modes(self) -> tuple[ReasoningMode, ...]:
+ return ("auto",)
+
+ def available_model_options(self) -> tuple[ProviderModelOption, ...]:
+ return _opencode_model_options(self._opencode_cmd)
+
+ def _get_semaphore(self) -> asyncio.Semaphore:
+ loop = asyncio.get_running_loop()
+ if self._semaphore_loop is not loop:
+ self._subprocess_semaphore = asyncio.Semaphore(1)
+ self._semaphore_loop = loop
+ return self._subprocess_semaphore # type: ignore[return-value]
+
+ def _build_command(self) -> list[str]:
+ cmd = [
+ self._opencode_cmd,
+ "run",
+ "--format",
+ "json",
+ "--dir",
+ str(self._repo_path),
+ ]
+ if self._model:
+ cmd.extend(["--model", self._model])
+ return cmd
+
+ async def generate(
+ self,
+ system_prompt: str,
+ user_prompt: str,
+ max_tokens: int = 4096,
+ temperature: float = 0.3,
+ request_id: str | None = None,
+ reasoning: ReasoningMode = "auto",
+ cache_hints: tuple[CacheHint, ...] = (),
+ ) -> GeneratedResponse:
+ if self._rate_limiter:
+ await self._rate_limiter.acquire(estimated_tokens=max_tokens)
+
+ cmd = self._build_command()
+ prompt = _combine_prompt(system_prompt, user_prompt)
+ log.debug(
+ "opencode.generate.start",
+ model=self.model_name,
+ repo_path=str(self._repo_path),
+ request_id=request_id,
+ )
+
+ async with self._get_semaphore():
+ try:
+ proc = await asyncio.create_subprocess_exec(
+ *cmd,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env={
+ **os.environ,
+ "OPENCODE_CONFIG_CONTENT": _OPENCODE_READONLY_CONFIG,
+ },
+ )
+ except FileNotFoundError as exc:
+ raise ProviderError(
+ "opencode",
+ "OpenCode CLI not found. Install it with: "
+ "curl -fsSL https://opencode.ai/install | bash",
+ ) from exc
+
+ try:
+ stdout_bytes, stderr_bytes = await asyncio.wait_for(
+ proc.communicate(prompt.encode("utf-8")),
+ timeout=_EXEC_TIMEOUT_SECONDS,
+ )
+ except TimeoutError as exc:
+ proc.kill()
+ with contextlib.suppress(ProcessLookupError):
+ await proc.wait()
+ raise ProviderError(
+ "opencode",
+ f"opencode run timed out after {_EXEC_TIMEOUT_SECONDS} seconds.",
+ ) from exc
+ finally:
+ await _close_subprocess_transport(proc)
+
+ stdout = stdout_bytes.decode("utf-8", errors="replace") if stdout_bytes else ""
+ stderr = stderr_bytes.decode("utf-8", errors="replace") if stderr_bytes else ""
+
+ if proc.returncode != 0:
+ raise ProviderError(
+ "opencode",
+ _error_message(stderr, stdout, proc.returncode),
+ status_code=proc.returncode,
+ )
+
+ content, usage = _parse_jsonl(stdout)
+ if not content:
+ raise ProviderError(
+ "opencode",
+ "opencode run completed but no text was found in JSONL output.",
+ )
+
+ usage_missing = not usage
+ input_tokens = int(usage.get("input", 0) or 0)
+ output_tokens = int(usage.get("output", 0) or 0)
+ cached_tokens = int((usage.get("cache") or {}).get("read", 0) or 0)
+
+ log.debug(
+ "opencode.generate.done",
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cached_tokens=cached_tokens,
+ request_id=request_id,
+ )
+ usage_payload = {
+ **usage,
+ "source": "opencode_run",
+ "model": self.model_name,
+ "stderr": _tail(stderr) if stderr.strip() else "",
+ }
+ if usage_missing:
+ usage_payload["estimated"] = True
+
+ return GeneratedResponse(
+ content=content,
+ input_tokens=input_tokens,
+ output_tokens=output_tokens,
+ cached_tokens=cached_tokens,
+ usage=usage_payload,
+ )
+
+
+async def _close_subprocess_transport(proc: asyncio.subprocess.Process) -> None:
+ transport = getattr(proc, "_transport", None)
+ close = getattr(transport, "close", None)
+ if not callable(close):
+ return
+ with contextlib.suppress(Exception):
+ close()
+ await asyncio.sleep(0)
diff --git a/packages/core/src/repowise/core/providers/llm/registry.py b/packages/core/src/repowise/core/providers/llm/registry.py
index 8b2699ffd..19d35a025 100644
--- a/packages/core/src/repowise/core/providers/llm/registry.py
+++ b/packages/core/src/repowise/core/providers/llm/registry.py
@@ -12,6 +12,7 @@ Built-in providers:
- ollama → OllamaProvider
- litellm → LiteLLMProvider
- codex_cli → CodexCliProvider
+ - opencode → OpenCodeProvider
- mock → MockProvider (testing only)
Custom provider registration:
@@ -46,6 +47,7 @@ _BUILTIN_PROVIDERS: dict[str, tuple[str, str]] = {
"litellm": ("repowise.core.providers.llm.litellm", "LiteLLMProvider"),
"deepseek": ("repowise.core.providers.llm.deepseek", "DeepSeekProvider"),
"codex_cli": ("repowise.core.providers.llm.codex_cli", "CodexCliProvider"),
+ "opencode": ("repowise.core.providers.llm.opencode", "OpenCodeProvider"),
"mock": ("repowise.core.providers.llm.mock", "MockProvider"),
}
@@ -123,7 +125,7 @@ def get_provider(
raise ValueError(f"Unknown provider: {name!r}. Available providers: {available}")
# Attach rate limiter (skip for mock — tests should run without limits)
- if with_rate_limiter and name not in ("mock", "codex_cli"):
+ if with_rate_limiter and name not in ("mock", "codex_cli", "opencode"):
config = rate_limit_config or PROVIDER_DEFAULTS.get(name)
if config and "rate_limiter" not in kwargs:
kwargs["rate_limiter"] = RateLimiter(config)
@@ -142,6 +144,7 @@ def get_provider(
"deepseek": "openai", # deepseek uses the openai package
"litellm": "litellm",
"codex_cli": "@openai/codex",
+ "opencode": "opencode",
}
package = _missing.get(name, name)
raise ImportError(
diff --git a/packages/server/src/repowise/server/provider_config.py b/packages/server/src/repowise/server/provider_config.py
index 5506272e6..9949126f1 100644
--- a/packages/server/src/repowise/server/provider_config.py
+++ b/packages/server/src/repowise/server/provider_config.py
@@ -84,6 +84,14 @@ PROVIDER_CATALOG: list[dict[str, Any]] = [
"env_keys": [],
"requires_key": True,
},
+ {
+ "id": "opencode",
+ "name": "OpenCode (Local CLI)",
+ "default_model": "opencode/default",
+ "models": ["opencode/default", "opencode/openai/gpt-5", "opencode/deepseek/deepseek-v4-pro"],
+ "env_keys": [],
+ "requires_key": False,
+ },
]
_CATALOG_BY_ID = {p["id"]: p for p in PROVIDER_CATALOG}
diff --git a/packages/web/src/components/repos/run-config-form.tsx b/packages/web/src/components/repos/run-config-form.tsx
index 51b5efc5f..6decee46f 100644
--- a/packages/web/src/components/repos/run-config-form.tsx
+++ b/packages/web/src/components/repos/run-config-form.tsx
@@ -27,7 +27,7 @@ interface Props {
onChange: (v: RunConfig) => void;
}
-const PROVIDERS = ["litellm", "openai", "anthropic", "gemini", "deepseek", "ollama", "mock"] as const;
+const PROVIDERS = ["litellm", "openai", "anthropic", "gemini", "deepseek", "opencode", "ollama", "mock"] as const;
export function RunConfigForm({ value, onChange }: Props) {
// Seed from saved settings on mount
diff --git a/packages/web/src/components/settings/provider-section.tsx b/packages/web/src/components/settings/provider-section.tsx
index c1ec73309..16aa2fc17 100644
--- a/packages/web/src/components/settings/provider-section.tsx
+++ b/packages/web/src/components/settings/provider-section.tsx
@@ -14,7 +14,7 @@ import {
SelectValue,
} from "@repowise-dev/ui/ui/select";
-const PROVIDERS = ["gemini", "openai", "anthropic", "deepseek", "ollama", "litellm", "mock"] as const;
+const PROVIDERS = ["gemini", "openai", "anthropic", "deepseek", "opencode", "ollama", "litellm", "mock"] as const;
const EMBEDDERS = ["mock", "gemini", "openai", "openrouter", "ollama"] as const;
const MODEL_PLACEHOLDERS: Record<string, string> = {
@@ -22,6 +22,7 @@ const MODEL_PLACEHOLDERS: Record<string, string> = {
openai: "gpt-5.4-nano",
anthropic: "claude-sonnet-4-6",
deepseek: "deepseek-v4-flash",
+ opencode: "opencode/default",
ollama: "llama3.2",
litellm: "groq/llama-3.1-70b-versatile",
mock: "mock",
@@ -34,6 +35,7 @@ const PROVIDER_ENV_VARS: Record<string, { vars: string[]; installHint: string }>
ollama: { vars: ["OLLAMA_BASE_URL"], installHint: "https://ollama.ai" },
deepseek: { vars: ["DEEPSEEK_API_KEY"], installHint: "pip install openai" },
litellm: { vars: ["LITELLM_*"], installHint: "pip install litellm" },
+ opencode: { vars: [], installHint: "curl -fsSL https://opencode.ai/install | bash" },
mock: { vars: [], installHint: "No key needed" },
};
diff --git a/tests/providers/test_registry.py b/tests/providers/test_registry.py
index cdc66d622..53be94f56 100644
--- a/tests/providers/test_registry.py
+++ b/tests/providers/test_registry.py
@@ -116,5 +116,5 @@ class TestCustomProviderRegistration:
assert received.get("api_key") == "key-123"
def test_builtin_count(self) -> None:
- """Sanity check: we have exactly 9 built-in providers."""
- assert len(_BUILTIN_PROVIDERS) == 9
+ """Sanity check: we have exactly 10 built-in providers."""
+ assert len(_BUILTIN_PROVIDERS) == 10
diff --git a/tests/unit/test_providers/test_opencode_provider.py b/tests/unit/test_providers/test_opencode_provider.py
new file mode 100644
index 000000000..136aaa4c9
--- /dev/null
+++ b/tests/unit/test_providers/test_opencode_provider.py
@@ -0,0 +1,466 @@
+"""Unit tests for OpenCodeProvider.
+
+All tests mock the opencode subprocess; no real opencode CLI calls are made.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from typing import Any
+
+import pytest
+
+from repowise.core.providers.llm.base import GeneratedResponse, ProviderError
+from repowise.core.providers.llm.opencode import (
+ OpenCodeProvider,
+ _parse_models_output,
+ _validate_model_name,
+)
+
+
+class FakeProcess:
+ def __init__(
+ self,
+ *,
+ returncode: int = 0,
+ stdout: str = "",
+ stderr: str = "",
+ on_communicate: Any | None = None,
+ transport: Any | None = None,
+ ) -> None:
+ self.returncode = returncode
+ self._stdout = stdout
+ self._stderr = stderr
+ self._on_communicate = on_communicate
+ self._transport = transport
+ self.stdin_input: bytes | None = None
+ self.killed = False
+
+ async def communicate(self, input: bytes | None = None) -> tuple[bytes, bytes]:
+ self.stdin_input = input
+ if self._on_communicate is not None:
+ await self._on_communicate()
+ return self._stdout.encode("utf-8"), self._stderr.encode("utf-8")
+
+ def kill(self) -> None:
+ self.killed = True
+
+ async def wait(self) -> int:
+ return self.returncode
+
+
+class FakeTransport:
+ def __init__(self) -> None:
+ self.closed = False
+
+ def close(self) -> None:
+ self.closed = True
+
+
+def _jsonl(*events: dict[str, Any], noise: bool = False) -> str:
+ lines = [json.dumps(event) for event in events]
+ if noise:
+ lines.insert(1, "warning: this is not JSON")
+ return "\n".join(lines) + "\n"
+
+
+def _success_jsonl(text: str = "OK") -> str:
+ return _jsonl(
+ {"type": "step_start", "sessionID": "s1"},
+ {"type": "text", "part": {"text": text}},
+ {
+ "type": "step_finish",
+ "part": {
+ "tokens": {
+ "total": 100,
+ "input": 80,
+ "output": 10,
+ "reasoning": 10,
+ "cache": {"write": 0, "read": 20},
+ },
+ },
+ },
+ noise=True,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Model name validation
+# ---------------------------------------------------------------------------
+
+
+def test_validate_model_name_accepts_valid_names():
+ for name in ["big-pickle", "deepseek-v4-pro", "provider/model", "abc.123_x/y-z"]:
+ _validate_model_name(name)
+
+
+def test_validate_model_name_rejects_shell_metacharacters():
+ for name in ["bad; ls", "name$(whoami)", "name|cat", "`evil`"]:
+ with pytest.raises(ProviderError, match="Invalid model name"):
+ _validate_model_name(name)
+
+
+def test_validate_model_name_rejects_empty():
+ with pytest.raises(ProviderError, match="Invalid model name"):
+ _validate_model_name("")
+
+
+def test_validate_model_name_rejects_leading_space():
+ with pytest.raises(ProviderError, match="Invalid model name"):
+ _validate_model_name(" model")
+
+
+def test_parse_models_output_extracts_provider_model_pairs():
+ output = """
+deepseek/deepseek-v4-pro
+openai/gpt-5
+anthropic/claude-sonnet-4-6
+"""
+ models = _parse_models_output(output)
+ assert models == [
+ "deepseek/deepseek-v4-pro",
+ "openai/gpt-5",
+ "anthropic/claude-sonnet-4-6",
+ ]
+
+
+def test_parse_models_output_ignores_invalid_lines():
+ output = """
+deepseek/deepseek-v4-pro
+some random text
+openai/gpt-5
+
+another invalid line
+"""
+ models = _parse_models_output(output)
+ assert models == ["deepseek/deepseek-v4-pro", "openai/gpt-5"]
+
+
+def test_parse_models_output_empty():
+ assert _parse_models_output("") == []
+ assert _parse_models_output(" \n \n") == []
+
+
+# ---------------------------------------------------------------------------
+# Provider metadata
+# ---------------------------------------------------------------------------
+
+
+def test_provider_name_and_default_model(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ provider = OpenCodeProvider(repo_path=tmp_path)
+
+ assert provider.provider_name == "opencode"
+ assert provider.model_name == "opencode/default"
+
+
+def test_custom_model_is_normalized(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ assert (
+ OpenCodeProvider(
+ model="opencode/deepseek/deepseek-v4-pro", repo_path=tmp_path
+ ).model_name
+ == "opencode/deepseek/deepseek-v4-pro"
+ )
+ assert (
+ OpenCodeProvider(model="opencode/default", repo_path=tmp_path).model_name
+ == "opencode/default"
+ )
+
+
+def test_invalid_model_name_raises(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ with pytest.raises(ProviderError, match="Invalid model name"):
+ OpenCodeProvider(model="bad;name", repo_path=tmp_path)
+
+
+def test_missing_cli_raises(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: None)
+
+ with pytest.raises(ProviderError, match="OpenCode CLI is not installed"):
+ OpenCodeProvider(repo_path=tmp_path)
+
+
+# ---------------------------------------------------------------------------
+# Generation
+# ---------------------------------------------------------------------------
+
+
+async def test_generate_invokes_opencode_with_stdin(monkeypatch, tmp_path):
+ opencode_cmd = str(tmp_path / "bin" / "opencode")
+ monkeypatch.setattr("shutil.which", lambda _cmd: opencode_cmd)
+ captured: dict[str, Any] = {}
+ proc = FakeProcess(stdout=_success_jsonl("Hello from OpenCode"))
+
+ async def fake_exec(*args: str, **kwargs: Any) -> FakeProcess:
+ captured["args"] = args
+ captured["kwargs"] = kwargs
+ return proc
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ provider = OpenCodeProvider(
+ model="opencode/deepseek/deepseek-v4-pro", repo_path=tmp_path
+ )
+ result = await provider.generate("system rules", "user context")
+
+ assert isinstance(result, GeneratedResponse)
+ assert result.content == "Hello from OpenCode"
+ assert proc.stdin_input is not None
+ prompt = proc.stdin_input.decode("utf-8")
+ assert "system rules" in prompt
+ assert "user context" in prompt
+ args = list(captured["args"])
+ assert args[:5] == [opencode_cmd, "run", "--format", "json", "--dir"]
+ assert "--dangerously-skip-permissions" not in args
+ assert args[args.index("--dir") + 1] == str(tmp_path.resolve())
+ assert args[args.index("--model") + 1] == "deepseek/deepseek-v4-pro"
+ assert captured["kwargs"]["stdin"] == asyncio.subprocess.PIPE
+ env = captured["kwargs"].get("env", {})
+ assert "OPENCODE_CONFIG_CONTENT" in env
+ config = json.loads(env["OPENCODE_CONFIG_CONTENT"])
+ assert config["permission"]["edit"] == "deny"
+ assert config["permission"]["bash"] == "deny"
+
+
+async def test_generate_default_model_omits_model_flag(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+ captured: dict[str, Any] = {}
+
+ async def fake_exec(*args: str, **kwargs: Any) -> FakeProcess:
+ captured["args"] = args
+ return FakeProcess(stdout=_success_jsonl("OK"))
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")
+
+ args = list(captured["args"])
+ assert "--model" not in args
+
+
+async def test_generate_parses_jsonl_tokens(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ return FakeProcess(stdout=_success_jsonl("OK"))
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ result = await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")
+
+ assert result.content == "OK"
+ assert result.input_tokens == 80
+ assert result.output_tokens == 10
+ assert result.cached_tokens == 20
+ assert result.usage["source"] == "opencode_run"
+ assert "estimated" not in result.usage
+
+
+async def test_generate_handles_jsonl_noise(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ return FakeProcess(stdout=_success_jsonl("Documentation here"))
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ result = await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")
+
+ assert result.content == "Documentation here"
+
+
+async def test_generate_marks_missing_usage_as_estimated(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ return FakeProcess(
+ stdout=_jsonl(
+ {"type": "step_start"},
+ {"type": "text", "part": {"text": "OK"}},
+ )
+ )
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ result = await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")
+
+ assert result.input_tokens == 0
+ assert result.output_tokens == 0
+ assert result.usage["estimated"] is True
+
+
+async def test_generate_raises_on_nonzero_exit(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ return FakeProcess(returncode=1, stdout="", stderr="not authenticated")
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ with pytest.raises(ProviderError, match="not authenticated"):
+ await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")
+
+
+async def test_generate_raises_when_jsonl_has_no_text(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ return FakeProcess(stdout=_jsonl({"type": "step_finish", "part": {"tokens": {}}}))
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ with pytest.raises(ProviderError, match="no text was found"):
+ await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")
+
+
+async def test_generate_serializes_subprocess_calls(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+ active = 0
+ max_active = 0
+
+ async def on_communicate() -> None:
+ nonlocal active, max_active
+ active += 1
+ max_active = max(max_active, active)
+ await asyncio.sleep(0.01)
+ active -= 1
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ return FakeProcess(stdout=_success_jsonl("OK"), on_communicate=on_communicate)
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+ provider = OpenCodeProvider(repo_path=tmp_path)
+
+ await asyncio.gather(
+ provider.generate("sys", "user 1"),
+ provider.generate("sys", "user 2"),
+ )
+
+ assert max_active == 1
+
+
+async def test_generate_times_out_and_kills_process(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+ monkeypatch.setattr(
+ "repowise.core.providers.llm.opencode._EXEC_TIMEOUT_SECONDS",
+ 0.01,
+ )
+
+ async def on_communicate() -> None:
+ await asyncio.sleep(1)
+
+ proc = FakeProcess(stdout="", on_communicate=on_communicate)
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ return proc
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ with pytest.raises(ProviderError, match="timed out"):
+ await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")
+
+ assert proc.killed
+
+
+async def test_generate_closes_subprocess_transport(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+ transport = FakeTransport()
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ return FakeProcess(stdout=_success_jsonl("OK"), transport=transport)
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")
+
+ assert transport.closed is True
+
+
+async def test_generate_accepts_cache_hints(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ return FakeProcess(stdout=_success_jsonl("OK"))
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ result = await OpenCodeProvider(repo_path=tmp_path).generate(
+ "sys",
+ "user",
+ cache_hints=(),
+ )
+
+ assert result.content == "OK"
+
+
+async def test_generate_handles_error_jsonl(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ return FakeProcess(
+ returncode=1,
+ stdout=_jsonl(
+ {
+ "type": "error",
+ "error": {"name": "APIError", "data": {"message": "Model is disabled"}},
+ }
+ ),
+ stderr="",
+ )
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ with pytest.raises(ProviderError, match="Model is disabled"):
+ await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")
+
+
+async def test_generate_handles_file_not_found(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+
+ async def fake_exec(*_args: str, **_kwargs: Any) -> FakeProcess:
+ raise FileNotFoundError("No such file")
+
+ monkeypatch.setattr("asyncio.create_subprocess_exec", fake_exec)
+
+ with pytest.raises(ProviderError, match="curl -fsSL"):
+ await OpenCodeProvider(repo_path=tmp_path).generate("sys", "user")
+
+
+async def test_available_model_options_with_catalog(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+ monkeypatch.setattr(
+ "repowise.core.providers.llm.opencode._load_opencode_model_catalog",
+ lambda _cmd: ["deepseek/deepseek-v4-pro", "openai/gpt-5"],
+ )
+
+ options = OpenCodeProvider(repo_path=tmp_path).available_model_options()
+
+ assert len(options) == 3
+ assert options[0].model == "opencode/default"
+ assert options[0].recommended is True
+ assert options[0].source == "local"
+ assert options[1].model == "opencode/deepseek/deepseek-v4-pro"
+ assert options[1].label == "deepseek/deepseek-v4-pro"
+ assert options[1].source == "local"
+ assert options[2].model == "opencode/openai/gpt-5"
+ assert options[2].label == "openai/gpt-5"
+
+
+async def test_available_model_options_fallback(monkeypatch, tmp_path):
+ monkeypatch.setattr("shutil.which", lambda _cmd: "opencode")
+ monkeypatch.setattr(
+ "repowise.core.providers.llm.opencode._load_opencode_model_catalog",
+ lambda _cmd: None,
+ )
+
+ options = OpenCodeProvider(repo_path=tmp_path).available_model_options()
+
+ assert len(options) == 1
+ assert options[0].model == "opencode/default"
+ assert options[0].recommended is True
+ assert options[0].source == "fallback"
diff --git a/website/cli-reference.md b/website/cli-reference.md
index edba78cb8..22edf1e1c 100644
--- a/website/cli-reference.md
+++ b/website/cli-reference.md
@@ -44,7 +44,7 @@ repowise init [PATH] [OPTIONS]
| Flag | Type | Default | Description |
|------|------|---------|-------------|
-| `--provider` | string | auto | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `codex_cli`, `mock` |
+| `--provider` | string | auto | LLM provider: `anthropic`, `openai`, `openrouter`, `gemini`, `deepseek`, `ollama`, `litellm`, `codex_cli`, `opencode`, `mock` |
| `--model` | string | — | Model override (e.g., `claude-sonnet-4-6`, `gpt-4.1`) |
| `--embedder` | choice | auto | Embedding provider: `gemini`, `openai`, `mock` |
| `--index-only` | flag | false | Skip LLM generation — parse, graph, git, dead code only |
@@ -76,6 +76,7 @@ repowise init --provider anthropic --yes
# Use the authenticated local Codex CLI
repowise init --provider codex_cli --codex --yes
+repowise init --provider opencode --yes
# OpenAI-compatible Qwen3 endpoint with thinking disabled
repowise init --provider openai --model qwen3 --reasoning off
diff --git a/website/configuration.md b/website/configuration.md
index ebd50c5ea..b5be7de77 100644
--- a/website/configuration.md
+++ b/website/configuration.md
@@ -200,6 +200,22 @@ Use `repowise init --codex` to write `.codex/config.toml` and `.codex/hooks.json
---
+### OpenCode CLI
+
+Use your local OpenCode CLI instead of an API key:
+
+```bash
+curl -fsSL https://opencode.ai/install | bash
+opencode # first-run setup
+repowise init --provider opencode --yes
+```
+
+`opencode/default` uses the OpenCode CLI's configured default model. `opencode/deepseek-v4-pro` passes `--model deepseek-v4-pro` to `opencode run`. Repowise records token usage from OpenCode JSONL output and treats `opencode/*` cost as `$0.00` because billing is handled by OpenCode's own auth/subscription.
+
+OpenCode is detected automatically when installed — no auth setup needed from repowise. Use `opencode providers` to manage authentication and `opencode models` to list available models.
+
+---
+
### Provider auto-detection
If you don't pass `--provider`, repowise detects your provider by checking:
@@ -208,7 +224,7 @@ If you don't pass `--provider`, repowise detects your provider by checking:
2. `provider` in `.repowise/config.yaml`
3. API key environment variables, in order: `ANTHROPIC_API_KEY` → `OPENAI_API_KEY` → `OLLAMA_BASE_URL` → `GEMINI_API_KEY`
-Codex CLI is intentionally explicit: pass `--provider codex_cli` or set `REPOWISE_PROVIDER=codex_cli`.
+Codex CLI is intentionally explicit: pass `--provider codex_cli` or set `REPOWISE_PROVIDER=codex_cli`. Similarly, OpenCode is detected automatically when on `PATH` but can be explicitly selected with `--provider opencode` or `REPOWISE_PROVIDER=opencode`.
---
diff --git a/website/opencode.md b/website/opencode.md
new file mode 100644
index 000000000..64159f04e
--- /dev/null
+++ b/website/opencode.md
@@ -0,0 +1,96 @@
+---
+layout: default
+title: OpenCode Integration
+nav_order: 5.6
+---
+
+# OpenCode Integration
+{: .no_toc }
+
+Use Repowise with OpenCode via the `opencode` LLM provider. No API keys — OpenCode manages auth and model selection.
+{: .fs-6 .fw-300 }
+
+---
+
+## Table of contents
+{: .no_toc .text-delta }
+
+1. TOC
+{:toc}
+
+---
+
+## Quick setup
+
+```bash
+curl -fsSL https://opencode.ai/install | bash
+opencode # first-run setup: configure your provider
+
+cd /path/to/your-repo
+repowise init --provider opencode --yes
+```
+
+OpenCode is detected automatically when it's on `PATH`. No API keys to store.
+
+## Provider
+
+`opencode` uses your local OpenCode CLI:
+
+```bash
+repowise init --provider opencode --yes
+```
+
+It runs:
+
+```bash
+opencode run --format json --dangerously-skip-permissions --dir <repo>
+```
+
+Repowise sends the prompt on **stdin**, parses OpenCode's **JSONL** output, and treats `opencode/*` cost as `$0.00`.
+
+### Model selection
+
+`opencode/default` uses OpenCode's configured default model. To pick a specific model:
+
+```bash
+repowise init --provider opencode --model opencode/deepseek-v4-pro
+```
+
+List available models:
+
+```bash
+opencode models
+```
+
+### Interactive selection
+
+When you run `repowise init` interactively, the provider table includes `opencode` with a status indicator. If OpenCode is installed, it shows as available and you can select it directly.
+
+If OpenCode is not installed, the interactive prompt shows:
+
+```
+Install: curl -fsSL https://opencode.ai/install | bash
+Setup: opencode (first run sets up your provider)
+Models: opencode models (list available models)
+```
+
+## Reasoning
+
+The opencode provider does not pass reasoning effort flags. OpenCode handles reasoning through its own model and agent configuration.
+
+## Comparison with Codex CLI
+
+| Aspect | `opencode` | `codex_cli` |
+|--------|-----------|-------------|
+| CLI | `opencode run` | `codex exec` |
+| Auth | OpenCode providers | `codex login` |
+| Format | `--format json` JSONL | `--json` JSONL |
+| Reasoning | N/A (OpenCode manages) | `model_reasoning_effort` |
+| Editor integration | None | MCP, hooks, plugin |
+| Key storage | No | No |
+
+## Official docs
+
+- [OpenCode](https://opencode.ai)
+- [OpenCode GitHub](https://github.com/anomalyco/opencode)
+- [OpenCode Docs](https://opencode.ai/docs)