nika 0.35.4

Semantic YAML workflow engine for AI tasks - DAG execution, MCP integration, multi-provider LLM 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
//! BuiltinToolRouter for nika:* tool dispatch.
//!
//! Provides routing for 12 builtin tools:
//!
//! **Core tools (7):**
//! - `nika:sleep` - Pause execution for duration
//! - `nika:log` - Emit log event at level
//! - `nika:emit` - Emit custom event to EventLog
//! - `nika:assert` - Validate condition, fail if false
//! - `nika:prompt` - HITL - request user input
//! - `nika:run` - Execute nested workflow
//! - `nika:complete` - Signal agent task completion
//!
//! **File tools (5) - requires ToolContext:**
//! - `nika:read` - Read file with line numbers
//! - `nika:write` - Create/overwrite file
//! - `nika:edit` - Modify file (old_string → new_string)
//! - `nika:glob` - Find files by pattern
//! - `nika:grep` - Search content with regex

use super::media::{context::MediaToolContext, create_media_tool_adapters};
use super::{
    create_file_tool_adapters, AssertTool, BuiltinTool, CompleteTool, EmitTool, LogTool,
    PromptTool, RunTool, SleepTool,
};
use crate::error::NikaError;
use crate::tools::ToolContext;
use rustc_hash::FxHashMap;
use std::sync::Arc;

/// Router for builtin nika:* tools.
///
/// Dispatches tool calls to appropriate builtin implementations based on
/// the nika: prefix.
///
/// # Example
///
/// ```ignore
/// let router = BuiltinToolRouter::new();
///
/// // Check if tool is builtin
/// if BuiltinToolRouter::is_builtin("nika:sleep") {
///     let result = router.dispatch("nika:sleep", r#"{"duration":"1s"}"#).await?;
/// }
/// ```
pub struct BuiltinToolRouter {
    tools: FxHashMap<&'static str, Arc<dyn BuiltinTool>>,
}

impl BuiltinToolRouter {
    /// Create a new router with 7 core builtin tools (no file tools).
    ///
    /// For file tools (read, write, edit, glob, grep), use `with_file_tools()`.
    pub fn new() -> Self {
        let mut tools: FxHashMap<&'static str, Arc<dyn BuiltinTool>> = FxHashMap::default();

        // Register 7 core builtin tools
        tools.insert("sleep", Arc::new(SleepTool));
        tools.insert("log", Arc::new(LogTool));
        tools.insert("emit", Arc::new(EmitTool));
        tools.insert("assert", Arc::new(AssertTool));
        tools.insert("prompt", Arc::new(PromptTool::default()));
        tools.insert("run", Arc::new(RunTool));
        tools.insert("complete", Arc::new(CompleteTool));

        Self { tools }
    }

    /// Create a router with all 12 builtin tools (7 core + 5 file tools).
    ///
    /// File tools require a `ToolContext` for working directory and permissions.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use std::sync::Arc;
    /// use nika::tools::{ToolContext, PermissionMode};
    ///
    /// let ctx = Arc::new(ToolContext::new(
    ///     std::env::current_dir().unwrap(),
    ///     PermissionMode::YoloMode,
    /// ));
    /// let router = BuiltinToolRouter::with_file_tools(ctx);
    ///
    /// // Now supports nika:read, nika:write, etc.
    /// assert!(router.has_tool("read"));
    /// assert!(router.has_tool("write"));
    /// ```
    pub fn with_file_tools(ctx: Arc<ToolContext>) -> Self {
        let mut router = Self::new();

        // Register 5 file tools via adapter
        for tool in create_file_tool_adapters(ctx) {
            router.tools.insert(tool.name(), Arc::from(tool));
        }

        router
    }

    /// Create a router with all builtin tools (7 core + 5 file + N media).
    ///
    /// Media tools require a `MediaToolContext` for CAS access, budget, and compute pool.
    pub fn with_all_tools(file_ctx: Arc<ToolContext>, media_ctx: Arc<MediaToolContext>) -> Self {
        let mut router = Self::with_file_tools(file_ctx);

        // Register media tools via adapter
        for tool in create_media_tool_adapters(media_ctx) {
            router.tools.insert(tool.name(), Arc::from(tool));
        }

        router
    }

    /// Check if a tool name is a builtin (has nika: prefix).
    ///
    /// # Example
    /// ```ignore
    /// assert!(BuiltinToolRouter::is_builtin("nika:sleep"));
    /// assert!(!BuiltinToolRouter::is_builtin("novanet:describe"));
    /// ```
    #[inline]
    pub fn is_builtin(tool_name: &str) -> bool {
        tool_name.starts_with("nika:")
    }

    /// Extract the tool name from a nika: prefixed string.
    ///
    /// Returns None if the string doesn't start with "nika:".
    ///
    /// # Example
    /// ```ignore
    /// assert_eq!(BuiltinToolRouter::extract_name("nika:sleep"), Some("sleep"));
    /// assert_eq!(BuiltinToolRouter::extract_name("novanet:x"), None);
    /// ```
    #[inline]
    pub fn extract_name(tool_name: &str) -> Option<&str> {
        tool_name.strip_prefix("nika:")
    }

    /// Check if the router has a specific tool registered.
    pub fn has_tool(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Get all registered tool names.
    pub fn tool_names(&self) -> Vec<&'static str> {
        self.tools.keys().copied().collect()
    }

    /// Register a builtin tool.
    pub fn register<T: BuiltinTool + 'static>(&mut self, tool: T) {
        self.tools.insert(tool.name(), Arc::new(tool));
    }

    /// Dispatch a tool call to the appropriate builtin tool.
    ///
    /// # Arguments
    /// * `tool_name` - Full tool name with nika: prefix (e.g., "nika:sleep")
    /// * `args` - JSON-encoded arguments
    ///
    /// # Returns
    /// * `Ok(String)` - JSON-encoded result from the tool
    /// * `Err(NikaError)` - If tool not found or execution fails
    pub async fn dispatch(&self, tool_name: &str, args: String) -> Result<String, NikaError> {
        let name = Self::extract_name(tool_name).ok_or_else(|| NikaError::BuiltinToolError {
            tool: tool_name.into(),
            reason: "Not a builtin tool (missing nika: prefix)".into(),
        })?;

        let tool = self
            .tools
            .get(name)
            .ok_or_else(|| NikaError::BuiltinToolError {
                tool: tool_name.into(),
                reason: format!("Unknown builtin tool: {}", name),
            })?;

        tool.call(args).await
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::PermissionMode;
    use tempfile::TempDir;

    fn setup_test_context() -> (TempDir, Arc<ToolContext>) {
        let temp_dir = TempDir::new().unwrap();
        let ctx = Arc::new(ToolContext::new(
            temp_dir.path().to_path_buf(),
            PermissionMode::YoloMode,
        ));
        (temp_dir, ctx)
    }

    #[test]
    fn test_router_is_builtin() {
        assert!(BuiltinToolRouter::is_builtin("nika:sleep"));
        assert!(BuiltinToolRouter::is_builtin("nika:log"));
        assert!(BuiltinToolRouter::is_builtin("nika:emit"));
        assert!(BuiltinToolRouter::is_builtin("nika:assert"));
        assert!(BuiltinToolRouter::is_builtin("nika:prompt"));
        assert!(BuiltinToolRouter::is_builtin("nika:run"));
        // File tools
        assert!(BuiltinToolRouter::is_builtin("nika:read"));
        assert!(BuiltinToolRouter::is_builtin("nika:write"));
        assert!(BuiltinToolRouter::is_builtin("nika:edit"));
        assert!(BuiltinToolRouter::is_builtin("nika:glob"));
        assert!(BuiltinToolRouter::is_builtin("nika:grep"));
        // Non-builtin
        assert!(!BuiltinToolRouter::is_builtin("novanet:describe"));
        assert!(!BuiltinToolRouter::is_builtin("sleep"));
        assert!(!BuiltinToolRouter::is_builtin(""));
    }

    #[test]
    fn test_router_extract_name() {
        assert_eq!(BuiltinToolRouter::extract_name("nika:sleep"), Some("sleep"));
        assert_eq!(BuiltinToolRouter::extract_name("nika:log"), Some("log"));
        assert_eq!(BuiltinToolRouter::extract_name("nika:emit"), Some("emit"));
        assert_eq!(
            BuiltinToolRouter::extract_name("nika:assert"),
            Some("assert")
        );
        assert_eq!(
            BuiltinToolRouter::extract_name("nika:prompt"),
            Some("prompt")
        );
        assert_eq!(BuiltinToolRouter::extract_name("nika:run"), Some("run"));
        assert_eq!(BuiltinToolRouter::extract_name("novanet:x"), None);
        assert_eq!(BuiltinToolRouter::extract_name("sleep"), None);
        assert_eq!(BuiltinToolRouter::extract_name(""), None);
    }

    #[test]
    fn test_router_new_has_6_core_tools() {
        let router = BuiltinToolRouter::new();
        assert!(router.has_tool("sleep"));
        assert!(router.has_tool("log"));
        assert!(router.has_tool("emit"));
        assert!(router.has_tool("assert"));
        assert!(router.has_tool("prompt"));
        assert!(router.has_tool("run"));
        assert!(router.has_tool("complete"));
        // new() does NOT include file tools
        assert!(!router.has_tool("read"));
        assert!(!router.has_tool("write"));
        assert_eq!(router.tool_names().len(), 7); // 6 core + complete
    }

    #[test]
    fn test_router_with_file_tools_has_12_tools() {
        let (_temp, ctx) = setup_test_context();
        let router = BuiltinToolRouter::with_file_tools(ctx);

        // 7 core tools (6 original + complete)
        assert!(router.has_tool("sleep"));
        assert!(router.has_tool("log"));
        assert!(router.has_tool("emit"));
        assert!(router.has_tool("assert"));
        assert!(router.has_tool("prompt"));
        assert!(router.has_tool("run"));
        assert!(router.has_tool("complete"));

        // 5 file tools
        assert!(router.has_tool("read"));
        assert!(router.has_tool("write"));
        assert!(router.has_tool("edit"));
        assert!(router.has_tool("glob"));
        assert!(router.has_tool("grep"));

        assert_eq!(router.tool_names().len(), 12); // 7 core + 5 file
    }

    #[test]
    fn test_router_register_tool() {
        struct TestTool;

        impl BuiltinTool for TestTool {
            fn name(&self) -> &'static str {
                "test"
            }

            fn call<'a>(
                &'a self,
                _args: String,
            ) -> std::pin::Pin<
                Box<dyn std::future::Future<Output = Result<String, NikaError>> + Send + 'a>,
            > {
                Box::pin(async { Ok("test result".to_string()) })
            }
        }

        let mut router = BuiltinToolRouter::new();
        router.register(TestTool);

        assert!(router.has_tool("test"));
        assert!(!router.has_tool("unknown"));
    }

    #[tokio::test]
    async fn test_router_dispatch_registered_tool() {
        struct TestTool;

        impl BuiltinTool for TestTool {
            fn name(&self) -> &'static str {
                "test"
            }

            fn call<'a>(
                &'a self,
                args: String,
            ) -> std::pin::Pin<
                Box<dyn std::future::Future<Output = Result<String, NikaError>> + Send + 'a>,
            > {
                Box::pin(async move { Ok(format!("received: {}", args)) })
            }
        }

        let mut router = BuiltinToolRouter::new();
        router.register(TestTool);

        let result = router
            .dispatch("nika:test", r#"{"hello":"world"}"#.to_string())
            .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), r#"received: {"hello":"world"}"#);
    }

    #[tokio::test]
    async fn test_router_dispatch_unknown_tool() {
        let router = BuiltinToolRouter::new();

        let result = router.dispatch("nika:unknown", "{}".to_string()).await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Unknown builtin tool"));
    }

    #[tokio::test]
    async fn test_router_dispatch_not_builtin() {
        let router = BuiltinToolRouter::new();

        let result = router.dispatch("novanet:describe", "{}".to_string()).await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Not a builtin tool"));
    }

    #[test]
    fn test_router_default() {
        let router = BuiltinToolRouter::default();
        // Default router has all 7 core tools (6 original + complete)
        assert_eq!(router.tool_names().len(), 7);
    }

    #[tokio::test]
    async fn test_router_dispatch_sleep() {
        let router = BuiltinToolRouter::new();
        let result = router
            .dispatch("nika:sleep", r#"{"duration":"1ms"}"#.to_string())
            .await;

        assert!(result.is_ok());
        let response: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(response["slept_for_ms"], 1);
    }

    #[tokio::test]
    async fn test_router_dispatch_log() {
        let router = BuiltinToolRouter::new();
        let result = router
            .dispatch(
                "nika:log",
                r#"{"level":"info","message":"test"}"#.to_string(),
            )
            .await;

        assert!(result.is_ok());
        let response: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(response["logged"], true);
    }

    #[tokio::test]
    async fn test_router_dispatch_emit() {
        let router = BuiltinToolRouter::new();
        let result = router
            .dispatch(
                "nika:emit",
                r#"{"name":"test_event","payload":{}}"#.to_string(),
            )
            .await;

        assert!(result.is_ok());
        let response: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(response["emitted"], true);
    }

    #[tokio::test]
    async fn test_router_dispatch_assert_true() {
        let router = BuiltinToolRouter::new();
        let result = router
            .dispatch("nika:assert", r#"{"condition":true}"#.to_string())
            .await;

        assert!(result.is_ok());
        let response: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(response["passed"], true);
    }

    #[tokio::test]
    async fn test_router_dispatch_assert_false() {
        let router = BuiltinToolRouter::new();
        let result = router
            .dispatch("nika:assert", r#"{"condition":false}"#.to_string())
            .await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Assertion failed"));
    }

    #[tokio::test]
    async fn test_router_dispatch_prompt_headless() {
        let router = BuiltinToolRouter::new();
        // In headless mode with default, should use default
        let result = router
            .dispatch(
                "nika:prompt",
                r#"{"message":"Test?","default":"yes"}"#.to_string(),
            )
            .await;

        assert!(result.is_ok());
        let response: serde_json::Value = serde_json::from_str(&result.unwrap()).unwrap();
        assert_eq!(response["response"], "yes");
        assert_eq!(response["default_used"], true);
    }

    #[tokio::test]
    async fn test_router_dispatch_run_nonexistent_file() {
        let router = BuiltinToolRouter::new();
        let result = router
            .dispatch("nika:run", r#"{"workflow":"test.nika.yaml"}"#.to_string())
            .await;

        // Path canonicalization gives "resolve workflow path" error
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("resolve workflow path")
                || err.to_string().contains("not found")
        );
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // FILE TOOL DISPATCH TESTS (via with_file_tools router)
    // ═══════════════════════════════════════════════════════════════════════════

    #[tokio::test]
    async fn test_router_dispatch_write_then_read() {
        let (temp_dir, ctx) = setup_test_context();
        let router = BuiltinToolRouter::with_file_tools(ctx);
        let file_path = temp_dir.path().join("test.txt");

        // Write file via router
        let write_args = serde_json::json!({
            "file_path": file_path.to_string_lossy(),
            "content": "Hello from router!"
        })
        .to_string();

        let result = router.dispatch("nika:write", write_args).await;
        assert!(result.is_ok(), "Write failed: {:?}", result);

        // Read file via router
        let read_args = serde_json::json!({
            "file_path": file_path.to_string_lossy()
        })
        .to_string();

        let result = router.dispatch("nika:read", read_args).await;
        assert!(result.is_ok(), "Read failed: {:?}", result);
        assert!(result.unwrap().contains("Hello from router!"));
    }

    #[tokio::test]
    async fn test_router_dispatch_glob() {
        let (temp_dir, ctx) = setup_test_context();
        let router = BuiltinToolRouter::with_file_tools(ctx);

        // Create test files
        std::fs::write(temp_dir.path().join("a.txt"), "a").unwrap();
        std::fs::write(temp_dir.path().join("b.txt"), "b").unwrap();
        std::fs::write(temp_dir.path().join("c.md"), "c").unwrap();

        let glob_args = serde_json::json!({
            "pattern": "*.txt",
            "path": temp_dir.path().to_string_lossy()
        })
        .to_string();

        let result = router.dispatch("nika:glob", glob_args).await;
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("a.txt"));
        assert!(output.contains("b.txt"));
        assert!(!output.contains("c.md"));
    }

    #[tokio::test]
    async fn test_router_dispatch_grep() {
        let (temp_dir, ctx) = setup_test_context();
        let router = BuiltinToolRouter::with_file_tools(ctx);

        // Create test file
        std::fs::write(
            temp_dir.path().join("search.txt"),
            "Line 1: foo\nLine 2: bar\nLine 3: foo bar",
        )
        .unwrap();

        let grep_args = serde_json::json!({
            "pattern": "foo",
            "path": temp_dir.path().to_string_lossy()
        })
        .to_string();

        let result = router.dispatch("nika:grep", grep_args).await;
        assert!(result.is_ok());
        assert!(result.unwrap().contains("search.txt"));
    }

    #[tokio::test]
    async fn test_router_dispatch_file_tool_not_found_without_context() {
        // Router without file tools
        let router = BuiltinToolRouter::new();

        let result = router
            .dispatch(
                "nika:write",
                r#"{"file_path":"x","content":"y"}"#.to_string(),
            )
            .await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Unknown builtin tool"));
    }
}