autumn-plugin-agent 0.2.0

Autumn plugin: provider-agnostic, always-on LLM agent harness (tool calling, sessions, memory, approvals, heartbeats) for OpenAI-compatible and Anthropic APIs.
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
560
561
562
563
564
565
566
567
568
569
570
//! Always-on behaviour: heartbeats, follow-ups, and delivery.
//!
//! An always-on agent wakes up by itself. This module gives it three ways:
//!
//! * **Heartbeat** — a [`Heartbeat`] registers an Autumn scheduled task
//!   (fixed delay or cron). Each tick runs the agent with a check-in prompt.
//!   If nothing needs attention, the agent answers [`HEARTBEAT_OK`] and the
//!   harness stays silent. Heartbeats run with read-only tools by default:
//!   the agent may look and take notes, not act.
//! * **Follow-ups** — the `schedule_followup` tool lets the agent book its
//!   own next wake-up ("check the deploy in 20 minutes") as a delayed
//!   `agent_run` job.
//! * **Precheck** — a cheap app callback can skip a heartbeat tick before any
//!   model call ("no new orders, nothing to look at").
//!
//! Whatever a background run has to say goes to a [`Delivery`]: the app's
//! bridge to mail, chat, push, or an in-app inbox. [`LogDelivery`] is the
//! default.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use autumn_web::task::{Schedule, TaskCoordination, TaskInfo};
use autumn_web::{AppState, AutumnResult};
use futures::future::BoxFuture;
use serde::{Deserialize, Serialize};

use crate::agent::{AgentOutcome, AgentRuntime};
use crate::error::{AgentError, ErrorKind};
use crate::ids::{RunId, SessionId};
use crate::jobs::{AgentRunArgs, RunOrigin, enqueue_agent_run_in, execute_run};
use crate::memory::MemoryScope;
use crate::policy::{Strictest, ToolPolicy, ToolRules};
use crate::tools::{Tool, ToolContext, ToolEffect};

/// The answer that means "nothing needs attention".
pub const HEARTBEAT_OK: &str = "HEARTBEAT_OK";

/// Longest extra text an answer may carry next to [`HEARTBEAT_OK`] and still
/// count as silent.
pub const SILENT_ACK_MAX_CHARS: usize = 300;

/// The default heartbeat prompt.
pub const DEFAULT_HEARTBEAT_PROMPT: &str = "This is a scheduled heartbeat check-in. Review your memory, your standing instructions, and anything your tools can show you. If something needs the user's attention, report it in a few sentences. If nothing needs attention, reply with exactly HEARTBEAT_OK.";

/// `true` when a background answer should not be delivered: it is
/// [`HEARTBEAT_OK`], or starts or ends with it and adds at most
/// [`SILENT_ACK_MAX_CHARS`] characters.
#[must_use]
pub fn is_silent(text: &str) -> bool {
    let text = text.trim();
    let rest = text
        .strip_prefix(HEARTBEAT_OK)
        .or_else(|| text.strip_suffix(HEARTBEAT_OK));
    rest.is_some_and(|rest| rest.trim().chars().count() <= SILENT_ACK_MAX_CHARS)
}

/// What started a background run that has something to say.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReportSource {
    /// A heartbeat tick.
    Heartbeat,
    /// A follow-up the agent scheduled.
    Followup,
    /// An `agent_run` job the app enqueued with `deliver` set.
    Job,
    /// A resumed run.
    Resume,
}

/// A message from a background run to a person.
#[derive(Debug, Clone, PartialEq)]
pub struct Report {
    /// What started the run.
    pub source: ReportSource,
    /// The run's id.
    pub run_id: RunId,
    /// The session the run belongs to, if any. Use it to route the report
    /// back to the right chat thread.
    pub session_id: Option<SessionId>,
    /// Text for a person: the answer, or what waits for approval.
    pub text: String,
    /// The full outcome. A paused run carries the
    /// [`RunState`](crate::agent::RunState) to store for the reviewer.
    pub outcome: AgentOutcome,
}

/// Where background results go: mail, chat, push, an inbox table.
pub trait Delivery: Send + Sync + std::fmt::Debug {
    /// Deliver one report.
    fn deliver<'a>(&'a self, report: &'a Report) -> BoxFuture<'a, Result<(), AgentError>>;
}

/// Logs reports with `tracing`. The default [`Delivery`].
#[derive(Debug, Clone, Copy, Default)]
pub struct LogDelivery;

impl Delivery for LogDelivery {
    fn deliver<'a>(&'a self, report: &'a Report) -> BoxFuture<'a, Result<(), AgentError>> {
        tracing::info!(
            source = ?report.source,
            run_id = %report.run_id,
            session = report.session_id.as_ref().map(SessionId::as_str),
            text = %report.text,
            "agent report"
        );
        Box::pin(std::future::ready(Ok(())))
    }
}

/// The text a person should see for an outcome, or `None` to stay quiet.
///
/// Final answers are delivered unless [`is_silent`]; paused runs always are
/// (someone has to approve). Budget and loop stops are only logged.
#[must_use]
pub fn report_text(outcome: &AgentOutcome) -> Option<String> {
    match outcome {
        AgentOutcome::Completed { text, .. } if !is_silent(text) => Some(text.clone()),
        AgentOutcome::AwaitingApproval { state } => {
            let lines: Vec<String> = state
                .awaiting()
                .map(|pending| format!("- {} {}", pending.call.name, pending.call.arguments))
                .collect();
            Some(format!(
                "The agent wants to run these calls and needs approval:\n{}",
                lines.join("\n")
            ))
        }
        _ => None,
    }
}

/// Deliver an outcome when it has something to say. Delivery failures are
/// logged, not returned: failing the job would re-run the whole agent.
pub(crate) async fn deliver_outcome(
    delivery: &dyn Delivery,
    source: ReportSource,
    run_id: &RunId,
    session_id: Option<&SessionId>,
    outcome: &AgentOutcome,
) {
    let Some(text) = report_text(outcome) else {
        tracing::debug!(run_id = %run_id, ?source, "background run had nothing to report");
        return;
    };
    let report = Report {
        source,
        run_id: run_id.clone(),
        session_id: session_id.cloned(),
        text,
        outcome: outcome.clone(),
    };
    if let Err(err) = delivery.deliver(&report).await {
        tracing::error!(run_id = %run_id, error = %err, "cannot deliver the agent report");
    }
}

/// A cheap app check that can skip a heartbeat tick before any model call.
pub type Precheck = Arc<dyn Fn(AppState) -> BoxFuture<'static, bool> + Send + Sync>;

/// When a heartbeat fires.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeartbeatSchedule {
    /// After a fixed delay from the end of the previous tick.
    Every(Duration),
    /// On a 6-field cron expression (`sec min hour day month weekday`).
    Cron {
        /// The expression, for example `"0 */30 8-18 * * Mon-Fri"`.
        expression: String,
        /// IANA time zone, for example `"Europe/Oslo"`. UTC when `None`.
        timezone: Option<String>,
    },
}

/// A periodic check-in for an always-on agent.
///
/// ```rust
/// use std::time::Duration;
/// use autumn_plugin_agent::proactive::Heartbeat;
///
/// // Every 30 minutes during office hours, Oslo time, in the "ops" session.
/// let heartbeat = Heartbeat::cron("0 */30 8-18 * * Mon-Fri")
///     .timezone("Europe/Oslo")
///     .session("ops");
/// # let _ = Heartbeat::every(Duration::from_secs(1_800));
/// ```
#[derive(Clone)]
pub struct Heartbeat {
    schedule: HeartbeatSchedule,
    prompt: String,
    session: Option<SessionId>,
    memory_scope: Option<MemoryScope>,
    read_only: bool,
    coordination: TaskCoordination,
    precheck: Option<Precheck>,
}

impl std::fmt::Debug for Heartbeat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Heartbeat")
            .field("schedule", &self.schedule)
            .field("session", &self.session)
            .field("memory_scope", &self.memory_scope)
            .field("read_only", &self.read_only)
            .field("coordination", &self.coordination)
            .field("precheck", &self.precheck.is_some())
            .finish_non_exhaustive()
    }
}

impl Heartbeat {
    /// The scheduled-task name the heartbeat registers.
    pub const TASK_NAME: &'static str = "agent_heartbeat";

    fn with_schedule(schedule: HeartbeatSchedule) -> Self {
        Self {
            schedule,
            prompt: DEFAULT_HEARTBEAT_PROMPT.to_owned(),
            session: None,
            memory_scope: None,
            read_only: true,
            coordination: TaskCoordination::Fleet,
            precheck: None,
        }
    }

    /// Tick after a fixed delay from the end of the previous tick.
    #[must_use]
    pub fn every(interval: Duration) -> Self {
        Self::with_schedule(HeartbeatSchedule::Every(interval))
    }

    /// Tick on a 6-field cron expression (`sec min hour day month weekday`).
    #[must_use]
    pub fn cron(expression: impl Into<String>) -> Self {
        Self::with_schedule(HeartbeatSchedule::Cron {
            expression: expression.into(),
            timezone: None,
        })
    }

    /// The IANA time zone for a cron schedule. Ignored for fixed delays.
    #[must_use]
    pub fn timezone(mut self, timezone: impl Into<String>) -> Self {
        if let HeartbeatSchedule::Cron { timezone: tz, .. } = &mut self.schedule {
            *tz = Some(timezone.into());
        }
        self
    }

    /// Replace the check-in prompt. Keep the [`HEARTBEAT_OK`] instruction
    /// in it, or every tick will be delivered.
    #[must_use]
    pub fn prompt(mut self, prompt: impl Into<String>) -> Self {
        self.prompt = prompt.into();
        self
    }

    /// Run ticks inside this session, so the agent sees earlier ticks.
    #[must_use]
    pub fn session(mut self, session: impl Into<SessionId>) -> Self {
        self.session = Some(session.into());
        self
    }

    /// Bind memory to this scope instead of [`MemoryScope::agent`].
    #[must_use]
    pub fn memory_scope(mut self, scope: MemoryScope) -> Self {
        self.memory_scope = Some(scope);
        self
    }

    /// Let ticks use every tool the app policy allows, not only read-only
    /// and internal ones.
    #[must_use]
    pub const fn allow_actions(mut self) -> Self {
        self.read_only = false;
        self
    }

    /// Run on every replica instead of once per tick across the fleet.
    #[must_use]
    pub const fn per_replica(mut self) -> Self {
        self.coordination = TaskCoordination::PerReplica;
        self
    }

    /// Skip a tick, before any model call, when `check` answers `false`.
    #[must_use]
    pub fn precheck<F, Fut>(mut self, check: F) -> Self
    where
        F: Fn(AppState) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = bool> + Send + 'static,
    {
        self.precheck = Some(Arc::new(move |state| Box::pin(check(state))));
        self
    }

    /// The configured schedule.
    #[must_use]
    pub const fn schedule(&self) -> &HeartbeatSchedule {
        &self.schedule
    }

    /// Check the schedule and prompt.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorKind::Config`] for an interval under one second, a
    /// blank cron expression, or a blank prompt.
    pub fn validate(&self) -> Result<(), AgentError> {
        match &self.schedule {
            HeartbeatSchedule::Every(interval) if *interval < Duration::from_secs(1) => {
                return Err(AgentError::new(
                    ErrorKind::Config,
                    "heartbeat interval must be at least one second",
                ));
            }
            HeartbeatSchedule::Cron { expression, .. } if expression.trim().is_empty() => {
                return Err(AgentError::new(
                    ErrorKind::Config,
                    "heartbeat cron expression must not be blank",
                ));
            }
            _ => {}
        }
        if self.prompt.trim().is_empty() {
            return Err(AgentError::new(
                ErrorKind::Config,
                "heartbeat prompt must not be blank",
            ));
        }
        Ok(())
    }

    /// The Autumn scheduled task for this heartbeat.
    pub(crate) fn task_info(&self) -> TaskInfo {
        let schedule = match &self.schedule {
            HeartbeatSchedule::Every(interval) => Schedule::FixedDelay(*interval),
            HeartbeatSchedule::Cron {
                expression,
                timezone,
            } => Schedule::Cron {
                expression: expression.clone(),
                timezone: timezone.clone(),
            },
        };
        TaskInfo {
            name: Self::TASK_NAME.to_owned(),
            schedule,
            coordination: self.coordination,
            handler: heartbeat_tick,
        }
    }

    /// Run one tick. Returns `None` when the precheck skipped it.
    ///
    /// # Errors
    ///
    /// Returns [`AgentError`] when the run fails (see
    /// [`Agent::run`](crate::agent::Agent::run)).
    pub async fn tick(
        &self,
        runtime: &AgentRuntime,
        state: &AppState,
    ) -> Result<Option<AgentOutcome>, AgentError> {
        if let Some(check) = &self.precheck
            && !check(state.clone()).await
        {
            tracing::debug!("heartbeat precheck found nothing to do; skipping the tick");
            return Ok(None);
        }
        let args = AgentRunArgs::new(self.prompt.clone())
            .session(self.session.clone())
            .memory_scope(self.memory_scope.clone())
            .deliver(true)
            .origin(RunOrigin::Heartbeat);
        let policy: Option<Arc<dyn ToolPolicy>> = self.read_only.then(|| {
            Arc::new(Strictest::new(vec![
                runtime.policy(),
                Arc::new(ToolRules::read_only()),
            ])) as Arc<dyn ToolPolicy>
        });
        execute_run(runtime, args, policy).await.map(Some)
    }
}

/// The heartbeat as installed on app state by the plugin's startup hook.
#[derive(Debug, Clone)]
pub(crate) struct HeartbeatSettings(pub(crate) Heartbeat);

/// The scheduled-task handler behind [`Heartbeat`].
fn heartbeat_tick(state: AppState) -> Pin<Box<dyn Future<Output = AutumnResult<()>> + Send>> {
    Box::pin(async move {
        let (Some(runtime), Some(settings)) = (
            state.extension::<AgentRuntime>(),
            state.extension::<HeartbeatSettings>(),
        ) else {
            tracing::warn!("agent heartbeat fired before the agent plugin started");
            return Ok(());
        };
        settings
            .0
            .tick(&runtime, &state)
            .await
            .map(|_| ())
            .map_err(|err| {
                tracing::error!(error = %err, "agent heartbeat failed");
                err.into_autumn_error()
            })
    })
}

/// The `schedule_followup` tool: the agent books its own next wake-up.
///
/// The follow-up runs as a delayed `agent_run` job in the same session, with
/// delivery on. Turn it on with
/// [`AgentPlugin::followups`](crate::plugin::AgentPlugin::followups).
#[derive(Debug, Clone)]
pub struct FollowupTool {
    max_delay: Duration,
    memory_scope: Option<MemoryScope>,
    depth: u32,
}

impl FollowupTool {
    /// Longest prompt a follow-up may carry, in characters.
    pub const MAX_PROMPT_CHARS: usize = 2_000;

    /// Longest chain of follow-ups (a follow-up that schedules a follow-up
    /// that ...). Stops an agent from waking itself forever.
    pub const MAX_CHAIN: u32 = 10;

    /// Allow follow-ups up to `max_delay` from now.
    #[must_use]
    pub const fn new(max_delay: Duration) -> Self {
        Self {
            max_delay,
            memory_scope: None,
            depth: 0,
        }
    }

    /// The run this tool serves is `depth` follow-ups deep.
    #[must_use]
    pub const fn depth(mut self, depth: u32) -> Self {
        self.depth = depth;
        self
    }

    /// Run follow-ups with memory bound to this scope.
    #[must_use]
    pub fn memory_scope(mut self, scope: MemoryScope) -> Self {
        self.memory_scope = Some(scope);
        self
    }

    /// Check the input and build the delayed job's arguments.
    fn plan(
        &self,
        input: &serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<(AgentRunArgs, Duration), AgentError> {
        let depth = self.depth.saturating_add(1);
        if depth > Self::MAX_CHAIN {
            return Err(AgentError::new(
                ErrorKind::Tool,
                format!(
                    "this run is already {} follow-ups deep; finish now and report instead of scheduling another",
                    self.depth
                ),
            ));
        }
        let max_minutes = self.max_delay.as_secs() / 60;
        let minutes = input
            .get("delay_minutes")
            .and_then(serde_json::Value::as_u64)
            .filter(|minutes| (1..=max_minutes).contains(minutes))
            .ok_or_else(|| {
                AgentError::new(
                    ErrorKind::Tool,
                    format!("delay_minutes must be a whole number from 1 to {max_minutes}"),
                )
            })?;
        let prompt = input
            .get("prompt")
            .and_then(serde_json::Value::as_str)
            .map(str::trim)
            .filter(|prompt| !prompt.is_empty())
            .ok_or_else(|| {
                AgentError::new(ErrorKind::Tool, "give a `prompt` for the follow-up run")
            })?;
        if prompt.chars().count() > Self::MAX_PROMPT_CHARS {
            return Err(AgentError::new(
                ErrorKind::Tool,
                format!(
                    "the follow-up prompt must be at most {} characters",
                    Self::MAX_PROMPT_CHARS
                ),
            ));
        }
        let mut args = AgentRunArgs::new(prompt)
            .session(ctx.session_id.clone())
            .memory_scope(self.memory_scope.clone())
            .deliver(true)
            .origin(RunOrigin::Followup);
        args.followup_depth = depth;
        Ok((args, Duration::from_secs(minutes.saturating_mul(60))))
    }
}

impl Tool for FollowupTool {
    fn name(&self) -> &'static str {
        "schedule_followup"
    }

    fn description(&self) -> &'static str {
        "Wake yourself up later: after delay_minutes, a new run starts with `prompt` in this conversation, and its answer is sent to the user. Use it to check back on something that is not ready yet."
    }

    fn input_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "delay_minutes": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": self.max_delay.as_secs() / 60,
                },
                "prompt": {
                    "type": "string",
                    "description": "What your future self should do, with every detail it needs.",
                }
            },
            "required": ["delay_minutes", "prompt"]
        })
    }

    fn effect(&self) -> ToolEffect {
        ToolEffect::Internal
    }

    fn execute<'a>(
        &'a self,
        input: serde_json::Value,
        ctx: &'a ToolContext,
    ) -> Pin<Box<dyn Future<Output = Result<serde_json::Value, AgentError>> + Send + 'a>> {
        Box::pin(async move {
            let (args, delay) = self.plan(&input, ctx)?;
            let run_id = args.run_id.clone();
            enqueue_agent_run_in(args, delay).await.map_err(|err| {
                AgentError::new(
                    ErrorKind::Tool,
                    format!("cannot schedule the follow-up: {err}"),
                )
            })?;
            Ok(serde_json::json!({
                "scheduled": true,
                "in_minutes": delay.as_secs() / 60,
                "run_id": run_id,
            }))
        })
    }
}

#[cfg(test)]
mod tests;