Skip to main content
Glama
README.md
# Colab-Hub: Cloudflare–Colab Async MCP Orchestrator & Interactive Control Center

**English** | **[Bahasa Indonesia](README.id.md)**

[![CI](https://github.com/Wontclogpores/colab-hub-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/Wontclogpores/colab-hub-mcp/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Cloudflare Workers Free Plan](https://img.shields.io/badge/Cloudflare%20Workers-Free%20Plan%20(%240%2Fmo)-F38020?logo=cloudflare&logoColor=white)](https://workers.cloudflare.com/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.8%2B-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![Python](https://img.shields.io/badge/Python-3.11%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)

**Colab-Hub** is a **\$0/month Remote Streamable HTTP MCP Server** on **Cloudflare Workers + SQLite Durable Objects** that turns **Google Colab Pro** (`CPU` / `T4` / `L4` / `A100`) into an asynchronous, unattended GPU compute backend controlled directly from **Gemini Chat**, backed by **Google Drive (`Drive:/Colab-Hub/`)** for persistent storage/caching and **Telegram** as a real-time **Interactive Control Center**.

> **Live-Verified Architecture:** End-to-end verified on Cloudflare Workers Free Plan (~179 KiB raw / ~42 KiB gzip, ~3 ms startup) driving live Google Colab Pro runtimes (`colaboratory.googleapis.com/mcp`), Google Drive API v3, and Telegram webhooks.

---

## Why Colab-Hub?

Conversational LLMs excel at reasoning and synthesis, but hit hard physical ceilings when tasks require:
- **Specialist CUDA GPU models:** Arabic/RTL & manuscript OCR (`Surya`, `Marker`, `Kraken`), long-form Arabic lecture transcription & diarization (`Faster-Whisper` + `Demucs` + `Pyannote`), classical Arabic computational linguistics (`CAMeL Tools`, `CAMeLBERT-CA`, `Parselmouth`/Praat, `ByT5` `'Arudh`), media restoration, and model fine-tuning.
- **Datacenter bandwidth & system binaries:** `yt-dlp`, `aria2c`, `XeLaTeX`/`Typst`, `DuckDB`/`Polars`, and `.apkg` Anki generation.
- **Multi-minute to multi-hour unattended pipelines** without triggering MCP client timeouts or leaking Google Colab Pro Compute Units (CU).

---

## Dual-Plane Architecture ("4 Homes")

```mermaid
flowchart TB
    subgraph UX["Clients & Interactive UX"]
        Gemini["Gemini Chat\nStreamable HTTP MCP\nPOST /mcp/:secret (<150ms writes)"]
        TG["Telegram Control Center\nLive Job Cards · Separate /menu\nInbox Quick Run · Stop All GPUs"]
    end

    subgraph CP["Home 1: Control Plane — Cloudflare Workers Free Plan ($0/mo)"]
        Router["Edge Router (src/router.ts)\nConstant-time Auth · OAuth CSRF"]
        DO["JobOrchestratorDO (SQLite Singleton)\n8 Tables · Deterministic recomputeNextAlarm()\nMax 1 Provision/Tick · Token Broker (503/401)"]
        Router --> DO
    end

    subgraph REPO["Home 2: Recipe Repo (GitHub)"]
        GH["runner/colab_runner.py\nrecipes/*.py + constraints/*.txt\n(Add recipes with 0 Worker redeploy)"]
    end

    subgraph EXEC["Home 3: Compute Plane — Google Colab Pro VM (Ephemeral)"]
        Colab["Official Colab MCP (colaboratory.googleapis.com/mcp)\n1. create_runtime (idempotent UUID)\n2. execute_code (UTF-8 Base64 bootstrap)\n3. Detached runner + 180s daemon heartbeat + uv venv\n4. delete_runtime (guaranteed async teardown)"]
    end

    subgraph STORE["Home 4: Storage Plane — Google Drive 5 TB (Drive:/Colab-Hub/)"]
        Drive["inbox/ · outputs/<date>_<slug>_<id>/\ncache/ (atomic .tar.zst + appProperties.sha256)\ncorpora/ · models/ · custom_modules/"]
    end

    Gemini -->|JSON-RPC 2.0| Router
    TG <-->|Webhook + Bot API| Router
    DO <-->|JSON-RPC · 0ms CPU wait| Colab
    Colab -->|HTTPS Raw / API Fetch| GH
    Colab -->|Pure-SQLite Webhook + Token Broker| Router
    Colab <-->|Direct Drive API v3 ~150-300 MB/s| Drive
    DO -->|Range <=64KB Summary & <=1.5MB PNG| Drive
```

---

## Production Engineering Highlights

Every invariant below is implemented in code, covered by automated tests (Vitest + `node:sqlite` and Python `unittest`), and verified against live Cloudflare & Google Colab production edge behavior:

| Engineering Pillar | What Is Built & Verified | Code Reference |
| :--- | :--- | :--- |
| **Anti-Timeout MCP & Pure-SQLite Hooks** | `submit_colab_job` and `control_job` only mutate SQLite DO and schedule `alarm(+250ms)` (`<150 ms`). Terminal webhooks (`completed`/`failed`) from Colab perform **0 outbound subrequests** — Telegram card edits and chart uploads run asynchronously in the next alarm tick. | [src/do/state.ts](src/do/state.ts), [src/do/orchestrator.ts](src/do/orchestrator.ts) |
| **Anti-Zombie GPU Teardown & Pool Caps** | Strict FIFO pool limits (`1 GPU` + `2 CPU`) count both active and `pending_delete` runtimes. Guards against post-`await` cancel races (`starting` vs `cancelling`), enforces 3m startup & 10m heartbeat watchdogs + hard `max_runtime_sec` kill switch, and verifies `delete_runtime` with backoff + `404`/`NOT_FOUND` idempotency. | [src/do/scheduler.ts](src/do/scheduler.ts), [src/do/orchestrator.ts](src/do/orchestrator.ts) |
| **Cost & Payload Blast-Radius Guards** | High-cost requests (`a100` or `max_runtime_minutes > 120`) require explicit `confirm_high_cost: true`. Hard caps enforced end-to-end: `custom_code <= 64 KB`, `params_json <= 80 KB`, `stages <= 5`, `SUMMARY_FOR_GEMINI.md <= 64 KB` (HTTP `Range`), and `preview_chart.png <= 1.5 MB` (streaming read). | [src/do/orchestrator.ts](src/do/orchestrator.ts), [src/drive/client.ts](src/drive/client.ts) |
| **Mid-Job OAuth Rescue (7-Day Gmail Cycle)** | Personal `@gmail.com` Testing-mode OAuth tokens expire every 7 days. Colab-Hub sends a proactive Day-6 Telegram reminder even when idle, pauses queued jobs in `awaiting_auth`, and returns HTTP `503 google_reauth_required` (vs `401` revocation) so long-running Colab VMs pause up to 15 min for 1-click re-auth instead of losing work. | [src/auth/google.ts](src/auth/google.ts), [runner/drive_io.py](runner/drive_io.py) |
| **Zero Secret Leaks Inside Ephemeral VMs** | Per-job `job_secret` is hashed (SHA-256) in SQLite; `colab_runner.py` immediately `unlink()`s `/tmp/job_config.json`; `custom_script.py` scrubs Worker/runner secrets from subprocess `env`; double-tap Telegram actions consume atomic one-time tokens inside `transactionSync()`. | [runner/colab_runner.py](runner/colab_runner.py), [recipes/custom_script.py](recipes/custom_script.py), [SECURITY.md](SECURITY.md) |
| **Battle-Tested Production Edge Fixes** | Live deployment surfaced and permanently fixed: `workerd` `globalThis.fetch` binding (`Illegal invocation`), RFC 6265bis `Path=/` requirement on `__Host-oauth_state` cookies, live `colaboratory.googleapis.com/mcp` nested `runtime.runtimeSpec` & `execute_code.runtime` schemas, `BOOTSTRAP_OK` stdout verification, and custom `ColabHubRunner/1.0` `User-Agent` for Cloudflare `*.workers.dev` edge filtering. | [src/auth/google.ts](src/auth/google.ts), [src/colab/client.ts](src/colab/client.ts), [runner/colab_runner.py](runner/colab_runner.py) |

---

## Capabilities: Wave 1 (Live) vs. Wave 2 (Roadmap)

All 13 recipes are defined in [src/recipes/registry.ts](src/recipes/registry.ts) across 4 zones. Only **Wave 1** recipes have `runnable: true`; attempting to submit a Wave 2 recipe from MCP or Telegram Quick Run is cleanly rejected until implemented.

### Wave 1 — Live & Production-Verified (6 Recipes)

| Zone | Recipe | Default Profile | Implemented Capabilities |
| :--- | :--- | :--- | :--- |
| **Zone 1: Media & Audio** | `download_to_drive` | `cpu` | `yt-dlp` (video/MP3) & `aria2c` (`mode: "direct"`) directly to Drive with per-URL checkpointing and `manifest.json`. |
| | `audio_lecture_pipeline` | `t4` / `l4` | `Faster-Whisper large-v3-turbo` (CUDA `float16` / CPU `int8`), optional `Demucs` denoise, `Pyannote` diarization (`HF_TOKEN`), `.srt`, `.transcript.md`, and `.apkg` Anki decks. |
| **Zone 2: Documents & OCR** | `ocr_pdf_to_drive` | `t4` / `l4` | `Surya` / `Marker` (printed Arabic/RTL multi-column PDFs) + `Kraken` (manuscript OCR via isolated console binary) with atomic Drive cache & per-file checkpointing. |
| **Zone 3: Arabic & Turats** | `shamela_bulk_export` | `cpu` (`t4` embed) | Polite official Shamela MCP mode (`concurrency=1`, `1.0–1.5s` delay, 3s fail-fast probe on `401`/`403`, 300-page default cap) plus `openiti` (`-ara1`) and `drive_dump` extractors preserving `[ج X / ص Y]` citations. |
| **Zone 4: Setup & Escape Hatch** | `bootstrap_hub` | `cpu` | Day-0 initializer: verifies all 6 `Drive:/Colab-Hub/` folders, initializes local cache layout, and optionally fetches `OpenITI_metadata_light.csv`. |
| | `custom_script` | Any | Sandboxed Python escape hatch (`<= 64 KB`, stripped env, auto-mounts `Drive:/Colab-Hub/custom_modules/` onto `PYTHONPATH`, auto-uploads `/tmp/job_output/`). |

### Wave 2 — Schema-Defined Blueprint (7 Recipes, `runnable: false`)

| Zone | Planned Recipe | Target Profile | Planned Scope |
| :--- | :--- | :--- | :--- |
| **Zone 1** | `media_restore_upscale` | `l4` / `a100` | `CodeFormer`, `Real-ESRGAN`, `RIFE` + before/after `preview_chart.png`. |
| **Zone 2** | `publish_document` | `cpu` | Print-ready Arabic RTL typesetting (`XeLaTeX`, `Typst`, `Pandoc`). |
| | `data_crunch` | `cpu_highram` | Multi-GB CSV/Parquet analytics (`DuckDB`, `Polars`, `matplotlib`). |
| **Zone 3: Arabic Lab Benches** | `lab_morphology_semantics` | `t4` / `l4` | **Bench A:** `CAMeL Tools`, `CAMeLBERT-CA`, `Stanza`, `bge-m3` + FAISS (2H–9H semantic shift). |
| | `lab_acoustic_phonetics` | `t4` | **Bench B:** `Parselmouth` (Praat), `Librosa`, `Wav2Vec2-XLSR-Arabic` ($F_1$–$F_3$, VOT, `.TextGrid`). |
| | `lab_arudh_stylometry` | `t4` / `l4` | **Bench C:** `ByT5` `'Arudh` scansion + `scikit-learn` stylometry (`tahqiq al-nisbah`). |
| **Zone 4** | `finetune_model` | `l4` / `a100` | `Unsloth` QLoRA / `ByT5` fine-tuning saved to `Drive:/Colab-Hub/models/`. |

---

## Telegram Interactive Control Center Flow

Every job owns a dedicated live-updating card message (separate from the persistent `/menu` dashboard) so real-time progress edits never overwrite navigation menus:

```mermaid
sequenceDiagram
    actor User
    participant TG as Telegram Bot
    participant DO as JobOrchestratorDO (SQLite)
    participant Colab as Colab Pro VM

    User->>TG: /inbox → Tap PDF → [Confirm Run]
    TG->>DO: POST /api/telegram/webhook (atomic one-time token)
    DO-->>TG: 200 OK + Enqueue job (<150ms) + alarm(+250ms)
    DO->>Colab: alarm() → create_runtime + Base64 bootstrap
    Colab->>DO: POST /webhook (started / progress / 180s heartbeat)
    DO->>TG: editMessageText (Live Job Card + [Live Log] / [Stop])
    Colab->>DO: POST /webhook (completed + summary_file_id) [0 subrequests]
    DO->>Colab: Next alarm() → delete_runtime (guaranteed teardown)
    DO->>TG: Final card ([Open Drive] / [View Summary]) + sendPhoto (<=1.5MB)
```

---

## Documentation Index

| Document | Contents |
| :--- | :--- |
| **[SECURITY.md](SECURITY.md)** | Threat model, secret isolation controls, CSRF/auth invariants, payload caps, and vulnerability reporting. |
| **[docs/SETUP.md](docs/SETUP.md)** *(ID)* | End-to-end deployment guide (GitHub, Google Cloud OAuth + Colab/Drive APIs, BotFather, `wrangler secret put`, `wrangler deploy`, 1-click Telegram setup, Gemini Chat URL). |
| **[docs/USAGE.md](docs/USAGE.md)** *(ID)* | Daily workflows, Gemini Chat prompts by Zone, CPU→GPU multi-stage pipelines, Telegram `/menu` & `/inbox` Quick Run, checkpoint resume, and 7-day OAuth cycle. |
| **[docs/MCP_API.md](docs/MCP_API.md)** *(ID)* | Complete reference for all 8 anti-timeout MCP tools, Streamable HTTP JSON-RPC 2.0 compliance, and Worker HTTP/webhook routes. |
| **[docs/RECIPES.md](docs/RECIPES.md)** *(ID)* | Developer guide for `RecipeContext`, detached runner lifecycle, atomic `.tar.zst` Drive caching, adding Wave 2 recipes, and third-party runtime license notes. |
| **[Design Spec v2.1](docs/superpowers/specs/2026-12-01-cloudflare-colab-mcp-design.md)** | Archived architectural specification post-adversarial audit (8-table DO SQLite schema, state machine, anti-zombie defenses, Free Plan budget). |
| **[Wave 1 TDD Plan](docs/superpowers/plans/2026-12-01-colab-hub-wave1.md)** | Archived 9-task TDD implementation plan for Wave 1. |
| **[README.id.md](README.id.md)** | Full Indonesian overview. |

---

## Quickstart & Local Verification

**Prerequisites:** Node.js `>= 22.13.0` (built-in `node:sqlite`), Python `>= 3.11`, Cloudflare Free Plan account, Google account with Colab Pro + Drive, and a Telegram Bot.

```bash
# 1. Install dependencies & run the full TypeScript quality gate (typecheck + 46 Vitest tests + offline Wrangler bundle check)
npm ci
npm run check

# 2. Run the Python runner & Wave 1 recipe unit tests (12 tests)
python -m unittest discover -s tests/python -v

# 3. Deploy to Cloudflare Workers (see docs/SETUP.md for OAuth & Wrangler secrets)
npx wrangler login
npx wrangler deploy

# 4. Register Telegram webhook/commands & send your 1-click Google OAuth link to Telegram
curl -X POST "https://<WORKER-NAME>.<SUBDOMAIN>.workers.dev/admin/telegram/setup" \
  -H "Authorization: Bearer <ADMIN_SECRET>"
```

Connect **Gemini Chat → Custom Streamable HTTP MCP** using:
```text
https://<WORKER-NAME>.<SUBDOMAIN>.workers.dev/mcp/<MCP_PATH_SECRET>
```
*(CLI / custom MCP clients can also use `POST /mcp` with `Authorization: Bearer <MCP_PATH_SECRET>`.)*

---

## License

Released under the [MIT License](LICENSE). Third-party Python packages dynamically installed inside the user's ephemeral Colab VM at runtime (such as `surya-ocr`/`marker-pdf`, `faster-whisper`, or `aria2c`) are not bundled in this repository and remain subject to their respective upstream licenses.