---
title: CLI
description: Comprehensive guide to the ChatBotKit CLI featuring autonomous agent mode for local file system operations, coding assistance, business automation workflows, and complete API management capabilities.
tags:
  - CLI
  - Agent
  - Automation
  - Development
category: Tooling
source: local
---

The ChatBotKit CLI is a powerful command-line tool that combines autonomous AI agent capabilities with comprehensive API management. It enables you to run AI-powered automation directly in your local environment while seamlessly integrating with the full ChatBotKit platform.

## Installation

Install the CLI globally using npm:

```bash
npm install --global @chatbotkit/cli
```

**Requirements:**
- Node.js 14.x or higher
- A ChatBotKit API token
- Terminal or command prompt access

## Authentication

The CLI requires a ChatBotKit API token for authentication. You can configure this using environment variables with flexible configuration options.

### Environment Variable Setup

Set your API token using one of these methods:

**Option 1: Global Configuration (Recommended)**

Create a global configuration file at `~/.cbk/env`:

```bash
# Create the directory
mkdir -p ~/.cbk

# Create the env file
cat > ~/.cbk/env << EOF
CHATBOTKIT_API_TOKEN=your_api_token_here
EOF
```

**Option 2: Project-Level Configuration**

Create a `.env` or `.env.local` file in your project directory:

```bash
# .env.local
CHATBOTKIT_API_TOKEN=your_api_token_here
```

**Option 3: Shell Environment Variable**

```bash
export CHATBOTKIT_API_TOKEN=your_api_token_here
```

### Configuration Precedence

The CLI loads environment variables in this order (first match wins):

1. `.env.local` - Project-specific local configuration (current directory)
2. `.env` - Project configuration (current directory)
3. `~/.cbk/env` - Global user configuration (home directory)
4. Shell environment variables

This allows you to have a global configuration while being able to override it per-project when needed.

### Partner API Configuration

For multi-tenant applications, you can run operations as a specific user:

```bash
# In ~/.cbk/env or .env.local
CHATBOTKIT_API_TOKEN=your_token
RUNAS_USERID=user_123
```

## Agent Mode

**Agent mode is the most powerful feature of the ChatBotKit CLI**, enabling autonomous AI agents to interact with your local file system, execute commands, and perform complex automation tasks. This makes it perfect for coding assistance, business automation workflows, and development tasks.

### What is Agent Mode?

Agent mode runs an AI agent that can:

- **Read and write files** in your local file system
- **Execute shell commands** with configurable timeouts
- **Edit files intelligently** with precise string replacements
- **Search for files** using glob patterns
- **Access all ChatBotKit platform features** including integrations, datasets, skillsets, and custom abilities

The agent operates autonomously, breaking down tasks, executing them step-by-step, and iterating until completion.

### Basic Agent Usage

Execute a task with a simple command:

```bash
cbk agent -p "Create a README.md file with a project description"
```

The agent will:
1. Analyze the task
2. Determine the necessary steps
3. Execute file operations
4. Verify the result
5. Report completion status

### Agent Options

```bash
cbk agent [options]

Options:
  -p, --prompt <text>        Task to execute (required)
  -b, --bot <botId>          Use specific bot configuration
  -m, --model <name>         AI model to use (default: gpt-4o)
  -t, --tools <names...>     Comma-separated tools to enable
  -i, --max-iterations <n>   Maximum iterations (default: 50)
```

### Available Tools

The agent has access to these local file system tools:

**read**
- Read file contents
- Returns full file content as text

```bash
# Example task using read
cbk agent -p "Read package.json and tell me the current version"
```

**write**
- Create new files or overwrite existing ones
- Write string content to specified path

```bash
# Example task using write
cbk agent -p "Create a new file 'test.txt' with hello world"
```

**edit**
- Replace exact string occurrences in files
- Ensures only one match exists (prevents accidental multi-replace)
- Perfect for precise code modifications

```bash
# Example task using edit
cbk agent -p "In index.js, change the port from 3000 to 8080"
```

**find**
- Search for files using glob patterns
- Returns list of matching file paths
- Useful for discovery before operations

```bash
# Example task using find
cbk agent -p "Find all JavaScript files in the src directory"
```

**exec**
- Execute shell commands with timeout protection
- Non-interactive only (commands must exit automatically)
- Default 30-second timeout, configurable

```bash
# Example task using exec
cbk agent -p "Run npm install and show the output"
```

### Restricting Tools

For security or specific use cases, limit which tools the agent can use:

```bash
# Only allow reading and writing, no command execution
cbk agent -t read,write -p "Analyze config.json and create backup"

# Only allow file operations, no editing
cbk agent -t read,write,find -p "Find and backup all .env files"
```

### Agent Mode Examples

**Coding Assistant:**

```bash
# Analyze and refactor code
cbk agent -p "Review src/index.js and suggest improvements"

# Generate boilerplate
cbk agent -p "Create a Express.js server with CORS and error handling"

# Update dependencies
cbk agent -p "Check package.json and update outdated dependencies"
```

**Business Automation:**

```bash
# Data processing
cbk agent -p "Read sales.csv, calculate totals, and create summary.txt"

# Report generation
cbk agent -p "Analyze logs from the past week and generate a report"

# Backup automation
cbk agent -p "Create backups of all config files in a backup directory"
```

**Development Workflows:**

```bash
# Project setup
cbk agent -p "Initialize a new TypeScript project with eslint and prettier"

# Testing
cbk agent -p "Run the test suite and create a coverage report"

# Documentation
cbk agent -p "Generate API documentation from src/routes/*.js"
```

**Complex Multi-Step Tasks:**

```bash
# Read a prompt file for complex instructions
cbk agent -p task-description.txt

# Use specific bot with custom configuration
cbk agent -b bot_abc123 -p "Implement the feature described in requirements.md"

# Long-running tasks with higher iteration limit
cbk agent -i 100 -p "Refactor the entire codebase following best practices"
```

### Agent Output

The agent provides structured output showing its progress:

```bash
$ cbk agent -p "Create a test file"

╭─ Iteration 0 ─╮
{
  "tool": "write",
  "status": "running",
  "args": {
    "path": "test.js",
    "content": "console.log('Hello World')"
  }
}
{
  "tool": "write",
  "status": "completed",
  "result": { "success": true }
}

> I've created test.js with a simple hello world example.

{
  "status": "success",
  "exitCode": 0
}
```

### Platform Integration

Agent mode runs with full ChatBotKit platform capabilities:

- **Integrations**: Access third-party services you've configured
- **Datasets**: Reference knowledge bases during execution
- **Skillsets**: Use custom abilities and functions
- **Bots**: Leverage specific bot configurations with `-b` option
- **Secrets**: Access stored credentials securely

This means your local agent can interact with external APIs, databases, and services while working on local files.

### Agent Best Practices

1. **Be specific in prompts**: Clear instructions lead to better results
2. **Use prompt files**: Store complex instructions in text files
3. **Restrict tools when appropriate**: Limit capabilities for specific tasks
4. **Monitor iterations**: Adjust max iterations based on task complexity
5. **Test incrementally**: Start with simple tasks, build to complex workflows
6. **Review changes**: Always review file modifications before committing
7. **Use version control**: Run agent in git repositories to track changes

## Interactive Chat Mode

For conversational interactions with file system access:

```bash
cbk chat [options]

Options:
  -b, --bot <botId>       Use specific bot
  -m, --model <name>      AI model to use
  -t, --tools <names...>  Available tools for the chat session
```

**Example:**

```bash
# Start chat with all tools
cbk chat

# Start chat with specific tools
cbk chat -t read,write

# Use custom bot
cbk chat -b bot_abc123
```

In chat mode, you can have an ongoing conversation where the AI can use tools to interact with your file system based on your requests.

## API Management Commands

The CLI provides comprehensive access to ChatBotKit API resources through the `cbk api` command.

### General API Command Structure

```bash
cbk api <resource> <operation> [arguments] [options]
```

### Conversation Management

```bash
# List conversations
cbk api conversation list

# Create a conversation
cbk api conversation create --bot bot_abc123

# Fetch conversation details
cbk api conversation fetch conv_xyz789

# Update conversation
cbk api conversation update conv_xyz789 --name "Updated Name"

# Delete conversation
cbk api conversation delete conv_xyz789

# Complete conversation (get response)
cbk api conversation complete conv_xyz789 --message "Hello"

# List messages in a conversation
cbk api conversation message list conv_xyz789

# Create a message
cbk api conversation message create conv_xyz789 \
  --type user \
  --text "What's the weather?"
```

### Bot Management

```bash
# List bots
cbk api bot list

# Fetch bot details
cbk api bot fetch bot_abc123

# Create bot
cbk api bot create \
  --name "Support Bot" \
  --model glm-5.2 \
  --backstory "You are a helpful assistant"

# Update bot
cbk api bot update bot_abc123 \
  --name "Updated Name" \
  --model glm-5.2

# Delete bot
cbk api bot delete bot_abc123
```

### Dataset Management

```bash
# List datasets
cbk api dataset list

# Create dataset
cbk api dataset create \
  --name "Knowledge Base" \
  --description "Company documentation"

# Fetch dataset
cbk api dataset fetch dataset_abc123

# Update dataset
cbk api dataset update dataset_abc123 --name "New Name"

# Delete dataset
cbk api dataset delete dataset_abc123

# Search dataset
cbk api dataset search dataset_abc123 --query "installation"
```

### Skillset Management

```bash
# List skillsets
cbk api skillset list

# Create skillset
cbk api skillset create \
  --name "Customer Tools" \
  --description "Tools for customer support"

# Fetch skillset
cbk api skillset fetch skillset_abc123

# Update skillset
cbk api skillset update skillset_abc123 --description "Updated"

# Delete skillset
cbk api skillset delete skillset_abc123
```

### Partner API

Manage multi-tenant accounts:

```bash
# List partner users
cbk api partner user list

# Create partner user
cbk api partner user create \
  --email "client@company.com" \
  --name "Client Name"

# Fetch partner user
cbk api partner user fetch user_abc123

# Update partner user
cbk api partner user update user_abc123 --name "New Name"

# Delete partner user
cbk api partner user delete user_abc123
```

## Solution Management

Solutions provide a way to manage complex ChatBotKit configurations as code.

```bash
# List solutions
cbk solution list

# Create a new solution
cbk solution create my-solution

# Delete a solution
cbk solution delete my-solution

# Sync a solution
cbk solution sync my-solution

# Manage solution resources
cbk solution resource list my-solution
cbk solution resource create my-solution --type bot
cbk solution resource delete my-solution resource-id
```

Solutions allow you to version control your ChatBotKit infrastructure and deploy configurations programmatically.

## Common Workflows

### Local Development Assistant

Use agent mode as a coding assistant:

```bash
# Code review
cbk agent -p "Review the code in src/ and suggest improvements"

# Generate tests
cbk agent -p "Create unit tests for utils/helpers.js"

# Documentation
cbk agent -p "Add JSDoc comments to all functions in api/routes.js"

# Refactoring
cbk agent -p "Refactor database.js to use async/await instead of callbacks"
```

### Automation Workflows

```bash
# Daily reports
cbk agent -p "Analyze yesterday's logs and create a summary report"

# Data processing
cbk agent -p "Process data.csv, clean invalid entries, and save to clean-data.csv"

# Backup automation
cbk agent -p "Backup all configuration files to backup-$(date +%Y%m%d)/"

# Monitoring
cbk agent -p "Check all service endpoints and report their status"
```

### Content Generation

```bash
# Documentation
cbk agent -p "Create a README.md with installation and usage instructions"

# Configuration
cbk agent -p "Generate a .env.example file from .env with dummy values"

# Boilerplate
cbk agent -p "Create a new React component with hooks and TypeScript"
```

### API Integration Testing

```bash
# Create test bot
BOT_ID=$(cbk api bot create --name "Test Bot" --model glm-5.2 | jq -r '.id')

# Test conversation
cbk api conversation complete null \
  --bot-id $BOT_ID \
  --message "Hello, how are you?"

# Clean up
cbk api bot delete $BOT_ID
```

## Error Handling

The CLI provides clear error messages with actionable guidance:

```bash
# Missing authentication
$ cbk api bot list
Error: CHATBOTKIT_API_TOKEN not set
Set your API token in ~/.cbk/env or .env.local

# Invalid resource
$ cbk api bot fetch invalid_id
Error: Bot not found: invalid_id

# Agent task failure
$ cbk agent -p "Do something impossible"
{
  "status": "failed",
  "exitCode": 1,
  "message": "Unable to complete the requested task"
}
```

## Advanced Features

### Custom Models

Specify alternative AI models:

```bash
# Use specific model for agent
cbk agent -m glm-5.2 -p "Complex reasoning task"

# Use specific model for chat
cbk chat -m glm-5.2

# Use custom model for API operations
cbk api conversation complete conv_123 \
  --model glm-5.2 \
  --message "Hello"
```

### Timeout Configuration

Configure execution timeouts for long-running commands:

```bash
# Agent with custom timeout for exec tool
cbk agent -p "Run a 60-second build process with timeout=60"

# The exec tool accepts timeout in the task description
cbk agent -p "Execute 'npm run build' with 120 second timeout"
```

### Prompt Files

Store complex instructions in files:

```bash
# Create prompt file
cat > task.txt << EOF
Please do the following:
1. Read the current package.json
2. Update the version to the next patch version
3. Create a changelog entry
4. Run npm install to update lock file
EOF

# Execute from file
cbk agent -p task.txt
```

### Output Formatting

The CLI automatically detects terminal capabilities:

- **Interactive mode** (TTY): Colorized output, spinners, formatted display
- **Non-interactive mode**: JSON output suitable for piping and parsing

```bash
# Interactive use
cbk agent -p "Create test file"

# Pipe to jq for processing
cbk api bot list | jq '.items[] | .name'

# Save to file
cbk api conversation list > conversations.json
```

## Best Practices

### Security

- **Store tokens securely**: Use `~/.cbk/env` with restricted permissions (`chmod 600`)
- **Never commit tokens**: Add `.env.local` to `.gitignore`
- **Use project-level configs**: Override global config per project when needed
- **Restrict tools**: Limit agent capabilities with `-t` for sensitive operations
- **Review agent actions**: Always verify file changes before committing

### Performance

- **Use specific tools**: Restrict tools to only what's needed
- **Set iteration limits**: Adjust `-i` based on task complexity
- **Batch operations**: Combine related tasks in one agent prompt
- **Use API commands directly**: For simple operations, API commands are faster than agent mode

### Development

- **Version control**: Run agent in git repositories to track changes
- **Incremental testing**: Test agent with simple tasks before complex workflows
- **Prompt engineering**: Be specific and clear in task descriptions
- **Monitor output**: Watch for agent reasoning to understand its approach
- **Use bot configurations**: Create specialized bots for specific automation tasks

### Automation

- **Script repetitive tasks**: Wrap CLI commands in shell scripts
- **Use cron for scheduling**: Schedule periodic agent tasks
- **Log outputs**: Redirect CLI output to logs for auditing
- **Error handling**: Check exit codes in scripts
- **Notification integration**: Pipe results to notification systems

## Troubleshooting

### Authentication Issues

```bash
# Verify token is loaded
cbk api bot list

# Check configuration file
cat ~/.cbk/env

# Test with explicit variable
CHATBOTKIT_API_TOKEN=your_token cbk api bot list
```

### Agent Not Completing Tasks

- Increase max iterations: `-i 100`
- Simplify the prompt: Break into smaller tasks
- Check tool restrictions: Ensure needed tools are enabled
- Review output: Look for error messages in tool calls

### Permission Errors

```bash
# Fix configuration file permissions
chmod 600 ~/.cbk/env

# Verify write permissions for agent
ls -la $(pwd)
```

## Additional Resources

- **CLI Repository**: [https://github.com/chatbotkit/node-sdk/tree/main/packages/cli](https://github.com/chatbotkit/node-sdk/tree/main/packages/cli)
- **API Documentation**: See platform documentation for detailed API specifications
- **Discord Community**: [https://go.cbk.ai/discord](https://go.cbk.ai/discord)
- **Email Support**: support@chatbotkit.com

## Related Tools

- **Node SDK**: [@chatbotkit/sdk](https://www.npmjs.com/package/@chatbotkit/sdk) - Programmatic API access
- **Agent Package**: [@chatbotkit/agent](https://www.npmjs.com/package/@chatbotkit/agent) - Standalone agent library
- **React SDK**: [@chatbotkit/react](https://www.npmjs.com/package/@chatbotkit/react) - React components