airust 0.1.8

A modular knowledge intelligence engine: lexical search, text matching, and explainable relation suggestions
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
// src/bin/airust.rs – Docker-style CLI
use airust::agent::{Agent, ContextualAgent, ResponseFormat, TrainableAgent, TrainingExample};
use airust::context_agent::ContextAgent;
use airust::knowledge::KnowledgeBase;
use airust::match_agent::MatchAgent;
use airust::tfidf_agent::TfidfAgent;
use std::env;
use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process;

const DEFAULT_PORT: u16 = 7070;
const PID_FILE: &str = "/tmp/airust.pid";

fn main() {
    let args: Vec<String> = env::args().collect();
    if args
        .get(1)
        .is_some_and(|arg| matches!(arg.as_str(), "--version" | "-V"))
    {
        println!("{}", airust::version_info());
        return;
    }

    let mut port: u16 = DEFAULT_PORT;
    let mut detached = false;
    let mut is_daemon = false;
    let mut show_landing = false;
    let mut command: Option<String> = None;
    let mut cli_args_start = args.len();
    let mut i = 1;

    while i < args.len() {
        match args[i].as_str() {
            "--_daemon" => is_daemon = true,
            "-d" => detached = true,
            "--landingpage" => show_landing = true,
            "--port" => {
                if i + 1 < args.len() {
                    port = args[i + 1].parse().unwrap_or_else(|_| {
                        eprintln!("Invalid port: {}", args[i + 1]);
                        process::exit(1);
                    });
                    if port == 0 || port == u16::MAX {
                        eprintln!("Port must be between 1 and 65534 (console uses port+1)");
                        process::exit(1);
                    }
                    i += 1;
                } else {
                    eprintln!("--port requires a value");
                    process::exit(1);
                }
            }
            "stop" | "cli" | "help" if command.is_none() => {
                command = Some(args[i].clone());
                cli_args_start = i + 1;
            }
            "-h" | "--help" => {
                command = Some("help".to_string());
            }
            _ => {
                if command.is_none() {
                    eprintln!("Unknown command: {}", args[i]);
                    print_help();
                    return;
                }
            }
        }
        i += 1;
    }

    #[cfg(not(feature = "web"))]
    let _ = (port, detached, show_landing);

    // Internal daemon mode (used by -d to respawn)
    if is_daemon {
        #[cfg(feature = "web")]
        run_web_server(port, show_landing);
        return;
    }

    match command.as_deref() {
        Some("stop") => stop_server(),
        Some("cli") => handle_cli(&args[cli_args_start..]),
        Some("help") => print_help(),
        None => {
            #[cfg(feature = "web")]
            {
                if detached {
                    start_detached(port, show_landing);
                } else {
                    run_web_server(port, show_landing);
                }
            }
            #[cfg(not(feature = "web"))]
            {
                print_help();
            }
        }
        _ => print_help(),
    }
}

// ── Web Server ────────────────────────────────────────────────────────────────

#[cfg(feature = "web")]
fn run_web_server(port: u16, show_landing: bool) {
    if is_server_running() {
        eprintln!("AIRust is already running. Use 'airust stop' first.");
        process::exit(1);
    }

    let pid = process::id();
    fs::write(PID_FILE, pid.to_string()).ok();

    tokio::runtime::Runtime::new()
        .expect("Failed to create Tokio runtime")
        .block_on(airust::web::start_server(port, show_landing));

    fs::remove_file(PID_FILE).ok();
}

#[cfg(feature = "web")]
fn start_detached(port: u16, show_landing: bool) {
    if is_server_running() {
        eprintln!("AIRust is already running. Use 'airust stop' first.");
        process::exit(1);
    }

    let exe = env::current_exe().expect("Failed to get executable path");

    let log_file = fs::File::create("/tmp/airust.log").expect("Failed to create log file");
    let err_file = log_file.try_clone().expect("Failed to clone log file");

    let mut daemon_args = vec![
        "--_daemon".to_string(),
        "--port".to_string(),
        port.to_string(),
    ];
    if show_landing {
        daemon_args.push("--landingpage".to_string());
    }

    let mut child = process::Command::new(exe)
        .args(&daemon_args)
        .stdout(log_file)
        .stderr(err_file)
        .stdin(process::Stdio::null())
        .spawn()
        .expect("Failed to start server");

    let pid = child.id();
    // Detach child so it doesn't become a zombie
    std::thread::spawn(move || {
        let _ = child.wait();
    });
    fs::write(PID_FILE, pid.to_string()).ok();

    println!("AIRust running at http://localhost:{}", port);
    println!("  PID:  {}", pid);
    println!("  Logs: /tmp/airust.log");
    println!("  Stop: airust stop");
}

fn stop_server() {
    match fs::read_to_string(PID_FILE) {
        Ok(pid_str) => {
            let pid = pid_str.trim().to_string();
            match process::Command::new("kill").arg(&pid).status() {
                Ok(s) if s.success() => {
                    fs::remove_file(PID_FILE).ok();
                    println!("AIRust stopped (PID: {})", pid);
                }
                _ => {
                    fs::remove_file(PID_FILE).ok();
                    eprintln!("Process {} not found (cleaned up)", pid);
                }
            }
        }
        Err(_) => eprintln!("No running AIRust server found."),
    }
}

#[cfg(feature = "web")]
fn is_server_running() -> bool {
    if let Ok(pid_str) = fs::read_to_string(PID_FILE) {
        let pid = pid_str.trim();
        // Don't consider our own process as "already running"
        if pid == process::id().to_string() {
            return false;
        }
        if let Ok(status) = process::Command::new("kill")
            .args(["-0", pid])
            .stderr(process::Stdio::null())
            .status()
        {
            if status.success() {
                return true;
            }
        }
        fs::remove_file(PID_FILE).ok();
    }
    false
}

// ── CLI Mode ──────────────────────────────────────────────────────────────────

fn handle_cli(args: &[String]) {
    if args.is_empty() {
        run_interactive_mode();
        return;
    }

    match args[0].as_str() {
        "query" => {
            if args.len() < 3 {
                eprintln!("Usage: airust cli query <agent> <question>");
                eprintln!("Agents: simple, fuzzy, tfidf, context");
                return;
            }
            handle_query(&args[1], &args[2..].join(" "));
        }
        "interactive" => run_interactive_mode(),
        "knowledge" => run_knowledge_management(),
        _ => {
            eprintln!("Unknown CLI command: {}", args[0]);
            eprintln!("Available: query, interactive, knowledge");
        }
    }
}

fn print_help() {
    println!(
        "{} — Modular Knowledge Intelligence Engine",
        airust::version_info()
    );
    println!(
        "Web dashboard: compile with --features web; library example: cargo run --example core"
    );
    println!();
    println!("Usage:");
    println!(
        "  airust                 Start web server (port {})",
        DEFAULT_PORT
    );
    println!("  airust --port <PORT>   Start on specific port");
    println!("  airust -d              Start in background (detached)");
    println!("  airust --landingpage   Show landing page + dashboard");
    println!("  airust stop            Stop background server");
    println!("  airust cli             Interactive CLI mode");
    println!("  airust help            Show this help");
    println!();
    println!("CLI subcommands:");
    println!("  airust cli query <agent> <question>");
    println!("  airust cli knowledge");
    println!();
    println!("Agents: simple, fuzzy, tfidf, context");
}

// ── Query & Interactive ───────────────────────────────────────────────────────

fn handle_query(agent_type: &str, question: &str) {
    let kb = KnowledgeBase::from_embedded();
    let examples = kb.get_examples();

    let answer = match agent_type {
        "simple" => {
            let mut agent = MatchAgent::new_exact();
            agent.train(examples);
            agent.predict(question)
        }
        "fuzzy" => {
            let mut agent = MatchAgent::new_fuzzy();
            agent.train(examples);
            agent.predict(question)
        }
        "tfidf" => {
            let mut agent = TfidfAgent::new();
            agent.train(examples);
            agent.predict(question)
        }
        "context" => {
            let mut base_agent = TfidfAgent::new();
            base_agent.train(examples);
            let agent = ContextAgent::new(base_agent, 3);
            agent.predict(question)
        }
        _ => ResponseFormat::Text(format!("Unknown agent type: {}", agent_type)),
    };

    println!("Answer: {}", String::from(answer));
}

fn run_interactive_mode() {
    println!("=== Interactive Mode ===");
    println!("Select an agent type:");
    println!("1. Exact (SimpleAgent)");
    println!("2. Fuzzy (FuzzyAgent)");
    println!("3. TFIDF (TfidfAgent)");
    println!("4. Context (ContextAgent)");
    print!("> ");
    let _ = io::stdout().flush();

    let mut input = String::new();
    let _ = io::stdin().read_line(&mut input);
    let choice = input.trim();

    let kb = KnowledgeBase::from_embedded();
    let examples = kb.get_examples();

    match choice {
        "1" => {
            let mut a = MatchAgent::new_exact();
            a.train(examples);
            interactive_loop(&a, "Exact Matching Agent");
        }
        "2" => {
            let mut a = MatchAgent::new_fuzzy();
            a.train(examples);
            interactive_loop(&a, "Fuzzy Matching Agent");
        }
        "3" => {
            let mut a = TfidfAgent::new();
            a.train(examples);
            interactive_loop(&a, "TFIDF Agent (BM25)");
        }
        "4" => interactive_loop_context(examples),
        _ => println!("Invalid selection. Please restart the program."),
    }
}

fn interactive_loop(agent: &impl Agent, name: &str) {
    println!("=== {} ===", name);
    println!("Enter questions or 'exit' to quit.");

    loop {
        print!("> ");
        let _ = io::stdout().flush();

        let mut input = String::new();
        if io::stdin().read_line(&mut input).is_err() {
            break;
        }
        let input = input.trim();

        if input.is_empty() || input.to_lowercase() == "exit" {
            break;
        }

        let answer = agent.predict(input);
        println!("Answer: {}", String::from(answer));
    }
}

fn interactive_loop_context(examples: &[TrainingExample]) {
    println!("=== Context Agent ===");
    println!("Enter questions or 'exit' to quit.");

    let mut base = TfidfAgent::new();
    base.train(examples);
    let mut agent = ContextAgent::new(base, 3);

    loop {
        print!("> ");
        let _ = io::stdout().flush();

        let mut input = String::new();
        if io::stdin().read_line(&mut input).is_err() {
            break;
        }
        let input = input.trim();

        if input.is_empty() || input.to_lowercase() == "exit" {
            break;
        }

        let answer = agent.predict(input);
        println!("Answer: {}", String::from(answer.clone()));
        agent.add_context(input.to_string(), answer);
    }
}

// ── Knowledge Management ──────────────────────────────────────────────────────

fn run_knowledge_management() {
    println!("=== Knowledge Base Management ===");
    println!("1. Create new knowledge base");
    println!("2. Load knowledge base");
    println!("3. Back");
    print!("> ");
    let _ = io::stdout().flush();

    let mut input = String::new();
    let _ = io::stdin().read_line(&mut input);
    let choice = input.trim();

    match choice {
        "1" => create_knowledge_base(),
        "2" => load_knowledge_base(),
        _ => (),
    }
}

fn create_knowledge_base() {
    let mut kb = KnowledgeBase::new();

    println!("=== Create New Knowledge Base ===");
    println!("Enter examples. Press Enter without input to finish.");

    loop {
        println!("\nNew example:");
        print!("Question: ");
        let _ = io::stdout().flush();

        let mut input = String::new();
        let _ = io::stdin().read_line(&mut input);
        let input = input.trim();

        if input.is_empty() {
            break;
        }

        print!("Answer: ");
        let _ = io::stdout().flush();

        let mut output = String::new();
        let _ = io::stdin().read_line(&mut output);
        let output = output.trim();

        print!("Weight (Default 1.0): ");
        let _ = io::stdout().flush();

        let mut weight_str = String::new();
        let _ = io::stdin().read_line(&mut weight_str);
        let weight_str = weight_str.trim();

        let weight = if weight_str.is_empty() {
            1.0
        } else {
            weight_str.parse::<f32>().unwrap_or(1.0)
        };

        kb.add_example(
            input.to_string(),
            ResponseFormat::Text(output.to_string()),
            weight,
        );
        println!("Example added!");
    }

    println!("\nEnter path to save:");
    print!("> ");
    let _ = io::stdout().flush();

    let mut path_str = String::new();
    let _ = io::stdin().read_line(&mut path_str);
    let path_str = path_str.trim();

    if path_str.is_empty() {
        println!("No path specified. Aborting.");
        return;
    }

    let path = PathBuf::from(path_str);
    match kb.save(Some(path.clone())) {
        Ok(_) => {
            println!("Knowledge base saved to {:?}", path);
            println!("Would you like to test the knowledge base? (y/n)");
            print!("> ");
            let _ = io::stdout().flush();

            let mut test = String::new();
            let _ = io::stdin().read_line(&mut test);
            let test = test.trim();

            if test.to_lowercase() == "y" {
                test_knowledge_base(&kb);
            }
        }
        Err(e) => println!("Error saving: {}", e),
    }
}

fn load_knowledge_base() {
    println!("Enter path to knowledge base:");
    print!("> ");
    let _ = io::stdout().flush();

    let mut path_str = String::new();
    let _ = io::stdin().read_line(&mut path_str);
    let path_str = path_str.trim();

    if path_str.is_empty() {
        println!("No path specified. Aborting.");
        return;
    }

    let path = PathBuf::from(path_str);
    match KnowledgeBase::load(path) {
        Ok(kb) => {
            println!(
                "Knowledge base loaded! {} examples found.",
                kb.get_examples().len()
            );
            println!("\nWhat would you like to do?");
            println!("1. Test knowledge base");
            println!("2. Add examples");
            println!("3. Back");
            print!("> ");
            let _ = io::stdout().flush();

            let mut choice = String::new();
            let _ = io::stdin().read_line(&mut choice);
            let choice = choice.trim();

            match choice {
                "1" => test_knowledge_base(&kb),
                "2" => add_examples_to_kb(kb),
                _ => (),
            }
        }
        Err(e) => println!("Error loading: {}", e),
    }
}

fn test_knowledge_base(kb: &KnowledgeBase) {
    println!("=== Test Knowledge Base ===");
    println!("Select an agent type for testing:");
    println!("1. Exact (SimpleAgent)");
    println!("2. Fuzzy (FuzzyAgent)");
    println!("3. TFIDF (TfidfAgent)");
    print!("> ");
    let _ = io::stdout().flush();

    let mut choice = String::new();
    let _ = io::stdin().read_line(&mut choice);
    let choice = choice.trim();

    let examples = kb.get_examples();

    match choice {
        "1" => {
            let mut agent = MatchAgent::new_exact();
            agent.train(examples);
            test_loop(&agent)
        }
        "2" => {
            let mut agent = MatchAgent::new_fuzzy();
            agent.train(examples);
            test_loop(&agent)
        }
        "3" => {
            let mut agent = TfidfAgent::new();
            agent.train(examples);
            test_loop(&agent)
        }
        _ => println!("Invalid selection."),
    }
}

fn test_loop(agent: &impl Agent) {
    println!("Ask questions or enter 'exit' to quit.");

    loop {
        print!("> ");
        let _ = io::stdout().flush();

        let mut input = String::new();
        let _ = io::stdin().read_line(&mut input);
        let input = input.trim();

        if input.to_lowercase() == "exit" {
            break;
        }

        let answer = agent.predict(input);
        println!("Answer: {}", String::from(answer));
    }
}

fn add_examples_to_kb(mut kb: KnowledgeBase) {
    println!("=== Add Examples ===");
    println!("Enter examples. Press Enter without input to finish.");

    loop {
        println!("\nNew example:");
        print!("Question: ");
        let _ = io::stdout().flush();

        let mut input = String::new();
        let _ = io::stdin().read_line(&mut input);
        let input = input.trim();

        if input.is_empty() {
            break;
        }

        print!("Answer: ");
        let _ = io::stdout().flush();

        let mut output = String::new();
        let _ = io::stdin().read_line(&mut output);
        let output = output.trim();

        print!("Weight (Default 1.0): ");
        let _ = io::stdout().flush();

        let mut weight_str = String::new();
        let _ = io::stdin().read_line(&mut weight_str);
        let weight_str = weight_str.trim();

        let weight = if weight_str.is_empty() {
            1.0
        } else {
            weight_str.parse::<f32>().unwrap_or(1.0)
        };

        kb.add_example(
            input.to_string(),
            ResponseFormat::Text(output.to_string()),
            weight,
        );
        println!("Example added!");
    }

    println!("\nWould you like to save the changes? (y/n)");
    print!("> ");
    let _ = io::stdout().flush();

    let mut save = String::new();
    let _ = io::stdin().read_line(&mut save);
    let save = save.trim();

    if save.to_lowercase() == "y" {
        match kb.save(None) {
            Ok(_) => println!("Knowledge base saved!"),
            Err(e) => println!("Error saving: {}", e),
        }
    }
}