Metadata-Version: 2.4
Name: kader
Version: 2.14.1
Summary: kader coding agent
Project-URL: Homepage, https://github.com/Kader-AI-hub/kader
Project-URL: Documentation, https://kader-ai-hub.github.io/kader/
Project-URL: Issues, https://github.com/Kader-AI-hub/kader/issues
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: aiofiles>=25.1.0
Requires-Dist: anthropic>=0.83.0
Requires-Dist: google-api-core>=2.24.0
Requires-Dist: google-genai>=1.61.0
Requires-Dist: jinja2>=3.1.6
Requires-Dist: loguru>=0.7.3
Requires-Dist: mistralai<=1.12.0
Requires-Dist: ollama>=0.6.1
Requires-Dist: openai>=2.20.0
Requires-Dist: prompt-toolkit>=3.0.50
Requires-Dist: python-frontmatter>=1.1.0
Requires-Dist: pywinpty>=3.0.0; platform_system == 'Windows'
Requires-Dist: pyyaml>=6.0.3
Requires-Dist: rich>=14.0.0
Requires-Dist: tenacity>=9.1.2
Requires-Dist: typer~=0.25.1
Requires-Dist: typing-extensions>=4.15.0
Requires-Dist: wcmatch>=10.1
Description-Content-Type: text/markdown

# Kader

Kader is an intelligent coding agent designed to assist with software development tasks. It provides a comprehensive framework for building AI-powered agents with advanced reasoning capabilities and tool integration.

## Features

- 🤖 **AI-powered Code Assistance** - Support for multiple LLM providers:
  - **Ollama**: Local LLM execution for privacy and speed.
  - **Ollama Cloud**: Cloud-based models via [ollama.com](https://ollama.com).
  - **Google Gemini**: Cloud-based powerful models via the Google GenAI SDK.
  - **Anthropic**: High-quality Claude models via the Anthropic SDK.
- 🖥️ **Interactive CLI** - Modern terminal interface built with Rich & prompt_toolkit:
  - **Beautiful Output**: Markdown rendering, styled panels, and dynamic tables.
  - **Interactive Tools**: Built-in interactive prompts for model selection and tool confirmation.
- ⚡ **Core CLI** - Lightweight command-line interface for one-shot operations:
  - `kader` - Launch the interactive AI coding agent
  - `kader chat -q "..."` - Send a one-shot query (no persistence)
  - `kader init` - Initialize `.kader` directory and generate KADER.md
  - `kader model` - Show and switch LLM models
  - `kader update` - Check for and install updates
  - `kader connect` - Connect an LLM provider by setting its API key
- 🛠️ **Tool Integration** - File system, command execution, web search, and more.
- 🧠 **Memory Management** - State persistence, conversation history, and isolated sub-agent memory.
- 🔁 **Session Management** - Save and load conversation sessions.
- ⌨️ **Keyboard Shortcuts** - Efficient navigation and operations.
- 📝 **YAML Configuration** - Agent configuration via YAML files.
- 🔄 **Planner-Executor Framework** - Sophisticated reasoning and acting architecture using task planning and delegation.
- 🗂️ **File System Tools** - Read, write, search, and edit files with automatic `.gitignore` filtering.
- 🤝 **Agent-As-Tool** - Spawn sub-agents for specific tasks with isolated memory and automated context aggregation.
- 🎯 **Agent Skills** - Modular skill system for specialized domain knowledge and task-specific instructions.
- ⚡ **Special Commands** - Create custom command agents from `CONTENT.md` files in `~/.kader/commands`
- 🔧 **Custom Tools** - Create custom tools for specific tasks, available to planner and/or executor agents

## Installation

### Prerequisites

- Python 3.11 or higher
- [Ollama](https://ollama.ai/) (optional, for local LLMs)
- [uv](https://docs.astral.sh/uv/) package manager (recommended) or [pip](https://pypi.org/project/pip/)

### Using uv (recommended)

```bash
# Clone the repository
git clone https://github.com/your-repo/kader.git
cd kader

# Install dependencies with uv
uv sync

# Run the CLI
uv run python -m cli
```

### Using uv tool

With uv tool, you can install Kader globally and run it directly with the `kader` command:

```bash
# Install Kader globally using uv tool
uv tool install kader

# Run the CLI
kader
```

### Using pip

```bash
# Clone the repository
git clone https://github.com/your-repo/kader.git
cd kader

# Install in development mode
pip install -e .

# Run the CLI
python -m cli
```

## Quick Start

### Running the CLI

```bash
# Launch the interactive Kader CLI
kader

# Or run a one-shot operation
kader init       # Initialize .kader directory
kader model      # Show and switch LLM models
kader update     # Check for and install updates
kader connect    # Set up provider API keys
kader chat -q "Write a hello world in Python"  # One-shot query

# Using uv or pip
uv run python -m cli
python -m cli

### First Steps in CLI

Once the CLI is running:

1. Type any question to start chatting with the agent.
2. Use `/help` to see available commands.
3. Use `/connect` to set up a provider's API key interactively.
4. Use `/models` to check and interactively switch available models.
5. Run terminal commands directly by prefixing with `!` (e.g. `!ls -la`).

## Configuration

When the kader module is imported for the first time, it automatically creates a `.kader` directory in your home directory and a `.env` file.

### Environment Variables

The application automatically loads environment variables from `~/.kader/.env`:

- `OLLAMA_API_KEY`: API key for Ollama Cloud (for cloud models at ollama.com). Get your key from https://ollama.com/settings
- `GOOGLE_API_KEY`: API key for Google Gemini (required for Google Provider).
- `ANTHROPIC_API_KEY`: API key for Anthropic Claude (required for Anthropic Provider).
- Additional variables can be added to the `.env` file and will be automatically loaded.

### Memory and Sessions

Kader stores data in `~/.kader/`:

- Sessions: `~/.kader/memory/sessions/`
- Configuration: `~/.kader/`
- Memory files: `~/.kader/memory/`
- Checkpoints: `~/.kader/memory/sessions/<session-id>/executors/` (Aggregated context from sub-agents)

### Settings

User preferences are stored in `~/.kader/settings.json`, created automatically on first run:

```json
{
  "main-agent-provider": "ollama",
  "sub-agent-provider": "ollama",
  "main-agent-model": "glm-5:cloud",
  "sub-agent-model": "glm-5:cloud",
  "auto-update": false,
  "callbacks": [],
  "tools": []
}
```

| Field                 | Description                               | Default       |
| --------------------- | ----------------------------------------- | ------------- |
| `main-agent-provider` | LLM provider for the planner agent        | `ollama`      |
| `sub-agent-provider`  | LLM provider for executor sub-agents      | `ollama`      |
| `main-agent-model`    | Model name for the planner agent          | `glm-5:cloud` |
| `sub-agent-model`     | Model name for executor sub-agents        | `glm-5:cloud` |
| `auto-update`         | Automatically update Kader on startup     | `false`       |
| `callbacks`           | List of user-level callbacks to enable    | `[]`          |
| `tools`               | List of user-level custom tools to enable | `[]`          |

#### Auto-Update

When `auto-update` is set to `true`, Kader will automatically check for and install updates on every startup using `uv tool upgrade kader`. The update is performed silently.

You can also manually check for updates using the `/update` command. If a newer version is available, it will upgrade Kader and restart the CLI. If you're already on the latest version, it will display a confirmation message.

## CLI Commands

### Core CLI Commands

| Command | Description |
| ------- | ----------- |
| `kader` | Launch the interactive AI coding agent |
| `kader chat -q "..."` | Send a one-shot query to the AI agent (no persistence) |
| `kader init` | Initialize .kader directory and generate KADER.md |
| `kader model` | Show and switch LLM models |
| `kader update` | Check for and install updates |
| `kader connect` | Connect an LLM provider by setting its API key |
| `kader --version` / `-v` | Show the installed version |

### Interactive CLI Commands

| Command     | Description                                                      |
| ----------- | ---------------------------------------------------------------- |
| `/connect`  | Connect a provider by setting its API key                        |
| `/help`     | Show command reference                                           |
| `/models`   | Show available models (Ollama local & cloud, Google & Anthropic) |
| `/clear`    | Clear conversation and create new session                        |
| `/sessions` | List and load saved sessions                                     |
| `/skills`   | List loaded skills                                               |
| `/commands` | List special commands                                            |
| `/cost`     | Show usage costs                                                 |
| `/init`     | Initialize .kader directory with KADER.md                        |
| `/update`   | Check for updates and update Kader if newer version available    |
| `/exit`     | Exit the CLI                                                     |
| `!cmd`      | Run terminal command                                             |

### Keyboard Shortcuts

| Shortcut | Action                   |
| -------- | ------------------------ |
| `Ctrl+C` | Cancel current operation |
| `Ctrl+D` | Exit the CLI             |

## Project Structure

```
kader/
├── cli/                    # Interactive command-line interface
│   ├── app.py             # Main application entry point (Rich + prompt_toolkit)
│   ├── utils.py           # Constants and helpers
│   ├── __init__.py        # Package exports
│   └── commands/          # CLI command handlers
│       ├── base.py        # Base command class
│       ├── connect.py     # /connect command
│       ├── initialize.py  # /init command
│       └── update.py      # /update command
├── examples/              # Example implementations
│   ├── memory_example.py  # Memory management examples
│   ├── google_example.py  # Google Gemini provider examples
│   ├── anthropic_example.py # Anthropic Claude provider examples
│   ├── planner_executor_example.py # Advanced workflow examples
│   ├── skills/           # Agent skills examples
│   │   ├── hello/        # Greeting skill with instructions
│   │   ├── calculator/   # Math calculation skill
│   │   └── react_agent.py # Skills demo with ReAct agent
│   └── README.md         # Examples documentation
├── kader/                # Core framework
│   ├── agent/            # Agent implementations (Planning, ReAct)
│   ├── cli/              # Core CLI (kader command-line interface)
│   ├── memory/           # Memory management & persistence
│   ├── providers/        # LLM providers + LLMProviderFactory
│   ├── tools/            # Tools (File System, Web, Command, AgentTool)
│   ├── prompts/          # Prompt templates (Jinja2)
│   ├── workflows/        # Workflow executors (PlannerExecutorWorkflow)
│   └── utils/            # Utilities (Checkpointer, ContextAggregator)
├── pyproject.toml        # Project dependencies
├── README.md             # This file
└── uv.lock               # Dependency lock file
```

## Core Components

### Agents

Kader provides a robust agent architecture:

- **ReActAgent**: Reasoning and Acting agent that combines thoughts with actions.
- **PlanningAgent**: High-level agent that breaks complex tasks into manageable plans.
- **BaseAgent**: Abstract base class for creating custom agent behaviors.

### LLM Providers

Kader supports multiple backends:

- **OllamaProvider**: Connects to locally running Ollama instances.
- **OllamaProvider (Cloud)**: Connects to cloud models at ollama.com (requires OLLAMA_API_KEY).
- **GoogleProvider**: High-performance access to Gemini models.
- **AnthropicProvider**: Full support for Claude models.

### Agent-As-Tool (AgentTool)

The `AgentTool` allows a `PlanningAgent` (Architect) to delegate work to a `ReActAgent` (Worker). It features:

- **Persistent Memory**: Sub-agent conversations are saved to JSON.
- **Context Aggregation**: Sub-agent research and actions are automatically merged into the main session's `checkpoint.md` via `ContextAggregator`.

### Agent Skills

Kader supports a modular skill system for domain-specific knowledge and specialized instructions:

- **Skill Structure**: Skills are defined as directories containing `SKILL.md` files with YAML frontmatter
- **Skill Loading**: Skills are loaded from `~/.kader/skills` (high priority) and `./.kader/` directories
- **Skill Injection**: Available skills are automatically injected into the system prompt
- **Skills Tool**: Agents can load skills dynamically using the `skills_tool`

### Special Commands

Kader supports special commands — custom command agents that can be invoked from the CLI:

- **Command Structure**: Commands can be defined as either:
  - **Directory**: `<command-name>/CONTENT.md` (can include additional files like templates, assets)
  - **Direct file**: `<command-name>.md` (simple command without extra files)
  - **Sub-commands**: `<command-name>/<subcommand>.md` (multiple commands in one directory)
- **Command Loading**: Commands are loaded from `./.kader/commands/` (higher priority) and `~/.kader/commands/`
- **Command Invocation**: Use `/<command-name> <task>` or `/<command-name>/<subcommand> <task>` to execute a command
- **Memory Persistence**: Command executions are saved to `~/.kader/memory/sessions/<session-id>/executors/<command-name>-<uuid>/conversation.json`

#### Creating a Special Command

**Option 1: Directory format** (with additional files)

```
~/.kader/commands/mycommand/
├── CONTENT.md          # Required - command instructions
├── templates/          # Optional - templates, scripts
└── assets/            # Optional - files
```

**Option 2: Simple file format**

```
~/.kader/commands/mycommand.md
```

**Option 3: Directory with sub-commands**

```
~/.kader/commands/mycommand/
├── CONTENT.md           # Main command (/mycommand)
├── subcommand1.md       # Sub-command (/mycommand/subcommand1)
├── subcommand2.md       # Sub-command (/mycommand/subcommand2)
├── templates/           # Optional - shared templates
└── assets/             # Optional - shared assets
```

**CONTENT.md or .md file format:**

```yaml
---
description: What this command does
---

# Command Instructions

Your command agent instructions here...

## Guidelines
- Guideline 1
- Guideline 2
```

#### Example: Lint and Test Command

```
~/.kader/commands/lint-test/
└── CONTENT.md
```

```yaml
---
description: Lint and test the codebase
---

You are a Lint and Test Agent. Run linting and tests when requested.

## Instructions

1. Run: uv run ruff check .
2. Run: uv run ruff format --check .
3. Run: uv run pytest -v
4. Report results
```

**Usage:**

```
/lint-test
/lint-test run full check
```

Use `/commands` to list all available special commands.

### Subagents (Custom Sub-Agents)

Subagents are specialized AI agents that can be delegated to by the planner in the Planner-Executor workflow. They are defined as YAML files and automatically discovered and registered as tools that the planner can invoke.

#### Subagent File Format

Subagents are loaded from:

- `./.kader/subagents/` — Project-level subagents (always enabled)
- `~/.kader/subagents/` — User-level subagents (gated by `settings.json`)

Each subagent is a YAML file with the following structure:

**Option 1: Flat file format**

```
~/.kader/subagents/code_reviewer.yaml
```

**Option 2: Directory format** (with additional template files)

```
~/.kader/subagents/code_reviewer/
└── template.yaml
```

**YAML format:**

```yaml
name: code-reviewer
objective: >
  Use for code review tasks including analyzing code quality,
  finding bugs, suggesting improvements, and reviewing pull requests
system_prompt: |
  You are an expert code reviewer specializing in thorough,
  constructive code reviews. Focus on code quality, bug detection,
  and best practices.
tools:
  - read_file
  - read_directory
  - grep
  - glob
```

| Field           | Description                                                               |
| --------------- | ------------------------------------------------------------------------- |
| `name`          | Unique subagent identifier (kebab-case, used as tool name)                |
| `objective`     | Description to help the planner decide when to use this subagent          |
| `system_prompt` | The system prompt defining the subagent's behavior and instructions       |
| `tools`         | List of tool names available to the subagent (empty = all standard tools) |

#### How Subagents Work

1. **Discovery**: On workflow startup, Kader scans subagent directories for YAML files
2. **Registration**: Each discovered subagent becomes an `AgentTool` registered with the planner
3. **Delegation**: The planner can invoke subagents by name (e.g., `code-reviewer`) to handle specialized tasks
4. **Isolation**: Each subagent runs with its own memory context, tool set, and provider
5. **Context Aggregation**: Subagent outputs are automatically aggregated into the session's checkpoint

#### User-Level Subagent Configuration

User-level subagents are controlled via `~/.kader/settings.json`:

```json
{
  "subagents": [
    { "name": "code-reviewer", "enabled": "true" },
    { "name": "research-agent", "enabled": "false" }
  ]
}
```

- `name`: Matches the YAML file stem (e.g., `code-reviewer` from `code_reviewer.yaml`)
- `enabled`: `"true"` to enable, `"false"` to disable
- Subagents not listed in settings are skipped
- Project-level subagents are always enabled regardless of settings

### Subagent UI Context

When your planner delegates tasks to an executor or custom subagent, the CLI shows a distinct UI indicating you are inside a subagent context:

```
[Kader is thinking... spinner]

[^^] Executor Started
│ Entering subagent mode — actions are now executed by Executor │

[Executor is working... spinner]

  ⚡ [executor] read_file: Reading file...
  [+] [executor] read_file completed successfully

[✓] Executor finished
  [+] executor completed successfully
```

This visual distinction helps you understand which agent is executing actions at any point during a conversation.

### Custom Tools

Kader supports custom tools that can be added at user-level or project-level. Custom tools extend agent capabilities beyond built-in tools.

#### Tool Locations

- **Project-level**: `./.kader/custom/tools/` (always enabled)
- **User-level**: `~/.kader/custom/tools/` (requires configuration in settings.json)

#### Creating a Custom Tool

Create a Python file in the tools directory that defines a class extending `BaseTool`:

```python
from kader.tools.base import BaseTool, ParameterSchema, ToolCategory

class MyTool(BaseTool[str]):
    def __init__(self):
        super().__init__(
            name="my_tool",
            description="What my tool does",
            parameters=[
                ParameterSchema(
                    name="param1",
                    type="string",
                    description="Parameter description",
                    required=True,
                ),
            ],
            category=ToolCategory.UTILITY,
        )

    def execute(self, **kwargs: Any) -> str:
        param1 = kwargs.get("param1", "")
        return f"Processed: {param1}"

    async def aexecute(self, **kwargs: Any) -> str:
        return self.execute(**kwargs)

    def get_interruption_message(self, **kwargs: Any) -> str:
        return f"execute my_tool"
```

#### Agent Targeting

Custom tools can be assigned to specific agents:

**For user-level tools** (in settings.json):

```json
{
  "tools": [
    {
      "name": "my_tool.MyTool",
      "enabled": "true",
      "agent": "executor"
    }
  ]
}
```

Agent options: `planner` | `executor` | `both` (default)

**For project-level tools** (in tool directory):
Create an `agent.json` file in the tool directory:

```json
{
  "agent": "both"
}
```

#### Example: DateTimeTool

Project-level tool at `.kader/custom/tools/datetime_tool/`:

```
.kader/custom/tools/datetime_tool/
├── __init__.py
└── agent.json
```

`agent.json`:

```json
{
  "agent": "both"
}
```

Usage:

```
What time is it in Japan?
```

### File System Tools with Gitignore Filtering

The file system tools (`read_directory`, `grep`, `glob`) automatically filter out files and directories that match patterns defined in `.gitignore` files.

You can disable this filtering by passing `apply_gitignore_filter=False` when creating tools:

```python
from pathlib import Path
from kader.tools.filesys import get_filesystem_tools

# With filtering (default)
tools = get_filesystem_tools(base_path=Path.cwd())

# Without filtering
tools = get_filesystem_tools(base_path=Path.cwd(), apply_gitignore_filter=False)
```

Example skill structure:

```
~/.kader/skills/hello/
├── SKILL.md
└── scripts/
    └── hello.py
```

Example skill (`SKILL.md`):

```yaml
---
name: hello
description: Skill for ALL greeting requests
---

# Hello Skill

This skill provides the greeting format you must follow.

## How to greet

Always greet the user with:
- A warm welcome
- Their name if mentioned
- A friendly emoji
```

### Memory Management

- **SlidingWindowConversationManager**: Maintains context within token limits.
- **PersistentSlidingWindowConversationManager**: Auto-saves sub-agent history.
- **Checkpointer**: Generates markdown summaries of agent actions.

## Development

### Setting up for Development

```bash
# Clone the repository
git clone https://github.com/your-repo/kader.git
cd kader

# Install in development mode with uv
uv sync

# Run the CLI
uv run python -m cli
```

### Running Tests

```bash
# Run tests with uv
uv run pytest

# Run tests with specific options
uv run pytest --verbose
```

### Code Quality

Kader uses various tools for maintaining code quality:

```bash
# Run linter
uv run ruff check .

# Format code
uv run ruff format .
```

## Troubleshooting

### Common Issues

- **No models found**: Ensure your providers are correctly configured. Use `/connect` to set API keys interactively. For Ollama, run `ollama serve`.
- **Connection errors**: Verify internet access for cloud providers and local service availability for Ollama.

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines on:

- Setting up your development environment
- Code style guidelines
- Running tests
- Submitting pull requests

### Quick Start for Contributors

```bash
# Fork and clone
git clone https://github.com/your-username/kader.git
cd kader

# Install dependencies
uv sync

# Run tests
uv run pytest

# Run linter
uv run ruff check .
```

### Coding with AI

This project includes a specialized skill for AI coding agents. When working with AI assistants on this codebase, they should use the `contributing-to-kader` skill located in [`.kader/skills/contributing-to-kader`](.kader/skills/contributing-to-kader). This skill provides AI agents with essential guidelines including:

- Core development rules (linting, formatting, testing)
- Key commands for development workflow
- Project structure overview
- Best practices for contributing

AI assistants can load this skill using the skills_tool to get specialized instructions for working with this project.

## License

This project is licensed under the MIT License - see the LICENSE file for details.

## Acknowledgments

- Built with [Rich](https://github.com/Textualize/rich) and [prompt_toolkit](https://python-prompt-toolkit.readthedocs.io/) for the beautiful CLI interface.
- Uses [Ollama](https://ollama.ai/) for local LLM execution.
- Powered by [Google Gemini](https://ai.google.dev/) for advanced cloud-based reasoning.
- Enhanced by [Anthropic Claude](https://www.anthropic.com/) for high-quality coding assistance.
