terraphim_agent 1.16.34

Terraphim AI Agent CLI - Command-line interface with interactive REPL and ASCII graph visualization
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
689
690
691
692
693
//! Self-documentation API for robot mode
//!
//! Provides introspection capabilities for AI agents to discover
//! available commands, their arguments, and expected responses.

use serde::{Deserialize, Serialize};

use super::schema::{CapabilitiesData, FeatureFlags};

/// Self-documentation provider
#[derive(Debug)]
pub struct SelfDocumentation {
    commands: Vec<CommandDoc>,
}

impl SelfDocumentation {
    /// Create documentation with all available commands
    pub fn new() -> Self {
        Self {
            commands: Self::build_command_docs(),
        }
    }

    /// Get capabilities summary
    pub fn capabilities(&self) -> Capabilities {
        Capabilities {
            name: "terraphim-agent".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            description: "Privacy-first AI assistant with knowledge graph search".to_string(),
            features: FeatureFlags::default(),
            commands: self.commands.iter().map(|c| c.name.clone()).collect(),
            supported_formats: vec![
                "json".to_string(),
                "jsonl".to_string(),
                "minimal".to_string(),
                "table".to_string(),
            ],
        }
    }

    /// Get capabilities as data structure for JSON response
    pub fn capabilities_data(&self) -> CapabilitiesData {
        CapabilitiesData {
            name: "terraphim-agent".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            description: "Privacy-first AI assistant with knowledge graph search".to_string(),
            features: FeatureFlags::default(),
            commands: self.commands.iter().map(|c| c.name.clone()).collect(),
            supported_formats: vec![
                "json".to_string(),
                "jsonl".to_string(),
                "minimal".to_string(),
                "table".to_string(),
            ],
            index_status: None,
        }
    }

    /// Get schema for a specific command
    pub fn schema(&self, command: &str) -> Option<&CommandDoc> {
        self.commands.iter().find(|c| c.name == command)
    }

    /// Get all command schemas
    pub fn all_schemas(&self) -> &[CommandDoc] {
        &self.commands
    }

    /// Get examples for a specific command
    pub fn examples(&self, command: &str) -> Option<&[ExampleDoc]> {
        self.schema(command).map(|c| c.examples.as_slice())
    }

    /// Build documentation for all commands
    fn build_command_docs() -> Vec<CommandDoc> {
        #[allow(unused_mut)] // mut needed with feature gates
        let mut docs = vec![
            // Search command
            CommandDoc {
                name: "search".to_string(),
                aliases: vec!["q".to_string(), "query".to_string(), "find".to_string()],
                description: "Search documents using semantic and keyword matching".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "query".to_string(),
                    arg_type: "string".to_string(),
                    required: true,
                    description: "Search query text".to_string(),
                    default: None,
                }],
                flags: vec![
                    FlagDoc {
                        name: "--role".to_string(),
                        short: Some("-r".to_string()),
                        flag_type: "string".to_string(),
                        default: Some("current".to_string()),
                        description: "Role context for search".to_string(),
                    },
                    FlagDoc {
                        name: "--limit".to_string(),
                        short: Some("-l".to_string()),
                        flag_type: "integer".to_string(),
                        default: Some("10".to_string()),
                        description: "Maximum results to return".to_string(),
                    },
                    FlagDoc {
                        name: "--semantic".to_string(),
                        short: None,
                        flag_type: "boolean".to_string(),
                        default: Some("false".to_string()),
                        description: "Enable semantic search".to_string(),
                    },
                    FlagDoc {
                        name: "--concepts".to_string(),
                        short: None,
                        flag_type: "boolean".to_string(),
                        default: Some("false".to_string()),
                        description: "Include concept matches".to_string(),
                    },
                ],
                examples: vec![
                    ExampleDoc {
                        description: "Basic search".to_string(),
                        command: "/search async error handling".to_string(),
                        output: None,
                    },
                    ExampleDoc {
                        description: "Search with role and limit".to_string(),
                        command: "/search database migration --role DevOps --limit 5".to_string(),
                        output: None,
                    },
                ],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "results": {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                    "rank": {"type": "integer"},
                                    "id": {"type": "string"},
                                    "title": {"type": "string"},
                                    "url": {"type": "string"},
                                    "score": {"type": "number"},
                                    "preview": {"type": "string"}
                                }
                            }
                        },
                        "total_matches": {"type": "integer"},
                        "concepts_matched": {"type": "array", "items": {"type": "string"}}
                    }
                }),
            },
            // Config command
            CommandDoc {
                name: "config".to_string(),
                aliases: vec!["c".to_string(), "cfg".to_string()],
                description: "View and modify configuration".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "subcommand".to_string(),
                    arg_type: "string".to_string(),
                    required: true,
                    description: "Subcommand: show, set".to_string(),
                    default: None,
                }],
                flags: vec![],
                examples: vec![
                    ExampleDoc {
                        description: "Show current configuration".to_string(),
                        command: "/config show".to_string(),
                        output: None,
                    },
                    ExampleDoc {
                        description: "Set configuration value".to_string(),
                        command: "/config set selected_role Engineer".to_string(),
                        output: None,
                    },
                ],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "config": {"type": "object"}
                    }
                }),
            },
            // Role command
            CommandDoc {
                name: "role".to_string(),
                aliases: vec!["r".to_string()],
                description: "Manage roles".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "subcommand".to_string(),
                    arg_type: "string".to_string(),
                    required: true,
                    description: "Subcommand: list, select".to_string(),
                    default: None,
                }],
                flags: vec![],
                examples: vec![
                    ExampleDoc {
                        description: "List available roles".to_string(),
                        command: "/role list".to_string(),
                        output: None,
                    },
                    ExampleDoc {
                        description: "Select a role".to_string(),
                        command: "/role select Engineer".to_string(),
                        output: None,
                    },
                ],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "roles": {"type": "array", "items": {"type": "string"}},
                        "current_role": {"type": "string"}
                    }
                }),
            },
            // Graph command
            CommandDoc {
                name: "graph".to_string(),
                aliases: vec!["g".to_string(), "kg".to_string()],
                description: "Display knowledge graph concepts".to_string(),
                arguments: vec![],
                flags: vec![FlagDoc {
                    name: "--top-k".to_string(),
                    short: Some("-k".to_string()),
                    flag_type: "integer".to_string(),
                    default: Some("10".to_string()),
                    description: "Number of top concepts to show".to_string(),
                }],
                examples: vec![
                    ExampleDoc {
                        description: "Show top concepts".to_string(),
                        command: "/graph".to_string(),
                        output: None,
                    },
                    ExampleDoc {
                        description: "Show top 20 concepts".to_string(),
                        command: "/graph --top-k 20".to_string(),
                        output: None,
                    },
                ],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "concepts": {
                            "type": "array",
                            "items": {
                                "type": "object",
                                "properties": {
                                    "term": {"type": "string"},
                                    "count": {"type": "integer"}
                                }
                            }
                        }
                    }
                }),
            },
            // VM command
            CommandDoc {
                name: "vm".to_string(),
                aliases: vec![],
                description: "Manage Firecracker VMs".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "subcommand".to_string(),
                    arg_type: "string".to_string(),
                    required: true,
                    description: "Subcommand: list, pool, status, metrics, execute, agent, tasks, allocate, release, monitor".to_string(),
                    default: None,
                }],
                flags: vec![
                    FlagDoc {
                        name: "--vm-id".to_string(),
                        short: None,
                        flag_type: "string".to_string(),
                        default: None,
                        description: "VM identifier".to_string(),
                    },
                ],
                examples: vec![
                    ExampleDoc {
                        description: "List VMs".to_string(),
                        command: "/vm list".to_string(),
                        output: None,
                    },
                    ExampleDoc {
                        description: "Execute code in VM".to_string(),
                        command: "/vm execute python print('hello')".to_string(),
                        output: None,
                    },
                ],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "vms": {"type": "array"},
                        "status": {"type": "string"}
                    }
                }),
            },
            // Help command
            CommandDoc {
                name: "help".to_string(),
                aliases: vec!["h".to_string(), "?".to_string()],
                description: "Show help information".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "command".to_string(),
                    arg_type: "string".to_string(),
                    required: false,
                    description: "Command to get help for".to_string(),
                    default: None,
                }],
                flags: vec![],
                examples: vec![
                    ExampleDoc {
                        description: "Show all commands".to_string(),
                        command: "/help".to_string(),
                        output: None,
                    },
                    ExampleDoc {
                        description: "Get help for search".to_string(),
                        command: "/help search".to_string(),
                        output: None,
                    },
                ],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "commands": {"type": "array"},
                        "help_text": {"type": "string"}
                    }
                }),
            },
            // Robot command (self-documentation)
            CommandDoc {
                name: "robot".to_string(),
                aliases: vec![],
                description: "Robot mode commands for AI agents".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "subcommand".to_string(),
                    arg_type: "string".to_string(),
                    required: true,
                    description: "Subcommand: capabilities, schemas, examples".to_string(),
                    default: None,
                }],
                flags: vec![
                    FlagDoc {
                        name: "--format".to_string(),
                        short: Some("-f".to_string()),
                        flag_type: "string".to_string(),
                        default: Some("json".to_string()),
                        description: "Output format: json, jsonl, minimal, table".to_string(),
                    },
                ],
                examples: vec![
                    ExampleDoc {
                        description: "Get capabilities".to_string(),
                        command: "/robot capabilities".to_string(),
                        output: None,
                    },
                    ExampleDoc {
                        description: "Get schema for search".to_string(),
                        command: "/robot schemas search".to_string(),
                        output: None,
                    },
                ],
                response_schema: serde_json::json!({
                    "type": "object"
                }),
            },
        ];

        // Add feature-gated commands
        #[cfg(feature = "repl-chat")]
        {
            docs.push(CommandDoc {
                name: "chat".to_string(),
                aliases: vec![],
                description: "Interactive chat with AI".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "message".to_string(),
                    arg_type: "string".to_string(),
                    required: false,
                    description: "Message to send".to_string(),
                    default: None,
                }],
                flags: vec![],
                examples: vec![ExampleDoc {
                    description: "Send a message".to_string(),
                    command: "/chat How do I handle errors in Rust?".to_string(),
                    output: None,
                }],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "response": {"type": "string"}
                    }
                }),
            });

            docs.push(CommandDoc {
                name: "summarize".to_string(),
                aliases: vec![],
                description: "Summarize content".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "target".to_string(),
                    arg_type: "string".to_string(),
                    required: true,
                    description: "Document ID or text to summarize".to_string(),
                    default: None,
                }],
                flags: vec![],
                examples: vec![ExampleDoc {
                    description: "Summarize a document".to_string(),
                    command: "/summarize doc-123".to_string(),
                    output: None,
                }],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "summary": {"type": "string"}
                    }
                }),
            });
        }

        #[cfg(feature = "repl-mcp")]
        {
            docs.push(CommandDoc {
                name: "autocomplete".to_string(),
                aliases: vec!["ac".to_string()],
                description: "Autocomplete terms from thesaurus".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "query".to_string(),
                    arg_type: "string".to_string(),
                    required: true,
                    description: "Partial term to complete".to_string(),
                    default: None,
                }],
                flags: vec![FlagDoc {
                    name: "--limit".to_string(),
                    short: Some("-l".to_string()),
                    flag_type: "integer".to_string(),
                    default: Some("10".to_string()),
                    description: "Maximum suggestions".to_string(),
                }],
                examples: vec![ExampleDoc {
                    description: "Autocomplete a term".to_string(),
                    command: "/autocomplete auth".to_string(),
                    output: None,
                }],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "suggestions": {"type": "array", "items": {"type": "string"}}
                    }
                }),
            });

            docs.push(CommandDoc {
                name: "extract".to_string(),
                aliases: vec![],
                description: "Extract paragraphs containing matched terms".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "text".to_string(),
                    arg_type: "string".to_string(),
                    required: true,
                    description: "Text to extract from".to_string(),
                    default: None,
                }],
                flags: vec![FlagDoc {
                    name: "--exclude-term".to_string(),
                    short: None,
                    flag_type: "boolean".to_string(),
                    default: Some("false".to_string()),
                    description: "Exclude the matched term from output".to_string(),
                }],
                examples: vec![ExampleDoc {
                    description: "Extract paragraphs".to_string(),
                    command:
                        "/extract \"This text contains authentication and authorization concepts.\""
                            .to_string(),
                    output: None,
                }],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "paragraphs": {"type": "array", "items": {"type": "string"}}
                    }
                }),
            });

            docs.push(CommandDoc {
                name: "find".to_string(),
                aliases: vec![],
                description: "Find term matches in text".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "text".to_string(),
                    arg_type: "string".to_string(),
                    required: true,
                    description: "Text to search".to_string(),
                    default: None,
                }],
                flags: vec![],
                examples: vec![ExampleDoc {
                    description: "Find matches".to_string(),
                    command: "/find \"async programming patterns\"".to_string(),
                    output: None,
                }],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "matches": {"type": "array", "items": {"type": "object"}}
                    }
                }),
            });

            docs.push(CommandDoc {
                name: "replace".to_string(),
                aliases: vec![],
                description: "Replace matched terms with links".to_string(),
                arguments: vec![ArgumentDoc {
                    name: "text".to_string(),
                    arg_type: "string".to_string(),
                    required: true,
                    description: "Text to process".to_string(),
                    default: None,
                }],
                flags: vec![FlagDoc {
                    name: "--format".to_string(),
                    short: Some("-f".to_string()),
                    flag_type: "string".to_string(),
                    default: Some("markdown".to_string()),
                    description: "Link format: markdown, wiki, html, plain".to_string(),
                }],
                examples: vec![ExampleDoc {
                    description: "Replace with markdown links".to_string(),
                    command: "/replace \"Learn about authentication\" --format markdown"
                        .to_string(),
                    output: None,
                }],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "result": {"type": "string"}
                    }
                }),
            });

            docs.push(CommandDoc {
                name: "thesaurus".to_string(),
                aliases: vec!["th".to_string()],
                description: "Show thesaurus entries".to_string(),
                arguments: vec![],
                flags: vec![FlagDoc {
                    name: "--role".to_string(),
                    short: Some("-r".to_string()),
                    flag_type: "string".to_string(),
                    default: Some("current".to_string()),
                    description: "Role to get thesaurus for".to_string(),
                }],
                examples: vec![ExampleDoc {
                    description: "Show thesaurus".to_string(),
                    command: "/thesaurus".to_string(),
                    output: None,
                }],
                response_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "entries": {"type": "array"}
                    }
                }),
            });
        }

        docs
    }
}

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

/// Capabilities summary
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Capabilities {
    pub name: String,
    pub version: String,
    pub description: String,
    pub features: FeatureFlags,
    pub commands: Vec<String>,
    pub supported_formats: Vec<String>,
}

/// Documentation for a single command
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandDoc {
    pub name: String,
    pub aliases: Vec<String>,
    pub description: String,
    pub arguments: Vec<ArgumentDoc>,
    pub flags: Vec<FlagDoc>,
    pub examples: Vec<ExampleDoc>,
    pub response_schema: serde_json::Value,
}

/// Documentation for a command argument
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArgumentDoc {
    pub name: String,
    #[serde(rename = "type")]
    pub arg_type: String,
    pub required: bool,
    pub description: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
}

/// Documentation for a command flag
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlagDoc {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub short: Option<String>,
    #[serde(rename = "type")]
    pub flag_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    pub description: String,
}

/// Documentation for a command example
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExampleDoc {
    pub description: String,
    pub command: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,
}

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

    #[test]
    fn test_self_documentation_new() {
        let docs = SelfDocumentation::new();
        assert!(!docs.commands.is_empty());
    }

    #[test]
    fn test_capabilities() {
        let docs = SelfDocumentation::new();
        let caps = docs.capabilities();

        assert_eq!(caps.name, "terraphim-agent");
        assert!(!caps.commands.is_empty());
        assert!(caps.supported_formats.contains(&"json".to_string()));
    }

    #[test]
    fn test_schema_lookup() {
        let docs = SelfDocumentation::new();

        let search_doc = docs.schema("search");
        assert!(search_doc.is_some());
        assert_eq!(search_doc.unwrap().name, "search");

        let unknown_doc = docs.schema("nonexistent");
        assert!(unknown_doc.is_none());
    }

    #[test]
    fn test_examples() {
        let docs = SelfDocumentation::new();

        let examples = docs.examples("search");
        assert!(examples.is_some());
        assert!(!examples.unwrap().is_empty());
    }

    #[test]
    fn test_command_doc_serialization() {
        let docs = SelfDocumentation::new();
        let search_doc = docs.schema("search").unwrap();

        let json = serde_json::to_string(search_doc).unwrap();
        assert!(json.contains("search"));
        assert!(json.contains("query"));
    }
}