Support configurable realtime BEM channel prefixes (#34816)

## What changed

- Route realtime V3 `bemTags` handoffs using `[ANALYSIS]`, `[COMMENTARY]`, and `[FINAL]` prefixes by default.
- Add `codexResponseHandoffChannelPrefixes` to realtime start requests so clients can replace the accepted prefixes for individual channels. Each channel may accept multiple prefixes, and omitted channels retain their defaults.
- Apply the configured prefixes to both complete and streamed handoff messages, without treating empty prefixes as matches.

## Testing

- Cover request deserialization, default and custom routing, partial streamed prefixes, empty-prefix handling, and end-to-end V3 handoffs.

GitOrigin-RevId: d0aef50aa71362a5beef2c6f6d28b8633da4e529
This commit is contained in:
jiayuhuang-openai authored and copyberry committed 2026-07-22 19:43:35 +00:00
1 parent 08ae0fc0ce
commit 4ebd976312
15 files changed
+325 -73

No files matched your search

+33 -11
View File
@@ -1,16 +1,30 @@
use codex_protocol::models::MessagePhase;
use std::collections::BTreeMap;
use std::sync::Arc;
const BEM_ASSISTANT_CHANNEL_PREFIX: &str = "<|start|>assistant<|channel|>";
const BEM_MESSAGE_MARKER: &str = "<|message|>";
pub(super) fn message_phase(text: &str) -> Option<MessagePhase> {
let channel_and_message = text.strip_prefix(BEM_ASSISTANT_CHANNEL_PREFIX)?;
let (channel, _) = channel_and_message.split_once(BEM_MESSAGE_MARKER)?;
match channel {
"analysis" | "commentary" => Some(MessagePhase::Commentary),
"final" => Some(MessagePhase::FinalAnswer),
_ => None,
pub(super) fn message_phase(
text: &str,
channel_prefixes: &BTreeMap<String, Vec<String>>,
) -> Option<MessagePhase> {
for (channel, default_prefix, phase) in [
("analysis", "[ANALYSIS]", MessagePhase::Commentary),
("commentary", "[COMMENTARY]", MessagePhase::Commentary),
("final", "[FINAL]", MessagePhase::FinalAnswer),
] {
let matches = channel_prefixes.get(channel).map_or_else(
|| text.starts_with(default_prefix),
|prefixes| {
prefixes
.iter()
.any(|prefix| !prefix.is_empty() && text.starts_with(prefix))
},
);
if matches {
return Some(phase);
}
}
None
}
/// Buffers a streamed BEM message until its channel header is complete.
@@ -19,18 +33,26 @@ pub(super) fn message_phase(text: &str) -> Option<MessagePhase> {
/// the frontend model can distinguish BEM `analysis` from `commentary`.
#[derive(Debug, Default)]
pub(super) struct ChannelParser {
channel_prefixes: Arc<BTreeMap<String, Vec<String>>>,
buffered_text: String,
phase: Option<MessagePhase>,
}
impl ChannelParser {
pub(super) fn new(channel_prefixes: Arc<BTreeMap<String, Vec<String>>>) -> Self {
Self {
channel_prefixes,
..Self::default()
}
}
pub(super) fn push(&mut self, text: &str) -> Option<String> {
if self.phase.is_some() {
return Some(text.to_string());
}
self.buffered_text.push_str(text);
self.phase = message_phase(&self.buffered_text);
self.phase = message_phase(&self.buffered_text, &self.channel_prefixes);
self.phase.as_ref()?;
Some(std::mem::take(&mut self.buffered_text))
}
@@ -2,34 +2,95 @@ use super::ChannelParser;
use super::message_phase;
use codex_protocol::models::MessagePhase;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::sync::Arc;
#[test]
fn maps_bem_channels_to_realtime_phases() {
let channel_prefixes = BTreeMap::new();
for (channel, expected) in [
("analysis", MessagePhase::Commentary),
("commentary", MessagePhase::Commentary),
("final", MessagePhase::FinalAnswer),
("ANALYSIS", MessagePhase::Commentary),
("COMMENTARY", MessagePhase::Commentary),
("FINAL", MessagePhase::FinalAnswer),
] {
assert_eq!(
message_phase(&format!(
"<|start|>assistant<|channel|>{channel}<|message|>text<|end|>"
)),
message_phase(&format!("[{channel}]text"), &channel_prefixes),
Some(expected)
);
}
}
#[test]
fn client_prefixes_override_only_their_configured_channels() {
let channel_prefixes = BTreeMap::from([
(
"analysis".to_string(),
vec!["[THINKING]".to_string(), "[THOUGHT]".to_string()],
),
(
"commentary".to_string(),
vec!["[PROGRESS]".to_string(), "[UPDATE]".to_string()],
),
]);
for (text, expected) in [
("[THINKING]reasoning", MessagePhase::Commentary),
("[THOUGHT]reasoning", MessagePhase::Commentary),
("[PROGRESS]working", MessagePhase::Commentary),
("[UPDATE]working", MessagePhase::Commentary),
("[FINAL]finished", MessagePhase::FinalAnswer),
] {
assert_eq!(message_phase(text, &channel_prefixes), Some(expected));
}
assert_eq!(
message_phase("[ANALYSIS]old analysis prefix", &channel_prefixes),
None
);
assert_eq!(
message_phase("[COMMENTARY]old commentary prefix", &channel_prefixes),
None
);
}
#[test]
fn empty_client_prefixes_do_not_match_every_message() {
let channel_prefixes = BTreeMap::from([("analysis".to_string(), vec![String::new()])]);
assert_eq!(message_phase("plain output", &channel_prefixes), None);
assert_eq!(
message_phase("[FINAL]finished", &channel_prefixes),
Some(MessagePhase::FinalAnswer)
);
}
#[test]
fn buffers_streamed_text_until_the_bem_channel_is_complete() {
let mut parser = ChannelParser::default();
assert_eq!(parser.push("<|start|>assistant<|channel|>com"), None);
assert_eq!(parser.push("[COM"), None);
assert_eq!(
parser.push("mentary<|message|>progress"),
Some("<|start|>assistant<|channel|>commentary<|message|>progress".to_string())
parser.push("MENTARY]progress"),
Some("[COMMENTARY]progress".to_string())
);
assert_eq!(parser.phase(), Some(MessagePhase::Commentary));
assert_eq!(parser.push(" update"), Some(" update".to_string()));
}
#[test]
fn buffers_a_client_prefix_until_the_streamed_header_is_complete() {
let channel_prefixes = BTreeMap::from([(
"commentary".to_string(),
vec!["[PROGRESS]".to_string(), "[UPDATE]".to_string()],
)]);
let mut parser = ChannelParser::new(Arc::new(channel_prefixes));
assert_eq!(parser.push("[PRO"), None);
assert_eq!(
parser.push("GRESS]working"),
Some("[PROGRESS]working".to_string())
);
assert_eq!(parser.phase(), Some(MessagePhase::Commentary));
assert_eq!(parser.push("<|end|>"), Some("<|end|>".to_string()));
}
#[test]