okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
112.6 KiB2108 linesraw
1"""serve/frontend.py - plan v0.3 P8: the request/response layer between API clients and the engine.
2
3Everything here is text: no model, no GPU. The engine consumes token ids and produces text deltas; this module
4
5  * normalizes OpenAI Chat Completions and Anthropic Messages requests into the chat template's message form,
6  * renders the model's own Jinja chat template (pack `tokenizer/chat_template.jinja`) exactly as Hugging Face
7    does (checked against the pack's `chat_golden.json`, 10 cases incl. thinking and tools),
8  * parses the streamed output incrementally into reasoning (`<think>...</think>`), content and tool calls in
9    the template's XML form (`<tool_call><function=NAME><parameter=P>VALUE</parameter>...</function></tool_call>`),
10    never emitting a partial tag to the client.
11
12Design note: plan v0.3 describes a single C++ process. The frontend is Python first because the template is Jinja
13and the formats change often; the engine boundary is token ids in, text deltas out, which keeps a later C++ port
14(or a pybind wrapper) a local change.
15"""
16from __future__ import annotations
17
18import json
19import logging
20import os
21import re
22import threading
23import uuid
24from collections import OrderedDict
25from dataclasses import dataclass, field
26from pathlib import Path
27
28import jinja2
29from jinja2.sandbox import ImmutableSandboxedEnvironment
30
31LOGGER = logging.getLogger(__name__)
32
33
34# ------------------------------------------------------------------------------------------------ template
35class TemplateRequestError(jinja2.exceptions.TemplateError, ValueError):
36    """The template refused the request's messages (e.g. "No user query found in messages."): a ValueError, so the
37    client gets a 400 with the template's message instead of a dropped connection (#365)."""
38
39
40class ChatTemplate:
41    """The model's chat template, rendered with the same Jinja settings as transformers' apply_chat_template."""
42
43    def __init__(self, path: str | Path):
44        def raise_exception(message):
45            raise TemplateRequestError(message)
46
47        def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
48            return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys)
49
50        env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=["jinja2.ext.loopcontrols"])
51        env.filters["tojson"] = tojson
52        env.globals["raise_exception"] = raise_exception
53        self.source = Path(path).read_text(encoding="utf-8")
54        self.template = env.from_string(self.source)
55        self.caps = self._detect_caps()
56
57    def render(self, messages: list[dict], tools: list[dict] | None = None, add_generation_prompt: bool = True,
58               **kwargs) -> str:
59        # Do not use completed empty assistant turns as examples for the next reply. Keep the final message.
60        # (#843.  STRATA_KEEP_EMPTY_TURNS=1 renders them as before.)
61        messages = [m for i, m in enumerate(messages)
62                    if i == len(messages) - 1 or os.environ.get("STRATA_KEEP_EMPTY_TURNS") == "1" or not (isinstance(m, dict) and m.get("role") == "assistant"
63                                                      and not _text_of(m.get("content")).strip()
64                                                      and not _has_image(m.get("content")) and not m.get("tool_calls"))]
65        return self.template.render(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt,
66                                    **kwargs)
67
68    def _detect_caps(self) -> dict[str, bool]:
69        """llama.cpp's capability names, checked at load time against this template and Strata's tool-call format.
70        These are rendering hints, not a guarantee that the model will follow a request."""
71        def render(messages, tools=None):
72            try:
73                return self.render(messages, tools=tools)
74            except Exception as exc:                # noqa: BLE001 - a hint only: never stop the server for a probe
75                # A template may reject a role or feature (a custom one may fail in any way): the feature is off,
76                # discovery still answers for the others, and the start-up goes on.
77                LOGGER.debug("chat template capability probe failed: %s", exc, exc_info=True)
78                return ""
79
80        user = {"role": "user", "content": "strata_caps_user"}
81        tools = [{"name": f"strata_caps_call_{i}", "description": "strata_caps_description",
82                  "parameters": {"type": "object", "properties": {"arg": {"type": "string"}}}}
83                 for i in range(2)]
84        tool_prompt = render([user], tools)
85
86        def calls_supported(count):
87            calls = [{"name": f"strata_caps_call_{i}", "arguments": {"arg": f"strata_caps_arg_{i}"}}
88                     for i in range(count)]
89            messages = [user, {"role": "assistant", "content": "",
90                               "tool_calls": [{"function": call} for call in calls]}]
91            replies = [f"strata_caps_result_{i}" for i in range(count)]
92            messages += [{"role": "tool", "content": reply} for reply in replies] + [user]
93            prompt = render(messages, tools)
94            # Instructions include example XML and literal tag names, which are not model output. Parse only
95            # complete calls to our probe functions, using the same body parser as OutputParser.
96            bodies = re.findall(r"<tool_call>\s*(<function=strata_caps_call_\d+>.*?</function>)\s*</tool_call>",
97                                prompt, re.S)
98            try:
99                parsed = [parse_tool_call(body) for body in bodies]
100            except ValueError:
101                return False
102            return [{"name": call.name, "arguments": call.arguments} for call in parsed] == calls \
103                and all(reply in prompt for reply in replies)
104
105        history = [user, {"role": "assistant", "content": "strata_caps_answer",
106                          "reasoning_content": "strata_caps_reasoning"}, user]
107        return {"supports_tools": all(s in tool_prompt for s in
108                                      ("strata_caps_call_0", "strata_caps_description", "<tool_call>", "<function=")),
109                "supports_tool_calls": calls_supported(1),
110                "supports_system_role": "strata_caps_system" in render(
111                    [{"role": "system", "content": "strata_caps_system"}, user]),
112                "supports_parallel_tool_calls": calls_supported(2),
113                "supports_preserve_reasoning": "strata_caps_reasoning" in render(history)}
114
115
116# ------------------------------------------------------------------------------------------------ requests
117# The content-part types the readers take as text (a part with no type that has a "text" field reads as text too)
118TEXT_PARTS = ("text", "input_text", None)
119
120
121def _text_of(content) -> str:
122    if content is None:
123        return ""
124    if isinstance(content, str):
125        return content
126    return "".join(part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") in
127                   TEXT_PARTS)
128
129
130IMAGE_PARTS = ("image_url", "input_image", "image")
131
132# Thinking levels.  The model's template knows low, medium and xhigh (its default; "high" means xhigh), and
133# enable_thinking=false for none.  Clients spell these many ways; everything maps onto those four.
134EFFORT = {"none": None, "off": None, "minimal": None, "disabled": None, "false": None,
135          "low": "low", "medium": "medium", "high": "xhigh", "xhigh": "xhigh", "max": "xhigh", "maximum": "xhigh"}
136
137
138# DeepSeek-V4.1's template takes low, medium, high (its default) and max, or a whole number 1..100 (the "Reasoning
139# Effort: N" line of its prompt).  use_family("deepseek41") switches the table; the other families keep the one above.
140EFFORT_DEEPSEEK = {"none": None, "off": None, "minimal": None, "disabled": None, "false": None,
141                   "low": "low", "medium": "medium", "high": "high", "xhigh": "max", "max": "max", "maximum": "max"}
142_EFFORT_QWEN = dict(EFFORT)
143_NUMERIC_EFFORT = False
144
145
146def use_family(family: str | None) -> None:
147    """The reasoning-effort words of the model family this server runs (module state, like ENV_TO_USER)."""
148    global _NUMERIC_EFFORT
149    EFFORT.clear()
150    EFFORT.update(EFFORT_DEEPSEEK if family == "deepseek41" else _EFFORT_QWEN)
151    _NUMERIC_EFFORT = family == "deepseek41"
152
153
154def effort_kwargs(value) -> dict:
155    """A reasoning effort as given by a client -> the template's kwargs.  Unknown values are a 400, not a crash."""
156    if value is None or value == "":
157        return {}
158    if value is False:
159        return {"enable_thinking": False}
160    if _NUMERIC_EFFORT and isinstance(value, int) and not isinstance(value, bool):
161        if not 1 <= value <= 100:
162            raise ValueError(f"unknown reasoning effort {value!r}: use none, low, medium, high, max or 1..100")
163        return {"reasoning_effort": value}
164    key = str(value).strip().lower()
165    if key not in EFFORT:
166        raise ValueError(f"unknown reasoning effort {value!r}: use none, low, medium or high"
167                         + (", max or 1..100" if _NUMERIC_EFFORT else ""))
168    level = EFFORT[key]
169    return {"enable_thinking": False} if level is None else {"reasoning_effort": level}
170
171
172def budget_effort(tokens) -> dict:
173    """Anthropic's thinking budget (budget_tokens) -> a level: under 2K low, under 8K medium, else high."""
174    try:
175        n = int(tokens)
176    except (TypeError, ValueError):
177        return {}
178    return {"reasoning_effort": "low" if n < 2048 else "medium" if n < 8192 else EFFORT["high"]}
179
180
181def _has_image(content) -> bool:
182    return isinstance(content, list) and any(isinstance(p, dict) and p.get("type") in IMAGE_PARTS for p in content)
183
184
185def _image_source(part: dict) -> str:
186    """An image part's source as one string: a data: URL, an http(s) URL or a local file path.
187    OpenAI: {"type": "image_url", "image_url": {"url": ...}} (or "image_url": "..."), Responses-style
188    {"type": "input_image", "image_url": ...}; Anthropic: {"type": "image", "source": {"type": "base64",
189    "media_type": ..., "data": ...}} or {"source": {"type": "url", "url": ...}}."""
190    if part.get("type") == "image":
191        src = part.get("source") or {}
192        if src.get("type") == "base64":
193            return f"data:{src.get('media_type', 'image/png')};base64,{src.get('data', '')}"
194        return src.get("url") or src.get("path") or ""
195    url = part.get("image_url")
196    if isinstance(url, dict):
197        url = url.get("url")
198    return url or ""
199
200
201def _parts_of(content):
202    """Message content for the template: a string when there is no image (unchanged behaviour), otherwise the
203    template's list form - text items and image items, in order - whose image items carry their source."""
204    if not _has_image(content):
205        return _text_of(content)
206    items = []
207    for part in content:
208        if not isinstance(part, dict):
209            continue
210        if part.get("type") in IMAGE_PARTS:
211            items.append({"type": "image", "source": _image_source(part)})
212        elif part.get("type") in TEXT_PARTS and "text" in part:
213            items.append({"type": "text", "text": part.get("text", "")})
214    return items
215
216
217# The blocks a messages request may carry: text, the image parts, thinking, tool_use and tool_result.
218# redacted_thinking is allowed only to be dropped without an error: another server's encrypted reasoning, which
219# carries nothing this server can read - the same reason responses.py's _reasoning_text gives for another server's
220# encrypted_content.
221ANTHROPIC_BLOCKS = ("text",) + IMAGE_PARTS + ("thinking", "tool_use", "tool_result", "redacted_thinking")
222
223
224def _check_parts(content, path: str, kinds):
225    """A request's content parts (on chat) or content blocks (on messages), looked at while the request is converted.
226    A part whose type this server does not read (a file, audio, a document, Anthropic's tool_reference,
227    search_result, server_tool_use / web_search_tool_result blocks, ...) is left out of the prompt exactly as it always
228    was, with a debug line: real clients (Claude Code, Codex, opencode, Cline, Continue, Open WebUI) send such parts
229    next to text the model can answer from, so refusing them would break requests that work.  A "refusal" part is read
230    as its text, as /v1/responses does.  Content that is not a list, and a part that is not an object, passes through
231    unchanged."""
232    if not isinstance(content, list):
233        return content
234    out = content
235    for j, part in enumerate(content):
236        if not isinstance(part, dict):
237            continue
238        kind = part.get("type")
239        if kind == "refusal":
240            if out is content:
241                out = list(content)
242            out[j] = {"type": "text", "text": part.get("refusal") or ""}
243        elif kind not in kinds:
244            LOGGER.debug("%s[%d].type: content part of type %r is not read by this server; left out of the prompt",
245                         path, j, kind)
246    return out
247
248
249def images_of(messages: list[dict]) -> list[str]:
250    """The image sources of the rendered conversation, in prompt order (the template renders one
251    <|vision_start|><|image_pad|><|vision_end|> per image item, message by message)."""
252    return [item["source"] for m in messages if isinstance(m.get("content"), list)
253            for item in m["content"] if item.get("type") == "image"]
254
255
256# #537: a literal <think> / </think> inside a message's text is plain text, not the model's reasoning markers.  The
257# tokenizer matches those two strings as their special tokens everywhere (GGUF token type 4, as llama.cpp does), so
258# a user quoting "</think>" used to hand the model a real end-of-reasoning token.  Before the template is rendered
259# they are swapped for these private-use characters, and the server encodes the spans they mark as ordinary text.
260THINK_TAGS = {"<think>": "\U000F0E01", "</think>": "\U000F0E02"}
261# #554: the vision markers the same way.  They are special tokens only where the template writes them for an image
262# item; the same strings in a message's text (an agent reading chat_template.jinja, a tool result quoting it) became
263# the same special ids, so text with <|vision_start|><|image_pad|> before a picture took that picture's embeddings
264VISION_TAGS = {"<|vision_start|>": "\U000F0E03", "<|image_pad|>": "\U000F0E04", "<|vision_end|>": "\U000F0E05",
265               "<|video_pad|>": "\U000F0E06"}
266# #2026: `</tool_call>` the same way.  A user asking for the string verbatim handed the model the real end-of-call token
267# (type 4, matched everywhere); it copied that token into its answer and the reply came back empty.  An assistant
268# message keeps its own: a client replaying the model's raw call text sends the tokens the model wrote.
269# 0.1.44: `<tool_call>`, `<tool_response>` and `</tool_response>` are type 4 too (ids 248058, 248066, 248070), so a quoted
270# one handed the model the real call / tool-result marker in the same way (found by 47Hunter47 in #2026).  The template
271# writes the tool-result markers around a tool message itself; only the text inside a message is marked.
272TOOL_LITERAL_TAGS = {"</tool_call>": "\U000F0E07", "<tool_call>": "\U000F0E08", "<tool_response>": "\U000F0E09",
273                     "</tool_response>": "\U000F0E0A"}
274LITERAL_TAGS = {**THINK_TAGS, **VISION_TAGS, **TOOL_LITERAL_TAGS}
275THINK_MARKS = {v: k for k, v in LITERAL_TAGS.items()}
276CONTROL_MARK0 = 0xF0E10      # the control tokens' marks start here, clear of the two sets above
277
278
279def literal_tags(controls) -> dict[str, str]:
280    """LITERAL_TAGS plus a mark for each control token's text (`controls`: the tokenizer's CONTROL literals,
281    <|im_start|>, <|im_end|>, <|endoftext|>, ...).  The rendered prompt is encoded with those literals parsed, so one
282    written inside a message - a file an agent reads, a pasted chat template - opened or ended a turn there.  Longest
283    first, as the tokenizer matches them: a literal inside a longer one is not marked before it."""
284    tags = {**LITERAL_TAGS, **{c: chr(CONTROL_MARK0 + k) for k, c in enumerate(c for c in controls
285                                                                                if c not in LITERAL_TAGS)}}
286    return dict(sorted(tags.items(), key=lambda t: -len(t[0])))
287
288
289def _mark(text: str, tags: dict[str, str] = LITERAL_TAGS) -> str:
290    for tag, mark in tags.items():
291        text = text.replace(tag, mark)
292    return text
293
294
295def _mark_deep(v, tags: dict[str, str] = LITERAL_TAGS):
296    if isinstance(v, str):
297        return _mark(v, tags)
298    if isinstance(v, dict):
299        return {k: _mark_deep(x, tags) for k, x in v.items()}
300    if isinstance(v, list):
301        return [_mark_deep(x, tags) for x in v]
302    return v
303
304
305def _has_tag(v, tags: dict[str, str] = LITERAL_TAGS) -> bool:
306    if isinstance(v, str):
307        return any(tag in v for tag in tags)
308    if isinstance(v, dict):
309        return any(_has_tag(x, tags) for x in v.values())
310    if isinstance(v, list):
311        return any(_has_tag(x, tags) for x in v)
312    return False
313
314
315_TOOL_RESULT_OPEN, _TOOL_RESULT_CLOSE = "<tool_response>", "</tool_response>"
316
317
318def _keep_tool_result_wrap(content, tags: dict[str, str]):
319    """A user message whose whole text is <tool_response>...</tool_response> (a client that formats a tool result the way
320    the template does for a tool message) keeps that outer pair as the markers - the template tells such a turn from a
321    real question by exactly that pair - and only the text inside is marked.  None: not such a message."""
322    o, c = _TOOL_RESULT_OPEN, _TOOL_RESULT_CLOSE
323
324    def wrap(text: str, first: bool, last: bool) -> str:
325        i = text.index(o) + len(o) if first else 0
326        j = text.rindex(c) if last else len(text)
327        head = _mark(text[:i - len(o)], tags) + o if first else ""
328        tail = c + _mark(text[j + len(c):], tags) if last else ""
329        return head + _mark(text[i:j], tags) + tail
330
331    if isinstance(content, str):
332        body = content.strip()
333        if len(body) >= len(o) + len(c) and body.startswith(o) and body.endswith(c):
334            return wrap(content, True, True)
335        return None
336    if not (isinstance(content, list) and content and all(isinstance(x, dict) and "text" in x for x in content)):
337        return None
338    texts = [x["text"] for x in content]
339    if not all(isinstance(t, str) for t in texts):
340        return None
341    body = "".join(texts).strip()
342    if not (len(body) >= len(o) + len(c) and body.startswith(o) and body.endswith(c)):
343        return None
344    if not (texts[0].lstrip().startswith(o) and texts[-1].rstrip().endswith(c)):
345        return None          # the pair is split across parts: mark it all, as before
346    if len(content) == 1:
347        return [{**content[0], "text": wrap(texts[0], True, True)}]
348    return ([{**content[0], "text": wrap(texts[0], True, False)}] +
349            [_mark_deep(x, tags) for x in content[1:-1]] +
350            [{**content[-1], "text": wrap(texts[-1], False, True)}])
351
352
353def mark_think_literals(messages: list[dict], tools: list[dict] | None, tags: dict[str, str] = LITERAL_TAGS):
354    """#537: (messages, tools) with every literal <think> / </think> (#554: and vision marker) in their text swapped for
355    LITERAL_TAGS' marks (or `tags`': literal_tags() adds the control tokens' texts), and
356    whether there was one (None: no change, the same objects back - a prompt without them renders as it always did).
357    An assistant message whose content opens with a whole <think>...</think> block (clients that send the reasoning
358    inline) keeps that one block as the model's markers, as before."""
359    if not _has_tag(messages, tags) and not _has_tag(tools, tags):
360        return messages, tools, False
361    out = []
362    own = {t: v for t, v in tags.items() if t not in TOOL_LITERAL_TAGS}     # what an assistant message keeps as written
363    for m in messages:
364        m = dict(m)
365        content = m.get("content")
366        mine = own if m.get("role") == "assistant" else tags
367        for k, v in m.items():
368            if k != "role":
369                m[k] = _mark_deep(v, mine)
370        if m.get("role") == "user":
371            kept = _keep_tool_result_wrap(content, tags)
372            if kept is not None:
373                m["content"] = kept
374        if m.get("role") == "assistant" and isinstance(content, str) and content.lstrip().startswith("<think>") \
375                and "</think>" in content:
376            i, j = content.index("<think>") + len("<think>"), content.index("</think>")
377            m["content"] = (content[:i] + _mark(content[i:j], own) + "</think>" +
378                            _mark(content[j + len("</think>"):], own))
379        out.append(m)
380    return out, _mark_deep(tools, tags), True
381
382
383_THINK_MARK_RE = re.compile("|".join(THINK_MARKS))
384
385
386def unmark_think_literals(prompt: str, tags: dict[str, str] = LITERAL_TAGS) -> tuple[str, list[tuple[int, int]]]:
387    """The rendered prompt with THINK_TAGS' marks turned back into the tags' text, and the (start, end) spans of those
388    tags in it: the server encodes them as ordinary text (the tokenizer's encode_plain_spans)."""
389    marks = THINK_MARKS if tags is LITERAL_TAGS else {v: k for k, v in tags.items()}
390    if marks and all(len(k) == 1 for k in marks):
391        # one character each: a range of code points is scanned ~20x faster than their alternation (13 ms for an
392        # 80K-token prompt), and a character in the range that is no mark is skipped below
393        lo, hi = min(marks), max(marks)
394        mark_re = re.compile(f"[{re.escape(lo)}-{re.escape(hi)}]")
395    else:
396        mark_re = _THINK_MARK_RE if tags is LITERAL_TAGS else re.compile("|".join(map(re.escape, marks)))
397    out, spans, pos, n = [], [], 0, 0
398    for m in mark_re.finditer(prompt):
399        tag = marks.get(m.group(0))
400        if tag is None:
401            continue
402        out.append(prompt[pos:m.start()])
403        n += m.start() - pos
404        out.append(tag)
405        spans.append((n, n + len(tag)))
406        n += len(tag)
407        pos = m.end()
408    out.append(prompt[pos:])
409    return "".join(out), spans
410
411
412# Config "env_to_user" (opt-in): opencode writes its <env> block (working directory, today's date) near the START of
413# the system message, before ~40K characters of instructions and tool definitions that are the same in every session.
414# The prefix cache only reuses a prompt's start, so a new folder or a new day read all of it again (~14K tokens, 8-11 s).
415# Moved to the front of the first user message, the system turn (and the tools the template writes into it) is the same
416# for every session and the disk prefix cache restores it.  The model still sees the same lines, one turn later.
417ENV_TO_USER = False
418_ENV_BLOCK = re.compile(r"(?:[^\n]*environment you are running in:\n)?<env>\n.*?\n</env>\n?", re.S)
419
420
421def _env_to_user(messages: list[dict]) -> list[dict]:
422    if not ENV_TO_USER or not messages or messages[0].get("role") != "system":
423        return messages
424    sys_text = messages[0].get("content")
425    if not isinstance(sys_text, str):
426        return messages
427    m = _ENV_BLOCK.search(sys_text)
428    if m is None:
429        return messages
430    for i in range(1, len(messages)):
431        if messages[i].get("role") != "user":
432            continue
433        block = m.group(0).rstrip("\n")
434        c = messages[i].get("content")
435        if isinstance(c, str):
436            nc = block + "\n\n" + c
437        elif isinstance(c, list):
438            nc = [{"type": "text", "text": block + "\n\n"}] + c
439        else:
440            return messages
441        out = list(messages)
442        out[0] = dict(messages[0], content=sys_text[:m.start()] + sys_text[m.end():])
443        out[i] = dict(messages[i], content=nc)
444        return out
445    return messages
446
447
448def _late_system_to_user(messages: list[dict]) -> list[dict]:
449    """The chat template takes a system message only at the start ("System message must be at the beginning").
450    Clients also send them mid-conversation - Claude Code's hook context as {"role": "system"} after the first user
451    turn, some OpenAI clients a late "developer" message (issue #56) - so those become user messages, in place:
452    merging them into the first one would change the prompt's start and cost the conversation cache every turn."""
453    return [dict(m, role="user") if m.get("role") == "system" and i > 0 else m for i, m in enumerate(messages)]
454
455
456def _object_list(value, name: str) -> list[dict]:
457    """#460: a request's "messages" (or a message's "tool_calls") as a list of objects.  Some clients send the array
458    double-encoded, as a JSON string, which used to be iterated character by character and crashed on m.get: such a
459    string is decoded.  Anything that is still not a list of objects is a ValueError, which the server answers with
460    a 400 naming the field.  None (or no field) is an empty list, as a missing field always was."""
461    if value is None:
462        return []
463    if isinstance(value, str):
464        try:
465            value = json.loads(value)
466        except ValueError:
467            raise ValueError(f"{name} must be a list of objects (a string was sent that is not JSON)") from None
468    if not isinstance(value, list) or not all(isinstance(m, dict) for m in value):
469        raise ValueError(f"{name} must be a list of objects")
470    return value
471
472
473_TOOL_ORDERS: "OrderedDict[frozenset, tuple]" = OrderedDict()   # a set of tool names -> the order it first came in
474_TOOL_ORDERS_LOCK = threading.Lock()
475_TOOL_ORDERS_MAX = 64
476
477
478def _stable_tool_order(tools: list[dict], name_of) -> list[dict]:
479    """The same set of tools comes back in the order it was first seen.  Clients send their tools in the order their
480    MCP servers finished registering, which can differ from one request (or one client restart) to the next, and the
481    template renders the tool list before the system prompt: one swap moves the shared prefix back thousands of
482    tokens and the whole conversation is read again (opencode issue 23571).  A request's first sight of a tool set
483    is untouched (so its prompt is byte for byte what the client sent); later requests with the same names in
484    another order are put back in that first order.  Duplicate names, or a single tool: left as sent."""
485    if len(tools) < 2:
486        return tools
487    names = [name_of(t) for t in tools]
488    if len(set(names)) != len(names):
489        return tools
490    key = frozenset(names)
491    with _TOOL_ORDERS_LOCK:
492        order = _TOOL_ORDERS.get(key)
493        if order is None:
494            _TOOL_ORDERS[key] = tuple(names)
495            while len(_TOOL_ORDERS) > _TOOL_ORDERS_MAX:
496                _TOOL_ORDERS.popitem(last=False)
497            return tools
498        _TOOL_ORDERS.move_to_end(key)
499    pos = {n: k for k, n in enumerate(order)}
500    return sorted(tools, key=lambda t: pos[name_of(t)])
501
502
503def _tool_list(value, wrapper: str | None) -> list[dict]:
504    """#592: a request's "tools" as a list of tool objects, each with a name - in the OpenAI shape
505    {"type": "function", "function": {"name": ...}} (`wrapper` "function"; a bare {"name": ...} is still taken), or
506    in the Anthropic shape {"name": ...} (`wrapper` None).  A value that is not (a string such as "auto", a list of
507    names, an object without a name) is a ValueError - a 400 naming the field - where it used to take the request
508    thread down with no reply at all.  No value (or an empty one) is no tools, as always.  A tool's schema -
509    "parameters" in the OpenAI shape, "input_schema" in the Anthropic one - is an object when it is there, for the
510    same reason: a string or a list passed and raised later instead, on the model's first call of that tool."""
511    if not value:
512        return []
513    shape = ('{"type": "function", "function": {"name": ..., "parameters": {...}}}' if wrapper else
514             '{"name": ..., "input_schema": {...}}')
515    try:
516        tools = _object_list(value, "tools")
517    except ValueError:
518        raise ValueError(f"tools must be a list of tool objects, each {shape}") from None
519    key = "parameters" if wrapper else "input_schema"
520    for i, t in enumerate(tools):
521        fn = t.get(wrapper, t) if wrapper and t.get("type") == wrapper else t
522        if not isinstance(fn, dict) or not isinstance(fn.get("name"), str) or not fn["name"]:
523            raise ValueError(f"tools[{i}] has no name: each tool must be {shape}")
524        schema = fn.get(key)
525        if schema is not None and not isinstance(schema, dict):
526            # it reached parse_tool_call and the stream parser as the tool's schema, whose .get("properties") raised
527            # AttributeError in the request thread - after the 200 and whatever the model had said before the call
528            raise ValueError(f'tools[{i}] ({fn["name"]}): "{key}" must be an object (the JSON schema of its '
529                             f"parameters), not {type(schema).__name__}")
530    return _stable_tool_order(tools, lambda t: (t.get(wrapper, t) if wrapper and t.get("type") == wrapper else t)["name"])
531
532
533def tool_arguments(raw) -> dict:
534    """A call's arguments from a client's history -> the mapping the template renders (both APIs).  A JSON object
535    (as text or already parsed) is used as it is; empty is {}; anything else (cut-off or malformed JSON, a list, a
536    number) is kept as text under "arguments" instead of refusing the whole conversation (#510)."""
537    if raw is None or (isinstance(raw, str) and not raw.strip()):
538        return {}
539    if isinstance(raw, dict):
540        return raw
541    if isinstance(raw, str):
542        try:
543            value = json.loads(raw)
544        except ValueError:
545            return {"arguments": raw}
546        return value if isinstance(value, dict) else {"arguments": raw}
547    return {"arguments": json.dumps(raw, ensure_ascii=False)}
548
549
550def require_messages(messages: list) -> None:
551    """A chat request with no message at all is a 400 (OpenAI: "empty array. Expected an array with minimum length 1"); the
552    template would otherwise render just the assistant turn and the model would answer nothing."""
553    if not messages:
554        raise ValueError("messages must be a non-empty list: send at least one message")
555
556
557def _order_chat_tool_results(messages: list[dict]) -> None:
558    """The template pairs results by position, so restore call order while IDs are still available.
559
560    Only a complete, unambiguous run of results is reordered. Legacy or incomplete histories keep their
561    received order. IDs are private to this conversion and never reach the template.
562    """
563    i = 0
564    while i < len(messages):
565        if messages[i]["role"] != "tool":
566            i += 1
567            continue
568        j = i + 1
569        while j < len(messages) and messages[j]["role"] == "tool":
570            j += 1
571        prev = messages[i - 1] if i else {}
572        calls = [c.get("_call_id") for c in prev.get("tool_calls") or []] if prev.get("role") == "assistant" else []
573        results = [m.get("_call_id") for m in messages[i:j]]
574        if len(calls) == len(results) and all(isinstance(cid, str) and cid for cid in calls + results):
575            if len(set(calls)) == len(calls) and len(set(results)) == len(results) and set(calls) == set(results):
576                rank = {cid: n for n, cid in enumerate(calls)}
577                messages[i:j] = sorted(messages[i:j], key=lambda m: rank[m["_call_id"]])
578        i = j
579    for message in messages:
580        message.pop("_call_id", None)
581        for call in message.get("tool_calls") or []:
582            call.pop("_call_id", None)
583
584
585def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:
586    """OpenAI Chat Completions -> (template messages, template tools, template kwargs)."""
587    messages = []
588    for i, m in enumerate(_object_list(req.get("messages"), "messages")):
589        role = m.get("role")
590        if role == "developer":
591            role = "system"
592        # an image is read in a user, tool or assistant message; the system prompt takes text only, as _text_of reads
593        images = role in ("user", "tool", "assistant")
594        content = _check_parts(m.get("content"), f"messages[{i}].content",
595                               TEXT_PARTS + IMAGE_PARTS if images else TEXT_PARTS)
596        out = {"role": role, "content": _parts_of(content) if images else _text_of(content)}
597        if role == "tool":
598            out["_call_id"] = m.get("tool_call_id")
599        if m.get("reasoning_content"):
600            out["reasoning_content"] = m["reasoning_content"]
601        if m.get("tool_calls"):
602            calls = []
603            for c in _object_list(m["tool_calls"], "tool_calls"):
604                fn = c.get("function", c)
605                if not isinstance(fn, dict):
606                    raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)")
607                calls.append({"function": {"name": fn.get("name"), "arguments": tool_arguments(fn.get("arguments"))},
608                              "_call_id": c.get("id")})
609            out["tool_calls"] = calls
610        messages.append(out)
611    _order_chat_tool_results(messages)
612    tools = [t.get("function", t) if t.get("type") == "function" else t
613             for t in _tool_list(req.get("tools"), "function")] or None
614    kwargs = {}
615    # OpenAI Chat Completions: "reasoning_effort"; Responses style: "reasoning": {"effort": ...}
616    reasoning = req.get("reasoning") if isinstance(req.get("reasoning"), dict) else {}
617    given = req.get("reasoning_effort")
618    # `false` is a level (thinking off, effort_kwargs): an `or` between the two fields dropped it
619    kwargs.update(effort_kwargs(given if given is not None and given != "" else reasoning.get("effort")))
620    # the vLLM / llama.cpp convention: {"chat_template_kwargs": {"enable_thinking": false, "reasoning_effort": "low"}}
621    for k, v in (req.get("chat_template_kwargs") or {}).items():
622        if k == "enable_thinking" and not v:
623            kwargs = {"enable_thinking": False}
624        elif k == "reasoning_effort" and "enable_thinking" not in kwargs:
625            kwargs.update(effort_kwargs(v))
626    return _env_to_user(_late_system_to_user(messages)), tools, kwargs
627
628
629BILLING_HEADER = "x-anthropic-billing-header:"
630
631
632def pin_billing_stamp(system: str) -> str:
633    """Claude Code starts its system prompt with `x-anthropic-billing-header: cc_version=2.1.170.bf4;
634    cc_entrypoint=sdk-cli; cch=b145e;`.  cch changes on EVERY request and the version's 4th part on every session, so
635    the prompt changed ~22K tokens in (after the tool list) on every turn and the conversation cache could only reuse
636    up to its last 16K checkpoint: half of every agent prompt was read again.  Both stamps are pinned to f's, as
637    llama.cpp does (ggml-org/llama.cpp#21793); only a header at the very start of the system text is touched, and
638    only inside its first 160 characters."""
639    if not system.startswith(BILLING_HEADER):
640        return system
641    s = list(system)
642    cch = system.find("cch=", len(BILLING_HEADER))
643    if 0 <= cch <= 160:
644        v, end = cch + 4, system.find(";", cch + 4)
645        if end > v and end - v <= 16:
646            s[v:end] = "f" * (end - v)
647    cv = system.find("cc_version=")
648    if 0 <= cv <= 160:
649        v, end = cv + len("cc_version="), system.find(";", cv)
650        if v < end and end - v <= 64:
651            parts = system[v:end].split(".")
652            if len(parts) > 3:
653                tail = v + len(".".join(parts[:3])) + 1
654                s[tail:end] = "f" * (end - tail)
655    return "".join(s)
656
657
658def _anthropic_tool(t: dict) -> dict:
659    """An Anthropic tool -> the template's form of it (also what the output parser reads its schema from)."""
660    return {"name": t["name"], "description": t.get("description", ""), "parameters": t.get("input_schema", {})}
661
662
663def anthropic_tools(req: dict) -> tuple[list[dict] | None, bool]:
664    """#4663, Anthropic's tool search: (every tool the request declared, the `defer_loading` ones included, whether any
665    tool is deferred).  A deferred tool is callable although the prompt does not list it.  A client that defers tools
666    (Claude Code) holds back more than it declares - it names the rest in the conversation and runs a call for any of
667    them - so with one deferred tool a call for an undeclared name is a call too (OutputParser's `deferred`)."""
668    tools = _tool_list(req.get("tools"), None)
669    return [_anthropic_tool(t) for t in tools] or None, any(t.get("defer_loading") for t in tools)
670
671
672def _tool_references(content, deferred: dict):
673    """A tool_result's tool_reference blocks (a tool search's results) -> the referenced deferred tools' definitions,
674    in the form the prompt lists tools: the model sees a tool where it was loaded, and the prompt's start (its tool
675    list) stays the same, so the prompt cache does too.  Any other reference is left out as before (_check_parts): a
676    listed tool is in the prompt already, and an old one (its MCP server gone) must not fail the rest of the session."""
677    if not isinstance(content, list):
678        return content
679    return [{"type": "text", "text": "<tools>\n" + json.dumps(deferred[p.get("tool_name")], ensure_ascii=False) + "\n</tools>"}
680            if isinstance(p, dict) and p.get("type") == "tool_reference" and isinstance(p.get("tool_name"), str)
681            and p["tool_name"] in deferred else p
682            for p in content]
683
684
685def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[dict], list[dict] | None, dict]:
686    """Anthropic Messages -> (template messages, template tools, template kwargs).  `think_unasked`: a request
687    without "thinking", an effort or a budget gets the template's default (it thinks), as through 0.1.31; False
688    renders it without thinking (#278, the config's "anthropic_thinking": "on_request")."""
689    declared = _tool_list(req.get("tools"), None)
690    # #4663: a `defer_loading` tool stays out of the prompt's tool list until a tool_reference loads it
691    deferred = {t["name"]: _anthropic_tool(t) for t in declared if t.get("defer_loading")}
692    messages = []
693    system = req.get("system")
694    if system:
695        messages.append({"role": "system",
696                         "content": pin_billing_stamp(_text_of(_check_parts(system, "system", TEXT_PARTS)))})
697    for i, m in enumerate(_object_list(req.get("messages"), "messages")):
698        content = _check_parts(m.get("content"), f"messages[{i}].content", ANTHROPIC_BLOCKS)
699        if isinstance(content, str):
700            messages.append({"role": m["role"], "content": content})
701            continue
702        if m.get("role") == "user" and _has_image(content) and not any(
703                isinstance(b, dict) and b.get("type") == "tool_result" for b in content):
704            messages.append({"role": "user", "content": _parts_of(content)})
705            continue
706        text, reasoning, calls, parts = [], [], [], []
707        for j, block in enumerate(content or []):
708            kind = block.get("type")
709            if kind == "text":
710                text.append(block.get("text", ""))
711                parts.append(block)
712            elif kind in IMAGE_PARTS:
713                parts.append(block)
714            elif kind == "thinking":
715                reasoning.append(block.get("thinking", ""))
716            elif kind == "tool_use":
717                calls.append({"function": {"name": block.get("name"), "arguments": tool_arguments(block.get("input"))},
718                              "_call_id": block.get("id")})
719            elif kind == "tool_result":
720                # A tool's image (Claude Code's Read of a picture) reaches the encoder like a user's, as the OpenAI
721                # path's tool messages already do; a text-only result is one string, as before.
722                messages.append({"role": "tool", "content": _parts_of(_check_parts(
723                    _tool_references(block.get("content"), deferred),
724                    f"messages[{i}].content[{j}].content", TEXT_PARTS + IMAGE_PARTS)),
725                                 "_call_id": block.get("tool_use_id")})
726        if text or calls or reasoning or parts:
727            # an image sent beside tool results stays in this turn instead of being dropped
728            out = {"role": m["role"], "content": _parts_of(parts) if _has_image(parts) else "".join(text)}
729            if reasoning:
730                out["reasoning_content"] = "".join(reasoning)
731            if calls:
732                out["tool_calls"] = calls
733            messages.append(out)
734    # A client may send results in the order its tools finished (Claude Code does for parallel calls)
735    _order_chat_tool_results(messages)
736    tools = [_anthropic_tool(t) for t in declared if t["name"] not in deferred] or None
737    kwargs = {}
738    # Anthropic: "thinking": {"type": "disabled"} or {"type": "enabled", "budget_tokens": N};
739    # "output_config": {"effort": "low" | "medium" | "high"}
740    thinking = req.get("thinking")
741    effort = (req.get("output_config") or {}).get("effort") if isinstance(req.get("output_config"), dict) else None
742    # 0.1.45: Anthropic's budget_tokens is a real budget, not only a level: the thinking is closed (wrap-up, </think>,
743    # the answer) after that many tokens.  A reasoning_budget_tokens of the request's own wins.
744    bt = thinking.get("budget_tokens") if isinstance(thinking, dict) and thinking.get("type") != "disabled" else None
745    if isinstance(bt, int) and not isinstance(bt, bool) and bt > 0 and req.get("reasoning_budget_tokens") is None:
746        req["reasoning_budget_tokens"] = bt
747    if isinstance(thinking, dict) and thinking.get("type") == "disabled":
748        kwargs["enable_thinking"] = False
749    elif effort:
750        kwargs.update(effort_kwargs(effort))
751    elif isinstance(thinking, dict) and thinking.get("budget_tokens"):
752        kwargs.update(budget_effort(thinking["budget_tokens"]))
753    elif thinking is None and not req.get("reasoning_budget_tokens") and not think_unasked:
754        # Opt-in (the config's "anthropic_thinking": "on_request"; the default thinks as 0.1.31 did, since a
755        # client that never asks would otherwise lose the thinking on every turn).  Anthropic's thinking is
756        # opt-in there. Claude Code's helper calls (a session title, a topic check) ask for none
757        # and allow a few dozen tokens, which the model otherwise spent thinking and answered with no text at all.
758        # A config's reasoning_effort still applies: Service.with_shared sets output_config before this runs.  A
759        # request that gives its own reasoning_budget_tokens (#123) asks for thinking, so it thinks as before.
760        kwargs["enable_thinking"] = False
761    return _env_to_user(_late_system_to_user(messages)), tools, kwargs
762
763
764# ------------------------------------------------------------------------------------------------ output parser
765@dataclass
766class ToolCall:
767    name: str
768    arguments: dict
769    id: str = field(default_factory=lambda: "call_" + uuid.uuid4().hex[:24])
770
771
772@dataclass
773class Event:
774    kind: str                     # "reasoning" | "content" | "tool_call"
775    text: str = ""
776    call: ToolCall | None = None
777
778
779THINK_END = "</think>"
780CALL_START = "<tool_call>"
781CALL_END = "</tool_call>"
782
783
784PARAM_END = "</parameter>"
785FUNC_START = "<function="
786FUNC_END = "</function>"
787# #3441: the opener a model writes when it drifts by a token inside the envelope the template documents:
788# `<=NAME>` (the word `function` dropped), `<function:NAME>`, `<function =NAME>`, or the bare `<NAME>`
789_LOOSE_OPEN = re.compile(r"<\s*(?:function\s*[=:]\s*|=\s*)?([A-Za-z0-9_.\-]+)\s*>")
790_PREFIX_LOOKBACK = 256     # how far before a new delta a prefixed name or a misspelt opener can start (see OutputParser._prefixed)
791# #5409: `<function=tools actio>` / `<function=tools>`; the prefixes are the ones of #4751
792_PREFIX_SPACED = re.compile(r"(<function=\s*(?:tools|functions|default_api)[ \t]+)([^<>\s]+)\s*>")
793_PREFIX_PART = re.compile(r"<function=\s*(?:tools|functions|default_api)[ \t]+[^<>\s]{0,80}\s*$")
794_PREFIX_BARE = re.compile(r"(<tool_call>\s*)<function=\s*(tools|functions|default_api)\s*>(.*?)</function>", re.S)
795_PREFIX_BARE_OPEN = re.compile(r"<tool_call>\s*<function=\s*(tools|functions|default_api)\s*>(?!.*</function>)", re.S)
796# #5276: `<toolcall>` / `<tool-call>` as the opener (then whitespace, `<function=NAME>`), and such an opener still arriving
797_MISSPELT_OPEN = re.compile(r"<tool-?call>(\s*)<function=(\s*[^<>\s]+\s*)>")
798_MISSPELT_PART = re.compile(r"<tool-?call>\s*<function=[^<>]{0,80}$|<tool-?call>\s*(?:<(?:f(?:u(?:n(?:c(?:t(?:i(?:o(?:n)?)?)?)?)?)?)?)?)?$")
799_LOOSE_PART = re.compile(r"<\s*(?:function[ \t]*[=:]?\s*|=\s*)?[A-Za-z0-9_.\-]*\s*$")
800
801
802# a quoted call's opener in a value: `<function=NAME>` and its first parameter or close; a bare FUNC_START is text
803_QUOTED_OPEN = re.compile(r"<function=[^<>\s]+>\s*(?:<parameter=|</function>)")
804
805
806#: #4701: how much text after a closing sequence is looked at before the value is taken as ended there (a call followed by a long sentence)
807CLOSE_LOOKAHEAD_CHARS = 1500
808
809
810def _close_verdict(after: str, final: bool) -> str:
811    """`after` starts with `</function>` and/or `</tool_call>` right after a `</parameter>`.  A file that documents the call format has those
812    three tags on lines of its own inside a value (#4701), so the sequence only ends the value when what follows is the end of the turn, another
813    call, or prose with no closing tag after it.  "end": the value ends here; "continue": it goes on to the next `</parameter>`; "hold": not
814    decidable yet (streaming): wait for more text.  Bounded: the end of the turn (`final`), a new `<tool_call>`, or CLOSE_LOOKAHEAD_CHARS of
815    text decide, so a call is never held longer than that."""
816    m = re.match(r"(?:</function>)?\s*</tool_call>", after)
817    if not m:
818        tail = after[len(FUNC_END):].lstrip() if after.startswith(FUNC_END) else after
819        if not final and CALL_END.startswith(tail):
820            return "hold"                                  # #5040: `</tool_call>` is still arriving: a streamed view must not end the value yet
821        return "end"                                       # the call is cut, or it has no wrapper: as before
822    rest = after[m.end():].lstrip()
823    if not rest:
824        return "end" if final else "hold"                  # the usual call: the turn ends right after it
825    if rest.startswith(CALL_START):
826        return "end"
827    if not final and CALL_START.startswith(rest):
828        return "hold"                                      # `<tool_c` of a second call is arriving
829    if CALL_START in rest:
830        return "end"                                       # prose, then another call: this one is complete
831    if PARAM_END in rest or CALL_END in rest or FUNC_END in rest:
832        return "continue"                                  # prose, then closing tags again: the text was part of the value
833    if final or len(rest) > CLOSE_LOOKAHEAD_CHARS:
834        return "end"
835    return "hold"
836
837
838
839def param_end(text: str, final: bool = False, name: str | None = None, hold: bool = True) -> int:
840    """Where a parameter value in `text` ends: the first PARAM_END followed (after whitespace) by the next
841    PARAM_START or FUNC_END, or by the wrapper's CALL_END when the call's `</function>` was left out (#4427) - the
842    same text inside a value (a file that documents the call format, #210) is
843    part of the value.  #4078: a close inside a call the value itself quotes (more _QUOTED_OPEN than FUNC_END before
844    it), or one followed by the same parameter `name` again, is part of the value too.  `text` starts at the value.
845    -1: none yet; -2: a candidate whose follower has not arrived (streaming; `final` accepts it)."""
846    at = text.find(PARAM_END)
847    while at >= 0:
848        if len(_QUOTED_OPEN.findall(text, 0, at)) <= text.count(FUNC_END, 0, at):
849            after = text[at + len(PARAM_END):].lstrip()
850            if after.startswith(PARAM_START):
851                gt = after.find(">")
852                if gt < 0:
853                    return at if final else -2
854                if name is None or after[len(PARAM_START):gt].strip() != name:
855                    return at
856            elif after.startswith((FUNC_END, CALL_END)):          # #4427: the model left out its `</function>`
857                verdict = _close_verdict(after, final) if hold else "end"      # hold=False: a call inside the reasoning keeps its old rule
858                if verdict == "end":
859                    return at
860                if verdict == "hold":
861                    return -2
862            elif not after or PARAM_START.startswith(after) or FUNC_END.startswith(after) or CALL_END.startswith(after):
863                return at if final else -2
864        at = text.find(PARAM_END, at + 1)
865    return -1
866
867
868def call_end(text: str, final: bool = False, hold: bool = True) -> int:
869    """Where a tool call's body ends (#210): the `</tool_call>` after the call's own `</function>`, found by walking
870    its parameters with param_end, so a value may contain either tag.  -1: not complete yet.  A body that is not in
871    the call format ends at the first `</tool_call>`, as before."""
872    s = text.lstrip()
873    pos = len(text) - len(s)
874    if not s.startswith("<function="):
875        return text.find(CALL_END) if not "<function=".startswith(s) else -1
876    gt = text.find(">", pos)
877    if gt < 0:
878        return -1
879    pos = gt + 1
880    while True:
881        rest = text[pos:]
882        s = rest.lstrip()
883        pos += len(rest) - len(s)
884        if s.startswith("<parameter="):
885            gt = text.find(">", pos)
886            if gt < 0:
887                return -1
888            end = param_end(text[gt + 1:], final, text[pos:gt].split("=", 1)[1].strip(), hold)
889            if end < 0:
890                return -1
891            pos = gt + 1 + end + len(PARAM_END)
892        elif s.startswith(FUNC_END):
893            rest = text[pos + len(FUNC_END):]
894            s = rest.lstrip()
895            if s.startswith(CALL_END):
896                return pos + len(FUNC_END) + len(rest) - len(s)
897            return -1 if CALL_END.startswith(s) else text.find(CALL_END, pos)
898        elif not s or "<parameter=".startswith(s) or FUNC_END.startswith(s):
899            return -1
900        else:
901            return text.find(CALL_END, pos)
902
903
904def tool_choice_of(tool_choice) -> tuple[str, str | None]:
905    """A client's `tool_choice` in either API's shape -> ("auto" | "none" | "required" | "named", name).  OpenAI:
906    "auto" / "none" / "required", {"type": "function", "function": {"name": N}} or the flat {"type": "function",
907    "name": N}; Anthropic: {"type": "auto" | "any" | "none"} and {"type": "tool", "name": N}.  A value it does not
908    know is ("unknown", None)."""
909    if tool_choice is None:
910        return "auto", None
911    if isinstance(tool_choice, str):
912        return (tool_choice, None) if tool_choice in ("auto", "none", "required") else ("unknown", None)
913    if isinstance(tool_choice, dict):
914        kind = tool_choice.get("type")
915        if kind in ("auto", "none"):
916            return kind, None
917        if kind in ("any", "required"):
918            return "required", None
919        if kind in ("function", "tool"):
920            fn = tool_choice.get("function")
921            name = (fn.get("name") if isinstance(fn, dict) else None) or tool_choice.get("name")
922            if isinstance(name, str) and name:
923                return "named", name
924    return "unknown", None
925
926
927def forced_call(tool_choice, tools: list[dict] | None) -> str | None:
928    """`tool_choice` -> the text that opens the call the reply must make, or None (the model decides).
929    There is no grammar here: the server writes this opening itself, so the model can only go on with a call.
930    "required" / Anthropic "any": any of the tools; a named function: that one.  A value it cannot honour (an
931    unknown shape, a name that is not one of the tools, "required" with no tools) is logged and acts as "auto",
932    not a 400: a client's odd choice must not stop its request.  "none" is handled by the caller (no tools)."""
933    kind, name = tool_choice_of(tool_choice)
934    names = {t.get("name") for t in tools or [] if isinstance(t, dict)}
935    if kind in ("auto", "none"):
936        return None
937    if kind == "required" and len(names) == 1:     # one tool to call: name it, the model cannot invent another
938        kind, name = "named", next(iter(names))
939    if kind == "required" and names:               # the model writes "<function=NAME>": from a written "<function=", Qwen3.8 went on with names no tool has
940        return CALL_START + "\n"
941    if kind == "named" and name in names:
942        return CALL_START + f"\n<function={name}>\n"
943    print(f"[strata] tool_choice {json.dumps(tool_choice)[:200]} is not supported here (or names no tool of the "
944          "request): the model decides, as with \"auto\"", flush=True)
945    return None
946
947
948PARAM_START = "<parameter="
949
950
951def function_end(text: str) -> int:
952    """Where a `<function=NAME>...</function>` at the start of `text` ends (just past `</function>`), walking its
953    parameters with param_end like call_end does; -1: not complete (or not in the call format)."""
954    s = text.lstrip()
955    pos = len(text) - len(s)
956    if not s.startswith(FUNC_START):
957        return -1
958    gt = text.find(">", pos)
959    if gt < 0:
960        return -1
961    pos = gt + 1
962    while True:
963        rest = text[pos:]
964        s = rest.lstrip()
965        pos += len(rest) - len(s)
966        if s.startswith(PARAM_START):
967            gt = text.find(">", pos)
968            if gt < 0:
969                return -1
970            end = param_end(text[gt + 1:], name=text[pos:gt].split("=", 1)[1].strip(), hold=False)   # a bare or unwrapped call: the old rule
971            if end < 0:
972                return -1
973            pos = gt + 1 + end + len(PARAM_END)
974        elif s.startswith(FUNC_END):
975            return pos + len(FUNC_END)
976        else:
977            return -1
978
979
980_JSON_FENCE = re.compile(r"```[ \t]*(?:json)?[ \t]*\r?\n\s*", re.I)
981
982
983def json_tool_call(body: str, schemas: dict) -> ToolCall | None:
984    """`{"name": N, "arguments": {...}}` (or "parameters", or the arguments as a JSON string) of a declared tool -> its
985    call; anything else -> None.  #2037: the object may sit in a Markdown fence (```json ... ```)."""
986    body = body.strip()
987    m = _JSON_FENCE.match(body)
988    if m:
989        body = body[m.end():].rstrip()
990        body = body[:-3] if body.endswith("```") else body
991    try:
992        obj = json.loads(body)
993    except ValueError:
994        return None
995    if not isinstance(obj, dict) or not isinstance(obj.get("name"), str) or obj["name"] not in schemas:
996        return None
997    args = obj.get("arguments", obj.get("parameters", {}))
998    if isinstance(args, str):
999        try:
1000            args = json.loads(args)
1001        except ValueError:
1002            return None
1003    if args is None:
1004        args = {}
1005    return ToolCall(name=obj["name"], arguments=args) if isinstance(args, dict) else None
1006
1007
1008LENIENT_MAX = 1 << 20           # the longest value lenient_json will try (it is a python loop)
1009
1010
1011class _Lenient:
1012    """A JSON reader for the slips a model makes inside an array or object argument (#4427): a trailing or doubled comma,
1013    single quotes and Python's True/False/None, a bare string between two members of an object (`"status": "pending",
1014    "in_progress", "pending": false`), brackets left open at the end, extra closers at the end.  It is only asked about
1015    text json.loads has refused.  It never guesses at a value: a string cut short, an unknown word, a missing colon
1016    after a key, anything else raises ValueError."""
1017
1018    _WORDS = {"true": True, "false": False, "null": None, "True": True, "False": False, "None": None}
1019    _ESC = {'"': '"', "'": "'", "\\": "\\", "/": "/", "b": "\b", "f": "\f", "n": "\n", "r": "\r", "t": "\t"}
1020    _TOKEN = re.compile(r"[^\s,\]}:]+")
1021
1022    def __init__(self, text: str):
1023        self.s, self.i = text, 0
1024
1025    def peek(self) -> str:
1026        s, n = self.s, len(self.s)
1027        while self.i < n and s[self.i] in " \t\r\n":
1028            self.i += 1
1029        return s[self.i:self.i + 1]
1030
1031    def string(self) -> str:
1032        s, q = self.s, self.s[self.i]
1033        self.i += 1
1034        out = []
1035        while self.i < len(s):
1036            c = s[self.i]
1037            if c == q:
1038                self.i += 1
1039                return "".join(out)
1040            if c == "\\":
1041                self.i += 1
1042                e = s[self.i:self.i + 1]
1043                if e == "u" and re.fullmatch(r"[0-9a-fA-F]{4}", s[self.i + 1:self.i + 5]):
1044                    out.append(chr(int(s[self.i + 1:self.i + 5], 16)))
1045                    self.i += 5
1046                    continue
1047                if e not in self._ESC:
1048                    raise ValueError("bad escape")
1049                out.append(self._ESC[e])
1050            else:
1051                out.append(c)
1052            self.i += 1
1053        raise ValueError("string not closed")
1054
1055    def value(self, depth: int = 0):
1056        if depth > 64:
1057            raise ValueError("too deep")
1058        c = self.peek()
1059        if c == "{":
1060            return self.obj(depth + 1)
1061        if c == "[":
1062            return self.arr(depth + 1)
1063        if c in ('"', "'"):
1064            return self.string()
1065        m = self._TOKEN.match(self.s, self.i)
1066        if not m:
1067            raise ValueError("no value")
1068        self.i = m.end()
1069        if m.group() in self._WORDS:
1070            return self._WORDS[m.group()]
1071        return json.loads(m.group())            # a number, or ValueError
1072
1073    def obj(self, depth: int):
1074        self.i += 1
1075        out: dict = {}
1076        while True:
1077            c = self.peek()
1078            if not c or c == "}":               # (no closer: the brackets were left open at the end)
1079                self.i += 1
1080                return out
1081            if c == ",":
1082                self.i += 1
1083                continue
1084            if c not in ('"', "'"):
1085                raise ValueError("object member")
1086            key = self.string()
1087            if self.peek() == ":":
1088                self.i += 1
1089                out[key] = self.value(depth)
1090            elif self.peek() not in (",", "}", ""):     # a bare string where a member belongs is dropped
1091                raise ValueError("object member")
1092
1093    def arr(self, depth: int):
1094        self.i += 1
1095        out: list = []
1096        while True:
1097            c = self.peek()
1098            if not c or c == "]":
1099                self.i += 1
1100                return out
1101            if c == ",":
1102                self.i += 1
1103                continue
1104            out.append(self.value(depth))
1105            if self.peek() not in (",", "]", ""):
1106                raise ValueError("array element")
1107
1108
1109def lenient_json(text: str):
1110    """The JSON array or object `text` was meant to be, read past the slips of _Lenient; ValueError for anything else
1111    (and for text that is not an array or object).  Valid JSON is not its business: callers try json.loads first."""
1112    t = text.strip()
1113    m = _JSON_FENCE.match(t)
1114    if m:
1115        t = t[m.end():].rstrip()
1116        t = t[:-3].rstrip() if t.endswith("```") else t
1117    if not t.startswith(("[", "{")) or len(t) > LENIENT_MAX:
1118        raise ValueError("not an array or object")
1119    r = _Lenient(t)
1120    v = r.value()
1121    if t[r.i:].strip("]}) \t\r\n"):
1122        raise ValueError("text after the value")
1123    return v
1124
1125
1126def coerce_value(value: str, declared, notes: list | None = None):
1127    """A non-string parameter's text -> its value by the tool's declared type: JSON when it parses; else an array or an
1128    object read with lenient_json (a note says so in `notes`); else the text itself, as before.  An array or object that
1129    arrived as a JSON string of itself is decoded once more."""
1130    if declared == "string":
1131        return value
1132    boolean = declared == "boolean" or (isinstance(declared, list) and "boolean" in declared and "string" not in declared)
1133    if boolean and value.strip().lower() in ("true", "false"):
1134        return value.strip().lower() == "true"         # #5979: the model's Python spelling (True / False) of a declared boolean is the boolean
1135    try:
1136        v = json.loads(value)
1137    except ValueError:
1138        if not value.lstrip().startswith(("[", "{", "`")) or (isinstance(declared, list) and "string" in declared):
1139            return value
1140        try:
1141            v = lenient_json(value)
1142        except (ValueError, RecursionError):
1143            return value
1144        if notes is not None:
1145            notes.append("a damaged JSON " + ("array" if isinstance(v, list) else "object") + " argument was read as written")
1146        return v
1147    if isinstance(v, str) and declared in ("array", "object") and v.lstrip().startswith(("[", "{")):
1148        try:
1149            return json.loads(v)
1150        except ValueError:
1151            return coerce_value(v, declared, notes)
1152    return v
1153
1154
1155def parse_tool_call(body: str, schema: dict | None = None, notes: list | None = None) -> ToolCall:
1156    """`<function=NAME>\\n<parameter=P>\\nVALUE\\n</parameter>...</function>` -> ToolCall. Values are JSON-decoded
1157    when the tool's schema says the parameter is not a string (or, without a schema, when they parse as JSON
1158    objects/arrays/numbers/booleans)."""
1159    body = body.strip()
1160    if not body.startswith("<function=") or ">" not in body:
1161        raise ValueError("malformed tool call: " + body[:80])
1162    name = body[len("<function="):body.index(">")].strip()      # `<function= capture>`: the model's stray space
1163    rest = body[body.index(">") + 1:]
1164    props = ((schema or {}).get("parameters") or {}).get("properties") or {}
1165    args = {}
1166    while "<parameter=" in rest:
1167        rest = rest[rest.index("<parameter=") + len("<parameter="):]
1168        pname = rest[:rest.index(">")]
1169        rest = rest[rest.index(">") + 1:]
1170        end = param_end(rest, final=True, name=pname.strip())
1171        value = rest[:end] if end >= 0 else rest
1172        rest = rest[end + len(PARAM_END):] if end >= 0 else ""
1173        if value.startswith("\n"):
1174            value = value[1:]
1175        if value.endswith("\n"):
1176            value = value[:-1]
1177        args[pname] = coerce_value(value, (props.get(pname) or {}).get("type"), notes)
1178    return ToolCall(name=name, arguments=args)
1179
1180
1181RCALL_MAX = 32768        # the most of a `<tool_call>` inside the reasoning that is held while waiting for its end (#804)
1182
1183
1184class OutputParser:
1185    """Incremental parser of the model's text. Feed deltas; get events. A tag split across deltas is held back
1186    until it is complete, so clients never see `<tool_` or `</thi`."""
1187
1188    def __init__(self, thinking: bool = True, tools: list[dict] | None = None, stream_tools: bool = False,
1189                 recover: bool = False, declared_only: bool = False, deferred: bool = False):
1190        self.state = "reasoning" if thinking else "content"
1191        self.buf = ""
1192        self.lead = False
1193        self.schemas = {t.get("name"): t for t in tools or []}
1194        # #4663: the request defers tools (Anthropic's tool search, see anthropic_tools): the client holds back more tools
1195        # than it declares, so a call for an undeclared name is a call too - Claude Code runs it, where text ended the turn.
1196        self.deferred = deferred
1197        # #804/#3075: in the answer too, a call counts only for a tool the request declared.  With tools declared a
1198        # call for another name stays text (the Responses spelling `namespace__tool` of a `namespace.tool` counts as
1199        # that tool); `declared_only` extends the rule to a request that declared none (Chat Completions, Anthropic:
1200        # the client has no tool to run).  The Responses route leaves it off: a Codex compaction request keeps its
1201        # conversation's tools in the prompt only, and its calls come back as before.
1202        self.declared_only = declared_only
1203        # A declared namespace.member tool is also accepted as namespace__member (PR #3556),
1204        # namespace=member (Qwen writes the <function= tag's equals sign into the name),
1205        # namespace_member (one underscore dropped), and the bare member when exactly one
1206        # declared tool has it. Only an unambiguous alias counts, and an exactly declared
1207        # name always wins over an alias.
1208        aliases = {}
1209        for name in self.schemas:
1210            if isinstance(name, str) and "." in name:
1211                namespace, member = name.rsplit(".", 1)
1212                for alias in (f"{namespace}__{member}", f"{namespace}={member}",
1213                              f"{namespace}_{member}", member):
1214                    aliases.setdefault(alias, set()).add(name)
1215        # #3796: the same tool written with every `__` collapsed to `_` (`mcp__playwright__browser_navigate` as
1216        # `mcp_playwright_browser_navigate`, the way Qwen often flattens a name) is that tool.  Only a spelling of a declared
1217        # name: a reordered or renamed tool (`server1_label_values` for `label_values_mcp_server1`) is not guessed.
1218        for name in self.schemas:
1219            if isinstance(name, str) and "__" in name:
1220                aliases.setdefault(name.replace("__", "_"), set()).add(name)
1221                # #5281: a namespaced MCP tool (`mcp__assets__get_asset_info`) written with its last segment only (`get_asset_info`),
1222                # as the bare member of a dotted name is accepted above; only when exactly one declared tool ends that way
1223                last = name.rsplit("__", 1)[1]
1224                if last:
1225                    aliases.setdefault(last, set()).add(name)
1226        # #4751: a programmatic-tool-calling harness (the DeepSeek Harness's PTC mode) shows the model its tools as `tools.write(...)`
1227        # inside code, and the model then writes the native call with that spelling (`tools.write`, also `functions.write`).  The
1228        # prefix is not part of the declared name; the same unambiguous-alias rule applies, an exactly declared name always wins.
1229        for name in self.schemas:
1230            if isinstance(name, str) and name:
1231                for prefix in ("tools.", "functions.", "default_api."):
1232                    aliases.setdefault(prefix + name, set()).add(name)
1233        self.aliases = {alias: next(iter(names)) for alias, names in aliases.items()
1234                        if len(names) == 1 and alias not in self.schemas}
1235        self.unread = 0              # #3441: `<tool_call>` blocks that opened like a call and were returned as text
1236        self.unread_names: list[str] = []   # the names (first few) of those that named a tool the request did not declare
1237        # stream_tools: a tool call is also reported while it is being written - "tool_start" (its name and id) as
1238        # soon as the name is known, then "tool_args" pieces of its JSON arguments (string parameters character by
1239        # character; other types whole, once complete) - before the final "tool_call".  Without it, a client sees
1240        # nothing until the call is complete, which for a large file write can be many minutes.
1241        self.stream_tools = stream_tools
1242        # #804/#1058: calls found inside the reasoning wait here as [raw text, ToolCall | None] until the turn shows
1243        # they were acts: only whitespace (or more calls) after them, then the end of the turn or `</think>`.  The
1244        # reasoning text before them is tracked (code fence, inline code, current line) to tell an act from a quote.
1245        self.pending: list[list] = []
1246        self.rescued = 0             # calls delivered from the reasoning
1247        self.notes: list[str] = []   # #4427: what was repaired in the arguments of the calls (a damaged JSON array or object)
1248        self.after_think = False     # #4077: the reasoning ended at a bare `</think>` (a second one in the answer is a stray)
1249        self.stray_think = 0         # ... and the strays of that kind dropped from the answer
1250        self.refused = 0             # declared calls kept as reasoning text (quoted, or the turn was cut)
1251        self.fence, self.line, self.ticks = "", "", 0
1252        self._prev_blank = self._indented = False   # #4703: the line before was blank / this is inside an indented (4-space) code block
1253        # recover (on in the server since 0.2.8, off for a bare OutputParser; the config's "tool_call_recovery": false turns it off): a declared tool's call written next to the template's
1254        # form is the call - `<parameter=NAME>` as the opener, JSON inside <tool_call>, a bare <function=NAME> at the
1255        # start of a line outside code, or a second call in the same <tool_call> (which otherwise merges into one).
1256        self.recover = recover
1257        self.bare = False            # the call being read opened with <function= alone (no <tool_call> around it)
1258        self.batch = False           # the call being finished is followed by another in the same wrapper
1259        self._final = False          # #4701: the turn has ended: a call held for what might follow it is decided now
1260        self._held = ""              # #5276/#5409: the end of a misspelt opener or a prefixed name still arriving (see _prefixed)
1261        self._reset_scan()
1262
1263    @property
1264    def clean(self) -> bool:
1265        """Nothing is held back: a clean point to stop the thinking at (a parser that rewrites the model's text, as
1266        serve/dsml.py's does, also counts what it holds)."""
1267        return not self.buf and not self._held
1268
1269    def _ok_at(self, p: int) -> bool:
1270        """self.buf[p] would open a call: at the start of a line, outside a code fence and inline code."""
1271        snap = self._snap()
1272        self._track(self.buf[:p])
1273        ok = self._opener_ok()
1274        self._restore(snap)
1275        return ok
1276
1277    def _opens_at(self, p: int) -> bool:
1278        """self.buf[p] would open a call as `<tool_call>` does: in the reasoning at the start of a line outside code, in the answer
1279        anywhere outside code (a fence, inline code, an indented block)."""
1280        if self.state == "reasoning":
1281            return self._ok_at(p)
1282        snap = self._snap()
1283        self._track(self.buf[:p])
1284        ok = not self._in_code()
1285        self._restore(snap)
1286        return ok
1287
1288    def _callable(self, name: str) -> bool:
1289        """#3075: may a call for `name` be a call?  A tool the request declared (or its Responses spelling); with
1290        none declared, only where `declared_only` is off."""
1291        if not self.schemas:
1292            return not self.declared_only
1293        return name in self.schemas or name in self.aliases or self.deferred
1294
1295    def _loose_open(self, after: str):
1296        """#3441: `after` (text after a `<tool_call>`, whitespace dropped) opens a call in a drifted form that names a
1297        declared tool -> (name, length of the opener); "wait" while it may still become one; None otherwise."""
1298        m = _LOOSE_OPEN.match(after)
1299        if m:
1300            name = m.group(1)
1301            return (name, m.end()) if self._callable(name) else None
1302        if ">" in after or "\n" in after or not after.startswith("<"):
1303            return None
1304        if _LOOSE_PART.match(after):
1305            bare = after[1:].strip().lstrip("=").strip()
1306            if after[1:].lstrip().startswith(("=", "function")):
1307                return "wait"
1308            if any(k.startswith(bare) for k in list(self.schemas) + list(self.aliases) if isinstance(k, str)):
1309                return "wait"
1310        return None
1311
1312    def _follower(self, after: str) -> str:
1313        """recover: what a `<tool_call>` followed (after whitespace) by `after` opens: "call" (`<function=`), "param"
1314        (a declared tool's name written as `<parameter=NAME>`), "json" (`{`), "wait" (not decided yet) or "text"."""
1315        if after.startswith(FUNC_START):
1316            return "call"
1317        if after.startswith(PARAM_START):
1318            gt = after.find(">")
1319            if gt < 0:
1320                return "wait" if "\n" not in after else "text"
1321            return "param" if after[len(PARAM_START):gt] in self.schemas else "text"
1322        if after.startswith("{"):
1323            return "json" if self.schemas else "text"
1324        if after.startswith("```") or (after and "```".startswith(after)):
1325            # #2037: the JSON call inside a Markdown fence (```json ... ```) in the explicit wrapper
1326            m = _JSON_FENCE.match(after)
1327            if m:
1328                rest = after[m.end():]
1329                if rest.startswith("{"):
1330                    return "json" if self.schemas else "text"
1331                return "wait" if not rest else "text"
1332            return "wait" if "\n" not in after else "text"
1333        if not after or FUNC_START.startswith(after) or PARAM_START.startswith(after):
1334            return "wait"
1335        return "text"
1336
1337    def _bare_opener(self) -> tuple[int, bool]:
1338        """recover: the first `<function=` in self.buf that opens a call without the wrapper (start of a line, outside
1339        code, a declared tool) -> (position, decided); (-1, False) for none.  A name still arriving is undecided."""
1340        p = self.buf.find(FUNC_START)
1341        while p >= 0:
1342            if self._ok_at(p):
1343                gt = self.buf.find(">", p)
1344                raw_name = self.buf[p + len(FUNC_START):gt if gt >= 0 else len(self.buf)]
1345                name = raw_name.strip()
1346                name = self.aliases.get(name, name)
1347                if gt < 0 and re.fullmatch(r"\s*[^<>\s]*\s*", raw_name):
1348                    return p, False
1349                if gt >= 0 and name in self.schemas:
1350                    return p, True
1351            p = self.buf.find(FUNC_START, p + 1)
1352        return -1, False
1353
1354    @property
1355    def line(self) -> str:
1356        """Materialize the current line only for a decision, newline, or state snapshot."""
1357        if self._line_blocks is not None:
1358            self._line_blocks.extend(self._line_parts)
1359            self._line_parts = ["".join(self._line_blocks)]
1360            self._line_blocks = None
1361        elif len(self._line_parts) > 1:
1362            self._line_parts = ["".join(self._line_parts)]
1363        return self._line_parts[0] if self._line_parts else ""
1364
1365    @line.setter
1366    def line(self, text: str):
1367        self._line_parts = [text] if text else []
1368        self._line_blocks = None
1369
1370    def _track(self, text: str) -> str:
1371        """Follow the reasoning text that has gone out: the open code fence, the current line, and the backticks of
1372        the current paragraph.  Returns the text."""
1373        # Most token fragments stay on the current line. Fence and paragraph
1374        # bookkeeping happens only when a newline completes that line.
1375        if "\n" not in text:
1376            if text:
1377                self._line_parts.append(text)
1378                if len(self._line_parts) == 64:
1379                    # Release small fragment objects in bounded groups. Completed
1380                    # blocks are never recopied until the full line is requested.
1381                    if self._line_blocks is None:
1382                        self._line_blocks = []
1383                    self._line_blocks.append("".join(self._line_parts))
1384                    self._line_parts.clear()
1385            return text
1386        parts = text.split("\n")
1387        for k, part in enumerate(parts):
1388            if k < len(parts) - 1:
1389                line = self.line + part if self._line_parts or self._line_blocks else part
1390                self._line_parts.clear()
1391                self._line_blocks = None
1392                s = line.lstrip()
1393                was_fenced = bool(self.fence)
1394                if self.fence:
1395                    # #4702: a fence is closed only by a line of at least as many of the same character as opened it (CommonMark), so a
1396                    # ``` example inside a ```` file stays inside it
1397                    run = len(s) - len(s.lstrip(self.fence[0]))
1398                    if run >= len(self.fence):
1399                        self.fence = ""
1400                elif s[:3] in ("```", "~~~") and (s[0] * 3) not in s[3:]:
1401                    self.fence = s[0] * (len(s) - len(s.lstrip(s[0])))
1402                elif not s:
1403                    self.ticks = 0
1404                else:
1405                    self.ticks += line.count("`")
1406                # #4703: an indented (4 spaces or a tab) code block starts after a blank line and goes on until a line that is not indented
1407                if was_fenced or self.fence:
1408                    self._prev_blank = self._indented = False
1409                elif not s:
1410                    self._prev_blank = True
1411                elif line.startswith(("    ", "\t")):
1412                    self._indented = self._prev_blank or self._indented
1413                    self._prev_blank = False
1414                else:
1415                    self._prev_blank = self._indented = False
1416            else:
1417                if part:
1418                    self._line_parts.append(part)
1419        return text
1420
1421    def _opener_ok(self) -> bool:
1422        """The reasoning text so far puts a `<tool_call>` at the start of a line, outside a code fence and outside
1423        inline code."""
1424        return not self.fence and not self.line.strip() and self.ticks % 2 == 0 and not self._in_indented_block()
1425
1426    def _in_indented_block(self) -> bool:
1427        """#4703: the current line is part of an indented code block: four spaces or a tab, after a blank line or another such line."""
1428        return (self._prev_blank or self._indented) and self.line.startswith(("    ", "\t"))
1429
1430    def _snap(self) -> tuple:
1431        return (self.fence, self.line, self.ticks, self._prev_blank, self._indented)
1432
1433    def _restore(self, snap: tuple) -> None:
1434        self.fence, self.line, self.ticks, self._prev_blank, self._indented = snap
1435
1436    def _reset_track(self) -> None:
1437        self.fence, self.line, self.ticks = "", "", 0
1438        self._prev_blank = self._indented = False
1439
1440    def _in_code(self) -> bool:
1441        """The text so far leaves the next character inside a code fence, inline code or an indented code block."""
1442        return bool(self.fence) or (self.ticks + self.line.count("`")) % 2 == 1 or self._in_indented_block()
1443
1444    def _quoted_think_end(self, i: int) -> bool | None:
1445        """#537: the `</think>` at self.buf[i] is the model quoting the tag while it thinks, not the end of the
1446        thinking: written right after a quote or backtick and followed by anything but a line break, as in `</think>`
1447        or "</think>...".  The end of the thinking is followed by a line break.  None while the character after the
1448        tag has not arrived."""
1449        before = self.buf[i - 1] if i else self.line[-1:]
1450        if before not in ('"', "'", "`"):
1451            return False
1452        after = self.buf[i + len(THINK_END):]
1453        if not after:
1454            return None
1455        return after[0] not in "\r\n"
1456
1457    def _stray_think_at(self) -> int:
1458        """#4077: where self.buf has a `</think>` at the start of a line, in the answer of a turn whose reasoning
1459        already ended at one; -1 for none.  A fence or backtick is no reason to keep it: the reasoning may have left
1460        one open, and the answer's own tracking of code is wrong from there on."""
1461        k = self.buf.find(THINK_END)
1462        while k >= 0:
1463            before = self.buf[:k]
1464            if not (before.rsplit("\n", 1)[1] if "\n" in before else self.line + before).strip():
1465                return k
1466            k = self.buf.find(THINK_END, k + 1)
1467        return -1
1468
1469    def _release(self, deliver: bool) -> list[Event]:
1470        """Settle the calls waiting in self.pending: events for real calls, or all of it back as reasoning text."""
1471        out = []
1472        for raw, call in self.pending:
1473            if call is not None and deliver:
1474                out.append(Event("tool_call", call=call))
1475                self.rescued += 1
1476            elif call is None or not deliver:
1477                if call is not None:
1478                    self.refused += 1
1479                if raw:
1480                    out.append(Event("reasoning", self._track(raw)))
1481        self.pending = []
1482        return out
1483
1484    def _reset_scan(self):
1485        self._call_end_checked = 0   # closing-tag search progress for the current wrapped call
1486        self.sp = 0                  # how much of self.buf (the call body) the scanner has consumed
1487        self.ss = "name"             # name -> between -> str|raw -> ... -> function_done -> done
1488        self.scall = None            # the ToolCall being streamed (its id is reused by the final event)
1489        self.sfirst = True
1490        self.sval_started = False
1491        self.sdeclared = {}
1492        self.spname = None
1493        self.svstart = 0
1494
1495    def _wrapped_call_end(self) -> int:
1496        # Without a closing tag the structural walk cannot finish. Search only
1497        # newly appended text plus enough overlap for a tag split across feeds.
1498        # A literal closing tag inside a value needs structural disambiguation:
1499        # once any candidate appears, keep the original full walk for this call.
1500        # Recovery can rewrite the buffer, so it always uses the full walk.
1501        if not self.recover and self._call_end_checked >= 0:
1502            start = max(0, self._call_end_checked - len(CALL_END) + 1)
1503            if self.buf.find(CALL_END, start) < 0:
1504                self._call_end_checked = len(self.buf)
1505                return -1
1506            self._call_end_checked = -1
1507        return call_end(self.buf, self._final)
1508
1509    def _scan(self) -> list[Event]:
1510        """Advance the streaming view of the call body in self.buf (see stream_tools)."""
1511        out = []
1512
1513        def args(s):
1514            if s:
1515                out.append(Event("tool_args", s, call=self.scall))
1516        while True:
1517            rest = self.buf[self.sp:]
1518            if self.ss == "name":
1519                a = rest.find("<function=")
1520                b = rest.find(">", a + 10) if a >= 0 else -1
1521                if b < 0:
1522                    return out
1523                raw_name = rest[a + 10:b]
1524                name = raw_name.strip()
1525                name = self.aliases.get(name, name)
1526                if raw_name != raw_name.strip() and name not in self.schemas:
1527                    return out
1528                self.scall = ToolCall(name=name, arguments={})
1529                props = ((self.schemas.get(name) or {}).get("parameters") or {}).get("properties") or {}
1530                self.sdeclared = {k: (v or {}).get("type") for k, v in props.items()}
1531                out.append(Event("tool_start", call=self.scall))
1532                args("{")
1533                self.sp += b + 1
1534                self.ss = "between"
1535            elif self.ss == "between":
1536                stripped = rest.lstrip()
1537                self.sp += len(rest) - len(stripped)
1538                if stripped.startswith("<parameter="):
1539                    b = stripped.find(">")
1540                    if b < 0:
1541                        return out
1542                    pname = stripped[11:b]
1543                    args(("" if self.sfirst else ",") + json.dumps(pname) + ":")
1544                    self.sfirst = False
1545                    self.sp += b + 1
1546                    self.spname = pname.strip()
1547                    if self.sdeclared.get(pname) == "string":
1548                        args('"')
1549                        self.ss, self.sval_started = "str", False
1550                    else:
1551                        self.ss = "raw"
1552                elif stripped.startswith("</function>"):
1553                    self.sp += len("</function>")
1554                    self.ss = "function_done"
1555                else:
1556                    return out          # a tag still arriving (or trailing text): wait
1557            elif self.ss == "str":
1558                if not self.sval_started:
1559                    if not rest:
1560                        return out
1561                    if rest[0] == "\n":          # the value's leading newline is not part of it
1562                        self.sp += 1
1563                        rest = rest[1:]
1564                    self.sval_started = True
1565                    self.svstart = self.sp
1566                # the walk starts at the value (a quoted call's opener counts); only a close in the new text can end it
1567                end = param_end(self.buf[self.svstart:], self._final, name=self.spname) if PARAM_END in rest else -1
1568                end = end - (self.sp - self.svstart) if end >= 0 else end
1569                if end >= 0:
1570                    value = rest[:end]
1571                    if value.endswith("\n"):
1572                        value = value[:-1]
1573                    args(json.dumps(value)[1:-1] + '"')
1574                    self.sp += end + len(PARAM_END)
1575                    self.ss = "between"
1576                    continue
1577                # an undecided </parameter> (-2) is held from its start, like a tag still arriving
1578                safe = rest.find(PARAM_END) if end == -2 else len(rest) - self._hold(rest, (PARAM_END,))
1579                if safe > 0 and rest[safe - 1] == "\n":   # may be the trailing newline before </parameter>
1580                    safe -= 1
1581                if safe > 0:
1582                    args(json.dumps(rest[:safe])[1:-1])
1583                    self.sp += safe
1584                return out
1585            elif self.ss == "raw":
1586                end = param_end(rest, self._final, name=self.spname)
1587                if end < 0:
1588                    return out
1589                value = rest[:end]
1590                if value.startswith("\n"):
1591                    value = value[1:]
1592                if value.endswith("\n"):
1593                    value = value[:-1]
1594                v = coerce_value(value, self.sdeclared.get(self.spname))    # the note comes with the final call (parse_tool_call)
1595                args(json.dumps(v, ensure_ascii=False))
1596                self.sp += end + len(PARAM_END)
1597                self.ss = "between"
1598            else:
1599                return out
1600
1601    def _close_scan(self) -> list[Event]:
1602        """Close streamed JSON only after its call boundary has been confirmed."""
1603        out = []
1604        if self.scall is None or self.ss == "done":
1605            return out
1606        tail = ""
1607        if self.ss == "str":
1608            tail += '"'
1609        elif self.ss == "raw":
1610            tail += json.dumps(self.buf[self.sp:].strip("\n"))
1611        tail += "}"
1612        out.append(Event("tool_args", tail, call=self.scall))
1613        self.ss = "done"
1614        return out
1615
1616    def _hold(self, text: str, tags: tuple[str, ...]) -> int:
1617        """Length of the longest suffix of `text` that is a proper prefix of one of `tags`."""
1618        best = 0
1619        size = len(text)
1620        for tag in tags:
1621            if len(tag) <= 1:
1622                continue
1623            # Only a suffix beginning with the tag's first character can match.
1624            # Ordinary token deltas contain no '<': one C-level search replaces
1625            # checking every possible prefix. Earliest candidate is the longest.
1626            start = text.find(tag[0], max(0, size - len(tag) + 1))
1627            while start >= 0 and size - start > best:
1628                if tag.startswith(text[start:]):
1629                    best = size - start
1630                    break
1631                start = text.find(tag[0], start + 1)
1632        return best
1633
1634    def _prefixed(self, fresh: int) -> str:
1635        """#5409: a call written `<function=tools NAME>` (a space for the dot of `tools.NAME`) is the call NAME, and one written
1636        `<function=tools>` (the bare prefix) is the one declared tool that takes the call's parameters.  Rewrites the complete
1637        ones in self.buf to `<function=NAME>` and returns the tail of a call still arriving, which feed() holds back until the next
1638        delta.  Only a declared name is ever the result; with none, or with two that fit, the text is left as it was.
1639        `fresh`: the length of the text just added; only the end of the buffer (that and a little before it) can hold a new match,
1640        so a long call is not scanned again with every token."""
1641        held = self._opener(fresh)
1642        start = max(0, len(self.buf) - fresh - _PREFIX_LOOKBACK)
1643        buf = self.buf[start:]
1644        if "<function=" in buf:
1645            def spaced(m):
1646                name = m.group(2).strip()
1647                return f"<function={name}>" if name in self.schemas else m.group(0)
1648            buf = _PREFIX_SPACED.sub(spaced, buf)
1649            m = _PREFIX_PART.search(buf)
1650            if m and not held:
1651                held, buf = buf[m.start():], buf[:m.start()]
1652            if self.recover:
1653                def bare(m):
1654                    body = m.group(3)
1655                    names = re.findall(r"<parameter=\s*([^<>\s]+?)\s*>", body)
1656                    tool = None if m.group(2) in self.schemas else self._tool_by_params(names)
1657                    return f"{m.group(1)}<function={tool}>{body}</function>" if tool else m.group(0)
1658                buf = _PREFIX_BARE.sub(bare, buf)
1659                m = _PREFIX_BARE_OPEN.search(buf)
1660                if m and m.group(1) not in self.schemas and not held and len(buf) - m.start() <= RCALL_MAX:
1661                    held, buf = buf[m.start():], buf[:m.start()]
1662            if buf != self.buf[start:]:
1663                self.buf = self.buf[:start] + buf
1664        return held
1665
1666    def _opener(self, fresh: int) -> str:
1667        """#5276: `<toolcall>` / `<tool-call>` (the opener written as text, misspelled) followed by `<function=NAME>` of a declared
1668        tool is `<tool_call>`, where a `<tool_call>` would open a call (in the reasoning the start of a line, outside code; in the
1669        answer outside code).  Prose that names the misspelled tag, or any other follower, is left as it was.  Returns the tail of
1670        an opener still arriving (held back by feed)."""
1671        start = max(0, len(self.buf) - fresh - _PREFIX_LOOKBACK)
1672        if "<tool" not in self.buf[start:]:
1673            return ""
1674        buf = self.buf
1675        pos, out = start, []
1676        for m in _MISSPELT_OPEN.finditer(buf, start):
1677            name = m.group(2).strip()
1678            name = self.aliases.get(name, name)
1679            if name in self.schemas and self._opens_at(m.start()):
1680                out.append(buf[pos:m.start()] + CALL_START + m.group(1) + FUNC_START + m.group(2) + ">")
1681                pos = m.end()
1682        buf = buf[:start] + "".join(out) + buf[pos:] if out else buf
1683        held = ""
1684        m = _MISSPELT_PART.search(buf, start)
1685        tail = buf[m.start():] if m else ""
1686        if not tail:                                        # the opener itself still arriving: a prefix of `<toolcall>`
1687            for k in range(min(len(buf), 11), 5, -1):
1688                if any(w.startswith(buf[-k:]) for w in ("<toolcall>", "<tool-call>")) and buf[-k:] != "<tool_":
1689                    tail = buf[-k:]
1690                    break
1691        if tail:
1692            held, buf = tail, buf[:len(buf) - len(tail)]
1693        self.buf = buf
1694        return held
1695
1696    def _tool_by_params(self, names: list[str]) -> str | None:
1697        """The one declared tool whose properties hold every one of `names` and whose required parameters are all in them."""
1698        found = []
1699        for tname, schema in self.schemas.items():
1700            params = (schema or {}).get("parameters") or {}
1701            props = params.get("properties") or {}
1702            if names and all(n in props for n in names) and all(r in names for r in params.get("required") or []):
1703                found.append(tname)
1704        return found[0] if len(found) == 1 else None
1705
1706    def feed(self, delta: str) -> list[Event]:
1707        if self._held:
1708            delta, self._held = self._held + delta, ""
1709        self.buf += delta
1710        if self.schemas and delta:
1711            self._held = self._prefixed(len(delta))
1712        return self._feed()
1713
1714    def _feed(self) -> list[Event]:
1715        out: list[Event] = []
1716        while True:
1717            if self.state == "rcall":
1718                # #804: a `<tool_call>` inside the reasoning, with tools declared.  It is held whole (never streamed
1719                # as a call) until it ends: a declared name is then a tool call, anything else stays reasoning text.
1720                body = self.buf[len(CALL_START):]
1721                end, think = call_end(body, hold=False), body.find(THINK_END)
1722                drop = len(CALL_END)
1723                f = function_end(body)               # #4427: as in the answer, a following call opener confirms an omitted closer
1724                if f >= 0 and (end < 0 or f < end) and re.match(r"<tool_call>\s*<function=\s*[^<>\s]+\s*>", body[f:].lstrip()):
1725                    end, drop = f, 0
1726                if end >= 0 and (think < 0 or think >= end):
1727                    call = None
1728                    try:
1729                        name = body[:end].strip()[len("<function="):].split(">", 1)[0].strip()
1730                        name = self.aliases.get(name, name)
1731                        if self._callable(name):
1732                            call = parse_tool_call(body[:end], self.schemas.get(name), self.notes)
1733                            call.name = name
1734                    except ValueError:
1735                        pass
1736                    raw = self.buf[:len(CALL_START) + end + drop]
1737                    if call is not None or self.pending:
1738                        self.pending.append([raw, call])    # settled by what follows it (see __init__)
1739                    else:
1740                        out.append(Event("reasoning", self._track(raw)))
1741                    self.buf = body[end + drop:]
1742                    self.state = "reasoning"
1743                elif think >= 0:                     # the thinking ended inside it: it never was a call
1744                    out += self._release(False)
1745                    out.append(Event("reasoning", self._track(self.buf[:len(CALL_START) + think])))
1746                    self.buf = body[think:]
1747                    self.state = "reasoning"
1748                elif len(body) > RCALL_MAX:          # a tag in the prose that never closes: stop holding the thinking back
1749                    out += self._release(False)
1750                    out.append(Event("reasoning", self._track(self.buf)))
1751                    self.buf = ""
1752                    self.state = "reasoning"
1753                else:
1754                    return out
1755            elif self.state == "reasoning":
1756                if self.pending:
1757                    # calls wait for what follows: more calls or whitespace keep them, `</think>` makes them acts,
1758                    # any other text means they were quoted
1759                    stripped = self.buf.lstrip()
1760                    if len(stripped) < len(self.buf):
1761                        self.pending[-1][0] += self.buf[:len(self.buf) - len(stripped)]
1762                        self.buf = stripped
1763                    if not self.buf:
1764                        return out
1765                    if self.buf.startswith(CALL_START):
1766                        self.state = "rcall"
1767                    elif self.buf.startswith(THINK_END):
1768                        out += self._release(True)
1769                    elif CALL_START.startswith(self.buf) or THINK_END.startswith(self.buf):
1770                        return out
1771                    else:
1772                        out += self._release(False)
1773                    continue
1774                i = self.buf.find(THINK_END)
1775                tool = self.buf.find(CALL_START) if self.schemas else -1
1776                if tool >= 0 and (i < 0 or tool < i):
1777                    if tool:
1778                        out.append(Event("reasoning", self._track(self.buf[:tool])))
1779                    if self._opener_ok():
1780                        self.buf = self.buf[tool:]
1781                        self.state = "rcall"
1782                    else:                            # mid-sentence, in a fence or in inline code: a quote
1783                        out.append(Event("reasoning", self._track(CALL_START)))
1784                        self.buf = self.buf[tool + len(CALL_START):]
1785                    continue
1786                if i < 0:
1787                    keep = self._hold(self.buf, (THINK_END, CALL_START) if self.schemas else (THINK_END,))
1788                    if len(self.buf) > keep:
1789                        out.append(Event("reasoning", self._track(self.buf[:len(self.buf) - keep])))
1790                        self.buf = self.buf[len(self.buf) - keep:]
1791                    return out
1792                quoted = self._quoted_think_end(i)
1793                if quoted is None:                   # held like a partial tag until the character after it is here
1794                    if i:
1795                        out.append(Event("reasoning", self._track(self.buf[:i])))
1796                        self.buf = self.buf[i:]
1797                    return out
1798                if quoted:                           # #537: a quoted `</think>` is reasoning text
1799                    out.append(Event("reasoning", self._track(self.buf[:i + len(THINK_END)])))
1800                    self.buf = self.buf[i + len(THINK_END):]
1801                    continue
1802                if i:
1803                    out.append(Event("reasoning", self._track(self.buf[:i])))
1804                self.buf = self.buf[i + len(THINK_END):]
1805                self.state, self.lead, self.after_think = "content", True, True
1806                self._reset_track()                               # the answer's own text starts here
1807            elif self.state == "content":
1808                if self.lead:                                   # newlines right after </think> or a call
1809                    stripped = self.buf.lstrip("\n")
1810                    if not stripped:
1811                        self.buf = ""
1812                        return out
1813                    self.buf, self.lead = stripped, False
1814                i = self.buf.find(CALL_START)
1815                stray = self._stray_think_at() if self.after_think else -1
1816                if stray >= 0 and (i < 0 or stray < i):
1817                    # #4077: the reasoning ended at a `</think>` the model wrote while thinking (quoting the format on a
1818                    # line of its own), and this is the one that ends it.  What came between was reasoning, already sent
1819                    # as the answer; the tag is dropped and the text after it starts over, so a call that follows is
1820                    # not taken for a quote by the code fence or backtick the reasoning left open.
1821                    if stray:
1822                        out.append(Event("content", self._track(self.buf[:stray])))
1823                    self.buf = self.buf[stray + len(THINK_END):]
1824                    self._reset_track()
1825                    self.lead = True
1826                    self.stray_think += 1
1827                    continue
1828                b, decided = self._bare_opener() if self.recover and self.schemas else (-1, False)
1829                if b >= 0 and (i < 0 or b < i):
1830                    # recover: <function=NAME> alone at the start of a line - the call without its <tool_call>.
1831                    # Until the name has arrived it is held.
1832                    j = b
1833                    while j > 0 and self.buf[j - 1] == "\n":
1834                        j -= 1
1835                    if j > 0 and self.buf[:j].strip():
1836                        out.append(Event("content", self._track(self.buf[:j])))
1837                    if not decided:
1838                        self.buf = self.buf[j:]
1839                        return out
1840                    self.buf = self.buf[b:]
1841                    self.state, self.bare = "call", True
1842                    continue
1843                if i < 0:
1844                    # Hold a partial tag AND the newlines before it: if a tool call follows, they are dropped,
1845                    # so emitting them early would make streamed and whole outputs differ.
1846                    j = len(self.buf) - self._hold(self.buf, (CALL_START, THINK_END) if self.after_think else (CALL_START,))
1847                    if self.recover and self.schemas:            # a line that may be becoming a bare <function=
1848                        k = self.buf.rfind("\n") + 1
1849                        tail = self.buf[k:]
1850                        if tail and FUNC_START.startswith(tail) and self._ok_at(k):
1851                            j = min(j, k)
1852                    while j > 0 and self.buf[j - 1] == "\n":
1853                        j -= 1
1854                    if j > 0:
1855                        out.append(Event("content", self._track(self.buf[:j])))
1856                        self.buf = self.buf[j:]
1857                    return out
1858                # #1058: an opener inside a code fence or inline code is text (a quoted example), never a call.  The
1859                # text before it decides, so streamed and whole outputs agree.  Mid-sentence openers still count.
1860                snap = self._snap()
1861                self._track(self.buf[:i])
1862                in_code = self._in_code()
1863                self._restore(snap)
1864                if in_code:
1865                    out.append(Event("content", self._track(self.buf[:i + len(CALL_START)])))
1866                    self.buf = self.buf[i + len(CALL_START):]
1867                    continue
1868                # A call is `<tool_call>` and then (after whitespace) `<function=`; the tag with anything else after
1869                # it is prose that names the format ("I'll use a <tool_call> block") - content, not a malformed call
1870                # that ends the request.  Until its follower has arrived it is held, like a partial tag.
1871                after = self.buf[i + len(CALL_START):].lstrip()
1872                if self.schemas and not after.startswith(FUNC_START):
1873                    loose = self._loose_open(after)
1874                    if loose == "wait":                  # may still become one: held like a partial tag
1875                        j = i
1876                        while j > 0 and self.buf[j - 1] == "\n":
1877                            j -= 1
1878                        if j > 0:
1879                            out.append(Event("content", self._track(self.buf[:j])))
1880                            self.buf = self.buf[j:]
1881                        return out
1882                    if loose:                            # #3441: `<=NAME>` etc. is `<function=NAME>`
1883                        at = len(self.buf) - len(after)
1884                        self.buf = self.buf[:at] + FUNC_START + loose[0] + ">" + after[loose[1]:]
1885                        continue
1886                kind = self._follower(after) if self.recover else None
1887                if (after.startswith("<") and kind is None and not FUNC_START.startswith(after)
1888                        and not after.startswith(FUNC_START)):
1889                    self.unread += 1
1890                if kind in ("param", "json"):
1891                    if i and self.buf[:i].strip():
1892                        out.append(Event("content", self._track(self.buf[:i].rstrip("\n"))))
1893                    rest = self.buf[i + len(CALL_START):]
1894                    if kind == "param":                  # <parameter=NAME> as the opener: the call's <function=NAME>
1895                        at = len(rest) - len(after)
1896                        rest = rest[:at] + FUNC_START + after[len(PARAM_START):]
1897                    self.buf = rest
1898                    self.state = "call" if kind == "param" else "json"
1899                    continue
1900                if kind == "wait":
1901                    after = ""
1902                is_call = re.match(r"<function=(\s*[^<>\s]+\s*)>", after)
1903                if is_call:
1904                    raw_name = is_call.group(1)
1905                    name = raw_name.strip()
1906                    name = self.aliases.get(name, name)
1907                    if raw_name != raw_name.strip() and name not in self.schemas:
1908                        is_call = None     # only declared names gain whitespace normalization
1909                is_partial = FUNC_START.startswith(after) or re.fullmatch(r"<function=\s*[^<>\s]*\s*", after)
1910                if not is_call and not is_partial:
1911                    out.append(Event("content", self._track(self.buf[:i + len(CALL_START)])))
1912                    self.buf = self.buf[i + len(CALL_START):]
1913                    continue
1914                if not is_call:
1915                    j = i
1916                    while j > 0 and self.buf[j - 1] == "\n":
1917                        j -= 1
1918                    if j > 0:
1919                        out.append(Event("content", self._track(self.buf[:j])))
1920                        self.buf = self.buf[j:]
1921                    return out
1922                if self.schemas or self.declared_only:
1923                    # #3075: a call counts only for a declared tool; the name must be complete to tell
1924                    gt = after.find(">")
1925                    nl = after.find("\n")
1926                    if gt < 0 and nl < 0:
1927                        j = i
1928                        while j > 0 and self.buf[j - 1] == "\n":
1929                            j -= 1
1930                        if j > 0:
1931                            out.append(Event("content", self._track(self.buf[:j])))
1932                            self.buf = self.buf[j:]
1933                        return out
1934                    if gt >= 0 and (nl < 0 or gt < nl) and not self._callable(after[len(FUNC_START):gt].strip()):
1935                        self.unread += 1                 # logged by the server: otherwise "the model ignored my tool" is the only clue
1936                        if len(self.unread_names) < 5:
1937                            self.unread_names.append(after[len(FUNC_START):gt].strip()[:80])
1938                        out.append(Event("content", self._track(self.buf[:i + len(CALL_START)])))
1939                        self.buf = self.buf[i + len(CALL_START):]
1940                        continue
1941                if i and self.buf[:i].strip():
1942                    out.append(Event("content", self._track(self.buf[:i].rstrip("\n"))))
1943                self.buf = self.buf[i + len(CALL_START):]
1944                self.state = "call"
1945            elif self.state == "json":
1946                # recover: `{"name": ..., "arguments": {...}}` inside the wrapper is the call once its </tool_call> has
1947                # arrived and it names a declared tool; anything else is the text it is
1948                i = self.buf.find(CALL_END)
1949                if i < 0:
1950                    return out
1951                call = json_tool_call(self.buf[:i].strip(), self.schemas)
1952                if call is None:
1953                    out.append(Event("content", self._track(CALL_START + self.buf[:i + len(CALL_END)])))
1954                else:
1955                    out.append(Event("tool_call", call=call))
1956                self.buf = self.buf[i + len(CALL_END):]
1957                self.state, self.lead = "content", call is not None
1958            else:
1959                drop = None
1960                if self.bare:                       # no wrapper: the call ends at its </function>; a stray
1961                    i = function_end(self.buf)      # </tool_call> after it is the wrapper's closer, dropped
1962                    if i >= 0:
1963                        after = self.buf[i:].lstrip()
1964                        if after.startswith(CALL_END):
1965                            drop = len(self.buf[i:]) - len(after) + len(CALL_END)
1966                        elif after and not CALL_END.startswith(after):
1967                            drop = 0
1968                else:
1969                    i = self._wrapped_call_end()
1970                    if i >= 0:
1971                        drop = len(CALL_END)
1972                    # Only a following call opener confirms an omitted wrapper closer.
1973                    f = function_end(self.buf)
1974                    nxt = self.buf[f:].lstrip() if f >= 0 else ""
1975                    if re.match(r"<tool_call>\s*<function=\s*[^<>\s]+\s*>", nxt):
1976                        i, drop = f, 0
1977                    if self.recover:                # a batch in one wrapper: the next call follows </function>
1978                        if nxt.startswith(PARAM_START) and self._follower(nxt) == "param":
1979                            at = len(self.buf) - len(nxt)
1980                            self.buf = self.buf[:at] + FUNC_START + nxt[len(PARAM_START):]
1981                            nxt = self.buf[at:]
1982                        if nxt.startswith(FUNC_START):
1983                            i, drop, self.batch = f, 0, True
1984                if self.stream_tools:
1985                    if i >= 0:
1986                        whole, self.buf = self.buf, self.buf[:i]     # scan only the body
1987                        final, self._final = self._final, True       # #5040: its end is known, so no closing tag is still arriving
1988                        out += self._scan()
1989                        out += self._close_scan()
1990                        self.buf, self._final = whole, final
1991                    else:
1992                        out += self._scan()
1993                if i < 0 or drop is None:
1994                    return out
1995                body = self.buf[:i]
1996                self.buf = self.buf[i + drop:]
1997                batch, self.batch = self.batch, False
1998                out += self._finish_call(body)
1999                if batch and out[-1].kind == "tool_call":
2000                    self.state, self.lead = "call", False
2001
2002    def finish(self, reason: str | None = None) -> list[Event]:
2003        """End of generation: flush whatever is held (an unterminated tool call is returned as content; one that was
2004        already announced stays unfinished: its JSON is not closed and no "tool_call" follows it, #211).  `reason` is
2005        how the turn ended: calls waiting from the reasoning become real calls only on a natural stop (None = stop);
2006        a turn cut by max tokens (or cancelled, or failed) keeps them as reasoning text (#1058)."""
2007        out = []
2008        if self._held:
2009            self.buf, self._held = self.buf + self._held, ""
2010        if self.buf and self.state in ("call", "rcall"):
2011            self._final = True                  # #4701: a call held after its closing tags (could a file's text go on?) is whole now
2012            out += self.feed("")
2013        if self.state == "rcall" and reason in (None, "stop"):
2014            # #4427: a call in the reasoning whose `</function>` is the end of the output (the `</tool_call>` left out)
2015            # is as whole as one in the answer: it waits for the turn's end like the others
2016            body = self.buf[len(CALL_START):]
2017            f = function_end(body)
2018            name = body.lstrip()[len(FUNC_START):].split(">", 1)[0].strip() if f >= 0 else ""
2019            name = self.aliases.get(name, name)
2020            if f >= 0 and not body[f:].strip() and self._callable(name):
2021                try:
2022                    call = parse_tool_call(body[:f], self.schemas.get(name), self.notes)
2023                    call.name = name
2024                    self.pending.append([self.buf, call])
2025                    self.buf, self.state = "", "reasoning"
2026                except ValueError:
2027                    pass
2028        if self.pending:
2029            out += self._release(reason in (None, "stop") and self.state == "reasoning" and not self.buf)
2030        if self.state == "call" and self.bare and function_end(self.buf) >= 0:
2031            i = function_end(self.buf)          # recover: a bare call is whole at its </function>
2032            body, rest = self.buf[:i], self.buf[i:].strip()
2033            self.buf = ""
2034            out += self._finish_call(body)
2035            if rest and not CALL_END.startswith(rest):
2036                out.append(Event("content", self._track(rest)))
2037            return out
2038        if self.state == "call" and self.stream_tools and self.scall is not None:
2039            out += self._scan()                 # the output ended inside a call that was already announced
2040            if self.ss == "function_done" and not self.buf[self.sp:].strip() and reason in (None, "stop"):
2041                # A natural end immediately after </function> retains native streaming recovery.
2042                out += self._close_scan()
2043                call = self.scall
2044                try:            # the final event carries the call's arguments, as the one _finish_call sends does
2045                    call = parse_tool_call(self.buf, self.schemas.get(call.name), self.notes)
2046                    call.name, call.id = self.scall.name, self.scall.id
2047                except ValueError:
2048                    pass
2049                out.append(Event("tool_call", call=call))
2050            elif self.ss == "function_done":
2051                out.append(Event("content", self._track(CALL_START + self.buf)))
2052            self.buf = ""
2053            self._reset_scan()
2054            return out
2055        if self.state == "reasoning" and self.buf == THINK_END:   # the output ends on a held `</think>`: its end
2056            self.buf, self.state = "", "content"
2057        if self.buf:
2058            # an unfinished call inside the reasoning (#804) is reasoning text, never a call
2059            kind = {"reasoning": "reasoning", "rcall": "reasoning", "content": "content"}.get(self.state, "content")
2060            text = CALL_START + self.buf if self.state in ("call", "json") and not self.bare else self.buf
2061            out.append(Event(kind, text))
2062            self.buf = ""
2063        return out
2064
2065    def _finish_call(self, body: str) -> list[Event]:
2066        """A whole call body in the template's form -> its tool_call event.  With recover, one that still does not
2067        parse is the text it is instead of an error that ends the request."""
2068        raw_name = body.strip()[len(FUNC_START):].split(">", 1)[0]
2069        name = raw_name.strip()
2070        name = self.aliases.get(name, name)
2071        bare, self.bare = self.bare, False
2072        try:
2073            if raw_name != raw_name.strip() and name not in self.schemas:
2074                raise ValueError("whitespace tool name is not declared")
2075            call = parse_tool_call(body, self.schemas.get(name), self.notes)
2076            call.name = name
2077        except ValueError:
2078            if not self.recover:
2079                raise
2080            self._reset_scan()
2081            self.state = "content"
2082            return [Event("content", self._track(body if bare else CALL_START + body + CALL_END))]
2083        if self.scall is not None:
2084            call.id = self.scall.id
2085        self._reset_scan()
2086        self.state, self.lead = "content", True
2087        return [Event("tool_call", call=call)]
2088
2089
2090class JsonOutputParser(OutputParser):
2091    """The parser for a model whose chat template tells it to write each call as JSON inside the wrapper:
2092    `<tool_call>\n{"name": NAME, "arguments": {...}}\n</tool_call>` (Qwen3, Hermes).  OutputParser already reads that form, but only
2093    as a recovery for a model that drifted off the XML form; for a JSON template it is the form itself, so it is read whether or
2094    not the server's tool_call_recovery is on.  Everything else (reasoning, code fences, declared-tool rules) is OutputParser's."""
2095
2096    def __init__(self, thinking: bool = True, tools: list[dict] | None = None, stream_tools: bool = False,
2097                 recover: bool = False, declared_only: bool = False, deferred: bool = False):
2098        super().__init__(thinking=thinking, tools=tools, stream_tools=stream_tools, recover=True,
2099                         declared_only=declared_only, deferred=deferred)
2100
2101
2102def parser_for_template(source: str | None):
2103    """The OutputParser class for a chat template's text, by the tool-call form the template documents (serve/toolformat.py):
2104    the JSON form gets JsonOutputParser; the XML form every Strata model ships with, templates without tools, and forms nothing
2105    here reads keep OutputParser (the same class as before this existed).  DeepSeek's DSML parser is chosen by the model family
2106    (Service.set_family), not here."""
2107    from serve import toolformat
2108    return JsonOutputParser if toolformat.tool_format(source or "") == "json" else OutputParser