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
//! `tool_search`, `tool_describe`, `tool_call` — reaching a tool the model was not given.
//!
//! Every tool in the request costs its description in every turn's input, whether or not the
//! model calls it. Ten tools is nothing; an MCP server that registers forty is four thousand
//! tokens of promise on every turn, and the model's attention on the one it wants is diluted by
//! thirty-nine it does not. Deferral is the answer: a deferred tool stays registered, stays
//! callable, and simply is not described — until the model asks for it.
//!
//! Three verbs, in the order a model uses them:
//!
//! - [`ToolSearch`] — *what is there?* Keyword search over the withheld tools' names and
//!   descriptions. Never touches a tool.
//! - [`ToolDescribe`] — *what does it take?* The full argument schemas, so the call can be
//!   formed correctly.
//! - [`ToolCall`] — *do it.* Dispatches through [`ToolRegistry::dispatch_scoped`], the same
//!   funnel a direct call goes through: policy, `[tools] disabled`, plugin hooks, the approval
//!   prompt, and the output cap. A router that skipped any of that would be a way around the
//!   approvals it was meant to route to.
//!
//! `tool_call` defaults to `allow` for exactly that reason: it has no side effect of its own,
//! and the thing being approved is the tool on the other side of it. It refuses to call itself,
//! which is the one target that would nest without bound.

use crate::tools::{str_arg, CallScope, Tool, ToolError};
use async_trait::async_trait;
use serde_json::{json, Value};

pub(crate) const SEARCH: &str = "tool_search";
pub(crate) const DESCRIBE: &str = "tool_describe";
pub(crate) const CALL: &str = "tool_call";

/// How many matches one search returns by default, and at most.
const DEFAULT_LIMIT: usize = 8;
const MAX_LIMIT: usize = 20;

/// How long a search-result line may get before it is cut. A listing exists to be scanned; a
/// description that runs to three lines defeats that however well it reads on its own.
const HEADLINE_MAX: usize = 100;

/// First sentence of a description, single-spaced, cut at `HEADLINE_MAX`.
fn headline(description: &str) -> String {
    let line = description.split_whitespace().collect::<Vec<_>>().join(" ");
    let first = match line.find(". ") {
        Some(at) => &line[..=at],
        None => &line[..],
    };
    if first.chars().count() <= HEADLINE_MAX {
        return first.trim_end_matches('.').to_string();
    }
    let cut: String = first.chars().take(HEADLINE_MAX).collect();
    format!("{}…", cut.trim_end())
}

/// Tools matching `query`, best first.
///
/// Four tiers, because a model asks in its own words rather than the tool's: the name contains
/// the whole query; the name contains every word; the description contains every word; and — the
/// tier that earns its keep — some of the words, ranked by how many. "edit file" does not occur in
/// `patch`'s description, but "file" does, and returning `patch` with the ranking stated is far
/// more use than returning nothing because one word missed. Nothing at all matches only when no
/// word appears anywhere, and then the caller is told what there is.
///
/// Ties break on name order, which is stable and therefore reviewable.
fn ranked<'a, I>(candidates: I, query: &str) -> Vec<&'a crate::tools::ToolDescriptor>
where
    I: IntoIterator<Item = &'a crate::tools::ToolDescriptor>,
{
    let query = query.trim().to_lowercase();
    let words: Vec<&str> = query.split_whitespace().collect();
    let mut scored: Vec<(u8, usize, &crate::tools::ToolDescriptor)> = Vec::new();
    for d in candidates {
        let name = d.name.to_lowercase();
        let text = format!("{} {}", name, d.description.to_lowercase());
        if words.is_empty() {
            scored.push((3, 0, d));
            continue;
        }
        let in_name = words.iter().filter(|w| name.contains(**w)).count();
        let in_text = words.iter().filter(|w| text.contains(**w)).count();
        let tier = if name.contains(&query) {
            0
        } else if in_name == words.len() {
            1
        } else if in_text == words.len() {
            2
        } else if in_text > 0 || in_name > 0 {
            3
        } else {
            continue;
        };
        scored.push((tier, in_text.max(in_name), d));
    }
    // Most words matched first within a tier; the name is the tie-break so the order is fixed.
    scored.sort_by(|a, b| {
        a.0.cmp(&b.0)
            .then_with(|| b.1.cmp(&a.1))
            .then_with(|| a.2.name.cmp(&b.2.name))
    });
    scored.into_iter().map(|(_, _, d)| d).collect()
}

pub struct ToolSearch;

#[async_trait]
impl Tool for ToolSearch {
    fn name(&self) -> &str {
        SEARCH
    }

    fn description(&self) -> &str {
        "Find tools this session has but does not describe: keyword search over their names and \
         descriptions. Use it when the tool you want is not in your list — then `tool describe` \
         it and `tool call` it. A tool you can already see needs neither."
    }

    fn parameters(&self) -> Value {
        json!({"type":"object","properties":{
            "query":{"type":"string","description":"Words to look for in a tool's name or description. Empty lists everything that is deferred."},
            "limit":{"type":"integer","description":format!("How many to return at most. Default {DEFAULT_LIMIT}, maximum {MAX_LIMIT}.")}
        },"required":[]})
    }

    fn describe_call(&self, args: &Value) -> String {
        format!(
            "tool_search {:?}",
            args["query"].as_str().unwrap_or("(everything)")
        )
    }

    async fn call(&self, args: Value) -> Result<String, ToolError> {
        // A registry is not in scope for a plain `call`, so this is the scoped path's job.
        let _ = args;
        Err(ToolError::Failed(
            "tool_search needs the registry; it is only reachable inside a run".into(),
        ))
    }

    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
        let query = args["query"].as_str().unwrap_or("").to_string();
        let limit = args["limit"]
            .as_u64()
            .map(|n| (n as usize).clamp(1, MAX_LIMIT))
            .unwrap_or(DEFAULT_LIMIT);

        let registry = scope.registry;
        let described = registry.descriptors();
        let (hidden, offered): (Vec<_>, Vec<_>) = described.iter().partition(|d| d.deferred);

        if hidden.is_empty() {
            return Ok(format!(
                "Nothing is deferred: all {} tool(s) are already described in your list: {}. \
                 Call one directly.",
                offered.len(),
                offered
                    .iter()
                    .map(|d| d.name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }

        let found = ranked(hidden.iter().copied(), &query);
        if found.is_empty() {
            return Ok(format!(
                "No deferred tool matches {query:?}. There {} {}: {}. Try a word from a name.",
                if hidden.len() == 1 { "is" } else { "are" },
                hidden.len(),
                hidden
                    .iter()
                    .map(|d| d.name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }

        let mut out = format!(
            "{} of {} deferred tool(s){}:\n",
            found.len().min(limit),
            hidden.len(),
            if query.trim().is_empty() {
                String::new()
            } else {
                format!(" matching {:?}", query.trim())
            }
        );
        for d in found.iter().take(limit) {
            let mut notes = Vec::new();
            if d.policy == crate::config::Policy::Ask {
                notes.push("asks first");
            }
            if d.policy == crate::config::Policy::Deny {
                notes.push("denied by policy — it will not run");
            }
            out.push_str(&format!(
                "- {} — {}{}\n",
                d.name,
                headline(&d.description),
                if notes.is_empty() {
                    String::new()
                } else {
                    format!(" [{}]", notes.join("; "))
                }
            ));
        }
        if found.len() > limit {
            out.push_str(&format!(
                "… {} more. Narrow the query.\n",
                found.len() - limit
            ));
        }
        out.push_str(
            "\nNext: `tool_describe` the one you want for its arguments, then `tool_call` it.",
        );
        Ok(out)
    }
}

pub struct ToolDescribe;

#[async_trait]
impl Tool for ToolDescribe {
    fn name(&self) -> &str {
        DESCRIBE
    }

    fn description(&self) -> &str {
        "The full argument schema of one or more tools, by name — including tools that are \
         deferred or that you were not given. Use it before `tool_call`."
    }

    fn parameters(&self) -> Value {
        json!({"type":"object","properties":{
            "names":{"description":"A tool name, or a list of them.",
                "oneOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]}
        },"required":["names"]})
    }

    fn describe_call(&self, args: &Value) -> String {
        let names: Vec<String> = match &args["names"] {
            Value::String(s) => vec![s.clone()],
            Value::Array(items) => items
                .iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect(),
            _ => Vec::new(),
        };
        format!("tool_describe {}", names.join(", "))
    }

    async fn call(&self, _args: Value) -> Result<String, ToolError> {
        Err(ToolError::Failed(
            "tool_describe needs the registry; it is only reachable inside a run".into(),
        ))
    }

    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
        // Models send one name or a list depending on the day; both are the same request.
        let names: Vec<String> = match &args["names"] {
            Value::String(s) => vec![s.clone()],
            Value::Array(items) => items
                .iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect(),
            _ => {
                return Err(ToolError::InvalidArgs(
                    "`names` must be a tool name or a list of them".into(),
                ))
            }
        };
        if names.is_empty() {
            return Err(ToolError::InvalidArgs("`names` is empty".into()));
        }

        let registry = scope.registry;
        let all = registry.descriptors();
        let mut out = String::new();
        for name in &names {
            match all.iter().find(|d| &d.name == name) {
                None => {
                    let near = ranked(all.iter(), name)
                        .into_iter()
                        .take(3)
                        .map(|d| d.name.as_str())
                        .collect::<Vec<_>>()
                        .join(", ");
                    out.push_str(&format!(
                        "{}: no such tool.{}\n",
                        name,
                        if near.is_empty() {
                            String::new()
                        } else {
                            format!(" Closest registered: {near}.")
                        }
                    ));
                }
                Some(d) if d.disabled => {
                    out.push_str(&format!(
                        "{}: named in `[tools] disabled`. It will not run, so there is nothing to \
                         describe.\n",
                        name
                    ));
                }
                Some(d) => {
                    out.push_str(&format!(
                        "{} — {}\n{}\n\n",
                        d.name,
                        d.description,
                        serde_json::to_string_pretty(&d.parameters)
                            .unwrap_or_else(|_| d.parameters.to_string())
                    ));
                }
            }
        }
        Ok(out.trim_end().to_string())
    }
}

pub struct ToolCall;

#[async_trait]
impl Tool for ToolCall {
    fn name(&self) -> &str {
        CALL
    }

    fn description(&self) -> &str {
        "Call a tool by name, including one that is not in your list. Pass `arguments` as the \
         object that tool's schema describes. The call goes through the same policy, approval \
         and hook checks as a direct one, so a tool that asks first still asks first."
    }

    fn parameters(&self) -> Value {
        json!({"type":"object","properties":{
            "name":{"type":"string","description":"The tool to call."},
            "arguments":{"description":"That tool's arguments, as an object (a JSON string is accepted too)."}
        },"required":["name"]})
    }

    fn describe_call(&self, args: &Value) -> String {
        format!(
            "tool_call {} {}",
            args["name"].as_str().unwrap_or("?"),
            args["arguments"]
        )
    }

    async fn call(&self, _args: Value) -> Result<String, ToolError> {
        Err(ToolError::Failed(
            "tool_call needs the registry; it is only reachable inside a run".into(),
        ))
    }

    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
        let name = str_arg(&args, "name")?.to_string();
        if name == CALL {
            return Err(ToolError::Failed(
                "`tool_call` cannot call itself. Name the tool you actually want.".into(),
            ));
        }
        // A model that has just read a schema sometimes sends the arguments as a JSON string.
        // Accepting it is cheaper than a round trip that only re-types them.
        let raw = match &args["arguments"] {
            Value::Null => String::new(),
            Value::String(s) => s.clone(),
            other => other.to_string(),
        };
        if !raw.trim().is_empty() {
            serde_json::from_str::<Value>(&raw).map_err(|e| {
                ToolError::InvalidArgs(format!("`arguments` is not a JSON object: {e}"))
            })?;
        }

        // The funnel. Everything below this line is a direct call: same policy, same disabled
        // list, same hooks, same approval prompt (on the inner tool's own describe_call), same
        // output cap, same malformed accounting. The outer call's id travels with it (`#369`): the
        // answer that unblocks this call is recorded against `tool_call`, so the inner prompt has to
        // name the same row or a resumed run can never match the decision it was given.
        let outcome = scope
            .registry
            .dispatch_scoped(&name, &raw, scope.approver, scope.call_id, scope.run)
            .await;
        if outcome.malformed {
            return Err(ToolError::InvalidArgs(outcome.output));
        }
        // `#369`: the gate has not answered. Collapsing this into a failure told the model a call
        // was waiting while the turn carried on and no row reached `eclipse approve`; the deferral
        // goes up instead, and the runtime records it and stops.
        if outcome.deferred {
            return Err(ToolError::Deferred(outcome.output));
        }
        if outcome.is_error {
            return Err(ToolError::Failed(outcome.output));
        }
        Ok(outcome.output)
    }
}

/// A `[tools] deferred` pattern: exact, or a prefix when it ends in `*`.
///
/// `"*"` is the prefix `""`, which is every name — so it needs no special case, and neither does
/// `"mcp_github_*"`.
pub(crate) fn matches_pattern(pattern: &str, name: &str) -> bool {
    match pattern.strip_suffix('*') {
        Some(prefix) => name.starts_with(prefix),
        None => pattern == name,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Policy;
    use crate::tools::{AllowAll, DenyAll, ToolRegistry, ToolSpec};
    use std::sync::Arc;

    /// A tool that says back what it was given, so a routed call is visibly the same call.
    struct Echo {
        name: &'static str,
        text: &'static str,
    }

    #[async_trait]
    impl Tool for Echo {
        fn name(&self) -> &str {
            self.name
        }
        fn description(&self) -> &str {
            self.text
        }
        fn parameters(&self) -> Value {
            json!({"type":"object","properties":{"msg":{"type":"string"}},"required":["msg"]})
        }
        async fn call(&self, args: Value) -> Result<String, ToolError> {
            Ok(format!("echo: {}", args["msg"].as_str().unwrap_or("")))
        }
    }

    fn registry(policy: Policy, deferred: &[&str]) -> ToolRegistry {
        let mut r = ToolRegistry::new(4096);
        r.register(
            Arc::new(Echo {
                name: "notes_add",
                text: "Append a line to the notes file. One line only.",
            }),
            policy,
        );
        r.register(
            Arc::new(Echo {
                name: "web_thing",
                text: "Fetch a page over HTTP and return its text. Follows redirects.",
            }),
            Policy::Allow,
        );
        let patterns: Vec<String> = deferred.iter().map(|s| s.to_string()).collect();
        let unknown = r.defer(&patterns);
        assert!(unknown.is_empty(), "{unknown:?}");
        r
    }

    async fn run(
        r: &ToolRegistry,
        name: &str,
        args: Value,
        approver: &dyn crate::tools::Approver,
    ) -> crate::tools::ToolOutcome {
        r.dispatch(name, &args.to_string(), approver).await
    }

    /// `#369`: with `--approvals-out`, a gated call made *through* `tool_call` came back as a plain
    /// failure — `Deferred` was collapsed into `Failed` — so no row reached `eclipse approve`, the
    /// turn carried on, and the model was told something was waiting when nothing was. A nested
    /// call now pauses the turn exactly like a top-level one, and the row it leaves names the outer
    /// call, which is the id `decision_for` looks up on resume.
    #[tokio::test]
    async fn a_deferral_inside_tool_call_comes_back_as_waiting() {
        struct Asked(std::sync::Mutex<Vec<String>>);
        #[async_trait]
        impl crate::tools::Approver for Asked {
            async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision {
                self.0.lock().unwrap().push(call.call_id.clone());
                crate::approvals::Decision::Defer
            }
        }

        let r = registry(Policy::Ask, &["notes_add"]);
        let asked = Asked(std::sync::Mutex::new(Vec::new()));
        let outcome = r
            .dispatch_call(
                "tool_call",
                &json!({"name": "notes_add", "arguments": {"msg": "hi"}}).to_string(),
                &asked,
                Some("call-7"),
            )
            .await;
        assert!(
            !outcome.malformed,
            "a deferral is not a broken call: {}",
            outcome.output
        );
        assert!(
            outcome.deferred,
            "the deferral survives the funnel: {}",
            outcome.output
        );
        assert!(
            outcome.output.contains("not approved yet"),
            "and says what it is: {}",
            outcome.output
        );
        assert!(
            !outcome.output.contains("echo:"),
            "the tool did not run: {}",
            outcome.output
        );
        assert_eq!(
            asked.0.lock().unwrap().as_slice(),
            ["call-7".to_string()],
            "the prompt names the call the answer will be recorded against"
        );
    }

    fn names(specs: &[ToolSpec]) -> Vec<String> {
        specs.iter().map(|s| s.function.name.clone()).collect()
    }

    #[test]
    fn a_pattern_is_exact_unless_it_ends_in_a_star() {
        assert!(matches_pattern("notes_add", "notes_add"));
        assert!(!matches_pattern("notes_add", "notes"));
        assert!(matches_pattern("notes_*", "notes_add"));
        assert!(!matches_pattern("notes_*", "web_thing"));
        // `*` is the prefix `""`: every name, with no special case for the operator.
        assert!(matches_pattern("*", "anything"));
    }

    #[test]
    fn a_deferred_tool_is_not_offered_but_is_still_registered() {
        let r = registry(Policy::Allow, &["notes_add"]);
        assert!(!names(&r.specs()).contains(&"notes_add".to_string()));
        assert!(r.names().contains(&"notes_add".to_string()));
        let d = r
            .descriptors()
            .into_iter()
            .find(|d| d.name == "notes_add")
            .unwrap();
        assert!(!d.advertised);
        assert!(d.deferred);
        assert!(!d.disabled);
        assert_eq!(d.policy, Policy::Allow);
    }

    #[test]
    fn deferring_something_registers_the_three_tools_that_reach_it() {
        let r = registry(Policy::Allow, &["notes_add"]);
        let offered = names(&r.specs());
        for name in [SEARCH, DESCRIBE, CALL] {
            assert!(
                offered.contains(&name.to_string()),
                "{name} not in {offered:?}"
            );
        }
        // And a deferred tool cannot be reached by deferring the tools that reach it.
        let d = r
            .descriptors()
            .into_iter()
            .find(|d| d.name == CALL)
            .unwrap();
        assert!(!d.deferred);
    }

    #[test]
    fn deferring_nothing_registers_no_extra_tools_and_a_typo_is_reported() {
        let mut r = ToolRegistry::new(4096);
        r.register(
            Arc::new(Echo {
                name: "a",
                text: "a",
            }),
            Policy::Allow,
        );
        assert!(r.defer(&[]).is_empty());
        assert_eq!(
            r.names(),
            ["a"],
            "three dead tools would cost tokens for nothing"
        );
        let unknown = r.defer(&["nope".to_string()]);
        assert_eq!(unknown, ["nope"]);
        assert_eq!(
            r.names(),
            ["a"],
            "a pattern that matched nothing defers nothing"
        );
    }

    #[tokio::test]
    async fn search_finds_a_deferred_tool_by_a_word_from_its_name_or_description() {
        let r = registry(Policy::Allow, &["notes_add", "web_thing"]);
        let by_name = run(&r, SEARCH, json!({"query": "notes"}), &AllowAll).await;
        assert!(by_name.output.contains("notes_add"), "{}", by_name.output);
        assert!(!by_name.output.contains("web_thing"), "{}", by_name.output);
        let by_text = run(&r, SEARCH, json!({"query": "HTTP"}), &AllowAll).await;
        assert!(by_text.output.contains("web_thing"), "{}", by_text.output);
        // One line per tool: the first sentence, not the whole description.
        assert!(
            by_text.output.contains("Fetch a page over HTTP"),
            "{}",
            by_text.output
        );
        assert!(
            !by_text.output.contains("Follows redirects"),
            "{}",
            by_text.output
        );
    }

    #[tokio::test]
    async fn a_query_in_the_model_s_own_words_still_finds_the_tool_by_the_words_that_do_match() {
        // The case that made this tier necessary: asked for "edit file", a description search
        // for every word returns nothing, and a model that gets nothing concludes there is
        // nothing. One word hits "text file" in `patch`, so `patch` comes back first.
        let r = registry(Policy::Allow, &["notes_add", "web_thing"]);
        let text = run(&r, SEARCH, json!({"query": "edit file"}), &AllowAll)
            .await
            .output;
        assert!(text.contains("notes_add"), "{text}");
        // Ranked, not filtered to the exact words: the count says one of two, and the other is
        // reachable with a narrower word rather than being invisible.
        assert!(text.contains("1 of 2 deferred"), "{text}");
        assert!(!text.contains("No deferred tool matches"), "{text}");
    }

    #[tokio::test]
    async fn an_empty_search_lists_everything_deferred_and_says_what_to_do_next() {
        let r = registry(Policy::Allow, &["*"]);
        let out = run(&r, SEARCH, json!({}), &AllowAll).await.output;
        assert!(
            out.contains("notes_add") && out.contains("web_thing"),
            "{out}"
        );
        assert!(out.contains("tool_describe"), "{out}");
        assert!(out.contains("2 of 2 deferred"), "{out}");
    }

    #[tokio::test]
    async fn a_search_that_matches_nothing_names_what_there_is_instead_of_returning_empty() {
        let r = registry(Policy::Allow, &["notes_add", "web_thing"]);
        let out = run(&r, SEARCH, json!({"query": "kalman"}), &AllowAll)
            .await
            .output;
        assert!(out.contains("No deferred tool matches"), "{out}");
        assert!(
            out.contains("notes_add") && out.contains("web_thing"),
            "{out}"
        );
    }

    #[tokio::test]
    async fn a_search_names_the_tools_already_in_the_list_rather_than_looking_more() {
        let mut r = ToolRegistry::new(4096);
        r.register(
            Arc::new(Echo {
                name: "hidden",
                text: "withheld",
            }),
            Policy::Allow,
        );
        r.register(
            Arc::new(Echo {
                name: "shown",
                text: "offered",
            }),
            Policy::Allow,
        );
        r.defer(&["hidden".to_string()]);
        let out = run(&r, SEARCH, json!({"query": "zzz"}), &AllowAll)
            .await
            .output;
        assert!(out.contains("No deferred tool matches"), "{out}");
        assert!(out.contains("hidden"), "{out}");
    }

    #[test]
    fn with_nothing_deferred_the_search_tool_is_not_registered_at_all() {
        // The negative case that keeps three useless tools out of the request: `defer` is what
        // registers them, so a registry nobody defers on has none.
        let mut r = ToolRegistry::new(4096);
        r.register(
            Arc::new(Echo {
                name: "solo",
                text: "the only tool",
            }),
            Policy::Allow,
        );
        assert_eq!(r.names(), ["solo"]);
        assert!(r.descriptors()[0].advertised);
    }

    #[tokio::test]
    async fn describe_gives_the_arguments_schema_for_a_name_or_a_list() {
        let r = registry(Policy::Allow, &["notes_add", "web_thing"]);
        let one = run(&r, DESCRIBE, json!({"names": "notes_add"}), &AllowAll).await;
        assert!(one.output.contains("\"msg\""), "{}", one.output);
        assert!(one.output.contains("Append a line"), "{}", one.output);
        let two = run(
            &r,
            DESCRIBE,
            json!({"names": ["notes_add", "web_thing"]}),
            &AllowAll,
        )
        .await;
        assert!(
            two.output.contains("notes_add") && two.output.contains("web_thing"),
            "{}",
            two.output
        );
    }

    #[tokio::test]
    async fn describe_a_name_that_does_not_exist_suggests_the_closest_instead_of_nothing() {
        let r = registry(Policy::Allow, &["notes_add"]);
        let out = run(&r, DESCRIBE, json!({"names": "notes"}), &AllowAll)
            .await
            .output;
        assert!(out.contains("no such tool"), "{out}");
        assert!(out.contains("notes_add"), "{out}");
    }

    #[tokio::test]
    async fn call_runs_a_deferred_tool_through_the_same_funnel() {
        let r = registry(Policy::Allow, &["notes_add"]);
        let out = run(
            &r,
            CALL,
            json!({"name": "notes_add", "arguments": {"msg": "hello"}}),
            &AllowAll,
        )
        .await;
        assert_eq!(out.output, "echo: hello");
        assert!(!out.is_error);
    }

    #[tokio::test]
    async fn arguments_may_arrive_as_a_json_string() {
        let r = registry(Policy::Allow, &["notes_add"]);
        let out = run(
            &r,
            CALL,
            json!({"name": "notes_add", "arguments": "{\"msg\": \"as text\"}"}),
            &AllowAll,
        )
        .await;
        assert_eq!(out.output, "echo: as text", "{}", out.output);
    }

    #[tokio::test]
    async fn a_tool_that_asks_still_asks_when_it_is_reached_through_tool_call() {
        let r = registry(Policy::Ask, &["notes_add"]);
        let denied = run(
            &r,
            CALL,
            json!({"name": "notes_add", "arguments": {"msg": "x"}}),
            &DenyAll,
        )
        .await;
        assert!(
            denied.is_error,
            "a router must not be a way around the prompt"
        );
        assert!(denied.output.contains("declined"), "{}", denied.output);
        let allowed = run(
            &r,
            CALL,
            json!({"name": "notes_add", "arguments": {"msg": "x"}}),
            &AllowAll,
        )
        .await;
        assert_eq!(allowed.output, "echo: x");
    }

    #[tokio::test]
    async fn tool_call_refuses_to_call_itself() {
        let r = registry(Policy::Allow, &["notes_add"]);
        let out = run(&r, CALL, json!({"name": CALL}), &AllowAll).await;
        assert!(out.is_error);
        assert!(out.output.contains("cannot call itself"), "{}", out.output);
    }

    #[tokio::test]
    async fn tool_call_to_a_disabled_tool_is_refused_by_the_same_rule_as_a_direct_call() {
        let mut r = registry(Policy::Allow, &["notes_add"]);
        // Disabled after deferral, which is the order the runtime applies them in reverse:
        // `disabled` first, then `deferred`. Either way the funnel is the same.
        assert!(r.disable(&["notes_add".to_string()]).is_empty());
        let out = run(
            &r,
            CALL,
            json!({"name": "notes_add", "arguments": {"msg": "x"}}),
            &AllowAll,
        )
        .await;
        assert!(out.is_error);
        assert!(
            out.output.contains("disabled in the config"),
            "{}",
            out.output
        );
    }

    #[tokio::test]
    async fn tool_call_to_an_unknown_tool_says_unknown_rather_than_failing_silently() {
        let r = registry(Policy::Allow, &["notes_add"]);
        let out = run(&r, CALL, json!({"name": "nothing_here"}), &AllowAll).await;
        assert!(out.is_error);
        assert!(out.output.contains("unknown tool"), "{}", out.output);
    }
}