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
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
//! SuperNovae Registry API Client
//!
//! HTTP client for the SuperNovae package registry.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │  REGISTRY API CLIENT                                                        │
//! ├─────────────────────────────────────────────────────────────────────────────┤
//! │                                                                             │
//! │  RegistryClient                                                             │
//! │  ├── base_url: https://registry.supernovae.studio/api/v1                    │
//! │  ├── client: reqwest::Client (connection pooling, rustls)                   │
//! │  └── timeout: 30s default                                                   │
//! │                                                                             │
//! │  API Endpoints:                                                             │
//! │  GET  /packages/:name              → Package metadata                       │
//! │  GET  /packages/:name/versions     → All versions                           │
//! │  GET  /packages/:name/:version     → Specific version                       │
//! │  GET  /search?q=:query             → Search packages                        │
//! │  GET  /packages/:name/:version/download → Download tarball                  │
//! │                                                                             │
//! └─────────────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Usage
//!
//! ```rust,ignore
//! use nika::registry::api::RegistryClient;
//!
//! let client = RegistryClient::new();
//!
//! // Search for packages
//! let results = client.search("workflow").await?;
//!
//! // Get package info
//! let info = client.get_package("@spn/core").await?;
//!
//! // Download package
//! let bytes = client.download("@spn/core", "1.0.0").await?;
//! ```

use std::path::PathBuf;
use std::time::Duration;

use reqwest::Client;
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Default registry URL
pub const DEFAULT_REGISTRY_URL: &str = "https://registry.supernovae.studio/api/v1";

/// Environment variable to override registry URL
pub const REGISTRY_URL_ENV: &str = "NIKA_REGISTRY_URL";

/// Default request timeout in seconds
pub const DEFAULT_TIMEOUT_SECS: u64 = 30;

/// Errors that can occur during registry API operations.
#[derive(Error, Debug)]
pub enum RegistryApiError {
    #[error("Network error: {0}")]
    NetworkError(#[from] reqwest::Error),

    #[error("Package not found: {0}")]
    PackageNotFound(String),

    #[error("Version not found: {0}@{1}")]
    VersionNotFound(String, String),

    #[error("API error: {status} - {message}")]
    ApiError { status: u16, message: String },

    #[error("Invalid response: {0}")]
    InvalidResponse(String),

    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Rate limited: retry after {retry_after} seconds")]
    RateLimited { retry_after: u64 },
}

/// Package metadata from the registry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PackageInfo {
    /// Package name (e.g., "@spn/core")
    pub name: String,

    /// Latest version
    pub latest_version: String,

    /// Short description
    #[serde(default)]
    pub description: Option<String>,

    /// Package authors
    #[serde(default)]
    pub authors: Option<Vec<String>>,

    /// SPDX license
    #[serde(default)]
    pub license: Option<String>,

    /// Repository URL
    #[serde(default)]
    pub repository: Option<String>,

    /// Keywords for search
    #[serde(default)]
    pub keywords: Option<Vec<String>>,

    /// Download count (all versions)
    #[serde(default)]
    pub downloads: Option<u64>,

    /// Available versions (newest first)
    #[serde(default)]
    pub versions: Vec<String>,

    /// Created timestamp (ISO 8601)
    #[serde(default)]
    pub created_at: Option<String>,

    /// Last updated timestamp (ISO 8601)
    #[serde(default)]
    pub updated_at: Option<String>,
}

/// Version-specific metadata from the registry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersionInfo {
    /// Package name
    pub name: String,

    /// Version string
    pub version: String,

    /// Description
    #[serde(default)]
    pub description: Option<String>,

    /// Dependencies (name -> version constraint)
    #[serde(default)]
    pub dependencies: Option<std::collections::HashMap<String, String>>,

    /// Skills provided by this version
    #[serde(default)]
    pub skills: Option<Vec<SkillInfo>>,

    /// Tarball size in bytes
    #[serde(default)]
    pub size: Option<u64>,

    /// SHA256 checksum of tarball
    #[serde(default)]
    pub checksum: Option<String>,

    /// Published timestamp (ISO 8601)
    #[serde(default)]
    pub published_at: Option<String>,
}

/// Skill information within a package.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillInfo {
    /// Skill name/alias
    pub name: String,

    /// Relative path within package
    pub path: String,

    /// Description
    #[serde(default)]
    pub description: Option<String>,
}

/// Search result item.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    /// Package name
    pub name: String,

    /// Latest version
    pub version: String,

    /// Description
    #[serde(default)]
    pub description: Option<String>,

    /// Keywords
    #[serde(default)]
    pub keywords: Option<Vec<String>>,

    /// Download count
    #[serde(default)]
    pub downloads: Option<u64>,

    /// Search relevance score (0.0 - 1.0)
    #[serde(default)]
    pub score: Option<f64>,
}

/// Search response from the registry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResponse {
    /// Total matching packages
    pub total: usize,

    /// Current page
    pub page: usize,

    /// Items per page
    pub per_page: usize,

    /// Search results
    pub results: Vec<SearchResult>,
}

/// SuperNovae Registry API Client.
///
/// Thread-safe, connection-pooled HTTP client for the package registry.
#[derive(Debug, Clone)]
pub struct RegistryClient {
    client: Client,
    base_url: String,
}

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

impl RegistryClient {
    /// Create a new registry client with default settings.
    ///
    /// Uses `NIKA_REGISTRY_URL` env var or falls back to the default registry.
    pub fn new() -> Self {
        let base_url =
            std::env::var(REGISTRY_URL_ENV).unwrap_or_else(|_| DEFAULT_REGISTRY_URL.to_string());

        let client = Client::builder()
            .timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
            .user_agent(format!("nika/{}", env!("CARGO_PKG_VERSION")))
            .build()
            .expect("Failed to build HTTP client");

        Self { client, base_url }
    }

    /// Create a client with a custom base URL.
    pub fn with_url(base_url: impl Into<String>) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
            .user_agent(format!("nika/{}", env!("CARGO_PKG_VERSION")))
            .build()
            .expect("Failed to build HTTP client");

        Self {
            client,
            base_url: base_url.into(),
        }
    }

    /// Create a client with custom timeout.
    pub fn with_timeout(timeout_secs: u64) -> Self {
        let base_url =
            std::env::var(REGISTRY_URL_ENV).unwrap_or_else(|_| DEFAULT_REGISTRY_URL.to_string());

        let client = Client::builder()
            .timeout(Duration::from_secs(timeout_secs))
            .user_agent(format!("nika/{}", env!("CARGO_PKG_VERSION")))
            .build()
            .expect("Failed to build HTTP client");

        Self { client, base_url }
    }

    /// Get package metadata.
    ///
    /// # Arguments
    ///
    /// * `name` - Package name (e.g., "@spn/core")
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let client = RegistryClient::new();
    /// let info = client.get_package("@spn/core").await?;
    /// println!("Latest version: {}", info.latest_version);
    /// ```
    pub async fn get_package(&self, name: &str) -> Result<PackageInfo, RegistryApiError> {
        let url = format!("{}/packages/{}", self.base_url, encode_package_name(name));

        let response = self.client.get(&url).send().await?;

        match response.status().as_u16() {
            200 => response
                .json::<PackageInfo>()
                .await
                .map_err(|e| RegistryApiError::InvalidResponse(e.to_string())),
            404 => Err(RegistryApiError::PackageNotFound(name.to_string())),
            429 => {
                let retry_after = response
                    .headers()
                    .get("retry-after")
                    .and_then(|v| v.to_str().ok())
                    .and_then(|v| v.parse().ok())
                    .unwrap_or(60);
                Err(RegistryApiError::RateLimited { retry_after })
            }
            status => {
                let message = response.text().await.unwrap_or_default();
                Err(RegistryApiError::ApiError { status, message })
            }
        }
    }

    /// Get specific version metadata.
    ///
    /// # Arguments
    ///
    /// * `name` - Package name
    /// * `version` - Version string (e.g., "1.0.0")
    pub async fn get_version(
        &self,
        name: &str,
        version: &str,
    ) -> Result<VersionInfo, RegistryApiError> {
        let url = format!(
            "{}/packages/{}/{}",
            self.base_url,
            encode_package_name(name),
            version
        );

        let response = self.client.get(&url).send().await?;

        match response.status().as_u16() {
            200 => response
                .json::<VersionInfo>()
                .await
                .map_err(|e| RegistryApiError::InvalidResponse(e.to_string())),
            404 => Err(RegistryApiError::VersionNotFound(
                name.to_string(),
                version.to_string(),
            )),
            429 => {
                let retry_after = response
                    .headers()
                    .get("retry-after")
                    .and_then(|v| v.to_str().ok())
                    .and_then(|v| v.parse().ok())
                    .unwrap_or(60);
                Err(RegistryApiError::RateLimited { retry_after })
            }
            status => {
                let message = response.text().await.unwrap_or_default();
                Err(RegistryApiError::ApiError { status, message })
            }
        }
    }

    /// Get all available versions for a package.
    ///
    /// # Arguments
    ///
    /// * `name` - Package name
    ///
    /// # Returns
    ///
    /// Vector of version strings, newest first.
    pub async fn get_versions(&self, name: &str) -> Result<Vec<String>, RegistryApiError> {
        let url = format!(
            "{}/packages/{}/versions",
            self.base_url,
            encode_package_name(name)
        );

        let response = self.client.get(&url).send().await?;

        match response.status().as_u16() {
            200 => {
                #[derive(Deserialize)]
                struct VersionsResponse {
                    versions: Vec<String>,
                }
                let resp: VersionsResponse = response
                    .json()
                    .await
                    .map_err(|e| RegistryApiError::InvalidResponse(e.to_string()))?;
                Ok(resp.versions)
            }
            404 => Err(RegistryApiError::PackageNotFound(name.to_string())),
            429 => {
                let retry_after = 60;
                Err(RegistryApiError::RateLimited { retry_after })
            }
            status => {
                let message = response.text().await.unwrap_or_default();
                Err(RegistryApiError::ApiError { status, message })
            }
        }
    }

    /// Search for packages.
    ///
    /// # Arguments
    ///
    /// * `query` - Search query
    /// * `page` - Page number (1-indexed)
    /// * `per_page` - Results per page (default 20, max 100)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let client = RegistryClient::new();
    /// let results = client.search("workflow", 1, 20).await?;
    /// for pkg in results.results {
    ///     println!("{}: {}", pkg.name, pkg.description.unwrap_or_default());
    /// }
    /// ```
    pub async fn search(
        &self,
        query: &str,
        page: usize,
        per_page: usize,
    ) -> Result<SearchResponse, RegistryApiError> {
        let url = format!(
            "{}/search?q={}&page={}&per_page={}",
            self.base_url,
            urlencoding::encode(query),
            page,
            per_page.min(100)
        );

        let response = self.client.get(&url).send().await?;

        match response.status().as_u16() {
            200 => response
                .json::<SearchResponse>()
                .await
                .map_err(|e| RegistryApiError::InvalidResponse(e.to_string())),
            429 => {
                let retry_after = 60;
                Err(RegistryApiError::RateLimited { retry_after })
            }
            status => {
                let message = response.text().await.unwrap_or_default();
                Err(RegistryApiError::ApiError { status, message })
            }
        }
    }

    /// Download package tarball.
    ///
    /// # Arguments
    ///
    /// * `name` - Package name
    /// * `version` - Version to download
    ///
    /// # Returns
    ///
    /// Raw bytes of the tarball (gzipped tar archive).
    pub async fn download(&self, name: &str, version: &str) -> Result<Vec<u8>, RegistryApiError> {
        let url = format!(
            "{}/packages/{}/{}/download",
            self.base_url,
            encode_package_name(name),
            version
        );

        let response = self.client.get(&url).send().await?;

        match response.status().as_u16() {
            200 => response
                .bytes()
                .await
                .map(|b| b.to_vec())
                .map_err(RegistryApiError::from),
            404 => Err(RegistryApiError::VersionNotFound(
                name.to_string(),
                version.to_string(),
            )),
            429 => {
                let retry_after = 60;
                Err(RegistryApiError::RateLimited { retry_after })
            }
            status => {
                let message = response.text().await.unwrap_or_default();
                Err(RegistryApiError::ApiError { status, message })
            }
        }
    }

    /// Download and extract package to a directory.
    ///
    /// # Arguments
    ///
    /// * `name` - Package name
    /// * `version` - Version to download
    /// * `target_dir` - Directory to extract to
    ///
    /// # Returns
    ///
    /// Path to the extracted package directory.
    pub async fn download_and_extract(
        &self,
        name: &str,
        version: &str,
        target_dir: &PathBuf,
    ) -> Result<PathBuf, RegistryApiError> {
        use flate2::read::GzDecoder;
        use tar::Archive;

        let bytes = self.download(name, version).await?;

        // Create target directory
        std::fs::create_dir_all(target_dir)?;

        // Extract tarball
        let gz = GzDecoder::new(bytes.as_slice());
        let mut archive = Archive::new(gz);
        archive.unpack(target_dir)?;

        Ok(target_dir.clone())
    }

    /// Check if a package exists.
    pub async fn package_exists(&self, name: &str) -> Result<bool, RegistryApiError> {
        match self.get_package(name).await {
            Ok(_) => Ok(true),
            Err(RegistryApiError::PackageNotFound(_)) => Ok(false),
            Err(e) => Err(e),
        }
    }

    /// Check if a specific version exists.
    pub async fn version_exists(
        &self,
        name: &str,
        version: &str,
    ) -> Result<bool, RegistryApiError> {
        match self.get_version(name, version).await {
            Ok(_) => Ok(true),
            Err(RegistryApiError::VersionNotFound(_, _)) => Ok(false),
            Err(e) => Err(e),
        }
    }

    /// Get the base URL being used.
    pub fn base_url(&self) -> &str {
        &self.base_url
    }
}

/// Encode package name for URL path.
///
/// Handles scoped packages: `@scope/name` -> `@scope%2Fname`
fn encode_package_name(name: &str) -> String {
    // URL encode the slash in scoped packages
    name.replace('/', "%2F")
}

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

    #[test]
    fn test_encode_package_name() {
        assert_eq!(encode_package_name("@spn/core"), "@spn%2Fcore");
        assert_eq!(encode_package_name("simple-pkg"), "simple-pkg");
        assert_eq!(
            encode_package_name("@workflows/seo-audit"),
            "@workflows%2Fseo-audit"
        );
    }

    #[test]
    fn test_registry_client_default() {
        let client = RegistryClient::new();
        // Should use default URL if env var not set
        assert!(client.base_url.contains("registry") || client.base_url.contains("supernovae"));
    }

    #[test]
    fn test_registry_client_with_url() {
        let client = RegistryClient::with_url("https://custom.registry.local/api");
        assert_eq!(client.base_url, "https://custom.registry.local/api");
    }

    #[test]
    fn test_package_info_deserialize() {
        let json = r#"{
            "name": "@spn/core",
            "latest_version": "1.0.0",
            "description": "Core skills",
            "versions": ["1.0.0", "0.9.0"]
        }"#;

        let info: PackageInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.name, "@spn/core");
        assert_eq!(info.latest_version, "1.0.0");
        assert_eq!(info.versions.len(), 2);
    }

    #[test]
    fn test_version_info_deserialize() {
        let json = r#"{
            "name": "@spn/core",
            "version": "1.0.0",
            "description": "Core skills package",
            "skills": [
                {"name": "brainstorm", "path": "skills/brainstorm.md"}
            ]
        }"#;

        let info: VersionInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.name, "@spn/core");
        assert_eq!(info.version, "1.0.0");
        assert!(info.skills.is_some());
        assert_eq!(info.skills.as_ref().unwrap().len(), 1);
    }

    #[test]
    fn test_search_response_deserialize() {
        let json = r#"{
            "total": 42,
            "page": 1,
            "per_page": 20,
            "results": [
                {
                    "name": "@spn/core",
                    "version": "1.0.0",
                    "description": "Core package",
                    "score": 0.95
                }
            ]
        }"#;

        let response: SearchResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.total, 42);
        assert_eq!(response.results.len(), 1);
        assert_eq!(response.results[0].name, "@spn/core");
    }

    #[test]
    fn test_skill_info_deserialize() {
        let json = r#"{
            "name": "brainstorm",
            "path": "skills/brainstorm.skill.md",
            "description": "Collaborative ideation"
        }"#;

        let skill: SkillInfo = serde_json::from_str(json).unwrap();
        assert_eq!(skill.name, "brainstorm");
        assert_eq!(skill.path, "skills/brainstorm.skill.md");
    }

    #[test]
    fn test_registry_api_error_display() {
        let err = RegistryApiError::PackageNotFound("@test/pkg".to_string());
        assert_eq!(err.to_string(), "Package not found: @test/pkg");

        let err = RegistryApiError::VersionNotFound("@test/pkg".to_string(), "1.0.0".to_string());
        assert_eq!(err.to_string(), "Version not found: @test/pkg@1.0.0");

        let err = RegistryApiError::RateLimited { retry_after: 60 };
        assert_eq!(err.to_string(), "Rate limited: retry after 60 seconds");
    }

    #[test]
    fn test_package_info_optional_fields() {
        let json = r#"{
            "name": "@minimal/pkg",
            "latest_version": "0.1.0",
            "versions": []
        }"#;

        let info: PackageInfo = serde_json::from_str(json).unwrap();
        assert!(info.description.is_none());
        assert!(info.authors.is_none());
        assert!(info.license.is_none());
        assert!(info.downloads.is_none());
    }
}