Next iterative Claude Code prompt engineered ™️ Plan (click to uncollapse)
Plan: per-format chat pipeline (FSM tracker → decoder → transformer → presenter)
Naming and responsibility split
The current code conflates several responsibilities into a single common_chat_peg_mapper::map() method. The refactor splits them into a four-stage per-format pipeline:
-
common_chat_format_tracker (FSM state) — Knows the current conversation state from what the model has emitted. Drives the PEG parser’s expectations (expected_productions() → tighter next_sequence_delimiters) and mirrors llguidance’s internal grammar state. Does NOT emit anything; pure state-keeping. Per format.
-
common_chat_format_decoder (wire-format extraction) — Reads AST nodes and produces typed, format-specific intermediate values: raw tool name, raw tool id, raw arg key/value pairs, raw reasoning text, raw content text. Knows the model’s wire format (DSML <param> tags, Python name(k=v), JSON {"k":v}, Kimi functions.NAME:IDX, Gemma’s <|"|>-delimited dict, etc.) and emits a stream of decoded_event structs. Per format.
-
common_chat_format_transformer (model-specific shaping) — Consumes decoded_events from the decoder and applies model-specific transforms to reasoning, content, and tool-call fields. Transformer responsibilities:
- Per-format reasoning shaping: stripping markers, normalizing whitespace, picking which channel becomes reasoning vs content (e.g. GPT-OSS
analysis → reasoning, commentary → content), concatenating multiple reasoning blocks per family rules.
- Per-format content shaping: stripping leftover chat-template tokens (e.g. Kimi
<|im_assistant|>assistant<|im_middle|> prefix that leaks into raw output), trimming, normalizing newlines.
- Per-format tool-call shaping: assembling
TOOL_ARG_KV events into a JSON args string (Python/DSML formats), JSON-pass-through for TOOL_ARGS_RAW (Kimi/Hermes/etc.), parsing tool-id functions.NAME:IDX into (name, id).
Output is a stream of shaped_events — same shape as decoded_event but cleaned/normalized per format. Per format.
-
common_chat_format_presenter (API-shape assembly → common_chat_msg) — Format-agnostic. Consumes shaped_events and writes them into the OpenAI-compatible common_chat_msg: .role, .content, .reasoning_content, .tool_calls[], .tool_call_id, etc. Cross-cutting concerns live here:
- Discarding whitespace-only reasoning content
- Ensuring tool calls have all required fields
- Maintaining streaming monotonicity invariants
- Default role=“assistant” assignment
One shared implementation; per-format presenters exist only if a model needs message-shape-level idiosyncrasies (which is rare).
The pipeline runs node-by-node during the AST walk. All four layers operate in lock-step with the tracker’s FSM state. The tracker advances first; then each downstream layer reads the now-current state at its own step. State changes affect interpretation at every layer:
AST node N
├─> tracker.advance(N) // update FSM state -> S
│
├─> events = decoder.decode(N) // reads S to interpret the node
│ // e.g. a `<` token in S=IN_CONTENT is a content char;
│ // in S=IN_TOOL_OPEN it's the start of a tool tag
│
├─> for each event in events:
│ shaped = transformer.shape(event) // reads S to shape the event
│ // e.g. CONTENT_TEXT in S=IN_CONTENT lands as content;
│ // CONTENT_TEXT in S=IN_REASONING (channel-overloaded format)
│ // could be re-routed to reasoning instead
│
└─> for each shaped event in shaped:
presenter.present(shaped) // reads S to land in common_chat_msg
// e.g. TOOL_NAME in S=IN_TOOL_NAME starts a new tool call;
// TOOL_NAME in S=IN_TOOL_CALL (already had a name) is a no-op
The lock-step property is invariant: the decoder, transformer, and presenter MUST consult tracker.current_state() at every step. They never assume state — they observe it. This way:
- The decoder never has to maintain duplicate state to know “am I inside a tool call?” — it just asks the tracker.
- The transformer never has to maintain duplicate state to know “is this fragment reasoning or content?” — same.
- The presenter never has to maintain duplicate state to know “is this a new tool call or a continuation?” — same.
The tracker is the single source of truth. The other three layers are stateless w.r.t. conversation position; any state they keep (e.g. transformer buffering KV events for args assembly) is local to a single state-bracketed span and reset on state transitions the tracker reports.
Per-format pieces live together:
| Old name |
New name |
Role |
common_chat_peg_mapper (legacy) |
split into 4 base classes (below) |
replaced |
| state enum |
common_chat_format_state |
tracker FSM states |
| parser-side read-only iface |
common_chat_format_state_view |
parser/decoder see only this |
| tracker base |
common_chat_format_tracker |
abstract, per-format subclass |
| decoder base |
common_chat_format_decoder |
abstract, per-format subclass |
| transformer base |
common_chat_format_transformer |
abstract, per-format subclass |
| presenter base |
common_chat_format_presenter |
concrete default; per-format subclass only if needed |
| family base for JSON-tagged decoders |
common_chat_json_tagged_decoder |
shared family base |
| family base for JSON-tagged transformers |
common_chat_json_tagged_transformer |
shared family base |
| per-format quartet |
common_chat_<family>_tracker + _decoder + _transformer (and optionally _presenter) |
up to four per family, in one *-format.{h,cpp} file |
| directory |
common/chat-formats/ |
houses all four layers |
| FSM transition method |
advance(const common_peg_ast_node&) (tracker) |
|
| Decoder per-node method |
decode(const common_peg_ast_node&) returns std::vector<decoded_event> |
|
| Transformer per-event method |
shape(decoded_event) returns std::vector<shaped_event> |
applies model-specific transforms |
| Presenter per-event method |
present(const shaped_event&) writes to common_chat_msg |
|
| Top-level coordinator |
common_chat_format_pipeline::run(arena, result) |
walks AST, invokes all four layers in order |
| Decoded events type |
common_chat_decoded_event (variant of tool_open/tool_close/arg_kv/reasoning_text/content_text/tool_id/tool_name) |
typed wire-shape output |
| Shaped events type |
common_chat_shaped_event (same variants as decoded but post-transform; e.g. args_json instead of arg_kv) |
typed model-shape output |
make_mapper lambda in chat.cpp |
make_format_pipeline(params.format, msg) |
dispatcher |
common_chat_peg_builder and the PEG runtime types are unchanged: they are the parsing machinery the tracker observes and the decoder reads.
Context
common/chat-peg-parser.cpp has accumulated format-specific hacks in a single 280-line common_chat_peg_mapper::map() method: a phantom-tool-open guard for streaming, a nested-tool-open extent check for LFM2’s ( opener, DSML branches handling DeepSeek’s <param> rule names, name-before-open recovery, JSON brace synthesis on is_tool_close, and quote synthesis on is_arg_value. Adding any new format means adding more branches.
The user’s intent — clarified: each model family gets a per-format pipeline of four cooperating layers that operate in lock-step with a Finite State Machine tracking the current conversation state (IN_REASONING, IN_TOOL_CALL, IN_TOOL_ARGS, IN_TOOL_CLOSE, IN_CONTENT, etc.) determined by what the model has emitted so far:
- Tracker (FSM) — pure state. Consumes AST nodes via
advance(node). Drives the PEG parser’s expectations (expected_productions() → tighter next_sequence_delimiters). Mirrors llguidance’s internal Lark-grammar state, so when the tracker says IN_TOOL_ARGS, llguidance is also at the tool-args rule and constraining tokens accordingly.
- Decoder — extracts wire-format-specific values (tool name, id, args, KV pairs, reasoning text, content text) from AST nodes as typed
decoded_events. Reads tracker state to interpret nodes.
- Transformer — applies model-specific shaping to events (content prefix stripping, reasoning channel routing, tool-args JSON construction). Reads tracker state.
- Presenter — projects shaped events onto
common_chat_msg. Reads tracker state. One default implementation covers all formats.
This is a bidirectional contract: model output advances the tracker FSM; the FSM constrains future model output (via llguidance and the parser) and instructs the downstream three layers how to interpret each AST node. The tracker is the single source of truth for “where in the conversation are we”; the other three layers are stateless w.r.t. conversation position and consult the tracker at every step.
Today, the parser and llguidance are independently driven only by the grammar string. The legacy common_chat_peg_mapper mixes state-keeping, wire-shape extraction, format-specific shaping, and common_chat_msg projection in a single map() method. The refactor splits these into the four-layer per-format pipeline.
Hard policies (carried over):
- Closing tokens MUST stay required in grammars.
- The decoder and presenter MUST NOT synthesize any character the model didn’t emit. The transformer MAY synthesize structural JSON characters (
{, }, ,, :) only when it has to convert non-JSON wire shapes (Python name(k=v), DSML <param>) into the JSON arguments string the API requires — and that is confined to per-format transformer subclasses with explicit “scoped exception” comments.
Today: 16/19 templates pass. Failing: Gemma-4 (grammar mismatches the real Gemma 4 spec at https://ai.google.dev/gemma/docs/core/prompt-formatting-gemma4), Qwen3-Coder (no grammar file), GLM-4.7-Flash (no grammar file). The refactor finishes them with their own pipelines.
Outcome
- Each model family has a dedicated four-layer pipeline (
tracker + decoder + transformer + presenter) in common/chat-formats/ and a per-format COMMON_CHAT_FORMAT_PEG_* enum value.
- All four layers operate in lock-step with the tracker FSM state. The tracker is the single source of truth; the other three layers are stateless w.r.t. conversation position and consult
tracker.current_state() at every step.
- The tracker is the explicit authority on conversation state, exposing
current_state(), expected_productions(), and advance(node).
- The decoder produces typed
common_chat_decoded_events from the AST per format wire shape.
- The transformer applies model-specific shaping (content prefix stripping, reasoning channel routing, tool-args JSON construction) and emits
common_chat_shaped_events.
- The presenter writes shaped events into
common_chat_msg (default impl handles all formats; per-format overrides are rare).
- llguidance is informed of state transitions via the same per-format grammar (no API change: it already tracks state internally from the Lark grammar). The per-format Lark grammar must encode all reachable FSM states; the tracker mirrors that structure 1:1.
- The legacy
common_chat_peg_mapper and common_chat_peg_gemma4_mapper are deleted at step 7.
- All 19 templates in
tests/test-chat.cpp pass, including Gemma-4 (with corrected grammar), Qwen3-Coder, and GLM-4.7-Flash.
- The only character-synthesis remaining is the deliberate
{/} and , for assembling TOOL_ARG_KV events into TOOL_ARGS_JSON in the transformer layer of formats whose wire shape isn’t JSON (DSML, lfm2, qwen3-coder, glm-4-7-flash). This is scoped, documented, and called out as the unavoidable shape conversion.
Architecture
Directory layout
One header+source pair per family declares the per-family tracker, decoder, and transformer (and a factory). The three layers always travel together for a format.
common/chat-formats/
decoded-event.h # struct common_chat_decoded_event + kind enum
format-tracker.{h,cpp} # abstract base tracker + state enum + state_view iface
format-decoder.{h,cpp} # abstract base decoder
format-transformer.{h,cpp} # default transformer (event -> common_chat_msg)
format-pipeline.{h,cpp} # coordinator: walk AST, run all three layers
json-tagged-format.{h,cpp} # shared family bases for JSON-tagged formats
gemma4-format.{h,cpp} # rewritten for the real Gemma 4 spec
deepseek-v3-2-format.{h,cpp} # DSML <param name="k" string="bool">v</param>
kimi-k2-format.{h,cpp} # JSON-tagged + functions.NAME:IDX id parse
ministral-3-format.{h,cpp} # pure JSON-tagged
gpt-oss-format.{h,cpp} # JSON-tagged + channel handling
functionary-v3-2-format.{h,cpp} # JSON-tagged + ">>>recipient" -> name
gigachat-v3-format.{h,cpp} # pure JSON-tagged
lfm2-format.{h,cpp} # python-style name(k=v)
lfm2-5-format.{h,cpp} # subclass of lfm2-format, no wrapper
qwen3-coder-format.{h,cpp} # NEW: <function=name><parameter=k>v</parameter>
glm-4-7-flash-format.{h,cpp} # NEW: <tool_call>name<arg_key>k</arg_key><arg_value>v</arg_value>
hermes-format.{h,cpp} # JSON-tagged (Nous Hermes)
granite-format.{h,cpp} # JSON-tagged (IBM Granite 3.3 / 4.0)
nemotron-format.{h,cpp} # JSON-tagged (NVIDIA Nemotron)
cohere-c4ai-format.{h,cpp} # action-tagged: <|START_ACTION|>[{...}]<|END_ACTION|>
seed-oss-format.{h,cpp} # XML-tagged (ByteDance Seed-OSS)
qwq-format.{h,cpp} # JSON-tagged (Qwen-QwQ-32B)
qwen3-5-format.{h,cpp} # XML-tagged (Qwen3.5)
glm-4-6-format.{h,cpp} # XML-tagged (GLM-4.6)
Each *-format.{h,cpp} exports the per-family tracker, decoder, and (when needed) transformer subclasses, plus a factory common_chat_<NAME>_make_pipeline(msg) returning a fully-wired common_chat_format_pipeline.
Abstract base APIs
common/chat-formats/decoded-event.h
The intermediate “decoded event” type passed from the decoder to the transformer. A typed enumeration of the wire-format-independent things a model can say. New variants are added centrally; per-format decoders pick the subset they emit.
struct common_chat_decoded_event {
enum class kind {
REASONING_TEXT, // text fragment to append to .reasoning_content
CONTENT_TEXT, // text fragment to append to .content
TOOL_OPEN, // begin a new tool call
TOOL_NAME, // function name (full string; partial frags suppressed by decoder)
TOOL_ID, // tool call id (Kimi-style)
TOOL_ARGS_RAW, // pre-formed JSON args text (model emitted JSON directly)
TOOL_ARG_KV, // a single (key, value, is_string) pair (formats that emit per-arg KV)
TOOL_CLOSE, // end of tool call
};
kind k;
std::string text; // for *_TEXT, TOOL_NAME, TOOL_ID, TOOL_ARGS_RAW
std::string key; // for TOOL_ARG_KV
std::string value; // for TOOL_ARG_KV (raw model bytes; transformer JSON-stringifies)
bool is_string; // for TOOL_ARG_KV (true => quote+escape; false => emit verbatim as JSON value)
bool is_partial; // event flagged as partial; transformer may choose to suppress
};
common/chat-formats/format-tracker.h
The tracker base owns the FSM enum, transition contract, and the read-only state view interface. It does NOT touch common_chat_msg and does NOT emit decoded events.
// Universal "where are we in the conversation" states. Each per-format FSM
// uses a SUBSET of these — e.g. DSML has IN_TOOL_PARAM that JSON-tagged formats
// don't. New states are added here as needed; per-format FSMs declare which
// they actually use.
enum class common_chat_format_state : uint8_t {
INITIAL, // nothing emitted yet
IN_CONTENT, // free-form assistant content
IN_REASONING, // inside <think>/<channel|>thought/etc.
IN_TOOL_CALL, // inside a tool call envelope (after open, before close)
IN_TOOL_NAME, // currently emitting the function name
IN_TOOL_ID, // currently emitting the tool-call id (Kimi-style)
IN_TOOL_ARGS, // inside the args region (json or per-format)
IN_TOOL_ARG_KEY, // tagged-args formats: between arg-name open and close
IN_TOOL_ARG_VAL, // tagged-args formats: between arg-value open and close
IN_TOOL_PARAM, // DSML <param>...</param>
DONE, // tool-call closed; back at top-level
};
// Read-only window into a tracker's FSM, exposed to the PEG parser context AND
// to the transformer so neither needs to include the tracker's full type.
class common_chat_format_state_view {
public:
virtual ~common_chat_format_state_view() = default;
virtual common_chat_format_state current_state() const = 0;
virtual std::vector<std::string> expected_productions() const = 0;
};
class common_chat_format_tracker : public common_chat_format_state_view {
public:
virtual ~common_chat_format_tracker() = default;
// Single transition entry-point. Concrete trackers MUST update `state_`
// per their declared FSM. NO side effects elsewhere — the tracker is
// pure state. It may inspect node.tag/node.rule/node.is_partial; it may
// not write to common_chat_msg, emit events, or mutate any other layer.
virtual void advance(const common_peg_ast_node & node) = 0;
// common_chat_format_state_view
common_chat_format_state current_state() const override { return state_; }
std::vector<std::string> expected_productions() const override = 0;
protected:
common_chat_format_state state_ = common_chat_format_state::INITIAL;
};
common/chat-formats/format-decoder.h
The decoder base reads AST nodes (in lock-step with the tracker) and emits typed common_chat_decoded_events. It is the only layer that knows the format’s wire shape. It does NOT touch common_chat_msg. It MUST consult the tracker’s current state on every call to interpret the node correctly.
class common_chat_format_decoder {
public:
explicit common_chat_format_decoder(const common_chat_format_state_view & state)
: state_(state) {}
virtual ~common_chat_format_decoder() = default;
// Per-node decode step. Returns zero or more decoded events. The decoder
// MUST read state_.current_state() to interpret the node correctly (e.g.
// a `<` token means different things in IN_CONTENT vs IN_TOOL_CALL).
// The decoder MUST NOT mutate tracker state.
virtual std::vector<common_chat_decoded_event>
decode(const common_peg_ast_node & node) = 0;
protected:
const common_chat_format_state_view & state_;
};
Concrete decoders are the bulk of per-format work. Examples:
common_chat_json_tagged_decoder: emits TOOL_OPEN on tag tool-open, TOOL_NAME on complete tag tool-name, TOOL_ARGS_RAW on complete tag tool-args, TOOL_CLOSE on tag tool-close.
common_chat_lfm2_decoder: emits TOOL_OPEN, TOOL_NAME, then TOOL_ARG_KV{key, value, is_string=…} per <tag tool-arg-name, tag tool-arg-value> pair, then TOOL_CLOSE.
common_chat_deepseek_v3_2_decoder: emits TOOL_OPEN, TOOL_NAME (from name="…" attr), then TOOL_ARG_KV per <param> (using bool-str rule for is_string), TOOL_CLOSE.
common_chat_gemma4_decoder: walks the gemma4_dict AST recursively, emits TOOL_OPEN, TOOL_NAME, TOOL_ARGS_RAW (built from gemma4_to_json() over the dict subtree), TOOL_CLOSE.
common/chat-formats/format-transformer.h
The transformer base consumes common_chat_decoded_events and emits common_chat_shaped_events. It applies model-specific transforms — content prefix stripping, reasoning channel routing, tool-args JSON construction. It does NOT touch common_chat_msg.
struct common_chat_shaped_event {
enum class kind {
REASONING_TEXT,
CONTENT_TEXT,
TOOL_OPEN,
TOOL_NAME,
TOOL_ID,
TOOL_ARGS_JSON, // always JSON-string form, regardless of source format
TOOL_CLOSE,
};
kind k;
std::string text;
bool is_partial = false;
};
class common_chat_format_transformer {
public:
explicit common_chat_format_transformer(const common_chat_format_state_view & state)
: state_(state) {}
virtual ~common_chat_format_transformer() = default;
// Per-event shaping. Receives one decoded event; emits zero or more
// shaped events. MUST consult state_.current_state() to know how to
// interpret the event (e.g. a CONTENT_TEXT in IN_REASONING for a
// channel-overloaded format may need to be re-routed). Subclasses may
// buffer state across calls (e.g. accumulate TOOL_ARG_KV events until
// TOOL_CLOSE and emit a single TOOL_ARGS_JSON).
virtual std::vector<common_chat_shaped_event>
shape(const common_chat_decoded_event & event) = 0;
// Optional final flush (e.g. emit any buffered events when AST walk ends).
virtual std::vector<common_chat_shaped_event> on_finalize() { return {}; }
protected:
const common_chat_format_state_view & state_;
};
The transformer is the per-format layer for cleaning up reasoning, content, and tool args. Examples:
- kimi-k2 transformer: passes most events through verbatim; strips
<|im_assistant|>assistant<|im_middle|> prefix from CONTENT_TEXT events.
- gpt-oss transformer: routes
analysis channel REASONING_TEXT to REASONING_TEXT, routes commentary channel content to CONTENT_TEXT (assignment depends on tracker state).
- lfm2 transformer: buffers
TOOL_ARG_KV events until TOOL_CLOSE; on close, emits a single TOOL_ARGS_JSON containing the JSON-stringified args (this is where the { / } synthesis is scoped — the only place it ever appears, and only for non-JSON-args formats).
- deepseek-v3-2 transformer: same KV-buffering pattern as lfm2.
- json-tagged transformers: passes
TOOL_ARGS_RAW through as TOOL_ARGS_JSON verbatim, no synthesis.
common/chat-formats/format-presenter.h
The presenter base consumes common_chat_shaped_events and writes to common_chat_msg. One shared implementation handles the OpenAI-compatible message shape for all formats. Per-format presenters exist only if a model needs message-shape-level peculiarities (rare).
class common_chat_format_presenter {
public:
common_chat_msg & result;
bool is_partial_parse = false;
explicit common_chat_format_presenter(common_chat_msg & m,
const common_chat_format_state_view & state)
: result(m), state_(state) {}
virtual ~common_chat_format_presenter() = default;
// Per-event projection into common_chat_msg. MUST consult
// state_.current_state() to disambiguate (e.g. TOOL_NAME in IN_TOOL_NAME
// starts a new pending call; TOOL_NAME in IN_TOOL_CALL/already-named is a
// no-op). The default implementation covers all formats:
// REASONING_TEXT -> append to result.reasoning_content
// CONTENT_TEXT -> append to result.content
// TOOL_OPEN -> push a new pending common_chat_tool_call
// TOOL_NAME -> set pending tool .name
// TOOL_ID -> set pending tool .id
// TOOL_ARGS_JSON -> set pending tool .arguments (verbatim, no synthesis)
// TOOL_CLOSE -> commit pending tool to result.tool_calls
virtual void present(const common_chat_shaped_event & event);
// Final cross-cutting cleanups:
// - Discard whitespace-only reasoning_content
// - Default role="assistant"
virtual void on_finalize();
protected:
const common_chat_format_state_view & state_;
};
Pipeline coordinator (common/chat-formats/format-pipeline.h)
struct common_chat_format_pipeline {
std::unique_ptr<common_chat_format_tracker> tracker;
std::unique_ptr<common_chat_format_decoder> decoder;
std::unique_ptr<common_chat_format_transformer> transformer;
std::unique_ptr<common_chat_format_presenter> presenter;
// Walk the AST. For each node:
// tracker.advance(node)
// for each event in decoder.decode(node):
// for each shaped in transformer.shape(event):
// presenter.present(shaped)
// Final: flush transformer.on_finalize() through presenter, then
// presenter.on_finalize().
void run(const common_peg_ast_arena&, const common_peg_parse_result&);
};
common_chat_format_pipeline common_chat_make_format_pipeline(
common_chat_format format, common_chat_msg & msg);
The dispatcher in chat.cpp builds the pipeline once per parse. The four layers are constructed wired together: the decoder gets a non-owning pointer to the tracker’s state_view; the transformer and presenter are independent.
FSM-to-grammar contract (documented in format-tracker.h):
- Every
common_chat_format_state reachable in a per-format FSM MUST correspond to a named rule (or set of rules) in the per-format Lark grammar.
expected_productions() MUST return the names of those rules. The PEG parser uses them to bound speculative matching; the llguidance setup verifies they’re declared.
- llguidance does not need direct hooks: by virtue of mirroring the grammar exactly, it’s already in the matching state internally. The tracker is the C++ mirror of llguidance’s internal state, observable for both parser and transformer.
Per-format pipelines
Each per-format pipeline declares its (tracker FSM, decoder events, transformer shapes). State transitions and events are decoupled: the tracker only updates state; the decoder reads state and emits events; the transformer reshapes events.
json_tagged family base (Kimi, Ministral, Functionary, GigaChat, Hermes, Granite, QwQ, Nemotron, Seed-OSS, Cohere c4ai, Qwen3.5, GLM-4.6 — most JSON-args formats)
Tracker FSM (states used: INITIAL, IN_CONTENT, IN_REASONING, IN_TOOL_CALL, IN_TOOL_NAME, IN_TOOL_ID, IN_TOOL_ARGS, DONE):
INITIAL/DONE --tag tool-open(complete, has tool-name child)--> IN_TOOL_CALL
IN_TOOL_CALL --tag tool-id(complete)--> IN_TOOL_ID
IN_TOOL_ID --tag tool-name(complete)--> IN_TOOL_NAME
IN_TOOL_CALL --tag tool-name(complete)--> IN_TOOL_NAME
IN_TOOL_NAME --tag tool-args(complete)--> IN_TOOL_ARGS
IN_TOOL_ARGS --tag tool-close--> DONE
expected_productions():
INITIAL/IN_CONTENT → ["content", "reasoning", "tool-open"]
IN_TOOL_CALL → ["tool-id", "tool-name"]
IN_TOOL_ID → ["tool-name"]
IN_TOOL_NAME → ["tool-args"]
IN_TOOL_ARGS → ["tool-close"]
DONE → ["tool-open", "content"]
Decoder emits, depending on tracker state at decode time:
tag reasoning → REASONING_TEXT{node.text}
tag content → CONTENT_TEXT{node.text}
tag tool-open (complete, has tool-name) → TOOL_OPEN{}
tag tool-id (complete) → TOOL_ID{trim(node.text)}
tag tool-name (complete) → TOOL_NAME{trim(node.text)}
tag tool-args (complete) → TOOL_ARGS_RAW{node.text} // raw model-emitted JSON
tag tool-close → TOOL_CLOSE{}
- Phantom partial
tag tool-open (no tool-name child): nothing emitted.
Transformer (default for json_tagged family): passes events through unchanged. TOOL_ARGS_RAW becomes TOOL_ARGS_JSON verbatim — no synthesis. Per-format subclasses can override:
- kimi-k2 transformer: when
TOOL_ID{text} arrives, parses functions.NAME:IDX, emits TOOL_NAME{NAME} followed by TOOL_ID{IDX}.
- gpt-oss transformer: re-routes
CONTENT_TEXT events to REASONING_TEXT if state is IN_REASONING (channel=analysis); other channels pass through.
- functionary-v3-2 transformer: maps recipient text to
TOOL_NAME.
Presenter: shared default. No format-specific overrides for these.
Rewritten grammar; tokens <|turn>/<turn|>, <|channel>thought/<channel|>, <|tool_call>call:NAME{K:<|"|>V<|"|>,...}<tool_call|>.
Tracker FSM: INITIAL, IN_CONTENT, IN_REASONING, IN_TOOL_CALL, IN_TOOL_NAME, IN_TOOL_ARGS, DONE.
Decoder: walks the gemma4_dict subtree (using the existing gemma4_to_json() logic, moved into the decoder), emits TOOL_OPEN/TOOL_NAME/TOOL_ARGS_RAW/TOOL_CLOSE. Reasoning + content as in json_tagged.
Transformer: pass-through (gemma’s args are already JSON-shape after gemma4_to_json()).
Presenter: shared default.
deepseek_v3_2 (DSML XML params)
Tracker FSM: INITIAL, IN_CONTENT, IN_REASONING, IN_TOOL_CALL, IN_TOOL_NAME, IN_TOOL_PARAM, DONE.
INITIAL --tag tool-open(<func_calls>)--> IN_TOOL_CALL
IN_TOOL_CALL --rule invoke (start)--> IN_TOOL_NAME
IN_TOOL_NAME --rule param (start)--> IN_TOOL_PARAM
IN_TOOL_PARAM --rule param-name--> IN_TOOL_PARAM
IN_TOOL_PARAM --rule bool-str--> IN_TOOL_PARAM
IN_TOOL_PARAM --rule param-value (complete)--> IN_TOOL_NAME
IN_TOOL_NAME --tag tool-close--> DONE
Decoder: emits TOOL_OPEN on tag tool-open; TOOL_NAME from invoke’s name="…" attribute; TOOL_ARG_KV{key, value, is_string} per <param> block (using bool-str rule for is_string); TOOL_CLOSE.
Transformer: buffers TOOL_ARG_KV events (no immediate emit); on TOOL_CLOSE, assembles TOOL_ARGS_JSON{"k1":dump(v1),...} and emits both. The { and } here are the deliberate, scoped synthesis (DSML format has no JSON envelope) — confined to this transformer.
Presenter: shared default.
lfm2 and lfm2_5 (Python-style name(k=v))
Tracker FSM: INITIAL, IN_CONTENT, IN_REASONING, IN_TOOL_CALL, IN_TOOL_NAME, IN_TOOL_ARG_KEY, IN_TOOL_ARG_VAL, DONE.
INITIAL --tag tool-open--> IN_TOOL_CALL
IN_TOOL_CALL --tag tool-name (complete)--> IN_TOOL_NAME
IN_TOOL_NAME --tag tool-arg-name (complete)--> IN_TOOL_ARG_KEY
IN_TOOL_ARG_KEY --tag tool-arg-value (complete)--> IN_TOOL_NAME
IN_TOOL_NAME --tag tool-close--> DONE
Decoder: emits TOOL_OPEN, TOOL_NAME, then TOOL_ARG_KV{key, value, is_string} per (arg-name, arg-value) pair (is_string from grammar/value form), then TOOL_CLOSE.
Transformer: same KV-buffering and TOOL_ARGS_JSON assembly as DSML.
Presenter: shared default.
lfm2_5 reuses lfm2’s tracker/decoder/transformer entirely — only the grammar differs (no wrapper tokens).
qwen3-coder and glm-4-7-flash (XML-tagged per-arg)
Same FSM shape as lfm2 (per-arg KV collection). Decoders read <parameter=key>val</parameter> (qwen3-coder) or <arg_key>k</arg_key><arg_value>v</arg_value> (glm-4-7-flash). Transformer is the same KV→JSON assembly.
common_chat_lfm2_5_tracker — : public common_chat_lfm2_tracker, identical state machine.
common_chat_qwen3_coder_tracker — same FSM shape as common_chat_lfm2_tracker (per-arg KV collection), with IN_TOOL_NAME set from the <function=...> open and IN_TOOL_ARG_KEY/VAL from <parameter=...>...</parameter>. New grammar qwen3-coder.lark:
%llguidance {}
start: think_block? content tool_call_block?
think_block: "<think>" reasoning "</think>"
reasoning: /(.|\n)*?/
content: /(.|\n)*?/
tool_call_block: tool_call+
tool_call: "<tool_call>" /[ \t\n\r]*/ "<function=" func_name ">" /[ \t\n\r]*/ tool_arg+ /[ \t\n\r]*/ "</function>" /[ \t\n\r]*/ tool_close
tool_close: "</tool_call>"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
tool_arg: "<parameter=" arg_name ">" /\n?/ arg_value /\n?/ "</parameter>" /\n?/
arg_name: /[a-zA-Z_][a-zA-Z0-9_]*/
arg_value: /(.|\n)*?/
New grammar files
grammars/chat/qwen3-coder.lark:
%llguidance {}
start: think_block? content tool_call_block?
think_block: "<think>" reasoning "</think>"
reasoning: /(.|\n)*?/
content: /(.|\n)*?/
tool_call_block: tool_call+
tool_call: "<tool_call>" /[ \t\n\r]*/ "<function=" func_name ">" /[ \t\n\r]*/ tool_arg+ /[ \t\n\r]*/ "</function>" /[ \t\n\r]*/ tool_close
tool_close: "</tool_call>"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
tool_arg: "<parameter=" arg_name ">" /\n?/ arg_value /\n?/ "</parameter>" /\n?/
arg_name: /[a-zA-Z_][a-zA-Z0-9_]*/
arg_value: /(.|\n)*?/
grammars/chat/glm-4-7-flash.lark:
%llguidance {}
start: think_block? content tool_call_block?
think_block: "<think>" reasoning "</think>"
reasoning: /(.|\n)*?/
content: /(.|\n)*?/
tool_call_block: tool_call+
tool_call: "<tool_call>" /[ \t\n\r]*/ func_name /[ \t\n\r]*/ tool_arg+ /[ \t\n\r]*/ tool_close
tool_close: "</tool_call>"
func_name: FUNC_NAME
FUNC_NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
tool_arg: "<arg_key>" arg_name "</arg_key>" /[ \t\n\r]*/ "<arg_value>" arg_value "</arg_value>" /[ \t\n\r]*/
arg_name: /[^<]*/
arg_value: /(.|\n)*?/
hermes / granite / nemotron / cohere-c4ai / seed-oss / qwq / qwen3-5 / glm-4-6
Each is a thin pipeline reusing the json_tagged family base for tracker/decoder/transformer (or the per-arg KV variant for XML-tagged sub-families). Today these all flow through the auto-parser path at chat.cpp:1790 setting PEG_NATIVE. After this refactor each gets its own COMMON_CHAT_FORMAT_PEG_<NAME> enum and its own (mostly thin) per-format header, even if the four layers are reused unchanged from the family base.
How the tracker FSM informs the parser and llguidance
The PEG parser consumes input and produces AST nodes; today its expectations come purely from the loaded grammar’s structure (next_sequence_delimiters collected from the next sibling literals). After the refactor, the per-format tracker’s FSM is consulted during parsing:
common_peg_parse_context gains an optional common_chat_format_state_view * pointer. The PEG runtime sees only this read-only view interface — no chat-module dependency.
- Before parsing a child sequence, the PEG context queries
view->expected_productions() and intersects the list with next_sequence_delimiters — a tighter constraint than grammar-only.
- The constraint is purely additive: if
expected_productions() returns empty, the parser falls back to grammar-only behavior (current). So formats that do not need state-driven hints work as today.
llguidance is informed implicitly: the per-format Lark grammar already encodes all reachable states as named rules. llguidance’s Earley + lexer parser tracks the rule path internally as the model emits tokens, and computes a token mask at every position. The tracker is the C++ mirror of the same state — it doesn’t push to llguidance, it watches the same source of truth (the grammar). The only operational requirement is: each per-format grammar must contain rules whose names match expected_productions() exactly, so the C++ tracker FSM and llguidance’s internal state agree.
This is verified at startup: after building the per-format common_peg_arena, the tracker exposes the full set of rule names it expects across all states. We assert each is present in the arena. If a grammar update drops a rule, the assertion fires before any model is run.
Implementation order
Step 1 — Infrastructure. Create:
common/chat-formats/decoded-event.h, format-tracker.{h,cpp}, format-decoder.{h,cpp}, format-transformer.{h,cpp}, format-presenter.{h,cpp}, format-pipeline.{h,cpp} — the four base classes, the events struct, and the pipeline coordinator.
common/chat-formats/json-tagged-format.{h,cpp} — shared family base (tracker + decoder + transformer reuse for the JSON-args formats).
common/peg-parser.{h,cpp} — add the optional common_chat_format_state_view * pointer in common_peg_parse_context and the additive intersection with next_sequence_delimiters. No-op when the pointer is null.
Add the per-format COMMON_CHAT_FORMAT_PEG_* enum values to common/chat.h (already done partially). Replace make_mapper lambda in common/chat.cpp with make_format_pipeline(params.format, msg) returning a common_chat_format_pipeline. Default branch keeps the legacy common_chat_peg_mapper path active for templates not yet migrated; the legacy class is deleted in Step 7. Verify: build/bin/test-chat — all 16/19 still pass, 3 still fail.
Step 2 — Migrate one format at a time, easiest first. For each: write the per-format *-format.{h,cpp} containing all four layers (tracker FSM, decoder events, transformer shaping, optional presenter overrides), declare valid rules in expected_productions(), set the new enum in the matching common_chat_params_init_*, make the dispatcher route to its pipeline, run only that template’s tests via --template <name>. After each, also run the full suite to confirm no regression elsewhere.
Order: ministral-3 → gigachat-v3 → kimi-k2 → gpt-oss → functionary-v3-2 → deepseek-v3-2 → lfm2 → lfm2-5. After lfm2/lfm2-5 we delete the synthesis branches from the legacy common_chat_peg_mapper::map().
Step 3 — Auto-parser families per-template. For each of Hermes, Granite, Nemotron, Cohere c4ai, Seed-OSS, QwQ, Qwen3.5, GLM-4.6: add COMMON_CHAT_FORMAT_PEG_<NAME>, set it from the auto-parser path (chat.cpp:1790), add a per-family *-format.{h,cpp} (typically a thin reuse of the json_tagged family). Run each template; no behavior change expected.
Step 4 — Add Qwen3-Coder. New grammars/chat/qwen3-coder.lark, register in the grammar map, add common_chat_params_init_qwen3_coder, dispatcher entry, common/chat-formats/qwen3-coder-format.{h,cpp} (FSM identical to lfm2; decoder reads <parameter=k>val</parameter> instead of name(k=v)). Run --template Qwen3-Coder. Currently failing test tests/test-chat.cpp:2530 (HTML markup) starts passing.
Step 5 — Add GLM-4.7-Flash. New grammars/chat/glm-4-7-flash.lark, init function, dispatcher, common/chat-formats/glm-4-7-flash-format.{h,cpp}. Run --template GLM-4.7-Flash. The g_template_filter carve-out at tests/test-chat.cpp:3057 for the throw-path assertion test should be revisited once a real grammar exists.
Step 6 — Replace Gemma-4 grammar + format files. Rewrite grammars/chat/gemma4.lark to match https://ai.google.dev/gemma/docs/core/prompt-formatting-gemma4 — <|turn>model\n envelope, <|channel>thought ... <channel|> reasoning, <|tool_call>call:NAME{...}<tool_call|> tool calls. Closing tokens stay required. Replace common_chat_peg_gemma4_mapper with the new common/chat-formats/gemma4-format.{h,cpp} (tracker FSM, decoder using existing gemma4_to_json() logic, default transformer + presenter). Run --template gemma-4.
Step 7 — Synthesis purge + legacy mapper deletion. Once every format dispatches to its common_chat_format_pipeline, the legacy common_chat_peg_mapper::map() body is no longer reached. Delete:
chat-peg-parser.cpp:336–338 — current_tool->arguments = "{" synthesis when args buffer empty
chat-peg-parser.cpp:374–377 — target = "{" and arg_count comma synthesis
chat-peg-parser.cpp:392, 397, 416, 442 — opening " synthesis for string values
chat-peg-parser.cpp:454–458 — closing " synthesis on arg_close
chat-peg-parser.cpp:471–477 — json_brace_depth } synthesis on tool_close
- The
common_chat_peg_mapper and common_chat_peg_gemma4_mapper classes themselves.
The four-layer pipeline base classes plus per-format subclasses cover all paths. The only remaining JSON-shape synthesis is in the transformer layer for TOOL_ARG_KV → TOOL_ARGS_JSON assembly (Python/DSML/XML-tagged formats whose wire shape isn’t JSON), and it’s confined to those transformers with explicit comments calling out the deliberate exception.
Critical files
common/chat.h — per-format enum values (partial; completes here)
common/chat.cpp — common_chat_format_name, make_format_pipeline dispatcher, every common_chat_params_init_* sets its enum, line 1790 auto-parser fallback dispatches per template
common/chat-peg-parser.{h,cpp} — slimmed; the legacy mapper classes are deleted at step 7
common/peg-parser.{h,cpp} — add common_chat_format_state_view * to common_peg_parse_context; intersect expected_productions() into next_sequence_delimiters when set (additive constraint)
common/chat-formats/* — new directory, one *-format.{h,cpp} per family containing all four layers
common/CMakeLists.txt — list the new files
grammars/chat/{gemma4,qwen3-coder,glm-4-7-flash}.lark — rewritten/new
Verification
After each migration step:
cmake --build build --target test-chat -j$(nproc) — must succeed.
build/bin/test-chat --template <template-name> — must report [chat] All template tests passed! for the migrated template, and same status as before for every other template.
After the full refactor:
3. build/bin/test-chat — all 19 templates pass, no Error comparing accumulated message to current and no Tool call mismatch.
4. Streaming monotonicity is preserved (the test suite asserts this implicitly via compute_diffs).
5. After Step 7: grep "json_brace_depth\|closing_quote_pending" common/chat-formats/ returns matches only inside the per-format transformer files that legitimately assemble JSON args from KV events (DSML, lfm2, qwen3-coder, glm-4-7-flash), with explicit comments calling out the deliberate exception. common/chat-peg-parser.cpp has neither symbol.
Out of scope
- Lark→PEG / GBNF→PEG transpilers, grammar file embedding, CLI
--chat-{lark,gbnf}-grammar-file flags — handled in the prior plan (already implemented).
- The auto-parser (
common/chat-auto-parser*) itself is not refactored; only its output is routed through per-format pipelines.
- Streaming PEG parser internals (
common/peg-parser.cpp) — bug fixes already landed in the prior session for chars/repetition NEED_MORE at EOF; no further changes here beyond the new common_chat_format_state_view * hook.