aidaemon_tools/status.rs
1//! Live progress of a turn: what tools and the agent loop report while they
2//! work, and the channel a tool call's progress goes to.
3
4use tokio::sync::mpsc;
5
6use crate::semantics::ToolCallContext;
7
8/// Status updates emitted by tools and the agent loop for live feedback to the user.
9#[derive(Debug, Clone)]
10pub enum StatusUpdate {
11 /// A chunk of the reply as the model writes it, for app clients that
12 /// stream it. Only a top-level turn sends it; the runner hands it to the
13 /// turn observer and never to a chat surface, its live state or a
14 /// parent's card. The finished reply still arrives as the turn's answer.
15 ReplyText(String),
16 /// A message the sender sent while the turn ran, taken into it: for app
17 /// clients, which show it in the conversation once the run reads it.
18 /// Like `ReplyText`, the runner hands it to the turn observer only (a
19 /// chat surface already shows what its sender typed). `origin` is the
20 /// platform it was sent from.
21 MessageTaken { text: String, origin: String },
22 /// Sent before each LLM call (skipped on iteration 0).
23 Thinking(usize),
24 /// Sent before each tool execution. `kind` is what every card shows;
25 /// `name` and `summary` are the call's own words for clients that list
26 /// calls. Built with [`StatusUpdate::tool_start`]: the variant is
27 /// non-exhaustive so a new field changes one constructor, not every
28 /// sender.
29 #[non_exhaustive]
30 ToolStart {
31 name: String,
32 summary: String,
33 kind: aidaemon_core::card::ActivityKind,
34 /// The call's arguments as an app shows them
35 /// ([`crate::shown::call_input`]); empty when there are none to show.
36 input: String,
37 },
38 /// Streaming output chunk from a tool (e.g., CLI agent progress).
39 ToolProgress { name: String, chunk: String },
40 /// A tool is paused until the user completes an explicit action, such as
41 /// authorizing an OAuth connection in their browser. Unlike ordinary tool
42 /// progress, channels must deliver this immediately and without truncation.
43 UserActionRequired { message: String },
44 /// Tool execution completed with a brief summary. Built with
45 /// [`StatusUpdate::tool_complete`].
46 #[non_exhaustive]
47 ToolComplete {
48 name: String,
49 summary: String,
50 /// The call's result as an app shows it
51 /// ([`crate::shown::call_output`]); empty when there is none to show.
52 output: String,
53 },
54 /// Tool can be cancelled with the given task_id.
55 ToolCancellable { name: String, task_id: String },
56 /// Periodic summary for long-running tasks (emitted every 5 minutes).
57 ProgressSummary { elapsed_mins: u64, summary: String },
58 /// Warning that soft iteration limit is approaching.
59 IterationWarning { current: usize, threshold: usize },
60 /// A new task plan was created.
61 PlanCreated {
62 plan_id: String,
63 description: String,
64 total_steps: usize,
65 },
66 /// A plan step has started executing.
67 PlanStepStart {
68 plan_id: String,
69 step_index: usize,
70 total_steps: usize,
71 description: String,
72 },
73 /// A plan step completed successfully.
74 PlanStepComplete {
75 plan_id: String,
76 step_index: usize,
77 total_steps: usize,
78 description: String,
79 summary: Option<String>,
80 },
81 /// A plan step failed.
82 PlanStepFailed {
83 plan_id: String,
84 step_index: usize,
85 description: String,
86 error: String,
87 },
88 /// The entire plan completed successfully.
89 PlanComplete {
90 plan_id: String,
91 description: String,
92 total_steps: usize,
93 duration_secs: u64,
94 },
95 /// The plan was abandoned by user request.
96 PlanAbandoned {
97 plan_id: String,
98 description: String,
99 },
100 /// The plan was revised with new/updated steps.
101 PlanRevised {
102 plan_id: String,
103 description: String,
104 reason: String,
105 new_total_steps: usize,
106 },
107 /// The task plan as the single live card shows it: its rendering and
108 /// its step count, which decides whether the card is kept.
109 Checklist(aidaemon_core::card::PlanCard),
110 /// A helper's record changed: it started, took a step or ended. The
111 /// view is the runtime's record of it, so the live card and the card a
112 /// turn leaves behind show the same thing.
113 Helper(aidaemon_core::card::HelperView),
114 /// The request finished in this turn, after helpers it waited on, as
115 /// the runtime measured it and already worded for the owner. `by_me`:
116 /// the turn finished work itself after a helper ended ("Finished by me
117 /// after the helper: Drupal install" and that work's measured line);
118 /// `total`: the request's whole time, from the owner's message to the
119 /// answer ("Answer sent 10m 12s after your request (5:30:24 PM to
120 /// 5:40:36 PM ET)."), when it adds to the helpers' own times.
121 Finished {
122 by_me: Option<String>,
123 total: Option<String>,
124 },
125 /// A step ended by handing its work to something that keeps running: a
126 /// helper (`ActivityKind::Delegate`) or a background job. The work has
127 /// not finished, so the step must never read as finished. Built with
128 /// [`StatusUpdate::step_handed_off`].
129 #[non_exhaustive]
130 StepHandedOff {
131 kind: aidaemon_core::card::ActivityKind,
132 /// The call's name as its [`Self::ToolStart`] gave it; empty when
133 /// there was no such update.
134 name: String,
135 /// The call's own result (its launch line) as an app shows it
136 /// ([`Self::showing_result`]); empty when there is none to show.
137 output: String,
138 },
139 /// How many lines a long-running command has printed so far, sent at
140 /// most every few seconds while it runs. A helper's card line shows the
141 /// count, so a long count or install visibly moves. Never the lines
142 /// themselves: a command's output is its own data and can carry a
143 /// credential (see [`aidaemon_core::card::Step::Output`]).
144 CommandOutput {
145 name: String,
146 lines: u64,
147 /// Its latest lines, secrets redacted, for the owner's own app only
148 /// ([`command_output_tail`]); a chat's card reads `lines` and never
149 /// this. `None` where the owner's app is not the reader.
150 tail: Option<String>,
151 },
152}
153
154/// The last lines of a command's output for the owner's own app: at most
155/// 20 lines and 2,000 characters, secrets redacted.
156pub fn command_output_tail(stdout: &[u8], stderr: &[u8]) -> Option<String> {
157 let mut text = String::from_utf8_lossy(stdout).into_owned();
158 if !stderr.is_empty() {
159 if !text.is_empty() && !text.ends_with('\n') {
160 text.push('\n');
161 }
162 text.push_str(&String::from_utf8_lossy(stderr));
163 }
164 let lines: Vec<&str> = text.lines().collect();
165 let tail = lines[lines.len().saturating_sub(20)..].join("\n");
166 let tail: String = tail
167 .chars()
168 .rev()
169 .take(2_000)
170 .collect::<Vec<_>>()
171 .into_iter()
172 .rev()
173 .collect();
174 let tail = crate::sanitize::redact_for_owner(&tail);
175 (!tail.trim().is_empty()).then_some(tail)
176}
177
178impl StatusUpdate {
179 /// A call starting, with nothing to show of its arguments yet
180 /// ([`Self::showing_arguments`] adds them).
181 pub fn tool_start(
182 name: impl Into<String>,
183 summary: impl Into<String>,
184 kind: aidaemon_core::card::ActivityKind,
185 ) -> Self {
186 Self::ToolStart {
187 name: name.into(),
188 summary: summary.into(),
189 kind,
190 input: String::new(),
191 }
192 }
193
194 /// A call finished, with nothing to show of its result yet
195 /// ([`Self::showing_result`] adds it).
196 pub fn tool_complete(name: impl Into<String>, summary: impl Into<String>) -> Self {
197 Self::ToolComplete {
198 name: name.into(),
199 summary: summary.into(),
200 output: String::new(),
201 }
202 }
203
204 /// A step that handed its work off ([`Self::StepHandedOff`]), named as
205 /// its call started; [`Self::showing_result`] adds its launch result.
206 pub fn step_handed_off(
207 name: impl Into<String>,
208 kind: aidaemon_core::card::ActivityKind,
209 ) -> Self {
210 Self::StepHandedOff {
211 kind,
212 name: name.into(),
213 output: String::new(),
214 }
215 }
216
217 /// A started call that shows its raw JSON arguments the way history
218 /// does ([`crate::shown::call_input`]). Other updates are unchanged.
219 pub fn showing_arguments(mut self, arguments: &str) -> Self {
220 if let Self::ToolStart { input, .. } = &mut self {
221 *input = crate::shown::call_input(&serde_json::Value::String(arguments.to_string()));
222 }
223 self
224 }
225
226 /// A finished or handed-off call that shows its result the way history
227 /// does ([`crate::shown::call_output`]). Other updates are unchanged.
228 pub fn showing_result(mut self, result: &str) -> Self {
229 if let Self::ToolComplete { output, .. } | Self::StepHandedOff { output, .. } = &mut self {
230 *output = crate::shown::call_output(result);
231 }
232 self
233 }
234
235 /// Whether a channel must deliver this update immediately instead of
236 /// treating it as optional, rate-limited progress.
237 pub fn requires_immediate_delivery(&self) -> bool {
238 // A token budget extended on productive progress is the run's own
239 // bookkeeping, never a status of its own: the owner acts on nothing
240 // (live 2026-11-13: seven "Auto-extended token budget" lines in one
241 // turn). It stays in the logs and the run's decision records.
242 matches!(self, Self::UserActionRequired { .. })
243 }
244}
245
246/// The channel a call's live progress goes to, carried in
247/// [`ToolCallContext::extensions`].
248#[derive(Clone)]
249pub struct ToolStatus(pub mpsc::Sender<StatusUpdate>);
250
251/// Where this call's live progress goes, if anywhere.
252pub fn status_sender(facts: &ToolCallContext) -> Option<mpsc::Sender<StatusUpdate>> {
253 facts
254 .extensions
255 .get::<ToolStatus>()
256 .map(|status| status.0.clone())
257}
258
259/// `facts` with this call's progress channel added.
260pub fn with_status(
261 mut facts: ToolCallContext,
262 status_tx: Option<mpsc::Sender<StatusUpdate>>,
263) -> ToolCallContext {
264 if let Some(status_tx) = status_tx {
265 facts.extensions.insert(ToolStatus(status_tx));
266 }
267 facts
268}
269
270#[cfg(test)]
271mod tests {
272 use super::StatusUpdate;
273
274 #[test]
275 fn url_in_ordinary_progress_does_not_force_chat_delivery() {
276 let progress = StatusUpdate::ToolProgress {
277 name: "agent delegation".to_string(),
278 chunk: "Checking https://blog.example.test/posts/example/".to_string(),
279 };
280 assert!(!progress.requires_immediate_delivery());
281
282 let action = StatusUpdate::UserActionRequired {
283 message: "[Authorize](https://auth.example.test/)".to_string(),
284 };
285 assert!(action.requires_immediate_delivery());
286 }
287}
288
289#[cfg(test)]
290mod command_output_tail_tests {
291 use super::command_output_tail;
292
293 #[test]
294 fn the_owner_sees_the_last_lines_with_secrets_redacted() {
295 let mut out = String::new();
296 for n in 1..=30 {
297 out.push_str(&format!("line {n}\n"));
298 }
299 out.push_str("token=sk-synthetic-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n");
300 let tail = command_output_tail(out.as_bytes(), b"").unwrap();
301 assert!(!tail.contains("line 1\n"), "{tail}");
302 assert!(tail.contains("line 30"));
303 assert!(!tail.contains("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), "{tail}");
304 assert_eq!(command_output_tail(b"", b""), None);
305 }
306}