use serde_json::json;
use sha2::{Digest, Sha256};
use super::{
ContentPart, CustomItem, FunctionCallItem, ItemStatus, MessageItem, MessageRole, OpenResponseError, OpenUsage,
OutputItem, ReasoningItem, Response, ResponseStatus, ResponseStreamEvent, StreamEventEmitter,
response::{generate_item_id, generate_response_id},
};
use crate::provider::{FinishReason, NormalizedStreamEvent, ToolCall};
use vtcode_exec_events::{
CommandExecutionStatus, McpToolCallStatus, PatchApplyStatus, ThreadEvent, ThreadItem, ThreadItemDetails,
ToolOutputItem,
};
#[derive(Debug)]
#[must_use = "build the response before discarding the builder"]
pub struct ResponseBuilder {
response: Response,
next_output_index: usize,
item_id_to_index: hashbrown::HashMap<String, usize>,
active_items: hashbrown::HashMap<String, ActiveItemState>,
tool_call_correlation_ids: hashbrown::HashMap<String, String>,
used_tool_call_ids: hashbrown::HashSet<String>,
normalized: NormalizedBridgeState,
}
#[derive(Debug, Clone)]
struct ActiveItemState {
output_index: usize,
content_index: usize,
prev_text: String,
tool_output_prefix: Option<ToolOutputPrefix>,
}
#[derive(Debug, Clone)]
struct ToolOutputPrefix {
digest: Sha256,
byte_len: Option<usize>,
}
impl ToolOutputPrefix {
fn new(text: &str) -> Self {
let mut prefix = Self { digest: Sha256::new(), byte_len: Some(0) };
prefix.append(text);
prefix
}
fn append(&mut self, text: &str) {
self.digest.update(text.as_bytes());
self.byte_len = self.byte_len.and_then(|len| len.checked_add(text.len()));
}
fn suffix<'a>(&self, snapshot: &'a str) -> Option<&'a str> {
let len = self.byte_len?;
let prefix = snapshot.get(..len)?;
(Sha256::digest(prefix.as_bytes()) == self.digest.clone().finalize())
.then(|| snapshot.get(len..))
.flatten()
}
}
#[derive(Debug, Clone)]
struct NormalizedFunctionCallState {
item_id: String,
output_index: usize,
name: Option<String>,
arguments: String,
}
#[derive(Debug, Default)]
struct NormalizedBridgeState {
response_started: bool,
message_item_id: Option<String>,
reasoning_item_id: Option<String>,
tool_calls: hashbrown::HashMap<String, NormalizedFunctionCallState>,
}
impl ResponseBuilder {
pub fn new(model: impl Into<String>) -> Self {
let response = Response::new(generate_response_id(), model);
Self {
response,
next_output_index: 0,
item_id_to_index: hashbrown::HashMap::new(),
active_items: hashbrown::HashMap::new(),
tool_call_correlation_ids: hashbrown::HashMap::new(),
used_tool_call_ids: hashbrown::HashSet::new(),
normalized: NormalizedBridgeState::default(),
}
}
pub(crate) fn response(&self) -> &Response {
&self.response
}
pub fn response_mut(&mut self) -> &mut Response {
&mut self.response
}
pub fn response_id(&self) -> &str {
&self.response.id
}
#[must_use]
pub fn build(self) -> Response {
self.response
}
}
mod emitter;
mod items;
mod normalized;
pub use emitter::DualEventEmitter;
#[cfg(test)]
mod tests;