# OPG Docs

OPG is the app backend cluster control plane for One Person Group. The SDK targets application runtime usage. The CLI handles platform login, app authorization, validation, and Codex MCP integration. Capabilities are connected through the manifest, Developer Grant, and backend-controlled proxies.

## Quickstart

Install the SDK and CLI, initialize platform configuration, complete platform login and app-level authorization, then local projects and Codex can use OPG capabilities.

```sh
npm install opg-sdk
npm install -g @jamba/opg-cli@latest --registry=https://registry.npmjs.org/

opg init --base-url https://your-opg.example.com
opg login
opg app list
opg app create --name "Demo App" --slug demo
opg login --app demo
opg smoke
opg db smoke
opg codex install
```

Authorization result: `opg login` obtains a platform token for creating apps and reading operations data. `opg login --app demo` obtains an app Developer Grant for SDK, database, AI, uploads, video, and MCP. Do not commit `.opg/credentials.json` or real API keys.

## Configuration Sources

The SDK and CLI read configuration in an order that works for local development and CI without putting secrets in the manifest.

| Source | Purpose |
| --- | --- |
| `OPG_BASE_URL` | Gateway base URL, for example `https://your-opg.example.com`. |
| `OPG_APP_SLUG` | Current app slug, used to build `/:app/v1` app-scoped API paths. |
| `OPG_API_KEY` | Optional Developer Grant, usually `opg_dev_...`, suitable for CI and non-interactive environments. |
| `OPG_PLATFORM_TOKEN` | Platform admin JWT, only for global control-plane operations. |
| `.opg/opg.config.json` | Base URL, app, and profile maintained by `opg init` and `opg app use`. |
| `.opg/credentials.json` | Local credentials generated by `opg login` and `opg login --app`. |
| `.env.local` | Local fallback for base URL and app slug. |

## CLI

After installing `@jamba/opg-cli`, the command is `opg`. The CLI handles platform login, app creation and switching, app-level authorization, manifest/smoke validation, database workspace commands, platform control-plane commands, and Codex MCP installation.

```sh
opg init --base-url https://your-opg.example.com
opg login
opg app list
opg app create --name "Demo App" --slug demo
opg app use demo
opg login --app demo

opg manifest
opg smoke
opg db manifest
opg db smoke
opg db tables
opg db query --sql "SELECT * FROM app_demo__customers ORDER BY created_at DESC" --limit 20
opg db execute --sql "CREATE TABLE app_demo__customers (id uuid PRIMARY KEY DEFAULT gen_random_uuid())" --dry-run true

opg platform apps list
opg platform analytics overview --app-id <app-id> --days 30
opg platform ai-usage logs --app-id <app-id> --days 7
opg platform payments orders --app-id <app-id> --page 1
```

Local project: `init` writes `.opg/opg.config.json` and `.env.local`; `app create` creates an app and switches the current project to that app.

Browser authorization: `login` is platform authorization; `login --app demo` is app-level authorization for SDK, database, and MCP app-scoped tools.

Validation path: `smoke` and `db smoke` validate manifest, table listing, query, and dry-run DDL access.

## SDK Client

`opg-sdk` provides an app-scoped runtime client and a platform admin client. Application runtimes should prefer local configuration.

```ts
import {
  createOpgClientFromLocalConfig,
  createOpgPlatformClient,
} from "opg-sdk";

const opg = await createOpgClientFromLocalConfig();

const manifest = await opg.sdk.manifest();
const models = await opg.ai.models();
const usage = await opg.usage.aiLogs({ limit: 20 });

const platform = createOpgPlatformClient({
  baseUrl: process.env.OPG_BASE_URL!,
  platformToken: process.env.OPG_PLATFORM_TOKEN!,
});
```

## App Capabilities

These capabilities use `/:app/v1` app-scoped APIs. Frontends and user projects do not touch provider secrets directly.

- AI Gateway: `opg.ai.models()`, `opg.ai.chat()`, `opg.ai.responses()`, `opg.ai.embeddings()`, `opg.ai.image()`, `opg.ai.speech()`.
- Agent: `opg.agents.list()`, `opg.agents.meta(slug)`, `opg.agents.run(slug, input)`, `opg.agents.stream(...)`.
- Uploads: `opg.upload.presignedUrl()`, `imageBuffer()`, `fileBuffer()`. Large files should use presigned URLs.
- Video jobs: `opg.video.generateAsync()` creates a job, `queryTask()` checks it, and `wait(taskId)` polls until completion.
- Usage: `opg.usage.aiLogs()` reads AI usage logs for model, cost, points, and failure debugging.
- SDK contract: `opg.sdk.manifest()`, `openapi()`, `examples()`, and `smokeTest()` support code generation and environment validation.

```ts
const chat = await opg.ai.chat({
  model: "gpt-4.1-mini",
  messages: [{ role: "user", content: "Give me an onboarding checklist" }],
});

const task = await opg.video.generateAsync({
  model: "runninghub-video",
  prompt: "A clean product intro video for OPG",
});

const result = await opg.video.wait(String(task.task_id || task.id));
```

## Database Workspace

Database capability is an app-scoped workspace through a backend proxy, not a direct database client. The SDK does not expose `DATABASE_URL`.

| Capability | Constraint |
| --- | --- |
| Namespace | Only the current app prefix is allowed, for example `app_your_app__customers`. |
| query | Only `SELECT` / `WITH` statements are allowed, with row limits. |
| execute | Defaults to dry-run and transaction rollback; real apply requires `confirm=apply:<app-slug>`. |
| Audit | All database changes write audit events and must go through the backend proxy. |

```ts
const db = await opg.database.manifest();

const rows = await opg.database.query({
  sql: `SELECT * FROM ${db.namespace}customers LIMIT 20`,
});

await opg.database.execute({
  sql: `CREATE TABLE ${db.namespace}customers (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), email text NOT NULL)`,
  dryRun: true,
});
```

## Platform Control Plane

The platform control plane creates apps and manages runtime settings, storage, SMS, email, OAuth, AI providers, models, proxies, payments, and app operations data. It requires `OPG_PLATFORM_TOKEN`.

- Apps: `platform.apps.list()`, `create()`, `update()`, `stats()`.
- Runtime: `platform.runtimeSettings.get()` / `update()` manage CORS, domains, scheduling, and integration configuration.
- Providers: storage, SMTP, SMS, OAuth, payment, proxy, AI source/model all use the platform client.
- App Data: feedbacks, analytics, aiUsage, payments, email, site, redeem, admins.

```ts
const app = await platform.apps.create({
  name: "Demo App",
  slug: "demo",
});

await platform.runtimeSettings.update({
  api_base_url: "https://opg.example.com",
  cors_origins: ["https://opg.example.com"],
});

const aiLogs = await platform.apps.aiUsage.logs(String(app.id), { days: 7 });
```

## Codex MCP

`opg codex install` generates local MCP configuration. The MCP server runs through `opg mcp` over stdio and exposes OPG tools to coding agents: manifest lookup, AI calls, Agent runs, video job submission, usage inspection, and database dry-run operations.

| Group | Tools |
| --- | --- |
| Read-only | `opg_database_manifest_get`, `opg_database_query`, `opg_platform_apps_list`. |
| Execution | `opg_database_execute`, `opg_platform_app_create`, `opg_platform_app_feedbacks_list`. |
| Platform | `opg_platform_app_analytics_users`, `opg_platform_app_ai_usage_logs`, `opg_platform_app_payment_orders`. |
| Cost risk | AI, video, and Agent execution may consume tokens, points, or provider quota; database execute defaults to dry-run. |

```json
{
  "mcpServers": {
    "opg": {
      "command": "opg",
      "args": ["mcp"],
      "env": {
        "OPG_BASE_URL": "https://your-opg.example.com",
        "OPG_APP_SLUG": "demo",
        "OPG_PLATFORM_TOKEN": "${OPG_PLATFORM_TOKEN}"
      }
    }
  }
}
```

## Backend Contract

SDK, CLI, and MCP depend only on the stable contract exposed by `/sdk/manifest`. Add new capabilities to the manifest first, then SDK and MCP.

- `GET /:app/v1/sdk/manifest`
- `GET /:app/v1/sdk/openapi.json`
- `GET /:app/v1/sdk/examples?target=node|react|codex`
- `POST /:app/v1/sdk/smoke-test`
- `POST /:app/v1/sdk/install-profile`
- `POST /:app/v1/sdk/auth/sessions`
- `POST /:app/v1/sdk/auth/token`
- `GET /:app/v1/sdk/database/manifest`
- `GET /:app/v1/sdk/database/tables`
- `POST /:app/v1/sdk/database/query`
- `POST /:app/v1/sdk/database/execute`

## Security and Performance

- Secret boundary: Developer Grants are stored as hashes and plaintext is returned only once. Real keys do not enter manifest, web pages, or generated config.
- Database protection: SQL is restricted by namespace, statement type, row limits, statement timeout, and dry-run behavior.
- Long jobs: AI, video, messages, webhooks, and bulk sync go through queues. HTTP requests create jobs and return task ids.
- Observability: AI requests, provider health, usage ledger, audit events, and request events are debugging truth.
- Caching: manifest can be short-cached for 30-300 seconds; secret state and audit results must not be publicly cached.
- Uploads: large files use object storage presigned URLs; do not put video or large base64 files in JSON.

## AI Reading Paths

- `https://opg.ceo/llms.txt`
- `https://opg.ceo/llms-full.txt`
- `https://opg.ceo/docs.md`
- `https://opg.ceo/en/docs.md`
