clawft-core 0.5.1

Core engine for clawft (agent loop, message bus, context management)
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
//! Application bootstrap and dependency wiring.
//!
//! Provides [`AppContext`], a convenience struct that initializes all
//! core components from a [`Config`] and a [`Platform`], then produces
//! an [`AgentLoop`] ready to run.
//!
//! # Usage
//!
//! ```rust,ignore
//! use clawft_core::bootstrap::AppContext;
//! use clawft_platform::NativePlatform;
//! use clawft_types::config::Config;
//!
//! let config = Config::default();
//! let platform = Arc::new(NativePlatform::new());
//! let ctx = AppContext::new(config, platform).await?;
//! let agent_loop = ctx.into_agent_loop();
//! agent_loop.run().await?;
//! ```

use std::sync::Arc;

use tracing::{debug, info};

use clawft_platform::Platform;
use clawft_types::config::Config;

use crate::agent::context::ContextBuilder;
use crate::agent::loop_core::{AgentLoop, AutoDelegation};
use crate::agent::memory::MemoryStore;
use crate::agent::skills::SkillsLoader;
use crate::bus::MessageBus;
use crate::pipeline::assembler::TokenBudgetAssembler;
use crate::pipeline::classifier::KeywordClassifier;
use crate::pipeline::cost_tracker::CostTracker;
use crate::pipeline::rate_limiter::RateLimiter;
use crate::pipeline::router::StaticRouter;
use crate::pipeline::tiered_router::TieredRouter;
use crate::pipeline::traits::{ModelRouter, Pipeline, PipelineRegistry};
use crate::pipeline::transport::OpenAiCompatTransport;
use crate::session::SessionManager;
use crate::tools::registry::ToolRegistry;

/// Fully initialized application context.
///
/// Holds all dependencies needed to run the agent loop. Created via
/// [`AppContext::new`] and consumed via [`AppContext::into_agent_loop`].
///
/// The generic parameter `P` is the platform implementation (e.g.
/// [`NativePlatform`](clawft_platform::NativePlatform) for native,
/// a WASM platform for browser environments).
pub struct AppContext<P: Platform> {
    /// Root configuration.
    config: Config,

    /// Platform abstraction.
    platform: Arc<P>,

    /// Message bus for inbound/outbound message routing.
    bus: Arc<MessageBus>,

    /// Session manager for conversation persistence.
    sessions: Arc<SessionManager<P>>,

    /// Tool registry with registered tools.
    tools: Arc<ToolRegistry>,

    /// Pipeline registry with all 6 stages wired.
    pipeline: PipelineRegistry,

    /// Context builder for assembling LLM prompts.
    context: ContextBuilder<P>,

    /// Shared memory store reference (for external access).
    memory: Arc<MemoryStore<P>>,

    /// Shared skills loader reference (for external access).
    skills: Arc<SkillsLoader<P>>,

    /// Optional auto-delegation router for pre-LLM routing.
    auto_delegation: Option<Arc<dyn AutoDelegation>>,
}

impl<P: Platform> AppContext<P> {
    /// Initialize all components from configuration and platform.
    ///
    /// This is the primary constructor. It:
    /// 1. Creates the [`MessageBus`]
    /// 2. Initializes the [`SessionManager`] (discovers/creates sessions dir)
    /// 3. Initializes the [`MemoryStore`] (discovers memory dir)
    /// 4. Initializes the [`SkillsLoader`] (discovers skills dir)
    /// 5. Creates the [`ContextBuilder`]
    /// 6. Creates an empty [`ToolRegistry`] (caller registers tools after)
    /// 7. Wires the default Level 0 pipeline (keyword classifier, static
    ///    router, token budget assembler, stub transport, noop scorer,
    ///    noop learner)
    ///
    /// # Errors
    ///
    /// Returns [`ClawftError`] if the home directory cannot be determined
    /// or the sessions directory cannot be created.
    pub async fn new(config: Config, platform: Arc<P>) -> clawft_types::Result<Self> {
        info!("bootstrapping application context");

        // 1. Message bus
        let bus = Arc::new(MessageBus::new());
        debug!("message bus created");

        // 2. Session manager
        let sessions = SessionManager::new(platform.clone()).await?;
        debug!("session manager initialized");

        // 3. Memory store
        let memory = Arc::new(MemoryStore::new(platform.clone())?);
        debug!(
            memory_path = %memory.memory_path().display(),
            "memory store initialized"
        );

        // 4. Skills loader
        let mut skills_loader = SkillsLoader::new(platform.clone())?;

        // Also scan extra `skills/` directories if they exist:
        // - workspace/skills/  (from config workspace path)
        // - ./skills/          (current working directory)
        for candidate in [
            config.workspace_path().join("skills"),
            std::env::current_dir().unwrap_or_default().join("skills"),
        ] {
            if candidate.is_dir() {
                skills_loader.add_extra_dir(candidate);
            }
        }

        let skills = Arc::new(skills_loader);
        debug!(
            skills_dir = %skills.skills_dir().display(),
            "skills loader initialized"
        );

        // 5. Context builder
        let context = ContextBuilder::new(
            config.agents.clone(),
            memory.clone(),
            skills.clone(),
            platform.clone(),
        );
        debug!("context builder created");

        // 6. Tool registry (empty -- caller adds tools)
        let tools = Arc::new(ToolRegistry::new());

        // 7. Default Level 0 pipeline
        let pipeline = build_default_pipeline(&config);
        debug!("default pipeline wired");

        info!("bootstrap complete");

        Ok(Self {
            config,
            platform,
            bus,
            sessions: Arc::new(sessions),
            tools,
            pipeline,
            context,
            memory,
            skills,
            auto_delegation: None,
        })
    }

    /// Consume the context and produce a running [`AgentLoop`].
    ///
    /// All dependencies are moved into the agent loop. After this call,
    /// the `AppContext` is consumed and cannot be reused.
    pub fn into_agent_loop(self) -> AgentLoop<P> {
        let resolver = crate::pipeline::permissions::PermissionResolver::new(
            &self.config.routing,
            None, // workspace config not yet supported
        );
        let mut agent = AgentLoop::new(
            self.config.agents,
            self.platform,
            self.bus,
            self.pipeline,
            self.tools.clone(),
            self.context,
            self.sessions.clone(),
            resolver,
        );
        if let Some(delegation) = self.auto_delegation {
            agent = agent.with_auto_delegation(delegation);
        }
        agent
    }

    /// Get a reference to the root configuration.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Get a reference to the platform.
    pub fn platform(&self) -> &Arc<P> {
        &self.platform
    }

    /// Get a reference to the message bus.
    ///
    /// Channel adapters should clone the inbound sender from here
    /// before the context is consumed by [`into_agent_loop`].
    pub fn bus(&self) -> &Arc<MessageBus> {
        &self.bus
    }

    /// Get a mutable reference to the tool registry.
    ///
    /// Call this to register tools before converting to an agent loop.
    ///
    /// # Panics
    ///
    /// Panics if Arc clones have already been taken (e.g. via `tools_arc()`).
    /// Always call `tools_mut()` for registration *before* sharing the registry.
    pub fn tools_mut(&mut self) -> &mut ToolRegistry {
        Arc::get_mut(&mut self.tools).expect("tools already shared -- register tools before cloning Arc")
    }

    /// Get a reference to the tool registry.
    pub fn tools(&self) -> &Arc<ToolRegistry> {
        &self.tools
    }

    /// Get a clone of the `Arc<ToolRegistry>` for sharing with other components.
    pub fn tools_arc(&self) -> Arc<ToolRegistry> {
        self.tools.clone()
    }

    /// Get a reference to the session manager.
    pub fn sessions(&self) -> &Arc<SessionManager<P>> {
        &self.sessions
    }

    /// Get a reference to the shared memory store.
    pub fn memory(&self) -> &Arc<MemoryStore<P>> {
        &self.memory
    }

    /// Get a reference to the shared skills loader.
    pub fn skills(&self) -> &Arc<SkillsLoader<P>> {
        &self.skills
    }

    /// Set an auto-delegation router for pre-LLM routing.
    ///
    /// When set, inbound messages are checked against delegation rules
    /// before the local LLM is invoked. Matching messages are routed
    /// directly to `delegate_task`.
    pub fn set_auto_delegation(&mut self, delegation: Arc<dyn AutoDelegation>) {
        self.auto_delegation = Some(delegation);
    }

    /// Replace the pipeline registry with a custom one.
    ///
    /// Use this to inject a transport backed by a real LLM provider
    /// or to register specialized pipelines for specific task types.
    pub fn set_pipeline(&mut self, pipeline: PipelineRegistry) {
        self.pipeline = pipeline;
    }

    /// Replace the pipeline with a live LLM-backed pipeline.
    ///
    /// Convenience method that calls [`build_live_pipeline`] and sets it
    /// as the active pipeline, enabling real LLM calls through the
    /// `clawft-llm` provider resolved from configuration.
    ///
    /// Only available with the `native` feature.
    #[cfg(feature = "native")]
    pub fn enable_live_llm(&mut self) {
        let pipeline = build_live_pipeline(&self.config);
        self.set_pipeline(pipeline);
    }
}

/// Build a live pipeline with a real LLM provider from configuration.
///
/// Uses [`ClawftLlmAdapter`](crate::pipeline::llm_adapter::ClawftLlmAdapter)
/// to bridge `clawft-llm` providers into the pipeline's transport layer,
/// enabling real LLM calls.
///
/// This is the production counterpart of [`build_default_pipeline`], which
/// uses a stub transport. All other pipeline stages are identical.
///
/// Only available with the `native` feature (requires clawft-llm HTTP providers).
#[cfg(feature = "native")]
pub fn build_live_pipeline(config: &Config) -> PipelineRegistry {
    crate::pipeline::llm_adapter::build_live_pipeline(config)
}

/// Build the default pipeline from configuration.
///
/// Uses the appropriate router based on `config.routing.mode`:
/// - `"tiered"` -> [`TieredRouter`] with cost tracking and rate limiting
/// - `"static"` (default) -> [`StaticRouter`] from config defaults
///
/// Other stages: [`KeywordClassifier`], [`TokenBudgetAssembler`],
/// [`OpenAiCompatTransport`] (stub), [`NoopScorer`], [`NoopLearner`].
fn build_default_pipeline(config: &Config) -> PipelineRegistry {
    let classifier = Arc::new(KeywordClassifier::new());
    let router: Arc<dyn ModelRouter> = build_router_from_config(config);
    let assembler = Arc::new(TokenBudgetAssembler::new(
        config.agents.defaults.max_tokens.max(1) as usize,
    ));
    let transport = Arc::new(OpenAiCompatTransport::new());
    let scorer = crate::pipeline::build_scorer(&config.pipeline);
    let learner = crate::pipeline::build_learner(&config.pipeline);

    let pipeline = Pipeline {
        classifier,
        router,
        assembler,
        transport,
        scorer,
        learner,
    };

    PipelineRegistry::new(pipeline)
}

/// Build the appropriate router based on `config.routing.mode`.
fn build_router_from_config(config: &Config) -> Arc<dyn ModelRouter> {
    if config.routing.mode == "tiered" {
        let routing = config.routing.clone();
        let cost_tracker = Arc::new(
            CostTracker::new(routing.cost_budgets.reset_hour_utc),
        );
        let rate_limiter = Arc::new(
            RateLimiter::new(routing.rate_limiting.window_seconds, routing.rate_limiting.global_rate_limit_rpm),
        );
        Arc::new(
            TieredRouter::new(routing)
                .with_cost_tracker(cost_tracker)
                .with_rate_limiter(rate_limiter),
        )
    } else {
        Arc::new(StaticRouter::from_config(&config.agents))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clawft_platform::NativePlatform;
    use clawft_types::config::{AgentDefaults, AgentsConfig};
    use std::sync::Arc;

    fn test_config() -> Config {
        Config {
            agents: AgentsConfig {
                defaults: AgentDefaults {
                    workspace: "~/.clawft/workspace".into(),
                    model: "deepseek/deepseek-chat".into(),
                    max_tokens: 4096,
                    temperature: 0.7,
                    max_tool_iterations: 10,
                    memory_window: 50,
                },
            },
            ..Config::default()
        }
    }

    #[tokio::test]
    async fn new_creates_app_context() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await;
        assert!(ctx.is_ok());
    }

    #[tokio::test]
    async fn config_accessor() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        assert_eq!(
            ctx.config().agents.defaults.model,
            "deepseek/deepseek-chat"
        );
        assert_eq!(ctx.config().agents.defaults.max_tokens, 4096);
    }

    #[tokio::test]
    async fn platform_accessor() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        let _p = ctx.platform();
    }

    #[tokio::test]
    async fn bus_accessor() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        let bus = ctx.bus();
        // Should be able to get an inbound sender
        let _tx = bus.inbound_sender();
    }

    #[tokio::test]
    async fn tools_starts_empty() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        assert!(ctx.tools().is_empty());
    }

    #[tokio::test]
    async fn tools_mut_allows_registration() {
        let platform = Arc::new(NativePlatform::new());
        let mut ctx = AppContext::new(test_config(), platform).await.unwrap();

        use crate::tools::registry::Tool;
        use async_trait::async_trait;

        struct DummyTool;

        #[async_trait]
        impl Tool for DummyTool {
            fn name(&self) -> &str {
                "dummy"
            }
            fn description(&self) -> &str {
                "A dummy tool"
            }
            fn parameters(&self) -> serde_json::Value {
                serde_json::json!({"type": "object", "properties": {}})
            }
            async fn execute(
                &self,
                _args: serde_json::Value,
            ) -> Result<serde_json::Value, crate::tools::registry::ToolError> {
                Ok(serde_json::json!({}))
            }
        }

        ctx.tools_mut().register(Arc::new(DummyTool));
        assert_eq!(ctx.tools().len(), 1);
        assert_eq!(ctx.tools().list(), vec!["dummy"]);
    }

    #[tokio::test]
    async fn memory_accessor() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        let memory = ctx.memory();
        assert!(memory.memory_path().is_absolute());
    }

    #[tokio::test]
    async fn skills_accessor() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        let skills = ctx.skills();
        assert!(skills.skills_dir().is_absolute());
    }

    #[tokio::test]
    async fn into_agent_loop_produces_valid_loop() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();
        let agent = ctx.into_agent_loop();
        assert_eq!(agent.config().defaults.model, "deepseek/deepseek-chat");
        assert_eq!(agent.config().defaults.max_tokens, 4096);
    }

    #[tokio::test]
    async fn set_pipeline_replaces_default() {
        let platform = Arc::new(NativePlatform::new());
        let mut ctx = AppContext::new(test_config(), platform).await.unwrap();

        // Build a custom pipeline with a different router
        let custom_pipeline = build_default_pipeline(&test_config());
        ctx.set_pipeline(custom_pipeline);

        // Should still produce a valid agent loop
        let agent = ctx.into_agent_loop();
        assert_eq!(agent.config().defaults.model, "deepseek/deepseek-chat");
    }

    #[tokio::test]
    async fn default_config_bootstrap() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(Config::default(), platform).await;
        assert!(ctx.is_ok());
    }

    #[test]
    fn build_default_pipeline_creates_registry() {
        let config = test_config();
        let _registry = build_default_pipeline(&config);
        // Should not panic.
    }

    #[test]
    fn build_default_pipeline_with_defaults() {
        let config = Config::default();
        let _registry = build_default_pipeline(&config);
    }

    #[tokio::test]
    async fn bus_clone_survives_into_agent_loop() {
        let platform = Arc::new(NativePlatform::new());
        let ctx = AppContext::new(test_config(), platform).await.unwrap();

        // Clone the bus sender before consuming the context
        let tx = ctx.bus().inbound_sender();
        let _agent = ctx.into_agent_loop();

        // The sender should still be usable
        use chrono::Utc;
        use clawft_types::event::InboundMessage;
        use std::collections::HashMap;

        let msg = InboundMessage {
            channel: "test".into(),
            sender_id: "user1".into(),
            chat_id: "chat1".into(),
            content: "hello".into(),
            timestamp: Utc::now(),
            media: vec![],
            metadata: HashMap::new(),
        };
        assert!(tx.send(msg).await.is_ok());
    }

    #[tokio::test]
    async fn app_context_is_send() {
        fn assert_send<T: Send>() {}
        assert_send::<AppContext<NativePlatform>>();
    }

    // ── Integration: build_live_pipeline transport is configured ─────

    #[tokio::test]
    async fn build_live_pipeline_transport_is_configured() {
        use crate::pipeline::traits::{LlmMessage, TaskType, TransportRequest};

        // The live pipeline should have a configured (non-stub) transport.
        // When we call complete() on the stub transport, it returns an error
        // containing "transport not configured". The live pipeline should
        // NOT produce that error -- it should attempt a real HTTP call
        // (which will fail differently without an API key).
        let config = test_config();
        let registry = build_live_pipeline(&config);

        // Access the default pipeline's transport via get() with an unregistered type.
        let pipeline = registry.get(&TaskType::Unknown);

        let transport_req = TransportRequest {
            provider: "anthropic".into(),
            model: "claude-opus-4-5".into(),
            messages: vec![LlmMessage {
                role: "user".into(),
                content: "test".into(),
                tool_call_id: None,
                tool_calls: None,
            }],
            tools: vec![],
            max_tokens: Some(10),
            temperature: Some(0.0),
        };

        let result = pipeline.transport.complete(&transport_req).await;

        // The live transport IS configured (has a provider), so it should
        // NOT fail with "transport not configured". It will fail with an
        // HTTP/auth error instead because there's no real API key.
        match result {
            Ok(_) => {} // unlikely without API key, but acceptable
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    !msg.contains("transport not configured"),
                    "live pipeline should not use stub transport, but got: {msg}"
                );
            }
        }
    }

    // ── Integration: enable_live_llm replaces the pipeline ──────────

    #[tokio::test]
    async fn app_context_enable_live_llm() {
        let platform = Arc::new(NativePlatform::new());
        let mut ctx = AppContext::new(test_config(), platform).await.unwrap();

        // Before enable_live_llm, the default pipeline uses a stub transport.
        // We cannot directly access ctx.pipeline, but we can verify behavior
        // indirectly: enable_live_llm should not panic and should replace
        // the pipeline such that transport errors no longer say "not configured".

        ctx.enable_live_llm();

        // Convert to agent loop and verify it's still valid.
        let agent = ctx.into_agent_loop();
        assert_eq!(agent.config().defaults.model, "deepseek/deepseek-chat");
    }

    // ── Integration: default pipeline uses stub (negative test) ─────

    #[tokio::test]
    async fn default_pipeline_transport_is_stub() {
        // Verify the default pipeline's transport IS the stub, confirming
        // that enable_live_llm / build_live_pipeline changes something.
        use crate::pipeline::traits::{LlmMessage, TaskType, TransportRequest};

        let config = test_config();
        let registry = build_default_pipeline(&config);
        let pipeline = registry.get(&TaskType::Unknown);

        let transport_req = TransportRequest {
            provider: "test".into(),
            model: "test".into(),
            messages: vec![LlmMessage {
                role: "user".into(),
                content: "hello".into(),
                tool_call_id: None,
                tool_calls: None,
            }],
            tools: vec![],
            max_tokens: None,
            temperature: None,
        };

        let result = pipeline.transport.complete(&transport_req).await;
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("transport not configured"),
            "default pipeline should use stub transport, got: {err_msg}"
        );
    }

    // ── Integration: build_live_pipeline creates a valid registry ────

    #[test]
    fn build_live_pipeline_creates_registry() {
        let config = test_config();
        let registry = build_live_pipeline(&config);
        // Registry should be usable for any task type (falls back to default).
        use crate::pipeline::traits::TaskType;
        let _pipeline = registry.get(&TaskType::Chat);
        let _pipeline = registry.get(&TaskType::CodeGeneration);
        let _pipeline = registry.get(&TaskType::Unknown);
    }
}