use aidaemon_core::{
Event, FinishOutcome, Interruption, LimitKind, ReceiptStatus, RunOutcome, RunStatus,
};
use crate::channel::{ProgressPhase, RunEnding, RunProgress, ToolProgress, ToolState};
const MAX_TOOL_LINES: usize = 8;
#[derive(Debug, Default)]
pub(crate) struct Progress {
tools: Vec<ToolProgress>,
stream: String,
}
impl Progress {
pub(crate) fn apply(&mut self, event: &Event) -> bool {
match event {
Event::TurnStarted { .. } => {
let changed = !self.stream.is_empty();
self.stream.clear();
changed
}
Event::TextDelta { text, .. } => {
self.stream.push_str(text);
!text.is_empty()
}
Event::ToolStarted { call_id, tool } => {
self.push(ToolProgress {
call_id: call_id.clone(),
tool: tool.clone(),
state: ToolState::Running,
});
true
}
Event::ToolFinished { receipt } => {
let state = ToolState::Ended(receipt.status);
match self.tools.iter_mut().find(|t| t.call_id == receipt.call_id) {
Some(line) => line.state = state,
None => self.push(ToolProgress {
call_id: receipt.call_id.clone(),
tool: receipt.tool.clone(),
state,
}),
}
true
}
_ => false,
}
}
fn push(&mut self, tool: ToolProgress) {
self.tools.push(tool);
if self.tools.len() > MAX_TOOL_LINES {
self.tools.remove(0);
}
}
pub(crate) fn working(&self) -> RunProgress {
RunProgress {
phase: ProgressPhase::Working,
tools: self.tools.clone(),
streamed: self.stream.clone(),
}
}
pub(crate) fn ended(&self, ending: RunEnding) -> RunProgress {
RunProgress {
phase: ProgressPhase::Ended(ending),
tools: self.tools.clone(),
streamed: String::new(),
}
}
}
pub(crate) fn receipt_word(status: ReceiptStatus) -> &'static str {
match status {
ReceiptStatus::Succeeded => "done",
ReceiptStatus::Failed => "failed",
ReceiptStatus::Denied => "denied",
ReceiptStatus::TimedOut => "timed out",
ReceiptStatus::Cancelled => "cancelled",
ReceiptStatus::UnknownTool => "unknown tool",
ReceiptStatus::InvalidArguments => "invalid arguments",
ReceiptStatus::Indeterminate => "outcome unknown",
ReceiptStatus::Skipped => "skipped",
ReceiptStatus::Answered => "answered without running",
}
}
pub(crate) use aidaemon_tools::text::truncate_str as truncate_chars;
pub(crate) fn tail_chars(text: &str, max: usize) -> String {
let count = text.chars().count();
if count <= max {
return text.to_string();
}
let keep = max.saturating_sub(3);
let tail: String = text.chars().skip(count - keep).collect();
format!("...{tail}")
}
pub(crate) fn approval_text(interruption: &Interruption, max_argument_chars: usize) -> String {
let args = serde_json::to_string_pretty(&interruption.call.arguments)
.unwrap_or_else(|_| interruption.call.arguments.to_string());
let args = truncate_chars(&args, max_argument_chars).replace("```", "'''");
let reason = interruption.reason.trim();
let mut out = format!(
"**Approval needed**\n\nThe agent wants to run `{}`.",
interruption.call.name
);
if !reason.is_empty() {
out.push_str(&format!("\n\nReason: {reason}"));
}
out.push_str(&format!("\n\nArguments:\n```json\n{args}\n```"));
out
}
pub(crate) fn approval_fallback(prompt_id: &str) -> String {
format!("Reply `/approve {prompt_id}` to allow it or `/deny {prompt_id}` to refuse.")
}
pub(crate) fn ending_text(status: &RunStatus) -> String {
match status {
RunStatus::Completed => "Done.".to_string(),
RunStatus::Interrupted { .. } => "Waiting for approval.".to_string(),
RunStatus::LimitReached { limit } => {
let what = match limit {
LimitKind::Turns => "the maximum number of steps",
LimitKind::Tokens => "its token budget",
LimitKind::ToolCalls => "the maximum number of tool calls",
LimitKind::WallClock => "its time limit",
#[allow(unreachable_patterns)]
_ => "a limit",
};
format!("I stopped because the run reached {what}.")
}
RunStatus::Stopped { reason } => {
format!("I stopped: {}", truncate_chars(reason, 300))
}
RunStatus::Stuck { .. } => {
"I stopped because I was repeating myself without making progress.".to_string()
}
RunStatus::Cancelled => "Stopped.".to_string(),
RunStatus::Finished { outcome, .. } => match outcome {
FinishOutcome::Succeeded => "Done.".to_string(),
FinishOutcome::Partial => "I did part of it; the rest is still underway.".to_string(),
FinishOutcome::Blocked => "I can't go on without help.".to_string(),
_ => "I stopped here.".to_string(),
},
RunStatus::ProviderFailed { error } => format!(
"I could not get a reply from the model provider ({}). Please try again.",
truncate_chars(error, 200)
),
#[allow(unreachable_patterns)]
_ => "The run ended unexpectedly.".to_string(),
}
}
pub(crate) fn outcome_ending_text(outcome: &RunOutcome) -> String {
if outcome.is_completed() && !outcome.unmet().is_empty() {
let mut text = "I stopped without finishing everything:".to_string();
for line in outcome.unmet() {
text.push_str("\n- ");
text.push_str(&truncate_chars(line, 300));
}
return text;
}
ending_text(&outcome.status)
}
pub(crate) fn outcome_ending(outcome: &RunOutcome) -> RunEnding {
if outcome.is_completed() && !outcome.is_succeeded() {
return RunEnding::PartlyDone;
}
status_ending(&outcome.status)
}
pub(crate) fn status_ending(status: &RunStatus) -> RunEnding {
match status {
RunStatus::Completed => RunEnding::Done,
RunStatus::Interrupted { .. } => RunEnding::WaitingForApproval,
RunStatus::Cancelled => RunEnding::Stopped,
RunStatus::Finished { outcome, .. } => match outcome {
FinishOutcome::Succeeded => RunEnding::Done,
FinishOutcome::Partial => RunEnding::PartlyDone,
FinishOutcome::Blocked => RunEnding::Blocked,
_ => RunEnding::Ended,
},
_ => RunEnding::Ended,
}
}
#[cfg(test)]
pub(crate) fn status_word(status: &RunStatus) -> &'static str {
status_ending(status).word()
}
#[cfg(test)]
pub(crate) fn outcome_word(outcome: &RunOutcome) -> &'static str {
outcome_ending(outcome).word()
}
#[cfg(test)]
mod tests {
use super::*;
use aidaemon_core::ToolCall;
use serde_json::json;
#[test]
fn approval_text_pretty_prints_and_truncates() {
let interruption = Interruption {
call: ToolCall::new(
"c1",
"deploy",
json!({"target": "staging", "zz_notes": "x".repeat(500)}),
),
reason: "deploys need a human".into(),
kind: aidaemon_core::InterruptKind::default(),
digest: None,
};
let text = approval_text(&interruption, 80);
assert!(text.contains("`deploy`"));
assert!(text.contains("Reason: deploys need a human"));
assert!(text.contains("\"target\": \"staging\""));
assert!(text.contains("..."));
assert!(text.chars().count() < 300);
}
#[test]
fn progress_tracks_tools_and_resets_stream_per_turn() {
let mut p = Progress::default();
assert!(p.apply(&Event::TextDelta {
turn: 1,
text: "thinking".into()
}));
assert!(p.working().to_markdown(200).contains("thinking"));
assert!(p.apply(&Event::TurnStarted { turn: 2 }));
assert!(!p.working().to_markdown(200).contains("thinking"));
p.apply(&Event::ToolStarted {
call_id: "c1".into(),
tool: "search".into(),
});
assert!(p.working().to_markdown(200).contains("Running `search`"));
assert!(p.working().to_markdown(10).chars().count() <= 10);
}
#[test]
fn finished_runs_read_by_their_outcome() {
let finished = |outcome| RunStatus::Finished {
outcome,
tool: "file_report".into(),
};
assert_eq!(ending_text(&finished(FinishOutcome::Succeeded)), "Done.");
assert_eq!(status_word(&finished(FinishOutcome::Succeeded)), "Done");
assert_eq!(
status_word(&finished(FinishOutcome::Partial)),
"Partly done"
);
assert_eq!(status_word(&finished(FinishOutcome::Blocked)), "Blocked");
for outcome in [FinishOutcome::Partial, FinishOutcome::Blocked] {
assert!(!ending_text(&finished(outcome)).contains("unexpectedly"));
}
}
#[test]
fn completed_runs_with_unmet_requirements_read_as_partly_done() {
let mut outcome = RunOutcome {
status: RunStatus::Completed,
final_text: None,
state: aidaemon_core::RunState::new("a", "s", "go"),
};
assert_eq!(outcome_word(&outcome), "Done");
assert_eq!(outcome_ending_text(&outcome), "Done.");
outcome.state.unmet = vec!["checklist: [-] email the report".into()];
assert_eq!(outcome_word(&outcome), "Partly done");
let text = outcome_ending_text(&outcome);
assert!(text.contains("without finishing") && text.contains("email the report"));
}
}