---
name: cli
version: 0.2.0
description: Deploy and operate web apps on CLI for your user. Wallet sign-in, x402 USDC payments, structured deploy errors with fixes.
api: https://clicloud-production.up.railway.app
---

# CLI skill

CLI hosts your user's apps. You (the agent) do the work: sign in with a wallet, fund the project over x402, deploy, read structured errors, fix them, and report back. Every response is JSON. Every error has `error.code`; branch on the code, never on the message text.

Prefer the MCP server (`cli_*` tools) if it is connected. Otherwise call the REST API at https://clicloud-production.up.railway.app. The sections below give REST paths; with MCP, use the tool for the same job:

- Who am I, limits, projects: `cli_whoami`, `cli_wallet`, `cli_list_projects`, `cli_create_project`, `cli_get_project`, `cli_add_agent`, `cli_add_member`, `cli_audit_log`, `cli_recent_changes`, `cli_undo`
- Money: `cli_topup`, `cli_funding_options`, `cli_token`, `cli_usage`, `cli_set_plan`, `cli_set_low_balance_alert`
- Services and deploys: `cli_create_service`, `cli_update_service`, `cli_deploy`, `cli_deploy_status`, `cli_logs`, `cli_service_logs`, `cli_rollback`, `cli_delete_service`, `cli_exec`, `cli_environments`, `cli_set_previews`
- Variables: `cli_set_env`, `cli_shared_variables`, `cli_check_variables`
- Databases and backups: `cli_create_database`, `cli_link_database`, `cli_query_database`, `cli_database_access`, `cli_list_backups`, `cli_backup_database`, `cli_restore_backup`
- Domains: `cli_add_domain`, `cli_generate_domain`, `cli_rename_domain`, `cli_verify_domain`, `cli_list_domains`, `cli_remove_domain`
- Cron: `cli_create_cron`, `cli_list_cron`, `cli_update_cron`, `cli_run_cron`
- Health and debugging: `cli_service_health`, `cli_request_metrics`, `cli_events`, `cli_explain_error`, `cli_known_fixes`
- Shipping safely and leaving: `cli_shadow`, `cli_provenance`, `cli_export_manifest`
- AI models and on-chain automation: `cli_ai`, `cli_keeper`, `cli_watch_contract`
- Domains, email, sign-in and vector search for the user's app: `cli_domain`, `cli_email`, `cli_app_signin`, `cli_vector`
- Static sites, functions, the edge and costs: `cli_static_site`, `cli_function`, `cli_edge`, `cli_static_ip`, `cli_rightsize`
- Workflows, testing, monitoring and forecasts: `cli_workflow`, `cli_load_test`, `cli_browser_check`, `cli_secrets`, `cli_forecast`
- Checking and setting up: `cli_doctor`, `cli_detect`
- Logs, databases, status and selling: `cli_log_alerts`, `cli_db_tools`, `cli_status_notice`, `cli_paid_apis`, `cli_sell`
- Launching and building: `cli_go_live`, `cli_requests`, `cli_compare_environments`, `cli_unit_economics`, `cli_project_map`, `cli_webhook_inbox`, `cli_flags`, `cli_dependencies`
- Templates and moving in: `cli_list_templates`, `cli_deploy_template`, `cli_import`
- Working with people and other agents: `cli_propose_change`, `cli_wait_for_approval`, `cli_find_api`, `cli_agent_credential`, `cli_agent_marketplace`, `cli_bounties`
- Sandboxes (run code in a throwaway machine): `cli_sandbox_create`, `cli_sandbox_exec`, `cli_sandbox_write_file`, `cli_sandbox_read_file`, `cli_sandbox_delete`

## 1. Sign in

People can also sign in with email or GitHub in the dashboard at https://clicloud-production.up.railway.app. Agents use a wallet:

1. `POST https://clicloud-production.up.railway.app/v1/auth/challenge` with `{"address":"<your wallet>"}`: a 0x EVM address or a base58 Solana address.
2. Sign the returned `message` exactly as given. EVM: personal_sign (EIP-191), hex signature. Solana: ed25519 signMessage over the UTF-8 bytes, signature as base58 (or base64).
3. `POST https://clicloud-production.up.railway.app/v1/auth/verify` with `{"message","signature"}`. You get `token`, valid 24h.
4. Send `Authorization: Bearer <token>` on every other request.

## 2. Project and funding

- Create: `POST /v1/projects {"name"}`. The signing wallet becomes owner.
- Check balance: `GET /v1/projects/:id` → `balance` (micro-USDC, 1 USDC = 1000000).
- Top up: `POST /v1/projects/:id/topup?amount=<micro>` (minimum 1000000).
  - First call returns **402** with `accepts[]` (also base64 JSON in the `PAYMENT-REQUIRED` header), one option per network. Pick the network your wallet holds USDC on:
- Base (EVM): network `eip155:84532`, USDC `0x036CbD53842c5426634e7929541eC2318f3dCF7e`
  - Base: sign an EIP-3009 `transferWithAuthorization` for that option. Payload: `{"signature","authorization"}`.
  - Solana: build a transaction with one SPL `TransferChecked` (6 decimals) from your USDC token account to the `payTo` wallet's associated token account, set the fee payer to `extra.feePayer`, sign it yourself (leave the fee payer signature empty) and base64 it. Payload: `{"transaction"}`.
  - Wrap it as `{"x402Version":2,"accepted":<the option you chose>,"payload":...}`, base64-encode, and resend the same request with header `PAYMENT-SIGNATURE`.
  - Success returns 200 with the new `balance`.
- Anyone can pay for a project. If you have no funds, give the user the project id and the top-up URL and ask them to pay.
- Users without crypto can pay by card: a signed-in person calls `POST /v1/projects/:id/topup/card {"amountUsd":10}` and opens the returned `checkoutUrl`. Credit appears once the payment clears. 402 responses include `error.details.cardTopupUrl` when cards are enabled. Agents should pay with x402 rather than cards.
- Some servers give a new account's first project free credit to start with: `POST /v1/projects` then says how much in `welcomeCredit`, and `GET /v1/me` shows whether it's still `available`. It's once per person (people signed in with email or GitHub; API keys never get it), so don't make extra projects to get more.
- Any request that starts compute can return **402 INSUFFICIENT_FUNDS**. Its body already contains the x402 challenge for the shortfall: pay it, then retry the original request.

## 3. Deploy loop

1. Create a service: `POST /v1/projects/:id/services` with `{"name","source":...,"port":8080}`. Sources:
   - Public git: `{"type":"git","repo":"https://github.com/org/repo","branch":"main"}`
   - Private GitHub (push-to-deploy and commit statuses): `{"type":"github","repo":"org/repo"}`. Needs the user's GitHub linked and the CLI GitHub App installed on the repo. If you get GITHUB_NOT_LINKED or GITHUB_REPO_NOT_ACCESSIBLE, give the user the URL from `POST /v1/auth/github/link` or `GET /v1/github/install-url`; only they can approve it in a browser. `GET /v1/github/repos` lists what you can deploy.
   - Docker image from any registry: `{"type":"image","image":"ghcr.io/org/app:tag"}`. It's pulled on every deploy and pinned to its digest (rollbacks get the exact image). Private images: add `"registry":{"server":"ghcr.io","username":"…","password":"<token>"}` (ask the user for these; GHCR tokens need read:packages). Pull problems fail as **IMAGE_PULL_FAILED**.
   - Optional `"startCommand":"node dist/server.js"` on any app replaces the image's command (run with /bin/sh -c). Change later with PATCH (`startCommand`, and for image services `image` and `registry`).
2. Set env vars: `PUT /v1/services/:id/env` with `{"vars":{"KEY":"value"}}`, or a whole .env file as `{"dotenv":"A=1\nB=2"}`. Use `null` to delete a key. Values are write-only. See **Variables** for references between services.
3. Deploy: `POST /v1/services/:id/deploys` (optional `{"commit":"sha"}`). Returns a deploy in `queued`.
4. Poll `GET /v1/deploys/:id` every 5 seconds until status is `healthy`, `failed` or `cancelled`.
5. On `healthy`: report `url` to the user. On `failed`: read `error.code` and follow the playbook below.

Your app must listen on `process.env.PORT` (CLI sets PORT to the service port) and host `0.0.0.0`, and answer `GET /` (or `healthcheckPath`) with 2xx.

### Variables and references

A value can point at another service instead of copying it, and it's resolved on every deploy:

- `${{postgres.DATABASE_URL}}` (or `MYSQL_URL`, `REDIS_URL`, `MONGO_URL`, `URL`, `HOST`, `PORT`, or any variable set on that database)
- `${{api.URL}}` (https://its public address), `${{api.DOMAIN}}`, `${{api.PRIVATE_URL}}` (http://api.internal:port, private network), `${{api.PRIVATE_HOST}}`, `${{api.PORT}}`, or any variable set on `api`
- `${{shared.KEY}}` for project-wide shared variables: `PUT /v1/projects/:id/variables {"vars":{...}}` (or `{"dotenv":"…"}`); `GET` lists them.

References can be mixed with text: `"API_URL":"${{api.URL}}/v1"`. Prefer references over pasting URLs: they survive renamed domains and rotated values. `GET /v1/services/:id/env/check` lists each reference and whether it resolves; a deploy with a broken one fails as **VARIABLE_REFERENCE_MISSING** before building. Every service can reach every other service in its project at `<name>.internal` (also plain `<name>`).

### Environments

A project is its **production** environment. `POST /v1/projects/:id/environments {"name":"staging"}` (admins; optional `"from"`) adds a copy: same services and variables, fresh empty databases, no domains, nothing running until you deploy. It has its own project id: use it anywhere a project id goes. Environments share the project's people, balance and approval policy. Variables with references point at the environment's own services automatically. Point an environment's GitHub services at another branch with `PATCH /v1/services/:id {"branch":"staging","autoDeploy":true}`. `GET /v1/projects/:id/environments` lists them; `DELETE /v1/projects/:envId` deletes one with its data. API keys created in an environment only work there.

### Monorepos and cli.json

- `"rootDir":"apps/web"` (on create or PATCH) builds from that folder. Pushes then only redeploy a service when they change files under its folder, or under its `watchPaths` (globs like `apps/web/**`, `packages/**`, `!**/*.md`). The push webhook reports skipped services.
- A `cli.json` in the root directory sets how it builds and runs, and wins over dashboard settings: `{"build":{"command","dockerfile"},"deploy":{"startCommand","healthcheckPath","port","replicas","sleepAfterMinutes"},"watchPaths":[…],"cron":[{"name","schedule","command"}]}`. Each deploy shows the config it used (`config`). A bad file fails as **CONFIG_INVALID** with every problem listed. Prefer cli.json when you're editing the repo anyway: it's reviewed with the code.

### Sleep when idle

`PATCH /v1/services/:id {"sleepAfterMinutes":30}` stops an app after 30 minutes without traffic, which stops its billing, and starts it again on the next request (visitors see a "Starting…" page for a few seconds). Good for previews, staging and side projects; leave production always on (`null`). `status` is `sleeping` while asleep; `POST /v1/services/:id/wake` wakes it. To sleep on a timetable: `PUT /v1/services/:id/sleep-schedule {"schedule":{"tz":"America/New_York","from":"22:00","to":"07:00","days":[1,2,3,4,5],"wakeOnRequest":true}}`. `PUT /v1/services/:id/instant-wake {"enabled":true}` keeps a sleeping app ready so the first visitor doesn't wait (paused in memory: memory is billed, no CPU).

### Talking to services

- **Private network:** every service reaches every other service in its environment at `<name>.internal` (`${{api.PRIVATE_URL}}`). Nothing private is exposed to the internet.
- **Databases from outside:** `PATCH /v1/services/:dbId {"publicTcp":true}` opens a TCP port; `GET /v1/services/:dbId/connection` returns the private and public URLs (with the password; developers and up). Only open it when the user asks, and close it after.
- **Data viewer:** `GET /v1/services/:dbId/tables` and `POST /v1/services/:dbId/query {"sql":"select …"}` for Postgres and MySQL, read-only by default. Writes need `"readOnly":false` and an admin.
- **Commands:** `POST /v1/services/:id/exec {"command":"npx prisma migrate deploy"}` runs in the live container and returns output and exit code. Use it for migrations and checks, not long-running work (60s default, 300s max).

### Templates

`GET /v1/templates` lists one-click stacks (web app + Postgres, web app + Postgres + Redis, n8n, Umami, Ghost, Uptime Kuma, Metabase, Directus, Gitea) with their inputs and hourly cost. `POST /v1/projects/:id/templates/:template {"inputs":{...}}` creates every service, wires their variables with references, starts the databases, and starts each app once the databases it uses are running (watch the event stream, or poll the services: `waitingFor` empties as they start). Show the user the dry run first; templates cost money.

### Databases

- `POST /v1/projects/:id/databases {"kind":"postgres"}` (or `"mysql"`, `"redis"`, `"mongo"`; optional `"name"`, `"plan"`, and `"linkTo":"<appId>"` to connect it in the same call) creates a private database with generated credentials and starts it. It is billed like any service and is only reachable from apps in the same project.
- `POST /v1/services/:appId/link {"databaseId":"svc_..."}` stores the connection URL in the app's env as a secret: `DATABASE_URL` for Postgres, `MYSQL_URL`, `REDIS_URL`, `MONGO_URL`, or pass `"var"`. Redeploy the app.
- If a deploy fails with MISSING_ENV for `DATABASE_URL` or `REDIS_URL`, ask the user whether to use an existing database (they give you the URL) or create one on CLI. Don't create one without asking: it costs money.
- Database credentials can't be edited. Data lives on a volume that survives redeploys.

### Domains

Every app gets `https://<service>-<id>.<app domain>` automatically. For a nicer address with no DNS work, `POST /v1/services/:id/domains/generate` (optional `{"subdomain":"my-shop"}`) gives a hosted `<subdomain>.<app domain>` that's live at once; rename it with `PATCH /v1/domains/:id {"subdomain"}`. One per service.

For the user's own domain:

1. `POST /v1/services/:id/domains {"hostname":"app.example.com"}` returns two `records`: a TXT that proves ownership and a CNAME that routes traffic.
2. Give both records to the user to add at their DNS provider. You can't do this step for them.
3. `POST /v1/domains/:id/verify`. **DOMAIN_NOT_VERIFIED** lists what's missing in `error.details.problems`. DNS can take minutes: retry at most every 2 minutes, and stop after 5 tries to check with the user.
4. Once `status` is `active`, `https://<hostname>` serves the app; the certificate is issued on the first request.

### Pull-request previews

`PATCH /v1/services/:id {"previews":true}` on a GitHub service. Every PR into its tracked branch then gets a preview service (`<name>-pr-<n>`) built from the PR's head, redeployed on each push, with the parent's env vars, a commit status and a PR comment with the URL. It's deleted when the PR closes. PRs from forks aren't built.

Databases linked with the link endpoint get a throwaway copy per preview (`<db>-pr-<n>`, smallest plan), so previews never touch production data. They start empty; `"previewData":"copy"` seeds them from the latest backup instead (tell the user: that copies production data into previews). Previews are billed like any service.

### Backups

- Every running database is backed up daily (encrypted, kept 7 days). Stored backups are billed per GB-month by the hour (price in `GET /v1/pricing` → `backupStorage`); each database's total is in `storage` on its backups list. `GET /v1/services/:id/backups` lists them.
- `POST /v1/services/:id/backups` backs up now. Do this before running migrations or anything risky against a database.
- Before a migration, check it: `POST /v1/services/:id/migrations/check {"sql":"…","rehearse":true}` lists what loses data, breaks the running code or locks a busy table, each with a `safer` way, and rehearses it on an empty copy of the schema. Prefer the safer way. `POST /v1/services/:id/migrations` refuses a `risky` one (409, `details.check`) unless you send `acceptRisk: true`: ask the person first. `CREATE INDEX CONCURRENTLY` needs `noTransaction: true`.
- `POST /v1/backups/:id/restore {"confirm":"<database name>"}` replaces all data with the backup, after taking a safety backup (its id is in the restore). Only restore when the user asks; poll `GET /v1/restores/:id`.

### Usage and right-sizing

- `GET /v1/projects/:id/usage` gives balance, burn per hour, runway in hours and cost per service. `GET /v1/services/:id/usage` gives hourly CPU, memory, egress and cost, utilization against the plan, and `advice` (`downsize`, `upsize` or `keep`, with the suggested plan and savings).
- When advice says downsize, propose it to the user with the saving; apply with `PATCH /v1/services/:id {"plan":{"cpu","memMb"}}` and redeploy. Ask before upsizing: it costs more.
- Owners can set `PATCH /v1/projects/:id {"lowBalanceAlert": <micro-USDC>}` to get emailed and webhooked when credit drops below it.

### Deploying local code

People with the `cli` command can run `cli up` in a folder to upload and deploy it (source type `upload`). Agents can do the same: `POST /v1/services/:id/deploys/upload` with a gzipped tarball body (`content-type: application/gzip`, limit in `GET /v1/config` → `uploadMaxMb`).

### Running in production

- **Scaling:** `PATCH /v1/services/:id {"replicas":3}` runs that many copies behind the address (1-10, each billed as a full plan, applies on the next deploy). Deploys are all-or-nothing: the old copies keep serving until every new one is healthy.
- **Volumes:** `PATCH /v1/services/:id {"volume":{"mountPath":"/data"}}` gives an app a persistent disk (billed per GB stored). A service with a volume runs one copy and restarts on deploy instead of overlapping. Its data is deleted only with `DELETE /v1/services/:id?deleteData=true` (admins).
- **Cron jobs:** `POST /v1/services/:id/cron {"name","schedule","command"}` runs `command` (via /bin/sh -c) in the service's live image with its env and databases. Schedules are 5-field cron in UTC or @hourly/@daily/@weekly, at most every 5 minutes. `POST /v1/cron/:id/run` runs now; `GET /v1/cron/:id/runs` and `GET /v1/cron-runs/:id` show results and output. Runs are billed by the second.
- **Uptime:** CLI checks every live app each minute. After 3 failed checks it's down: an incident opens and owners/admins get an email and the project webhook a message, again on recovery. `GET /v1/services/:id/health` shows status, uptime and incidents; `"healthAlerts":false` silences a service.

### Previews of changes (dry runs)

Add `?dryRun=true` (or header `X-CLI-Dry-Run: true`) to a deploy, rollback, service update, new database, template or delete and you get `{"dryRun":true,"plan":{…}}` instead: what would change, the hourly cost before and after, whether it restarts anything, what would break, `wouldFail` (e.g. not enough credit) and `needsApproval`. Nothing changes and nothing is logged. Use it to show the user a plan before anything costly or destructive.

### Approvals

Projects can require a person's sign-off before agents (the **agent** role and agent API keys) make destructive changes (delete services or domains, restore backups, remove members, delete cron jobs) or changes that add more than a set amount an hour (`approvalPolicy` on `GET /v1/projects/:id`). When that applies you get **403 APPROVAL_REQUIRED** with `details.approvalId` and `details.approveUrl`:

1. Tell the user what you asked for and give them the approveUrl. They're also notified.
2. Poll `GET /v1/approvals/:id` (every 10 seconds at most) until `status` is `approved` or `denied`. Don't resend before that.
3. If approved, resend the exact same request (same path, query and body) with header `X-CLI-Approval: <approvalId>`. It works once. If denied, stop and ask the user what to do instead.

### Events

`GET /v1/projects/:id/events?after=<seq>` returns what happened since `seq` (deploy_queued, deploy_succeeded, deploy_failed, insufficient_funds, service_down, service_up, low_balance, cron_failed, approval_requested, approval_resolved, template_deployed) and `next` to pass as `after` next time. Optional `kinds=a,b`. `GET /v1/projects/:id/events/stream` is the same as server-sent events (resume with Last-Event-ID). Use it instead of polling many endpoints.

People can send these to Slack, Discord, Telegram or a webhook: `POST /v1/projects/:id/channels` (admins).

### API keys

Admins can create project API keys for agents and CI: `POST /v1/projects/:id/keys {"name","role":"agent","spendCap":<micro>|null,"expiresInDays":90}` returns a `clik_…` token once. Use it as `Authorization: Bearer clik_…`: it works for that one project only, with that role and cap. `POST /v1/projects/:id/keys/revoke-all` revokes every key and removes every agent member.

### Teams

Roles: **viewer** (read only), **developer** (deploy, configure, databases, domains, backups, cron), **admin** (also members, project settings and deleting data), **owner**. Agents added with a spend cap are developers capped by spend. `POST /v1/projects/:id/members {"email","role"}` invites someone; `PATCH`/`DELETE /v1/projects/:id/members/:principal` change or remove them. **FORBIDDEN** with `details.required` means your role is too low: ask an admin. `GET /v1/projects/:id/audit` lists who changed what.

### Live logs

- `GET /v1/services/:id/logs?tail=200` returns recent lines from the running service (secrets masked). Use it to debug a healthy app that misbehaves. Add `q=<text or /regex/>` and/or `level=error|warn` to search the last 5000 lines.
- `GET /v1/services/:id/requests?hours=24` gives requests per hour, 4xx/5xx counts and p50/p95 latency (when the server has router metrics on). After deploying, compare error rates with the hours before.
- `GET /v1/services/:id/logs/stream` is a server-sent event stream (Authorization header required): one `data:` event per line.

### Keys, secrets and security

- API keys have **scopes**: `read`, `deploy`, `manage` and `secrets`. New keys get the first three; reading variable values, connection URLs, running SQL or `exec` need `secrets`, which a person must grant. A **FORBIDDEN** naming a scope or an IP address means the key can't do that: ask the user rather than looking for another way.
- Every read of secret values (`env/export`, `connection`) is recorded in the project's activity log.
- `cli up` uploads are scanned: **SECRETS_IN_UPLOAD** lists files and lines (never values). Move the values into variables and remove the files; only resend with `?allowSecrets=true` if the user says the finding is a false alarm.
- Public database ports close by themselves: `PATCH /v1/services/:id {"publicTcp": {"hours": 2, "allowFrom": "me"}}` opens one for your own IP only, TLS required (`sslmode=require`).
- **STEP_UP_REQUIRED** means the signed-in person has 2FA and this action needs them to confirm it in the dashboard. Tell them what you were doing; don't retry until they say they've confirmed.

### What changed, and how long it takes

- `GET /v1/deploys/:id/diff` lists what changed since the previous live deploy: code (with a GitHub compare link), settings, which variables were added, removed or changed (never their values) and cli.json. Read it before rolling back, and when a deploy breaks something that worked.
- Deploys still running carry `eta.expectedAt` from this service's recent deploys. Wait about that long before polling hard.

### When things break: fix-it PRs and the on-call agent

- **Calling AI models from an app?** Use CLI's AI gateway instead of asking the user for provider keys: `cli_ai` with `create_key` returns an AI key and the two variables to set (`OPENAI_BASE_URL`, `OPENAI_API_KEY`); any OpenAI SDK works and calls are paid from the project's credit. Suggest a monthly cap (`set_cap`).
- **A real domain?** `cli_domain` searches and buys one (a year from project credit) and points it at the service with no DNS steps. Buying spends real money and accepts the registrar's terms: show the user the price and ask before `buy` (only then pass `agreeToTerms`).
- **The app needs email or user sign-in?** Use CLI's instead of a third-party account: `cli_email` (a sending domain, a key, per-recipient pricing) and `cli_app_signin` (emailed codes or wallets; the app checks JWTs against the project's JWKS). For semantic search, `cli_vector` turns on pgvector and `/v1/ai/embeddings` makes the vectors.
- **A site that's just files** (Vite, Astro, Next export, Hugo, a landing page)? Make it a static site: `cli_static_site` with the build's output folder (`dist`, `build`, `out`), then deploy. No container runs; it's served with CDN cache headers and billed for bandwidth only. Set `spa` for single-page apps with client-side routing.
- **A small endpoint** (a webhook receiver, a proxy, a cron target)? `cli_function` deploys one file (Node: `export default async (request) => Response`; Python: `def handler(request)`) as an HTTPS endpoint that sleeps when idle. Bigger than one file: deploy it as an app.
- **A public app getting hammered, scraped or attacked?** `cli_edge` sets rate limits, connection caps, IP allow/deny lists and bot blocking at the router (start from the `standard` or `api` preset). `GET /v1/services/:id/edge` says what was blocked.
- **An API or database that only accepts allow-listed IPs?** `cli_static_ip` sends the app's outbound traffic from CLI's fixed addresses (it costs a little per hour: tell the user). Give the user the IPs it returns to allow-list.
- **Cutting the bill:** `cli_rightsize` reads a week of measured use and suggests sleeping idle apps, fewer copies, static sites and plan sizes, with the monthly saving of each. CLI bills measured use, so a smaller plan lowers the most a service can cost, not the bill; say so. Apply the low-risk changes with `apply`; ask before anything with `risk: "medium"`.
- **"How's my project?" or after any change:** `cli_doctor` lists what needs attention, worst first, each with a fix. Work through critical items first. When an item has `fix.request`, that call fixes it (ask first if it costs money or changes a live app); otherwise send the user to `fix.dashboardPath`.
- **Before creating a service from a repo:** `cli_detect` reads it and returns the framework, whether it's an app or a static site, the start command, port, root directory, the databases it needs and the variables in .env.example. Create the service with those settings, add the databases (CLI fills in their variables), ask the user for the other variables, then deploy. Don't guess what detect can tell you.
- **"Tell me if X happens":** `cli_log_alerts` watches an app's output for text (or a regex) and alerts through the project's channels. Preview a rule against recent output before relying on it.
- **Changing a database's schema:** `cli_db_tools` `migrate` backs up first and runs the SQL in one transaction, with a history. Show the user the SQL and get a yes first; read `schema` before writing a migration.
- **An outage or planned work people should know about:** `cli_status_notice` posts to the public status page and updates it as things change. Resolve it when it's over.
- **"Can I make money from this?":** any app can charge per call: `cli_sell` `set_prices`, then `list` to be found in the directory (agree prices with the user first). `cli_paid_apis` shows what a project already sells and what CLI itself offers.
- **"Just show me something working":** deploy a starter (`cli_deploy_template` with `starter-nextjs-postgres`, `starter-fastapi`, `starter-discord-bot` or `starter-cron-worker`). They need no repository; the Discord bot needs the user's bot token and application id.
- **About to send real users to an app?** `cli_go_live` lists what's missing (live version, own domain with HTTPS, backups, alerts, browser check, edge protection, leaked secrets, budget), each with its fix. Fix the required items before saying it's ready.
- **"Why did that request fail?"** `cli_requests` shows recent requests as the router saw them (filter by path, `5xx`, or slower than N ms). `replay` resends a GET, HEAD or OPTIONS one so you can check a fix.
- **"Why does staging work but production doesn't?"** `cli_compare_environments` `compare` lists every difference (variables by name, plans, copies, versions). `copy` moves named variables across; they apply on the next deploy.
- **Pricing a paid API:** `cli_unit_economics` `pricing` suggests a price per call from its cost and similar APIs; `costs` shows cost per request and margin per paying caller. Agree the price with the user before `cli_sell`.
- **New to a project?** `cli_project_map` gives its services, what connects to what, what's public and what each costs, in plain sentences.
- **What needs the person:** `GET /v1/me/needs-you` lists everything waiting on a person across their projects (failed deploys, fixes to accept, low credit, promises slipping, domains not connected, changes and bounties to review), worst first, each with a plain title. Check it when they ask "is everything OK?". `GET /v1/projects/:id/overview` and `GET /v1/services/:id/overview` give a one-sentence status.
- **Security fixes for packages (Drop 55):** for an app deployed from GitHub, `cli_dependencies` `get` lists packages with known security problems at the live commit and the version that fixes each. `fix` opens a pull request with the upgrades and builds it in a throwaway copy; when `open.status` is `ready`, tell the person and `accept` only once they agree (it merges and deploys). With `settings` mode `propose`, CLI opens these itself once a day.
- **Real visitor speed:** `PUT /v1/services/:id/visitor-speed {enabled: true}` returns a script tag for the app's pages; `GET /v1/services/:id/visitor-speed` then shows what visitors waited for (main content, taps, layout jumps) by device, country and page. A promise can use it: `{visitorLoadMs: 2500}` means 75% of visits show the page within 2.5 s.
- **Cloud access without stored keys:** don't ask for AWS, Google Cloud or Azure keys. `PUT /v1/services/:id/cloud-access {enabled: true}` (owner or admin), redeploy, and the app gets `CLI_OIDC_TOKEN_URL` and `CLI_OIDC_REQUEST_TOKEN`; `GET` returns the exact trust policy or setup steps for each cloud. The app fetches a short-lived token and swaps it for temporary cloud credentials.
- **Bounties (earn for your project):** `cli_bounties` `board` lists jobs with money attached. To attempt one, fork its `repo`, make the change, push, then `attempt` with your own `projectId`, the fork's https URL and the commit. It costs the `attemptFee`; CLI builds it in a copy without the owner's secrets and runs the check. Poll `status`: `failed` comes with the reason and the build log; `won` credits the reward to your project. Only attempt what you can test first, and tell the person before spending.
- **Building a webhook handler:** `cli_webhook_inbox` `create` gives a public URL to paste into Stripe, GitHub or anything else; `captures` shows exactly what arrived (headers and body) and `replay` sends one to the app as many times as you need.
- **Shipping something risky behind a switch:** `cli_flags` `set` turns a feature on, off or on for a percentage of users without a deploy. Apps read `CLI_FLAGS_URL?user=<id>` (`POST /v1/projects/:id/flags/install` adds the variable to every app).
- **Multi-step jobs that must finish** (checkout → fulfilment → email, onboarding sequences, anything with "wait until…")? Use `cli_workflow` instead of a queue and a cron: each step calls an app endpoint, retries with backoff and the same `Idempotency-Key` (make the endpoint ignore repeats), and the run resumes after restarts. `wait` steps pause until the app sends an event to the run.
- **Will it hold up?** Before a launch or after a big change, `cli_load_test` the app with thresholds (start low, use `rampSeconds`). Report the `breakingPoint` and p95 in plain words. It sends real traffic and costs a little: say so first, and never point it at anything but the user's own app.
- **Is the important flow actually working?** `cli_browser_check` runs sign-up, checkout or login in a real browser every few minutes. Add one for each flow that makes money; the user hears about failures with a screenshot.
- **Leaked keys:** when `secret_found` arrives (or `cli_secrets` shows open findings), tell the user which key and where. The fix is rotating it at the provider, then storing the new one as a secret variable; deleting the line is not enough. Mark a finding resolved only after rotating.
- **"What will this cost?"** `cli_forecast` gives the month-end estimate with a range, the trend per category and when credit runs out. Quote the range, not just the middle.
- **On-chain chores** (harvest, rebase, liquidations, oracle pushes) don't need an app: `cli_keeper` calls a function through a managed signer on a schedule or on an event. The signer's policy still applies; make it as narrow as the job. To keep a table of a contract's events, use `cli_watch_contract` with target `index`.
- **Known fixes first.** A failed deploy's `GET /v1/deploys/:id` may carry `knownFixes`: changes that fixed this same kind of failure in other projects (anonymized), best first, with how often each worked (`cli_known_fixes` for the full list). Try the top one before guessing, and tell the user which one you tried.
- **Risky change to a live app? Try it in the shadow.** `POST /v1/services/:id/shadow {"minutes": 30}` (`cli_shadow`) runs the new version on a copy of live read traffic; users only see the live version. When it's `finished`, read the `verdict`; promote only if it's `good` (or the user says so). Don't set `includeWrites` unless the user agrees: copied writes run twice against the same database.
- Every image CLI builds has a signed record of its commit (`GET /v1/deploys/:id/provenance`). When the user asks "what exactly is running?", answer from it.
- The user can take the whole project elsewhere: `GET /v1/projects/:id/export` (a person's download, it holds secrets). Never download it yourself unless asked; `cli_export_manifest` shows what it would hold.
- For a failed deploy of a GitHub service, `GET /v1/deploys/:id/fix-pr` says whether CLI can open a pull request with a fix, and `POST /v1/deploys/:id/fix-pr` opens it (CLI reads the error and the files it points at). Prefer this over pushing straight to the branch when the user wants review. It never touches CI files or lockfiles.
- CLI's on-call agent watches failed deploys and outages and proposes one action (rollback, restart, more memory, or a fix PR): `GET /v1/projects/:id/proposals?status=open`. `POST /v1/proposals/:id/apply` runs it, `…/dismiss` drops it. Read the reason and tell the user before applying.

### Database copies and point-in-time recovery

- `POST /v1/services/:id/branch {"scrub": "auto"}` makes a new database with a copy of the data and personal-data columns replaced (`GET /v1/services/:id/scrub-plan` shows which). Use a branch, never the production database, for experiments and migrations you aren't sure of. Poll `GET /v1/branches/:id` until `done`.
- Postgres can keep its history: `PUT /v1/services/:id/point-in-time {"enabled": true}`. Then `POST /v1/services/:id/restore-to {"at": "<ISO time>"}` creates a new database with the data as it was then; the original is untouched. Ask the user before turning it on (the database restarts briefly).

### Previews and budgets

- `PATCH /v1/services/:id {"previewAccess": "team"}` puts an app's PR previews behind CLI sign-in; `POST /v1/services/:previewId/share-links {"hours": 72}` makes a link for someone outside the team.
- `GET /v1/projects/:id/forecast` gives this month's spend, the burn rate and the projected total. **BUDGET_EXCEEDED** means a hard monthly budget was reached: tell the user, don't look for ways around it.

### Charging callers, canaries, workspaces and undo

- **Paid routes:** `PUT /v1/services/:id/paywall {"rules": [{"path": "/api/*", "price": 10000}]}` makes callers pay that many micro-USDC per request over x402 (they get a 402 with the price first). The project is credited, less CLI's fee. `GET …/paywall` shows earnings. The app sees the payer in `X-CLI-Paid-By`.
- **Canaries:** `PATCH /v1/services/:id {"canary": {"percent": 10, "minutes": 10}}`. New versions then stay `deploying` with `canary.state: "watching"` while they get that share of traffic; they're promoted or rolled back (**CANARY_FAILED**, with the numbers) on their own. `POST /v1/deploys/:id/canary {"action": "promote"|"rollback"}` decides early.
- **Work in a workspace, not production:** `POST /v1/projects/:id/workspaces {"purpose": "…", "hours": 24, "spendCap": 5000000}` returns a token that only works in a fresh copy of the project (databases scrubbed). Do risky work there; it deletes itself when the time is up.
- **Undo:** every change is journaled. `GET /v1/projects/:id/sessions` lists sessions by actor; an admin can `POST /v1/projects/:id/sessions/undo {"actor", "from"}` (dry run first) to put everything back.

### On-chain apps

- RPC with failover: `POST /v1/projects/:id/rpc/<chainId>` (JSON-RPC; reads and `eth_sendRawTransaction` only). `GET /v1/chains` lists chains.
- Managed signers: an admin creates one with a policy (chains, contracts, selectors, value per tx and per day, rate). Apps use its token: `POST /v1/signers/:id/send {"tx": {"to", "data", "chainId"}}` fills nonce, gas and fees, signs and broadcasts. **SIGNER_POLICY** says which rule refused it; never try to work around it.
- Watchers: `POST /v1/services/:id/watchers {"chainId", "kind": "event", "address", "path"}` (or `"kind": "block", "everyBlocks"`) POSTs signed JSON to the app.

### Shipping safely, scaling and regions

- **Release command:** `PATCH /v1/services/:id {"releaseCommand": "npm run migrate"}` runs it once in the new image before it takes traffic. A failure stops the deploy (**RELEASE_COMMAND_FAILED**) and the old version keeps running. Rehearse first: `POST /v1/services/:id/rehearse` runs it against a throwaway copy of the linked database; poll `GET /v1/rehearsals/:id` for `passed` or `failed` with output.
- **Smoke tests:** `PATCH … {"smokeTests": [{"path": "/api/products", "contains": "sku"}]}` (also `method`, `status`). A failing test stops the deploy (**SMOKE_TEST_FAILED**, naming the test).
- **Autoscaling:** `PATCH … {"autoscale": {"min": 1, "max": 6, "targetRps": 50}}`; null turns it off.
- **Regions and own servers:** `GET /v1/projects/:id/servers` lists them; `PATCH /v1/services/:id {"serverId": "srv_…"}` moves a service (it's rebuilt there). Adding a server is for admins.
- **Status page:** `PUT /v1/projects/:id/status-page {"enabled": true, "slug", "title", "services": [ids]}` publishes `/status/<slug>`.

### Debugging: ask, errors, traces

- **Ask first:** `POST /v1/services/:id/ask {"question": "why did checkout start failing?"}` reads recent output, deploys, error groups and slow routes and answers with `evidence` (real log lines only) and `next` steps. Cheaper than reading thousands of log lines yourself.
- Apps are deployed with `OTEL_EXPORTER_OTLP_*` set, so any OpenTelemetry SDK reports to CLI. `GET /v1/projects/:id/errors?status=open` lists exceptions grouped (type, message, top frame, count, traces); `PATCH /v1/errors/:id {"status": "resolved"}` after a fix: if it comes back, it reopens and raises an `error_new` event.
- `GET /v1/services/:id/traces?sort=slow` gives the slowest requests and p50/p95 per route; `GET /v1/projects/:id/traces/:traceId` gives every span with timings.
- PR previews get a comment comparing build time, start time, response time, vulnerabilities and cost with production.

### Local development

`cli dev <command>` runs a local command with the service's variables, opening its databases to this machine only (4 hours) and swapping their URLs in. `cli tunnel 3000` gives a local port a public https address (`POST /v1/projects/:id/tunnels` returns the token; connect to `wss://…/v1/tunnels/connect?token=`).

### Storage, queues and GPUs

- **Buckets:** `POST /v1/projects/:id/buckets {"name": "uploads", "link": {"serviceId"}}` gives the app `BUCKET_URL`, `BUCKET_TOKEN`. Apps `PUT`/`GET`/`DELETE` `$BUCKET_URL/<key>` with `Authorization: Bearer $BUCKET_TOKEN` (raw bytes, up to 100 MB; `GET $BUCKET_URL?prefix=` lists). `POST /v1/buckets/:id/sign {"key", "method": "GET"|"PUT", "seconds"}` makes a link for browsers. Use buckets for user files, never the container's disk.
- **Queues:** `POST /v1/projects/:id/queues {"name", "link": {"serviceIds": [...]}}` gives `QUEUE_URL`, `QUEUE_TOKEN`. Send `POST $QUEUE_URL/messages {"body": {...}}`; workers `POST $QUEUE_URL/receive {"max": 10, "waitSeconds": 20}` then `POST $QUEUE_URL/ack {"receipts": [...]}`. Unacked messages come back after the visibility window; after maxAttempts they go to `/dead` (`/redrive` retries them). With `"push": {"serviceId", "path"}` CLI POSTs each message to the app, signed in `X-CLI-Signature`.
- **GPUs:** `GET /v1/projects/:id/gpus` shows kinds, prices and free cards; `PATCH /v1/services/:id {"gpu": {"kind": "L4", "count": 1}}` places the app on a server with free cards (**GPU_UNAVAILABLE** lists capacity when none fit). Add `"waitForGpu": true` to join the waitlist instead: the error then says your place in line (projects whose staking tier gives GPU priority go first); when cards free up they're held for you for 15 minutes and a `gpu_available` event fires: send the same request again to take them. Billed per second while running; `{"gpu": null}` removes them.

### Secrets that look after themselves

- **Sync:** `POST /v1/projects/:id/secret-syncs {"provider": "doppler"|"vault"|"http", "token", "url", "path", "serviceId" (or null for shared), "autoDeploy"}` pulls every five minutes. It only changes keys it wrote. Ask the user for the token; never invent one.
- **Rotation:** `POST /v1/services/:id/rotations {"key": "SESSION_SECRET", "everyDays": 30}` (on a database: no key; it changes the password in place and redeploys the apps using it). The old app value stays as `KEY_PREVIOUS` for the grace period, so verify against both. `POST /v1/rotations/:id/rotate` rotates now.

### Trust: receipts, reputation, streams

- **Receipts:** `PUT /v1/projects/:id/receipts {"enabled": true}` seals the audit log every few hours and writes its Merkle root on chain. `GET …/receipts/proof/:entryId` gives a proof; `POST /v1/receipts/verify` checks one (no sign-in).
- **Reputation:** `GET /v1/projects/:id/agents` scores every agent from deploys, undos and denied approvals. Owners can let agents above a score skip spending and production approvals (`PUT …/trust {"aboveScore": 90}`); destructive actions always ask. Your record follows from what you do: deploys that fail and changes people undo lower it.
- **Your credential (portable identity):** with an API key, `POST /v1/agents/me/credential {"audience"?, "ttlHours"?}` (`cli_agent_credential`) returns a signed JWT of your record here: score, deploys live and failed, changes undone, approvals. Give it to another service or person; they check it with `POST /v1/credentials/verify` or offline against `/.well-known/jwks.json`. To make the record follow your wallet across projects, bind it first: `GET /v1/agents/me/wallet/challenge?address=0x…`, sign the message (personal_sign), `POST /v1/agents/me/wallet {"address","message","signature"}`. Never hand out your API key in its place.
- **Payment streams:** to call a paid route many times, open a stream once: `POST /v1/services/:id/streams {"amount", "fromProject"}` (from your CLI balance) or with an x402 payment. Then send `X-CLI-Stream: <token>` instead of paying per request. **STREAM_EMPTY** means top it up (`POST /v1/streams/:id/topup`) or open another; `POST /v1/streams/:id/close` returns what's left.

### Your own cloud, and security rules

- A project can run on machines in its own cloud account (`POST /v1/projects/:id/servers {"connect": true, …}`); only a person sets that up. If the project keeps everything on its own servers, a service that would start on CLI's machines fails with **PLACEMENT_REQUIRED**: move it with the request in `error.details.fix`. Sandboxes aren't available in such projects.
- **MFA_REQUIRED** means the project requires a person with a second factor for that change. You can't satisfy it: tell the user. API keys aren't affected.

### If something is stopped or suspended

**SUSPENDED_BY_OPERATOR** means CLI's operators suspended the project; nothing deploys until it's lifted. `GET /v1/projects/:id/abuse` shows why. Services on new accounts can be stopped automatically for crypto mining, phishing pages or runaway outbound traffic. Tell the user what the flag says; only they (an admin) should appeal (`POST /v1/abuse/:id/appeal`), and never retry or redeploy around a flag.

### Selling and buying access

- **Subscriptions:** a service with paid routes can sell plans: `PUT /v1/services/:id/plans {"plans": [{"id": "pro", "name": "Pro", "price": 9000000, "period": "month", "includedRequests": 10000}]}`. The app reads `X-CLI-Plan` on admitted requests. To buy one for the user's project: `POST /v1/services/:id/subscribe {"plan", "fromProject"}` (renews monthly from that project) and send `X-CLI-Subscription` on requests. Subscriptions are recurring spending: confirm with the user first.
- **Earnings, withdrawals and splits are the owner's:** `GET /v1/projects/:id/earnings` shows them; withdrawing and changing revenue splits need the signed-in owner, never a key. Point the user at the dashboard instead of trying.
- **Credit without x402:** `GET /v1/projects/:id/deposit-address` (send USDC there) and `POST /v1/projects/:id/onramp {"usd": 50}` (a card payment link for the user to open), or `cli_funding_options` for both. Give the user the link; never open it or pay by card yourself.

### Working well with people and other agents

- **Check your limits first:** `GET /v1/me/wallet` shows your spend cap, what's left, your scopes and which services you may change. A 403 saying the key "can only work on" some services means stop and ask.
- **Propose risky changes instead of making them:** `POST /v1/projects/:id/changes {"serviceId", "title", "commit"?, "settings"?, "env"?}`. CLI builds it in a copy, summarizes it with a risk level, and a person approves. Use it for production changes you aren't sure about, or whenever the project asks for approvals. You can't approve your own change.
- **Need an API?** Search `GET /v1/directory?q=…` before building one: entries show price per call, uptime and how to pay (x402 per call, a stream for many calls, or a plan).
- **Moving a project here:** read the repo's railway.json / Procfile / render.yaml / fly.toml / vercel.json / docker-compose.yml and send them to `POST /v1/projects/:id/import {"provider", "files"}`. Config files miss most variables and extra services; to bring everything, ask the user for a Railway token (a read-only project token is enough) and the project id, or a Heroku API token and app name, and send `{"provider": "railway", "railway": {"token", "projectId"}}` or `{"provider": "heroku", "heroku": {"token", "app"}}` instead. CLI uses the token once to read the old project and never stores it; don't save it anywhere yourself either. Database references (`${{Postgres.DATABASE_URL}}`) become links to new CLI databases, but the data isn't copied: tell the user. Show the user the plan, then repeat with `"apply": true`.
- **Apps that pay for APIs:** when an app you build calls an API that charges per request (x402, or a paid route on another CLI app), don't put a wallet or key in the app. Ask the user to turn on outbound payments for that service with caps (`PUT /v1/services/:id/outbound {"enabled": true, "perCallMax", "dailyCap"}`; only a person can). After the next deploy the app has `CLI_PAY_URL` and `CLI_PAY_TOKEN`: it sends `POST $CLI_PAY_URL` with `Authorization: Bearer $CLI_PAY_TOKEN` and `{"url", "method", "headers", "body", "maxPrice"}`, and gets back `{"status", "headers", "body", "bodyEncoding", "paid"}`. CLI pays from the project's balance; going over a cap is **SPEND_CAP_EXCEEDED**.
- **Sandboxes:** to run code (test a snippet, transform a file, try a package) without deploying anything, start a sandbox: `cli_sandbox_create` (python, node, ubuntu, go, rust or any image; no network unless `network: true`), then `cli_sandbox_exec` and the file tools. It's billed per second while it exists: delete it when done (idle ones go after 10 minutes, all after an hour).
- **Selling tools to other agents (MCP):** an app that serves MCP over HTTP can charge per tool call: `PUT /v1/services/:id/mcp {"enabled": true, "path": "/mcp", "prices": {"tool_name": 20000}, "defaultPrice": 0}` (admins). Callers connect to the gateway URL it returns, not the app; `tools/call` answers 402 with an x402 challenge (or takes `X-CLI-Stream`). The app must reject MCP requests whose `X-CLI-MCP-Gateway` header isn't `CLI_MCP_SECRET`. Paid MCP servers show up in `cli_find_api` with their tools' prices.
- **Databases that survive a failure:** `PUT /v1/services/:id/ha {"standbys": 1, "readReplicas": 0}` (admins) adds a standby that takes over automatically if the primary stops answering; `DATABASE_URL` keeps working. Read replicas serve `${{db.READ_URL}}`. Each member costs a full plan: ask the user first. `GET /v1/services/:id/ha` shows members and lag; **database_failover** events say when it switched.
- **Hosted agents:** people can have agents run on CLI on a schedule or when something happens (`GET /v1/projects/:id/hosted-agents` lists them; only a person can create or change one). If the user wants something checked or fixed regularly while they're away, suggest one instead of asking them to keep you running. If you are a hosted agent, nobody is watching: never wait for an answer, finish with a report.
- **Refunds for failed calls:** a seller can promise refunds: `PUT /v1/services/:id/guarantee {"enabled": true}` (admins). Each paid call then carries `X-CLI-Receipt` to the app; calls that fail (a 5xx, an MCP error, no answer) are refunded on their own (the buyer gets the full price back to their stream or wallet). The app can refund a call itself: `POST $CLI_REFUND_URL {"receipt", "reason"}` with `Authorization: Bearer $CLI_REFUND_TOKEN`. When buying, prefer directory entries with `guarantee.enabled` and a low `refundRate30`.
- **Watching a long sandbox command:** `GET /v1/sandboxes/:id/runs/:runId/output?out=0&err=0` returns what it has printed so far and the offsets to ask from next (or follow `/stream`, server-sent events).
- **Templates:** `GET /v1/templates/community` lists stacks others published; paid ones charge per deploy (confirm the price with the user).

### The CLI token (Robinhood Chain)

- CLI also takes its own token, **CLI**, on Robinhood Chain. It's optional: USDC and cards work exactly as before, and nothing is gated behind holding it. `GET /v1/token` (`cli_token` action `info`) gives the price, the bonus for paying in CLI, the staking tiers and locks, and the contract addresses. If it says `enabled: false`, this server doesn't take CLI.
- **Buying credit with CLI:** `POST /v1/token/quote {"projectId", "tokens": "1000"}` (or `"usd": 20`, and `"from": "<wallet>"` to skip an approval that isn't needed) returns the credit, a `minCreditOut` that protects against the price moving, and `transactions` to send in order from the wallet holding the CLI. The price is a 30-minute average from an oracle, not the pool's spot price. The credit lands on the project a few blocks after the purchase is mined (a `payment_received` event). Credit goes to exactly the project named: check the id. It's spending: confirm the amount with the user first.
- **Staking:** `POST /v1/token/stake-tx {"action": "stake", "amount", "lockId", "projectId"}` returns the transactions; `"unstake"` and `"setProject"` (with `positionId`) too. Staked CLI earns hosting credit for its project by the second (paid out every 15 minutes): the stake's dollar value × the tier's yearly rate (by how much the wallet has staked in total) × the lock's multiplier. `GET /v1/token/stakes/:address` shows positions, tier, credit per day and credit paid. Locked tokens can't be withdrawn early. Never stake on the user's behalf without them asking: it locks their tokens.
- **Tier perks:** staking for a project also lowers its fee on sales, puts its builds first when build slots are busy, and (higher tiers) puts it first in the GPU waitlist: `GET /v1/projects/:id/benefits`.
- CLI is not a way around limits: credit bought with it is ordinary credit, subject to the same budgets, caps and approvals.

### Log drains

`POST /v1/projects/:id/drains {"target": {"kind": "datadog", "apiKey": "…"}}` (or `axiom` with token and dataset, `betterstack` with token, `http` with url) ships every running service's output, masked. `POST …/drains/:drain/test` sends a test line. Ask the user for the key; never invent one.

### Deleting

`DELETE /v1/services/:id` stops a service and moves it to the trash for 7 days; its domains stay reserved. A database keeps its data unless `?deleteData=true` (owner only), and even then the data is only removed when the 7 days are up. `GET /v1/projects/:id/trash` lists deleted services and `POST /v1/services/:id/restore` brings one back, redeploying the version that was live. `?permanent=true` skips the trash. Always confirm with the user before deleting.

## 4. Guardrails (mandatory)

- Say why. Every change carries a one-sentence reason: the `why` argument of each MCP tool, or the `X-CLI-Intent` header on the API. The person sees it beside the change in their flight recorder, with its cost and an undo button. Write it for them ("Raise memory: the worker was killed for running out at 512 MB"), not for yourself.
- If a sandbox command comes back CONFLICT because a person has taken over, stop using that sandbox and wait: they're working in it (`GET /v1/sandboxes/:id/runs` shows what they did).
- Before changing something, look at `GET /v1/projects/:id/flight` (`cli_recent_changes`): if a person just changed it, ask before changing it back. `POST /v1/flight/:changeId/undo` (`cli_undo`) takes back one of your own mistakes.
- At most **3 automatic fix attempts** per failing service before asking the user.
- Stop and ask the user if the same error code repeats twice in a row with the same evidence.
- Never invent secret values. Ask the user for API keys and passwords. The only generated credentials are CLI databases, set with the link endpoint.
- Never print secret values back to the user or into logs.
- Do not spend more than the user authorised. Escalate on SPEND_CAP_EXCEEDED (your own cap, or the project's daily limit for agents: `GET /v1/projects/:id/rules` says what the owner allows).
- A failed deploy never takes down the running version, so failing is safe; looping is not.

## 5. Report back

After success tell the user: the URL, what you changed to make it work, and the current balance. After giving up, tell them the error code, the evidence line, what you tried, and what you need from them.

## 6. Deploy failure playbook

### SMOKE_TEST_FAILED

The new version started but failed one of the service's smoke tests, so it never took traffic. (HTTP 409, phase: runtime)

1. error.detail.evidence names the request and what came back. Reproduce it against a preview or workspace.
2. Fix the app (or the test, if the expectation changed) and deploy again. The current version kept serving.

Retry: Retry only after you changed something.

### RELEASE_COMMAND_FAILED

The release command (usually migrations) exited with an error, so the new version wasn't started. (HTTP 409, phase: runtime)

1. error.detail.evidence has the last lines of its output. Rehearse it on a copy of the database: POST /v1/services/:id/rehearse.
2. Fix the command or the migration and deploy again. The current version kept serving.

Retry: Retry only after you changed something.

### CANARY_FAILED

The new version did worse than the one serving traffic while it was tried on a share of requests, so it was rolled back. (HTTP 409, phase: runtime)

1. error.details compares the canary's error rate and p95 latency with the stable version's. Check the runtime logs of this deploy for the failing requests.
2. Fix the cause and deploy again; the stable version kept serving the whole time.

Retry: Retry only after you changed something.

### STATIC_PUBLISH_FAILED

The build worked, but CLI couldn't publish its files as a static site. (HTTP 409, phase: build)

1. error.detail.summary says why: usually the output folder is wrong or has no index.html.
2. Set staticSite.outputDir to the folder your build writes (dist, build, out, public) with PUT /v1/services/:id/static-site, then deploy again. The previous version kept serving.

Retry: Retry only after you changed something.

### SHADOW_FAILED

The version tried in the shadow didn't start for real traffic when promoted. (HTTP 409, phase: runtime)

1. The live version kept serving. Check this deploy's runtime logs, fix the cause and try again.

Retry: Retry only after you changed something.

### SOURCE_ACCESS_DENIED

CLI could not get access to the source repository. (HTTP 422, phase: build)

1. Make sure the CLI GitHub App is still installed on the repo and has access to it (GET /v1/github/install-url).
2. Redeploy.

Retry: Retry only after you changed something.

### IMAGE_PULL_FAILED

CLI couldn't pull the container image. (HTTP 422, phase: build)

1. Check the image name and tag exist (try `docker pull <image>` locally).
2. For a private image, set registry credentials: PATCH /v1/services/:id {"registry":{"server":"ghcr.io","username":"…","password":"<token>"}}. GHCR tokens need read:packages.
3. Redeploy.

Retry: Retry only after you changed something.

### BUILD_NO_BUILDER

The builder could not detect how to build this source. (HTTP 422, phase: build)

1. Add a Dockerfile, or a recognised manifest at the repo root (package.json, requirements.txt, pyproject.toml, go.mod, Cargo.toml).
2. Commit it and redeploy.

Retry: Retry only after you changed something.

### BUILD_DEP_INSTALL

Dependency installation failed. (HTTP 422, phase: build)

1. Read error.detail.evidence for the failing package.
2. Fix the version or name, regenerate and commit the lockfile, redeploy.

Retry: Retry only after you changed something.

### BUILD_COMPILE

The code failed to compile or type-check. (HTTP 422, phase: build)

1. Fix the error at the file and line in error.detail.evidence, commit, redeploy.

Retry: Retry only after you changed something.

### BUILD_TIMEOUT

The build took longer than the time limit. (HTTP 422, phase: build)

1. Speed up the build: cache dependencies, skip unneeded steps, or build a smaller image.
2. Or deploy a prebuilt image instead (source type image).

Retry: Retry only after you changed something.

### BUILD_OOM

The build ran out of memory. (HTTP 422, phase: build)

1. Reduce build parallelism (for example NODE_OPTIONS=--max-old-space-size or fewer workers), or move the service to a larger plan.

Retry: Retry only after you changed something.

### MISSING_ENV

The app needs an environment variable that is not set. (HTTP 422, phase: runtime)

1. Set the variable named in error.detail.variable with PUT /v1/services/:id/env.
2. Ask the user for the value if you do not know it. Never invent secrets.
3. Redeploy.

Retry: Retry only after you changed something.

### PORT_MISMATCH

The app is not listening on the port CLI routes to, or only on localhost. (HTTP 422, phase: runtime)

1. Make the app listen on process.env.PORT (or the PORT variable for your language) and host 0.0.0.0.
2. Redeploy.

Retry: Retry only after you changed something.

### HEALTHCHECK_TIMEOUT

The app started but never answered the health check. (HTTP 422, phase: runtime)

1. Read the runtime logs for slow startup.
2. Make GET / (or the service healthcheckPath) return 2xx quickly, or set healthcheckPath to a route that does.

Retry: Retry only after you changed something.

### RUNTIME_CRASH

The process exited during startup. (HTTP 422, phase: runtime)

1. Read the stack trace in error.detail.evidence and the runtime logs, fix the cause, redeploy.

Retry: Retry only after you changed something.

### RUNTIME_OOM

The app was killed for using more memory than its plan allows. (HTTP 422, phase: runtime)

1. Move the service to a plan with more memory, or reduce memory use, then redeploy.

Retry: Retry only after you changed something.

### CONFIG_INVALID

The cli.json in the repo isn't valid. (HTTP 422, phase: build)

1. error.detail.problems lists each problem with the field it's in. Fix cli.json and push again.
2. Allowed keys: build.command, build.dockerfile, deploy.startCommand, deploy.healthcheckPath, deploy.port, deploy.replicas, deploy.sleepAfterMinutes, watchPaths, cron[]. Remove the file to use dashboard settings.

Retry: Retry only after you changed something.

### VARIABLE_REFERENCE_MISSING

A variable references a service or variable that doesn't exist. (HTTP 422, phase: build)

1. error.detail.missing lists each ${{service.KEY}} that didn't resolve. Check the service name (GET /v1/projects/:id) and the key.
2. Shared values are ${{shared.KEY}}: set them with PUT /v1/projects/:id/variables.
3. Fix the variable with PUT /v1/services/:id/env, then deploy again.

Retry: Retry only after you changed something.

### PLATFORM_ERROR

CLI infrastructure failed. Not your fault. (HTTP 503, phase: any)

1. Retry with exponential backoff, at most 3 times. Escalate to the user if it persists.

Retry: Retry with backoff (max 3).

### UNKNOWN

The failure did not match a known pattern. (HTTP 422, phase: any)

1. Read GET /v1/deploys/:id/logs in full and attempt a fix.
2. After 2 failed attempts, stop and report the logs to the user.

Retry: Retry only after you changed something.

## 7. Payment and limit errors

### PAYMENT_REQUIRED

This request needs an x402 payment. (HTTP 402, phase: api)

1. Pick an option from accepts[] in the response body (also base64 JSON in the PAYMENT-REQUIRED header).
2. Sign an EIP-3009 transferWithAuthorization for it and resend the same request with the PAYMENT-SIGNATURE header.

Retry: Retry only after you changed something.

### INSUFFICIENT_FUNDS

Project balance does not cover one hour of the requested plan. (HTTP 402, phase: preflight)

1. Top up via x402: POST /v1/projects/:id/topup (pay the 402), or ask the user to fund the project.
2. Then retry the original request.

Retry: Retry after topping up.

### PAYMENT_INVALID

The x402 payment payload failed verification. (HTTP 402, phase: api)

1. Re-sign the payment against the exact requirements in the latest 402 response (amount, payTo, asset, network).

Retry: Retry only after you changed something.

### PAYMENT_REPLAYED

This payment authorization was already used. (HTTP 409, phase: api)

1. Sign a new authorization with a fresh random nonce.

Retry: Retry only after you changed something.

### PAYMENT_SETTLEMENT_FAILED

The facilitator could not settle the payment on-chain. (HTTP 502, phase: api)

1. Check your wallet has enough USDC on the required network, then retry once.

Retry: Retry with backoff (max 3).

### SPEND_CAP_EXCEEDED

This agent wallet has reached the spend cap set by the project owner. (HTTP 403, phase: preflight)

1. Stop and ask the user (project owner) to raise your spend cap. Do not retry.

Retry: Do not retry. Escalate to the user.

### ACCOUNT_REVIEW

This project is on hold while CLI reviews unusual activity. (HTTP 403, phase: preflight)

1. Stop and tell the user. They need to contact CLI support to lift the hold. Do not retry.

Retry: Do not retry. Escalate to the user.

### PROJECT_SUSPENDED

The project ran out of credit and its services were stopped. (HTTP 402, phase: preflight)

1. Top up via x402. Services restart automatically when the balance is positive.

Retry: Retry after topping up.

## 8. Other API errors

### VALIDATION

The request body or parameters are invalid. (HTTP 400, phase: api)

1. Read error.details for the failing fields and resend a corrected request.

Retry: Retry only after you changed something.

### UNAUTHORIZED

Missing, invalid or expired session token. (HTTP 401, phase: api)

1. Sign in again: POST /v1/auth/challenge, sign the message with your wallet, POST /v1/auth/verify.

Retry: Retry only after you changed something.

### AUTH_INVALID_SIGNATURE

The signature does not match the address in the challenge. (HTTP 401, phase: api)

1. Sign the exact message returned by /v1/auth/challenge with the same wallet, using personal_sign (EIP-191).

Retry: Retry only after you changed something.

### AUTH_NONCE_INVALID

The challenge nonce is unknown, already used or expired. (HTTP 401, phase: api)

1. Request a fresh challenge and sign it within 5 minutes. Each nonce works once.

Retry: Retry only after you changed something.

### AUTH_CODE_INVALID

The email sign-in code or link is wrong, used or expired. (HTTP 401, phase: api)

1. Check the code in the most recent email, or request a new one with POST /v1/auth/email/start.

Retry: Retry only after you changed something.

### FORBIDDEN

Your wallet is not allowed to do this on this project. (HTTP 403, phase: api)

1. Ask the project owner to add your wallet as a member, or use the owner wallet.

Retry: Do not retry. Escalate to the user.

### NOT_FOUND

The resource does not exist or you cannot see it. (HTTP 404, phase: api)

1. Check the id. List resources with GET /v1/projects/:id.

Retry: Do not retry. Escalate to the user.

### CONFLICT

The resource is in a state that does not allow this action. (HTTP 409, phase: api)

1. Read the current state with a GET and retry only if the action is still valid.

Retry: Retry only after you changed something.

### DOMAIN_TAKEN

That domain is already attached to a service. (HTTP 409, phase: api)

1. Remove it from the other service first, or use a different hostname.

Retry: Do not retry. Escalate to the user.

### DOMAIN_NOT_VERIFIED

The DNS records for this domain aren't in place yet. (HTTP 409, phase: api)

1. Add the records listed in error.details.records at your DNS provider.
2. DNS can take a few minutes to update. Then verify again.

Retry: Retry only after you changed something.

### RATE_LIMITED

Too many requests: for this project, this key or this address. (HTTP 429, phase: api)

1. Wait for the period in error.details.retryAfterSeconds before retrying. Do not loop.

Retry: Retry with backoff (max 3).

### APPROVAL_REQUIRED

This project needs a person to approve this action first. (HTTP 403, phase: api)

1. Tell the user what you want to do and that it's waiting for approval at error.details.approveUrl.
2. Poll GET /v1/approvals/:id (error.details.approvalId) until status is approved or denied. Don't resend before then.
3. Once approved, resend the exact same request with the header X-CLI-Approval: <approvalId>. Each approval works once.

Retry: Wait until a person approves it, then resend with the X-CLI-Approval header.

### APPROVAL_INVALID

The approval in X-CLI-Approval doesn't match this request, was denied, used or has expired. (HTTP 409, phase: api)

1. Check GET /v1/approvals/:id. An approval covers one exact request (same route and body) by the same agent.
2. If it expired or was used, resend the request without the header to ask again.

Retry: Retry only after you changed something.

### STEP_UP_REQUIRED

This action needs the person to confirm it's them (2FA or passkey) in the last 10 minutes. (HTTP 403, phase: api)

1. Agents: ask the user to approve this in the dashboard. Sensitive actions by people with 2FA need a fresh second factor.
2. People: POST /v1/auth/step-up with a 2FA code, a recovery code or a passkey response, then resend the request.

Retry: undefined

### SIGNER_POLICY

The managed signer's policy doesn't allow this transaction. (HTTP 403, phase: api)

1. error.message says which rule (chain, contract, function, value per transaction or per day, rate). Nothing was signed.
2. If the transaction is right, ask a project admin to change the signer's policy: PATCH /v1/signers/:id.

Retry: Retry only after you changed something.

### EMAIL_DOMAIN_UNVERIFIED

The from address isn't on one of this project's verified sending domains. (HTTP 403, phase: api)

1. Add the domain (POST /v1/projects/:id/email/domains), set the DNS records it lists (CLI writes them itself for domains bought through CLI), then verify it (POST /v1/projects/:id/email/domains/:domainId/verify).
2. Send from an address on that domain.

Retry: Retry only after you changed something.

### EDGE_BLOCKED

The app's edge rules blocked this request. (HTTP 403, phase: api)

1. The app's owner set rules for who may reach it (GET /v1/services/:id/edge). Ask them if you should have access.

Retry: Do not retry. Escalate to the user.

### AI_CAP_REACHED

This AI call would take the project's AI spending past its monthly cap. (HTTP 402, phase: api)

1. error.details has the cap, what's been spent this month and what the call could cost.
2. A project admin can raise or remove the cap (PUT /v1/projects/:id/ai/cap), or wait for next month. Smaller max_tokens lowers the worst case.

Retry: Retry only after you changed something.

### SHADOW_NEEDS_LIVE

Shadow traffic copies requests from the live version, and this service has no live version. (HTTP 409, phase: api)

1. Deploy normally first (POST /v1/services/:id/deploys); once it's live, try the next version in its shadow.

Retry: Retry only after you changed something.

### OPERATOR_APPROVAL_REQUIRED

This operator action needs a second operator's approval (the two-person rule). (HTTP 403, phase: api)

1. Ask another operator who covers this area to approve it on the Operations page (error.details.approvalId).
2. Then send the same request again with the header X-CLI-Operator-Approval: <approvalId>. It works once, within an hour.

Retry: Wait until a person approves it, then resend with the X-CLI-Approval header.

### PAUSED_BY_OPERATOR

CLI's operators have paused this for everyone while they deal with a security problem. (HTTP 503, phase: api)

1. Nothing is wrong with your project. Running apps keep running.
2. Try again later; https://clicloud.app/status says when it's back.

Retry: Retry with backoff (max 3).

### SUSPENDED_BY_OPERATOR

This project is suspended by the CLI operators. (HTTP 403, phase: api)

1. GET /v1/projects/:id/abuse shows why. An admin can appeal: POST /v1/abuse/:id/appeal with a message.
2. Nothing can be deployed until the suspension is lifted.

Retry: Do not retry. Escalate to the user.

### IDENTITY_REQUIRED

This withdrawal takes the project past the amount that needs a verified identity. (HTTP 403, phase: api)

1. Only the person withdrawing can do this: they start a check with POST /v1/me/identity and open the returned url (Stripe asks for a document and a selfie).
2. Agents: tell the user; never try to verify for them. Once verified, withdraw again.

Retry: Retry only after you changed something.

### PLACEMENT_REQUIRED

This project keeps everything on its own servers, and this would run on CLI's machines. (HTTP 409, phase: api)

1. Place the service on one of the project's servers: error.details.fix has the request (PATCH /v1/services/:id {"serverId"}).
2. Sandboxes always run on CLI's machines; a person can turn off own-servers-only in placement (PUT /v1/projects/:id/placement) if that's acceptable.

Retry: Do not retry. Escalate to the user.

### GPU_UNAVAILABLE

No server has enough free GPUs of that kind right now. (HTTP 409, phase: api)

1. error.details.capacity lists every server's GPUs and how many are free. Ask for fewer, another kind, or try again later.
2. A project can add its own GPU server: POST /v1/projects/:id/servers with gpus.

Retry: Retry only after you changed something.

### UPSTREAM_FAILED

Something CLI depends on for this action (a database, a secrets manager, a chain) refused or failed. (HTTP 502, phase: api)

1. error.message says what answered and how. Nothing was changed.
2. Fix the cause it names (a token, a permission) and try again.

Retry: Retry only after you changed something.

### STREAM_EMPTY

The payment stream doesn't have enough left for this request, or is closed. (HTTP 402, phase: api)

1. Top it up (POST /v1/streams/:id/topup) or open a new one (POST /v1/services/:id/streams).

Retry: Retry after topping up.

### BUDGET_EXCEEDED

The project has used its monthly budget, which is set to stop spending. (HTTP 402, phase: api)

1. Tell the user. They can raise or remove the budget (PUT /v1/projects/:id/budget) or wait for the next month (error.details.resetsAt).
2. GET /v1/projects/:id/forecast shows what was spent and how fast.

Retry: Retry only after you changed something.

### CSRF_INVALID

A browser request signed in with a cookie didn't carry the matching X-CLI-CSRF header. (HTTP 403, phase: api)

1. Send the value of the cli_csrf cookie in the X-CLI-CSRF header on every request that changes something.
2. API clients should use a bearer token instead of cookies.

Retry: Retry only after you changed something.

### MFA_REQUIRED

This needs a person with a second factor (an authenticator app or a passkey) set up. (HTTP 403, phase: api)

1. Tell the user: they set one up on their account page, then try again. The project (or the server, for operators) requires it.

Retry: Do not retry. Escalate to the user.

### MFA_CODE_INVALID

That second-factor code or passkey didn't check out. (HTTP 401, phase: api)

1. Use the current 6-digit code from the authenticator app, a recovery code, or try the passkey again.

Retry: Retry only after you changed something.

### MFA_LOCKED

Too many wrong second-factor attempts. (HTTP 429, phase: api)

1. Wait 15 minutes and try again.

Retry: Retry with backoff (max 3).

### SECRETS_IN_UPLOAD

The uploaded code contains secrets (an .env file, a private key or a live API key). (HTTP 422, phase: api)

1. error.details.findings lists each file and line. Move the values into the service's variables (PUT /v1/services/:id/env) and remove them from the code.
2. Add files like .env to .gitignore or .cliignore so cli up skips them.
3. If a finding is a false alarm, resend with ?allowSecrets=true (ask the user first).

Retry: Retry only after you changed something.

### FEATURE_DISABLED

This feature is not configured on this CLI server. (HTTP 501, phase: api)

1. Use another option (for example x402 instead of card), or ask the operator to enable it.

Retry: Do not retry. Escalate to the user.

### GITHUB_NOT_LINKED

This account has no linked GitHub account, or its GitHub authorization expired. (HTTP 409, phase: api)

1. Link GitHub: POST /v1/auth/github/link and open the returned url in a browser (the user must do this step).
2. Then install the CLI GitHub App on the repo: GET /v1/github/install-url.

Retry: Retry only after you changed something.

### GITHUB_REPO_NOT_ACCESSIBLE

The CLI GitHub App is not installed on this repository, or your GitHub account cannot see it. (HTTP 403, phase: api)

1. Install the CLI GitHub App on the repository (GET /v1/github/install-url), granting it access to this repo.
2. Check the owner/name spelling with GET /v1/github/repos.

Retry: Retry only after you changed something.

### WEBHOOK_SIGNATURE_INVALID

The webhook signature did not verify. (HTTP 401, phase: api)

1. Check the webhook secret configured on the sender matches the server's.

Retry: Do not retry. Escalate to the user.

## 9. Reference

- Error catalogue (JSON): `GET https://clicloud-production.up.railway.app/v1/errors`
- Deploy logs: `GET /v1/deploys/:id/logs`; live service logs: `GET /v1/services/:id/logs`
- Roll back: `POST /v1/deploys/:id/rollback` redeploys the previous healthy image.
- **Promises:** `GET /v1/services/:id/promise` shows an app's uptime, success and speed targets and how much room to miss is left. When one breaks and the app holds back deploys, `POST /v1/services/:id/deploys` answers 409 with `details.frozen: true`. Then roll back, or deploy with `{"fix": true}` if `details.canDeployFix` (the app has a canary or smoke tests). Don't use `override`: that's for an owner or admin, with their reason.
- Add another agent with a cap (owner only): `POST /v1/projects/:id/members {"wallet","spendCap"}`
