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