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
//! Terminal User Interface Module
//!
//! Feature-gated TUI with 3-view architecture.
//!
//! # Entry Points
//!
//! - `nika` → Studio view (3-panel: Browser | Editor | DAG)
//! - `nika chat` → Command view (Chat mode)
//! - `nika studio` → Studio view (YAML editor)
//! - `nika workflow.yaml` → Command view (Monitor mode)
//!
//! # 3-View Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  [1] Studio  │ [2] Command │ [3] Control                       │
//! ├─────────────────────────────────────────────────────────────────┤
//! │                                                                 │
//! │  Studio:    3-panel layout (Browser | Editor | DAG Preview)    │
//! │  Command:   Chat + Monitor modes (Ctrl+M to toggle)           │
//! │  Control:   Configuration and preferences                      │
//! │                                                                 │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Navigation
//!
//! - `1-3` - Switch views (Normal mode)
//! - `?` - Show help
//! - `Ctrl+C` (2x) - Quit
//!
//! # Panic Recovery
//!
//! The TUI installs a panic hook to restore terminal state on crashes.
//! Crash logs are written to `~/.nika/crash.log`.

#[cfg(feature = "tui")]
mod app;
#[cfg(feature = "tui")]
mod cache;
#[cfg(feature = "tui")]
pub mod chat_agent;
#[cfg(feature = "tui")]
pub mod command;
#[cfg(feature = "tui")]
pub mod config;
#[cfg(feature = "tui")]
mod cosmic_theme;
#[cfg(feature = "tui")]
pub mod diagnostics;
#[cfg(feature = "tui")]
mod edit_history;
#[cfg(feature = "tui")]
pub mod file_resolve;
#[cfg(feature = "tui")]
mod focus;
#[cfg(feature = "tui")]
pub mod git; // Git integration for gutter + file status
#[cfg(feature = "tui")]
pub mod highlight;
#[cfg(feature = "tui")]
pub mod icons;
#[cfg(feature = "tui")]
mod keybindings;
#[cfg(feature = "tui")]
mod layout;
#[cfg(feature = "tui")]
mod mode;
#[cfg(feature = "tui")]
pub mod providers;
#[cfg(feature = "tui")]
pub mod selection;
#[cfg(feature = "tui")]
pub mod session;
#[cfg(feature = "tui")]
mod standalone;
#[cfg(feature = "tui")]
pub mod startup;
#[cfg(feature = "tui")]
mod state;
#[cfg(feature = "tui")]
mod theme;
#[cfg(feature = "tui")]
pub mod tokens;
#[cfg(feature = "tui")]
mod unicode;
#[cfg(feature = "tui")]
mod utils;
#[cfg(feature = "tui")]
mod verification;
#[cfg(feature = "tui")]
mod views;
#[cfg(feature = "tui")]
pub mod widgets;
#[cfg(feature = "tui")]
pub mod wizard;

#[cfg(feature = "tui")]
pub use app::App;
#[cfg(feature = "tui")]
pub use cache::RenderCache;
#[cfg(feature = "tui")]
pub use chat_agent::{ChatAgent, ChatMessage, ChatRole, StreamingState};
#[cfg(feature = "tui")]
pub use command::{Command, HELP_TEXT};
#[cfg(feature = "tui")]
pub use config::{
    ChatSettings, ConfigError, PathSettings, StudioSettings, ThemeName, TuiConfig, TuiSettings,
};
#[cfg(feature = "tui")]
pub use cosmic_theme::CosmicTheme;
#[cfg(feature = "tui")]
pub use edit_history::EditHistory;
#[cfg(feature = "tui")]
pub use file_resolve::FileResolver;
#[cfg(feature = "tui")]
pub use focus::{FocusState, PanelId as NavPanelId};
#[cfg(feature = "tui")]
pub use highlight::{
    HighlightCapture, HighlightTheme, Highlighter, SolarizedTheme, TreeSitterHighlighter,
};
#[cfg(feature = "tui")]
pub use icons::{IconMode, IconSet};
#[cfg(feature = "tui")]
pub use keybindings::{format_key, keybindings_for_context, KeyCategory, Keybinding};
#[cfg(feature = "tui")]
pub use layout::{LayoutMode, ResponsiveLayout};
#[cfg(feature = "tui")]
pub use mode::InputMode;
#[cfg(feature = "tui")]
pub use selection::{Position, Selection, SelectionMode, SelectionSet};
#[cfg(feature = "tui")]
pub use session::{
    delete_session, get_latest_session, list_sessions, load_session, save_session, ChatSession,
    SessionMeta,
};
#[cfg(feature = "tui")]
pub use standalone::{BrowserEntry, HistoryEntry, StandalonePanel, StandaloneState};
#[cfg(feature = "tui")]
pub use state::{
    // Animation frame constants
    AgentTurnState,
    PanelId,
    PanelScrollState,
    TuiMode,
    TuiState,
    FRAME_CYCLE,
    FRAME_DIV_GLACIAL,
    FRAME_DIV_NORMAL,
};
#[cfg(feature = "tui")]
pub use theme::{ColorMode, MissionPhase, TaskStatus, Theme, VerbColor};
#[cfg(feature = "tui")]
pub use tokens::{ColorPalette, CosmicVariant, SemanticColors, TokenResolver};
#[cfg(feature = "tui")]
pub use unicode::{display_width, truncate_to_width};
#[cfg(feature = "tui")]
pub use utils::{format_number, format_number_compact, format_number_u64};
#[cfg(feature = "tui")]
pub use verification::{VerificationCache, VerificationEntry};
#[cfg(feature = "tui")]
pub use views::{
    ChatView, DagTab, HomeView, MissionTab, MonitorView, NovanetTab, ReasoningTab, SettingsView,
    StudioView, TuiView, View, ViewAction, YamlEditorPanel,
};
#[cfg(feature = "tui")]
pub use wizard::{WizardConfig, WizardState, WizardStep};

/// Install panic hook to restore terminal state on crashes.
///
/// This function saves the original panic hook and wraps it with
/// terminal restoration logic. Crash logs are written to `~/.nika/crash.log`.
///
/// # Safety
///
/// This function should be called BEFORE entering raw mode.
/// It is safe to call multiple times (only installs once via std::sync::Once).
#[cfg(feature = "tui")]
fn install_panic_hook() {
    use std::io::Write;
    use std::panic;
    use std::sync::Once;

    use crossterm::{execute, terminal::LeaveAlternateScreen};

    static HOOK_INSTALLED: Once = Once::new();

    HOOK_INSTALLED.call_once(|| {
        let original_hook = panic::take_hook();

        panic::set_hook(Box::new(move |panic_info| {
            // 1. Restore terminal state FIRST (before any output)
            let _ = crossterm::terminal::disable_raw_mode();
            let _ = execute!(std::io::stdout(), LeaveAlternateScreen);

            // 2. Write crash log
            let crash_log_path = dirs::config_dir()
                .map(|d| d.join("nika").join("crash.log"))
                .unwrap_or_else(|| std::path::PathBuf::from("/tmp/nika-crash.log"));

            // Ensure parent directory exists
            if let Some(parent) = crash_log_path.parent() {
                let _ = std::fs::create_dir_all(parent);
            }

            if let Ok(mut f) = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(&crash_log_path)
            {
                let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S");
                let _ = writeln!(
                    f,
                    "\n══════════════════════════════════════════════════════════════"
                );
                let _ = writeln!(f, "NIKA CRASH: {}", timestamp);
                let _ = writeln!(
                    f,
                    "══════════════════════════════════════════════════════════════"
                );
                let _ = writeln!(f, "{}", panic_info);

                // Try to capture backtrace
                let backtrace = std::backtrace::Backtrace::capture();
                let _ = writeln!(f, "\nBacktrace:\n{}", backtrace);
            }

            // 3. Print user-friendly message to stderr
            eprintln!(
                "\n\x1b[31m╔══════════════════════════════════════════════════════════════╗\x1b[0m"
            );
            eprintln!(
                "\x1b[31m║  NIKA CRASHED - Terminal has been restored                    ║\x1b[0m"
            );
            eprintln!(
                "\x1b[31m╠══════════════════════════════════════════════════════════════╣\x1b[0m"
            );
            eprintln!(
                "\x1b[31m║  Crash log: {:49} ║\x1b[0m",
                crash_log_path.display()
            );
            eprintln!(
                "\x1b[31m║  Please report: https://github.com/SuperNovae-studio/nika    ║\x1b[0m"
            );
            eprintln!(
                "\x1b[31m╚══════════════════════════════════════════════════════════════╝\x1b[0m"
            );

            // 4. Call original hook
            original_hook(panic_info);
        }));
    });
}

/// Run the TUI for a workflow
///
/// This function:
/// 1. Parses and validates the workflow
/// 2. Creates an EventLog with broadcast channel
/// 3. Spawns the Runner in a background task
/// 4. Runs the TUI with real-time event updates
#[cfg(feature = "tui")]
pub async fn run_tui(workflow_path: &std::path::Path) -> crate::error::Result<()> {
    use crate::ast::parse_analyzed;
    use crate::event::EventLog;
    use crate::runtime::Runner;

    // Install panic hook for terminal recovery
    install_panic_hook();

    // 1. Parse and validate workflow (use tokio::fs for non-blocking I/O)
    let yaml_content = tokio::fs::read_to_string(workflow_path)
        .await
        .map_err(|e| crate::error::NikaError::WorkflowNotFound {
            path: format!("{}: {}", workflow_path.display(), e),
        })?;

    let workflow = parse_analyzed(&yaml_content)?;

    // 2. Create EventLog with broadcast channel for TUI
    let (event_log, event_rx) = EventLog::new_with_broadcast();

    // 3. Create Runner with the broadcast-enabled EventLog and quiet mode
    // quiet() suppresses console output that would interfere with the TUI
    let mut runner = Runner::with_event_log(workflow, event_log)?.quiet();

    // 4. Spawn Runner in background task
    let runner_handle = tokio::spawn(async move {
        match runner.run().await {
            Ok(output) => {
                tracing::info!("Workflow completed: {} bytes output", output.len());
            }
            Err(e) => {
                tracing::error!("Workflow failed: {}", e);
            }
        }
    });

    // 5. Create and run TUI with event receiver
    // Use run_unified() for the 3-view architecture (Studio/Command/Control)
    let app = App::new(workflow_path)?.with_broadcast_receiver(event_rx);
    let tui_result = app.run_unified().await.map(|_| ());

    // 6. Abort runner if TUI exits early (user pressed q)
    runner_handle.abort();

    tui_result
}

/// Run the TUI in standalone mode (file browser + history)
///
/// This function:
/// 1. Scans for .nika.yaml files in the project
/// 2. Shows file browser, history, and preview
/// 3. Allows user to select and run workflows
#[cfg(feature = "tui")]
pub async fn run_tui_standalone() -> crate::error::Result<()> {
    use views::WizardView;

    // First-run detection: if wizard hasn't been completed, offer to run it
    if !WizardView::was_completed() {
        // Check if we're in an interactive terminal
        use std::io::IsTerminal;
        if std::io::stdin().is_terminal() {
            use colored::Colorize;
            use std::io::{self, Write};

            println!();
            println!(
                "{}",
                "╔═══════════════════════════════════════════════════════════════╗".cyan()
            );
            println!(
                "{}",
                "║  🦋 Welcome to Nika!                                          ║".cyan()
            );
            println!(
                "{}",
                "║                                                               ║".cyan()
            );
            println!(
                "{}",
                "║  It looks like this is your first time running Nika.         ║".cyan()
            );
            println!(
                "{}",
                "║  Would you like to run the setup wizard?                      ║".cyan()
            );
            println!(
                "{}",
                "╚═══════════════════════════════════════════════════════════════╝".cyan()
            );
            println!();
            print!("{}", "Run setup wizard? [Y/n]: ".bold());
            io::stdout().flush().ok();

            let mut input = String::new();
            if io::stdin().read_line(&mut input).is_ok() {
                let input = input.trim().to_lowercase();
                if input.is_empty() || input == "y" || input == "yes" {
                    println!();
                    println!("{}", "Starting setup wizard...".dimmed());
                    println!();
                    // Run the wizard
                    run_tui_wizard().await?;
                    println!();
                    println!("{}", "Setup complete! Starting Nika...".green());
                    println!();
                }
            }
        }
    }

    // Install panic hook for terminal recovery
    install_panic_hook();

    // Find project root (look for Cargo.toml or .git)
    let root = find_project_root().unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

    // Create standalone state
    let state = StandaloneState::new(root);

    // Create and run standalone app with unified 3-view architecture
    // Starts in Studio view (3-panel: Browser | Editor | DAG)
    let app = App::new_standalone(state)?;
    let launch_wizard = app.run_unified().await?;

    // Check if wizard was requested from Settings view
    if launch_wizard {
        println!();
        run_tui_wizard().await?;
    }

    Ok(())
}

/// Run the TUI in Chat mode (conversational agent)
///
/// This is the entry point for `nika chat` command.
/// Starts directly in Chat view for conversational interactions.
///
/// # Arguments
///
/// * `provider` - Optional provider override ("claude" or "openai")
/// * `model` - Optional model override (e.g., "claude-sonnet-4-6")
#[cfg(feature = "tui")]
pub async fn run_tui_chat(
    provider: Option<String>,
    model: Option<String>,
) -> crate::error::Result<()> {
    use views::TuiView;

    // Install panic hook for terminal recovery
    install_panic_hook();

    // Find project root
    let root = find_project_root().unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

    // Create standalone state (Chat mode needs file context)
    let state = StandaloneState::new(root);

    // Create app with provider/model overrides
    let app = App::new_standalone(state)?
        .with_initial_view(TuiView::Command)
        .with_chat_overrides(provider, model);

    app.run_unified().await.map(|_| ())
}

/// Run the TUI in Studio mode (workflow editor)
///
/// This is the entry point for `nika studio [workflow]` command.
/// Starts directly in Studio view for YAML editing with live validation.
#[cfg(feature = "tui")]
pub async fn run_tui_studio(workflow: Option<std::path::PathBuf>) -> crate::error::Result<()> {
    use views::TuiView;

    // Install panic hook for terminal recovery
    install_panic_hook();

    // Find project root
    let root = find_project_root().unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

    // Create standalone state
    let state = StandaloneState::new(root.clone());

    // Create app and set initial view to Studio
    let mut app = App::new_standalone(state)?.with_initial_view(TuiView::Studio);

    // If workflow provided, load it into Editor view
    if let Some(path) = workflow {
        let full_path = if path.is_absolute() {
            path
        } else {
            root.join(path)
        };
        app = app.with_studio_file(full_path);
    }

    app.run_unified().await.map(|_| ())
}

/// Run the TUI with customizable options (view and workflow)
///
/// This is the entry point for `nika ui [--view <view>] [workflow]` command.
/// Supports all 3 views: Studio, Command, Control.
///
/// # Arguments
///
/// * `workflow` - Optional workflow file to load
/// * `initial_view` - Optional initial view (defaults to Studio)
#[cfg(feature = "tui")]
pub async fn run_tui_with_options(
    workflow: Option<std::path::PathBuf>,
    initial_view: Option<views::TuiView>,
) -> crate::error::Result<()> {
    // Install panic hook for terminal recovery
    install_panic_hook();

    // Find project root
    let root = find_project_root().unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

    // Create standalone state
    let state = StandaloneState::new(root.clone());

    // Create app with initial view (default to Studio)
    let mut app = App::new_standalone(state)?;

    if let Some(view) = initial_view {
        app = app.with_initial_view(view);
    }

    // If workflow provided and view is Editor/Runner, load it
    if let Some(path) = workflow {
        let full_path = if path.is_absolute() {
            path
        } else {
            root.join(path)
        };

        // Load file into Studio view
        app = app.with_studio_file(full_path);
    }

    app.run_unified().await.map(|_| ())
}

/// Find project root by looking for Cargo.toml or .git
#[cfg(feature = "tui")]
fn find_project_root() -> Option<std::path::PathBuf> {
    let mut current = std::env::current_dir().ok()?;

    loop {
        if current.join("Cargo.toml").exists() || current.join(".git").exists() {
            return Some(current);
        }
        if !current.pop() {
            return None;
        }
    }
}

#[cfg(not(feature = "tui"))]
pub async fn run_tui(_workflow_path: &std::path::Path) -> crate::error::Result<()> {
    Err(crate::error::NikaError::ValidationError {
        reason: "TUI feature not enabled. Rebuild with --features tui".to_string(),
    })
}

#[cfg(not(feature = "tui"))]
pub async fn run_tui_standalone() -> crate::error::Result<()> {
    Err(crate::error::NikaError::ValidationError {
        reason: "TUI feature not enabled. Rebuild with --features tui".to_string(),
    })
}

#[cfg(not(feature = "tui"))]
pub async fn run_tui_chat(
    _provider: Option<String>,
    _model: Option<String>,
) -> crate::error::Result<()> {
    Err(crate::error::NikaError::ValidationError {
        reason: "TUI feature not enabled. Rebuild with --features tui".to_string(),
    })
}

#[cfg(not(feature = "tui"))]
pub async fn run_tui_studio(_workflow: Option<std::path::PathBuf>) -> crate::error::Result<()> {
    Err(crate::error::NikaError::ValidationError {
        reason: "TUI feature not enabled. Rebuild with --features tui".to_string(),
    })
}

#[cfg(not(feature = "tui"))]
pub async fn run_tui_with_options(
    _workflow: Option<std::path::PathBuf>,
    _initial_view: Option<views::TuiView>,
) -> crate::error::Result<()> {
    Err(crate::error::NikaError::ValidationError {
        reason: "TUI feature not enabled. Rebuild with --features tui".to_string(),
    })
}

/// Run the TUI Setup Wizard (standalone)
///
/// This is the entry point for `nika setup` command.
/// Runs a full-screen setup wizard separate from the 3-view TUI.
#[cfg(feature = "tui")]
pub async fn run_tui_wizard() -> crate::error::Result<()> {
    use crossterm::{
        event::{self, Event, KeyEventKind},
        execute,
        terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
    };
    use ratatui::{backend::CrosstermBackend, Terminal};
    use std::io::stdout;

    use crate::tui::state::TuiState;
    use crate::tui::theme::Theme;
    use crate::tui::views::{View, ViewAction, WizardView};

    // Install panic hook for terminal recovery
    install_panic_hook();

    // Setup terminal
    enable_raw_mode().map_err(crate::error::NikaError::IoError)?;
    let mut stdout = stdout();
    execute!(stdout, EnterAlternateScreen).map_err(crate::error::NikaError::IoError)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend).map_err(crate::error::NikaError::IoError)?;

    // Create wizard view and state
    let mut wizard = WizardView::new();
    let mut tui_state = TuiState::new("wizard");
    let theme = Theme::default();

    // Main loop
    let result = loop {
        // Draw
        terminal
            .draw(|frame| {
                wizard.render(frame, frame.area(), &tui_state, &theme);
            })
            .map_err(crate::error::NikaError::IoError)?;

        // Handle events
        if event::poll(std::time::Duration::from_millis(100))
            .map_err(crate::error::NikaError::IoError)?
        {
            if let Event::Key(key) = event::read().map_err(crate::error::NikaError::IoError)? {
                // Only handle key press events
                if key.kind == KeyEventKind::Press {
                    match wizard.handle_key(key, &mut tui_state) {
                        ViewAction::Quit => break Ok(()),
                        ViewAction::Error(msg) => {
                            break Err(crate::error::NikaError::ValidationError { reason: msg })
                        }
                        _ => {}
                    }
                }
            }
        }
    };

    // Restore terminal
    disable_raw_mode().ok();
    execute!(terminal.backend_mut(), LeaveAlternateScreen).ok();
    terminal.show_cursor().ok();

    result
}

#[cfg(not(feature = "tui"))]
pub async fn run_tui_wizard() -> crate::error::Result<()> {
    Err(crate::error::NikaError::ValidationError {
        reason: "TUI feature not enabled. Rebuild with --features tui".to_string(),
    })
}