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        let result = self
413            .execute(&run, &jobs, merge, scope.approver, &scope.run.cancel)
414            .await;
415
416        let merged = result.merge(merge);
417        // The ledger closes even when the run failed: a row left `running` is a run nothing can
418        // ever cancel.
419        let state = if result.lines.iter().any(|l| l.state == State::Dropped) {
420            "cancelled"
421        } else if result.lines.iter().any(|l| l.state == State::Failed) {
422            "failed"
423        } else {
424            "done"
425        };
426        let _ = self.store.finish_flare_run(
427            &run,
428            state,
429            result.prompt_tokens(),
430            result.completion_tokens(),
431            result.iterations(),
432        );
433
434        Ok(result.readout(&run, merge, &merged))
435    }
436}
437
438/// A finished run: its children, in the lead's order.
439pub struct RunResult {
440    pub run: String,
441    pub lines: Vec<FlareLine>,
442}
443
444impl RunResult {
445    pub fn prompt_tokens(&self) -> Option<u64> {
446        self.lines
447            .iter()
448            .filter_map(|l| l.prompt_tokens)
449            .reduce(|a, b| a + b)
450    }
451
452    pub fn completion_tokens(&self) -> Option<u64> {
453        self.lines
454            .iter()
455            .filter_map(|l| l.completion_tokens)
456            .reduce(|a, b| a + b)
457    }
458
459    pub fn iterations(&self) -> usize {
460        self.lines.iter().map(|l| l.iterations).sum()
461    }
462
463    /// The children's answers, in the order they were asked for.
464    pub fn merge(&self, how: Merge) -> String {
465        let mut out = String::new();
466        for line in &self.lines {
467            if !out.is_empty() {
468                out.push_str("\n\n");
469            }
470            match how {
471                Merge::Concat => out.push_str(&format!(
472                    "--- flare {} ({}) ---\n{}",
473                    line.n,
474                    line.route,
475                    line.text.trim()
476                )),
477                Merge::Lead => out.push_str(&format!(
478                    "--- flare {} ({}) · session {} ---\n{}\n[the lead merges these]",
479                    line.n,
480                    line.route,
481                    line.session_id.as_deref().unwrap_or("-"),
482                    line.text.trim()
483                )),
484            }
485        }
486        out
487    }
488
489    /// The heading, one line per child, and the merge — what the lead's tool result carries.
490    fn readout(&self, run: &str, _how: Merge, merged: &str) -> String {
491        let done = self.lines.iter().filter(|l| l.state == State::Done).count();
492        let dropped = self
493            .lines
494            .iter()
495            .filter(|l| l.state == State::Dropped)
496            .count();
497        let failed = self.lines.len() - done - dropped;
498        let mut out = format!(
499            "flare run `{run}`: {done} of {} finished{}{} \u{2014} {} iteration{}, {} prompt / {} completion tokens\n",
500            self.lines.len(),
501            if failed > 0 {
502                format!(", {failed} failed")
503            } else {
504                String::new()
505            },
506            if dropped > 0 {
507                format!(", {dropped} dropped")
508            } else {
509                String::new()
510            },
511            self.iterations(),
512            if self.iterations() == 1 { "" } else { "s" },
513            count(self.prompt_tokens()),
514            count(self.completion_tokens()),
515        );
516        for line in &self.lines {
517            out.push_str(&format!(
518                "  {}. {} on {} \u{b7} {}",
519                line.n,
520                line.state.word(),
521                line.route,
522                line.session_id.as_deref().unwrap_or("-")
523            ));
524            if let Some(why) = &line.why {
525                out.push_str(&format!(" \u{b7} {why}"));
526            }
527            out.push('\n');
528        }
529        out.push('\n');
530        out.push_str(merged);
531        out
532    }
533}
534
535impl FlareTool {
536    /// Start every job, in the lead's order, under the run's caps.
537    ///
538    /// One future per lane, `join_all`ed: a lane is a serial queue on one server, so concurrent
539    /// lanes are concurrent *servers*. That is why no `tokio::spawn` appears here — everything
540    /// lives in the tool call that asked for it, and a cancelled call drops the futures.
541    async fn execute(
542        &self,
543        run: &str,
544        jobs: &[FlareJob],
545        _merge: Merge,
546        approver: &dyn Approver,
547        cancel: &Cancel,
548    ) -> RunResult {
549        let slots = self.slots();
550        let mut lanes: Vec<(String, Vec<(usize, &FlareJob)>)> = Vec::new();
551        // Lanes are filled round-robin per group, so a group with two slots gets two lanes and a
552        // route with one gets one. A job goes to the lane that has least queued at that point.
553        let mut lane_of_group: BTreeMap<String, usize> = BTreeMap::new();
554        for (index, job) in jobs.iter().enumerate() {
555            let route = job
556                .route
557                .clone()
558                .unwrap_or_else(|| self.runner.default_route());
559            let key = self
560                .routes
561                .iter()
562                .find(|r| r.name == route)
563                .map(RouteSlot::key)
564                .unwrap_or_else(|| route.clone());
565            let bound = slots.per_group.get(&key).copied().unwrap_or(1).max(1);
566            let base = {
567                let next = lane_of_group.entry(key.clone()).or_insert(0);
568                let lane = *next;
569                *next = (*next + 1) % bound;
570                lane
571            };
572            let lane_key = format!("{key}#{base}");
573            match lanes.iter_mut().find(|(k, _)| *k == lane_key) {
574                Some((_, queue)) => queue.push((index + 1, job)),
575                None => lanes.push((lane_key, vec![(index + 1, job)])),
576            }
577        }
578
579        let budget = Arc::new(Mutex::new(self.cfg.budget()));
580        let spent = Arc::new(Mutex::new(0u64));
581        let token_cap = self.cfg.total_tokens;
582        let lines: Arc<Mutex<Vec<FlareLine>>> = Arc::new(Mutex::new(Vec::new()));
583
584        let lanes = futures_util::future::join_all(lanes.into_iter().map(|(_, queue)| {
585            let runner = Arc::clone(&self.runner);
586            let tools = Arc::clone(&self.tools);
587            let store = self.store.clone();
588            let budget = Arc::clone(&budget);
589            let spent = Arc::clone(&spent);
590            let lines = Arc::clone(&lines);
591            async move {
592                for (n, job) in queue {
593                    let route = job.route.clone().unwrap_or_default();
594                    // Cancelled, out of budget, or over the spend cap: a dropped flare is a row,
595                    // not a silent nothing — `flares list` has to be able to say why.
596                    if cancel.is_cancelled() {
597                        push(
598                            &lines,
599                            &store,
600                            FlareLine::dropped(n, &route, "the run was cancelled"),
601                            run,
602                        );
603                        continue;
604                    }
605                    match store.flare_cancel_requested(run) {
606                        Ok(true) => {
607                            push(
608                                &lines,
609                                &store,
610                                FlareLine::dropped(n, &route, "cancelled from another process"),
611                                run,
612                            );
613                            continue;
614                        }
615                        Ok(false) => {}
616                        Err(_) => {}
617                    }
618                    if let Some(cap) = token_cap {
619                        if *spent.lock().unwrap_or_else(|e| e.into_inner()) >= cap {
620                            push(
621                                &lines,
622                                &store,
623                                FlareLine::dropped(n, &route, "the run's token cap was reached"),
624                                run,
625                            );
626                            continue;
627                        }
628                    }
629                    let take = {
630                        let mut left = budget.lock().unwrap_or_else(|e| e.into_inner());
631                        let want = job
632                            .max_iterations
633                            .unwrap_or(self.cfg.per_flare())
634                            .min(*left);
635                        *left -= want;
636                        want
637                    };
638                    if take == 0 {
639                        push(
640                            &lines,
641                            &store,
642                            FlareLine::dropped(n, &route, "the run's iteration budget was spent"),
643                            run,
644                        );
645                        continue;
646                    }
647                    let session_id = runner.new_session_id();
648                    let _ = store.flare_job_running(run, n, &route, &session_id);
649                    let outcome = runner
650                        .run_child(
651                            Arc::clone(&tools),
652                            ChildJob {
653                                session_id: &session_id,
654                                prompt: &job.prompt,
655                                system: job.system.as_deref(),
656                                route: &route,
657                                budget: take,
658                                origin: ChildOrigin::Flare { run, n },
659                            },
660                            approver,
661                            cancel,
662                        )
663                        .await;
664                    let (state, text, why) = match outcome.answer {
665                        Ok(text) => (State::Done, text, None),
666                        Err(reason) => (State::Failed, String::new(), Some(reason)),
667                    };
668                    if let Some(p) = outcome.prompt_tokens {
669                        *spent.lock().unwrap_or_else(|e| e.into_inner()) += p;
670                    }
671                    if let Some(c) = outcome.completion_tokens {
672                        *spent.lock().unwrap_or_else(|e| e.into_inner()) += c;
673                    }
674                    push(
675                        &lines,
676                        &store,
677                        FlareLine {
678                            n,
679                            route: outcome.route.clone(),
680                            session_id: Some(session_id),
681                            state,
682                            text,
683                            why,
684                            prompt_tokens: outcome.prompt_tokens,
685                            completion_tokens: outcome.completion_tokens,
686                            iterations: outcome.iterations,
687                        },
688                        run,
689                    );
690                }
691            }
692        }))
693        .await;
694        let _ = lanes;
695        let mut lines = lines
696            .lock()
697            .map(|l| l.clone())
698            .unwrap_or_else(|e| e.into_inner().clone());
699        lines.sort_by_key(|l| l.n);
700        RunResult {
701            run: run.to_string(),
702            lines,
703        }
704    }
705}
706
707/// Record one child's row and keep it for the merge.
708fn push(lines: &Arc<Mutex<Vec<FlareLine>>>, store: &SessionStore, line: FlareLine, run: &str) {
709    let _ = store.flare_job_done(&FlareJobRow {
710        run_id: run.to_string(),
711        n: line.n,
712        route: line.route.clone(),
713        session_id: line.session_id.clone(),
714        state: line.state.word().to_string(),
715        prompt_tokens: line.prompt_tokens,
716        completion_tokens: line.completion_tokens,
717        iterations: line.iterations,
718        why: line.why.clone(),
719    });
720    if let Ok(mut all) = lines.lock() {
721        all.push(line);
722    }
723}
724
725fn count(tokens: Option<u64>) -> String {
726    tokens.map_or_else(|| "?".to_string(), |n| n.to_string())
727}
728
729fn store_error(e: crate::error::Error) -> ToolError {
730    ToolError::Failed(format!("the flare run's ledger: {e}"))
731}
732
733#[cfg(test)]
734mod tests {
735    use super::*;
736    use crate::message::Message;
737    use crate::provider::ChatProvider;
738    use crate::router::RouteInfo;
739    use crate::tools::ToolSpec;
740    use crate::tools_delegate::{ChildProviders, DelegateSettings};
741    use crate::usage::TurnUsage;
742
743    /// A provider that hands out scripted replies and records the tools it was offered.
744    struct Scripted {
745        replies: Mutex<Vec<String>>,
746        offered: Mutex<Vec<Vec<String>>>,
747        usage: Mutex<Option<TurnUsage>>,
748    }
749
750    impl Scripted {
751        fn new(replies: &[&str]) -> Arc<Self> {
752            Arc::new(Self {
753                replies: Mutex::new(replies.iter().rev().map(|r| r.to_string()).collect()),
754                offered: Mutex::new(Vec::new()),
755                usage: Mutex::new(Some(TurnUsage {
756                    prompt_tokens: Some(10),
757                    completion_tokens: Some(2),
758                    ..TurnUsage::default()
759                })),
760            })
761        }
762    }
763
764    #[async_trait]
765    impl ChatProvider for Scripted {
766        async fn chat(&self, _: &[Message], tools: &[ToolSpec]) -> crate::Result<Message> {
767            self.offered
768                .lock()
769                .unwrap()
770                .push(tools.iter().map(|t| t.function.name.clone()).collect());
771            let reply = self
772                .replies
773                .lock()
774                .unwrap()
775                .pop()
776                .unwrap_or_else(|| "no reply scripted".to_string());
777            Ok(Message::assistant(&reply))
778        }
779        fn take_usage(&self) -> Option<TurnUsage> {
780            self.usage.lock().unwrap().take()
781        }
782    }
783
784    struct Routes {
785        routes: Vec<(String, Arc<dyn ChatProvider>)>,
786        default: String,
787    }
788
789    impl ChildProviders for Routes {
790        fn routes(&self) -> Vec<RouteInfo> {
791            self.routes
792                .iter()
793                .map(|(n, _)| RouteInfo {
794                    name: n.clone(),
795                    model: format!("{n}-model"),
796                    endpoint: String::new(),
797                })
798                .collect()
799        }
800        fn default_route(&self) -> String {
801            self.default.clone()
802        }
803        fn provider(
804            &self,
805            name: &str,
806        ) -> std::result::Result<crate::tools_delegate::ChildRoute, String> {
807            self.routes
808                .iter()
809                .find(|(n, _)| n == name)
810                .map(|(_, p)| crate::tools_delegate::ChildRoute {
811                    name: name.to_string(),
812                    provider: Arc::clone(p),
813                    context_budget_tokens: 8000,
814                })
815                .ok_or_else(|| format!("unknown route `{name}`"))
816        }
817    }
818
819    /// The tool a lead would hold: three read tools and one write tool, so a flare's registry can
820    /// be shown to be missing the one that matters.
821    struct ReadFile;
822    #[async_trait]
823    impl Tool for ReadFile {
824        fn name(&self) -> &str {
825            "read_file"
826        }
827        fn description(&self) -> &str {
828            "read"
829        }
830        fn parameters(&self) -> Value {
831            json!({"type": "object"})
832        }
833        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
834            Ok("contents".into())
835        }
836    }
837    struct WriteFile;
838    #[async_trait]
839    impl Tool for WriteFile {
840        fn name(&self) -> &str {
841            "write_file"
842        }
843        fn description(&self) -> &str {
844            "write"
845        }
846        fn parameters(&self) -> Value {
847            json!({"type": "object"})
848        }
849        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
850            Ok("written".into())
851        }
852    }
853
854    /// A tool that exists only to be named: these tests are about which names a registry holds,
855    /// not about what the tools do.
856    struct Named(&'static str);
857
858    #[async_trait]
859    impl Tool for Named {
860        fn name(&self) -> &str {
861            self.0
862        }
863        fn description(&self) -> &str {
864            "named"
865        }
866        fn parameters(&self) -> Value {
867            json!({"type": "object"})
868        }
869        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
870            Ok(String::new())
871        }
872    }
873
874    fn harness(
875        dir: &std::path::Path,
876        provider: Arc<Scripted>,
877        cfg: FlaresConfig,
878    ) -> (FlareTool, SessionStore) {
879        let (tool, store, _) = harness_with_extra(dir, provider, cfg, &[]);
880        (tool, store)
881    }
882
883    /// The same harness with extra tools in the lead's registry, and the names the lead ended up
884    /// with — a test about what a flare does *not* hold has to prove the lead held it.
885    fn harness_with_extra(
886        dir: &std::path::Path,
887        provider: Arc<Scripted>,
888        cfg: FlaresConfig,
889        extra: &[&'static str],
890    ) -> (FlareTool, SessionStore, Vec<String>) {
891        let store = SessionStore::new(dir.join("sessions"));
892        let mut registry = ToolRegistry::new(4096);
893        registry.register(Arc::new(ReadFile), crate::config::Policy::Allow);
894        registry.register(Arc::new(WriteFile), crate::config::Policy::Allow);
895        for name in extra {
896            registry.register(Arc::new(Named(name)), crate::config::Policy::Allow);
897        }
898        let lead_names = registry.names();
899        let routes = Routes {
900            routes: vec![("local".to_string(), provider as Arc<dyn ChatProvider>)],
901            default: "local".to_string(),
902        };
903        let delegate = Arc::new(DelegateTool::new(
904            Arc::new(routes),
905            Arc::new(registry),
906            store.clone(),
907            DelegateSettings {
908                max_output_bytes: 8000,
909                max_malformed_calls: 3,
910                tool_concurrency: 1,
911                lock_wait: std::time::Duration::from_secs(5),
912            },
913        ));
914        let slots = vec![RouteSlot {
915            name: "local".to_string(),
916            parallel: 1,
917            group: None,
918        }];
919        (
920            FlareTool::new(delegate, store.clone(), cfg, slots),
921            store,
922            lead_names,
923        )
924    }
925
926    /// Read-only is an allowlist, not a subtraction (`#548`). A flare's registry used to be the
927    /// lead's minus eight names, which left `cronjob_manage`, `skill_manage` and every plugin and
928    /// MCP tool in it — under `auto`, `smart` or `--yes` a flare could schedule future cron runs
929    /// and rewrite the user's skills directory while its own description said the capability was
930    /// not there.
931    #[test]
932    fn a_flare_holds_the_readers_and_nothing_else() {
933        let dir = tempfile::tempdir().unwrap();
934        let provider = Scripted::new(&["unused"]);
935        let extra = [
936            "search_files",
937            "fetch",
938            "session_search",
939            "skill_view",
940            "skill_search",
941            "cronjob_manage",
942            "skill_manage",
943            "plugin:notes:publish",
944            "tool_call",
945        ];
946        let (tool, _store, lead) =
947            harness_with_extra(dir.path(), provider, FlaresConfig::default(), &extra);
948
949        // The lead really did hold the four, or the assertion below proves nothing.
950        for name in &extra {
951            assert!(
952                lead.iter().any(|held| held == name),
953                "the lead's registry holds `{name}`: {lead:?}"
954            );
955        }
956
957        assert_eq!(
958            tool.tools.names(),
959            [
960                "fetch",
961                "read_file",
962                "search_files",
963                "session_search",
964                "skill_search",
965                "skill_view"
966            ],
967            "a flare holds the readers and nothing else"
968        );
969    }
970
971    #[test]
972    fn a_group_is_one_server_worth_of_slots_and_the_cap_is_their_sum() {
973        let local = |name: &str, parallel: usize, group: Option<&str>| RouteSlot {
974            name: name.to_string(),
975            parallel,
976            group: group.map(str::to_string),
977        };
978        // Two routes on one box are one slot, and the box takes its lowest member's bound.
979        let plan = slots(
980            &[local("a", 1, Some("gpu0")), local("b", 4, Some("gpu0"))],
981            4,
982        );
983        assert_eq!(plan.per_group.get("gpu0"), Some(&1));
984        assert_eq!(plan.total, 1, "two routes on one server are one slot");
985
986        // Three local readers and one cloud thinker: two slots, not four.
987        let plan = slots(
988            &[
989                local("read1", 1, Some("gpu0")),
990                local("read2", 1, Some("gpu0")),
991                local("read3", 1, Some("gpu0")),
992                local("cloud", 4, None),
993            ],
994            4,
995        );
996        // The local group is one slot and the cloud route four: four in flight, and no more
997        // than `max_concurrent` allows.
998        assert_eq!(plan.total, 4, "one local slot plus the cloud route's four");
999        assert_eq!(plan.per_group.len(), 2);
1000
1001        // `max_concurrent` is a ceiling, never a floor: a config that allows four on a box with
1002        // one slot gets one.
1003        let plan = slots(&[local("a", 1, None)], 16);
1004        assert_eq!(plan.total, 1, "one slot is one slot");
1005    }
1006
1007    #[tokio::test]
1008    async fn a_run_is_n_read_only_sessions_in_the_leads_order_with_one_merge() {
1009        let dir = tempfile::tempdir().unwrap();
1010        let provider = Scripted::new(&["alpha", "beta"]);
1011        let (tool, store) = harness(dir.path(), Arc::clone(&provider), FlaresConfig::default());
1012        let scope = crate::tools::RunScope::new("lead-session");
1013        let call = CallScope {
1014            approver: &DenyAll,
1015            run: &scope,
1016            registry: &ToolRegistry::new(4096),
1017            call_id: None,
1018        };
1019        let args = json!({"jobs": [
1020            {"prompt": "read the first crate"},
1021            {"prompt": "read the second crate"}
1022        ]});
1023        let text = tool.call_scoped(args, &call).await.unwrap();
1024
1025        assert!(text.contains("2 of 2 finished"), "{text}");
1026        assert!(text.contains("--- flare 1 (local) ---"), "{text}");
1027        assert!(text.contains("alpha") && text.contains("beta"), "{text}");
1028
1029        // Two sessions, both flares, positions 1 and 2, and the store knows the run.
1030        let runs = store.flare_runs(10).unwrap();
1031        assert_eq!(runs.len(), 1, "{runs:?}");
1032        let run = &runs[0];
1033        assert_eq!(run.jobs, 2);
1034        assert_eq!(run.state, "done");
1035        assert_eq!(run.parent.as_deref(), Some("lead-session"));
1036        assert_eq!(run.iterations, 2, "one call per flare");
1037        let (_, jobs) = store.flare_run(&run.id).unwrap().unwrap();
1038        assert_eq!(
1039            jobs.iter().map(|j| j.n).collect::<Vec<_>>(),
1040            vec![1, 2],
1041            "the ledger keeps the lead's order"
1042        );
1043        assert!(jobs.iter().all(|j| j.state == "done"));
1044        let sessions = store.flares_of(&run.id).unwrap();
1045        assert_eq!(sessions.len(), 2);
1046        assert_eq!(sessions[0].flare().unwrap().n, 1);
1047
1048        // And the one claim that makes a fan-out safe: the write tool was not offered at all.
1049        let offered = provider.offered.lock().unwrap();
1050        assert!(
1051            offered
1052                .iter()
1053                .all(|tools| !tools.iter().any(|t| t == "write_file")),
1054            "a flare was offered write_file: {offered:?}"
1055        );
1056        assert!(offered
1057            .iter()
1058            .all(|tools| tools.iter().any(|t| t == "read_file")));
1059    }
1060
1061    #[tokio::test]
1062    async fn a_run_whose_budget_runs_out_drops_the_rest_and_says_so() {
1063        let dir = tempfile::tempdir().unwrap();
1064        let provider = Scripted::new(&["only one"]);
1065        let cfg = FlaresConfig {
1066            // One iteration in the whole run: the first flare spends it, the second never starts.
1067            total_iterations: 1,
1068            ..Default::default()
1069        };
1070        let (tool, store) = harness(dir.path(), Arc::clone(&provider), cfg);
1071        let scope = crate::tools::RunScope::new("lead");
1072        let call = CallScope {
1073            approver: &DenyAll,
1074            run: &scope,
1075            registry: &ToolRegistry::new(4096),
1076            call_id: None,
1077        };
1078        let text = tool
1079            .call_scoped(
1080                json!({"jobs": [{"prompt": "one", "max_iterations": 1}, {"prompt": "two"}]}),
1081                &call,
1082            )
1083            .await
1084            .unwrap();
1085        assert!(text.contains("1 of 2 finished"), "{text}");
1086        assert!(text.contains("1 dropped"), "{text}");
1087        assert!(text.contains("budget"), "{text}");
1088
1089        let run = &store.flare_runs(10).unwrap()[0];
1090        let (_, jobs) = store.flare_run(&run.id).unwrap().unwrap();
1091        assert_eq!(jobs[1].state, "dropped");
1092        assert!(
1093            jobs[1]
1094                .why
1095                .as_deref()
1096                .unwrap_or_default()
1097                .contains("budget"),
1098            "{:?}",
1099            jobs[1]
1100        );
1101        // A dropped flare has no session: there is nothing to open.
1102        assert!(store.flares_of(&run.id).unwrap().len() == 1);
1103    }
1104
1105    struct DenyAll;
1106    #[async_trait]
1107    impl Approver for DenyAll {
1108        async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
1109            crate::approvals::Decision::Deny("no".into())
1110        }
1111    }
1112}