diff --git a/serve/frontend.py b/serve/frontend.py index c7b0d63a..e4810ac1 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -19,7 +19,9 @@ import json import logging import os import re +import threading import uuid +from collections import OrderedDict from dataclasses import dataclass, field from pathlib import Path @@ -350,6 +352,36 @@ def _object_list(value, name: str) -> list[dict]: return value +_TOOL_ORDERS: "OrderedDict[frozenset, tuple]" = OrderedDict() # a set of tool names -> the order it first came in +_TOOL_ORDERS_LOCK = threading.Lock() +_TOOL_ORDERS_MAX = 64 + + +def _stable_tool_order(tools: list[dict], name_of) -> list[dict]: + """The same set of tools comes back in the order it was first seen. Clients send their tools in the order their + MCP servers finished registering, which can differ from one request (or one client restart) to the next, and the + template renders the tool list before the system prompt: one swap moves the shared prefix back thousands of + tokens and the whole conversation is read again (opencode issue 23571). A request's first sight of a tool set + is untouched (so its prompt is byte for byte what the client sent); later requests with the same names in + another order are put back in that first order. Duplicate names, or a single tool: left as sent.""" + if len(tools) < 2: + return tools + names = [name_of(t) for t in tools] + if len(set(names)) != len(names): + return tools + key = frozenset(names) + with _TOOL_ORDERS_LOCK: + order = _TOOL_ORDERS.get(key) + if order is None: + _TOOL_ORDERS[key] = tuple(names) + while len(_TOOL_ORDERS) > _TOOL_ORDERS_MAX: + _TOOL_ORDERS.popitem(last=False) + return tools + _TOOL_ORDERS.move_to_end(key) + pos = {n: k for k, n in enumerate(order)} + return sorted(tools, key=lambda t: pos[name_of(t)]) + + def _tool_list(value, wrapper: str | None) -> list[dict]: """#592: a request's "tools" as a list of tool objects, each with a name - in the OpenAI shape {"type": "function", "function": {"name": ...}} (`wrapper` "function"; a bare {"name": ...} is still taken), or @@ -377,7 +409,7 @@ def _tool_list(value, wrapper: str | None) -> list[dict]: # AttributeError in the request thread - after the 200 and whatever the model had said before the call raise ValueError(f'tools[{i}] ({fn["name"]}): "{key}" must be an object (the JSON schema of its ' f"parameters), not {type(schema).__name__}") - return tools + return _stable_tool_order(tools, lambda t: (t.get(wrapper, t) if wrapper and t.get("type") == wrapper else t)["name"]) def tool_arguments(raw) -> dict: diff --git a/serve/test_server.py b/serve/test_server.py index 97313767..849e6761 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -5022,6 +5022,36 @@ class ClaudeCodeBillingStamp(unittest.TestCase): self.assertEqual(ids[1][:len(first) - 8], first[:len(first) - 8]) # all but the generation header +class ToolOrder(unittest.TestCase): + """A tool set that comes back in another order is put back in the order it was first seen (RealScaniX, #1624): the + template renders the tool list before the system prompt, so a client whose MCP tools register in a varying order + would move the shared prefix back thousands of tokens on every turn and have the conversation read again. The + first request of a set is left exactly as sent.""" + + def names(self, tools, wrapper="function"): + from serve.frontend import _tool_list + return [t.get(wrapper, t)["name"] for t in _tool_list(tools, wrapper)] + + def test_openai_shape_keeps_the_first_order(self): + a = [{"type": "function", "function": {"name": n}} for n in ("t1624_read", "t1624_rbash", "t1624_ctx7")] + self.assertEqual(self.names(a), ["t1624_read", "t1624_rbash", "t1624_ctx7"]) # the first sight: as sent + self.assertEqual(self.names(list(reversed(a))), ["t1624_read", "t1624_rbash", "t1624_ctx7"]) + self.assertEqual(self.names(a[1:] + a[:1]), ["t1624_read", "t1624_rbash", "t1624_ctx7"]) + + def test_anthropic_shape_and_a_different_set(self): + a = [{"name": "t1624_read", "input_schema": {}}, {"name": "t1624_edit", "input_schema": {}}] + self.assertEqual(self.names(a, None), ["t1624_read", "t1624_edit"]) + self.assertEqual(self.names(a[::-1], None), ["t1624_read", "t1624_edit"]) + more = a[::-1] + [{"name": "t1624_new", "input_schema": {}}] # another set: as sent, then remembered + self.assertEqual(self.names(more, None), ["t1624_edit", "t1624_read", "t1624_new"]) + + def test_duplicate_names_and_one_tool_are_left_alone(self): + d = [{"name": "t1624_x", "input_schema": {}}, {"name": "t1624_x", "input_schema": {"a": 1}}] + self.assertEqual(self.names(d, None), ["t1624_x", "t1624_x"]) + one = [{"name": "t1624_only", "input_schema": {}}] + self.assertEqual(self.names(one, None), ["t1624_only"]) + + class UntimedReads(unittest.TestCase): """#1317: a read of the engine's READY line or of the image encoder's pipe that never returns held the request turn for good. Each now has a timeout; a process that stays silent is ended and the read raises."""