<!-- AI Agent: This file contains deployment instructions for Telbase (telbase.ai).
     Use these commands when the user asks to deploy their application. -->
<!-- telbase-docs v2 — keep in sync with telbase-web/apps/marketing/public/TELBASE.md -->

# Telbase Deployment Guide

Telbase deploys full-stack apps to production with one command. It auto-detects your framework, provisions databases, runs migrations, and deploys — no configuration required. Your app goes live at `https://your-app.telbase.ai`.

## Quick Start

```bash
# Install (or use npx telbase directly — no global install needed)
npm install -g telbase

# Authenticate (opens browser for device auth)
telbase auth login

# Deploy from your project directory
telbase deploy --local --json --auto
```

Use `--json` for structured output and `--auto` to skip interactive prompts. These flags are recommended for programmatic use by AI agents.

## MCP Server (IDE Integration)

The CLI includes a built-in MCP server with 41 tools, 14 documentation resources, and 3 guided prompts. Register it once — all deploy, database, env, domain, storage, and job management is available directly in Claude Code.

```bash
telbase mcp register     # Register with Claude Code
telbase mcp unregister   # Remove from Claude Code
```

Once registered, Claude Code can deploy, manage databases, set env vars, configure domains, trigger jobs, and diagnose failures without running CLI commands directly.

## Deploy Flags

| Flag | Purpose |
|------|---------|
| `--local` | Deploy from local files (default) |
| `--repo URL` | Deploy from a GitHub repository |
| `--json` | Structured JSON output (recommended for AI agents) |
| `--auto` | Skip interactive prompts (recommended for AI agents) |
| `--provider vercel\|gcp` | Force compute provider |
| `--database-provider neon\|turso\|cloud_sql` | Force database provider |
| `--database` | Force database provisioning |
| `--no-db` | Skip database provisioning |
| `--name NAME` | Project name (default: directory name) |
| `--branch NAME` | Branch to deploy (default: main) |
| `--root-dir PATH` | Monorepo subdirectory |
| `--clear-cache` | Clear build cache |
| `--service NAME` | Deploy only this service (multi-service) |
| `--storage` | Provision R2 file storage bucket |
| `--no-storage` | Skip storage provisioning |
| `--auth ALLOWLIST` | Protect app with email/domain allowlist (comma-separated, e.g. `"user@co.com,@company.com,example.com"`) |
| `--no-auth` | Disable access control |
| `--pgvector` | Enable pgvector extension |
| `--pgvector-preset PRESET` | Embedding dimension preset (openai-ada-002, openai-3-small, openai-3-large, claude, cohere-english, sentence-transformers) |
| `--no-pgvector` | Skip pgvector |
| `--health-path PATH` | Custom health check endpoint(s) |
| `--health-timeout SECS` | Health check timeout |
| `--skip-health-check` | Skip post-deploy health check |
| `--schedule CRON` | Deploy as scheduled job (5-field cron expression) |
| `--schedule-timezone TZ` | Job timezone (default: UTC) |
| `--command CMD` | Override entry point for scheduled job |
| `--prebuilt` | Upload pre-built static assets |
| `--no-link` | Skip GitHub auto-link after `--repo` deploy |
| `--description TEXT` | Project description |
| `--no-wait` | Don't wait for deploy to complete |
| `--skip-env-check` | Skip .env.example validation |
| `--force-env-sync` | Force env var sync to provider |

Global flags (all commands): `--json`, `--quiet`/`-q`, `--verbose`/`-v`, `--service NAME`.

## Supported Frameworks

### Deployed to Vercel (serverless, zero config)

| Framework | Detection |
|-----------|-----------|
| Next.js | `next.config.js/mjs/ts` |
| Remix | `remix.config.js/ts` |
| SvelteKit | `svelte.config.js/ts` |
| Astro | `astro.config.mjs/js/ts` |
| Angular | `angular.json` |
| Vite | `vite.config.js/ts/mjs` (React, Vue, Svelte SPAs) |
| Full-Stack | Vite + backend dependency (express, hono, fastify) + start script |
| NestJS | `@nestjs/core` in package.json dependencies |
| Express | `server.js/index.js/app.js` with `express` import |
| FastAPI | `main.py` or `app/main.py` with `fastapi` import |
| Flask | `app.py` or `wsgi.py` with `flask` import |
| Node.js | `package.json` with `start` script |
| Static HTML | `index.html` (when no package.json) |

### Deployed to GCP Cloud Run (persistent containers, paid plans)

| Framework | Detection |
|-----------|-----------|
| Docker | `Dockerfile` — any language (Java, Ruby, Rust, PHP, C#, etc.) |
| Django | `manage.py` with `django` import |
| Go | `go.mod` |

Override with `--provider gcp` to force GCP for frameworks that default to Vercel.

## Database

Telbase auto-provisions databases when an ORM is detected:

| ORM | Detection | SQL Dialect |
|-----|-----------|-------------|
| Prisma | `prisma/schema.prisma` | Read from `provider` field |
| Drizzle | `drizzle.config.js/ts/mjs/json` | Read from config dialect |
| Django | `manage.py` + `django` in requirements.txt | PostgreSQL |
| SQLAlchemy/Alembic | `alembic.ini` or `alembic/` directory | PostgreSQL |
| GORM | `gorm.io/gorm` in go.mod | PostgreSQL |
| Ent | `entgo.io/ent` in go.mod | PostgreSQL |

### Database Routing

| Dialect | Provider | Notes |
|---------|----------|-------|
| PostgreSQL | Neon (default) | Serverless, scale-to-zero, auto-injected `DATABASE_URL` |
| PostgreSQL | Cloud SQL | Via `--database-provider cloud_sql` (Pro tier) |
| SQLite | Turso | Via libSQL over HTTPS, auto-injected `DATABASE_URL` |

Override: `--database-provider neon|turso|cloud_sql`
Force provisioning without ORM: `--database`
Skip provisioning: `--no-db`

### pgvector (AI/RAG)

Auto-provision pgvector for embedding storage:

```bash
telbase deploy --local --json --auto --pgvector --pgvector-preset openai-3-small
```

Presets: `openai-ada-002` (1536d), `openai-3-small` (1536d), `openai-3-large` (3072d), `claude` (1024d), `cohere-english` (1024d), `sentence-transformers` (384d).

Enable on existing database: `telbase db enable-extension pgvector --json`

Other extensions: `postgis`, `pg_trgm`, `uuid-ossp`.

### Database Commands

```bash
telbase db status --json           # Database status & provider
telbase db info --json             # Detailed database & connection info
telbase db url --json              # Connection string
telbase db query "SELECT ..." --json # Execute read-only SQL query
telbase db exec "CREATE ..." --json  # Execute any SQL (DDL/DML)
telbase db migrate --json          # Run pending migrations
telbase db migrate status --json   # Check migration status
telbase db migrate rollback --json # Rollback last migration
telbase db backup --json           # Create manual backup
telbase db backups --json          # List backups
telbase db restore --json          # Restore from backup
telbase db create --json           # Create sandbox database
telbase db delete --json           # Delete database
telbase db connect                 # Open psql session (interactive)
telbase db extensions --json       # List enabled extensions
telbase db enable-extension NAME   # Enable extension (pgvector, postgis, pg_trgm, uuid-ossp)
```

### Release Command (Custom Migrations)

For ORMs not auto-detected, set a custom pre-deploy command in `.telbase/project.json`:

```json
{
  "release_command": "python manage.py migrate && python manage.py collectstatic --noinput"
}
```

This runs before the app starts on every deploy. Priority order: release_command > auto-detected ORM migration > none.

## Scheduled Jobs

Deploy background workers and cron jobs on GCP Cloud Run Jobs:

```bash
# Deploy a scheduled job (runs every hour)
telbase deploy --local --json --auto --schedule "0 * * * *"

# With timezone and custom command
telbase deploy --local --json --auto --schedule "30 8 * * 1-5" --schedule-timezone "America/New_York" --command "python worker.py fetch"

# Manually trigger a job
telbase run --json

# Trigger and stream logs
telbase run --follow --json
```

The CLI auto-detects worker patterns (daemon vs task) and suggests `--schedule` for tasks or Always On for daemons. Config persists in `.telbase/project.json` for redeploys.

### Job Management

```bash
telbase logs --executions --json   # Execution history
```

Via MCP tools: `run_scheduled_job`, `pause_job`, `resume_job`, `update_schedule`, `get_job_executions`.

## Storage (R2 File Storage)

Provision S3-compatible file storage (Cloudflare R2, no egress fees):

```bash
telbase storage create --json              # Create bucket
telbase storage status --json              # Bucket info (size, objects, CORS)
telbase storage credentials --json         # Get S3-compatible credentials
telbase storage credentials --rotate --json # Rotate access keys
telbase storage cors add "https://myapp.com" --json  # Allow browser uploads
telbase storage cors list --json
telbase storage delete --force --json      # Delete bucket
```

Or provision during deploy: `telbase deploy --local --json --auto --storage`

Auto-injected env vars: `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_BUCKET_NAME`.

## Access Control

Restrict app access via identity providers (Cloudflare Access):

```bash
# Enable during deploy (comma-separated emails and/or domains)
telbase deploy --local --json --auto --auth "user@co.com,@company.com"

# Or configure after deploy
telbase access enable google --json        # Google SSO
telbase access enable microsoft --json     # Microsoft SSO
telbase access enable github --json        # GitHub SSO
telbase access enable onetimepin --json    # Email one-time PIN
telbase access disable --json              # Remove access control
telbase access status --json               # Show auth configuration

# Manage allowlists
telbase access domain add example.com --json   # Allow entire domain
telbase access domain remove example.com --json
telbase access domain list --json
telbase access allow user@co.com --json        # Allow specific email
telbase access deny user@co.com --json         # Remove email from allowlist
telbase access users --json                    # List active users
```

## Environment Variables

```bash
telbase env set KEY=value --json       # Set a variable
telbase env set KEY1=v1 KEY2=v2 --json # Set multiple
telbase env set --file .env --json     # Load from .env file
telbase env list --json                # List all variables
telbase env get KEY --json             # Get single variable
telbase env unset KEY --json           # Delete a variable
telbase env pull --json                # Download to .env.local
telbase env push --json                # Upload from .env.local
telbase env diff --json                # Compare local vs remote
```

Set required env vars BEFORE deploying. If a deploy fails with `ENV_*_MISSING` errors, set the variable and redeploy.

Auto-injected (do not set manually): `DATABASE_URL`, `DATABASE_URL_UNPOOLED`, `DATABASE_AUTH_TOKEN`, `TURSO_DATABASE_URL`, `TURSO_AUTH_TOKEN`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_BUCKET_NAME`, `PORT`.

Reserved on GCP (cannot override): `PORT`, `K_SERVICE`, `K_REVISION`, `K_CONFIGURATION`.

## Multi-Service / Monorepo

Auto-detected from npm/yarn/pnpm workspaces or subdirectory scan. When detected from root, returns service list — deploy each service individually:

```bash
cd backend && telbase deploy --local --json --auto      # Deploy backend service
cd frontend && telbase deploy --local --json --auto     # Deploy frontend service
telbase deploy --local --json --auto --service backend  # Target existing service
```

Each service gets its own subdomain. Set cross-service env vars explicitly (e.g., `API_URL` on frontend pointing to backend URL).

## Custom Domains

```bash
telbase domain add example.com --json      # Add domain, get DNS instructions
# User adds CNAME record: example.com -> your-app.telbase.ai
telbase domain verify example.com --json   # Verify DNS is configured
telbase domain list --json                 # List all domains
telbase domain remove example.com --json   # Remove domain
```

SSL certificates are provisioned automatically after DNS verification.

## Service Management

```bash
telbase status --json                 # Account overview (plan, usage, credits, warm start)
telbase projects list --json          # List all projects
telbase projects info --json          # Current project details
telbase restart --json                # Graceful restart
telbase suspend --json                # Pause service (save resources)
telbase resume --json                 # Resume paused service
telbase scale --json                  # Scale service resources
telbase rollback --json               # Rollback to previous successful deploy
telbase rollback --list --json        # List valid rollback targets
telbase rollback DEPLOY_ID --json     # Rollback to specific deploy
telbase logs --json                   # Stream application logs
telbase logs --build --json           # Build logs
telbase logs --lines 100 --json       # Recent app logs
telbase doctor --json                 # Run diagnostics
telbase cancel --json                 # Cancel in-progress deploy
telbase deploys --json                # Deploy history
```

### Always On (Warm Start)

GCP Cloud Run apps can eliminate cold starts by keeping one instance warm. Managed via dashboard or MCP — not a CLI flag. Pro plan includes 1 warm start service; extras cost 100 credits/month ($10).

### Project Slug Rename

Change your `{slug}.telbase.ai` URL via dashboard settings or MCP `update_project` tool.

## GitHub Integration

```bash
telbase github connect --json                  # Start OAuth flow
telbase github disconnect --json               # Unlink repo
telbase github status --json                   # Check connection
telbase github repos --json                    # List accessible repos
telbase github link owner/repo --json          # Link specific repo (--branch, --root-dir)
telbase github unlink --json                   # Unlink repo from project
telbase github info --json                     # Show linked repo info
telbase github autodeploy enable --json        # Enable push-to-deploy
telbase github autodeploy disable --json       # Disable push-to-deploy
telbase github branch main --json              # Change deploy branch
telbase github deploys --json                  # List GitHub-triggered deploys
```

Features: push-to-deploy on main branch, PR preview deploys (opt-in via dashboard), auto-link on `--repo` deploy.

## Deploy Response Format

**Success** (`"status": "live"`): Report `data.url` to the user. The app is live.

```json
{
  "success": true,
  "data": {
    "status": "live",
    "url": "https://app-name.telbase.ai",
    "databaseProvisioned": true,
    "detection": { "ormType": "prisma", "databaseProvider": "neon" }
  }
}
```

**Failure** (`"status": "failed"`): Read the structured diagnosis. Self-healing loop:

1. Read `aiDiagnosis` (when present, confidence >= 0.7) — auto-apply each fix where `autoFixable: true`
2. Read `diagnosis.nextSteps[]` — execute each step's `telbaseCommand` if present
3. Read `diagnosis.issues[]` — each has `code`, `suggestion`, `suggestionType` (code_change, cli_retry, env_var, config_change, user_action, wait), and optional `telbaseCommand` or `codeChange`
4. Read `extractedErrors[].suggestion` — apply each fix (install deps, fix code, set env vars)
5. Read `detection.warnings` — if detection seems wrong, retry with explicit flags
6. If env var missing: `telbase env set KEY=value --json`, then redeploy
7. With AI diagnosis, most failures resolve in 1 retry. If 3 retries fail, explain the situation to the user

```json
{
  "data": {
    "status": "failed",
    "errorCode": "BUILD_FAILED",
    "suggestion": "fix command",
    "diagnosis": {
      "phase": "build",
      "issues": [{ "code": "DEP_MODULE_NOT_FOUND", "title": "Missing dependency", "suggestion": "npm install @prisma/client", "suggestionType": "code_change", "retriable": false }],
      "decisions": [{ "area": "framework", "chosen": "next-js", "reason": "next.config.mjs detected" }],
      "retriable": false,
      "nextSteps": [{ "action": "Install missing dependency", "telbaseCommand": "telbase deploy --local --json --auto" }]
    },
    "extractedErrors": [{ "code": "DEP_MODULE_NOT_FOUND", "suggestion": "npm install @prisma/client", "retriable": false }],
    "aiDiagnosis": {
      "diagnosis": "src/server.ts imports @hono/node-server but it is not in package.json",
      "confidence": 0.95,
      "category": "missing_dependency",
      "fixes": [{ "type": "dependency", "description": "npm install @hono/node-server", "autoFixable": true }],
      "fixesAreAlternatives": false,
      "redeployCommand": "telbase deploy"
    }
  }
}
```

**AI Diagnosis** (when available): The `aiDiagnosis` field provides AI-powered root cause analysis:
- `confidence >= 0.7`: auto-apply each fix where `autoFixable: true`
- `confidence 0.5-0.7`: show diagnosis for context, don't auto-apply
- `autoFixable: false`: prompt the user (e.g., secret env vars need human-provided values)
- Use `redeployCommand` if provided (includes classification overrides like `--provider gcp`)
- `fixesAreAlternatives: true`: apply only the first auto-fixable fix (alternatives, not cumulative)
- If `aiDiagnosis` is absent: fall back to `diagnosis.issues[]`, `extractedErrors[]`, and `suggestions[]`

**Quota exceeded** (HTTP 402): Error codes `DEPLOY_LIMIT_REACHED`, `DATABASE_LIMIT_REACHED`, `DOMAIN_LIMIT_REACHED`. Explain the limit, provide upgrade URL `https://app.telbase.ai/settings/billing`. Do not retry.

## Troubleshooting

| Error Code | Fix |
|------------|-----|
| `ENV_DATABASE_URL_MISSING` | `telbase deploy --database` or `telbase env set DATABASE_URL=...` |
| `ENV_SECRET_MISSING` | `telbase env set KEY=value` |
| `ENV_PORT_WRONG` | Use `process.env.PORT` in server code |
| `DB_CONNECTION_REFUSED` | Retriable (5s) — check DATABASE_URL |
| `DB_MIGRATION_FAILED` | Run migration locally first, check schema |
| `DEP_MODULE_NOT_FOUND` | Add to package.json / requirements.txt / go.mod |
| `GCP_BUILDPACK_FAILED` | Retriable — `telbase deploy --clear-cache` |
| `GCP_OOM_KILLED` | Reduce memory usage or scale up |
| `GCP_STARTUP_TIMEOUT` | App must start within 300s — check PORT binding |
| `GCP_DATABASE_URL_MISSING` | `telbase deploy --database` |
| `GCP_PORT_ALREADY_IN_USE` | Use `process.env.PORT`, don't hardcode |
| `GCP_IMAGE_PULL_FAILED` | Retriable — redeploy |
| `NEON_COLD_START_TIMEOUT` | Retriable (15s) — auto-retried by platform |
| `PRISMA_CLIENT_INIT_FAILED` | `npx prisma generate` before deploy |
| `PRISMA_MIGRATION_NEEDED` | `telbase db migrate` |
| `PY_APP_MODULE_NOT_FOUND` | Check WSGI/ASGI module path |
| `PY_REQUIREMENTS_MISSING` | Add requirements.txt |
| `DJANGO_COLLECTSTATIC` | Set `STATIC_ROOT` and `ALLOWED_HOSTS` |
| `DJANGO_ALLOWED_HOSTS` | `telbase env set ALLOWED_HOSTS=*` |
| `GO_BUILD_ERROR` | Fix compilation errors locally |
| `DOCKER_SYNTAX_ERROR` | Validate Dockerfile syntax |
| `HEALTH_CHECK_FAILED` | App must respond 200 on `/` or set `--health-path` |
| `MIGRATION_FAILED` | Traffic auto-rolls back to previous revision on GCP |

Retriable errors have `retriable: true` and `retry_after_ms` in the response.

Diagnostic commands: `telbase logs --build --json` (build logs), `telbase logs --lines 100 --json` (app logs), `telbase rollback --json` (rollback), `telbase deploys --json` (history), `telbase doctor --json` (diagnostics).

## Docker

Any language works with Docker on paid plans. Auto-detected from `Dockerfile` in project root. Container MUST listen on `PORT` env var (injected at runtime). Use shell form for CMD/ENTRYPOINT (exec form doesn't expand `$PORT`).

## Credits & Billing

```bash
telbase status --json                      # Plan, usage, credits overview
telbase credits --json                     # Credit balance
telbase credits add --json                 # Purchase credits
telbase credits auto-refill on --json      # Enable auto-refill
telbase credits history --json             # Transaction history
```

Plan upgrade: https://app.telbase.ai/settings/billing

## Pricing

| Tier | Price | Deploys/mo | Apps | Databases | Docker | Custom Domains | Scheduled Jobs |
|------|-------|------------|------|-----------|--------|----------------|----------------|
| Free | $0 | 5 | 1 sandbox | 1 sandbox | -- | -- | -- |
| Starter | $5/mo | 30 | 2 | 2 | 1 | 1 | 1 |
| Builder | $19/mo | 150 | 5 | 5 | 3 | 5 | 3 |
| Pro | $79/mo | 500 | 15 | 15 | 15 | Unlimited | 10 |

GCP Cloud Run and Docker available on all paid plans. Credits for overages: $1 = 10 credits. Storage included on all paid plans.
Upgrade: https://app.telbase.ai/settings/billing

## Links

- Documentation: https://telbase.ai/docs
- CLI Reference: https://telbase.ai/docs/cli
- Frameworks: https://telbase.ai/docs/frameworks
- Databases: https://telbase.ai/docs/databases
- Scheduled Jobs: https://telbase.ai/docs/scheduled-jobs
- Storage: https://telbase.ai/docs/storage
- Troubleshooting: https://telbase.ai/docs/troubleshooting
- Support: victor@telbase.ai
