aidaemon-core 0.29.0

The aidaemon agent kernel: a small, hook-driven agent loop with tools, providers, receipts and resumable state
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! The typed state every status card renders from.
//!
//! A chat's card (the live one during a turn and the one a turn leaves
//! behind) shows three things: the plan's steps, each helper run and the
//! turn's own current activity. The runtime owns the records; the channels
//! render them. Both sides read these types, so no surface ever rebuilds a
//! status from model text, a label string or a flag.

use serde::{Deserialize, Serialize};

/// The header of a run the owner stopped.
const STOPPED_BY_OWNER: &str = "\u{23f9}\u{fe0f} Stopped by you";

/// Where a helper run stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunPhase {
    Running,
    /// Its own end record says it did the work.
    Succeeded,
    /// It ended without doing the work: an error, a typed failure.
    Failed,
    /// It ended before the work was done: it stopped short by its own
    /// typed verdict, was cancelled, or made no progress for its limit.
    Stopped,
}

impl RunPhase {
    pub fn is_terminal(self) -> bool {
        self != Self::Running
    }

    /// A helper's header on its card: a background helper's says so, one
    /// the turn waits on reads as part of the turn's work.
    pub fn helper_headline(self, background: bool) -> &'static str {
        if background {
            return self.headline();
        }
        match self {
            Self::Running => "\u{23f3} A helper is working",
            Self::Succeeded => "\u{2705} A helper finished",
            Self::Stopped => "\u{26a0}\u{fe0f} A helper didn't finish",
            Self::Failed => "\u{274c} A helper failed",
        }
    }

    /// A background helper's header: on its card and as the first line of
    /// its result in the chat.
    pub fn headline(self) -> &'static str {
        match self {
            Self::Running => "\u{23f3} Running in the background",
            Self::Succeeded => "\u{2705} Finished in the background",
            Self::Stopped => "\u{26a0}\u{fe0f} Didn't finish in the background",
            Self::Failed => "\u{274c} Failed in the background",
        }
    }
}

/// What kind of work a step is, as the owner reads it. Set from the tool's
/// typed identity and semantics, never from its text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActivityKind {
    /// Reading a file or document.
    Read,
    /// Searching files or listing what is there.
    Search,
    /// Writing or editing files.
    Write,
    /// Running a command or program.
    Run,
    /// Searching or reading the web.
    Web,
    /// Handing work to a helper.
    Delegate,
    /// Reading what was remembered.
    Recall,
    /// Saving or changing what is remembered.
    Remember,
    /// Setting a reminder or a schedule.
    Remind,
    /// Any other look at the state of things.
    Check,
    /// Any other change.
    Change,
}

impl ActivityKind {
    /// The plain words the owner reads for it.
    pub fn words(self) -> &'static str {
        match self {
            Self::Read => "Reading files",
            Self::Search => "Looking through files",
            Self::Write => "Changing files",
            Self::Run => "Running a command",
            Self::Web => "Looking things up online",
            Self::Delegate => "Asking a helper",
            Self::Recall => "Checking what I remember",
            Self::Remember => "Updating what I remember",
            Self::Remind => "Setting a reminder",
            Self::Check => "Checking things",
            Self::Change => "Making a change",
        }
    }
}

/// What kind of step a coding agent a run launched took last, from the
/// agent's typed event (never its words): what a client draws the run's
/// mark by while it works.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentStepKind {
    Read,
    Search,
    Edit,
    /// Ran a command.
    Run,
    /// Looked something up online.
    Fetch,
    /// Asked one of its own helpers.
    Delegate,
    /// Updated its plan.
    Plan,
    /// Talked to the other agents of its run or conversations (messaging,
    /// checking on them, the shared board).
    Coordinate,
    /// Handed work to another agent.
    HandOff,
    /// Blocked until something else happens: another agent's answer,
    /// another conversation's, a free slot or folder.
    Wait,
    /// Any other tool.
    Other,
}

/// What a helper, or the turn itself, is doing now.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Step {
    /// A step of this kind is running.
    Doing(ActivityKind),
    /// A step of this kind handed its work on to something that keeps
    /// running: the work goes on, so it never reads as finished.
    HandedOff(ActivityKind),
    /// A command is running and has printed this many lines so far. What
    /// it printed is the command's own data, never the owner's card: a line
    /// can carry a credential (live 2026-11-13: `drush site:install` printed
    /// the new admin password and the card showed it), so the card shows
    /// that it moves, not what it said.
    Output { lines: u64 },
    /// Its work ended and its result is being written up for the chat.
    Reporting,
}

impl ActivityKind {
    /// Whether its words say what is being done. `Check` and `Change` are
    /// the kinds of a tool without one of its own: "Checking things" says
    /// nothing, so a card shows no step rather than that filler.
    pub fn says_what(self) -> bool {
        !matches!(self, Self::Check | Self::Change)
    }
}

impl Step {
    /// Whether a card shows this step: a typed step that says what is being
    /// done. A generic kind of work ([`ActivityKind::says_what`]) is shown
    /// as nothing.
    pub fn is_shown(&self) -> bool {
        match self {
            Self::Doing(kind) => kind.says_what(),
            // Work that goes on elsewhere says so, whatever its kind.
            Self::HandedOff(_) | Self::Output { .. } | Self::Reporting => true,
        }
    }

    /// The plain words the owner reads for it.
    pub fn words(&self) -> String {
        match self {
            Self::Doing(kind) => kind.words().to_string(),
            Self::HandedOff(ActivityKind::Delegate) => {
                "Handed to a helper; it works in the background".to_string()
            }
            Self::HandedOff(kind) => format!("{} · goes on in the background", kind.words()),
            Self::Output { lines: 0 } => ActivityKind::Run.words().to_string(),
            Self::Output { lines: 1 } => {
                format!("{} · 1 line of output so far", ActivityKind::Run.words())
            }
            Self::Output { lines } => {
                format!(
                    "{} · {lines} lines of output so far",
                    ActivityKind::Run.words()
                )
            }
            Self::Reporting => "Writing up the result".to_string(),
        }
    }
}

/// One helper as every card shows it: the runtime's record of it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HelperView {
    /// The run it is the record of (its run id), when the sender knows
    /// it: a card keeps one entry per run, found by this id, so two runs
    /// under one name never share a line (live 2026-11-14: a "Finished …
    /// Took 42s" line stood under the WordPress helper's name while that
    /// helper still ran). `None`: found by its name.
    pub run: Option<String>,
    /// The name the owner reads for it.
    pub label: String,
    pub phase: RunPhase,
    /// It works in the background, past the turn that started it.
    pub background: bool,
    /// Its latest step while it runs.
    pub step: Option<Step>,
    /// The plan steps (zero-based) it was started to do, as the spawn call
    /// named them: the typed link a later run for the same step supersedes
    /// it by ([`superseded_runs`]).
    pub steps: Vec<usize>,
    /// Once it failed or stopped, why, in plain words from its run record
    /// (the same sentence its result carries). Never from its reply.
    pub reason: Option<String>,
    /// It stopped because the owner stopped it: its header says so
    /// plainly ("Stopped by you"), never as a failure or an error. Set
    /// only from its run record's typed end.
    pub stopped_by_owner: bool,
    /// It stopped because its coding agent's account ran out of usage (the
    /// agent's own typed answer): until when, where the agent said.
    pub out_of_usage: Option<OutOfUsage>,
    /// Once it ended, how long it took and when, as the runtime measured it
    /// and already worded for the owner ("Took 21s (2:21:16 PM to 2:21:37 PM
    /// ET)."). Never worked out from anything a model wrote.
    pub took: Option<String>,
    /// Once it ended, how long after the owner's request that started it,
    /// as the runtime measured it: what "how long did it take" means to the
    /// owner, request to finish.
    pub since_request: Option<SinceRequest>,
}

/// A coding agent's account out of usage, as the agent itself said.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutOfUsage {
    /// When its usage resets, ms since the epoch; `None`: it did not say.
    pub resets_at_ms: Option<u64>,
}

/// How long after the owner's request a helper ended, measured by the
/// runtime: the seconds (so a card with several helpers knows which ended
/// last) and the same span already worded for the owner ("4m 10s after
/// your request (5:37:57 AM to 5:42:07 AM ET)").
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SinceRequest {
    pub secs: u64,
    pub words: String,
}

impl HelperView {
    /// A helper that is running with `step`.
    pub fn running(label: &str, background: bool, step: Option<Step>) -> Self {
        Self {
            run: None,
            label: label.to_string(),
            phase: RunPhase::Running,
            background,
            step,
            steps: Vec::new(),
            reason: None,
            stopped_by_owner: false,
            out_of_usage: None,
            took: None,
            since_request: None,
        }
    }

    /// Its header on a card: how it stands, from its typed record. A run
    /// the owner stopped reads "Stopped by you" whether it ran in the
    /// background or not.
    pub fn headline(&self) -> &'static str {
        if self.phase == RunPhase::Stopped && self.stopped_by_owner {
            return STOPPED_BY_OWNER;
        }
        self.phase.helper_headline(self.background)
    }

    /// The same record, of run `run` (its id), when known.
    pub fn of_run(mut self, run: Option<&str>) -> Self {
        self.run = run.map(str::to_string);
        self
    }

    /// Whether `other` is a record of the same helper: the same run when
    /// both name theirs, else the same name.
    pub fn same_helper(&self, other: &HelperView) -> bool {
        match (self.run.as_deref(), other.run.as_deref()) {
            (Some(mine), Some(theirs)) => mine == theirs,
            _ => self.label == other.label,
        }
    }

    /// The same record, started for the plan steps `steps`.
    pub fn for_steps(mut self, steps: &[usize]) -> Self {
        self.steps = steps.to_vec();
        self
    }
}

/// What took a run's plan steps over after it ended without succeeding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SupersededBy {
    /// A later run on the card, by its index, was started for all of them.
    Run(usize),
    /// The turn itself finished them: the plan reads each done (or not
    /// needed) although the run didn't do them.
    Turn,
}

/// Which runs on a card were superseded: one that ended without succeeding
/// whose plan steps a later attempt took over. A step's outcome is its
/// latest attempt's, whoever made it: a later run started for every one of
/// its steps, else the turn itself, when the plan's records read each of
/// them finished. Superseded, the run is history: it never counts as a
/// failure in the card's header or total (live 2026-11-14: "A helper didn't
/// finish · 5 of 5 done" over a Drupal setup the turn finished after its
/// helper stopped). `helpers` are in the order they started; the result is
/// index for index. Linked only by the runs' typed plan steps and the
/// plan's step records, never by names or text.
pub fn superseded_runs(
    helpers: &[&HelperView],
    plan: Option<&PlanCard>,
) -> Vec<Option<SupersededBy>> {
    helpers
        .iter()
        .enumerate()
        .map(|(index, helper)| {
            if helper.steps.is_empty()
                || !helper.phase.is_terminal()
                || helper.phase == RunPhase::Succeeded
            {
                return None;
            }
            // The latest later run that took over all its steps.
            helpers
                .iter()
                .enumerate()
                .skip(index + 1)
                .rfind(|(_, later)| helper.steps.iter().all(|step| later.steps.contains(step)))
                .map(|(later, _)| SupersededBy::Run(later))
                .or_else(|| {
                    plan.is_some_and(|plan| {
                        helper
                            .steps
                            .iter()
                            .all(|step| plan.finished_steps.contains(step))
                    })
                    .then_some(SupersededBy::Turn)
                })
        })
        .collect()
}

/// A run the turn itself finished after it: one quiet line ("Drupal
/// install: first try didn't finish; I finished it myself").
pub fn finished_by_turn_line(earlier: &HelperView, attempt: usize) -> String {
    let ended = match earlier.phase {
        RunPhase::Failed => "failed",
        _ => "didn't finish",
    };
    format!(
        "\u{21aa}\u{fe0f} {}: {} try {ended}; I finished it myself",
        earlier.label.trim(),
        ordinal(attempt),
    )
}

/// A superseded run's one quiet line: its try, how it ended and what the
/// run that took its step over did ("Drupal install: first try didn't
/// finish; a second helper finished it").
pub fn superseded_line(
    earlier: &HelperView,
    attempt: usize,
    later: &HelperView,
    later_attempt: usize,
) -> String {
    let ended = match earlier.phase {
        RunPhase::Failed => "failed",
        _ => "didn't finish",
    };
    let later_did = match later.phase {
        RunPhase::Running => "is on it",
        RunPhase::Succeeded => "finished it",
        RunPhase::Stopped => "didn't finish it either",
        RunPhase::Failed => "failed too",
    };
    format!(
        "\u{21aa}\u{fe0f} {}: {} try {ended}; a {} helper {later_did}",
        earlier.label.trim(),
        ordinal(attempt),
        ordinal(later_attempt),
    )
}

/// "first", "second", … for a try's number (1-based).
fn ordinal(n: usize) -> String {
    match n {
        1 => "first".to_string(),
        2 => "second".to_string(),
        3 => "third".to_string(),
        4 => "fourth".to_string(),
        5 => "fifth".to_string(),
        n => format!("{n}th"),
    }
}

/// Each run's try at its plan steps (1-based): one more than the runs
/// before it that were started for any of the same steps. A run with no
/// steps is its own first try.
pub fn run_attempts(helpers: &[&HelperView]) -> Vec<usize> {
    helpers
        .iter()
        .enumerate()
        .map(|(index, helper)| {
            1 + helpers[..index]
                .iter()
                .filter(|earlier| earlier.steps.iter().any(|step| helper.steps.contains(step)))
                .count()
        })
        .collect()
}

/// A plan as the card shows it: its own rendering, how many steps it has
/// and how many of them are done. The step count, not the text, decides how
/// the card ends; the counts, with the card's run records, decide its
/// header ([`PlanCard::header_with_runs`]).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PlanCard {
    pub text: String,
    pub steps: usize,
    /// Its steps done.
    pub done: usize,
    /// The steps (zero-based) whose latest outcome is finished: done, or
    /// set aside as not needed. A run that ended short on steps all listed
    /// here was superseded by the turn ([`superseded_runs`]).
    pub finished_steps: Vec<usize>,
    /// Its records say how it ended: no step is left for its turn to do
    /// (each is done, set aside, failed, or handed to a run). Only a settled
    /// plan's header is a verdict the card's runs could contradict; one
    /// still being worked through keeps its own ("Working · step 2 of 4").
    pub settled: bool,
}

impl PlanCard {
    /// The header the card shows above this plan's steps, from the plan's
    /// own state and the phases of the runs on the same card together, so
    /// the header never says something the runs' lines (or the card's total)
    /// contradict. While any run on the card still runs, the work goes on:
    /// "continuing in the background", whatever the plan's own steps read
    /// (live 2026-11-13: "Stopped short · 2 of 4 done" above two helpers that
    /// were still working, then finished). Once all ended, a plan whose
    /// steps all read done on a card where a run failed or stopped says how
    /// that run ended. Otherwise the plan's own header. `None`: the plan's
    /// own header stands (a one-step plan has none).
    pub fn header_with_runs(&self, runs: &[RunPhase]) -> Option<String> {
        if self.steps < 2 || runs.is_empty() || !self.settled {
            return None;
        }
        if runs.iter().any(|phase| !phase.is_terminal()) {
            return Some(format!(
                "\u{23f3} Continuing in the background \u{b7} {} of {} done",
                self.done, self.steps
            ));
        }
        let worst = runs
            .iter()
            .copied()
            .filter(|phase| matches!(phase, RunPhase::Failed | RunPhase::Stopped))
            .max_by_key(|phase| matches!(phase, RunPhase::Failed))?;
        (self.done == self.steps).then(|| {
            format!(
                "{} \u{b7} {} of {} done",
                worst.helper_headline(false),
                self.done,
                self.steps
            )
        })
    }
}

/// How a turn's card ends, decided once from its typed state for every
/// channel path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CardEnd {
    /// The card is the record of the work: it stays, settled to its final
    /// header (each helper's end, the plan's closing state).
    Keep,
    /// The card was only progress for one step: it goes, and the reply
    /// says what was done.
    Collapse,
}

impl CardEnd {
    /// A card with a helper on it, or a plan of more than one step, is
    /// kept; only a single-step card with no helper collapses into the
    /// reply.
    pub fn of(plan: Option<&PlanCard>, helpers: usize) -> Self {
        if helpers > 0 || plan.is_some_and(|plan| plan.steps > 1) {
            Self::Keep
        } else {
            Self::Collapse
        }
    }
}

/// How a plan step's state is known.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StepEvidence {
    /// Typed evidence settled it (a receipt, a helper's run record), or
    /// it is not settled yet.
    #[default]
    Settled,
    /// Completed on the executing model's word alone. A step that changes
    /// nothing (a check, a read) needs no receipt: the reply reports what
    /// it found. Only a step that declared a side effect is flagged.
    ModelSaid,
    /// It was handed to a helper that never started, so nothing worked
    /// on it.
    HelperNotStarted,
}

impl StepEvidence {
    pub fn is_settled(&self) -> bool {
        *self == Self::Settled
    }
}