use serde_json::{Map, Value, json};
use super::events::{ERROR_BYTES, EVENTS_PER_ANSWER, OUTPUT_BYTES, head};
use super::link::{self, Linked, Naming};
use super::text::say;
use super::turn::{End, lock};
pub use super::child::Child;
use super::child::filed_as;
use crate::memory::dispatch::Memory;
const LIST_ERROR_BYTES: usize = 512;
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum View {
Read,
Brief,
Listed,
}
fn unrecorded(filed: Option<&Value>, ended: bool) -> String {
let Some(filed) = filed else {
return say(if ended { "record_gap" } else { "not_recorded" }, &[]);
};
let key = match filed["disposition"].as_str().unwrap_or_default() {
"pending" => "record_pending",
"capture_off" | "capture_off_pending" => "record_off",
"capture_paused" => "record_paused",
"excluded" | "empty" => "record_excluded",
"gap" => "record_gap",
"stopped" => "record_stopped",
"bound" => "record_bound",
"session" | "existing" => "record_session",
"recorded" => "record_elsewhere",
"error" => {
let error = filed["error"].as_str().unwrap_or_default();
return say("record_error", &[("error", head(error, ERROR_BYTES))]);
}
_ => "not_recorded",
};
say(key, &[])
}
fn record(
memory: &Memory,
naming: &Naming,
child: &Child,
ended: bool,
notes: &mut Vec<String>,
) -> Value {
let Some(native) = child.session.as_deref() else {
notes.push(say("record_unknown", &[]));
return Value::Null;
};
if child.existed {
notes.push(say("announced_existing", &[("session", native)]));
return Value::Null;
}
let conversation = naming.conversation(child.agent.kind(), native);
let before = child
.current
.as_ref()
.map_or(Ok(0), |turn| turn.before.clone());
let read = before.and_then(|before| {
link::last_turn_bounded(&memory.store, &conversation).map(|after| (before, after))
});
let (before, after) = match read {
Ok(pair) => pair,
Err(error) => {
notes.push(say(
"record_failed",
&[("error", head(&error, ERROR_BYTES))],
));
return Value::Null;
}
};
let parent = if ended { child.parent.as_deref() } else { None };
let linked = parent.map(|parent| link::link(memory, child.agent.kind(), &conversation, parent));
let after = match &linked {
Some(Linked::Yes | Linked::Written) if after <= before => {
link::last_turn_bounded(&memory.store, &conversation).unwrap_or(after)
}
_ => after,
};
let value = if after > before {
let turns = if after == before + 1 {
after.to_string()
} else {
format!("{}-{after}", before + 1)
};
notes.push(say(
"recorded",
&[("conversation", &conversation), ("turns", &turns)],
));
json!({"conversation": conversation, "turns": turns})
} else {
let filed = child
.current
.as_ref()
.and_then(|turn| lock(&turn.shared).filed.clone());
notes.push(unrecorded(filed.as_ref(), ended));
Value::Null
};
if !ended {
return value;
}
let (Some(parent), Some(linked)) = (parent, linked) else {
notes.push(say("not_linked_session", &[]));
return value;
};
notes.push(match linked {
Linked::Yes => say("linked", &[("session", parent)]),
Linked::Written => say("link_written", &[("session", parent)]),
Linked::Absent if after > 0 => say("not_linked_mount", &[]),
Linked::Absent => say("not_linked_absent", &[]),
Linked::NoMount => say("not_linked_mount", &[]),
Linked::OtherAgent => say("not_linked_agent", &[]),
Linked::Retry => say("not_linked_retry", &[]),
Linked::Failed(error) => say("link_failed", &[("error", head(&error, ERROR_BYTES))]),
});
value
}
pub fn child(memory: &Memory, naming: &Naming, child: &mut Child, view: View) -> Value {
child.learn();
let state = child.state();
let failed = child.outcome() == "failed";
let mut out = Map::new();
out.insert("child".into(), json!(child.id));
out.insert("agent".into(), json!(child.agent.name()));
out.insert("mode".into(), json!(child.mode.name()));
out.insert("model".into(), json!(child.model));
out.insert(
"directory".into(),
json!(child.directory.display().to_string()),
);
out.insert("state".into(), json!(state));
out.insert("turn".into(), json!(child.turns));
out.insert("session".into(), json!(child.session));
let conversation = child
.session
.as_deref()
.filter(|_| !child.existed)
.map(|native| naming.conversation(child.agent.kind(), native));
out.insert("conversation".into(), json!(conversation));
let mut notes = Vec::new();
let ended = state != "running" && state != "starting";
if let Some(turn) = child.current.as_mut() {
if view != View::Listed {
notes.extend(turn.notes.iter().cloned());
}
let shared = lock(&turn.shared);
if view == View::Read {
let (text, skipped) = shared.text.since(turn.read_text, OUTPUT_BYTES);
let (mut events, left_out) = shared.log.since(turn.read_events, EVENTS_PER_ANSWER - 2);
if left_out > 0 {
events.insert(
0,
json!({"kind": "truncated", "field": "events", "count": left_out}),
);
}
if skipped > 0 {
events.insert(
0,
json!({"kind": "truncated", "field": "text", "bytes": skipped}),
);
notes.push(say("output_cut", &[("bytes", &skipped.to_string())]));
}
out.insert("text".into(), json!(text));
out.insert("events".into(), json!(events));
turn.read_text = shared.text.total();
turn.read_events = shared.log.total();
}
if ended
&& view != View::Listed
&& let Some(answer) = shared.final_answer()
{
let shown = head(answer, OUTPUT_BYTES);
out.insert("answer".into(), json!(shown));
if shown.len() < answer.len() {
out.insert("answer_bytes".into(), json!(answer.len()));
let (shown, bytes) = (shown.len().to_string(), answer.len().to_string());
notes.push(say("answer_cut", &[("shown", &shown), ("bytes", &bytes)]));
}
}
if failed {
let limit = if view == View::Listed {
LIST_ERROR_BYTES
} else {
ERROR_BYTES
};
let error = match (&shared.failure, shared.end) {
(Some(failure), _) => failure.clone(),
(None, Some(End::Lost)) => say("watcher_lost", &[]),
(None, _) => shared.stderr.text().to_string(),
};
out.insert("error".into(), json!(head(&error, limit)));
if let Some(End::Exited(code)) = shared.end {
out.insert("exit".into(), json!(code));
}
}
if child.stopped && filed_as(shared.filed.as_ref(), &["recorded", "pending"]) {
notes.push(say("stopped_recorded", &[]));
}
if state == "timed_out" {
notes.push(say(
"timed_out",
&[("seconds", &child.limit_seconds.to_string())],
));
}
}
let recorded = record(memory, naming, child, ended, &mut notes);
out.insert("record".into(), recorded);
notes.extend(super::sandbox::note(
super::sandbox::platform(),
child.agent,
child.mode,
));
let filed = child.claim();
notes.push(match state {
"running" | "starting" => say("running", &[("child", &child.id)]),
"stopped" => say("stopped_note", &[]),
"failed" | "timed_out" if !filed => say("ended_unfiled", &[("child", &child.id)]),
_ => say("ended", &[("child", &child.id)]),
});
out.insert("notes".into(), json!(notes));
Value::Object(out)
}