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
22 changes: 21 additions & 1 deletion terminal/serve/frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,8 @@ def _order_chat_tool_results(messages: list[dict]) -> None:
"""The template pairs results by position, so restore call order while IDs are still available.

Only a complete, unambiguous run of results is reordered. Legacy or incomplete histories keep their
received order. IDs are private to this conversion and never reach the template.
received order. Each result is then named after its call (_name_tool_results). IDs are private to this
conversion and never reach the template.
"""
i = 0
while i < len(messages):
Expand All @@ -660,12 +661,29 @@ def _order_chat_tool_results(messages: list[dict]) -> None:
rank = {cid: n for n, cid in enumerate(calls)}
messages[i:j] = sorted(messages[i:j], key=lambda m: rank[m["_call_id"]])
i = j
_name_tool_results(messages)
for message in messages:
message.pop("_call_id", None)
for call in message.get("tool_calls") or []:
call.pop("_call_id", None)


def _name_tool_results(messages: list[dict]) -> None:
"""#7051: a tool result without a `name` takes the function name of the nearest earlier call with its `_call_id`
(Inkling's template heads the result with it); an id used twice in that call's turn is ambiguous and names
nothing. Run before the private ids are dropped."""
names = {}
for message in messages:
cid = message.get("_call_id")
if message["role"] == "tool" and not message.get("name") and isinstance(cid, str) and names.get(cid):
message["name"] = names[cid]
ids = [c.get("_call_id") for c in message.get("tool_calls") or []]
for call in message.get("tool_calls") or []:
cid, name = call.get("_call_id"), call["function"].get("name")
if isinstance(cid, str) and cid:
names[cid] = name if isinstance(name, str) and name and ids.count(cid) == 1 else None


def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:
"""OpenAI Chat Completions -> (template messages, template tools, template kwargs)."""
messages = []
Expand All @@ -680,6 +698,8 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:
out = {"role": role, "content": _parts_of(content) if images else _text_of(content)}
if role == "tool":
out["_call_id"] = m.get("tool_call_id")
if isinstance(m.get("name"), str) and m["name"]:
out["name"] = m["name"]
if m.get("reasoning_content"):
out["reasoning_content"] = m["reasoning_content"]
if m.get("tool_calls"):
Expand Down
7 changes: 4 additions & 3 deletions terminal/serve/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import time
import uuid

from serve.frontend import Event, _late_system_to_user, _parts_of, cut_arguments, declared_parameters, effort_kwargs
from serve.frontend import Event, _late_system_to_user, _name_tool_results, _parts_of, cut_arguments, declared_parameters, effort_kwargs

ENCRYPTED_PREFIX = "strata.r1:" # our own reasoning replay strings; others' are ignored
HOSTED_TOOLS = ("web_search", "web_search_preview", "file_search", "computer_use_preview", "computer_use",
Expand Down Expand Up @@ -331,8 +331,8 @@ def turn(content=""):

def _order_tool_results(messages):
"""The template places tool results by position: each run of tool messages is put in the order of the calls of
the assistant turn before it (a client may send the results in the order they finished), then the private call
ids are dropped."""
the assistant turn before it (a client may send the results in the order they finished), each result is named
after its call (frontend._name_tool_results), then the private call ids are dropped."""
i = 0
while i < len(messages):
if messages[i]["role"] != "tool":
Expand All @@ -346,6 +346,7 @@ def _order_tool_results(messages):
rank = {cid: k for k, cid in enumerate(order) if cid}
messages[i:j] = sorted(messages[i:j], key=lambda m: rank.get(m.get("_call_id"), len(order)))
i = j
_name_tool_results(messages)
for m in messages:
m.pop("_call_id", None)
for c in m.get("tool_calls") or []:
Expand Down
2 changes: 1 addition & 1 deletion terminal/serve/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -6723,7 +6723,7 @@ def work(c=c, box=box):
messages.append({"role": "assistant", "content": "".join(text).strip(),
**({"reasoning_content": "".join(reasoning).strip()} if reasoning else {}),
"tool_calls": [{"function": {"name": c.name, "arguments": c.arguments}} for c in calls]})
messages += [{"role": "tool", "content": r} for r in results]
messages += [{"role": "tool", "content": r, "name": c.name} for c, r in zip(calls, results)] # #7051
if rounds >= max_rounds:
finalizing = True
tools = None
Expand Down
18 changes: 16 additions & 2 deletions terminal/serve/test_anthropic_tool_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,29 @@ def test_already_ordered_and_legacy_prompts_are_identical(self):
block.pop("id")
for block in legacy[2]["content"]:
block.pop("tool_use_id")
self.assertEqual(normalized(ordered), normalized(legacy))
# #7051: with ids each result also gets its tool_use's name; without ids there is nothing to name it from
named = normalized(ordered)
self.assertEqual([m.pop("name") for m in named[2:]], ["Grep", "Grep"])
self.assertEqual(named, normalized(legacy))
self.assertEqual([m["content"] for m in normalized(ordered)[2:]], ["RESULT_FROM_SLOW", "RESULT_FROM_FAST"])

def test_ids_never_reach_the_template(self):
for raw in (history(), in_call_order()):
messages = normalized(raw)
self.assertTrue(all(set(m) == {"role", "content"} for m in messages[2:]))
self.assertTrue(all(set(m) <= {"role", "content", "name"} for m in messages[2:]))
self.assertTrue(all(set(c) == {"function"} for c in messages[1]["tool_calls"]))

def test_results_are_named_after_their_tool_use_in_the_inkling_prompt(self):
raw = history()
raw[1]["content"][1]["name"] = "Glob"
messages = normalized(raw)
self.assertEqual([(m["content"], m["name"]) for m in messages[2:]],
[("RESULT_FROM_SLOW", "Grep"), ("RESULT_FROM_FAST", "Glob")])
inkling = ChatTemplate(Path(__file__).resolve().parents[1] / "tests" / "data" / "inkling" / "chat_template.jinja")
prompt = inkling.render(messages)
self.assertIn("<|message_tool|>Grep<|content_text|>RESULT_FROM_SLOW", prompt)
self.assertIn("<|message_tool|>Glob<|content_text|>RESULT_FROM_FAST", prompt)

def test_ambiguous_or_incomplete_ids_preserve_received_order(self):
for case in ("missing_call", "missing_result", "duplicate_call", "duplicate_result", "unknown",
"list_call", "list_result", "empty_call", "empty_result", "partial"):
Expand Down
82 changes: 80 additions & 2 deletions terminal/serve/test_chat_tool_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def test_reversed_results_of_the_same_function_follow_call_ids(self):
self.assertEqual(raw, before)
messages = normalized(raw)
self.assertEqual([m["content"] for m in messages[2:]], ["RESULT_FROM_A", "RESULT_FROM_B"])
self.assertTrue(all(set(m) == {"role", "content"} for m in messages[2:]))
self.assertTrue(all(set(m) <= {"role", "content", "name"} for m in messages[2:]))
self.assertTrue(all(set(c) == {"function"} for c in messages[1]["tool_calls"]))

def test_already_ordered_and_legacy_prompts_are_identical(self):
Expand All @@ -54,7 +54,10 @@ def test_already_ordered_and_legacy_prompts_are_identical(self):
call.pop("id")
for result in legacy[2:]:
result.pop("tool_call_id")
self.assertEqual(normalized(ordered), normalized(legacy))
# #7051: with ids each result also gets its call's name; without ids there is nothing to name it from
named = normalized(ordered)
self.assertEqual([m.pop("name") for m in named[2:]], ["read_file", "read_file"])
self.assertEqual(named, normalized(legacy))
self.assertEqual(rendered(ordered), rendered(legacy))

def test_ambiguous_or_incomplete_ids_preserve_received_order(self):
Expand Down Expand Up @@ -84,6 +87,8 @@ def test_ambiguous_or_incomplete_ids_preserve_received_order(self):
with self.subTest(case=case):
self.assertEqual([m["content"] for m in normalized(raw)[2:]],
[m["content"] for m in raw[2:]])
if case == "duplicate_call": # call_a twice in one turn: ambiguous, so neither result is named
self.assertEqual([m.get("name") for m in normalized(raw)[2:]], [None, None])

def test_each_tool_run_is_scoped_to_its_assistant_turn(self):
raw = history() + history()
Expand Down Expand Up @@ -129,5 +134,78 @@ def test_http_engine_receives_the_ordered_prompt(self):
httpd.server_close()


DATA = Path(__file__).resolve().parents[1] / "tests" / "data"
INKLING = ChatTemplate(DATA / "inkling" / "chat_template.jinja")


def call(cid, name):
return {"id": cid, "type": "function", "function": {"name": name, "arguments": "{}"}}


def result(cid, content, **extra):
return {"role": "tool", "tool_call_id": cid, "content": content, **extra}


def names(messages):
return [m.get("name") for m in normalized(messages) if m["role"] == "tool"]


class ChatToolResultNames(unittest.TestCase):
"""#7051: Inkling's template heads a tool result with its tool's name, from `name` or the matching call id."""

def test_a_result_is_named_after_its_call_in_the_inkling_prompt(self):
raw = [{"role": "user", "content": "Weather?"},
{"role": "assistant", "content": "", "tool_calls": [call("call_1", "get_weather")]},
result("call_1", "18 C")]
self.assertEqual(names(raw), ["get_weather"])
self.assertIn("<|message_tool|>get_weather<|content_text|>18 C", INKLING.render(normalized(raw)))

def test_a_client_name_is_kept(self):
raw = [{"role": "user", "content": "Weather?"},
{"role": "assistant", "content": "", "tool_calls": [call("call_1", "get_weather")]},
result("call_1", "18 C", name="weather_v2")]
self.assertEqual(names(raw), ["weather_v2"])
raw[2]["name"] = 7 # not a name: resolved from the call instead
self.assertEqual(names(raw), ["get_weather"])

def test_an_unmatched_empty_or_missing_id_gets_no_name(self):
raw = [{"role": "user", "content": "Weather?"},
{"role": "assistant", "content": "", "tool_calls": [call("", "get_weather"), call("call_2", None)]},
result("call_9", "a"), result("", "b"), {"role": "tool", "content": "c"}, result("call_2", "d")]
self.assertEqual(names(raw), [None, None, None, None])

def test_parallel_results_take_their_own_calls_names(self):
raw = [{"role": "user", "content": "Weather and time?"},
{"role": "assistant", "content": "", "tool_calls": [call("call_w", "get_weather"), call("call_t", "get_time")]},
result("call_t", "noon"), result("call_w", "18 C")]
messages = normalized(raw)
self.assertEqual([(m["content"], m["name"]) for m in messages[2:]], [("18 C", "get_weather"), ("noon", "get_time")])
# an incomplete run keeps its received order, and each result is still named by its id, not its position
raw = [{"role": "user", "content": "Three things?"},
{"role": "assistant", "content": "", "tool_calls": [call("call_1", "a"), call("call_2", "b"), call("call_3", "c")]},
result("call_3", "third"), result("call_1", "first")]
self.assertEqual([(m["content"], m["name"]) for m in normalized(raw)[2:]], [("third", "c"), ("first", "a")])

def test_a_reused_id_takes_the_nearest_earlier_call(self):
raw = [{"role": "user", "content": "Read, then write."},
{"role": "assistant", "content": "", "tool_calls": [call("call_1", "read_file")]}, result("call_1", "old"),
{"role": "assistant", "content": "", "tool_calls": [call("call_1", "write_file")]}, result("call_1", "ok")]
self.assertEqual(names(raw), ["read_file", "write_file"])
raw[3]["tool_calls"].append(call("call_1", "delete_file")) # twice in the second turn: that result is unnamed
self.assertEqual(names(raw), ["read_file", None])

def test_the_other_templates_render_the_same_with_names(self):
messages = normalized(history())
unnamed = copy.deepcopy(messages)
for m in unnamed:
m.pop("name", None)
self.assertEqual([m.get("name") for m in messages[2:]], ["read_file", "read_file"])
for path in (Path(__file__).with_name("chat_template.jinja"), DATA / "hy4" / "chat_template.jinja",
Path(__file__).resolve().parents[1] / "tools" / "qwen4_intake_fixtures" / "qwen3-0.6b.chat_template.jinja"):
with self.subTest(template=path.name, parent=path.parent.name):
template = ChatTemplate(path)
self.assertEqual(template.render(messages), template.render(unnamed))


if __name__ == "__main__":
unittest.main()
16 changes: 16 additions & 0 deletions terminal/serve/test_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,22 @@ def test_a_call_the_output_ends_inside_is_not_run(self):
self.assertNotIn('"call"', Path(self.log.name).read_text()) # nothing ran
self.assertEqual(cs[-1]["choices"][0]["finish_reason"], "stop")

def test_results_are_named_after_their_calls(self):
"""#7051: the template messages of the next round carry each result's tool name (Inkling's header reads it)."""
two = call_script("fake__add", a=2, b=3) + call_script("fake__echo", text="hi").split("Let me check.\n\n")[1]
self.start(two, "</think>\n\nDone.")
seen = []
encode = self.svc.encode_prompt

def spy(messages, *args, **kwargs):
seen.append(json.loads(json.dumps(messages)))
return encode(messages, *args, **kwargs)
self.svc.encode_prompt = spy
code, text = self.post({"strata_mcp": True}, stream=False)
self.assertEqual(code, 200, text)
tools = [(m["name"], m["content"]) for m in seen[-1] if m["role"] == "tool"]
self.assertEqual(tools, [("fake__add", "5"), ("fake__echo", "hi")])

def test_non_stream(self):
self.start(call_script("fake__add", a=2, b=3), "</think>\n\n5.")
code, text = self.post({"strata_mcp": True}, stream=False)
Expand Down
6 changes: 4 additions & 2 deletions terminal/serve/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,12 @@ def test_codex_history_becomes_one_assistant_turn_per_answer(self):
{"role": "assistant", "content": "Looking.", "reasoning_content": "look first", "tool_calls": [
{"function": {"name": "exec_command", "arguments": {"cmd": "cat a"}}},
{"function": {"name": "multi_agent_v1.spawn_agent", "arguments": {}}}]},
{"role": "tool", "content": "before"}, {"role": "tool", "content": "agent"},
# #7051: each result is named after its call, for templates that head a result with it (Inkling)
{"role": "tool", "content": "before", "name": "exec_command"},
{"role": "tool", "content": "agent", "name": "multi_agent_v1.spawn_agent"},
{"role": "assistant", "content": "", "reasoning_content": "now write", "tool_calls": [
{"function": {"name": "exec_command", "arguments": {"cmd": "w"}}}]},
{"role": "tool", "content": "ok"}])
{"role": "tool", "content": "ok", "name": "exec_command"}])

def test_reasoning_comes_back_from_our_encrypted_content_and_foreign_tokens_are_ignored(self):
enc = ENCRYPTED_PREFIX + base64.b64encode(json.dumps({"text": "hidden"}).encode()).decode()
Expand Down
4 changes: 2 additions & 2 deletions terminal/serve/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,10 +530,10 @@ def encode(self, source):
m, _, _ = anthropic_to_messages({"messages": [{"role": "user", "content": [good]}]})
with self.assertRaises(ValueError):
svc.prepare(m, None, {})
# a text-only tool result renders exactly as before: one string
# a text-only tool result renders exactly as before: one string (named after its call, #7051)
msgs = [{"role": "user", "content": "q"}, call,
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [{"type": "text", "text": "r"}]}]}]
self.assertEqual(anthropic_to_messages({"messages": msgs})[0][-1], {"role": "tool", "content": "r"})
self.assertEqual(anthropic_to_messages({"messages": msgs})[0][-1], {"role": "tool", "content": "r", "name": "Read"})


def test_the_whole_marker_in_text_before_images(self):
Expand Down
Loading