mod batch;
mod errors;
mod run_actions;
mod seam;
use serde_json::Value;
use crate::engine::executor::ParseOutcome;
use crate::engine::runtime::LlmTurnResult;
use crate::engine::runtime::plan_runner::RuntimeCore;
use crate::types::{Action, AgentError, FinishReason, Observation, SessionId};
pub(super) struct ToolBatchReport {
pub observation: Observation,
pub first_failure: Option<AgentError>,
}
pub(super) struct ToolCallExecutor<'c> {
core: &'c RuntimeCore,
session_id: SessionId,
}
pub(super) fn actions_to_triples(actions: &[Action]) -> Vec<(String, String, String)> {
actions
.iter()
.map(|a| (a.id.clone(), a.name.clone(), a.raw_args().into_owned()))
.collect()
}
pub(super) fn triples_to_actions(tool_calls: &[(String, String, String)]) -> Vec<Action> {
tool_calls
.iter()
.map(|(id, name, args)| Action::from_tool_call(id.clone(), name.clone(), args.clone()))
.collect()
}
impl<'c> ToolCallExecutor<'c> {
pub(super) fn new(core: &'c RuntimeCore, session_id: SessionId) -> Self {
Self { core, session_id }
}
pub(super) fn classify(&self, turn: &LlmTurnResult) -> ParseOutcome {
classify_turn(turn)
}
}
fn classify_turn(turn: &LlmTurnResult) -> ParseOutcome {
let actions = triples_to_actions(&flatten_envelope(turn));
if turn.is_tool_call {
if actions.is_empty() {
ParseOutcome::Incomplete
} else {
ParseOutcome::Actions(actions)
}
} else if !turn.full_text.is_empty() {
let finish = FinishReason::from_raw(turn.finish_reason.as_deref());
if finish.is_truncated() || matches!(finish, FinishReason::ToolUse) {
ParseOutcome::Malformed
} else {
ParseOutcome::Empty
}
} else {
ParseOutcome::Empty
}
}
fn flatten_envelope(turn: &LlmTurnResult) -> Vec<(String, String, String)> {
turn.tool_calls
.iter()
.map(|tc| {
let id = tc
.get("id")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let name = tc
.get("function")
.and_then(|f| f.get("name"))
.and_then(|n| n.as_str())
.unwrap_or("")
.to_string();
let args = tc
.get("function")
.and_then(|f| f.get("arguments"))
.and_then(|a| a.as_str())
.unwrap_or("")
.to_string();
(id, name, args)
})
.collect()
}
fn failing_tool_names(tool_calls: &[(String, String, String)], error: &AgentError) -> Vec<String> {
match error {
AgentError::ToolArgsInvalid { name, .. } => vec![name.clone()],
AgentError::ToolExecution { name, .. } => vec![name.clone()],
_ => tool_calls.iter().map(|(_, n, _)| n.clone()).collect(),
}
}
fn is_truncation_wrapper(args: &Value) -> bool {
let obj = match args.as_object() {
Some(o) => o,
None => return false,
};
let marker = obj
.get("error")
.and_then(Value::as_str)
.is_some_and(|s| s == "tool_call_arguments_truncated");
let preview = obj.contains_key("original_args_preview");
marker || (preview && obj.contains_key("message"))
}
#[cfg(test)]
mod parse_fixtures;
#[cfg(test)]
mod tests;