# 🏋️ Doit — Telegram-Controlled Local Automation Engine

**Doit** is a production-grade open-source automation agent that runs silently on your laptop and executes real OS-level tasks — controlled entirely through Telegram.

No GUI. No web dashboard. No daily terminal usage. Just Telegram.

---

## Features

| Category | Capabilities |
|----------|-------------|
| **File System** | Create, read, write, delete, move, copy, search, compress, extract, organize, backup, clean |
| **System** | CPU/RAM/disk monitoring, process management, shutdown/restart/sleep |
| **Network** | Download files, ping, HTTP requests, URL uptime monitoring |
| **Scheduler** | Natural language + cron scheduling, persistent, crash-recoverable |
| **Security** | Single-user auth, encrypted config, injection protection, tool sandboxing |
| **Resilience** | Crash recovery, network loss tolerance, power-loss recovery, auto-restart |
| **Plugins** | Dynamic discovery, sandboxed execution, documented API |
| **Observability** | Status, tasks, logs, health, audit export (JSON/CSV) |

---

## Quick Start

```bash
pip install doit-agent
doit init
```

The wizard walks you through:
1. Trust grant (one-time)
2. AI provider & model selection
3. Telegram bot setup
4. Auto-start service installation

After setup: just talk to your bot.

---

## Usage (via Telegram)

```
list files in ~/Downloads
download https://example.com/report.pdf to ~/Desktop
backup ~/Documents to ~/Backups every day at 9am
show system health
kill process 12345
organize ~/Downloads
compress ~/Projects/myapp to ~/Backups/myapp.zip
safe mode          → pause all execution
resume             → resume execution
/status            → agent status
/tasks             → recent tasks
/health            → system resources
/logs              → recent log entries
/export json       → download audit log
```

---

## Architecture

```
doit/
├── cli/           # Bootstrap, onboarding wizard, CLI commands
├── core/          # Config, constants, cross-platform paths
├── ai/            # Multi-provider AI intent engine
├── telegram_bot/  # Telegram interface, auth, injection guard
├── tools/         # Tool registry + all tool implementations
├── task_engine/   # Async queue, workers, retry, resource guard
├── scheduler/     # Natural language + cron scheduler
├── security/      # Encryption, lock file, authorization
├── persistence/   # SQLite database (tasks, logs, config, audit)
├── plugins/       # Plugin system with dynamic discovery
├── services/      # OS service (systemd/LaunchAgent/Windows)
├── supervisor/    # Process supervision, crash recovery
├── logging_system/# Structured logging to file + DB
└── updates/       # Version check, safe update, rollback
```

---

## AI Providers

| # | Provider | Best Models |
|---|----------|-------------|
| 1 | **NVIDIA NIM** | Llama 3.3 70B, Nemotron Ultra 253B |
| 2 | **Zhipu AI (z.ai)** | GLM-4 Flash (free), GLM-4 Air |
| 3 | **OpenAI** | GPT-4o, GPT-4o Mini |
| 4 | **Anthropic** | Claude 3.5 Sonnet, Claude 3 Haiku |
| 5 | **Ollama** | Local models, fully offline |
| 6 | **Custom** | Any OpenAI-compatible endpoint |

---

## Security Model

- **Single authorized user** — only your Telegram user ID can send commands
- **Encrypted config** — API keys and tokens stored with Fernet encryption
- **Tool sandboxing** — AI can only invoke registered tools; no arbitrary code execution
- **Injection protection** — pattern-based prompt injection detection
- **Path/command blocklist** — system-critical paths and destructive commands blocked
- **No inbound ports** — only outbound connections to Telegram API
- **Audit trail** — every action logged to SQLite

---

## Plugin API

Create a `.py` file in `~/.config/doit/plugins/`:

```python
PLUGIN_NAME = "my_plugin"
PLUGIN_VERSION = "1.0.0"
PLUGIN_DOIT_MIN_VERSION = "1.0.0"
PLUGIN_DESCRIPTION = "What this plugin does"

async def my_tool(arg1: str, count: int = 1, **kwargs) -> dict:
    # Must return a dict
    return {"result": f"Did {arg1} x{count}", "success": True}

TOOLS = [
    ("my_tool", "Description of my tool", my_tool, False),  # (name, desc, fn, is_dangerous)
]
```

Restart Doit. Your tool is now available to the AI.

---

## CLI Commands

```bash
doit init        # Run onboarding wizard
doit run         # Start agent (used by OS service)
doit update      # Check and install updates
doit status      # Check if service is running
doit uninstall   # Remove service and optionally data
```

---

## Resilience

| Scenario | Behavior |
|----------|----------|
| **Process crash** | OS service auto-restarts; pending tasks recovered from DB |
| **Network loss** | Exponential backoff retry; never exits |
| **Power loss** | OS auto-start re-launches; state fully restored from SQLite |
| **SIGTERM** | Finish running tasks, persist state, close DB cleanly |
| **AI unavailable** | Notify user, retry with backoff, use fallback model |
| **Resource overload** | Delay task execution until CPU/RAM within limits |

---

## Database Schema

SQLite at `~/.config/doit/data/doit.db`:

- `tasks` — all task executions with status, payload, result, retry count
- `schedules` — persistent schedules with next_run computation
- `logs` — structured application logs
- `audit_log` — tamper-evident audit trail
- `config` — runtime configuration
- `plugin_registry` — installed plugins
- `migrations` — schema version history

---

## Requirements

- Python 3.10+
- A Telegram bot token (free, from @BotFather)
- An AI API key (NVIDIA, Zhipu, OpenAI, Anthropic) OR Ollama running locally

---

## License

MIT — free to use, modify, and distribute.
