repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

docs/AI-CRATE-DESIGN.md

Raw

smith-ai Crate Design

Overview

The smith-ai crate handles:

  1. Provider connections — connecting to LLM APIs
  2. Authentication — API keys and OAuth flows
  3. Streaming — streaming responses from providers
  4. Model registry — all available models from bundled JSON

Provider Data (JSON)

Location

Structure

{
  "providers": {
    "anthropic": {
      "id": "anthropic",
      "name": "Anthropic",
      "auth_types": {
        "api_key": {
          "env_var": "ANTHROPIC_API_KEY"
        }
      },
      "oauth": {
        "id": "anthropic",
        "name": "Anthropic",
        "scope": "profile"
      },
      "models": [
        {
          "id": "claude-3-5-sonnet-20241022",
          "name": "Claude 3.5 Sonnet",
          "api": "anthropic-messages",
          "base_url": "https://api.anthropic.com",
          "reasoning": false,
          "input": ["text", "image"],
          "cost": {
            "input": 0.000003,
            "output": 0.000015,
            "cache_read": 0.00000030,
            "cache_write": 0.000012
          },
          "context_window": 200000,
          "max_tokens": 8192
        }
      ]
    },
    "openai": {
      "id": "openai",
      "name": "OpenAI",
      "auth_types": {
        "api_key": {
          "env_var": "OPENAI_API_KEY"
        },
        "organization": {
          "env_var": "OPENAI_ORG"
        }
      },
      "models": [...]
    },
    "google": {
      "id": "google",
      "name": "Google",
      "auth_types": {
        "api_key": {
          "env_var": "GOOGLE_API_KEY"
        }
      },
      "oauth": {
        "id": "google-gemini-cli",
        "name": "Google Gemini CLI"
      },
      "models": [...]
    },
    "github-copilot": {
      "id": "github-copilot",
      "name": "GitHub Copilot",
      "auth_types": {
        "oauth": {
          "id": "github-copilot",
          "name": "GitHub Copilot"
        }
      },
      "models": [...]
    }
  }
}

Generated Fields

Some fields are generated at build time and embedded:

Auth Types

1. API Key

pub struct ApiKeyAuth {
    pub env_var: String,  // e.g., "ANTHROPIC_API_KEY"
}

2. OAuth

pub struct OAuthConfig {
    pub id: String,           // e.g., "github-copilot"
    pub name: String,         // e.g., "GitHub Copilot"
    pub auth_url: String,     // authorization URL
    pub token_url: String,    // token exchange URL
    pub scope: String,        // OAuth scope
    pub client_id: String,    // OAuth client ID
}

pub struct OAuthCredentials {
    pub access_token: String,
    pub refresh_token: String,
    pub expires_at: i64,      // Unix timestamp
}

3. Organization (OpenAI specific)

pub struct OrganizationAuth {
    pub org_id: String,
}

Auth Resolution

pub enum AuthMethod {
    ApiKey(String),           // API key value
    OAuth(OAuthCredentials),   // OAuth tokens
    Organization {
        api_key: String,
        org_id: String,
    },
}

pub trait AuthResolver: Send + Sync {
    fn resolve(&self, provider: &str, auth_type: &str) -> Result<AuthMethod, AuthError>;
}

Provider Trait

pub trait Provider: Send + Sync {
    fn id(&self) -> &str;
    fn name(&self) -> &str;
    fn base_url(&self) -> &str;
    
    fn complete(&self, request: ProviderRequest) -> ProviderStream;
    fn authenticate(&self, auth: &AuthMethod) -> Result<(), AuthError>;
}

Model Resolution

pub struct ModelRegistry {
    providers: HashMap<String, ProviderData>,
}

impl ModelRegistry {
    pub fn load() -> Self;
    pub fn get(&self, provider: &str, model: &str) -> Option<&Model>;
    pub fn list_models(&self, provider: Option<&str>) -> Vec<&Model>;
    pub fn list_providers(&self) -> Vec<&ProviderData>;
}

Streaming

pub struct ProviderStream {
    // async stream of events
}

pub enum ProviderEvent {
    TextDelta { text: String },
    ToolCall { id: String, name: String, arguments: String },
    ThinkingDelta { text: String },
    Done { usage: ProviderUsage, stop_reason: StopReason },
    Error { message: String },
}

OAuth Flow

1. User initiates login

pub struct OAuthCallbacks {
    pub on_auth_url: Box<dyn Fn(String)>,        // Display URL to user
    pub on_code: Box<dyn Fn() -> String>,        // Get code from user (or callback server)
}

2. Login process

pub trait OAuthProvider: Send + Sync {
    fn get_auth_url(&self, state: &str) -> String;
    fn exchange_code(&self, code: &str) -> Result<OAuthCredentials, AuthError>;
    fn refresh(&self, credentials: &OAuthCredentials) -> Result<OAuthCredentials, AuthError>;
}

3. Callback server

xtask: Fetch Providers

// xtask/src/fetch_providers.rs

pub fn fetch_providers() -> Result<()> {
    // 1. Fetch from pi.dev
    let pi_models = fetch_pi_models()?;
    
    // 2. Fetch from catwalk repo
    let catwalk_models = fetch_catwalk_models()?;
    
    // 3. Merge and deduplicate
    let merged = merge_models(pi_models, catwalk_models);
    
    // 4. Generate JSON
    let json = generate_provider_json(merged);
    
    // 5. Write to smith-ai/src/providers.json
    write_providers_json(&json)?;
    
    Ok(())
}

Override Cascade

bundled providers.json
        ↓
plugin overrides (add/modify providers)
        ↓
user config (~/.smith/providers.json)

OAuth Storage

OAuth tokens stored in auth JSON file:

// ~/.smith/auth.json
{
  "anthropic": {
    "access_token": "...",
    "refresh_token": "...",
    "expires_at": 1234567890
  },
  "github-copilot": {...}
}

Plugin Override

Plugins can add or modify providers via SDK:

// In plugin manifest or SDK call
sdk.add_provider("my-provider", ProviderData { ... });
sdk.override_model("anthropic", "claude-3-5-sonnet-20241022", ModelOverrides { ... });

Initial Providers

All providers from pi.dev + catwalk:

TODO

Markdown source
File outline
# smith-ai Crate Design

## Overview

The `smith-ai` crate handles:
1. **Provider connections** — connecting to LLM APIs
2. **Authentication** — API keys and OAuth flows
3. **Streaming** — streaming responses from providers
4. **Model registry** — all available models from bundled JSON

## Provider Data (JSON)

### Location
- Bundled at compile time: `smith-ai/src/providers.json`
- Generated by `xtask fetch-providers` from pi.dev + catwalk

### Structure

```json
{
  "providers": {
    "anthropic": {
      "id": "anthropic",
      "name": "Anthropic",
      "auth_types": {
        "api_key": {
          "env_var": "ANTHROPIC_API_KEY"
        }
      },
      "oauth": {
        "id": "anthropic",
        "name": "Anthropic",
        "scope": "profile"
      },
      "models": [
        {
          "id": "claude-3-5-sonnet-20241022",
          "name": "Claude 3.5 Sonnet",
          "api": "anthropic-messages",
          "base_url": "https://api.anthropic.com",
          "reasoning": false,
          "input": ["text", "image"],
          "cost": {
            "input": 0.000003,
            "output": 0.000015,
            "cache_read": 0.00000030,
            "cache_write": 0.000012
          },
          "context_window": 200000,
          "max_tokens": 8192
        }
      ]
    },
    "openai": {
      "id": "openai",
      "name": "OpenAI",
      "auth_types": {
        "api_key": {
          "env_var": "OPENAI_API_KEY"
        },
        "organization": {
          "env_var": "OPENAI_ORG"
        }
      },
      "models": [...]
    },
    "google": {
      "id": "google",
      "name": "Google",
      "auth_types": {
        "api_key": {
          "env_var": "GOOGLE_API_KEY"
        }
      },
      "oauth": {
        "id": "google-gemini-cli",
        "name": "Google Gemini CLI"
      },
      "models": [...]
    },
    "github-copilot": {
      "id": "github-copilot",
      "name": "GitHub Copilot",
      "auth_types": {
        "oauth": {
          "id": "github-copilot",
          "name": "GitHub Copilot"
        }
      },
      "models": [...]
    }
  }
}
```

### Generated Fields

Some fields are generated at build time and embedded:
- `base_url` — from provider API docs
- `cost` — current pricing
- `context_window`, `max_tokens` — from model specs

## Auth Types

### 1. API Key
```rust
pub struct ApiKeyAuth {
    pub env_var: String,  // e.g., "ANTHROPIC_API_KEY"
}
```
- Read from environment variable
- Simple, stateless

### 2. OAuth
```rust
pub struct OAuthConfig {
    pub id: String,           // e.g., "github-copilot"
    pub name: String,         // e.g., "GitHub Copilot"
    pub auth_url: String,     // authorization URL
    pub token_url: String,    // token exchange URL
    pub scope: String,        // OAuth scope
    pub client_id: String,    // OAuth client ID
}

pub struct OAuthCredentials {
    pub access_token: String,
    pub refresh_token: String,
    pub expires_at: i64,      // Unix timestamp
}
```
- Requires callback server for user authorization
- Tokens stored securely (where? config file? OS keyring?)
- Auto-refresh when expired

### 3. Organization (OpenAI specific)
```rust
pub struct OrganizationAuth {
    pub org_id: String,
}
```

## Auth Resolution

```rust
pub enum AuthMethod {
    ApiKey(String),           // API key value
    OAuth(OAuthCredentials),   // OAuth tokens
    Organization {
        api_key: String,
        org_id: String,
    },
}

pub trait AuthResolver: Send + Sync {
    fn resolve(&self, provider: &str, auth_type: &str) -> Result<AuthMethod, AuthError>;
}
```

## Provider Trait

```rust
pub trait Provider: Send + Sync {
    fn id(&self) -> &str;
    fn name(&self) -> &str;
    fn base_url(&self) -> &str;
    
    fn complete(&self, request: ProviderRequest) -> ProviderStream;
    fn authenticate(&self, auth: &AuthMethod) -> Result<(), AuthError>;
}
```

## Model Resolution

```rust
pub struct ModelRegistry {
    providers: HashMap<String, ProviderData>,
}

impl ModelRegistry {
    pub fn load() -> Self;
    pub fn get(&self, provider: &str, model: &str) -> Option<&Model>;
    pub fn list_models(&self, provider: Option<&str>) -> Vec<&Model>;
    pub fn list_providers(&self) -> Vec<&ProviderData>;
}
```

## Streaming

```rust
pub struct ProviderStream {
    // async stream of events
}

pub enum ProviderEvent {
    TextDelta { text: String },
    ToolCall { id: String, name: String, arguments: String },
    ThinkingDelta { text: String },
    Done { usage: ProviderUsage, stop_reason: StopReason },
    Error { message: String },
}
```

## OAuth Flow

### 1. User initiates login
```rust
pub struct OAuthCallbacks {
    pub on_auth_url: Box<dyn Fn(String)>,        // Display URL to user
    pub on_code: Box<dyn Fn() -> String>,        // Get code from user (or callback server)
}
```

### 2. Login process
```rust
pub trait OAuthProvider: Send + Sync {
    fn get_auth_url(&self, state: &str) -> String;
    fn exchange_code(&self, code: &str) -> Result<OAuthCredentials, AuthError>;
    fn refresh(&self, credentials: &OAuthCredentials) -> Result<OAuthCredentials, AuthError>;
}
```

### 3. Callback server
- Starts local HTTP server on random port
- Receives OAuth callback
- Extracts code from URL parameters
- Returns code to smith

## xtask: Fetch Providers

```rust
// xtask/src/fetch_providers.rs

pub fn fetch_providers() -> Result<()> {
    // 1. Fetch from pi.dev
    let pi_models = fetch_pi_models()?;
    
    // 2. Fetch from catwalk repo
    let catwalk_models = fetch_catwalk_models()?;
    
    // 3. Merge and deduplicate
    let merged = merge_models(pi_models, catwalk_models);
    
    // 4. Generate JSON
    let json = generate_provider_json(merged);
    
    // 5. Write to smith-ai/src/providers.json
    write_providers_json(&json)?;
    
    Ok(())
}
```

## Override Cascade

```
bundled providers.json
        ↓
plugin overrides (add/modify providers)
        ↓
user config (~/.smith/providers.json)
```

### OAuth Storage

OAuth tokens stored in auth JSON file:
```json
// ~/.smith/auth.json
{
  "anthropic": {
    "access_token": "...",
    "refresh_token": "...",
    "expires_at": 1234567890
  },
  "github-copilot": {...}
}
```

### Plugin Override

Plugins can add or modify providers via SDK:
```rust
// In plugin manifest or SDK call
sdk.add_provider("my-provider", ProviderData { ... });
sdk.override_model("anthropic", "claude-3-5-sonnet-20241022", ModelOverrides { ... });
```

### Initial Providers

All providers from pi.dev + catwalk:
- **pi.dev providers**: anthropic, openai, google, mistral, amazon-bedrock, google-vertex, google-gemini-cli, azure-openai, openai-codex, github-copilot, xai, groq, cerebras, openrouter, vercel-ai-gateway, zai, minimax, huggingface, opencode, kimi-coding
- **catwalk providers**: openrouter, huggingface, and OpenAI-compatible APIs

## TODO

- [x] Define exact JSON schema
- [x] Design OAuth storage (auth JSON file)
- [x] Design OAuth callback server integration
- [x] Design plugin override mechanism
- [ ] ~~Implement xtask fetch command~~ — tracked in SM-007 Steps
- [ ] ~~Implement model registry~~ — tracked in SM-007 Steps
- [ ] ~~Implement auth resolvers~~ — tracked in SM-007 Steps
- [ ] ~~Implement all providers from pi.dev + catwalk~~ — tracked in SM-007 Steps