Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions cecli/coders/agent_coder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
Expand All @@ -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
]

Expand All @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions cecli/coders/architect_coder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -25,7 +25,7 @@ async def reply_completed(self):
)

if not confirmation:
return
return True

if confirmation == "tweak":
if self.tui and self.tui():
Expand Down
99 changes: 52 additions & 47 deletions cecli/coders/base_coder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
2 changes: 1 addition & 1 deletion cecli/coders/context_coder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions cecli/helpers/desktop/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
6 changes: 6 additions & 0 deletions cecli/helpers/llms/litellm_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
6 changes: 3 additions & 3 deletions cecli/helpers/llms/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading