---
name: coding-agent
description: Add provider abstraction layer for AI providers (Claude, OpenAI, Gemini) and TUI integration via coding-agent. Enables provider-agnostic AI execution. Triggers on "coding agent", "tui setup", "provider setup", "multi-provider".
---

# Coding Agent Provider Integration

This skill adds a provider abstraction layer to Clawdie, enabling support for multiple AI providers (Claude via Anthropic API or subscription, OpenAI, Gemini) and TUI interfaces like coding-agent from the pi-mono project.

## Overview

The provider system allows Clawdie to:

1. **Support multiple AI backends** - Switch between Claude, OpenAI, Gemini without code changes
2. **Use TUI interfaces** - coding-agent provides a terminal UI similar to Claude Code
3. **Container-based execution** - Keep existing Docker/jail isolation for production
4. **Direct API access** - For development and testing without containers

## Phase 1: Pre-flight

### Check current configuration

Read `src/config.ts` and `.env` to understand current setup:

```bash
grep -E "ANTHROPIC|OPENAI|GEMINI|AGENT_CODE" .env || echo "No provider config found"
```

### Ask configuration questions

Use `AskUserQuestion` to determine setup:

1. **Primary provider**: Claude (Anthropic), OpenAI, or Gemini?
2. **Execution mode**: Container-based (current), TUI (coding-agent), or direct API?
3. **Fallback provider**: Optional secondary provider for redundancy

## Phase 2: Apply Code Changes

### Initialize skills system (if needed)

```bash
npx tsx scripts/apply-skill.ts --init
```

### Apply the skill

```bash
npx tsx scripts/apply-skill.ts .agent/skills/coding-agent
```

This deterministically:

- Adds `src/providers/provider.ts` (Provider interface)
- Adds `src/providers/anthropic.ts` (Claude/Anthropic provider)
- Adds `src/providers/openai.ts` (OpenAI provider)
- Adds `src/providers/gemini.ts` (Gemini provider - stub)
- Adds `src/providers/coding-agent.ts` (TUI wrapper)
- Adds `src/providers/index.ts` (Provider factory)
- Modifies `src/config.ts` to add provider configuration
- Modifies `src/container-runner.ts` to use provider abstraction
- Installs npm dependencies if needed
- Updates `.env.example` with provider config options
- Records the application in `.nanoclaw/state.yaml`

### Validate code changes

```bash
npm test
npm run build
```

All tests must pass and build must be clean.

## Phase 3: Provider Configuration

### Claude/Anthropic Setup

#### Option A: Claude Subscription (OAuth)

Run Claude Code setup:

```bash
claude setup-token
```

Copy the token and add to `.env`:

```bash
AGENT_CODE_OAUTH_TOKEN=<your-token>
```

#### Option B: Anthropic API Key

Get API key from https://console.anthropic.com/

Add to `.env`:

```bash
ANTHROPIC_API_KEY=sk-ant-...
```

### OpenAI Setup

Get API key from https://platform.openai.com/api-keys

Add to `.env`:

```bash
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4o  # or gpt-4-turbo, gpt-3.5-turbo
```

### Gemini Setup

Get API key from https://aistudio.google.com/app/apikey

Add to `.env`:

```bash
GOOGLE_API_KEY=...
GEMINI_MODEL=gemini-pro  # or gemini-pro-vision
```

### Provider Selection

Set the active provider in `.env`:

```bash
AI_PROVIDER=claude  # Options: claude, openai, gemini
```

### Execution Mode

Set execution mode in `.env`:

```bash
EXECUTION_MODE=container  # Options: container, tui, direct
```

## Phase 4: Coding-Agent TUI Setup

### Install coding-agent

```bash
# From npm (when published)
npm install -g @pi-ai/coding-agent

# Or build from source
git clone https://github.com/pi-apps-managed/pi-mono.git
cd pi-mono
pnpm install
pnpm build
npm link
```

### Verify installation

```bash
coding-agent --version
```

### Configure coding-agent

Create `~/.config/coding-agent/config.json`:

```json
{
  "provider": "claude",
  "model": "claude-sonnet-4-20250514",
  "apiKey": "${ANTHROPIC_API_KEY}",
  "enableTools": true,
  "enableMcp": true
}
```

### Test TUI mode

```bash
cd /home/clawdie/clawdie-cp
coding-agent
```

## Phase 5: Integration with Clawdie

### Update execution mode

In `src/config.ts`, the provider system will be automatically used based on `EXECUTION_MODE`:

```typescript
export const EXECUTION_MODE = process.env.EXECUTION_MODE || 'container';
export const AI_PROVIDER = process.env.AI_PROVIDER || 'claude';
```

### Container execution (default)

Existing container-based execution continues to work. The provider config is passed to the container via environment.

### TUI execution

When `EXECUTION_MODE=tui`:

1. Clawdie spawns `coding-agent` process
2. Routes messages to coding-agent stdin
3. Reads responses from stdout
4. Maintains session state

### Direct API execution

When `EXECUTION_MODE=direct`:

1. Clawdie calls provider API directly
2. No container or TUI overhead
3. Useful for testing and development

## Phase 6: Verify

### Test provider connection

```bash
npx tsx scripts/test-provider.ts
```

This tests:

- API key validity
- Model availability
- Basic completion

### Test with Telegram

Send a message to your registered Telegram chat and verify response.

### Check logs

```bash
tail -f logs/nanoclaw.log
```

## Provider-Specific Notes

### Claude/Anthropic

- **Models**: claude-sonnet-4-20250514 (default), claude-opus-4-20250514
- **Context window**: 200K tokens
- **Rate limits**: Varies by plan
- **OAuth token**: Expires periodically, refresh with `claude setup-token`

### OpenAI

- **Models**: gpt-4o, gpt-4-turbo, gpt-3.5-turbo
- **Context window**: 128K tokens (gpt-4-turbo)
- **Rate limits**: Based on tier
- **Streaming**: Supported

### Gemini

- **Models**: gemini-pro, gemini-pro-vision
- **Context window**: 32K tokens
- **Free tier**: Available with rate limits
- **Safety filters**: Configurable

## Troubleshooting

### Provider not responding

1. Check API key is set: `echo $ANTHROPIC_API_KEY`
2. Verify key validity: `curl -H "x-api-key: $ANTHROPIC_API_KEY" https://api.anthropic.com/v1/models`
3. Check logs for errors
4. Verify model name is correct

### coding-agent not found

1. Install: `npm install -g @pi-ai/coding-agent`
2. Or build from source (see Phase 4)
3. Check PATH: `which coding-agent`

### TUI mode not working

1. Verify coding-agent installed
2. Check EXECUTION_MODE=tui in `.env`
3. Test manually: `coding-agent` in terminal
4. Check logs for spawn errors

### Container mode fallback

If TUI mode fails, Clawdie will fall back to container execution. Check logs for fallback messages.

## Environment Variables Reference

```bash
# Provider Selection
AI_PROVIDER=claude              # claude | openai | gemini
EXECUTION_MODE=container        # container | tui | direct

# Claude/Anthropic
ANTHROPIC_API_KEY=sk-ant-...    # API key
AGENT_CODE_OAUTH_TOKEN=...      # OAuth token (alternative)
CLAUDE_MODEL=claude-sonnet-4-20250514

# OpenAI
OPENAI_API_KEY=sk-...           # API key
OPENAI_MODEL=gpt-4o             # Model selection
OPENAI_ORG_ID=org-...           # Organization ID (optional)

# Gemini
GOOGLE_API_KEY=...              # API key
GEMINI_MODEL=gemini-pro         # Model selection

# Fallback Provider (optional)
FALLBACK_PROVIDER=openai        # Secondary provider
FALLBACK_MODEL=gpt-4o           # Fallback model
```

## Architecture

```
┌─────────────────────────────────────────────────┐
│                   Clawdie Core                   │
│                                                  │
│  ┌────────────────────────────────────────────┐ │
│  │           Provider Abstraction              │ │
│  │                                             │ │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐ │ │
│  │  │ Anthropic│  │  OpenAI  │  │  Gemini  │ │ │
│  │  │ Provider │  │ Provider │  │ Provider │ │ │
│  │  └──────────┘  └──────────┘  └──────────┘ │ │
│  └────────────────────────────────────────────┘ │
│                                                  │
│  ┌────────────────────────────────────────────┐ │
│  │          Execution Modes                    │ │
│  │                                             │ │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐ │ │
│  │  │Container │  │   TUI    │  │  Direct  │ │ │
│  │  │ (Jail)   │  │(coding-  │  │   API    │ │ │
│  │  │          │  │ agent)   │  │          │ │ │
│  │  └──────────┘  └──────────┘  └──────────┘ │ │
│  └────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────┘
```

## Provider Interface

The `Provider` interface in `src/providers/provider.ts`:

```typescript
export interface ProviderOptions {
  model?: string;
  maxTokens?: number;
  temperature?: number;
  systemPrompt?: string;
  tools?: ToolDefinition[];
}

export interface ProviderResult {
  content: string;
  toolCalls?: ToolCall[];
  usage?: {
    inputTokens: number;
    outputTokens: number;
  };
}

export interface AIProvider {
  readonly name: string;

  execute(prompt: string, options?: ProviderOptions): Promise<ProviderResult>;
  stream(
    prompt: string,
    options?: ProviderOptions,
  ): AsyncIterable<ProviderResult>;
  isAvailable(): boolean;
  getModels(): Promise<string[]>;
}
```

## Extending with New Providers

To add a new provider:

1. Create `src/providers/<provider>.ts`
2. Implement `AIProvider` interface
3. Add to factory in `src/providers/index.ts`
4. Add configuration to `src/config.ts`
5. Update `.env.example`
6. Add tests in `src/providers/<provider>.test.ts`

## Security Notes

- API keys are read from environment, never logged
- OAuth tokens stored securely in `.env`
- Provider credentials not exposed to channels
- Rate limiting per-provider to prevent abuse

## Performance Considerations

- **Container mode**: Highest isolation, moderate overhead
- **TUI mode**: Lower overhead, interactive debugging
- **Direct mode**: Lowest overhead, no isolation

Choose based on your security and performance requirements.
