use agent_base::{Action, ChatMessage};
use codexec::observation::CellEvent;
use codexec::{ArtifactHub, ArtifactRef, Observation as EngineObservation, artifact_line};
use serde_json::Value;
use crate::script_tool::truncate_output;
pub(super) fn render_pair(actions: &[Action], observation: String) -> Vec<ChatMessage> {
let blocks: Vec<String> = actions
.iter()
.map(|a| {
let (intent, code) = block_of(a);
format!("<intent>{intent}</intent>\n<code>{code}</code>")
})
.collect();
vec![
ChatMessage::assistant(blocks.join("\n")),
ChatMessage::user(observation),
]
}
pub(super) fn block_of(action: &Action) -> (String, String) {
let obj = action.args.as_object();
let field = |k: &str| {
obj.and_then(|o| o.get(k))
.and_then(Value::as_str)
.unwrap_or_default()
.to_string()
};
(field("intent"), field("code"))
}
pub(super) fn observation_text(
obs: &EngineObservation,
cap: usize,
hub: Option<&ArtifactHub>,
) -> (String, Option<ArtifactRef>) {
let mut out = String::from("[observation]\n");
let mut any = false;
let line = |text: String, out: &mut String, any: &mut bool| {
if *any && !out.ends_with('\n') {
out.push('\n');
}
out.push_str(&text);
*any = true;
};
if !obs.stdout.is_empty() {
line(obs.stdout.clone(), &mut out, &mut any);
}
if !obs.stderr.is_empty() {
line(format!("stderr:\n{}", obs.stderr), &mut out, &mut any);
}
if let Some(err) = &obs.error {
line(format!("error: {err}"), &mut out, &mut any);
}
for ev in &obs.events {
let text = match ev {
CellEvent::TodoChanged { id, status } => format!("todo {id}: {status}"),
CellEvent::Notice { text } => format!("notice: {text}"),
CellEvent::Artifact {
capture_id,
kind,
bytes,
summary,
} => artifact_line(capture_id, kind, *bytes, summary),
CellEvent::Image(_) => continue,
};
line(text, &mut out, &mut any);
}
if !any {
out.push_str("(no output)");
}
fit_to_cap(out, cap, hub)
}
fn fit_to_cap(
text: String,
cap: usize,
hub: Option<&ArtifactHub>,
) -> (String, Option<ArtifactRef>) {
if text.chars().count() <= cap {
return (text, None);
}
let Some(r) = hub.and_then(|h| h.store().spill("observation", &text).ok()) else {
return (truncate_output(&text, Some(cap)), None);
};
let line = artifact_line(&r.capture_id, &r.kind, r.bytes, &r.summary);
if line.chars().count() + 1 >= cap {
return (truncate_output(&text, Some(cap)), None);
}
let budget = cap - line.chars().count() - 1;
let text = format!("{}\n{}", truncate_output(&text, Some(budget)), line);
(text, Some(r))
}