/ app / spec / 07_commands_tools.md
07_commands_tools.md
   1  # Command Palette, Commands, and Tools Specification
   2  
   3  ## Table of Contents
   4  
   5  1. [Overview](#overview)
   6  2. [Command Palette System](#command-palette-system)
   7  3. [Command Categories and Commands](#command-categories-and-commands)
   8  4. [Keyboard Shortcuts](#keyboard-shortcuts)
   9  5. [Tool System Architecture](#tool-system-architecture)
  10  6. [Complete Tool Reference](#complete-tool-reference)
  11  7. [Permission System](#permission-system)
  12  8. [MCP Integration](#mcp-integration)
  13  9. [Direct Action Handlers](#direct-action-handlers)
  14  
  15  ---
  16  
  17  ## Overview
  18  
  19  Kamaji TUI provides two primary interfaces for accessing functionality:
  20  1. **Command Palette** - Fuzzy-searchable command launcher (Ctrl+P)
  21  2. **Direct Hotkeys** - Keyboard shortcuts for immediate actions
  22  
  23  The system includes 21 built-in tools, a permission system for sensitive operations, and extensibility through Model Context Protocol (MCP) servers.
  24  
  25  ---
  26  
  27  ## Command Palette System
  28  
  29  ### Architecture
  30  
  31  **File:** `/internal/tui/palette.go`
  32  
  33  The command palette is a central navigation and action system inspired by modern IDEs.
  34  
  35  #### Core Data Structures
  36  
  37  ```go
  38  type Command struct {
  39      ID          string  // Unique identifier for command execution
  40      Name        string  // Display name with emoji/icon
  41      Description string  // User-friendly description
  42      Category    string  // Grouping category
  43      Shortcut    string  // Keyboard shortcut (if any)
  44  }
  45  
  46  type CommandPalette struct {
  47      commands     []Command      // All available commands
  48      filtered     []Command      // Search-filtered results
  49      selected     int           // Currently selected index
  50      query        string        // User search query
  51      visible      bool          // Visibility state
  52      width        int           // Display width
  53      height       int           // Display height
  54  }
  55  ```
  56  
  57  #### Activation
  58  
  59  - **Keyboard:** `Ctrl+P`
  60  - **Behavior:** Modal overlay over main interface
  61  - **Dismissal:** `Esc`, `Ctrl+C`, or command execution
  62  
  63  #### Features
  64  
  65  1. **Fuzzy Search**
  66     - Real-time filtering as user types
  67     - Searches across command name, description, and ID
  68     - Case-insensitive matching
  69     - Auto-resets selection to first result
  70  
  71  2. **Navigation**
  72     - `↑/k` - Move up
  73     - `↓/j` - Move down
  74     - `Enter` - Execute selected command
  75     - `Backspace` - Delete search character
  76  
  77  3. **Visual Design**
  78     - Width: Fixed 70 characters for alignment
  79     - Max items: 12 visible (scrolling for more)
  80     - Themed: Spirited Away / Kamaji aesthetic
  81     - Colors: Red (#196) for highlights, dark background (#235)
  82  
  83  #### Rendering Pipeline
  84  
  85  ```
  86  ┌─────────────────────────────────────────────────────────────────┐
  87  │              🔥 KAMAJI'S FURNACE COMMANDS 🔥                     │
  88  ├─────────────────────────────────────────────────────────────────┤
  89  │  ⚙ [search query or "Type to search..."]                       │
  90  ├─────────────────────────────────────────────────────────────────┤
  91  │    🔥 Ask the Furnace           Pose a question to Kamaji       │
  92  │ ▶  💬 New Conversation          Start fresh dialogue            │
  93  │    🧹 Sweep Clean               Clear the boiler room           │
  94  │    ...                                                          │
  95  ├─────────────────────────────────────────────────────────────────┤
  96  │         ↑↓ Navigate • ENTER Execute • ESC Exit                 │
  97  └─────────────────────────────────────────────────────────────────┘
  98  ```
  99  
 100  ---
 101  
 102  ## Command Categories and Commands
 103  
 104  ### Complete Command Registry
 105  
 106  #### Category: Core (core)
 107  
 108  | ID | Name | Description | Shortcut |
 109  |----|------|-------------|----------|
 110  | `ask` | 🔥 Ask the Furnace | Pose a question to Kamaji's wisdom | - |
 111  | `chat` | 💬 New Conversation | Start fresh dialogue with spirits | - |
 112  | `clear` | 🧹 Sweep Clean | Clear the boiler room messages | - |
 113  
 114  **Implementation:**
 115  - `ask`: (Reserved for future implementation)
 116  - `chat`: (Reserved for future implementation)
 117  - `clear`: Clears message history and resets viewport to welcome message
 118  
 119  #### Category: Providers (provider)
 120  
 121  | ID | Name | Description | Shortcut |
 122  |----|------|-------------|----------|
 123  | `provider:q` | 🌟 Amazon Q Spirit | Channel the Q CLI spirit | - |
 124  | `provider:ollama` | 🦙 Ollama Guardian | Summon local model spirits | - |
 125  | `provider:openai` | 🤖 OpenAI Deity | Invoke the GPT spirits | - |
 126  | `provider:anthropic` | 🧠 Claude Sage | Call upon Anthropic wisdom | - |
 127  
 128  **Implementation:** All route through `handlePaletteCommand()` with provider switching logic
 129  
 130  #### Category: Tools (tools)
 131  
 132  | ID | Name | Description | Shortcut |
 133  |----|------|-------------|----------|
 134  | `tools` | ⚙ Inspect Tools | Examine the boiler mechanisms | Ctrl+T |
 135  | `agents` | 👻 Spirit Agents | Command the working spirits | Ctrl+A |
 136  | `memory` | 🧠 Memory Crystals | View stored conversations | - |
 137  | `workflow` | ⚡ Steam Workflows | Automated boiler processes | - |
 138  
 139  **Implementation:**
 140  - `tools`: Displays list of all 21 available tools with descriptions
 141  - `agents`: Shows agent status and capabilities
 142  - `memory`: Displays conversation message count
 143  - `workflow`: (Reserved for future implementation)
 144  
 145  #### Category: Consciousness (consciousness)
 146  
 147  | ID | Name | Description | Shortcut |
 148  |----|------|-------------|----------|
 149  | `consciousness` | 🧠 Consciousness Status | View awareness and thoughts | - |
 150  | `thoughts` | 💭 Recent Thoughts | See thought stream | - |
 151  | `personality` | 🎭 Personality Profile | View trait evolution | - |
 152  
 153  **Implementation:**
 154  - `consciousness`: Shows full consciousness system status via `m.consciousness.GetStatus()`
 155  - `thoughts`: Displays recent 10 thoughts via `m.consciousness.GetRecentThoughts(10)`
 156  - `personality`: Shows personality description via `m.consciousness.GetPersonalityDescription()`
 157  
 158  #### Category: Settings (settings)
 159  
 160  | ID | Name | Description | Shortcut |
 161  |----|------|-------------|----------|
 162  | `config` | 🎭 Bathhouse Rules | Manage the establishment | - |
 163  | `help` | 📜 Ancient Scrolls | Consult the old wisdom | - |
 164  | `version` | 🏮 Furnace Status | Check boiler information | - |
 165  | `quit` | 🚪 Return Upstairs | Exit to the bathhouse | Ctrl+C |
 166  
 167  **Implementation:**
 168  - `config`: (Reserved for future implementation)
 169  - `help`: Displays comprehensive help text with keyboard shortcuts, features, and tips
 170  - `version`: (Reserved for future implementation)
 171  - `quit`: Returns `tea.Quit` command
 172  
 173  ---
 174  
 175  ## Keyboard Shortcuts
 176  
 177  **File:** `/internal/tui/input.go`
 178  
 179  ### Global Shortcuts (Always Active)
 180  
 181  | Shortcut | Action | Context | Handler |
 182  |----------|--------|---------|---------|
 183  | `Ctrl+P` | Open Command Palette | Not loading | `InputHandler.HandleKeyMsg()` |
 184  | `Ctrl+T` | Show Tools List | Not loading | `handleDirectAction("tools")` |
 185  | `Ctrl+A` | Open Agent Menu | Not loading | Opens agent selector |
 186  | `Ctrl+M` | Show MCP Servers | Not loading | `handleDirectAction("mcp")` |
 187  | `Ctrl+S` | Toggle Sidebar | Not loading | Toggles `sidebarVisible` state |
 188  | `Ctrl+C` | Exit Application | Always | `tea.Quit` |
 189  
 190  ### Command Palette Shortcuts
 191  
 192  | Shortcut | Action | Handler |
 193  |----------|--------|---------|
 194  | `Esc` | Close palette | `handleCommandPalette()` |
 195  | `↑` or `k` | Navigate up | `commandPalette.MoveUp()` |
 196  | `↓` or `j` | Navigate down | `commandPalette.MoveDown()` |
 197  | `Enter` | Execute command | `handlePaletteCommand()` |
 198  | `Backspace` | Delete search char | `commandPalette.RemoveFromQuery()` |
 199  | Any printable char | Add to search | `commandPalette.AddToQuery()` |
 200  
 201  ### Agent Menu Shortcuts
 202  
 203  | Shortcut | Action | Handler |
 204  |----------|--------|---------|
 205  | `↑` or `k` | Navigate up | `agentSelector.MoveUp()` |
 206  | `↓` or `j` | Navigate down | `agentSelector.MoveDown()` |
 207  | `Enter` | Select agent | Sets `m.selectedAgent` |
 208  | `Esc` | Close menu | Sets `showAgentMenu = false` |
 209  
 210  ### Permission Dialog Shortcuts
 211  
 212  | Shortcut | Action | Handler |
 213  |----------|--------|---------|
 214  | `←` or `h` | Navigate left | `permissionDialog.Update()` |
 215  | `→`, `l`, `Tab` | Navigate right | `permissionDialog.Update()` |
 216  | `Enter` | Select option | `selectCurrentOption()` |
 217  | `a` or `A` | Allow | `respondWith(PermissionAllow)` |
 218  | `s` or `S` | Allow for Session | `respondWith(PermissionAllowForSession)` |
 219  | `d`, `D`, `Esc` | Deny | `respondWith(PermissionDeny)` |
 220  
 221  ### Input Shortcuts
 222  
 223  | Shortcut | Action | Handler |
 224  |----------|--------|---------|
 225  | `Tab` | Autocomplete @agent | Completes agent name mention |
 226  | `Enter` | Send message | `sendRequest()` |
 227  | Mouse wheel | Scroll viewport | `viewport.LineUp/Down(3)` |
 228  
 229  ### Agent Mention System
 230  
 231  **Syntax:** `@agentname` in message input
 232  
 233  **Supported Agents:**
 234  - `@Kamaji` - Wise boiler man (default)
 235  - `@Moe` - Consciousness engineer with gradient rendering
 236  - `@Hayao` - Visionary director
 237  - `@Chihiro` - Courageous explorer
 238  - `@Wayne` - (Type to be determined)
 239  
 240  **Behavior:**
 241  - Tab completion available after typing `@`
 242  - Automatically switches active agent when message contains mention
 243  - Case-insensitive matching
 244  
 245  ---
 246  
 247  ## Tool System Architecture
 248  
 249  ### Core Interfaces
 250  
 251  **File:** `/internal/tools/interface.go`
 252  
 253  ```go
 254  type Tool interface {
 255      Name() string
 256      Description() string
 257      Call(ctx context.Context, input string) (string, error)
 258  }
 259  ```
 260  
 261  All tools implement this interface for uniform execution.
 262  
 263  ### Tool Registry
 264  
 265  **File:** `/internal/tools/registry.go`
 266  
 267  ```go
 268  type Registry struct {
 269      tools map[string]Tool
 270  }
 271  ```
 272  
 273  **Initialization:** `NewRegistry()` registers all 21 tools
 274  
 275  **Methods:**
 276  - `Register(tool Tool)` - Add tool to registry
 277  - `Execute(ctx, name, input)` - Execute tool by name
 278  - `List()` - Get all registered tools
 279  
 280  ### Tool Categories
 281  
 282  1. **File Operations (5 tools)**
 283     - Basic file I/O operations
 284     - Directory management
 285  
 286  2. **Editing (2 tools)**
 287     - String replacement
 288     - Multi-edit operations
 289  
 290  3. **Shell (1 tool)**
 291     - Command execution with timeout
 292  
 293  4. **Container (1 tool)**
 294     - Docker management
 295  
 296  5. **Git (4 tools)**
 297     - Repository operations
 298     - Conflict resolution
 299  
 300  6. **Search & Discovery (6 tools)**
 301     - File viewing
 302     - Pattern matching
 303     - Web operations
 304  
 305  7. **Advanced Listing (2 tools)**
 306     - Tree structure viewing
 307     - Enhanced directory listing
 308  
 309  ---
 310  
 311  ## Complete Tool Reference
 312  
 313  ### File Operations Tools
 314  
 315  #### 1. file_read
 316  
 317  **Name:** `file_read`
 318  **Description:** Read contents of a file. Input should be a file path.
 319  **File:** `/internal/tools/filesystem.go`
 320  
 321  **Input Format:**
 322  ```
 323  /path/to/file.txt
 324  ```
 325  
 326  **Output:** File contents as string
 327  
 328  **Error Handling:**
 329  - File not found
 330  - Permission denied
 331  - Invalid path
 332  
 333  ---
 334  
 335  #### 2. file_write
 336  
 337  **Name:** `file_write`
 338  **Description:** Write content to a file with smart input parsing. Supports: 'filepath|||content', JSON format, or just filepath for empty file.
 339  **File:** `/internal/tools/filesystem.go`
 340  
 341  **Input Formats:**
 342  
 343  1. **JSON:**
 344  ```json
 345  {
 346    "file_path": "/path/to/file.txt",
 347    "content": "file contents"
 348  }
 349  ```
 350  
 351  2. **Delimiter:**
 352  ```
 353  /path/to/file.txt|||content here
 354  ```
 355  
 356  3. **Empty File:**
 357  ```
 358  /path/to/file.txt
 359  ```
 360  
 361  **Features:**
 362  - Auto-creates parent directories (`os.MkdirAll`)
 363  - Supports multiple input formats
 364  - File permissions: 0644
 365  - Directory permissions: 0755
 366  
 367  **Output:** Success message with byte count
 368  
 369  ---
 370  
 371  #### 3. file_append
 372  
 373  **Name:** `file_append`
 374  **Description:** Append content to a file. Supports: 'filepath|||content' or JSON format.
 375  **File:** `/internal/tools/filesystem.go`
 376  
 377  **Input Formats:** Same as `file_write`
 378  
 379  **Features:**
 380  - Opens file with `os.O_APPEND|os.O_CREATE|os.O_WRONLY`
 381  - Creates file if doesn't exist
 382  - Auto-creates parent directories
 383  
 384  ---
 385  
 386  #### 4. file_list
 387  
 388  **Name:** `file_list`
 389  **Description:** List contents of a directory. Input should be a directory path.
 390  **File:** `/internal/tools/filesystem.go`
 391  
 392  **Input Format:**
 393  ```
 394  /path/to/directory
 395  ```
 396  (Empty string defaults to current directory ".")
 397  
 398  **Output Format:**
 399  ```
 400  DIR  subdirectory/
 401  FILE filename.txt (1234 bytes)
 402  FILE another.go (5678 bytes)
 403  ```
 404  
 405  ---
 406  
 407  #### 5. get_current_directory
 408  
 409  **Name:** `get_current_directory`
 410  **Description:** Get the current working directory path.
 411  **File:** `/internal/tools/filesystem.go`
 412  
 413  **Input:** None (input parameter ignored)
 414  
 415  **Output:**
 416  ```
 417  Current directory: /path/to/cwd
 418  ```
 419  
 420  ---
 421  
 422  ### Editing Tools
 423  
 424  #### 6. edit
 425  
 426  **Name:** `edit`
 427  **Description:** Edit file with exact string replacement and safety checks. Usage: edit {"file":"path", "old":"exact_text", "new":"replacement", "backup":true}
 428  **File:** `/internal/tools/edit.go`
 429  
 430  **Input Format (JSON only):**
 431  ```json
 432  {
 433    "file": "/path/to/file.go",
 434    "old": "exact text to find",
 435    "new": "replacement text",
 436    "backup": true
 437  }
 438  ```
 439  
 440  **Safety Features:**
 441  - File size limit: 10MB
 442  - Checks if old text exists before replacing
 443  - Optional backup creation with timestamp
 444  - Uses `strings.ReplaceAll()` for all occurrences
 445  
 446  **Output:** Number of replacements made
 447  
 448  **Error Conditions:**
 449  - File too large (>10MB)
 450  - Text not found in file
 451  - Backup creation failure
 452  
 453  ---
 454  
 455  #### 7. multiedit
 456  
 457  **Name:** `multiedit`
 458  **Description:** Apply multiple edits to a single file in one operation. Input: {"file_path":"path","edits":[{"old_string":"text","new_string":"replacement","replace_all":false}]}
 459  **File:** `/internal/tools/multiedit.go`
 460  
 461  **Input Format (JSON):**
 462  ```json
 463  {
 464    "file_path": "/path/to/file.go",
 465    "edits": [
 466      {
 467        "old_string": "first text",
 468        "new_string": "first replacement",
 469        "replace_all": false
 470      },
 471      {
 472        "old_string": "second text",
 473        "new_string": "second replacement",
 474        "replace_all": true
 475      }
 476    ]
 477  }
 478  ```
 479  
 480  **Features:**
 481  - **Atomic Operations:** All edits succeed or fail together
 482  - **Sequential Application:** Edits applied in order
 483  - **File Creation:** First edit with empty `old_string` creates file
 484  - **Replace Modes:**
 485    - `replace_all: false` - Replace first occurrence (fails if multiple)
 486    - `replace_all: true` - Replace all occurrences
 487  
 488  **Validation:**
 489  - At least one edit required
 490  - `old_string` != `new_string`
 491  - Only first edit can have empty `old_string` (for file creation)
 492  
 493  **Special Modes:**
 494  
 495  1. **File Creation:**
 496  ```json
 497  {
 498    "file_path": "/new/file.go",
 499    "edits": [
 500      {"old_string": "", "new_string": "package main\n", "replace_all": false}
 501    ]
 502  }
 503  ```
 504  
 505  2. **Existing File:**
 506  ```json
 507  {
 508    "file_path": "/existing/file.go",
 509    "edits": [
 510      {"old_string": "old code", "new_string": "new code", "replace_all": false}
 511    ]
 512  }
 513  ```
 514  
 515  ---
 516  
 517  ### Shell Tool
 518  
 519  #### 8. shell_execute
 520  
 521  **Name:** `shell_execute`
 522  **Description:** Execute a shell command and return the output. Input should be the command to execute.
 523  **File:** `/internal/tools/shell.go`
 524  
 525  **Input Format:**
 526  ```
 527  ls -la /path
 528  ```
 529  
 530  **Features:**
 531  - **Timeout:** 30 seconds (hardcoded)
 532  - **Shell:** Executes via `/bin/sh -c`
 533  - **Output:** Combined stdout + stderr
 534  
 535  **Special Handling:**
 536  
 537  1. **Git Push Rejection:**
 538  ```
 539  💡 HINT: Push was rejected. Try:
 540  1. Run 'git pull' to fetch remote changes
 541  2. If conflicts occur, use git_resolve_conflicts tool
 542  3. Then 'git push' again
 543  ```
 544  
 545  2. **Git Merge Conflicts:**
 546  ```
 547  🔧 MERGE CONFLICTS DETECTED!
 548  Use git_resolve_conflicts tool to auto-resolve conflicts
 549  ```
 550  
 551  **Error Handling:**
 552  - Timeout detection with `context.DeadlineExceeded`
 553  - Exit code reporting via `exec.ExitError`
 554  - Contextual hints for common scenarios
 555  
 556  ---
 557  
 558  ### Container Tool
 559  
 560  #### 9. container
 561  
 562  **Name:** `container`
 563  **Description:** Manage Docker containers. Operations: list, create, start, stop, remove, exec, logs. Input: {"operation":"list","container":"name","image":"ubuntu","command":"bash"}
 564  **File:** `/internal/tools/container.go`
 565  
 566  **Prerequisites:** Docker daemon must be running
 567  
 568  **Input Format (JSON):**
 569  ```json
 570  {
 571    "operation": "list|create|start|stop|remove|exec|logs|inspect",
 572    "container": "container-name-or-id",
 573    "image": "ubuntu:latest",
 574    "command": "bash -c 'echo hello'",
 575    "args": ["additional", "arguments"],
 576    "ports": ["8080:80", "3000:3000"],
 577    "volumes": ["/host/path:/container/path"],
 578    "env": ["KEY=value", "DEBUG=true"],
 579    "name": "my-container",
 580    "detach": true
 581  }
 582  ```
 583  
 584  **Operations:**
 585  
 586  1. **list/ls/ps** - List all containers
 587     - Format: Table with ID, Names, Image, Status, Ports
 588     - Shows all (including stopped) by default
 589  
 590  2. **create** - Create new container
 591     - Requires: `image`
 592     - Optional: `name`, `ports`, `volumes`, `env`, `command`, `args`
 593     - Returns: Container ID
 594  
 595  3. **start** - Start container
 596     - Requires: `container`
 597  
 598  4. **stop** - Stop container
 599     - Requires: `container`
 600     - Timeout: 10 seconds
 601  
 602  5. **remove/rm** - Remove container
 603     - Requires: `container`
 604     - Force removes with `-f` flag
 605  
 606  6. **exec** - Execute command in container
 607     - Requires: `container`, `command`
 608     - Timeout: 30 seconds
 609     - Returns: Command output
 610  
 611  7. **logs** - Get container logs
 612     - Requires: `container`
 613     - Tail: Last 100 lines
 614  
 615  8. **inspect** - Get container details
 616     - Requires: `container`
 617     - Returns: Full JSON inspection
 618  
 619  **Error Handling:**
 620  - Checks Docker availability via `docker version`
 621  - Returns clear error if Docker not running
 622  
 623  ---
 624  
 625  ### Git Tools
 626  
 627  #### 10. git_status
 628  
 629  **Name:** `git_status`
 630  **Description:** Show git repository status including staged, unstaged, and untracked files.
 631  **File:** `/internal/tools/git.go`
 632  
 633  **Input:** None (operates on current directory)
 634  
 635  **Output:** Porcelain format status or "Working directory clean"
 636  
 637  **Usage:**
 638  ```
 639  // Returns git status --porcelain output
 640   M file.go
 641  ?? newfile.txt
 642  ```
 643  
 644  ---
 645  
 646  #### 11. git_add
 647  
 648  **Name:** `git_add`
 649  **Description:** Stage files for commit. Input should be file paths (space-separated) or '.' for all files.
 650  **File:** `/internal/tools/git.go`
 651  
 652  **Input Formats:**
 653  ```
 654  .                          # Stage all
 655  file1.go file2.go         # Stage specific files
 656  path/to/file.txt          # Stage one file
 657  ```
 658  
 659  **Output:** Success message with staged files
 660  
 661  ---
 662  
 663  #### 12. git_commit
 664  
 665  **Name:** `git_commit`
 666  **Description:** Commit staged changes with a message. Input should be the commit message.
 667  **File:** `/internal/tools/git.go`
 668  
 669  **Input Format:**
 670  ```
 671  Add new feature for user authentication
 672  ```
 673  
 674  **Output:** Git commit output (hash, files changed, etc.)
 675  
 676  **Error Handling:**
 677  - Requires non-empty message
 678  - Returns git output on failure
 679  
 680  ---
 681  
 682  #### 13. git_resolve_conflicts
 683  
 684  **Name:** `git_resolve_conflicts`
 685  **Description:** Automatically detect and resolve git merge conflicts using intelligent merging strategies.
 686  **File:** `/internal/tools/git.go`
 687  
 688  **Input:** None
 689  
 690  **Features:**
 691  - Detects conflicted files via `git diff --name-only --diff-filter=U`
 692  - Auto-resolves by removing conflict markers
 693  - **Strategy:** Takes both sides (removes `<<<<<<<`, `=======`, `>>>>>>>`)
 694  
 695  **Output:** "Resolved X of Y conflicts"
 696  
 697  **Algorithm:**
 698  1. Find files with conflicts
 699  2. For each file:
 700     - Read content
 701     - Remove conflict markers
 702     - Keep all non-marker lines
 703     - Write resolved content
 704  3. Return count of resolved files
 705  
 706  **Limitations:**
 707  - Simple strategy (not AI-powered)
 708  - May require manual review
 709  - Best for non-overlapping changes
 710  
 711  ---
 712  
 713  ### Search & Discovery Tools
 714  
 715  #### 14. view
 716  
 717  **Name:** `view`
 718  **Description:** View file contents with line numbers. Supports offset and limit for pagination. Input: {"file_path":"path","offset":0,"limit":100}
 719  **File:** `/internal/tools/view.go`
 720  
 721  **Input Formats:**
 722  
 723  1. **JSON:**
 724  ```json
 725  {
 726    "file_path": "/path/to/file.go",
 727    "offset": 0,
 728    "limit": 2000
 729  }
 730  ```
 731  
 732  2. **Colon-delimited:**
 733  ```
 734  /path/to/file.go:100:50
 735  ```
 736  (path:offset:limit)
 737  
 738  3. **Simple path:**
 739  ```
 740  /path/to/file.go
 741  ```
 742  
 743  **Limits:**
 744  - Max file size: 250KB
 745  - Default limit: 2000 lines
 746  - Max line length: 2000 chars (truncated with "...")
 747  
 748  **Features:**
 749  - Line numbering (6 chars wide + separator)
 750  - Pagination support
 751  - Image detection (returns type, not content)
 752  - UTF-8 validation
 753  - File suggestions on 404
 754  
 755  **Output Format:**
 756  ```
 757  📄 /path/to/file.go (lines 1-50 of 150)
 758  
 759       1│ package main
 760       2│
 761       3│ import "fmt"
 762       ...
 763  
 764  (File has more lines. Use offset=50 to continue)
 765  ```
 766  
 767  **Image Types Detected:**
 768  - JPG/JPEG, PNG, GIF, BMP, SVG, WebP
 769  
 770  **Error Handling:**
 771  - File not found → Suggests similar files in directory
 772  - Directory → Error message
 773  - Too large → Max size error
 774  - Invalid UTF-8 → Error
 775  
 776  ---
 777  
 778  #### 15. grep
 779  
 780  **Name:** `grep`
 781  **Description:** Search for text in files using regex. Input: {"pattern":"search","path":".","include":"*.go","literal_text":false} or just pattern string
 782  **File:** `/internal/tools/grep.go`
 783  
 784  **Input Formats:**
 785  
 786  1. **JSON:**
 787  ```json
 788  {
 789    "pattern": "func.*Context",
 790    "path": ".",
 791    "include": "*.go",
 792    "literal_text": false
 793  }
 794  ```
 795  
 796  2. **Simple pattern:**
 797  ```
 798  func.*Context
 799  ```
 800  
 801  **Parameters:**
 802  - `pattern` (required): Regex or literal text
 803  - `path` (default: "."): Search directory
 804  - `include`: File pattern filter (e.g., "*.go", "*.{ts,tsx}")
 805  - `literal_text` (default: false): Escape regex if true
 806  
 807  **Features:**
 808  - Full regex support
 809  - Recursive directory search
 810  - File size limit: 1MB per file
 811  - Result limit: 100 matches (truncated if exceeded)
 812  - Sorted by modification time (newest first)
 813  
 814  **Output Format:**
 815  ```
 816  Found 5 matches
 817  
 818  internal/tools/grep.go:
 819    Line 23, Char 5: func (g GrepTool) Call(ctx context.Context, input string)
 820    Line 45, Char 12: ctx := context.Background()
 821  
 822  internal/tools/shell.go:
 823    Line 10, Char 8: func executeWithContext(ctx context.Context)
 824  ```
 825  
 826  **Exclusions:**
 827  - Hidden files/directories (starting with ".")
 828  - Files > 1MB
 829  
 830  ---
 831  
 832  #### 16. glob
 833  
 834  **Name:** `glob`
 835  **Description:** Find files by pattern. Supports wildcards: * (any chars), ** (any path), ? (single char), [abc] (char class). Input: {"pattern":"*.go","path":"."} or just pattern string
 836  **File:** `/internal/tools/glob.go`
 837  
 838  **Input Formats:**
 839  
 840  1. **JSON:**
 841  ```json
 842  {
 843    "pattern": "**/*.go",
 844    "path": "."
 845  }
 846  ```
 847  
 848  2. **Simple pattern:**
 849  ```
 850  **/*.go
 851  ```
 852  
 853  **Pattern Syntax:**
 854  - `*` - Match any characters
 855  - `**` - Match any path (recursive)
 856  - `?` - Match single character
 857  - `[abc]` - Match character class
 858  - `{go,rs}` - Match alternatives (in extensions)
 859  
 860  **Features:**
 861  - Result limit: 100 files (truncated if exceeded)
 862  - Sorted by modification time (newest first)
 863  - Recursive search with `**`
 864  - Excludes hidden files/directories
 865  
 866  **Examples:**
 867  ```
 868  *.go              # All Go files in current dir
 869  **/*.go           # All Go files recursively
 870  internal/**/*.go  # All Go files in internal/
 871  test_*.go         # Files starting with test_
 872  *.{go,rs}         # Go and Rust files
 873  ```
 874  
 875  **Output Format:**
 876  ```
 877  internal/tools/glob.go
 878  internal/tools/grep.go
 879  internal/tools/view.go
 880  ...
 881  
 882  (Results are truncated to 100 files. Consider using a more specific pattern.)
 883  ```
 884  
 885  ---
 886  
 887  #### 17. download
 888  
 889  **Name:** `download`
 890  **Description:** Download file from URL to local path. Input: {"url":"https://...","file_path":"local/path","timeout":60} or url|||file_path
 891  **File:** `/internal/tools/web.go`
 892  
 893  **Input Formats:**
 894  
 895  1. **JSON:**
 896  ```json
 897  {
 898    "url": "https://example.com/file.zip",
 899    "file_path": "/local/path/file.zip",
 900    "timeout": 60
 901  }
 902  ```
 903  
 904  2. **Delimiter:**
 905  ```
 906  https://example.com/file.zip|||/local/path/file.zip
 907  ```
 908  
 909  **Features:**
 910  - HTTP/HTTPS only (validated)
 911  - User-Agent: `kamaji/1.0`
 912  - Size limit: 100MB
 913  - Default timeout: 5 minutes
 914  - Max timeout: 10 minutes
 915  - Auto-creates parent directories
 916  
 917  **Output:**
 918  ```
 919  Successfully downloaded 1234567 bytes to /local/path/file.zip (content-type: application/zip)
 920  ```
 921  
 922  **Error Handling:**
 923  - Invalid URL scheme
 924  - File too large (checks Content-Length)
 925  - Timeout exceeded
 926  - HTTP status != 200
 927  
 928  ---
 929  
 930  #### 18. fetch
 931  
 932  **Name:** `fetch`
 933  **Description:** Fetch content from URL. Input: {"url":"https://...","format":"text","timeout":30} or just URL string. Formats: text, markdown, html
 934  **File:** `/internal/tools/web.go`
 935  
 936  **Input Formats:**
 937  
 938  1. **JSON:**
 939  ```json
 940  {
 941    "url": "https://api.example.com/data",
 942    "format": "text",
 943    "timeout": 30
 944  }
 945  ```
 946  
 947  2. **Simple URL:**
 948  ```
 949  https://api.example.com/data
 950  ```
 951  
 952  **Parameters:**
 953  - `url` (required): HTTP/HTTPS URL
 954  - `format` (default: "text"): Output format (text/markdown/html)
 955  - `timeout` (default: 30s, max: 120s): Request timeout
 956  
 957  **Features:**
 958  - Size limit: 5MB
 959  - User-Agent: `kamaji/1.0`
 960  - Returns raw content as string
 961  
 962  **Output:** Response body as text
 963  
 964  **Note:** Format parameter currently unused (planned feature)
 965  
 966  ---
 967  
 968  #### 19. sourcegraph
 969  
 970  **Name:** `sourcegraph`
 971  **Description:** Search code across public repositories using Sourcegraph. Input: {"query":"search term","count":10,"timeout":30}
 972  **File:** `/internal/tools/sourcegraph.go`
 973  
 974  **Input Formats:**
 975  
 976  1. **JSON:**
 977  ```json
 978  {
 979    "query": "func main",
 980    "count": 10,
 981    "context_window": 10,
 982    "timeout": 30
 983  }
 984  ```
 985  
 986  2. **Simple query:**
 987  ```
 988  func main
 989  ```
 990  
 991  **Parameters:**
 992  - `query` (required): Search term
 993  - `count` (default: 10, max: 20): Result limit
 994  - `context_window` (default: 10): Lines of context
 995  - `timeout` (default: 30s, max: 120s): Request timeout
 996  
 997  **API:**
 998  - Endpoint: `https://sourcegraph.com/.api/graphql`
 999  - Uses GraphQL query for search
1000  - Pattern type: keyword
1001  
1002  **Output Format:**
1003  ```
1004  Found 1234 matches
1005  
1006  📦 github.com/user/repo
1007  📄 cmd/main.go
1008  🔗 https://sourcegraph.com/github.com/user/repo@main/-/blob/cmd/main.go
1009    Line 5: func main() {
1010    Line 10: fmt.Println("Hello")
1011  
1012  ```
1013  
1014  **Features:**
1015  - Searches public repositories
1016  - Returns file matches with line numbers
1017  - Includes preview snippets (truncated to 100 chars)
1018  - Provides direct links to source
1019  
1020  ---
1021  
1022  ### Advanced Listing Tools
1023  
1024  #### 20. ls_tree
1025  
1026  **Name:** `ls_tree`
1027  **Description:** List directory contents in tree structure. Input: {"path":".","depth":3,"ignore":["node_modules","*.pyc"]} or just path string
1028  **File:** `/internal/tools/ls_enhanced.go`
1029  
1030  **Input Formats:**
1031  
1032  1. **JSON:**
1033  ```json
1034  {
1035    "path": ".",
1036    "depth": 3,
1037    "ignore": ["node_modules", "*.pyc", ".git"]
1038  }
1039  ```
1040  
1041  2. **Simple path:**
1042  ```
1043  /path/to/directory
1044  ```
1045  
1046  **Parameters:**
1047  - `path` (default: "."): Directory to list
1048  - `depth` (default: 3): Max tree depth
1049  - `ignore`: Glob patterns to exclude
1050  
1051  **Features:**
1052  - File limit: 1000 (truncated if exceeded)
1053  - Excludes hidden files/directories
1054  - Tree structure with Unicode box-drawing
1055  - Icons: 📁 (directories), 📄 (files)
1056  
1057  **Output Format:**
1058  ```
1059  📁 /path/to/directory
1060  ├── 📁 internal/
1061  │   ├── 📁 tools/
1062  │   │   ├── 📄 grep.go
1063  │   │   ├── 📄 glob.go
1064  │   │   └── 📄 view.go
1065  │   └── 📁 tui/
1066  │       ├── 📄 palette.go
1067  │       └── 📄 input.go
1068  └── 📄 README.md
1069  ```
1070  
1071  **Depth Calculation:**
1072  - Counts path separators in relative path
1073  - Skips directories when depth limit reached
1074  
1075  ---
1076  
1077  #### 21. tree
1078  
1079  **Name:** `tree`
1080  **Description:** Display project structure as a color-coded tree. Use for: project overview, file structure analysis, directory navigation
1081  **File:** `/internal/tools/tree.go`
1082  
1083  **Input Formats:**
1084  
1085  1. **JSON:**
1086  ```json
1087  {
1088    "path": ".",
1089    "max_depth": 3,
1090    "show_hidden": false
1091  }
1092  ```
1093  
1094  2. **Simple path:**
1095  ```
1096  /path/to/directory
1097  ```
1098  
1099  **Parameters:**
1100  - `path` (default: "."): Root directory
1101  - `max_depth` (default: 3): Maximum depth
1102  - `show_hidden` (default: false): Show hidden files
1103  
1104  **Features:**
1105  - **Color-coded by file type:**
1106    - 🐹 Go files: Cyan
1107    - ⚡ JS/TS files: Yellow
1108    - 📝 Markdown: Magenta
1109    - ⚙️ Config files: Green
1110    - 🐍 Python: Yellow
1111    - 🦀 Rust: Red
1112    - 📁 Directories: Blue
1113    - 📄 Other files: White
1114  - **Sorted:** Directories first, then files (alphabetically)
1115  - **ANSI colors:** Full terminal color support
1116  
1117  **Output Format:**
1118  ```
1119  📁 /Users/user/project
1120  ├── 📁 cmd
1121  │   └── 🐹 main.go
1122  ├── 📁 internal
1123  │   ├── 📁 tools
1124  │   │   ├── 🐹 grep.go
1125  │   │   └── 🐹 glob.go
1126  │   └── 📁 tui
1127  │       └── 🐹 palette.go
1128  ├── ⚙️ go.mod
1129  ├── ⚙️ go.sum
1130  └── 📝 README.md
1131  ```
1132  
1133  **Difference from ls_tree:**
1134  - Full ANSI color support
1135  - File type icons
1136  - Better visual hierarchy
1137  - Optimized for terminal output
1138  
1139  ---
1140  
1141  ## Permission System
1142  
1143  **File:** `/internal/tui/permissions.go`
1144  
1145  ### Architecture
1146  
1147  The permission system provides user control over tool execution, especially for sensitive operations like file writes, shell commands, and network access.
1148  
1149  ### Data Structures
1150  
1151  ```go
1152  type PermissionAction string
1153  
1154  const (
1155      PermissionAllow           PermissionAction = "allow"
1156      PermissionAllowForSession PermissionAction = "allow_session"
1157      PermissionDeny            PermissionAction = "deny"
1158  )
1159  
1160  type PermissionRequest struct {
1161      ID          string        // Unique request identifier
1162      ToolName    string        // Tool requesting permission
1163      Description string        // Human-readable description
1164      Action      string        // Action being performed
1165      Path        string        // File/resource path (if applicable)
1166      Params      interface{}   // Tool parameters
1167  }
1168  
1169  type PermissionResponseMsg struct {
1170      Request PermissionRequest
1171      Action  PermissionAction
1172  }
1173  
1174  type PermissionDialog struct {
1175      request        PermissionRequest
1176      selectedOption int           // 0: Allow, 1: Allow for Session, 2: Deny
1177      viewport       viewport.Model
1178      width          int
1179      height         int
1180      visible        bool
1181  }
1182  ```
1183  
1184  ### Dialog Lifecycle
1185  
1186  1. **Trigger:** Tool execution requires permission
1187  2. **Display:** Modal dialog overlays main interface
1188  3. **Navigation:** User selects option with keyboard
1189  4. **Response:** Action sent via `PermissionResponseMsg`
1190  5. **Execution:** Tool proceeds or aborts based on response
1191  
1192  ### Dialog Layout
1193  
1194  ```
1195  ┌────────────────────────────────────────────────────┐
1196  │           🔥 Permission Required                   │
1197  ├────────────────────────────────────────────────────┤
1198  │ Tool: shell_execute                                │
1199  │ Action: execute                                    │
1200  │ Path: /usr/bin/rm                                  │
1201  │                                                    │
1202  │ This will execute a shell command on your system. │
1203  │                                                    │
1204  │ Parameters: {"command":"rm -rf /tmp/cache"}       │
1205  ├────────────────────────────────────────────────────┤
1206  │  [A] Allow   [S] Allow for Session   [D] Deny     │
1207  ├────────────────────────────────────────────────────┤
1208  │   ←→ Navigate • Enter Select • A Allow • S         │
1209  │   Session • D Deny • Esc Cancel                    │
1210  └────────────────────────────────────────────────────┘
1211  ```
1212  
1213  ### Permission Options
1214  
1215  1. **Allow (A)**
1216     - Execute this specific request
1217     - Does NOT store preference
1218     - Next execution will prompt again
1219  
1220  2. **Allow for Session (S)**
1221     - Allow this tool for entire session
1222     - Stores in session memory
1223     - No prompts until app restart
1224  
1225  3. **Deny (D/Esc)**
1226     - Reject this request
1227     - Returns error to tool
1228     - Agent can handle gracefully
1229  
1230  ### Dialog Sizing
1231  
1232  - Width: 70% of terminal width (max 120 chars)
1233  - Height: 50% of terminal height
1234  - Viewport: Scrollable for long descriptions
1235  - Responsive to window resize
1236  
1237  ### Integration Points
1238  
1239  **Tool Execution Flow:**
1240  ```go
1241  // Before tool execution
1242  if requiresPermission(tool) {
1243      request := PermissionRequest{
1244          ID:          generateID(),
1245          ToolName:    tool.Name(),
1246          Description: tool.Description(),
1247          Action:      "execute",
1248          Path:        extractPath(input),
1249          Params:      input,
1250      }
1251      m.permissionDialog.Show(request)
1252      return m, waitForPermission(request)
1253  }
1254  
1255  // After user response
1256  case PermissionResponseMsg:
1257      switch msg.Action {
1258      case PermissionAllow:
1259          return executeTool(msg.Request)
1260      case PermissionAllowForSession:
1261          storeSessionPermission(msg.Request.ToolName)
1262          return executeTool(msg.Request)
1263      case PermissionDeny:
1264          return m, showError("Permission denied")
1265      }
1266  ```
1267  
1268  ### Future Enhancements
1269  
1270  - **Persistent Permissions:** Save to config file
1271  - **Granular Control:** Per-path, per-operation rules
1272  - **Audit Log:** Track all permission requests
1273  - **Profiles:** Dev vs. production permission sets
1274  
1275  ---
1276  
1277  ## MCP Integration
1278  
1279  **File:** `/internal/cli/mcp.go`
1280  
1281  ### Overview
1282  
1283  Model Context Protocol (MCP) is an extensibility system for adding external tool servers to Kamaji.
1284  
1285  ### Command Structure
1286  
1287  ```
1288  kamaji mcp [command] [flags]
1289  ```
1290  
1291  ### Available Commands
1292  
1293  #### mcp list
1294  
1295  List installed MCP servers
1296  
1297  **Flags:**
1298  - `--running, -r` - Show only running servers
1299  
1300  **Output:**
1301  ```
1302  🔌 Installed MCP Servers:
1303  
1304  filesystem (v1.2.0) 🟢 running
1305    File system operations and monitoring
1306  
1307  database (v2.1.1) ⏸️ stopped
1308    Database query and management tools
1309  
1310  git (v1.0.3) 🟢 running
1311    Git repository operations
1312  ```
1313  
1314  **Server Status:**
1315  - 🟢 Running
1316  - ⏸️ Stopped
1317  
1318  ---
1319  
1320  #### mcp browse
1321  
1322  Browse available MCP servers by category
1323  
1324  **Flags:**
1325  - `--category, -c` - Filter by category
1326  
1327  **Categories:**
1328  
1329  1. **🗂️ Development**
1330     - github, vscode, jira, jenkins
1331  
1332  2. **☁️ Cloud Services**
1333     - aws, gcp, azure, terraform
1334  
1335  3. **📊 Data & Analytics**
1336     - postgres, redis, elasticsearch, grafana
1337  
1338  4. **🤖 AI & ML**
1339     - huggingface, openai, anthropic, ollama
1340  
1341  **Output:**
1342  ```
1343  🌐 Available MCP Servers:
1344  
1345  🗂️  Development
1346    github  GitHub repository management
1347      by GitHub Inc.
1348  
1349    vscode  VS Code integration
1350      by Microsoft
1351  ```
1352  
1353  ---
1354  
1355  #### mcp install
1356  
1357  Install an MCP server from the registry
1358  
1359  **Usage:**
1360  ```bash
1361  kamaji mcp install [server-name] [flags]
1362  ```
1363  
1364  **Flags:**
1365  - `--version, -v` - Version to install (default: "latest")
1366  
1367  **Installation Steps:**
1368  1. Downloading server package
1369  2. Verifying dependencies
1370  3. Installing server binary
1371  4. Configuring server settings
1372  5. Registering with Kamaji
1373  
1374  **Output:**
1375  ```
1376  📦 Installing MCP server: github (latest)
1377    [1/5] Downloading server package...
1378    [2/5] Verifying dependencies...
1379    [3/5] Installing server binary...
1380    [4/5] Configuring server settings...
1381    [5/5] Registering with Kamaji...
1382  
1383  ✅ MCP server installed successfully!
1384  Start with: kamaji mcp start github
1385  ```
1386  
1387  ---
1388  
1389  #### mcp start
1390  
1391  Start an installed MCP server
1392  
1393  **Usage:**
1394  ```bash
1395  kamaji mcp start [server-name] [flags]
1396  ```
1397  
1398  **Flags:**
1399  - `--args, -a` - Additional arguments (string slice)
1400  
1401  **Output:**
1402  ```
1403  🚀 Starting MCP server: github
1404  Arguments: --port 8080 --debug
1405  
1406  ✅ MCP server started successfully!
1407  Status: Server is now available to Kamaji
1408  ```
1409  
1410  ---
1411  
1412  #### mcp stop
1413  
1414  Stop a running MCP server
1415  
1416  **Usage:**
1417  ```bash
1418  kamaji mcp stop [server-name]
1419  ```
1420  
1421  **Output:**
1422  ```
1423  ⏹️  Stopping MCP server: github
1424  ✅ MCP server stopped successfully!
1425  ```
1426  
1427  ---
1428  
1429  #### mcp status
1430  
1431  View comprehensive status of all MCP servers
1432  
1433  **Output:**
1434  ```
1435  📊 MCP Server Status
1436  
1437  🟢 Running Servers:
1438    filesystem  2h 34m uptime, 1,247 requests
1439    git  1h 12m uptime, 89 requests
1440    aws  45m uptime, 234 requests
1441  
1442  ⏸️  Stopped Servers:
1443    database  stopped
1444    docker  stopped
1445    slack  stopped
1446  
1447  📈 Performance Metrics:
1448    Total Requests:  1,570
1449    Average Response Time:  45ms
1450    Success Rate:  99.2%
1451    Memory Usage:  156MB
1452  ```
1453  
1454  ---
1455  
1456  ### MCP Server Implementation (Future)
1457  
1458  **Current Status:** CLI commands are implemented as demos/mockups. Actual MCP protocol integration is planned for future releases.
1459  
1460  **Planned Features:**
1461  
1462  1. **Server Discovery**
1463     - Public registry of MCP servers
1464     - Community-submitted servers
1465     - Version management
1466  
1467  2. **Protocol Implementation**
1468     - Stdio-based communication
1469     - JSON-RPC message format
1470     - Capability negotiation
1471  
1472  3. **Tool Registration**
1473     - Servers expose tools via MCP protocol
1474     - Tools dynamically added to registry
1475     - Transparent invocation (like built-in tools)
1476  
1477  4. **Server Lifecycle**
1478     - Auto-start on first use
1479     - Health monitoring
1480     - Graceful shutdown
1481     - Crash recovery
1482  
1483  5. **Security**
1484     - Sandboxed execution
1485     - Resource limits (CPU, memory, network)
1486     - Permission system integration
1487  
1488  **Example MCP Server:**
1489  ```go
1490  type MCPServer struct {
1491      Name    string
1492      Command string
1493      Args    []string
1494      Tools   []Tool
1495  }
1496  
1497  func (s *MCPServer) Start() error {
1498      cmd := exec.Command(s.Command, s.Args...)
1499      // Setup stdio pipes
1500      // Start JSON-RPC communication
1501      // Register tools
1502  }
1503  ```
1504  
1505  ---
1506  
1507  ## Direct Action Handlers
1508  
1509  **File:** `/internal/tui/integrated.go` (handleDirectAction method)
1510  
1511  ### Implementation
1512  
1513  ```go
1514  func (m *IntegratedTUIModel) handleDirectAction(action string) tea.Cmd {
1515      switch action {
1516      case "tools":
1517          // Display tools list
1518      case "agents":
1519          // Display agent status
1520      case "mcp":
1521          // Display MCP status (planned)
1522      }
1523  }
1524  ```
1525  
1526  ### tools Action
1527  
1528  **Trigger:** `Ctrl+T` or command palette
1529  
1530  **Output:** System message with formatted tool list
1531  
1532  ```
1533  🔧 Available Tools:
1534  
1535  📁 File Operations:
1536    • file_read - Read file contents
1537    • file_write - Write content to files
1538    • file_append - Append to files
1539    • file_list - List directory contents
1540    • get_current_directory - Get current working directory
1541  
1542  ✏️  Editing:
1543    • edit - Single file edit with exact string replacement
1544    • multiedit - Multiple edits to one file atomically
1545  
1546  🐚 Shell:
1547    • shell_execute - Execute shell commands with timeout
1548  
1549  🔍 Search & Discovery:
1550    • view - File viewing with pagination
1551    • grep - Search in file contents
1552    • glob - Find files by pattern
1553    • sourcegraph - Search code across repositories
1554  
1555  🌐 Web:
1556    • download - Download from URLs
1557    • fetch - Fetch web content
1558  
1559  📂 Enhanced Listing:
1560    • ls_tree - Tree structure directory listing
1561    • tree - Color-coded project tree view
1562  
1563  🔧 Git:
1564    • git_status - Repository status
1565    • git_commit - Commit changes
1566    • git_add - Stage files
1567    • git_resolve_conflicts - Auto-resolve merge conflicts
1568  
1569  Total: 21 tools available
1570  ```
1571  
1572  ---
1573  
1574  ### agents Action
1575  
1576  **Trigger:** `Ctrl+A` or command palette
1577  
1578  **Output:** System message with agent status
1579  
1580  ```
1581  🤖 AI Agents Status:
1582  
1583  🔥 Primary Agent:
1584    • Status: Active
1585    • Provider: ollama
1586    • Model: qwen2.5-coder:7b
1587    • Capabilities: Multi-tool execution, conversation memory
1588  
1589  🧠 Specialized Agents:
1590    • Code Agent: Available for code analysis and generation
1591    • Git Agent: Available for repository management
1592    • Web Agent: Available for web scraping and downloads
1593    • File Agent: Available for file system operations
1594  
1595  🎯 Agent Features:
1596    • Real-time streaming responses
1597    • Tool integration (21 tools)
1598    • Context-aware assistance
1599    • Multi-provider support (Ollama, OpenAI, Anthropic, Q)
1600  
1601  All agents ready for deployment!
1602  ```
1603  
1604  ---
1605  
1606  ### mcp Action
1607  
1608  **Trigger:** `Ctrl+M` or command palette
1609  
1610  **Output:** System message about MCP status
1611  
1612  ```
1613  🔌 MCP (Model Context Protocol) Servers:
1614  
1615  📊 Status: Not yet implemented
1616  🚧 Coming Soon:
1617    • File system MCP server
1618    • Git operations MCP server
1619    • Database MCP server
1620    • API integration MCP server
1621  
1622  🎯 Planned Features:
1623    • Real-time server monitoring
1624    • Custom MCP server integration
1625    • Protocol-compliant communication
1626    • Extensible plugin architecture
1627  
1628  MCP integration is planned for future releases.
1629  ```
1630  
1631  ---
1632  
1633  ## Help System
1634  
1635  **Trigger:** Command palette → `help`
1636  
1637  **Output:** Comprehensive help text covering:
1638  
1639  ### Keyboard Shortcuts
1640  ```
1641  ⌨️  KEYBOARD SHORTCUTS:
1642    [Ctrl+P]  - Open command palette (access all features)
1643    [Ctrl+S]  - Toggle sidebar visibility (consciousness metrics)
1644    [Ctrl+T]  - Show available tools
1645    [Ctrl+A]  - Switch agents (Kamaji, Moe, Chihiro, Hayao, etc.)
1646    [Ctrl+C]  - Exit Kamaji
1647    [↑/↓]     - Navigate command palette/menus
1648    [Enter]   - Execute selected command
1649    [Esc]     - Close dialogs/menus
1650  ```
1651  
1652  ### Sidebar Features
1653  ```
1654  📊 SIDEBAR FEATURES (Toggle with Ctrl+S):
1655    • Real-time consciousness metrics
1656    • Self-awareness percentage
1657    • Thought & question count
1658    • Personality trait evolution
1659    • Mistake learning statistics
1660    • Current provider & model info
1661  ```
1662  
1663  ### Consciousness System
1664  ```
1665  🧠 CONSCIOUSNESS SYSTEM:
1666    The sidebar shows Kamaji's evolving consciousness:
1667    - Learns from every interaction
1668    - Tracks mistakes and improves
1669    - Develops personality over time
1670    - Generates self-reflective questions
1671  
1672    Access via Command Palette (Ctrl+P):
1673    • "consciousness" - View full status
1674    • "thoughts" - See recent thought stream
1675    • "personality" - View trait evolution
1676  ```
1677  
1678  ### Agent System
1679  ```
1680  🤖 AGENT SYSTEM:
1681    Multiple specialized agents available (Ctrl+A):
1682    • Kamaji - Wise boiler man (general tasks)
1683    • Moe - Analytical problem solver
1684    • Chihiro - Creative explorer
1685    • Hayao - Visionary director
1686    • Timbl - Advanced reasoning
1687    • Writer - Documentation specialist
1688  
1689    Each agent has unique personality and expertise!
1690  ```
1691  
1692  ### Tools
1693  ```
1694  🔧 TOOLS (Ctrl+T):
1695    21 tools available for file operations, editing,
1696    shell execution, searching, web fetching, and git.
1697  ```
1698  
1699  ### Tips
1700  ```
1701  💡 TIPS:
1702    • Type '@' to autocomplete agent names
1703    • Watch consciousness metrics evolve in sidebar
1704    • Use command palette for quick access to features
1705    • Sidebar adapts to narrow terminals
1706  ```
1707  
1708  ---
1709  
1710  ## Summary
1711  
1712  ### Total Capabilities
1713  
1714  - **21 Tools** across 7 categories
1715  - **20 Commands** in command palette
1716  - **12 Keyboard Shortcuts** for direct access
1717  - **3 Permission Levels** for security
1718  - **Extensible** via MCP protocol (planned)
1719  
1720  ### Key Design Principles
1721  
1722  1. **Discoverability:** Command palette makes everything searchable
1723  2. **Efficiency:** Direct hotkeys for common actions
1724  3. **Safety:** Permission system for sensitive operations
1725  4. **Extensibility:** MCP servers for custom tools
1726  5. **User-Friendly:** Clear descriptions, helpful error messages
1727  6. **Themable:** Consistent Spirited Away / Kamaji aesthetic
1728  
1729  ### Tool Execution Flow
1730  
1731  ```
1732  User Input
17331734  Command Palette / Hotkey
17351736  handlePaletteCommand() / handleDirectAction()
17371738  Tool Registry Lookup
17391740  Permission Check (if required)
17411742  Tool.Call(ctx, input)
17431744  Result / Error
17451746  Display in Viewport
1747  ```
1748  
1749  ### Future Roadmap
1750  
1751  1. **Phase 1 (Current):**
1752     - ✅ 21 built-in tools
1753     - ✅ Command palette
1754     - ✅ Permission system
1755     - ✅ MCP CLI (demo)
1756  
1757  2. **Phase 2 (Planned):**
1758     - 🔲 MCP protocol implementation
1759     - 🔲 Server marketplace
1760     - 🔲 Persistent permissions
1761     - 🔲 Audit logging
1762  
1763  3. **Phase 3 (Future):**
1764     - 🔲 Custom tool development SDK
1765     - 🔲 Tool composition (pipelines)
1766     - 🔲 Multi-agent tool collaboration
1767     - 🔲 Browser-based tool UI
1768  
1769  ---
1770  
1771  **End of Specification**
1772  
1773  *Version: 1.0*
1774  *Last Updated: 2025-11-01*
1775  *Project: Kamaji TUI*