use agent_base::{
Action, ActionFormat, ActionOutcome, BatchStatus, Observation, ObservationEvent, ParseOutcome,
};
use codexec::observation::CellEvent;
use codexec::{
Action as EngineAction, ArtifactHub, ExecError as EngineError, Observation as EngineObservation,
};
use serde_json::Value;
use super::render::{observation_text, render_pair};
pub(super) fn classify_text(text: &str) -> ParseOutcome {
match codexec::parse_actions(text) {
Ok(cells) => ParseOutcome::Actions(
cells
.iter()
.enumerate()
.map(|(i, c)| {
Action::from_code_cell(
format!("cell_{i}"),
c.intent().to_string(),
c.code().to_string(),
)
})
.collect(),
),
Err(codexec::ParseError::NoBlocks) => ParseOutcome::Empty,
Err(codexec::ParseError::Malformed { detail, .. }) => {
if detail.starts_with("unclosed") || detail.contains("without a following") {
ParseOutcome::Incomplete
} else {
ParseOutcome::Malformed
}
}
}
}
pub(super) fn decode_batch(actions: &[Action]) -> Result<Vec<EngineAction>, String> {
let mut cells = Vec::with_capacity(actions.len());
for a in actions {
if a.format != ActionFormat::CodeAct {
return Err(format!("action {} is not a CodeAct cell", a.id));
}
let Some(obj) = a.args.as_object() else {
return Err(format!("action {} does not carry the block shape", a.id));
};
let field = |k: &str| {
obj.get(k)
.and_then(Value::as_str)
.map(str::to_string)
.ok_or_else(|| format!("action {} is missing `{k}`", a.id))
};
let intent = field("intent")?;
let code = field("code")?;
if code.trim().is_empty() {
return Err(format!("action {} has empty code", a.id));
}
cells.push(EngineAction::CodeCell { intent, code });
}
Ok(cells)
}
pub(super) fn fold(
actions: &[Action],
obs: EngineObservation,
cap: usize,
hub: Option<&ArtifactHub>,
) -> Observation {
let batch_status = match &obs.error {
Some(EngineError::Timeout { .. } | EngineError::Worker(_) | EngineError::SessionReset) => {
BatchStatus::EnvDied
}
_ => BatchStatus::Completed,
};
let (pane, spill) = observation_text(&obs, cap, hub);
let mut events = observation_events(&obs);
if let Some(r) = spill {
events.push(ObservationEvent::Artifact {
capture_id: r.capture_id,
kind: r.kind,
summary: r.summary,
});
}
Observation {
outcomes: fates(actions, &obs),
events,
history_messages: render_pair(actions, pane),
batch_status,
}
}
pub(super) fn observation_events(obs: &EngineObservation) -> Vec<ObservationEvent> {
obs.events
.iter()
.filter_map(|ev| match ev {
CellEvent::TodoChanged { id, status } => Some(ObservationEvent::Text {
text: format!("todo {id}: {status}"),
}),
CellEvent::Notice { text } => Some(ObservationEvent::Text { text: text.clone() }),
CellEvent::Image(_) => None,
CellEvent::Artifact {
capture_id,
kind,
summary,
..
} => Some(ObservationEvent::Artifact {
capture_id: capture_id.clone(),
kind: kind.clone(),
summary: summary.clone(),
}),
})
.collect()
}
pub(super) fn fates(actions: &[Action], obs: &EngineObservation) -> Vec<ActionOutcome> {
let n = actions.len();
let fate = |i: usize, ok: bool, denied: bool, summary: String| ActionOutcome {
action_id: actions[i].id.clone(),
name: actions[i].name.clone(),
ok,
denied,
summary,
details: None,
};
match &obs.error {
None => (0..n)
.map(|i| fate(i, true, false, "completed".into()))
.collect(),
Some(EngineError::CompileError { index, message }) => (0..n)
.map(|i| {
if i == *index {
fate(i, false, false, format!("compile_error: {message}"))
} else {
fate(
i,
false,
false,
format!("not run (compile_error in block #{index})"),
)
}
})
.collect(),
Some(EngineError::CellError {
index,
kind,
message,
}) => (0..n)
.map(|i| {
if i < *index {
fate(i, true, false, "completed".into())
} else if i == *index {
fate(i, false, false, format!("{kind}: {message}"))
} else {
fate(
i,
false,
false,
format!("not run (step halted at block #{index})"),
)
}
})
.collect(),
Some(err @ EngineError::PolicyHold { cell_index, .. }) => (0..n)
.map(|i| {
if i < *cell_index {
fate(i, true, false, "completed".into())
} else if i == *cell_index {
fate(i, false, true, err.to_string())
} else {
fate(
i,
false,
false,
format!("not run (step halted on policy hold at block #{cell_index})"),
)
}
})
.collect(),
Some(EngineError::SessionReset) => (0..n)
.map(|i| fate(i, false, false, "not run (session_reset)".into()))
.collect(),
Some(err @ (EngineError::Timeout { .. } | EngineError::Worker(_))) => (0..n)
.map(|i| fate(i, false, false, format!("fate not reported ({err})")))
.collect(),
Some(EngineError::Journal(msg)) => (0..n)
.map(|i| {
fate(
i,
false,
false,
format!("not run (journal failed: {msg}; fail-closed)"),
)
})
.collect(),
}
}