diff --git a/CHANGELOG.md b/CHANGELOG.md index b9d0c5fa..e6427d98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,8 +66,36 @@ For auto-generated release notes, see [GitHub Releases](https://github.com/DataV depends on `althing` Historical changelog entries below retain the old name. +- **Sampling docs corrected.** Claude Code is no longer listed as a + sampling-capable host (it has never implemented the client side — + anthropics/claude-code#1785), the docs note the MCP 2026-07-28 + sampling deprecation, and the no-credentials error now points at + subscription CLI models. + ### Added +- **Subscription CLI providers: `claude-code:` and `codex:`.** + Completions can now run through a locally installed, signed-in Claude + Code (`claude -p`) or Codex (`codex exec`) CLI, drawing on the user's + Claude / ChatGPT subscription instead of an API key — the + forward-looking replacement for MCP sampling, which MCP 2026-07-28 + deprecated (SEP-2577) and Claude Code never implemented. Each call is + an isolated, tool-less completion (agent prompt replaced by the persona + prompt; tools, MCP servers, user settings, and session persistence + disabled; empty scratch working directory), and forced-tool structured + output maps onto the CLIs' native JSON-schema flags, so panels, + extraction, and SynthBench's `althing` provider work unchanged. The + prefixes are explicit-only (never a credential fallback), structured + output escalation stays on the same CLI, and an explicit CLI model + makes MCP tools run without a key or sampling. Limits: no + temperature/top_p/seed/max_tokens control, text-only, throughput bound + by subscription usage limits (surfaced as rate limits). Knobs: + `ALTHING_CLI_MAX_CONCURRENT`, `ALTHING_CLI_TIMEOUT`, + `ALTHING_CLAUDE_CODE_EFFORT` / `ALTHING_CODEX_EFFORT`, + `ALTHING_CLAUDE_CODE_BIN` / `ALTHING_CODEX_BIN`, and + `ALTHING_CLAUDE_CODE_ALLOW_API_KEY` (by default `ANTHROPIC_API_KEY` is + stripped from the child env so the CLI can't silently bill it). + - **`cost show `.** Per-run cost breakdown for one saved panel result — total/panelist cost, per-model token + USD rollup, and synthesis cost — as a thin alias over the cost section of `panel diff --git a/CLAUDE.md b/CLAUDE.md index 21bca315..15ea905e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -92,6 +92,12 @@ Set the appropriate environment variable: | OpenAI | `OPENAI_API_KEY` | (must specify --model) | | xAI | `XAI_API_KEY` | grok-3 | | Google | `GOOGLE_API_KEY` or `GEMINI_API_KEY` | gemini-2.5-flash | +| Claude Code CLI | none (signed-in `claude`) | explicit only: `claude-code:` | +| Codex CLI | none (signed-in `codex`) | explicit only: `codex:` | + +Subscription CLI providers live in `llm/providers/subscription_cli.py` and +register *before* Anthropic in `_PROVIDER_REGISTRY` (`claude-code:` would +otherwise match `claude-`). They never satisfy the credential fallback. ## YAML Formats diff --git a/README.md b/README.md index 6e0a00e3..be2b216a 100644 --- a/README.md +++ b/README.md @@ -419,10 +419,20 @@ Add to your editor's MCP config (Claude Code, Cursor, Windsurf): ### Zero-config first run via sampling -No API key? No problem. When the invoking MCP client (Claude Desktop, -Claude Code, Cursor, Windsurf) advertises the `sampling` capability, -althing falls back to asking the client to run the LLM completion on -its behalf — using the client's own subscription. That means `run_prompt` +No API key? When the invoking MCP client advertises the `sampling` +capability, althing falls back to asking the client to run the LLM +completion on its behalf — using the client's own subscription. + +> **Sampling is deprecated and not universally supported.** MCP +> 2026-07-28 deprecated sampling (SEP-2577; still functional for at +> least 12 months), and **Claude Code has never implemented it** +> ([anthropics/claude-code#1785](https://github.com/anthropics/claude-code/issues/1785)). +> To use a Claude or ChatGPT subscription from Claude Code (or anywhere +> else), pass a subscription CLI model instead — e.g. +> `model="claude-code:haiku"` — see +> [Subscription CLI models](#subscription-cli-models-claude-code--codex). + +With a sampling-capable client, That means `run_prompt` and small `run_quick_poll` calls (up to 3 personas) work with zero env setup: @@ -1083,6 +1093,8 @@ althing works with any LLM provider. Set the appropriate environment variable: | OpenRouter | `OPENROUTER_API_KEY` | `--model openrouter/anthropic/claude-haiku-4-5` | | xAI (Grok) | `XAI_API_KEY` | `--model grok` | | Any OpenAI-compatible | `OPENAI_API_KEY` + `OPENAI_BASE_URL` | `--model ` | +| Claude Code CLI (subscription) | none — signed-in `claude` on PATH | `--model claude-code:sonnet` | +| Codex CLI (subscription) | none — signed-in `codex` on PATH | `--model codex:` or `--model codex:` | ```bash # Use Claude (default) @@ -1096,6 +1108,48 @@ OPENAI_BASE_URL=http://localhost:11434/v1 \ althing panel run --personas p.yaml --instrument s.yaml --model llama3 ``` +### Subscription CLI models (`claude-code:` / `codex:`) + +The `claude-code:` and `codex:` prefixes run each completion +through a locally installed, signed-in agent CLI in headless mode +(`claude -p` / `codex exec`), so calls draw on your Claude or ChatGPT +subscription instead of an API key. Every call is an isolated, tool-less +completion: the CLI's agent system prompt is replaced by the persona +prompt, tools / MCP servers / user settings are disabled, nothing is +persisted, and the process runs in an empty scratch directory. Structured +output maps onto the CLIs' native JSON-schema flags. + +```bash +althing panel run --personas p.yaml --instrument s.yaml --model claude-code:haiku +althing prompt "Hello" --model codex: # Codex CLI's default model +``` + +Things to know before relying on it: + +- **No sampling controls.** `temperature`, `top_p`, `seed`, and + `max_tokens` are not exposed by the CLIs and are ignored (with a + warning). Results are not directly comparable to API-key runs of the + same model — label them separately (e.g. on SynthBench). +- **Subscription usage limits** bound throughput. Usage-limit errors + surface as rate limits and get the normal backoff. Cap in-flight CLI + processes with `ALTHING_CLI_MAX_CONCURRENT` (default 4) and per-call + time with `ALTHING_CLI_TIMEOUT` (default 300 s). +- **Text only, forced single-tool only.** Attachments and free tool + use are rejected; multi-turn persona history is flattened into one + prompt per call. +- **Cost figures are estimates.** There is no per-call bill, so cost is + the local pricing-table estimate (API list-price equivalent) and + `--max-cost` acts as a usage budget. +- **API keys are stripped.** `claude` prefers `ANTHROPIC_API_KEY` over + the subscription login, so althing removes it from the child process + environment. Set `ALTHING_CLAUDE_CODE_ALLOW_API_KEY=1` to keep it. +- Optional: `ALTHING_CLAUDE_CODE_EFFORT` / `ALTHING_CODEX_EFFORT` pass a + reasoning-effort level; `ALTHING_CLAUDE_CODE_BIN` / `ALTHING_CODEX_BIN` + override the executable path. + +These prefixes are only used when you ask for them — they are never +picked as an implicit default. + > **Large panels and the OpenRouter default (synthbench#261):** when > `--model` is omitted, the default is resolved from whichever key is > present — for an OpenRouter-only environment that's `openrouter/auto`, diff --git a/docs/mcp.md b/docs/mcp.md index eaea2c30..f415a9f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -520,12 +520,17 @@ and `_resolve_mcp_default_model()` in `src/althing/mcp/server.py`. | no | yes | (auto) | **BYOK** | | no | (any) | `true` | **error** — host did not advertise `sampling` | | no | (any) | `false` | **BYOK** — falls through to a missing-creds error if no key is set | +| (any) | (any) | (auto), with `model="claude-code:*"` / `"codex:*"` | **BYOK** — the subscription CLI needs no key | "Provider key available" means any of `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `XAI_API_KEY`, `GOOGLE_API_KEY`, `GEMINI_API_KEY`, or `OPENROUTER_API_KEY` — checked first against the process environment, then against the on-disk credential store written by `althing login` -(so MCP-launched subprocesses recognise keys the CLI can see). +(so MCP-launched subprocesses recognise keys the CLI can see). An +explicit subscription CLI model (`claude-code:` / +`codex:`) counts as available credentials: it runs on the +signed-in CLI and needs no key (see +[Subscription CLI models](#subscription-cli-models)). The auto rule "local key wins over sampling" exists so users who *have* configured BYOK keep BYOK's full feature set (cross-provider ensembles, @@ -589,6 +594,15 @@ failing. See [Model Resolution Order](#model-resolution-order) for the full configuration → mode matrix. +> **Deprecated, and not available in Claude Code.** MCP 2026-07-28 +> deprecated sampling (SEP-2577) — it keeps working for at least twelve +> months, with removal no earlier than the first revision after +> 2027-07-28 — and **Claude Code has never implemented the client side** +> ([anthropics/claude-code#1785](https://github.com/anthropics/claude-code/issues/1785)), +> so sampling mode never activates under Claude Code. The +> forward-looking way to run on a subscription is a +> [subscription CLI model](#subscription-cli-models). + ### Tradeoffs Sampling mode is intentionally less capable than BYOK: @@ -669,6 +683,34 @@ decided per call by probing the client's declared `sampling` capability (from the `initialize` handshake on legacy connections, or the per-request `_meta` envelope on modern ones). +## Subscription CLI models + +`claude-code:` and `codex:` route each completion through a +locally installed, signed-in agent CLI in headless mode (`claude -p` / +`codex exec`), drawing on your Claude or ChatGPT subscription instead of +an API key. Unlike sampling it works under any MCP host (including +Claude Code), on the CLI and SDK, and has no persona/question caps or +structured-output restriction: + +```jsonc +// run_quick_poll arguments +{ "question": "...", "pack_id": "...", "model": "claude-code:haiku" } +``` + +Each call is an isolated, tool-less completion — the CLI's agent prompt +is replaced by the persona prompt, tools / MCP servers / user settings +are disabled, nothing is persisted, and the process runs in an empty +scratch directory. The CLI must be installed and signed in on the +machine running `althing mcp-serve`. + +Tradeoffs: no `temperature` / `top_p` / `seed` / `max_tokens` control, +text-only content, throughput bounded by subscription usage limits +(surfaced as rate limits), and cost figures that are API list-price +estimates rather than bills. See the +README's "Subscription CLI models" section for the environment knobs +(`ALTHING_CLI_MAX_CONCURRENT`, `ALTHING_CLI_TIMEOUT`, +`ALTHING_CLAUDE_CODE_ALLOW_API_KEY`, …). + ## Host Integration Flags ### `ALTHING_DRIFT_DEGRADE` @@ -784,9 +826,13 @@ Symptom: tool calls return `MISSING_CREDS` or a provider-specific - Run `althing login` to seed the on-disk credential store; the MCP server reads from there as a fallback when the env is empty (see [Model Resolution Order](#model-resolution-order)). -- If your host advertises MCP `sampling` (Claude Desktop, Claude Code, - Cursor, Windsurf), you can omit the key entirely and althing will - borrow the host's LLM access — see [Sampling Mode](#sampling-mode). +- To run without a key, pass a subscription CLI model + (`model="claude-code:haiku"` or `"codex:"`) — it uses the signed-in + CLI on the server machine; see + [Subscription CLI models](#subscription-cli-models). If your host + advertises MCP `sampling` (**not** Claude Code), you can also omit + the key and althing will borrow the host's LLM access — see + [Sampling Mode](#sampling-mode). ### Timeouts on long panel runs diff --git a/site/mcp/index.html b/site/mcp/index.html index 47d03c5b..88044f05 100644 --- a/site/mcp/index.html +++ b/site/mcp/index.html @@ -1558,9 +1558,13 @@

the env block, run althing login to - seed the on-disk credential store, or omit the key and - let MCP sampling borrow the host's LLM access - (Claude Desktop, Claude Code, Cursor, Windsurf). + seed the on-disk credential store, pass a subscription + CLI model such as + model="claude-code:haiku" + to run on the signed-in Claude Code / Codex CLI, or omit + the key and let MCP sampling borrow the host's + LLM access (deprecated in MCP 2026-07-28, and not + supported by Claude Code).
diff --git a/site/mcp/index.md b/site/mcp/index.md index b07ac21d..1132550d 100644 --- a/site/mcp/index.md +++ b/site/mcp/index.md @@ -376,7 +376,7 @@ Note the two distinct locations: API keys saved by `althing login` live in the c Server starts but no tools appear The MCP server needs the `[mcp]` extra: `pip install "althing[mcp]"`. After config edits or upgrades, fully quit and relaunch the host — tool lists are cached per server entry. Sanity-check by running `althing mcp-serve` in a terminal; it should boot silently. -Missing API key The subprocess only sees env vars from the MCP `env` block. A shell-profile export does not propagate. Set the key in the `env` block, run `althing login` to seed the on-disk credential store, or omit the key and let MCP *sampling* borrow the host's LLM access (Claude Desktop, Claude Code, Cursor, Windsurf). +Missing API key The subprocess only sees env vars from the MCP `env` block. A shell-profile export does not propagate. Set the key in the `env` block, run `althing login` to seed the on-disk credential store, pass a subscription CLI model such as `model="claude-code:haiku"` to run on the signed-in Claude Code / Codex CLI, or omit the key and let MCP *sampling* borrow the host's LLM access (deprecated in MCP 2026-07-28, and not supported by Claude Code). Timeouts on long panels A 5-persona × 3-question BYOK panel takes 30–90 seconds; cross-provider ensembles can take 2–5 minutes. Raise the host's per-tool timeout (Hermes: `timeout: 300`). For exploratory work, prefer `run_quick_poll` over `run_panel`. diff --git a/src/althing/_runners.py b/src/althing/_runners.py index 6e3dfe8d..4d5a28bc 100644 --- a/src/althing/_runners.py +++ b/src/althing/_runners.py @@ -246,7 +246,14 @@ def _resolve_context_window(model: str | None) -> tuple[int, bool]: # "haiku" doesn't falsely pick the default window. try: from althing.llm.aliases import resolve_alias - + from althing.llm.providers.subscription_cli import SUBSCRIPTION_CLI_PREFIXES + + # Subscription CLI models ("claude-code:haiku") size like the model + # they wrap. + for cli_prefix in SUBSCRIPTION_CLI_PREFIXES: + if model.startswith(cli_prefix): + model = model[len(cli_prefix) :] + break resolved = resolve_alias(model) except Exception: resolved = model diff --git a/src/althing/llm/client.py b/src/althing/llm/client.py index 0e16a9ca..21f9c44d 100644 --- a/src/althing/llm/client.py +++ b/src/althing/llm/client.py @@ -16,6 +16,12 @@ from althing.llm.providers.gemini import GEMINI_CONFIG, GeminiProvider from althing.llm.providers.openai_compat import OPENAI_COMPAT_CONFIG, OpenAICompatibleProvider from althing.llm.providers.openrouter import OPENROUTER_CONFIG, OpenRouterProvider +from althing.llm.providers.subscription_cli import ( + CLAUDE_CODE_CONFIG, + CODEX_CONFIG, + ClaudeCodeProvider, + CodexProvider, +) from althing.llm.providers.xai import XAI_CONFIG, XAIProvider from althing.llm.retry import ( DEFAULT_INITIAL_BACKOFF as _DEFAULT_INITIAL_BACKOFF, @@ -39,7 +45,12 @@ logger = logging.getLogger(__name__) # Provider detection order (SPEC.md §2 — Provider Resolution). +# Subscription CLI providers come first: ``claude-code:*`` would otherwise +# match Anthropic's ``claude-`` prefix. They never satisfy the credential +# fallback below, so they are only reachable by explicit prefix. _PROVIDER_REGISTRY: list[tuple[ProviderConfig, type[LLMProvider]]] = [ + (CLAUDE_CODE_CONFIG, ClaudeCodeProvider), + (CODEX_CONFIG, CodexProvider), (ANTHROPIC_CONFIG, AnthropicProvider), (GEMINI_CONFIG, GeminiProvider), (XAI_CONFIG, XAIProvider), @@ -152,7 +163,8 @@ def _resolve_provider(self, model: str) -> LLMProvider: raise LLMError( "No LLM provider credentials found. Run `althing login` or set " "ANTHROPIC_API_KEY, GEMINI_API_KEY, XAI_API_KEY, OPENROUTER_API_KEY, " - "or OPENAI_API_KEY.", + "or OPENAI_API_KEY — or use a subscription CLI model " + "(claude-code: / codex:).", LLMErrorCategory.MISSING_CREDENTIALS, ) diff --git a/src/althing/llm/providers/__init__.py b/src/althing/llm/providers/__init__.py index 029ca262..ef14c643 100644 --- a/src/althing/llm/providers/__init__.py +++ b/src/althing/llm/providers/__init__.py @@ -5,10 +5,13 @@ from althing.llm.providers.gemini import GeminiProvider from althing.llm.providers.openai_compat import OpenAICompatibleProvider from althing.llm.providers.openrouter import OpenRouterProvider +from althing.llm.providers.subscription_cli import ClaudeCodeProvider, CodexProvider from althing.llm.providers.xai import XAIProvider __all__ = [ "AnthropicProvider", + "ClaudeCodeProvider", + "CodexProvider", "GeminiProvider", "LLMProvider", "OpenAICompatibleProvider", diff --git a/src/althing/llm/providers/subscription_cli.py b/src/althing/llm/providers/subscription_cli.py new file mode 100644 index 00000000..7496fcf0 --- /dev/null +++ b/src/althing/llm/providers/subscription_cli.py @@ -0,0 +1,686 @@ +"""Subscription CLI providers: Claude Code and Codex in headless mode. + +These providers route completions through a locally installed, signed-in +agent CLI (``claude -p`` / ``codex exec``) instead of an HTTP API, so the +calls draw on the user's Claude or ChatGPT subscription rather than a +BYOK API key. They are the replacement for MCP *sampling* as the +"borrow the host's model access" path: sampling is deprecated as of MCP +2026-07-28 (SEP-2577) and Claude Code never implemented it. + +Selection is explicit and prefix-based — never a credential fallback: + +* ``claude-code:`` → ``claude -p --model `` (``claude-code:`` + alone uses the CLI's default model). ```` accepts anything the + CLI does: ``haiku`` / ``sonnet`` / ``opus`` or a full model id. +* ``codex:`` → ``codex exec -m `` (``codex:`` alone uses the + CLI's default model). + +Each call runs the CLI as an isolated, tool-less completion: the agent +system prompt is replaced by the request's ``system``, tools / MCP +servers / user settings are disabled, sessions are not persisted, and +the process runs in an empty scratch directory so no project context +(CLAUDE.md, AGENTS.md) leaks in. Structured output maps onto the CLIs' +native JSON-schema flags, so forced single-tool requests (the +:class:`~althing.structured.output.StructuredOutputEngine` path) come +back as ordinary :class:`ToolInvocationBlock` responses. + +Limitations, by construction: + +* No sampling controls — ``temperature`` / ``top_p`` / ``seed`` / + ``max_tokens`` are not exposed by the CLIs and are ignored (one-shot + warning for the sampling params). +* Multi-turn history is flattened into one prompt; text only (image / + document attachments are rejected). +* Only forced single-tool calls are supported (no free tool use). +* Throughput is bounded by subscription usage limits; usage-limit + errors surface as ``RATE_LIMIT`` so the client's backoff applies. +* No per-call bill exists, so no provider cost is reported and cost + figures are local pricing-table estimates (API list-price + equivalents). ``--max-cost`` therefore acts as a usage budget. + +Environment knobs: + +* ``ALTHING_CLAUDE_CODE_BIN`` / ``ALTHING_CODEX_BIN`` — executable path. +* ``ALTHING_CLI_MAX_CONCURRENT`` — max in-flight CLI processes per + provider (default 4). +* ``ALTHING_CLI_TIMEOUT`` — per-call timeout in seconds (default 300). +* ``ALTHING_CLAUDE_CODE_EFFORT`` / ``ALTHING_CODEX_EFFORT`` — optional + reasoning-effort level passed through to the CLI. +* ``ALTHING_CLAUDE_CODE_ALLOW_API_KEY=1`` — keep ``ANTHROPIC_API_KEY`` + in the child environment. By default it is stripped, because + ``claude`` prefers an API key over the subscription login when both + are present, which would silently bill the key. +""" + +from __future__ import annotations + +import atexit +import json +import logging +import os +import shutil +import subprocess +import tempfile +import threading +import uuid +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from althing.llm.errors import LLMError, LLMErrorCategory +from althing.llm.models import ( + CompletionRequest, + CompletionResponse, + InputMessage, + StopReason, + StreamEvent, + StreamEventType, + TextBlock, + ThinkingBlock, + TokenUsage, + ToolChoiceKind, + ToolDefinition, + ToolInvocationBlock, + ToolResultBlock, +) +from althing.llm.providers.base import LLMProvider, ProviderConfig + +logger = logging.getLogger(__name__) + +CLAUDE_CODE_PREFIX = "claude-code:" +CODEX_PREFIX = "codex:" +SUBSCRIPTION_CLI_PREFIXES: tuple[str, ...] = (CLAUDE_CODE_PREFIX, CODEX_PREFIX) + +_MAX_CONCURRENT_ENV = "ALTHING_CLI_MAX_CONCURRENT" +_TIMEOUT_ENV = "ALTHING_CLI_TIMEOUT" +_DEFAULT_MAX_CONCURRENT = 4 +_DEFAULT_TIMEOUT = 300.0 +_ALLOW_API_KEY_ENV = "ALTHING_CLAUDE_CODE_ALLOW_API_KEY" + +# A system prompt is always sent: omitting it would leave the CLI's own +# coding-agent prompt in place and contaminate persona responses. +_NEUTRAL_SYSTEM_PROMPT = "You are a helpful assistant." + +_RATE_LIMIT_MARKERS = ( + "rate limit", + "rate_limit", + "usage limit", + "hit your limit", + "limit reached", + "too many requests", + "429", +) +_AUTH_MARKERS = ( + "not logged in", + "/login", + "codex login", + "invalid api key", + "authentication", + "unauthorized", + "401", +) +_OVERLOADED_MARKERS = ("overloaded", "529", "500", "502", "503", "internal server error") + + +def is_subscription_cli_model(model: str | None) -> bool: + """Return True when *model* routes to a subscription CLI provider.""" + return bool(model) and str(model).startswith(SUBSCRIPTION_CLI_PREFIXES) + + +@dataclass(frozen=True) +class CLIProviderConfig(ProviderConfig): + """Provider config for a CLI-backed provider. + + There is no API key: authentication is whatever the CLI is signed in + with. ``has_credentials`` is always False so the client's + "first provider with credentials" fallback never picks a CLI provider + implicitly — they are reachable only through their model prefix. + """ + + executable: str = "" + executable_env: str = "" + + def has_credentials(self) -> bool: + return False + + def resolve_executable(self) -> str: + override = os.environ.get(self.executable_env, "").strip() if self.executable_env else "" + found = shutil.which(override or self.executable) + if not found: + raise LLMError( + f"{self.name} provider requires the `{override or self.executable}` CLI on PATH " + f"(signed in to your subscription). Install it, or point {self.executable_env} at the " + "executable.", + LLMErrorCategory.MISSING_CREDENTIALS, + ) + return found + + +CLAUDE_CODE_CONFIG = CLIProviderConfig( + api_key_env="", + base_url_env="", + default_base_url="", + model_prefixes=(CLAUDE_CODE_PREFIX,), + name="Claude Code", + executable="claude", + executable_env="ALTHING_CLAUDE_CODE_BIN", +) + +CODEX_CONFIG = CLIProviderConfig( + api_key_env="", + base_url_env="", + default_base_url="", + model_prefixes=(CODEX_PREFIX,), + name="Codex", + executable="codex", + executable_env="ALTHING_CODEX_BIN", +) + + +# --------------------------------------------------------------------------- +# Shared helpers +# --------------------------------------------------------------------------- + +_scratch_lock = threading.Lock() +_scratch_root: Path | None = None +_semaphores: dict[str, threading.BoundedSemaphore] = {} +_sampling_warned: set[str] = set() + + +def _scratch_dir() -> Path: + """Return an empty process-wide working directory for CLI calls.""" + global _scratch_root + with _scratch_lock: + if _scratch_root is None: + _scratch_root = Path(tempfile.mkdtemp(prefix="althing-cli-")) + atexit.register(shutil.rmtree, _scratch_root, True) + return _scratch_root + + +def _semaphore_for(name: str) -> threading.BoundedSemaphore: + with _scratch_lock: + sem = _semaphores.get(name) + if sem is None: + try: + limit = int(os.environ.get(_MAX_CONCURRENT_ENV, "") or _DEFAULT_MAX_CONCURRENT) + except ValueError: + limit = _DEFAULT_MAX_CONCURRENT + sem = threading.BoundedSemaphore(max(1, limit)) + _semaphores[name] = sem + return sem + + +def _api_key_allowed() -> bool: + return os.environ.get(_ALLOW_API_KEY_ENV, "").strip().lower() in ("1", "true", "yes") + + +def _timeout() -> float: + try: + return float(os.environ.get(_TIMEOUT_ENV, "") or _DEFAULT_TIMEOUT) + except ValueError: + return _DEFAULT_TIMEOUT + + +def _warn_ignored_sampling_params(provider_name: str, request: CompletionRequest) -> None: + if request.temperature is None and request.top_p is None: + return + with _scratch_lock: + if provider_name in _sampling_warned: + return + _sampling_warned.add(provider_name) + logger.warning( + "%s CLI provider does not expose temperature/top_p; requested values are ignored " + "and the CLI's default sampling applies.", + provider_name, + ) + + +def cli_model_name(model: str, prefix: str) -> str | None: + """Strip the routing prefix; ``None`` means "use the CLI's default model".""" + rest = model[len(prefix) :].strip() if model.startswith(prefix) else model.strip() + return rest or None + + +def _block_to_text(block: Any) -> str: + if isinstance(block, TextBlock): + return block.text + if isinstance(block, ThinkingBlock): + return "" + if isinstance(block, ToolInvocationBlock): + return f"[structured response via {block.name}: {json.dumps(block.input, ensure_ascii=False)}]" + if isinstance(block, ToolResultBlock): + body = "\n".join(b.text for b in block.content) + return f"[{'error' if block.is_error else 'result'}: {body}]" + if getattr(block, "type", None) == "html": + return block.text + raise LLMError( + f"Subscription CLI providers accept text content only; got a {getattr(block, 'type', type(block).__name__)!r} " + "block. Use an API-key provider for attachments.", + LLMErrorCategory.BAD_REQUEST, + ) + + +def _message_text(message: InputMessage) -> str: + return "\n".join(t for t in (_block_to_text(b) for b in message.content) if t) + + +def render_prompt(messages: list[InputMessage]) -> str: + """Flatten a conversation into a single prompt for a one-shot CLI call. + + A lone user message passes through verbatim. Longer conversations are + rendered as a tagged transcript followed by the final user turn, so + persona sessions keep their earlier answers in view. + """ + if not messages: + raise LLMError("Request has no messages", LLMErrorCategory.BAD_REQUEST) + *history, last = messages + final = _message_text(last) + if not history: + return final + lines = [""] + for message in history: + tag = "you" if message.role == "assistant" else "user" + lines.append(f"<{tag}>\n{_message_text(message)}\n") + lines.append("") + lines.append("") + if last.role == "assistant": + lines.append(f"Continue your previous reply, which so far reads:\n{final}") + else: + lines.append(final) + return "\n".join(lines) + + +def forced_tool(request: CompletionRequest) -> ToolDefinition | None: + """Return the single tool the request forces, or ``None`` for plain text. + + Only forced single-tool calls map onto the CLIs' JSON-schema mode; + anything else would need real tool calling, which a one-shot headless + run can't provide. + """ + if not request.tools: + return None + choice = request.tool_choice + if choice is not None and choice.kind == ToolChoiceKind.SPECIFIC: + for tool in request.tools: + if tool.name == choice.name: + return tool + raise LLMError(f"tool_choice names unknown tool {choice.name!r}", LLMErrorCategory.BAD_REQUEST) + if choice is not None and choice.kind == ToolChoiceKind.ANY and len(request.tools) == 1: + return request.tools[0] + raise LLMError( + "Subscription CLI providers support only a single forced tool (structured output); " + "free tool use is not available. Use an API-key provider for tool-calling agents.", + LLMErrorCategory.BAD_REQUEST, + ) + + +def strict_schema(schema: dict[str, Any]) -> dict[str, Any]: + """Return a copy of *schema* in OpenAI strict structured-output form. + + Codex's ``--output-schema`` enforces OpenAI strict mode: every object + needs ``additionalProperties: false`` and must list all properties as + required. Optional properties become required-but-nullable so their + meaning survives. + """ + + def walk(node: Any) -> Any: + if isinstance(node, list): + return [walk(n) for n in node] + if not isinstance(node, dict): + return node + out = {k: walk(v) for k, v in node.items()} + if out.get("type") == "object" or "properties" in out: + props: dict[str, Any] = out.get("properties", {}) + required = set(out.get("required", [])) + for name, sub in props.items(): + if name not in required and isinstance(sub, dict): + sub_type = sub.get("type") + if isinstance(sub_type, str): + props[name] = {**sub, "type": [sub_type, "null"]} + elif isinstance(sub_type, list) and "null" not in sub_type: + props[name] = {**sub, "type": [*sub_type, "null"]} + out["properties"] = props + out["required"] = list(props) + out["additionalProperties"] = False + return out + + return walk(schema) + + +def classify_cli_error(message: str, *, status: int | None = None) -> LLMErrorCategory: + """Map CLI error text (and an optional HTTP status) to an error category.""" + if status is not None: + if status in (401, 403): + return LLMErrorCategory.AUTHENTICATION + if status == 429: + return LLMErrorCategory.RATE_LIMIT + if status >= 500: + return LLMErrorCategory.SERVER_ERROR + if 400 <= status < 500: + return LLMErrorCategory.BAD_REQUEST + lower = message.lower() + if any(m in lower for m in _RATE_LIMIT_MARKERS): + return LLMErrorCategory.RATE_LIMIT + if any(m in lower for m in _AUTH_MARKERS): + return LLMErrorCategory.AUTHENTICATION + if any(m in lower for m in _OVERLOADED_MARKERS): + return LLMErrorCategory.SERVER_ERROR + return LLMErrorCategory.SERVER_ERROR + + +def _run_cli( + provider_name: str, + argv: list[str], + *, + stdin: str, + cwd: Path, + env: dict[str, str] | None = None, +) -> subprocess.CompletedProcess[str]: + sem = _semaphore_for(provider_name) + with sem: + try: + return subprocess.run( + argv, + input=stdin, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + cwd=cwd, + env=env, + timeout=_timeout(), + check=False, + ) + except subprocess.TimeoutExpired as exc: + raise LLMError( + f"{provider_name} CLI timed out after {exc.timeout:.0f}s (raise {_TIMEOUT_ENV} for long calls)", + LLMErrorCategory.TRANSPORT, + cause=exc, + ) from exc + except OSError as exc: + raise LLMError( + f"Failed to launch {provider_name} CLI: {exc}", + LLMErrorCategory.TRANSPORT, + cause=exc, + ) from exc + + +def _structured_response( + *, + model: str, + tool: ToolDefinition | None, + data: Any, + text: str, + usage: TokenUsage, + stop_reason: StopReason | None, +) -> CompletionResponse: + """Build a response; a forced tool + parsed object becomes a tool call.""" + if tool is not None and isinstance(data, dict): + return CompletionResponse( + id=f"cli_{uuid.uuid4().hex}", + model=model, + content=[ToolInvocationBlock(id=f"toolu_cli_{uuid.uuid4().hex[:24]}", name=tool.name, input=data)], + stop_reason=StopReason.TOOL_USE, + usage=usage, + ) + # No parseable object: return the text so the structured-output engine's + # retry ladder sees a missing tool call and re-prompts. + return CompletionResponse( + id=f"cli_{uuid.uuid4().hex}", + model=model, + content=[TextBlock(text=text)] if text else [], + stop_reason=stop_reason or StopReason.END_TURN, + usage=usage, + ) + + +def _single_shot_stream(response: CompletionResponse) -> Iterator[StreamEvent]: + """Replay a completed response as a minimal event stream.""" + yield StreamEvent(type=StreamEventType.MESSAGE_START, data={"id": response.id, "model": response.model}) + if response.text: + yield StreamEvent(type=StreamEventType.CONTENT_BLOCK_DELTA, index=0, data={"text": response.text}) + stop = response.stop_reason.value if response.stop_reason else None + yield StreamEvent(type=StreamEventType.MESSAGE_DELTA, data={"stop_reason": stop}) + yield StreamEvent(type=StreamEventType.MESSAGE_STOP, data={}) + + +def _try_parse_json(text: str) -> Any: + try: + return json.loads(text) + except (json.JSONDecodeError, ValueError): + pass + for line in reversed(text.splitlines()): + line = line.strip() + if line.startswith("{"): + try: + return json.loads(line) + except (json.JSONDecodeError, ValueError): + continue + return None + + +# --------------------------------------------------------------------------- +# Claude Code +# --------------------------------------------------------------------------- + + +class ClaudeCodeProvider(LLMProvider): + """Completions via ``claude -p`` on the user's Claude subscription.""" + + config = CLAUDE_CODE_CONFIG + + def __init__(self) -> None: + self._exe = self.config.resolve_executable() + + def _env(self) -> dict[str, str]: + env = dict(os.environ) + if not _api_key_allowed(): + env.pop("ANTHROPIC_API_KEY", None) + return env + + def send(self, request: CompletionRequest) -> CompletionResponse: + _warn_ignored_sampling_params(self.config.name, request) + tool = forced_tool(request) + prompt = render_prompt(request.messages) + with tempfile.TemporaryDirectory(dir=_scratch_dir()) as tmp: + system_file = Path(tmp) / "system.txt" + system_file.write_text(request.system or _NEUTRAL_SYSTEM_PROMPT, encoding="utf-8") + argv = [ + self._exe, + "-p", + "--output-format", + "json", + "--system-prompt-file", + str(system_file), + "--tools", + "", + "--setting-sources", + "", + "--strict-mcp-config", + "--no-session-persistence", + ] + model = cli_model_name(request.model, CLAUDE_CODE_PREFIX) + if model: + argv += ["--model", model] + effort = os.environ.get("ALTHING_CLAUDE_CODE_EFFORT", "").strip() + if effort: + argv += ["--effort", effort] + if tool is not None: + argv += ["--json-schema", json.dumps(tool.input_schema)] + proc = _run_cli(self.config.name, argv, stdin=prompt, cwd=Path(tmp), env=self._env()) + return self._parse(proc, request, tool) + + def _parse( + self, + proc: subprocess.CompletedProcess[str], + request: CompletionRequest, + tool: ToolDefinition | None, + ) -> CompletionResponse: + data = _try_parse_json(proc.stdout or "") + if not isinstance(data, dict): + detail = (proc.stderr or proc.stdout or "").strip()[-500:] + raise LLMError( + f"Claude Code CLI exited {proc.returncode} without a JSON result: {detail}", + classify_cli_error(detail), + ) + if data.get("is_error") or data.get("subtype") not in (None, "success"): + detail = str(data.get("result") or data.get("subtype") or "unknown error") + status = data.get("api_error_status") + raise LLMError( + f"Claude Code CLI error: {detail[:500]}", + classify_cli_error(detail, status=status if isinstance(status, int) else None), + status_code=status if isinstance(status, int) else None, + ) + + raw_usage = data.get("usage") or {} + usage = TokenUsage( + input_tokens=int(raw_usage.get("input_tokens") or 0), + output_tokens=int(raw_usage.get("output_tokens") or 0), + cache_write_tokens=int(raw_usage.get("cache_creation_input_tokens") or 0), + cache_read_tokens=int(raw_usage.get("cache_read_input_tokens") or 0), + reasoning_tokens=int((raw_usage.get("output_tokens_details") or {}).get("thinking_tokens") or 0), + # Subscription calls have no per-call bill, so cost falls back to + # the local pricing-table estimate; with an API key allowed + # through, the CLI's own cost figure is what was billed. + provider_reported_cost=data.get("total_cost_usd") if _api_key_allowed() else None, + ) + model_usage = data.get("modelUsage") or {} + served = next(iter(model_usage), None) + model = f"{CLAUDE_CODE_PREFIX}{served}" if served else request.model + stop = StopReason.MAX_TOKENS if data.get("stop_reason") == "max_tokens" else StopReason.END_TURN + result_text = str(data.get("result") or "") + structured = data.get("structured_output") + if tool is not None and structured is None: + structured = _try_parse_json(result_text) + return _structured_response( + model=model, tool=tool, data=structured, text=result_text, usage=usage, stop_reason=stop + ) + + def stream(self, request: CompletionRequest) -> Iterator[StreamEvent]: + yield from _single_shot_stream(self.send(request)) + + +# --------------------------------------------------------------------------- +# Codex +# --------------------------------------------------------------------------- + +# Agent features switched off so a call behaves like a plain completion. +# Passed as ``-c features.=false`` (unknown names are ignored, unlike +# ``--disable``, which errors on features a given codex version lacks). +_CODEX_DISABLED_FEATURES = ( + "apps", + "plugins", + "multi_agent", + "shell_tool", + "unified_exec", + "goals", + "hooks", + "tool_suggest", +) + + +class CodexProvider(LLMProvider): + """Completions via ``codex exec`` on the user's ChatGPT subscription.""" + + config = CODEX_CONFIG + + def __init__(self) -> None: + self._exe = self.config.resolve_executable() + + def send(self, request: CompletionRequest) -> CompletionResponse: + _warn_ignored_sampling_params(self.config.name, request) + tool = forced_tool(request) + prompt = render_prompt(request.messages) + with tempfile.TemporaryDirectory(dir=_scratch_dir()) as tmp: + tmp_path = Path(tmp) + instructions = tmp_path / "instructions.md" + instructions.write_text(request.system or _NEUTRAL_SYSTEM_PROMPT, encoding="utf-8") + last_message = tmp_path / "last_message.txt" + argv = [ + self._exe, + "exec", + "--skip-git-repo-check", + "--ephemeral", + "--ignore-user-config", + "--ignore-rules", + "--sandbox", + "read-only", + "--cd", + str(tmp_path), + "--json", + "--output-last-message", + str(last_message), + "-c", + f"model_instructions_file={json.dumps(instructions.as_posix())}", + "-c", + "mcp_servers={}", + "-c", + "tools.web_search=false", + ] + for feature in _CODEX_DISABLED_FEATURES: + argv += ["-c", f"features.{feature}=false"] + effort = os.environ.get("ALTHING_CODEX_EFFORT", "").strip() + if effort: + argv += ["-c", f"model_reasoning_effort={json.dumps(effort)}"] + model = cli_model_name(request.model, CODEX_PREFIX) + if model: + argv += ["--model", model] + if tool is not None: + schema_file = tmp_path / "schema.json" + schema_file.write_text(json.dumps(strict_schema(tool.input_schema)), encoding="utf-8") + argv += ["--output-schema", str(schema_file)] + argv.append("-") + proc = _run_cli(self.config.name, argv, stdin=prompt, cwd=tmp_path) + final_text = last_message.read_text(encoding="utf-8") if last_message.is_file() else "" + return self._parse(proc, final_text, request, tool) + + def _parse( + self, + proc: subprocess.CompletedProcess[str], + final_text: str, + request: CompletionRequest, + tool: ToolDefinition | None, + ) -> CompletionResponse: + usage = TokenUsage() + messages: list[str] = [] + errors: list[str] = [] + for line in (proc.stdout or "").splitlines(): + try: + event = json.loads(line) + except (json.JSONDecodeError, ValueError): + continue + kind = event.get("type") + if kind == "turn.completed": + raw = event.get("usage") or {} + usage = usage + TokenUsage( + input_tokens=int(raw.get("input_tokens") or 0), + output_tokens=int(raw.get("output_tokens") or 0), + cached_tokens=int(raw.get("cached_input_tokens") or 0), + reasoning_tokens=int(raw.get("reasoning_output_tokens") or 0), + ) + elif kind == "item.completed": + item = event.get("item") or {} + if item.get("type") == "agent_message" and item.get("text"): + messages.append(str(item["text"])) + elif kind in ("error", "turn.failed"): + err = event.get("error") if isinstance(event.get("error"), dict) else {} + errors.append(str(event.get("message") or err.get("message") or event)) + + text = final_text.strip() or (messages[-1] if messages else "") + if not text: + detail = "; ".join(errors) or (proc.stderr or "").strip()[-500:] or f"exit code {proc.returncode}" + raise LLMError(f"Codex CLI produced no response: {detail[:500]}", classify_cli_error(detail)) + + structured = _try_parse_json(text) if tool is not None else None + if tool is not None and isinstance(structured, dict): + # Undo strict_schema's required-but-nullable rewrite for fields the + # caller's schema left optional. + required = set(tool.input_schema.get("required", [])) + structured = {k: v for k, v in structured.items() if v is not None or k in required} + return _structured_response( + model=request.model, tool=tool, data=structured, text=text, usage=usage, stop_reason=None + ) + + def stream(self, request: CompletionRequest) -> Iterator[StreamEvent]: + yield from _single_shot_stream(self.send(request)) diff --git a/src/althing/mcp/sampling.py b/src/althing/mcp/sampling.py index 07352870..c0736f40 100644 --- a/src/althing/mcp/sampling.py +++ b/src/althing/mcp/sampling.py @@ -1,9 +1,15 @@ """MCP sampling bridge. MCP's *sampling* feature lets an MCP server ask the invoking client -(Claude Desktop, Claude Code, Cursor, Windsurf, ...) to run an LLM -completion on the server's behalf, using the client's own subscription -or credentials. This lets althing give first-time users a +(e.g. Claude Desktop) to run an LLM completion on the server's behalf, +using the client's own subscription or credentials. + +Sampling is deprecated as of MCP 2026-07-28 (SEP-2577) and Claude Code +never implemented the client side. The subscription CLI providers +(``claude-code:*`` / ``codex:*`` in +:mod:`althing.llm.providers.subscription_cli`) are the forward-looking +"run on the user's subscription" path; an explicit CLI model makes +:func:`decide_mode` pick BYOK. This lets althing give first-time users a zero-configuration experience — no ``ANTHROPIC_API_KEY`` setup needed to fire their first prompt or quick poll. @@ -196,6 +202,7 @@ def decide_mode( *, use_sampling: bool | None = None, env: dict[str, str] | None = None, + model: str | None = None, ) -> SamplingDecision: """Choose between sampling and BYOK for this tool call. @@ -207,6 +214,9 @@ def decide_mode( env: Optional env dict for testing. When ``None`` both the process environment and the on-disk credential store are consulted via :func:`has_byok_credentials`. + model: The model the call will run on. A subscription CLI model + (``claude-code:*`` / ``codex:*``) needs no API key, so it + counts as available credentials in auto mode. Rules (in order): * ``use_sampling=True`` + client supports sampling → sampling. @@ -216,11 +226,14 @@ def decide_mode( * Auto + no creds + client supports sampling → sampling. * Auto + no creds + no sampling → error (set an API key OR use a sampling-capable client). - * Auto + creds present → BYOK (preserves existing behaviour - and keeps ensemble / multi-provider features available). + * Auto + creds present (or a subscription CLI model) → BYOK + (preserves existing behaviour and keeps ensemble / + multi-provider features available). """ + from althing.llm.providers.subscription_cli import is_subscription_cli_model + supports = client_supports_sampling(ctx) - has_creds = has_byok_credentials(env) + has_creds = is_subscription_cli_model(model) or has_byok_credentials(env) if use_sampling is True: if supports: @@ -229,10 +242,11 @@ def decide_mode( mode="error", error=( "use_sampling=True was requested, but the invoking MCP " - "client did not advertise the 'sampling' capability. " - "Either run althing from a sampling-capable client " - "(Claude Desktop, Claude Code, Cursor, Windsurf) or set " - "a provider API key (e.g. ANTHROPIC_API_KEY) to use BYOK." + "client did not advertise the 'sampling' capability " + "(Claude Code does not support MCP sampling). Set a " + "provider API key (e.g. ANTHROPIC_API_KEY), or pass a " + "subscription CLI model such as model='claude-code:haiku' " + "to run on a signed-in Claude Code / Codex CLI." ), ) @@ -250,9 +264,11 @@ def decide_mode( "No provider credentials found (ANTHROPIC_API_KEY / " "OPENAI_API_KEY / XAI_API_KEY / GOOGLE_API_KEY / " "GEMINI_API_KEY / OPENROUTER_API_KEY) and the invoking " - "MCP client did not advertise 'sampling' capability. " - "Set a provider key in your environment, or run althing " - "from a sampling-capable client such as Claude Desktop. " + "MCP client did not advertise 'sampling' capability. Set a " + "provider key in your environment, pass a subscription CLI " + "model such as model='claude-code:haiku' to run on a " + "signed-in Claude Code / Codex CLI, or run althing from a " + "sampling-capable client (Claude Code is not one). " "See https://althing.dev/mcp#credentials." ), ) diff --git a/src/althing/mcp/server.py b/src/althing/mcp/server.py index ae70bf0f..d6692e3b 100644 --- a/src/althing/mcp/server.py +++ b/src/althing/mcp/server.py @@ -1671,7 +1671,7 @@ async def run_prompt( if spec_error is not None: return spec_error model = model or _resolve_mcp_default_model() - decision = _decide_sampling_mode(ctx, use_sampling=use_sampling) + decision = _decide_sampling_mode(ctx, use_sampling=use_sampling, model=model) logger.info("run_prompt: mode=%s model=%s prompt_len=%d", decision.mode, model, len(prompt)) if decision.mode == "error": @@ -2112,7 +2112,7 @@ async def run_panel( # Ensemble mode is BYOK-only (sampling host exposes only one model), # so we only consult the decision in the non-ensemble branch. if not (models and len(models) >= 2): - decision = _decide_sampling_mode(ctx, use_sampling=use_sampling) + decision = _decide_sampling_mode(ctx, use_sampling=use_sampling, model=model) if decision.mode == "error": return json.dumps({"error": decision.error}) if decision.mode == "sampling": @@ -2508,7 +2508,7 @@ async def run_quick_poll( if not model_was_explicit: model = _resolve_mcp_default_model_for_panel(len(personas)) - decision = _decide_sampling_mode(ctx, use_sampling=use_sampling) + decision = _decide_sampling_mode(ctx, use_sampling=use_sampling, model=model) logger.info("run_quick_poll: mode=%s model=%s personas=%d", decision.mode, model, len(personas)) if decision.mode == "error": diff --git a/src/althing/structured/output.py b/src/althing/structured/output.py index b52b6de0..29ca9e10 100644 --- a/src/althing/structured/output.py +++ b/src/althing/structured/output.py @@ -26,6 +26,7 @@ ToolInvocationBlock, ToolResultBlock, ) +from althing.llm.providers.subscription_cli import CLAUDE_CODE_PREFIX, CODEX_PREFIX logger = logging.getLogger(__name__) @@ -97,6 +98,8 @@ def _escalation_model_for(model: str) -> str | None: the final strike (gh#571). Per family: * ``openrouter/*`` → OpenRouter-served Sonnet (same key; sy-549, unchanged) + * ``claude-code:*`` → ``claude-code:sonnet`` (stays on the subscription CLI) + * ``codex:*`` → none * ``claude-*`` → ``sonnet`` alias (historical behaviour, unchanged) * ``gemini-*`` → ``gemini-2.5-pro`` * ``grok-*`` → ``grok-4`` @@ -114,6 +117,15 @@ def _escalation_model_for(model: str) -> str | None: if model.startswith(_OPENROUTER_PREFIX): return _OPENROUTER_ESCALATION_MODEL + # Subscription CLI models must stay on the same CLI: ``claude-code:haiku`` + # starts with ``claude-`` and would otherwise escalate to the API-key + # ``sonnet`` alias. + if model.startswith(CLAUDE_CODE_PREFIX): + target = f"{CLAUDE_CODE_PREFIX}sonnet" + return None if model == target else target + if model.startswith(CODEX_PREFIX): + return None # no stable cheap/strong model ladder on the Codex CLI + canonical = resolve_alias(model) if canonical.startswith("claude-"): return _ESCALATION_MODEL diff --git a/tests/test_subscription_cli.py b/tests/test_subscription_cli.py new file mode 100644 index 00000000..597f5eee --- /dev/null +++ b/tests/test_subscription_cli.py @@ -0,0 +1,455 @@ +"""Tests for the subscription CLI providers (claude-code:* / codex:*).""" + +from __future__ import annotations + +import json +import subprocess +from decimal import Decimal +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest + +from althing.llm.client import LLMClient +from althing.llm.errors import LLMError, LLMErrorCategory +from althing.llm.models import ( + CompletionRequest, + InputMessage, + StopReason, + TextBlock, + ToolChoice, + ToolDefinition, + ToolInvocationBlock, +) +from althing.llm.providers import subscription_cli as cli +from althing.llm.providers.subscription_cli import ( + ClaudeCodeProvider, + CodexProvider, + render_prompt, + strict_schema, +) + +SCHEMA = { + "type": "object", + "properties": { + "choice": {"type": "string", "enum": ["A", "B"]}, + "note": {"type": "string"}, + }, + "required": ["choice"], +} +RESPOND = ToolDefinition(name="respond", input_schema=SCHEMA) + + +def _request(model: str, *, tool: bool = False, system: str | None = "You are Maria.") -> CompletionRequest: + return CompletionRequest( + model=model, + max_tokens=256, + system=system, + messages=[InputMessage(role="user", content=[TextBlock(text="Pick one: (A) or (B)")])], + tools=[RESPOND] if tool else None, + tool_choice=ToolChoice.specific("respond") if tool else None, + ) + + +def _completed(stdout: str = "", stderr: str = "", returncode: int = 0) -> subprocess.CompletedProcess[str]: + return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr) + + +def _claude_result(**overrides) -> str: + payload = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "Hello there", + "stop_reason": "end_turn", + "total_cost_usd": 0.0123, + "api_error_status": None, + "usage": { + "input_tokens": 10, + "output_tokens": 20, + "cache_creation_input_tokens": 30, + "cache_read_input_tokens": 40, + "output_tokens_details": {"thinking_tokens": 5}, + }, + "modelUsage": {"claude-haiku-5-5": {"inputTokens": 10}}, + } + payload.update(overrides) + return json.dumps(payload) + + +@pytest.fixture(autouse=True) +def _fake_executables(): + with patch.object(cli.shutil, "which", side_effect=lambda name: f"/usr/bin/{Path(name).name}"): + yield + + +# --------------------------------------------------------------------------- +# Routing +# --------------------------------------------------------------------------- + + +class TestRouting: + def test_claude_code_prefix_routes_before_anthropic(self): + provider = LLMClient()._resolve_provider("claude-code:haiku") + assert isinstance(provider, ClaudeCodeProvider) + + def test_codex_prefix_routes_to_codex(self): + provider = LLMClient()._resolve_provider("codex:") + assert isinstance(provider, CodexProvider) + + def test_plain_claude_model_still_routes_to_anthropic(self, monkeypatch): + from althing.llm.providers.anthropic import AnthropicProvider + + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test") + provider = LLMClient()._resolve_provider("claude-sonnet-5") + assert isinstance(provider, AnthropicProvider) + + def test_cli_providers_never_used_as_credential_fallback(self): + assert cli.CLAUDE_CODE_CONFIG.has_credentials() is False + assert cli.CODEX_CONFIG.has_credentials() is False + + def test_missing_executable_is_missing_credentials(self): + with patch.object(cli.shutil, "which", return_value=None), pytest.raises(LLMError) as exc: + ClaudeCodeProvider() + assert exc.value.category == LLMErrorCategory.MISSING_CREDENTIALS + assert "claude" in str(exc.value) + + def test_is_subscription_cli_model(self): + assert cli.is_subscription_cli_model("claude-code:sonnet") + assert cli.is_subscription_cli_model("codex:") + assert not cli.is_subscription_cli_model("claude-sonnet-5") + assert not cli.is_subscription_cli_model(None) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +class TestRenderPrompt: + def test_single_message_passes_through(self): + msgs = [InputMessage(role="user", content=[TextBlock(text="Hi")])] + assert render_prompt(msgs) == "Hi" + + def test_history_is_rendered_as_transcript(self): + msgs = [ + InputMessage(role="user", content=[TextBlock(text="Q1")]), + InputMessage(role="assistant", content=[TextBlock(text="A1")]), + InputMessage(role="user", content=[TextBlock(text="Q2")]), + ] + out = render_prompt(msgs) + assert "\nQ1\n" in out + assert "\nA1\n" in out + assert out.endswith("Q2") + + def test_tool_calls_in_history_render_as_text(self): + msgs = [ + InputMessage(role="user", content=[TextBlock(text="Q1")]), + InputMessage( + role="assistant", + content=[ToolInvocationBlock(id="t1", name="respond", input={"choice": "A"})], + ), + InputMessage(role="user", content=[TextBlock(text="Try again")]), + ] + assert '"choice": "A"' in render_prompt(msgs) + + def test_attachments_rejected(self): + from althing.llm.models import ImageBlock, InlineSource + + msgs = [InputMessage(role="user", content=[ImageBlock(source=InlineSource(data="xx"))])] + with pytest.raises(LLMError) as exc: + render_prompt(msgs) + assert exc.value.category == LLMErrorCategory.BAD_REQUEST + + +class TestForcedTool: + def test_unforced_tools_rejected(self): + req = _request("claude-code:haiku") + req.tools = [RESPOND] + req.tool_choice = ToolChoice.auto() + with pytest.raises(LLMError) as exc: + cli.forced_tool(req) + assert exc.value.category == LLMErrorCategory.BAD_REQUEST + + def test_any_with_single_tool_is_forced(self): + req = _request("claude-code:haiku") + req.tools = [RESPOND] + req.tool_choice = ToolChoice.any() + assert cli.forced_tool(req) is RESPOND + + +class TestStrictSchema: + def test_optional_fields_become_required_nullable(self): + out = strict_schema(SCHEMA) + assert out["additionalProperties"] is False + assert out["required"] == ["choice", "note"] + assert out["properties"]["note"]["type"] == ["string", "null"] + assert out["properties"]["choice"]["type"] == "string" + assert SCHEMA["required"] == ["choice"] # input not mutated + + def test_nested_objects_are_strict(self): + schema = { + "type": "object", + "properties": {"inner": {"type": "object", "properties": {"x": {"type": "integer"}}}}, + } + out = strict_schema(schema) + assert out["properties"]["inner"]["type"] == ["object", "null"] + assert out["properties"]["inner"]["additionalProperties"] is False + assert out["properties"]["inner"]["required"] == ["x"] + + +@pytest.mark.parametrize( + ("message", "status", "expected"), + [ + ("Claude AI usage limit reached|1760000000", None, LLMErrorCategory.RATE_LIMIT), + ("You've hit your limit · resets 3pm", None, LLMErrorCategory.RATE_LIMIT), + ("Not logged in · Please run /login", None, LLMErrorCategory.AUTHENTICATION), + ("API Error: 529 Overloaded", None, LLMErrorCategory.SERVER_ERROR), + ("anything", 429, LLMErrorCategory.RATE_LIMIT), + ("anything", 400, LLMErrorCategory.BAD_REQUEST), + ], +) +def test_classify_cli_error(message, status, expected): + assert cli.classify_cli_error(message, status=status) == expected + + +# --------------------------------------------------------------------------- +# Claude Code provider +# --------------------------------------------------------------------------- + + +class TestClaudeCodeProvider: + def test_plain_text_call(self, monkeypatch): + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-should-be-stripped") + run = MagicMock(return_value=_completed(_claude_result())) + with patch.object(cli.subprocess, "run", run): + resp = ClaudeCodeProvider().send(_request("claude-code:haiku")) + + argv = run.call_args.args[0] + kwargs = run.call_args.kwargs + assert argv[:2] == ["/usr/bin/claude", "-p"] + assert argv[argv.index("--tools") + 1] == "" + assert argv[argv.index("--setting-sources") + 1] == "" + assert argv[argv.index("--model") + 1] == "haiku" + assert "--strict-mcp-config" in argv + assert "--no-session-persistence" in argv + assert "--json-schema" not in argv + assert kwargs["input"] == "Pick one: (A) or (B)" + assert "ANTHROPIC_API_KEY" not in kwargs["env"] + + assert resp.text == "Hello there" + assert resp.model == "claude-code:claude-haiku-5-5" + assert resp.stop_reason == StopReason.END_TURN + assert resp.usage.input_tokens == 10 + assert resp.usage.output_tokens == 20 + assert resp.usage.cache_write_tokens == 30 + assert resp.usage.cache_read_tokens == 40 + assert resp.usage.reasoning_tokens == 5 + assert resp.usage.provider_reported_cost is None + + def test_system_prompt_replaces_agent_prompt(self): + seen: dict[str, str] = {} + + def fake_run(argv, **kwargs): + seen["system"] = Path(argv[argv.index("--system-prompt-file") + 1]).read_text(encoding="utf-8") + return _completed(_claude_result()) + + with patch.object(cli.subprocess, "run", side_effect=fake_run): + ClaudeCodeProvider().send(_request("claude-code:", system=None)) + assert seen["system"] == cli._NEUTRAL_SYSTEM_PROMPT + + def test_default_model_omits_model_flag(self): + run = MagicMock(return_value=_completed(_claude_result())) + with patch.object(cli.subprocess, "run", run): + ClaudeCodeProvider().send(_request("claude-code:")) + assert "--model" not in run.call_args.args[0] + + def test_api_key_kept_when_allowed(self, monkeypatch): + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-keep") + monkeypatch.setenv("ALTHING_CLAUDE_CODE_ALLOW_API_KEY", "1") + run = MagicMock(return_value=_completed(_claude_result())) + with patch.object(cli.subprocess, "run", run): + resp = ClaudeCodeProvider().send(_request("claude-code:haiku")) + assert run.call_args.kwargs["env"]["ANTHROPIC_API_KEY"] == "sk-keep" + assert resp.usage.provider_reported_cost == Decimal("0.0123") + + def test_structured_output_becomes_tool_call(self): + run = MagicMock( + return_value=_completed(_claude_result(result='{"choice":"A"}', structured_output={"choice": "A"})) + ) + with patch.object(cli.subprocess, "run", run): + resp = ClaudeCodeProvider().send(_request("claude-code:haiku", tool=True)) + + argv = run.call_args.args[0] + assert json.loads(argv[argv.index("--json-schema") + 1]) == SCHEMA + assert resp.stop_reason == StopReason.TOOL_USE + assert resp.tool_calls[0].name == "respond" + assert resp.tool_calls[0].input == {"choice": "A"} + + def test_missing_structured_output_returns_text_for_retry(self): + run = MagicMock(return_value=_completed(_claude_result(result="I refuse to pick"))) + with patch.object(cli.subprocess, "run", run): + resp = ClaudeCodeProvider().send(_request("claude-code:haiku", tool=True)) + assert resp.tool_calls == [] + assert resp.text == "I refuse to pick" + + def test_usage_limit_error_is_rate_limit(self): + out = _claude_result(is_error=True, result="Claude AI usage limit reached|1760000000") + with ( + patch.object(cli.subprocess, "run", return_value=_completed(out, returncode=1)), + pytest.raises(LLMError) as exc, + ): + ClaudeCodeProvider().send(_request("claude-code:haiku")) + assert exc.value.category == LLMErrorCategory.RATE_LIMIT + assert exc.value.retryable + + def test_non_json_output_is_classified(self): + with ( + patch.object(cli.subprocess, "run", return_value=_completed("", "Not logged in", returncode=1)), + pytest.raises(LLMError) as exc, + ): + ClaudeCodeProvider().send(_request("claude-code:haiku")) + assert exc.value.category == LLMErrorCategory.AUTHENTICATION + + def test_timeout_is_transport_error(self): + with ( + patch.object(cli.subprocess, "run", side_effect=subprocess.TimeoutExpired(cmd="claude", timeout=5)), + pytest.raises(LLMError) as exc, + ): + ClaudeCodeProvider().send(_request("claude-code:haiku")) + assert exc.value.category == LLMErrorCategory.TRANSPORT + + def test_stream_replays_single_response(self): + from althing.llm.models import StreamEventType + + with patch.object(cli.subprocess, "run", return_value=_completed(_claude_result())): + events = list(ClaudeCodeProvider().stream(_request("claude-code:haiku"))) + assert [e.type for e in events] == [ + StreamEventType.MESSAGE_START, + StreamEventType.CONTENT_BLOCK_DELTA, + StreamEventType.MESSAGE_DELTA, + StreamEventType.MESSAGE_STOP, + ] + assert events[1].data == {"text": "Hello there"} + + +# --------------------------------------------------------------------------- +# Codex provider +# --------------------------------------------------------------------------- + + +def _codex_run(final_text: str, *, events: list[dict] | None = None, returncode: int = 0, seen: dict | None = None): + """Build a fake subprocess.run that writes codex's last-message file.""" + default_events = [ + {"type": "thread.started", "thread_id": "t"}, + {"type": "item.completed", "item": {"id": "i0", "type": "agent_message", "text": final_text}}, + { + "type": "turn.completed", + "usage": {"input_tokens": 100, "cached_input_tokens": 60, "output_tokens": 7, "reasoning_output_tokens": 2}, + }, + ] + + def fake_run(argv, **kwargs): + if seen is not None: + seen["argv"] = argv + seen["kwargs"] = kwargs + if "--output-schema" in argv: + schema_path = Path(argv[argv.index("--output-schema") + 1]) + seen["schema"] = json.loads(schema_path.read_text(encoding="utf-8")) + if final_text: + Path(argv[argv.index("--output-last-message") + 1]).write_text(final_text, encoding="utf-8") + stdout = "\n".join(json.dumps(e) for e in (events if events is not None else default_events)) + return _completed(stdout, returncode=returncode) + + return fake_run + + +class TestCodexProvider: + def test_plain_text_call(self): + seen: dict = {} + with patch.object(cli.subprocess, "run", side_effect=_codex_run("Hi, I'm Maria.", seen=seen)): + resp = CodexProvider().send(_request("codex:gpt-5.5")) + + argv = seen["argv"] + assert argv[:2] == ["/usr/bin/codex", "exec"] + for flag in ("--ephemeral", "--ignore-user-config", "--skip-git-repo-check", "--json"): + assert flag in argv + assert argv[argv.index("--sandbox") + 1] == "read-only" + assert argv[argv.index("--model") + 1] == "gpt-5.5" + assert "features.shell_tool=false" in argv + assert any(a.startswith("model_instructions_file=") for a in argv) + assert argv[-1] == "-" + assert seen["kwargs"]["input"] == "Pick one: (A) or (B)" + + assert resp.text == "Hi, I'm Maria." + assert resp.model == "codex:gpt-5.5" + assert resp.usage.input_tokens == 100 + assert resp.usage.cached_tokens == 60 + assert resp.usage.output_tokens == 7 + assert resp.usage.reasoning_tokens == 2 + assert resp.usage.provider_reported_cost is None + + def test_structured_output_uses_strict_schema_and_strips_nulls(self): + seen: dict = {} + fake = _codex_run('{"choice":"B","note":null}', seen=seen) + with patch.object(cli.subprocess, "run", side_effect=fake): + resp = CodexProvider().send(_request("codex:", tool=True)) + + assert seen["schema"]["additionalProperties"] is False + assert "--model" not in seen["argv"] + assert resp.stop_reason == StopReason.TOOL_USE + assert resp.tool_calls[0].input == {"choice": "B"} + + def test_failed_turn_without_message_raises(self): + events = [{"type": "turn.failed", "error": {"message": "You've hit your usage limit."}}] + with ( + patch.object(cli.subprocess, "run", side_effect=_codex_run("", events=events, returncode=1)), + pytest.raises(LLMError) as exc, + ): + CodexProvider().send(_request("codex:")) + assert exc.value.category == LLMErrorCategory.RATE_LIMIT + + +# --------------------------------------------------------------------------- +# Integration with the structured-output engine and MCP mode selection +# --------------------------------------------------------------------------- + + +class TestIntegration: + def test_structured_engine_round_trip(self): + from althing.structured.output import StructuredOutputConfig, StructuredOutputEngine + + out = _claude_result(result='{"choice":"A"}', structured_output={"choice": "A"}) + with patch.object(cli.subprocess, "run", return_value=_completed(out)): + result = StructuredOutputEngine(LLMClient()).extract( + model="claude-code:haiku", + max_tokens=256, + messages=[InputMessage(role="user", content=[TextBlock(text="Pick")])], + config=StructuredOutputConfig(schema=SCHEMA), + ) + assert result.data == {"choice": "A"} + assert not result.is_fallback + + def test_escalation_stays_on_cli(self): + from althing.structured.output import _escalation_model_for + + assert _escalation_model_for("claude-code:haiku") == "claude-code:sonnet" + assert _escalation_model_for("claude-code:sonnet") is None + assert _escalation_model_for("codex:gpt-5-mini") is None + assert _escalation_model_for("claude-haiku-4-5-20251001") == "sonnet" + + def test_decide_mode_cli_model_needs_no_key_or_sampling(self): + from althing.mcp.sampling import decide_mode + + ctx = MagicMock() + ctx.session.check_client_capability.return_value = False + assert decide_mode(ctx, env={}).mode == "error" + assert decide_mode(ctx, env={}, model="claude-code:haiku").mode == "byok" + assert decide_mode(ctx, env={}, model="codex:").mode == "byok" + + def test_decide_mode_explicit_sampling_still_wins(self): + from althing.mcp.sampling import decide_mode + + ctx = MagicMock() + ctx.session.check_client_capability.return_value = True + assert decide_mode(ctx, env={}, model="claude-code:haiku", use_sampling=True).mode == "sampling"