# TypeDialog AI & AG Integration

TypeDialog provides two AI-powered tools for Provisioning: **typedialog-ai** (configuration assistant) and **typedialog-ag** (agent automation).

## TypeDialog Components

### typedialog-ai v0.1.0

**AI Assistant** - HTTP server backend for intelligent form suggestions and infrastructure recommendations.

**Purpose**: Enhance interactive forms with AI-powered suggestions and natural language parsing.

**Architecture**:

```text
TypeDialog Form
    ↓
typedialog-ai HTTP Server
    ↓
SurrealDB Backend
    ↓
LLM Provider (OpenAI, Anthropic, etc.)
    ↓
Suggestions → Deployed Config
```

**Key Features**:

- **Form Intelligence**: Context-aware field suggestions
- **Database Recommendations**: Suggest database type/configuration based on workload
- **Network Optimization**: Generate optimal network topology
- **Security Policies**: AI-generated Cedar policies
- **Cost Estimation**: Predict infrastructure costs

**Installation**:

```bash
# Via provisioning script
provisioning install ai-tools

# Manual installation
wget  [https://github.com/typedialog/typedialog-ai/releases/download/v0.1.0/typedialog-ai-<os>-<arch>](https://github.com/typedialog/typedialog-ai/releases/download/v0.1.0/typedialog-ai-<os>-<arch>)
chmod +x typedialog-ai
mv typedialog-ai ~/.local/bin/
```

**Usage**:

```bash
# Start AI server
typedialog ai serve --db-path ~/.typedialog/ai.db --port 9000

# Test connection
curl  [http://localhost:9000/health](http://localhost:9000/health)

# Get suggestion for database
curl -X POST  [http://localhost:9000/suggest/database](http://localhost:9000/suggest/database) \
  -H "Content-Type: application/json" \
  -d '{"workload": "transactional", "size": "1TB", "replicas": 3}'

# Response:
# {"suggestion": "PostgreSQL 15 with pgvector", "confidence": 0.92}
```

**Configuration**:

```yaml
# ~/.typedialog/ai-config.yaml
typedialog-ai:
  port: 9000
  db_path: ~/.typedialog/ai.db
  loglevel: info

  llm:
    provider: openai              # or: anthropic, local
    model: gpt-4
    api_key: ${OPENAI_API_KEY}
    temperature: 0.7

  features:
    form_suggestions: true
    database_recommendations: true
    network_optimization: true
    security_policy_generation: true
    cost_estimation: true

  cache:
    enabled: true
    ttl: 3600
```

**Database Schema**:

```sql
-- SurrealDB schema for AI suggestions
DEFINE TABLE ai_suggestions SCHEMAFULL
DEFINE FIELD timestamp ON ai_suggestions TYPE datetime DEFAULT now();
DEFINE FIELD context ON ai_suggestions TYPE object;
DEFINE FIELD suggestion ON ai_suggestions TYPE string;
DEFINE FIELD confidence ON ai_suggestions TYPE float;
DEFINE FIELD accepted ON ai_suggestions TYPE bool;

DEFINE TABLE ai_models SCHEMAFULL
DEFINE FIELD name ON ai_models TYPE string;
DEFINE FIELD version ON ai_models TYPE string;
DEFINE FIELD provider ON ai_models TYPE string;
```

**Endpoints**:

| Endpoint | Method | Purpose |
| --- | --- | --- |
| `/health` | GET | Health check |
| `/suggest/database` | POST | Database recommendations |
| `/suggest/network` | POST | Network topology |
| `/suggest/security` | POST | Security policies |
| `/estimate/cost` | POST | Cost estimation |
| `/parse/natural-language` | POST | Parse natural language |
| `/feedback` | POST | Store suggestion feedback |

### typedialog-ag v0.1.0

**AI Agents** - Type-safe agents for automation workflows and Nickel transpilation.

**Purpose**: Define complex automation workflows using type-safe agent descriptions, then transpile to executable Nickel.

**Architecture**:

```text
Agent Definition (.agent.yaml)
    ↓
typedialog-ag Type Checker
    ↓
Agent Execution Plan
    ↓
Nickel Transpilation
    ↓
Provisioning Execution
```

**Key Features**:

- **Type-Safe Agents**: Strongly-typed agent definitions
- **Workflow Automation**: Chain multiple infrastructure tasks
- **Nickel Transpilation**: Generate Nickel IaC automatically
- **Agent Orchestration**: Parallel and sequential execution
- **Rollback Support**: Automatic rollback on failure

**Installation**:

```bash
# Via provisioning script
provisioning install ai-tools

# Manual installation
wget  [https://github.com/typedialog/typedialog-ag/releases/download/v0.1.0/typedialog-ag-<os>-<arch>](https://github.com/typedialog/typedialog-ag/releases/download/v0.1.0/typedialog-ag-<os>-<arch>)
chmod +x typedialog-ag
mv typedialog-ag ~/.local/bin/
```

**Agent Definition Syntax**:

```yaml
# provisioning/workflows/deploy-k8s.agent.yaml
version: "1.0"
agent: deploy-k8s
description: "Deploy HA Kubernetes cluster with observability stack"

types:
  CloudProvider:
    enum: ["aws", "upcloud", "hetzner"]
  NodeConfig:
    cpu: int           # 2..64
    memory: int        # 4..256 (GB)
    disk: int          # 10..1000 (GB)

input:
  provider: CloudProvider
  name: string         # cluster name
  nodes: int           # 3..100
  node_config: NodeConfig
  enable_monitoring: bool = true
  enable_backup: bool = true

workflow:
  - name: validate
    task: validate_cluster_config
    args:
      provider: $input.provider
      nodes: $input.nodes
      node_config: $input.node_config

  - name: create_network
    task: create_vpc
    depends_on: [validate]
    args:
      provider: $input.provider
      cidr: "10.0.0.0/16"

  - name: create_nodes
    task: create_nodes
    depends_on: [create_network]
    parallel: true
    args:
      provider: $input.provider
      count: $input.nodes
      config: $input.node_config

  - name: install_kubernetes
    task: install_kubernetes
    depends_on: [create_nodes]
    args:
      nodes: $create_nodes.output.node_ids
      version: "1.28.0"

  - name: add_monitoring
    task: deploy_observability_stack
    depends_on: [install_kubernetes]
    when: $input.enable_monitoring
    args:
      cluster_name: $input.name
      storage_class: "ebs"

  - name: setup_backup
    task: configure_backup
    depends_on: [install_kubernetes]
    when: $input.enable_backup
    args:
      cluster_name: $input.name
      backup_interval: "daily"

output:
  cluster_name: string
  cluster_id: string
  kubeconfig_path: string
  monitoring_url: string
```

**Usage**:

```bash
# Type-check agent
typedialog ag check deploy-k8s.agent.yaml

# Run agent interactively
typedialog ag run deploy-k8s.agent.yaml \
  --provider upcloud \
  --name production-k8s \
  --nodes 5 \
  --node-config '{"cpu": 8, "memory": 32, "disk": 100}'

# Transpile to Nickel
typedialog ag transpile deploy-k8s.agent.yaml > deploy-k8s.ncl

# Execute generated Nickel
provisioning apply deploy-k8s.ncl
```

**Generated Nickel Output** (example):

```nickel
{
  metadata = {
    agent = "deploy-k8s"
    version = "1.0"
    generated_at = "2026-01-16T01:47:00Z"
  }

  resources = {
    network = {
      provider = "upcloud"
      vpc = { cidr = "10.0.0.0/16" }
    }

    compute = {
      provider = "upcloud"
      nodes = [
        { count = 5, cpu = 8, memory = 32, disk = 100 }
      ]
    }

    kubernetes = {
      version = "1.28.0"
      high_availability = true
      monitoring = {
        enabled = true
        stack = "prometheus-grafana"
      }
      backup = {
        enabled = true
        interval = "daily"
      }
    }
  }
}
```

**Agent Features**:

| Feature | Purpose |
| --- | --- |
| **Dependencies** | Declare task ordering (depends_on) |
| **Parallelism** | Run independent tasks in parallel |
| **Conditionals** | Execute tasks based on input conditions |
| **Type Safety** | Strong typing on inputs and outputs |
| **Rollback** | Automatic rollback on failure |
| **Logging** | Full execution trace for debugging |

## Integration with Provisioning

### Using typedialog-ai in Forms

```toml
# .typedialog/provisioning/form.toml
[[elements]]
name = "database_type"
prompt = "form-database_type-prompt"
type = "select"
options = ["postgres", "mysql", "mongodb"]

# Enable AI suggestions
[elements.ai_suggestions]
enabled = true
context = "workload"
provider = "typedialog-ai"
endpoint = " [http://localhost:9000/suggest/database"](http://localhost:9000/suggest/database")
```

### Using typedialog-ag in Workflows

```bash
# Define agent-based workflow
provisioning workflow define \
  --agent deploy-k8s.agent.yaml \
  --name k8s-deployment \
  --auto-execute

# Run workflow
provisioning workflow run k8s-deployment \
  --provider upcloud \
  --nodes 5
```

## Performance

### typedialog-ai

- **Suggestion latency**: 500ms-2s per suggestion
- **Database queries**: <100ms (cached)
- **Concurrent users**: 50+
- **SurrealDB storage**: <1GB for 10K suggestions

### typedialog-ag

- **Type checking**: <100ms per agent
- **Transpilation**: <500ms to Nickel
- **Parallel task execution**: O(1) overhead
- **Agent memory**: <50MB per agent

## Configuration

### Enable AI in Provisioning

```yaml
# provisioning/config/config.defaults.toml
[ai]
enabled = true
typedialog_ai = true
typedialog_ag = true

[ai.typedialog]
ai_server_url = " [http://localhost:9000"](http://localhost:9000")
ag_executable = "typedialog-ag"

[ai.form_suggestions]
enabled = true
providers = ["database", "network", "security"]
confidence_threshold = 0.75
```

## Related Documentation

- [AI Architecture](./ai-architecture.md) - System design
- [Natural Language Infrastructure](./natural-language-infrastructure.md) - LLM usage
- [AI Service Crate](./ai-service-crate.md) - Core microservice
