funera-orchestrate 0.1.0

Easy-to-use orchestration layer for funera-core — build LLM agents with a simple builder API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
use std::marker::PhantomData;
#[cfg(feature = "skill")]
use std::path::PathBuf;
use std::sync::Arc;

use async_openai::config::OpenAIConfig;
use tokio::sync::{broadcast, mpsc, RwLock};
use tokio::task::JoinHandle;

#[cfg(feature = "sandbox")]
use funera_core::security::sandbox::SandboxPolicy;
#[cfg(feature = "security")]
use funera_core::security::audit::{AuditBus, AuditEvent};
#[cfg(feature = "security")]
use funera_core::security::policy::ToolPolicy;
#[cfg(feature = "security")]
use funera_core::security::registry::ApprovalCallback;
#[cfg(feature = "security")]
use funera_core::security::secret::SecureApiKey;
#[cfg(all(feature = "sandbox", feature = "security"))]
use funera_core::security::path_guard::PathGuard;
use funera_core::chat::session::{spawn_session_actor, SessionCmd};
#[cfg(test)]
use funera_core::chat::session::FuneraSession;
#[cfg(feature = "deepseek")]
use funera_core::provider::deepseek::DeepSeekProvider;
use funera_core::env::{FuneraEnv, FuneraEnvWatcher};
use funera_core::event_bus::env_state_bus::EnvStateEvent;
#[cfg(feature = "tool")]
use funera_core::event_bus::tool_bus::ToolBus;
use funera_core::provider::ChatProvider;
#[cfg(feature = "skill")]
use funera_core::re_act::skills::{Skill, SkillRegistry};
#[cfg(feature = "tool")]
use funera_core::re_act::tool::{Tool, ToolRegistry};
#[cfg(feature = "tool")]
use funera_core::re_act::tool_executor::ToolExecutor;

#[cfg(feature = "middleware")]
use crate::event::AgentEvent;
#[cfg(feature = "middleware")]
use crate::middleware_bundle::MiddlewareBundle;
#[cfg(feature = "middleware")]
use funera_core::middleware::{ErrorsEnabled, MiddlewareChain};

use crate::error::OrchestrateError;

/// Builds an [`AgentRuntime`].
///
/// ```rust,no_run
/// # use funera_orchestrate::{AgentRuntime, DeepSeekProvider};
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let runtime = AgentRuntime::<DeepSeekProvider>::builder()
///     .api_key(std::env::var("DEEPSEEK_API_KEY")?)
///     .model("deepseek-v4-flash")
///     .build()?;
/// # Ok(())
/// # }
/// ```
pub struct AgentRuntimeBuilder {
    api_key: Option<String>,
    base_url: Option<String>,
    client: Option<async_openai::Client<OpenAIConfig>>,
    model: Option<String>,
    max_iterations: usize,
    channel_buffer: usize,
    #[cfg(feature = "tool")]
    tools: Vec<Box<dyn Tool>>,
    #[cfg(feature = "skill")]
    skills: Vec<Skill>,
    #[cfg(feature = "skill")]
    skill_names_to_activate: Vec<String>,
    #[cfg(feature = "skill")]
    load_default_skills: bool,
    #[cfg(feature = "sandbox")]
    sandbox_policy: Option<SandboxPolicy>,
    #[cfg(feature = "security")]
    tool_policy: Option<ToolPolicy>,
    #[cfg(feature = "security")]
    secure_api_key: Option<SecureApiKey>,
    #[cfg(feature = "security")]
    approval_callback: Option<ApprovalCallback>,
    #[cfg(feature = "security")]
    approval_timeout: Option<std::time::Duration>,
    #[cfg(feature = "middleware")]
    middleware_bundle: Option<MiddlewareBundle<AgentEvent>>,
}

impl Default for AgentRuntimeBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl AgentRuntimeBuilder {
    pub fn new() -> Self {
        Self {
            api_key: None,
            base_url: None,
            client: None,
            model: None,
            max_iterations: 10,
            channel_buffer: 32,
            #[cfg(feature = "tool")]
            tools: Vec::new(),
            #[cfg(feature = "skill")]
            skills: Vec::new(),
            #[cfg(feature = "skill")]
            skill_names_to_activate: Vec::new(),
            #[cfg(feature = "skill")]
            load_default_skills: false,
            #[cfg(feature = "sandbox")]
            sandbox_policy: None,
            #[cfg(feature = "security")]
            tool_policy: None,
            #[cfg(feature = "security")]
            secure_api_key: None,
            #[cfg(feature = "security")]
            approval_callback: None,
            #[cfg(feature = "security")]
            approval_timeout: None,
            #[cfg(feature = "middleware")]
            middleware_bundle: None,
        }
    }

    /// OpenAI API key. Falls back to `OPENAI_API_KEY` env var.
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        let key = key.into();
        #[cfg(feature = "security")]
        {
            self.secure_api_key = Some(SecureApiKey::new(key.clone()));
        }
        self.api_key = Some(key);
        self
    }

    /// Custom base URL (proxy, compatible API, etc.).
    /// Pass e.g. `std::env::var("OPENAI_BASE_URL").ok()`.
    pub fn base_url(mut self, url: Option<String>) -> Self {
        if let Some(u) = url {
            self.base_url = Some(u);
        }
        self
    }

    /// LLM model name. Falls back to `OPENAI_MODEL` env var, then `"gpt-4o"`.
    pub fn model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Directly provide an OpenAI client (overrides api_key + base_url).
    pub fn client(mut self, client: async_openai::Client<OpenAIConfig>) -> Self {
        self.client = Some(client);
        self
    }

    /// Maximum number of ReAct iterations per call (default 10).
    pub fn max_iterations(mut self, n: usize) -> Self {
        self.max_iterations = n;
        self
    }

    /// Internal channel buffer size (default 32).
    pub fn channel_buffer(mut self, n: usize) -> Self {
        self.channel_buffer = n;
        self
    }

    /// Load a skill from a SKILL.md file.
    #[cfg(feature = "skill")]
    pub fn with_skill_file(mut self, path: impl Into<PathBuf>) -> Self {
        let path = path.into();
        match Skill::from_file(&path) {
            Ok(skill) => {
                self.skills.push(skill);
            }
            Err(e) => {
                eprintln!("warn: failed to load skill from {:?}: {}", path, e);
            }
        }
        self
    }

    /// Load all SKILL.md files from a directory.
    #[cfg(feature = "skill")]
    pub fn with_skills_dir(mut self, path: impl Into<PathBuf>) -> Self {
        let path = path.into();
        match Skill::from_dir(&path) {
            Ok(skills) => self.skills.extend(skills),
            Err(e) => {
                eprintln!("warn: failed to load skills from {:?}: {}", path, e);
            }
        }
        self
    }

    /// Register an inline skill definition.
    #[cfg(feature = "skill")]
    pub fn with_skill(
        mut self,
        name: impl Into<String>,
        description: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        self.skills.push(Skill::new(name, description, content));
        self
    }

    /// Activate a previously loaded skill by name.
    /// If the skill does not exist, the call is silently ignored.
    #[cfg(feature = "skill")]
    pub fn with_skill_active(mut self, name: impl Into<String>) -> Self {
        self.skill_names_to_activate.push(name.into());
        self
    }

    /// Auto-discover and load skills from default paths
    /// (`$SKILLS_HOME` or `~/.agents/skills/`), then activate them.
    #[cfg(feature = "skill")]
    pub fn with_skills_default_path(mut self) -> Self {
        self.load_default_skills = true;
        self
    }

    /// Register a tool by its type (requires `Tool + Default`).
    #[cfg(feature = "tool")]
    pub fn with_tool<T: Tool + Default + 'static>(mut self) -> Self {
        self.tools.push(Box::new(T::default()));
        self
    }

    /// Register a pre-constructed tool.
    #[cfg(feature = "tool")]
    pub fn with_tool_instance(mut self, tool: Box<dyn Tool>) -> Self {
        self.tools.push(tool);
        self
    }

    /// Attach a middleware chain with error channel.
    ///
    /// The runtime will spawn a task to consume inspector errors via `tracing::warn`.
    #[cfg(feature = "middleware")]
    pub fn with_middleware_bundle(mut self, bundle: MiddlewareBundle<AgentEvent>) -> Self {
        self.middleware_bundle = Some(bundle);
        self
    }

    /// Set a kernel-enforced sandbox policy for tool subprocesses.
    ///
    /// When enabled, tool subprocesses are isolated via Landlock
    /// (Linux 5.13+), Seatbelt (macOS), or Write-Restricted Token
    /// (Windows 8+). Unsupported configurations gracefully degrade
    /// without full isolation.
    #[cfg(feature = "sandbox")]
    pub fn with_sandbox_policy(mut self, policy: SandboxPolicy) -> Self {
        self.sandbox_policy = Some(policy);
        self
    }

    /// Set an application-level tool policy for controlling which tools
    /// are allowed/denied, shell command restrictions, argument size
    /// limits, timeout bounds, and working directory restrictions.
    ///
    /// The policy is enforced by the guarded tool registry before each
    /// tool call.  Combine with [`with_sandbox_policy`](Self::with_sandbox_policy)
    /// for defence-in-depth (application-level + kernel-enforced isolation).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use funera_orchestrate::{AgentRuntimeBuilder, ToolPolicy, ShellPolicy};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let policy = ToolPolicy {
    ///     denied_tools: ["shell".into()].into_iter().collect(),
    ///     shell_policy: Some(ShellPolicy::strict()),
    ///     ..ToolPolicy::default()
    /// };
    ///
    /// let runtime = AgentRuntimeBuilder::new()
    ///     .api_key(std::env::var("DEEPSEEK_API_KEY")?)
    ///     .model("deepseek-v4-flash")
    ///     .with_tool_policy(policy)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "security")]
    pub fn with_tool_policy(mut self, policy: ToolPolicy) -> Self {
        self.tool_policy = Some(policy);
        self
    }

    /// Register a handler that fires when a tool call requires user approval.
    ///
    /// When a tool call targets a path outside the [`PathGuard`] trusted zone but
    /// within the sandbox boundary, the registry pauses execution and invokes this
    /// handler with `(call_id, tool_name, reason)`. The caller must call
    /// [`GuardedToolRegistry::approve_tool_call`](funera_core::security::registry::GuardedToolRegistry::approve_tool_call)
    /// to approve or reject the pending call.
    ///
    /// Requires the `security` feature.
    #[cfg(feature = "security")]
    pub fn with_approval_handler(
        mut self,
        cb: impl Fn(String, String, String) + Send + Sync + 'static,
    ) -> Self {
        self.approval_callback = Some(std::sync::Arc::new(
            move |call_id: &str, tool_name: &str, reason: &str, _paths: &[std::path::PathBuf]| {
                cb(call_id.to_string(), tool_name.to_string(), reason.to_string());
            },
        ));
        self
    }

    /// Set a timeout for tool call approval. If not set, the registry waits indefinitely.
    /// When the timeout elapses, the tool call is automatically rejected.
    ///
    /// Requires the `security` feature.
    #[cfg(feature = "security")]
    pub fn with_approval_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.approval_timeout = Some(timeout);
        self
    }

    /// Register all builtin tools (Read, Write, Edit, Shell).
    /// Requires the `builtin-tools` feature.
    ///
    /// If a sandbox policy was configured via [`with_sandbox_policy`],
    /// the `shell` tool will apply kernel-level isolation to each subprocess.
    #[cfg(feature = "builtin-tools")]
    pub fn with_builtin_tools(mut self) -> Self {
        use builtin_tools::{EditTool, ReadTool, ShellTool, WriteTool};
        self.tools.push(Box::new(ReadTool));
        self.tools.push(Box::new(WriteTool));
        self.tools.push(Box::new(EditTool));
        #[cfg(feature = "sandbox")]
        if let Some(ref policy) = self.sandbox_policy {
            self.tools.push(Box::new(ShellTool::with_sandbox(policy.clone())));
        } else {
            self.tools.push(Box::new(ShellTool::new()));
        }
        #[cfg(not(feature = "sandbox"))]
        self.tools.push(Box::new(ShellTool::new()));
        self
    }

    /// Build the runtime with the default DeepSeek provider.
    ///
    /// Spawns a background `ToolExecutor` task that lives for the runtime's
    /// lifetime and processes tool calls from the ReAct loop.
    #[cfg(feature = "deepseek")]
    pub fn build(self) -> Result<AgentRuntime<DeepSeekProvider>, OrchestrateError> {
        self.build_with::<DeepSeekProvider>()
    }

    /// Build the runtime with a custom LLM provider.
    ///
    /// ```rust,no_run
    /// # use funera_orchestrate::{AgentRuntime, DeepSeekProvider};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let rt = AgentRuntime::<DeepSeekProvider>::builder().api_key(std::env::var("DEEPSEEK_API_KEY")?).model("deepseek-v4-flash").build_with::<DeepSeekProvider>()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_with<P: ChatProvider>(
        #[allow(unused_mut)] mut self,
    ) -> Result<AgentRuntime<P>, OrchestrateError> {
        #[cfg(feature = "security")]
        let api_key = {
            self.secure_api_key
                .take()
                .map(|k| k.expose_secret().to_string())
                .or_else(|| self.api_key.take())
                .or_else(|| std::env::var("OPENAI_API_KEY").ok())
        };
        #[cfg(not(feature = "security"))]
        let api_key = self.api_key.or_else(|| std::env::var("OPENAI_API_KEY").ok());
        let model = self
            .model
            .or_else(|| std::env::var("OPENAI_MODEL").ok())
            .unwrap_or_else(|| "gpt-4o".into());

        let client = match self.client {
            Some(c) => c,
            None => {
                let key = api_key.ok_or_else(|| {
                    OrchestrateError::Config(
                        "no API key; set OPENAI_API_KEY or call .api_key()".into(),
                    )
                })?;
                let mut cfg = OpenAIConfig::default().with_api_key(key);
                if let Some(url) = &self.base_url {
                    cfg = cfg.with_api_base(url);
                }
                async_openai::Client::with_config(cfg)
            }
        };

        // Sync sandbox policy into tool policy when only sandbox was configured.
        #[cfg(all(feature = "sandbox", feature = "security"))]
        {
            if self.tool_policy.is_none() {
                if let Some(ref sp) = self.sandbox_policy {
                    let mut tp = ToolPolicy::default();
                    tp.sandbox = sp.clone();
                    self.tool_policy = Some(tp);
                }
            }
        }

        #[cfg(feature = "security")]
        let audit_bus = AuditBus::default();

        #[cfg(feature = "tool")]
        let registry = {
            #[cfg(feature = "security")]
            let mut reg = match self.tool_policy {
                Some(ref policy) => ToolRegistry::new_from_policy(policy.clone()),
                None => ToolRegistry::new(),
            };
            #[cfg(not(feature = "security"))]
            let mut reg = ToolRegistry::new();
            for t in self.tools {
                reg.add_tool(t);
            }

            // ── Security wiring ─────────────────────────────────
            #[cfg(feature = "security")]
            reg.set_audit_bus(audit_bus.clone());

            #[cfg(all(feature = "sandbox", feature = "security"))]
            if let Some(ref sp) = self.sandbox_policy {
                if sp.enabled && (!sp.read_paths.is_empty() || !sp.read_write_paths.is_empty()) {
                    let all_paths: Vec<_> = sp
                        .read_paths
                        .iter()
                        .chain(sp.read_write_paths.iter())
                        .cloned()
                        .collect();
                    if !all_paths.is_empty() {
                        let path_guard = PathGuard::new(
                            all_paths.iter().map(|p| p.as_path()),
                        );
                        reg.set_path_guard(path_guard);
                    }
                }
                reg.set_sandbox_paths(
                    sp.read_paths.clone(),
                    sp.read_write_paths.clone(),
                );
            }

            #[cfg(feature = "security")]
            {
                if let Some(ref cb) = self.approval_callback {
                    reg.set_approval_callback(cb.clone());
                }
                if let Some(dur) = self.approval_timeout {
                    reg.set_approval_timeout(Some(dur));
                }
            }
            // ── End security wiring ─────────────────────────────

            reg
        };

        #[cfg(feature = "skill")]
        let mut skill_registry = SkillRegistry::new();

        #[cfg(feature = "skill")]
        {
            if self.load_default_skills {
                let default_skills = Skill::from_default_path();
                for skill in default_skills {
                    let name = skill.name.clone();
                    skill_registry.add(skill);
                    self.skill_names_to_activate.push(name);
                }
            }
            for skill in self.skills {
                skill_registry.add(skill);
            }
            for name in &self.skill_names_to_activate {
                skill_registry.activate(name);
            }
        }

        let (env, env_watcher) = FuneraEnv::new(client, &model);

        #[cfg(feature = "sandbox")]
        let env = if let Some(ref sp) = self.sandbox_policy {
            env.with_sandbox_policy(sp.clone())
        } else {
            env
        };

        #[cfg(feature = "tool")]
        let env = env.with_tool_registry(registry);
        #[cfg(feature = "skill")]
        let env = env.with_skill_registry(skill_registry);

        let (env_state_tx, _) = broadcast::channel(32);

        #[cfg(feature = "tool")]
        if let Ok(guard) = env.tool_registry.try_read() {
            let tools = guard.get_all_tools();
            for name in tools.keys() {
                let _ = env_state_tx.send(EnvStateEvent::ToolAdded(name.clone()));
            }
        }

        #[cfg(feature = "skill")]
        if let Ok(guard) = env.skill_registry.try_read() {
            let skills = guard.all_skills();
            for name in skills.keys() {
                let _ = env_state_tx.send(EnvStateEvent::SkillAdded(name.clone()));
            }
        }

        #[cfg(feature = "middleware")]
        let middleware_chain = if let Some(bundle) = self.middleware_bundle.take() {
            let MiddlewareBundle { chain, error_rx } = bundle;
            tokio::spawn(async move {
                let mut rx = error_rx;
                while let Some((name, err)) = rx.recv().await {
                    tracing::warn!("[middleware:{name}] inspector error: {err}");
                }
            });
            Arc::new(chain)
        } else {
            let (chain, error_rx) = MiddlewareChain::<AgentEvent>::new().activate_error_channel();
            tokio::spawn(async move {
                let mut rx = error_rx;
                while let Some((name, err)) = rx.recv().await {
                    tracing::warn!("[middleware:{name}] inspector error: {err}");
                }
            });
            Arc::new(chain)
        };

        #[cfg(feature = "tool")]
        let (tool_bus, exec_rx) = ToolBus::new();
        #[cfg(feature = "tool")]
        let reg = env.tool_registry.clone();
        #[cfg(feature = "tool")]
        let handle = tokio::spawn(async move {
            ToolExecutor::new(reg, exec_rx).run().await;
        });

        let session_tx = spawn_session_actor();

        #[cfg(feature = "security")]
        let tool_policy_val = self.tool_policy.clone().unwrap_or_default();

        Ok(AgentRuntime::<P> {
            env,
            env_watcher,
            #[cfg(feature = "tool")]
            tool_bus,
            model,
            max_iterations: self.max_iterations,
            channel_buffer: self.channel_buffer,
            env_state_tx,
            #[cfg(feature = "tool")]
            _executor_handle: handle,
            session_tx,
            _state: PhantomData,
            _phantom: PhantomData,
            #[cfg(feature = "middleware")]
            middleware_chain,
            #[cfg(feature = "security")]
            tool_policy: tool_policy_val,
            #[cfg(feature = "security")]
            audit_bus,
        })
    }
}

/// A runtime context for executing agent interactions.
///
/// Marker type-state: the runtime is available for a `send`/`send_stream` call.
pub struct Idle;

/// Marker type-state: a `send`/`send_stream` call is in progress.
pub struct Acquired;

/// `AgentRuntime` owns the shared infrastructure (LLM client, tool registry,
/// tool executor) and a persistent session (backed by a session actor).
///
/// The generic parameter `S` is a type-state marker — [`Idle`] means
/// no `send`/`send_stream` is in progress, [`Acquired`] means one is active.
/// Send operations consume `AgentRuntime<P, Idle>` and return a handle that
/// eventually yields back `AgentRuntime<P, Idle>`.
pub struct AgentRuntime<P: ChatProvider, S = Idle> {
    env: FuneraEnv,
    pub(crate) env_watcher: FuneraEnvWatcher,
    #[cfg(feature = "tool")]
    pub(crate) tool_bus: ToolBus,
    pub(crate) model: String,
    pub(crate) max_iterations: usize,
    pub(crate) channel_buffer: usize,
    env_state_tx: broadcast::Sender<EnvStateEvent>,
    #[cfg(feature = "tool")]
    _executor_handle: JoinHandle<()>,
    pub(crate) session_tx: mpsc::UnboundedSender<SessionCmd>,
    _state: PhantomData<S>,
    _phantom: PhantomData<fn() -> P>,
    #[cfg(feature = "middleware")]
    middleware_chain: Arc<MiddlewareChain<AgentEvent, ErrorsEnabled>>,
    #[cfg(feature = "security")]
    tool_policy: ToolPolicy,
    #[cfg(feature = "security")]
    audit_bus: AuditBus,
}

// ── All state markers share these methods ─────────────────────

impl<P: ChatProvider, S> AgentRuntime<P, S> {
    /// Create a new builder.
    pub fn builder() -> AgentRuntimeBuilder {
        AgentRuntimeBuilder::new()
    }

    /// Reset the conversation session (clear message history).
    pub fn reset(&self) {
        let _ = self.session_tx.send(SessionCmd::Clear);
    }

    /// Access the session control channel.
    pub fn session_tx(&self) -> mpsc::UnboundedSender<SessionCmd> {
        self.session_tx.clone()
    }

    /// The LLM model name configured for this runtime.
    pub fn model(&self) -> &str {
        &self.model
    }

    /// Maximum ReAct iterations per call.
    pub fn max_iterations(&self) -> usize {
        self.max_iterations
    }

    /// Channel buffer size.
    pub fn channel_buffer(&self) -> usize {
        self.channel_buffer
    }

    /// Clone the env watcher for a session.
    pub(crate) fn env_watcher(&self) -> FuneraEnvWatcher {
        self.env_watcher.clone()
    }

    /// Subscribe to runtime-level environment state events.
    ///
    /// The returned receiver yields [`EnvStateEvent`] notifications about
    /// tool/skill registration changes, LLM model changes, etc. that occur
    /// during the runtime's lifetime.
    ///
    /// Unlike [`Agent::subscribe_raw_events`](crate::Agent::subscribe_raw_events)
    /// which only delivers events during a `fire`/`send` call, this subscription
    /// is persistent and independent of any agent call.
    pub fn subscribe_env_state(&self) -> broadcast::Receiver<EnvStateEvent> {
        self.env_state_tx.subscribe()
    }

    /// Subscribe to security audit events.
    ///
    /// The returned receiver yields [`AuditEvent`] notifications for every
    /// tool execution, denial, policy violation, and sandbox action. This is
    /// an independent, persistent subscription that is not tied to any
    /// particular agent call.
    ///
    /// Requires the `security` feature.
    #[cfg(feature = "security")]
    pub fn subscribe_audit(&self) -> broadcast::Receiver<AuditEvent> {
        self.audit_bus.subscribe()
    }

    /// Access the middleware chain for event filtering.
    #[cfg(feature = "middleware")]
    pub fn middleware_chain(&self) -> Arc<MiddlewareChain<AgentEvent, ErrorsEnabled>> {
        self.middleware_chain.clone()
    }

    /// Transform the runtime into `Acquired` state (internal use).
    pub(crate) fn into_acquired(self) -> AgentRuntime<P, Acquired> {
        AgentRuntime::<P, Acquired> {
            env: self.env,
            env_watcher: self.env_watcher,
            #[cfg(feature = "tool")]
            tool_bus: self.tool_bus,
            model: self.model,
            max_iterations: self.max_iterations,
            channel_buffer: self.channel_buffer,
            env_state_tx: self.env_state_tx,
            #[cfg(feature = "tool")]
            _executor_handle: self._executor_handle,
            session_tx: self.session_tx,
            _state: PhantomData,
            _phantom: PhantomData,
            #[cfg(feature = "middleware")]
            middleware_chain: self.middleware_chain,
            #[cfg(feature = "security")]
            tool_policy: self.tool_policy,
            #[cfg(feature = "security")]
            audit_bus: self.audit_bus,
        }
    }

    /// The tool registry (for dynamic tool management).
    #[cfg(feature = "tool")]
    pub fn tool_registry(&self) -> Arc<RwLock<ToolRegistry>> {
        self.env.tool_registry.clone()
    }

    /// The skill registry (for dynamic skill management).
    #[cfg(feature = "skill")]
    pub fn skill_registry(&self) -> Arc<RwLock<SkillRegistry>> {
        self.env.skill_registry.clone()
    }

    /// The sandbox policy configured for this runtime.
    #[cfg(feature = "sandbox")]
    pub fn sandbox_policy(&self) -> SandboxPolicy {
        self.env.sandbox_policy().clone()
    }

    /// The application-level tool policy configured for this runtime.
    ///
    /// Returns the [`ToolPolicy`] that controls which tools are allowed,
    /// shell command restrictions, argument size limits, timeout bounds,
    /// and working directory restrictions.
    #[cfg(feature = "security")]
    pub fn tool_policy(&self) -> &ToolPolicy {
        &self.tool_policy
    }
}

// ── Acquired → Idle ─────────────────────────────────────────

impl<P: ChatProvider> AgentRuntime<P, Acquired> {
    pub(crate) fn into_idle(self) -> AgentRuntime<P, Idle> {
        AgentRuntime::<P, Idle> {
            env: self.env,
            env_watcher: self.env_watcher,
            #[cfg(feature = "tool")]
            tool_bus: self.tool_bus,
            model: self.model,
            max_iterations: self.max_iterations,
            channel_buffer: self.channel_buffer,
            env_state_tx: self.env_state_tx,
            #[cfg(feature = "tool")]
            _executor_handle: self._executor_handle,
            session_tx: self.session_tx,
            _state: PhantomData,
            _phantom: PhantomData,
            #[cfg(feature = "middleware")]
            middleware_chain: self.middleware_chain,
            #[cfg(feature = "security")]
            tool_policy: self.tool_policy,
            #[cfg(feature = "security")]
            audit_bus: self.audit_bus,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use funera_core::chat::message::{FuneraMessage, MsgVariant, Role, TextMessage};

    // ── builder defaults ───────────────────────────────────────────

    #[test]
    fn builder_defaults() {
        let b = AgentRuntimeBuilder::new();
        assert_eq!(b.max_iterations, 10);
        assert_eq!(b.channel_buffer, 32);
        assert!(b.api_key.is_none());
        assert!(b.model.is_none());
    }

    #[cfg(feature = "tool")]
    mod tool_tests {
        use super::*;
        use funera_core::re_act::tool::ToolCallError;

        #[derive(Default)]
        struct MockTool;

        #[async_trait::async_trait]
        impl Tool for MockTool {
            fn name(&self) -> &str {
                "mock_tool"
            }
            fn description(&self) -> &str {
                "A mock tool for testing"
            }
            fn schema(&self) -> serde_json::Value {
                serde_json::json!({})
            }
            async fn execute(&self, _args: serde_json::Value) -> Result<String, ToolCallError> {
                Ok("ok".into())
            }
        }

        #[test]
        fn builder_defaults_tools_empty() {
            let b = AgentRuntimeBuilder::new();
            assert!(b.tools.is_empty());
        }

        #[test]
        fn builder_with_tool_instance() {
            let b = AgentRuntimeBuilder::new()
                .with_tool_instance(Box::new(MockTool));
            assert_eq!(b.tools.len(), 1);
        }

        #[tokio::test]
        async fn build_with_tool_adds_to_registry() {
            let rt = AgentRuntimeBuilder::new()
                .api_key("sk-test")
                .model("x")
                .with_tool::<MockTool>()
                .build()
                .unwrap();
            let registry = rt.tool_registry();
            let guard = registry.read().await;
            let tools = guard.get_all_tools();
            assert!(tools.contains_key("mock_tool"));
        }

        #[tokio::test]
        async fn tool_registry_accessor() {
            let rt = AgentRuntimeBuilder::new()
                .api_key("sk-test")
                .model("x")
                .build()
                .unwrap();
            let reg = rt.tool_registry();
            let guard = reg.read().await;
            let tools = guard.get_all_tools();
            assert!(tools.is_empty());
        }
    }

    #[cfg(feature = "skill")]
    mod skill_tests {
        use super::*;

        #[test]
        fn builder_with_skill_inline() {
            let b = AgentRuntimeBuilder::new()
                .with_skill("s1", "desc", "content");
            assert_eq!(b.skills.len(), 1);
            assert_eq!(b.skills[0].name, "s1");
            assert_eq!(b.skills[0].description, "desc");
            assert_eq!(b.skills[0].content, "content");
        }

        #[test]
        fn builder_with_skill_active_adds_to_list() {
            let b = AgentRuntimeBuilder::new()
                .with_skill_active("s1")
                .with_skill_active("s2");
            assert_eq!(b.skill_names_to_activate, vec!["s1", "s2"]);
        }

        #[test]
        fn builder_with_skills_default_path_sets_flag() {
            let b = AgentRuntimeBuilder::new().with_skills_default_path();
            assert!(b.load_default_skills);
        }

        #[test]
        fn builder_skills_combined() {
            let b = AgentRuntimeBuilder::new()
                .with_skill("a", "", "aaa")
                .with_skill("b", "", "bbb")
                .with_skill_active("a");
            assert_eq!(b.skills.len(), 2);
            assert_eq!(b.skill_names_to_activate, vec!["a"]);
        }
    }

    #[test]
    fn builder_set_max_iterations() {
        let b = AgentRuntimeBuilder::new().max_iterations(20);
        assert_eq!(b.max_iterations, 20);
    }

    #[test]
    fn builder_set_channel_buffer() {
        let b = AgentRuntimeBuilder::new().channel_buffer(64);
        assert_eq!(b.channel_buffer, 64);
    }

    #[test]
    fn builder_set_model() {
        let b = AgentRuntimeBuilder::new().model("test-model");
        assert_eq!(b.model, Some("test-model".into()));
    }

    #[test]
    fn builder_set_api_key() {
        let b = AgentRuntimeBuilder::new().api_key("sk-test");
        assert_eq!(b.api_key, Some("sk-test".into()));
    }

    #[test]
    fn builder_set_base_url() {
        let b = AgentRuntimeBuilder::new().base_url(Some("https://example.com".into()));
        assert_eq!(b.base_url, Some("https://example.com".into()));
    }

    #[test]
    fn builder_set_base_url_none_noop() {
        let b = AgentRuntimeBuilder::new().base_url(None);
        assert!(b.base_url.is_none());
    }

    #[test]
    fn builder_set_client() {
        let cfg = async_openai::config::OpenAIConfig::default();
        let client = async_openai::Client::with_config(cfg);
        let b = AgentRuntimeBuilder::new().client(client);
        assert!(b.client.is_some());
    }

    // ── build ──────────────────────────────────────────────────────

    #[tokio::test]
    async fn build_with_explicit_key() {
        let rt = AgentRuntimeBuilder::new()
            .api_key("sk-test")
            .model("test-model")
            .build()
            .expect("build should succeed with api_key");
        assert_eq!(rt.model(), "test-model");
        assert_eq!(rt.max_iterations(), 10);
        assert_eq!(rt.channel_buffer(), 32);
    }

    #[tokio::test]
    async fn build_custom_params() {
        let rt = AgentRuntimeBuilder::new()
            .api_key("sk-test")
            .model("my-model")
            .max_iterations(15)
            .channel_buffer(8)
            .build()
            .unwrap();
        assert_eq!(rt.model(), "my-model");
        assert_eq!(rt.max_iterations(), 15);
        assert_eq!(rt.channel_buffer(), 8);
    }

    #[tokio::test]
    async fn build_fails_without_key() {
        let has_key = std::env::var("OPENAI_API_KEY").is_ok();
        if has_key {
            // Can't test failure when key is present in env
            return;
        }
        let result = AgentRuntimeBuilder::new().model("x").build();
        assert!(matches!(result, Err(OrchestrateError::Config(_))));
    }

    #[tokio::test]
    async fn build_model_fallback_default() {
        let has_model = std::env::var("OPENAI_MODEL").is_ok();
        if has_model {
            return;
        }
        let rt = AgentRuntimeBuilder::new()
            .api_key("sk-test")
            .build()
            .unwrap();
        assert_eq!(rt.model(), "gpt-4o");
    }

    // ── session management ─────────────────────────────────────────

    #[tokio::test]
    async fn session_actor_is_alive() {
        let rt = AgentRuntimeBuilder::new()
            .api_key("sk-test")
            .model("x")
            .build()
            .unwrap();
        let tx = rt.session_tx();
        assert!(tx.send(SessionCmd::Clear).is_ok());
    }

    #[tokio::test]
    async fn session_context_works_immediately() {
        let rt = AgentRuntimeBuilder::new()
            .api_key("sk-test")
            .model("x")
            .build()
            .unwrap();
        let ctx = FuneraSession::new(rt.session_tx())
            .session_context()
            .await;
        assert!(ctx.is_empty());
    }

    #[tokio::test]
    async fn reset_clears_messages() {
        let rt = AgentRuntimeBuilder::new()
            .api_key("sk-test")
            .model("x")
            .build()
            .unwrap();
        let session = FuneraSession::new(rt.session_tx());
        session.push_message(FuneraMessage::new(
            Role::User,
            MsgVariant::Text(TextMessage { text: "hi".into(), reasoning_content: None }),
        ));
        let ctx_before = session.session_context().await;
        assert_eq!(ctx_before.len(), 1);

        rt.reset();

        let ctx_after = session.session_context().await;
        assert_eq!(ctx_after.len(), 0);
    }

    #[tokio::test]
    async fn subscribe_env_state_works() {
        let rt = AgentRuntimeBuilder::new()
            .api_key("sk-test")
            .model("x")
            .build()
            .unwrap();
        let mut rx = rt.subscribe_env_state();
        // Send an event after subscribing to verify the channel works
        rt.env_state_tx
            .send(EnvStateEvent::LlmChanged("new-model".into()))
            .unwrap();
        let got = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv()).await;
        assert!(matches!(
            got,
            Ok(Ok(EnvStateEvent::LlmChanged(m))) if m == "new-model"
        ));
    }

    // ── sandbox integration tests ───────────────────────────────────

    #[cfg(feature = "sandbox")]
    #[tokio::test]
    async fn builder_sandbox_policy_flows_to_env() {
        use funera_core::security::sandbox::SandboxPolicy;

        let custom_policy = SandboxPolicy {
            read_write_paths: vec!["/project".into()],
            block_network: true,
            ..Default::default()
        };

        let rt = AgentRuntimeBuilder::new()
            .api_key("sk-test")
            .model("x")
            .with_sandbox_policy(custom_policy.clone())
            .build()
            .unwrap();

        let stored = rt.sandbox_policy();
        assert_eq!(stored.read_write_paths, custom_policy.read_write_paths);
        assert_eq!(stored.block_network, custom_policy.block_network);
        assert!(stored.enabled);
    }

    #[cfg(feature = "sandbox")]
    #[tokio::test]
    async fn builder_no_sandbox_uses_default() {
        let rt = AgentRuntimeBuilder::new()
            .api_key("sk-test")
            .model("x")
            .build()
            .unwrap();
        let stored = rt.sandbox_policy();
        // Default policy is enabled with network blocked and empty paths
        assert!(stored.enabled);
        assert!(stored.block_network);
        assert!(stored.read_paths.is_empty());
        assert!(stored.read_write_paths.is_empty());
        assert!(stored.execute_paths.is_empty());
    }

    #[cfg(feature = "sandbox")]
    #[tokio::test]
    async fn builder_sandbox_with_custom_environments() {
        use funera_core::security::sandbox::SandboxPolicy;

        // Test that a disabled sandbox policy flows correctly
        let rt = AgentRuntimeBuilder::new()
            .api_key("sk-test")
            .model("x")
            .with_sandbox_policy(SandboxPolicy::disabled())
            .build()
            .unwrap();

        let stored = rt.sandbox_policy();
        assert!(!stored.enabled, "disabled policy should stay disabled");
    }
}