eli 0.3.2

Ease Lives Instantly — hook-first AI agent framework with multi-channel support
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
//! Builtin module — default hook implementations and runtime components.

pub mod agent;
pub mod cli;
pub mod config;
mod model_specs;
pub mod settings;
pub mod shell_manager;
pub mod store;
pub mod tape;
pub mod tape_viewer;
pub mod tools;

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use async_trait::async_trait;
use chrono::Utc;
use nexil::ConduitError;
use serde_json::Value;
use tokio::sync::Mutex;

use crate::builtin::agent::Agent;
use crate::builtin::store::FileTapeStore;
use crate::channels::message::{ChannelMessage, MessageKind};
use crate::hooks::{EliHookSpec, TapeStoreKind};
use crate::smart_router::{RouteDecision, SmartRouter};
use crate::tool_middleware::MiddlewareChain;
use crate::types::{Envelope, PromptValue, State};

pub(crate) const CLEANUP_ONLY_CONTEXT_KEY: &str = "_eli_cleanup_only";

// ---------------------------------------------------------------------------
// BuiltinImpl — default hook implementations
// ---------------------------------------------------------------------------

/// Default hook implementations for basic runtime operations.
pub struct BuiltinImpl {
    agents: std::sync::RwLock<HashMap<String, Arc<Mutex<Agent>>>>,
    home: PathBuf,
    router: SmartRouter,
    middleware_chain: MiddlewareChain,
}

#[allow(clippy::new_without_default)]
impl BuiltinImpl {
    /// Create a new `BuiltinImpl`, registering builtin tools.
    pub fn new() -> Self {
        tools::register_builtin_tools();
        let home = settings::AgentSettings::from_env().home;
        Self {
            agents: std::sync::RwLock::new(HashMap::new()),
            home,
            router: SmartRouter::new(),
            middleware_chain: MiddlewareChain::with_defaults(),
        }
    }

    /// Get or create a per-session Agent, enabling concurrent model execution across sessions.
    fn get_or_create_agent(&self, session_id: &str) -> Arc<Mutex<Agent>> {
        {
            let agents = self.agents.read().unwrap_or_else(|e| e.into_inner());
            if let Some(agent) = agents.get(session_id) {
                return Arc::clone(agent);
            }
        }
        let mut agents = self.agents.write().unwrap_or_else(|e| e.into_inner());
        agents
            .entry(session_id.to_owned())
            .or_insert_with(|| Arc::new(Mutex::new(Agent::new())))
            .clone()
    }

    /// Resolve a session ID from a channel message.
    pub fn resolve_session(&self, message: &ChannelMessage) -> String {
        if !message.session_id.trim().is_empty() {
            return message.session_id.clone();
        }
        let channel = &message.channel;
        let chat_id = &message.chat_id;
        format!("{channel}:{chat_id}")
    }

    /// Load initial state for a session.
    pub fn load_state(&self, session_id: &str) -> HashMap<String, Value> {
        let mut state: HashMap<String, Value> = HashMap::new();
        state.insert(
            "session_id".to_owned(),
            Value::String(session_id.to_owned()),
        );
        let workspace = std::env::current_dir()
            .unwrap_or_default()
            .display()
            .to_string();
        state.insert("_runtime_workspace".to_owned(), Value::String(workspace));
        state
    }

    /// Build a prompt from an inbound message.
    pub fn build_prompt(&self, message: &ChannelMessage) -> PromptValue {
        let content = extract_message_text(&message.content);
        if content.starts_with('/') {
            return PromptValue::Text(content);
        }
        let now = Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
        let context_str = message.context_str();
        let text = if context_str.is_empty() {
            content
        } else {
            format!("{context_str}\n---Date: {now}---\n{content}")
        };
        PromptValue::Text(text)
    }

    /// Run the model on a prompt within a session.
    pub async fn run_model(
        &self,
        prompt: PromptValue,
        session_id: &str,
        state: &HashMap<String, Value>,
    ) -> Result<String, ConduitError> {
        let agent = self.get_or_create_agent(session_id);
        agent
            .lock()
            .await
            .run(session_id, prompt, state, None, None, None)
            .await
    }

    /// Provide the tape store (FileTapeStore backed by the agent's home directory).
    pub fn provide_tape_store(&self) -> FileTapeStore {
        FileTapeStore::new(self.home.join("tapes"))
    }

    /// Handle errors by logging them.
    pub async fn on_error(&self, stage: &str, error: &str, message: Option<&ChannelMessage>) {
        tracing::error!(stage = stage, error = error, "pipeline error");
        if let Some(msg) = message {
            tracing::error!(
                session_id = %msg.session_id,
                channel = %msg.channel,
                "error occurred in session"
            );
        }
    }

    /// Render outbound messages from model output.
    pub fn render_outbound(
        &self,
        message: &ChannelMessage,
        session_id: &str,
        model_output: &str,
    ) -> Vec<ChannelMessage> {
        let output_channel = if message.output_channel.is_empty() {
            message.channel.as_str()
        } else {
            message.output_channel.as_str()
        };
        let clean = crate::builtin::cli::strip_fake_tool_calls(model_output);
        if clean.trim().is_empty() {
            tracing::info!(
                target: "eli_trace",
                session_id = %session_id,
                raw_model_output = ?model_output,
                "builtin.render_outbound.empty_after_cleanup"
            );
            let mut extra = message.context.clone();
            extra.insert(CLEANUP_ONLY_CONTEXT_KEY.to_owned(), Value::Bool(true));
            let outbound = ChannelMessage::new(session_id, &message.channel, "")
                .with_chat_id(&message.chat_id)
                .with_output_channel(output_channel)
                .with_kind(message.kind)
                .with_context(extra)
                .finalize();
            return vec![outbound];
        }

        let outbound = ChannelMessage::new(session_id, &message.channel, clean)
            .with_chat_id(&message.chat_id)
            .with_output_channel(output_channel)
            .with_kind(message.kind)
            .with_context(message.context.clone())
            .finalize();
        vec![outbound]
    }
}

fn extract_message_text(content: &str) -> String {
    match serde_json::from_str::<Value>(content) {
        Ok(val) => val
            .get("message")
            .and_then(|v| v.as_str())
            .unwrap_or(content)
            .to_owned(),
        Err(_) => content.to_owned(),
    }
}

fn envelope_to_channel_message(message: &Envelope) -> ChannelMessage {
    let channel = message
        .get("channel")
        .and_then(|v| v.as_str())
        .unwrap_or("cli")
        .to_owned();

    let kind = match message
        .get("kind")
        .and_then(|v| v.as_str())
        .unwrap_or("normal")
    {
        "error" => MessageKind::Error,
        "command" => MessageKind::Command,
        _ => MessageKind::Normal,
    };

    ChannelMessage {
        session_id: message
            .get("session_id")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_owned(),
        channel: channel.clone(),
        content: match message.get("content") {
            Some(Value::String(s)) => s.clone(),
            Some(other) => other.to_string(),
            None => String::new(),
        },
        chat_id: message
            .get("chat_id")
            .and_then(|v| v.as_str())
            .unwrap_or("default")
            .to_owned(),
        is_active: message
            .get("is_active")
            .and_then(|v| v.as_bool())
            .unwrap_or(false),
        kind,
        context: message
            .get("context")
            .and_then(|v| v.as_object())
            .cloned()
            .unwrap_or_default(),
        media: Vec::new(),
        output_channel: message
            .get("output_channel")
            .and_then(|v| v.as_str())
            .unwrap_or(&channel)
            .to_owned(),
    }
}

#[async_trait]
impl EliHookSpec for BuiltinImpl {
    fn plugin_name(&self) -> &str {
        "builtin"
    }

    fn classify_inbound(&self, message: &Envelope) -> Option<RouteDecision> {
        let content = message
            .get("content")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        self.router.classify(content)
    }

    async fn resolve_session(
        &self,
        message: &Envelope,
    ) -> Result<Option<String>, crate::hooks::HookError> {
        Ok(Some(
            self.resolve_session(&envelope_to_channel_message(message)),
        ))
    }

    async fn load_state(
        &self,
        message: &Envelope,
        session_id: &str,
    ) -> Result<Option<State>, crate::hooks::HookError> {
        let mut state = self.load_state(session_id);
        for field in ["sender_id", "chat_id", "channel", "output_channel"] {
            if let Some(value) = message.get(field).cloned() {
                state.insert(field.to_owned(), value);
            }
        }
        Ok(Some(state))
    }

    async fn build_user_prompt(
        &self,
        message: &Envelope,
        _session_id: &str,
        _state: &State,
    ) -> Option<PromptValue> {
        let text_prompt = self.build_prompt(&envelope_to_channel_message(message));

        // If the envelope carries resolved image content blocks, return a
        // multimodal Parts prompt so the LLM receives them as vision input.
        if let Some(parts) = message.get("media_parts").and_then(|v| v.as_array())
            && !parts.is_empty()
        {
            let mut content =
                vec![serde_json::json!({"type": "text", "text": text_prompt.as_text()})];
            content.extend(parts.iter().cloned());
            return Some(PromptValue::Parts(content));
        }

        Some(text_prompt)
    }

    async fn run_model(
        &self,
        prompt: &PromptValue,
        session_id: &str,
        state: &State,
    ) -> Result<Option<String>, crate::hooks::HookError> {
        match self.run_model(prompt.clone(), session_id, state).await {
            Ok(output) => Ok(Some(output)),
            Err(e) => {
                tracing::error!(error = %e, session_id = %session_id, "run_model failed");
                Err(crate::hooks::HookError::Plugin {
                    plugin: self.plugin_name().to_owned(),
                    hook_point: "run_model",
                    source: e.into(),
                })
            }
        }
    }

    async fn render_outbound(
        &self,
        message: &Envelope,
        session_id: &str,
        _state: &State,
        model_output: &str,
    ) -> Option<Vec<Envelope>> {
        let outbounds = self.render_outbound(
            &envelope_to_channel_message(message),
            session_id,
            model_output,
        );
        Some(
            outbounds
                .into_iter()
                .filter_map(|message| serde_json::to_value(message).ok())
                .collect(),
        )
    }

    async fn on_error(&self, stage: &str, error: &anyhow::Error, message: Option<&Envelope>) {
        let channel_message = message.map(envelope_to_channel_message);
        self.on_error(stage, &error.to_string(), channel_message.as_ref())
            .await;
    }

    fn build_system_prompt(&self, prompt_text: &str, state: &State) -> Option<String> {
        Some(Agent::new().system_prompt(prompt_text, state, None))
    }

    fn wrap_tool(&self, tool: &nexil::Tool) -> nexil::ToolAction {
        let wrapped = self.middleware_chain.wrap_tools(std::slice::from_ref(tool));
        match wrapped.into_iter().next() {
            Some(t) => nexil::ToolAction::Replace(t),
            None => nexil::ToolAction::Remove,
        }
    }

    fn provide_tape_store(&self) -> Option<TapeStoreKind> {
        Some(TapeStoreKind::Sync(Arc::new(self.provide_tape_store())))
    }
}

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

    #[test]
    fn test_render_outbound_empty_emits_cleanup_only_message() {
        let builtin = BuiltinImpl::new();
        let mut extra = serde_json::Map::new();
        extra.insert(
            "source_channel".to_owned(),
            Value::String("feishu".to_owned()),
        );
        let message = ChannelMessage::new("feishu:default:user_1", "webhook", "hello")
            .with_chat_id("user_1")
            .with_context(extra)
            .finalize();

        let outbounds = builtin.render_outbound(&message, "feishu:default:user_1", "");

        assert_eq!(outbounds.len(), 1);
        assert!(outbounds[0].content.is_empty());
        assert_eq!(
            outbounds[0]
                .context
                .get(CLEANUP_ONLY_CONTEXT_KEY)
                .and_then(|v| v.as_bool()),
            Some(true)
        );
        assert_eq!(
            outbounds[0]
                .context
                .get("source_channel")
                .and_then(|v| v.as_str()),
            Some("feishu")
        );
    }

    #[test]
    fn test_get_or_create_agent_returns_same_instance_for_same_session() {
        let builtin = BuiltinImpl::new();
        let a1 = builtin.get_or_create_agent("session:1");
        let a2 = builtin.get_or_create_agent("session:1");
        assert!(Arc::ptr_eq(&a1, &a2), "same session must return same Arc");
    }

    #[test]
    fn test_get_or_create_agent_returns_different_instances_for_different_sessions() {
        let builtin = BuiltinImpl::new();
        let a1 = builtin.get_or_create_agent("session:1");
        let a2 = builtin.get_or_create_agent("session:2");
        assert!(
            !Arc::ptr_eq(&a1, &a2),
            "different sessions must return different Arcs"
        );
    }

    #[tokio::test]
    async fn test_concurrent_sessions_do_not_block_each_other() {
        let builtin = Arc::new(BuiltinImpl::new());

        // Lock session:1's agent
        let agent1 = builtin.get_or_create_agent("session:1");
        let guard = agent1.lock().await;

        // session:2 should still be lockable (not blocked by session:1)
        let agent2 = builtin.get_or_create_agent("session:2");
        let try_lock = agent2.try_lock();
        assert!(
            try_lock.is_ok(),
            "session:2 must not be blocked by session:1"
        );

        drop(guard);
    }

    #[tokio::test]
    async fn test_same_session_serializes() {
        let builtin = BuiltinImpl::new();

        let agent = builtin.get_or_create_agent("session:1");
        let _guard = agent.lock().await;

        // Same session should be locked
        let agent_again = builtin.get_or_create_agent("session:1");
        let try_lock = agent_again.try_lock();
        assert!(
            try_lock.is_err(),
            "same session must serialize (lock should be held)"
        );
    }

    #[test]
    fn test_get_or_create_agent_concurrent_creation() {
        use std::thread;

        let builtin = Arc::new(BuiltinImpl::new());
        let mut handles = vec![];

        // Spawn 10 threads all requesting the same session simultaneously
        for _ in 0..10 {
            let b = Arc::clone(&builtin);
            handles.push(thread::spawn(move || b.get_or_create_agent("shared")));
        }

        let agents: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();

        // All must point to the same Arc
        for agent in &agents[1..] {
            assert!(
                Arc::ptr_eq(&agents[0], agent),
                "concurrent creation must converge to single instance"
            );
        }
    }

    #[test]
    fn test_render_outbound_normal_propagates_inbound_context() {
        let builtin = BuiltinImpl::new();
        let mut extra = serde_json::Map::new();
        extra.insert(
            "source_channel".to_owned(),
            Value::String("feishu".to_owned()),
        );
        extra.insert("account_id".to_owned(), Value::String("default".to_owned()));
        extra.insert(
            "channel_target".to_owned(),
            Value::String("user:ou_abc".to_owned()),
        );
        let message = ChannelMessage::new("feishu:default:ou_abc", "webhook", "hello")
            .with_chat_id("ou_abc")
            .with_context(extra)
            .finalize();

        let outbounds = builtin.render_outbound(&message, "feishu:default:ou_abc", "reply text");

        assert_eq!(outbounds.len(), 1);
        assert_eq!(outbounds[0].content, "reply text");
        // Inbound context must be propagated so the sidecar can route
        // the outbound correctly and clean up typing indicators.
        assert_eq!(
            outbounds[0]
                .context
                .get("source_channel")
                .and_then(|v| v.as_str()),
            Some("feishu"),
            "normal outbound must carry source_channel from inbound context"
        );
        assert_eq!(
            outbounds[0]
                .context
                .get("account_id")
                .and_then(|v| v.as_str()),
            Some("default"),
        );
        assert_eq!(
            outbounds[0]
                .context
                .get("channel_target")
                .and_then(|v| v.as_str()),
            Some("user:ou_abc"),
        );
    }

    #[tokio::test]
    async fn test_build_user_prompt_with_media_parts() {
        let builtin = BuiltinImpl::new();
        let envelope = serde_json::json!({
            "session_id": "test",
            "channel": "telegram",
            "chat_id": "123",
            "content": "What is this image?",
            "context": {},
            "kind": "normal",
            "output_channel": "telegram",
            "media_parts": [
                {"type": "image_base64", "mime_type": "image/jpeg", "data": "AQID"}
            ]
        });

        let prompt = builtin
            .build_user_prompt(&envelope, "test", &HashMap::new())
            .await
            .unwrap();

        match prompt {
            PromptValue::Parts(parts) => {
                assert_eq!(parts.len(), 2);
                assert_eq!(parts[0]["type"], "text");
                assert!(
                    parts[0]["text"]
                        .as_str()
                        .unwrap()
                        .contains("What is this image?")
                );
                assert_eq!(parts[1]["type"], "image_base64");
                assert_eq!(parts[1]["data"], "AQID");
            }
            PromptValue::Text(_) => panic!("expected Parts, got Text"),
        }
    }

    #[tokio::test]
    async fn test_build_user_prompt_without_media_returns_text() {
        let builtin = BuiltinImpl::new();
        let envelope = serde_json::json!({
            "session_id": "test",
            "channel": "telegram",
            "chat_id": "123",
            "content": "hello",
            "context": {},
            "kind": "normal",
            "output_channel": "telegram",
        });

        let prompt = builtin
            .build_user_prompt(&envelope, "test", &HashMap::new())
            .await
            .unwrap();

        match prompt {
            PromptValue::Text(t) => assert!(t.contains("hello")),
            PromptValue::Parts(_) => panic!("expected Text, got Parts"),
        }
    }

    #[tokio::test]
    async fn test_build_user_prompt_empty_media_parts_returns_text() {
        let builtin = BuiltinImpl::new();
        let envelope = serde_json::json!({
            "session_id": "test",
            "channel": "telegram",
            "chat_id": "123",
            "content": "no images",
            "context": {},
            "kind": "normal",
            "output_channel": "telegram",
            "media_parts": []
        });

        let prompt = builtin
            .build_user_prompt(&envelope, "test", &HashMap::new())
            .await
            .unwrap();

        match prompt {
            PromptValue::Text(t) => assert!(t.contains("no images")),
            PromptValue::Parts(_) => panic!("expected Text when media_parts is empty"),
        }
    }

    #[tokio::test]
    async fn test_build_user_prompt_multiple_images() {
        let builtin = BuiltinImpl::new();
        let envelope = serde_json::json!({
            "session_id": "test",
            "channel": "telegram",
            "chat_id": "123",
            "content": "compare",
            "context": {},
            "kind": "normal",
            "output_channel": "telegram",
            "media_parts": [
                {"type": "image_base64", "mime_type": "image/png", "data": "A"},
                {"type": "image_base64", "mime_type": "image/jpeg", "data": "B"}
            ]
        });

        let prompt = builtin
            .build_user_prompt(&envelope, "test", &HashMap::new())
            .await
            .unwrap();

        match prompt {
            PromptValue::Parts(parts) => {
                assert_eq!(parts.len(), 3); // text + 2 images
                assert_eq!(parts[0]["type"], "text");
                assert_eq!(parts[1]["mime_type"], "image/png");
                assert_eq!(parts[2]["mime_type"], "image/jpeg");
            }
            PromptValue::Text(_) => panic!("expected Parts with multiple images"),
        }
    }

    #[tokio::test]
    async fn test_build_user_prompt_media_parts_null_returns_text() {
        let builtin = BuiltinImpl::new();
        let envelope = serde_json::json!({
            "session_id": "test",
            "channel": "telegram",
            "chat_id": "123",
            "content": "null media",
            "context": {},
            "kind": "normal",
            "output_channel": "telegram",
            "media_parts": null
        });

        let prompt = builtin
            .build_user_prompt(&envelope, "test", &HashMap::new())
            .await
            .unwrap();

        match prompt {
            PromptValue::Text(t) => assert!(t.contains("null media")),
            PromptValue::Parts(_) => panic!("expected Text when media_parts is null"),
        }
    }

    #[tokio::test]
    async fn test_build_user_prompt_parts_text_extraction() {
        let builtin = BuiltinImpl::new();
        let envelope = serde_json::json!({
            "session_id": "test",
            "channel": "telegram",
            "chat_id": "123",
            "content": "describe this",
            "context": {},
            "kind": "normal",
            "output_channel": "telegram",
            "media_parts": [
                {"type": "image_base64", "mime_type": "image/png", "data": "X"}
            ]
        });

        let prompt = builtin
            .build_user_prompt(&envelope, "test", &HashMap::new())
            .await
            .unwrap();

        // strict_text() should extract only the text part, ignoring image blocks.
        let text = prompt.strict_text();
        assert!(text.contains("describe this"));
        assert!(!text.contains("image_base64"));
        assert!(!text.contains("image/png"));
    }
}