# Kami Being Runtime - Developer & Agent Skill

Give any app, website, community, game, or robot a persistent, multimodal living **Kami Being** - with continuous sealed memory, streaming turns, async webhooks, bidirectional MCP tools, Knowledge Packs, and an embeddable In-App Co-Pilot widget.

- **API Base URL**: `https://api.kami.bot`
- **Developer Console (self-serve UI)**: `https://kami.bot/developers/console`
- **Interactive OpenAPI Reference**: `https://api.kami.bot/api/docs`

## 1. What You Can Build

1. **Community & Marketplace Chat Bots** - Drop a Being into multi-user rooms (`kind: "room"`). Ingest ambient chat at **$0** (`addressed: false`), trigger replies on mentions via Rail A (`/turn`) or Rail B (`/messages` + signed webhook), and attach your own HTTPS MCP server for live floor prices, listings, or order lookups.
2. **In-App Co-Pilot & Product Guide** - Sync your docs/Markdown/`llms.txt` into a sealed Placement Knowledge Pack, drop `<script src="https://kami.bot/embed.js">` onto your app (or pass `uiSnapshot` from React Native / Swift / Android / Quest), and let the Being guide users with spotlights, cross-page walkthroughs, flying pointer cursor, and human-confirmed actions.
3. **Real-Time Voice, 3D Avatars, NPCs & Robots** - Low-latency SSE `POST /api/placement/v1/turn` (`channel: "voice"`) with multimodal `perceptions`, `attachments`, `bodyGestures`, and `POST /api/placement/v1/episodes/end` memory consolidation.
4. **Coding-Agent & MCP Automations** - Connect Claude Code, Cursor, Codex, or Antigravity directly to `POST https://api.kami.bot/api/mcp`.

## 2. Credentials (Never Mix Them)

- **Developer Key (`kdev_...`)** - Account-level management key. Create Beings, create/edit Placements, approve hires, sync Knowledge Packs, check credits. Always sent in `Authorization: Bearer kdev_...`.
- **Placement Key (`kpl_...`)** - Runtime key scoped to **one Being in one Placement**. Sent **only** in `Authorization: Bearer kpl_...` (never in query params - `?token=kpl_...` is refused with `403`; never expose `kpl_` in browser HTML). Every thread created through a `kpl_` key is cryptographically sealed (`pl:<placementId>:...`) to that placement.

## 3. 5-Minute Self-Serve Setup (Console or REST with `kdev_`)

1. **Get your `kdev_` key (or create everything in the UI)**:
   Sign in at `https://kami.bot/developers/console` to create Beings, Placements, and API keys with zero boilerplate - or mint a `kdev_` key from a signed-in session via `POST /api/v1/developer-keys`.
2. **Create your own Being (or browse hireable public Beings)**:
   - `POST /api/v1/beings` (`{ id, name, personality, description?, appearance?, avatarUrl?, visibility?, hirePolicy?, metadata? }`)
   - `GET /api/v1/beings` (`?mineOnly=true` or `?hireableOnly=true`)
   - `GET /api/v1/beings/{id}` / `PATCH /api/v1/beings/{id}` (creator-only updates, including `avatarUrl` and opaque `metadata` up to 16 KB; never injected into LLM prompts, no secrets)
3. **Create a Placement** (returns `kpl_` immediately for your own Being or an `open` public Being; returns `status: "pending"` + `approvalUrl` for an `approval` public Being):
   - `POST /api/v1/placements` - minimal body works out of the box:
     ```json
     {
       "beingId": "my-agent",
       "holderLabel": "Acme App"
     }
     ```
     **Defaults when omitted**: `places: [{ "key": "dm", "kind": "one_to_one", "perSender": true }]`, `verbs: ["turn", "post", "read", "receive", "erase", "usage"]`, `caps: { "senderPerHour": 30, "placePerHour": 600, "dailyUsd": 10 }`.
   - **Defining `places`** (you invent each `key`, matching `/^[a-z0-9][a-z0-9_-]{0,31}$/`, max 16 places per placement):
     - `kind: "one_to_one"` - one private thread per `senderId` (`pl:<placementId>:dm:<senderId>`; `perSender: true` is auto-applied; at most one `one_to_one` place per placement).
     - `kind: "room"` - one shared multi-user thread (`pl:<placementId>:<key>`, e.g. `{ "key": "lounge", "kind": "room", "title": "The Lounge" }`; `key: "dm"` is reserved for `one_to_one`).
     - `kind: "physical_room"` - shared embodied/IoT room.
   - **Manage & evolve a Placement without revoking its key or losing sealed history**:
     - `GET /api/v1/placements` / `GET /api/v1/placements/{id}`
     - `PATCH /api/v1/placements/{id}` - update `places`, `verbs`, `caps`, `holderLabel`, `kit` (`instructions`, `topic`, `web`, `mcpServers`, `compute`, `embodiment`, `appData`), `webhook`, write-only `mcpSecret`, or write-only `computeSecret` anytime. (`kit.compute` sets default semantic quality tiers `off|fast|standard|hq`, `mediaMode: "managed"|"mcp"|"delegated"` emitting signed `media.requested` webhook events, and optional BYOK `llmEndpoint` `{ kind: "openai_compat", baseUrl, model? }` with bearer key vaulted in `computeSecret`; `kit.embodiment` binds a Body Plugin; `kit.appData` stores per-app opaque JSON up to 8 KB; none are injected into LLM prompts.)
     - `POST /api/v1/placements/{id}/approve` / `POST /api/v1/placements/{id}/reject` (creator approval for hired Beings)
     - `POST /api/v1/placements/{id}/pause` / `POST /api/v1/placements/{id}/resume` / `POST /api/v1/placements/{id}/revoke` (bilateral kill-switch)
     - `POST /api/v1/placements/{id}/rotate` / `GET /api/v1/placements/{id}/usage`
     - `GET /api/v1/placements/{id}/knowledge` / `POST /api/v1/placements/{id}/knowledge` / `DELETE /api/v1/placements/{id}/knowledge/{knowledgeId}`
4. **Credits & Auto-Recharge**:
   - `GET /api/v1/credits` / `POST /api/v1/credits/checkout` / `PATCH /api/v1/credits/auto-recharge`

## 4. Choosing Your Runtime Rail (`Authorization: Bearer kpl_...`)

| Need | Use Rail A (`/turn`) | Use Rail B (`/messages` + Webhook) | Hybrid (Rooms without Webhooks!) |
|---|---|---|---|
| **Response delivery** | Sync JSON or SSE stream (`stream: true`) | Async `202` + signed outbound webhook (or poll `GET /threads/{place}/messages`) | Ambient via `/messages (addressed: false)`, replies via `/turn` |
| **Ambient context (`addressed: false`)** | - | **Yes - $0 cost** (no LLM turn, no cap deduction) | **Yes - $0 cost**, immediately visible to next `/turn` |
| **Partner MCP tools (`kit.mcpServers`) & HTTP sources (`kit.sources`)** | **Yes** | **Yes** | **Yes** |
| **Placement Knowledge Pack (`recall_knowledge` / `list_knowledge`)** | **Yes** | **Yes** | **Yes** |
| **In-App Co-Pilot (`uiSnapshot` / `uiActions`)** | **Yes** | - | **Yes** |
| **Best for** | Live chat, voice, 3D avatars, NPCs, co-pilot widgets | High-volume community rooms, Discord/Slack/Telegram bridges | Marketplace/community rooms wanting instant SSE replies + ambient memory |

### Rail A - Real-Time Sync / Streaming Turn
- `POST /api/placement/v1/turn`
  - Body: `{ "place": "dm", "senderId": "user_42", "senderName": "Alex", "text": "Hello!", "stream": true, "channel": "text" }`
  - `channel`: `"text"` (default for `kind: "room"` and `uiSnapshot` turns - multi-user aware, never uses voice-call framing) or `"voice"` (spoken prose for TTS/avatars/NPCs, supports `bodyGestures`, `sessionPacing`, `audienceMode`, and `lastAssistantSpokenText` for barge-in reconciliation).
  - `channelContext` (optional): structured omnichannel delivery context (`{ transport, modality, participants, maxSpokenSeconds?, supportsMarkdown, supportsOutboundMedia, callerLocale? }`) orthogonal to Body Plugins - automatically adapts cadence for PSTN audio-only calls, multi-party video meetings, or async messaging.
  - `stream: false` returns JSON `{ response, action, telemetry, place, threadId, senderId }`.
  - `stream: true` returns SSE (`X-Accel-Buffering: no`) with `event: token` (`{ text, token }`), `event: done` (full turn result), `event: error`.
  - Supports up to 4 validated multimodal `attachments` (`image/*`, `audio/*`, `video/*` via HTTPS URL or base64, with optional `duration`), `perceptions`, `uiSnapshot` (with structured `state`, typed `availableActions[].paramsSchema`, and `action_result` events), progressive-disclosure `recall_knowledge`/`list_knowledge` over the placement's Knowledge Pack, per-placement `kit.sources`, and per-placement `kit.mcpServers` tools.
- `POST /api/placement/v1/episodes/end` - close an episode, evict warm RAM context, and consolidate sealed placement memory.

### Rail B - Async Chat + Signed Webhook
- `POST /api/placement/v1/messages`
  - Body: `{ "place": "lounge", "senderId": "user_42", "senderName": "Alex", "messageId": "msg_01J9", "addressed": true, "text": "What is the floor price?", "capabilities": { "imageGen": "fast", "voiceGen": true } }`
  - Always pass a stable idempotency `messageId` (retries return `202` and cost nothing). Optional `capabilities` gates per-sender async media spawns (`imageGen`: `boolean | "off" | "fast" | "standard" | "hq"`, `imageGenBlockedReason`: `"quota_reached" | "upgrade_required" | "unsupported"`, `voiceGen`, `videoGen`).
  - Every API response echoes `X-Request-Id` (and includes `requestId` on structured error envelopes) for end-to-end tracing.
  - In a `room`, explicitly pass `addressed: true | false`. `addressed: false` stores ambient context at **$0 cost** (no LLM call, no cap deduction) and invalidates any warm Rail A cache so subsequent `/turn` calls see it immediately.
- `GET /api/placement/v1/threads/{place}/messages` - read thread history (pass `?senderId=...` for `one_to_one` places).

### Runtime Ops, Knowledge Packs, Usage & GDPR
- `GET /api/placement/v1/me` - inspect placement identity, places, verbs, caps, effective kit, webhook health, and credits.
- `GET /api/placement/v1/knowledge` / `POST /api/placement/v1/knowledge` / `DELETE /api/placement/v1/knowledge/{id}` - attach or sync Markdown/text or a URL (`llms.txt`) into this placement's isolated Knowledge Pack (large docs auto-split by headings; zero cross-tenant leakage).
- `GET /api/placement/v1/usage` - usage & spend (`period=24h|7d|30d` or `from`/`to` epoch ms).
- `DELETE /api/placement/v1/users/{senderId}/data` - 1-call GDPR right-to-erasure strictly inside this placement.
- `POST /api/placement/v1/key/rotate` - rotate `kpl_` key (10-minute grace window on previous key).
- `POST /api/placement/v1/webhook/secret/rotate` - rotate webhook HMAC signing secret (two-slot grace window).
- `POST /api/placement/v1/peer-memory/memories` / `GET /api/placement/v1/peer-memory/memories` / `DELETE /api/placement/v1/peer-memory/memories` / `PUT /api/placement/v1/peer-memory/share-edges` - record, list, delete, and configure directed trust edges for provenance-tagged inter-Being epistemic memories sealed to this placement (purged automatically on `DELETE /api/placement/v1/users/{senderId}/data`).

### Omnichannel Presence (Telephony and SMS - verb `channels`)
- `GET /api/placement/v1/channels/status` - check configured telephony and SMS provider readiness.
- `POST /api/placement/v1/channels/sms/send` - send transactional SMS via vendor-agnostic SmsPort (enforces verb `channels`, caps, and cost ledger).
- `POST /api/placement/v1/channels/telephony/outbound` - place an outbound PSTN call into a realtime room (enforces verb `channels`, caps, and cost ledger).
- `POST /api/placement/v1/channels/telephony/hangup` - hang up an active PSTN call (enforces verb `channels`).
- `POST /api/placement/v1/channels/telephony/parse-webhook` - verify and normalize a vendor telephony webhook into a vendor-free event.

## 5. Outbound Webhook Payload & Signature Verification (`Kami-Signature`)

Every Rail B reply POSTs the following `message.created` JSON body to your configured `webhook.url`:

```json
{
  "type": "message.created",
  "id": "evt_9f2a...",
  "placementId": "pl_abc123",
  "place": "lounge",
  "threadId": "pl:pl_abc123:lounge",
  "senderId": "user_42",
  "inReplyTo": "msg_01J9",
  "trigger": "reply",
  "seq": 1,
  "agent": {
    "id": "my-agent",
    "name": "Nova",
    "avatarUrl": "https://media.kami.bot/..."
  },
  "text": "Floor is 34.2 ETH right now - 2 listed under 35 ETH.",
  "attachments": [],
  "createdAt": 1796250437385
}
```

Headers sent on every delivery: `Kami-Event-Id`, `Kami-Delivery-Attempt`, and `Kami-Signature: t=<unixSec>,v1=<hex>[,v1=<hex>]`.
Return HTTP `2xx` quickly (do heavy work async); delivery retries with exponential backoff, keeps per-thread `seq` order, and opens a circuit breaker after 5 consecutive failures. Always verify against the **raw request body** within a 5-minute replay window:

```ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyKamiWebhook(rawBody: string, sigHeader: string, secret: string): boolean {
  const parts = sigHeader.split(",").map((p) => p.trim());
  const tPart = parts.find((p) => p.startsWith("t="));
  const v1s = parts.filter((p) => p.startsWith("v1=")).map((p) => p.slice(3));
  if (!tPart || v1s.length === 0) return false;
  const ts = Number(tPart.slice(2));
  if (!Number.isFinite(ts) || Math.abs(Math.floor(Date.now() / 1000) - ts) > 300) return false;
  const expected = createHmac("sha256", secret).update(`${ts}.${rawBody}`).digest("hex");
  return v1s.some((sig) => sig.length === expected.length && timingSafeEqual(Buffer.from(sig), Buffer.from(expected)));
}
```

## 6. Outbound Partner Tools (Per-Placement MCP Client)

Let your Being query your live backend (marketplace floor prices, inventory, indexer, CRM) on **both Rail A (`/turn`) and Rail B (`/messages`)** by attaching an HTTPS MCP server via `PATCH /api/v1/placements/{id}`:

```json
{
  "kit": {
    "mcpServers": [
      {
        "id": "market",
        "label": "Marketplace Indexer",
        "url": "https://mcp.yoursite.com/mcp",
        "timeoutMs": 6000
      }
    ]
  },
  "mcpSecret": {
    "serverId": "market",
    "secret": "your_write_only_bearer_token"
  }
}
```

- **Scoping & Security**: Tools are namespaced `<serverId>__<toolName>`, strictly scoped to that placement, SSRF-pinned, and secret-redacted.
- **Timeouts & Failure Behavior**: Each MCP tool call enforces a hard timeout of `min(server.timeoutMs ?? 8000, placement.source.timeout_ms_max)` (default max 10s). If a tool times out or errors mid-turn, the error is returned cleanly to the Being so it answers gracefully without hanging your request.
- **Billing (`dailyUsd`)**: Kami does **not** charge a fee per MCP tool call; only the LLM input/output tokens consumed during the tool-calling loop count against your `dailyUsd` cap and prepaid credits.

## 7. Drop-In In-App Co-Pilot V2 (`https://kami.bot/embed.js`)

Embed a persistent, Shadow-DOM co-pilot drawer on any website (or send the same `uiSnapshot` JSON from React Native, Swift/iOS, Kotlin/Android, or Meta Quest/Unity) without exposing `kpl_` in client code:
- Point `data-endpoint="/api/kami-support"` at a thin server proxy forwarding `{ place: "dm", senderId, text, uiSnapshot, stream: true }` to `POST /api/placement/v1/turn`. The turn response returns validated UI guidance inside `action.uiActions` (`highlight`, `scroll_to`, `navigate`, `walkthrough`, `suggest_action`).
- `embed.js` automatically captures a privacy-safe `uiSnapshot` (never reading input values), persists across SPA navigations (`sessionStorage` + `pushState`/`popstate`), renders a Clicky-style flying pointer cursor & spotlight ring, runs multi-step cross-page `walkthrough` guides, publishes structured read-only app state via `window.KamiCopilot.setState(...)` / `setStateProvider(fn)`, and supports typed human-confirmed host actions via `window.KamiCopilot.registerAction({ verb, label, paramsSchema, execute })` (emitting `action_result` events back on subsequent turns).
- **White-label seal**: Third-party placements (`pl:*`) are strictly isolated - they never leak Kami URLs or Kami's internal API docs.

## 8. Connecting via Kami MCP Server (`POST /api/mcp`)

Kami exposes a first-party Streamable HTTP + SSE MCP server at `POST /api/mcp`:

```json
{
  "mcpServers": {
    "kami-runtime": {
      "url": "https://api.kami.bot/api/mcp",
      "headers": { "Authorization": "Bearer kpl_YOUR_PLACEMENT_KEY" }
    }
  }
}
```

- **With `kpl_` (runtime)**: `kami_run_turn` (streams SSE tokens with `Accept: text/event-stream`), `kami_send_message`, `kami_read_thread`, `kami_end_episode`, `kami_purge_user_data`, `kami_get_usage`, `kami_list_knowledge`, `kami_sync_knowledge`, `kami_delete_knowledge`, and resources `kami://placement/me` & `kami://placement/threads/{place}`.
- **With `kdev_` (management)**: `kami_create_being`, `kami_list_beings`, `kami_get_being`, `kami_update_being`, `kami_create_placement`, `kami_list_placements`, `kami_get_placement`, `kami_configure_placement`, `kami_approve_hire`, `kami_reject_hire`, `kami_pause_placement`, `kami_resume_placement`, `kami_revoke_placement`, `kami_rotate_placement_key`, `kami_get_usage`, `kami_get_credits`, `kami_list_knowledge`, `kami_sync_knowledge`, `kami_delete_knowledge`.

## 9. Error Handling (Exact JSON Shapes)

Every error returns JSON with `error` (human-readable) and `code` (machine-readable), plus `retryAfterS` (and `Retry-After` header) on `429` and actionable `hint` when applicable:

- `401` - invalid, revoked, or expired key.
- `402` - prepaid credit balance reached 0:
  ```json
  { "error": "credit_exhausted - prepaid credit balance is exhausted; top up credits to continue", "code": "credit_exhausted", "hint": "Top up prepaid credits in https://kami.bot/developers/console or via POST /api/v1/credits/checkout" }
  ```
- `403` - paused placement, missing verb (`verb_not_granted` - add verbs via `PATCH /api/v1/placements/{id}`), or out-of-scope route.
- `429` - `sender_rate`, `place_rate`, or `daily_budget` cap reached (honor `Retry-After`):
  ```json
  { "error": "daily_budget - this placement's cap is reached; retry after 14200 s", "code": "daily_budget", "retryAfterS": 14200 }
  ```
- `503` - `placement_webhook_down` (webhook failed 5+ consecutive deliveries; recover endpoint to close breaker) or `agent_unavailable`.
