Documentation

Everything you need to install, configure, and use Klyxor effectively.

What is Klyxor?

Klyxor is an AI coding agent that runs in your terminal. It connects to any OpenAI-compatible LLM provider, reads and writes files, executes shell commands, and delegates tasks to subagents. Think of it as a coding assistant that lives where you work.

It comes with two distinct modes: Plan (read-only analysis) and Build (full code access). You can switch between them on the fly, manage multiple sessions, and extend its capabilities through a markdown-based skills system.

Key Features

Plan / Build Modes
Read-only planning or full-access execution. Switch anytime.
Subagent Delegation
Spawn nested subagents for parallel tasks (max depth 2).
Multi-Provider LLM
Connect multiple providers, each with multiple models.
Skills System
Markdown skills with triggers, dependencies, and auto-matching.
Streaming
Real-time token-by-token output. See responses as they arrive.
Error Recovery
Auto-retry with exponential backoff. Fallback model on failure.
MCP Integration
Connect to any MCP server for external tools and data.
Refactoring Engine
Analyze code, generate plans, execute with validation.
Multi-Agent Orchestrator
7 specialized agents (frontend, backend, db, devops, security, testing, docs).
Time Machine
Snapshot codebase state, rewind, compare, branch.
Predictive Bug Detection
25+ built-in patterns. Scan files for potential bugs.
Token & Cost Tracking
Per-model usage stats with estimated costs.
Project Context
Auto-loads AGENTS.md, KLYXOR.md, .klyxor/context.md.
Session Persistence
Conversation history saved and resumable across sessions.

Requirements

Installation

Install Klyxor globally via npm:

bash
$ npm install -g @alnyx/klyxor

Verify the installation:

bash
$ klyxor --help
Note

On first launch, Klyxor creates ~/.klyxor/ in your home directory with default config, sessions storage, and skills folder.

Quick Start

Run a one-shot query without entering interactive mode:

bash
# One-shot query
$ klyxor "Write a hello world in Python"

Start in Plan mode for read-only analysis:

bash
# Plan mode
$ klyxor --plan "Design a REST API"

Launch interactive mode:

bash
# Interactive mode
$ klyxor

Set up a provider from the interactive prompt:

bash
# Set your API key
$ export OPENAI_API_KEY=sk-your-key-here

# Or connect via slash command
> /connect openai
> /model gpt-4o

Configuration

All configuration lives in ~/.klyxor/:

text
~/.klyxor/ ├── config.json # Providers, models, API keys ├── sessions.json # Chat session history ├── skills/ # Custom skill files (.md) └── exports/ # Exported session transcripts

config.json

The main configuration file. Providers, models, and API keys all live here:

json
{ "providers": { "openai": { "base_url": "https://api.openai.com/v1", "api_key": "${OPENAI_API_KEY}", "models": ["gpt-4o", "gpt-4o-mini"], "active_model": "gpt-4o" } }, "active_provider": "openai" }

Environment Variable Expansion

API keys support two syntaxes for referencing environment variables:

SyntaxExample
${VAR_NAME}"${OPENAI_API_KEY}"
env:VAR_NAME"env:OPENAI_API_KEY"

Both syntaxes resolve the environment variable at runtime. The key value is never stored in plain text.

Fallback API Key

If a provider's api_key field is empty or missing, Klyxor checks for a KLYXOR_API_KEY environment variable as a universal fallback. This works across all providers.

Environment Variables

VariableDescription
KLYXOR_API_KEY Fallback API key for any provider. Used when a provider's api_key is empty.
OPENAI_API_KEY OpenAI API key. Referenced via ${OPENAI_API_KEY} in config.
ANTHROPIC_API_KEY Anthropic API key. Referenced via ${ANTHROPIC_API_KEY} in config.
Any *_API_KEY Can be referenced in config.json via ${VAR_NAME} or env:VAR_NAME.

Project Context

Klyxor auto-loads specific files from your project root into the system prompt. This gives the agent awareness of your project's conventions, architecture, and constraints without you having to explain them every session.

Auto-loaded Files

FilePurpose
AGENTS.md Standard agent instructions (shared with other AI tools)
KLYXOR.md Klyxor-specific project instructions
.klyxor/context.md Additional context (architecture notes, constraints, etc.)

Place any of these in your project root. They're loaded automatically on startup and included in every LLM call.

Slash Commands

Type these in the interactive prompt. All commands start with /.

CommandDescription
/helpList all available commands
/planSwitch to Plan mode (read-only)
/buildSwitch to Build mode (full access)
/model [name]Show current model or switch to a new one
/connect [name]Connect a provider (format: provider/model)
/skillsList available skills
/skills create <name>Create a new skill
/skills info <name>Show skill details and metadata
/skills find <query>Find skills matching a file or task description
/sessions [name]List sessions or switch to a specific one
/new [name]Create and switch to a new session
/resetClear current session history
/export [path]Export chat transcript to a markdown file
/compactManually compress conversation history
/costShow total usage and estimated cost
/tokensDetailed per-model token breakdown
/toolsList all tools available in current mode
/mcp listList connected MCP servers and their tools
/mcp connect <name>Connect to a configured MCP server
/mcp disconnect <name>Disconnect from an MCP server
/updateCheck for Klyxor updates
/exitSave and exit Klyxor

Modes

Klyxor has two operating modes. You can switch between them at any time with /plan or /build.

Plan Mode

Read-only analysis. The agent can read files, search code, grep, and fetch web pages, but cannot write, edit, or execute commands. Use this for code review, architecture planning, and understanding unfamiliar codebases.

Build Mode

Full access. The agent can read, write, edit files, run shell commands, and delegate tasks. Use this when you're ready to implement changes.

Tip

Start in Plan mode to analyze what needs changing, then switch to Build mode when you're ready to write code. The agent keeps context across mode switches.

Tools Reference

These are the tools available to the agent. Tool availability depends on the current mode.

bash Build only

Execute shell commands. Destructive commands (rm, mv, etc.) are blocked in Plan mode.

command
string - The shell command to execute
Timeout
120 seconds. Commands that exceed this are killed.
read_file Both modes

Read file contents with optional line range.

path
string - Absolute or relative file path
offset
number - Line number to start from (optional, 1-indexed)
limit
number - Max lines to return (optional, default: 2000)
write_file Build only

Create or overwrite a file. Parent directories are created automatically.

path
string - Absolute or relative file path
content
string - Full file content to write
edit_file Build only

Edit files with exact string replacement. Fails if old_text is found zero times or more than once. Provide enough surrounding context to make the match unique.

path
string - File to edit
old_text
string - Exact text to find and replace
new_text
string - Replacement text
list_files Both modes

List directory contents. Supports glob patterns. Skips .git, node_modules, __pycache__, .klyxor.

path
string - Directory path (optional, defaults to current dir)
pattern
string - Glob pattern: *, **/*, **/*.ts, etc.
grep Both modes

Search file contents using regex. Returns file:line:content matches.

pattern
string - Regular expression pattern
path
string - Directory to search in (optional)
include
string - File pattern filter (e.g. *.ts)
delegate Both modes

Delegate a task to a subagent. Subagents can run in plan or build mode independently. Maximum nesting depth: 2 levels.

task
string - Description of what the subagent should do
mode
string - "plan" or "build" (optional, defaults to current mode)
git_status Both modes

Show git status for the current repository. Runs git status --short --branch.

No parameters
git_diff Both modes

Show git diff for the repository or a specific path.

path
string - Specific file or directory (optional)
staged
boolean - Show staged changes if true (optional)
web_fetch Both modes

Fetch a web page and extract its text content. HTML is stripped. Max 8000 characters returned.

url
string - URL to fetch
Timeout
20 seconds
todo_list Both modes

Manage a task list within the session. The full list is shown after every action.

action
string - One of: "add", "update", "delete", "list"
text
string - Task description (for add)
id
number - Task ID (for update/delete)
status
string - "pending", "in_progress", or "completed" (for update)

Extended Tools

http_request Both modes

Make HTTP requests to any URL. Supports GET, POST, PUT, DELETE, PATCH, HEAD.

url
string - URL to request
method
string - HTTP method (default: GET)
headers
object - Request headers (optional)
body
string - Request body (optional)
json_query Both modes

Read JSON files with dot-notation path navigation.

path
string - JSON file path
query
string - Dot-notation path (e.g. users[0].name)
env_read Both modes

Read environment variables. Returns specific var or lists common vars.

name
string - Variable name (optional, lists all if omitted)
file_info Both modes

Get file metadata: size, timestamps, permissions, type flags.

path
string - File path
copy_file Build only

Copy files. Blocked in Plan mode.

source
string - Source file path
destination
string - Destination path
move_file Build only

Move or rename files. Destructive operation.

source
string - Source file path
destination
string - Destination path
diff_apply Build only

Apply unified diff patches to files.

path
string - File to patch
diff
string - Unified diff content
tree Both modes

Display directory tree visualization with SKIP_DIRS filtering.

path
string - Directory path (optional)
depth
number - Max depth (default: 3)
hash Both modes

Hash files or strings with md5, sha1, or sha256.

path
string - File path (optional)
text
string - Text to hash (optional)
algorithm
string - md5, sha1, or sha256 (default: sha256)
base64 Both modes

Base64 encode or decode strings.

action
string - "encode" or "decode"
text
string - Input text

Intelligence Tools

spawn_parallel Both modes

Execute multiple tasks in parallel with separate subagents.

tasks
array - Array of {task, mode?} objects
git_worktree Both modes

Manage git worktrees for parallel branch work.

action
string - add, remove, list, switch, prune
name
string - Worktree name
branch
string - Branch name (for add)
pipeline Build only

Execute multi-step command pipelines with variable interpolation.

name
string - Pipeline name (optional)
steps
string - JSON array of step objects
refactor Build only

Analyze code, generate refactoring plans, execute with validation.

action
string - analyze, plan, execute
path
string - File or directory to analyze
multi_agent Both modes

Access 7 specialized agents: frontend, backend, database, devops, security, testing, documentation.

action
string - list, suggest, describe
agent
string - Agent role name
task
string - Task description (for suggest)
time_machine Both modes

Snapshot codebase state, rewind, compare, and branch.

action
string - snapshot, restore, list, diff, branch, branches, delete
name
string - Snapshot or branch name
predict_bugs Both modes

Scan code for 25+ built-in bug patterns across 7 categories.

action
string - scan, scan-dir, patterns
path
string - File or directory to scan
category
string - Filter by category (optional)
list_skills Both modes

List all available skills in ~/.klyxor/skills/.

No parameters
read_skill Both modes

Read a skill file to load its instructions.

name
string - Skill name (without .md)
find_skills Both modes

Find skills matching a file path or task description.

query
string - File path or task description

Skills System

Skills are markdown files in ~/.klyxor/skills/ that extend the agent's behavior. They load on demand, matched by file extension, task keywords, or explicit triggers.

Skill File Format

markdown
--- name: typescript-refactor description: Best practices for refactoring TypeScript codebases triggers: - refactor - cleanup - typescript tags: - typescript - refactoring version: 1.0.0 requires: - typescript-basics --- # TypeScript Refactoring When refactoring TypeScript code, follow these guidelines...

Frontmatter Fields

FieldTypeDescription
namestringUnique skill identifier
descriptionstringWhat this skill does
triggersstring[]Keywords that activate this skill
tagsstring[]Categorization tags
versionstringSemver version
requiresstring[]Other skills this one depends on

Auto-matching

Skills are automatically matched based on:

Dependencies

Skills can declare dependencies via the requires field. When a skill is loaded, its dependencies are loaded first. This lets you compose complex behaviors from smaller building blocks.

Managing Skills

From the interactive prompt:

MCP Integration

Klyxor supports the Model Context Protocol (MCP) for connecting to external tool servers. MCP lets you extend the agent with tools from any compatible server.

Configuration

Add MCP servers to your config:

json
{
  "mcpServers": {
    "my-server": {
      "name": "my-server",
      "transport": "stdio",
      "command": "npx",
      "args": ["-y", "@my-org/mcp-server"]
    }
  }
}

Commands

Transport Types

Note

MCP tools are prefixed with mcp_<server>_<tool> to avoid naming conflicts. A server providing a search tool becomes mcp_my-server_search.

Streaming

Klyxor supports real-time streaming of LLM responses. Tokens are displayed as they arrive, giving you immediate feedback.

How It Works

When streaming is enabled (default), the agent uses Server-Sent Events (SSE) to receive tokens from the LLM provider. Each token is written to stdout immediately.

Error Recovery

If a stream fails, Klyxor automatically:

  1. Classifies the error (rate limit, timeout, server error, etc.)
  2. Retries with exponential backoff (up to 3 attempts)
  3. Falls back to a backup model if retries fail

Configuration

json
{
  "stream": true,
  "errorRecovery": {
    "maxRetries": 3,
    "fallbackModel": "gpt-4o-mini"
  }
}

Refactoring Engine

Analyze code quality, generate refactoring plans, and execute changes with validation.

Actions

Metrics Detected

Refactoring Actions

Multi-Agent Orchestrator

Access 7 specialized agents optimized for different domains.

Available Agents

AgentDomainExpertise
frontendUI/UXReact, CSS, accessibility, responsive design
backendServerAPIs, databases, authentication, performance
databaseDataSchema design, queries, migrations, optimization
devopsInfrastructureDocker, CI/CD, deployment, monitoring
securitySecurityVulnerabilities, OWASP, authentication, encryption
testingQualityUnit, integration, e2e testing strategies
documentationDocsAPI docs, README, inline comments

Actions

Time Machine

Snapshot your codebase state, rewind to previous points, compare changes, and create branches.

Actions

Storage

Snapshots are stored in .klyxor/snapshots/. Each snapshot contains file contents and metadata. Maximum 100 snapshots, 50 files per snapshot.

Predictive Bug Detection

Scan code for 25+ built-in bug patterns across 7 categories.

Actions

Categories

CategoryExamples
null-safetyUnchecked null/undefined access, optional chaining misses
asyncMissing await, unhandled promises, race conditions
resourceUnclosed resources, missing cleanup, memory leaks
logicOff-by-one errors, unreachable code, empty blocks
typeImplicit any, type coercion issues
securitySQL injection, eval usage, hardcoded secrets
qualityComplex functions, deep nesting, too many parameters

Session Management

Sessions persist your conversation history across restarts. Each session tracks its own mode (plan/build), message history, and todo list.

Creating Sessions

text
# Create a named session > /new auth-refactor # Create an auto-named session > /new # → Creates "session-3" (increments automatically)

Switching Sessions

text
# List all sessions > /sessions # Switch to a specific session > /sessions auth-refactor

Session Storage

All sessions are saved to ~/.klyxor/sessions.json. This includes message history, active mode, and todo state. Sessions are loaded on startup and saved after each interaction.

Resetting a Session

/reset clears the current session's message history but keeps the session itself. Use this when you want a fresh context without creating a new session.

Context Compaction

Long conversations consume tokens fast. Klyxor handles this with automatic context compaction.

How It Works

Manual Trigger

text
> /compact

Run /compact manually when you want to free up context space before starting a new task. The agent keeps the important parts and discards the rest.

Token & Cost Tracking

Klyxor tracks token usage per model with estimated costs. This helps you stay aware of spending.

/cost

Shows total calls, tokens, and estimated cost across all models used in the session.

/tokens

Detailed per-model breakdown showing input tokens, output tokens, and cost for each model that was called.

Note

Costs are estimated using built-in pricing tables. Actual charges may vary by provider and plan. Check your provider's dashboard for exact billing.

Troubleshooting

"Provider not configured"

No active provider is set. Run /connect to list and select a provider, or add one through the config file.

"API key not set"

The provider's API key is missing. Set the environment variable (e.g. export OPENAI_API_KEY=sk-...) or update config.json with the ${ENV_VAR} syntax.

"LLM call failed"

Check your network connection, API key validity, and model availability. Klyxor retries on transient failures (408, 429, 5xx) with exponential backoff. If it keeps failing, try a different model or provider.

Context too long / slow responses

Your conversation has grown large. Run /compact to summarize old messages and free up context space. You can also /reset to start fresh.

"Command not found: klyxor"

Klyxor isn't in your PATH. Run npm install -g @alnyx/klyxor again. On some systems, you may need to use sudo or configure npm's global prefix.

API Reference

Klyxor connects to any OpenAI-compatible API. This means you can use it with OpenAI, Anthropic (via compatible endpoints), local models (Ollama, vLLM), or any provider that implements the OpenAI chat completions format.

Provider Configuration

FieldTypeDescription
base_urlstringAPI endpoint URL (must be OpenAI-compatible)
api_keystringAuthentication key (supports env var expansion)
modelsstring[]List of available model IDs
active_modelstringCurrently selected model from the list

Example: Adding a Local Provider

json
{ "providers": { "ollama": { "base_url": "http://localhost:11434/v1", "api_key": "ollama", "models": ["llama3", "codellama", "mistral"], "active_model": "codellama" } }, "active_provider": "ollama" }

Default Parameters

ParameterValue
Temperature0.1
Max tokens4096
Max turns per query200
LLM timeout120s
Retry attempts3
Retry backoffExponential (2s, 4s, 8s)