aither-agent 0.15.0

AI agent framework with planning, memory, and tool execution for aither
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Built-in context sources.
//!
//! These three cover the ambient state every terminal-first agent has: the
//! checklist it is working through, the terminals still running behind it,
//! and the skills activated for the run. Each one used to be a special case
//! inside the agent loop, with its own field on `Agent`, its own
//! repopulation call and its own alert path. As [`ContextSource`]
//! implementations they are ordinary registrations with nothing privileged
//! about them, and the state each one needs to remember between turns —
//! previous file contents, how many turns have passed without a change —
//! belongs to the source instead of the agent.

#[cfg(feature = "skills")]
use std::future::Future;
use std::path::PathBuf;

use askama::Template;

use super::source::{Block, ContextSource};
use crate::working_docs::{self, AnyTaskBlockerResolver, WorkingDocsSnapshot};

#[derive(Template)]
#[template(path = "tasks_document.txt", escape = "none")]
struct TasksDocumentTemplate {
    /// The whole document, at session start and after a reassembly.
    tasks: Option<String>,
    /// The diff of a change seen since the document was last shown.
    changes: Option<String>,
}

#[derive(Template)]
#[template(path = "tasks_stale.txt", escape = "none")]
struct TasksStaleTemplate {
    content: String,
}

#[derive(Template)]
#[template(path = "tasks_continue.txt", escape = "none")]
struct TasksContinueTemplate;

#[derive(Template)]
#[template(path = "system_reminder.txt", escape = "none")]
struct SystemReminderTemplate {
    content: String,
}

/// Renders a typed template into a block under `tag`.
///
/// # Panics
///
/// Panics if the template fails to render, which is a bug in the template.
fn block(tag: &str, template: &impl Template) -> Block {
    Block::new(
        tag,
        template
            .render()
            .expect("context block template must render"),
    )
}

/// Brings `tasks.md` into the conversation and nags when it stops being maintained.
///
/// The document is the canonical task list: it outlives compaction, which the
/// conversation does not, so a model that stops updating it loses the only
/// durable record of its own plan. Staleness is measured in tool turns rather
/// than wall-clock time — a turn that ran tools without touching the file is
/// the actual signal — and the counter resets on any content change, as well
/// as while the checklist has no unchecked items, because a finished
/// checklist is not stale. The alert fires once per stale episode.
///
/// The document enters the conversation as durable alerts, never as a block
/// re-rendered into every request: whole at the start of the session and
/// after a reassembly wiped the earlier alerts, and otherwise only as the
/// diff of a change, once, when the change is seen.
#[derive(Debug)]
pub struct TasksDocument {
    /// Sandbox root holding `tasks.md`.
    sandbox_dir: PathBuf,
    /// Tool turns without a change before alerting.
    stale_after_turns: usize,
    /// What the conversation last received of the document; `None` until the
    /// session start has shown it.
    shown: Option<WorkingDocsSnapshot>,
    /// Content observed at the previous tool turn (`None` = file absent).
    last_content: Option<String>,
    /// Whether a baseline observation exists yet.
    seen: bool,
    /// Consecutive tool turns without a content change.
    stale_turns: usize,
    /// Whether the current stale episode already alerted.
    alerted: bool,
    /// Resolves `BLOCKING` marks when the host can say what still waits.
    blocker_resolver: Option<AnyTaskBlockerResolver>,
}

impl TasksDocument {
    /// Watches `tasks.md` in `sandbox_dir`, alerting after `stale_after_turns`.
    #[must_use]
    pub fn new(sandbox_dir: impl Into<PathBuf>, stale_after_turns: usize) -> Self {
        Self {
            sandbox_dir: sandbox_dir.into(),
            stale_after_turns,
            shown: None,
            last_content: None,
            seen: false,
            stale_turns: 0,
            alerted: false,
            blocker_resolver: None,
        }
    }

    /// Resolves `BLOCKING` mark payloads through `resolver`: a mark it
    /// reports dead no longer holds the item. Without it every mark is
    /// trusted.
    #[must_use]
    pub fn with_blocker_resolver(mut self, resolver: AnyTaskBlockerResolver) -> Self {
        self.blocker_resolver = Some(resolver);
        self
    }
}

impl ContextSource for TasksDocument {
    async fn on_request(&mut self, reassembled: bool) -> Option<Block> {
        let docs = working_docs::read_snapshot(&self.sandbox_dir).await;
        let (tasks, changes) = match self.shown.as_ref() {
            Some(shown) if !reassembled => (None, working_docs::tasks_md_diff(shown, &docs)),
            _ => (docs.tasks_md.clone(), None),
        };
        self.shown = Some(docs);
        if tasks.is_none() && changes.is_none() {
            return None;
        }
        Some(block(
            "tasks_document",
            &TasksDocumentTemplate { tasks, changes },
        ))
    }

    async fn on_tool_turn_end(&mut self) -> Option<Block> {
        let docs = working_docs::read_snapshot(&self.sandbox_dir).await;
        let threshold = self.stale_after_turns;

        if !self.seen {
            self.seen = true;
            self.last_content = docs.tasks_md;
            return None;
        }
        if self.last_content != docs.tasks_md {
            self.last_content = docs.tasks_md;
            self.stale_turns = 0;
            self.alerted = false;
            return None;
        }

        let missing = match &docs.tasks_md {
            Some(content) => {
                if working_docs::has_unblocked_markdown_tasks(
                    content,
                    self.blocker_resolver.as_ref(),
                )
                .await
                {
                    false
                } else {
                    self.stale_turns = 0;
                    self.alerted = false;
                    return None;
                }
            }
            None => true,
        };

        self.stale_turns += 1;
        if self.stale_turns < threshold || self.alerted {
            return None;
        }
        self.alerted = true;
        let content = if missing {
            format!(
                "{threshold} tool turns have run without a tasks.md. For multi-step work, create tasks.md in the sandbox root with a checklist of the plan — it is the canonical task document and survives context compaction."
            )
        } else {
            format!(
                "tasks.md has unchecked items but has not been updated for {threshold} tool turns. Mark finished items and keep the checklist in sync with actual progress."
            )
        };
        Some(block("tasks_stale", &TasksStaleTemplate { content }))
    }

    async fn on_final_turn(&mut self) -> Option<Block> {
        let docs = working_docs::read_snapshot(&self.sandbox_dir).await;
        if !docs
            .has_unblocked_items(self.blocker_resolver.as_ref())
            .await
        {
            return None;
        }
        Some(block(
            "system_reminder",
            &SystemReminderTemplate {
                content: TasksContinueTemplate
                    .render()
                    .expect("tasks continue template must render"),
            },
        ))
    }
}

/// Surfaces the terminals still running behind the agent.
#[derive(Debug)]
pub struct BackgroundJobs {
    registry: aither_sandbox::JobRegistry,
}

impl BackgroundJobs {
    /// Reports the jobs tracked by `registry`.
    #[must_use]
    pub const fn new(registry: aither_sandbox::JobRegistry) -> Self {
        Self { registry }
    }
}

impl ContextSource for BackgroundJobs {
    async fn render(&self) -> Option<Block> {
        let running = self.registry.format_running_jobs().await;
        if running.is_empty() {
            return None;
        }
        Some(block(
            "system_reminder",
            &SystemReminderTemplate {
                content: format!(
                    "Running background terminals:\n{running}Use terminal_read for incremental output, read redirected output files via terminal commands like head/tail/rg/cat when needed, terminal_input for stdin, and terminal_kill to stop tasks."
                ),
            },
        ))
    }
}

#[cfg(feature = "skills")]
#[derive(Template)]
#[template(path = "skill_instruction.txt", escape = "none")]
struct SkillInstructionTemplate<'a> {
    name: &'a str,
    description: &'a str,
    instructions: &'a str,
    allowed_tools: Option<&'a [String]>,
    resource_paths: Option<&'a [String]>,
}

/// Surfaces the instructions of the skills activated for the current run.
#[cfg(feature = "skills")]
#[derive(Debug, Default)]
pub struct ActiveSkills {
    skills: Vec<aither_skills::Skill>,
}

#[cfg(feature = "skills")]
impl ActiveSkills {
    /// Creates an empty set of active skills.
    #[must_use]
    pub const fn new() -> Self {
        Self { skills: Vec::new() }
    }

    /// Replaces the activated skills.
    pub fn set(&mut self, skills: Vec<aither_skills::Skill>) {
        self.skills = skills;
    }

    /// The activated skills.
    #[must_use]
    pub fn skills(&self) -> &[aither_skills::Skill] {
        &self.skills
    }

    /// Whether any skill is activated.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.skills.is_empty()
    }
}

#[cfg(feature = "skills")]
impl ContextSource for ActiveSkills {
    fn render(&self) -> impl Future<Output = Option<Block>> + Send {
        std::future::ready(self.render_skills())
    }
}

#[cfg(feature = "skills")]
impl ActiveSkills {
    /// Renders every activated skill into a single block.
    fn render_skills(&self) -> Option<Block> {
        if self.skills.is_empty() {
            return None;
        }
        let mut rendered = String::new();
        for skill in &self.skills {
            let mut resource_paths = skill.resources.keys().cloned().collect::<Vec<_>>();
            resource_paths.sort();
            let instruction = SkillInstructionTemplate {
                name: &skill.name,
                description: &skill.description,
                instructions: &skill.instructions,
                allowed_tools: skill.allowed_tools.as_deref(),
                resource_paths: (!resource_paths.is_empty()).then_some(resource_paths.as_slice()),
            }
            .render()
            .expect("skill instruction template must render");
            if !rendered.is_empty() {
                rendered.push('\n');
            }
            rendered.push_str(&instruction);
        }
        Some(Block::new("skill_instructions", rendered))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    async fn write_tasks(root: &std::path::Path, content: &str) {
        async_fs::write(root.join("tasks.md"), content)
            .await
            .expect("write tasks.md");
    }

    #[tokio::test]
    async fn an_absent_tasks_document_renders_nothing() {
        let root = tempfile::tempdir().expect("tempdir");
        let source = TasksDocument::new(root.path(), 4);
        assert!(source.render().await.is_none());
    }

    #[tokio::test]
    async fn the_document_is_never_rendered_into_the_tail() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] first\n").await;
        let source = TasksDocument::new(root.path(), 4);
        assert!(source.render().await.is_none());
    }

    #[tokio::test]
    async fn the_session_start_carries_the_whole_document() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] first\n").await;
        let mut source = TasksDocument::new(root.path(), 4);

        let block = source.on_request(false).await.expect("shows the document");
        assert!(block.content().contains("Contents of tasks.md"));
        assert!(block.content().contains("- [ ] first"));
        assert!(!block.content().contains("Changes to tasks.md"));
    }

    #[tokio::test]
    async fn an_unchanged_document_adds_nothing_after_the_start() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] first\n").await;
        let mut source = TasksDocument::new(root.path(), 4);

        assert!(source.on_request(false).await.is_some());
        assert!(source.on_request(false).await.is_none());
        assert!(source.on_request(false).await.is_none());
    }

    #[tokio::test]
    async fn a_change_is_shown_once_as_its_diff() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] first\n").await;
        let mut source = TasksDocument::new(root.path(), 4);
        source.on_request(false).await.expect("session start");

        write_tasks(root.path(), "- [x] first\n- [ ] second\n").await;
        let block = source.on_request(false).await.expect("shows the diff");
        assert!(block.content().contains("Changes to tasks.md"));
        assert!(block.content().contains("+ - [ ] second"));
        assert!(
            !block.content().contains("Contents of tasks.md"),
            "a change must not resend the document: {}",
            block.content()
        );
        assert!(source.on_request(false).await.is_none());
    }

    #[tokio::test]
    async fn a_reassembly_shows_the_whole_document_again() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] first\n").await;
        let mut source = TasksDocument::new(root.path(), 4);
        source.on_request(false).await.expect("session start");

        let block = source.on_request(true).await.expect("shows the document");
        assert!(block.content().contains("Contents of tasks.md"));
        assert!(source.on_request(false).await.is_none());
    }

    #[tokio::test]
    async fn an_absent_document_is_never_shown() {
        let root = tempfile::tempdir().expect("tempdir");
        let mut source = TasksDocument::new(root.path(), 4);
        assert!(source.on_request(false).await.is_none());
        assert!(source.on_request(true).await.is_none());
    }

    #[tokio::test]
    async fn staleness_alerts_once_per_episode_and_resets_on_change() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] work\n").await;
        let mut source = TasksDocument::new(root.path(), 2);

        // First turn establishes the baseline.
        assert!(source.on_tool_turn_end().await.is_none());
        // Second turn is the first stale one; the threshold is two.
        assert!(source.on_tool_turn_end().await.is_none());
        let alert = source.on_tool_turn_end().await.expect("alert fires");
        assert!(alert.content().contains("has unchecked items"));
        assert!(
            source.on_tool_turn_end().await.is_none(),
            "the alert must not repeat within one episode"
        );

        write_tasks(root.path(), "- [x] work\n- [ ] more\n").await;
        assert!(source.on_tool_turn_end().await.is_none());
        assert!(source.on_tool_turn_end().await.is_none());
        assert!(
            source.on_tool_turn_end().await.is_some(),
            "a new stale episode must alert again"
        );
    }

    #[tokio::test]
    async fn a_complete_checklist_is_never_stale() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [x] done\n").await;
        let mut source = TasksDocument::new(root.path(), 1);

        assert!(source.on_tool_turn_end().await.is_none());
        for _ in 0..5 {
            assert!(source.on_tool_turn_end().await.is_none());
        }
    }

    #[tokio::test]
    async fn a_missing_document_is_reported_differently() {
        let root = tempfile::tempdir().expect("tempdir");
        let mut source = TasksDocument::new(root.path(), 1);

        assert!(source.on_tool_turn_end().await.is_none());
        let alert = source.on_tool_turn_end().await.expect("alert fires");
        assert!(alert.content().contains("without a tasks.md"));
    }

    #[tokio::test]
    async fn unchecked_items_block_the_final_turn() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] work\n").await;
        let mut source = TasksDocument::new(root.path(), 4);
        assert!(source.on_final_turn().await.is_some());

        write_tasks(root.path(), "- [x] work\n").await;
        assert!(source.on_final_turn().await.is_none());
    }

    #[tokio::test]
    async fn blocked_items_hold_no_turn_open() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(
            root.path(),
            "- [ ] ship it BLOCKING req-123\n- [ ] pick a topic BLOCKING waiting on the user\n",
        )
        .await;
        let mut source = TasksDocument::new(root.path(), 4);
        assert!(source.on_final_turn().await.is_none());
    }

    #[tokio::test]
    async fn a_bare_blocking_word_is_not_a_mark() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] work BLOCKING\n").await;
        let mut source = TasksDocument::new(root.path(), 4);
        assert!(source.on_final_turn().await.is_some());
    }

    #[tokio::test]
    async fn a_blocked_item_among_runnable_ones_still_objects() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] work\n- [ ] ship it BLOCKING req-123\n").await;
        let mut source = TasksDocument::new(root.path(), 4);
        assert!(source.on_final_turn().await.is_some());
    }

    #[tokio::test]
    async fn blocked_items_are_never_stale() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] ship it BLOCKING req-123\n").await;
        let mut source = TasksDocument::new(root.path(), 1);

        assert!(source.on_tool_turn_end().await.is_none());
        for _ in 0..5 {
            assert!(source.on_tool_turn_end().await.is_none());
        }
    }

    struct TestResolver;
    impl crate::working_docs::TaskBlockerResolver for TestResolver {
        fn is_open(&self, mark: &str) -> impl std::future::Future<Output = bool> + Send {
            // Mirrors a host resolver: only issued-and-still-open marks
            // hold; unknown payloads are free text and trusted.
            std::future::ready(!matches!(mark, "req-answered" | "req-withdrawn"))
        }
    }

    fn resolved() -> AnyTaskBlockerResolver {
        AnyTaskBlockerResolver::new(TestResolver)
    }

    #[tokio::test]
    async fn a_dead_mark_leaves_the_item_runnable() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] pick a db BLOCKING req-answered\n").await;
        let mut source = TasksDocument::new(root.path(), 4).with_blocker_resolver(resolved());
        assert!(source.on_final_turn().await.is_some());
    }

    #[tokio::test]
    async fn a_live_mark_and_free_text_still_hold() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(
            root.path(),
            "- [ ] pick a db BLOCKING req-open\n- [ ] write poem BLOCKING waiting on the user\n",
        )
        .await;
        let mut source = TasksDocument::new(root.path(), 4).with_blocker_resolver(resolved());
        assert!(source.on_final_turn().await.is_none());
    }

    #[tokio::test]
    async fn a_dead_mark_counts_toward_staleness() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] pick a db BLOCKING req-withdrawn\n").await;
        let mut source = TasksDocument::new(root.path(), 1).with_blocker_resolver(resolved());
        assert!(source.on_tool_turn_end().await.is_none());
        assert!(source.on_tool_turn_end().await.is_some());
    }

    #[tokio::test]
    async fn the_continue_alert_holds_work_an_open_question_blocks() {
        let root = tempfile::tempdir().expect("tempdir");
        write_tasks(root.path(), "- [ ] work\n").await;
        let mut source = TasksDocument::new(root.path(), 4);
        let alert = source.on_final_turn().await.expect("alert fires");
        assert_eq!(
            alert.content(),
            "<system_reminder>tasks.md still has unblocked unchecked items; continue with them. An item waiting on an open ask_user answer — or on anything else the run cannot resolve — is marked BLOCKING <request_id or reason>: blocked items wait for what they name instead of holding the turn open. A mark naming a request that is no longer open does not hold.</system_reminder>"
        );
    }
}