use std::sync::Arc;
use agent_base::{
Action, ActionBackend, ActionExecutor, ActionFormat, ActionOutcome, ChatMessage, ExecCtx,
ExecError, LlmTurnResult, Observation, ParseError, ParseOutcome, SessionError, SessionHandle,
};
#[allow(unused_imports)]
use agent_base::BatchStatus;
use async_trait::async_trait;
use codexec::{CodeCellExecutor, Worker};
pub(crate) const DEFAULT_OBSERVATION_CAP: usize = 16_000;
pub struct CodeActExecutor<W: Worker> {
engine: CodeCellExecutor<W>,
interact: Arc<ExecCtxBridge>,
observation_cap: usize,
}
impl<W: Worker> CodeActExecutor<W> {
pub fn new(engine: CodeCellExecutor<W>, interact: Arc<ExecCtxBridge>) -> Self {
Self {
engine,
interact,
observation_cap: DEFAULT_OBSERVATION_CAP,
}
}
pub fn with_observation_cap(mut self, cap: usize) -> Self {
self.observation_cap = cap;
self
}
pub fn engine(&self) -> &CodeCellExecutor<W> {
&self.engine
}
pub fn into_engine(self) -> CodeCellExecutor<W> {
self.engine
}
}
#[async_trait]
impl<W: Worker + Send + Sync + 'static> ActionExecutor for CodeActExecutor<W> {
fn parse(&self, turn: &LlmTurnResult) -> Result<ParseOutcome, ParseError> {
if turn.is_tool_call {
return Err(ParseError::Unparseable(
"tool-envelope turn routed to the CodeAct backend".into(),
));
}
Ok(classify_text(&turn.full_text))
}
async fn execute(
&mut self,
actions: Vec<Action>,
ctx: &ExecCtx,
) -> Result<Observation, ExecError> {
if actions.is_empty() {
return Err(ExecError::NothingRan {
reason: "empty batch".into(),
});
}
let cells = decode_batch(&actions).map_err(|reason| ExecError::NothingRan { reason })?;
self.interact.arm(ctx);
let obs = self.engine.execute(cells).await;
self.interact.disarm();
let hub = self.engine.registry().artifacts();
Ok(fold(&actions, obs, self.observation_cap, hub.as_deref()))
}
}
#[async_trait]
impl<W: Worker + Send + Sync + 'static> SessionHandle for CodeActExecutor<W> {
fn is_alive(&self) -> bool {
self.engine.is_session_alive()
}
async fn rebuild(&mut self) -> Result<(), SessionError> {
Ok(())
}
}
#[async_trait]
impl<W: Worker + Send + Sync + 'static> ActionBackend for CodeActExecutor<W> {
fn format(&self) -> ActionFormat {
ActionFormat::CodeAct
}
fn render_fates(&self, actions: &[Action], fates: &[ActionOutcome]) -> Vec<ChatMessage> {
let mut out = String::from("[observation]\n");
for (i, (a, f)) in actions.iter().zip(fates.iter()).enumerate() {
let (intent, _) = block_of(a);
out.push_str(&format!("#{} {}: {}\n", i + 1, intent, f.summary));
}
render_pair(actions, out)
}
}
mod adapt;
mod bridge;
mod render;
use adapt::{classify_text, decode_batch, fold};
use render::{block_of, render_pair};
pub use bridge::ExecCtxBridge;
#[cfg(test)]
mod tests;