> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orcbot.buzzchat.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Configuration

> Configure OrcBot with YAML files, environment variables, and hot-reload settings

## Configuration File Structure

OrcBot uses a hierarchical YAML-based configuration system that supports multiple config file locations, environment variable overrides, and hot-reload capabilities.

### Configuration Priority

OrcBot reads configuration in this order (highest priority first):

<Steps>
  <Step title="Environment Variables">
    Environment variables like `OPENAI_API_KEY`, `TELEGRAM_TOKEN` take precedence
  </Step>

  <Step title="Local Config">
    `./orcbot.config.yaml` in your current working directory
  </Step>

  <Step title="Home Config">
    `~/orcbot.config.yaml` in your home directory
  </Step>

  <Step title="Global Config">
    `~/.orcbot/orcbot.config.yaml` (default location)
  </Step>
</Steps>

### Basic Configuration File

Create your configuration file at `~/.orcbot/orcbot.config.yaml`:

```yaml theme={null}
# ~/.orcbot/orcbot.config.yaml

# LLM Provider Configuration
llmProvider: openai
modelName: gpt-4o-mini
openaiApiKey: sk-your-key-here

# Alternative providers
# googleApiKey: your-google-api-key
# openrouterApiKey: your-openrouter-key
# anthropicApiKey: your-anthropic-key

# Agent Identity
agentName: OrcBot

# Channel Tokens
telegramToken: your-telegram-bot-token
discordToken: your-discord-bot-token

# Autonomy Settings
autonomyEnabled: true
autonomyInterval: 300000  # 5 minutes in milliseconds
autonomyBacklogLimit: 10
autonomyAllowedChannels:
  - telegram
  - discord

# Task Execution Limits
maxStepsPerAction: 20
maxMessagesPerAction: 5
messageDedupWindow: 15

# Safety & Security
safeMode: false
sudoMode: false
adminUsers:
  telegram:
    - "123456789"  # Your Telegram user ID
  discord:
    - "987654321"  # Your Discord user ID

# Memory & Context
memoryContextLimit: 15
journalContextLimit: 1000
learningContextLimit: 1000
userContextLimit: 1500

# Web Gateway
gatewayPort: 3100
gatewayHost: 0.0.0.0
gatewayApiKey: your-secret-api-key

# Browser Settings
browserHeadless: true
browserMaxConcurrent: 2
```

## Environment Variables

### API Keys

<CodeGroup>
  ```bash Linux/macOS theme={null}
  export OPENAI_API_KEY="sk-your-key-here"
  export TELEGRAM_TOKEN="your-telegram-bot-token"
  export GOOGLE_API_KEY="your-google-api-key"
  export SERPER_API_KEY="your-serper-api-key"
  ```

  ```powershell Windows theme={null}
  $env:OPENAI_API_KEY="sk-your-key-here"
  $env:TELEGRAM_TOKEN="your-telegram-bot-token"
  $env:GOOGLE_API_KEY="your-google-api-key"
  $env:SERPER_API_KEY="your-serper-api-key"
  ```

  ```yaml Docker Compose theme={null}
  environment:
    - OPENAI_API_KEY=sk-your-key-here
    - TELEGRAM_TOKEN=your-telegram-bot-token
    - GOOGLE_API_KEY=your-google-api-key
    - SERPER_API_KEY=your-serper-api-key
  ```
</CodeGroup>

### Supported Environment Variables

| Variable               | Purpose                                        |
| ---------------------- | ---------------------------------------------- |
| `OPENAI_API_KEY`       | OpenAI API authentication                      |
| `GOOGLE_API_KEY`       | Google Gemini API authentication               |
| `ANTHROPIC_API_KEY`    | Anthropic Claude API authentication            |
| `OPENROUTER_API_KEY`   | OpenRouter API authentication                  |
| `NVIDIA_API_KEY`       | NVIDIA NIM API authentication                  |
| `SERPER_API_KEY`       | Serper search API                              |
| `BRAVE_SEARCH_API_KEY` | Brave search API                               |
| `TELEGRAM_TOKEN`       | Telegram bot token from @BotFather             |
| `DISCORD_TOKEN`        | Discord bot token                              |
| `SLACK_BOT_TOKEN`      | Slack bot token                                |
| `CAPTCHA_API_KEY`      | 2Captcha API key for solving CAPTCHAs          |
| `ORCBOT_DATA_DIR`      | Override data directory (default: `~/.orcbot`) |
| `ORCBOT_CONFIG_PATH`   | Override config file path                      |

<Note>
  Environment variables only override config values if the config file doesn't already define them. Config files take precedence.
</Note>

## Hot-Reload Configuration

OrcBot automatically watches the configuration file for changes and reloads settings without restarting.

### How It Works

```typescript theme={null}
// ConfigManager watches the file and emits events
fs.watch(this.configPath, (eventType) => {
  if (eventType === 'change') {
    const oldConfig = { ...this.config };
    this.config = this.loadConfig(customPath, true);
    eventBus.emit('config:changed', { oldConfig, newConfig: this.config });
  }
});
```

### Live Update Example

<Steps>
  <Step title="Edit Config">
    Open `~/.orcbot/orcbot.config.yaml` in your editor
  </Step>

  <Step title="Change Settings">
    ```yaml theme={null}
    modelName: gpt-4o  # Change from gpt-4o-mini to gpt-4o
    autonomyInterval: 600000  # Change interval to 10 minutes
    ```
  </Step>

  <Step title="Save File">
    Save the file. OrcBot will log:

    ```
    ConfigManager: Config file changed on disk, reloading...
    ConfigManager: Config reloaded and config:changed event emitted
    ```
  </Step>

  <Step title="Changes Applied">
    New settings take effect immediately for the next action
  </Step>
</Steps>

<Warning>
  Hot-reload does not restart channel connections (Telegram, Discord, WhatsApp). To apply channel token changes, restart OrcBot.
</Warning>

## Agent-Driven Config Management

OrcBot v2.0+ includes intelligent configuration where the agent can optimize settings based on task requirements.

### Policy-Based Security

Config keys are classified into three policy levels:

<Tabs>
  <Tab title="SAFE">
    The agent can modify these autonomously without approval:

    * `modelName` - Switch between models
    * `memoryContextLimit` - Adjust context window
    * `maxStepsPerAction` - Increase/decrease step budget
    * `maxMessagesPerAction` - Control response verbosity
    * `reasoningExposeChecklist` - Show/hide planning steps
  </Tab>

  <Tab title="APPROVAL">
    The agent can request changes, but requires human approval:

    * API keys (`openaiApiKey`, `googleApiKey`, etc.)
    * `llmProvider` - Switch LLM provider
    * `autonomyEnabled` - Enable/disable autonomy
    * `autonomyInterval` - Change heartbeat frequency
  </Tab>

  <Tab title="LOCKED">
    The agent cannot modify these:

    * `safeMode` - Prevents command execution
    * `sudoMode` - Elevated permissions
    * `adminUsers` - Admin access control
    * `pluginAllowList` / `pluginDenyList` - Plugin security
  </Tab>
</Tabs>

### Autonomous Optimization

The agent intelligently adjusts configuration when:

* Code tasks need more capable models → auto-switch to GPT-4
* Complex tasks require more memory context → increase `memoryContextLimit`
* Multi-step workflows need higher step budgets → increase `maxStepsPerAction`
* LLM provider is unavailable → auto-fallback to alternatives

### Using manage\_config Skill

```javascript theme={null}
// Agent autonomously optimizes for code tasks
manage_config({
  action: "set",
  key: "modelName",
  value: "gpt-4o",
  reason: "Code refactoring task benefits from GPT-4's superior reasoning"
})

// Agent requests approval for sensitive changes
manage_config({
  action: "set",
  key: "openaiApiKey",
  value: "sk-new-key",
  reason: "API key rotation for security"
})

// View pending approvals
manage_config({ action: "pending" })

// Approve a requested change
manage_config({ action: "approve", key: "openaiApiKey" })
```

## Server Mode Defaults

When `serverMode: true` is set, OrcBot applies conservative defaults optimized for headless deployments:

```yaml theme={null}
serverMode: true

# Automatically applies:
actionQueueCompletedTTL: 7200000  # 2 hours
actionQueueFailedTTL: 43200000    # 12 hours
vectorMemoryMaxEntries: 1500
processedMessagesCacheSize: 300
memoryConsolidationThreshold: 20
journalContextLimit: 800
learningContextLimit: 800
skipSimulationForSimpleTasks: true
compactSkillsPrompt: true
```

## Configuration Syncing

OrcBot automatically syncs config changes across multiple config file locations while protecting secrets:

```typescript theme={null}
private syncConfigAcrossPaths() {
  const targets = [globalPath, homePath, localPath]
    .filter(p => p !== this.configPath);

  const protectedKeys = [
    'telegramToken', 'discordToken', 'openaiApiKey',
    'googleApiKey', 'smtpPassword', 'imapPassword'
  ];

  // Merge current config with existing values
  const merged = { ...this.config };
  for (const key of protectedKeys) {
    if (!merged[key] && targetConfig[key]) {
      merged[key] = targetConfig[key];  // Preserve existing secrets
    }
  }

  fs.writeFileSync(target, yaml.stringify(merged));
}
```

<Warning>
  Config syncing is disabled for worker processes to prevent corruption. Worker configs are isolated to their instance directories.
</Warning>

## Advanced Settings

### Task Complexity Classifier

```yaml theme={null}
# Dynamic step budgets based on LLM-classified complexity
skipSimulationForSimpleTasks: true  # Skip planning for trivial tasks

# Complexity-based budgets:
# - trivial: 5 steps, 1 message
# - simple: 10 steps, 2 messages
# - standard: 20 steps, 5 messages
# - complex: 35 steps, 8 messages
```

### Skill Routing Rules

Configure intent-based skill selection:

```yaml theme={null}
skillRoutingRules:
  - intent: "search"
    preferSkills:
      - web_search
      - browser_navigate
  - intent: "code"
    preferSkills:
      - run_command
      - execute_typescript
  - intent: "communication"
    preferSkills:
      - send_message
      - telegram_send_buttons
```

### Autonomy Channel Policy

Control where the agent can send proactive updates:

```yaml theme={null}
autonomyAllowedChannels:
  - telegram  # Agent can message Telegram proactively
  - discord   # Agent can message Discord proactively
  # WhatsApp omitted - agent won't send unprompted messages there
```

<Note>
  **Direct Responses:** Always allowed on any channel where the user messages the bot

  **Proactive Updates:** Only allowed on channels listed in `autonomyAllowedChannels`

  **Default:** Empty `[]` means silent in background
</Note>

### Memory & Consolidation

```yaml theme={null}
# Memory consolidation thresholds
memoryConsolidationThreshold: 25  # Trigger at 25 short memories
memoryConsolidationBatch: 20      # Consolidate 20 at a time
memoryFlushSoftThreshold: 22      # Soft limit before flushing
memoryFlushCooldownMinutes: 30    # Wait 30min between flushes

# Vector memory
vectorMemoryMaxEntries: 2000      # Max semantic search entries
vectorMemoryEnabled: true

# Context limits
memoryContextLimit: 15            # Recent step memories
threadContextRecentN: 8           # Recent thread messages
threadContextRelevantN: 6         # Relevant thread messages
memoryExtendedContextLimit: 1200  # Extended context chars
```

## Platform-Specific Paths

OrcBot automatically normalizes file paths for cross-platform compatibility:

```typescript theme={null}
private normalizePlatformPaths(config: AgentConfig): AgentConfig {
  // On Windows, POSIX paths from CI/Linux are remapped
  if (process.platform === 'win32') {
    const remapIfCiOrPosix = (value: string): string => {
      // /home/runner/.orcbot/memory.json → C:\Users\You\.orcbot\memory.json
      const idx = normalized.indexOf('/.orcbot/');
      if (idx >= 0) {
        const suffix = normalized.slice(idx + '/.orcbot/'.length);
        return path.join(this.dataHome, ...suffix.split('/'));
      }
      return value;
    };
  }
}
```

## Accessing Config in Code

### From Agent Instance

```typescript theme={null}
// Get single value
const modelName = this.agent.config.get('modelName');
const apiKey = this.agent.config.get('openaiApiKey');

// Set value (triggers hot-reload)
this.agent.config.set('modelName', 'gpt-4o');

// Get all config
const allConfig = this.agent.config.getAll();

// Get data directory
const dataHome = this.agent.config.getDataHome();
```

### Listen for Config Changes

```typescript theme={null}
import { eventBus } from './core/EventBus';

eventBus.on('config:changed', ({ oldConfig, newConfig }) => {
  if (oldConfig.modelName !== newConfig.modelName) {
    logger.info(`Model changed: ${oldConfig.modelName} → ${newConfig.modelName}`);
  }
});
```

## Troubleshooting

### Config Not Loading

```bash theme={null}
# Check which config file is being used
node dist/cli/index.js run
# Look for: "ConfigManager: Config path set to ..."

# Verify config syntax
npx js-yaml ~/.orcbot/orcbot.config.yaml
```

### Environment Variables Not Working

<Warning>
  Environment variables are **fallback only**. If the config file already defines a value, the env var is ignored.

  To force env var usage, remove the key from your config file.
</Warning>

### Hot-Reload Not Working

```bash theme={null}
# Check file watcher is active
# OrcBot logs: "ConfigManager: Config file changed on disk, reloading..."

# If not working:
# 1. Check file permissions (must be readable)
# 2. Some editors use atomic writes that break watchers
# 3. Restart OrcBot to re-establish watch
```

### Worker Corruption Repair

If you see paths like `orchestrator/instances/agent-xxx` in your config:

```bash theme={null}
# OrcBot auto-repairs on next load:
ConfigManager: Repairing worker-corrupted path for memoryPath: ...
ConfigManager: Worker-corruption repair complete. Saving corrected config.
```

This happens automatically. No action needed.
