diff --git a/AGENTS.md b/AGENTS.md index 87e81b3..e019f4e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -133,8 +133,19 @@ llm.py small OpenAI-compatible provider (LLMClient) that authors a is shared from provider.py; `_parse_json` is also borrowed by the authoring parsers provider.py shared OpenAI-compatible chat transport (OpenAICompatClient: - SSE stream, token budget, idle watchdog, degeneration hook) + SSE stream, token budget, idle watchdog, degeneration hook, + optional `api_key` bearer auth + `extra_headers`/`user_agent`, + and `query_context` to skip the ollama /api/show probe) subclassed by llm.LLMClient and codegen.CodegenClient +console.py OpenCode Console provider: OpenCodeConsoleClient + the + ConsoleLLMClient / ConsoleCodegenClient endpoint subclasses. + Hosted, authenticated OpenAI-compatible Chat Completions API + (https://opencode.ai/inference/openai/v1); bearer key, skips the + ollama probe, always sends a User-Agent (the gateway 403s + urllib's default Python-urllib/), and forces + disable_thinking off (the gateway 400s reasoning_effort). + Selected via the llm/codegen `provider` key + ("opencode" vs "ollama"). log.py decisions.jsonl rows {state, question, options, predicted_probs, selected, observed_outcome, label_source} trace.py runs.jsonl lifecycle events keyed by run_id (submit/queued/ @@ -538,6 +549,30 @@ CLI, unit tests (24) + box integration tests (2). IQ3_S GGUF — huge/slow). Title + description for new skills come from the separate small `llm` provider (its own endpoint/model, shared transport in `provider.py`); only the runnable code body uses codegen. +- **Alternate hosted provider: OpenCode Console** (`console.py`). Either + endpoint can run against the hosted, authenticated OpenAI-compatible Console + inference API instead of local ollama: set `llm.provider` / `codegen.provider` + to `"opencode"` (default `"ollama"`), set `model` to a **Chat Completions** + family id (`kimi-k2.7-code`, `glm-5.3`, `deepseek-v4.1-flash`, `qwen3.8-max`, + the free models, …), and give `api_key` (literal) or `api_key_env` (env var + name — preferred). `build_scheduler` maps `"opencode"` → `ConsoleLLMClient` / + `ConsoleCodegenClient`, which keep the existing error contracts + (`LLMError` / `CodegenError` / `DegenerationError`) and the same sampler + defaults. The `OpenAICompatClient` transport already speaks the Console's SSE + shape (`delta.content` + `delta.reasoning_content` + `include_usage` + + `[DONE]`); the Console subclass adds bearer auth, defaults the base URL to + `https://opencode.ai/inference/openai/v1`, and sets `query_context=False` so no + ollama `/api/show` probe is sent. **It always sends a `User-Agent`** — the + Console gateway returns HTTP 403 for urllib's default `Python-urllib/` + (urllib does not send one; it sends its default, which is blocked) — override + with `user_agent` if desired. The Console `llm` client also forces + `disable_thinking` off: `LLMClient` sends `reasoning_effort: "none"` (an + ollama-compat knob) and the Console gateway rejects that parameter with HTTP + 400. Only the Chat Completions family is drop-in; + Claude / OpenAI-Responses / Gemini models use different wire formats and need + their own adapters. The Console's **Jev** (`/zen/v1/systemone`) is a + probability/decision evaluator — do NOT wire it into routing/assessment; SemIf + alone decides. - **Do NOT cap `max_tokens`** on the codegen call. qwen38-iq3s reasons first and a cap truncates the hidden reasoning, leaving `content` empty (`finish_reason: length`) and the body write fails with "skill body is diff --git a/config.example.json b/config.example.json index fbd745a..b9e7beb 100644 --- a/config.example.json +++ b/config.example.json @@ -21,9 +21,13 @@ "threads": 8 }, "llm": { - "_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap sets base_url from --llm-url (default http://127.0.0.1:11434) and pulls `model` if it is missing. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies, so the sampler defaults are conservative (low temperature, no presence penalty). The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter).", + "_comment": "Small OpenAI-compatible model that authors a new category/skill title + description (never the runnable body — that is `codegen` below). Deliberately its own endpoint/model, so it can be local and fast even when codegen is remote. Runs on THIS machine's local ollama; bootstrap sets base_url from --llm-url (default http://127.0.0.1:11434) and pulls `model` if it is missing. Uses the same provider machinery as codegen (real SSE stream, token budget, idle watchdog); short JSON replies, so the sampler defaults are conservative (low temperature, no presence penalty). The draft is authored asynchronously by a single-slot worker and the request re-runs when it lands; an unreachable endpoint is graceful (traced, user notified), not fatal. disable_thinking sends reasoning_effort:none so a reasoning model answers the short JSON directly instead of spending the reply budget on hidden chain-of-thought (set false only for an endpoint that rejects the parameter). provider selects the transport: \"ollama\" (default; a local OpenAI-compatible server, context auto-detected via /api/show) or \"opencode\" (the hosted OpenCode Console inference API at https://opencode.ai/inference/openai/v1 — set model to a Chat Completions family id such as kimi-k2.7-code or glm-5.3, and provide api_key or api_key_env; the ollama probe is skipped).", + "provider": "ollama", "base_url": "http://localhost:11434/v1", "model": "qwen3.5:4b", + "api_key": "", + "api_key_env": "", + "user_agent": "", "timeout": 600, "stream": false, "idle_warn": 30, @@ -36,9 +40,13 @@ "disable_thinking": true }, "codegen": { - "_comment": "OpenAI-compatible model that writes runnable skill bodies. Runs on a REMOTE ollama host (bootstrap sets base_url from --codegen-url, default guppy http://192.168.8.181:11434); the local small model is `llm` above. Bodies perform real actions against the user's configured services via stdlib transports, read every operational value from ctx.config, and declare their integration (INTEGRATION: service/transport/config_vars). Larger/slower than the decision or title/description model. The transport always streams so the client-side token budget (output cap / peak total fill) can abort a runaway in real time; stream only toggles console echo of tokens. timeout is total seconds; idle_warn/idle_timeout surface a silent (wedged) stream. The context window is auto-detected via ollama /api/show; context_window is the manual fallback (0 = auto/default 100000). smart_limit/warn_limit and max_fill_ratio/warn_fill_ratio bound total fill; max_output caps streamed output (>=1 absolute tokens, 0=1 absolute tokens, 0 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): diff --git a/semif_agent/console.py b/semif_agent/console.py new file mode 100644 index 0000000..3105b64 --- /dev/null +++ b/semif_agent/console.py @@ -0,0 +1,124 @@ +"""OpenCode Console provider (hosted, authenticated OpenAI-compatible API). + +The `OpenCode 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 ``), 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/`` 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 diff --git a/semif_agent/llm.py b/semif_agent/llm.py index b9c9da8..c96faf7 100644 --- a/semif_agent/llm.py +++ b/semif_agent/llm.py @@ -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 diff --git a/semif_agent/provider.py b/semif_agent/provider.py index 2e18d72..fcfec44 100644 --- a/semif_agent/provider.py +++ b/semif_agent/provider.py @@ -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 ` 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 ` (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) diff --git a/tests/test_console.py b/tests/test_console.py new file mode 100644 index 0000000..85949c4 --- /dev/null +++ b/tests/test_console.py @@ -0,0 +1,218 @@ +"""Stdlib tests for the OpenCode Console provider. + +A throwaway stdlib HTTP server stands in for the Console endpoint; the client +is real, not mocked. These are hermetic mechanics checks (bearer header, the +skipped ollama probe, the preserved error contracts, the model-list parse) — +only a real Console call proves the hosted integration. No external network. +""" + +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from semif_agent.codegen import CodegenError, DegenerationError +from semif_agent.console import ( + OPENCODE_BASE_URL, + ConsoleCodegenClient, + ConsoleLLMClient, + OpenCodeConsoleClient, + OpenCodeError, +) +from semif_agent.llm import LLMClient, LLMError +from semif_agent.provider import ProviderError + + +def _sse_frame(payload: dict) -> str: + return f"data: {json.dumps(payload)}\n\n" + + +class _FakeConsole(BaseHTTPRequestHandler): + """Records every request (method, path, lowercased headers). Answers GET + /models with an OpenAI list and POST with a one-delta SSE reply.""" + + reply: str = "{}" + models: list = ["kimi-k2.7-code", "glm-5.3"] + calls: list = [] + + def _record(self) -> None: + type(self).calls.append( + (self.command, self.path, {k.lower(): v for k, v in self.headers.items()}) + ) + + def do_GET(self) -> None: + self._record() + body = json.dumps( + {"object": "list", "data": [{"id": m} for m in self.models]} + ).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + self.rfile.read(length) + self._record() + body = ( + _sse_frame({"choices": [{"delta": {"content": self.reply}}]}) + + "data: [DONE]\n\n" + ).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args) -> None: + pass + + +def _server(reply: str = "{}", models: list | None = None): + attrs = {"reply": reply, "calls": []} + if models is not None: + attrs["models"] = models + handler = type("Handler", (_FakeConsole,), attrs) + httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + return httpd, f"http://127.0.0.1:{httpd.server_address[1]}" + + +def test_console_llm_pins_defaults_and_error_contract(): + client = ConsoleLLMClient(api_key="k", model="m") + assert client.base_url == OPENCODE_BASE_URL + assert client.label == "opencode:llm" + assert client.error_class is LLMError + assert client.degeneration_error_class is LLMError + assert client.query_context is False + # Console rejects reasoning_effort → forced off despite LLMClient's default. + assert client.disable_thinking is False + + +def test_console_llm_never_sends_reasoning_effort_even_if_requested(): + client = ConsoleLLMClient(api_key="k", model="m", disable_thinking=True) + assert client.disable_thinking is False + + +def test_console_codegen_pins_defaults_and_error_contract(): + client = ConsoleCodegenClient(api_key="k", model="m") + assert client.base_url == OPENCODE_BASE_URL + assert client.label == "opencode:codegen" + assert client.error_class is CodegenError + assert client.degeneration_error_class is DegenerationError + assert client.query_context is False + assert client.presence_penalty == 1.5 # CodegenClient sampler default preserved + + +def test_console_error_is_provider_error(): + assert issubclass(OpenCodeError, ProviderError) + + +def test_chat_sends_bearer_and_skips_ollama_probe(): + httpd, base = _server(reply='{"ok": true}') + try: + client = ConsoleLLMClient(base_url=base, api_key="secret", model="m", timeout=10) + out = client.chat([{"role": "user", "content": "hi"}]) + assert out == '{"ok": true}' + calls = httpd.RequestHandlerClass.calls + # query_context=False → the only request is the chat completion. + assert [c[1] for c in calls] == ["/chat/completions"] + assert calls[0][2]["authorization"] == "Bearer secret" + finally: + httpd.shutdown() + httpd.server_close() + + +def test_plain_llm_without_key_sends_no_auth_header(): + httpd, base = _server(reply="{}") + try: + LLMClient(base_url=base, model="m", timeout=10).chat( + [{"role": "user", "content": "hi"}] + ) + chat = [ + c for c in httpd.RequestHandlerClass.calls if c[1].endswith("/chat/completions") + ] + assert chat and "authorization" not in chat[0][2] + finally: + httpd.shutdown() + httpd.server_close() + + +def test_extra_headers_are_merged(): + httpd, base = _server(reply="{}") + try: + client = ConsoleLLMClient( + base_url=base, + api_key="k", + extra_headers={"X-Route": "edge"}, + model="m", + timeout=10, + ) + client.chat([{"role": "user", "content": "hi"}]) + headers = httpd.RequestHandlerClass.calls[0][2] + assert headers["x-route"] == "edge" + assert headers["authorization"] == "Bearer k" + finally: + httpd.shutdown() + httpd.server_close() + + +def test_console_sends_default_user_agent(): + """The Console gateway 403s urllib's default Python-urllib UA.""" + httpd, base = _server(reply="{}") + try: + ConsoleLLMClient(base_url=base, model="m", timeout=10).chat( + [{"role": "user", "content": "hi"}] + ) + ua = httpd.RequestHandlerClass.calls[0][2].get("user-agent") + assert ua and "semif-agent" in ua + finally: + httpd.shutdown() + httpd.server_close() + + +def test_console_user_agent_can_be_overridden(): + httpd, base = _server(reply="{}") + try: + ConsoleLLMClient( + base_url=base, model="m", timeout=10, user_agent="my-agent/9" + ).chat([{"role": "user", "content": "hi"}]) + assert httpd.RequestHandlerClass.calls[0][2]["user-agent"] == "my-agent/9" + finally: + httpd.shutdown() + httpd.server_close() + + +def test_list_models_parses_catalog(): + httpd, base = _server(models=["kimi-k2.7-code", "glm-5.3"]) + try: + client = OpenCodeConsoleClient(base_url=base, api_key="k", model="m", timeout=10) + assert client.list_models(url=f"{base}/models") == ["kimi-k2.7-code", "glm-5.3"] + assert httpd.RequestHandlerClass.calls[0][2]["authorization"] == "Bearer k" + finally: + httpd.shutdown() + httpd.server_close() + + +def test_provider_endpoint_selects_console_and_resolves_key(monkeypatch): + from semif_agent import cli + + monkeypatch.setenv("MY_CONSOLE_KEY", "envkey") + console = cli._provider_endpoint( + {"provider": "opencode", "api_key_env": "MY_CONSOLE_KEY"}, + "http://localhost:11434/v1", + ) + assert console["base_url"] == OPENCODE_BASE_URL + assert console["api_key"] == "envkey" + + ollama = cli._provider_endpoint({"provider": "ollama"}, "http://localhost:11434/v1") + assert ollama["base_url"] == "http://localhost:11434/v1" + assert ollama["api_key"] == "" + + literal = cli._provider_endpoint({"provider": "opencode", "api_key": "lit"}, "x") + assert literal["api_key"] == "lit" + + explicit = cli._provider_endpoint( + {"provider": "opencode", "base_url": "https://example.test/v1"}, "x" + ) + assert explicit["base_url"] == "https://example.test/v1"