From 82f1768abe36670a548951e59aeaea47af7dcfc8 Mon Sep 17 00:00:00 2001 From: Dustin Washington Date: Sat, 28 Nov 2026 14:30:40 -0500 Subject: [PATCH 1/5] #762: Add unified strict schema to provider adapters --- cecli/helpers/llms/litellm_compat.py | 6 + cecli/helpers/llms/pipeline.py | 6 +- cecli/helpers/llms/providers/base.py | 137 ++++++++++++-- cecli/helpers/llms/providers/groq.py | 21 ++- cecli/helpers/llms/providers/mistral.py | 74 +------- tests/helpers/test_llms_groq_provider.py | 197 ++++++++++++++++++++ tests/helpers/test_llms_mistral_provider.py | 9 + tests/helpers/test_llms_strict_schema.py | 140 ++++++++++++++ 8 files changed, 504 insertions(+), 86 deletions(-) create mode 100644 tests/helpers/test_llms_strict_schema.py diff --git a/cecli/helpers/llms/litellm_compat.py b/cecli/helpers/llms/litellm_compat.py index cb6c4b638a3..fba164344d3 100644 --- a/cecli/helpers/llms/litellm_compat.py +++ b/cecli/helpers/llms/litellm_compat.py @@ -529,6 +529,12 @@ def _translate_http_error(err: httpx.HTTPStatusError) -> _FacadeException: message=message, status_code=status, response=err.response ) + if status == 400: + # litellm maps 400 to BadRequestError (non-retryable). Replaying an + # invalid body cannot succeed, so do not burn the retry budget on it + # (e.g. Groq's "property ... is unsupported" invalid_request_error). + return BadRequestError(message=message, status_code=status, response=err.response) + if status in (401, 403): return AuthenticationError(message=message, status_code=status, response=err.response) diff --git a/cecli/helpers/llms/pipeline.py b/cecli/helpers/llms/pipeline.py index a36da85490a..be33dfb1110 100644 --- a/cecli/helpers/llms/pipeline.py +++ b/cecli/helpers/llms/pipeline.py @@ -80,13 +80,13 @@ async def acompletion( headers = provider.build_headers(resolved, key, family, headers) # Allow the provider adapter to transform the outgoing message body before - # dispatch (e.g. Mistral's strict schema rejects reasoning_content / - # provider_specific_fields / function_call and a null tool-call index). + # dispatch. The family is passed so strict-schema sanitization only applies + # to chat-family (OpenAI /chat/completions) requests. # The chat payload echoes prior-turn reasoning_content back for providers # that require it (DeepSeek thinking mode); strict providers opt out here so # the coercer cannot re-inject a field the transform just stripped. resolved["_echo_reasoning_content"] = getattr(provider, "echoes_reasoning_content", True) - messages = provider.transform_messages(messages) + messages = provider.transform_messages(messages, family) messages = _null_content_to_empty(messages) if stream: diff --git a/cecli/helpers/llms/providers/base.py b/cecli/helpers/llms/providers/base.py index ae13c308ff5..4d12bc59905 100644 --- a/cecli/helpers/llms/providers/base.py +++ b/cecli/helpers/llms/providers/base.py @@ -8,7 +8,33 @@ from __future__ import annotations -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List, Optional, Tuple + +#: Message fields accepted by the OpenAI chat-completions request schema, per +#: role. Providers with a strict validator set ``strict_schema = True`` to drop +#: every other field. Values are the OpenAI spec's ChatCompletionRequest*Message +#: properties (plus the deprecated ``function`` role). +OPENAI_CHAT_MESSAGE_FIELDS: Dict[str, Tuple[str, ...]] = { + "developer": ("role", "content", "name"), + "system": ("role", "content", "name"), + "user": ("role", "content", "name"), + "assistant": ( + "role", + "content", + "name", + "refusal", + "audio", + "tool_calls", + "function_call", + ), + "tool": ("role", "content", "tool_call_id"), + "function": ("role", "content", "name"), +} + +#: Fields accepted on an OpenAI chat tool call and its nested payloads. +OPENAI_CHAT_TOOL_CALL_FIELDS: Tuple[str, ...] = ("id", "type", "function", "custom") +OPENAI_CHAT_FUNCTION_FIELDS: Tuple[str, ...] = ("name", "arguments") +OPENAI_CHAT_CUSTOM_TOOL_FIELDS: Tuple[str, ...] = ("name", "input") class ProviderAdapter: @@ -20,10 +46,10 @@ class ProviderAdapter: authenticated session's ``endpoints.api``). - :meth:`resolve_api_key` - key source (env, auth cache, oauth refresh). - :meth:`build_headers` - auth scheme + provider-specific headers. - - :meth:`transform_messages` - transform the outgoing message body to - normalize fields a stricter provider rejects (e.g. Mistral rejects - ``reasoning_content`` / ``provider_specific_fields`` / ``function_call`` and - a null tool-call ``index``). + - :meth:`transform_messages` - transform the outgoing message body. Set + ``strict_schema`` to strip chat requests down to the OpenAI + chat-completions field set; ``unsupported_message_fields`` adds fields + OpenAI allows but the provider still rejects. - :meth:`chat_url` / :meth:`chat_payload` / :meth:`chat_stream_json` / :meth:`parse_chat_response` / :meth:`parse_chat_chunk` - override the shared chat-family wire (e.g. Ollama's native ``/api/chat``). @@ -36,13 +62,22 @@ class ProviderAdapter: #: Whether prior-turn ``reasoning_content`` must be echoed back on assistant #: messages (DeepSeek thinking mode). Strict providers that reject the field - #: (Mistral) set this False so the chat payload's coercer skips them. + #: (Mistral / Groq) set this False so the chat payload's coercer skips them. echoes_reasoning_content: bool = True #: Whether OPENAI_API_BASE/OPENAI_API_KEY may redirect this provider's chat #: request (see domains/chat.py). Native wires (Ollama) opt out. honors_openai_env_override: bool = True + #: Strip outgoing chat messages to the OpenAI chat-completions schema. + #: Only applies to the ``chat`` family (the OpenAI /chat/completions wire); + #: models routed through responses/messages/gemini/etc. are untouched. + strict_schema: bool = False + + #: Extra message fields to drop even though OpenAI's schema accepts them + #: (e.g. Groq rejects ``refusal`` and ``audio``). + unsupported_message_fields: Tuple[str, ...] = () + def resolve_api_base(self, resolved: Dict[str, Any]) -> str: """Return the api_base for a resolved config (default: as resolved).""" return resolved["api_base"] @@ -69,16 +104,19 @@ def build_headers( merged.setdefault("Content-Type", "application/json") return merged - def transform_messages(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: - """Transform the outgoing message body to normalize provider-specific fields. + def transform_messages( + self, messages: List[Dict[str, Any]], family: str = "chat" + ) -> List[Dict[str, Any]]: + """Transform outgoing messages for ``family`` (default: no-op). - The default is a no-op. Providers with a stricter request schema override - this to strip fields the generic OpenAI-compatible wire tolerates but the - provider rejects (e.g. Mistral rejects ``reasoning_content`` / - ``provider_specific_fields`` / ``function_call`` on assistant turns, and a - null tool-call ``index``). + Providers that set ``strict_schema`` get their chat messages reduced to + the OpenAI chat-completions field set. The transform is chat-only: other + families use different schemas and are returned untouched. """ - return messages + if not self.strict_schema or family != "chat": + return messages + + return self._strip_to_openai_chat_schema(messages) def chat_url(self, resolved: Dict[str, Any], base: str) -> str: """Return the chat endpoint URL (default: OpenAI ``/chat/completions``).""" @@ -124,5 +162,76 @@ def normalize( """Post-process a normalized response (default: no-op).""" return data + def _strip_to_openai_chat_schema(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """Drop fields outside the OpenAI chat request schema.""" + changed = False + out: List[Dict[str, Any]] = [] + + for msg in messages: + cleaned = self._clean_message(msg) + + if cleaned is not None: + out.append(cleaned) + changed = True + else: + out.append(msg) + + return out if changed else messages + + def _clean_message(self, msg: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """Return a schema-clean copy of ``msg``, or ``None`` when unchanged.""" + if not isinstance(msg, dict): + return None + + allowed = OPENAI_CHAT_MESSAGE_FIELDS.get(msg.get("role")) + + if allowed is None: + return None + + cleaned = {key: msg[key] for key in allowed if key in msg} + changed = cleaned != msg + + for key in self.unsupported_message_fields: + if key in cleaned: + cleaned.pop(key) + changed = True + + for key in ("tool_calls", "function_call"): + if key in cleaned and cleaned[key] is None: + cleaned.pop(key) + changed = True + + tool_calls = cleaned.get("tool_calls") + + if isinstance(tool_calls, list): + cleaned_calls = [self._clean_tool_call(tc) for tc in tool_calls] + + if cleaned_calls != tool_calls: + cleaned["tool_calls"] = cleaned_calls + changed = True + + return cleaned if changed else None + + def _clean_tool_call(self, tc: Any) -> Any: + """Keep only the OpenAI tool-call properties.""" + if not isinstance(tc, dict): + return tc + + cleaned = {key: tc[key] for key in OPENAI_CHAT_TOOL_CALL_FIELDS if key in tc} + function = tc.get("function") + custom = tc.get("custom") + + if isinstance(function, dict): + cleaned["function"] = { + key: function[key] for key in OPENAI_CHAT_FUNCTION_FIELDS if key in function + } + + if isinstance(custom, dict): + cleaned["custom"] = { + key: custom[key] for key in OPENAI_CHAT_CUSTOM_TOOL_FIELDS if key in custom + } + + return cleaned if cleaned != tc else tc + __all__ = ["ProviderAdapter"] diff --git a/cecli/helpers/llms/providers/groq.py b/cecli/helpers/llms/providers/groq.py index 72d6f180438..ac74d841159 100644 --- a/cecli/helpers/llms/providers/groq.py +++ b/cecli/helpers/llms/providers/groq.py @@ -1,23 +1,34 @@ """Groq provider adapter for the llms package. Groq speaks OpenAI-compatible /v1/chat/completions with Bearer auth, but its -endpoint validates the request body strictly and rejects unknown properties. -Groq has no prompt-cache key parameter, so this adapter strips the -``prompt_cache_key`` the shared chat payload builder would otherwise forward. +endpoint validates the request body strictly. This adapter opts into the base +``strict_schema`` sanitizer (the OpenAI chat-completions message schema), +adds Groq-specific rejects that OpenAI allows (``refusal`` / ``audio``), and +removes the ``prompt_cache_key`` the shared builder would otherwise forward. +Groq returns reasoning in ``message.reasoning``, not ``reasoning_content``. """ from __future__ import annotations -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List, Optional, Tuple from .base import ProviderAdapter class GroqProvider(ProviderAdapter): - """Groq: Bearer auth + strict chat body without ``prompt_cache_key``.""" + """Groq: Bearer auth + strict OpenAI chat schema (chat family only).""" provider: str = "groq" + strict_schema: bool = True + + #: Groq rejects these even though OpenAI's chat schema allows them. + unsupported_message_fields: Tuple[str, ...] = ("refusal", "audio") + + #: Groq rejects ``reasoning_content`` on replayed assistant turns (and the + #: chat payload would otherwise inject it), so opt out of the echo. + echoes_reasoning_content: bool = False + def chat_payload( self, resolved: Dict[str, Any], diff --git a/cecli/helpers/llms/providers/mistral.py b/cecli/helpers/llms/providers/mistral.py index b6c91159d1a..040344b6be8 100644 --- a/cecli/helpers/llms/providers/mistral.py +++ b/cecli/helpers/llms/providers/mistral.py @@ -2,15 +2,9 @@ Mistral speaks OpenAI-compatible /v1/chat/completions with Bearer auth, but its request body is validated by a strict Pydantic schema that rejects fields the -generic OpenAI-compatible wire tolerates. Assistant turns built by cecli carry -``reasoning_content`` and ``provider_specific_fields`` on the message, a null -``function_call`` left behind by the legacy wire, and ``provider_specific_fields`` -plus a null ``index`` on tool calls (a streaming artifact); Mistral rejects -each of these with a 422 on the relevant ``messages[i]`` path. - -This adapter iterates over the message body before dispatch and strips those -fields, leaving tool calls in the request wire shape (``id`` / ``type`` / -``function``). +generic OpenAI-compatible wire tolerates. This adapter opts into the base +``strict_schema`` sanitizer (chat family only) and additionally drops +``function_call``, which OpenAI's schema allows but Mistral rejects. On the response side Mistral streams ``content`` as a list of typed parts (``thinking`` / ``text``); :meth:`normalize` flattens those into the generic @@ -19,36 +13,24 @@ from __future__ import annotations -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Tuple from ..types import CompletionChunk, CompletionResponse from .base import ProviderAdapter class MistralProvider(ProviderAdapter): - """Mistral: Bearer auth (default) + strict message-body sanitization.""" + """Mistral: Bearer auth + strict OpenAI chat schema (chat family only).""" provider: str = "mistral" - #: Mistral rejects ``reasoning_content`` on assistant turns (see - #: :meth:`transform_messages`), so the chat payload must not inject it. - echoes_reasoning_content: bool = False - - def transform_messages(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: - """Strip fields Mistral's strict chat-completions schema rejects.""" - changed = False - out: List[Dict[str, Any]] = [] + strict_schema: bool = True - for msg in messages: - cleaned = self._clean_message(msg) + #: Mistral rejects this even though OpenAI's chat schema allows it. + unsupported_message_fields: Tuple[str, ...] = ("function_call",) - if cleaned is not None: - out.append(cleaned) - changed = True - else: - out.append(msg) - - return out if changed else messages + #: The chat payload must not inject prior-turn ``reasoning_content``. + echoes_reasoning_content: bool = False def normalize(self, family: str, data: Any, resolved: Dict[str, Any]) -> Any: """Flatten Mistral's typed content parts into the generic shape. @@ -71,42 +53,6 @@ def normalize(self, family: str, data: Any, resolved: Dict[str, Any]) -> Any: return data - def _clean_message(self, msg: Dict[str, Any]) -> Optional[Dict[str, Any]]: - """Return a sanitized copy of ``msg``, or ``None`` when unchanged.""" - tool_calls = msg.get("tool_calls") - needs_tool_fix = any( - isinstance(tc, dict) and ("index" in tc or "provider_specific_fields" in tc) - for tc in tool_calls or [] - ) - - if ( - "reasoning_content" not in msg - and "provider_specific_fields" not in msg - and "function_call" not in msg - and not needs_tool_fix - ): - return None - - cleaned = dict(msg) - cleaned.pop("reasoning_content", None) - cleaned.pop("provider_specific_fields", None) - cleaned.pop("function_call", None) - - if tool_calls: - cleaned["tool_calls"] = [self._clean_tool_call(tc) for tc in tool_calls] - - return cleaned - - def _clean_tool_call(self, tc: Any) -> Any: - """Drop streaming-only fields from a tool call.""" - if not isinstance(tc, dict): - return tc - - cleaned = dict(tc) - cleaned.pop("index", None) - cleaned.pop("provider_specific_fields", None) - return cleaned - def _normalize_chunk(self, chunk: CompletionChunk) -> CompletionChunk: """Flatten a streamed chunk's typed ``content`` parts.""" text, reasoning = self._split_content(chunk.text) diff --git a/tests/helpers/test_llms_groq_provider.py b/tests/helpers/test_llms_groq_provider.py index 3930bc493c8..43840074a11 100644 --- a/tests/helpers/test_llms_groq_provider.py +++ b/tests/helpers/test_llms_groq_provider.py @@ -116,3 +116,200 @@ def test_pipeline_groq_request_body_omits_prompt_cache_key(monkeypatch): assert "prompt_cache_key" not in body assert body["model"] == "openai/gpt-oss-120b" assert client.calls[0]["url"] == "https://api.groq.com/openai/v1/chat/completions" + + +def test_transform_strips_unsupported_message_fields(): + provider = GroqProvider() + messages = [ + { + "role": "system", + "content": "sys", + "provider_specific_fields": {"anthropic": []}, + }, + { + "role": "user", + "content": "hi", + "reasoning_content": "", + }, + { + "role": "assistant", + "content": "hello", + "reasoning_content": "thinking", + "provider_specific_fields": {}, + "reasoning_redacted": True, + "refusal": None, + "audio": None, + "thinking": None, + "reasoning_details": [], + "logprobs": None, + }, + { + "role": "tool", + "tool_call_id": "call_1", + "content": "{}", + "provider_specific_fields": {}, + }, + ] + + cleaned = provider.transform_messages(messages) + + for msg in cleaned: + assert "reasoning_content" not in msg + assert "provider_specific_fields" not in msg + assert "reasoning_redacted" not in msg + assert "refusal" not in msg + assert "audio" not in msg + assert "thinking" not in msg + assert "reasoning_details" not in msg + assert "logprobs" not in msg + + assert cleaned[2]["content"] == "hello" + assert cleaned[3]["tool_call_id"] == "call_1" + + +def test_transform_drops_null_tool_calls_and_function_call(): + provider = GroqProvider() + messages = [ + { + "role": "assistant", + "content": "hello", + "tool_calls": None, + "function_call": None, + } + ] + + cleaned = provider.transform_messages(messages) + + assert "tool_calls" not in cleaned[0] + assert "function_call" not in cleaned[0] + assert cleaned[0]["content"] == "hello" + + +def test_transform_strips_extra_tool_call_properties(): + provider = GroqProvider() + messages = [ + { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "index": 0, + "provider_specific_fields": {}, + "function": { + "name": "get", + "arguments": "{}", + "provider_specific_fields": {}, + }, + } + ], + } + ] + + cleaned = provider.transform_messages(messages) + tool_call = cleaned[0]["tool_calls"][0] + + assert tool_call == { + "id": "call_1", + "type": "function", + "function": {"name": "get", "arguments": "{}"}, + } + + +def test_groq_does_not_echo_reasoning_content(): + assert GroqProvider().echoes_reasoning_content is False + + +def test_pipeline_groq_second_turn_strips_replayed_fields(monkeypatch): + import asyncio + + import cecli.helpers.llms.domains.chat as chat_domain + from cecli.helpers.llms import pipeline + + client = _FakeClient() + monkeypatch.setattr(chat_domain, "make_client", lambda *a, **k: client) + monkeypatch.setenv("GROQ_API_KEY", "gsk-test") + + original_resolve = pipeline.resolve_model_config + + def resolve_with_reasoning(model): + resolved = original_resolve(model) + resolved["api_block"] = {"reasoning_effort": "high"} + return resolved + + monkeypatch.setattr(pipeline, "resolve_model_config", resolve_with_reasoning) + + messages = [ + {"role": "user", "content": "hi"}, + { + "role": "assistant", + "content": "hello", + "reasoning_content": "thinking", + "provider_specific_fields": {}, + "tool_calls": None, + "function_call": None, + }, + {"role": "user", "content": "again"}, + ] + + asyncio.run( + pipeline.acompletion( + model="groq/openai/gpt-oss-120b", + messages=messages, + ) + ) + + sent = client.calls[0]["json"]["messages"] + assistant = sent[1] + + assert "reasoning_content" not in assistant + assert "provider_specific_fields" not in assistant + assert "tool_calls" not in assistant + assert "function_call" not in assistant + assert assistant["content"] == "hello" + + +def test_http_400_is_non_retryable_bad_request(): + import httpx + + from cecli.exceptions import LiteLLMExceptions + from cecli.helpers.llms.litellm_compat import BadRequestError, _translate_http_error + + request = httpx.Request("POST", "https://api.groq.com/openai/v1/chat/completions") + response = httpx.Response( + 400, + request=request, + json={ + "error": { + "message": "property 'reasoning_content' is unsupported", + "type": "invalid_request_error", + } + }, + ) + err = httpx.HTTPStatusError("bad request", request=request, response=response) + + translated = _translate_http_error(err) + + assert isinstance(translated, BadRequestError) + assert translated.status_code == 400 + assert LiteLLMExceptions().get_ex_info(translated).retry is False + + +def test_http_400_context_error_remains_context_window(): + import httpx + + from cecli.helpers.llms.litellm_compat import ( + ContextWindowExceededError, + _translate_http_error, + ) + + request = httpx.Request("POST", "https://api.groq.com/openai/v1/chat/completions") + response = httpx.Response( + 400, + request=request, + json={"error": {"message": "maximum context length exceeded"}}, + ) + err = httpx.HTTPStatusError("bad request", request=request, response=response) + + assert isinstance(_translate_http_error(err), ContextWindowExceededError) diff --git a/tests/helpers/test_llms_mistral_provider.py b/tests/helpers/test_llms_mistral_provider.py index c6ef5c07658..a8bd24ffee6 100644 --- a/tests/helpers/test_llms_mistral_provider.py +++ b/tests/helpers/test_llms_mistral_provider.py @@ -92,6 +92,15 @@ def test_non_chat_family_is_untouched(): assert MistralProvider().normalize("responses", chunk, {}) is chunk +def test_non_list_content_is_ignored(): + chunk = CompletionChunk(text=None) + + normalized = MistralProvider().normalize("chat", chunk, {}) + + assert normalized.text == "" + assert normalized.reasoning == "" + + def test_mistral_does_not_echo_reasoning_content(): assert MistralProvider().echoes_reasoning_content is False diff --git a/tests/helpers/test_llms_strict_schema.py b/tests/helpers/test_llms_strict_schema.py new file mode 100644 index 00000000000..2ec0155c7db --- /dev/null +++ b/tests/helpers/test_llms_strict_schema.py @@ -0,0 +1,140 @@ +"""Tests for the ProviderAdapter strict chat-schema sanitizer.""" + +from cecli.helpers.llms.providers import ProviderAdapter +from cecli.helpers.llms.providers.groq import GroqProvider +from cecli.helpers.llms.providers.mistral import MistralProvider + + +class _StrictProvider(ProviderAdapter): + provider = "strict-test" + strict_schema = True + + +class _CompatStrictProvider(_StrictProvider): + unsupported_message_fields = ("refusal", "audio") + + +def test_strips_messages_to_openai_chat_schema(): + messages = [ + {"role": "system", "content": "sys", "cache_control": {"type": "ephemeral"}}, + {"role": "developer", "content": "dev", "extra": 1}, + {"role": "user", "content": "hi", "reasoning_content": ""}, + { + "role": "assistant", + "content": "hello", + "name": "assistant-name", + "refusal": None, + "audio": None, + "reasoning_content": "thinking", + "provider_specific_fields": {"x": 1}, + "reasoning": "why", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "index": 0, + "provider_specific_fields": {}, + "function": { + "name": "get", + "arguments": "{}", + "provider_specific_fields": {}, + }, + } + ], + "function_call": None, + }, + {"role": "tool", "tool_call_id": "call_1", "content": "{}", "name": "tool"}, + {"role": "function", "name": "legacy", "content": "{}", "extra": 1}, + ] + + cleaned = _StrictProvider().transform_messages(messages) + + assert cleaned[0] == {"role": "system", "content": "sys"} + assert cleaned[1] == {"role": "developer", "content": "dev"} + assert cleaned[2] == {"role": "user", "content": "hi"} + assert cleaned[3] == { + "role": "assistant", + "content": "hello", + "name": "assistant-name", + "refusal": None, + "audio": None, + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": {"name": "get", "arguments": "{}"}, + } + ], + } + assert cleaned[4] == {"role": "tool", "tool_call_id": "call_1", "content": "{}"} + assert cleaned[5] == {"role": "function", "name": "legacy", "content": "{}"} + + +def test_provider_extra_unsupported_fields_are_dropped(): + messages = [ + { + "role": "assistant", + "content": "hello", + "refusal": "no", + "audio": {"id": "audio_1"}, + "name": "kept", + } + ] + + cleaned = _CompatStrictProvider().transform_messages(messages) + + assert cleaned[0] == {"role": "assistant", "content": "hello", "name": "kept"} + + +def test_strict_schema_is_chat_family_only(): + provider = _StrictProvider() + messages = [{"role": "assistant", "content": "hi", "reasoning_content": "x"}] + + for family in ("responses", "messages", "gemini", "bedrock", "interactions"): + assert provider.transform_messages(messages, family) is messages + + assert provider.transform_messages(messages, "chat") is not messages + + +def test_strict_schema_does_not_mutate_input(): + provider = _StrictProvider() + messages = [{"role": "assistant", "content": "hi", "reasoning_content": "x"}] + + cleaned = provider.transform_messages(messages) + + assert cleaned is not messages + assert messages[0]["reasoning_content"] == "x" + + +def test_custom_tool_call_is_kept_to_schema(): + messages = [ + { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": "call_1", + "type": "custom", + "custom": {"name": "shell", "input": "ls", "extra": 1}, + } + ], + } + ] + + cleaned = _StrictProvider().transform_messages(messages) + + assert cleaned[0]["tool_calls"] == [ + { + "id": "call_1", + "type": "custom", + "custom": {"name": "shell", "input": "ls"}, + } + ] + + +def test_groq_and_mistral_opt_into_strict_schema(): + assert GroqProvider.strict_schema is True + assert GroqProvider.unsupported_message_fields == ("refusal", "audio") + assert MistralProvider.strict_schema is True + assert MistralProvider.unsupported_message_fields == ("function_call",) + assert ProviderAdapter.strict_schema is False From 5ab83023bc76dae44fce9c090598be97edbc8ec3 Mon Sep 17 00:00:00 2001 From: Dustin Washington Date: Sat, 28 Nov 2026 15:07:20 -0500 Subject: [PATCH 2/5] Reasoning only responses should reflect, small structural updates --- cecli/coders/agent_coder.py | 30 +++++- cecli/coders/architect_coder.py | 4 +- cecli/coders/base_coder.py | 99 ++++++++++--------- cecli/coders/context_coder.py | 2 +- tests/basic/test_coder.py | 2 +- tests/basic/test_empty_response.py | 4 +- .../test_agent_coder_reply_completed.py | 69 +++++++++++++ 7 files changed, 153 insertions(+), 57 deletions(-) create mode 100644 tests/coders/test_agent_coder_reply_completed.py diff --git a/cecli/coders/agent_coder.py b/cecli/coders/agent_coder.py index 0806f615dfa..bc80fea41ad 100644 --- a/cecli/coders/agent_coder.py +++ b/cecli/coders/agent_coder.py @@ -1083,6 +1083,11 @@ async def reply_completed(self): Tool extraction and execution is now handled in BaseCoder.consolidate_chunks and BaseCoder.process_tool_calls respectively. + + Returns: + True when the turn is complete and no further work is needed. + False when the turn is not complete; ``reflected_message`` has been + set so the caller starts another turn. """ content = self.partial_response_content tool_calls_found = bool(self.partial_response_tool_calls) @@ -1096,7 +1101,7 @@ async def reply_completed(self): if self.files_edited_by_tools: _ = await self.auto_commit(self.files_edited_by_tools) - return False + return True # 2. Check for unfinished and recently finished background commands background_commands = BackgroundCommandManager.list_background_commands() @@ -1118,6 +1123,7 @@ async def reply_completed(self): for cmd_key, cmd_info in background_commands.items() if not cmd_info.get("running", False) and cmd_info.get("end_time") + and cmd_info.get("consumed_at") is None and (current_time - cmd_info["end_time"]) < command_timeout * 4 ] @@ -1140,16 +1146,30 @@ async def reply_completed(self): # stays inside the worker loop and re-prompts, matching the # lint interrupt path above. raise asyncio.CancelledError("Interrupted while waiting for background commands") - return True + return False # Check for recently finished commands that need reflection if recently_finished_commands and not self.agent_finished: - return True # Retrigger reflection to process recently finished command outputs + self.reflected_message = True + return False # 3. If no content and no tools, we might be done or just empty response if (not content or not content.strip()) and not tool_calls_found: + if ( + self.is_meaningful_reasoning(self.partial_response_reasoning_content) + and self.num_reflections < self.max_reflections + ): + self.reflected_message = wrap_context( + "empty_response", + "You produced reasoning but no visible reply and no tool calls." + " Continue by replying to the user with your answer or calling the" + " appropriate tool.", + ) + return False + if len(self.tool_usage_history) > self.tool_usage_retries: self.tool_usage_history = [] + return True # 4. If we have called no tools (e.g. the first message) @@ -1164,7 +1184,7 @@ async def reply_completed(self): "yield_check", "No tools called, did you mean to yield? If not, please continue with your task.", ) - return True + return False if tool_calls_found and self.num_reflections < self.max_reflections: self.tool_call_count = 0 @@ -1199,7 +1219,7 @@ async def reply_completed(self): self.tool_call_count = 0 self.files_added_in_exploration = set() self.files_edited_by_tools = set() - return False + return True async def hot_reload(self): if self.hot_reload_enabled: diff --git a/cecli/coders/architect_coder.py b/cecli/coders/architect_coder.py index f116c56c839..052add6d974 100644 --- a/cecli/coders/architect_coder.py +++ b/cecli/coders/architect_coder.py @@ -15,7 +15,7 @@ async def reply_completed(self): content = self.partial_response_content if not content or not content.strip(): - return + return True tweak_responses = getattr(self.args, "tweak_responses", False) confirmation = await self.io.confirm_ask( @@ -25,7 +25,7 @@ async def reply_completed(self): ) if not confirmation: - return + return True if confirmation == "tweak": if self.tui and self.tui(): diff --git a/cecli/coders/base_coder.py b/cecli/coders/base_coder.py index 66bf8cd2837..c66b587b9be 100755 --- a/cecli/coders/base_coder.py +++ b/cecli/coders/base_coder.py @@ -3657,9 +3657,11 @@ async def add_assistant_reply_to_cur_messages(self): msg = response_dict["choices"][0]["message"] if self.partial_response_tool_calls: - msg["tool_calls"] = [_tool_call_to_dict(tc) for tc in self.partial_response_tool_calls] + msg["tool_calls"] = [ + self._tool_call_to_dict(tc) for tc in self.partial_response_tool_calls + ] elif self.partial_response_function_call: - msg["function_call"] = _function_call_to_dict(self.partial_response_function_call) + msg["function_call"] = self._function_call_to_dict(self.partial_response_function_call) if "reasoning_content" not in msg: msg["reasoning_content"] = self.partial_response_reasoning_content @@ -3966,7 +3968,7 @@ async def show_send_output(self, completion): if ( not len(self.partial_response_content) and not len(self.partial_response_tool_calls) - and not _is_meaningful_reasoning(self.partial_response_reasoning_content) + and not self.is_meaningful_reasoning(self.partial_response_reasoning_content) ): self.empty_response = True return @@ -4098,7 +4100,7 @@ async def show_send_output_stream(self, completion): text += reasoning_content self.got_reasoning_content = True - if _is_meaningful_reasoning(reasoning_content): + if self.is_meaningful_reasoning(reasoning_content): received_content = True self.token_profiler.on_token() @@ -4186,7 +4188,7 @@ async def show_send_output_stream(self, completion): if ( not received_content and len(self.partial_response_tool_calls) == 0 - and not _is_meaningful_reasoning(self.partial_response_reasoning_content) + and not self.is_meaningful_reasoning(self.partial_response_reasoning_content) ): self.empty_response = True return @@ -4524,7 +4526,7 @@ def calculate_and_show_tokens_and_cost(self, messages, completion=None, model=No completion_tokens = ( nested.getter(usage, ["completion_tokens", "output_tokens", "eval_count"], 0) or 0 ) - cache_hit_tokens = _first_usage_tokens( + cache_hit_tokens = self._first_usage_tokens( usage, [ "prompt_cache_hit_tokens", @@ -4650,7 +4652,7 @@ def record_background_usage_and_cost(self, messages, completion=None, model=None completion_tokens = ( nested.getter(usage, ["completion_tokens", "output_tokens", "eval_count"], 0) or 0 ) - cache_hit_tokens = _first_usage_tokens( + cache_hit_tokens = self._first_usage_tokens( usage, [ "prompt_cache_hit_tokens", @@ -5342,49 +5344,52 @@ def format_command_with_prefix(self, command): # Append the command to the prefix with a space return f"{command_prefix} {command}" + @staticmethod + def is_meaningful_reasoning(text): + """Return True if reasoning text contains at least one alphanumeric character. + + Some providers (e.g. moonshotai/kimi-k3) occasionally return completions + with empty ``content`` and a ``reasoning_content`` made entirely of + punctuation (e.g. ``"!!!!"``). Those responses are effectively empty, so + the empty-response detector only lets reasoning count as response + content when it holds at least one alphanumeric character. + """ + return bool(text) and any(ch.isalnum() for ch in text) -def _tool_call_to_dict(tc): - """Normalize a tool call (dict or litellm-shaped object) to a wire-format dict.""" - if isinstance(tc, dict): - return tc + @staticmethod + def _tool_call_to_dict(tc): + """Normalize a tool call (dict or litellm-shaped object) to a wire-format dict.""" + if isinstance(tc, dict): + return tc - if hasattr(tc, "to_dict"): - return tc.to_dict() + if hasattr(tc, "to_dict"): + return tc.to_dict() - return tc + return tc + @staticmethod + def _function_call_to_dict(function_call): + """Normalize a function call (dict or litellm-shaped Function) to a dict.""" + if isinstance(function_call, dict): + return function_call + + if hasattr(function_call, "to_dict"): + return function_call.to_dict() -def _function_call_to_dict(function_call): - """Normalize a function call (dict or litellm-shaped Function) to a dict.""" - if isinstance(function_call, dict): return function_call - if hasattr(function_call, "to_dict"): - return function_call.to_dict() - return function_call - - -def _first_usage_tokens(usage: object, paths: list[str], default: int = 0) -> int: - """Return the first non-None token count among ``paths``. - - ``nested.getter`` stops at the first attribute that exists even when its value - is None. Anthropic/copilot ``Usage`` always declares ``prompt_cache_hit_tokens`` - (None) and populates ``cache_read_input_tokens``, so looking only at the first - field would report zero cache hits despite the server serving the cached prefix. - """ - for path in paths: - value = nested.getter(usage, path, None) - if value is not None: - return value - return default - - -def _is_meaningful_reasoning(text): - """Return True if reasoning text contains at least one alphanumeric character. - - Some providers (e.g. moonshotai/kimi-k3) occasionally return completions - with empty ``content`` and a ``reasoning_content`` made entirely of - punctuation (e.g. ``"!!!!"``). Those responses are effectively empty, so - the empty-response detector only lets reasoning count as response - content when it holds at least one alphanumeric character. - """ - return bool(text) and any(ch.isalnum() for ch in text) + + @staticmethod + def _first_usage_tokens(usage: object, paths: list[str], default: int = 0) -> int: + """Return the first non-None token count among ``paths``. + + ``nested.getter`` stops at the first attribute that exists even when its value + is None. Anthropic/copilot ``Usage`` always declares ``prompt_cache_hit_tokens`` + (None) and populates ``cache_read_input_tokens``, so looking only at the first + field would report zero cache hits despite the server serving the cached prefix. + """ + for path in paths: + value = nested.getter(usage, path, None) + if value is not None: + return value + + return default diff --git a/cecli/coders/context_coder.py b/cecli/coders/context_coder.py index 96f86204f33..df0cd91a868 100644 --- a/cecli/coders/context_coder.py +++ b/cecli/coders/context_coder.py @@ -46,7 +46,7 @@ async def reply_completed(self): # mentioned_idents = self.get_ident_mentions(cur_msg_text) # if mentioned_idents: - return True + return False def check_for_file_mentions(self, content): pass diff --git a/tests/basic/test_coder.py b/tests/basic/test_coder.py index 20a2b34cb68..fc9d34063dc 100644 --- a/tests/basic/test_coder.py +++ b/tests/basic/test_coder.py @@ -1510,7 +1510,7 @@ async def test_architect_coder_auto_accept_false_rejected(self): ): result = await coder.reply_completed() - assert result is None + assert result is True io.confirm_ask.assert_called_once_with( "Edit the files?", allow_tweak=False, diff --git a/tests/basic/test_empty_response.py b/tests/basic/test_empty_response.py index fb1e9cf39c3..77a380bec41 100644 --- a/tests/basic/test_empty_response.py +++ b/tests/basic/test_empty_response.py @@ -10,11 +10,13 @@ import pytest -from cecli.coders.base_coder import Coder, _is_meaningful_reasoning +from cecli.coders.base_coder import Coder from cecli.helpers.loop_detect import LoopThresholdTracker from cecli.helpers.threading import ThreadSafeEvent from cecli.llm import litellm +_is_meaningful_reasoning = Coder.is_meaningful_reasoning + # --------------------------------------------------------------------------- # # Test doubles diff --git a/tests/coders/test_agent_coder_reply_completed.py b/tests/coders/test_agent_coder_reply_completed.py new file mode 100644 index 00000000000..92baaf48d6c --- /dev/null +++ b/tests/coders/test_agent_coder_reply_completed.py @@ -0,0 +1,69 @@ +from unittest.mock import patch + +from cecli.coders.agent_coder import AgentCoder + + +class TestAgentCoderReplyCompleted: + """Tests for AgentCoder.reply_completed turn-completion semantics.""" + + @staticmethod + def _make_coder(**overrides): + coder = AgentCoder.__new__(AgentCoder) + coder.partial_response_content = "" + coder.partial_response_tool_calls = [] + coder.partial_response_reasoning_content = "" + coder.agent_finished = False + coder.agent_config = {"command_timeout": 30} + coder.tool_usage_history = [] + coder.tool_usage_retries = 20 + coder.num_reflections = 0 + coder.max_reflections = 5 + coder.reflected_message = None + + for key, value in overrides.items(): + setattr(coder, key, value) + + return coder + + async def test_reasoning_without_content_reflects(self): + coder = self._make_coder( + partial_response_reasoning_content="I should inspect the file first." + ) + + with patch( + "cecli.coders.agent_coder.BackgroundCommandManager.list_background_commands", + return_value={}, + ): + completed = await coder.reply_completed() + + assert completed is False + assert coder.reflected_message is not None + assert 'type="empty_response"' in coder.reflected_message + + async def test_punctuation_only_reasoning_yields(self): + coder = self._make_coder(partial_response_reasoning_content="!!!!") + + with patch( + "cecli.coders.agent_coder.BackgroundCommandManager.list_background_commands", + return_value={}, + ): + completed = await coder.reply_completed() + + assert completed is True + assert coder.reflected_message is None + + async def test_reasoning_yields_when_reflection_budget_exhausted(self): + coder = self._make_coder( + partial_response_reasoning_content="Still thinking.", + num_reflections=5, + max_reflections=5, + ) + + with patch( + "cecli.coders.agent_coder.BackgroundCommandManager.list_background_commands", + return_value={}, + ): + completed = await coder.reply_completed() + + assert completed is True + assert coder.reflected_message is None From 2d7899a105d13e44b0050a53b5d8c5cd1feb3fc0 Mon Sep 17 00:00:00 2001 From: Dustin Washington Date: Sat, 28 Nov 2026 15:09:11 -0500 Subject: [PATCH 3/5] Fix formatting --- cecli/helpers/desktop/bridge.py | 1 + desktop/tests/test_bridge.py | 2 +- desktop/tests/test_hooks.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/cecli/helpers/desktop/bridge.py b/cecli/helpers/desktop/bridge.py index 98182bf8904..fbb9f1a2bf4 100644 --- a/cecli/helpers/desktop/bridge.py +++ b/cecli/helpers/desktop/bridge.py @@ -4710,6 +4710,7 @@ def _kill_process_tree(process: asyncio.subprocess.Process) -> None: if result.returncode != 0: process.terminate() + def _signal_process(process: asyncio.subprocess.Process, hard: bool = False) -> None: """Signal the child's process group on POSIX, or the child elsewhere.""" if os.name == "posix": diff --git a/desktop/tests/test_bridge.py b/desktop/tests/test_bridge.py index b05c7612db3..27dddf846d8 100644 --- a/desktop/tests/test_bridge.py +++ b/desktop/tests/test_bridge.py @@ -185,7 +185,7 @@ def setUp(self) -> None: else: wrapper = Path(self.temp_dir.name) / "fake-cecli" wrapper.write_text( - f'#!/bin/sh\nexec {shlex.quote(sys.executable)} ' + f"#!/bin/sh\nexec {shlex.quote(sys.executable)} " f'{shlex.quote(str(FAKE_AGENT))} "$@"\n', encoding="utf-8", ) diff --git a/desktop/tests/test_hooks.py b/desktop/tests/test_hooks.py index 0da91fab6d2..fc705725944 100644 --- a/desktop/tests/test_hooks.py +++ b/desktop/tests/test_hooks.py @@ -75,7 +75,7 @@ def setUp(self) -> None: else: wrapper = Path(self.temp_dir.name) / "fake-cecli" wrapper.write_text( - f'#!/bin/sh\nexec {shlex.quote(sys.executable)} ' + f"#!/bin/sh\nexec {shlex.quote(sys.executable)} " f'{shlex.quote(str(FAKE_AGENT))} "$@"\n', encoding="utf-8", ) From 64f0fc28bc690bb3872c2395b22f5438a7b6b95a Mon Sep 17 00:00:00 2001 From: Dustin Washington Date: Sat, 28 Nov 2026 15:16:52 -0500 Subject: [PATCH 4/5] Use system certs for uv install --- desktop/src-tauri/src/main.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index bb9fd1f0af5..13c0fb092b9 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -646,6 +646,8 @@ fn provision_runtime( .arg("3.12") // Require uv's own CPython so the runtime survives a system Python change. .arg("--managed-python") + // --native-tls: the managed CPython download must trust the OS store too. + .arg("--native-tls") .arg("--no-progress") .arg(env_dir); prepare_uv(&mut venv, root); @@ -671,6 +673,10 @@ fn provision_runtime( fn prepare_uv(command: &mut Command, root: &Path) { command .env("UV_PYTHON_INSTALL_DIR", root.join("python")) + // Corporate TLS interception is only trusted via the platform store. + // UV_NATIVE_TLS is the pre-0.10 spelling of UV_SYSTEM_CERTS. + .env("UV_SYSTEM_CERTS", "1") + .env("UV_NATIVE_TLS", "1") .env_remove("PYTHONHOME") .env_remove("PYTHONPATH") .stdin(Stdio::null()) From 93460a8115fee32ff18aa2cd520a64e4efe06fda Mon Sep 17 00:00:00 2001 From: Dustin Washington Date: Sat, 28 Nov 2026 15:24:51 -0500 Subject: [PATCH 5/5] Update MCP tests after lazy load imprting for desktop bridge --- tests/mcp/conftest.py | 4 ++-- tests/mcp/test_keepalive_concurrency.py | 2 +- tests/mcp/test_keepalive_config.py | 4 ++-- tests/mcp/test_server_sdk_compat.py | 8 ++++---- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/mcp/conftest.py b/tests/mcp/conftest.py index cd5dd67db0f..736d5d06203 100644 --- a/tests/mcp/conftest.py +++ b/tests/mcp/conftest.py @@ -78,7 +78,7 @@ def http_based_server(http_server_config, mock_io) -> HttpBasedMcpServer: mock_session = AsyncMock() mock_session.initialize = AsyncMock() mock_session_class = MagicMock(return_value=mock_session) - server._session_patch = patch("cecli.mcp.server.ClientSession", mock_session_class) + server._session_patch = patch("mcp.ClientSession", mock_session_class) server._session_patch.start() return server @@ -101,7 +101,7 @@ def http_streaming_server(http_streaming_server_config, mock_io) -> HttpStreamin mock_session = AsyncMock() mock_session.initialize = AsyncMock() mock_session_class = MagicMock(return_value=mock_session) - server._session_patch = patch("cecli.mcp.server.ClientSession", mock_session_class) + server._session_patch = patch("mcp.ClientSession", mock_session_class) server._session_patch.start() return server diff --git a/tests/mcp/test_keepalive_concurrency.py b/tests/mcp/test_keepalive_concurrency.py index cadf561fe53..ede61342b25 100644 --- a/tests/mcp/test_keepalive_concurrency.py +++ b/tests/mcp/test_keepalive_concurrency.py @@ -123,7 +123,7 @@ async def test_no_keepalive_task_when_disabled(self, http_server_config, mock_io mock_session = AsyncMock() mock_session.initialize = AsyncMock() mock_session_class = MagicMock(return_value=mock_session) - server._session_patch = patch("cecli.mcp.server.ClientSession", mock_session_class) + server._session_patch = patch("mcp.ClientSession", mock_session_class) server._session_patch.start() # Connect server diff --git a/tests/mcp/test_keepalive_config.py b/tests/mcp/test_keepalive_config.py index a9b86573d7c..507a7548ef6 100644 --- a/tests/mcp/test_keepalive_config.py +++ b/tests/mcp/test_keepalive_config.py @@ -103,8 +103,8 @@ async def test_auth_header_included_in_keepalive_request( server._create_oauth_provider = AsyncMock() with ( - patch("cecli.mcp.server.ClientSession") as MockSession, - patch("cecli.mcp.server.streamable_http_client") as mock_transport, + patch("mcp.ClientSession") as MockSession, + patch("mcp.client.streamable_http.streamable_http_client") as mock_transport, patch("cecli.mcp.server._get_http_client_module") as mock_get_http_module, ): # Setup mock HTTP client module to capture constructor args diff --git a/tests/mcp/test_server_sdk_compat.py b/tests/mcp/test_server_sdk_compat.py index 1f274c99174..5001b80bdbd 100644 --- a/tests/mcp/test_server_sdk_compat.py +++ b/tests/mcp/test_server_sdk_compat.py @@ -183,8 +183,8 @@ async def test_connect_skips_oauth_provider_when_headers_set(): server._create_oauth_provider = AsyncMock() with ( - patch("cecli.mcp.server.ClientSession") as MockSession, - patch("cecli.mcp.server.streamable_http_client") as mock_transport, + patch("mcp.ClientSession") as MockSession, + patch("mcp.client.streamable_http.streamable_http_client") as mock_transport, patch("cecli.mcp.server._get_http_client_module") as mock_get_module, ): mock_http_client = AsyncMock() @@ -225,8 +225,8 @@ async def test_connect_creates_oauth_provider_when_no_headers(): server._create_oauth_provider = AsyncMock(return_value=None) with ( - patch("cecli.mcp.server.ClientSession") as MockSession, - patch("cecli.mcp.server.streamable_http_client") as mock_transport, + patch("mcp.ClientSession") as MockSession, + patch("mcp.client.streamable_http.streamable_http_client") as mock_transport, patch("cecli.mcp.server._get_http_client_module") as mock_get_module, ): mock_http_client = AsyncMock()