diff --git a/core/agent_runtime/helpers.py b/core/agent_runtime/helpers.py index d33949735..c42ed8419 100644 --- a/core/agent_runtime/helpers.py +++ b/core/agent_runtime/helpers.py @@ -292,6 +292,31 @@ def build_assistant_message( return msg +def named_tool_calls(tool_calls: Any) -> list[dict[str, Any]]: + """Keep only the tool calls that name the function to run. + + A call whose ``function.name`` is missing or blank names nothing: the model + API rejects the whole request that carries one, and the records round-trip + verbatim, so a single such entry poisons a session on every resume. A parser + glitch that turns raw tool-call text into a ``tool_calls`` entry while + dropping the name is enough to produce one. + + Shared by the transcript boundary, which drops them on save and on rebuild, + and by the request path, which drops them from the provider-visible view so + a live session heals without a restart. + """ + if not isinstance(tool_calls, (list, tuple)): + return [] + return [ + call + for call in tool_calls + if isinstance(call, dict) + and isinstance(call.get("function"), dict) + and isinstance(call["function"].get("name"), str) + and call["function"]["name"].strip() + ] + + def estimate_prompt_tokens( messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None, diff --git a/core/agent_runtime/runner.py b/core/agent_runtime/runner.py index 6c7d2481e..dcebb2293 100644 --- a/core/agent_runtime/runner.py +++ b/core/agent_runtime/runner.py @@ -38,6 +38,7 @@ estimate_message_tokens, find_legal_message_start, maybe_persist_tool_result, + named_tool_calls, renew_tool_result_references, truncate_text, ) @@ -1163,7 +1164,8 @@ def _request_view( minimal repair instead of aborting the run. """ try: - view = self._drop_orphan_tool_results(messages) + view = self._drop_nameless_tool_calls(messages) + view = self._drop_orphan_tool_results(view) view = self._backfill_missing_tool_results(view) view = self._apply_tool_result_budget(spec, view) view = self._with_transient_context( @@ -1181,7 +1183,8 @@ def _request_view( exc, ) try: - view = self._drop_orphan_tool_results(messages) + view = self._drop_nameless_tool_calls(messages) + view = self._drop_orphan_tool_results(view) return self._backfill_missing_tool_results(view) except Exception: return messages @@ -1880,6 +1883,47 @@ def _normalize_tool_result( return truncate_text(content, spec.max_tool_result_chars) return content + @staticmethod + def _drop_nameless_tool_calls( + messages: list[dict[str, Any]], + ) -> list[dict[str, Any]]: + """Drop tool calls that name no function, and turns left empty by them. + + A live session keeps ``AgentSession._history`` in memory between turns, + so the record boundary in :mod:`core.sessions.transcript` cannot heal a + run that is already poisoned: the nameless call sits in the message list + the provider is about to receive, and the request is rejected until the + process restarts. + + Runs before :meth:`_drop_orphan_tool_results` on purpose. Dropping a + call orphans its tool result, and the orphan pass that follows then + removes it, so calls and results still pair up. + """ + updated: list[dict[str, Any]] | None = None + for idx, msg in enumerate(messages): + current = msg + raw = msg.get("tool_calls") + if msg.get("role") == "assistant" and isinstance(raw, (list, tuple)): + raw_calls = list(raw) + kept = named_tool_calls(raw_calls) + if len(kept) != len(raw_calls): + if updated is None: + updated = [dict(m) for m in messages[:idx]] + if not kept and not msg.get("content"): + # Nothing survives this turn: no name to run, no text. + continue + current = dict(msg) + if kept: + current["tool_calls"] = kept + else: + current.pop("tool_calls", None) + if updated is not None: + updated.append(dict(current)) + + if updated is None: + return messages + return updated + @staticmethod def _drop_orphan_tool_results( messages: list[dict[str, Any]], diff --git a/core/sessions/transcript.py b/core/sessions/transcript.py index 2ad3a8936..00b492ccc 100644 --- a/core/sessions/transcript.py +++ b/core/sessions/transcript.py @@ -12,6 +12,7 @@ from typing import Any, Iterable, Mapping from core.agent_runtime.context import EnvironmentContext +from core.agent_runtime.helpers import named_tool_calls from core.domain.message_provenance import TurnInputSource from core.sessions.continuation import session_message_history_entry from core.sessions.models import SessionMessage @@ -40,7 +41,7 @@ def kernel_message_to_record(message: Mapping[str, Any]) -> SessionMessage | Non if EnvironmentContext.is_history_message(message): return None content = _as_text(message.get("content")) - tool_calls = message.get("tool_calls") + tool_calls = named_tool_calls(message.get("tool_calls")) if role == "assistant" and not content and not tool_calls: return None if role == "user" and not content: @@ -50,7 +51,7 @@ def kernel_message_to_record(message: Mapping[str, Any]) -> SessionMessage | Non metadata: dict[str, Any] = {} if role == "assistant": if tool_calls: - metadata[TOOL_CALLS_META] = deepcopy(list(tool_calls)) + metadata[TOOL_CALLS_META] = deepcopy(tool_calls) provider_state = message.get("provider_state") if isinstance(provider_state, dict) and provider_state: metadata["providerState"] = deepcopy(provider_state) @@ -116,8 +117,7 @@ def record_fingerprint(message: SessionMessage) -> tuple[Any, ...]: "" if message.role == "tool" and call_id else message.content, tuple( str(call.get("id", "")) - for call in metadata.get(TOOL_CALLS_META) or () - if isinstance(call, dict) + for call in named_tool_calls(metadata.get(TOOL_CALLS_META)) ), call_id, ) @@ -135,17 +135,17 @@ def session_message_to_kernel(message: SessionMessage) -> dict[str, Any] | None: if message.role not in {"user", "assistant", "tool"}: return None metadata = message.metadata or {} - if ( - message.role in {"user", "assistant"} - and not message.content - and not metadata.get(TOOL_CALLS_META) - ): + tool_calls = ( + named_tool_calls(metadata.get(TOOL_CALLS_META)) + if message.role == "assistant" + else [] + ) + if message.role in {"user", "assistant"} and not message.content and not tool_calls: return None entry = session_message_history_entry(message) if message.role == "assistant": - tool_calls = metadata.get(TOOL_CALLS_META) if tool_calls: - entry["tool_calls"] = deepcopy(list(tool_calls)) + entry["tool_calls"] = deepcopy(tool_calls) if message.role == "tool": call_id = metadata.get(TOOL_CALL_ID_META) if call_id: diff --git a/tests/test_session_transcript.py b/tests/test_session_transcript.py index 4dd2f7f26..e8ac0b78c 100644 --- a/tests/test_session_transcript.py +++ b/tests/test_session_transcript.py @@ -2,6 +2,14 @@ from __future__ import annotations +from typing import Any + +import pytest + +from core.agent_runtime.tools.registry import ToolRegistry +from core.events import AgentSession +from core.events.protocol import UserInput +from core.providers.base import LLMResponse, ToolCallRequest from core.sessions.models import SessionMessage from core.sessions.transcript import ( is_context_note, @@ -184,6 +192,107 @@ def test_a_tool_result_pruned_under_pressure_is_not_saved_again() -> None: assert [(item.role, item.content) for item in added] == [("assistant", "done")] +def test_a_nameless_call_is_dropped_before_it_is_stored() -> None: + # A parser glitch can hand back a call whose function carries the raw + # payload but no name. The API rejects a request that replays one + # (400/422 missing field name), so it must never reach the store. + history = [ + {"role": "user", "content": "run echo"}, + { + "role": "assistant", + "content": "calling", + "tool_calls": [ + { + "id": "c1", + "type": "function", + "function": {"arguments": '{"command":"echo hi"}'}, + }, + {"id": "c2", "type": "function", "function": {"name": " "}}, + { + "id": "c3", + "type": "function", + "function": {"name": "bash", "arguments": '{"command":"echo hi"}'}, + }, + ], + }, + {"role": "tool", "content": "hi", "tool_call_id": "c3", "name": "bash"}, + ] + stored = new_records_from_history(history, stored=()) + calls = (stored[1].metadata or {})["toolCalls"] + assert [call["id"] for call in calls] == ["c3"] + + +def test_a_stored_nameless_call_is_dropped_on_resume() -> None: + # A record poisoned before this guard existed self-heals on resume: + # its text stays, the undeliverable call goes. + stored = [ + SessionMessage(role="user", content="run echo"), + SessionMessage( + role="assistant", + content="calling", + metadata={ + "toolCalls": [ + { + "id": "c1", + "type": "function", + "function": {"arguments": '{"command":"echo hi"}'}, + } + ] + }, + ), + ] + rebuilt = visible_kernel_history(stored) + assert rebuilt[1]["content"] == "calling" + assert "tool_calls" not in rebuilt[1] + + +def test_a_turn_of_only_nameless_calls_leaves_nothing_behind() -> None: + # No text and no deliverable call means there is no message to keep. + history = [ + {"role": "user", "content": "run echo"}, + { + "role": "assistant", + "content": "", + "tool_calls": [{"id": "c1", "type": "function", "function": {}}], + }, + ] + stored = new_records_from_history(history, stored=()) + assert [item.role for item in stored] == ["user"] + assert [item["role"] for item in visible_kernel_history(stored)] == ["user"] + + +def test_a_resumed_poisoned_turn_is_not_stored_again() -> None: + # The fingerprint must see the same surviving calls the replay does, + # or every resume re-saves the cleaned turn as a second message. + stored = [ + SessionMessage(role="user", content="run echo"), + SessionMessage( + role="assistant", + content="calling", + metadata={ + "toolCalls": [ + { + "id": "c1", + "type": "function", + "function": {"arguments": "{}"}, + }, + { + "id": "c2", + "type": "function", + "function": {"name": "bash", "arguments": "{}"}, + }, + ] + }, + ), + ] + history = [ + *visible_kernel_history(stored), + {"role": "assistant", "content": "done"}, + ] + added = new_records_from_history(history, stored) + assert [(item.role, item.content) for item in added] == [("assistant", "done")] + + def test_only_runtime_notes_count_as_context_notes() -> None: def user(**metadata: str) -> SessionMessage: return SessionMessage("user", "text", metadata=metadata) @@ -197,3 +306,73 @@ def user(**metadata: str) -> SessionMessage: assert not is_context_note( SessionMessage("assistant", "text", metadata={"delivery": "mid_turn"}) ) + + +class _NamelessCallProvider: + """Records every request and replays a scripted response list.""" + + def __init__(self, responses: list[LLMResponse]) -> None: + self.responses = list(responses) + self.calls = 0 + self.requests: list[list[dict[str, Any]]] = [] + + def get_default_model(self) -> str: + return "fake-model" + + async def chat_with_retry(self, **kwargs: Any) -> LLMResponse: + self.requests.append(list(kwargs.get("messages") or [])) + index = min(self.calls, len(self.responses) - 1) + self.calls += 1 + return self.responses[index] + + +def _nameless_calls(messages: list[dict[str, Any]]) -> list[str]: + """Ids of the tool calls in ``messages`` that name no function.""" + found: list[str] = [] + for message in messages: + if message.get("role") != "assistant": + continue + for call in message.get("tool_calls") or (): + function = call.get("function") if isinstance(call, dict) else None + name = (function or {}).get("name") + if not isinstance(name, str) or not name.strip(): + found.append(str(call.get("id"))) + return found + + +@pytest.mark.asyncio +async def test_a_live_session_never_sends_a_nameless_tool_call() -> None: + """Storage is healed by the record boundary; a live run must heal too. + + ``AgentSession._history`` is kept in memory between turns, so dropping the + nameless call on save and on rebuild is not enough: the follow-up request in + the same turn, and every later turn, would still carry it until a restart. + """ + provider = _NamelessCallProvider( + [ + LLMResponse( + content="", + tool_calls=[ToolCallRequest(id="nameless-1", name="", arguments={})], + finish_reason="tool_calls", + ), + LLMResponse(content="after the tool turn", finish_reason="stop"), + LLMResponse(content="second turn", finish_reason="stop"), + ] + ) + session = AgentSession(provider, ToolRegistry(), model="fake-model") + + await session.submit(UserInput(text="first")) + first_events = session.drain_events() + await session.submit(UserInput(text="second")) + second_events = session.drain_events() + + # The follow-up request of the same turn, and every later request, is clean. + assert len(provider.requests) >= 3 + for index, request in enumerate(provider.requests[1:], start=1): + assert _nameless_calls(request) == [], ( + f"request {index} carried a nameless tool call" + ) + + # The poisoned turn ends, and the turn after it succeeds. + assert [event.msg.type for event in first_events][-1] == "task_complete" + assert [event.msg.type for event in second_events][-1] == "task_complete"