kandil_code 2.1.1

Intelligent development platform (CLI + TUI + Multi-Agent System) with cross-platform AI model benchmarking, system diagnostics, and advanced development tools
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
use crate::{
    enhanced_ui::{
        adaptive::AdaptiveUI,
        ide_sync::IdeSync,
        input::{InputMethod, UniversalInput},
        persona::PersonaProfile,
        predictive::PredictiveExecutor,
        smart_prompt::{PipelineStage, SmartPrompt},
        splash::{self, CommandContext, SplashResult},
        terminal::KandilTerminal,
        thought::{OutputMode, ThoughtFragment, ThoughtStreamer},
    },
    mobile::MobileBridge,
};
use anyhow::Result;
use futures_util;
use std::{collections::VecDeque, env, sync::Arc, time::Duration};

#[derive(Default)]
pub struct KandilPrompt {
    mode: PromptMode,
}

impl KandilPrompt {
    fn render(&self) -> String {
        match self.mode {
            PromptMode::Chat => "🤖 ".to_string(),
            PromptMode::Shell => "".to_string(),
        }
    }

    fn set_mode(&mut self, mode: PromptMode) {
        self.mode = mode;
    }
}

#[derive(Default, Copy, Clone)]
pub enum PromptMode {
    #[default]
    Chat,
    Shell,
}

pub async fn run_repl() -> Result<()> {
    let terminal = Arc::new(KandilTerminal::new()?);
    let mut context = CommandContext::new(terminal.clone());
    let mut prompt = KandilPrompt::default();
    let mut universal_input = UniversalInput::new()?;
    let adaptive_ui = AdaptiveUI::from_system();
    let ide_sync = IdeSync::new();
    if let Err(e) = ide_sync.start_language_server(env::current_dir()?).await {
        eprintln!("Warning: Failed to start language server: {}", e);
    }
    let mobile_bridge = MobileBridge::new()?;
    let mut predictive_executor = PredictiveExecutor::new();
    let thought_streamer = ThoughtStreamer::with_output_mode(OutputMode::Streaming);
    let mut persona_profile = PersonaProfile::from_history(&context.recent_commands);

    println!("Kandil Shell initialized. Type /help for splash commands.");

    // Display UI capabilities based on hardware and accessibility settings
    println!(
        "UI Capabilities: {}",
        adaptive_ui.capabilities_description()
    );
    if adaptive_ui.should_enhance_accessibility() {
        println!(
            "Accessibility features enabled: {:?}",
            adaptive_ui.accessibility_mode()
        );
    }

    loop {
        // Enhance context detection before input processing
        context.refresh_project_context();
        context.refresh_file_context().await;
        context.refresh_git_status().await;

        let input = if let Some(remote) = mobile_bridge.try_voice_command()? {
            adaptive_ui.announce("status", "📱 Remote command received");
            remote
        } else {
            match universal_input.read(&prompt.render())? {
                InputMethod::Text(text) => text,
                InputMethod::Voice(transcript) => {
                    adaptive_ui.announce("status", "🎙️ Voice input detected");
                    transcript
                }
                InputMethod::Image(description) => {
                    adaptive_ui.announce("status", "🖼️ Image input routed to /ask");
                    format!("/ask {}", description)
                }
                InputMethod::Gesture(action) => {
                    adaptive_ui.announce("status", "🖐️ Gesture input mapped to /ask");
                    format!("/ask {}", action)
                }
                InputMethod::Modal(content) => {
                    adaptive_ui.announce("status", "🎛️ Modal input mapped to text");
                    content
                }
            }
        };

        let trimmed = input.trim();
        if trimmed.is_empty() {
            continue;
        }

        if trimmed == "exit" || trimmed == "quit" {
            break;
        }

        universal_input.add_history(trimmed)?;

        if handle_special_input(trimmed, &terminal, &mut context, Some(&thought_streamer)).await? {
            continue;
        }

        thought_streamer.emit(ThoughtFragment::Context(format!("Input `{}`", trimmed)));

        // Use enhanced prefetching with async capabilities
        if predictive_executor.should_prefetch() {
            predictive_executor.prefetch(trimmed);
            predictive_executor.mark_prefetch_time();

            // In a real implementation, we might also call prefetch_async here
            // tokio::spawn(async move {
            //     let _ = predictive_executor.prefetch_async(trimmed).await;
            // });
        }

        // Enhanced context-aware command parsing
        let parsed = parse_command_enhanced(trimmed, &context).await;
        if let Err(err) = execute_command(
            parsed,
            &terminal,
            &mut context,
            &mut prompt,
            &adaptive_ui,
            &thought_streamer,
        )
        .await
        {
            eprintln!("Command error: {}", err);
        }

        context.remember_command(trimmed);
        context.refresh_project_context();
        context.refresh_file_context().await; // Refresh file context after execution
        context
            .job_tracker
            .auto_complete_elapsed(Duration::from_secs(45));
        let job_snapshot = context.job_tracker.snapshot();
        predictive_executor.observe(trimmed);
        show_contextual_hint(&context, &adaptive_ui);
        if let Some(hint) = predictive_executor.predict_hint() {
            println!("🔮 Prediction: {}", hint);
        }

        // Display ghost text information if available
        if let Some(ghost) = predictive_executor.get_ghost_text() {
            if ghost.confidence > 0.5 {
                println!(
                    "👻 Ghost text suggestion: {} (confidence: {:.1})",
                    ghost.text, ghost.confidence
                );
            }
        }
        mobile_bridge.sync_jobs(&job_snapshot);
        let updated_profile = PersonaProfile::from_history(&context.recent_commands);
        if updated_profile.persona != persona_profile.persona {
            adaptive_ui.announce("persona", &updated_profile.greeting);
            persona_profile = updated_profile;
        } else {
            // Update the current profile with the new command
            let mut temp_profile = persona_profile.clone();
            if let Some(last_command) = context.recent_commands.back() {
                temp_profile.update_with_command(last_command);
            }
            persona_profile = temp_profile;
        }

        // Adjust behavior based on persona preferences
        match persona_profile.preferences.project_focus {
            crate::enhanced_ui::persona::ProjectFocus::Frontend => {
                if persona_profile.confidence > 0.7 {
                    // Provide frontend-specific hints or auto-completions
                }
            }
            crate::enhanced_ui::persona::ProjectFocus::Backend => {
                if persona_profile.confidence > 0.7 {
                    // Provide backend-specific hints
                }
            }
            crate::enhanced_ui::persona::ProjectFocus::Testing => {
                if persona_profile.confidence > 0.7 && predictive_executor.should_prefetch() {
                    // Prefetch testing resources more aggressively
                    predictive_executor.prefetch("/test");
                    predictive_executor.mark_prefetch_time();
                }
            }
            _ => {}
        }
    }

    println!("👋 Goodbye!");
    Ok(())
}

async fn handle_special_input(
    input: &str,
    terminal: &Arc<KandilTerminal>,
    context: &mut CommandContext,
    thought_streamer: Option<&ThoughtStreamer>,
) -> Result<bool> {
    match input {
        "/help" => {
            print_help();
            Ok(true)
        }
        "/clear" => {
            terminal.clear_screen()?;
            Ok(true)
        }
        "/reset" => {
            terminal.reset_context().await?;
            context.job_tracker.complete_all();
            println!("🔄 Context reset");
            Ok(true)
        }
        "/thoughts" => {
            if let Some(thinker) = thought_streamer {
                println!("💡 Recent thoughts:");
                let recent = thinker.get_recent_thoughts(5);
                for thought in &recent {
                    match &thought.fragment {
                        ThoughtFragment::Action(msg) => println!("  ⚙️  Action: {}", msg),
                        ThoughtFragment::Result(msg) => println!("  ✅ Result: {}", msg),
                        ThoughtFragment::Insight(msg) => println!("  💡 Insight: {}", msg),
                        ThoughtFragment::Hypothesis(msg) => println!("  🧠 Hypothesis: {}", msg),
                        ThoughtFragment::Context(msg) => println!("  📚 Context: {}", msg),
                        ThoughtFragment::Process(msg) => println!("  🔄 Process: {}", msg),
                        ThoughtFragment::Question(msg) => println!("  ❓ Question: {}", msg),
                    }
                }

                if recent.is_empty() {
                    println!("  No recent thoughts to display");
                }
            } else {
                println!("  No thought streamer available");
            }
            Ok(true)
        }
        "exit" | "quit" => Ok(false),
        _ => {
            // Handle other splash commands
            if input.starts_with('/') {
                let mut parts = input.split_whitespace();
                let trigger = parts.next().unwrap_or("");
                let args: Vec<String> = parts.map(|p| p.to_string()).collect();
                let result = splash::execute_splash_command(trigger, &args, context).await?;
                if let Some(message) = result.message {
                    println!("{}", message);
                }
                Ok(true)
            } else {
                Ok(false)
            }
        }
    }
}

fn parse_command(input: &str) -> Command {
    if input.contains('|') {
        let stages = input
            .split('|')
            .map(|segment| parse_single_command(segment.trim()))
            .collect();
        Command::Pipeline(stages)
    } else {
        parse_single_command(input)
    }
}

async fn parse_command_enhanced(input: &str, context: &CommandContext) -> Command {
    // First try the normal parsing
    let basic_command = parse_single_command(input);

    // Apply context-aware enhancements
    match &basic_command {
        Command::Splash { trigger, args } => {
            // Enhance splash command with context
            let enhanced_args = enhance_args_with_context(trigger, args, context).await;
            Command::Splash {
                trigger: trigger.clone(),
                args: enhanced_args,
            }
        }
        Command::Shell(cmd) => {
            // Potentially enhance shell command with context
            Command::Shell(cmd.clone())
        }
        Command::NaturalLanguage(query) => {
            // Potentially enhance natural language with context
            Command::NaturalLanguage(query.clone())
        }
        Command::Pipeline(commands) => {
            // Enhance pipeline commands recursively
            let enhanced_commands: Vec<Command> = futures_util::future::join_all(
                commands
                    .iter()
                    .map(|cmd| enhance_command_with_context(cmd, context)),
            )
            .await;
            Command::Pipeline(enhanced_commands)
        }
    }
}

fn parse_single_command(input: &str) -> Command {
    if input.contains('|') {
        let stages = input
            .split('|')
            .map(|segment| parse_single_command(segment.trim()))
            .collect();
        Command::Pipeline(stages)
    } else if input.starts_with('/') {
        let mut parts = input.split_whitespace();
        let trigger = parts.next().unwrap_or("").to_string();
        let args = parts.map(|p| p.to_string()).collect();
        Command::Splash { trigger, args }
    } else if looks_like_natural_language(input) {
        Command::NaturalLanguage(input.to_string())
    } else {
        Command::Shell(input.to_string())
    }
}

async fn enhance_args_with_context(
    trigger: &str,
    args: &[String],
    context: &CommandContext,
) -> Vec<String> {
    // Add context-aware enhancements to arguments
    let mut enhanced_args = args.to_vec();

    // For /test command, automatically target the active file if no target is specified
    if trigger == "/test" && enhanced_args.is_empty() {
        if let Some(active_file) = &context.active_file {
            enhanced_args.push(active_file.to_string_lossy().to_string());
        }
    }

    // For /fix command, add context about current errors if any
    if trigger == "/fix" && context.project_context.errors > 0 {
        // In a real implementation, this could add specific file targets based on detected errors
    }

    // For /review command, automatically target the active file if no target is specified
    if trigger == "/review" && enhanced_args.is_empty() {
        if let Some(active_file) = &context.active_file {
            enhanced_args.push(active_file.to_string_lossy().to_string());
        }
    }

    enhanced_args
}

async fn enhance_command_with_context(command: &Command, context: &CommandContext) -> Command {
    match command {
        Command::Splash { trigger, args } => {
            let enhanced_args = enhance_args_with_context(trigger, args, context).await;
            Command::Splash {
                trigger: trigger.clone(),
                args: enhanced_args,
            }
        }
        _ => command.clone(),
    }
}

fn looks_like_natural_language(input: &str) -> bool {
    input.ends_with('?') || input.split_whitespace().count() > 7
}

fn emit_result(result: SplashResult, adaptive_ui: &AdaptiveUI) {
    if let Some(message) = result.message {
        adaptive_ui.announce("status", &message);
    }
}

fn show_contextual_hint(ctx: &CommandContext, adaptive_ui: &AdaptiveUI) {
    if ctx.recent_commands.is_empty() {
        return;
    }
    if !adaptive_ui.should_rich_render() {
        return;
    }
    let latest = ctx.recent_commands.back().unwrap();
    if latest.starts_with('/') {
        println!("Hint: try chaining {} with shell commands.", latest);
    } else {
        let suggestions = ctx.contextual_suggestions();
        if !suggestions.is_empty() {
            let labels: Vec<&str> = suggestions.into_iter().collect();
            println!("💡 Try splash commands: {}", labels.join(", "));
        }
    }
}

#[derive(Clone)]
enum Command {
    Splash { trigger: String, args: Vec<String> },
    Shell(String),
    NaturalLanguage(String),
    Pipeline(Vec<Command>),
}

async fn execute_command(
    command: Command,
    terminal: &Arc<KandilTerminal>,
    context: &mut CommandContext,
    prompt: &mut KandilPrompt,
    adaptive_ui: &AdaptiveUI,
    thought_streamer: &ThoughtStreamer,
) -> Result<()> {
    match command {
        Command::Pipeline(commands) => {
            // Create detailed pipeline stages for better visualization
            let mut stages = Vec::new();
            for (i, cmd) in commands.iter().enumerate() {
                let stage = PipelineStage::new(&format!("Stage {}", i + 1), &command_label(cmd))
                    .with_description(&match cmd {
                        Command::Splash { trigger, .. } => {
                            format!("Splash command: {}", trigger)
                        }
                        Command::Shell(cmd_str) => format!("Shell command: {}", cmd_str),
                        Command::NaturalLanguage(_) => "Natural language query".to_string(),
                        Command::Pipeline(_) => "Nested pipeline".to_string(),
                    })
                    .with_duration(Duration::from_secs((i + 1) as u64 * 2)); // Estimate duration based on stage number

                stages.push(stage);
            }

            println!("{}", SmartPrompt::pipeline_summary_detailed(&stages)); // Fixed: borrowed instead of moved

            for cmd in flatten_pipeline(commands) {
                handle_basic_command(
                    cmd,
                    terminal,
                    context,
                    prompt,
                    adaptive_ui,
                    thought_streamer,
                )
                .await?;
            }
            Ok(())
        }
        other => {
            handle_basic_command(
                other,
                terminal,
                context,
                prompt,
                adaptive_ui,
                thought_streamer,
            )
            .await
        }
    }
}

fn command_label(command: &Command) -> String {
    match command {
        Command::Splash { trigger, .. } => trigger.clone(),
        Command::Shell(cmd) => cmd.clone(),
        Command::NaturalLanguage(_) => "chat".to_string(),
        Command::Pipeline(stages) => format!(
            "pipeline({})",
            stages
                .iter()
                .map(|stage| match stage {
                    Command::Splash { trigger, .. } => trigger.clone(),
                    Command::Shell(cmd) => cmd.clone(),
                    Command::NaturalLanguage(_) => "chat".to_string(),
                    Command::Pipeline(_) => "pipeline".to_string(),
                })
                .collect::<Vec<_>>()
                .join(", ")
        ),
    }
}

async fn handle_basic_command(
    command: Command,
    terminal: &Arc<KandilTerminal>,
    context: &mut CommandContext,
    prompt: &mut KandilPrompt,
    adaptive_ui: &AdaptiveUI,
    thought_streamer: &ThoughtStreamer,
) -> Result<()> {
    match command {
        Command::Splash { trigger, args } => {
            prompt.set_mode(PromptMode::Chat);
            thought_streamer.emit(ThoughtFragment::Hypothesis(format!(
                "Executing splash {}",
                trigger
            )));
            let result = splash::execute_splash_command(&trigger, &args, context).await?;
            emit_result(result, adaptive_ui);
            thought_streamer.emit(ThoughtFragment::Result(format!("Completed {}", trigger)));
            Ok(())
        }
        Command::Shell(cmd) => {
            prompt.set_mode(PromptMode::Shell);
            thought_streamer.emit(ThoughtFragment::Action(format!("Running {}", cmd)));
            let result = terminal.execute(&cmd, false).await?;
            if !result.stdout.is_empty() {
                print!("{}", result.stdout);
            }
            if let Some(analysis) = result.ai_analysis {
                println!("\n{}", analysis);
            }
            thought_streamer.emit(ThoughtFragment::Result(format!("Command {} finished", cmd)));
            Ok(())
        }
        Command::NaturalLanguage(query) => {
            prompt.set_mode(PromptMode::Chat);
            emit_result(
                SplashResult {
                    message: Some(format!("💬 {}", query)),
                },
                adaptive_ui,
            );
            thought_streamer.emit(ThoughtFragment::Result("Answered chat query".into()));
            Ok(())
        }
        Command::Pipeline(_) => {
            unreachable!("Nested pipelines should be flattened before execution");
        }
    }
}

fn flatten_pipeline(commands: Vec<Command>) -> Vec<Command> {
    let mut flat = Vec::new();
    let mut queue: VecDeque<Command> = commands.into();
    while let Some(cmd) = queue.pop_front() {
        match cmd {
            Command::Pipeline(inner) => {
                for stage in inner.into_iter().rev() {
                    queue.push_front(stage);
                }
            }
            other => flat.push(other),
        }
    }
    flat
}

fn print_help() {
    println!("Available splash commands:");
    for cmd in splash::SPLASH_COMMANDS.iter() {
        println!("  {:<10} {}", cmd.trigger, cmd.description);
    }
    println!("\nSpecial commands:");
    println!("  {:<10} {}", "/help", "Show this help message");
    println!("  {:<10} {}", "/clear", "Clear the terminal screen");
    println!("  {:<10} {}", "/reset", "Reset the command context");
    println!(
        "  {:<10} {}",
        "/thoughts", "Display recent thoughts from AI reasoning"
    );
    println!(
        "\nKandil Shell adapts to your development persona and provides contextual assistance."
    );
    println!("Use standard shell commands without '/' prefix.");
}

async fn handle_splash(input: &str, ctx: &mut CommandContext) -> Result<SplashResult> {
    let mut parts = input.split_whitespace();
    let trigger = parts.next().unwrap_or("");
    let args: Vec<String> = parts.map(|p| p.to_string()).collect();
    splash::execute_splash_command(trigger, &args, ctx).await
}