implement opencode provider

This commit is contained in:
gabby committed 2026-10-01 06:00:45 +00:00
1 parent 375d37d1f1
commit 4a62e794a5
7 files changed
+500 -13

No files matched your search

+62 -6
View File
@@ -14,11 +14,17 @@ from __future__ import annotations
import argparse
import json
import os
import sys
from pathlib import Path
from .dream import dream as run_dream
from .codegen import CodegenClient
from .console import (
OPENCODE_BASE_URL,
ConsoleCodegenClient,
ConsoleLLMClient,
)
from .decisions import DecisionRequest, Option
from .engine import EngineConfig, EngineUnavailable, SemIfEngine
from .llm import LLMClient
@@ -45,6 +51,41 @@ def _anchor_path(value: str) -> str:
return str(path if path.is_absolute() else REPO_ROOT / path)
def _resolve_api_key(cfg: dict) -> str:
"""Service-account key for an authenticated provider.
A literal `api_key` wins; otherwise `api_key_env` names an environment
variable (preferred, so the secret never lands in config.json).
"""
key = cfg.get("api_key") or ""
if key:
return str(key)
env = cfg.get("api_key_env")
if env:
return os.environ.get(str(env), "")
return ""
def _provider_endpoint(cfg: dict, default_base: str) -> dict:
"""Endpoint kwargs shared by the llm/codegen clients.
`provider` selects the class (`opencode` → the Console client) and the base
URL default: an explicit `base_url` always wins, else the Console URL for
`opencode` and `default_base` (ollama) otherwise. Auth comes from
`api_key`/`api_key_env`; `extra_headers` passes through for custom schemes.
"""
provider = str(cfg.get("provider", "ollama") or "ollama").lower()
base_url = cfg.get("base_url") or (
OPENCODE_BASE_URL if provider == "opencode" else default_base
)
return {
"base_url": base_url,
"api_key": _resolve_api_key(cfg),
"extra_headers": cfg.get("extra_headers") or None,
"user_agent": cfg.get("user_agent"),
}
def load_config(path: str = "config.json") -> dict:
"""Load config.json and anchor its runtime paths to the checkout root.
@@ -71,8 +112,11 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
)
)
llm_cfg = config.get("llm", {}) or {}
llm = LLMClient(
base_url=llm_cfg.get("base_url", "http://localhost:11434/v1"),
llm_provider = str(llm_cfg.get("provider", "ollama") or "ollama").lower()
llm_cls = ConsoleLLMClient if llm_provider == "opencode" else LLMClient
llm_endpoint = _provider_endpoint(llm_cfg, "http://localhost:11434/v1")
llm = llm_cls(
base_url=llm_endpoint["base_url"],
model=llm_cfg.get("model", "qwen2.5:3b"),
timeout=float(llm_cfg.get("timeout", 600.0)),
stream=bool(llm_cfg.get("stream", False)),
@@ -84,15 +128,24 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
presence_penalty=float(llm_cfg.get("presence_penalty", 0.0)),
frequency_penalty=float(llm_cfg.get("frequency_penalty", 0.0)),
disable_thinking=bool(llm_cfg.get("disable_thinking", True)),
api_key=llm_endpoint["api_key"],
extra_headers=llm_endpoint["extra_headers"],
user_agent=llm_endpoint["user_agent"],
)
log = DecisionLog(config.get("log", "data/decisions.jsonl"))
trace = TraceLog(config.get("trace", "data/runs.jsonl"))
codegen_cfg = config.get("codegen", {})
deg_cfg = codegen_cfg.get("degeneration", {}) or {}
codegen = CodegenClient(
base_url=codegen_cfg.get(
"base_url", config.get("llm", {}).get("base_url", "http://localhost:11434/v1")
),
codegen_provider = str(codegen_cfg.get("provider", "ollama") or "ollama").lower()
codegen_cls = (
ConsoleCodegenClient if codegen_provider == "opencode" else CodegenClient
)
codegen_endpoint = _provider_endpoint(
codegen_cfg,
config.get("llm", {}).get("base_url", "http://localhost:11434/v1"),
)
codegen = codegen_cls(
base_url=codegen_endpoint["base_url"],
model=codegen_cfg.get("model", "qwen38-iq3s"),
timeout=float(codegen_cfg.get("timeout", 1200.0)),
stream=bool(codegen_cfg.get("stream", False)),
@@ -113,6 +166,9 @@ def build_scheduler(config: dict) -> tuple[Scheduler, dict]:
presence_penalty=float(codegen_cfg.get("presence_penalty", 1.5)),
frequency_penalty=float(codegen_cfg.get("frequency_penalty", 0.2)),
max_attempts=int(codegen_cfg.get("max_attempts", 3)),
api_key=codegen_endpoint["api_key"],
extra_headers=codegen_endpoint["extra_headers"],
user_agent=codegen_endpoint["user_agent"],
)
def make_degeneration_check(run_id: str):
+124
View File
@@ -0,0 +1,124 @@
"""OpenCode Console provider (hosted, authenticated OpenAI-compatible API).
The `OpenCode Console <https://opencode.ai/console>`_ serves an
OpenAI-compatible Chat Completions API at
``https://opencode.ai/inference/openai/v1``. It is wire-identical to
``provider.OpenAICompatClient`` (SSE ``delta.content`` +
``delta.reasoning_content``, an ``include_usage`` chunk, then ``[DONE]``), so
this module only adds what the Console needs on top of the shared transport:
* a bearer service-account key (``Authorization: Bearer <key>``), and
* ``query_context = False`` — the Console has no ollama ``/api/show``, so the
context window comes from config or the default instead of a stray probe.
Only the **Chat Completions** model family is supported (GLM, DeepSeek, Kimi,
Qwen3.8 Max, MiniMax, and the free models). Claude / OpenAI-Responses / Gemini
models use different wire formats and would need their own adapters.
``build_scheduler`` selects these classes from ``llm.provider`` /
``codegen.provider`` (``"opencode"`` vs the default ``"ollama"``) and passes
``api_key`` (or ``api_key_env``). The error contracts are preserved: the `llm`
variant still raises ``LLMError`` and the codegen variant ``CodegenError`` /
``DegenerationError``, so existing callers keep catching their own types.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.request
from .codegen import CodegenClient, CodegenError, DegenerationError
from .llm import LLMClient, LLMError
from .provider import OpenAICompatClient, ProviderError
OPENCODE_BASE_URL = "https://opencode.ai/inference/openai/v1"
OPENCODE_MODELS_URL = "https://opencode.ai/inference/v1/models"
OPENCODE_USER_AGENT = "semif-agent/0.1"
class OpenCodeError(ProviderError):
"""The OpenCode Console endpoint could not be reached."""
class OpenCodeConsoleClient(OpenAICompatClient):
"""Authenticated OpenAI-compatible client for the OpenCode Console.
Pins the Console defaults: bearer auth, the Console base URL, a Console
label, and ``query_context = False`` (no ollama ``/api/show`` probe). The
endpoint subclasses below reuse it via cooperative multiple inheritance so
they also keep ``LLMClient``/``CodegenClient`` sampler defaults.
A default ``User-Agent`` is always sent: the Console gateway rejects
urllib's default ``Python-urllib/<ver>`` with HTTP 403. Pass ``user_agent``
to override it (the Go docs ask clients to identify themselves).
"""
label = "opencode"
error_class = OpenCodeError
degeneration_error_class = OpenCodeError
query_context = False
def __init__(self, base_url: str = OPENCODE_BASE_URL, **kwargs):
if not kwargs.get("user_agent"):
kwargs["user_agent"] = OPENCODE_USER_AGENT
super().__init__(base_url=base_url, **kwargs)
def list_models(self, url: str | None = None) -> list[str]:
"""Fetch the Console model catalog (``GET /inference/v1/models``).
Returns the model ids; a fresh service-account key is not required for
the free models. Raises the client's own error type when unreachable.
"""
target = url or OPENCODE_MODELS_URL
request = urllib.request.Request(target, headers=self._headers())
try:
with urllib.request.urlopen(
request, timeout=min(self.timeout, 30.0)
) as response:
data = json.loads(response.read().decode("utf-8"))
except (urllib.error.URLError, TimeoutError, ValueError) as exc:
raise self.error_class(
f"{self.label} model list unreachable at {target}: {exc}"
) from exc
return [
item["id"]
for item in (data.get("data") or [])
if isinstance(item, dict) and item.get("id")
]
class ConsoleLLMClient(OpenCodeConsoleClient, LLMClient):
"""Console-backed `llm` author (skill/category title + description).
Same conservative sampler defaults as ``LLMClient``; the Console transport
adds the bearer key and skips the ollama probe. Raises ``LLMError``
(unchanged contract).
``disable_thinking`` is forced **off**: `LLMClient` sends
``reasoning_effort: "none"`` (an ollama-compat knob) and the Console
gateway rejects that parameter with HTTP 400. Console models are not the
local reasoning model the knob exists for, so the parameter is simply not
sent. Passing ``disable_thinking=True`` to the constructor still ends up
off here.
"""
label = "opencode:llm"
error_class = LLMError
degeneration_error_class = LLMError
def __init__(self, *args, **kwargs):
kwargs["disable_thinking"] = False
super().__init__(*args, **kwargs)
class ConsoleCodegenClient(OpenCodeConsoleClient, CodegenClient):
"""Console-backed `codegen` writer (runnable skill bodies).
Console defaults on the codegen transport. Raises ``CodegenError`` /
``DegenerationError`` (unchanged contract).
"""
label = "opencode:codegen"
error_class = CodegenError
degeneration_error_class = DegenerationError
+6
View File
@@ -62,6 +62,9 @@ class LLMClient(OpenAICompatClient):
presence_penalty: float = 0.0,
frequency_penalty: float = 0.0,
disable_thinking: bool = True,
api_key: str = "",
extra_headers: dict[str, str] | None = None,
user_agent: str | None = None,
):
super().__init__(
base_url=base_url,
@@ -85,6 +88,9 @@ class LLMClient(OpenAICompatClient):
presence_penalty=presence_penalty,
frequency_penalty=frequency_penalty,
disable_thinking=disable_thinking,
api_key=api_key,
extra_headers=extra_headers,
user_agent=user_agent,
)
@staticmethod
+44 -4
View File
@@ -95,11 +95,21 @@ class OpenAICompatClient:
reasoning; the `llm` title/description author turns it on. Ollama honors it
on the `/v1` compat endpoint (its native `think:false` is not plumbed
through `/v1`).
`api_key` (when set) is sent as `Authorization: Bearer <key>` on every
request — the OpenCode Console inference API and most hosted
OpenAI-compatible gateways require it. `extra_headers` are merged on top
(custom auth schemes, routing hints) and `user_agent` overrides the default
client string. `query_context` gates the ollama `/api/show` probe: a
hosted/non-ollama endpoint (see `console.OpenCodeConsoleClient`) sets it
False so no stray `/api/show` request is sent and the window comes from
`context_window`/the default.
"""
error_class = ProviderError
degeneration_error_class = ProviderError
label = "provider"
query_context = True
def __init__(
self,
@@ -125,6 +135,9 @@ class OpenAICompatClient:
frequency_penalty: float = 0.2,
max_attempts: int = 3,
disable_thinking: bool = False,
api_key: str = "",
extra_headers: dict[str, str] | None = None,
user_agent: str | None = None,
):
self.base_url = base_url.rstrip("/")
self.model = model
@@ -148,8 +161,30 @@ class OpenAICompatClient:
self.frequency_penalty = frequency_penalty
self.max_attempts = max_attempts
self.disable_thinking = disable_thinking
self.api_key = api_key
self.extra_headers = dict(extra_headers or {})
self.user_agent = user_agent
self._window: int | None = None
def _headers(self) -> dict[str, str]:
"""Request headers: JSON content type plus optional auth/extra/UA.
A non-empty `api_key` becomes `Authorization: Bearer <key>` (required by
the OpenCode Console inference API and most hosted gateways);
`extra_headers` merge on top (last writer wins) and `user_agent`
overrides the library default. The ollama context probe uses the same
headers so an authenticated gateway never sees an unauthenticated
request.
"""
headers = {"Content-Type": "application/json"}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
if self.user_agent:
headers["User-Agent"] = self.user_agent
if self.extra_headers:
headers.update(self.extra_headers)
return headers
def chat(
self,
messages: list[dict],
@@ -184,7 +219,7 @@ class OpenAICompatClient:
payload["max_tokens"] = max_tokens
body = json.dumps(payload).encode("utf-8")
request = urllib.request.Request(
url, data=body, headers={"Content-Type": "application/json"}
url, data=body, headers=self._headers()
)
try:
with urllib.request.urlopen(request, timeout=self.timeout) as response:
@@ -213,7 +248,7 @@ class OpenAICompatClient:
request = urllib.request.Request(
url,
data=json.dumps({"model": self.model}).encode("utf-8"),
headers={"Content-Type": "application/json"},
headers=self._headers(),
)
try:
with urllib.request.urlopen(
@@ -246,10 +281,15 @@ class OpenAICompatClient:
return None
def _context_window(self) -> int:
"""Detected context window, queried once and cached."""
"""Detected context window, queried once and cached.
`query_context=False` (hosted/non-ollama endpoints) skips the
`/api/show` probe entirely: the window is taken from `context_window`
config or `DEFAULT_CONTEXT_WINDOW`, so no stray request is sent.
"""
if self._window is not None:
return self._window
window = self._query_context_window()
window = self._query_context_window() if self.query_context else None
if window is None:
window = (
int(self.context_window)