vendor/ -- what is lifted, from where, and what we changed
==========================================================

The rule (spec.md §12): lifts live here, tracked to a named upstream commit, with local changes
kept as a patch series rather than edited in place. Anything that could not be expressed as a
patch was REWRITTEN into core/ under our own name instead, so this directory stays updatable.
The bottom half of this file is the list of things that went the other way, and why -- that list
is as much a part of the record as the lifts are.

One exception, taken deliberately: the chat lift (common/chat*, the auto-parser, jinja/ and
json-schema-to-grammar) is maintained directly in place. Its former patch series (0002-0021)
was verified applied -- the whole stack reverses cleanly on a copy of the tree it was removed
from, and on the directly edited tree only context lines of 0012 and 0015 have moved -- and the
patch files were then removed: the code itself is the change, the PATCH SERIES notes at the
bottom keep the rationale for each former patch by its old name, and the diffs are in git
history at 008eed4f, the last commit that has vendor/patches/0002-0021. Later changes -- the
render-path work that cut a chat request from three template renders to two and made the
Jinja string machinery move instead of copy -- are likewise direct edits. A refresh of those files is therefore a manual port, not a re-copy and re-apply.

The mechanical half of the promise is vendor/SHA256SUMS: every file under this directory -- lifts,
patch series, this record -- hashed, recomputed by tests/vendor_sums.sh (ctest: vendor_sums). A
file that differs, or arrived unrecorded, fails the suite: an unrecorded change to a lifted
dependency has to survive being a committed, hashed manifest update to ship, not slip through a
rebase. Regenerate the manifest in the same commit that changes vendor/:

    find vendor -type f ! -name SHA256SUMS | sort | xargs sha256sum > vendor/SHA256SUMS

UPSTREAM
--------

  llama.cpp   https://github.com/ggml-org/llama.cpp
              commit 06938ac129e5feee1e731323e5c37dc973de5573
              ("tests : add support for qwen3 SSM archs (#24031)")
              MIT.

To refresh the lifts still under the rule: check out the new upstream commit, re-copy the files
listed below to the same paths, re-apply patches/*.patch with `patch -p1` from vendor/llama/,
and update the commit above. Paths under vendor/llama/ mirror the upstream tree exactly so a
patch generated with `git diff` in llama.cpp applies here unchanged. The chat lift is the
exception above: do not re-copy it; port by hand.


LIFTED FILES
------------

vendor/llama/LICENSE                         <- llama.cpp LICENSE

    The MIT License every file lifted from llama.cpp is under, including those under core/ and
    libquant/ that NOTICE names.

vendor/llama/src/unicode.h
vendor/llama/src/unicode.cpp                 <- llama.cpp src/unicode.{h,cpp}
vendor/llama/src/unicode-data.h
vendor/llama/src/unicode-data.cpp            <- llama.cpp src/unicode-data.{h,cpp}

    The unicode category tables and the pre-tokeniser splitters. core/text reads the category
    tables for the pre-tokeniser steps that are not regexes (Whitespace, Punctuation, Digits) and
    for its UTF-8 helpers; it does not split with unicode_regex_split(), which dispatches a
    pattern to a hand-written codepoint state machine where one exists (GPT-2, Llama-3, Qwen2,
    Qwen3.5, Kimi-K2, the AFMoE digit rule, "[^\n]+|[\n]+") and to std::regex over a
    category-collapsed copy of the text otherwise. Split patterns are compiled by
    core/text/tokenizer_regex.cpp instead. The splitters remain as the reference encoder
    tools/tokref runs, which tests/tokenizer_test and rad-tokcheck compare the tokeniser against.

    LOCAL CHANGES: patches/0001-unicode-reject-codepoints-above-U-10FFFF.patch

vendor/llama/common/unicode.h
vendor/llama/common/unicode.cpp              <- llama.cpp common/unicode.{h,cpp}

    A different file with the same basename: streaming UTF-8 parsing helpers, used only by the
    jinja engine. Both are carried at their upstream paths, and vendor/CMakeLists.txt keeps
    llama/common off the public include path so `#include "unicode.h"` can only ever mean one
    of them.

    LOCAL CHANGES: none.

vendor/llama/common/jinja/                   <- llama.cpp common/jinja/
    caps.{h,cpp} lexer.{h,cpp} parser.{h,cpp} runtime.{h,cpp} string.{h,cpp} value.{h,cpp}
    utils.h README.md

    The Jinja engine and the template capability probe (spec §12: 5.0k + 0.5k lines). It depends
    on the tree's JSON DOM (core/util/json.h; nlohmann/json when lifted) and common/unicode.h
    and on nothing else in llama.cpp -- no ggml, no llama.h, no common.h -- which is why it
    lifts cleanly and chat.cpp did not.

    LOCAL CHANGES: maintained directly (see the chat exception at the top of this file). The
                   former patches 0006 (min/max over a sequence), 0015 (print a list or dict
                   as its repr) and 0021 (a dotted integer is an index), `unique` over a sequence
                   with jinja2's semantics (upstream's is a stub that throws, which the capability
                   probe reports as a template without tool support: GLM-5.3-Flash's), the probe's
                   first exception under tools kept (caps::probe_error,
                   common_chat_templates_get_probe_error), then the string/render
                   hot paths: parts are moved instead of copied through the gather, appends no
                   longer return a copy, the parts join is one compaction pass, the flat render
                   is gathered without a parts list, and loop/member lookups stop rehashing.
                   Added 2026-11: budgets. A container's chat template is server-side attacker
                   data and the engine ran it without any: parse_any and parse_expression
                   recursed once per nesting block/paren with no bound -- tens of KB of `{{ (((`
                   or `{% if %}{% if %}` stack-overflowed whoever parsed, the capability probe
                   or the first render, past every catch -- so both now share one 128-level cap
                   whose throw is the same exception class a malformed template already raises.
                   An elif chain counts against the same cap: parse_if_statement calls itself
                   once per elif without passing through parse_any.
                   And range() emitted one array element per step uncapped -- `range(4000000000)`
                   OOMed per render -- so it refuses above 65536 values, far past any template
                   that exists. String repetition is that cap's sibling -- `'x' * 4000000000`
                   appended one step at a time, uncapped, and chained repetitions multiply past
                   any bound -- so a repetition whose result passes 64 MiB throws the same
                   exception, at any step of the chain.

vendor/llama/common/chat.{h,cpp}
vendor/llama/common/chat-auto-parser.h
vendor/llama/common/chat-auto-parser-generator.cpp
vendor/llama/common/chat-auto-parser-helpers.{h,cpp}
vendor/llama/common/chat-diff-analyzer.cpp
vendor/llama/common/chat-peg-parser.{h,cpp}
vendor/llama/common/peg-parser.{h,cpp}
vendor/llama/common/json-partial.{h,cpp}
vendor/llama/common/json-schema-to-grammar.{h,cpp}
vendor/llama/common/regex-partial.{h,cpp}    <- llama.cpp common/*

    Rendering a message list through a chat template, the differential analysis that finds a
    template's reply delimiters, and the JSON-schema-to-GBNF converter the grammar path needs.
    The note above says chat.cpp "does not" lift cleanly and that was true of the old chat.cpp,
    which reached for llama.h and common.h; the auto-parser generation that replaced it does not,
    so it is carried here rather than rewritten. The engine does NOT read replies with the PEG
    parser the auto-parser generates: core/text/chatparse.cpp reads them in one streaming pass
    from a format description, and core/text/chatfmt.cpp takes that description from the
    analyser's derived markers (or from the architecture plugin). The PEG path survives only as
    the oracle in tests/legacy/. core/text/chat.cpp, chatfmt.cpp and chatparse.cpp are the only
    files in core/ that include any of these, which keeps a vendor refresh from rippling into the
    server.

    LOCAL CHANGES: maintained directly (see the chat exception at the top of this file). The
                   former patches 0002-0005 and 0007-0020 (listed with their rationale under
                   PATCH SERIES below), then in place: the generation-prompt render reuse and
                   the dropped message_spans computation. The
                   whole lift's JSON type is now the tree's own DOM (core/util/json.h,
                   rad::Json) where upstream spells nlohmann::ordered_json (and
                   nlohmann::json in peg-parser's to_json/save, whose text now keeps
                   insertion order instead of sorting keys), and
                   json-partial.cpp's error locator is a small structural scanner where
                   upstream drives nlohmann's SAX interface; a refresh re-applies both by
                   renaming the type and keeping the scanner.

    On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three
    of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs
    on an empty vector for a leading quantifier; and a stray ']' or '}' -- in NON_LITERAL_SET, but
    claimed by no arm of the scanner -- makes the literal arm break without consuming it, so the
    loop reconsiders the same byte forever. core/text/chat.cpp:148 catches what the converter
    throws, so its std::stoi range errors already come back as a clean refusal; a hang and a
    read off the end of a container are the two things a catch cannot turn into a 400. The patch
    adds a size test, two empty-container guards, and a did-we-consume-a-byte test at the bottom
    of the loop, each recording an error the existing check_errors() already turns into a throw.

    Added 2026-11 on 0003's footing: the same client `pattern` can also KILL the worker by
    recursion -- transform() calls itself once per nested '(', no cap anywhere, and no JSON
    depth bound helps because the brackets are string content, not JSON nesting. A pattern of
    tens of KB of '(' is an uncatchable stack overflow. A nesting counter caps the recursion
    at 64 groups and records one more error the existing check_errors() turns into a refusal.

    On 0004: three things upstream ACCEPTS and then gets wrong, each now refused by name.
    A remote $ref is fetched through a callback the public entry point stubs out, so it silently
    degrades into "accepts any object" -- we refuse and fetch nothing, because a sampler that
    reaches the network to decide what tokens are legal is not one we ship. `"not"` has no case in
    visit(), so it falls through to a rule accepting any value -- a constraint the caller asked
    for, did not get, and is not told about. And a regex escape GBNF cannot spell (\d \w \s \b
    \/ \-, a backreference) is copied into the output verbatim, so the converter returns success
    and the grammar then fails to LOAD.

    0003 and 0004 together are what core/sample/json_schema.cpp used to carry on its own. That was
    a SECOND, independently hardened lift of this same file -- and, checked against a running
    server, one that NO REQUEST COULD REACH: response_format on /v1/chat/completions is compiled
    by THIS copy through the chat template, and on /v1/completions it is refused by the endpoint
    accept-list before the fork's seam is called. So the hardened copy never ran and the copy that
    serves every structured-output request was the unhardened one. The fork is deleted and its
    refusals are here, which is where they were needed all along.

vendor/cpp-httplib/httplib.h
vendor/cpp-httplib/httplib.cpp
vendor/cpp-httplib/LICENSE                   <- llama.cpp vendor/cpp-httplib/cpp-httplib/*

    The HTTP library at cpp-httplib v0.66.0, carried as the .h/.cpp SPLIT pair llama.cpp
    distributes (v0.64.0 split upstream's single ~24,300-line header into a pair so that one
    translation unit pays for it). Apart from the split mechanics the split itself introduced
    (two decorative `// ----` separator lines dropped, `inline` moved from definitions to
    declarations, the .cpp's `#include "httplib.h"` and namespace brace added) and patch 0022
    below, the pair is llama.cpp's bytes at the recorded commit, byte for byte. The PATH is
    ours: llama.cpp nests the pair one directory deeper; flattening lets
    `<cpp-httplib/httplib.h>` resolve with vendor/ alone on the path, which is the one include
    directory core/CMakeLists.txt already adds.

    cpp-httplib's own CMakeLists.txt is NOT carried. vendor/CMakeLists.txt builds httplib.cpp
    itself, because upstream's version reaches for llama.cpp's license and compile-flag helpers
    and pulls in an SSL provider fetch we do not want. It was kept "for reference" for a while and
    that was the wrong call: it set four CPPHTTPLIB_* definitions of its own beside the four
    vendor/CMakeLists.txt sets, so a future disagreement between them would have been invisible --
    the copy nobody builds is the copy nobody checks.

    Upstream tracked: cpp-httplib tag v0.66.0 (yhirose/cpp-httplib); the split pair as carried by
    llama.cpp commit b8abe41a5 ("vendor: update cpp-httplib to 0.66.0 (#32049)"). Earlier this pair
    sat at v0.46.1 -- what llama.cpp carried at the lifted commit -- and carried patches/0022, and
    at v0.64.0; the v0.64.0 bump retired most of that patch, because 0.64.0 natively closes the
    connection on every 4xx/5xx response (the "Connection: close" option is honored by a scope_exit
    in write_response), skips the keep-alive drain for any response that committed to close, bounds
    the drain that does run (CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH, the connection timeout as a
    total max_timeout, and a close for a part-read body), and routes exceptions from the pre-routing
    handler and the WebSocket upgrade through the exception handler. What survived is the budget the
    library still ties to the connection's own timeout and cannot lower without capping uploads
    too: see below. The v0.66.0 bump is for its ThreadPool, which
    wraps the dynamic worker's creation in try/catch (std::system_error) and keeps the job queued
    when the thread budget runs out, where 0.64.0 let the exception escape the accept loop into
    std::terminate -- thread exhaustion was a process abort. radiance's socket gate and drain
    budget narrowed that window; they never closed it.

    LOCAL CHANGES: patches/0022-httplib-the-drain-keeps-a-five-second-budget.patch

    On 0022: a response whose body the handler left unread drains on the keep-alive socket, and
    upstream bounds that drain only by the connection's read timeout -- the same knob that bounds a
    whole request's reads, uploads included, so radiance cannot simply lower it. A client dribbling
    one byte per gap paces a worker for that full timeout after the response was already sent.
    0022 caps the drain's total budget at 5 s (or the connection timeout, whichever is smaller).
    Re-verified against 0.66.0: the hunk lands at the same site with a +26-line offset and no
    fuzz, and upstream changed nothing around it -- the drain is still bound only by the
    connection's timeout, so the patch stands. The six CPPHTTPLIB_* defines vendor/CMakeLists.txt
    passes were each re-checked as live knobs in the 0.66.0 pair.

vendor/yyjson/yyjson.h
vendor/yyjson/yyjson.c
vendor/yyjson/LICENSE                        <- ibireme/yyjson src/* and LICENSE at tag 0.13.0
                                                (commit 138b4a7e757426bbbaa11ca37f257ce8d8489007)

    The reader inside the tree's JSON DOM. Parsing a large agent-turn body with the DOM
    library this replaced cost ~340 MB/s -- the largest single host item on the serving path
    once rendering was optimised -- and almost all of it was the lexer, not the tree. The
    DOM now lives in core/util/json.{h,cpp} (rad::Json, ours): yyjson reads under a
    byte-budgeted allocator and a converter rebuilds the value tree, enforcing the value
    budget and depth cap the request path's bounded parse promises. That displaced the old
    DOM everywhere -- server, chat templates, the vendored lift above, config and
    checkpoint files, tests -- and vendor/nlohmann is gone with it. The behavioural
    contract carried over (typing, refusals, boundaries, dump bytes bar a float's digits
    where the old ones were not the shortest that read back) is recorded in
    tests/json_test.cpp. MIT.

    Upstream tracked: yyjson tag 0.13.0. To refresh: re-copy src/yyjson.{h,c} and LICENSE from
    the new tag, keep the include spelled <yyjson/yyjson.h>, and re-run the parse contract
    cases (tests/json_test.cpp, tests/wire_test.cpp) -- the converter and the budget
    arithmetic in core/util/json.cpp assume yyjson's reader allocates an input copy plus
    one value buffer and nothing else, which a refresh must re-confirm.

    LOCAL CHANGES: none.


vendor/rapidyaml/ryml.hpp                    <- rapidyaml v0.16.0 release asset
                                                rapidyaml.v0.16.0.singlehdr.hpp (biojppm/rapidyaml),
                                                renamed; byte-identical
vendor/rapidyaml/LICENSE.txt                 <- rapidyaml LICENSE.txt at tag v0.16.0
vendor/shim/ryml_impl.cpp                    ours: defines RYML_SINGLE_HDR_DEFINE_NOW and includes
                                                the header, the one TU holding the implementation

    The YAML configuration reader (core/fleet/config.cpp) is the only user. The amalgamated header
    carries c4core and fast_float inside it, so nothing else is fetched. MIT.

    LOCAL CHANGES: none.


vendor/shim/common.h                       ours -- NOT a lift -- but MIT-derived all the same:
vendor/shim/ggml.h                             common.h transcribes, unchanged, the string helpers
vendor/shim/llama.h                             the lifted chat and PEG-parser sources need from
vendor/shim/log.h                              llama.cpp's common/common.{h,cpp} (06938ac12); the
vendor/shim/llama_shim.cpp                     other four declare the small macros, types and log
                                               surface those lifts reach for outside themselves.
                                               Each file's own header says why the shim exists: the
                                               lifts compile byte-for-byte without the CLI
                                               argument machinery, the engine being replaced, or
                                               upstream's logging subsystem. Recorded beside the
                                               lifts because upstream's code or upstream's shape
                                               lives in them -- this file is where lifted
                                               provenance lives, and the manifest under which
                                               vendor_sums hashes them is the tamper check.

    LOCAL CHANGES: n/a -- maintained in place. A vendor refresh re-derives what the lifts expect
                   of these headers (their comments enumerate the needs); nothing is re-copied.


REWRITTEN INTO core/ INSTEAD
----------------------------

spec §12 marks these as rewritten. Each one would have needed heavy modification, so it lives in
core/ under our own name, with a comment at the top naming what it was read from.

  src/llama-grammar.{h,cpp} -> core/sample/gbnf.{h,cpp}
      MIT, same upstream commit. The GBNF parser and the stack machine, element for element; it
      is under core/sample/ rather than here because it is on the SAMPLING path and the sampler
      owns it, where vendor/ belongs to the text frontend. gbnf.h's own header lists what changed
      (llama_vocab became VocabView, GGML_ASSERT became status returns, and the parser gained the
      partial-UTF-8 and lazy-trigger handling the server needs) so a re-lift knows what to
      re-apply. Recorded here because it was not, and an MIT lift belongs in this list whichever
      directory it sits in.

  ggml/src/gguf.cpp        -> core/text/gguf.{h,cpp}
      Upstream is a reader, a writer and a ggml_context builder welded together: it fills
      `struct ggml_tensor`, calls ggml_blck_size(), and includes ggml.h for both. Taking it whole
      means taking ggml, which §12 says we do not. The wire format is a header, a KV table, a
      tensor directory and a padded blob, so the reader is a page of code. The one thing kept
      verbatim is the block geometry of every ggml dtype, which is data rather than code and is
      marked as such at the table.

  src/llama-vocab.cpp      -> core/text/tokenizer.{h,cpp}
      Welded to llama_model_loader, GGML_ASSERT and the llama_vocab class, and organised around a
      pre-tokeniser identified by HASHING tokenizer.json against a hardcoded enum -- which is the
      behaviour spec §12 exists to replace. The BPE bigram queue and the UGM Viterbi are
      re-expressed with attribution; the enum is gone, and a declared RadVocabStep chain drives
      the tokeniser instead.

  convert_hf_to_gguf.py    -> core/text/tokenizer_json.cpp
      Python, so not liftable at all. parse_tokenizer_json() interprets the declared
      normalizer / pre_tokenizer / decoder chain and refuses, by name, any component it cannot
      express -- rather than approximating it.

  (no upstream)            -> core/text/unicode_norm.{h,cpp}, unicode_norm_data.cpp
      llama.cpp has no NFC/NFD/NFKC/NFKD. Its `unicode_ranges_nfd` is a strip-accents table for
      the WordPiece path, not a canonical decomposition. The tables here were generated once from
      a system ICU; unicode_norm_data.cpp documents the recipe. radiance links no ICU.


PATCH SERIES
------------

Only 0001 and 0022 still live in patches/. The entries for 0002-0021 keep the rationale for
changes that are now maintained directly in the chat lift (see the top of this file); their
headings name the removed patch files, whose diffs are in git history.

  patches/0001-unicode-reject-codepoints-above-U-10FFFF.patch

      unicode_cpt_from_utf8() accepts a 4-byte sequence with a 0xF5..0xF7 lead and returns a
      codepoint above U+10FFFF. unicode_cpt_to_utf8() then throws std::invalid_argument, and
      nothing on the tokenise path catches it -- so four arbitrary bytes in a prompt terminate
      the process. Measured: 93 of 15,000 random byte strings do it.

      The patch rejects the out-of-range result at the decode site, where the existing
      unicode_cpts_from_utf8() handler already turns an invalid_argument into U+FFFD. Every
      sequence upstream accepts still decodes to the same codepoint, so nothing that worked
      changes; only the crash does. Verified by re-running the 15,000-string comparison against
      llama.cpp: identical output on all 14,907 strings it survives.

  patches/0002-chat-unclosed-reasoning-must-not-swallow-a-tool-call.patch

      analyze_reasoning::build_parser() ends a reasoning block with `until(</think>)`, and
      `until` returns the REST OF THE INPUT when its delimiter never arrives. So a reply whose
      reasoning block the model never closed was captured whole as reasoning_content -- and when
      that reply contained a <tool_call>, the call went with it: parsed as reasoning text, not as
      a call. The turn then carried no tool call and no content, and an agent driving the server
      stopped dead. Templates shipped for this model family carry explicit self-heals for the
      same shape, which is how we know models emit it.

      The patch adds an ordered choice whose first branch is guarded by a peek: reasoning may
      also end at the tool-call opener, but only when the opener is what actually stopped it.
      Every reply that closes its reasoning block takes the second branch, which is upstream's
      rule unchanged -- including reasoning that merely MENTIONS an opener, since such a reply
      still has its closing tag and the peek never fires. The marker is handed down from
      autoparser::build_parser(), the one scope that can see both the reasoning and the tool
      analyzers. tests/chat_test.cpp pins all three shapes against the real Qwen3.8 template.

  patches/0005-chat-an-xml-argument-value-owns-its-indentation.patch

      common_chat_peg_mapper::map() strips "one leading whitespace character" from every tool
      argument value. For Qwen's XML the grammar has ALREADY consumed the newline after
      <parameter=x> -- the differential analyzer derives it as the value prefix -- so the
      character that gets stripped is the first SPACE of the value. An agent's edit tool matches
      old_string against the file byte for byte, so `    return a + b` arrives as
      `   return a + b` and the edit never applies, on a model that wrote a perfectly good call.
      Every indented hunk, every call, silently.

      The patch strips the DELIMITER instead: one leading newline (\n or \r\n) and one trailing
      one, and nothing else. Values with no surrounding newlines are unchanged, which is every
      JSON-format call and every python-style one; only the tagged XML path can differ, and there
      the delimiter is exactly what upstream meant to remove. tests/chat_test.cpp pins an indented
      value and a multi-line one -- blank line, tab, trailing spaces -- against the real template.

  patches/0006-jinja-min-and-max-over-a-sequence.patch

      The engine has `sort` and `reverse` for an array but neither `min` nor `max`, and the
      undefined-value table lists both -- so the omission is in the array table, not in the
      design. A template that uses one throws mid-render, and the CAPABILITY PROBE SWALLOWS THE
      EXCEPTION ("ignore exceptions during capability analysis"), so the template comes back
      reporting tools=0 tool_calls=0: indistinguishable from a model that genuinely cannot call
      tools. MiniCPM5-2B's tool block sets `[tool_calls_count, tool_sep_count]|min`, and the
      symptom was /v1/chat/completions refusing `tools` with a 400 naming the MODEL.

      jinja2 semantics: the smallest (largest) ITEM of the sequence, by `attribute` where one is
      given, undefined for an empty sequence, `case_sensitive` accepted and ignored -- which is
      what the `sort` beside it does with the same argument.

  patches/0007-autoparser-split-the-per-argument-suffix-from-the-call-close.patch

      analyze_arguments() takes everything after an argument's value as `value_suffix` and then
      trims `function.close`, `per_call_end` or `section_end` off it. A template that declares
      none of the three has nothing to cut against and keeps the lot. MiniCPM5-2B writes
      `<function name="F"><param name="A">V</param></function>`, so the suffix came out
      `</param></function><|im_end|>\n` with an EMPTY close, and no tool call could ever parse: a
      second argument because the suffix closes the whole call, and even the FIRST because a
      generated turn ends at `<|im_end|>` and never carries the newline the template writes
      BETWEEN turns. Every call came back to the client as prose.

      The boundary is already rendered, one phase later, by extract_argument_separator(): between
      the first argument's value and the second argument's name marker is exactly the
      per-argument suffix. The patch measures it there and splits the tail -- value_suffix
      `</param>`, close `</function><|im_end|>` -- and declines, leaving upstream's result, if the
      markers do not line up. Only reached when the derived close is empty, so every template
      that already worked is untouched.

      The close is measured off a TWO-CALL render, not off the tail of a one-call one: the tail is
      what a template writes after the LAST call of a turn, so it carries the turn terminator, and
      a close demanding `</function><|im_end|>` can only ever match a reply holding exactly one
      call. Between the end of one call and the opener of the next there is no terminator.
      core/server/adapters.h still strips a trailing terminator from content, for the paths where
      the parser does not consume one.

  patches/0008-autoparser-tagged-calls-separate-on-space-and-named-args-in-any-order.patch

      TWO strictnesses in build_tool_parser_tag_tagged(), both of which turn a good call into
      prose. The rule ends in p.end(), so neither failure is partial: an unmatched call fails the
      whole parse and the optional `tool_calls` then matches NONE of them.

      build_tool_parser_tag_tagged() separates parallel calls with a literal ", " -- the separator
      of a JSON ARRAY of calls -- for a format whose calls are TAGS. MiniCPM5-2B writes
      `<function name="ls">..</function>\n<function name="bash">..</function>`, so the second call
      was required to begin with a comma and a space and never did.

      The failure is not partial. The rule ends in p.end(), so a trailing unmatched call makes the
      whole parse fail, and `tool_calls` being optional then matches ZERO of them: every reply
      with two calls in it came back as raw prose with the reasoning and the tags still in it. One
      call parsed, two never. Found by reading an agent transcript, where the client had parsed
      the first call out of that prose itself and silently dropped the second.

      A tagged call opens with its own name prefix and closes with its own close, so nothing
      between them is needed to tell one from the next: the separator is p.space(), which accepts
      the newline these models write and the nothing a template writing them adjacently produces.

  patches/0009-chat-a-cdata-section-is-punctuation-not-content.patch

      MiniCPM5's template instructs the model, verbatim: "If it contains <, & or newline
      characters, wrap it in a CDATA block: <param name="p"><![CDATA[...]]></param>". The mapper
      does not know that, so a `write` call arrived with `<![CDATA[` and `]]>` inside the argument
      value and every source file an agent wrote would have carried them.

      THE TWO ENDS ARE STRIPPED INDEPENDENTLY, and that is the whole of it. A streamed value is
      re-parsed from the top on every chunk and the server sends only what is new, so a value
      already emitted cannot be taken back. Requiring both delimiters before removing either let
      the opener escape in the first chunk every time -- files came out beginning `<![CDATA[` and
      ending `]]`, the model read back its own corrupted output, and it spent the rest of the
      session trying to edit the markers out. Anything that could still BECOME the opener is held
      back whole while the value is partial, as is a trailing `]` or `]]`, which is either the
      start of the closer or the end of a JSON array; withholding keeps what is emitted a prefix
      of the finished value, which is what the streaming diff requires.

      Same family as 0005: the punctuation of an XML argument value is not part of it.

  On 0008, the second half: REQUIRED ARGUMENTS WERE REQUIRED IN SCHEMA ORDER.

      A tagged argument carries its own name -- `<param name="path">..</param>` -- so its
      position means nothing, and a model emits them in whatever order it composed them. For a
      write that is very often the content first, because that is the part it was thinking about.
      Found in an agent transcript: the file was written, the model reviewed its own code, and
      its follow-up `write` came back as prose ending
      `]]></param><param name="path">/work/tic_tac_toe.py</param></function>`.

      Every argument is accepted in any order now, required and optional alike. What the grammar
      gives up -- checking that each required argument appears exactly once -- was never its job
      here: a call missing one is a bad call, and arriving at the tool AS a bad call says so,
      where arriving as prose says nothing at all. Scoped to the tagged builder; the JSON and
      positional builders keep their ordering.

  On 0008, the third: NOTHING WAS ALLOWED BEFORE THE CALL.

      `content_before_tools` is what lets a model say a sentence and THEN call a tool, and it is
      driven by the section or per-call opener. A format with neither -- this one -- got p.eps(),
      which permits no content at all, so a reply opening "The workspace is empty. I need to
      create a Tic Tac Toe implementation." and then making a well-formed call did not match, and
      p.end() made that a whole-parse failure. What opens a call in a tagged format is the
      function name prefix, so that is the marker to read up to; it is a fallback only, since a
      format that really has a section or per-call opener starts earlier in the text than the
      function name does.

  On 0008, the fourth and fifth: CONTENT AFTER THE CALLS, AND BETWEEN THEM.

      The same trap with the ends swapped. The rule was reasoning + optional(content) + calls +
      p.end(), so a model that signs off after a call, or narrates between two of them ("Next, I
      will check the current directory."), failed the whole parse. Content is now allowed after
      the last call and before each subsequent one, read up to the same trigger marker.

      All five of 0008's halves are one bug wearing different hats: the tool-call rule ends in
      p.end(), so ANY mismatch anywhere fails everything and `tool_calls` being optional then
      matches NONE. There is no partial credit, so every strictness in this grammar -- a comma, a
      terminator, an argument order, a sentence -- presents identically, as a model that cannot
      call tools.

  On 0008, the sixth: A NON-STRING ARGUMENT THAT IS NOT VALID JSON.

      An array or object parameter is matched by a schema-constrained JSON parser, and models do
      not reliably write JSON inside an XML tag. MiniCPM5 writes Python:
      `<param name="edits">[{'oldText': 'a', 'newText': 'b'}]</param>`. The JSON parser cannot
      begin on a single quote, so the argument did not match, so the call did not, so the reply
      came back as prose -- and the model, reading that as a rejection, rewrote the same call
      four times, once reordering its arguments to appease it.

      Strict JSON is still tried FIRST, so nothing that parses today parses differently. The
      fallback takes the value the way a string argument takes it, as the text up to `</param>`,
      which is what actually delimits it in this format -- and the mapper already normalises a
      Python-style container to JSON from there (normalize_container_value, which upstream wrote
      and the grammar never let it reach). What is given up is schema VALIDATION of the argument.
      A mistyped argument reaching the tool as a mistyped argument is strictly better than a
      correct call reaching the user as prose.

0010-autoparser-an-undeclared-argument-must-not-lose-the-call.patch
      chat-auto-parser-generator.cpp. Every argument arm matches its parameter name as a LITERAL,
      so an argument the schema does not declare matches nothing, the call matches nothing, and
      the tool rule's `p.end()` makes that THE WHOLE REPLY -- which reaches the caller as prose
      with the XML in it. Observed on a live MiniCPM5-2B agent: a `read` tool whose only parameter
      is `path`, called as `<param name="action">read</param>`, and the turn was lost. The cost is
      not limited to the malformed argument: a call that is entirely valid is lost when one extra
      argument sits beside it, which is the case the second test covers.

      A generic arm is appended LAST to the ordered choice, matching any name up to the name's own
      delimiter and taking the value the way a string argument takes it. Declared names still bind
      to their own schema-checked arms first, so nothing that parsed before parses differently.
      What is given up is knowing the argument was undeclared -- the TOOL gets to say so, properly,
      and a reply that never arrives cannot.

      THE DELIMITER AFTER THE NAME IS NOT ALWAYS `name_suffix`: this format decomposes
      `<param name="path">v</param>` as prefix `<param name="`, name_suffix EMPTY and value_prefix
      `">`. The first cut guarded on `!name_suffix.empty()` and so never built its own arm, built
      clean and changed nothing. Read the analysis rather than assuming the decomposition.

  patches/0011-chat-add_bos-must-come-from-the-inputs.patch

      `common_chat_templates_inputs` carries add_bos and add_eos, and the jinja conversion
      overwrote both from the TEMPLATES object -- which is only ever filled inside
      common_chat_templates_init, off a llama_vocab. A host that passes `model = nullptr` and
      supplies the vocabulary's facts as overrides had both flags stuck at false whatever it
      asked for, and that is exactly the shape of this lift's use here: the .rad carries the
      template, the BOS/EOS spellings and the add flags, so there is no llama_model to read.

      The flag strips a BOS the TEMPLATE rendered, because the tokeniser is about to add one. Off,
      a container whose tokeniser adds BOS and whose template also writes `bos_token` gets two.
      The Llama-family templates write it and Qwen's do not, which is why nothing here saw it.

      The two upstream callers that do set the field -- common_chat_format_single and
      common_chat_format_example -- assign `inputs.add_bos = tmpls->add_bos` immediately before
      calling apply, which is the redundancy you would expect if apply were meant to read the
      inputs. The fix ORs the two, so those two callers behave exactly as before.

  patches/0012-json-schema-a-schema-no-value-satisfies.patch

      oh-my-pi's `task` tool declares `"model?": "never"` in its batch form, and Arktype exports
      `never` as `{"not": {}}` -- as TypeBox does Type.Never. 0004 refuses `not` outright, so the
      tool-call grammar for every request carrying that tool failed to build and the request with
      it. `not` of the empty schema is not a constraint that has to be complemented: it makes the
      schema unsatisfiable, the same schema as `false`, and that is exactly representable where it
      occurs. An object property of that kind is a key the object never carries -- no rule, and
      its name kept out of an additionalProperties rule -- and a union alternative of that kind is
      dropped. The tagged-argument builders (chat-auto-parser-generator.cpp, and chat.cpp's
      `string="true|false"` format), which give every argument an arm of its own and so never see
      the object, give an optional one of that kind no arm; a model that writes it reaches the
      undeclared-argument arm of 0010 where the format has one. core/text/chatfmt.cpp, the
      declared-format grammar, does the same outside this tree. Where a value is required (a
      required property, the root, an array's items, a union with no alternative left) it is still
      refused, by name. Every other `not` is refused as 0004 refuses it.

  patches/0013-json-schema-a-count-past-int-is-no-bound.patch

      minLength, maxLength, minItems and maxItems were read with get<int>(), which casts: a bound
      past INT_MAX wrapped, and Number.MAX_SAFE_INTEGER -- a common way for a schema generator to
      write "no limit" -- came out as -1 and the grammar failed to parse, failing the request with
      it. A count at or past INT_MAX is now INT_MAX, which build_repetition already reads as no
      maximum. That is exact for anything served here: no context holds a string or an array that
      long. A count that is negative or not a number is refused by name. A float count is
      truncated, where maxItems used to ignore one. The other half of the same report -- any count
      past 2000 refused -- was the GBNF parser's, and is fixed in core/sample/gbnf.cpp.

  patches/0014-json-schema-a-not-of-every-type-is-never.patch

      0012 recognised `never` only as `{"not": {}}`. oh-my-pi 18.6.0 sends its `task` tool's
      optional `model` as the `not` of a union of all six JSON types -- `{"not": {"anyOf":
      [{"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "object"},
      {"type": "array"}, {"type": "null"}]}}` -- so under every template that constrains tool
      arguments the request still failed with "Unsupported schema keyword \"not\"". A `not` is now
      `never` whenever what it negates accepts every value: `{}` or `true`, a type list naming all
      six types, or a union of bare types that between them name all six (an alternative that is
      itself universal settles it). Annotations may sit beside; any other keyword narrows the
      schema, an alternative that constrains more than its type is not counted, and `integer` does
      not stand for `number`, so a `not` is only read as `never` when it is. Every other `not` is
      refused as 0004 refuses it. The comment of 0012 above is_unsatisfiable, which 0013 had left
      above _schema_count, is back beside the function it describes.

  patches/0015-jinja-print-a-list-or-a-dict-as-its-repr.patch

      `{{ value }}` with a list or a dict printed the list's strings run together and nothing at
      all for a dict: statement results are gathered as an array and flattened, and an
      expression's own list was flattened with them. jinja2 prints the repr. MiniCPM5's template
      prints a tool call's arguments with a bare `{{ param_value }}`, so every list or object
      argument in a replayed call reached the model as `<param name="edits"></param>`. Every block
      statement returns a string, so a list or a dict among a block's results is now printed as
      its repr. The repr of a string inside one is Python's: single quotes unless the text holds
      one and no double quote, and backslash escapes for the backslash, the quote and the ASCII
      controls; it was the bare text in single quotes, or JSON when it held a quote. Python also
      escapes non-printable non-ASCII code points, which pass through. tests/chat_test.cpp
      (every_shipped_template_renders_as_reference_jinja_does) compares every shipped template's
      render with Python jinja2's.

  patches/0016-chat-analyse-a-template-once.patch

      common_chat_templates_apply ran autoparser::analyze_template on every request: many
      renders of the template to find its reply delimiters, most of what a Qwen 3.x or MiniCPM5
      render cost. The analysis reads nothing but the template, so it is now made on
      first use and kept beside the template (one for template_default, one for
      template_tool_use), under a mutex because requests render from several threads. An analysis
      that throws is not kept, so the next request throws the same refusal. The parser generated
      from it per request is unchanged: the prompt, grammar, triggers, preserved tokens, stops and
      PEG parser of 32 requests through each shipped template hash the same with and without the
      cache, and a render took 1.4-1.6 ms with it against 10-13 ms without (one loaded machine).

  patches/0017-json-schema-a-pattern-without-anchors-searches.patch

      _visit_pattern() read only ^...$ and refused every other `pattern` with "Pattern must
      start with '^' and end with '$'". JSON Schema patterns are unanchored (ECMA-262 search,
      validation 6.3.3), and tool schemas send them bare: an opencode agent's tool list drew
      twelve of these refusals, so every request it made failed. A bare pattern on array items
      is refused, since a tool call's JSON arguments reach this converter. (A top-level string
      argument is written raw under the XML call formats and never reaches it, which is why a
      bare pattern there passed.) A missing anchor is now written out as any string text on that
      side, (?:[^"\\]|\\.)*, before the old check, which then refuses only what that cannot
      spell: a one-sided anchor beside a top-level '|', where the anchor binds to one branch. The
      filler is not ".*": '.' matches '"' here, and on array items ["1","x"] then read as one
      string "1\",\"x" holding a digit. An empty pattern now matches every string rather than
      being refused (tests/sample_test.cpp updated). A final '$' after an odd run of
      backslashes is a literal and does not count as an anchor. tests/gbnf_test.cpp
      (json_schema_grammars_admit_exactly_their_instances) holds the converter to the search
      reading, on plain strings and on array items, and pins the refusal.

  patches/0018-json-schema-shorthand-classes-are-written-out.patch

      \d \w \s and their negations were refused in a literal ("Unsupported regex escape") and
      copied raw inside a class, where GBNF cannot load them. Tool schemas use them freely:
      oh-my-pi's workpool tool carries "\S" thirteen times, so with 0017 the request got past
      the anchors and was refused here instead. Each shorthand is now written out before the
      scanner reads the pattern, as the class ECMA-262 gives it: \d [0-9], \w [A-Za-z0-9_], \s the
      ECMA-262 space characters. A JSON string holds text, so the negated forms leave out '"',
      '\' and the control characters and admit any JSON escape instead -- a match cannot run past
      the closing quote -- and \s also admits the escapes \t \n \f \r. In a class a positive
      shorthand becomes its ranges ([\w-], [\da-f]) and [\s\S] and its kin become any text; a
      negated shorthand mixed into a class has no GBNF spelling and is refused with a message
      that says so. The escapes are judged on the encoded text, so \D admits an escape such as
      \u0031 that decodes to a digit. sample_test's "cannot spell" case moves from \d to \b,
      which is still refused; gbnf_test covers \S on strings and array items, \d dates and
      decimals, [\w-], \s with an escaped tab, [\s\S] and \D, and the refused [a\S].

  patches/0019-json-schema-identity-escapes-of-punctuation.patch

      Patterns written in JavaScript escape punctuation that needs no escape: "\/" in a path,
      "\-" in a class (zod's email pattern carries both "[A-Za-z0-9_'+\-]" and "[A-Za-z0-9\-]").
      Outside a class these were refused ("Unsupported regex escape"); inside one they were copied
      raw and the grammar failed to load. Outside a class such an escape is now the bare
      character -- regex syntax characters and '"' keep their backslash and go the old way --
      and inside a class it is written \xHH, so an escaped '-' or '^' cannot read as a range or
      a negation. gbnf_test covers "\/" and "\-" in literals, "\-" "\^" "\." in classes and as
      a range endpoint, an unanchored "a\-b", and zod's email pattern.

  patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch

      Inside a class, escapes GBNF does not know (\b \f \v \0, an escaped space, \p{..}, \c, a
      backreference) were copied raw and the grammar failed to load -- an internal error on a
      schema the converter had accepted. A JSON string holds a control character only as an
      escape, so \t \n \r \f \b \v \0 in a class, and \t \n \r \f \v \0 outside one, now
      match that escape: a positive class gains them as alternatives ("[a\t]" reads
      "(?:[a]|\\t)", and "[\s]" gains "\\[tnfr]" as 0018 gave the bare \s), and a negated class is
      spelled as text that is neither a listed character nor one of those escapes ("[^\n]+" no
      longer admits the escape \n). An outside escape is a group, so a quantifier takes all of it.
      An escaped space or non-ASCII character is itself. \x and \u in a class need their hex
      digits; "\0" before a digit (a legacy octal) is refused. Every other class escape is now
      refused at conversion with a message naming it. Limits: a negated class still admits the
      \u form of a character it leaves out (\u0009 for \t), and a positive class admits \t \n \r \f
      \b only in their short form. gbnf_test covers each escape in and out of a class, quantified,
      and negated, and the refusals.

  patches/0021-jinja-a-dotted-integer-is-an-index.patch

      llama.cpp's ae9afff8 ("jinja : support dot property integer literals (#28817)"), after the
      lifted commit; drop it on the next refresh. jinja2 reads `obj.0` as `obj[0]`; the engine
      threw "Static member property must be an identifier". GLM-5's template tests a tool result
      with `m.content.0.type`, and since the probe swallows the throw the template came back as
      tools=0 tool_calls=0, as 0006 describes: every request with `tools` was refused.
      tests/chat_test.cpp (a_dotted_integer_is_an_index_as_in_jinja2).

  patches/0022-httplib-the-drain-keeps-a-five-second-budget.patch

      vendor/cpp-httplib/, not vendor/llama/: applies from vendor/cpp-httplib/ with `patch -p1`.

      Upstream's tail of process_request() drains an unconsumed framed body to keep it from being
      read back as the next request on a keep-alive connection. Since v0.64.0 the library bounds
      that drain -- a byte cap (CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH), the connection's read
      timeout as a total max_timeout, an immediate close for a body left partway -- and closes the
      connection on every 4xx/5xx response, skipping the drain there entirely. What it cannot
      bound tighter is the drain's time, because the timeout it uses is the same knob that bounds
      a whole request's reads: lowering it to hurry a drain along would cap slow uploads just as
      hard. A client dribbling one byte per packet gap still paces a worker for that full timeout
      on a socket that was never going to be used again.

      The patch gives the drain its own budget: five seconds total, or the connection's read
      timeout when that is shorter. Past it the stream read fails, the drain gives up, and the
      connection closes with the unread bytes still on it. Tests: transport_test
      (a_stalled_drain_dies_on_its_deadline, a_refusal_closes_the_connection,
      the_inflight_body_budget).

  patches/0023-jinja-tojson-sort-keys.patch

      llama.cpp's e1925b36 ("jinja: support json sort_keys=true (#32366)"), after the lifted
      commit; drop it on the next refresh. tojson threw "tojson sort_keys=true not implemented".
      Inkling 2 Mini's template writes its tool list with tojson(sort_keys=true), so the probe
      failed, as 0006 describes, and every request with `tools` was refused. value_to_json takes
      sort_keys and orders each object's keys by their UTF-8 bytes, nested objects and objects in
      arrays too. tests/chat_test.cpp (tojson_sorts_object_keys_when_sort_keys_is_true,
      a_template_that_sorts_its_tools_reports_tool_support,
      inklings_tool_declaration_renders_its_tools_with_sorted_keys).
