Skip to main content

agentmux_srv_core/backend/
worker_notes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A leader hears from its workers without polling
5//! (docs/specs/SPEC_AGENT_WORKERS_2026_10_15.md §3.3).
6//!
7//! A watched agent (a spawned worker, a definition carrying `agent:worker_of`,
8//! `app_api::agent_spawn`; or any agent that holds a claimed Kanban task) that
9//! is waiting for an answer, fails, or whose process exits gets its watchers
10//! (its seat lead, its leader, the agents that filed its tasks) an `[AgentMux]`
11//! note in their open pane. A worker whose turn ends with a question for its
12//! leader and no report gets one too; a turn that ends without a report is no
13//! note by itself, since `quiet_watch` tells the watchers when the agent has
14//! gone quiet (SPEC_LEADER_TOLD_WHEN_AN_AGENT_GOES_QUIET_2026_11_21.md §7). At
15//! most one note per agent a minute; a held one is counted in the next.
16//!
17//! Installed at boot (not with the notify Router, which starts only when a
18//! window connects): a broker observer forwards turn ends and failures, and a
19//! reducer subscriber a question still waiting after its grace, to a task
20//! that does the store reads and the delivery.
21
22use std::collections::HashMap;
23use std::sync::{Arc, LazyLock};
24
25use crate::backend::mps::{Broker, MuxEvent};
26use crate::backend::obj::{self, Block, Tab};
27use crate::backend::storage::filestore::FileStore;
28use crate::backend::storage::store::Store;
29use super::worker_failure_note::FAILED_AT;
30
31/// The fewest milliseconds between two notes about the same worker.
32const NOTE_GAP_MS: u64 = 60_000;
33/// How long an exit waits for the failure that ended the turn, so its note can leave the cause to that failure's.
34const EXIT_SETTLE: std::time::Duration = std::time::Duration::from_millis(1_000);
35/// How much of a worker's last message a note quotes.
36const LAST_WORDS_CHARS: usize = 200;
37/// How long after a turn ended its note may still be sent. An end is published within seconds of the turn's;
38/// one older than this is a turn from before (an agent's old turn read again when its session resumed), and a
39/// note about it would tell the leader of a turn that did not just end.
40const TURN_END_FRESH_MS: u64 = 10 * 60_000;
41/// How far before a turn's start the transcript's last write may be and still be that turn's words: the file
42/// is written line by line while the turn runs, so a quieter one holds only older turns.
43const WROTE_SINCE_SLACK_MS: u64 = 5_000;
44
45/// Whether a turn that ended at `ended_at_ms` (0: not said) ended recently enough for a note at `now_ms`.
46fn turn_end_is_fresh(ended_at_ms: u64, now_ms: u64) -> bool {
47    ended_at_ms == 0 || now_ms.saturating_sub(ended_at_ms) <= TURN_END_FRESH_MS
48}
49
50/// Whether a transcript last written at `modts` (ms; `None`: no file) holds words of a turn that started at
51/// `started_at_ms` (0: not said).
52fn written_since(modts: Option<i64>, started_at_ms: u64) -> bool {
53    match modts {
54        None => false,
55        Some(_) if started_at_ms == 0 => true,
56        Some(at) => (at.max(0) as u64).saturating_add(WROTE_SINCE_SLACK_MS) >= started_at_ms,
57    }
58}
59
60/// What a worker did that its leader hears about.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub(crate) enum WorkerEvent {
63    /// A turn ended (`agentturn` with `end: completed`), started at `started_at_ms` and ended at
64    /// `ended_at_ms` (0 when the event did not say); `key` is the turn's identity (see `Seen`).
65    TurnEnded { block_id: String, started_at_ms: u64, ended_at_ms: u64, key: String },
66    /// Its process exited (`agentturn` with `end: exited`).
67    Exited { block_id: String, key: String },
68    /// It failed (`agentfailure`), with the failure's title.
69    Failed { block_id: String, title: String },
70    /// A question has waited for the user for `ASKED_GRACE` in the middle of
71    /// a turn (`term:awaiting_user`, which the agent pane sets).
72    Asked { block_id: String },
73}
74
75/// How long a question waits for the user before the leader hears of it: a
76/// user at the pane usually answers first.
77const ASKED_GRACE: std::time::Duration = std::time::Duration::from_secs(30);
78
79/// The block whose pane just set `term:awaiting_user`, from a reducer event.
80pub(crate) fn asked_in(event: &agentmux_common::ipc::Event) -> Option<&str> {
81    match event {
82        agentmux_common::ipc::Event::BlockMetaUpdated { block_id, meta_patch, .. }
83            if meta_patch.get(crate::backend::agent_state::META_AWAITING_USER).and_then(|v| v.as_bool()) == Some(true) =>
84        {
85            Some(block_id)
86        }
87        _ => None,
88    }
89}
90
91/// Read a broker event as a worker event, for any agent pane; whether the
92/// pane is a worker is decided later, off the broker's lock.
93pub(crate) fn parse_event(event: &str, scopes: &[String], data: Option<&serde_json::Value>) -> Option<WorkerEvent> {
94    let d = data?;
95    if event == crate::backend::mps::EVENT_AGENT_TURN {
96        // AgentMux's own hidden turns are nobody's report.
97        if d.pointer("/trigger/kind").and_then(|k| k.as_str()) == Some("system") {
98            return None;
99        }
100        let block_id = d.get("block_id")?.as_str()?.to_string();
101        // One turn's end can be published twice (when its settle window lapses
102        // and again at the tracker's close): the same turn and end time.
103        let key = format!(
104            "{block_id}/{}/{}",
105            d.get("turn_id").and_then(|t| t.as_u64()).unwrap_or(0),
106            d.get("ended_at_ms").and_then(|t| t.as_u64()).unwrap_or(0)
107        );
108        return match d.get("end").and_then(|e| e.as_str()) {
109            Some("completed") => Some(WorkerEvent::TurnEnded {
110                block_id,
111                started_at_ms: d.get("started_at_ms").and_then(|s| s.as_u64()).unwrap_or(0),
112                ended_at_ms: d.get("ended_at_ms").and_then(|s| s.as_u64()).unwrap_or(0),
113                key,
114            }),
115            Some("exited") => Some(WorkerEvent::Exited { block_id, key }),
116            _ => None,
117        };
118    }
119    if event == crate::backend::mps::EVENT_AGENT_FAILURE {
120        let block_id = scopes.iter().find_map(|s| s.strip_prefix("block:"))?.to_string();
121        let title = d.get("title").and_then(|t| t.as_str()).unwrap_or("an error").to_string();
122        return Some(WorkerEvent::Failed { block_id, title });
123    }
124    None
125}
126
127/// Start listening. Called once from `main`.
128pub fn install(
129    broker: Arc<Broker>,
130    mut reducer_events: tokio::sync::broadcast::Receiver<agentmux_common::ipc::Event>,
131    mstore: Arc<Store>,
132    work: Arc<Store>,
133    filestore: Arc<FileStore>,
134    config: Arc<crate::backend::wconfig::ConfigState>,
135) {
136    let _ = WORK.set(work.clone());
137    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<WorkerEvent>();
138    let observer_tx = tx.clone();
139    // Observers run inside `Broker::publish`, under its locks: parse and hand off only.
140    broker.add_observer(Arc::new(move |ev: &MuxEvent| {
141        if let Some(e) = parse_event(&ev.event, &ev.scopes, ev.data.as_ref()) {
142            let _ = observer_tx.send(e);
143        }
144    }));
145    // A question in the middle of a turn ends no turn: the pane's flag is the
146    // only sign of it. Looked at again after the grace, one wait per pane.
147    tokio::spawn(async move {
148        let waiting: Arc<parking_lot::Mutex<std::collections::HashSet<String>>> = Default::default();
149        loop {
150            let ev = match reducer_events.recv().await {
151                Ok(ev) => ev,
152                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
153                Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
154            };
155            let Some(block_id) = asked_in(&ev).map(str::to_string) else { continue };
156            if !waiting.lock().insert(block_id.clone()) {
157                continue;
158            }
159            let (tx, waiting) = (tx.clone(), waiting.clone());
160            tokio::spawn(async move {
161                tokio::time::sleep(ASKED_GRACE).await;
162                waiting.lock().remove(&block_id);
163                let _ = tx.send(WorkerEvent::Asked { block_id });
164            });
165        }
166    });
167    // The delivery log is a short ring (`AUDIT_LOG_MAX`): copy reports out
168    // of it often enough that one isn't gone before its turn ends.
169    let (flush_mstore, flush_config) = (mstore.clone(), config.clone());
170    tokio::spawn(async move {
171        let mut tick = tokio::time::interval(std::time::Duration::from_secs(2));
172        loop {
173            tick.tick().await;
174            absorb(&crate::backend::reactive::get_global_handler().get_audit_log(usize::MAX));
175            // The notes gathered for a leader leave when their window is over.
176            let (mstore, config) = (flush_mstore.clone(), flush_config.clone());
177            let _ = tokio::task::spawn_blocking(move || super::note_outbox::flush_due(&mstore, &config, agentmux_common::time::now_ms_u64())).await;
178        }
179    });
180    tokio::spawn(async move {
181        let mut seen = Seen::default();
182        while let Some(ev) = rx.recv().await {
183            if !seen.first(&ev) {
184                continue;
185            }
186            if let WorkerEvent::Failed { block_id, .. } = &ev {
187                FAILED_AT.lock().record(block_id, std::time::Instant::now());
188            }
189            let (mstore, work, filestore, config) = (mstore.clone(), work.clone(), filestore.clone(), config.clone());
190            if matches!(ev, WorkerEvent::Exited { .. }) {
191                // Off the loop, so the wait delays no other worker's note.
192                tokio::spawn(note_exit(ev, mstore, work, filestore, config));
193            } else {
194                send_note(ev, mstore, work, filestore, config).await;
195            }
196        }
197    });
198}
199
200/// The note for `ev`, queued for its watchers: it leaves at once when nothing else waits for that leader, else with
201/// the others in the leader's window (`note_outbox`).
202async fn send_note(ev: WorkerEvent, mstore: Arc<Store>, work: Arc<Store>, filestore: Arc<FileStore>, config: Arc<crate::backend::wconfig::ConfigState>) {
203    let store = mstore.clone();
204    let note = tokio::task::spawn_blocking(move || note_line_for(&store, Some(&work), &filestore, &ev)).await;
205    if let Ok(Some(n)) = note {
206        let line = super::note_outbox::Line { agent: n.def_id, text: n.text, held_key: n.wait_key };
207        let _ = tokio::task::spawn_blocking(move || super::note_outbox::queue(&mstore, &config, &n.watchers, &line, agentmux_common::time::now_ms_u64())).await;
208    }
209}
210
211/// An exit's note, unless the failure that ended the turn speaks for it (#2617): its `agentfailure` follows the
212/// exit within milliseconds and names the cause, so the exit waits `EXIT_SETTLE` for it.
213async fn note_exit(ev: WorkerEvent, mstore: Arc<Store>, work: Arc<Store>, filestore: Arc<FileStore>, config: Arc<crate::backend::wconfig::ConfigState>) {
214    let WorkerEvent::Exited { block_id, .. } = &ev else { return };
215    let (block_id, heard_at) = (block_id.clone(), std::time::Instant::now());
216    tokio::time::sleep(EXIT_SETTLE).await;
217    if FAILED_AT.lock().speaks_for_exit(&block_id, heard_at) {
218        return;
219    }
220    send_note(ev, mstore, work, filestore, config).await;
221}
222
223/// An agent the notes are about, and who is told.
224#[derive(Debug, Clone)]
225struct Watched {
226    def_id: String,
227    name: String,
228    /// A spawned worker (`agent:worker_of`), else an agent that holds a claimed task.
229    is_worker: bool,
230    /// The panes to tell: its seat lead, its leader, and the filers of the tasks it holds.
231    watchers: Vec<String>,
232}
233
234/// The agent in `block_id`, when it is watched: a spawned worker, or an agent that holds a claimed task (`work`).
235fn watched_of_block(mstore: &Store, work: Option<&Store>, block_id: &str) -> Option<Watched> {
236    let block = mstore.get::<Block>(block_id).ok()??;
237    let def_id = obj::meta_get_string(&block.meta, "agentId", "");
238    if def_id.is_empty() {
239        return None;
240    }
241    let def = mstore.agent_def_list().ok()?.into_iter().find(|d| d.id == def_id)?;
242    let is_worker = crate::backend::agent_seat::worker_of(mstore, &def_id).is_some();
243    let tasks = work
244        .map(|w| {
245            let now = agentmux_common::time::now_ms();
246            crate::backend::quiet_watch::owed_by(&crate::backend::quiet_watch::claimed_by_holder(&crate::backend::quiet_watch::read_claimed(w, now)), &def)
247        })
248        .unwrap_or_default();
249    if !is_worker && tasks.is_empty() {
250        return None;
251    }
252    let filers: Vec<String> = tasks.iter().map(|t| t.filer_uid.clone()).collect();
253    Some(Watched { watchers: crate::backend::quiet_watch::watcher_panes(mstore, &def_id, &filers), def_id, name: def.name, is_worker })
254}
255
256/// A note's opening words name a worker as one, and any other watched agent as an agent.
257fn named_for(body: String, is_worker: bool) -> String {
258    match body.strip_prefix("Your worker ") {
259        Some(rest) if !is_worker => format!("Your agent {rest}"),
260        _ => body,
261    }
262}
263
264/// The Kanban store, kept at install so `already_tells_its_leader` can tell which agents hold a task.
265static WORK: std::sync::OnceLock<Arc<Store>> = std::sync::OnceLock::new();
266
267/// A worker pane's worker and leader, as srv knows them.
268#[derive(Debug, Clone)]
269struct Worker {
270    /// What it sends messages as (its AGENTMUX_AGENT_ID).
271    slug: String,
272    leader_def_id: String,
273}
274
275fn worker_of_block(mstore: &Store, block_id: &str) -> Option<Worker> {
276    let block = mstore.get::<Block>(block_id).ok()??;
277    let def_id = obj::meta_get_string(&block.meta, "agentId", "");
278    if def_id.is_empty() {
279        return None;
280    }
281    let leader_def_id = crate::backend::agent_seat::worker_of(mstore, &def_id)?;
282    let def = mstore.agent_def_list().ok()?.into_iter().find(|d| d.id == def_id)?;
283    Some(Worker { slug: def.slug, leader_def_id })
284}
285
286/// Whether this block's own note already tells `sender` (an agent slug or id) about an exit of it: the sender is one
287/// of the watchers of the agent (a worker's leader or seat lead, or the filer of a task it holds) and has an open
288/// pane to be told in. `sender_failure_note` skips telling the same agent again, less richly, about the same exit
289/// (#2627).
290pub(crate) fn already_tells_its_leader(mstore: &Store, block_id: &str, sender: &str) -> bool {
291    already_tells(mstore, WORK.get().map(|w| &**w), block_id, sender)
292}
293
294pub(crate) fn already_tells(mstore: &Store, work: Option<&Store>, block_id: &str, sender: &str) -> bool {
295    let Some(watched) = watched_of_block(mstore, work, block_id) else { return false };
296    let Ok(defs) = mstore.agent_def_list() else { return false };
297    let Some(sender_id) = defs.iter().find(|d| d.slug == sender || d.id == sender).map(|d| d.id.clone()) else { return false };
298    // The same check `note_for` makes: the sender is one of the panes its note goes to (the worker's leader or seat
299    // lead, or the filer of a task the agent holds) and has one open.
300    let sender_panes = live_panes_of(mstore, &sender_id);
301    if !watched.watchers.iter().any(|p| sender_panes.contains(p)) {
302        return false;
303    }
304    // Only suppressed when that note was actually admitted, not held by the one-note-a-minute throttle just
305    // below (#2629): a held note tells the leader nothing, so the sender's own note must go through instead.
306    super::worker_failure_note::failure_note_was_admitted(block_id)
307}
308
309/// The open panes (in a tab) of definition `def_id`.
310pub fn live_panes_of(mstore: &Store, def_id: &str) -> Vec<String> {
311    let Ok(tabs) = mstore.get_all::<Tab>() else {
312        return Vec::new();
313    };
314    tabs.iter()
315        .flat_map(|t| t.blockids.iter())
316        .filter(|id| {
317            mstore
318                .get::<Block>(id)
319                .ok()
320                .flatten()
321                .is_some_and(|b| obj::meta_get_string(&b.meta, "agentId", "") == def_id)
322        })
323        .cloned()
324        .collect()
325}
326
327/// The note for `ev`: the panes to tell, the text, and a key when the note may wait for a cold
328/// leader's next turn; no key when the leader must hear at once (the agent failed or stopped, or is
329/// waiting for an answer). `None` when `ev` isn't a watched agent's, nobody watching is open, or the
330/// agent's gap runs. `work` is the Kanban store, which says which agents hold a claimed task.
331pub(crate) fn note_for(mstore: &Store, work: Option<&Store>, filestore: &FileStore, ev: &WorkerEvent) -> Option<(Vec<String>, String, Option<String>)> {
332    note_line_for(mstore, work, filestore, ev).map(|n| (n.watchers, format!("[AgentMux] {}", n.text), n.wait_key))
333}
334
335/// A note about a watched agent, before it is addressed: who is told, which agent it is about, what it says (quoted,
336/// with no `[AgentMux]` prefix) and the key it may wait under (see `note_for`).
337pub(crate) struct NoteLine {
338    pub watchers: Vec<String>,
339    pub def_id: String,
340    pub text: String,
341    pub wait_key: Option<String>,
342}
343
344pub(crate) fn note_line_for(mstore: &Store, work: Option<&Store>, filestore: &FileStore, ev: &WorkerEvent) -> Option<NoteLine> {
345    let block_id = match ev {
346        WorkerEvent::TurnEnded { block_id, .. }
347        | WorkerEvent::Exited { block_id, .. }
348        | WorkerEvent::Failed { block_id, .. }
349        | WorkerEvent::Asked { block_id } => block_id,
350    };
351    // Answered within the grace, or the turn is over (its end has a note of its own).
352    if matches!(ev, WorkerEvent::Asked { .. })
353        && crate::backend::agent_state::current_state(mstore, block_id) != Some(crate::backend::agent_state::AgentState::Waiting)
354    {
355        return None;
356    }
357    // A route out of credits stops every agent on it: its leads are told once for the route (`route_credits`).
358    if matches!(ev, WorkerEvent::Failed { title, .. } if title == crate::agents::failure::ROUTE_CREDITS_TITLE) {
359        return None;
360    }
361    let worker = watched_of_block(mstore, work, block_id)?;
362    if worker.watchers.is_empty() {
363        return None;
364    }
365    let body = match ev {
366        WorkerEvent::TurnEnded { started_at_ms, ended_at_ms, .. } => {
367            // A turn that ends without a report is no note by itself (`quiet_watch` tells the watchers when the
368            // agent has gone quiet). One that ends with a question for the leader is: the worker waits for the
369            // answer. Only a spawned worker has a leader it reports to.
370            let spawned = worker_of_block(mstore, block_id).filter(|_| worker.is_worker)?;
371            let leader_panes = live_panes_of(mstore, &spawned.leader_def_id);
372            // Only a turn that has just ended is news. An old end (a turn read again when a session resumed) is not,
373            // and neither is an end heard while the worker is in a turn: nothing has finished, and its words would
374            // be an earlier turn's.
375            if !turn_end_is_fresh(*ended_at_ms, agentmux_common::time::now_ms_u64()) {
376                tracing::debug!(block_id, ended_at_ms, "worker note: an old turn end, no note");
377                return None;
378            }
379            if crate::backend::blockcontroller::get_block_controller_status(block_id).is_some_and(|s| s.turn_active) {
380                tracing::debug!(block_id, "worker note: the worker is in a turn, no note");
381                return None;
382            }
383            absorb(&crate::backend::reactive::get_global_handler().get_audit_log(usize::MAX));
384            if last_report(&spawned.slug, &leader_panes).is_some_and(|at| at + 1_000 >= *started_at_ms) {
385                return None;
386            }
387            let words = last_words(mstore, filestore, block_id, *started_at_ms);
388            if !words.asked {
389                return None;
390            }
391            turn_end_body(&worker.name, words)
392        }
393        WorkerEvent::Exited { .. } => format!("Your worker {} stopped: its process exited.", worker.name),
394        WorkerEvent::Failed { title, .. } => {
395            let meta = mstore.get::<Block>(block_id).ok().flatten().map(|b| b.meta).unwrap_or_default();
396            super::worker_failure_note::failed_body(&worker.name, title, &meta, agentmux_common::time::now_ms_u64())
397        }
398        WorkerEvent::Asked { .. } => format!(
399            "Your worker {} is waiting for the user to answer a question in its pane; it can't go on until they do.",
400            worker.name
401        ),
402    };
403    let body = named_for(body, worker.is_worker);
404    let admitted = GAPS.lock().admit(&worker.def_id, body, agentmux_common::time::now_ms_u64());
405    if matches!(ev, WorkerEvent::Failed { .. }) {
406        // So `sender_failure_note::already_tells_its_leader` knows whether this failure's own note actually
407        // reached the leader, or was held by the throttle just below — a held note tells the leader nothing
408        // (#2629).
409        super::worker_failure_note::record_failure_admission(block_id, admitted.is_some());
410    }
411    let body = admitted?;
412    Some(NoteLine { watchers: worker.watchers, def_id: worker.def_id, text: crate::backend::reactive::sanitize::quote_in_system_note(&body), wait_key: None })
413}
414
415/// One note per agent per `NOTE_GAP_MS`, shared by every kind of note about it (`quiet_watch` uses it too): the
416/// text to send, with a count of the notes held back since the last one, or `None` while the gap runs.
417pub(crate) fn admit(def_id: &str, body: String, now_ms: u64) -> Option<String> {
418    GAPS.lock().admit(def_id, body, now_ms)
419}
420
421/// When `sender` (an agent id, any case) last messaged anyone, from the deliveries `absorb` has copied.
422pub(crate) fn last_message_by(sender: &str) -> Option<u64> {
423    let sender = sender.to_lowercase();
424    REPORTS.lock().iter().filter(|((from, _), _)| *from == sender).map(|(_, at)| *at).max()
425}
426
427/// The words of the newest turn the agent in `block_id` wrote, as `last_words` reads them (no turn start given):
428/// empty when there are none.
429pub(crate) fn last_words_of(mstore: &Store, filestore: &FileStore, block_id: &str) -> String {
430    last_words(mstore, filestore, block_id, 0).text
431}
432
433/// Reports, kept past the delivery log's ring: (sender, target pane) → the
434/// last successful delivery (unix ms). The sender's name is the one it gave;
435/// a false claim can only hide a note, never send one.
436static REPORTS: LazyLock<parking_lot::Mutex<HashMap<(String, String), u64>>> = LazyLock::new(Default::default);
437const REPORTS_MAX: usize = 4096;
438
439/// Copy the successful deliveries in `audit` into `REPORTS`.
440pub fn absorb(audit: &[crate::backend::reactive::AuditLogEntry]) {
441    let mut reports = REPORTS.lock();
442    for e in audit.iter().filter(|e| e.success && e.event_kind == "delivery") {
443        let Some(source) = e.source_agent.as_deref().filter(|s| !s.is_empty()) else { continue };
444        let at = reports.entry((source.to_lowercase(), e.block_id.clone())).or_insert(0);
445        *at = (*at).max(e.timestamp);
446    }
447    if reports.len() > REPORTS_MAX {
448        let mut by_age: Vec<u64> = reports.values().copied().collect();
449        by_age.sort_unstable();
450        let cutoff = by_age[reports.len() - REPORTS_MAX];
451        reports.retain(|_, at| *at >= cutoff);
452    }
453}
454
455/// When `worker` (its agent id) last messaged one of `leader_panes`.
456pub fn last_report(worker: &str, leader_panes: &[String]) -> Option<u64> {
457    let reports = REPORTS.lock();
458    let worker = worker.to_lowercase();
459    leader_panes.iter().filter_map(|p| reports.get(&(worker.clone(), p.clone())).copied()).max()
460}
461
462/// Turn ends already handled, so a second publish of one is skipped.
463#[derive(Default)]
464struct Seen {
465    keys: std::collections::VecDeque<String>,
466}
467
468impl Seen {
469    /// True the first time `ev` is seen; failures have no turn identity.
470    fn first(&mut self, ev: &WorkerEvent) -> bool {
471        let key = match ev {
472            WorkerEvent::TurnEnded { key, .. } | WorkerEvent::Exited { key, .. } => key,
473            WorkerEvent::Failed { .. } | WorkerEvent::Asked { .. } => return true,
474        };
475        if self.keys.contains(key) {
476            return false;
477        }
478        if self.keys.len() >= 256 {
479            self.keys.pop_front();
480        }
481        self.keys.push_back(key.clone());
482        true
483    }
484}
485
486/// The worker's last message, and whether it ended asking something.
487#[derive(Debug, Clone, Default, PartialEq, Eq)]
488struct LastWords {
489    text: String,
490    asked: bool,
491}
492
493/// What the worker said in the turn that began at `started_at_ms`: nothing when its transcript was not written
494/// since (the copy read is an older session's, as after a container agent's session resumed), rather than words
495/// from before.
496fn last_words(mstore: &Store, filestore: &FileStore, block_id: &str, started_at_ms: u64) -> LastWords {
497    use crate::ambient::digest::{read_recent_activity_from, reads_output_format, TurnEnding};
498    let format = mstore
499        .get::<Block>(block_id)
500        .ok()
501        .flatten()
502        .map(|b| obj::meta_get_string(&b.meta, "agentOutputFormat", ""))
503        .unwrap_or_default();
504    if !reads_output_format(&format) {
505        return LastWords::default();
506    }
507    let source = crate::backend::transcript::source::TranscriptSource::resolve(filestore, mstore, block_id);
508    if !written_since(source.stat().map(|(_, modts)| modts), started_at_ms) {
509        return LastWords::default();
510    }
511    let Some(activity) = read_recent_activity_from(&source, block_id) else {
512        return LastWords::default();
513    };
514    LastWords { text: ended_turn_text(&activity.text), asked: matches!(activity.ending, TurnEnding::AssistantAsked | TurnEnding::AskedUser) }
515}
516
517/// The newest assistant message of the turn that ended: the one after the last `[user]` entry of the digest. A
518/// turn that was only tool calls has none, and quoting an older turn's message would repeat the same words, as if
519/// they were new, in every note that follows.
520fn ended_turn_text(digest: &str) -> String {
521    digest
522        .lines()
523        .rev()
524        .take_while(|l| !l.starts_with("[user] "))
525        .find_map(|l| l.strip_prefix("[assistant] "))
526        .map(|t| clip(t, LAST_WORDS_CHARS))
527        .unwrap_or_default()
528}
529
530/// The note for a turn that ended with a question for the leader.
531fn turn_end_body(name: &str, words: LastWords) -> String {
532    let quoted = if words.text.is_empty() { String::new() } else { format!(" Its last words: \"{}\"", words.text) };
533    format!("Your worker {name} is waiting for an answer and hasn't reported to you.{quoted} Answer it with Message send.")
534}
535
536fn clip(s: &str, max: usize) -> String {
537    let flat = s.split_whitespace().collect::<Vec<_>>().join(" ");
538    if flat.chars().count() <= max {
539        flat
540    } else {
541        format!("{}…", flat.chars().take(max).collect::<String>())
542    }
543}
544
545/// One note per worker per `NOTE_GAP_MS`; the next one says how many were held.
546#[derive(Default)]
547struct Gaps {
548    by_worker: HashMap<String, (u64, u32)>,
549}
550
551impl Gaps {
552    fn admit(&mut self, worker: &str, body: String, now_ms: u64) -> Option<String> {
553        let entry = self.by_worker.entry(worker.to_string()).or_insert((0, 0));
554        if entry.0 != 0 && now_ms < entry.0 + NOTE_GAP_MS {
555            entry.1 += 1;
556            return None;
557        }
558        let held = std::mem::take(&mut entry.1);
559        entry.0 = now_ms;
560        if self.by_worker.len() > 512 {
561            self.by_worker.retain(|_, (at, _)| now_ms < *at + NOTE_GAP_MS);
562        }
563        Some(match held {
564            0 => body,
565            1 => format!("{body} (1 earlier update from it was held back.)"),
566            n => format!("{body} ({n} earlier updates from it were held back.)"),
567        })
568    }
569}
570
571static GAPS: LazyLock<parking_lot::Mutex<Gaps>> = LazyLock::new(Default::default);
572
573/// What a note to the pane `block_id` is addressed to: its agent's uid, else its id.
574pub(crate) fn note_target(block_id: &str) -> Option<String> {
575    crate::backend::reactive::get_global_handler()
576        .list_agents()
577        .into_iter()
578        .find(|r| r.block_id == block_id)
579        .map(|r| r.uid.clone().filter(|u| !u.is_empty()).unwrap_or(r.agent_id.clone()))
580}
581
582/// The first open pane of the lead of the agent `def_id` (its seat's lead, on this machine), if it has one.
583pub(crate) fn leader_pane_of(mstore: &Store, def_id: &str) -> Option<String> {
584    let lead = crate::backend::agent_seat::effective_seat_by_id(mstore, def_id)
585        .and_then(|seat| seat.lead)
586        .filter(|lead| !crate::backend::agent_seat::is_remote_lead(lead));
587    lead.and_then(|lead| live_panes_of(mstore, &lead).into_iter().next())
588}
589
590/// Like [`tell_leader`], for a note that asks nothing: it joins the leader's turn if one is running, else waits under
591/// `key` for the next one (a second note under the same key replaces the first). It never starts a turn.
592pub fn tell_leader_held(mstore: &Store, def_id: &str, body: &str, key: &str) -> bool {
593    let Some(leader_block) = leader_pane_of(mstore, def_id) else {
594        return false;
595    };
596    let text = format!("[AgentMux] {}", crate::backend::reactive::sanitize::quote_in_system_note(body));
597    crate::backend::blockcontroller::system_note_into_turn_or_hold(&leader_block, key, &text);
598    true
599}
600
601/// Tell the lead of the agent `def_id` something about it, as an `[AgentMux]` note: its seat's lead (a
602/// spawned worker's is its leader) when that agent is on this machine and has a pane open. `false` when
603/// nobody was told: it reports to the operator, its lead is on another machine, or its pane is not open.
604pub fn tell_leader(mstore: &Store, def_id: &str, body: &str) -> bool {
605    let Some(leader_block) = leader_pane_of(mstore, def_id) else {
606        return false;
607    };
608    let Some(target) = note_target(&leader_block) else {
609        return false;
610    };
611    let text = format!("[AgentMux] {}", crate::backend::reactive::sanitize::quote_in_system_note(body));
612    crate::backend::reactive::get_global_handler().deliver_system_note(&target, &text).is_ok()
613}
614
615/// Whether the note was delivered or kept for the leader's next turn.
616pub(crate) fn deliver(mstore: &Store, config: &crate::backend::wconfig::ConfigState, leader_block: &str, text: &str, wait_key: Option<&str>) -> bool {
617    let handler = crate::backend::reactive::get_global_handler();
618    let target = note_target(leader_block);
619    let Some(target) = target else {
620        tracing::debug!(leader_block, "worker note: the leader's pane isn't registered");
621        return false;
622    };
623    let sent = match wait_key {
624        Some(key) => crate::backend::cold_hold::note_or_wait_if_cold(mstore, &config.get_settings().extra, leader_block, &target, key, text),
625        None => handler.deliver_system_note(&target, text),
626    };
627    if let Err(e) = &sent {
628        tracing::warn!(leader_block, error = %e, "worker note not delivered");
629    }
630    sent.is_ok()
631}
632
633#[cfg(test)]
634#[path = "worker_notes_tests.rs"]
635mod tests;