JSPM

  • Created
  • Published
  • Downloads 17
  • Score
    100M100P100Q92805F
  • License MIT

AI-powered development assistant with memory and learning capabilities

Package Exports

  • khawarizm

Readme

Khawarizm Core Package

The core package of Khawarizm, providing the main CLI interface, agent system, tool execution, and session management.

Overview

Khawarizm is an AI-powered development assistant that provides intelligent help for building, managing, and deploying projects. This package contains the core functionality including:

  • Agent System - AI agents with different capabilities and permission levels
  • Tool System - Extensible tools for file operations, bash commands, web fetching, etc.
  • Session Management - Persistent conversation sessions with message history
  • CLI Interface - Command-line interface for all operations
  • Configuration System - Flexible configuration with permission modes and agent customization

Installation

Global Installation

# Install via npm
npm install -g @khawarizm-ai/khawarizm

# Install via bun
bun add -g @khawarizm-ai/khawarizm

# Install via yarn
yarn global add @khawarizm-ai/khawarizm

Development Installation

# Clone the repository
git clone https://github.com/khawarizm-ai/khawarizm.git
cd khawarizm

# Install dependencies
bun install

# Build the project
bun run build

# Link for development
bun link

Quick Start

1. Authentication

First, authenticate with your preferred AI provider:

# Interactive provider selection
khawarizm auth login

# Or specify provider directly
khawarizm auth login openai
khawarizm auth login anthropic

2. Basic Usage

# Start the Terminal User Interface
khawarizm tui

# Or use the CLI directly
khawarizm run "Help me refactor this function"

# Continue the last session
khawarizm run --continue

3. Configuration

Create a project configuration:

# Create khawarizm.json
cat > khawarizm.json << EOF
{
  "$schema": "https://khawarizm.ai/config.json",
  "model": "anthropic/claude-3-sonnet",
  "permission": {
    "mode": "auto-low"
  }
}
EOF

Architecture

Core Components

Agent System

Agents are AI entities with specific capabilities and permission levels:

import { Agent } from "@khawarizm-ai/core"

// List available agents
const agents = await Agent.list()

// Get specific agent
const agent = await Agent.get("build")

// Execute agent
const result = await agent.execute({
  prompt: "Build a REST API",
  sessionID: "session-id",
})

Tool System

Tools are the building blocks that agents use to interact with your system:

import { Tool } from "@khawarizm-ai/core"

// Execute a tool directly
const result = await Tool.execute("bash", {
  command: "ls -la",
  description: "List files in current directory",
})

Available tools:

  • File Operations: read, write, edit, list
  • Search: glob, grep
  • System: bash
  • Web: webfetch
  • Productivity: todowrite, todoread

Session Management

Sessions provide persistent conversation history:

import { Session } from "@khawarizm-ai/core"

// Create new session
const session = await Session.create({
  title: "Development Session",
})

// Continue existing session
const existing = await Session.get("session-id")

// List all sessions
const sessions = await Session.list()

CLI Commands

Core Commands

Command Description Example
run Execute Khawarizm with a message khawarizm run "Help me debug"
tui Start Terminal User Interface khawarizm tui
auth Manage credentials khawarizm auth login
agent Manage agents khawarizm agent create
models List available models khawarizm models

Development Commands

Command Description Example
debug Debug utilities khawarizm debug config
doctor Health check khawarizm doctor
upgrade Upgrade Khawarizm khawarizm upgrade
generate Generate OpenAPI spec khawarizm generate

Git Integration

Command Description Example
commit Smart commits khawarizm commit
pr Pull request management khawarizm pr create
test Test management khawarizm test run

Configuration

Configuration Files

Khawarizm loads configuration from multiple sources:

  1. Global: ~/.khawarizm/config.json
  2. Project: ./khawarizm.json
  3. Directory: ./.khawarizm/khawarizm.json

Example Configuration

{
  "$schema": "https://khawarizm.ai/config.json",
  "model": "anthropic/claude-3-sonnet",
  "small_model": "anthropic/claude-3-haiku",
  "permission": {
    "mode": "auto-low"
  },
  "agent": {
    "build": {
      "description": "Full development mode",
      "permission": {
        "mode": "auto-medium"
      }
    },
    "review": {
      "description": "Code review mode",
      "permission": {
        "mode": "spec"
      }
    }
  },
  "share": "auto",
  "theme": "dark"
}

Permission Modes

  • default - Manual control (ask for all actions)
  • spec - Research and planning only
  • auto-low - Allow file edits and read-only commands
  • auto-medium - Allow reversible commands
  • auto-high - Allow all commands

Development

Project Structure

src/
├── agent/          # Agent system
├── tool/           # Tool implementations
├── session/        # Session management
├── cli/            # CLI commands
├── config/         # Configuration system
├── provider/       # AI provider integrations
├── bus/            # Event system
├── project/        # Project management
└── index.ts        # Main entry point

Building

# Install dependencies
bun install

# Build TypeScript
bun run build

# Run tests
bun test

# Lint code
bun run lint

# Format code
bun run format

Testing

# Run all tests
bun test

# Run specific test file
bun test test/session.test.ts

# Run with coverage
bun test --coverage

API Reference

Core Classes

Agent

class Agent {
  static list(): Promise<Agent.Info[]>
  static get(name: string): Promise<Agent.Info>
  static generate(options: { description: string }): Promise<GeneratedAgent>

  async execute(options: { prompt: string; sessionID: string; model?: string }): Promise<Agent.Result>
}

Session

class Session {
  static create(options: { title?: string }): Promise<Session.Info>
  static get(id: string): Promise<Session.Info>
  static list(): AsyncIterable<Session.Info>
  static share(id: string): Promise<void>

  static prompt(options: {
    sessionID: string
    agent: string
    model: { providerID: string; modelID: string }
    parts: Message.Part[]
  }): Promise<Session.Result>
}

Tool

class Tool {
  static execute<T = any>(name: string, input: Record<string, any>): Promise<T>

  static list(): Promise<Tool.Info[]>
}

Configuration Types

interface Config {
  model?: string // Default model
  small_model?: string // Small model for auxiliary tasks
  permission?: {
    mode?: PermissionMode
    edit?: Permission
    bash?: Permission | Record<string, Permission>
    webfetch?: Permission
  }
  agent?: Record<string, Agent.Config>
  provider?: Record<string, Provider.Config>
  theme?: string
  share?: "manual" | "auto" | "disabled"
}

Environment Variables

Variable Description Example
KHAWARIZM_CONFIG Path to custom config file /path/to/config.json
KHAWARIZM_PERMISSION JSON permission override {"mode":"auto-low"}
OPENCODE_DISABLE_AUTOUPDATE Disable auto updates 1
OPENCODE_AUTO_SHARE Enable auto sharing 1

Provider Configuration

OpenAI

{
  "provider": {
    "openai": {
      "apiKey": "{env:OPENAI_API_KEY}",
      "baseURL": "https://api.openai.com/v1",
      "models": {
        "gpt-4": {
          "maxTokens": 8192
        }
      }
    }
  }
}

Anthropic

{
  "provider": {
    "anthropic": {
      "apiKey": "{env:ANTHROPIC_API_KEY}",
      "baseURL": "https://api.anthropic.com",
      "models": {
        "claude-3-sonnet-20240229": {
          "maxTokens": 200000
        }
      }
    }
  }
}

Custom Agents

Create custom agents in .khawarizm/agent/:

---
description: "Database migration specialist"
mode: "primary"
tools:
  bash: true
  read: true
  write: true
  edit: true
permission:
  mode: "auto-low"
---

You are a database migration specialist. Focus on creating safe, reversible database migrations. Always:

1. Analyze current schema
2. Plan migration steps
3. Create rollback procedures
4. Test migrations thoroughly
5. Document changes

When working with databases, prioritize data integrity and minimize downtime.

Custom Commands

Create custom commands in .khawarizm/command/:

---
description: "Deploy to production"
agent: "build"
model: "anthropic/claude-3-sonnet"
subtask: true
---

Deploy the current application to production environment:

1. Run all tests
2. Build the application
3. Deploy to staging environment
4. Run smoke tests
5. Promote to production
6. Verify deployment

Ensure rollback procedures are in place before deployment.

Integration

Language Server Protocol

Configure LSP servers for enhanced IDE integration:

{
  "lsp": {
    "typescript": {
      "command": ["typescript-language-server", "--stdio"],
      "extensions": [".ts", ".tsx", ".js", ".jsx"]
    },
    "python": {
      "command": ["pylsp"],
      "extensions": [".py"]
    }
  }
}

Model Context Protocol

Connect to MCP servers for additional tools:

{
  "mcp": {
    "filesystem": {
      "type": "local",
      "command": ["npx", "@modelcontextprotocol/server-filesystem", "/path/to/project"],
      "enabled": true
    }
  }
}

Troubleshooting

Common Issues

  1. Authentication fails

    # Check configured providers
    khawarizm auth list
    
    # Re-authenticate
    khawarizm auth login
  2. Configuration errors

    # Validate configuration
    khawarizm debug config
    
    # Check paths
    khawarizm debug paths
  3. Permission issues

    # Run health check
    khawarizm doctor

Debug Mode

Enable debug logging:

khawarizm --log-level DEBUG run "test message"

Getting Help

# General help
khawarizm --help

# Command-specific help
khawarizm run --help

# Check system health
khawarizm doctor

Contributing

Development Setup

# Clone repository
git clone https://github.com/khawarizm-ai/khawarizm.git
cd khawarizm

# Install dependencies
bun install

# Setup development environment
bun run dev

# Run tests
bun test

Code Style

  • Use TypeScript for all new code
  • Follow existing code patterns
  • Add JSDoc comments for public APIs
  • Run bun run format before committing

Submitting Changes

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

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

Support