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