diff --git a/crates/dim-agent-aimux/src/driver.rs b/crates/dim-agent-aimux/src/driver.rs index fddbec471e..7e88238f3e 100644 --- a/crates/dim-agent-aimux/src/driver.rs +++ b/crates/dim-agent-aimux/src/driver.rs @@ -950,6 +950,7 @@ impl ModelDriver for AimuxDriver { result, tool_names, protocol, + preset == Some(OPENAI_CODEX_PRESET), cancel, abort, self.generation.clone(), diff --git a/crates/dim-agent-aimux/src/stream.rs b/crates/dim-agent-aimux/src/stream.rs index 4d9d80059e..716c1269ea 100644 --- a/crates/dim-agent-aimux/src/stream.rs +++ b/crates/dim-agent-aimux/src/stream.rs @@ -1,4 +1,5 @@ mod content; +mod tags; use std::{ collections::{HashMap, HashSet}, @@ -19,8 +20,8 @@ use dim_agent_capabilities::host::{ ModelStream, }; use dim_agent_types::{ - FAILURE_CAUSE_CHARS, FAILURE_CAUSE_FRAMES, FAILURE_REASON_CHARS, MessagePart, ModelFailureKind, - ToolCall, Usage, one_line, + ContentMetadata, FAILURE_CAUSE_CHARS, FAILURE_CAUSE_FRAMES, FAILURE_REASON_CHARS, MessagePart, + ModelFailureKind, ToolCall, Usage, one_line, }; use futures_util::{StreamExt, future::poll_immediate}; use serde_json::Value; @@ -47,10 +48,18 @@ use crate::request::ToolNames; /// idle bound would let a trickle of bytes extend it. pub(crate) const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(300); +/// `scan_thinking_tags` converts the `` sections the managed +/// openai-codex provider writes into its text stream; every other provider +/// streams text verbatim. +#[expect( + clippy::too_many_arguments, + reason = "one parameter per stream or cancellation handle the conversion is assembled from" +)] pub(crate) fn convert( result: StreamResult, tool_names: ToolNames, protocol: ModelProtocol, + scan_thinking_tags: bool, cancel: CancellationToken, abort: AbortSignal, generation: CancellationToken, @@ -72,6 +81,10 @@ pub(crate) fn convert( let mut ended_inputs = HashSet::new(); let mut completed_calls = HashSet::new(); let mut thinking = HashMap::::new(); + // Per text block, the `` scan and the metadata held back + // from a converted part; both stay empty without the scan. + let mut tag_scans = HashMap::::new(); + let mut scan_metadata = HashMap::>::new(); let mut answered = false; let mut unfinished_call = None; let terminal = loop { @@ -171,6 +184,9 @@ pub(crate) fn convert( } StreamPart::TextStart { id, provider_metadata } => { block_active.insert((false, id.clone())); + if scan_thinking_tags { + tag_scans.insert(id.clone(), tags::TagScan::new()); + } if preserve { let metadata = match content::metadata(protocol, provider_metadata.as_ref()) { @@ -205,28 +221,80 @@ pub(crate) fn convert( } } StreamPart::TextDelta { id, delta, provider_metadata } => { - if preserve { - let metadata = + if scan_thinking_tags && tag_scans.contains_key(&id) { + let metadata = if preserve { match content::metadata(protocol, provider_metadata.as_ref()) { Ok(metadata) => metadata, Err(error) => break Some(Err(error)), - }; - let Some(part) = blocks - .get(&(false, id)) - .and_then(|index| parts.get_mut(*index)) - else { + } + } else { + None + }; + let Some(scan) = tag_scans.get_mut(&id) else { break Some(Err(error( AiMuxError::invalid_response_data("Missing text block"), &cancel, ))); }; - if let MessagePart::Text { text, .. } = part { - text.push_str(&delta); + let outputs = scan.feed(&delta); + let chunks = match apply_scan_outputs( + outputs, + &id, + preserve, + &mut parts, + &mut blocks, + &mut scan_metadata, + &mut answered, + ) { + Ok(chunks) => chunks, + Err(error) => break Some(Err(error)), + }; + for chunk in chunks { + yield Ok(chunk); } - content::update(part, metadata); + // While the scan holds the block inside the tag, the + // metadata folds into the trailing text part instead + // of the converted thinking part. + if preserve && let Some(incoming) = metadata { + if let Some(held) = scan_metadata.get_mut(&id) { + content::merge(held, incoming); + } else { + let Some(part) = blocks + .get(&(false, id.clone())) + .and_then(|index| parts.get_mut(*index)) + else { + break Some(Err(error( + AiMuxError::invalid_response_data("Missing text block"), + &cancel, + ))); + }; + content::update(part, Some(incoming)); + } + } + } else { + if preserve { + let metadata = + match content::metadata(protocol, provider_metadata.as_ref()) { + Ok(metadata) => metadata, + Err(error) => break Some(Err(error)), + }; + let Some(part) = blocks + .get(&(false, id)) + .and_then(|index| parts.get_mut(*index)) + else { + break Some(Err(error( + AiMuxError::invalid_response_data("Missing text block"), + &cancel, + ))); + }; + if let MessagePart::Text { text, .. } = part { + text.push_str(&delta); + } + content::update(part, metadata); + } + if !delta.trim().is_empty() { answered = true; } + if !delta.is_empty() { yield Ok(ModelChunk::Text(delta)); } } - if !delta.trim().is_empty() { answered = true; } - if !delta.is_empty() { yield Ok(ModelChunk::Text(delta)); } } StreamPart::ReasoningDelta { id, delta, provider_metadata } => { let Some(thought) = thinking.get_mut(&id) else { @@ -266,6 +334,27 @@ pub(crate) fn convert( _ => unreachable!(), }; block_active.remove(&(reasoning, id.clone())); + if !reasoning + && scan_thinking_tags + && let Some(mut scan) = tag_scans.remove(&id) + { + let outputs = scan.end(); + let chunks = match apply_scan_outputs( + outputs, + &id, + preserve, + &mut parts, + &mut blocks, + &mut scan_metadata, + &mut answered, + ) { + Ok(chunks) => chunks, + Err(error) => break Some(Err(error)), + }; + for chunk in chunks { + yield Ok(chunk); + } + } if preserve { let metadata = match content::metadata(protocol, provider_metadata.as_ref()) { @@ -486,6 +575,91 @@ pub(crate) fn convert( }) } +/// Applies one batch of scan decisions of the text block `id` to the reply's +/// parts and returns the chunks they stream, in order. `Opened` converts the +/// block's part in place: the scan never decides before the open tag +/// completed, so the part is still empty. `ThinkingEnd` ends that part and +/// starts the block's trailing text part, which receives what follows the +/// close tag and carries the continuation metadata the thinking part must +/// not keep. +fn apply_scan_outputs( + outputs: Vec, + id: &str, + preserve: bool, + parts: &mut Vec, + blocks: &mut HashMap<(bool, String), usize>, + scan_metadata: &mut HashMap>, + answered: &mut bool, +) -> Result, HostError> { + let mut chunks = Vec::new(); + for output in outputs { + match output { + tags::ScanOutput::Opened => { + scan_metadata.entry(id.to_owned()).or_insert(None); + if preserve { + let Some(part) = blocks + .get(&(false, id.to_owned())) + .and_then(|index| parts.get_mut(*index)) + else { + return Err(HostError::failed("Missing scanned text block")); + }; + if let MessagePart::Text { + provider_metadata, .. + } = part + && let Some(held) = scan_metadata.get_mut(id) + { + *held = provider_metadata.take(); + } + *part = MessagePart::Thinking { + thinking: String::new(), + start_time: None, + end_time: None, + provider_metadata: None, + }; + } + } + tags::ScanOutput::Thinking(delta) => { + if preserve + && let Some(index) = blocks.get(&(false, id.to_owned())) + && let Some(MessagePart::Thinking { thinking, .. }) = parts.get_mut(*index) + { + thinking.push_str(&delta); + } + if !delta.trim().is_empty() { + *answered = true; + } + chunks.push(ModelChunk::Thinking(delta)); + } + tags::ScanOutput::ThinkingEnd(total) => { + if preserve { + let metadata = scan_metadata.remove(id).unwrap_or(None); + blocks.insert((false, id.to_owned()), parts.len()); + parts.push(MessagePart::Text { + text: String::new(), + start_time: None, + end_time: None, + provider_metadata: metadata, + }); + } + chunks.push(ModelChunk::ThinkingEnd { thinking: total }); + } + tags::ScanOutput::Text(text) => { + if preserve + && let Some(index) = blocks.get(&(false, id.to_owned())) + && let Some(MessagePart::Text { text: part, .. }) = parts.get_mut(*index) + { + part.push_str(&text); + } + if !text.trim().is_empty() { + *answered = true; + } + chunks.push(ModelChunk::Text(text)); + } + } + } + Ok(chunks) +} + /// The metadata of a reasoning block. A Bedrock reasoning block without a /// signature or redacted payload is still a Bedrock block, so it is stored as /// an unsigned one; the converter leaves such a block out of a replayed diff --git a/crates/dim-agent-aimux/src/stream/content.rs b/crates/dim-agent-aimux/src/stream/content.rs index e280508aac..06b85023eb 100644 --- a/crates/dim-agent-aimux/src/stream/content.rs +++ b/crates/dim-agent-aimux/src/stream/content.rs @@ -125,27 +125,34 @@ pub(super) fn update(part: &mut MessagePart, incoming: Option) } => provider_metadata, _ => unreachable!(), }; - if let Some(mut incoming) = incoming { - if let ( - Some(ContentMetadata::OpenaiResponses { - item_id: old_id, - encrypted_content: old_encrypted, - summary_index: old_index, - phase: old_phase, - }), - ContentMetadata::OpenaiResponses { - item_id, - encrypted_content, - summary_index, - phase, - }, - ) = (target.as_ref(), &mut incoming) - && old_id == item_id - { - *encrypted_content = encrypted_content.take().or_else(|| old_encrypted.clone()); - *summary_index = summary_index.or(*old_index); - *phase = phase.take().or_else(|| old_phase.clone()); - } - *target = Some(incoming); + if let Some(incoming) = incoming { + merge(target, incoming); + } +} + +/// Folds one metadata event into the accumulated continuation fields. Later +/// events replace the value, except within one OpenAI Responses item, where a +/// field the event leaves out keeps what the item already carried. +pub(super) fn merge(target: &mut Option, mut incoming: ContentMetadata) { + if let ( + Some(ContentMetadata::OpenaiResponses { + item_id: old_id, + encrypted_content: old_encrypted, + summary_index: old_index, + phase: old_phase, + }), + ContentMetadata::OpenaiResponses { + item_id, + encrypted_content, + summary_index, + phase, + }, + ) = (target.as_ref(), &mut incoming) + && old_id == item_id + { + *encrypted_content = encrypted_content.take().or_else(|| old_encrypted.clone()); + *summary_index = summary_index.or(*old_index); + *phase = phase.take().or_else(|| old_phase.clone()); } + *target = Some(incoming); } diff --git a/crates/dim-agent-aimux/src/stream/tags.rs b/crates/dim-agent-aimux/src/stream/tags.rs new file mode 100644 index 0000000000..aa85b71055 --- /dev/null +++ b/crates/dim-agent-aimux/src/stream/tags.rs @@ -0,0 +1,212 @@ +//! The `` compatibility scan of one text block. +//! +//! The managed openai-codex provider writes its reasoning into the text +//! stream itself, wrapped in ``…``. Only a tag that opens +//! the block converts: the first non-whitespace content of the block must be +//! the open tag, which the model emits as literal text. A tag anywhere later +//! is the model talking about the tag and stays text. + +/// The open tag of a codex reasoning section inside a text block. +const OPEN: &str = ""; +/// The close tag of a codex reasoning section inside a text block. +const CLOSE: &str = ""; + +/// What one scan step decided, in the order it must reach the stream. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum ScanOutput { + /// Text that is not a tag: append it to the block's part and stream it. + Text(String), + /// Thinking content: append it to the converted part and stream it. + Thinking(String), + /// The block opened with the tag: convert its part to thinking. + Opened, + /// The thinking section is complete, at the close tag or the block end, + /// with its whole content. + ThinkingEnd(String), +} + +enum Scan { + /// Nothing decided yet; everything so far is buffered because the open + /// tag may still complete across deltas. + Undecided(String), + /// Inside the tag; `held` is the tail that may start a close tag. + Thinking(String), + /// Decided: the block is plain text (no tag, or the tag already closed). + Text, +} + +/// The scan state of one text block. The machine is byte-oriented over +/// `String`s: both tags are ASCII, so a match never falls inside a multi-byte +/// character and every split point is a character boundary. +pub(super) struct TagScan { + scan: Scan, + total: String, +} + +impl TagScan { + pub(super) fn new() -> Self { + Self { + scan: Scan::Undecided(String::new()), + total: String::new(), + } + } + + /// Feeds one delta. The outputs are in stream order; `Opened` precedes + /// the first `Thinking` it belongs to, and `ThinkingEnd` precedes any + /// text that follows the close tag in the same delta. + pub(super) fn feed(&mut self, delta: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = delta.to_owned(); + loop { + match &mut self.scan { + Scan::Undecided(pending) => { + pending.push_str(&rest); + rest.clear(); + let trimmed = pending.trim_start(); + let after = trimmed.strip_prefix(OPEN).map(str::to_owned); + if let Some(after) = after { + // The whitespace before the tag is part of the tag's + // formatting, not text: keeping it would put a + // whitespace text block before the thinking. + self.scan = Scan::Thinking(String::new()); + out.push(ScanOutput::Opened); + rest = after; + if rest.is_empty() { + return out; + } + continue; + } + if OPEN.starts_with(trimmed) { + // Nothing yet, or a strict prefix of the open tag; the + // decision waits for more of the block. + return out; + } + // Not the tag: everything buffered so far is text, + // whitespace included, and the block is text from here. + let text = std::mem::take(pending); + self.scan = Scan::Text; + if !text.is_empty() { + out.push(ScanOutput::Text(text)); + } + return out; + } + Scan::Thinking(held) => { + held.push_str(&rest); + rest.clear(); + if let Some(pos) = held.find(CLOSE) { + let before = held[..pos].to_owned(); + let after = held[pos + CLOSE.len()..].to_owned(); + if !before.is_empty() { + self.total.push_str(&before); + out.push(ScanOutput::Thinking(before)); + } + let total = std::mem::take(&mut self.total); + out.push(ScanOutput::ThinkingEnd(total)); + self.scan = Scan::Text; + rest = after; + if rest.is_empty() { + return out; + } + continue; + } + // Hold back the longest suffix that may still complete + // into the close tag; everything before it is thinking. + let hold = close_prefix_suffix(held); + let emit = held[..held.len() - hold].to_owned(); + *held = held[held.len() - hold..].to_owned(); + if !emit.is_empty() { + self.total.push_str(&emit); + out.push(ScanOutput::Thinking(emit)); + } + return out; + } + Scan::Text => { + if !rest.is_empty() { + out.push(ScanOutput::Text(std::mem::take(&mut rest))); + } + return out; + } + } + } + } + + /// The block ended. A decision never reached is text; an unclosed tag + /// keeps its content as thinking. + pub(super) fn end(&mut self) -> Vec { + let mut out = Vec::new(); + match &mut self.scan { + Scan::Undecided(pending) => { + let text = std::mem::take(pending); + self.scan = Scan::Text; + if !text.is_empty() { + out.push(ScanOutput::Text(text)); + } + } + Scan::Thinking(held) => { + let rest = std::mem::take(held); + if !rest.is_empty() { + self.total.push_str(&rest); + out.push(ScanOutput::Thinking(rest)); + } + let total = std::mem::take(&mut self.total); + out.push(ScanOutput::ThinkingEnd(total)); + self.scan = Scan::Text; + } + Scan::Text => {} + } + out + } +} + +/// The length of the longest suffix of `held` that is a strict prefix of the +/// close tag, which the next delta may complete. +fn close_prefix_suffix(held: &str) -> usize { + let max = held.len().min(CLOSE.len() - 1); + (1..=max) + .rev() + .find(|&len| { + // The suffix starts with '<', so a match never begins inside a + // multi-byte character; other lengths are not candidates. + held.is_char_boundary(held.len() - len) && CLOSE.starts_with(&held[held.len() - len..]) + }) + .unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scan(parts: &[&str]) -> Vec { + let mut scan = TagScan::new(); + let mut out = Vec::new(); + for part in parts { + out.extend(scan.feed(part)); + } + out.extend(scan.end()); + out + } + + #[test] + fn the_close_tag_never_splits_inside_a_character() { + assert_eq!(close_prefix_suffix("héllo"), 0); + assert_eq!(close_prefix_suffix("plain"), 0); + } + + #[test] + fn machine_examples() { + // The byte check above pins the boundary arithmetic; the stream-level + // tests in stream/tests.rs cover the machine through convert, where + // its outputs have their meaning. + assert_eq!( + scan(&["thoughtanswer"]), + vec![ + ScanOutput::Opened, + ScanOutput::Thinking("thought".into()), + ScanOutput::ThinkingEnd("thought".into()), + ScanOutput::Text("answer".into()), + ] + ); + } +} diff --git a/crates/dim-agent-aimux/src/stream/tests.rs b/crates/dim-agent-aimux/src/stream/tests.rs index 456de95a38..82132d13ec 100644 --- a/crates/dim-agent-aimux/src/stream/tests.rs +++ b/crates/dim-agent-aimux/src/stream/tests.rs @@ -74,6 +74,7 @@ fn fixture_with( result, ToolNames::default(), ModelProtocol::OpenaiChat, + false, cancel.clone(), abort.clone(), CancellationToken::new(), @@ -119,6 +120,7 @@ fn feedable() -> (ModelStream, Feed) { result, ToolNames::default(), ModelProtocol::OpenaiChat, + false, CancellationToken::new(), AbortSignal::new(), CancellationToken::new(), @@ -1041,6 +1043,7 @@ async fn cancelling_a_cut_tool_call_wins_a_ready_part() { result, ToolNames::default(), ModelProtocol::OpenaiChat, + false, cancel, abort.clone(), CancellationToken::new(), @@ -1153,6 +1156,7 @@ async fn a_strict_responses_stream_delivers_a_cut_call_next_to_its_filter() { }, ToolNames::default(), ModelProtocol::OpenaiResponses, + false, CancellationToken::new(), AbortSignal::new(), CancellationToken::new(), @@ -2074,3 +2078,501 @@ fn a_string_code_is_a_status_only_when_it_is_exactly_three_digits_in_range() { } ); } + +/// A scan fixture: the codex conversion over the OpenAI Responses protocol, +/// which is the only pairing the driver ever enables it for. +fn scan_fixture( + parts: Vec>, +) -> (ModelStream, CancellationToken, AbortSignal, Arc) { + let dropped = Arc::new(AtomicBool::new(false)); + let result = StreamResult { + stream: Box::pin(NativeStream { + parts: parts.into(), + dropped: dropped.clone(), + end_when_empty: true, + }), + request: None, + response: None, + }; + let cancel = CancellationToken::new(); + let abort = AbortSignal::new(); + let stream = convert( + result, + ToolNames::default(), + ModelProtocol::OpenaiResponses, + true, + cancel.clone(), + abort.clone(), + CancellationToken::new(), + tokio_util::task::TaskTracker::new().token(), + ); + (stream, cancel, abort, dropped) +} + +/// The same parts with the scan off: what every other provider streams. +fn unscanned_responses_fixture( + parts: Vec>, +) -> (ModelStream, CancellationToken, AbortSignal, Arc) { + let dropped = Arc::new(AtomicBool::new(false)); + let result = StreamResult { + stream: Box::pin(NativeStream { + parts: parts.into(), + dropped: dropped.clone(), + end_when_empty: true, + }), + request: None, + response: None, + }; + let cancel = CancellationToken::new(); + let abort = AbortSignal::new(); + let stream = convert( + result, + ToolNames::default(), + ModelProtocol::OpenaiResponses, + false, + cancel.clone(), + abort.clone(), + CancellationToken::new(), + tokio_util::task::TaskTracker::new().token(), + ); + (stream, cancel, abort, dropped) +} + +fn text_block(id: &str, deltas: &[&str]) -> Vec> { + let mut parts = vec![ + Ok(start()), + Ok(StreamPart::TextStart { + id: id.into(), + provider_metadata: None, + }), + ]; + for delta in deltas { + parts.push(Ok(StreamPart::TextDelta { + id: id.into(), + delta: (*delta).into(), + provider_metadata: None, + })); + } + parts.push(Ok(StreamPart::TextEnd { + id: id.into(), + provider_metadata: None, + })); + parts.push(Ok(finish( + FinishReasonUnified::Stop, + NativeUsage::default(), + ))); + parts +} + +/// The stream's chunks reduced to what the scan decides: thinking and text +/// payloads, both ends, and the terminal. +fn reduced(chunks: &[Result]) -> Vec { + chunks + .iter() + .filter_map(|chunk| match chunk { + Ok(ModelChunk::Text(text)) => Some(format!("text:{text:?}")), + Ok(ModelChunk::TextEnd) => Some("text-end".into()), + Ok(ModelChunk::Thinking(thinking)) => Some(format!("thinking:{thinking:?}")), + Ok(ModelChunk::ThinkingEnd { thinking }) => Some(format!("thinking-end:{thinking:?}")), + Ok(ModelChunk::MessageStop { reason, .. }) => Some(format!("stop:{reason:?}")), + Err(error) => Some(format!("error:{error}")), + _ => None, + }) + .collect() +} + +/// The reply's committed parts, or a test failure naming what ended instead. +fn committed(chunks: &[Result], case: &str) -> Vec { + chunks + .iter() + .find_map(|chunk| match chunk { + Ok(ModelChunk::Content(parts)) => Some(parts.clone()), + _ => None, + }) + .unwrap_or_else(|| { + panic!( + "{case}: the reply committed no content: {}", + reduced(chunks).join(" ") + ) + }) +} + +async fn scan_chunks( + parts: Vec>, +) -> Vec> { + let (stream, _, _, _) = scan_fixture(parts); + collect_or_stall(stream, "scan fixture").await +} + +#[tokio::test] +async fn thinking_tags_convert_a_codex_block_into_thinking_then_text() { + let chunks = scan_chunks(text_block( + "msg", + &["\nthe plan\n\n\nthe answer"], + )) + .await; + assert_eq!( + reduced(&chunks), + [ + "thinking:\"\\nthe plan\\n\"", + "thinking-end:\"\\nthe plan\\n\"", + "text:\"\\n\\nthe answer\"", + "text-end", + "stop:EndTurn", + ] + ); + let parts = committed(&chunks, "converted block"); + assert_eq!(parts.len(), 2, "{parts:?}"); + let MessagePart::Thinking { + thinking, + provider_metadata, + .. + } = &parts[0] + else { + panic!("the thinking section is not a thinking part: {parts:?}") + }; + assert_eq!(thinking, "\nthe plan\n"); + assert_eq!( + *provider_metadata, None, + "converted thinking must carry no continuation metadata" + ); + let MessagePart::Text { text, .. } = &parts[1] else { + panic!("the answer is not a text part: {parts:?}") + }; + assert_eq!(text, "\n\nthe answer"); +} + +#[tokio::test] +async fn thinking_tags_split_across_deltas_convert_identically() { + for deltas in [ + vec!["plananswer"], + vec![ + "<", "t", "h", "i", "n", "k", "i", "n", "g", ">", "p", "l", "a", "n", "<", "/", "t", + "h", "i", "n", "k", "i", "n", "g", ">", "a", "n", "s", "w", "e", "r", + ], + vec!["plananswer"], + ] { + let chunks = scan_chunks(text_block("msg", &deltas)).await; + // Deltas fragment the thinking and text emissions, so only the + // conversion's shape and content are identical across splittings. + let mut kinds: Vec<_> = reduced(&chunks) + .iter() + .filter(|event| !event.starts_with("thinking:\"\"") && !event.starts_with("text:\"\"")) + .map(|event| event.split(':').next().unwrap().to_owned()) + .collect(); + kinds.dedup(); + assert_eq!( + kinds, + ["thinking", "thinking-end", "text", "text-end", "stop"], + "deltas {deltas:?}: {}", + reduced(&chunks).join(" ") + ); + let parts = committed(&chunks, "split tags"); + assert!( + matches!(&parts[0], MessagePart::Thinking { thinking, .. } if thinking == "plan"), + "deltas {deltas:?}: {parts:?}" + ); + assert!( + matches!(&parts[1], MessagePart::Text { text, .. } if text == "answer"), + "deltas {deltas:?}: {parts:?}" + ); + } +} + +#[tokio::test] +async fn thinking_tags_inside_text_stay_verbatim() { + for (case, deltas) in [ + ("inline", vec!["use plan carefully"]), + ( + "mid-block", + vec!["first half", " then not a tag"], + ), + ( + "inside a code fence", + vec!["```\nexample\n```"], + ), + ] { + let chunks = scan_chunks(text_block("msg", &deltas)).await; + assert!( + reduced(&chunks) + .iter() + .all(|event| !event.starts_with("thinking")), + "{case}: a tag inside the text converted: {}", + reduced(&chunks).join(" ") + ); + let parts = committed(&chunks, case); + assert_eq!(parts.len(), 1, "{case}: {parts:?}"); + let joined: String = deltas.concat(); + assert!( + matches!(&parts[0], MessagePart::Text { text, .. } if *text == joined), + "{case}: buffered bytes were lost or repeated: {parts:?} vs {joined:?}" + ); + } +} + +#[tokio::test] +async fn thinking_tags_almost_openings_are_buffered_verbatim() { + for (case, deltas, expected) in [ + ( + "no closing bracket", + vec!["not a tag"], + vec!["text:\"< thinking>not a tag\"", "text-end", "stop:EndTurn"], + ), + ( + "longer tag name", + vec!["rest"], + vec![ + "text:\"rest\"", + "text-end", + "stop:EndTurn", + ], + ), + ( + "short tag name", + vec!["rest"], + vec!["text:\"rest\"", "text-end", "stop:EndTurn"], + ), + ] { + let chunks = scan_chunks(text_block("msg", &deltas)).await; + assert_eq!( + reduced(&chunks), + expected, + "{case}: buffered bytes were lost or repeated" + ); + } +} + +#[tokio::test] +async fn thinking_tags_leading_whitespace_before_the_open_tag() { + let chunks = scan_chunks(text_block("msg", &["\n plandone"])).await; + assert_eq!( + reduced(&chunks), + [ + "thinking:\"plan\"", + "thinking-end:\"plan\"", + "text:\"done\"", + "text-end", + "stop:EndTurn", + ] + ); + let parts = committed(&chunks, "leading whitespace"); + assert!( + matches!(&parts[0], MessagePart::Thinking { thinking, .. } if thinking == "plan"), + "the whitespace before the tag is not text: {parts:?}" + ); +} + +#[tokio::test] +async fn thinking_tags_close_followed_by_text_on_the_same_line() { + let chunks = scan_chunks(text_block("msg", &["planright after"])).await; + assert_eq!( + reduced(&chunks), + [ + "thinking:\"plan\"", + "thinking-end:\"plan\"", + "text:\"right after\"", + "text-end", + "stop:EndTurn", + ] + ); +} + +#[tokio::test] +async fn thinking_tags_unclosed_at_the_block_end_stay_thinking() { + let chunks = scan_chunks(text_block("msg", &["never closedhiddendone"), + ] + .iter() + .enumerate() + { + if index == 1 { + // The second block of a turn usually follows a tool call, as when + // the model answers after its calls: the blocks scan independently. + parts.push(Ok(tool("{}"))); + } + parts.push(Ok(StreamPart::TextStart { + id: (*id).into(), + provider_metadata: None, + })); + parts.push(Ok(StreamPart::TextDelta { + id: (*id).into(), + delta: (*delta).into(), + provider_metadata: None, + })); + parts.push(Ok(StreamPart::TextEnd { + id: (*id).into(), + provider_metadata: None, + })); + } + parts.push(Ok(finish( + FinishReasonUnified::Stop, + NativeUsage::default(), + ))); + let chunks = scan_chunks(parts).await; + assert_eq!( + reduced(&chunks), + [ + "text:\"plain answer\"", + "text-end", + "thinking:\"hidden\"", + "thinking-end:\"hidden\"", + "text:\"done\"", + "text-end", + "stop:EndTurn", + ] + ); + let parts = committed(&chunks, "multiple blocks"); + assert!( + matches!(&parts[0], MessagePart::Text { text, .. } if text == "plain answer"), + "the first block must not be scanned into the second: {parts:?}" + ); + assert!( + matches!(&parts[1], MessagePart::ToolUse { .. }), + "{parts:?}" + ); + assert!( + matches!(&parts[2], MessagePart::Thinking { .. }), + "{parts:?}" + ); + assert!( + matches!(&parts[3], MessagePart::Text { text, .. } if text == "done"), + "{parts:?}" + ); +} + +#[tokio::test] +async fn thinking_tags_only_reply_answers_the_turn() { + let chunks = scan_chunks(text_block("msg", &["everything"])).await; + assert_eq!( + reduced(&chunks), + [ + "thinking:\"everything\"", + "thinking-end:\"everything\"", + "text-end", + "stop:EndTurn", + ] + ); +} + +#[tokio::test] +async fn thinking_tags_empty_section_answers_nothing() { + let chunks = scan_chunks(text_block("msg", &[""])).await; + let events = reduced(&chunks); + assert_eq!( + events[..2], + ["thinking-end:\"\"", "text-end"], + "{}", + events.join(" ") + ); + assert!( + events + .iter() + .any(|event| event.starts_with("error:") && event.contains("no text and no tool call")), + "an empty tag alone still answers nothing: {}", + events.join(" ") + ); +} + +#[tokio::test] +async fn thinking_tags_other_providers_stream_them_verbatim() { + let chunks = { + let (stream, _, _, _) = + unscanned_responses_fixture(text_block("msg", &["plananswer"])); + collect_or_stall(stream, "unscanned fixture").await + }; + assert_eq!( + reduced(&chunks), + [ + "text:\"plananswer\"", + "text-end", + "stop:EndTurn", + ] + ); +} + +#[tokio::test] +async fn thinking_tags_continuation_metadata_reaches_only_the_text_part() { + let metadata = || { + aimux_core::shared::provider_namespace( + "openai", + json!({"itemId": "msg_1", "phase": "final_answer"}), + ) + .unwrap() + }; + let (stream, _, _, _) = scan_fixture(vec![ + Ok(start()), + Ok(StreamPart::TextStart { + id: "msg".into(), + provider_metadata: Some(metadata()), + }), + Ok(StreamPart::TextDelta { + id: "msg".into(), + delta: "plananswer".into(), + provider_metadata: Some(metadata()), + }), + Ok(StreamPart::TextEnd { + id: "msg".into(), + provider_metadata: Some(metadata()), + }), + Ok(finish(FinishReasonUnified::Stop, NativeUsage::default())), + ]); + let chunks = collect_or_stall(stream, "metadata fixture").await; + let parts = committed(&chunks, "metadata"); + let MessagePart::Thinking { + provider_metadata, .. + } = &parts[0] + else { + panic!("{parts:?}") + }; + assert_eq!( + *provider_metadata, None, + "the converted thinking must not carry the item reference: {parts:?}" + ); + let MessagePart::Text { + provider_metadata: text_metadata, + .. + } = &parts[1] + else { + panic!("{parts:?}") + }; + assert!( + matches!( + text_metadata, + Some(dim_agent_types::ContentMetadata::OpenaiResponses { item_id, phase, .. }) + if item_id == "msg_1" && phase.as_deref() == Some("final_answer") + ), + "the trailing text part keeps the item's continuation metadata: {text_metadata:?}" + ); +} diff --git a/crates/dim-agent-aimux/tests/model_flow.rs b/crates/dim-agent-aimux/tests/model_flow.rs index fd52b7b7e2..c84c5a4dc6 100644 --- a/crates/dim-agent-aimux/tests/model_flow.rs +++ b/crates/dim-agent-aimux/tests/model_flow.rs @@ -125,6 +125,12 @@ async fn respond_responses( json!({"input_tokens":3,"output_tokens":6,"total_tokens":9, "output_tokens_details":{"reasoning_tokens":0}}) }; + if let Some(scenario) = requested_text(&request).strip_prefix("tags:") { + return Response::builder() + .header("content-type", "text/event-stream") + .body(Body::from(responses_tag_script(scenario, usage))) + .unwrap(); + } let body = sse_value(&[ json!({"type":"response.output_item.added","output_index":0, "item":{"type":"message","id":"msg-1","role":"assistant","content":[]}}), @@ -140,6 +146,37 @@ async fn respond_responses( .unwrap() } +/// One Responses text reply of streamed deltas, in the SSE framing the real +/// provider sends. +fn responses_text_events(deltas: &[&str], usage: Value) -> String { + let mut events = vec![json!({"type":"response.output_item.added","output_index":0, + "item":{"type":"message","id":"msg-1","role":"assistant","content":[]}})]; + for delta in deltas { + events.push( + json!({"type":"response.output_text.delta","item_id":"msg-1","output_index":0,"delta":delta}), + ); + } + events.push(json!({"type":"response.output_item.done","output_index":0, + "item":{"type":"message","id":"msg-1","role":"assistant", + "content":[{"type":"output_text","text":deltas.concat()}]}})); + events.push( + json!({"type":"response.completed","response":{"id":"resp-1","status":"completed","usage":usage}}), + ); + sse_value(&events) +} + +/// The replies of the `` scenarios: the close tag of `convert` is +/// split across two deltas, as the provider fragments them on the wire. +fn responses_tag_script(scenario: &str, usage: Value) -> String { + let deltas: &[&str] = match scenario { + "convert" => &["\nINNER-THOUGHT\n\n\nFINAL-ANSWER"], + "inline" => &["inline not a tag INLINE-ANSWER"], + "only" => &["EVERYTHING-INSIDE"], + _ => panic!("unknown tag scenario: {scenario}"), + }; + responses_text_events(deltas, usage) +} + /// Gemini replies in its own SSE framing: `thoughtsTokenCount` appears only /// for the prompt that asks to think. async fn respond_gemini(State(endpoint): State, Json(request): Json) -> Response { @@ -1836,5 +1873,326 @@ async fn a_wait_for_response_headers_past_the_idle_allowance_fails_as_a_network_ root.shutdown().await.unwrap(); } +/// The managed codex account's connection for the test server, answered +/// through the process's connection port. The development model +/// configuration cannot express this pairing on purpose: `compatible.preset` +/// requires openai-compatible (models.rs) while the driver requires +/// openai-codex connections to speak the Responses protocol (driver.rs), so +/// only the managed account path carries the preset in production. +struct CodexConnection { + base_url: String, + generation: CancellationToken, +} +impl ResolveModalityConnection for CodexConnection { + fn resolve_for_modality( + &self, + target: ModalityTarget, + _cancel: CancellationToken, + ) -> HostFuture<'_, ModalityConnection> { + Box::pin(async move { Err(undeclared_modality_operation(&target.operation)) }) + } +} +impl ResolveModelConnection for CodexConnection { + fn resolve( + &self, + _request: Arc, + cancel: CancellationToken, + ) -> HostFuture<'_, ResolvedModelConnection> { + Box::pin(async move { + if self.generation.is_cancelled() { + return Err(HostError::classified( + HostErrorKind::OwnerClosed, + "Model catalog owner is closed", + )); + } + if cancel.is_cancelled() { + return Err(HostError::Cancelled( + "Connection resolution cancelled".into(), + )); + } + Ok(ResolvedModelConnection { + failure_policy: None, + recovery: None, + connection: ModelConnection::Http(HttpModelConnection { + protocol: ModelProtocol::OpenaiResponses, + base_url: self.base_url.clone(), + network: Default::default(), + headers: Default::default(), + bearer: Some("codex-test-token".into()), + api_key: None, + preset: Some("openai-codex".into()), + }), + }) + }) + } +} + +/// The same process services ConfiguredModelsPlugin provides, with the +/// managed account's connection behind the shared resolver. +struct CodexModelsPlugin { + base_url: String, + models: Arc, +} +impl rutis::Plugin for CodexModelsPlugin { + type Deps = (Arc,); + fn name(&self) -> &str { + "CodexModels" + } + async fn apply(&self, ctx: &rutis::Ctx, _: Self::Deps) -> rutis::Result { + ctx.provide_as::(self.models.clone())?; + let resolver = Arc::new(CodexConnection { + base_url: self.base_url.clone(), + generation: ctx.cancellation_token(), + }); + ctx.provide(ProviderConnectionResolver(resolver.clone()))?; + let selection = resolver.clone(); + dim_agent_capabilities::host::provide_model_selection( + ctx, + &ModelSelectionHost::new(Arc::new(move |explicit, _cwd, _cancel| { + let generation = selection.generation.clone(); + Box::pin(async move { + if generation.is_cancelled() { + return Err(HostError::classified( + HostErrorKind::OwnerClosed, + "Model catalog owner is closed", + )); + } + let id = explicit.unwrap_or_else(|| ModelId { + provider_id: "local".into(), + model_id: "test-model".into(), + }); + Ok(ModelSelection { + provider_id: id.provider_id, + model_id: id.model_id, + capability_snapshot: None, + config: Some(ModelConfig { + max_tokens: Some(4096.), + temperature: Some(0.), + ..Default::default() + }), + metadata: Some(RequestMetadata { + extensions: serde_json::Map::from_iter([( + "providerProtocol".into(), + json!("openai-responses"), + )]), + ..Default::default() + }), + }) + }) + })), + )?; + ctx.provide(ModalityConnectionHost(resolver.clone()))?; + dim_agent_capabilities::host::provide_selectable_models( + ctx, + &SelectableModelsHost::new( + Arc::new(move |_cancel| Box::pin(async move { Ok(Vec::new()) })), + Arc::new(move |_cancel| Box::pin(async move { Ok(Vec::new()) })), + ), + )?; + Ok(()) + } +} + +/// A Session whose model requests resolve to the managed codex account's +/// connection against the test server. +async fn codex_session(server: &TestServer) -> (MinimalHost, dim_agent_runtime::Session) { + let models = Arc::new(AimuxModels::from_config(configuration(&server.url)).unwrap()); + let mut builder = builder(models.clone(), Arc::new(MockTools)); + builder + .plugin(|_| Ok(Box::new(AimuxPlugin::default()))) + .plugin({ + let url = server.url.clone(); + move |_| { + Ok(Box::new(CodexModelsPlugin { + base_url: url.clone(), + models: models.clone(), + })) + } + }); + let agent = MinimalHost::start(&builder).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); + (agent, session) +} + +/// The flattened thinking and text deltas of the main branch, in order. +async fn thinking_text_flow(session: &dim_agent_runtime::Session) -> Vec<(String, String)> { + chain_events(session, "main", ..) + .await + .unwrap() + .iter() + .filter_map(|event| match &event.kind { + EventKind::Thinking(data) => Some(("thinking".into(), data.delta.clone())), + EventKind::Text(data) => Some(("text".into(), data.delta.clone())), + _ => None, + }) + .collect() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn codex_thinking_tags_leave_text_as_thinking_and_the_next_request() { + tokio::time::timeout(Duration::from_secs(15), async { + let server = TestServer::start().await; + let (agent, session) = codex_session(&server).await; + session + .submit("tags:convert".into(), InputMode::Queue, "main") + .await + .unwrap(); + session.idle("main").await.unwrap(); + let flow = thinking_text_flow(&session).await; + let thinking: String = flow + .iter() + .filter(|(kind, _)| kind == "thinking") + .map(|(_, delta)| delta.clone()) + .collect(); + let text: String = flow + .iter() + .filter(|(kind, _)| kind == "text") + .map(|(_, delta)| delta.clone()) + .collect(); + assert!( + thinking.contains("INNER-THOUGHT"), + "the tag's content streams as thinking: {flow:?}" + ); + assert!( + !thinking.contains(" Some(data.delta.clone()), + _ => None, + }) + .collect(); + assert!( + inline.contains("not a tag INLINE-ANSWER"), + "a tag inside the text is not converted at this level either: {inline}" + ); + agent.close().await.unwrap(); + server.close().await; + }) + .await + .unwrap(); +} + +/// The same scripted reply over a connection without the preset streams the +/// tags as the text they are for every other provider. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn responses_without_the_codex_preset_streams_tags_verbatim() { + tokio::time::timeout(Duration::from_secs(15), async { + let server = TestServer::start().await; + let (agent, session) = protocol_session(&server, "openai-responses").await; + session + .submit("tags:convert".into(), InputMode::Queue, "main") + .await + .unwrap(); + session.idle("main").await.unwrap(); + let flow = thinking_text_flow(&session).await; + assert!( + flow.iter().all(|(kind, _)| kind == "text"), + "without the preset nothing is thinking: {flow:?}" + ); + let text: String = flow.iter().map(|(_, delta)| delta.clone()).collect(); + assert!( + text.contains("") && text.contains("INNER-THOUGHT"), + "the reply streams verbatim: {flow:?}" + ); + agent.close().await.unwrap(); + server.close().await; + }) + .await + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn codex_thinking_tags_only_reply_completes_the_turn() { + tokio::time::timeout(Duration::from_secs(15), async { + let server = TestServer::start().await; + let (agent, session) = codex_session(&server).await; + session + .submit("tags:only".into(), InputMode::Queue, "main") + .await + .unwrap(); + session.idle("main").await.unwrap(); + let events = chain_events(&session, "main", ..).await.unwrap(); + assert!( + events.iter().any(|event| matches!( + &event.kind, + EventKind::Thinking(data) if data.delta.contains("EVERYTHING-INSIDE") + )), + "the whole reply is its thinking: {events:?}" + ); + assert!( + matches!( + events + .iter() + .rfind(|event| matches!(event.kind, EventKind::TurnEnd(_))) + .unwrap() + .kind, + EventKind::TurnEnd(TurnEndData { + outcome: TurnOutcome::Completed { .. }, + .. + }) + ), + "a reply of nothing but its tag completes instead of retrying empty: {events:?}" + ); + assert_eq!( + server.endpoint.requests.lock().unwrap().len(), + 1, + "no empty-reply retry issued another request" + ); + agent.close().await.unwrap(); + server.close().await; + }) + .await + .unwrap(); +} + #[path = "model_flow/native.rs"] mod native;