agent-base 0.5.0

A lightweight Agent Runtime Kernel for building AI agents in Rust
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
use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use serde_json::{Value, json};
use tokio::sync::mpsc;

use crate::engine::SessionStore;
use crate::types::{AgentError, AgentResult, SessionId, UserEvent};

pub mod auto_continue;
pub mod policy;
pub mod update_plan;

pub use auto_continue::AutoContinueTool;
pub use update_plan::UpdatePlanTool;

pub use policy::{DenyAllToolPolicy, ToolDecision, ToolPolicy};

// Re-export pure types from agent-types
pub use agent_types::{
    ActivationContext, Content, ToolExposure, ToolMetadata, content_details, content_text,
};

#[derive(Clone)]
pub struct ToolContext {
    pub session_id: SessionId,
    /// Channel for sending user-space events (progress, sub-agent, structured).
    /// Tools should use `emit_user_event()` or `emit_progress()`.
    pub user_event_tx: mpsc::UnboundedSender<UserEvent>,
    pub llm_client: Option<Arc<dyn llm_trait::LlmProvider>>,
    pub session_store: Option<Arc<dyn SessionStore>>,
    /// Language preference for tool output.
    /// Defaults to `Language::En` if not set.
    pub language: crate::types::Language,
    /// Cancellation token for checking if the operation should be cancelled.
    pub cancel_token: tokio_util::sync::CancellationToken,
    /// Output budget for this call, in characters (set from the engine's
    /// `max_tool_output_chars`). Tools that can return large results (e.g.
    /// `read_file`) should self-truncate to this bound and mark the cut, so
    /// the engine's hard reject (ยง6.5) never fires for a paginated read.
    pub max_output_chars: Option<usize>,
    /// Internal runtime event bus (framework tools emit `RuntimeEvent`s here).
    /// `pub(crate)` โ€” engine-internal; user tools should use `emit_user_event()`.
    pub(crate) event_bus: crate::engine::EventBus,
}

impl ToolContext {
    /// Send a user-space event (progress, sub-agent forwarding, structured data).
    pub fn emit_user_event(&self, event: UserEvent) {
        let _ = self.user_event_tx.send(event);
    }

    /// Convenience: send a progress event with text.
    pub fn emit_progress(&self, text: impl Into<String>) {
        self.emit_user_event(UserEvent::Progress { text: text.into() });
    }

    /// Convenience: emit a partial result during long-running tool execution.
    /// `is_partial: true` means more output is coming; `false` means final.
    pub fn emit_partial_result(
        &self,
        tool_call_id: &str,
        content: impl Into<String>,
        is_partial: bool,
    ) {
        self.emit_user_event(UserEvent::ToolPartialResult {
            tool_call_id: tool_call_id.to_string(),
            content: content.into(),
            is_partial,
        });
    }

    /// Test-only constructor: a `ToolContext` with a disconnected event
    /// channel and no LLM/session backends. Lets downstream tests drop their
    /// bespoke `dummy_ctx()` helpers.
    pub fn for_test() -> Self {
        let (tx, _rx) = mpsc::unbounded_channel();
        ToolContext {
            session_id: SessionId::new(0),
            user_event_tx: tx,
            llm_client: None,
            session_store: None,
            language: crate::types::Language::En,
            cancel_token: tokio_util::sync::CancellationToken::new(),
            max_output_chars: None,
            event_bus: crate::engine::EventBus::new(1),
        }
    }
}

#[async_trait]
pub trait Tool: Send + Sync {
    fn name(&self) -> &'static str;
    /// Human-readable description of what this tool does and when to use it.
    fn description(&self) -> &'static str;
    /// JSON Schema for the tool's input arguments (MCP `inputSchema` shape,
    /// without the provider envelope).
    fn schema(&self) -> Value;
    async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>>;

    /// Timeout for this tool in milliseconds.
    ///
    /// Returns `Some(ms)` to enforce a timeout, or `None` to use the
    /// framework's default timeout from `ToolConfig.default_tool_timeout_ms`.
    /// Tools that need more or less time should override this method.
    fn timeout_ms(&self) -> Option<u64> {
        None // Use framework default
    }

    /// Machine-readable metadata for tool introspection.
    ///
    /// The default implementation derives `name` and `description` from
    /// [`Tool::name`] and [`Tool::description`], sets `origin` to `"custom"`,
    /// and leaves `requirements` empty. Tool authors are encouraged to
    /// override this to provide an accurate `origin` and `version`.
    fn metadata(&self) -> ToolMetadata {
        ToolMetadata {
            name: self.name().to_string(),
            description: self.description().to_string(),
            origin: "custom".to_string(),
            version: "unknown".to_string(),
            requirements: vec![],
        }
    }

    /// Visibility level for this tool. Default: `Direct` (always visible).
    ///
    /// Override to return `Deferred` (conditionally visible) or `Hidden`
    /// (never visible to the model). `Deferred` tools are only included
    /// when [`Tool::should_activate`] returns `true`.
    fn exposure(&self) -> ToolExposure {
        ToolExposure::Direct
    }

    /// Activation condition for `Deferred` tools.
    ///
    /// Called once per turn for each `Deferred` tool. Return `true` to
    /// include this tool in the model's tool list this turn. Ignored for
    /// `Direct` and `Hidden` tools.
    fn should_activate(&self, _ctx: &ActivationContext) -> bool {
        true
    }
}

#[async_trait]
pub trait TypedTool: Send + Sync {
    type Args: serde::de::DeserializeOwned + schemars::JsonSchema;
    type Output: serde::Serialize;

    fn name(&self) -> &'static str;
    fn description(&self) -> &'static str;
    async fn call_typed(&self, args: Self::Args, ctx: &ToolContext) -> AgentResult<Self::Output>;

    fn format_output(&self, output: Self::Output) -> Content {
        // A `String` output is emitted verbatim; any other serializable type is
        // rendered as JSON. This avoids `serde_json::to_string` wrapping a plain
        // string in literal double quotes (`hello` โ†’ `"hello"`), which would leak
        // quotes into the LLM-visible tool result.
        match serde_json::to_value(&output) {
            Ok(serde_json::Value::String(s)) => Content::text(s),
            Ok(other) => Content::text(other.to_string()),
            Err(_) => Content::text(String::new()),
        }
    }

    /// Machine-readable origin of this tool (crate name, `"agent-base"`, or `"custom"`).
    fn origin(&self) -> &'static str {
        "custom"
    }

    /// Crate/package version, or `"unknown"` when built outside a crate.
    fn version(&self) -> &'static str {
        "unknown"
    }

    /// Visibility level for this tool. Default: `Direct` (always visible).
    fn exposure(&self) -> ToolExposure {
        ToolExposure::Direct
    }

    /// Activation condition for `Deferred` tools. Ignored for `Direct`/`Hidden`.
    fn should_activate(&self, _ctx: &ActivationContext) -> bool {
        true
    }
}

#[async_trait]
impl<T: TypedTool + Send + Sync + 'static> Tool for T {
    fn name(&self) -> &'static str {
        TypedTool::name(self)
    }

    fn description(&self) -> &'static str {
        TypedTool::description(self)
    }

    fn schema(&self) -> Value {
        // Generate a provider-safe JSON Schema: Draft 7 (not 2020-12), with
        // nested subschemas inlined (no `$ref`/`$defs`/`/definitions`) and no
        // root `$schema`/meta-schema key. OpenAI-compatible function-calling
        // rejects `$ref` and 2020-12's `$defs`, so the default 2020-12 output
        // would break any `Args` containing a nested enum or struct.
        let settings = schemars::generate::SchemaSettings::draft07().with(|s| {
            s.inline_subschemas = true;
            s.meta_schema = None;
        });
        let generator = schemars::SchemaGenerator::new(settings);
        let schema = generator.into_root_schema_for::<T::Args>();
        serde_json::to_value(schema).unwrap_or(Value::Null)
    }

    fn metadata(&self) -> ToolMetadata {
        ToolMetadata {
            name: self.name().to_string(),
            description: self.description().to_string(),
            origin: self.origin().to_string(),
            version: self.version().to_string(),
            requirements: vec![],
        }
    }

    fn exposure(&self) -> ToolExposure {
        TypedTool::exposure(self)
    }

    fn should_activate(&self, ctx: &ActivationContext) -> bool {
        TypedTool::should_activate(self, ctx)
    }

    async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>> {
        let typed_args: T::Args =
            serde_json::from_value(args.clone()).map_err(|_| AgentError::ToolArgsInvalid {
                name: self.name().to_string(),
                raw: args.to_string(),
            })?;
        let output = self.call_typed(typed_args, ctx).await?;
        Ok(vec![self.format_output(output)])
    }
}

/// Render a single tool's definition into the OpenAI function-calling
/// envelope. Tools only provide `name`/`description`/`schema`; the envelope is
/// assembled here at the LLM boundary (Anthropic gets its own renderer, and
/// tool authors stay protocol-agnostic).
pub fn render_tool_definition(tool: &dyn Tool) -> Value {
    json!({
        "type": "function",
        "function": {
            "name": tool.name(),
            "description": tool.description(),
            "parameters": tool.schema(),
        }
    })
}

pub(crate) type ToolRef = Arc<dyn Tool>;

#[derive(Clone, Default)]
pub struct ToolRegistry {
    tools: HashMap<String, ToolRef>,
}

impl ToolRegistry {
    pub fn register(&mut self, tool: impl Tool + 'static) {
        self.tools.insert(tool.name().to_string(), Arc::new(tool));
    }

    pub fn register_arc(&mut self, tool: Arc<dyn Tool>) {
        self.tools.insert(tool.name().to_string(), tool);
    }

    /// Remove a tool from the registry by name.
    pub fn remove(&mut self, name: &str) {
        self.tools.remove(name);
    }

    pub fn get(&self, name: &str) -> Option<ToolRef> {
        self.tools.get(name).cloned()
    }

    pub fn definitions(&self) -> Vec<Value> {
        let mut tools: Vec<_> = self.tools.values().collect();
        tools.sort_by_key(|t| t.name());
        tools
            .into_iter()
            .map(|t| render_tool_definition(t.as_ref()))
            .collect()
    }

    /// Return tool definitions filtered by [`ToolExposure`].
    ///
    /// - `Direct` tools are always included.
    /// - `Deferred` tools are included only when `should_activate(ctx)` returns `true`.
    /// - `Hidden` tools are never included.
    pub fn definitions_filtered(&self, ctx: &ActivationContext) -> Vec<Value> {
        let mut tools: Vec<_> = self.tools.values().collect();
        tools.sort_by_key(|t| t.name());

        // Single sequential pass: collect Direct names first, then evaluate
        // Deferred tools in sorted order. Each Deferred tool sees the names of
        // all Direct + previously-activated Deferred tools in ctx.current_tools.
        // Evaluation order matters: a later Deferred tool can see an earlier one,
        // but not vice versa.
        let direct_names: Vec<String> = tools
            .iter()
            .filter(|t| t.exposure() == ToolExposure::Direct)
            .map(|t| t.name().to_string())
            .collect();

        let mut activated_names = direct_names.clone();
        for t in &tools {
            if t.exposure() == ToolExposure::Deferred {
                let mut ctx_with_tools = ctx.clone();
                ctx_with_tools.current_tools = activated_names.clone();
                if t.should_activate(&ctx_with_tools) {
                    activated_names.push(t.name().to_string());
                }
            }
        }

        tools
            .into_iter()
            .filter(|t| match t.exposure() {
                ToolExposure::Direct => true,
                ToolExposure::Deferred => activated_names.contains(&t.name().to_string()),
                ToolExposure::Hidden => false,
            })
            .map(|t| render_tool_definition(t.as_ref()))
            .collect()
    }

    pub fn len(&self) -> usize {
        self.tools.len()
    }

    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }

    /// Collect metadata for every registered tool, sorted by name.
    ///
    /// This is the preferred introspection API for consumers โ€” it returns a
    /// stable `ToolMetadata` struct per tool instead of having callers parse
    /// the LLM-facing JSON definitions.
    pub fn metadatas(&self) -> Vec<ToolMetadata> {
        let mut list: Vec<_> = self.tools.values().map(|tool| tool.metadata()).collect();
        list.sort_by(|a, b| a.name.cmp(&b.name));
        list
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn content_text_ctor_and_into_vec() {
        let c = Content::text("hello");
        let v: Vec<Content> = c.clone().into();
        assert_eq!(v.len(), 1);
        assert!(matches!(v[0], Content::Text { .. }));
        assert!(matches!(&c, Content::Text { text } if text == "hello"));
    }

    #[test]
    fn content_serializes_with_type_tag() {
        let c = Content::text("hi");
        let j = serde_json::to_value(&c).unwrap();
        assert_eq!(j["type"], "text");
        assert_eq!(j["text"], "hi");
    }

    #[test]
    fn tool_context_for_test_constructs() {
        let ctx = ToolContext::for_test();
        assert!(ctx.llm_client.is_none());
        assert!(ctx.session_store.is_none());
        assert!(!ctx.cancel_token.is_cancelled());
        ctx.emit_progress("hello");
    }

    #[test]
    fn typed_tool_schema_is_derived_from_args() {
        #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
        struct GreetArgs {
            name: String,
            #[serde(default)]
            times: u32,
        }

        let schema = schemars::schema_for!(GreetArgs);
        let j = serde_json::to_value(&schema).unwrap();
        // The derived schema exposes the struct's fields as object properties.
        assert!(j["properties"]["name"].is_object());
        assert!(j["properties"]["times"].is_object());
    }

    #[test]
    fn typed_tool_schema_is_provider_safe_for_nested_enum() {
        #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
        enum Status {
            Active,
            Paused,
        }

        #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
        struct Args {
            name: String,
            status: Status,
        }

        #[derive(Default)]
        struct NestedTool;
        #[async_trait]
        impl TypedTool for NestedTool {
            type Args = Args;
            type Output = String;
            fn name(&self) -> &'static str {
                "nested"
            }
            fn description(&self) -> &'static str {
                ""
            }
            async fn call_typed(
                &self,
                _args: Args,
                _ctx: &ToolContext,
            ) -> crate::types::AgentResult<String> {
                Ok(String::new())
            }
        }

        let schema = Tool::schema(&NestedTool);
        let raw = schema.to_string();
        // OpenAI-compatible function-calling rejects $ref / $defs; the nested
        // enum must be inlined rather than referenced.
        assert!(!raw.contains("$ref"), "schema contains $ref: {raw}");
        assert!(!raw.contains("$defs"), "schema contains $defs: {raw}");
        assert!(
            !raw.contains("definitions"),
            "schema has definitions: {raw}"
        );
        assert!(schema.get("$schema").is_none(), "schema has $schema key");

        // The enum variants are inlined directly under properties.status.
        let variants: Vec<&str> = schema["properties"]["status"]["enum"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(variants.contains(&"Active"), "missing Active: {variants:?}");
        assert!(variants.contains(&"Paused"), "missing Paused: {variants:?}");
    }

    #[test]
    fn definitions_are_sorted_by_name() {
        struct NamedTool(&'static str);
        #[async_trait::async_trait]
        impl Tool for NamedTool {
            fn name(&self) -> &'static str {
                self.0
            }
            fn description(&self) -> &'static str {
                ""
            }
            fn schema(&self) -> serde_json::Value {
                serde_json::Value::Null
            }
            async fn call(
                &self,
                _args: &serde_json::Value,
                _ctx: &ToolContext,
            ) -> crate::types::AgentResult<Vec<Content>> {
                Ok(vec![])
            }
        }

        let mut registry = ToolRegistry::default();
        registry.register(NamedTool("zeta"));
        registry.register(NamedTool("alpha"));
        registry.register(NamedTool("mike"));

        let defs = registry.definitions();
        let names: Vec<&str> = defs
            .iter()
            .map(|d| d["function"]["name"].as_str().unwrap())
            .collect();
        assert_eq!(names, vec!["alpha", "mike", "zeta"]);
    }

    // โ”€โ”€ B4: content image / partial result / typed-tool blanket / registry โ”€โ”€

    #[test]
    fn content_image_and_content_text_skips_images() {
        let img = Content::image("base64data", "image/png");
        assert!(
            matches!(&img, Content::Image { data, mime_type } if data == "base64data" && mime_type == "image/png")
        );

        let text = content_text(&[
            Content::text("a"),
            Content::image("b", "image/png"),
            Content::text("c"),
        ]);
        assert_eq!(text, "a\nc");
    }

    #[test]
    fn emit_partial_result_sends_event() {
        let (tx, mut rx) = mpsc::unbounded_channel();
        let ctx = ToolContext {
            session_id: SessionId::new(0),
            user_event_tx: tx,
            llm_client: None,
            session_store: None,
            language: crate::types::Language::En,
            cancel_token: tokio_util::sync::CancellationToken::new(),
            max_output_chars: None,
            event_bus: crate::engine::EventBus::new(1),
        };
        ctx.emit_partial_result("tc1", "partial", true);
        match rx.try_recv().unwrap() {
            UserEvent::ToolPartialResult {
                tool_call_id,
                content,
                is_partial,
            } => {
                assert_eq!(tool_call_id, "tc1");
                assert_eq!(content, "partial");
                assert!(is_partial);
            }
            other => panic!("unexpected event: {other:?}"),
        }
    }

    // A concrete TypedTool exercising the blanket `impl Tool for T`.
    #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
    struct GreetArgs {
        name: String,
    }

    struct GreetTool;
    #[async_trait]
    impl TypedTool for GreetTool {
        type Args = GreetArgs;
        type Output = String;
        fn name(&self) -> &'static str {
            "greet"
        }
        fn description(&self) -> &'static str {
            "greets a name"
        }
        fn origin(&self) -> &'static str {
            "test-crate"
        }
        fn version(&self) -> &'static str {
            "1.0.0"
        }
        async fn call_typed(&self, args: GreetArgs, _ctx: &ToolContext) -> AgentResult<String> {
            Ok(format!("Hello, {}!", args.name))
        }
    }

    #[test]
    fn typed_tool_blanket_delegates_name_description() {
        let t = GreetTool;
        assert_eq!(Tool::name(&t), "greet");
        assert_eq!(Tool::description(&t), "greets a name");
    }

    #[test]
    fn typed_tool_metadata_uses_origin_and_version() {
        let m = Tool::metadata(&GreetTool);
        assert_eq!(m.name, "greet");
        assert_eq!(m.description, "greets a name");
        assert_eq!(m.origin, "test-crate");
        assert_eq!(m.version, "1.0.0");
        assert!(m.requirements.is_empty());
    }

    #[tokio::test]
    async fn typed_tool_call_deserializes_and_formats() {
        let ctx = ToolContext::for_test();
        let out = Tool::call(&GreetTool, &json!({"name": "world"}), &ctx)
            .await
            .unwrap();
        // format_output emits a String verbatim (not JSON-quoted).
        assert_eq!(content_text(&out), "Hello, world!");
    }

    // A struct-typed output confirms non-String outputs still serialize as JSON.
    #[derive(serde::Serialize)]
    struct GreetResult {
        message: String,
    }

    struct GreetStructTool;
    #[async_trait]
    impl TypedTool for GreetStructTool {
        type Args = GreetArgs;
        type Output = GreetResult;
        fn name(&self) -> &'static str {
            "greet_struct"
        }
        fn description(&self) -> &'static str {
            "greets as json"
        }
        async fn call_typed(
            &self,
            args: GreetArgs,
            _ctx: &ToolContext,
        ) -> AgentResult<GreetResult> {
            Ok(GreetResult {
                message: format!("Hello, {}!", args.name),
            })
        }
    }

    #[test]
    fn format_output_json_serializes_struct() {
        let out = GreetStructTool.format_output(GreetResult {
            message: "hi".into(),
        });
        assert_eq!(content_text(&[out]), r#"{"message":"hi"}"#);
    }

    #[tokio::test]
    async fn typed_tool_call_invalid_args_is_tool_args_invalid() {
        let ctx = ToolContext::for_test();
        let err = Tool::call(&GreetTool, &json!({"nope": 1}), &ctx)
            .await
            .unwrap_err();
        assert!(matches!(err, AgentError::ToolArgsInvalid { .. }));
    }

    struct NamedTool(&'static str);
    #[async_trait]
    impl Tool for NamedTool {
        fn name(&self) -> &'static str {
            self.0
        }
        fn description(&self) -> &'static str {
            ""
        }
        fn schema(&self) -> serde_json::Value {
            serde_json::Value::Null
        }
        async fn call(
            &self,
            _args: &serde_json::Value,
            _ctx: &ToolContext,
        ) -> AgentResult<Vec<Content>> {
            Ok(vec![])
        }
    }

    #[test]
    fn registry_register_arc_get_remove_len_is_empty() {
        let mut r = ToolRegistry::default();
        assert!(r.is_empty());
        assert_eq!(r.len(), 0);

        let t: Arc<dyn Tool> = Arc::new(NamedTool("x"));
        r.register_arc(t);
        assert!(!r.is_empty());
        assert_eq!(r.len(), 1);
        assert!(r.get("x").is_some());
        assert!(r.get("missing").is_none());

        r.remove("x");
        assert!(r.is_empty());
    }

    #[test]
    fn metadatas_are_sorted_by_name() {
        let mut r = ToolRegistry::default();
        r.register(NamedTool("zeta"));
        r.register(NamedTool("alpha"));

        let metas = r.metadatas();
        let names: Vec<&str> = metas.iter().map(|m| m.name.as_str()).collect();
        assert_eq!(names, vec!["alpha", "zeta"]);
        assert_eq!(metas[0].origin, "custom");
        assert_eq!(metas[0].version, "unknown");
    }

    // โ”€โ”€ Phase 2: ToolExposure + definitions_filtered โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    struct ExposureTool(&'static str, ToolExposure);
    #[async_trait]
    impl Tool for ExposureTool {
        fn name(&self) -> &'static str {
            self.0
        }
        fn description(&self) -> &'static str {
            ""
        }
        fn schema(&self) -> serde_json::Value {
            serde_json::Value::Null
        }
        async fn call(
            &self,
            _args: &serde_json::Value,
            _ctx: &ToolContext,
        ) -> AgentResult<Vec<Content>> {
            Ok(vec![])
        }
        fn exposure(&self) -> ToolExposure {
            self.1.clone()
        }
    }

    struct ConditionalTool(&'static str, bool);
    #[async_trait]
    impl Tool for ConditionalTool {
        fn name(&self) -> &'static str {
            self.0
        }
        fn description(&self) -> &'static str {
            ""
        }
        fn schema(&self) -> serde_json::Value {
            serde_json::Value::Null
        }
        async fn call(
            &self,
            _args: &serde_json::Value,
            _ctx: &ToolContext,
        ) -> AgentResult<Vec<Content>> {
            Ok(vec![])
        }
        fn exposure(&self) -> ToolExposure {
            ToolExposure::Deferred
        }
        fn should_activate(&self, _ctx: &ActivationContext) -> bool {
            self.1
        }
    }

    fn default_ctx() -> ActivationContext {
        ActivationContext {
            session_id: crate::types::SessionId::new(0),
            current_tools: vec![],
            workspace: std::path::PathBuf::from("/tmp"),
        }
    }

    #[test]
    fn tool_exposure_default_is_direct() {
        // NamedTool doesn't override exposure() โ†’ default Direct
        let t = NamedTool("x");
        assert_eq!(t.exposure(), ToolExposure::Direct);
    }

    #[test]
    fn tool_should_activate_default_is_true() {
        let t = NamedTool("x");
        assert!(t.should_activate(&default_ctx()));
    }

    #[test]
    fn definitions_filtered_includes_direct_excludes_hidden() {
        let mut r = ToolRegistry::default();
        r.register(ExposureTool("direct_a", ToolExposure::Direct));
        r.register(ExposureTool("hidden_a", ToolExposure::Hidden));
        r.register(ExposureTool("direct_b", ToolExposure::Direct));

        let defs = r.definitions_filtered(&default_ctx());
        let names: Vec<&str> = defs
            .iter()
            .map(|d| d["function"]["name"].as_str().unwrap())
            .collect();
        assert_eq!(names, vec!["direct_a", "direct_b"]);
    }

    #[test]
    fn definitions_filtered_includes_deferred_when_activated() {
        let mut r = ToolRegistry::default();
        r.register(ExposureTool("always", ToolExposure::Direct));
        r.register(ConditionalTool("maybe", true)); // should_activate = true
        r.register(ConditionalTool("never", false)); // should_activate = false

        let defs = r.definitions_filtered(&default_ctx());
        let names: Vec<&str> = defs
            .iter()
            .map(|d| d["function"]["name"].as_str().unwrap())
            .collect();
        assert_eq!(names, vec!["always", "maybe"]);
    }

    #[test]
    fn definitions_filtered_all_hidden_returns_empty() {
        let mut r = ToolRegistry::default();
        r.register(ExposureTool("h1", ToolExposure::Hidden));
        r.register(ExposureTool("h2", ToolExposure::Hidden));

        let defs = r.definitions_filtered(&default_ctx());
        assert!(defs.is_empty());
    }

    #[test]
    fn definitions_filtered_empty_registry() {
        let r = ToolRegistry::default();
        let defs = r.definitions_filtered(&default_ctx());
        assert!(defs.is_empty());
    }

    #[test]
    fn definitions_unfiltered_includes_hidden() {
        // The original definitions() method does NOT filter โ€” all tools appear.
        let mut r = ToolRegistry::default();
        r.register(ExposureTool("visible", ToolExposure::Direct));
        r.register(ExposureTool("secret", ToolExposure::Hidden));

        let defs = r.definitions();
        assert_eq!(defs.len(), 2);
    }
}