ultron-session-core 1.0.0

One session's runtime, shared by every mode through the session worker: the rlm lane (model, provider, system prompt, the single rlm tool), the composition root of its host stack, the format-4 run journal, session naming, Pi read views, and the session actor
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
//! Completion events instead of polling: a port of `packages/coding-agent/src/ultron/async-events.ts`.
//!
//! When detached work ends (a shell job started with `yield_after`, an `rlm.spawn` child, an `agents.*` task, a
//! detached cell), the host delivers one short `ultron-runtime-event` custom message to the lane that owns the work:
//!
//! ```text
//! <runtime_event kind="job_done" id="job-1a2b" status="completed" summary="exit 0; 12 passed" fetch="await rlm.job('job-1a2b')" />
//! ```
//!
//! Delivery ([`Dispatcher`]):
//! - completions within the coalescing window (500 ms) of the first one become one message;
//! - a lane in the middle of a run gets the message as a steer, placed at the next turn boundary; a steer that a run
//!   did not consume (it ended first) is taken back and delivered again as below;
//! - an idle root lane is re-invoked: the message starts a run charged to the root that started the work, so the
//!   per-root turn, token and cost limits keep counting across the chain;
//! - otherwise (a child lane, or a root that must not be re-invoked) the message waits as next-run input. Events are
//!   only ever appended, which keeps the provider's prompt-cache prefix valid.
//!
//! Loop guards: only root-owned work re-invokes the root; a root whose turn the user aborted never restarts work (its
//! jobs are cancelled and their ends are not announced); a refused root (a spent budget) or more than `max_runs`
//! automatic runs in one chain turn re-invocation into quiet delivery. `ULTRON_ASYNC_EVENTS=off` disables events.
//!
//! The dispatcher is one thread: publications, run ends and drains are commands it handles in order, and each lane's
//! batch is delivered after its coalescing deadline, so delivery decisions never race each other.

use jsrt::sync;
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

pub const ASYNC_EVENTS_ENV: &str = "ULTRON_ASYNC_EVENTS";

pub const RUNTIME_EVENT_MESSAGE_TYPE: &str = "ultron-runtime-event";
pub const DEFAULT_COALESCE: Duration = Duration::from_millis(500);
pub const DEFAULT_MAX_EVENT_RUNS: usize = 16;
/// How long a batch that could not be delivered (the lane was compacting, a steer failed) waits before it is tried
/// again.
pub const RETRY_AFTER: Duration = Duration::from_millis(1000);

/// One completion.
#[derive(Clone, Debug, PartialEq)]
pub struct RuntimeEvent {
    /// `job_done`, `tool_done`, `child_done`, `task_done` (and the Rust `cell_done`).
    pub kind: String,
    pub id: String,
    pub status: String,
    pub summary: String,
    /// The kernel call that returns the full result.
    pub fetch: String,
    /// The lane that owns the work and receives the event.
    pub lane: String,
    /// The usage root the work was started under.
    pub root_id: Option<String>,
}

/// `asyncEventsEnabled`: on unless `off`, `0`, `false` or `no`.
pub fn async_events_enabled(value: Option<&str>) -> bool {
    match value.map(str::trim) {
        None | Some("") => true,
        Some(value) => !["off", "0", "false", "no"].contains(&value.to_lowercase().as_str()),
    }
}

/// `maxEventRunsFromEnv`: a non-negative integer, else [`DEFAULT_MAX_EVENT_RUNS`].
pub fn max_event_runs_from_env(value: Option<&str>) -> usize {
    value
        .map(str::trim)
        .filter(|v| !v.is_empty())
        .and_then(|v| v.parse::<usize>().ok())
        .unwrap_or(DEFAULT_MAX_EVENT_RUNS)
}

/// Masks secrets in text that reaches the model (`maskCellOutput`: the session's known secrets and the shipped rules,
/// unless `ULTRON_MASK_SECRETS` turns masking off).
pub type MaskText = Arc<dyn Fn(&str) -> String + Send + Sync>;

/// The shipped rules only, masking on (no session: nothing registered).
pub fn default_mask() -> MaskText {
    Arc::new(|text: &str| host::secrets::OutputMasker::default().mask_counted(text, None).0)
}

/// `<runtime_event>` attribute text (`attribute` of async-events.ts).
fn attribute(value: &str) -> String {
    value
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

/// `boundedSummary`: one line of at most 240 characters.
fn bounded(text: &str) -> String {
    let line = jsrt::string::flatten(text);
    if line.chars().count() > 240 {
        format!("{}…", line.chars().take(239).collect::<String>())
    } else {
        line
    }
}

/// One `<runtime_event>` line (`runtimeEventText` of async-events.ts) with the session's masking
/// (`maskCellOutput`).
pub fn runtime_event_line(kind: &str, id: &str, status: &str, summary: &str, fetch: &str, mask: &MaskText) -> String {
    format!(
        "<runtime_event kind=\"{}\" id=\"{}\" status=\"{}\" summary=\"{}\" fetch=\"{}\" />",
        attribute(kind),
        attribute(id),
        attribute(status),
        attribute(&bounded(&mask(summary))),
        attribute(fetch)
    )
}

/// `runtimeEventText` with the session's masking: each summary is cut to 4 × 240 UTF-16 units, masked, then
/// bounded.
pub fn runtime_event_text(events: &[RuntimeEvent], mask: &MaskText) -> String {
    events
        .iter()
        .map(|e| {
            let summary = jsrt::utf16::head(&e.summary, 4 * 240).to_string();
            runtime_event_line(&e.kind, &e.id, &e.status, &summary, &e.fetch, mask)
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// `runtimeEventMessage`: the events as one Pi custom message, with the session's masking.
pub fn runtime_event_message_with(events: &[RuntimeEvent], now: u64, mask: &MaskText) -> Value {
    json!({
        "role": "custom",
        "customType": RUNTIME_EVENT_MESSAGE_TYPE,
        "content": runtime_event_text(events, mask),
        "display": true,
        "details": {"events": events.iter().map(|e| json!({"kind": e.kind, "id": e.id, "status": e.status})).collect::<Vec<_>>()},
        "timestamp": now,
    })
}

/// What a lane is doing (`inspectExecution`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Execution {
    Idle,
    Run,
    /// Compaction or navigation: delivery waits for it to settle.
    Other,
}

/// The outcome of starting a run with an event message (`accept`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Accepted {
    /// The run started (its operation id), charged to the given root.
    Run(String),
    /// The lane is running after all (`LaneBusy`).
    Busy,
    Refused(String),
}

/// What taking back a steered message found (`cancelQueued`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cancelled {
    Cancelled,
    AlreadyConsumed,
    NotFound,
}

/// The lanes events are delivered to, as the dispatcher uses the harness's lanes.
pub trait EventLanes: Send + Sync {
    fn execution(&self, lane: &str) -> Execution;
    /// Start a run of `lane` with `message`, charged to `root` (`continueRootTurn`).
    fn accept(&self, lane: &str, message: &Value, root: &str) -> Accepted;
    /// Queue `message` for the lane's running run; its queued entry id.
    fn steer(&self, lane: &str, message: &Value) -> Result<String, String>;
    /// Keep `message` for the lane's next run.
    fn next_run(&self, lane: &str, message: &Value) -> Result<String, String>;
    fn cancel_queued(&self, lane: &str, entry: &str) -> Result<Cancelled, String>;
}

/// A delivery decision, for tests and diagnostics (`onDelivery`).
#[derive(Clone, Debug, PartialEq)]
pub struct Delivery {
    pub lane: String,
    /// `run`, `steer` or `nextRun`.
    pub mode: &'static str,
    pub events: Vec<RuntimeEvent>,
    pub reason: Option<String>,
}

pub type RootRefusal = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
pub type RootCallback = Arc<dyn Fn(&str) + Send + Sync>;
pub type DeliveryCallback = Arc<dyn Fn(&Delivery) + Send + Sync>;
pub type RootOfRun = Arc<dyn Fn(&str) -> String + Send + Sync>;
/// A line that ends a lane's event message (`lane`, the message text): the context reminder (crate::context_reminder).
pub type EventNote = Arc<dyn Fn(&str, &str) -> Option<String> + Send + Sync>;

/// What delivery remembers across workers (a hand-over, a restart): the roots whose turn the user aborted (their
/// work never re-invokes the model) and how many automatic runs each chain started (its `max_runs` budget). Kept in
/// the session (`ultron.module/async-events`); in memory only, a successor re-invoked an aborted root for a late
/// completion and gave every chain a fresh budget.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Chains {
    pub aborted: BTreeSet<String>,
    pub runs: BTreeMap<String, usize>,
}

/// The `ultron.module` key [`Chains`] are stored under.
pub const CHAINS_MODULE: &str = "async-events";

impl Chains {
    /// The stored value (absent or unreadable: nothing remembered).
    pub fn from_value(value: Option<&Value>) -> Chains {
        let Some(value) = value else {
            return Chains::default();
        };
        Chains {
            aborted: value["abortedRoots"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(|root| root.as_str().map(str::to_string))
                .collect(),
            runs: value["chainRuns"]
                .as_object()
                .into_iter()
                .flatten()
                .filter_map(|(root, runs)| Some((root.clone(), runs.as_u64()? as usize)))
                .collect(),
        }
    }

    pub fn to_value(&self) -> Value {
        json!({"version": 1, "abortedRoots": self.aborted, "chainRuns": self.runs})
    }
}

/// Keeps [`Chains`] after each change.
pub type SaveChains = Arc<dyn Fn(&Chains) + Send + Sync>;

/// `AsyncEventOptions`.
#[derive(Clone)]
pub struct DispatcherOptions {
    pub enabled: bool,
    pub coalesce: Duration,
    /// Automatic runs one chain (a root and the runs its events started) may start.
    pub max_runs: usize,
    /// The usage root of a root-lane run (its own, or the root it continues).
    pub root_of_run: RootOfRun,
    /// Why the root may not be re-invoked (a spent budget), or `None` when it may.
    pub refuse: Option<RootRefusal>,
    /// A root turn was aborted (Esc): stop its jobs.
    pub on_root_aborted: Option<RootCallback>,
    pub on_delivery: Option<DeliveryCallback>,
    pub retry_after: Duration,
    /// Ends the message of a batch with a backgrounded cell's end (`cell_done`), as the cell's result would end.
    pub note: Option<EventNote>,
    /// Masks the summaries (none: the shipped rules only).
    pub mask: Option<MaskText>,
    /// What an earlier worker of the session remembered, and where changes go (none: kept in memory only).
    pub chains: Chains,
    pub save_chains: Option<SaveChains>,
}

impl DispatcherOptions {
    pub fn new(root_of_run: RootOfRun) -> DispatcherOptions {
        DispatcherOptions {
            enabled: true,
            coalesce: DEFAULT_COALESCE,
            max_runs: DEFAULT_MAX_EVENT_RUNS,
            root_of_run,
            refuse: None,
            on_root_aborted: None,
            on_delivery: None,
            retry_after: RETRY_AFTER,
            note: None,
            mask: None,
            chains: Chains::default(),
            save_chains: None,
        }
    }
}

enum Command {
    Publish(RuntimeEvent),
    RunEnded {
        lane: String,
        run_id: String,
        aborted: bool,
    },
    Drain(Sender<()>),
    Close,
}

#[derive(Default)]
struct Counts {
    pending: HashMap<String, usize>,
    steered: HashMap<String, usize>,
    in_flight: usize,
    aborted: HashSet<String>,
}

/// `AsyncEventDispatcher`.
pub struct Dispatcher {
    tx: Mutex<Option<Sender<Command>>>,
    counts: Arc<Mutex<Counts>>,
    enabled: bool,
    thread: Mutex<Option<std::thread::JoinHandle<()>>>,
}

impl Dispatcher {
    pub fn new(options: DispatcherOptions, lanes: Arc<dyn EventLanes>) -> Arc<Dispatcher> {
        let (tx, rx) = channel();
        let counts = Arc::new(Mutex::new(Counts {
            aborted: options.chains.aborted.iter().cloned().collect(),
            ..Counts::default()
        }));
        let enabled = options.enabled;
        let chain_runs = options.chains.runs.clone().into_iter().collect();
        let mut worker = Worker {
            options,
            lanes,
            counts: counts.clone(),
            pending: HashMap::new(),
            retries: Vec::new(),
            steered: Vec::new(),
            chain_runs,
            notes: HashMap::new(),
            now: || jsrt::date::now_ms() as u64,
        };
        let thread = std::thread::spawn(move || worker.run(&rx));
        Arc::new(Dispatcher {
            tx: Mutex::new(Some(tx)),
            counts,
            enabled,
            thread: Mutex::new(Some(thread)),
        })
    }

    pub fn enabled(&self) -> bool {
        self.enabled
    }

    fn send(&self, command: Command) -> bool {
        sync::lock(&self.tx).as_ref().is_some_and(|tx| tx.send(command).is_ok())
    }

    /// A completion: delivered after the coalescing window with the others of its lane.
    pub fn publish(&self, event: RuntimeEvent) {
        if !self.enabled {
            return;
        }
        *sync::lock(&self.counts).pending.entry(event.lane.clone()).or_default() += 1;
        if !self.send(Command::Publish(event.clone())) {
            let mut counts = sync::lock(&self.counts);
            if let Some(n) = counts.pending.get_mut(&event.lane) {
                *n = n.saturating_sub(1);
            }
        }
    }

    /// The harness's `run_end` of `lane`: an aborted root turn's root never restarts work, and steers the run did
    /// not consume are taken back.
    pub fn run_ended(&self, lane: &str, run_id: &str, aborted: bool) {
        self.send(Command::RunEnded {
            lane: lane.into(),
            run_id: run_id.into(),
            aborted,
        });
    }

    /// Deliver now, bypassing the coalescing window (tests, shutdown); returns once delivered.
    pub fn drain(&self) {
        let (ack, done) = channel();
        if self.send(Command::Drain(ack)) {
            let _ = done.recv();
        }
    }

    /// Events for `lane` waiting to be delivered, or steered into a run that has not consumed them yet.
    pub fn pending_for(&self, lane: &str) -> usize {
        let counts = sync::lock(&self.counts);
        counts.pending.get(lane).copied().unwrap_or(0)
            + counts.steered.get(lane).copied().unwrap_or(0)
            + counts.in_flight
    }

    /// Whether a root turn was aborted (its work never restarts the model).
    pub fn root_aborted(&self, root: Option<&str>) -> bool {
        root.is_some_and(|root| sync::lock(&self.counts).aborted.contains(root))
    }

    /// Stop delivering (pending events are dropped). The dispatcher thread ends by itself once its current
    /// delivery returns; this never waits for it, as a delivery may be waiting for the caller (the session actor).
    pub fn close(&self) {
        if let Some(tx) = sync::lock(&self.tx).take() {
            let _ = tx.send(Command::Close);
        }
        sync::lock(&self.thread).take();
    }
}

impl Drop for Dispatcher {
    fn drop(&mut self) {
        self.close();
    }
}

struct Steered {
    lane: String,
    entry: String,
    events: Vec<RuntimeEvent>,
}

struct Worker {
    options: DispatcherOptions,
    lanes: Arc<dyn EventLanes>,
    counts: Arc<Mutex<Counts>>,
    /// Per lane: its batch and when it is delivered.
    pending: HashMap<String, (Vec<RuntimeEvent>, Instant)>,
    retries: Vec<(Instant, Vec<RuntimeEvent>)>,
    steered: Vec<Steered>,
    chain_runs: HashMap<String, usize>,
    /// The note of each batch with cell ends, by its cells, decided once: a batch delivered again keeps it.
    notes: HashMap<String, Option<String>>,
    now: fn() -> u64,
}

impl Worker {
    fn run(&mut self, rx: &Receiver<Command>) {
        loop {
            let next = self
                .pending
                .values()
                .map(|(_, at)| *at)
                .chain(self.retries.iter().map(|(at, _)| *at))
                .min();
            let received = match next {
                Some(at) => rx.recv_timeout(at.saturating_duration_since(Instant::now())),
                None => rx.recv().map_err(|_| RecvTimeoutError::Disconnected),
            };
            match received {
                Ok(Command::Publish(event)) => {
                    let coalesce = self.options.coalesce;
                    self.pending
                        .entry(event.lane.clone())
                        .or_insert_with(|| (Vec::new(), Instant::now() + coalesce))
                        .0
                        .push(event);
                }
                Ok(Command::RunEnded { lane, run_id, aborted }) => {
                    if lane == session_journal::run::MAIN_LANE && aborted {
                        let root = (self.options.root_of_run)(&run_id);
                        if sync::lock(&self.counts).aborted.insert(root.clone()) {
                            self.save_chains();
                        }
                        if let Some(callback) = &self.options.on_root_aborted {
                            callback(&root);
                        }
                    }
                    if self.steered.iter().any(|s| s.lane == lane) {
                        self.reclaim(&lane, aborted);
                    }
                }
                Ok(Command::Drain(ack)) => {
                    let lanes: Vec<String> = self.pending.keys().cloned().collect();
                    for lane in lanes {
                        self.flush(&lane);
                    }
                    let _ = ack.send(());
                }
                Ok(Command::Close) | Err(RecvTimeoutError::Disconnected) => return,
                Err(RecvTimeoutError::Timeout) => {}
            }
            let now = Instant::now();
            let due: Vec<String> = self
                .pending
                .iter()
                .filter(|(_, (_, at))| *at <= now)
                .map(|(lane, _)| lane.clone())
                .collect();
            for lane in due {
                self.flush(&lane);
            }
            let (retry, waiting): (Vec<_>, Vec<_>) = std::mem::take(&mut self.retries)
                .into_iter()
                .partition(|(at, _)| *at <= now);
            self.retries = waiting;
            for (_, events) in retry {
                // Counted as pending since `retry_later`.
                for event in events {
                    let coalesce = self.options.coalesce;
                    self.pending
                        .entry(event.lane.clone())
                        .or_insert_with(|| (Vec::new(), Instant::now() + coalesce))
                        .0
                        .push(event);
                }
            }
        }
    }

    fn flush(&mut self, lane: &str) {
        let Some((events, _)) = self.pending.remove(lane) else {
            return;
        };
        {
            let mut counts = sync::lock(&self.counts);
            if let Some(n) = counts.pending.get_mut(lane) {
                *n = n.saturating_sub(events.len());
            }
            counts.in_flight += 1;
        }
        self.deliver(lane, events);
        sync::lock(&self.counts).in_flight -= 1;
    }

    fn save_chains(&self) {
        if let Some(save) = &self.options.save_chains {
            let chains = Chains {
                aborted: sync::lock(&self.counts).aborted.iter().cloned().collect(),
                runs: self
                    .chain_runs
                    .iter()
                    .map(|(root, runs)| (root.clone(), *runs))
                    .collect(),
            };
            save(&chains);
        }
    }

    fn message(&mut self, lane: &str, events: &[RuntimeEvent]) -> Value {
        let mask = self.options.mask.clone().unwrap_or_else(default_mask);
        let mut message = runtime_event_message_with(events, (self.now)(), &mask);
        let cells: Vec<&str> = events
            .iter()
            .filter(|e| e.kind == "cell_done")
            .map(|e| e.id.as_str())
            .collect();
        if let (Some(note), false) = (&self.options.note, cells.is_empty()) {
            let text = message["content"].as_str().unwrap_or_default().to_string();
            let line = self
                .notes
                .entry(cells.join("\n"))
                .or_insert_with(|| note(lane, &text))
                .clone();
            if let Some(line) = line {
                message["content"] = Value::String(format!("{text}\n{line}"));
            }
        }
        message
    }

    fn delivered(&self, lane: &str, mode: &'static str, events: &[RuntimeEvent], reason: Option<String>) {
        if let Some(callback) = &self.options.on_delivery {
            callback(&Delivery {
                lane: lane.into(),
                mode,
                events: events.to_vec(),
                reason,
            });
        }
    }

    fn deliver(&mut self, lane: &str, events: Vec<RuntimeEvent>) {
        if events.is_empty() {
            return;
        }
        match self.lanes.execution(lane) {
            Execution::Other => return self.retry_later(events),
            Execution::Run => return self.steer(lane, events),
            Execution::Idle => {}
        }
        let message = self.message(lane, &events);
        let reason = self.refusal(lane, &events);
        if reason.is_none() {
            let root = chain_root(&events).unwrap_or_default();
            match self.lanes.accept(lane, &message, &root) {
                Accepted::Run(_) => {
                    *self.chain_runs.entry(root).or_default() += 1;
                    self.save_chains();
                    self.delivered(lane, "run", &events, None);
                    return;
                }
                Accepted::Busy => return self.steer(lane, events),
                Accepted::Refused(_) => {}
            }
        }
        if self.lanes.next_run(lane, &message).is_ok() {
            self.delivered(lane, "nextRun", &events, reason);
        }
    }

    /// Why an idle lane's events must not start a run; `None` when they may.
    fn refusal(&self, lane: &str, events: &[RuntimeEvent]) -> Option<String> {
        if lane != session_journal::run::MAIN_LANE {
            return Some("child lanes are never re-invoked".into());
        }
        let Some(root) = chain_root(events) else {
            return Some("no root turn owns this work".into());
        };
        if sync::lock(&self.counts).aborted.contains(&root) {
            return Some("the root turn was aborted".into());
        }
        let runs = self.chain_runs.get(&root).copied().unwrap_or(0);
        let max = self.options.max_runs;
        if runs >= max {
            return Some(format!("{runs} of {max} automatic runs used for {root}"));
        }
        self.options.refuse.as_ref().and_then(|refuse| refuse(&root))
    }

    fn steer(&mut self, lane: &str, events: Vec<RuntimeEvent>) {
        let message = self.message(lane, &events);
        let entry = match self.lanes.steer(lane, &message) {
            Ok(entry) => entry,
            Err(_) => return self.retry_later(events),
        };
        self.delivered(lane, "steer", &events, None);
        *sync::lock(&self.counts).steered.entry(lane.to_string()).or_default() += 1;
        self.steered.push(Steered {
            lane: lane.into(),
            entry,
            events,
        });
        // The run may have ended between the check and the steer: then nothing will consume it.
        if self.lanes.execution(lane) == Execution::Idle {
            self.reclaim(lane, false);
        }
    }

    /// Deliver `events` again after `retry_after`. They count as pending meanwhile: uncounted, the session saw no
    /// work waiting and an unattached worker could retire with them undelivered.
    fn retry_later(&mut self, events: Vec<RuntimeEvent>) {
        {
            let mut counts = sync::lock(&self.counts);
            for event in &events {
                *counts.pending.entry(event.lane.clone()).or_default() += 1;
            }
        }
        self.retries.push((Instant::now() + self.options.retry_after, events));
    }

    fn forget_steer(&mut self, entry: &str) {
        if let Some(index) = self.steered.iter().position(|s| s.entry == entry) {
            let steered = self.steered.remove(index);
            if let Some(n) = sync::lock(&self.counts).steered.get_mut(&steered.lane) {
                *n = n.saturating_sub(1);
            }
        }
    }

    /// Steered events a finished run did not consume are taken back and delivered again. After an abort, steers are
    /// dropped with the queue; completions of tasks (not of the jobs the abort cancelled) are kept for the lane's
    /// next run.
    fn reclaim(&mut self, lane: &str, aborted: bool) {
        let entries: Vec<(String, Vec<RuntimeEvent>)> = self
            .steered
            .iter()
            .filter(|s| s.lane == lane)
            .map(|s| (s.entry.clone(), s.events.clone()))
            .collect();
        for (entry, events) in entries {
            match self.lanes.cancel_queued(lane, &entry) {
                Err(_) | Ok(Cancelled::AlreadyConsumed) => self.forget_steer(&entry),
                Ok(outcome) if outcome == Cancelled::Cancelled || aborted => {
                    self.forget_steer(&entry);
                    let kept: Vec<RuntimeEvent> = events
                        .into_iter()
                        .filter(|e| !((e.kind == "job_done" || e.kind == "tool_done") && e.status == "cancelled"))
                        .collect();
                    if !kept.is_empty() {
                        self.deliver(lane, kept);
                    }
                }
                Ok(_) => {}
            }
        }
    }
}

/// The root a batch belongs to: the newest event's that names one.
fn chain_root(events: &[RuntimeEvent]) -> Option<String> {
    events.iter().rev().find_map(|e| e.root_id.clone())
}