Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agent-chat): replay tool rounds as a labelled record, not a call marker (#980)
Ruben Lütkefd6a1a357aa7
diff --git a/dodaios/agent_chat/runner_brain.py b/dodaios/agent_chat/runner_brain.pyindex 218710c55d..b35df2b7cf 100644--- a/dodaios/agent_chat/runner_brain.py+++ b/dodaios/agent_chat/runner_brain.py@@ -91,47 +91,95 @@ def brain_history_from_events() -> list[BrainMessage]:"""The chat's own log as the turn's history: what was said, in prose.- User and assistant TEXT only. A tool round is folded into the assistant- message as one line per call ("[used tool X: …]") and its results are- dropped: Jarvis' loop rebuilds its own tool rounds, and replaying a- foreign provider's ``tool_use`` ids into a different provider fails its- validation. Capped to the last ``_HISTORY_MAX`` messages.+ User and assistant TEXT only, so no foreign provider's ``tool_use`` ids are+ replayed into a different provider (that fails its validation). A turn's+ tool rounds become one labelled tool record at the top of that turn's+ assistant message: each call with a short, bounded result, errors kept.++ The record is worded as data on purpose. An older format wrote each call+ as an assistant line ("[used tool X]") and dropped the results; smaller+ local models then copied that line instead of making a real tool call+ (issue #978). Capped to the last ``_HISTORY_MAX`` messages."""out: list[BrainMessage] = []+ prose: list[str] = []+ calls: list[dict[str, str]] = []+ by_id: dict[str, dict[str, str]] = {}++ def flush_turn() -> None:+ parts = ([_tool_record(calls)] if calls else []) + prose+ text = "\n".join(parts)+ if text.strip():+ out.append(BrainMessage(role="assistant", content=text))+ prose.clear()+ calls.clear()+ by_id.clear()+for message in messages_from_events(events, max_events=None if max_messages is None else 600):if message.role == "user":text = message.content if isinstance(message.content, str) else ""if text.strip():+ flush_turn()out.append(BrainMessage(role="user", content=text))elif message.role == "assistant":- text = _assistant_prose(message.content)- if not text.strip():+ # One answer per turn: the tool rounds and the prose after them+ # are several provider messages but one thing Jarvis said.+ if isinstance(message.content, str):+ if message.content.strip():+ prose.append(message.content)continue- if out and out[-1].role == "assistant":- # One answer per turn: the tool round and the prose after it- # are two provider messages but one thing Jarvis said.- merged = f"{out[-1].content}\n{text}"- out[-1] = BrainMessage(role="assistant", content=merged)- else:- out.append(BrainMessage(role="assistant", content=text))+ for block in message.content:+ kind = block.get("type")+ if kind == "text":+ text = str(block.get("text") or "")+ if text.strip():+ prose.append(text)+ elif kind == "tool_use":+ name = str(block.get("name") or "tool")+ args = block.get("input") or {}+ entry = {+ "name": name,+ "summary": summarize_call(name, args) if isinstance(args, dict) else "",+ }+ calls.append(entry)+ by_id[str(block.get("id") or "")] = entry+ elif message.role == "tool":+ entry = by_id.get(str(message.tool_call_id or ""))+ if entry is not None:+ entry["result"] = message.content if isinstance(message.content, str) else ""+ flush_turn()return out[-max_messages:] if max_messages else out-def _assistant_prose(content: str | list[dict[str, Any]]) -> str:- if isinstance(content, str):- return content- lines: list[str] = []- for block in content:- kind = block.get("type")- if kind == "text":- text = str(block.get("text") or "")- if text.strip():- lines.append(text)- elif kind == "tool_use":- name = str(block.get("name") or "tool")- args = block.get("input") or {}- summary = summarize_call(name, args) if isinstance(args, dict) else ""- lines.append(f"[used tool {name}: {summary}]" if summary else f"[used tool {name}]")+#: How much of one tool result the record keeps, and how many calls it lists.+_RECORD_RESULT_CHARS: Final[int] = 300+_RECORD_MAX_CALLS: Final[int] = 8++_RECORD_HEADER: Final[str] = (+ "Tool record of this turn (already executed; historical data, not a format "+ "for new calls; new tool calls go through the tool interface):"+)+++def _tool_record(calls: list[dict[str, str]]) -> str:+ """The labelled data block for one turn's tool calls and their results."""+ lines = [_RECORD_HEADER]+ for entry in calls[:_RECORD_MAX_CALLS]:+ target = f"{entry['name']} ({entry['summary']})" if entry["summary"] else entry["name"]+ if "result" not in entry:+ lines.append(f"- {target}: no result recorded")+ continue+ result = entry["result"]+ failed = result.startswith("[error]")+ if failed:+ result = result[len("[error]") :]+ result = " ".join(result.split())+ if len(result) > _RECORD_RESULT_CHARS:+ result = result[:_RECORD_RESULT_CHARS] + "…"+ verb = "failed" if failed else "returned"+ lines.append(f"- {target} {verb}: {result}" if result else f"- {target} {verb} nothing")+ if len(calls) > _RECORD_MAX_CALLS:+ lines.append(f"- … and {len(calls) - _RECORD_MAX_CALLS} more calls")return "\n".join(lines)@@ -691,8 +739,8 @@ async def _generate(# turn lock; do not detect language from an English result prompt.if not handle.output_language:pin = getattr(brain, "reply_language", "")- language = pin if is_supported_locale(pin) else getattr(- brain, "conversation_language", ""+ language = (+ pin if is_supported_locale(pin) else getattr(brain, "conversation_language", ""))if is_known_language(language):handle.output_language = languagediff --git a/dodaios/society/conversation.py b/dodaios/society/conversation.pyindex 1ecaa3cbf4..a5ed3efcff 100644--- a/dodaios/society/conversation.py+++ b/dodaios/society/conversation.py@@ -344,10 +344,11 @@ async def prepare_history(tail: list[dict[str, Any]] = []tail_size = 0for event in reversed(remaining):- # The API history renderer does not replay raw tool results.- # Charging their full size here displaced the latest user request- # even when the actual conversational tail easily fit the budget.- cost = 0 if event.get("kind") == "tool_result" else len(event_text(event)) + 32+ # The API history renderer keeps only a short excerpt of each tool+ # result. Charging the full size here displaced the latest user+ # request even when the actual conversational tail easily fit.+ text_len = len(event_text(event))+ cost = (min(text_len, 320) if event.get("kind") == "tool_result" else text_len) + 32if tail_size + cost > budget // 2:breaktail.append(event)diff --git a/tests/unit/agent_chat/test_runner_brain.py b/tests/unit/agent_chat/test_runner_brain.pyindex 66f778c05b..57e535956b 100644--- a/tests/unit/agent_chat/test_runner_brain.py+++ b/tests/unit/agent_chat/test_runner_brain.py@@ -202,7 +202,10 @@ async def test_history_is_the_sessions_own_log_in_prose(history = kw["history_override"]assert [m.role for m in history] == ["user", "assistant"]assert history[0].content == "first question"- assert "[used tool Read: a.py]" in history[1].content and "It prints 1." in history[1].content+ assert "[used tool" not in history[1].content, "no imitable call marker (#978)"+ assert "Tool record of this turn" in history[1].content+ assert "- Read (a.py) returned: print(1)" in history[1].content+ assert history[1].content.endswith("It prints 1.")assert all(isinstance(m.content, str) for m in history), "prose only, no foreign tool ids"diff --git a/tests/unit/agent_chat/test_tool_history_record.py b/tests/unit/agent_chat/test_tool_history_record.pynew file mode 100644index 0000000000..e6097d38a0--- /dev/null+++ b/tests/unit/agent_chat/test_tool_history_record.py@@ -0,0 +1,76 @@+"""History replay renders tool rounds as labelled data, never as a call marker (#978)."""++from __future__ import annotations++from typing import Any++from dodaios.agent_chat.events import make_event+from dodaios.agent_chat.runner_brain import brain_history_from_events+++def _ev(seq: int, kind: str, payload: dict[str, Any]) -> dict[str, Any]:+ event = make_event(kind, payload)+ event["seq"] = seq+ return event+++def _turn(calls: list[tuple[str, dict[str, Any], str | None, bool]]) -> list[dict[str, Any]]:+ events = [_ev(1, "user_message", {"text": "do it"})]+ seq = 2+ for index, (name, args, output, is_error) in enumerate(calls):+ call_id = f"c{index}"+ events.append(+ _ev(seq, "tool_call", {"turn_id": "t", "call_id": call_id, "name": name, "input": args})+ )+ seq += 1+ if output is not None:+ events.append(+ _ev(+ seq,+ "tool_result",+ {"turn_id": "t", "call_id": call_id, "output": output, "is_error": is_error},+ )+ )+ seq += 1+ events.append(_ev(seq, "assistant_text", {"turn_id": "t", "text": "Done."}))+ events.append(_ev(seq + 1, "turn_finished", {"turn_id": "t", "status": "done"}))+ events.append(_ev(seq + 2, "user_message", {"text": "next"}))+ return events+++def test_errors_are_kept_and_results_are_bounded() -> None:+ history = brain_history_from_events(+ _turn(+ [+ ("Bash", {"command": "ls"}, "x" * 2000, False),+ ("Read", {"file_path": "b.py"}, "no such file", True),+ ]+ )+ )+ assert [m.role for m in history] == ["user", "assistant", "user"]+ text = history[1].content+ assert isinstance(text, str)+ assert "[used tool" not in text+ assert "failed: no such file" in text+ assert "x" * 300 + "…" in text and "x" * 301 not in text+ assert text.endswith("Done.")+++def test_a_cancelled_call_reads_as_cancelled_not_as_a_new_call() -> None:+ events = _turn([("Read", {"file_path": "a.py"}, None, False)])+ # Drop the closing turn so the call stays open, like a cancelled turn.+ history = brain_history_from_events([e for e in events if e["kind"] != "turn_finished"])+ assert "cancelled before it ran" in history[1].content+++def test_the_record_lists_at_most_eight_calls() -> None:+ calls = [("Read", {"file_path": f"f{i}.py"}, "ok", False) for i in range(11)]+ text = brain_history_from_events(_turn(calls))[1].content+ assert text.count("\n- Read") == 8+ assert "and 3 more calls" in text+++def test_no_provider_tool_ids_reach_the_history() -> None:+ history = brain_history_from_events(_turn([("Read", {"file_path": "a.py"}, "ok", False)]))+ assert all(isinstance(m.content, str) and m.tool_call_id is None for m in history)+ assert all(m.role in {"user", "assistant"} for m in history)