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
//! nika:complete - Signal agent task completion
//!
//! The completion tool is called by the agent to signal task completion
//! with a structured result. This is part of the "explicit" completion mode.
//!
//! # Parameters
//!
//! ```json
//! {
//!   "result": "The final answer or output",        // Required
//!   "confidence": 0.95,                            // Optional: 0.0-1.0
//!   "reasoning": "Explanation of the approach"     // Optional: For audit
//! }
//! ```
//!
//! # Returns
//!
//! ```json
//! {
//!   "completed": true,
//!   "result": "...",
//!   "confidence": 0.95,
//!   "is_final": true
//! }
//! ```
//!
//! # Integration with CompletionConfig
//!
//! When the agent is configured with `completion.mode: explicit`, the system
//! prompt instructs the agent to call this tool when done. The RigAgentLoop
//! detects calls to this tool and triggers completion.

use super::BuiltinTool;
use crate::error::NikaError;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::future::Future;
use std::pin::Pin;

// ═══════════════════════════════════════════════════════════════════════════
// Constants
// ═══════════════════════════════════════════════════════════════════════════

/// Special marker that RigAgentLoop uses to detect completion
pub const COMPLETION_MARKER: &str = "__NIKA_COMPLETE__";

// ═══════════════════════════════════════════════════════════════════════════
// Parameters
// ═══════════════════════════════════════════════════════════════════════════

/// Parameters for nika:complete tool.
#[derive(Debug, Clone, Deserialize)]
pub struct CompleteParams {
    /// The final result of the task (required).
    pub result: Value,

    /// Confidence level in the result (0.0-1.0, optional).
    #[serde(default)]
    pub confidence: Option<f64>,

    /// Reasoning or explanation for the result (optional).
    #[serde(default)]
    pub reasoning: Option<String>,

    /// Additional metadata (optional).
    #[serde(default)]
    pub metadata: Option<Value>,
}

impl CompleteParams {
    /// Validate the parameters.
    pub fn validate(&self) -> Result<(), NikaError> {
        // Validate confidence range if provided
        if let Some(conf) = self.confidence {
            if !(0.0..=1.0).contains(&conf) {
                return Err(NikaError::ValidationError {
                    reason: format!("confidence must be between 0.0 and 1.0, got {}", conf),
                });
            }
        }

        Ok(())
    }

    /// Get the result as a string (for simple text results).
    pub fn result_as_string(&self) -> String {
        match &self.result {
            Value::String(s) => s.clone(),
            other => other.to_string(),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Response
// ═══════════════════════════════════════════════════════════════════════════

/// Response from nika:complete tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompleteResponse {
    /// Whether completion was successful.
    pub completed: bool,

    /// The result value.
    pub result: Value,

    /// Confidence level (if provided).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,

    /// Marker for RigAgentLoop to detect completion.
    #[serde(default = "default_marker")]
    pub marker: String,

    /// Whether this is a final completion (not low-confidence retry).
    #[serde(default)]
    pub is_final: bool,
}

fn default_marker() -> String {
    COMPLETION_MARKER.to_string()
}

impl CompleteResponse {
    /// Create a successful completion response.
    pub fn success(params: &CompleteParams, is_final: bool) -> Self {
        Self {
            completed: true,
            result: params.result.clone(),
            confidence: params.confidence,
            marker: COMPLETION_MARKER.to_string(),
            is_final,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Tool Implementation
// ═══════════════════════════════════════════════════════════════════════════

/// nika:complete builtin tool.
///
/// Called by the agent to signal task completion in "explicit" mode.
/// The RigAgentLoop detects this tool call and triggers the completion flow.
pub struct CompleteTool;

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

    fn description(&self) -> &'static str {
        "Signal task completion with a structured result"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "result": {
                    "type": "string",
                    "description": "The final result or answer for the task. Serialize complex values as JSON strings."
                },
                "confidence": {
                    "type": "number",
                    "description": "Confidence level in the result (0.0-1.0)"
                },
                "reasoning": {
                    "type": "string",
                    "description": "Explanation of how you arrived at this result"
                }
            },
            "required": ["result", "confidence", "reasoning"],
            "additionalProperties": false
        })
    }

    fn call<'a>(
        &'a self,
        args: String,
    ) -> Pin<Box<dyn Future<Output = Result<String, NikaError>> + Send + 'a>> {
        Box::pin(async move {
            // Parse parameters
            let params: CompleteParams =
                serde_json::from_str(&args).map_err(|e| NikaError::BuiltinInvalidParams {
                    tool: "nika:complete".into(),
                    reason: format!("Invalid JSON parameters: {}", e),
                })?;

            // Validate parameters
            params
                .validate()
                .map_err(|e| NikaError::BuiltinInvalidParams {
                    tool: "nika:complete".into(),
                    reason: e.to_string(),
                })?;

            tracing::debug!(
                target: "nika_complete",
                confidence = ?params.confidence,
                has_reasoning = params.reasoning.is_some(),
                "Agent signaling completion"
            );

            // Create response
            // Note: is_final will be determined by RigAgentLoop based on confidence config
            let response = CompleteResponse::success(&params, true);

            serde_json::to_string(&response).map_err(|e| NikaError::BuiltinToolError {
                tool: "nika:complete".into(),
                reason: format!("Failed to serialize response: {}", e),
            })
        })
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Utility Functions
// ═══════════════════════════════════════════════════════════════════════════

/// Check if a tool call response indicates completion.
pub fn is_completion_signal(tool_name: &str, response: &str) -> bool {
    if tool_name != "nika:complete" && tool_name != "complete" {
        return false;
    }

    // Check for the completion marker in the response
    response.contains(COMPLETION_MARKER)
}

/// Parse a completion response from tool output.
pub fn parse_completion_response(response: &str) -> Option<CompleteResponse> {
    serde_json::from_str(response).ok()
}

// ═══════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_complete_tool_name() {
        let tool = CompleteTool;
        assert_eq!(tool.name(), "complete");
    }

    #[test]
    fn test_complete_tool_description() {
        let tool = CompleteTool;
        assert!(tool.description().contains("completion"));
    }

    #[test]
    fn test_complete_tool_schema() {
        let tool = CompleteTool;
        let schema = tool.parameters_schema();
        assert_eq!(schema["type"], "object");
        assert!(schema["properties"]["result"].is_object());
        assert!(schema["properties"]["confidence"].is_object());
        assert!(schema["properties"]["reasoning"].is_object());
        assert_eq!(schema["additionalProperties"], false);
        assert!(schema["required"]
            .as_array()
            .unwrap()
            .contains(&serde_json::json!("result")));
    }

    #[tokio::test]
    async fn test_complete_simple_string_result() {
        let tool = CompleteTool;
        let result = tool
            .call(r#"{"result": "Task completed successfully"}"#.to_string())
            .await;

        assert!(result.is_ok());
        let response: CompleteResponse = serde_json::from_str(&result.unwrap()).unwrap();
        assert!(response.completed);
        assert_eq!(response.result, "Task completed successfully");
        assert_eq!(response.marker, COMPLETION_MARKER);
        assert!(response.is_final);
    }

    #[tokio::test]
    async fn test_complete_with_confidence() {
        let tool = CompleteTool;
        let result = tool
            .call(r#"{"result": "Answer", "confidence": 0.95}"#.to_string())
            .await;

        assert!(result.is_ok());
        let response: CompleteResponse = serde_json::from_str(&result.unwrap()).unwrap();
        assert!(response.completed);
        assert_eq!(response.confidence, Some(0.95));
    }

    #[tokio::test]
    async fn test_complete_with_reasoning() {
        let tool = CompleteTool;
        let result = tool
            .call(r#"{"result": "42", "reasoning": "Based on the calculation..."}"#.to_string())
            .await;

        assert!(result.is_ok());
        let response: CompleteResponse = serde_json::from_str(&result.unwrap()).unwrap();
        assert!(response.completed);
    }

    #[tokio::test]
    async fn test_complete_with_complex_result() {
        let tool = CompleteTool;
        let result = tool
            .call(
                r#"{
                    "result": {"items": [1, 2, 3], "total": 6},
                    "confidence": 0.99
                }"#
                .to_string(),
            )
            .await;

        assert!(result.is_ok());
        let response: CompleteResponse = serde_json::from_str(&result.unwrap()).unwrap();
        assert!(response.completed);
        assert_eq!(response.result["items"][0], 1);
        assert_eq!(response.result["total"], 6);
    }

    #[tokio::test]
    async fn test_complete_invalid_confidence_too_high() {
        let tool = CompleteTool;
        let result = tool
            .call(r#"{"result": "x", "confidence": 1.5}"#.to_string())
            .await;

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

    #[tokio::test]
    async fn test_complete_invalid_confidence_negative() {
        let tool = CompleteTool;
        let result = tool
            .call(r#"{"result": "x", "confidence": -0.1}"#.to_string())
            .await;

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

    #[tokio::test]
    async fn test_complete_missing_result() {
        let tool = CompleteTool;
        let result = tool.call(r#"{"confidence": 0.9}"#.to_string()).await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Invalid JSON parameters"));
    }

    #[tokio::test]
    async fn test_complete_invalid_json() {
        let tool = CompleteTool;
        let result = tool.call("not json".to_string()).await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Invalid JSON parameters"));
    }

    /// BUG-4: OpenAI rejects schemas where properties lack a "type" field.
    /// This test prevents regressions by verifying all properties have one.
    #[test]
    fn test_all_properties_have_type_field() {
        let tool = CompleteTool;
        let schema = tool.parameters_schema();
        let props = schema["properties"]
            .as_object()
            .expect("properties must be an object");
        for (name, prop_schema) in props {
            assert!(
                prop_schema.get("type").is_some(),
                "Property '{}' missing 'type' field — OpenAI will reject this schema",
                name,
            );
        }
    }

    #[test]
    fn test_is_completion_signal_positive() {
        let response = serde_json::to_string(&CompleteResponse {
            completed: true,
            result: Value::String("done".into()),
            confidence: Some(0.9),
            marker: COMPLETION_MARKER.to_string(),
            is_final: true,
        })
        .unwrap();

        assert!(is_completion_signal("nika:complete", &response));
        assert!(is_completion_signal("complete", &response));
    }

    #[test]
    fn test_is_completion_signal_negative_wrong_tool() {
        let response = format!(r#"{{"marker": "{}"}}"#, COMPLETION_MARKER);
        assert!(!is_completion_signal("nika:emit", &response));
    }

    #[test]
    fn test_is_completion_signal_negative_no_marker() {
        let response = r#"{"completed": true}"#;
        assert!(!is_completion_signal("nika:complete", response));
    }

    #[test]
    fn test_parse_completion_response() {
        let response = serde_json::to_string(&CompleteResponse {
            completed: true,
            result: Value::String("test".into()),
            confidence: Some(0.8),
            marker: COMPLETION_MARKER.to_string(),
            is_final: true,
        })
        .unwrap();

        let parsed = parse_completion_response(&response).unwrap();
        assert!(parsed.completed);
        assert_eq!(parsed.result, "test");
        assert_eq!(parsed.confidence, Some(0.8));
    }

    #[test]
    fn test_complete_params_validate_valid() {
        let params = CompleteParams {
            result: Value::String("ok".into()),
            confidence: Some(0.5),
            reasoning: None,
            metadata: None,
        };
        assert!(params.validate().is_ok());
    }

    #[test]
    fn test_complete_params_result_as_string() {
        // String result
        let params = CompleteParams {
            result: Value::String("hello".into()),
            confidence: None,
            reasoning: None,
            metadata: None,
        };
        assert_eq!(params.result_as_string(), "hello");

        // Number result
        let params = CompleteParams {
            result: serde_json::json!(42),
            confidence: None,
            reasoning: None,
            metadata: None,
        };
        assert_eq!(params.result_as_string(), "42");

        // Object result
        let params = CompleteParams {
            result: serde_json::json!({"key": "value"}),
            confidence: None,
            reasoning: None,
            metadata: None,
        };
        assert!(params.result_as_string().contains("key"));
    }

    #[test]
    fn test_complete_response_success() {
        let params = CompleteParams {
            result: Value::String("done".into()),
            confidence: Some(0.99),
            reasoning: Some("explanation".into()),
            metadata: None,
        };

        let response = CompleteResponse::success(&params, true);
        assert!(response.completed);
        assert_eq!(response.result, "done");
        assert_eq!(response.confidence, Some(0.99));
        assert!(response.is_final);
        assert_eq!(response.marker, COMPLETION_MARKER);
    }
}