Skip to main content

agentmux_srv_core/backend/jobs/
app_events.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! App events: something inside AgentMux happened, and a job on the `app_event` source starts a run
5//! (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md §3.2, §3.2.1).
6//!
7//! An observer on the broker reads each published event and keeps only the few it names (a turn that ended, an
8//! agent that failed); AgentMux's own start is the one more, said once; it does nothing else under the broker's locks but queue. A task then gives the event its
9//! typed fields, finds the enabled jobs whose filter it matches and starts each one's run through
10//! [`CronScheduler::fire_event`], which records it, applies policy, caps, the delay and the rate limit, and drops
11//! an event the job already heard. The run reads the fields as `{{trigger.*}}`.
12//!
13//! A job's filter names the event (`"event": "agent.turn_ended"`) and may name any of that event's fields
14//! (`"agent": "<agent id>"`, `"outcome": "completed"`); an event matches when every entry equals its field.
15
16use std::sync::Arc;
17
18use serde::Deserialize;
19use serde_json::{json, Map, Value};
20
21use super::definition::{event_source, trigger_kind};
22use crate::backend::blockcontroller::health::{TriggerKind, TurnEnd, TurnTrigger};
23use crate::backend::cron::{CronScheduler, JobEvent};
24use crate::backend::mps::{Broker, MuxEvent, EVENT_AGENT_FAILURE, EVENT_AGENT_TURN};
25use crate::backend::obj::{meta_get_string, Block};
26use crate::backend::storage::store::Store;
27
28/// The events a job can name, as its filter's `event` says them.
29pub mod name {
30    /// An agent's turn, as its ledger reports it, is over.
31    pub const AGENT_TURN_ENDED: &str = "agent.turn_ended";
32    /// An agent's process failed (a limit, a sign-in, a crash).
33    pub const AGENT_CRASHED: &str = "agent.crashed";
34    /// AgentMux (srv) has started; `upgraded` says whether this start made an upgrade.
35    pub const APP_STARTED: &str = "app.started";
36    pub const ALL: [&str; 3] = [AGENT_TURN_ENDED, AGENT_CRASHED, APP_STARTED];
37}
38
39/// The fields an event carries besides its name: what a filter may name, and all a run reads of it.
40pub fn fields_of(event: &str) -> Option<&'static [&'static str]> {
41    match event {
42        name::AGENT_TURN_ENDED => Some(&["agent", "outcome", "cost_usd"]),
43        name::AGENT_CRASHED => Some(&["agent", "reason"]),
44        name::APP_STARTED => Some(&["version", "upgraded", "upgraded_from"]),
45        _ => None,
46    }
47}
48
49/// An `app_event` trigger's filter names one of the events, and only fields that event has.
50pub fn validate_filter(filter: &Map<String, Value>) -> Result<(), String> {
51    let Some(event) = filter.get("event").and_then(Value::as_str) else {
52        return Err(format!("trigger: an app_event filter names its event, one of {}", name::ALL.join(", ")));
53    };
54    let Some(fields) = fields_of(event) else {
55        return Err(format!("trigger: app event {event:?} is not one of {}", name::ALL.join(", ")));
56    };
57    for key in filter.keys().filter(|k| k.as_str() != "event") {
58        if !fields.contains(&key.as_str()) {
59            return Err(format!("trigger: {event} has no field {key:?}; it has {}", fields.join(", ")));
60        }
61    }
62    Ok(())
63}
64
65/// What the observer keeps of a broker event: enough to find the agent later, off the broker's locks.
66#[derive(Debug, Clone, PartialEq)]
67pub enum Raw {
68    TurnEnded { block_id: String, turn_id: u64, ended_at_ms: u64, outcome: &'static str, cost_usd: f64 },
69    Crashed { block_id: String, reason: String },
70    Started { version: String, upgraded_from: String, at_ms: i64 },
71}
72
73/// The fields of a published ledger that matter here.
74#[derive(Deserialize)]
75struct Ledger {
76    block_id: String,
77    turn_id: u64,
78    #[serde(default)]
79    ended_at_ms: Option<u64>,
80    #[serde(default)]
81    end: Option<TurnEnd>,
82    #[serde(default)]
83    trigger: Option<TurnTrigger>,
84    #[serde(default)]
85    cost_usd: f64,
86}
87
88/// The broker event as an app event, or `None` for one no job can name. AgentMux's own hidden turn (the memory
89/// reinjection) is not an agent's turn; a turn still running or settling has no end yet.
90pub fn raw_of(ev: &MuxEvent) -> Option<Raw> {
91    if ev.event == EVENT_AGENT_TURN {
92        let l = Ledger::deserialize(ev.data.as_ref()?).ok()?;
93        let outcome = match l.end? {
94            TurnEnd::Completed => "completed",
95            TurnEnd::Exited => "errored",
96        };
97        if l.trigger.is_some_and(|t| t.kind == TriggerKind::System) {
98            return None;
99        }
100        return Some(Raw::TurnEnded {
101            block_id: l.block_id,
102            turn_id: l.turn_id,
103            ended_at_ms: l.ended_at_ms.unwrap_or(0),
104            outcome,
105            cost_usd: l.cost_usd,
106        });
107    }
108    if ev.event == EVENT_AGENT_FAILURE {
109        let block_id = ev.scopes.iter().find_map(|s| s.strip_prefix("block:"))?.to_string();
110        let reason = ev.data.as_ref()?.get("code")?.as_str()?.to_string();
111        if reason.is_empty() {
112            return None;
113        }
114        return Some(Raw::Crashed { block_id, reason });
115    }
116    None
117}
118
119/// An app event with its fields: what [`fire_matching`] matches jobs against and hands to the run.
120#[derive(Debug, Clone, PartialEq)]
121pub struct AppEvent {
122    /// Unique per occurrence: a repeat of it starts nothing.
123    pub id: String,
124    pub name: &'static str,
125    /// `event` and the event's typed fields.
126    pub input: Map<String, Value>,
127}
128
129/// The agent a block runs: its id, or none for a block this machine does not know.
130fn agent_of(store: &Store, block_id: &str) -> String {
131    let block = store.get::<Block>(block_id).ok().flatten();
132    block.map(|b| meta_get_string(&b.meta, "agentId", "")).unwrap_or_default()
133}
134
135/// Gives a raw event its fields. Reads the store: off the async workers.
136pub fn event_of(raw: &Raw, store: &Store, now_ms: i64) -> AppEvent {
137    let mut input = Map::new();
138    match raw {
139        Raw::TurnEnded { block_id, turn_id, ended_at_ms, outcome, cost_usd } => {
140            input.insert("event".into(), json!(name::AGENT_TURN_ENDED));
141            input.insert("agent".into(), json!(agent_of(store, block_id)));
142            input.insert("outcome".into(), json!(outcome));
143            input.insert("cost_usd".into(), json!(cost_usd));
144            // A turn rejoined by a held message ends again later: that end is a new one.
145            AppEvent { id: format!("turn:{block_id}:{turn_id}:{ended_at_ms}"), name: name::AGENT_TURN_ENDED, input }
146        }
147        Raw::Crashed { block_id, reason } => {
148            input.insert("event".into(), json!(name::AGENT_CRASHED));
149            input.insert("agent".into(), json!(agent_of(store, block_id)));
150            input.insert("reason".into(), json!(reason));
151            AppEvent { id: format!("crash:{block_id}:{reason}:{now_ms}"), name: name::AGENT_CRASHED, input }
152        }
153        Raw::Started { version, upgraded_from, at_ms } => {
154            input.insert("event".into(), json!(name::APP_STARTED));
155            input.insert("version".into(), json!(version));
156            input.insert("upgraded".into(), json!(!upgraded_from.is_empty()));
157            input.insert("upgraded_from".into(), json!(upgraded_from));
158            AppEvent { id: format!("started:{version}:{at_ms}"), name: name::APP_STARTED, input }
159        }
160    }
161}
162
163/// Whether a job listens for this event: an enabled event job on `app_event` whose filter every entry the event meets.
164pub fn listens(job: &crate::backend::storage::cron::CronJob, event: &AppEvent) -> bool {
165    if !job.enabled || job.trigger_kind != trigger_kind::EVENT {
166        return false;
167    }
168    let t = &job.trigger_event;
169    if t.get("source").and_then(Value::as_str) != Some(event_source::APP_EVENT) {
170        return false;
171    }
172    let Some(filter) = t.get("filter").and_then(Value::as_object) else { return false };
173    filter.get("event").and_then(Value::as_str) == Some(event.name)
174        && filter.iter().all(|(key, want)| event.input.get(key).is_some_and(|have| same(have, want)))
175}
176
177/// A filter value equals a field: text and true or false by value, numbers as numbers.
178fn same(have: &Value, want: &Value) -> bool {
179    match (have, want) {
180        (Value::Number(a), Value::Number(b)) => a.as_f64() == b.as_f64(),
181        _ => have == want,
182    }
183}
184
185/// Starts the run of every job that listens for `event`. Returns how many jobs it was offered to. Reads the
186/// store: the job list is read off the async workers.
187pub async fn fire_matching(scheduler: &CronScheduler, jobs: &Arc<Store>, event: &AppEvent) -> usize {
188    let listing = jobs.clone();
189    let all = tokio::task::spawn_blocking(move || listing.cron_list_enabled()).await.ok().and_then(Result::ok).unwrap_or_default();
190    let mut offered = 0;
191    for job in all.iter().filter(|j| listens(j, event)) {
192        offered += 1;
193        let _ = scheduler
194            .fire_event(job, JobEvent { id: event.id.clone(), source: event_source::APP_EVENT.to_string(), input: Value::Object(event.input.clone()) })
195            .await;
196    }
197    offered
198}
199
200/// The most events waiting to be looked at: past it the newest are dropped, as a stuck consumer must not grow without bound.
201const QUEUE: usize = 1024;
202
203/// Start following the broker. `mstore` knows the agents' blocks, `jobs` the jobs.
204pub fn spawn(broker: &Arc<Broker>, mstore: Arc<Store>, jobs: Arc<Store>, scheduler: Arc<CronScheduler>) {
205    if tokio::runtime::Handle::try_current().is_err() {
206        return;
207    }
208    let (tx, mut rx) = tokio::sync::mpsc::channel::<Raw>(QUEUE);
209    // This start is the first event: a job that names `app.started` runs once for it, whatever else follows.
210    if let Some(start) = crate::backend::upgrade_notice::this_start() {
211        let _ = tx.try_send(Raw::Started { version: start.version, upgraded_from: start.upgraded_from.unwrap_or_default(), at_ms: start.at_ms });
212    }
213    // The observer runs inside `Broker::publish`, under its locks: it only parses and queues.
214    broker.add_observer(Arc::new(move |ev: &MuxEvent| {
215        if let Some(raw) = raw_of(ev) {
216            let _ = tx.try_send(raw);
217        }
218    }));
219    tokio::spawn(async move {
220        while let Some(raw) = rx.recv().await {
221            let now = agentmux_common::time::now_ms();
222            let store = mstore.clone();
223            let Ok(event) = tokio::task::spawn_blocking(move || event_of(&raw, &store, now)).await else { continue };
224            fire_matching(&scheduler, &jobs, &event).await;
225        }
226    });
227}