Skip to main content

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 a helper, or the turn itself, is doing now.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub enum Step {
108    /// A step of this kind is running.
109    Doing(ActivityKind),
110    /// A step of this kind handed its work on to something that keeps
111    /// running: the work goes on, so it never reads as finished.
112    HandedOff(ActivityKind),
113    /// A command is running and has printed this many lines so far. What
114    /// it printed is the command's own data, never the owner's card: a line
115    /// can carry a credential (live 2026-11-13: `drush site:install` printed
116    /// the new admin password and the card showed it), so the card shows
117    /// that it moves, not what it said.
118    Output { lines: u64 },
119    /// Its work ended and its result is being written up for the chat.
120    Reporting,
121}
122
123impl ActivityKind {
124    /// Whether its words say what is being done. `Check` and `Change` are
125    /// the kinds of a tool without one of its own: "Checking things" says
126    /// nothing, so a card shows no step rather than that filler.
127    pub fn says_what(self) -> bool {
128        !matches!(self, Self::Check | Self::Change)
129    }
130}
131
132impl Step {
133    /// Whether a card shows this step: a typed step that says what is being
134    /// done. A generic kind of work ([`ActivityKind::says_what`]) is shown
135    /// as nothing.
136    pub fn is_shown(&self) -> bool {
137        match self {
138            Self::Doing(kind) => kind.says_what(),
139            // Work that goes on elsewhere says so, whatever its kind.
140            Self::HandedOff(_) | Self::Output { .. } | Self::Reporting => true,
141        }
142    }
143
144    /// The plain words the owner reads for it.
145    pub fn words(&self) -> String {
146        match self {
147            Self::Doing(kind) => kind.words().to_string(),
148            Self::HandedOff(ActivityKind::Delegate) => {
149                "Handed to a helper; it works in the background".to_string()
150            }
151            Self::HandedOff(kind) => format!("{} · goes on in the background", kind.words()),
152            Self::Output { lines: 0 } => ActivityKind::Run.words().to_string(),
153            Self::Output { lines: 1 } => {
154                format!("{} · 1 line of output so far", ActivityKind::Run.words())
155            }
156            Self::Output { lines } => {
157                format!(
158                    "{} · {lines} lines of output so far",
159                    ActivityKind::Run.words()
160                )
161            }
162            Self::Reporting => "Writing up the result".to_string(),
163        }
164    }
165}
166
167/// One helper as every card shows it: the runtime's record of it.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct HelperView {
170    /// The run it is the record of (its run id), when the sender knows
171    /// it: a card keeps one entry per run, found by this id, so two runs
172    /// under one name never share a line (live 2026-11-14: a "Finished …
173    /// Took 42s" line stood under the WordPress helper's name while that
174    /// helper still ran). `None`: found by its name.
175    pub run: Option<String>,
176    /// The name the owner reads for it.
177    pub label: String,
178    pub phase: RunPhase,
179    /// It works in the background, past the turn that started it.
180    pub background: bool,
181    /// Its latest step while it runs.
182    pub step: Option<Step>,
183    /// The plan steps (zero-based) it was started to do, as the spawn call
184    /// named them: the typed link a later run for the same step supersedes
185    /// it by ([`superseded_runs`]).
186    pub steps: Vec<usize>,
187    /// Once it failed or stopped, why, in plain words from its run record
188    /// (the same sentence its result carries). Never from its reply.
189    pub reason: Option<String>,
190    /// It stopped because the owner stopped it: its header says so
191    /// plainly ("Stopped by you"), never as a failure or an error. Set
192    /// only from its run record's typed end.
193    pub stopped_by_owner: bool,
194    /// It stopped because its coding agent's account ran out of usage (the
195    /// agent's own typed answer): until when, where the agent said.
196    pub out_of_usage: Option<OutOfUsage>,
197    /// Once it ended, how long it took and when, as the runtime measured it
198    /// and already worded for the owner ("Took 21s (2:21:16 PM to 2:21:37 PM
199    /// ET)."). Never worked out from anything a model wrote.
200    pub took: Option<String>,
201    /// Once it ended, how long after the owner's request that started it,
202    /// as the runtime measured it: what "how long did it take" means to the
203    /// owner, request to finish.
204    pub since_request: Option<SinceRequest>,
205}
206
207/// A coding agent's account out of usage, as the agent itself said.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub struct OutOfUsage {
210    /// When its usage resets, ms since the epoch; `None`: it did not say.
211    pub resets_at_ms: Option<u64>,
212}
213
214/// How long after the owner's request a helper ended, measured by the
215/// runtime: the seconds (so a card with several helpers knows which ended
216/// last) and the same span already worded for the owner ("4m 10s after
217/// your request (5:37:57 AM to 5:42:07 AM ET)").
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct SinceRequest {
220    pub secs: u64,
221    pub words: String,
222}
223
224impl HelperView {
225    /// A helper that is running with `step`.
226    pub fn running(label: &str, background: bool, step: Option<Step>) -> Self {
227        Self {
228            run: None,
229            label: label.to_string(),
230            phase: RunPhase::Running,
231            background,
232            step,
233            steps: Vec::new(),
234            reason: None,
235            stopped_by_owner: false,
236            out_of_usage: None,
237            took: None,
238            since_request: None,
239        }
240    }
241
242    /// Its header on a card: how it stands, from its typed record. A run
243    /// the owner stopped reads "Stopped by you" whether it ran in the
244    /// background or not.
245    pub fn headline(&self) -> &'static str {
246        if self.phase == RunPhase::Stopped && self.stopped_by_owner {
247            return STOPPED_BY_OWNER;
248        }
249        self.phase.helper_headline(self.background)
250    }
251
252    /// The same record, of run `run` (its id), when known.
253    pub fn of_run(mut self, run: Option<&str>) -> Self {
254        self.run = run.map(str::to_string);
255        self
256    }
257
258    /// Whether `other` is a record of the same helper: the same run when
259    /// both name theirs, else the same name.
260    pub fn same_helper(&self, other: &HelperView) -> bool {
261        match (self.run.as_deref(), other.run.as_deref()) {
262            (Some(mine), Some(theirs)) => mine == theirs,
263            _ => self.label == other.label,
264        }
265    }
266
267    /// The same record, started for the plan steps `steps`.
268    pub fn for_steps(mut self, steps: &[usize]) -> Self {
269        self.steps = steps.to_vec();
270        self
271    }
272}
273
274/// What took a run's plan steps over after it ended without succeeding.
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276pub enum SupersededBy {
277    /// A later run on the card, by its index, was started for all of them.
278    Run(usize),
279    /// The turn itself finished them: the plan reads each done (or not
280    /// needed) although the run didn't do them.
281    Turn,
282}
283
284/// Which runs on a card were superseded: one that ended without succeeding
285/// whose plan steps a later attempt took over. A step's outcome is its
286/// latest attempt's, whoever made it: a later run started for every one of
287/// its steps, else the turn itself, when the plan's records read each of
288/// them finished. Superseded, the run is history: it never counts as a
289/// failure in the card's header or total (live 2026-11-14: "A helper didn't
290/// finish · 5 of 5 done" over a Drupal setup the turn finished after its
291/// helper stopped). `helpers` are in the order they started; the result is
292/// index for index. Linked only by the runs' typed plan steps and the
293/// plan's step records, never by names or text.
294pub fn superseded_runs(
295    helpers: &[&HelperView],
296    plan: Option<&PlanCard>,
297) -> Vec<Option<SupersededBy>> {
298    helpers
299        .iter()
300        .enumerate()
301        .map(|(index, helper)| {
302            if helper.steps.is_empty()
303                || !helper.phase.is_terminal()
304                || helper.phase == RunPhase::Succeeded
305            {
306                return None;
307            }
308            // The latest later run that took over all its steps.
309            helpers
310                .iter()
311                .enumerate()
312                .skip(index + 1)
313                .rfind(|(_, later)| helper.steps.iter().all(|step| later.steps.contains(step)))
314                .map(|(later, _)| SupersededBy::Run(later))
315                .or_else(|| {
316                    plan.is_some_and(|plan| {
317                        helper
318                            .steps
319                            .iter()
320                            .all(|step| plan.finished_steps.contains(step))
321                    })
322                    .then_some(SupersededBy::Turn)
323                })
324        })
325        .collect()
326}
327
328/// A run the turn itself finished after it: one quiet line ("Drupal
329/// install: first try didn't finish; I finished it myself").
330pub fn finished_by_turn_line(earlier: &HelperView, attempt: usize) -> String {
331    let ended = match earlier.phase {
332        RunPhase::Failed => "failed",
333        _ => "didn't finish",
334    };
335    format!(
336        "\u{21aa}\u{fe0f} {}: {} try {ended}; I finished it myself",
337        earlier.label.trim(),
338        ordinal(attempt),
339    )
340}
341
342/// A superseded run's one quiet line: its try, how it ended and what the
343/// run that took its step over did ("Drupal install: first try didn't
344/// finish; a second helper finished it").
345pub fn superseded_line(
346    earlier: &HelperView,
347    attempt: usize,
348    later: &HelperView,
349    later_attempt: usize,
350) -> String {
351    let ended = match earlier.phase {
352        RunPhase::Failed => "failed",
353        _ => "didn't finish",
354    };
355    let later_did = match later.phase {
356        RunPhase::Running => "is on it",
357        RunPhase::Succeeded => "finished it",
358        RunPhase::Stopped => "didn't finish it either",
359        RunPhase::Failed => "failed too",
360    };
361    format!(
362        "\u{21aa}\u{fe0f} {}: {} try {ended}; a {} helper {later_did}",
363        earlier.label.trim(),
364        ordinal(attempt),
365        ordinal(later_attempt),
366    )
367}
368
369/// "first", "second", … for a try's number (1-based).
370fn ordinal(n: usize) -> String {
371    match n {
372        1 => "first".to_string(),
373        2 => "second".to_string(),
374        3 => "third".to_string(),
375        4 => "fourth".to_string(),
376        5 => "fifth".to_string(),
377        n => format!("{n}th"),
378    }
379}
380
381/// Each run's try at its plan steps (1-based): one more than the runs
382/// before it that were started for any of the same steps. A run with no
383/// steps is its own first try.
384pub fn run_attempts(helpers: &[&HelperView]) -> Vec<usize> {
385    helpers
386        .iter()
387        .enumerate()
388        .map(|(index, helper)| {
389            1 + helpers[..index]
390                .iter()
391                .filter(|earlier| earlier.steps.iter().any(|step| helper.steps.contains(step)))
392                .count()
393        })
394        .collect()
395}
396
397/// A plan as the card shows it: its own rendering, how many steps it has
398/// and how many of them are done. The step count, not the text, decides how
399/// the card ends; the counts, with the card's run records, decide its
400/// header ([`PlanCard::header_with_runs`]).
401#[derive(Debug, Clone, Default, PartialEq, Eq)]
402pub struct PlanCard {
403    pub text: String,
404    pub steps: usize,
405    /// Its steps done.
406    pub done: usize,
407    /// The steps (zero-based) whose latest outcome is finished: done, or
408    /// set aside as not needed. A run that ended short on steps all listed
409    /// here was superseded by the turn ([`superseded_runs`]).
410    pub finished_steps: Vec<usize>,
411    /// Its records say how it ended: no step is left for its turn to do
412    /// (each is done, set aside, failed, or handed to a run). Only a settled
413    /// plan's header is a verdict the card's runs could contradict; one
414    /// still being worked through keeps its own ("Working · step 2 of 4").
415    pub settled: bool,
416}
417
418impl PlanCard {
419    /// The header the card shows above this plan's steps, from the plan's
420    /// own state and the phases of the runs on the same card together, so
421    /// the header never says something the runs' lines (or the card's total)
422    /// contradict. While any run on the card still runs, the work goes on:
423    /// "continuing in the background", whatever the plan's own steps read
424    /// (live 2026-11-13: "Stopped short · 2 of 4 done" above two helpers that
425    /// were still working, then finished). Once all ended, a plan whose
426    /// steps all read done on a card where a run failed or stopped says how
427    /// that run ended. Otherwise the plan's own header. `None`: the plan's
428    /// own header stands (a one-step plan has none).
429    pub fn header_with_runs(&self, runs: &[RunPhase]) -> Option<String> {
430        if self.steps < 2 || runs.is_empty() || !self.settled {
431            return None;
432        }
433        if runs.iter().any(|phase| !phase.is_terminal()) {
434            return Some(format!(
435                "\u{23f3} Continuing in the background \u{b7} {} of {} done",
436                self.done, self.steps
437            ));
438        }
439        let worst = runs
440            .iter()
441            .copied()
442            .filter(|phase| matches!(phase, RunPhase::Failed | RunPhase::Stopped))
443            .max_by_key(|phase| matches!(phase, RunPhase::Failed))?;
444        (self.done == self.steps).then(|| {
445            format!(
446                "{} \u{b7} {} of {} done",
447                worst.helper_headline(false),
448                self.done,
449                self.steps
450            )
451        })
452    }
453}
454
455/// How a turn's card ends, decided once from its typed state for every
456/// channel path.
457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
458pub enum CardEnd {
459    /// The card is the record of the work: it stays, settled to its final
460    /// header (each helper's end, the plan's closing state).
461    Keep,
462    /// The card was only progress for one step: it goes, and the reply
463    /// says what was done.
464    Collapse,
465}
466
467impl CardEnd {
468    /// A card with a helper on it, or a plan of more than one step, is
469    /// kept; only a single-step card with no helper collapses into the
470    /// reply.
471    pub fn of(plan: Option<&PlanCard>, helpers: usize) -> Self {
472        if helpers > 0 || plan.is_some_and(|plan| plan.steps > 1) {
473            Self::Keep
474        } else {
475            Self::Collapse
476        }
477    }
478}
479
480/// How a plan step's state is known.
481#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
482#[serde(rename_all = "snake_case")]
483pub enum StepEvidence {
484    /// Typed evidence settled it (a receipt, a helper's run record), or
485    /// it is not settled yet.
486    #[default]
487    Settled,
488    /// Completed on the executing model's word alone. A step that changes
489    /// nothing (a check, a read) needs no receipt: the reply reports what
490    /// it found. Only a step that declared a side effect is flagged.
491    ModelSaid,
492    /// It was handed to a helper that never started, so nothing worked
493    /// on it.
494    HelperNotStarted,
495}
496
497impl StepEvidence {
498    pub fn is_settled(&self) -> bool {
499        *self == Self::Settled
500    }
501}