anda_engine 0.19.0

Agents engine for Anda -- an AI agent framework built with Rust, powered by ICP and TEEs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
//! A host may add request-scoped tools and compose them through the same
//! dispatch path as a model turn. Neither capability is exported over RPC.
use super::{
    AgentCtx, BaseCtx, DiscoveredTools,
    compaction::COMPACT_CONTEXT_TOOL,
    strip_routing_prefix,
    tool::{
        DiscoveryMode, TOOLS_CALL_NAME, TOOLS_SELECT_NAME, ToolsOutput, append_proxy_nudge_note,
        attach_schema_to_error, is_invalid_args_error, observes_discovery,
        parse_tools_call_payload, suggest_similar_names, validate_top_level_tool_args,
    },
};
use crate::subagent::SubAgentSet;
use anda_core::{
    AgentContext, AgentInput, BoxError, BoxPinFut, CancellationToken, FunctionDefinition, Json,
    Resource, ToolInput, ToolOutput, ToolProvider,
};
use parking_lot::Mutex;
use serde::Deserialize;
use serde_json::json;
use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Arc,
};

/// Host-provided callables and policy for the current request.
///
/// Name-based callbacks receive lowercase callable names including any routing prefix.
pub trait RequestCatalog: Send + Sync {
    /// Supplies the tools belonging to this request.
    fn provider(&self, ctx: &BaseCtx) -> Option<Arc<dyn ToolProvider<BaseCtx>>>;
    /// Controls which definitions and group members appear in discovery.
    fn visible(&self, ctx: &BaseCtx, name: &str) -> bool;
    /// Checks host policy at dispatch time. Defaults to visibility.
    fn executable(&self, ctx: &BaseCtx, name: &str) -> bool {
        self.visible(ctx, name)
    }
    /// An optional revision for a scoped definition. Revision changes and removal invalidate prior discovery.
    fn revision(&self, _ctx: &BaseCtx, _name: &str) -> Option<String> {
        None
    }
    /// An optional Python calling hint included in bounded discovery output.
    fn interface(&self, _ctx: &BaseCtx, _definition: &FunctionDefinition) -> Option<String> {
        None
    }
}

/// Install this wrapper in [`BaseCtx`] state to attach a [`RequestCatalog`].
#[derive(Clone)]
pub struct RequestToolCatalog(
    /// Catalog consulted by this request’s discovery and dispatch.
    pub Arc<dyn RequestCatalog>,
);

impl RequestToolCatalog {
    pub(super) fn is_visible(&self, ctx: &BaseCtx, name: &str) -> bool {
        self.0.visible(ctx, &name.to_ascii_lowercase())
    }

    pub(super) fn permits_execution(ctx: &BaseCtx, name: &str) -> bool {
        ctx.get_state::<Self>()
            .is_none_or(|catalog| catalog.0.executable(ctx, &name.to_ascii_lowercase()))
    }
}

pub(super) fn callable_allowed(
    allowed: Option<&BTreeSet<String>>,
    discovered: &DiscoveredTools,
    lowercase_name: &str,
) -> bool {
    allowed.is_none_or(|allowed| {
        let contains = |name: &str| allowed.contains(name) || discovered.contains(name);
        contains(lowercase_name) || strip_routing_prefix(lowercase_name).is_some_and(contains)
    })
}

/// Prepared callable invocation returned by [`CallableDispatch::prepare_call`].
pub(super) struct PreparedCall {
    /// Resolved callable name (the unwrapped target for `tools_call`, otherwise the called name).
    pub(super) target_name: String,
    pub(super) run: BoxPinFut<Result<ToolOutput<Json>, BoxError>>,
}

/// A runner round’s dispatch handle, available to tools through [`BaseCtx::get_state`].
#[derive(Clone)]
pub struct CallableDispatch {
    ctx: AgentCtx,
    allowed: Option<Arc<BTreeSet<String>>>,
    discovered: Arc<Mutex<DiscoveredTools>>,
    resources: Arc<tokio::sync::Mutex<Vec<Resource>>>,
    /// Whether the model that emitted these calls was offered the proxy.
    proxy_declared: bool,
    /// Explicit tools offered for the next turn, which receives the discovery guidance.
    offered_tools: Arc<BTreeSet<String>>,
    /// Whether the active model activates mid-conversation `tool_additions` natively.
    native_tool_additions: bool,
    /// Whether runner-intrinsic `compact_context` is active on this runner.
    self_compaction_active: bool,
    pub(super) cancellation: CancellationToken,
    /// Provider-supplied ID of the outer model call, when present.
    pub call_id: Option<String>,
}

impl CallableDispatch {
    pub(super) fn new(
        ctx: AgentCtx,
        allowed: Option<BTreeSet<String>>,
        discovered: DiscoveredTools,
        resources: Arc<tokio::sync::Mutex<Vec<Resource>>>,
    ) -> Self {
        Self {
            cancellation: ctx.base.cancellation_token.child_token(),
            ctx,
            allowed: allowed.map(Arc::new),
            discovered: Arc::new(Mutex::new(discovered)),
            resources,
            proxy_declared: false,
            offered_tools: Arc::default(),
            native_tool_additions: false,
            self_compaction_active: false,
            call_id: None,
        }
    }

    pub(super) fn with_runner_policy(
        mut self,
        history_tools: Option<&BTreeSet<String>>,
        next_tools: &[FunctionDefinition],
        native_tool_additions: bool,
        self_compaction_active: bool,
    ) -> Self {
        self.proxy_declared = history_tools.is_some_and(|tools| {
            tools
                .iter()
                .any(|name| name.eq_ignore_ascii_case(TOOLS_CALL_NAME))
        });
        self.offered_tools = Arc::new(
            next_tools
                .iter()
                .map(|tool| tool.name.to_ascii_lowercase())
                .collect(),
        );
        self.native_tool_additions = native_tool_additions;
        self.self_compaction_active = self_compaction_active;
        self
    }

    pub(super) fn take_discovered(&self) -> DiscoveredTools {
        std::mem::take(&mut *self.discovered.lock())
    }

    pub(super) fn proxy_target(&self, base: &BaseCtx, name: &str) -> bool {
        !self.offered_tools.contains(&name.to_ascii_lowercase())
            && RequestToolCatalog::permits_execution(base, name)
    }

    fn proxy_offered_next(&self, base: &BaseCtx) -> bool {
        self.offered_tools.contains(TOOLS_CALL_NAME) && self.policy_permits(base, TOOLS_CALL_NAME)
    }

    /// Returns whether discovery output should advertise `call_via_tools_call`:
    /// the proxy is usable and discovered tools are not merged into the request.
    pub(super) fn should_hint_proxy(&self, base: &BaseCtx) -> bool {
        self.proxy_offered_next(base)
            && !self
                .discovered
                .lock()
                .effective_merge(self.native_tool_additions)
    }

    /// Checks request identity, host execution policy and the runner allowlist.
    /// The opt-in `tools_call` proxy must also be declared on the calling turn and visible.
    pub fn permits(&self, base: &BaseCtx, name: &str) -> bool {
        (!name.eq_ignore_ascii_case(TOOLS_CALL_NAME) || self.proxy_declared)
            && self.policy_permits(base, name)
    }

    fn policy_permits(&self, base: &BaseCtx, name: &str) -> bool {
        if self.cancellation.is_cancelled() || !self.ctx.base.shares_request(base) {
            return false;
        }
        let name = name.to_ascii_lowercase();
        let is_proxy = name == TOOLS_CALL_NAME;
        if let Some(catalog) = base.get_state::<RequestToolCatalog>()
            && (!catalog.0.executable(base, &name) || (is_proxy && !catalog.0.visible(base, &name)))
        {
            return false;
        }
        let mut discovered = self.discovered.lock();
        discovered.refresh_scoped(base);
        callable_allowed(self.allowed.as_deref(), &discovered, &name)
    }

    /// Dispatch with a snapshot of the invoking tool's state in the same request.
    /// The call follows cancellation of either the invoking context or the runner round.
    pub async fn call(
        &self,
        base: &BaseCtx,
        name: String,
        args: Json,
    ) -> Result<ToolOutput<Json>, BoxError> {
        self.prepare_call(base, name, args).await?.run.await
    }

    // Reserve all direct model calls' inputs before starting any of them.
    pub(super) async fn prepare_call(
        &self,
        base: &BaseCtx,
        mut name: String,
        mut args: Json,
    ) -> Result<PreparedCall, BoxError> {
        if self.cancellation.is_cancelled() || base.cancellation_token.is_cancelled() {
            return Err("tool call cancelled".into());
        }
        if !self.permits(base, &name) {
            return Err(format!("tool {name} is not permitted for this agent").into());
        }

        let via_proxy = name.eq_ignore_ascii_case(TOOLS_CALL_NAME);
        let mut is_raw_string = false;
        if via_proxy {
            let (parsed, raw_str) =
                parse_tools_call_payload(&args).map_err(|err| -> BoxError { err.into() })?;
            if parsed.name.eq_ignore_ascii_case(TOOLS_CALL_NAME) {
                return Err(format!(
                    "{TOOLS_CALL_NAME} cannot invoke itself; pass the target callable name directly"
                )
                .into());
            }
            if self.self_compaction_active && parsed.name.eq_ignore_ascii_case(COMPACT_CONTEXT_TOOL)
            {
                return Err(format!(
                    "{COMPACT_CONTEXT_TOOL} cannot be invoked via {TOOLS_CALL_NAME}; call it directly as the sole call in your response"
                )
                .into());
            }
            if !self.permits(base, &parsed.name) {
                return Err(format!("tool {} is not permitted for this agent", parsed.name).into());
            }
            if self
                .offered_tools
                .contains(&parsed.name.to_ascii_lowercase())
            {
                log::debug!(
                    "{TOOLS_CALL_NAME} invoked directly offered callable {}",
                    parsed.name
                );
            }
            name = parsed.name;
            args = parsed.arguments;
            is_raw_string = raw_str;
        }

        let mut ctx = self.ctx.clone();
        ctx.base = base.with_caller(base.caller);
        ctx.base.set_state(self.clone());
        let lower = name.to_ascii_lowercase();
        let is_tool = ctx.has_tool_lowercase(&lower);
        let has_agent = ctx.agents.contains_lowercase(&lower)
            || strip_routing_prefix(&lower)
                .is_some_and(|sub| ctx.subagents.contains_lowercase(sub));
        if !is_tool && !has_agent {
            if via_proxy {
                let candidates: Vec<FunctionDefinition> = ctx
                    .definitions(None)
                    .await
                    .into_iter()
                    .filter(|def| self.permits(&ctx.base, &def.name))
                    .collect();
                let suggestions = suggest_similar_names(&candidates, &name, 3);
                let mut payload = serde_json::Map::new();
                payload.insert(
                    "error".to_string(),
                    Json::String(format!("tool call failed: {name} not found")),
                );
                if !suggestions.is_empty() {
                    payload.insert("did_you_mean".to_string(), json!(suggestions));
                }
                let output = ToolOutput {
                    is_error: Some(true),
                    ..ToolOutput::new(Json::Object(payload))
                };
                return Ok(PreparedCall {
                    target_name: TOOLS_CALL_NAME.to_string(),
                    run: Box::pin(async move { Ok(output) }),
                });
            }
            return Err(format!("tool call failed: {name} not found").into());
        }

        if via_proxy && is_tool {
            let target = visible_target_definition(&ctx, &lower, true);
            let error = if is_raw_string {
                Some(format!(
                    "invalid {TOOLS_CALL_NAME} arguments: \"arguments\" for tool {name} must be a JSON object"
                ))
            } else {
                target
                    .as_ref()
                    .and_then(|def| validate_top_level_tool_args(def, &args).err())
            };
            if let Some(error) = error {
                let output = attach_schema_to_error(error, target.as_ref());
                return Ok(PreparedCall {
                    target_name: name,
                    run: Box::pin(async move { Ok(output) }),
                });
            }
        }

        let resources = {
            let mut pool = self.resources.lock().await;
            if is_tool {
                ctx.select_tool_resources(&name, &mut pool).await
            } else {
                ctx.select_agent_resources(&name, &mut pool).await
            }
        };
        let cancellation = base.cancellation_token.clone();
        let dispatch = self.clone();
        let target_name = name.clone();
        Ok(PreparedCall {
            target_name,
            run: Box::pin(async move {
                let run = async {
                    if (via_proxy && !dispatch.permits(&ctx.base, TOOLS_CALL_NAME))
                        || !dispatch.permits(&ctx.base, &name)
                    {
                        return Err(format!("tool {name} is not permitted for this agent").into());
                    }
                    // Capture revisions before discovery can await its selector model.
                    let revisions = observes_discovery(&name).then(|| scoped_revisions(&ctx));
                    let exec_res: Result<ToolOutput<Json>, BoxError> = if is_tool {
                        ctx.tool_call(ToolInput {
                            name: name.clone(),
                            args,
                            resources,
                            meta: None,
                        })
                        .await
                        .map_err(|err| format!("tool call failed: {err}").into())
                    } else {
                        let prompt = if let Some(prompt) = args.as_str() {
                            prompt.to_owned()
                        } else if let Some(object) = args.as_object()
                            && object.len() == 1
                            && let Some(prompt) = object.get("prompt").and_then(Json::as_str)
                        {
                            prompt.to_owned()
                        } else {
                            args.to_string()
                        };
                        ctx.clone()
                            .agent_run(AgentInput {
                                name: name.clone(),
                                prompt,
                                resources,
                                ..Default::default()
                            })
                            .await
                            .map_err(|err| format!("agent run failed: {err}").into())
                            .map(anda_core::AgentOutput::into_tool_output)
                    };
                    let argument_error = |message| {
                        let target = dispatch
                            .permits(&ctx.base, &name)
                            .then(|| visible_target_definition(&ctx, &lower, is_tool))
                            .flatten();
                        attach_schema_to_error(message, target.as_ref())
                    };
                    let mut result = match exec_res {
                        Ok(output) => output,
                        Err(err) if via_proxy && is_invalid_args_error(&err.to_string()) => {
                            return Ok(argument_error(err.to_string()));
                        }
                        Err(err) => return Err(err),
                    };
                    if via_proxy
                        && result.is_error == Some(true)
                        && result.model_output.is_none()
                        && let Some(text) = result
                            .output
                            .as_str()
                            .filter(|text| is_invalid_args_error(text))
                    {
                        result.output = argument_error(text.to_owned()).output;
                    }
                    if let Some(revisions) = revisions
                        && !result.is_error.unwrap_or(false)
                        && let Ok(tools) = ToolsOutput::deserialize(&result.output)
                    {
                        // An explicit `Some(false)` disables native merging too, so the proxy
                        // path (hints and repeat nudges) applies.
                        let native = dispatch.native_tool_additions
                            && dispatch.discovered.lock().merge_policy() != Some(false);
                        let mode = if native {
                            DiscoveryMode::NativeAdditions
                        } else if name.eq_ignore_ascii_case(TOOLS_SELECT_NAME)
                            && dispatch.proxy_offered_next(&ctx.base)
                        {
                            DiscoveryMode::ProxyActive(
                                tools
                                    .tools
                                    .iter()
                                    .filter(|tool| dispatch.proxy_target(&ctx.base, &tool.name))
                                    .map(|tool| tool.name.clone())
                                    .collect(),
                            )
                        } else {
                            DiscoveryMode::LegacyProbe
                        };
                        let repeated = dispatch
                            .discovered
                            .lock()
                            .observe_scoped(&name, tools, &revisions, mode);
                        append_proxy_nudge_note(&mut result.output, &repeated);
                    }
                    Ok(result)
                };
                tokio::select! {
                    biased;
                    _ = cancellation.cancelled() => Err("tool call cancelled".into()),
                    _ = dispatch.cancellation.cancelled() => Err("tool call cancelled".into()),
                    result = run => result,
                }
            }),
        })
    }
}

/// Returns the requested callable's visible definition, excluding other routing names.
fn visible_target_definition(
    ctx: &AgentCtx,
    lowercase_name: &str,
    is_tool: bool,
) -> Option<FunctionDefinition> {
    let names = [lowercase_name.to_string()];
    let definitions = if is_tool {
        ctx.tool_definitions(Some(&names))
    } else {
        ctx.agent_definitions(Some(&names))
    };
    definitions
        .into_iter()
        .find(|d| d.name.eq_ignore_ascii_case(lowercase_name))
}

fn scoped_revisions(ctx: &AgentCtx) -> BTreeMap<String, Option<String>> {
    let Some(catalog) = ctx.base.get_state::<RequestToolCatalog>() else {
        return BTreeMap::new();
    };
    ctx.scoped_tool_definitions(None)
        .into_iter()
        .map(|d| {
            let revision = catalog.0.revision(&ctx.base, &d.name);
            (d.name, revision)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        context::test_fixtures::{EchoAgent, EchoTool, RecordingCompleter, ToolCallCompleter},
        engine::EngineBuilder,
        model::{CompletionFeaturesDyn, Model},
    };
    use anda_core::{
        AgentOutput, BoxFut, CompletionRequest, StateFeatures, Tool, ToolCall, ToolGroup,
    };
    use parking_lot::RwLock;
    use serde_json::json;

    struct ScopedProvider {
        definitions: RwLock<Vec<FunctionDefinition>>,
    }

    impl ToolProvider<BaseCtx> for ScopedProvider {
        fn name(&self) -> String {
            "scoped".into()
        }

        fn definitions(&self, _: Option<&[String]>) -> Vec<FunctionDefinition> {
            self.definitions.read().clone()
        }

        fn groups(&self) -> Vec<ToolGroup> {
            vec![ToolGroup {
                id: "scope".into(),
                members: self
                    .definitions
                    .read()
                    .iter()
                    .map(|def| def.name.clone())
                    .collect(),
                ..Default::default()
            }]
        }

        fn supported_resource_tags(&self, name: &str) -> Vec<String> {
            if name == "scoped_read" {
                vec!["*".into()]
            } else {
                Vec::new()
            }
        }

        fn call(
            &self,
            ctx: BaseCtx,
            input: ToolInput<Json>,
        ) -> BoxFut<'_, Result<ToolOutput<Json>, BoxError>> {
            Box::pin(async move {
                if input.name == "scoped_wait" {
                    std::future::pending::<()>().await;
                }
                let call_id = ctx.get_state::<CallableDispatch>().and_then(|d| d.call_id);
                Ok(ToolOutput::new(json!({
                    "name": input.name,
                    "resources": input.resources.len(),
                    "call_id": call_id,
                })))
            })
        }
    }

    struct ScopedCatalog(Arc<ScopedProvider>);

    impl RequestCatalog for ScopedCatalog {
        fn provider(&self, _: &BaseCtx) -> Option<Arc<dyn ToolProvider<BaseCtx>>> {
            Some(self.0.clone())
        }

        fn visible(&self, _: &BaseCtx, name: &str) -> bool {
            !matches!(name, "scoped_hidden" | "echo_agent" | "note")
        }

        fn revision(&self, _: &BaseCtx, name: &str) -> Option<String> {
            self.0
                .definitions
                .read()
                .iter()
                .find(|def| def.name != "scoped_wait" && def.name.eq_ignore_ascii_case(name))
                .map(|def| def.description.clone())
        }
    }

    fn tool_definition(name: &str, description: &str) -> FunctionDefinition {
        FunctionDefinition {
            name: name.into(),
            description: description.into(),
            parameters: json!({"type":"object","properties":{}}),
            ..Default::default()
        }
    }

    fn install_catalog(ctx: &AgentCtx) -> Arc<ScopedProvider> {
        let provider = Arc::new(ScopedProvider {
            definitions: RwLock::new(vec![
                tool_definition("SCOPED_READ", "v1"),
                tool_definition("scoped_hidden", "hidden"),
                tool_definition("echo_tool", "shadowed"),
                tool_definition("scoped_wait", "wait"),
            ]),
        });
        ctx.base
            .set_state(RequestToolCatalog(Arc::new(ScopedCatalog(
                provider.clone(),
            ))));
        provider
    }

    #[tokio::test]
    async fn code_mode_dispatch_requires_execution_permission_independent_of_loaded_schemas() {
        let ctx = EngineBuilder::new()
            .register_tool(Arc::new(EchoTool))
            .unwrap()
            .mock_ctx();
        let host = CallableDispatch::new(ctx.clone(), None, Default::default(), Default::default());
        assert!(
            host.call(&ctx.base, "echo_tool".into(), json!({"input":"ok"}))
                .await
                .is_ok()
        );
        let restricted = CallableDispatch::new(
            ctx.clone(),
            Some(BTreeSet::new()),
            Default::default(),
            Default::default(),
        );
        let fake = json!({"tools":[{"name":"echo_tool","description":"echo","parameters":{"type":"object"}}]});
        restricted
            .discovered
            .lock()
            .observe_output("code_list", &fake);
        assert!(!restricted.permits(&ctx.base, "echo_tool"));
        assert!(
            restricted
                .call(&ctx.base, "echo_tool".into(), json!({"input":"denied"}))
                .await
                .is_err()
        );
        let other = ctx
            .base
            .with_caller(anda_core::Principal::management_canister());
        assert!(!host.permits(&other, "echo_tool"));

        let other_request = EngineBuilder::new().mock_ctx();
        assert_eq!(ctx.base.caller(), other_request.base.caller());
        assert!(!host.permits(&other_request.base, "echo_tool"));
        assert!(host.permits(&ctx.base.cancellable_child(), "echo_tool"));
    }

    #[tokio::test]
    async fn scoped_catalog_applies_filters_and_execution_policy() {
        let ctx = EngineBuilder::new()
            .register_tool(Arc::new(EchoTool))
            .unwrap()
            .register_agent(Arc::new(EchoAgent), None)
            .unwrap()
            .mock_ctx();
        install_catalog(&ctx);

        let definitions = ctx
            .definitions(Some(&["SCOPED_READ".into(), "scoped_hidden".into()]))
            .await;
        assert_eq!(definitions.len(), 1);
        assert_eq!(definitions[0].name, "scoped_read");
        assert!(ctx.tool_definitions(Some(&[])).is_empty());
        assert!(
            ctx.tool_definitions(None)
                .iter()
                .all(|def| !def.name.eq_ignore_ascii_case("scoped_hidden"))
        );
        assert!(
            ctx.agent_definitions(None)
                .iter()
                .all(|def| !def.name.eq_ignore_ascii_case("echo_agent"))
        );
        let groups = ctx.tool_groups();
        let group = groups.iter().find(|group| group.id == "scope").unwrap();
        assert_eq!(group.members, ["scoped_read", "scoped_wait"]);

        let dispatch =
            CallableDispatch::new(ctx.clone(), None, Default::default(), Default::default());
        assert!(!dispatch.permits(&ctx.base, "SCOPED_HIDDEN"));
        assert!(
            ctx.tool_call(ToolInput::new("SCOPED_HIDDEN".into(), json!({})))
                .await
                .is_err()
        );
        assert!(
            ctx.clone()
                .agent_run(AgentInput {
                    name: "ECHO_AGENT".into(),
                    ..Default::default()
                })
                .await
                .is_err()
        );
        let output = dispatch
            .call(&ctx.base, "SCOPED_READ".into(), json!({}))
            .await
            .unwrap();
        assert_eq!(output.output["name"], "scoped_read");
        let child = ctx.base.cancellable_child();
        child.cancellation_token().cancel();
        assert_eq!(
            dispatch
                .call(&child, "scoped_read".into(), json!({}))
                .await
                .unwrap_err()
                .to_string(),
            "tool call cancelled"
        );
    }

    #[tokio::test]
    async fn runner_refreshes_only_live_scoped_offers() {
        let requests = Arc::new(std::sync::Mutex::new(Vec::new()));
        let model = Model::with_completer(Arc::new(RecordingCompleter {
            name: "scoped_offers".into(),
            requests: requests.clone(),
        }));
        let ctx = EngineBuilder::new()
            .with_model(model)
            .register_tool(Arc::new(EchoTool))
            .unwrap()
            .mock_ctx();
        let provider = install_catalog(&ctx);
        let mut runner = ctx
            .clone()
            .completion_iter(
                CompletionRequest {
                    prompt: "initial offer".into(),
                    tools: ctx
                        .definitions(Some(&["scoped_read".into(), "echo_tool".into()]))
                        .await,
                    ..Default::default()
                },
                Vec::new(),
            )
            .unbound();
        runner.next().await.unwrap().unwrap();
        provider.definitions.write()[0].description = "v2".into();
        runner.follow_up("updated catalog".to_string());
        runner.next().await.unwrap().unwrap();
        provider.definitions.write().remove(0);
        runner.follow_up("removed scoped tool".to_string());
        runner.next().await.unwrap().unwrap();

        let requests = requests.lock().unwrap();
        assert_eq!(requests[0].tools[1].description, "v1");
        assert_eq!(requests[1].tools[1].description, "v2");
        assert_eq!(requests[2].tools.len(), 1);
        for request in requests.iter() {
            assert_eq!(request.tools[0].name, "echo_tool");
            assert_eq!(request.tools[0].description, EchoTool.description());
        }
    }

    #[tokio::test]
    async fn a_hidden_note_tool_does_not_inject_its_index() {
        use crate::extension::note::{NoteArgs, NoteContextConfig, NoteItemInput, NoteTool};

        let requests = Arc::new(std::sync::Mutex::new(Vec::new()));
        let model = Model::with_completer(Arc::new(RecordingCompleter {
            name: "hidden_note".into(),
            requests: requests.clone(),
        }));
        let note = Arc::new(NoteTool::new());
        let ctx = EngineBuilder::new()
            .with_model(model)
            .register_tool(note.clone())
            .unwrap()
            .mock_ctx();
        note.call(
            ctx.child_base(NoteTool::NAME).unwrap(),
            NoteArgs {
                op: Some("set".into()),
                items: Some(vec![NoteItemInput {
                    id: "fact".into(),
                    content: Some("stored note".into()),
                }]),
                ..Default::default()
            },
            Vec::new(),
        )
        .await
        .unwrap();
        ctx.base.set_state(NoteContextConfig::default());
        install_catalog(&ctx);

        let mut runner = ctx.completion_iter(
            CompletionRequest {
                prompt: "start".into(),
                tools: vec![note.definition()],
                ..Default::default()
            },
            Vec::new(),
        );
        runner.next().await.unwrap().unwrap();
        let requests = requests.lock().unwrap();
        assert!(requests[0].tools.is_empty());
        assert!(requests[0].chat_history.is_empty());
    }

    struct UpdatingSelector(Arc<ScopedProvider>);

    impl CompletionFeaturesDyn for UpdatingSelector {
        fn model_name(&self) -> String {
            "updating_selector".into()
        }

        fn completion(&self, _: CompletionRequest) -> BoxPinFut<Result<AgentOutput, BoxError>> {
            self.0.definitions.write()[0].description = "v2".into();
            Box::pin(async {
                Ok(AgentOutput {
                    content: json!({"tools":["scoped_read"]}).to_string(),
                    ..Default::default()
                })
            })
        }
    }

    #[tokio::test]
    async fn composed_discovery_is_invalidated_if_the_catalog_changes_during_selection() {
        let ctx = EngineBuilder::new().mock_ctx();
        let provider = install_catalog(&ctx);
        ctx.models
            .set_model(Model::with_completer(Arc::new(UpdatingSelector(provider))));
        let dispatch = CallableDispatch::new(
            ctx.clone(),
            Some(BTreeSet::from(["tools_select".into()])),
            Default::default(),
            Default::default(),
        );

        let selected = dispatch
            .call(
                &ctx.base,
                "tools_select".into(),
                json!({"query":"scoped_read"}),
            )
            .await
            .unwrap();
        assert_eq!(selected.output["tools"][0]["description"], "v1");
        assert!(!dispatch.permits(&ctx.base, "scoped_read"));
        let selected = dispatch
            .call(
                &ctx.base,
                "tools_select".into(),
                json!({"tools":["scoped_read"]}),
            )
            .await
            .unwrap();
        assert_eq!(selected.output["tools"][0]["description"], "v2");
        assert!(dispatch.permits(&ctx.base, "scoped_read"));
    }

    #[tokio::test]
    async fn discovery_forgets_removed_unversioned_tools() {
        let ctx = EngineBuilder::new().mock_ctx();
        let provider = install_catalog(&ctx);
        let dispatch = CallableDispatch::new(
            ctx.clone(),
            Some(BTreeSet::from(["tools_select".into()])),
            Default::default(),
            Default::default(),
        );
        dispatch
            .call(
                &ctx.base,
                "tools_select".into(),
                json!({"tools":["scoped_wait"]}),
            )
            .await
            .unwrap();
        assert!(dispatch.permits(&ctx.base, "scoped_wait"));
        provider
            .definitions
            .write()
            .retain(|def| def.name != "scoped_wait");
        assert!(!dispatch.permits(&ctx.base, "scoped_wait"));
    }

    struct ComposeTool;

    impl Tool<BaseCtx> for ComposeTool {
        type Args = Json;
        type Output = Json;

        fn name(&self) -> String {
            "compose".into()
        }
        fn description(&self) -> String {
            "Call another tool".into()
        }
        fn definition(&self) -> FunctionDefinition {
            tool_definition(&self.name(), &self.description())
        }

        async fn call(
            &self,
            ctx: BaseCtx,
            args: Json,
            _: Vec<Resource>,
        ) -> Result<ToolOutput<Json>, BoxError> {
            let dispatch = ctx.get_state::<CallableDispatch>().unwrap();
            dispatch.call(&ctx, "scoped_read".into(), args).await
        }
    }

    fn calls_model(names: &[&str]) -> Model {
        Model::with_completer(Arc::new(ToolCallCompleter {
            tool_calls: names
                .iter()
                .map(|name| ToolCall {
                    name: name.to_string(),
                    args: json!({}),
                    call_id: Some(name.to_string()),
                    ..Default::default()
                })
                .collect(),
        }))
    }

    #[tokio::test]
    async fn composed_calls_share_resources_after_direct_calls_reserve_theirs() {
        let ctx = EngineBuilder::new()
            .with_model(calls_model(&["compose", "scoped_read"]))
            .register_tool(Arc::new(ComposeTool))
            .unwrap()
            .mock_ctx();
        install_catalog(&ctx);
        let mut runner = ctx.completion_iter(
            CompletionRequest {
                prompt: "run both tools".into(),
                ..Default::default()
            },
            vec![Resource::default()],
        );
        runner.next().await.unwrap().unwrap();
        let output = runner.next().await.unwrap().unwrap();
        let composed = &output.tool_calls[0].result.as_ref().unwrap().output;
        let direct = &output.tool_calls[1].result.as_ref().unwrap().output;
        assert_eq!(composed["call_id"], "compose");
        assert_eq!(composed["resources"], 0);
        assert_eq!(direct["resources"], 1);
    }

    #[tokio::test]
    async fn runner_keeps_unused_resources_when_a_tool_round_is_interrupted() {
        let ctx = EngineBuilder::new()
            .with_model(calls_model(&["scoped_wait"]))
            .mock_ctx();
        install_catalog(&ctx);
        let mut runner = ctx.clone().completion_iter(
            CompletionRequest {
                prompt: "start work".into(),
                ..Default::default()
            },
            vec![Resource::default()],
        );
        runner.next().await.unwrap().unwrap();
        {
            let mut step = Box::pin(runner.next());
            assert!(futures::poll!(step.as_mut()).is_pending());
        }

        runner.discard_in_flight_request();
        ctx.models.set_model(calls_model(&["scoped_read"]));
        runner.follow_up("read the attachment".to_string());
        runner.next().await.unwrap().unwrap();
        let output = runner.next().await.unwrap().unwrap();
        assert_eq!(
            output.tool_calls[0].result.as_ref().unwrap().output["resources"],
            1
        );
    }
}