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
//! Init subcommand handler

use std::fs;

use colored::Colorize;

use nika::error::NikaError;
use nika::init::{
    get_all_context_files, get_all_partials, get_all_schemas, get_all_workflows, WORKFLOWS_README,
};
use nika::tools::PermissionMode;

/// Initialize a new Nika project
///
/// Creates:
/// - `.nika/` directory with config, agents, skills, memory, etc.
/// - `workflows/` with 30 progressive example workflows organized by tier (unless --no-example)
/// - `context/` with context files for workflows
/// - `workflows/partials/` with reusable workflow fragments (for include:)
/// - `schemas/` with JSON schemas for output validation
/// - `output/` for generated workflow outputs
pub fn init_project(
    permission: &str,
    no_example: bool,
    migrate_keys: bool,
) -> Result<(), NikaError> {
    let cwd = std::env::current_dir()?;
    let nika_dir = cwd.join(".nika");

    // Check if already initialized
    if nika_dir.exists() {
        return Err(NikaError::ValidationError {
            reason: format!(
                "Project already initialized at {}. Remove .nika/ to reinitialize.",
                nika_dir.display()
            ),
        });
    }

    // Parse permission mode
    let permission_mode = match permission.to_lowercase().as_str() {
        "deny" => PermissionMode::Deny,
        "plan" => PermissionMode::Plan,
        "accept-edits" | "acceptedits" => PermissionMode::AcceptEdits,
        "accept-all" | "acceptall" | "yolo" => PermissionMode::YoloMode,
        other => {
            return Err(NikaError::ValidationError {
                reason: format!(
                    "Invalid permission mode: '{}'. Use: deny, plan, accept-edits, yolo",
                    other
                ),
            });
        }
    };

    // Create .nika directory
    fs::create_dir_all(&nika_dir)?;
    println!("{} Created {}", "".green(), nika_dir.display());

    // Create config.toml
    let config_path = nika_dir.join("config.toml");
    let config_content = format!(
        r#"# Nika Project Configuration
# Generated by `nika init`

[tools]
# Permission mode for file tools
# Options: deny, plan, accept-edits, accept-all
permission = "{}"

# Working directory (default: project root)
# Files outside this directory cannot be accessed
# working_dir = "."

[provider]
# Default LLM provider (claude, openai, mistral, groq, deepseek, native)
# Provider auto-detection checks env vars: ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.
# Can also override with: nika chat --provider <name>
default = "claude"

# Default model (provider-specific)
# Can also override with: nika chat --model <name>
# model = "claude-sonnet-4-6"
"#,
        permission_mode
            .display_name()
            .to_lowercase()
            .replace(" (yolo)", "")
    );
    fs::write(&config_path, config_content)?;
    println!("{} Created {}", "".green(), config_path.display());

    // Create agents directory with example
    let agents_dir = nika_dir.join("agents");
    fs::create_dir_all(&agents_dir)?;
    println!("{} Created {}", "".green(), agents_dir.display());

    // Create example agent (Claude Code style with YAML frontmatter)
    let example_agent_path = agents_dir.join("researcher.md");
    let example_agent_content = r#"---
name: researcher
description: A helpful research agent that can search and summarize information
model: claude-sonnet-4-6
max_turns: 10
---

You are a Research Agent specialized in finding and synthesizing information.

## Capabilities

- Search the web for relevant information
- Summarize findings in clear, concise language
- Cite sources and provide references
- Answer follow-up questions

## Guidelines

1. Always verify information from multiple sources when possible
2. Clearly distinguish between facts and opinions
3. Acknowledge uncertainty when information is incomplete
4. Provide actionable insights when relevant

## Output Format

Structure your responses with:
- **Summary**: Key findings in 2-3 sentences
- **Details**: Supporting information
- **Sources**: References used (when applicable)
"#;
    fs::write(&example_agent_path, example_agent_content)?;
    println!("{} Created {}", "".green(), example_agent_path.display());

    // Create skills directory with example
    let skills_dir = nika_dir.join("skills");
    fs::create_dir_all(&skills_dir)?;
    println!("{} Created {}", "".green(), skills_dir.display());

    // Create example skill
    let example_skill_path = skills_dir.join("code-review.md");
    let example_skill_content = r#"---
name: code-review
description: Skill for reviewing code quality, patterns, and best practices
---

# Code Review Skill

When reviewing code, analyze for:

## Quality Checks
- Clear naming conventions
- Appropriate error handling
- Code duplication
- Complexity and readability

## Security
- Input validation
- Authentication/authorization
- Sensitive data handling

## Best Practices
- SOLID principles
- DRY (Don't Repeat Yourself)
- Single responsibility
- Proper documentation

## Output
Provide feedback in categories:
- 🔴 Critical: Must fix before merge
- 🟡 Important: Should address
- 🟢 Suggestion: Nice to have
"#;
    fs::write(&example_skill_path, example_skill_content)?;
    println!("{} Created {}", "".green(), example_skill_path.display());

    // Create context directory
    let context_dir = nika_dir.join("context");
    fs::create_dir_all(&context_dir)?;
    println!("{} Created {}", "".green(), context_dir.display());

    // Create example context file
    let context_path = context_dir.join("project.md");
    let context_content = r#"# Project Context

This file provides shared context for all agents and workflows.

## Project Overview

Describe your project here. This context will be available to agents via `memory.context.project`.

## Key Information

- Project name: [Your Project]
- Tech stack: [Your Stack]
- Key conventions: [Your Conventions]
"#;
    fs::write(&context_path, context_content)?;
    println!("{} Created {}", "".green(), context_path.display());

    // Create memory directory
    let memory_dir = nika_dir.join("memory");
    fs::create_dir_all(&memory_dir)?;
    println!("{} Created {}", "".green(), memory_dir.display());

    // Create proposed directory (for agent-proposed changes)
    let proposed_dir = nika_dir.join("proposed");
    fs::create_dir_all(&proposed_dir)?;
    println!("{} Created {}", "".green(), proposed_dir.display());

    // Create cache directory
    let cache_dir = nika_dir.join("cache");
    fs::create_dir_all(&cache_dir)?;
    println!("{} Created {}", "".green(), cache_dir.display());

    // Create workflows directory (for sub-workflow composition)
    let workflows_dir = nika_dir.join("workflows");
    fs::create_dir_all(&workflows_dir)?;
    println!("{} Created {}", "".green(), workflows_dir.display());

    // Create example sub-workflow (can be called via nika:run)
    let example_subworkflow_path = workflows_dir.join("helpers.nika.yaml");
    let example_subworkflow_content = r#"# Helper Sub-Workflows
# These are standalone helper workflows — run them directly
# or compose them into larger DAGs with depends_on.
#
# Examples:
#   nika run .nika/workflows/helpers.nika.yaml
#   nika run .nika/workflows/helpers.nika.yaml -p provider=openai

schema: "nika/workflow@0.12"
workflow: helpers
description: "Reusable helper workflows for common tasks"

inputs:
  content: "Nika is a semantic YAML workflow engine for AI tasks."
  target_language: "French"

tasks:
  - id: summarize
    infer:
      prompt: |
        Summarize the following content in 3 bullet points:

        {{inputs.content}}
      temperature: 0.3
      max_tokens: 300

  - id: translate
    infer:
      prompt: |
        Translate the following text to {{inputs.target_language}}:

        {{inputs.content}}
      temperature: 0.2
      max_tokens: 500

  - id: review
    depends_on: [summarize, translate]
    with:
      summary: $summarize
      translation: $translate
    infer:
      prompt: |
        Review these outputs for quality:

        SUMMARY:
        {{with.summary}}

        TRANSLATION ({{inputs.target_language}}):
        {{with.translation}}

        Rate each 1-10 and suggest improvements.
      temperature: 0.3
      max_tokens: 400
"#;
    fs::write(&example_subworkflow_path, example_subworkflow_content)?;
    println!(
        "{} Created {}",
        "".green(),
        example_subworkflow_path.display()
    );

    // Create user.yaml
    let user_path = nika_dir.join("user.yaml");
    let user_content = r#"# Nika User Profile
# Personalize your AI experience

# Your name (used in greetings and personalization)
# name: "Your Name"

# Email (optional, for notifications)
# email: "you@example.com"

# Timezone (for scheduling and timestamps)
timezone: "UTC"

# Preferred language (ISO 639-1 code)
language: "en-US"

# Additional context about you (helps agents understand your preferences)
# context: |
#   I prefer concise responses.
#   I work primarily with Rust and TypeScript.
"#;
    fs::write(&user_path, user_content)?;
    println!("{} Created {}", "".green(), user_path.display());

    // Create memory.yaml
    let memory_config_path = nika_dir.join("memory.yaml");
    let memory_config_content = r#"# Nika Memory Configuration
# Persistent memory across sessions

# Enable/disable memory system
enabled: true

# Storage backend: file, sqlite, redis (file is default)
backend: file

# Time-to-live in seconds for memory entries (0 = no expiry)
ttl_secs: 0

# Maximum number of entries to keep (0 = unlimited)
max_entries: 1000

# Memory scopes (named memory buckets)
scopes:
  # Conversation history
  conversation:
    persist: true
    ttl_secs: 86400  # 24 hours

  # Project-specific memory
  project:
    persist: true
    ttl_secs: 0  # Never expires

  # Temporary scratch space
  scratch:
    persist: false
    ttl_secs: 3600  # 1 hour
"#;
    fs::write(&memory_config_path, memory_config_content)?;
    println!("{} Created {}", "".green(), memory_config_path.display());

    // Create policies.yaml
    let policies_path = nika_dir.join("policies.yaml");
    let policies_content = r#"# Nika Security Policies
# Control what agents can do

execution:
  # Shell commands that are always allowed (glob patterns)
  allow_commands:
    - "echo *"
    - "cat *"
    - "ls *"
    - "pwd"
    - "date"
    - "git status"
    - "git diff *"
    - "git log *"
    - "cargo *"
    - "npm *"
    - "pnpm *"

  # Shell commands that are always blocked
  block_commands:
    - "rm -rf /*"
    - "sudo *"
    - "chmod 777 *"

  # Require confirmation for potentially destructive commands
  confirm_destructive: true

  # Maximum execution time for any command (seconds)
  max_execution_secs: 300

budget:
  # Daily token limit (0 = unlimited)
  daily_token_limit: 0

  # Monthly cost limit in cents (0 = unlimited)
  monthly_cost_limit_cents: 0

  # Warn when this percentage of budget is reached
  warn_at_percent: 80

network:
  # Domains that can be accessed (empty = all allowed)
  # allow_domains:
  #   - "api.example.com"

  # Domains that are always blocked
  block_domains:
    - "localhost:internal"

  # Allow localhost/127.0.0.1 access
  allow_localhost: true
"#;
    fs::write(&policies_path, policies_content)?;
    println!("{} Created {}", "".green(), policies_path.display());

    // Create progressive example workflows unless --no-example
    if !no_example {
        // Create workflows/ directory at project root
        let workflows_dir = cwd.join("workflows");
        fs::create_dir_all(&workflows_dir)?;
        println!("{} Created {}", "".green(), workflows_dir.display());

        // Write README.md for workflows
        let readme_path = workflows_dir.join("README.md");
        fs::write(&readme_path, WORKFLOWS_README)?;
        println!("{} Created {}", "".green(), readme_path.display());

        // Create tier directories and write all 30 workflows
        let workflows = get_all_workflows();
        let mut created_tiers = std::collections::HashSet::new();

        for workflow in &workflows {
            let tier_dir = workflows_dir.join(workflow.tier_dir);
            if created_tiers.insert(workflow.tier_dir) {
                fs::create_dir_all(&tier_dir)?;
                println!("{} Created {}", "".green(), tier_dir.display());
            }
            let wf_path = tier_dir.join(workflow.filename);
            fs::write(&wf_path, workflow.content)?;
            println!("{} Created {}", "".green(), wf_path.display());
        }

        // Create context/ directory at project root
        let context_dir = cwd.join("context");
        fs::create_dir_all(&context_dir)?;
        println!("{} Created {}", "".green(), context_dir.display());

        // Write all context files
        for ctx_file in get_all_context_files() {
            let ctx_path = context_dir.join(ctx_file.filename);
            fs::write(&ctx_path, ctx_file.content)?;
            println!("{} Created {}", "".green(), ctx_path.display());
        }

        // Create partials/ directory inside workflows/ (for include: security)
        let partials_dir = workflows_dir.join("partials");
        fs::create_dir_all(&partials_dir)?;
        println!("{} Created {}", "".green(), partials_dir.display());

        // Write all partial workflows
        for partial in get_all_partials() {
            let partial_path = partials_dir.join(partial.filename);
            fs::write(&partial_path, partial.content)?;
            println!("{} Created {}", "".green(), partial_path.display());
        }

        // Create schemas/ directory at project root
        let schemas_dir = cwd.join("schemas");
        fs::create_dir_all(&schemas_dir)?;
        println!("{} Created {}", "".green(), schemas_dir.display());

        // Write all JSON schemas
        for schema in get_all_schemas() {
            let schema_path = schemas_dir.join(schema.filename);
            fs::write(&schema_path, schema.content)?;
            println!("{} Created {}", "".green(), schema_path.display());
        }

        // Create output/ directory at project root with .gitkeep
        let output_dir = cwd.join("output");
        fs::create_dir_all(&output_dir)?;
        fs::write(output_dir.join(".gitkeep"), "")?;
        println!("{} Created {}", "".green(), output_dir.display());

        println!();
        println!(
            "{} {} workflows created across {} tiers",
            "".green(),
            workflows.len().to_string().cyan(),
            created_tiers.len().to_string().cyan()
        );
    }

    // Print summary
    println!();
    println!("{}", "Nika project initialized!".green().bold());
    println!();
    println!(
        "  Permission mode: {}",
        permission_mode.display_name().cyan()
    );
    println!("  Config: {}", config_path.display());
    println!();
    println!("  {} Project structure:", "📁".cyan());
    println!();
    println!(
        "    {}  .nika/             # Nika configuration",
        "⚙️".dimmed()
    );
    println!("    ├── config.toml        # Main configuration");
    println!("    ├── agents/            # Agent definitions");
    println!("    ├── skills/            # Skill definitions");
    println!("    └── ...");
    if !no_example {
        println!();
        println!(
            "    {}  workflows/          # 30 example workflows by tier",
            "📂".cyan()
        );
        println!("    ├── README.md                     # Quick start guide");
        println!("    ├── tier-1-no-deps/  (01-03)      # exec, fetch, builtins");
        println!("    ├── tier-2-llm/      (04-07)      # infer, DAG, for_each");
        println!("    ├── tier-3-agent/    (08-09)      # agent + file tools");
        println!("    ├── tier-4-mcp/      (10)         # NovaNet integration");
        println!("    ├── tier-5-dev/      (11-20)      # Developer use cases");
        println!("    └── tier-6-magic/    (21-30)      # Everyday automation");
        println!();
        println!(
            "    {}  context/            # Context files for workflows",
            "📁".dimmed()
        );
        println!(
            "    {}  partials/           # Reusable workflow fragments",
            "📁".dimmed()
        );
        println!(
            "    {}  schemas/            # JSON schemas for validation",
            "📁".dimmed()
        );
        println!(
            "    {}  output/             # Generated outputs (gitignored)",
            "📁".dimmed()
        );
    }
    println!();
    if !no_example {
        println!("  {} Get started:", "".cyan());
        println!();
        println!("    # Tier 1: Works immediately (no API key)");
        println!("    nika run workflows/tier-1-no-deps/01-exec-basics.nika.yaml");
        println!();
        println!("    # Tier 2: Setup provider first");
        println!("    nika provider set anthropic");
        println!("    nika run workflows/tier-2-llm/04-infer-basics.nika.yaml");
        println!();
        println!("  {} Learn more:", "📖".cyan());
        println!("    See workflows/README.md for full tier guide");
    }

    // Migrate API keys from env vars to keychain if requested
    #[cfg(feature = "tui")]
    if migrate_keys {
        use nika::secrets::migrate_env_to_keyring;
        println!();
        println!(
            "{}",
            "Migrating API keys from environment variables...".cyan()
        );
        let report = migrate_env_to_keyring();
        println!();
        println!("{}", report.summary());

        if !report.errors.is_empty() {
            println!();
            println!("{}:", "Errors".red());
            for (provider, error) in &report.errors {
                println!("  {} - {}", provider, error);
            }
        }

        if report.migrated > 0 {
            println!();
            println!(
                "{}",
                "NOTE: You can now remove these env vars from your shell config.".yellow()
            );
        }
    }
    #[cfg(not(feature = "tui"))]
    if migrate_keys {
        println!(
            "{} Key migration requires TUI feature. Use: cargo build --features tui",
            "Warning:".yellow()
        );
    }

    Ok(())
}