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
Restore Claude Auto mode through OpenAI connected accounts (#1455)
Ali Khokhar41045e738060
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex d90067cc..a4603187 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -1144,10 +1144,15 @@ The Messages handler runs these only after model routing and after local server-handling. Each optimization is controlled by settings flags.Claude Code auto-mode safety-classifier requests are a message-only routing-policy, not a short-circuit response. After routing, the Messages handler detects the-narrow classifier prompt shape and forces reasoning off before provider execution-so Claude Code receives a parser-readable `<block>yes</block>` or-`<block>no</block>` verdict.+policy, not a short-circuit response. After routing, the Messages handler detects+the exact current severity or legacy Boolean classifier shape, forces reasoning+off, and consumes only that classifier's optional `</severity>` or `</block>`+terminator before provider execution. Claude accepts the parser-readable verdict+when the provider completes normally with `end_turn`; FCC does not fabricate a+stop reason or truncate the output. Unrecognized and non-classifier stop+sequences remain on the request so a target converter can preserve them or reject+the request as lossy. This policy belongs to the Claude Messages boundary, never+to an OpenAI provider or model-specific adapter.Local `web_search` and `web_fetch` handling lives under[api/web_tools/](src/free_claude_code/api/web_tools/). When `ENABLE_WEB_SERVER_TOOLS` is true, thediff --git a/pyproject.toml b/pyproject.tomlindex cdf6096a..c90e763e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "5.6.1"+version = "5.6.2"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/smoke/README.md b/smoke/README.mdindex 24e1e9f2..aa1aadcc 100644--- a/smoke/README.md+++ b/smoke/README.md@@ -55,7 +55,7 @@ Default targets do not send real bot messages or load voice backends:| --- | --- | --- || `api` | messages, count_tokens full payload, errors, `/stop`, optimizations | configured provider only for streaming messages || `auth` | canonical bearer auth, conflicting legacy headers, invalid/missing auth | none; test sets an isolated token |-| `cli` | server entrypoint, Claude CLI adaptive thinking, session cleanup | Claude CLI binary and provider only for real CLI |+| `cli` | server entrypoint, Claude CLI adaptive thinking, Auto-mode classifier, session cleanup | Claude CLI binary and provider only for real CLI; connected OpenAI account for Auto mode || `clients` | VS Code and JetBrains protocol payloads; Pi, OpenCode, and Cline CLI prompts | configured provider; installed Pi/OpenCode/Cline binaries for their CLI scenarios || `config` | env precedence, removed-env migration, proxy/timeouts | none || `extensibility` | provider runtime and platform factory construction | none |@@ -113,6 +113,14 @@ $env:FCC_SMOKE_OPENROUTER_FREE_MODELS = "nvidia/nemotron-3-super-120b-a12b:free,uv run pytest smoke/product -n 0 -s --tb=short```+```powershell+$env:FCC_LIVE_SMOKE = "1"+$env:FCC_SMOKE_TARGETS = "cli"+$env:FCC_SMOKE_PROVIDER_MATRIX = "openai"+$env:FCC_SMOKE_MODEL_OPENAI = "gpt-5.6-luna"+uv run pytest smoke/product/test_client_product_live.py -n 0 -s --tb=short -k claude_auto_mode_openai_connected+```+```powershell$env:FCC_LIVE_SMOKE = "1"$env:FCC_SMOKE_TARGETS = "messaging,config,extensibility"diff --git a/smoke/capabilities.py b/smoke/capabilities.pyindex e90253f4..4f8515a9 100644--- a/smoke/capabilities.py+++ b/smoke/capabilities.py@@ -243,6 +243,22 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (),("test_optimization_fast_paths_do_not_need_provider",),),+ CapabilityContract(+ "request_behavior",+ "claude_auto_mode_classifier",+ "claude_auto_mode_classifier",+ "free_claude_code.api.handlers.messages.MessagesHandler",+ "known Claude classifier prompt and its owned stop hint",+ "reasoning disabled and classifier stop hint consumed before provider conversion",+ "unknown prompts and arbitrary stop sequences retain ordinary strict behavior",+ (+ "tests/api/test_detection.py",+ "tests/api/test_api_handlers.py",+ "tests/api/test_openai_codex_compatibility.py",+ "tests/contracts/test_nvidia_nim_cli_matrix.py",+ ),+ ("test_claude_auto_mode_openai_connected_e2e",),+ ),CapabilityContract("request_behavior","token_counting",diff --git a/smoke/features.py b/smoke/features.pyindex 653503ef..2eb1fd09 100644--- a/smoke/features.py+++ b/smoke/features.py@@ -60,6 +60,21 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (),"skip real CLI when binary is absent; configured providers must pass",),+ FeatureCoverage(+ "claude_auto_mode_classifier",+ "Claude Auto mode classifies and executes Bash through OpenAI connected accounts",+ (+ "tests/api/test_detection.py",+ "tests/api/test_api_handlers.py",+ "tests/api/test_openai_codex_compatibility.py",+ "tests/contracts/test_nvidia_nim_cli_matrix.py",+ ),+ ("test_claude_cli_prompt_when_available",),+ ("test_claude_auto_mode_openai_connected_e2e",),+ ("cli",),+ ("Claude CLI", "FCC_SMOKE_MODEL_OPENAI and connected OpenAI account"),+ "skip only before launch when Claude or an explicit OpenAI smoke model is absent",+ ),FeatureCoverage("drop_in_codex_replacement","OpenAI Responses API and Codex CLI adapter route through the proxy",diff --git a/smoke/lib/claude_cli_matrix.py b/smoke/lib/claude_cli_matrix.pyindex ad605e7d..c887f3c4 100644--- a/smoke/lib/claude_cli_matrix.py+++ b/smoke/lib/claude_cli_matrix.py@@ -81,6 +81,7 @@ def run_claude_cli(session_id: str | None = None,resume_session_id: str | None = None,no_session_persistence: bool = True,+ auto_mode: bool = False,) -> ClaudeCliRun:"""Run Claude Code CLI against the local smoke proxy."""cwd.mkdir(parents=True, exist_ok=True)@@ -96,6 +97,7 @@ def run_claude_cli(session_id=session_id,resume_session_id=resume_session_id,no_session_persistence=no_session_persistence,+ auto_mode=auto_mode,))@@ -147,6 +149,7 @@ def _build_claude_cli_command(session_id: str | None = None,resume_session_id: str | None = None,no_session_persistence: bool = True,+ auto_mode: bool = False,) -> tuple[str, ...]:cmd: list[str] = [claude_bin]if bare:@@ -162,8 +165,13 @@ def _build_claude_cli_command("--include-partial-messages","--verbose","--permission-mode",- "bypassPermissions",- "--dangerously-skip-permissions",+ "auto" if auto_mode else "bypassPermissions",+ ]+ )+ if not auto_mode:+ cmd.append("--dangerously-skip-permissions")+ cmd.extend(+ ["--model","sonnet",]@@ -173,7 +181,7 @@ def _build_claude_cli_command(cmd.extend(pre_tool_args)if tools is not None:cmd.extend(["--tools", tools])- if tools:+ if tools and not auto_mode:cmd.extend(["--allowedTools", tools])cmd.extend(extra_args)cmd.extend(["-p", prompt])diff --git a/smoke/product/test_client_product_live.py b/smoke/product/test_client_product_live.pyindex 33734827..9c2b17de 100644--- a/smoke/product/test_client_product_live.py+++ b/smoke/product/test_client_product_live.py@@ -3,6 +3,7 @@ import osimport shutilimport subprocessimport threading+import uuidfrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom http import HTTPStatus@@ -11,6 +12,8 @@ from pathlib import Pathimport pytest+from free_claude_code.core.json_types import JsonObject, JsonValue+from smoke.lib.claude_cli_matrix import run_claude_clifrom smoke.lib.config import SmokeConfigfrom smoke.lib.e2e import (ClientProtocolDriver,@@ -23,6 +26,20 @@ from smoke.lib.e2e import (pytestmark = [pytest.mark.live]+def _json_object_lines(text: str) -> list[JsonObject]:+ objects: list[JsonObject] = []+ for line in text.splitlines():+ if not line.strip():+ continue+ try:+ value: JsonValue = json.loads(line)+ except json.JSONDecodeError:+ continue+ if isinstance(value, dict):+ objects.append(value)+ return objects++@pytest.mark.smoke_target("clients")def test_vscode_protocol_e2e(smoke_config: SmokeConfig) -> None:provider_model = ProviderMatrixDriver(smoke_config).first_model()@@ -285,6 +302,98 @@ def test_claude_cli_adaptive_thinking_e2e(assert "FCC_SMOKE_CLI" in result.stdout[email protected]_target("cli")+def test_claude_auto_mode_openai_connected_e2e(+ smoke_config: SmokeConfig, tmp_path: Path+) -> None:+ claude_bin = shutil.which(smoke_config.claude_bin)+ if not claude_bin:+ pytest.skip(f"missing_env: Claude CLI not found: {smoke_config.claude_bin}")++ provider_models = ProviderMatrixDriver(smoke_config).provider_smoke_models()+ provider_model = next(+ (model for model in provider_models if model.provider == "openai"),+ None,+ )+ if provider_model is None:+ pytest.skip(+ "missing_env: set FCC_SMOKE_MODEL_OPENAI to run the connected-account "+ "Auto-mode smoke"+ )++ marker = f"FCC_SMOKE_AUTO_MODE_{uuid.uuid4().hex}"+ marker_path = tmp_path / "auto-mode-marker.txt"+ marker_path.write_text(marker, encoding="utf-8")+ workspace = tmp_path / "workspace"+ routed_model = provider_model.full_model++ with SmokeServerDriver(+ smoke_config,+ name="product-claude-auto-mode-openai",+ env_overrides={+ "MODEL": routed_model,+ "MODEL_FABLE": routed_model,+ "MODEL_OPUS": routed_model,+ "MODEL_SONNET": routed_model,+ "MODEL_HAIKU": routed_model,+ "MESSAGING_PLATFORM": "none",+ "LOG_LEVEL": "DEBUG",+ "LOG_RAW_API_PAYLOADS": "false",+ "LOG_RAW_SSE_EVENTS": "false",+ },+ ).run() as server:+ run = run_claude_cli(+ claude_bin=claude_bin,+ server=server,+ config=smoke_config,+ cwd=workspace,+ prompt=(+ "Use Bash exactly once to run `cat "+ f'"{marker_path.as_posix()}"`. After the tool succeeds, reply '+ "with exactly the file contents."+ ),+ tools="Bash",+ auto_mode=True,+ )+ server_log = server.log_path.read_text(encoding="utf-8", errors="replace")++ assert run.timed_out is False, run.combined_output+ assert run.returncode == 0, run.combined_output+ cli_events = _json_object_lines(run.stdout)+ assert cli_events, run.stdout+ encoded_events = json.dumps(cli_events, sort_keys=True)+ assert '"type": "tool_use"' in encoded_events+ assert '"name": "Bash"' in encoded_events+ assert '"type": "tool_result"' in encoded_events+ assert marker in encoded_events++ combined_lower = run.combined_output.lower()+ for unexpected in (+ "temporarily unavailable",+ "cannot determine the safety",+ "automode-unavailable",+ "openai responses cannot represent",+ ):+ assert unexpected not in combined_lower++ log_rows = _json_object_lines(server_log)+ policy_rows = [+ row+ for row in log_rows+ if row.get("event") == "free_claude_code.api.route.safety_classifier_policy"+ ]+ assert any(+ row.get("classifier_stop_sequence") == "</severity>"+ and row.get("stop_sequence_removed") is True+ for row in policy_rows+ ), server_log+ message_requests = [+ line for line in server_log.splitlines() if "POST /v1/messages" in line+ ]+ assert len(message_requests) >= 2, server_log+ assert all(" 400 " not in message for message in message_requests), server_log++@pytest.mark.smoke_target("cli")def test_claude_cli_provider_error_e2e(smoke_config: SmokeConfig, tmp_path: Pathdiff --git a/src/free_claude_code/api/detection.py b/src/free_claude_code/api/detection.pyindex 1bac08e4..817a53ac 100644--- a/src/free_claude_code/api/detection.py+++ b/src/free_claude_code/api/detection.py@@ -98,20 +98,27 @@ def is_prefix_detection_request(request_data: MessagesRequest) -> tuple[bool, streturn False, ""-def is_safety_classifier_request(request_data: MessagesRequest) -> bool:- """Return whether this is Claude Code's auto-mode safety classifier prompt."""+def detect_safety_classifier_stop_sequence(+ request_data: MessagesRequest,+) -> str | None:+ """Return the stop hint owned by a known Claude auto-mode classifier."""if request_data.tools:- return False+ return None- system_text = (- extract_text_from_content(request_data.system) if request_data.system else ""- )- messages_text = "".join(- extract_text_from_content(message.content) for message in request_data.messages+ messages_text = "\n".join(+ extract_text_from_content(message.content)+ for message in request_data.messages+ if message.role != "system")- combined = f"{system_text}\n{messages_text}"- has_verdict_instruction = "yes</block>" in combined or "no</block>" in combined- return "<transcript>" in combined and has_verdict_instruction+ if "<transcript>" not in messages_text:+ return None++ system_text = _request_system_text(request_data)+ if "Output <severity>N</severity>" in system_text:+ return "</severity>"+ if "yes</block>" in system_text or "no</block>" in system_text:+ return "</block>"+ return Nonedef is_suggestion_mode_request(request_data: MessagesRequest) -> bool:diff --git a/src/free_claude_code/api/handlers/messages.py b/src/free_claude_code/api/handlers/messages.pyindex 36efaf74..049f24df 100644--- a/src/free_claude_code/api/handlers/messages.py+++ b/src/free_claude_code/api/handlers/messages.py@@ -7,7 +7,7 @@ from dataclasses import dataclass, replacefrom fastapi.responses import JSONResponse, Responsefrom loguru import logger-from free_claude_code.api.detection import is_safety_classifier_request+from free_claude_code.api.detection import detect_safety_classifier_stop_sequencefrom free_claude_code.api.optimization_handlers import try_optimizationsfrom free_claude_code.api.request_errors import (http_status_for_unexpected_api_exception,@@ -270,19 +270,48 @@ class MessagesHandler:def _apply_message_routing_policies(self, routed: RoutedMessagesRequest) -> RoutedMessagesRequest:- if not is_safety_classifier_request(routed.request):+ classifier_stop_sequence = detect_safety_classifier_stop_sequence(+ routed.request+ )+ if classifier_stop_sequence is None:return routed- changed = routed.reasoning.control is not ReasoningControl.OFF++ reasoning_changed = routed.reasoning.control is not ReasoningControl.OFF+ stop_sequences = routed.request.stop_sequences+ remaining_stop_sequences = (+ [+ stop_sequence+ for stop_sequence in stop_sequences+ if stop_sequence != classifier_stop_sequence+ ]+ if stop_sequences is not None+ else None+ )+ stop_sequence_removed = remaining_stop_sequences != stop_sequencestrace_event(stage="routing",- event="free_claude_code.api.optimization.safety_classifier_no_thinking",+ event="free_claude_code.api.route.safety_classifier_policy",source="api",model=routed.resolved.original_model,- changed=changed,+ classifier_stop_sequence=classifier_stop_sequence,+ reasoning_changed=reasoning_changed,+ stop_sequence_removed=stop_sequence_removed,)- if not changed:+ if not reasoning_changed and not stop_sequence_removed:return routed- return replace(routed, reasoning=ReasoningPolicy.off())++ request = routed.request+ if stop_sequence_removed:+ request = request.model_copy(+ update={"stop_sequences": remaining_stop_sequences or None}+ )+ return replace(+ routed,+ request=request,+ reasoning=(+ ReasoningPolicy.off() if reasoning_changed else routed.reasoning+ ),+ )def _run_message_intercepts(self, routed: RoutedMessagesRequestdiff --git a/tests/api/test_api_handlers.py b/tests/api/test_api_handlers.pyindex 456eebbc..6caea988 100644--- a/tests/api/test_api_handlers.py+++ b/tests/api/test_api_handlers.py@@ -24,12 +24,16 @@ from free_claude_code.core.failures import ExecutionFailure, FailureKindfrom free_claude_code.core.openai_responses import OpenAIResponsesRequestfrom free_claude_code.core.reasoning import ReasoningPolicy-_CLASSIFIER_SYSTEM = (+_LEGACY_CLASSIFIER_SYSTEM = ("You are a security monitor. Respond with <block>yes</block> or <block>no</block>.")+_CURRENT_CLASSIFIER_SYSTEM = (+ "Classify the command's safety. Output <severity>N</severity> where N is the "+ "numeric severity."+)_CLASSIFIER_USER = (- "<transcript>\nUser: review the repo\nWebFetch https://example.com: fetch\n"- "</transcript>\n<block> immediately."+ "<transcript>\nUser: review the repo\nBash: inspect the requested file\n"+ "</transcript>")@@ -383,14 +387,25 @@ async def test_messages_handler_stream_false_provider_exception_keeps_status() -@pytest.mark.asyncio-async def test_messages_handler_forces_no_thinking_for_safety_classifier() -> None:+ ("system", "classifier_stop_sequence"),+ [+ (_CURRENT_CLASSIFIER_SYSTEM, "</severity>"),+ (_LEGACY_CLASSIFIER_SYSTEM, "</block>"),+ ],+)+async def test_messages_handler_normalizes_safety_classifier_policy(+ system: str,+ classifier_stop_sequence: str,+) -> None:provider = FakeProvider()handler = MessagesHandler(Settings(), provider_resolver=lambda _: provider)request = MessagesRequest(model="nvidia_nim/test-model",max_tokens=100,stream=True,- system=_CLASSIFIER_SYSTEM,+ system=system,+ stop_sequences=[classifier_stop_sequence],messages=[Message(role="user", content=_CLASSIFIER_USER)],)@@ -402,16 +417,21 @@ async def test_messages_handler_forces_no_thinking_for_safety_classifier() -> Noassert provider.preflight_calls[0][1] == ReasoningPolicy.off()assert provider.stream_kwargs[0]["reasoning"] == ReasoningPolicy.off()assert provider.requests[0].model == "test-model"- assert provider.requests[0].system == _CLASSIFIER_SYSTEM+ assert provider.requests[0].system == system+ assert provider.preflight_calls[0][0].stop_sequences is None+ assert provider.requests[0].stop_sequences is None+ assert request.stop_sequences == [classifier_stop_sequence]assert _trace_events(- trace_mock, "free_claude_code.api.optimization.safety_classifier_no_thinking"+ trace_mock, "free_claude_code.api.route.safety_classifier_policy") == [{"stage": "routing",- "event": "free_claude_code.api.optimization.safety_classifier_no_thinking",+ "event": "free_claude_code.api.route.safety_classifier_policy","source": "api","model": "nvidia_nim/test-model",- "changed": True,+ "classifier_stop_sequence": classifier_stop_sequence,+ "reasoning_changed": True,+ "stop_sequence_removed": True,}]@@ -425,6 +445,7 @@ async def test_messages_handler_preserves_thinking_for_non_classifier() -> None:max_tokens=100,stream=True,system="Explain XML formats.",+ stop_sequences=["</severity>"],messages=[Message(role="user",@@ -443,10 +464,11 @@ async def test_messages_handler_preserves_thinking_for_non_classifier() -> None:assert provider.preflight_calls[0][1] == ReasoningPolicy.provider_default()assert provider.stream_kwargs[0]["reasoning"] == ReasoningPolicy.provider_default()+ assert provider.requests[0].stop_sequences == ["</severity>"]assert (_trace_events(trace_mock,- "free_claude_code.api.optimization.safety_classifier_no_thinking",+ "free_claude_code.api.route.safety_classifier_policy",)== [])@@ -460,7 +482,8 @@ async def test_messages_handler_keeps_existing_no_thinking_for_classifier() -> Nmodel="claude-3-freecc-no-thinking/nvidia_nim/test-model",max_tokens=100,stream=True,- system=_CLASSIFIER_SYSTEM,+ system=_LEGACY_CLASSIFIER_SYSTEM,+ stop_sequences=["</block>"],messages=[Message(role="user", content=_CLASSIFIER_USER)],)@@ -471,19 +494,87 @@ async def test_messages_handler_keeps_existing_no_thinking_for_classifier() -> Nassert provider.preflight_calls[0][1] == ReasoningPolicy.off()assert provider.stream_kwargs[0]["reasoning"] == ReasoningPolicy.off()+ assert provider.requests[0].stop_sequences is None+ assert request.stop_sequences == ["</block>"]assert _trace_events(- trace_mock, "free_claude_code.api.optimization.safety_classifier_no_thinking"+ trace_mock, "free_claude_code.api.route.safety_classifier_policy") == [{"stage": "routing",- "event": "free_claude_code.api.optimization.safety_classifier_no_thinking",+ "event": "free_claude_code.api.route.safety_classifier_policy","source": "api","model": "claude-3-freecc-no-thinking/nvidia_nim/test-model",- "changed": False,+ "classifier_stop_sequence": "</block>",+ "reasoning_changed": False,+ "stop_sequence_removed": True,+ }+ ]+++async def test_messages_handler_forces_no_thinking_without_classifier_stop_hint() -> (+ None+):+ provider = FakeProvider()+ handler = MessagesHandler(Settings(), provider_resolver=lambda _: provider)+ request = MessagesRequest(+ model="nvidia_nim/test-model",+ max_tokens=100,+ stream=True,+ system=_CURRENT_CLASSIFIER_SYSTEM,+ messages=[Message(role="user", content=_CLASSIFIER_USER)],+ )++ with patch("free_claude_code.api.handlers.messages.trace_event") as trace_mock:+ response = await handler.create(request)+ assert isinstance(response, StreamingResponse)+ await _streaming_body_text(response)++ assert provider.preflight_calls[0][1] == ReasoningPolicy.off()+ assert provider.requests[0].stop_sequences is None+ assert _trace_events(+ trace_mock, "free_claude_code.api.route.safety_classifier_policy"+ ) == [+ {+ "stage": "routing",+ "event": "free_claude_code.api.route.safety_classifier_policy",+ "source": "api",+ "model": "nvidia_nim/test-model",+ "classifier_stop_sequence": "</severity>",+ "reasoning_changed": True,+ "stop_sequence_removed": False,}]+async def test_messages_handler_preserves_unowned_classifier_stop_sequences() -> None:+ provider = FakeProvider()+ handler = MessagesHandler(Settings(), provider_resolver=lambda _: provider)+ original_stops = ["custom", "</severity>", "custom", "</severity>", "tail"]+ request = MessagesRequest(+ model="nvidia_nim/test-model",+ max_tokens=100,+ stream=True,+ system=_CURRENT_CLASSIFIER_SYSTEM,+ stop_sequences=original_stops,+ messages=[Message(role="user", content=_CLASSIFIER_USER)],+ )++ response = await handler.create(request)+ assert isinstance(response, StreamingResponse)+ await _streaming_body_text(response)++ assert provider.preflight_calls[0][1] == ReasoningPolicy.off()+ assert provider.preflight_calls[0][0].stop_sequences == [+ "custom",+ "custom",+ "tail",+ ]+ assert provider.requests[0].stop_sequences == ["custom", "custom", "tail"]+ assert request.stop_sequences == original_stops++@pytest.mark.asyncioasync def test_messages_handler_optimization_intercepts_before_provider_execution() -> (None@@ -538,7 +629,7 @@ async def test_responses_handler_does_not_apply_safety_classifier_policy() -> NoOpenAIResponsesRequest(model="nvidia_nim/test-model",input=_CLASSIFIER_USER,- instructions=_CLASSIFIER_SYSTEM,+ instructions=_CURRENT_CLASSIFIER_SYSTEM,))@@ -550,7 +641,7 @@ async def test_responses_handler_does_not_apply_safety_classifier_policy() -> Noassert (_trace_events(trace_mock,- "free_claude_code.api.optimization.safety_classifier_no_thinking",+ "free_claude_code.api.route.safety_classifier_policy",)== [])diff --git a/tests/api/test_detection.py b/tests/api/test_detection.pyindex 3fbfaff0..aad21dca 100644--- a/tests/api/test_detection.py+++ b/tests/api/test_detection.py@@ -2,11 +2,13 @@from unittest.mock import patch+import pytest+from free_claude_code.api.detection import (+ detect_safety_classifier_stop_sequence,is_filepath_extraction_request,is_prefix_detection_request,is_quota_check_request,- is_safety_classifier_request,is_title_generation_request,)from free_claude_code.core.anthropic.models import Message, MessagesRequest@@ -89,45 +91,89 @@ class TestIsPrefixDetectionRequest:assert cmd == ""-class TestIsSafetyClassifierRequest:- _SYSTEM = (+class TestDetectSafetyClassifierStopSequence:+ _LEGACY_SYSTEM = ("You are a security monitor. Respond with <block>yes</block> ""or <block>no</block>.")- _USER = (+ _CURRENT_SYSTEM = (+ "Classify the command's safety. Output <severity>N</severity> where N "+ "is the numeric severity."+ )+ _TRANSCRIPT = ("<transcript>\nUser: review the repo\n"- "WebFetch https://example.com: fetch\n</transcript>\n<block> immediately."+ "Bash: inspect the requested file\n</transcript>")- def test_classifier_request_detected(self):- req = _make_request(self._USER, system=self._SYSTEM)- assert is_safety_classifier_request(req) is True+ @pytest.mark.parametrize(+ ("system", "expected"),+ [+ (_CURRENT_SYSTEM, "</severity>"),+ (_LEGACY_SYSTEM, "</block>"),+ ],+ )+ def test_known_classifier_request_returns_owned_stop_hint(+ self, system: str, expected: str+ ) -> None:+ req = _make_request(self._TRANSCRIPT, system=system)- def test_markers_split_across_system_and_user(self):+ assert detect_safety_classifier_stop_sequence(req) == expected++ def test_inline_system_context_uses_same_detection_path(self) -> None:req = _make_request(- "<transcript>\nWebFetch x\n</transcript>", system=self._SYSTEM+ self._TRANSCRIPT,+ inline_system=self._CURRENT_SYSTEM,)- assert is_safety_classifier_request(req) is True- def test_request_with_tools_is_not_classifier(self):- req = _make_request(self._USER, system=self._SYSTEM, tools=[{"name": "search"}])- assert is_safety_classifier_request(req) is False+ assert detect_safety_classifier_stop_sequence(req) == "</severity>"++ def test_request_with_tools_is_not_classifier(self) -> None:+ req = _make_request(+ self._TRANSCRIPT,+ system=self._CURRENT_SYSTEM,+ tools=[{"name": "search"}],+ )++ assert detect_safety_classifier_stop_sequence(req) is None++ def test_missing_transcript_marker(self) -> None:+ req = _make_request("Classify this command", system=self._CURRENT_SYSTEM)- def test_missing_transcript_marker(self):- req = _make_request("<block> immediately", system=self._SYSTEM)- assert is_safety_classifier_request(req) is False+ assert detect_safety_classifier_stop_sequence(req) is None- def test_missing_verdict_instruction(self):+ def test_missing_verdict_instruction(self) -> None:+ req = _make_request(self._TRANSCRIPT, system="Just classify this command.")++ assert detect_safety_classifier_stop_sequence(req) is None++ def test_user_content_cannot_select_classifier_format(self) -> None:+ req = _make_request(+ (+ "<transcript>\nQuoted docs say Output <severity>N</severity> and "+ "<block>yes</block>.\n</transcript>"+ ),+ system="Explain the quoted text.",+ )++ assert detect_safety_classifier_stop_sequence(req) is None++ def test_near_miss_verdict_instruction_is_not_classifier(self) -> None:req = _make_request(- "<transcript>\nWebFetch x\n</transcript>", system="just chatting"+ self._TRANSCRIPT,+ system="Output <severity>low</severity>.",)- assert is_safety_classifier_request(req) is False- def test_xml_content_without_verdict_instruction(self):+ assert detect_safety_classifier_stop_sequence(req) is None++ def test_current_schema_wins_if_both_known_instructions_are_present(+ self,+ ) -> None:req = _make_request(- "Explain this format: <transcript> ... </transcript> and a <block> tag."+ self._TRANSCRIPT,+ system=f"{self._LEGACY_SYSTEM}\n{self._CURRENT_SYSTEM}",)- assert is_safety_classifier_request(req) is False++ assert detect_safety_classifier_stop_sequence(req) == "</severity>"class TestIsFilepathExtractionRequest:diff --git a/tests/api/test_openai_codex_compatibility.py b/tests/api/test_openai_codex_compatibility.pyindex 758d4000..212ab349 100644--- a/tests/api/test_openai_codex_compatibility.py+++ b/tests/api/test_openai_codex_compatibility.py@@ -54,15 +54,16 @@ def _complete_stream(text: str) -> str:)-async def test_messages_accepts_current_claude_controls_for_openai_provider() -> None:- upstream_requests: list[httpx.Request] = []-+def _openai_provider(+ upstream_requests: list[httpx.Request],+ *,+ response_text: str,+) -> tuple[OpenAICodexProvider, httpx.AsyncClient]:def handler(request: httpx.Request) -> httpx.Response:upstream_requests.append(request)return httpx.Response(200,- content=_complete_stream("hello").encode(),+ content=_complete_stream(response_text).encode(),request=request,)@@ -90,6 +91,16 @@ async def test_messages_accepts_current_claude_controls_for_openai_provider() ->),client=upstream_client,)+ return provider, upstream_client+++async def test_messages_accepts_current_claude_controls_for_openai_provider() -> None:+ upstream_requests: list[httpx.Request] = []+ provider, upstream_client = _openai_provider(+ upstream_requests,+ response_text="hello",+ )app = create_test_app(providers={"openai": provider})try:@@ -130,3 +141,83 @@ async def test_messages_accepts_current_claude_controls_for_openai_provider() ->assert "metadata" not in payloadassert "context_management" not in payloadassert "output_config" not in payload+++async def test_messages_auto_mode_classifier_composes_with_openai_provider() -> None:+ upstream_requests: list[httpx.Request] = []+ provider, upstream_client = _openai_provider(+ upstream_requests,+ response_text="<severity>0</severity>",+ )+ app = create_test_app(providers={"openai": provider})++ try:+ with TestClient(app) as client:+ response = client.post(+ "/v1/messages?beta=true",+ json={+ "model": "openai/gpt-test",+ "max_tokens": 64,+ "system": (+ "Classify the command's safety. "+ "Output <severity>N</severity> where N is the numeric "+ "severity."+ ),+ "messages": [+ {+ "role": "user",+ "content": (+ "<transcript>\nUser: inspect a file\n"+ "Bash: cat the file\n</transcript>"+ ),+ }+ ],+ "stop_sequences": ["</severity>"],+ },+ )+ finally:+ await upstream_client.aclose()++ assert response.status_code == 200+ assert response.headers["content-type"].startswith("application/json")+ body = response.json()+ assert body["content"] == [{"type": "text", "text": "<severity>0</severity>"}]+ assert body["stop_reason"] == "end_turn"+ assert len(upstream_requests) == 1+ payload = json.loads(upstream_requests[0].content)+ assert payload["model"] == "gpt-test"+ assert payload["reasoning"] == {"effort": "none"}+ assert "stop" not in payload+ assert "stop_sequences" not in payload+++async def test_messages_non_classifier_stop_remains_lossy_for_openai_provider() -> None:+ upstream_requests: list[httpx.Request] = []+ provider, upstream_client = _openai_provider(+ upstream_requests,+ response_text="unreachable",+ )+ app = create_test_app(providers={"openai": provider})++ try:+ with TestClient(app) as client:+ response = client.post(+ "/v1/messages",+ json={+ "model": "openai/gpt-test",+ "max_tokens": 64,+ "messages": [{"role": "user", "content": "hello"}],+ "stop_sequences": ["caller-owned-stop"],+ },+ )+ finally:+ await upstream_client.aclose()++ assert response.status_code == 400+ body = response.json()+ assert body["error"]["type"] == "invalid_request_error"+ assert "cannot represent" in body["error"]["message"]+ assert "stop_sequences" in body["error"]["message"]+ assert upstream_requests == []diff --git a/tests/contracts/test_nvidia_nim_cli_matrix.py b/tests/contracts/test_nvidia_nim_cli_matrix.pyindex 3e93ea19..68db1ec5 100644--- a/tests/contracts/test_nvidia_nim_cli_matrix.py+++ b/tests/contracts/test_nvidia_nim_cli_matrix.py@@ -564,6 +564,20 @@ def test_cli_matrix_default_command_uses_bare_mode() -> None:assert "Read" in command+def test_cli_matrix_auto_mode_exposes_tool_without_preapproval() -> None:+ command = _build_claude_cli_command(+ claude_bin="claude",+ prompt="read the marker",+ tools="Bash",+ auto_mode=True,+ )++ assert command[command.index("--permission-mode") + 1] == "auto"+ assert command[command.index("--tools") + 1] == "Bash"+ assert "--dangerously-skip-permissions" not in command+ assert "--allowedTools" not in command++def test_cli_matrix_subagent_command_uses_agent_without_bare_or_task() -> None:bare, tools, pre_tool_args, extra_args = _subagent_probe_options("{}")command = _build_claude_cli_command(diff --git a/uv.lock b/uv.lockindex 84593688..c6d89c0d 100644--- a/uv.lock+++ b/uv.lock@@ -607,7 +607,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "5.6.1"+version = "5.6.2"source = { editable = "." }dependencies = [{ name = "aiohttp" },