# RTIE — AI coding context file

RTIE (Real Time Intelligence Engine) is a multi-tenant, AI-native realtime runtime.
Developers build realtime products on RTIE with module APIs, provider-neutral
runtime identity, private-preview MCP tooling, and AI agent skills.

## What RTIE is NOT

- Not a direct Supabase/Cloudflare/SpacetimeDB wrapper. When building on RTIE, you
  work with RTIE's abstraction layer. **Never call Supabase, Cloudflare, or SpacetimeDB
  APIs directly** from application code — use RTIE modules and the @rtie/sdk instead.
- Not a commerce platform. Commerce is a launch product category. The runtime is
  product-agnostic.

## Auth model

Credential surfaces:
- `rtie_live_*` or `rtie_test_*` — RTIE API key (get from cloud.rtie.ai → API Keys)
- Hosted auth JWT — Supabase Auth for RTIE Cloud and first-party products
- BYOA/OIDC adapter — Auth0, Firebase, Cognito, custom OIDC, or guest identity mapped to an RTIE actor
- RTIE module/session token — short-lived token from `/v1/runtime/connect`

```
Authorization: Bearer rtie_live_xxxx
```

API keys are tenant-scoped. Runtime users do not need Supabase Auth; your backend can mint scoped RTIE session tokens after verifying your own identity provider.

## MCP private preview

Public MCP tool calling at `mcp.rtie.ai` is in private preview while the T20 external MCP server ships.
The configuration shape is:

```json
{
  "mcpServers": {
    "rtie": {
      "type": "http",
      "url": "https://mcp.rtie.ai/mcp",
      "headers": { "Authorization": "Bearer ${RTIE_API_KEY}" }
    }
  }
}
```

- Manifest: `https://mcp.rtie.ai/.well-known/mcp/manifest.json`
- Tools are tenant-scoped to your API key or short-lived RTIE session token
- Tool availability requires private-preview access until T20 ships
- Platform tools (agent-work, memory) require enterprise plan or internal workspace
- Product-bundle tools (auctions, arcade, etc.) require an operator workspace

## Key modules and planned MCP tools

| Module | Planned MCP tools | Notes |
|--------|-----------|-------|
| rooms | list_rooms, create_room, get_room, activate_room, close_room, add_room_member | Foundation for all sessions |
| presence | get_presence | Who is in a room right now |
| chat | send_chat_message, list_chat_messages | Realtime messaging |
| auctions | create_auction, start_auction, close_auction, get_winning_bid | + agentic commerce tools below |
| agentic commerce | listing_browse, listing_get, auction_list_live, auction_get_high_bid, auction_place_bid*, listing_buy_now* | *Requires human confirmation |
| payments | get_payment_status, list_orders | Stripe-powered |
| webhooks | list_webhook_endpoints, create_webhook_endpoint, list_webhook_deliveries | HMAC-signed event delivery |
| actions | ingest_signal, get_action_log, get_rules, set_rules | Signal → rules → real-time actions |
| sync | sync_list_games, sync_create_game, sync_create_room, sync_get_state, sync_push_state, sync_broadcast_event | Multiplayer game state |

## @rtie/sdk install

```bash
bun add @rtie/sdk
# or
npm install @rtie/sdk
```

Basic usage:
```typescript
import { AuctionSync } from "@rtie/sdk";

const handshake = await fetch("https://api.rtie.ai/v1/runtime/connect", {
  method: "POST",
  headers: {
    "X-API-Key": process.env.RTIE_API_KEY!,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    modules: ["rooms", "presence", "chat"],
    actor: { type: "agent", id: "agent:host" },
  }),
}).then((res) => res.json());

const sync = new AuctionSync({
  host: handshake.realtime.endpoint,
  moduleAddress: handshake.realtime.moduleAddress,
  authToken: handshake.session.token,
});
```

## Module manifest (building a custom module)

```typescript
import { defineModule } from "@rtie/module-sdk";

export default defineModule({
  manifest: {
    id: "my-module",
    name: "My Module",
    version: "1.0.0",
    publisher: "Acme Corp",
    tier: "marketplace",
    description: "Does something useful.",
    routes: [
      { method: "GET", path: "/v1/my-module/things", description: "List things" },
    ],
    events: ["my-module.thing.created"],
    sdk_surface: ["listThings"],
    mcp_tools: [
      {
        name: "list_things",
        description: "List things from my module.",
        inputSchema: { type: "object", properties: {} },
        handler: { kind: "http", method: "GET", path: "/v1/my-module/things" },
        annotations: { readOnlyHint: true },
      },
    ],
    requires: ["auth"],
    conflicts: [],
    contexts: {
      supportedTypes: ["room"],
      policyActions: ["my-module.things.read"],
    },
  },
});
```

## Schema and migrations

Drizzle ORM, Postgres on Supabase (connected via HyperDrive from CF Workers).

```bash
# Apply migrations
source ~/.zshrc && bun db:migrate

# Generate new migration
bun db:generate
```

Schema files live in `packages/db/src/schema/`. Each module owns its tables.
**Do not use the Supabase MCP or Supabase CLI** to run migrations — use `bun db:migrate`.

## Realtime (SpacetimeDB via RTIE)

SpacetimeDB is the realtime engine. Access it via `manifest.spacetime` declarations
and `@rtie/sdk` subscriptions — never connect to SpacetimeDB directly.

```typescript
// Via @rtie/sdk — correct
const sub = rtie.presence.watch(roomId, (state) => console.log(state));

// Never do this — wrong
import { DbConnection } from "@clockworklabs/spacetimedb-sdk"; // ❌
```

## Action Engine (signal → rules → actions)

Submit a signal, the engine evaluates rules, triggers actions in <350ms:

```typescript
// Via MCP tool
await callTool("ingest_signal", {
  signal_type: "churn_risk",
  source: "ml_model",
  payload: { score: 0.87, userId: "usr_123" },
  confidence: 0.87,
});

// Via REST
POST /v1/actions/signals
{ "signal_type": "churn_risk", "source": "ml_model", "payload": {...} }
```

## Deploy

Modules deploy as Cloudflare Workers via wrangler. Never deploy to Railway, Vercel, or AWS.

```bash
source ~/.zshrc && bunx wrangler deploy
```

## Resources

- Docs: https://docs.rtie.ai
- AI tools: https://docs.rtie.ai/ai-tools
- Cloud: https://cloud.rtie.ai
- API: https://api.rtie.ai
- MCP private preview: https://mcp.rtie.ai
