zeroclawlabs 0.6.9

Zero overhead. Zero compromise. 100% Rust. The fastest, smallest AI assistant.
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
//! Emoji reaction tool for cross-channel message reactions.
//!
//! Exposes `add_reaction` and `remove_reaction` from the [`Channel`] trait as an
//! agent-callable tool. The tool holds a late-binding channel map handle that is
//! populated once channels are initialized (after tool construction). This mirrors
//! the pattern used by [`DelegateTool`] for its parent-tools handle.

use super::traits::{Tool, ToolResult};
use crate::channels::traits::Channel;
use crate::security::SecurityPolicy;
use crate::security::policy::ToolOperation;
use async_trait::async_trait;
use parking_lot::RwLock;
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;

/// Shared handle to the channel map. Starts empty; populated once channels boot.
pub type ChannelMapHandle = Arc<RwLock<HashMap<String, Arc<dyn Channel>>>>;

/// Agent-callable tool for adding or removing emoji reactions on messages.
pub struct ReactionTool {
    channels: ChannelMapHandle,
    security: Arc<SecurityPolicy>,
}

impl ReactionTool {
    /// Create a new reaction tool with an empty channel map.
    /// Call [`populate`] or write to the returned [`ChannelMapHandle`] once channels
    /// are available.
    pub fn new(security: Arc<SecurityPolicy>) -> Self {
        Self {
            channels: Arc::new(RwLock::new(HashMap::new())),
            security,
        }
    }

    /// Return the shared handle so callers can populate it after channel init.
    pub fn channel_map_handle(&self) -> ChannelMapHandle {
        Arc::clone(&self.channels)
    }

    /// Convenience: populate the channel map from a pre-built map.
    pub fn populate(&self, map: HashMap<String, Arc<dyn Channel>>) {
        *self.channels.write() = map;
    }
}

#[async_trait]
impl Tool for ReactionTool {
    fn name(&self) -> &str {
        "reaction"
    }

    fn description(&self) -> &str {
        "Add or remove an emoji reaction on a message in any active channel. \
         Provide the channel name (e.g. 'discord', 'slack'), the platform channel ID, \
         the platform message ID, and the emoji (Unicode character or platform shortcode)."
    }

    fn parameters_schema(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "channel": {
                    "type": "string",
                    "description": "Name of the channel to react in (e.g. 'discord', 'slack', 'telegram')"
                },
                "channel_id": {
                    "type": "string",
                    "description": "Platform-specific channel/conversation identifier (e.g. Discord channel snowflake, Slack channel ID)"
                },
                "message_id": {
                    "type": "string",
                    "description": "Platform-scoped message identifier to react to"
                },
                "emoji": {
                    "type": "string",
                    "description": "Emoji to react with (Unicode character or platform shortcode)"
                },
                "action": {
                    "type": "string",
                    "enum": ["add", "remove"],
                    "description": "Whether to add or remove the reaction (default: 'add')"
                }
            },
            "required": ["channel", "channel_id", "message_id", "emoji"]
        })
    }

    async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
        // Security gate
        if let Err(error) = self
            .security
            .enforce_tool_operation(ToolOperation::Act, "reaction")
        {
            return Ok(ToolResult {
                success: false,
                output: String::new(),
                error: Some(error),
            });
        }

        let channel_name = args
            .get("channel")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'channel' parameter"))?;

        let channel_id = args
            .get("channel_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'channel_id' parameter"))?;

        let message_id = args
            .get("message_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'message_id' parameter"))?;

        let emoji = args
            .get("emoji")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("Missing 'emoji' parameter"))?;

        let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("add");

        if action != "add" && action != "remove" {
            return Ok(ToolResult {
                success: false,
                output: String::new(),
                error: Some(format!(
                    "Invalid action '{action}': must be 'add' or 'remove'"
                )),
            });
        }

        // Read-lock the channel map to find the target channel.
        let channel = {
            let map = self.channels.read();
            if map.is_empty() {
                return Ok(ToolResult {
                    success: false,
                    output: String::new(),
                    error: Some("No channels available yet (channels not initialized)".to_string()),
                });
            }
            match map.get(channel_name) {
                Some(ch) => Arc::clone(ch),
                None => {
                    let available: Vec<String> = map.keys().cloned().collect();
                    return Ok(ToolResult {
                        success: false,
                        output: String::new(),
                        error: Some(format!(
                            "Channel '{channel_name}' not found. Available channels: {}",
                            available.join(", ")
                        )),
                    });
                }
            }
        };

        let result = if action == "add" {
            channel.add_reaction(channel_id, message_id, emoji).await
        } else {
            channel.remove_reaction(channel_id, message_id, emoji).await
        };

        let past_tense = if action == "remove" {
            "removed"
        } else {
            "added"
        };

        match result {
            Ok(()) => Ok(ToolResult {
                success: true,
                output: format!(
                    "Reaction {past_tense}: {emoji} on message {message_id} in {channel_name}"
                ),
                error: None,
            }),
            Err(e) => Ok(ToolResult {
                success: false,
                output: String::new(),
                error: Some(format!("Failed to {action} reaction: {e}")),
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::channels::traits::{ChannelMessage, SendMessage};
    use std::sync::atomic::{AtomicBool, Ordering};

    struct MockChannel {
        reaction_added: AtomicBool,
        reaction_removed: AtomicBool,
        last_channel_id: parking_lot::Mutex<Option<String>>,
        fail_on_add: bool,
    }

    impl MockChannel {
        fn new() -> Self {
            Self {
                reaction_added: AtomicBool::new(false),
                reaction_removed: AtomicBool::new(false),
                last_channel_id: parking_lot::Mutex::new(None),
                fail_on_add: false,
            }
        }

        fn failing() -> Self {
            Self {
                reaction_added: AtomicBool::new(false),
                reaction_removed: AtomicBool::new(false),
                last_channel_id: parking_lot::Mutex::new(None),
                fail_on_add: true,
            }
        }
    }

    #[async_trait]
    impl Channel for MockChannel {
        fn name(&self) -> &str {
            "mock"
        }

        async fn send(&self, _message: &SendMessage) -> anyhow::Result<()> {
            Ok(())
        }

        async fn listen(
            &self,
            _tx: tokio::sync::mpsc::Sender<ChannelMessage>,
        ) -> anyhow::Result<()> {
            Ok(())
        }

        async fn add_reaction(
            &self,
            channel_id: &str,
            _message_id: &str,
            _emoji: &str,
        ) -> anyhow::Result<()> {
            if self.fail_on_add {
                return Err(anyhow::anyhow!("API error: rate limited"));
            }
            *self.last_channel_id.lock() = Some(channel_id.to_string());
            self.reaction_added.store(true, Ordering::SeqCst);
            Ok(())
        }

        async fn remove_reaction(
            &self,
            channel_id: &str,
            _message_id: &str,
            _emoji: &str,
        ) -> anyhow::Result<()> {
            *self.last_channel_id.lock() = Some(channel_id.to_string());
            self.reaction_removed.store(true, Ordering::SeqCst);
            Ok(())
        }
    }

    fn make_tool_with_channels(channels: Vec<(&str, Arc<dyn Channel>)>) -> ReactionTool {
        let tool = ReactionTool::new(Arc::new(SecurityPolicy::default()));
        let map: HashMap<String, Arc<dyn Channel>> = channels
            .into_iter()
            .map(|(name, ch)| (name.to_string(), ch))
            .collect();
        tool.populate(map);
        tool
    }

    #[test]
    fn tool_metadata() {
        let tool = ReactionTool::new(Arc::new(SecurityPolicy::default()));
        assert_eq!(tool.name(), "reaction");
        assert!(!tool.description().is_empty());
        let schema = tool.parameters_schema();
        assert_eq!(schema["type"], "object");
        assert!(schema["properties"]["channel"].is_object());
        assert!(schema["properties"]["channel_id"].is_object());
        assert!(schema["properties"]["message_id"].is_object());
        assert!(schema["properties"]["emoji"].is_object());
        assert!(schema["properties"]["action"].is_object());
        let required = schema["required"].as_array().unwrap();
        assert!(required.iter().any(|v| v == "channel"));
        assert!(required.iter().any(|v| v == "channel_id"));
        assert!(required.iter().any(|v| v == "message_id"));
        assert!(required.iter().any(|v| v == "emoji"));
        // action is optional (defaults to "add")
        assert!(!required.iter().any(|v| v == "action"));
    }

    #[tokio::test]
    async fn add_reaction_success() {
        let mock: Arc<dyn Channel> = Arc::new(MockChannel::new());
        let tool = make_tool_with_channels(vec![("discord", Arc::clone(&mock))]);

        let result = tool
            .execute(json!({
                "channel": "discord",
                "channel_id": "ch_001",
                "message_id": "msg_123",
                "emoji": "\u{2705}"
            }))
            .await
            .unwrap();

        assert!(result.success);
        assert!(result.output.contains("added"));
        assert!(result.error.is_none());
    }

    #[tokio::test]
    async fn remove_reaction_success() {
        let mock: Arc<dyn Channel> = Arc::new(MockChannel::new());
        let tool = make_tool_with_channels(vec![("slack", Arc::clone(&mock))]);

        let result = tool
            .execute(json!({
                "channel": "slack",
                "channel_id": "C0123SLACK",
                "message_id": "msg_456",
                "emoji": "\u{1F440}",
                "action": "remove"
            }))
            .await
            .unwrap();

        assert!(result.success);
        assert!(result.output.contains("removed"));
    }

    #[tokio::test]
    async fn unknown_channel_returns_error() {
        let tool = make_tool_with_channels(vec![(
            "discord",
            Arc::new(MockChannel::new()) as Arc<dyn Channel>,
        )]);

        let result = tool
            .execute(json!({
                "channel": "nonexistent",
                "channel_id": "ch_x",
                "message_id": "msg_1",
                "emoji": "\u{2705}"
            }))
            .await
            .unwrap();

        assert!(!result.success);
        let err = result.error.as_deref().unwrap();
        assert!(err.contains("not found"));
        assert!(err.contains("discord"));
    }

    #[tokio::test]
    async fn invalid_action_returns_error() {
        let tool = make_tool_with_channels(vec![(
            "discord",
            Arc::new(MockChannel::new()) as Arc<dyn Channel>,
        )]);

        let result = tool
            .execute(json!({
                "channel": "discord",
                "channel_id": "ch_001",
                "message_id": "msg_1",
                "emoji": "\u{2705}",
                "action": "toggle"
            }))
            .await
            .unwrap();

        assert!(!result.success);
        assert!(result.error.as_deref().unwrap().contains("toggle"));
    }

    #[tokio::test]
    async fn channel_error_propagated() {
        let mock: Arc<dyn Channel> = Arc::new(MockChannel::failing());
        let tool = make_tool_with_channels(vec![("discord", mock)]);

        let result = tool
            .execute(json!({
                "channel": "discord",
                "channel_id": "ch_001",
                "message_id": "msg_1",
                "emoji": "\u{2705}"
            }))
            .await
            .unwrap();

        assert!(!result.success);
        assert!(result.error.as_deref().unwrap().contains("rate limited"));
    }

    #[tokio::test]
    async fn missing_required_params() {
        let tool = make_tool_with_channels(vec![(
            "test",
            Arc::new(MockChannel::new()) as Arc<dyn Channel>,
        )]);

        // Missing channel
        let result = tool
            .execute(json!({"channel_id": "c1", "message_id": "1", "emoji": "x"}))
            .await;
        assert!(result.is_err());

        // Missing channel_id
        let result = tool
            .execute(json!({"channel": "test", "message_id": "1", "emoji": "x"}))
            .await;
        assert!(result.is_err());

        // Missing message_id
        let result = tool
            .execute(json!({"channel": "a", "channel_id": "c1", "emoji": "x"}))
            .await;
        assert!(result.is_err());

        // Missing emoji
        let result = tool
            .execute(json!({"channel": "a", "channel_id": "c1", "message_id": "1"}))
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn empty_channels_returns_not_initialized() {
        let tool = ReactionTool::new(Arc::new(SecurityPolicy::default()));
        // No channels populated

        let result = tool
            .execute(json!({
                "channel": "discord",
                "channel_id": "ch_001",
                "message_id": "msg_1",
                "emoji": "\u{2705}"
            }))
            .await
            .unwrap();

        assert!(!result.success);
        assert!(result.error.as_deref().unwrap().contains("not initialized"));
    }

    #[tokio::test]
    async fn default_action_is_add() {
        let mock = Arc::new(MockChannel::new());
        let mock_ch: Arc<dyn Channel> = Arc::clone(&mock) as Arc<dyn Channel>;
        let tool = make_tool_with_channels(vec![("test", mock_ch)]);

        let result = tool
            .execute(json!({
                "channel": "test",
                "channel_id": "ch_test",
                "message_id": "msg_1",
                "emoji": "\u{2705}"
            }))
            .await
            .unwrap();

        assert!(result.success);
        assert!(mock.reaction_added.load(Ordering::SeqCst));
        assert!(!mock.reaction_removed.load(Ordering::SeqCst));
    }

    #[tokio::test]
    async fn channel_id_passed_to_trait_not_channel_name() {
        let mock = Arc::new(MockChannel::new());
        let mock_ch: Arc<dyn Channel> = Arc::clone(&mock) as Arc<dyn Channel>;
        let tool = make_tool_with_channels(vec![("discord", mock_ch)]);

        let result = tool
            .execute(json!({
                "channel": "discord",
                "channel_id": "123456789",
                "message_id": "msg_1",
                "emoji": "\u{2705}"
            }))
            .await
            .unwrap();

        assert!(result.success);
        // The trait must receive the platform channel_id, not the channel name
        assert_eq!(
            mock.last_channel_id.lock().as_deref(),
            Some("123456789"),
            "add_reaction must receive channel_id, not channel name"
        );
    }

    #[tokio::test]
    async fn channel_map_handle_allows_late_binding() {
        let tool = ReactionTool::new(Arc::new(SecurityPolicy::default()));
        let handle = tool.channel_map_handle();

        // Initially empty — tool reports not initialized
        let result = tool
            .execute(json!({
                "channel": "slack",
                "channel_id": "C0123",
                "message_id": "msg_1",
                "emoji": "\u{2705}"
            }))
            .await
            .unwrap();
        assert!(!result.success);

        // Populate via the handle
        {
            let mut map = handle.write();
            map.insert(
                "slack".to_string(),
                Arc::new(MockChannel::new()) as Arc<dyn Channel>,
            );
        }

        // Now the tool can route to the channel
        let result = tool
            .execute(json!({
                "channel": "slack",
                "channel_id": "C0123",
                "message_id": "msg_1",
                "emoji": "\u{2705}"
            }))
            .await
            .unwrap();
        assert!(result.success);
    }

    #[test]
    fn spec_matches_metadata() {
        let tool = ReactionTool::new(Arc::new(SecurityPolicy::default()));
        let spec = tool.spec();
        assert_eq!(spec.name, "reaction");
        assert_eq!(spec.description, tool.description());
        assert!(spec.parameters["required"].is_array());
    }
}