# Mithril Design Document

## Executive Summary

Mithril provides command-line access to FCP spot instances with minimal abstraction. It targets developers who need direct compute access without workflow orchestration or platform abstractions.

## Problem Statement

Current FCP access methods either:
- Require complex SDK integration (Flow SDK)
- Provide web interfaces unsuitable for automation
- Abstract away too much control

Mithril fills the gap for users who want:
- Direct API access via CLI
- Standard Unix tool compatibility  
- Transparent pricing and availability
- No hidden automation

## Design Goals

### Primary Goals
1. **Simplicity**: Learn in 5 minutes, master in 10
2. **Transparency**: What you type is what happens
3. **Reliability**: Predictable behavior, clear errors
4. **Compatibility**: Works with existing tools

### Non-Goals
1. Workflow orchestration (use Flow SDK)
2. Cost optimization automation
3. Multi-cloud abstraction
4. GUI or web interface

## User Interface

### Command Structure
```
mithril <verb> <resource> [options]
```

### Core Commands
- `list` - Show available instance types or active instances
- `create` - Submit spot bid for instance
- `status` - Check instance provisioning status
- `ssh` - Connect to running instance
- `delete` - Terminate instance and cancel bid

### Design Decisions

#### Why Spot-Only?
- Represents 95% of FCP usage
- Simplifies pricing model
- Reduces API surface area
- On-demand can be added later

#### Why No Configuration File?
- Environment variables are standard
- Reduces complexity
- Easier containerization
- No state to manage

## Technical Architecture

### Language Choice: Python
- Ubiquitous availability
- Excellent HTTP libraries
- Clean subprocess handling
- No compilation required

### Dependency Management
```
Required:
- Python 3.8+ (standard library)
- requests (HTTP client)

Optional:
- flow-sdk (catalog resolution only)
```

### API Client Design

#### Connection Management
- Persistent sessions for connection reuse
- Exponential backoff with jitter
- Timeout handling for long requests

#### Error Handling
- Preserve API error structure
- Add context without wrapping
- Use standard exit codes

### Instance Type Resolution

#### Challenge
FCP uses opaque IDs like `it_XqgKWbhZ5gznAYsG` internally but users expect names like `gpu.a100.1x`.

#### Solution
1. Try Flow SDK catalog (if available)
2. Cache successful resolutions
3. Fall back to raw IDs
4. Allow both formats as input

## Implementation Details

### SSH Key Management

#### Problem
FCP requires SSH keys to be pre-registered but users expect seamless access.

#### Solution
- Check if key exists on first use
- Upload automatically if missing
- Use fingerprint for deduplication
- Support multiple keys per project

### Price Display

#### Challenge  
Spot prices fluctuate and may be unavailable.

#### Design
- Show last known price when available
- Display "--" when unknown
- Never show $0.00 (dangerous)
- Include currency symbol

### Progress Indication

#### Provisioning Feedback
- Show elapsed time
- Estimate remaining time
- Avoid false precision
- Clear status messages

## Security Model

### Authentication
- API key via environment only
- No embedded credentials
- Project isolation enforced

### SSH Security
- Disable host key checking (ephemeral hosts)
- Private key never transmitted
- Standard OpenSSH client

### Audit Trail
- All actions traceable via API
- No local operation logs
- Rely on FCP audit logs

## Performance Targets

### Latency Goals
- List operations: <500ms
- Create operations: <1s
- Status checks: <300ms

### Optimization Techniques
- Connection pooling
- Parallel availability checks
- Response caching (runtime only)

## Error Scenarios

### Network Failures
- Retry with backoff
- Preserve error details
- Clear timeout messages

### API Errors
- 400: Invalid parameters - show what's wrong
- 401: Authentication - check API key
- 404: Resource not found - helpful message
- 429: Rate limited - automatic retry
- 500: Server error - suggest retry

### Configuration Errors
- Missing API key: Setup instructions
- Invalid project: List valid projects
- SSH key not found: Check path

## Testing Approach

### Unit Testing
- Mock all external calls
- Test error conditions
- Verify output formatting

### Integration Testing  
- Test account with quotas
- Real API interactions
- SSH connectivity tests

### User Acceptance
- Time to first instance
- Error message clarity
- Command memorability

## Migration Path

### From Existing Tools
- Compatible environment variables
- Similar command structure
- Gradual adoption possible

### Version Compatibility
- Support FCP API v2
- Graceful degradation
- Version negotiation

## Success Metrics

### Adoption
- Time to first successful instance
- Daily active users
- Command success rate

### Quality
- API error rate <1%
- User error rate <5%  
- Support ticket volume

### Performance
- 95th percentile latency
- Retry rate
- Timeout frequency

## Future Evolution

### Possible Extensions
1. Instance templates
2. Spot price history
3. Multiple instance operations
4. Cost tracking integration

### Compatibility Promises
1. Environment variables remain stable
2. Command structure unchanged
3. Output format versioning
4. Deprecation warnings

## Alternatives Considered

### Full Flow SDK Wrapper
- Pros: Feature complete
- Cons: Large dependency
- Decision: Too heavy for simple use cases

### Direct curl Scripts  
- Pros: No dependencies
- Cons: Poor error handling
- Decision: Too primitive

### Go Implementation
- Pros: Single binary
- Cons: Requires compilation  
- Decision: Python is more accessible

## Conclusion

Mithril occupies a specific niche: developers who need direct compute access without complexity. By maintaining focus on this use case and resisting feature creep, it provides maximum value with minimal complexity.