# OpenCode-Compatible Server

This module implements an OpenCode-compatible API server, allowing OpenCode SDK clients
to interact with AgentPool agents.

## Reference Documentation

- **Python SDK**: https://github.com/sst/opencode-sdk-python
- **Server Docs**: https://raw.githubusercontent.com/sst/opencode/refs/heads/dev/packages/web/src/content/docs/server.mdx
- **OpenCode Main Repo**: https://github.com/sst/opencode

## SDK Clone (for reference during development)

To get the SDK locally for reference:
```bash
git clone --depth 1 https://github.com/sst/opencode-sdk-python.git /tmp/opencode-sdk-python
```

Key SDK paths:
- Types: `src/opencode_ai/types/` - All Pydantic models
- Resources: `src/opencode_ai/resources/` - API client methods (shows endpoint signatures)

## Architecture

```
opencode_server/
├── __init__.py
├── server.py           # FastAPI app factory and main server class
├── models/             # Pydantic models matching OpenCode API types
│   ├── __init__.py
│   ├── base.py         # Shared base model with camelCase alias config
│   ├── session.py      # Session, SessionStatus, etc.
│   ├── message.py      # Message, Parts, etc.
│   ├── provider.py     # Provider, Model, Config
│   ├── file.py         # File operations models
│   └── events.py       # SSE event models
├── routes/             # Route handlers grouped by domain
│   ├── __init__.py
│   ├── global_routes.py
│   ├── session_routes.py
│   ├── message_routes.py
│   ├── file_routes.py
│   ├── config_routes.py
│   └── agent_routes.py
├── state.py            # Server state management
└── ENDPOINTS.md        # Implementation status checklist
```

## Key Conventions

### Models
- All models inherit from `OpenCodeBaseModel` which sets `populate_by_name=True`
- Use `Field(alias="camelCase")` for fields that differ from snake_case
- OpenCode uses camelCase in JSON (e.g., `sessionID`, `messageID`, `providerID`)

### Routes
- Each route file defines a router with appropriate prefix/tags
- Routes are registered in `server.py`
- Use dependency injection for server state access

### Field Naming Examples
```python
session_id: str = Field(alias="sessionID")
message_id: str = Field(alias="messageID")
provider_id: str = Field(alias="providerID")
model_id: str = Field(alias="modelID")
parent_id: str | None = Field(default=None, alias="parentID")
```

## Implementation Status

See `ENDPOINTS.md` for the full checklist of endpoints and their implementation status.

## Logging

Log file location: `~/.local/state/agentpool/log/opencode.log`

To tail the logs:
```bash
tail -f ~/.local/state/agentpool/log/opencode.log
```

To filter for SSE events:
```bash
tail -f ~/.local/state/agentpool/log/opencode.log | grep -i sse
```

## Testing with the SDK

```python
from opencode_ai import Opencode

client = Opencode(base_url="http://localhost:4096")
sessions = client.session.list()
```
