klieo-tools 3.5.0

Tool dispatch + JSON-schema arg validation + timeout enforcement for klieo-core.
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
//! `AgentTool` — presents any [`klieo_core::Agent`] as a single-tool
//! [`klieo_core::Tool`], so it can be wrapped alongside ordinary tools
//! in a [`crate::ChainedInvoker`] (or run directly as a
//! [`klieo_core::ToolInvoker`] — see the type docs).
//!
//! Promoted from the `klieo-mcp-server`-private `AgentAsToolInvoker`
//! (klieo ADK-gap-close Item D) so any transport — not just MCP — can
//! expose an agent as a tool without hand-rolling the `AgentContext`
//! wiring: a fresh context per invocation via `ctx_factory`,
//! cancellation derived from the incoming [`ToolCtx`], non-PII tenant
//! attribution from `ToolCtx::caller_principal`, and cross-hop
//! provenance from `ToolCtx::parent_anchor`.

use async_trait::async_trait;
use klieo_core::agent::{Agent, AgentContext};
use klieo_core::error::ToolError;
use klieo_core::llm::ToolDef;
use klieo_core::tool::{Tool, ToolCtx, ToolInvoker};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::sync::Arc;

/// Factory for a fresh [`AgentContext`], called once per invocation so
/// every run gets its own `RunId` and cancellation token. Caller-owned
/// so `klieo-tools` stays free of opinions about which memory / bus /
/// LLM backends an agent runs against.
pub type AgentContextFactory = Arc<dyn Fn() -> AgentContext + Send + Sync + 'static>;

/// Hook applied to the freshly-built [`AgentContext`] immediately
/// before the wrapped agent runs, after [`AgentTool`]'s own
/// cancellation / attribution / provenance wiring. Lets a caller
/// install cross-cutting context mutation — e.g. `klieo-mcp-server`'s
/// optional inbound governor wraps `ctx.llm` in a `GovernedLlmClient`
/// — without `klieo-tools` depending on the caller's crate.
pub type AgentContextTransform = Arc<dyn Fn(AgentContext) -> AgentContext + Send + Sync + 'static>;

/// Presents one [`Agent`] as a single named [`Tool`]. Also implements
/// [`ToolInvoker`] directly so a caller exposing exactly this one
/// agent (the common case) can skip [`crate::ChainedInvoker`]'s
/// per-tool timeout and schema re-validation — useful for transports
/// that already validate args against the advertised schema before
/// dispatch (e.g. `klieo-mcp-server`).
pub struct AgentTool<A>
where
    A: Agent + 'static,
    A::Input: DeserializeOwned + Send + 'static,
    A::Output: Serialize + Send + 'static,
{
    agent: Arc<A>,
    name: String,
    description: String,
    input_schema: serde_json::Value,
    ctx_factory: AgentContextFactory,
    ctx_transform: Option<AgentContextTransform>,
}

impl<A> AgentTool<A>
where
    A: Agent + 'static,
    A::Input: DeserializeOwned + Send + 'static,
    A::Output: Serialize + Send + 'static,
{
    /// Wrap `agent` as a tool named after [`Agent::name`], advertising
    /// `input_schema` as its JSON-schema. `ctx_factory` mints a fresh
    /// [`AgentContext`] per invocation. Default description is
    /// `"klieo agent: {name}"`; override via [`Self::with_description`].
    pub fn new(
        agent: A,
        input_schema: serde_json::Value,
        ctx_factory: AgentContextFactory,
    ) -> Self {
        let name = agent.name().to_string();
        let description = format!("klieo agent: {name}");
        Self {
            agent: Arc::new(agent),
            name,
            description,
            input_schema,
            ctx_factory,
            ctx_transform: None,
        }
    }

    /// Override the default `"klieo agent: {name}"` description shown
    /// to callers (e.g. in an MCP `tools/list` response).
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Install a hook applied to every freshly-built [`AgentContext`]
    /// just before the agent runs, after this type's own cancellation
    /// / attribution / provenance wiring. See [`AgentContextTransform`].
    #[must_use]
    pub fn with_context_transform(mut self, transform: AgentContextTransform) -> Self {
        self.ctx_transform = Some(transform);
        self
    }

    /// Build the per-invocation [`AgentContext`], run the agent, and
    /// encode its output. Shared by the [`Tool`] and [`ToolInvoker`]
    /// impls below so neither re-implements the wiring.
    async fn run_agent(
        &self,
        args: serde_json::Value,
        tool_ctx: ToolCtx,
    ) -> Result<serde_json::Value, ToolError> {
        let input = self.decode_input(args)?;
        let ctx = self.build_context(tool_ctx);
        let output = self.agent.run(ctx, input).await.map_err(|e| {
            tracing::warn!(agent = %self.name, error = %e, "exposed agent execution failed");
            ToolError::Permanent("agent execution failed".into())
        })?;
        serde_json::to_value(output).map_err(|e| {
            tracing::warn!(agent = %self.name, error = %e, "encode of agent output failed");
            ToolError::Permanent("agent output not serialisable".into())
        })
    }

    /// Decode `args` into `A::Input`. The stable wire-bound message
    /// never carries the serde internal detail (type names, field
    /// paths) — only a server-side log does (CWE-209).
    fn decode_input(&self, args: serde_json::Value) -> Result<A::Input, ToolError> {
        serde_json::from_value(args).map_err(|e| {
            tracing::warn!(agent = %self.name, error = %e, "decode of agent tool args failed");
            ToolError::InvalidArgs("arguments do not match inputSchema".into())
        })
    }

    /// Mint the per-invocation context: start from `ctx_factory`,
    /// overlay cancellation + progress from the incoming `tool_ctx`,
    /// derive non-PII tenant attribution from `caller_principal`,
    /// thread through `parent_anchor` verbatim, then apply the
    /// caller's `ctx_transform` hook (if any).
    fn build_context(&self, tool_ctx: ToolCtx) -> AgentContext {
        let mut ctx = (self.ctx_factory)();
        ctx.cancel = tool_ctx.cancel.child_token();
        ctx.progress = tool_ctx.progress.clone();
        if let Some(principal) = tool_ctx.caller_principal.as_ref() {
            ctx = ctx.with_tenant_label(klieo_core::principal_hash(principal.as_str()));
        }
        if let Some(anchor) = tool_ctx.parent_anchor.as_ref() {
            ctx = ctx.with_parent_anchor(anchor.as_str().to_string());
        }
        if let Some(transform) = self.ctx_transform.as_ref() {
            ctx = transform(ctx);
        }
        ctx
    }
}

#[async_trait]
impl<A> Tool for AgentTool<A>
where
    A: Agent + 'static,
    A::Input: DeserializeOwned + Send + 'static,
    A::Output: Serialize + Send + 'static,
{
    fn name(&self) -> &str {
        &self.name
    }

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

    fn json_schema(&self) -> &serde_json::Value {
        &self.input_schema
    }

    async fn invoke(
        &self,
        args: serde_json::Value,
        ctx: ToolCtx,
    ) -> Result<serde_json::Value, ToolError> {
        self.run_agent(args, ctx).await
    }
}

#[async_trait]
impl<A> ToolInvoker for AgentTool<A>
where
    A: Agent + 'static,
    A::Input: DeserializeOwned + Send + 'static,
    A::Output: Serialize + Send + 'static,
{
    fn catalogue(&self) -> Vec<ToolDef> {
        vec![ToolDef::new(
            self.name.clone(),
            self.description.clone(),
            self.input_schema.clone(),
        )]
    }

    async fn invoke(
        &self,
        name: &str,
        args: serde_json::Value,
        ctx: ToolCtx,
    ) -> Result<serde_json::Value, ToolError> {
        if name != self.name {
            return Err(ToolError::UnknownTool(name.to_string()));
        }
        self.run_agent(args, ctx).await
    }
}

#[cfg(test)]
mod tests {
    use crate::invoker::ChainedInvoker;
    use async_trait::async_trait;
    use klieo_core::agent::{Agent, AgentContext};
    use klieo_core::error::ToolError;
    use klieo_core::ids::ThreadId;
    use klieo_core::llm::ToolDef;
    use klieo_core::test_utils::{fake_context, noop_bus, FakeLlmClient, FakeLlmStep};
    use klieo_core::tool::ToolCtx;
    use klieo_core::Episode;
    use std::sync::Arc;

    use super::{AgentContextFactory, AgentTool};

    /// Minimal agent: echoes `{"who": ..}` back as `{"greeting": ..}`
    /// with no LLM/tool dependency, for tests that only exercise
    /// decode/run/encode plumbing.
    struct GreeterAgent;

    #[async_trait]
    impl Agent for GreeterAgent {
        type Input = serde_json::Value;
        type Output = serde_json::Value;
        type Error = std::convert::Infallible;

        fn name(&self) -> &str {
            "greeter"
        }
        fn system_prompt(&self) -> &str {
            ""
        }
        fn tools(&self) -> &[ToolDef] {
            &[]
        }
        async fn run(
            &self,
            _ctx: AgentContext,
            input: serde_json::Value,
        ) -> Result<serde_json::Value, Self::Error> {
            let who = input.get("who").and_then(|v| v.as_str()).unwrap_or("world");
            Ok(serde_json::json!({ "greeting": format!("hello {who}") }))
        }
    }

    #[derive(serde::Deserialize, serde::Serialize)]
    struct GreetInput {
        who: String,
    }

    struct StrictGreeterAgent;

    #[async_trait]
    impl Agent for StrictGreeterAgent {
        type Input = GreetInput;
        type Output = serde_json::Value;
        type Error = std::convert::Infallible;

        fn name(&self) -> &str {
            "strict-greeter"
        }
        fn system_prompt(&self) -> &str {
            ""
        }
        fn tools(&self) -> &[ToolDef] {
            &[]
        }
        async fn run(
            &self,
            _ctx: AgentContext,
            input: GreetInput,
        ) -> Result<serde_json::Value, Self::Error> {
            Ok(serde_json::json!({ "greeting": format!("hello {}", input.who) }))
        }
    }

    /// Reports `ctx.cancel.is_cancelled()` and `ctx.progress.is_some()`
    /// in its output, for tests proving `ToolCtx` wiring reaches the
    /// minted `AgentContext`.
    struct ObserverAgent;

    #[derive(serde::Serialize)]
    struct ObserverOut {
        cancelled: bool,
        has_progress: bool,
    }

    #[async_trait]
    impl Agent for ObserverAgent {
        type Input = serde_json::Value;
        type Output = ObserverOut;
        type Error = std::convert::Infallible;

        fn name(&self) -> &str {
            "observer"
        }
        fn system_prompt(&self) -> &str {
            ""
        }
        fn tools(&self) -> &[ToolDef] {
            &[]
        }
        async fn run(
            &self,
            ctx: AgentContext,
            _input: serde_json::Value,
        ) -> Result<ObserverOut, Self::Error> {
            Ok(ObserverOut {
                cancelled: ctx.cancel.is_cancelled(),
                has_progress: ctx.progress.is_some(),
            })
        }
    }

    /// Agent whose `run` drives `klieo_core::runtime::run_steps`, so
    /// `Episode::RunAttributed` / `Episode::RunOrigin` recording (which
    /// only the runtime emits) can be observed.
    struct EchoLoopAgent;

    #[async_trait]
    impl Agent for EchoLoopAgent {
        type Input = serde_json::Value;
        type Output = serde_json::Value;
        type Error = klieo_core::Error;

        fn name(&self) -> &str {
            "echo-loop"
        }
        fn system_prompt(&self) -> &str {
            ""
        }
        fn tools(&self) -> &[ToolDef] {
            &[]
        }
        async fn run(
            &self,
            ctx: AgentContext,
            _input: serde_json::Value,
        ) -> Result<serde_json::Value, Self::Error> {
            let out = klieo_core::runtime::run_steps(
                &ctx,
                "",
                ThreadId::new("echo-loop-thread"),
                klieo_core::runtime::RunOptions::default(),
            )
            .await?;
            Ok(serde_json::Value::String(out))
        }
    }

    struct FailingAgent;

    #[async_trait]
    impl Agent for FailingAgent {
        type Input = serde_json::Value;
        type Output = serde_json::Value;
        type Error = std::io::Error;

        fn name(&self) -> &str {
            "failing"
        }
        fn system_prompt(&self) -> &str {
            ""
        }
        fn tools(&self) -> &[ToolDef] {
            &[]
        }
        async fn run(
            &self,
            _ctx: AgentContext,
            _input: serde_json::Value,
        ) -> Result<serde_json::Value, Self::Error> {
            Err(std::io::Error::other(
                "internal secret-abc leaked from https://internal.example/",
            ))
        }
    }

    /// `Serialize` impl that always fails, so the encode step in
    /// `AgentTool::run_agent` has something real to sanitise.
    struct UnserializableOutput;

    impl serde::Serialize for UnserializableOutput {
        fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
            Err(serde::ser::Error::custom(
                "intentionally unserialisable: internal-detail-xyz",
            ))
        }
    }

    struct UnserializableAgent;

    #[async_trait]
    impl Agent for UnserializableAgent {
        type Input = serde_json::Value;
        type Output = UnserializableOutput;
        type Error = std::convert::Infallible;

        fn name(&self) -> &str {
            "unserializable"
        }
        fn system_prompt(&self) -> &str {
            ""
        }
        fn tools(&self) -> &[ToolDef] {
            &[]
        }
        async fn run(
            &self,
            _ctx: AgentContext,
            _input: serde_json::Value,
        ) -> Result<UnserializableOutput, Self::Error> {
            Ok(UnserializableOutput)
        }
    }

    fn object_schema() -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }

    fn ctx_factory() -> AgentContextFactory {
        Arc::new(|| fake_context("agent-tool-test"))
    }

    fn tool_ctx() -> ToolCtx {
        let (pubsub, _, kv, jobs) = noop_bus();
        ToolCtx::new(pubsub, kv, jobs)
    }

    struct PlainEchoTool;

    #[async_trait]
    impl klieo_core::tool::Tool for PlainEchoTool {
        fn name(&self) -> &str {
            "plain-echo"
        }
        fn description(&self) -> &str {
            "echoes args back"
        }
        fn json_schema(&self) -> &serde_json::Value {
            static SCHEMA: std::sync::OnceLock<serde_json::Value> = std::sync::OnceLock::new();
            SCHEMA.get_or_init(|| serde_json::json!({"type": "object"}))
        }
        async fn invoke(
            &self,
            args: serde_json::Value,
            _ctx: ToolCtx,
        ) -> Result<serde_json::Value, ToolError> {
            Ok(args)
        }
    }

    #[tokio::test]
    async fn tool_invoke_runs_agent_in_process_and_returns_serialized_output() {
        use klieo_core::tool::Tool;

        let tool = AgentTool::new(GreeterAgent, object_schema(), ctx_factory());
        let out = tool
            .invoke(serde_json::json!({"who": "ferris"}), tool_ctx())
            .await
            .unwrap();
        assert_eq!(out, serde_json::json!({"greeting": "hello ferris"}));
    }

    #[tokio::test]
    async fn tool_exposes_agent_name_description_and_schema() {
        use klieo_core::tool::Tool;

        let schema = object_schema();
        let tool = AgentTool::new(GreeterAgent, schema.clone(), ctx_factory());
        assert_eq!(tool.name(), "greeter");
        assert_eq!(tool.description(), "klieo agent: greeter");
        assert_eq!(tool.json_schema(), &schema);
    }

    #[tokio::test]
    async fn tool_invoker_dispatches_by_matching_name() {
        use klieo_core::tool::ToolInvoker;

        let tool = AgentTool::new(GreeterAgent, object_schema(), ctx_factory());
        let out = tool
            .invoke("greeter", serde_json::json!({"who": "world"}), tool_ctx())
            .await
            .unwrap();
        assert_eq!(out, serde_json::json!({"greeting": "hello world"}));
    }

    #[tokio::test]
    async fn tool_invoker_rejects_wrong_tool_name() {
        use klieo_core::tool::ToolInvoker;

        let tool = AgentTool::new(GreeterAgent, object_schema(), ctx_factory());
        let err = tool
            .invoke("not-greeter", serde_json::json!({}), tool_ctx())
            .await
            .unwrap_err();
        assert!(matches!(err, ToolError::UnknownTool(name) if name == "not-greeter"));
    }

    #[tokio::test]
    async fn tool_invoker_catalogue_lists_agent_as_single_tool() {
        use klieo_core::tool::ToolInvoker;

        let tool = AgentTool::new(GreeterAgent, object_schema(), ctx_factory());
        let cat = tool.catalogue();
        assert_eq!(cat.len(), 1);
        assert_eq!(cat[0].name, "greeter");
    }

    #[tokio::test]
    async fn malformed_args_return_invalid_args_not_panic() {
        use klieo_core::tool::Tool;

        let tool = AgentTool::new(StrictGreeterAgent, object_schema(), ctx_factory());
        let err = tool
            .invoke(serde_json::json!({"unexpected": "shape"}), tool_ctx())
            .await
            .unwrap_err();
        assert!(matches!(err, ToolError::InvalidArgs(_)));
    }

    #[tokio::test]
    async fn malformed_args_detail_is_not_leaked_on_the_wire() {
        use klieo_core::tool::Tool;

        let tool = AgentTool::new(StrictGreeterAgent, object_schema(), ctx_factory());
        let err = tool
            .invoke(serde_json::json!({"unexpected": "shape"}), tool_ctx())
            .await
            .unwrap_err();
        let ToolError::InvalidArgs(msg) = err else {
            panic!("expected InvalidArgs, got {err:?}");
        };
        assert_eq!(msg, "arguments do not match inputSchema");
        assert!(!msg.contains("missing field"), "serde detail leaked: {msg}");
        assert!(!msg.contains("who"), "field name leaked: {msg}");
    }

    #[tokio::test]
    async fn agent_execution_error_is_sanitised_and_does_not_leak_detail() {
        use klieo_core::tool::Tool;

        let tool = AgentTool::new(FailingAgent, object_schema(), ctx_factory());
        let err = tool
            .invoke(serde_json::json!({}), tool_ctx())
            .await
            .unwrap_err();
        let ToolError::Permanent(msg) = err else {
            panic!("expected Permanent, got {err:?}");
        };
        assert_eq!(msg, "agent execution failed");
        assert!(!msg.contains("secret-abc"));
        assert!(!msg.contains("https://"));
    }

    #[tokio::test]
    async fn output_encode_failure_is_sanitised() {
        use klieo_core::tool::Tool;

        let tool = AgentTool::new(UnserializableAgent, object_schema(), ctx_factory());
        let err = tool
            .invoke(serde_json::json!({}), tool_ctx())
            .await
            .unwrap_err();
        let ToolError::Permanent(msg) = err else {
            panic!("expected Permanent, got {err:?}");
        };
        assert_eq!(msg, "agent output not serialisable");
        assert!(
            !msg.contains("internal-detail-xyz"),
            "encode detail leaked: {msg}"
        );
    }

    #[tokio::test]
    async fn chained_invoker_resolves_agent_tool_alongside_a_normal_tool() {
        use klieo_core::tool::ToolInvoker;

        let agent_tool = AgentTool::new(GreeterAgent, object_schema(), ctx_factory());
        let inv = ChainedInvoker::new()
            .with_tool(Arc::new(agent_tool))
            .unwrap()
            .with_tool(Arc::new(PlainEchoTool))
            .unwrap();

        let agent_out = inv
            .invoke("greeter", serde_json::json!({"who": "chained"}), tool_ctx())
            .await
            .unwrap();
        assert_eq!(agent_out, serde_json::json!({"greeting": "hello chained"}));

        let plain_out = inv
            .invoke("plain-echo", serde_json::json!({"x": 1}), tool_ctx())
            .await
            .unwrap();
        assert_eq!(plain_out, serde_json::json!({"x": 1}));

        let catalogue = inv.catalogue();
        let cat_names: Vec<&str> = catalogue.iter().map(|d| d.name.as_str()).collect();
        assert!(cat_names.contains(&"greeter"));
        assert!(cat_names.contains(&"plain-echo"));
    }

    #[tokio::test]
    async fn cancel_token_is_derived_from_tool_ctx_when_live() {
        use klieo_core::tool::Tool;

        let tool = AgentTool::new(ObserverAgent, object_schema(), ctx_factory());
        let out = tool
            .invoke(serde_json::json!({}), tool_ctx())
            .await
            .unwrap();
        assert_eq!(out["cancelled"], false);
    }

    #[tokio::test]
    async fn cancel_token_propagates_when_tool_ctx_is_already_cancelled() {
        use klieo_core::tool::Tool;

        let ctx = tool_ctx();
        ctx.cancel.cancel();

        let tool = AgentTool::new(ObserverAgent, object_schema(), ctx_factory());
        let out = tool.invoke(serde_json::json!({}), ctx).await.unwrap();
        assert_eq!(out["cancelled"], true);
    }

    #[tokio::test]
    async fn progress_sender_is_propagated_from_tool_ctx() {
        use klieo_core::tool::Tool;

        let (tx, _rx) = tokio::sync::broadcast::channel::<klieo_core::AgentEvent>(8);
        let ctx = tool_ctx().with_progress(tx);

        let tool = AgentTool::new(ObserverAgent, object_schema(), ctx_factory());
        let out = tool.invoke(serde_json::json!({}), ctx).await.unwrap();
        assert_eq!(out["has_progress"], true);
    }

    #[tokio::test]
    async fn progress_defaults_to_none_when_tool_ctx_has_none() {
        use klieo_core::tool::Tool;

        let tool = AgentTool::new(ObserverAgent, object_schema(), ctx_factory());
        let out = tool
            .invoke(serde_json::json!({}), tool_ctx())
            .await
            .unwrap();
        assert_eq!(out["has_progress"], false);
    }

    #[tokio::test]
    async fn tenant_label_is_installed_from_caller_principal() {
        use klieo_core::tool::Tool;
        const PRINCIPAL: &str = "alice@example.com";

        let mut seed = fake_context("echo-loop");
        seed.llm =
            Arc::new(FakeLlmClient::new("fake").with_steps(vec![FakeLlmStep::Text("done".into())]));
        let episodic = seed.episodic.clone();
        let run_id = seed.run_id;
        let slot = Arc::new(std::sync::Mutex::new(Some(seed)));
        let factory: AgentContextFactory = Arc::new(move || slot.lock().unwrap().take().unwrap());

        let tool = AgentTool::new(EchoLoopAgent, object_schema(), factory);
        let ctx = tool_ctx().with_caller_principal(PRINCIPAL.into());
        tool.invoke(serde_json::json!({}), ctx).await.unwrap();

        let expected = klieo_core::principal_hash(PRINCIPAL);
        let episodes = episodic.replay(run_id).await.unwrap();
        let labels: Vec<&str> = episodes
            .iter()
            .filter_map(|e| match e {
                Episode::RunAttributed { tenant_label } => Some(tenant_label.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(labels, vec![expected.as_str()]);
        for ep in &episodes {
            let payload = serde_json::to_string(ep).unwrap();
            assert!(
                !payload.contains(PRINCIPAL),
                "raw principal leaked: {payload}"
            );
        }
    }

    #[tokio::test]
    async fn parent_anchor_is_recorded_verbatim_as_run_origin() {
        use klieo_core::tool::Tool;
        const ANCHOR: &str = "sha256:deadbeefcafe0123";

        let mut seed = fake_context("echo-loop");
        seed.llm =
            Arc::new(FakeLlmClient::new("fake").with_steps(vec![FakeLlmStep::Text("done".into())]));
        let episodic = seed.episodic.clone();
        let run_id = seed.run_id;
        let slot = Arc::new(std::sync::Mutex::new(Some(seed)));
        let factory: AgentContextFactory = Arc::new(move || slot.lock().unwrap().take().unwrap());

        let tool = AgentTool::new(EchoLoopAgent, object_schema(), factory);
        let ctx = tool_ctx().with_parent_anchor(ANCHOR.into());
        tool.invoke(serde_json::json!({}), ctx).await.unwrap();

        let episodes = episodic.replay(run_id).await.unwrap();
        let anchors: Vec<&str> = episodes
            .iter()
            .filter_map(|e| match e {
                Episode::RunOrigin { parent_anchor } => Some(parent_anchor.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(anchors, vec![ANCHOR]);
    }

    #[tokio::test]
    async fn context_transform_hook_is_applied_before_the_agent_runs() {
        use klieo_core::tool::Tool;

        struct ReportsTenantLabelAgent;
        #[async_trait]
        impl Agent for ReportsTenantLabelAgent {
            type Input = serde_json::Value;
            type Output = serde_json::Value;
            type Error = std::convert::Infallible;
            fn name(&self) -> &str {
                "reports-tenant-label"
            }
            fn system_prompt(&self) -> &str {
                ""
            }
            fn tools(&self) -> &[ToolDef] {
                &[]
            }
            async fn run(
                &self,
                ctx: AgentContext,
                _input: serde_json::Value,
            ) -> Result<serde_json::Value, Self::Error> {
                Ok(serde_json::json!({ "tenant_label": ctx.tenant_label() }))
            }
        }

        // No `caller_principal` on the `ToolCtx`, so `AgentTool`'s own
        // attribution wiring installs nothing — the label observed by
        // the agent can only have come from the transform hook,
        // proving it runs after the built-in wiring and before `run`.
        let tool = AgentTool::new(ReportsTenantLabelAgent, object_schema(), ctx_factory())
            .with_context_transform(Arc::new(|ctx: AgentContext| {
                ctx.with_tenant_label("governed".into())
            }));
        let out = tool
            .invoke(serde_json::json!({}), tool_ctx())
            .await
            .unwrap();
        assert_eq!(out["tenant_label"], serde_json::json!("governed"));
    }

    #[tokio::test]
    async fn with_description_overrides_the_default_description() {
        use klieo_core::tool::Tool;

        let tool = AgentTool::new(GreeterAgent, object_schema(), ctx_factory())
            .with_description("custom description");
        assert_eq!(tool.description(), "custom description");
    }
}