aidaemon_core/card.rs
1//! The typed state every status card renders from.
2//!
3//! A chat's card (the live one during a turn and the one a turn leaves
4//! behind) shows three things: the plan's steps, each helper run and the
5//! turn's own current activity. The runtime owns the records; the channels
6//! render them. Both sides read these types, so no surface ever rebuilds a
7//! status from model text, a label string or a flag.
8
9use serde::{Deserialize, Serialize};
10
11/// The header of a run the owner stopped.
12const STOPPED_BY_OWNER: &str = "\u{23f9}\u{fe0f} Stopped by you";
13
14/// Where a helper run stands.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum RunPhase {
17 Running,
18 /// Its own end record says it did the work.
19 Succeeded,
20 /// It ended without doing the work: an error, a typed failure.
21 Failed,
22 /// It ended before the work was done: it stopped short by its own
23 /// typed verdict, was cancelled, or made no progress for its limit.
24 Stopped,
25}
26
27impl RunPhase {
28 pub fn is_terminal(self) -> bool {
29 self != Self::Running
30 }
31
32 /// A helper's header on its card: a background helper's says so, one
33 /// the turn waits on reads as part of the turn's work.
34 pub fn helper_headline(self, background: bool) -> &'static str {
35 if background {
36 return self.headline();
37 }
38 match self {
39 Self::Running => "\u{23f3} A helper is working",
40 Self::Succeeded => "\u{2705} A helper finished",
41 Self::Stopped => "\u{26a0}\u{fe0f} A helper didn't finish",
42 Self::Failed => "\u{274c} A helper failed",
43 }
44 }
45
46 /// A background helper's header: on its card and as the first line of
47 /// its result in the chat.
48 pub fn headline(self) -> &'static str {
49 match self {
50 Self::Running => "\u{23f3} Running in the background",
51 Self::Succeeded => "\u{2705} Finished in the background",
52 Self::Stopped => "\u{26a0}\u{fe0f} Didn't finish in the background",
53 Self::Failed => "\u{274c} Failed in the background",
54 }
55 }
56}
57
58/// What kind of work a step is, as the owner reads it. Set from the tool's
59/// typed identity and semantics, never from its text.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum ActivityKind {
62 /// Reading a file or document.
63 Read,
64 /// Searching files or listing what is there.
65 Search,
66 /// Writing or editing files.
67 Write,
68 /// Running a command or program.
69 Run,
70 /// Searching or reading the web.
71 Web,
72 /// Handing work to a helper.
73 Delegate,
74 /// Reading what was remembered.
75 Recall,
76 /// Saving or changing what is remembered.
77 Remember,
78 /// Setting a reminder or a schedule.
79 Remind,
80 /// Any other look at the state of things.
81 Check,
82 /// Any other change.
83 Change,
84}
85
86impl ActivityKind {
87 /// The plain words the owner reads for it.
88 pub fn words(self) -> &'static str {
89 match self {
90 Self::Read => "Reading files",
91 Self::Search => "Looking through files",
92 Self::Write => "Changing files",
93 Self::Run => "Running a command",
94 Self::Web => "Looking things up online",
95 Self::Delegate => "Asking a helper",
96 Self::Recall => "Checking what I remember",
97 Self::Remember => "Updating what I remember",
98 Self::Remind => "Setting a reminder",
99 Self::Check => "Checking things",
100 Self::Change => "Making a change",
101 }
102 }
103}
104
105/// What kind of step a coding agent a run launched took last, from the
106/// agent's typed event (never its words): what a client draws the run's
107/// mark by while it works.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum AgentStepKind {
110 Read,
111 Search,
112 Edit,
113 /// Ran a command.
114 Run,
115 /// Looked something up online.
116 Fetch,
117 /// Asked one of its own helpers.
118 Delegate,
119 /// Updated its plan.
120 Plan,
121 /// Talked to the other agents of its run or conversations (messaging,
122 /// checking on them, the shared board).
123 Coordinate,
124 /// Handed work to another agent.
125 HandOff,
126 /// Blocked until something else happens: another agent's answer,
127 /// another conversation's, a free slot or folder.
128 Wait,
129 /// Any other tool.
130 Other,
131}
132
133/// What a helper, or the turn itself, is doing now.
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub enum Step {
136 /// A step of this kind is running.
137 Doing(ActivityKind),
138 /// A step of this kind handed its work on to something that keeps
139 /// running: the work goes on, so it never reads as finished.
140 HandedOff(ActivityKind),
141 /// A command is running and has printed this many lines so far. What
142 /// it printed is the command's own data, never the owner's card: a line
143 /// can carry a credential (live 2026-11-13: `drush site:install` printed
144 /// the new admin password and the card showed it), so the card shows
145 /// that it moves, not what it said.
146 Output { lines: u64 },
147 /// Its work ended and its result is being written up for the chat.
148 Reporting,
149}
150
151impl ActivityKind {
152 /// Whether its words say what is being done. `Check` and `Change` are
153 /// the kinds of a tool without one of its own: "Checking things" says
154 /// nothing, so a card shows no step rather than that filler.
155 pub fn says_what(self) -> bool {
156 !matches!(self, Self::Check | Self::Change)
157 }
158}
159
160impl Step {
161 /// Whether a card shows this step: a typed step that says what is being
162 /// done. A generic kind of work ([`ActivityKind::says_what`]) is shown
163 /// as nothing.
164 pub fn is_shown(&self) -> bool {
165 match self {
166 Self::Doing(kind) => kind.says_what(),
167 // Work that goes on elsewhere says so, whatever its kind.
168 Self::HandedOff(_) | Self::Output { .. } | Self::Reporting => true,
169 }
170 }
171
172 /// The plain words the owner reads for it.
173 pub fn words(&self) -> String {
174 match self {
175 Self::Doing(kind) => kind.words().to_string(),
176 Self::HandedOff(ActivityKind::Delegate) => {
177 "Handed to a helper; it works in the background".to_string()
178 }
179 Self::HandedOff(kind) => format!("{} · goes on in the background", kind.words()),
180 Self::Output { lines: 0 } => ActivityKind::Run.words().to_string(),
181 Self::Output { lines: 1 } => {
182 format!("{} · 1 line of output so far", ActivityKind::Run.words())
183 }
184 Self::Output { lines } => {
185 format!(
186 "{} · {lines} lines of output so far",
187 ActivityKind::Run.words()
188 )
189 }
190 Self::Reporting => "Writing up the result".to_string(),
191 }
192 }
193}
194
195/// One helper as every card shows it: the runtime's record of it.
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct HelperView {
198 /// The run it is the record of (its run id), when the sender knows
199 /// it: a card keeps one entry per run, found by this id, so two runs
200 /// under one name never share a line (live 2026-11-14: a "Finished …
201 /// Took 42s" line stood under the WordPress helper's name while that
202 /// helper still ran). `None`: found by its name.
203 pub run: Option<String>,
204 /// The name the owner reads for it.
205 pub label: String,
206 pub phase: RunPhase,
207 /// It works in the background, past the turn that started it.
208 pub background: bool,
209 /// Its latest step while it runs.
210 pub step: Option<Step>,
211 /// The plan steps (zero-based) it was started to do, as the spawn call
212 /// named them: the typed link a later run for the same step supersedes
213 /// it by ([`superseded_runs`]).
214 pub steps: Vec<usize>,
215 /// Once it failed or stopped, why, in plain words from its run record
216 /// (the same sentence its result carries). Never from its reply.
217 pub reason: Option<String>,
218 /// It stopped because the owner stopped it: its header says so
219 /// plainly ("Stopped by you"), never as a failure or an error. Set
220 /// only from its run record's typed end.
221 pub stopped_by_owner: bool,
222 /// It stopped because its coding agent's account ran out of usage (the
223 /// agent's own typed answer): until when, where the agent said.
224 pub out_of_usage: Option<OutOfUsage>,
225 /// Once it ended, how long it took and when, as the runtime measured it
226 /// and already worded for the owner ("Took 21s (2:21:16 PM to 2:21:37 PM
227 /// ET)."). Never worked out from anything a model wrote.
228 pub took: Option<String>,
229 /// Once it ended, how long after the owner's request that started it,
230 /// as the runtime measured it: what "how long did it take" means to the
231 /// owner, request to finish.
232 pub since_request: Option<SinceRequest>,
233}
234
235/// A coding agent's account out of usage, as the agent itself said.
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
237pub struct OutOfUsage {
238 /// When its usage resets, ms since the epoch; `None`: it did not say.
239 pub resets_at_ms: Option<u64>,
240}
241
242/// How long after the owner's request a helper ended, measured by the
243/// runtime: the seconds (so a card with several helpers knows which ended
244/// last) and the same span already worded for the owner ("4m 10s after
245/// your request (5:37:57 AM to 5:42:07 AM ET)").
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub struct SinceRequest {
248 pub secs: u64,
249 pub words: String,
250}
251
252impl HelperView {
253 /// A helper that is running with `step`.
254 pub fn running(label: &str, background: bool, step: Option<Step>) -> Self {
255 Self {
256 run: None,
257 label: label.to_string(),
258 phase: RunPhase::Running,
259 background,
260 step,
261 steps: Vec::new(),
262 reason: None,
263 stopped_by_owner: false,
264 out_of_usage: None,
265 took: None,
266 since_request: None,
267 }
268 }
269
270 /// Its header on a card: how it stands, from its typed record. A run
271 /// the owner stopped reads "Stopped by you" whether it ran in the
272 /// background or not.
273 pub fn headline(&self) -> &'static str {
274 if self.phase == RunPhase::Stopped && self.stopped_by_owner {
275 return STOPPED_BY_OWNER;
276 }
277 self.phase.helper_headline(self.background)
278 }
279
280 /// The same record, of run `run` (its id), when known.
281 pub fn of_run(mut self, run: Option<&str>) -> Self {
282 self.run = run.map(str::to_string);
283 self
284 }
285
286 /// Whether `other` is a record of the same helper: the same run when
287 /// both name theirs, else the same name.
288 pub fn same_helper(&self, other: &HelperView) -> bool {
289 match (self.run.as_deref(), other.run.as_deref()) {
290 (Some(mine), Some(theirs)) => mine == theirs,
291 _ => self.label == other.label,
292 }
293 }
294
295 /// The same record, started for the plan steps `steps`.
296 pub fn for_steps(mut self, steps: &[usize]) -> Self {
297 self.steps = steps.to_vec();
298 self
299 }
300}
301
302/// What took a run's plan steps over after it ended without succeeding.
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304pub enum SupersededBy {
305 /// A later run on the card, by its index, was started for all of them.
306 Run(usize),
307 /// The turn itself finished them: the plan reads each done (or not
308 /// needed) although the run didn't do them.
309 Turn,
310}
311
312/// Which runs on a card were superseded: one that ended without succeeding
313/// whose plan steps a later attempt took over. A step's outcome is its
314/// latest attempt's, whoever made it: a later run started for every one of
315/// its steps, else the turn itself, when the plan's records read each of
316/// them finished. Superseded, the run is history: it never counts as a
317/// failure in the card's header or total (live 2026-11-14: "A helper didn't
318/// finish · 5 of 5 done" over a Drupal setup the turn finished after its
319/// helper stopped). `helpers` are in the order they started; the result is
320/// index for index. Linked only by the runs' typed plan steps and the
321/// plan's step records, never by names or text.
322pub fn superseded_runs(
323 helpers: &[&HelperView],
324 plan: Option<&PlanCard>,
325) -> Vec<Option<SupersededBy>> {
326 helpers
327 .iter()
328 .enumerate()
329 .map(|(index, helper)| {
330 if helper.steps.is_empty()
331 || !helper.phase.is_terminal()
332 || helper.phase == RunPhase::Succeeded
333 {
334 return None;
335 }
336 // The latest later run that took over all its steps.
337 helpers
338 .iter()
339 .enumerate()
340 .skip(index + 1)
341 .rfind(|(_, later)| helper.steps.iter().all(|step| later.steps.contains(step)))
342 .map(|(later, _)| SupersededBy::Run(later))
343 .or_else(|| {
344 plan.is_some_and(|plan| {
345 helper
346 .steps
347 .iter()
348 .all(|step| plan.finished_steps.contains(step))
349 })
350 .then_some(SupersededBy::Turn)
351 })
352 })
353 .collect()
354}
355
356/// A run the turn itself finished after it: one quiet line ("Drupal
357/// install: first try didn't finish; I finished it myself").
358pub fn finished_by_turn_line(earlier: &HelperView, attempt: usize) -> String {
359 let ended = match earlier.phase {
360 RunPhase::Failed => "failed",
361 _ => "didn't finish",
362 };
363 format!(
364 "\u{21aa}\u{fe0f} {}: {} try {ended}; I finished it myself",
365 earlier.label.trim(),
366 ordinal(attempt),
367 )
368}
369
370/// A superseded run's one quiet line: its try, how it ended and what the
371/// run that took its step over did ("Drupal install: first try didn't
372/// finish; a second helper finished it").
373pub fn superseded_line(
374 earlier: &HelperView,
375 attempt: usize,
376 later: &HelperView,
377 later_attempt: usize,
378) -> String {
379 let ended = match earlier.phase {
380 RunPhase::Failed => "failed",
381 _ => "didn't finish",
382 };
383 let later_did = match later.phase {
384 RunPhase::Running => "is on it",
385 RunPhase::Succeeded => "finished it",
386 RunPhase::Stopped => "didn't finish it either",
387 RunPhase::Failed => "failed too",
388 };
389 format!(
390 "\u{21aa}\u{fe0f} {}: {} try {ended}; a {} helper {later_did}",
391 earlier.label.trim(),
392 ordinal(attempt),
393 ordinal(later_attempt),
394 )
395}
396
397/// "first", "second", … for a try's number (1-based).
398fn ordinal(n: usize) -> String {
399 match n {
400 1 => "first".to_string(),
401 2 => "second".to_string(),
402 3 => "third".to_string(),
403 4 => "fourth".to_string(),
404 5 => "fifth".to_string(),
405 n => format!("{n}th"),
406 }
407}
408
409/// Each run's try at its plan steps (1-based): one more than the runs
410/// before it that were started for any of the same steps. A run with no
411/// steps is its own first try.
412pub fn run_attempts(helpers: &[&HelperView]) -> Vec<usize> {
413 helpers
414 .iter()
415 .enumerate()
416 .map(|(index, helper)| {
417 1 + helpers[..index]
418 .iter()
419 .filter(|earlier| earlier.steps.iter().any(|step| helper.steps.contains(step)))
420 .count()
421 })
422 .collect()
423}
424
425/// A plan as the card shows it: its own rendering, how many steps it has
426/// and how many of them are done. The step count, not the text, decides how
427/// the card ends; the counts, with the card's run records, decide its
428/// header ([`PlanCard::header_with_runs`]).
429#[derive(Debug, Clone, Default, PartialEq, Eq)]
430pub struct PlanCard {
431 pub text: String,
432 pub steps: usize,
433 /// Its steps done.
434 pub done: usize,
435 /// The steps (zero-based) whose latest outcome is finished: done, or
436 /// set aside as not needed. A run that ended short on steps all listed
437 /// here was superseded by the turn ([`superseded_runs`]).
438 pub finished_steps: Vec<usize>,
439 /// Its records say how it ended: no step is left for its turn to do
440 /// (each is done, set aside, failed, or handed to a run). Only a settled
441 /// plan's header is a verdict the card's runs could contradict; one
442 /// still being worked through keeps its own ("Working · step 2 of 4").
443 pub settled: bool,
444}
445
446impl PlanCard {
447 /// The header the card shows above this plan's steps, from the plan's
448 /// own state and the phases of the runs on the same card together, so
449 /// the header never says something the runs' lines (or the card's total)
450 /// contradict. While any run on the card still runs, the work goes on:
451 /// "continuing in the background", whatever the plan's own steps read
452 /// (live 2026-11-13: "Stopped short · 2 of 4 done" above two helpers that
453 /// were still working, then finished). Once all ended, a plan whose
454 /// steps all read done on a card where a run failed or stopped says how
455 /// that run ended. Otherwise the plan's own header. `None`: the plan's
456 /// own header stands (a one-step plan has none).
457 pub fn header_with_runs(&self, runs: &[RunPhase]) -> Option<String> {
458 if self.steps < 2 || runs.is_empty() || !self.settled {
459 return None;
460 }
461 if runs.iter().any(|phase| !phase.is_terminal()) {
462 return Some(format!(
463 "\u{23f3} Continuing in the background \u{b7} {} of {} done",
464 self.done, self.steps
465 ));
466 }
467 let worst = runs
468 .iter()
469 .copied()
470 .filter(|phase| matches!(phase, RunPhase::Failed | RunPhase::Stopped))
471 .max_by_key(|phase| matches!(phase, RunPhase::Failed))?;
472 (self.done == self.steps).then(|| {
473 format!(
474 "{} \u{b7} {} of {} done",
475 worst.helper_headline(false),
476 self.done,
477 self.steps
478 )
479 })
480 }
481}
482
483/// How a turn's card ends, decided once from its typed state for every
484/// channel path.
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486pub enum CardEnd {
487 /// The card is the record of the work: it stays, settled to its final
488 /// header (each helper's end, the plan's closing state).
489 Keep,
490 /// The card was only progress for one step: it goes, and the reply
491 /// says what was done.
492 Collapse,
493}
494
495impl CardEnd {
496 /// A card with a helper on it, or a plan of more than one step, is
497 /// kept; only a single-step card with no helper collapses into the
498 /// reply.
499 pub fn of(plan: Option<&PlanCard>, helpers: usize) -> Self {
500 if helpers > 0 || plan.is_some_and(|plan| plan.steps > 1) {
501 Self::Keep
502 } else {
503 Self::Collapse
504 }
505 }
506}
507
508/// How a plan step's state is known.
509#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
510#[serde(rename_all = "snake_case")]
511pub enum StepEvidence {
512 /// Typed evidence settled it (a receipt, a helper's run record), or
513 /// it is not settled yet.
514 #[default]
515 Settled,
516 /// Completed on the executing model's word alone. A step that changes
517 /// nothing (a check, a read) needs no receipt: the reply reports what
518 /// it found. Only a step that declared a side effect is flagged.
519 ModelSaid,
520 /// It was handed to a helper that never started, so nothing worked
521 /// on it.
522 HelperNotStarted,
523}
524
525impl StepEvidence {
526 pub fn is_settled(&self) -> bool {
527 *self == Self::Settled
528 }
529}