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 Anthropic API provider with native Messages routing (#1967)
Ali Khokhar7254c1ffc398
diff --git a/README.md b/README.mdindex 2a4b9c62..1185b3f7 100644--- a/README.md+++ b/README.md@@ -25,7 +25,7 @@## What You Get-- **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.+- **59 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.@@ -235,6 +235,7 @@ For another API endpoint, open **Providers → Custom providers → Add provider| [Agnes AI](https://agnes-ai.com/) | `AGNES_API_KEY` | `agnes/agnes-2.0-flash` || [ZenMux](https://zenmux.ai/platform/pay-as-you-go) | `ZENMUX_API_KEY` | `zenmux/deepseek/deepseek-v4-flash-free` || [W&B Inference](https://wandb.ai/settings) | `WANDB_API_KEY` | `wandb/openai/gpt-oss-20b` |+| [Anthropic](https://platform.claude.com/settings/keys) | `ANTHROPIC_API_KEY` | `anthropic/<model-id>` || [Azure OpenAI](https://learn.microsoft.com/azure/foundry/openai/how-to/chatgpt) | `AZURE_OPENAI_API_KEY` and `AZURE_OPENAI_BASE_URL` | `azure_openai/<deployment-name>` || [Google AI Studio (Gemini)](https://aistudio.google.com/apikey) | `GEMINI_API_KEY` | `gemini/models/gemini-3.1-flash-lite` || [Google Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/start/openai) | `VERTEX_PROJECT_ID` + ADC | `vertex/google/gemini-3.5-flash` |@@ -282,6 +283,12 @@ For another API endpoint, open **Providers → Custom providers → Add provider- OpenAI / ChatGPT uses your ChatGPT subscription rather than an API key. Connect from**Providers → OAuth providers → OpenAI / ChatGPT → Connect** in the Admin UIand finish signing in through your browser. Restart an already-running agent after connecting.+- Anthropic uses a separately billed API key. Add it under+ **Providers → Cloud providers → Anthropic → Configure**, then choose a discovered+ model. Multi-workspace keys also require `ANTHROPIC_WORKSPACE_ID`.+ Messages requests use Anthropic's native tools and the client's thinking controls.+ FCC local web tools and prompt optimizations apply to other routes. Native requests+ can fall back only to other Anthropic models. Anthropic tool access and charges apply.- OpenAI API uses a separate Platform API key. Enter it under**Providers → Cloud providers → OpenAI API → Configure**. The model list mayinclude IDs that cannot handle coding requests. Choose a text-generation model.diff --git a/e2e/test_admin_providers.py b/e2e/test_admin_providers.pyindex 4c5187d6..80256d1b 100644--- a/e2e/test_admin_providers.py+++ b/e2e/test_admin_providers.py@@ -450,3 +450,42 @@ def test_xkiro_uses_standard_provider_configuration(page: Page, admin_base_url:expect(dialog.locator("#field-XKIRO_PROXY")).to_be_visible()expect(dialog).to_contain_text("xkiro.com/dashboard/api/keys")close_provider(page)+++def test_anthropic_standard_modal_groups_key_workspace_and_proxy(+ page: Page, admin_base_url: str+):+ submissions = []++ def save(route: Route):+ submissions.append(route.request.post_data_json)+ route.fulfill(+ json={+ "applied": True,+ "credential_checks": [],+ "restart": {"required": False},+ }+ )++ page.route("**/admin/api/config/apply", save)+ _open_admin(page, admin_base_url, {"width": 1280, "height": 720})+ card = page.locator('[data-provider="anthropic"]')+ expect(card.get_by_role("button", name="Configure", exact=True)).to_be_visible()+ dialog = open_provider(page, "anthropic")+ key = dialog.locator("#field-ANTHROPIC_API_KEY")+ expect(key).to_have_attribute("data-secret", "true")+ expect(key).to_be_focused()+ expect(dialog.locator("#field-ANTHROPIC_WORKSPACE_ID")).to_be_visible()+ expect(dialog.locator("#field-ANTHROPIC_PROXY")).to_be_visible()+ key.fill("test-api-key")+ dialog.locator("#field-ANTHROPIC_WORKSPACE_ID").fill("wrkspc_test")+ dialog.get_by_role("button", name="Save", exact=True).click()+ expect(dialog).not_to_be_visible()+ assert submissions == [+ {+ "values": {+ "ANTHROPIC_API_KEY": "test-api-key",+ "ANTHROPIC_WORKSPACE_ID": "wrkspc_test",+ }+ }+ ]diff --git a/src/free_claude_code/api/admin_static/providers/SOURCES.md b/src/free_claude_code/api/admin_static/providers/SOURCES.mdindex 6160905c..735fe4de 100644--- a/src/free_claude_code/api/admin_static/providers/SOURCES.md+++ b/src/free_claude_code/api/admin_static/providers/SOURCES.md@@ -8,6 +8,7 @@ The LLaMA.cpp icon comes from the upstream llama.cpp repository; its MIT license| Asset | Source || --- | --- || `agnesai.svg` | https://unpkg.com/@lobehub/[email protected]/icons/agnesai.svg |+| `anthropic.svg` | https://unpkg.com/@lobehub/[email protected]/icons/anthropic.svg || `azure-color.svg` | https://unpkg.com/@lobehub/[email protected]/icons/azure-color.svg || `bedrock-color.svg` | https://unpkg.com/@lobehub/[email protected]/icons/bedrock-color.svg || `cerebras-color.svg` | https://unpkg.com/@lobehub/[email protected]/icons/cerebras-color.svg |diff --git a/src/free_claude_code/api/admin_static/providers/anthropic.svg b/src/free_claude_code/api/admin_static/providers/anthropic.svgnew file mode 100644index 00000000..09693652--- /dev/null+++ b/src/free_claude_code/api/admin_static/providers/anthropic.svg@@ -0,0 +1 @@+<svg fill="#e5e7eb" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Anthropic</title><path d="M13.827 3.52h3.603L24 20h-3.603l-6.57-16.48zm-7.258 0h3.767L16.906 20h-3.674l-1.343-3.461H5.017l-1.344 3.46H0L6.57 3.522zm4.132 9.959L8.453 7.687 6.205 13.48H10.7z"></path></svg>\ No newline at end of filediff --git a/src/free_claude_code/api/handlers/messages.py b/src/free_claude_code/api/handlers/messages.pyindex e5eec9f8..52f2b014 100644--- a/src/free_claude_code/api/handlers/messages.py+++ b/src/free_claude_code/api/handlers/messages.py@@ -1,6 +1,7 @@"""Claude Messages API product flow."""import asyncio+import sysfrom collections.abc import AsyncIterator, Mappingfrom dataclasses import dataclass, replace@@ -26,7 +27,11 @@ from free_claude_code.api.response_streams import (from free_claude_code.application.errors import ApplicationErrorfrom free_claude_code.application.execution import ProviderExecutor, TokenCounterfrom free_claude_code.application.ports import ModelInfoLookup, ProviderResolver-from free_claude_code.application.routing import ModelRouter, RoutedMessagesRequest+from free_claude_code.application.routing import (+ ModelRouter,+ RoutedMessagesRequest,+ RoutedNativeMessagesRequest,+)from free_claude_code.application.web_tools.ports import WebToolsPortfrom free_claude_code.application.web_tools.service import WebToolServicefrom free_claude_code.config.settings import Settings@@ -43,7 +48,7 @@ from free_claude_code.core.diagnostics import safe_exception_messagefrom free_claude_code.core.failures import ExecutionFailure, find_execution_failurefrom free_claude_code.core.reasoning import ReasoningControl, ReasoningPolicyfrom free_claude_code.core.request_outcomes import record_request_route-from free_claude_code.core.trace import trace_event+from free_claude_code.core.trace import close_stream_input, trace_eventfrom .classifier_response import classifier_response@@ -95,6 +100,33 @@ class MessagesHandler:token_counter=token_counter,)+ async def create_native(+ self, routed: RoutedNativeMessagesRequest, *, request_id: str+ ) -> object:+ body = self._provider_executor.stream_native_messages(+ routed, request_id=request_id+ )+ if routed.request.stream:+ return await anthropic_sse_streaming_response(+ body,+ pre_start_error_response=lambda exc: self._pre_start_error_response(+ exc, request_id=request_id+ ),+ request_id=request_id,+ )+ try:+ chunks = [chunk async for chunk in body]+ return Response(content="".join(chunks), media_type="application/json")+ except (Exception, BaseExceptionGroup) as error:+ return self._pre_start_error_response(error, request_id=request_id)+ finally:+ await close_stream_input(+ body,+ owner="native_messages_json",+ source="api",+ preserved_error=sys.exception(),+ )+async def create(self, request_data: MessagesRequest, *, request_id: str | None = None) -> object:diff --git a/src/free_claude_code/api/handlers/token_count.py b/src/free_claude_code/api/handlers/token_count.pyindex d9bc638d..b977ef37 100644--- a/src/free_claude_code/api/handlers/token_count.py+++ b/src/free_claude_code/api/handlers/token_count.py@@ -11,9 +11,10 @@ from free_claude_code.api.request_errors import (from free_claude_code.api.request_ids import new_request_idfrom free_claude_code.application.errors import ApplicationErrorfrom free_claude_code.application.execution import TokenCounter-from free_claude_code.application.routing import ModelRouter+from free_claude_code.application.routing import ModelRouter, ResolvedModelRoutefrom free_claude_code.config.settings import Settingsfrom free_claude_code.core.anthropic import (+ NativeTokenCountRequest,TokenCountRequest,TokenCountResponse,anthropic_request_snapshot,@@ -38,14 +39,20 @@ class TokenCountHandler:self._token_counter = token_counterdef count(- self, request_data: TokenCountRequest, *, request_id: str | None = None+ self,+ request_data: TokenCountRequest | NativeTokenCountRequest,+ *,+ request_id: str | None = None,+ resolved: ResolvedModelRoute | None = None,) -> TokenCountResponse:"""Count tokens for a request after applying configured model routing."""request_id = request_id or new_request_id()with logger.contextualize(request_id=request_id):try:require_non_empty_messages(request_data.messages)- routed = self._model_router.resolve_token_count_request(request_data)+ routed = self._model_router.resolve_token_count_request(+ request_data, resolved=resolved+ )tokens = self._token_counter(routed.request.messages, routed.request.system, routed.request.tools)diff --git a/src/free_claude_code/api/model_catalog.py b/src/free_claude_code/api/model_catalog.pyindex 35556d4a..0faa77a4 100644--- a/src/free_claude_code/api/model_catalog.py+++ b/src/free_claude_code/api/model_catalog.py@@ -12,6 +12,7 @@ from free_claude_code.application.model_catalog import (read_model_catalog,)from free_claude_code.application.ports import ModelCatalogPort+from free_claude_code.application.routing import supports_native_messagesfrom free_claude_code.config.settings import Settingsfrom free_claude_code.core.gateway_model_ids import (desktop_model_id,@@ -196,13 +197,16 @@ def _build_claude_models_response(models = list(SUPPORTED_CLAUDE_MODELS)for model in catalog.models:ref = model.provider_model_ref- if model.supports_reasoning is not False:+ native = supports_native_messages(ref.partition("/")[0])+ if native or model.supports_reasoning is not False:models.append(_discovered_model_response(desktop_model_id(ref) if desktop else gateway_model_id(ref),display_name=ref,))+ if native:+ continuemodels.append(_discovered_model_response(desktop_model_id(ref, no_thinking=True)@@ -232,12 +236,19 @@ def _build_direct_models_response(else None)+ default_model_id = catalog.default_model_idfor model in catalog.models:+ native = view is ModelCatalogView.MESSAGES and supports_native_messages(+ model.provider_model_ref.partition("/")[0]+ )+ model_id = model.provider_model_ref if native else model.wire_slug+ if model.wire_slug == catalog.default_model_id:+ default_model_id = model_idallows_reasoning = model.supports_reasoning is not Falsemodels.append(ModelResponse(- id=model.wire_slug,- display_name=model.display_name,+ id=model_id,+ display_name=model.provider_model_ref if native else model.display_name,created_at=DISCOVERED_MODEL_CREATED_AT,provider_model_ref=model.provider_model_ref,api_backend=(@@ -266,7 +277,7 @@ def _build_direct_models_response(return ModelsListResponse(data=models,- default_model_id=catalog.default_model_id,+ default_model_id=default_model_id,first_id=models[0].id if models else None,has_more=False,last_id=models[-1].id if models else None,diff --git a/src/free_claude_code/api/routes.py b/src/free_claude_code/api/routes.pyindex 4b1cd655..03436ed4 100644--- a/src/free_claude_code/api/routes.py+++ b/src/free_claude_code/api/routes.py@@ -1,19 +1,30 @@"""FastAPI route handlers."""from collections.abc import Mapping+from typing import Annotated, Any, cast-from fastapi import APIRouter, Depends, Header, HTTPException, Request, Response+from fastapi import APIRouter, Body, Depends, Header, HTTPException, Request, Response+from fastapi.exceptions import RequestValidationErrorfrom loguru import logger+from pydantic import ValidationError-from free_claude_code.application.errors import ApplicationError+from free_claude_code.application.errors import ApplicationError, InvalidRequestErrorfrom free_claude_code.application.ports import ProviderResolver, RequestRuntimeLease+from free_claude_code.application.routing import ModelRouter, supports_native_messagesfrom free_claude_code.config.model_refs import parse_provider_typefrom free_claude_code.config.settings import Settingsfrom free_claude_code.core.anthropic import (MessagesRequest,+ NativeTokenCountRequest,TokenCountRequest,get_token_count,)+from free_claude_code.core.anthropic.native import (+ NativeMessagesError,+ validate_messages_json,+)+from free_claude_code.core.anthropic.passthrough import NativeMessagesRequest+from free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_responses import OpenAIResponsesRequestfrom free_claude_code.core.trace import trace_event@@ -45,7 +56,7 @@ def _provider_resolver(lease: RequestRuntimeLease) -> ProviderResolver:async def _create_messages_response(services: ApiServices,- request_data: MessagesRequest,+ request_data: MessagesRequest | JsonObject,*,request_id: str,request_headers: Mapping[str, str] | None = None,@@ -53,7 +64,37 @@ async def _create_messages_response(lease: RequestRuntimeLease | None = Nonetry:lease = await services.requests.acquire()- await lease.wait_for_token_estimation()+ router = ModelRouter(lease.settings)+ raw = (+ request_data.model_dump(mode="json", exclude_unset=True)+ if isinstance(request_data, MessagesRequest)+ else request_data+ )+ model = raw.get("model")+ resolved = (+ router.resolve(model) if isinstance(model, str) and model.strip() else None+ )+ native = resolved is not None and supports_native_messages(+ resolved.primary.provider_id+ )+ if native:+ try:+ native_request = NativeMessagesRequest(raw)+ except NativeMessagesError as error:+ raise InvalidRequestError(str(error)) from error+ else:+ if not isinstance(request_data, MessagesRequest):+ try:+ request_data = MessagesRequest.model_validate(raw)+ except ValidationError as error:+ raise RequestValidationError(+ [+ {**item, "loc": ("body", *item["loc"])}+ for item in error.errors()+ ],+ body=raw,+ ) from error+ await lease.wait_for_token_estimation()handler = MessagesHandler(lease.settings,web_tools=services.web_tools,@@ -63,7 +104,15 @@ async def _create_messages_response(request_headers=request_headers,model_info_lookup=lease.model_info,)- response = await handler.create(request_data, request_id=request_id)+ if native:+ assert resolved is not None+ response = await handler.create_native(+ router.route_native_messages(native_request, resolved),+ request_id=request_id,+ )+ else:+ assert isinstance(request_data, MessagesRequest)+ response = await handler.create(request_data, request_id=request_id)except ApplicationError as exc:if lease is not None:await lease.release()@@ -122,14 +171,14 @@ def _probe_response(allow: str) -> Response:@router.post("/v1/messages")async def create_message(request: Request,- request_data: MessagesRequest,+ request_data: Annotated[dict[str, Any], Body()],services: ApiServices = Depends(get_services),_auth=Depends(require_anthropic_proxy_auth),):"""Create a message (JSON by default; stream=true returns Anthropic SSE)."""return await _create_messages_response(services,- request_data,+ cast(JsonObject, request_data),request_id=get_request_id(request),request_headers=request.headers,)@@ -164,16 +213,44 @@ async def probe_responses(_auth=Depends(require_proxy_auth)):@router.post("/v1/messages/count_tokens")async def count_tokens(request: Request,- request_data: TokenCountRequest,+ request_data: Annotated[dict[str, Any], Body()],services: ApiServices = Depends(get_services),_auth=Depends(require_anthropic_proxy_auth),):"""Count tokens for a request."""lease = await services.requests.acquire()try:+ model_router = ModelRouter(lease.settings)+ model = request_data.get("model")+ if isinstance(model, str) and not model.strip():+ raise InvalidRequestError("Messages model must not be empty.")+ resolved = (+ model_router.resolve(model)+ if isinstance(model, str) and model.strip()+ else None+ )+ try:+ if resolved is not None and supports_native_messages(+ resolved.primary.provider_id+ ):+ validate_messages_json(request_data)+ counted = NativeTokenCountRequest.model_validate(request_data)+ else:+ counted = TokenCountRequest.model_validate(request_data)+ except NativeMessagesError as error:+ raise InvalidRequestError(str(error)) from error+ except ValidationError as error:+ raise RequestValidationError(+ [{**item, "loc": ("body", *item["loc"])} for item in error.errors()],+ body=request_data,+ ) from errorawait lease.wait_for_token_estimation()- handler = TokenCountHandler(lease.settings, token_counter=get_token_count)- return handler.count(request_data, request_id=get_request_id(request))+ handler = TokenCountHandler(+ lease.settings, model_router=model_router, token_counter=get_token_count+ )+ return handler.count(+ counted, request_id=get_request_id(request), resolved=resolved+ )finally:await lease.release()diff --git a/src/free_claude_code/application/execution.py b/src/free_claude_code/application/execution.pyindex 1796f201..d6c22c66 100644--- a/src/free_claude_code/application/execution.py+++ b/src/free_claude_code/application/execution.py@@ -11,12 +11,10 @@ from typing import Literalfrom loguru import loggerfrom free_claude_code.core.anthropic import (- Message,- SystemContent,- Tool,anthropic_request_snapshot,get_token_count,)+from free_claude_code.core.anthropic.tokens import TokenCounterfrom free_claude_code.core.failures import ExecutionFailure, FailureKindfrom free_claude_code.core.openai_responses import (OpenAIResponsesRequest,@@ -35,13 +33,10 @@ from .routing import (ProviderModelTarget,ResolvedModelRoute,RoutedMessagesRequest,+ RoutedNativeMessagesRequest,RoutedResponsesRequest,)-TokenCounter = Callable[- [list[Message], str | list[SystemContent] | None, list[Tool] | None],- int,-]ResponsesTokenCounter = Callable[[OpenAIResponsesRequest], int]WireApi = Literal["messages", "responses"]CandidateStreamOpener = Callable[@@ -163,6 +158,42 @@ class ProviderExecutor:fields["generation_id"] = self._generation_idtrace_event(**fields)+ def stream_native_messages(+ self,+ routed: RoutedNativeMessagesRequest,+ *,+ request_id: str,+ ) -> AsyncIterator[str]:+ async def open_candidate(+ index: int, target: ProviderModelTarget+ ) -> AsyncIterator[str]:+ provider = await self._provider_resolver(target.provider_id)+ return provider.stream_native_messages(+ routed.request.with_model(target.provider_model),+ request_id=request_id,+ response_model=routed.resolved.original_model,+ request_headers=self._request_headers,+ )++ messages = routed.request.body["messages"]+ assert isinstance(messages, list)+ return self._stream_candidates(+ resolved=routed.resolved,+ reasoning=ReasoningPolicy.provider_default(),+ wire_api="messages",+ raw_log_label="FULL_NATIVE_MESSAGES_PAYLOAD",+ raw_log_payload=lambda: routed.request.body,+ request_snapshot=lambda: {+ "model": routed.request.model,+ "message_count": len(messages),+ "contract": "native",+ },+ ingress_count_name="message_count",+ ingress_count=len(messages),+ request_id=request_id,+ open_candidate=open_candidate,+ )+def stream_messages(self,routed: RoutedMessagesRequest,diff --git a/src/free_claude_code/application/ports.py b/src/free_claude_code/application/ports.pyindex fbcf2a56..15376c78 100644--- a/src/free_claude_code/application/ports.py+++ b/src/free_claude_code/application/ports.py@@ -6,6 +6,7 @@ from typing import Protocolfrom free_claude_code.config.settings import Settingsfrom free_claude_code.core.anthropic import MessagesRequest+from free_claude_code.core.anthropic.passthrough import NativeMessagesRequestfrom free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_responses import OpenAIResponsesRequestfrom free_claude_code.core.reasoning import ReasoningPolicy@@ -16,6 +17,15 @@ from .model_metadata import ProviderModelInfoclass ProviderPort(Protocol):"""Minimal provider capability required to execute one request."""+ def stream_native_messages(+ self,+ request: NativeMessagesRequest,+ *,+ request_id: str,+ response_model: str,+ request_headers: Mapping[str, str] | None = None,+ ) -> AsyncIterator[str]: ...+def stream_messages(self,request: MessagesRequest,diff --git a/src/free_claude_code/application/routing.py b/src/free_claude_code/application/routing.pyindex 00336cda..61b4fc38 100644--- a/src/free_claude_code/application/routing.py+++ b/src/free_claude_code/application/routing.py@@ -1,6 +1,6 @@"""Model routing for Claude-compatible requests."""-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom loguru import logger@@ -13,9 +13,15 @@ from free_claude_code.config.model_refs import (parse_model_name,parse_provider_type,)+from free_claude_code.config.provider_catalog import PROVIDER_CATALOGfrom free_claude_code.config.reasoning import ReasoningPreferencefrom free_claude_code.config.settings import Settings-from free_claude_code.core.anthropic import MessagesRequest, TokenCountRequest+from free_claude_code.core.anthropic import (+ MessagesRequest,+ NativeTokenCountRequest,+ TokenCountRequest,+)+from free_claude_code.core.anthropic.passthrough import NativeMessagesRequestfrom free_claude_code.core.gateway_model_ids import (DESKTOP_MODEL_PREFIX,DESKTOP_NO_THINKING_PREFIX,@@ -23,6 +29,7 @@ from free_claude_code.core.gateway_model_ids import ()from free_claude_code.core.openai_responses import OpenAIResponsesRequestfrom free_claude_code.core.reasoning import ReasoningPolicy+from free_claude_code.core.trace import trace_eventfrom .reasoning import resolve_reasoning_policy, resolve_responses_reasoning_policy@@ -60,6 +67,17 @@ class RoutedMessagesRequest:reasoning: ReasoningPolicy+@dataclass(frozen=True, slots=True)+class RoutedNativeMessagesRequest:+ request: NativeMessagesRequest+ resolved: ResolvedModelRoute+++def supports_native_messages(provider_id: str) -> bool:+ descriptor = PROVIDER_CATALOG.get(provider_id)+ return descriptor is not None and descriptor.native_messages_passthrough++@dataclass(frozen=True, slots=True)class RoutedResponsesRequest:request: OpenAIResponsesRequest@@ -69,7 +87,7 @@ class RoutedResponsesRequest:@dataclass(frozen=True, slots=True)class RoutedTokenCountRequest:- request: TokenCountRequest+ request: TokenCountRequest | NativeTokenCountRequestresolved: ResolvedModelRoute@@ -230,6 +248,31 @@ class ModelRouter:None,)+ def route_native_messages(+ self,+ request: NativeMessagesRequest,+ resolved: ResolvedModelRoute,+ ) -> RoutedNativeMessagesRequest:+ eligible = tuple(+ target+ for target in resolved.fallbacks+ if supports_native_messages(target.provider_id)+ )+ trace_event(+ stage="routing",+ event="free_claude_code.api.route.messages_contract",+ source="application",+ contract="native",+ excluded_fallbacks=tuple(+ target.provider_model_ref+ for target in resolved.fallbacks+ if target not in eligible+ ),+ )+ return RoutedNativeMessagesRequest(+ request, replace(resolved, fallbacks=eligible)+ )+def resolve_messages_request(self, request: MessagesRequest) -> RoutedMessagesRequest:@@ -266,10 +309,13 @@ class ModelRouter:)def resolve_token_count_request(- self, request: TokenCountRequest+ self,+ request: TokenCountRequest | NativeTokenCountRequest,+ *,+ resolved: ResolvedModelRoute | None = None,) -> RoutedTokenCountRequest:"""Return an internal token-count request context."""- resolved = self.resolve(request.model)+ resolved = resolved or self.resolve(request.model)routed = request.model_copy(update={"model": resolved.primary.provider_model}, deep=True)diff --git a/src/free_claude_code/config/admin/manifest.py b/src/free_claude_code/config/admin/manifest.pyindex 37477cee..3bdfde5a 100644--- a/src/free_claude_code/config/admin/manifest.py+++ b/src/free_claude_code/config/admin/manifest.py@@ -134,7 +134,8 @@ _NON_PROVIDER_FIELDS: tuple[ConfigFieldSpec, ...] = (description=("Tried in order when the selected provider/model fails before output ""starts. Applies to every client. One request may reach multiple "- "providers and consume usage at each."+ "providers and consume usage at each. Native Anthropic Messages requests "+ "use only other Anthropic models as fallbacks."),),ConfigFieldSpec(@@ -146,7 +147,8 @@ _NON_PROVIDER_FIELDS: tuple[ConfigFieldSpec, ...] = (options=_reasoning_options(ROOT_REASONING_PREFERENCES),description=("From client preserves CLI effort. Providers translate only the controls "- "their API supports."+ "their API supports. Native Anthropic Messages requests always use the "+ "client thinking controls."),),ConfigFieldSpec(diff --git a/src/free_claude_code/config/admin/provider_manifest.py b/src/free_claude_code/config/admin/provider_manifest.pyindex 6c69d2ef..df3afad2 100644--- a/src/free_claude_code/config/admin/provider_manifest.py+++ b/src/free_claude_code/config/admin/provider_manifest.py@@ -18,6 +18,9 @@ class ProviderFieldOverride(TypedDict, total=False):_PROVIDER_FIELD_OVERRIDES: dict[str, ProviderFieldOverride] = {+ "ANTHROPIC_API_KEY": {+ "description": "Anthropic API access with separate usage billing. Messages requests use Anthropic tools and client thinking controls. Native fallback uses other Anthropic models. FCC local web and prompt optimizations apply to compatibility routes.",+ },"OPENAI_API_KEY": {"label": "OpenAI API Key","description": "API key for the OpenAI Platform. Separate from ChatGPT sign-in.",@@ -341,6 +344,14 @@ def provider_field_specs() -> tuple[ConfigFieldSpec, ...]:return (*_credential_field_specs(),+ ConfigFieldSpec(+ key="ANTHROPIC_WORKSPACE_ID",+ label="Anthropic Workspace ID",+ section_id="providers",+ settings_attr="anthropic_workspace_id",+ provider_ids=("anthropic",),+ description="Optional for workspace-scoped keys. Required for multi-workspace API keys.",+ ),*_cloudflare_account_field_specs(),*_vertex_field_specs(),*_base_url_field_specs(),diff --git a/src/free_claude_code/config/provider_catalog.py b/src/free_claude_code/config/provider_catalog.pyindex 7cc04f3e..efd34ca7 100644--- a/src/free_claude_code/config/provider_catalog.py+++ b/src/free_claude_code/config/provider_catalog.py@@ -126,6 +126,7 @@ class ProviderDescriptor:base_url_attr: str | None = Noneproxy_attr: str | None = Nonerequired_settings_attrs: tuple[str, ...] = ()+ native_messages_passthrough: bool = Falsedef configuration_attrs(self) -> tuple[str, ...]:"""Return settings fields whose non-empty values configure this provider."""@@ -203,6 +204,18 @@ PROVIDER_CATALOG: dict[str, ProviderDescriptor] = {default_base_url="https://api.openai.com/v1",proxy_attr="openai_api_proxy",),+ "anthropic": ProviderDescriptor(+ provider_id="anthropic",+ display_name="Anthropic",+ website_url="https://www.anthropic.com/",+ logo_filename="anthropic.svg",+ credential_env="ANTHROPIC_API_KEY",+ credential_attr="anthropic_api_key",+ credential_url="https://platform.claude.com/settings/keys",+ default_base_url="https://api.anthropic.com/v1",+ proxy_attr="anthropic_proxy",+ native_messages_passthrough=True,+ ),"github_copilot": ProviderDescriptor(provider_id="github_copilot",display_name="GitHub Copilot",diff --git a/src/free_claude_code/config/settings.py b/src/free_claude_code/config/settings.pyindex 37016c09..6aa0d15d 100644--- a/src/free_claude_code/config/settings.py+++ b/src/free_claude_code/config/settings.py@@ -296,6 +296,15 @@ class Settings(BaseModel):)# ==================== Alibaba Cloud Model Studio ====================+ anthropic_api_key: OptionalNonEmptyString = Field(+ default=None, validation_alias="ANTHROPIC_API_KEY"+ )+ anthropic_workspace_id: OptionalNonEmptyString = Field(+ default=None, validation_alias="ANTHROPIC_WORKSPACE_ID"+ )+ anthropic_proxy: OptionalNonEmptyString = Field(+ default=None, validation_alias="ANTHROPIC_PROXY"+ )alibaba_cloud_api_key: OptionalNonEmptyString = Field(default=None, validation_alias="ALIBABA_CLOUD_API_KEY")diff --git a/src/free_claude_code/core/anthropic/__init__.py b/src/free_claude_code/core/anthropic/__init__.pyindex 78c7dbdd..b5a9b41f 100644--- a/src/free_claude_code/core/anthropic/__init__.py+++ b/src/free_claude_code/core/anthropic/__init__.py@@ -27,6 +27,7 @@ from .models import (Message,MessagesRequest,MessagesResponse,+ NativeTokenCountRequest,SystemContent,ThinkingConfig,TokenCountRequest,@@ -66,6 +67,7 @@ __all__ = ["Message","MessagesRequest","MessagesResponse",+ "NativeTokenCountRequest","OpenAIConversionError","ReasoningReplayMode","StreamBlockLedger",diff --git a/src/free_claude_code/core/anthropic/models.py b/src/free_claude_code/core/anthropic/models.pyindex ab79bd08..46df1379 100644--- a/src/free_claude_code/core/anthropic/models.py+++ b/src/free_claude_code/core/anthropic/models.py@@ -167,6 +167,26 @@ class TokenCountResponse(BaseModel):input_tokens: int+class NativeTokenCountMessage(BaseModel):+ """The outer message shape needed by local estimation, with opaque blocks."""++ model_config = ConfigDict(extra="allow", strict=True)++ role: str+ content: str | list[dict[str, Any]]+++class NativeTokenCountRequest(BaseModel):+ """Count native inputs without applying compatibility protocol validation."""++ model_config = ConfigDict(extra="allow", strict=True)++ model: str = Field(min_length=1)+ messages: list[NativeTokenCountMessage]+ system: str | list[dict[str, Any]] | None = None+ tools: list[dict[str, Any]] | None = None++class Usage(BaseModel):input_tokens: intoutput_tokens: intdiff --git a/src/free_claude_code/core/anthropic/native.py b/src/free_claude_code/core/anthropic/native.pyindex eb37f49c..cd458101 100644--- a/src/free_claude_code/core/anthropic/native.py+++ b/src/free_claude_code/core/anthropic/native.py@@ -14,7 +14,7 @@ from .request_serialization import dump_messages_request_BETA_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")_NATIVE_EXTRA_FIELDS = frozenset({"cache_control", "service_tier"})-_RESERVED_EXTRA_FIELDS = frozenset(+RESERVED_MESSAGES_EXTRA_FIELDS = frozenset({"model","messages",@@ -171,7 +171,7 @@ def build_native_messages_request(if not isinstance(extra, Mapping):raise NativeMessagesError("Messages extra_body must be an object.")for name, value in extra.items():- if name.lower() in _RESERVED_EXTRA_FIELDS or name in body:+ if name.lower() in RESERVED_MESSAGES_EXTRA_FIELDS or name in body:raise NativeMessagesError(f"Messages extra_body cannot override {name!r}.")diff --git a/src/free_claude_code/core/anthropic/passthrough.py b/src/free_claude_code/core/anthropic/passthrough.pynew file mode 100644index 00000000..6d3fc3ea--- /dev/null+++ b/src/free_claude_code/core/anthropic/passthrough.py@@ -0,0 +1,105 @@+"""Opaque native Messages requests and lifecycle-only SSE relay."""++import json+from copy import deepcopy+from dataclasses import dataclass++from free_claude_code.core.history_replay import (+ ReplayOrigin,+ decode_replay,+ is_replay,+)+from free_claude_code.core.json_types import JsonObject++from .native import NativeMessagesError, validate_messages_json+++@dataclass(frozen=True, slots=True)+class NativeMessagesRequest:+ body: JsonObject++ def __post_init__(self) -> None:+ validate_messages_json(self.body)+ if not isinstance(self.body.get("model"), str) or not self.model.strip():+ raise NativeMessagesError("Messages model must not be empty.")+ messages = self.body.get("messages")+ if not isinstance(messages, list) or not messages:+ raise NativeMessagesError("Messages input must be a nonempty array.")+ if "stream" in self.body and not isinstance(self.body["stream"], bool):+ raise NativeMessagesError("Messages stream must be a boolean.")+ object.__setattr__(self, "body", deepcopy(self.body))++ @property+ def model(self) -> str:+ value = self.body["model"]+ assert isinstance(value, str)+ return value++ @property+ def stream(self) -> bool:+ return self.body.get("stream", False) is True++ def with_model(self, model: str) -> NativeMessagesRequest:+ return NativeMessagesRequest({**self.body, "model": model})+++def restore_native_history(body: JsonObject, origin: ReplayOrigin) -> JsonObject:+ """Unwrap only FCC-owned state, without changing native history."""+ result = deepcopy(body)+ messages = result.get("messages")+ if not isinstance(messages, list):+ return result+ for message in messages:+ if not isinstance(message, dict):+ continue+ content = message.get("content")+ if not isinstance(content, list):+ continue+ for index, block in enumerate(content):+ if not isinstance(block, dict):+ continue+ field = {"thinking": "signature", "redacted_thinking": "data"}.get(+ str(block.get("type"))+ )+ value = block.get(field) if field else None+ if not isinstance(value, str) or not is_replay(value):+ continue+ record = decode_replay(value)+ if not origin.accepts(record.origin):+ raise NativeMessagesError(+ "Native Messages cannot replay history from a different provider or model."+ )+ content[index] = deepcopy(record.native)+ return result+++class NativeMessagesPassthrough:+ """Inspect the envelope and preserve provider-owned event payloads."""++ def __init__(self, public_model: str) -> None:+ self.public_model = public_model+ self.started = False+ self.completed = False++ def feed(self, kind: str, payload: JsonObject) -> str | None:+ if self.completed:+ raise NativeMessagesError("Messages event arrived after message_stop.")+ validate_messages_json(payload)+ if payload.get("type") != kind:+ raise NativeMessagesError("Messages event has an invalid payload type.")+ if kind == "ping" and not self.started:+ return None+ body = dict(payload)+ if kind == "message_start":+ message = body.get("message")+ if self.started or not isinstance(message, dict):+ raise NativeMessagesError("Invalid native message_start.")+ self.started = True+ body["message"] = {**message, "model": self.public_model}+ elif kind != "ping" and not self.started:+ raise NativeMessagesError(+ "Native Messages event arrived before message_start."+ )+ if kind == "message_stop":+ self.completed = True+ return f"event: {kind}\ndata: {json.dumps(body, ensure_ascii=False)}\n\n"diff --git a/src/free_claude_code/core/anthropic/request_snapshot.py b/src/free_claude_code/core/anthropic/request_snapshot.pyindex 36bb85bb..30edef42 100644--- a/src/free_claude_code/core/anthropic/request_snapshot.py+++ b/src/free_claude_code/core/anthropic/request_snapshot.py@@ -4,11 +4,11 @@ from typing import Anyfrom free_claude_code.core.trace import sanitize_trace_value-from .models import MessagesRequest, TokenCountRequest+from .models import MessagesRequest, NativeTokenCountRequest, TokenCountRequestdef anthropic_request_snapshot(- request: MessagesRequest | TokenCountRequest,+ request: MessagesRequest | TokenCountRequest | NativeTokenCountRequest,) -> dict[str, Any]:"""Return the traceable public fields of an Anthropic request."""data = request.model_dump(mode="python")diff --git a/src/free_claude_code/core/anthropic/tokens.py b/src/free_claude_code/core/anthropic/tokens.pyindex cdce8f36..05a3ef26 100644--- a/src/free_claude_code/core/anthropic/tokens.py+++ b/src/free_claude_code/core/anthropic/tokens.py@@ -1,6 +1,7 @@"""Token estimation for Anthropic-compatible requests."""import json+from collections.abc import Callable, Sequencefrom typing import Anyfrom loguru import logger@@ -8,7 +9,12 @@ from loguru import loggerfrom free_claude_code.core.token_estimation import estimate_text_tokensfrom .content import get_block_attr, get_block_type-from .models import Message, SystemContent, Tool+from .models import Message, NativeTokenCountMessage, SystemContent, Tool++type CountMessages = Sequence[Message | NativeTokenCountMessage]+type CountSystem = str | Sequence[SystemContent | dict[str, Any]] | None+type CountTools = Sequence[Tool | dict[str, Any]] | None+type TokenCounter = Callable[[CountMessages, CountSystem, CountTools], int]def _image_tokens(block: Any) -> int:@@ -26,9 +32,9 @@ def _image_tokens(block: Any) -> int:def get_token_count(- messages: list[Message],- system: str | list[SystemContent] | None = None,- tools: list[Tool] | None = None,+ messages: CountMessages,+ system: CountSystem = None,+ tools: CountTools = None,) -> int:"""Estimate token count for a request."""total_tokens = 0@@ -36,11 +42,14 @@ def get_token_count(if system:if isinstance(system, str):total_tokens += estimate_text_tokens(system)- elif isinstance(system, list):+ else:for block in system:- text = get_block_attr(block, "text", "")- if text:- total_tokens += estimate_text_tokens(str(text))+ if isinstance(block, dict) and block.get("type") != "text":+ total_tokens += estimate_text_tokens(json.dumps(block))+ else:+ text = get_block_attr(block, "text", "")+ if text:+ total_tokens += estimate_text_tokens(str(text))total_tokens += 4for msg in messages:@@ -89,10 +98,8 @@ def get_token_count("web_search_tool_result","web_fetch_tool_result",):- if hasattr(block, "model_dump"):- blob: object = block.model_dump()- else:- blob = block+ dump = getattr(block, "model_dump", None)+ blob: object = dump() if callable(dump) else blocktry:total_tokens += estimate_text_tokens(json.dumps(blob, default=str, ensure_ascii=False)@@ -116,7 +123,11 @@ def get_token_count(if tools:for tool in tools:tool_str = (- tool.name + (tool.description or "") + json.dumps(tool.input_schema)+ json.dumps(tool)+ if isinstance(tool, dict)+ else tool.name+ + (tool.description or "")+ + json.dumps(tool.input_schema))total_tokens += estimate_text_tokens(tool_str)diff --git a/src/free_claude_code/providers/anthropic/__init__.py b/src/free_claude_code/providers/anthropic/__init__.pynew file mode 100644index 00000000..60d97fd2--- /dev/null+++ b/src/free_claude_code/providers/anthropic/__init__.py@@ -0,0 +1,5 @@+"""Anthropic API-key provider."""++from .provider import AnthropicProvider++__all__ = ["AnthropicProvider"]diff --git a/src/free_claude_code/providers/anthropic/headers.py b/src/free_claude_code/providers/anthropic/headers.pynew file mode 100644index 00000000..98e56bfa--- /dev/null+++ b/src/free_claude_code/providers/anthropic/headers.py@@ -0,0 +1,67 @@+"""Anthropic API credentials and request-owned protocol headers."""++import re+from collections.abc import Mapping+from copy import deepcopy+from datetime import date++from free_claude_code.application.errors import InvalidRequestError+from free_claude_code.core.anthropic.native import RESERVED_MESSAGES_EXTRA_FIELDS+from free_claude_code.core.json_types import JsonObject++API_VERSION = "2023-06-01"+_BETA = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")+++def api_headers(api_key: str, workspace_id: str | None = None) -> dict[str, str]:+ headers = {"Authorization": f"Bearer {api_key}", "anthropic-version": API_VERSION}+ if workspace_id:+ headers["anthropic-workspace-id"] = workspace_id+ return headers+++def native_request(+ body: JsonObject,+ headers: Mapping[str, str] | None,+) -> tuple[JsonObject, dict[str, str]]:+ result = deepcopy(body)+ result.pop("original_model", None)+ result.pop("resolved_provider_model", None)+ extra = result.pop("extra_body", None)+ if extra is not None:+ if not isinstance(extra, dict):+ raise InvalidRequestError("Messages extra_body must be an object.")+ for key, value in extra.items():+ if key.lower() in RESERVED_MESSAGES_EXTRA_FIELDS or key in result:+ raise InvalidRequestError(+ f"Messages extra_body cannot override {key!r}."+ )+ result[key] = value+ incoming = {key.lower(): value for key, value in (headers or {}).items()}+ protocol: dict[str, str] = {}+ version = incoming.get("anthropic-version")+ if version is not None:+ if re.fullmatch(r"\d{4}-\d{2}-\d{2}", version) is None:+ raise InvalidRequestError("Invalid anthropic-version header.")+ try:+ date.fromisoformat(version)+ except ValueError as error:+ raise InvalidRequestError("Invalid anthropic-version header.") from error+ protocol["anthropic-version"] = version+ betas = result.pop("betas", [])+ if not isinstance(betas, list) or any(not isinstance(beta, str) for beta in betas):+ raise InvalidRequestError("Messages betas must be a list of header tokens.")+ values = [+ value.strip()+ for value in incoming.get("anthropic-beta", "").split(",")+ if value.strip()+ ]+ for beta in [*values, *betas]:+ if not isinstance(beta, str) or _BETA.fullmatch(beta) is None:+ raise InvalidRequestError(+ "Messages beta names must be valid header tokens."+ )+ merged = tuple(dict.fromkeys([*values, *betas]))+ if merged:+ protocol["anthropic-beta"] = ",".join(merged)+ return result, protocoldiff --git a/src/free_claude_code/providers/anthropic/models.py b/src/free_claude_code/providers/anthropic/models.pynew file mode 100644index 00000000..0f9b3c1f--- /dev/null+++ b/src/free_claude_code/providers/anthropic/models.py@@ -0,0 +1,63 @@+"""Immutable discovery records for Anthropic protocol conversion."""++from dataclasses import dataclass+from typing import Literal++from free_claude_code.application.model_metadata import ProviderModelInfo+from free_claude_code.core.json_types import JsonObject+from free_claude_code.providers.anthropic_messages.discovery import messages_model_info+from free_claude_code.providers.anthropic_messages.request_policy import (+ MessagesModelCapabilities,+)+++@dataclass(frozen=True, slots=True)+class AnthropicModelRecord:+ info: ProviderModelInfo+ messages: MessagesModelCapabilities+++def model_record(item: JsonObject) -> AnthropicModelRecord:+ info = messages_model_info(item, "anthropic")+ capabilities = item.get("capabilities")+ capabilities = capabilities if isinstance(capabilities, dict) else {}+ thinking = capabilities.get("thinking")+ thinking = thinking if isinstance(thinking, dict) else {}+ types = thinking.get("types")+ types = types if isinstance(types, dict) else {}+ adaptive = types.get("adaptive")+ manual = types.get("enabled")+ adaptive_supported = (+ adaptive.get("supported") if isinstance(adaptive, dict) else None+ )+ manual_supported = manual.get("supported") if isinstance(manual, dict) else None+ mode: Literal["unsupported", "optional", "required"] | None = None+ if adaptive_supported is True:+ mode = "required" if manual_supported is False else "optional"+ elif adaptive_supported is False:+ mode = "unsupported"+ effort = capabilities.get("effort")+ effort = effort if isinstance(effort, dict) else {}+ support = effort.get("supported")+ advertised = {+ name: value.get("supported")+ for name, value in effort.items()+ if name != "supported" and isinstance(value, dict)+ }+ values = (+ tuple(name for name, supported in advertised.items() if supported is True)+ if advertised+ else None+ )+ image = capabilities.get("image_input")+ image_support = image.get("supported") if isinstance(image, dict) else None+ return AnthropicModelRecord(+ info,+ MessagesModelCapabilities(+ max_output_tokens=info.max_output_tokens,+ adaptive_thinking=mode,+ supports_output_effort=support if isinstance(support, bool) else None,+ supported_efforts=values,+ supports_vision=image_support if isinstance(image_support, bool) else None,+ ),+ )diff --git a/src/free_claude_code/providers/anthropic/provider.py b/src/free_claude_code/providers/anthropic/provider.pynew file mode 100644index 00000000..e5dd6a8e--- /dev/null+++ b/src/free_claude_code/providers/anthropic/provider.py@@ -0,0 +1,230 @@+"""Anthropic credentials, HTTP lifetime, and atomic model capability snapshots."""++import asyncio+from collections.abc import AsyncIterator, Mapping+from types import MappingProxyType+from typing import cast+from urllib.parse import quote++import httpx++from free_claude_code.application.errors import InvalidRequestError+from free_claude_code.application.model_metadata import ProviderModelInfo+from free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.anthropic.native import NativeMessagesError+from free_claude_code.core.anthropic.passthrough import (+ NativeMessagesRequest,+ restore_native_history,+)+from free_claude_code.core.history_replay import HistoryReplayError+from free_claude_code.core.json_types import JsonObject+from free_claude_code.core.openai_responses import OpenAIResponsesRequest+from free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicy+from free_claude_code.providers.admission import (+ ProviderAdmissionController,+ ProviderOperationKind,+)+from free_claude_code.providers.anthropic_messages.discovery import list_messages_models+from free_claude_code.providers.anthropic_messages.passthrough import (+ stream_native_messages,+)+from free_claude_code.providers.anthropic_messages.request_policy import (+ MessagesModelCapabilities,+)+from free_claude_code.providers.anthropic_messages.transport import (+ AnthropicMessagesTransport,+)+from free_claude_code.providers.base import BaseProvider, ProviderConfig+from free_claude_code.providers.endpoint_types import HttpEndpoint+from free_claude_code.providers.failure_policy import ProviderRecoveryExhausted+from free_claude_code.providers.history_replay import replay_origin+from free_claude_code.providers.http import maybe_await_aclose+from free_claude_code.providers.model_listing import ModelListResponseError++from .headers import api_headers, native_request+from .models import AnthropicModelRecord, model_record+++async def _omit_cookies(request: httpx.Request) -> None:+ request.headers.pop("cookie", None)+++class AnthropicProvider(BaseProvider):+ def __init__(+ self,+ config: ProviderConfig,+ *,+ admission: ProviderAdmissionController,+ workspace_id: str | None = None,+ transport: httpx.AsyncBaseTransport | None = None,+ ) -> None:+ super().__init__(config)+ self._admission = admission+ self._snapshot = HttpEndpoint(+ base_url=config.base_url,+ api_key=config.api_key,+ headers=MappingProxyType(api_headers(config.api_key or "", workspace_id)),+ )+ self._http = httpx.AsyncClient(+ timeout=httpx.Timeout(+ config.http_read_timeout,+ connect=config.http_connect_timeout,+ write=config.http_write_timeout,+ ),+ proxy=config.proxy,+ transport=transport,+ follow_redirects=False,+ event_hooks={"request": [_omit_cookies]},+ )+ self._records: Mapping[str, AnthropicModelRecord] = MappingProxyType({})+ self._model_lock = asyncio.Lock()++ async def endpoint(self, *, force_refresh: bool = False) -> HttpEndpoint:+ return self._snapshot++ async def cleanup(self) -> None:+ await self._http.aclose()++ async def list_model_infos(self) -> frozenset[ProviderModelInfo]:+ async with self._model_lock:+ items = await list_messages_models(+ self._http,+ self._admission,+ base_url=self._snapshot.base_url,+ headers=self._snapshot.headers,+ )+ records = tuple(model_record(item) for item in items)+ self._records = MappingProxyType(+ {record.info.model_id: record for record in records}+ )+ return frozenset(record.info for record in records)++ async def model_record(self, model: str) -> AnthropicModelRecord:+ record = self._records.get(model)+ if record is not None:+ return record+ async with self._model_lock:+ record = self._records.get(model)+ if record is not None:+ return record++ async def fetch() -> object:+ response = await self._http.get(+ self._snapshot.base_url.rstrip("/")+ + "/models/"+ + quote(model, safe=""),+ headers=self._snapshot.headers,+ )+ response.raise_for_status()+ return response.json()++ try:+ item = await self._admission.start_execution().run_call(+ fetch, operation_kind=ProviderOperationKind.MODEL_DISCOVERY+ )+ if not isinstance(item, dict):+ raise ModelListResponseError("Invalid Anthropic model record")+ record = model_record(cast(JsonObject, item))+ except (+ httpx.HTTPError,+ ModelListResponseError,+ ProviderRecoveryExhausted,+ ValueError,+ ):+ return AnthropicModelRecord(+ ProviderModelInfo(model), MessagesModelCapabilities()+ )+ self._records = MappingProxyType({**self._records, model: record})+ return record++ def _transport(self, record: AnthropicModelRecord) -> AnthropicMessagesTransport:+ return AnthropicMessagesTransport(+ client=self._http,+ admission=self._admission,+ provider_name="anthropic",+ replay_scope="anthropic",+ read_timeout_s=self._config.http_read_timeout,+ capabilities=record.messages,+ )++ def stream_native_messages(+ self,+ request: NativeMessagesRequest,+ *,+ request_id: str | None = None,+ response_model: str | None = None,+ request_headers: Mapping[str, str] | None = None,+ ) -> AsyncIterator[str]:+ body, headers = native_request(request.body, request_headers)+ try:+ body = restore_native_history(+ body,+ replay_origin(+ "anthropic", "messages", request.model, endpoint=self._snapshot+ ),+ )+ except (NativeMessagesError, HistoryReplayError) as error:+ raise InvalidRequestError(str(error)) from error+ return stream_native_messages(+ self._http,+ self._admission,+ base_url=self._snapshot.base_url,+ headers={**self._snapshot.headers, **headers},+ body=body,+ public_model=response_model or request.model,+ provider_name="anthropic",+ read_timeout_s=self._config.http_read_timeout,+ request_id=request_id,+ )++ async def stream_messages(+ self,+ request: MessagesRequest,+ input_tokens: int = 0,+ *,+ request_id: str | None = None,+ response_model: str | None = None,+ reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,+ request_headers: Mapping[str, str] | None = None,+ model_info: ProviderModelInfo | None = None,+ ) -> AsyncIterator[str]:+ record = await self.model_record(request.model)+ stream = self._transport(record).stream_messages(+ request,+ endpoint_context=self,+ request_id=request_id,+ response_model=response_model,+ reasoning=reasoning,+ model_info=record.info,+ )+ try:+ async for event in stream:+ yield event+ finally:+ await maybe_await_aclose(stream)++ async def stream_responses(+ self,+ request: OpenAIResponsesRequest,+ input_tokens: int = 0,+ *,+ request_id: str | None = None,+ response_model: str | None = None,+ reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,+ request_headers: Mapping[str, str] | None = None,+ model_info: ProviderModelInfo | None = None,+ ) -> AsyncIterator[str]:+ record = await self.model_record(request.model)+ stream = self._transport(record).stream_responses(+ request,+ endpoint_context=self,+ request_id=request_id,+ response_model=response_model,+ reasoning=reasoning,+ model_info=record.info,+ )+ try:+ async for event in stream:+ yield event+ finally:+ await maybe_await_aclose(stream)diff --git a/src/free_claude_code/providers/anthropic_messages/discovery.py b/src/free_claude_code/providers/anthropic_messages/discovery.pynew file mode 100644index 00000000..2b474b5b--- /dev/null+++ b/src/free_claude_code/providers/anthropic_messages/discovery.py@@ -0,0 +1,81 @@+"""Authenticated cursor discovery shared by Messages endpoint owners."""++from collections.abc import Mapping+from typing import cast++import httpx++from free_claude_code.application.model_metadata import ProviderModelInfo+from free_claude_code.core.json_types import JsonObject+from free_claude_code.core.model_capabilities import ModelInputModality+from free_claude_code.providers.admission import (+ ProviderAdmissionController,+ ProviderOperationKind,+)+from free_claude_code.providers.model_listing import (+ ModelListResponseError,+ extract_openai_model_infos,+)+++def messages_model_info(item: JsonObject, provider_name: str) -> ProviderModelInfo:+ infos = extract_openai_model_infos(+ {"data": [item]},+ provider_name=provider_name,+ thinking_boolean_path=("capabilities", "thinking", "supported"),+ fixed_input_modalities=frozenset({ModelInputModality.TEXT}),+ input_modality_boolean_paths=(+ (ModelInputModality.IMAGE, ("capabilities", "image_input", "supported")),+ ),+ context_window_tokens_path=("max_input_tokens",),+ max_output_tokens_path=("max_tokens",),+ )+ return next(iter(infos))+++async def list_messages_models(+ client: httpx.AsyncClient,+ admission: ProviderAdmissionController,+ *,+ base_url: str,+ headers: Mapping[str, str],+) -> tuple[JsonObject, ...]:+ params = {"limit": "1000"}+ seen: set[str] = set()+ records: dict[str, JsonObject] = {}+ for _ in range(100):++ async def fetch(params: dict[str, str] = params) -> object:+ response = await client.get(+ base_url.rstrip("/") + "/models", headers=headers, params=params+ )+ response.raise_for_status()+ return response.json()++ page = await admission.start_execution().run_call(+ fetch, operation_kind=ProviderOperationKind.MODEL_DISCOVERY+ )+ if (+ not isinstance(page, dict)+ or not isinstance(page.get("has_more"), bool)+ or not isinstance(page.get("data"), list)+ ):+ raise ModelListResponseError("Invalid Messages model-list page")+ ids: set[str] = set()+ for item in page["data"]:+ if (+ not isinstance(item, dict)+ or not isinstance(item.get("id"), str)+ or not item["id"].strip()+ ):+ raise ModelListResponseError("Invalid Messages model identifier")+ ids.add(item["id"])+ records[item["id"]] = cast(JsonObject, item)+ if not page["has_more"]:+ return tuple(records.values())+ cursor = page.get("last_id")+ if not isinstance(cursor, str) or cursor not in ids or cursor in seen:+ raise ModelListResponseError("Messages model-list cursor did not advance")+ seen.add(cursor)+ params = {"limit": "1000", "after_id": cursor}+ raise ModelListResponseError("Messages model-list exceeded 100 pages")diff --git a/src/free_claude_code/providers/anthropic_messages/passthrough.py b/src/free_claude_code/providers/anthropic_messages/passthrough.pynew file mode 100644index 00000000..0cd0fa04--- /dev/null+++ b/src/free_claude_code/providers/anthropic_messages/passthrough.py@@ -0,0 +1,165 @@+"""Native Messages execution using the common admission and attempt owners."""++import asyncio+import json+import sys+from collections.abc import AsyncIterator, Mapping+from dataclasses import replace++import httpx++from free_claude_code.core.anthropic.native import (+ NativeMessagesError,+ validate_messages_json,+)+from free_claude_code.core.anthropic.passthrough import NativeMessagesPassthrough+from free_claude_code.core.diagnostics import (+ extract_upstream_error_detail,+ format_execution_failure_message,+)+from free_claude_code.core.failures import ExecutionFailure+from free_claude_code.core.json_types import JsonObject+from free_claude_code.providers.admission import (+ ProviderAdmissionController,+ ProviderOperationKind,+)+from free_claude_code.providers.failure_policy import (+ RetryableProviderProtocolError,+ classify_provider_failure,+)+from free_claude_code.providers.http import ProviderAttemptScope++from .wire import check_messages_failure, messages_events, messages_status_error+++async def stream_native_messages(+ client: httpx.AsyncClient,+ admission: ProviderAdmissionController,+ *,+ base_url: str,+ headers: Mapping[str, str],+ body: JsonObject,+ public_model: str,+ provider_name: str,+ read_timeout_s: float,+ request_id: str | None,+) -> AsyncIterator[str]:+ execution = admission.start_execution(request_id=request_id)+ streaming = body.get("stream", False) is True++ async def complete() -> str:+ async with client.stream(+ "POST", base_url.rstrip("/") + "/messages", json=body, headers=headers+ ) as response:+ if not response.is_success:+ raise await messages_status_error(response)+ await response.aread()+ try:+ message = response.json()+ validate_messages_json(message)+ except (ValueError, NativeMessagesError) as error:+ raise RetryableProviderProtocolError(+ "Messages upstream returned invalid JSON."+ ) from error+ if not isinstance(message, dict) or message.get("type") != "message":+ raise RetryableProviderProtocolError(+ "Messages upstream did not return a Message object."+ )+ return json.dumps({**message, "model": public_model}, ensure_ascii=False)++ try:+ if not streaming:+ yield await execution.run_call(+ complete, operation_kind=ProviderOperationKind.GENERATION+ )+ return+ committed = False+ while execution.can_attempt:+ scope = None+ try:+ attempt = await execution.open_attempt(ProviderOperationKind.GENERATION)+ scope = ProviderAttemptScope(+ attempt, provider_name=provider_name, request_id=request_id+ )+ response = scope.retain(+ await client.send(+ client.build_request(+ "POST",+ base_url.rstrip("/") + "/messages",+ json=body,+ headers=headers,+ ),+ stream=True,+ )+ )+ if not response.is_success:+ raise await messages_status_error(response)+ if (+ "text/event-stream"+ not in response.headers.get("content-type", "").lower()+ ):+ raise RetryableProviderProtocolError(+ "Messages upstream did not return an SSE stream."+ )+ relay = NativeMessagesPassthrough(public_model)+ async for kind, payload in messages_events(response):+ check_messages_failure(kind, payload, native=True)+ output = relay.feed(kind, payload)+ if output is None:+ continue+ if not attempt.accepted:+ await attempt.accept()+ committed = True+ yield output+ if relay.completed:+ break+ if not relay.completed:+ raise RetryableProviderProtocolError(+ "Messages stream ended without message_stop."+ )+ execution.succeed()+ return+ except asyncio.CancelledError, GeneratorExit:+ raise+ except Exception as raw_error:+ error = (+ RetryableProviderProtocolError(str(raw_error))+ if isinstance(raw_error, NativeMessagesError)+ else raw_error+ )+ if scope is not None:+ decision = await scope.attempt.fail(error)+ if not committed and decision.retry_allowed:+ continue+ if error is not raw_error:+ raise error from raw_error+ raise+ finally:+ if scope is not None:+ await scope.aclose(active_error=sys.exception())+ raise RuntimeError("Messages execution ended without a terminal result.")+ except asyncio.CancelledError, GeneratorExit:+ raise+ except Exception as error:+ if isinstance(error, ExecutionFailure):+ # Stream errors carry their native evidence before classification.+ failure = replace(+ error,+ message=format_execution_failure_message(+ error,+ extract_upstream_error_detail(error),+ upstream_name=provider_name,+ request_id=request_id,+ ),+ )+ else:+ failure = classify_provider_failure(+ error,+ provider_name=provider_name,+ read_timeout_s=read_timeout_s,+ request_id=request_id,+ )+ execution.fail(failure)+ raise failure from error+ finally:+ execution.abandon()diff --git a/src/free_claude_code/providers/anthropic_messages/transport.py b/src/free_claude_code/providers/anthropic_messages/transport.pyindex b19207bc..58e6182d 100644--- a/src/free_claude_code/providers/anthropic_messages/transport.py+++ b/src/free_claude_code/providers/anthropic_messages/transport.py@@ -1,18 +1,15 @@"""Native Messages HTTP execution with one admitted recovery budget."""import asyncio-import jsonimport sys-from collections.abc import AsyncIterator, Callable, Mapping+from collections.abc import AsyncIterator, Callablefrom dataclasses import replacefrom functools import partial-from typing import castimport httpxfrom free_claude_code.application.errors import InvalidRequestErrorfrom free_claude_code.application.model_metadata import ProviderModelInfo-from free_claude_code.core.anthropic.errors import anthropic_status_for_error_typefrom free_claude_code.core.anthropic.models import MessagesRequestfrom free_claude_code.core.anthropic.native import (NativeMessagesError,@@ -20,13 +17,7 @@ from free_claude_code.core.anthropic.native import (build_native_messages_request,)from free_claude_code.core.anthropic.native_stream import NativeMessagesRelay-from free_claude_code.core.anthropic.streaming.decoder import AnthropicSSEDecoder-from free_claude_code.core.diagnostics import (- ERROR_DETAIL_DISPLAY_CAP_BYTES,- attach_upstream_error_body,- redact_sensitive_error_text,-)-from free_claude_code.core.failures import ExecutionFailure, FailureKind+from free_claude_code.core.failures import ExecutionFailurefrom free_claude_code.core.history_replay import ReplayOrigin, prepare_historyfrom free_claude_code.core.json_types import JsonObjectfrom free_claude_code.core.openai_responses import (@@ -52,9 +43,6 @@ from free_claude_code.providers.endpoint_types import EndpointContextfrom free_claude_code.providers.failure_policy import (RetryableProviderProtocolError,classify_provider_failure,- context_window_exceeded_provider_failure,- is_context_window_error_code,- is_context_window_finish_reason,is_retryable_stream_error,)from free_claude_code.providers.history_replay import (@@ -81,6 +69,7 @@ from .request_policy import (MessagesModelCapabilities,resolve_messages_options,)+from .wire import check_messages_failure, messages_events, messages_status_errortype _Presenter = NativeMessagesRelay | AnthropicToResponsesStream@@ -331,15 +320,15 @@ class AnthropicMessagesTransport:))if not response.is_success:- raise await _status_error(response)+ raise await messages_status_error(response)content_type = response.headers.get("content-type", "")if "text/event-stream" not in content_type.lower():raise RetryableProviderProtocolError("Messages upstream did not return an SSE stream.")stream_opened = True- async for event_type, payload in _events(response):- _check_failure(event_type, payload)+ async for event_type, payload in messages_events(response):+ check_messages_failure(event_type, payload)output = presenter.feed(event_type, payload)if event_type != "ping" and not attempt.accepted:await attempt.accept()@@ -437,82 +426,3 @@ class AnthropicMessagesTransport:if execution.last_failure is not None:raise execution.last_failureraise RuntimeError("Messages execution ended without a terminal result.")---async def _events(response: httpx.Response) -> AsyncIterator[tuple[str, JsonObject]]:- decoder = AnthropicSSEDecoder()- async for chunk in response.aiter_text():- for event in decoder.feed(chunk):- payload = cast(JsonObject, event.data)- kind = event.event or payload.get("type")- if not isinstance(kind, str) or not kind:- raise RetryableProviderProtocolError(- "Messages stream has an invalid event type."- )- yield kind, payload- for event in decoder.finish():- payload = cast(JsonObject, event.data)- kind = event.event or payload.get("type")- if not isinstance(kind, str) or not kind:- raise RetryableProviderProtocolError(- "Messages stream has an invalid final event."- )- yield kind, payload---def _check_failure(event_type: str, payload: JsonObject) -> None:- delta = payload.get("delta")- if (- event_type == "message_delta"- and isinstance(delta, Mapping)- and is_context_window_finish_reason(delta.get("stop_reason"))- ):- raise context_window_exceeded_provider_failure()- if event_type != "error":- return- error = payload.get("error")- kind = error.get("type") if isinstance(error, Mapping) else None- if isinstance(error, Mapping) and any(- is_context_window_error_code(error.get(key)) for key in ("type", "code")- ):- raise context_window_exceeded_provider_failure()- status = anthropic_status_for_error_type(kind if isinstance(kind, str) else "")- failure_kind = {- 400: FailureKind.INVALID_REQUEST,- 401: FailureKind.AUTHENTICATION,- 402: FailureKind.PERMISSION,- 403: FailureKind.PERMISSION,- 404: FailureKind.INVALID_REQUEST,- 413: FailureKind.INVALID_REQUEST,- 429: FailureKind.RATE_LIMIT,- 504: FailureKind.TIMEOUT,- 529: FailureKind.OVERLOADED,- }.get(status, FailureKind.UPSTREAM)- message = error.get("message") if isinstance(error, Mapping) else None- failure = ExecutionFailure(- failure_kind,- status,- redact_sensitive_error_text(message[:ERROR_DETAIL_DISPLAY_CAP_BYTES])- if isinstance(message, str) and message- else "Messages upstream returned an error.",- status == 429 or status >= 500,- )- attach_upstream_error_body(failure, json.dumps(payload))- raise failure---async def _status_error(response: httpx.Response) -> httpx.HTTPStatusError:- limit = ERROR_DETAIL_DISPLAY_CAP_BYTES- body = bytearray()- async for chunk in response.aiter_bytes():- body.extend(chunk[: limit + 1 - len(body)])- if len(body) > limit:- break- try:- response.raise_for_status()- except httpx.HTTPStatusError as error:- attach_upstream_error_body(- error, bytes(body[:limit]), truncated=len(body) > limit- )- return error- raise AssertionError("Expected an unsuccessful Messages response.")diff --git a/src/free_claude_code/providers/anthropic_messages/wire.py b/src/free_claude_code/providers/anthropic_messages/wire.pynew file mode 100644index 00000000..fd75a110--- /dev/null+++ b/src/free_claude_code/providers/anthropic_messages/wire.py@@ -0,0 +1,107 @@+"""Shared Messages framing and upstream failure evidence."""++import json+from collections.abc import AsyncIterator, Mapping+from typing import cast++import httpx++from free_claude_code.core.anthropic.errors import anthropic_status_for_error_type+from free_claude_code.core.anthropic.streaming.decoder import AnthropicSSEDecoder+from free_claude_code.core.diagnostics import (+ ERROR_DETAIL_DISPLAY_CAP_BYTES,+ attach_upstream_error_body,+ redact_sensitive_error_text,+)+from free_claude_code.core.failures import ExecutionFailure, FailureKind+from free_claude_code.core.json_types import JsonObject+from free_claude_code.providers.failure_policy import (+ RetryableProviderProtocolError,+ context_window_exceeded_provider_failure,+ is_context_window_error_code,+ is_context_window_finish_reason,+)+++async def messages_events(+ response: httpx.Response,+) -> AsyncIterator[tuple[str, JsonObject]]:+ decoder = AnthropicSSEDecoder()+ async for chunk in response.aiter_text():+ for event in decoder.feed(chunk):+ payload = cast(JsonObject, event.data)+ kind = event.event or payload.get("type")+ if not isinstance(kind, str) or not kind:+ raise RetryableProviderProtocolError(+ "Messages stream has an invalid event type."+ )+ yield kind, payload+ for event in decoder.finish():+ payload = cast(JsonObject, event.data)+ kind = event.event or payload.get("type")+ if not isinstance(kind, str) or not kind:+ raise RetryableProviderProtocolError(+ "Messages stream has an invalid final event."+ )+ yield kind, payload+++def check_messages_failure(+ event_type: str, payload: JsonObject, *, native: bool = False+) -> None:+ delta = payload.get("delta")+ if (+ not native+ and event_type == "message_delta"+ and isinstance(delta, Mapping)+ and is_context_window_finish_reason(delta.get("stop_reason"))+ ):+ raise context_window_exceeded_provider_failure()+ if event_type != "error":+ return+ error = payload.get("error")+ kind = error.get("type") if isinstance(error, Mapping) else None+ if isinstance(error, Mapping) and any(+ is_context_window_error_code(error.get(key)) for key in ("type", "code")+ ):+ raise context_window_exceeded_provider_failure()+ status = anthropic_status_for_error_type(kind if isinstance(kind, str) else "")+ failure_kind = {+ 400: FailureKind.INVALID_REQUEST,+ 401: FailureKind.AUTHENTICATION,+ 402: FailureKind.PERMISSION,+ 403: FailureKind.PERMISSION,+ 404: FailureKind.INVALID_REQUEST,+ 413: FailureKind.INVALID_REQUEST,+ 429: FailureKind.RATE_LIMIT,+ 504: FailureKind.TIMEOUT,+ 529: FailureKind.OVERLOADED,+ }.get(status, FailureKind.UPSTREAM)+ message = error.get("message") if isinstance(error, Mapping) else None+ failure = ExecutionFailure(+ failure_kind,+ status,+ redact_sensitive_error_text(message[:ERROR_DETAIL_DISPLAY_CAP_BYTES])+ if isinstance(message, str) and message+ else "Messages upstream returned an error.",+ status == 429 or status >= 500,+ )+ attach_upstream_error_body(failure, json.dumps(payload))+ raise failure+++async def messages_status_error(response: httpx.Response) -> httpx.HTTPStatusError:+ limit = ERROR_DETAIL_DISPLAY_CAP_BYTES+ body = bytearray()+ async for chunk in response.aiter_bytes():+ body.extend(chunk[: limit + 1 - len(body)])+ if len(body) > limit:+ break+ try:+ response.raise_for_status()+ except httpx.HTTPStatusError as error:+ attach_upstream_error_body(+ error, bytes(body[:limit]), truncated=len(body) > limit+ )+ return error+ raise AssertionError("Expected an unsuccessful Messages response.")diff --git a/src/free_claude_code/providers/base.py b/src/free_claude_code/providers/base.pyindex a8ab4405..4dae7210 100644--- a/src/free_claude_code/providers/base.py+++ b/src/free_claude_code/providers/base.py@@ -4,8 +4,10 @@ from abc import ABC, abstractmethodfrom collections.abc import AsyncIterator, Mappingfrom dataclasses import dataclass+from free_claude_code.application.errors import InvalidRequestErrorfrom free_claude_code.application.model_metadata import ProviderModelInfofrom free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.anthropic.passthrough import NativeMessagesRequestfrom free_claude_code.core.openai_responses import OpenAIResponsesRequestfrom free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicy@@ -42,6 +44,18 @@ class BaseProvider(ABC):async def list_model_infos(self) -> frozenset[ProviderModelInfo]:"""Return the model metadata currently advertised by this provider."""+ def stream_native_messages(+ self,+ request: NativeMessagesRequest,+ *,+ request_id: str | None = None,+ response_model: str | None = None,+ request_headers: Mapping[str, str] | None = None,+ ) -> AsyncIterator[str]:+ raise InvalidRequestError(+ "This provider does not support native Messages execution."+ )+@abstractmethoddef stream_messages(self,diff --git a/src/free_claude_code/providers/credential_validation.py b/src/free_claude_code/providers/credential_validation.pyindex 7b9b4306..6aac08a0 100644--- a/src/free_claude_code/providers/credential_validation.py+++ b/src/free_claude_code/providers/credential_validation.py@@ -76,6 +76,8 @@ _MODELS = _list_field("data")# https://router.bynara.id/id/docs# https://platform.experientiallabs.ai/docs/authentication_PROBES = (+ # https://platform.claude.com/docs/en/api/models/list+ _Probe("anthropic", "/models?limit=1", _MODELS, _AUTH_401),_Probe("open_router","/key",@@ -244,6 +246,11 @@ def _interpret(key: str, probe: _Probe, response: httpx.Response) -> CredentialCCredentialStatus.REJECTED,"The provider rejected this API key. Check it or create a new key.",)+ if probe.provider_id == "anthropic":+ return _unverified(+ key,+ "Could not verify this key. Check the Workspace ID, API permissions, billing, or rate limits. You can still save it.",+ )if response.status_code in {402, 403}:return _unverified(key,@@ -278,6 +285,10 @@ async def _check_one(settings: Settings, key: str, probe: _Probe) -> CredentialCheaders["x-goog-api-key"] = credentialelse:headers["Authorization"] = f"Bearer {credential}"+ if probe.provider_id == "anthropic":+ from free_claude_code.providers.anthropic.headers import api_headers++ headers.update(api_headers(credential, settings.anthropic_workspace_id))if probe.provider_id == "novita":headers["Content-Type"] = "application/json"try:diff --git a/src/free_claude_code/providers/custom.py b/src/free_claude_code/providers/custom.pyindex 07f51f8a..595ff4af 100644--- a/src/free_claude_code/providers/custom.py+++ b/src/free_claude_code/providers/custom.py@@ -9,7 +9,6 @@ from free_claude_code.application.errors import InvalidRequestErrorfrom free_claude_code.application.model_metadata import ProviderModelInfofrom free_claude_code.config.custom_providers import CustomProviderDefinitionfrom free_claude_code.core.anthropic import MessagesRequest, ReasoningReplayMode-from free_claude_code.core.model_capabilities import ModelInputModalityfrom free_claude_code.core.openai_responses import (OpenAIResponsesRequest,responses_reasoning_policy,@@ -23,6 +22,10 @@ from free_claude_code.providers.admission import (ProviderAdmissionController,ProviderOperationKind,)+from free_claude_code.providers.anthropic_messages.discovery import (+ list_messages_models,+ messages_model_info,+)from free_claude_code.providers.anthropic_messages.request_policy import (MessagesModelCapabilities,)@@ -32,7 +35,6 @@ from free_claude_code.providers.anthropic_messages.transport import (from free_claude_code.providers.base import BaseProvider, ProviderConfigfrom free_claude_code.providers.endpoint_types import HttpEndpointfrom free_claude_code.providers.model_listing import (- ModelListResponseError,extract_openai_model_infos,model_infos_from_ids,)@@ -326,55 +328,9 @@ class CustomProvider(BaseProvider):headers = {"anthropic-version": "2023-06-01"}if self._config.api_key:headers["x-api-key"] = self._config.api_key- params = {"limit": "1000"}- seen: set[str] = set()- infos: dict[str, ProviderModelInfo] = {}- for _ in range(100):- response = await self._admission.start_execution().run_call(- lambda params=params: self._fetch_models(headers, params),- operation_kind=ProviderOperationKind.MODEL_DISCOVERY,- )- if not isinstance(response, dict) or not isinstance(- response.get("has_more"), bool- ):- raise ModelListResponseError("Invalid Messages model-list page")- page = extract_openai_model_infos(- response,- provider_name=self._definition.provider_id,- thinking_boolean_path=("capabilities", "thinking", "supported"),- fixed_input_modalities=frozenset({ModelInputModality.TEXT}),- input_modality_boolean_paths=(- (- ModelInputModality.IMAGE,- ("capabilities", "image_input", "supported"),- ),- ),- context_window_tokens_path=("max_input_tokens",),- max_output_tokens_path=("max_tokens",),- )- infos.update((info.model_id, info) for info in page)- if not response["has_more"]:- return frozenset(infos.values())- cursor = response.get("last_id")- if (- not isinstance(cursor, str)- or not cursor- or cursor in seen- or cursor not in {info.model_id for info in page}- ):- raise ModelListResponseError(- "Messages model-list cursor did not advance"- )- seen.add(cursor)- params = {"limit": "1000", "after_id": cursor}- raise ModelListResponseError("Messages model-list exceeded 100 pages")-- async def _fetch_models(- self, headers: dict[str, str], params: dict[str, str]- ) -> object:- assert self._http is not None- response = await self._http.get(- self._config.base_url + "/models", headers=headers, params=params+ records = await list_messages_models(+ self._http, self._admission, base_url=self._config.base_url, headers=headers+ )+ return frozenset(+ messages_model_info(item, self._definition.provider_id) for item in records)- response.raise_for_status()- return response.json()diff --git a/src/free_claude_code/providers/runtime/factory.py b/src/free_claude_code/providers/runtime/factory.pyindex 71969742..94f9cadf 100644--- a/src/free_claude_code/providers/runtime/factory.py+++ b/src/free_claude_code/providers/runtime/factory.py@@ -25,6 +25,21 @@ ProviderFactory = Callable[]+def _load_anthropic() -> ProviderFactory:+ from free_claude_code.providers.anthropic import AnthropicProvider++ def construct(+ config: ProviderConfig,+ settings: Settings,+ admission: ProviderAdmissionController,+ ) -> BaseProvider:+ return AnthropicProvider(+ config, workspace_id=settings.anthropic_workspace_id, admission=admission+ )++ return construct++def _load_nvidia_nim() -> ProviderFactory:from free_claude_code.providers.nvidia_nim import NvidiaNimProvider@@ -221,6 +236,7 @@ def _load_opencode_go() -> ProviderFactory:_SPECIAL_PROVIDER_FACTORIES: dict[str, Callable[[], ProviderFactory]] = {+ "anthropic": _load_anthropic,"alibaba_cloud": _load_alibaba_cloud,"nvidia_nim": _load_nvidia_nim,"open_router": _load_open_router,@@ -305,7 +321,16 @@ def prepare_provider(config = build_provider_config(descriptor, settings)admission = admission_registry.get(provider_id)if factory is not None:- return factory(config, settings, admission)+ provider = factory(config, settings, admission)+ if (+ descriptor.native_messages_passthrough+ and type(provider).stream_native_messages+ is BaseProvider.stream_native_messages+ ):+ raise AssertionError(+ f"Provider {provider_id!r} lacks native Messages execution"+ )+ return providerreturn create_openai_chat_provider(provider_id, config, admission)return constructdiff --git a/src/free_claude_code/runtime/diagnostics.py b/src/free_claude_code/runtime/diagnostics.pyindex 30008440..61296132 100644--- a/src/free_claude_code/runtime/diagnostics.py+++ b/src/free_claude_code/runtime/diagnostics.py@@ -106,6 +106,7 @@ EXCLUDED_FIELDS = {"allowed_discord_channels","allowed_dir","cloudflare_account_id",+ "anthropic_workspace_id","vertex_project_id",} | {d.credential_attr for d in PROVIDER_CATALOG.values() if d.credential_attr}URL_FIELDS = {diff --git a/tests/api/test_native_anthropic.py b/tests/api/test_native_anthropic.pynew file mode 100644index 00000000..8326c0b0--- /dev/null+++ b/tests/api/test_native_anthropic.py@@ -0,0 +1,284 @@+"""Messages ingress chooses one native contract before lossy processing."""++import json+from typing import cast+from unittest.mock import patch++import httpx+import pytest+from fastapi.testclient import TestClient++from free_claude_code.config.settings import Settings+from free_claude_code.providers.base import BaseProvider+from tests.api.support import create_test_app+from tests.providers.test_anthropic_provider import native_body, provider+++def test_native_ingress_preserves_extensions_and_bypasses_local_processing():+ sent = []++ def handle(request):+ sent.append(json.loads(request.content))+ return httpx.Response(+ 200,+ json={+ "type": "message",+ "model": "claude-test",+ "content": [{"type": "new_hosted_result", "value": 42}],+ "stop_reason": "pause_turn",+ },+ )++ p = provider(handle)+ settings = Settings(+ MODEL="anthropic/claude-test",+ ANTHROPIC_API_KEY="key",+ ENABLE_WEB_SERVER_TOOLS=False,+ )+ app = create_test_app(settings, providers={"anthropic": p})+ body = native_body()+ body["model"] = "claude-sonnet-client-alias"+ with (+ patch(+ "free_claude_code.api.handlers.messages.try_optimizations",+ side_effect=AssertionError("native optimization"),+ ),+ patch(+ "free_claude_code.runtime.provider_manager.ProviderGenerationLease.wait_for_token_estimation",+ side_effect=AssertionError("native token wait"),+ ),+ patch(+ "free_claude_code.api.routes.get_token_count",+ side_effect=AssertionError("native counting"),+ ),+ patch(+ "free_claude_code.application.web_tools.service.WebToolService.try_stream_messages",+ side_effect=AssertionError("local tools"),+ ),+ TestClient(app) as client,+ ):+ response = client.post("/v1/messages", json=body)+ assert response.status_code == 200, response.text+ assert response.json()["model"] == body["model"]+ assert response.json()["stop_reason"] == "pause_turn"+ assert sent == [{**body, "model": "claude-test"}]+++def test_native_fallback_excludes_compatibility_and_preserves_alias():+ sent = []++ def handle(request):+ body = json.loads(request.content)+ sent.append(body)+ if body["model"] == "primary":+ return httpx.Response(+ 403,+ json={+ "type": "error",+ "error": {"type": "permission_error", "message": "unavailable"},+ },+ )+ return httpx.Response(+ 200, json={"type": "message", "model": "backup", "content": []}+ )++ settings = Settings(+ MODEL="anthropic/primary",+ ANTHROPIC_API_KEY="key",+ MODEL_FALLBACKS=["nvidia_nim/never", "anthropic/backup"],+ )+ app = create_test_app(settings, providers={"anthropic": provider(handle)})+ body = native_body()+ with TestClient(app) as client:+ response = client.post("/v1/messages", json=body)+ assert response.status_code == 200, response.text+ assert response.json()["model"] == body["model"]+ assert [item["model"] for item in sent] == ["primary", "backup"]+ assert sent[-1]["tools"] == body["tools"]+++def test_compatibility_ingress_still_rejects_unknown_blocks():+ app = create_test_app(Settings())+ with TestClient(app) as client:+ response = client.post("/v1/messages", json=native_body())+ assert response.status_code == 422+++def test_leading_pings_allow_exhausted_primary_to_reach_native_fallback():+ from free_claude_code.core.anthropic.stream_contracts import parse_sse_text+ from tests.providers.test_anthropic_messages_transport import Wire, _events, _sse++ calls = []+ wires = []++ def handle(request):+ model = json.loads(request.content)["model"]+ calls.append(model)+ events = (+ [{"type": "error", "error": {"type": "overloaded_error"}}]+ if model == "primary"+ else _events()+ )+ wire = Wire([_sse({"type": "ping"}, *events)])+ wires.append(wire)+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=wire+ )++ app = create_test_app(+ Settings(+ MODEL="anthropic/primary",+ MODEL_FALLBACKS=["nvidia_nim/excluded", "anthropic/backup"],+ ),+ providers={"anthropic": provider(handle)},+ )+ body = native_body(True)+ with TestClient(app) as client:+ response = client.post("/v1/messages", json=body)+ assert response.status_code == 200, response.text+ events = parse_sse_text(response.text)+ assert events[0].event == "message_start"+ assert events[0].data["message"]["model"] == body["model"]+ assert events[-1].event == "message_stop"+ assert calls == ["primary", "primary", "backup"]+ assert all(wire.closed for wire in wires)+++def test_stream_failure_after_start_emits_one_error_without_fallback():+ from free_claude_code.core.anthropic.stream_contracts import parse_sse_text+ from tests.providers.test_anthropic_messages_transport import _events, _sse++ requests = []++ def handle(request):+ requests.append(request)+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ content=_sse(+ _events()[0],+ {+ "type": "error",+ "error": {"type": "overloaded_error", "message": "late failure"},+ "request_id": "anthropic-req-evidence",+ },+ ),+ )++ settings = Settings(+ MODEL="anthropic/primary",+ ANTHROPIC_API_KEY="key",+ MODEL_FALLBACKS=["anthropic/backup"],+ )+ app = create_test_app(settings, providers={"anthropic": provider(handle)})+ with TestClient(app) as client:+ response = client.post("/v1/messages", json=native_body(True))+ assert response.status_code == 200+ events = parse_sse_text(response.text)+ assert [event.event for event in events] == ["message_start", "error"]+ assert "anthropic-req-evidence" in response.text+ assert len(requests) == 1++[email protected]("view", ["claude", "claude-desktop", "messages"])[email protected]("thinking", [False, True, None])+def test_native_model_catalog_does_not_advertise_ignored_thinking_variant(+ view, thinking+):+ from free_claude_code.application.model_metadata import ProviderModelInfo+ from free_claude_code.core.gateway_model_ids import decode_gateway_model_id+ from tests.api.support import provider_manager_for_app++ app = create_test_app(Settings(MODEL="anthropic/selected", ANTHROPIC_API_KEY="key"))+ provider_manager_for_app(app).cache_model_infos(+ "anthropic", [ProviderModelInfo("selected", supports_thinking=thinking)]+ )+ with TestClient(app) as client:+ rows = client.get(f"/v1/models?view={view}").json()+ native = [row for row in rows["data"] if "anthropic" in row["display_name"]]+ assert len(native) == 1+ decoded = decode_gateway_model_id(native[0]["id"])+ assert decoded is None or not decoded.force_reasoning_off+ if view == "messages":+ assert rows["default_model_id"] == "anthropic/selected"+++def test_native_proxy_auth_remains_separate_from_upstream_key():+ calls = []++ def handle(request):+ calls.append(request)+ return httpx.Response(200, json={"type": "message", "content": []})++ settings = Settings(+ MODEL="anthropic/selected",+ ANTHROPIC_API_KEY="api-key",+ ANTHROPIC_AUTH_TOKEN="proxy-secret",+ PROXY_AUTH_ENABLED=True,+ )+ app = create_test_app(settings, providers={"anthropic": provider(handle)})+ with TestClient(app) as client:+ denied = client.post(+ "/v1/messages", json=native_body(), headers={"x-api-key": "api-key"}+ )+ accepted = client.post(+ "/v1/messages",+ json=native_body(),+ headers={"Authorization": "Bearer proxy-secret"},+ )+ assert denied.status_code in {401, 403}+ assert accepted.status_code == 200+ assert len(calls) == 1+ assert calls[0].headers["Authorization"] == "Bearer upstream-secret"+++def test_compatibility_primary_keeps_conversion_when_anthropic_is_fallback():+ from tests.api.model_fallback_support import (+ ControlledFallbackProvider,+ execution_failure,+ )+ from tests.providers.test_anthropic_discovery import metadata+ from tests.providers.test_anthropic_messages_transport import _events, _sse++ sent = []++ def handle(request):+ if request.method == "GET":+ return httpx.Response(200, json=metadata("backup", True))+ sent.append(json.loads(request.content))+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, content=_sse(*_events())+ )++ primary = ControlledFallbackProvider(+ failure=execution_failure("primary unavailable")+ )+ settings = Settings(+ MODEL="nvidia_nim/primary",+ ANTHROPIC_API_KEY="key",+ MODEL_FALLBACKS=["anthropic/backup"],+ REASONING_POLICY="off",+ )+ p = provider(handle)+ app = create_test_app(+ settings, providers={"nvidia_nim": cast(BaseProvider, primary), "anthropic": p}+ )+ with (+ patch.object(+ p, "stream_native_messages", side_effect=AssertionError("contract changed")+ ),+ TestClient(app) as client,+ ):+ response = client.post(+ "/v1/messages",+ json={+ "model": "client-alias",+ "messages": [{"role": "user", "content": "hi"}],+ "max_tokens": 32000,+ },+ )+ assert response.status_code == 200, response.text+ assert sent[0]["thinking"] == {"type": "disabled"}+ assert sent[0]["max_tokens"] == 8192+ assert sent[0]["stream"] is True+ assert response.json()["model"] == "client-alias"diff --git a/tests/api/test_native_recovery.py b/tests/api/test_native_recovery.pynew file mode 100644index 00000000..edbd5417--- /dev/null+++ b/tests/api/test_native_recovery.py@@ -0,0 +1,240 @@+"""Native commitment, cleanup, and count/continue workflows across API layers."""++import asyncio+import json+from unittest.mock import patch++import httpx+import pytest+from fastapi.testclient import TestClient++from free_claude_code.config.settings import Settings+from free_claude_code.core.anthropic.stream_contracts import parse_sse_text+from free_claude_code.providers.admission import (+ ProviderAdmissionController,+ ProviderOperationKind,+)+from tests.api.support import create_test_app, provider_manager_for_app+from tests.api.test_native_token_count import count_body+from tests.api.test_request_lifetime import _http_scope+from tests.providers.test_anthropic_messages_transport import Wire, _events, _sse+from tests.providers.test_anthropic_provider import native_body, provider+++def test_only_leading_pings_then_all_candidates_fail_returns_json_error():+ calls = []+ wires = []++ def handle(request):+ calls.append(json.loads(request.content)["model"])+ wire = Wire(+ [+ _sse(+ {"type": "ping"},+ {+ "type": "error",+ "error": {"type": "overloaded_error", "message": "busy"},+ "request_id": "upstream-evidence",+ },+ )+ ]+ )+ wires.append(wire)+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=wire+ )++ app = create_test_app(+ Settings(MODEL="anthropic/primary", MODEL_FALLBACKS=["anthropic/backup"]),+ providers={"anthropic": provider(handle)},+ )+ with TestClient(app) as client:+ response = client.post("/v1/messages", json=native_body(True))+ assert response.status_code == 529, response.text+ assert response.headers["content-type"] == "application/json"+ assert response.headers["x-should-retry"] == "false"+ assert response.json()["error"]["type"] == "overloaded_error"+ assert "upstream-evidence" in response.text+ assert calls == ["primary", "primary", "backup", "backup"]+ assert all(wire.closed for wire in wires)+ assert provider_manager_for_app(app)._current.active_leases == 0++[email protected]("disconnect", [False, True])+async def test_leading_ping_timeout_or_disconnect_releases_all_resources(disconnect):+ entered = asyncio.Event()+ calls = []++ class Pings(httpx.AsyncByteStream):+ closed = False++ async def __aiter__(self):+ for _ in range(100):+ entered.set()+ yield _sse({"type": "ping"})+ await asyncio.sleep(0.005)+ raise httpx.ReadError("No message started")++ async def aclose(self):+ self.closed = True++ wire = Pings()++ def handle(request):+ calls.append(request)+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=wire+ )++ p = provider(handle)+ p._admission = ProviderAdmissionController(+ provider_name="native-recovery-test",+ rate_limit=1_000_000,+ rate_window=1.0,+ max_concurrency=1,+ max_attempts=2,+ base_delay=0.0,+ max_delay=0.0,+ jitter=0.0,+ )+ app = create_test_app(+ Settings(+ MODEL="anthropic/primary",+ MODEL_FALLBACKS=["anthropic/backup"],+ provider_progress_timeout=0.05,+ ),+ providers={"anthropic": p},+ )+ manager = provider_manager_for_app(app)+ try:+ if disconnect:+ body = json.dumps(native_body(True)).encode()+ scope = _http_scope()+ scope["headers"] = [(b"content-type", b"application/json")]+ sent = []+ pending = True++ async def receive():+ nonlocal pending+ if pending:+ pending = False+ return {"type": "http.request", "body": body, "more_body": False}+ await entered.wait()+ return {"type": "http.disconnect"}++ async def send(message):+ sent.append(message)++ await asyncio.wait_for(app(scope, receive, send), 2)+ assert sent == []+ else:+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app), base_url="http://test"+ ) as client:+ response = await asyncio.wait_for(+ client.post("/v1/messages", json=native_body(True)), 2+ )+ assert response.status_code == 504, response.text+ assert response.json()["error"]["type"] == "timeout_error"+ assert response.headers["x-should-retry"] == "false"+ assert len(calls) == 1+ assert wire.closed+ assert manager._current.active_leases == 0+ # With concurrency one, a new operation can finish only if the old permit was released.+ execution = p._admission.start_execution()++ async def next_call():+ return "released"++ assert (+ await asyncio.wait_for(+ execution.run_call(+ next_call, operation_kind=ProviderOperationKind.GENERATION+ ),+ 1,+ )+ == "released"+ )+ finally:+ await manager.close()+++def test_count_generate_and_continue_native_tool_history_with_recovery():+ sent = []+ result_block = {+ "type": "future_hosted_result",+ "tool_use_id": "srvtoolu_new",+ "content": {"payload": "hosted tool response " * 30},+ }+ events = _events(stop="pause_turn")+ events[1]["content_block"] = result_block+ del events[2]++ def handle(request):+ body = json.loads(request.content)+ sent.append(body)+ if len(sent) == 1:+ wire = Wire([_sse({"type": "ping"}), httpx.ReadError("retry before start")])+ elif body.get("stream"):+ wire = Wire([_sse({"type": "ping"}, *events)])+ else:+ return httpx.Response(+ 200,+ json={"type": "message", "model": "primary", "content": [result_block]},+ )+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=wire+ )++ app = create_test_app(+ Settings(MODEL="anthropic/primary", ENABLE_WEB_SERVER_TOOLS=False),+ providers={"anthropic": provider(handle)},+ )+ body = {**count_body(), "max_tokens": 512, "stream": True}+ with TestClient(app) as client:+ with patch(+ "free_claude_code.runtime.provider_manager.ProviderGenerationLease.resolve_provider",+ side_effect=AssertionError("local count"),+ ):+ initial_count = client.post("/v1/messages/count_tokens", json=body)+ response = client.post("/v1/messages", json=body)+ assert initial_count.status_code == 200, initial_count.text+ assert response.status_code == 200, response.text+ output = parse_sse_text(response.text)+ assert output[0].event == "message_start"+ assert output[0].data["message"]["model"] == body["model"]+ returned = next(+ event.data["content_block"]+ for event in output+ if event.event == "content_block_start"+ )+ assert returned == result_block+ history = body["messages"]+ assert isinstance(history, list)+ continuation = {+ **body,+ "stream": False,+ "messages": [+ *history,+ {"role": "assistant", "content": [returned]},+ {"role": "user", "content": "continue"},+ ],+ }+ with patch(+ "free_claude_code.runtime.provider_manager.ProviderGenerationLease.resolve_provider",+ side_effect=AssertionError("local count"),+ ):+ next_count = client.post("/v1/messages/count_tokens", json=continuation)+ continued = client.post("/v1/messages", json=continuation)+ assert next_count.status_code == 200, next_count.text+ assert next_count.json()["input_tokens"] > initial_count.json()["input_tokens"]+ assert continued.status_code == 200, continued.text+ assert continued.json()["content"] == [result_block]+ assert continued.json()["model"] == body["model"]+ assert sent == [+ {**body, "model": "primary"},+ {**body, "model": "primary"},+ {**continuation, "model": "primary"},+ ]+ assert provider_manager_for_app(app)._current.active_leases == 0diff --git a/tests/api/test_native_token_count.py b/tests/api/test_native_token_count.pynew file mode 100644index 00000000..ae85ab03--- /dev/null+++ b/tests/api/test_native_token_count.py@@ -0,0 +1,247 @@+"""Native histories remain countable without contacting their provider."""++import asyncio+import json+from copy import deepcopy+from unittest.mock import patch++import httpx+import pytest+from fastapi.testclient import TestClient++from free_claude_code.config.settings import Settings+from free_claude_code.core.anthropic import get_token_count+from tests.api.support import create_test_app, provider_manager_for_app+++def count_body():+ return {+ "model": "claude-sonnet-client-alias",+ "messages": [+ {+ "role": "assistant",+ "content": [+ {+ "type": "bash_code_execution_tool_result",+ "tool_use_id": "srvtoolu_test",+ "content": {+ "type": "bash_code_execution_result",+ "stdout": "hello",+ "stderr": "",+ "return_code": 0,+ "content": [],+ },+ },+ {"type": "future_result", "opaque": {"keep": [1, 2]}},+ ],+ }+ ],+ "system": [{"type": "future_system", "instructions": "be helpful"}],+ "tools": [{"type": "web_search_future", "name": "web_search", "max_uses": 2}],+ "thinking": {"type": "future_thinking", "option": True},+ }++[email protected]("field", ["messages", "system", "tools"])+def test_native_count_accepts_and_estimates_opaque_payload_without_provider(field):+ app = create_test_app(Settings(MODEL="anthropic/selected"))+ body = count_body()+ expanded = deepcopy(body)+ extra = "a substantially longer native payload " * 100+ if field == "messages":+ expanded[field][0]["content"][1]["opaque"]["extra"] = extra+ else:+ expanded[field][0]["extra"] = extra+ original = deepcopy(body)+ with (+ patch(+ "free_claude_code.runtime.provider_manager.ProviderGenerationLease.resolve_provider",+ side_effect=AssertionError("Counting must not resolve a provider"),+ ),+ TestClient(app) as client,+ ):+ baseline = client.post("/v1/messages/count_tokens", json=body)+ larger = client.post("/v1/messages/count_tokens", json=expanded)+ assert baseline.status_code == 200, baseline.text+ assert larger.status_code == 200, larger.text+ assert larger.json()["input_tokens"] > baseline.json()["input_tokens"] > 0+ assert body == original+++def test_compatibility_primary_keeps_count_validation_with_native_fallback():+ app = create_test_app(+ Settings(MODEL="nvidia_nim/selected", MODEL_FALLBACKS=["anthropic/backup"])+ )+ with TestClient(app) as client:+ response = client.post("/v1/messages/count_tokens", json=count_body())+ assert response.status_code == 422+ assert any(+ error["loc"][:2] == ["body", "messages"] for error in response.json()["detail"]+ )+++ ("update", "status"),+ [+ ({"messages": []}, 400),+ ({"messages": "invalid"}, 422),+ ({"messages": [{"role": "assistant", "content": [42]}]}, 422),+ ({"system": 42}, 422),+ ({"tools": [42]}, 422),+ ({"model": 42}, 422),+ ({"model": " "}, 400),+ ],+)+def test_native_count_rejects_bad_shapes_and_releases_lease(update, status):+ app = create_test_app(Settings(MODEL="anthropic/selected"))+ manager = provider_manager_for_app(app)+ with TestClient(app) as client:+ response = client.post(+ "/v1/messages/count_tokens", json={**count_body(), **update}+ )+ assert response.status_code == status, response.text+ assert manager._current.active_leases == 0++[email protected]("value", [float("nan"), float("inf"), "\ud800"])+def test_native_count_rejects_non_finite_or_non_utf8_json(value):+ app = create_test_app(Settings(MODEL="anthropic/selected"))+ with TestClient(app) as client:+ response = client.post(+ "/v1/messages/count_tokens",+ content=json.dumps({**count_body(), "extension": value}),+ headers={"content-type": "application/json"},+ )+ assert response.status_code == 400, response.text+ assert response.json()["error"]["type"] == "invalid_request_error"+ assert provider_manager_for_app(app)._current.active_leases == 0+++def test_native_count_proxy_auth_and_local_estimator_failure_release():+ app = create_test_app(+ Settings(+ MODEL="anthropic/selected",+ PROXY_AUTH_ENABLED=True,+ ANTHROPIC_AUTH_TOKEN="proxy-secret",+ )+ )+ with TestClient(app) as client:+ denied = client.post("/v1/messages/count_tokens", json=count_body())+ accepted = client.post(+ "/v1/messages/count_tokens",+ json=count_body(),+ headers={"Authorization": "Bearer proxy-secret"},+ )+ with (+ patch(+ "free_claude_code.api.routes.get_token_count",+ side_effect=RuntimeError("private-estimate-token"),+ ),+ patch("free_claude_code.api.request_errors.logger.error") as error_log,+ ):+ failed = client.post(+ "/v1/messages/count_tokens",+ json=count_body(),+ headers={"Authorization": "Bearer proxy-secret"},+ )+ assert denied.status_code in {401, 403}+ assert accepted.status_code == 200, accepted.text+ assert failed.status_code == 500, failed.text+ assert "private-estimate-token" not in str(error_log.call_args_list)+ assert provider_manager_for_app(app)._current.active_leases == 0+++def test_native_count_estimator_receives_payload_without_mutation_and_traces_alias():+ from free_claude_code.application.routing import ModelRouter++ body = count_body()+ body["tools"][0]["api_key"] = "private-tool-option"+ original = deepcopy(body)+ captured = []+ resolutions = []+ resolve = ModelRouter.resolve++ def record_resolve(router, model):+ resolutions.append(model)+ return resolve(router, model)++ def count(messages, system, tools):+ captured.append(+ (+ [message.model_dump() for message in messages],+ deepcopy(system),+ deepcopy(tools),+ )+ )+ before = deepcopy(captured[-1])+ result = get_token_count(messages, system, tools)+ assert ([message.model_dump() for message in messages], system, tools) == before+ return result++ app = create_test_app(Settings(MODEL="anthropic/selected"))+ with (+ patch.object(ModelRouter, "resolve", record_resolve),+ patch("free_claude_code.api.routes.get_token_count", count),+ patch("free_claude_code.api.handlers.token_count.trace_event") as trace,+ TestClient(app) as client,+ ):+ response = client.post("/v1/messages/count_tokens", json=body)+ assert response.status_code == 200, response.text+ assert resolutions == [body["model"]]+ assert captured == [(body["messages"], body["system"], body["tools"])]+ assert body == original+ route = next(+ call.kwargs+ for call in trace.call_args_list+ if call.kwargs["stage"] == "routing"+ )+ assert route["provider_model_ref"] == "anthropic/selected"+ assert route["gateway_model"] == body["model"]+ snapshot = next(call.args[0]() for call in trace.call_args_list if call.args)[+ "snapshot"+ ]+ assert snapshot["tools"][0]["api_key"] == "<redacted>"++[email protected]("cancel", [False, True])+async def test_native_count_retains_generation_while_waiting_for_encoder(cancel):+ from free_claude_code.runtime.provider_manager import ProviderGenerationLease++ entered = asyncio.Event()+ proceed = asyncio.Event()++ async def wait(lease):+ entered.set()+ await proceed.wait()++ async def commit():+ pass++ app = create_test_app(Settings(MODEL="anthropic/selected"))+ manager = provider_manager_for_app(app)+ old_generation = manager._current+ try:+ with patch.object(ProviderGenerationLease, "wait_for_token_estimation", wait):+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app), base_url="http://test"+ ) as client:+ task = asyncio.create_task(+ client.post("/v1/messages/count_tokens", json=count_body())+ )+ await asyncio.wait_for(entered.wait(), 2)+ await manager.replace(Settings(MODEL="nvidia_nim/other"), commit=commit)+ assert old_generation.active_leases == 1+ if cancel:+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ else:+ proceed.set()+ response = await asyncio.wait_for(task, 2)+ assert response.status_code == 200, response.text+ assert old_generation.active_leases == 0+ assert manager._current.active_leases == 0+ finally:+ proceed.set()+ await manager.close()diff --git a/tests/application/test_execution.py b/tests/application/test_execution.pyindex bfadbac2..570662df 100644--- a/tests/application/test_execution.py+++ b/tests/application/test_execution.py@@ -17,6 +17,7 @@ from free_claude_code.application.routing import ()from free_claude_code.config.reasoning import ReasoningPreferencefrom free_claude_code.core.anthropic.models import Message, MessagesRequest+from free_claude_code.core.anthropic.passthrough import NativeMessagesRequestfrom free_claude_code.core.async_iterators import AsyncCloseablefrom free_claude_code.core.failures import ExecutionFailure, FailureKindfrom free_claude_code.core.openai_responses import OpenAIResponsesRequest@@ -28,6 +29,16 @@ class FakeProvider:self.stream_calls: list[dict[str, object]] = []self.stream_close_calls = 0+ def stream_native_messages(+ self,+ request: NativeMessagesRequest,+ *,+ request_id: str,+ response_model: str,+ request_headers: Mapping[str, str] | None = None,+ ) -> AsyncIterator[str]:+ raise AssertionError("Compatibility test provider received a native request")+async def stream_messages(self,request: MessagesRequest,diff --git a/tests/cli/test_doctor.py b/tests/cli/test_doctor.pyindex b9ac54c5..ed490862 100644--- a/tests/cli/test_doctor.py+++ b/tests/cli/test_doctor.py@@ -27,6 +27,8 @@ def test_missing_configuration_still_produces_report(monkeypatch):def test_settings_projection_excludes_secrets_and_url_credentials():settings = Settings(OPENAI_API_KEY="secret-api-key",+ ANTHROPIC_API_KEY="secret-anthropic-key",+ ANTHROPIC_WORKSPACE_ID="secret-workspace",ANTHROPIC_AUTH_TOKEN="secret-proxy-token",TELEGRAM_BOT_TOKEN="secret-bot-token",ALLOWED_TELEGRAM_USER_ID="secret-user-id",diff --git a/tests/config/test_anthropic_configuration.py b/tests/config/test_anthropic_configuration.pynew file mode 100644index 00000000..b8ca5fbd--- /dev/null+++ b/tests/config/test_anthropic_configuration.py@@ -0,0 +1,53 @@+"""Anthropic settings share the standard masked configuration boundary."""++from free_claude_code.config.admin.manifest import FIELD_BY_KEY+from free_claude_code.config.loader import ManagedConfigStore+from free_claude_code.config.provider_catalog import PROVIDER_CATALOG+from free_claude_code.harnesses.claude import build_claude_proxy_env+from free_claude_code.providers.runtime.config import (+ build_provider_config,+ has_provider_configuration,+)+++def test_save_remove_workspace_optional_and_local_token_independent():+ store = ManagedConfigStore()+ store.initialize({})+ values = dict(store.read({}).managed) | {+ "ANTHROPIC_API_KEY": "upstream-key",+ "ANTHROPIC_WORKSPACE_ID": "wrkspc_test",+ "ANTHROPIC_PROXY": "http://localhost:8888",+ "ANTHROPIC_AUTH_TOKEN": "proxy-token",+ }+ store.commit(values)+ settings = store.read({}).settings+ descriptor = PROVIDER_CATALOG["anthropic"]+ config = build_provider_config(descriptor, settings)+ assert config.api_key == "upstream-key"+ assert config.proxy == "http://localhost:8888"+ assert settings.proxy_auth_token == "proxy-token"+ assert has_provider_configuration(+ descriptor, settings.model_copy(update={"anthropic_workspace_id": None})+ )+ assert FIELD_BY_KEY["ANTHROPIC_API_KEY"].secret+ assert FIELD_BY_KEY["ANTHROPIC_WORKSPACE_ID"].provider_ids == ("anthropic",)+ values.pop("ANTHROPIC_API_KEY")+ store.commit(values)+ assert not has_provider_configuration(descriptor, store.read({}).settings)+++def test_claude_launch_does_not_inherit_anthropic_account_credentials():+ env = build_claude_proxy_env(+ proxy_root_url="http://localhost:8082",+ auth_token="proxy-token",+ base_env={+ "ANTHROPIC_API_KEY": "upstream-key",+ "ANTHROPIC_WORKSPACE_ID": "wrkspc_test",+ "ANTHROPIC_AUTH_TOKEN": "stale-token",+ "PATH": "retained",+ },+ )+ assert "ANTHROPIC_API_KEY" not in env+ assert "ANTHROPIC_WORKSPACE_ID" not in env+ assert env["ANTHROPIC_AUTH_TOKEN"] == "proxy-token"+ assert env["PATH"] == "retained"diff --git a/tests/contracts/test_feature_manifest.py b/tests/contracts/test_feature_manifest.pyindex c7740c4b..8db4f12f 100644--- a/tests/contracts/test_feature_manifest.py+++ b/tests/contracts/test_feature_manifest.py@@ -66,9 +66,11 @@ def test_product_coverage_is_not_satisfied_by_prereq_probes() -> None:def test_provider_and_platform_registries_include_builtins() -> None:from free_claude_code.providers.alibaba_cloud import AlibabaCloudProvider+ from free_claude_code.providers.anthropic import AnthropicProviderspecialized_provider_classes = {"alibaba_cloud": AlibabaCloudProvider,+ "anthropic": AnthropicProvider,"openai": OpenAICodexProvider,"openai_api": OpenAIAPIProvider,"github_copilot": GitHubCopilotProvider,diff --git a/tests/contracts/test_provider_catalog_order.py b/tests/contracts/test_provider_catalog_order.pyindex 16cea2c5..1667f336 100644--- a/tests/contracts/test_provider_catalog_order.py+++ b/tests/contracts/test_provider_catalog_order.py@@ -12,6 +12,7 @@ _EXPECTED_PROVIDER_ORDER: tuple[str, ...] = ("cline_pass","openai","openai_api",+ "anthropic","github_copilot","xai","alibaba_cloud",diff --git a/tests/core/anthropic/test_native_count_and_relay.py b/tests/core/anthropic/test_native_count_and_relay.pynew file mode 100644index 00000000..095ddefb--- /dev/null+++ b/tests/core/anthropic/test_native_count_and_relay.py@@ -0,0 +1,62 @@+"""Native boundary rules that must hold before admission and local estimation."""++from copy import deepcopy++import pytest++from free_claude_code.core.anthropic import (+ MessagesRequest,+ NativeTokenCountRequest,+ get_token_count,+)+from free_claude_code.core.anthropic.native import NativeMessagesError+from free_claude_code.core.anthropic.passthrough import NativeMessagesPassthrough+++ "block",+ [+ {"type": "not-ping"},+ {"type": "ping", "extra": float("nan")},+ {"type": "ping", "extra": "\ud800"},+ ],+)+def test_suppressed_leading_ping_still_validates_envelope(block):+ relay = NativeMessagesPassthrough("alias")+ with pytest.raises(NativeMessagesError):+ relay.feed("ping", block)+ assert not relay.started++[email protected]("in_tool", [False, True])+def test_native_count_retains_existing_text_and_image_estimation(in_tool):+ image = {+ "type": "image",+ "source": {"type": "base64", "media_type": "image/png", "data": "A" * 300_000},+ }+ text = {"type": "text", "text": "Screenshot captured"}++ def payload(with_image):+ blocks = [text, image] if with_image else [text]+ if in_tool:+ blocks = [{"type": "tool_result", "tool_use_id": "t1", "content": blocks}]+ return {+ "model": "test",+ "max_tokens": 32,+ "messages": [{"role": "user", "content": blocks}],+ "system": [{"type": "text", "text": "Describe the screenshot"}],+ }++ body = payload(True)+ original = deepcopy(body)+ native = NativeTokenCountRequest.model_validate(body)+ typed = MessagesRequest.model_validate(body)+ without_image = NativeTokenCountRequest.model_validate(payload(False))+ counted = get_token_count(native.messages, native.system)+ assert counted == get_token_count(typed.messages, typed.system)+ assert (+ 85+ <= counted - get_token_count(without_image.messages, without_image.system)+ < 1000+ )+ assert body == originaldiff --git a/tests/providers/test_anthropic_discovery.py b/tests/providers/test_anthropic_discovery.pynew file mode 100644index 00000000..11e4ea0f--- /dev/null+++ b/tests/providers/test_anthropic_discovery.py@@ -0,0 +1,283 @@+"""Discovery snapshots remain authoritative for each compatibility request."""++import asyncio+import json++import httpx+import pytest++from free_claude_code.application.errors import InvalidRequestError+from free_claude_code.application.model_metadata import ProviderModelInfo+from free_claude_code.core.anthropic.models import MessagesRequest+from free_claude_code.core.openai_responses import OpenAIResponsesRequest+from free_claude_code.core.reasoning import (+ ReasoningCapability,+ ReasoningEffort,+ ReasoningPolicy,+)+from free_claude_code.providers.anthropic.models import model_record+from free_claude_code.providers.model_listing import ModelListResponseError+from tests.providers.test_anthropic_messages_transport import _events, _sse+from tests.providers.test_anthropic_provider import provider+++def metadata(model, adaptive, *, max_tokens=8192):+ return {+ "id": model,+ "max_tokens": max_tokens,+ "max_input_tokens": 200000,+ "capabilities": {+ "thinking": {+ "supported": True,+ "types": {+ "adaptive": {"supported": adaptive},+ "enabled": {"supported": not adaptive},+ },+ },+ "effort": {+ "supported": adaptive,+ "low": {"supported": adaptive},+ "high": {"supported": adaptive},+ "max": {"supported": False},+ },+ "image_input": {"supported": True},+ },+ }+++def test_metadata_uses_advertised_types_and_efforts_without_name_inference():+ adaptive = model_record(metadata("manual-sounding-name", True))+ manual = model_record(metadata("adaptive-sounding-name", False))+ unknown = model_record({"id": "claude-future"})+ assert adaptive.messages.adaptive_thinking == "required"+ assert adaptive.messages.supported_efforts == ("low", "high")+ assert adaptive.info.reasoning_capability is not ReasoningCapability.REQUIRED+ assert adaptive.info.context_window_tokens == 200000+ assert adaptive.messages.supports_vision is True+ assert manual.messages.adaptive_thinking == "unsupported"+ assert unknown.messages.adaptive_thinking is None+ assert unknown.info.supports_thinking is None+++ "bad_page",+ [+ {"data": [], "has_more": True, "last_id": "old"},+ {"data": [{"id": "old"}], "has_more": True, "last_id": "old"},+ {"data": [], "has_more": "false"},+ {"data": [{"id": ""}], "has_more": False},+ {"has_more": False},+ ],+)+async def test_malformed_refresh_never_publishes_a_partial_catalog(bad_page):+ refresh = False+ calls = []++ def handle(request):+ calls.append(request)+ assert request.headers["authorization"] == "Bearer upstream-secret"+ assert request.headers["anthropic-workspace-id"] == "wrkspc_test"+ assert request.headers["anthropic-version"] == "2023-06-01"+ if not refresh:+ return httpx.Response(+ 200, json={"data": [metadata("old", False)], "has_more": False}+ )+ return httpx.Response(200, json=bad_page)++ p = provider(handle)+ try:+ await p.list_model_infos()+ before = await p.model_record("old")+ refresh = True+ with pytest.raises(ModelListResponseError):+ await p.list_model_infos()+ assert await p.model_record("old") is before+ assert len(calls) <= 3+ finally:+ await p.cleanup()+++async def test_valid_empty_catalog_is_published_without_fabricated_models():+ p = provider(+ lambda request: httpx.Response(200, json={"data": [], "has_more": False})+ )+ try:+ assert await p.list_model_infos() == frozenset()+ finally:+ await p.cleanup()+++async def test_concurrent_alias_lookup_is_cached_and_uses_same_credentials():+ calls = []++ async def handle(request):+ calls.append(request)+ await asyncio.sleep(0)+ assert request.url.path == "/v1/models/latest-alias"+ assert request.headers["authorization"] == "Bearer upstream-secret"+ assert request.headers["anthropic-workspace-id"] == "wrkspc_test"+ return httpx.Response(200, json=metadata("resolved-model", True))++ p = provider(handle)+ try:+ first, second = await asyncio.gather(+ p.model_record("latest-alias"), p.model_record("latest-alias")+ )+ assert first is second+ assert first.info.model_id == "resolved-model"+ assert len(calls) == 1+ finally:+ await p.cleanup()+++async def test_concurrent_models_use_independent_conversion_capabilities():+ sent = []++ async def handle(request):+ if request.method == "GET":+ return httpx.Response(+ 200,+ json={+ "data": [metadata("manual", False), metadata("adaptive", True)],+ "has_more": False,+ },+ )+ sent.append(json.loads(request.content))+ await asyncio.sleep(0)+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, content=_sse(*_events())+ )++ p = provider(handle)+ try:+ await p.list_model_infos()++ async def messages():+ return [+ event+ async for event in p.stream_messages(+ MessagesRequest(+ model="manual",+ messages=[{"role": "user", "content": "hello"}],+ max_tokens=16000,+ ),+ reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),+ )+ ]++ async def responses():+ return [+ event+ async for event in p.stream_responses(+ OpenAIResponsesRequest(model="adaptive", input="hello"),+ reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),+ )+ ]++ message_output, response_output = await asyncio.gather(messages(), responses())+ assert "message_stop" in "".join(message_output)+ assert "response.completed" in "".join(response_output)+ by_model = {body["model"]: body for body in sent}+ assert by_model["manual"]["thinking"] == {+ "type": "enabled",+ "budget_tokens": 2048,+ }+ assert by_model["manual"]["max_tokens"] == 8192+ assert "output_config" not in by_model["manual"]+ assert by_model["adaptive"]["thinking"] == {"type": "adaptive"}+ assert by_model["adaptive"]["output_config"] == {"effort": "high"}+ finally:+ await p.cleanup()+++async def test_refresh_does_not_mutate_an_inflight_model_record():+ posted = asyncio.Event()+ release = asyncio.Event()+ refresh = False+ sent = []++ async def handle(request):+ if request.method == "GET":+ return httpx.Response(+ 200,+ json={+ "data": [+ metadata("same", refresh, max_tokens=4096 if refresh else 8192)+ ],+ "has_more": False,+ },+ )+ sent.append(json.loads(request.content))+ posted.set()+ await release.wait()+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, content=_sse(*_events())+ )++ p = provider(handle)++ async def run():+ return [+ event+ async for event in p.stream_messages(+ MessagesRequest(+ model="same", messages=[{"role": "user", "content": "hi"}]+ ),+ reasoning=ReasoningPolicy.on(),+ )+ ]++ try:+ await p.list_model_infos()+ before = await p.model_record("same")+ task = asyncio.create_task(run())+ await asyncio.wait_for(posted.wait(), 1)+ refresh = True+ await p.list_model_infos()+ after = await p.model_record("same")+ assert before.messages.adaptive_thinking == "unsupported"+ assert after.messages.adaptive_thinking == "required"+ release.set()+ await task+ await run()+ assert sent[0]["thinking"]["type"] == "enabled"+ assert sent[0]["max_tokens"] == 8192+ assert sent[1]["thinking"]["type"] == "adaptive"+ assert sent[1]["max_tokens"] == 4096+ finally:+ release.set()+ await p.cleanup()+++async def test_fresh_owner_does_not_trust_stale_generic_capabilities():+ calls = []++ def handle(request):+ calls.append(request)+ assert request.method == "GET"+ return httpx.Response(404, json={"error": {"type": "not_found_error"}})++ p = provider(handle)+ try:+ with pytest.raises(InvalidRequestError, match="thinking mode"):+ _ = [+ event+ async for event in p.stream_messages(+ MessagesRequest(+ model="alias", messages=[{"role": "user", "content": "hi"}]+ ),+ model_info=ProviderModelInfo(+ "alias", supports_thinking=True, max_output_tokens=8000+ ),+ reasoning=ReasoningPolicy.on(),+ )+ ]+ assert len(calls) == 1+ finally:+ await p.cleanup()diff --git a/tests/providers/test_anthropic_native_transport.py b/tests/providers/test_anthropic_native_transport.pynew file mode 100644index 00000000..11b75ca6--- /dev/null+++ b/tests/providers/test_anthropic_native_transport.py@@ -0,0 +1,398 @@+"""Native controls, upstream recovery, and admitted resource lifetime."""++import asyncio+import json+from dataclasses import replace++import httpx+import pytest++from free_claude_code.application.errors import InvalidRequestError+from free_claude_code.core.anthropic.passthrough import NativeMessagesRequest+from free_claude_code.core.anthropic.stream_contracts import parse_sse_text+from free_claude_code.core.failures import ExecutionFailure+from free_claude_code.core.history_replay import ReplayRecord, encode_replay+from free_claude_code.core.json_types import JsonObject+from free_claude_code.providers.history_replay import replay_origin+from tests.providers.test_anthropic_messages_transport import Wire, _events, _sse+from tests.providers.test_anthropic_provider import native_body, provider+++async def collect(p, body=None, **kwargs):+ return [+ event+ async for event in p.stream_native_messages(+ NativeMessagesRequest(body or native_body()), **kwargs+ )+ ]+++async def test_native_omissions_helpers_controls_and_cookie_isolation():+ received = []++ def handle(request):+ received.append(request)+ return httpx.Response(+ 200,+ json={"type": "message", "content": []},+ headers={"set-cookie": "upstream=session"},+ )++ p = provider(handle)+ body = native_body()+ del body["max_tokens"]+ del body["stream"]+ body.update(+ {+ "original_model": "fcc",+ "resolved_provider_model": "fcc",+ "betas": ["a-beta", "b-beta"],+ "extra_body": {"new_option": {"data": True}},+ "stop_sequences": ["</severity>"],+ "temperature": 0.7,+ "cache_control": {"type": "ephemeral"},+ "thinking": {+ "type": "enabled",+ "budget_tokens": 3579,+ "display": "summarized",+ },+ }+ )+ try:+ await collect(+ p,+ body,+ request_headers={+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "a-beta,c-beta",+ "x-api-key": "foreign",+ "Host": "foreign.test",+ },+ )+ await collect(p)+ sent = json.loads(received[0].content)+ assert "stream" not in sent and "max_tokens" not in sent+ assert "original_model" not in sent and "resolved_provider_model" not in sent+ assert "betas" not in sent and "extra_body" not in sent+ assert sent["new_option"] == {"data": True}+ assert sent["thinking"] == body["thinking"]+ assert sent["stop_sequences"] == body["stop_sequences"]+ assert sent["temperature"] == 0.7+ assert sent["cache_control"] == body["cache_control"]+ assert received[0].headers["anthropic-beta"] == "a-beta,c-beta,b-beta"+ assert "anthropic-beta" not in received[1].headers+ assert all(+ "cookie" not in request.headers and "x-api-key" not in request.headers+ for request in received+ )+ assert received[0].headers["host"] == "api.anthropic.com"+ finally:+ await p.cleanup()+++ "helper",+ [+ {"model": "other"},+ {"headers": {"Authorization": "other"}},+ {"api_key": "other"},+ {"stream": True},+ ],+)+async def test_helpers_cannot_override_transport_ownership(helper):+ def handle(request):+ raise AssertionError("Invalid helpers reached upstream")++ p = provider(handle)+ try:+ with pytest.raises(InvalidRequestError):+ await collect(p, {**native_body(), "extra_body": helper})+ finally:+ await p.cleanup()+++async def test_hosted_tool_stream_preserves_signatures_usage_and_pause_turn():+ events = _events(stop="pause_turn")+ events[1]["content_block"] = {+ "type": "server_tool_use",+ "id": "srv",+ "name": "web_search",+ "input": {},+ }+ events[2]["delta"] = {+ "type": "input_json_delta",+ "partial_json": '{"query":"hello"}',+ }+ events[4]["usage"] = {+ "output_tokens": 15,+ "cache_read_input_tokens": 8,+ "server_tool_use": {"web_search_requests": 1},+ }+ events[4:4] = [+ {+ "type": "content_block_start",+ "index": 1,+ "content_block": {+ "type": "web_search_tool_result",+ "tool_use_id": "srv",+ "content": [+ {"encrypted_content": "opaque", "url": "https://example.test"}+ ],+ },+ },+ {"type": "content_block_stop", "index": 1},+ {+ "type": "content_block_start",+ "index": 2,+ "content_block": {+ "type": "future_execution_result",+ "data": {"keep": True},+ },+ },+ {+ "type": "content_block_delta",+ "index": 2,+ "delta": {"type": "signature_delta", "signature": "native-signature"},+ },+ {"type": "content_block_stop", "index": 2},+ ]+ wire = Wire([_sse(*events)])+ p = provider(+ lambda request: httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=wire+ )+ )+ try:+ output = parse_sse_text(+ "".join(await collect(p, native_body(True), response_model="alias"))+ )+ expected = json.loads(json.dumps(events))+ expected[0]["message"]["model"] = "alias"+ assert [event.data for event in output] == expected+ assert wire.closed+ finally:+ await p.cleanup()++[email protected]("streaming", [False, True])[email protected]("status", [401, 402, 403, 429, 529])+async def test_http_failure_status_evidence_and_bounded_recovery(streaming, status):+ wires = []++ def handle(request):+ wire = Wire(+ [+ json.dumps(+ {+ "type": "error",+ "error": {+ "type": "api_error",+ "message": "test provider evidence",+ },+ "request_id": "upstream-request",+ }+ ).encode()+ ]+ )+ wires.append(wire)+ return httpx.Response(+ status, stream=wire, headers={"request-id": "upstream-request"}+ )++ p = provider(handle)+ try:+ with pytest.raises(ExecutionFailure) as result:+ await collect(p, native_body(streaming), request_id="local-request")+ assert result.value.status_code == status+ assert "test provider evidence" in result.value.message+ assert "local-request" in result.value.message+ assert "upstream-request" in result.value.message+ assert len(wires) == (2 if status in {429, 529} else 1)+ assert all(wire.closed for wire in wires)+ finally:+ await p.cleanup()++[email protected]("streaming", [False, True])+async def test_connection_recovery_before_output_closes_failed_response(streaming):+ first = Wire([httpx.ReadError("connection closed")])+ second = Wire(+ [_sse(*_events()) if streaming else b'{"type":"message","content":[]}']+ )+ wires = iter([first, second])+ p = provider(+ lambda request: httpx.Response(+ 200,+ stream=next(wires),+ headers={+ "content-type": "text/event-stream" if streaming else "application/json"+ },+ )+ )+ try:+ assert await collect(p, native_body(streaming))+ assert first.closed and second.closed+ finally:+ await p.cleanup()++[email protected]("failure", ["error", "connection", "eof"])+async def test_leading_ping_does_not_accept_attempt_or_prevent_retry(failure):+ tail = {+ "error": _sse({"type": "error", "error": {"type": "overloaded_error"}}),+ "connection": httpx.ReadError("connection lost"),+ "eof": b"",+ }[failure]+ first = Wire([_sse({"type": "ping"}), tail])+ events = _events()+ events.insert(1, {"type": "ping", "extension": "preserve after start"})+ second = Wire([_sse({"type": "ping"}, *events)])+ wires = iter([first, second])+ p = provider(+ lambda request: httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ stream=next(wires),+ )+ )+ try:+ output = parse_sse_text(+ "".join(await collect(p, native_body(True), response_model="native"))+ )+ assert [event.data for event in output] == events+ assert first.closed and second.closed+ finally:+ await p.cleanup()+++ "bad_tail",+ [+ b"",+ b"event: content_block_delta\ndata: not-json\n\n",+ _sse({"type": "message_start", "message": {}}),+ ],+)+async def test_malformed_or_incomplete_stream_after_output_never_replays(bad_tail):+ calls = []+ wire = Wire([_sse(_events()[0]), bad_tail])++ def handle(request):+ calls.append(request)+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=wire+ )++ p = provider(handle)+ try:+ stream = p.stream_native_messages(NativeMessagesRequest(native_body(True)))+ assert "message_start" in await anext(stream)+ with pytest.raises(ExecutionFailure):+ await anext(stream)+ assert len(calls) == 1+ assert wire.closed+ finally:+ await p.cleanup()+++async def test_early_consumer_exit_releases_admission_and_response():+ wire = Wire([_sse(*_events())])+ p = provider(+ lambda request: httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=wire+ )+ )+ stream = p.stream_native_messages(NativeMessagesRequest(native_body(True)))+ try:+ await anext(stream)+ await stream.aclose()+ assert wire.closed+ assert await collect(p, native_body(True))+ finally:+ await p.cleanup()++[email protected]("streaming", [False, True])+async def test_cancelled_read_closes_response_without_retry(streaming):+ reading = asyncio.Event()+ closed = asyncio.Event()+ calls = []++ class BlockingWire(httpx.AsyncByteStream):+ async def __aiter__(self):+ reading.set()+ await asyncio.Event().wait()+ yield b""++ async def aclose(self):+ closed.set()++ def handle(request):+ calls.append(request)+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=BlockingWire()+ )++ p = provider(handle)+ task = asyncio.create_task(collect(p, native_body(streaming)))+ try:+ await asyncio.wait_for(reading.wait(), 1)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert closed.is_set()+ assert len(calls) == 1+ finally:+ await p.cleanup()+++async def test_native_history_restores_matching_fcc_carriers_and_rejects_foreign():+ received = []++ def handle(request):+ received.append(json.loads(request.content))+ return httpx.Response(200, json={"type": "message", "content": []})++ p = provider(handle)+ native: JsonObject = {+ "type": "thinking",+ "thinking": "native",+ "signature": "original-signature",+ }+ origin = replay_origin(+ "anthropic", "messages", "claude-test", endpoint=await p.endpoint()+ )+ body = native_body()+ body["messages"] = [+ {+ "role": "assistant",+ "content": [+ {+ "type": "thinking",+ "thinking": "client",+ "signature": encode_replay(ReplayRecord(origin, native)),+ }+ ],+ }+ ]+ try:+ await collect(p, body)+ assert received[0]["messages"][0]["content"] == [native]+ body["messages"][0]["content"][0]["signature"] = encode_replay(+ ReplayRecord(replace(origin, provider="foreign"), native)+ )+ with pytest.raises(InvalidRequestError, match="different provider"):+ await collect(p, body)+ assert len(received) == 1+ finally:+ await p.cleanup()diff --git a/tests/providers/test_anthropic_provider.py b/tests/providers/test_anthropic_provider.pynew file mode 100644index 00000000..980ea961--- /dev/null+++ b/tests/providers/test_anthropic_provider.py@@ -0,0 +1,195 @@+import json++import httpx+import pytest++from free_claude_code.config.provider_catalog import PROVIDER_CATALOG+from free_claude_code.core.anthropic.passthrough import NativeMessagesRequest+from free_claude_code.core.failures import ExecutionFailure+from free_claude_code.providers.anthropic import AnthropicProvider+from tests.providers.support import immediate_admission, make_provider_config+++def provider(handler, **kwargs):+ return AnthropicProvider(+ make_provider_config("upstream-secret", "https://api.anthropic.com/v1"),+ workspace_id="wrkspc_test",+ admission=immediate_admission(max_attempts=2),+ transport=httpx.MockTransport(handler),+ **kwargs,+ )+++def native_body(stream=False):+ return {+ "model": "claude-test",+ "stream": stream,+ "max_tokens": 12345,+ "thinking": {"type": "adaptive", "future": "keep"},+ "messages": [+ {+ "role": "assistant",+ "content": [{"type": "future_tool_result", "opaque": [1, 2]}],+ }+ ],+ "tools": [{"type": "web_search_20260318", "name": "web_search", "max_uses": 1}],+ "future_option": {"keep": True},+ }+++async def test_native_json_preserves_body_and_owns_auth():+ body = native_body()+ received = []++ def handle(request):+ received.append(request)+ return httpx.Response(+ 200,+ json={+ "type": "message",+ "model": "claude-test",+ "content": [{"type": "future_tool_result", "opaque": "kept"}],+ "usage": {+ "output_tokens": 4,+ "server_tool_use": {"web_search_requests": 1},+ },+ },+ )++ p = provider(handle)+ try:+ result = [+ x+ async for x in p.stream_native_messages(+ NativeMessagesRequest(body),+ request_id="r",+ response_model="public",+ request_headers={+ "Authorization": "Bearer client",+ "Cookie": "secret",+ "anthropic-workspace-id": "foreign",+ "anthropic-beta": "test-beta,test-beta",+ },+ )+ ]+ message = json.loads("".join(result))+ assert message["model"] == "public"+ assert message["content"][0]["opaque"] == "kept"+ assert message["usage"]["server_tool_use"]["web_search_requests"] == 1+ assert json.loads(received[0].content) == body+ assert received[0].headers["authorization"] == "Bearer upstream-secret"+ assert received[0].headers["anthropic-workspace-id"] == "wrkspc_test"+ assert received[0].headers["anthropic-beta"] == "test-beta"+ assert "cookie" not in received[0].headers+ assert "x-api-key" not in received[0].headers+ assert body == native_body()+ finally:+ await p.cleanup()+++async def test_native_sse_relays_unknown_tool_events_without_replay():+ calls = []+ events = [+ {"type": "message_start", "message": {"id": "m", "model": "claude-test"}},+ {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "server_tool_use",+ "id": "s",+ "name": "web_search",+ "input": {},+ },+ },+ {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "input_json_delta", "partial_json": '{"query":"hi"}'},+ },+ {"type": "future_event", "opaque": "keep"},+ {"type": "error", "error": {"type": "overloaded_error", "message": "busy"}},+ ]++ def handle(request):+ calls.append(request)+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ content="".join(+ f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in events+ ),+ )++ p = provider(handle)+ output = []+ try:+ with pytest.raises(ExecutionFailure):+ async for chunk in p.stream_native_messages(+ NativeMessagesRequest(native_body(True)),+ request_id="r",+ response_model="public",+ ):+ assert isinstance(chunk, str)+ output.append(chunk)+ assert len(calls) == 1+ assert '"model": "public"' in output[0]+ assert "input_json_delta" in "".join(output)+ assert "future_event" in "".join(output)+ finally:+ await p.cleanup()+++async def test_model_discovery_is_atomic_and_retains_thinking_types():+ fail = False++ def handle(request):+ if "after_id" not in request.url.params:+ return httpx.Response(+ 200,+ json={+ "data": [+ {+ "id": "adaptive",+ "max_tokens": 8192,+ "capabilities": {+ "thinking": {+ "supported": True,+ "types": {+ "adaptive": {"supported": True},+ "enabled": {"supported": False},+ },+ }+ },+ }+ ],+ "has_more": True,+ "last_id": "adaptive",+ },+ )+ return httpx.Response(+ 503 if fail else 200, json={"data": [{"id": "manual"}], "has_more": False}+ )++ p = provider(handle)+ try:+ assert {x.model_id for x in await p.list_model_infos()} == {+ "adaptive",+ "manual",+ }+ before = await p.model_record("adaptive")+ assert before.messages.adaptive_thinking == "required"+ fail = True+ with pytest.raises(httpx.HTTPStatusError):+ await p.list_model_infos()+ assert await p.model_record("adaptive") == before+ finally:+ await p.cleanup()+++def test_anthropic_is_configuration_provider_with_native_messages():+ descriptor = PROVIDER_CATALOG["anthropic"]+ assert descriptor.credential_env == "ANTHROPIC_API_KEY"+ assert descriptor.native_messages_passthroughdiff --git a/tests/providers/test_credential_validation.py b/tests/providers/test_credential_validation.pyindex b5227602..bc4d3c8e 100644--- a/tests/providers/test_credential_validation.py+++ b/tests/providers/test_credential_validation.py@@ -11,6 +11,7 @@ from free_claude_code.providers import credential_validation as validation# Minimal published response shapes, independent of the implementation registry.CASES = [+ ("anthropic", "https://api.anthropic.com/v1/models?limit=1", {"data": []}, 401),("open_router","https://openrouter.ai/api/v1/key",@@ -180,7 +181,7 @@ async def test_documented_probe_acceptance_and_rejection(@pytest.mark.asyncio@pytest.mark.parametrize("status", [400, 402, 403, 404, 429, 500, 503])[email protected]("provider_id", ["groq", "xkiro"])[email protected]("provider_id", ["groq", "xkiro", "anthropic"])async def test_ambiguous_errors_warn_without_retry(monkeypatch, status, caplog, provider_id):@@ -201,7 +202,7 @@ async def test_ambiguous_errors_warn_without_retry(@pytest.mark.asyncio@pytest.mark.parametrize("status", [200, 401, 302])[email protected]("provider_id", ["groq", "xkiro"])[email protected]("provider_id", ["groq", "xkiro", "anthropic"])async def test_non_api_responses_do_not_verify_or_reject(monkeypatch, status, provider_id):@@ -381,3 +382,30 @@ 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.UNVERIFIED+++async def test_anthropic_probe_uses_workspace_and_version_without_inference(+ monkeypatch,+):+ requests = []++ def respond(request):+ requests.append(request)+ return httpx.Response(200, json={"data": []})++ _mock_http(monkeypatch, respond)+ settings = Settings(+ ANTHROPIC_API_KEY="api-key",+ ANTHROPIC_AUTH_TOKEN="local-token",+ ANTHROPIC_WORKSPACE_ID="wrkspc_test",+ )+ checks = await validation.check_credentials(settings, ("ANTHROPIC_API_KEY",))+ assert checks[0].status is validation.CredentialStatus.VERIFIED+ assert len(requests) == 1+ request = requests[0]+ assert request.method == "GET" and request.url.params["limit"] == "1"+ assert request.headers["Authorization"] == "Bearer api-key"+ assert request.headers["anthropic-workspace-id"] == "wrkspc_test"+ assert request.headers["anthropic-version"] == "2023-06-01"+ assert "local-token" not in str(request.headers)diff --git a/tests/providers/test_provider_runtime.py b/tests/providers/test_provider_runtime.pyindex c0878395..85aafe54 100644--- a/tests/providers/test_provider_runtime.py+++ b/tests/providers/test_provider_runtime.py@@ -48,6 +48,7 @@ from free_claude_code.providers.admission import ProviderAdmissionControllerfrom free_claude_code.providers.admission_policy import ProviderAdmissionLimitsfrom free_claude_code.providers.admission_registry import ProviderAdmissionRegistryfrom free_claude_code.providers.alibaba_cloud import AlibabaCloudProvider+from free_claude_code.providers.anthropic import AnthropicProviderfrom free_claude_code.providers.cloudflare import CloudflareProviderfrom free_claude_code.providers.deepseek import DeepSeekProviderfrom free_claude_code.providers.gemini import GeminiProvider@@ -86,6 +87,9 @@ def _make_settings(**overrides):mock.nvidia_nim_api_key = "test_key"mock.open_router_api_key = "test_openrouter_key"mock.xai_api_key = "test_xai_key"+ mock.anthropic_api_key = "test_anthropic_key"+ mock.anthropic_workspace_id = "workspace"+ mock.anthropic_proxy = Nonemock.alibaba_cloud_api_key = "test_alibaba_key"mock.alibaba_cloud_base_url = Nonemock.alibaba_cloud_proxy = None@@ -1104,6 +1108,7 @@ async def test_create_provider_instantiates_each_builtin():"github_copilot": GitHubCopilotProvider,"cline_pass": OpenAIChatProvider,"xai": OpenAIChatProvider,+ "anthropic": AnthropicProvider,"alibaba_cloud": AlibabaCloudProvider,"qwencloud": OpenAIChatProvider,"qwencloud_coding": OpenAIChatProvider,diff --git a/tests/runtime/test_anthropic_provider_lifecycle.py b/tests/runtime/test_anthropic_provider_lifecycle.pynew file mode 100644index 00000000..a1f70304--- /dev/null+++ b/tests/runtime/test_anthropic_provider_lifecycle.py@@ -0,0 +1,87 @@+"""Credential changes create fresh Anthropic state while retained leases drain."""++import httpx+import pytest++from free_claude_code.config.provider_catalog import PROVIDER_CATALOG+from free_claude_code.config.settings import Settings+from free_claude_code.providers.anthropic import AnthropicProvider+from free_claude_code.providers.runtime import ProviderRuntime+from free_claude_code.providers.runtime.config import build_provider_config+from free_claude_code.runtime.provider_manager import ProviderRuntimeManager+from tests.providers.support import immediate_admission+from tests.providers.test_anthropic_discovery import metadata+++async def test_workspace_replacement_retires_http_and_capabilities_with_lease():+ owners = []+ requests = []++ def factory(settings, registry):+ def handle(request):+ requests.append(request)+ if settings.anthropic_workspace_id == "new":+ return httpx.Response(403, json={"error": {"type": "permission_error"}})+ if request.url.path == "/v1/models":+ return httpx.Response(+ 200,+ json={"data": [metadata("same-model", True)], "has_more": False},+ )+ return httpx.Response(200, json=metadata("same-model", True))++ owner = AnthropicProvider(+ build_provider_config(PROVIDER_CATALOG["anthropic"], settings),+ workspace_id=settings.anthropic_workspace_id,+ admission=immediate_admission(max_attempts=1),+ transport=httpx.MockTransport(handle),+ )+ owners.append(owner)+ return ProviderRuntime(settings, registry, {"anthropic": owner})++ async def commit():+ return None++ settings = Settings(+ MODEL="anthropic/same-model",+ NVIDIA_NIM_API_KEY=None,+ ANTHROPIC_API_KEY="old-key",+ ANTHROPIC_WORKSPACE_ID="old",+ )+ manager = ProviderRuntimeManager(settings, runtime_factory=factory)+ old_lease = await manager.acquire()+ new_lease = None+ try:+ old = await old_lease.resolve_provider("anthropic")+ assert isinstance(old, AnthropicProvider)+ record = await old.model_record("same-model")+ await manager.replace(+ settings.model_copy(+ update={"anthropic_api_key": "new-key", "anthropic_workspace_id": "new"}+ ),+ commit=commit,+ )+ new_lease = await manager.acquire()+ new = await new_lease.resolve_provider("anthropic")+ assert isinstance(new, AnthropicProvider)+ assert new is not old+ # Generic catalog rows may survive failed discovery; native facts do not.+ assert new_lease.model_info("anthropic", "same-model") is not None+ assert (await new.model_record("same-model")).messages.adaptive_thinking is None+ assert await old.model_record("same-model") is record+ assert (await old.endpoint()).headers["anthropic-workspace-id"] == "old"+ assert (await new.endpoint()).headers["Authorization"] == "Bearer new-key"+ assert not old._http.is_closed+ await old_lease.release()+ assert old._http.is_closed+ assert not new._http.is_closed+ finally:+ await old_lease.release()+ if new_lease is not None:+ await new_lease.release()+ await manager.close()+ assert all(owner._http.is_closed for owner in owners)+ assert {request.headers["anthropic-workspace-id"] for request in requests} == {+ "old",+ "new",+ }