Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(models): onboard meta-models/Muse-Glimmer-30B (#888)
Shai Shmuele8aeb682281a
diff --git a/packages/sie_server/models/meta-models__Muse-Glimmer-30B.yaml b/packages/sie_server/models/meta-models__Muse-Glimmer-30B.yamlnew file mode 100644index 000000000..cc1fc42ec--- /dev/null+++ b/packages/sie_server/models/meta-models__Muse-Glimmer-30B.yaml@@ -0,0 +1,96 @@+sie_id: meta-models/Muse-Glimmer-30B+hf_id: meta-models/Muse-Glimmer-30B+hf_revision: cec94fcfd6512f2cfe708138c32533b346ea4f69+# MuseGlimmerForConditionalGeneration: 29.8B parameters in 55.5 GiB of BF16+# weights, with a native window of 131,072 tokens. The sglang-cu130 engine+# registers the architecture and its reasoning and tool parsers, both named+# ``muse``. No remote code. SGLangMuseAdapter rewrites the model's channel framing+# into <think> and <tool_call> blocks for the native /generate surfaces.+inputs:+ text: true+ image: true+ audio: false+ video: false+tasks:+ generate:+ context_length: 8192+ max_output_tokens: 4096+ # The chat template has no switch that turns reasoning off and never reads+ # enable_thinking. Declaring it true marks that reasoning private.+ chat_template_kwargs:+ enable_thinking: true+ capabilities:+ grammar: ["json_schema", "regex"]+ streaming: true+ tools: true+max_sequence_length: 8192+profiles:+ default:+ max_batch_tokens: 16384+ kv_budget_tokens: 8192+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.cuda13:SGLangMuseAdapter+ adapter_options:+ loadtime:+ mem_fraction_static: 0.85+ served_model_name: meta-models/Muse-Glimmer-30B+ trust_remote_code: false+ grammar_backend: xgrammar+ reasoning_parser: muse+ tool_call_parser: muse+ # The vendor's draft doubles decode throughput on H100: 47 to 97 tokens/s+ # at one request and 369 to 671 at eight when greedy, and 82 to 87 at one+ # request under the sampling below. JSON schema, regex, tool and image+ # requests all passed on this shape.+ speculative_needs_extra_buffer: false+ speculative:+ enabled: true+ algorithm: dflash+ draft_model: meta-models/Muse-Glimmer-30B-assistant+ draft_model_revision: c676cce91658f9568aaf264a416211e2782735b7+ runtime:+ first_chunk_timeout_s: 90+ inter_chunk_timeout_s: 15+ overall_timeout_s: 600+ # The model card's recommended sampling.+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 64+ stop_tokens:+ - "<|eot|>"++ # H100-80GB: the native window, without FP8. The draft and its cache need the+ # extra 5%: 0.85 caps the KV cache at 92,938 tokens and 0.90 raises it to 157,094.+ # A 130,010-token prompt answered correctly with 78.9 GiB of the GPU in use.+ h100-128k:+ max_output_tokens: 32768+ max_batch_tokens: 131072+ kv_budget_tokens: 131072+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.cuda13:SGLangMuseAdapter+ adapter_options:+ loadtime:+ max_seq_length: 131072+ mem_fraction_static: 0.9+ served_model_name: meta-models/Muse-Glimmer-30B+ trust_remote_code: false+ grammar_backend: xgrammar+ reasoning_parser: muse+ tool_call_parser: muse+ speculative_needs_extra_buffer: false+ speculative:+ enabled: true+ algorithm: dflash+ draft_model: meta-models/Muse-Glimmer-30B-assistant+ draft_model_revision: c676cce91658f9568aaf264a416211e2782735b7+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 64+ stop_tokens:+ - "<|eot|>"diff --git a/packages/sie_server/src/sie_server/adapters/sglang/cuda13.py b/packages/sie_server/src/sie_server/adapters/sglang/cuda13.pyindex 5ac59b2ce..4ad0da068 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/cuda13.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/cuda13.py@@ -1,6 +1,9 @@+from collections.abc import AsyncIteratorfrom typing import Any+from sie_server.adapters._generation_base import GenerationChunkfrom sie_server.adapters.sglang.generation import SGLangGenerationAdapter+from sie_server.adapters.sglang.muse_channels import translate_muse_channelsclass SGLangCuda13Adapter(SGLangGenerationAdapter):@@ -38,3 +41,10 @@ class SGLangStrictThinkingAdapter(SGLangCuda13Adapter):extra_launch_args=launch_args,**kwargs,)+++class SGLangMuseAdapter(SGLangCuda13Adapter):+ """CUDA 13 SGLang lane for Muse Glimmer's channel-framed native output."""++ def generate(self, prompt: str, **kwargs: Any) -> AsyncIterator[GenerationChunk]:+ return translate_muse_channels(super().generate(prompt, **kwargs))diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex 2cf2f9d34..e18d7ee00 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -1147,6 +1147,8 @@ class SGLangGenerationAdapter(SGLangLoraMixin, GenerationAdapter):- ``NGRAM`` (model-independent; the documented fallback thatworks for any base model — the speculative-decoding investigationchose this for the Qwen3-4B-Instruct-2507 side-cell).+ - ``DFLASH`` (requires the external draft model a vendor publishes+ for it; Muse Glimmer's serves as published).Recognised keys:@@ -1154,7 +1156,7 @@ class SGLangGenerationAdapter(SGLangLoraMixin, GenerationAdapter):Top-level gate. When False (or block missing), returns``[]`` — caller still gets the unchanged baseline command.``algorithm`` (str, required when enabled)- One of ``nextn``, ``eagle``, ``eagle3``, ``ngram`` (case-insensitive).+ One of ``nextn``, ``eagle``, ``eagle3``, ``ngram``, ``dflash`` (case-insensitive).Surfaced verbatim to SGLang's ``--speculative-algorithm``.``num_steps`` (int, optional)``--speculative-num-steps``. Qwen3.5-4B's documented@@ -1193,10 +1195,10 @@ class SGLangGenerationAdapter(SGLangLoraMixin, GenerationAdapter):)return []algorithm = algorithm_raw.strip().upper()- if algorithm not in {"NEXTN", "EAGLE", "EAGLE3", "NGRAM"}:+ if algorithm not in {"NEXTN", "EAGLE", "EAGLE3", "NGRAM", "DFLASH"}:logger.warning("speculative.algorithm=%r is not in the recognised set "- "{NEXTN, EAGLE, EAGLE3, NGRAM}; forwarding to SGLang anyway "+ "{NEXTN, EAGLE, EAGLE3, NGRAM, DFLASH}; forwarding to SGLang anyway ""(it will reject if unsupported).",algorithm_raw,)@@ -1579,15 +1581,15 @@ class SGLangGenerationAdapter(SGLangLoraMixin, GenerationAdapter):"temperature": temperature,"top_p": top_p,}- if self._reasoning_parser == "gemma4":- # Gemma 4's private reasoning boundary uses special channel- # tokens. SGLang's default detokenization drops those tokens from- # the native /generate text while leaving the ordinary- # ``thought\n`` label and reasoning body visible, so SIE's- # family-aware privacy filter can no longer identify the block.- # Preserve the markers at this internal boundary; every public- # generation surface removes the complete reasoning block before- # returning content to the caller.+ if self._reasoning_parser in ("gemma4", "muse"):+ # Gemma 4's and Muse Glimmer's private reasoning boundaries use+ # special channel tokens. SGLang's default detokenization drops+ # those tokens from the native /generate text while leaving the+ # ordinary labels and reasoning body visible, so SIE's family-aware+ # privacy filter can no longer identify the block. Preserve the+ # markers at this internal boundary; every public generation+ # surface removes the complete reasoning block before returning+ # content to the caller.sampling_params["skip_special_tokens"] = False# SGLang accepts ``top_k`` (int) and ``repetition_penalty`` (float)# natively under ``sampling_params``. Forward only when the gatewaydiff --git a/packages/sie_server/src/sie_server/adapters/sglang/muse_channels.py b/packages/sie_server/src/sie_server/adapters/sglang/muse_channels.pynew file mode 100644index 000000000..56004893d--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/sglang/muse_channels.py@@ -0,0 +1,199 @@+"""Translate Muse Glimmer's channel framing into SIE's reasoning and tool-call forms.++SGLang's native ``/generate`` returns the model's raw wire format. A turn is a+sequence of channels, each addressed to a recipient::++ to=self<|message|>REASONING<|eom|><|start|>assistant to=user<|message|>ANSWER++Tool calls travel on a channel addressed to the tool::++ <|start|>assistant to=NAME<|message|><atem:function_calls>+ <atem:invoke name="NAME">+ <atem:parameter name="KEY">VALUE</atem:parameter>+ </atem:invoke>+ </atem:function_calls>++Every generation surface already handles ``<think>`` and ``<tool_call>`` blocks,+so rewriting the stream once at the adapter boundary keeps the format out of the+rest of the stack: the ``to=self`` channel becomes a ``<think>`` block, tool+channels become ``<tool_call>`` blocks in the Qwen XML form, and the ``to=user``+channel becomes plain text.+"""++from __future__ import annotations++import re+from collections.abc import AsyncIterator+from dataclasses import replace+from typing import Any++from sie_server.adapters._generation_base import GenerationChunk, aclose_with_error_precedence++_ASSISTANT = "<|start|>assistant"+_MESSAGE = "<|message|>"+_CHANNEL_ENDS = ("<|eom|>", "<|eot|>")+_THINK_OPEN = "<think>"+_THINK_CLOSE = "</think>"++_HEADER_RE = re.compile(r"(?:<\|start\|>assistant)?\s*(?:to=([^\s<]+))?\s*<\|message\|>")+_INVOKE_RE = re.compile(r'<atem:invoke\b[^>]*?\bname="([^"]+)"[^>]*?>(.*?)</atem:invoke>', re.DOTALL)+_PARAMETER_RE = re.compile(r'<atem:parameter\b[^>]*?\bname="([^"]+)"[^>]*?>(.*?)</atem:parameter>', re.DOTALL)+++def _may_become_header(text: str) -> bool:+ """Return whether buffered text could still grow into a channel header."""+ if text.startswith(_ASSISTANT):+ text = text[len(_ASSISTANT) :].lstrip()+ elif _ASSISTANT.startswith(text):+ return True+ if text.startswith("to="):+ recipient, angle, marker = text[3:].partition("<")+ if any(char.isspace() for char in recipient.rstrip()):+ return False+ return not angle or _MESSAGE.startswith("<" + marker)+ return "to=".startswith(text) or _MESSAGE.startswith(text)+++def _held_back(text: str, markers: tuple[str, ...]) -> int:+ """Return the length of the longest suffix of ``text`` that could become a marker."""+ for length in range(min(len(text), max(map(len, markers)) - 1), 0, -1):+ suffix = text[-length:]+ if any(marker.startswith(suffix) for marker in markers):+ return length+ return 0+++def _tool_name(emitted: str) -> str:+ """Undo the doubled namespace (``name.name``) the chat template can provoke."""+ head, _, tail = emitted.partition(".")+ return head if head == tail else emitted+++def _tool_call_blocks(body: str) -> str:+ """Rewrite each complete ``atem:invoke`` as a ``<tool_call>`` block."""+ blocks: list[str] = []+ for name, invoke in _INVOKE_RE.findall(body):+ parameters = "".join(+ f"<parameter={key}>\n{value}\n</parameter>\n" for key, value in _PARAMETER_RE.findall(invoke)+ )+ blocks.append(f"<tool_call>\n<function={_tool_name(name)}>\n{parameters}</function>\n</tool_call>")+ return "".join(blocks)+++class MuseChannelTranslator:+ """Rewrite one candidate's generated text incrementally."""++ def __init__(self) -> None:+ self._buffer = ""+ # ``self``, ``user`` or ``tool``; ``None`` while between channels.+ self._channel: str | None = None++ def feed(self, text: str) -> str:+ self._buffer += text+ output: list[str] = []+ progressed = True+ while self._buffer and progressed:+ progressed = self._drain_channel(output) if self._channel else self._open_channel(output)+ return "".join(output)++ def finish(self) -> str:+ """Flush at end of stream. Truncated control text never becomes output."""+ buffered, self._buffer = self._buffer, ""+ channel, self._channel = self._channel, None+ if channel == "tool":+ return _tool_call_blocks(buffered)+ if channel == "self":+ return buffered.replace(_THINK_CLOSE, "") + _THINK_CLOSE+ if channel == "user":+ return buffered+ stripped = buffered.lstrip()+ return "" if not stripped or "=" in stripped or stripped.startswith("<") else buffered++ def _open_channel(self, output: list[str]) -> bool:+ stripped = self._buffer.lstrip()+ header = _HEADER_RE.match(stripped)+ if header is not None:+ recipient = header[1] or "user"+ self._channel = recipient if recipient in ("self", "user") else "tool"+ self._buffer = stripped[header.end() :]+ if self._channel == "self":+ output.append(_THINK_OPEN)+ return True+ if _may_become_header(stripped):+ return False+ # A JSON schema or regex response format constrains the output from its+ # first byte, so it arrives without a header.+ self._channel = "user"+ return True++ def _drain_channel(self, output: list[str]) -> bool:+ ends = [(at, len(end)) for end in _CHANNEL_ENDS if (at := self._buffer.find(end)) >= 0]+ if not ends:+ if self._channel == "tool":+ return False # A call is rewritten whole, once it has closed.+ markers = (*_CHANNEL_ENDS, _THINK_CLOSE) if self._channel == "self" else _CHANNEL_ENDS+ cut = len(self._buffer) - _held_back(self._buffer, markers)+ output.append(self._visible(self._buffer[:cut]))+ self._buffer = self._buffer[cut:]+ return False+ end_at, end_length = min(ends)+ body = self._buffer[:end_at]+ output.append(_tool_call_blocks(body) if self._channel == "tool" else self._visible(body))+ if self._channel == "self":+ output.append(_THINK_CLOSE)+ self._buffer = self._buffer[end_at + end_length :]+ self._channel = None+ return True++ def _visible(self, text: str) -> str:+ # Reasoning that quotes the closing tag must not end the private block early.+ return text.replace(_THINK_CLOSE, "") if self._channel == "self" else text+++def translate_muse_text(text: str) -> str:+ """Rewrite a complete generation."""+ translator = MuseChannelTranslator()+ return translator.feed(text) + translator.finish()+++def _translate_candidate(candidate: dict[str, Any]) -> dict[str, Any]:+ text = candidate.get("text")+ if not isinstance(text, str):+ return candidate+ translated = translate_muse_text(text)+ return candidate if translated == text else {**candidate, "text": translated, "logprobs": None}+++async def translate_muse_channels(chunks: AsyncIterator[GenerationChunk]) -> AsyncIterator[GenerationChunk]:+ """Rewrite an adapter stream, keeping per-choice state for ``n > 1``."""+ translators: dict[int, MuseChannelTranslator] = {}+ emitted_text = False+ terminal_outcome_selected = False+ try:+ async for chunk in chunks:+ translator = translators.setdefault(chunk.choice_index, MuseChannelTranslator())+ text = translator.feed(chunk.text_delta)+ ending = chunk.done or chunk.finish_reason is not None+ if ending:+ text += translator.finish()+ elif not text:+ continue+ candidates = chunk.candidates+ if candidates is not None:+ candidates = tuple(_translate_candidate(candidate) for candidate in candidates)+ is_first = bool(text) and not emitted_text+ emitted_text = emitted_text or bool(text)+ terminal_outcome_selected = terminal_outcome_selected or chunk.done+ yield replace(+ chunk,+ text_delta=text,+ is_first=is_first,+ logprobs=chunk.logprobs if text == chunk.text_delta else None,+ candidates=candidates,+ )+ finally:+ await aclose_with_error_precedence(+ chunks,+ outcome_selected=terminal_outcome_selected,+ context="muse-channel upstream iterator",+ )diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex 331315f4a..bed0e9b2c 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -965,6 +965,15 @@ def _prepare_sglang_body(max_tokens: int | None,seed: int | None,) -> dict[str, Any]:+ # SGLang's chat endpoint parses Muse Glimmer's tool calls without constraining+ # them and ignores a regex sent alongside ``tool_choice``, so it would return a+ # plain answer to a request that requires a call. The queued route can force one.+ if adapter.reasoning_parser == "muse" and body.get("tool_choice") not in (None, "auto", "none"):+ raise _bad_request(+ "'tool_choice' must be 'auto' or 'none' on this route for this model, which cannot force a tool call",+ param="tool_choice",+ code="unsupported_field",+ )proxied = _prepare_chat_body(body,config=config,diff --git a/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py b/packages/sie_server/src/sie_server/processors/remote_chat_prompt.pyindex 21080a9a0..d283affdc 100644--- a/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py+++ b/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py@@ -51,6 +51,8 @@ def _tool_format(config: ModelConfig) -> ToolCallFormat:return "qwen_xml"if parser.startswith("glm"):return "glm_xml"+ if parser == "muse":+ return "muse_atem"return "auto"diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex 652321178..2d089c108 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -1391,8 +1391,8 @@ class StreamingProcessor:``--tool-call-parser`` launch flag) — instead of guessing perblock from the model output. ``qwen25`` (Qwen2.5-style Hermes JSON)and ``hermes`` → ``hermes_json``; ``qwen3_coder`` (and any other- ``qwen*`` parser) → ``qwen_xml``; ``glm*`` → ``glm_xml``; anything- unknown / missing → ``auto`` (keep the runtime heuristic so+ ``qwen*`` parser) → ``qwen_xml``; ``glm*`` → ``glm_xml``; ``muse`` →+ ``muse_atem``; anything unknown / missing → ``auto`` (keep the runtime heuristic soout-of-tree models still work)."""try:@@ -1413,6 +1413,8 @@ class StreamingProcessor:return "qwen_xml"if parser_l.startswith("glm"):return "glm_xml"+ if parser_l == "muse":+ return "muse_atem"return "auto"@staticmethoddiff --git a/packages/sie_server/src/sie_server/processors/tool_call_grammar.py b/packages/sie_server/src/sie_server/processors/tool_call_grammar.pyindex 2ba23e513..2d7032723 100644--- a/packages/sie_server/src/sie_server/processors/tool_call_grammar.py+++ b/packages/sie_server/src/sie_server/processors/tool_call_grammar.py@@ -119,6 +119,8 @@ def build_tool_choice_grammar(pattern = _hermes_json_force_regex(allowed)elif tool_call_format == "glm_xml":pattern = _glm_xml_force_regex(allowed)+ elif tool_call_format == "muse_atem":+ pattern = _muse_atem_force_regex(allowed)elif tool_call_format == "auto":# ``auto`` means the model's on-wire tool-call format could not be# confidently resolved from config. Guessing Qwen XML here would@@ -207,3 +209,26 @@ def _glm_xml_force_regex(names: list[str]) -> str:pair = r"<arg_key>[^<>]*</arg_key>\s*<arg_value>" + _INNER + r"</arg_value>\s*"block = r"<tool_call>\s*" + _name_alternation(names) + r"\s*(?:" + pair + r")*</tool_call>"return r"\s*(?:" + block + r"\s*)+"+++def _muse_atem_force_regex(names: list[str]) -> str:+ """Force one Muse Glimmer tool channel holding one-or-more calls.++ A channel looks like::++ to=NAME<|message|><atem:function_calls>+ <atem:invoke name="NAME">+ <atem:parameter name="KEY">VALUE</atem:parameter>+ </atem:invoke>+ </atem:function_calls>++ The generation prompt ends at ``<|start|>assistant``, so the output starts at+ the recipient and constraining it skips the reasoning channel. Nothing optional+ surrounds the channel: greedy decoding fills optional leading whitespace up to+ the token limit. Parameters are complete so every accepted block parses;+ values stay free, as in the other formats.+ """+ name = _name_alternation(names)+ parameter = r'<atem:parameter name="[^"<>]+">' + _INNER + r"</atem:parameter>\s*"+ invoke = r'<atem:invoke name="' + name + r'">\s*(?:' + parameter + r")*</atem:invoke>"+ return r" to=" + name + r"<\|message\|><atem:function_calls>\s*(?:" + invoke + r"\s*)+</atem:function_calls>"diff --git a/packages/sie_server/src/sie_server/processors/tool_call_parser.py b/packages/sie_server/src/sie_server/processors/tool_call_parser.pyindex c91b63bc4..17f35ab57 100644--- a/packages/sie_server/src/sie_server/processors/tool_call_parser.py+++ b/packages/sie_server/src/sie_server/processors/tool_call_parser.py@@ -57,6 +57,8 @@ _PARALLEL_TOOL_CALLS_VIOLATED = "parallel_tool_calls_violated"# - ``qwen_xml`` — Qwen3(-Coder): ``<function=NAME><parameter=K>V</parameter>…</function>``# - ``hermes_json`` — Hermes: ``{"name": "...", "arguments": {...}}``# - ``glm_xml`` — GLM: ``NAME<arg_key>K</arg_key><arg_value>V</arg_value>…``+# - ``muse_atem`` — Muse Glimmer: its adapter rewrites ``atem:invoke`` blocks+# into the ``qwen_xml`` form; only forcing sees the original.# - ``auto`` — runtime heuristic (XML if the block starts with# ``<function=``, else JSON). Kept as a fallback for# callers that cannot resolve the model's configured@@ -64,7 +66,7 @@ _PARALLEL_TOOL_CALLS_VIOLATED = "parallel_tool_calls_violated"# model config (``tasks.generate`` → adapter# ``tool_call_parser``) so production traffic uses an# explicit format rather than guessing per block.-ToolCallFormat = Literal["auto", "qwen_xml", "hermes_json", "glm_xml"]+ToolCallFormat = Literal["auto", "qwen_xml", "hermes_json", "glm_xml", "muse_atem"]# A model that emits ``<tool_call>`` and never closes it would let# ``tool_buffer`` grow without bound (same for free-form prose with no@@ -813,7 +815,7 @@ def _tool_call_deltas(# Qwen3.5's chat template emits format (2); other models emit (1).# ``tool_call_format`` makes the choice explicit (config-driven);# ``"auto"`` falls back to the original "starts-with-<function=" heuristic.- if tool_call_format == "qwen_xml":+ if tool_call_format in ("qwen_xml", "muse_atem"):name, arguments = _parse_xml_tool_call(raw, schemas)elif tool_call_format == "hermes_json":name, arguments = _parse_hermes_tool_call(raw)@@ -857,12 +859,13 @@ def _parse_hermes_tool_call(raw: str) -> tuple[object, object]:_XML_FUNC_RE = re.compile(r"<function=([^>\s]+)\s*>")-# Matches only a parameter *opener* — ``<parameter=name>`` — with a bounded-# character class, so it cannot backtrack. The value and closing-# ``</parameter>`` are located with a linear ``str.find`` below rather than a-# ``(.*?)...</parameter>`` group, which on a 256 KiB buffer of garbled output-# (many openers, no closers) is O(n²) and runs INLINE on the event loop.-_XML_PARAM_OPEN_RE = re.compile(r"<parameter=([^>\s]+)\s*>")+# Matches only a parameter *opener* — ``<parameter=name>``. A name may contain+# spaces, as JSON Schema allows. Its character classes stop at the next ``<`` or+# ``>``, so an opener that never closes cannot rescan the rest of the buffer. The+# value and closing ``</parameter>`` are located with a linear ``str.find`` below+# rather than a ``(.*?)...</parameter>`` group, which on a 256 KiB buffer of garbled+# output (many openers, no closers) is O(n²) and runs INLINE on the event loop.+_XML_PARAM_OPEN_RE = re.compile(r"<parameter=([^<>]*[^<>\s])\s*>")_XML_PARAM_CLOSE = "</parameter>"# Hard cap on parameters parsed from one XML tool call. Defends against an# adversarial buffer packed with openers; well-formed calls have a handful.diff --git a/packages/sie_server/tests/adapters/test_sglang_muse_channels.py b/packages/sie_server/tests/adapters/test_sglang_muse_channels.pynew file mode 100644index 000000000..0c8ed7b34--- /dev/null+++ b/packages/sie_server/tests/adapters/test_sglang_muse_channels.py@@ -0,0 +1,322 @@+"""Muse Glimmer's channel framing becomes SIE's reasoning and tool-call forms."""++from __future__ import annotations++import asyncio+import json+from collections.abc import AsyncIterator+from typing import Any+from unittest.mock import MagicMock, patch++import pytest+from sie_server.adapters._generation_base import GenerationChunk, suppress_thinking_blocks+from sie_server.adapters.sglang.cuda13 import SGLangMuseAdapter+from sie_server.adapters.sglang.muse_channels import (+ MuseChannelTranslator,+ translate_muse_channels,+ translate_muse_text,+)+from sie_server.processors.tool_call_parser import parse_tool_call_stream++# Recorded from the model through SGLang's native /generate with+# skip_special_tokens disabled.+ANSWER = (+ " to=self<|message|>The user asks 17 times 3. That is 51.<|eom|>"+ "<|start|>assistant to=user<|message|>17 times 3 is 51."+)+TOOL_CALL = (+ " to=self<|message|>I should call the weather tool.<|eom|>"+ "<|start|>assistant to=get_weather<|message|><atem:function_calls>\n"+ '<atem:invoke name="get_weather">\n'+ '<atem:parameter name="city">Paris</atem:parameter>\n'+ '<atem:parameter name="unit">c</atem:parameter>\n'+ "</atem:invoke>\n"+ "</atem:function_calls>"+)+FORCED_TOOL_CALL = (+ " to=get_weather<|message|><atem:function_calls>\n"+ '<atem:invoke name="get_weather">\n'+ '<atem:parameter name="city">Paris</atem:parameter>\n'+ "</atem:invoke>\n"+ "</atem:function_calls>"+)+WEATHER = {+ "type": "function",+ "function": {+ "name": "get_weather",+ "parameters": {+ "type": "object",+ "properties": {"city": {"type": "string"}, "unit": {"type": "string"}, "days": {"type": "integer"}},+ },+ },+}+++def _split(text: str, size: int) -> list[str]:+ return [text[i : i + size] for i in range(0, len(text), size)]+++async def _chunks(*pieces: str, finish_reason: Any = "stop") -> AsyncIterator[GenerationChunk]:+ for index, piece in enumerate(pieces):+ yield GenerationChunk(text_delta=piece, is_first=index == 0)+ yield GenerationChunk(text_delta="", done=True, finish_reason=finish_reason, prompt_tokens=3, completion_tokens=9)+++async def _collect(stream: AsyncIterator[GenerationChunk]) -> list[GenerationChunk]:+ return [chunk async for chunk in stream]+++def _text(chunks: list[GenerationChunk]) -> str:+ return "".join(chunk.text_delta for chunk in chunks)++[email protected]("size", [1, 2, 3, 7, 11, 10_000])+def test_answer_reads_the_same_however_the_stream_is_cut(size: int) -> None:+ translator = MuseChannelTranslator()+ translated = "".join(translator.feed(piece) for piece in _split(ANSWER, size)) + translator.finish()++ assert translated == "<think>The user asks 17 times 3. That is 51.</think>17 times 3 is 51."++[email protected]("size", [1, 2, 3, 7, 11, 10_000])+def test_tool_channel_becomes_a_tool_call_block_however_the_stream_is_cut(size: int) -> None:+ translator = MuseChannelTranslator()+ translated = "".join(translator.feed(piece) for piece in _split(TOOL_CALL, size)) + translator.finish()++ assert translated == (+ "<think>I should call the weather tool.</think>"+ "<tool_call>\n<function=get_weather>\n"+ "<parameter=city>\nParis\n</parameter>\n"+ "<parameter=unit>\nc\n</parameter>\n"+ "</function>\n</tool_call>"+ )+++def test_each_tool_channel_of_a_turn_becomes_its_own_block() -> None:+ second = TOOL_CALL.split("<|eom|>")[1].replace("get_weather", "get_time")++ translated = translate_muse_text(f"{TOOL_CALL}<|eom|>{second}<|eot|>")++ assert translated.count("<tool_call>") == 2+ assert "<function=get_weather>" in translated+ assert "<function=get_time>" in translated+++def test_visible_text_streams_without_waiting_for_the_channel_to_close() -> None:+ translator = MuseChannelTranslator()++ translator.feed("<|start|>assistant to=user<|message|>")++ assert translator.feed("Hello") == "Hello"+ assert translator.feed(" wor") == " wor"+ assert translator.feed("ld<|eo") == "ld"+ assert translator.feed("t|>") == ""++[email protected]("text", ['{"city": "Paris", "population_millions": 2.1}', "yes", "t", "to", "tomorrow"])+def test_grammar_output_without_a_header_passes_through(text: str) -> None:+ assert translate_muse_text(text) == text+++def test_forced_tool_channel_becomes_a_tool_call_block() -> None:+ assert translate_muse_text(FORCED_TOOL_CALL) == (+ "<tool_call>\n<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n</function>\n</tool_call>"+ )+++def test_prose_on_the_user_channel_that_quotes_a_call_stays_prose() -> None:+ quoted = '<atem:function_calls><atem:invoke name="x"></atem:invoke></atem:function_calls>'++ translated = translate_muse_text(f"<|start|>assistant to=user<|message|>Models emit {quoted}")++ assert translated == f"Models emit {quoted}"+++def test_reasoning_that_quotes_the_closing_tag_stays_private() -> None:+ translated = translate_muse_text(+ " to=self<|message|>The </think> tag is private.<|eom|><|start|>assistant to=user<|message|>Done."+ )++ assert translated == "<think>The tag is private.</think>Done."+++ "truncated",+ [" to=sel", " to=self<|mess", "<|start|>assistant to=us", "<|start|>assi"],+)+def test_truncated_control_text_never_reaches_the_output(truncated: str) -> None:+ assert translate_muse_text(truncated) == ""+++def test_reasoning_cut_by_the_token_limit_stays_closed() -> None:+ assert translate_muse_text(" to=self<|message|>Still thinking") == "<think>Still thinking</think>"+++def test_tool_call_cut_by_the_token_limit_produces_no_partial_call() -> None:+ cut = TOOL_CALL[: TOOL_CALL.index("</atem:invoke>")]++ assert translate_muse_text(cut) == "<think>I should call the weather tool.</think>"+++def test_doubled_tool_namespace_is_removed() -> None:+ doubled = FORCED_TOOL_CALL.replace('name="get_weather"', 'name="get_weather.get_weather"')++ assert "<function=get_weather>" in translate_muse_text(doubled)+++def test_stream_hides_reasoning_and_keeps_the_terminal_metadata() -> None:+ stream = suppress_thinking_blocks(translate_muse_channels(_chunks(*_split(ANSWER, 4))))++ chunks = asyncio.run(_collect(stream))++ assert _text(chunks) == "17 times 3 is 51."+ assert [chunk.is_first for chunk in chunks if chunk.is_first] == [True]+ assert chunks[-1].done is True+ assert chunks[-1].finish_reason == "stop"+ assert chunks[-1].completion_tokens == 9+++def test_stream_gives_each_choice_its_own_state() -> None:+ async def interleaved() -> AsyncIterator[GenerationChunk]:+ for first, second in zip(_split(ANSWER, 5), _split(TOOL_CALL, 5), strict=False):+ yield GenerationChunk(text_delta=first, choice_index=0)+ yield GenerationChunk(text_delta=second, choice_index=1)++ chunks = asyncio.run(_collect(translate_muse_channels(interleaved())))++ assert "".join(c.text_delta for c in chunks if c.choice_index == 0).startswith("<think>The user asks")+ assert "".join(c.text_delta for c in chunks if c.choice_index == 1).startswith("<think>I should call")+++def test_stream_flushes_a_choice_on_its_own_finish_reason_only_once() -> None:+ async def script() -> AsyncIterator[GenerationChunk]:+ yield GenerationChunk(text_delta=" to=self<|message|>hmm", choice_index=1)+ yield GenerationChunk(text_delta="", finish_reason="length", choice_index=1)+ yield GenerationChunk(text_delta="", done=True, finish_reason="stop", choice_index=1)++ chunks = asyncio.run(_collect(translate_muse_channels(script())))++ assert _text(chunks) == "<think>hmm</think>"+++def test_stream_translates_terminal_candidates() -> None:+ async def script() -> AsyncIterator[GenerationChunk]:+ yield GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ candidates=({"text": ANSWER, "finish_reason": "stop", "logprobs": [{"token": "x"}]},),+ )++ chunks = asyncio.run(_collect(translate_muse_channels(script())))++ assert chunks[-1].candidates == (+ {+ "text": "<think>The user asks 17 times 3. That is 51.</think>17 times 3 is 51.",+ "finish_reason": "stop",+ "logprobs": None,+ },+ )+++def test_stream_keeps_logprobs_only_on_text_it_did_not_change() -> None:+ logprobs = ({"token": "x", "logprob": -0.1},)++ async def script() -> AsyncIterator[GenerationChunk]:+ yield GenerationChunk(text_delta="<|start|>assistant to=user<|message|>A", logprobs=logprobs)+ yield GenerationChunk(text_delta="B", logprobs=logprobs)+ yield GenerationChunk(text_delta="", done=True, finish_reason="stop")++ chunks = asyncio.run(_collect(translate_muse_channels(script())))++ assert [chunk.logprobs for chunk in chunks[:2]] == [None, logprobs]+++def test_closing_the_stream_closes_the_upstream_iterator() -> None:+ closed = asyncio.Event()++ async def upstream() -> AsyncIterator[GenerationChunk]:+ try:+ yield GenerationChunk(text_delta="<|start|>assistant to=user<|message|>A")+ yield GenerationChunk(text_delta="B")+ finally:+ closed.set()++ async def run() -> None:+ stream = translate_muse_channels(upstream())+ await stream.__anext__()+ await stream.aclose()++ asyncio.run(run())++ assert closed.is_set()++[email protected]("size", [1, 5, 10_000])+def test_worker_pipeline_returns_an_openai_tool_call(size: int) -> None:+ stream = parse_tool_call_stream(+ suppress_thinking_blocks(translate_muse_channels(_chunks(*_split(TOOL_CALL, size)))),+ tool_call_format="muse_atem",+ tools=[WEATHER],+ )++ chunks = asyncio.run(_collect(stream))++ deltas = [chunk.tool_call_delta for chunk in chunks if chunk.tool_call_delta is not None]+ assert deltas[0].function_name == "get_weather"+ assert json.loads(deltas[1].arguments_delta) == {"city": "Paris", "unit": "c"}+ assert _text(chunks) == ""+ assert chunks[-1].finish_reason == "tool_calls"+++ ("value", "expected"),+ [("null", "null"), ("true", "true"), ("12", "12"), ("Paris\nFrance", "Paris\nFrance"), ("a < b", "a < b")],+)+def test_worker_pipeline_keeps_string_arguments_as_written(value: str, expected: str) -> None:+ text = FORCED_TOOL_CALL.replace(">Paris<", f">{value}<")+ stream = parse_tool_call_stream(+ translate_muse_channels(_chunks(text)), tool_call_format="muse_atem", tools=[WEATHER]+ )++ chunks = asyncio.run(_collect(stream))++ deltas = [chunk.tool_call_delta for chunk in chunks if chunk.tool_call_delta is not None]+ assert json.loads(deltas[1].arguments_delta) == {"city": expected}+++def test_worker_pipeline_converts_arguments_by_their_declared_type() -> None:+ text = FORCED_TOOL_CALL.replace('name="city">Paris', 'name="days">3')+ stream = parse_tool_call_stream(+ translate_muse_channels(_chunks(text)), tool_call_format="muse_atem", tools=[WEATHER]+ )++ chunks = asyncio.run(_collect(stream))++ deltas = [chunk.tool_call_delta for chunk in chunks if chunk.tool_call_delta is not None]+ assert json.loads(deltas[1].arguments_delta) == {"days": 3}+++def test_reasoning_that_uses_the_whole_budget_is_an_explicit_error() -> None:+ stream = suppress_thinking_blocks(+ translate_muse_channels(_chunks(" to=self<|message|>Still", finish_reason="length"))+ )++ chunks = asyncio.run(_collect(stream))++ assert _text(chunks) == ""+ assert chunks[-1].error_code == "empty_model_output"+++def test_adapter_translates_what_the_base_adapter_streams() -> None:+ adapter = SGLangMuseAdapter.__new__(SGLangMuseAdapter)++ with patch(+ "sie_server.adapters.sglang.cuda13.SGLangCuda13Adapter.generate",+ MagicMock(return_value=_chunks(*_split(ANSWER, 6))),+ ) as base:+ chunks = asyncio.run(_collect(adapter.generate("prompt", max_new_tokens=8, stream=True)))++ assert base.call_args.args == ("prompt",)+ assert base.call_args.kwargs == {"max_new_tokens": 8, "stream": True}+ assert _text(chunks) == "<think>The user asks 17 times 3. That is 51.</think>17 times 3 is 51."diff --git a/packages/sie_server/tests/config/test_muse_glimmer_profiles.py b/packages/sie_server/tests/config/test_muse_glimmer_profiles.pynew file mode 100644index 000000000..f39c09395--- /dev/null+++ b/packages/sie_server/tests/config/test_muse_glimmer_profiles.py@@ -0,0 +1,242 @@+from __future__ import annotations++import asyncio+import re+from pathlib import Path+from typing import Self+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+import yaml+from fastapi import HTTPException+from sie_server.adapters._generation_base import resolve_reasoning_format, thinking_blocks_must_be_hidden+from sie_server.adapters.sglang.cuda13 import SGLangMuseAdapter+from sie_server.adapters.sglang.muse_channels import translate_muse_text+from sie_server.api.openai_local import _prepare_sglang_body+from sie_server.config.model import ModelConfig+from sie_server.core.loader import _build_adapter_kwargs+from sie_server.processors.remote_chat_prompt import _tool_format+from sie_server.processors.streaming import StreamingProcessor+from sie_server.processors.tool_call_grammar import build_tool_choice_grammar+from sie_server.processors.tool_call_parser import _parse_xml_tool_call, tool_parameter_schemas++MODEL_FILE = Path(__file__).resolve().parents[2] / "models" / "meta-models__Muse-Glimmer-30B.yaml"+PROMPT = "<|start|>user<|message|>Hi<|eot|><|start|>assistant"+TOOLS = (+ {"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object"}}},+ {"type": "function", "function": {"name": "get_time", "parameters": {"type": "object"}}},+)+++class _OneEventStream:+ def __init__(self) -> None:+ self.status_code = 200++ async def __aenter__(self) -> Self:+ return self++ async def __aexit__(self, *exc: object) -> None:+ return None++ async def aiter_lines(self):+ yield (+ 'data: {"text": " to=self<|message|>x<|eom|><|start|>assistant to=user<|message|>Hi", '+ '"meta_info": {"prompt_tokens": 1, "completion_tokens": 1, "finish_reason": {"type": "stop"}}}'+ )++ def raise_for_status(self) -> None:+ return None+++def _channel(name: str, *others: str) -> str:+ invokes = "".join(f'<atem:invoke name="{called}"></atem:invoke>' for called in (name, *others))+ return f" to={name}<|message|><atem:function_calls>{invokes}</atem:function_calls>"+++def _config() -> ModelConfig:+ return ModelConfig.model_validate(yaml.safe_load(MODEL_FILE.read_text()))+++def _adapter(config: ModelConfig) -> SGLangMuseAdapter:+ assert config.resolve_profile("default").adapter_path == "sie_server.adapters.sglang.cuda13:SGLangMuseAdapter"+ return SGLangMuseAdapter(**_build_adapter_kwargs(config, "bfloat16"))+++def test_muse_glimmer_claims_tools_grammar_and_private_reasoning() -> None:+ config = _config()+ assert config.tasks.generate is not None+ capabilities = config.tasks.generate.capabilities++ assert capabilities.tools is True+ assert capabilities.grammar == ["json_schema", "regex"]+ assert thinking_blocks_must_be_hidden(config) is True+++def test_muse_glimmer_resolves_to_its_formats_on_the_worker_routes() -> None:+ config = _config()+ registry = MagicMock()+ registry.get_config.return_value = config+ processor = StreamingProcessor(nc=AsyncMock(), registry=registry, worker_id="w1")++ assert processor._resolve_tool_call_format(config.sie_id) == "muse_atem"+ assert _tool_format(config) == "muse_atem"+ # The adapter rewrites the reasoning channel into <think> blocks.+ assert resolve_reasoning_format(config) == "qwen3"+++@patch("sie_server.adapters.sglang._server.subprocess.Popen")+@patch("sie_server.adapters.sglang._server.requests.get")+@patch("sie_server.adapters.sglang._server.find_free_port")+def test_muse_glimmer_launches_the_engine_with_its_parsers_and_no_remote_code(+ mock_find_port: MagicMock, mock_requests_get: MagicMock, mock_popen: MagicMock+) -> None:+ mock_find_port.return_value = 30005+ mock_popen.return_value = MagicMock(poll=MagicMock(return_value=None))+ mock_requests_get.return_value = MagicMock(status_code=200)++ _adapter(_config()).load("cuda:0")++ cmd = mock_popen.call_args[0][0]+ assert cmd[cmd.index("--tool-call-parser") + 1] == "muse"+ assert cmd[cmd.index("--reasoning-parser") + 1] == "muse"+ assert cmd[cmd.index("--grammar-backend") + 1] == "xgrammar"+ assert "--trust-remote-code" not in cmd+ assert cmd[cmd.index("--context-length") + 1] == "8192"+ assert cmd[cmd.index("--speculative-algorithm") + 1] == "DFLASH"+ assert cmd[cmd.index("--speculative-draft-model-path") + 1] == "meta-models/Muse-Glimmer-30B-assistant"+ assert len(cmd[cmd.index("--speculative-draft-model-revision") + 1]) == 40+ assert mock_popen.call_args.kwargs["env"]["SGLANG_ENABLE_SPEC_V2"] == "1"+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_muse_glimmer_keeps_channel_markers_at_the_engine_and_hides_them_from_callers(+ mock_async_client: MagicMock,+) -> None:+ client = MagicMock()+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=None)+ client.stream = MagicMock(return_value=_OneEventStream())+ client.is_closed = False+ mock_async_client.return_value = client+ adapter = _adapter(_config())+ adapter._server_url = "http://localhost:30005"++ async def _drain() -> str:+ return "".join([chunk.text_delta async for chunk in adapter.generate(prompt=PROMPT, max_new_tokens=8)])++ text = asyncio.run(_drain())++ body = client.stream.call_args.kwargs["json"]+ assert body["sampling_params"]["skip_special_tokens"] is False+ assert "require_reasoning" not in body+ assert text == "<think>x</think>Hi"+++def test_forced_tool_choice_regex_accepts_only_declared_tools() -> None:+ spec = build_tool_choice_grammar(TOOLS, "required", "muse_atem")+ assert spec is not None+ assert spec.kind == "regex"+ pattern = re.compile(spec.value)+ weather = (+ ' to=get_weather<|message|><atem:function_calls>\n<atem:invoke name="get_weather">\n'+ '<atem:parameter name="city">a < b</atem:parameter>\n</atem:invoke>\n</atem:function_calls>'+ )++ assert pattern.fullmatch(weather)+ assert pattern.fullmatch(_channel("get_time"))+ assert pattern.fullmatch(_channel("get_time", "get_weather"))+ assert not pattern.fullmatch(weather.replace("get_weather", "delete_everything"))+ assert not pattern.fullmatch("I cannot help with that.")+ assert not pattern.fullmatch(' to=get_time<|message|><atem:function_calls><atem:invoke name="get_time">')+++def test_forced_tool_choice_regex_has_no_optional_whitespace_around_the_channel() -> None:+ # Greedy decoding filled optional leading whitespace up to the token limit.+ spec = build_tool_choice_grammar(TOOLS, "required", "muse_atem")+ assert spec is not None+ pattern = re.compile(spec.value)++ assert not pattern.fullmatch(" " + _channel("get_time"))+ assert not pattern.fullmatch(_channel("get_time") + " ")+++def test_named_tool_choice_regex_pins_the_function() -> None:+ spec = build_tool_choice_grammar(TOOLS, {"type": "function", "function": {"name": "get_time"}}, "muse_atem")+ assert spec is not None+ pattern = re.compile(spec.value)++ assert pattern.fullmatch(_channel("get_time"))+ assert not pattern.fullmatch(_channel("get_weather"))+++def test_channels_the_regex_accepts_parse_after_translation() -> None:+ spec = build_tool_choice_grammar(TOOLS, "required", "muse_atem")+ assert spec is not None+ pattern = re.compile(spec.value)+ schemas = tool_parameter_schemas(TOOLS)+ with_argument = (+ " to=get_weather<|message|><atem:function_calls>\n"+ '<atem:invoke name="get_weather">\n'+ '<atem:parameter name="city">Paris</atem:parameter>\n'+ '<atem:parameter name="first name">Ada</atem:parameter>\n'+ "</atem:invoke>\n"+ "</atem:function_calls>"+ )+ expected_calls = {+ with_argument: [("get_weather", {"city": "Paris", "first name": "Ada"})],+ _channel("get_time"): [("get_time", {})],+ _channel("get_time", "get_weather"): [("get_time", {}), ("get_weather", {})],+ }++ for channel, calls in expected_calls.items():+ assert pattern.fullmatch(channel)+ bodies = re.findall(r"<tool_call>\n(.*?)\n</tool_call>", translate_muse_text(channel), re.DOTALL)+ assert [_parse_xml_tool_call(body, schemas) for body in bodies] == calls+++def test_direct_route_refuses_a_tool_choice_the_engine_cannot_force() -> None:+ config = _config()+ adapter = _adapter(config)+ body = {"messages": [{"role": "user", "content": "Hi"}], "tools": list(TOOLS)}++ for choice in ("required", {"type": "function", "function": {"name": "get_time"}}):+ with pytest.raises(HTTPException) as refused:+ _prepare_sglang_body(+ {**body, "tool_choice": choice},+ config=config,+ adapter=adapter,+ max_completion_tokens=None,+ max_tokens=8,+ seed=None,+ )+ assert refused.value.status_code == 400+ assert refused.value.detail["param"] == "tool_choice"++ for choice in (None, "auto", "none"):+ prepared = _prepare_sglang_body(+ {**body, "tool_choice": choice},+ config=config,+ adapter=adapter,+ max_completion_tokens=None,+ max_tokens=8,+ seed=None,+ )+ assert prepared["model"] == config.sie_id+++def test_native_window_profile_keeps_the_default_launch_shape() -> None:+ config = _config()+ default = config.resolve_profile("default")+ native = config.resolve_profile("h100-128k")++ assert native.adapter_path == default.adapter_path+ assert native.kv_budget_tokens == 131072+ assert native.loadtime["max_seq_length"] == 131072+ # At 0.85 the draft leaves room for only 92,938 tokens of KV cache.+ assert native.loadtime["mem_fraction_static"] == 0.9+ assert native.loadtime["speculative"] == default.loadtime["speculative"]+ assert native.loadtime["tool_call_parser"] == "muse"+ assert native.loadtime["reasoning_parser"] == "muse"+ assert native.runtime["stop_tokens"] == ["<|eot|>"]+ assert native.runtime["default_sampling"] == default.runtime["default_sampling"]+ assert default.kv_budget_tokens == 8192diff --git a/packages/sie_server/tests/processors/test_tool_call_parser.py b/packages/sie_server/tests/processors/test_tool_call_parser.pyindex 9ef849b72..5d299db7e 100644--- a/packages/sie_server/tests/processors/test_tool_call_parser.py+++ b/packages/sie_server/tests/processors/test_tool_call_parser.py@@ -549,6 +549,42 @@ def test_xml_param_scan_garbled_openers_no_close_is_fast() -> None:assert elapsed < 2.0+ "garbage",+ [+ "<parameter=" * (256 * 1024 // len("<parameter=")),+ "<parameter=a b " * (256 * 1024 // len("<parameter=a b ")),+ "<parameter=" + " " * (256 * 1024),+ ],+ ids=["openers-only", "openers-with-spaces", "one-opener-then-spaces"],+)+def test_xml_param_scan_openers_that_never_end_are_fast(garbage: str) -> None:+ """An opener with no ``>`` must not rescan the buffer for every opener."""+ import time++ from sie_server.processors.tool_call_parser import _parse_xml_tool_call++ t0 = time.monotonic()+ parsed = _parse_xml_tool_call("<function=f>" + garbage)+ elapsed = time.monotonic() - t0+ assert parsed == ("f", {})+ assert elapsed < 2.0+++def test_xml_param_name_may_contain_spaces() -> None:+ """JSON Schema allows such a name, and failing to read it loses the argument silently."""+ from sie_server.processors.tool_call_parser import _parse_xml_tool_call++ raw = "<function=f><parameter=first name>\nAda\n</parameter><parameter=city >\nParis\n</parameter></function>"+ assert _parse_xml_tool_call(raw) == ("f", {"first name": "Ada", "city": "Paris"})+++def test_xml_param_opener_needs_a_visible_name() -> None:+ from sie_server.processors.tool_call_parser import _parse_xml_tool_call++ assert _parse_xml_tool_call("<function=f><parameter= >\nv\n</parameter></function>") == ("f", {})++# ── GLM argument tags ──────────────────────────────────────────────────