//! The Inkling-2-Mini output channel dialect, ported faithfully from //! `serve/inkling_dialect.py` **as patched by the launcher `run_strata_cot.py`**. //! //! The model emits special *channel tokens* that segment its output. The engine //! streams them to us as detokenized pieces, and the server drives us once per //! token via [`InklingDialect::feed_token`] with `is_special` set for the channel //! tokens (mirrors `server.py`: `parser.feed_token(piece, is_special=(t in //! inkling_special_ids))`). We translate that into typed pieces: reasoning //! (chain-of-thought) and content (the answer, plus tool invocations rendered as //! JSON inside a tool-call frame). //! //! Two behaviours come from the launcher patch, not the base class: thinking is //! streamed live as it arrives (rather than accumulated and hidden), and the //! reasoning effort is whatever the config sets. We reproduce that patched //! behaviour, which is what actually runs on this machine. use serde_json::{Map, Value}; /// Channel tag literals, exactly as the detokenizer spells them. pub mod tag { pub const MESSAGE_MODEL: &str = "<|message_model|>"; pub const CONTENT_THINKING: &str = "<|content_thinking|>"; pub const CONTENT_TEXT: &str = "<|content_text|>"; pub const CONTENT_INVOKE_TOOL_JSON: &str = "<|content_invoke_tool_json|>"; pub const CONTENT_INVOKE_TOOL_TEXT: &str = "<|content_invoke_tool_text|>"; pub const CONTENT_XML: &str = "<|content_xml|>"; pub const END_MESSAGE: &str = "<|end_message|>"; pub const END_SAMPLING: &str = "<|content_model_end_sampling|>"; pub const ENDOFTEXT: &str = "<|endoftext|>"; /// The downstream OpenAI tool layer reads frames delimited by these; JSON /// inside them preserves arbitrary characters losslessly. pub const TOOL_CALL_OPEN: &str = ""; pub const TOOL_CALL_CLOSE: &str = ""; } /// Which output channel a piece belongs to. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { Reasoning, Content, } /// A typed output chunk produced by the dialect. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Out { pub kind: Kind, pub text: String, } impl Out { fn reasoning(text: impl Into) -> Self { Out { kind: Kind::Reasoning, text: text.into(), } } fn content(text: impl Into) -> Self { Out { kind: Kind::Content, text: text.into(), } } } /// The channel/structural tokens. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Tag { MessageModel, ContentThinking, ContentText, ContentInvokeToolJson, ContentInvokeToolText, ContentXml, EndMessage, EndSampling, EndOfText, } impl Tag { pub fn as_str(self) -> &'static str { use tag::*; match self { Tag::MessageModel => MESSAGE_MODEL, Tag::ContentThinking => CONTENT_THINKING, Tag::ContentText => CONTENT_TEXT, Tag::ContentInvokeToolJson => CONTENT_INVOKE_TOOL_JSON, Tag::ContentInvokeToolText => CONTENT_INVOKE_TOOL_TEXT, Tag::ContentXml => CONTENT_XML, Tag::EndMessage => END_MESSAGE, Tag::EndSampling => END_SAMPLING, Tag::EndOfText => ENDOFTEXT, } } pub fn parse(s: &str) -> Option { use tag::*; Some(match s { MESSAGE_MODEL => Tag::MessageModel, CONTENT_THINKING => Tag::ContentThinking, CONTENT_TEXT => Tag::ContentText, CONTENT_INVOKE_TOOL_JSON => Tag::ContentInvokeToolJson, CONTENT_INVOKE_TOOL_TEXT => Tag::ContentInvokeToolText, CONTENT_XML => Tag::ContentXml, END_MESSAGE => Tag::EndMessage, END_SAMPLING => Tag::EndSampling, ENDOFTEXT => Tag::EndOfText, _ => return None, }) } } const ALL_TAGS: [Tag; 9] = [ Tag::MessageModel, Tag::ContentThinking, Tag::ContentText, Tag::ContentInvokeToolJson, Tag::ContentInvokeToolText, Tag::ContentXml, Tag::EndMessage, Tag::EndSampling, Tag::EndOfText, ]; #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] enum State { #[default] Idle, Header, Think, ThinkEnd, Text, TextEnd, ToolJson, ToolText, } const MAX_HEADER_CHARS: usize = 128; const MAX_THINK_ACC: usize = 65536; /// The tags valid as transitions in each state (mirrors `_tags_for`). fn tags_for(state: State) -> &'static [Tag] { use State::*; match state { Idle | Header | ThinkEnd | TextEnd => &ALL_TAGS, Think => &[ Tag::EndMessage, Tag::ContentText, Tag::EndSampling, Tag::EndOfText, ], Text => &[Tag::EndMessage, Tag::EndSampling, Tag::EndOfText], ToolJson | ToolText => &[Tag::EndMessage, Tag::EndSampling, Tag::EndOfText], } } /// One instance per assistant reply: consumes the engine's token stream and /// yields typed reasoning/content pieces. #[derive(Debug, Default)] pub struct InklingDialect { state: State, header_acc: String, tool_acc: String, think_acc: String, end_ws: String, emitted_visible: bool, /// Thinking already streamed live by `emit` (so `finish` must not re-emit it). emitted_reasoning: bool, /// How many tool frames have been rendered (diagnostics). pub calls: u32, } impl InklingDialect { pub fn new() -> Self { Self::default() } /// Current state name, for tests and diagnostics. pub fn state(&self) -> &'static str { match self.state { State::Idle => "idle", State::Header => "header", State::Think => "think", State::ThinkEnd => "think_end", State::Text => "text", State::TextEnd => "text_end", State::ToolJson => "tool_json", State::ToolText => "tool_text", } } /// Token-aware entry: `piece` is one detokenized token; ordinary BPE text /// (`is_special = false`) is literal content and can never drive a channel /// transition, even if it spells a tag. Real channel tokens do. pub fn feed_token(&mut self, piece: &str, is_special: bool) -> Vec { let mut out = Vec::new(); if piece.is_empty() { return out; } if is_special { if let Some(tag) = Tag::parse(piece) { if tags_for(self.state).contains(&tag) { self.handle_tag(tag, &mut out); } else { // A real channel tag illegal in this state is emitted // verbatim in the current channel (e.g. quoted in thinking). self.emit(piece, &mut out); } return out; } } self.emit(piece, &mut out); out } /// Flush at end of stream. `reason` is the finish word (`"length"`, ...). pub fn finish(&mut self, reason: Option<&str>) -> Vec { let mut out = Vec::new(); self.finish_into(&mut out, reason); out } /// `_emit_typed`, patched: live reasoning for the thinking states; base /// behaviour for everything else. fn emit(&mut self, chunk: &str, out: &mut Vec) { if chunk.is_empty() { return; } match self.state { // patched: thinking streams live instead of being hidden State::Think => { self.append_think(chunk); out.push(Out::reasoning(chunk)); self.emitted_reasoning = true; } State::ThinkEnd => { if chunk.trim().is_empty() { self.end_ws.push_str(chunk); return; } let combined = format!("{}{}{}", tag::END_MESSAGE, self.end_ws, chunk); self.append_think(&combined); out.push(Out::reasoning(combined)); self.emitted_reasoning = true; self.end_ws.clear(); self.state = State::Think; } // ---- base `_emit_typed` for the remaining states ---- State::TextEnd => { if chunk.trim().is_empty() { self.end_ws.push_str(chunk); return; } out.push(Out::content(format!( "{}{}{}", tag::END_MESSAGE, self.end_ws, chunk ))); self.emitted_visible = true; self.end_ws.clear(); self.state = State::Text; } State::Idle => { out.push(Out::content(chunk)); if !chunk.trim().is_empty() { self.emitted_visible = true; self.state = State::Text; } } State::Text => { out.push(Out::content(chunk)); if !chunk.trim().is_empty() { self.emitted_visible = true; } } State::Header => { self.header_acc.push_str(chunk); // A real tool-name header is short and single-line; newlines or // an over-long run mean the model skipped content_text and is // writing plain text (#6620). if self.header_acc.contains('\n') || self.header_acc.chars().count() > MAX_HEADER_CHARS { let acc = std::mem::take(&mut self.header_acc); out.push(Out::content(acc)); self.emitted_visible = true; self.state = State::Text; } } State::ToolJson | State::ToolText => { self.tool_acc.push_str(chunk); } } } fn append_think(&mut self, chunk: &str) { if !chunk.is_empty() && self.think_acc.len() < MAX_THINK_ACC { let room = MAX_THINK_ACC - self.think_acc.len(); let take = room.min(chunk.len()); // slice on a char boundary let mut end = take; while end > 0 && !chunk.is_char_boundary(end) { end -= 1; } self.think_acc.push_str(&chunk[..end]); } } fn handle_tag(&mut self, tag: Tag, out: &mut Vec) { match tag { Tag::EndSampling | Tag::EndOfText => { self.close_channel(out); self.state = State::Idle; } Tag::EndMessage => match self.state { State::Think => { self.end_ws.clear(); self.state = State::ThinkEnd; } // Second end-message after a quoted one in thinking: absorb the // first, hold the second (#6675). State::ThinkEnd => { let held = format!("{}{}", tag::END_MESSAGE, self.end_ws); self.append_think(&held); // Stream the quoted end-message live (mirrors TextEnd below): // it is thinking text, not a channel end, and must not be lost. out.push(Out::reasoning(held)); self.emitted_reasoning = true; self.end_ws.clear(); } State::Text => { self.end_ws.clear(); self.state = State::TextEnd; } // Adjacent quoted + real end-message in visible text: emit the // first, hold the second (#6675). State::TextEnd => { out.push(Out::content(format!("{}{}", tag::END_MESSAGE, self.end_ws))); self.emitted_visible = true; self.end_ws.clear(); } _ => { self.close_channel(out); self.state = State::Idle; } }, Tag::MessageModel => { self.close_channel(out); self.state = State::Header; self.header_acc.clear(); } Tag::ContentThinking => { self.close_channel(out); self.header_acc.clear(); self.think_acc.clear(); self.state = State::Think; } Tag::ContentText => { if matches!(self.state, State::Think | State::ThinkEnd | State::TextEnd) { self.close_channel(out); } self.header_acc.clear(); self.state = State::Text; } Tag::ContentInvokeToolJson => { if matches!(self.state, State::Think | State::ThinkEnd | State::TextEnd) { self.close_channel(out); } self.state = State::ToolJson; self.tool_acc.clear(); } Tag::ContentInvokeToolText | Tag::ContentXml => { if matches!(self.state, State::Think | State::ThinkEnd | State::TextEnd) { self.close_channel(out); } self.state = State::ToolText; self.tool_acc.clear(); } } } fn close_channel(&mut self, out: &mut Vec) { // Snapshot to avoid holding a borrow of self across the mutation. let state = self.state; let header = std::mem::take(&mut self.header_acc); let tool = std::mem::take(&mut self.tool_acc); match state { State::ToolJson | State::ToolText => { let rendered = parse_tool_body(&header, &tool, state, false); if !rendered.is_empty() { if rendered.contains(tag::TOOL_CALL_OPEN) { self.calls += 1; } out.push(Out::content(rendered)); self.emitted_visible = true; } } State::Header => { if !header.is_empty() { out.push(Out::content(header)); self.emitted_visible = true; } } State::Think | State::ThinkEnd => { self.end_ws.clear(); } State::TextEnd => self.end_ws.clear(), _ => {} } } fn finish_into(&mut self, out: &mut Vec, reason: Option<&str>) { let state = self.state; let header = std::mem::take(&mut self.header_acc); let tool = std::mem::take(&mut self.tool_acc); let think = std::mem::take(&mut self.think_acc); match state { State::Header if !header.is_empty() => { out.push(Out::content(header)); self.emitted_visible = true; } State::ToolJson | State::ToolText if !tool.trim().is_empty() || !header.trim().is_empty() => { let rendered = parse_tool_body(&header, &tool, state, true); if !rendered.is_empty() { if rendered.contains(tag::TOOL_CALL_OPEN) { self.calls += 1; } out.push(Out::content(rendered)); self.emitted_visible = true; } } // #6682: budget expired inside thinking with no visible answer yet. // Thinking is streamed live by `emit`, so only surface the buffer if // it was somehow NOT streamed — never duplicate the live CoT (BUG-06). State::Think | State::ThinkEnd if reason == Some("length") && !self.emitted_visible && !self.emitted_reasoning && !think.trim().is_empty() => { out.push(Out::reasoning(think)); } _ => {} } self.end_ws.clear(); self.state = State::Idle; } } /// Serialize a call as OPEN newline json newline CLOSE, escaping the sequence /// " String { let mut obj = Map::new(); obj.insert("name".into(), Value::String(name.to_string())); obj.insert("arguments".into(), arguments); let payload = Value::Object(obj).to_string().replace(" Option<&str> { let start = raw.find('{')?; let end = raw.rfind('}')?; if end >= start { Some(&raw[start..=end]) } else { None } } /// Normalize an arguments value: a JSON string parses to an object (or a /// {"raw": ...} wrapper); a non-object becomes {"value": ...}. fn normalize_args(value: Value) -> Value { match value { Value::String(s) => match serde_json::from_str::(&s) { Ok(parsed) if parsed.is_object() => parsed, _ => Value::Object(Map::from_iter([("raw".to_string(), Value::String(s))])), }, v if v.is_object() => v, other => Value::Object(Map::from_iter([("value".to_string(), other)])), } } /// Render the body of a tool channel into a tool-call frame. /// /// Faithful for the JSON channel (the form Inkling emits: an object with a /// name and args/arguments). `tool_text` / `content_xml` bodies that are JSON /// or already carry a function marker are handled; the exotic XML attribute /// recovery is intentionally reduced to a raw payload (documented, not silent) /// since the OpenAI tool layer is not wired yet. fn parse_tool_body(header_name: &str, body: &str, kind: State, truncated: bool) -> String { let raw = body.trim(); let fallback = header_name.trim(); if kind == State::ToolJson { // parse `raw`, recovering a `{...}` object if the whole thing is dirty let obj = serde_json::from_str::(raw) .ok() .or_else(|| extract_object(raw).and_then(|s| serde_json::from_str::(s).ok())); if let Some(Value::Object(map)) = obj { let name = map .get("name") .and_then(|v| v.as_str()) .map(str::to_string) .filter(|s| !s.trim().is_empty()) .unwrap_or_else(|| fallback.to_string()); let args = if map.contains_key("args") { normalize_args(map["args"].clone()) } else if map.contains_key("arguments") { normalize_args(map["arguments"].clone()) } else if map.contains_key("name") { // args are the remaining keys let rest: Map = map .iter() .filter(|(k, _)| k.as_str() != "name") .map(|(k, v)| (k.clone(), v.clone())) .collect(); Value::Object(rest) } else { Value::Object(Map::new()) }; if !name.trim().is_empty() { return safe_json_call(name.trim(), args); } } if truncated && !raw.is_empty() && !raw.starts_with('{') { return raw.to_string(); } if !fallback.is_empty() { let args = if raw.is_empty() { Value::Object(Map::new()) } else { Value::Object(Map::from_iter([( "raw".to_string(), Value::String(raw.to_string()), )])) }; return safe_json_call(fallback, args); } return raw.to_string(); } // tool_text / content_xml if raw.starts_with('{') { if let Ok(Value::Object(map)) = serde_json::from_str::(raw) { let name = map .get("name") .and_then(|v| v.as_str()) .map(str::to_string) .unwrap_or_else(|| fallback.to_string()); if let Some(args) = map.get("args").or(map.get("arguments")) { if args.is_object() && !name.trim().is_empty() { return safe_json_call(name.trim(), args.clone()); } } } } if raw.contains("