Skip to main content

eclipse_core/
flares.rs

1//! `#171`: a flare run — N read-only sibling agents on one task, and the merge of what they said.
2//!
3//! A **flare** is one child agent: its own session (`origin = "flare:<run>:<n>"`), its own route,
4//! a small iteration budget, and a registry holding **only the readers** ([`READ_TOOLS`]). A
5//! **flare run** is the set of them on one task, plus the merge. The lead is unchanged — it is the
6//! only agent that writes.
7//!
8//! This is not a second runtime. A flare is what a `delegate` child is, times N, plus a scheduler:
9//! [`DelegateTool::run_child`] builds both, so the preamble, the hooks, the usage capture and the
10//! cancellation are one implementation with two callers.
11//!
12//! # Why local runs are serial, and why that is correct
13//!
14//! A local server serves one model at a time — llama-swap swaps by stopping one to start another —
15//! so N flares on one local route are N sequential turns. Parallelism buys nothing there; what it
16//! buys is **isolation**: each flare reads its own files, and the lead's context never fills with
17//! them. Mixed routes are the case where concurrency is real: three cheap local readers plus one
18//! cloud thinker run in two slots, not four. So the cap is per *server*, which is why a route can
19//! name a `group`: two routes pointed at one box are one slot.
20//!
21//! # What keeps a fan-out safe
22//!
23//! Every flare is read-only, and read-only is a property of its registry, not of a policy: it is
24//! narrowed to [`READ_TOOLS`] by [`crate::tools::ToolRegistry::only`], so a `tool_call` bridge
25//! cannot reach anything that is not there. Approvals stay one at a time on purpose (`runtime.rs`'s
26//! gate), and a read-only flare asks nothing at all.
27
28use crate::cancel::Cancel;
29use crate::config::FlaresConfig;
30use crate::session::{FlareJobRow, SessionStore};
31use crate::tools::{Approver, CallScope, Tool, ToolError, ToolRegistry};
32use crate::tools_delegate::{ChildJob, ChildOrigin, DelegateTool};
33use async_trait::async_trait;
34use serde_json::{json, Value};
35use std::collections::BTreeMap;
36use std::sync::{Arc, Mutex};
37use std::time::Duration;
38
39/// The tools a flare **does** have (`#548`): the readers, named one at a time.
40///
41/// This is an allowlist on purpose, and the direction is the fix. A denylist was only correct
42/// until the next tool was registered: `cronjob_manage` and `skill_manage` sit in the same registry
43/// as the readers, so does every plugin tool and every MCP server's tool, and each of those was
44/// handed to a read-only flare by default. Approvals `ask` on them is not the guarantee the tool's
45/// own doc claims — under `auto`, `smart` or `--yes` a flare could schedule cron runs and rewrite
46/// the skills directory while its description said the capability was not there.
47///
48/// Nothing here writes, schedules work for later, spends a budget nobody is watching, or edits the
49/// user's install: a flare reads what it is pointed at and answers. `delegate` and `flares` are
50/// absent for the reason a `delegate` child does not get `delegate` — no nesting — and `memory`
51/// because a flare is a worker, not an identity: it has no memory of its own to write to. The
52/// `tool_search` bridge is absent as well: it reaches whatever the registry holds, so naming it
53/// back would hand a flare the deferred half of the lead's capability.
54pub const READ_TOOLS: &[&str] = &[
55    "read_file",
56    "search_files",
57    "fetch",
58    "session_search",
59    "skill_view",
60    "skill_search",
61];
62
63/// The most jobs one call may name. A model that wants more has not split the task, it has
64/// multiplied it; the CLI's `-n` is where a bigger number is typed deliberately.
65pub const MAX_FLARES_PER_RUN: usize = 16;
66
67/// One job as the lead states it.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct FlareJob {
70    pub prompt: String,
71    pub route: Option<String>,
72    pub max_iterations: Option<usize>,
73    pub system: Option<String>,
74}
75
76/// How a run's answers come back.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum Merge {
79    /// One block, children in the lead's order.
80    Concat,
81    /// The children's answers, labelled, with the instruction that the lead writes the merge.
82    Lead,
83}
84
85impl Merge {
86    pub fn parse(text: &str) -> Option<Self> {
87        match text.trim().to_ascii_lowercase().as_str() {
88            "" | "concat" => Some(Self::Concat),
89            "lead" => Some(Self::Lead),
90            _ => None,
91        }
92    }
93}
94
95/// How a child ended, as one word the ledger and the readout both use.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum State {
98    Done,
99    Failed,
100    /// Never started: the run was cancelled, its budget was gone, or its spend cap was reached.
101    Dropped,
102}
103
104impl State {
105    pub fn word(self) -> &'static str {
106        match self {
107            Self::Done => "done",
108            Self::Failed => "failed",
109            Self::Dropped => "dropped",
110        }
111    }
112}
113
114/// One child's row in the run's report.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct FlareLine {
117    pub n: usize,
118    pub route: String,
119    pub session_id: Option<String>,
120    pub state: State,
121    pub text: String,
122    pub why: Option<String>,
123    pub prompt_tokens: Option<u64>,
124    pub completion_tokens: Option<u64>,
125    pub iterations: usize,
126}
127
128impl FlareLine {
129    fn dropped(n: usize, route: &str, why: &str) -> Self {
130        Self {
131            n,
132            route: route.to_string(),
133            session_id: None,
134            state: State::Dropped,
135            text: String::new(),
136            why: Some(why.to_string()),
137            prompt_tokens: None,
138            completion_tokens: None,
139            iterations: 0,
140        }
141    }
142}
143
144/// What a route offers a run: its name, how many flares may share it, and which server it is.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct RouteSlot {
147    pub name: String,
148    pub parallel: usize,
149    /// Routes with the same group are one server's worth of slots.
150    pub group: Option<String>,
151}
152
153impl RouteSlot {
154    pub fn of(route: &crate::config::NamedRoute) -> Self {
155        Self {
156            name: route.name.clone(),
157            parallel: route.parallel(),
158            group: route.group.clone(),
159        }
160    }
161
162    fn key(&self) -> String {
163        self.group.clone().unwrap_or_else(|| self.name.clone())
164    }
165}
166
167/// The cap a run actually has: one number per server, and the sum of them, floored by
168/// `[flares] max_concurrent`.
169///
170/// A group takes its **lowest** member's bound — the conservative reading of "these are the same
171/// box", because the cost of guessing high is a swap cycle that stops one model mid-turn.
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct Slots {
174    pub per_group: BTreeMap<String, usize>,
175    pub total: usize,
176}
177
178pub fn slots(routes: &[RouteSlot], max_concurrent: usize) -> Slots {
179    let mut per_group: BTreeMap<String, usize> = BTreeMap::new();
180    for route in routes {
181        let entry = per_group.entry(route.key()).or_insert(route.parallel);
182        *entry = (*entry).min(route.parallel.max(1));
183    }
184    let available: usize = per_group.values().copied().sum();
185    Slots {
186        total: max_concurrent.max(1).min(available.max(1)),
187        per_group,
188    }
189}
190
191/// The `flares` tool.
192pub struct FlareTool {
193    runner: Arc<DelegateTool>,
194    /// The registry every flare gets: the lead's, without [`WRITE_TOOLS`].
195    tools: Arc<ToolRegistry>,
196    store: SessionStore,
197    cfg: FlaresConfig,
198    routes: Vec<RouteSlot>,
199    description: String,
200}
201
202impl FlareTool {
203    pub fn new(
204        runner: Arc<DelegateTool>,
205        store: SessionStore,
206        cfg: FlaresConfig,
207        routes: Vec<RouteSlot>,
208    ) -> Self {
209        let description = format!(
210            "Run several read-only agents on one task at the same time. Name every job: a job is \
211             one prompt and the route it runs on. Each agent gets its own session, its own route \
212             and a small iteration budget, holds only the readers (`read_file`, `search_files`, \
213             `fetch`, `session_search`, `skill_view`, `skill_search`) and cannot write, schedule or \
214             delegate. Use it to read several things at once \
215             and get one answer back; do not use it for work you could do in one turn. At most \
216             {MAX_FLARES_PER_RUN} jobs."
217        );
218        Self {
219            tools: Arc::new(runner.flare_registry()),
220            runner,
221            store,
222            cfg,
223            routes,
224            description,
225        }
226    }
227
228    /// The cap this tool's routes give it.
229    pub fn slots(&self) -> Slots {
230        slots(&self.routes, self.cfg.concurrency())
231    }
232
233    fn resolve_route(&self, named: Option<&str>) -> Result<String, ToolError> {
234        let name = match named {
235            Some(name) => name.to_string(),
236            None => self.runner.default_route(),
237        };
238        if self.routes.iter().any(|r| r.name == name) {
239            return Ok(name);
240        }
241        Err(ToolError::InvalidArgs(format!(
242            "`{name}` is not a route this agent can use. Declared: {}",
243            self.routes
244                .iter()
245                .map(|r| r.name.as_str())
246                .collect::<Vec<_>>()
247                .join(", ")
248        )))
249    }
250}
251
252#[async_trait]
253impl Tool for FlareTool {
254    fn name(&self) -> &str {
255        "flares"
256    }
257
258    fn description(&self) -> &str {
259        &self.description
260    }
261
262    fn parameters(&self) -> Value {
263        json!({
264            "type": "object",
265            "properties": {
266                "jobs": {
267                    "type": "array",
268                    "minItems": 1,
269                    "maxItems": MAX_FLARES_PER_RUN,
270                    "description": "One entry per agent. Name the jobs — never a count.",
271                    "items": {
272                        "type": "object",
273                        "properties": {
274                            "prompt": {
275                                "type": "string",
276                                "description": "The job, stated so it makes sense with no other context."
277                            },
278                            "route": {
279                                "type": "string",
280                                "description": "Which route this agent runs on. Unset: the delegate route, else this run's."
281                            },
282                            "max_iterations": {
283                                "type": "integer",
284                                "minimum": 1,
285                                "description": "Model requests this agent may make. Unset: the configured default."
286                            },
287                            "system": {
288                                "type": "string",
289                                "description": "Extra instructions for this agent, added to its preamble."
290                            }
291                        },
292                        "required": ["prompt"]
293                    }
294                },
295                "merge": {
296                    "type": "string",
297                    "enum": ["concat", "lead"],
298                    "description": "`concat` (default) joins the answers; `lead` returns them labelled and the lead writes the merge."
299                }
300            },
301            "required": ["jobs"]
302        })
303    }
304
305    fn describe_call(&self, args: &Value) -> String {
306        let jobs = args
307            .get("jobs")
308            .and_then(Value::as_array)
309            .map(|a| a.len())
310            .unwrap_or(0);
311        let routes: Vec<String> = args
312            .get("jobs")
313            .and_then(Value::as_array)
314            .map(|jobs| {
315                let mut seen: Vec<String> = Vec::new();
316                for job in jobs {
317                    if let Some(route) = job.get("route").and_then(Value::as_str) {
318                        if !seen.iter().any(|r| r == route) {
319                            seen.push(route.to_string());
320                        }
321                    }
322                }
323                seen
324            })
325            .unwrap_or_default();
326        let routes = if routes.is_empty() {
327            self.runner.default_route()
328        } else {
329            routes.join(", ")
330        };
331        format!("flare run: {jobs} read-only agent(s) on {routes}")
332    }
333
334    async fn call(&self, _args: Value) -> Result<String, ToolError> {
335        Err(ToolError::Failed(
336            "`flares` only runs inside an agent run".into(),
337        ))
338    }
339
340    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
341        let raw = args
342            .get("jobs")
343            .and_then(Value::as_array)
344            .ok_or_else(|| ToolError::InvalidArgs("`jobs` is not a list".into()))?;
345        if raw.is_empty() {
346            return Err(ToolError::InvalidArgs("`jobs` is empty".into()));
347        }
348        if raw.len() > MAX_FLARES_PER_RUN {
349            return Err(ToolError::InvalidArgs(format!(
350                "{} jobs is more than the {MAX_FLARES_PER_RUN} one run may start; split the task",
351                raw.len()
352            )));
353        }
354        let merge = match args.get("merge") {
355            None | Some(Value::Null) => Merge::Concat,
356            Some(Value::String(s)) => Merge::parse(s).ok_or_else(|| {
357                ToolError::InvalidArgs(format!("`merge` is `concat` or `lead`, not {s:?}"))
358            })?,
359            Some(_) => return Err(ToolError::InvalidArgs("`merge` is not a string".into())),
360        };
361
362        let mut jobs = Vec::with_capacity(raw.len());
363        for job in raw {
364            let prompt = job
365                .get("prompt")
366                .and_then(Value::as_str)
367                .unwrap_or_default()
368                .trim();
369            if prompt.is_empty() {
370                return Err(ToolError::InvalidArgs("every job needs a `prompt`".into()));
371            }
372            let route = match job.get("route") {
373                None | Some(Value::Null) => None,
374                Some(Value::String(s)) => Some(self.resolve_route(Some(s))?),
375                Some(_) => return Err(ToolError::InvalidArgs("`route` is not a string".into())),
376            };
377            let max_iterations = match job.get("max_iterations") {
378                None | Some(Value::Null) => None,
379                Some(Value::Number(n)) => n.as_u64().map(|n| n.max(1) as usize),
380                Some(_) => {
381                    return Err(ToolError::InvalidArgs(
382                        "`max_iterations` is not a number".into(),
383                    ))
384                }
385            };
386            jobs.push(FlareJob {
387                prompt: prompt.to_string(),
388                route: Some(route.unwrap_or_else(|| self.runner.default_route())),
389                max_iterations,
390                system: job
391                    .get("system")
392                    .and_then(Value::as_str)
393                    .map(str::to_string),
394            });
395        }
396
397        let run = self.store.new_id();
398        let task = crate::compact::clean(&jobs[0].prompt, 200);
399        let routes: Vec<String> = {
400            let mut seen: Vec<String> = Vec::new();
401            for job in &jobs {
402                let name = job.route.clone().unwrap_or_default();
403                if !seen.contains(&name) {
404                    seen.push(name);
405                }
406            }
407            seen
408        };
409        self.store
410            .begin_flare_run(&run, &task, &routes, jobs.len(), &scope.run.session)
411            .map_err(store_error)?;
412
413        // The runtime cancels a run by dropping its future (`tokio::select!`), and then nothing
414        // after the `.await` below ever runs — so the row stayed `running`, which this file calls
415        // "a run nothing can ever cancel" (`#553`). A guard is the one piece of this that a dropped
416        // future cannot skip.
417        let mut close = CloseOnDrop {
418            store: &self.store,
419            run: &run,
420            armed: true,
421        };
422        let result = self
423            .execute(&run, &jobs, merge, scope.approver, &scope.run.cancel)
424            .await;
425
426        let merged = result.merge(merge);
427        // The ledger closes even when the run failed: a row left `running` is a run nothing can
428        // ever cancel.
429        let state = if result.lines.iter().any(|l| l.state == State::Dropped) {
430            "cancelled"
431        } else if result.lines.iter().any(|l| l.state == State::Failed) {
432            "failed"
433        } else {
434            "done"
435        };
436        let _ = self.store.finish_flare_run(
437            &run,
438            state,
439            result.prompt_tokens(),
440            result.completion_tokens(),
441            result.iterations(),
442        );
443        close.armed = false;
444
445        Ok(result.readout(&run, merge, &merged))
446    }
447}
448
449/// Closes a flare run's ledger row as `cancelled` if the call is dropped before it can close it.
450///
451/// The counts are `None` rather than zero: a cancelled run does not know them, and a zero would read
452/// as "this ran and cost nothing" (`#553`).
453struct CloseOnDrop<'a> {
454    store: &'a SessionStore,
455    run: &'a str,
456    armed: bool,
457}
458
459impl Drop for CloseOnDrop<'_> {
460    fn drop(&mut self) {
461        if self.armed {
462            let _ = self
463                .store
464                .finish_flare_run(self.run, "cancelled", None, None, 0);
465        }
466    }
467}
468
469/// A finished run: its children, in the lead's order.
470pub struct RunResult {
471    pub run: String,
472    pub lines: Vec<FlareLine>,
473}
474
475impl RunResult {
476    pub fn prompt_tokens(&self) -> Option<u64> {
477        self.lines
478            .iter()
479            .filter_map(|l| l.prompt_tokens)
480            .reduce(|a, b| a + b)
481    }
482
483    pub fn completion_tokens(&self) -> Option<u64> {
484        self.lines
485            .iter()
486            .filter_map(|l| l.completion_tokens)
487            .reduce(|a, b| a + b)
488    }
489
490    pub fn iterations(&self) -> usize {
491        self.lines.iter().map(|l| l.iterations).sum()
492    }
493
494    /// The children's answers, in the order they were asked for.
495    pub fn merge(&self, how: Merge) -> String {
496        let mut out = String::new();
497        for line in &self.lines {
498            if !out.is_empty() {
499                out.push_str("\n\n");
500            }
501            match how {
502                Merge::Concat => out.push_str(&format!(
503                    "--- flare {} ({}) ---\n{}",
504                    line.n,
505                    line.route,
506                    line.text.trim()
507                )),
508                Merge::Lead => out.push_str(&format!(
509                    "--- flare {} ({}) · session {} ---\n{}\n[the lead merges these]",
510                    line.n,
511                    line.route,
512                    line.session_id.as_deref().unwrap_or("-"),
513                    line.text.trim()
514                )),
515            }
516        }
517        out
518    }
519
520    /// The heading, one line per child, and the merge — what the lead's tool result carries.
521    fn readout(&self, run: &str, _how: Merge, merged: &str) -> String {
522        let done = self.lines.iter().filter(|l| l.state == State::Done).count();
523        let dropped = self
524            .lines
525            .iter()
526            .filter(|l| l.state == State::Dropped)
527            .count();
528        let failed = self.lines.len() - done - dropped;
529        let mut out = format!(
530            "flare run `{run}`: {done} of {} finished{}{} \u{2014} {} iteration{}, {} prompt / {} completion tokens\n",
531            self.lines.len(),
532            if failed > 0 {
533                format!(", {failed} failed")
534            } else {
535                String::new()
536            },
537            if dropped > 0 {
538                format!(", {dropped} dropped")
539            } else {
540                String::new()
541            },
542            self.iterations(),
543            if self.iterations() == 1 { "" } else { "s" },
544            count(self.prompt_tokens()),
545            count(self.completion_tokens()),
546        );
547        for line in &self.lines {
548            out.push_str(&format!(
549                "  {}. {} on {} \u{b7} {}",
550                line.n,
551                line.state.word(),
552                line.route,
553                line.session_id.as_deref().unwrap_or("-")
554            ));
555            if let Some(why) = &line.why {
556                out.push_str(&format!(" \u{b7} {why}"));
557            }
558            out.push('\n');
559        }
560        out.push('\n');
561        out.push_str(merged);
562        out
563    }
564}
565
566impl FlareTool {
567    /// Start every job, in the lead's order, under the run's caps.
568    ///
569    /// One future per lane, `join_all`ed: a lane is a serial queue on one server, so concurrent
570    /// lanes are concurrent *servers*. That is why no `tokio::spawn` appears here — everything
571    /// lives in the tool call that asked for it, and a cancelled call drops the futures.
572    async fn execute(
573        &self,
574        run: &str,
575        jobs: &[FlareJob],
576        _merge: Merge,
577        approver: &dyn Approver,
578        cancel: &Cancel,
579    ) -> RunResult {
580        let slots = self.slots();
581        let mut lanes: Vec<(String, Vec<(usize, &FlareJob)>)> = Vec::new();
582        // Lanes are filled round-robin per group, so a group with two slots gets two lanes and a
583        // route with one gets one. A job goes to the lane that has least queued at that point.
584        let mut lane_of_group: BTreeMap<String, usize> = BTreeMap::new();
585        for (index, job) in jobs.iter().enumerate() {
586            let route = job
587                .route
588                .clone()
589                .unwrap_or_else(|| self.runner.default_route());
590            let key = self
591                .routes
592                .iter()
593                .find(|r| r.name == route)
594                .map(RouteSlot::key)
595                .unwrap_or_else(|| route.clone());
596            let bound = slots.per_group.get(&key).copied().unwrap_or(1).max(1);
597            let base = {
598                let next = lane_of_group.entry(key.clone()).or_insert(0);
599                let lane = *next;
600                *next = (*next + 1) % bound;
601                lane
602            };
603            let lane_key = format!("{key}#{base}");
604            match lanes.iter_mut().find(|(k, _)| *k == lane_key) {
605                Some((_, queue)) => queue.push((index + 1, job)),
606                None => lanes.push((lane_key, vec![(index + 1, job)])),
607            }
608        }
609
610        let budget = Arc::new(Mutex::new(self.cfg.budget()));
611        let spent = Arc::new(Mutex::new(0u64));
612        let token_cap = self.cfg.total_tokens;
613        let lines: Arc<Mutex<Vec<FlareLine>>> = Arc::new(Mutex::new(Vec::new()));
614        // `#555`: the cap is a cap. `slots.total` was computed and then never spent — the lanes
615        // were built from `per_group` alone, so two groups of four ran eight children with
616        // `max_concurrent = 2`, and the setting that exists to protect a shared GPU did nothing.
617        let gate = Arc::new(tokio::sync::Semaphore::new(slots.total));
618
619        let lanes = futures_util::future::join_all(lanes.into_iter().map(|(_, queue)| {
620            let runner = Arc::clone(&self.runner);
621            let tools = Arc::clone(&self.tools);
622            let store = self.store.clone();
623            let budget = Arc::clone(&budget);
624            let spent = Arc::clone(&spent);
625            let lines = Arc::clone(&lines);
626            let gate = Arc::clone(&gate);
627            async move {
628                for (n, job) in queue {
629                    let route = job.route.clone().unwrap_or_default();
630                    // Cancelled, out of budget, or over the spend cap: a dropped flare is a row,
631                    // not a silent nothing — `flares list` has to be able to say why.
632                    if cancel.is_cancelled() {
633                        push(
634                            &lines,
635                            &store,
636                            FlareLine::dropped(n, &route, "the run was cancelled"),
637                            run,
638                        );
639                        continue;
640                    }
641                    match store.flare_cancel_requested(run) {
642                        Ok(true) => {
643                            push(
644                                &lines,
645                                &store,
646                                FlareLine::dropped(n, &route, "cancelled from another process"),
647                                run,
648                            );
649                            continue;
650                        }
651                        Ok(false) => {}
652                        Err(_) => {}
653                    }
654                    if let Some(cap) = token_cap {
655                        if *spent.lock().unwrap_or_else(|e| e.into_inner()) >= cap {
656                            push(
657                                &lines,
658                                &store,
659                                FlareLine::dropped(n, &route, "the run's token cap was reached"),
660                                run,
661                            );
662                            continue;
663                        }
664                    }
665                    let take = {
666                        let mut left = budget.lock().unwrap_or_else(|e| e.into_inner());
667                        let want = job
668                            .max_iterations
669                            .unwrap_or(self.cfg.per_flare())
670                            .min(*left);
671                        *left -= want;
672                        want
673                    };
674                    if take == 0 {
675                        push(
676                            &lines,
677                            &store,
678                            FlareLine::dropped(n, &route, "the run's iteration budget was spent"),
679                            run,
680                        );
681                        continue;
682                    }
683                    let session_id = runner.new_session_id();
684                    let _ = store.flare_job_running(run, n, &route, &session_id);
685                    // `#554`: a cancel from another process is a row, and the child used to get
686                    // only the parent's in-process token — with every lane busy, the flag was not
687                    // read again until the run was over. One per-job token, armed by either source.
688                    let job_cancel = Cancel::new();
689                    let watch = watch_cancel(
690                        cancel.clone(),
691                        job_cancel.clone(),
692                        store.clone(),
693                        run.to_string(),
694                    );
695                    let outcome = gated(
696                        &gate,
697                        runner.run_child(
698                            Arc::clone(&tools),
699                            ChildJob {
700                                session_id: &session_id,
701                                prompt: &job.prompt,
702                                system: job.system.as_deref(),
703                                route: &route,
704                                budget: take,
705                                origin: ChildOrigin::Flare { run, n },
706                            },
707                            approver,
708                            &job_cancel,
709                        ),
710                    )
711                    .await;
712                    watch.abort();
713                    let (state, text, why) = match outcome.answer {
714                        Ok(text) => (State::Done, text, None),
715                        Err(reason) => (State::Failed, String::new(), Some(reason)),
716                    };
717                    if let Some(p) = outcome.prompt_tokens {
718                        *spent.lock().unwrap_or_else(|e| e.into_inner()) += p;
719                    }
720                    if let Some(c) = outcome.completion_tokens {
721                        *spent.lock().unwrap_or_else(|e| e.into_inner()) += c;
722                    }
723                    push(
724                        &lines,
725                        &store,
726                        FlareLine {
727                            n,
728                            route: outcome.route.clone(),
729                            session_id: Some(session_id),
730                            state,
731                            text,
732                            why,
733                            prompt_tokens: outcome.prompt_tokens,
734                            completion_tokens: outcome.completion_tokens,
735                            iterations: outcome.iterations,
736                        },
737                        run,
738                    );
739                }
740            }
741        }))
742        .await;
743        let _ = lanes;
744        let mut lines = lines
745            .lock()
746            .map(|l| l.clone())
747            .unwrap_or_else(|e| e.into_inner().clone());
748        lines.sort_by_key(|l| l.n);
749        RunResult {
750            run: run.to_string(),
751            lines,
752        }
753    }
754}
755
756/// Run one child under the run's total slot count (`#555`). The permit is held for the whole
757/// child, not for its start: what the cap is about is how many are reading at once.
758async fn gated<T>(
759    gate: &Arc<tokio::sync::Semaphore>,
760    work: impl std::future::Future<Output = T>,
761) -> T {
762    let permit = gate
763        .acquire()
764        .await
765        .expect("the flare gate is never closed");
766    let out = work.await;
767    drop(permit);
768    out
769}
770
771/// How often a running flare looks at the store's cancel flag (`#554`). Fast enough that a
772/// dashboard cancel is felt on the next tool call, slow enough that a minute of reading costs a
773/// handful of small reads.
774const CANCEL_POLL: Duration = Duration::from_millis(200);
775
776/// Stop a child when either source says so: the parent's token (Esc, `#171`) or the store's flag
777/// (`flares cancel` in another process, `#554`). The flag is polled because it is a row, and a row
778/// cannot notify a process that is not looking at it.
779fn watch_cancel(
780    parent: Cancel,
781    child: Cancel,
782    store: SessionStore,
783    run: String,
784) -> tokio::task::JoinHandle<()> {
785    tokio::spawn(async move {
786        loop {
787            if parent.is_cancelled() || matches!(store.flare_cancel_requested(&run), Ok(true)) {
788                child.cancel();
789                return;
790            }
791            tokio::time::sleep(CANCEL_POLL).await;
792        }
793    })
794}
795
796/// Record one child's row and keep it for the merge.
797fn push(lines: &Arc<Mutex<Vec<FlareLine>>>, store: &SessionStore, line: FlareLine, run: &str) {
798    let _ = store.flare_job_done(&FlareJobRow {
799        run_id: run.to_string(),
800        n: line.n,
801        route: line.route.clone(),
802        session_id: line.session_id.clone(),
803        state: line.state.word().to_string(),
804        prompt_tokens: line.prompt_tokens,
805        completion_tokens: line.completion_tokens,
806        iterations: line.iterations,
807        why: line.why.clone(),
808    });
809    if let Ok(mut all) = lines.lock() {
810        all.push(line);
811    }
812}
813
814fn count(tokens: Option<u64>) -> String {
815    tokens.map_or_else(|| "?".to_string(), |n| n.to_string())
816}
817
818fn store_error(e: crate::error::Error) -> ToolError {
819    ToolError::Failed(format!("the flare run's ledger: {e}"))
820}
821
822#[cfg(test)]
823mod tests {
824    use super::*;
825    use crate::message::Message;
826    use crate::provider::ChatProvider;
827    use crate::router::RouteInfo;
828    use crate::tools::ToolSpec;
829    use crate::tools_delegate::{ChildProviders, DelegateSettings};
830    use crate::usage::TurnUsage;
831
832    /// A provider that hands out scripted replies and records the tools it was offered.
833    struct Scripted {
834        replies: Mutex<Vec<String>>,
835        offered: Mutex<Vec<Vec<String>>>,
836        usage: Mutex<Option<TurnUsage>>,
837        /// When set, `chat` never answers: the shape a cancelled run leaves behind (`#553`).
838        hang: bool,
839    }
840
841    impl Scripted {
842        fn new(replies: &[&str]) -> Arc<Self> {
843            Arc::new(Self {
844                replies: Mutex::new(replies.iter().rev().map(|r| r.to_string()).collect()),
845                offered: Mutex::new(Vec::new()),
846                usage: Mutex::new(Some(TurnUsage {
847                    prompt_tokens: Some(10),
848                    completion_tokens: Some(2),
849                    ..TurnUsage::default()
850                })),
851                hang: false,
852            })
853        }
854
855        /// A provider that never answers, so a run can be cancelled while it is really in flight.
856        fn hanging() -> Arc<Self> {
857            let mut me = Self::new(&[]);
858            // `new` returns an `Arc`; nothing else holds it yet.
859            Arc::get_mut(&mut me).expect("a fresh Arc").hang = true;
860            me
861        }
862    }
863
864    #[async_trait]
865    impl ChatProvider for Scripted {
866        async fn chat(&self, _: &[Message], tools: &[ToolSpec]) -> crate::Result<Message> {
867            if self.hang {
868                std::future::pending::<()>().await;
869            }
870            self.offered
871                .lock()
872                .unwrap()
873                .push(tools.iter().map(|t| t.function.name.clone()).collect());
874            let reply = self
875                .replies
876                .lock()
877                .unwrap()
878                .pop()
879                .unwrap_or_else(|| "no reply scripted".to_string());
880            Ok(Message::assistant(&reply))
881        }
882        fn take_usage(&self) -> Option<TurnUsage> {
883            self.usage.lock().unwrap().take()
884        }
885    }
886
887    struct Routes {
888        routes: Vec<(String, Arc<dyn ChatProvider>)>,
889        default: String,
890    }
891
892    impl ChildProviders for Routes {
893        fn routes(&self) -> Vec<RouteInfo> {
894            self.routes
895                .iter()
896                .map(|(n, _)| RouteInfo {
897                    name: n.clone(),
898                    model: format!("{n}-model"),
899                    endpoint: String::new(),
900                })
901                .collect()
902        }
903        fn default_route(&self) -> String {
904            self.default.clone()
905        }
906        fn provider(
907            &self,
908            name: &str,
909        ) -> std::result::Result<crate::tools_delegate::ChildRoute, String> {
910            self.routes
911                .iter()
912                .find(|(n, _)| n == name)
913                .map(|(_, p)| crate::tools_delegate::ChildRoute {
914                    name: name.to_string(),
915                    provider: Arc::clone(p),
916                    context_budget_tokens: 8000,
917                })
918                .ok_or_else(|| format!("unknown route `{name}`"))
919        }
920    }
921
922    /// The tool a lead would hold: three read tools and one write tool, so a flare's registry can
923    /// be shown to be missing the one that matters.
924    struct ReadFile;
925    #[async_trait]
926    impl Tool for ReadFile {
927        fn name(&self) -> &str {
928            "read_file"
929        }
930        fn description(&self) -> &str {
931            "read"
932        }
933        fn parameters(&self) -> Value {
934            json!({"type": "object"})
935        }
936        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
937            Ok("contents".into())
938        }
939    }
940    struct WriteFile;
941    #[async_trait]
942    impl Tool for WriteFile {
943        fn name(&self) -> &str {
944            "write_file"
945        }
946        fn description(&self) -> &str {
947            "write"
948        }
949        fn parameters(&self) -> Value {
950            json!({"type": "object"})
951        }
952        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
953            Ok("written".into())
954        }
955    }
956
957    /// A tool that exists only to be named: these tests are about which names a registry holds,
958    /// not about what the tools do.
959    struct Named(&'static str);
960
961    #[async_trait]
962    impl Tool for Named {
963        fn name(&self) -> &str {
964            self.0
965        }
966        fn description(&self) -> &str {
967            "named"
968        }
969        fn parameters(&self) -> Value {
970            json!({"type": "object"})
971        }
972        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
973            Ok(String::new())
974        }
975    }
976
977    fn harness(
978        dir: &std::path::Path,
979        provider: Arc<Scripted>,
980        cfg: FlaresConfig,
981    ) -> (FlareTool, SessionStore) {
982        let (tool, store, _) = harness_with_extra(dir, provider, cfg, &[]);
983        (tool, store)
984    }
985
986    /// The same harness with extra tools in the lead's registry, and the names the lead ended up
987    /// with — a test about what a flare does *not* hold has to prove the lead held it.
988    fn harness_with_extra(
989        dir: &std::path::Path,
990        provider: Arc<Scripted>,
991        cfg: FlaresConfig,
992        extra: &[&'static str],
993    ) -> (FlareTool, SessionStore, Vec<String>) {
994        let store = SessionStore::new(dir.join("sessions"));
995        let mut registry = ToolRegistry::new(4096);
996        registry.register(Arc::new(ReadFile), crate::config::Policy::Allow);
997        registry.register(Arc::new(WriteFile), crate::config::Policy::Allow);
998        for name in extra {
999            registry.register(Arc::new(Named(name)), crate::config::Policy::Allow);
1000        }
1001        let lead_names = registry.names();
1002        let routes = Routes {
1003            routes: vec![("local".to_string(), provider as Arc<dyn ChatProvider>)],
1004            default: "local".to_string(),
1005        };
1006        let delegate = Arc::new(DelegateTool::new(
1007            Arc::new(routes),
1008            Arc::new(registry),
1009            store.clone(),
1010            DelegateSettings {
1011                max_output_bytes: 8000,
1012                max_malformed_calls: 3,
1013                tool_concurrency: 1,
1014                lock_wait: std::time::Duration::from_secs(5),
1015            },
1016        ));
1017        let slots = vec![RouteSlot {
1018            name: "local".to_string(),
1019            parallel: 1,
1020            group: None,
1021        }];
1022        (
1023            FlareTool::new(delegate, store.clone(), cfg, slots),
1024            store,
1025            lead_names,
1026        )
1027    }
1028
1029    /// Read-only is an allowlist, not a subtraction (`#548`). A flare's registry used to be the
1030    /// lead's minus eight names, which left `cronjob_manage`, `skill_manage` and every plugin and
1031    /// MCP tool in it — under `auto`, `smart` or `--yes` a flare could schedule future cron runs
1032    /// and rewrite the user's skills directory while its own description said the capability was
1033    /// not there.
1034    #[test]
1035    fn a_flare_holds_the_readers_and_nothing_else() {
1036        let dir = tempfile::tempdir().unwrap();
1037        let provider = Scripted::new(&["unused"]);
1038        let extra = [
1039            "search_files",
1040            "fetch",
1041            "session_search",
1042            "skill_view",
1043            "skill_search",
1044            "cronjob_manage",
1045            "skill_manage",
1046            "plugin:notes:publish",
1047            "tool_call",
1048        ];
1049        let (tool, _store, lead) =
1050            harness_with_extra(dir.path(), provider, FlaresConfig::default(), &extra);
1051
1052        // The lead really did hold the four, or the assertion below proves nothing.
1053        for name in &extra {
1054            assert!(
1055                lead.iter().any(|held| held == name),
1056                "the lead's registry holds `{name}`: {lead:?}"
1057            );
1058        }
1059
1060        assert_eq!(
1061            tool.tools.names(),
1062            [
1063                "fetch",
1064                "read_file",
1065                "search_files",
1066                "session_search",
1067                "skill_search",
1068                "skill_view"
1069            ],
1070            "a flare holds the readers and nothing else"
1071        );
1072    }
1073
1074    #[test]
1075    fn a_group_is_one_server_worth_of_slots_and_the_cap_is_their_sum() {
1076        let local = |name: &str, parallel: usize, group: Option<&str>| RouteSlot {
1077            name: name.to_string(),
1078            parallel,
1079            group: group.map(str::to_string),
1080        };
1081        // Two routes on one box are one slot, and the box takes its lowest member's bound.
1082        let plan = slots(
1083            &[local("a", 1, Some("gpu0")), local("b", 4, Some("gpu0"))],
1084            4,
1085        );
1086        assert_eq!(plan.per_group.get("gpu0"), Some(&1));
1087        assert_eq!(plan.total, 1, "two routes on one server are one slot");
1088
1089        // Three local readers and one cloud thinker: two slots, not four.
1090        let plan = slots(
1091            &[
1092                local("read1", 1, Some("gpu0")),
1093                local("read2", 1, Some("gpu0")),
1094                local("read3", 1, Some("gpu0")),
1095                local("cloud", 4, None),
1096            ],
1097            4,
1098        );
1099        // The local group is one slot and the cloud route four: four in flight, and no more
1100        // than `max_concurrent` allows.
1101        assert_eq!(plan.total, 4, "one local slot plus the cloud route's four");
1102        assert_eq!(plan.per_group.len(), 2);
1103
1104        // `max_concurrent` is a ceiling, never a floor: a config that allows four on a box with
1105        // one slot gets one.
1106        let plan = slots(&[local("a", 1, None)], 16);
1107        assert_eq!(plan.total, 1, "one slot is one slot");
1108    }
1109
1110    #[tokio::test]
1111    async fn a_run_is_n_read_only_sessions_in_the_leads_order_with_one_merge() {
1112        let dir = tempfile::tempdir().unwrap();
1113        let provider = Scripted::new(&["alpha", "beta"]);
1114        let (tool, store) = harness(dir.path(), Arc::clone(&provider), FlaresConfig::default());
1115        let scope = crate::tools::RunScope::new("lead-session");
1116        let call = CallScope {
1117            approver: &DenyAll,
1118            run: &scope,
1119            registry: &ToolRegistry::new(4096),
1120            call_id: None,
1121        };
1122        let args = json!({"jobs": [
1123            {"prompt": "read the first crate"},
1124            {"prompt": "read the second crate"}
1125        ]});
1126        let text = tool.call_scoped(args, &call).await.unwrap();
1127
1128        assert!(text.contains("2 of 2 finished"), "{text}");
1129        assert!(text.contains("--- flare 1 (local) ---"), "{text}");
1130        assert!(text.contains("alpha") && text.contains("beta"), "{text}");
1131
1132        // Two sessions, both flares, positions 1 and 2, and the store knows the run.
1133        let runs = store.flare_runs(10).unwrap();
1134        assert_eq!(runs.len(), 1, "{runs:?}");
1135        let run = &runs[0];
1136        assert_eq!(run.jobs, 2);
1137        assert_eq!(run.state, "done");
1138        assert_eq!(run.parent.as_deref(), Some("lead-session"));
1139        assert_eq!(run.iterations, 2, "one call per flare");
1140        let (_, jobs) = store.flare_run(&run.id).unwrap().unwrap();
1141        assert_eq!(
1142            jobs.iter().map(|j| j.n).collect::<Vec<_>>(),
1143            vec![1, 2],
1144            "the ledger keeps the lead's order"
1145        );
1146        assert!(jobs.iter().all(|j| j.state == "done"));
1147        let sessions = store.flares_of(&run.id).unwrap();
1148        assert_eq!(sessions.len(), 2);
1149        assert_eq!(sessions[0].flare().unwrap().n, 1);
1150
1151        // And the one claim that makes a fan-out safe: the write tool was not offered at all.
1152        let offered = provider.offered.lock().unwrap();
1153        assert!(
1154            offered
1155                .iter()
1156                .all(|tools| !tools.iter().any(|t| t == "write_file")),
1157            "a flare was offered write_file: {offered:?}"
1158        );
1159        assert!(offered
1160            .iter()
1161            .all(|tools| tools.iter().any(|t| t == "read_file")));
1162    }
1163
1164    /// `#553`: the runtime cancels by dropping the future, so `call_scoped` never reached the code
1165    /// that closes the ledger and the row stayed `running` — a run nothing could ever cancel.
1166    #[tokio::test]
1167    async fn a_dropped_flare_call_closes_its_run_as_cancelled() {
1168        let dir = tempfile::tempdir().unwrap();
1169        let provider = Scripted::hanging();
1170        let (tool, store) = harness(dir.path(), Arc::clone(&provider), FlaresConfig::default());
1171        let scope = crate::tools::RunScope::new("lead");
1172        let call = CallScope {
1173            approver: &DenyAll,
1174            run: &scope,
1175            registry: &ToolRegistry::new(4096),
1176            call_id: None,
1177        };
1178        let mut fut = Box::pin(tool.call_scoped(json!({"jobs": [{"prompt": "one"}]}), &call));
1179        // One poll writes the ledger row and gets the job in flight; then the future is dropped,
1180        // which is exactly what `select!` does when the run is cancelled.
1181        assert!(
1182            futures_util::poll!(fut.as_mut()).is_pending(),
1183            "the job must still be running for this to be a cancellation"
1184        );
1185        drop(fut);
1186
1187        let run = &store.flare_runs(10).unwrap()[0];
1188        assert_eq!(
1189            run.state, "cancelled",
1190            "a dropped run is not left `running` for ever"
1191        );
1192    }
1193
1194    #[tokio::test]
1195    async fn a_run_whose_budget_runs_out_drops_the_rest_and_says_so() {
1196        let dir = tempfile::tempdir().unwrap();
1197        let provider = Scripted::new(&["only one"]);
1198        let cfg = FlaresConfig {
1199            // One iteration in the whole run: the first flare spends it, the second never starts.
1200            total_iterations: 1,
1201            ..Default::default()
1202        };
1203        let (tool, store) = harness(dir.path(), Arc::clone(&provider), cfg);
1204        let scope = crate::tools::RunScope::new("lead");
1205        let call = CallScope {
1206            approver: &DenyAll,
1207            run: &scope,
1208            registry: &ToolRegistry::new(4096),
1209            call_id: None,
1210        };
1211        let text = tool
1212            .call_scoped(
1213                json!({"jobs": [{"prompt": "one", "max_iterations": 1}, {"prompt": "two"}]}),
1214                &call,
1215            )
1216            .await
1217            .unwrap();
1218        assert!(text.contains("1 of 2 finished"), "{text}");
1219        assert!(text.contains("1 dropped"), "{text}");
1220        assert!(text.contains("budget"), "{text}");
1221
1222        let run = &store.flare_runs(10).unwrap()[0];
1223        let (_, jobs) = store.flare_run(&run.id).unwrap().unwrap();
1224        assert_eq!(jobs[1].state, "dropped");
1225        assert!(
1226            jobs[1]
1227                .why
1228                .as_deref()
1229                .unwrap_or_default()
1230                .contains("budget"),
1231            "{:?}",
1232            jobs[1]
1233        );
1234        // A dropped flare has no session: there is nothing to open.
1235        assert!(store.flares_of(&run.id).unwrap().len() == 1);
1236    }
1237
1238    struct DenyAll;
1239    #[async_trait]
1240    impl Approver for DenyAll {
1241        async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
1242            crate::approvals::Decision::Deny("no".into())
1243        }
1244    }
1245
1246    /// `#555`: `[flares] max_concurrent` is a cap on children at once, not a number that is
1247    /// computed and dropped. Six children, two permits: never three live.
1248    #[tokio::test]
1249    async fn the_flare_gate_holds_the_run_to_its_total() {
1250        use std::sync::atomic::{AtomicUsize, Ordering};
1251        let gate = Arc::new(tokio::sync::Semaphore::new(2));
1252        let live = Arc::new(AtomicUsize::new(0));
1253        let peak = Arc::new(AtomicUsize::new(0));
1254        let mut handles = Vec::new();
1255        for _ in 0..6 {
1256            let (gate, live, peak) = (Arc::clone(&gate), Arc::clone(&live), Arc::clone(&peak));
1257            handles.push(tokio::spawn(async move {
1258                gated(&gate, async move {
1259                    let now = live.fetch_add(1, Ordering::SeqCst) + 1;
1260                    peak.fetch_max(now, Ordering::SeqCst);
1261                    tokio::time::sleep(Duration::from_millis(20)).await;
1262                    live.fetch_sub(1, Ordering::SeqCst);
1263                })
1264                .await;
1265            }));
1266        }
1267        for handle in handles {
1268            handle.await.expect("no panic in the child");
1269        }
1270        assert_eq!(
1271            peak.load(Ordering::SeqCst),
1272            2,
1273            "two at a time, not six: the setting did nothing before this"
1274        );
1275    }
1276
1277    /// `#554`: a cancel from another process is a row. With every lane busy the flag was never
1278    /// read again, so the run kept spending after `flares cancel`. The watcher is the bridge from
1279    /// that row to the token a child actually watches.
1280    #[tokio::test]
1281    async fn a_cancel_from_another_process_stops_a_started_child() {
1282        let dir = tempfile::tempdir().unwrap();
1283        let store = SessionStore::new(dir.path().join("sessions"));
1284        store
1285            .begin_flare_run("r1", "a task", &["local".into()], 1, "parent")
1286            .unwrap();
1287        let parent = Cancel::new();
1288        let child = Cancel::new();
1289        let watch = watch_cancel(parent.clone(), child.clone(), store.clone(), "r1".into());
1290        assert!(!child.is_cancelled(), "nothing has asked it to stop");
1291        store.cancel_flare_run("r1").unwrap();
1292        tokio::time::sleep(CANCEL_POLL * 3).await;
1293        assert!(
1294            child.is_cancelled(),
1295            "the store's flag reached the child that was already running"
1296        );
1297        watch.abort();
1298
1299        // And the parent's own token still works, which is the path Esc takes in-process.
1300        let (parent, child) = (Cancel::new(), Cancel::new());
1301        let watch = watch_cancel(parent.clone(), child.clone(), store.clone(), "r2".into());
1302        parent.cancel();
1303        tokio::time::sleep(CANCEL_POLL * 3).await;
1304        assert!(child.is_cancelled(), "the parent's token");
1305        watch.abort();
1306    }
1307}