eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
//! `#171`: a flare run — N read-only sibling agents on one task, and the merge of what they said.
//!
//! A **flare** is one child agent: its own session (`origin = "flare:<run>:<n>"`), its own route,
//! a small iteration budget, and a registry with the write tools **taken out**. A **flare run** is
//! the set of them on one task, plus the merge. The lead is unchanged — it is the only agent that
//! writes.
//!
//! This is not a second runtime. A flare is what a `delegate` child is, times N, plus a scheduler:
//! [`DelegateTool::run_child`] builds both, so the preamble, the hooks, the usage capture and the
//! cancellation are one implementation with two callers.
//!
//! # Why local runs are serial, and why that is correct
//!
//! A local server serves one model at a time — llama-swap swaps by stopping one to start another —
//! so N flares on one local route are N sequential turns. Parallelism buys nothing there; what it
//! buys is **isolation**: each flare reads its own files, and the lead's context never fills with
//! them. Mixed routes are the case where concurrency is real: three cheap local readers plus one
//! cloud thinker run in two slots, not four. So the cap is per *server*, which is why a route can
//! name a `group`: two routes pointed at one box are one slot.
//!
//! # What keeps a fan-out safe
//!
//! Every flare is read-only, and read-only is a property of its registry, not of a policy: the
//! write tools are removed by [`crate::tools::ToolRegistry::without`], so a `tool_call` bridge
//! cannot reach one. Approvals stay one at a time on purpose (`runtime.rs`'s gate), and a
//! read-only flare asks nothing at all.

use crate::cancel::Cancel;
use crate::config::FlaresConfig;
use crate::session::{FlareJobRow, SessionStore};
use crate::tools::{Approver, CallScope, Tool, ToolError, ToolRegistry};
use crate::tools_delegate::{ChildJob, ChildOrigin, DelegateTool};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};

/// The tools a flare never has (`#171`). Removed from its registry, not disabled: the whole claim
/// of a read-only fan-out is that the capability is not there.
///
/// `delegate` and `flares` are on the list for the reason a `delegate` child does not get
/// `delegate` — no nesting — and `memory` because a flare is a worker, not an identity: it has no
/// memory of its own to write to.
pub const WRITE_TOOLS: &[&str] = &[
    "write_file",
    "patch",
    "shell",
    "script",
    "execute_code",
    "memory",
    "delegate",
    "flares",
];

/// The most jobs one call may name. A model that wants more has not split the task, it has
/// multiplied it; the CLI's `-n` is where a bigger number is typed deliberately.
pub const MAX_FLARES_PER_RUN: usize = 16;

/// One job as the lead states it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlareJob {
    pub prompt: String,
    pub route: Option<String>,
    pub max_iterations: Option<usize>,
    pub system: Option<String>,
}

/// How a run's answers come back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Merge {
    /// One block, children in the lead's order.
    Concat,
    /// The children's answers, labelled, with the instruction that the lead writes the merge.
    Lead,
}

impl Merge {
    pub fn parse(text: &str) -> Option<Self> {
        match text.trim().to_ascii_lowercase().as_str() {
            "" | "concat" => Some(Self::Concat),
            "lead" => Some(Self::Lead),
            _ => None,
        }
    }
}

/// How a child ended, as one word the ledger and the readout both use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
    Done,
    Failed,
    /// Never started: the run was cancelled, its budget was gone, or its spend cap was reached.
    Dropped,
}

impl State {
    pub fn word(self) -> &'static str {
        match self {
            Self::Done => "done",
            Self::Failed => "failed",
            Self::Dropped => "dropped",
        }
    }
}

/// One child's row in the run's report.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlareLine {
    pub n: usize,
    pub route: String,
    pub session_id: Option<String>,
    pub state: State,
    pub text: String,
    pub why: Option<String>,
    pub prompt_tokens: Option<u64>,
    pub completion_tokens: Option<u64>,
    pub iterations: usize,
}

impl FlareLine {
    fn dropped(n: usize, route: &str, why: &str) -> Self {
        Self {
            n,
            route: route.to_string(),
            session_id: None,
            state: State::Dropped,
            text: String::new(),
            why: Some(why.to_string()),
            prompt_tokens: None,
            completion_tokens: None,
            iterations: 0,
        }
    }
}

/// What a route offers a run: its name, how many flares may share it, and which server it is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteSlot {
    pub name: String,
    pub parallel: usize,
    /// Routes with the same group are one server's worth of slots.
    pub group: Option<String>,
}

impl RouteSlot {
    pub fn of(route: &crate::config::NamedRoute) -> Self {
        Self {
            name: route.name.clone(),
            parallel: route.parallel(),
            group: route.group.clone(),
        }
    }

    fn key(&self) -> String {
        self.group.clone().unwrap_or_else(|| self.name.clone())
    }
}

/// The cap a run actually has: one number per server, and the sum of them, floored by
/// `[flares] max_concurrent`.
///
/// A group takes its **lowest** member's bound — the conservative reading of "these are the same
/// box", because the cost of guessing high is a swap cycle that stops one model mid-turn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Slots {
    pub per_group: BTreeMap<String, usize>,
    pub total: usize,
}

pub fn slots(routes: &[RouteSlot], max_concurrent: usize) -> Slots {
    let mut per_group: BTreeMap<String, usize> = BTreeMap::new();
    for route in routes {
        let entry = per_group.entry(route.key()).or_insert(route.parallel);
        *entry = (*entry).min(route.parallel.max(1));
    }
    let available: usize = per_group.values().copied().sum();
    Slots {
        total: max_concurrent.max(1).min(available.max(1)),
        per_group,
    }
}

/// The `flares` tool.
pub struct FlareTool {
    runner: Arc<DelegateTool>,
    /// The registry every flare gets: the lead's, without [`WRITE_TOOLS`].
    tools: Arc<ToolRegistry>,
    store: SessionStore,
    cfg: FlaresConfig,
    routes: Vec<RouteSlot>,
    description: String,
}

impl FlareTool {
    pub fn new(
        runner: Arc<DelegateTool>,
        store: SessionStore,
        cfg: FlaresConfig,
        routes: Vec<RouteSlot>,
    ) -> Self {
        let description = format!(
            "Run several read-only agents on one task at the same time. Name every job: a job is \
             one prompt and the route it runs on. Each agent gets its own session, its own route \
             and a small iteration budget, cannot write (no `write_file`, `patch`, `shell`, \
             `script`, `execute_code`) and cannot delegate. Use it to read several things at once \
             and get one answer back; do not use it for work you could do in one turn. At most \
             {MAX_FLARES_PER_RUN} jobs."
        );
        Self {
            tools: Arc::new(runner.flare_registry()),
            runner,
            store,
            cfg,
            routes,
            description,
        }
    }

    /// The cap this tool's routes give it.
    pub fn slots(&self) -> Slots {
        slots(&self.routes, self.cfg.concurrency())
    }

    fn resolve_route(&self, named: Option<&str>) -> Result<String, ToolError> {
        let name = match named {
            Some(name) => name.to_string(),
            None => self.runner.default_route(),
        };
        if self.routes.iter().any(|r| r.name == name) {
            return Ok(name);
        }
        Err(ToolError::InvalidArgs(format!(
            "`{name}` is not a route this agent can use. Declared: {}",
            self.routes
                .iter()
                .map(|r| r.name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        )))
    }
}

#[async_trait]
impl Tool for FlareTool {
    fn name(&self) -> &str {
        "flares"
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "jobs": {
                    "type": "array",
                    "minItems": 1,
                    "maxItems": MAX_FLARES_PER_RUN,
                    "description": "One entry per agent. Name the jobs — never a count.",
                    "items": {
                        "type": "object",
                        "properties": {
                            "prompt": {
                                "type": "string",
                                "description": "The job, stated so it makes sense with no other context."
                            },
                            "route": {
                                "type": "string",
                                "description": "Which route this agent runs on. Unset: the delegate route, else this run's."
                            },
                            "max_iterations": {
                                "type": "integer",
                                "minimum": 1,
                                "description": "Model requests this agent may make. Unset: the configured default."
                            },
                            "system": {
                                "type": "string",
                                "description": "Extra instructions for this agent, added to its preamble."
                            }
                        },
                        "required": ["prompt"]
                    }
                },
                "merge": {
                    "type": "string",
                    "enum": ["concat", "lead"],
                    "description": "`concat` (default) joins the answers; `lead` returns them labelled and the lead writes the merge."
                }
            },
            "required": ["jobs"]
        })
    }

    fn describe_call(&self, args: &Value) -> String {
        let jobs = args
            .get("jobs")
            .and_then(Value::as_array)
            .map(|a| a.len())
            .unwrap_or(0);
        let routes: Vec<String> = args
            .get("jobs")
            .and_then(Value::as_array)
            .map(|jobs| {
                let mut seen: Vec<String> = Vec::new();
                for job in jobs {
                    if let Some(route) = job.get("route").and_then(Value::as_str) {
                        if !seen.iter().any(|r| r == route) {
                            seen.push(route.to_string());
                        }
                    }
                }
                seen
            })
            .unwrap_or_default();
        let routes = if routes.is_empty() {
            self.runner.default_route()
        } else {
            routes.join(", ")
        };
        format!("flare run: {jobs} read-only agent(s) on {routes}")
    }

    async fn call(&self, _args: Value) -> Result<String, ToolError> {
        Err(ToolError::Failed(
            "`flares` only runs inside an agent run".into(),
        ))
    }

    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
        let raw = args
            .get("jobs")
            .and_then(Value::as_array)
            .ok_or_else(|| ToolError::InvalidArgs("`jobs` is not a list".into()))?;
        if raw.is_empty() {
            return Err(ToolError::InvalidArgs("`jobs` is empty".into()));
        }
        if raw.len() > MAX_FLARES_PER_RUN {
            return Err(ToolError::InvalidArgs(format!(
                "{} jobs is more than the {MAX_FLARES_PER_RUN} one run may start; split the task",
                raw.len()
            )));
        }
        let merge = match args.get("merge") {
            None | Some(Value::Null) => Merge::Concat,
            Some(Value::String(s)) => Merge::parse(s).ok_or_else(|| {
                ToolError::InvalidArgs(format!("`merge` is `concat` or `lead`, not {s:?}"))
            })?,
            Some(_) => return Err(ToolError::InvalidArgs("`merge` is not a string".into())),
        };

        let mut jobs = Vec::with_capacity(raw.len());
        for job in raw {
            let prompt = job
                .get("prompt")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .trim();
            if prompt.is_empty() {
                return Err(ToolError::InvalidArgs("every job needs a `prompt`".into()));
            }
            let route = match job.get("route") {
                None | Some(Value::Null) => None,
                Some(Value::String(s)) => Some(self.resolve_route(Some(s))?),
                Some(_) => return Err(ToolError::InvalidArgs("`route` is not a string".into())),
            };
            let max_iterations = match job.get("max_iterations") {
                None | Some(Value::Null) => None,
                Some(Value::Number(n)) => n.as_u64().map(|n| n.max(1) as usize),
                Some(_) => {
                    return Err(ToolError::InvalidArgs(
                        "`max_iterations` is not a number".into(),
                    ))
                }
            };
            jobs.push(FlareJob {
                prompt: prompt.to_string(),
                route: Some(route.unwrap_or_else(|| self.runner.default_route())),
                max_iterations,
                system: job
                    .get("system")
                    .and_then(Value::as_str)
                    .map(str::to_string),
            });
        }

        let run = self.store.new_id();
        let task = crate::compact::clean(&jobs[0].prompt, 200);
        let routes: Vec<String> = {
            let mut seen: Vec<String> = Vec::new();
            for job in &jobs {
                let name = job.route.clone().unwrap_or_default();
                if !seen.contains(&name) {
                    seen.push(name);
                }
            }
            seen
        };
        self.store
            .begin_flare_run(&run, &task, &routes, jobs.len(), &scope.run.session)
            .map_err(store_error)?;

        let result = self
            .execute(&run, &jobs, merge, scope.approver, &scope.run.cancel)
            .await;

        let merged = result.merge(merge);
        // The ledger closes even when the run failed: a row left `running` is a run nothing can
        // ever cancel.
        let state = if result.lines.iter().any(|l| l.state == State::Dropped) {
            "cancelled"
        } else if result.lines.iter().any(|l| l.state == State::Failed) {
            "failed"
        } else {
            "done"
        };
        let _ = self.store.finish_flare_run(
            &run,
            state,
            result.prompt_tokens(),
            result.completion_tokens(),
            result.iterations(),
        );

        Ok(result.readout(&run, merge, &merged))
    }
}

/// A finished run: its children, in the lead's order.
pub struct RunResult {
    pub run: String,
    pub lines: Vec<FlareLine>,
}

impl RunResult {
    pub fn prompt_tokens(&self) -> Option<u64> {
        self.lines
            .iter()
            .filter_map(|l| l.prompt_tokens)
            .reduce(|a, b| a + b)
    }

    pub fn completion_tokens(&self) -> Option<u64> {
        self.lines
            .iter()
            .filter_map(|l| l.completion_tokens)
            .reduce(|a, b| a + b)
    }

    pub fn iterations(&self) -> usize {
        self.lines.iter().map(|l| l.iterations).sum()
    }

    /// The children's answers, in the order they were asked for.
    pub fn merge(&self, how: Merge) -> String {
        let mut out = String::new();
        for line in &self.lines {
            if !out.is_empty() {
                out.push_str("\n\n");
            }
            match how {
                Merge::Concat => out.push_str(&format!(
                    "--- flare {} ({}) ---\n{}",
                    line.n,
                    line.route,
                    line.text.trim()
                )),
                Merge::Lead => out.push_str(&format!(
                    "--- flare {} ({}) · session {} ---\n{}\n[the lead merges these]",
                    line.n,
                    line.route,
                    line.session_id.as_deref().unwrap_or("-"),
                    line.text.trim()
                )),
            }
        }
        out
    }

    /// The heading, one line per child, and the merge — what the lead's tool result carries.
    fn readout(&self, run: &str, _how: Merge, merged: &str) -> String {
        let done = self.lines.iter().filter(|l| l.state == State::Done).count();
        let dropped = self
            .lines
            .iter()
            .filter(|l| l.state == State::Dropped)
            .count();
        let failed = self.lines.len() - done - dropped;
        let mut out = format!(
            "flare run `{run}`: {done} of {} finished{}{} \u{2014} {} iteration{}, {} prompt / {} completion tokens\n",
            self.lines.len(),
            if failed > 0 {
                format!(", {failed} failed")
            } else {
                String::new()
            },
            if dropped > 0 {
                format!(", {dropped} dropped")
            } else {
                String::new()
            },
            self.iterations(),
            if self.iterations() == 1 { "" } else { "s" },
            count(self.prompt_tokens()),
            count(self.completion_tokens()),
        );
        for line in &self.lines {
            out.push_str(&format!(
                "  {}. {} on {} \u{b7} {}",
                line.n,
                line.state.word(),
                line.route,
                line.session_id.as_deref().unwrap_or("-")
            ));
            if let Some(why) = &line.why {
                out.push_str(&format!(" \u{b7} {why}"));
            }
            out.push('\n');
        }
        out.push('\n');
        out.push_str(merged);
        out
    }
}

impl FlareTool {
    /// Start every job, in the lead's order, under the run's caps.
    ///
    /// One future per lane, `join_all`ed: a lane is a serial queue on one server, so concurrent
    /// lanes are concurrent *servers*. That is why no `tokio::spawn` appears here — everything
    /// lives in the tool call that asked for it, and a cancelled call drops the futures.
    async fn execute(
        &self,
        run: &str,
        jobs: &[FlareJob],
        _merge: Merge,
        approver: &dyn Approver,
        cancel: &Cancel,
    ) -> RunResult {
        let slots = self.slots();
        let mut lanes: Vec<(String, Vec<(usize, &FlareJob)>)> = Vec::new();
        // Lanes are filled round-robin per group, so a group with two slots gets two lanes and a
        // route with one gets one. A job goes to the lane that has least queued at that point.
        let mut lane_of_group: BTreeMap<String, usize> = BTreeMap::new();
        for (index, job) in jobs.iter().enumerate() {
            let route = job
                .route
                .clone()
                .unwrap_or_else(|| self.runner.default_route());
            let key = self
                .routes
                .iter()
                .find(|r| r.name == route)
                .map(RouteSlot::key)
                .unwrap_or_else(|| route.clone());
            let bound = slots.per_group.get(&key).copied().unwrap_or(1).max(1);
            let base = {
                let next = lane_of_group.entry(key.clone()).or_insert(0);
                let lane = *next;
                *next = (*next + 1) % bound;
                lane
            };
            let lane_key = format!("{key}#{base}");
            match lanes.iter_mut().find(|(k, _)| *k == lane_key) {
                Some((_, queue)) => queue.push((index + 1, job)),
                None => lanes.push((lane_key, vec![(index + 1, job)])),
            }
        }

        let budget = Arc::new(Mutex::new(self.cfg.budget()));
        let spent = Arc::new(Mutex::new(0u64));
        let token_cap = self.cfg.total_tokens;
        let lines: Arc<Mutex<Vec<FlareLine>>> = Arc::new(Mutex::new(Vec::new()));

        let lanes = futures_util::future::join_all(lanes.into_iter().map(|(_, queue)| {
            let runner = Arc::clone(&self.runner);
            let tools = Arc::clone(&self.tools);
            let store = self.store.clone();
            let budget = Arc::clone(&budget);
            let spent = Arc::clone(&spent);
            let lines = Arc::clone(&lines);
            async move {
                for (n, job) in queue {
                    let route = job.route.clone().unwrap_or_default();
                    // Cancelled, out of budget, or over the spend cap: a dropped flare is a row,
                    // not a silent nothing — `flares list` has to be able to say why.
                    if cancel.is_cancelled() {
                        push(
                            &lines,
                            &store,
                            FlareLine::dropped(n, &route, "the run was cancelled"),
                            run,
                        );
                        continue;
                    }
                    match store.flare_cancel_requested(run) {
                        Ok(true) => {
                            push(
                                &lines,
                                &store,
                                FlareLine::dropped(n, &route, "cancelled from another process"),
                                run,
                            );
                            continue;
                        }
                        Ok(false) => {}
                        Err(_) => {}
                    }
                    if let Some(cap) = token_cap {
                        if *spent.lock().unwrap_or_else(|e| e.into_inner()) >= cap {
                            push(
                                &lines,
                                &store,
                                FlareLine::dropped(n, &route, "the run's token cap was reached"),
                                run,
                            );
                            continue;
                        }
                    }
                    let take = {
                        let mut left = budget.lock().unwrap_or_else(|e| e.into_inner());
                        let want = job
                            .max_iterations
                            .unwrap_or(self.cfg.per_flare())
                            .min(*left);
                        *left -= want;
                        want
                    };
                    if take == 0 {
                        push(
                            &lines,
                            &store,
                            FlareLine::dropped(n, &route, "the run's iteration budget was spent"),
                            run,
                        );
                        continue;
                    }
                    let session_id = runner.new_session_id();
                    let _ = store.flare_job_running(run, n, &route, &session_id);
                    let outcome = runner
                        .run_child(
                            Arc::clone(&tools),
                            ChildJob {
                                session_id: &session_id,
                                prompt: &job.prompt,
                                system: job.system.as_deref(),
                                route: &route,
                                budget: take,
                                origin: ChildOrigin::Flare { run, n },
                            },
                            approver,
                            cancel,
                        )
                        .await;
                    let (state, text, why) = match outcome.answer {
                        Ok(text) => (State::Done, text, None),
                        Err(reason) => (State::Failed, String::new(), Some(reason)),
                    };
                    if let Some(p) = outcome.prompt_tokens {
                        *spent.lock().unwrap_or_else(|e| e.into_inner()) += p;
                    }
                    if let Some(c) = outcome.completion_tokens {
                        *spent.lock().unwrap_or_else(|e| e.into_inner()) += c;
                    }
                    push(
                        &lines,
                        &store,
                        FlareLine {
                            n,
                            route: outcome.route.clone(),
                            session_id: Some(session_id),
                            state,
                            text,
                            why,
                            prompt_tokens: outcome.prompt_tokens,
                            completion_tokens: outcome.completion_tokens,
                            iterations: outcome.iterations,
                        },
                        run,
                    );
                }
            }
        }))
        .await;
        let _ = lanes;
        let mut lines = lines
            .lock()
            .map(|l| l.clone())
            .unwrap_or_else(|e| e.into_inner().clone());
        lines.sort_by_key(|l| l.n);
        RunResult {
            run: run.to_string(),
            lines,
        }
    }
}

/// Record one child's row and keep it for the merge.
fn push(lines: &Arc<Mutex<Vec<FlareLine>>>, store: &SessionStore, line: FlareLine, run: &str) {
    let _ = store.flare_job_done(&FlareJobRow {
        run_id: run.to_string(),
        n: line.n,
        route: line.route.clone(),
        session_id: line.session_id.clone(),
        state: line.state.word().to_string(),
        prompt_tokens: line.prompt_tokens,
        completion_tokens: line.completion_tokens,
        iterations: line.iterations,
        why: line.why.clone(),
    });
    if let Ok(mut all) = lines.lock() {
        all.push(line);
    }
}

fn count(tokens: Option<u64>) -> String {
    tokens.map_or_else(|| "?".to_string(), |n| n.to_string())
}

fn store_error(e: crate::error::Error) -> ToolError {
    ToolError::Failed(format!("the flare run's ledger: {e}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::Message;
    use crate::provider::ChatProvider;
    use crate::router::RouteInfo;
    use crate::tools::ToolSpec;
    use crate::tools_delegate::{ChildProviders, DelegateSettings};
    use crate::usage::TurnUsage;

    /// A provider that hands out scripted replies and records the tools it was offered.
    struct Scripted {
        replies: Mutex<Vec<String>>,
        offered: Mutex<Vec<Vec<String>>>,
        usage: Mutex<Option<TurnUsage>>,
    }

    impl Scripted {
        fn new(replies: &[&str]) -> Arc<Self> {
            Arc::new(Self {
                replies: Mutex::new(replies.iter().rev().map(|r| r.to_string()).collect()),
                offered: Mutex::new(Vec::new()),
                usage: Mutex::new(Some(TurnUsage {
                    prompt_tokens: Some(10),
                    completion_tokens: Some(2),
                    ..TurnUsage::default()
                })),
            })
        }
    }

    #[async_trait]
    impl ChatProvider for Scripted {
        async fn chat(&self, _: &[Message], tools: &[ToolSpec]) -> crate::Result<Message> {
            self.offered
                .lock()
                .unwrap()
                .push(tools.iter().map(|t| t.function.name.clone()).collect());
            let reply = self
                .replies
                .lock()
                .unwrap()
                .pop()
                .unwrap_or_else(|| "no reply scripted".to_string());
            Ok(Message::assistant(&reply))
        }
        fn take_usage(&self) -> Option<TurnUsage> {
            self.usage.lock().unwrap().take()
        }
    }

    struct Routes {
        routes: Vec<(String, Arc<dyn ChatProvider>)>,
        default: String,
    }

    impl ChildProviders for Routes {
        fn routes(&self) -> Vec<RouteInfo> {
            self.routes
                .iter()
                .map(|(n, _)| RouteInfo {
                    name: n.clone(),
                    model: format!("{n}-model"),
                    endpoint: String::new(),
                })
                .collect()
        }
        fn default_route(&self) -> String {
            self.default.clone()
        }
        fn provider(
            &self,
            name: &str,
        ) -> std::result::Result<crate::tools_delegate::ChildRoute, String> {
            self.routes
                .iter()
                .find(|(n, _)| n == name)
                .map(|(_, p)| crate::tools_delegate::ChildRoute {
                    name: name.to_string(),
                    provider: Arc::clone(p),
                    context_budget_tokens: 8000,
                })
                .ok_or_else(|| format!("unknown route `{name}`"))
        }
    }

    /// The tool a lead would hold: three read tools and one write tool, so a flare's registry can
    /// be shown to be missing the one that matters.
    struct ReadFile;
    #[async_trait]
    impl Tool for ReadFile {
        fn name(&self) -> &str {
            "read_file"
        }
        fn description(&self) -> &str {
            "read"
        }
        fn parameters(&self) -> Value {
            json!({"type": "object"})
        }
        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
            Ok("contents".into())
        }
    }
    struct WriteFile;
    #[async_trait]
    impl Tool for WriteFile {
        fn name(&self) -> &str {
            "write_file"
        }
        fn description(&self) -> &str {
            "write"
        }
        fn parameters(&self) -> Value {
            json!({"type": "object"})
        }
        async fn call(&self, _: Value) -> std::result::Result<String, ToolError> {
            Ok("written".into())
        }
    }

    fn harness(
        dir: &std::path::Path,
        provider: Arc<Scripted>,
        cfg: FlaresConfig,
    ) -> (FlareTool, SessionStore) {
        let store = SessionStore::new(dir.join("sessions"));
        let mut registry = ToolRegistry::new(4096);
        registry.register(Arc::new(ReadFile), crate::config::Policy::Allow);
        registry.register(Arc::new(WriteFile), crate::config::Policy::Allow);
        let routes = Routes {
            routes: vec![("local".to_string(), provider as Arc<dyn ChatProvider>)],
            default: "local".to_string(),
        };
        let delegate = Arc::new(DelegateTool::new(
            Arc::new(routes),
            Arc::new(registry),
            store.clone(),
            DelegateSettings {
                max_output_bytes: 8000,
                max_malformed_calls: 3,
                tool_concurrency: 1,
                lock_wait: std::time::Duration::from_secs(5),
            },
        ));
        let slots = vec![RouteSlot {
            name: "local".to_string(),
            parallel: 1,
            group: None,
        }];
        (FlareTool::new(delegate, store.clone(), cfg, slots), store)
    }

    #[test]
    fn a_group_is_one_server_worth_of_slots_and_the_cap_is_their_sum() {
        let local = |name: &str, parallel: usize, group: Option<&str>| RouteSlot {
            name: name.to_string(),
            parallel,
            group: group.map(str::to_string),
        };
        // Two routes on one box are one slot, and the box takes its lowest member's bound.
        let plan = slots(
            &[local("a", 1, Some("gpu0")), local("b", 4, Some("gpu0"))],
            4,
        );
        assert_eq!(plan.per_group.get("gpu0"), Some(&1));
        assert_eq!(plan.total, 1, "two routes on one server are one slot");

        // Three local readers and one cloud thinker: two slots, not four.
        let plan = slots(
            &[
                local("read1", 1, Some("gpu0")),
                local("read2", 1, Some("gpu0")),
                local("read3", 1, Some("gpu0")),
                local("cloud", 4, None),
            ],
            4,
        );
        // The local group is one slot and the cloud route four: four in flight, and no more
        // than `max_concurrent` allows.
        assert_eq!(plan.total, 4, "one local slot plus the cloud route's four");
        assert_eq!(plan.per_group.len(), 2);

        // `max_concurrent` is a ceiling, never a floor: a config that allows four on a box with
        // one slot gets one.
        let plan = slots(&[local("a", 1, None)], 16);
        assert_eq!(plan.total, 1, "one slot is one slot");
    }

    #[tokio::test]
    async fn a_run_is_n_read_only_sessions_in_the_leads_order_with_one_merge() {
        let dir = tempfile::tempdir().unwrap();
        let provider = Scripted::new(&["alpha", "beta"]);
        let (tool, store) = harness(dir.path(), Arc::clone(&provider), FlaresConfig::default());
        let scope = crate::tools::RunScope::new("lead-session");
        let call = CallScope {
            approver: &DenyAll,
            run: &scope,
            registry: &ToolRegistry::new(4096),
            call_id: None,
        };
        let args = json!({"jobs": [
            {"prompt": "read the first crate"},
            {"prompt": "read the second crate"}
        ]});
        let text = tool.call_scoped(args, &call).await.unwrap();

        assert!(text.contains("2 of 2 finished"), "{text}");
        assert!(text.contains("--- flare 1 (local) ---"), "{text}");
        assert!(text.contains("alpha") && text.contains("beta"), "{text}");

        // Two sessions, both flares, positions 1 and 2, and the store knows the run.
        let runs = store.flare_runs(10).unwrap();
        assert_eq!(runs.len(), 1, "{runs:?}");
        let run = &runs[0];
        assert_eq!(run.jobs, 2);
        assert_eq!(run.state, "done");
        assert_eq!(run.parent.as_deref(), Some("lead-session"));
        assert_eq!(run.iterations, 2, "one call per flare");
        let (_, jobs) = store.flare_run(&run.id).unwrap().unwrap();
        assert_eq!(
            jobs.iter().map(|j| j.n).collect::<Vec<_>>(),
            vec![1, 2],
            "the ledger keeps the lead's order"
        );
        assert!(jobs.iter().all(|j| j.state == "done"));
        let sessions = store.flares_of(&run.id).unwrap();
        assert_eq!(sessions.len(), 2);
        assert_eq!(sessions[0].flare().unwrap().n, 1);

        // And the one claim that makes a fan-out safe: the write tool was not offered at all.
        let offered = provider.offered.lock().unwrap();
        assert!(
            offered
                .iter()
                .all(|tools| !tools.iter().any(|t| t == "write_file")),
            "a flare was offered write_file: {offered:?}"
        );
        assert!(offered
            .iter()
            .all(|tools| tools.iter().any(|t| t == "read_file")));
    }

    #[tokio::test]
    async fn a_run_whose_budget_runs_out_drops_the_rest_and_says_so() {
        let dir = tempfile::tempdir().unwrap();
        let provider = Scripted::new(&["only one"]);
        let cfg = FlaresConfig {
            // One iteration in the whole run: the first flare spends it, the second never starts.
            total_iterations: 1,
            ..Default::default()
        };
        let (tool, store) = harness(dir.path(), Arc::clone(&provider), cfg);
        let scope = crate::tools::RunScope::new("lead");
        let call = CallScope {
            approver: &DenyAll,
            run: &scope,
            registry: &ToolRegistry::new(4096),
            call_id: None,
        };
        let text = tool
            .call_scoped(
                json!({"jobs": [{"prompt": "one", "max_iterations": 1}, {"prompt": "two"}]}),
                &call,
            )
            .await
            .unwrap();
        assert!(text.contains("1 of 2 finished"), "{text}");
        assert!(text.contains("1 dropped"), "{text}");
        assert!(text.contains("budget"), "{text}");

        let run = &store.flare_runs(10).unwrap()[0];
        let (_, jobs) = store.flare_run(&run.id).unwrap().unwrap();
        assert_eq!(jobs[1].state, "dropped");
        assert!(
            jobs[1]
                .why
                .as_deref()
                .unwrap_or_default()
                .contains("budget"),
            "{:?}",
            jobs[1]
        );
        // A dropped flare has no session: there is nothing to open.
        assert!(store.flares_of(&run.id).unwrap().len() == 1);
    }

    struct DenyAll;
    #[async_trait]
    impl Approver for DenyAll {
        async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
            crate::approvals::Decision::Deny("no".into())
        }
    }
}