Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
minor: Add xKiro provider (#1960)
Ali Khokharf88793c7815d
diff --git a/README.md b/README.mdindex 66ad4395..76682879 100644--- a/README.md+++ b/README.md@@ -25,7 +25,7 @@## What You Get-- **56 ToS-friendly providers. 1.3B+ free tokens every month.** Use free, paid, subscription, and local models from one searchable UI without putting your account at risk. FCC follows provider terms and removes integrations if they stop being allowed.+- **58 ToS-friendly providers. 1.3B+ free tokens every month.** Use free, paid, subscription, and local models from one searchable UI without putting your account at risk. FCC follows provider terms and removes integrations if they stop being allowed.- **11 coding agents. One model catalog.** Run [Claude Code](https://code.claude.com/docs/en/overview), [Codex](https://github.com/openai/codex), [Pi](https://github.com/earendil-works/pi), [OpenCode](https://github.com/anomalyco/opencode), [Cline](https://github.com/cline/cline), [Hermes](https://github.com/NousResearch/hermes-agent), [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness), [Grok Build](https://github.com/xai-org/grok-build), [Muse Code](https://research.meta.ai/blog/introducing-muse-code-and-muse-spark-1-2/), [Aider](https://aider.chat/), or [VS Code Chat](https://code.visualstudio.com/) with your FCC models.- **Keep coding through provider outages.** After retries are exhausted, FCC automatically tries your next configured model without making you restart the turn. This works across every client.- **Up to 90% fewer terminal-output tokens.** Optional [RTK](https://github.com/rtk-ai/rtk) filters common command output, while five FCC optimizations handle quota probes, command-prefix detection, titles, suggestions, and filepaths without calling a provider.@@ -258,6 +258,7 @@ For another API endpoint, open **Providers → Custom providers → Add provider| [Experiential Labs](https://platform.experientiallabs.ai/) | `EXPLABS_API_KEY` | `experiential/union-alpha` || [Cheaper Inference](https://cheaperinference.com/signup) | `CHEAPER_INFERENCE_API_KEY` | `cheaperinference/gpt-5.4-mini` || [OrcaRouter](https://www.orcarouter.ai/) | `ORCAROUTER_API_KEY` | `orcarouter/deepseek/deepseek-v4-flash-free` |+| [xKiro](https://xkiro.com/) | `XKIRO_API_KEY` | `xkiro/qwen/qwen3.7-flash:free` || [Ollama Cloud](https://ollama.com/settings/keys) | `OLLAMA_API_KEY` | `ollama_cloud/qwen3-coder:480b` || [LM Studio](https://lmstudio.ai/) | `LM_STUDIO_BASE_URL` | `lmstudio/<model-id>` || [llama.cpp](https://github.com/ggml-org/llama.cpp) | `LLAMACPP_BASE_URL` | `llamacpp/<model-id>` |diff --git a/e2e/test_admin_providers.py b/e2e/test_admin_providers.pyindex f8d98bc0..4c5187d6 100644--- a/e2e/test_admin_providers.py+++ b/e2e/test_admin_providers.py@@ -435,3 +435,18 @@ def test_manual_provider_test_takes_precedence_over_automatic_availability()expect(result).to_have_text("1 model available")expect(dialog.get_by_role("button", name="Test", exact=True)).to_be_enabled()+++def test_xkiro_uses_standard_provider_configuration(page: Page, admin_base_url: str):+ _open_admin(page, admin_base_url, {"width": 1280, "height": 720})+ card = page.locator('[data-provider="xkiro"]')+ expect(card.get_by_role("button", name="Configure", exact=True)).to_be_visible()+ expect(card.locator('a[href="https://xkiro.com/"]')).to_be_visible()+ dialog = open_provider(page, "xkiro")+ expect(dialog.locator("#field-XKIRO_API_KEY")).to_be_focused()+ expect(dialog.locator("#field-XKIRO_API_KEY")).to_have_attribute(+ "data-secret", "true"+ )+ expect(dialog.locator("#field-XKIRO_PROXY")).to_be_visible()+ expect(dialog).to_contain_text("xkiro.com/dashboard/api/keys")+ close_provider(page)diff --git a/smoke/lib/config.py b/smoke/lib/config.pyindex d82a14bd..8528a425 100644--- a/smoke/lib/config.py+++ b/smoke/lib/config.py@@ -98,6 +98,7 @@ PROVIDER_SMOKE_DEFAULT_MODELS: dict[str, str] = {"experiential": "experiential/union-alpha","cheaperinference": "cheaperinference/gpt-5.4-mini","orcarouter": "orcarouter/deepseek/deepseek-v4-flash-free",+ "xkiro": "xkiro/qwen/qwen3.7-flash:free","agnes": "agnes/agnes-2.0-flash","zenmux": "zenmux/deepseek/deepseek-v4-flash-free","wandb": "wandb/openai/gpt-oss-20b",diff --git a/src/free_claude_code/api/admin_static/providers/SOURCES.md b/src/free_claude_code/api/admin_static/providers/SOURCES.mdindex 2baca012..6160905c 100644--- a/src/free_claude_code/api/admin_static/providers/SOURCES.md+++ b/src/free_claude_code/api/admin_static/providers/SOURCES.md@@ -42,6 +42,7 @@ The LLaMA.cpp icon comes from the upstream llama.cpp repository; its MIT license| `opencode.svg` | https://unpkg.com/@lobehub/[email protected]/icons/opencode.svg || `openrouter.svg` | https://unpkg.com/@lobehub/[email protected]/icons/openrouter.svg || `orcarouter.png` | https://www.orcarouter.ai/apple-touch-icon.png |+| `xkiro.png` | https://xkiro.com/images/logo/logo-xt-green.png || `poolside-color.svg` | https://unpkg.com/@lobehub/[email protected]/icons/poolside-color.svg || `qwen-color.svg` | https://unpkg.com/@lobehub/[email protected]/icons/qwen-color.svg || `sambanova-color.svg` | https://unpkg.com/@lobehub/[email protected]/icons/sambanova-color.svg |diff --git a/src/free_claude_code/api/admin_static/providers/xkiro.png b/src/free_claude_code/api/admin_static/providers/xkiro.pngnew file mode 100644index 00000000..1f84de6bBinary files /dev/null and b/src/free_claude_code/api/admin_static/providers/xkiro.png differdiff --git a/src/free_claude_code/config/admin/provider_manifest.py b/src/free_claude_code/config/admin/provider_manifest.pyindex d205f836..6c69d2ef 100644--- a/src/free_claude_code/config/admin/provider_manifest.py+++ b/src/free_claude_code/config/admin/provider_manifest.py@@ -290,6 +290,13 @@ _PROVIDER_FIELD_OVERRIDES: dict[str, ProviderFieldOverride] = {"www.orcarouter.ai/console."),},+ "XKIRO_API_KEY": {+ "label": "xKiro API Key",+ "description": (+ "xKiro API key for api.xkiro.com/v1. "+ "Create one at xkiro.com/dashboard/api/keys."+ ),+ },"AGNES_API_KEY": {"label": "Agnes AI API Key","description": (diff --git a/src/free_claude_code/config/provider_catalog.py b/src/free_claude_code/config/provider_catalog.pyindex a3aff95e..7cc04f3e 100644--- a/src/free_claude_code/config/provider_catalog.py+++ b/src/free_claude_code/config/provider_catalog.py@@ -91,6 +91,8 @@ EXPERIENTIAL_DEFAULT_BASE = "https://api.experientiallabs.ai/v1"CHEAPERINFERENCE_DEFAULT_BASE = "https://api.cheaperinference.com/v1"# OrcaRouter OpenAI-compatible multi-provider gateway.ORCAROUTER_DEFAULT_BASE = "https://api.orcarouter.ai/v1"+# xKiro OpenAI-compatible multi-provider gateway.+XKIRO_DEFAULT_BASE = "https://api.xkiro.com/v1"# Agnes AI OpenAI-compatible Chat Completions API.AGNES_DEFAULT_BASE = "https://apihub.agnes-ai.com/v1"# ZenMux OpenAI-compatible Chat Completions gateway.@@ -726,6 +728,17 @@ PROVIDER_CATALOG: dict[str, ProviderDescriptor] = {default_base_url=ORCAROUTER_DEFAULT_BASE,proxy_attr="orcarouter_proxy",),+ "xkiro": ProviderDescriptor(+ provider_id="xkiro",+ display_name="xKiro",+ website_url="https://xkiro.com/",+ logo_filename="xkiro.png",+ credential_env="XKIRO_API_KEY",+ credential_url="https://xkiro.com/dashboard/api/keys",+ credential_attr="xkiro_api_key",+ default_base_url=XKIRO_DEFAULT_BASE,+ proxy_attr="xkiro_proxy",+ ),"ollama_cloud": ProviderDescriptor(provider_id="ollama_cloud",display_name="Ollama Cloud",diff --git a/src/free_claude_code/config/settings.py b/src/free_claude_code/config/settings.pyindex da4f93aa..37016c09 100644--- a/src/free_claude_code/config/settings.py+++ b/src/free_claude_code/config/settings.py@@ -244,6 +244,11 @@ class Settings(BaseModel):default=None, validation_alias="ORCAROUTER_API_KEY")+ # ==================== xKiro (OpenAI-compatible gateway) ====================+ xkiro_api_key: OptionalNonEmptyString = Field(+ default=None, validation_alias="XKIRO_API_KEY"+ )+# ==================== Fireworks AI Config ====================fireworks_api_key: OptionalNonEmptyString = Field(default=None, validation_alias="FIREWORKS_API_KEY"@@ -564,6 +569,9 @@ class Settings(BaseModel):orcarouter_proxy: OptionalNonEmptyString = Field(default=None, validation_alias="ORCAROUTER_PROXY")+ xkiro_proxy: OptionalNonEmptyString = Field(+ default=None, validation_alias="XKIRO_PROXY"+ )fireworks_proxy: OptionalNonEmptyString = Field(default=None, validation_alias="FIREWORKS_PROXY")diff --git a/src/free_claude_code/providers/credential_validation.py b/src/free_claude_code/providers/credential_validation.pyindex be9a4f7b..7b9b4306 100644--- a/src/free_claude_code/providers/credential_validation.py+++ b/src/free_claude_code/providers/credential_validation.py@@ -146,6 +146,18 @@ _PROBES = (_Probe("nararoute", "/models", _MODELS, _AUTH_401),_Probe("experiential", "/models", _MODELS, _AUTH_401),_Probe("orcarouter", "/models", _MODELS, _AUTH_401),+ # xKiro's /models is public; /usage requires the inference API key.+ # https://docs.xkiro.com/api/usage/+ _Probe(+ "xkiro",+ "/usage",+ lambda p: (+ _field(p, "object") == "usage"+ and isinstance(_field(p, "windows"), list)+ and isinstance(_field(p, "free_tokens"), Mapping)+ ),+ _AUTH_401,+ ),# Positive evidence only: these errors can also reflect permissions, budget,# token type, or an undocumented response contract. Never reject on failure.# https://docs.deepinfra.com/api-reference/account/mediff --git a/src/free_claude_code/providers/openai_chat/profiles.py b/src/free_claude_code/providers/openai_chat/profiles.pyindex a18df435..a5ea459c 100644--- a/src/free_claude_code/providers/openai_chat/profiles.py+++ b/src/free_claude_code/providers/openai_chat/profiles.py@@ -754,6 +754,26 @@ OPENAI_CHAT_PROFILES: dict[str, OpenAIChatProfile] = {optional_sequence_items=(("supported_endpoint_types", "openai"),),),),+ "xkiro": OpenAIChatProfile(+ _policy(+ "XKIRO",+ ReasoningReplayMode.REASONING_CONTENT,+ default_max_tokens=ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS,+ ),+ NamedEffortReasoning(+ _ALL_EFFORTS, disabled_value="none", enabled_value="adaptive"+ ),+ model_listing=OpenAIModelListing(+ path="/models",+ thinking_boolean_path=("capabilities", "reasoning"),+ fixed_input_modalities=_TEXT_INPUT_MODALITIES,+ input_modality_boolean_paths=(+ (ModelInputModality.IMAGE, ("capabilities", "vision")),+ ),+ context_window_tokens_path=("context_length",),+ max_output_tokens_path=("max_output_tokens",),+ ),+ ),"ollama_cloud": OpenAIChatProfile(_policy("OLLAMA_CLOUD",diff --git a/tests/config/test_config.py b/tests/config/test_config.pyindex 875969fc..a9470240 100644--- a/tests/config/test_config.py+++ b/tests/config/test_config.py@@ -554,6 +554,7 @@ def test_configured_chat_model_refs_are_unique() -> None:[("nvidia_nim/meta/llama", "nvidia_nim", "meta/llama"),("open_router/deepseek/r1", "open_router", "deepseek/r1"),+ ("xkiro/qwen/qwen3.7-flash:free", "xkiro", "qwen/qwen3.7-flash:free"),("ollama_cloud/qwen3-coder:480b", "ollama_cloud", "qwen3-coder:480b"),],)diff --git a/tests/contracts/test_provider_catalog_order.py b/tests/contracts/test_provider_catalog_order.pyindex 511d52d3..16cea2c5 100644--- a/tests/contracts/test_provider_catalog_order.py+++ b/tests/contracts/test_provider_catalog_order.py@@ -59,6 +59,7 @@ _EXPECTED_PROVIDER_ORDER: tuple[str, ...] = ("experiential","cheaperinference","orcarouter",+ "xkiro","ollama_cloud","lmstudio","llamacpp",diff --git a/tests/contracts/test_smoke_config.py b/tests/contracts/test_smoke_config.pyindex c963906a..11ecea5c 100644--- a/tests/contracts/test_smoke_config.py+++ b/tests/contracts/test_smoke_config.py@@ -72,6 +72,7 @@ def _settings(**overrides):"experiential_api_key": "","cheaperinference_api_key": "","orcarouter_api_key": "",+ "xkiro_api_key": "","fireworks_api_key": "","novita_api_key": "","cloudflare_api_token": "",@@ -1353,3 +1354,53 @@ def test_smoke_config_returns_openrouter_free_cli_provider_models(monkeypatch) -assert models[0].provider == "open_router"assert models[0].full_model == "open_router/nvidia/nemotron-3-super-120b-a12b:free"assert models[0].source == "openrouter_free_cli_default"+++def test_xkiro_provider_configuration_uses_documented_free_model(+ monkeypatch,+) -> None:+ monkeypatch.delenv("FCC_SMOKE_MODEL_XKIRO", raising=False)+ config = _smoke_config(+ settings=_settings(+ model="ollama/llama3.1",+ ollama_base_url="",+ xkiro_api_key="xkiro-key",+ )+ )++ assert config.has_provider_configuration("xkiro")+ models = config.provider_smoke_models()+ assert [model.provider for model in models] == ["xkiro"]+ assert models[0].full_model == "xkiro/qwen/qwen3.7-flash:free"+ assert models[0].source == "provider_default"+++def test_xkiro_smoke_override_accepts_model_with_or_without_prefix(+ monkeypatch,+) -> None:+ settings = _settings(+ model="ollama/llama3.1",+ ollama_base_url="",+ xkiro_api_key="xkiro-key",+ )+ for override in (+ "qwen/other-model",+ "xkiro/qwen/other-model",+ ):+ monkeypatch.setenv("FCC_SMOKE_MODEL_XKIRO", override)+ models = _smoke_config(settings=settings).provider_smoke_models()++ assert [model.provider for model in models] == ["xkiro"]+ assert models[0].full_model == "xkiro/qwen/other-model"+ assert models[0].source == "FCC_SMOKE_MODEL_XKIRO"+++def test_xkiro_is_not_enabled_without_explicit_credential(monkeypatch) -> None:+ monkeypatch.delenv("FCC_SMOKE_MODEL_XKIRO", raising=False)+ config = _smoke_config(+ provider_matrix=frozenset({"xkiro"}),+ settings=_settings(ollama_base_url="", xkiro_api_key=""),+ )++ assert not config.has_provider_configuration("xkiro")+ assert config.provider_smoke_models() == []diff --git a/tests/providers/test_credential_validation.py b/tests/providers/test_credential_validation.pyindex acdd970a..b5227602 100644--- a/tests/providers/test_credential_validation.py+++ b/tests/providers/test_credential_validation.py@@ -63,6 +63,19 @@ CASES = [("nararoute", "https://router.bynara.id/v1/models", {"data": []}, 401),("experiential", "https://api.experientiallabs.ai/v1/models", {"data": []}, 401),("orcarouter", "https://api.orcarouter.ai/v1/models", {"data": []}, 401),+ (+ "xkiro",+ "https://api.xkiro.com/v1/usage",+ {+ "object": "usage",+ "windows": [],+ "free_tokens": {},+ "plan": None,+ "user": None,+ "wallet": None,+ },+ 401,+ ),("deepinfra","https://api.deepinfra.com/v1/me",@@ -167,7 +180,10 @@ async def test_documented_probe_acceptance_and_rejection(@pytest.mark.asyncio@pytest.mark.parametrize("status", [400, 402, 403, 404, 429, 500, 503])-async def test_ambiguous_errors_warn_without_retry(monkeypatch, status, caplog):[email protected]("provider_id", ["groq", "xkiro"])+async def test_ambiguous_errors_warn_without_retry(+ monkeypatch, status, caplog, provider_id+):requests = []def respond(request):@@ -175,7 +191,9 @@ async def test_ambiguous_errors_warn_without_retry(monkeypatch, status, caplog):return httpx.Response(status, json={"error": "secret-not-a-known-format"})_mock_http(monkeypatch, respond)- result = await validation.check_credentials(_settings("groq"), ("GROQ_API_KEY",))+ key = PROVIDER_CATALOG[provider_id].credential_env+ assert key is not None+ result = await validation.check_credentials(_settings(provider_id), (key,))assert result[0].status == validation.CredentialStatus.UNVERIFIEDassert len(requests) == 1assert "secret-not-a-known-format" not in caplog.text@@ -183,7 +201,10 @@ async def test_ambiguous_errors_warn_without_retry(monkeypatch, status, caplog):@pytest.mark.asyncio@pytest.mark.parametrize("status", [200, 401, 302])-async def test_non_api_responses_do_not_verify_or_reject(monkeypatch, status):[email protected]("provider_id", ["groq", "xkiro"])+async def test_non_api_responses_do_not_verify_or_reject(+ monkeypatch, status, provider_id+):_mock_http(monkeypatch,lambda request: httpx.Response(@@ -192,7 +213,9 @@ async def test_non_api_responses_do_not_verify_or_reject(monkeypatch, status):headers={"Location": "https://other.invalid/"},),)- result = await validation.check_credentials(_settings("groq"), ("GROQ_API_KEY",))+ key = PROVIDER_CATALOG[provider_id].credential_env+ assert key is not None+ result = await validation.check_credentials(_settings(provider_id), (key,))assert result[0].status == validation.CredentialStatus.UNVERIFIED@@ -343,3 +366,18 @@ async def test_programming_errors_do_not_become_permission_to_save(monkeypatch):await validation.check_credentials(_settings("groq"), ("GROQ_API_KEY",))assert isinstance(error.value.exceptions[0], RuntimeError)assert all(client.is_closed for client in clients)+++ "payload",+ [+ {"data": []},+ {"object": "usage", "windows": None, "free_tokens": {}},+ {"object": "usage", "windows": [], "free_tokens": None},+ ],+)+async def test_xkiro_unexpected_usage_remains_unverified(monkeypatch, payload):+ _mock_http(monkeypatch, lambda request: httpx.Response(200, json=payload))+ result = await validation.check_credentials(_settings("xkiro"), ("XKIRO_API_KEY",))+ assert result[0].status == validation.CredentialStatus.UNVERIFIEDdiff --git a/tests/providers/test_provider_runtime.py b/tests/providers/test_provider_runtime.pyindex 39e9e860..c0878395 100644--- a/tests/providers/test_provider_runtime.py+++ b/tests/providers/test_provider_runtime.py@@ -39,6 +39,7 @@ from free_claude_code.config.provider_catalog import (VERCEL_AI_GATEWAY_DEFAULT_BASE,WANDB_INFERENCE_DEFAULT_BASE,XAI_DEFAULT_BASE,+ XKIRO_DEFAULT_BASE,ZAI_API_DEFAULT_BASE,ZAI_CODING_DEFAULT_BASE,ZENMUX_DEFAULT_BASE,@@ -124,6 +125,7 @@ def _make_settings(**overrides):mock.experiential_api_key = "test_experiential_key"mock.cheaperinference_api_key = "test_cheaperinference_key"mock.orcarouter_api_key = "test_orcarouter_key"+ mock.xkiro_api_key = "test_xkiro_key"mock.nvidia_nim_proxy = Nonemock.open_router_proxy = Nonemock.lmstudio_proxy = None@@ -174,6 +176,7 @@ def _make_settings(**overrides):mock.experiential_proxy = Nonemock.cheaperinference_proxy = Nonemock.orcarouter_proxy = None+ mock.xkiro_proxy = Nonemock.kilo_api_key = "test_kilo_key"mock.kilo_proxy = Nonemock.openai_proxy = None@@ -1134,6 +1137,7 @@ async def test_create_provider_instantiates_each_builtin():"experiential": OpenAIChatProvider,"cheaperinference": OpenAIChatProvider,"orcarouter": OpenAIChatProvider,+ "xkiro": OpenAIChatProvider,"opencode_go": OpenCodeProvider,"vercel": OpenAIChatProvider,"bedrock": OpenAIChatProvider,@@ -1626,3 +1630,40 @@ async def test_provider_runtime_cleanup_exceptiongroup_on_multiple_failures() ->assert not runtime.is_cached("x")assert not runtime.is_cached("y")+++async def test_xkiro_provider_config_uses_key_base_and_proxy() -> None:+ descriptor = PROVIDER_CATALOG["xkiro"]+ settings = _make_settings(+ xkiro_api_key="xkiro-token",+ xkiro_base_url="https://unused.example/v1",+ xkiro_proxy="http://proxy.test:8080",+ )++ config = build_provider_config(descriptor, settings)+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):+ provider = await create_provider(+ "xkiro",+ settings,+ ProviderAdmissionRegistry(ProviderAdmissionLimits.from_settings(settings)),+ )++ assert descriptor.display_name == "xKiro"+ assert descriptor.credential_env == "XKIRO_API_KEY"+ assert descriptor.credential_attr == "xkiro_api_key"+ assert descriptor.credential_url == "https://xkiro.com/dashboard/api/keys"+ assert descriptor.default_base_url == XKIRO_DEFAULT_BASE+ assert descriptor.base_url_attr is None+ assert descriptor.proxy_attr == "xkiro_proxy"+ assert config.api_key == "xkiro-token"+ assert config.base_url == XKIRO_DEFAULT_BASE+ assert config.proxy == "http://proxy.test:8080"+ assert isinstance(provider, OpenAIChatProvider)+++def test_xkiro_requires_key_despite_public_catalog():+ with pytest.raises(ApplicationUnavailableError, match="XKIRO_API_KEY is not set"):+ build_provider_config(+ PROVIDER_CATALOG["xkiro"], _make_settings(xkiro_api_key=None)+ )diff --git a/tests/providers/test_xkiro.py b/tests/providers/test_xkiro.pynew file mode 100644index 00000000..c0dcc611--- /dev/null+++ b/tests/providers/test_xkiro.py@@ -0,0 +1,452 @@+"""Tests for the xKiro OpenAI-chat gateway profile and catalog."""++import json+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock++import httpx2+import pytest+import pytest_asyncio+from openai import AsyncOpenAI++from free_claude_code.application.model_metadata import ProviderModelInfo+from free_claude_code.config.constants import ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS+from free_claude_code.config.provider_catalog import XKIRO_DEFAULT_BASE+from free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.json_types import JsonObject, JsonValue+from free_claude_code.core.model_capabilities import ModelInputModality+from free_claude_code.core.openai_responses import OpenAIResponsesRequest+from free_claude_code.core.reasoning import ReasoningEffort, ReasoningPolicy+from free_claude_code.providers.model_listing import ModelListResponseError+from free_claude_code.providers.openai_chat import (+ OPENAI_CHAT_PROFILES,+ OpenAIChatProvider,+)+from tests.providers.support import (+ REASONING_DEFAULT,+ REASONING_OFF,+ REASONING_ON,+ immediate_admission,+ make_provider_config,+ profiled_provider,+ reasoning_for,+)++_MODEL = "qwen/qwen3.7-flash:free"+++@pytest_asyncio.fixture+async def xkiro_provider():+ provider = profiled_provider(+ "xkiro",+ make_provider_config(api_key="test-xkiro-key", base_url=XKIRO_DEFAULT_BASE),+ admission=immediate_admission(provider_name="xkiro", max_attempts=1),+ )+ try:+ yield provider+ finally:+ await provider.cleanup()+++@asynccontextmanager+async def _wire_provider(handler):+ async with AsyncOpenAI(+ api_key="wire-xkiro-key",+ base_url=XKIRO_DEFAULT_BASE,+ max_retries=0,+ http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)),+ ) as client:+ yield OpenAIChatProvider(+ make_provider_config(api_key="wire-xkiro-key", base_url=XKIRO_DEFAULT_BASE),+ profile=OPENAI_CHAT_PROFILES["xkiro"],+ admission=immediate_admission(provider_name="xkiro", max_attempts=1),+ client=client,+ )+++def _request(**overrides: JsonValue) -> MessagesRequest:+ payload: JsonObject = {+ "model": _MODEL,+ "messages": [{"role": "user", "content": "Inspect the file."}],+ "tools": [+ {+ "name": "read_file",+ "description": "Read a file",+ "input_schema": {+ "type": "object",+ "properties": {"path": {"type": "string"}},+ "required": ["path"],+ },+ }+ ],+ }+ payload.update(overrides)+ return MessagesRequest.model_validate(payload)+++def test_constructs_standard_openai_chat_provider(+ xkiro_provider: OpenAIChatProvider,+) -> None:+ assert isinstance(xkiro_provider, OpenAIChatProvider)+ assert xkiro_provider._provider_name == "XKIRO"+ assert xkiro_provider._api_key == "test-xkiro-key"+ assert xkiro_provider._base_url == XKIRO_DEFAULT_BASE+++ ("reasoning", "expected"),+ [+ (REASONING_DEFAULT, None),+ (REASONING_OFF, "none"),+ (REASONING_ON, "adaptive"),+ (ReasoningPolicy.on(budget_tokens=8000), "adaptive"),+ (ReasoningPolicy.on(effort=ReasoningEffort.MINIMAL), "minimal"),+ (ReasoningPolicy.on(effort=ReasoningEffort.LOW), "low"),+ (ReasoningPolicy.on(effort=ReasoningEffort.MEDIUM), "medium"),+ (ReasoningPolicy.on(effort=ReasoningEffort.HIGH), "high"),+ (ReasoningPolicy.on(effort=ReasoningEffort.XHIGH), "xhigh"),+ (ReasoningPolicy.on(effort=ReasoningEffort.MAX), "max"),+ ],+)+def test_encodes_only_documented_reasoning_efforts(+ xkiro_provider: OpenAIChatProvider,+ reasoning: ReasoningPolicy,+ expected: str | None,+) -> None:+ body = xkiro_provider._chat._build_request_body(+ _request(),+ reasoning=reasoning,+ )++ assert body.get("reasoning_effort") == expected+ assert body["max_tokens"] == ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS+ assert body["model"] == _MODEL+ assert body["tools"][0]["function"]["name"] == "read_file"+ assert "thinking" not in body+ assert "extra_body" not in body+++def test_replays_reasoning_content_with_tool_history(+ xkiro_provider: OpenAIChatProvider,+) -> None:+ request = _request(+ messages=[+ {"role": "user", "content": "Inspect the file."},+ {+ "role": "assistant",+ "content": [+ {"type": "thinking", "thinking": "Read it first."},+ {"type": "text", "text": "I will inspect it."},+ {+ "type": "tool_use",+ "id": "toolu_1",+ "name": "read_file",+ "input": {"path": "example.py"},+ },+ ],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_1",+ "content": "print('hello')",+ }+ ],+ },+ ]+ )++ body = xkiro_provider._chat._build_request_body(+ request,+ reasoning=reasoning_for(request),+ )++ assert body["messages"][1] == {+ "role": "assistant",+ "content": "I will inspect it.",+ "reasoning_content": "Read it first.",+ "tool_calls": [+ {+ "id": "toolu_1",+ "type": "function",+ "function": {+ "name": "read_file",+ "arguments": '{"path": "example.py"}',+ },+ }+ ],+ }+ assert body["messages"][2] == {+ "role": "tool",+ "tool_call_id": "toolu_1",+ "content": "print('hello')",+ }+ assert (+ xkiro_provider._profile.reasoning_delta(+ SimpleNamespace(reasoning_content="next thought")+ )+ == "next thought"+ )+++async def test_model_catalog_extracts_bare_model_ids(+ xkiro_provider: OpenAIChatProvider,+) -> None:+ xkiro_provider._client.get = AsyncMock(+ return_value={"data": [{"id": _MODEL}, {"id": "xkiro/free"}]}+ )++ model_infos = await xkiro_provider.list_model_infos()++ assert model_infos == frozenset(+ {ProviderModelInfo(_MODEL), ProviderModelInfo("xkiro/free")}+ )+ xkiro_provider._client.get.assert_awaited_once_with(+ "/models",+ cast_to=object,+ )+++ ("payload", "message"),+ [+ ({"models": []}, "expected top-level data array"),+ ({"data": [{"id": _MODEL}, {}]}, "include id"),+ ({"data": []}, "did not include any model ids"),+ ],+)+async def test_rejects_malformed_or_empty_catalog_atomically(+ xkiro_provider: OpenAIChatProvider,+ payload: object,+ message: str,+) -> None:+ xkiro_provider._client.get = AsyncMock(return_value=payload)++ with pytest.raises(ModelListResponseError, match=message):+ await xkiro_provider.list_model_infos()+++async def test_model_catalog_uses_documented_url_and_bearer_auth() -> None:+ requests: list[httpx2.Request] = []++ def handler(request: httpx2.Request) -> httpx2.Response:+ requests.append(request)+ return httpx2.Response(200, json={"data": [{"id": _MODEL}]})++ async with _wire_provider(handler) as provider:+ model_infos = await provider.list_model_infos()++ assert model_infos == frozenset({ProviderModelInfo(_MODEL)})+ assert len(requests) == 1+ assert str(requests[0].url) == "https://api.xkiro.com/v1/models"+ assert requests[0].headers["authorization"] == "Bearer wire-xkiro-key"+++async def test_full_catalog_retains_tiers_and_maps_capabilities(xkiro_provider):+ xkiro_provider._client.get = AsyncMock(+ return_value={+ "data": [+ {+ "id": _MODEL,+ "access_tier": "free",+ "capabilities": {"reasoning": True, "vision": True, "tools": True},+ "context_length": 128000,+ "max_output_tokens": 8192,+ },+ {+ "id": "paid/model:free",+ "access_tier": "paid",+ "capabilities": {+ "reasoning": False,+ "vision": False,+ "tools": False,+ },+ },+ {"id": "premium/model", "access_tier": "premium"},+ {"id": _MODEL},+ ]+ }+ )+ infos = {info.model_id: info for info in await xkiro_provider.list_model_infos()}+ assert set(infos) == {_MODEL, "paid/model:free", "premium/model"}+ assert infos[_MODEL].supports_thinking is True+ assert infos[_MODEL].input_modalities == frozenset(+ {ModelInputModality.TEXT, ModelInputModality.IMAGE}+ )+ assert infos[_MODEL].context_window_tokens == 128000+ assert infos[_MODEL].max_output_tokens == 8192+ assert infos["paid/model:free"].supports_thinking is False+ assert infos["paid/model:free"].input_modalities == frozenset(+ {ModelInputModality.TEXT}+ )+ assert infos["premium/model"].supports_thinking is None+ assert infos["premium/model"].input_modalities is None+ assert infos["premium/model"].context_window_tokens is None++[email protected]("wire", ["messages", "responses"])+def test_image_and_named_effort_translation(xkiro_provider, wire):+ image = "https://example.test/image.png"+ if wire == "messages":+ request = _request(+ messages=[+ {+ "role": "user",+ "content": [+ {"type": "image", "source": {"type": "url", "url": image}},+ {"type": "text", "text": "Describe"},+ ],+ }+ ]+ )+ body = xkiro_provider._chat._build_request_body(+ request, reasoning=ReasoningPolicy.on(effort=ReasoningEffort.XHIGH)+ )+ else:+ request = OpenAIResponsesRequest(+ model=_MODEL,+ input=[+ {+ "role": "user",+ "content": [+ {"type": "input_image", "image_url": image},+ {"type": "input_text", "text": "Describe"},+ ],+ }+ ],+ )+ body = xkiro_provider._chat._build_responses_request_body(+ request, reasoning=ReasoningPolicy.on(effort=ReasoningEffort.XHIGH)+ ).body+ assert body["reasoning_effort"] == "xhigh"+ assert body["model"] == _MODEL+ assert body["messages"][0]["content"][0] == {+ "type": "image_url",+ "image_url": {"url": image},+ }++[email protected]("wire", ["messages", "responses"])+async def test_chat_stream_preserves_reasoning_tools_and_usage(wire):+ requests = []+ chunks = [+ {"choices": [{"index": 0, "delta": {"reasoning_content": "Inspecting."}}]},+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {+ "name": "inspect",+ "arguments": '{"path":',+ },+ }+ ]+ },+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {"index": 0, "function": {"arguments": '"README.md"}'}}+ ]+ },+ "finish_reason": "tool_calls",+ }+ ]+ },+ {+ "choices": [],+ "usage": {"prompt_tokens": 25, "completion_tokens": 10, "total_tokens": 35},+ },+ ]++ def handler(request):+ requests.append(request)+ frames = [+ {+ "id": "chat_1",+ "object": "chat.completion.chunk",+ "created": 0,+ "model": _MODEL,+ **chunk,+ }+ for chunk in chunks+ ]+ return httpx2.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ text="".join(f"data: {json.dumps(frame)}\n\n" for frame in frames)+ + "data: [DONE]\n\n",+ )++ schema = {"type": "object", "properties": {"path": {"type": "string"}}}+ async with _wire_provider(handler) as provider:+ stream = (+ provider.stream_messages(+ MessagesRequest(+ model=_MODEL,+ max_tokens=2048,+ messages=[{"role": "user", "content": "Inspect the README."}],+ tools=[{"name": "inspect", "input_schema": schema}],+ )+ )+ if wire == "messages"+ else provider.stream_responses(+ OpenAIResponsesRequest(+ model=_MODEL,+ input="Inspect the README.",+ max_output_tokens=2048,+ tools=[+ {"type": "function", "name": "inspect", "parameters": schema}+ ],+ )+ )+ )+ output = "".join([event async for event in stream])++ assert len(requests) == 1+ assert requests[0].url.path == "/v1/chat/completions"+ assert requests[0].headers["authorization"] == "Bearer wire-xkiro-key"+ body = json.loads(requests[0].content)+ assert body["model"] == _MODEL+ assert body["stream"] is True+ assert body["stream_options"] == {"include_usage": True}+ assert body["max_tokens"] == 2048+ assert body["tools"][0]["function"]["parameters"] == schema+ assert "reasoning_effort" not in body+ assert "Inspecting." in output+ assert "inspect" in output+ assert "README.md" in output+ events = [+ json.loads(line[6:])+ for line in output.splitlines()+ if line.startswith("data: {")+ ]+ if wire == "messages":+ terminal = next(event for event in events if event["type"] == "message_delta")+ assert terminal["delta"]["stop_reason"] == "tool_use"+ assert terminal["usage"]["output_tokens"] == 10+ else:+ terminal = next(+ event for event in events if event["type"] == "response.completed"+ )+ assert terminal["response"]["usage"]["input_tokens"] == 25+ assert terminal["response"]["usage"]["output_tokens"] == 10